Compare commits

..

1 Commits

134 changed files with 5284 additions and 17760 deletions

View File

@@ -897,16 +897,13 @@ src/scene/setting/iplRakuRakuThread.cpp:
.sbss start:0x81698C60 end:0x81698C70
src/scene/setting/AOSS.c:
.bss start:0x810BDEF8 end:0x810BE838
.bss start:0x810BDEF8 end:0x810BECA0
.text start:0x813FE27C end:0x814021BC
.data start:0x81657C48 end:0x81657DB8
.sdata2 start:0x81694C78 end:0x81694C80
.sdata start:0x81697200 end:0x81697218
.sbss start:0x81698C70 end:0x81698C90
src/scene/setting/AOSSData.c:
.bss start:0x810BE838 end:0x810BECA0
src/scene/setting/ATERM.c:
.bss start:0x810BECA0 end:0x810C0C80
.text start:0x814021BC end:0x81406CC0

View File

@@ -42,7 +42,7 @@ AppLoaderHdr = .bss:0x810ABF40; // type:object size:0x20 align:32 data:4byte
bi2 = .bss:0x810ABF60; // type:object size:0x2000 align:32 data:4byte
UpdateDiskID = .bss:0x810ADF60; // type:object size:0x20 align:32 data:4byte
TicketViewsBuf = .bss:0x810ADF80; // type:object size:0x3600 scope:local align:32
Flags0$1129 = .bss:0x810B1580; // type:object size:0x800 scope:local
Flags0 = .bss:0x810B1580; // type:object size:0x800 scope:local
Flags1 = .bss:0x810B1D80; // type:object size:0x800 scope:local
Thread = .bss:0x810B2580; // type:object size:0x318 scope:local
UpdateHeader0 = .bss:0x810B38A0; // type:object size:0x20 scope:local
@@ -93,8 +93,8 @@ sRakuMsgQueue = .bss:0x810BDED4; // type:object size:0x20
AOSS_810BDEF8 = .bss:0x810BDEF8; // type:object size:0x20 data:4byte
AOSS_810BDF18 = .bss:0x810BDF18; // type:object size:0x6A0
AOSS_810BE5B8 = .bss:0x810BE5B8; // type:object size:0x280
s_packetState = .bss:0x810BE838; // type:object size:0x68
s_crcTable = .bss:0x810BE8A0; // type:object size:0x400
AOSS_810BE838 = .bss:0x810BE838; // type:object size:0x68
AOSS_810BE8A0 = .bss:0x810BE8A0; // type:object size:0x400
gAtermIpConfig = .bss:0x810BECA0; // type:object size:0x7C4 data:4byte
gAtermIfConfig = .bss:0x810BF464; // type:object size:0x15E
ATERM_810BF5C4 = .bss:0x810BF5C4; // type:object size:0x24
@@ -4584,11 +4584,11 @@ enqueueLoadNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB308; // type:f
enqueuePageNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB364; // type:function size:0x5C
enqueueResultNotice__Q33ipl5scene15SDChannelSelectFUl = .text:0x813DB3C0; // type:function size:0x5C
enqueueChannelNotice__Q33ipl5scene15SDChannelSelectFUxUl = .text:0x813DB41C; // type:function size:0x5C
enqueueMoveNotice__Q33ipl5scene15SDChannelSelectFUx = .text:0x813DB478; // type:function size:0x5C
enqueueMoveNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB478; // type:function size:0x5C
enqueueStateNotice__Q33ipl5scene15SDChannelSelectFUxUl = .text:0x813DB4D4; // type:function size:0x5C
enqueueErrorNotice__Q33ipl5scene15SDChannelSelectFPQ33ipl12NandSDWorker11TitleIdListPQ33ipl12NandSDWorker11TitleIdList = .text:0x813DB530; // type:function size:0x5C
enqueueCommandNotice__Q33ipl5scene15SDChannelSelectFPQ33ipl12NandSDWorker11TitleIdListPQ33ipl12NandSDWorker11TitleIdListPQ33ipl12NandSDWorker11TitleIdList = .text:0x813DB58C; // type:function size:0x60
enqueueDeleteNotice__Q33ipl5scene15SDChannelSelectFUx = .text:0x813DB5EC; // type:function size:0x60
enqueueErrorNotice__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DB530; // type:function size:0x5C
enqueueCommandNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB58C; // type:function size:0x60
enqueueDeleteNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB5EC; // type:function size:0x60
clearCommandQueue__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB64C; // type:function size:0x40
clearNoticeQueue__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB68C; // type:function size:0x40
processWorkerCommands__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB6CC; // type:function size:0x518
@@ -4617,11 +4617,11 @@ updateDialogAnimation__Q33ipl5scene15SDChannelSelectFv = .text:0x813DCAC4; // ty
setDialogMessage__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DCEF0; // type:function size:0x24
isCurrentTitleUsageEnough__Q33ipl5scene15SDChannelSelectCFPCl = .text:0x813DCF14; // type:function size:0xCC
getCurrentTitleUsage__Q33ipl5scene15SDChannelSelectCFPlPl = .text:0x813DCFE0; // type:function size:0xCC
collectTitlesByUsage__Q33ipl5scene15SDChannelSelectFPlPlPUxPA21_wPUl = .text:0x813DD0AC; // type:function size:0x194
collectTitlesFromNandUsage__Q33ipl5scene15SDChannelSelectFPlPlPUxPA21_wPUl = .text:0x813DD240; // type:function size:0x198
collectTitlesByChannelOrder__Q33ipl5scene15SDChannelSelectFPlPlPUxPA21_wPUl = .text:0x813DD3D8; // type:function size:0x1F8
collectTitlesBySpecialChannels__Q33ipl5scene15SDChannelSelectFPlPlPUxPA21_wPUl = .text:0x813DD5D0; // type:function size:0x5A4
collectTitlesForMode__Q33ipl5scene15SDChannelSelectFPlPlPUxPA21_wPUli = .text:0x813DDB74; // type:function size:0x40
collectTitlesByUsage__Q33ipl5scene15SDChannelSelectFPClPClPUxPcPUl = .text:0x813DD0AC; // type:function size:0x194
collectTitlesFromNandUsage__Q33ipl5scene15SDChannelSelectFPClPClPUxPcPUl = .text:0x813DD240; // type:function size:0x198
collectTitlesByChannelOrder__Q33ipl5scene15SDChannelSelectFPClPClPUxPcPUl = .text:0x813DD3D8; // type:function size:0x1F8
collectTitlesBySpecialChannels__Q33ipl5scene15SDChannelSelectFPClPClPUxPcPUl = .text:0x813DD5D0; // type:function size:0x5A4
collectTitlesForMode__Q33ipl5scene15SDChannelSelectFPClPClPUxPcPUli = .text:0x813DDB74; // type:function size:0x40
findAdjacentChannel__Q33ipl5scene15SDChannelSelectCFiPiPi = .text:0x813DDBB4; // type:function size:0xB4
setCurrentPageAndRefresh__Q33ipl5scene15SDChannelSelectFiiPQ33ipl5scene12SDChannelObj = .text:0x813DDC68; // type:function size:0x18
handleFourPageDialog__Q33ipl5scene15SDChannelSelectFv = .text:0x813DDC80; // type:function size:0x58
@@ -4762,7 +4762,7 @@ iplSDChannelTitle_updateParentalResult = .text:0x813E69B4; // type:function size
iplSDChannelTitle_updateDialogResult = .text:0x813E6B88; // type:function size:0x144
iplSDChannelTitle_startCopyProgress = .text:0x813E6CCC; // type:function size:0x158
iplSDChannelTitle_updateCopyPrepare = .text:0x813E6E24; // type:function size:0x17C
__as__Q43ipl5scene8SDMemory10TitleRangeFRCQ43ipl5scene8SDMemory10TitleRange = .text:0x813E6FA0; // type:function size:0x14 scope:weak
iplSDChannelTitle_copyTitleRange = .text:0x813E6FA0; // type:function size:0x14
iplSDChannelTitle_updateMemoryCalc = .text:0x813E6FB4; // type:function size:0xC0
iplSDChannelTitle_updateCopyStart = .text:0x813E7074; // type:function size:0x130
iplSDChannelTitle_updateAfterClearTmp = .text:0x813E71A4; // type:function size:0xA8
@@ -4900,8 +4900,8 @@ onDialogState23__Q33ipl5scene8SDMemoryFv = .text:0x813EEDF8; // type:function si
onDialogState24__Q33ipl5scene8SDMemoryFv = .text:0x813EEE70; // type:function size:0xC0
draw__Q33ipl5scene8SDMemoryFv = .text:0x813EEF30; // type:function size:0x88
drawTransferTitles__Q33ipl5scene8SDMemoryFv = .text:0x813EEFB8; // type:function size:0x70C
__ct__Q34nw4r2ut5ColorFiiii = .text:0x813EF6C4; // type:function size:0x14
SetTextColor__Q34nw4r3lyt7TextBoxFQ34nw4r2ut5ColorQ34nw4r2ut5Color = .text:0x813EF6D8; // type:function size:0x48
writeFourFlagBytes__Q23ipl5sceneFPUcUcUcUcUc = .text:0x813EF6C4; // type:function size:0x14
setTitleRowColors__Q23ipl5sceneFPQ34nw4r3lyt7TextBoxRCQ34nw4r2ut5ColorRCQ34nw4r2ut5Color = .text:0x813EF6D8; // type:function size:0x48
GetBeginIter__Q34nw4r2ut28LinkList<Q34nw4r3lyt4Pane,4>Fv = .text:0x813EF720; // type:function size:0x8
GetEndIter__Q34nw4r2ut28LinkList<Q34nw4r3lyt4Pane,4>Fv = .text:0x813EF728; // type:function size:0x8
__ne__Q24nw4r2utFQ44nw4r2ut28LinkList<Q34nw4r3lyt4Pane,4>8IteratorQ44nw4r2ut28LinkList<Q34nw4r3lyt4Pane,4>8Iterator = .text:0x813EF730; // type:function size:0x18
@@ -17727,20 +17727,12 @@ __vt__Q39textinput4util9Animation = .data:0x8165D258; // type:object size:0x24
@STRING@GetTextColor__Q34nw4r3lyt7TextBoxCFUl = .data:0x8165D28C; // type:object size:0x41 data:string
scT_prdc_Text_00 = .data:0x8165D2D0; // type:object size:0xF data:string
scP_prdc_scrl_Left = .data:0x8165D2E0; // type:object size:0x11 data:string
csPaneToAnimation__Q29textinput12candidatebox = .data:0x8165D2F8; // type:object size:0x680 scope:local
@9934 = .data:0x8165D978; // type:object size:0x9 scope:local data:string
@9935 = .data:0x8165D984; // type:object size:0x9 scope:local data:string
@9936 = .data:0x8165D990; // type:object size:0xB scope:local data:string
@9937 = .data:0x8165D99C; // type:object size:0xB scope:local data:string
@9938 = .data:0x8165D9A8; // type:object size:0xA scope:local data:string
@9939 = .data:0x8165D9B4; // type:object size:0x11 scope:local data:string
@9940 = .data:0x8165D9C8; // type:object size:0x11 scope:local data:string
@9941 = .data:0x8165D9DC; // type:object size:0x11 scope:local data:string
@9942 = .data:0x8165D9F0; // type:object size:0x11 scope:local data:string
@9943 = .data:0x8165DA08; // type:object size:0x10 scope:local data:string
@10036 = .data:0x8165DA18; // type:object size:0xF scope:local data:string
@10037 = .data:0x8165DA28; // type:object size:0xD scope:local data:string
@10041 = .data:0x8165DA38; // type:object size:0xD scope:local data:string
scCandidatePaneData = .data:0x8165D2F8; // type:object size:0x68C
scPaneNameTable = .data:0x8165D984; // type:object size:0x84
scW_predictWindow = .data:0x8165DA08; // type:object size:0x10 data:string
scN_predictInput = .data:0x8165DA18; // type:object size:0xF data:string
scW_OnOff_Area = .data:0x8165DA28; // type:object size:0xD data:string
scN_prdc_Texts = .data:0x8165DA38; // type:object size:0xD data:string
@10530 = .data:0x8165DA48; // type:object size:0x1C scope:local
@6761 = .data:0x8165DA64; // type:object size:0xF scope:local data:string
@6762 = .data:0x8165DA74; // type:object size:0xF scope:local data:string
@@ -23681,8 +23673,8 @@ RegionValid = .sbss:0x81698A48; // type:object size:0x4 data:4byte
NandPending = .sbss:0x81698A4C; // type:object size:0x4 scope:local data:4byte
CancelNand = .sbss:0x81698A50; // type:object size:0x4 scope:local data:4byte
LowReadResult = .sbss:0x81698A54; // type:object size:0x4 scope:local data:4byte
CacheCommandComplete$1963 = .sbss:0x81698A58; // type:object size:0x4 scope:local data:4byte
AudioBufferUnconfigured$2065 = .sbss:0x81698A5C; // type:object size:0x4 scope:local data:4byte
CacheCommandComplete = .sbss:0x81698A58; // type:object size:0x4 scope:local data:4byte
AudioBufferUnconfigured = .sbss:0x81698A5C; // type:object size:0x4 scope:local data:4byte
ResetTime = .sbss:0x81698A60; // type:object size:0x8 scope:local data:4byte
SpinupDeadline = .sbss:0x81698A68; // type:object size:0x8 scope:local data:4byte
CoverPollTime = .sbss:0x81698A70; // type:object size:0x8 data:4byte
@@ -23690,13 +23682,15 @@ DriveWasReset = .sbss:0x81698A78; // type:object size:0x4 data:4byte
TitleTicketView = .sbss:0x81698A7C; // type:object size:0x4 scope:local data:4byte
CurrentTmd = .sbss:0x81698A80; // type:object size:0x4 scope:local data:4byte
TitleCode = .sbss:0x81698A84; // type:object size:0x4 data:4byte
RequiredIos = .sbss:0x81698A88; // type:object size:0x8 data:4byte
RequiredIosHigh = .sbss:0x81698A88; // type:object size:0x4 data:4byte
RequiredIosLow = .sbss:0x81698A8C; // type:object size:0x4 data:4byte
GamePartition = .sbss:0x81698A90; // type:object size:0x4 data:4byte
UpdatePartition = .sbss:0x81698A94; // type:object size:0x4 data:4byte
PartitionCursor = .sbss:0x81698A98; // type:object size:0x4 data:4byte
DataToc = .sbss:0x81698A9C; // type:object size:0x4 data:4byte
GameToc = .sbss:0x81698AA0; // type:object size:0x8 data:4byte
CoverOpenTime = .sbss:0x81698AA8; // type:object size:0x8 data:4byte
CoverOpenTimeHigh = .sbss:0x81698AA8; // type:object size:0x4 data:4byte
CoverOpenTimeLow = .sbss:0x81698AAC; // type:object size:0x4 data:4byte
NandTransferred = .sbss:0x81698AB0; // type:object size:0x4 data:4byte
NandLength = .sbss:0x81698AB4; // type:object size:0x4 data:4byte
NandBuffer = .sbss:0x81698AB8; // type:object size:0x4 data:4byte

View File

@@ -658,7 +658,7 @@ config.libs = [
Object(Matching, "system/iplChannelRsoThread.cpp"),
Object(Matching, "system/RsoSystem.cpp"),
Object(Matching, "system/iplCdbBackup.cpp"),
Object(Matching, "system/odh.cpp"),
Object(NonMatching, "system/odh.cpp"),
Object(Matching, "system/iplSDVFWorker.cpp"),
Object(Matching, "system/iplNandWrapper.cpp"),
Object(Matching, "system/main.cpp"),
@@ -678,7 +678,7 @@ config.libs = [
Object(Matching, "utility/iplThread.cpp"),
Object(Matching, "utility/iplMessageBase.cpp"),
Object(Matching, "utility/iplJpegDecoder.cpp"),
Object(Matching, "utility/iplESMisc.cpp"),
Object(NonMatching, "utility/iplESMisc.cpp"),
Object(Matching, "utility/iplCSFlags.cpp"),
]
),
@@ -700,7 +700,7 @@ config.libs = [
Object(Matching, "iplwww/www_print.cpp"),
Object(Matching, "iplwww/www_window.cpp"),
Object(Matching, "iplwww/www_trasition.cpp"),
Object(Matching, "iplwww/www_wiisetting.cpp"),
Object(Equivalent, "iplwww/www_wiisetting.cpp"),
Object(Matching, "iplwww/www_arcreader.cpp"),
]
),
@@ -718,8 +718,8 @@ config.libs = [
Object(Matching, "BS2/BS2Entry.c"),
Object(Matching, "BS2/BS2.c"),
Object(Matching, "BS2/BS2Init.c"),
Object(Matching, "BS2/BS2Mach.c"),
Object(Matching, "BS2/BS2Update.c"),
Object(NonMatching, "BS2/BS2Mach.c"),
Object(NonMatching, "BS2/BS2Update.c"),
Object(Matching, "BS2/BS2ParentalControl.c"),
Object(Matching, "BS2/BS2BringUp.c"),
Object(Matching, "BS2/BS2Reset.c"),
@@ -729,7 +729,7 @@ config.libs = [
IPLSection("address", [
Object(Matching, "scene/address/iplAddress.cpp"),
Object(Matching, "scene/address/iplAddressAddSel.cpp"),
Object(Matching, "scene/address/iplAddressEdit.cpp"),
Object(NonMatching, "scene/address/iplAddressEdit.cpp"),
]
),
IPLSection("backMenu", [
@@ -814,7 +814,7 @@ config.libs = [
IPLSection("memoryCard", [
Object(Matching, "scene/memoryCard/iplMemoryCard.cpp"),
Object(Matching, "scene/memoryCard/iplMemoryCardBase.cpp"),
Object(Matching, "scene/memoryCard/iplMemoryCardManager.cpp"),
Object(NonMatching, "scene/memoryCard/iplMemoryCardManager.cpp"),
Object(Matching, "scene/memoryCard/iplGCSaveData.cpp"),
Object(Matching, "scene/memoryCard/iplGCWindow.cpp"),
]
@@ -849,12 +849,12 @@ config.libs = [
]
),
IPLSection("sdChannelSelect", [
Object(Matching, "scene/sdChannelSelect/iplSDChannelSelect.cpp"),
Object(NonMatching, "scene/sdChannelSelect/iplSDChannelSelect.cpp"),
Object(Matching, "scene/sdChannelSelect/iplSDChannelObj.cpp"),
]
),
IPLSection("sdChannelTitle", [
Object(Matching, "scene/sdChannelTitle/iplSDChannelTitle.cpp"),
Object(NonMatching, "scene/sdChannelTitle/iplSDChannelTitle.cpp"),
]
),
IPLSection("sdButton", [
@@ -864,11 +864,11 @@ config.libs = [
]
),
IPLSection("sdChannelMemory", [
Object(Matching, "scene/sdChannelMemory/iplSDMemory.cpp"),
Object(NonMatching, "scene/sdChannelMemory/iplSDMemory.cpp"),
]
),
IPLSection("setting", [
Object(Matching, "scene/setting/iplSetting.cpp"),
Object(NonMatching, "scene/setting/iplSetting.cpp"),
Object(Matching, "scene/setting/iplSensitivity.cpp"),
Object(Matching, "scene/setting/iplNCDSetting.cpp"),
Object(Matching, "scene/setting/iplParental.cpp"),
@@ -879,8 +879,7 @@ config.libs = [
Object(NonMatching, "scene/setting/AOSSLink.c"),
Object(Matching, "scene/setting/iplRakuRakuThread.cpp"),
Object(NonMatching, "scene/setting/AOSS.c", extra_cflags=["-O4,p", "-inline off"]),
Object(Matching, "scene/setting/AOSSData.c"),
Object(NonMatching, "scene/setting/ATERM.c", mw_version="GC/3.0a5", extra_cflags=["-O4,p", "-inline on"]),
Object(NonMatching, "scene/setting/ATERM.c", extra_cflags=["-O4,p", "-inline on"]),
]
),
IPLSection("settingSelect", [
@@ -912,13 +911,13 @@ config.libs = [
Object(Matching, "keyboard/tiPcKeyboard.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiCellPhone.cpp", extra_cflags=["-O4,p"]),
Object(NonMatching, "keyboard/tiInputForm.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiCandidateBox.cpp", extra_cflags=["-O4,p"]),
Object(NonMatching, "keyboard/tiCandidateBox.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiToolBar.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiPredictLang.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiSignWindow.cpp", extra_cflags=["-O4,p"]),
Object(NonMatching, "keyboard/tiString.cpp", extra_cflags=["-O4,p"]),
Object(NonMatching, "keyboard/tiAtokString.cpp", extra_cflags=["-O4,p"]), # for 4.3J
Object(Matching, "keyboard/tiZiString.cpp", extra_cflags=["-O4,p"]), # for 4.3U and 4.3E
Object(NonMatching, "keyboard/tiZiString.cpp", extra_cflags=["-O4,p"]), # for 4.3U and 4.3E
Object(Matching, "keyboard/tiTextDrawer.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiNw4rManager.cpp", extra_cflags=["-O4,p"]),
Object(Matching, "keyboard/tiKeyboard.cpp", extra_cflags=["-O4,p"]),
@@ -1049,7 +1048,7 @@ config.libs = [
Object(Matching, "net/hmac.c"),
Object(Matching, "net/neterrorcode.c"),
Object(Matching, "net/NETVersion.c"),
Object(Matching, "net/aes.c"),
Object(NonMatching, "net/aes.c"),
Object(Matching, "net/wireless_macaddr.c"),
]
),
@@ -1058,11 +1057,11 @@ config.libs = [
Object(Matching, "nhttp/NHTTP_control.c"),
Object(Matching, "nhttp/NHTTP_list.c"),
Object(Matching, "nhttp/NHTTP_os_RVL.c"),
Object(Matching, "nhttp/NHTTP_recvbuf.c", mw_version="GC/3.0a5"),
Object(NonMatching, "nhttp/NHTTP_recvbuf.c"),
Object(Matching, "nhttp/NHTTP_request.c"),
Object(Matching, "nhttp/NHTTP_response.c"),
Object(Matching, "nhttp/NHTTP_socket_RVL.c"),
Object(Matching, "nhttp/NHTTP_stdlib_RVL.c", mw_version="GC/3.0a5"),
Object(NonMatching, "nhttp/NHTTP_stdlib_RVL.c"),
Object(Matching, "nhttp/NHTTP_thread.c"),
Object(Matching, "nhttp/d_nhttp_private.c"),
Object(Matching, "nhttp/d_nhttp.c"),
@@ -1215,9 +1214,9 @@ config.libs = [
Object(Matching, "reschange/iqdec_resolution_change_a3.c"),
Object(Matching, "reschange/idct_resolution_change_var.c"),
Object(Matching, "texturecvtr/Texture_MCUtoY8U8V8.c"),
Object(Matching, "texturecvtr/Texture_MCUtoRGB565.c"),
Object(Matching, "texturecvtr/Texture_MCUtoRGBA8.c"),
Object(NonMatching, "texturecvtr/Texture_MCUtoY8U8V8.c"),
Object(NonMatching, "texturecvtr/Texture_MCUtoRGB565.c"),
Object(NonMatching, "texturecvtr/Texture_MCUtoRGBA8.c"),
Object(Matching, "b65/iqdec_b65_frv32.c"),
]
@@ -1324,7 +1323,7 @@ config.libs = [
Object(Matching, "lyt/lyt_layout.cpp"),
Object(Matching, "lyt/lyt_picture.cpp"),
Object(Matching, "lyt/lyt_textBox.cpp"),
Object(Matching, "lyt/lyt_window.cpp"),
Object(Equivalent, "lyt/lyt_window.cpp"),
Object(Matching, "lyt/lyt_bounding.cpp"),
Object(Matching, "lyt/lyt_material.cpp"),
Object(Matching, "lyt/lyt_drawinfo.cpp"),
@@ -1855,7 +1854,7 @@ config.libs = [
Object(Matching, "fa/kernel/pfk_api.c"),
Object(Matching, "fa/driver/nand_drv.c"),
Object(Matching, "fa/driver/sd_drv.c"),
Object(NonMatching, "fa/driver/sd_drv.c"),
Object(Matching, "fa/driver/pfd_cmn.c"),
Object(Matching, "fa/driver/msc_drv.c"),
@@ -1886,7 +1885,7 @@ config.libs = [
]
),
RVLSDKLib("kbd", [
Object(Matching, "kbd/kbd_lib.c"),
Object(NonMatching, "kbd/kbd_lib.c"),
Object(NonMatching, "kbd/kbd_lib_map_jp.c"),
Object(Matching, "kbd/kbd_lib_map_us.c"),
Object(NonMatching, "kbd/kbd_lib_map_eu.c"),

View File

@@ -1,7 +1,7 @@
# Assembly inventory
4.3U, 2026-10-08. 166 functions contain 168 assembly
bodies/blocks: 162 ORIGINAL functions and 4 PLACEHOLDER functions.
4.3U, 2026-10-05. 173 functions contain 175 assembly
bodies/blocks: 162 ORIGINAL functions and 10 PLACEHOLDER functions.
Run `python3 tools/check_asm_inventory.py`. Completion requires exit 0, complete
coverage and zero placeholders. The checker also rejects stale/duplicate rows,
@@ -88,7 +88,9 @@ found. Historical logs absent from this branch have commit IDs and excerpts in
| `libs/RVL_SDK/src/base/PPCArch.c` | `PPCSetFpIEEEMode` | ORIGINAL | Special-register or synchronization operation: `mtfsb0 FPSCR_NI_BIT`. |
| `libs/RVL_SDK/src/base/PPCArch.c` | `PPCSetFpNonIEEEMode` | ORIGINAL | Special-register or synchronization operation: `mtfsb1 FPSCR_NI_BIT`. |
| `libs/RVL_SDK/src/base/PPCArch.c` | `PPCMthid4` | ORIGINAL | Both branches write HID4 with mtspr; the fallback preserves the Broadway H4A bit. |
| `libs/RVL_SDK/src/cntcache/cntcache.c` | `CNTCACHEClear` | PLACEHOLDER | NAND/token logic; best C 47/151 differing, 149/151 instructions; pool solved with stripped writer literals, two post-delete compares missing, [rx30][rx30], [opus-cntc](../tools/decomp-assist/opus-cntc.attempts.md). |
| `libs/RVL_SDK/src/cntcache/cntcache.c` | `CNTCACHEClear` | PLACEHOLDER | NAND/token logic; best C 93.364235%, 147/151 instructions, four missing pool literals, [rx30][rx30]. |
| `libs/RVL_SDK/src/cntcache/cntcache.c` | `_CNTCACHEIsTitleRemovable` | PLACEHOLDER | NAND/TMD checks; best diagnostic C 93.70731%, 82/82 instructions, status-register interference, [rx18][rx18]. |
| `libs/RVL_SDK/src/cntcache/cntcache.c` | `_CNTCACHEDeleteContent` | PLACEHOLDER | Token parsing and ES deletion; best C 95.793106%, 143/145 instructions, missing reload/copy, [rx18][rx18]. |
| `libs/RVL_SDK/src/db/db.c` | `__DBExceptionDestination` | ORIGINAL | mfmsr/mtmsr enable address translation before the exception-handler tail branch. |
| `libs/RVL_SDK/src/gx/GXLight.c` | `PushLight` | ORIGINAL | psq_l/psq_st transfers paired-single values for the GX command stream. |
| `libs/RVL_SDK/src/gx/GXTransform.c` | `WriteProjPS` | ORIGINAL | psq_l/psq_st transfers paired-single values for the GX command stream. |
@@ -160,6 +162,7 @@ found. Historical logs absent from this branch have commit IDs and excerpts in
| `libs/RVL_SDK/src/os/__ppc_eabi_init.cpp` | `__init_hardware` | ORIGINAL | Before normal C startup, mfmsr/mtmsr enables the FPU and r31 holds LR across init calls. |
| `libs/RVL_SDK/src/os/__ppc_eabi_init.cpp` | `__flush_cache` | ORIGINAL | dcbst/sync/icbi/isync make freshly initialized code visible to instruction fetch. |
| `libs/RVL_SDK/src/os/__ppc_eabi_init.cpp` | `__init_user` | ORIGINAL | fralloc/bl __init_cpp/frfree/blr matches the public [SDK startup assembly][sdk-init]. |
| `libs/RevoEX/src/nwc24/NWC24UserId.c` | `getUnScrambleId` | PLACEHOLDER | Integer byte permutation; best C 76.27329%, 161/161 instructions, 97 register/scheduling differences, [rx30][rx30]. |
| `libs/Runtime/src/Gecko_setjmp.c` | `__setjmp` | ORIGINAL | Saves or restores caller GPRs/FPRs, LR, CR, and stack state across nonlocal returns. |
| `libs/Runtime/src/Gecko_setjmp.c` | `longjmp` | ORIGINAL | Saves or restores caller GPRs/FPRs, LR, CR, and stack state across nonlocal returns. |
| `libs/Runtime/src/__init_cpp_exceptions.cpp` | `__exception_info_constants` | ORIGINAL | Reads the caller ABI TOC register r2 directly for exception registration. |
@@ -186,7 +189,10 @@ found. Historical logs absent from this branch have commit IDs and excerpts in
| `src/BS2/BS2Start.c` | `__start` | ORIGINAL | Runs before the C stack and ABI registers exist; constructs the initial stack. |
| `src/BS2/BS2Start.c` | `__init_registers` | ORIGINAL | Initializes GPRs, r1, r2, and r13 for the C runtime. |
| `src/scene/nakamuraTest/gamespy/common/gsPlatformUtil.c` | `GetTicks` | ORIGINAL | Inactive PS2 branch reads the CP0 Count register with mfc0 $9. |
| `src/system/iplSaveDataManager.cpp` | `Manager::hasChannel` | PLACEHOLDER | Title-slot search; best C 71/71 instructions, 12 mask/base register differences, [sol-ph1](../tools/decomp-assist/sol-ph1.attempts.md). |
| `src/system/iplChannelManager.cpp` | `getTitleName__Q33ipl7channel7ManagerCFiii` | PLACEHOLDER | Channel-name copying; best C 99.57746%, 71/71 instructions, four address-order differences, [rx17][rx17]. |
| `src/system/iplSaveDataManager.cpp` | `Manager::hasChannel` | PLACEHOLDER | Title-slot search; best C 98.87324%, 71/71 instructions, 14 mask/base register differences, [rx30][rx30]. |
| `src/system/iplSaveDataManager.cpp` | `Manager::makePriorTitleIDList` | PLACEHOLDER | Title filtering; best recorded C 80.22556%, 124/133 instructions, address CSE, [da1](../tools/decomp-assist/da1.attempts.md); newer [rx17][rx17] 79.827065%. |
| `src/system/iplSaveDataManager.cpp` | `Manager::doUpdateChanInfos` | PLACEHOLDER | Channel metadata updates; best C 93.35821%, 68/67 instructions, extra memset base, [rx17][rx17]. |
| `src/system/iplSystem.cpp` | `System::warning_run` | PLACEHOLDER | Scene/render calls; best C 98.66477%, 176/176 instructions, 47 saved-register differences, [rx17][rx17]. |
| `src/system/rvl_dec.c` | `Rvl_decode` | ORIGINAL | Direct beq decoder entries preserve r3/r4 and LR; lis/ori builds the format signatures. |
| `src/system/rvl_dec.c` | `Rvl_decode_szs` | ORIGINAL | Original SZS decoder convention: nofralloc, r0 retains output length, fixed r3..r10/CTR byte-copy pipeline. |
@@ -194,6 +200,7 @@ found. Historical logs absent from this branch have commit IDs and excerpts in
| `src/system/rvl_dec.c` | `Rvl_decode_asr` | ORIGINAL | nofralloc hand-built 0x40 frame saves r21..31 with stmw; work address uses lis @h/ori @l. |
[rx17]: ../tools/decomp-assist/rx36.attempts.md#rx17
[rx18]: ../tools/decomp-assist/rx36.attempts.md#rx18
[rx24]: ../tools/decomp-assist/rx36.attempts.md#rx24
[rx30]: ../tools/decomp-assist/rx36.attempts.md#rx30
[rx36-osinit]: ../tools/decomp-assist/rx36.attempts.md#osinit

View File

@@ -7,7 +7,7 @@
extern "C" {
#endif
typedef CHANSVmObjHdr* (*VmConvertFunc)(CHANSVm*, CHANSVmObjType, const CHANSVmObjHdr*);
typedef CHANSVmObjHdr* (*VmConvertFunc)(CHANSVm*, CHANSVmObjType, CHANSVmObjHdr*);
typedef struct VmConvertEntry {
VmConvertFunc convFunc[6]; // 0x00

View File

@@ -12,7 +12,6 @@ extern void __sync();
extern unsigned int __cntlzw(unsigned int value);
extern void __memclr(void* buffer, int len);
extern unsigned int __rlwimi(unsigned int a, unsigned int b, unsigned int c, unsigned int d, unsigned int e);
extern unsigned int __rlwinm(unsigned int value, unsigned int shift, unsigned int maskBegin, unsigned int maskEnd);
extern void* __alloca(unsigned int blockSize);
extern int __abs(int n);

View File

@@ -77,7 +77,7 @@ namespace textinput {
class Base : public CommandSender {
public:
#if defined(TIMANAGER_IMPLEMENTATION) || defined(TI_CANDIDATEBOX_SAMPLE_CLASS)
#ifdef TIMANAGER_IMPLEMENTATION
Base(Manager* manager) : mpCandidates(NULL), mpAllocator(NULL), mbOn(false), mbInvalid(true), meLanguage(USA), mpManager(manager) {}
#endif
virtual ~Base();
@@ -114,7 +114,7 @@ namespace textinput {
class EventHandler : public nw4rmanager::TiEventHandler {
public:
#if defined(TIMANAGER_IMPLEMENTATION) || defined(TI_CANDIDATEBOX_SAMPLE_CLASS)
#ifdef TIMANAGER_IMPLEMENTATION
EventHandler(LayoutByNW4R* layout) : mpLayoutByNW4R(layout) {}
#endif
virtual void onTiEvent(gui::PaneComponent* paneComponent, u32 event, Input* input) override; // 0x18
@@ -302,7 +302,7 @@ namespace textinput {
// TODO
class LayoutByNW4R : public Base, public nw4rmanager::Layout, public UIObj::Listener {
public:
#if defined(TIMANAGER_IMPLEMENTATION) || defined(TI_CANDIDATEBOX_SAMPLE_CLASS)
#ifdef TIMANAGER_IMPLEMENTATION
LayoutByNW4R(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* accessor, EventObserver* observer, const char* layoutName)
: Base(manager), nw4rmanager::Layout(accessor, layoutName, observer), mEventHandler(this), mpTiString(NULL),
mTextArea(0, this, this), mLeftScroll(1, this, this), mRightScroll(2, this, this), mOnOffButton(3, this, this),
@@ -371,15 +371,6 @@ namespace textinput {
bool mbActive;
};
#ifdef TI_CANDIDATEBOX_SAMPLE_CLASS
class Sample : public LayoutByNW4R {
public:
Sample(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* accessor, EventObserver* observer, const char* layoutName)
: LayoutByNW4R(manager, accessor, observer, layoutName) {}
virtual ~Sample() {}
};
#endif
class CandidateTextAnmPane : public nw4rmanager::AnmPane {
public:
CandidateTextAnmPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer)

View File

@@ -129,7 +129,7 @@ namespace textinput {
#ifdef TIHWKEYBOARD_IMPLEMENTATION
EventObserver* getEventObserverForHardware() const { return mpEventObserver; }
#endif
#if defined(TISIGNWINDOW_IMPLEMENTATION) || defined(IPL_ADDRESS_EDIT_CPP)
#ifdef TISIGNWINDOW_IMPLEMENTATION
virtual InputForm* getInputForm();
#else
virtual InputForm* getInputForm() { return mpInputForm; }

View File

@@ -105,7 +105,7 @@ namespace ipl {
#ifdef IPL_CHANNEL_TITLE_NOVTABLE
template <typename T>
class HermiteIntp : public utility::FrameController {
class __declspec(novtable) HermiteIntp : public utility::FrameController {
public:
HermiteIntp() {}
virtual ~HermiteIntp();
@@ -296,6 +296,45 @@ namespace ipl {
};
#endif
#ifdef IPL_SD_CHANNEL_SELECT_CPP
} // namespace math
} // namespace ipl
#include "math/iplMathTypes.h"
namespace ipl {
namespace math {
template <>
class HermiteIntp<VEC3> : public utility::FrameController {
public:
HermiteIntp() {}
virtual ~HermiteIntp();
void init(const VEC3& start, const VEC3& end, f32 maxFrame, f32 startTangent, f32 endTangent, int playback = ANIM_TYPE_FORWARD, f32 speed = 1.0f);
VEC3 get() const {
f32 frame = mFrame;
f32 inverseDuration = 1.0f / mMaxFrame;
VEC3 result =
(mStart * (1.0f + (inverseDuration * (inverseDuration *
(inverseDuration * (frame * (2.0f * frame * frame)))) -
inverseDuration * (inverseDuration * (3.0f * frame * frame))))) -
(mEnd * (inverseDuration * (inverseDuration *
(inverseDuration * (frame * (2.0f * frame * frame)))) -
inverseDuration * (inverseDuration * (3.0f * frame * frame))));
f32 frameSquared = frame * frame;
f32 cubic = inverseDuration * (inverseDuration * (frame * frameSquared));
f32 tangent = mStartTangent * (frame + (cubic -
inverseDuration * (2.0f * frame * frame))) +
mEndTangent * (cubic - inverseDuration * frameSquared);
result.x += tangent;
result.y += tangent;
result.z += tangent;
return result;
}
protected:
VEC3 mStart;
VEC3 mEnd;
f32 mStartTangent;
f32 mEndTangent;
};
#endif
} // namespace math
} // namespace ipl

View File

@@ -50,7 +50,6 @@ namespace ipl {
void add_friendinfo();
void delete_friendinfo();
void set_textbox(nw4r::lyt::Pane*, const wchar_t*);
void set_textbox(nw4r::lyt::Pane* pane, u32 msgId);
void setDefaultTitleText(const wchar_t*, bool);
static void wiiid_utf16(u64, wchar_t*);
static void nigaoe_create_callback_add(ipl::nigaoe::Object*, void*);

View File

@@ -35,7 +35,11 @@ namespace ipl {
MemoryBase* mpBase; // 0x0C
};
#ifdef IPL_CHANNEL_TITLE_NOVTABLE
class __declspec(novtable) MemoryBase {
#else
class MemoryBase {
#endif
public:
class Anm {
public:

View File

@@ -166,11 +166,11 @@ namespace ipl {
void update_file_array(u8 slot);
void update_change_cardstate(u8 slot);
const GXTexObj* create_icon(u8 slot, s16 index);
const GXTexObj* create_icon(u8 slot, s16 index, long start);
const GXTexObj* _create_icon(u8 slot, s16 fileNo, long start);
GXTexObj* create_icon(u8 slot, s16 index);
GXTexObj* create_icon(u8 slot, s16 index, long start);
GXTexObj* _create_icon(u8 slot, s16 fileNo, long start);
const wchar_t* getComment(u8 slot, s16 index, int which);
const GXTexObj* create_banner(u8 slot, s16 index);
GXTexObj* create_banner(u8 slot, s16 index);
#ifdef IPL_GC_WINDOW_CPP
u32 getBlocks(u8 slot, s16 index);
#else
@@ -187,7 +187,7 @@ namespace ipl {
}
private:
const GXTexObj* initBannerTexture(u8 slot, s32 file, void* data) {
GXTexObj* initBannerTexture(u8 slot, s32 file, void* data) {
GXInitTexObj(&mFileCell[slot][file].banner, data, CARD_BANNER_WIDTH, CARD_BANNER_HEIGHT,
GX_TF_RGB5A3, GX_CLAMP, GX_CLAMP, GX_FALSE);
return &mFileCell[slot][file].banner;
@@ -203,22 +203,6 @@ namespace ipl {
return &mFileCell[slot][file].bannerTlut;
}
const GXTexObj* initIconTexture(u8 slot, s32 file, void* data) {
GXInitTexObj(&mFileCell[slot][file].icon, data, CARD_ICON_WIDTH, CARD_ICON_HEIGHT,
GX_TF_RGB5A3, GX_CLAMP, GX_CLAMP, GX_FALSE);
return &mFileCell[slot][file].icon;
}
void initIconTextureCI(u8 slot, s32 file, void* data) {
GXInitTexObjCI(&mFileCell[slot][file].icon, data, CARD_ICON_WIDTH, CARD_ICON_HEIGHT,
GX_TF_C8, GX_CLAMP, GX_CLAMP, GX_FALSE, GX_TLUT0);
}
GXTlutObj* initIconPalette(u8 slot, s32 file, void* data) {
GXInitTlutObj(&mFileCell[slot][file].iconTlut, data, GX_TL_RGB5A3, 0x100);
return &mFileCell[slot][file].iconTlut;
}
u32 reserved; // 0x00004
MCFile mFile[2][CARD_MAX_FILE]; // 0x00008
MCFileCell mFileCell[2][CARD_MAX_FILE]; // 0x00FE8

View File

@@ -142,9 +142,14 @@ namespace ipl {
u32 mTransferStatus;
u64 mTransferStartTime;
s32 mTransferFrame;
NandSDWorker::TitleIdList mTitleList;
NandSDWorker::TitleIdList mNandTitleList;
NandSDWorker::TitleIdList mSDTitleList;
struct TitleListState {
ESTitleId* mpTitles;
u32 mCount;
ESTitleId* mpSecondaryTitles;
u32 mSecondaryCount;
ESTitleId* mpNames;
u32 mNameCount;
} mTitleListState;
scroller mScroller;
s32 mButtonState;
u8 mControllerFlags[4];

View File

@@ -177,8 +177,8 @@ namespace ipl {
const controller::Interface* controller);
BOOL onEventDerived(const char* paneName, u32 event,
controller::Interface* controller);
bool collectTitlesByUsage(s32* firstUsage, s32* secondUsage,
ESTitleId* titleIds, wchar_t (*titleNames)[21],
bool collectTitlesByUsage(const s32* firstUsage, const s32* secondUsage,
ESTitleId* titleIds, char* titleNames,
u32* titleCount);
static const char* mscChannelPaneNames[PAGE_COUNT][MAX_CHANNEL_INDEX];
@@ -197,8 +197,6 @@ namespace ipl {
friend class SDChannelSelectEventHandler;
friend class SDChannelSelectButtonEventHandler;
#endif
friend class SDMemory;
void enqueueStartNotice();
bool enqueueFinishNotice();
bool enqueueNotice(u32 highTitleId, u32 lowTitleId, u32 result);
@@ -206,14 +204,11 @@ namespace ipl {
bool enqueuePageNotice();
bool enqueueResultNotice(u32 result);
bool enqueueChannelNotice(u64 titleId, u32 value);
bool enqueueMoveNotice(ESTitleId titleId);
bool enqueueMoveNotice(u32 controller, u32 page, u32 index);
bool enqueueStateNotice(u64 titleId, u32 state);
bool enqueueErrorNotice(NandSDWorker::TitleIdList* newTitles,
NandSDWorker::TitleIdList* replacingTitles);
bool enqueueCommandNotice(NandSDWorker::TitleIdList* titles,
NandSDWorker::TitleIdList* foundTitles,
NandSDWorker::TitleIdList* badTitles);
bool enqueueDeleteNotice(ESTitleId titleId);
bool enqueueErrorNotice(u32 page, u32 index);
bool enqueueCommandNotice(u32 page, u32 index, u32 command);
bool enqueueDeleteNotice(u32 controller, u32 page, u32 index);
void clearCommandQueue();
void clearNoticeQueue();
void calcChannelObjects();
@@ -226,7 +221,7 @@ namespace ipl {
int getCenterChannelIndex(const char* paneName) const;
nw4r::lyt::Pane* getCenterChannelPane(int index) const;
nw4r::lyt::Pane* getChannelPane(int index) const;
static nw4r::math::VEC3 getChannelPanePosition(SDChannelSelect* scene, int index);
static math::VEC3 getChannelPanePosition(SDChannelSelect* scene, int index);
void calcPageAnimations();
void processNormalInput();
void updateArrowVisibility();
@@ -237,17 +232,17 @@ namespace ipl {
void setChannelScissor(const SDChannelObj* channel) const;
bool isCurrentTitleUsageEnough(const s32* usage) const;
void getCurrentTitleUsage(s32* bytes, s32* blocks) const;
bool collectTitlesByChannelOrder(s32* firstUsage, s32* secondUsage,
ESTitleId* titleIds, wchar_t (*titleNames)[21],
bool collectTitlesByChannelOrder(const s32* firstUsage, const s32* secondUsage,
ESTitleId* titleIds, char* titleNames,
u32* titleCount);
bool collectTitlesFromNandUsage(s32* firstUsage, s32* secondUsage,
ESTitleId* titleIds, wchar_t (*titleNames)[21],
bool collectTitlesFromNandUsage(const s32* firstUsage, const s32* secondUsage,
ESTitleId* titleIds, char* titleNames,
u32* titleCount);
bool collectTitlesBySpecialChannels(s32* firstUsage, s32* secondUsage,
ESTitleId* titleIds, wchar_t (*titleNames)[21],
bool collectTitlesBySpecialChannels(const s32* firstUsage, const s32* secondUsage,
ESTitleId* titleIds, char* titleNames,
u32* titleCount);
bool collectTitlesForMode(s32* firstUsage, s32* secondUsage,
ESTitleId* titleIds, wchar_t (*titleNames)[21],
bool collectTitlesForMode(const s32* firstUsage, const s32* secondUsage,
ESTitleId* titleIds, char* titleNames,
u32* titleCount, int searchMode);
bool findAdjacentChannel(int direction, int* page, int* index) const;
void setStateAndPlaySelectSound(int state) NO_INLINE;

View File

@@ -20,19 +20,6 @@ typedef struct AOSSInitInput {
u8 result[0x154];
} AOSSInitInput;
typedef struct AOSSKeyMaterial {
u8 nonce[2];
u8 address[8];
} AOSSKeyMaterial;
typedef struct AOSSPacketState {
AOSSKeyMaterial key;
u8 payload[0x5e];
} AOSSPacketState;
extern AOSSPacketState s_packetState;
extern u32 s_crcTable[0x100];
int AOSSi_Init(AOSSInitInput* input);
int AOSS_Init_old(AOSSInitInput* input);
void* AOSSi_Alloc(u32 size);

View File

@@ -18,15 +18,6 @@ namespace ipl {
f32 margin16x9 = 120.0f, f32 margin4x3 = 30.0f);
~TextBalloon();
static f32 getDefaultMargin16x9() {
f32 margin = 120.0f;
return margin;
}
static f32 getDefaultMargin4x3() {
f32 margin = 30.0f;
return margin;
}
void calc();
void draw();

View File

@@ -277,9 +277,6 @@ namespace ipl {
/* SEntry */
bool hasLoadedBnr(int page, int index) const { return mChannels[page][index].loadedBnr; }
int getSceneID(int page, int index) const { return mChannels[page][index].loadedBnr ? mChannels[page][index].info.sceneID : 0; }
ESTitleId getEntryTitleID(int page, int index) const {
return mChannels[page][index].loadedBnr ? ES_TITLE_ID(mChannels[page][index].info.titleType, mChannels[page][index].info.titleCode) : 0;
}
/* SMetaBlockHeader */
u32 getIconRSOIdx(int page, int index) const {

View File

@@ -15,7 +15,7 @@ namespace ipl {
Manager(EGG::Heap* heap);
/** @return The message data in use. */
wchar_t* getMessage(u32 id) const { return mpMessage->getMessage(id); }
const wchar_t* getMessage(u32 id) const { return mpMessage->getMessage(id); }
void setResource(u8* msgData) const { mpMessage->setResource(msgData); }
private:

View File

@@ -302,7 +302,7 @@ namespace ipl {
}
/** @return The Message ID as a Wide-string. */
static wchar_t* getMessage(u32 id) { return smArg.mpMessageMgr->getMessage(id); }
static const wchar_t* getMessage(u32 id) { return smArg.mpMessageMgr->getMessage(id); }
static message::Manager* getMessageManager() { return smArg.mpMessageMgr; }
static void* getFont();

View File

@@ -27,11 +27,7 @@ wchar_t* wcscat(wchar_t* dest, const wchar_t* src);
wchar_t* wcsncat(wchar_t* dest, const wchar_t* src, size_t num);
int wcsncmp(const wchar_t* s1, const wchar_t* s2, size_t num);
wchar_t* wcschr(wchar_t* ws, wchar_t wc);
#ifndef __cplusplus
wchar_t* wcsstr(const wchar_t* s1, const wchar_t* s2);
#else
const wchar_t* wcsstr(const wchar_t* s1, const wchar_t* s2);
#endif
int swprintf(wchar_t* ws, size_t len, const wchar_t* format, ...);
int vswprintf(wchar_t* ws, size_t len, const wchar_t* format, va_list arg);
@@ -40,12 +36,6 @@ int wcsnicmp(const char* dst, const char* src, size_t num);
#ifdef __cplusplus
}
extern "C++" {
inline wchar_t* wcsstr(wchar_t* s1, const wchar_t* s2) {
return const_cast<wchar_t*>(wcsstr(static_cast<const wchar_t*>(s1), s2));
}
}
#endif
#endif // MSL_WCHAR_H

View File

@@ -123,7 +123,7 @@ namespace nw4r {
const math::MTX34& GetMtx() const { return mMtx; }
void SetMtx(const math::MTX34& mtx) { mMtx = mtx; }
u8 GetAlpha() const { return mAlpha; }
u8 GetAlpha() { return mAlpha; }
void SetAlpha(u8 alpha) { mAlpha = alpha; }
const char* GetName() const { return mName; }

View File

@@ -55,14 +55,16 @@ namespace nw4r {
NW4R_ASSERT(type < TEXTCOLOR_MAX);
return mTextColors[type];
}
#ifdef IPL_SDMEMORY_SET_TEXT_COLORS
void SetTextColors(const ut::Color& first, const ut::Color& second) {
mTextColors[0] = first;
mTextColors[1] = second;
}
#endif
void SetTextColor(u32 type, ut::Color value) {
NW4R_ASSERT(type < TEXTCOLOR_MAX);
mTextColors[type] = value;
}
void SetTextColor(ut::Color top, ut::Color bottom) {
mTextColors[0] = top;
mTextColors[1] = bottom;
}
void SetTextPositionH(u8 pos) { detail::SetHorizontalPosition(&mTextPosition, pos); }
void SetTextPositionV(u8 pos) { detail::SetVerticalPosition(&mTextPosition, pos); }

View File

@@ -1,21 +1,10 @@
#include <nw4r/db/assert.h>
#include <nw4r/lyt/window.h>
#include <nw4r/lyt/common.h>
#include <nw4r/lyt/layout.h>
#include <nw4r/lyt/resources.h>
#include <nw4r/lyt/types.h>
#include <nw4r/math.h>
#include <new>
extern "C" const u8 scLytFatalColorR;
extern "C" const u8 scLytFatalColorG;
extern "C" const u8 scLytFatalColorB;
extern "C" const u8 scLytFatalColorA;
extern "C" char scLytFatalMsg[];
extern "C" char scLytFatalMsg[] = "Error#004\nAn error has occurred.\nThe system files are corrupted.";
#undef NW4R_ASSERT
#define NW4R_GLOBAL_ASSERT(x) \
@@ -37,6 +26,18 @@ extern "C" char scLytFatalMsg[];
} \
}
#include <nw4r/lyt/window.h>
#include <nw4r/lyt/common.h>
#include <nw4r/lyt/layout.h>
#include <nw4r/lyt/resources.h>
#include <nw4r/lyt/types.h>
#include <nw4r/math.h>
#include <new>
namespace nw4r {
namespace lyt {
NW4R_UT_GET_DERIVED_RUNTIME_TYPEINFO(Window, Pane);
@@ -173,22 +174,8 @@ namespace {
flipInfo.coords[VERTEXCOLOR_RB][iy] +
polSize.height / ((flipInfo.coords[VERTEXCOLOR_RT][iy] - flipInfo.coords[VERTEXCOLOR_RB][iy]) * tSz[iy]);
}
inline void SetFrameTexOrigin(math::VEC2* texCds, int corner, int ix, int iy, u8 originX, u8 originY) {
texCds[corner][ix] = texCds[corner ^ 2][ix] = originX;
texCds[corner][iy] = texCds[corner ^ 1][iy] = originY;
}
inline void SetFrameTexExtent(math::VEC2* texCds, const Size& polSize, const Size& texSize, const TextureFlipInfo& flipInfo, int corner, int ix,
int iy, u8 originX, u8 originY) {
const math::VEC2 tSz(texSize.width, texSize.height);
texCds[corner ^ 3][ix] = texCds[corner ^ 1][ix] = originX + polSize.width / ((flipInfo.coords[corner ^ 1][ix] - originX) * tSz[ix]);
texCds[corner ^ 3][iy] = texCds[corner ^ 2][iy] = originY + polSize.height / ((flipInfo.coords[corner ^ 2][iy] - originY) * tSz[iy]);
}
} // namespace
extern "C" char scLytFatalMsg[] = "Error#004\nAn error has occurred.\nThe system files are corrupted.";
namespace nw4r {
namespace lyt {
Window::Window(const res::Window* pBlock, const ResBlockSet& resBlockSet) : Pane(pBlock) {
@@ -401,17 +388,7 @@ namespace nw4r {
detail::DrawQuad(polPt, polSize, GX_TEXMAP1, texCds, bUseVtxCol ? vtxColors : NULL, alpha); \
}
GetLTFrameSize(&polPt, &polSize, basePt, mSize, frameSize);
{
TextureFlipInfo& flipInfo = GetTexutreFlipInfo(TEXTUREFLIP_NONE);
int iy = flipInfo.idx[FLIPINDEX_Y];
int ix = flipInfo.idx[FLIPINDEX_X];
const u8 originX = flipInfo.coords[VERTEXCOLOR_LT][ix];
const u8 originY = flipInfo.coords[VERTEXCOLOR_LT][iy];
SetFrameTexOrigin(*texCds, VERTEXCOLOR_LT, ix, iy, originX, originY);
SetFrameTexExtent(*texCds, polSize, texSize, flipInfo, VERTEXCOLOR_LT, ix, iy, originX, originY);
}
detail::DrawQuad(polPt, polSize, GX_TEXMAP1, texCds, bUseVtxCol ? vtxColors : NULL, alpha);
DRAW_QUAD_FOR_FRAME_1(LT, TEXTUREFLIP_NONE);
DRAW_QUAD_FOR_FRAME_1(RT, TEXTUREFLIP_H);
DRAW_QUAD_FOR_FRAME_1(RB, TEXTUREFLIP_180);
DRAW_QUAD_FOR_FRAME_1(LB, TEXTUREFLIP_V);

View File

@@ -33,417 +33,391 @@ static s32 scalingClampU8(s32 value) {
void TMCJPEGDEC_IdctBlock_Lumi(s32* block, u8* conv_row_ptr, u16 pitch, s32 zigzag) {
s32 workspace[64];
s32 pitch4;
s32* dst;
s32* src;
s32 pitch7;
s32 rowCount;
s32 pitch6;
s32 pitch5;
s32 pitch3;
s32 pitch2;
s32 processed;
s32* workspaceCursor;
s32 evenBaseSum;
s32 evenRotation;
s32 column;
s32 evenOutput3;
s32 coefficient2;
s32 coefficient1;
s32 coefficient4;
s32 coefficient5;
s32 coefficient6;
s32 coefficient7;
s32 oddOutput0;
s32 m;
s32 evenBaseDifference;
s32 processedCoefficients;
s32 z;
s32 evenOutput1;
s32 oddOutput3;
s32 oddLowRotation;
s32 oddHighRotation;
s32 evenRotationSum;
s32 r;
s32 oddOutput1;
s32 oddSumRotation;
s32 oddSumDifference;
s32 oddDifferenceSum;
s32 columnsRemaining;
s32 oddOutput2;
s32 evenOutput0;
s32 evenOutput2;
s32 coefficient3;
rowCount = (zigzag >> 4) * 8;
dst = workspace;
for (processed = 0; processed < rowCount; processed += 8) {
s32 c1;
s32 c2;
int acBits;
s32 c7;
s32 c5;
s32 c4;
s32 c3;
s32 c6;
c4 = block[4];
c6 = block[6];
c2 = block[2];
c1 = block[1];
c7 = block[7];
c5 = block[5];
c3 = block[3];
acBits = c4 | c6;
acBits = c2 | acBits;
acBits = c1 | acBits;
acBits = c7 | acBits;
acBits = c5 | acBits;
acBits = c3 | acBits;
if (acBits == 0) {
s32 dc = block[0];
dst[7] = dc;
dst[6] = dc;
dst[5] = dc;
dst[4] = dc;
dst[3] = dc;
dst[2] = dc;
dst[1] = dc;
dst[0] = dc;
} else {
s32 dc;
s32 evenSum;
s32 oddSumRotation;
s32 oddOutput0;
s32 evenRotationSum;
s32 evenRotation;
s32 oddLowDifference;
s32 oddDifferenceRotation;
s32 evenOutput3;
s32 oddOutput1;
s32 oddHighSum;
s32 oddOutput2;
s32 evenBaseSum;
s32 evenOutput0;
s32 oddDifferenceSum;
s32 evenOutput2;
s32 oddMix;
s32 oddLowRotation;
s32 oddOutput3;
s32 evenOutput1;
s32 oddHighRotation;
s32 oddLowSum;
s32 oddSumDifference;
s32 evenBaseDifference;
s32 oddHighDifference;
oddHighSum = c1 + c7;
dc = block[0];
evenSum = c6 + c2;
oddLowDifference = c5 - c3;
oddHighDifference = c1 - c7;
evenRotation = c2 - c6;
c2 = evenRotation * 0xB5 >> 8;
evenBaseDifference = dc - c4;
oddLowSum = c5 + c3;
oddSumDifference = oddHighSum - oddLowSum;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
oddDifferenceSum = oddLowDifference + oddHighDifference;
oddDifferenceRotation = oddDifferenceSum * 0x62 >> 8;
oddLowRotation = oddLowDifference * 0x8B;
oddHighRotation = oddHighDifference * 0x14E >> 8;
evenRotationSum = c2 + evenSum;
evenOutput1 = evenBaseDifference + c2;
oddLowRotation >>= 8;
evenBaseSum = dc + c4;
oddMix = oddHighRotation - oddDifferenceRotation;
evenOutput2 = evenBaseDifference - c2;
oddOutput1 = oddSumRotation + oddMix;
evenOutput3 = evenBaseSum - evenRotationSum;
oddLowSum += oddMix;
evenOutput0 = evenBaseSum + evenRotationSum;
oddOutput0 = oddHighSum + oddLowSum;
oddOutput3 = oddDifferenceRotation + oddLowRotation;
oddOutput2 = oddOutput3 + oddSumRotation;
dst[0] = evenOutput0 + oddOutput0;
dst[7] = evenOutput0 - oddOutput0;
dst[1] = evenOutput1 + oddOutput1;
dst[6] = evenOutput1 - oddOutput1;
dst[2] = evenOutput2 + oddOutput2;
dst[5] = evenOutput2 - oddOutput2;
dst[3] = evenOutput3 + oddOutput3;
dst[4] = evenOutput3 - oddOutput3;
r = (zigzag >> 4) * 8;
workspaceCursor = workspace;
processedCoefficients = 0;
{
for (; processedCoefficients < r; processedCoefficients += 8) {
u32 acBits;
coefficient4 = block[4];
coefficient6 = block[6];
coefficient2 = block[2];
coefficient1 = block[1];
coefficient7 = block[7];
coefficient5 = block[5];
coefficient3 = block[3];
acBits = (u32)coefficient4;
acBits |= (u32)coefficient6;
acBits |= (u32)coefficient2;
acBits |= (u32)coefficient1;
acBits |= (u32)coefficient7;
acBits |= (u32)coefficient5;
acBits |= (u32)coefficient3;
if (acBits == 0) {
s32 sample = block[0];
workspaceCursor[7] = sample;
workspaceCursor[6] = sample;
workspaceCursor[5] = sample;
workspaceCursor[4] = sample;
workspaceCursor[3] = sample;
workspaceCursor[2] = sample;
workspaceCursor[1] = sample;
workspaceCursor[0] = sample;
} else {
s32 oddLowSum;
s32 oddHighSum;
s32 oddLowDifference;
s32 oddHighDifference;
s32 dcValue;
evenRotation = coefficient2 - coefficient6;
oddLowSum = coefficient5 + coefficient3;
oddLowDifference = coefficient5 - coefficient3;
oddHighSum = coefficient1 + coefficient7;
oddHighDifference = coefficient1 - coefficient7;
evenRotationSum = coefficient6 + coefficient2;
evenRotation = evenRotation * 0xB5 >> 8;
oddSumDifference = oddHighSum - oddLowSum;
oddDifferenceSum = oddLowDifference + oddHighDifference;
dcValue = block[0];
evenBaseDifference = dcValue - coefficient4;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
evenBaseSum = dcValue + coefficient4;
evenRotationSum = evenRotation + evenRotationSum;
evenOutput1 = evenBaseDifference + evenRotation;
z = oddDifferenceSum * 0x62 >> 8;
evenOutput0 = evenBaseSum + evenRotationSum;
evenOutput3 = evenBaseSum - evenRotationSum;
oddHighRotation = oddHighDifference * 0x14E >> 8;
evenOutput2 = evenBaseDifference - evenRotation;
m = oddHighRotation - z;
oddLowSum += m;
oddOutput0 = oddHighSum + oddLowSum;
oddOutput1 = oddSumRotation + m;
workspaceCursor[0] = evenOutput0 + oddOutput0;
oddLowRotation = oddLowDifference * 0x8B;
workspaceCursor[7] = evenOutput0 - oddOutput0;
oddLowRotation >>= 8;
workspaceCursor[1] = evenOutput1 + oddOutput1;
oddOutput3 = z + oddLowRotation;
oddOutput2 = oddOutput3 + oddSumRotation;
workspaceCursor[6] = evenOutput1 - oddOutput1;
workspaceCursor[2] = evenOutput2 + oddOutput2;
workspaceCursor[5] = evenOutput2 - oddOutput2;
workspaceCursor[3] = evenOutput3 + oddOutput3;
workspaceCursor[4] = evenOutput3 - oddOutput3;
}
block += 8;
workspaceCursor += 8;
}
block += 8;
dst += 8;
}
dst = workspace + processed;
for (; processed <= 56; processed += 8) {
memset(dst, 0, 32);
dst += 8;
workspaceCursor = workspace + processedCoefficients;
for (; processedCoefficients <= 0x38; processedCoefficients += 8) {
memset(workspaceCursor, 0, 0x20);
workspaceCursor += 8;
}
src = workspace + 7;
pitch4 = pitch * 4;
pitch5 = pitch4 + pitch;
pitch3 = pitch4 - pitch;
pitch2 = pitch * 2;
pitch6 = pitch * 6;
pitch7 = pitch * 8 - pitch;
for (column = 7; column >= 0; column--) {
s32 c1;
s32 c2;
s32 c5;
s32 c3;
s32 c6;
s32 c4;
s32 c7;
int acBits;
r = pitch * 8 - pitch;
z = pitch * 4;
m = pitch * 2;
workspaceCursor = workspace + 7;
for (columnsRemaining = 8, column = 7; columnsRemaining > 0; columnsRemaining--, column--) {
u32 acBits;
u8* output;
c4 = src[32];
c6 = src[48];
c2 = src[16];
c1 = src[8];
c7 = src[56];
c5 = src[40];
c3 = src[24];
acBits = c4 | c6;
acBits = c2 | acBits;
acBits = c1 | acBits;
acBits = c7 | acBits;
acBits = c5 | acBits;
acBits = c3 | acBits;
coefficient4 = workspaceCursor[0x20];
coefficient6 = workspaceCursor[0x30];
coefficient2 = workspaceCursor[0x10];
coefficient1 = workspaceCursor[8];
coefficient7 = workspaceCursor[0x38];
coefficient5 = workspaceCursor[0x28];
coefficient3 = workspaceCursor[0x18];
acBits = (u32)coefficient4;
acBits |= (u32)coefficient6;
acBits |= (u32)coefficient2;
acBits |= (u32)coefficient1;
acBits |= (u32)coefficient7;
acBits |= (u32)coefficient5;
acBits |= (u32)coefficient3;
output = conv_row_ptr + column;
if (acBits == 0) {
u8 sample = clampU8((*src >> 11) + 0x80);
output[pitch7] = sample;
output[pitch6] = sample;
output[pitch5] = sample;
output[pitch4] = sample;
output[pitch3] = sample;
output[pitch2] = sample;
u8 sample = clampU8((*workspaceCursor >> 11) + 0x80);
output[r] = sample;
output[pitch * 6] = sample;
output[z + pitch] = sample;
output[z] = sample;
output[z - pitch] = sample;
output[m] = sample;
output[pitch] = sample;
output[0] = sample;
} else {
s32 oddDifferenceSum;
s32 oddSumRotation;
s32 evenBaseSum;
s32 evenOutput2;
s32 dc;
s32 evenBaseDifference;
s32 evenOutput0;
s32 evenOutput1;
s32 evenOutput3;
s32 oddHighRotation;
s32 oddMix;
s32 oddHighDifference;
s32 oddLowSum;
s32 oddLowRotation;
s32 evenRotation;
s32 oddLowDifference;
s32 oddSumDifference;
s32 oddHighSum;
s32 evenRotationSum;
s32 oddOutput0;
s32 evenSum;
s32 oddOutput2;
s32 oddDifferenceRotation;
s32 oddOutput1;
s32 oddOutput3;
evenSum = c6 + c2;
evenRotation = c2 - c6;
oddLowSum = c5 + c3;
oddHighDifference = c1 - c7;
oddLowDifference = c5 - c3;
oddHighSum = c1 + c7;
c2 = evenRotation * 0xB5 >> 8;
dc = *src + 0x40000;
oddDifferenceSum = oddLowDifference + oddHighDifference;
s32 dcValue;
evenRotation = coefficient2 - coefficient6;
oddLowSum = coefficient5 + coefficient3;
coefficient5 = coefficient5 - coefficient3;
oddHighSum = coefficient1 + coefficient7;
coefficient1 = coefficient1 - coefficient7;
evenRotationSum = coefficient6 + coefficient2;
coefficient2 = evenRotation * 0xB5 >> 8;
oddSumDifference = oddHighSum - oddLowSum;
oddDifferenceSum = coefficient5 + coefficient1;
dcValue = *workspaceCursor + 0x40000;
evenBaseDifference = dcValue - coefficient4;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
evenBaseSum = dc + c4;
oddDifferenceRotation = oddDifferenceSum * 0x62 >> 8;
oddHighRotation = oddHighDifference * 0x14E >> 8;
evenRotationSum = c2 + evenSum;
oddMix = oddHighRotation - oddDifferenceRotation;
oddLowSum += oddMix;
evenBaseSum = dcValue + coefficient4;
evenRotationSum = coefficient2 + evenRotationSum;
evenOutput1 = evenBaseDifference + coefficient2;
oddDifferenceSum = oddDifferenceSum * 0x62 >> 8;
evenOutput0 = evenBaseSum + evenRotationSum;
evenBaseDifference = dc - c4;
evenOutput3 = evenBaseSum - evenRotationSum;
evenOutput1 = evenBaseDifference + c2;
oddHighRotation = coefficient1 * 0x14E >> 8;
evenOutput2 = evenBaseDifference - coefficient2;
oddHighRotation = oddHighRotation - oddDifferenceSum;
oddLowSum += oddHighRotation;
oddOutput0 = oddHighSum + oddLowSum;
oddLowRotation = oddLowDifference * 0x8B >> 8;
oddOutput3 = oddDifferenceRotation + oddLowRotation;
evenOutput2 = evenBaseDifference - c2;
oddOutput1 = oddSumRotation + oddHighRotation;
oddLowRotation = coefficient5 * 0x8B >> 8;
oddOutput3 = oddDifferenceSum + oddLowRotation;
oddOutput2 = oddOutput3 + oddSumRotation;
oddOutput1 = oddSumRotation + oddMix;
output[0] = scalingClampU8(evenOutput0 + oddOutput0);
output[pitch7] = scalingClampU8(evenOutput0 - oddOutput0);
output[r] = scalingClampU8(evenOutput0 - oddOutput0);
output[pitch] = scalingClampU8(evenOutput1 + oddOutput1);
output[pitch6] = scalingClampU8(evenOutput1 - oddOutput1);
output[pitch2] = scalingClampU8(evenOutput2 + oddOutput2);
output[pitch5] = scalingClampU8(evenOutput2 - oddOutput2);
output[pitch3] = scalingClampU8(evenOutput3 + oddOutput3);
output[pitch4] = scalingClampU8(evenOutput3 - oddOutput3);
output[pitch * 6] = scalingClampU8(evenOutput1 - oddOutput1);
output[m] = scalingClampU8(evenOutput2 + oddOutput2);
output[z + pitch] = scalingClampU8(evenOutput2 - oddOutput2);
output[z - pitch] = scalingClampU8(evenOutput3 + oddOutput3);
output[z] = scalingClampU8(evenOutput3 - oddOutput3);
}
src--;
workspaceCursor--;
}
}
void TMCJPEGDEC_IdctBlock_Col(s32* block, u8* conv_row_ptr, u16 pitch, s32 zigzag) {
s32 workspace[64];
s32* src;
s32* workspaceCursor;
s32 evenBaseDifference;
s32 columnsRemaining;
s32 evenBaseSum;
s32 coefficient1;
s32 coefficient2;
s32 coefficient3;
s32 coefficient4;
s32 coefficient5;
s32 coefficient6;
s32 coefficient7;
s32 v;
s32 rowCoefficientCount;
s32 processedCoefficients;
s32 column;
s32 rowCount;
s32 processed;
s32* dst;
s32 m;
s32 n;
s32 oddOutput1;
s32 oddSumRotation;
s32 oddOutput2;
s32 evenOutput2;
s32 u;
s32 evenOutput0;
s32 oddOutput3;
s32 rotation45;
s32 z;
s32 oddSumDifference;
s32 oddDifferenceSum;
s32 oddHighRotation;
s32 oddLowRotation;
s32 evenOutput3;
if (zigzag == 0x11) {
s32 dc = block[0];
s32 sample = clampS8(dc >> 11);
memset(conv_row_ptr, (s8)sample, 64);
s32 sample;
sample = clampS8(block[0] >> 11);
memset(conv_row_ptr, (s8)sample, 0x40);
return;
}
rowCount = (zigzag >> 4) * 8;
if ((zigzag & 0xF) <= 2) {
dst = workspace;
for (processed = 0; processed < rowCount; processed += 8) {
s32 mid;
s32 odd;
s32 outer;
s32 dc;
s32 inner;
s32 rotation;
s32 lowRotation;
s32 mix;
odd = block[1];
rotation = odd * 0xB5 >> 8;
lowRotation = odd * 0x62 >> 8;
dc = block[0];
mix = (odd * 0x14E >> 8) - lowRotation;
outer = odd + mix;
dst[0] = dc + outer;
inner = rotation + mix;
dst[7] = dc - outer;
dst[1] = dc + inner;
mid = lowRotation + rotation;
dst[6] = dc - inner;
dst[2] = dc + mid;
dst[5] = dc - mid;
dst[3] = dc + lowRotation;
dst[4] = dc - lowRotation;
dst += 8;
block += 8;
}
dst = workspace + processed;
for (; processed <= 56; processed += 8) {
memset(dst, 0, 32);
dst += 8;
}
} else {
dst = workspace;
for (processed = 0; processed < rowCount; processed += 8) {
s32 c2;
s32 c7;
s32 c3;
s32 c5;
s32 c1;
s32 c6;
int acBits;
s32 c4;
c4 = block[4];
c6 = block[6];
c2 = block[2];
c1 = block[1];
c7 = block[7];
c5 = block[5];
c3 = block[3];
acBits = c4 | c6;
acBits = c2 | acBits;
acBits = c1 | acBits;
acBits = c7 | acBits;
acBits = c5 | acBits;
acBits = c3 | acBits;
if (acBits == 0) {
s32 dc = block[0];
dst[7] = dc;
dst[6] = dc;
dst[5] = dc;
dst[4] = dc;
dst[3] = dc;
dst[2] = dc;
dst[1] = dc;
dst[0] = dc;
} else {
s32 evenBaseDifference;
s32 oddOutput3;
s32 oddMix;
s32 evenOutput1;
s32 evenOutput2;
s32 oddDifferenceRotation;
s32 oddLowRotation;
s32 oddDifferenceSum;
s32 evenSum;
s32 oddLowSum;
s32 dc;
s32 oddSumDifference;
s32 oddLowDifference;
s32 evenBaseSum;
s32 oddSumRotation;
s32 evenRotationSum;
s32 evenRotation;
s32 evenOutput0;
s32 oddOutput1;
s32 oddHighDifference;
s32 oddOutput0;
s32 evenOutput3;
s32 oddHighSum;
s32 oddOutput2;
s32 oddHighRotation;
oddHighDifference = c1 - c7;
oddLowSum = c5 + c3;
evenSum = c6 + c2;
oddHighSum = c1 + c7;
evenRotation = c2 - c6;
dc = block[0];
evenBaseDifference = dc - c4;
c2 = evenRotation * 0xB5 >> 8;
oddSumDifference = oddHighSum - oddLowSum;
oddLowDifference = c5 - c3;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
evenBaseSum = dc + c4;
oddHighRotation = oddHighDifference * 0x14E >> 8;
oddDifferenceSum = oddLowDifference + oddHighDifference;
oddDifferenceRotation = oddDifferenceSum * 0x62 >> 8;
evenRotationSum = c2 + evenSum;
oddMix = oddHighRotation - oddDifferenceRotation;
oddOutput1 = oddSumRotation + oddMix;
evenOutput1 = evenBaseDifference + c2;
oddLowRotation = oddLowDifference * 0x8B;
oddLowSum += oddMix;
evenOutput3 = evenBaseSum - evenRotationSum;
evenOutput0 = evenBaseSum + evenRotationSum;
oddLowRotation >>= 8;
oddOutput3 = oddDifferenceRotation + oddLowRotation;
evenOutput2 = evenBaseDifference - c2;
oddOutput0 = oddHighSum + oddLowSum;
dst[0] = evenOutput0 + oddOutput0;
dst[7] = evenOutput0 - oddOutput0;
dst[1] = evenOutput1 + oddOutput1;
oddOutput2 = oddOutput3 + oddSumRotation;
dst[6] = evenOutput1 - oddOutput1;
dst[2] = evenOutput2 + oddOutput2;
dst[5] = evenOutput2 - oddOutput2;
dst[3] = evenOutput3 + oddOutput3;
dst[4] = evenOutput3 - oddOutput3;
}
block += 8;
dst += 8;
}
dst = workspace + processed;
for (; processed <= 56; processed += 8) {
memset(dst, 0, 32);
dst += 8;
}
rowCoefficientCount = (zigzag >> 4) * 8;
if ((zigzag & 0xF) > 2) {
goto fullRowTransform;
}
src = workspace + 7;
for (column = 7; column >= 0; column--) {
s32 c1;
s32 c3;
int acBits;
s32 c7;
s32 c2;
s32 c5;
workspaceCursor = workspace;
processedCoefficients = 0;
for (; processedCoefficients < rowCoefficientCount; processedCoefficients += 8) {
s32 dcValue;
s32 oddCoefficient;
oddCoefficient = block[1];
dcValue = block[0];
rotation45 = oddCoefficient * 0xB5 >> 8;
v = oddCoefficient * 0x62 >> 8;
u = v + rotation45;
z = (oddCoefficient * 0x14E >> 8) - v;
m = oddCoefficient + z;
n = rotation45 + z;
workspaceCursor[0] = dcValue + m;
workspaceCursor[7] = dcValue - m;
workspaceCursor[1] = dcValue + n;
workspaceCursor[6] = dcValue - n;
workspaceCursor[2] = dcValue + u;
workspaceCursor[5] = dcValue - u;
workspaceCursor[3] = dcValue + v;
workspaceCursor[4] = dcValue - v;
workspaceCursor += 8;
block += 8;
}
workspaceCursor = workspace + processedCoefficients;
for (; processedCoefficients <= 0x38; processedCoefficients += 8) {
memset(workspaceCursor, 0, 0x20);
workspaceCursor += 8;
}
goto columnTransform;
fullRowTransform:
workspaceCursor = workspace;
processedCoefficients = 0;
for (; processedCoefficients < rowCoefficientCount; processedCoefficients += 8) {
u32 acBits;
coefficient4 = block[4];
coefficient6 = block[6];
coefficient2 = block[2];
coefficient1 = block[1];
coefficient7 = block[7];
coefficient5 = block[5];
coefficient3 = block[3];
acBits = (u32)coefficient4;
acBits |= (u32)coefficient6;
acBits |= (u32)coefficient2;
acBits |= (u32)coefficient1;
acBits |= (u32)coefficient7;
acBits |= (u32)coefficient5;
acBits |= (u32)coefficient3;
if (acBits == 0) {
s32 sample;
sample = block[0];
workspaceCursor[7] = sample;
workspaceCursor[6] = sample;
workspaceCursor[5] = sample;
workspaceCursor[4] = sample;
workspaceCursor[3] = sample;
workspaceCursor[2] = sample;
workspaceCursor[1] = sample;
workspaceCursor[0] = sample;
} else {
s32 oddLowSum;
s32 oddLowDifference;
s32 oddHighSum;
s32 oddHighDifference;
s32 dcValue;
rotation45 = coefficient2 - coefficient6;
oddLowSum = coefficient5 + coefficient3;
oddLowDifference = coefficient5 - coefficient3;
oddHighSum = coefficient1 + coefficient7;
oddHighDifference = coefficient1 - coefficient7;
u = coefficient6 + coefficient2;
rotation45 = rotation45 * 0xB5 >> 8;
oddSumDifference = oddHighSum - oddLowSum;
oddDifferenceSum = oddLowDifference + oddHighDifference;
dcValue = block[0];
evenBaseDifference = dcValue - coefficient4;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
evenBaseSum = dcValue + coefficient4;
u = rotation45 + u;
v = evenBaseDifference + rotation45;
z = oddDifferenceSum * 0x62 >> 8;
evenOutput0 = evenBaseSum + u;
evenOutput3 = evenBaseSum - u;
oddHighRotation = oddHighDifference * 0x14E >> 8;
evenOutput2 = evenBaseDifference - rotation45;
m = oddHighRotation - z;
oddLowSum += m;
n = oddHighSum + oddLowSum;
oddOutput1 = oddSumRotation + m;
workspaceCursor[0] = evenOutput0 + n;
oddLowRotation = oddLowDifference * 0x8B;
workspaceCursor[7] = evenOutput0 - n;
oddLowRotation >>= 8;
workspaceCursor[1] = v + oddOutput1;
oddOutput3 = z + oddLowRotation;
oddOutput2 = oddOutput3 + oddSumRotation;
workspaceCursor[6] = v - oddOutput1;
workspaceCursor[2] = evenOutput2 + oddOutput2;
workspaceCursor[5] = evenOutput2 - oddOutput2;
workspaceCursor[3] = evenOutput3 + oddOutput3;
workspaceCursor[4] = evenOutput3 - oddOutput3;
}
block += 8;
workspaceCursor += 8;
}
workspaceCursor = workspace + processedCoefficients;
for (; processedCoefficients <= 0x38; processedCoefficients += 8) {
memset(workspaceCursor, 0, 0x20);
workspaceCursor += 8;
}
columnTransform:
workspaceCursor = workspace + 7;
for (columnsRemaining = 8, column = 7; columnsRemaining > 0; columnsRemaining--, column--) {
u32 acBits;
u8* output;
s32 c6;
s32 c4;
c4 = src[32];
coefficient4 = workspaceCursor[0x20];
output = conv_row_ptr + column;
c6 = src[48];
c2 = src[16];
c1 = src[8];
c7 = src[56];
c5 = src[40];
c3 = src[24];
acBits = c4 | c6;
acBits = c2 | acBits;
acBits = c1 | acBits;
acBits = c7 | acBits;
acBits = c5 | acBits;
acBits = c3 | acBits;
coefficient6 = workspaceCursor[0x30];
coefficient2 = workspaceCursor[0x10];
coefficient1 = workspaceCursor[8];
coefficient7 = workspaceCursor[0x38];
coefficient5 = workspaceCursor[0x28];
coefficient3 = workspaceCursor[0x18];
acBits = (u32)coefficient4;
acBits |= (u32)coefficient6;
acBits |= (u32)coefficient2;
acBits |= (u32)coefficient1;
acBits |= (u32)coefficient7;
acBits |= (u32)coefficient5;
acBits |= (u32)coefficient3;
if (acBits == 0) {
s32 sample = clampS8(*src >> 11);
s32 sample;
sample = clampS8(*workspaceCursor >> 11);
output[56] = (u8)sample;
output[48] = (u8)sample;
output[40] = (u8)sample;
@@ -453,68 +427,48 @@ void TMCJPEGDEC_IdctBlock_Col(s32* block, u8* conv_row_ptr, u16 pitch, s32 zigza
output[8] = (u8)sample;
output[0] = (u8)sample;
} else {
s32 evenSum;
s32 evenOutput2;
s32 oddOutput0;
s32 oddMix;
s32 evenBaseSum;
s32 oddHighRotation;
s32 evenRotationSum;
s32 oddSumDifference;
s32 evenOutput1;
s32 oddHighSum;
s32 evenOutput0;
s32 oddOutput1;
s32 oddDifferenceSum;
s32 oddLowSum;
s32 oddOutput3;
s32 evenBaseDifference;
s32 oddHighDifference;
s32 oddOutput2;
s32 dc;
s32 oddLowDifference;
s32 evenOutput3;
s32 oddDifferenceRotation;
s32 oddLowRotation;
s32 evenRotation;
s32 oddSumRotation;
oddHighSum = c1 + c7;
evenRotation = c2 - c6;
oddLowSum = c5 + c3;
s32 oddHighSum;
s32 oddHighDifference;
s32 dcValue;
rotation45 = coefficient2 - coefficient6;
oddLowSum = coefficient5 + coefficient3;
oddLowDifference = coefficient5 - coefficient3;
oddHighSum = coefficient1 + coefficient7;
oddHighDifference = coefficient1 - coefficient7;
u = coefficient6 + coefficient2;
rotation45 = rotation45 * 0xB5 >> 8;
oddSumDifference = oddHighSum - oddLowSum;
evenSum = c6 + c2;
oddLowDifference = c5 - c3;
c2 = evenRotation * 0xB5 >> 8;
oddHighDifference = c1 - c7;
dc = *src;
evenRotationSum = c2 + evenSum;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
oddDifferenceSum = oddLowDifference + oddHighDifference;
oddDifferenceRotation = oddDifferenceSum * 0x62 >> 8;
evenBaseDifference = dc - c4;
evenBaseSum = dc + c4;
dcValue = *workspaceCursor;
evenBaseDifference = dcValue - coefficient4;
oddSumRotation = oddSumDifference * 0xB5 >> 8;
evenBaseSum = dcValue + coefficient4;
u = rotation45 + u;
v = evenBaseDifference + rotation45;
z = oddDifferenceSum * 0x62 >> 8;
evenOutput0 = evenBaseSum + u;
evenOutput3 = evenBaseSum - u;
oddHighRotation = oddHighDifference * 0x14E >> 8;
oddMix = oddHighRotation - oddDifferenceRotation;
evenOutput3 = evenBaseSum - evenRotationSum;
evenOutput1 = evenBaseDifference + c2;
evenOutput2 = evenBaseDifference - c2;
evenOutput0 = evenBaseSum + evenRotationSum;
evenOutput2 = evenBaseDifference - rotation45;
m = oddHighRotation - z;
oddLowSum += m;
n = oddHighSum + oddLowSum;
oddOutput1 = oddSumRotation + m;
oddLowRotation = oddLowDifference * 0x8B >> 8;
oddOutput3 = oddDifferenceRotation + oddLowRotation;
oddLowSum += oddMix;
oddOutput1 = oddSumRotation + oddMix;
oddOutput0 = oddHighSum + oddLowSum;
oddOutput3 = z + oddLowRotation;
oddOutput2 = oddOutput3 + oddSumRotation;
output[0] = (u8)clampS8((evenOutput0 + oddOutput0) >> 11);
output[56] = (u8)clampS8((evenOutput0 - oddOutput0) >> 11);
output[8] = (u8)clampS8((evenOutput1 + oddOutput1) >> 11);
output[48] = (u8)clampS8((evenOutput1 - oddOutput1) >> 11);
output[0] = (u8)clampS8((evenOutput0 + n) >> 11);
output[56] = (u8)clampS8((evenOutput0 - n) >> 11);
output[8] = (u8)clampS8((v + oddOutput1) >> 11);
output[48] = (u8)clampS8((v - oddOutput1) >> 11);
output[16] = (u8)clampS8((evenOutput2 + oddOutput2) >> 11);
output[40] = (u8)clampS8((evenOutput2 - oddOutput2) >> 11);
output[24] = (u8)clampS8((evenOutput3 + oddOutput3) >> 11);
output[32] = (u8)clampS8((evenOutput3 - oddOutput3) >> 11);
}
src--;
workspaceCursor--;
}
}

View File

@@ -14,37 +14,7 @@ static void TMCJPEGDEC_converterYUV444toRGB565edge(TMCCJPEGDecWork*, s32, s32);
static void TMCJPEGDEC_converterYUV400toRGB565(TMCCJPEGDecWork*, s32, s32);
static void TMCJPEGDEC_converterYUV400toRGB565edge(TMCCJPEGDecWork*, s32, s32);
#pragma push
#pragma optimization_level 1
s32 TMCJPEGDEC_set_converterRGB565(TMCCJPEGDecWork* work) {
u8 mode411;
u8* crBlock411;
u8* cbBlock411;
u8* fourthRow411;
u8* thirdRow411;
u8* secondRow411;
u8* firstRow411;
TMCConverterFunc* edgeConverter411;
TMCConverterFunc* converter411;
u8 mode422;
u8* crBlock422;
u8* cbBlock422;
u8* secondRow422;
u8* firstRow422;
TMCConverterFunc* edgeConverter422;
TMCConverterFunc* converter422;
u8 mode420;
u8* crBlock420;
u8* cbBlock420;
u8* fourthRow420;
u8* thirdRow420;
u8* secondRow420;
u8* firstRow420;
TMCConverterFunc* edgeConverter420;
TMCConverterFunc* converter420;
u8* buffer;
s32 componentCount;
TMCCJPEGDecState* state;
@@ -55,84 +25,97 @@ s32 TMCJPEGDEC_set_converterRGB565(TMCCJPEGDecWork* work) {
switch (componentCount) {
case 0: {
mode411 = work->idctMode;
firstRow411 = buffer + 4;
converter411 = TMCJPEGDEC_converterYUV411toRGB565;
edgeConverter411 = TMCJPEGDEC_converterYUV411toRGB565edge;
secondRow411 = firstRow411 + mode411;
thirdRow411 = secondRow411 + mode411;
fourthRow411 = thirdRow411 + mode411;
cbBlock411 = buffer + 260;
crBlock411 = buffer + 324;
work->pConverterFunc = converter411;
work->pConverterFuncEdge = edgeConverter411;
work->pConvRowPtrs[0] = firstRow411;
work->pConvRowPtrs[1] = secondRow411;
work->pConvRowPtrs[2] = thirdRow411;
work->pConvRowPtrs[3] = fourthRow411;
work->pConvRowPtrs[5] = cbBlock411;
work->pConvRowPtrs[6] = crBlock411;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* thirdRow;
u8* fourthRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEGDEC_converterYUV411toRGB565;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV411toRGB565edge;
secondRow = firstRow + mode;
thirdRow = secondRow + mode;
fourthRow = thirdRow + mode;
cbBlock = buffer + 260;
crBlock = buffer + 324;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[2] = thirdRow;
work->pConvRowPtrs[3] = fourthRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 32;
work->converterFlags = 0;
break;
}
case 1: {
mode422 = work->idctMode;
firstRow422 = buffer + 4;
converter422 = TMCJPEGDEC_converterYUV422toRGB565;
edgeConverter422 = TMCJPEGDEC_converterYUV422toRGB565edge;
secondRow422 = firstRow422 + mode422;
cbBlock422 = buffer + 132;
crBlock422 = buffer + 196;
work->pConverterFunc = converter422;
work->pConverterFuncEdge = edgeConverter422;
work->pConvRowPtrs[0] = firstRow422;
work->pConvRowPtrs[1] = secondRow422;
work->pConvRowPtrs[5] = cbBlock422;
work->pConvRowPtrs[6] = crBlock422;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEGDEC_converterYUV422toRGB565;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV422toRGB565edge;
secondRow = firstRow + mode;
cbBlock = buffer + 132;
crBlock = buffer + 196;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 16;
work->converterFlags = 0;
break;
}
case 2: {
mode420 = work->idctMode;
firstRow420 = buffer + 4;
converter420 = TMCJPEGDEC_converterYUV420toRGB565;
edgeConverter420 = TMCJPEGDEC_converterYUV420toRGB565edge;
secondRow420 = firstRow420 + mode420;
thirdRow420 = firstRow420 + mode420 * 16;
fourthRow420 = thirdRow420 + mode420;
cbBlock420 = buffer + 260;
crBlock420 = buffer + 324;
work->pConverterFunc = converter420;
work->pConverterFuncEdge = edgeConverter420;
work->pConvRowPtrs[0] = firstRow420;
work->pConvRowPtrs[1] = secondRow420;
work->pConvRowPtrs[2] = thirdRow420;
work->pConvRowPtrs[3] = fourthRow420;
work->pConvRowPtrs[5] = cbBlock420;
work->pConvRowPtrs[6] = crBlock420;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* thirdRow;
u8* fourthRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEGDEC_converterYUV420toRGB565;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV420toRGB565edge;
secondRow = firstRow + mode;
thirdRow = firstRow + mode * 16;
fourthRow = thirdRow + mode;
cbBlock = buffer + 260;
crBlock = buffer + 324;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[2] = thirdRow;
work->pConvRowPtrs[3] = fourthRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 16;
work->converterFlags = 0;
break;
}
case 3: {
u32 mode;
u8* crBlock;
u8* cbBlock;
u8* secondRow;
u8 mode;
u8* firstRow;
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
u8* secondRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
converter = TMCJPEGDEC_converterYUV211toRGB565;
edgeConverter = TMCJPEGDEC_converterYUV211toRGB565edge;
work->pConverterFunc = TMCJPEGDEC_converterYUV211toRGB565;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV211toRGB565edge;
secondRow = firstRow + mode * 8;
cbBlock = buffer + 132;
crBlock = buffer + 196;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[5] = cbBlock;
@@ -142,27 +125,27 @@ s32 TMCJPEGDEC_set_converterRGB565(TMCCJPEGDecWork* work) {
break;
}
case 4: {
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
TMCConverterFunc* edgeConverter;
converter = TMCJPEGDEC_converterYUV444toRGB565;
edgeConverter = TMCJPEGDEC_converterYUV444toRGB565edge;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = buffer + 4;
work->pConvRowPtrs[5] = buffer + 0x44;
work->pConvRowPtrs[6] = buffer + 0x84;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pitch = 0x08;
work->converterFlags = 0;
break;
}
case 5: {
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
TMCConverterFunc* edgeConverter;
converter = TMCJPEGDEC_converterYUV400toRGB565;
edgeConverter = TMCJPEGDEC_converterYUV400toRGB565edge;
work->pConvRowPtrs[0] = buffer + 4;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = buffer + 4;
work->pitch = 0x08;
work->converterFlags = 0;
break;
@@ -175,19 +158,13 @@ s32 TMCJPEGDEC_set_converterRGB565(TMCCJPEGDecWork* work) {
{
s32 width = state->jpegWidth;
s32 height = state->jpegHeight;
s32 roundedWidth;
s32 heightPadding;
state->convWidth = ((u32)width / 4 + (width % 4 != 0)) * 4;
state->convHeight = ((u32)height / 4 + (height % 4 != 0)) * 4;
roundedWidth = (u32)width / 4 + (width % 4 != 0);
heightPadding = height % 4 != 0;
state->convWidth = roundedWidth * 4;
state->convHeight = ((u32)height / 4 + heightPadding) * 4;
}
return 0;
}
#pragma pop
static void TMCJPEGDEC_converterYUV411toRGB565(TMCCJPEGDecWork* work, s32 x, s32 y) {
s32 tileColumn;
s32 red;

View File

@@ -14,37 +14,7 @@ static void TMCJPEGDEC_converterYUV444toRGBA8edge(TMCCJPEGDecWork*, s32, s32);
static void TMCJPEGDEC_converterYUV400toRGBA8(TMCCJPEGDecWork*, s32, s32);
static void TMCJPEGDEC_converterYUV400toRGBA8edge(TMCCJPEGDecWork*, s32, s32);
#pragma push
#pragma optimization_level 1
s32 TMCJPEGDEC_set_converterRGBA8(TMCCJPEGDecWork* work) {
u8 mode411;
u8* crBlock411;
u8* cbBlock411;
u8* fourthRow411;
u8* thirdRow411;
u8* secondRow411;
u8* firstRow411;
TMCConverterFunc* edgeConverter411;
TMCConverterFunc* converter411;
u8 mode422;
u8* crBlock422;
u8* cbBlock422;
u8* secondRow422;
u8* firstRow422;
TMCConverterFunc* edgeConverter422;
TMCConverterFunc* converter422;
u8 mode420;
u8* crBlock420;
u8* cbBlock420;
u8* fourthRow420;
u8* thirdRow420;
u8* secondRow420;
u8* firstRow420;
TMCConverterFunc* edgeConverter420;
TMCConverterFunc* converter420;
u8* buffer;
s32 componentCount;
TMCCJPEGDecState* state;
@@ -55,84 +25,97 @@ s32 TMCJPEGDEC_set_converterRGBA8(TMCCJPEGDecWork* work) {
switch (componentCount) {
case 0: {
mode411 = work->idctMode;
firstRow411 = buffer + 4;
converter411 = TMCJPEGDEC_converterYUV411toRGBA8;
edgeConverter411 = TMCJPEGDEC_converterYUV411toRGBA8edge;
secondRow411 = firstRow411 + mode411;
thirdRow411 = secondRow411 + mode411;
fourthRow411 = thirdRow411 + mode411;
cbBlock411 = buffer + 260;
crBlock411 = buffer + 324;
work->pConverterFunc = converter411;
work->pConverterFuncEdge = edgeConverter411;
work->pConvRowPtrs[0] = firstRow411;
work->pConvRowPtrs[1] = secondRow411;
work->pConvRowPtrs[2] = thirdRow411;
work->pConvRowPtrs[3] = fourthRow411;
work->pConvRowPtrs[5] = cbBlock411;
work->pConvRowPtrs[6] = crBlock411;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* thirdRow;
u8* fourthRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEGDEC_converterYUV411toRGBA8;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV411toRGBA8edge;
secondRow = firstRow + mode;
thirdRow = secondRow + mode;
fourthRow = thirdRow + mode;
cbBlock = buffer + 260;
crBlock = buffer + 324;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[2] = thirdRow;
work->pConvRowPtrs[3] = fourthRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 32;
work->converterFlags = 0;
break;
}
case 1: {
mode422 = work->idctMode;
firstRow422 = buffer + 4;
converter422 = TMCJPEGDEC_converterYUV422toRGBA8;
edgeConverter422 = TMCJPEGDEC_converterYUV422toRGBA8edge;
secondRow422 = firstRow422 + mode422;
cbBlock422 = buffer + 132;
crBlock422 = buffer + 196;
work->pConverterFunc = converter422;
work->pConverterFuncEdge = edgeConverter422;
work->pConvRowPtrs[0] = firstRow422;
work->pConvRowPtrs[1] = secondRow422;
work->pConvRowPtrs[5] = cbBlock422;
work->pConvRowPtrs[6] = crBlock422;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEGDEC_converterYUV422toRGBA8;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV422toRGBA8edge;
secondRow = firstRow + mode;
cbBlock = buffer + 132;
crBlock = buffer + 196;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 16;
work->converterFlags = 0;
break;
}
case 2: {
mode420 = work->idctMode;
firstRow420 = buffer + 4;
converter420 = TMCJPEGDEC_converterYUV420toRGBA8;
edgeConverter420 = TMCJPEGDEC_converterYUV420toRGBA8edge;
secondRow420 = firstRow420 + mode420;
thirdRow420 = firstRow420 + mode420 * 16;
fourthRow420 = thirdRow420 + mode420;
cbBlock420 = buffer + 260;
crBlock420 = buffer + 324;
work->pConverterFunc = converter420;
work->pConverterFuncEdge = edgeConverter420;
work->pConvRowPtrs[0] = firstRow420;
work->pConvRowPtrs[1] = secondRow420;
work->pConvRowPtrs[2] = thirdRow420;
work->pConvRowPtrs[3] = fourthRow420;
work->pConvRowPtrs[5] = cbBlock420;
work->pConvRowPtrs[6] = crBlock420;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* thirdRow;
u8* fourthRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEGDEC_converterYUV420toRGBA8;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV420toRGBA8edge;
secondRow = firstRow + mode;
thirdRow = firstRow + mode * 16;
fourthRow = thirdRow + mode;
cbBlock = buffer + 260;
crBlock = buffer + 324;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[2] = thirdRow;
work->pConvRowPtrs[3] = fourthRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 16;
work->converterFlags = 0;
break;
}
case 3: {
u32 mode;
u8* crBlock;
u8* cbBlock;
u8* secondRow;
u8 mode;
u8* firstRow;
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
u8* secondRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
converter = TMCJPEGDEC_converterYUV211toRGBA8;
edgeConverter = TMCJPEGDEC_converterYUV211toRGBA8edge;
work->pConverterFunc = TMCJPEGDEC_converterYUV211toRGBA8;
work->pConverterFuncEdge = TMCJPEGDEC_converterYUV211toRGBA8edge;
secondRow = firstRow + mode * 8;
cbBlock = buffer + 132;
crBlock = buffer + 196;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[5] = cbBlock;
@@ -142,27 +125,27 @@ s32 TMCJPEGDEC_set_converterRGBA8(TMCCJPEGDecWork* work) {
break;
}
case 4: {
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
TMCConverterFunc* edgeConverter;
converter = TMCJPEGDEC_converterYUV444toRGBA8;
edgeConverter = TMCJPEGDEC_converterYUV444toRGBA8edge;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = buffer + 4;
work->pConvRowPtrs[5] = buffer + 0x44;
work->pConvRowPtrs[6] = buffer + 0x84;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pitch = 0x08;
work->converterFlags = 0;
break;
}
case 5: {
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
TMCConverterFunc* edgeConverter;
converter = TMCJPEGDEC_converterYUV400toRGBA8;
edgeConverter = TMCJPEGDEC_converterYUV400toRGBA8edge;
work->pConvRowPtrs[0] = buffer + 4;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = buffer + 4;
work->pitch = 0x08;
work->converterFlags = 0;
break;
@@ -175,127 +158,129 @@ s32 TMCJPEGDEC_set_converterRGBA8(TMCCJPEGDecWork* work) {
{
s32 width = state->jpegWidth;
s32 height = state->jpegHeight;
s32 roundedWidth;
s32 heightPadding;
state->convWidth = ((u32)width / 4 + (width % 4 != 0)) * 4;
state->convHeight = ((u32)height / 4 + (height % 4 != 0)) * 4;
roundedWidth = (u32)width / 4 + (width % 4 != 0);
heightPadding = height % 4 != 0;
state->convWidth = roundedWidth * 4;
state->convHeight = ((u32)height / 4 + heightPadding) * 4;
}
return 0;
}
#pragma pop
static void TMCJPEGDEC_converterYUV411toRGBA8(TMCCJPEGDecWork* work, s32 x, s32 y) {
u16* output;
s32 tileRow;
s32 secondGreen;
s32 thirdGreen;
s32 fourthBlue;
s32 columnInTile;
s32 secondColumnInTile;
s32 thirdColumnInTile;
s32 fourthColumnInTile;
s32 red;
s32 secondBlue;
s32 thirdBlue;
s32 fourthGreen;
s32 green;
s32 secondRed;
s32 thirdRed;
s32 fourthRed;
u8* texture;
u8* luminance;
u8* cb;
u8* cr;
TMCCJPEGDecState* state;
u8* texture;
s32 height;
s32 column;
s32 xEnd;
s32 green;
s32 yEnd;
s32 tileWidth;
s32 redOffset;
s32 greenOffset;
s32 blueOffset;
s32 blue;
s32 value;
TMCCJPEGDecState* state;
s32 width;
s32 height;
s32 greenOffset;
s32 tileRow;
s32 lumaSkip;
s8 crValue;
s32 chromaSkip;
s32 width;
s32 cbValue;
u8 value;
s32 row;
u16* output;
s32 redOffset;
s32 blue;
luminance = work->convBuf + 4;
cb = &work->convBuf[260];
cr = &work->convBuf[324];
cb = work->convBuf + 260;
cr = work->convBuf + 324;
state = work->pState;
tileWidth = (state->convWidth >> 2) << 1;
texture = state->pTexBuffer;
width = 32 / state->scaleFactor;
height = 8 / state->scaleFactor;
xEnd = x + width;
yEnd = y + height;
for (; y < yEnd; y++) {
for (column = x; column < xEnd; column += 4) {
cbValue = (s8)*cb++;
crValue = (s8)*cr++;
redOffset = (crValue * 359) >> 8;
greenOffset = -(cbValue * 88 + crValue * 183) >> 8;
blueOffset = (cbValue * 454) >> 8;
value = *luminance++;
green = value + greenOffset;
red = value + redOffset;
blue = value + blueOffset;
if ((red | green | blue) >> 8) {
blue = blue > 255 ? 255 : blue < 0 ? 0 : blue;
green = green > 255 ? 255 : green < 0 ? 0 : green;
red = red > 255 ? 255 : red < 0 ? 0 : red;
{
yEnd = y + height;
xEnd = x + width;
lumaSkip = 32 - width;
chromaSkip = lumaSkip >> 2;
for (row = y; row < yEnd; row++) {
output = (u16*)(texture + ((row & 3) << 3));
tileRow = (row >> 2) * tileWidth;
for (column = x; column < xEnd; column += 4) {
{
cbValue = (s8)*cb++;
crValue = (s8)*cr++;
redOffset = (crValue * 359) >> 8;
greenOffset = -(crValue * 183 + cbValue * 88) >> 8;
blueOffset = (cbValue * 454) >> 8;
}
{
value = *luminance++;
green = value + greenOffset;
red = value + redOffset;
blue = value + blueOffset;
if ((red | green | blue) >> 8) {
blue = blue > 255 ? 255 : blue < 0 ? 0 : blue;
green = green > 255 ? 255 : green < 0 ? 0 : green;
red = red > 255 ? 255 : red < 0 ? 0 : red;
}
red = (u8)red + 0x10000 - 0x100;
output[(column & 3) + (((((column) >> 2) << 1) + tileRow) << 4)] = red;
output[(column & 3) + (((((column) >> 2) << 1) + tileRow + 1) << 4)] = ((green & 255) << 8) + (blue & 255);
}
{
value = *luminance++;
green = value + greenOffset;
red = value + redOffset;
blue = value + blueOffset;
if ((red | green | blue) >> 8) {
blue = blue > 255 ? 255 : blue < 0 ? 0 : blue;
green = green > 255 ? 255 : green < 0 ? 0 : green;
red = red > 255 ? 255 : red < 0 ? 0 : red;
}
red = (u8)red + 0x10000 - 0x100;
output[(column + 1 & 3) + (((((column + 1) >> 2) << 1) + tileRow) << 4)] = red;
output[(column + 1 & 3) + (((((column + 1) >> 2) << 1) + tileRow + 1) << 4)] = ((green & 255) << 8) + (blue & 255);
}
{
value = *luminance++;
green = value + greenOffset;
red = value + redOffset;
blue = value + blueOffset;
if ((red | green | blue) >> 8) {
blue = blue > 255 ? 255 : blue < 0 ? 0 : blue;
green = green > 255 ? 255 : green < 0 ? 0 : green;
red = red > 255 ? 255 : red < 0 ? 0 : red;
}
red = (u8)red + 0x10000 - 0x100;
output[(column + 2 & 3) + (((((column + 2) >> 2) << 1) + tileRow) << 4)] = red;
output[(column + 2 & 3) + (((((column + 2) >> 2) << 1) + tileRow + 1) << 4)] = ((green & 255) << 8) + (blue & 255);
}
{
value = *luminance++;
green = value + greenOffset;
red = value + redOffset;
blue = value + blueOffset;
if ((red | green | blue) >> 8) {
blue = blue > 255 ? 255 : blue < 0 ? 0 : blue;
green = green > 255 ? 255 : green < 0 ? 0 : green;
red = red > 255 ? 255 : red < 0 ? 0 : red;
}
red = (u8)red + 0x10000 - 0x100;
output[(column + 3 & 3) + (((((column + 3) >> 2) << 1) + tileRow) << 4)] = red;
output[(column + 3 & 3) + (((((column + 3) >> 2) << 1) + tileRow + 1) << 4)] = ((green & 255) << 8) + (blue & 255);
}
}
columnInTile = column & 3;
(output = (u16*)(texture + ((y & 3) << 3)))[
columnInTile + ((((column >> 2) << 1) +
(tileRow = (y >> 2) * tileWidth)) << 4)] = (u8)red + 0x10000 - 0x100;
output[columnInTile + ((((column >> 2) << 1) + (tileRow + 1)) << 4)] = ((green & 255) << 8) + (blue & 255);
value = *luminance++;
secondGreen = value + greenOffset;
secondRed = value + redOffset;
secondBlue = value + blueOffset;
if ((secondRed | secondGreen | secondBlue) >> 8) {
secondBlue = secondBlue > 255 ? 255 : secondBlue < 0 ? 0 : secondBlue;
secondGreen = secondGreen > 255 ? 255 : secondGreen < 0 ? 0 : secondGreen;
secondRed = secondRed > 255 ? 255 : secondRed < 0 ? 0 : secondRed;
}
secondColumnInTile = (column + 1) & 3;
output[secondColumnInTile + (((((column + 1) >> 2) << 1) + tileRow) << 4)] = (u8)secondRed + 0x10000 - 0x100;
output[secondColumnInTile + (((((column + 1) >> 2) << 1) + (tileRow + 1)) << 4)] = ((secondGreen & 255) << 8) + (secondBlue & 255);
value = *luminance++;
thirdGreen = value + greenOffset;
thirdRed = value + redOffset;
thirdBlue = value + blueOffset;
if ((thirdRed | thirdGreen | thirdBlue) >> 8) {
thirdBlue = thirdBlue > 255 ? 255 : thirdBlue < 0 ? 0 : thirdBlue;
thirdGreen = thirdGreen > 255 ? 255 : thirdGreen < 0 ? 0 : thirdGreen;
thirdRed = thirdRed > 255 ? 255 : thirdRed < 0 ? 0 : thirdRed;
}
thirdColumnInTile = (column + 2) & 3;
output[thirdColumnInTile + (((((column + 2) >> 2) << 1) + tileRow) << 4)] = (u8)thirdRed + 0x10000 - 0x100;
output[thirdColumnInTile + (((((column + 2) >> 2) << 1) + (tileRow + 1)) << 4)] = ((thirdGreen & 255) << 8) + (thirdBlue & 255);
value = *luminance++;
fourthGreen = value + greenOffset;
fourthRed = value + redOffset;
fourthBlue = value + blueOffset;
if ((fourthRed | fourthGreen | fourthBlue) >> 8) {
fourthBlue = fourthBlue > 255 ? 255 : fourthBlue < 0 ? 0 : fourthBlue;
fourthGreen = fourthGreen > 255 ? 255 : fourthGreen < 0 ? 0 : fourthGreen;
fourthRed = fourthRed > 255 ? 255 : fourthRed < 0 ? 0 : fourthRed;
}
fourthColumnInTile = (column + 3) & 3;
output[fourthColumnInTile + (((((column + 3) >> 2) << 1) + tileRow) << 4)] = (u8)fourthRed + 0x10000 - 0x100;
output[fourthColumnInTile + (((((column + 3) >> 2) << 1) + (tileRow + 1)) << 4)] = ((fourthGreen & 255) << 8) + (fourthBlue & 255);
luminance += lumaSkip;
cb += chromaSkip;
cr += chromaSkip;
}
luminance += (32 - width);
cb += ((32 - width) >> 2);
cr += ((32 - width) >> 2);
}
}

View File

@@ -14,37 +14,7 @@ static void TMCJPEG_814F32E4(TMCCJPEGDecWork*, s32, s32);
static void TMCJPEG_814F34A4(TMCCJPEGDecWork*, s32, s32);
static void TMCJPEG_814F372C(TMCCJPEGDecWork*, s32, s32);
#pragma push
#pragma optimization_level 1
s32 TMCJPEGDEC_set_converterY8U8V8(TMCCJPEGDecWork* work) {
u8 mode411;
u8* crBlock411;
u8* cbBlock411;
u8* fourthRow411;
u8* thirdRow411;
u8* secondRow411;
u8* firstRow411;
TMCConverterFunc* edgeConverter411;
TMCConverterFunc* converter411;
u8 mode422;
u8* crBlock422;
u8* cbBlock422;
u8* secondRow422;
u8* firstRow422;
TMCConverterFunc* edgeConverter422;
TMCConverterFunc* converter422;
u8 mode420;
u8* crBlock420;
u8* cbBlock420;
u8* fourthRow420;
u8* thirdRow420;
u8* secondRow420;
u8* firstRow420;
TMCConverterFunc* edgeConverter420;
TMCConverterFunc* converter420;
u8* buffer;
s32 componentCount;
TMCCJPEGDecState* state;
@@ -55,84 +25,97 @@ s32 TMCJPEGDEC_set_converterY8U8V8(TMCCJPEGDecWork* work) {
switch (componentCount) {
case 0: {
mode411 = work->idctMode;
firstRow411 = buffer + 4;
converter411 = TMCJPEG_814EFEAC;
edgeConverter411 = TMCJPEG_814F043C;
secondRow411 = firstRow411 + mode411;
thirdRow411 = secondRow411 + mode411;
fourthRow411 = thirdRow411 + mode411;
cbBlock411 = buffer + 260;
crBlock411 = buffer + 324;
work->pConverterFunc = converter411;
work->pConverterFuncEdge = edgeConverter411;
work->pConvRowPtrs[0] = firstRow411;
work->pConvRowPtrs[1] = secondRow411;
work->pConvRowPtrs[2] = thirdRow411;
work->pConvRowPtrs[3] = fourthRow411;
work->pConvRowPtrs[5] = cbBlock411;
work->pConvRowPtrs[6] = crBlock411;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* thirdRow;
u8* fourthRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEG_814EFEAC;
work->pConverterFuncEdge = TMCJPEG_814F043C;
secondRow = firstRow + mode;
thirdRow = secondRow + mode;
fourthRow = thirdRow + mode;
cbBlock = buffer + 260;
crBlock = buffer + 324;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[2] = thirdRow;
work->pConvRowPtrs[3] = fourthRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 32;
work->converterFlags = 0;
break;
}
case 1: {
mode422 = work->idctMode;
firstRow422 = buffer + 4;
converter422 = TMCJPEG_814F0A58;
edgeConverter422 = TMCJPEG_814F11C4;
secondRow422 = firstRow422 + mode422;
cbBlock422 = buffer + 132;
crBlock422 = buffer + 196;
work->pConverterFunc = converter422;
work->pConverterFuncEdge = edgeConverter422;
work->pConvRowPtrs[0] = firstRow422;
work->pConvRowPtrs[1] = secondRow422;
work->pConvRowPtrs[5] = cbBlock422;
work->pConvRowPtrs[6] = crBlock422;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEG_814F0A58;
work->pConverterFuncEdge = TMCJPEG_814F11C4;
secondRow = firstRow + mode;
cbBlock = buffer + 132;
crBlock = buffer + 196;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 16;
work->converterFlags = 0;
break;
}
case 2: {
mode420 = work->idctMode;
firstRow420 = buffer + 4;
converter420 = TMCJPEG_814F17E0;
edgeConverter420 = TMCJPEG_814F1F48;
secondRow420 = firstRow420 + mode420;
thirdRow420 = firstRow420 + mode420 * 16;
fourthRow420 = thirdRow420 + mode420;
cbBlock420 = buffer + 260;
crBlock420 = buffer + 324;
work->pConverterFunc = converter420;
work->pConverterFuncEdge = edgeConverter420;
work->pConvRowPtrs[0] = firstRow420;
work->pConvRowPtrs[1] = secondRow420;
work->pConvRowPtrs[2] = thirdRow420;
work->pConvRowPtrs[3] = fourthRow420;
work->pConvRowPtrs[5] = cbBlock420;
work->pConvRowPtrs[6] = crBlock420;
u8 mode;
u8* firstRow;
u8* secondRow;
u8* thirdRow;
u8* fourthRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
work->pConverterFunc = TMCJPEG_814F17E0;
work->pConverterFuncEdge = TMCJPEG_814F1F48;
secondRow = firstRow + mode;
thirdRow = firstRow + mode * 16;
fourthRow = thirdRow + mode;
cbBlock = buffer + 260;
crBlock = buffer + 324;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[2] = thirdRow;
work->pConvRowPtrs[3] = fourthRow;
work->pConvRowPtrs[5] = cbBlock;
work->pConvRowPtrs[6] = crBlock;
work->pitch = 16;
work->converterFlags = 0;
break;
}
case 3: {
u32 mode;
u8* crBlock;
u8* cbBlock;
u8* secondRow;
u8 mode;
u8* firstRow;
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
u8* secondRow;
u8* cbBlock;
u8* crBlock;
mode = work->idctMode;
firstRow = buffer + 4;
converter = TMCJPEG_814F2570;
edgeConverter = TMCJPEG_814F2B50;
work->pConverterFunc = TMCJPEG_814F2570;
work->pConverterFuncEdge = TMCJPEG_814F2B50;
secondRow = firstRow + mode * 8;
cbBlock = buffer + 132;
crBlock = buffer + 196;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = firstRow;
work->pConvRowPtrs[1] = secondRow;
work->pConvRowPtrs[5] = cbBlock;
@@ -142,27 +125,27 @@ s32 TMCJPEGDEC_set_converterY8U8V8(TMCCJPEGDecWork* work) {
break;
}
case 4: {
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
TMCConverterFunc* edgeConverter;
converter = TMCJPEG_814F3158;
edgeConverter = TMCJPEG_814F32E4;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = buffer + 4;
work->pConvRowPtrs[5] = buffer + 0x44;
work->pConvRowPtrs[6] = buffer + 0x84;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pitch = 0x08;
work->converterFlags = 0;
break;
}
case 5: {
TMCConverterFunc* edgeConverter;
TMCConverterFunc* converter;
TMCConverterFunc* edgeConverter;
converter = TMCJPEG_814F34A4;
edgeConverter = TMCJPEG_814F372C;
work->pConvRowPtrs[0] = buffer + 4;
work->pConverterFunc = converter;
work->pConverterFuncEdge = edgeConverter;
work->pConvRowPtrs[0] = buffer + 4;
work->pitch = 0x08;
work->converterFlags = 0;
break;
@@ -175,25 +158,16 @@ s32 TMCJPEGDEC_set_converterY8U8V8(TMCCJPEGDecWork* work) {
{
s32 width = state->jpegWidth;
s32 height = state->jpegHeight;
s32 roundedWidth;
s32 heightPadding;
roundedWidth = (u32)width / 8 + (width % 8 != 0);
heightPadding = height % 4 != 0;
state->convWidth = roundedWidth * 8;
state->convHeight = ((u32)height / 4 + heightPadding) * 4;
state->convWidth = ((u32)width / 8 + (width % 8 != 0)) * 8;
state->convHeight = ((u32)height / 4 + (height % 4 != 0)) * 4;
width = state->outputWidth;
height = state->outputHeight;
roundedWidth = (u32)width / 8 + (width % 8 != 0);
heightPadding = height % 4 != 0;
state->chromaWidth = roundedWidth * 8;
state->chromaHeight = ((u32)height / 4 + heightPadding) * 4;
state->chromaWidth = ((u32)width / 8 + (width % 8 != 0)) * 8;
state->chromaHeight = ((u32)height / 4 + (height % 4 != 0)) * 4;
}
return 0;
}
#pragma pop
static void TMCJPEG_814EFEAC(TMCCJPEGDecWork* work, s32 x, s32 y) {
s32 rowSkip;
u8* output;

View File

@@ -113,16 +113,18 @@ ziU32 Zi8SecMatchChar(ziU8* nodeAddress, ziU8* dictionaryAddress, ziMatchParam*
ziU16 matchCode;
ziU8* data;
ziU8 value;
ziU16 targetCode;
ziU8 dataIndex;
ziU8 remaining;
struct {
ziU8 remaining;
ziU8 dataIndex;
ziU16 targetCode;
} state;
if (match->componentIndex != 0) {
targetCode = match->componentIndex;
state.targetCode = match->componentIndex;
matchCode = ((ziU16)(nodeAddress[4] & 3) << 8) | nodeAddress[5];
value = 0;
while (value++ < 6) {
if (targetCode == matchCode) {
if (state.targetCode == matchCode) {
break;
}
matchCode = ((ziU16)(*(dictionaryAddress + matchCode * 8 + 6) & 3) << 8) | *(dictionaryAddress + matchCode * 8 + 7);
@@ -130,7 +132,7 @@ ziU32 Zi8SecMatchChar(ziU8* nodeAddress, ziU8* dictionaryAddress, ziMatchParam*
break;
}
}
if (targetCode != matchCode) {
if (state.targetCode != matchCode) {
return 0;
}
}
@@ -204,9 +206,9 @@ ziU32 Zi8SecMatchChar(ziU8* nodeAddress, ziU8* dictionaryAddress, ziMatchParam*
}
}
dataIndex = 4;
remaining = ((match->length + 1) >> 1) - 4;
if ((value + 1) < remaining) {
state.dataIndex = 4;
state.remaining = ((match->length + 1) >> 1) - 4;
if ((value + 1) < state.remaining) {
return 0;
}
if ((match->length & 1) != 0) {
@@ -219,12 +221,12 @@ ziU32 Zi8SecMatchChar(ziU8* nodeAddress, ziU8* dictionaryAddress, ziMatchParam*
}
}
if (match->count == 0) {
while (remaining != 0) {
if ((data[0] & match->recordMasks[dataIndex]) != match->recordValues[dataIndex]) {
while (state.remaining != 0) {
if ((data[0] & match->recordMasks[state.dataIndex]) != match->recordValues[state.dataIndex]) {
return 0;
}
dataIndex++;
remaining--;
state.dataIndex++;
state.remaining--;
data++;
}
}
@@ -288,15 +290,17 @@ extern ziU16 Zi8MatchAltSound(ziPtr soundTable, ziU16 soundCode, ziPtr pCodeTabl
ziU16 Zi8GetPCode(ziU8* table, ziU8* node);
ziBool Zi8MatchPhonetic(ziU8* pCodeTable, ziU8* dictionary, ziPtr soundTable, ziU16 soundCode, ziU32 tableAddress, ziU8* node, ziU16* masks, ziU16* values, ziU16* count, ziU8** resultNode, ziU8** stringOffset, ziU8 partialMode, ziU8 strictMode, ziU8 numParts, ziU16 partMask, ziU16 partValue, ziU8 flag, ziU8 altMode, ziU16 initialCode, ziU16* resultCode, ziU8 lastMode ZI_NEED_WORK) {
ziU16 code;
ziU16 remaining;
ziU16 soundIndex;
ziU16 dictionaryIndex;
ziU8 matchedParts;
ziU8 nextCode;
ziU8 partCount;
ziU8 partIndex;
ziBool hasString;
struct {
ziBool hasString;
ziU8 partIndex;
ziU8 partCount;
ziU8 nextCode;
ziU8 matchedParts;
ziU16 dictionaryIndex;
ziU16 soundIndex;
ziU16 remaining;
ziU16 code;
} traversal;
ziU8* sound;
typedef struct {
ziU8 header;
@@ -304,42 +308,42 @@ ziBool Zi8MatchPhonetic(ziU8* pCodeTable, ziU8* dictionary, ziPtr soundTable, zi
} DictionaryNode;
if (*stringOffset != 0) {
hasString = 1;
traversal.hasString = 1;
} else {
hasString = 0;
traversal.hasString = 0;
}
if (*count != 0) {
remaining = *count;
traversal.remaining = *count;
} else {
remaining = 1;
traversal.remaining = 1;
}
matchedParts = 0;
traversal.matchedParts = 0;
if ((lastMode != 0) && (numParts > 1)) {
altMode = 1;
}
while (remaining-- != 0) {
while (traversal.remaining-- != 0) {
if ((node[0] & flag) != 0) goto decode_node;
next_node:
node += 0xC;
continue;
decode_node:
code = Zi8GetPCode(pCodeTable, node);
if ((*values != (code & *masks)) && (altMode == 0) && ((node[0] & 0x80) != 0)) {
traversal.code = Zi8GetPCode(pCodeTable, node);
if ((*values != (traversal.code & *masks)) && (altMode == 0) && ((node[0] & 0x80) != 0)) {
if (*count != 0) {
soundIndex = (initialCode - remaining) - 1;
traversal.soundIndex = (initialCode - traversal.remaining) - 1;
} else {
soundIndex = initialCode;
traversal.soundIndex = initialCode;
}
code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, soundIndex, *masks, *values, flag, ZI_WORK);
traversal.code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, traversal.soundIndex, *masks, *values, flag, ZI_WORK);
}
goto check_code;
match_code:
if (partValue == (code & partMask)) goto next_node;
matchedParts = 1;
if (partValue == (traversal.code & partMask)) goto next_node;
traversal.matchedParts = 1;
if (*count != 0) {
soundIndex = (initialCode - remaining) - 1;
traversal.soundIndex = (initialCode - traversal.remaining) - 1;
} else {
soundIndex = initialCode;
traversal.soundIndex = initialCode;
}
sound = (ziU8*)(tableAddress + ((node[9] & 0xF) * 0x10000 + (node[0xB] + node[0xA] * 0x100)));
if (ZI_WORK->cangjieEnabled != 0) {
@@ -364,46 +368,46 @@ match_code:
} else if (numParts > 1) {
goto next_node;
}
if (((ziU8)matchedParts == numParts) || (numParts == 0)) {
if (((ziU8)traversal.matchedParts == numParts) || (numParts == 0)) {
*resultNode = node;
*resultCode = ((ziU16)node[6] << 8) + node[7];
*count = remaining;
*count = traversal.remaining;
return 1;
}
next_group:
{
nextCode = *sound++;
partCount = nextCode & 0xF;
if ((nextCode & flag) == 0) {
for (; partCount != 0; partCount--) {
traversal.nextCode = *sound++;
traversal.partCount = traversal.nextCode & 0xF;
if ((traversal.nextCode & flag) == 0) {
for (; traversal.partCount != 0; traversal.partCount--) {
for (sound++; (*sound & 0x80) == 0; sound += 2) {
}
sound++;
}
}
for (; partCount != 0; partCount--) {
partIndex = 1;
if (hasString && (sound > *stringOffset)) {
hasString = 0;
for (; traversal.partCount != 0; traversal.partCount--) {
traversal.partIndex = 1;
if (traversal.hasString && (sound > *stringOffset)) {
traversal.hasString = 0;
}
if (!hasString) {
if (!traversal.hasString) {
*stringOffset = sound;
}
do {
dictionaryIndex = sound[0] | ((ziU16)sound[1] << 8);
traversal.dictionaryIndex = sound[0] | ((ziU16)sound[1] << 8);
sound += 2;
if (hasString) {
if (traversal.hasString) {
goto phonetic_skip;
}
code = Zi8GetPCode(pCodeTable, dictionary + (dictionaryIndex & 0x7FFF) * sizeof(DictionaryNode));
if (((code & masks[partIndex]) != values[partIndex]) && (altMode == 0) && (dictionary[(dictionaryIndex & 0x7FFF) * sizeof(DictionaryNode)] & 0x80) != 0) {
code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, dictionaryIndex & 0x7FFF, masks[partIndex], values[partIndex], flag, ZI_WORK);
traversal.code = Zi8GetPCode(pCodeTable, dictionary + (traversal.dictionaryIndex & 0x7FFF) * sizeof(DictionaryNode));
if (((traversal.code & masks[traversal.partIndex]) != values[traversal.partIndex]) && (altMode == 0) && (dictionary[(traversal.dictionaryIndex & 0x7FFF) * sizeof(DictionaryNode)] & 0x80) != 0) {
traversal.code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, traversal.dictionaryIndex & 0x7FFF, masks[traversal.partIndex], values[traversal.partIndex], flag, ZI_WORK);
}
if ((code & masks[partIndex]) == values[partIndex]) {
if ((traversal.code & masks[traversal.partIndex]) == values[traversal.partIndex]) {
goto phonetic_matched;
}
phonetic_skip:
if ((dictionaryIndex & 0x8000) == 0) {
if ((traversal.dictionaryIndex & 0x8000) == 0) {
sound++;
while ((*sound & 0x80) == 0) {
sound += 2;
@@ -412,23 +416,23 @@ phonetic_skip:
}
break;
phonetic_matched:
if (++partIndex == numParts) {
if (++traversal.partIndex == numParts) {
if (partialMode != 0) {
if (strictMode == 0 && (dictionaryIndex & 0x8000) != 0) goto phonetic_skip;
if (strictMode != 0 && (dictionaryIndex & 0x8000) == 0) goto phonetic_skip;
if (strictMode == 0 && (traversal.dictionaryIndex & 0x8000) != 0) goto phonetic_skip;
if (strictMode != 0 && (traversal.dictionaryIndex & 0x8000) == 0) goto phonetic_skip;
}
*resultNode = node;
*resultCode = ((ziU16)node[6] << 8) + node[7];
*count = remaining;
*count = traversal.remaining;
return 1;
}
} while ((dictionaryIndex & 0x8000) == 0);
} while ((traversal.dictionaryIndex & 0x8000) == 0);
}
}
if ((nextCode & 0x80) != 0) goto next_node;
if ((traversal.nextCode & 0x80) != 0) goto next_node;
goto next_group;
check_code:
if (*values == (code & *masks)) goto match_code;
if (*values == (traversal.code & *masks)) goto match_code;
goto next_node;
}
return 0;

View File

@@ -27,29 +27,31 @@ ziU8 Zi8MatchKoreanSequence(ziU16* resultIndex, ziU16* input, ziU8 type, ziU16 c
ziU32 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument,
struct __zi8_work_data_s* workData) {
ziU8* table1;
ziU8* table2;
ziU8* table31;
ziU16 tableCount0;
ziU16 tableCount3;
ziU16 tableCount6;
ziU16 tableCount31;
ziU16 nextIndex;
ziU16 inputIndex;
ziU16 currentCandidate;
ziU16 index;
ziU8 elementIndex;
ziU8 matched;
ziU8 characterIndex;
struct {
ziU8 characterIndex;
ziU8 matched;
ziU8 elementIndex;
ziU16 index;
ziU16 currentCandidate;
ziU16 inputIndex;
ziU16 nextIndex;
ziU16 tableCount31;
ziU16 tableCount6;
ziU16 tableCount3;
ziU16 tableCount0;
ziU8* table31;
ziU8* table2;
ziU8* table1;
} state;
ziU16 buffer[100];
ziU8 result;
ziU16 currentCharacter;
ziU8* selectedTable;
nextIndex = 0;
state.nextIndex = 0;
result = 0;
characterIndex = 0xFF;
currentCandidate = params->firstCandidate;
state.characterIndex = 0xFF;
state.currentCandidate = params->firstCandidate;
params->letters = params->completion = params->count = 0;
if ((argument != 0) && (*argument != 0)) {
Zi8LogError(0x7D0, workData);
@@ -61,31 +63,31 @@ ziU32 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument,
}
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 4, workData);
table1 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 1, workData);
table2 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 2, workData);
table31 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x31, workData);
tableCount0 = Zi8GetTableCount(ZI8_LANG_KO, 0, workData);
tableCount3 = Zi8GetTableCount(ZI8_LANG_KO, 3, workData);
tableCount6 = Zi8GetTableCount(ZI8_LANG_KO, 6, workData);
tableCount31 = Zi8GetTableCount(ZI8_LANG_KO, 0x31, workData);
state.table1 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 1, workData);
state.table2 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 2, workData);
state.table31 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x31, workData);
state.tableCount0 = Zi8GetTableCount(ZI8_LANG_KO, 0, workData);
state.tableCount3 = Zi8GetTableCount(ZI8_LANG_KO, 3, workData);
state.tableCount6 = Zi8GetTableCount(ZI8_LANG_KO, 6, workData);
state.tableCount31 = Zi8GetTableCount(ZI8_LANG_KO, 0x31, workData);
for (elementIndex = 0; elementIndex < params->elementCount;
elementIndex++) {
currentCharacter = params->elements[elementIndex];
for (state.elementIndex = 0; state.elementIndex < params->elementCount;
state.elementIndex++) {
currentCharacter = params->elements[state.elementIndex];
if ((currentCharacter >= 0x61) && (currentCharacter <= 0x7A)) {
buffer[elementIndex] = table1[(currentCharacter - 0x61) * 2];
buffer[state.elementIndex] = state.table1[(currentCharacter - 0x61) * 2];
} else if ((currentCharacter >= 0x41) && (currentCharacter <= 0x5A)) {
buffer[elementIndex] = (table1 + (currentCharacter - 0x41) * 2)[1];
buffer[state.elementIndex] = (state.table1 + (currentCharacter - 0x41) * 2)[1];
} else {
matched = 0;
for (; table2[matched * 3] != 0; matched++) {
if (currentCharacter == table2[matched * 3]) break;
state.matched = 0;
for (; state.table2[state.matched * 3] != 0; state.matched++) {
if (currentCharacter == state.table2[state.matched * 3]) break;
}
if (table2[matched * 3] != 0) {
buffer[elementIndex] =
((ziU16)(table2 + matched * 3)[1] << 8) |
(table2 + matched * 3)[2];
if (state.table2[state.matched * 3] != 0) {
buffer[state.elementIndex] =
((ziU16)(state.table2 + state.matched * 3)[1] << 8) |
(state.table2 + state.matched * 3)[2];
} else {
Zi8LogError(0x161, workData);
return 0;
@@ -94,16 +96,16 @@ ziU32 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument,
}
result = 0;
for (currentCharacter = 0; currentCharacter < elementIndex; currentCharacter++) {
if (Zi8LookupKoreanChar(buffer[currentCharacter], &characterIndex,
&inputIndex, workData) != 0) {
matched = Zi8MatchKoreanSequence(&nextIndex,
for (currentCharacter = 0; currentCharacter < state.elementIndex; currentCharacter++) {
if (Zi8LookupKoreanChar(buffer[currentCharacter], &state.characterIndex,
&state.inputIndex, workData) != 0) {
state.matched = Zi8MatchKoreanSequence(&state.nextIndex,
buffer + currentCharacter + 1,
characterIndex,
(elementIndex - currentCharacter) - 1,
state.characterIndex,
(state.elementIndex - currentCharacter) - 1,
workData);
if (workData->koAltTables == 1) {
switch (characterIndex) {
switch (state.characterIndex) {
case 1:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1E, workData);
break;
@@ -166,59 +168,59 @@ ziU32 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument,
}
}
} else {
matched = 0;
state.matched = 0;
}
if (matched != 0) {
if (tableCount6 == 0) {
nextIndex += inputIndex * tableCount3;
if (state.matched != 0) {
if (state.tableCount6 == 0) {
state.nextIndex += state.inputIndex * state.tableCount3;
}
if (currentCandidate != 0) {
currentCandidate--;
if (state.currentCandidate != 0) {
state.currentCandidate--;
} else {
params->candidates[result] =
((ziU16)selectedTable[nextIndex * 2] << 8) | (selectedTable + nextIndex * 2)[1];
if ((tableCount6 != 0) && (workData->koAltTables == 0)) {
params->candidates[result] += inputIndex * tableCount3;
((ziU16)selectedTable[state.nextIndex * 2] << 8) | (selectedTable + state.nextIndex * 2)[1];
if ((state.tableCount6 != 0) && (workData->koAltTables == 0)) {
params->candidates[result] += state.inputIndex * state.tableCount3;
}
result++;
}
if (currentCharacter == 0) {
params->completion = matched + 1;
params->completion = state.matched + 1;
}
currentCharacter += matched;
currentCharacter += state.matched;
} else {
if (currentCandidate != 0) {
index = 0;
for (; index < tableCount31; index++) {
if (table31[index * 3] == buffer[currentCharacter] &&
(table31 + index * 3)[1] == buffer[currentCharacter + 1]) break;
if (state.currentCandidate != 0) {
state.index = 0;
for (; state.index < state.tableCount31; state.index++) {
if (state.table31[state.index * 3] == buffer[currentCharacter] &&
(state.table31 + state.index * 3)[1] == buffer[currentCharacter + 1]) break;
}
if (index == tableCount31) {
currentCandidate--;
if (state.index == state.tableCount31) {
state.currentCandidate--;
}
if (currentCharacter == 0) {
params->completion = 1;
}
} else {
for (index = 0; index < tableCount31; index++) {
if ((table31[(index * 3)] == buffer[currentCharacter]) &&
((table31 + index * 3)[1] == buffer[currentCharacter + 1])) {
for (state.index = 0; state.index < state.tableCount31; state.index++) {
if ((state.table31[(state.index * 3)] == buffer[currentCharacter]) &&
((state.table31 + state.index * 3)[1] == buffer[currentCharacter + 1])) {
if (currentCharacter == 0) {
params->completion = 1;
}
params->candidates[result] =
tableCount0 + (table31 + index * 3)[2];
state.tableCount0 + (state.table31 + state.index * 3)[2];
result++;
currentCharacter++;
break;
}
}
if (index == tableCount31) {
if (state.index == state.tableCount31) {
if ((params->candidates[result] = buffer[currentCharacter]) < 0xFF) {
if (currentCharacter == 0) {
params->completion = 1;
}
params->candidates[result] += tableCount0;
params->candidates[result] += state.tableCount0;
result++;
}
}

View File

@@ -72,7 +72,7 @@ struct DVDCommandBlock {
DVDCommandBlock* prev; // 0x04
u32 command; // 0x08
s32 state; // 0x0C
volatile s32 state;
u32 offset; // 0x10
u32 length; // 0x14

View File

@@ -14,7 +14,7 @@ typedef GXTlutRegion* (*GXTlutRegionCallback)(u32 idx);
u32 GXGetTexBufferSize(u16 width, u16 height, u32 format, u8 mipmap, u8 max_lod);
void GXInitTexObj(GXTexObj* obj, void* image_ptr, u16 width, u16 height, GXTexFmt format, GXTexWrapMode wrap_s, GXTexWrapMode wrap_t,
void GXInitTexObj(const GXTexObj* obj, void* image_ptr, u16 width, u16 height, GXTexFmt format, GXTexWrapMode wrap_s, GXTexWrapMode wrap_t,
u8 mipmap);
void GXInitTexObjCI(GXTexObj* obj, void* image_ptr, u16 width, u16 height, GXCITexFmt format, GXTexWrapMode wrap_s, GXTexWrapMode wrap_t, u8 mipmap,
u32 tlut_name);

View File

@@ -31,6 +31,8 @@ char scCntCacheSpaceNl[3] = {0x20, 0x0a, 0x00};
extern void _savegpr_23();
extern void _restgpr_23();
extern void _savegpr_26();
extern void _restgpr_26();
OSMutex _CNTCACHEMutex;
long long _CNTCACHEUnused816997A8;
@@ -261,102 +263,254 @@ void _CNTCACHEDeleteTitle() {
}
}
static s32 GetSaveDataUsage(ESTitleId titleId) {
s32 ret = -1;
char nandPath[64] ALIGN32;
u32 usedBlocks = 1;
u32 usedINodes = 1;
snprintf(nandPath, (int)sizeof(nandPath), scCntCacheTitleDataFmt, NANDTitleIdHi(titleId), NANDTitleIdLo(titleId));
ret = NANDSecretGetUsage(nandPath, &usedBlocks, &usedINodes);
if (ret == NAND_RESULT_NOEXISTS) {
ret = 2;
} else if (ret >= NAND_RESULT_OK) {
if (usedINodes == 1 && usedBlocks == 0) {
ret = 1;
} else {
ret = 0;
}
}
return ret;
asm int _CNTCACHEIsTitleRemovable(ESTitleId titleId) {
clrlwi r11, r1, 0x1b
mr r12, r1
subfic r11, r11, -0x2100
stwux r1, r1, r11
mflr r0
lis r5, scCntCacheTitleDataFmt@ha
stw r0, 4(r12)
li r0, 1
addi r5, r5, scCntCacheTitleDataFmt@l
stw r31, -4(r12)
stw r30, -8(r12)
mr r30, r3
addi r3, r1, 0x40
stw r29, -0xc(r12)
mr r29, r4
li r4, -1
stw r0, 0x20(r1)
and r6, r30, r4
and r7, r29, r4
li r4, 0x40
stw r0, 0x24(r1)
crclr 4*cr1+eq
bl snprintf
addi r3, r1, 0x40
addi r4, r1, 0x20
addi r5, r1, 0x24
bl NANDSecretGetUsage
cmpwi r3, -0xc
mr r4, r3
bne L_418
li r4, 2
b L_444
L_418:
cmpwi r3, 0
blt L_444
lwz r0, 0x24(r1)
cmplwi r0, 1
bne L_440
lwz r0, 0x20(r1)
cmpwi r0, 0
bne L_440
li r4, 1
b L_444
L_440:
li r4, 0
L_444:
cmpwi r4, 1
bne L_4bc
mr r4, r29
mr r3, r30
addi r31, r1, 0x80
addi r6, r1, 0x28
li r5, 0
bl ES_GetTmdView
cmpwi r3, 0
beq L_470
b L_4c0
L_470:
lwz r0, 0x28(r1)
cmplwi r0, 0x2060
ble L_484
li r3, -0x400
b L_4c0
L_484:
mr r4, r29
mr r3, r30
mr r5, r31
addi r6, r1, 0x28
bl ES_GetTmdView
cmpwi r3, 0
beq L_4a4
b L_4c0
L_4a4:
lhz r0, 0xd8(r1)
rlwinm. r0, r0, 0x18, 0x18, 0x1f
bne L_4b8
li r4, 1
b L_4bc
L_4b8:
li r4, 0
L_4bc:
mr r3, r4
L_4c0:
lwz r10, 0(r1)
lwz r0, 4(r10)
lwz r31, -4(r10)
lwz r30, -8(r10)
lwz r29, -0xc(r10)
mtlr r0
mr r1, r10
blr
}
BOOL _CNTCACHEIsTitleRemovable(ESTitleId titleId) {
u8 tmdBuf[OSRoundUp32B(sizeof(ESTmdView))] ALIGN32;
u32 tmdSize;
ESTmdView* tmd;
s32 ret;
ret = GetSaveDataUsage(titleId);
if (ret == 1) {
tmd = (ESTmdView*)tmdBuf;
ret = ES_GetTmdView(titleId, NULL, &tmdSize);
if (ret != ES_ERR_OK) {
return ret;
}
if (tmdSize > sizeof(tmdBuf)) {
return ES_ERR_MEMORY_ERROR;
}
ret = ES_GetTmdView(titleId, tmd, &tmdSize);
if (ret != ES_ERR_OK) {
return ret;
}
if (((tmd->head.titleVersion >> 8) & 0xFF) == 0) {
ret = 1;
} else {
ret = 0;
}
}
return ret;
}
void _CNTCACHEDeleteContent() {
u8 buf[OSRoundUp32B(sizeof(ESTmdView))] ALIGN32;
u32 numOnCard;
u32 size;
ESTitleId titleId;
ESTmdView* tmd;
ESError result;
char* token;
token = strtok(NULL, scCntCacheSpaceNl);
errno = 0;
titleId = strtoull(token, NULL, 16);
if (errno == 0 && NANDTitleIdHi(titleId) == 0x00010005) {
tmd = (ESTmdView*)buf;
result = ES_GetTmdView(titleId, NULL, &size);
if (result == ES_ERR_DONT_EXISTS) {
return;
}
if (result == ES_ERR_OK && ES_GetTmdView(titleId, tmd, &size) == ES_ERR_OK) {
if ((tmd->head.titleType & 8) && (tmd->head.titleType & 0x10)) {
token = strtok(NULL, scCntCacheSpaceNl);
while (token) {
u32 index;
u32 i;
errno = 0;
index = strtoul(token, NULL, 10);
if (errno == 0 && index <= 510) {
for (i = 0; i < tmd->head.numContents; i++) {
if (index == tmd->contents[i].index) {
if (!(tmd->contents[i].type & 0x8000) &&
ES_DeleteContent(titleId, tmd->contents[i].cid) == ES_ERR_OK &&
ES_ListTitleContentsOnCard(titleId, NULL, &numOnCard) == ES_ERR_OK &&
numOnCard == 0 && GetSaveDataUsage(titleId) == 1) {
ES_DeleteTitle(titleId);
}
break;
}
}
}
token = strtok(NULL, scCntCacheSpaceNl);
}
}
memset(buf, 0, OSRoundUp32B(size));
}
}
asm void _CNTCACHEDeleteContent() {
clrlwi r11, r1, 0x1b
mr r12, r1
subfic r11, r11, -0x2100
stwux r1, r1, r11
mflr r0
mr r11, r12
stw r0, 4(r12)
bl _savegpr_26
li r3, 0
la r4, scCntCacheSpaceNl
bl strtok
li r31, 0
li r4, 0
stw r31, errno(r0)
li r5, 0x10
bl strtoull
lwz r0, errno(r0)
mr r29, r4
mr r30, r3
cmpwi r0, 0
bne L_708
li r0, -1
and r5, r3, r0
addis r0, r5, -1
cmplwi r0, 5
bne L_708
addi r28, r1, 0x80
addi r6, r1, 0x28
li r5, 0
bl ES_GetTmdView
cmpwi r3, -0x6a
beq L_708
cmpwi r3, 0
bne L_708
mr r4, r29
mr r3, r30
mr r5, r28
addi r6, r1, 0x28
bl ES_GetTmdView
cmpwi r3, 0
bne L_708
lwz r3, 0x94(r1)
rlwinm. r0, r3, 0, 0x1c, 0x1c
beq L_6f0
rlwinm. r0, r3, 0, 0x1b, 0x1b
beq L_6f0
li r3, 0
la r4, scCntCacheSpaceNl
bl strtok
li r26, 1
lis r27, scCntCacheTitleDataFmt@ha
b L_6e8
L_5b0:
stw r31, errno(r0)
li r4, 0
li r5, 0xa
bl strtoul
lwz r0, errno(r0)
cmpwi r0, 0
bne L_6dc
cmplwi r3, 0x1fe
bgt L_6dc
lhz r0, 0xda(r1)
li r4, 0
mtctr r0
cmplwi r0, 0
ble L_6dc
L_5e8:
add r5, r28, r4
lhz r0, 0x60(r5)
cmplw r3, r0
bne L_6d4
lhz r0, 0x62(r5)
rlwinm. r0, r0, 0, 0x10, 0x10
bne L_6dc
lwz r5, 0x5c(r5)
mr r4, r29
mr r3, r30
bl ES_DeleteContent
cmpwi r3, 0
bne L_6dc
mr r4, r29
mr r3, r30
addi r6, r1, 0x2c
li r5, 0
bl ES_ListTitleContentsOnCard
cmpwi r3, 0
bne L_6dc
lwz r0, 0x2c(r1)
cmpwi r0, 0
bne L_6dc
li r0, -1
stw r26, 0x20(r1)
addi r3, r1, 0x40
addi r5, r27, scCntCacheTitleDataFmt@l
stw r26, 0x24(r1)
and r6, r30, r0
and r7, r29, r0
li r4, 0x40
crclr 4*cr1+eq
bl snprintf
addi r3, r1, 0x40
addi r4, r1, 0x20
addi r5, r1, 0x24
bl NANDSecretGetUsage
cmpwi r3, -0xc
mr r0, r3
bne L_690
li r0, 2
b L_6bc
L_690:
cmpwi r3, 0
blt L_6bc
lwz r0, 0x24(r1)
cmplwi r0, 1
bne L_6b8
lwz r0, 0x20(r1)
cmpwi r0, 0
bne L_6b8
li r0, 1
b L_6bc
L_6b8:
li r0, 0
L_6bc:
cmpwi r0, 1
bne L_6dc
mr r4, r29
mr r3, r30
bl ES_DeleteTitle
b L_6dc
L_6d4:
addi r4, r4, 0x10
bdnz L_5e8
L_6dc:
li r3, 0
la r4, scCntCacheSpaceNl
bl strtok
L_6e8:
cmpwi r3, 0
bne L_5b0
L_6f0:
lwz r5, 0x28(r1)
addi r3, r1, 0x80
li r4, 0
addi r0, r5, 0x1f
rlwinm r5, r0, 0, 0, 0x1a
bl memset
L_708:
lwz r10, 0(r1)
mr r11, r10
bl _restgpr_26
lwz r0, 4(r10)
mtlr r0
mr r1, r10
blr
}

View File

@@ -1894,7 +1894,7 @@ s32 DVDGetCommandBlockStatus(const DVDCommandBlock* block) {
if (block->state == DVD_STATE_COVER_CLOSED) {
retVal = DVD_STATE_BUSY;
} else if (((volatile DVDCommandBlock*)block)->state == DVD_STATE_COVER_OPENED) {
} else if (block->state == DVD_STATE_COVER_OPENED) {
retVal = DVD_STATE_NO_DISK;
} else if (executing == &__DVDStopMotorCommandBlock) {
next = __DVDGetNextWaitingQueue();
@@ -1912,7 +1912,7 @@ s32 DVDGetCommandBlockStatus(const DVDCommandBlock* block) {
}
}
} else {
retVal = ((volatile DVDCommandBlock*)block)->state;
retVal = block->state;
}
OSRestoreInterrupts(enabled);

View File

@@ -29,13 +29,13 @@ typedef struct PFD_SDDRV_FORMAT_DATA {
u32 total_sectors;
} PFD_SDDRV_FORMAT_DATA;
volatile PFD_SDDRV_INFO g_pfd_sddrv_info;
PFD_SDDEV_STORAGE g_pfd_sddev ATTRIBUTE_ALIGN(32);
PFD_SDDRV_INFO g_pfd_sddrv_info;
PFD_SDDEV_STORAGE g_pfd_sddev;
u8 g_pfd_sddrv_buf[0x200];
static FAInsertCallback g_attach_func = 0;
static FAEjectCallback g_detach_func = 0;
u32 g_event ATTRIBUTE_ALIGN(32);
u32 g_event;
extern u8 pfd_get_media_drv_char(FADisk*, s8*, u32);
extern void pdm_disk_notify_media_insert(FADisk*);
@@ -243,23 +243,39 @@ static inline void clear_mount_flag(void) {
g_pfd_sddrv_info.flags &= ~2;
}
static inline u32 pfd_sddrv_flags(const PFD_SDDRV_INFO* info) {
return info->flags;
}
static inline SDDev* pfd_sddrv_device(const PFD_SDDRV_INFO* info) {
return info->device;
}
static inline FADisk* pfd_sddrv_disk(const PFD_SDDRV_INFO* info) {
return info->disk;
}
static inline s8 pfd_sddrv_drive(const PFD_SDDRV_INFO* info) {
return info->drive;
}
s32 pfd_st_inter_callback(s32 status, void* data) {
s32 result;
if ((status & 1) != 1) {
return 0;
}
if (g_pfd_sddrv_info.device != 0) {
if (pfd_sddrv_device(&g_pfd_sddrv_info) != 0) {
g_event = 2;
result = ISD_RegisterDeviceIntrHandler(g_pfd_sddrv_info.device, (SDDevIntrCallback)pfd_st_removal_callback, &g_event);
if (result != 0) {
OSReport("ERR:Failed to regist intr handler. pfd_st_inter_callback()\n");
}
}
if (g_pfd_sddrv_info.disk != 0) {
if (pfd_sddrv_disk(&g_pfd_sddrv_info) != 0) {
update_media_drive();
pdm_disk_notify_media_insert(g_pfd_sddrv_info.disk);
if (g_pfd_sddrv_info.drive != 0 && g_attach_func != 0) {
if (pfd_sddrv_drive(&g_pfd_sddrv_info) != 0 && g_attach_func != 0) {
g_attach_func(g_pfd_sddrv_info.drive);
}
}
@@ -275,39 +291,36 @@ s32 pfd_st_removal_callback(s32 status, void* data) {
return 0;
}
g_pfd_sddrv_info.media_inserted = 0;
if (g_pfd_sddrv_info.device != 0) {
if (g_pfd_sddrv_info.media_inserted == 0 && pfd_sddrv_device(&g_pfd_sddrv_info) != 0) {
g_event = 1;
result = ISD_RegisterDeviceIntrHandler(g_pfd_sddrv_info.device, (SDDevIntrCallback)pfd_st_inter_callback, &g_event);
if (result != 0) {
OSReport("ERR:Failed to regist intr handler. pfd_st_removal_callback()\n");
}
}
if (g_pfd_sddrv_info.disk != 0) {
if (pfd_sddrv_disk(&g_pfd_sddrv_info) != 0) {
update_media_drive();
pdm_disk_notify_media_eject(g_pfd_sddrv_info.disk);
if (g_pfd_sddrv_info.drive != 0 && g_detach_func != 0) {
if (pfd_sddrv_drive(&g_pfd_sddrv_info) != 0 && g_detach_func != 0) {
g_detach_func(g_pfd_sddrv_info.drive);
}
}
return 0;
}
#pragma push
#pragma ppc_iro_level 0
s32 pfd_sddrv_init(FADisk* disk) {
s32 sd_result;
SDDev* device;
u32 status;
if (disk == NULL) {
if (disk == 0) {
return -30;
}
if ((g_pfd_sddrv_info.flags & 1) != 0) {
if ((pfd_sddrv_flags(&g_pfd_sddrv_info) & 1) != 0) {
OSReport("INFO SD Card driver is already initialize. pfd_sddrv_init()\n");
if (disk != g_pfd_sddrv_info.disk) {
return -44;
}
return 0;
} else {
if ((g_pfd_sddrv_info.flags & 4) == 0) {
g_pfd_sddrv_info.bytes_per_sector = 0x200;
@@ -359,7 +372,6 @@ s32 pfd_sddrv_init(FADisk* disk) {
}
return 0;
}
#pragma pop
s32 pfd_sddrv_mount(FADisk* disk) {
s32 result;
@@ -461,7 +473,7 @@ s32 pfd_sddrv_unmount(FADisk* disk) {
if (disk == 0) {
return -30;
}
if ((g_pfd_sddrv_info.flags & 2) != 0) {
if ((pfd_sddrv_flags(&g_pfd_sddrv_info) & 2) != 0) {
clear_mount_flag();
}
return 0;
@@ -473,7 +485,7 @@ s32 pfd_sddrv_finalize(FADisk* disk) {
if (disk == 0) {
return -30;
}
if ((g_pfd_sddrv_info.flags & 2) != 0) {
if ((pfd_sddrv_flags(&g_pfd_sddrv_info) & 2) != 0) {
clear_mount_flag();
}
if ((g_pfd_sddrv_info.flags & 1) != 0) {
@@ -1359,24 +1371,22 @@ s32 pfd_sddrv_store_fat32_bpb_buf(PFD_SDDRV_FORMAT_DATA* format_data, u8* sector
static s32 pfd_sddrv_store_fat32_reserved_buf(u8* sector_buffer) {
PFD_SDDRV_RESERVED_BOOT_SECTOR* reserved_boot_sector;
s32 result = -30;
pf_memset(sector_buffer, 0, 0x200);
reserved_boot_sector = (PFD_SDDRV_RESERVED_BOOT_SECTOR*)sector_buffer;
if (((u32)reserved_boot_sector->signature.bytes & 1) != 0) {
reserved_boot_sector->signature.bytes[0] = 0x55;
reserved_boot_sector->signature.bytes[1] = 0xaa;
} else {
reserved_boot_sector->signature.value = 0x55aa;
if (sector_buffer != 0) {
pf_memset(sector_buffer, 0, 0x200);
reserved_boot_sector = (PFD_SDDRV_RESERVED_BOOT_SECTOR*)sector_buffer;
if (((u32)reserved_boot_sector->signature.bytes & 1) != 0) {
reserved_boot_sector->signature.bytes[0] = 0x55;
reserved_boot_sector->signature.bytes[1] = 0xaa;
} else {
reserved_boot_sector->signature.value = 0x55aa;
}
result = 0;
}
return 0;
return result;
}
static inline s32 pfd_sddrv_write_sector(u32 sector) {
return ISD_WriteBlock(g_pfd_sddrv_info.device, sector, g_pfd_sddrv_buf, 1);
}
#pragma push
#pragma ppc_iro_level 0
s32 pfd_sddrv_build_fat32_mbr_bpb(u32 total_sectors) {
PFD_SDDRV_FORMAT_DATA format_data;
s32 result;
@@ -1398,12 +1408,12 @@ s32 pfd_sddrv_build_fat32_mbr_bpb(u32 total_sectors) {
if (g_pfd_sddrv_info.media_ejected != 0) {
return -33;
}
result = pfd_sddrv_write_sector(format_data.partition_start_sector);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, format_data.partition_start_sector, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write BPB fields. ISD_WriteBlock()\n");
return -36;
}
result = pfd_sddrv_write_sector(format_data.partition_start_sector + 6);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, format_data.partition_start_sector + 6, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write BPB fields. ISD_WriteBlock()\n");
return -36;
@@ -1419,12 +1429,12 @@ s32 pfd_sddrv_build_fat32_mbr_bpb(u32 total_sectors) {
if (g_pfd_sddrv_info.media_ejected != 0) {
return -33;
}
result = pfd_sddrv_write_sector(format_data.partition_start_sector + 1);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, format_data.partition_start_sector + 1, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write BPB fields. ISD_WriteBlock()\n");
return -36;
}
result = pfd_sddrv_write_sector(format_data.partition_start_sector + 7);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, format_data.partition_start_sector + 7, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write BPB fields. ISD_WriteBlock()\n");
return -36;
@@ -1441,12 +1451,12 @@ s32 pfd_sddrv_build_fat32_mbr_bpb(u32 total_sectors) {
if (g_pfd_sddrv_info.media_ejected != 0) {
return -33;
}
result = pfd_sddrv_write_sector(format_data.partition_start_sector + 2);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, format_data.partition_start_sector + 2, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write BPB fields. ISD_WriteBlock()\n");
return -36;
}
result = pfd_sddrv_write_sector(format_data.partition_start_sector + 8);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, format_data.partition_start_sector + 8, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write BPB fields. ISD_WriteBlock()\n");
return -36;
@@ -1462,14 +1472,13 @@ s32 pfd_sddrv_build_fat32_mbr_bpb(u32 total_sectors) {
if (g_pfd_sddrv_info.media_ejected != 0) {
return -33;
}
result = pfd_sddrv_write_sector(0);
result = ISD_WriteBlock(g_pfd_sddrv_info.device, 0, g_pfd_sddrv_buf, 1);
if (result != 0) {
OSReport("ERR Failed to write MBR fields. ISD_WriteBlock()\n");
return -36;
}
return 0;
}
#pragma pop
s32 pfd_sddrv_full_format(void) {
FADiskInfo geometry;

View File

@@ -8,6 +8,11 @@ static inline pf_u16 read_boot_u16(pf_u8* buf, pf_u32 offset) {
return PF_SWAP_16(*(pf_u16*)&buf[(offset + 1) & ~1]);
}
static inline pf_u32 read_partition_u32(const pf_u8* buf, pf_u32 offset) {
return (((pf_u32)buf[offset + 2] << 16) + buf[offset]) +
(((pf_u32)buf[offset + 3] << 24) + ((pf_u32)buf[offset + 1] << 8));
}
pf_s32 pdm_part_is_master_boot_sector(pf_u8* buf, pf_u32 total, pf_bool* p_is_mbr) {
pf_u32* p_start;
pf_u32* p_count;
@@ -20,8 +25,8 @@ pf_s32 pdm_part_is_master_boot_sector(pf_u8* buf, pf_u32 total, pf_bool* p_is_mb
p_count = count;
for (index = 0; index < 4; index++) {
*p_start = 0;
*p_start = MBR_WORD(buf, 454);
*p_count = MBR_WORD(buf, 458);
*p_start = read_partition_u32(buf, 454);
*p_count = read_partition_u32(buf, 458);
if (*p_start != 0 && *p_count != 0) {
if (index == 0) { *p_is_mbr = 1; }
} else {
@@ -31,11 +36,15 @@ pf_s32 pdm_part_is_master_boot_sector(pf_u8* buf, pf_u32 total, pf_bool* p_is_mb
p_count++;
buf += 16;
}
p_start = start;
p_count = count;
for (index = 0; index < 4; index++) {
if (start[index] + count[index] > total) {
if (*p_start + *p_count > total) {
if (index == 0) { *p_is_mbr = 0; }
return 2;
}
p_start++;
p_count++;
}
return 0;
}

View File

@@ -173,77 +173,72 @@ pf_s32 PFFAT12_WriteFATEntryWithBuf(PF_VOLUME* p_vol, pf_s16 cluster, pf_u16 val
#undef FLUSH_FAT_BUFFER
}
static inline pf_s32 ReadFAT12WordWithBuf(PF_VOLUME* p_vol, pf_u32 offset, pf_u32* p_value, PF_CACHE_PAGE* p_page) {
pf_u32 current_fat;
pf_u32 sector;
pf_s32 err;
pf_s32 PFFAT12_ReadFATEntryWithBuf(PF_VOLUME* p_vol , pf_u16 cluster , pf_u32* p_value ,
PF_CACHE_PAGE* p_page ) {
struct {
pf_u32 sector;
pf_u32 current_fat;
pf_s32 err;
pf_u32 offset;
} state;
pf_s32 result;
#define LOAD_FAT_SECTOR(next_sector) \
if (p_page->sector != sector + (next_sector)) { \
if (p_page->sector != state.sector + (next_sector)) { \
if (p_page->option == 1) { \
for (err = 0; (pf_u16)err < p_vol->bpb.num_active_FATs; err++) { \
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + (pf_u16)err * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector); \
for (state.err = 0; (pf_u16)state.err < p_vol->bpb.num_active_FATs; state.err++) { \
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + (pf_u16)state.err * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector); \
} \
} \
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, sector + (next_sector), 0, p_vol->bpb.bytes_per_sector); \
if (err != 0) { continue; } \
p_page->sector = sector + (next_sector); \
state.err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, state.sector + (next_sector), 0, p_vol->bpb.bytes_per_sector); \
if (state.err != 0) { continue; } \
p_page->sector = state.sector + (next_sector); \
}
sector = p_vol->bpb.active_FAT_sector + (offset >> p_vol->bpb.log2_bytes_per_sector) & 0xFFFF;
state.offset = (pf_u16)(cluster + (cluster >> 1));
state.sector = p_vol->bpb.active_FAT_sector + (state.offset >> p_vol->bpb.log2_bytes_per_sector) & 0xFFFF;
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & (0x01 | 0x02 | 0x04);
state.current_fat = p_vol->bpb.ext_flags & (0x01 | 0x02 | 0x04);
} else {
current_fat = 1;
state.current_fat = 1;
}
err = 0;
state.err = 0;
while (PF_TRUE) {
if (err == 0x1000 && p_vol->p_callback != PF_NULL) {
if (state.err == 0x1000 && p_vol->p_callback != PF_NULL) {
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result == 0) {
err = 0;
state.err = 0;
continue;
}
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
sector += p_vol->bpb.sectors_per_FAT;
err = 0;
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && state.current_fat < p_vol->bpb.num_active_FATs) {
state.current_fat++;
state.sector += p_vol->bpb.sectors_per_FAT;
state.err = 0;
continue;
}
} else {
LOAD_FAT_SECTOR(0);
offset &= p_vol->bpb.bytes_per_sector - 1;
if (offset == (p_vol->bpb.bytes_per_sector - 1)) {
*p_value = p_page->p_buf[offset];
state.offset &= p_vol->bpb.bytes_per_sector - 1;
if (state.offset == (p_vol->bpb.bytes_per_sector - 1)) {
*p_value = p_page->p_buf[state.offset];
if (p_page->option == 1) {
for (err = 0; (pf_u16)err < p_vol->bpb.num_active_FATs; err++) {
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + (pf_u16)err * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
for (state.err = 0; (pf_u16)state.err < p_vol->bpb.num_active_FATs; state.err++) {
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + (pf_u16)state.err * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
}
}
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, sector + 1, 0, p_vol->bpb.bytes_per_sector);
if (err != 0) { continue; }
p_page->sector = sector + 1;
state.err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, state.sector + 1, 0, p_vol->bpb.bytes_per_sector);
if (state.err != 0) { continue; }
p_page->sector = state.sector + 1;
*p_value += (pf_u16)(*p_page->p_buf) << 8;
} else {
*p_value = ((pf_u16)p_page->p_buf[offset + 1] << 8) + p_page->p_buf[offset];
*p_value = ((pf_u16)p_page->p_buf[state.offset + 1] << 8) + p_page->p_buf[state.offset];
}
}
break;
}
return err;
#undef LOAD_FAT_SECTOR
}
pf_s32 PFFAT12_ReadFATEntryWithBuf(PF_VOLUME* p_vol, pf_u16 cluster, pf_u32* p_value,
PF_CACHE_PAGE* p_page) {
pf_s32 err;
err = ReadFAT12WordWithBuf(p_vol, (pf_u16)(cluster + (cluster >> 1)), p_value, p_page);
if (err != 0) {
if (state.err != 0) {
*p_value = -1;
return err;
return state.err;
}
if ((cluster & 0x01) != 0) {
*p_value = *p_value >> 4;
@@ -251,4 +246,6 @@ pf_s32 PFFAT12_ReadFATEntryWithBuf(PF_VOLUME* p_vol, pf_u16 cluster, pf_u32* p_v
*p_value &= 0xFFF;
}
return 0;
#undef LOAD_FAT_SECTOR
}

View File

@@ -1873,7 +1873,10 @@ pf_s32 PFFILE_fappend(PFFILE_FILE* file, pf_u32 size, pf_u32* size_appended) {
pf_s32 PFFILE_fadjust(PFFILE_FILE* file) {
PF_VOLUME* volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
PFFILE_CURSOR saved_cursor;
PFFILE_FAT_HINT saved_hint;
struct {
PF_FAT_HINT hint;
pf_u32 last_access_chain_index;
} saved_hint;
pf_u16 access_time;
pf_s32 error;
@@ -1891,7 +1894,8 @@ pf_s32 PFFILE_fadjust(PFFILE_FILE* file) {
}
((PFFILE_VOLUME_DIRS*)volume)->cache_signature = file;
saved_cursor = file->cursor;
saved_hint = *(PFFILE_FAT_HINT*)&file->hint;
saved_hint.hint = file->hint;
saved_hint.last_access_chain_index = file->last_access_data.last_access.chain_index;
if ((file->open_mode & 8) == 0 && (file->open_mode & 2) != 0) {
error = 0x0A;
} else if ((file->p_sfd->lock.mode & 3) != 0 &&
@@ -1903,7 +1907,8 @@ pf_s32 PFFILE_fadjust(PFFILE_FILE* file) {
error &= (-error | error) >> 31;
}
file->cursor = saved_cursor;
*(PFFILE_FAT_HINT*)&file->hint = saved_hint;
file->hint = saved_hint.hint;
file->last_access_data.last_access.chain_index = saved_hint.last_access_chain_index;
((PFFILE_VOLUME_DIRS*)volume)->cache_signature = PF_NULL;
if (error != 0) {
pf_vol_set.last_error = error;
@@ -1918,7 +1923,10 @@ pf_s32 PFFILE_fadjust(PFFILE_FILE* file) {
pf_s32 PFFILE_finfo(PFFILE_FILE* file, PF_INFO* info) {
PF_VOLUME* volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
PFFILE_CURSOR saved_cursor;
PFFILE_FAT_HINT saved_hint;
struct {
PF_FAT_HINT hint;
pf_u32 last_access_chain_index;
} saved_hint;
pf_s32 error;
error = PFVOL_CheckForRead(volume);
@@ -1935,10 +1943,12 @@ pf_s32 PFFILE_finfo(PFFILE_FILE* file, PF_INFO* info) {
}
((PFFILE_VOLUME_DIRS*)volume)->cache_signature = file;
saved_cursor = file->cursor;
saved_hint = *(PFFILE_FAT_HINT*)&file->hint;
saved_hint.hint = file->hint;
saved_hint.last_access_chain_index = file->last_access_data.last_access.chain_index;
error = PFFILE_p_finfo(file, info);
file->cursor = saved_cursor;
*(PFFILE_FAT_HINT*)&file->hint = saved_hint;
file->hint = saved_hint.hint;
file->last_access_data.last_access.chain_index = saved_hint.last_access_chain_index;
((PFFILE_VOLUME_DIRS*)volume)->cache_signature = PF_NULL;
if (error != 0) {
pf_vol_set.last_error = error;

View File

@@ -418,13 +418,15 @@ pf_s32 PFPATH_cmpNameUni(const pf_u16* name, PF_STR* pattern) {
}
pf_s32 PFPATH_cmpName(const pf_s8* short_name, PF_STR* pattern, pf_u32 short_search) {
pf_s8 name_buffer[13];
pf_u32 matched_end;
pf_s8* name = name_buffer;
struct {
pf_u32 matched_end;
pf_s8 name[0x10];
} work;
pf_s8* name = work.name;
pf_s8* name_end;
const pf_s8* pattern_text;
matched_end = 0;
work.matched_end = 0;
pattern_text = PFSTR_GetStrPos(pattern, 3);
pf_strcpy(name, short_name);
if ((pf_vol_set.setting & 2) == 2 && PFSTR_GetCodeMode(pattern) == 2 && pf_strcmp(name, (const pf_s8*)".") != 0 &&
@@ -448,7 +450,7 @@ pf_s32 PFPATH_cmpName(const pf_s8* short_name, PF_STR* pattern, pf_u32 short_sea
return 1;
}
}
return PFPATH_cmpNameImpl(name_buffer, pattern_text, &matched_end);
return PFPATH_cmpNameImpl(work.name, pattern_text, &work.matched_end);
}
pf_s32 PFPATH_cmpTailSFN(const pf_s8* sfn_name, const pf_s8* pattern) {

View File

@@ -124,7 +124,7 @@ void __GetImageTileCount(GXTexFmt fmt, u16 wd, u16 ht, u32* rowTiles, u32* colTi
*cmpTiles = (fmt == GX_TF_RGBA8 || fmt == GX_TF_Z24X8) ? 2 : 1;
}
void GXInitTexObj(GXTexObj* obj, void* image_ptr, u16 width, u16 height, GXTexFmt format, GXTexWrapMode wrap_s, GXTexWrapMode wrap_t,
void GXInitTexObj(const GXTexObj* obj, void* image_ptr, u16 width, u16 height, GXTexFmt format, GXTexWrapMode wrap_s, GXTexWrapMode wrap_t,
GXBool mipmap) {
u32 imageBase;
u32 maxLOD;

View File

@@ -396,8 +396,6 @@ static void kbdProcKey(u32 key, u32 pressed, u32 channel) {
kbdSendKey(&event);
}
#pragma push
#pragma opt_propagation off
static void kbdProcMod(u32 key, u32 pressed, u32 channel) {
KBDChannel* data;
u32 modState;
@@ -526,7 +524,6 @@ static void kbdProcMod(u32 key, u32 pressed, u32 channel) {
finalState = modState | 0x1000;
KBDSetModState(channel, finalState);
}
#pragma pop
static void kbdSendKey(KBDKeyEventData* event) {
KBDChannel* data;
@@ -557,24 +554,26 @@ static void kbdSendKey(KBDKeyEventData* event) {
}
}
#pragma push
#pragma ppc_iro_level 0
static void kbd_led_handler(BOOL success, void* callbackArg) {
u32 index;
USBKBDErr err;
index = (u32)callbackArg;
const KBDLEDCallbackData* callback;
s32 index;
u32 err;
index = (s32)callbackArg;
callback = &kbdLCBuf[index];
kbdCmdBuf[index].device = 0;
if (kbdLCBuf[index].callbackAddress == NULL) {
if (callback->callbackAddress == (USBKBDCmdLEDCallback)(u32)kbdCmdBuf[(u32)callbackArg].device) {
return;
}
if (success == TRUE) {
err = 0;
} else {
switch (success) {
default:
err = 7;
break;
case TRUE:
err = 0;
break;
}
kbdLCBuf[index].callbackAddress(err, kbdLCBuf[index].callbackArg);
kbdLCBuf[(u32)callbackArg].callbackAddress(err, kbdLCBuf[(u32)callbackArg].callbackArg);
}
#pragma pop
USBKBDErr KBDSetLedsAsync(u32 channel, u32 leds, USBKBDCmdLEDCallback callback, void* callbackArg) {
u8 ledBits;
@@ -824,8 +823,6 @@ USBKBDErr KBDSetLockProcessing(u32 channel, u32 value) {
return 0;
}
#pragma push
#pragma ppc_iro_level 1
USBKBDErr KBDSetModState(u32 channel, u32 value) {
if (!kbdInitialized) {
return 2;
@@ -842,13 +839,12 @@ USBKBDErr KBDSetModState(u32 channel, u32 value) {
interrupts = OSDisableInterrupts();
newState.value = value & 0xfc0;
oldState.value = kbdData[channel].modState;
newState.bits.physical = oldState.value;
newState.bits.physical = oldState.bits.physical;
kbdData[channel].modState = newState.value;
OSRestoreInterrupts(interrupts);
}
return 0;
}
#pragma pop
u16 KBDTranslateHidCode(u32 keyCode, u32 modifiers, s32 country) {
s32 mask;

View File

@@ -83,10 +83,8 @@ typedef struct WADFileHeader {
u8 reserved_0x60[0x20];
} WADFileHeader;
typedef struct WADImportParts {
s32 type;
u16 cidxMode;
u16 version;
typedef struct WADBootImportParts {
s32 headerInfo[2];
u32 certificateSize;
void* certificates;
u32 crlSize;
@@ -95,7 +93,7 @@ typedef struct WADImportParts {
void* ticket;
u32 titleMetaSize;
void* titleMeta;
} WADImportParts;
} WADBootImportParts;
typedef struct WADBackupFileHeader {
u32 magic;
@@ -3399,7 +3397,7 @@ static s32 _WADCleanTmpDir(MEMAllocator* allocator) {
s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) {
DVDFileInfo fileInfo;
WADImportParts parts;
WADBootImportParts parts;
WADHeader* header;
u8* readBuffer;
BOOL fileOpened = FALSE;
@@ -3435,14 +3433,14 @@ s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) {
memset(&parts, 0, sizeof(parts));
header = (WADHeader*)readBuffer;
result = WAD_815C2F44(header, &parts.type);
result = WAD_815C2F44(header, parts.headerInfo);
if (result != 2) {
OSReport("%s:%d Format should be iRD format: %s\n", __func__, 0x17D2,
path);
result = -3000;
goto cleanup;
}
if (parts.type == 3) {
if (parts.headerInfo[0] == 3) {
sectionOffset = (header->hdrSize + 0x3F) & ~0x3F;
if (header->certSize != 0) {
parts.certificateSize = header->certSize;
@@ -3498,7 +3496,19 @@ cleanup:
s32 WADImportDVDExForBS(const char* path, void* buffer, u32 bufferSize) {
WADHeader header ALIGN32;
DVDFileInfo fileInfo;
WADImportParts parts;
struct {
s32 type;
u16 cidxMode;
u16 version;
u32 certificateSize;
void* certificates;
u32 crlSize;
void* crls;
u32 ticketSize;
void* ticket;
u32 titleMetaSize;
void* titleMeta;
} parts;
BOOL fileOpened = FALSE;
s32 result;
u8* contentBuffer;

View File

@@ -168,86 +168,72 @@ static const u32 AESiDecryptTable[] = {
0xa8017139, 0xcb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0
};
#define ROTATE(x, n) __rlwinm((x), (n), 0, 31)
#define ROUND_WORD(table, a, b, c, d) (ROTATE(table[(a) >> 24], 24) ^ ROTATE(table[((b) >> 16) & 255], 16) ^ ROTATE(table[((c) >> 8) & 255], 8) ^ table[(d) & 255])
#define SUBSTITUTE_WORD(table, a, b, c, d) (((u32)table[(a) >> 24] << 24) | ((u32)table[((b) >> 16) & 255] << 16) | ((u32)table[((c) >> 8) & 255] << 8) | table[(d) & 255])
#define DOUBLE_BYTES(x) ((((x) & 0x7f7f7f7f) << 1) ^ ((((x) & 0x80808080) >> 7) * 0x1b))
#define ROTATE(x,n) (((x) << (n)) | ((x) >> (32 - (n))))
#define ENCRYPT(state0,state1,state2,state3) (((ROTATE(AESiEncryptTable[((state1)>>16)&255],16) ^ ROTATE(AESiEncryptTable[(state0)>>24],24)) ^ AESiEncryptTable[(state3)&255]) ^ ROTATE(AESiEncryptTable[((state2)>>8)&255],8))
#define DECRYPT(state0,state1,state2,state3) (((ROTATE(AESiDecryptTable[((state1)>>16)&255],16) ^ AESiDecryptTable[(state3)&255]) ^ ROTATE(AESiDecryptTable[(state0)>>24],24)) ^ ROTATE(AESiDecryptTable[((state2)>>8)&255],8))
#define SUBSTITUTE(table,state0,state1,state2,state3) ((((u32)table[(state0)>>24]<<24) | table[(state3)&255]) | (((u32)table[((state1)>>16)&255]<<16) | ((u32)table[((state2)>>8)&255]<<8)))
#define DECRYPT_FINAL(table,state0,state1,state2,state3,key) ((table[(state3)&255] ^ ((u32)table[((state2)>>8)&255]<<8)) ^ (((u32)table[((state1)>>16)&255]<<16) ^ ((key) ^ ((u32)table[(state0)>>24]<<24))))
void AESiEncryptBlock(AESContext* context, u32* output, const u32* input) {
const u32* key = context->keys;
u32 rounds = context->rounds;
u32 state0 = input[0];
u32 state1 = input[1];
u32 state2 = input[2];
u32 state3 = input[3];
state0 ^= key[0];
state1 ^= key[1];
state2 ^= key[2];
state3 ^= key[3];
key += 4;
const u32* key = context->keys + 4;
u32 state0=input[0]^context->keys[0], state1=input[1]^context->keys[1], state2=input[2]^context->keys[2], state3=input[3]^context->keys[3];
while (--rounds != 0) {
u32 next0 = ROUND_WORD(AESiEncryptTable, state0, state1, state2, state3);
u32 next1 = ROUND_WORD(AESiEncryptTable, state1, state2, state3, state0);
u32 next2 = ROUND_WORD(AESiEncryptTable, state2, state3, state0, state1);
u32 next3 = ROUND_WORD(AESiEncryptTable, state3, state0, state1, state2);
state0 = next0 ^ key[0];
state1 = next1 ^ key[1];
state2 = next2 ^ key[2];
state3 = next3 ^ key[3];
u32 nextState0=ENCRYPT(state0,state1,state2,state3);
u32 nextState1=ENCRYPT(state1,state2,state3,state0);
u32 nextState2=ENCRYPT(state2,state3,state0,state1);
u32 nextState3=ENCRYPT(state3,state0,state1,state2);
state0=nextState0^key[0]; state1=nextState1^key[1]; state2=nextState2^key[2]; state3=nextState3^key[3];
key += 4;
}
output[0] = SUBSTITUTE_WORD(AESiSubShiftTable, state0, state1, state2, state3) ^ key[0];
output[1] = SUBSTITUTE_WORD(AESiSubShiftTable, state1, state2, state3, state0) ^ key[1];
output[2] = SUBSTITUTE_WORD(AESiSubShiftTable, state2, state3, state0, state1) ^ key[2];
output[3] = SUBSTITUTE_WORD(AESiSubShiftTable, state3, state0, state1, state2) ^ key[3];
output[0] = SUBSTITUTE(AESiSubShiftTable,state0,state1,state2,state3)^key[0];
output[1] = SUBSTITUTE(AESiSubShiftTable,state1,state2,state3,state0)^key[1];
output[2] = SUBSTITUTE(AESiSubShiftTable,state2,state3,state0,state1)^key[2];
output[3] = SUBSTITUTE(AESiSubShiftTable,state3,state0,state1,state2)^key[3];
}
static inline void AESiInvMixColumn(u32* word) {
u32 value = *word;
u32 timesTwo = DOUBLE_BYTES(value);
u32 timesFour = DOUBLE_BYTES(timesTwo);
u32 mixed = DOUBLE_BYTES(timesFour) ^ value;
mixed ^= timesFour ^ ROTATE(mixed, 8);
mixed ^= timesTwo ^ ROTATE(mixed, 8);
mixed ^= value ^ ROTATE(mixed, 8);
*word = mixed;
}
#define DOUBLE_BYTES(x) ((((x)&0x7f7f7f7f)<<1) ^ ((((x)&0x80808080)>>7)*0x1b))
void AESiDecryptBlock(AESContext* context, u32* output, const u32* input) {
u32* key = context->keys;
u32 rounds = context->rounds;
u32 state0, state1, state2, state3;
key += rounds * 4;
u32 rounds=context->rounds;
u32* key=context->keys;
u32 state1;
u32 state0;
u32 state2;
u32 state3;
key += rounds*4;
if (context->needsTransform) {
u32 round;
for (round = 1; round < context->rounds; round++) {
for (round=1; round<context->rounds; ++round) {
u32 word;
for (word = 0; word < 4; word++) {
AESiInvMixColumn(&context->keys[round * 4 + word]);
for (word=0; word<4; ++word) {
u32 value=context->keys[round*4 + word];
u32 timesTwo=DOUBLE_BYTES(value);
u32 timesFour=DOUBLE_BYTES(timesTwo);
u32 timesNine=DOUBLE_BYTES(timesFour)^value;
u32 mixed=(ROTATE(timesNine,8) ^ (timesNine ^ timesFour));
mixed=(ROTATE(mixed,8) ^ (mixed ^ timesTwo));
mixed=(ROTATE(mixed,8) ^ (mixed ^ value));
context->keys[round*4 + word]=mixed;
}
}
context->needsTransform = 0;
context->needsTransform=0;
}
state0 = input[0] ^ key[0];
state1 = input[1] ^ key[1];
state2 = input[2] ^ key[2];
state3 = input[3] ^ key[3];
key -= 4;
state0=input[0]^key[0]; state1=input[1]^key[1]; state2=input[2]^key[2]; state3=input[3]^key[3];
key-=4;
while (--rounds != 0) {
u32 next0 = ROUND_WORD(AESiDecryptTable, state0, state3, state2, state1);
u32 next1 = ROUND_WORD(AESiDecryptTable, state1, state0, state3, state2);
u32 next2 = ROUND_WORD(AESiDecryptTable, state2, state1, state0, state3);
u32 next3 = ROUND_WORD(AESiDecryptTable, state3, state2, state1, state0);
state0 = next0 ^ key[0];
state1 = next1 ^ key[1];
state2 = next2 ^ key[2];
state3 = next3 ^ key[3];
key -= 4;
u32 nextState0=DECRYPT(state0,state3,state2,state1);
u32 nextState1=DECRYPT(state1,state0,state3,state2);
u32 nextState2=DECRYPT(state2,state1,state0,state3);
u32 nextState3=DECRYPT(state3,state2,state1,state0);
state0=nextState0^key[0]; state1=nextState1^key[1]; state2=nextState2^key[2]; state3=nextState3^key[3];
key-=4;
}
output[0] = key[0] ^ ((u32)AESiInvSubShiftTable[state0 >> 24] << 24) ^ ((u32)AESiInvSubShiftTable[(state3 >> 16) & 255] << 16) ^ ((u32)AESiInvSubShiftTable[(state2 >> 8) & 255] << 8) ^ AESiInvSubShiftTable[state1 & 255];
output[1] = key[1] ^ ((u32)AESiInvSubShiftTable[state1 >> 24] << 24) ^ ((u32)AESiInvSubShiftTable[(state0 >> 16) & 255] << 16) ^ ((u32)AESiInvSubShiftTable[(state3 >> 8) & 255] << 8) ^ AESiInvSubShiftTable[state2 & 255];
output[2] = key[2] ^ ((u32)AESiInvSubShiftTable[state2 >> 24] << 24) ^ ((u32)AESiInvSubShiftTable[(state1 >> 16) & 255] << 16) ^ ((u32)AESiInvSubShiftTable[(state0 >> 8) & 255] << 8) ^ AESiInvSubShiftTable[state3 & 255];
output[3] = key[3] ^ ((u32)AESiInvSubShiftTable[state3 >> 24] << 24) ^ ((u32)AESiInvSubShiftTable[(state2 >> 16) & 255] << 16) ^ ((u32)AESiInvSubShiftTable[(state1 >> 8) & 255] << 8) ^ AESiInvSubShiftTable[state0 & 255];
output[0]=DECRYPT_FINAL(AESiInvSubShiftTable,state0,state3,state2,state1,key[0]);
output[1]=DECRYPT_FINAL(AESiInvSubShiftTable,state1,state0,state3,state2,key[1]);
output[2]=DECRYPT_FINAL(AESiInvSubShiftTable,state2,state1,state0,state3,key[2]);
output[3]=DECRYPT_FINAL(AESiInvSubShiftTable,state3,state2,state1,state0,key[3]);
}
BOOL NETAESCreateEx(AESContext* context, const void* key, u32 keyLength, const void* iv, const AESBlockMode* mode) {

View File

@@ -3,8 +3,6 @@
void* NHTTPi_memcpy(void*, const void*, u32);
s32 NHTTPi_SocRecv(void*, NHTTPRequestInfo*, s32, void*, s32, s32);
#define NHTTPi_TOLOWER(c) ((((c) >= 'A') & ((c) <= 'Z')) ? (c) + ('a' - 'A') : (c))
static void FindHeaderBlock(const NHTTPResponseInfo* response, s32 position, NHTTPi_HDRBUFLIST** block, s32* offset) {
if(position<NHTTP_HDRRECVBUF_INILEN) { *offset=position; *block=NULL; }
else {
@@ -24,6 +22,10 @@ static int ReadHeaderChar(const NHTTPResponseInfo* response, NHTTPi_HDRBUFLIST**
return (*block)->block[(*offset)++];
}
static int LowerCase(int character) {
return ((character >= 'A') & (character <= 'Z')) ? character + ('a' - 'A') : character;
}
s32 NHTTPi_findNextLineHdrRecvBuf(const NHTTPResponseInfo* response, s32 position, s32 limit, s32* colon, s32* newlineLength) {
NHTTPi_HDRBUFLIST* block;
s32 offset;
@@ -73,48 +75,16 @@ s32 NHTTPi_skipSpaceHdrRecvBuf(const NHTTPResponseInfo* response, s32 position,
s32 NHTTPi_compareTokenN_HdrRecvBuf(const NHTTPResponseInfo* response, s32 position, s32 limit, const char* token, s8 delimiter) {
NHTTPi_HDRBUFLIST* block;
s32 offset;
s32 i;
s32 tokenChar;
s32 character;
int character;
if (position < limit) {
FindHeaderBlock(response, position, &block, &offset);
if (block == NULL) {
if (offset < NHTTP_HDRRECVBUF_INILEN) {
character = (s8)response->hdrBufFirst[offset++];
goto compare_characters;
}
block = response->hdrBufBlock_p;
offset = 0;
} else if (offset == NHTTP_HDRRECVBUF_BLOCKLEN) {
offset = 0;
block = block->next_p;
}
character = block->block[offset++];
compare_characters:
i = position;
while (NHTTPi_TOLOWER((s8)character) == NHTTPi_TOLOWER((s8)*token)) {
tokenChar = (s8)*token;
if (tokenChar == '\0' || tokenChar == ' ' || tokenChar == delimiter || i == limit - 1) return 0;
if (block == NULL) {
if (offset < NHTTP_HDRRECVBUF_INILEN) {
character = (s8)response->hdrBufFirst[offset++];
goto advance_token;
}
block = response->hdrBufBlock_p;
offset = 0;
} else if (offset == NHTTP_HDRRECVBUF_BLOCKLEN) {
offset = 0;
block = block->next_p;
}
character = block->block[offset++];
advance_token:
i++;
token++;
character = ReadHeaderChar(response, &block, &offset);
while (LowerCase((s8)character) == LowerCase(*token)) {
if (*token == 0 || *token == ' ' || *token == delimiter || position == limit - 1) return 0;
character = ReadHeaderChar(response, &block, &offset);
++position;
++token;
}
}
return -1;

View File

@@ -1,8 +1,6 @@
#include <revolution/types.h>
#include <string.h>
#define NHTTPi_TOLOWER(c) ((((c) >= 'A') & ((c) <= 'Z')) ? (c) + ('a' - 'A') : (c))
void* NHTTPi_memcpy(void* destination, const void* source, u32 size)
{
return memcpy(destination, source, size);
@@ -28,33 +26,28 @@ static int LowerCase(int character)
return ((character >= 'A') & (character <= 'Z')) ? character + 32 : character;
}
s32 NHTTPi_strnicmp(const char* left, const char* right, s32 size)
s32 NHTTPi_strnicmp(const char* left, const char* right, s32 length)
{
char leftChar;
char rightChar;
while (size > 0)
while (length > 0)
{
leftChar = *left++;
rightChar = *right++;
if (leftChar == '\0' || rightChar == '\0')
int a = *left++, b = *right++;
if (a == 0 || b == 0)
{
if (leftChar == '\0' && rightChar == '\0')
if (a == 0 && b == 0)
{
size = 0;
length = 0;
break;
}
}
if (NHTTPi_TOLOWER(leftChar) != NHTTPi_TOLOWER(rightChar))
b = LowerCase(b);
a = LowerCase(a);
if (a != b)
{
break;
}
size--;
--length;
}
return size;
return length;
}
static BOOL UrlPlain(int character)
@@ -244,18 +237,18 @@ s32 NHTTPi_intToStr(char* destination, u32 value)
return length + 1;
}
s32 NHTTPi_compareToken(const char* string, const char* token)
s32 NHTTPi_compareToken(const char* left, const char* right)
{
while (NHTTPi_TOLOWER(*string) == NHTTPi_TOLOWER(*token))
u32 rawLeft;
while (LowerCase((s8)(rawLeft = *(const u8*)left)) == LowerCase((s8)*(const u8*)right))
{
if (*string == '\0' || *string == ' ')
if ((s8)rawLeft == 0 || (s8)rawLeft == ' ')
{
return 0;
}
string++;
token++;
++left;
++right;
}
return -1;
}

View File

@@ -2,7 +2,6 @@
#include <revolution/nwc24.h>
static const u8 TtableInv[] = {13, 5, 9, 7, 0, 15, 10, 2, 12, 3, 14, 1, 8, 6, 11, 4};
static const u8 ExcTable[] = {1, 5, 0, 4, 2, 3, 6, 7};
extern void _savegpr_27(void);
extern void _restgpr_27(void);
extern void __shr2u(void);
@@ -54,34 +53,166 @@ NWC24Err NWC24iCheckUserIdCRC(NWC24UserId id) {
return NWC24_OK;
}
static u8 getByte(u64 value, u8 index) {
return (value >> (index * 8)) & 0xFF;
}
static u64 setByte(u64 value, u8 index, u8 byte) {
return (value & ~(0xFFULL << ((u64)8 * index))) | ((u64)byte << ((u64)8 * index));
}
static NWC24UserId getUnScrambleId(NWC24UserId id) {
u64 copy;
u8 i;
id &= 0x001FFFFFFFFFFFFFULL;
id ^= 0x00005E5E5E5E5E5EULL;
id &= 0x001FFFFFFFFFFFFFULL;
id |= (((id & 0xFF) << 5) & 0x20) << 48;
id >>= 1;
copy = id;
for (i = 0; i < 6; ++i) {
id = setByte(id, i, getByte(copy, ExcTable[i]));
}
for (i = 0; i < 6; ++i) {
id = setByte(id, i, (TtableInv[(getByte(id, i) >> 4) & 0xF] << 4) | TtableInv[getByte(id, i) & 0xF]);
}
id = ((id & 0x7FFFFFFFFFFULL) << 10) | ((id >> 43) & 0x3FF);
id ^= 0x0000B3B3B3B3B3B3ULL;
return id;
static asm NWC24UserId getUnScrambleId(register NWC24UserId id) {
li r9,-1
lis r7,0x20
lis r6,0x5e5e
stwu r1,-0x20(r1)
subi r7,r7,1
and r8,r4,r9
addi r0,r6,0x5e5e
stw r31,0x1c(r1)
and r3,r3,r7
lis r5,-1
xor r8,r8,r0
stw r30,0x18(r1)
and r8,r8,r9
xori r3,r3,0x5e5e
rlwinm r0,r8,0x15,0xa,0xa
li r6,-0x100
and r3,r3,r7
rlwinm r8,r8,0x1f,0,0x1f
or r3,r3,r0
stw r29,0x14(r1)
rlwimi r8,r3,0x1f,0,0
lis r4,-0xff
rlwinm r7,r3,0x1f,1,0x1f
addi r5,r5,0xff
rlwinm r30,r8,0x18,0,0x1f
rlwinm r29,r3,0x17,0x18,0x1f
and r12,r7,r9
li r0,0
rlwimi r30,r3,0x17,0,7
and r31,r8,r6
rlwimi r31,r30,0,0x18,0x1f
rlwinm r11,r3,0x1f,0x10,0x17
and r30,r31,r5
and r12,r12,r9
rlwimi r0,r29,8,0x18,0x1f
subi r4,r4,1
or r12,r12,r0
or r11,r30,r11
and r30,r11,r4
rlwinm r31,r8,0,0x18,0x1f
li r0,0
rlwinm r11,r8,0x10,8,0xf
lis r10,0x100
and r12,r12,r9
rlwimi r0,r31,0x10,0x10,0x1f
or r30,r30,r11
or r29,r12,r0
rlwinm r12,r3,0x1f,0x18,0x1f
subi r0,r10,1
li r10,0
rlwimi r10,r12,0x18,8,0x1f
and r11,r29,r9
and r12,r30,r0
rlwinm r3,r3,0x17,0,7
or r3,r12,r3
or r12,r11,r10
and r10,r3,r9
lis r3,TtableInv@ha
and r31,r10,r9
rlwinm r30,r8,0x10,0,0x1f
rlwinm r11,r31,0x1c,0x1c,0x1f
addi r3,r3,TtableInv@l
rlwimi r30,r7,0x10,0,0xf
rlwinm r10,r31,0,0x1c,0x1f
and r29,r12,r6
rlwinm r12,r8,8,0,0x1f
lbzx r11,r3,r11
rlwimi r12,r7,8,0,0x17
lbzx r7,r3,r10
rlwimi r29,r30,0,0x18,0x1f
rlwinm r8,r11,4,0,0x1b
rlwinm r10,r12,8,0x10,0x17
and r11,r29,r5
or r10,r11,r10
or r7,r8,r7
and r11,r31,r6
li r8,0
rlwimi r11,r7,0,0x18,0x1f
and r12,r10,r9
rlwinm r10,r11,0x18,0,0x1f
li r7,0
rlwimi r10,r12,0x18,0,7
and r31,r11,r5
rlwinm r11,r10,0x1c,0x1c,0x1f
and r12,r12,r9
rlwinm r10,r10,0,0x1c,0x1f
lbzx r11,r3,r11
lbzx r10,r3,r10
rlwinm r11,r11,4,0,0x1b
or r10,r11,r10
rlwinm r11,r10,0,0x18,0x1f
rlwinm r10,r10,8,0x10,0x17
rlwimi r8,r11,8,0x18,0x1f
or r10,r31,r10
or r8,r12,r8
rlwinm r12,r10,0x10,0,0x1f
and r11,r10,r4
rlwimi r12,r8,0x10,0,0xf
and r10,r8,r9
rlwinm r8,r12,0x1c,0x1c,0x1f
rlwinm r4,r12,0,0x1c,0x1f
lbzx r8,r3,r8
lbzx r4,r3,r4
rlwinm r8,r8,4,0,0x1b
or r4,r8,r4
rlwinm r8,r4,0,0x18,0x1f
rlwinm r4,r4,0x10,8,0xf
or r29,r11,r4
rlwimi r7,r8,0x10,0x10,0x1f
or r11,r10,r7
lis r4,1
rlwinm r8,r29,8,0,0x1f
and r31,r29,r0
rlwimi r8,r11,8,0,0x17
and r12,r11,r9
rlwinm r10,r8,0x1c,0x1c,0x1f
subi r0,r4,0x4c4d
lbzx r11,r3,r10
rlwinm r8,r8,0,0x1c,0x1f
lbzx r10,r3,r8
li r8,0
rlwinm r11,r11,4,0,0x1b
lis r7,-0x4c4c
or r11,r11,r10
rlwinm r10,r11,0,0x18,0x1f
subi r7,r7,0x4c4d
rlwimi r8,r10,0x18,8,0x1f
rlwinm r4,r11,0x18,0,7
or r10,r12,r8
rlwinm r8,r10,0x1c,0x1c,0x1f
or r12,r31,r4
rlwinm r4,r10,0,0x1c,0x1f
lbzx r8,r3,r8
and r11,r10,r6
lbzx r4,r3,r4
rlwinm r6,r8,4,0,0x1b
and r8,r12,r9
or r4,r6,r4
rlwimi r11,r4,0,0x18,0x1f
and r10,r8,r9
rlwinm r6,r11,0x14,0x1c,0x1f
rlwinm r4,r11,0x18,0x1c,0x1f
lbzx r6,r3,r6
lbzx r3,r3,r4
and r8,r11,r5
rlwinm r5,r6,4,0,0x1b
and r4,r10,r9
or r3,r5,r3
rlwinm r3,r3,8,0x10,0x17
or r3,r8,r3
rlwinm r5,r3,0xa,0xb,0x15
rlwinm r3,r3,0x15,0x16,0x1f
rlwimi r5,r4,0xa,0x16,0x1f
rlwimi r3,r4,0xa,0,0x15
xor r4,r3,r7
xor r3,r5,r0
lwz r31,0x1c(r1)
lwz r30,0x18(r1)
lwz r29,0x14(r1)
addi r1,r1,0x20
blr
}

View File

@@ -31,7 +31,7 @@ typedef struct AppLoaderHeader {
u8 pad_0x1C[4];
} AppLoaderHeader;
static u8 TicketViewsBuf[OSRoundUp32B(sizeof(ESTicketView) * 64)] ALIGN32;
u8 TicketViewsBuf[OSRoundUp32B(sizeof(ESTicketView) * 64)] ALIGN32;
ESTicketView *TicketViews = (ESTicketView *)TicketViewsBuf;
DVDDiskID UpdateDiskID ALIGN32;
OSBootInfo2 bi2 ALIGN32;
@@ -39,65 +39,69 @@ AppLoaderHeader AppLoaderHdr ALIGN32;
OSBootInfo3 bi3 ALIGN32;
u8 GameTOCBuf[OSRoundUp32B(sizeof(DVDGameTOC))] ALIGN32;
DVDDriveInfo DriveInfo ALIGN32;
static DVDDiskID DiskID ALIGN32;
static DVDPartitionParams PartitionParams ALIGN32;
DVDDiskID DiskID ALIGN32;
DVDPartitionParams PartitionParams ALIGN32;
NANDCommandBlock BS2NandBlock;
NANDFileInfo BS2CacheFileInfo;
DVDCommandBlock CoverBlock;
u8 PartitionInfoBuf[OSRoundUp32B(sizeof(DVDPartitionInfo) * 256)] ALIGN32;
DVDCommandBlock Block;
static BS2State State = BS2_STT_BEGIN;
static vu32 DvdReadPending = 0;
static u32 BannerAllocation = 0;
static u32 BannerBuffer = 0;
static u32 BannerAvailable = 0;
static u32 Allocator = 0;
volatile BOOL StartingGame = FALSE;
static vu32 RestartRequested = 0;
static vu32 PartitionOpen = 0;
static u32 CacheSeekComplete = 0;
static vu32 LoadingTitle = 0;
volatile BOOL FatalErrorFlag = FALSE;
BS2State State = BS2_STT_BEGIN;
vu32 DvdReadPending = 0;
u32 BannerAllocation = 0;
u32 BannerBuffer = 0;
u32 BannerAvailable = 0;
u32 Allocator = 0;
BOOL StartingGame = FALSE;
u32 RestartRequested = 0;
u32 PartitionOpen = 0;
u32 CacheSeekComplete = 0;
u32 LoadingTitle = 0;
BOOL FatalErrorFlag = FALSE;
BOOL RetryErrorFlag = FALSE;
BOOL UpdateErrorFlag = FALSE;
volatile BOOL AbortFlag = FALSE;
BOOL AbortFlag = FALSE;
volatile int CacheFailed = 0;
volatile int RegionValid = 0;
static volatile int NandPending = 0;
static vu32 CancelNand = 0;
static vu32 LowReadResult = 0;
static u32 LoaderInit;
static u32 LoaderMain;
static u32 LoaderClose;
static u32 *DvdProgress;
static vu32 DvdTransferred;
static vu32 DvdTransferLength;
static vu32 BannerLength;
vu32 CacheLength;
u32 LoaderAddress;
vu32 LoaderLength;
u32 LoaderOffset;
volatile NANDCallback NandCompletion;
vu32 NandOperation;
NANDFileInfo *NandFile;
u8 *NandBuffer;
vu32 NandLength;
vu32 NandTransferred;
OSTime CoverOpenTime;
u64 GameToc;
u32 DataToc;
u32 PartitionCursor;
u32 UpdatePartition;
u32 GamePartition;
u64 RequiredIos;
u32 TitleCode;
static u32 CurrentTmd;
static u32 TitleTicketView;
u32 DriveWasReset;
u64 CoverPollTime;
static u64 SpinupDeadline;
static u64 ResetTime;
volatile int NandPending = 0;
vu32 CancelNand = 0;
vu32 LowReadResult = 0;
u32 CacheCommandComplete = 0;
u32 AudioBufferUnconfigured = 0;
u64 ResetTime = 0;
u64 SpinupDeadline = 0;
u64 CoverPollTime = 0;
u32 DriveWasReset = 0;
u32 TitleTicketView = 0;
u32 CurrentTmd = 0;
u32 TitleCode = 0;
u32 RequiredIosHigh = 0;
u32 RequiredIosLow = 0;
u32 GamePartition = 0;
u32 UpdatePartition = 0;
u32 PartitionCursor = 0;
u32 DataToc = 0;
u64 GameToc = 0;
u32 CoverOpenTimeHigh = 0;
u32 CoverOpenTimeLow = 0;
vu32 NandTransferred = 0;
vu32 NandLength = 0;
u8 *NandBuffer = NULL;
NANDFileInfo *NandFile = NULL;
vu32 NandOperation = 0;
volatile NANDCallback NandCompletion = NULL;
u32 LoaderOffset = 0;
vu32 LoaderLength = 0;
u32 LoaderAddress = 0;
vu32 CacheLength = 0;
vu32 BannerLength = 0;
vu32 DvdTransferLength = 0;
vu32 DvdTransferred = 0;
u32 *DvdProgress = 0;
u32 LoaderClose = 0;
u32 LoaderMain = 0;
u32 LoaderInit = 0;
void BS2Report(const char *msg, ...) {
@@ -239,7 +243,7 @@ BOOL BS2IsDiagDisc() { return (u8)(*(u8 *)OSPhysicalToCached(OS_ADDR_BOOT_INFO)
extern vu32 BS2VideoMode;
extern vu32 __DVDLayoutFormat;
static asm void Run(u32 entryPoint, void *start, u32 blockCount, u32 argument) {
asm void Run(u32 entryPoint, void *start, u32 blockCount, u32 argument) {
// clang-format off
#ifdef __MWERKS__
nofralloc
@@ -487,7 +491,7 @@ BOOL BS2StartLoadingTitle(ESTitleId titleId, ESTicketView *pTicketView) {
static void callback(u32 result) { LowReadResult = result; }
static ESError BS2ESGetTicketViews(IOSFd *descriptor, ESTitleId titleId, ESTicketView *views, u32 *count) {
ESError BS2ESGetTicketViews(IOSFd *descriptor, ESTitleId titleId, ESTicketView *views, u32 *count) {
u8 work[256] ALIGN32;
IOSIoVector vectors[4] ALIGN32;
ESError result;
@@ -525,7 +529,7 @@ static ESError BS2ESGetTicketViews(IOSFd *descriptor, ESTitleId titleId, ESTicke
request[2].length = *count * sizeof(*views);
return IOS_Ioctlv(*descriptor, 0x13, 2, 1, request);
}
static void BS2Reboot(void) {
void BS2Reboot(void) {
ESTicketView ticket ALIGN32;
u8 work[256] ALIGN32;
OSStateFlags flags ALIGN32;
@@ -619,7 +623,7 @@ void BS2StartGame() {
u32 (*entry)(void);
StartingGame = TRUE;
while (((volatile DVDCommandBlock *)&CoverBlock)->state != DVD_STATE_IDLE) {
while (CoverBlock.state != DVD_STATE_IDLE) {
}
BS2Report("BS2StartGame(1)\n");
@@ -663,8 +667,8 @@ void BS2StartGame() {
__OSWriteStateFlags(&stateFlags);
__OSClearRTCFlags();
titleType = (u32)(RequiredIos >> 32);
titleCode = (u32)RequiredIos;
titleType = RequiredIosHigh;
titleCode = RequiredIosLow;
ticketCount = 1;
ticketViews = TicketViews;
if ((titleCode | titleType) == 0) {
@@ -802,25 +806,16 @@ partition_fatal:
partition_done:
BS2Report("DVDLowOpenPartition done\n");
if (*(u8 *)0x8000315D != 0x80) {
typedef union {
u32 value;
struct {
u32 reserved : 29;
u32 bit2 : 1;
u32 bit1 : 1;
u32 bit0 : 1;
} bits;
} DIControl;
DIControl diBits;
DIControl diValue;
u32 diBits;
u32 diValue;
u32 *diAddr;
diAddr = (u32 *)0xCC003024;
diValue.value = *diAddr;
diValue.bits.bit0 = 1;
diBits.value = 2;
diBits.bits.bit2 = 1;
*diAddr = diValue.value | diBits.value;
diBits = 2;
diBits |= 4;
diValue = *diAddr;
diValue |= 1;
*diAddr = diValue | diBits;
enableLegacyDI();
}
oldInterrupts = OSDisableInterrupts();
@@ -839,6 +834,9 @@ void BS2StartGCGame() {
static u8 gameCubeLanguages[] = {0, 0, 1, 2, 3, 4, 5};
s32 ret;
u32 rtc;
u32 counterBias;
u32 seconds;
u32 timerFrequency;
u32 soundMode;
s8 productVideoMode;
u8 progressiveMode;
@@ -850,7 +848,7 @@ void BS2StartGCGame() {
OSTime time;
StartingGame = TRUE;
while (((volatile DVDCommandBlock *)&CoverBlock)->state != DVD_STATE_IDLE) {
while (CoverBlock.state != DVD_STATE_IDLE) {
}
soundMode = SCGetSoundMode();
@@ -880,7 +878,10 @@ void BS2StartGCGame() {
}
__OSGetRTC(&rtc);
time = OS_TIMER_CLOCK * (OSTime)(rtc + SCGetCounterBias());
counterBias = SCGetCounterBias();
seconds = rtc + counterBias;
timerFrequency = OS_BUS_CLOCK >> 2;
time = (OSTime)seconds * timerFrequency;
__OSSetTime(time);
sram = __OSLockSram();
@@ -954,7 +955,7 @@ void BS2StartGCGame() {
}
}
static BOOL CheckDVDCommandStatus(DVDCommandBlock *block) {
BOOL CheckDVDCommandStatus(DVDCommandBlock *block) {
if (State == 0x3A) {
return TRUE;
}
@@ -978,7 +979,9 @@ static BOOL CheckDVDCommandStatus(DVDCommandBlock *block) {
case 4:
case 5:
if (State == 7 || State == 9 || State == 10) {
CoverOpenTime = __OSGetSystemTime();
u64 systemTime = __OSGetSystemTime();
CoverOpenTimeLow = (u32)systemTime;
CoverOpenTimeHigh = (u32)(systemTime >> 32);
State = BS2_STT_66;
} else {
State = BS2_STT_NO_DISK;
@@ -1015,11 +1018,11 @@ static BOOL CheckDVDCommandStatus(DVDCommandBlock *block) {
return FALSE;
}
static void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block);
static void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block);
static void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block);
void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block);
void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block);
void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block);
static void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block) {
void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block) {
s32 ret;
if (CancelNand != 0) {
@@ -1060,7 +1063,7 @@ static void BS2NANDDivideCallback(s32 result, NANDCommandBlock *block) {
}
}
static void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block) {
void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block) {
NandCompletion = callback;
NandOperation = 2;
NandLength = length;
@@ -1076,7 +1079,7 @@ static void BS2NANDDivideReadAsync(NANDFileInfo *info, void *buffer, u32 length,
}
}
static void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block) {
void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32 length, NANDCallback callback, NANDCommandBlock *block) {
NandCompletion = callback;
NandOperation = 1;
NandLength = length;
@@ -1092,9 +1095,7 @@ static void BS2NANDDivideWriteAsync(NANDFileInfo *info, const void *buffer, u32
}
}
static BOOL CheckBS2CommandStatus() {
static u32 CacheCommandComplete = 0;
BOOL CheckBS2CommandStatus() {
if (CheckDVDCommandStatus(&Block) == 0) {
BS2Report("DVD command is issuing\n");
return 0;
@@ -1177,8 +1178,8 @@ static BOOL CheckBS2CommandStatus() {
if (BS2BootCaching != 0) {
BS2Report("Write partition ifno\n");
NandPending = 1;
CacheCommandComplete = 1;
CacheLength += OSRoundUp32B(((DVDGameTOC *)DataToc)->partitionCount * sizeof(DVDPartitionInfo)) + 32;
CacheCommandComplete = 1;
if ((unsigned int)CacheLength > 0xb00000) {
BS2NANDCallback(-1, NULL);
return 1;
@@ -1298,7 +1299,7 @@ static BOOL CheckBS2CommandStatus() {
return TRUE;
}
static void BS2InquiryAsync(void *buffer, s32 length, u32 offset) {
void BS2InquiryAsync(void *buffer, s32 length, u32 offset) {
if (BS2BootFromCache) {
BS2Report("Unencrypted read from cache.dat\n");
NandPending = 1;
@@ -1308,7 +1309,7 @@ static void BS2InquiryAsync(void *buffer, s32 length, u32 offset) {
}
}
static void BS2ReadDiskID(void *buffer, s32 length, u32 offset) {
void BS2ReadDiskID(void *buffer, s32 length, u32 offset) {
if (BS2BootFromCache) {
BS2Report("Read from cache.dat\n");
NandPending = 1;
@@ -1320,24 +1321,25 @@ static void BS2ReadDiskID(void *buffer, s32 length, u32 offset) {
}
BS2State BS2Tick() {
static u32 AudioBufferUnconfigured;
u32 interruptsEnabled = OSDisableInterrupts();
u32 loaderAddress;
u32 loaderLength;
u32 loaderOffset;
u32 titleCode;
s32 titlePrefix;
u8 titleCharacters[4];
struct {
u32 offset;
u32 length;
u32 address;
} loaderRead;
DVDFileInfo bannerFile;
u32 bannerAddress;
u32 discRegion;
s32 status;
u64 currentTime;
BOOL regionMatches;
char productRegion;
u32 iosHigh;
char *ticketByte;
u32 entryCount;
DVDGameTOC *dataToc;
u32 readInterruptsEnabled;
u32 readAddress;
const char *discTitle;
const DVDDiskID *bootDisc;
@@ -1347,16 +1349,17 @@ BS2State BS2Tick() {
BS2Report("Drive Reset : %d\n", BS2DriveReset);
BS2Report("Wait Spinup : %d\n", BS2WaitSpinup);
BS2Report("Boot From Cache : %d\n", BS2BootFromCache);
DvdProgress = (u32 *)0x800030d4;
DvdProgress = (u32 *)&(*(u32 *)0x800030d4);
PartitionParams.numTmdBytes = 0;
PartitionParams.numCertBytes = 0;
PartitionParams.dataWordOffset = 0;
*DvdProgress = 0;
(*(u32 *)0x800030d4) = 0;
DvdTransferred = 0;
DvdTransferLength = 0;
status = BS2NoDisk;
AudioBufferUnconfigured = 1;
CoverBlock.state = 0;
if (BS2NoDisk != 0)
if (status != 0)
State = BS2_STT_NO_DISK;
else if (BS2DriveReset != 0)
State = BS2_STT_2;
@@ -1435,14 +1438,13 @@ BS2State BS2Tick() {
case 5:
status = CheckBS2CommandStatus();
if (status != 0) {
OSBootInfo *bootInfo = (OSBootInfo *)OSPhysicalToCached(OS_ADDR_BOOT_INFO);
if ((bootInfo->consoleType & 0xf0000000) == 0) {
if ((((const OSBootInfo *)0x80000000)->consoleType & 0xf0000000) == 0) {
__OSDeviceCode = 0x8002;
State = BS2_STT_8;
} else {
__OSDeviceCode = DriveInfo.deviceCode | 0x8000;
State = BS2_STT_8;
}
State = BS2_STT_8;
}
break;
case 6:
@@ -1569,9 +1571,8 @@ invalidGcRegion:
BS2Report("length ... 0x%08X\n", 0x20);
BS2Report("numGamePartitions ... 0x%08X\n", (*(DVDGameTOC **)&GameToc)->partitionCount);
BS2Report("partitionInfos ... 0x%08X\n", (u32)(*(DVDGameTOC **)&GameToc)->partitionInfo);
dataToc = (DVDGameTOC *)GameTOCBuf + 1;
DataToc = (u32)dataToc;
BS2Report("numGamePartitions ... 0x%08X\n", dataToc->partitionCount);
DataToc = (u32)((DVDGameTOC *)GameTOCBuf + 1);
BS2Report("numGamePartitions ... 0x%08X\n", ((DVDGameTOC *)GameTOCBuf)[1].partitionCount);
BS2Report("partitionInfos ... 0x%08X\n", ((DVDGameTOC *)DataToc)->partitionInfo);
State = BS2_STT_17;
case 0x11:
@@ -1728,23 +1729,21 @@ invalidRvlRegion:
((void (*)(void *))((*(void **)&LoaderInit)))((void *)BS2Report);
BS2Report("\nApploader Initialized\n");
State = BS2_STT_29;
case 0x1d: {
u32 readInterruptsEnabled;
status = ((int (*)(u32 *, u32 *, u32 *))((*(void **)&LoaderMain)))(&loaderAddress, &loaderLength, &loaderOffset);
case 0x1d:
status = ((int (*)(u32 *, u32 *, u32 *))((*(void **)&LoaderMain)))(&loaderRead.address, &loaderRead.length, &loaderRead.offset);
if (status != 0) {
BS2Report("Addr [0x%x] length [0x%x] offset [0x%x]\n", loaderAddress, loaderLength, loaderOffset);
BS2Report("Addr [0x%x] length [0x%x] offset [0x%x]\n", loaderRead.address, loaderRead.length, loaderRead.offset);
readInterruptsEnabled = OSDisableInterrupts();
DVDReadAbsAsyncForBS(&Block, (void *)loaderAddress, loaderLength, loaderOffset >> __DVDLayoutFormat, BS2DVDCallback);
DVDReadAbsAsyncForBS(&Block, (void *)loaderRead.address, loaderRead.length, loaderRead.offset >> __DVDLayoutFormat, BS2DVDCallback);
if (*(s32 *)DvdProgress != 0) {
DvdReadPending = 1;
DvdTransferLength = loaderLength;
DvdTransferLength = loaderRead.length;
}
OSRestoreInterrupts(readInterruptsEnabled);
State = BS2_STT_30;
} else
State = BS2_STT_31;
break;
}
case 0x1e:
status = CheckDVDCommandStatus(&Block);
if (status != 0)
@@ -1878,7 +1877,9 @@ invalidRvlRegion:
(u32)((ESTitleMeta *)CurrentTmd)->head.sysVersion);
BS2Report("Title ID ... 0x%08X%08X\n", (u32)(((ESTitleMeta *)CurrentTmd)->head.titleId >> 32),
(u32)((ESTitleMeta *)CurrentTmd)->head.titleId);
RequiredIos = ((ESTitleMeta *)CurrentTmd)->head.sysVersion;
iosHigh = (u32)(((ESTitleMeta *)CurrentTmd)->head.sysVersion >> 32);
RequiredIosLow = (u32)((ESTitleMeta *)CurrentTmd)->head.sysVersion;
RequiredIosHigh = iosHigh;
titleCode = (u32)((ESTitleMeta *)CurrentTmd)->head.titleId;
TitleCode = titleCode;
if (((ESTitleMeta *)CurrentTmd)->head.sysVersion == 0x0000000100000010ULL) {
@@ -2016,27 +2017,25 @@ invalidRvlRegion:
((void (*)(void *))((*(void **)&LoaderInit)))((void *)OSReport);
BS2Report("\nApploader Initialized\n");
State = BS2_STT_43;
case 0x2b: {
u32 readInterruptsEnabled;
status = ((int (*)(u32 *, u32 *, u32 *))((*(void **)&LoaderMain)))(&loaderAddress, &loaderLength, &loaderOffset);
case 0x2b:
status = ((int (*)(u32 *, u32 *, u32 *))((*(void **)&LoaderMain)))(&loaderRead.address, &loaderRead.length, &loaderRead.offset);
if (status != 0) {
BS2Report("Addr [0x%x] length [0x%x] offset [0x%x]\n", loaderAddress, loaderLength, loaderOffset);
BS2Report("Addr [0x%x] length [0x%x] offset [0x%x]\n", loaderRead.address, loaderRead.length, loaderRead.offset);
readInterruptsEnabled = OSDisableInterrupts();
BS2ReadDiskID((void *)loaderAddress, loaderLength, loaderOffset >> __DVDLayoutFormat);
readAddress = loaderAddress;
LoaderLength = loaderLength;
BS2ReadDiskID((void *)loaderRead.address, loaderRead.length, loaderRead.offset >> __DVDLayoutFormat);
readAddress = loaderRead.address;
LoaderLength = loaderRead.length;
LoaderAddress = readAddress;
LoaderOffset = loaderOffset;
LoaderOffset = loaderRead.offset;
if ((*(s32 *)DvdProgress != 0) && (BS2BootFromCache == 0)) {
DvdReadPending = 1;
DvdTransferLength = loaderLength;
DvdTransferLength = loaderRead.length;
}
OSRestoreInterrupts(readInterruptsEnabled);
State = BS2_STT_44;
} else
State = BS2_STT_45;
break;
}
case 0x2c:
status = CheckBS2CommandStatus();
if (status != 0)
@@ -2059,15 +2058,13 @@ invalidRvlRegion:
BannerAllocation = status;
if (status == 0)
OSPanic("BS2Mach.c", 0x12c8, "BS2 ERROR >>> Cannnot alloc 0x%08x from MEMAllocator", bannerFile.length);
bannerAddress = BannerAllocation + 32 - BannerAllocation % 32;
BannerLength = bannerFile.length;
BannerBuffer = bannerAddress;
BannerBuffer = BannerAllocation + 32 - BannerAllocation % 32;
BS2Report("BannerBufferAddr : %08X\n", BannerBuffer);
} else {
if ((BannerBuffer != 0) && (BannerLength != 0)) {
if (BannerLength < ((bannerFile.length + 0x1fU) & 0xffffffe0))
OSPanic("BS2Mach.c", 0x12d3, "BS2 ERROR >>> Banner buffer is not enough to load banner file (0x%08x)",
bannerFile.length);
OSPanic("BS2Mach.c", 0x12d3, "BS2 ERROR >>> Banner buffer is not enough to load banner file (0x%08x)");
BS2Report("BannerBufferAddr : %08X\n", BannerBuffer);
} else
OSPanic("BS2Mach.c", 0x12da, "BS2 ERROR >>> MEMAllocator and banner buffer is not set");
@@ -2171,7 +2168,7 @@ invalidRvlRegion:
BS2BootFromCache = 0;
BS2BootCaching = 1;
LoadingTitle = 0;
switch (((volatile DVDCommandBlock *)&Block)->state) {
switch (Block.state) {
case 4:
case 5:
CheckDVDCommandStatus(&Block);
@@ -2316,7 +2313,7 @@ invalidRvlRegion:
break;
case 0x42:
currentTime = __OSGetSystemTime();
if ((OSTime)(currentTime - CoverOpenTime) < OSMillisecondsToTicks((OSTime)350))
if ((OSTime)(currentTime - (((u64)CoverOpenTimeHigh << 32) | CoverOpenTimeLow)) < OSMillisecondsToTicks((OSTime)350))
break;
currentTime = __OSGetSystemTime();
CoverPollTime = currentTime;

View File

@@ -9,13 +9,14 @@
#include <string.h>
static u32 Flags1[BS2_UPDATE_ENTRY_COUNT];
static OSThread Thread;
static u8 ThreadStack[4096];
static BS2UpdateHeader UpdateHeader0 ALIGN32;
static BS2UpdateHeader UpdateHeader1 ALIGN32;
static u32 Flags0[BS2_UPDATE_ENTRY_COUNT] = {0};
static u32 Flags1[BS2_UPDATE_ENTRY_COUNT] = {0};
static OSThread Thread = {0};
static u8 ThreadStack[4096] = {0};
static BS2UpdateHeader UpdateHeader0 ALIGN32 = {0};
static BS2UpdateHeader UpdateHeader1 ALIGN32 = {0};
BS2UpdateEntry DiscEntries[BS2_UPDATE_ENTRY_COUNT] ADDRESS(0x80480000);
#define UPDATE_DISC_ENTRIES ((BS2UpdateEntry*)0x80480000)
s32 WADCheckImport(u64 titleId, u16 titleVersion);
s32 WADImportDVDForBS(const char* path, void* buffer, u32 length);
@@ -31,8 +32,8 @@ static u32 RebootRequired = 0;
static BOOL ContainsSeatTitles = 0;
static u32 UpdateImportState = 0;
static u32 UpdateImportResult = 0;
volatile u32 StartUpdate = 0;
volatile u32 CancelUpdate = 0;
u32 StartUpdate = 0;
u32 CancelUpdate = 0;
static u32 UpdateProgress = 0;
static volatile s32 rc = 0;
static u64 VersionIOS = 0;
@@ -49,44 +50,71 @@ char* getSuffix(const char* path) {
return suffix;
}
static void* UpdateThread(void* argument);
void BS2UpdateInit(void* allocator) {
BS2Report("initialize BS2Update\n");
ConsoleType = OSGetConsoleType();
VersionES = __OSGetHollywoodRev();
VersionMEM2 = OSGetPhysicalMem2Size();
__OSGetIOSRev((OSIOSRev*)&VersionIOS);
BS2Report("Console Type : %08X\n", ConsoleType);
BS2Report("Hollywood Rev : %08X\n", VersionES);
BS2Report("MEM2 Size : %08X\n", VersionMEM2);
MemAllocator = allocator;
State = 0;
CurrentEntry = NULL;
pEntries = NULL;
EntriesCount = 0;
memset(UPDATE_DISC_ENTRIES, 0, 0x40000);
memset(EntriesToImport, 0, 0x40000);
memset(Flags1, 0, sizeof(Flags1));
BS2Report("Create update thread\n");
OSCreateThread(&Thread, UpdateThread, NULL, ThreadStack + sizeof(ThreadStack),
sizeof(ThreadStack), 31, OS_THREAD_ATTR_DETACH);
OSResumeThread(&Thread);
}
static inline u32 BS2SelectUpdateEntries(void) {
static u32 Flags0[BS2_UPDATE_ENTRY_COUNT];
BOOL missingFile;
u32 index;
u32 selectedCount;
u32 requiredBytes;
u32 requiredInodes;
u32 channelCount;
u32 index;
BS2UpdateEntry* seatEntries;
BS2UpdateEntry* selectedSeats;
u32 selectedSeatCount;
BOOL regionValid;
u32 titleRegion;
u32 freeChannels;
u32 freeBlocks;
u32 freeInodes;
u32 ticketCount;
char productArea[8];
u64 titleId;
char updatePath[32];
char seatPath[32];
DVDFileInfo file;
struct {
u32 freeChannels;
u32 freeBlocks;
u32 freeInodes;
u32 ticketCount;
char productArea[8];
u64 titleId;
char updatePath[32];
char seatPath[32];
DVDFileInfo file;
} scratch;
missingFile = FALSE;
selectedCount = 0;
requiredBytes = 0;
requiredInodes = 0;
channelCount = 0;
freeChannels = 0;
freeBlocks = 0;
freeInodes = 0;
scratch.freeChannels = 0;
scratch.freeBlocks = 0;
scratch.freeInodes = 0;
selectedSeatCount = 0;
State = 0;
ContainsSeatTitles = FALSE;
if (ES_GetTitleId(&titleId) != ES_ERR_OK) {
if (ES_GetTitleId(&scratch.titleId) != ES_ERR_OK) {
regionValid = FALSE;
} else {
titleRegion = (u8)titleId;
titleRegion = (u8)scratch.titleId;
switch (SCGetProductArea()) {
case SC_PRODUCT_AREA_JPN:
case SC_PRODUCT_AREA_TWN:
@@ -131,23 +159,23 @@ product_region_checked:
selectedCount = 0;
goto selection_complete;
}
if (!SCGetProductAreaString(productArea, sizeof(productArea))) {
if (!SCGetProductAreaString(scratch.productArea, sizeof(scratch.productArea))) {
BS2Report("Error: failed to get product information.");
selectedCount = 0;
goto selection_complete;
}
strcpy(updatePath, "__update.inf");
strcat(updatePath, ".");
strcat(updatePath, productArea);
if (DVDConvertPathToEntrynum(updatePath) < 0) {
strcpy(scratch.updatePath, "__update.inf");
strcat(scratch.updatePath, ".");
strcat(scratch.updatePath, scratch.productArea);
if (DVDConvertPathToEntrynum(scratch.updatePath) < 0) {
switch (SCGetProductArea()) {
case 0:
case 1:
case 2:
case 6:
case 11:
strcpy(updatePath, "__update.inf");
if (DVDConvertPathToEntrynum(updatePath) < 0) {
strcpy(scratch.updatePath, "__update.inf");
if (DVDConvertPathToEntrynum(scratch.updatePath) < 0) {
BS2Report("Error: update information file is not found.");
selectedCount = 0;
goto selection_complete;
@@ -159,13 +187,13 @@ product_region_checked:
goto selection_complete;
}
}
BS2Report("%s is found.\n", updatePath);
if (!DVDOpen(updatePath, &file)) {
BS2Report("%s is found.\n", scratch.updatePath);
if (!DVDOpen(scratch.updatePath, &scratch.file)) {
BS2Report("Error: failed to open update information file.");
selectedCount = 0;
goto selection_complete;
}
if (DVDReadPrio(&file, &UpdateHeader0, sizeof(UpdateHeader0), 0, 2) < 0) {
if (DVDReadPrio(&scratch.file, &UpdateHeader0, sizeof(UpdateHeader0), 0, 2) < 0) {
BS2Report("Error: failed to read update information header.");
selectedCount = 0;
goto selection_complete;
@@ -186,24 +214,25 @@ product_region_checked:
selectedCount = 0;
goto selection_complete;
}
if (DVDReadPrio(&file, DiscEntries, UpdateHeader0.wadCount * sizeof(BS2UpdateEntry), 32, 2) < 0) {
if (DVDReadPrio(&scratch.file, UPDATE_DISC_ENTRIES, UpdateHeader0.wadCount * sizeof(BS2UpdateEntry), 32, 2) < 0) {
BS2Report("Error: failed to read update information.");
selectedCount = 0;
goto selection_complete;
}
{
BS2UpdateEntry *discEntries = UPDATE_DISC_ENTRIES;
for (index = 0; index < UpdateHeader0.wadCount; index++) {
if ((DiscEntries[index].attr & 1) == 0) {
if ((discEntries[index].attr & 1) == 0) {
continue;
}
switch (OSGetPhysicalMem2Size()) {
case 0x4000000:
if ((DiscEntries[index].depend & 1) == 0) {
if ((discEntries[index].depend & 1) == 0) {
continue;
}
break;
case 0x8000000:
if ((DiscEntries[index].depend & 2) == 0) {
if ((discEntries[index].depend & 2) == 0) {
continue;
}
break;
@@ -213,37 +242,37 @@ product_region_checked:
selectedCount = 0;
goto selection_complete;
}
if (DVDOpen(DiscEntries[index].path, &file) < 0) {
BS2Report("%s is not found\n", DiscEntries[index].path);
if (DVDOpen(discEntries[index].path, &scratch.file) < 0) {
BS2Report("%s is not found\n", discEntries[index].path);
missingFile = TRUE;
continue;
}
DiscEntries[index].size = file.length;
if (DiscEntries[index].type == 0) {
discEntries[index].size = scratch.file.length;
if (discEntries[index].type == 0) {
selectedCount++;
} else if (WADCheckImport(DiscEntries[index].titleId, DiscEntries[index].titleVersion) == 0) {
BS2Report("%s is already installed\n", DiscEntries[index].path);
} else if (WADCheckImport(discEntries[index].titleId, discEntries[index].titleVersion) == 0) {
BS2Report("%s is already installed\n", discEntries[index].path);
Flags1[index] = 0;
} else {
BS2Report("%s\n", DiscEntries[index].path);
memcpy(&EntriesToImport[selectedCount], &DiscEntries[index], sizeof(BS2UpdateEntry));
BS2Report("%s\n", discEntries[index].path);
memcpy(&EntriesToImport[selectedCount], &discEntries[index], sizeof(BS2UpdateEntry));
selectedCount++;
Flags1[index] = 1;
}
}
}
strcpy(seatPath, "__seatholder.inf");
strcat(seatPath, ".");
strcat(seatPath, productArea);
if (DVDConvertPathToEntrynum(seatPath) < 0) {
strcpy(scratch.seatPath, "__seatholder.inf");
strcat(scratch.seatPath, ".");
strcat(scratch.seatPath, scratch.productArea);
if (DVDConvertPathToEntrynum(scratch.seatPath) < 0) {
switch (SCGetProductArea()) {
case 0:
case 1:
case 2:
case 6:
case 11:
strcpy(seatPath, "__seatholder.inf");
if (DVDConvertPathToEntrynum(seatPath) < 0) {
strcpy(scratch.seatPath, "__seatholder.inf");
if (DVDConvertPathToEntrynum(scratch.seatPath) < 0) {
BS2Report("Error: update seatholder information file is not found.");
goto seats_done;
}
@@ -253,12 +282,12 @@ product_region_checked:
goto seats_done;
}
}
BS2Report("%s is found.\n", seatPath);
if (!DVDOpen(seatPath, &file)) {
BS2Report("%s is found.\n", scratch.seatPath);
if (!DVDOpen(scratch.seatPath, &scratch.file)) {
BS2Report("Error: failed to open update information file.");
goto seats_done;
}
if (DVDReadPrio(&file, &UpdateHeader1, sizeof(UpdateHeader1), 0, 2) < 0) {
if (DVDReadPrio(&scratch.file, &UpdateHeader1, sizeof(UpdateHeader1), 0, 2) < 0) {
BS2Report("Error: failed to read update information header.");
goto seats_done;
}
@@ -271,9 +300,11 @@ product_region_checked:
BS2Report("Error: found too many extra entries.");
goto seats_done;
}
seatEntries = DiscEntries + UpdateHeader0.wadCount;
selectedSeats = EntriesToImport + selectedCount;
if (DVDReadPrio(&file, seatEntries, UpdateHeader1.wadCount * sizeof(BS2UpdateEntry), 32, 2) < 0) {
seatEntries = UPDATE_DISC_ENTRIES;
seatEntries += UpdateHeader0.wadCount;
selectedSeats = EntriesToImport;
selectedSeats += selectedCount;
if (DVDReadPrio(&scratch.file, seatEntries, UpdateHeader1.wadCount * sizeof(BS2UpdateEntry), 32, 2) < 0) {
BS2Report("Error: failed to read update information.");
goto seats_done;
}
@@ -306,7 +337,7 @@ product_region_checked:
State = 5;
goto seats_done;
}
if (DVDOpen(seatEntries[index].path, &file) < 0) {
if (DVDOpen(seatEntries[index].path, &scratch.file) < 0) {
BS2Report("%s is not found\n", seatEntries[index].path);
missingFile = TRUE;
continue;
@@ -314,11 +345,11 @@ product_region_checked:
if (seatEntries[index].type != 7) {
continue;
}
if (ES_GetTicketViews(seatEntries[index].titleId, NULL, &ticketCount) != ES_ERR_OK) {
if (ES_GetTicketViews(seatEntries[index].titleId, NULL, &scratch.ticketCount) != ES_ERR_OK) {
BS2Report("Faild to get eTicket views.\n");
continue;
}
if (ticketCount != 0) {
if (scratch.ticketCount != 0) {
continue;
}
if (SCGetWwwRestriction() && ((u32)(seatEntries[index].titleId & 0xFFFFFFFFULL) & 0xFFFFFF00) == 0x48414400) {
@@ -341,23 +372,23 @@ product_region_checked:
requiredInodes += seatEntries[index].inodes;
}
if (channelCount != 0) {
if (!SCGetFreeChannelAppCount(&freeChannels)) {
if (!SCGetFreeChannelAppCount(&scratch.freeChannels)) {
BS2Report("Error: cannot get channel count.");
goto seats_done;
}
if (NANDSecretGetUserAvailableArea(&freeBlocks, &freeInodes) != NAND_RESULT_OK) {
if (NANDSecretGetUserAvailableArea(&scratch.freeBlocks, &scratch.freeInodes) != NAND_RESULT_OK) {
BS2Report("Error: cannot get free user blocks.");
goto seats_done;
}
if ((freeBlocks << 14) < 0x1004000 || requiredBytes > (freeBlocks << 14) - 0x1004000) {
if ((scratch.freeBlocks << 14) < 0x1004000 || requiredBytes > (scratch.freeBlocks << 14) - 0x1004000) {
BS2Report("Sufficient user blocks doesn't exist.");
goto seats_done;
}
if (freeInodes < requiredInodes + 36) {
if (scratch.freeInodes < requiredInodes + 36) {
BS2Report("Sufficient user inodes doesn't exist.");
goto seats_done;
}
if (channelCount > freeChannels) {
if (channelCount > scratch.freeChannels) {
BS2Report("No enough blank channel.");
goto seats_done;
}
@@ -379,13 +410,14 @@ seats_done:
pEntries = EntriesToImport;
pFlags = Flags1;
{
BS2UpdateEntry *discEntries = UPDATE_DISC_ENTRIES;
for (index = 0; index < UpdateHeader0.wadCount; index++) {
if (Flags1[index] == 1) {
BS2Report("File: %s\n", DiscEntries[index].path);
BS2Report("Name: %s\n", DiscEntries[index].dataName);
BS2Report("Info: %s\n", DiscEntries[index].dataMeta);
BS2Report("Attr: %s\n", (DiscEntries[index].attr & 1) ? "Critical" : "Non critical");
BS2Report(" %s\n", (DiscEntries[index].attr & 2) ? "Reboot" : "Not reboot");
BS2Report("File: %s\n", discEntries[index].path);
BS2Report("Name: %s\n", discEntries[index].dataName);
BS2Report("Info: %s\n", discEntries[index].dataMeta);
BS2Report("Attr: %s\n", (discEntries[index].attr & 1) ? "Critical" : "Non critical");
BS2Report(" %s\n", (discEntries[index].attr & 2) ? "Reboot" : "Not reboot");
}
}
}
@@ -393,31 +425,6 @@ selection_complete:
return selectedCount;
}
static void* UpdateThread(void* argument);
void BS2UpdateInit(void* allocator) {
BS2Report("initialize BS2Update\n");
ConsoleType = OSGetConsoleType();
VersionES = __OSGetHollywoodRev();
VersionMEM2 = OSGetPhysicalMem2Size();
__OSGetIOSRev((OSIOSRev*)&VersionIOS);
BS2Report("Console Type : %08X\n", ConsoleType);
BS2Report("Hollywood Rev : %08X\n", VersionES);
BS2Report("MEM2 Size : %08X\n", VersionMEM2);
MemAllocator = allocator;
State = 0;
CurrentEntry = NULL;
pEntries = NULL;
EntriesCount = 0;
memset(DiscEntries, 0, 0x40000);
memset(EntriesToImport, 0, 0x40000);
memset(Flags1, 0, sizeof(Flags1));
BS2Report("Create update thread\n");
OSCreateThread(&Thread, UpdateThread, NULL, ThreadStack + sizeof(ThreadStack),
sizeof(ThreadStack), 31, OS_THREAD_ATTR_DETACH);
OSResumeThread(&Thread);
}
static void* UpdateThread(void* argument) {
u32 index;
s32 importResult;
@@ -435,24 +442,25 @@ static void* UpdateThread(void* argument) {
State = 1;
UpdateProgress = 0;
{
BS2UpdateEntry *discEntries = UPDATE_DISC_ENTRIES;
for (;;) {
if (StartUpdate != 0) {
if (UpdateProgress < UpdateHeader0.wadCount) {
BS2Report("Progress : %d\n", UpdateProgress);
if (Flags1[UpdateProgress] == 1) {
const char* path = DiscEntries[UpdateProgress].path;
const char* path = discEntries[UpdateProgress].path;
BS2Report("Import : %s\n", path);
State = 2;
CurrentEntry = &DiscEntries[UpdateProgress];
if (DiscEntries[UpdateProgress].type == 0) {
CurrentEntry = &discEntries[UpdateProgress];
if (discEntries[UpdateProgress].type == 0) {
UpdateProgress++;
continue;
}
if (((const BS2UpdateEntry *)DiscEntries)[UpdateProgress].type == 1) {
if (((const BS2UpdateEntry *)discEntries)[UpdateProgress].type == 1) {
BS2Report("BS2WADImportDVD : ");
index = UpdateProgress;
if (strcmp(getSuffix(DiscEntries[index].path), "wad") == 0) {
importResult = WADImportDVDForBS(DiscEntries[index].path, (void*)BS2_UPDATE_ADDRESS, 0x80000);
if (strcmp(getSuffix(discEntries[index].path), "wad") == 0) {
importResult = WADImportDVDForBS(discEntries[index].path, (void*)BS2_UPDATE_ADDRESS, 0x80000);
} else {
importResult = 0;
}
@@ -460,20 +468,20 @@ static void* UpdateThread(void* argument) {
BS2Report("rc = %d\n", rc);
if (rc != 0) {
NANDLoggingAddMessageAsync(NULL, "BS2 error. [%d] titleID: 0x%016llx %s line: %d",
rc, DiscEntries[UpdateProgress].titleId, "BS2Update.c", 0x3F5);
rc, discEntries[UpdateProgress].titleId, "BS2Update.c", 0x3F5);
State = 5;
UpdateProgress = UpdateHeader0.wadCount + 1;
break;
}
if ((DiscEntries[UpdateProgress].attr & 2) != 0) {
if ((discEntries[UpdateProgress].attr & 2) != 0) {
RebootRequired = 1;
}
UpdateProgress++;
} else {
BS2Report("BS2WADImportDVDEx : ");
index = UpdateProgress;
if (strcmp(getSuffix(DiscEntries[index].path), "wad") == 0) {
importResult = WADImportDVDExForBS(DiscEntries[index].path, (void*)BS2_UPDATE_ADDRESS, 0x80000);
if (strcmp(getSuffix(discEntries[index].path), "wad") == 0) {
importResult = WADImportDVDExForBS(discEntries[index].path, (void*)BS2_UPDATE_ADDRESS, 0x80000);
} else {
importResult = 0;
}
@@ -481,18 +489,18 @@ static void* UpdateThread(void* argument) {
BS2Report("rc = %d\n", rc);
if (rc != 0) {
NANDLoggingAddMessageAsync(NULL, "BS2 error. [%d] titleID: 0x%016llx %s line: %d",
rc, DiscEntries[UpdateProgress].titleId, "BS2Update.c", 0x40F);
rc, discEntries[UpdateProgress].titleId, "BS2Update.c", 0x40F);
State = 5;
UpdateProgress = UpdateHeader0.wadCount + 1;
break;
}
if ((DiscEntries[UpdateProgress].attr & 2) != 0) {
if ((discEntries[UpdateProgress].attr & 2) != 0) {
RebootRequired = 1;
}
UpdateProgress++;
}
} else {
const char* path = DiscEntries[UpdateProgress].path;
const char* path = discEntries[UpdateProgress].path;
BS2Report("Not import : %s\n", path);
UpdateProgress++;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,3 @@
int gDpdWaitFrm = 0;
#include "iplwww/www_wiisetting.h"
#include <string.h>
@@ -11,18 +9,16 @@ int gDpdWaitFrm = 0;
#include "iplwww/www_browser.h"
int gDpdWaitFrm = 0;
BOOL gEnableDpd = TRUE;
namespace www {
namespace wiisetting {
struct ReportInfo {
char tickTimerTag[12];
char warningTag[10];
char eventTag[10];
const char* MessageArr[6];
};
ReportInfo reportInfo = {"[TickTimer]", "[Warning]", "[[Event]]", {NULL, NULL, NULL, NULL, NULL, NULL}};
static const char emptyString[] = "";
char MSG_TICK_TIMER_TAG[12] = "[TickTimer]";
char MSG_WARNING_TAG[10] = "[Warning]";
char MSG_EVENT_TAG[10] = "[[Event]]";
const char* Message[] = {NULL, NULL, NULL, NULL, emptyString, NULL};
const u8 kbLangUsaLUT[][0x30] = {
{
@@ -154,8 +150,8 @@ namespace www {
extern const char* strProps[FORM_ID_MAX];
int getStringPropertyIdx(const char* targetStr) {
const char* names[ARRAY_LENGTH(strProps)];
const char* const* sourceName = strProps - 1;
const char** destinationName = names - 1;
const char* const* sourceName = strProps - 1;
for (int i = 0; i < (ARRAY_LENGTH(names) >> 1); i++) {
*(++destinationName) = *(++sourceName);
*(++destinationName) = *(++sourceName);
@@ -173,19 +169,9 @@ namespace www {
return -1;
}
static inline int getSettingProperty(const char* str, WWWJSPluginValue* val);
static inline void selectEuropeanKeyboardLanguage(u32& kbLang) {
int i;
for (i = 0; i < 0x3b; i++) {
if (sWiiData.data[WB_ID_COUNTRY] == kbLangEurLUT[ipl::System::getLanguage() - 1][i] + 0x40) {
kbLang = (u8)(i + 0x40);
break;
}
}
}
int Getter_(WWWJSPluginObj* obj, const char* str, WWWJSPluginValue* val) {
int retVal;
int strPropIdx;
if (strcmp(str, "CallOSReport") == 0) {
int data;
if (opera_callbacks->globalGet(obj, 0, 0, wiiOSReport, wiiOSReport, "", 0, (WWWJSPluginValueData*)&data) < 0) {
@@ -205,15 +191,6 @@ namespace www {
return 7;
}
}
return getSettingProperty(str, val);
}
static inline int getSettingProperty(const char* str, WWWJSPluginValue* val) {
int privacyIndex;
int retVal;
SetStringBuf* strBuf;
int maskLength;
int strPropIdx;
if (!(writeBackID == WB_ID_PROGRESSIVE || writeBackID == WB_ID_PAL || writeBackID == WB_ID_COUNTRY || writeBackID == WB_ID_LIGHT ||
writeBackID == WB_ID_LANGUAGE || writeBackID == WB_ID_RATE)) {
writeBackID = WB_ID_RESET;
@@ -304,13 +281,14 @@ namespace www {
memset(pString->asterisks, 0, sizeof(pString->asterisks));
OSReport("mode %d %d\n", saveData, (u16)ipl::ncd::NCDSetting::getPrivacyMode());
if (saveData == (u16)ipl::ncd::NCDSetting::getPrivacyMode()) {
int i;
OSReport("len ::: %d\n", ipl::ncd::NCDSetting::getPrivacyLen());
for (privacyIndex = 0; privacyIndex < ipl::ncd::NCDSetting::getPrivacyLen(); privacyIndex++) {
pString->asterisks[privacyIndex] = '*';
for (i = 0; i < ipl::ncd::NCDSetting::getPrivacyLen(); i++) {
pString->asterisks[i] = '*';
}
if (0x20 < privacyIndex) {
if (0x20 < i) {
pString->asterisks[0x20] = '\n';
pString->asterisks[privacyIndex] = '*';
pString->asterisks[i] = '*';
}
} else {
memset(pString->securityKey, 0, sizeof(pString->securityKey));
@@ -320,11 +298,13 @@ namespace www {
}
case FORM_ID_DUMMY_SECURITY_KEY: {
memset(pString->asterisks, 0, sizeof(pString->asterisks));
for (maskLength = 0; maskLength < strlen((strBuf = pString)->securityKey); strBuf->asterisks[maskLength++] = '*') {
SetStringBuf* strBuf;
int i;
for (i = 0; i < strlen((strBuf = pString)->securityKey); strBuf->asterisks[i++] = '*') {
}
if (maskLength > 0x20) {
if (i > 0x20) {
pString->asterisks[0x20] = '\n';
pString->asterisks[maskLength] = '*';
pString->asterisks[i] = '*';
}
val->data.jsStr = pString->asterisks;
break;
@@ -542,7 +522,12 @@ namespace www {
}
}
} else if ((u32)ipl::System::getRegion() == SC_PRODUCT_AREA_EUR) {
selectEuropeanKeyboardLanguage(kbLang);
for (int i = 0; i < 0x3b; i++) {
if (sWiiData.data[WB_ID_COUNTRY] == kbLangEurLUT[ipl::System::getLanguage() - 1][i] + 0x40) {
kbLang = (u8)(i + 0x40);
break;
}
}
}
val->data.jsDouble = (u8)kbLang;
}

View File

@@ -1,7 +1,5 @@
#define TI_CANDIDATEBOX_IMPLEMENTATION
#define TI_CANDIDATEBOX_SAMPLE_CLASS
#include "keyboard/tiCandidateBox.h"
#undef TI_CANDIDATEBOX_SAMPLE_CLASS
#include "keyboard/tiManager.h"
@@ -62,7 +60,12 @@ namespace textinput {
{ANM_InvalidOff, "fs_VK_predictInput_a_invalidMode_OFF.brlan"},
};
static const PaneToAnimation csPaneToAnimation[] = {
struct CandidatePaneData {
PaneToAnimation panes[26];
char tail[12];
};
extern "C" const CandidatePaneData scCandidatePaneData __attribute__((aligned(8))) = {{
{KT_CandidateText, "N_predictInput", 1, NULL, {&csAninationFile[0]}},
{KT_ScrollButton,
"P_prdc_scrl_Left",
@@ -193,7 +196,22 @@ namespace textinput {
6,
NULL,
{&csAninationFile[0], &csAninationFile[8], &csAninationFile[9], &csAninationFile[10], &csAninationFile[11], &csAninationFile[12]}},
};
}, {"P_OffBtn"}};
extern "C" char scPaneNameTable[132] =
"B_OffBtn\0\0\0\0"
"P_JPOffBtn\0\0"
"P_CNOffBtn\0\0"
"P_CNOnBtn\0\0\0"
"B_prdc_scrl_Left\0\0\0\0"
"P_prdc_scrl_Left\0\0\0\0"
"B_prdc_scrl_Rght\0\0\0\0"
"P_prdc_scrl_Rght\0\0\0\0"
"\0\0\0";
extern "C" char scW_predictWindow[16] = "W_predictWindow";
extern "C" char scN_predictInput[15] = "N_predictInput";
extern "C" char scW_OnOff_Area[13] = "W_OnOff_Area";
extern "C" char scN_prdc_Texts[13] = "N_prdc_Texts";
void CandidateBoxCaller::Candidates::addCandidate(const wchar_t* wcString) {
wcsncpy(szwcPredicted[mNumCandidate], wcString, ARRAY_LENGTH(szwcPredicted[0]));
@@ -365,60 +383,72 @@ namespace textinput {
mTextArea.Init();
mOnOffButton.Create(this);
mOnOffButton.Init();
mLeftScroll.Create(this, "P_prdc_scrl_Left", "B_prdc_scrl_Left");
mRightScroll.Create(this, "P_prdc_scrl_Rght", "B_prdc_scrl_Rght");
const char* paneNames = scPaneNameTable;
const char* leftScrollBoundName = paneNames + 48;
const char* leftScrollPaneName = paneNames + 68;
mLeftScroll.Create(this, leftScrollPaneName, leftScrollBoundName);
const char* rightScrollBoundName = paneNames + 88;
const char* rightScrollPaneName = paneNames + 108;
mRightScroll.Create(this, rightScrollPaneName, rightScrollBoundName);
mLeftScroll.Init();
mRightScroll.Init();
mTextWindow.Create(this, "W_predictWindow");
const char* windowName = scW_predictWindow;
mTextWindow.Create(this, windowName);
init();
}
void LayoutByNW4R::createAnmPane_(MEMAllocator* allocator) {
for (u16 i = 0; i < ARRAY_LENGTH(csPaneToAnimation); i++) {
const PaneToAnimation& paneAnimations = csPaneToAnimation[i];
CandidateTextAnmPane* pane = NULL;
switch (paneAnimations.type) {
CandidateTextAnmPane* pane;
u16 j;
u16 i;
for (i = 0; i < ARRAY_LENGTH(scCandidatePaneData.panes); i++) {
pane = NULL;
const PaneToAnimation& p = scCandidatePaneData.panes[i];
switch (p.type) {
case KT_ScrollButton: {
void* pBtnBuf = MEMAllocFromAllocator(allocator, sizeof(CandidateScrollAnmPane));
pane = new (pBtnBuf) CandidateScrollAnmPane(getPane(paneAnimations.paneName), NULL);
pane = new (pBtnBuf) CandidateScrollAnmPane(getPane(p.paneName), NULL);
break;
}
case KT_CandidateText: {
void* pBtnBuf = MEMAllocFromAllocator(allocator, sizeof(CandidateTextAnmPane));
pane = new (pBtnBuf) CandidateTextAnmPane(getPane(paneAnimations.paneName), NULL);
pane = new (pBtnBuf) CandidateTextAnmPane(getPane(p.paneName), NULL);
break;
}
case KT_OnOffButton: {
void* pBtnBuf = MEMAllocFromAllocator(allocator, sizeof(OnOffAnmPane));
pane = new (pBtnBuf) OnOffAnmPane(getPane(paneAnimations.paneName), &mOnOffButton);
pane = new (pBtnBuf) OnOffAnmPane(getPane(p.paneName), &mOnOffButton);
break;
}
case KT_Window: {
void* pBtnBuf = MEMAllocFromAllocator(allocator, sizeof(PredictWindow));
pane = new (pBtnBuf) PredictWindow(getPane(paneAnimations.paneName), &mTextWindow);
pane = new (pBtnBuf) PredictWindow(getPane(p.paneName), &mTextWindow);
break;
}
}
nw4r::ut::List_Append(&mAnmPanes, pane);
for (u16 j = 0; j < paneAnimations.count; j++) {
void* pResource = mpMultiArcResourceAccessor->GetResource(0, paneAnimations.pAnims[j]->fileName);
const char* forceAddName = p.forceAddName;
u32 animationCount = p.count;
for (j = 0; j < animationCount; j++) {
const AnimationFile* const& animation = p.pAnims[j];
void* pResource = mpMultiArcResourceAccessor->GetResource(0, animation->fileName);
AnimTransformPane* transform =
static_cast<AnimTransformPane*>(getLayout()->CreateAnimTransform(pResource, mpMultiArcResourceAccessor));
if (paneAnimations.forceAddName == NULL) {
pane->addAnimation(allocator, paneAnimations.pAnims[j]->id, transform, false, true);
if (forceAddName == NULL) {
pane->addAnimation(allocator, animation->id, transform, false, true);
} else {
pane->forceAddAnimation(allocator, paneAnimations.pAnims[j]->id, transform, paneAnimations.forceAddName, false, true);
pane->forceAddAnimation(allocator, animation->id, transform, forceAddName, false, true);
}
}
}
}
void LayoutByNW4R::init() {
searchAnmPane("N_predictInput")->changeAnimation(ANM_Normal);
searchAnmPane(scN_predictInput)->changeAnimation(ANM_Normal);
Base::setInvalid(false);
setActive(true);
setOnOff(false);
@@ -431,7 +461,7 @@ namespace textinput {
mpLayout->CalculateMtx(mDrawInfo);
if (meLanguage == KR) {
mTextWindow.SetVisible(false);
getPane("W_OnOff_Area")->SetVisible(false);
getPane(scW_OnOff_Area)->SetVisible(false);
} else if (meLanguage == CN) {
setOnOff(true);
mTextWindow.SetVisible(true);
@@ -441,16 +471,16 @@ namespace textinput {
} else {
mTextWindow.ChangeAnimation(ANM_Normal);
}
getPane("W_OnOff_Area")->SetVisible(false);
getPane(scW_OnOff_Area)->SetVisible(false);
} else {
getPane("W_OnOff_Area")->SetVisible(true);
getPane(scW_OnOff_Area)->SetVisible(true);
}
}
void LayoutByNW4R::draw() {
getPane("N_prdc_Texts")->SetVisible(false);
getPane(scN_prdc_Texts)->SetVisible(false);
nw4rmanager::Layout::draw();
getPane("N_prdc_Texts")->SetVisible(true);
getPane(scN_prdc_Texts)->SetVisible(true);
if (!isInvalid()) {
mTextArea.Draw(mDrawInfo);
}
@@ -460,8 +490,8 @@ namespace textinput {
nw4rmanager::Layout::calc();
mTextArea.Calc();
if (mbAnimOn) {
getPane("N_prdc_Texts")->Animate(0);
getPane("N_prdc_Texts")->CalculateMtx(mDrawInfo);
getPane(scN_prdc_Texts)->Animate(0);
getPane(scN_prdc_Texts)->CalculateMtx(mDrawInfo);
}
}
@@ -469,7 +499,7 @@ namespace textinput {
Base::setLanguage(language);
init();
// Maybe inlines, maybe not
nw4r::math::VEC3 pos = searchAnmPane("W_predictWindow")->getPane()->GetTranslate();
nw4r::math::VEC3 pos = searchAnmPane(scW_predictWindow)->getPane()->GetTranslate();
if (meLanguage == CN || meLanguage == KR) {
Base::checkValidation();
// Potentially an inline
@@ -484,7 +514,7 @@ namespace textinput {
pos.x = 202.0f;
}
searchAnmPane("W_predictWindow")->getPane()->SetTranslate(pos);
searchAnmPane(scW_predictWindow)->getPane()->SetTranslate(pos);
if (meLanguage == CN) {
mTextArea.ApplyFontScale(1.2f);
} else if (meLanguage == KR) {
@@ -601,7 +631,7 @@ namespace textinput {
current = reinterpret_cast<CandidateBoxCaller::Candidates*>(reinterpret_cast<u8*>(current) + sizeof(current->szwcPredicted[0]));
}
}
gui::PaneComponent* p = mpPaneManager->searchPaneComponent(isOn() ? scB_OnBtn : "B_OffBtn");
gui::PaneComponent* p = mpPaneManager->searchPaneComponent(isOn() ? scB_OnBtn : scPaneNameTable);
if (p != NULL) {
p->lockInitialize(true);
}
@@ -670,8 +700,8 @@ namespace textinput {
}
void LayoutByNW4R::cancelStateFocusIn() {
const PaneToAnimation* pane = csPaneToAnimation;
for (int i = 0; i < ARRAY_LENGTH(csPaneToAnimation); i++) {
const PaneToAnimation* pane = scCandidatePaneData.panes;
for (int i = 0; i < ARRAY_LENGTH(scCandidatePaneData.panes); i++) {
CandidateTextAnmPane* p = static_cast<CandidateTextAnmPane*>(searchAnmPane(pane->paneName));
if (p != NULL) {
switch (p->getKeyType()) {
@@ -979,7 +1009,7 @@ namespace textinput {
mpBoundingPane[i]->setListener(this);
}
mpTextAreaPane = mgr->searchPaneComponent("N_prdcTextArea");
mpTextsPane = mgr->searchPaneComponent("N_prdc_Texts");
mpTextsPane = mgr->searchPaneComponent(scN_prdc_Texts);
mSize = mpTextBoxPane[0]->getTextPane()->GetFontSize();
mpTextAreaPane->setListener(this);
}
@@ -1464,7 +1494,7 @@ namespace textinput {
if (mgr()->isInScroll() && event != gui::EventHandler::ON_LEFT && event != gui::EventHandler::ON_POINT) {
return;
}
if (!mgr()->searchAnmPane("W_predictWindow")->isInAnimation() || event == gui::EventHandler::ON_LEFT) {
if (!mgr()->searchAnmPane(scW_predictWindow)->isInAnimation() || event == gui::EventHandler::ON_LEFT) {
if (!mgr()->isInvalid()) {
switch (event) {
case gui::EventHandler::ON_TRIG:
@@ -1615,7 +1645,7 @@ namespace textinput {
if (mgr()->isInScroll() && event != gui::EventHandler::ON_LEFT && event != gui::EventHandler::ON_POINT) {
return;
}
if (!mgr()->searchAnmPane("W_predictWindow")->isInAnimation() || event == gui::EventHandler::ON_LEFT) {
if (!mgr()->searchAnmPane(scW_predictWindow)->isInAnimation() || event == gui::EventHandler::ON_LEFT) {
if (!mgr()->isInvalid()) {
switch (event) {
case gui::EventHandler::ON_TRIG:
@@ -1661,15 +1691,15 @@ namespace textinput {
mpOnPictPane = mgr->searchPaneComponent(scP_OnBtn);
mpOnBoundPane = mgr->searchPaneComponent(scB_OnBtn);
mpOnAnmPane = static_cast<OnOffAnmPane*>(layout->searchAnmPane(scP_OnBtn));
mpOffPictPane = mgr->searchPaneComponent("P_OffBtn");
mpOffBoundPane = mgr->searchPaneComponent("B_OffBtn");
mpOffAnmPane = static_cast<OnOffAnmPane*>(layout->searchAnmPane("P_OffBtn"));
mpOffPictPane = mgr->searchPaneComponent(scCandidatePaneData.tail);
mpOffBoundPane = mgr->searchPaneComponent(scPaneNameTable);
mpOffAnmPane = static_cast<OnOffAnmPane*>(layout->searchAnmPane(scCandidatePaneData.tail));
layout->getLayout()->GetRootPane()->FindPaneByName("P_OffBtn")->GetMaterial()->GetTexture(&mOffTexDefault, 0);
layout->getLayout()->GetRootPane()->FindPaneByName("P_JPOffBtn")->GetMaterial()->GetTexture(&mOffTexJP, 0);
layout->getLayout()->GetRootPane()->FindPaneByName("P_CNOffBtn")->GetMaterial()->GetTexture(&mOffTexCN, 0);
layout->getLayout()->GetRootPane()->FindPaneByName(scCandidatePaneData.tail)->GetMaterial()->GetTexture(&mOffTexDefault, 0);
layout->getLayout()->GetRootPane()->FindPaneByName(scPaneNameTable + 12)->GetMaterial()->GetTexture(&mOffTexJP, 0);
layout->getLayout()->GetRootPane()->FindPaneByName(scPaneNameTable + 24)->GetMaterial()->GetTexture(&mOffTexCN, 0);
layout->getLayout()->GetRootPane()->FindPaneByName(scP_OnBtn)->GetMaterial()->GetTexture(&mOnTexDefault, 0);
layout->getLayout()->GetRootPane()->FindPaneByName("P_CNOnBtn")->GetMaterial()->GetTexture(&mOnTexCN, 0);
layout->getLayout()->GetRootPane()->FindPaneByName(scPaneNameTable + 36)->GetMaterial()->GetTexture(&mOnTexCN, 0);
mpOffBoundPane->setListener(this);
mpOnBoundPane->setListener(this);
@@ -1725,7 +1755,7 @@ namespace textinput {
if (mgr()->isInScroll() && event != gui::EventHandler::ON_LEFT && event != gui::EventHandler::ON_POINT) {
return;
}
if (!mgr()->searchAnmPane("W_predictWindow")->isInAnimation() || event == gui::EventHandler::ON_LEFT) {
if (!mgr()->searchAnmPane(scW_predictWindow)->isInAnimation() || event == gui::EventHandler::ON_LEFT) {
OnOffAnmPane* p;
if (&component == mpOnBoundPane) {
p = mpOnAnmPane;
@@ -1758,48 +1788,3 @@ namespace textinput {
} // namespace candidatebox
} // namespace textinput
inline void textinput::util::Animation::startAnm(AnimObserver* observer, f32 start, f32 end, f32 duration, void* data) {
mfStartPoint = start;
mfEndPoint = end;
mfAnimationTime = duration;
mfCurrentFrame = 0.0f;
mbInAnimation = true;
mpAnimObserver = observer;
mpData = data;
mbSE = false;
if (observer) observer->onAnmEvent(AnimObserver::AE_0, data);
}
inline void textinput::util::Animation::calc() {
if (mbInAnimation) {
if (mfCurrentFrame < mfAnimationTime) {
mfCurrentFrame = 1.0f + mfCurrentFrame;
} else {
if (mbInAnimation && mpAnimObserver) {
mpAnimObserver->onAnmEvent(AnimObserver::AE_1, mpData);
}
mbInAnimation = false;
}
}
}
inline f32 textinput::util::Animation::getValue() {
return hermiteInterporation(mfCurrentFrame, 0.0f, mfStartPoint, 0.0f, mfAnimationTime, mfEndPoint, 0.0f);
}
inline bool textinput::util::Animation::isActive() {
return mbInAnimation;
}
inline void textinput::util::Animation::setSEFlag(bool flag) {
mbSE = flag;
}
inline bool textinput::util::Animation::isSEFlag() {
return mbSE;
}
inline void textinput::util::Animation::stop() {
mbInAnimation = false;
}

View File

@@ -295,40 +295,13 @@ confirmLetters:
update();
}
static inline void CopyWordSuffix(u16* word, u32 length) {
u32 wordLength;
u32 copied;
wordLength = wcslen((wchar_t*)word) & 0xff;
for (copied = 0; copied < length; ++copied) {
word[copied] = word[(wordLength - length) + copied];
}
word[copied] = 0;
}
void WithZi::update() {
u16* koreanOutput;
u16* keyOutput;
wchar_t* candidateOutput;
u16* destination;
u32 copyLength;
u16 keyCharacter;
u16* wordOutput;
u16* letter;
u32 count;
s32 elementCount;
u16* source;
s32 keyIndex;
s32 position;
s32 candidateLength;
u16 character;
s32 index;
if (mbDictionaryOpen == 0) {
return;
}
mSelectedCandidate = 0;
elementCount = static_cast<u16>(setElementBuffer());
s32 elementCount = static_cast<u16>(setElementBuffer());
mSearch.language = getPredictLanguage();
mSearch.subLanguage = 7;
mSearch.getMode = 0;
@@ -366,23 +339,24 @@ void WithZi::update() {
CandidatedWord[0] = L'>';
CandidatedWord[1] = 0;
mCandidateCount = 1;
keyOutput = CandidatedWord;
for (keyIndex = 1; keyIndex < 16; ++keyIndex) {
keyCharacter = static_cast<keyboard::cellphonetype::PaneNameToCharCode*>(mpHoldingKey)->wc[keyIndex - 1];
if (keyCharacter != 0) {
keyOutput[keyIndex * 0x40] = keyCharacter;
keyOutput[keyIndex * 0x40 + 1] = 0;
u16* output = CandidatedWord + 0x40;
for (s32 keyIndex = 1; keyIndex < 16; ++keyIndex) {
u16 candidate = static_cast<keyboard::cellphonetype::PaneNameToCharCode*>(mpHoldingKey)->wc[keyIndex - 1];
if (candidate != 0) {
output[0] = candidate;
output[1] = 0;
++mCandidateCount;
}
output += 0x40;
}
EZTXGetCandidates(&mSearch, mpDictionaryWork);
}
else {
memcpy(PredictionBuffer, CandidatesBuffer, 0x200);
ChangeDictionaryLanguage(getPredictLanguage());
count = EZTXGetCandidates(&mSearch, mpDictionaryWork) & 0xff;
u32 count = EZTXGetCandidates(&mSearch, mpDictionaryWork) & 0xff;
if (getPredictLanguage() == ZI8_LANG_ZH && count == 0x61) {
candidateOutput = reinterpret_cast<wchar_t*>(PredictionBuffer);
wchar_t* candidateOutput = reinterpret_cast<wchar_t*>(PredictionBuffer);
mSearch.firstCandidate = 0x61;
mSearch.candidates = candidateOutput + 0xC2;
mSearch.maxCandidates = 199;
@@ -395,8 +369,13 @@ void WithZi::update() {
}
if (getPredictLanguage() == ZI8_LANG_ZH && mbContextChanged != 0 &&
(mbContextChanged = 0, mSearch.count == 0)) {
copyLength = mCurrentWordLength;
CopyWordSuffix(LatestWord, copyLength);
u32 length = mCurrentWordLength;
u32 wordLength = wcslen((wchar_t*)LatestWord) & 0xff;
u32 copied;
for (copied = 0; copied < length; ++copied) {
LatestWord[copied] = LatestWord[(wordLength - length) + copied];
}
LatestWord[copied] = 0;
mSearch.wordCharCount = wcslen((wchar_t*)LatestWord);
count = EZTXGetCandidates(&mSearch, mpDictionaryWork) & 0xff;
}
@@ -413,25 +392,28 @@ void WithZi::update() {
memset(CandidatedWord, 0, 0x1400);
mCandidateCount = 0;
if (elementCount != 0 || mSearch.wordCharCount != 0) {
source = reinterpret_cast<u16*>(mSearch.candidates);
destination = CandidatedWord;
for (index = 0; index < static_cast<s32>(count); index++) {
u16* source = reinterpret_cast<u16*>(mSearch.candidates);
u16* destination = CandidatedWord;
for (s32 index = 0; index < static_cast<s32>(count); index++) {
if (getPredictLanguage() == ZI8_LANG_ZH) {
candidateLength = 0;
wordOutput = destination;
u16* output;
s32 length;
length = 0;
output = destination;
for (; *source != L' ' && *source != 0; source++) {
*wordOutput++ = *source;
++candidateLength;
*output++ = *source;
++length;
}
++source;
destination[candidateLength] = 0;
destination[length] = 0;
} else if (mPredictLanguage == PL_11) {
*destination = *source++;
destination[1] = 0;
} else if (getPredictLanguage() == ZI8_LANG_KO) {
koreanOutput = destination;
u16* output = destination;
u16 character;
while ((character = *source) >= 0x100) {
*koreanOutput++ = character;
*output++ = character;
++source;
}
} else if (EZTXCopy(reinterpret_cast<wchar_t*>(destination), &mSearch, index & 0xff, mpDictionaryWork) == 0) {
@@ -439,18 +421,20 @@ void WithZi::update() {
}
++mCandidateCount;
{
u16* candidate;
s32 position;
position = 0;
for (letter = destination; *letter != 0; ++letter, ++position) {
for (candidate = destination; *candidate != 0; ++candidate, ++position) {
switch (mLetterMode) {
case LM_1:
*letter = util::toWLower(*letter);
*candidate = util::toWLower(*candidate);
break;
case LM_2:
*letter = util::toWUpper(*letter);
*candidate = util::toWUpper(*candidate);
break;
case LM_0:
if (position == 0) *letter = util::toWUpper(*letter);
else *letter = util::toWLower(*letter);
if (position == 0) *candidate = util::toWUpper(*candidate);
else *candidate = util::toWLower(*candidate);
break;
case LM_3:
break;

File diff suppressed because it is too large Load Diff

View File

@@ -403,86 +403,43 @@ static inline void sendValidityResponse(u32 command, u32 valid) {
u32 value;
struct { u32 upper : 16; u32 valid : 8; u32 command : 8; } fields;
} reply;
reply.value = valid << 8;
reply.fields.command = command;
reply.value = command;
reply.fields.valid = valid;
OSSendMessage(&sThread->responses, (OSMessage)reply.value, OS_MESSAGE_BLOCK);
}
static inline u8 getCardCommandSlot(u32 message) {
u8 slot = message >> 16;
slot &= 1;
return slot;
}
static inline s32 countCardTitleBlocks(s32 slot, CARDDir* dir) {
s32 fileNo;
s32 result;
s32 blocks;
blocks = 0;
for (fileNo = 0; fileNo < CARD_MAX_FILE; ++fileNo) {
result = __CARDGetStatusEx(slot, fileNo, dir);
if (result < CARD_RESULT_READY && result != CARD_RESULT_NOFILE) {
blocks = -1;
break;
}
if (result == CARD_RESULT_READY &&
memcmp(dir->gameName, (void*)0x80000000, 4) == 0 &&
memcmp(dir->company, (void*)0x80000004, 2) == 0) {
blocks += dir->length;
}
}
return blocks;
}
static inline void listCardFiles(u8 slot, CARDDir& dir, char* fileName) {
u32 fileNo;
for (fileNo = 0; fileNo < CARD_MAX_FILE; ++fileNo) {
if (__CARDGetStatusEx(slot, (u16)fileNo, &dir) == CARD_RESULT_READY) {
memcpy(fileName, dir.fileName, CARD_FILENAME_MAX);
fileName[CARD_FILENAME_MAX] = 0;
OSReport("%d - %s: %d blocks\n", (u16)fileNo, fileName, dir.length);
}
}
}
static inline void deleteCardFile(u8 slot, s16 fileNo) {
s32 result = CARDFastDelete(slot, fileNo);
if (result < CARD_RESULT_READY) {
reportCardThreadError(slot, 4, result);
} else {
clearCardFileEntry(slot, fileNo);
refreshCardSlotInfo(slot);
sendCardSlotState(slot, 4, (u8)fileNo);
}
}
extern "C" void* cardThreadMain(void*) {
char fileName[33];
CARDDir listingDir;
CARDDir mountDir;
CARDDir freeDir;
u32 message;
s32 result;
u8 slot;
struct CardThreadLocals {
u8 compareName[6];
u32 message;
CARDDir freeDir;
CARDDir mountDir;
CARDDir listingDir;
char fileName[33];
} local;
BOOL brokenFile;
s32 scanResult;
s32 file;
s32 freeBlocks;
s32 outerSlot;
u32 validState = TRUE;
BOOL exitThread = FALSE;
u32 validState = TRUE;
u32 command;
s16 fileNo;
u8 slot;
s32 result;
s32 file;
u32 listingFile;
s32 outerSlot;
s32 freeFile;
s32 freeBlocks;
sThread->mounted[0] = 0;
sThread->mounted[1] = 0;
goto loopCheck;
loopStart:
OSReceiveMessage(&sThread->requests, (OSMessage*)&message, OS_MESSAGE_BLOCK);
OSReport("CARD THREAD: Message received %d\n", (s8)(u8)message);
OSReceiveMessage(&sThread->requests, (OSMessage*)&local.message, OS_MESSAGE_BLOCK);
OSReport("CARD THREAD: Message received %d\n", (s8)(u8)local.message);
if (validState != TRUE) {
goto loopCheck;
}
command = message & 0xFF;
command = local.message & 0xFF;
switch ((s8)command) {
case 10:
@@ -494,8 +451,8 @@ loopStart:
exitThread = TRUE;
break;
case 0: {
slot = getCardCommandSlot(message);
command = (message >> 14) & 4;
slot = (local.message >> 16) & 1;
command = (local.message >> 14) & 4;
result = CARDMount(slot, sThread->mountBuffers[command / 4], 0);
if (result < CARD_RESULT_READY) {
result = handleCardMountResult(slot, result);
@@ -504,15 +461,15 @@ loopStart:
}
break;
}
scanResult = CARDCheck(slot);
if (scanResult < CARD_RESULT_READY) {
result = CARDCheck(slot);
if (result < CARD_RESULT_READY) {
goto mountError;
}
mountContinue:
clearAllCardFileEntries(slot);
for (file = 0; file < CARD_MAX_FILE; ++file) {
result = __CARDGetStatusEx(slot, (s16)file, &mountDir);
result = __CARDGetStatusEx(slot, (s16)file, &local.mountDir);
if (result < CARD_RESULT_READY) {
result = handleCardMountResult(slot, result);
if (result != CARD_RESULT_READY) {
@@ -520,29 +477,27 @@ loopStart:
}
goto loopCheck;
} else {
u8 company[2];
u8 gameName[4];
company[0] = 0;
company[1] = 0;
gameName[0] = 0;
gameName[1] = 0;
gameName[2] = 0;
gameName[3] = 0;
if (strncmp((const char*)mountDir.fileName, "Broken File", 0xB) == 0 &&
memcmp(mountDir.gameName, gameName, 4) == 0 &&
memcmp(mountDir.company, company, 2) == 0) {
local.compareName[0] = 0;
local.compareName[1] = 0;
local.compareName[2] = 0;
local.compareName[3] = 0;
local.compareName[4] = 0;
local.compareName[5] = 0;
if (strncmp((const char*)local.mountDir.fileName, "Broken File", 0xB) == 0 &&
memcmp(local.mountDir.gameName, local.compareName + 2, 4) == 0 &&
memcmp(local.mountDir.company, local.compareName, 2) == 0) {
brokenFile = TRUE;
} else {
brokenFile = FALSE;
}
if (brokenFile) {
scanResult = CARDFastDelete(slot, (s16)file);
if (scanResult < CARD_RESULT_READY) {
result = CARDFastDelete(slot, (s16)file);
if (result < CARD_RESULT_READY) {
goto mountError;
}
} else {
scanResult = loadCardFileIcons(slot, (s16)file, &mountDir);
if (scanResult < CARD_RESULT_READY) {
result = loadCardFileIcons(slot, (s16)file, &local.mountDir);
if (result < CARD_RESULT_READY) {
goto mountError;
}
}
@@ -552,19 +507,26 @@ loopStart:
sThread->mounted[command / 4] = 1;
sendCardSlotState(slot, 0, 0);
OSReport("Slot %c\n", sCardSlotName[slot]);
listCardFiles(slot, listingDir, fileName);
for (listingFile = 0; listingFile < CARD_MAX_FILE; ++listingFile) {
if (__CARDGetStatusEx(slot, (u16)listingFile, &local.listingDir) == CARD_RESULT_READY) {
memcpy(local.fileName, local.listingDir.fileName, CARD_FILENAME_MAX);
local.fileName[CARD_FILENAME_MAX] = 0;
OSReport("%d - %s: %d blocks\n", (u16)listingFile, local.fileName,
local.listingDir.length);
}
}
break;
mountError:
OSReport("MountError\n");
reportCardThreadError(slot, 0, scanResult);
reportCardThreadError(slot, 0, result);
break;
}
case 9:
reportCardThreadError(getCardCommandSlot(message), 9, CARD_RESULT_NOCARD);
reportCardThreadError((local.message >> 16) & 1, 9, CARD_RESULT_NOCARD);
break;
case 1: {
slot = getCardCommandSlot(message);
slot = (local.message >> 16) & 1;
result = CARDFormat(slot);
if (result < CARD_RESULT_READY) {
reportCardThreadError(slot, 1, result);
@@ -576,22 +538,44 @@ loopStart:
break;
}
case 2:
runCardMoveOrCopy(getCardCommandSlot(message),
(s16)(u8)(message >> 24), (s8)command);
runCardMoveOrCopy((local.message >> 16) & 1,
(s16)(u8)(local.message >> 24), (s8)command);
break;
case 3:
runCardMoveOrCopy(getCardCommandSlot(message),
(s16)(u8)(message >> 24), (s8)command);
runCardMoveOrCopy((local.message >> 16) & 1,
(s16)(u8)(local.message >> 24), (s8)command);
break;
case 4:
deleteCardFile(getCardCommandSlot(message), (s16)(message >> 24));
case 4: {
slot = (local.message >> 16) & 1;
fileNo = (s16)(local.message >> 24);
result = CARDFastDelete(slot, fileNo);
if (result < CARD_RESULT_READY) {
reportCardThreadError(slot, 4, result);
} else {
clearCardFileEntry(slot, fileNo);
refreshCardSlotInfo(slot);
sendCardSlotState(slot, 4, (u8)fileNo);
}
break;
}
case 12:
outerSlot = 0;
do {
if (sThread->mounted[outerSlot] != 0) {
freeBlocks = countCardTitleBlocks(outerSlot, &freeDir);
freeBlocks = 0;
for (freeFile = 0; freeFile < CARD_MAX_FILE; ++freeFile) {
result = __CARDGetStatusEx(outerSlot, freeFile, &local.freeDir);
if (result < CARD_RESULT_READY && result != CARD_RESULT_NOFILE) {
freeBlocks = -1;
break;
}
if (result == CARD_RESULT_READY &&
memcmp(local.freeDir.gameName, (void*)0x80000000, 4) == 0 &&
memcmp(local.freeDir.company, (void*)0x80000004, 2) == 0) {
freeBlocks += local.freeDir.length;
}
}
sThread->slots[outerSlot].unk_0x12 = freeBlocks;
}
++outerSlot;
@@ -707,75 +691,25 @@ extern "C" void clearAllCardFileEntries(s32 slot) {
} while (file < CARD_MAX_FILE);
}
static inline s32 readCardImages(s32 slot, s32 fileNo, CARDDir* dir, CARDFileInfo* fileInfo,
u32 address, s32 offset, s32 imageSize) {
s32 sectorSize;
u32 transferSize = (imageSize + offset + 0x1FF) & 0xFFFFFE00;
if (CARDGetSectorSize(slot, (u32*)&sectorSize) < CARD_RESULT_READY) {
sThread->icons[slot][fileNo].bannerEnable = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
return 0;
extern "C" s32 loadCardFileIcons(s32 slot, s32 fileNo, CARDDir* dir) {
struct CardSequenceFileData {
s32 commentSectorSize;
s32 sectorSize;
CARDFileInfo fileInfo;
} local;
s32 iconAddressOffset;
u32 iconAddressBase;
s32 result;
result = CARDFastOpen(slot, fileNo, &local.fileInfo);
if (result < CARD_RESULT_READY) {
return result;
}
u32 fileSize = (u32)dir->length * sectorSize;
if (address > fileSize) {
sThread->icons[slot][fileNo].bannerEnable = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
return 0;
}
if (address + transferSize > fileSize) {
sThread->icons[slot][fileNo].bannerEnable = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
return 0;
}
if (imageSize > 0) {
s32 result = CARDRead(fileInfo, sThread->imageReadBuffer, transferSize, address);
if (result < CARD_RESULT_READY) {
return result;
}
memcpy(sThread->images[slot][fileNo], sThread->imageReadBuffer + offset, imageSize);
DCStoreRange(sThread->images[slot][fileNo], transferSize);
}
return 0;
}
static inline s32 readCardComment(s32 slot, s32 fileNo, CARDDir* dir, CARDFileInfo* fileInfo) {
u32 address = dir->commentAddr;
u32 base = address & 0xFFFFFE00;
s32 offset = address - base;
s32 readSize = ((address + 0x23F) & 0xFFFFFE00) - base;
s32 sectorSize;
s32 result = CARDGetSectorSize(slot, (u32*)&sectorSize);
if (result >= CARD_RESULT_READY) {
u32 fileSize;
if ((s32)base < 0 || base > (fileSize = (u32)dir->length * sectorSize)) {
result = 0;
} else {
u32 end = base + readSize;
if ((s32)end < 0 || end > fileSize) {
result = 0;
} else {
result = CARDRead(fileInfo, sThread->commentBuffer, readSize, base);
if (result >= CARD_RESULT_READY) {
memset(sThread->comments[slot][fileNo], 0, CARD_COMMENT_SIZE);
memcpy(sThread->comments[slot][fileNo], sThread->commentBuffer + offset,
CARD_COMMENT_SIZE);
return 0;
}
}
}
}
memset(sThread->comments[slot][fileNo], 0, CARD_COMMENT_SIZE);
return result;
}
static inline s32 loadCardIconImages(s32 slot, s32 fileNo, CARDDir* dir, CARDFileInfo* fileInfo) {
s32 bannerImageSize = 0;
u8 format = dir->bannerFormat & CARD_STAT_BANNER_MASK;
u32 iconAddress = dir->iconAddr;
s32 iconAddressOffset = iconAddress - (iconAddress & 0xFFFFFE00);
iconAddressBase = iconAddress & 0xFFFFFE00;
iconAddressOffset = iconAddress - iconAddressBase;
switch (format) {
case CARD_STAT_BANNER_C8: {
@@ -812,37 +746,37 @@ static inline s32 loadCardIconImages(s32 slot, s32 fileNo, CARDDir* dir, CARDFil
}
}
s32 shift;
BOOL hasTlut;
s32 iconImageSize;
s32 shift = 0;
s32 iconImageSize = 0;
s32 iconCount = 0;
s32 icon;
s32 iconCount;
shift = 0;
iconCount = 0;
hasTlut = FALSE;
iconImageSize = 0;
sThread->icons[slot][fileNo].unk_0x02 = 0;
sThread->icons[slot][fileNo].anmMax = 0;
sThread->icons[slot][fileNo].anmFrameBits = dir->iconSpeed;
sThread->icons[slot][fileNo].unk_0x06 = (dir->iconSpeed & CARD_STAT_SPEED_MASK) << 2;
sThread->icons[slot][fileNo].unk_0x06 =
(dir->iconSpeed & CARD_STAT_SPEED_MASK) << 2;
for (icon = 0; icon < CARD_ICON_MAX; ++icon) {
s32 iconSpeed = (dir->iconSpeed >> shift) & CARD_STAT_SPEED_MASK;
if (iconSpeed != 0) {
sThread->icons[slot][fileNo].anmMax = sThread->icons[slot][fileNo].anmMax + (iconSpeed << 2);
sThread->icons[slot][fileNo].anmMax =
sThread->icons[slot][fileNo].anmMax + (iconSpeed << 2);
} else {
sThread->icons[slot][fileNo].unk_0x07 =
(u8)(((dir->iconSpeed >> ((iconCount - 1) * 2)) << 2) & 0xC);
goto animationDone;
goto iconSpeedDone;
}
iconCount = iconCount + 1;
shift = shift + 2;
}
sThread->icons[slot][fileNo].unk_0x07 = (dir->iconSpeed >> 0xC) & 0xC;
animationDone:
sThread->icons[slot][fileNo].unk_0x07 =
(dir->iconSpeed >> 0xC) & 0xC;
iconSpeedDone:
if ((dir->iconSpeed & CARD_STAT_SPEED_MASK) == 0 || (dir->iconFormat & CARD_STAT_ICON_MASK) == 0) {
sThread->icons[slot][fileNo].unk_0x01 = 0;
iconImageSize = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
} else {
BOOL hasTlut = FALSE;
iconCount = 0;
shift = 0;
for (icon = 0; icon < CARD_ICON_MAX; ++icon) {
@@ -861,15 +795,17 @@ animationDone:
break;
case CARD_STAT_ICON_NONE: {
paletteSize = 0;
u8* previous = &sThread->icons[slot][fileNo].iconFmt[iconCount - 1];
sThread->icons[slot][fileNo].iconFmt[iconCount] = *previous;
u8* iconPalette =
&sThread->icons[slot][fileNo].iconFmt[iconCount];
*iconPalette = iconPalette[-1];
break;
}
default:
paletteSize = 0;
break;
}
if (iconCount < 7) {
sThread->icons[slot][fileNo].iconOffset[(u32)(iconCount + 1)] =
sThread->icons[slot][fileNo].iconOffset[iconCount + 1] =
paletteSize + sThread->icons[slot][fileNo].iconOffset[iconCount];
} else {
sThread->icons[slot][fileNo].iconTlutOffset =
@@ -894,28 +830,85 @@ animationDone:
sThread->icons[slot][fileNo].anmDelta = 1;
}
return readCardImages(slot, fileNo, dir, fileInfo, iconAddress & 0xFFFFFE00, iconAddressOffset,
bannerImageSize + iconImageSize);
}
extern "C" s32 loadCardFileIcons(s32 slot, s32 fileNo, CARDDir* dir) {
CARDFileInfo fileInfo;
s32 result = CARDFastOpen(slot, fileNo, &fileInfo);
s32 totalImageSize = iconImageSize + bannerImageSize;
u32 transferSize = (totalImageSize + iconAddressOffset + 0x1FF) & 0xFFFFFE00;
result = CARDGetSectorSize(slot, (u32*)&local.sectorSize);
if (result < CARD_RESULT_READY) {
return result;
result = 0;
sThread->icons[slot][fileNo].bannerEnable = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
} else {
u32 fileSize = (u32)dir->length * local.sectorSize;
if (iconAddressBase > fileSize) {
result = 0;
sThread->icons[slot][fileNo].bannerEnable = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
} else if (iconAddressBase + transferSize > fileSize) {
result = 0;
sThread->icons[slot][fileNo].bannerEnable = 0;
sThread->icons[slot][fileNo].unk_0x01 = 0;
} else if (totalImageSize > 0) {
result = CARDRead(&local.fileInfo, sThread->imageReadBuffer,
transferSize, iconAddressBase);
if (result < CARD_RESULT_READY) {
goto closeFile;
}
memcpy(sThread->images[slot][fileNo],
sThread->imageReadBuffer + iconAddressOffset,
totalImageSize);
DCStoreRange(sThread->images[slot][fileNo], transferSize);
result = 0;
}
}
result = loadCardIconImages(slot, fileNo, dir, &fileInfo);
if (result < CARD_RESULT_READY) {
return result;
goto closeFile;
}
result = readCardComment(slot, fileNo, dir, &fileInfo);
iconAddress = dir->commentAddr;
iconAddressBase = iconAddress & 0xFFFFFE00;
s32 commentDataOffset = iconAddress - iconAddressBase;
s32 imageSize = ((iconAddress + 0x23F) & 0xFFFFFE00) - iconAddressBase;
result = CARDGetSectorSize(slot, (u32*)&local.commentSectorSize);
if (result < CARD_RESULT_READY) {
return result;
goto clearComment;
}
{
u32 fileSize;
if ((s32)iconAddressBase < 0 ||
iconAddressBase > (fileSize = (u32)dir->length * local.commentSectorSize)) {
result = 0;
} else {
u32 endOffset = iconAddressBase + imageSize;
if ((s32)endOffset < 0 || endOffset > fileSize) {
result = 0;
goto clearComment;
}
result = CARDRead(&local.fileInfo, sThread->commentBuffer, imageSize,
iconAddressBase);
if (result < CARD_RESULT_READY) {
goto clearComment;
}
memset(sThread->comments[slot][fileNo], 0, CARD_COMMENT_SIZE);
memcpy(sThread->comments[slot][fileNo],
sThread->commentBuffer + commentDataOffset, CARD_COMMENT_SIZE);
result = 0;
goto commentDone;
}
}
result = CARDClose(&fileInfo);
clearComment:
memset(sThread->comments[slot][fileNo], 0, CARD_COMMENT_SIZE);
commentDone:
if (result >= CARD_RESULT_READY) {
goto closeFileSuccess;
}
closeFile:
return result;
closeFileSuccess:
result = CARDClose(&local.fileInfo);
if (result < CARD_RESULT_READY) {
return result;
}

View File

@@ -87,9 +87,11 @@ namespace ipl {
mNwc24ErrCountdown2 = 0;
// Text balloon for Mii face
f32 f0 = 30.0f;
f32 f1 = 120.0f;
mpNigaoeBalloon =
new TextBalloon(getSceneHeap(), mpBalloonFile, "arc", "my_IplTopBalloon_a.brlyt", math::VEC3(0.0f, 0.0f, 0.0f),
TextBalloon::getDefaultMargin16x9(), TextBalloon::getDefaultMargin4x3());
new TextBalloon(getSceneHeap(), mpBalloonFile, "arc", "my_IplTopBalloon_a.brlyt",
math::VEC3(0.0f, (f1 = 120.0f, 0.0f), (f0 = 30.0f, 0.0f)), f1, f0);
// Scroller
mpScroller = new utility::YoungBScroller();
@@ -194,8 +196,7 @@ namespace ipl {
mpCaptionString->clear();
mpCaptionString->set(System::getMessage(MESG_LETTERWRITER_LETTER_HEADER));
wchar_t* caption = mpCaptionString->getWCString();
wchar_t* namePlaceholder = wcsstr(caption, L"xxxxxxxxxx");
wchar_t* namePlaceholder = wcsstr(mpCaptionString->getWCString(), L"xxxxxxxxxx");
mpCaptionString->replace((namePlaceholder - mpCaptionString->getWCString()), RFL_NAME_LENGTH, headerCaption);
return mpCaptionString->getWCString();

View File

@@ -341,7 +341,7 @@ void MemoryCardManager::update_change_cardstate(u8 slot) {
}
}
const GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index) {
GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index) {
memorycard::IconState (*icons)[CARD_MAX_FILE] = reinterpret_cast<memorycard::IconState(*)[CARD_MAX_FILE]>(memorycard::getIconStateArray());
int total = 0;
s16 frame = 0;
@@ -355,24 +355,26 @@ const GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index) {
return _create_icon(slot, file, frame - 1);
}
const GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index, long start) {
GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index, long start) {
memorycard::getIconStateArray();
u32 file = mFile[slot][index].fileNo;
return _create_icon(slot, file, 0);
}
const GXTexObj* MemoryCardManager::_create_icon(u8 slot, s16 file, long start) {
GXTexObj* MemoryCardManager::_create_icon(u8 slot, s16 file, long start) {
CardDirectory* dirs = reinterpret_cast<CardDirectory*>(memorycard::getCardDirState());
if (dirs[slot][file].fileNo == 0) {
return NULL;
}
CardIcons* icons = reinterpret_cast<CardIcons*>(memorycard::getIconStateArray());
if ((int)icons[slot][file].iconFmt[start] == GX_TF_RGB5A3) {
GXLoadTexObj(initIconTexture(slot, file, reinterpret_cast<u8*>(&icons[slot][file]) + icons[slot][file].iconOffset[start]), GX_TEXMAP0);
} else if ((int)icons[slot][file].iconFmt[start] == GX_TF_C8) {
initIconTextureCI(slot, file, reinterpret_cast<u8*>(&icons[slot][file]) + icons[slot][file].iconOffset[start]);
GXTlutObj* tlut = initIconPalette(slot, file, reinterpret_cast<u8*>(&icons[slot][file]) + icons[slot][file].iconTlutOffset);
GXLoadTlut(tlut, GX_TLUT0);
memorycard::IconState* icon = &icons[slot][file];
if ((int)icon->iconFmt[start] == GX_TF_RGB5A3) {
GXInitTexObj(&mFileCell[slot][file].icon, reinterpret_cast<u8*>(icon) + icon->iconOffset[start], CARD_ICON_WIDTH, CARD_ICON_HEIGHT, GX_TF_RGB5A3, GX_CLAMP, GX_CLAMP, GX_FALSE);
GXLoadTexObj(&mFileCell[slot][file].icon, GX_TEXMAP0);
} else if ((int)icon->iconFmt[start] == GX_TF_C8) {
GXInitTexObjCI(&mFileCell[slot][file].icon, reinterpret_cast<u8*>(icon) + icon->iconOffset[start], CARD_ICON_WIDTH, CARD_ICON_HEIGHT, GX_TF_C8, GX_CLAMP, GX_CLAMP, GX_FALSE, GX_TLUT0);
GXInitTlutObj(&mFileCell[slot][file].iconTlut, reinterpret_cast<u8*>(icon) + icons[slot][file].iconTlutOffset, GX_TL_RGB5A3, 0x100);
GXLoadTlut(&mFileCell[slot][file].iconTlut, GX_TLUT0);
GXLoadTexObj(&mFileCell[slot][file].icon, GX_TEXMAP0);
} else {
return NULL;
@@ -422,7 +424,7 @@ const wchar_t* MemoryCardManager::getComment(u8 slot, s16 index, int which) {
return mFileCell[slot][file].comment[which];
}
const GXTexObj* MemoryCardManager::create_banner(u8 slot, s16 index) {
GXTexObj* MemoryCardManager::create_banner(u8 slot, s16 index) {
CardDirectory* dirs = reinterpret_cast<CardDirectory*>(memorycard::getCardDirState());
CardIcons* icons = reinterpret_cast<CardIcons*>(memorycard::getIconStateArray());
u32 file = mFile[slot][index].fileNo;
@@ -430,7 +432,7 @@ const GXTexObj* MemoryCardManager::create_banner(u8 slot, s16 index) {
return NULL;
}
if ((int)icons[slot][file].bannerType == GX_TF_RGB5A3) {
const GXTexObj* banner = initBannerTexture(slot, file,
GXTexObj* banner = initBannerTexture(slot, file,
reinterpret_cast<u8*>(&icons[slot][file]) + icons[slot][file].bannerOffset);
GXLoadTexObj(banner, GX_TEXMAP0);
} else if ((int)icons[slot][file].bannerType == GX_TF_C8) {

View File

@@ -7,11 +7,13 @@
#define IPL_SDMEMORY_SD_CHANNEL_SELECT_LAYOUT
#define IPL_SDMEMORY_COMPLETION_PCT_ACCESSOR
#define IPL_SDMEMORY_DIALOG_PROGRESS_FRAME_ACCESSOR
#define IPL_SDMEMORY_SET_TEXT_COLORS
#define IPL_SDMEMORY_SCROLLER_STATE_ACCESSOR
#include "system/iplDialogWindow.h"
#undef IPL_SDMEMORY_DIALOG_PROGRESS_FRAME_ACCESSOR
#include "scene/sdChannelMemory/iplSDMemory.h"
#include "scene/sdChannelSelect/iplSDChannelSelect.h"
#undef IPL_SDMEMORY_SET_TEXT_COLORS
#undef IPL_SDMEMORY_SCROLLER_STATE_ACCESSOR
#undef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR
#undef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE
@@ -26,12 +28,34 @@
#include "utility/iplLayout.h"
#include <revolution/os/OSTime.h>
extern "C" bool iplSDChannelSelect_813DDB74(ipl::scene::SDChannelSelect* channelSelect,
ipl::scene::SDMemory::TitleRange* nandTitles,
ipl::scene::SDMemory::TitleRange* sdTitles,
ESTitleId* titleIds, wchar_t* titleNames, u32* titleCount,
s32 state);
extern "C" bool iplSDChannelSelect_813DB5EC(ipl::scene::SDChannelSelect* channelSelect,
ESTitleId titleId);
extern "C" bool iplSDChannelSelect_813DB4D4(ipl::scene::SDChannelSelect* channelSelect,
ESTitleId titleId, u32 flags);
extern "C" bool iplSDChannelSelect_813DB530(ipl::scene::SDChannelSelect* channelSelect,
ESTitleId** titleNames, ESTitleId** secondaryTitles);
extern "C" bool iplSDChannelSelect_813DB478(ipl::scene::SDChannelSelect* channelSelect,
ESTitleId titleId);
extern "C" bool iplSDChannelSelect_813DB58C(ipl::scene::SDChannelSelect* channelSelect,
ESTitleId** titles, ESTitleId** secondaryTitles,
ESTitleId** names);
namespace ipl {
namespace scene {
typedef ::gui::Component GuiComponent;
typedef ::gui::PaneComponent GuiPaneComponent;
typedef controller::Interface ControllerInterface;
void writeFourFlagBytes(u8* flags, u8 first, u8 second, u8 third, u8 fourth);
void setTitleRowColors(nw4r::lyt::TextBox* textBox, const nw4r::ut::Color& first,
const nw4r::ut::Color& second) NO_INLINE;
static const char* sControlPaneNames[] = {
"A", "B", "B_BtnA",
};
@@ -44,19 +68,6 @@ namespace ipl {
SDMemory::~SDMemory() {}
static inline s32 countCachedTitles(const savedata::Manager* saveData) {
s32 count = 0;
for (s32 i = 0; i < 48; ++i) {
if (saveData->getTitleCacheEntry(i) == 0) {
break;
}
++count;
}
return count;
}
#pragma push
#pragma ppc_iro_level 1
void SDMemory::create(EGG::Heap* heap, nand::LayoutFile* layoutFile, SDChannelSelect* channelSelect) {
s32 cachedTitleCount;
const savedata::Manager* saveData;
@@ -140,7 +151,13 @@ namespace ipl {
textBox->SetString(System::getMessage(0xBA));
saveData = System::getSaveData();
cachedTitleCount = countCachedTitles(saveData);
cachedTitleCount = 0;
for (s32 i = 0; i < 48; ++i) {
if (saveData->getTitleCacheEntry(i) == 0) {
break;
}
++cachedTitleCount;
}
if (cachedTitleCount >= 5) {
mpTitleLayout->FindPaneByName("N_Btn_3")->SetVisible(false);
nw4r::lyt::Pane* expandedButton = mpTitleLayout->FindPaneByName("N_Btn_4");
@@ -236,8 +253,6 @@ namespace ipl {
mTransferFlags[0] = 1;
}
#pragma pop
void SDMemory::setTitleLists(const TitleRange& nandTitles, const TitleRange& sdTitles) {
mNandTitleRange = nandTitles;
mSDTitleRange = sdTitles;
@@ -708,8 +723,8 @@ namespace ipl {
if (!mpMainLayout->isPlaying(-1)) {
switch (mProcessState) {
case 0:
if (mpSDChannelSelect->collectTitlesForMode(&mNandTitleRange.mByteSize, &mSDTitleRange.mByteSize,
mTitleIds, mTitleNames, &mTitleCount, 2)) {
if (iplSDChannelSelect_813DDB74(mpSDChannelSelect, &mNandTitleRange, &mSDTitleRange,
mTitleIds, &mTitleNames[0][0], &mTitleCount, 2)) {
mDialogState = 4;
mpTitleLayout->getAnim(0)->initAnmFrame();
mpTitleLayout->getAnim(0)->play();
@@ -792,8 +807,8 @@ namespace ipl {
if (System::getDialog()->getLastResult() != -1) {
if (mpSDChannelSelect->getWorker()->get_async_result() == NandSDWorker::RESULT_OK) {
mNandTitleCount = mNandTitleList.count;
mTitleNameCount = mSDTitleList.count;
mNandTitleCount = mTitleListState.mSecondaryCount;
mTitleNameCount = mTitleListState.mNameCount;
} else {
mNandTitleCount = 0;
mTitleNameCount = 0;
@@ -907,7 +922,8 @@ namespace ipl {
return;
}
if (mpSDChannelSelect->enqueueErrorNotice(&mSDTitleList, &mNandTitleList)) {
if (iplSDChannelSelect_813DB530(mpSDChannelSelect, &mTitleListState.mpNames,
&mTitleListState.mpSecondaryTitles)) {
mDialogState = 19;
mCurrentTitleName[0] = L'\0';
mCurrentTitle = 0;
@@ -980,7 +996,7 @@ namespace ipl {
if (iplSDMemory_containsTitleId(this, mTitleIds[mCurrentTitle], mSDTitleIds, mTitleNameCount) ||
iplSDMemory_containsTitleId(this, mTitleIds[mCurrentTitle], mNandTitleIds, mNandTitleCount)) {
ESTitleId titleId = mTitleIds[mCurrentTitle];
if (mpSDChannelSelect->enqueueMoveNotice(titleId)) {
if (iplSDChannelSelect_813DB478(mpSDChannelSelect, titleId)) {
mDialogState = 14;
} else {
System::getDialog()->terminate();
@@ -1030,7 +1046,7 @@ namespace ipl {
void SDMemory::onDialogState16() {
if (mTitleCount > mCurrentTitle && System::isReceiveScheduleStopped()) {
if (mpSDChannelSelect->enqueueStateNotice(mTitleIds[mCurrentTitle], 0)) {
if (iplSDChannelSelect_813DB4D4(mpSDChannelSelect, mTitleIds[mCurrentTitle], 0)) {
mDialogState = 16;
} else {
System::getDialog()->terminate();
@@ -1085,7 +1101,7 @@ namespace ipl {
System::getDialog()->setTitleForSDMemory(mCurrentTitleName);
const ESTitleId titleId = mTitleIds[mCurrentTitle];
if (mpSDChannelSelect->enqueueDeleteNotice(titleId)) {
if (iplSDChannelSelect_813DB5EC(mpSDChannelSelect, titleId)) {
mDialogState = 18;
} else {
System::getDialog()->terminate();
@@ -1245,41 +1261,19 @@ namespace ipl {
}
void SDMemory::drawTransferTitles() {
f32 rowY;
f32 rowTop;
f32 backgroundOffset;
f32 titleOffset;
f32 rowHeight;
f32 messageOffset;
f32 bodyHeight;
f32 bodyY;
u8 alpha;
nw4r::lyt::Pane* bodyPane;
nw4r::lyt::Pane* titleSizePane;
nw4r::lyt::TextBox* titleText;
nw4r::lyt::Pane* footerPane;
u32 nandTitleIndex;
u32 titleIndex;
wchar_t* messageForCount;
s32 lineCount;
wchar_t* messageLine;
nw4r::lyt::TextBox* messageText;
s32 lineIndex;
wchar_t* lineEnd;
u32 lineLength;
const nw4r::math::VEC3& translation = mpDialogLayout->FindPaneByName("N_Memo")->GetTranslate();
nw4r::math::VEC3 memoPosition;
memoPosition.x = translation.x;
memoPosition.y = translation.y;
memoPosition.z = translation.z;
bodyY = memoPosition.y;
f32 bodyY = memoPosition.y;
mpDialogLayout->FindPaneByName("header_header");
bodyPane = mpDialogLayout->FindPaneByName("header_body");
nw4r::lyt::Pane* bodyPane = mpDialogLayout->FindPaneByName("header_body");
if (bodyY < 500.0f) {
mpDialogLayout->draw("header_header");
}
alpha = mpDialogLayout->FindPaneByName("N_Memo")->GetAlpha();
u8 alpha = mpDialogLayout->FindPaneByName("N_Memo")->GetAlpha();
nw4r::ut::LinkList<nw4r::lyt::Pane, offsetof(nw4r::lyt::detail::PaneBase, mLink)>::Iterator child =
bodyPane->GetChildList().GetBeginIter();
while (child != bodyPane->GetChildList().GetEndIter()) {
@@ -1287,26 +1281,29 @@ namespace ipl {
++child;
}
messageOffset = 0.0f;
bodyHeight = bodyPane->GetSize().height;
f32 messageOffset = 0.0f;
f32 bodyHeight = bodyPane->GetSize().height;
if (mNandTitleCount != 0) {
messageForCount = System::getMessage(0xCB);
lineCount = 0;
wchar_t* newline = wcsstr(messageForCount, L"\n");
const wchar_t* messageForCount = System::getMessage(0xCB);
s32 lineCount = 0;
const wchar_t* newline = wcsstr(messageForCount, L"\n");
while (newline != NULL) {
++lineCount;
newline = wcsstr(newline + 1, L"\n");
}
messageLine = System::getMessage(0xCB);
messageText = static_cast<nw4r::lyt::TextBox*>(
const wchar_t* messageLine = System::getMessage(0xCB);
nw4r::lyt::TextBox* messageText = static_cast<nw4r::lyt::TextBox*>(
mpDialogLayout->FindPaneByName("T_Header_body"));
for (lineIndex = 0; lineIndex < lineCount + 1; ++lineIndex) {
lineEnd = wcsstr(messageLine, L"\n");
s32 totalLines = lineCount + 1;
s32 lineIndex = 0;
if (lineIndex < totalLines) {
do {
const wchar_t* lineEnd = wcsstr(messageLine, L"\n");
if (lineEnd == NULL) {
utility::layout::set_string(messageText, messageLine);
} else {
lineLength = static_cast<u32>(lineEnd - messageLine);
u32 lineLength = static_cast<u32>(lineEnd - messageLine);
wcsncpy(mCurrentTitleName, messageLine, lineLength);
mCurrentTitleName[lineLength] = L'\0';
utility::layout::set_string(messageText, mCurrentTitleName);
@@ -1321,42 +1318,52 @@ namespace ipl {
}
messageOffset -= bodyHeight;
++lineIndex;
} while (lineIndex < totalLines);
}
}
messageOffset += bodyHeight;
backgroundOffset = 40.0f + messageOffset;
titleOffset = 79.5f + messageOffset;
f32 backgroundOffset = 40.0f + messageOffset;
f32 titleOffset = 79.5f + messageOffset;
titleSizePane = mpDialogLayout->FindPaneByName("N_Body");
rowHeight = titleSizePane->GetSize().height;
nw4r::lyt::PaneList::Iterator bodyChild = titleSizePane->GetChildList().GetBeginIter();
while (bodyChild != titleSizePane->GetChildList().GetEndIter()) {
bodyChild->SetAlpha(alpha);
++bodyChild;
nw4r::lyt::Pane* titleSizePane = mpDialogLayout->FindPaneByName("N_Body");
f32 rowHeight = titleSizePane->GetSize().height;
nw4r::lyt::PaneList::Iterator titleChild = titleSizePane->GetChildList().GetBeginIter();
while (titleChild != titleSizePane->GetChildList().GetEndIter()) {
titleChild->SetAlpha(alpha);
++titleChild;
}
titleText = static_cast<nw4r::lyt::TextBox*>(
nw4r::lyt::TextBox* titleText = static_cast<nw4r::lyt::TextBox*>(
mpDialogLayout->FindPaneByName("T_Letter"));
titleText->SetAlpha(alpha);
nandTitleIndex = 0;
for (titleIndex = 0; titleIndex < mTitleCount; ++titleIndex) {
u32 nandTitleIndex = 0;
for (u32 titleIndex = 0; titleIndex < mTitleCount; ++titleIndex) {
utility::layout::set_string(titleText, mTitleNames[titleIndex]);
if (nandTitleIndex < mNandTitleCount && mTitleIds[titleIndex] == mNandTitleIds[nandTitleIndex]) {
GXColor gxActive;
writeFourFlagBytes(&gxActive.r, 0x34, 0xBE, 0xED, 0xFF);
++nandTitleIndex;
nw4r::ut::Color color(0x34, 0xBE, 0xED, 0xFF);
titleText->SetTextColor(color, color);
nw4r::ut::Color active0 = *reinterpret_cast<const nw4r::ut::Color*>(&gxActive);
setTitleRowColors(titleText,
nw4r::ut::Color(*reinterpret_cast<const nw4r::ut::Color*>(&gxActive)),
nw4r::ut::Color(*reinterpret_cast<const nw4r::ut::Color*>(&gxActive)));
} else {
nw4r::ut::Color color(0x64, 0x64, 0x64, 0xFF);
titleText->SetTextColor(color, color);
GXColor gxInactive;
writeFourFlagBytes(&gxInactive.r, 0x64, 0x64, 0x64, 0xFF);
nw4r::ut::Color inactive0 = *reinterpret_cast<const nw4r::ut::Color*>(&gxInactive);
setTitleRowColors(titleText,
nw4r::ut::Color(*reinterpret_cast<const nw4r::ut::Color*>(&gxInactive)),
nw4r::ut::Color(*reinterpret_cast<const nw4r::ut::Color*>(&gxInactive)));
}
nw4r::ut::Rect textRect = mpDialogLayout->getTextDrawRect("T_Letter");
rowTop = textRect.bottom - textRect.top;
f32 rowTop = textRect.bottom - textRect.top;
s32 visibleRows = static_cast<s32>(static_cast<f32>(ceil(-rowTop / titleSizePane->GetSize().height)));
for (s32 row = 0; row < visibleRows; ++row) {
rowY = bodyY + backgroundOffset;
f32 rowY = bodyY + backgroundOffset;
if (-500.0f < rowY && rowY < 500.0f) {
nw4r::math::VEC2 translation(0.0f, backgroundOffset);
titleSizePane->SetTranslate(translation);
@@ -1371,11 +1378,11 @@ namespace ipl {
titleText->CalculateMtx(*mpDialogLayout->getDrawInfo());
mpDialogLayout->draw(titleText);
}
titleOffset -= visibleRows * rowHeight;
titleOffset -= rowHeight * static_cast<f32>(visibleRows);
}
backgroundOffset += rowHeight;
footerPane = mpDialogLayout->FindPaneByName("N_Footer");
nw4r::lyt::Pane* footerPane = mpDialogLayout->FindPaneByName("N_Footer");
nw4r::lyt::PaneList::Iterator footerChild = footerPane->GetChildList().GetBeginIter();
while (footerChild != footerPane->GetChildList().GetEndIter()) {
footerChild->SetAlpha(alpha);
@@ -1394,6 +1401,18 @@ namespace ipl {
mpDialogLayout->draw("N_Move");
}
void writeFourFlagBytes(u8* flags, u8 first, u8 second, u8 third, u8 fourth) {
flags[0] = first;
flags[1] = second;
flags[2] = third;
flags[3] = fourth;
}
void setTitleRowColors(nw4r::lyt::TextBox* textBox, const nw4r::ut::Color& first,
const nw4r::ut::Color& second) NO_INLINE {
textBox->SetTextColors(first, second);
}
s32 SDMemory::getControlPaneIndex(const char* paneName) {
s32 paneIndex = -1;
for (s32 i = 0; i < 3; i++) {
@@ -1617,23 +1636,23 @@ namespace ipl {
switch (paneIndex) {
case 0:
animator = mpTitleLayout->getAnim(7);
mpSDChannelSelect->collectTitlesForMode(&mNandTitleRange.mByteSize, &mSDTitleRange.mByteSize,
mTitleIds, mTitleNames, &mTitleCount, 0);
iplSDChannelSelect_813DDB74(mpSDChannelSelect, &mNandTitleRange, &mSDTitleRange,
mTitleIds, &mTitleNames[0][0], &mTitleCount, 0);
break;
case 1:
animator = mpTitleLayout->getAnim(10);
mpSDChannelSelect->collectTitlesForMode(&mNandTitleRange.mByteSize, &mSDTitleRange.mByteSize,
mTitleIds, mTitleNames, &mTitleCount, 1);
iplSDChannelSelect_813DDB74(mpSDChannelSelect, &mNandTitleRange, &mSDTitleRange,
mTitleIds, &mTitleNames[0][0], &mTitleCount, 1);
break;
case 2:
animator = mpTitleLayout->getAnim(13);
mpSDChannelSelect->collectTitlesForMode(&mNandTitleRange.mByteSize, &mSDTitleRange.mByteSize,
mTitleIds, mTitleNames, &mTitleCount, 2);
iplSDChannelSelect_813DDB74(mpSDChannelSelect, &mNandTitleRange, &mSDTitleRange,
mTitleIds, &mTitleNames[0][0], &mTitleCount, 2);
break;
case 3:
animator = mpTitleLayout->getAnim(16);
mpSDChannelSelect->collectTitlesForMode(&mNandTitleRange.mByteSize, &mSDTitleRange.mByteSize,
mTitleIds, mTitleNames, &mTitleCount, 3);
iplSDChannelSelect_813DDB74(mpSDChannelSelect, &mNandTitleRange, &mSDTitleRange,
mTitleIds, &mTitleNames[0][0], &mTitleCount, 3);
break;
case 4:
animator = mpTitleLayout->getAnim(4);
@@ -1653,13 +1672,16 @@ namespace ipl {
memset(mSDTitleIds, 0, sizeof(mSDTitleIds));
mNandTitleCount = 0;
mTitleNameCount = 0;
mTitleList.titleIds = mTitleIds;
mTitleList.count = mTitleCount;
mNandTitleList.titleIds = mNandTitleIds;
mNandTitleList.count = 0;
mSDTitleList.titleIds = mSDTitleIds;
mSDTitleList.count = 0;
mpSDChannelSelect->enqueueCommandNotice(&mTitleList, &mNandTitleList, &mSDTitleList);
mTitleListState.mpTitles = mTitleIds;
mTitleListState.mCount = mTitleCount;
mTitleListState.mpSecondaryTitles = mNandTitleIds;
mTitleListState.mSecondaryCount = 0;
mTitleListState.mpNames = mSDTitleIds;
mTitleListState.mNameCount = 0;
iplSDChannelSelect_813DB58C(mpSDChannelSelect,
&mTitleListState.mpTitles,
&mTitleListState.mpSecondaryTitles,
&mTitleListState.mpNames);
}
if (paneIndex == 4) {

View File

@@ -212,8 +212,6 @@ namespace ipl {
}
}
#pragma push
#pragma ppc_iro_level 0
void SDChannelSelect::create() {
mpSDWorker = new (System::getMem2App(), 4) NandSDWorker();
mpWorkerHeap = (EGG::Heap*)System::getMem2App()->alloc(0x3EA60, 0x40);
@@ -255,7 +253,6 @@ namespace ipl {
utility::CSFlags::UpdateFlagsFile();
}
#pragma pop
void SDChannelSelect::enqueueStartNotice() {
SDChannelSelectCommand command;
command.type = 1;
@@ -352,7 +349,7 @@ namespace ipl {
return true;
}
bool SDChannelSelect::enqueueMoveNotice(ESTitleId titleId) {
bool SDChannelSelect::enqueueMoveNotice(u32 controller, u32 page, u32 index) {
if (mCurrentSDState != 6) {
return false;
}
@@ -361,7 +358,7 @@ namespace ipl {
command.type = 6;
command.arguments.values[0] = 0;
command.arguments.values[1] = 0;
command.titleId = titleId;
command.titleId = ((u64)page << 32) | index;
mCommandQueue.push(command);
return true;
}
@@ -380,39 +377,36 @@ namespace ipl {
return true;
}
bool SDChannelSelect::enqueueErrorNotice(NandSDWorker::TitleIdList* newTitles,
NandSDWorker::TitleIdList* replacingTitles) {
bool SDChannelSelect::enqueueErrorNotice(u32 page, u32 index) {
if (mCurrentSDState != 6) {
return false;
}
SDChannelSelectCommand command;
command.type = 11;
command.arguments.titleLists[0] = newTitles;
command.arguments.titleLists[1] = replacingTitles;
command.arguments.values[0] = page;
command.arguments.values[1] = index;
command.titleId = 0;
mCommandQueue.push(command);
return true;
}
bool SDChannelSelect::enqueueCommandNotice(NandSDWorker::TitleIdList* titles,
NandSDWorker::TitleIdList* foundTitles,
NandSDWorker::TitleIdList* badTitles) {
bool SDChannelSelect::enqueueCommandNotice(u32 page, u32 index, u32 commandType) {
if (mCurrentSDState != 6) {
return false;
}
SDChannelSelectCommand command;
command.arguments.titleLists[0] = titles;
command.arguments.values[0] = page;
command.type = 12;
command.arguments.titleLists[1] = foundTitles;
command.arguments.titleLists[2] = badTitles;
command.arguments.values[1] = index;
command.arguments.values[2] = commandType;
command.titleId = 0;
mCommandQueue.push(command);
return true;
}
bool SDChannelSelect::enqueueDeleteNotice(ESTitleId titleId) {
bool SDChannelSelect::enqueueDeleteNotice(u32 controller, u32 page, u32 index) {
if (mCurrentSDState != 6) {
return false;
}
@@ -422,7 +416,7 @@ namespace ipl {
command.arguments.values[0] = 0;
command.arguments.values[1] = 0;
command.arguments.values[2] = 0;
command.titleId = titleId;
command.titleId = ((u64)page << 32) | index;
mCommandQueue.push(command);
return true;
}
@@ -1328,8 +1322,8 @@ namespace ipl {
}
bool SDChannelSelect::collectTitlesByUsage(
s32* firstUsage, s32* secondUsage, ESTitleId* titleIds,
wchar_t (*titleNames)[21], u32* titleCount) {
const s32* firstUsage, const s32* secondUsage, ESTitleId* titleIds,
char* titleNames, u32* titleCount) {
s32 bytes;
s32 blocks;
getCurrentTitleUsage(&bytes, &blocks);
@@ -1346,7 +1340,7 @@ namespace ipl {
titleIds[*titleCount] = mpNandTitleInfo[index].curTitleId;
wchar_t* titleName = System::getChannelManager()->getTitleName(
page, channelIndex, 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1363,8 +1357,8 @@ namespace ipl {
}
bool SDChannelSelect::collectTitlesFromNandUsage(
s32* firstUsage, s32* secondUsage,
ESTitleId* titleIds, wchar_t (*titleNames)[21], u32* titleCount) {
const s32* firstUsage, const s32* secondUsage,
ESTitleId* titleIds, char* titleNames, u32* titleCount) {
s32 bytes;
s32 blocks;
getCurrentTitleUsage(&bytes, &blocks);
@@ -1387,7 +1381,7 @@ namespace ipl {
titleIds[*titleCount] = mpNandTitleInfo[index].curTitleId;
wchar_t* titleName = System::getChannelManager()->getTitleName(
page, channelIndex, 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1402,8 +1396,8 @@ namespace ipl {
}
bool SDChannelSelect::collectTitlesByChannelOrder(
s32* firstUsage, s32* secondUsage, ESTitleId* titleIds,
wchar_t (*titleNames)[21], u32* titleCount) {
const s32* firstUsage, const s32* secondUsage, ESTitleId* titleIds,
char* titleNames, u32* titleCount) {
static const int channelOrder[MAX_CHANNEL_INDEX] = {
11, 7, 3, 10, 6, 2, 9, 5, 1, 8, 4, 0,
};
@@ -1412,10 +1406,17 @@ namespace ipl {
getCurrentTitleUsage(&bytes, &blocks);
*titleCount = 0;
ESTitleId titleId;
for (int page = MAX_CHANNEL_PAGE - 1; page >= 0; --page) {
for (int order = 0; order < MAX_CHANNEL_INDEX; ++order) {
ESTitleId titleId =
System::getChannelManager()->getEntryTitleID(page, channelOrder[order]);
int channelIndex = channelOrder[order];
const channel::SEntry& channelInfo =
System::getChannelManager()->mChannels[page][channelIndex];
if (channelInfo.loadedBnr) {
titleId = ES_TITLE_ID(channelInfo.info.titleType, channelInfo.info.titleCode);
} else {
titleId = 0;
}
if (titleId == 0 || titleId == 0x48415A41) {
continue;
}
@@ -1430,7 +1431,7 @@ namespace ipl {
titleIds[*titleCount] = mpNandTitleInfo[usageIndex].curTitleId;
wchar_t* titleName =
System::getChannelManager()->getTitleName(page, channelOrder[order], 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1447,8 +1448,8 @@ namespace ipl {
}
bool SDChannelSelect::collectTitlesBySpecialChannels(
s32* firstUsage, s32* secondUsage, ESTitleId* titleIds,
wchar_t (*titleNames)[21], u32* titleCount) {
const s32* firstUsage, const s32* secondUsage, ESTitleId* titleIds,
char* titleNames, u32* titleCount) {
s32 bytes;
s32 blocks;
getCurrentTitleUsage(&bytes, &blocks);
@@ -1505,7 +1506,7 @@ namespace ipl {
titleIds[*titleCount] = mpNandTitleInfo[usageIndex].curTitleId;
wchar_t* titleName = System::getChannelManager()->getTitleName(
page, channelIndex, 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1531,7 +1532,7 @@ namespace ipl {
titleIds[*titleCount] = mpNandTitleInfo[usageIndex].curTitleId;
wchar_t* titleName = System::getChannelManager()->getTitleName(
page, channelIndex, 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1547,7 +1548,7 @@ namespace ipl {
wchar_t* titleName =
System::getChannelManager()->getTitleName(
hadePage, hadeChannelIndex, 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1562,7 +1563,7 @@ namespace ipl {
wchar_t* titleName =
System::getChannelManager()->getTitleName(
hatePage, hateChannelIndex, 0);
memcpy(titleNames[*titleCount], titleName, sizeof(*titleNames));
memcpy(titleNames + *titleCount * 0x2a, titleName, 0x2a);
++*titleCount;
if (bytes >= secondUsage[0] && blocks >= secondUsage[1]) {
@@ -1577,8 +1578,8 @@ namespace ipl {
}
bool SDChannelSelect::collectTitlesForMode(
s32* requiredBytes, s32* requiredBlocks,
ESTitleId* titleIds, wchar_t (*titleNames)[21], u32* titleCount, int searchMode) {
const s32* requiredBytes, const s32* requiredBlocks,
ESTitleId* titleIds, char* titleNames, u32* titleCount, int searchMode) {
switch (searchMode) {
case 0:
return collectTitlesBySpecialChannels(
@@ -1646,8 +1647,6 @@ namespace ipl {
}
}
#pragma push
#pragma ppc_iro_level 0
void SDChannelSelect::flushSaveDataAndMountSD() {
if (System::getDialog()->getLastResult() != DialogWindow::RESULT_NONE) {
mpPointerLayout->getAnim(0)->initAnmFrame();
@@ -1659,7 +1658,6 @@ namespace ipl {
}
}
#pragma pop
void SDChannelSelect::handleThreePageDialog() {
if (System::getDialog()->callBtn2Multi(sThreePageDialogPages, 3, 10)) {
mState = 27;
@@ -1904,7 +1902,7 @@ namespace ipl {
pageText->SetString(pageNumber, 0);
nw4r::lyt::Pane* clockPane = mpLayout->FindPaneByName(mscClockPaneNames[page]);
nw4r::math::MTX34 paneMatrix = clockPane->GetGlobalMtx();
math::VEC3 position(0.0f, 0.0f, 0.0f);
nw4r::math::VEC3 position(0.0f, 0.0f, 0.0f);
PSMTXMultVec(paneMatrix, position, position);
mpDialogLayout->GetRootPane()->SetTranslate(position);
mpDialogLayout->calcMtx();
@@ -2701,8 +2699,8 @@ namespace ipl {
return mpLayout->FindPaneByName(mscChannelPaneNames[2][index]);
}
nw4r::math::VEC3 SDChannelSelect::getChannelPanePosition(SDChannelSelect* scene, int index) {
nw4r::math::VEC3 position(0.0f, 0.0f, 0.0f);
math::VEC3 SDChannelSelect::getChannelPanePosition(SDChannelSelect* scene, int index) {
math::VEC3 position(0.0f, 0.0f, 0.0f);
MTXMultVec(scene->getCenterChannelPane(index)->GetGlobalMtx(), position, position);
return position;
}

View File

@@ -5,9 +5,9 @@
#define IPL_CHANNEL_TITLE_NOVTABLE
#include "math/iplInterporation.h"
#undef IPL_CHANNEL_TITLE_NOVTABLE
#include "scene/sdChannelTitle/iplSDChannelTitle.h"
#undef IPL_CHANNEL_TITLE_NOVTABLE
#include "scene/sdChannelSelect/iplSDChannelSelect.h"
#include "system/iplSystem.h"
#include "sound/iplSound.h"
@@ -83,6 +83,7 @@ extern "C" void iplSDChannelTitle_setPageAndIndex(SDChannelTitle* scene, int pag
extern "C" void iplSDChannelTitle_cleanupAndLeave(SDChannelTitle* scene);
extern "C" void iplSDChannelTitle_confirmLeaveToSettings(SDChannelTitle* scene, bool settings);
extern "C" void iplSDChannelTitle_flushSaveBeforeExit(SDChannelTitle* scene, int nextScene);
extern "C" SDMemory::TitleRange* iplSDChannelTitle_copyTitleRange(SDMemory::TitleRange*, const SDMemory::TitleRange*);
static inline void setMemoryTitleLists(SDMemory* memory, SDMemory::TitleRange sdRange,
SDMemory::TitleRange nandRange) {
@@ -763,9 +764,9 @@ extern "C" void iplSDChannelTitle_updateCopyPrepare(SDChannelTitle* scene) {
if (static_cast<u32>(scene->mTitleRange.mByteSize) < 0x3800000) {
nandRange.mByteSize = 0x3800000;
nandRange.mCount = scene->mTitleRange.mCount;
sdRange = scene->mTitleRange;
iplSDChannelTitle_copyTitleRange(&sdRange, &scene->mTitleRange);
} else {
nandRange = sdRange = scene->mTitleRange;
iplSDChannelTitle_copyTitleRange(&nandRange, iplSDChannelTitle_copyTitleRange(&sdRange, &scene->mTitleRange));
}
SDMemory* memory = &scene->mMemory;
setMemoryTitleLists(memory, sdRange, nandRange);
@@ -787,6 +788,14 @@ extern "C" void iplSDChannelTitle_updateCopyPrepare(SDChannelTitle* scene) {
}
}
extern "C" SDMemory::TitleRange* iplSDChannelTitle_copyTitleRange(
SDMemory::TitleRange* target, const SDMemory::TitleRange* source) {
s32 bytes = source->mByteSize;
target->mCount = source->mCount;
target->mByteSize = bytes;
return target;
}
extern "C" void iplSDChannelTitle_updateMemoryCalc(SDChannelTitle* scene) {
if (!scene->mMemory.calc()) {
return;
@@ -1342,8 +1351,6 @@ extern "C" void iplSDChannelTitle_prepareSceneExit(SDChannelTitle* scene, int ne
}
}
#pragma push
#pragma ppc_iro_level 0
extern "C" void iplSDChannelTitle_flushSaveBeforeExit(SDChannelTitle* scene, int nextScene) {
int page;
int index;
@@ -1351,10 +1358,10 @@ extern "C" void iplSDChannelTitle_flushSaveBeforeExit(SDChannelTitle* scene, int
System::getSaveData()->pushTitleCache(scene->mTitleId);
}
System::getSaveData()->getSDPrevPage() = scene->mPage;
scene->mpSaveFile = System::getSaveData()->flushAsync(System::getMem2App());
EGG::Heap* saveHeap = System::getMem2App();
scene->mpSaveFile = System::getSaveData()->flushAsync(saveHeap);
__WPADReconnect(TRUE);
}
#pragma pop
extern "C" void iplSDChannelTitle_rebootSystem(SDChannelTitle*) {
snd::getSystem()->stopAllSound(0);

View File

@@ -167,6 +167,11 @@ typedef struct AOSSKeySchedule {
u32 length;
} AOSSKeySchedule;
typedef struct AOSSKeyMaterial {
u8 nonce[2];
u8 address[8];
} AOSSKeyMaterial;
typedef struct AOSSReceiveBuffer {
s32 socket;
u32 length;
@@ -256,6 +261,11 @@ typedef struct AOSSConfigData {
static AOSSRuntimeState s_runtime;
static AOSSConfigData s_configData;
static u8 s_networkBuffer[0x280];
static struct {
AOSSKeyMaterial key;
u8 payload[0x5e];
} s_packetState;
static u32 s_crcTable[0x100];
static s32 s_socket = -1;
static char s_manufacturer[] = "MELCO";
@@ -281,7 +291,7 @@ extern void AOSSi_Sleep(u32 duration);
struct AOSSConnection;
struct AOSSConnectionStatus;
extern int AOSSi_WLANConnect(struct AOSSConnection* connection, struct AOSSConnectionStatus* status);
extern int SOPoll(AOSSPollDescriptor* descriptors, int count, OSTime timeout);
extern int SOPoll(AOSSPollDescriptor* descriptors, int count, s32 timeoutHigh, s32 timeoutLow);
extern int SORecvFrom(int socket, void* buffer, int length, int flags, void* address);
extern int SOSendTo(int socket, const void* buffer, int length, int flags, const void* address);
extern int SOBind(int socket, const void* address);
@@ -388,7 +398,8 @@ cleanup_done:
int AOSS_Init_old(AOSSInitInput* input)
{
short waitAttempt;
s16 initialWait;
u64 tickRemainder;
AOSSReceiveBuffer* packetBuffer;
AOSSPacketHeader* packetWords;
u32 initialSleep;
@@ -396,7 +407,7 @@ int AOSS_Init_old(AOSSInitInput* input)
u32 resultCode;
u32 flags;
int state;
int timeoutMilliseconds;
int protocolState;
u32 retryWait;
u16 retryDelay;
u32 delayStep;
@@ -405,13 +416,15 @@ int AOSS_Init_old(AOSSInitInput* input)
int requestResult;
size_t manufacturerLength;
int timeoutSeconds;
int protocolState;
int timeoutMilliseconds;
int protocolResult;
OSTime timeoutTicks;
u32 responseSleep;
u32 subnetMask;
u64 timeoutTicks;
int initializationResult;
short attemptCount;
u16 remainingWait;
s16 initialWait;
short waitAttempt;
u16 defaultConnection;
u16 defaultResponse;
union {
@@ -427,6 +440,7 @@ int AOSS_Init_old(AOSSInitInput* input)
u8 messageIdentity[8];
__declspec(align(32)) AOSSSocketAddress socketAddress;
struct { int seconds; int microseconds; } pollTime;
AOSSSocketAddress receivedAddress;
u32 networkAddresses[5];
AOSSPollDescriptor pollArguments[2];
@@ -624,7 +638,7 @@ int AOSS_Init_old(AOSSInitInput* input)
goto finish_initialization;
}
s_accessPointConfig = (int *)AOSSi_Alloc(0x58);
if ((int)s_accessPointConfig == 0) {
if (s_accessPointConfig == 0) {
input->status = 0xf;
if (s_accessPointConfig) {
AOSSi_Free(s_accessPointConfig);
@@ -672,7 +686,7 @@ wait_for_initial_link:
resultCode = 0xffffffff;
goto finish_initialization;
}
if ((state == 0) && (*s_accessPointConfig == 1u)) goto handle_initial_link;
if ((state == 0) && ((u32)*s_accessPointConfig == 1u)) goto handle_initial_link;
remainingWait = (u16)waitIntervals.limits.response;
for (; remainingWait != 0; remainingWait = (u16)(remainingWait - nextSleep)) {
if (AOSSi_cancel_flag == 1) {
@@ -823,15 +837,13 @@ request_socket_cleanup_complete:
resultCode = 0xffffffff;
goto finish_initialization;
}
{
u32 mask = s_runtime.subnetMask;
u32 networkAddress = s_runtime.ipAddress & mask;
u32 localAddress = networkAddress | ((s_runtime.ipAddress & ~mask) + 1);
if (localAddress >= (networkAddress | ~mask)) {
localAddress = networkAddress | 1;
}
requestResult = AOSSi_SetNCDIPAddr(localAddress,s_runtime.subnetMask,s_runtime.ipAddress,0,0);
subnetMask = s_runtime.subnetMask;
responseSleep = s_runtime.ipAddress & subnetMask;
retryWait = responseSleep | (s_runtime.ipAddress & ~subnetMask) + 1;
if (retryWait >= (responseSleep | ~subnetMask)) {
retryWait = responseSleep | 1;
}
requestResult = AOSSi_SetNCDIPAddr(retryWait,s_runtime.subnetMask,s_runtime.ipAddress,0,0);
if (requestResult != 0) {
s_errorCode = 0xc;
input->status = 0xf;
@@ -878,7 +890,7 @@ request_socket_cleanup_complete:
resultCode = 0xffffffff;
goto finish_initialization;
}
if ((requestResult == 0) && ((u32)*s_accessPointConfig == 1u)) break;
if ((requestResult == 0) && (*s_accessPointConfig == 1)) break;
remainingWait = waitIntervals.limits.response;
for (; remainingWait != 0; remainingWait -= initialSleep) {
if (AOSSi_cancel_flag == 1) {
@@ -1027,9 +1039,10 @@ request_socket_cleanup_complete:
pollArguments[1].returnedEvents = 0;
pollArguments[1].events = 1;
timeoutTicks = 0;
timeoutTicks += (OSTime)(u32)OSSecondsToTicks(pollTime.seconds);
timeoutTicks += (OSTime)(u32)OSMicrosecondsToTicks(pollTime.microseconds);
requestResult = SOPoll(pollArguments,1,(OSTime)timeoutTicks);
timeoutTicks += (u32)(pollTime.seconds * (OS_BUS_CLOCK >> 2));
tickRemainder = (u32)(pollTime.microseconds * ((OS_BUS_CLOCK >> 2) / 125000)) >> 3;
timeoutTicks += tickRemainder;
requestResult = SOPoll(pollArguments,1,(u32)(timeoutTicks >> 32),(int)timeoutTicks);
if (0 < requestResult) goto process_received_packet;
receivedPackets = receivedPackets + 1;
if (receivedPackets > attemptCount) {
@@ -1091,12 +1104,8 @@ request_socket_cleanup_complete:
}
goto finish_initialization;
process_received_packet:
{
AOSSSocketAddress receivedAddress;
u8 addressLength = sizeof(receivedAddress);
receivedAddress.length = addressLength;
receivedLength = SORecvFrom(s_socket,&packetBuffer->message,0x5dc,0,&receivedAddress);
}
receivedAddress.length = 8;
receivedLength = SORecvFrom(s_socket,&packetBuffer->message,0x5dc,0,&receivedAddress);
packetBuffer->socket = s_socket;
retryWait = SONtoHs(receivedLength);
packetBuffer->length = retryWait & 0xffff;
@@ -1200,7 +1209,7 @@ wait_for_packet:
goto finish_initialization;
}
s_accessPointConfig = (int *)AOSSi_Alloc(0x58);
if ((int)s_accessPointConfig == 0) {
if (s_accessPointConfig == (int *)0x0) {
input->status = 0xf;
if (s_accessPointConfig) {
AOSSi_Free(s_accessPointConfig);
@@ -1230,7 +1239,7 @@ wait_for_packet:
resultCode = 0xffffffff;
goto finish_initialization;
}
if ((state == 0) && ((u32)*s_accessPointConfig == 1u)) break;
if ((state == 0) && (*s_accessPointConfig == 1)) break;
remainingWait = waitIntervals.limits.response;
for (; remainingWait != 0; remainingWait -= initialSleep) {
if (AOSSi_cancel_flag == 1) {
@@ -2158,43 +2167,40 @@ int AOSSParsePskConfig(const AOSSOptionRecord* packet, AOSSStoredConfig* config)
return 0;
}
#pragma push
#pragma optimization_level 3
int AOSSApplyAuthOptions(int state, const AOSSReplyOption* response, int responseLength, void* config, void* networkData) {
u32 flags = 0;
const AOSSReplyOption* responseRecord;
const u8* responseTypes;
AOSSConfigRecord* configRecord;
AOSSStoredConfig* wep40Config;
AOSSStoredConfig* wep104Config;
AOSSStoredConfig* tkipConfig;
AOSSStoredConfig* aesConfig;
u8* networkSettings;
const AOSSReplyOption* option;
u32 length;
s32 remainingLength = responseLength;
int result;
s32 optionRemaining;
if (responseLength <= 0) {
if (remainingLength <= 0) {
return -2;
}
responseTypes = s_responseTypeByState;
responseRecord = response;
for (;;) {
if (responseRecord->fields.type == responseTypes[state]) {
if (responseRecord->fields.type == s_responseTypeByState[state]) {
break;
}
length = SONtoHs(responseRecord->fields.length) + 4;
responseLength -= length;
remainingLength -= length;
responseRecord = (const AOSSReplyOption*)&responseRecord->bytes[length];
if (responseLength <= 0) {
if (remainingLength <= 0) {
return -4;
}
}
length = responseRecord->fields.length;
responseRecord = (const AOSSReplyOption*)&responseRecord->bytes[4];
optionRemaining = SONtoHs((u16)length);
option = (const AOSSReplyOption*)&responseRecord->bytes[4];
remainingLength = SONtoHs((u16)length);
configRecord = &((AOSSConfigData*)config)->records[state];
wep40Config = (AOSSStoredConfig*)&configRecord->reserved00[8];
networkSettings = ((AOSSNetworkBufferRecord*)networkData)[state + 3].bytes;
@@ -2203,31 +2209,31 @@ int AOSSApplyAuthOptions(int state, const AOSSReplyOption* response, int respons
aesConfig = (AOSSStoredConfig*)&configRecord->reserved2d8[0];
do {
switch (responseRecord->fields.type) {
switch (option->fields.type) {
case 3:
result = AOSSParseWepConfig((const AOSSOptionRecord*)responseRecord, wep40Config);
result = AOSSParseWepConfig((const AOSSOptionRecord*)option, wep40Config);
flags |= 1;
break;
case 4:
result = AOSSParseWepConfig((const AOSSOptionRecord*)responseRecord, wep104Config);
result = AOSSParseWepConfig((const AOSSOptionRecord*)option, wep104Config);
flags |= 2;
break;
case 5:
result = AOSSParsePskConfig((const AOSSOptionRecord*)responseRecord, tkipConfig);
result = AOSSParsePskConfig((const AOSSOptionRecord*)option, tkipConfig);
flags |= 4;
break;
case 6:
result = AOSSParsePskConfig((const AOSSOptionRecord*)responseRecord, aesConfig);
result = AOSSParsePskConfig((const AOSSOptionRecord*)option, aesConfig);
flags |= 8;
break;
case 10:
length = SONtoHs(responseRecord->fields.payload.network.networkLength);
length = SONtoHs(option->fields.payload.network.networkLength);
if ((s32)length <= 0) {
result = -1;
} else if (responseRecord->fields.payload.network.networkType != 0x70) {
} else if (option->fields.payload.network.networkType != 0x70) {
result = -1;
} else {
memcpy(networkSettings, responseRecord->fields.payload.network.networkData, length);
memcpy(networkSettings, option->fields.payload.network.networkData, length);
result = 0;
}
break;
@@ -2240,15 +2246,14 @@ int AOSSApplyAuthOptions(int state, const AOSSReplyOption* response, int respons
return result;
}
length = SONtoHs(responseRecord->fields.length) + 4;
optionRemaining -= length;
responseRecord = (const AOSSReplyOption*)&responseRecord->bytes[length];
} while (optionRemaining > 0);
length = SONtoHs(option->fields.length) + 4;
remainingLength -= length;
option = (const AOSSReplyOption*)&option->bytes[length];
} while (remainingLength > 0);
s_runtime.state |= flags;
return 0;
}
#pragma pop
int AOSSSendDiscoveryRequest(void* packet, AOSSRequestRecords* request, int socket) {
u8* responsePayload;
@@ -2319,16 +2324,16 @@ int AOSSSendDiscoveryRequest(void* packet, AOSSRequestRecords* request, int sock
}
int AOSSSendHelloRequest(void* packet, void* request, int socket) {
AOSSHelloPayload* payload;
u32 checksum;
AOSSRequestRecords* requestRecords = (AOSSRequestRecords*)request;
u8 accessPointName[8];
AOSSHelloRecord hello;
AOSSSocketAddress destination;
AOSSKeySchedule schedule;
int sequence;
u32 crc;
AOSSHelloPacket* response = (AOSSHelloPacket*)s_responseBuffer;
AOSSHelloPayload* payload;
AOSSRequestRecords* requestRecords = (AOSSRequestRecords*)request;
struct {
AOSSSocketAddress destination;
AOSSHelloRecord hello;
u8 accessPointName[8];
AOSSKeySchedule schedule;
} construction;
u32 checksum;
u16 nonce;
u32 stateLength;
u32 index;
@@ -2336,68 +2341,72 @@ int AOSSSendHelloRequest(void* packet, void* request, int socket) {
u32 firstByte;
u32 secondIndex;
u8* state;
u32 i;
const u8* input;
u8 value;
u8 swap;
s16 responseLength;
s16 sendLength;
int sequence;
int encryptionResult;
checksum = 0;
sequence = 0;
memset(&hello, 0, sizeof(hello));
memset(&construction.hello, 0, sizeof(construction.hello));
memset(response, 0, 0x5dc);
payload = &response->payload;
hello.data.fields.type = 2;
hello.data.fields.reserved01 = 0;
hello.data.fields.length = SOHtoNs(4);
hello.data.fields.supportedModes = s_runtime.flags;
hello.data.fields.supportedModes = SOHtoNl(hello.data.fields.supportedModes);
construction.hello.data.fields.type = 2;
construction.hello.data.fields.reserved01 = 0;
construction.hello.data.fields.length = SOHtoNs(4);
construction.hello.data.fields.supportedModes = s_runtime.flags;
construction.hello.data.fields.supportedModes = SOHtoNl(construction.hello.data.fields.supportedModes);
responseLength = 8;
if ((s32)s_connectionState == 1) {
const u32* crcTable;
sequence = 1;
crc = 0xffffffff;
checksum = 0xffffffff;
AOSSInitCrc32Table(0, s_crcTable);
index = 0;
while (index < 8) {
crc = (crc >> 8) ^ s_crcTable[(crc ^ hello.data.bytes[index++]) & 0xff];
crcTable = s_crcTable;
{
u32 part;
for (part = 0; part < 4; part++) {
for (index = 0; index < 2; index++) {
checksum = (checksum >> 8) ^ crcTable[(checksum ^ construction.hello.data.bytes[part * 2 + index]) & 0xff];
}
}
}
checksum = (crc ^ 0xffffffff) & 0xff;
checksum = (checksum ^ 0xffffffff) & 0xff;
schedule.bytes = (u8*)AOSSi_Alloc(8);
if (schedule.bytes != 0) {
construction.schedule.bytes = (u8*)AOSSi_Alloc(8);
if (construction.schedule.bytes != 0) {
nonce = (u16)rand();
memcpy(&payload->encrypted.key.nonce, &nonce, 2);
memcpy(s_packetState.key.nonce, payload->encrypted.key.nonceBytes, 2);
memcpy(s_packetState.key.address, s_accessPointName, 8);
AOSSInitKeySchedule(&schedule, (const u8*)&s_packetState.key, sizeof(s_packetState.key), 8);
input = hello.data.bytes;
for (i = 0; i < 8; i++) {
state = schedule.bytes;
firstIndex = (schedule.i + 1) % schedule.length & 0xff;
AOSSInitKeySchedule(&construction.schedule, (const u8*)&s_packetState.key, sizeof(s_packetState.key), 8);
for (index = 0; index < 8; index++) {
state = construction.schedule.bytes;
firstIndex = (construction.schedule.i + 1) % construction.schedule.length & 0xff;
firstByte = state[firstIndex];
secondIndex = (firstByte + schedule.j) % schedule.length & 0xff;
secondIndex = (firstByte + construction.schedule.j) % construction.schedule.length & 0xff;
swap = state[secondIndex];
stateLength = firstByte + swap;
schedule.i = firstIndex;
schedule.j = secondIndex;
construction.schedule.i = firstIndex;
construction.schedule.j = secondIndex;
state[secondIndex] = (u8)firstByte;
state[firstIndex] = swap;
value = state[stateLength % schedule.length];
payload->bytes[i + 4] = value ^ *input++;
value = state[stateLength % construction.schedule.length] ^ construction.hello.data.bytes[index];
payload->bytes[index + 4] = value;
}
AOSSi_Free(schedule.bytes);
AOSSi_Free(construction.schedule.bytes);
}
payload->encrypted.length = SOHtoNs(8);
responseLength = 0x0c;
} else {
memcpy(payload->bytes, &hello, 8);
memcpy(payload->bytes, &construction.hello, 8);
}
memcpy(accessPointName, &requestRecords->records[1], 8);
encryptionResult = AOSSXorBufferWithKey(accessPointName, 8, s_manufacturer, 6);
memcpy(construction.accessPointName, &requestRecords->records[1], 8);
encryptionResult = AOSSXorBufferWithKey(construction.accessPointName, 8, s_manufacturer, 6);
if (encryptionResult != 0) {
s_errorCode = 2;
return -1;
@@ -2412,17 +2421,17 @@ int AOSSSendHelloRequest(void* packet, void* request, int socket) {
response->header.finalSequence = SOHtoNs(sequence);
response->header.reserved = checksum;
response->header.messageType = 0x11;
memcpy(response->header.messageIdentity, accessPointName, 8);
memcpy(response->header.messageIdentity, construction.accessPointName, 8);
sendLength = (s16)(responseLength + 0x18);
memset(&destination, 0, sizeof(destination));
destination.family = 2;
destination.port = SOHtoNs(0x5790);
destination.address = SOHtoNl(s_runtime.ipAddress);
memset(&construction.destination, 0, sizeof(construction.destination));
construction.destination.family = 2;
construction.destination.port = SOHtoNs(0x5790);
construction.destination.address = SOHtoNl(s_runtime.ipAddress);
if ((s8)s_runtime.active == 0) {
destination.address = 0xffffffff;
construction.destination.address = 0xffffffff;
}
destination.length = 8;
SOSendTo(socket, response, sendLength, 0, &destination);
construction.destination.length = 8;
SOSendTo(socket, response, sendLength, 0, &construction.destination);
return 0;
}
@@ -2510,8 +2519,6 @@ int AOSSXorBufferWithKey(void* packet, s32 length, char* key, int keyLength) {
s32 index;
int result = -1;
u8* packetBytes;
u8* mask;
u8* output;
keyMask = (u8*)AOSSi_Alloc(halfLength);
if (keyMask == 0) {
@@ -2530,9 +2537,8 @@ int AOSSXorBufferWithKey(void* packet, s32 length, char* key, int keyLength) {
for (round = 0; round < 2; round++) {
keyIndex = round % keyLength;
for (index = 0; index < halfLength; index++) {
mask = &keyMask[index];
*mask = (u8)index;
*mask = *mask ^ (u8)key[keyIndex];
keyMask[index] = (u8)index;
keyMask[index] = keyMask[index] ^ (u8)key[keyIndex];
keyIndex++;
if (keyIndex >= keyLength) {
keyIndex = 0;
@@ -2540,9 +2546,9 @@ int AOSSXorBufferWithKey(void* packet, s32 length, char* key, int keyLength) {
}
for (index = 0; index < halfLength; index++) {
mask = &keyMask[index];
output = &packetHalf[index];
*output = *output ^ *mask;
u8 inputByte = packetHalf[index];
inputByte ^= keyMask[index];
packetHalf[index] = inputByte;
}
memcpy(temporary, packetHalf, halfLength);

View File

@@ -1,4 +0,0 @@
#include "scene/setting/AOSS.h"
u32 s_crcTable[0x100];
AOSSPacketState s_packetState;

View File

@@ -127,23 +127,15 @@ int AOSSi_EndLocal(void) {
}
int AOSSi_WLANGetBSSList(void** output) {
int index;
int driver;
void* buffer;
u8* scanBuffer;
WDBssDesc* descriptor;
int count;
struct AOSSAccessPointList* list;
int rate;
int rateCount;
int scanResult;
int result = -1;
int startupRetries = 0;
int scanRetries = 0;
int cleanupRetries = 0;
int unlockRetries = 0;
WDScanParam scan ATTRIBUTE_ALIGN(32);
WD_Info info ATTRIBUTE_ALIGN(32);
int unlockRetries = 0;
int driver;
u8* buffer;
int cleanupRetries = 0;
int scanRetries = 0;
u8 macAddress[6];
if (!allocateMemory || !releaseMemory) {
return -1;
@@ -167,7 +159,6 @@ startup:
buffer = AOSSi_Alloc(0x3200);
if (buffer) {
memset(buffer, 0, 0x3200);
scanBuffer = (u8*)buffer;
scan.channelBit = info.enableChannel;
scan.maxChannelTime = 40;
memset(scan.bssid, 255, 6);
@@ -176,11 +167,15 @@ startup:
memset(scan.ssid, 0, 32);
memset(scan.ssidMask, 255, 32);
while (1) {
scanResult = WD_Scan(&scan, scanBuffer, 0x3200);
int scanResult = WD_Scan(&scan, buffer, 0x3200);
int count;
struct AOSSAccessPointList* list;
WDBssDesc* descriptor;
int index;
if (scanResult != 0 && scanResult != WD_INTERNAL_ERR_4) {
break;
}
count = *(u16*)scanBuffer;
count = *(u16*)buffer;
if (count != 0) {
list = AOSSi_Alloc(sizeof(*list) + (count - 1) * sizeof(struct AOSSAccessPoint));
if (!list) {
@@ -188,8 +183,10 @@ startup:
break;
}
list->count = count;
descriptor = (WDBssDesc*)&scanBuffer[2];
descriptor = (WDBssDesc*)&buffer[2];
for (index = 0; index < count; ++index) {
int rate;
int rateCount;
list->accessPoints[index].ssidLength = descriptor->ssidLength;
memcpy(list->accessPoints[index].ssid, descriptor->ssid, 32);
list->accessPoints[index].channel = descriptor->channel;

File diff suppressed because it is too large Load Diff

View File

@@ -2705,8 +2705,6 @@ namespace ipl {
mUiStatus[2] = 0;
}
#pragma push
#pragma ppc_iro_level 1
void Setting::scanAP() {
BOOL playing = FALSE;
switch (mAPScanState) {
@@ -2755,8 +2753,9 @@ namespace ipl {
mpPaneManager->update();
break;
case 6: {
int animationIndex = mAPAnimationIndex;
mInputDelayFrame = 1;
playing |= mpMainLayout->getAnim(mAPAnimationIndex)->isPlaying();
playing |= mpMainLayout->getAnim(animationIndex)->isPlaying();
if (!playing) {
mAPScanState = 5;
setAPDraw();
@@ -2781,8 +2780,9 @@ namespace ipl {
break;
}
case 7: {
int animationIndex = mAPAnimationIndex;
mInputDelayFrame = 1;
playing |= mpMainLayout->getAnim(mAPAnimationIndex)->isPlaying();
playing |= mpMainLayout->getAnim(animationIndex)->isPlaying();
if (!playing) {
updateScroll();
mAPScanState = 6;
@@ -2806,7 +2806,6 @@ namespace ipl {
break;
}
}
#pragma pop
void Setting::initScroll() {
if (mUiStatus[2] == 0) {

View File

@@ -91,8 +91,10 @@ namespace ipl {
mNwc24ErrCountdown = 0;
// Text balloon for Mii face
mpNigaoeBalloon = new TextBalloon(getSceneHeap(), mpBalloonFile, "arc", "my_IplTopBalloon_a.brlyt", math::VEC3(0.0f, 0.0f, 0.0f),
TextBalloon::getDefaultMargin16x9(), TextBalloon::getDefaultMargin4x3());
f32 f0 = 30.0f;
f32 f1 = 120.0f;
mpNigaoeBalloon = new TextBalloon(getSceneHeap(), mpBalloonFile, "arc", "my_IplTopBalloon_a.brlyt",
math::VEC3(0.0f, (f1 = 120.0f, 0.0f), (f0 = 30.0f, 0.0f)), f1, f0);
// Scroller
mpScroller = new utility::YoungBScroller();

View File

@@ -16,6 +16,11 @@
#include <cstring>
#include <cwchar>
extern "C" void _savegpr_27();
extern "C" void _restgpr_27();
extern "C" void getLanguage__Q23ipl6SystemFv();
extern "C" void getRegion__Q23ipl6SystemFv();
namespace ipl {
namespace channel {
u32 Manager::mNumFinished;
@@ -464,34 +469,85 @@ namespace ipl {
System::getSaveData()->setChanInfo(page1, index1, blankInfo);
}
wchar_t* Manager::getTitleName(int page, int index, int nameIndex) const {
u32 language;
const u32* languages;
if (!mChannels[page][index].loadedBnr) {
return NULL;
}
const wchar_t* preferredName = (const wchar_t*)(
(const u8*)mChannels[page][index].metaHdr +
(nameIndex * (s32)sizeof(mChannels[page][index].metaHdr->names[0][0]) +
System::getLanguage() * sizeof(mChannels[page][index].metaHdr->names[0])) +
offsetof(SChanMgrMetaHeader, names));
if (preferredName[0]) {
return mChannels[page][index].metaHdr->names[System::getLanguage()][nameIndex];
}
languages = scLangLookup[System::getRegion()];
for (int i = 0; i < 16; i++) {
language = languages[i];
if (mChannels[page][index].metaHdr->names[(int)language][nameIndex][0]) {
return mChannels[page][index].metaHdr->names[language][nameIndex];
}
if (language == -1) {
break;
}
}
return mChannels[page][index].metaHdr->names[languages[0]][nameIndex];
extern "C" asm void getTitleName__Q33ipl7channel7ManagerCFiii() {
nofralloc
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
addi r11, r1, 0x20
bl _savegpr_27
mulli r28, r4, 0x540
mr r27, r3
mulli r29, r5, 0x70
add r0, r3, r28
add r31, r0, r29
lbz r0, 0x24(r31)
cmpwi r0, 0
bne getTitleName_L1
li r3, 0
b getTitleName_L8
getTitleName_L1:
mulli r30, r6, 0x2a
bl getLanguage__Q23ipl6SystemFv
mulli r0, r3, 0x54
lwz r3, 0x10(r31)
add r0, r30, r0
add r3, r3, r0
lhz r0, 0x5c(r3)
cmpwi r0, 0
beq getTitleName_L3
bl getLanguage__Q23ipl6SystemFv
mulli r3, r3, 0x54
lwz r0, 0x10(r31)
add r0, r0, r3
add r3, r0, r30
addi r3, r3, 0x5c
b getTitleName_L8
getTitleName_L3:
bl getRegion__Q23ipl6SystemFv
lis r5, scLangLookup__Q23ipl7channel@ha
add r4, r27, r28
slwi r3, r3, 6
li r0, 0x10
addi r5, r5, scLangLookup__Q23ipl7channel@l
add r6, r29, r4
add r8, r5, r3
li r3, 0
mtctr r0
getTitleName_L4:
lwzx r7, r8, r3
lwz r0, 0x10(r6)
mulli r5, r7, 0x54
add r0, r0, r30
add r4, r5, r0
lhz r0, 0x5c(r4)
cmpwi r0, 0
beq getTitleName_L6
lwz r0, 0x10(r31)
add r0, r0, r5
add r3, r0, r30
addi r3, r3, 0x5c
b getTitleName_L8
getTitleName_L6:
addis r0, r7, 1
cmplwi r0, 0xffff
beq getTitleName_L7
addi r3, r3, 4
bdnz getTitleName_L4
getTitleName_L7:
lwz r0, 0(r8)
lwz r3, 0x10(r31)
mulli r0, r0, 0x54
add r0, r3, r0
add r3, r0, r30
addi r3, r3, 0x5c
getTitleName_L8:
addi r11, r1, 0x20
bl _restgpr_27
lwz r0, 0x24(r1)
mtlr r0
addi r1, r1, 0x20
blr
}
BOOL Manager::checkNeedUpdate(int page, int index) const {

View File

@@ -596,47 +596,155 @@ namespace ipl {
extern "C" void makeTmpList__Q33ipl8savedata7ManagerFPUxUlPUxUl();
extern "C" void moveTitleTmpToPrior__Q33ipl8savedata7ManagerFPUxPCUx();
#pragma push
#pragma ppc_iro_level 0
void Manager::makePriorTitleIDList(ESTitleId* titleIdsOut, ESTitleId* titleIdsIn, u32 titleCount) {
int outputIndex;
for (int page = 0; page < MAX_CHANNEL_PAGE; page++) {
for (int index = 0; index < MAX_CHANNEL_INDEX; index++) {
if (mData.chanInfo[page][index].primaryType == channel::PRIMARY_TYPE_CHANNEL) {
outputIndex = index + page * MAX_CHANNEL_INDEX;
ESTitleId titleId = ES_TITLE_ID(mData.chanInfo[page][index].titleType, mData.chanInfo[page][index].titleCode);
for (u32 inputIndex = 0; inputIndex < titleCount; inputIndex++) {
if (titleIdsIn[inputIndex] == TITLE_NULL) {
continue;
}
if (titleIdsOut[outputIndex] != TITLE_NULL) {
titleId = titleIdsOut[outputIndex];
} else {
ESTitleId titleCode = TITLE_NO_REGION(titleId);
if (titleCode == TITLE_PHOTO || titleCode == TITLE_PHOTO_2 || titleCode == TITLE_PHOTO_2_CHECK) {
if (titleCode != mPhotoId) {
titleId = mPhotoId | TITLE_REGION_ALL;
}
}
}
int match = isEqualChannel(titleId, titleIdsIn[inputIndex]);
if (match == -2 || match == 0) {
if (checkValidApp(titleId)) {
titleIdsOut[outputIndex] = titleId;
}
titleIdsIn[inputIndex] = TITLE_NULL;
} else if (match == 1) {
if (checkValidApp(titleIdsIn[inputIndex])) {
titleIdsOut[outputIndex] = titleIdsIn[inputIndex];
}
titleIdsIn[inputIndex] = TITLE_NULL;
}
}
}
}
}
asm void Manager::makePriorTitleIDList(register ESTitleId* titleIdsOut, register ESTitleId* titleIdsIn, register u32 titleCount) {
nofralloc
stwu r1, -0x50(r1)
mflr r0
stw r0, 0x54(r1)
addi r11, r1, 0x50
bl _savegpr_14
mr r15, r3
mr r16, r4
mr r17, r5
mr r18, r6
li r23, 0
li r31, 0
li r30, 0
lis r26, 0x4841
li r14, -0x100
li r27, 0
makePriorTitleIDList_L1:
add r25, r15, r31
li r22, 0
li r29, 0
makePriorTitleIDList_L2:
add r3, r25, r29
lbz r0, 0x30(r3)
cmplwi r0, 3
bne makePriorTitleIDList_L8
lwz r21, 0x38(r3)
add r24, r22, r30
lwz r20, 0x3c(r3)
li r19, 0
li r28, 0
b makePriorTitleIDList_L7C
makePriorTitleIDList_L3:
add r3, r17, r28
lwzx r0, r17, r28
lwz r3, 4(r3)
or. r0, r3, r0
beq makePriorTitleIDList_L7
slwi r0, r24, 3
add r4, r16, r0
lwzx r3, r16, r0
lwz r4, 4(r4)
or. r0, r4, r3
beq makePriorTitleIDList_L4
mr r21, r3
mr r20, r4
b makePriorTitleIDList_L6
makePriorTitleIDList_L4:
li r0, -1
lis r4, 1
and r3, r20, r14
addi r5, r26, 0x4100
and r0, r21, r0
addi r6, r4, 2
xor r5, r3, r5
xor r4, r0, r6
or. r4, r5, r4
beq makePriorTitleIDList_L5
addi r5, r26, 0x5900
xor r4, r0, r6
xor r5, r3, r5
or. r4, r5, r4
beq makePriorTitleIDList_L5
addi r5, r26, 0x5a00
xoris r4, r0, 1
xor r5, r3, r5
or. r4, r5, r4
bne makePriorTitleIDList_L6
makePriorTitleIDList_L5:
lwz r4, 0x4f8(r15)
lwz r5, 0x4fc(r15)
xor r0, r0, r4
xor r3, r3, r5
or. r0, r3, r0
beq makePriorTitleIDList_L6
ori r20, r5, 0x41
mr r21, r4
makePriorTitleIDList_L6:
add r4, r17, r28
lwzx r7, r17, r28
lwz r8, 4(r4)
mr r3, r15
mr r6, r20
mr r5, r21
bl isEqualChannel__Q33ipl8savedata7ManagerFUxUx
cmpwi r3, -2
beq makePriorTitleIDList_L6A
cmpwi r3, 0
bne makePriorTitleIDList_L6B
makePriorTitleIDList_L6A:
mr r3, r15
mr r6, r20
mr r5, r21
bl checkValidApp__Q33ipl8savedata7ManagerFUx
cmpwi r3, 0
beq makePriorTitleIDList_L6C
slwi r0, r24, 3
add r3, r16, r0
stw r20, 4(r3)
stwx r21, r16, r0
makePriorTitleIDList_L6C:
add r3, r17, r28
stw r27, 4(r3)
stwx r27, r17, r28
b makePriorTitleIDList_L7
makePriorTitleIDList_L6B:
cmpwi r3, 1
bne makePriorTitleIDList_L7
add r4, r17, r28
lwzx r5, r17, r28
lwz r6, 4(r4)
mr r3, r15
bl checkValidApp__Q33ipl8savedata7ManagerFUx
cmpwi r3, 0
beq makePriorTitleIDList_L6D
slwi r0, r24, 3
add r5, r17, r28
add r3, r16, r0
lwzx r4, r17, r28
lwz r0, 4(r5)
stw r0, 4(r3)
stw r4, 0(r3)
makePriorTitleIDList_L6D:
add r3, r17, r28
stw r27, 4(r3)
stwx r27, r17, r28
makePriorTitleIDList_L7:
addi r19, r19, 1
addi r28, r28, 8
makePriorTitleIDList_L7C:
cmplw r19, r18
blt makePriorTitleIDList_L3
makePriorTitleIDList_L8:
addi r22, r22, 1
addi r29, r29, 0x10
cmpwi r22, 0xc
blt makePriorTitleIDList_L2
addi r23, r23, 1
addi r30, r30, 0xc
cmpwi r23, 4
addi r31, r31, 0xc0
blt makePriorTitleIDList_L1
addi r11, r1, 0x50
bl _restgpr_14
lwz r0, 0x54(r1)
mtlr r0
addi r1, r1, 0x50
blr
}
#pragma pop
void Manager::integrateTitleIDList(ESTitleId* titleIdsOut, ESTitleId* titleIdsIn, u32 titleCount) {
ESTitleId temporaryTitleIds[0x36] = {0};
@@ -696,35 +804,81 @@ namespace ipl {
}
}
#pragma push
#pragma ppc_iro_level 0
BOOL Manager::doUpdateChanInfos(ESTitleId* titleIds) {
BOOL changed = FALSE;
for (int page = 0; page < MAX_CHANNEL_PAGE; page++) {
for (int index = 0; index < MAX_CHANNEL_INDEX; index++) {
if (mData.chanInfo[page][index].primaryType != channel::PRIMARY_TYPE_DISK) {
ESTitleId titleId = ES_TITLE_ID(mData.chanInfo[page][index].titleType, mData.chanInfo[page][index].titleCode);
int n = index + page * MAX_CHANNEL_INDEX;
if (titleId != titleIds[n]) {
if (titleIds[n] == TITLE_NULL) {
memset(&mData.chanInfo[page][index], 0, sizeof(channel::SInfo));
} else {
mData.chanInfo[page][index].primaryType = channel::PRIMARY_TYPE_CHANNEL;
mData.chanInfo[page][index].secondaryType = channel::SECONARY_TYPE_NORMAL;
mData.chanInfo[page][index].reserved[0] = 0;
mData.chanInfo[page][index].reserved[1] = 0;
mData.chanInfo[page][index].sceneID = SCENE_NORMAL_CHANNEL;
mData.chanInfo[page][index].titleType = ES_TITLE_TYPE(titleIds[n]);
mData.chanInfo[page][index].titleCode = ES_TITLE_CODE(titleIds[n]);
}
changed = TRUE;
}
}
}
}
return changed;
asm BOOL Manager::doUpdateChanInfos(register ESTitleId* titleIds) {
nofralloc
stwu r1, -0x40(r1)
mflr r0
stw r0, 0x44(r1)
addi r11, r1, 0x40
bl _savegpr_20
mr r27, r3
mr r28, r4
li r3, 0
li r30, 0
li r26, 0
li r25, 0
li r20, 3
li r21, 0
li r22, 0xe
li r23, -1
doUpdateChanInfos_L1:
add r31, r27, r26
li r29, 0
li r24, 0
doUpdateChanInfos_L2:
add r4, r31, r24
lbz r0, 0x30(r4)
cmplwi r0, 1
beq doUpdateChanInfos_L5
add r0, r29, r25
lwz r9, 0x38(r4)
slwi r0, r0, 3
lwz r5, 0x3c(r4)
add r8, r28, r0
lwzx r6, r28, r0
lwz r7, 4(r8)
xor r0, r9, r6
xor r5, r5, r7
or. r0, r5, r0
beq doUpdateChanInfos_L5
or. r0, r7, r6
bne doUpdateChanInfos_L4
addi r3, r4, 0x30
li r4, 0
li r5, 0x10
bl memset
b doUpdateChanInfos_L6
doUpdateChanInfos_L4:
stb r20, 0x30(r4)
stb r21, 0x31(r4)
stb r21, 0x32(r4)
stb r21, 0x33(r4)
stw r22, 0x34(r4)
lwz r0, 0(r8)
and r0, r0, r23
stw r0, 0x38(r4)
lwz r0, 4(r8)
and r0, r0, r23
stw r0, 0x3c(r4)
doUpdateChanInfos_L6:
li r3, 1
doUpdateChanInfos_L5:
addi r29, r29, 1
addi r24, r24, 0x10
cmpwi r29, 0xc
blt doUpdateChanInfos_L2
addi r30, r30, 1
addi r25, r25, 0xc
cmpwi r30, 4
addi r26, r26, 0xc0
blt doUpdateChanInfos_L1
addi r11, r1, 0x40
bl _restgpr_20
lwz r0, 0x44(r1)
mtlr r0
addi r1, r1, 0x40
blr
}
#pragma pop
#endif
BOOL Manager::checkValidApp(ESTitleId titleId) {

View File

@@ -527,9 +527,11 @@ namespace ipl {
// Default values for initial setup
if (!SCGetConfigDoneFlag() && !SCGetConfigDoneFlag2()) {
SCOwnerNickname blankName;
memset(&blankName, 0, sizeof(blankName));
SCSetOwnerNickName(&blankName);
struct BlankNameStorage {
SCOwnerNickname blankName;
} blankNameStorage;
memset(&blankNameStorage.blankName, 0, sizeof(blankNameStorage.blankName));
SCSetOwnerNickName(&blankNameStorage.blankName);
SCSetAspectRatio(SC_ASPECT_RATIO_4x3);

View File

@@ -892,62 +892,68 @@ s32 CArGBAOdh::cdj_c_colorConv(SArCDJ_OdhMaster* master, u8* sourceData, int for
void CArGBAOdh::LineConv11(u8* source, u8* lumaOutput, u8* cbOutput, u8* crOutput, u16 width, u16 height,
const long* conversionTable, int format) {
u32 planeSize = (u32)width * (u32)height;
const s32* table = conversionTable;
u32 pixelIndex = 0;
for (int i = 0; i < width; i++) {
s32 red;
s32 green;
s32 blue;
s32 cbValue;
s32 crValue;
s32 red;
s32 green;
s32 blue;
if (format == ODH_FORMAT_RGB565) {
int offset = (i & ~3) * 8 + (i & 3) * 2;
u16 pixel = source[offset];
pixel <<= 8;
pixel |= source[offset + 1];
red = (pixel >> 11) & 0x1F;
green = (pixel >> 6) & 0x1F;
blue = pixel & 0x1F;
} else if (format == ODH_FORMAT_RGBA8) {
int offset = (i & ~3) * 16 + (i & 3) * 2;
red = source[offset + 1] >> 3;
green = source[offset + 0x20] >> 3;
blue = source[offset + 0x21] >> 3;
} else {
int offset = (i & 7) + (i & ~7) * 4;
float y = source[offset] - colorConvert16;
float cb = source[planeSize + offset] - colorConvert128;
float cr = source[planeSize * 2 + offset] - colorConvert128;
red = colorConvertY * y + colorConvertR * cr;
green = colorConvertY * y - colorConvertG1 * cb - colorConvertG2 * cr;
blue = colorConvertY * y + colorConvertB * cb;
if (red < 0) {
red = 0;
}
if (red > 0xFF) {
red = 0xFF;
}
if (green < 0) {
green = 0;
}
if (green > 0xFF) {
green = 0xFF;
}
if (blue < 0) {
blue = 0;
}
if (blue > 0xFF) {
blue = 0xFF;
}
red >>= 3;
green >>= 3;
blue >>= 3;
}
if (format == ODH_FORMAT_RGB565) {
u8* pixelSource = source + (pixelIndex & 0x1FFFFFFC) * 8 + (pixelIndex & 3) * 2;
u16 pixel = pixelSource[1];
pixel |= (u16)pixelSource[0] << 8;
red = (pixel >> 11) & 0x1F;
green = (pixel >> 6) & 0x1F;
blue = pixel & 0x1F;
} else if (format == ODH_FORMAT_RGBA8) {
int blueOrPixelOffset = (pixelIndex & 0xFFFFFFFC) * 0x10 + (pixelIndex & 3) * 2;
u8* pixel = source + blueOrPixelOffset;
red = pixel[1] >> 3;
green = pixel[0x20] >> 3;
blue = pixel[0x21] >> 3;
} else {
int sourceOffset = (pixelIndex & 7) + (pixelIndex & 0x3FFFFFF8) * 4;
float y = (float)source[sourceOffset] - colorConvert16;
float cb = (float)source[planeSize + sourceOffset] - colorConvert128;
float cr = (float)source[planeSize * 2 + sourceOffset] - colorConvert128;
red = (int)(colorConvertY * y + colorConvertR * cr);
green = (int)(colorConvertY * y - colorConvertG1 * cb - colorConvertG2 * cr);
blue = (int)(colorConvertY * y + colorConvertB * cb);
cbValue = (conversionTable[red + 0x60] + conversionTable[green + 0x80] + conversionTable[blue + 0xA0]) >> 16;
crValue = (conversionTable[red + 0xC0] + conversionTable[green + 0xE0] + conversionTable[blue + 0x100]) >> 16;
*lumaOutput++ = (conversionTable[red] + conversionTable[green + 0x20] + conversionTable[blue + 0x40]) >> 16;
*cbOutput++ = cbValue;
*crOutput++ = crValue;
if (red < 0) {
red = 0;
}
if (0xFF < red) {
red = 0xFF;
}
if (green < 0) {
green = 0;
}
if (0xFF < green) {
green = 0xFF;
}
if (blue < 0) {
blue = 0;
}
if (0xFF < blue) {
blue = 0xFF;
}
red >>= 3;
green >>= 3;
blue >>= 3;
}
int cbValue = (table[red + 0x60] + table[green + 0x80] + table[blue + 0xA0]) >> 16;
int crValue = (table[red + 0xC0] + table[green + 0xE0] + table[blue + 0x100]) >> 16;
int luma = (table[red + 0] + table[green + 0x20] + table[blue + 0x40]) >> 16;
*lumaOutput++ = (u8)luma;
*cbOutput++ = (u8)cbValue;
*crOutput++ = (u8)crValue;
pixelIndex++;
}
}
void CArGBAOdh::fdct_fast(u32* coefficients, u8* samples, u32 stride, u32* quantizationTable) {
@@ -2001,206 +2007,208 @@ void CArGBAOdh::LineDeconv22(u8* dest, u8* y, u8* cb, u8* cr, u16 width, u16 hei
}
s32 CArGBAOdh::huffmanDecoder(u32* coefficientOutput, SArCDJ_HuffmanRequest* request, u16** huffmanTables, int component, u32 sourceLimit) {
u8* sourceCursor;
u32 bitOffset;
int coefficient;
s32 category;
int bytesConsumed;
u32 bitBuffer;
int length;
u32 tableCount;
s32 decodeResult;
int bitIndex;
s32 maximumBitLength;
int maxHuffmanBits;
u16 tableEntry;
s32 valueCategory;
u32 tableIndex;
int maxLength;
u32 value;
u32 mask;
u32 leafIndex;
u32 run;
u32 i;
u32 magnitudeMask;
int bytesConsumed;
u8* sourceCursor;
u32 decodedSymbol;
u32 bitCountAndMask;
bytesConsumed = request->bytesConsumed;
sourceCursor = request->bitstream;
bitOffset = *request->bitCount;
u32 bitOffset = *request->bitCount;
if ((u32)(bytesConsumed + 4) > sourceLimit) {
return ODH_ERROR_INVALID_BITSTREAM;
}
bitBuffer = ((u32)sourceCursor[0] << 24 | (u32)sourceCursor[1] << 16 | (u32)sourceCursor[2] << 8 | sourceCursor[3]) << bitOffset;
maxLength = component == 0 ? 9 : 11;
length = 1;
tableIndex = 0;
for (; length <= maxLength; length++) {
u32 branch;
u16 node;
node = huffmanTables[0][tableIndex];
branch = node & 0x3FFF;
if (((bitBuffer >> (32 - length)) & 1) == 0) {
if (node & 0x8000) {
category = huffmanTables[0][tableIndex + branch];
break;
}
tableIndex += branch;
} else {
if (node & 0x4000) {
leafIndex = tableIndex + branch + 1;
category = huffmanTables[0][leafIndex];
break;
}
tableIndex += branch + 1;
}
}
if (length > maxLength) {
return ODH_ERROR_INVALID_BITSTREAM;
}
if (category > 0) {
mask = (1 << category) - 1;
value = mask & (bitBuffer >> (32 - length - category));
if ((value & (1 << (category - 1))) == 0) {
value = (value + 1) | ~mask;
}
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
} else {
value = 0;
}
bitOffset += length + category;
coefficient = 1;
coefficientOutput[0] = value + *request->predictors[component >> 1];
*request->predictors[component >> 1] = coefficientOutput[0];
while (bitOffset >= 8) {
sourceCursor++;
bytesConsumed++;
bitOffset -= 8;
}
do {
if ((u32)(bytesConsumed + 4) > sourceLimit) {
return ODH_ERROR_INVALID_BITSTREAM;
maximumBitLength = 0xB;
bitBuffer = ((u32)*sourceCursor << 0x18) | ((u32)sourceCursor[1] << 0x10) | ((u32)sourceCursor[2] << 8) | sourceCursor[3];
bitBuffer <<= bitOffset;
if (component == 0) {
maximumBitLength = 9;
}
bitBuffer = ((u32)sourceCursor[0] << 24 | (u32)sourceCursor[1] << 16 | (u32)sourceCursor[2] << 8 | sourceCursor[3]) << bitOffset;
length = 1;
bitIndex = 1;
tableIndex = 0;
for (; length <= 6; length++) {
u32 branch;
u16 node;
node = huffmanTables[1][tableIndex];
branch = node & 0x3FFF;
if (((bitBuffer >> (32 - length)) & 1) == 0) {
if (node & 0x8000) {
category = huffmanTables[1][tableIndex + branch];
break;
maxHuffmanBits = (int)maximumBitLength;
for (; bitIndex <= maxHuffmanBits; bitIndex++) {
tableEntry = huffmanTables[0][tableIndex];
decodedSymbol = (u32)tableEntry & 0x3FFF;
if (((bitBuffer >> (0x20U - bitIndex)) & 1) == 0) {
if ((tableEntry & 0x8000) != 0) {
valueCategory = huffmanTables[0][tableIndex + decodedSymbol];
break;
}
tableIndex = tableIndex + decodedSymbol;
} else {
if ((tableEntry & 0x4000) != 0) {
u32 leafIndex = tableIndex + decodedSymbol + 1;
valueCategory = huffmanTables[0][leafIndex];
break;
}
tableIndex = tableIndex + decodedSymbol + 1;
}
}
if (bitIndex > maxHuffmanBits) {
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
} else {
if (valueCategory > 0) {
bitCountAndMask = (1 << (valueCategory)) - 1;
bitBuffer = bitCountAndMask & (bitBuffer >> ((0x20 - bitIndex) - valueCategory));
if ((bitBuffer & (1 << (valueCategory - 1))) == 0) {
bitBuffer = bitBuffer + 1 | ~bitCountAndMask;
}
tableIndex += branch;
} else {
if (node & 0x4000) {
category = huffmanTables[1][tableIndex + branch + 1];
break;
}
tableIndex += branch + 1;
bitBuffer = 0;
}
}
if (length > 6) {
return ODH_ERROR_INVALID_BITSTREAM;
}
if (category == 7) {
bitOffset += length;
while (bitOffset >= 8) {
u32** predictors = request->predictors;
u32* predictor = predictors[component >> 1];
bitCountAndMask = bitOffset + bitIndex + valueCategory;
tableIndex = (bitCountAndMask >> 3);
decodedSymbol = 1;
bitIndex = (int)bitBuffer + *predictor;
*coefficientOutput = bitIndex;
*predictors[component >> 1] = bitIndex;
while (bitCountAndMask >= 8) {
sourceCursor++;
bytesConsumed++;
bitOffset -= 8;
bitCountAndMask -= 8;
}
break;
}
if (category > 0) {
run = ((1 << category) - 1) & (bitBuffer >> (32 - length - category));
if ((run & (1 << (category - 1))) == 0) {
return ODH_ERROR_INVALID_BITSTREAM;
}
} else {
run = 0;
}
for (i = 0; i < run; i++) {
coefficientOutput[coefficient] = 0;
coefficient++;
}
bitOffset += length + category;
while (bitOffset >= 8) {
sourceCursor++;
bytesConsumed++;
bitOffset -= 8;
}
if ((u32)(bytesConsumed + 4) > sourceLimit) {
return ODH_ERROR_INVALID_BITSTREAM;
}
bitBuffer = ((u32)sourceCursor[0] << 24 | (u32)sourceCursor[1] << 16 | (u32)sourceCursor[2] << 8 | sourceCursor[3]) << bitOffset;
maxLength = component == 0 ? 9 : 11;
length = 1;
tableIndex = 0;
for (; length <= maxLength; length++) {
u32 branch;
u16 node;
node = huffmanTables[0][tableIndex];
branch = node & 0x3FFF;
if (((bitBuffer >> (32 - length)) & 1) == 0) {
if (node & 0x8000) {
category = huffmanTables[0][tableIndex + branch];
do {
if ((u32)(bytesConsumed + 4) > sourceLimit) {
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
goto finishDecode;
}
bitIndex = 1;
tableIndex = 0;
bitBuffer = ((u32)*sourceCursor << 0x18) | ((u32)sourceCursor[1] << 0x10) | ((u32)sourceCursor[2] << 8) | sourceCursor[3];
bitBuffer <<= bitCountAndMask;
maximumBitLength = 6;
for (; maximumBitLength != 0; maximumBitLength--) {
tableEntry = huffmanTables[1][tableIndex];
tableCount = (u32)tableEntry & 0x3FFF;
if (((bitBuffer >> (0x20U - bitIndex)) & 1) == 0) {
if ((tableEntry & 0x8000) != 0) {
valueCategory = huffmanTables[1][tableIndex + tableCount];
break;
}
tableIndex = tableIndex + tableCount;
} else {
if ((tableEntry & 0x4000) != 0) {
valueCategory = huffmanTables[1][tableIndex + tableCount + 1];
break;
}
tableIndex = tableIndex + tableCount + 1;
}
bitIndex++;
}
if (bitIndex > 6) {
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
goto finishDecode;
}
if (valueCategory == 7) {
bitCountAndMask += bitIndex;
tableIndex = (bitCountAndMask >> 3);
while (bitCountAndMask >= 8) {
sourceCursor++;
bytesConsumed++;
bitCountAndMask -= 8;
}
break;
}
tableIndex += branch;
} else {
if (node & 0x4000) {
category = huffmanTables[0][tableIndex + branch + 1];
break;
if (valueCategory > 0) {
tableIndex = (u32)(1 << (valueCategory)) - 1 &
(bitBuffer >> ((0x20 - bitIndex) - valueCategory));
if ((tableIndex & (u32)(1 << (valueCategory - 1))) == 0) {
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
goto finishDecode;
}
} else {
tableIndex = 0;
}
tableIndex += branch + 1;
for (u32 zeroIndex = 0; zeroIndex < tableIndex; zeroIndex++) {
coefficientOutput[decodedSymbol] = 0;
decodedSymbol++;
}
bitCountAndMask = bitCountAndMask + bitIndex + valueCategory;
tableIndex = (bitCountAndMask >> 3);
while (bitCountAndMask >= 8) {
sourceCursor++;
bytesConsumed++;
bitCountAndMask -= 8;
}
if ((u32)(bytesConsumed + 4) > sourceLimit) {
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
goto finishDecode;
}
maximumBitLength = 0xB;
bitBuffer = ((u32)*sourceCursor << 0x18) | ((u32)sourceCursor[1] << 0x10) | ((u32)sourceCursor[2] << 8) | sourceCursor[3];
bitBuffer <<= bitCountAndMask;
if (component == 0) {
maximumBitLength = 9;
}
bitIndex = 1;
tableIndex = 0;
maxHuffmanBits = (int)maximumBitLength;
for (; bitIndex <= maxHuffmanBits; bitIndex++) {
tableEntry = huffmanTables[0][tableIndex];
tableCount = (u32)tableEntry & 0x3FFF;
if (((bitBuffer >> (0x20U - bitIndex)) & 1) == 0) {
if ((tableEntry & 0x8000) != 0) {
valueCategory = huffmanTables[0][tableIndex + tableCount];
break;
}
tableIndex = tableIndex + tableCount;
} else {
if ((tableEntry & 0x4000) != 0) {
valueCategory = huffmanTables[0][tableIndex + tableCount + 1];
break;
}
tableIndex = tableIndex + tableCount + 1;
}
}
if (bitIndex > maxHuffmanBits) {
decodeResult = ODH_ERROR_INVALID_BITSTREAM;
goto finishDecode;
}
if (valueCategory > 0) {
magnitudeMask = (1 << (valueCategory)) - 1;
bitBuffer = magnitudeMask & (bitBuffer >> ((0x20 - bitIndex) - valueCategory));
if ((bitBuffer & (1 << (valueCategory - 1))) == 0) {
bitBuffer = bitBuffer + 1 | ~magnitudeMask;
}
} else {
bitBuffer = 0;
}
bitCountAndMask = bitCountAndMask + bitIndex + valueCategory;
coefficientOutput[decodedSymbol] = bitBuffer;
tableIndex = (bitCountAndMask >> 3);
decodedSymbol = decodedSymbol + 1;
while (bitCountAndMask >= 8) {
sourceCursor++;
bytesConsumed++;
bitCountAndMask -= 8;
}
} while ((int)decodedSymbol < 0x40);
for (; (int)decodedSymbol < 0x40; decodedSymbol++) {
coefficientOutput[decodedSymbol] = 0;
}
request->bytesConsumed = bytesConsumed;
decodeResult = 0;
request->bitstream = sourceCursor;
*request->bitCount = bitCountAndMask;
}
if (length > maxLength) {
return ODH_ERROR_INVALID_BITSTREAM;
}
if (category > 0) {
mask = (1 << category) - 1;
value = mask & (bitBuffer >> (32 - length - category));
if ((value & (1 << (category - 1))) == 0) {
value = (value + 1) | ~mask;
}
} else {
value = 0;
}
coefficientOutput[coefficient++] = value;
bitOffset += length + category;
while (bitOffset >= 8) {
sourceCursor++;
bytesConsumed++;
bitOffset -= 8;
}
} while (coefficient < 64);
for (; coefficient < 64; coefficient++) {
coefficientOutput[coefficient] = 0;
}
request->bytesConsumed = bytesConsumed;
request->bitstream = sourceCursor;
*request->bitCount = bitOffset;
return 0;
finishDecode:
return decodeResult;
}
void CArGBAOdh::idct_fast(const u8* rangeLimitTable, u32* coefficients, u32* quantizationTable, u8* destination, u32 stride) {
int evenPart0, evenPart1, evenPart2, evenPart3, oddPart3, oddPart2, oddPart1, oddPart0;
int butterflyTerm0, butterflyTerm1, butterflyTerm2, evenInnerSum;

View File

@@ -998,24 +998,12 @@ namespace ipl {
return ret;
}
static inline void verifySavedataZD(EGG::Heap* heap, ESTitleId requestedTitleId, NANDFileInfo* fileInfo) {
ESTitleId titleId;
u32 offset;
u32 j;
BOOL valid;
BOOL fileOpen;
u8* firstBlock;
u8* secondBlock;
BOOL deleteSaveData;
s32 ret;
u8* saveData;
titleId = requestedTitleId;
static inline void verifySavedataZD(EGG::Heap* heap, ESTitleId titleId, NANDFileInfo* fileInfo) {
char path[NAND_MAX_PATH];
saveData = NULL;
fileOpen = FALSE;
deleteSaveData = FALSE;
s32 ret;
u8* saveData = NULL;
BOOL fileOpen = FALSE;
BOOL deleteSaveData = FALSE;
sprintf(path, "/title/%08x/%08x/data/%s", (u32)((titleId & 0x00FFFFFFFFFFFFFFULL) >> 32), (u32)(titleId & 0x00FFFFFFFFFFFFFFULL), "zeldaTp.dat");
if (!ESMisc::ChangeUid(titleId)) {
@@ -1042,17 +1030,17 @@ namespace ipl {
OSReport("%s::%s: File size is not correct: %d\n", __FILE__, __FUNCTION__, ret);
deleteSaveData = TRUE;
} else {
offset = 8;
valid = FALSE;
j = 0;
u32 offset = 8;
u32 j = 0;
BOOL valid = FALSE;
while (j < 3) {
firstBlock = saveData + offset;
if (!checkForNullTermination((char*)firstBlock + 0x4e, 8) ||
!checkForNullTermination((char*)firstBlock + 0x58, 8) ||
!checkForNullTermination((char*)firstBlock + 0x72, 8) ||
!checkForNullTermination((char*)firstBlock + 0x8e, 8) ||
!checkForNullTermination((char*)firstBlock + 0x1b4, 0x11) ||
!checkForNullTermination((char*)firstBlock + 0x1c5, 0x11)) {
u8* block = saveData + offset;
if (!checkForNullTermination((char*)block + 0x4e, 8) ||
!checkForNullTermination((char*)block + 0x58, 8) ||
!checkForNullTermination((char*)block + 0x72, 8) ||
!checkForNullTermination((char*)block + 0x8e, 8) ||
!checkForNullTermination((char*)block + 0x1b4, 0x11) ||
!checkForNullTermination((char*)block + 0x1c5, 0x11)) {
goto verify_failed;
}
j++;
@@ -1062,13 +1050,13 @@ namespace ipl {
offset = 0x2008;
j = 0;
while (j < 3) {
secondBlock = saveData + offset;
if (!checkForNullTermination((char*)secondBlock + 0x4e, 8) ||
!checkForNullTermination((char*)secondBlock + 0x58, 8) ||
!checkForNullTermination((char*)secondBlock + 0x72, 8) ||
!checkForNullTermination((char*)secondBlock + 0x8e, 8) ||
!checkForNullTermination((char*)secondBlock + 0x1b4, 0x11) ||
!checkForNullTermination((char*)secondBlock + 0x1c5, 0x11)) {
u8* block = saveData + offset;
if (!checkForNullTermination((char*)block + 0x4e, 8) ||
!checkForNullTermination((char*)block + 0x58, 8) ||
!checkForNullTermination((char*)block + 0x72, 8) ||
!checkForNullTermination((char*)block + 0x8e, 8) ||
!checkForNullTermination((char*)block + 0x1b4, 0x11) ||
!checkForNullTermination((char*)block + 0x1c5, 0x11)) {
goto verify_failed;
}
j++;
@@ -1105,11 +1093,8 @@ namespace ipl {
}
static inline s32 DeleteTicketsForce(EGG::Heap* heap, ESTitleId titleId, u8* ticketViews, u32* ticketViewCount) {
ESTicketView* ticketViewList = NULL;
s32 ret;
u32 j;
ESTicketView* ticketViewList;
ticketViewList = NULL;
memset(ticketViews, 0, OSRoundUp32B(sizeof(ESTicketView)));
ret = ES_GetTicketViews(titleId, NULL, ticketViewCount);
if (ret != ES_ERR_OK) {
@@ -1125,7 +1110,7 @@ namespace ipl {
OSReport("%s::%s: ES_GetTicketViews failed: %d for %016llx\n", __FILE__, __FUNCTION__, ret, titleId);
goto cleanup;
}
for (j = 0; j < *ticketViewCount; j++) {
for (u32 j = 0; j < *ticketViewCount; j++) {
memcpy(ticketViews, &ticketViewList[j], sizeof(ESTicketView));
ret = ES_DeleteTicket((ESTicketView*)ticketViews);
if (ret != ES_ERR_OK) {
@@ -1141,16 +1126,12 @@ namespace ipl {
}
static inline s32 InitSavedata(EGG::Heap* heap) {
u32 i;
s32 ret;
ESTitleId* titleIds;
u8* ticketScratch;
u8 ticketViews[OSRoundUp32B(sizeof(ESTicketView))] ALIGN32;
NANDFileInfo fileInfo ALIGN32;
u32 ticketViewCount;
titleIds = NULL;
ESTitleId* titleIds = NULL;
u32 titleCount = 0;
ret = ES_ListTitlesOnCard(NULL, &titleCount);
s32 ret = ES_ListTitlesOnCard(NULL, &titleCount);
if (ret != ES_ERR_OK) {
OSReport("%s::%s: Failed to ES_ListTitlesOnCard1: %d\n", __FILE__, __FUNCTION__, ret);
@@ -1170,8 +1151,8 @@ namespace ipl {
}
{
ticketScratch = ticketViews;
for (i = 0; i < titleCount; i++) {
u8* ticketScratch = ticketViews;
for (u32 i = 0; i < titleCount; i++) {
if ((titleIds[i] & 0xFFFFFFFFFFFFFF00ULL) == 0x00010000525A4400ULL) {
verifySavedataZD(heap, titleIds[i], &fileInfo);
continue;
@@ -1196,6 +1177,10 @@ namespace ipl {
return ret;
}
s32 ESMisc::DeleteUnauthorizedData(EGG::Heap* heap) {
return InitSavedata(heap);
}
BOOL checkForNullTermination(char* str, u32 len) {
for (u32 i = 0; i < len; i++) {
if (*str == 0) {
@@ -1206,10 +1191,6 @@ namespace ipl {
return FALSE;
}
s32 ESMisc::DeleteUnauthorizedData(EGG::Heap* heap) {
return InitSavedata(heap);
}
TMDFile::TMDFile(EGG::Heap* heap) : mpHeap(heap), mbFileOpen(FALSE), mFileLength(0) {
memset(&mFile, 0, sizeof(mFile));
}

View File

@@ -9,7 +9,7 @@ from pathlib import Path
EXPECTED_DOL_SHA1 = "26116613f624061ba99c8d1a299aaa6efa85670d"
EXPECTED_TOTAL_UNITS = 1028
EXPECTED_TOTAL_UNITS = 1027
EXPECTED_TOTAL_CODE = 2995176
EXPECTED_TOTAL_DATA = 1832684
EXPECTED_TOTAL_FUNCTIONS = 12563

View File

@@ -1,58 +0,0 @@
# CHANSVm converter input types
Base: `20cf9f9f25b13b8cd6910e07cc5eb71558845d4e`, target 43U only.
## Change and source review
`CHANSVmConvertToFloatFromStr` took a pointer-to-const source header while
`VmConvertFunc` specified a mutable source header. The conversion table cast
hid that incompatible function-pointer type at the indirect call.
Give all 11 converters and the callback typedef the same pointer-to-const
source-header type, and remove the callback cast. All converters either read
source values, ignore the source, or pass it through the read-only array-join
path. They write only newly allocated result objects. Propagate the input type
through `VmArrayJoinCommon`, `VmArrayJoinEstimateStrSize`, `VmArrayJoinSub`, and
`VmArraySeekTop`, including the forward declaration. These helpers only read
the source header; the join routines write the destination string and local
state. `VmArraySeekTop` still returns a mutable chunk pointer because header
constness is shallow and other callers can mutate array elements. No cast is
needed at the array-join boundary.
The public `CHANSVmConvertObjectType` input remains mutable: its same-type fast
path returns the original mutable object. Passing it to a const-source
converter is valid. No executable expressions, flags, data or layout changed.
## Fresh leaf verification
Configured using the restored `wii-source-tools/build-43U.sh` tool paths and
flags, with commands run in the isolated leaf instead of that script's fixed
main directory. Baseline object was freshly compiled before editing.
- Entire CHANSVm object is byte-identical to that baseline, SHA256
`11fa48261cd93668d133d5ef73efbf3c9109181730b21409153b78316189e063`.
All 233 sibling function spans, allocated sections and relocations unchanged.
- All 15 emitted converter/dispatch/join functions: exact-name objdiff 100.0,
raw target function bytes and normalized relocation targets identical
(86 code relocations). VmArraySeekTop is inlined.
- All target data sections match including alignment padding: `.rodata` 1432,
`.data` 4672, `.sdata2` 184, `.sdata` 600, `.sbss` 16 bytes;
all 614 data relocations match by resolved section/function target.
- Pool: 125/125 strings identical. Dispatch ctxdiff: 47/47 instructions, 0 diffs.
FloatFromStr: 83/83 instructions, one textual symbol-alias difference
(`VmNaN` versus `lbl_81694F08`); raw bytes and resolved relocation target are
identical. This is not represented as a literal ctxdiff-zero result.
- Fresh full 43U build, report and `build/43U/ok` pass. DOL SHA1:
`26116613f624061ba99c8d1a299aaa6efa85670d`.
- All 1028 unit measures/functions/sections and overall report measures are
unchanged against the saved base report. All 22 workflow guards pass with
no skips. `git diff --check` passes.
This is a binary-neutral type correction, not a new matching/linking gain.
CHANSVm remains 229/233 exact, 45284/53564 exact code bytes, 6904/6904 matching
data bytes, and unlinked. The completion assertion still fails on the existing
project-wide incomplete code/link totals; no full-completion claim is made.
Local evidence: `../vm-converter-const-evidence/` contains baseline/candidate
build logs, original baseline object/report, verification script/results,
full-build/report/ok logs, pool and ctxdiff results, guards and completion logs.

View File

@@ -1,14 +0,0 @@
## scanAP (w1010 revisit) — inlined-bool materialization wall
Orig inlines `Animator::isPlaying()` (`mState == 1` at +0x14) 3x but always as a
MATERIALIZED bool: `lwz rX,0x14; addi r0,rX,-1; cntlzw r0,r0; rlwinm. r0,r0,27,5,31; bne`.
Ours fuses to `lwz r0,0x14; cmpwi r0,1; beq` — 6 insns shorter overall (272 vs 266).
Tried and rejected (MWCC normalizes/folds all of them):
- `isPlaying() == false` at the call site
- `bool playing = anim->isPlaying(); if (!playing)` named local (fuses; eggColorFader's
fadeOut materializes only because `success` is also RETURNED — a second value-use)
- `int isPlaying()` return type — still fuses
- `return !(mState != ANIM_STATE_PLAY)` in the header — still fuses
Conclusion: orig's bool crosses a real value-boundary (2nd use, or a different inlined
shape we haven't identified). Same family as the fused-compare fossil in CHANSVm.
Also tried: convertRevIP untouched (98.7, 292B).

View File

@@ -1,75 +0,0 @@
# o2-aes-idct attempts
Worktree data-d11, branch agent/w1009/o2-aes-idct (from origin/main 20cf9f9f). 43U only.
## Unit-level checks
- Compiler sweep (all GC and Wii compilers; `-ipa file` dropped for GC < 3.0): aes GC/3.0a3 .. 3.0a5.2
identical (7/9), older or Wii compilers worse. idct_block_var GC/3.0a3 .. 3.0a5.2 identical (0/2).
Version is not the lever for either unit.
- combosweep (single + pairwise pragmas): aes best 137 -> 135 (opt_propagation off), no lead.
## net/aes: AESiEncryptBlock 137 -> 0, AESiDecryptBlock 215 -> 0 (unit Matching, DOL OK)
Tooling: `tree.py` symbolically executes a function and compares the expression tree of every
store against the target, independent of registers and scheduling. That separated "wrong
dataflow" from "wrong allocation", which earlier rounds had mixed together.
Findings, in order:
1. The target round is plain rijndael-fst order `hi ^ m16 ^ m8 ^ lo`, then `^ key`. The target
tree is `(lo ^ (m8 ^ (hi ^ m16))) ^ key`. At -O3/-O4 MWCC rebalances any 4-leaf XOR chain
(tree height reduction): every one of the 120 shapes tried compiled to `(x^y)^(z^w)`. At
optimization_level 2 it is not rebalanced, but level 2 cannot unroll the decrypt key loop,
which the target does (mtctr 2), so the unit is O4.
2. With the rotate written as the `__rlwinm(x, n, 0, 31)` intrinsic instead of the shift/or
macro, O4 leaves the chain alone (intrinsic calls are not reassociated), and the natural
expression gives exactly the target tree. It also removes the CSE temporaries the shift/or
macro created for the table loads (x used twice), which is what had kept the allocation off.
3. Final round: encrypt `(hi<<24 | m16<<16 | m8<<8 | lo) ^ key[i]`; decrypt is XOR-based with the
key first, `key[i] ^ hi<<24 ^ m16<<16 ^ m8<<8 ^ lo` (O4 rebalances it the target way).
4. Encrypt init: `state = input[i]; ... state ^= key[i]` with `key = context->keys` walked by
`key += 4` (single-expression init put keys[i] in the state register; 9 diffs).
5. Decrypt: `key = context->keys; key += rounds * 4;` (the one-expression form folds +16 into
the loads). InvMixColumn as `static inline void AESiInvMixColumn(u32* word)` (pointer
parameter) fixes the last r7/r8 swap between value and timesTwo; value-parameter helpers and
all local declaration orders left 26+ diffs.
Rejected along the way: optimization_level 2 pragma (correct tree, wrong key loop), int/long
casts between XOR stages (blocks rebalancing but unnatural).
`include/global/decomp/ide.h`: declared `__rlwinm` for non-MWCC tooling (guarded by
`#ifndef __MWERKS__`, no build effect).
## buffer/idct_block_var: Lumi and Col (in progress)
Dataflow first (path-based symbolic execution of both objects, `ptree.py`):
1. Even part: the target computes `rot + (c6 + c2)` into a fresh variable. `x = rot + x` is
rewritten by MWCC to `x += rot` (operand order `sum + rot`), and a single-use `evenSum`
gets forward-substituted and reassociated (`c2 + (rot + c6)`). Fix: `evenSum = c6 + c2;
c2 = evenRotation * 0xB5 >> 8; evenRotationSum = c2 + evenSum;` (the c2 reassignment
blocks the substitution). Same in both passes of both functions.
2. AC test: the target ORs leaf-first (`c2 | acc`). `acc |= c` or `acc = c | acc` with a u32/s32
accumulator is canonicalised to acc-first, a single 7-way expression is rebalanced at O4.
An `int` accumulator over `s32` coefficients (`acBits = c2 | acBits;`) keeps leaf-first
(the long->int conversion stops the `|=` rewrite).
3. Level 2 or 1 cannot be it: no CTR row loop at level 2 (274 vs 257 insns).
With 1-2, all store/call trees of Lumi (3 paths) and Col (4 paths) equal the target and the
frame sizes match. Remaining differences are allocation and scheduling only.
Allocation findings (mwdbg + regsim, `wantmap.py` maps candidate vregs to target registers by
symbolic value):
- Named locals are numbered per block in reverse declaration order, blocks top-down (function
scope first), forward-substituted locals take no number; split webs and inline locals become
`@` temps numbered after all named locals.
- Column setup now matches exactly: `pitch4/7/6/5/3/2` as named locals assigned before the
loop, a separate column cursor (`src`, not a split web of the row cursor), and
`for (column = 7; column >= 0; column--)` (CTR trip count becomes a temp colored first).
- Declaration-order search inside blocks on the captured graph tops out at 113/153 target
registers, and a greedy order-feasibility check stalls on callee-saved claim order, so the
column AC block still has a different pre-RA schedule (live ranges).
- objdiff fuzzy is the gate metric and disagrees with positional diff counts; searches now
score candidates with objdiff itself (`odfuzzy.py`, one-unit objdiff project per slot).

View File

@@ -1,84 +0,0 @@
# o2-aoss attempts (2026-10-09)
Worktree data-d1, branch agent/w1009/o2-aoss at origin/main 20cf9f9f.
Scratch compiles in /tmp/o2-aoss (same flags as ninja, ~0.2 s per unit).
## Findings that apply to both AOSSLink functions
- IRO is skipped for AOSSi_WLANGetBSSList and AOSSi_WLANConnect. Enabling
MWCC's own IRO dump (flag byte 0x725e5c, log opened by 0x5ed500 in
GC/3.0a5.2) shows both stop after IRO_BuildflowGraph. The cause is the
check at 0x5bd060/0x5bd150: any EOBJREF to an object whose qualifiers carry
alignment bits (0x1f000000) disables IRO for the whole function. Here that
is `WD_Info info ATTRIBUTE_ALIGN(32)` (and `scan`). Removing the attribute
makes IRO run, but it also drops the 32-byte frame alignment the target
has. Type-level `ATTRIBUTE_ALIGN(32)` on the WD structs is ignored by this
compiler (sizeof/alignof unchanged, no aligned frame), so the target also
ran without IRO. Source shape maps almost 1:1 to PCode in these functions.
- Ported MWCC's pre-RA list scheduler and the 750 machine model to Python
(/tmp/o2-aoss/sched.py). It reproduces our B1/B14 of WLANConnect, the
target B1, and our B19 of GetBSSList exactly. Facts it needed: stores to
the same local at different offsets are independent; a store cannot issue
while another store sits in LSU stage 2; ties go count -> height -> opcode
rank (MR 0 < STH 1 < ADDI 2 < LHZ 3 < LI 4) -> program order.
- With mwdbg extended with dump points before/after pre-RA scheduling and
after each COptimizer level-4 pass (private copy, /tmp/o2-aoss/mwdbg2):
the scheduler input for both blocks equals our final code minus nothing.
Both target orders need one extra instruction in the block at scheduling
time that is gone later (RA coalescing or post-schedule cleanup).
## AOSSi_WLANGetBSSList: 25 -> 3
regsim with the parameter pinned (/tmp/o2-aoss/ordanneal.py) found 1500
declaration orders reaching all 11 target registers. Common constraints:
index < driver < buffer < descriptor < count < cleanupRetries < unlockRetries
and result < startupRetries < scanRetries. Declared C89-style at the top in
that order (block-scoped declarations moved up): 25 -> 3, pool identical.
Remaining 3: block after `memset(buffer, 0, 0x3200)`, target issues
`sth channelBit` before `li r5, 6` (so the lhz temp can be r5). Simulator:
any one extra instruction in that block at scheduling time gives the target
(dead VN copy, extra addi, ...). Tried, all still 3: `&scan.bssid`, scan
pointer local, inline scan-param initializers (2 shapes), inline memset
wrappers (void and returning), statement order permutations, unpacked WD
structs (header override).
## AOSSi_WLANConnect: 2 (unchanged)
Second memset: target `li r4; li r5; mr r3, r27`, ours `li r4; mr r3; li r5`.
Simulator: only an extra instruction on the address chain
(lis -> addi -> X -> mr r3, X later coalesced) reproduces the target; no
reordering of the block's inputs does, and a dead side copy does not.
Explicit copies through a second local (i6, n3), inline helpers with a
param or a cast local (m0/m1 x void/int x global/var), getter inline,
NULL-initialised pointer, extern/global/static/struct-wrapped configs
(struct gives `addi r27, r3, 0x160`: right order but one extra insn),
array decay, casts: all removed by the COptimizer "pre" phase (peephole 0 +
DCE) before scheduling, or by VN. 2 unchanged.
## AOSSi_WLANGetBSSList: 3 -> 0 (EXACT)
The missing instruction is a copy that lives until pre-RA scheduling and is
coalesced by the allocator afterwards. A copy into a named local survives the
COptimizer when its uses are in other blocks (the block-local peephole cannot
rewrite them). A typed view of the scan buffer does exactly that:
`void* buffer` for alloc/memset/free, `u8* scanBuffer = (u8*)buffer;` right
after the memset, used by WD_Scan, the BSS count and the first descriptor.
The copy sits in the scan-parameter block at scheduling time, so `sth` of
channelBit issues before `li r5, 6` (target), then r24 holds both names.
Variants that did not work: alias for the count pointer only (3), alias
assigned before the memset (3).
## AOSSi_WLANConnect: more evidence (still 2)
- Pass tracing (dump after every COptimizer level-4 call): the in-block copy
chain `addi vB; mr vC, vB; mr r3, vC` is collapsed by 0x596850 (block-local
copy forwarding + DCE, pre phase); copies created later by value numbering
(0x5976e0) get their uses canonicalised to the first holder. So a chain
copy in the memset block cannot come from a plain second local.
- Simulator searches: no input order, no 1-2 dead extra instructions
(return copy, li, mr, addi, lis), no 1-2 side copies reproduce the target.
Only (a) a copy on the address chain or (b) r4 and r5 both coming from
register copies at scheduling time do.
- Pragma sweep (15 single + all pairs, unit-wide, diagnostic): best is
baseline 2; `peephole off` 11, `scheduling off` 50.

View File

@@ -1,105 +0,0 @@
# o2-aterm attempts (ATERM, 2026-10-09)
Start (a6e74ad2): ATERM 22/26 exact; open: DiscoverAccessPoints 7, BuildEncryptedMessage 2,
BuildAssociationRequest 28, RunConfigProtocol 294.
End (2882435b): 25/26 exact; BuildEncryptedMessage 2 (scheduler tie-break, below). ATERM stays
NonMatching.
## Prior art: the DS build of the same library
The DS DWC library ships the same NEC "AtermStation" code with its real static names
(CacaBueno64/ie3ogres `lib/TwlDWC_dl/asm/util/atermset.s`, read-only). Name map:
ScanAP = DiscoverAccessPoints, CheckAccessPoint = FindChangedApRecord, GetMacEncKey =
BuildAssociationRequest, GetWLanSetElement = ParseAssociationResponse, AsciiToHex = ParseHexBytes,
StoreNetParam = ApplyScanSecuritySettings, AutoConfigThreadEx = RunConfigProtocol,
keywrap_encrypt/decrypt = AesKeyWrap/Unwrap, rijndael* = Aes*, MY_MD5Update = Md5Update,
PutHex/PutMac = the hex and MAC formatters (non-inlined on DS, so their bodies are visible).
## MAC formatter (DiscoverAccessPoints 7 -> 0, BuildAssociationRequest 28 -> 0)
Cause: the register swap was input pointer r9 vs r5 and low nibble r5 vs r9. With the
`nibbles[2]` array helper both nibbles are codegen temps, which are numbered above every inline
variable and therefore colored first, so the low nibble always took r5 (array element types,
declaration orders, 400 sampled formatter shapes, pragmas and compiler versions: no change).
The DS PutHex keeps one nibble variable and rotates it: `h = (c & 0xF0) >> 4; for (2) { emit h;
h = c & 0xF; }`. On MWCC the loop-invariant `c & 0xF` becomes an IR temp numbered below the
inline locals, so it is colored last (r9), and PutMac's `*mac++` parameter takes r5. Both
functions exact; ParseAssociationResponse (GetWLanSetElement calls PutHex on DS) stays exact with
the same helper (`key += atermFormatHexByte(key, *optionValue++)`), so the separate straight-line
atermEncodeHexByte is gone.
## Readability: scan buffer header
`(u16*)scanBuffer + 1` replaced by `((AtermScanBuffer*)scanBuffer)->descriptorWords`
(count, then the descriptor word stream): 0 diffs. Typing the scanBuffer local itself as
AtermScanBuffer* changes the alignment arithmetic (98 diffs, size 0x418).
## RunConfigProtocol (294 -> 2) = DS AutoConfigThreadEx
Rebuilt from the DS layout instead of the hand-inlined body: GetTickCount, Sleep (alarm), SendNotify,
SendFrame -> SendBroadcast -> SendFrameViaInterface, GetFrameData/GetCommandElement,
GetElementData/GetFirstElement, SetElementData/SetSingleElement/SetSearchRes, RFC 1321 MD5
Init/Encode/Final/memset as static inlines, globals used directly (no request/packet/response/session
pointer locals). Findings, each measured:
- .bss order follows the first reference in the function IR. Passing a cast global address
(`(u8*)&gAtermDecodedResponse`, `(u16*)buf`) into a static inline hoists it to the function entry
and moves it first. The element buffer is a plain `u8[0x800]` in the original (like FrameData), so
it is now one, with an AtermElementHeader view; that keeps the target order without pointer locals.
- Inline helper uses of a global address get a hoisted register (r25/r31/r15) while direct call
arguments rematerialize `addi rN, base, off`. This is plain MWCC behaviour, matching the target.
- MD5: the exact RFC 1321 Encode/MD5_memset text (`unsigned int` lengths, `unsigned char` masks)
keeps IRO from unrolling the Encode loops, so the PCode unroller produces the target's
load/store order (u32 types: 35 diffs; RFC types: 0).
- SetElementData must advance its own cursor parameter (`cursor += recordSize; return cursor;`)
for the r16/r17 alternation; the value pointer as `cursor + sizeof(AtermOptionHeader)`.
- GetFrameData returns `frame + sizeof(AtermFrameHeader)` (not `packet->payload`), declares
`end` before `cursor` (inline locals number in reverse order); SetSingleElement writes through a
header pointer local.
Remaining 2 at 23addcb1: SetSearchRes' second element folds its value pointer to the first
element's base (`addi r3, r16, 0xc`, target `addi r3, r17, 4`).
## RunConfigProtocol (2 -> 0): the DS SetElementData body with an int pad size
Found with IRO dumps. The compiler prints them once two dump flags are set: gdb breaks at
0x5ed507 (log open) and writes 0x725e5c, then toggles 0x725e5c/0x70f24d per function at
0x577716. That is o2-keyboard's /tmp/o2-keyboard/irodump1_gdb.py; the log is `<source>.log`. A
copy that keeps its temporary source in this worktree is /tmp/o2-aterm/irod/run.sh. It drops
the AES tables and the bodies after RunConfigProtocol, which leaves the function's code identical
and takes about a minute.
- Elements 1 and 2 share one IRO block. Block-local expression propagation chains element 2's
cursor copies back to element 1's cursor temp, so element 2's `cursor + 4` reads element 1's
temp. IRO_PropagateSelfAssignments (inc/dec propagation, 0x5f2150) then folds element 1's
`+= 8` into it, giving base1 + 0xc. Elements 5 and 4 sit in their own blocks: global copy
propagation reaches them one step at a time, so they fold onto the previous element's base,
which is what the target does.
- Inc/dec propagation is all-or-nothing per `+=` def. Every reached use must have that def as its
only reaching definition. More than one use needs the helper at 0x5f24e0, which builds
`var op const` and asks a backend predicate (0x56ac90).
- The DS SetElementData does `p += sizeof(header); memset(p, 0, pad); memcpy(p, data, len);
return p + pad`. A mid-body `+= 4` kills the copy before element 2's value uses. With
`cursor += paddedLength; return cursor;` and an `int` (or unsigned int, u16, short) pad size, the
first PropagateSelfAssignments round leaves those incs alone. Element 1's `+= 8` therefore
reaches element 2's cursor copy (`@c2 = @c1 + 8`, no longer a copy) before any copy
propagation reaches the value uses, and they stay `base2 + 4`. With `s32`/`u32` (long) pad
sizes, the first round merges the `+= 4`. Second-pass copy propagation then rewrites the
value uses to element 1's temp, and the fold comes back (2 diffs). A mini repro with `int`
typedefs behaves like the `int` case, which is how the type dependence showed up. Measured
variants: E4 (`+= pad; return cursor`) int/unsigned/u16/short: 0. E4 s32/u32: 2. E1 any type: 2.
E3 (`return cursor + pad`) any type: 661.
- Bisecting the full function (other switch cases, the loop condition, atermSleep, the
epilogue) changed nothing. Only the helper text matters.
## BuildEncryptedMessage (2, unchanged): entry-block scheduler order
Target `mr r27,r5; mr r30,r3; mr r26,r4; mr r28,r6; mr r3,r27; mr r29,r7`; ours puts
`mr r29,r7` before `mr r3,r27`. The mwdbg capture shows the entry block is list-scheduled before
register allocation, with the program order r3..r7 parameter moves, `li checksum`, `mr r3,payload`,
`li r4`, `li r5`, `bl memset`. The 750 model gives the memset call latency 0, and the GPR
anti-dependency edges have latency 0. The call's operand list also clobbers r6 and r7. So the r6
copy and the r7 copy have identical dependencies, unlocked-successor counts, heights,
criticality and rank. Program order then always places both before `mr r3,payload`, but the
target puts r6 before it and r7 after. Not reachable by:
- K&R parameter declaration orders
- every `#pragma scheduling` model (740/750/7400/altivec/on/reset: 2; others: 12-40)
- key copies, extra param copies and inline wrappers (the earlier session)
Recorded as a scheduler tie-break.

View File

@@ -1,112 +0,0 @@
# o2-bs2mach attempts (BS2Mach: CheckBS2CommandStatus, BS2Tick)
Worktree data-d7, branch agent/w1009/o2-bs2mach, base 20cf9f9f (origin/main).
Start: 27/29 exact, CheckBS2CommandStatus 2/406, BS2Tick 57/1940, data 158528/158528, pool 91/91.
## CheckBS2CommandStatus (lever 35)
Target case 0x12 issues `lwz count; stw CacheCommandComplete; slwi`: the completion
store fills the load-latency slot, so it has no edge to the partition-count load
through `DataToc`. A file-scope static may alias that pointer load, a
function-local static whose address is never taken may not.
1. `static u32 CacheCommandComplete = 0;` inside CheckBS2CommandStatus (it is the
only user), completion stored before the length update as in every other case:
CheckBS2CommandStatus 0/406. Every other function unchanged, pool identical.
The static lands at the end of .sbss (after LoaderInit) instead of 0x50.
2. Compiler probe (same flags): initialized objects and function statics are
emitted in parse order, tentative definitions after them in reverse definition
order (`I1 I2 L$4 I3 T4 T3 T2 T1`).
3. AudioBufferUnconfigured..LoaderInit made tentative (initializers dropped) and
listed in reverse: .sbss order and offsets identical to the target, 28/29
exact, data 158528/158528. Target symbol renamed `CacheCommandComplete$1964`
in config/43U/symbols.txt (project convention for function statics).
## BS2Tick (57 at start)
4. Same lever in case 0: the target schedules `li 1` first and keeps the
`AudioBufferUnconfigured = 1` store free of the absolute `*(u32 *)0x800030d4`
store (unknown storage aliases every file-scope object, not a function static).
AudioBufferUnconfigured, ResetTime and SpinupDeadline are only used by BS2Tick
and sit right after CacheCommandComplete in .sbss. All three as BS2Tick
statics: 57 -> 52; only AudioBufferUnconfigured as a static gives the same 52,
so ResetTime/SpinupDeadline stay file-scope tentatives. Symbol renamed
`AudioBufferUnconfigured$2066`. .sbss order identical.
5. Store-before-load pairs the target keeps and we hoist (case 0x30
`PartitionOpen = 0; if (RegionValid == 0)`, case 0x34/0x35
`LoadingTitle = 0; switch (Block.state)`, case 0x40 `AbortFlag = 0;
if (RestartRequested == 0)` and `RestartRequested = 0; if (FatalErrorFlag)`).
Compiler probe with the unit's flags (/tmp/o2-bs2mach/probe/t2.c, t3.c): a
store to one global followed by a load of another keeps its order only when
BOTH are volatile; non-volatile/volatile, volatile/non-volatile, extern and
address-taken globals are all reordered. So the target proves PartitionOpen,
LoadingTitle, AbortFlag, RestartRequested and FatalErrorFlag volatile
(RegionValid and DVDCommandBlock.state already are). AbortFlag is also read in
BS2DVDCallback (interrupt context); RestartRequested/AbortFlag writers disable
interrupts. One-at-a-time sweeps could not see the case-0x40 chain because it
needs all three together. All five: 52 -> 42, other 28 functions unchanged.
6. Device-code block (case 5): the initial PCode has a separate `lis 0x8000` per
branch and backend value numbering merges them into the consoleType base. Per
the MWCC decomp (ValueNumbering.c), `li`/`lis` are only value-numbered when the
destination is a temporary inside the coalesce window; named locals never are.
Reading consoleType through a named `OSBootInfo *bootInfo` and sharing the
`State = BS2_STT_8` tail: 42 -> 28, block exact.
7. Case 0: `DvdProgress = (u32 *)0x800030d4; ... *DvdProgress = 0;` (as case 2
writes it) and testing `BS2NoDisk` directly: 28 -> 24 -> 12 together with 8.
8. CoverOpenTimeHigh/Low are one 8-aligned big-endian OSTime: a single
`OSTime CoverOpenTime` keeps CheckDVDCommandStatus exact (u64 store is low word
first, as in the target) and makes the case-0x42 zero high word a later temp,
fixing that whole register cluster (24 -> 14 at the time).
9. Banner check: the target loads bannerFile.length straight into r6 because it is
the 4th OSPanic argument; the format string has `(0x%08x)` and our call had no
argument. Passing bannerFile.length fixes the cluster.
10. RequiredIosHigh/Low are likewise one 8-aligned u64 (BS2StartGame reads it as a
title ID with the `== 0 -> 1:3` default). `u64 RequiredIos` gives the target
pair coloring (hi r0, lo r3, TMD r4) and keeps BS2StartGame exact.
symbols.txt: CoverOpenTime and RequiredIos as size-8 objects (only BS2Mach
referenced the halves; every relocation resolves to the same address).
BS2Tick 4/1940 left: case 0 `CoverBlock.state = 0` is ordered before the
volatile BS2NoDisk load (target: after).
### Volatile flags: per-flag evidence (current source, BS2Tick 4 diffs)
Target pairs a store to one global with a later load of another and keeps that
order; MWCC only does so when both are volatile (probe t2/t3: non-volatile,
one-sided, extern and address-taken pairs are all reordered).
- 0x3b04 case 0x30: `stw PartitionOpen; lwz RegionValid` (RegionValid volatile).
- 0x3d68 case 0x34/0x35: `stw LoadingTitle; lwz Block.state` (state volatile).
- 0x40a0 case 0x40: `stw AbortFlag; lwz RestartRequested`, then
`stw RestartRequested; lwz FatalErrorFlag`.
Dropping any single flag: PartitionOpen 4->7, LoadingTitle 4->6, AbortFlag 4->7,
RestartRequested 4->9, FatalErrorFlag 4->6; no other function changes.
### Last 4 diffs: case 0 `CoverBlock.state = 0` vs the BS2NoDisk test
Target: `lwz r0,BS2NoDisk; stw r4,AUC; cmpwi r0,0; stw r27,0xc(r3); beq`.
Ours: the CoverBlock store precedes the load. Everything else in the block,
including every register, already matches.
- BS2NoDisk, DvdTransferred and DvdTransferLength are volatile (non-volatile
BS2NoDisk hoists the load above both DvdTransfer stores; non-volatile
DvdTransferred breaks BS2DVDCallback's order against DvdReadPending).
- DVDCommandBlock.state reads are volatile in the target (BS2StartGame and
BS2StartGCGame poll it with a re-read every iteration; case 0x34 above). With
`state` non-volatile case 0 becomes exact but those break.
- So the source reads BS2NoDisk before the store. Holding it in any variable
(named, block-scoped, inline parameter/local, any same-width type) makes it a
named/`@` local, numbered below statement temps and colored after the constant
1: registers rotate (1 r0, BS2NoDisk r4, &PP r4, &0x800030d4 r5), 10 diffs.
mwdbg capture o2-bs2mach-st + regsim what-if: coloring that holder first gives
exactly the target (only those 4 nodes change). Narrow holders (u8/s8/u16/s16)
force a statement temp and get everything right except `clrlwi.` vs `cmpwi`
(1 diff). A 64-bit round trip is folded away.
- Diagnostic only, both exact 29/29, both forbidden, not committed:
`if ((BS2NoDisk | (CoverBlock.state = 0)) != 0)` (read then store in one
expression) and `*(s32 *)&CoverBlock.state = 0;` (non-volatile store).
No natural spelling found: hoisting a common leading store out of all three
branches doesn't happen (size grows); statement order grid (84 builds),
inline helpers, casts and holder types all stay at 4-10.
- Pragma sweep (combosweep, single + pairwise): BS2Tick 4 -> 4.
### Tooling note
`#pragma push / ppc_iro_level 0 / pop` tightly around BS2Tick (the last function
in the file) leaves it byte-identical, which earlier rounds read as "IRO does not
run on BS2Tick". A file-level `#pragma ppc_iro_level 0` changes BS2Tick in 1910
instructions, so IRO does run; only the scoped placement is not honored for it.

View File

@@ -1,110 +0,0 @@
# o2-cardseq-sdmem attempts
Branch `agent/w1009/o2-cardseq-sdmem` from `20cf9f9f`.
## iplSDMemory: SDMemory::drawTransferTitles (50 -> 0), unit linked
Start: 50/451 differing, register-only. Earlier Opus run (data-d9 `9b634499`) had brought it
363 -> 50 with the MSL `wcsstr` overload and `TextBox::SetTextColor`.
### Diagnosis with mwdbg + regsim
Target vs ours, GPRs only:
- alpha r31 / string-pool base r30 / bodyPane, titleSizePane r29; ours r29 / r31 / r30.
- line loop: lineCount r22, totalLines r23, `L"\n"` r24, messageLine r26, messageText r27,
lineIndex r28; ours r19 / r19 / r23 / r20 / r26 / r24.
The capture shows vreg numbering = `this`, named locals (reverse declaration order), frontend
temps (reverse creation order), then codegen vregs (string base r70 first). Coloring is reverse
simplify order and picks the lowest free register, requesting saved registers from r31 down.
Replaying the capture with relabelled vregs (`/tmp` wrapper around `regsim.simulate/color`)
reproduced the whole target when:
1. alpha lives in a codegen vreg created after the string base (any number 71..150),
2. totalLines sits between the third wcsstr's `s2` temp (v62) and lineEnd (v106/107),
3. row and visibleRows are numbered below every line-loop local,
4. messageText is numbered above lineIndex.
### Source changes that produce it
1. `nw4r::lyt::Pane::GetAlpha()` is `const` in real NW4R. With the const member the inline's
result is a codegen value, not a frontend temp, and alpha moves above the string base.
(An explicit `static_cast<u8>` around the call did the same; the const accessor is the real
declaration, so that is what landed.) 50 -> 20.
2. `visibleRows` / `row` declared in the title loop body (`s32 visibleRows = ...; for (s32 row = 0; ...)`). 20 -> 18.
3. `messageText` declared before `lineIndex`. With 2: 13.
4. No `totalLines` local: `for (lineIndex = 0; lineIndex < lineCount + 1; ++lineIndex)`.
With 1-3: 0 differing.
Types of alpha tried first (u32, s32, int, u16): no change; s8/char: worse. A named
`memoPane` local: no change.
### Linking the unit (Matching flip)
Flipping the unit failed to link: the source called six SDChannelSelect members through
`extern "C" iplSDChannelSelect_813D....` placeholders. A temporary link with the existing
mangled names linked but changed the DOL: one weak function survived dedup,
`SDMemory::TitleRange::operator=`, because SDChannelTitle hand-wrote the same compiler-generated
function as `extern "C" iplSDChannelTitle_copyTitleRange`. Fixes (all byte-identical where noted):
- SDChannelTitle: `sdRange = scene->mTitleRange;` / `nandRange = sdRange = scene->mTitleRange;`
instead of the hand-written copy; symbols.txt names 0x813E6FA0
`__as__Q43ipl5scene8SDMemory10TitleRangeFRCQ43ipl5scene8SDMemory10TitleRange` (scope:weak).
The compiler emits it at the same place. Unit stays 69/69.
- SDChannelSelect, real parameter types from the command dispatch and NandSDWorker:
`enqueueMoveNotice(ESTitleId)` (type 6 -> copy_nand_app_to_sd_async), `enqueueDeleteNotice(ESTitleId)`
(type 13), `enqueueErrorNotice(TitleIdList*, TitleIdList*)` (type 11 -> check_backup_fits_async),
`enqueueCommandNotice(TitleIdList* x3)` (type 12; the worker casts paramA-C to TitleIdList*),
collect* `titleNames` as `wchar_t (*)[21]`. Object bytes identical, only symbol names change
(symbols.txt updated for the nine functions). `friend class SDMemory;` for the private members.
- SDMemory: `TitleListState` was three `NandSDWorker::TitleIdList`s; it is now
`mTitleList / mNandTitleList / mSDTitleList`, and the calls are member calls. Still 66/66.
Full build: DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d with iplSDMemory Matching.
gate.py (SDMemory, SDChannelSelect, SDChannelTitle) --quick: 0 regressions, GATE PASS.
## iplCardSequence: loadCardFileIcons (213 -> 135, equal size)
Kept (all functions of the unit otherwise unchanged, pool identical):
- Format-3 palette left uninitialized (lever 10). Asm proof: in the target icon loop r6 is
paletteSize; its only writes are `li r6,0x400` (case 1), `li r6,0x800` (case 2) and `li r6,0`
(case 0). Case 3 branches (`cmpwi r4,3; bge`) straight to the iconOffset update that reads r6
(`add r22,r6,r22` / `add r21,r6,r21`) and `add r7,r7,r6`; no instruction writes r6 between
function entry and the loop. Case 0 sets paletteSize to 0 itself. 213 -> 387 (511 insns) with
the array form, -> 192 (512/512) with the existing `u8* iconPalette` pointer form.
- Image read as `static inline s32 readCardImages(...)`: the target's CARDRead failure is
`bge +8; b <check>` into the shared `if (result < 0)` test, the shape of an inlined early
`return` (a goto folds to `blt`, a top-level return branches to the epilogue).
- Comment read as `static inline s32 readCardComment(...)`: with only the image helper the two
sector-size slots swapped (0x8/0xC); as a second inline its `sectorSize` gets 0x8 again, and
its early `return 0` / final `return result` give the target's comment flow.
- Banner/icon setup + image read as `loadCardIconImages(...)`, and the block base/offset split
as `getCardBlockAddress(address, &offset)`: 231 -> 135, slot/fileNo/dir get r24/r25/r26.
Allocator analysis (mwdbg + regsim, a want-map derived by aligning backend-01/04 PCode with the
target): remaining diffs are register-only. Target colors iconAddressBase r31, then the four
CSE multipliers (fileNo*64 r30, slot*8128 r29, fileNo*4 r28, slot*508 r27), dir r26, fileNo r25,
slot r24, iconAddressOffset r23; comment base r23 / offset r21 / readSize r22 / result r29.
In the current capture iconAddressOffset sits in the last simplify scan (colored first, r31)
and iconAddressBase leaves one scan earlier; no numbering of the existing temps fixes both.
### loadCardFileIcons 135 -> 126
- NONE case as `u8* previous = &...iconFmt[iconCount - 1]; ...iconFmt[iconCount] = *previous;`:
gives the target's `add; lwz; addis; subi; add; lbz -1(p); stb 0(p)` shape (134). The array
form and `p[-1]` forms keep the -0x6fb4 in the displacement instead.
- Animation setup written in place with the icon loop's own `iconCount`/`shift`/`icon`, initialized
`shift, iconCount, hasTlut, iconImageSize` in that order, early exit by `goto animationDone`.
PCode value numbering reuses the first `li 0` of the block for the two zero stores; the target
reuses the animation shift (r3), which only happens when shift is the first zero in that block.
With the old helper the stores reused hasTlut. Anim region instruction order now matches.
- Block base as the common subexpression `iconAddress & 0xFFFFFE00` (IRO CSE temp, numbered just
above the CSE multipliers, as the simulator requires); offset `iconAddress - (iconAddress & ~0x1FF)`.
Base, params and the four multipliers now get the target registers (126).
Tooling: private mwdbg copy on gdb port 9137 (/tmp/o2-cardseq-sdmem-mwdbg, retrowin32 rebuilt with
the port patched) because the shared port queue timed out; IRO log via the known 2-byte patch of a
/tmp copy of GC/3.0a5.2 (diagnosis only). Remaining in the simulator: transferSize must be numbered
below the image offset, the comment base/offset/readSize above every other temp, result low.

View File

@@ -1,111 +0,0 @@
# o2-chansvm: CHANSVm round 2 (WinEmuWrite, BlobGetHexString, BlobPackCommon, Step)
Worktree data-d2, branch agent/w1009/o2-chansvm, base 20cf9f9f. Start: WinEmuWrite 5, BlobGetHexString 14,
BlobPackCommon 47, CHANSVmStep 262 (odiff differing instructions).
Scratch: /tmp/o2-chansvm (score.py = whole-unit compile + per-function diff; t/ = one-function harness
that reproduces the unit's codegen in under a second; tmw.sh = mwdbg on a harness file, ~8 s).
## VmWinEmuWrite: 5 -> 0 (exact)
Diff: strObj and totalLength swap r27/r29. mwdbg: every node is low-degree, so the color order is plain
descending vreg number. Named locals are numbered first (reverse declaration order), then IR temps and
inline locals (forward order), then codegen temps. The strObj value survived as the codegen temp of the
call result (`mr r40, r3; mr r37, r40` -> r37 propagated away), so it always had the highest number of
the loop values and took r29 first.
Copy-propagation probes on small functions (X1-X12 in t/x*.c): the backend replaces a named local by
the call-result temp unless the named local has a copy use (`mr rX, local`). Load-base and compare uses
do not block it; a copy use does (X8 vs X7). IRO removes plain `p = o` copies and inline parameters
before the backend sees them (X11, X12).
`strObj = CHANSVmGetArgString(vm, 0)` (the real exported helper, inlined) leaves the inline's return
temp (@1501, IR class) with a copy use, so that temp survives instead of the codegen temp. Moving the
loop into a static inline helper numbers its locals after that temp, which gives the target order.
| attempt | Win | others |
|---|---|---|
| strObj assigned twice (GetArg, then Convert), 3 declaration orders | 5 / 8 / 8 | - |
| for loop, guard clause, no `remaining`, if/else inLen, assign-in-if, nested if | 5 .. 54 | - |
| GetArgString only | 5 | - |
| loop in inline helper only (prior run) | 10 / 13 | - |
| GetArgString + inline helper, locals offset, totalLength, buf, outLen, inLen | 5 (outLen/inLen slots swapped) | - |
| GetArgString + inline helper, locals offset, totalLength, buf, inLen, outLen | 0 | no change, pool identical |
## VmBlobGetHexString: 14 -> 0 (exact)
Diff: loop registers. Target colors IV4 (byte offset +4) r4, the +2 counter r5, src r6, digit chain r7,
hexTbl r8; ours had the counter and the digit chain swapped. The digit chain is codegen temps, so the
counter and src must be numbered above it: both have to be strength-reduction IVs, created in the order
src, counter, IV4.
Per-pass PCode dumps (private copy of mwdbg with a breakpoint after every pass call in the -O4 driver at
0x5964c0, /tmp/o2-chansvm/mwdbgp) showed what each form does:
- pass 10 (0x62be80) is strength reduction; pass 14 (0x62e8d0) the CTR conversion.
- `src[byteIndex]` makes src an SR IV; `dest[byteIndex * 2]` gives IV4.
- A separate +1 counter for the low index (`lowDigitIndex = i * 2 + 1; i++`) gives the target coloring,
but SR rewrites i as `mr i, byteIndex`, which keeps byteIndex alive past the CTR conversion: two extra
instructions (n=84).
- `lowDigitIndex = byteIndex * 2 + 1` with matching signedness is folded by the front end into a
displacement (`sth 2(rX)`, n=79).
- A signed index variable fed from the unsigned counter blocks that fold: the low index stays
`(cnt + 1) << 1` with cnt = SR(byteIndex << 1), created between src and IV4.
| attempt | Hex |
|---|---|
| 16 combinations of src (ptr/index) x high (destOff/byteIndex*2/i) x low index | 16 .. 48 |
| byteIndex*2+1 low index forms (a1-a7), digitIndex++ forms (q1-q5), dest[j++] x2 (j1-j6) | 38 (n=79) |
| separate +1 counter for the low index (m2, n1-n6, 24 declaration orders) | 50 (n=84) |
| u32 counter, int/s32 low index (t_u32_int, c1, c5, c6) | 0 |
| int highDigitIndex/lowDigitIndex from u32 byteIndex (c7, kept) | 0, no change elsewhere, pool identical |
## VmBlobPackCommon: 47 -> 0 (exact)
Diff: argArr (ours r23, target r18) and argCount/writeArgCount (ours r18, target r23). The allocator
needs three simplify sweeps here, so sweep membership matters, not only numbering. A graph simulator
(/tmp/o2-chansvm/packsim.py, built on regsim) traced remaining degrees per sweep:
- Swapping the argArr/writeArgCount declaration slots alone fails: argArr reaches its sweep-2 scan
with degree 29, one over the limit, and drags fmtLen/fmtStr/parentBlob into sweep 3.
- With argArr one neighbour lighter at that point, the swap plus argCount declared between fmtPos and
totalSize reproduces every target register.
- Searching single-node renumberings found the neighbour: @10858, the `dataSize` local of the
VmBlobCopyPadded inline. Inline locals are numbered after all declared locals; the target needs it
in the declared range (ids 36..45), i.e. a local of PackCommon itself. srcOff and dest may sit
anywhere (3855/4000 sampled placements hit).
Kept: the copy code written out in case 4 with writeBlobSrcOff/DataSize/Dest locals of the function,
argArr and writeArgCount declarations swapped, argCount declared between fmtPos and totalSize.
VmBlobCopyPadded (only used here) removed. Pool identical, no other function changed.
| attempt | Pack |
|---|---|
| shared argCount for both passes (merged node), all placements in the simulator | >= 28 misses |
| shared counter, restricted declaration-order annealing (6 seeds) | 7 misses best |
| simulator: swap only / swap + one edge cut / swap + merged loop constants | 3 / 2 / 0 misses |
| simulator: swap + argCount slot + @10858 in declared range | 0 misses |
| source: inline copy code with function-scope locals + two declaration moves | 0 |
## CHANSVmStep (in progress)
Structure first (opcode stream with registers masked, difflib-aligned; /tmp/o2-chansvm/opdiff.py),
then allocation. Findings, each checked against the target object:
- The target addresses VmResultTypeTbl and the constant objects off one .rodata base (r28 = .rodata+0,
offsets 0x160.. and 0xa0). MWCC pools a section base only when a function references three or more
distinct objects in it (/tmp/o2-chansvm/pool/p3.c: two objects never pool, three always do, global or
static). VmResultTypeTbl (0xB4) has no relocation anywhere in the target: it is a dtk-inferred
aggregate of five 6x6 tables (lever 13). Five separate tables give the pooled base.
- `&CHANSVmConstStringObjectUndefined_[4]` takes two addis (array, then element); the target takes one
(`addi r5, r28, 0xa0`), so those five 16-byte objects were separate too. With names, the `base[7]`
hack in CHANSVmConvertToStrFromFloat goes away and that function stays exact.
- `if (stepCount == 0) stepCount = 1;` plus `while (stepCount-- != 0)` (target enters the loop with a
branch to the test at the bottom).
- Stack: target 0x30 = object behind stackPtr (SET_INDEX), 0x40 = STORE_INDIRECT object, 0x50 load,
0x60 operand. MWCC orders frame slots by size, ties in reverse declaration order (pool/s2.c), so
`copies[2]` was two separate objects.
- operandTypes filled through `&operandTypes[typeIdx]` (target keeps a +4 byte IV), not a walker.
- BRANCH_CASE computes into a case-local result (target `li r3, ..` then `mr r14, r3` at the join)
and stores the flag only on the OK path after the pop.
- GET_PROPERTY_NAME: `foundEntry = 0` before the lookup, a one-case `switch (foundObj->type)` (target
`beq +8; b far`), `shouldBranch = foundEntry` before `result = OK`, check reads shouldBranch.
- BRANCH_CASE reads pObjStackTopBuf into stackTop before the stackDepth test.
With these the opcode stream matches except three scheduling ties (511, 598, 836) that depend on
registers; 297 register differences remain.

View File

@@ -1,67 +0,0 @@
# o2-small attempts (2026-10-09)
Worktree `sol-low`, branch `agent/w1009/o2-mcm-pdm-nup`, base `20cf9f9f` (origin/main). Full build OK, DOL SHA1 `26116613…`.
## Compiler version check (all three units)
`/tmp/o2-small/ccsweep.py` compiles the unit with every GC and Wii compiler using the unit's exact flags (`-ipa file` dropped for GC/1.x-2.x, `NO_INLINE` stripped where those can't parse it) and counts instruction-exact functions.
| Unit | GC/1.x-2.7 | GC/3.0a3 … 3.0a5 | GC/3.0a5.2 | Wii 1.x |
|---|---|---|---|---|
| fa/pdm_partition | 5-7/20 | 19/20 (3.0a3 17/20 without NO_INLINE) | 19/20 | 15/20 |
| nup/nup | 0/23 | 20-21/23 (GetAuditData 12) | 22/23 | 9-10/23 |
| iplMemoryCardManager | does not compile | 25/26 (_create_icon 41) | 25/26 (_create_icon 37) | 22/26 |
All three stay on GC/3.0a5.2. `-proc` sweep for pdm (gekko, 750, 740, 7400, 7450, 603e, 604e, generic, 8xx, e300 …): gekko/750/740/7400 identical (19/20), every other model breaks other functions.
## Tooling built this round (all under /tmp/o2-small, not committed)
- `mwdbg/`: private copy of `_mwdbg` (shared lock) with extra PCode dump points: after backend optimizer (0x469383), around 0x596960(func,0) (0x4693a2/0x4693af, a no-op for scheduling), after the real first scheduling pass 0x5995c0(0) (0x4695dd), after 0x59a030 (store→load forwarding, 0x4695ee), before the second pass (0x469548).
- `sim/sched750.py` + `model2.py`: the tw2004 (mitsevox/tw2004 tools/matching/sched750.py) GC/2.6 750 scheduler model, fixed for virtual CR fields (`cr10+` were not parsed) and record forms (`add. rD,…,cr0` defines cr0). GC/3.0a5.2's pick function (0x599920) and DAG builder (0x599ac0) were read from the binary: same rules as GC/2.6, except memory edges use the PCode alias objects (+0x1c, `0x5a0150`). Approximating that with "same base register" reproduces both scheduling passes of the pdm loop block exactly and 49/55 blocks over four pdm functions (the misses are blocks where one object is reached through two different base registers).
## libs/RVL_SDK/src/fa/pdm_partition: pdm_part_is_master_boot_sector (84/86 in repo)
- Plain-sum LE32 (`b0 + (b1<<8) + (b2<<16) + (b3<<24)`, same as the exact sibling's MBR_WORD) + indexed second loop: 21, equal size, exact add tree and loop 2. Only the first loop's byte-load schedule/registers differ.
- First scheduling pass (0x5995c0(0)) input = initial code (the `*p_start` reload is still a `lwz`; 0x59a030 turns it into `mr` after the pass). Model reproduces our pass exactly: `s1` is picked over `s0` at cycle 2 because its shift makes one more successor ready.
- Target register sharing (`s3`/`s1` in r9, `s0`/`s1<<8` in r11) needs a pre-allocation order with `s0` loaded before `s1` and `add (s2<<16)+s0` before `s1<<8`. Annealing over all register-consistent pre-allocation orders under the post-RA model: best 10 ('base' alias) / 8 (all memory ops ordered), never 0. Both residual spots are the same pattern: target issues the low byte load before a shift that frees the next load through an anti-dependence. So with these 24 instructions the target is unreachable; the original block had a different DAG (extra node or different alias edges).
- Model experiments: an extra copy/zero-extend on `b0` in the first pass gives exactly the target load order (s3,s2,s0,s1 / c3,c2,c0,c1) but breaks the r11 sharing; keeping it through both passes (removed after) best 11.
- Source variants tried this round (all 21 or worse): `& 0xFF`, `(pf_u8)`/`(pf_u16)` casts, `<< 0`, byte_at() helper, b0 local, u8-param make_u32 helper (all forms), u8 locals, pointer cursor, array-indexed first loop (24, same first-pass input), accumulator (43).
## libs/RVL_SDK/src/nup/nup: __nupParseServerInfo (66)
- Allocator: coloring order is descending vreg for these low-degree nodes; colour = lowest already-claimed callee-saved register that is free, else claim downward from r31 (regsim reproduces 162/162).
- Per `__nupFindTag` expansion the vregs are: `start` = base, `endTag` = base+2, `startTag` = base+3, ret = base+4; `end` becomes a late temp (114, 120, …) because the backend copy propagation (0x596400) keeps the `strstr` result temp instead of the named `end` (declaring `end` first does not change that: it still becomes the temp).
- Want-list for all 34 FindTag values built from the target. Arbitrary renumbering reaches 34/34 in regsim; constrained to in-block numbering also 34/34, but per-block orders differ: blocks 1-2 need (end < start < endTag < startTag), blocks 3-7 need (end < endTag < startTag < start). No single uniform order gets more than 26/34. Target block 2 claims r18 (end2) before blocks 3-7 reuse it.
- Variants: end declared first 66, separate if-statements 469 (size).
## src/scene/memoryCard/iplMemoryCardManager: _create_icon (37)
- Callers (iplGCWindow) store the result in `const GXTexObj*`, and GXLoadTexObj takes `const GXTexObj*`. Declaring `create_icon`/`_create_icon` as returning `const GXTexObj*` (return type is not in the mangled name) with the banner-style helpers (`initIconTexture` returning `&cell.icon`, `initIconTextureCI`, `initIconPalette` with direct `&mFileCell[slot][file].iconTlut`) gives 11 with no casts. Address shapes all match; the only diff is the C8-path rotation slot*S r28/file*T r26/cellbase r27 (target r26/r27/r28).
- regsim on the captured graph: either swapping the vreg numbers of the two IRO temps (file*T @2824 → r44, slot*S @2826 → r43) or adding the slot↔file*T interference that a `mulli`-before-`mullw` pre-allocation order would create gives the exact target colours.
- IroCSE.c (rayanht/mwcc) shows temps are created in linear-IR order of each expression's first redundant occurrence (second loop of IRO_CommonSubs). Here that is the palette helper's address, where file*T is reached first. sol-r11's `cells` local fixes the order (3 diffs) but changes the TLUT address shape.
- Variants tried (all ≥11): non-const `GXTexObj*` local 44, texture assigned before the palette 21, tlut local in helper 34, helper param types (u8/u16/u32/int/s16 × s32/u32/s16/u16/long) 11-91, `GXLoadTlut(initIconPalette(...))` 11, getter for the icon 44, `&(mFileCell[slot] + file)->…` 11 (same IR).
## Round 2 findings (same day)
### Landed locally
- `6b6aeb4d` _create_icon 37 → 3: icon helpers mirroring the banner ones (palette helper walks `mFileCell[slot]`), `create_icon`/`_create_icon` return `const GXTexObj*` (iplGCWindow already stores the result as const; GXLoadTexObj takes const). No casts. Caller objects differ only in `.strtab`; DOL unchanged.
- `7086ed4c` pdm_part_is_master_boot_sector 84 → 21: entries read with the file's existing `MBR_WORD` (same add tree as the exact pdm_part_get_start_sector), extent check indexed. Equal size; only the first loop's byte-load schedule differs.
### MWCC internals used (GC/3.0a5.2)
- IRO dump: setting byte `[0x725e5c]` when the log is opened (bp at 0x5ed500) makes the compiler write `<source>.log` next to the source; also setting `[0x70f24d]` dumps the full linear IR after every IRO pass. Private mwdbg copy with its own gdb port (LD_PRELOAD bind remap) in /tmp/o2-small/mwdbg; run with `MWDBG_IRODUMP=full`. Delete the `.log` from the worktree afterwards.
- IRO lowering order (rayanht/mwcc IrOptimizer.c): for a binary node the operand with the higher cost is lowered first, ties lower the RIGHT operand first; MUL behaves like cost+2. `&mFileCell[slot][file].x` becomes `((this + C) + slot*S) + file*T`, so file*T is serialized before slot*S.
- IRO_CommonSubs mints a temp at the first redundant occurrence in that serialized order (IroCSE.c), and the backend numbers @temps in reverse creation order (earlier temp = higher vreg = coloured first).
- IRO_SplitLifetimes renames a temp that is assigned on two exclusive paths: the later path's copy gets a new, late @temp (low vreg, coloured last).
- PCode copy propagation (CopyPropagation.c) keeps a copy into a variable only if the variable is in the caller's initial named-object range or one of its uses is itself a move. This is why nup's helper `start` survives (`mr r3, start` feeds the second strstr) while `end` collapses into the late call-result temp.
### _create_icon status
- The C8 rotation (slot*S r26 / file*T r27 / cellbase r28) needs slot*S coloured before file*T. Two sources were found that give it, neither complete:
- `R2C2T2`: `GXLoadTexObj(initIconTexture(...))`, C8 `GXLoadTexObj(&mFileCell[slot][file].icon)`, `return &mFileCell[slot][file].icon` after the if/else. The join return makes the RGB and C8 file*T/cellbase temps one object; IRO_SplitLifetimes renames the C8 copies late → C8 exact. But the same join group merges the RGB GXInitTexObj argument with the post-call address (address kept across the call, r26), 8 diffs.
- Row-pointer local in the palette helper (committed form): slot*S is minted first, but the TLUT address becomes `(row + file*T) + 0x112c` instead of `(row + 0x112c) + file*T`, 3 diffs.
- Type experiments: with the original non-const return type, the RGB path recomputes after the call like the target (the const conversion of the GXInitTexObj argument keeps it out of the join group) but the C8 GXInitTexObjCI argument (non-const prototype) joins the group, 30. Making both GXInit prototypes match the real SDK (non-const) or both const: 27/33/46. SDK header restored each time; not changed.
- Tiny-file probes (/tmp/o2-small/t): inner-index multiply is always minted first unless an earlier statement uses the bare row `cells[slot]`.
- Function-scoped pragmas around _create_icon: wrapping alone changes size (+4), nothing below 34.
### nup
- Pragma sweep (16 singles + all pairs, function-scoped) on __nupParseServerInfo: nothing below 66.
- Literal-tag macro form: tag addresses are rematerialised each time (target keeps them in r22/r25-style registers), size 0x76c; per-block value/length locals: size 0x708. FindTag variants (end first, nested, result var, end+=, param order): 66 or worse.

View File

@@ -1,47 +0,0 @@
# ODH source-integrity checks
Base: 3d7e767cf729de96ac1cd88ddbf5c18eaa08187d (43U only).
- Restored unsigned arithmetic in all three huffmanDecoder word refills by
casting the shifted bytes to u32. The combined word and its bitOffset shift
now remain unsigned, including input words with the high bit set.
- Restored unsigned planeSize indexing in LineConv11. Chroma source pointers
are only formed by accesses in the planar-format branch. The RGB565 caller
passes a row-offset pointer into Capture's GXGetTexBufferSize allocation;
for tile-aligned dimensions that allocation is exactly width*height*2 bytes.
Unconditionally adding two planes to a nonzero row pointer could therefore
form an out-of-bounds pointer even though RGB565 never dereferences it.
- Reviewed the full huffmanDecoder rewrite against its preceding source.
Other category shifts and caller/table preconditions were already present;
no additional newly introduced arithmetic issue was identified in this pass.
One candidate, no compiler flags or other source changes. No debugger, compiler
memory access, forced registers, assembly, uninitialized values, or online source
references were used. Retail objects and disassembly remained local.
Validation:
- All allocated source-object sections, function spans, and resolved relocations
are identical to the unmodified base object (debug metadata differs).
- All 28 retail function spans are raw-byte exact: 14,684 bytes, with all 203
relocations identical after resolving local symbols to actual section offsets
and code symbols to function-relative targets.
- Data matches: .rodata 5,856, .data 464, .sdata2 40 bytes. The source .data is
459 bytes plus five zero alignment bytes in the split/link target.
- Pool identical, 10/10 strings. huffmanDecoder ctxdiff: 306/306, zero diffs.
LineConv11: 146/146; the strict-name local helper prints eight pre-existing
label-name differences. Exact bytes, resolved relocation destinations, and
referenced data independently match; none were ignored without resolution.
- Official objdiff: ODH 28/28 functions; code, data, fuzzy and link all 100%.
- Every measure, function and section in all 1,028 report units, plus all global
measures, is unchanged from the base report.
- Full 43U build and build/43U/ok pass. DOL SHA1:
26116613f624061ba99c8d1a299aaa6efa85670d.
- All 22 workflow-guard tests pass. A host UBSan refill test passes 524,288
cases against a 64-bit oracle (every high byte, offsets 0..7).
- The global completion checker still fails on pre-existing incomplete units;
this change does not claim repository-wide completion.
Local reproducible evidence: ../odh-unsigned-refills-evidence/verify.py,
verification.log, full-build.log, pool.log, guards.log, refill-test.cpp/log,
completion.log, status.json and dol.sha1. No publication or merge performed.

View File

@@ -1,143 +0,0 @@
# opus-aoss: AOSS.c .bss ownership (s_packetState, s_crcTable)
## Evidence
Target relocations (pyelftools over build/43U/obj/src/scene/setting/*.o):
- `AOSS_810BE838` (0x68) and `AOSS_810BE8A0` (0x400) are referenced only by
`AOSSDecryptMessage` (0x81400830) and `AOSSSendHelloRequest` (0x81401778).
No other object in build/43U/obj references them (grep over every .o).
- Those two functions are not contiguous in .text (7 functions between them,
4 after), so (a) "split AOSS.c into a CRC/packet TU with its own functions"
is ruled out: there is no function tail that moves with the objects.
- ATERM.c never references them, so (b) "they are ATERM's" has no support.
- (c) common/tentative: MWLD puts SHN_COMMON blocks after all other .bss of the
link, but ATERM.c's .bss follows these objects, so they are not commons.
Addressing-pattern experiments (AOSS.o, -O4,p -inline off), SendHello differing
lines out of 273 (odiff.py), every other function checked each time:
| AOSS.c form of the two objects | SendHello | other effect |
|---|---|---|
| `static`, defined before the functions (main) | 254 (size 0x43c vs 0x444) | - |
| non-static, defined before the functions | 254 | none |
| `extern` decl at top, definition at end of AOSS.c | 254 | none |
| `extern`, not defined in AOSS.c | 97 (size 0x444) | none |
| all five .bss objects `extern` | 97 | HandleAuthReply 0 -> 103 |
| s_configData + s_networkBuffer also `extern` | 97 | HandleAuthReply 0 -> 103 |
Any definition inside AOSS.c (static, global, early, late) makes MWCC share one
`...bss.0` base register across s_runtime / s_packetState / s_crcTable in
SendHello. The target forms a separate `lis/addi` per object (two for
s_runtime alone), which this compiler only produces when the symbol is
undefined in the TU. Meanwhile s_runtime, s_configData, s_networkBuffer must
stay defined in AOSS.c, or HandleAuthReply loses its exact match. So the two
objects are defined in a different TU that the linker places right after
AOSS.c, with no .text of its own.
## Applied split
- New data-only TU `src/scene/setting/AOSSData.c` (Matching), linked between
AOSS.c and ATERM.c; splits.txt `.bss 0x810BE838..0x810BECA0`.
- They're tentative definitions, so MWCC emits them in reverse order: the
source declares `s_crcTable` and then `s_packetState` (first try in forward
order gave the wrong order and a wrong DOL hash).
- symbols.txt: `AOSS_810BE838` -> `s_packetState`, `AOSS_810BE8A0` -> `s_crcTable`
(needed so the retail AOSS.o asm links against the new definitions).
- `AOSSKeyMaterial`, `AOSSPacketState` and the extern declarations moved to
include/scene/setting/AOSS.h (only AOSS.c includes it).
- Full build: DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d; symorder
AOSSData ORDER OK. All 17 exact AOSS functions are still exact.
## SendHello follow-up (254 -> 58)
| attempt | differing |
|---|---|
| split only, existing source | 97 |
| drop `crcTable` alias local | 97 |
| decl order permutations of response/payload/checksum/sequence (24) | best 82 |
| flat `for (index < 8)` / int index / pointer / sizeof bound / operand swap | 237 (first iteration constant-folded) |
| 2x4 nested loop | 82 |
| `index = 0; while (index < 8) ... bytes[index++]` | 58 |
| decl permutations on top of the while loop | best 58 |
| swap `sequence = 0` / `checksum = 0` | 59 |
| `payload = &response->payload` earlier / at declaration | 69 / 82 |
Remaining in SendHello: checksum r31 vs r30 and payload r30 vs r31 (decl order
can't reach it), and the RC4 loop addresses `construction` from its base
(r1+0x10, offsets 8/9) where the target holds a pointer to `hello.data.bytes`
(r1+0x18, offsets 0/1). The second points at the `construction` carrier struct:
the target probably has `hello` as its own local. That's the next lever.
## Gate (AOSS AOSSData ATERM --quick)
`GATE FAIL: 1 regressions vs main`. The only one is `AOSS: matched_data 3928 -> 2800`,
which is exactly the 1128 bytes now in AOSSData (1128/1128, linked). Global
matched data stays 100%, global fuzzy goes 99.88565 -> 99.88798, no forbidden or
readability findings, DOL SHA1 OK. AOSS is 17/21 exact (unchanged), ATERM 20/26 (unchanged).
## Round 2: alternatives to the data-only TU
| alternative | result |
|---|---|
| definitions in ATERM.c (AOSSData removed, ATERM .bss split moved to 0x810BE838, `AOSSPacketState s_packetState; u32 s_crcTable[0x100];` placed before `gAtermIpConfig`) | built ATERM.o puts them at .bss offsets 8144/9168, i.e. after every ATERM object (unreferenced in the TU, emitted last in reverse order); target needs offset 0/104. MWCC emits a TU's .bss referenced-first, so ATERM can't own the start of its .bss with objects it never uses. Rejected. |
| function-local `static` arrays in SendHello (shadowing the externs) | SendHello 58 -> 231; local statics join the TU's shared `...bss.0` base exactly like file statics. Also ruled out by relocations: AOSSDecryptMessage references both objects directly, so neither function can own them as locals. |
| AOSSLink.c / iplRakuRakuThread.cpp | earlier in link order, their .bss sits before AOSS.c's, can't hold 0x810BE838. Not tried. |
Data-only AOSSData.c remains the only form that gives a separate lis/addi per object.
## Round 2: AOSSSendHelloRequest 58 -> 0
| attempt | differing |
|---|---|
| carrier struct `construction` removed, four plain locals in old order | 84 (hello now addressed at r1+0x18 directly; stack order wrong) |
| 24 permutations of the four locals | best 74: `accessPointName, hello, destination, schedule` (schedule position irrelevant); stack layout now matches |
| RC4 loop reads `*input++` from `input = hello.data.bytes`, as AOSSDecryptMessage does | 57 |
| single-line moves of every declaration (460 builds) | none below 57 |
| no `payload` local (`response->payload.` everywhere) | 261, rejected |
| mwdbg capture (first two runs crashed in the emulator before the function, third worked): `@2964` = checksum's {0, final} web, a split compiler temp numbered above all locals, so it's colored first and takes r31 before `payload`; `@2966` = the reused `index` split for the RC4 loop, colored before `state` and takes r3 | - |
| separate `crc` accumulator for the CRC loop, `checksum = (crc ^ 0xffffffff) & 0xff` | 55 |
| + `checksum` declared right after `payload` (move search) | 23 (r30/r31 fixed) |
| + RC4 loop gets its own counter `i` instead of reusing `index`, declared after `state` | **0**, size 0x444 = 0x444 |
AOSS after: 18/21 exact (was 17). AOSSDecryptMessage still 0/321. Unchanged non-exact:
AOSS_Init_old 1306/1584, AOSSApplyAuthOptions 22/114, AOSSXorBufferWithKey 34/147. Pool identical.
## Gate round 2 (AOSS AOSSData ATERM --quick)
`GATE FAIL: 1 regressions vs main`, again only `AOSS: matched_data 3928 -> 2800` (the 1128 bytes now in
AOSSData, 1128/1128). AOSS 18/21 exact (17 -> 18), code 7720 -> 8812/16192, ATERM 20/26 unchanged, pools
identical, global matched code 97.12163 -> 97.15810, fuzzy 99.88565 -> 99.88839, data 100%, 0 forbidden, 0
readability, DOL SHA1 OK.
# opus-aoss round 3 (2026-10-09): AOSSXorBufferWithKey, AOSS_Init_old
Worktree data-d1, branch agent/w1009/o-aoss at origin/main 72e9c8d6. Scratch
compiles in /tmp/opus-aoss (same flags as ninja, 0.2 s per unit).
## AOSSXorBufferWithKey: 34 -> 0
mwdbg on the old forms (base, compound `^=`, `P = P ^ K`, `output` pointer)
showed what decides the unrolled-loop registers. The second loop's index is
an IRO temp split late, so it is numbered below the IRO CSE cursors
(`packetHalf + index`, `keyMask + index`). With three per-copy values the
cursors are high-degree and colored before the index, so the index never got
r3. A function-scope `output` pointer (used for load and store) is a named
local and survives; a single-use `mask` pointer inside only the second loop
is propagated back into a CSE temp.
The fix is the same `mask` pointer used in both loops (the first loop writes
the mask byte through it twice). Then both cursors stay named locals, the
index temp is colored first (r3), mask (declared first) gets r4 and output
r5, and `mask =` before `output =` gives the target add order.
| trial | differing |
|---|---|
| 14 loop-body spellings (compound, P^K, K^P, temps u8/u32/int, casts) | 37-57 |
| 256-form sweep (P/K spellings x 16 bodies x shared/new index) | best 24 (`u8* output = &packetHalf[index]`) |
| scoped pragma x every form above (15 pragmas) | best 24 |
| `output`/`mask` function-scope, `mask` only in loop 2 | 24 |
| `mask` in both loops, `output =` before `mask =` | 2 (add order) |
| `mask` in both loops, `mask =` before `output =` | **0** |
Unit after: 20/21 exact, pool identical.

View File

@@ -1,29 +0,0 @@
# opus-art: prior-art port attempts (library units)
| unit | symbol | sources found | result |
|------|--------|---------------|--------|
| libs/RevoEX/src/nhttp/NHTTP_stdlib_RVL | NHTTPi_strnicmp | yannicksuter/mscharged-decomp src/RVL_SDK/nhttp/NHTTP_stdlib_RVL.c (+ configure note: NHTTP exact under GC/3.0a5 only); InusualZ/mhtri-decomp src/NHTTP/d_nhttp.c (non-matching there) | 2 -> 0. mscharged source alone stays at 2 under 3.0a5.2; our old int-helper source stays at 2 under 3.0a5; mscharged source + `mw_version="GC/3.0a5"` = exact. |
| libs/RevoEX/src/nhttp/NHTTP_stdlib_RVL | NHTTPi_compareToken | same | 2 -> 0, same fix. Unit fully exact, flipped to Matching, DOL SHA1 unchanged. Using a `LowerCase()` helper instead of the literal ternaries regresses (2 / 17 differing). |
| libs/RevoEX/src/net/aes | AESiEncryptBlock | none (searched AESiEncryptBlock, NETiAESEncryptoBlock, AESiRoundKeyRcon0, NET_AES_BLOCK_MODE_CBC, NETAESCreate: only symbol maps in riptl/wii-symbols and a WiiLink patch header) | no change; GC/3.0a5, 3.0a3.4, 3.0a3 give the same score |
| libs/RevoEX/src/net/aes | AESiDecryptBlock | none (same searches) | no change; same compiler sweep |
| libs/RVL_SDK/src/kbd/kbd_lib | kbdProcMod | headers only (DarkRTA/rb3 kbd.h, galaxymaster2007/THPConv kbd.h); robojumper/sdk_2009-12-11 has kpr_lib.c but no kbd_lib.c | no change (4 differing); compiler sweep no effect |
| libs/RVL_SDK/src/kbd/kbd_lib | kbd_led_handler | same | 3 differing; if/else, `err = 7; if (success == TRUE)`, reordered switch cases give 13-23 (worse); compiler sweep no effect |
| libs/RVL_SDK/src/kbd/kbd_lib | KBDSetModState | same | no change (4 differing) |
| libs/RVL_SDK/src/fa/driver/sd_drv | pfd_sddrv_init / pfd_sddrv_finalize / pfd_sddrv_build_fat32_mbr_bpb | ACreTeam/cf-decomp has only sd_drv.h (VF variant) and nand_drv.c (nanddrv_init/finalize: different body, saved to _refs/prior) | no portable code; compiler sweep no effect |
| libs/RVLMiddleware/TMC_JPEG/src/buffer/idct_block_var | TMCJPEGDEC_IdctBlock_Lumi / _Col | none outside upstream | no change; compiler sweep no effect |
| libs/RVLMiddleware/TMC_JPEG/src/texturecvtr/Texture_MCUtoRGBA8 | TMCJPEGDEC_set_converterRGBA8 / TMCJPEGDEC_converterYUV411toRGBA8 | none outside upstream | no change; compiler sweep no effect |
| libs/RVLMiddleware/TMC_JPEG/src/jpegdec/jdec_main | TMCJPEGDEC_err_restart (asm PLACEHOLDER) | none outside upstream | still asm |
| libs/RVL_SDK/src/cntcache/cntcache | CNTCACHEClear (asm PLACEHOLDER) | bgsamm/pbr-dtk cntcache.h (header only, saved); pret/pokerevo has asm only | still asm |
Note for the NHTTP_recvbuf owner: mscharged-decomp builds all of NHTTP with GC/3.0a5 ("retail code keeps the older compiler's constant order and saved-register zeros ... exact under GC/3.0a5 only"). That is what fixed NHTTP_stdlib_RVL here, so NHTTPi_compareTokenN_HdrRecvBuf is worth trying with `mw_version="GC/3.0a5"` and mscharged's NHTTP_recvbuf.c (already in _refs/prior).
## Round 2: readability
- NHTTP_stdlib_RVL: replaced the four inline tolower ternaries with `NHTTPi_TOLOWER(c)` macro. 14/14 exact, pool identical, DOL SHA1 26116613. `LowerCase()` kept (still used by NHTTPi_strToHex).
## Round 2: NHTTP_recvbuf
- mw_version GC/3.0a5 alone: 6/7, compareTokenN still 5/124.
- Reference compareTokenN control flow (prior/yannicksuter_mscharged-decomp__NHTTP_recvbuf.c), with NHTTPi_TOLOWER macro: 0/124, 7/7.
- Same, without the gotos (if/else reads): 86/128. Rejected; goto form kept.
- Locate step through the existing FindHeaderBlock() helper: still 0/124. Kept.
- Removed the unused static LowerCase(): still 7/7, pool identical, ctxdiff diffs 0.
- Flipped to Matching: DOL SHA1 26116613.

View File

@@ -1,52 +0,0 @@
# opus-aterm attempts (ATERM, 2026-10-09)
Baseline 72e9c8d6: ATERM 20/26 exact; open: BuildEncryptedMessage 2, AutoConfigThread 3,
AesExpandEncryptKey 6, DiscoverAccessPoints 17, BuildAssociationRequest 28, RunConfigProtocol 294.
## Pragma sweep (combosweep, GC/3.0a5.2)
Single and pairwise pragmas: no function improves (BEST = base for all six).
## Compiler version (new finding)
Compiled the unchanged ATERM.c with every GC/Wii compiler that accepts the unit's flags:
| compiler | exact | total diffs | AutoConfigThread |
| --- | ---: | ---: | ---: |
| GC/3.0a3, 3.0a3.2, 3.0a3.3, 3.0a3.4, 3.0a5 | 21/26 | 347 | 0 |
| GC/3.0a5.2 (previous) | 20/26 | 350 | 3 |
| Wii/* | 7/26 | 1590+ | 5 |
GC/3.0a5 makes ATERMi_AutoConfigThread exact with no other function changing; pool identical,
data 100%. The other third-party middleware in this project (Zi Corp eZiText, NHTTP, bte) is already
built with GC/3.0a5. Set `mw_version="GC/3.0a5"` on ATERM.c.
## ATERMBuildEncryptedMessage (2: entry `mr r29,r7` / `mr r3,r27` swapped)
Read MWCC's scheduler (rayanht/mwcc decomp: Scheduler.c, MachineSimulation750.c) and wrote a model
(/tmp/opus-aterm-sched/sim.py). It reproduces our entry block and six micro-tests exactly (count of
unlocked successors, then height, then opcode rank mr < li, then program order; 2 IU slots).
The entry block is scheduled once, before register allocation (block flag 8 stops the post-RA pass).
Exhaustive search over that model: no order of the same ten PCode instructions with the parameter
copies first gives the target, and no single extra/deleted instruction does either. The target order
needs the copy of r7 to come after memset's first-argument move in the scheduler input.
## ATERMAesExpandEncryptKey (6 -> 0, EXACT)
The function is rijndaelKeySetupEnc from the public reference rijndael-alg-fst.c (Te4 = the
substitution table, rcon = the round constants). Earlier forms (initialKey[] array + copy loop,
hand-reassociated XOR trees) left the second key word's two XOR halves scheduled in the other order.
Trials (all GC/3.0a5): array/scalar/direct stores x seven XOR associations: 9..268; reference
GETU32 + reference loops verbatim: 3 (only cmplwi vs cmpwi); with the reference `int keyBits`: 0.
## ATERMDiscoverAccessPoints (17 -> 7)
mwdbg: callee-saved colors go r31 downward in decreasing vreg number. The three strength-reduced
record pointers (entries[i].ssid, entries[i] base, entries[i].bssid) are compiler temps created in
first-use order, so the target's increment order (ssid, base, bssid) means all three were indexed
accesses, not named cursors. The descriptor start (scan buffer + 2) has r27 above them, so it is a
loop-invariant expression hoisted after strength reduction, not a named local set before the loop.
- indexed record fields, named firstDescriptor: 22 (increment order fixed, firstDescriptor r24)
- descriptorWords = (u16*)scanBuffer + 1 inside the loop: 7; &((u16*)scanBuffer)[1]: 7;
(u16*)(scanBuffer + 2) and (u16*)(scanBuffer + sizeof(u16)): 105 (size changes)
Remaining 7: MAC formatter input pointer r9 vs target r5, low nibble r5 vs r9.

View File

@@ -1,62 +0,0 @@
# opus-bs2 attempts (BS2Mach 4 non-exact, BS2Update UpdateThread)
Base 16023905. Start: BS2StartGame 10/393, BS2StartGCGame 9/228, CheckBS2CommandStatus 2/406, BS2Tick 71/1940, UpdateThread 335/913.
Tooling notes:
- mwdbg crashes the emulator (WRITE_UNMAPPED @47e090) whenever `-enc SJIS` is on the command line; drop that flag for tracing (BS2Mach is ASCII). Pass the command via `--args`.
- /tmp/var.py belongs to another worker; my scratch lives in /tmp/opusbs2/.
## Lever 26 IRO off
1. `#pragma ppc_iro_level 0` around each of the four BS2Mach functions, one at a time: StartGame 10->10, StartGCGame 9->145, CheckBS2CommandStatus 2->2, BS2Tick 71->71. Rejected.
## Symbol binding (found via readelf, target LOCAL vs ours GLOBAL)
2. Target has 39 BS2Mach symbols LOCAL (State, NandPending, CacheCommandComplete, CacheSeekComplete, Run, CheckBS2CommandStatus, BS2NANDDivide*, LoaderInit/Main/Close, ...). Made them `static`. Bindings now match; no function changed score (codegen identical). Kept as a link-correctness fix.
## CheckBS2CommandStatus (case 0x12: target `lwz count; stw CacheCommandComplete; slwi`, ours `slwi; stw`)
3. NP; CCC; CacheLength += expr -> 4 (store hoisted before count load).
4. `sizeof * count` operand order -> 2. 5. `CacheLength = CacheLength + expr` -> 9. 6. `= expr + CacheLength + 32` -> 9. 7. `+= 32 + round` -> 2. 8. `* 8` -> 2. 9. `**(u32 **)&DataToc` -> 2.
10. const DVDGameTOC* cast, CCC before -> 4; CCC after -> 2 (lever 27, no effect).
11. (u32) cast on sum -> 3. 12. TRUE -> 2. 13. 0x20 -> 2. 14. `*(DVDGameTOC **)&DataToc` -> 2. 15. open-coded round -> 2.
16. static inline WriteCacheData(buf,size) helper for case 0x12 -> 241 (size becomes temp; target recomputes in else branch, so no helper).
17. mwdbg: the order comes from the pre-RA scheduler (backend-00 -> 01); post-RA scheduler leaves it. Input order has CCC store after the CacheLength store.
18. CacheCommandComplete type BOOL/int/s32 -> 2; volatile -> 46.
19. With static globals: NP;CCC;CL+= -> 4; CL = CL + (expr) after CCC -> 4.
## BS2StartGame / BS2StartGCGame shared prologue (`li r0,1` must precede the base `lis` pair)
20. mwdbg: B1 holds the bss/data base pairs, li/stw StartingGame and the hoisted `&CoverBlock` addi; height of the bss chain wins over li.
21. do-while cover loop -> 10; `for(;;) if break` -> 10; `(&CoverBlock)->state` -> 10; `while (CoverBlock.state)` -> 10; StartingGame = 1 / state != 0 -> 10.
22. `DVDGetCommandBlockStatus(&CoverBlock)` call -> 8 (prologue fixed but loop becomes bl; rejected, evidence that the stw needs a successor/priority).
23. static inline WaitForCoverCommand() / WaitCommandIdle(block) helpers -> 10/9.
24. StartingGame after the loop -> 368 (wrong).
25. `volatile BOOL StartingGame` -> StartGame 10->5, StartGCGame 9->4, every other BS2Mach function unchanged (report: 25/29 exact, data 100%). StartingGame is the cross-thread "game is starting" flag read by BS2Tick, like the other volatile flags (CacheFailed, RegionValid, NandPending). KEPT.
## BS2StartGame DI write (0xCC003024): target addr r4 / value r3, ours addr r3 / value r4 (5 diffs)
26. Declaration permutations of diBits/diValue/diAddr (5 orders) -> 5 or 7.
27. `__PIRegs[9]` instead of raw pointer, value/bits named -> 5 (same tie). regsim (want diValue=r3): structural, 0/1.
28. regsim on three-named form (want diValue=r3,diAddr=r4,diBits=r0): best 1/3, structural. The address is always a lis temp (r196); the value must be a temp numbered after it to be colored first.
29. `*diAddr = (*diAddr | 1) | diBits` (u32/vu32, 1U, no parens) -> registers right but `ori 4`+`ori 1` merge into `ori 5`: 24, size -4.
30. `diBits | (*diAddr | 1)` -> 7 (ori 1 moves after the or). `(u32)(...) | diBits` -> 7. `diValue = *diAddr | 1` -> 7. `__PIRegs[9] | 1` into named -> 7.
## BS2StartGCGame 64-bit multiply (target mulhwu(freq r5, seconds r7); ours mulhwu(seconds, freq))
31. Declaration permutations of rtc/counterBias/seconds/timerFrequency x two operand orders (48 builds) -> all 8 (freq*sec) / 4; named values are forwarded, decl order irrelevant.
32. freq*sec forms: `(OSTime)freq * sec`, `freq * (OSTime)sec`, both cast, `(u64)` (145, size change), OS_TIMER_CLOCK*, `(OS_BUS_CLOCK >> 2)` / `/ 4` inline -> 8: operand order fixes the multiply but evaluation order follows it, so registers swap.
33. sec*freq forms: OSSecondsToTicks, `time = rtc + bias; time *= clock`, `time = CLOCK * time` (operands get swapped back to time first!), OSTime-typed seconds and/or timerFrequency -> 4.
34. freq computed before seconds statement -> 4/8; `time = freq; time *= sec` -> 9.
35. OSTime-typed timerFrequency x four freq*sec forms -> 8.
36. Put the SCGetCounterBias() call inside the right operand: `time = OS_TIMER_CLOCK * (OSTime)(rtc + SCGetCounterBias());` -> 0/228 EXACT. The call makes the seconds operand heavier, so it is evaluated first (lower vreg -> r7) while the clock stays the left operand. Also exact: `(OSTime)OS_TIMER_CLOCK * (rtc + SCGetCounterBias())`, `(OSTime)(OS_BUS_CLOCK >> 2) * (...)`. Unused locals counterBias/seconds/timerFrequency removed. Pool identical (91/91), BS2Mach 26/29, data 100%.
## BS2Tick (71 at start of this round)
37. IRO off -> 71 (attempt 1).
38. Move `AudioBufferUnconfigured = 1` to each of 10 positions in case 0 -> 71/72. volatile AudioBufferUnconfigured -> 71.
39. Definition-level volatile sweep, one global at a time (36 globals): PartitionOpen 71->68, LoadingTitle 71->69, all others same or worse (State 76, ResetTime 91, CoverPollTime 166, CurrentTmd 1314, ...).
40. `static vu32 PartitionOpen` + `static vu32 LoadingTitle` -> BS2Tick 66; every other BS2Mach function unchanged (26/29, data 100%). LoadingTitle is set by BS2StartLoadingTitle from the menu thread and polled by BS2Tick; PartitionOpen is likewise a cross-call state flag. KEPT.
41. Second single-volatile sweep on top of 40 -> nothing below 66.
42. Device-code block (target 0x27d4): target shares one `State = BS2_STT_8` after the if/else; ours duplicates it. Merging fixes the tail but target also re-materializes `lis 0x8000` in each branch, ours reuses the consoleType base -> 8 bytes short, 1703 diffs. Tried consoleType as `(OSBootInfo *)`, `OSPhysicalToCached(0x2C)`, `*(u32 *)0x8000002C`, `OS_ADDR_BOOT_INFO`, `!(...)`, `OSGetConsoleType()` (adds bl), and `*(u16 *)OSPhysicalToCached(0x30E6)` for the store: all 1701-1703. Restored the duplicated State (66).
43. `#pragma ppc_iro_level 0` around BS2Tick with merged State -> identical output; IRO evidently does not run on BS2Tick (or StartGame) at all, so the lis sharing comes from the backend.
## BS2Update
44. readelf: target has rc/VersionIOS/VersionMEM2/VersionES/ConsoleType GLOBAL and getSuffix LOCAL (ours the opposite). Fixed the bindings: UpdateThread 335/913 unchanged (codegen identical).
45. Logging-call `titleId` via UPDATE_DISC_ENTRIES macro instead of discEntries (target re-materializes `lis 0x8048` there) -> 335. Dropping the discEntries local entirely -> 382. Remaining diff is an extra callee-saved register in target (r14..r31) shifting every allocation; not pursued further this round.
Final gate (BS2Mach + BS2Update, --quick): GATE PASS, 0 regressions, BS2Mach 26/29 exact (BS2StartGCGame new), BS2Update 9/10.
Best non-exact sources: opus-bs2.best.c (BS2Tick 66, volatile PartitionOpen/LoadingTitle), opus-bs2.best.BS2Update.c (binding fixes, UpdateThread 335).

View File

@@ -1,44 +0,0 @@
# opus-bs2update UpdateThread attempts
Worktree data-d10, branch agent/w1009/o-bs2update, base 72e9c8d6 (origin/main). Owned `src/BS2/BS2Update.c`; the fix also needs a one-line rename in `config/43U/symbols.txt` and the Matching flip in `configure.py`. Read opus-common, levers, the effort-policy entries, sol-x8, sol-y3 (`git show 4925fde2`) and sol-z1.
Start: UpdateThread 6/913 differing, equal size 0xe44. The other nine functions are exact. The remaining diffs are the three seat-loop scheduling swaps described by sol-x8, sol-y3 and sol-z1.
combosweep (single and pairwise allowed pragmas): `BEST src/BS2/BS2Update UpdateThread base 6 -> 6 []`. No pragma moves it.
## Diagnosis
The decompiled 1.2.5 scheduler (rayanht/mwcc `src/backend/Scheduler.c`, inspiredrobot/mwcc `docs/SCHEDULER.md`) adds a store-to-later-load edge for every memory pair the alias test cannot separate, with the store's latency. sol-y3's capture already showed that the seat loads carry a worst-case alias set that contains Flags0's bit, so `Flags0[index] = 0` wins the height race against the seat address `add`. The target schedules the `add` first. That is the order you get when no such edge exists.
I tested small probe functions with the unit's exact compiler flags: a loop that stores `FlagsX[i] = 0` and then tests `p[i].attr & 1`. The results:
| Seat entries come from | Flag array | Edge (store first)? |
| --- | --- | --- |
| absolute `T a[] : addr` (array, struct, single entry, const, static) | file-scope static | yes |
| integer cast `(T*)0x80480000 + n` (folds to `addis`, wrong form anyway) | file-scope static | yes |
| pointer parameter | file-scope static | yes |
| normal relocated global array | file-scope static | no, but needs `lis/addi` with relocs (wrong form) |
| absolute array (target's `lis r0,0x8048; add` form) | file-scope static, initialized or tentative, extern | yes |
| absolute array | **function-local static** | **no** |
| absolute array | global scalar / local stack array | no |
An unknown pointer (absolute storage counts as unknown) may alias every file-scope object, but not a function-local static whose address is never taken. The target keeps the absolute `lis r0, 0x8048; add` form and has no edge. So Flags0 was a function-local static of the selection code.
## .bss order
The target order is Flags0, Flags1, Thread, ThreadStack, UpdateHeader0, UpdateHeader1. Probes on the same compiler show the emission rules:
- initialized objects are emitted where they are defined;
- tentative definitions are emitted at their first use;
- a function static is emitted when its function is parsed.
So the static has to come from a function parsed before BS2UpdateInit, and the other five arrays have to be tentative definitions. Init first uses Flags1, Thread and ThreadStack, and the inlined selection code first uses UpdateHeader0 and UpdateHeader1. That gives exactly the target order.
## Trials
1. `seatEntries = (BS2UpdateEntry*)0x80480000 + wadCount`: 549/912 (address folds into `addis`; the swaps stay). Rejected.
2. `static u32 Flags0[...] = {0};` inside BS2SelectUpdateEntries, everything else unchanged: 18/913. All three swaps gone; the 18 left are .bss offsets because Flags0 lands after UpdateHeader1. Init 4 diffs from the same shift.
3. As 2, but the Flags1/Thread/ThreadStack/UpdateHeader0/UpdateHeader1 definitions are tentative (the `= {0}` initializers dropped) and BS2SelectUpdateEntries is defined before BS2UpdateInit: **UpdateThread 0/913, all 10 functions exact**. .bss layout identical to the target, pool 55/55 identical.
4. Rename the target symbol `Flags0` to the compiler's local-static name `Flags0$1129` in config/43U/symbols.txt. This is the project convention for function statics (144 `name$N` entries). Report: code 4052/4052, data 10488/10488, every section 100%, functions 10/10.
5. Flip BS2Update to Matching and run the full build: DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d. build.ninja links build/43U/src/src/BS2/BS2Update.o.
No pragma, asm, volatile change, carrier, padding or dummy is added. The source change is: the selection helper moves above BS2UpdateInit, Flags0 becomes its function static, and five `= {0}` initializers are removed.

View File

@@ -1,61 +0,0 @@
# opus-candbox attempts
Worktree `sol-high`, branch `agent/w1009/o-candbox`, base `72e9c8d6`. Unit `src/keyboard/tiCandidateBox`, last open function `LayoutByNW4R::createAnmPane_` (6/216, count r23 and slot r31 swapped). Read opus-common.md, levers.md, effort-policy entries, sol-x9 log, sol-m4 log (branch `agent/w1009/candbox-max`), saved sol-r12/sol-y11 diffs.
Baseline: full build OK, DOL `26116613...`, odiff 6/216, pool identical 57/57. combosweep (single and pairwise pragmas): `base 6 -> 6`, no hit.
## Root cause
`tiPredictLang::create` is already exact and has the same inner loop with the same struct (`char paneName[20]`, `count`, `forceAddName`, `pAnims[8]`). Its target has count r31 and slot r23, which is what createAnmPane_ needs.
A private mwdbg trace of `tiPredictLang::create` (port 19931 copy of the launcher, shared tool unchanged) shows why. The slot base `p + j*4` is IRO CSE temp `@7026` (vreg r45) and forceAddName is IRO temp `@7028` (r44). Both are numbered after the named locals and before the hoisted constructor constants, so they simplify before the constants and color after them (slot r23). Count is a late anonymous load hoisted out of the loop condition (r131), so it colors first (r31).
The same natural loop inside tiCandidateBox (`j < paneAnimations.count`, `paneAnimations.pAnims[j]->` three times) gives 220 insns. No IRO temps are created, the slot is recomputed in each branch, and constant `2` survives pass-1 spilling.
Table declaration trials with that loop:
| trial | table | result |
| --- | --- | --- |
| 01 | `extern "C" const CandidatePaneData scCandidatePaneData` (struct wrapper, aligned(8)) | 158/220 |
| 02 | `static const CandidatePaneData` (struct wrapper) | 158/220 |
| 03 | `extern "C" const PaneToAnimation[]` (plain array) | 158/220 |
| 04 | `static const PaneToAnimation[]` (plain array, no aligned) | **0/216** |
IRO only CSEs the table loads and addresses when the table is a static plain array, which is how every sibling unit declares it (`csPaneToAnimation`). The `CandidatePaneData` wrapper and `extern "C"` were decomp scaffolding. Without `aligned(8)` the table still lands at .data 0x28, size 0x680.
## Source changes
- Table: `static const PaneToAnimation csPaneToAnimation[]`, same name as tiToolBar/tiPredictLang/pctype. Removed the unused `CandidatePaneData` struct.
- `createAnmPane_`: the tiPredictLang/tiToolBar loop form, with no count/forceAddName/animation locals.
- symbols.txt: `scCandidatePaneData` -> `csPaneToAnimation__Q29textinput12candidatebox` (scope:local). Same address and size. Only tiCandidateBox referenced the old name.
Unit after this: 112/112 functions, code 100%, data 100%, all sections 100%, pool identical.
## Link (Matching flip)
First flip: DOL `8d444a7b...`. Two causes, both checked against the original objects:
1. Thunk order. Target `@36@__dt__` comes before `@36@setRootPaneScaleFor4x3..init`; ours put it last (already true on the old baseline). This is the "move to end on touch" thunk list (eggAudioExpMgr, lever 12). tiPredictLang/tiToolBar/tiCellPhone fix it with a header `Sample : public LayoutByNW4R` behind a `*_SAMPLE_CLASS` macro, and `__vt__Q39textinput12candidatebox6Sample` exists in the DOL. A Sample with only `virtual ~Sample() {}` does not move the thunks. It needs the inline constructor, so the Base/EventHandler/LayoutByNW4R constructor guards also accept `TI_CANDIDATEBOX_SAMPLE_CLASS`, as tiPredictLang.h does. After that, all 112 common functions are in target order. Proof it is required: removing it leaves the wrong thunk order and DOL `5507fb9e...`.
2. Weak vtable hole. The target has 0x40 zero bytes between `__vt__...AnmObserver` (0xd48) and `__vt__Q39textinput4util12AnimObserver` (0xd94). Ours left only the deduplicated gui::EventHandler copy (0x18), so everything after shifted by -0x20/-0x24. util::Animation methods were inline in the original: they sit as scattered weak functions in tiInputForm's .text, and MyTiManager.cpp already defines them `inline`. UITextArea has a `util::Animation` member, so the original object also emitted a weak `__vt__Q39textinput4util9Animation` (0x24, kept from tiInputForm). EventHandler 0x18 at 0xd58 + Animation 0x24 at 0xd70 ends at 0xd94. I added the same inline definitions as MyTiManager.cpp at the end of tiCandidateBox.cpp, with startAnm in this TU's declared parameter order. Only virtual calls exist, so no code changes. .data is now 0xda0, the target size.
Flip with both: full build OK, `build/43U/main.dol` SHA1 `26116613f624061ba99c8d1a299aaa6efa85670d`.
Trial snapshots: `/tmp/opus-candbox/trials/`. Captures: `/tmp/opus-candbox-cap-predictlang`, `/tmp/opus-candbox-cap-f01`.
## Gate
```text
full build: ok
main.dol sha1: 26116613f624061ba99c8d1a299aaa6efa85670d
[src/keyboard/tiCandidateBox] pool: IDENTICAL
[src/keyboard/tiCandidateBox] objdiff: code 24000/24000 data 4652/4652 functions 112/112 fuzzy 100.0000 linked code 24000
[src/keyboard/tiCandidateBox] instruction-exact functions: 112/112
regressions vs baseline: 0
global matched_code_percent: 98.14728 -> 98.17613
global complete_code_percent: 91.22256 -> 92.02384
forbidden patterns added (net, per file): 0
readability warnings (net, per file; must be 0 in the final result): 0
GATE PASS
```
origin/main moved to `82783c6e` during the run (BS2Update lines in configure.py/symbols.txt only, no overlap). Not rebased.

View File

@@ -1,47 +0,0 @@
# opus-chansvm: CHANSVm round (ConvertToFloatFromStr, WinEmuWrite, DateDtor, BlobGetHexString, BlobPackCommon, Step)
Worktree data-d2, branch agent/w1009/o-chansvm, base 72e9c8d6. Start: 227/233 exact.
Scratch harness: /tmp/opus-chansvm (score.py compiles the unit with the Ninja flags and diffs every function).
## combosweep (single + pairwise pragmas, whole unit)
No setting improves any of the six functions (Float 2, Win 5, Date 7, Hex 14, Pack 47, Step 262).
## CHANSVmConvertToFloatFromStr: 2 -> 0 (exact)
Diff: target `lbz type; li 0; stw endPtr; cmplwi`, ours `... cmplwi; stw`.
Scheduler RE (mwcceppc 0x599ac0 builds the block graph bottom-up; 0x5a0150/0x5a0170 is Alias.c may_alias):
a load gets an edge to every later store it may alias, with the load latency as delay. The `obj->type`
load had the worst_case alias set, which contains the escaped local endPtr, so LBZ -> STW had delay 2
and the compare won the cycle-2 tie. A load whose base register comes from a pointer-to-const (or
restrict) variable gets a private pseudo-object alias instead (see zcanann/FFCC-Decomp
tools/patch_compiler_rw.py notes), so the edge disappears and the store issues at cycle 1.
The inlined parser's `const` parameter is copy-propagated into the caller's `object`, so the const has
to be on the caller's parameter. Small-harness check: const/restrict on the inline parameter alone keeps
the old order; on the caller parameter it gives the target order.
| attempt | Float | others |
|---|---|---|
| `const CHANSVmObjHdr* object` on ConvertToFloatFromStr, `(VmConvertFunc)` cast at its table slot | 0 | no change |
| VmConvertFunc typedef and all 11 converters take const, cast in StrFromArray | 0 | no change |
| `#pragma opt_pointer_analysis on` (diagnostic) | compiler segfaults | - |
Kept the first (minimal) form. Same lever as CHANSVmParseInt (`const CHANSVmObjHdr* obj`).
## VmDateDtor: 7 -> 0 (exact)
Diff: target loads `MonthTbl[mon]` before the outgoing `year` stack-argument store; ours after it.
Same mechanism: the stack-argument stores carry the worst_case alias, and global tables are members of
it, so every store -> table-load edge had delay 2. The target object has no symbols for the two tables
(0xb34, 0xb50 are unnamed local data), so they were never globals.
| attempt | Date | others |
|---|---|---|
| file-scope `static` on both tables | 7 | no change |
| file-scope `static` on one table (each) | 7 | no change |
| both tables as function-scope `static` inside VmDateDtor | 0 | no change, .data bytes identical |
| plus direct `date.x` access instead of `datePtr` | 84 | - |
Kept function-scope statics with the datePtr form.

View File

@@ -1,87 +0,0 @@
# opus-cntc attempts (cntcache.c)
## _CNTCACHEDeleteContent (start: asm placeholder; prior best C 95.79%, 143/145)
1. Flat early-return C, typed `ESTmdView view` local: 80/145 differing, frame 0x2120.
2. `u8 buf[sizeof(ESTmdView)]` + `ESTmdView* tmd` pointer, size/count decl order swapped: 118 (frame fixed, pointer r28 appears).
3. Helper with multiple returns: 90 (worse branch shape in helper, `bge; b`).
4. Helper with `usage` var + if/else chain: 90.
5. `usage = result;` before chain: 118 (coalesced anyway).
6. Type check via `ES_TITLE_TYPE` (u32 cast and 64-bit): -1 still CSE'd into r31.
7. `(titleId & 0xFFFFFFFF00000000) != 0x0001000500000000`: 96, xor form.
8. Nested-if structure (single exit, memset inside): 90/145, 143/145 insns; only diffs are the
missing `li r0,-1` reload before snprintf (CSE/LICM keeps -1 in r31) and missing `mr r0,r3`
(helper result coalesced into r3); everything else is register renumbering from those.
9. Diagnostic: type check without mask -> li -1 hoisted to outer token-loop preheader (LICM).
10. 32-bit masks `(u32)(x>>32) & 0xFFFFFFFF`: masks fold away, 82 but wrong (no `and`).
11. Mask variants `(u32)(t>>32),(u32)(t&0xFFFFFFFF)` etc.: 89-90, -1 still hoisted.
12. Helper `static` (auto-inline) instead of `static inline`: 90, no change.
## _CNTCACHEIsTitleRemovable (start: asm placeholder; prior best C 93.71%)
Upstream koopthekoopa/wii-ipl has a non-matching C sketch (GetSavePath/GetTmdView helpers, `ret = -1`, goto out); read only.
1. Typed flat version with my usage helper: 69/82.
2. Upstream structure (GetSavePath + GetTmdView helpers, `s32 ret = -1`, goto out): 72.
3. GetTmdView takes `u32* tmdSize` from caller: frame offsets right, 72.
4. Usage code written directly in the caller (no GetSavePath): `mr r4,r3` copy appears in target position.
5. + `u8 tmdBuf[OSRoundUp32B(sizeof(ESTmdView))]` with `ESTmdView* tmd` pointer: 5/82.
6. `(u8)(titleVersion >> 8)`: no change (srawi.); `((v >> 8) & 0xFF)`: 4/82.
7. Back to GetSavePath helper with those fixes: 18 (copy coalesced on the wrong side).
8. `result`/`ret` split in helper: 18. `static inline`/`s32` helper: 18. Drop `= -1` init: 69.
## _CNTCACHEDeleteContent (cont.)
13. Usage code written directly (no helper): no copy, 90.
14. Function-wide `ret` reused for every status (typical SDK style): 94, no copy.
15. Shared `static s32 GetSaveDataUsage` helper written like the matched inline code
(`s32 ret = -1;`, separate `usedBlocks = 1; usedINodes = 1;` stores, if/else chain):
21/145. Swapping usedBlocks/usedINodes declaration order: 15. Declaring `titleId` before
`tmd`: **0/145 (exact)**. The dead `ret = -1` init is load-bearing (without it: 90).
16. IsTitleRemovable switched to the same helper with caller `s32 ret;` (no init): **0/82**.
(With caller `ret = -1` init: 16/82.)
## CNTCACHEClear (start: asm placeholder; prior best C 93.36%, 147/151)
1. Replaced the hex blob with real literals (SDKDefineVersion, path/command literals,
`" \n"`, `"/title/%08x/%08x/data"`). Clear in C with `FindLineEnd` static helper: 162/180;
`_CNTCACHEDeleteTitle` got auto-inlined into Clear (target calls it).
2. `(void)` prototypes, no prototypes (compile error), `-ipa function` / no ipa (no change, or
header static inlines emitted): DeleteTitle still inlined / unusable.
3. Diagnostic `#pragma inline_max_auto_size(k)`: DeleteTitle's auto-inline size is 15 and the
default limit is 15, so the original DeleteTitle must score >= 16.
while->for, nested ifs, result assignments: still 15. switch: breaks DeleteTitle.
4. DeleteTitle as a `for` loop with `if (errno != 0 || type == 1) continue;`: size 16, not
inlined, DeleteTitle still 0/50. Clear: 126/151, size 147/151.
5. Error exits: `goto close`, else-goto, switch, do/while(0)+break all give `bne close`; micro-tests
show only `return` gives the target `beq +8; b close`. Helper `ExecuteCacheFile(info, result)`
with returns: 151/151 (not inlined, auto size); `static inline`: 68/151, 149 insns, branch
layout matches.
6. `s32 readLength` + `> sizeof(buf)` clamp: cmpw/bgt/cmplwi as target, 67.
Swapping compare operands: no effect. `!lineEnd` / `if (command)`: immediate compares, 64.
7. Stripped writers `CNTCACHEAddDeleteTitle` / `CNTCACHEAddDeleteContent` (+ static Read/Write
helpers using /shared2/cntcache.txt, /tmp/cntcache.txt, NANDPrivateMove to /shared2):
.data and .sdata bytes identical to target, Clear string offsets match.
8. Brute-force local order: Clear's own decls have no effect; helper decls reversed
(lineLength, line, readLength, offset): 47/151 (helper r23..r26 match).
9. Lone `cmpwi r3,0` after each NANDPrivateDelete: empty if, `;`, `(void)(x == 0)`, empty inline
call, dead store, inline void/return helpers all remove it. Micro-test: kept only when
the body copies between two coalesced variables (`r = res; if (g()) { r = res; }`).
`opened = FALSE` in body: 49/155. `result = result;`: keeps only the second compare, 47/151 at 150 insns.
Not found; stopped here.
Result: CNTCACHEClear not exact (best 47/151, 149/151 insns). Best C plus required companion
changes in [opus-cntc.best.c](opus-cntc.best.c); the asm placeholder and original data arrays stay.
## Final state
- `_CNTCACHEIsTitleRemovable` 0/82, `_CNTCACHEDeleteContent` 0/145 (C, shared GetSaveDataUsage).
- `CNTCACHEInit` 0/29, `_CNTCACHEDeleteTitle` 0/50, `CNTCACHEClear` 0/151 (asm) unchanged.
- pool_diff: identical (9/9).
- Note: in DeleteContent, `result != ES_ERR_DONT_EXISTS && result == ES_ERR_OK` keeps the
target's separate -106 compare; this is redundant but not impossible.
## Round 2: _CNTCACHEDeleteContent without the redundant test
1. Replaced `result != ES_ERR_DONT_EXISTS && result == ES_ERR_OK && ...` with an early
`if (result == ES_ERR_DONT_EXISTS) { return; }` followed by `if (result == ES_ERR_OK && ...)`:
0/145, equal size. IsTitleRemovable still 0/82, pool identical (9/9).
check_asm_inventory: FAIL before and after (same 8 pre-existing placeholders incl. parked CNTCACHEClear).

View File

@@ -1,259 +0,0 @@
/*
* opus-cntc best C for CNTCACHEClear: 47/151 differing, 149/151 instructions
* (odiff libs/RVL_SDK/src/cntcache/cntcache CNTCACHEClear). Not exact; the retail
* assembly placeholder stays in cntcache.c.
*
* Needed alongside this text (all verified in the trial build):
* - Replace the scCntCacheStrs/scCntCacheTitleDataFmt/scCntCacheSpaceNl byte arrays with
* real literals: SDKDefineVersion(CNTCACHE, "Apr 20 2010", "14:15:28"), " \n",
* "/title/%08x/%08x/data". The writer functions below (stripped from the DOL) own
* "DeleteTitle ", "%016llx ", "/shared2" and "DeleteContent " and put them before
* Clear's literals; with them .data/.sdata bytes are identical to the target.
* - _CNTCACHEDeleteTitle must be the for/continue form below. The while form has auto-inline
* size 15 (= the -inline auto limit) and gets inlined into Clear; the target calls it.
* The for/continue form still matches DeleteTitle 0/50 and is not inlined.
* - ExecuteCacheFile must be `static inline` with `return`s: that is what produces the
* target's `beq +8; b close` exits (goto produces `bne close`).
* - Helper locals declared in reverse (lineLength, line, readLength, offset) give the
* target's r23..r26. Clear's own local order has no effect.
*
* Remaining: the target has a lone `cmpwi r3,0` after each NANDPrivateDelete. MWCC keeps
* such a compare when the if-body is a copy between two coalesced variables (micro-test:
* `r = res; if (g() != 0) { r = res; }`). An empty if-body or ignored return removes it, and
* `result = result;` keeps only the second one. The caller-side registers (base r30, opened
* r29, result r28, locked r27, zero r31) are still off, probably because of that missing copy.
*/
#define CNTCACHE_READ_SIZE 0x400
#define CNTCACHE_LINE_SIZE 0x40
#define CNTCACHE_RESULT_READ_ERROR (-5299)
static s32 ReadCacheFile(char* buf, u32 bufSize, u32* length) {
NANDFileInfo info;
s32 result;
*length = 0;
result = NANDPrivateOpen("/shared2/cntcache.txt", &info, NAND_ACCESS_READ);
if (result == NAND_RESULT_NOEXISTS) {
return NAND_RESULT_OK;
}
if (result != NAND_RESULT_OK) {
return result;
}
result = NANDGetLength(&info, length);
if (result == NAND_RESULT_OK && *length > bufSize) {
result = NAND_RESULT_MAXBLOCKS;
}
if (result == NAND_RESULT_OK && NANDRead(&info, buf, OSRoundUp32B(*length)) != *length) {
result = CNTCACHE_RESULT_READ_ERROR;
}
NANDClose(&info);
return result;
}
static s32 WriteCacheFile(const char* buf, u32 length);
s32 CNTCACHEAddDeleteTitle(ESTitleId titleId) {
char buf[CNTCACHE_READ_SIZE + CNTCACHE_LINE_SIZE] ALIGN32;
u32 length;
s32 result;
OSLockMutex(&_CNTCACHEMutex);
result = ReadCacheFile(buf, CNTCACHE_READ_SIZE, &length);
if (result == NAND_RESULT_OK) {
strcpy(buf + length, "DeleteTitle ");
length += strlen(buf + length);
length += sprintf(buf + length, "%016llx ", titleId);
buf[length++] = '\n';
result = WriteCacheFile(buf, length);
}
OSUnlockMutex(&_CNTCACHEMutex);
return result;
}
static s32 WriteCacheFile(const char* buf, u32 length) {
NANDFileInfo info;
s32 result;
NANDPrivateDelete("/tmp/cntcache.txt");
result = NANDPrivateCreate("/tmp/cntcache.txt", NAND_PERM_USER | NAND_PERM_GROUP, 0);
if (result != NAND_RESULT_OK) {
return result;
}
result = NANDPrivateOpen("/tmp/cntcache.txt", &info, NAND_ACCESS_WRITE);
if (result != NAND_RESULT_OK) {
return result;
}
if (NANDWrite(&info, buf, length) != length) {
result = CNTCACHE_RESULT_READ_ERROR;
}
NANDClose(&info);
if (result != NAND_RESULT_OK) {
return result;
}
return NANDPrivateMove("/tmp/cntcache.txt", "/shared2");
}
s32 CNTCACHEAddDeleteContent(ESTitleId titleId, const char* indices) {
char buf[CNTCACHE_READ_SIZE + CNTCACHE_LINE_SIZE] ALIGN32;
u32 length;
s32 result;
if (strlen(indices) > CNTCACHE_LINE_SIZE / 2) {
return NAND_RESULT_INVALID;
}
OSLockMutex(&_CNTCACHEMutex);
result = ReadCacheFile(buf, CNTCACHE_READ_SIZE, &length);
if (result == NAND_RESULT_OK) {
strcpy(buf + length, "DeleteContent ");
length += strlen(buf + length);
length += sprintf(buf + length, "%016llx ", titleId);
strcpy(buf + length, indices);
length += strlen(buf + length);
buf[length++] = '\n';
result = WriteCacheFile(buf, length);
}
OSUnlockMutex(&_CNTCACHEMutex);
return result;
}
static char* FindLineEnd(char* str, u32 length) {
u32 i;
for (i = 0; i < length; i++) {
if (*str == '\n') {
return str;
}
str++;
}
return NULL;
}
static inline s32 ExecuteCacheFile(NANDFileInfo* info, s32 result) {
u32 fileLength;
u8 buf[CNTCACHE_READ_SIZE] ALIGN32;
u32 lineLength;
char* line;
s32 readLength;
u32 offset;
char* lineEnd;
char* command;
if (result != NAND_RESULT_OK) {
return result;
}
result = NANDGetLength(info, &fileLength);
if (result != NAND_RESULT_OK) {
return result;
}
offset = 0;
while (fileLength != 0) {
readLength = fileLength;
if (readLength > sizeof(buf)) {
readLength = sizeof(buf);
}
line = (char*)buf;
if (NANDRead(info, buf, OSRoundUp32B(readLength)) != readLength) {
return CNTCACHE_RESULT_READ_ERROR;
}
result = NAND_RESULT_OK;
lineEnd = FindLineEnd(line, readLength);
if (!lineEnd) {
return NAND_RESULT_OK;
}
while (readLength > 0) {
*lineEnd = '\0';
lineLength = lineEnd - line;
command = strtok(line, " \n");
if (command) {
if (strcmp(command, "DeleteTitle") == 0) {
_CNTCACHEDeleteTitle();
} else if (strcmp(command, "DeleteContent") == 0) {
_CNTCACHEDeleteContent();
}
}
lineLength++;
line += lineLength;
fileLength -= lineLength;
readLength -= lineLength;
offset += lineLength;
lineEnd = FindLineEnd(line, readLength);
if (!lineEnd) {
break;
}
}
if (fileLength != 0) {
if (NANDSeek(info, offset, NAND_SEEK_BEG) != offset) {
return CNTCACHE_RESULT_READ_ERROR;
}
result = NAND_RESULT_OK;
}
}
return result;
}
s32 CNTCACHEClear(void) {
NANDFileInfo info;
BOOL opened = FALSE;
BOOL locked;
s32 result;
OSLockMutex(&_CNTCACHEMutex);
locked = TRUE;
result = NANDPrivateOpen("/shared2/cntcache.txt", &info, NAND_ACCESS_RW);
if (result == NAND_RESULT_NOEXISTS) {
result = NAND_RESULT_OK;
goto end;
}
result = ExecuteCacheFile(&info, result);
NANDClose(&info);
opened = FALSE;
if (NANDPrivateDelete("/shared2/cntcache.txt") != NAND_RESULT_OK) {
}
if (NANDPrivateDelete("/tmp/cntcache.txt") != NAND_RESULT_OK) {
}
end:
if (opened) {
NANDClose(&info);
}
if (locked) {
OSUnlockMutex(&_CNTCACHEMutex);
}
return result;
}
void _CNTCACHEDeleteTitle() {
char* token;
for (token = strtok(NULL, " \n"); token != NULL; token = strtok(NULL, " \n")) {
ESTitleId titleId;
int removable;
errno = 0;
titleId = strtoull(token, NULL, 16);
if (errno != 0 || (u32)ES_TITLE_TYPE(titleId) == 1) {
continue;
}
removable = _CNTCACHEIsTitleRemovable(titleId);
if (removable == 1) {
ES_DeleteTitle(titleId);
} else if (removable == 0) {
ES_DeleteTitleContent(titleId);
}
}
}

View File

@@ -1,33 +0,0 @@
# opus-fa attempts
## libs/RVL_SDK/src/fa/driver/sd_drv (23/26 -> 26/26, linked)
### pfd_sddrv_finalize (4 -> 0)
- Evidence for volatile: target reloads `flags` straight after testing it (`lwz; rlwinm.; beq; lwz` with no store in between) and keeps the final state stores in source order. The previous rounds faked the reloads with const-pointer accessors.
- Fix: `volatile PFD_SDDRV_INFO g_pfd_sddrv_info;` (definition-level, lever 19: the struct is written from the SD insert/remove interrupt callbacks). The fake accessors `pfd_sddrv_flags/device/disk/drive` are removed and the fields read directly. The removal callback loses its `media_inserted == 0 &&` re-check, which only existed to force a reload. Every other function stays exact.
### pfd_sddrv_init (142 -> 0)
- Explicit `return 0;` in the already-initialized branch: 142 -> 26. MWCC then turned `disk != info.disk ? -44 : 0` into a branchless select. The target branches instead.
- if/else/eq/goto spellings of the same return: still branchless (26).
- `#pragma ppc_iro_level 0` around the function (lever 26): 26 -> 1. Only the null test was left: target `li r0,0; cmplw r3,r0`.
- `disk == NULL` (NULL is `((void*)0)`) under IRO 0: 1 -> 0. Without IRO 0, NULL gives cmpwi.
- Diagnostic only: optimization_level 1/2/3 and iro 1/2 did not help.
### pfd_sddrv_build_fat32_mbr_bpb (122 -> 0)
- Target leaves an unreachable `bl OSReport` without its argument after the inlined reserved-sector writer, and has no null check of the buffer. A mini test shows this exact remnant comes from an inline helper with no null check that returns 0, compiled under IRO 0.
- The reserved-sector helper is now written like its sibling `pfd_sddrv_store_fat32_fsi_buf` (no null check, `return 0`). The only caller passes `g_pfd_sddrv_buf`, so behaviour is unchanged. With IRO 0 around build_fat32: 122 -> 2.
- Last 2: the first write loads the sector before the device. A local `partition_start_sector` like the FAT16 builder: 14. `+ 0`, casts: 2. Fix: `static inline s32 pfd_sddrv_write_sector(u32 sector)` wrapping `ISD_WriteBlock(device, sector, g_pfd_sddrv_buf, 1)`, so the argument is evaluated before the device load: 0.
### Link
- Flipped to Matching. The first DOL had `addi r27/r28` swapped in physical_read/write. The cause was `ATTRIBUTE_ALIGN(32)` on `g_pfd_sddrv_buf`, which changes codegen, so it was dropped.
- Without a 32-aligned .bss object, every `g_pfd_sddrv_info` access moved by 0x10. The fix is `ATTRIBUTE_ALIGN(32)` on `g_pfd_sddev` (the IPC device storage) and on `g_event` (the IPC event word, which the target places at .sbss+0x20).
- DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d OK.
## libs/RVL_SDK/src/fa/pdm_partition: pdm_part_is_master_boot_sector (start 84 in repo / 21 in opus-vf best -> best 19, not exact)
Remaining difference: the byte-load schedule of the inlined LE32 read. The target builds the tree (b2<<16 + b0) + (b3<<24 + b1<<8) and loads b3, b2, b0, b1. Ours loads b3, b2, b1, b0.
- mwdbg: our pre-RA scheduler already emits b1 before b0, so b1 has a higher priority. In the target, b1 shares b3's register, which proves its load comes after the b3 shift in the pre-RA order. So the target DAG or the initial order differs, and it is not a register tie.
- Mini-file study (/tmp/opus-fa/perm*.py): MWCC reassociates a 4-term add chain into pairs (L0+L2),(L1+L3) in source operand order. No permutation or parenthesization of the 4 terms gives the target pairing together with the target load order. All 120 tried in the real function: best 19 (e.g. `b1<<8 + b0 + b2<<16 + b3<<24`). Saved as opus-fa.best.pdm_partition.c.
- Unrolled byte loops (+=, |=, Horner): 43-69. Loads before the zero store: 73 (the zero store is DCE'd). Reusing a local for start/count: 21. Removing the zero store: 73. Count read first: 88.
- buf indexing instead of `buf += 16`: 90-91. Partition-entry pointer: 69.
- Helper boundaries (local for b0, u8/u32 parameter helper, two u16 halves, pointer to the field): 20-21.
- Pragmas (diagnostic): iro 0/1: 37 (25 with pointer loop 2, best 23 over all 120 sum shapes). scheduling off: 77. IRO is not the lever here.

View File

@@ -1,96 +0,0 @@
# opus-game attempts (worktree sol-high, base origin/main 77cf3598)
Units: iplCardSequence, odh, tiInputForm, tiCandidateBox. Diff counts are odiff.py (differing / total).
## tiCandidateBox
### create (278/356, size 0x590 vs 0x580) -> EXACT 0/352
Evidence: target addresses every pane-name string directly off the .data base
(r30+0x6a8, +0x6b4, +0x6c0, ...). Ours CSE'd `scPaneNameTable` and
`&scCandidatePaneData` into sub-bases (+0x28, +0x6b4). In the inlined
UIButton::Create the target holds both name args in saved registers instead of
rematerializing the address, which is how MWCC treats string-literal args.
1. Pass scroll/window names directly, no paneNames locals: 268/353.
2. Split scPaneNameTable into separate char arrays: 278/352 (equal size, sub-bases remain).
3. Names as string literals (B_OffBtn ... P_prdc_scrl_Rght): literals emitted after the
named globals, in the target's order; 287/354.
4. Also W_predictWindow, N_predictInput, W_OnOff_Area, N_prdc_Texts and the
"P_OffBtn" tail of scCandidatePaneData as literals: 0/352, .data bytes identical.
symbols.txt: scCandidatePaneData size 0x68C -> 0x680; scPaneNameTable and the four
named strings replaced by local literal labels at the same addresses. Total data
unchanged; unit data 100%; DOL SHA1 unchanged.
### createAnmPane_ (64/216)
mwdbg trace + regsim (127/127 reproduced). Named locals colored in reverse
declaration order; `animationCount` cannot reach r31 by order (regsim 0/1).
1. Loop bound `j < p.count` (count becomes a compiler temp -> r31): 86/216 but count now r31.
2. Declare forceAddName, i at top; p, pane in loop; j in for: 41/216. All named locals match;
left: animation-address temp r30 vs r23 and the hoisted constant temps shifted by one.
3. `p.pAnims[j]` at each use instead of the reference: 149/220 (reloads). Reverted.
4. forceAddName declared in the loop: 82/216. Reverted.
5. Pointer to slot `const AnimationFile* const* animation = &p.pAnims[j]`: 41 (no change). Reverted.
6. `animations = p.pAnims` hoisted, `animations[j]`: 86. Reverted.
Retrace after step 2: named locals all match; the only mismatch is the unnamed
animation-address temp (ours r30, target r23), numbered after the LICM constant temps.
Declaration order cannot move it. Kept steps 1-2 (64 -> 41) in the create commit.
## tiInputForm (best: opus-game.best.tiInputForm.diff, apply with patch -p0)
### create (153/356)
Register-blind diff showed one structural spot: target evaluates the
`getLanguageTextPane() ? textBox : "T_2l_TextBox"` name before loading mpLayout.
1. Name hoisted into a local before FindPaneByName: 153 (MWCC still loads mpLayout first).
2. Use the existing `selectInputTextName(*this, mpLanguageData)` helper (moved above create):
146/356, now register-only (register-blind diff identical). Unit still 219/221, data 100%.
3. Drop `count` local (loop bound `button.count`): 179, count not hoisted here. Reverted.
mwdbg + regsim on step 2: reproduces 138/138; best 7/10 wanted registers with named
locals only and 7/10 even with temps. Structural: target puts LICM constants (li 0, lis
vtable) in r20/r21/r31 between named locals. Not fixable by declaration order.
### calcCursorPos (43/326)
FPR tie plus scheduling. scale.x/scale.y FPRs swapped (ours x=f31, target x=f30); the
SRA'd fields are numbered by first use.
1. GetHeight() instead of bottom-top: 43 (no change).
2. Compute `right` before `lineBottom`: 41, scale FPRs match, but schedule order flips
(target computes the height product first) and fuzzy drops 93.05 -> 93.03. Not kept.
3. Named scaleX/scaleY locals: 235. Reverted.
## iplCardSequence (best: opus-game.best.iplCardSequence.diff, apply with patch -p0)
### loadCardFileIcons (436/512, 0x7f4 vs 0x800) -> best 406/512 (91.34% -> 93.34%)
Register-blind structural diff lines 41 -> 28.
1. `hasTlut = FALSE` initialized with the other counters before the speed loop: 419.
2. No-icon branch: store unk_0x01 before `iconImageSize = 0`: 408.
3. iconCount declared after the unk_0x02 store: 408 (struct 36).
4. `goto closeFile` -> `return result` (target's `bge; b epilogue` pairs, result stays in r3): 406, struct 28.
5. Tail `if (result < 0) return result;` instead of closeFile/closeFileSuccess labels: 406 (same, cleaner).
Tried without gain: iconCount u32/int, icon u32, `iconOffset[icon + 1]` (worse),
NONE-case spellings (array copy with [iconCount - 1], `(&...)[-1]`, `+ iconCount`, paletteSize after pointer).
Evidence for the rest: the target never sets paletteSize on the switch default path (r6 is
not initialized before the loop; default jumps straight to the iconCount < 7 test), so the
original read a stale paletteSize for format 3. Dropping the default assignment gives 404
and size 508, but that is an uninitialized read, so not kept. Remaining structure: NONE case
pointer formed as sThread + (iconCount + slot/file offset + 0x10000 - 0x6fb4), and
iconOffset[iconCount + 1] computed as ((iconCount + 1) << 2) without folding into +4.
### cardThreadMain (78/301)
mwdbg + regsim: reproduces 109/109; 9/9 wanted only with @-temps interleaved, 7/9 with
named locals only. One structural spot: the validity reply. Target copies command (mr r4, r19)
then rlwimi from validState (r25); ours coalesces the reply with command and inserts the
hoisted constant 1 (r29). PCode: `mr r72, r40; rlwimi r72, r71` with r71 the hoisted const;
r40 -> r72 coalesced because command dies there.
Tried: OR-expression reply (const-folds to ori 0x100: 261), mask-and-or (77), named
OSMessage local (78), validState BOOL/u8 (79/78), helper param u8/BOOL, command u8 (78).
## odh
### LineConv11 (12/146)
mwdbg + regsim: 77/77 reproduced; best 6/10 wanted (pixelSource r29, hi byte r8,
pixel r25, RGBA8 pointer r30) -> structural register tie. Plus lfs f7 / lis 0x4330 order.
Tried: split pointer add (15), &source[...] (12), operand order of the pointer sum (12),
pixel assembled from [0] first (12).
### huffmanDecoder (171/306)
Traced only. Target keeps sourceCursor in a volatile reg (r12) and bitOffset in r31; ours
the reverse, from the decomp's reuse of bitIndex/tableIndex/bitCountAndMask for several
values. Not attempted further this round.

View File

@@ -1,36 +0,0 @@
# opus-iro attempts
## Part A: function-scoped ppc_iro_level
| unit | function | before | change | after |
|------|----------|--------|--------|-------|
| sdChannelSelect/iplSDChannelSelect | create | 39/146 | `ppc_iro_level 0` around the function | 0/146 |
| sdChannelSelect/iplSDChannelSelect | flushSaveDataAndMountSD | 2/35 | `ppc_iro_level 0` | 0/35 |
| sdChannelTitle/iplSDChannelTitle | iplSDChannelTitle_flushSaveBeforeExit | 6/37 | `ppc_iro_level 0`; dropped the `saveHeap` temporary | 0/37 |
| setting/iplSetting | scanAP | 4/272 | `ppc_iro_level 1` (level 0 not exact per sweep); dropped `animationIndex` temporaries in cases 6/7 | 0/272 |
Other functions in each unit unchanged (per-function diff before/after). Pools identical.
- iplSetting: every function exact; flipped to Matching, full build DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d.
- iplSDChannelTitle: every .text function exact, but flipping to Matching breaks the DOL (0x40 shift).
Object .text is 0x4b48 vs target 0x48c0 and .data 0x65c vs 0x6a0, so the unit emits extra code and
misses data that objdiff's per-symbol view does not show. Left NonMatching.
- iplSDChannelSelect: 4 functions still non-exact; stays NonMatching.
## Part B: asm placeholders under ppc_iro_level
| function | candidate | default (3) | level 0 | level 1 | level 2 |
|----------|-----------|-------------|---------|---------|---------|
| Manager::doUpdateChanInfos | plain `mData.chanInfo[page][index]` form, `n` local | 62/68 | 7/67 | 7/67 | 66/71 |
| Manager::doUpdateChanInfos | swap `!=` operands | - | 7/67 | | |
| Manager::doUpdateChanInfos | inline `titleIds[index + page * 12]`, no `n` | - | 7/67 | | |
| Manager::doUpdateChanInfos | `int n` hoisted to function scope | - | 7/67 | | |
| Manager::doUpdateChanInfos | `ESTitleId* titleId = &titleIds[n]` | - | 7/67 | | |
| Manager::doUpdateChanInfos | `ESTitleId titleId = titleIds[n]` value local | - | 48/67 | | |
| Manager::doUpdateChanInfos | `ESTitleId titleId = ES_TITLE_ID(stored)` before `n` (same shape as makePriorTitleIDList) | - | **0/67** | | |
| Manager::hasChannel | rx30 has-00 (best C) | 14/71 | 29/71 | 29/71 | 29/71 |
| getTitleName | grok-title best C | 4/71 | 82/88 | 82/88 | 56/71 |
doUpdateChanInfos converted to C under `ppc_iro_level 0`; the remaining 7 register diffs came from the order the
stored title and the input title were evaluated. hasChannel and getTitleName have strength-reduced, hoisted
IRO-on codegen in the target (mtctr loop, hoisted name stride), so lowering IRO makes them worse; both stay asm.

View File

@@ -1,41 +0,0 @@
# opus-mwdbg: unblocking mwdbg for large C++ units, and regsim verdicts (base d9d33ca0)
These are tool changes only. No source file in this worktree was edited. The tool changes are in `_mwdbg` (see its README section "Emulator limits, sjiswrap, and the socket stub").
## Why mwdbg stopped (follow-up to opus-ties.attempts.md)
1. The 1 MB stack overflowed. The emulator now reads `RETROWIN32_MEMORY_MB` and `RETROWIN32_MIN_STACK_MB`, and mwdbg.py sets them to 1024 and 32 by default (`--memory-mb`, `--stack-mb`).
2. `ws2_32!send` was missing. I added a builtin ws2_32 that logs every call to `<capture>/socket.log`. With that log, the message turned out to be `(10430) system does not support converting from 'SHIFT-JIS', treating as ASCII`. Afterwards the compiler longjmps through an empty jmp_buf (`WRITE_UNMAPPED @40495a`, esp 0).
3. The cause of that message: mwdbg drops `wibo sjiswrap.exe` from the Ninja command, so the compiler read UTF-8 sources directly and could not convert them. retrowin32 now emulates sjiswrap when `RETROWIN32_SJISWRAP=1`, and mwdbg.py turns it on automatically when the Ninja command uses sjiswrap. The emulation re-encodes source files to Shift JIS, makes `GetACP` return 932, has `IsValidCodePage(932)` succeed, and decodes code pages 0 and 932 in MultiByteToWideChar.
4. Then iplESMisc failed with `(10151) the file 'nw4r/lyt/textbox.h' cannot be opened`. The file on disk is `textBox.h`, and wibo matches paths case-insensitively. retrowin32 now falls back to a case-insensitive match when the exact path is missing.
5. regsim reproduced the iplESMisc capture only 157/161. The capture needed a second pass with a spill candidate, and regsim picked the spill node by maximum degree. MWCC picks by minimum `cost/degree`, with ties going to the later node in scan order. After fixing that, the capture reproduces 161/161, and `examples/pressure` goes from 108/126 to 126/126. None of the other 76 stored runs changed.
## Validation (data-d4, build/43U objects rebuilt before comparing)
| capture | regsim | unit.o vs ninja object |
|---|---|---|
| kbd_lib / kbdProcMod | 156/156 | identical (sha256 6a85c207…) |
| iplESMisc / DeleteUnauthorizedData__Q33ipl7utility6ESMiscFPQ23EGG4Heap | 161/161 (2 GPR passes) | identical (8a31efdb…) |
| tiZiString / update__Q39textinput8tistring6WithZiFv | 161/161 | identical (da68c526…) |
| www_wiisetting / Getter___Q23www10wiisettingFP14WWWJSPluginObjPCcP16WWWJSPluginValue | 312/312 | identical (ff8f136d…) |
## Verdicts
Method: `_mwdbg/scratch_opusmwdbg/vmap2.py` builds the want-list. It aligns the scheduled PCode with our object using difflib, because opus-ties.vmap.py's index alignment drifted and left 210 operand mismatches on tiZiString. Each want is keyed by virtual number, since names such as `candidate`, `output` and `i` repeat. A virtual is kept when at least 75% of its uses agree on one target register. `_mwdbg/scratch_opusmwdbg/regsim_locals.py` then anneals over the numbering of real source locals only, leaving `@` temps, parameters and unnamed values in place. For www_wiisetting I enumerated every ordering of its 8 locals instead.
| function | wants | as built | best with source locals reordered | best with `@` values reordered too | verdict |
|---|---|---|---|---|---|
| DeleteUnauthorizedData | 64 | 54 | 60 | 64 | structural |
| WithZi::update | 98 | 83 | 92 | 98 | structural (callee-saved part fixable by order) |
| wiisetting::Getter_ | 159 | 156 | 156 (exhaustive, 8! orders) | not needed | structural |
- **DeleteUnauthorizedData** is `return InitSavedata(heap);`. Every mismatched value is a local of an inlined function, which is why they all have `@` names.
- InitSavedata: v33 `titleIds`, v34 `ret`, v35 `ticketScratch`, v36 `i`.
- verifySavedataZD: v37/38 `titleId` parameter (hi/lo), v39/40 `block`, v41 `valid`, v42 `j`, v43 `offset`, v44 `deleteSaveData`, v45 `fileOpen`, v46 `saveData`, v47 `ret`.
- DeleteTicketsForce: v49/50 `titleId`, v51 `j`, v52 `ret`, v53 `ticketViewList`.
Reordering locals inside each inlinee reaches 60/64. That search was exhaustive over InitSavedata × DeleteTicketsForce and annealed over verifySavedataZD. The four misses are `titleId` v37/v38 (wants r19/r20) against `saveData`/`deleteSaveData` (want r30/r31). Reaching 64/64 requires numbering the inlined `titleId` parameter after verifySavedataZD's locals, and declaration order can't do that. A possible lever, still untested: copy `titleId` into a local in verifySavedataZD that is declared last, or change how titleId is passed.
- **WithZi::update**: reordering locals fixes the 9 callee-saved mismatches (index, destination, source, length v44, count, elementCount, v64, v70, v175). The order regsim found, lowest number first: index, character, length(v37), position, keyIndex, source, copied, wordLength, elementCount, count, candidate(v34), output(v38), candidate(v47), length(v44), destination, candidateOutput, output(v49), output(v36). It is untested and may conflict with nested scopes.
Six volatile-register misses remain: copied r4→r5, wordLength r7→r4, @1343 r6→r7, @1338 r5→r4, @1330 r5→r6, v148 r5→r4. @1343/@1341, @1338/@1336 and @1349 are the induction pointers of the 8-way unrolled copy loop, and @1330 is `length-8`. All of these are optimizer temps. They reach 98/98 only when the temps are renumbered, so this is structural, and it needs a loop shape that makes the unroller create its temps in a different order.
- **wiisetting::Getter_**: no ordering of the 8 locals (str, val, i ×3, kbLang, staIdx, retVal) improves on 156/159. The misses are `i`(v35) r25→r31, `i`(v38) r25→r26 and temp `@17419`(v42) r26→r25. This confirms opus-ties' result that swapping `strBuf`/`i` changes nothing, so the function is structural.

View File

@@ -1,41 +0,0 @@
# opus-novt: per-TU novtable switches
Method: full `ninja`, then SHA1 of all 1027 `build/43U/src/**/*.o` compared with a
baseline from origin/main ca98b14a, plus the DOL SHA1. A variant is kept only if
no object changes.
| # | Change | Result |
|---|--------|--------|
| 1 | `LangFile`/`LayoutFile`: out-of-line virtuals for everyone | iplChannelTitle.o, iplSDChannelTitle.o change, DOL changes. Both TUs need weak copies of `~LangFile` (88), `read` (4), `checkData` (8), `isFinished` (8), `isFatalError` (8), `~LayoutFile` (92) and weak `__vt__LangFile`/`__vt__LayoutFile`. |
| 2 | `LangFile`/`LayoutFile`: inline stub virtuals for everyone | iplNand.cpp fails (redefinition of the real bodies); 46 other objects gain weak copies. |
| 3 | `MemoryBase`: drop the `IPL_CHANNEL_TITLE_NOVTABLE` novtable switch | no object changes. **Kept.** |
| 4 | primary `HermiteIntp` under the macro: drop `__declspec(novtable)` | no object changes. **Kept.** |
| 5 | `HermiteIntp` macro block disabled for everyone (`#if 0`) | iplChannelTitle.o, iplSDChannelTitle.o change. |
| 6 | `HermiteIntp` macro block enabled for everyone (`#if 1`) | ~50 objects change. |
| 7 | `gui::Interface` novtable for everyone | ~20 objects change (saveDataEdit, sdButton, setting, dialog window, ...). |
| 8 | `gui::Interface` never novtable | iplGCSaveData.o, iplMemoryCard.o gain an unused UNDEF `__vt__Q23gui9Interface` (code/data bytes same). |
| 9 | `~gui::Interface` always inline | iplGCSaveData.o, iplMemoryCard.o gain a weak 64-byte `~Interface`. |
| 10 | `gui::EventHandler` never novtable | iplGCSaveData.o, iplGCWindow.o, iplMemoryCard.o change, DOL changes. |
| 11 | `gui::EventHandler` always novtable | ~20 objects change. |
| 12 | `ipl::gui::PaneManager` dtor always inline | iplGCSaveData.o, iplMemoryCard.o change, DOL changes. |
| 13 | `MemCardEventListener`: drop its (already unconditional) novtable | iplGCWindow.o changes. Already consistent; left as is. |
## Result
Removed the two dead pieces (3, 4). All 1027 objects and the DOL are unchanged.
Switches that stay, and why:
- `IPL_CHANNEL_TITLE_NOVTABLE` in `iplNand.h`: the channel-title TUs must emit
weak stub copies of the `LangFile`/`LayoutFile` virtuals, which have real
out-of-line bodies in iplNand.cpp. No single declaration gives both (1, 2).
The macro no longer adds any `novtable`; its name is historical.
- `IPL_CHANNEL_TITLE_NOVTABLE` in `iplInterporation.h`: it selects a different
`HermiteIntp` primary template (FrameController base, out-of-line `init`,
`HermiteIntp<f32>` specialization, `dont_instantiate`). The same header also
has `IPL_CHANNEL_SELECT_CPP` / `IPL_SD_CHANNEL_SELECT_CPP` /
`IPL_SD_CHANNEL_TITLE_CPP` variants, so untangling it is a separate job (5, 6).
- `IPL_GC_SAVEDATA_NOVTABLE` / `IPL_MEMORY_CARD_NOVTABLE` / `IPL_GC_WINDOW_NOVTABLE`
in `GUIManager.h` and `iplGuiManager.h`: the memory-card TUs need novtable
`Interface`/`EventHandler` and out-of-line `~Interface`/`~PaneManager`, while
every other GUI user needs the opposite (7-12).

View File

@@ -1,68 +0,0 @@
# opus-odh attempts (src/system/odh)
Worktree data-d6, branch agent/w1009/o-odh from origin/main 72e9c8d6. Read opus-common.md, sol-r4 and
sol-m2 logs, effort-policy entries, levers.md, the mwdbg README and the allocator reference.
Baseline: LineConv11 12/146, huffmanDecoder 171/306, unit 26/28 exact, pool identical.
## combosweep (run first)
- main source: LineConv11 12 -> 12, huffmanDecoder 171 -> 166 (opt_propagation off). No exact.
- sol-m2 seed: LineConv11 6 -> 6, huffmanDecoder 114 -> 114. No exact.
## LineConv11: EXACT
mwdbg capture of the seed: inside the loop r8 is the only free volatile GPR, so every other temp takes a
saved register and the lowest claimed one wins. The packed RGB565 word (v68) was colored before the
high byte (v66) and took r8. The target needs the high byte on r8, the pointer on r29, and the packed word
colored after cbValue claims r25. So the packed word has to be a named local numbered below cbValue.
Petari's matching SMG source (SMGCommunity/Petari src/Game/Screen/odh.cpp, read-only) does exactly that:
cbValue/crValue are declared with red/green/blue before the format chain, and `pixel` is built high byte
first (`pixel = src[o]; pixel <<= 8; pixel |= src[o + 1];`) inside the RGB565 block. Ported as-is with
this file's names: LineConv11 0/146, ctxdiff diffs 0, pool identical, no other function changes.
Lever isolation (each from the exact version):
- cbValue/crValue declared at their assignment instead: 5 diffs.
- pixel low byte first (`pixel = src[o + 1]; pixel |= src[o] << 8`): 6 diffs.
- pixel as one expression `(src[o] << 8) | src[o + 1]`: 6 diffs.
- planeSize indexing instead of cbSource/crSource pointers: 0 (either form works).
## huffmanDecoder: EXACT
Started from a fresh natural rewrite (early returns, `length`/`tableIndex`/`category` names, Petari-style
tree walks) instead of the Ghidra-shaped seed: 170 diffs, same 306 instructions. Structural fixes first:
- `coefficient = 1` before the first refill loop (the target sets it in the DC block): 163.
- DC leaf through a named `leafIndex` (target keeps `(idx + off + 1) * 2` + lhzx only in the DC walk).
- `length = 1;` before `tableIndex = 0;` in every walk (li order): 139, 0 structural left.
Then allocator work with mwdbg + a per-vreg want list built by aligning backend-04 PCode with the target
object (/tmp/opus-odh-want.py), and an annealer over the numbering (/tmp/opus-odh-anneal.py):
- A full renumbering (temps included) reached 1 miss and showed both maxLength values must be colored
after their walk temps, i.e. behave as codegen temps. `maxLength = component == 0 ? 9 : 11;` gets
copy-propagated into the ternary temp: 139 -> 80.
- `dc` must be colored before the predictor-index temp, so no named `dc`:
`coefficientOutput[0] = value + *pred; *pred = coefficientOutput[0];` (store forwarded, no reload): 68.
- AC tail: target creates the store address before `length + category`:
`coefficientOutput[coefficient++] = value; bitOffset += length + category;`: 66.
- Remaining misses were named-local order only. Simulator: declare sourceCursor, bitOffset, coefficient,
category before bytesConsumed (sourceCursor colors first and takes r12, bitOffset claims r31, then
coefficient r30, category r29, bytesConsumed r28). C89 declarations at the top of the function: 9.
- Last 9: the run walk needs `branch` numbered above `node` (declared first). Per-walk C89 blocks
`u32 branch; u16 node;` then assignments: 0. Only the run walk needs it; using it in all three walks
is also exact, so the final source is uniform.
Checked and rejected along the way: function-scope shared node/branch (always 9, any position);
`value += *pred` (80); chained assignment for the predictor works (68) but the two-statement form reads
better. maxLength/value/mask/leafIndex/run/i can sit anywhere in the top declaration list.
Final: huffmanDecoder 0/306, ctxdiff diffs 0, pool identical, unit 28/28, code 14684/14684, data 6360/6360.
## Link
Flipped system/odh.cpp to Matching. ODHEncodeRGBA8/ODHEncodeY8U8V8/ODHDecodeY8U8V8 are in the source but
not in the split target (unreferenced, dead-stripped); the link output is unchanged.
Full build: main.dol SHA1 26116613f624061ba99c8d1a299aaa6efa85670d, "system/odh.cpp: linked True".
Gate (`gate.py src/system/odh --quick`): GATE PASS, 28/28 instruction-exact, linked code 14684,
0 regressions, 0 forbidden patterns, 0 readability warnings. Global matched code 98.14728 -> 98.20765.

View File

@@ -1,116 +0,0 @@
# opus-ph attempts
Branch agent/w1008/data-d3-c. Measure: `odiff.py <unit> <symbol>` differing count.
## TMCJPEGDEC_err_restart
Start: rx5b finishRestart candidate (114/115 insns, odiff 73 differing because of the 1-insn shift).
Key finding: mwdbg backend-00 shows the marker test is already folded (`bt gt -> loop`) in the
initial PCode, so the target's `ble found; b loop` is decided before the backend. In matched
code (`__OSInitNet`) the same unfolded shape comes from `if (a || b) return;`, i.e. a jump the
IR folder does not treat as a goto.
- v0 rx5b baseline: 73/115 (114 insns).
- A `if (m>=D0 && m<=D7) break;` + finish after loop: 73.
- B `if (m>=D0 && m<=D7) return finish;`: 73.
- C `if (m<D0 || m>D7) continue; return finish;`: 73.
- E nested `if (m>=D0) { if (m<=D7) return finish; }`: 73.
- H `goto found` after loop: 73.
- I empty-then / else return: 73.
- D1 `{ result = 0; continue; }`: 73. D2 else-arm assignment: 73. D3 continue/else break: 73.
- W1 do/while(byte<D0||byte>D7) using byte: 73. W2 byte instead of marker: 73.
- W3 marker as loop-carried while condition: 98/118.
- E1 else-if chain: 73. E2 inverted D9 test: 81. E3 inverted D9 inner test + break: 76.
- G1 `goto retry` label before inner while: 73.
- P1/P2/P3 isRestartMarker inline predicate (3 shapes x 2 uses): 76-78, 118-119 insns.
- S1 `switch (marker) { case 0xD0..0xD7: return finish; }`: 21/115, size equal. Switch
lowering emits the unfolded `bge case; b default`, but as signed `cmpwi d8; bge; cmpwi d0`
instead of target `cmplwi d0; blt; cmplwi d7; ble; b`. Marker lands in r4 not r6.
- S2 switch on (u32): 21. S3 default: continue: 21. S4 default: break: 21.
- S5/S6/S7 marker as u32/s32/u16 with switch: 21 (switch compares stay signed).
Result: not exact. Best is S1 (equal size, 21 differing). Remaining: switch compares are signed
and use a different tree (hi+1 then lo); marker gets r4 instead of r6, which shifts the finish
block's temporaries. Next lever: a construct whose jump the IR folder leaves alone (like the
`return` in `__OSInitNet`) but keeps the unsigned `cmplwi d0 / blt / cmplwi d7 / ble` order.
## getUnScrambleId
Start: rx30 id-08 (loop + inline helpers). That source is now auto-inlined into both C callers
(target keeps it out of line), so loop forms are out; the function must be written unrolled.
Metric below is (insns, exact positional, opcode positional) out of 161.
- u1 unrolled inline get/set/unscramble helpers: 156 differing.
- m1 macros GET_BYTE/SET_BYTE/UNSCRAMBLE, lazy permutation: 159 differing; multiset differs
only by two rlwimi shift-combines (b2/b3 read from rotated hi in target).
- x1 read all six bytes into b0..b5 first, then set: 111 differing.
- x1 extraction orders (4) / declaration order: 111-112.
- xf/xg `(x >> 1) | ((x & 1) << 52)` rotation: b2/b3 match but b1/b4/b5 stop combining; 113.
- greedy over GET/SET/UNSCRAMBLE/rotation/mask/permutation/substitution/final forms (24 builds):
best r2 (`mixId |= (mixId & 1) << 53; mixId >>= 1;`) + t2 (substitution via `b` temp): 69.
- p3 copy + `b = GET_BYTE(copy, k); mixId = SET_BYTE(mixId, i, b);`: 68 (prologue and rotation
now exact; b3 combine matches).
- greedy from p3 over all dims + declaration orders (≈30 builds): no gain.
- SET split into &=/|= (3 variants): 162-166 insns. inline get/set helpers: 161-163, ≤93 exact.
- b as u32/int/u16/s32: 164-175 insns. GET without cast / const shift / u64 cast: unchanged.
- SET mask spellings, (u8) value cast, assignment-macro, block-scoped/const copy: unchanged.
- per-pair inline GET in SET for subsets of the six moves: worse.
- distinct b0..b5 lazily: 156. separate perm/subst temps: 163 insns.
- 160 spellings of the mask/xor/rotate statements: all identical (IR canonicalizes).
Finding: mwdbg backend-00 shows MWCC splits this straight-line function into ~100-instruction
blocks at statement ends (B1 ends after `b = GET_BYTE(copy, 2)` at 103; before it 97). Combines
and scheduling are block-local. The target splits one statement earlier (b2/b3 both read the
uncombined rotated hi), so the original has 1-6 more initial PCode instructions before set 3.
No natural spelling found that adds them without changing final code.
Best: 161/161, 68 differing (93 exact positional), saved in opus-ph.best.c.
## Round 2 (higher effort)
### getUnScrambleId: exact
- u1 substitution as a `for (i = 0; i < 6; i++)` loop over GET/SET: 68 (identical to the unrolled form;
MWCC fully unrolls it, so loop source is fine as long as the function stays out of line).
- final step spellings: `return (rot) ^ B3` 61 (tail exact), operand swap 67, copy temp 68, split 80.
- copies/temps at the start (id_direct, copyfirst, idcopy, block-scoped inst temp): 68, IR propagates them.
- inline u8 getByte for the permutation only: 156 (different prologue allocation).
- permutation statement orders (source order, reversed): 148-159.
- prior art: `gh search code getUnScrambleId` found SMGCommunity/Petari src/RVL_SDK/nwc24/NWC24UserId.c
(same SDK, same 0x284 size in SMG). Its shape: static `getbyte`/`setbyte` helpers (auto-inlined), a
`static const u8 ExcTable[8] = {1, 5, 0, 4, 2, 3, 6, 7}` permutation table read in a `u8 i` loop,
a second loop for the TtableInv substitution, rotation spelled `v |= (((v & 0xFF) << 5) & 0x20) << 48`.
Compiled as is: 0/161. Unrolling the ExcTable loop by hand gives 159/163, so the table loop is what
shapes the PCode blocks. ExcTable lands in .sdata2 of the object (constant-folded after unrolling,
never referenced) and the linker dead-strips it: main.dol SHA1 unchanged, gate data 16/16.
- Final: renamed to repo style (getByte/setByte/copy/id), still 0/161; NWC24CheckUserId and
NWC24iCheckUserIdCRC stay 0. gate.py --quick: GATE PASS.
### TMCJPEGDEC_err_restart: not exact (best stays S1, 21/115, equal size)
Standalone harness (/tmp, same flags, `-ipa file`) to test the range-test shape. Target wants
`cmplwi d0; blt test; cmplwi d7; ble F; b test` (unsigned, unfolded).
- switch lowering is always signed and hi-first (`cmpwi hi+1; bge def; cmpwi lo; bge case; b def`),
for u8, u32, `unsigned long`, `(u32)` casts, `m - 0xD0` with cases 0..7, `(u8)(m - 0xD0)`, and even
case values >= 0x80000000. So the target is not a switch.
- if-forms all fold to `bgt test` (≈45 shapes): &&/|| in either direction, continue/break/goto
found/goto label, do-while with `||` or `!(&&)`, else-if chains, nested ifs, empty then, else
continue, flag loops (`found`, `keepGoing` style as in parse_para), ternary conditions,
`(u32)(m - 0xD0) <= 7`, `(m & 0xF8) == 0xD0`, the whole loop inside a static inline.
- `{ r = 0; continue; }`, `{ m = 0; continue; }`, `{ nop(); continue; }`, `{ (void)0; continue; }`:
still folded (IR removes the dead statement before folding).
- IRO 0 around the function (levers.md 26): no change (21 / 73). Target shows no IRO-off symptoms.
- inline predicates with `return` (`if (m < D0 || m > D7) return 0; return 1;`) give the unfolded
`ble` but materialize a bool (`li r0,0/1; cmpwi; beq`) that the target lacks.
- Scan of all compiled C objects: unfolded backward `bc +8; b back` appears only in switch lowering
(NHTTP) and inline-function exits (VF Advance/MoveTo); in retail, err_restart is the only
`cmplwi lo; blt; cmplwi hi; ble +8; b back` in the DOL.
- Mechanism found (t13): a then-arm with a surviving non-jump statement, e.g.
`if (m < 0xD0 || m > 0xD7) { last = r; continue; }`, gives exactly `blt X; cmplwi d7; ble F;
X: mr; b top`. The target matches this if that statement is a register copy that coalesces away
after the IR fold (same as tolower's empty ternary arm in MSL stricmp). No natural loop-carried
register variable exists in this function to carry such a copy (byte is address-taken, result/
marker are dead on that path), so not adopted.
- upstream koopthekoopa C (read-only) is the same nonmatching shape as our #else branch.
Next lever: find what loop-carried value the original kept in a register on the "other marker" path
(the copy that vanished), e.g. a marker/previous-marker variable or a result carried to the EOI return.

View File

@@ -1,143 +0,0 @@
/* opus-ph best C. Not exact; the retail asm stays in the source. */
/* libs/RevoEX/src/nwc24/NWC24UserId.c getUnScrambleId: 161/161 insns, odiff 68 differing (prior best 97). */
#define GET_BYTE(id, n) ((u8)((id) >> ((n) * 8)))
#define SET_BYTE(id, n, b) (((id) & ~((u64)0xFF << ((n) * 8))) | ((u64)(b) << ((n) * 8)))
#define UNSCRAMBLE(b) ((u8)((TtableInv[(b) >> 4] << 4) | TtableInv[(b) & 0xF]))
static NWC24UserId getUnScrambleId(NWC24UserId id) {
u64 mixId;
u64 copy;
u8 b;
mixId = id;
mixId &= 0x001FFFFFFFFFFFFFULL;
mixId ^= 0x00005E5E5E5E5E5EULL;
mixId &= 0x001FFFFFFFFFFFFFULL;
mixId |= (mixId & 1) << 53;
mixId >>= 1;
copy = mixId;
b = GET_BYTE(copy, 1);
mixId = SET_BYTE(mixId, 0, b);
b = GET_BYTE(copy, 5);
mixId = SET_BYTE(mixId, 1, b);
b = GET_BYTE(copy, 0);
mixId = SET_BYTE(mixId, 2, b);
b = GET_BYTE(copy, 4);
mixId = SET_BYTE(mixId, 3, b);
b = GET_BYTE(copy, 2);
mixId = SET_BYTE(mixId, 4, b);
b = GET_BYTE(copy, 3);
mixId = SET_BYTE(mixId, 5, b);
b = GET_BYTE(mixId, 0);
mixId = SET_BYTE(mixId, 0, UNSCRAMBLE(b));
b = GET_BYTE(mixId, 1);
mixId = SET_BYTE(mixId, 1, UNSCRAMBLE(b));
b = GET_BYTE(mixId, 2);
mixId = SET_BYTE(mixId, 2, UNSCRAMBLE(b));
b = GET_BYTE(mixId, 3);
mixId = SET_BYTE(mixId, 3, UNSCRAMBLE(b));
b = GET_BYTE(mixId, 4);
mixId = SET_BYTE(mixId, 4, UNSCRAMBLE(b));
b = GET_BYTE(mixId, 5);
mixId = SET_BYTE(mixId, 5, UNSCRAMBLE(b));
mixId = ((mixId & 0x7FFFFFFFFFFULL) << 10) | ((mixId >> 43) & 0x3FF);
mixId ^= 0x0000B3B3B3B3B3B3ULL;
return mixId;
}
/* libs/RVLMiddleware/TMC_JPEG/src/jpegdec/jdec_main.c TMCJPEGDEC_err_restart: 115/115 insns, odiff 21 differing (prior 114/115). */
static inline s32 finishRestart(TMCCJPEGDecWork* work, TMCCJPEGDecState* state, u8 marker) {
u8 restartDistance;
s32 result;
s32 next;
u8 skipped;
s32 quotient;
s32 remainder;
u16 y;
u16 x;
u16 pitch;
u16 interval;
u32 position;
restartDistance = marker + 8 - (work->rstMarkerIdx + 0xCF);
if (marker > work->rstMarkerIdx + 0xCF) {
restartDistance = marker - (work->rstMarkerIdx + 0xCF);
}
pitch = state->maxX;
interval = work->restartInterval;
skipped = restartDistance * interval;
work->rstMarkerIdx = (marker + 1) & 7;
position = work->mcuPos;
next = (u8)position * pitch + (skipped + (position >> 16));
quotient = next / pitch;
remainder = next - quotient * pitch;
y = quotient;
work->mcuPos = ((u32)remainder << 16) + y;
x = remainder;
work->components.dcPredict[0] = 0;
work->components.dcPredict[1] = 0;
work->components.dcPredict[2] = 0;
work->components.dcPredict[3] = 0;
work->restartCnt = 0;
result = TMCJPEGDEC_init_buff(work);
if (result < 0) {
return result;
}
state->posX = x;
state->posY = y;
state->position = TMCJPEGDEC_get_position(work);
return state->result - state->posY * state->maxX - state->posX;
}
s32 TMCJPEGDEC_err_restart(TMCCJPEGDecWork* work) {
u8 byte;
TMCCJPEGDecState* state;
s32 result;
u8 marker;
state = work->pState;
if (work->scanCount == 1) {
state->decodeResult = 0;
return 0;
}
result = TMCJPEGDEC_rewind_ptr(work);
if (result < 0) {
return result;
}
byte = *work->pBufCur;
for (;;) {
while (byte != 0xFF) {
result = TMCJPEGDEC_get_byte(&byte, work);
if (result < 0) {
return result;
}
}
result = TMCJPEGDEC_get_byte(&byte, work);
marker = byte;
if (marker == 0xD9) {
if (result < 0 && result != TMCC_ERROR_UNDERFLOW) {
return result;
}
return 0;
}
if (result < 0) {
return result;
}
switch (marker) {
case 0xD0:
case 0xD1:
case 0xD2:
case 0xD3:
case 0xD4:
case 0xD5:
case 0xD6:
case 0xD7:
return finishRestart(work, state, marker);
}
}
}

View File

@@ -1,47 +0,0 @@
# opus-prior: makePriorTitleIDList__Q33ipl8savedata7ManagerFPUxPUxUl
Start: opus-sdm best (p1 below), 96 differing / 133, 122 instructions.
Measured with odiff (differing / total). Harness spliced each trial over the asm block.
## Cause
The target is exactly MWCC's code with IRO (the front-end optimizer) disabled for this function.
No CSE of `&titleIdsIn[i]` / `&titleIdsOut[outputIndex]`, no LICM of `outputIndex << 3`, and the
backend alone strength-reduces and hoists the constants. That's why every C spelling caches the addresses.
| # | Change | odiff |
|---|---|---|
| p1 | opus-sdm best | 96 |
| h1 | `*&titleId` in isEqualChannel | 96 |
| h2 | assign through pointer helper | 97 |
| h3 | titleId written through a local pointer | 96 |
| b | match handled by switch (-2/0, 1) | 95 |
| a | goto instead of continue | 96 |
| d1 | diag `#pragma opt_common_subs off` | 64 |
| d2 | diag `#pragma opt_loop_invariants off` | 120 |
| d3 | diag both | 24 |
| d4 | diag `#pragma global_optimizer off` | 148/150 |
| d5 | diag `#pragma ppc_iro_level 0` (or 1) | 24, 133 insns, register names only |
| t1 | diag statement `asm { nop }` in body (IRO DisableDueToAsm) | same shape as d5 + nop |
| q1 | d5 + outputIndex declared before titleId | 10 |
| **q2** | d5 + `int outputIndex;` at function top, assigned per slot | **0 (exact)** |
| s1 | no pragma, function-local static | 116 |
| s2 | no pragma, try/catch | build error (exceptions off) |
| s3 | no pragma, inlined nw4r::math::FAbs (asm inline) | 119 |
## Result
Exact only with `#pragma push / #pragma ppc_iro_level 0 / #pragma pop` around the function (q2, saved in
opus-prior.best.cpp). The brief forbids `#pragma`, so this is not landed. Upstream uses the same pragma for
the same symptom (`// uhh` before iplChannelManager.cpp loadMetaHeaderAsync, iplUtility.cpp
BScroller::set_arw_param; koopthekoopa ff68d54a / 25f93e26). No natural construct found that disables IRO
(MWCC disables it for functions containing an asm statement; none fits here). Orchestrator call: allow the
upstream-precedent pragma for this function, or park it.
## Round 2 (landing)
Orchestrator accepted the function-scoped `ppc_iro_level 0` push/pop as an exception (same convention as
iplChannelManager.cpp, iplUtility.cpp, iplBoard.cpp, iplChannelTitle.cpp). q2 replaces the asm placeholder;
odiff 0 / 133, size 0x214 both; all 35 functions in the unit 0 differing; pool identical. Inventory row
removed (checker flagged it stale once the asm was gone); header counts 171/173/162/9. opus-prior.best.cpp
deleted as obsolete. Gate: only forbidden pattern is the pragma (push, ppc_iro_level 0, pop).

View File

@@ -1,37 +0,0 @@
# opus-sdcs: iplSDChannelSelect collectTitles* (2026-10-08)
Start: ByUsage 4/101, FromNandUsage 4/102, ByChannelOrder 7/126, BySpecialChannels 16/361.
Shared diff: `lwz secondUsage[0]` scheduled above `stw ++*titleCount` in ours, after it in target.
- `*titleCount += 1`, `(*titleCount)++`, `titleCount[0]++`, `= *titleCount + 1`: no change (4).
- `!(a < b || c < d)`, nested ifs: no change. static inline usage predicate: 40 diffs.
- function-scoped IRO 0 / IRO 1: no change.
- casts `(s32*)secondUsage`, `const_cast`, `(s32*)(u32)`, local non-const copy (also under IRO 0): no change.
- mwdbg on a standalone repro: the load is hoisted before regalloc; loads through a pointer-to-const
PARAMETER are treated as unaffected by any store (casts do not remove it). Only a non-const
`s32*` parameter keeps source order: repro then matched the target byte for byte.
- The `PClPClPUxPcPUl` mangling was decomp-assigned (symbols.txt names were invented), so the
params become `s32*` and the 5 symbols are renamed to `FPlPlPUxPcPUl`.
=> ByUsage 0, FromNandUsage 0, BySpecialChannels 0, ByChannelOrder 3.
ByChannelOrder residual: `mulli r0/add r3,r17,r3` vs target `mulli r4/add r0,r17,r3`.
- if/else vs ternary, `getChannel`, `hasLoadedBnr`, row pointer, ref/ptr locals, idx/manager locals
in either order, inverted branch: 3-8 diffs.
- regsim: declaration order cannot reach (0/2), IRO temps @162/@164 for mgr/sum get low vreg numbers.
- inline Manager member with getTitleID's body (`getEntryTitleID(page, channelOrder[order])`): exact.
Result: 129/129 exact, gate PASS.
## Link (configure.py -> Matching)
First link: DOL SHA1 798af348..., .data 0x20 short and two swapped calls.
- objdiff missed that `draw` calls `ipl::math::VEC3(f,f,f)` and `getChannelPanePosition` calls
`nw4r::math::VEC3(f,f,f)`, because the two weak bodies are identical. Fixed the local in draw
and made getChannelPanePosition return `nw4r::math::VEC3` (NRVO builds it in the return slot,
and callers only read .x/.y).
- Target .data has 0x20 zero bytes (deduped weak vtables) before the anonymous handler vtables.
iplChannelSelect emits `HermiteIntp<VEC3>` and `Interporation<VEC3>` weak vtables at the same
spot. Dropped the SD-only full `HermiteIntp<VEC3>` specialization in iplInterporation.h so the
generic template (with the SD `get()` already there) is used: .data 0xab0, as in the target.
- Removing the unreferenced handleDeleteComplete/handleStorageCheckComplete: no DOL change (they
get dead-stripped), so I reverted it.
Result: DOL SHA1 26116613f624061ba99c8d1a299aaa6efa85670d, gate PASS, linked code 33828.

View File

@@ -1,6 +0,0 @@
# opus-sdct: link iplSDChannelTitle
Target .data is 0x6a0 with 0xd8 zero bytes after the SDChannelTitle vtable (deduped weak vtables); built emitted 0x94 (PaneManager, EventHandler, Interface). Text extras are weak and get deduped, so they're fine.
1. Dropped IPL_CHANNEL_TITLE_NOVTABLE entirely: adds HermiteIntp<f>/Interporation<f> weak vtables, data 0x67c, text/sdata2 grow. Rejected (HermiteIntp<f> vtable is global elsewhere; Interporation<f> never exists in the DOL).
2. Kept IPL_CHANNEL_TITLE_NOVTABLE defined across iplSDChannelTitle.h too (same as iplChannelTitle.cpp does), so the inline LangFile/LayoutFile path from iplNand.h is used: adds LayoutFile + LangFile weak vtables (0x40), data 0x69c = target content. 69/69 exact, flip to Matching, DOL SHA1 OK, gate PASS.

Some files were not shown because too many files have changed in this diff Show More