From 95c685534e95e3467206998ce5db99a3f1eb568c Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:05:27 -0500 Subject: [PATCH 1/5] tiHKBManager: 21/29 functions, data 100% (worker adbf6056) (#323) --- README.md | 4 +- include/keyboard/tiHKBManager.h | 127 +++++ libs/RVL_SDK/include/revolution/kbd.h | 10 + src/keyboard/tiHKBManager.cpp | 549 +++++++++++++++++++ tools/decomp-assist/tiHKBManager.attempts.md | 106 ++++ 5 files changed, 794 insertions(+), 2 deletions(-) create mode 100644 src/keyboard/tiHKBManager.cpp create mode 100644 tools/decomp-assist/tiHKBManager.attempts.md diff --git a/README.md b/README.md index f7bd6703..f2e3fc9b 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 84.90% | 75.26% | 56.76% | 86.70% | +| 85.10% | 75.39% | 56.76% | 86.72% | -units 748/1027 complete, functions 10978/12563 matched. +units 748/1027 complete, functions 10999/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/include/keyboard/tiHKBManager.h b/include/keyboard/tiHKBManager.h index 2ac12374..1f5504a1 100644 --- a/include/keyboard/tiHKBManager.h +++ b/include/keyboard/tiHKBManager.h @@ -6,9 +6,135 @@ #include #include "keyboard/tiCpData.h" +#ifdef TIHKBMANAGER_IMPLEMENTATION +#include +enum _KBDEc { KBD_EC_BUSY = 7 }; +#endif namespace textinput { namespace input { +#ifdef TIHKBMANAGER_IMPLEMENTATION + class HKBManager { + public: + class KeyState_ { + public: + void NotifyEvent(u8 down, u8 code); + void Update(); + void UpdateModState_(); + void Clear() { + held = 0; + triggered = 0; + released = 0; + repeated = 0; + current = 0; + pending = 0; + modifiers &= 0x700; + forceMask = 0; + forceState = 0; + retryLeds = 0; + } + void Initialize(u8 channel) { + held = 0; + triggered = 0; + released = 0; + repeated = 0; + current = 0; + pending = 0; + forceMask = 0; + forceState = 0; + retryLeds = 0; + device = channel; + country = 0xf; + modifiers = 0; + } + u8 device; + u32 held, triggered, released, repeated; + u32 previous, current, pending; + u32 modifiers, forceState, forceMask; + s32 country; + u8 retryLeds; + u8 previousKeys[8], currentKeys[8], pendingKeys[8]; + u32 repeatDelay[8]; + }; + class KeySet { + public: + KeySet() {} + KeySet(const HKBManager* owner, u8 kind) + : manager(owner), type(kind), index(-1), device(0), vcode(0) {} + u8 GetKey() const; + u32 GetWChar() const; + u32 GetVCode() const; + u32 IsValid() const; + bool CheckValidity() const { + if (!manager) return false; + s8 keyIndex = index; + if (keyIndex < 0 || keyIndex >= 8) return false; + u8 keyDevice = device; + if (keyDevice >= 2) return false; + switch (type) { + case 0: return (manager->states[keyDevice].held & (1 << keyIndex)) != 0; + case 1: return (manager->states[keyDevice].triggered & (1 << keyIndex)) != 0; + case 2: return (manager->states[keyDevice].released & (1 << keyIndex)) != 0; + case 3: return (manager->states[keyDevice].repeated & (1 << keyIndex)) != 0; + } + return false; + } + KeySet GetNext() const; + const HKBManager* manager; + u8 type; + s8 index; + u8 device; + mutable u16 vcode; + }; + class KBDListenerOwn; + class KBDListenerLinks { + public: + KBDListenerLinks() : previous(0), next(0) {} + virtual ~KBDListenerLinks() {} + virtual void OnAttach(KBDDevEvent*) = 0; + virtual void OnDetach(KBDDevEvent*) = 0; + virtual void OnKeyEvent(KBDKeyEvent*) = 0; + KBDListenerOwn* previous; + KBDListenerOwn* next; + }; + class KBDListenerOwn : public KBDListenerLinks { + public: + KBDListenerOwn(HKBManager* owner) : manager(owner) {} + virtual ~KBDListenerOwn(); + virtual void OnAttach(KBDDevEvent* event); + virtual void OnDetach(KBDDevEvent* event); + virtual void OnKeyEvent(KBDKeyEvent* event); + HKBManager* manager; + }; + HKBManager() __attribute__((never_inline)); + ~HKBManager(); + static HKBManager& getInstance() { return sInstance; } + void Initialize(); + void ClearState(); + u32 GetModifierState() const; + void SetCountry(u8 country); + void SetModifierState(u32 state, u32 mask); + void SetForceModifierState(u32 state, u32 mask); + void Update(); + KeySet GetTriggeredKeySet() const; + KeySet GetReleasedKeySet() const; + KeySet GetRepeatedKeySet() const; + static void SetLedCB(_KBDEc result, void* userData); + static void AttachCB(KBDDevEvent* event); + static void DetachCB(KBDDevEvent* event); + static void KeyEventCB(KBDKeyEvent* event); + private: + u8 initialized; + u8 attached[2]; + u32 lockState; + u32 retryDevices; + const wchar_t* allowedCharacters; + u32 allowedCharacterCount; + KeyState_ states[2]; + KBDListenerOwn listener; + static HKBManager sInstance; + }; +#else class HKBManager { public: #ifdef TIMANAGER_IMPLEMENTATION @@ -56,6 +182,7 @@ namespace textinput { static HKBManager sInstance; }; +#endif } // namespace input } // namespace textinput diff --git a/libs/RVL_SDK/include/revolution/kbd.h b/libs/RVL_SDK/include/revolution/kbd.h index 41aae23e..047b045c 100644 --- a/libs/RVL_SDK/include/revolution/kbd.h +++ b/libs/RVL_SDK/include/revolution/kbd.h @@ -30,11 +30,21 @@ typedef enum _KBDCountryCode { } KBDCountryCode; typedef struct _KBDKeyEvent { +#ifdef TIHKBMANAGER_IMPLEMENTATION + u8 device; + u8 key; + u32 flags; +#else u8 unk_0x00[32]; +#endif } KBDKeyEvent; typedef struct _KBDDevEvent { +#ifdef TIHKBMANAGER_IMPLEMENTATION + u8 device; +#else u8 unk_0x00[32]; +#endif } KBDDevEvent; #ifdef __cplusplus diff --git a/src/keyboard/tiHKBManager.cpp b/src/keyboard/tiHKBManager.cpp new file mode 100644 index 00000000..e858331f --- /dev/null +++ b/src/keyboard/tiHKBManager.cpp @@ -0,0 +1,549 @@ +#define TIHKBMANAGER_IMPLEMENTATION +#include "keyboard/tiHKBManager.h" +#include + +extern "C" { +_KBDEc KBDSetLedsAsync(u8, u8, void (*)(_KBDEc, void*), void*); +void KBDSetLockProcessing(u8, int); +int KBDSetCountry(u8, u32); +int KBDSetModState(u8, u32); +_KBDEc KBDSetLeds(u8, u8); +u16 KBDTranslateHidCode(u8, u32, u32); +void KBDInitRegionUS(); +void KBDInit(); +void KBDSetAttachCallback(void (*)(KBDDevEvent*)); +void KBDSetDetachCallback(void (*)(KBDDevEvent*)); +void KBDSetKeyCallback(void (*)(KBDKeyEvent*)); +} + +namespace textinput { +namespace input { + +HKBManager HKBManager::sInstance; + +// KBD callbacks encode the device in the first byte of the opaque pointer value. +union LedCallbackData { + void* pointer; + u8 device; + struct { + u8 device; + u32 leds; + } request; +}; + +void HKBManager::SetLedCB(_KBDEc result, void* userData) { + if (result == KBD_EC_BUSY) { + LedCallbackData received; + received.pointer = userData; + LedCallbackData callback; + callback.request.device = received.device; + callback.request.leds = 0; + const u8 leds = callback.request.leds; + u32 interrupts = OSDisableInterrupts(); + u32 mask = 1 << received.device; + sInstance.retryDevices &= ~mask; + OSRestoreInterrupts(interrupts); + if (KBDSetLedsAsync(received.device, leds, SetLedCB, callback.pointer) == KBD_EC_BUSY) { + interrupts = OSDisableInterrupts(); + sInstance.retryDevices |= mask; + OSRestoreInterrupts(interrupts); + } + } +} + +void HKBManager::KBDListenerOwn::OnAttach(KBDDevEvent* event) { + HKBManager* owner; + u8 device; + if (event->device >= 2) { + KBDSetLockProcessing(event->device, 0); + device = event->device; + owner = manager; + LedCallbackData callback; + callback.request.device = device; + callback.request.leds = 0; + const u8 leds = callback.request.leds; + u32 interrupts = OSDisableInterrupts(); + u32 mask = 1 << device; + owner->retryDevices &= ~mask; + OSRestoreInterrupts(interrupts); + if (KBDSetLedsAsync(device, leds, SetLedCB, callback.pointer) == KBD_EC_BUSY) { + interrupts = OSDisableInterrupts(); + owner->retryDevices |= mask; + OSRestoreInterrupts(interrupts); + } + } else { + manager->attached[event->device] = 1; + KBDSetLockProcessing(event->device, 0); + manager->states[event->device].retryLeds = 1; + } +} + +void HKBManager::KBDListenerOwn::OnDetach(KBDDevEvent* event) { + u8 device = event->device; + if (device >= 2) return; + HKBManager* owner = manager; + owner->attached[device] = 0; + owner->states[device].Clear(); +} + +void HKBManager::KBDListenerOwn::OnKeyEvent(KBDKeyEvent* event) { + if (event->device >= 2) return; + if (event->flags & 2) return; + manager->states[event->device].NotifyEvent(event->flags & 1, event->key); +} + +void HKBManager::AttachCB(KBDDevEvent* event) { + KBDListenerOwn* current = &sInstance.listener; + while (current != 0) { + current->OnAttach(event); + current = current->next; + if (current == &sInstance.listener) break; + } +} + +void HKBManager::DetachCB(KBDDevEvent* event) { + KBDListenerOwn* current = &sInstance.listener; + while (current != 0) { + current->OnDetach(event); + current = current->next; + if (current == &sInstance.listener) break; + } +} + +void HKBManager::KeyEventCB(KBDKeyEvent* event) { + KBDListenerOwn* current = &sInstance.listener; + while (current != 0) { + current->OnKeyEvent(event); + current = current->next; + if (current == &sInstance.listener) break; + } +} + +HKBManager::HKBManager() + : initialized(0), lockState(0), retryDevices(0), allowedCharacters(0), + allowedCharacterCount(0), listener(this) { + for (u32 device = 0; device < 2; device++) { + attached[device] = 0; + states[static_cast(device)].Initialize(static_cast(device)); + } +} + +HKBManager::KBDListenerOwn::~KBDListenerOwn() {} + +void HKBManager::Initialize() { + if (initialized == 0) { + initialized = 1; + KBDInitRegionUS(); + KBDInit(); + if (listener.previous == 0) { + KBDSetAttachCallback(AttachCB); + KBDSetDetachCallback(DetachCB); + KBDSetKeyCallback(KeyEventCB); + } + u32 device = 0; + do { + KBDSetCountry(static_cast(device), states[static_cast(device)].country); + device++; + } while (device < 2); + } +} + +void HKBManager::ClearState() { + for (u32 device = 0; device < 2; device++) { + states[static_cast(device)].Clear(); + } +} + +u32 HKBManager::GetModifierState() const { + u32 modifiers = states[0].modifiers; + u32 mask = states[0].forceMask; + modifiers &= ~mask; + modifiers |= states[0].forceState & mask; + u32 forceMask; + u32 force; + force = states[1].modifiers; + forceMask = states[1].forceMask; + force &= ~forceMask; + force |= states[1].forceState & forceMask; + return modifiers | force; +} +void HKBManager::SetCountry(u8 country) { + KeyState_* state; + u32 device = 0; + do { + state = &states[static_cast(device)]; + state->country = country; + KBDSetCountry(device & 0xff, country); + KBDSetModState(state->device, state->modifiers); + u32 modifiers = state->modifiers; + u8 leds = 0; + if ((modifiers & 0x100) != 0) { + leds |= 1; + } + if ((modifiers & 0x200) != 0) { + leds |= 2; + } + if ((modifiers & 0x400) != 0) { + leds |= 4; + } + if (KBDSetLeds(state->device, leds) == 7) { + state->retryLeds = 1; + } + device++; + } while (device < 2); +} + +void HKBManager::SetModifierState(u32 state, u32 mask) { + lockState = lockState & ~mask | state & mask; + KeyState_* slot; + u32 modifiers; + u32 global; + u32 device = 0; + do { + slot = &states[static_cast(device)]; + modifiers = slot->modifiers; + global = lockState & 0x700; + bool changed = global != (modifiers & 0x700); + slot->modifiers &= ~0x700; + slot->modifiers |= lockState; + if (changed && + attached[static_cast(device)] != 0) { + KBDSetModState(slot->device, slot->modifiers); + modifiers = slot->modifiers; + u8 leds = 0; + if ((modifiers & 0x100) != 0) { + leds |= 1; + } + if ((modifiers & 0x200) != 0) { + leds |= 2; + } + if ((modifiers & 0x400) != 0) { + leds |= 4; + } + if (KBDSetLeds(slot->device, leds) == 7) { + slot->retryLeds = 1; + } + } + device++; + } while (device < 2); +} + +void HKBManager::SetForceModifierState(u32 state, u32 mask) { + states[0].forceState = state; + states[0].forceMask = mask; + states[1].forceState = state; + states[1].forceMask = mask; +} + +void HKBManager::Update() { + if (initialized != 0) { + u32 mask; + u32 device = 2; + do { + u8 shiftIndex = static_cast(device); + mask = 1 << shiftIndex; + if ((retryDevices & mask) != 0) { + LedCallbackData callback; + callback.request.device = static_cast(device); + callback.request.leds = 0; + const u8 leds = callback.request.leds; + u32 interrupts = OSDisableInterrupts(); + retryDevices &= ~mask; + OSRestoreInterrupts(interrupts); + if (KBDSetLedsAsync(device & 0xff, leds, + SetLedCB, + callback.pointer) == 7) { + interrupts = OSDisableInterrupts(); + retryDevices |= mask; + OSRestoreInterrupts(interrupts); + } + } + device++; + } while (device < 4); + u32 updateIndex = 0; + do { + states[updateIndex & 0xff].Update(); + updateIndex++; + } while (updateIndex < 2); + } +} + +HKBManager::KeySet HKBManager::GetTriggeredKeySet() const { + KeySet keys; + keys.manager = this; + keys.type = 1; + keys.index = -1; + keys.device = 0; + keys.vcode = 0; + return keys.GetNext(); +} + +HKBManager::KeySet HKBManager::GetReleasedKeySet() const { + KeySet keys; + keys.manager = this; + keys.type = 2; + keys.index = -1; + keys.device = 0; + keys.vcode = 0; + return keys.GetNext(); +} + +HKBManager::KeySet HKBManager::GetRepeatedKeySet() const { + KeySet keys; + keys.manager = this; + keys.type = 3; + keys.index = -1; + keys.device = 0; + keys.vcode = 0; + return keys.GetNext(); +} + +void HKBManager::KeyState_::NotifyEvent(u8 down, u8 code) { + u32 index; + s32 found = -1; + if (down == 1) { + for (index = 0; index < 8; index++) { + if ((pending & (1 << index)) != 0) { + if (code == pendingKeys[index]) { found = index; break; } + } else { + found = index; + break; + } + } + if (found >= 0) { + pendingKeys[found] = code; + pending |= 1 << found; + } + } else { + for (index = 0; index < 8; index++) { + if ((pending & (1 << index)) && code == pendingKeys[index]) { + found = index; + break; + } + } + if (found >= 0) pending &= ~(1 << found); + } +} + +void HKBManager::KeyState_::Update() { + u32 interrupts = OSDisableInterrupts(); + previous = current; + current = pending; + previousKeys[0] = currentKeys[0]; + currentKeys[0] = pendingKeys[0]; + previousKeys[1] = currentKeys[1]; + currentKeys[1] = pendingKeys[1]; + previousKeys[2] = currentKeys[2]; + currentKeys[2] = pendingKeys[2]; + previousKeys[3] = currentKeys[3]; + currentKeys[3] = pendingKeys[3]; + previousKeys[4] = currentKeys[4]; + currentKeys[4] = pendingKeys[4]; + previousKeys[5] = currentKeys[5]; + currentKeys[5] = pendingKeys[5]; + previousKeys[6] = currentKeys[6]; + currentKeys[6] = pendingKeys[6]; + previousKeys[7] = currentKeys[7]; + currentKeys[7] = pendingKeys[7]; + OSRestoreInterrupts(interrupts); + UpdateModState_(); + u32 bit; + u32 index; + u32 heldKeys = current; + triggered = 0; + held = heldKeys; + for (index = 0; index < 8; index++) { + bit = 1 << index; + if ((current & bit) != 0) { + if ((previous & bit) == 0 || previousKeys[index] != currentKeys[index]) { + triggered |= bit; + } + } + } + released = 0; + for (index = 0; index < 8; index++) { + bit = 1 << index; + if ((previous & bit) != 0) { + if ((current & bit) == 0 || previousKeys[index] != currentKeys[index]) { + released |= bit; + } + } + } + repeated = 0; + for (index = 0; index < 8; index++) { + bit = 1 << index; + if ((current & bit) != 0) { + if ((triggered & bit) != 0) { + repeatDelay[index] = 30; + repeated |= bit; + } + repeatDelay[index]--; + if (repeatDelay[index] == 0) { + repeatDelay[index] = 8; + repeated |= bit; + } + } + } +} + +void HKBManager::KeyState_::UpdateModState_() { + u32 index; + u32 oldModifiers = modifiers; + modifiers = oldModifiers & 0xffffffd0; + index = 0; + for (; index < 8; index++) { + u32 keySet; + u8 slot; + keySet = current; + slot = index; + if ((keySet & (1 << slot)) != 0) { + u8 code = currentKeys[slot]; + if (code == 0xe5 || code == 0xe1) { + modifiers |= 2; + } else if (code == 0xe4 || code == 0xe0) { + modifiers |= 1; + } else if (code == 0xe7 || code == 0xe3) { + modifiers |= 8; + } else if (code == 0xe2) { + modifiers |= 4; + } else if (code == 0xe6) { + if (static_cast(country) == 0xf || + static_cast(country) == 0x21) { + modifiers |= 4; + } else { + modifiers |= 0x20; + } + } + } + } + if ((oldModifiers & 0x700) != (modifiers & 0x700) || retryLeds != 0) { + retryLeds = 0; + KBDSetModState(device, modifiers); + u32 modifiers = this->modifiers; + u8 leds = 0; + if ((modifiers & 0x100) != 0) { + leds |= 1; + } + if ((modifiers & 0x200) != 0) { + leds |= 2; + } + if ((modifiers & 0x400) != 0) { + leds |= 4; + } + if (KBDSetLeds(device, leds) == 7) { + retryLeds = 1; + } + } +} + +u8 HKBManager::KeySet::GetKey() const { + if (!CheckValidity()) return 0; + switch (type) { + case 0: return manager->states[device].currentKeys[index]; + case 1: return manager->states[device].currentKeys[index]; + case 2: return manager->states[device].previousKeys[index]; + case 3: return manager->states[device].currentKeys[index]; + } + return 0; +} + +u32 HKBManager::KeySet::GetWChar() const { + u32 code = GetVCode(); + if ((code & 0xffff) >= 0xf130 && (code & 0xffff) <= 0xf139) { + code = code - 0xf100 & 0xffff; + } else { + u32 lowCode = code & 0xffff; + if (lowCode == 0xf10d) { + code = 0xf1cd; + } else if (lowCode >= 0xf100 && lowCode <= 0xf13f) { + code = code - 0xf100 & 0xffff; + } else if ((code & 0xffff) >= 0xf140 && (code & 0xffff) <= 0xf17f) { + code = code + 0x40 & 0xffff; + } + } + u16 character = code; + if ((character & 0xf000) == 0xf000) { + code = 0; + } else if ((code & 0xffff) == 0xeeee) { + code = 0; + } else if ((code & 0xffff) < 0x20) { + code = 0; + } + const HKBManager* owner = manager; + if (owner->allowedCharacters == 0) return code; + u32 count = owner->allowedCharacterCount; + if (count == 0) return code; + for (u32 index = 0; index < count; index++) { + if ((code & 0xffff) == owner->allowedCharacters[index]) return code; + } + return 0; +} + +u32 HKBManager::KeySet::GetVCode() const { + u32 modifiers; + if (!CheckValidity()) return 0; + if (vcode) return vcode; + u32 first = manager->states[0].modifiers; + u32 mask = manager->states[0].forceMask; + first &= ~mask; + first |= manager->states[0].forceState & mask; + u32 secondMask; + u32 second; + second = manager->states[1].modifiers; + secondMask = manager->states[1].forceMask; + second &= ~secondMask; + second |= manager->states[1].forceState & secondMask; + modifiers = first | second; + if ((modifiers & 0xd) != 0 && (modifiers & 5) != 5) return 0; + switch (type) { + case 0: + case 1: + case 3: + if ((manager->states[device].current & (1 << index)) != 0) { + vcode = KBDTranslateHidCode(manager->states[device].currentKeys[index], modifiers, + manager->states[device].country); + } + break; + case 2: + if ((manager->states[device].previous & (1 << index)) != 0) { + vcode = KBDTranslateHidCode(manager->states[device].previousKeys[index], modifiers, + manager->states[device].country); + } + break; + } + return vcode; +} + +u32 HKBManager::KeySet::IsValid() const { + return CheckValidity(); +} + +HKBManager::KeySet HKBManager::KeySet::GetNext() const { + KeySet next(manager, type); + if (manager != 0) { + next.device = device; + while (next.device < 2) { + u32 keyFlags = 0; + switch (type) { + case 0: keyFlags = manager->states[next.device].held; break; + case 1: keyFlags = manager->states[next.device].triggered; break; + case 2: keyFlags = manager->states[next.device].released; break; + case 3: keyFlags = manager->states[next.device].repeated; break; + } + next.index = index + 1; + while (next.index < 8) { + if ((keyFlags & (1 << next.index)) != 0) return next; + next.index++; + } + next.index = -1; + next.device++; + } + } + return next; +} + + +HKBManager::~HKBManager() {} + +} +} diff --git a/tools/decomp-assist/tiHKBManager.attempts.md b/tools/decomp-assist/tiHKBManager.attempts.md new file mode 100644 index 00000000..1ea6c144 --- /dev/null +++ b/tools/decomp-assist/tiHKBManager.attempts.md @@ -0,0 +1,106 @@ +# tiHKBManager attempts + +Baseline: no source, 0/29 instruction-exact functions and 0/6116 code bytes. +The pool is empty and identical from the first object build. All fields and +calls use typed keyboard declarations. Only TIHKBMANAGER_IMPLEMENTATION selects +the added layouts; existing keyboard guard branches remain unchanged. + +## Remaining functions, in object order + +### SetLedCB +1. Initialized pointer union followed by device byte: 41/41 instructions, + six differences in stack offsets and store scheduling. +2. Typed LED request containing the device and LED mask, using its mask as + the asynchronous call argument: 42/41, one extra load and mask conversion. +3. Snapshot the request mask before disabling interrupts: 42/41, unchanged. +4. Make the snapshot const: 42/41, unchanged. Retained this readable request. + A literal mask enum reached 41/41 with zero differences, but left the + request's mask unused; that experiment was discarded. + +### KBDListenerOwn::OnAttach +1. Pointer union initialized to zero: 59/61 instructions; saved-register + allocation and callback stores differed. +2. LED request and mask argument: 60/61; allocation still differed. +3. Declare owner/device outside the branch: request with a literal mask + reached 61/61 and zero differences. +4. Read the actual request mask into a local, then make that local const: + both 62/61, an extra load and mask conversion. Retained the const snapshot + so both request fields have a real use. + +### KBDListenerOwn::OnDetach +1. Owner alias and typed Clear helper: 22/22, four register differences. +2. Declare a state pointer before clearing attached: 22/22, same four. +3. Access manager directly twice: 23/22, an additional owner load. +4. State reference before owner declaration: 22/22, six differences. +5. Owner declared before device: 22/22, six differences. Retained attempt 1. + +### HKBManager::Update +1. Zero-initialized pointer union: 55/55, two callback-store differences. +2. Typed LED request used by the asynchronous call: 55/55, one argument + conversion difference. +3. Literal LED mask enum: 55/55, zero differences, but unused request mask. +4. Snapshot the request mask, then make it const: 55/55, one conversion + difference. Retained the const snapshot with both request fields used. + +### KeyState_::Update +1. Explicit groups of two event/repeat slots: 183/183, 63 differences. +2. Ordinary loops over eight slots: 183/183, 51 differences. +3. Snapshot held keys before clearing triggers: 183/183, 47 differences. +4. Hoist shared bit/index declarations: 183/183, unchanged. +5. Cache previous/current array pointers: 247/183, rejected. +6. Reverse bit/index declaration order: 183/183, 44 differences, retained. + Registers and repeat-array address calculation still differ. + +### KeyState_::UpdateModState_ +1. Loop counter before old modifier snapshot: 104/104, seven differences. +2. Move old modifier snapshot before counter: 104/104, ten differences. +3. Use a byte slot index: 104/104, seven differences. +4. Separate slot/key-mask declarations and assignments: 104/104, unchanged. +5. Scope the counter inside for: 104/104, ten differences. Retained attempt 4. + +### KeySet::GetWChar +1. Original nested descending range tests: 70/77 instructions. +2. Ascending range branches, u32 virtual-code return, direct whitelist + indexing and early exits: 74/77. +3. Signed code temporary: 82/77, rejected. +4. Separate u16 character for the private-code mask: 75/77, retained. +5. Inline range predicate accepting u16: 89/77, rejected. + The retained version lacks two repeated narrowing instructions and uses + different whitelist-loop registers. + +### KeySet::IsValid +1. Direct guard/switch with owner alias: 70/70, 18 register differences. +2. Hoist index/device declarations before owner: 70/70, 12 differences. +3. Reverse those declaration positions: 70/70, unchanged. +4. Widen index/device temporaries: 70/70, 14 differences. +5. Inline the same CheckValidity helper used by GetKey/GetVCode: + 70/70, 12 differences, retained. Index/device registers are exchanged. + +## Exact functions + +All other functions are C++ and instruction-exact. Important successful +changes: sequential Clear stores; callback traversal compares its next node +with the owning listener; a polymorphic listener base initializes its links +before the derived vtable; NotifyEvent shares its loop index outside both +branches; SetModifierState computes its comparison before changing the field +and compares new locks against old locks; KeySet uses typed validity and +separate switch cases; GetVCode declares the second modifier mask before its +state value. The constructor uses the compiler +never_inline attribute so static initialization calls the real constructor. +Both the constructor and its static initializer are exact. A scoped pragma +experiment was rejected by the source gate and removed. Changing the +constructor loop to do/while produced 35/45 constructor and 43/18 initializer +instructions; the ordinary for loop was restored. + +## Data and files + +The singleton and compiler-generated destructor registration supply .bss. +The compiler supplies the constructor entry and listener vtable. No literal +pool, pinned addresses, hand-built vtable, or forced sections are added. +A weak abstract listener-base vtable is also compiler-generated. + +Changed files: +- src/keyboard/tiHKBManager.cpp +- include/keyboard/tiHKBManager.h +- libs/RVL_SDK/include/revolution/kbd.h +- tools/decomp-assist/tiHKBManager.attempts.md -- 2.49.1 From b615148895df337b4c956f72f0c44916f9e382a0 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:08:46 -0500 Subject: [PATCH 2/5] fa/pf_entry 20/20, pf_cluster 5/8 (worker 5fc6d9c5) (#324) --- README.md | 4 +- libs/RVL_SDK/src/fa/pf_cluster.c | 644 +++++++++++++++ libs/RVL_SDK/src/fa/pf_entry.c | 759 ++++++++++++++++++ tools/decomp-assist/fa_pf_cluster_attempts.md | 26 + 4 files changed, 1431 insertions(+), 2 deletions(-) create mode 100644 libs/RVL_SDK/src/fa/pf_cluster.c create mode 100644 libs/RVL_SDK/src/fa/pf_entry.c create mode 100644 tools/decomp-assist/fa_pf_cluster_attempts.md diff --git a/README.md b/README.md index f2e3fc9b..1e699365 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 85.10% | 75.39% | 56.76% | 86.72% | +| 85.47% | 75.70% | 56.76% | 86.72% | -units 748/1027 complete, functions 10999/12563 matched. +units 748/1027 complete, functions 11024/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RVL_SDK/src/fa/pf_cluster.c b/libs/RVL_SDK/src/fa/pf_cluster.c new file mode 100644 index 00000000..e079f2b8 --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_cluster.c @@ -0,0 +1,644 @@ +#include + +typedef struct PFCLUSTER_FAT_HINT { + pf_u32 chain_index; + pf_u32 cluster; + pf_u32 previous_cluster; +} PFCLUSTER_FAT_HINT; + +typedef struct PFCLUSTER_FFD { + pf_u32 start_cluster; + pf_u32 current_start_cluster; + pf_u32* p_start_cluster; + PF_LAST_CLUSTER last_cluster; + PF_FAT_LAST_ACCESS last_access_cluster; + PF_CLUSTER_LINK cluster_link; + PFCLUSTER_FAT_HINT* p_hint; + PF_VOLUME* p_vol; +} PFCLUSTER_FFD; + +typedef struct PFCLUSTER_ENT_ITER { + pf_u32 index; + PF_VOLUME* p_vol; + PFCLUSTER_FFD ffd; + pf_u32 file_sector_index; + pf_u32 sector; + pf_u16 offset; + pf_u16 offset_mask; + pf_u8 buf[32]; + pf_u8 log2_entries_per_sector; +} PFCLUSTER_ENT_ITER; + +typedef struct PFCLUSTER_BPB { + pf_u16 bytes_per_sector; + pf_u16 num_reserved_sectors; + pf_u16 num_root_dir_entries; + pf_u8 sectors_per_cluster; + pf_u8 num_FATs; + pf_u32 total_sectors; + pf_u32 sectors_per_FAT; + pf_u32 root_dir_cluster; + pf_u16 fs_info_sector; + pf_u16 backup_boot_sector; + pf_u16 ext_flags; + pf_u8 media; + pf_s32 fat_type; + pf_u8 log2_bytes_per_sector; + pf_u8 log2_sectors_per_cluster; + pf_u8 num_active_FATs; + pf_u16 num_root_dir_sectors; + pf_u32 active_FAT_sector; + pf_u32 first_root_dir_sector; + pf_u32 first_data_sector; + pf_u32 num_clusters; +} PFCLUSTER_BPB; + +struct PF_VOLUME { + PFCLUSTER_BPB bpb; + pf_u32 num_free_clusters; + pf_u32 last_free_cluster; + pf_u8 file_and_directory_state[0x1624 - 0x40]; + pf_u32 cache_mode; + pf_u8 cache_and_driver_state[0x1f90 - 0x1628]; + pf_u16 fsi_flag; +}; + +typedef struct PFCLUSTER_CURSOR { + pf_u32 position; + pf_u32 sector; + pf_u32 file_sector_index; + pf_u16 offset_in_sector; + pf_u16 reserved; +} PFCLUSTER_CURSOR; + +typedef struct PFCLUSTER_SFD { + pf_u32 stat; + PFCLUSTER_FFD ffd; + PF_DIR_ENT dir_entry; +} PFCLUSTER_SFD; + +typedef struct PFCLUSTER_FILE { + pf_u32 stat; + pf_u32 open_mode; + PFCLUSTER_SFD* p_sfd; + PFCLUSTER_FAT_HINT hint; + pf_s32 last_error; + PFCLUSTER_CURSOR cursor; +} PFCLUSTER_FILE; + +extern pf_s32 PFFILE_Cursor_MoveToClusterEnd(PFCLUSTER_FILE*, pf_u32); +extern pf_s32 PFFILE_Cursor_MoveToEnd(PFCLUSTER_FILE*); +extern pf_s32 PFFAT_GetSectorAllocated(PFCLUSTER_FFD*, pf_u32, pf_u32, pf_u32*); +extern pf_s32 PFFAT_getContinuousSector(PFCLUSTER_FFD*, pf_u32, pf_u32, pf_u32*, pf_u32*); +extern pf_s32 PFFAT_TraceClustersChain(PFCLUSTER_FFD*, pf_u32, pf_u32, pf_u32*, pf_u32*); +extern pf_u32 PFFAT_GetValueOfEOC2(PF_VOLUME*); +extern pf_s32 PFFAT_WriteValueToSpecifiedCluster(PF_VOLUME*, pf_u32, pf_u32); +extern pf_s32 PFFAT_ReadValueToSpecifiedCluster(PF_VOLUME*, pf_u32, pf_u32*); +extern pf_s32 PFFAT_FreeChain(PFCLUSTER_FFD*, pf_u32, pf_u32, pf_u32); +extern pf_s32 PFFAT_AllocateNumClusters(PFCLUSTER_FFD*, pf_u32, pf_u32*, pf_u32*, pf_u32*); +extern pf_s32 PFENT_updateEntry(PF_DIR_ENT*, pf_u32); +extern pf_u8 PFENT_getcurrentDateTimeForEnt(pf_u16*, pf_u16*); +extern pf_s32 PFCACHE_FlushDataCacheSpecific(PF_VOLUME*, void*); +extern pf_s32 PFCACHE_AllocateDataPage(PF_VOLUME*, pf_u32, PF_CACHE_PAGE**, pf_bool*); +extern void PFCACHE_FreeDataPage(PF_VOLUME*, PF_CACHE_PAGE*); +extern pf_s32 PFSEC_ReadData(PF_VOLUME*, pf_u8*, pf_u32, pf_u16, pf_u32, pf_u32*, pf_bool); +extern pf_s32 PFSEC_WriteData(PF_VOLUME*, const pf_u8*, pf_u32, pf_u16, pf_u32, pf_u32*, pf_bool); + + + +void PFCLUSTER_UpdateLastAccessCluster(PFCLUSTER_FILE* p_file, pf_u32 sector) { + PF_VOLUME* p_vol; + + if (p_file->cursor.position == 0) { + p_file->p_sfd->ffd.last_access_cluster.cluster = 0; + p_file->p_sfd->ffd.last_access_cluster.chain_index = 0; + return; + } + + p_vol = p_file == PF_NULL ? PF_NULL : p_file->p_sfd->dir_entry.p_vol; + if ((p_file->cursor.position & (p_vol->bpb.bytes_per_sector - 1)) == 0 && + (p_file->cursor.file_sector_index & (p_vol->bpb.sectors_per_cluster - 1)) == 0) { + if (p_file->cursor.file_sector_index != 0) { + p_file->p_sfd->ffd.last_access_cluster.chain_index = (p_file->cursor.file_sector_index - 1) >> p_vol->bpb.log2_sectors_per_cluster; + p_file->p_sfd->ffd.last_access_cluster.cluster = (((sector - 1) - p_vol->bpb.first_data_sector) >> p_vol->bpb.log2_sectors_per_cluster) + 2; + } + } else { + p_file->p_sfd->ffd.last_access_cluster.chain_index = p_file->cursor.file_sector_index >> p_vol->bpb.log2_sectors_per_cluster; + p_file->p_sfd->ffd.last_access_cluster.cluster = ((sector - p_vol->bpb.first_data_sector) >> p_vol->bpb.log2_sectors_per_cluster) + 2; + } +} + +pf_s32 PFCLUSTER_AppendCluster(PFCLUSTER_FILE* p_file, pf_u32 byte, pf_bool* p_success) { + pf_s32 err; + PF_VOLUME* p_vol; + pf_u32 sector; + pf_u32 num_sector; + pf_u32 max_appendable_size; + PFCLUSTER_CURSOR save_cursor; + PFCLUSTER_FAT_HINT save_hint; + + *p_success = 0; + if ((p_file->p_sfd->stat & 0x01) == 0 || (p_file->p_sfd->stat & 0x02) == 0) { + return 38; + } + + p_vol = p_file == PF_NULL ? PF_NULL : p_file->p_sfd->dir_entry.p_vol; + + save_cursor = p_file->cursor; + save_hint = p_file->hint; + + p_file->p_sfd->ffd.p_hint = &p_file->hint; + sector = 0xFFFFFFFF; + if ((p_vol->fsi_flag & 0x04) != 0 && p_vol->num_free_clusters != -1 && p_vol->num_free_clusters == 0) { + return 6; + } + PFFILE_Cursor_MoveToClusterEnd(p_file, p_file->p_sfd->dir_entry.file_size + byte); + if (p_file->cursor.position == -1) { + *p_success = 0; + return 37; + } + err = PFFAT_GetSectorAllocated(&p_file->p_sfd->ffd, p_file->cursor.file_sector_index, byte, §or); + if (err != 0) { + p_file->cursor = save_cursor; + p_file->hint = save_hint; + return err; + } + num_sector = 0; + err = PFFAT_getContinuousSector(&p_file->p_sfd->ffd, p_file->cursor.file_sector_index, byte, §or, &num_sector); + p_file->cursor = save_cursor; + p_file->hint = save_hint; + if (err != 0) return err; + if (sector == -1U) { + PFFILE_Cursor_MoveToEnd(p_file); + return 28; + } + max_appendable_size = num_sector << p_vol->bpb.log2_bytes_per_sector; + if (byte < max_appendable_size) { + max_appendable_size = byte; + } + *p_success = max_appendable_size; + return 0; +} + +pf_s32 PFCLUSTER_AdjustCluster(PFCLUSTER_FILE* p_file) { + PF_VOLUME* p_vol; + pf_u32 num_cluster; + pf_u32 file_end_cluster; + pf_u32 spare_cluster; + pf_u32 sig_eoc; + pf_u32 chain_index; + pf_s32 err; + + if (((p_file->p_sfd->stat & 1) == 0) || ((p_file->p_sfd->stat & 2) == 0)) { + return 0x26; + } + p_vol = p_file == PF_NULL ? PF_NULL : p_file->p_sfd->dir_entry.p_vol; + + p_file->p_sfd->ffd.p_hint = &p_file->hint; + chain_index = -1U; + if (p_file->p_sfd->ffd.last_cluster.max_chain_index != 0) { + num_cluster = ((p_file->p_sfd->dir_entry.file_size & ((p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster) - 1)) ? 1 : 0) + + (p_file->p_sfd->dir_entry.file_size >> (p_vol->bpb.log2_bytes_per_sector + p_vol->bpb.log2_sectors_per_cluster)); + + if ((p_file->p_sfd->ffd.last_cluster.max_chain_index + 1) == num_cluster) { + return 0; + } + } + if (p_file->p_sfd->dir_entry.file_size != 0) { + err = PFFAT_TraceClustersChain(&p_file->p_sfd->ffd, p_file->p_sfd->dir_entry.start_cluster, p_file->p_sfd->dir_entry.file_size, + &file_end_cluster, &spare_cluster); + if (err != 0) { + return err; + } + } else { + file_end_cluster = 0; + spare_cluster = p_file->p_sfd->dir_entry.start_cluster; + } + if (spare_cluster != 0) { + sig_eoc = PFFAT_GetValueOfEOC2(p_vol); + if (spare_cluster != sig_eoc) { + if (file_end_cluster != 0) { + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, file_end_cluster, sig_eoc); + if (err != 0) { + return err; + } + p_file->p_sfd->ffd.last_cluster.num_last_cluster = file_end_cluster; + p_file->p_sfd->ffd.last_cluster.max_chain_index = + ((p_file->p_sfd->dir_entry.file_size >> (p_vol->bpb.log2_bytes_per_sector + p_vol->bpb.log2_sectors_per_cluster)) + + ((p_file->p_sfd->dir_entry.file_size & ((p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster) - 1)) ? 1 : 0)) - + 1; + chain_index = p_file->p_sfd->ffd.last_cluster.max_chain_index + 1; + + } else { + p_file->p_sfd->dir_entry.start_cluster = 0; + *p_file->p_sfd->ffd.p_start_cluster = 0; + p_file->p_sfd->ffd.last_cluster.num_last_cluster = 0; + p_file->p_sfd->ffd.last_cluster.max_chain_index = 0; + err = PFENT_updateEntry(&p_file->p_sfd->dir_entry, 1U); + if (err != 0) { + return err; + } + if ((p_vol->cache_mode & 4) != 0) { + err = PFCACHE_FlushDataCacheSpecific(p_vol, p_file); + if (err != 0) { + return err; + } + } + } + err = PFFAT_FreeChain(&p_file->p_sfd->ffd, spare_cluster, chain_index, -1U); + if (err != 0) { + return err; + } + } + } + + return 0; +} + +pf_s32 PFCLUSTER_GetAppendSize(PFCLUSTER_FILE* p_file, pf_u32* p_size) { + PF_VOLUME* p_vol; + pf_u32 cluster_size; + pf_u32 file_cluster_size; + pf_u32 total_allocated_size; + pf_u32 file_end_cluster; + pf_u32 spare_cluster; + pf_u32 next_cluster; + pf_u32 num_append_cluster; + pf_u32 sig_eoc; + pf_s32 err; + + *p_size = 0; + if ((p_file->p_sfd->stat & 0x01) == 0 || (p_file->p_sfd->stat & 0x02) == 0) { + return 38; + } + + p_vol = p_file == PF_NULL ? PF_NULL : p_file->p_sfd->dir_entry.p_vol; + + cluster_size = p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster; + if (p_file->p_sfd->dir_entry.start_cluster != 0) { + file_cluster_size = + p_file->p_sfd->dir_entry.file_size + + ((p_file->p_sfd->dir_entry.file_size % cluster_size) != 0 ? cluster_size - (p_file->p_sfd->dir_entry.file_size % cluster_size) : 0); + if (p_file->p_sfd->ffd.last_cluster.max_chain_index != 0) { + total_allocated_size = (p_file->p_sfd->ffd.last_cluster.max_chain_index + 1) * cluster_size; + + } else { + if (p_file->p_sfd->dir_entry.file_size != 0) { + err = PFFAT_TraceClustersChain(&p_file->p_sfd->ffd, p_file->p_sfd->dir_entry.start_cluster, p_file->p_sfd->dir_entry.file_size, + &file_end_cluster, &spare_cluster); + if (err != 0) { + return err; + } + } else { + spare_cluster = p_file->p_sfd->dir_entry.start_cluster; + } + + sig_eoc = PFFAT_GetValueOfEOC2(p_vol); + num_append_cluster = 0; + for (; spare_cluster != sig_eoc; spare_cluster = next_cluster) { + num_append_cluster++; + err = PFFAT_ReadValueToSpecifiedCluster(p_vol, spare_cluster, &next_cluster); + if (err != 0) { + return err; + } + } + + total_allocated_size = file_cluster_size + (num_append_cluster * cluster_size); + } + *p_size = total_allocated_size - file_cluster_size; + } + + return 0; +} + +pf_s32 PFCLUSTER_CombineFiles(PFCLUSTER_ENT_ITER* p_first_iter, PFCLUSTER_ENT_ITER* p_second_iter, + PF_DIR_ENT* p_first_entry, PF_DIR_ENT* p_second_entry) { + pf_s32 err; + pf_u32 end_cluster; + pf_u32 spare_cluster; + pf_u32 cluster_size; + pf_u32 first_used_clusters; + pf_u32 second_used_clusters; + pf_u32 first_spare_clusters; + pf_u32 second_spare_clusters; + pf_u32 excess_clusters; + pf_u32 first_end_cluster; + pf_u32 first_spare_cluster; + pf_u32 second_spare_cluster; + pf_u32 sig_eoc; + PF_VOLUME* p_vol; + + p_vol = p_first_entry->p_vol; + first_used_clusters = 0; + second_used_clusters = 0; + first_spare_clusters = 0; + second_spare_clusters = 0; + first_spare_cluster = 0; + err = PFFAT_TraceClustersChain(&p_first_iter->ffd, *p_first_iter->ffd.p_start_cluster, + p_first_entry->file_size, &end_cluster, &spare_cluster); + if (err != 0) return err; + cluster_size = p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster; + first_end_cluster = end_cluster; + if (p_first_entry->file_size != 0) { + first_used_clusters = p_first_entry->file_size / cluster_size; + if (p_first_entry->file_size % cluster_size != 0) ++first_used_clusters; + } + sig_eoc = PFFAT_GetValueOfEOC2(p_vol); + if (spare_cluster != sig_eoc) { + if (p_first_entry->file_size != 0 && spare_cluster != 0) first_spare_cluster = spare_cluster; + else first_spare_cluster = *p_first_iter->ffd.p_start_cluster; + err = PFFAT_TraceClustersChain(&p_first_iter->ffd, first_spare_cluster, -1U, &end_cluster, &spare_cluster); + if (err != 0) return err; + if (*p_first_iter->ffd.p_start_cluster != 0) { + first_spare_clusters = p_first_iter->ffd.last_cluster.max_chain_index + 1 - first_used_clusters; + } + } + err = PFFAT_TraceClustersChain(&p_second_iter->ffd, *p_second_iter->ffd.p_start_cluster, + p_second_entry->file_size, &end_cluster, &spare_cluster); + if (err != 0) return err; + if (p_second_entry->file_size != 0) { + second_used_clusters = p_second_entry->file_size / cluster_size; + if (p_second_entry->file_size % cluster_size != 0) ++second_used_clusters; + } + second_spare_cluster = spare_cluster; + if (second_spare_cluster != sig_eoc) { + if (p_second_entry->file_size != 0 && spare_cluster != 0) { + second_spare_cluster = spare_cluster; + } else second_spare_cluster = *p_second_iter->ffd.p_start_cluster; + err = PFFAT_TraceClustersChain(&p_second_iter->ffd, second_spare_cluster, -1U, &end_cluster, &spare_cluster); + if (err != 0) return err; + if (*p_second_iter->ffd.p_start_cluster != 0) { + second_spare_clusters = p_second_iter->ffd.last_cluster.max_chain_index + 1 - second_used_clusters; + } + if (-1U / cluster_size + 1 < (second_used_clusters + second_spare_clusters) + first_used_clusters) { + excess_clusters = (second_used_clusters + second_spare_clusters) + first_used_clusters - (-1U / cluster_size + 1); + err = PFFAT_TraceClustersChain(&p_second_iter->ffd, second_spare_cluster, + cluster_size * ((p_second_iter->ffd.last_cluster.max_chain_index + 1 - excess_clusters) - second_used_clusters), + &end_cluster, &spare_cluster); + if (err != 0) return err; + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, end_cluster, sig_eoc); + if (err != 0) return err; + err = PFFAT_FreeChain(&p_second_iter->ffd, spare_cluster, -1U, excess_clusters * cluster_size); + if (err != 0) return err; + if (p_second_entry->file_size == 0 && second_spare_clusters == excess_clusters) { + *p_second_iter->ffd.p_start_cluster = 0; + p_second_entry->start_cluster = 0; + } + } + } + if (first_spare_clusters != 0) { + err = PFFAT_FreeChain(&p_first_iter->ffd, first_spare_cluster, -1U, first_spare_clusters * cluster_size); + if (err != 0) return err; + if (p_first_entry->file_size == 0) { + *p_first_iter->ffd.p_start_cluster = 0; + p_first_entry->start_cluster = 0; + } + } + if (*p_first_iter->ffd.p_start_cluster != 0 && *p_second_iter->ffd.p_start_cluster != 0) { + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, first_end_cluster, *p_second_iter->ffd.p_start_cluster); + if (err != 0) return err; + } else if (*p_first_iter->ffd.p_start_cluster == 0 && *p_second_iter->ffd.p_start_cluster != 0) { + p_first_entry->start_cluster = p_second_entry->start_cluster; + } + p_first_entry->file_size = p_second_entry->file_size + first_used_clusters * cluster_size; + return 0; +} +pf_s32 PFCLUSTER_DivideFile(PFCLUSTER_ENT_ITER* p_source_iter, PFCLUSTER_ENT_ITER* p_dest_iter, + PF_DIR_ENT* p_source_entry, PF_DIR_ENT* p_dest_entry, pf_u32 split_size) { + pf_s32 err; + pf_u32 source_end; + pf_u32 success_size; + pf_u32 allocated_start; + pf_u32 allocated_end; + pf_u32 dest_cluster; + PF_CACHE_PAGE* p_page; + pf_bool cache_hit; + pf_u32 source_sector; + pf_u32 dest_sector; + pf_u32 sector_index; + pf_u32 cluster_size; + pf_u32 last_cluster; + pf_u32 allocated_size; + pf_u32 dest_first; + pf_u32 remaining; + PF_VOLUME* p_vol; + pf_u32 saved_next; + pf_u32 sig_eoc; + + allocated_start = 0; + p_vol = p_source_entry->p_vol; + dest_first = 0; + last_cluster = 0; + remaining = 0; + + if (split_size == 0) { + dest_cluster = p_source_entry->start_cluster; + } else { + err = PFFAT_TraceClustersChain(&p_source_iter->ffd, *p_source_iter->ffd.p_start_cluster, + split_size, &source_end, &dest_cluster); + if (err != 0) return err; + saved_next = dest_cluster; + sig_eoc = PFFAT_GetValueOfEOC2(p_vol); + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, sig_eoc); + if (err != 0) return err; + if (split_size == p_source_entry->file_size) { + if (dest_cluster == sig_eoc) dest_cluster = 0; + } else { + cluster_size = p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster; + remaining = split_size % cluster_size; + if (remaining != 0) { + for (allocated_size = 0; allocated_size < cluster_size; ) { + err = PFFAT_AllocateNumClusters(&p_dest_iter->ffd, cluster_size, + &allocated_start, &allocated_end, &success_size); + if (err != 0) { + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + if (success_size == 0) break; + if (allocated_size == 0) { + dest_first = allocated_start; + } else { + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, last_cluster, allocated_start); + if (err != 0) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + } + allocated_size += success_size; + last_cluster = allocated_end; + } + if (cluster_size != allocated_size) { + if (allocated_size != 0) { + err = PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + if (err != 0) { + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + } + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return 6; + } + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, last_cluster, dest_cluster); + if (err != 0) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + dest_cluster = dest_first; + source_sector = p_vol->bpb.first_data_sector + ((source_end - 2) << p_vol->bpb.log2_sectors_per_cluster); + dest_sector = p_vol->bpb.first_data_sector + ((allocated_start - 2) << p_vol->bpb.log2_sectors_per_cluster); + err = PFCACHE_AllocateDataPage(p_vol, -1U, &p_page, &cache_hit); + if (err != 0) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + for (sector_index = 0; sector_index < p_vol->bpb.sectors_per_cluster; ++sector_index) { + err = PFSEC_ReadData(p_vol, p_page->p_buf, source_sector, 0, + p_vol->bpb.bytes_per_sector, &success_size, 0); + if (err != 0) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + if (success_size != p_vol->bpb.bytes_per_sector) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return 17; + } + err = PFSEC_WriteData(p_vol, p_page->p_buf, dest_sector, 0, + p_vol->bpb.bytes_per_sector, &success_size, 0); + if (err != 0) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return err; + } + if (success_size != p_vol->bpb.bytes_per_sector) { + PFFAT_FreeChain(&p_dest_iter->ffd, dest_first, -1U, allocated_size); + PFFAT_WriteValueToSpecifiedCluster(p_vol, source_end, saved_next); + return 17; + } + ++source_sector; + ++dest_sector; + } + PFCACHE_FreeDataPage(p_vol, p_page); + } + } + } + p_dest_entry->start_cluster = dest_cluster; + p_dest_entry->file_size = p_source_entry->file_size - split_size + remaining; + return 0; +} + +pf_s32 PFCLUSTER_InsertCluster(PFCLUSTER_ENT_ITER* p_iter, PF_DIR_ENT* p_ent, + pf_u32 cluster_index, pf_u32 num_clusters, pf_u32* p_inserted_clusters) { + pf_s32 err; + pf_u32 previous_cluster; + pf_u32 next_cluster; + pf_u32 success_size; + pf_u32 allocated_start; + pf_u32 allocated_end; + pf_u32 cluster_size; + pf_u32 allocated_size; + pf_u32 first_cluster; + pf_u32 last_cluster; + pf_u32 requested_size; + pf_u32 file_clusters; + pf_u32 remainder; + pf_u32 extra_size; + PF_VOLUME* p_vol; + + p_vol = p_ent->p_vol; + cluster_size = p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster; + first_cluster = 0; + last_cluster = 0; + err = PFFAT_TraceClustersChain(&p_iter->ffd, *p_iter->ffd.p_start_cluster, + cluster_index * cluster_size, &previous_cluster, &next_cluster); + if (err != 0) return err; + file_clusters = p_ent->file_size / cluster_size; + if (p_ent->file_size % cluster_size != 0) ++file_clusters; + if (-1U / cluster_size + 1 < file_clusters + num_clusters) { + num_clusters = file_clusters + num_clusters - (-1U / cluster_size + 1); + } + requested_size = num_clusters * cluster_size; + for (allocated_size = 0; allocated_size < requested_size; ) { + err = PFFAT_AllocateNumClusters(&p_iter->ffd, requested_size, &allocated_start, &allocated_end, &success_size); + if (err != 0) return err; + if (success_size == 0) { + if (allocated_size != 0) break; + return 6; + } + if (allocated_size == 0) first_cluster = allocated_start; + else { + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, last_cluster, allocated_start); + if (err != 0) return err; + } + allocated_size += success_size; + last_cluster = allocated_end; + } + if (next_cluster == 0) { + next_cluster = p_ent->start_cluster != 0 ? p_ent->start_cluster : PFFAT_GetValueOfEOC2(p_vol); + } + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, last_cluster, next_cluster); + if (err != 0) return err; + if (cluster_index != 0) { + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, previous_cluster, first_cluster); + if (err != 0) return err; + } else p_ent->start_cluster = first_cluster; + file_clusters = p_ent->file_size / cluster_size; + remainder = p_ent->file_size % cluster_size; + if (remainder != 0) ++file_clusters; + extra_size = 0; + if (cluster_index == file_clusters && remainder != 0) extra_size = cluster_size - remainder; + p_ent->file_size += allocated_size + extra_size; + *p_inserted_clusters = allocated_size / cluster_size; + return 0; +} + +pf_s32 PFCLUSTER_DeleteCluster(PFCLUSTER_ENT_ITER* p_iter, PF_DIR_ENT* p_ent, + pf_u32 cluster_index, pf_u32 num_clusters, pf_u32* p_deleted_clusters) { + pf_s32 err; + pf_u32 previous_cluster; + pf_u32 next_cluster; + pf_u32 first_deleted_cluster; + pf_u32 last_deleted_cluster; + PF_VOLUME* p_vol; + pf_u32 cluster_size; + pf_u32 byte_position; + + p_vol = p_ent->p_vol; + cluster_size = p_vol->bpb.bytes_per_sector << p_vol->bpb.log2_sectors_per_cluster; + byte_position = cluster_index * cluster_size; + err = PFFAT_TraceClustersChain(&p_iter->ffd, *p_iter->ffd.p_start_cluster, + byte_position, &previous_cluster, &first_deleted_cluster); + if (err != 0) return err; + if (cluster_index == 0) first_deleted_cluster = p_ent->start_cluster; + num_clusters = num_clusters * cluster_size; + if (num_clusters > p_ent->file_size - byte_position) num_clusters = p_ent->file_size - byte_position; + err = PFFAT_TraceClustersChain(&p_iter->ffd, first_deleted_cluster, num_clusters, &last_deleted_cluster, &next_cluster); + if (err != 0) return err; + if (cluster_index == 0) { + if (next_cluster == PFFAT_GetValueOfEOC2(p_vol)) next_cluster = 0; + p_ent->start_cluster = next_cluster; + } + p_ent->file_size -= num_clusters; + PFENT_getcurrentDateTimeForEnt(&p_ent->modify_date, &p_ent->modify_time); + p_ent->access_date = p_ent->modify_date; + err = PFENT_updateEntry(p_ent, 1); + if (err != 0) return err; + if (p_vol->cache_mode & 4) { + err = PFCACHE_FlushDataCacheSpecific(p_vol, PF_NULL); + if (err != 0) return err; + } + err = PFFAT_FreeChain(&p_iter->ffd, first_deleted_cluster, -1U, num_clusters); + if (err != 0) return err; + if (cluster_index != 0) { + err = PFFAT_WriteValueToSpecifiedCluster(p_vol, previous_cluster, next_cluster); + if (err != 0) return err; + } + *p_deleted_clusters = num_clusters / cluster_size; + if (num_clusters % cluster_size != 0) ++*p_deleted_clusters; + return 0; +} diff --git a/libs/RVL_SDK/src/fa/pf_entry.c b/libs/RVL_SDK/src/fa/pf_entry.c new file mode 100644 index 00000000..d0a12eb5 --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_entry.c @@ -0,0 +1,759 @@ +#include + +typedef struct PFENTRY_FAT_HINT { + pf_u32 chain_index; + pf_u32 cluster; + pf_u32 previous_cluster; +} PFENTRY_FAT_HINT; + +typedef struct PFENTRY_FFD { + pf_u32 start_cluster; + pf_u32 current_start_cluster; + pf_u32* p_start_cluster; + PF_LAST_CLUSTER last_cluster; + PF_FAT_LAST_ACCESS last_access_cluster; + PF_CLUSTER_LINK cluster_link; + PFENTRY_FAT_HINT* p_hint; + PF_VOLUME* p_vol; +} PFENTRY_FFD; + +typedef struct PFENTRY_ENT_ITER { + pf_u32 index; + PF_VOLUME* p_vol; + PFENTRY_FFD ffd; + pf_u32 file_sector_index; + pf_u32 sector; + pf_u16 offset; + pf_u16 offset_mask; + pf_u8 buf[32]; + pf_u8 log2_entries_per_sector; +} PFENTRY_ENT_ITER; + +typedef struct PFENTRY_BPB { + pf_u16 bytes_per_sector; + pf_u16 num_reserved_sectors; + pf_u16 num_root_dir_entries; + pf_u8 sectors_per_cluster; + pf_u8 num_FATs; + pf_u32 total_sectors; + pf_u32 sectors_per_FAT; + pf_u32 root_dir_cluster; + pf_u16 fs_info_sector; + pf_u16 backup_boot_sector; + pf_u16 ext_flags; + pf_u8 media; + pf_s32 fat_type; + pf_u8 log2_bytes_per_sector; + pf_u8 log2_sectors_per_cluster; + pf_u8 num_active_FATs; + pf_u16 num_root_dir_sectors; + pf_u32 active_FAT_sector; + pf_u32 first_root_dir_sector; + pf_u32 first_data_sector; + pf_u32 num_clusters; +} PFENTRY_BPB; + +struct PF_VOLUME { + PFENTRY_BPB bpb; + pf_u32 num_free_clusters; + pf_u32 last_free_cluster; + pf_u8 file_and_directory_state[0x1f74 - 0x40]; + struct { + pf_u32 tracker_size; + pf_u32 tracker_max; + pf_u32* tracker_bits; + } tail_entry; +}; + +typedef struct PFENTRY_CONTEXT_VOLUME { + pf_u32 stat; + pf_s32 context_id; + PF_VOLUME* p_vol; +} PFENTRY_CONTEXT_VOLUME; + +typedef struct PFENTRY_VOLUME_SET { + pf_u32 flags; + pf_u32 reserved; + PF_VOLUME* current_volume; + PFENTRY_CONTEXT_VOLUME context_volumes[3]; + pf_s32 num_attached; + pf_s32 num_mounted; + pf_u32 config; + void* user_data; + pf_s32 last_error; + pf_s32 last_driver_error; + void (*code_callbacks[6])(void); + pf_u32 setting; +} PFENTRY_VOLUME_SET; + +typedef struct PFENTRY_SYS_DATE { pf_u32 sys_year, sys_month, sys_day; } PFENTRY_SYS_DATE; +typedef struct PFENTRY_SYS_TIME { pf_u32 sys_hour, sys_min, sys_sec, sys_ms; } PFENTRY_SYS_TIME; + +extern PFENTRY_VOLUME_SET pf_vol_set; +void* pf_memcpy(void* dst, void* src, pf_u32 length); +void* pf_memset(void* dst, pf_s32 c, pf_u32 length); +void PF_LE16_TO_U16_STR(pf_u8* sSrc, pf_u32 num); +pf_s32 PFPATH_cmpNameUni(const pf_u16* p_name, PF_STR* sPattern); +pf_s32 PFPATH_cmpName(const pf_s8* sShort, PF_STR* p_pattern, pf_bool is_short_search); +pf_s32 PFPATH_cmpTailSFN(const pf_s8* sfn_name, const pf_s8* pattern); +pf_s32 PFPATH_putShortName(pf_u8* pDirEntry, const pf_s8* short_name, pf_u8 attr); +pf_s32 PFPATH_getShortName(pf_s8* short_name, const pf_u8* pDirEntry, pf_u8 attr); +void PFPATH_getLongNameformShortName(pf_s8* short_name, pf_s8* long_name, pf_u8 flag); +pf_s32 PFPATH_transformInUnicode(pf_u16* sDestStr, const pf_s8* sSrcStr); +pf_s32 PFPATH_parseShortNameNumeric(pf_s8* p_char, pf_u32 count); +pf_u32 PFPATH_CheckExtShortNameSignature(PF_STR* p_str); +pf_bool PFPATH_GetExtShortNameIndex(PF_STR* p_str, pf_u32* p_index); +pf_s32 PFSEC_WriteData(PF_VOLUME* p_vol, const pf_u8* p_buf, pf_u32 sector, pf_u16 offset, pf_u32 size, pf_u32* p_success_size, pf_bool set_sig); +pf_s32 PFCACHE_AllocateDataPage(PF_VOLUME*, pf_u32, PF_CACHE_PAGE**, pf_bool*); +void PFCACHE_FreeDataPage(PF_VOLUME*, PF_CACHE_PAGE*); +pf_s32 PFCACHE_FlushDataCacheSpecific(PF_VOLUME*, void*); +pf_s32 PFFAT_InitFFD(PFENTRY_FFD*, PFENTRY_FAT_HINT*, PF_VOLUME*, pf_u32*); +pf_s32 PFFAT_GetSectorSpecified(PFENTRY_FFD*, pf_u32, pf_u32, pf_u32*); +pf_s32 PFFAT_MakeRootDir(PF_VOLUME*); +pf_s32 PFENT_ITER_IteratorInitialize(PFENTRY_ENT_ITER*, pf_u32); +pf_s32 PFENT_ITER_Advance(PFENTRY_ENT_ITER*, pf_u32); +pf_s32 PFENT_ITER_Retreat(PFENTRY_ENT_ITER*, pf_u32); +pf_bool PFENT_ITER_IsAtLogicalEnd(PFENTRY_ENT_ITER*); +void PFDRV_LoadVolumeLabelFromBuf(PF_VOLUME*, const pf_u8*); +void PFSYS_TimeStamp(PFENTRY_SYS_DATE*, PFENTRY_SYS_TIME*); +void PFENT_LoadShortNameFromBuf(PF_DIR_ENT*, const pf_u8*); +pf_u8 PFENT_CalcCheckSum(PF_DIR_ENT*); +void PFENT_loadEntryNumericFieldsFromBuf(PF_DIR_ENT*, const pf_u8*); +pf_s32 PFENT_LoadLFNEntryFieldsFromBuf(PF_DIR_ENT*, const pf_u8*); + +static void PFENT_storeShortNameToBuf(pf_u8* buf, const PF_DIR_ENT* p_ent) { + PFPATH_putShortName(buf, p_ent->short_name, p_ent->attr); + + if (*buf == 0xE5) { + *buf = 5; + } +} +pf_s32 PFENT_compareEntry(PF_DIR_ENT* p_ent, const pf_u8* buf, PF_STR* p_pattern, pf_s32 attr, + pf_u32 attr_required, pf_u32 attr_forbidden, pf_u32* p_lpos) { + pf_s32 is_match = 1; + pf_u32 is_valid = 1; + if ((attr & 15) == 15) { + is_match = 1; + } else { + if (attr == 0) attr = 0x40; + if (attr_required & 0x80) { + attr_required &= 0x7f; + attr_forbidden &= 0x7f; + if ((attr_required && (pf_s32)(attr_required & attr) != (pf_s32)attr_required) || + (attr_forbidden && (pf_s32)(attr_forbidden & attr) == (pf_s32)attr_forbidden)) is_valid = 0; + } else if (attr_required != 0x7f && (pf_u32)attr != attr_required && + (!(attr & attr_required) || (attr & attr_forbidden))) is_valid = 0; + if (is_valid == 0) { + is_match = 1; + } else { + if (attr & 8) { + p_ent->num_entry_LFNs = 0; + p_ent->long_name[0] = 0; + } + PFENT_LoadShortNameFromBuf(p_ent, buf); + if (p_ent->num_entry_LFNs && p_ent->ordinal == 1 && p_ent->check_sum == PFENT_CalcCheckSum(p_ent)) { + is_match = PFPATH_cmpNameUni(p_ent->long_name, p_pattern) != 0; + } + if (is_match == 1) { + if ((pf_vol_set.setting & 2) == 2 && !(attr & 8)) { + if (PFPATH_cmpName(p_ent->short_name, p_pattern, 0) == 0) is_match = 0; + } else { + if (PFPATH_cmpName(p_ent->short_name, p_pattern, 1) == 0) is_match = 0; + } + } + if (is_match == 1) ++*p_lpos; + } + } + return is_match; +} + +pf_s32 PFENT_getEntry(PF_DIR_ENT* p_ent, PFENTRY_ENT_ITER* p_iter, PF_STR* p_pattern, + pf_u32 attr_required, pf_u32 attr_forbidden, pf_u32* p_lpos) { + pf_s32 err; + pf_u8 attr = p_iter->buf[11]; + if (PFENT_compareEntry(p_ent, p_iter->buf, p_pattern, attr, attr_required, attr_forbidden, p_lpos) == 1) { + if ((attr & 15) == 15) { + err = PFENT_LoadLFNEntryFieldsFromBuf(p_ent, p_iter->buf); + if (err != 0) { + p_ent->num_entry_LFNs = 0; + p_ent->long_name[0] = 0; + } + } else { + p_ent->num_entry_LFNs = 0; + p_ent->long_name[0] = 0; + } + return -1; + } + if (p_ent->num_entry_LFNs == 0 && (p_iter->buf[12] & 0x18)) { + pf_s8 filename[13]; + pf_s32 length; + PFPATH_getLongNameformShortName(p_ent->short_name, filename, p_iter->buf[12]); + length = PFPATH_transformInUnicode(p_ent->long_name, filename); + p_ent->num_entry_LFNs = length / 13 + ((length % 13) != 0); + p_ent->check_sum = PFENT_CalcCheckSum(p_ent); + p_ent->ordinal = 1; + } + PFENT_loadEntryNumericFieldsFromBuf(p_ent, p_iter->buf); + p_ent->entry_sector = p_iter->sector; + p_ent->entry_offset = p_iter->offset; + if ((p_ent->attr & 0x10) && p_ent->start_cluster == 0) p_ent->start_cluster = 1; + return 0; +} +pf_s32 PFENT_searchEmptyTailSFN(PFENTRY_FFD* p_ffd, pf_u32 tail_index, const pf_s8* pattern, pf_u32* p_tail_bit) { + PFENTRY_ENT_ITER iter; + pf_u8 attr; + pf_s32 err = 0; + pf_u32 bit_pos; + pf_u32 sfn_taillen; + pf_u32 sfn_baselen; + pf_u32 i; + pf_s8 sfnbuf[13]; + pf_s8 patbuf[13]; + PF_VOLUME* p_vol = p_ffd->p_vol; + + pf_memset(p_tail_bit, 0, p_vol->tail_entry.tracker_size * 4); + iter.ffd = *p_ffd; + + for (err = PFENT_ITER_IteratorInitialize(&iter, 0); PFENT_ITER_IsAtLogicalEnd(&iter) == PF_FALSE; + err = PFENT_ITER_Advance(&iter, PF_FALSE)) { + if (err != 0) { + return err; + } + if (*iter.buf == 0) { + break; + } + if (*iter.buf != 0xE5) { + attr = iter.buf[11]; + if (((attr & (0x01 | 0x02 | 0x04 | 0x08)) != (0x01 | 0x02 | 0x04 | 0x08)) && ((attr & 8) == 0)) { + PFPATH_getShortName((pf_s8*)&sfnbuf, (pf_u8*)&iter.buf, 0); + for (sfn_taillen = 1; (sfnbuf[sfn_taillen] != 0x7E) && (sfnbuf[sfn_taillen] != 0) && (sfn_taillen < 7U); sfn_taillen++) { + } + + if (sfn_taillen < 7 && sfnbuf[sfn_taillen] == 0x7E) { + for (sfn_baselen = sfn_taillen + 1; sfnbuf[sfn_baselen] >= 0x30 && sfnbuf[sfn_baselen] <= 0x39; sfn_baselen++) { + } + + if (sfnbuf[sfn_baselen] == '.' || sfnbuf[sfn_baselen] == 0) { + i = (sfn_baselen - sfn_taillen) - 1; + bit_pos = 0; + for (; i != 0; i--) { + bit_pos *= 10; + bit_pos += (sfnbuf[sfn_baselen - i]) - 0x30; + } + + pf_strcpy((pf_s8*)&patbuf, pattern); + PFPATH_parseShortNameNumeric((pf_s8*)&patbuf, bit_pos); + if (PFPATH_cmpTailSFN((pf_s8*)&sfnbuf, (pf_s8*)&patbuf) == 0 && bit_pos >= tail_index && + bit_pos < (tail_index + (p_vol->tail_entry.tracker_size << 5))) { + bit_pos -= tail_index; + p_tail_bit[bit_pos >> 5] |= 1 << bit_pos; + } + } + } + } + } + } + + return 0; +} + +pf_s32 PFENT_findEmptyTailSFN(PF_DIR_ENT* p_ent_containig_dir, const pf_s8* name, pf_u32* p_tails) { + PFENTRY_FFD ffd; + PFENTRY_FAT_HINT hint; + pf_s32 err; + pf_u32 num; + PF_VOLUME* p_vol = p_ent_containig_dir->p_vol; + pf_u32 track_num; + + *p_tails = 1; + PFFAT_InitFFD(&ffd, &hint, p_ent_containig_dir->p_vol, &p_ent_containig_dir->start_cluster); + + for (num = 1; num <= (1000000 - 1); num += p_vol->tail_entry.tracker_size << 5) { + err = PFENT_searchEmptyTailSFN(&ffd, num, name, p_vol->tail_entry.tracker_bits); + if (err != 0) { + return err; + } + + for (track_num = 0; track_num < p_vol->tail_entry.tracker_size; track_num += 1) { + if (p_vol->tail_entry.tracker_bits[track_num] != -1) { + for (; (p_vol->tail_entry.tracker_bits[track_num] & 1) != 0; p_vol->tail_entry.tracker_bits[track_num] >>= 1, (*p_tails)++) { + } + num = 1000000; + break; + } else { + *p_tails += 0x20; + } + } + } + return 0; +} + +pf_u8 PFENT_CalcCheckSum(PF_DIR_ENT* p_ent) { + pf_u16 i; + pf_u8 sum; + pf_u8 buf[13]; + + PFPATH_putShortName((pf_u8*)buf, p_ent->short_name, 0); + + sum = 0; + for (i = 0; i < 11; i++) { + sum = ((sum & 1) != 0 ? 0x80 : 0) + (sum >> 1) + buf[i]; + } + return sum; +} + +void PFENT_LoadShortNameFromBuf(PF_DIR_ENT* p_ent, const pf_u8* buf) { + PFPATH_getShortName(p_ent->short_name, buf, buf[11]); + if (p_ent->short_name[0] == 5) { + p_ent->short_name[0] = -0x1B; + } +} + +void PFENT_loadEntryNumericFieldsFromBuf(PF_DIR_ENT* p_ent, const pf_u8* buf) { + p_ent->attr = buf[0xB]; + p_ent->small_letter_flag = buf[0xC]; + p_ent->create_time_ms = buf[0xD]; + p_ent->create_time = PF_SWAP_16(*(pf_u16*)&buf[0xE]); + p_ent->create_date = PF_SWAP_16(*(pf_u16*)&buf[0x10]); + p_ent->access_date = PF_SWAP_16(*(pf_u16*)&buf[0x12]); + p_ent->modify_time = PF_SWAP_16(*(pf_u16*)&buf[0x16]); + p_ent->modify_date = PF_SWAP_16(*(pf_u16*)&buf[0x18]); + p_ent->file_size = PF_SWAP_32(*(pf_u32*)&buf[0x1C]); + p_ent->start_cluster = ((pf_u16)PF_SWAP_16(*(pf_u16*)&buf[0x14]) << 16) | (pf_u16)(PF_SWAP_16(*(pf_u16*)&buf[0x1A])); +} + +void PFENT_StoreEntryNumericFieldsToBuf(pf_u8* buf, const PF_DIR_ENT* p_ent) { + buf[0x0B] = p_ent->attr; + buf[0x0C] = p_ent->small_letter_flag; + buf[0x0D] = p_ent->create_time_ms; + *(pf_u16*)&buf[0x0E] = PF_SWAP_16(p_ent->create_time); + *(pf_u16*)&buf[0x10] = PF_SWAP_16(p_ent->create_date); + *(pf_u16*)&buf[0x12] = PF_SWAP_16(p_ent->access_date); + *(pf_u16*)&buf[0x16] = PF_SWAP_16(p_ent->modify_time); + *(pf_u16*)&buf[0x18] = PF_SWAP_16(p_ent->modify_date); + *(pf_u16*)&buf[0x14] = PF_SWAP_16((pf_u16)(p_ent->start_cluster >> 16)); + *(pf_u16*)&buf[0x1A] = PF_SWAP_16((pf_u16)(p_ent->start_cluster)); + *(pf_u32*)&buf[0x1C] = PF_SWAP_32(p_ent->file_size); +} + +pf_s32 PFENT_LoadLFNEntryFieldsFromBuf(PF_DIR_ENT* p_ent, const pf_u8* buf) { + pf_u8 ordinal; + pf_u8 check_sum; + pf_u32 is_last_LFN_ent; + pf_u8* p; + pf_u16* q; + pf_u16* q_after; + + ordinal = buf[0]; + check_sum = buf[13]; + if ((ordinal & ~0x40U) > 0x14U) { + p_ent->ordinal = 0; + p_ent->check_sum = 0; + p_ent->num_entry_LFNs = 0; + return 33; + } + if ((buf[0] & 0x40) != 0) { + ordinal &= ~0x40; + p_ent->num_entry_LFNs = 0; + is_last_LFN_ent = 1; + } else { + is_last_LFN_ent = 0; + if (p_ent->num_entry_LFNs == 0) return 33; + if (ordinal != p_ent->ordinal - 1 || check_sum != p_ent->check_sum) { + p_ent->ordinal = 0; + p_ent->check_sum = 0; + p_ent->num_entry_LFNs = 0; + return 33; + } + } + p_ent->ordinal = ordinal; + p_ent->check_sum = check_sum; + p = (pf_u8*)p_ent->long_name; + p += (ordinal - 1) * 0x1A; + pf_memcpy(&p[0x0], (pf_s8*)&buf[0x1], 10); + pf_memcpy(&p[10], (pf_s8*)&buf[0xE], 0xC); + pf_memcpy(&p[0x16], (pf_s8*)&buf[0x1C], 4U); + PF_LE16_TO_U16_STR(&p[0x0], 10); + PF_LE16_TO_U16_STR(&p[10], 0xC); + PF_LE16_TO_U16_STR(&p[0x16], 4U); + if (is_last_LFN_ent != 0) { + ((pf_u16*)p)[13] = 0; + q = (pf_u16*)p; + q_after = (pf_u16*)&p[0x1A]; + for (; q < q_after; q++) { + if (*q == 0) { + q++; + break; + } + } + + for (; q < q_after; q++) { + if (*q != 0xFFFF) { + p_ent->num_entry_LFNs = 0; + return 33; + } + } + } + p_ent->num_entry_LFNs++; + return 0; +} + +void PFENT_storeLFNEntryFieldsToBuf(pf_u8* buf, PF_DIR_ENT* p_ent, pf_u8 ord, pf_u8 sum, pf_bool is_last) { + pf_u8* p_seg; + pf_u16* p; + pf_u16* p_after; + + if (is_last) { + *buf = ord | 0x40; + } else { + *buf = ord; + } + buf[0xB] = (0x01 | 0x02 | 0x04 | 0x08); + buf[0xD] = sum; + buf[0xC] = 0; + *(pf_u16*)&buf[0x1A] = 0; + p_seg = (pf_u8*)p_ent->long_name; + p_seg += (ord - 1) * 0x1A; + if (is_last != 0) { + p = (pf_u16*)p_seg; + p_after = (pf_u16*)&p_seg[0x1A]; + for (; p < p_after; p++) { + if (*p == 0x0000) { + p++; + break; + } + } + + for (; p < p_after; p++) { + *p = 0xFFFF; + } + } + pf_memcpy(&buf[1], p_seg, 10); + pf_memcpy(&buf[0xE], &p_seg[10], 0xC); + pf_memcpy(&buf[0x1C], &p_seg[0x16], 4); + PF_LE16_TO_U16_STR(&buf[1], 10); + PF_LE16_TO_U16_STR(&buf[0xE], 0xC); + PF_LE16_TO_U16_STR(&buf[0x1C], 4); +} + +pf_s32 PFENT_findEntryPos(PFENTRY_FFD* p_ffd, PF_DIR_ENT* p_ent, pf_u32 index_search_from, PF_STR* p_pattern, + pf_u32 attr_required, pf_u32 attr_forbidden, pf_u32* p_lpos, pf_u32* p_ppos) { + pf_s32 err; + PFENTRY_ENT_ITER iter; + pf_u32 lpos; + pf_bool is_extsfn = 0; + *p_lpos = 0; + *p_ppos = 0; + p_ent->num_entry_LFNs = 0; + p_ent->ordinal = 0; + p_ent->check_sum = 0; + p_ent->long_name[0] = 0; + lpos = 0; + if ((pf_vol_set.setting & 2) == 2) is_extsfn = PFPATH_GetExtShortNameIndex(p_pattern, &index_search_from); + iter.ffd = *p_ffd; + if (is_extsfn == 1) { + err = PFENT_ITER_IteratorInitialize(&iter, index_search_from - 1); + { + if (err != 0) { + *p_lpos = 999999; + *p_ppos = 999999; + return err; + } + if (PFENT_getEntry(p_ent, &iter, p_pattern, attr_required, attr_forbidden, &lpos) == 0) { + *p_lpos = 999999; + *p_ppos = 999999; + return 3; + } + if (iter.buf[0] & 0x40) { + err = PFENT_ITER_IteratorInitialize(&iter, index_search_from); + if (err != 0) { + *p_lpos = 999999; + *p_ppos = 999999; + return err; + } + if (PFENT_getEntry(p_ent, &iter, p_pattern, attr_required, attr_forbidden, &lpos) == 0) { + p_ent->p_vol = p_ffd->p_vol; + *p_lpos = lpos; + *p_ppos = iter.index; + return 0; + } + } + } + } else { + for (err = PFENT_ITER_IteratorInitialize(&iter, index_search_from); !PFENT_ITER_IsAtLogicalEnd(&iter); err = PFENT_ITER_Advance(&iter, 0)) { + if (err != 0) { + *p_lpos = 999999; + *p_ppos = 999999; + return err; + } + if (iter.buf[0] == 0) break; + if (iter.buf[0] == 0xe5) { + p_ent->num_entry_LFNs = 0; + p_ent->long_name[0] = 0; + } else if (PFENT_getEntry(p_ent, &iter, p_pattern, attr_required, attr_forbidden, &lpos) == 0) { + p_ent->p_vol = p_ffd->p_vol; + *p_lpos = lpos; + *p_ppos = iter.index; + return 0; + } + } + } + *p_lpos = 999999; + *p_ppos = 999999; + return 3; +} + +pf_s32 PFENT_findEntry(PFENTRY_FFD* p_ffd, PF_DIR_ENT* p_ent, pf_u32 index_search_from, PF_STR* p_pattern, + pf_u32 attr_required, pf_u32 attr_forbidden) { + pf_u32 lpos; + pf_u32 ppos; + return PFENT_findEntryPos(p_ffd, p_ent, index_search_from, p_pattern, attr_required, attr_forbidden, &lpos, &ppos); +} + +pf_s32 PFENT_allocateEntryPos(PF_DIR_ENT* p_ent, pf_u32 num_entries, PFENTRY_FFD* p_ffd, pf_u32* p_prev_chain, + PF_STR* p_filename, pf_u32* p_pos) { + pf_s32 err; + PFENTRY_ENT_ITER iter; + PF_DIR_ENT current_ent; + PF_VOLUME* p_vol; + pf_u32 next_sector; + pf_u32 logical_scratch; + pf_u32 saved_sector; + pf_u16 saved_offset; + pf_u32 current_sector; + pf_u32 previous_sector0; + pf_u32 previous_sector1; + pf_bool is_found; + pf_u32 num_free_entries; + pf_u32 logical_position; + if ((pf_vol_set.setting & 2) == 2 && PFPATH_CheckExtShortNameSignature(p_filename) == 1) return 1; + p_vol = p_ffd->p_vol; + saved_sector = -1U; + p_prev_chain[0] = p_prev_chain[1] = saved_sector; + num_free_entries = 0; + logical_position = 0; + saved_offset = 0; + current_sector = -1U; + previous_sector1 = -1U; + previous_sector0 = -1U; + is_found = 0; + iter.sector = 0; + iter.index = 0; + iter.ffd = *p_ffd; + for (err = PFENT_ITER_IteratorInitialize(&iter, 0);; err = PFENT_ITER_Advance(&iter, 1)) { + if (err != 0) { + if (err == 16) break; + return err; + } + if (iter.sector == -1U) break; + if (is_found == 0 && num_free_entries == 0) { + saved_offset = iter.offset; + saved_sector = iter.sector; + current_sector = iter.sector; + } + if (is_found == 0) { + if (iter.buf[0] == 0 || iter.buf[0] == 0xe5) { + if (current_sector != iter.sector) { + pf_bool is_first = previous_sector0 == -1U; + if (is_first) previous_sector0 = iter.sector; + if (!is_first) previous_sector1 = iter.sector; + current_sector = iter.sector; + } + ++num_free_entries; + } else { + num_free_entries = 0; + previous_sector0 = -1U; + previous_sector1 = -1U; + } + } + if (num_free_entries >= num_entries) { + if (is_found == 0) { + logical_position = iter.index; + is_found = 1; + } + if (iter.buf[0] == 0) break; + } + if (iter.buf[0] != 0 && iter.buf[0] != 0xe5 && PFENT_getEntry(¤t_ent, &iter, p_filename, 0x7f, 0, &logical_scratch) == 0) { + *p_ent = current_ent; + p_ent->p_vol = p_ffd->p_vol; + return 8; + } + if (iter.offset + 32 == p_vol->bpb.bytes_per_sector) { + err = PFFAT_GetSectorSpecified(p_ffd, iter.file_sector_index + 1, 0, &next_sector); + if (err != 0) return err; + if (next_sector == -1U && is_found == 1) break; + } + } + if (is_found == 0) return 5; + p_prev_chain[0] = previous_sector0; + p_prev_chain[1] = previous_sector1; + p_ent->entry_sector = saved_sector; + p_ent->entry_offset = saved_offset; + *p_pos = logical_position; + return 0; +} + +pf_s32 PFENT_allocateEntry(PF_DIR_ENT* p_ent, pf_u32 num_entries, PFENTRY_FFD* p_ffd, pf_u32* p_prev_chain, PF_STR* p_filename) { + pf_u32 position; + return PFENT_allocateEntryPos(p_ent, num_entries, p_ffd, p_prev_chain, p_filename, &position); +} + +pf_s32 PFENT_GetRootDir(PF_VOLUME* p_vol, PF_DIR_ENT* p_ent) { + p_ent->long_name[0] = 0x5C; + p_ent->long_name[1] = 0; + p_ent->num_entry_LFNs = 0; + p_ent->ordinal = 0; + p_ent->check_sum = 0; + p_ent->short_name[0] = 0x5C; + p_ent->short_name[1] = 0; + p_ent->small_letter_flag = 0; + p_ent->attr = 0x10; + p_ent->create_time_ms = 0; + p_ent->create_time = 0; + p_ent->create_date = 0; + p_ent->access_date = 0; + p_ent->modify_time = 0; + p_ent->modify_date = 0; + p_ent->file_size = 0; + p_ent->p_vol = p_vol; + p_ent->path_len = 3; + p_ent->start_cluster = 1; + p_ent->entry_sector = -1; + p_ent->entry_offset = 0; + return 0; +} +pf_s32 PFENT_MakeRootDir(PF_VOLUME* p_vol) { + PF_CACHE_PAGE* p_page; + pf_u32 sector; + pf_u32 success_size; + pf_bool hit; + pf_s32 err; + switch (p_vol->bpb.fat_type) { + case FAT_32: + PFFAT_MakeRootDir(p_vol); + break; + case FAT_12: + case FAT_16: + err = PFCACHE_AllocateDataPage(p_vol, -1U, &p_page, &hit); + if (err != 0) return err; + pf_memset(p_page->p_buf, 0, p_vol->bpb.bytes_per_sector); + for (sector = p_vol->bpb.first_root_dir_sector; sector < p_vol->bpb.first_data_sector; ++sector) { + err = PFSEC_WriteData(p_vol, p_page->p_buf, sector, 0, p_vol->bpb.bytes_per_sector, &success_size, 0); + if (err != 0) { + PFCACHE_FreeDataPage(p_vol, p_page); + return err; + } + if (success_size != p_vol->bpb.bytes_per_sector) { + PFCACHE_FreeDataPage(p_vol, p_page); + return 17; + } + } + PFCACHE_FreeDataPage(p_vol, p_page); + break; + default: + return 7; + } + PFDRV_LoadVolumeLabelFromBuf(p_vol, (pf_u8*)"NO NAME "); + return 0; +} + +pf_s32 PFENT_updateEntry(PF_DIR_ENT* p_ent, pf_u32 flag) { + PF_VOLUME* p_vol; + pf_u32 success_size; + pf_u8 buf[32]; + pf_s32 err; + + p_vol = p_ent->p_vol; + if (p_ent->start_cluster == 1) { + return 0xE; + } + if (flag == 1) { + p_ent->attr |= (pf_u8)0x20; + } + PFENT_storeShortNameToBuf(buf, p_ent); + PFENT_StoreEntryNumericFieldsToBuf(buf, p_ent); + err = PFSEC_WriteData(p_vol, buf, p_ent->entry_sector, p_ent->entry_offset, 32, &success_size, 0U); + if (err != 0) { + return err; + } + if (success_size != 0x20) { + return 0x11; + } + + return 0; +} +pf_s32 PFENT_AdjustSFN(PF_DIR_ENT* p_ent, pf_s8* p_short_name) { + pf_u32 i = 0; + pf_u32 tail_num; + pf_s32 err = 0; + + for (i = 1; (p_short_name[i] != 0x7E) && (p_short_name[i] != 0) && (i < 7U); i++) { + } + if ((i < 7U) && (p_short_name[i] == 0x7E)) { + for (i++; (p_short_name[i] >= 0x30) && (p_short_name[i] <= 0x39); i++) { + } + if ((p_short_name[i] == '.') || (p_short_name[i] == 0)) { + err = PFENT_findEmptyTailSFN(p_ent, p_short_name, &tail_num); + if (err != 0) { + return err; + } + if (tail_num != 1) { + PFPATH_parseShortNameNumeric(p_short_name, tail_num); + } + } + } + + return 0; +} +pf_u8 PFENT_getcurrentDateTimeForEnt(pf_u16* p_date, pf_u16* p_time) { + PFENTRY_SYS_DATE sys_date; + PFENTRY_SYS_TIME sys_time; + + PFSYS_TimeStamp(&sys_date, &sys_time); + *p_date = ((sys_date.sys_day & 0x1F) | ((sys_date.sys_month << 5) & 0x1E0)) | (((sys_date.sys_year - 0x7BC) << 9) & 0xFE00); + *p_time = (((sys_time.sys_sec >> 1) & 0x1F) | ((sys_time.sys_min << 5) & 0x7E0)) | ((sys_time.sys_hour << 0xB) & 0xF800); + + return sys_time.sys_ms; +} +pf_s32 PFENT_RemoveEntry(PF_DIR_ENT* p_ent, PFENTRY_ENT_ITER* p_iter) { + pf_u32 success_size; + pf_s32 err = 0; + pf_u32 entry_sector; + pf_u16 entry_offset; + pf_u32 i; + PF_VOLUME* p_vol = PF_NULL; + const pf_u8 dir_fb_free[1] = {0xE5}; + + p_vol = p_ent->p_vol; + entry_sector = p_ent->entry_sector; + entry_offset = p_ent->entry_offset; + if ((p_ent->num_entry_LFNs != 0) && ((p_ent->small_letter_flag & 0x18) == 0)) { + for (i = 1; i <= p_ent->num_entry_LFNs; i++) { + err = PFENT_ITER_Retreat(p_iter, 0); + if (err != 0) { + return err; + } + entry_sector = p_iter->sector; + entry_offset = p_iter->offset; + err = PFSEC_WriteData(p_vol, (pf_u8*)&dir_fb_free, entry_sector, entry_offset, 1, &success_size, 0); + if (err != 0) { + return err; + } + if (success_size != 1) { + return 17; + } + } + } + err = PFSEC_WriteData(p_vol, (pf_u8*)&dir_fb_free, p_ent->entry_sector, p_ent->entry_offset, 1, &success_size, 0); + if (err != 0) { + return err; + } + if (success_size != 1) { + return 17; + } + err = PFCACHE_FlushDataCacheSpecific(p_vol, PF_NULL); + if (err != 0) { + return err; + } + return 0; +} diff --git a/tools/decomp-assist/fa_pf_cluster_attempts.md b/tools/decomp-assist/fa_pf_cluster_attempts.md new file mode 100644 index 00000000..764e9edf --- /dev/null +++ b/tools/decomp-assist/fa_pf_cluster_attempts.md @@ -0,0 +1,26 @@ +# fa/pf_cluster matching attempts + +All eight functions are implemented. The five exact functions have zero instruction differences. The three open functions have identical instruction counts to the target and differ in register allocation or arithmetic scheduling. The unit has no target data section. + +## PFCLUSTER_CombineFiles (207 instructions) + +1. Initial C reconstruction: 206 instructions; swapped stack addresses and one missing branch in the second spare-chain selection. +2. Separate second-chain selection assignment, reversed stack declarations, and grouped cluster totals: 207 instructions, four differences in the overflow comparison's registers and addition order. Retained. +3. Explicit total-cluster temporary, then an explicit maximum-cluster temporary: seven differences in the same comparison; the compiler retained different temporary registers. +4. Reversed temporary initialization order: seven differences; restored attempt 2. + +## PFCLUSTER_InsertCluster (126 instructions) + +1. Initial C reconstruction: 28 register differences; stack locations and instruction count match. Retained. +2. Reused the incoming cluster count as the allocation-loop byte count: the same 28 differences. +3. Copied the incoming count to an allocation local before the first call: 29 differences, including changed argument scheduling; no improved register assignment. +4. Initialized the allocation count before tracing and removed the loop initializer: 36 differences, with the same total instruction count; restored attempt 1. + +## PFCLUSTER_DeleteCluster (108 instructions) + +1. Initial C reconstruction: 51 differences, including reversed stack locations and saved-register assignments. +2. Reordered output locals, moved volume before size locals, and reused the incoming count for the deletion byte count: 35 register differences; all stack locations and instruction count match. Retained. +3. Reversed the volume/size declaration order: 42 register differences; no instruction-count improvement. +4. Scoped the size computations in a nested block with a separate deletion-size local: 35 differences, with a different count register; restored attempt 2. + +The forbidden-pattern scan initially classified the real FAT spare-chain variables as dummy objects because their inherited names contained `unused`. Renamed them to `spare`; these variables are consumed by chain tracing and freeing. -- 2.49.1 From b983deeb07ec8989d0814a9eb54b1804308b541d Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:23:10 -0500 Subject: [PATCH 3/5] tiHKBManager: 24/29 functions (worker 2e1dbe5d) (#325) --- README.md | 4 +- src/keyboard/tiHKBManager.cpp | 61 ++++++---------- tools/decomp-assist/tiHKBManager.attempts.md | 74 +++++++++++++++++++- 3 files changed, 97 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 1e699365..f932065b 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 85.47% | 75.70% | 56.76% | 86.72% | +| 85.47% | 75.72% | 56.76% | 86.72% | -units 748/1027 complete, functions 11024/12563 matched. +units 748/1027 complete, functions 11027/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/src/keyboard/tiHKBManager.cpp b/src/keyboard/tiHKBManager.cpp index e858331f..39fba930 100644 --- a/src/keyboard/tiHKBManager.cpp +++ b/src/keyboard/tiHKBManager.cpp @@ -22,13 +22,12 @@ namespace input { HKBManager HKBManager::sInstance; // KBD callbacks encode the device in the first byte of the opaque pointer value. -union LedCallbackData { - void* pointer; - u8 device; - struct { +struct LedCallbackData { + union { + void* pointer; u8 device; - u32 leds; - } request; + }; + u32 leds; }; void HKBManager::SetLedCB(_KBDEc result, void* userData) { @@ -36,9 +35,8 @@ void HKBManager::SetLedCB(_KBDEc result, void* userData) { LedCallbackData received; received.pointer = userData; LedCallbackData callback; - callback.request.device = received.device; - callback.request.leds = 0; - const u8 leds = callback.request.leds; + callback.device = received.device; + const u8 leds = callback.leds = 0; u32 interrupts = OSDisableInterrupts(); u32 mask = 1 << received.device; sInstance.retryDevices &= ~mask; @@ -59,9 +57,8 @@ void HKBManager::KBDListenerOwn::OnAttach(KBDDevEvent* event) { device = event->device; owner = manager; LedCallbackData callback; - callback.request.device = device; - callback.request.leds = 0; - const u8 leds = callback.request.leds; + callback.device = device; + const u8 leds = callback.leds = 0; u32 interrupts = OSDisableInterrupts(); u32 mask = 1 << device; owner->retryDevices &= ~mask; @@ -244,9 +241,8 @@ void HKBManager::Update() { mask = 1 << shiftIndex; if ((retryDevices & mask) != 0) { LedCallbackData callback; - callback.request.device = static_cast(device); - callback.request.leds = 0; - const u8 leds = callback.request.leds; + callback.device = static_cast(device); + const u8 leds = callback.leds = 0; u32 interrupts = OSDisableInterrupts(); retryDevices &= ~mask; OSRestoreInterrupts(interrupts); @@ -329,22 +325,10 @@ void HKBManager::KeyState_::Update() { u32 interrupts = OSDisableInterrupts(); previous = current; current = pending; - previousKeys[0] = currentKeys[0]; - currentKeys[0] = pendingKeys[0]; - previousKeys[1] = currentKeys[1]; - currentKeys[1] = pendingKeys[1]; - previousKeys[2] = currentKeys[2]; - currentKeys[2] = pendingKeys[2]; - previousKeys[3] = currentKeys[3]; - currentKeys[3] = pendingKeys[3]; - previousKeys[4] = currentKeys[4]; - currentKeys[4] = pendingKeys[4]; - previousKeys[5] = currentKeys[5]; - currentKeys[5] = pendingKeys[5]; - previousKeys[6] = currentKeys[6]; - currentKeys[6] = pendingKeys[6]; - previousKeys[7] = currentKeys[7]; - currentKeys[7] = pendingKeys[7]; + for (u32 slot = 0; slot < 8; slot++) { + previousKeys[slot] = currentKeys[slot]; + currentKeys[slot] = pendingKeys[slot]; + } OSRestoreInterrupts(interrupts); UpdateModState_(); u32 bit; @@ -448,8 +432,8 @@ u8 HKBManager::KeySet::GetKey() const { } u32 HKBManager::KeySet::GetWChar() const { - u32 code = GetVCode(); - if ((code & 0xffff) >= 0xf130 && (code & 0xffff) <= 0xf139) { + s32 code = GetVCode(); + if (static_cast(code) >= 0xf130 && static_cast(code) <= 0xf139) { code = code - 0xf100 & 0xffff; } else { u32 lowCode = code & 0xffff; @@ -457,24 +441,25 @@ u32 HKBManager::KeySet::GetWChar() const { code = 0xf1cd; } else if (lowCode >= 0xf100 && lowCode <= 0xf13f) { code = code - 0xf100 & 0xffff; - } else if ((code & 0xffff) >= 0xf140 && (code & 0xffff) <= 0xf17f) { + } else if ((static_cast(code) & 0xffff) >= 0xf140 && (static_cast(code) & 0xffff) <= 0xf17f) { code = code + 0x40 & 0xffff; } } u16 character = code; if ((character & 0xf000) == 0xf000) { code = 0; - } else if ((code & 0xffff) == 0xeeee) { + } else if ((static_cast(code) & 0xffff) == 0xeeee) { code = 0; - } else if ((code & 0xffff) < 0x20) { + } else if ((static_cast(code) & 0xffff) < 0x20) { code = 0; } + u32 index = 0; const HKBManager* owner = manager; if (owner->allowedCharacters == 0) return code; u32 count = owner->allowedCharacterCount; if (count == 0) return code; - for (u32 index = 0; index < count; index++) { - if ((code & 0xffff) == owner->allowedCharacters[index]) return code; + for (; index < count; index++) { + if ((static_cast(code) & 0xffff) == owner->allowedCharacters[index]) return code; } return 0; } diff --git a/tools/decomp-assist/tiHKBManager.attempts.md b/tools/decomp-assist/tiHKBManager.attempts.md index 1ea6c144..16eda518 100644 --- a/tools/decomp-assist/tiHKBManager.attempts.md +++ b/tools/decomp-assist/tiHKBManager.attempts.md @@ -5,7 +5,7 @@ The pool is empty and identical from the first object build. All fields and calls use typed keyboard declarations. Only TIHKBMANAGER_IMPLEMENTATION selects the added layouts; existing keyboard guard branches remain unchanged. -## Remaining functions, in object order +## First pass attempts, in object order ### SetLedCB 1. Initialized pointer union followed by device byte: 41/41 instructions, @@ -76,7 +76,7 @@ the added layouts; existing keyboard guard branches remain unchanged. 5. Inline the same CheckValidity helper used by GetKey/GetVCode: 70/70, 12 differences, retained. Index/device registers are exchanged. -## Exact functions +## First pass exact functions All other functions are C++ and instruction-exact. Important successful changes: sequential Clear stores; callback traversal compares its next node @@ -104,3 +104,73 @@ Changed files: - include/keyboard/tiHKBManager.h - libs/RVL_SDK/include/revolution/kbd.h - tools/decomp-assist/tiHKBManager.attempts.md + +## Continuation at 21/29 exact + +Baseline code 3664/6116, data 292/292. The empty string pool remains identical. +The five still-open functions were visited closest first; each has at least +three new source variations in this pass. + +### KeyState_::UpdateModState_ — still open +1. Signed loop counter: 104/104 instructions, same seven register differences. +2. Initialize key mask and widened byte slot in one declaration each: + 104/104, ten differences. +3. Hoist key mask and byte slot outside the loop: 104/104, ten differences. +Retained the original seven-difference version. + +### KeySet::IsValid — still open +1. Direct validity body with the shifted bit as the left operand: + 70/70, 18 register differences. +2. Declare the signed index before the owner alias: 70/70, 12 differences. +3. Widen device/index to signed words and compare device as unsigned: + 70/70, 14 differences. +Retained the shared CheckValidity helper, 12 differences. + +### KBDListenerOwn::OnDetach — still open +1. Widen device to u32: 22/22, four register differences, unchanged. +2. Inline DetachDevice helper combining attached flag and state clearing: + 22/22, five differences. +3. Name the state reference inside that helper before flag clearing: + 22/22, six differences. +Removed the experimental helper and retained the four-difference version. + +### KeyState_::Update — still open +1. Replace the eight explicit key snapshots with a normal loop: + 183/183, same 44 register differences. Retained for readability. +2. Signed event/repeat loop index: 183/183, same 44 differences. +3. Local bit temporaries and negated unchanged-key predicates: + 183/183, 47 differences. + +### KeySet::GetWChar — improved, still open +1. Signed virtual code with explicitly unsigned mask comparisons: + 76/77 instructions, one repeated narrowing still absent. +2. Inline normalization helper returning each normalized value: + 75/77, unchanged from baseline. +3. u16 intermediate character and do/while whitelist traversal: + 74/77, rejected. +4. Distinguish the initial 16-bit key range from the signed normalization + intermediate and subsequent unsigned masks: 77/77, nine whitelist-loop + register differences. Retained. +5. Hoist whitelist index declaration: 77/77, unchanged. +6. Initialize that index before the owner alias: 77/77, unchanged. +7. Signed whitelist index: 77/77, unchanged. +8. Count down remaining whitelist entries: 76/77, rejected. +9. Unsigned main code and signed normalization intermediate: + 77/77, same nine differences, rejected in favor of attempt 4. + +### LED operations — three new exact functions +1. Widen the asynchronous LED argument and snapshot to u32: + SetLedCB 41/41 with two differences, OnAttach 61/61 with three, + HKBManager::Update 55/55 with three. +2. Move the LED mask outside the opaque-pointer/device union, making the + request a struct: identical differences and counts. +3. Snapshot the value assigned when clearing the request's LED mask: + all three functions reach zero differences. +4. Restore the original byte API argument and byte snapshot: + all three remain exact, without emitted LED constant objects. +The mask field supplies the call argument through the assignment result; +there is no separate literal argument or unused request-mask initialization. + +Data sections remain 100%. No shared header changes are retained in this +continuation. A quick gate reports 24/29 exact, code 4292/6116, +data 292/292, fuzzy 99.7057, and zero regressions or source warnings. -- 2.49.1 From df54d9a3482ad28146665832dc615c0aafb9af80 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:27:26 -0500 Subject: [PATCH 4/5] NWC24Mime 8/16, NWC24MsgSubject 5/12 (worker fd8d384c) (#326) --- README.md | 4 +- .../include/revolution/nwc24/NWC24MsgBoard.h | 4 + libs/RevoEX/src/nwc24/NWC24Mime.c | 787 ++++++++++++++++ libs/RevoEX/src/nwc24/NWC24MsgSubject.c | 855 ++++++++++++++++++ tools/decomp-assist/NWC24Mime.attempts.md | 77 ++ .../decomp-assist/NWC24MsgSubject.attempts.md | 100 ++ 6 files changed, 1825 insertions(+), 2 deletions(-) create mode 100644 libs/RevoEX/src/nwc24/NWC24Mime.c create mode 100644 libs/RevoEX/src/nwc24/NWC24MsgSubject.c create mode 100644 tools/decomp-assist/NWC24Mime.attempts.md create mode 100644 tools/decomp-assist/NWC24MsgSubject.attempts.md diff --git a/README.md b/README.md index f932065b..4be03c0f 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 85.47% | 75.72% | 56.76% | 86.72% | +| 85.82% | 75.85% | 56.76% | 86.74% | -units 748/1027 complete, functions 11027/12563 matched. +units 748/1027 complete, functions 11040/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RevoEX/include/revolution/nwc24/NWC24MsgBoard.h b/libs/RevoEX/include/revolution/nwc24/NWC24MsgBoard.h index 20173025..51c649b7 100644 --- a/libs/RevoEX/include/revolution/nwc24/NWC24MsgBoard.h +++ b/libs/RevoEX/include/revolution/nwc24/NWC24MsgBoard.h @@ -104,8 +104,12 @@ NWC24Err NWC24ReadMsgMBOptOutFlag(const NWC24MsgObj* msg, BOOL* mbOptOutFlag, u3 NWC24Err NWC24ReadMsgFromAddr(const NWC24MsgObj* msg, char* addr, u32 addrLen); NWC24Err NWC24ReadMsgSubject(const NWC24MsgObj* msg, char* subject, u32 subjectLen); NWC24Err NWC24ReadMsgText(const NWC24MsgObj* msg, char* text, u32 textLen, NWC24Charset* charset, NWC24Encoding* encoding); +#ifdef NWC24_MSG_SUBJECT +NWC24Err NWC24ReadMsgTextEx(const NWC24MsgObj* msg, char* text, u32 textLen, char* name, u32 nameLen); +#else NWC24Err NWC24ReadMsgTextEx(const NWC24MsgObj* msg, char* text, u32 textLen, const char* name, u32 nameLen, NWC24Charset* charset, NWC24Encoding* encoding); +#endif NWC24Err NWC24ReadMsgAttached(const NWC24MsgObj* msg, u32 attachIndex, u8* attachData, u32 attachSize); NWC24Err NWC24ReadMsgSubjectPublic(const NWC24MsgObj* msg, u16* subject, u32* subjectLen, NWC24EncodingRegion encRegion, u16 unk, u8* work, diff --git a/libs/RevoEX/src/nwc24/NWC24Mime.c b/libs/RevoEX/src/nwc24/NWC24Mime.c new file mode 100644 index 00000000..94b4a9af --- /dev/null +++ b/libs/RevoEX/src/nwc24/NWC24Mime.c @@ -0,0 +1,787 @@ +#include +#include + +static const char* MIMEEncStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + +static NWC24Err Base64Encode(u8* decoded, int decodedSize, u32* stringSize, u8* encoded, int encodedSize, u32* encodedSizeOut) { + NWC24Err result = NWC24_OK; + s32 textIdx; + s32 dataIdx = 0; + BOOL hasThird; + BOOL hasSecond; + u32 combined; + + for (textIdx = 0; dataIdx < decodedSize; dataIdx += 3) { + if (textIdx + 3 >= encodedSize) { + result = NWC24_ERR_OVERFLOW; + break; + } + + hasThird = FALSE; + hasSecond = FALSE; + + combined = (u32)decoded[dataIdx] << 8; + + if (dataIdx + 1 < decodedSize) { + hasSecond = TRUE; + combined |= (u8)decoded[dataIdx + 1]; + } + + combined <<= 8; + + if (dataIdx + 2 < decodedSize) { + hasThird = TRUE; + combined |= (u8)decoded[dataIdx + 2]; + } + + encoded[textIdx + 0] = MIMEEncStr[combined >> 18 & (64 - 1)]; + encoded[textIdx + 1] = MIMEEncStr[combined >> 12 & (64 - 1)]; + encoded[textIdx + 2] = MIMEEncStr[hasSecond ? (combined >> 6 & (64 - 1)) : 64]; + encoded[textIdx + 3] = MIMEEncStr[hasThird ? (combined & (64 - 1)) : 64]; + + textIdx += 4; + } + + *encodedSizeOut = textIdx; + + if (stringSize != NULL) { + textIdx = decodedSize; + + if (decodedSize < dataIdx) { + dataIdx = decodedSize; + } + + *stringSize = dataIdx; + } + + return result; +} + +NWC24Err NWC24Base64Encode(u8* decoded, int decodedSize, u8* encoded, int encodedSize, u32* stringSize) { + return Base64Encode(decoded, decodedSize, NULL, encoded, encodedSize, stringSize); +} + +NWC24Err NWC24Base64Decode(u8* encoded, int encodedSize, u8* decoded, int decodedSize, u32* stringSize) { + int bitCount = 0; + u32 bitBuffer = 0; + u32 decodedOffset = 0; + s8* table = (s8*)NWC24WorkP->base64Work; + BOOL produceOutput; + int i; + + for (i = 0; i < encodedSize; i++) { + if ((s32)table[encoded[i]] >= 0) { + if ((s32)table[encoded[i]] < 0x40) { + bitCount += 6; + bitBuffer <<= 6; + produceOutput = bitCount >= 8; + bitBuffer |= (u32)table[encoded[i]]; + if (produceOutput) { + if (decodedOffset >= (u32)decodedSize) { + *stringSize = decodedSize; + return NWC24_ERR_OVERFLOW; + } + bitCount -= 8; + *decoded++ = (u8)((s32)bitBuffer >> bitCount); + decodedOffset++; + } + } + } + } + *stringSize = decodedOffset; + return NWC24_OK; +} + +void NWC24InitBase64Table(u8* table) { + s8* signedTable = (s8*)table; + int i; + + for (i = 0; i < 256; i++) { + signedTable[i] = -1; + } + for (i = 'A'; i <= 'Z'; i++) { + table[i] = i - 'A'; + } + for (i = 0; i < 26; i++) { + table['a' + i] = i + 26; + } + for (i = 0; i < 10; i++) { + table['0' + i] = i + 52; + } + table['+'] = 62; + table['/'] = 63; +} + +static NWC24Err QEncode(char* encoded, u32 encodedCapacity, u32* encodedSize, u8* decoded, u32 decodedSize, u32* decodedSizeOut, s32 maxLineLength) { + char* output; + u32 textWritten; + u32 dataIdx; + NWC24Err result; + s32 lineLength; + u8 octets[3]; + BOOL lineBreak; + s32 emitCount; + s32 bytesRead; + s16 currentByte; + s32 i; + + result = NWC24_OK; + + if (encoded == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + + if (decoded == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + + if (decodedSize <= 0) { + return NWC24_ERR_OVERFLOW; + } + + if (decodedSizeOut != NULL) { + *decodedSizeOut = 0; + } + + if (encodedSize != NULL) { + *encodedSize = 0; + } + + output = encoded; + lineLength = 0; + textWritten = 0; + dataIdx = 0; + + while (dataIdx < decodedSize) { + currentByte = *decoded; + lineBreak = FALSE; + + if ((char)currentByte >= '!' && (char)currentByte <= '~' && (char)currentByte != '=') { + bytesRead = 1; + emitCount = 1; + octets[0] = *decoded; + + } else if (dataIdx + 1 < decodedSize && (char)currentByte == '\r' && (char)decoded[1] == '\n') { + bytesRead = 2; + emitCount = 1; + octets[0] = *decoded; + octets[1] = decoded[1]; + + } else { + octets[0] = '='; + + if ((*decoded >> 4) >= 10) { + octets[1] = (*decoded >> 4) % 10 + 'A'; + } else { + octets[1] = (*decoded >> 4) % 10 + '0'; + } + + if ((*decoded & 0x0F) >= 10) { + octets[2] = (*decoded & 0x0F) % 10 + 'A'; + } else { + octets[2] = (*decoded & 0x0F) % 10 + '0'; + } + + bytesRead = 1; + emitCount = 3; + } + + if (maxLineLength == 0 && lineLength + emitCount >= 75) { + lineBreak = TRUE; + emitCount += 3; + } + + if (textWritten + emitCount >= encodedCapacity) { + result = NWC24_ERR_OVERFLOW; + break; + } + + textWritten += emitCount; + + if (lineBreak) { + output[0] = '='; + output[1] = '\r'; + output[2] = '\n'; + + output += 3; + emitCount -= 3; + + lineLength = 0; + } + + lineLength += emitCount; + + for (i = 0; i < emitCount; i++) { + *(output++) = octets[i]; + } + + dataIdx += bytesRead; + decoded += bytesRead; + } + + if (decodedSizeOut != NULL) { + *decodedSizeOut = dataIdx; + } + + if (encodedSize != NULL) { + *encodedSize = textWritten; + } + + return result; +} + +static NWC24Err QDecode(char* decoded, u32 decodedCapacity, u32* decodedSize, char* encoded, u32 encodedSize, u32* encodedSizeOut, int flags) { + u32 decodedOffset = 0; + u32 encodedOffset; + char* input; + char* output; + u32 value = 0; + NWC24Err result = NWC24_OK; + + if (decoded == NULL || encoded == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + if (decodedCapacity == 0) { + return NWC24_ERR_OVERFLOW; + } + if (decodedSize != NULL) { + *decodedSize = 0; + } + if (encodedSizeOut != NULL) { + *encodedSizeOut = 0; + } + + input = encoded; + output = decoded; + for (encodedOffset = 0; encodedOffset < encodedSize; encodedOffset++) { + if (decodedCapacity <= decodedOffset) { + result = NWC24_ERR_OVERFLOW; + break; + } + if (flags != 0 && *input == '_') { + *output++ = ' '; + input++; + decodedOffset++; + } else if (*input == '=' && encodedOffset + 2 < encodedSize) { + u32 inputAfterEqual = encodedOffset + 1; + char* current = ++input; + if (*current == ' ' || *current == '\t') { + char* previous = current; + u32 scan = 1; + while (inputAfterEqual + scan + 1 < encodedSize) { + char* next = previous + 1; + if (*next == '\r' && previous[2] == '\n') { + inputAfterEqual += scan; + current = next; + break; + } + if (*next != ' ' && *next != '\t') { + break; + } + previous = next; + scan++; + } + } + if (*current == '\r' && current[1] == '\n') { + current += 2; + encodedOffset = inputAfterEqual + 1; + input = current; + } else { + int high = Util_xtoi(*current); + int low; + if (high >= 0) { + value = (high & 0x0F) << 4; + } + low = Util_xtoi(current[1]); + if (low >= 0) { + value |= low & 0x0F; + } + current += 2; + if (high >= 0 && low >= 0) { + *output++ = (char)value; + decodedOffset++; + } + encodedOffset = inputAfterEqual + 1; + input = current; + } + } else { + *output++ = *input++; + decodedOffset++; + } + } + if (decodedSize != NULL) { + *decodedSize = decodedOffset; + } + if (encodedSizeOut != NULL) { + *encodedSizeOut = encodedOffset; + } + return result; +} + +NWC24Err NWC24EncodeQuotedPrintable(char* encoded, u32 encodedCapacity, u32* encodedSize, u8* decoded, u32 decodedSize, u32* decodedSizeOut) { + return QEncode(encoded, encodedCapacity, encodedSize, decoded, decodedSize, decodedSizeOut, 0); +} + +NWC24Err NWC24DecodeQuotedPrintable(char* decoded, u32 decodedCapacity, u32* decodedSize, u8* encoded, u32 encodedSize, u32* encodedSizeOut) { + return QDecode(decoded, decodedCapacity, decodedSize, (char*)encoded, encodedSize, encodedSizeOut, 0); +} + +static NWC24Err ConcatEncodedText(char* encoded, u32 encodedCapacity, u32* encodedSize, char encoding, u8* decoded, u32 decodedSize, + u32* decodedSizeOut); + +static NWC24Err EncodeWord(char* encoded, u32 encodedCapacity, u32* encodedSize, char* charset, u32 charsetSize, char encoding, u8* decoded, + u32 decodedSize, u32* decodedSizeOut) { + NWC24Err result = NWC24_OK; + BOOL encodeOverflow = FALSE; + + if (decodedSizeOut != NULL) { + *decodedSizeOut = 0; + } + if (encodedCapacity == 0) { + if (decodedSizeOut != NULL) { + *decodedSizeOut = 0; + } + return NWC24_ERR_INVALID_VALUE; + } + *encoded = '\0'; + if (encodedSize != NULL) { + *encodedSize = 1; + } + if (Mail_strlen(encoded) + 2 < encodedCapacity) { + Mail_strncat(encoded, "=?", 2); + } else { + result = NWC24_ERR_OVERFLOW; + } + if (result == NWC24_OK) { + if (charset == NULL) { + result = NWC24_ERR_INVALID_VALUE; + } else if (charsetSize + Mail_strlen(encoded) < encodedCapacity) { + u32 length = Mail_strlen(charset); + Mail_strncat(encoded, charset, length); + } else { + result = NWC24_ERR_OVERFLOW; + } + } + if (result == NWC24_OK) { + if (Mail_strlen(encoded) + 2 < encodedCapacity) { + Mail_strncat(encoded, "?", 1); + } else { + result = NWC24_ERR_OVERFLOW; + } + } + if (result == NWC24_OK) { + if (encoding == 'B' || encoding == 'b' || encoding == 'Q' || encoding == 'q') { + char value[1]; + u32 length = Mail_strlen(encoded); + value[0] = encoding; + if (length + 1 < encodedCapacity) { + Mail_strncat(encoded, value, 1); + } else { + result = NWC24_ERR_OVERFLOW; + } + } else { + result = NWC24_ERR_INVALID_VALUE; + } + } + if (result == NWC24_OK) { + if (Mail_strlen(encoded) + 2 < encodedCapacity) { + Mail_strncat(encoded, "?", 1); + } else { + result = NWC24_ERR_OVERFLOW; + } + } + if (result == NWC24_OK) { + result = ConcatEncodedText(encoded, encodedCapacity, encodedSize, encoding, decoded, decodedSize, decodedSizeOut); + if (result == NWC24_OK || result == NWC24_ERR_OVERFLOW) { + encodeOverflow = result == NWC24_ERR_OVERFLOW; + if (Mail_strlen(encoded) + 2 < encodedCapacity) { + Mail_strncat(encoded, "?=", 2); + result = NWC24_OK; + if (encodedSize != NULL) { + *encodedSize = Mail_strlen(encoded) + 1; + } + if (encodeOverflow) { + result = NWC24_ERR_OVERFLOW; + } + } else { + *encoded = '\0'; + if (decodedSizeOut != NULL) { + *decodedSizeOut = 1; + } + result = NWC24_ERR_OVERFLOW; + } + } else { + *encoded = '\0'; + if (decodedSizeOut != NULL) { + *decodedSizeOut = 1; + } + } + } else { + *encoded = '\0'; + } + return result; +} + +NWC24Err NWC24EncodeWord(u8* encoded, u32 encodedCapacity, u32* encodedSize, char* charset, u32 charsetSize, char encoding, u8* decoded, + u32 decodedSize) { + NWC24Err result; + + if (encodedSize == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + if (encoded == NULL || encodedCapacity == 0) { + return NWC24_ERR_INVALID_VALUE; + } + if (charset == NULL || charsetSize == 0) { + return NWC24_ERR_INVALID_VALUE; + } + if (encoding == '\0') { + return NWC24_ERR_INVALID_VALUE; + } + if (decoded == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + + *encoded = 0; + *encodedSize = 1; + result = EncodeWord((char*)encoded, encodedCapacity, encodedSize, charset, charsetSize, encoding, decoded, decodedSize, NULL); + if (result == NWC24_OK || result == NWC24_ERR_OVERFLOW) { + encoded[*encodedSize - 1] = 0; + } + return result; +} + +static NWC24Err ExtractCharset(char* charset, u32 charsetCapacity, u32* charsetSize, char* encoded, u32 encodedSize); +static NWC24Err ExtractEncodedText(char* decoded, u32 decodedCapacity, u32* decodedSize, char encoding, char* encoded, u32 encodedSize, + u32* encodedSizeOut); + +static BOOL CopyWithoutLinearWhiteSpaces(char* output, int* outputSize, char* input, int inputSize) { + BOOL afterNewline = FALSE; + u32 outputOffset = 0; + s32 capacity; + + if (output == NULL || outputSize == NULL || *outputSize == 0) { + return FALSE; + } + capacity = *outputSize; + if (input == NULL) { + *output = '\0'; + *outputSize = 1; + return TRUE; + } + while (outputOffset < capacity - 1U && inputSize != 0 && *input != '\0') { + char value = *input; + switch (value) { + case '\r': + case '\n': + if (!afterNewline) { + *output++ = ' '; + outputOffset++; + } + afterNewline = TRUE; + break; + case '\t': + case ' ': + if (!afterNewline) { + *output++ = value; + outputOffset++; + } + break; + default: + *output = value; + afterNewline = FALSE; + output++; + outputOffset++; + break; + } + input++; + inputSize--; + } + *output = '\0'; + *outputSize = outputOffset + 1; + return inputSize == 0 || *input == '\0'; +} + +static NWC24Err DecodeWord(char* charsetData, u32 charsetCapacity, char* decoded, u32 decodedCapacity, u32* decodedSize, char* encoded, + u32 encodedSize, u32* encodedSizeOut) { + int encodedWordPosition = 0; + int encodedLength; + u32 decodedLength; + u32 consumedSize; + NWC24Err result = NWC24_OK; + + if (encodedSizeOut != NULL) { + *encodedSizeOut = 0; + } + if (decodedCapacity == 0) { + if (encodedSizeOut != NULL) + *encodedSizeOut = 0; + return NWC24_ERR_INVALID_VALUE; + } + *decoded = '\0'; + if (decodedSize != NULL) { + *decodedSize = 1; + } + if (encodedSizeOut != NULL) { + *encodedSizeOut = 0; + } + { + u32 markerLength = Mail_strlen("=?"); + u32 offset; + for (offset = 0; offset <= encodedSize; offset++) { + encodedWordPosition = (int)(encoded + offset); + if (Mail_strncmp((char*)encodedWordPosition, "=?", markerLength) == 0) { + break; + } + } + if (offset > encodedSize) { + encodedWordPosition = 0; + } + } + if (encodedWordPosition == (int)encoded) { + result = ExtractCharset(charsetData, charsetCapacity, &consumedSize, (char*)encoded, encodedSize); + if (result != NWC24_OK) { + return result; + } + encodedLength = consumedSize; + { + u32 markerLength = Mail_strlen("?"); + u32 offset; + char* delimiter = NULL; + char* current = (char*)encodedWordPosition + encodedLength; + for (offset = 0; offset <= encodedSize - encodedLength; offset++) { + if (Mail_strncmp((char*)current, "?", markerLength) == 0) { + delimiter = current; + break; + } + current++; + } + if (delimiter == 0) { + return NWC24_ERR_INVALID_VALUE; + } + { + char encoding = delimiter[1]; + consumedSize = 2; + encodedLength += consumedSize; + result = ExtractEncodedText(decoded, decodedCapacity, &decodedLength, encoding, encoded + encodedLength, encodedSize - encodedLength, + &consumedSize); + if (result != NWC24_OK) { + return result; + } + encodedLength += consumedSize; + } + } + } else { + u32 localSize = decodedCapacity; + if (encodedWordPosition == 0) { + encodedLength = STD_strnlen(encoded, encodedSize); + } else { + encodedLength = encodedWordPosition - (int)encoded; + } + if (!CopyWithoutLinearWhiteSpaces(decoded, (int*)&localSize, encoded, encodedLength)) { + if (decodedSize != NULL) { + *decodedSize = localSize; + } + if (encodedSizeOut != NULL) { + *encodedSizeOut = encodedLength; + } + return NWC24_ERR_OVERFLOW; + } + decodedLength = localSize; + if (encodedWordPosition != 0) { + BOOL whitespaceOnly = TRUE; + u32 offset; + for (offset = 0; offset < localSize && decoded[offset] != '\0'; offset++) { + char value = decoded[offset]; + if (value != ' ' && value != '\t' && value != '\r' && value != '\n') { + whitespaceOnly = FALSE; + } + } + if (whitespaceOnly) { + *decoded = '\0'; + decodedLength = 1; + } + } + } + if (decodedSize != NULL) { + *decodedSize = decodedLength; + } + if (encodedSizeOut != NULL) { + *encodedSizeOut = encodedLength; + } + return result; +} + +NWC24Err NWC24DecodeMIMEHeaderFieldBody(u8* charsetData, u32 charsetDataSize, u8* decoded, u32 decodedCapacity, u32* decodedSize, u8* encoded, + u32 encodedSize) { + int result = 0; + u8* output; + u32 inputSize = encodedSize; + + if (decodedSize == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + if (charsetData == NULL || charsetDataSize == 0) { + return NWC24_ERR_INVALID_VALUE; + } + if (decoded == NULL || decodedCapacity == 0) { + return NWC24_ERR_INVALID_VALUE; + } + if (encoded == NULL) + return NWC24_ERR_INVALID_VALUE; + if (encoded == NULL) + return NWC24_ERR_INVALID_VALUE; + *decoded = 0; + *charsetData = 0; + *decodedSize = 1; + output = decoded; + while ((s32)inputSize > 0 && (s32)decodedCapacity > 0 && *encoded != '\0') { + u32 copiedSize = 0; + u32 consumedSize; + result = + DecodeWord((char*)charsetData, charsetDataSize, (char*)output, decodedCapacity, &copiedSize, (char*)encoded, inputSize, &consumedSize); + if (copiedSize == 0) { + break; + } + copiedSize--; + output += copiedSize; + decodedCapacity -= copiedSize; + *decodedSize += copiedSize; + encoded += consumedSize; + inputSize -= consumedSize; + if (result != NWC24_OK) { + break; + } + } + if (result == NWC24_OK && inputSize > 0 && *encoded != '\0') { + result = NWC24_ERR_OVERFLOW; + } + decoded[*decodedSize - 1] = '\0'; + return result; +} + +static NWC24Err ConcatEncodedText(char* encoded, u32 encodedCapacity, u32* encodedSize, char encoding, u8* decoded, u32 decodedSize, + u32* decodedSizeOut) { + u32 prefixSize = Mail_strlen(encoded); + int available = encodedCapacity - prefixSize - 2; + NWC24Err result; + + if (available <= 0) { + return NWC24_ERR_OVERFLOW; + } + if (encoding == 'B' || encoding == 'b') { + result = Base64Encode(decoded, decodedSize, decodedSizeOut, (u8*)encoded + prefixSize, (u32)(available - 1), encodedSize); + } else if (encoding == 'Q' || encoding == 'q') { + result = QEncode(encoded + prefixSize, (u32)(available - 1), encodedSize, decoded, decodedSize, decodedSizeOut, 1); + } else { + result = NWC24_ERR_NOT_SUPPORTED; + } + if (result == NWC24_OK || result == NWC24_ERR_OVERFLOW) { + encoded[prefixSize + *encodedSize] = '\0'; + *encodedSize += 1; + } + return result; +} + +static NWC24Err ExtractCharset(char* charset, u32 charsetCapacity, u32* charsetSize, char* encoded, u32 encodedSize) { + u32 markerLength; + u32 offset; + int start = 0; + int end = 0; + u32 charsetLength; + + if (charset == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + markerLength = Mail_strlen("=?"); + for (offset = 0; offset <= encodedSize; offset++) { + int current = (int)(encoded + offset); + if (Mail_strncmp((char*)current, "=?", markerLength) == 0) { + start = current; + break; + } + } + if (start == 0) { + return NWC24_ERR_NOT_SUPPORTED; + } + markerLength = Mail_strlen("?"); + start += 2; + for (offset = 0; offset <= encodedSize - (u32)(start - (int)encoded); offset++) { + int current = start + offset; + if (Mail_strncmp((char*)current, "?", markerLength) == 0) { + end = current; + break; + } + } + if (end == 0) { + return NWC24_ERR_NOT_SUPPORTED; + } + charsetLength = (u32)(end - start); + if (charsetLength >= charsetCapacity) { + return NWC24_ERR_OVERFLOW; + } + Mail_strncpy(charset, (char*)start, charsetLength); + charset[charsetLength] = '\0'; + *charsetSize = charsetLength + 2; + return NWC24_OK; +} + +static NWC24Err ExtractEncodedText(char* decoded, u32 decodedCapacity, u32* decodedSize, char encoding, char* encoded, u32 encodedSize, + u32* encodedSizeOut) { + u32 markerLength; + u32 offset; + int start = 0; + int end = 0; + int length; + NWC24Err result; + + if (encoded == NULL || decodedSize == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + *decodedSize = 0; + if (encodedSizeOut == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + *encodedSizeOut = 0; + markerLength = Mail_strlen("?"); + for (offset = 0; offset <= encodedSize; offset++) { + int current = (int)(encoded + offset); + if (Mail_strncmp((char*)current, "?", markerLength) == 0) { + start = current; + break; + } + } + if (start == 0) { + return NWC24_ERR_NOT_SUPPORTED; + } + markerLength = Mail_strlen("?="); + start++; + for (offset = 0; offset <= encodedSize - (u32)(start - (int)encoded); offset++) { + int current = start + offset; + if (Mail_strncmp((char*)current, "?=", markerLength) == 0) { + end = current; + break; + } + } + if (end == 0) { + return NWC24_ERR_NOT_SUPPORTED; + } + length = end - start; + if (encoding == 'B' || encoding == 'b') { + result = NWC24Base64Decode((u8*)start, length, (u8*)decoded, decodedCapacity - 1, decodedSize); + if (result == NWC24_OK || result == NWC24_ERR_OVERFLOW) { + decoded[*decodedSize] = '\0'; + *decodedSize += 1; + } + } else if (encoding == 'Q' || encoding == 'q') { + result = QDecode(decoded, decodedCapacity - 1, decodedSize, (char*)start, length, NULL, 1); + if (result == NWC24_OK || result == NWC24_ERR_OVERFLOW) { + decoded[*decodedSize] = '\0'; + *decodedSize += 1; + } + } else { + return NWC24_ERR_NOT_SUPPORTED; + } + *encodedSizeOut = (u32)(end - (int)encoded) + 2; + return result; +} diff --git a/libs/RevoEX/src/nwc24/NWC24MsgSubject.c b/libs/RevoEX/src/nwc24/NWC24MsgSubject.c new file mode 100644 index 00000000..cee480ca --- /dev/null +++ b/libs/RevoEX/src/nwc24/NWC24MsgSubject.c @@ -0,0 +1,855 @@ +#define NWC24_MSG_SUBJECT +#include +#include +#include +#include + +#include + +static char CharsetUsAscii[] = "us-ascii"; +static char CharsetIso2022Jp[] = "iso-2022-jp"; +static char CharsetUtf8[] = "utf-8"; +static char CharsetEucKr[] = "euc-kr"; +static char CharsetGb2312[] = "gb2312"; +static const char* JapaneseCharsets[] = {CharsetUsAscii, CharsetIso2022Jp, CharsetUtf8}; +static const char* ChineseCharsets[] = {CharsetUsAscii, CharsetGb2312}; +static char CharsetIso88591[] = "iso-8859-1"; +static char CharsetWindows1252[] = "windows-1252"; +static char CharsetIso88592[] = "iso-8859-2"; +static char CharsetIso88597[] = "iso-8859-7"; +static char CharsetIso885910[] = "iso-8859-10"; +char CharsetIso88593[] = "iso-8859-3"; +static const char* WesternCharsets[] = {CharsetUsAscii, CharsetIso88591, CharsetWindows1252, CharsetIso88592, + CharsetIso88597, CharsetIso885910, CharsetIso88593, CharsetUtf8}; +static const char* KoreanCharsets[] = {CharsetUsAscii, CharsetEucKr, CharsetUtf8}; +static char DefaultCharsetJp[] = "iso-2022-jp"; +static char DefaultCharsetKr[] = "euc-kr"; + +NWC24Err NWC24iGetDefaultCharset(char* charset, u32 charsetSize, NWC24EncodingRegion region); +NWC24Err NWC24iConvertToInternalEncoding(u16* dst, u32* dstSize, const u8* src, u32* srcSize, char* charset, u32 charsetSize, + NWC24EncodingRegion region, u16 alternative); +NWC24Err NWC24iConvertFromInternalEncoding(u8* dst, u32* dstSize, const u16* src, u32* srcSize, char* charset, u32 charsetSize, + NWC24EncodingRegion region, u16 alternative); +NWC24Err NWC24iDetectEncodingToSend(char* charset, u32 charsetSize, const u16* subject, u32 subjectSize, const u16* text, u32 textSize, + NWC24EncodingRegion region); +NWC24Err NWC24iDetectBreakPoint(u32* breakPoint, NWC24Charset charset, const u8* text, u32 textSize, u32 maxSize); +NWC24Err NWC24iSetMsgSubjectPlain(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize, NWC24Charset charset, char* charsetName); +NWC24Err NWC24iSetMsgSubjectQP(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize, NWC24Charset charset, char* charsetName); +NWC24Err NWC24iSetMsgSubjectBase64(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize, NWC24Charset charset, char* charsetName); + +NWC24Err NWC24ReadMsgSubjectPublic(const NWC24MsgObj* msg, u16* subject, u32* subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize) { + BOOL truncated; + u8* decodedData; + u32 decodedCapacity; + u32 originalSize; + u32 subjectDataSize; + u32 workHalf; + u32 decodedSize; + char* charsetBuffer; + NWC24Err result; + u32 i; + + if (subjectSize == NULL) { + result = NWC24_ERR_INVALID_VALUE; + } else { + originalSize = *subjectSize; + *subjectSize = 0; + truncated = FALSE; + if (work == NULL) { + result = NWC24_ERR_INVALID_VALUE; + } else { + workHalf = workSize >> 1; + decodedData = work + workHalf; + decodedCapacity = workSize - workHalf; + result = NWC24GetMsgSubjectSize(msg, &subjectDataSize); + switch (result) { + case NWC24_OK: + if (subjectDataSize > workHalf) { + subjectDataSize = workHalf; + truncated = TRUE; + } + result = NWC24ReadMsgSubject(msg, (char*)work, subjectDataSize); + if (result != NWC24_OK) { + if (result == NWC24_ERR_OVERFLOW) { + truncated = TRUE; + } else { + goto done; + } + } + charsetBuffer = NWC24WorkP->stringWork; + result = + NWC24DecodeMIMEHeaderFieldBody((u8*)charsetBuffer, 0x40, decodedData, decodedCapacity, &decodedSize, work, subjectDataSize); + if (result != NWC24_OK) { + if (result == NWC24_ERR_OVERFLOW) { + truncated = TRUE; + } else { + goto done; + } + } + *subjectSize = originalSize; + result = + NWC24iConvertToInternalEncoding(subject, subjectSize, decodedData, &decodedSize, charsetBuffer, 0x40, region, alternative); + if ((result == NWC24_OK) || (result == NWC24_ERR_OVERFLOW)) { + for (i = 0; (i < *subjectSize) && (subject[i] != 0); i++) { + if ((subject[i] == 0x0D) || (subject[i] == 0x0A)) { + subject[i] = 0x20; + } + } + if ((result == NWC24_OK) && truncated) { + result = NWC24_ERR_OVERFLOW; + } + } + break; + default: + goto done; + } + } + } + +done: + return result; +} + +NWC24Err NWC24ReadMsgTextPublic(const NWC24MsgObj* msg, u16* text, u32* textSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize) { + char* charsetBuffer; + BOOL truncated; + u32 originalSize; + u32 textDataSize; + NWC24Err result; + + if (textSize == NULL) { + result = NWC24_ERR_INVALID_VALUE; + } else { + originalSize = *textSize; + *textSize = 0; + truncated = FALSE; + if (work == NULL) { + result = NWC24_ERR_INVALID_VALUE; + } else { + result = NWC24GetMsgTextSize(msg, &textDataSize); + switch (result) { + case NWC24_OK: + if (textDataSize > workSize) { + textDataSize = workSize; + truncated = TRUE; + } + charsetBuffer = NWC24WorkP->stringWork + 0x20; + result = NWC24ReadMsgTextEx(msg, (char*)work, textDataSize, charsetBuffer, 0x40); + if (result != NWC24_OK) { + if (result != NWC24_ERR_OVERFLOW) { + goto done; + } + truncated = TRUE; + } + + *textSize = originalSize; + result = NWC24iConvertToInternalEncoding(text, textSize, work, &textDataSize, charsetBuffer, 0x40, region, alternative); + if ((result == NWC24_OK) && truncated) { + result = NWC24_ERR_OVERFLOW; + } + break; + default: + goto done; + } + } + } + +done: + return result; +} + +NWC24Err NWC24SetMsgSubjectPublic(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize) { + NWC24MsgObjPrivate* privateMsg = (NWC24MsgObjPrivate*)msg; + NWC24Work* nwcWork; + NWC24Charset charset; + NWC24Err result; + + if (((privateMsg->type & 0x100) == 0) || ((privateMsg->type & 0x200) != 0)) { + result = NWC24_ERR_PROTECTED; + goto done; + } + if ((subject == NULL) || (*subject == 0)) { + result = NWC24_ERR_NULL; + goto done; + } + if (subject[subjectSize] != 0) { + result = NWC24_ERR_STRING_END; + goto done; + } + if (work == NULL) { + result = NWC24_ERR_INVALID_VALUE; + goto done; + } + + nwcWork = NWC24WorkP; + result = NWC24iDetectEncodingToSend(nwcWork->stringWork, 0x40, subject, subjectSize, NULL, 0, region); + switch (result) { + case NWC24_OK: + break; + default: + goto done; + } + if (NWC24ParseCharsetStr(&charset, nwcWork->stringWork) != NWC24_OK) { + charset = 0; + } + if (charset == 0) { + result = NWC24iSetMsgSubjectPlain(msg, subject, subjectSize, region, alternative, work, workSize, charset, nwcWork->stringWork); + goto done; + } + switch (region) { + case 0: + result = 2; + break; + case 1: + case 2: + result = 3; + break; + case 3: + case 4: + result = 2; + break; + default: + result = 2; + break; + } + if (result == 3) { + result = NWC24iSetMsgSubjectQP(msg, subject, subjectSize, region, alternative, work, workSize, charset, nwcWork->stringWork); + } else { + result = NWC24iSetMsgSubjectBase64(msg, subject, subjectSize, region, alternative, work, workSize, charset, nwcWork->stringWork); + } + +done: + return result; +} + +NWC24Err NWC24SetMsgSubjectAndTextPublic(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, const u16* text, u32 textSize, + NWC24EncodingRegion region, u16 alternative, u8* work, u32 workSize) { + NWC24MsgObjPrivate* privateMsg = (NWC24MsgObjPrivate*)msg; + NWC24Work* nwcWork; + u32 textSourceSize; + u32 textWorkSize; + BOOL is7Bit; + NWC24Charset charset; + u32 subjectWorkSize; + u8* subjectWork; + NWC24Err result; + + if (((privateMsg->type & 0x100) == 0) || ((privateMsg->type & 0x200) != 0)) { + result = NWC24_ERR_PROTECTED; + goto done; + } + if ((subject == NULL) || (*subject == 0)) { + result = NWC24_ERR_NULL; + goto done; + } + if ((text == NULL) || (textSize == 0)) { + NWC24Data_Init(&privateMsg->text); + result = NWC24SetMsgSubjectPublic(msg, subject, subjectSize, region, alternative, work, workSize); + goto done; + } + if ((text[textSize] != 0) || (subject[subjectSize] != 0)) { + result = NWC24_ERR_STRING_END; + goto done; + } + if (work == NULL) { + result = NWC24_ERR_INVALID_VALUE; + goto done; + } + + nwcWork = NWC24WorkP; + result = NWC24iDetectEncodingToSend(nwcWork->stringWork, 0x40, subject, subjectSize, text, textSize, region); + switch (result) { + case NWC24_OK: + break; + default: + goto done; + } + if (NWC24ParseCharsetStr(&charset, nwcWork->stringWork) != NWC24_OK) { + charset = 0; + } + textWorkSize = (workSize * textSize) / (textSize + subjectSize * 4); + subjectWorkSize = workSize - textWorkSize; + subjectWork = work + textWorkSize; + textSourceSize = textSize; + result = NWC24iConvertFromInternalEncoding(work, &textWorkSize, text, &textSourceSize, nwcWork->stringWork, 0x40, region, alternative); + if (result != NWC24_OK) { + goto done; + } + + result = ENCIs7BitEncoding(&is7Bit, nwcWork->stringWork); + if (!is7Bit || (result != ENC_OK)) { + switch (region) { + case 0: + result = 2; + break; + case 1: + case 2: + result = 3; + break; + case 3: + case 4: + result = 2; + break; + default: + result = 2; + break; + } + } else { + result = 0; + } + result = NWC24SetMsgText(msg, (char*)work, textWorkSize - 1, charset, result); + if (result != NWC24_OK) { + goto done; + } + if (charset == 0) { + result = NWC24iSetMsgSubjectPlain(msg, subject, subjectSize, region, alternative, subjectWork, subjectWorkSize, charset, nwcWork->stringWork); + goto done; + } + switch (region) { + case 0: + result = 2; + break; + case 1: + case 2: + result = 3; + break; + case 3: + result = 2; + break; + case 4: + result = 2; + break; + default: + result = 2; + break; + } + if (result == 3) { + result = NWC24iSetMsgSubjectQP(msg, subject, subjectSize, region, alternative, subjectWork, subjectWorkSize, charset, nwcWork->stringWork); + } else { + result = + NWC24iSetMsgSubjectBase64(msg, subject, subjectSize, region, alternative, subjectWork, subjectWorkSize, charset, nwcWork->stringWork); + } + +done: + return result; +} + +NWC24Err NWC24iGetDefaultCharset(char* charset, u32 charsetSize, NWC24EncodingRegion region) { + NWC24Err result = NWC24_OK; + + switch (region) { + case 0: + strncpy(charset, DefaultCharsetJp, charsetSize - 1); + charset[charsetSize - 1] = 0; + goto done; + case 1: + strncpy(charset, "iso-8859-1", charsetSize - 1); + charset[charsetSize - 1] = 0; + goto done; + case 2: + strncpy(charset, "iso-8859-1", charsetSize - 1); + charset[charsetSize - 1] = 0; + goto done; + case 3: + strncpy(charset, DefaultCharsetKr, charsetSize - 1); + charset[charsetSize - 1] = 0; + goto done; + case 4: + strncpy(charset, "gb2312", charsetSize - 1); + charset[charsetSize - 1] = 0; + goto done; + default: + strncpy(charset, "iso-8859-1", charsetSize - 1); + charset[charsetSize - 1] = 0; + result = NWC24_ERR_INVALID_VALUE; + } + +done: + return result; +} + +NWC24Err NWC24iConvertToInternalEncoding(u16* dst, u32* dstSize, const u8* src, u32* srcSize, char* charset, u32 charsetSize, + NWC24EncodingRegion region, u16 alternative) { + ENCContext context; + u32 dstBytes; + u32 convertedBytes; + NWC24Err result; + + dstBytes = *dstSize * 2; + *dstSize = 0; + if (dstBytes < 2) { + result = NWC24_ERR_OVERFLOW; + goto done; + } + if (charset[0] == '\0') { + result = NWC24iGetDefaultCharset(charset, charsetSize, region); + switch (result) { + case NWC24_OK: + break; + default: + goto done; + } + } + result = ENCInitContext(&context); + if ((result == ENC_OK) && ((result = ENCSetExternalEncoding(&context, charset)) == ENC_OK) && + ((result = ENCSetBreakType(&context, ENC_BR_LF)) == ENC_OK) && + ((alternative == 0) || ((result = ENCSetAlternativeCharacter(&context, alternative, alternative)) == ENC_OK))) { + convertedBytes = dstBytes - 2; + result = ENCConvertToInternalEncoding(&context, dst, (s32*)&convertedBytes, src, (s32*)srcSize); + dst[convertedBytes >> 1] = 0; + *dstSize = (convertedBytes >> 1) + 1; + } + if (result == ENC_ERR_NO_MAP_RULE) { + goto invalidCharacter; + } + if (result < ENC_ERR_NO_MAP_RULE) { + if (result == ENC_ERR_INVALID_FORMAT) { + goto invalidCharacter; + } + if (result >= ENC_ERR_INVALID_FORMAT) { + goto invalidValue; + } + if (result >= ENC_ERR_NOT_LOADED) { + goto notSupported; + } + } else { + if (result == ENC_OK) { + goto success; + } + if (result >= ENC_OK) { + goto fatal; + } + goto overflow; + } + goto fatal; + +success: + result = ENC_OK; + goto done; + +invalidValue: + result = NWC24_ERR_INVALID_VALUE; + goto done; + +overflow: + result = NWC24_ERR_OVERFLOW; + goto done; + +invalidCharacter: + result = NWC24_ERR_INVALID_CHAR; + goto done; + +notSupported: + result = NWC24_ERR_NOT_SUPPORTED; + goto done; + +fatal: + result = NWC24_ERR_FATAL; + +done: + return result; +} + +NWC24Err NWC24iConvertFromInternalEncoding(u8* dst, u32* dstSize, const u16* src, u32* srcSize, char* charset, u32 charsetSize, + NWC24EncodingRegion region, u16 alternative) { + ENCContext context; + u32 outputCapacity; + u32 outputBytes; + u32 inputBytes; + NWC24Err result; + + outputCapacity = *dstSize; + *dstSize = 0; + if (outputCapacity < 1) { + result = NWC24_ERR_OVERFLOW; + goto done; + } + if (charset[0] == '\0') { + result = NWC24iGetDefaultCharset(charset, charsetSize, region); + switch (result) { + case NWC24_OK: + break; + default: + goto done; + } + } + result = ENCInitContext(&context); + if ((result == ENC_OK) && ((result = ENCSetExternalEncoding(&context, charset)) == ENC_OK) && + ((result = ENCSetBreakType(&context, ENC_BR_CRLF)) == ENC_OK) && + ((alternative == 0) || ((result = ENCSetAlternativeCharacter(&context, alternative, alternative)) == ENC_OK))) { + outputBytes = outputCapacity - 1; + inputBytes = *srcSize << 1; + result = ENCConvertFromInternalEncoding(&context, dst, (s32*)&outputBytes, src, (s32*)&inputBytes); + dst[outputBytes] = 0; + *srcSize = inputBytes >> 1; + *dstSize = outputBytes + 1; + } + if (result == ENC_ERR_NO_MAP_RULE) { + goto invalidCharacter; + } + if (result < ENC_ERR_NO_MAP_RULE) { + if (result == ENC_ERR_INVALID_FORMAT) { + goto invalidCharacter; + } + if (result >= ENC_ERR_INVALID_FORMAT) { + goto invalidValue; + } + if (result >= ENC_ERR_NOT_LOADED) { + goto notSupported; + } + goto fatal; + } + if (result == ENC_OK) { + goto success; + } + if (result >= ENC_OK) { + goto fatal; + } + goto overflow; + +success: + result = ENC_OK; + goto done; + +invalidValue: + result = NWC24_ERR_INVALID_VALUE; + goto done; + +overflow: + result = NWC24_ERR_OVERFLOW; + goto done; + +invalidCharacter: + result = NWC24_ERR_INVALID_CHAR; + goto done; + +notSupported: + result = NWC24_ERR_NOT_SUPPORTED; + goto done; + +fatal: + result = NWC24_ERR_FATAL; + +done: + return result; +} + +NWC24Err NWC24iDetectEncodingToSend(char* charset, u32 charsetSize, const u16* subject, u32 subjectSize, const u16* text, u32 textSize, + NWC24EncodingRegion region) { + const char** names; + int numNames; + int index; + int lastIndex; + int endIndex; + int startIndex; + int subjectIndex; + int result; + + index = 0; + lastIndex = -1; + if (region == 3) { + names = KoreanCharsets; + numNames = 3; + } else if (region < 3) { + if (region == 0) { + names = JapaneseCharsets; + numNames = 3; + } else if (region >= 0) { + names = WesternCharsets; + numNames = 8; + } else { + names = WesternCharsets; + numNames = 8; + } + } else if (region < 5) { + names = ChineseCharsets; + numNames = 2; + } else { + names = WesternCharsets; + numNames = 8; + } + endIndex = numNames - 1; + startIndex = 0; + do { + subjectIndex = index; + if (endIndex <= index) { + break; + } + result = ENCCheckEncoding(&index, names + startIndex, endIndex - startIndex, subject, subjectSize << 1); + if (result != ENC_OK) { + return NWC24_ERR_NOT_SUPPORTED; + } + if (index == ENC_CHECK_ENCODING_NOT_FOUND) { + subjectIndex = numNames - 1; + break; + } + subjectIndex = startIndex + index; + if ((text == NULL) || (lastIndex == subjectIndex)) { + break; + } + lastIndex = subjectIndex; + result = ENCCheckEncoding(&index, names + subjectIndex, endIndex - subjectIndex, text, textSize << 1); + if (result != ENC_OK) { + return NWC24_ERR_NOT_SUPPORTED; + } + if (index == ENC_CHECK_ENCODING_NOT_FOUND) { + subjectIndex = numNames - 1; + break; + } + lastIndex = subjectIndex + index; + startIndex = lastIndex; + } while (lastIndex != subjectIndex); + index = subjectIndex; + strncpy(charset, names[index], charsetSize - 1); + charset[charsetSize - 1] = '\0'; + return NWC24_OK; +} + +NWC24Err NWC24iDetectBreakPoint(u32* breakPoint, NWC24Charset charset, const u8* text, u32 textSize, u32 maxSize) { + const u8* ptr; + BOOL byteEncoding; + u32 i; + u32 lastBreak; + + i = 0; + lastBreak = 0; + if ((breakPoint == NULL) || (text == NULL)) { + return NWC24_ERR_INVALID_VALUE; + } + if (charset == 0) { + byteEncoding = TRUE; + } else if (charset == NWC24_UTF_8) { + byteEncoding = FALSE; + } else if (((charset & 0xFFFF0000) == 0x00080000) || (charset == NWC24_WINDOWS_1252)) { + byteEncoding = TRUE; + } else { + return NWC24_ERR_NOT_SUPPORTED; + } + if (textSize <= maxSize) { + *breakPoint = textSize; + return NWC24_OK; + } + ptr = text; + while ((i < maxSize) && (*text != 0)) { + if (*ptr == 0x20) { + lastBreak = i; + } + i++; + ptr++; + } + if (lastBreak != 0) { + *breakPoint = lastBreak; + return NWC24_OK; + } + if (byteEncoding) { + *breakPoint = maxSize; + return NWC24_OK; + } + { + u32 utf8Index = 0; + ptr = text; + while (utf8Index < maxSize && *text != 0) { + if (((u32)*ptr & 0xC0) != 0x80U) + lastBreak = utf8Index; + utf8Index++; + ptr++; + } + } + *breakPoint = lastBreak; + return NWC24_OK; +} + +NWC24Err NWC24iSetMsgSubjectPlain(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize, NWC24Charset charset, char* charsetName) { + u32 workHalf; + u32 secondSize; + u8* second; + u32 subjectLength; + u32 lineLength; + u32 sourceOffset; + s32 copied; + u32 i; + NWC24Err result; + + workHalf = workSize >> 1; + secondSize = workSize - workHalf; + second = work + workHalf; + subjectLength = subjectSize; + lineLength = 0; + result = NWC24iConvertFromInternalEncoding(work, &workHalf, subject, &subjectLength, charsetName, 0x40, region, alternative); + if (result == NWC24_OK) { + subjectLength = workHalf - 1; + for (i = 0; i < workHalf; i++) { + if ((work[i] == '\n') || (work[i] == '\r')) { + work[i] = ' '; + } + } + NWC24iDetectBreakPoint(&lineLength, charset, work, subjectLength, 0x3F); + if (lineLength == subjectLength) { + result = NWC24SetMsgSubject(msg, (char*)work, subjectLength); + } else if (lineLength < secondSize) { + copied = NWC24iStrLCpy((char*)second, (char*)work, lineLength + 1); + workHalf = secondSize; + for (sourceOffset = lineLength; sourceOffset < subjectLength; sourceOffset += lineLength) { + if (workHalf - copied < 3) { + result = NWC24_ERR_OVERFLOW; + goto done; + } + second[copied] = '\r'; + second[copied + 1] = '\n'; + copied += 2; + if (work[sourceOffset] != ' ') { + second[copied] = ' '; + copied++; + } + NWC24iDetectBreakPoint(&lineLength, charset, work + sourceOffset, subjectLength - sourceOffset, 0x47); + if (workHalf - copied <= lineLength) { + result = NWC24_ERR_OVERFLOW; + goto done; + } + copied += NWC24iStrLCpy((char*)second + copied, (char*)work + sourceOffset, lineLength + 1); + } + second[copied] = 0; + result = NWC24SetMsgSubject(msg, (char*)second, copied); + } else { + result = NWC24_ERR_OVERFLOW; + } + } + +done: + return result; +} + +NWC24Err NWC24iSetMsgSubjectQP(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize, NWC24Charset charset, char* charsetName) { + u32 workHalf; + u32 secondSize; + u8* second; + u32 subjectLength; + u32 lineLength; + u32 outputLength; + u32 sourceOffset; + u32 nextOutput; + u32 total; + u32 i; + u32 charsetLength; + NWC24Err result; + + workHalf = workSize >> 1; + secondSize = workSize - workHalf; + second = work + workHalf; + subjectLength = subjectSize; + lineLength = 0; + result = NWC24iConvertFromInternalEncoding(work, &workHalf, subject, &subjectLength, charsetName, 0x40, region, alternative); + if (result == NWC24_OK) { + subjectLength = workHalf - 1; + for (i = 0; i < workHalf; i++) { + if ((work[i] == '\n') || (work[i] == '\r')) { + work[i] = ' '; + } + } + charsetLength = strlen(charsetName); + NWC24iDetectBreakPoint(&lineLength, charset, work, subjectLength, (0x38 - charsetLength) / 3); + result = NWC24EncodeWord(second, secondSize, &outputLength, charsetName, 0x40, 'Q', work, lineLength); + sourceOffset = lineLength; + if (result == NWC24_OK) { + if (lineLength == subjectLength) { + result = NWC24SetMsgSubject(msg, (char*)second, outputLength - 1); + } else { + charsetLength = strlen(charsetName); + total = outputLength; + workHalf = secondSize; + for (; sourceOffset < subjectLength; sourceOffset += lineLength) { + nextOutput = total - 1; + if (workHalf - nextOutput < 3) { + result = NWC24_ERR_OVERFLOW; + goto done; + } + second[nextOutput] = '\r'; + second[total] = '\n'; + second[total + 1] = ' '; + total += 2; + NWC24iDetectBreakPoint(&lineLength, charset, work + sourceOffset, subjectLength - sourceOffset, (0x40 - charsetLength) / 3); + result = + NWC24EncodeWord(second + total, workHalf - total, &outputLength, charsetName, 0x40, 'Q', work + sourceOffset, lineLength); + if (result != NWC24_OK) { + goto done; + } + total += outputLength; + } + result = NWC24SetMsgSubject(msg, (char*)second, total - 1); + } + } + } + +done: + return result; +} + +NWC24Err NWC24iSetMsgSubjectBase64(NWC24MsgObj* msg, const u16* subject, u32 subjectSize, NWC24EncodingRegion region, u16 alternative, u8* work, + u32 workSize, NWC24Charset charset, char* charsetName) { + u32 workHalf; + u32 secondSize; + u8* second; + u32 subjectLength; + u32 lineLength; + u32 outputLength; + u32 sourceOffset; + u32 total; + u32 charsetLength; + NWC24Err result; + + workHalf = workSize >> 1; + secondSize = workSize - workHalf; + second = work + workHalf; + charsetLength = strlen(charsetName); + lineLength = ((0x36 - charsetLength) * 3) >> 2; + if (workHalf < lineLength) { + result = NWC24_ERR_OVERFLOW; + } else { + outputLength = lineLength + 1; + subjectLength = subjectSize; + result = NWC24iConvertFromInternalEncoding(work, &outputLength, subject, &subjectLength, charsetName, 0x40, region, alternative); + if (((result == NWC24_OK) || (result == NWC24_ERR_OVERFLOW)) && + ((result = NWC24EncodeWord(second, secondSize, &outputLength, charsetName, 0x40, 'B', work, outputLength - 1)) == NWC24_OK)) { + sourceOffset = subjectLength; + if (sourceOffset == subjectSize) { + result = NWC24SetMsgSubject(msg, (char*)second, outputLength - 1); + } else { + charsetLength = strlen(charsetName); + lineLength = (((0x3E - charsetLength) * 3) >> 2) + 1; + total = outputLength; + for (; sourceOffset < subjectSize; sourceOffset += subjectLength) { + subjectLength = subjectSize - sourceOffset; + workHalf = lineLength; + if (secondSize - (total - 1) < 3) { + result = NWC24_ERR_OVERFLOW; + goto done; + } + second[total - 1] = '\r'; + second[total] = '\n'; + second[total + 1] = ' '; + total += 2; + result = NWC24iConvertFromInternalEncoding(work, &workHalf, subject + sourceOffset, &subjectLength, charsetName, 0x40, region, + alternative); + if (((result != NWC24_OK) && (result != NWC24_ERR_OVERFLOW)) || + ((result = NWC24EncodeWord(second + total, secondSize - total, &outputLength, charsetName, 0x40, 'B', work, workHalf - 1)) != + NWC24_OK)) { + goto done; + } + total += outputLength; + } + result = NWC24SetMsgSubject(msg, (char*)second, total - 1); + } + } + } + +done: + return result; +} diff --git a/tools/decomp-assist/NWC24Mime.attempts.md b/tools/decomp-assist/NWC24Mime.attempts.md new file mode 100644 index 00000000..30cf4998 --- /dev/null +++ b/tools/decomp-assist/NWC24Mime.attempts.md @@ -0,0 +1,77 @@ +# NWC24Mime matching attempts + +Baseline: no source, 0/16 functions, 0/6124 code bytes, 0/88 data bytes. +All functions are implemented in object order, with ordinary literals. +The encoding alphabet, pointer and small marker strings match all 88 data bytes. +The initial implementation was adapted from readable C references available +in /tmp, then checked against the target object and object-exported Ghidra C. +Oversized Ghidra stack arrays were replaced with actual octet/scalar storage. + +## Source-level experiments + +Base64Encode | canonical three-byte loop from SDK | (96.233765, -37) | src 0x134 base 0x134 insns 77/77 +Base64Encode | mask initial sextet | (80.19481, -9999) | src 0x144 base 0x134 insns 81/77 +Base64Encode | pointer-relative second byte | (80.38961, -9999) | src 0x144 base 0x134 insns 81/77 +NWC24InitBase64Table | unsigned scan index | (97.41304, -51) | src 0x2e0 base 0x2e0 insns 184/184 +NWC24InitBase64Table | one character scan with explicit bounds | (100.0, 0) | src 0x2e0 base 0x2e0 insns 184/184 +QEncode | signed copy count | (73.83251, -9999) | src 0x324 base 0x32c insns 201/203 +QEncode | credit output before optional line break | (72.28571, -9999) | src 0x2fc base 0x32c insns 191/203 +QEncode | initialize encoded byte before classification | (69.3202, -9999) | src 0x2f4 base 0x32c insns 189/203 +QDecode | signed cursors | (74.9315, -9999) | src 0x234 base 0x248 insns 141/146 +QDecode | predicate return order | (74.863014, -9999) | src 0x234 base 0x248 insns 141/146 +QDecode | remaining input while loop | (74.9315, -9999) | src 0x234 base 0x248 insns 141/146 +QEncode | SDK signed copy scan and octet operations | (100.0, 0) | src 0x32c base 0x32c insns 203/203 +EncodeWord | unsigned intermediate string length | (69.91919, -9999) | src 0x2c0 base 0x318 insns 176/198 +EncodeWord | capacity condition reversed | (69.86869, -9999) | src 0x2c0 base 0x318 insns 176/198 +EncodeWord | defer overflow flag initialization | (69.91919, -9999) | src 0x2c0 base 0x318 insns 176/198 +CopyWithoutLinearWhiteSpaces | switch classification | (8.835616, -55) | src 0x124 base 0x124 insns 73/73 +CopyWithoutLinearWhiteSpaces | signed output offset | (14.315068, -9999) | src 0x114 base 0x124 insns 69/73 +CopyWithoutLinearWhiteSpaces | cache input value across capacity check | (10.068493, -9999) | src 0x110 base 0x124 insns 68/73 +DecodeWord | repeat consumed initialization before capacity return | (77.37222, -161) | src 0x2d0 base 0x2d0 insns 180/180 +DecodeWord | independent whitespace scan pointer | (74.02778, -9999) | src 0x2c0 base 0x2d0 insns 176/180 +DecodeWord | unconditional decoded size on copy overflow | (74.094444, -9999) | src 0x2b8 base 0x2d0 insns 174/180 +NWC24DecodeMIMEHeaderFieldBody | check decode status before consumed count | (74.13043, -9999) | src 0x158 base 0x170 insns 86/92 +NWC24DecodeMIMEHeaderFieldBody | signed remaining input | (81.195656, -9999) | src 0x158 base 0x170 insns 86/92 +NWC24DecodeMIMEHeaderFieldBody | direct input size parameter scan | (81.195656, -9999) | src 0x158 base 0x170 insns 86/92 +ConcatEncodedText | signed prefix length | (93.22222, -43) | src 0xfc base 0xfc insns 63/63 +ConcatEncodedText | single remaining capacity expression | (93.492065, -41) | src 0xfc base 0xfc insns 63/63 +ConcatEncodedText | positive capacity branch | (90.84127, -9999) | src 0x100 base 0xfc insns 64/63 +ExtractCharset | signed scan indices | (74.04762, -9999) | src 0x148 base 0x150 insns 82/84 +ExtractCharset | signed extracted length | (75.34524, -9999) | src 0x144 base 0x150 insns 81/84 +ExtractCharset | reuse marker length for span | (75.34524, -9999) | src 0x144 base 0x150 insns 81/84 +ExtractEncodedText | signed scan index | (85.4, -9999) | src 0x208 base 0x21c insns 130/135 +ExtractEncodedText | unsigned extracted length | (87.437035, -9999) | src 0x204 base 0x21c insns 129/135 +ExtractEncodedText | merge invalid pointer predicates | (87.36296, -9999) | src 0x204 base 0x21c insns 129/135 +CopyWithoutLinearWhiteSpaces | switch with loop continuation predicate | (98.287674, -20) | src 0x124 base 0x124 insns 73/73 +CopyWithoutLinearWhiteSpaces | unsigned cached capacity | (98.42466, -18) | src 0x124 base 0x124 insns 73/73 +CopyWithoutLinearWhiteSpaces | capacity before output counter | (98.287674, -20) | src 0x124 base 0x124 insns 73/73 +Base64Encode | combine shifted initial octet | (100.0, 0) | src 0x134 base 0x134 insns 77/77 +CopyWithoutLinearWhiteSpaces | declare character before flags | (98.42466, -18) | src 0x124 base 0x124 insns 73/73 +CopyWithoutLinearWhiteSpaces | separate default pointer advancement | (98.561646, -17) | src 0x124 base 0x124 insns 73/73 +CopyWithoutLinearWhiteSpaces | cache capacity minus terminator | (96.9863, -10) | src 0x124 base 0x124 insns 73/73 +NWC24DecodeMIMEHeaderFieldBody | bounded signed input and output cursors | (85.92391, -9999) | src 0x16c base 0x170 insns 91/92 +NWC24DecodeMIMEHeaderFieldBody | avoid initial consumed-count clear | (82.065216, -9999) | src 0x154 base 0x170 insns 85/92 +NWC24DecodeMIMEHeaderFieldBody | fold status into loop condition | (83.36957, -9999) | src 0x16c base 0x170 insns 91/92 +QDecode | moving input/output cursors | (81.99315, -9999) | src 0x230 base 0x248 insns 140/146 +QDecode | late moving cursor initialization | (81.03425, -9999) | src 0x230 base 0x248 insns 140/146 +QDecode | decode high nibble before low conversion | (86.20548, -9999) | src 0x230 base 0x248 insns 140/146 +QDecode | independent pointer validation | (81.10274, -9999) | src 0x238 base 0x248 insns 142/146 +NWC24DecodeMIMEHeaderFieldBody | independent encoded-pointer validation | (88.20652, -9999) | src 0x174 base 0x170 insns 93/92 +NWC24DecodeMIMEHeaderFieldBody | consumed count written by decoder | (86.95652, -9999) | src 0x168 base 0x170 insns 90/92 +NWC24DecodeMIMEHeaderFieldBody | defer remaining input initialization | (88.097824, -9999) | src 0x16c base 0x170 insns 91/92 + +## Retained result + +8/16 instruction-exact and objdiff-exact functions; 2240/6124 code bytes; +88/88 data bytes. Base64 encoding uses the canonical three-byte scan and +one initial shifted-octet expression. Alphabet initialization scans actual +character bounds. Quoted-printable encoding uses a signed byte-copy scan. +All remaining functions have at least three logged distinct experiments. +Remaining differences: QDecode cursor/error control flow; EncodeWord append +status propagation; CopyWithoutLinearWhiteSpaces register allocation; +DecodeWord search/status allocation; MIME header validation and cursor +allocation; ConcatEncodedText allocation; charset/text search loop scheduling. +Combination of moving QDecode cursor initialization and sequential nibble +conversion gives 86.54794%. Combining bounded MIME-header scanning, independent +input validation and decoder-owned consumed count gives 86.03261%. +No other unit or shared header was changed. diff --git a/tools/decomp-assist/NWC24MsgSubject.attempts.md b/tools/decomp-assist/NWC24MsgSubject.attempts.md new file mode 100644 index 00000000..503af832 --- /dev/null +++ b/tools/decomp-assist/NWC24MsgSubject.attempts.md @@ -0,0 +1,100 @@ +# NWC24MsgSubject matching attempts + +Baseline: no source, 0/12 functions, 0/5352 code bytes, 0/232 data bytes. +All twelve functions are implemented in object order. The initial readable C +reference from /tmp was checked against target assembly and Ghidra output. +Charset strings and pointer tables retain source order; .data and .sdata +match 100%, with an identical pool. + +## Source-level experiments + +NWC24ReadMsgSubjectPublic | switch write overflow status | (92.11539, -10) | src 0x1a0 base 0x1a0 insns 104/104 +NWC24ReadMsgSubjectPublic | signed subject whitespace index | (96.15385, -9999) | src 0x190 base 0x1a0 insns 100/104 +NWC24ReadMsgSubjectPublic | late original-size read | (96.15385, -9999) | src 0x190 base 0x1a0 insns 100/104 +NWC24ReadMsgTextPublic | switch read overflow status | (94.14286, -5) | src 0x118 base 0x118 insns 70/70 +NWC24ReadMsgTextPublic | truncation flag after size temporaries | (96.71429, -9999) | src 0x110 base 0x118 insns 68/70 +NWC24ReadMsgTextPublic | explicit error status declaration first | (97.14286, -9999) | src 0x110 base 0x118 insns 68/70 +NWC24SetMsgSubjectPublic | regional encoding switch | (94.59649, -9999) | src 0x1b0 base 0x1c8 insns 108/114 +NWC24SetMsgSubjectPublic | charset initialized before detection | (87.89474, -9999) | src 0x1bc base 0x1c8 insns 111/114 +NWC24SetMsgSubjectPublic | private message view used directly | (95.74561, -9999) | src 0x1b8 base 0x1c8 insns 110/114 +NWC24SetMsgSubjectAndTextPublic | regional subject encoding switch | (0, -9999) | [1/1] MWCC build/43U/src/libs/RevoEX/src/nwc24/NWC24MsgSubject.o +NWC24SetMsgSubjectAndTextPublic | unsigned intermediate text size | (0, -9999) | [1/1] MWCC build/43U/src/libs/RevoEX/src/nwc24/NWC24MsgSubject.o +NWC24SetMsgSubjectAndTextPublic | initialize charset before charset parser | (86.23158, -9999) | src 0x2d0 base 0x2f8 insns 180/190 +NWC24ReadMsgSubjectPublic | switch only exceptional statuses | (94.03846, -9999) | src 0x198 base 0x1a0 insns 102/104 +NWC24ReadMsgTextPublic | switch only exceptional statuses | (95.57143, -9999) | src 0x114 base 0x118 insns 69/70 +NWC24SetMsgSubjectAndTextPublic | regional subject switch at final choice | (91.405266, -9999) | src 0x2e8 base 0x2f8 insns 186/190 +NWC24SetMsgSubjectAndTextPublic | defer subject workspace pointer calculation | (86.6579, -9999) | src 0x2c4 base 0x2f8 insns 177/190 +NWC24SetMsgSubjectAndTextPublic | reorder text source/work count declarations | (90.052635, -9999) | src 0x2cc base 0x2f8 insns 179/190 +NWC24iDetectEncodingToSend | continue when text charset advances subject charset | (72.376144, -9999) | src 0x18c base 0x1b4 insns 99/109 +NWC24iDetectEncodingToSend | signed charset region switch | (58.19266, -9999) | src 0x154 base 0x1b4 insns 85/109 +NWC24iDetectEncodingToSend | result index before loop bound check | (65.39449, -9999) | src 0x164 base 0x1b4 insns 89/109 +NWC24iDetectBreakPoint | signed scan counter | (77.75676, -53) | src 0x128 base 0x128 insns 74/74 +NWC24iDetectBreakPoint | direct size fit return | (77.554054, -53) | src 0x128 base 0x128 insns 74/74 +NWC24iDetectBreakPoint | cache leading byte for scan | (73.432434, -9999) | src 0x120 base 0x128 insns 72/74 +NWC24iSetMsgSubjectPlain | signed folding scan index | (88.424, -9999) | src 0x1e8 base 0x1f4 insns 122/125 +NWC24iSetMsgSubjectPlain | moving newline normalization cursor | (87.904, -9999) | src 0x1e8 base 0x1f4 insns 122/125 +NWC24iSetMsgSubjectPlain | defer folded buffer pointer calculation | (81.744, -9999) | src 0x1e8 base 0x1f4 insns 122/125 +NWC24iSetMsgSubjectQP | signed folding scan index | (76.75, -9999) | src 0x258 base 0x240 insns 150/144 +NWC24iSetMsgSubjectQP | moving newline normalization cursor | (76.298615, -9999) | src 0x258 base 0x240 insns 150/144 +NWC24iSetMsgSubjectQP | defer folded buffer pointer calculation | (71.02778, -9999) | src 0x258 base 0x240 insns 150/144 +NWC24iSetMsgSubjectBase64 | signed folding scan index | (70.0, -9999) | src 0x230 base 0x220 insns 140/136 +NWC24iSetMsgSubjectBase64 | moving newline normalization cursor | (70.0, -9999) | src 0x230 base 0x220 insns 140/136 +NWC24iSetMsgSubjectBase64 | defer folded buffer pointer calculation | (70.0, -9999) | src 0x230 base 0x220 insns 140/136 +NWC24ReadMsgSubjectPublic | success/default status switch | (96.15385, -9999) | src 0x190 base 0x1a0 insns 100/104 +NWC24ReadMsgTextPublic | success/default status switch | (97.14286, -9999) | src 0x110 base 0x118 insns 68/70 +NWC24SetMsgSubjectPublic | individual regional switch cases | (97.149124, -9999) | src 0x1d4 base 0x1c8 insns 117/114 +NWC24iSetMsgSubjectPlain | begin folding after first line and reuse capacity slot | (90.496, -96) | src 0x1f4 base 0x1f4 insns 125/125 +NWC24iSetMsgSubjectPlain | conversion status switch | (89.304, -9999) | src 0x1ec base 0x1f4 insns 123/125 +NWC24iSetMsgSubjectPlain | folded capacity comparison direction | (88.384, -9999) | src 0x1e8 base 0x1f4 insns 122/125 +NWC24iSetMsgSubjectQP | unsigned charset-size arithmetic | (78.13194, -9999) | src 0x250 base 0x240 insns 148/144 +NWC24iSetMsgSubjectQP | separate running and per-word output counts | (86.270836, -9999) | src 0x230 base 0x240 insns 140/144 +NWC24iSetMsgSubjectQP | conversion status switch | (77.513885, -9999) | src 0x25c base 0x240 insns 151/144 +NWC24iSetMsgSubjectBase64 | signed line size and unsigned charset length | (71.43382, -9999) | src 0x230 base 0x220 insns 140/136 +NWC24iSetMsgSubjectBase64 | separate total and encoded word sizes | (79.70588, -9999) | src 0x208 base 0x220 insns 130/136 +NWC24iSetMsgSubjectBase64 | folded output capacity cached in input capacity | (70.0, -9999) | src 0x230 base 0x220 insns 140/136 +NWC24iDetectBreakPoint | supported charset branch and early breakpoint returns | (98.64865, -8) | src 0x128 base 0x128 insns 74/74 +NWC24ReadMsgSubjectPublic | break from overflowing switch case | (96.15385, -9999) | src 0x190 base 0x1a0 insns 100/104 +NWC24ReadMsgTextPublic | break from overflowing switch case | (97.14286, -9999) | src 0x110 base 0x118 insns 68/70 +NWC24iDetectBreakPoint | pointer declared before byte-encoding flag | (100.0, 0) | src 0x128 base 0x128 insns 74/74 +NWC24SetMsgSubjectPublic | merge Korean and Chinese base64 cases | (100.0, 0) | src 0x1c8 base 0x1c8 insns 114/114 +NWC24SetMsgSubjectAndTextPublic | merge second base64 regional cases | (93.947365, -9999) | src 0x2dc base 0x2f8 insns 183/190 +NWC24SetMsgSubjectAndTextPublic | regional text encoding switch | (94.789474, -125) | src 0x2f8 base 0x2f8 insns 190/190 +NWC24SetMsgSubjectAndTextPublic | test external conversion status before seven-bit flag | (90.378944, -9999) | src 0x2e8 base 0x2f8 insns 186/190 +NWC24SetMsgSubjectAndTextPublic | work pointer before message view | (94.789474, -125) | src 0x2f8 base 0x2f8 insns 190/190 +NWC24SetMsgSubjectAndTextPublic | detection status switch | (95.36842, -9999) | src 0x2fc base 0x2f8 insns 191/190 +NWC24SetMsgSubjectAndTextPublic | work pointer declared after size variables | (94.789474, -125) | src 0x2f8 base 0x2f8 insns 190/190 + +## Retained corrections + +Grouped Korean/Chinese base64 cases match NWC24SetMsgSubjectPublic. +Breakpoint detection uses the supported-charset branch, separate UTF-8 scan, +early returns, and unsigned masked-byte comparison; it matches exactly. +Both internal-encoding conversion functions and the default charset selector +also match exactly. Plain subject folding starts after the initial line. +Charset detection repeats while the text charset advances the subject charset. +QP/base64 folding uses distinct running and per-word lengths; the short +single-word branch uses its initialized word length. Unsigned charset-length +arithmetic reproduces the target division. Removing unused base64 temporaries +and fixing those single-word branches gives QP 88.4375% and base64 81.94853%. +The detection-status switch gives SubjectAndText 95.36842%. + +NWC24_MSG_SUBJECT is defined only by this source. Its header gate supplies the +five-argument, writable-name NWC24ReadMsgTextEx declaration seen in the target +callee, which overwrites r8 on entry. Every other translation unit keeps the +existing declaration. The gate reports zero regressions. + +Several temporary variants failed compilation and were discarded. Unchanged +source variants in the raw log are not counted as distinct attempts. Every +remaining function has at least three actual source edits recorded. + +## Remaining functions + +NWC24ReadMsgSubjectPublic 96.15385%: 104 target instructions versus 100; overflow-handling branch structure +NWC24ReadMsgTextPublic 97.14286%: 70 target instructions versus 68; overflow-handling branch structure +NWC24SetMsgSubjectAndTextPublic 95.36842%: regional dispatch, detection-status flow and register allocation +NWC24iDetectEncodingToSend 72.376144%: charset scan state and search-loop scheduling/allocation +NWC24iSetMsgSubjectPlain 90.496%: folded-line control flow and allocation +NWC24iSetMsgSubjectQP 88.4375%: word-size accounting, folding control flow and allocation +NWC24iSetMsgSubjectBase64 81.94853%: conversion/encoding status flow and folding allocation + +Retained: 5/12 exact functions; 1840/5352 code bytes; 232/232 data bytes. -- 2.49.1 From 0c543ddf5a09c2d46d15a583f650526c25dd0fd4 Mon Sep 17 00:00:00 2001 From: devin Date: Wed, 30 Sep 2026 03:48:49 +0000 Subject: [PATCH 5/5] fa: link pf_clib, pf_code, pf_str, pf_driver (objdiff 100% code+data) Co-Authored-By: wch --- configure.py | 8 +- libs/RVL_SDK/src/fa/pf_clib.c | 177 +++++++++++++ libs/RVL_SDK/src/fa/pf_code.c | 21 ++ libs/RVL_SDK/src/fa/pf_driver.c | 442 ++++++++++++++++++++++++++++++++ libs/RVL_SDK/src/fa/pf_str.c | 229 +++++++++++++++++ 5 files changed, 873 insertions(+), 4 deletions(-) create mode 100644 libs/RVL_SDK/src/fa/pf_clib.c create mode 100644 libs/RVL_SDK/src/fa/pf_code.c create mode 100644 libs/RVL_SDK/src/fa/pf_driver.c create mode 100644 libs/RVL_SDK/src/fa/pf_str.c diff --git a/configure.py b/configure.py index a09222f7..eaa5c416 100644 --- a/configure.py +++ b/configure.py @@ -1682,11 +1682,11 @@ config.libs = [ ] ), RVLSDKLib("fa", [ - Object(NonMatching, "fa/pf_clib.c"), - Object(NonMatching, "fa/pf_code.c"), + Object(Matching, "fa/pf_clib.c"), + Object(Matching, "fa/pf_code.c"), Object(NonMatching, "fa/pf_service.c"), - Object(NonMatching, "fa/pf_str.c"), - Object(NonMatching, "fa/pf_driver.c"), + Object(Matching, "fa/pf_str.c"), + Object(Matching, "fa/pf_driver.c"), Object(NonMatching, "fa/pdm_api.c"), Object(NonMatching, "fa/pdm_bpb.c"), Object(NonMatching, "fa/pdm_disk.c"), diff --git a/libs/RVL_SDK/src/fa/pf_clib.c b/libs/RVL_SDK/src/fa/pf_clib.c new file mode 100644 index 00000000..31dd911f --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_clib.c @@ -0,0 +1,177 @@ +#include + +pf_s32 pf_toupper(pf_s32 c) { + if (c >= 'a' && c <= 'z') { + return c + ('A' - 'a'); + } else { + return c; + } +} + +void* pf_memcpy(void* dst, void* src, pf_u32 length) { + pf_s8* d; + const pf_s8* s; + + pf_u32* ld = (pf_u32*)dst; + const pf_u32* ls = (pf_u32*)src; + + if (((pf_u32)ld & 3) == 0 && ((pf_u32)ls & 3) == 0) { + for (; length > 3; length -= 4) { + *ld++ = *ls++; + } + } + + d = (pf_s8*)ld; + s = (pf_s8*)ls; + + while (length-- != 0) { + *d++ = *s++; + } + + return dst; +} + +void* pf_memset(void* dst, pf_s32 c, pf_u32 length) { + pf_s8* d = (pf_s8*)dst; + pf_u32* ld; + pf_u32 lc; + + for (; ((pf_u32)d & 3) != 0; length--) { + *d++ = c; + } + + ld = (pf_u32*)d; + lc = (c << 24) | (c << 16) | (c << 8) | (c); + + for (; length > 3; length -= 4) { + *ld++ = lc; + } + + d = (pf_s8*)ld; + while (length-- != 0) { + *d++ = c; + } + + return dst; +} + +pf_s32 pf_memcmp(const void* s1, const void* s2, pf_u32 length) { + const pf_u8* p1 = (const pf_u8*)s1; + const pf_u8* p2 = (const pf_u8*)s2; + + if (((pf_u32)p1 & 3) == 0 && ((pf_u32)p2 & 3) == 0) { + const pf_u32* lp1 = (const pf_u32*)p1; + const pf_u32* lp2 = (const pf_u32*)p2; + + for (; length > 3; length -= 4, lp1++, lp2++) { + if (*lp1 != *lp2) { + break; + } + } + + p1 = (const pf_u8*)lp1; + p2 = (const pf_u8*)lp2; + } + + while (length-- != 0) { + if (*p1 != *p2) { + return *p1 - *p2; + } + p1++; + p2++; + } + + return 0; +} + +pf_u32 pf_strlen(const pf_s8* s) { + const pf_s8* t = s; + + while (*t != 0) { + t++; + } + + return (pf_u32)(t - s); +} + +pf_s8* pf_strcpy(pf_s8* dst, const pf_s8* src) { + pf_s8* d; + + for (d = dst; (*d = *src) != 0; src++, d++) { + } + + return dst; +} + +pf_s32 pf_strcmp(const pf_s8* s1, const pf_s8* s2) { + const pf_u8* p1 = (pf_u8*)s1; + const pf_u8* p2 = (pf_u8*)s2; + + while (*p1 != 0 && *p2 != 0 && *p1 == *p2) { + p1++; + p2++; + } + + return *p1 - *p2; +} + +pf_s32 pf_strncmp(const pf_s8* s1, const pf_s8* s2, pf_u32 length) { + const pf_u8* p1 = (pf_u8*)s1; + const pf_u8* p2 = (pf_u8*)s2; + + while (length-- != 0) { + if (!(*p1 != 0 && *p2 != 0 && *p1 == *p2)) { + return *p1 - *p2; + } + p1++; + p2++; + } + + return 0; +} + +pf_u32 pf_w_strlen(const pf_u16* s) { + const pf_u16* t = s; + + while (*t != 0) { + t++; + } + + return ((pf_s8*)t - (pf_s8*)s) >> 1; +} + +pf_u16* pf_w_strcpy(pf_u16* dst, const pf_u16* src) { + pf_u16* d; + + for (d = dst; (*d = *src) != 0; src++, d++) { + } + + return dst; +} + +pf_s32 pf_w_strcmp(const pf_u16* s1, const pf_u16* s2) { + const pf_u16* p1 = (pf_u16*)s1; + const pf_u16* p2 = (pf_u16*)s2; + + while (*p1 != 0 && *p2 != 0 && *p1 == *p2) { + p1++; + p2++; + } + + return *p1 - *p2; +} + +pf_s32 pf_w_strncmp(const pf_u16* s1, const pf_u16* s2, pf_u32 length) { + const pf_u16* p1 = (pf_u16*)s1; + const pf_u16* p2 = (pf_u16*)s2; + + while (length-- != 0) { + if (*p1 == 0 || *p2 == 0 || *p1 != *p2) { + return *p1 - *p2; + } + p1++; + p2++; + } + + return 0; +} diff --git a/libs/RVL_SDK/src/fa/pf_code.c b/libs/RVL_SDK/src/fa/pf_code.c new file mode 100644 index 00000000..9e49f1db --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_code.c @@ -0,0 +1,21 @@ +#include + +// clang-format off +const pf_u8 pf_valid_fn_char_8162E6B0[96] = { + 1, 3, 0, 3, 3, 3, 3, 3, 3, 3, 0, 1, 1, 3, 3, 0, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 0, 1, 0, 0, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 1, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 0, +}; +// clang-format on + +pf_s32 PFCODE_Combine_Width(pf_s16 oem_width, pf_s16 uni_width) { + return (oem_width << 16) + uni_width; +} + +void PFCODE_Divide_Width(pf_s32 width, pf_s16* oem_width, pf_s16* uni_width) { + *oem_width = (width & 0xFFFF0000) >> 16; + *uni_width = (width & 0x0000FFFF); +} diff --git a/libs/RVL_SDK/src/fa/pf_driver.c b/libs/RVL_SDK/src/fa/pf_driver.c new file mode 100644 index 00000000..ed75944b --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_driver.c @@ -0,0 +1,442 @@ +#include + +typedef struct PFDRV_BPB { + pf_u16 bytes_per_sector; // 0x00 + pf_u8 pad_02[0x12]; // 0x02 + pf_u16 fs_info_sector; // 0x14 + pf_u8 pad_16[0x6]; // 0x16 + pf_s32 fat_type; // 0x1C + pf_u8 tail[0x38 - 0x20]; // 0x20 +} PFDRV_BPB; + +typedef struct PFDRV_VOLUME { + PFDRV_BPB bpb; // 0x00 + pf_u32 num_free_clusters; // 0x38 + pf_u32 last_free_cluster; // 0x3C + pf_u8 file_and_dir_state[0x1648 - 0x40]; // 0x40 + pf_s8 label[12]; // 0x1648 + pf_u8 tail_1654[0x1F84 - 0x1654]; // 0x1654 + pf_s32 last_driver_error; // 0x1F84 + pf_u32 reserved_1f88; // 0x1F88 + pf_u16 flags; // 0x1F8C + pf_u16 options; // 0x1F8E + pf_u16 fsi_flag; // 0x1F90 + pf_u16 cluster_link_flags; // 0x1F92 + pf_u16 cluster_link_interval; // 0x1F94 + pf_u32* cluster_link_buffer; // 0x1F98 + pf_u32 cluster_link_capacity; // 0x1F9C + void* driver_partition; // 0x1FA0 + pf_u8 gap_1fa4[4]; // 0x1FA4 + const pf_u8* format_options; // 0x1FA8 +} PFDRV_VOLUME; + +typedef struct PFDRV_VOLUME_SET { + pf_u8 state_prefix[0x40]; // 0x00 + pf_s32 last_error; // 0x40 + pf_s32 last_driver_error; // 0x44 + pf_u8 tail_48[0x88 - 0x48]; // 0x48 + PFDRV_VOLUME volumes[26]; // 0x88 +} PFDRV_VOLUME_SET; + +extern PFDRV_VOLUME_SET pf_vol_set; + +typedef struct PFDRV_CACHE_PAGE { + pf_u16 stat; + pf_u16 option; + pf_u8* buffer; + pf_u8* p_buf; + pf_u8* p_mod_sbuf; + pf_u8* p_mod_ebuf; + pf_u32 size; + pf_u32 sector; + void* signature; + struct PFDRV_CACHE_PAGE* p_next; + struct PFDRV_CACHE_PAGE* p_prev; +} PFDRV_CACHE_PAGE; + +typedef struct PFDRV_PART_FUNC { + void (*insert)(void* partition); + void (*eject)(void* partition); +} PFDRV_PART_FUNC; + +typedef struct PFDRV_MEDIA_INFO { + pf_u32 total_sectors; // 0x00 + pf_u16 cylinders; // 0x04 + pf_u8 heads; // 0x06 + pf_u8 sectors_per_track; // 0x07 + pf_u16 bytes_per_sector; // 0x08 + pf_u16 reserved_0a; // 0x0A + pf_u32 media_attr; // 0x0C + const pf_u8* format_param; // 0x10 +} PFDRV_MEDIA_INFO; + +typedef struct PFDRV_VOLUME_INFO { + pf_s8 label[12]; // 0x00 + pf_u8 tail[8]; // 0x0C +} PFDRV_VOLUME_INFO; + +enum { + FAT_32 = 2 +}; + +extern void* pf_memcpy(void* dst, const void* src, pf_u32 length); + +extern pf_s32 PFCACHE_AllocateDataPage(PFDRV_VOLUME* volume, pf_u32 sector, PFDRV_CACHE_PAGE** p_page, pf_u32* option); +extern void PFCACHE_FreeDataPage(PFDRV_VOLUME* volume, PFDRV_CACHE_PAGE* p_page); + +extern pf_s32 pdm_part_logical_read(void* partition, pf_u8* buffer, pf_u32 sector, pf_u32 num_sector, pf_u16 bps, + pf_u32* p_num_success); +extern pf_s32 pdm_part_logical_write(void* partition, const pf_u8* buffer, pf_u32 sector, pf_u32 num_sector, pf_u16 bps, + pf_u32* p_num_success); +extern pf_s32 pdm_part_register_callback(void* partition, const PFDRV_PART_FUNC* func); +extern pf_s32 pdm_part_unregister_callback(void* partition); +extern pf_s32 pdm_part_init(void* partition); +extern pf_s32 pdm_part_finalize(void* partition); +extern pf_s32 pdm_part_mount(void* partition); +extern pf_s32 pdm_part_unmount(void* partition, pf_u32 mode); +extern pf_s32 pdm_part_get_media_attribute(void* partition, PFDRV_MEDIA_INFO* info); +extern pf_s32 pdm_part_get_driver_error_code(void* partition); +extern pf_s32 pdm_part_format(void* partition, const pf_u8* format_param); +extern pf_s32 pdm_bpb_InitVolumeWithBootSector(PFDRV_VOLUME* volume, const pf_u8* buf); +extern pf_s32 pdm_bpb_InitVolumeWithFSINFOSector(PFDRV_VOLUME* volume, const pf_u8* buf, pf_u32* p_num_free_clusters, + pf_u32* p_last_free_cluster); + +void PFDRV_LoadVolumeLabelFromBuf(PFDRV_VOLUME* volume, const pf_u8* buf) { + pf_memcpy(volume->label, buf, 0xB); + volume->label[0xB] = 0; +} + +void PFDRV_StoreVolumeLabelToBuf(PFDRV_VOLUME_INFO* volume_info, PFDRV_VOLUME* volume) { + pf_memcpy(volume_info->label, volume->label, 0xB); + volume_info->label[0xB] = 0; +} + +pf_s32 PFDRV_StoreVolumeLabelToBPB(PFDRV_VOLUME* volume, const pf_s8* label) { + PFDRV_CACHE_PAGE* p_page; + pf_u32 option; + pf_u32 num_sector; + pf_s32 err; + pf_s32 result; + + err = PFCACHE_AllocateDataPage(volume, -1, &p_page, &option); + if (err != 0) { + return err; + } + + err = pdm_part_logical_read(volume->driver_partition, p_page->p_buf, 0, 1, volume->bpb.bytes_per_sector, &num_sector); + if (err != 0) { + if (err == 0x15) { + result = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = result; + volume->last_driver_error = result; + result = 0x1000; + } else { + result = -1; + } + } else { + result = 0; + } + if (result != 0) { + PFCACHE_FreeDataPage(volume, p_page); + return result; + } + + if (num_sector != 1) { + PFCACHE_FreeDataPage(volume, p_page); + return 0x11; + } + + if (volume->bpb.fat_type == FAT_32) { + pf_memcpy(p_page->p_buf + 0x47, label, 0xB); + } else { + pf_memcpy(p_page->p_buf + 0x2B, label, 0xB); + } + + err = pdm_part_logical_write(volume->driver_partition, p_page->p_buf, 0, 1, volume->bpb.bytes_per_sector, + &num_sector); + if (err != 0) { + if (err == 0x15) { + result = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = result; + volume->last_driver_error = result; + result = 0x1000; + } else { + result = -1; + } + } else { + result = 0; + } + PFCACHE_FreeDataPage(volume, p_page); + if (result != 0) { + return result; + } + + if (num_sector != 1) { + return 0x11; + } + + pf_memcpy(volume->label, label, 0xB); + volume->label[0xB] = 0; + return 0; +} + +void PFDRV_MediaEject(void* partition) { + PFDRV_VOLUME* p_vol; + pf_u32 i; + + p_vol = pf_vol_set.volumes; + for (i = 0; i < 26; p_vol++, i++) { + if (p_vol->driver_partition == partition) { + if ((p_vol->flags & 0x08) != 0) { + p_vol->flags |= 0x20; + } + p_vol->flags &= ~0x0C; + } + } +} + +void PFDRV_MediaInsert(void* partition) { + PFDRV_VOLUME* p_vol; + pf_u32 i; + + p_vol = pf_vol_set.volumes; + for (i = 0; i < 26; p_vol++, i++) { + if (p_vol->driver_partition == partition) { + p_vol->flags |= 0x14; + } + } +} + +pf_s32 PFDRV_IsInserted(PFDRV_VOLUME* volume) { + return (volume->flags >> 2) & 1; +} + +pf_s32 PFDRV_IsMountRequested(PFDRV_VOLUME* volume) { + return (volume->flags >> 4) & 1; +} + +void PFDRV_ClearMountRequested(PFDRV_VOLUME* volume) { + volume->flags &= ~0x10; +} + +pf_s32 PFDRV_IsUnmountRequested(PFDRV_VOLUME* volume) { + return (volume->flags >> 5) & 1; +} + +void PFDRV_ClearUnmountRequested(PFDRV_VOLUME* volume) { + volume->flags &= ~0x20; +} + +pf_s32 PFDRV_init(PFDRV_VOLUME* volume) { + PFDRV_PART_FUNC func; + pf_s32 err; + + func.insert = PFDRV_MediaInsert; + func.eject = PFDRV_MediaEject; + + err = pdm_part_register_callback(volume->driver_partition, &func); + if (err != 0) { + return -1; + } + + err = pdm_part_init(volume->driver_partition); + if (err != 0) { + pdm_part_unregister_callback(volume->driver_partition); + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + return 0; +} + +pf_s32 PFDRV_finalize(PFDRV_VOLUME* volume) { + pf_s32 err; + + err = pdm_part_unregister_callback(volume->driver_partition); + if (err != 0) { + return -1; + } + + err = pdm_part_finalize(volume->driver_partition); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + return 0; +} + +pf_s32 PFDRV_mount(PFDRV_VOLUME* volume) { + PFDRV_MEDIA_INFO info; + pf_u32 option; + PFDRV_CACHE_PAGE* p_page; + pf_u32 num_sector; + pf_s32 err; + + err = pdm_part_mount(volume->driver_partition); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + err = pdm_part_get_media_attribute(volume->driver_partition, &info); + if (err != 0) { + pdm_part_unmount(volume->driver_partition, 0); + return -1; + } + + if ((info.media_attr & 0x01) != 0) { + volume->flags |= 0x02; + } else { + volume->flags &= ~0x02; + } + if ((info.media_attr & 0x02) != 0) { + const pf_u8* format_param = info.format_param; + volume->flags |= 0x40; + volume->format_options = format_param; + } + if ((info.media_attr & 0x08) != 0) { + volume->flags |= 0x80; + } + + PFCACHE_AllocateDataPage(volume, -1, &p_page, &option); + + err = pdm_part_logical_read(volume->driver_partition, p_page->buffer, 0, 1, 0x200, &num_sector); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + err = 0x1000; + } else { + err = -1; + } + PFCACHE_FreeDataPage(volume, p_page); + pdm_part_unmount(volume->driver_partition, 0); + return err; + } + + err = pdm_bpb_InitVolumeWithBootSector(volume, p_page->buffer); + if (err != 0) { + PFCACHE_FreeDataPage(volume, p_page); + pdm_part_unmount(volume->driver_partition, 0); + return 7; + } + + volume->num_free_clusters = -1; + volume->last_free_cluster = -1; + + if (volume->bpb.fat_type == FAT_32) { + err = pdm_part_logical_read(volume->driver_partition, p_page->buffer, volume->bpb.fs_info_sector, 1, 0x200, + &num_sector); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + err = 0x1000; + } else { + err = -1; + } + PFCACHE_FreeDataPage(volume, p_page); + pdm_part_unmount(volume->driver_partition, 0); + return err; + } + + err = pdm_bpb_InitVolumeWithFSINFOSector(volume, p_page->buffer, &volume->num_free_clusters, + &volume->last_free_cluster); + if (err != 0) { + PFCACHE_FreeDataPage(volume, p_page); + pdm_part_unmount(volume->driver_partition, 0); + return -1; + } + } + + PFCACHE_FreeDataPage(volume, p_page); + return 0; +} + +pf_s32 PFDRV_unmount(PFDRV_VOLUME* volume, pf_u32 mode) { + pf_s32 err; + + err = pdm_part_unmount(volume->driver_partition, mode == 1); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + return 0; +} + +pf_s32 PFDRV_format(PFDRV_VOLUME* volume, const pf_u8* format_options) { + pf_s32 err; + + err = pdm_part_format(volume->driver_partition, format_options); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + return 0; +} + +pf_s32 PFDRV_lread(PFDRV_VOLUME* volume, pf_u8* buffer, pf_u32 sector, pf_u32 num_sector, pf_u32* p_num_success) { + pf_s32 err; + + err = pdm_part_logical_read(volume->driver_partition, buffer, sector, num_sector, volume->bpb.bytes_per_sector, + p_num_success); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + return 0; +} + +pf_s32 PFDRV_lwrite(PFDRV_VOLUME* volume, const pf_u8* buffer, pf_u32 sector, pf_u32 num_sector, pf_u32* p_num_success) { + pf_s32 err; + + err = pdm_part_logical_write(volume->driver_partition, buffer, sector, num_sector, volume->bpb.bytes_per_sector, + p_num_success); + if (err != 0) { + if (err == 0x15) { + err = pdm_part_get_driver_error_code(volume->driver_partition); + pf_vol_set.last_driver_error = err; + volume->last_driver_error = err; + return 0x1000; + } + return -1; + } + + return 0; +} diff --git a/libs/RVL_SDK/src/fa/pf_str.c b/libs/RVL_SDK/src/fa/pf_str.c new file mode 100644 index 00000000..74f0cb58 --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_str.c @@ -0,0 +1,229 @@ +#include + +typedef struct PF_STR { + const pf_s8* p_head; + const pf_s8* p_tail; + const pf_s8* p_current; + pf_u32 code_mode; +} PF_STR; + +typedef struct PFSTR_CHARCODE { + pf_s32 (*oem2unicode)(const pf_s8*, pf_u16*); + pf_s32 (*unicode2oem)(const pf_u16*, pf_s8*); + pf_s32 (*oem_char_width)(const pf_s8*); + pf_bool (*is_oem_mb_char)(pf_s8, pf_bool); + pf_s32 (*unicode_char_width)(const pf_u16*); + pf_bool (*is_unicode_mb_char)(pf_u16, pf_bool); +} PFSTR_CHARCODE; + +typedef struct PFSTR_VOLUME_SET { + pf_u8 state_prefix[0x48]; + PFSTR_CHARCODE codeset; +} PFSTR_VOLUME_SET; + +extern PFSTR_VOLUME_SET pf_vol_set; + +extern pf_s32 pf_toupper(pf_s32 c); +extern pf_u32 pf_strlen(const pf_s8* s); +extern pf_u32 pf_w_strlen(const pf_u16* s); +extern pf_s32 pf_strcmp(const pf_s8* s1, const pf_s8* s2); +extern pf_s32 pf_strncmp(const pf_s8* s1, const pf_s8* s2, pf_u32 length); + +void PFSTR_SetCodeMode(PF_STR* p_str, pf_u32 code_mode) { + p_str->code_mode = code_mode; +} + +pf_u32 PFSTR_GetCodeMode(PF_STR* p_str) { + return p_str->code_mode; +} + +void PFSTR_SetLocalStr(PF_STR* p_str, const pf_s8* local_str) { + if (p_str->code_mode == 1 || local_str == PF_NULL) { + p_str->p_current = p_str->p_head; + } else { + p_str->p_current = local_str; + } +} + +pf_s8* PFSTR_GetStrPos(PF_STR* p_str, pf_u32 target) { + pf_s8* p_pos; + if (target == 1) { + p_pos = (pf_s8*)p_str->p_head; + } else if (target == 2) { + p_pos = (pf_s8*)p_str->p_tail; + } else { + p_pos = (pf_s8*)p_str->p_current; + } + return p_pos; +} + +void PFSTR_MoveStrPos(PF_STR* p_str, pf_s16 num_char) { + pf_s16 cnt; + pf_s16 offset = 0; + pf_s32 width; + pf_s8* p; + pf_u16* wp; + + if (PFSTR_GetCodeMode(p_str) == 1) { + p = (pf_s8*)p_str->p_head; + while (num_char != 0) { + if (pf_vol_set.codeset.is_oem_mb_char((pf_s8)*p, PF_TRUE)) { + offset++; + } + offset++; + num_char--; + } + } else { + wp = (pf_u16*)p_str->p_head; + + for (cnt = 0; cnt < num_char; cnt++) { + width = pf_vol_set.codeset.unicode_char_width(wp); + wp += width; + offset += (pf_s16)width; + } + } + + p_str->p_head = &p_str->p_head[offset]; +} + +pf_s32 PFSTR_InitStr(PF_STR* p_str, const pf_s8* s, pf_u32 code_mode) { + if (code_mode == 1) { + p_str->p_head = s; + p_str->p_tail = &s[pf_strlen(s)]; + } else if (code_mode == 2) { + p_str->p_head = s; + p_str->p_tail = s + (pf_w_strlen((pf_u16*)s) * sizeof(pf_u16)); + } + + PFSTR_SetCodeMode(p_str, code_mode); + return 0; +} + +pf_u16 PFSTR_StrLen(PF_STR* p_str) { + return (pf_u16)(p_str->p_tail - p_str->p_head); +} + +pf_u16 PFSTR_StrNumChar(PF_STR* p_str, pf_u32 target) { + pf_s8* p; + pf_u16 cnt; + pf_s32 width; + + if (target == 1) { + p = (pf_s8*)p_str->p_head; + } else { + p = (pf_s8*)p_str->p_tail; + } + + if (p_str->code_mode == 1) { + for (cnt = 0; (pf_s8)*p != 0; cnt++) { + if (pf_vol_set.codeset.is_oem_mb_char((pf_s8)*p, PF_TRUE)) { + p++; + } + p++; + } + } else { + for (cnt = 0; (pf_s8)p[0] != 0 || (pf_s8)p[1] != 0; cnt++) { + width = pf_vol_set.codeset.unicode_char_width((pf_u16*)p); + p += width; + } + } + + return cnt; +} + +pf_s32 PFSTR_StrCmp(const PF_STR* p_str, const pf_s8* s) { + pf_u16 wc; + const pf_u16* wp; + const pf_s8* p1; + const pf_s8* p2; + pf_s32 ret; + + if (p_str->code_mode == 1) { + p1 = p_str->p_head; + p2 = s; + ret = pf_strcmp(p1, p2); + } else { + wp = (pf_u16*)p_str->p_head; + + do { + pf_vol_set.codeset.oem2unicode((pf_s8*)s, &wc); + s++; + + if (*wp++ != wc) { + break; + } + } while (*(wp - 1) != 0 && wc != 0); + + wp--; + ret = *wp - wc; + } + + return ret; +} + +pf_s32 PFSTR_StrNCmp(PF_STR* p_str, const pf_s8* s, pf_u32 target, pf_s16 offset, pf_u16 num) { + pf_u16 wc; + const pf_u16* wp; + const pf_s8* p1; + const pf_s8* p2; + pf_s32 ret; + + if (p_str->code_mode == 1 || target == 3) { + if (target == 1) { + p1 = &p_str->p_head[offset]; + } else if (target == 2) { + p1 = &p_str->p_tail[offset]; + } else { + p1 = &p_str->p_current[offset]; + } + p2 = s; + ret = pf_strncmp(p1, p2, num); + } else { + if (target == 1) { + wp = (pf_u16*)p_str->p_head + offset; + } else { + wp = (pf_u16*)p_str->p_tail + offset; + } + + do { + pf_vol_set.codeset.oem2unicode((pf_s8*)s, &wc); + s++; + num--; + + if (*wp++ != wc || num == 0) { + break; + } + } while (*(wp - 1) != 0 && wc != 0); + + wp--; + ret = *wp - wc; + } + + return ret; +} + +void PFSTR_ToUpperNStr(PF_STR* p_str, pf_u16 num, pf_s8* dest) { + pf_u16 wc; + const pf_u16* wp; + const pf_s8* p; + + if (p_str->code_mode == 1) { + p = (pf_s8*)p_str->p_head; + + for (; num != 0 && *p != 0; p++, num--) { + *dest++ = pf_toupper(*p); + } + } else { + wp = (pf_u16*)p_str->p_head; + + for (; num != 0 && *wp != 0; wp++, num--) { + wc = (*wp >= 'a' && *wp <= 'z') ? *wp + ('A' - 'a') : *wp; + *(dest) = (pf_u8)wc; + *(dest + 1) = (pf_u8)(wc >> 8); + dest += sizeof(pf_u16); + } + *dest = 0; + } + + *dest = 0; +} -- 2.49.1