Compare commits

...

21 Commits

Author SHA1 Message Date
coah
16c3dc834f vi3in1 15/18, kbd_lib 12/21, iplMemoryCardManager (worker feba9540) 2026-09-30 06:04:22 +00:00
coah
856a31f8c9 MSL: printf, wprintf, ansi_fp, time, scanf, strtold (worker 969bc2aa) (#339) 2026-09-30 00:55:53 -05:00
coah
9ea683dd61 eZiText: zi8match, zi8getc2, zikorean, zi8dawg (worker 1f628177) (#338) 2026-09-30 00:54:06 -05:00
github-actions[bot]
ea4ec10115 docs: update progress [skip ci] 2026-09-30 05:46:33 +00:00
devin-ai-integration[bot]
97a2eb1f23 fa: link 6 more pf units (service,fopen,fseek,fsfirst,fsnext,fstat) - objdiff 100% (#337)
Co-authored-by: devin <devin@cognition.ai>
Co-authored-by: wch <usernamecole7@gmail.com>
2026-09-30 05:45:42 +00:00
coah
3cbf4bb3e9 fa: pf_volume 33/37, pf_dir 29/38, pf_fat 29/35, pf_file 43/45 (worker 4c6c5008) (#336) 2026-09-30 00:38:19 -05:00
coah
033b33a486 tiCellPhone: 72/86 functions (worker 1ccf7e1f) (#335) 2026-09-30 00:18:48 -05:00
coah
6b6215ad3e CDBRecord 26/29, CDBIntArray 13/13, NWC24Download (worker 231065dc) (#334) 2026-09-30 00:15:46 -05:00
coah
9ad0863dbf tiHwKeyboard 10/10, tiCandidateBox 105/112, MyTiManager 91/91 (worker 913d06d4) (#333) 2026-09-30 00:14:18 -05:00
coah
41877f03dc NWC24MsgRead 11/16, DateParser 5/8, System 4/4 (worker 5e5e6e1d) (#332) 2026-09-29 23:33:10 -05:00
coah
bc95aa48e9 fa: decompile 29 filesystem units from vf leads (worker dd4743d9) (#331) 2026-09-29 23:20:36 -05:00
coah
64018b3b33 tiTextDrawer 23/24, MyTiLetterForm 26/26 (worker ea883a22) (#330) 2026-09-29 23:19:04 -05:00
coah
2748f29a98 tiString 41/42, tiZiString 24/29 (worker aa0ab97c) (#329) 2026-09-29 22:58:25 -05:00
coah
e6ef163648 NWC24Mime 9/16, NWC24MsgSubject 7/12 (worker eb06c45d) (#328) 2026-09-29 22:57:06 -05:00
github-actions[bot]
c765bd2eca docs: update progress [skip ci] 2026-09-30 03:49:39 +00:00
devin-ai-integration[bot]
c65c722932 fa: link pf_clib, pf_code, pf_str, pf_driver (objdiff 100% code+data) (#327)
Co-authored-by: devin <devin@cognition.ai>
Co-authored-by: wch <usernamecole7@gmail.com>
2026-09-30 03:49:01 +00:00
coah
df54d9a348 NWC24Mime 8/16, NWC24MsgSubject 5/12 (worker fd8d384c) (#326) 2026-09-29 22:27:26 -05:00
coah
b983deeb07 tiHKBManager: 24/29 functions (worker 2e1dbe5d) (#325) 2026-09-29 22:23:10 -05:00
coah
b615148895 fa/pf_entry 20/20, pf_cluster 5/8 (worker 5fc6d9c5) (#324) 2026-09-29 22:08:46 -05:00
coah
95c685534e tiHKBManager: 21/29 functions, data 100% (worker adbf6056) (#323) 2026-09-29 22:05:27 -05:00
coah
68f1674a5d NWC24MsgCommit: 15/18 exact (worker fc42b29c) (#322) 2026-09-29 21:56:26 -05:00
135 changed files with 27171 additions and 2683 deletions

View File

@@ -53,9 +53,9 @@ Progress
<!-- progress:start -->
| Decompiled | Matched | Linked | Data |
|:---:|:---:|:---:|:---:|
| 84.89% | 75.24% | 56.76% | 86.70% |
| 91.56% | 80.70% | 56.95% | 88.70% |
units 748/1027 complete, functions 10976/12563 matched.
units 758/1027 complete, functions 11604/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
<!-- progress:end -->

View File

@@ -1682,11 +1682,11 @@ config.libs = [
]
),
RVLSDKLib("fa", [
Object(NonMatching, "fa/pf_clib.c"),
Object(NonMatching, "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_clib.c"),
Object(Matching, "fa/pf_code.c"),
Object(Matching, "fa/pf_service.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"),
@@ -1733,15 +1733,15 @@ config.libs = [
Object(Matching, "fa/pf_ferror.c"),
Object(NonMatching, "fa/pf_finfo.c"),
Object(Matching, "fa/pf_flock.c"),
Object(NonMatching, "fa/pf_fopen.c"),
Object(Matching, "fa/pf_fopen.c"),
Object(NonMatching, "fa/pf_format.c"),
Object(Matching, "fa/pf_fread.c"),
Object(NonMatching, "fa/pf_fseek.c"),
Object(Matching, "fa/pf_fseek.c"),
Object(NonMatching, "fa/pf_fsetclstlink.c"),
Object(NonMatching, "fa/pf_fsexec.c"),
Object(NonMatching, "fa/pf_fsfirst.c"),
Object(NonMatching, "fa/pf_fsnext.c"),
Object(NonMatching, "fa/pf_fstat.c"),
Object(Matching, "fa/pf_fsfirst.c"),
Object(Matching, "fa/pf_fsnext.c"),
Object(Matching, "fa/pf_fstat.c"),
Object(Matching, "fa/pf_fsync.c"),
Object(Matching, "fa/pf_fwrite.c"),
Object(NonMatching, "fa/pf_getdev.c"),
@@ -1944,7 +1944,7 @@ config.libs = [
Object(Matching, "MSL_Common/alloc.c"),
Object(Matching, "MSL_Common/errno.c"),
Object(Matching, "MSL_Common/ansi_files.c"),
Object(NonMatching, "MSL_Common_Embedded/ansi_fp.c"),
Object(NonMatching, "MSL_Common_Embedded/ansi_fp.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/ctype.c"),
Object(NonMatching, "MSL_Common/locale.c"),
Object(Matching, "MSL_Common/arith.c", extra_cflags=["-Cpp_exceptions on"]),
@@ -1958,19 +1958,19 @@ config.libs = [
Object(Matching, "MSL_Common/mem_funcs.c"),
Object(Matching, "MSL_Common/math_api.c"),
Object(Matching, "MSL_Common/misc_io.c"),
Object(NonMatching, "MSL_Common/printf.c"),
Object(NonMatching, "MSL_Common/printf.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/qsort.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/rand.c"),
Object(NonMatching, "MSL_Common/scanf.c"),
Object(NonMatching, "MSL_Common/scanf.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/signal.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/string.c"),
Object(Matching, "MSL_Common/float.c"),
Object(NonMatching, "MSL_Common/strtold.c"),
Object(NonMatching, "MSL_Common/strtold.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/strtoul.c", extra_cflags=["-Cpp_exceptions on"]),
Object(NonMatching, "MSL_Common/time.c"),
Object(NonMatching, "MSL_Common/time.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/wctype.c"),
Object(Matching, "MSL_Common/wmem.c"),
Object(NonMatching, "MSL_Common/wprintf.c"),
Object(NonMatching, "MSL_Common/wprintf.c", extra_cflags=["-Cpp_exceptions on"]),
Object(Matching, "MSL_Common/wstring.c"),
Object(Matching, "MSL_Common/wchar_io.c"),
Object(Matching, "PPC_EABI/time.dolphin.c"),

View File

@@ -18,7 +18,9 @@ namespace textinput {
LayoutByNW4R(nw4r::lyt::MultiArcResourceAccessor* multiArc, const char* layoutName, EventObserver* event)
: nw4rmanager::Layout(multiArc, layoutName, event) {}
#endif
#ifdef MYTIMANAGER_IMPLEMENTATION
#if defined(MYTIMANAGER_MATCHING)
virtual ~LayoutByNW4R() {}
#elif defined(MYTIMANAGER_IMPLEMENTATION)
virtual ~LayoutByNW4R();
#else
virtual ~LayoutByNW4R() {}

View File

@@ -20,7 +20,7 @@ namespace textinput {
virtual void moveNigaoeButton() {}
};
#ifdef MYTIINPUTFORM_IMPLEMENTATION
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
class ScrollButton;
#endif
@@ -48,7 +48,7 @@ namespace textinput {
#endif
~InputForm();
#ifdef MYTIINPUTFORM_IMPLEMENTATION
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
virtual void moveCursorUp();
virtual void moveCursorDown();
virtual void onCommand(INPUT_COMMAND command, void* data);
@@ -131,7 +131,7 @@ namespace textinput {
void setEditScrollDown(bool editScrollDown) { mbEditScrollUp = editScrollDown; }
void setCloseWithSend(bool closeWithSend) { mbCloseWithSend = closeWithSend; }
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(MYTIINPUTFORM_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
void setEditMode(EditMode editMode);
#else
void setEditMode(EditMode editMode) { meEditMode = editMode; }
@@ -147,8 +147,12 @@ namespace textinput {
tistring::Decolated* getSendString() { return mpSendString; }
#ifdef MYTILETTERFORM_IMPLEMENTATION
protected:
#else
private:
#ifdef MYTIINPUTFORM_IMPLEMENTATION
#endif
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
nw4r::lyt::Pane* mpMemoPane;
nw4r::lyt::Pane* mpMemoRootPane;
nw4r::lyt::Pane* mpBoundPane;
@@ -172,7 +176,7 @@ namespace textinput {
nw4r::lyt::Size mDefaultBoundSize; // 0x358
Mtx mDrawMtx; // 0x360
Mtx mBoundMtx; // 0x390
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(MYTIINPUTFORM_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
util::Animation mExScrollAnm; // 0x3C0
#else
u8 /*todo*/ mExScrollAnm[32]; // 0x3C0
@@ -186,7 +190,7 @@ namespace textinput {
bool mbEditScrollDown; // 0x3EF
bool mbCloseWithSend; // 0x3F0
u8 padding[3]; // 0x3F1
#ifdef MYTIINPUTFORM_IMPLEMENTATION
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
ScrollButton* mpScrollButton;
#else
undefined4* mpScrollButton;

View File

@@ -23,6 +23,15 @@ namespace textinput {
unk_0x400(0), mbPhotoDraw(false), meType(T_MailAddressSel) {}
#endif
#ifdef MYTILETTERFORM_IMPLEMENTATION
virtual ~InputForm();
virtual void create(MEMAllocator*, inputform::EditBuffer*);
virtual void drawBody();
virtual void drawFooter();
virtual void open();
virtual void close();
virtual bool isWholePaneInAnimation();
#endif
virtual nw4r::lyt::Material* getPhotoPaneMaterial();
virtual void onPhotoTrig();
@@ -38,7 +47,11 @@ namespace textinput {
void resizePhotoPane(f32 width, f32 height);
private:
#ifdef MYTILETTERFORM_IMPLEMENTATION
bool mbPhotoScaledUp;
#else
u8 unk_0x400;
#endif
bool mbPhotoDraw; // 0x401
Type meType; // 0x404
};

View File

@@ -167,6 +167,25 @@ namespace textinput {
void setManager(Manager* manager) { mpManager = manager; }
#endif
virtual ~State();
#ifdef MYTIMANAGER_MATCHING
virtual Manager::StateType getStateType() = 0;
virtual void create() = 0;
virtual void init() = 0;
virtual void draw() = 0;
virtual void memoDraw() = 0;
virtual void calc() = 0;
virtual bool updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release) = 0;
virtual bool updateInput(input::HKBManager& hkbManager) = 0;
virtual void start() = 0;
virtual void end() = 0;
#else
virtual Manager::StateType getStateType();
virtual void create();
@@ -184,6 +203,7 @@ namespace textinput {
virtual void start();
virtual void end();
#endif
#ifdef MYTIMANAGER_IMPLEMENTATION
virtual InputForm* InputForm();
virtual keyboard::hwkey::HWKeyboard* HWKeyboard();

View File

@@ -2,20 +2,58 @@
#define TEXTINPUT_CELL_PHONE_H
#include "tiNw4rManager.h"
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#include "tiKeyboard.h"
#endif
#ifdef TI_CELLPHONE_IMPLEMENTATION
#include <revolution/gx.h>
#endif
namespace textinput {
class Manager;
#ifdef TI_CELLPHONE_SAMPLE_CLASS
class EventObserver;
#endif
namespace predictlang {
class LayoutByNW4R;
}
namespace keyboard {
#ifdef TI_CELLPHONE_IMPLEMENTATION
enum VKeyCode {
VK_LINE_FEED = 0,
VK_DELETE = 1,
VK_SIGN_INPUT = 9,
VK_PREDICT_LANGUAGE = 10,
VK_INPUT_MODE_02 = 11,
VK_INPUT_MODE_03 = 13,
VK_INPUT_MODE_00 = 18,
VK_INPUT_MODE_01 = 19,
VK_TOGGLE_ABC_MODE = 23,
};
#endif
namespace signwindow {
class LayoutByNW4R;
}
}
namespace keyboard {
namespace cellphonetype {
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
class EventHandler;
#ifdef TI_CELLPHONE_IMPLEMENTATION
class CellPhoneAnmPane;
struct PaneNameToCharCode;
#endif
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
class Base : public textinput::keyboard::KeyboardBase {
#else
class Base {
#endif
public:
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) && defined(TI_CELLPHONE_SAMPLE_CLASS)
Base(Manager* manager) : mPreviousInputMode(0), mCurrentInputMode(0), mpManager(manager) {}
#endif
enum InputMode {
IM_00,
IM_01,
@@ -31,6 +69,12 @@ namespace textinput {
virtual void onKey(u32, void*) override;
#ifdef TIMANAGER_IMPLEMENTATION
Base(Manager* manager) : mpManager(manager) {}
#endif
#if defined(TI_CELLPHONE_IMPLEMENTATION)
virtual u32 getType() override;
#elif defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
virtual int getType() override;
#elif defined(TIHWKEYBOARD_IMPLEMENTATION)
virtual int getType() override;
#else
virtual void getType() override;
@@ -57,6 +101,9 @@ namespace textinput {
virtual bool isAtokActive();
virtual void doInput();
virtual void updateFixMode();
#ifdef TI_CELLPHONE_IMPLEMENTATION
wchar_t convertToZiCellphoneInput_(wchar_t value);
#endif
#else
virtual void vt_0x08();
virtual void vt_0x0C();
@@ -79,7 +126,7 @@ namespace textinput {
virtual void vt_0x4C();
virtual void vt_0x50();
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
virtual void doNumericMode(bool);
#else
virtual void vt_0x54();
@@ -95,12 +142,16 @@ namespace textinput {
// TODO enum?
int getInputType() const;
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
void resetHoldingButton();
#endif
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) && defined(TI_CELLPHONE_IMPLEMENTATION)
protected:
#else
private:
#endif
u32 mPreviousInputMode;
u32 mCurrentInputMode;
bool mbInputModeLocked;
@@ -109,21 +160,32 @@ namespace textinput {
bool mbUpperCaseMode;
bool mbAbcMode;
bool mbLanguageKeyMode;
#ifdef TI_CELLPHONE_IMPLEMENTATION
const PaneNameToCharCode* mHoldingButton;
#else
u32 mHoldingButton;
#endif
void* mpInputModeTable;
MEMAllocator* mpAllocator;
#ifdef TIMANAGER_IMPLEMENTATION
#ifdef TI_CELLPHONE_IMPLEMENTATION
Manager* mpManager;
bool mInputState;
#elif defined(TIMANAGER_IMPLEMENTATION)
Manager* mpManager;
u32 mInputState;
#else
void* mpInputSettings;
#endif
u32 mInputState;
#endif
#ifdef TI_CELLPHONE_IMPLEMENTATION
void onCtrlKey_(VKeyCode keyCode);
#endif
#endif
};
class LayoutByNW4R : public Base, public nw4rmanager::Layout {
public:
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#ifdef TIMANAGER_IMPLEMENTATION
LayoutByNW4R(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* accessor, EventObserver* observer, const char* layoutName)
: Base(manager), nw4rmanager::Layout(accessor, layoutName, observer), mpEventHandler(NULL) {}
@@ -149,9 +211,18 @@ namespace textinput {
virtual void setPredictLanguageDialog(predictlang::LayoutByNW4R* dialog);
virtual void setSignWindow(signwindow::LayoutByNW4R* window);
#else
#if defined(MYTIMANAGER_IMPLEMENTATION) && defined(TI_CELLPHONE_SAMPLE_CLASS)
LayoutByNW4R(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* resAccessor, EventObserver* observer)
: Base(manager), nw4rmanager::Layout(resAccessor, "fs_VK_cellPhone_a.brlyt", observer), mpSignWindow(NULL) {}
#endif
virtual void doNumericMode(bool);
#ifdef TI_CELLPHONE_IMPLEMENTATION
virtual void setPredictLanguageDialog(predictlang::LayoutByNW4R*);
virtual void setSignWindow(signwindow::LayoutByNW4R*);
#else
virtual void setPredictLanguageDialog(void*);
virtual void setSignWindow(void*);
#endif
#endif
virtual void doNumericWithDotMode(bool);
virtual void setLineFeedButton(bool);
@@ -162,7 +233,7 @@ namespace textinput {
void onPressedShift(bool shift);
void onReleasedShift();
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
bool hasLineFeedButton() const { return mbLineFeedButton; }
private:
bool mbLineFeedButton;
@@ -176,11 +247,45 @@ namespace textinput {
#endif
public:
#endif
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
virtual bool updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release, void* data) override;
virtual bool updateInput(input::HKBManager& hkbManager) override;
#endif
#ifdef TIMANAGER_IMPLEMENTATION
#ifdef TI_CELLPHONE_IMPLEMENTATION
virtual ~LayoutByNW4R();
virtual void create(MEMAllocator* allocator) override;
virtual void init() override;
virtual void draw() override;
virtual void calc() override;
virtual void update() override;
virtual void onKey(u32 key, void* data) override;
virtual void onActive() override;
virtual void updateFromReceiver(u32 command, void* data) override;
virtual void changeInputMode(InputMode mode) override;
virtual void changePredictLanguage() override;
virtual void setAbcMode(bool enabled) override;
virtual void goSignInputMode() override;
virtual void setInputMode(InputMode mode) override;
virtual void setLanguage(Language language) override;
virtual void setCommandReceiver(CommandReceiver* receiver) override;
virtual CellPhoneAnmPane* getAnmPane(InputMode mode);
virtual void throwReleaseForAll();
virtual void changeAnimationAllToNormal();
virtual void updatePredictLanguage(CommandReceiver::ChangePredictMode* mode);
virtual void changeKeyTop(const PaneNameToCharCode* keys);
virtual void changeSpaceKeyTop(const PaneNameToCharCode* keys);
void setUpperCaseJP(bool enabled);
void setLangKeyActive(bool enabled);
void resetHoldingButton();
private:
bool mbLineFeedButton;
GXTexObj mTextures[3];
EventHandler* mpEventHandler;
predictlang::LayoutByNW4R* mpPredictLanguageDialog;
signwindow::LayoutByNW4R* mpSignWindow;
#elif defined(TIMANAGER_IMPLEMENTATION)
virtual nw4rmanager::AnmPane* getAnmPane(InputMode mode);
virtual void throwReleaseForAll();
virtual void changeAnimationAllToNormal();
@@ -190,6 +295,71 @@ namespace textinput {
#endif
};
#ifdef TI_CELLPHONE_SAMPLE_CLASS
class Sample : public LayoutByNW4R {
public:
Sample(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* resAccessor, EventObserver* observer)
: LayoutByNW4R(manager, resAccessor, observer) {}
virtual ~Sample() {}
};
#endif
#ifdef TI_CELLPHONE_IMPLEMENTATION
enum Animation {
ANM_Normal,
ANM_FocusIn,
ANM_FocusOut,
ANM_RollOver,
ANM_Pushed,
ANM_05,
ANM_06,
ANM_ToggleOff,
ANM_Last,
};
enum KeyType {
KT_NormalButton,
KT_ControlButton,
};
class CellPhoneAnmPane : public nw4rmanager::AnmPane {
public:
CellPhoneAnmPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer)
: nw4rmanager::AnmPane(pane, observer), meState(ANM_Normal), meKeyType(KT_NormalButton) {}
virtual void init() override;
virtual void onAnmEvent(AnmPaneEvent event) override;
virtual void changeAnimation(u32 id) override;
virtual KeyType getKeyType() const;
u32 getAnimationState() const { return meState; }
virtual ~CellPhoneAnmPane();
protected:
Animation meState;
KeyType meKeyType;
};
class CellPhoneControlAnmPane : public CellPhoneAnmPane {
public:
CellPhoneControlAnmPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer)
: CellPhoneAnmPane(pane, observer) { meKeyType = KT_ControlButton; }
virtual void onAnmEvent(AnmPaneEvent event) override;
virtual ~CellPhoneControlAnmPane();
};
class EventHandler : public nw4rmanager::TiEventHandler {
public:
EventHandler(LayoutByNW4R* layout) : mpLayoutByNW4R(layout) {}
virtual ~EventHandler();
virtual void onTiEvent(gui::PaneComponent* pane, u32 event, Input* input) override;
private:
LayoutByNW4R* mpLayoutByNW4R;
};
#endif
} // namespace cellphonetype
} // namespace keyboard
} // namespace textinput

View File

@@ -6,9 +6,138 @@
#include <revolution/mem/allocator.h>
#include "keyboard/tiCpData.h"
#ifdef TIHKBMANAGER_IMPLEMENTATION
#include <revolution/kbd.h>
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;
#ifdef TIHWKEYBOARD_IMPLEMENTATION
KeySet GetReleasedKeySet() const;
#endif
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
@@ -22,15 +151,22 @@ namespace textinput {
u32 GetModifierState() const;
void SetModifierState(u32, u32);
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)
class KeySet {
public:
u8 GetKey() const;
#ifdef TIHWKEYBOARD_IMPLEMENTATION
u32 GetWChar() const;
#else
wchar_t GetWChar() const;
#endif
bool IsValid() const;
KeySet GetNext() const;
KeySet(const KeySet& other)
: mpManager(other.mpManager), mKind(other.mKind), mIndex(other.mIndex), mDevice(other.mDevice), mCharacter(other.mCharacter) {}
#ifdef TIHWKEYBOARD_IMPLEMENTATION
KeySet() : mpManager(NULL), mKind(0), mIndex(-1), mDevice(0), mCharacter(0) {}
#endif
private:
const HKBManager* mpManager;
u8 mKind;
@@ -40,6 +176,9 @@ namespace textinput {
};
KeySet GetTriggeredKeySet() const;
KeySet GetRepeatedKeySet() const;
#ifdef TIHWKEYBOARD_IMPLEMENTATION
KeySet GetReleasedKeySet() const;
#endif
void SetForceModifierState(u32 mask, u32 state);
#else
class KeySet {
@@ -48,14 +187,28 @@ namespace textinput {
wchar_t szKeySetName[17]; // 0x04
u16 uNum; // 0x26
u16 uType; // 0x28
#ifdef TI_CELLPHONE_IMPLEMENTATION
public:
bool IsValid() const;
u32 GetKey() const;
wchar_t GetWChar() const;
KeySet GetNext() const;
#endif
};
#ifdef TI_CELLPHONE_IMPLEMENTATION
KeySet GetTriggeredKeySet() const;
KeySet GetRepeatedKeySet() const;
#endif
#endif
private:
u8 unk_0x00[0xFC];
static HKBManager sInstance;
};
#endif
} // namespace input
} // namespace textinput

View File

@@ -25,7 +25,7 @@ namespace textinput {
#endif
virtual void init();
#ifdef TI_PC_KEYBOARD_IMPLEMENTATION
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)
wchar_t convertWCCode(wchar_t code) const;
#endif
@@ -40,6 +40,11 @@ namespace textinput {
void resetQuoteState() { mbSingleQuoteClosing = 0; mbDoubleQuoteClosing = 0; }
#endif
private:
#ifdef TIHWKEYBOARD_IMPLEMENTATION
bool updateRepeatKey_(input::HKBManager&);
bool updateTriggerKey_(input::HKBManager&);
bool updateTappingShift_(input::HKBManager&);
#endif
void updateShift(input::HKBManager& hkbManager);
void controlKeyTriggeredHandler(input::HKBManager);
@@ -50,9 +55,14 @@ namespace textinput {
#ifdef TIINPUTFORM_IMPLEMENTATION
u8 mbSingleQuoteClosing;
u8 mbDoubleQuoteClosing;
#else
#ifdef TIHWKEYBOARD_IMPLEMENTATION
bool field_0x15;
bool field_0x16;
#else
u8 field_0x15; // 0x15
u8 field_0x16; // 0x16
#endif
#endif
};

View File

@@ -144,6 +144,11 @@ namespace textinput {
#ifdef TISIGNWINDOW_IMPLEMENTATION
bool isAtokActive() const;
#endif
#ifdef MYTILETTERFORM_IMPLEMENTATION
virtual void create(MEMAllocator* allocator);
virtual void init();
virtual void onCommand(INPUT_COMMAND command, void* data);
#endif
virtual ~Base();
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
@@ -284,7 +289,7 @@ namespace textinput {
virtual void makeUpCursorPos(CursorPos* cursorPos, u32 pos, s32 startLine, s32 endLine);
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
protected:
#if !defined(TIINPUTFORM_IMPLEMENTATION) && !defined(TIMANAGER_IMPLEMENTATION)
void setCursorPos(tistring::Decolated* string, u32 pos);
@@ -294,7 +299,7 @@ namespace textinput {
#else
private:
#endif
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
nw4r::ut::Rect mRect;
#else
Rect mRect;
@@ -379,13 +384,13 @@ namespace textinput {
virtual void setRootPaneScaleFor16x9();
virtual void setRootPaneScaleFor4x3();
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
virtual void onSE(sound::SE seId);
#endif
virtual void visibleSeparator(bool flag);
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
protected:
const void* mpLayoutData;
const void* mpLanguageData;

View File

@@ -12,7 +12,7 @@ namespace textinput {
KeyboardBase() : meLanguage(JP) {}
#endif
virtual ~KeyboardBase() {}
#if !defined(TI_PC_KEYBOARD_IMPLEMENTATION) && !defined(TIMANAGER_IMPLEMENTATION) && !defined(TISIGNWINDOW_IMPLEMENTATION)
#if !(defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) && !defined(TIMANAGER_IMPLEMENTATION) && !defined(TISIGNWINDOW_IMPLEMENTATION)
virtual void create(MEMAllocator* alloc) override;
virtual void init() override;
virtual void setCommandReceiver(CommandReceiver* receiver) override;
@@ -21,18 +21,24 @@ namespace textinput {
#if !defined(TIMANAGER_IMPLEMENTATION) && !defined(TISIGNWINDOW_IMPLEMENTATION)
virtual void updateFromReceiver(u32, void*) override;
#endif
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
virtual void onKey(u32, void*);
#else
virtual void onKey(u32);
#endif
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#ifdef TI_CELLPHONE_IMPLEMENTATION
virtual u32 getType();
#elif (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
virtual int getType();
#else
virtual void getType();
#endif
#ifdef TI_CELLPHONE_IMPLEMENTATION
virtual void setLanguage(Language language) { meLanguage = language; }
#else
virtual void setLanguage(Language language);
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#endif
#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#ifdef TISIGNWINDOW_IMPLEMENTATION
virtual Language getLanguage() const;
#else

View File

@@ -120,6 +120,9 @@ namespace textinput {
virtual void start() {}
virtual void end() {}
#ifdef TIHWKEYBOARD_IMPLEMENTATION
EventObserver* getEventObserverForHardware() const { return mpEventObserver; }
#endif
virtual InputForm* getInputForm() { return mpInputForm; }
virtual const InputForm* getInputForm() const { return mpInputForm; }

View File

@@ -14,7 +14,7 @@ namespace textinput {
class TiEventHandler : public gui::EventHandler {
public:
typedef struct Input {
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
u32 controller;
f32 x;
f32 y;

View File

@@ -1,7 +1,7 @@
#ifndef TEXTINPUT_PC_KEYBOARD_H
#define TEXTINPUT_PC_KEYBOARD_H
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#include "tiPcKeyboardImpl.h"
#else
@@ -65,7 +65,11 @@ namespace textinput {
virtual void init() override;
virtual void updateFromReceiver(u32, void*) override;
virtual void onKey(u32, void*) override;
#ifdef TI_CELLPHONE_IMPLEMENTATION
virtual u32 getType() override;
#else
virtual void getType() override;
#endif
virtual void setLanguage(Language) override;
virtual void onActive() override;
virtual void inputCharCode(u16);

View File

@@ -226,6 +226,12 @@ namespace textinput {
State mState;
const LanguageData* mpInitialLanguageData;
KeyState mKeyState;
#ifdef TIHWKEYBOARD_IMPLEMENTATION
public:
KeyState& hardwareKeyState() { return mKeyState; }
bool hardwareLanguageKeyActive() const { return mbLanguageKeyActive; }
protected:
#endif
MEMAllocator* mpAllocator;
bool mbOnlyQwerty;
bool mbLanguageKeyActive;

View File

@@ -3,7 +3,7 @@
#include <revolution/types.h>
#include <revolution/mem/allocator.h>
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
#include <revolution/kpr.h>
#endif
@@ -39,7 +39,7 @@ namespace textinput {
virtual wchar_t* getWCString() const { return mpszString; }
virtual void setCandidate(wchar_t candidate) { mwcCandidate = candidate; }
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
virtual wchar_t getCandidate() const { return mwcCandidate; }
#else
virtual wchar_t getCandidate() { return mwcCandidate; }
@@ -48,7 +48,11 @@ namespace textinput {
virtual wchar_t getLastWChar();
#if defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
protected:
#else
private:
#endif
u16 muMaxLength; // 0x04
u16 muLength; // 0x06
@@ -61,7 +65,7 @@ namespace textinput {
};
class KanaStream {
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
public:
KPRQueue mQueue;
wchar_t mPending;
@@ -74,13 +78,13 @@ namespace textinput {
class Decolated : public StringBase {
public:
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
Decolated(u16 maxLen) : StringBase(maxLen), mCursorStart(0), mCursorEnd(0), mbSustain(false), mTranslateMode(0) { initKanaConverter(); }
#else
Decolated(u16 maxLen) : StringBase(maxLen), field_0x18(0), field_0x1C(0), field_0x20(0), field_0x24(0) { initKanaConverter(); }
#endif
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
virtual ~Decolated();
enum TranslateMode { TM_Direct, TM_Kana, TM_Roman, TM_Hangul };
virtual void clear();
@@ -103,7 +107,7 @@ namespace textinput {
virtual u32 getCursorPos() const;
virtual void getCursorPos(u32* start, u32* end);
virtual bool canBackSpace();
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
virtual bool deleteForward();
#else
virtual void deleteForward();
@@ -161,12 +165,21 @@ namespace textinput {
#endif
#if defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
protected:
#else
private:
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#endif
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
u32 mCursorStart;
u32 mCursorEnd;
#if defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
u8 mbSustain;
s32 mTranslateMode;
#else
bool mbSustain;
u32 mTranslateMode;
#endif
#else
u32 field_0x18; // 0x18
u32 field_0x1C; // 0x1C
@@ -176,7 +189,7 @@ namespace textinput {
KanaStream mKanaStream; // 0x28
};
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISTRING_IMPLEMENTATION) || defined(TIZISTRING_IMPLEMENTATION)
class WithAtok : public Decolated {
public:
WithAtok(u16 maxLength) : Decolated(maxLength) {}

View File

@@ -6,13 +6,13 @@
#include <nw4r/ut/CharWriter.h>
#include <nw4r/ut/Rect.h>
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
#include <string.h>
#endif
namespace textinput {
namespace textdrawer {
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
class Base : public nw4r::ut::CharWriter {
#else
class Base : nw4r::ut::CharWriter {
@@ -34,7 +34,7 @@ namespace textinput {
} CursorPos;
typedef struct DrawInfo {
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
nw4r::ut::Rect rect;
wchar_t character;
#else
@@ -94,7 +94,7 @@ namespace textinput {
virtual u32 getEndPos() const;
// todo
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
virtual void setDrawModifyScopeLine(s32 startLine, s32 endLine);
virtual void setDrawCacheScopeLine(s32 startLine, s32 endLine);
virtual void modifyCursorCache(s32 line, u32 position, f32 x, f32 y, f32 width, f32 height);
@@ -103,12 +103,12 @@ namespace textinput {
virtual void setDrawCacheScopeLine();
virtual void modifyCursorCache();
#endif
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
virtual bool isEnableCursorCache() const;
#else
virtual void isEnableCursorCache();
#endif
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
virtual u32 getDrawModifyStartLine() const;
virtual u32 getDrawModifyEndLine() const;
#else
@@ -119,7 +119,42 @@ namespace textinput {
virtual void dirtyDrawCache();
virtual void dirtyCursorCache();
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#ifdef TITEXTDRAWER_IMPLEMENTATION
protected:
const wchar_t* mpDrawString;
ViewPort mSavedViewport;
f32 mSavedProjection[7];
nw4r::ut::Rect mProjectionRect;
f32 mfVIWidth;
bool mbAspect4x3;
bool mbDrawClipped;
s32 muLine;
f32 mfLineSpacing;
f32 mfCharacterSpacing;
f32 mfFontWidth;
f32 mfFontHeight;
f32 mfModifyStartY;
f32 mfMinScrollY;
u32 muDrawStartPos;
u32 muDrawEndPos;
u32 muDrawCacheStartPos;
bool mbSecretMode;
s32 muDrawModifyStartLine;
s32 muDrawModifyEndLine;
s32 muDrawModifyStartPos;
s32 muDrawModifyEndPos;
u32 muCachedStartPos;
u32 muCachedEndPos;
bool mbDrawCache;
f32 mfCachedCursorX;
f32 mfCachedCursorY;
f32 mfDrawScrollY;
s32 mnCachedCursorLine;
CursorPos mCachedCursor;
bool mbCursorCache;
bool mbMaintainCursorCache;
#else
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
protected:
MEMAllocator* mpDrawAllocator;
u8 mDrawConfiguration[0x34];
@@ -145,7 +180,7 @@ namespace textinput {
u8 unk_0x50[0x78];
#endif
bool mbSecretMode; // 0xC8
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TITEXTDRAWER_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION)
u32 muDrawModifyStartLine;
u32 muDrawModifyEndLine;
u32 muDrawModifyStartPos;
@@ -167,6 +202,7 @@ namespace textinput {
u8 mDrawCacheState[0x14];
#else
u8 unk_0xCC[0x3C];
#endif
#endif
};
}

View File

@@ -54,11 +54,14 @@ namespace textinput {
class CommandSender;
class CommandReceiver : public Base {
public:
#ifdef TI_CELLPHONE_IMPLEMENTATION
struct ChangePredictMode;
#endif
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
CommandReceiver() { clearSender(); }
virtual ~CommandReceiver();
#endif
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(MYTIINPUTFORM_IMPLEMENTATION) || defined(MYTILETTERFORM_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
struct Scroll {
bool absY;
f32 x;
@@ -70,7 +73,7 @@ namespace textinput {
INPUT_COMMAND_37 = 37,
} INPUT_COMMAND;
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION)
struct ChangePredictMode { u32 mode; bool enabled; };
#endif
virtual void clearSender();
@@ -86,7 +89,7 @@ namespace textinput {
CommandSender() : mpCommandReceiver(NULL) {}
virtual void setCommandReceiver(CommandReceiver* cmdRecv);
#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION)
virtual void sendCommand(u32 command, void* data) {
if (mpCommandReceiver != NULL) mpCommandReceiver->onCommand(static_cast<CommandReceiver::INPUT_COMMAND>(command), data);
}

View File

@@ -56,10 +56,19 @@ namespace textinput {
virtual void onOK();
virtual void onCancel();
virtual void setQwertyWithSE(bool qwerty);
#ifdef TI_CELLPHONE_IMPLEMENTATION
virtual bool isEnableKeytopChange() const { return mbIsEnableQwertyChg; }
#else
virtual bool isEnableKeytopChange() const;
#endif
virtual void enableKeytopChange(bool enable);
#ifdef MYTIMANAGER_MATCHING
virtual nw4r::lyt::Pane* getDownArea();
virtual nw4r::lyt::Pane* getUpArea();
#else
virtual nw4r::lyt::Pane* getUpArea();
virtual nw4r::lyt::Pane* getDownArea();
#endif
virtual void setOKButtonVisible(bool visible);
virtual void setCancelButtonVisible(bool visible);
virtual void setOKButtonCaption(const wchar_t* caption);

View File

@@ -20,9 +20,15 @@ namespace textinput {
wchar_t KBD_ConvertSmall(wchar_t ch);
wchar_t KBD_ConvertAll(wchar_t ch);
#ifdef TISTRING_IMPLEMENTATION
u32 KBD_IsDakuten(wchar_t ch);
u32 KBD_IsHandaku(wchar_t ch);
u32 KBD_IsSmall(wchar_t ch);
#else
bool KBD_IsDakuten(wchar_t ch);
bool KBD_IsHandaku(wchar_t ch);
bool KBD_IsSmall(wchar_t ch);
#endif
bool strcmp(const char* s1, const char* s2);
void replaceChar(char* dest, u32 destLen, const char* src, int replaceIdx, char newCh);

View File

@@ -1,14 +1,102 @@
#ifndef TEXTINPUT_ZI_STRING_H
#define TEXTINPUT_ZI_STRING_H
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIZISTRING_IMPLEMENTATION)
#include "tiString.h"
extern "C" {
#include <eztx.h>
}
#elif defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#include "tiString.h"
#include <eztx.h>
#endif
namespace textinput {
namespace tistring {
#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
#if defined(TIZISTRING_IMPLEMENTATION)
class WithZi : public Decolated {
public:
enum PredictLanguage {
PL_0,
PL_1,
PL_2,
PL_3,
PL_4,
PL_5,
PL_6,
PL_7,
PL_8,
PL_9,
PL_10,
PL_11
};
enum LetterMode {
LM_0,
LM_1,
LM_2,
LM_3
};
static u16 ElementBuffer[0x100];
static u16 CandidatesBuffer[0x300];
static u16 CandidatedWord[0xa00];
static u16 LatestWord[0x40];
virtual ~WithZi();
virtual void create(MEMAllocator*);
virtual void pushBack(wchar_t);
virtual void popBack();
virtual void clear();
virtual void inputChar(wchar_t);
virtual void backSpace();
virtual void confirm(const wchar_t*);
virtual bool moveCursorRight();
virtual bool moveCursorLeft();
virtual bool canBackSpace();
virtual void EnableKSXFilter(bool);
virtual void init();
virtual void setInputting(wchar_t);
virtual u32 getCurrentNumPredicted();
virtual void getPredicted(int, wchar_t*);
virtual wchar_t* getCurrentSelected();
virtual u16 getInputStringLength();
virtual void setSelectedCandidate(s32);
virtual bool isFix();
virtual void setPredictLaunguage(PredictLanguage);
virtual void changeLetterMode(LetterMode);
virtual void ChangeDictionaryLanguage(u8);
virtual void setCellPhoneHoldingkey(void*);
virtual u32 setElementBuffer();
virtual u8 getPredictLanguage();
void openDictionary(void*, void*);
void clearCandidates();
void partialConfirmForKR();
void update();
u32 complementsCandidates_(s32);
void setCurrentWord(const wchar_t*);
u32 getCurrentInput(wchar_t*, u32);
wchar_t* getCurrentInput();
private:
EZTXGetParam mSearch;
u32 mSearchState;
u8 mbDictionaryOpen;
u8 mbContextChanged;
u32 mCurrentWordLength;
EZTXLanguageEntry* mpDictionaries;
void* mpDictionaryWork;
u16 mInputLength;
u32 mCandidateCount;
u32 mOemDictionaryId;
u8 mDictionaryLanguage;
s32 mSelectedCandidate;
PredictLanguage mPredictLanguage;
LetterMode mLetterMode;
void* mpHoldingKey;
u8 mbKoreanPartialConfirm;
};
#elif defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION)
class WithZi : public Decolated {
public:
enum PredictLanguage { PL_Default };

View File

@@ -0,0 +1,41 @@
#ifndef MSL_FORMAT_RUNTIME_H
#define MSL_FORMAT_RUNTIME_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <internal/locale.h>
#define SIGDIGLEN 36
#define LDBL_MANT_DIG 53
#define LDBL_MAX_EXP 1024
#define LDBL_MIN_EXP (-1021)
#define DBL_MAX 1.7976931348623157e308
#define DBL_MIN 2.2250738585072014e-308
#define DBL_EPSILON 2.2204460492503131e-16
#define EOF (-1)
typedef long ptrdiff_t;
typedef long long intmax_t;
typedef unsigned long long uintmax_t;
typedef struct {
char sign;
short exp;
struct { unsigned char length; unsigned char text[SIGDIGLEN]; } sig;
} decimal;
typedef struct { char style; short digits; } decform;
enum __ReadProcActions { __GetAChar, __UngetAChar, __TestForError };
typedef struct { char* CharStr; size_t MaxCharCount; size_t CharsWritten; } __OutStrCtrl;
typedef struct { char* NextChar; int NullCharDetected; } __InStrCtrl;
void __num2dec(const decform*, double, decimal*);
double __dec2num(const decimal*);
size_t __fwrite(const void*, size_t, size_t, FILE*);
int __StringRead(void*, int, int);
unsigned long __strtoul(int, int, int (*)(void*, int, int), void*, int*, int*, int*);
unsigned long long __strtoull(int, int, int (*)(void*, int, int), void*, int*, int*, int*);
long double __strtold(int, int (*)(void*, int, int), void*, int*, int*);
int wctomb(char*, wchar_t);
double nan(const char*);
#define signbit(x) __signbitd(x)
#endif

View File

@@ -0,0 +1,43 @@
MSL restoration, 43U, baseline 0 exact functions and 0 matched code/data in all six units.
Sources: zeldaret/tp MSL printf/wprintf; public Mario Strikers Charged MSL decimal/scanning/strtold references in /tmp/mscharged-new; time reference experiments in /tmp. All measurements were rebuilt locally.
printf long2str: corrected 32-bit minimum constant; 138/138 instructions, zero differences.
printf float2str: removed unnecessary short narrowing from exponent update; 500/500 instructions, zero differences.
printf double2hex:
1. Deferred output pointer initialization until after width validation: 242/242, 97 differences.
2. Moved output pointer declaration after decimal: 242/242, same 97 differences.
3. Copied incoming format into a local format: 244/242 and larger frame; rejected.
4. Reconstructed the actual zero-value path and ordinary literal 0x0p0 from target assembly.
5. Corrected unconditional exponent subtraction and explicit byte narrowing based on target assembly. Remaining struct argument copies use floating loads/stores instead of integer loads/stores; conversion-loop scheduling differs.
printf __pformatter:
1. Moved format declaration after buffers: 535/535, same 321 differences.
2. Initialized format to zero: 540/535, additional stores; rejected.
3. Copied parsed format before dispatch, with both locals declared at function entry: 515/535 after target semantic fixes, larger frame; rejected.
4. Removed hex-prefix zero-fill handling absent from this binary. Remaining mismatch is by-value struct copy code generation; target has 535 instructions, source 511.
wprintf double2hex:
1. Used the Charged reference implementation: 246/242, different frame/scheduling; rejected.
2. Deferred output pointer initialization: 243/242, register and copy differences remained.
3. Moved output pointer declaration after decimal: 243/242, unchanged differences.
4. Reconstructed zero-value output and unconditional exponent subtraction from target assembly. Explicit byte narrowing improved conversion instructions; struct-copy and loop scheduling remain open.
wprintf __wpformatter:
1. Initialized local format: 596/593, additional stores; rejected.
2. Moved format declaration after buffers: 591/593, changed scheduling; rejected.
3. Copied parsed format before dispatch: 595/593, larger frame; rejected.
4. Corrected the imported narrow Pascal-string branch to read and advance its actual input pointer, eliminating an uninitialized output-pointer read.
5. Removed hex-prefix zero-fill handling absent from the target. Remaining struct-copy code generation and register scheduling differ.
wprintf __wStringWrite: used the real callback result from wmemcpy; 27/27 instructions, zero differences.
ansi_fp: all ten functions have zero ctxdiff differences. Exception metadata enabled for this unit, using the same setting as matching MSL siblings. Code 6512/6512 and data 780/780.
time strftime:
1. Assigned default calendar fields individually: 906/913, scheduling differences; rejected.
2. Initialized the default calendar at declaration: 913/913, 34 remaining string-offset differences; retained.
3. Moved format-pointer declaration before locale: 913/913, 76 differences; rejected.
4. Replaced imported pooled-string address arithmetic with ordinary literals. Reconstructed real asctime/ctime formatting to account for the original literals, rather than retaining fake calls with missing format arguments.
5. With ordinary source-token order restored, strftime has 913/913 instructions and zero ctxdiff differences. Keeping the shared asctime result local to asctime restored the target BSS symbols; exception records for the additional real library functions still differ at unit level. No padding or forced placement was added.
scanf: all four functions have zero ctxdiff differences, code 5484/5484 and data 388/388. The formatter retains its actual secure-mode parameter.
strtold: __strtold has 1277/1277 instructions and strtod 44/44, both zero differences. Removed the imported inline qualifier from the public strtod wrapper so the real target symbol is emitted. Code 5284/5284 and data 112/112.
Exception metadata settings change only owned NonMatching units; configure.py status flags remain NonMatching. Clean gates require the original DOL SHA1 and zero baseline regressions. Raw instruction-exact counts can be lower than objdiff exact counts because the varargs conditional branch to an external register-save helper is compared without relocation normalization by gate.py. These counts are reported separately; they were not patched or hidden.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,817 @@
#include <internal/format_runtime.h>
typedef long long intmax_t;
enum argument_options {
normal_argument,
char_argument,
short_argument,
long_argument,
intmax_argument,
size_t_argument,
ptrdiff_argument,
long_long_argument,
double_argument,
long_double_argument,
wchar_argument
};
typedef unsigned char char_map[32];
typedef struct {
unsigned char suppress_assignment;
unsigned char field_width_specified;
unsigned char argument_options;
unsigned char conversion_char;
int field_width;
char_map char_set;
} scan_format;
#define set_char_map(map, ch) map[(unsigned char)ch >> 3] |= (1 << (ch & 7))
#define tst_char_map(map, ch) (map[(unsigned char)ch >> 3] & (1 << (ch & 7)))
static const char* parse_format(const char* format_string, scan_format* format) {
const char* s = format_string;
int c;
int flag_found, invert;
scan_format f = {0, 0, normal_argument, 0, 2147483647, {0}};
if (((c = *++s) == '%')) {
f.conversion_char = c;
*format = f;
return s + 1;
}
if (c == '*') {
f.suppress_assignment = 1;
c = *++s;
}
if (isdigit(c)) {
f.field_width = 0;
do {
f.field_width = (f.field_width * 10) + (c - '0');
c = *++s;
} while (isdigit(c));
if (f.field_width == 0) {
f.conversion_char = 0xFF;
*format = f;
return s + 1;
}
f.field_width_specified = 1;
}
flag_found = 1;
switch (c) {
case 'h':
f.argument_options = short_argument;
if (s[1] == 'h') {
f.argument_options = char_argument;
c = *++s;
}
break;
case 'l':
f.argument_options = long_argument;
if (s[1] == 'l') {
f.argument_options = long_long_argument;
c = *++s;
}
break;
case 'L':
f.argument_options = long_double_argument;
break;
case 'j':
f.argument_options = intmax_argument;
break;
case 'z':
f.argument_options = size_t_argument;
break;
case 't':
f.argument_options = ptrdiff_argument;
break;
default:
flag_found = 0;
}
if (flag_found) {
c = *++s;
}
f.conversion_char = c;
switch (c) {
case 'd':
case 'i':
case 'u':
case 'o':
case 'x':
case 'X':
if (f.argument_options == long_double_argument) {
f.conversion_char = 0xFF;
break;
}
break;
case 'a':
case 'A':
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
if (f.argument_options == char_argument || f.argument_options == short_argument ||
f.argument_options == intmax_argument || f.argument_options == size_t_argument ||
f.argument_options == ptrdiff_argument || f.argument_options == long_long_argument) {
f.conversion_char = 0xFF;
break;
}
if (f.argument_options == long_argument) {
f.argument_options = double_argument;
}
break;
case 'p':
f.argument_options = long_argument;
f.conversion_char = 'x';
break;
case 'c':
if (f.argument_options == long_argument) {
f.argument_options = wchar_argument;
} else {
if (f.argument_options != normal_argument) {
f.conversion_char = 0xFF;
}
}
break;
case 's':
if (f.argument_options == long_argument) {
f.argument_options = wchar_argument;
} else {
if (f.argument_options != normal_argument) {
f.conversion_char = 0xFF;
}
}
{
int i;
unsigned char* p;
for (i = sizeof(f.char_set), p = f.char_set; i; --i) {
*p++ = 0xFF;
}
f.char_set[1] = 0xC1;
f.char_set[4] = 0xFE;
}
break;
case 'n':
break;
case '[':
if (f.argument_options == long_argument) {
f.argument_options = wchar_argument;
} else {
if (f.argument_options != normal_argument) {
f.conversion_char = 0xFF;
}
}
c = *++s;
invert = 0;
if (c == '^') {
invert = 1;
c = *++s;
}
if (c == ']') {
set_char_map(f.char_set, ']');
c = *++s;
}
while (c && c != ']') {
int d;
set_char_map(f.char_set, c);
if (*(s + 1) == '-' && (d = *(s + 2)) != 0 && d != ']') {
while (++c <= d) {
set_char_map(f.char_set, c);
}
c = *(s += 3);
} else {
c = *++s;
}
}
if (!c) {
f.conversion_char = 0xFF;
break;
}
if (invert) {
int i;
unsigned char* p;
for (i = sizeof(f.char_set), p = f.char_set; i; --i, ++p) {
*p = ~*p;
}
break;
}
break;
default:
f.conversion_char = 0xFF;
break;
}
*format = f;
return s + 1;
}
int __sformatter(int (*ReadProc)(void*, int, int), void* ReadProcArg, const char* format_str, va_list arg,
int is_secure) {
int num_chars, chars_read, items_assigned, conversions;
int base, negative, overflow;
int rval;
const char* format_ptr;
char format_char;
char c;
scan_format format;
long long_num;
unsigned long u_long_num;
long long long_long_num = 0;
unsigned long long u_long_long_num;
long double long_double_num;
char* arg_ptr;
int elem_valid;
size_t elem_maxsize;
int match_failure = 0;
int terminate = 0;
format_ptr = format_str;
chars_read = 0;
items_assigned = 0;
conversions = 0;
while (!terminate && (format_char = *format_ptr) != 0) {
if (isspace(format_char)) {
do {
format_char = *++format_ptr;
} while (isspace(format_char));
if (!match_failure) {
while (isspace(c = (*ReadProc)(ReadProcArg, 0, __GetAChar))) {
++chars_read;
}
(*ReadProc)(ReadProcArg, c, __UngetAChar);
}
continue;
}
if ((format_char != '%') && (!match_failure)) {
if ((c = (*ReadProc)(ReadProcArg, 0, __GetAChar)) != (unsigned char)format_char) {
(*ReadProc)(ReadProcArg, c, __UngetAChar);
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
++format_ptr;
continue;
}
}
chars_read++;
format_ptr++;
continue;
}
format_ptr = parse_format(format_ptr, &format);
if (!format.suppress_assignment && format.conversion_char != '%') {
arg_ptr = va_arg(arg, char*);
} else {
arg_ptr = 0;
}
if ((format.conversion_char != 'n') && (!match_failure) && (*ReadProc)(ReadProcArg, 0, __TestForError)) {
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
}
}
switch (format.conversion_char) {
case 'd':
base = 10;
goto signed_int;
case 'i':
base = 0;
signed_int:
if (match_failure) {
long_num = 0;
long_long_num = 0;
} else {
if ((format.argument_options == long_long_argument) ||
(format.argument_options == intmax_argument)) {
u_long_long_num = __strtoull(base, format.field_width, ReadProc, ReadProcArg, &num_chars,
&negative, &overflow);
} else {
u_long_num = __strtoul(base, format.field_width, ReadProc, ReadProcArg, &num_chars, &negative,
&overflow);
}
if (!num_chars) {
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
long_num = 0;
long_long_num = 0;
goto signed_int_assign;
}
}
chars_read += num_chars;
if ((format.argument_options == long_long_argument) ||
(format.argument_options == intmax_argument)) {
long_long_num = (negative ? -u_long_long_num : u_long_long_num);
} else {
long_num = (negative ? -u_long_num : u_long_num);
}
}
signed_int_assign:
if (arg_ptr) {
switch (format.argument_options) {
case normal_argument:
*(int*)arg_ptr = long_num;
break;
case char_argument:
*(signed char*)arg_ptr = long_num;
break;
case short_argument:
*(short*)arg_ptr = long_num;
break;
case long_argument:
*(long*)arg_ptr = long_num;
break;
case intmax_argument:
*(intmax_t*)arg_ptr = long_long_num;
break;
case size_t_argument:
*(size_t*)arg_ptr = long_num;
break;
case ptrdiff_argument:
*(ptrdiff_t*)arg_ptr = long_num;
break;
case long_long_argument:
*(long long*)arg_ptr = long_long_num;
break;
}
if (!match_failure) {
items_assigned++;
}
}
conversions++;
break;
case 'o':
base = 8;
goto unsigned_int;
case 'u':
base = 10;
goto unsigned_int;
case 'x':
case 'X':
base = 16;
unsigned_int:
if (match_failure) {
u_long_num = 0;
u_long_long_num = 0;
} else {
if ((format.argument_options == long_long_argument) ||
(format.argument_options == intmax_argument)) {
u_long_long_num = __strtoull(base, format.field_width, ReadProc, ReadProcArg, &num_chars,
&negative, &overflow);
} else {
u_long_num = __strtoul(base, format.field_width, ReadProc, ReadProcArg, &num_chars, &negative,
&overflow);
}
if (!num_chars) {
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
u_long_num = 0;
u_long_long_num = 0;
goto unsigned_int_assign;
}
}
chars_read += num_chars;
if (negative) {
if (format.argument_options == long_long_argument) {
u_long_long_num = -u_long_long_num;
} else {
u_long_num = -u_long_num;
}
}
}
unsigned_int_assign:
if (arg_ptr) {
switch (format.argument_options) {
case normal_argument:
*(unsigned int*)arg_ptr = u_long_num;
break;
case char_argument:
*(unsigned char*)arg_ptr = u_long_num;
break;
case short_argument:
*(unsigned short*)arg_ptr = u_long_num;
break;
case long_argument:
*(unsigned long*)arg_ptr = u_long_num;
break;
case intmax_argument:
*(intmax_t*)arg_ptr = u_long_long_num;
break;
case size_t_argument:
*(size_t*)arg_ptr = u_long_num;
break;
case ptrdiff_argument:
*(ptrdiff_t*)arg_ptr = u_long_num;
break;
case long_long_argument:
*(unsigned long long*)arg_ptr = u_long_long_num;
break;
}
if (!match_failure) {
items_assigned++;
}
}
conversions++;
break;
case 'a':
case 'A':
case 'f':
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
flt:
if (match_failure) {
long_double_num = NAN;
} else {
long_double_num = __strtold(format.field_width, ReadProc, ReadProcArg, &num_chars, &overflow);
if (!num_chars) {
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
long_double_num = NAN;
goto assign_float;
}
}
chars_read += num_chars;
}
assign_float:
if (arg_ptr) {
switch (format.argument_options) {
case normal_argument:
*(float*)arg_ptr = long_double_num;
break;
case double_argument:
*(double*)arg_ptr = long_double_num;
break;
case long_double_argument:
*(long double*)arg_ptr = long_double_num;
break;
}
if (!match_failure) {
items_assigned++;
}
}
conversions++;
break;
case 'c':
if (!format.field_width_specified) {
format.field_width = 1;
}
if (arg_ptr) {
if (is_secure) {
elem_valid = 1;
elem_maxsize = va_arg(arg, size_t);
}
num_chars = 0;
if (match_failure) {
if (elem_maxsize > 0) {
*arg_ptr = 0;
}
continue;
} else {
char* arg_start = arg_ptr;
while (format.field_width-- &&
(!is_secure || ((elem_valid = (elem_maxsize > num_chars)) != 0)) &&
((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) {
c = rval;
if (format.argument_options == wchar_argument) {
mbtowc(((wchar_t*)arg_ptr), (char*)(&c), 1);
arg_ptr += sizeof(char);
} else {
*arg_ptr++ = c;
}
num_chars++;
}
c = rval;
if (!num_chars || (is_secure && !elem_valid)) {
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
if (elem_maxsize > 0) {
*arg_start = 0;
}
continue;
}
}
chars_read += num_chars;
items_assigned++;
}
} else {
num_chars = 0;
while (format.field_width-- && ((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) {
c = rval;
num_chars++;
}
c = rval;
if (!num_chars) {
goto exit;
}
}
conversions++;
break;
case '%':
if (match_failure) {
continue;
} else {
while (isspace(c = (*ReadProc)(ReadProcArg, 0, __GetAChar))) {
chars_read++;
}
if (c != '%') {
(*ReadProc)(ReadProcArg, c, __UngetAChar);
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
continue;
}
}
chars_read++;
}
break;
case 's':
if (!match_failure) {
c = (*ReadProc)(ReadProcArg, 0, __GetAChar);
while (isspace(c)) {
chars_read++;
c = (*ReadProc)(ReadProcArg, 0, __GetAChar);
}
(*ReadProc)(ReadProcArg, c, __UngetAChar);
}
case '[':
if (arg_ptr) {
if (is_secure) {
elem_valid = 1;
elem_maxsize = va_arg(arg, size_t) - 1;
}
num_chars = 0;
if (match_failure) {
if (elem_maxsize > 0) {
*arg_ptr = 0;
}
continue;
} else {
char* arg_start = arg_ptr;
while (format.field_width-- &&
(!is_secure || ((elem_valid = (elem_maxsize >= num_chars)) != 0)) &&
((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) {
c = rval;
if (!tst_char_map(format.char_set, c)) {
break;
}
if (format.argument_options == wchar_argument) {
mbtowc(((wchar_t*)arg_ptr), (char*)&c, 1);
arg_ptr = (char*)((wchar_t*)arg_ptr + 1);
} else {
*arg_ptr++ = c;
}
num_chars++;
}
c = rval;
if (!num_chars || (is_secure && !elem_valid)) {
(*ReadProc)(ReadProcArg, c, __UngetAChar);
if (!is_secure) {
goto exit;
} else {
match_failure = 1;
if (elem_maxsize > 0) {
*arg_start = 0;
}
continue;
}
}
chars_read += num_chars;
if (format.argument_options == wchar_argument) {
*(wchar_t*)arg_ptr = L'\0';
} else {
*arg_ptr = 0;
}
items_assigned++;
}
} else {
num_chars = 0;
while (format.field_width-- && ((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) {
c = rval;
if (!tst_char_map(format.char_set, c)) {
break;
}
num_chars++;
}
c = rval;
if (!num_chars) {
(*ReadProc)(ReadProcArg, c, __UngetAChar);
break;
}
chars_read += num_chars;
}
if (format.field_width >= 0) {
(*ReadProc)(ReadProcArg, c, __UngetAChar);
}
conversions++;
break;
case 'n':
if (arg_ptr) {
switch (format.argument_options) {
case normal_argument:
*(int*)arg_ptr = chars_read;
break;
case short_argument:
*(short*)arg_ptr = chars_read;
break;
case long_argument:
*(long*)arg_ptr = chars_read;
break;
case char_argument:
*(char*)arg_ptr = chars_read;
break;
case long_long_argument:
*(long long*)arg_ptr = chars_read;
break;
}
}
continue;
case 0xFF:
default:
goto exit;
}
}
exit:
if ((*ReadProc)(ReadProcArg, 0, __TestForError) && conversions == 0) {
return -1;
}
return items_assigned;
}
int __StringRead(void* pPtr, int ch, int act) {
char ret;
__InStrCtrl* Iscp = (__InStrCtrl*)pPtr;
switch (act) {
case __GetAChar:
ret = *(Iscp->NextChar);
if (ret == '\0') {
Iscp->NullCharDetected = 1;
return -1;
} else {
Iscp->NextChar++;
return (unsigned char)ret;
}
case __UngetAChar:
if (Iscp->NullCharDetected == 0) {
Iscp->NextChar--;
} else {
Iscp->NullCharDetected = 0;
}
return ch;
case __TestForError:
return Iscp->NullCharDetected;
}
return 0;
}
inline int vsscanf(const char* s, const char* format, va_list arg) {
__InStrCtrl isc;
isc.NextChar = (char*)s;
if ((s == 0) || (*isc.NextChar == '\0')) {
return -1;
}
isc.NullCharDetected = 0;
return __sformatter(&__StringRead, (void*)&isc, format, arg, 0);
}
int sscanf(const char* s, const char* pFormat, ...) {
va_list args;
va_start(args, pFormat);
return vsscanf(s, pFormat, args);
}

View File

@@ -0,0 +1,659 @@
#include <internal/format_runtime.h>
#define DBL_MAX_10_EXP 308
#define DBL_MIN_10_EXP (-307)
#define LDBL_MIN DBL_MIN
#define LDBL_MAX DBL_MAX
#define TARGET_FLOAT_BITS 64
#define TARGET_FLOAT_BYTES (TARGET_FLOAT_BITS / 8)
#define TARGET_FLOAT_MAX_EXP LDBL_MAX_EXP
#define TARGET_FLOAT_MANT_DIG LDBL_MANT_DIG
#define TARGET_FLOAT_IMPLICIT_J_BIT 1
#define TARGET_FLOAT_MANT_BITS (TARGET_FLOAT_MANT_DIG - TARGET_FLOAT_IMPLICIT_J_BIT)
#define TARGET_FLOAT_EXP_BITS (TARGET_FLOAT_BITS - TARGET_FLOAT_MANT_BITS - 1)
enum scan_states {
start = 0x0001,
sig_start = 0x0002,
leading_sig_zeroes = 0x0004,
int_digit_loop = 0x0008,
frac_start = 0x0010,
frac_digit_loop = 0x0020,
sig_end = 0x0040,
exp_start = 0x0080,
leading_exp_digit = 0x0100,
leading_exp_zeroes = 0x0200,
exp_digit_loop = 0x0400,
finished = 0x0800,
failure = 0x1000,
nan_state = 0x2000,
infin_state = 0x4000,
hex_state = 0x8000
};
enum hex_scan_states {
not_hex = 0x0000,
hex_start = 0x0001,
hex_leading_sig_zeroes = 0x0002,
hex_int_digit_loop = 0x0004,
hex_frac_digit_loop = 0x0008,
hex_sig_end = 0x0010,
hex_exp_start = 0x0020,
hex_leading_exp_digit = 0x0040,
hex_leading_exp_zeroes = 0x0080,
hex_exp_digit_loop = 0x0100
};
#define final_state(scan_state) (scan_state & (finished | failure))
#define success(scan_state) \
(scan_state & \
(leading_sig_zeroes | int_digit_loop | frac_digit_loop | leading_exp_zeroes | exp_digit_loop | finished))
#define hex_success(count, scan_state) \
(count - 1 > 2 && scan_state & (hex_leading_sig_zeroes | hex_int_digit_loop | hex_frac_digit_loop | \
hex_leading_exp_zeroes | hex_exp_digit_loop))
#define fetch() (count++, (*ReadProc)(ReadProcArg, 0, __GetAChar))
#define unfetch(c) (*ReadProc)(ReadProcArg, c, __UngetAChar)
long double __strtold(int max_width, int (*ReadProc)(void*, int, int), void* ReadProcArg, int* chars_scanned,
int* overflow) {
int scan_state = start;
int hex_scan_state = not_hex;
int count = 0;
int spaces = 0;
int c;
decimal d = {0, 0, {0, ""}};
int sig_negative = 0;
int exp_negative = 0;
long exp_value = 0;
int exp_adjust = 0;
long double result = 0.0;
int sign_detected = 0;
int radix_marker = *(unsigned char*)(__lconv).decimal_point;
unsigned char* chptr;
unsigned char mantissa[TARGET_FLOAT_BYTES];
unsigned mantissa_digits;
unsigned long exponent = 0;
int ui;
unsigned char uch, uch1;
int NibbleIndex;
int expsign = 0;
int exp_digits = 0;
unsigned intdigits = 0;
*overflow = 0;
c = fetch();
while (count <= max_width && c != -1 && !final_state(scan_state)) {
switch (scan_state) {
case start:
if (isspace(c)) {
c = fetch();
count--;
spaces++;
break;
}
switch (toupper(c)) {
case '-':
sig_negative = 1;
case '+':
c = fetch();
sign_detected = 1;
break;
case 'I':
c = fetch();
scan_state = infin_state;
break;
case 'N':
c = fetch();
scan_state = nan_state;
break;
default:
scan_state = sig_start;
break;
}
break;
case infin_state: {
int i = 1;
char model[] = "INFINITY";
while ((i < 8) && (toupper(c) == model[i])) {
i++;
c = fetch();
}
if ((i == 3) || (i == 8)) {
if (sig_negative) {
result = (float)-(double)INFINITY;
} else {
result = INFINITY;
}
*chars_scanned = spaces + i + sign_detected;
return result;
} else {
scan_state = failure;
}
break;
}
case nan_state: {
int i = 1, j = 0;
char model[] = "NAN(";
char nan_arg[32] = "";
while ((i < 4) && (toupper(c) == model[i])) {
i++;
c = fetch();
}
if ((i == 3) || (i == 4)) {
if (i == 4) {
while ((j < 32) && (isdigit(c) || isalpha(c) || (c == radix_marker))) {
nan_arg[j++] = (char)c;
c = fetch();
}
if (c != ')') {
scan_state = failure;
break;
} else {
j++;
}
}
nan_arg[j] = '\0';
if (sig_negative) {
result = -nan(nan_arg);
} else {
result = nan(nan_arg);
}
*chars_scanned = spaces + i + j + sign_detected;
return result;
} else {
scan_state = failure;
}
break;
}
case sig_start:
if (c == radix_marker) {
scan_state = frac_start;
c = fetch();
break;
}
if (!isdigit(c)) {
scan_state = failure;
break;
}
if (c == '0') {
c = fetch();
if (toupper(c) == 'X') {
scan_state = hex_state;
hex_scan_state = hex_start;
} else {
scan_state = leading_sig_zeroes;
}
break;
}
scan_state = int_digit_loop;
break;
case leading_sig_zeroes:
if (c == '0') {
c = fetch();
break;
}
scan_state = int_digit_loop;
break;
case int_digit_loop:
if (!isdigit(c)) {
if (c == radix_marker) {
scan_state = frac_digit_loop;
c = fetch();
} else {
scan_state = sig_end;
}
break;
}
if (d.sig.length < 20) {
d.sig.text[d.sig.length++] = (unsigned char)c;
} else {
exp_adjust++;
}
c = fetch();
break;
case frac_start:
if (!isdigit(c)) {
scan_state = failure;
break;
}
scan_state = frac_digit_loop;
break;
case frac_digit_loop:
if (!isdigit(c)) {
scan_state = sig_end;
break;
}
if (d.sig.length < 20) {
if (c != '0' || d.sig.length) {
d.sig.text[d.sig.length++] = (unsigned char)c;
}
exp_adjust--;
}
c = fetch();
break;
case sig_end:
if (toupper(c) == 'E') {
scan_state = exp_start;
c = fetch();
break;
}
scan_state = finished;
break;
case exp_start:
if (c == '+') {
c = fetch();
} else if (c == '-') {
c = fetch();
exp_negative = 1;
}
scan_state = leading_exp_digit;
break;
case leading_exp_digit:
if (!isdigit(c)) {
scan_state = failure;
break;
}
if (c == '0') {
scan_state = leading_exp_zeroes;
c = fetch();
break;
}
scan_state = exp_digit_loop;
break;
case leading_exp_zeroes:
if (c == '0') {
c = fetch();
break;
}
scan_state = exp_digit_loop;
break;
case exp_digit_loop:
if (!isdigit(c)) {
scan_state = finished;
break;
}
exp_value = exp_value * 10 + (c - '0');
if (exp_value > 0x7FFF) {
*overflow = 1;
}
c = fetch();
break;
case hex_state: {
switch (hex_scan_state) {
case hex_start:
memset(mantissa, 0, sizeof(mantissa));
chptr = mantissa;
mantissa_digits = (53 + 3) / 4;
intdigits = 0;
NibbleIndex = 0;
hex_scan_state = hex_leading_sig_zeroes;
c = fetch();
break;
case hex_leading_sig_zeroes:
if (c == '0') {
c = fetch();
break;
}
hex_scan_state = hex_int_digit_loop;
break;
case hex_int_digit_loop:
if (!isxdigit(c)) {
if (c == radix_marker) {
hex_scan_state = hex_frac_digit_loop;
c = fetch();
}
else {
hex_scan_state = hex_sig_end;
}
break;
}
if (intdigits < mantissa_digits) {
intdigits++;
uch = *(chptr + NibbleIndex / 2);
ui = toupper(c);
if (ui >= 'A') {
ui = ui - 'A' + 10;
} else {
ui -= '0';
}
uch1 = (unsigned char)ui;
if ((NibbleIndex % 2) != 0) {
uch |= uch1;
} else {
uch |= (unsigned char)(uch1 << 4);
}
*(chptr + NibbleIndex++ / 2) = uch;
c = fetch();
}
else {
c = fetch();
}
break;
case hex_frac_digit_loop:
if (!isxdigit(c)) {
hex_scan_state = hex_sig_end;
break;
}
if (intdigits < mantissa_digits) {
uch = *(chptr + NibbleIndex / 2);
ui = toupper(c);
if (ui >= 'A') {
ui = ui - 'A' + 10;
} else {
ui -= '0';
}
uch1 = (unsigned char)ui;
if ((NibbleIndex % 2) != 0) {
uch |= uch1;
} else {
uch |= (unsigned char)(uch1 << 4);
}
*(chptr + NibbleIndex++ / 2) = uch;
c = fetch();
} else {
c = fetch();
}
break;
case hex_sig_end:
if (toupper(c) == 'P') {
hex_scan_state = hex_exp_start;
exp_digits++;
c = fetch();
} else {
scan_state = finished;
}
break;
case hex_exp_start:
exp_digits++;
if (c == '-') {
expsign = 1;
} else if (c != '+') {
c = unfetch(c);
count--;
exp_digits--;
}
hex_scan_state = hex_leading_exp_digit;
c = fetch();
break;
case hex_leading_exp_digit:
if (!isdigit(c)) {
scan_state = failure;
break;
}
if (c == '0') {
exp_digits++;
hex_scan_state = hex_leading_exp_zeroes;
c = fetch();
break;
}
hex_scan_state = hex_exp_digit_loop;
break;
case hex_leading_exp_zeroes:
if (c == '0') {
c = fetch();
break;
}
hex_scan_state = hex_exp_digit_loop;
break;
case hex_exp_digit_loop:
if (!isdigit(c)) {
scan_state = finished;
break;
}
exponent = exponent * 10 + (c - '0');
if (exp_value > SHRT_MAX) {
*overflow = 1;
}
exp_digits++;
c = fetch();
break;
}
} break;
}
}
if (scan_state != 32768 ? !success(scan_state) : !hex_success(count, hex_scan_state)) {
count = 0;
*chars_scanned = 0;
} else {
count--;
*chars_scanned = count + spaces;
}
unfetch(c);
if (hex_scan_state == not_hex) {
if (exp_negative) {
exp_value = -exp_value;
}
{
int n = d.sig.length;
unsigned char* p = &d.sig.text[n];
while (n-- && *--p == '0') {
exp_adjust++;
}
d.sig.length = (unsigned char)(n + 1);
if (d.sig.length == 0) {
d.sig.text[d.sig.length++] = '0';
}
}
exp_value += exp_adjust;
if (exp_value < -0x8000 || exp_value > 0x7FFF) {
*overflow = 1;
}
if (*overflow) {
if (exp_negative) {
return 0.0;
} else {
return sig_negative ? -HUGE_VAL : HUGE_VAL;
}
}
d.exp = (short)exp_value;
result = __dec2num(&d);
if (result != 0.0 && result < LDBL_MIN) {
*overflow = 1;
} else if (result > LDBL_MAX) {
*overflow = 1;
result = HUGE_VAL;
}
if (sig_negative && success(scan_state)) {
result = -result;
}
return result;
} else {
unsigned mantissa_bit, dbl_bit;
unsigned one_bit;
long double dbl_bits_storage;
unsigned char* dbl_bits = (unsigned char*)&dbl_bits_storage;
if (expsign) {
exponent = -exponent;
}
exponent += intdigits * 4;
one_bit = 0;
while (one_bit < 4 && !(mantissa[0] & (0x80 >> one_bit))) {
one_bit++;
exponent--;
}
if (TARGET_FLOAT_IMPLICIT_J_BIT) {
one_bit++;
}
if (one_bit) {
unsigned char carry = 0;
for (chptr = mantissa + sizeof(mantissa) - 1; chptr >= mantissa; chptr--) {
unsigned char a = *chptr;
*chptr = (unsigned char)((a << one_bit) | carry);
carry = (unsigned char)(a >> (8 - one_bit));
}
}
memset(dbl_bits, 0, sizeof(dbl_bits_storage));
dbl_bit = (TARGET_FLOAT_BITS - TARGET_FLOAT_MANT_BITS);
for (mantissa_bit = 0; mantissa_bit < TARGET_FLOAT_MANT_BITS; mantissa_bit += 8) {
unsigned char ui = mantissa[mantissa_bit >> 3];
int halfbits;
if (mantissa_bit + 8 > TARGET_FLOAT_MANT_BITS) {
ui &= 0xff << (TARGET_FLOAT_MANT_BITS - mantissa_bit);
}
halfbits = (dbl_bit & 7);
dbl_bits[dbl_bit >> 3] |= (unsigned char)(ui >> halfbits);
dbl_bit += 8;
dbl_bits[dbl_bit >> 3] |= (unsigned char)(ui << (8 - halfbits));
}
exponent += TARGET_FLOAT_MAX_EXP - 2;
if ((exponent & ~(TARGET_FLOAT_MAX_EXP * 2 - 1))) {
*overflow = 1;
return 0.0;
}
exponent <<= 32 - TARGET_FLOAT_EXP_BITS;
dbl_bits[0] |= exponent >> 25;
if (TARGET_FLOAT_EXP_BITS > 7) {
dbl_bits[1] |= exponent >> 17;
}
if (TARGET_FLOAT_EXP_BITS > 15) {
dbl_bits[2] |= exponent >> 9;
}
if (TARGET_FLOAT_EXP_BITS > 23) {
dbl_bits[3] |= exponent >> 1;
}
if (sig_negative) {
dbl_bits[0] |= 0x80;
}
result = *(long double*)dbl_bits;
return result;
}
}
double strtod(const char* str, char** end) {
__InStrCtrl isc;
double value, abs_value;
int count, overflow;
isc.NextChar = (char*)str;
isc.NullCharDetected = 0;
value = __strtold(INT_MAX, &__StringRead, (void*)&isc, &count, &overflow);
if (end) {
*end = (char*)str + count;
}
abs_value = fabs(value);
if (overflow || (value != 0.0 && (abs_value < DBL_MIN || abs_value > DBL_MAX))) {
errno = ERANGE;
}
return value;
}

View File

@@ -0,0 +1,721 @@
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stddef.h>
#include <internal/locale.h>
#include <string.h>
typedef struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
} tm;
extern int __msl_mod(int, int);
extern div_t __msl_div(long, long);
extern int __msl_add(int*, int);
extern int __msl_ladd(long*, long);
extern int __msl_lmul(long*, long);
static int __leap_year(int year) {
return __msl_mod(year, 4) == 0 && (__msl_mod(year, 100) != 0 || __msl_mod(year, 400) == 100);
}
static int leap_days(int year, int month) {
int n;
div_t q;
q = div(year, 4);
n = q.quot;
q = div(year, 100);
n -= q.quot;
if (year < 100) {
q = __msl_div(year + 899, 1000);
n += q.quot;
} else {
q = __msl_div(year - 100, 1000);
n += q.quot + 1;
}
if (__leap_year(year)) {
if (year < 0) {
if (month > 1) {
n++;
}
} else if (month <= 1) {
n--;
}
}
return n;
}
#define seconds_per_minute (60L)
#define seconds_per_hour (60L * seconds_per_minute)
#define seconds_per_day (24L * seconds_per_hour)
#define seconds_1900_to_1970 (((365 * 70UL) + 17) * 24 * 60 * 60)
const short __msl_month_to_days[2][13] = {
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}
};
extern int __isdst(void);
extern time_t __get_time(void);
extern int __to_gm_time(time_t*);
void __msl_time2tm(time_t in_time, tm* tm) {
unsigned long years, months, days, seconds;
int is_leap_year;
unsigned long time = in_time + seconds_1900_to_1970;
if (!tm) {
return;
}
tm->tm_isdst = __isdst();
days = time / seconds_per_day;
seconds = time % seconds_per_day;
tm->tm_wday = (days + 1) % 7;
years = 0;
for (;;) {
unsigned long days_this_year = __leap_year(years) ? 366 : 365;
if (days < days_this_year) {
break;
}
days -= days_this_year;
years += 1;
}
tm->tm_year = years;
tm->tm_yday = days;
months = 0;
is_leap_year = __leap_year(years);
for (;;) {
unsigned long days_thru_this_month = __msl_month_to_days[is_leap_year][months + 1];
if (days < days_thru_this_month) {
days -= __msl_month_to_days[is_leap_year][months];
break;
}
++months;
}
tm->tm_mon = months;
tm->tm_mday = days + 1;
tm->tm_hour = seconds / seconds_per_hour;
seconds %= seconds_per_hour;
tm->tm_min = seconds / seconds_per_minute;
tm->tm_sec = seconds % seconds_per_minute;
}
static int adjust(int* x, int y, int* z) {
div_t q;
q = __msl_div(*x, y);
*x = q.rem;
return __msl_add(z, q.quot);
}
static int __tm2time(tm* tm, time_t* time) {
long days;
time_t seconds, day_secs;
if (!tm || !time) {
return 0;
}
--tm->tm_mday;
if (!adjust(&tm->tm_sec, 60, &tm->tm_min)) {
goto no_exit;
}
if (!adjust(&tm->tm_min, 60, &tm->tm_hour)) {
goto no_exit;
}
if (!adjust(&tm->tm_hour, 24, &tm->tm_mday)) {
goto no_exit;
}
if (!adjust(&tm->tm_mon, 12, &tm->tm_year)) {
goto no_exit;
}
days = tm->tm_year;
if (!__msl_lmul(&days, 365)) {
goto no_exit;
}
if (!__msl_ladd(&days, leap_days(tm->tm_year, tm->tm_mon))) {
goto no_exit;
}
if (!__msl_ladd(&days, __msl_month_to_days[0][tm->tm_mon])) {
goto no_exit;
}
if (!__msl_ladd(&days, tm->tm_mday)) {
goto no_exit;
}
if (days < 0 || days > (ULONG_MAX / seconds_per_day)) {
goto no_exit;
}
day_secs = days * seconds_per_day;
seconds = (tm->tm_hour * seconds_per_hour) + (tm->tm_min * seconds_per_minute) + tm->tm_sec;
if (seconds > ULONG_MAX - day_secs) {
goto no_exit;
}
seconds += day_secs;
seconds -= seconds_1900_to_1970;
*time = seconds;
__msl_time2tm(seconds, tm);
return 1;
no_exit:
return 0;
}
extern clock_t __get_clock(void);
clock_t clock(void) {
return __get_clock();
}
time_t mktime(tm* timeptr) {
struct tm tm = *timeptr;
time_t time;
if (!__tm2time(&tm, &time)) {
return (time_t)-1;
}
*timeptr = tm;
return time;
}
static void clear_tm(struct tm* tm) {
tm->tm_sec = 0;
tm->tm_min = 0;
tm->tm_hour = 0;
tm->tm_mday = 1;
tm->tm_mon = 0;
tm->tm_year = 0;
tm->tm_wday = 1;
tm->tm_yday = 0;
tm->tm_isdst = -1;
}
static char* find_name(const char* names, int index) {
static char extracted_name[32];
int i;
const char* start = names;
const char* end;
for (i = 0; i <= index; i++) {
end = strchr(start, '|');
if (i == index) {
if (end == NULL) {
strcpy(extracted_name, start);
} else {
strncpy(extracted_name, start, end - start);
extracted_name[end - start] = '\0';
}
break;
}
start = end + 1;
}
return extracted_name;
}
char* asctime(const struct tm* timeptr) {
static char asctime_result[26];
char* result = asctime_result;
if (!timeptr) {
strcpy(result, "xxx xxx xx xx:xx:xx xxxx\n");
} else {
char day[4];
char month[4];
strncpy(day, find_name(_current_locale.time_cmpt_ptr->Day_Names, timeptr->tm_wday * 2), 3);
day[3] = 0;
strncpy(month, find_name(_current_locale.time_cmpt_ptr->MonthNames, timeptr->tm_mon * 2), 3);
month[3] = 0;
sprintf(result, "%s %s%3d %.2d:%.2d:%.2d %d\n", day, month, timeptr->tm_mday,
timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec, timeptr->tm_year + 1900);
}
return result;
}
struct tm* localtime(const time_t* timer);
char* ctime(const time_t* timer) {
struct tm* calendar = localtime(timer);
char* result = asctime(calendar);
char day[4];
char month[4];
strncpy(day, find_name(_current_locale.time_cmpt_ptr->Day_Names, calendar->tm_wday * 2), 3);
day[3] = 0;
strncpy(month, find_name(_current_locale.time_cmpt_ptr->MonthNames, calendar->tm_mon * 2), 3);
month[3] = 0;
sprintf(result, "%.3s %.3s %2d %.2d:%.2d:%.2d %4d\n", day, month,
calendar->tm_mday, calendar->tm_hour, calendar->tm_min, calendar->tm_sec,
calendar->tm_year + 1900);
return result;
}
static time_t time(time_t* timer) {
time_t result = __get_time();
if (timer) {
*timer = result;
}
return result;
}
static struct tm* gmtime(const time_t* timer) {
static struct tm gmtime_tm;
time_t time;
if (!timer) {
clear_tm(&gmtime_tm);
return &gmtime_tm;
}
time = *timer;
if (!__to_gm_time(&time)) {
return NULL;
}
__msl_time2tm(time, &gmtime_tm);
gmtime_tm.tm_isdst = 0;
return &gmtime_tm;
}
struct tm* localtime(const time_t* timer) {
static struct tm localtime_tm;
if (!timer) {
clear_tm(&localtime_tm);
localtime_tm.tm_isdst = __isdst();
return &localtime_tm;
} else {
__msl_time2tm(*timer, &localtime_tm);
localtime_tm.tm_isdst = __isdst();
return &localtime_tm;
}
}
static int emit(char* str, size_t size, size_t* max_size, const char* format_str, ...) {
va_list args;
va_start(args, format_str);
if (size > *max_size) {
return 0;
}
*max_size -= size;
return vsprintf(str, format_str, args);
}
time_t __MSL_ISO8601NewYear(int year) {
struct tm ts0;
time_t timeval;
short StartMday[7] = {2, 3, 4, 29, 30, 31, 1};
ts0.tm_sec = 0;
ts0.tm_min = 0;
ts0.tm_hour = 0;
ts0.tm_mon = 0;
ts0.tm_isdst = -1;
ts0.tm_mday = 0;
ts0.tm_wday = 7;
ts0.tm_year = year;
while ((ts0.tm_wday != 0) && (ts0.tm_mday <= 7)) {
ts0.tm_mday++;
timeval = mktime(&ts0);
}
ts0.tm_mday = StartMday[ts0.tm_mday - 1];
if (ts0.tm_mday >= 29) {
ts0.tm_mon = 11;
ts0.tm_year--;
}
return mktime(&ts0);
}
static double difftime(time_t time1, time_t time0) {
time_t diff;
if (time1 >= time0) {
return time1 - time0;
}
diff = time0 - time1;
return -(double)diff;
}
extern const double msl_seconds_per_day;
extern const double msl_days_per_week;
extern const double msl_seconds_per_minute;
int __MSL_ISO8601Week(const struct tm* tmptr, int* WYear) {
struct WeekYear {
int Year;
time_t Start;
};
struct WeekYear LastYear, ThisYear, NextYear;
struct WeekYear* WyPtr;
struct tm Localtm = *tmptr;
double Days;
int WeekNo;
time_t GivenTimeVal;
LastYear.Year = tmptr->tm_year - 1;
LastYear.Start = __MSL_ISO8601NewYear(LastYear.Year);
ThisYear.Year = tmptr->tm_year;
ThisYear.Start = __MSL_ISO8601NewYear(ThisYear.Year);
NextYear.Year = tmptr->tm_year + 1;
NextYear.Start = __MSL_ISO8601NewYear(NextYear.Year);
GivenTimeVal = mktime(&Localtm);
if ((LastYear.Start <= GivenTimeVal) && (GivenTimeVal < ThisYear.Start)) {
WyPtr = &LastYear;
} else if ((ThisYear.Start <= GivenTimeVal) && (GivenTimeVal < NextYear.Start)) {
WyPtr = &ThisYear;
} else {
WyPtr = &NextYear;
}
*WYear = WyPtr->Year;
{
double diff;
if (GivenTimeVal >= WyPtr->Start) {
diff = (double)(GivenTimeVal - WyPtr->Start);
} else {
diff = -(double)(WyPtr->Start - GivenTimeVal);
}
Days = diff / msl_seconds_per_day;
}
WeekNo = (int)(Days / msl_days_per_week) + 1;
return WeekNo;
}
static int week_num(const struct tm* tm, int starting_day) {
int days = tm->tm_yday;
days -= __msl_mod(tm->tm_wday - starting_day, 7);
if (days < 0) {
return 0;
}
return (days / 7) + 1;
}
static int emit_string(char* str, size_t size, size_t* max_size, const char* value) {
return emit(str, size, max_size, "%s", value);
}
size_t strftime(char* str, size_t max_size, const char* format_str, const struct tm* timeptr) {
char name[32];
size_t num_chars, chars_written, space_remaining;
struct __locale* locale = &_current_locale;
const char* format_ptr;
const char* curr_format;
int n, ISO8601Year, ISO8601WeekNo;
struct tm tm;
struct tm defaults = {0, 0, 0, 1, 0, 0, 1, 0, -1};
if ((space_remaining = --max_size) <= 0) {
return 0;
}
tm = defaults;
if (timeptr) {
tm = *timeptr;
if (mktime(&tm) == (time_t)-1) {
tm = defaults;
}
}
format_ptr = format_str;
chars_written = 0;
while (*format_ptr) {
if (!(curr_format = strchr(format_ptr, '%'))) {
if ((num_chars = strlen(format_ptr)) != 0) {
if (num_chars <= space_remaining) {
memcpy(str, format_ptr, num_chars);
chars_written += num_chars;
str += num_chars;
space_remaining -= num_chars;
} else {
return 0;
}
}
break;
}
if ((num_chars = curr_format - format_ptr) != 0) {
if (num_chars <= space_remaining) {
memcpy(str, format_ptr, num_chars);
chars_written += num_chars;
str += num_chars;
space_remaining -= num_chars;
} else {
return 0;
}
}
format_ptr = curr_format;
if (format_ptr[1] == 'E' || format_ptr[1] == 'O') {
++format_ptr;
}
switch (*++format_ptr) {
case 'a':
strcpy(name, find_name(locale->time_cmpt_ptr->Day_Names, tm.tm_wday * 2));
num_chars = emit_string(str, strlen(name), &space_remaining, name);
break;
case 'A':
strcpy(name, find_name(locale->time_cmpt_ptr->Day_Names, tm.tm_wday * 2 + 1));
num_chars = emit_string(str, strlen(name), &space_remaining, name);
break;
case 'b':
case 'h': {
num_chars =
emit(str, 3, &space_remaining, "%.3s",
find_name(locale->time_cmpt_ptr->MonthNames, tm.tm_mon * 2));
break;
}
case 'B':
strcpy(name, find_name(locale->time_cmpt_ptr->MonthNames, tm.tm_mon * 2 + 1));
num_chars = emit_string(str, strlen(name), &space_remaining, name);
break;
case 'c':
num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->DateTime_Format, &tm);
space_remaining -= num_chars;
break;
case 'd':
num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_mday);
break;
case 'D':
num_chars = strftime(str, space_remaining + 1, "%m/%d/%y", &tm);
break;
case 'e':
num_chars = emit(str, 2, &space_remaining, "%2d", tm.tm_mday);
break;
case 'F':
num_chars =
emit(str, 10, &space_remaining, "%.4d-%.2d-%.2d", tm.tm_year + 1900, tm.tm_mon + 1,
tm.tm_mday);
break;
case 'g':
ISO8601WeekNo = __MSL_ISO8601Week(timeptr, &ISO8601Year);
num_chars = emit(str, 2, &space_remaining, "%.2d", ISO8601Year % 100);
break;
case 'G':
ISO8601WeekNo = __MSL_ISO8601Week(timeptr, &ISO8601Year);
num_chars = emit(str, 4, &space_remaining, "%.4d", ISO8601Year + 1900);
break;
case 'H':
num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_hour);
break;
case 'I':
num_chars = emit(str, 2, &space_remaining, "%.2d",
(n = tm.tm_hour % 12) ? n : 12);
break;
case 'j':
num_chars = emit(str, 3, &space_remaining, "%.3d", tm.tm_yday + 1);
break;
case 'm':
num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_mon + 1);
break;
case 'M':
num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_min);
break;
case 'n':
num_chars = emit(str, 2, &space_remaining, "\n");
break;
case 'p': {
char* name;
name = find_name(locale->time_cmpt_ptr->am_pm, tm.tm_hour < 12 ? 0 : 1);
num_chars = emit_string(str, strlen(name), &space_remaining, name);
break;
}
case 'r':
num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->Twelve_hr_format, &tm);
space_remaining -= num_chars;
break;
case 'R':
num_chars = strftime(str, space_remaining + 1, "%H:%M", &tm);
space_remaining -= num_chars;
break;
case 'S':
num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_sec);
break;
case 't':
num_chars = emit(str, 2, &space_remaining, "\t");
break;
case 'T':
num_chars = strftime(str, space_remaining + 1, "%H:%M:%S", &tm);
space_remaining -= num_chars;
break;
case 'u':
if (tm.tm_wday == 0) {
num_chars = emit(str, 1, &space_remaining, "7");
} else {
num_chars = emit(str, 1, &space_remaining, "%.1d", tm.tm_wday);
}
break;
case 'U':
num_chars = emit(str, 2, &space_remaining, "%.2d", week_num(&tm, 0));
break;
case 'V':
ISO8601WeekNo = __MSL_ISO8601Week(timeptr, &ISO8601Year);
num_chars = emit(str, 2, &space_remaining, "%.2d", ISO8601WeekNo);
break;
case 'w':
num_chars = emit(str, 1, &space_remaining, "%.1d", tm.tm_wday);
break;
case 'W':
num_chars = emit(str, 2, &space_remaining, "%.2d", week_num(&tm, 1));
break;
case 'x':
num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->Date_Format, &tm);
space_remaining -= num_chars;
break;
case 'X':
num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->Time_Format, &tm);
space_remaining -= num_chars;
break;
case 'y':
case 'C':
num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_year % 100);
break;
case 'Y':
num_chars = emit(str, 4, &space_remaining, "%.4d", tm.tm_year + 1900);
break;
case 'z': {
time_t local, utc, now;
struct tm localtm, *utctmptr;
double diff, diffmins, diffhours;
now = time(NULL);
utctmptr = gmtime(&now);
if (utctmptr == NULL) {
num_chars = emit(str, 4, &space_remaining, "0000");
} else {
localtm = *localtime(&now);
local = mktime(&localtm);
utc = mktime(utctmptr);
diff = difftime(local, utc);
diffhours = (int)diff / 3600;
diffmins = __abs(diff / msl_seconds_per_minute - msl_seconds_per_minute * diffhours);
num_chars = emit(str, 5, &space_remaining, "%+03.0f%02.0f", diffhours, diffmins);
}
break;
}
case 'Z': {
char* TimeZone = locale->time_cmpt_ptr->TimeZone;
if (*TimeZone == '\0') {
num_chars = 0;
*str = '\0';
} else {
num_chars = emit_string(str, strlen(TimeZone), &space_remaining, TimeZone);
}
break;
}
case '%':
num_chars = emit(str, 2, &space_remaining, "%%", *format_ptr);
break;
default:
num_chars = emit(str, 2, &space_remaining, "%%%c", *format_ptr);
break;
}
if (!num_chars) {
return 0;
}
chars_written += num_chars;
str += num_chars;
++format_ptr;
}
*str = 0;
if (max_size < chars_written) {
return 0;
} else {
return chars_written;
}
}
const double msl_seconds_per_day = 86400.0;
const double msl_days_per_week = 7.0;
const double msl_seconds_per_minute = 60.0;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,671 @@
#include <internal/format_runtime.h>
#define LDBL_MAX DBL_MAX
typedef unsigned long long d_int;
static inline int __count_trailing_zerol(unsigned long x) { return 32 - __cntlzw(~x & (x - 1)); }
static int __count_trailing_zero(double n) {
unsigned long* array = (unsigned long*)&n;
unsigned long hi = array[0] | 0x100000;
unsigned long lo = array[1];
int zeros = __count_trailing_zerol(lo);
if (lo == 0) {
return 32 + __count_trailing_zerol(hi);
}
return zeros;
}
static int __must_round(const decimal* d, int digits) {
unsigned char const* i = d->sig.text + digits;
if (*i > 5) {
return 1;
}
if (*i < 5) {
return -1;
}
{
unsigned char const* e = d->sig.text + d->sig.length;
for (i++; i < e; i++) {
if (*i != 0) {
return 1;
}
}
}
if (d->sig.text[digits - 1] & 1) {
return 1;
}
return -1;
}
static void __dorounddecup(decimal* d, int digits) {
unsigned char* b = d->sig.text;
unsigned char* i = b + digits - 1;
while (1) {
if (*i < 9) {
*i += 1;
break;
}
if (i == b) {
*i = 1;
d->exp++;
break;
}
*i-- = 0;
}
}
static void __rounddec(decimal* d, int digits) {
if (digits > 0 && digits < d->sig.length) {
int unkBool = __must_round(d, digits);
d->sig.length = digits;
if (unkBool >= 0) {
__dorounddecup(d, digits);
}
}
}
static void __ull2dec(decimal* result, unsigned long long val) {
result->sign = 0;
result->sig.length = 0;
for (; val != 0; val /= 10) {
result->sig.text[result->sig.length++] = (unsigned char)(val % 10);
}
{
unsigned char* i = result->sig.text;
unsigned char* j = result->sig.text + result->sig.length;
for (; i < --j; ++i) {
unsigned char t = *i;
*i = *j;
*j = t;
}
}
result->exp = result->sig.length - 1;
}
static void __timesdec(decimal* result, const decimal* x, const decimal* y) {
unsigned long accumulator = 0;
unsigned char mantissa[SIGDIGLEN * 2];
int i = x->sig.length + y->sig.length - 1;
unsigned char* pDigit;
unsigned char* ip = mantissa + i + 1;
unsigned char* ep = ip;
result->sign = 0;
for (; i > 0; i--) {
int k = y->sig.length - 1;
int j = i - k - 1;
int l;
int t;
const unsigned char* jp;
const unsigned char* kp;
if (j < 0) {
j = 0;
k = i - 1;
}
jp = x->sig.text + j;
kp = y->sig.text + k;
l = k + 1;
t = x->sig.length - j;
if (l > t)
l = t;
for (; l > 0; l--, jp++, kp--) {
accumulator += *jp * *kp;
}
*--ip = (unsigned char)(accumulator % 10);
accumulator /= 10;
}
result->exp = (short)(x->exp + y->exp);
if (accumulator) {
*--ip = (unsigned char)(accumulator);
result->exp++;
}
for (i = 0; i < SIGDIGLEN && ip < ep; i++, ip++) {
result->sig.text[i] = *ip;
}
result->sig.length = (unsigned char)(i);
if (ip < ep && *ip >= 5) {
if (*ip == 5) {
unsigned char* jp = ip + 1;
for (; jp < ep; jp++) {
if (*jp != 0)
goto round;
}
if ((ip[-1] & 1) == 0)
return;
}
round:
__dorounddecup(result, result->sig.length);
}
}
static void __str2dec(decimal* d, const char* s, short exp) {
int i;
d->exp = exp;
d->sign = 0;
for (i = 0; i < SIGDIGLEN && *s;) {
d->sig.text[i++] = *s++ - '0';
}
d->sig.length = i;
if (*s != 0) {
if (*s < 5)
return;
if (*s > 5)
goto round;
{
const char* p = s + 1;
for (; *p != 0; p++) {
if (*p != '0')
goto round;
}
if ((d->sig.text[i - 1] & 1) == 0)
return;
}
round:
__dorounddecup(d, d->sig.length);
}
}
static void __two_exp(decimal* result, long exp) {
switch (exp) {
case -64:
__str2dec(result, "542101086242752217003726400434970855712890625", -20);
return;
case -53:
__str2dec(result, "11102230246251565404236316680908203125", -16);
return;
case -32:
__str2dec(result, "23283064365386962890625", -10);
return;
case -16:
__str2dec(result, "152587890625", -5);
return;
case -8:
__str2dec(result, "390625", -3);
return;
case -7:
__str2dec(result, "78125", -3);
return;
case -6:
__str2dec(result, "15625", -2);
return;
case -5:
__str2dec(result, "3125", -2);
return;
case -4:
__str2dec(result, "625", -2);
return;
case -3:
__str2dec(result, "125", -1);
return;
case -2:
__str2dec(result, "25", -1);
return;
case -1:
__str2dec(result, "5", -1);
return;
case 0:
__str2dec(result, "1", 0);
return;
case 1:
__str2dec(result, "2", 0);
return;
case 2:
__str2dec(result, "4", 0);
return;
case 3:
__str2dec(result, "8", 0);
return;
case 4:
__str2dec(result, "16", 1);
return;
case 5:
__str2dec(result, "32", 1);
return;
case 6:
__str2dec(result, "64", 1);
return;
case 7:
__str2dec(result, "128", 2);
return;
case 8:
__str2dec(result, "256", 2);
return;
}
{
decimal x2, temp;
__two_exp(&x2, exp / 2);
__timesdec(result, &x2, &x2);
if (exp & 1) {
temp = *result;
if (exp > 0) {
__str2dec(&x2, "2", 0);
} else {
__str2dec(&x2, "5", -1);
}
__timesdec(result, &temp, &x2);
}
}
}
static int __equals_dec(const decimal* x, const decimal* y) {
if (x->sig.text[0] == 0) {
return y->sig.text[0] == 0;
}
if (y->sig.text[0] == 0) {
return x->sig.text[0] == 0;
}
if (x->exp == y->exp) {
int i;
int l = x->sig.length;
if (l > y->sig.length) {
l = y->sig.length;
}
for (i = 0; i < l; i++) {
if (x->sig.text[i] != y->sig.text[i]) {
return 0;
}
}
if (l == x->sig.length) {
x = y;
}
for (; i < x->sig.length; i++) {
if (x->sig.text[i] != 0) {
return 0;
}
}
return 1;
}
return 0;
}
static int __less_dec(const decimal* x, const decimal* y) {
if (x->sig.text[0] == 0) {
unsigned char leading_digit = y->sig.text[0];
return ((unsigned long)(-leading_digit | leading_digit) >> 31);
}
if (y->sig.text[0] == 0) {
return 0;
}
if (x->exp == y->exp) {
int i;
int l = x->sig.length;
if (l > y->sig.length) {
l = y->sig.length;
}
for (i = 0; i < l; i++) {
if (x->sig.text[i] < y->sig.text[i]) {
return 1;
} else if (y->sig.text[i] < x->sig.text[i]) {
return 0;
}
}
if (l == x->sig.length) {
for (; i < y->sig.length; i++) {
if (y->sig.text[i] != 0) {
return 1;
}
}
}
return 0;
}
return x->exp < y->exp;
}
static void __minus_dec(decimal* z, const decimal* x, const decimal* y) {
int zlen, dexp;
unsigned char *ib, *i, *ie;
unsigned char const *jb, *j, *jn;
*z = *x;
if (y->sig.text[0] == 0)
return;
zlen = z->sig.length;
if (zlen < y->sig.length)
zlen = y->sig.length;
dexp = z->exp - y->exp;
zlen += dexp;
if (zlen > SIGDIGLEN)
zlen = SIGDIGLEN;
while (z->sig.length < zlen) {
z->sig.text[z->sig.length++] = 0;
}
ib = z->sig.text;
i = ib + zlen;
if (y->sig.length + dexp < zlen) {
i = ib + (y->sig.length + dexp);
}
jb = y->sig.text;
j = jb + (i - ib - dexp);
jn = j;
while (i > ib && j > jb) {
i--;
j--;
if (*i < *j) {
unsigned char* k = i - 1;
while (*k == 0)
k--;
while (k != i) {
--*k;
*++k += 10;
}
}
*i -= *j;
}
if (jn - jb < y->sig.length) {
int round_down = 0;
if (*jn < 5)
round_down = 1;
else if (*jn == 5) {
unsigned char const* ibPtr = y->sig.text + y->sig.length;
for (j = jn + 1; j < ibPtr; j++) {
if (*j != 0)
goto done;
}
i = ib + (jn - jb) + dexp - 1;
if (*i & 1)
round_down = 1;
}
if (round_down) {
if (*i < 1) {
unsigned char* k = i - 1;
while (*k == 0)
k--;
while (k != i) {
--*k;
*++k += 10;
}
}
*i -= 1;
}
}
done:
for (i = ib; *i == 0; ++i) {}
if (i > ib) {
unsigned char dl = (unsigned char)(i - ib);
z->exp -= dl;
ie = ib + z->sig.length;
for (; i < ie; ++i, ++ib)
*ib = *i;
z->sig.length -= dl;
}
ib = z->sig.text;
for (i = ib + z->sig.length; i > ib;) {
i--;
if (*i != 0)
break;
}
z->sig.length = (unsigned char)(i - ib + 1);
}
static void __num2dec_internal(decimal* d, double x) {
signed char sign = (signed char)(__signbitd(x) != 0);
if (x == 0) {
d->sign = sign;
d->exp = 0;
d->sig.length = 1;
d->sig.text[0] = 0;
return;
}
if (!isfinite(x)) {
d->sign = sign;
d->exp = 0;
d->sig.length = 1;
d->sig.text[0] = fpclassify(x) == 1 ? 'N' : 'I';
return;
}
if (sign != 0) {
x = -x;
}
{
int exp;
double frac = frexp(x, &exp);
int num_bits_extract = LDBL_MANT_DIG - __count_trailing_zero(frac);
decimal int_d, pow2_d;
__two_exp(&pow2_d, exp - num_bits_extract);
__ull2dec(&int_d, ldexp(frac, num_bits_extract));
__timesdec(d, &int_d, &pow2_d);
d->sign = sign;
}
}
void __num2dec(const decform* form, double x, decimal* d) {
short digits = form->digits;
int i;
__num2dec_internal(d, x);
if (d->sig.text[0] > 9) {
return;
}
if (digits > SIGDIGLEN) {
digits = SIGDIGLEN;
}
__rounddec(d, digits);
while (d->sig.length < digits) {
d->sig.text[d->sig.length++] = 0;
}
d->exp -= d->sig.length - 1;
for (i = 0; i < d->sig.length; i++) {
d->sig.text[i] += '0';
}
}
double __dec2num(const decimal* d) {
if (d->sig.length <= 0) {
return copysign(0.0, d->sign == 0 ? 1.0 : -1.0);
}
switch (d->sig.text[0]) {
case '0':
return copysign(0.0, d->sign == 0 ? 1.0 : -1.0);
case 'I':
return copysign((double)INFINITY, d->sign == 0 ? 1.0 : -1.0);
case 'N': {
double result;
d_int* ll = (d_int*)&result;
*ll = 0x7FF0000000000000;
if (d->sign)
*ll |= 0x8000000000000000;
*ll |= 0x8000000000000;
return result;
}
}
{
static double pow_10[8] = {1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8};
decimal dec = *d;
unsigned char* i = dec.sig.text;
unsigned char* e = i + dec.sig.length;
double first_guess;
int exponent;
for (; i < e; ++i)
*i -= '0';
dec.exp += dec.sig.length - 1;
exponent = dec.exp;
{
decimal max;
__str2dec(&max, "179769313486231580793728714053034151", 308);
if (__less_dec(&max, &dec)) {
return copysign((double)INFINITY, d->sign == 0 ? 1.0 : -1.0);
}
}
i = dec.sig.text;
first_guess = *i++;
while (i < e) {
unsigned long ival = 0;
int j;
double temp1, temp2;
int ndig = (int)(e - i) % 8;
if (ndig == 0)
ndig = 8;
for (j = 0; j < ndig; ++j, ++i) {
ival = ival * 10 + *i;
}
temp1 = first_guess * pow_10[ndig - 1];
temp2 = temp1 + ival;
if (ival != 0 && temp1 == temp2)
break;
first_guess = temp2;
exponent -= ndig;
}
if (exponent < 0) {
first_guess /= pow(5.0, -exponent);
} else {
first_guess *= pow(5.0, exponent);
}
first_guess = ldexp(first_guess, exponent);
if (fpclassify(first_guess) == 2) {
first_guess = LDBL_MAX;
}
{
decimal feedback1, feedback2, difflow, diffhigh;
double next_guess;
d_int* ull = (d_int*)&next_guess;
int guessed_low = 0;
__num2dec_internal(&feedback1, first_guess);
if (__equals_dec(&feedback1, &dec)) {
goto done;
}
if (__less_dec(&feedback1, &dec)) {
guessed_low = 1;
}
next_guess = first_guess;
while (1) {
if (guessed_low) {
++*ull;
if (fpclassify(next_guess) == 2) {
goto done;
}
} else {
--*ull;
}
__num2dec_internal(&feedback2, next_guess);
if (guessed_low && !__less_dec(&feedback2, &dec)) {
break;
} else if (!guessed_low && !__less_dec(&dec, &feedback2)) {
difflow = feedback1;
feedback1 = feedback2;
feedback2 = difflow;
{
double temp = first_guess;
first_guess = next_guess;
next_guess = temp;
}
break;
}
feedback1 = feedback2;
first_guess = next_guess;
}
__minus_dec(&difflow, &dec, &feedback1);
__minus_dec(&diffhigh, &feedback2, &dec);
if (__equals_dec(&difflow, &diffhigh)) {
if (*(unsigned long long*)&first_guess & 1) {
first_guess = next_guess;
}
} else if (!__less_dec(&difflow, &diffhigh)) {
first_guess = next_guess;
}
}
done:
if (dec.sign) {
first_guess = -first_guess;
}
return first_guess;
}
}

View File

@@ -130,11 +130,18 @@ typedef struct EZTXGetParam {
wchar_t* candidates; // 0x18
u8 maxCandidates; // 0x1C
wchar_t firstCandidate; // 0x1E
#ifndef TIZISTRING_IMPLEMENTATION
u8 wordCandidates; // 0x1F
#endif
u8 count; // 0x20
u8 letters; // 0x21
#ifdef TIZISTRING_IMPLEMENTATION
u8 completion;
u8* scratch;
#else
u8* scratch; // 0x22
#endif
} EZTXGetParam;
u16 EZTXGetGlobalDataSize();

View File

@@ -0,0 +1,430 @@
#include <zi8clib/zitypes.h>
#include <zi8clib/zierror.h>
#include <zi8clib/zconvert.h>
ziU32 Zi8GetTableSize(ziU8 language, ziU8 table, ziPtr work);
ziU32 Zi8GetTableAddress(ziU8 language, ziU8 table, ziPtr work);
ziU16 Zi8GetTableCount(ziU8 language, ziU8 table, ziPtr work);
ziU8* ZiDAWGGetGraph(zi8DawgCtx* context);
ziU8* ZiDAWGGetGraphInfo(zi8DawgCtx* context, ziU8* table, ziS16* keys);
ziU32 ZiDAWGgetCHARattribute(zi8DawgCtx* context, ziU8* graph, ziPtr work);
ziU8 ZiDAWGgetEOWattribute(ziU8* graph);
ziU8* ZiDAWGGetChild(ziU8* graph);
ziU8* ZiDAWGGetSibling(ziU8* graph);
ziU32 Zi8MatchROMdata0(ziWChar* elements, ziU32 count, ziU8 language,
ziWChar* output, ziU16 capacity, ziU8 mode, ziU8 status,
ziU8 graphTable, ziU8 keyTable, ziU8 acceptPrefix,
ziU8* prefixLength, zi8DawgCtx* context, ziU8* search,
ziPtr __zi8_work_data) {
ziBool searching;
ziS32 tableSize;
ziU8* graph;
ziS16 key;
ziU8 endOfWord;
zi8DawgRec* current;
ziU16 index;
ziU16 depth;
zi8DawgRec* records = context->recs;
ziU8 result = 0;
ziU32 keyCount;
ziU8* table;
ziS16 keys[3];
if (language != context->lang || graphTable != context->key) {
records[0].key = 0;
}
if ((ziU8)count != 1 || mode == 0 || graphTable != 0xe) {
if (status != 0) {
if (records[context->cnt - 1].node == (ziU8*)context->unk_0x338) goto finish_graph;
for (index = 0; (ziU16)index < (ziU8)count; index++) {
if (records[(ziU16)index].key != elements[(ziU16)index] &&
(records[(ziU16)index].attr & 0xffff) != elements[(ziU16)index]) goto finish_graph;
}
if (mode == 1) acceptPrefix = 0;
} else {
if (ZI_WORK->unk_0x141E == 0 || graphTable != 0xc ||
(tableSize = Zi8GetTableSize(language, ZI_WORK->unk_0x141E, ZI_WORK)) == 0) {
tableSize = Zi8GetTableSize(language, graphTable, ZI_WORK);
if (tableSize == 0) {
Zi8LogError(0x961, ZI_WORK);
goto finish_graph;
}
table = (ziU8*)Zi8GetTableAddress(language, graphTable, ZI_WORK);
} else {
table = (ziU8*)Zi8GetTableAddress(language, ZI_WORK->unk_0x141E, ZI_WORK);
keyTable = ZI_WORK->unk_0x141E + 1;
}
context->table = table;
context->cap = (((ziU16)context->table[2] << 8) + (ziU16)context->table[3]) / 3;
context->p08 = context->table + 4;
context->p0C = context->table + context->cap * 2 + 4;
context->lang = language;
context->key = graphTable;
index = 0;
while ((ziU16)index < (ziU8)count && records[(ziU16)index].key == elements[(ziU16)index]) {
index++;
}
if ((ziU16)index < 2) {
key = Zi8GetTableSize(language, keyTable, ZI_WORK);
if (key == 0 || ZI_WORK->userKeys[language] != 0) {
graph = ZiDAWGGetGraph(context);
records[0].node = graph;
context->unk_0x338 = 0;
context->p14 = 0;
} else {
index = 0;
while (1) {
if ((ziU8)count < 2) keyCount = (ziU8)count;
else keyCount = 2;
if (keyCount <= (ziU16)index) break;
key = Zi8ConvertWC2Key(elements[(ziU16)index], language, ZI_WORK);
keys[(ziU16)index] = key;
if (keys[(ziU16)index] == 0) keys[(ziU16)index] = elements[(ziU16)index];
index++;
}
keys[(ziU16)index] = 0;
table = (ziU8*)Zi8GetTableAddress(language, keyTable, ZI_WORK);
context->p14 = table + 2;
records[0].node = ZiDAWGGetGraphInfo(context, table + context->cap * 2 + 2, keys);
}
records[0].key = 0;
if (records[0].node == 0) goto finish_graph;
} else {
records[0].node = records[(ziU16)index - 1].back;
}
context->cnt = 1;
search[1] = count;
search[0] = 0;
if (mode == 1) {
search[0] = 1;
acceptPrefix = 0;
} else if (mode == 0 && acceptPrefix == 0) {
search[1]++;
}
}
searching = 1;
depth = context->cnt;
while ((current = &records[depth - 1], searching) && context->cnt != 0 &&
current->node != (ziU8*)context->unk_0x338 && context->cnt <= capacity) {
current->attr = ZiDAWGgetCHARattribute(context, current->node, ZI_WORK);
if ((ziU8)count < context->cnt) {
check_word:
if (context->cnt < search[1]) goto descend;
if (search[0] == 0 || context->cnt <= search[1]) {
if (acceptPrefix != 0 || (endOfWord = ZiDAWGgetEOWattribute(current->node)) != 0) {
for (depth = 0; depth < context->cnt; depth++) {
output[depth] = records[depth].attr;
}
result = context->cnt;
searching = 0;
if (acceptPrefix != 0) goto next_sibling;
}
if (search[0] == 0 || context->cnt < search[1]) goto descend;
}
next_sibling:
while (context->cnt != 0) {
graph = ZiDAWGGetSibling(records[context->cnt - 1].node);
records[context->cnt - 1].node = graph;
if (records[context->cnt - 1].node != 0) break;
context->cnt--;
}
} else {
if (context->p14 == 0) {
key = Zi8ConvertWC2Key(current->attr & 0xffff, language, ZI_WORK);
} else {
key = (ziU16)context->p14[(current->attr >> 24) * 2] * 0x100 +
(ziU16)context->p14[(current->attr >> 24) * 2 + 1];
}
if (key != elements[context->cnt - 1] &&
(current->attr & 0xffff) != elements[context->cnt - 1]) goto next_sibling;
if (current->key != elements[context->cnt - 1]) {
current->key = elements[context->cnt - 1];
current->back = records[0].node;
depth = context->cnt;
records[depth].key = 0;
}
if (prefixLength != 0 && *prefixLength < context->cnt &&
(endOfWord = ZiDAWGgetEOWattribute(current->node)) != 0) {
*prefixLength = context->cnt;
for (depth = 0; depth < context->cnt; depth++) output[depth] = records[depth].attr;
}
if ((ziU8)count <= context->cnt) goto check_word;
descend:
graph = ZiDAWGGetChild(records[context->cnt - 1].node);
records[context->cnt].node = graph;
if (records[context->cnt].node == 0) goto next_sibling;
context->cnt++;
if (ZI_WORK->unk_0x141F < context->cnt) ZI_WORK->unk_0x141F = context->cnt;
}
depth = context->cnt;
}
}
finish_graph:
return result;
}
ziU8* NextDawgGroup(ziU8* group, ziU8 language, ziPtr __zi8_work_data)
{
if (Zi8GetTableSize(language,0x1c,ZI_WORK) != 0) {
if (group == 0) {
group = (ziU8*)Zi8GetTableAddress(language,0x1c,ZI_WORK);
if (group == 0) {
Zi8LogError(0x962,ZI_WORK);
return 0;
}
if (ZI_WORK->unk_0x141D == 0) {
return group;
}
}
while (group[0] != 0xff || group[1] != 0xff) {
group = group + 1;
}
group = group + 2;
if (group[0] == 0xff) {
Zi8LogError(0x963,ZI_WORK);
return 0;
}
return group;
}
Zi8LogError(0x961,ZI_WORK);
return 0;
}
unsigned int Zi8MatchROMdata1(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 mode, unsigned int status, ziU32 groupIndex, char *group, ziU8 acceptPrefix, ziPtr __zi8_work_data)
{
unsigned int result;
ziU32 tableAddress;
result = 0;
if ((status & 0xff) == 0) {
ZI_WORK->unk_0x1764 = (ziU8*)group;
if (ZI_WORK->unk_0x1764 == 0) {
if (Zi8GetTableSize(language & 0xff,0xb,ZI_WORK) != 0) {
tableAddress = Zi8GetTableAddress(language & 0xff,0xb,ZI_WORK);
ZI_WORK->unk_0x1764 = (ziU8*)tableAddress;
}
}
if (ZI_WORK->unk_0x1764 != 0) {
for (; (*ZI_WORK->unk_0x1764 != 0xff && ((groupIndex & 0xff) != 0));
groupIndex = groupIndex - 1) {
while (*ZI_WORK->unk_0x1764 != 0xff) {
ZI_WORK->unk_0x1764 += 2;
}
ZI_WORK->unk_0x1764++;
}
}
}
if (ZI_WORK->unk_0x1764 == 0) {
result = Zi8MatchROMdata0(elements,count,language & 0xff,output,capacity & 0xffff,
mode & 0xff,status & 0xff,0,1,acceptPrefix,0,&ZI_WORK->dawgCtx,
ZI_WORK->unk_0x1760,ZI_WORK);
}
else {
while (*ZI_WORK->unk_0x1764 != 0xff) {
result = Zi8MatchROMdata0(elements,count,language & 0xff,output,
capacity & 0xffff,mode & 0xff,status & 0xff,
*ZI_WORK->unk_0x1764,
ZI_WORK->unk_0x1764[1],acceptPrefix,0,
&ZI_WORK->dawgCtx,ZI_WORK->unk_0x1760,ZI_WORK);
if ((result & 0xff) != 0) break;
ZI_WORK->unk_0x1764 += 2;
status = 0;
}
}
return result;
}
unsigned int Zi8MatchROMdata2(ziWChar *elements, unsigned int count, unsigned int language, ziWChar *output, unsigned int capacity, unsigned int mode, unsigned int status, ziU8 reservedMode, ziU8 *group, ziU8 acceptPrefix, ziPtr __zi8_work_data)
{
ziU16 character;
unsigned int result;
ziU8 prefixCount;
unsigned int index;
unsigned int remaining;
result = 0;
if (reservedMode != 0) return 0;
if ((status & 0xff) == 0) {
ZI_WORK->unk_0x1768 = 0;
ZI_WORK->unk_0x17EA = 0;
if ((((group == 0) || (*group != '\f')) || ((language & 0xff) != 10)) ||
(ZI_WORK->unk_0x141C == '\0')) {
ZI_WORK->unk_0x141E = 0;
}
else {
ZI_WORK->unk_0x141E = 0x10;
}
}
search_segment:
ZI_WORK->unk_0x141F = 1;
result = Zi8MatchROMdata1(elements + (unsigned int)ZI_WORK->unk_0x17EA,
count - ZI_WORK->unk_0x17EA & 0xff,language & 0xff,
&ZI_WORK->unk_0x17F4[ZI_WORK->unk_0x17EA],
capacity & 0xffff,mode & 0xff,status & 0xff,
ZI_WORK->unk_0x1768,(char *)group,acceptPrefix,ZI_WORK);
if ((result & 0xff) == 0) {
if ((((status & 0xff) != 0) || ((count & 0xff) == 1)) ||
(((mode & 0xff) == 1 &&
((ZI_WORK->unk_0x1768 == 0 &&
(prefixCount = Zi8MatchROMdata1(elements + (unsigned int)ZI_WORK->unk_0x17EA,
count - ZI_WORK->unk_0x17EA & 0xff,language & 0xff,
&ZI_WORK->unk_0x17F4[ZI_WORK->unk_0x17EA],
capacity & 0xffff,0,status & 0xff,
ZI_WORK->unk_0x1768,(char *)group,acceptPrefix,ZI_WORK),
prefixCount != '\0')))))) goto finish_segments;
index = Zi8GetTableCount(language & 0xff,0x1f,ZI_WORK);
if ((index & 4) == 0) {
for (index = 0; (index & 0xff) < (count & 0xff); index = index + 1) {
if (elements[index & 0xff] == 0xeff1) goto finish_segments;
}
}
if ((capacity & 0xffff) < (unsigned int)ZI_WORK->unk_0x141F) goto finish_segments;
prefixCount = ZI_WORK->unk_0x141F;
for (; prefixCount != 0; prefixCount--) {
result = Zi8MatchROMdata1(elements + (unsigned int)ZI_WORK->unk_0x17EA,prefixCount,
language & 0xff,
&ZI_WORK->unk_0x17F4[ZI_WORK->unk_0x17EA],
capacity & 0xffff,1,0,ZI_WORK->unk_0x1768,(char *)group,
acceptPrefix,ZI_WORK);
if ((result & 0xff) != 0) break;
}
if (prefixCount == 0) goto finish_segments;
ZI_WORK->unk_0x17EA = ZI_WORK->unk_0x17EA + ((ziU16)result & 0xff);
if ((unsigned int)ZI_WORK->unk_0x17EA == (count & 0xff)) {
result = 0;
goto finish_segments;
}
ZI_WORK->unk_0x1768 = ZI_WORK->unk_0x1768 + 1;
status = 0;
ZI_WORK->unk_0x141E = 0;
if ((ZI_WORK->dawgCtx.key == 0) && ((language & 0xff) == 10)) {
for (result = 0; (result & 0xff) < (unsigned int)ZI_WORK->unk_0x17EA; result = result + 1) {
character = ZI_WORK->unk_0x17F4[result & 0xff];
if (character == 0x6f) {
select_vowel_table:
ZI_WORK->unk_0x141E = 0x10;
break;
}
if (character < 0x6f) {
if (character == 0x61) goto select_vowel_table;
}
else if (character == 0x75) goto select_vowel_table;
}
}
goto search_segment;
}
for (remaining = ZI_WORK->unk_0x17EA + result & 0xff; (remaining & 0xff) != 0;
remaining = remaining - 1) {
output[(remaining & 0xff) - 1] = ZI_WORK->unk_0x17F4[(remaining & 0xff) - 1];
}
result = result + ZI_WORK->unk_0x17EA & 0xff;
finish_segments:
return result;
}
ziU8 Zi8MatchROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 mode, ziU8 status, ziU8 reservedMode, ziU8 acceptPrefix, ziPtr __zi8_work_data)
{
ziU16 *input;
ziU8* group;
int tableSize;
ziU8 found;
unsigned int elementCount;
unsigned int result;
input = (ziU16 *)elements;
elementCount = (unsigned int)count;
result = 0;
if ((capacity & 0xffff) < (elementCount & 0xff)) {
Zi8LogError(0x321,ZI_WORK);
}
else if ((status & 0xff) == 2) {
Zi8LogError(100,ZI_WORK);
}
else {
if ((status & 0xff) == 0) {
ZI_WORK->unk_0x17EC = 0;
group = NextDawgGroup(0,language & 0xff,ZI_WORK);
ZI_WORK->unk_0x17F0 = group;
}
else if (ZI_WORK->unk_0x17EC != '\0') {
Zi8LogError(100,ZI_WORK);
goto finish_match;
}
tableSize = Zi8GetTableSize(language & 0xff,0x1c,ZI_WORK);
if (tableSize == 0) {
result = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,
mode & 0xff,status & 0xff,reservedMode & 0xff,0,acceptPrefix,ZI_WORK);
}
else {
while (((ZI_WORK->unk_0x17F0 != 0 &&
(result = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,
mode & 0xff,status & 0xff,reservedMode & 0xff,
(ziU8 *)ZI_WORK->unk_0x17F0,acceptPrefix,ZI_WORK),
(result & 0xff) == 0)) &&
((status = 0, 1 < (elementCount & 0xff) || ((language & 0xff) != 0x36))))) {
group = NextDawgGroup(ZI_WORK->unk_0x17F0,language & 0xff,ZI_WORK);
ZI_WORK->unk_0x17F0 = group;
}
}
if (((((result & 0xff) == 0) && ((status & 0xff) == 0)) && ((mode & 0xff) == 1)) &&
(((elementCount & 0xff) == 1 && ((capacity & 0xffff) != 0)))) {
ZI_WORK->unk_0x17EC = 1;
if (tableSize == 0) {
found = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0,
status & 0xff,reservedMode & 0xff,0,acceptPrefix,ZI_WORK);
if (found != '\0') {
*output = *input;
result = 1;
}
}
else {
group = NextDawgGroup(0,language & 0xff,ZI_WORK);
ZI_WORK->unk_0x17F0 = group;
while (ZI_WORK->unk_0x17F0 != 0) {
found = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0,
status & 0xff,reservedMode & 0xff,(ziU8 *)ZI_WORK->unk_0x17F0,
acceptPrefix,ZI_WORK);
if (found != '\0') {
*output = *input;
result = 1;
break;
}
group = NextDawgGroup(ZI_WORK->unk_0x17F0,language & 0xff,ZI_WORK);
ZI_WORK->unk_0x17F0 = group;
}
}
}
Zi8LogError(100,ZI_WORK);
}
finish_match:
return (ziU8)result;
}
void Zi8SyllablesROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 status, ziU8* prefixLength, ziU8 reverseOrder, ziPtr __zi8_work_data)
{
ziU32 keyTable;
ziU8 graphTable;
graphTable = 0x1a;
keyTable = 0x1b;
if (prefixLength != 0) {
*prefixLength = 0;
}
if (reverseOrder != 0) {
graphTable = 0x18;
keyTable = 0x19;
}
if (Zi8GetTableSize(language & 0xff,graphTable,ZI_WORK) == 0) {
if (graphTable == 0x1a) {
graphTable = 0x18;
keyTable = 0x19;
}
else {
graphTable = 0x1a;
keyTable = 0x1b;
}
}
Zi8MatchROMdata0(elements,count,language & 0xff,output,capacity,1,status,graphTable,keyTable,0,(ziU8 *)prefixLength,
&ZI_WORK->dawgCtx,ZI_WORK->unk_0x1760,ZI_WORK);
return;
}

View File

@@ -0,0 +1,735 @@
#include <zi8clib/zitypes.h>
#include <zi8clib/zierror.h>
#include <zi8clib/zi8getc2.h>
typedef struct {
ziU8 countOnly;
ziU8 maxWordLength;
ziU8 lookupMode;
ziU8 suffixOnly;
ziU8 controls[8];
ziU32 maxCount;
ziU16 capacity;
ziU8 minWordLength;
ziU8 flags;
ziU16 candidateCapacity;
ziU8 checkOnly;
ziU8 reserved;
} ZiCandidateOptions;
const ziU8 Zi8SOdefaultArray[16] = {1, 4, 3, 2, 1, 8, 7, 6, 5, 0};
const ziFuzzyPYPairs Zi8PYdefaultFuzzyPairs = {0, 1, 1, 1, 1, 1, 1};
const ziFuzzyZYPairs Zi8ZYdefaultFuzzyPairs = {0};
ziU8 Zi8GetFormatVersion(ziU8 language, ziPtr work);
ziU32 Zi8GetTableAddress(ziU8 language, ziU8 table, ziPtr work);
ziU16 Zi8GetTableCount(ziU8 language, ziU8 table, ziPtr work);
ziU16 Zi8GetVersion(ziPtr work);
ziU16 Zi8GetOEMID(ziPtr work);
ziU16 Zi8GetBuildID(ziPtr work);
void Zi8Memcpy(ziU8* destination, ziU8* source, ziS32 count);
ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* options, ziPtr work);
ziBool Zi8ZHsetPYfuzzyPairs(ziFuzzyPYPairs pairs ZI_NEED_WORK) {
if (pairs.ziDefault) {
ZI_WORK->unk_0x1B28.word = *(const ziU32*)&Zi8PYdefaultFuzzyPairs;
} else {
ZI_WORK->unk_0x1B28.word = *(ziU32*)&pairs;
}
return 1;
}
ziBool Zi8ZHsetZYfuzzyPairs(ziFuzzyZYPairs pairs ZI_NEED_WORK) {
if (pairs.ziDefault) {
ZI_WORK->unk_0x1B2C.word = *(const ziU32*)&Zi8ZYdefaultFuzzyPairs;
} else {
ZI_WORK->unk_0x1B2C.word = *(ziU32*)&pairs;
}
return 1;
}
ziBool Zi8SetLatinSearchOrder(ziU8* searchArray, ziU8 searchSize ZI_NEED_WORK) {
if (searchArray == 0 || *searchArray == 0) {
ZI_WORK->unk_0x1410 = (ziU32)Zi8SOdefaultArray;
ZI_WORK->unk_0x1418 = 9;
} else {
ZI_WORK->unk_0x1410 = (ziU32)searchArray;
ZI_WORK->unk_0x1418 = searchSize;
}
return 1;
}
ziU16 Zi8GetGlobalDataSize(void) {
return sizeof(struct __zi8_work_data_s);
}
static ziU16 Zi8GetDataSignature(ziU8* destination, ziU16 capacity, ziU8 language, ziPtr work) {
ziU8* signature;
ziU16 length;
if (language == 1) {
if (Zi8GetFormatVersion(1, work) < 8) {
Zi8LogError(0x26f, work);
return 0;
}
length = 0x1e;
} else {
length = 3;
}
signature = (ziU8*)Zi8GetTableAddress(language, (ziU8)length, work);
length = Zi8GetTableCount(language, (ziU8)length, work);
if (length == 0 || length > capacity) {
Zi8LogError(0x961, work);
return 0;
}
Zi8Memcpy(destination, signature, length);
destination[length] = 0;
Zi8LogError(100, work);
return length;
}
static ziU16 Zi8GetEngineSignature(ziU8* destination, ziPtr work) {
ziU16 index = 0;
ziU16 major;
ziU16 minor;
ziU16 number;
destination[index++] = 'v';
major = (Zi8GetVersion(work) & 0xff00) >> 8;
minor = Zi8GetVersion(work) & 0xff;
destination[index++] = (ziU8)(major / 10 + '0');
destination[index++] = (ziU8)(major % 10 + '0');
destination[index++] = (ziU8)(minor / 10 + '0');
destination[index++] = (ziU8)(minor % 10 + '0');
destination[index++] = 'o';
number = Zi8GetOEMID(work);
destination[index++] = (ziU8)(number / 100 + '0');
destination[index++] = (ziU8)((number % 100) / 10 + '0');
destination[index++] = (ziU8)((number % 100) % 10 + '0');
destination[index++] = 'b';
number = Zi8GetBuildID(work);
destination[index++] = (ziU8)(number / 100 + '0');
destination[index++] = (ziU8)((number % 100) / 10 + '0');
destination[index++] = (ziU8)((number % 100) % 10 + '0');
destination[index] = 0;
return index;
}
static ziBool Zi8AlphaSignature(ziGetParam* parameters, ziBool countOnly ZI_NEED_WORK) {
ziU16 secondLength;
ziU16 firstLength;
ziU8* second;
ziU8* first;
ziU8 engine[32];
ziU8 dictionary[56];
ziU16 length;
ziU16 candidateCount;
ziWChar* output = parameters->candidates;
second = 0;
firstLength = 0;
secondLength = 0;
Zi8LogError(100, ZI_WORK);
parameters->letters = 0;
length = Zi8GetDataSignature(dictionary, 0x20, parameters->language, ZI_WORK);
if (length == 0 || length < parameters->elementCount) {
first = engine;
} else {
first = dictionary;
second = engine;
firstLength = length;
}
length = Zi8GetEngineSignature(engine, ZI_WORK);
if (length < parameters->elementCount) {
if (firstLength == 0) {
Zi8ReplaceLastError(500, ZI_WORK);
return 0;
}
second = 0;
candidateCount = 1;
} else if (firstLength == 0) {
candidateCount = 1;
firstLength = length;
} else {
candidateCount = 2;
secondLength = length;
}
if (parameters->firstCandidate < candidateCount) {
candidateCount -= parameters->firstCandidate;
if (!countOnly) {
if (parameters->maxCandidates < candidateCount) {
candidateCount = parameters->maxCandidates;
}
parameters->letters = candidateCount;
if (!(parameters->getOptions & 0x80)) {
ZI_WORK->unk_0x538 = parameters->language;
parameters->candidates[0] = 0xfff0;
output = (ziWChar*)&ZI_WORK->unk_0x338;
}
if (parameters->firstCandidate != 0) {
first = second;
firstLength = secondLength;
}
if (ZI_WORK->unk_0x0A < firstLength) {
firstLength = ZI_WORK->unk_0x0A;
}
if ((parameters->elementCount < ZI_WORK->unk_0x140C[0] ||
(parameters->getOptions & 0x7e) == 2) &&
parameters->elementCount < firstLength) {
firstLength = parameters->elementCount;
}
while (firstLength-- != 0) {
*output++ = *first++;
}
*output++ = 0;
if (parameters->letters == 2) {
if (ZI_WORK->unk_0x0A < secondLength) {
secondLength = ZI_WORK->unk_0x0A;
}
if ((parameters->elementCount < ZI_WORK->unk_0x140C[0] ||
(parameters->getOptions & 0x7e) == 2) &&
parameters->elementCount < secondLength) {
secondLength = parameters->elementCount;
}
while (secondLength-- != 0) {
*output++ = *second++;
}
*output++ = 0;
}
*output = 0;
ZI_WORK->unk_0x0A = 0xff;
return 1;
}
parameters->letters = candidateCount;
ZI_WORK->unk_0x0A = 0xff;
return 1;
}
Zi8ReplaceLastError(501, ZI_WORK);
return 0;
}
static ziBool Zi8ZhSignature(ziGetParam* parameters, ziBool countOnly ZI_NEED_WORK) {
ziWChar* output = parameters->candidates;
ziU8* current = 0;
ziU16 copied;
ziU8 engine[32];
ziU8 dictionary[64];
ziU16 dataLength;
ziU32 engineLength;
ziU32 candidateCount;
ziU8 available;
Zi8LogError(100, ZI_WORK);
parameters->letters = 0;
dataLength = Zi8GetDataSignature(dictionary, 0x20, parameters->language, ZI_WORK);
engineLength = Zi8GetEngineSignature(engine, ZI_WORK);
if (!(parameters->context & 0x10)) {
candidateCount = dataLength + engineLength;
} else {
candidateCount = dataLength != 0;
if (engineLength != 0) candidateCount++;
}
if (parameters->firstCandidate < candidateCount) {
available = candidateCount - parameters->firstCandidate;
if (!countOnly) {
if (parameters->maxCandidates < (ziU16)(candidateCount - parameters->firstCandidate)) {
available = parameters->maxCandidates;
}
parameters->letters = available;
if (!(parameters->context & 0x10)) {
copied = 0;
if (dataLength != 0) {
if (parameters->firstCandidate < dataLength) {
candidateCount = dataLength - parameters->firstCandidate;
current = dictionary + parameters->firstCandidate;
} else {
candidateCount = 0;
}
if (parameters->letters < candidateCount) candidateCount = parameters->letters;
copied = candidateCount;
while (candidateCount-- != 0) *output++ = *current++;
}
current = engine;
if (dataLength <= parameters->firstCandidate) {
dataLength += engineLength - parameters->firstCandidate;
current += engineLength - dataLength;
engineLength = dataLength;
}
if ((int)(parameters->letters - copied) < (int)engineLength) {
engineLength = parameters->letters - copied;
}
while (engineLength-- != 0) *output++ = *current++;
} else {
if (parameters->firstCandidate == 0 && dataLength != 0) {
current = dictionary;
} else {
if (parameters->firstCandidate != 0 && dataLength == 0) {
Zi8ReplaceLastError(500, ZI_WORK);
return 0;
}
current = engine;
dataLength = engineLength;
}
while (dataLength-- != 0) *output++ = *current++;
*output = 0x20;
if (parameters->letters == 2) {
current = engine;
while (++output, engineLength-- != 0) *output = *current++;
*output = 0x20;
}
}
return 1;
}
parameters->letters = available;
ZI_WORK->unk_0x0A = 0xff;
return 1;
}
Zi8ReplaceLastError(502, ZI_WORK);
return 0;
}
ziU8 _Zi8GetCandidates(ziGetParam* parameters ZI_NEED_WORK) {
ZiCandidateOptions options = {0};
options.capacity = ZI_WORK->unk_0x141A;
return Zi8GetCandidatesOrCount(parameters, &options, ZI_WORK);
}
ziU8 _Zi8CheckCandidates(ziGetParam* parameters ZI_NEED_WORK) {
ZiCandidateOptions options = {0};
options.capacity = ZI_WORK->unk_0x141A;
options.flags = 1;
return Zi8GetCandidatesOrCount(parameters, &options, ZI_WORK);
}
ziU8 Zi8LangSupported(ziU8 language, ziPtr work);
ziBool Zi8IsCharacter(ziWChar character, ziPtr work);
ziU8 Zi8GetCharInfo(ziWChar character, ziWChar* output, ziU8 capacity, ziU8 type, ziPtr work);
ziU8 Zi8GetKOcandidates(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8GetKoreanCandidates(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8Punctuation(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8GetChineseCandidates(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8Get1KeyPressCandidates(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8Get1KeyPressSpelling(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8GetSyllablesCandidates(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU8 Zi8AlphaGetCandidates(ziGetParam* parameters, ziPtr options, ziPtr work);
ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* options ZI_NEED_WORK) {
ziU8 savedElementCount;
ziU16 savedCharacter;
ziWChar* savedElements;
ziBool restoreCandidates;
char signatureFound;
ziU8 elementCount;
int error;
unsigned int candidateCount;
ziU8 savedOptions;
ziWChar* savedCandidates;
ziU16 characterInfo [32];
error = 0;
savedOptions = 0;
savedCandidates = 0;
restoreCandidates = 0;
if (options->lookupMode == '\0') {
if (((ZI_WORK->unk_0x00 == '\t') && (parameters->elementCount != 0)) &&
((((ziS16)parameters->elements[parameters->elementCount - 1] == -0x1008 &&
(signatureFound = Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) ||
(((ziS16)parameters->elements[parameters->elementCount - 1] == -0x10fc &&
(signatureFound = Zi8ZhSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')))))) {
candidateCount = (unsigned int)parameters->letters;
if (options->countOnly != '\0') {
parameters->letters = 0;
}
Zi8LogError(100,ZI_WORK);
goto finishCandidates;
}
if ((parameters->elementCount == 1) && (parameters->firstCandidate == 0)) {
elementCount = parameters->language;
if (elementCount == 0x11) goto latinSequence;
if (elementCount < 0x11) {
if (elementCount == 1) {
if ((ZI_WORK->unk_0x00 == '\0') || (ZI_WORK->unk_0x01 == options->countOnly)) {
switch(ZI_WORK->unk_0x00) {
case '\0':
if ((ziS16)parameters->elements[0] == -0x10fc) {
ZI_WORK->unk_0x01 = options->countOnly;
ZI_WORK->unk_0x00 = '\x01';
}
break;
case '\x01':
case '\x03':
case '\x05':
case '\a':
if ((ziS16)parameters->elements[0] == -0x10ff) {
ZI_WORK->unk_0x00 = ZI_WORK->unk_0x00 + '\x01';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\x02':
case '\x04':
case '\x06':
if ((ziS16)parameters->elements[0] == -0x10fc) {
ZI_WORK->unk_0x00 = ZI_WORK->unk_0x00 + '\x01';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\b':
case '\t':
if (((ziS16)parameters->elements[0] == -0x10fc) &&
(signatureFound = Zi8ZhSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) {
ZI_WORK->unk_0x00 = '\t';
candidateCount = (unsigned int)parameters->letters;
if (options->countOnly != '\0') {
parameters->letters = 0;
}
Zi8LogError(100,ZI_WORK);
goto finishCandidates;
}
default:
ZI_WORK->unk_0x00 = '\0';
}
if ((ZI_WORK->unk_0x00 == '\0') && ((ziS16)parameters->elements[0] == -0x10fc)) {
ZI_WORK->unk_0x00 = '\x01';
}
}
}
else if ((elementCount == 0) || (elementCount < 0x10)) goto latinSequence;
}
else if (elementCount < 0x77) {
if (0x12 < elementCount) {
latinSequence:
if ((ZI_WORK->unk_0x00 == '\0') || (ZI_WORK->unk_0x01 == options->countOnly)) {
switch(ZI_WORK->unk_0x00) {
case '\0':
if ((ziS16)parameters->elements[0] == -0x100e) {
ZI_WORK->unk_0x01 = options->countOnly;
ZI_WORK->unk_0x00 = '\x01';
}
break;
case '\x01':
if ((ziS16)parameters->elements[0] == -0x100d) {
ZI_WORK->unk_0x00 = '\x02';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\x02':
if ((ziS16)parameters->elements[0] == -0x100b) {
ZI_WORK->unk_0x00 = '\x03';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\x03':
if ((ziS16)parameters->elements[0] == -0x1009) {
ZI_WORK->unk_0x00 = '\x04';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\x04':
if ((ziS16)parameters->elements[0] == -0x1008) {
ZI_WORK->unk_0x00 = '\x05';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\x05':
if ((ziS16)parameters->elements[0] == -0x1007) {
ZI_WORK->unk_0x00 = '\x06';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\x06':
if ((ziS16)parameters->elements[0] == -0x100e) {
ZI_WORK->unk_0x00 = '\a';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\a':
if ((ziS16)parameters->elements[0] == -0x100b) {
ZI_WORK->unk_0x00 = '\b';
}
else {
ZI_WORK->unk_0x00 = '\0';
}
break;
case '\b':
case '\t':
if (((ziS16)parameters->elements[0] == -0x1008) &&
(signatureFound = Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) {
ZI_WORK->unk_0x00 = '\t';
candidateCount = (unsigned int)parameters->letters;
if (options->countOnly != '\0') {
parameters->letters = 0;
}
Zi8LogError(100,ZI_WORK);
goto finishCandidates;
}
default:
ZI_WORK->unk_0x00 = '\0';
}
if ((ZI_WORK->unk_0x00 == '\0') && ((ziS16)parameters->elements[0] == -0x100e)) {
ZI_WORK->unk_0x00 = '\x01';
}
}
}
}
else if (0x7d < elementCount) goto latinSequence;
}
else if (1 < parameters->elementCount) {
ZI_WORK->unk_0x00 = '\0';
}
}
ZI_WORK->unk_0x18 = parameters->subLanguage;
elementCount = Zi8GetFormatVersion(1,ZI_WORK);
ZI_WORK->unk_0x16 = elementCount & 2;
options->maxCount = ZI_WORK->unk_0x10;
options->maxWordLength = ZI_WORK->unk_0x0A;
ZI_WORK->unk_0x0A = -1;
signatureFound = Zi8LangSupported(parameters->language,ZI_WORK);
if (signatureFound == '\0') {
Zi8LogError(0x163,ZI_WORK);
candidateCount = 0;
}
else {
if (parameters->language == 0x10) {
error = 0x2c1;
candidateCount = 0;
}
else if (parameters->language == 0x12) {
if ((parameters->elementCount == 0) || (0xeff0 < parameters->elements[0])) {
candidateCount = Zi8GetKOcandidates(parameters,options,ZI_WORK);
}
else {
candidateCount = Zi8GetKoreanCandidates(parameters,options,ZI_WORK);
}
}
else if ((parameters->language == 1) && ((parameters->context & 8) != 0)) {
candidateCount = Zi8Punctuation(parameters,options,ZI_WORK);
error = 100;
}
else if ((parameters->language == 1) &&
((((parameters->getOptions & 0xbf) == 4 && (parameters->elementCount != 0)) &&
(signatureFound = Zi8IsCharacter(parameters->elements[0],ZI_WORK), signatureFound != '\0')))) {
elementCount = Zi8GetCharInfo(parameters->elements[0],characterInfo,0x10,1,ZI_WORK);
if (elementCount == 0) {
parameters->unk_0x20 = 0;
parameters->count = 0;
parameters->letters = 0;
candidateCount = 0;
error = 900;
}
else {
if ((0xf330 < characterInfo[elementCount - 1]) && (characterInfo[elementCount - 1] < 0xf336)) {
characterInfo[elementCount - 1] = 0xf360;
}
savedElements = parameters->elements;
parameters->elements = characterInfo;
savedElementCount = parameters->elementCount;
parameters->elementCount = elementCount;
elementCount = parameters->getMode;
parameters->getMode = 1;
candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK);
parameters->elements = savedElements;
parameters->elementCount = savedElementCount;
parameters->getMode = elementCount;
parameters->count = 1;
}
}
else if ((parameters->language == 1) && (parameters->getMode == 0xf)) {
error = 0x2d0;
candidateCount = 0;
}
else if ((parameters->language == 1) && ((parameters->getMode == 3 || (parameters->getMode == 4)))) {
if ((parameters->getOptions & 0x80) == 0) {
if (parameters->elementCount == 0) {
candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK);
}
else {
candidateCount = Zi8Get1KeyPressCandidates(parameters,options,ZI_WORK);
}
}
else {
candidateCount = Zi8Get1KeyPressSpelling(parameters,options,ZI_WORK);
}
}
else if ((parameters->language == 1) &&
((((parameters->getMode == 7 || (parameters->getMode == 8)) || (parameters->getMode == 10)) || (parameters->getMode == 9)))) {
if (ZI_WORK->unk_0x16 == '\0') {
error = 0x708;
candidateCount = 0;
}
else {
candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK);
}
}
else if ((parameters->language == 1) && ((parameters->getMode == 0xb || (parameters->getMode == 0xe)))) {
error = 0x2ee;
candidateCount = 0;
}
else if (parameters->language == 1) {
candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK);
if ((((candidateCount == 0) && ((parameters->getOptions & 0x20) == 0)) && ((parameters->getMode == 1 && (parameters->elementCount != 0))))
&& ((((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc86 ||
((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc9d)) ||
((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc8d)))) {
savedCharacter = parameters->elements[parameters->elementCount];
elementCount = parameters->elementCount;
parameters->elements[elementCount] = 0xf368;
parameters->elementCount = elementCount + 1;
candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK);
elementCount = parameters->elementCount;
parameters->elementCount = elementCount - 1;
parameters->elements[(ziU8)(elementCount - 1)] = savedCharacter;
}
}
else {
ZI_WORK->unk_0x538 = parameters->language;
restoreCandidates = (parameters->getOptions & 0x80) == 0;
if (restoreCandidates) {
savedOptions = parameters->getOptions;
savedCandidates = parameters->candidates;
parameters->getOptions = parameters->getOptions | 0x81;
parameters->candidates = (ziWChar*)&ZI_WORK->unk_0x338;
options->capacity = 0x100;
}
if (parameters->getMode == 2) {
candidateCount = Zi8GetTableCount(parameters->language,0x1f,ZI_WORK);
if ((candidateCount & 0x200) == 0) {
error = 0x44c;
candidateCount = 0;
}
else {
candidateCount = Zi8GetSyllablesCandidates(parameters,options,ZI_WORK);
}
}
else {
candidateCount = Zi8AlphaGetCandidates(parameters,options,ZI_WORK);
}
}
if (restoreCandidates) {
parameters->getOptions = savedOptions;
parameters->candidates = savedCandidates;
for (elementCount = 0; elementCount < parameters->letters; elementCount = elementCount + 1) {
parameters->candidates[elementCount] = elementCount - 0x10;
}
}
if (error != 0) {
Zi8LogError(error,ZI_WORK);
}
}
finishCandidates:
return candidateCount;
}
void Zi8InitDupWordBuf(ziPtr __zi8_work_data) {
ZI_WORK->unk_0x539 = 0;
}
ziBool Zi8IsDupWChar(ziWChar character ZI_NEED_WORK) {
ziBool duplicate = 0;
ziU16* buffer = ZI_WORK->unk_0x57A;
unsigned int index;
ziU16 position;
if (ZI_WORK->unk_0x539 == 0) {
buffer[0] = 2;
buffer[1] = character;
ZI_WORK->unk_0x539 = 1;
Zi8LogError(0x8fd, ZI_WORK);
return 0;
}
for (index = ZI_WORK->unk_0x539; index != 0; index--) {
if (character == buffer[index]) {
duplicate = 1;
break;
}
}
ZI_WORK->unk_0x539++;
position = *buffer;
buffer[position] = character;
*buffer = ++position;
if (*buffer > 100) {
*buffer = 2;
buffer[1] = character;
ZI_WORK->unk_0x539 = 1;
}
Zi8LogError(100, ZI_WORK);
return duplicate;
}
ziBool Zi8IsDupWordW(ziWChar* word, ziU8 length ZI_NEED_WORK) {
ziU8 slot;
ziU32 duplicate = 0;
unsigned int position;
int index;
int character;
if (word == 0 || length == 0) {
Zi8LogError(300, ZI_WORK);
return 0;
}
if (length > 20) {
word += length - 20;
length = 20;
}
for (index = 0; index < ZI_WORK->unk_0x539; index++) {
slot = ZI_WORK->unk_0x53A[index];
for (character = 0; character < length; character++) {
if (word[character] != ZI_WORK->unk_0x57A[slot * 21 + character]) break;
}
if (character >= length && ZI_WORK->unk_0x57A[slot * 21 + character] == 0) {
duplicate = 1;
break;
}
}
if (!duplicate) {
if (ZI_WORK->unk_0x539 < 64) {
position = ZI_WORK->unk_0x539;
ZI_WORK->unk_0x53A[ZI_WORK->unk_0x539] = ZI_WORK->unk_0x539;
ZI_WORK->unk_0x539++;
} else {
slot = ZI_WORK->unk_0x53A[0];
position = slot;
for (index = 1; index < ZI_WORK->unk_0x539; index++) {
ZI_WORK->unk_0x53A[index - 1] = ZI_WORK->unk_0x53A[index];
}
ZI_WORK->unk_0x53A[index - 1] = slot;
}
} else {
slot = ZI_WORK->unk_0x53A[index];
position = slot;
for (; index < ZI_WORK->unk_0x539 - 1; index++) {
ZI_WORK->unk_0x53A[index] = ZI_WORK->unk_0x53A[index + 1];
}
ZI_WORK->unk_0x53A[index] = slot;
}
for (index = 0; index < length; index++) {
ZI_WORK->unk_0x57A[position * 21 + index] = word[index];
}
ZI_WORK->unk_0x57A[position * 21 + index] = 0;
Zi8LogError(100, ZI_WORK);
return duplicate;
}
void Zi8Memset(ziU8* destination, ziU32 value, ziS32 count) {
ziS32 index;
for (index = 0; index < count; index++) destination[index] = (ziU8)value;
}
void Zi8Memcpy(ziU8* destination, ziU8* source, ziS32 count) {
ziS32 index;
for (index = 0; index < count; index++) destination[index] = source[index];
}
ziBool Zi8SetMaxWordLength(ziU8 length ZI_NEED_WORK) {
ZI_WORK->unk_0x0A = length;
return 1;
}

View File

@@ -0,0 +1,876 @@
#include <zi8clib/zierror.h>
#include <zi8clib/zitypes.h>
extern ziU32 Zi8GetTableAddress(ziU8 lang, ziU8 tableIdx ZI_NEED_WORK);
const ziU8 Zi8PinyinInitials[0x1C] = {
0x00, 0x3C, 0x98, 0x02, 0x00, 0x38, 0x34, 0x3B, 0x00, 0x06, 0x37, 0x2B,
0x0C, 0x26, 0x00, 0x3F, 0x09, 0x2C, 0x9A, 0x05, 0x00, 0x00, 0x11, 0x0A,
0x0D, 0x9C, 0x00, 0x00
};
const ziU8 Zi8BpmfInitials[0x24] = {
0x3C, 0x3F, 0x0C, 0x38, 0x02, 0x05, 0x26, 0x2B, 0x34, 0x37, 0x3B, 0x06,
0x09, 0x0A, 0x1D, 0x19, 0x1B, 0x2C, 0x1C, 0x18, 0x1A, 0x01, 0x02, 0x03,
0x05, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0E, 0x0D, 0x0F, 0x04, 0x00, 0x00
};
const ziU8 Zi8PinyinFinals[0x36][8] = {
{0x0F, 0xFF, 0x00, 0x00, 0x3C, 0x28, 0x00, 0x00},
{0x0F, 0x00, 0x00, 0x00, 0x3F, 0x2B, 0x00, 0x00},
{0x0F, 0x0E, 0xFF, 0x00, 0x3F, 0x28, 0x00, 0x00},
{0x0F, 0x0E, 0x07, 0x00, 0x3F, 0x28, 0x00, 0x00},
{0x0F, 0x15, 0x00, 0x00, 0x3F, 0x2A, 0x00, 0x00},
{0x09, 0xFF, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00},
{0x09, 0x00, 0x00, 0x00, 0x3F, 0x08, 0x00, 0x00},
{0x09, 0x01, 0xFF, 0x00, 0x38, 0x00, 0x00, 0x00},
{0x09, 0x01, 0x00, 0x00, 0x3F, 0x04, 0x00, 0x00},
{0x09, 0x01, 0x0F, 0x00, 0x3F, 0x01, 0x00, 0x00},
{0x09, 0x01, 0x0E, 0xFF, 0x3E, 0x02, 0x00, 0x00},
{0x09, 0x01, 0x0E, 0x00, 0x3F, 0x02, 0x00, 0x00},
{0x09, 0x01, 0x0E, 0x07, 0x3F, 0x03, 0x00, 0x00},
{0x09, 0x05, 0x00, 0x00, 0x3F, 0x09, 0x00, 0x00},
{0x09, 0x15, 0x00, 0x00, 0x3F, 0x0B, 0x00, 0x00},
{0x09, 0x0E, 0xFF, 0x00, 0x3E, 0x0C, 0x00, 0x00},
{0x09, 0x0E, 0x00, 0x00, 0x3F, 0x0C, 0x00, 0x00},
{0x09, 0x0E, 0x07, 0x00, 0x3F, 0x0D, 0x00, 0x00},
{0x09, 0x0F, 0xFF, 0x00, 0x3E, 0x0E, 0x00, 0x00},
{0x09, 0x0F, 0x15, 0x00, 0x3F, 0x0E, 0x00, 0x00},
{0x09, 0x0F, 0x0E, 0xFF, 0x3F, 0x0F, 0x00, 0x00},
{0x09, 0x0F, 0x0E, 0x07, 0x3F, 0x0F, 0x00, 0x00},
{0x15, 0xFF, 0x00, 0x00, 0x30, 0x10, 0x00, 0x00},
{0x15, 0x00, 0x00, 0x00, 0x3F, 0x18, 0x00, 0x00},
{0x15, 0x01, 0xFF, 0x00, 0x38, 0x10, 0x00, 0x00},
{0x15, 0x01, 0x00, 0x00, 0x3F, 0x17, 0x00, 0x00},
{0x15, 0x01, 0x0E, 0xFF, 0x3E, 0x10, 0x00, 0x00},
{0x15, 0x01, 0x0E, 0x00, 0x3F, 0x10, 0x00, 0x00},
{0x15, 0x01, 0x0E, 0x07, 0x3F, 0x11, 0x00, 0x00},
{0x15, 0x01, 0x09, 0x00, 0x3F, 0x13, 0x00, 0x00},
{0x15, 0x0E, 0x00, 0x00, 0x3F, 0x1C, 0x00, 0x00},
{0x15, 0x09, 0x00, 0x00, 0x3F, 0x1D, 0x00, 0x00},
{0x15, 0x0F, 0x00, 0x00, 0x3F, 0x1E, 0x00, 0x00},
{0x15, 0x05, 0x00, 0x00, 0x3F, 0x1F, 0x00, 0x00},
{0x01, 0xFF, 0x00, 0x00, 0x38, 0x20, 0x00, 0x00},
{0x01, 0x00, 0x00, 0x00, 0x3F, 0x23, 0x00, 0x00},
{0x01, 0x0E, 0xFF, 0x00, 0x3E, 0x20, 0x00, 0x00},
{0x01, 0x0E, 0x00, 0x00, 0x3F, 0x20, 0x00, 0x00},
{0x01, 0x0E, 0x07, 0x00, 0x3F, 0x21, 0x00, 0x00},
{0x01, 0x09, 0x00, 0x00, 0x3F, 0x25, 0x00, 0x00},
{0x01, 0x0F, 0x00, 0x00, 0x3F, 0x26, 0x00, 0x00},
{0x05, 0xFF, 0x00, 0x00, 0x38, 0x30, 0x00, 0x00},
{0x05, 0x00, 0x00, 0x00, 0x3F, 0x34, 0x00, 0x00},
{0x05, 0x0E, 0xFF, 0x00, 0x3E, 0x30, 0x00, 0x00},
{0x05, 0x0E, 0x00, 0x00, 0x3F, 0x30, 0x00, 0x00},
{0x05, 0x0E, 0x07, 0x00, 0x3F, 0x31, 0x00, 0x00},
{0x05, 0x09, 0x00, 0x00, 0x3F, 0x35, 0x00, 0x00},
{0x05, 0x12, 0x00, 0x00, 0x3F, 0x33, 0x00, 0x00},
{0x16, 0xFF, 0x00, 0x00, 0x3C, 0x38, 0x00, 0x00},
{0x16, 0x00, 0x00, 0x00, 0x3F, 0x38, 0x00, 0x00},
{0x16, 0x01, 0xFF, 0x00, 0x3F, 0x39, 0x00, 0x00},
{0x16, 0x01, 0x0E, 0x00, 0x3F, 0x39, 0x00, 0x00},
{0x16, 0x05, 0x00, 0x00, 0x3F, 0x1F, 0x00, 0x00},
{0x16, 0x0E, 0x00, 0x00, 0x3F, 0x3B, 0x00, 0x00}
};
const ziU8 nodeHeaderTable[0x20] = {
0x00, 0x10, 0x00, 0x01, 0x00, 0x03, 0x00, 0x14, 0x00, 0x05, 0x00, 0x07,
0x00, 0x1C, 0x00, 0x0D, 0x00, 0x0F, 0x00, 0x11, 0x00, 0x13, 0x00, 0x15,
0x00, 0x17, 0x00, 0x1D, 0x00, 0x1F, 0x00, 0x35
};
ziBool Zi8PriMatchNextChar(ziU8* node, ziU8 mask0, ziU8 value0, ziU8 mask1, ziU8 value1, ziU8 mask2, ziU8 value2, ziU8 mask3, ziU8 value3, ziU16* count, ziU8** result, ziU16* code ZI_NEED_WORK) {
ziU16 remaining = *count;
while (remaining-- != 0) {
if ((value0 == (node[0] & mask0)) && (value3 == (node[3] & mask3)) && (value2 == (node[2] & mask2)) && (value1 == (node[1] & mask1))) {
*result = node;
*code = ((ziU16)node[6] << 8) + (ziU16)node[7];
*count = remaining;
Zi8LogError(0x64, ZI_WORK);
return 1;
}
node += 0xC;
}
Zi8LogError(0x12E, ZI_WORK);
return 0;
}
ziBool Zi8ExactMatchNextChar(ziU8* node, ziU8 mask0, ziU8 value0, ziU8 mask1, ziU8 value1, ziU8 mask2, ziU8 value2, ziU8 mask3, ziU8 value3, ziU16* count, ziU8** result, ziU16* code ZI_NEED_WORK) {
ziU16 remaining = *count;
ziU8* current = node;
while (remaining-- != 0) {
if ((value0 == (current[0] & mask0)) && (value3 == (current[3] & mask3)) && (value2 == (current[2] & mask2)) && (value1 == (current[1] & mask1))) {
*result = current;
*code = ((ziU16)current[6] << 8) + (ziU16)current[7];
*count = remaining;
Zi8LogError(0x64, ZI_WORK);
return 1;
}
current += 0xC;
}
Zi8LogError(0x12E, ZI_WORK);
return 0;
}
ziU32 Zi8SecMatchChar(ziPtr nodeAddress, ziU8* dictionaryAddress, ziMatchParam* match, ziU16* code ZI_NEED_WORK) {
ziBool isPartial = 0;
ziU16 matchCode;
ziU8* data;
ziU8 value;
struct {
ziU8 remaining;
ziU8 dataIndex;
ziU16 targetCode;
} state;
if (match->field22 != 0) {
state.targetCode = match->field22;
matchCode = ((ziU16)(((ziU8*)nodeAddress)[4] & 3) << 8) | ((ziU8*)nodeAddress)[5];
value = 0;
while (value++ < 6) {
if (state.targetCode == matchCode) {
break;
}
matchCode = ((ziU16)(*(dictionaryAddress + matchCode * 8 + 6) & 3) << 8) | *(dictionaryAddress + matchCode * 8 + 7);
if (matchCode == 0) {
break;
}
}
if (state.targetCode != matchCode) {
return 0;
}
}
data = (ziU8*)Zi8GetTableAddress(1, 1, ZI_WORK);
data += ((ziU8*)nodeAddress)[0xB] + (((ziU8*)nodeAddress)[0xA] << 8) + ((((ziU8*)nodeAddress)[9] & 0xF) << 16);
if (ZI_WORK->unk_0x16 != 0) {
switch (data[0] & 7) {
case 2:
data += 2;
break;
case 3:
case 4:
data += 3;
break;
case 5:
data += 4;
break;
default:
data++;
break;
}
}
value = data[0];
value = (value >> 4) & 7;
if (value * 2 + 10 < match->length) {
return 0;
}
if (match->length < 9) {
if (match->length == 8) {
if ((data[0] & 0xF) == 0xF) {
isPartial = 1;
}
} else if ((match->length & 1) != 0) {
if ((((ziU8*)nodeAddress)[match->length >> 1] & 0xF) == 0xF) {
isPartial = 1;
}
} else {
if ((((ziU8*)nodeAddress)[match->length >> 1] & 0xF0) == 0xF0) {
isPartial = 1;
}
}
if (match->length > 2) {
if ((match->length & 1) != 0) {
if (((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF0) == 0) || ((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF0) == 0xF0)) {
return 0;
}
} else {
if (((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF) == 0) || ((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF) == 0xF)) {
return 0;
}
}
}
if (code != 0) {
*code = ((ziU16)((ziU8*)nodeAddress)[6] << 8) + (ziU16)((ziU8*)nodeAddress)[7];
}
if (isPartial) {
return 2;
}
return 1;
}
if ((match->length & 1) != 0) {
if (((data[((match->length - 1) >> 1) - 4] & 0xF0) == 0) || ((data[((match->length - 1) >> 1) - 4] & 0xF0) == 0xF0)) {
return 0;
}
} else {
if (((data[((match->length - 1) >> 1) - 4] & 0xF) == 0) || ((data[((match->length - 1) >> 1) - 4] & 0xF) == 0xF)) {
return 0;
}
}
state.dataIndex = 4;
state.remaining = ((match->length + 1) >> 1) - 4;
if (((ziU8)value + 1) < (int)state.remaining) {
return 0;
}
if ((match->length & 1) != 0) {
if ((data[(match->length >> 1) - 4] & 0xF) == 0xF) {
isPartial = 1;
}
} else {
if ((data[(match->length >> 1) - 4] & 0xF0) == 0xF0) {
isPartial = 1;
}
}
if (match->count == 0) {
while (state.remaining != 0) {
if ((data[0] & match->arr1[state.dataIndex]) != match->arrD[state.dataIndex]) {
return 0;
}
state.dataIndex++;
state.remaining--;
data++;
}
}
if (code != 0) {
*code = ((ziU16)((ziU8*)nodeAddress)[6] << 8) + (ziU16)((ziU8*)nodeAddress)[7];
}
if (isPartial) {
return 2;
}
return 1;
}
ziBool Zi8PriMatchNextComp(ziU8* node, ziU8 mask0, ziU8 value0, ziU8 mask1, ziU8 value1, ziU8 mask2, ziU8 value2, ziU8 mask3, ziU8 value3, ziU16* count, ziU8** result ZI_NEED_WORK) {
ziU16 remaining = *count;
while (remaining-- != 0) {
if ((value0 == (node[0] & mask0)) && (value1 == (node[1] & mask1)) && (value2 == (node[2] & mask2)) && (value3 == (node[3] & mask3))) {
*result = node;
*count = remaining;
Zi8LogError(0x64, ZI_WORK);
return 1;
}
node += 8;
}
Zi8LogError(0x12E, ZI_WORK);
return 0;
}
ziBool Zi8SecMatchComp(ziPtr nodeAddress, ziMatchParam* matchAddress, ziPtr dictionaryAddress) {
int chainIndex;
ziU16 matchCode;
ziU16 targetCode;
if (matchAddress->field22 != 0) {
targetCode = matchAddress->field22;
matchCode = ((ziU16)(((ziU8*)nodeAddress)[6] & 3) << 8) | ((ziU8*)nodeAddress)[7];
chainIndex = 0;
while (chainIndex++ < 6) {
if (targetCode == matchCode) {
break;
}
matchCode = ((ziU16)(*((ziU8*)dictionaryAddress + matchCode * 8 + 6) & 3) << 8) | *((ziU8*)dictionaryAddress + matchCode * 8 + 7);
if (matchCode == 0) {
break;
}
}
if (targetCode != matchCode) {
return 0;
}
}
if (matchAddress->length > 8) {
if ((int)((ziU8*)nodeAddress)[5] < (int)(matchAddress->length - 2)) {
return 0;
}
} else if ((int)((ziU8*)nodeAddress)[5] < (int)(matchAddress->length - 1)) {
return 0;
}
return 1;
}
extern ziU16 Zi8MatchAltSound(ziPtr soundTable, ziU16 soundCode, ziPtr pCodeTable, ziU16 index, ziU16 mask, ziU16 value, ziU8 flag ZI_NEED_WORK);
ziU16 Zi8GetPCode(ziU8* table, ziU8* node);
ziBool Zi8MatchPhonetic(ziPtr pCodeTable, ziPtr dictionary, ziPtr soundTable, ziU16 soundCode, ziU32 tableAddress, ziU8* node, ziU16* masks, ziU16* values, ziU16* count, ziU8** resultNode, ziU8** stringOffset, ziS8 partialMode, ziU8 strictMode, ziU8 numParts, ziU16 partMask, ziU16 partValue, ziU8 flag, ziU8 altMode, ziU16 initialCode, ziU16* resultCode, ziU8 lastMode ZI_NEED_WORK) {
ziBool hasString;
ziU32 matchedParts;
ziU32 altModeActive;
ziU8 partCode;
ziU8 partCount;
ziU8 partIndex;
ziU16 soundIndex;
ziU16 remaining;
ziU16 code;
ziU16 dictionaryIndex;
ziU8 nextCode;
ziU8* sound;
ziU8* nextPart;
if (*stringOffset != 0) {
hasString = 1;
} else {
hasString = 0;
}
if (*count == 0) {
remaining = 1;
} else {
remaining = *count;
}
matchedParts = 0;
altModeActive = altMode;
if ((lastMode != 0) && (numParts > 1)) {
altModeActive = 1;
}
while (remaining-- != 0) {
if ((node[0] & flag) != 0) {
code = Zi8GetPCode((ziU8*)pCodeTable, node);
if ((*values != (code & *masks)) && (altModeActive == 0) && ((node[0] & 0x80) != 0)) {
if (*count != 0) {
soundIndex = (initialCode - remaining) - 1;
} else {
soundIndex = initialCode;
}
code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, soundIndex, *masks, *values, flag, ZI_WORK);
}
if ((*values == (code & *masks)) && (partValue != (code & partMask))) {
matchedParts = 1;
sound = (ziU8*)((tableAddress + ((node[9] & 0xF) * 0x10000)) + node[0xB] + node[0xA] * 0x100);
if (ZI_WORK->unk_0x16 != 0) {
switch (sound[0] & 7) {
case 2:
sound += 2;
break;
case 3:
case 4:
sound += 3;
break;
case 5:
sound += 4;
break;
default:
sound++;
break;
}
}
if ((sound[0] & 0x80) != 0) {
sound += ((sound[0] & 0x7F) >> 4) + 1;
} else if (numParts > 1) {
goto next_node;
}
if (((ziU8)matchedParts == numParts) || (numParts == 0)) {
*resultNode = node;
*resultCode = ((ziU16)node[6] << 8) + node[7];
*count = remaining;
return 1;
}
do {
nextCode = *sound++;
partCount = nextCode & 0xF;
if ((nextCode & flag) == 0) {
for (; partCount != 0; partCount--) {
for (sound++; (*sound & 0x80) == 0; sound += 2) {
}
sound++;
}
}
for (; partCount != 0; partCount--) {
partIndex = 1;
if (hasString && (*stringOffset < sound)) {
hasString = 0;
}
nextPart = sound;
if (!hasString) {
*stringOffset = sound;
}
do {
partCode = nextPart[1];
dictionaryIndex = ((ziU16)partCode << 8) | nextPart[0];
sound = nextPart + 2;
if (hasString) {
goto phonetic_skip;
}
code = Zi8GetPCode((ziU8*)pCodeTable, (ziU8*)dictionary + (dictionaryIndex & 0x7FFF) * 0xC);
if (((code & masks[partIndex]) != values[partIndex]) && (altModeActive == 0) && (((ziU8*)dictionary)[(dictionaryIndex & 0x7FFF) * 0xC] & 0x80) != 0) {
code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, dictionaryIndex & 0x7FFF, masks[partIndex], values[partIndex], flag, ZI_WORK);
}
if ((code & masks[partIndex]) != values[partIndex]) {
goto phonetic_skip;
}
partIndex++;
if (partIndex == numParts) {
if ((partialMode != 0) && ((strictMode == 0 && (partCode & 0x80) != 0) || (strictMode != 0 && (partCode & 0x80) == 0))) {
goto phonetic_skip;
}
*resultNode = node;
code = ((ziU16)node[6] << 8) + node[7];
*resultCode = code;
*count = remaining;
return 1;
}
nextPart = sound;
} while ((partCode & 0x80) == 0);
continue;
phonetic_skip:
if ((partCode & 0x80) == 0) {
nextPart += 3;
while ((*nextPart & 0x80) == 0) {
nextPart += 2;
}
sound = nextPart + 1;
}
}
} while ((nextCode & 0x80) == 0);
}
}
next_node:
node += 0xC;
}
return 0;
}
ziBool Zi8GetPyFinal(ziU8* pinyin, ziU8* initial, ziU8* final);
ziU8 Zi8GetPyPhonetic(ziWChar* text, ziU8 count, ziU16* initial, ziU16* final, ziU8* resultCount, ziU16* bestInitial, ziU16* bestFinal ZI_NEED_WORK) {
ziU8 firstInitial;
ziU8 pyFinal;
ziU8 pyInitial;
ziU8 convertedCount;
ziBool partial;
ziU8 result;
ziU8 outputIndex;
ziU8 partCount;
ziU16 value;
ziU8 index;
ziWChar converted[256];
ziWChar* current;
ziU8 pinyin[12];
current = converted;
result = 0;
*resultCount = 0;
if (count == 0) {
Zi8LogError(0x135, ZI_WORK);
return 0;
}
convertedCount = 0;
for (index = 0; index < count; index++) {
if (((text[index] >= 0xF341) && (text[index] <= 0xF35A)) || ((text[index] >= 0x41) && (text[index] <= 0x5A))) {
if ((convertedCount != 0) && (current[convertedCount - 1] != 0xF360) && (current[convertedCount - 1] != 0x27)) {
current[convertedCount] = 0x27;
convertedCount++;
}
current[convertedCount] = (text[index] & 0xFF) + 0x20;
} else {
current[convertedCount] = text[index];
}
convertedCount++;
}
count = convertedCount;
outputIndex = 0;
*bestInitial = 0;
*bestFinal = 0;
while ((outputIndex < 0x10) && (count != 0)) {
initial[outputIndex] = 0;
final[outputIndex] = 0;
value = *current;
if (value < 0x61) {
goto check_pinyin_extension;
}
if (value <= 0x7A) {
goto pinyin_ascii;
}
check_pinyin_extension:
if (value < 0xF361) {
goto invalid_pinyin;
}
if (value <= 0xF37A) {
value += 0xC9F;
goto pinyin_initial;
}
invalid_pinyin:
initial[0] = 0xFFFF;
final[0] = 0xFFFF;
*bestInitial = 0xFFFF;
*bestFinal = 0xFFFF;
return 1;
pinyin_ascii:
value -= 0x61;
pinyin_initial:
firstInitial = Zi8PinyinInitials[value];
if (firstInitial != 0) {
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
result++;
initial[outputIndex] = 0x7E00;
final[outputIndex] = (ziU16)firstInitial << 9;
*bestInitial = initial[outputIndex];
*bestFinal = final[outputIndex];
count--;
if (count == 0) {
break;
}
current += 1;
if (((firstInitial & 0x80) != 0) && ((current[0] == 0x68) || (current[0] == 0xF368))) {
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
final[outputIndex] += 0x200;
*bestInitial = initial[outputIndex];
*bestFinal = final[outputIndex];
count--;
if (count == 0) {
break;
}
current += 1;
}
} else if ((*current == 0xF369) || (*current == 0x69)) {
goto invalid_pinyin;
}
partial = 0;
for (index = 0; index < 4; index++) {
pinyin[index] = 0;
}
index = 0;
do {
while (1) {
if (index > 3) {
goto finish_final;
}
value = *current;
if ((value == 0x27) || (value == 0xF360) || (value == 0x20)) {
if (index != 0) {
partial = 1;
}
goto finish_final;
}
if ((value > 0xF330) && (value < 0xF336)) {
if (index != 0) {
partial = 1;
}
goto finish_final;
}
if ((value < 0x61) || (value > 0x7A)) {
if (value < 0xF361) {
goto finish_final;
}
value += 0xC9F;
if (value > 0x19) {
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
goto finish_final;
}
} else {
value -= 0x61;
}
pinyin[index] = (ziU8)value + 1;
if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) == 0) {
break;
}
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
current++;
index++;
count--;
if (count == 0) {
goto finish_final;
}
}
if (index > 2) {
pinyin[index] = 0;
partial = 1;
break;
}
pinyin[index + 1] = 0xFF;
if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) == 0) {
pinyin[index + 1] = 0;
pinyin[index] = 0;
partial = 1;
break;
}
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
pinyin[index + 1] = 0;
current++;
index++;
count--;
} while (count != 0);
finish_final:
if ((index > 3) && (count != 0) && ((*current == 0x27) || (*current == 0xF360) || (*current == 0x20))) {
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
current++;
count--;
}
if (index > 3) {
partial = 1;
}
if (!partial) {
pinyin[index] = 0xFF;
if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) == 0) {
pinyin[index] = 0;
if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) != 0) {
if (firstInitial == 0) {
result++;
initial[outputIndex] = 0x7E00;
final[outputIndex] = 0x200;
}
initial[outputIndex] |= (ziU16)pyInitial << 3;
final[outputIndex] |= (ziU16)pyFinal << 3;
*bestInitial = initial[outputIndex];
*bestFinal = final[outputIndex];
}
} else {
if (firstInitial == 0) {
result++;
initial[outputIndex] = 0x7E00;
final[outputIndex] = 0x200;
}
initial[outputIndex] |= (ziU16)pyInitial << 3;
final[outputIndex] |= (ziU16)pyFinal << 3;
*bestInitial = initial[outputIndex];
*bestFinal = final[outputIndex];
if ((outputIndex == 0) && (count == 0)) {
pinyin[index] = 0;
if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) != 0) {
if (firstInitial == 0) {
*bestInitial = 0x7E00;
*bestFinal = 0x200;
}
*bestInitial |= (ziU16)pyInitial << 3;
*bestFinal |= (ziU16)pyFinal << 3;
}
}
}
} else {
if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) != 0) {
if (firstInitial == 0) {
result++;
initial[outputIndex] = 0x7E00;
final[outputIndex] = 0x200;
}
initial[outputIndex] |= (ziU16)pyInitial << 3;
final[outputIndex] |= (ziU16)pyFinal << 3;
*bestInitial = initial[outputIndex];
*bestFinal = final[outputIndex];
} else {
if ((index != 0) && (count != 0)) {
goto invalid_pinyin;
}
}
}
convertedCount = count;
if (count != 0) {
value = *current;
if ((value == 0x27) || (value == 0xF360) || (value == 0x20)) {
current++;
convertedCount = count - 1;
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
} else if ((value > 0xF330) && ((ziU16)(value + 0xCCF) < 5)) {
initial[outputIndex] |= 7;
final[outputIndex] |= value + 0xCD0;
*bestInitial = initial[outputIndex];
*bestFinal = final[outputIndex];
convertedCount = count - 1;
current++;
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
if ((convertedCount != 0) && ((*current == 0x27) || (*current == 0xF360) || (*current == 0x20))) {
convertedCount = count - 2;
current++;
if (outputIndex == 0) {
*resultCount = *resultCount + 1;
}
}
}
}
count = convertedCount;
outputIndex++;
}
if ((*resultCount > 1) && (text[*resultCount - 1] > 0xF340) && (text[*resultCount - 1] < 0xF35B)) {
*resultCount = *resultCount - 1;
}
return result;
}
ziBool Zi8GetPyFinal(ziU8* pinyin, ziU8* initial, ziU8* final) {
ziU8 index = 0;
ziU8 row;
row = 0;
goto check_row;
scan_row:
while (index < 4) {
if (pinyin[index] != Zi8PinyinFinals[row][index]) {
break;
}
index++;
}
if (index < 4) {
goto next_row;
}
*initial = Zi8PinyinFinals[row][4];
*final = Zi8PinyinFinals[row][5];
return 1;
next_row:
row++;
index = 0;
check_row:
if (row < 0x36) {
goto scan_row;
}
return 0;
}
ziS32 Zi8GetBpmfPhonetic(ziWChar* text, ziU8 count, ziU16* initial, ziU16* final, ziU16* bestInitial, ziU16* bestFinal ZI_NEED_WORK) {
ziU16 value;
ziU32 resultCount = 0;
Zi8LogError(0x64, ZI_WORK);
if (count == 0) {
Zi8ReplaceLastError(0x135, ZI_WORK);
return 0;
}
value = text[0];
if (value < 0xF305) {
Zi8ReplaceLastError(0x154, ZI_WORK);
return 0;
}
value -= 0xF305;
if (value >= 0x25) {
Zi8ReplaceLastError(0x154, ZI_WORK);
return 0;
}
if (value < 0x15) {
*initial = 0x7E00;
*final = ((ziU16)Zi8BpmfInitials[value] & 0x7F) << 9;
resultCount++;
count--;
if (count == 0) {
*bestInitial = *initial;
*bestFinal = *final;
if ((value >= 0xE) && (value <= 0x14)) {
*bestInitial |= 0x1F8;
*bestFinal |= 0x38;
}
return resultCount;
}
text++;
if (*text == 0xF360) {
resultCount++;
count--;
if (count == 0) {
return resultCount;
}
Zi8ReplaceLastError(0x156, ZI_WORK);
return 0;
}
} else {
*initial = 0x7E00;
*final = 0x200;
}
value = *text - 0xF305;
switch ((ziS32)value) {
case 0x22:
goto bpmf_value_22;
case 0x23:
goto bpmf_value_23;
case 0x24:
goto bpmf_value_24;
default:
goto set_bpmf_initial;
}
bpmf_value_22:
*final |= 0x80;
*initial |= 0x180;
resultCount++;
count--;
if (count == 0) {
*bestInitial = *initial | 0x78;
*bestFinal = *final | 0x38;
return resultCount;
}
text++;
goto after_bpmf_initial;
bpmf_value_23:
*final |= 0x100;
*initial |= 0x180;
resultCount++;
count--;
if (count == 0) {
*bestInitial = *initial | 0x78;
*bestFinal = *final | 0x38;
return resultCount;
}
text++;
goto after_bpmf_initial;
bpmf_value_24:
*final |= 0x180;
*initial |= 0x180;
resultCount++;
count--;
if (count == 0) {
*bestInitial = *initial | 0x78;
*bestFinal = *final | 0x38;
return resultCount;
}
text++;
goto after_bpmf_initial;
set_bpmf_initial:
if ((*text < 0xF331) || (*text > 0xF335)) {
*initial |= 0x180;
}
after_bpmf_initial:
value = *text - 0xF305;
if ((value > 0x14) && (value < 0x22)) {
*final |= (ziU16)Zi8BpmfInitials[value] << 3;
*initial |= 0x78;
resultCount++;
count--;
if (count == 0) {
*bestInitial = *initial;
*bestFinal = *final;
return resultCount;
}
text++;
} else if ((*text < 0xF331) || (*text > 0xF335) || ((*initial & 0x180) == 0x180)) {
*final |= 0x38;
*initial |= 0x78;
}
value = *text;
if (value < 0xF331) {
Zi8ReplaceLastError(0x155, ZI_WORK);
return 0;
}
value -= 0xF330;
if (value > 5) {
Zi8ReplaceLastError(0x155, ZI_WORK);
return 0;
}
*initial |= 7;
*final |= value;
*bestInitial = *initial;
*bestFinal = *final;
resultCount++;
count--;
if (count != 0) {
Zi8ReplaceLastError(0x157, ZI_WORK);
return 0;
}
return resultCount;
}
ziU16 Zi8GetPCode(ziU8* table, ziU8* node) {
ziU16 index = ((ziU16)node[8] << 2) | (((ziU16)node[9] & 0x80) >> 6);
return ((((ziU16)node[9] >> 4) & 7) | (ziU16)table[index] | ((ziU16)table[index + 1] << 8));
}

View File

@@ -0,0 +1,423 @@
#include <zi8clib/zierror.h>
#include <zi8clib/zitypes.h>
ziU32 Zi8GetTableAddress(ziU8 lang, ziU8 tableIdx, ziPtr workData);
ziU16 Zi8GetTableCount(ziU8 lang, ziU8 tableIdx, ziPtr workData);
ziU8 Zi8_814813FC(ziWChar character, ziU8* result, ziU16* index, ziPtr workData) {
ziU16 i;
ziU8* table;
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 5, workData);
i = 0;
while (table[i] != 0) {
if (character == table[i]) {
*index = i;
*result = table[i];
Zi8LogError(0x64, workData);
return 1;
}
i++;
}
Zi8LogError(0x2A8, workData);
return 0;
}
ziU8 Zi8_81481E6C(ziU16* resultIndex, ziU16* input, ziU8 type, ziU16 count, ziPtr workData);
ziU8 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument,
ziPtr workData) {
struct {
ziU8 characterIndex;
ziU8 matched;
ziU8 elementIndex;
ziU8 reserved;
ziU16 index;
ziU16 currentCandidate;
ziU16 inputIndex;
ziU16 nextIndex;
ziU16 tableCount31;
ziU16 tableCount6;
ziU16 tableCount3;
ziU16 tableCount0;
ziU8* table31;
ziU8* table2;
ziU8* table1;
} state;
ziU16 buffer[100];
ziU8 result;
ziU16 currentCharacter;
ziU8* selectedTable;
state.nextIndex = 0;
result = 0;
state.characterIndex = 0xFF;
state.currentCandidate = params->firstCandidate;
params->unk_0x20 = 0;
params->count = 0;
params->letters = 0;
if ((argument != 0) && (*argument != 0)) {
Zi8LogError(0x7D0, workData);
return 0;
}
if ((params->elementCount == 0) || (params->elementCount > 100)) {
Zi8LogError(0x64, workData);
return 0;
}
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 4, workData);
state.table1 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 1, workData);
state.table2 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 2, workData);
state.table31 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x31, workData);
state.tableCount0 = Zi8GetTableCount(ZI8_LANG_KO, 0, workData);
state.tableCount3 = Zi8GetTableCount(ZI8_LANG_KO, 3, workData);
state.tableCount6 = Zi8GetTableCount(ZI8_LANG_KO, 6, workData);
state.tableCount31 = Zi8GetTableCount(ZI8_LANG_KO, 0x31, workData);
for (state.elementIndex = 0; state.elementIndex < params->elementCount;
state.elementIndex++) {
currentCharacter = params->elements[state.elementIndex];
if ((currentCharacter >= 0x61) && (currentCharacter <= 0x7A)) {
buffer[state.elementIndex] = state.table1[(currentCharacter - 0x61) * 2];
} else if ((currentCharacter >= 0x41) && (currentCharacter <= 0x5A)) {
buffer[state.elementIndex] = state.table1[(currentCharacter - 0x41) * 2 + 1];
} else {
state.matched = 0;
for (; state.table2[state.matched * 3] != 0; state.matched++) {
if (currentCharacter == state.table2[state.matched * 3]) break;
}
if (state.table2[(state.matched * 3)] == 0) {
Zi8LogError(0x161, workData);
return 0;
}
buffer[state.elementIndex] =
(state.table2[(state.matched * 3) + 1] << 8) |
state.table2[(state.matched * 3) + 2];
}
}
for (currentCharacter = 0; currentCharacter < state.elementIndex; currentCharacter++) {
state.inputIndex = 0;
if (Zi8_814813FC(buffer[currentCharacter], (ziU8*)&state.characterIndex,
(ziU16*)&state.inputIndex, workData) == 0) {
state.matched = 0;
} else {
state.matched = Zi8_81481E6C((ziU16*)&state.nextIndex,
&buffer[currentCharacter + 1],
state.characterIndex,
(state.elementIndex - currentCharacter) - 1,
workData);
if ((((struct __zi8_work_data_s*)workData)->unk_0x1B30 == 1) && (state.characterIndex < 0x1F)) {
switch (state.characterIndex) {
case 1:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1E, workData);
break;
case 2:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1F, workData);
break;
case 4:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x20, workData);
break;
case 7:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x21, workData);
break;
case 8:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x22, workData);
break;
case 9:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x23, workData);
break;
case 0x11:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x24, workData);
break;
case 0x12:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x25, workData);
break;
case 0x13:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x26, workData);
break;
case 0x15:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x27, workData);
break;
case 0x16:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x28, workData);
break;
case 0x17:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x29, workData);
break;
case 0x18:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2A, workData);
break;
case 0x19:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2B, workData);
break;
case 0x1A:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2C, workData);
break;
case 0x1B:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2D, workData);
break;
case 0x1C:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2E, workData);
break;
case 0x1D:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2F, workData);
break;
case 0x1E:
selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x30, workData);
break;
default:
break;
}
}
}
if (state.matched == 0) {
if (state.currentCandidate == 0) {
for (state.index = 0; state.index < state.tableCount31; state.index++) {
if (((ziU16)state.table31[(state.index * 3)] == buffer[currentCharacter]) &&
((ziU16)state.table31[(state.index * 3) + 1] == buffer[currentCharacter + 1])) {
if (currentCharacter == 0) {
params->count = 1;
}
params->candidates[result] =
state.tableCount0 + state.table31[(state.index * 3) + 2];
result++;
currentCharacter++;
break;
}
}
if (state.index == state.tableCount31) {
params->candidates[result] = buffer[currentCharacter];
if (buffer[currentCharacter] < 0xFF) {
if (currentCharacter == 0) {
params->count = 1;
}
params->candidates[result] += state.tableCount0;
result++;
}
}
} else {
state.index = 0;
while ((state.index < state.tableCount31) &&
(((ziU16)state.table31[(state.index * 3)] != buffer[currentCharacter]) ||
((ziU16)state.table31[(state.index * 3) + 1] != buffer[currentCharacter + 1]))) {
state.index++;
}
if (state.index == state.tableCount31) {
state.currentCandidate--;
}
if (currentCharacter == 0) {
params->count = 1;
}
}
} else {
if (state.tableCount6 == 0) {
state.nextIndex += state.inputIndex * state.tableCount3;
}
if (state.currentCandidate == 0) {
params->candidates[result] =
(selectedTable[state.nextIndex * 2] << 8) | selectedTable[state.nextIndex * 2 + 1];
if ((state.tableCount6 != 0) && (((struct __zi8_work_data_s*)workData)->unk_0x1B30 == 0)) {
params->candidates[result] += state.inputIndex * state.tableCount3;
}
result++;
} else {
state.currentCandidate--;
}
if (currentCharacter == 0) {
params->count = state.matched + 1;
}
currentCharacter += state.matched;
}
if (result >= params->maxCandidates) {
break;
}
}
params->letters = result;
Zi8LogError(0x64, workData);
return result;
}
ziU8 Zi8_81481E6C(ziU16* resultIndex, ziU16* input, ziU8 type, ziU16 count, ziPtr workData) {
ziU16 nestedScratch;
ziU16 nestedIndexStorage;
ziU16 index1;
ziU16 index2;
ziU16 index3;
ziU16 index4;
ziU16 firstCharacter;
ziU16 tableCount;
ziU8 mappedCharacter;
ziU8* table;
firstCharacter = input[0];
mappedCharacter = 0xFF;
if (((struct __zi8_work_data_s*)workData)->unk_0x1B30 == 0) {
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 3, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 3, workData);
} else {
switch (type) {
case 1:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xB, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xB, workData);
break;
case 2:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xC, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xC, workData);
break;
case 4:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xD, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xD, workData);
break;
case 7:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xE, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xE, workData);
break;
case 8:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xF, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xF, workData);
break;
case 9:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x10, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x10, workData);
break;
case 0x11:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x11, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x11, workData);
break;
case 0x12:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x12, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x12, workData);
break;
case 0x13:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x13, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x13, workData);
break;
case 0x15:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x14, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x14, workData);
break;
case 0x16:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x15, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x15, workData);
break;
case 0x17:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x16, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x16, workData);
break;
case 0x18:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x17, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x17, workData);
break;
case 0x19:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x18, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x18, workData);
break;
case 0x1A:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x19, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x19, workData);
break;
case 0x1B:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1A, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1A, workData);
break;
case 0x1C:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1B, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1B, workData);
break;
case 0x1D:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1C, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1C, workData);
break;
case 0x1E:
table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1D, workData);
tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1D, workData);
break;
}
}
*resultIndex = 0;
if ((count < 1) || (firstCharacter >= 0xFF)) {
return 0;
}
index1 = *resultIndex;
for (; index1 < tableCount; index1++) {
if (table[index1 * 4] >= firstCharacter) {
break;
}
}
if ((index1 >= tableCount) || (firstCharacter != table[index1 * 4])) {
return 0;
}
if ((count < 2) || ((firstCharacter = input[1]) >= 0xFF)) {
*resultIndex = index1;
return 1;
}
index2 = index1;
for (; index2 < tableCount; index2++) {
if ((table + index2 * 4)[1] >= firstCharacter) {
break;
}
}
if ((index2 >= tableCount) || (firstCharacter != (table + index2 * 4)[1]) ||
(input[0] != table[index2 * 4])) {
*resultIndex = index1;
return 1;
}
if ((count < 3) || ((firstCharacter = input[2]) >= 0xFF)) {
*resultIndex = index2;
return 2;
}
index3 = index2;
for (; index3 < tableCount; index3++) {
if ((table + index3 * 4)[2] >= firstCharacter) {
break;
}
}
if ((index3 >= tableCount) || (firstCharacter != (table + index3 * 4)[2]) ||
(input[1] != (table + index3 * 4)[1]) || (input[0] != table[index3 * 4])) {
if ((Zi8_814813FC(input[1], &mappedCharacter, &nestedScratch, workData) != 0) &&
(Zi8_81481E6C(&nestedIndexStorage, input + 2, mappedCharacter, 1, workData) != 0)) {
*resultIndex = index1;
return 1;
}
*resultIndex = index2;
return 2;
}
if ((count < 4) || ((firstCharacter = input[3]) >= 0xFF)) {
*resultIndex = index3;
return 3;
}
index4 = index3;
for (; index4 < tableCount; index4++) {
if ((table + index4 * 4)[3] >= firstCharacter) {
break;
}
}
if ((index4 >= tableCount) || (firstCharacter != (table + index4 * 4)[3]) ||
(input[2] != (table + index4 * 4)[2]) || (input[1] != (table + index4 * 4)[1]) ||
(input[0] != table[index4 * 4])) {
if ((Zi8_814813FC(input[2], &mappedCharacter, &nestedScratch, workData) != 0) &&
(Zi8_81481E6C(&nestedIndexStorage, input + 3, mappedCharacter, 1, workData) != 0)) {
*resultIndex = index2;
return 2;
}
*resultIndex = index3;
return 3;
}
if ((count < 5) || ((firstCharacter = input[4]) >= 0xFF)) {
*resultIndex = index4;
return 4;
}
if ((Zi8_814813FC(input[3], &mappedCharacter, &nestedScratch, workData) != 0) &&
(Zi8_81481E6C(&nestedIndexStorage, input + 4, mappedCharacter, 1, workData) != 0)) {
*resultIndex = index3;
return 3;
}
*resultIndex = index4;
return 4;
}

View File

@@ -0,0 +1,53 @@
#ifndef PF_FA_PDM_H
#define PF_FA_PDM_H
#include <private/vf/PrFILE2/dskmng/pdm_types.h>
typedef struct PDM_PARTITION PDM_PARTITION;
typedef struct PDM_CALLBACK {
void (*insert)(PDM_PARTITION*);
void (*eject)(PDM_PARTITION*);
} PDM_CALLBACK;
struct PDM_PARTITION {
pf_u32 status;
PDM_DISK* p_disk;
pf_u32 part_id;
pf_u32 start_sector;
pf_u32 total_sector;
pf_s32 driver_last_error;
pf_u32 lock_state[2];
PDM_CALLBACK callbacks;
};
struct PDM_DISK {
pf_u32 status;
PDM_DISK_TBL disk_tbl;
pf_s16 init_count;
pf_s16 mount_count;
PDM_DISK* lock_handle;
pf_u32 lock_count;
PDM_DISK_INFO disk_info;
PDM_PARTITION* p_cur_part;
};
typedef struct PDM_DISK_SET {
pf_u16 num_partition;
pf_u16 num_allocated_disk;
PDM_DISK disk[26];
PDM_PARTITION partition[26];
} PDM_DISK_SET;
extern PDM_DISK_SET pdm_disk_set;
extern PDM_DISK_TBL pdm_drv_tbl[26];
void pdm_part_set_driver_error_code(PDM_PARTITION*, pf_s32);
void pdm_part_set_change_media_state(PDM_DISK*, pf_bool);
pf_s32 pdm_disk_convert_sector_into_block(PDM_DISK*, pf_u32, pf_u32, pf_u32, pf_u32*, pf_u32*);
pf_s32 pdm_disk_convert_block_into_sector(PDM_DISK*, pf_u32, pf_u32, pf_u32, pf_u32*, pf_u32*);
pf_s32 pdm_disk_add_disk(PDM_INIT_DISK*, PDM_DISK**);
pf_s32 pdm_disk_del_disk(PDM_DISK*);
pf_s32 pdm_disk_set_disk(PDM_DISK*, PDM_PARTITION*);
pf_s32 pdm_disk_get_media_attribute(PDM_DISK*, PDM_DISK_INFO*);
pf_s32 pdm_disk_get_media_bps(PDM_DISK*, pf_u16*);
pf_s32 pdm_disk_init(PDM_DISK*);
pf_s32 pdm_disk_mount(PDM_DISK*);
pf_s32 pdm_disk_format(PDM_DISK*, const pf_u8*);
pf_s32 pdm_disk_physical_read(PDM_DISK*, pf_u8*, pf_u32, pf_u32, pf_u32, pf_u32*);
pf_s32 pdm_disk_physical_write(PDM_DISK*, const pf_u8*, pf_u32, pf_u32, pf_u32, pf_u32*);
pf_s32 pdm_disk_unmount(PDM_DISK*, pf_u32);
pf_s32 pdm_disk_finalize(PDM_DISK*);
#endif

View File

@@ -0,0 +1,17 @@
#ifndef PF_FA_SYSTEM_LAYOUT_H
#define PF_FA_SYSTEM_LAYOUT_H
#include <revolution/os.h>
typedef struct PFSYS_SYSTEM_SET {
u32 initialized;
s32 task_id;
s32 mailbox_id;
u8 task_stack[0x2000];
OSThread task;
OSMessageQueue mailbox;
OSMessage messages[20];
u32 flock_count;
} PFSYS_SYSTEM_SET;
extern PFSYS_SYSTEM_SET pf_sys_set;
#endif

View File

@@ -0,0 +1,96 @@
#ifndef PF_FA_VOLUME_LAYOUT_H
#define PF_FA_VOLUME_LAYOUT_H
#define PRFILE2_VFMOD_PF_VOLUME_H
#include <private/vf/PrFILE2/fatfs/pf_entry.h>
#include <private/vf/PrFILE2/driver/pf_driver.h>
#include <private/vf/PrFILE2/fatfs/pf_devinf.h>
typedef struct PF_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)(const pf_s8, pf_bool);
pf_s32 (*unicode_char_width)(const pf_u16*);
pf_bool (*is_unicode_mb_char)(const pf_u16, pf_bool);
} PF_CHARCODE;
typedef struct PF_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_FAT_TYPE 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;
} PF_BPB;
typedef struct PF_CUR_DIR {
pf_u32 stat;
pf_s32 context_id;
PF_DIR_ENT directory;
} PF_CUR_DIR;
typedef pf_s32 (*PF_VOLUME_CB)(pf_s32);
struct PF_VOLUME {
PF_BPB bpb;
pf_u32 num_free_clusters;
pf_u32 last_free_cluster;
pf_u8 file_and_directory_state[0x1624 - 0x40];
PF_SECTOR_CACHE cache;
pf_s8 label[12];
PF_CUR_DIR current_dir[4];
struct {
pf_u32 tracker_size;
pf_u32 tracker_max;
pf_u32* tracker_bits;
} tail_entry;
pf_s32 last_error;
pf_s32 last_driver_error;
pf_u32 file_config;
pf_u16 flags;
pf_s8 drv_char;
pf_u16 fsi_flag;
PF_CLUSTER_LINK_VOL cluster_link;
void* p_part;
void (*p_callback)();
const pf_u8* format_param;
};
typedef struct PF_FA_CUR_VOLUME {
pf_u32 stat;
pf_s32 context_id;
PF_VOLUME* p_vol;
} PF_FA_CUR_VOLUME;
typedef struct PF_VOLUME_SET {
pf_u32 flags;
pf_u32 reserved;
PF_VOLUME* current_volume;
PF_FA_CUR_VOLUME context_volumes[3];
pf_s32 num_attached_drives;
pf_s32 num_mounted_volumes;
pf_u32 config;
void* param;
pf_s32 last_error;
pf_s32 last_driver_error;
PF_CHARCODE codeset;
pf_u32 setting;
pf_s32 context_id;
pf_u32 context_state[2];
struct { pf_u32 stat; pf_s32 context_id; } contexts[3];
PF_VOLUME volumes[26];
} PF_VOLUME_SET;
extern PF_VOLUME_SET pf_vol_set;
#endif

View File

@@ -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

View File

@@ -0,0 +1,535 @@
#include <private/fa/pdm.h>
#include <revolution/nand.h>
#include <revolution/types.h>
extern void* pf_memset(void*, u8, u32);
extern void* pf_memcpy(void*, const void*, u32);
extern s32 pf_strcmp(const char*, const char*);
extern char* pf_strcpy(char*, const char*);
extern u32 pf_strlen(const char*);
extern void pdm_disk_notify_media_insert(PDM_DISK*);
typedef struct NAND_DISK_INFO {
PDM_DISK* disk;
char path[80];
u32 file_size;
NANDFileInfo file;
u32 flags;
u32 reserved_sectors;
s32 last_error;
} NAND_DISK_INFO;
typedef struct NAND_SEMAPHORE { s32 count; s32 maximum; void* object; } NAND_SEMAPHORE;
extern s32 pfk_create_semaphore(NAND_SEMAPHORE*);
extern void pfk_get_semaphore(s32);
extern void pfk_release_semaphore(s32);
char NAND_Org_Path[64];
NAND_DISK_INFO nanddisk_info[23];
NAND_SEMAPHORE csem;
NAND_SEMAPHORE osem;
s32 Nanddisk_Internal_Info_Init;
s32 NAND_Init;
s32 fa_nanad_semid;
static inline s32 find_disk(PDM_DISK* disk, NAND_DISK_INFO** result) {
NAND_DISK_INFO* info;
u16 index;
for (index = 0; index < 23; index++) {
info = &nanddisk_info[index];
if (info->disk == disk) { *result = info; break; }
}
return index == 23 ? -22 : 0;
}
static inline s32 set_disk_error(PDM_DISK* disk, s32 error) {
u16 index;
for (index = 0; index < 23; index++) {
if (nanddisk_info[index].disk == disk) { nanddisk_info[index].last_error = error; break; }
}
return index == 23 ? -22 : 0;
}
static inline void store_disk_error(PDM_DISK* disk, s32 error) {
u16 index;
for (index = 0; index < 23; index++) {
if (nanddisk_info[index].disk == disk) { nanddisk_info[index].last_error = error; break; }
}
}
static inline NAND_DISK_INFO* find_unmounted_disk(PDM_DISK* disk) {
u16 index;
NAND_DISK_INFO* info;
for (index = 0; index < 23; index++) {
info = &nanddisk_info[index];
if (info->disk == disk) { if (!(info->flags & 2)) { return info; } }
}
for (index = 0; index < 23; index++) {
info = &nanddisk_info[index];
if (info->disk == 0) { if (info->path[0] != 0) { return info; } }
}
return 0;
}
static inline u16 read_u16(u8* buf, u32 offset) {
if ((u32)&buf[offset] & 1) { return (buf[offset + 1] << 8) | buf[offset]; }
return PF_SWAP_16(*(u16*)&buf[(offset + 1) & ~1]);
}
static inline void write_u16(u8* buf, u32 offset, u16 value) {
if ((u32)&buf[offset] & 1) { buf[offset] = value; buf[offset + 1] = value >> 8; }
else { *(u16*)&buf[(offset + 1) & ~1] = PF_SWAP_16(value); }
}
static inline void write_u32(u8* buf, u32 offset, u32 value) {
if ((u32)&buf[offset] & 3) { buf[offset] = value; buf[offset + 1] = value >> 8; buf[offset + 2] = value >> 16; buf[offset + 3] = value >> 24; }
else { *(u32*)&buf[offset] = PF_SWAP_32(value); }
}
static s32 fa_nanddrv_CreateNANDFileForDsk(NAND_DISK_INFO*);
static s32 fa_nanddrv_ParseCreateNANDFile(NAND_DISK_INFO*);
static s32 fa_nanddrv_VerifyBPB(u8*, u32*);
static s32 fa_nanddrv_BuildUpFSInfoSector(u8*);
static s32 fa_nanddrv_BuildUpBootSector(NAND_DISK_INFO*, u8*, PDM_FAT_TYPE*, u32);
static s32 fa_nanddrv_physical_read(u32, u8*, u32, u32, u32*, PDM_DISK*);
static s32 fa_nanddrv_physical_write(u32, const u8*, u32, u32, u32*, PDM_DISK*);
static s32 fa_nanddrv_RelateNANDFileToDsk(PDM_DISK* disk, NAND_DISK_INFO* info, s32 format) {
s32 error = NANDChangeDir(NAND_Org_Path);
if (error != 0) { return error; }
if (info->flags & 4) { error = 0; }
else { error = NANDOpen(info->path, &info->file, 3); }
if (format) { error = -12; }
switch (error) {
case -12:
error = fa_nanddrv_CreateNANDFileForDsk(info);
if (error == 0) { info->disk = disk; }
break;
case 0:
info->disk = disk;
error = 0;
break;
}
return error;
}
static s32 fa_nanddrv_CreateNANDFileForDsk(NAND_DISK_INFO* info) {
u8 zeros[512] __attribute__((aligned(32)));
u8 boot[512] __attribute__((aligned(32)));
u8 fsinfo[512] __attribute__((aligned(32)));
PDM_FAT_TYPE type;
u32 clusters;
s32 error;
u32 remaining;
error = fa_nanddrv_ParseCreateNANDFile(info);
if (error != 0) { return error; }
pf_memset(boot, 0, 512);
clusters = 0;
fa_nanddrv_BuildUpBootSector(info, boot, &type, 0);
if (type != fa_nanddrv_VerifyBPB(boot, &clusters)) { fa_nanddrv_BuildUpBootSector(info, boot, &type, clusters); }
error = NANDWrite(&info->file, boot, 512);
if (error < 0) { NANDClose(&info->file); NANDDelete(info->path); return error; }
remaining = info->file_size - 512;
if (type == PDM_FAT_32) {
fa_nanddrv_BuildUpFSInfoSector(fsinfo);
error = NANDWrite(&info->file, fsinfo, 512);
if (error < 0) { NANDClose(&info->file); NANDDelete(info->path); return error; }
remaining -= 512;
}
pf_memset(zeros, 0, 512);
for (; remaining >= 512; remaining -= 512) {
error = NANDWrite(&info->file, zeros, 512);
if (error < 0) { NANDClose(&info->file); NANDDelete(info->path); return error; }
}
if (remaining) {
error = NANDWrite(&info->file, zeros, remaining);
if (error < 0) { NANDClose(&info->file); NANDDelete(info->path); return error; }
}
return 0;
}
static s32 fa_nanddrv_ParseCreateNANDFile(NAND_DISK_INFO* info) {
u16 length = 0;
char* path;
u16 position = 0;
char name[16];
char* next;
s32 error;
if (info->flags & 4) { return 0; }
path = info->path;
pf_memset(name, 0, 16);
next = name;
for (;;) {
switch (*path) {
case '/':
if (length == 0) {
if (position == 0) { error = NANDChangeDir("/"); if (error != 0) { return error; } }
path++;
break;
}
if (path[1] == 0) {
if (length > 12) { return -20; }
error = NANDCreate(name, 0x30, 0);
if (error == 0 || error == -6) {
NANDOpen(name, &info->file, 3);
error = NANDChangeDir(NAND_Org_Path);
}
return error;
}
if (length > 11) { return -20; }
if (pf_strcmp(name, "..") != 0) { error = NANDCreateDir(name, 0x30, 0); }
else { error = 0; }
if (error == 0 || error == -6 || error == -1) {
error = NANDChangeDir(name);
if (error != 0) { return error; }
path++;
pf_memset(name, 0, 16);
next = name;
length = 0;
break;
}
return error;
case 0:
if (length > 12) { return -20; }
error = NANDCreate(name, 0x30, 0);
if (error == 0 || error == -6) {
NANDOpen(name, &info->file, 3);
error = NANDChangeDir(NAND_Org_Path);
}
return error;
}
*next = *path;
length++;
position++;
path++;
next++;
}
}
static s32 fa_nanddrv_VerifyBPB(u8* buf, u32* clusters) {
u8 sector_log = 0;
u8 cluster_log;
u16 value = 512;
u32 root;
u32 fat;
u32 total;
u16 root_sectors;
PDM_FAT_TYPE result;
u32 first;
while ((value >>= 1) != 0) { sector_log++; }
cluster_log = 0;
value = 1;
while ((value >>= 1) != 0) { cluster_log++; }
if ((u32)&buf[17] & 1) { root = (buf[18] << 8) | buf[17]; }
else { root = PF_SWAP_16(*(u16*)&buf[18]) << 5; }
root_sectors = (s32)(root + 511) >> sector_log;
fat = read_u16(buf, 22);
if (fat == 0) { fat = PF_SWAP_32(*(u32*)&buf[36]); }
first = root_sectors + fat * 2 + 1;
if ((u32)&buf[19] & 1) { total = (buf[20] << 8) | buf[19]; }
else { total = PF_SWAP_16(*(u16*)&buf[20]); }
if (total == 0) { total = PF_SWAP_32(*(u32*)&buf[32]); }
*clusters = total - first;
total = (u32)(total - first) >> cluster_log;
if (total < 4085) { return 0; }
result = PDM_FAT_32;
if ((u32)total < 65525) { result = PDM_FAT_16; }
return result;
}
#pragma dont_inline on
static s32 fa_nanddrv_BuildUpFSInfoSector(u8* buf) {
pf_memset(buf, 0, 512);
if ((u32)&buf[0] & 3) { buf[0] = 0x52; buf[1] = 0x52; buf[2] = 0x61; buf[3] = 0x41; }
else { *(u32*)&buf[0] = 0x52526141; }
if ((u32)&buf[484] & 3) { buf[484] = 0x72; buf[485] = 0x72; buf[486] = 0x41; buf[487] = 0x61; }
else { *(u32*)&buf[484] = 0x72724161; }
if ((u32)&buf[488] & 3) { buf[488] = 0xFF; buf[489] = 0xFF; buf[490] = 0xFF; buf[491] = 0xFF; }
else { *(u32*)&buf[488] = 0xFFFFFFFF; }
if ((u32)&buf[492] & 3) { buf[492] = 0xFF; buf[493] = 0xFF; buf[494] = 0xFF; buf[495] = 0xFF; }
else { *(u32*)&buf[492] = 0xFFFFFFFF; }
if ((u32)&buf[508] & 3) { buf[508] = 0x00; buf[509] = 0x00; buf[510] = 0x55; buf[511] = 0xAA; }
else { *(u32*)&buf[508] = 0x000055AA; }
return 0;
}
#pragma dont_inline reset
static s32 fa_nanddrv_BuildUpBootSector(NAND_DISK_INFO* info, u8* buf, PDM_FAT_TYPE* type, u32 clusters) {
u32 total;
u32 fat_sectors;
PDM_FAT_TYPE fat_type;
total = clusters ? clusters : info->file_size >> 9;
if (total < 4085) { fat_type = PDM_FAT_12; fat_sectors = (((total * 3) >> 1) + 511) >> 9; }
else if (total < 65525) { fat_type = PDM_FAT_16; fat_sectors = (total * 2 + 511) >> 9; }
else { fat_type = PDM_FAT_32; fat_sectors = (total * 4 + 511) >> 9; }
pf_memset(buf, 0, 512);
buf[0] = 0xEB; buf[2] = 0x90; buf[510] = 0x55; buf[511] = 0xAA;
write_u16(buf, 24, 63);
write_u16(buf, 26, 255);
write_u16(buf, 11, 512);
buf[13] = 1;
write_u16(buf, 14, 1);
buf[16] = 2;
write_u16(buf, 17, 128);
buf[21] = 0xF0;
if (total < 65536) { write_u16(buf, 19, total); write_u32(buf, 32, 0); }
else { write_u16(buf, 19, 0); write_u32(buf, 32, total); }
if (fat_type == PDM_FAT_32) {
write_u16(buf, 17, 0);
write_u32(buf, 36, fat_sectors);
write_u16(buf, 40, 0); write_u16(buf, 42, 0);
write_u32(buf, 44, 2); write_u16(buf, 48, 1);
buf[65] = 0; buf[66] = 0x29;
if ((u32)&buf[67] & 3) { buf[67] = 0x34; buf[68] = 0x12; buf[69] = 0; buf[70] = 0; }
else { *(u32*)&buf[76] = 0x34120000; }
} else {
write_u16(buf, 17, 128); write_u16(buf, 22, fat_sectors);
buf[37] = 0; buf[38] = 0x29;
if ((u32)&buf[39] & 3) { buf[39] = 0x34; buf[40] = 0x12; buf[41] = 0; buf[42] = 0; }
else { *(u32*)&buf[48] = 0x34120000; }
}
*type = fat_type;
return 0;
}
s32 fa_nanddrv_init(PDM_DISK* disk) {
if (disk == 0) { return -20; }
if (NAND_Init == 0) {
if (NANDInit() != 0) { return -21; }
if (NANDGetCurrentDir(NAND_Org_Path) != 0) { return -21; }
NAND_Init++;
}
pdm_disk_notify_media_insert(disk);
return 0;
}
s32 fa_nanddrv_mount(PDM_DISK* disk) {
NAND_DISK_INFO* info;
NAND_DISK_INFO* mounted;
s32 error;
pfk_get_semaphore(fa_nanad_semid);
if (disk == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
if (find_disk(disk, &mounted) == 0 && (mounted->flags & 2)) { pfk_release_semaphore(fa_nanad_semid); return -21; }
info = find_unmounted_disk(disk);
if (info == 0) { pfk_release_semaphore(fa_nanad_semid); return -22; }
if (info->disk != 0) { error = 0; }
else { error = fa_nanddrv_RelateNANDFileToDsk(disk, info, 0); }
if (error == 0) { info->flags |= 2; }
pfk_release_semaphore(fa_nanad_semid);
return error;
}
s32 fa_nanddrv_format(PDM_DISK* disk, const u8* param) {
NAND_DISK_INFO* info = 0;
s32 error;
pfk_get_semaphore(fa_nanad_semid);
if (disk == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
if (find_disk(disk, &info) != 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
info->flags |= 4;
error = fa_nanddrv_RelateNANDFileToDsk(disk, info, 1);
info->flags &= ~4;
pfk_release_semaphore(fa_nanad_semid);
return error;
}
s32 fa_nanddrv_pread(PDM_DISK* disk, u8* buf, u32 block, u32 count, u32* success) {
s32 error;
pfk_get_semaphore(fa_nanad_semid);
*success = 0;
if (disk == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
if (buf == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
error = fa_nanddrv_physical_read(count, buf, block, 512, success, disk);
if (error != 0) { pfk_release_semaphore(fa_nanad_semid); return error; }
pfk_release_semaphore(fa_nanad_semid);
return 0;
}
s32 fa_nanddrv_pwrite(PDM_DISK* disk, const u8* buf, u32 block, u32 count, u32* success) {
s32 error;
pfk_get_semaphore(fa_nanad_semid);
*success = 0;
if (disk == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
if (buf == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
error = fa_nanddrv_physical_write(count, buf, block, 512, success, disk);
if (error != 0) { pfk_release_semaphore(fa_nanad_semid); return error; }
pfk_release_semaphore(fa_nanad_semid);
return 0;
}
s32 fa_nanddrv_unmount(PDM_DISK* disk) {
NAND_DISK_INFO* info = 0;
u32 position;
s32 error;
s32 result;
pfk_get_semaphore(fa_nanad_semid);
if (disk == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
error = set_disk_error(disk, 0);
if (error == 0) {
if (find_disk(disk, &info) != 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
info->flags &= ~2;
error = NANDTell(&info->file, &position);
if (error != 0) { result = error; goto flush_done; }
error = NANDClose(&info->file);
if (error < 0) { result = error; goto flush_done; }
error = NANDOpen(info->path, &info->file, 3);
if (error < 0) { result = error; goto flush_done; }
error = NANDSeek(&info->file, position, 0);
result = error < 0 ? error : 0;
flush_done:
error = result;
if (error < 0) { set_disk_error(disk, error); pfk_release_semaphore(fa_nanad_semid); return error; }
}
pfk_release_semaphore(fa_nanad_semid);
return error;
}
s32 fa_nanddrv_finalize(PDM_DISK* disk) {
NAND_DISK_INFO* info;
s32 error = 0;
u16 index;
pfk_get_semaphore(fa_nanad_semid);
if (disk == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
for (index = 0; index < 23; index++) {
info = &nanddisk_info[index];
if (info->disk == disk) {
error = NANDClose(&info->file);
pf_memset(info, 0, sizeof(*info));
break;
}
}
pfk_release_semaphore(fa_nanad_semid);
if (error != 0) { return -20; }
return index == 23 ? -22 : 0;
}
s32 fa_nanddrv_get_disk_info(PDM_DISK* disk, PDM_DISK_INFO* disk_info) {
NAND_DISK_INFO* info = 0;
pfk_get_semaphore(fa_nanad_semid);
if (disk == 0 || disk_info == 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
if (find_disk(disk, &info) != 0) { pfk_release_semaphore(fa_nanad_semid); return -20; }
disk_info->total_sectors = info->file_size >> 9;
disk_info->cylinders = disk_info->total_sectors / 255 / 63 / 512;
disk_info->heads = 255;
disk_info->sectors_per_track = 63;
disk_info->bytes_per_sector = 512;
disk_info->media_attr = 0;
disk_info->format_param = 0;
pfk_release_semaphore(fa_nanad_semid);
return 0;
}
const PDM_FUNCTBL fa_nand_func = {
fa_nanddrv_init, fa_nanddrv_finalize, fa_nanddrv_mount, fa_nanddrv_unmount,
fa_nanddrv_format, fa_nanddrv_pread, fa_nanddrv_pwrite, fa_nanddrv_get_disk_info
};
s32 fa_nanddrv_init_drv_tbl(PDM_DISK_TBL* table, u32 extension) {
table->ui_ext = extension;
table->p_func = (PDM_FUNCTBL*)&fa_nand_func;
return 0;
}
s32 fa_nanddrv_NotifyNANDFile(const char* path, u32 size) {
NAND_DISK_INFO* info;
u16 index;
if (pf_strlen(path) >= 76) { return -20; }
if (Nanddisk_Internal_Info_Init == 0) {
pf_memset(nanddisk_info, 0, sizeof(nanddisk_info));
Nanddisk_Internal_Info_Init++;
csem.count = 1;
csem.maximum = 1;
csem.object = &osem;
fa_nanad_semid = pfk_create_semaphore(&csem);
if (fa_nanad_semid == 0) { return -21; }
}
for (index = 0; index < 23; index++) {
info = &nanddisk_info[index];
if (pf_strcmp(info->path, path) == 0) { return 0; }
if (nanddisk_info[index].disk == 0) {
pf_strcpy(info->path, path);
info->file_size = size;
break;
}
}
return index == 23 ? -22 : 0;
}
static s32 fa_nanddrv_physical_read(u32 count, u8* buf, u32 block, u32 bps, u32* success, PDM_DISK* disk) {
u32 file_size;
u32 wanted;
u32 remaining;
s32 error;
NAND_DISK_INFO* info = 0;
u16 index;
u32 offset;
u32 position;
u8 work[512] __attribute__((aligned(32)));
for (index = 0; index < 23; index++) {
if (nanddisk_info[index].disk == disk) { info = &nanddisk_info[index]; break; }
}
if ((index == 23 ? -22 : 0) != 0) { return -20; }
remaining = count * bps;
file_size = info->file_size;
wanted = block * bps;
if (NANDTell(&info->file, &position) != 0 || position != wanted) { error = NANDSeek(&info->file, wanted, 0); }
else { error = 0; }
if (error >= 0) {
if (wanted + remaining > file_size) {
remaining = file_size - wanted;
offset = 0;
while (remaining >= 512) {
error = NANDRead(&info->file, work, 512);
if (error < 0) { return -22; }
pf_memcpy(buf + offset, work, error);
offset += error; remaining -= error;
}
if (remaining) {
error = NANDRead(&info->file, work, remaining);
if (error < 0) { return -22; }
pf_memcpy(buf + offset, work, error);
}
return -22;
}
offset = 0;
while (remaining >= 512) {
error = NANDRead(&info->file, work, 512);
if (error < 0) { store_disk_error(disk, error); return error; }
pf_memcpy(buf + offset, work, error);
offset += error; remaining -= error;
}
if (remaining) {
error = NANDRead(&info->file, work, remaining);
if (error < 0) { store_disk_error(disk, error); return error; }
pf_memcpy(buf + offset, work, error);
}
*success = count;
return 0;
}
store_disk_error(disk, error);
return error;
}
static s32 fa_nanddrv_physical_write(u32 count, const u8* buf, u32 block, u32 bps, u32* success, PDM_DISK* disk) {
u32 remaining;
u32 wanted;
u32 file_size;
NAND_DISK_INFO* info = 0;
u16 index;
u32 offset;
u32 position;
s32 error;
u8 work[512] __attribute__((aligned(32)));
for (index = 0; index < 23; index++) {
if (nanddisk_info[index].disk == disk) { info = &nanddisk_info[index]; break; }
}
if ((index == 23 ? -22 : 0) != 0) { return -20; }
remaining = count * bps;
file_size = info->file_size;
wanted = block * bps;
if (NANDTell(&info->file, &position) != 0 || position != wanted) { error = NANDSeek(&info->file, wanted, 0); }
else { error = 0; }
if (error >= 0) {
if (wanted + remaining > file_size) {
remaining = file_size - wanted;
offset = 0;
while (remaining >= 512) {
pf_memcpy(work, buf + offset, 512);
error = NANDWrite(&info->file, work, 512);
if (error < 0) { return -22; }
remaining -= error; offset += error;
}
if (remaining) {
pf_memcpy(work, buf + offset, remaining);
error = NANDWrite(&info->file, work, remaining);
}
return -22;
}
offset = 0;
while (remaining >= 512) {
pf_memcpy(work, buf + offset, 512);
error = NANDWrite(&info->file, work, 512);
if (error < 0) { store_disk_error(disk, error); return error; }
remaining -= error; offset += error;
}
if (remaining) {
pf_memcpy(work, buf + offset, remaining);
error = NANDWrite(&info->file, work, remaining);
if (error < 0) { store_disk_error(disk, error); return error; }
}
*success = count;
return 0;
}
store_disk_error(disk, error);
return error;
}

View File

@@ -0,0 +1,99 @@
#define PF_FA_STR_LAYOUT
#include <private/fa/pf_volume.h>
#include <private/vf/PrFILE2/dskmng/pdm_bpb.h>
extern pf_bool pdm_part_is_boot_sector(pf_u8*);
static inline pf_u16 read_boot_u16(pf_u8* buf, pf_u32 offset) {
if ((pf_u32)&buf[offset] & 1) {
return (buf[offset + 1] << 8) | buf[offset];
}
return PF_SWAP_16(*(pf_u16*)&buf[(offset + 1) & ~1]);
}
void pdm_bpb_CalcBPBFields(PF_VOLUME* p_vol) {
pf_u32 num_data_sectors;
pf_u16 val;
p_vol->bpb.log2_bytes_per_sector = 0;
val = p_vol->bpb.bytes_per_sector;
while (val >>= 1) { p_vol->bpb.log2_bytes_per_sector++; }
p_vol->bpb.log2_sectors_per_cluster = 0;
val = p_vol->bpb.sectors_per_cluster;
while (val >>= 1) { p_vol->bpb.log2_sectors_per_cluster++; }
p_vol->bpb.num_root_dir_sectors = ((p_vol->bpb.num_root_dir_entries << 5) + (p_vol->bpb.bytes_per_sector - 1)) >> p_vol->bpb.log2_bytes_per_sector;
p_vol->bpb.first_data_sector = (p_vol->bpb.num_FATs * p_vol->bpb.sectors_per_FAT) + (p_vol->bpb.num_root_dir_sectors + p_vol->bpb.num_reserved_sectors);
num_data_sectors = p_vol->bpb.total_sectors - p_vol->bpb.first_data_sector;
p_vol->bpb.num_clusters = num_data_sectors >> p_vol->bpb.log2_sectors_per_cluster;
if (p_vol->bpb.num_clusters < 0xFF5) {
p_vol->bpb.fat_type = FAT_12;
p_vol->bpb.first_root_dir_sector = p_vol->bpb.num_reserved_sectors + p_vol->bpb.num_FATs * p_vol->bpb.sectors_per_FAT;
} else if (p_vol->bpb.num_clusters < 0xFFF5) {
p_vol->bpb.fat_type = FAT_16;
p_vol->bpb.first_root_dir_sector = p_vol->bpb.num_reserved_sectors + p_vol->bpb.num_FATs * p_vol->bpb.sectors_per_FAT;
} else {
p_vol->bpb.fat_type = FAT_32;
p_vol->bpb.first_root_dir_sector = 0;
}
}
pf_s32 pdm_bpb_InitVolumeWithBootSector(PF_VOLUME* p_vol, pf_u8* buf) {
pf_u32 total_sectors;
pf_s32 err = 0;
pf_u32 fat_sectors;
pf_u32 version;
if (!pdm_part_is_boot_sector(buf)) {
err = 3;
} else {
p_vol->bpb.bytes_per_sector = read_boot_u16(buf, 11);
p_vol->bpb.sectors_per_cluster = buf[13];
p_vol->bpb.num_reserved_sectors = read_boot_u16(buf, 14);
p_vol->bpb.num_FATs = buf[16];
p_vol->bpb.num_root_dir_entries = read_boot_u16(buf, 17);
p_vol->bpb.media = buf[21];
total_sectors = read_boot_u16(buf, 19);
p_vol->bpb.total_sectors = total_sectors == 0 ? PF_SWAP_32(*(pf_u32*)&buf[32]) : total_sectors;
fat_sectors = read_boot_u16(buf, 22);
p_vol->bpb.sectors_per_FAT = fat_sectors == 0 ? PF_SWAP_32(*(pf_u32*)&buf[36]) : fat_sectors;
pdm_bpb_CalcBPBFields(p_vol);
switch (p_vol->bpb.fat_type) {
case FAT_12:
case FAT_16:
if (fat_sectors == 0) { err = 4; }
break;
case FAT_32:
if (total_sectors != 0 || fat_sectors != 0) { err = 4; }
version = read_boot_u16(buf, 42);
p_vol->bpb.ext_flags = read_boot_u16(buf, 40);
p_vol->bpb.root_dir_cluster = PF_SWAP_32(*(pf_u32*)&buf[44]);
p_vol->bpb.fs_info_sector = read_boot_u16(buf, 48);
p_vol->bpb.backup_boot_sector = read_boot_u16(buf, 50);
p_vol->bpb.first_root_dir_sector = p_vol->bpb.first_data_sector + ((p_vol->bpb.root_dir_cluster - 2) << p_vol->bpb.log2_sectors_per_cluster);
if (version != 0) { err = 4; }
break;
default:
err = 4;
break;
}
if (p_vol->bpb.ext_flags & 0x80) {
p_vol->bpb.num_active_FATs = 1;
p_vol->bpb.active_FAT_sector = p_vol->bpb.num_reserved_sectors + ((p_vol->bpb.ext_flags & 7) * p_vol->bpb.sectors_per_FAT);
} else {
p_vol->bpb.num_active_FATs = p_vol->bpb.num_FATs;
p_vol->bpb.active_FAT_sector = p_vol->bpb.num_reserved_sectors;
}
}
return err;
}
pf_s32 pdm_bpb_InitVolumeWithFSINFOSector(PF_VOLUME* p_vol, pf_u8* buf, pf_u32* p_free_count, pf_u32* p_next_free) {
pf_u32 free_count;
pf_u32 next_free;
*p_free_count = -1;
*p_next_free = -1;
if (PF_SWAP_32(*(pf_u32*)&buf[0]) == 0x41615252 && PF_SWAP_32(*(pf_u32*)&buf[484]) == 0x61417272 && PF_SWAP_32(*(pf_u32*)&buf[508]) == 0xAA550000) {
free_count = PF_SWAP_32(*(pf_u32*)&buf[488]);
next_free = PF_SWAP_32(*(pf_u32*)&buf[492]);
if (free_count >= 2 && free_count < p_vol->bpb.num_clusters + 2) { *p_free_count = free_count; }
if (next_free >= 2 && next_free < p_vol->bpb.num_clusters + 2) { *p_next_free = next_free; }
}
return 0;
}

View File

@@ -0,0 +1,161 @@
#include <private/fa/pdm.h>
extern void* pf_memset(void*, pf_u8, pf_u32);
PDM_DISK_SET pdm_disk_set;
PDM_DISK_TBL pdm_drv_tbl[26];
pf_s32 pdm_disk_convert_sector_into_block(PDM_DISK* p_disk, pf_u32 start, pf_u32 count, pf_u32 bytes_per_sector, pf_u32* p_start, pf_u32* p_count) {
pf_u32 ratio;
pf_s32 err = 0;
*p_start = start;
*p_count = count;
if (bytes_per_sector > 512) {
ratio = (pf_u16)bytes_per_sector >> 9;
if (ratio == 2) { *p_start <<= 1; }
else if (ratio == 4) { *p_start <<= 2; }
else if (ratio == 8) { *p_start <<= 3; }
if (ratio == 2) { *p_count <<= 1; }
else if (ratio == 4) { *p_count <<= 2; }
else if (ratio == 8) { *p_count <<= 3; }
} else if (bytes_per_sector < 512) { err = 4; }
return err;
}
pf_s32 pdm_disk_convert_block_into_sector(PDM_DISK* p_disk, pf_u32 start, pf_u32 count, pf_u32 bytes_per_sector, pf_u32* p_start, pf_u32* p_count) {
pf_u32 ratio;
pf_s32 err = 0;
*p_start = start;
*p_count = count;
if (bytes_per_sector > 512) {
ratio = (pf_u16)bytes_per_sector >> 9;
if (ratio == 2) { *p_start >>= 1; }
else if (ratio == 4) { *p_start >>= 2; }
else if (ratio == 8) { *p_start >>= 3; }
if (ratio == 2) { *p_count >>= 1; }
else if (ratio == 4) { *p_count >>= 2; }
else if (ratio == 8) { *p_count >>= 3; }
} else if (bytes_per_sector < 512) { err = 4; }
return err;
}
pf_s32 pdm_disk_init_disk_manager(void) {
pf_memset(&pdm_disk_set, 0, sizeof(pdm_disk_set));
return 0;
}
pf_s32 pdm_disk_add_disk(PDM_INIT_DISK* p_init_disk_tbl, PDM_DISK** pp_disk) {
PDM_DISK_TBL* p_driver;
pf_u16 disk_no;
PDM_DISK* p_disk;
*pp_disk = PF_NULL;
if (pdm_disk_set.num_allocated_disk >= 26) { return 8; }
for (disk_no = 0; disk_no < 26; disk_no++) {
if (!(pdm_disk_set.disk[disk_no].status & 1)) { break; }
}
if (disk_no >= 26) { return 8; }
p_driver = &pdm_drv_tbl[disk_no];
p_init_disk_tbl->p_func(p_driver, p_init_disk_tbl->ui_ext);
p_disk = &pdm_disk_set.disk[disk_no];
p_disk->disk_tbl = *p_driver;
p_disk->status |= 1;
pdm_disk_set.num_allocated_disk++;
*pp_disk = p_disk;
return 0;
}
pf_s32 pdm_disk_del_disk(PDM_DISK* p_disk) {
if (p_disk->init_count != 0) { return 16; }
if (p_disk->mount_count != 0) { return 17; }
p_disk->status &= ~1;
pdm_disk_set.num_allocated_disk--;
return 0;
}
pf_s32 pdm_disk_set_disk(PDM_DISK* p_disk, PDM_PARTITION* p_part) {
p_disk->p_cur_part = p_part;
return 0;
}
pf_s32 pdm_disk_get_media_attribute(PDM_DISK* p_disk, PDM_DISK_INFO* p_info) {
*p_info = p_disk->disk_info;
return 0;
}
pf_s32 pdm_disk_get_media_bps(PDM_DISK* p_disk, pf_u16* p_bps) {
*p_bps = p_disk->disk_info.bytes_per_sector;
return 0;
}
pf_s32 pdm_disk_init(PDM_DISK* p_disk) {
pf_s32 err;
if (p_disk->init_count == 0) {
err = p_disk->disk_tbl.p_func->init(p_disk);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); return 21; }
}
p_disk->init_count++;
return 0;
}
pf_s32 pdm_disk_mount(PDM_DISK* p_disk) {
pf_s32 err;
if (p_disk->mount_count == 0) {
err = p_disk->disk_tbl.p_func->mount(p_disk);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); return 21; }
err = p_disk->disk_tbl.p_func->get_disk_info(p_disk, &p_disk->disk_info);
if (err != 0) {
pdm_part_set_driver_error_code(p_disk->p_cur_part, err);
p_disk->disk_tbl.p_func->unmount(p_disk);
return 21;
}
if (p_disk->disk_info.media_attr & 1) { p_disk->status |= 2; }
else { p_disk->status &= ~2; }
}
p_disk->mount_count++;
return 0;
}
pf_s32 pdm_disk_format(PDM_DISK* p_disk, const pf_u8* param) {
pf_s32 err;
err = p_disk->disk_tbl.p_func->format(p_disk, param);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); return 21; }
return 0;
}
pf_s32 pdm_disk_physical_read(PDM_DISK* p_disk, pf_u8* buf, pf_u32 sector, pf_u32 count, pf_u32 bps, pf_u32* p_success) {
pf_s32 err;
pf_u32 block;
pf_u32 num_blocks;
pf_u32 converted_sector;
err = pdm_disk_convert_sector_into_block(p_disk, sector, count, bps, &block, &num_blocks);
if (err != 0) { return err; }
err = p_disk->disk_tbl.p_func->physical_read(p_disk, buf, block, num_blocks, p_success);
pdm_disk_convert_block_into_sector(p_disk, block, *p_success, bps, &converted_sector, p_success);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); return 21; }
return 0;
}
pf_s32 pdm_disk_physical_write(PDM_DISK* p_disk, const pf_u8* buf, pf_u32 sector, pf_u32 count, pf_u32 bps, pf_u32* p_success) {
pf_s32 err;
pf_u32 block;
pf_u32 num_blocks;
pf_u32 converted_sector;
err = pdm_disk_convert_sector_into_block(p_disk, sector, count, bps, &block, &num_blocks);
if (err != 0) { return err; }
err = p_disk->disk_tbl.p_func->physical_write(p_disk, buf, block, num_blocks, p_success);
pdm_disk_convert_block_into_sector(p_disk, block, *p_success, bps, &converted_sector, p_success);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); return 21; }
return 0;
}
pf_s32 pdm_disk_unmount(PDM_DISK* p_disk, pf_u32 mode) {
pf_s32 err = 0;
if (p_disk->mount_count == 1) {
err = p_disk->disk_tbl.p_func->unmount(p_disk);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); err = 21; }
} else if (p_disk->mount_count == 0) { return 14; }
if (err == 0 || mode == 1) { p_disk->mount_count--; }
return err;
}
pf_s32 pdm_disk_finalize(PDM_DISK* p_disk) {
pf_s32 err;
if (p_disk->init_count == 1) {
err = p_disk->disk_tbl.p_func->finalize(p_disk);
if (err != 0) { pdm_part_set_driver_error_code(p_disk->p_cur_part, err); return 21; }
} else if (p_disk->init_count == 0) { return 13; }
p_disk->init_count--;
return 0;
}
void pdm_disk_notify_media_eject(PDM_DISK* p_disk) {
p_disk->status &= ~4;
pdm_part_set_change_media_state(p_disk, 0);
}
void pdm_disk_notify_media_insert(PDM_DISK* p_disk) {
p_disk->status |= 4;
pdm_part_set_change_media_state(p_disk, 1);
}

View File

@@ -0,0 +1,287 @@
#include <private/fa/pdm.h>
#include <revolution/types.h>
#define MBR_WORD(buf, offset) (((pf_u32)(buf)[(offset) + 2] << 16) + (buf)[offset] + (((pf_u32)(buf)[(offset) + 3] << 24) + ((pf_u32)(buf)[(offset) + 1] << 8)))
static inline pf_u16 read_boot_u16(pf_u8* buf, pf_u32 offset) {
if ((pf_u32)&buf[offset] & 1) { return (buf[offset + 1] << 8) | buf[offset]; }
return PF_SWAP_16(*(pf_u16*)&buf[(offset + 1) & ~1]);
}
pf_s32 pdm_part_is_master_boot_sector(pf_u8* buf, pf_u32 total, pf_bool* p_is_mbr) {
pf_s16 index;
pf_u32 start[4];
pf_u32 count[4];
*p_is_mbr = 0;
if (buf[510] != 0x55 || buf[511] != 0xAA) { return 2; }
for (index = 0; index < 4; index++) {
start[index] = 0;
start[index] = (((pf_u32)buf[456] << 16) + buf[454]) + (((pf_u32)buf[457] << 24) + ((pf_u32)buf[455] << 8));
count[index] = (((pf_u32)buf[460] << 16) + buf[458]) + (((pf_u32)buf[461] << 24) + ((pf_u32)buf[459] << 8));
if (start[index] != 0 && count[index] != 0) {
if (index == 0) { *p_is_mbr = 1; }
} else {
if (index == 0) { return 2; }
}
buf += 16;
}
for (index = 0; index < 4; index++) {
if (start[index] + count[index] > total) {
if (index == 0) { *p_is_mbr = 0; }
return 2;
}
}
return 0;
}
pf_bool pdm_part_is_boot_sector(pf_u8* buf) {
pf_u16 byte_per_sector;
pf_u16 sector_per_cluster;
pf_u8 media;
pf_bool is_boot;
is_boot = PF_TRUE;
if ((buf[0x00] != 0xEB || buf[0x2] != 0x90) && buf[0x0] != 0xE9) {
is_boot = PF_FALSE;
}
if (buf[0x1FE] != 0x55 || buf[0x1FF] != 0xAA) {
is_boot = PF_FALSE;
}
byte_per_sector = read_boot_u16(buf, 0xB);
if (byte_per_sector != 0x200 && byte_per_sector != 0x400 && byte_per_sector != 0x800 && byte_per_sector != 0x1000) {
is_boot = PF_FALSE;
}
sector_per_cluster = buf[0xD];
if (sector_per_cluster != 1 && sector_per_cluster != 2 && sector_per_cluster != 4 && sector_per_cluster != 8 && sector_per_cluster != 0x10 &&
sector_per_cluster != 0x20 && sector_per_cluster != 0x40 && sector_per_cluster != 0x80) {
is_boot = PF_FALSE;
}
media = buf[0x15];
if (media != 0xF0 && media != 0xF8 && media != 0xF9 && media != 0xFA && media != 0xFB && media != 0xFC && media != 0xFD && media != 0xFE &&
media != 0xFF) {
is_boot = PF_FALSE;
}
return is_boot;
}
pf_s32 pdm_part_get_start_sector(PDM_PARTITION* p_part) {
pf_u32 part_index = 0;
pf_u32 requested = p_part->part_id;
pf_u32 start[4];
pf_u32 count[4];
pf_u16 index;
pf_u16 extended_index;
pf_u32 base;
pf_u32 sector;
pf_u32 length;
pf_bool is_mbr;
pf_u32 success;
pf_s32 err;
pf_u8 buf[512] __attribute__((aligned(32)));
p_part->start_sector = 0;
p_part->total_sector = p_part->p_disk->disk_info.total_sectors;
err = pdm_disk_physical_read(p_part->p_disk, buf, 0, 1, 512, &success);
if (err != 0) { return err; }
pdm_part_is_master_boot_sector(buf, p_part->p_disk->disk_info.total_sectors, &is_mbr);
if (is_mbr) {
start[0] = MBR_WORD(buf, 454);
start[1] = MBR_WORD(buf, 470);
start[2] = MBR_WORD(buf, 486);
start[3] = MBR_WORD(buf, 502);
count[0] = MBR_WORD(buf, 458);
count[1] = MBR_WORD(buf, 474);
count[2] = MBR_WORD(buf, 490);
count[3] = MBR_WORD(buf, 506);
part_index = 0;
for (index = 0; index < 4; index++) {
sector = start[index];
length = count[index];
if (sector == 0 || length == 0) { return 7; }
err = pdm_disk_physical_read(p_part->p_disk, buf, sector, 1, 512, &success);
if (err != 0) { return err; }
pdm_part_is_master_boot_sector(buf, p_part->p_disk->disk_info.total_sectors, &is_mbr);
if (is_mbr) {
base = start[index];
sector = base;
for (extended_index = 0; extended_index < 2; extended_index++) {
if (extended_index == 0) {
sector = sector + MBR_WORD(buf, 454);
length = MBR_WORD(buf, 458);
err = pdm_disk_physical_read(p_part->p_disk, buf, sector, 1, 512, &success);
if (err != 0) { return err; }
if (requested == part_index) { p_part->start_sector = sector; p_part->total_sector = length; return 0; }
part_index++;
} else {
sector = base + MBR_WORD(buf, 470);
length = MBR_WORD(buf, 474);
if (sector == 0 || length == 0) { break; }
err = pdm_disk_physical_read(p_part->p_disk, buf, sector, 1, 512, &success);
if (err != 0) { return err; }
pdm_part_is_master_boot_sector(buf, p_part->p_disk->disk_info.total_sectors, &is_mbr);
if (!is_mbr) { break; }
extended_index = 0;
}
}
} else {
if (requested == part_index) { p_part->start_sector = sector; p_part->total_sector = length; break; }
part_index++;
}
}
} else {
if (requested >= 2) { return 7; }
p_part->start_sector = part_index;
p_part->total_sector = p_part->p_disk->disk_info.total_sectors;
}
return 0;
}
pf_u32 pdm_part_chg_ltop(PDM_PARTITION* p_part, pf_u32 sector, pf_u32 bps) {
pf_u16 media_bps;
pf_u32 ratio;
pf_u32 start;
pdm_disk_get_media_bps(p_part->p_disk, &media_bps);
if (bps == media_bps) { return sector + p_part->start_sector; }
start = p_part->start_sector;
ratio = media_bps >> 9;
if (ratio == 2) { start <<= 1; }
else if (ratio == 4) { start <<= 2; }
else if (ratio == 8) { start <<= 3; }
ratio = (pf_u16)bps >> 9;
if (ratio == 2) { start >>= 1; }
else if (ratio == 4) { start >>= 2; }
else if (ratio == 8) { start >>= 3; }
return sector + start;
}
pf_s32 pdm_part_get_partition(PDM_DISK* p_disk, pf_u32 id, PDM_PARTITION** pp_part) {
pf_s32 err;
pf_u16 index;
*pp_part = PF_NULL;
if (pdm_disk_set.num_partition >= 26) { return 10; }
for (index = 0; index < 26; index++) {
if (!(pdm_disk_set.partition[index].status & 1)) { break; }
}
if (index == 26) { return 10; }
err = pdm_disk_set_disk(p_disk, &pdm_disk_set.partition[index]);
if (err != 0) { return err; }
pdm_disk_set.num_partition++;
pdm_disk_set.partition[index].status |= 1;
pdm_disk_set.partition[index].p_disk = p_disk;
pdm_disk_set.partition[index].part_id = id;
*pp_part = &pdm_disk_set.partition[index];
return 0;
}
pf_s32 pdm_part_release_partition(PDM_PARTITION* p_part) {
p_part->status &= ~1;
pdm_disk_set.num_partition--;
return 0;
}
pf_bool pdm_part_is_attached_partition(PDM_PARTITION* p_part) { return (p_part->status >> 2) & 1; }
void pdm_part_set_driver_error_code(PDM_PARTITION* p_part, pf_s32 err) { p_part->driver_last_error = err; }
pf_s32 pdm_part_get_driver_error_code(PDM_PARTITION* p_part) { return p_part->driver_last_error; }
pf_s32 pdm_part_get_media_attribute(PDM_PARTITION* p_part, PDM_DISK_INFO* p_info) {
pf_s32 err = pdm_disk_get_media_attribute(p_part->p_disk, p_info);
if (err != 0) { return err; }
return 0;
}
pf_s32 pdm_part_init(PDM_PARTITION* p_part) {
pf_s32 err;
if (!(p_part->status & 4)) {
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
err = pdm_disk_init(p_part->p_disk);
if (err != 0) { return err; }
} else { return 11; }
p_part->status |= 4;
return 0;
}
pf_s32 pdm_part_mount(PDM_PARTITION* p_part) {
pf_s32 err;
if (!(p_part->status & 8)) {
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
err = pdm_disk_mount(p_part->p_disk);
if (err != 0) { return err; }
err = pdm_part_get_start_sector(p_part);
if (err != 0) { pdm_disk_unmount(p_part->p_disk, 0); return err; }
} else { return 12; }
p_part->status &= ~2;
p_part->status |= 8;
return 0;
}
pf_s32 pdm_part_format(PDM_PARTITION* p_part, const pf_u8* param) {
pf_s32 err;
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
err = pdm_disk_format(p_part->p_disk, param);
if (err != 0) { return err; }
return 0;
}
pf_s32 pdm_part_logical_read(PDM_PARTITION* p_part, pf_u8* buf, pf_u32 sector, pf_u32 count, pf_u32 bps, pf_u32* p_success) {
pf_s32 err;
pf_u32 physical_sector;
if ((p_part->status & 8) != 8 || (p_part->status & 2) == 2) { return 15; }
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
if (p_part->total_sector <= sector) { return 18; }
if (p_part->total_sector < sector + count) { count -= (sector + count) - p_part->total_sector; }
physical_sector = pdm_part_chg_ltop(p_part, sector, bps);
err = pdm_disk_physical_read(p_part->p_disk, buf, physical_sector, count, bps, p_success);
if (err != 0) { return err; }
return 0;
}
pf_s32 pdm_part_logical_write(PDM_PARTITION* p_part, const pf_u8* buf, pf_u32 sector, pf_u32 count, pf_u32 bps, pf_u32* p_success) {
pf_s32 err;
pf_u32 physical_sector;
if ((p_part->status & 8) != 8 || (p_part->status & 2) == 2) { return 15; }
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
if (p_part->total_sector <= sector) { return 18; }
if (p_part->total_sector < sector + count) { count -= (sector + count) - p_part->total_sector; }
physical_sector = pdm_part_chg_ltop(p_part, sector, bps);
err = pdm_disk_physical_write(p_part->p_disk, buf, physical_sector, count, bps, p_success);
if (err != 0) { return err; }
return 0;
}
pf_s32 pdm_part_unmount(PDM_PARTITION* p_part, pf_u32 mode) {
pf_s32 err;
pf_s32 result = 0;
if (p_part->status & 8) {
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
err = pdm_disk_unmount(p_part->p_disk, mode);
if (err != 0) { result = err; }
} else { result = 14; }
if (result == 0 || mode == 1) { p_part->status &= ~2; p_part->status &= ~8; }
return result;
}
pf_s32 pdm_part_finalize(PDM_PARTITION* p_part) {
pf_s32 err;
if (p_part->status & 4) {
err = pdm_disk_set_disk(p_part->p_disk, p_part);
if (err != 0) { return err; }
err = pdm_disk_finalize(p_part->p_disk);
if (err != 0) { return err; }
} else { return 13; }
p_part->status &= ~4;
return 0;
}
pf_s32 pdm_part_register_callback(PDM_PARTITION* p_part, PDM_CALLBACK* callbacks) {
p_part->callbacks.insert = callbacks->insert;
p_part->callbacks.eject = callbacks->eject;
return 0;
}
pf_s32 pdm_part_unregister_callback(PDM_PARTITION* p_part) {
p_part->callbacks.insert = PF_NULL;
p_part->callbacks.eject = PF_NULL;
return 0;
}
void pdm_part_set_change_media_state(PDM_DISK* p_disk, pf_bool is_inserted) {
pf_u16 index;
for (index = 0; index < 26; index++) {
if ((pdm_disk_set.partition[index].status & 1) && pdm_disk_set.partition[index].p_disk == p_disk) {
PDM_PARTITION* p_part = &pdm_disk_set.partition[index];
p_part->status |= 2;
if (is_inserted == 0 && pdm_disk_set.partition[index].callbacks.eject != PF_NULL) {
pdm_disk_set.partition[index].callbacks.eject(p_part);
} else if (pdm_disk_set.partition[index].callbacks.insert != PF_NULL) {
pdm_disk_set.partition[index].callbacks.insert(p_part);
}
}
}
}

View File

@@ -0,0 +1,29 @@
#include <private/vf/PrFILE2/pf_types.h>
#include <private/vf/PrFILE2/driver/pf_driver.h>
typedef struct PFATTACH_NOTIFY {
pf_u8 driver_state[0x50];
void* callback_data;
} PFATTACH_NOTIFY;
typedef struct PFATTACH_GLOBAL {
pf_u8 volume_state[0x40];
pf_s32 last_error;
} PFATTACH_GLOBAL;
extern PFATTACH_GLOBAL pf_vol_set;
extern pf_s32 PFVOL_attach(PF_DRV_TBL*, PFATTACH_NOTIFY*, void*);
extern pf_s32 PFAPI_convertReturnValue(pf_s32);
pf_int32 pf2_attach(PF_DRV_TBL** drv_tbl, PFATTACH_NOTIFY* notify) {
pf_s32 err;
if (drv_tbl == PF_NULL || !*drv_tbl) {
err = 10;
pf_vol_set.last_error = 10;
} else {
for (; *drv_tbl != PF_NULL; drv_tbl++) {
if (notify != PF_NULL) err = PFVOL_attach(*drv_tbl, notify, notify->callback_data);
else err = PFVOL_attach(*drv_tbl, PF_NULL, PF_NULL);
if (err != 0) return PFAPI_convertReturnValue(err);
}
}
return PFAPI_convertReturnValue(err);
}

View File

@@ -0,0 +1,31 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFDIR_chdir PFDIR_chdir
#define VFiPFSTR_InitStr PFSTR_InitStr
#include <private/vf/PrFILE2/standard/pf_mkdir.h>
typedef struct PFAPI_GLOBAL_STATE {
pf_u8 volume_state[0x40];
pf_s32 last_error;
} PFAPI_GLOBAL_STATE;
extern PFAPI_GLOBAL_STATE pf_vol_set;
#include <private/vf/PrFILE2/fatfs/pf_dir.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
#include <private/vf/PrFILE2/common/pf_str.h>
pf_int32 pf2_chdir(const pf_ch8* sPath) {
pf_s32 err;
PF_STR path_str;
err = VFiPFSTR_InitStr(&path_str, (pf_s8*)sPath, 1U);
if (err == 0) {
err = VFiPFDIR_chdir(&path_str);
} else {
pf_vol_set.last_error = err;
}
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,177 @@
#include <private/vf/PrFILE2/pf_types.h>
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;
}

View File

@@ -0,0 +1,644 @@
#include <private/vf/PrFILE2/fatfs/pf_entry.h>
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, &sector);
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, &sector, &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;
}

View File

@@ -0,0 +1,21 @@
#include <private/vf/PrFILE2/pf_types.h>
// 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);
}

View File

@@ -0,0 +1,178 @@
#define PF_FA_CP932_TABLE
#define VFiPFCODE_CP932_OEM2Unicode PFCODE_CP932_OEM2Unicode
#define VFiPFCODE_CP932_OEMCharWidth PFCODE_CP932_OEMCharWidth
#define VFiPFCODE_CP932_Unicode2OEM PFCODE_CP932_Unicode2OEM
#define VFiPFCODE_CP932_UnicodeCharWidth PFCODE_CP932_UnicodeCharWidth
#define VFiPFCODE_CP932_isOEMMBchar PFCODE_CP932_isOEMMBchar
#define VFiPFCODE_CP932_isUnicodeMBchar PFCODE_CP932_isUnicodeMBchar
#define VFiPFCODE_Combine_Width PFCODE_Combine_Width
#define VFiPFCODE_Divide_Width PFCODE_Divide_Width
#include <private/vf/PrFILE2/local/pf_cp932.h>
#include <private/vf/PrFILE2/local/pf_cp932_to_unicode.h>
#include <private/vf/PrFILE2/common/pf_code.h>
pf_s32 VFiPFCODE_CP932_OEM2Unicode(const pf_s8* cp932_src, pf_u16* uc_dst) {
pf_u8 cp932_lead = *cp932_src++;
pf_u8 cp932_trail = *cp932_src;
pf_s32 lead_index;
pf_s32 trail_index;
if (cp932_lead < 0x80) {
*uc_dst = cp932_lead;
return VFiPFCODE_Combine_Width(1, 2);
}
if (cp932_lead >= 0xA1 && cp932_lead <= 0xDF) {
*uc_dst = cp932_lead + 0xFEC0;
return VFiPFCODE_Combine_Width(1, 2);
}
if (cp932_lead == 0x80 || cp932_lead == 0x85 || cp932_lead == 0x86 || cp932_lead == 0xA0 || cp932_lead == 0xEB ||
cp932_lead == 0xEC || (cp932_lead >= 0xEF && cp932_lead <= 0xF9) ||
(cp932_lead >= 0xFD && cp932_lead == 0xFF)) {
*uc_dst = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
if (cp932_trail >= 0xFD) {
*uc_dst = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
if (cp932_lead >= 0x81 && cp932_lead <= 0x84) {
lead_index = cp932_lead - 0x81;
} else if (cp932_lead >= 0x87 && cp932_lead <= 0x9F) {
lead_index = cp932_lead - 0x83;
} else if (cp932_lead >= 0xE0 && cp932_lead <= 0xEA) {
lead_index = cp932_lead - 0xC3;
} else if (cp932_lead >= 0xED && cp932_lead <= 0xEE) {
lead_index = cp932_lead - 0xC5;
} else if (cp932_lead >= 0xFA && cp932_lead <= 0xFC) {
lead_index = cp932_lead - 0xD0;
} else {
*uc_dst = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
trail_index = cp932_trail - '@';
if (trail_index < 0 || trail_index >= 189) {
*uc_dst = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
*uc_dst = cp932_to_unicode[lead_index][trail_index] & 0xFFFF;
if (*uc_dst == 0) {
*uc_dst = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
return VFiPFCODE_Combine_Width(2, 2);
}
pf_s32 VFiPFCODE_CP932_Unicode2OEM(const pf_u16* uc_src, pf_s8* cp932_dst) {
pf_s32 i;
pf_s32 j;
pf_u16* p_table;
pf_u8 uc_lead;
pf_u8 uc_trail;
pf_u16 uc;
pf_u16 cp932;
j = 0;
uc_lead = (pf_u8)(*uc_src >> 8);
uc_trail = (pf_u8)*uc_src;
if (uc_trail < 0x80 && uc_lead == 0) {
cp932_dst[0] = uc_trail;
cp932_dst[1] = 0;
return VFiPFCODE_Combine_Width(1, 2);
}
uc = PF_CODE_C_TO_WC(uc_lead, uc_trail);
if (0xFF61 <= uc && uc <= 0xFF9F) {
cp932 = uc - 0xFEC0;
cp932_dst[0] = cp932;
cp932_dst[1] = 0;
return VFiPFCODE_Combine_Width(1, 2);
}
if (uc == '_') {
cp932_dst[0] = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
for (i = 0; i < 45; i++) {
for (j = 0, p_table = (pf_u16*)&cp932_to_unicode[i]; j < 189; j++, p_table++) {
if (*p_table == uc) {
break;
}
}
if (j < 189) {
break;
}
}
if (j == 189) {
cp932_dst[0] = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
if (i >= 0 && i <= 3) {
cp932 = ((i + 0x81) << 8) | (j + '@');
} else if (i >= 4 && i <= 0x1C) {
cp932 = ((i + 0x83) << 8) | (j + '@');
} else if (i >= 0x1D && i <= '\'') {
cp932 = ((i + 0xC3) << 8) | (j + '@');
} else if (i >= '(' && i <= ')') {
cp932 = ((i + 0xC5) << 8) | (j + '@');
} else if (i >= '*' && i <= ',') {
cp932 = ((i + 0xD0) << 8) | (j + '@');
} else {
cp932_dst[0] = '_';
return VFiPFCODE_Combine_Width(1, 2);
}
cp932_dst[0] = (pf_u8)(cp932 >> 8);
cp932_dst[1] = (pf_u8)cp932;
return VFiPFCODE_Combine_Width(2, 2);
}
pf_s32 VFiPFCODE_CP932_OEMCharWidth(const pf_s8* buf) {
pf_u16 tmp;
pf_s32 width;
pf_s16 oem_width;
pf_s16 uni_width;
width = VFiPFCODE_CP932_OEM2Unicode(buf, &tmp);
VFiPFCODE_Divide_Width(width, &oem_width, &uni_width);
return (pf_s32)oem_width;
}
pf_bool VFiPFCODE_CP932_isOEMMBchar(pf_s8 cp932, pf_u32 num) {
pf_u8 code;
pf_bool is_mb;
code = (pf_u8)cp932;
switch (num) {
case 1: {
is_mb = (code >= 0x81 && code <= 0x9F) || (code >= 0xE0 && code <= 0xFC);
break;
}
case 2: {
is_mb = (code >= '@' && code <= '~') || (code >= 0x80 && code <= 0xFC);
break;
}
default: {
is_mb = PF_FALSE;
}
}
return is_mb;
}
pf_s32 VFiPFCODE_CP932_UnicodeCharWidth(const pf_u16* buf) {
pf_s8 tmp[2];
pf_s32 width;
pf_s16 oem_width;
pf_s16 uni_width;
width = VFiPFCODE_CP932_Unicode2OEM(buf, tmp);
VFiPFCODE_Divide_Width(width, &oem_width, &uni_width);
return uni_width;
}
pf_bool VFiPFCODE_CP932_isUnicodeMBchar(pf_u16 uc_src, pf_u32 num) {
return PF_FALSE;
}

View File

@@ -0,0 +1,36 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue2NULL PFAPI_convertReturnValue2NULL
#define VFiPFFILE_fopen PFFILE_fopen
#define VFiPFSTR_InitStr PFSTR_InitStr
#include <private/vf/PrFILE2/standard/pf_create.h>
typedef struct PFAPI_GLOBAL_STATE {
pf_u8 volume_state[0x40];
pf_s32 last_error;
} PFAPI_GLOBAL_STATE;
extern PFAPI_GLOBAL_STATE pf_vol_set;
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
PF_FILE* pf2_create(const pf_ch8* path, pf_int32 mode) {
pf_u32 open_mode_create;
PF_FILE* p_file;
PF_STR path_str;
pf_s32 err;
(void)mode;
open_mode_create = 0x19;
err = VFiPFSTR_InitStr(&path_str, (pf_s8*)path, 1U);
if (err == 0) {
err = VFiPFFILE_fopen(&path_str, open_mode_create, &p_file);
} else {
pf_vol_set.last_error = err;
}
p_file = VFiPFAPI_convertReturnValue2NULL(err, p_file);
return p_file;
}

View File

@@ -0,0 +1,13 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFVOL_detach PFVOL_detach
#include <private/vf/PrFILE2/standard/pf_detach.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
pf_int32 pf2_detach(pf_ch8 drive) {
pf_s32 err = VFiPFVOL_detach(drive);
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -102,6 +102,8 @@ typedef struct PFDIR_VOLUME_DIRS {
typedef struct PFDIR_GLOBAL_STATE {
pf_u8 state_prefix[0x40];
pf_s32 last_error;
pf_u8 driver_and_code_state[0x1C];
pf_u32 setting;
} PFDIR_GLOBAL_STATE;
extern PFDIR_GLOBAL_STATE pf_vol_set;
@@ -134,6 +136,26 @@ extern pf_s32 PFVOL_CheckCurrentDir(PF_VOLUME* volume, pf_u32 start_cluster);
extern pf_s32 PFENT_RemoveEntry(PF_DIR_ENT* entry, PF_ENT_ITER* iter);
extern pf_s32 PFFAT_FreeChain(PFDIR_FFD* ffd, pf_u32 start_cluster, pf_u32 chain_index, pf_u32 size);
static inline pf_u32 directory_is_open(PF_DIR_ENT* entry) {
PFDIR_VOLUME_DIRS* volume = (PFDIR_VOLUME_DIRS*)entry->p_vol;
pf_s32 index;
PFDIR_SDD* sdd = volume->sdds;
for (index = 0; index < 3; index++, sdd++) {
if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 &&
entry->p_vol == sdd->dir_entry.p_vol &&
entry->entry_sector == sdd->dir_entry.entry_sector &&
entry->entry_offset == sdd->dir_entry.entry_offset) { return 1; }
}
return 0;
}
extern void PFFAT_ResetFFD(PFDIR_FFD*, pf_u32*);
static inline pf_s32 release_directory_chain(PFDIR_FFD* ffd, pf_u32 cluster, pf_u32 count) {
pf_s32 error = PFFAT_FreeChain(ffd, cluster, -1U, count);
if (error != 0) { return error; }
return 0;
}
pf_s32 PFDIR_CheckDirIsEmpty(PF_ENT_ITER* iter, pf_u32* is_empty) {
pf_u32 start_cluster = *iter->ffd.p_start_cluster;
pf_s32 error;
@@ -177,8 +199,8 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) {
pf_s32 i;
pf_s32 remaining = 3;
for (i = 0; remaining != 0; i++, free_candidate++, remaining--) {
if ((volume_dirs->sdds[i].stat & 1) == 0 || (volume_dirs->sdds[i].stat & 2) == 0) {
for (i = 0; remaining != 0; remaining--) {
if ((volume_dirs->sdds[i].stat & 1) == 0 || ((volume_dirs->sdds[i].stat & 1) != 0 && (!volume_dirs->sdds[i].stat & 2) != 0)) {
if (first_free_sdd == 0) {
first_free_sdd = free_candidate;
}
@@ -187,6 +209,8 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) {
entry->entry_offset == volume_dirs->sdds[i].dir_entry.entry_offset) {
return &volume_dirs->sdds[i];
}
free_candidate++;
i++;
}
if (first_free_sdd == 0) {
return 0;
@@ -198,12 +222,21 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) {
return first_free_sdd;
}
static inline PFDIR_DIR* unused_directory(PF_VOLUME* volume) {
pf_s32 index;
for (index = 0; index < 3; index++) {
if ((((PFDIR_VOLUME_DIRS*)volume)->udds[index].stat & 1) == 0) {
return &((PFDIR_VOLUME_DIRS*)volume)->udds[index];
}
}
return 0;
}
pf_s32 PFDIR_DoFsexecOpenDir(PF_DIR_ENT* entry, PF_ENT_ITER* iter, PFDIR_DIR** opened_dir) {
PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol;
pf_s32 i;
PFDIR_SDD* sdd;
PFDIR_DIR* dir;
PFDIR_DIR* scan_dir;
pf_s32 i;
*opened_dir = 0;
if ((entry->attr & 0x10) == 0) {
@@ -213,15 +246,7 @@ pf_s32 PFDIR_DoFsexecOpenDir(PF_DIR_ENT* entry, PF_ENT_ITER* iter, PFDIR_DIR** o
if (sdd == 0) {
return 0x15;
}
scan_dir = volume_dirs->udds;
for (i = 0; i < 3; i++, scan_dir++) {
if ((scan_dir->stat & 1) == 0) {
dir = &volume_dirs->udds[i];
goto directory_available;
}
}
dir = 0;
directory_available:
dir = unused_directory((PF_VOLUME*)volume_dirs);
if (dir == 0) {
return 0x16;
}
@@ -239,9 +264,9 @@ directory_available:
pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_dir) {
PF_ENT_ITER iter;
PF_DIR_ENT entry;
pf_s32 i;
PFDIR_SDD* sdd;
PFDIR_DIR* dir;
pf_s32 i;
pf_s32 error;
if ((PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 0, 1) == 0 ||
@@ -255,9 +280,6 @@ pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_di
} else if (PFSTR_StrNumChar(path, 1) == 2 &&
PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0) {
error = PFVOL_GetCurrentDir(volume, &entry);
if (error != 0) {
return error;
}
goto open_directory;
} else if (PFSTR_StrNumChar(path, 1) == 3 &&
PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0 &&
@@ -288,14 +310,7 @@ open_directory:
if (sdd == 0) {
return 0x15;
}
for (i = 0; i < 3; i++) {
if ((((PFDIR_VOLUME_DIRS*)volume)->udds[i].stat & 1) == 0) {
dir = &((PFDIR_VOLUME_DIRS*)volume)->udds[i];
goto directory_available;
}
}
dir = 0;
directory_available:
dir = unused_directory(volume);
if (dir == 0) {
return 0x16;
}
@@ -349,17 +364,23 @@ pf_s32 PFDIR_p_readdir(PFDIR_DIR* dir, PFDIR_READ_RESULT* result) {
return 0;
}
extern pf_s32 PFENT_findEntry(PFDIR_FFD*, PF_DIR_ENT*, pf_u32, PFDIR_STR*, pf_u8, pf_u32*, pf_u32*);
extern pf_s32 PFFAT_GetSectorSpecified(PFDIR_FFD*, pf_u32, pf_u32, pf_u32*);
extern pf_s32 PFPATH_transformInUnicode(pf_u16*, const pf_s8*);
extern void PFPATH_SetSearchPattern(pf_s8*, pf_u16*, PFDIR_STR*);
extern pf_u16* pf_w_strcpy(pf_u16*, const pf_u16*);
pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_dta) {
pf_s32 err;
PF_STR full_path;
PF_STR dirname;
PFDIR_STR full_path;
PFDIR_STR dirname;
pf_u16 dirname_len;
PF_ENT_ITER parent_iter;
PF_DIR_ENT entry;
PF_DIR_ENT parent_entry;
PF_ENT_ITER parent_iter;
PF_FFD ffd;
PFDIR_FFD ffd;
PFDIR_FAT_HINT fat_hint;
pf_u32 pos;
PF_FAT_HINT fat_hint;
pf_u32 prev_chain[2];
pf_u32 new_sector;
@@ -368,7 +389,7 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_
err = 0;
new_sector = 0;
err = VFiPFPATH_SplitPath(p_path, &full_path, &dirname);
err = PFPATH_SplitPath((PFDIR_STR*)p_path, &full_path, &dirname);
if (err != 0) {
return err;
}
@@ -383,40 +404,39 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_
if (p_dta != PF_NULL) {
p_dta->parent_start_cluster = parent_entry.start_cluster;
}
VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster);
err = VFiPFENT_findEntry(&ffd, &entry, 0U, &dirname, 0x77U, PF_NULL, PF_NULL);
PFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster);
err = PFENT_findEntry(&ffd, &entry, 0U, &dirname, 0x77U, PF_NULL, PF_NULL);
if (err == 0) {
return 8;
}
if (err != 3) {
return err;
}
dirname_len = VFiPFSTR_StrNumChar(&dirname, 1U);
if ((dirname_len > 0xFFU) || ((dirname_len + parent_entry.path_len) > 0x103U)) {
return 2;
}
err = VFiPFENT_InitENT(&entry, &dirname, 0x10U, 1U, &parent_entry, p_vol);
dirname_len = PFSTR_StrNumChar(&dirname, 1U);
if (dirname_len + parent_entry.path_len > 0x103U) { return 2; }
if (dirname_len > 0xFFU) { return 1; }
err = VFiPFENT_InitENT(&entry, (PF_STR*)&dirname, 0x10U, 1U, &parent_entry, p_vol);
if (err == 0) {
VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster);
err = VFiPFENT_allocateEntry(&entry, (entry.num_entry_LFNs + 1), &ffd, prev_chain, PF_NULL, 0x77U, &pos);
PFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster);
err = VFiPFENT_allocateEntry(&entry, (entry.num_entry_LFNs + 1), (PF_FFD*)&ffd, prev_chain, PF_NULL, 0x77U, &pos);
if (err == 0) {
entry.start_cluster = 0;
VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &entry.start_cluster);
err = VFiPFFAT_GetSectorSpecified(&ffd, 0U, 1U, &new_sector);
PFFAT_InitFFD(&ffd, &fat_hint, p_vol, &entry.start_cluster);
err = PFFAT_GetSectorSpecified(&ffd, 0U, 1U, &new_sector);
if (new_sector == -1U) {
err = 6;
}
if (err == 0) {
err = VFiPFENT_FillVoidEntryToSectors(p_vol, new_sector, p_vol->bpb.sectors_per_cluster, 1U, &entry, &parent_entry);
if (err == 0) {
if ((entry.long_name[0] != 0) && ((VFipf_vol_set.setting & 2) == 2)) {
if ((entry.long_name[0] != 0) && ((pf_vol_set.setting & 2) == 2)) {
VFiPFPATH_AdjustExtShortName(&entry.short_name[0], pos);
entry.check_sum = VFiPFENT_CalcCheckSum(&entry);
}
err = VFiPFENT_UpdateEntry(&entry, prev_chain, 0U);
}
if (err != 0) {
VFiPFFAT_FreeChain(&ffd, entry.start_cluster, -1U, -1U);
PFFAT_FreeChain(&ffd, entry.start_cluster, -1U, -1U);
} else if (p_dta != PF_NULL) {
p_dta->p_file = PF_NULL;
p_dta->p_dir = PF_NULL;
@@ -428,16 +448,16 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_
p_dta->Date = entry.modify_date;
p_dta->FileSize = entry.file_size;
p_dta->Attribute = entry.attr;
if (VFiPFSTR_GetCodeMode(&dirname) == 1) {
VFiPFPATH_SetSearchPattern(p_dta->reg_exp, PF_NULL, &dirname);
if (VFiPFSTR_GetCodeMode((PF_STR*)&dirname) == 1) {
PFPATH_SetSearchPattern(p_dta->reg_exp, PF_NULL, &dirname);
p_dta->status |= 1;
} else {
VFiPFPATH_SetSearchPattern(p_dta->reg_exp, ((PF_DTAW*)p_dta)->reg_expW, &dirname);
PFPATH_SetSearchPattern(p_dta->reg_exp, ((PF_DTAW*)p_dta)->reg_expW, &dirname);
p_dta->status |= 2;
}
VFipf_strcpy(p_dta->FileName, &entry.short_name[0]);
pf_strcpy(p_dta->FileName, &entry.short_name[0]);
if ((p_dta->status & 2) == 2) {
VFiPFPATH_transformInUnicode(((PF_DTAW*)p_dta)->FileNameW, p_dta->FileName);
PFPATH_transformInUnicode(((PF_DTAW*)p_dta)->FileNameW, p_dta->FileName);
}
if (entry.long_name[0] == 0) {
p_dta->ordinal = 0;
@@ -449,17 +469,17 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_
} else {
p_dta->ordinal = 1;
p_dta->check_sum = entry.check_sum;
if ((VFipf_vol_set.setting & 2) == 2) {
VFipf_vol_set.setting &= 0xFFFFFFFC;
VFipf_vol_set.setting |= 1;
VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name);
VFipf_vol_set.setting &= 0xFFFFFFFC;
VFipf_vol_set.setting |= 2;
if ((pf_vol_set.setting & 2) == 2) {
pf_vol_set.setting &= 0xFFFFFFFC;
pf_vol_set.setting |= 1;
PFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name);
pf_vol_set.setting &= 0xFFFFFFFC;
pf_vol_set.setting |= 2;
} else {
VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name);
PFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name);
}
if ((p_dta->status & 2) == 2) {
VFipf_w_strcpy(((PF_DTAW*)p_dta)->LongNameW, entry.long_name);
pf_w_strcpy(((PF_DTAW*)p_dta)->LongNameW, entry.long_name);
}
}
}
@@ -524,7 +544,7 @@ pf_s32 PFDIR_p_chdir(PF_VOLUME* p_vol, PFDIR_STR* p_path_str) {
return 0;
}
pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u8 attributes) {
pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u32 attributes) {
PFDIR_STR directory_path;
PFDIR_STR filename;
PF_ENT_ITER iter;
@@ -544,52 +564,50 @@ pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u8 attributes) {
if (error != 0) {
return error;
}
if (((entry.attr & 0x10) == 0 && (attributes & 0x10) != 0) ||
((entry.attr & 0x10) != 0 && (attributes & 0x10) == 0)) {
if (((entry.attr & 0x10) != 0 && (attributes & 0x10) == 0) ||
((entry.attr & 0x10) == 0 && (attributes & 0x10) != 0)) {
return 10;
}
if ((attributes & 0x40) != 0) {
attributes &= (pf_u8)~0x40;
attributes = (pf_u8)(attributes & ~0x40);
}
if ((entry.attr & 0x10) == 0) {
if (PFFILE_IsOpened(&entry) != 0) {
return 0x13;
}
} else {
if ((entry.attr & 0x10) != 0) {
volume_dirs = (PFDIR_VOLUME_DIRS*)volume;
for (i = 0; i < 3; i++) {
PFDIR_SDD* sdd = &volume_dirs->sdds[i];
if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 &&
entry.p_vol == sdd->dir_entry.p_vol &&
entry.entry_sector == sdd->dir_entry.entry_sector &&
entry.entry_offset == sdd->dir_entry.entry_offset) {
return 0x13;
}
}
if ((attributes & 4) != 0 && (attributes & 0xF) != 0xF) {
if (directory_is_open(&entry) != 0) { return 0x13; }
if ((attributes & 4) != 0 && (pf_s32)(attributes & 0xF) != 0xF) {
return 10;
}
attributes |= 0x10;
entry.attr = attributes;
} else {
if (PFFILE_IsOpened(&entry) != 0) {
return 0x13;
}
entry.attr = attributes;
}
create_time_ms = PFENT_getcurrentDateTimeForEnt(&date, &time);
entry.modify_date = date;
entry.modify_time = time;
entry.create_time_ms = create_time_ms;
entry.attr = attributes;
return PFENT_updateEntry(&entry, 0);
PFENT_getcurrentDateTimeForEnt(&entry.access_date, &time);
if (entry.file_size == 0 && (entry.attr & 0x10) == 0) { entry.start_cluster = 0; }
error = PFENT_updateEntry(&entry, 0);
if (error != 0) { return error; }
return 0;
}
pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) {
PFDIR_VOLUME_DIRS* volume_dirs;
PFDIR_STR directory_path;
PFDIR_STR filename;
PFDIR_FAT_HINT saved_hint;
PFDIR_FAT_HINT hint;
PFDIR_FFD ffd;
PF_ENT_ITER iter;
PF_ENT_ITER directory_iter;
PF_DIR_ENT entry;
pf_u32 is_empty;
pf_u32 is_empty = 0;
pf_u32 i;
pf_s32 error;
error = PFPATH_SplitPath(path, &directory_path, &filename);
if (error != 0) { return error; }
error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0);
if (error != 0) {
return error;
@@ -597,30 +615,19 @@ pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) {
if ((entry.attr & 0x10) == 0 || (entry.attr & 1) != 0) {
return 0x14;
}
if (entry.start_cluster == 1 ||
(volume->bpb.fat_type == FAT_32 && entry.start_cluster == volume->bpb.root_dir_cluster)) {
return 0x1C;
}
volume_dirs = (PFDIR_VOLUME_DIRS*)volume;
for (i = 0; i < 3; i++) {
PFDIR_SDD* sdd = &volume_dirs->sdds[i];
if ((sdd->stat & 3) == 3 && entry.p_vol == sdd->dir_entry.p_vol &&
entry.entry_sector == sdd->dir_entry.entry_sector &&
entry.entry_offset == sdd->dir_entry.entry_offset) {
return 0x13;
}
}
directory_iter = iter;
saved_hint = *iter.ffd.p_hint;
if (directory_is_open(&entry) != 0) { return 0x13; }
error = PFVOL_CheckCurrentDir(volume, entry.start_cluster);
if (error != 0) {
return 0x1C;
}
if (error != 0 || entry.start_cluster == 1 ||
(volume->bpb.fat_type == FAT_32 && entry.start_cluster == volume->bpb.root_dir_cluster)) { return 0x1C; }
PFFAT_InitFFD(&ffd, &hint, volume, &entry.start_cluster);
directory_iter.ffd = ffd;
error = PFENT_ITER_IteratorInitialize(&directory_iter, 0);
if (error != 0) {
return error;
}
is_empty = 0;
error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty);
if (error != 0) {
return error;
@@ -628,18 +635,20 @@ pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) {
if (is_empty == 0) {
return 0x1D;
}
iter = directory_iter;
iter.ffd.p_hint = &saved_hint;
error = PFENT_RemoveEntry(&entry, &iter);
if (error != 0) {
return error;
}
return PFFAT_FreeChain(&iter.ffd, entry.start_cluster, -1U, -1U);
return release_directory_chain(&iter.ffd, entry.start_cluster, -1U);
}
pf_s32 PFDIR_p_fstat(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_FILE_STAT* file_stat) {
PF_ENT_ITER iter;
PF_DIR_ENT entry;
PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume;
pf_u32 index;
pf_s32 index = 0;
pf_s32 error;
error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0);
@@ -648,32 +657,32 @@ pf_s32 PFDIR_p_fstat(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_FILE_STAT* file_s
}
if (volume_dirs->num_opened_files != 0) {
for (index = 0; index < 5; index++) {
PFDIR_SFD* sfd = &volume_dirs->sfds[index];
if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 &&
entry.p_vol == sfd->dir_entry.p_vol &&
entry.entry_sector == sfd->dir_entry.entry_sector &&
entry.entry_offset == sfd->dir_entry.entry_offset) {
file_stat->file_size = sfd->dir_entry.file_size;
file_stat->access_date = sfd->dir_entry.access_date;
file_stat->modify_time = sfd->dir_entry.modify_time;
file_stat->modify_date = sfd->dir_entry.modify_date;
file_stat->create_time = sfd->dir_entry.create_time;
file_stat->create_date = sfd->dir_entry.create_date;
file_stat->small_letter_flag = sfd->dir_entry.small_letter_flag;
file_stat->attributes = sfd->dir_entry.attr;
if ((volume_dirs->sfds[index].stat & 1) != 0 && (volume_dirs->sfds[index].stat & 2) != 0 &&
entry.p_vol == volume_dirs->sfds[index].dir_entry.p_vol &&
entry.entry_sector == volume_dirs->sfds[index].dir_entry.entry_sector &&
entry.entry_offset == volume_dirs->sfds[index].dir_entry.entry_offset) {
file_stat->file_size = volume_dirs->sfds[index].dir_entry.file_size;
file_stat->attributes = volume_dirs->sfds[index].dir_entry.attr;
file_stat->modify_time = volume_dirs->sfds[index].dir_entry.modify_time;
file_stat->modify_date = volume_dirs->sfds[index].dir_entry.modify_date;
file_stat->access_date = volume_dirs->sfds[index].dir_entry.access_date;
file_stat->create_time = volume_dirs->sfds[index].dir_entry.create_time;
file_stat->create_date = volume_dirs->sfds[index].dir_entry.create_date;
file_stat->small_letter_flag = volume_dirs->sfds[index].dir_entry.create_time_ms;
break;
}
}
}
if (volume_dirs->num_opened_files == 0 || index == 5) {
file_stat->file_size = (entry.attr & 0x10) == 0 ? entry.file_size : 0;
file_stat->access_date = entry.access_date;
if ((entry.attr & 0x10) != 0) { file_stat->file_size = 0; }
else { file_stat->file_size = entry.file_size; }
file_stat->attributes = entry.attr;
file_stat->modify_time = entry.modify_time;
file_stat->modify_date = entry.modify_date;
file_stat->access_date = entry.access_date;
file_stat->create_time = entry.create_time;
file_stat->create_date = entry.create_date;
file_stat->small_letter_flag = entry.small_letter_flag;
file_stat->attributes = entry.attr;
file_stat->small_letter_flag = entry.create_time_ms;
}
return 0;
}
@@ -721,14 +730,18 @@ pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) {
PFDIR_STR destination_directory;
PFDIR_STR destination_name;
pf_s8 normalized_name[512];
pf_u32 code_mode;
const pf_s8* name;
pf_u32 entry_position;
pf_u16 filename_length;
pf_s32 error;
error = PFPATH_SplitPath((PFDIR_STR*)old_path, &source_directory, &source_name);
if (error != 0) {
return error;
}
filename_length = PFSTR_StrNumChar(&source_name, 1);
if (filename_length > 0xFF) { return 1; }
if (PFSTR_GetCodeMode(&source_name) == 2) {
if (PFSTR_StrNumChar(&source_name, 1) > 0xFF) {
return 1;
@@ -755,7 +768,7 @@ pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) {
if (error != 0) {
return error;
}
if (entry_position == 0) {
if (entry_position == 999999) {
return 3;
}
if ((source_entry.attr & 0x10) != 0) {
@@ -784,7 +797,7 @@ pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) {
if (source_iter.ffd.start_cluster != destination_parent.start_cluster) {
return 0x1F;
}
if (PFSTR_GetCodeMode(&destination_name) == 2) {
if ((code_mode = PFSTR_GetCodeMode(&destination_name)) == 2) {
if (PFSTR_StrNumChar(&destination_name, 1) > 0xFF) {
return 1;
}
@@ -822,8 +835,10 @@ pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) {
PFDIR_STR destination_name;
PFDIR_VOLUME_DIRS* volume_dirs;
pf_s8 normalized_name[512];
pf_u32 code_mode;
pf_u32 entry_position;
pf_u32 index;
pf_u16 filename_length;
pf_s32 index = 0;
pf_s32 error;
error = PFENT_ITER_GetEntryOfPath(&source_iter, &source_entry, volume,
@@ -839,7 +854,9 @@ pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) {
if (error != 0) {
return error;
}
if (PFSTR_GetCodeMode(&destination_name) == 2) {
filename_length = PFSTR_StrNumChar(&destination_name, 1);
if (filename_length > 0xFF) { return 1; }
if ((code_mode = PFSTR_GetCodeMode(&destination_name)) == 2) {
if (PFSTR_StrNumChar(&destination_name, 1) > 0xFF) {
return 1;
}
@@ -869,15 +886,7 @@ pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) {
source_entry.start_cluster == volume->bpb.root_dir_cluster)) {
return 0x1C;
}
for (index = 0; index < 3; index++) {
PFDIR_SDD* sdd = &volume_dirs->sdds[index];
if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 &&
sdd->dir_entry.p_vol == source_entry.p_vol &&
sdd->dir_entry.entry_sector == source_entry.entry_sector &&
sdd->dir_entry.entry_offset == source_entry.entry_offset) {
return 0x13;
}
}
if (directory_is_open(&source_entry) != 0) { return 0x13; }
} else if (PFFILE_IsOpened(&source_entry) != 0) {
return 0x13;
}
@@ -908,9 +917,10 @@ pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter)
PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol;
PFDIR_FAT_HINT hint;
PF_ENT_ITER directory_iter;
pf_u32 is_empty;
pf_u32 index;
pf_u32 start_cluster = entry->start_cluster;
pf_u32 is_empty = 0;
pf_s32 index = 0;
pf_u32 start_cluster;
pf_u32 chain_size;
pf_s32 error;
if ((entry->attr & 1) != 0) {
@@ -922,32 +932,30 @@ pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter)
entry->start_cluster == entry->p_vol->bpb.root_dir_cluster)) {
return 0x1C;
}
for (index = 0; index < 3; index++) {
PFDIR_SDD* sdd = &volume_dirs->sdds[index];
if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 &&
sdd->dir_entry.p_vol == entry->p_vol &&
sdd->dir_entry.entry_sector == entry->entry_sector &&
sdd->dir_entry.entry_offset == entry->entry_offset) {
return 0x13;
}
}
if (directory_is_open(entry) != 0) { return 0x13; }
directory_iter = *iter;
PFFAT_InitFFD(&directory_iter.ffd, &hint, entry->p_vol, &entry->start_cluster);
error = PFENT_ITER_IteratorInitialize(&directory_iter, 0);
hint = *iter->ffd.p_hint;
PFFAT_ResetFFD(&iter->ffd, &entry->start_cluster);
error = PFENT_ITER_IteratorInitialize(iter, 0);
if (error != 0) {
return error;
}
is_empty = 0;
error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty);
error = PFDIR_CheckDirIsEmpty(iter, &is_empty);
if (error != 0) {
return error;
}
if (is_empty == 0) {
return 0x1D;
}
} else if (PFFILE_IsOpened(entry) != 0) {
return 0x13;
*iter = directory_iter;
iter->ffd.p_hint = &hint;
chain_size = -1U;
} else {
if (PFFILE_IsOpened(entry) != 0) { return 0x13; }
chain_size = entry->file_size;
}
start_cluster = entry->start_cluster;
entry->num_entry_LFNs = data->num_entry_LFNs;
entry->ordinal = data->ordinal;
entry->check_sum = data->check_sum;
@@ -955,21 +963,29 @@ pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter)
if (error != 0) {
return error;
}
return PFFAT_FreeChain(&iter->ffd, start_cluster, -1U, -1U);
return release_directory_chain(&iter->ffd, start_cluster, chain_size);
}
pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode) {
pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 mode, pf_u32 attributes) {
PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol;
pf_u16 date;
pf_u16 time;
pf_u8 create_time_ms;
pf_u32 index;
pf_s32 index = 0;
pf_s32 error;
if ((attributes & 0x40) != 0) {
attributes &= ~0x40;
attributes = (pf_u8)(attributes & ~0x40);
}
if ((entry->attr & 0x10) == 0) {
if ((entry->attr & 0x10) != 0) {
if ((attributes & 4) != 0) {
return 10;
}
if (directory_is_open(entry) != 0) { return 0x13; }
entry->attr = attributes | 0x10;
} else {
if ((attributes & 0x10) != 0) {
return 10;
}
@@ -977,25 +993,8 @@ pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes,
return 0x13;
}
entry->attr = attributes;
} else {
if ((attributes & 4) != 0) {
return 10;
}
for (index = 0; index < 3; index++) {
PFDIR_SDD* sdd = &volume_dirs->sdds[index];
if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 &&
sdd->dir_entry.p_vol == entry->p_vol &&
sdd->dir_entry.entry_sector == entry->entry_sector &&
sdd->dir_entry.entry_offset == entry->entry_offset) {
return 0x13;
}
}
entry->attr = attributes | 0x10;
}
create_time_ms = PFENT_getcurrentDateTimeForEnt(&date, &time);
entry->modify_date = date;
entry->modify_time = time;
entry->create_time_ms = create_time_ms;
PFENT_getcurrentDateTimeForEnt(&entry->access_date, &time);
error = PFENT_updateEntry(entry, 0);
if (error != 0) {
return error;
@@ -1003,7 +1002,9 @@ pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes,
if ((mode & 0x80000000) == 0) {
data->Attribute = entry->attr;
}
return PFCACHE_FlushDataCacheSpecific(entry->p_vol, 0);
error = PFCACHE_FlushDataCacheSpecific(entry->p_vol, 0);
if (error != 0) { return error; }
return 0;
}
pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags,
@@ -1062,9 +1063,9 @@ pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter
}
pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) {
PF_ENT_ITER iter;
PFDIR_FFD ffd;
PFDIR_FAT_HINT hint;
PF_ENT_ITER iter;
PF_DIR_ENT entry;
PFDIR_STR pattern;
pf_u32 logical_position;
@@ -1074,32 +1075,34 @@ pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) {
const pf_s8* name;
pf_s32 error;
if ((flags & 0x26) == 0 && (flags & 1) == 0) {
if ((flags & 6) == 0 && (flags & 1) == 0 && (flags & 0x10) == 0 && (flags & 0x20) == 0) {
return 10;
}
if ((flags & 0x26) != 0 || (flags & 1) != 0 || ((flags & 0x10) != 0 && mode != 2)) {
if ((flags & 6) != 0 || (flags & 1) != 0 || ((flags & 0x10) != 0 && mode != 2)) {
error = PFVOL_CheckForWrite(data->p_vol);
if (error != 0) {
return error;
}
}
entry.start_cluster = data->parent_start_cluster;
entry.check_sum = 0;
PFFAT_InitFFD(&ffd, &hint, data->p_vol, &entry.start_cluster);
iter.p_vol = data->p_vol;
iter.ffd = ffd;
start_position = data->parent_pos - 1;
if ((flags & 0x80000000) == 0) {
start_position -= data->num_entry_LFNs;
}
PFFAT_InitFFD(&ffd, &hint, data->p_vol, &data->parent_start_cluster);
iter.p_vol = data->p_vol;
iter.ffd = ffd;
error = PFENT_ITER_IteratorInitialize(&iter, start_position);
if (error != 0) {
return error;
}
if ((data->status & 1) != 0) {
if ((data->status & 1) == 1) {
code_mode = 1;
name = data->FileName;
} else {
code_mode = 2;
if ((VFipf_vol_set.setting & 2) != 0) {
if ((pf_vol_set.setting & 2) != 0) {
name = (const pf_s8*)((PF_DTAW*)data)->LongNameW;
} else {
name = (const pf_s8*)((PF_DTAW*)data)->FileNameW;
@@ -1109,7 +1112,7 @@ pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) {
if (error != 0) {
return error;
}
if ((VFipf_vol_set.setting & 2) != 0) {
if ((pf_vol_set.setting & 2) != 0) {
PFSTR_SetLocalStr(&pattern, (pf_u32)data->LongName);
} else {
PFSTR_SetLocalStr(&pattern, (pf_u32)data->FileName);
@@ -1137,7 +1140,7 @@ pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) {
return error;
}
if ((flags & 6) != 0) {
return PFDIR_p_fsexec_chmod(data, &entry, flags, mode);
return PFDIR_p_fsexec_chmod(data, &entry, mode, flags);
}
if ((flags & 1) != 0) {
return PFDIR_p_fsexec_remove(data, &entry, &iter);
@@ -1316,7 +1319,7 @@ void PFDIR_opendir(PF_STR* path, PFDIR_DIR** dir) {
pf_vol_set.last_error = error;
((PFDIR_VOLUME_DIRS*)volume)->last_error = error;
} else {
((PFDIR_VOLUME_DIRS*)volume)->num_opened_directories++;
((PFDIR_VOLUME_DIRS*)volume)->num_opened_directories += 1;
}
}
@@ -1507,9 +1510,15 @@ pf_s32 PFDIR_chdir(PF_STR* path) {
if (error != 0) {
pf_vol_set.last_error = error;
((PFDIR_VOLUME_DIRS*)volume)->last_error = error;
return error;
} else {
PFVOL_SetCurrentVolume(volume);
}
PFVOL_SetCurrentVolume(volume);
return error;
}
static inline pf_s32 set_directory_context(PF_VOLUME* volume, PF_DIR_ENT* entry) {
pf_s32 error = PFVOL_SetCurrentDir(volume, entry);
if (error != 0) { return error; }
return 0;
}
@@ -1528,14 +1537,14 @@ pf_s32 PFDIR_fchdir(PFDIR_DIR* dir) {
((PFDIR_VOLUME_DIRS*)volume)->last_error = error;
return error;
}
error = PFVOL_SetCurrentDir(volume, &dir->p_sdd->dir_entry);
error = set_directory_context(volume, &dir->p_sdd->dir_entry);
if (error != 0) {
pf_vol_set.last_error = error;
((PFDIR_VOLUME_DIRS*)volume)->last_error = error;
return error;
} else {
PFVOL_SetCurrentVolume(volume);
}
PFVOL_SetCurrentVolume(volume);
return 0;
return error;
}
void PFDIR_chmod(PF_STR* path, pf_u8 attributes) {
@@ -1580,7 +1589,7 @@ void PFDIR_chdmod(PF_STR* path, pf_u8 attributes) {
return;
}
volume_dirs->cache_signature = 0;
error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, attributes | 0x10);
error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, (pf_u8)(attributes | 0x10));
if (error != 0) {
pf_vol_set.last_error = error;
((PFDIR_VOLUME_DIRS*)volume)->last_error = error;
@@ -1608,7 +1617,7 @@ pf_s32 PFDIR_p_fsnext(PF_DTA* data) {
pf_u32 logical_position = 0;
pf_u32 entry_position = 0;
pf_u32 code_mode;
pf_u32 index;
pf_s32 index = 0;
pf_s32 error;
if ((data->status & 1) == 1) {
@@ -1621,63 +1630,55 @@ pf_s32 PFDIR_p_fsnext(PF_DTA* data) {
if (error != 0) {
return error;
}
PFSTR_SetLocalStr(&pattern, 0);
if (entry_position < 0xF423F) {
if (data->parent_pos > 0xF423E) {
return 10;
}
ffd.start_cluster = data->parent_start_cluster;
PFFAT_InitFFD(&ffd, &hint, data->p_vol, &ffd.start_cluster);
PFSTR_SetLocalStr(&pattern, (pf_u32)data->reg_exp);
while (entry_position < 999999) {
if (data->parent_pos >= 999999) { return 10; }
entry.start_cluster = data->parent_start_cluster;
PFFAT_InitFFD(&ffd, &hint, data->p_vol, &entry.start_cluster);
error = PFENT_findEntryPos(&ffd, &entry, data->parent_pos, &pattern, data->attr, 0,
&logical_position, &entry_position);
if (error != 0) {
return error;
}
if (error != 0) { return error; }
data->parent_pos = entry_position + 1;
if (entry_position == 0xF423F) {
return 3;
}
if (entry_position == 999999) { return 3; }
}
pf_strcpy(data->FileName, entry.short_name);
if ((data->status & 2) == 2) {
PFPATH_transformInUnicode(((PF_DTAW*)data)->FileNameW, data->FileName);
}
if (entry.long_name[0] == 0) {
data->LongName[0] = 0;
if ((data->status & 2) == 2) {
((PF_DTAW*)data)->LongNameW[0] = 0;
}
} else {
if ((VFipf_vol_set.setting & 2) == 2) {
VFipf_vol_set.setting &= 0xFFFFFFFC;
VFipf_vol_set.setting |= 1;
if (entry.long_name[0] != 0) {
if ((pf_vol_set.setting & 2) == 2) {
pf_vol_set.setting &= 0xFFFFFFFC;
pf_vol_set.setting |= 1;
PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name);
VFipf_vol_set.setting &= 0xFFFFFFFC;
VFipf_vol_set.setting |= 2;
pf_vol_set.setting &= 0xFFFFFFFC;
pf_vol_set.setting |= 2;
} else {
PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name);
}
if ((data->status & 2) == 2) {
pf_w_strcpy(((PF_DTAW*)data)->LongNameW, entry.long_name);
}
} else {
data->LongName[0] = 0;
if ((data->status & 2) == 2) {
((PF_DTAW*)data)->LongNameW[0] = 0;
}
}
if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files != 0) {
PFDIR_SFD* sfd = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds;
for (index = 0; index < 5; index++) {
if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 &&
sfd->dir_entry.p_vol == entry.p_vol &&
sfd->dir_entry.entry_sector == entry.entry_sector &&
sfd->dir_entry.entry_offset == entry.entry_offset) {
data->FileSize = sfd->dir_entry.file_size;
data->Time = sfd->dir_entry.modify_time;
data->Date = sfd->dir_entry.modify_date;
data->Attribute = sfd->dir_entry.attr;
data->num_entry_LFNs = sfd->dir_entry.num_entry_LFNs;
data->ordinal = sfd->dir_entry.ordinal;
data->check_sum = sfd->dir_entry.check_sum;
if ((((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].stat & 1) != 0 && (((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].stat & 2) != 0 &&
entry.p_vol == ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.p_vol &&
((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.entry_sector == entry.entry_sector &&
((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.entry_offset == entry.entry_offset) {
data->FileSize = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.file_size;
data->Time = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.modify_time;
data->Date = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.modify_date;
data->Attribute = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.attr;
data->num_entry_LFNs = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.num_entry_LFNs;
data->ordinal = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.ordinal;
data->check_sum = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.check_sum;
break;
}
sfd++;
}
}
if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files == 0 || index == 5) {

View File

@@ -0,0 +1,442 @@
#include <private/vf/PrFILE2/pf_types.h>
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;
}

View File

@@ -0,0 +1,759 @@
#include <private/vf/PrFILE2/fatfs/pf_entry.h>
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(&current_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;
}

View File

@@ -358,8 +358,8 @@ s32 PFFAT_FindClusterLink(PFFAT_FFD* file, u32 chainIndex, u32* cluster,
u32 nextCluster;
s32 error;
*found = 0;
nextCluster = -1;
*found = 0;
if (file->cluster_link.position == 0) {
return 0;
}
@@ -388,6 +388,7 @@ s32 PFFAT_FindClusterLink(PFFAT_FFD* file, u32 chainIndex, u32* cluster,
&nextCluster);
break;
default:
nextCluster = -1;
error = 15;
break;
}
@@ -486,6 +487,7 @@ s32 PFFAT_ReadCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
u32* nextCluster, u32* checkClusterLink)
{
s32 error;
u32 value;
*nextCluster = -1;
if (file->cluster_link.buffer != 0 && *checkClusterLink == 1) {
@@ -515,22 +517,22 @@ s32 PFFAT_ReadCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
if (error != 0) {
return error;
}
if (*nextCluster == 0) {
value = *nextCluster;
if (value == 0) {
return 13;
}
if (*nextCluster == -1) {
if (value == -1) {
return 6;
}
}
if (file->cluster_link.buffer != 0 &&
*nextCluster != fat_special_values[file->p_vol->bpb.fat_type].eoc2) {
if (file->cluster_link.buffer != 0 &&
value != fat_special_values[file->p_vol->bpb.fat_type].eoc2) {
if (file->cluster_link.max_count > file->cluster_link.position &&
file->cluster_link.max_count != 0) {
if (chainIndex == file->cluster_link.position *
(file->cluster_link.interval + 1)) {
file->cluster_link.interval_offset = 0;
file->cluster_link.buffer[file->cluster_link.position] =
*nextCluster;
value;
file->cluster_link.position++;
} else {
file->cluster_link.interval_offset++;
@@ -538,6 +540,7 @@ s32 PFFAT_ReadCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
file->cluster_link.save_index = chainIndex;
}
}
}
return 0;
}
@@ -546,6 +549,7 @@ s32 PFFAT_ReadClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
PF_CACHE_PAGE* page)
{
s32 error;
u32 value;
*nextCluster = -1;
if (file->cluster_link.buffer != 0 && *checkClusterLink == 1) {
@@ -576,22 +580,22 @@ s32 PFFAT_ReadClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
if (error != 0) {
return error;
}
if (*nextCluster == 0) {
value = *nextCluster;
if (value == 0) {
return 13;
}
if (*nextCluster == -1) {
if (value == -1) {
return 6;
}
}
if (file->cluster_link.buffer != 0 &&
*nextCluster != fat_special_values[file->p_vol->bpb.fat_type].eoc2) {
if (file->cluster_link.buffer != 0 &&
value != fat_special_values[file->p_vol->bpb.fat_type].eoc2) {
if (file->cluster_link.max_count > file->cluster_link.position &&
file->cluster_link.max_count != 0) {
if (chainIndex == file->cluster_link.position *
(file->cluster_link.interval + 1)) {
file->cluster_link.interval_offset = 0;
file->cluster_link.buffer[file->cluster_link.position] =
*nextCluster;
value;
file->cluster_link.position++;
} else {
file->cluster_link.interval_offset++;
@@ -599,6 +603,7 @@ s32 PFFAT_ReadClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
file->cluster_link.save_index = chainIndex;
}
}
}
return 0;
}
@@ -608,6 +613,7 @@ s32 PFFAT_WriteCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
u32 accessCluster;
u32 position;
u32 divisor;
u32* linkBuffer;
u32 precedingIndex;
s32 error;
@@ -641,14 +647,15 @@ s32 PFFAT_WriteCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
if (error != 0) {
return error;
}
if (file->cluster_link.buffer != 0 && useClusterLink == 1) {
linkBuffer = file->cluster_link.buffer;
if (linkBuffer != 0 && useClusterLink == 1) {
if (nextCluster == 0) {
divisor = file->cluster_link.interval + 1;
position = chainIndex / divisor;
if (file->cluster_link.max_count >= position) {
if (chainIndex % divisor == 0) {
file->cluster_link.buffer[position] = 0;
linkBuffer[position] = 0;
}
if (file->cluster_link.save_index >= chainIndex) {
precedingIndex = chainIndex - 1;
@@ -694,6 +701,7 @@ s32 PFFAT_WriteClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
u32 accessCluster;
u32 position;
u32 divisor;
u32* linkBuffer;
u32 precedingIndex;
s32 error;
@@ -729,14 +737,15 @@ s32 PFFAT_WriteClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex,
if (error != 0) {
return error;
}
if (file->cluster_link.buffer != 0 && useClusterLink == 1) {
linkBuffer = file->cluster_link.buffer;
if (linkBuffer != 0 && useClusterLink == 1) {
if (nextCluster == 0) {
divisor = file->cluster_link.interval + 1;
position = chainIndex / divisor;
if (file->cluster_link.max_count >= position) {
if (chainIndex % divisor == 0) {
file->cluster_link.buffer[position] = 0;
linkBuffer[position] = 0;
}
if (file->cluster_link.save_index >= chainIndex) {
precedingIndex = chainIndex - 1;
@@ -1108,14 +1117,25 @@ s32 PFFAT_GetClusterAllocatedInChain(PFFAT_FFD* file, u32 initialCluster,
return 0;
}
static inline s32 find_cluster_in_chain(PFFAT_FFD* file, u32 index, u32 mode, u32 count, u32 useFirst, u32* cluster) {
u32 firstCluster;
u32 lastCluster;
u32 candidate;
s32 error = PFFAT_GetClusterInChain(file, index, mode, count, &firstCluster, &lastCluster);
if (error != 0) { return error; }
candidate = useFirst ? firstCluster : lastCluster;
if (candidate >= 2 && candidate < file->p_vol->bpb.num_clusters + 2) { *cluster = candidate; }
return 0;
}
s32 PFFAT_GetClusterSpecified(PFFAT_FFD* file, u32 chainIndex,
u32 mayAllocate, u32* cluster)
{
PFFAT_HINT* hint;
u32 fatType;
u32 found;
u32 locateEnd;
u32 locateStart;
u32 locateEnd;
s32 error;
fatType = file->p_vol->bpb.fat_type;
@@ -1144,20 +1164,7 @@ s32 PFFAT_GetClusterSpecified(PFFAT_FFD* file, u32 chainIndex,
}
}
*cluster = -1;
error = PFFAT_GetClusterInChain(file, chainIndex, mayAllocate != 0, 0,
&locateStart, &locateEnd);
if (error == 0) {
goto cluster_lookup_succeeded;
}
goto cluster_lookup_complete;
cluster_lookup_succeeded:
if (locateEnd >= 2 && locateEnd < file->p_vol->bpb.num_clusters + 2) {
*cluster = locateEnd;
}
error = 0;
cluster_lookup_complete:
error = find_cluster_in_chain(file, chainIndex, mayAllocate != 0, 0, 0, cluster);
if (error != 0) {
return error;
}
@@ -1173,10 +1180,10 @@ cluster_lookup_complete:
s32 PFFAT_GetClusterAllocated(PFFAT_FFD* file, u32 chainIndex,
u32 numClusters, u32* cluster)
{
u32 fatType;
PFFAT_HINT* hint;
u32 locateEnd;
u32 fatType;
u32 locateStart;
u32 locateEnd;
s32 error;
fatType = file->p_vol->bpb.fat_type;
@@ -1189,15 +1196,7 @@ s32 PFFAT_GetClusterAllocated(PFFAT_FFD* file, u32 chainIndex,
*file->p_start_cluster = file->p_vol->bpb.root_dir_cluster;
}
*cluster = -1;
error = PFFAT_GetClusterInChain(file, chainIndex, 2, numClusters,
&locateStart, &locateEnd);
if (error == 0) {
if (locateStart >= 2 &&
locateStart < file->p_vol->bpb.num_clusters + 2) {
*cluster = locateStart;
}
error = 0;
}
error = find_cluster_in_chain(file, chainIndex, 2, numClusters, 1, cluster);
if (error != 0) {
return error;
}
@@ -1225,17 +1224,18 @@ s32 PFFAT_GetSector(PFFAT_FFD* file, u32 fileSectorIndex, u32 mode,
u32 size, u32* sector)
{
PF_VOLUME* volume;
u32 fatType;
u32 chainIndex;
u32 cluster;
u32 numDivide;
u32 numRemainder;
u32 numSectors;
u32 numDivide;
u32 numClusters;
u32 numSectors;
s32 error;
volume = file->p_vol;
if (*file->p_start_cluster == 1 &&
(u32)volume->bpb.fat_type <= FAT_16) {
fatType = volume->bpb.fat_type;
if (*file->p_start_cluster == 1 && fatType <= FAT_16) {
error = PFFAT_GetSectorInRootDirRegion(volume, fileSectorIndex, sector);
if (error != 0) {
return error;
@@ -1244,13 +1244,12 @@ s32 PFFAT_GetSector(PFFAT_FFD* file, u32 fileSectorIndex, u32 mode,
}
chainIndex = fileSectorIndex >> volume->bpb.log2_sectors_per_cluster;
if (mode == 2) {
numDivide = size / volume->bpb.bytes_per_sector;
numRemainder = (size % volume->bpb.bytes_per_sector) != 0;
numSectors = numDivide + numRemainder;
numSectors = (size / volume->bpb.bytes_per_sector) +
((size % volume->bpb.bytes_per_sector) != 0);
numDivide = numSectors / volume->bpb.sectors_per_cluster;
numRemainder =
(numSectors % volume->bpb.sectors_per_cluster) != 0;
numClusters = numDivide + numRemainder;
numClusters = numRemainder + numDivide;
error = PFFAT_GetClusterAllocated(file, chainIndex, numClusters,
&cluster);
if (error != 0) {
@@ -1375,7 +1374,8 @@ s32 PFFAT_CountAllocatedClusters(PFFAT_FFD* file, u32 size,
*numAllocatedClusters = file->p_hint->chain_index;
cluster = file->p_hint->cluster;
chainIndex = file->p_hint->chain_index + 1;
size -= file->p_hint->chain_index * bytesPerCluster;
size -= file->p_hint->chain_index *
(file->p_vol->bpb.bytes_per_sector * file->p_vol->bpb.sectors_per_cluster);
} else {
cluster = *file->p_start_cluster;
chainIndex = 1;
@@ -1520,9 +1520,9 @@ s32 PFFAT_FreeChain(PFFAT_FFD* file, u32 startCluster, u32 chainIndex,
}
if (nextCluster == 0) {
s32 firstFlushError;
u32 fatSector;
u16 fatIndex;
PF_CACHE_PAGE* flushPage;
u16 fatIndex;
u32 fatSector;
firstFlushError = 0;
flushPage = page;
@@ -1857,7 +1857,8 @@ s32 PFFAT_RefreshFSINFO(PF_VOLUME* volume)
if ((volume->fsi_flag & 4) != 0) {
error = PFCACHE_AllocateDataPage(volume, -1, &page,
&alreadyAllocated);
if (error == 0) {
if (error != 0) { goto finished; }
{
error = PFSEC_ReadData(
volume, page->p_buf, volume->bpb.fs_info_sector, 0,
volume->bpb.bytes_per_sector, &completedBytes, 0);
@@ -1896,6 +1897,7 @@ s32 PFFAT_RefreshFSINFO(PF_VOLUME* volume)
PFCACHE_FreeDataPage(volume, page);
}
}
finished:
return error;
}

View File

@@ -0,0 +1,248 @@
#define PF_FA_STR_LAYOUT
#define VFiPFCACHE_ReadFATPage PFCACHE_ReadFATPage
#define VFiPFCACHE_UpdateModifiedSector PFCACHE_UpdateModifiedSector
#define VFiPFFAT12_ReadFATEntry PFFAT12_ReadFATEntry
#define VFiPFFAT12_ReadFATEntryPage PFFAT12_ReadFATEntryPage
#define VFiPFFAT12_WriteFATEntry PFFAT12_WriteFATEntry
#define VFiPFFAT12_WriteFATEntryPage PFFAT12_WriteFATEntryPage
#define VFiPFFAT_UpdateFATEntry PFFAT_UpdateFATEntry
#define VFiPFSEC_ReadFAT PFSEC_ReadFAT
#define VFiPFSEC_WriteFAT PFSEC_WriteFAT
#include <private/fa/pf_volume.h>
#include <private/vf/PrFILE2/fatfs/pf_fat.h>
#include <private/vf/PrFILE2/fatfs/pf_fat12.h>
#include <private/vf/PrFILE2/fatfs/pf_sector.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/common/pf_code.h>
pf_s32 VFiPFFAT12_ReadFATEntry(PF_VOLUME* p_vol, pf_u16 cluster, pf_u32* p_value) {
pf_u16 fat_sector;
pf_s32 err;
pf_u16 fat_offset;
pf_u16 offset_in_sector;
pf_u16 word;
pf_u8 buf[sizeof(pf_u16)];
pf_u32 current_fat;
pf_s32 result;
fat_offset = cluster + (cluster >> 1);
fat_sector = p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector);
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & (0x01 | 0x02 | 0x04);
} else {
current_fat = 1;
}
do {
if (offset_in_sector < (p_vol->bpb.bytes_per_sector - 1)) {
err = VFiPFSEC_ReadFAT(p_vol, &buf[0], (pf_u32)fat_sector, offset_in_sector, 2);
} else {
err = VFiPFSEC_ReadFAT(p_vol, &buf[0], (pf_u32)fat_sector, offset_in_sector, 1);
if (err == 0) {
err = VFiPFSEC_ReadFAT(p_vol, &buf[1], fat_sector + 1, 0U, 1);
}
}
if (err == 0x1000 && p_vol->p_callback != PF_NULL) {
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result == 0) {
continue;
}
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
fat_sector += (pf_u16)p_vol->bpb.sectors_per_FAT;
continue;
}
}
if (err != 0) {
*p_value = -1;
return err;
}
} while (err != 0);
word = PF_SWAP_16(*(pf_u16*)buf);
if ((cluster & 0x01) != 0) {
*p_value = (word >> 4);
} else {
*p_value = word & 0xFFF;
}
return 0;
}
pf_s32 VFiPFFAT12_WriteFATEntry(PF_VOLUME* p_vol, pf_u16 cluster, pf_u16 value) {
pf_s32 err;
pf_u16 fat_offset;
pf_u16 fat_sector;
pf_u16 offset_in_sector;
pf_u16 fat_sector2;
pf_u16 offset_in_sector2;
pf_u16 word;
pf_u16 current_fat;
pf_s32 result;
pf_u8 buf[sizeof(pf_u16)];
fat_offset = cluster + (cluster >> 1);
fat_sector = p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector);
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
if ((cluster & 0x01) != 0) {
err = VFiPFSEC_ReadFAT(p_vol, &buf[0], fat_sector, offset_in_sector, 1);
if (err != 0) {
return err;
}
word = (pf_u16)((value << 4) + (buf[0] & 0xF));
} else {
fat_sector2 = p_vol->bpb.active_FAT_sector + ((fat_offset + 1) >> p_vol->bpb.log2_bytes_per_sector);
offset_in_sector2 = (fat_offset + 1) & (p_vol->bpb.bytes_per_sector - 1);
err = VFiPFSEC_ReadFAT(p_vol, &buf[0], fat_sector2, offset_in_sector2, 1);
if (err != 0) {
return err;
}
word = (pf_u16)buf[0] << 8;
word = (word & 0xF000) + (pf_u16)(value & 0xFFF);
}
*(pf_u16*)buf = PF_SWAP_16(word);
result = 0;
for (current_fat = 0; current_fat < p_vol->bpb.num_active_FATs; current_fat++) {
if (offset_in_sector < (p_vol->bpb.bytes_per_sector - 1)) {
err = VFiPFSEC_WriteFAT(p_vol, &buf[0], fat_sector, offset_in_sector, 2);
if (err != 0 && result == 0) { result = err; }
} else {
err = VFiPFSEC_WriteFAT(p_vol, &buf[0], fat_sector, offset_in_sector, 1U);
if (err != 0 && result == 0) { result = err; }
err = VFiPFSEC_WriteFAT(p_vol, &buf[1], fat_sector + 1, 0U, 1);
if (err != 0 && result == 0) { result = err; }
}
fat_sector += p_vol->bpb.sectors_per_FAT;
}
return result;
}
pf_s32 PFFAT12_WriteFATEntryWithBuf(PF_VOLUME* p_vol, pf_s16 cluster, pf_u16 value, PF_CACHE_PAGE* p_page) {
pf_s32 err;
pf_u32 offset_in_sector;
pf_u16 current_fat;
pf_s32 fat_offset;
pf_u32 fat_sector;
pf_s32 result;
fat_offset = (pf_u16)(cluster + (cluster >> 1));
fat_sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector));
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
err = 0;
result = 0;
#define FLUSH_FAT_BUFFER() \
for (current_fat = 0; current_fat < p_vol->bpb.num_active_FATs; current_fat++) { \
err = VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + current_fat * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector); \
if (err != 0 && result == 0) { result = err; } \
}
if (p_page->sector != fat_sector) {
FLUSH_FAT_BUFFER();
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, fat_sector, 0, p_vol->bpb.bytes_per_sector);
if (err != 0) { return err; }
p_page->sector = fat_sector;
}
if (cluster & 1) {
p_page->p_buf[(pf_u16)offset_in_sector] = (p_page->p_buf[(pf_u16)offset_in_sector] & 0xF) | ((value << 4) & 0xF0);
if ((pf_u16)offset_in_sector == (pf_u32)(p_vol->bpb.bytes_per_sector - 1)) {
FLUSH_FAT_BUFFER();
offset_in_sector = fat_sector + 1;
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, offset_in_sector, 0, p_vol->bpb.bytes_per_sector);
if (err != 0) { return err; }
p_page->sector = offset_in_sector;
p_page->p_buf[0] = value >> 4;
} else {
((pf_u16)offset_in_sector + p_page->p_buf)[1] = value >> 4;
}
} else {
p_page->p_buf[(pf_u16)offset_in_sector] = value;
if ((pf_u16)offset_in_sector == (pf_u32)(p_vol->bpb.bytes_per_sector - 1)) {
FLUSH_FAT_BUFFER();
offset_in_sector = fat_sector + 1;
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, offset_in_sector, 0, p_vol->bpb.bytes_per_sector);
if (err != 0) { return err; }
p_page->sector = offset_in_sector;
p_page->p_buf[0] = (p_page->p_buf[0] & 0xF0) | ((pf_u8)(value >> 8));
} else {
((pf_u16)offset_in_sector + p_page->p_buf)[1] = (((pf_u16)offset_in_sector + p_page->p_buf)[1] & 0xF0) | ((pf_u8)(value >> 8));
}
}
if (err != 0) { result = err; }
return result;
#undef FLUSH_FAT_BUFFER
}
pf_s32 PFFAT12_ReadFATEntryWithBuf(PF_VOLUME* p_vol , pf_u16 cluster , pf_u32* p_value ,
PF_CACHE_PAGE* p_page ) {
pf_s32 err;
pf_u32 current_fat;
pf_u32 sector;
pf_u32 offset;
pf_s32 result;
#define LOAD_FAT_SECTOR(next_sector) \
if (p_page->sector != sector + (next_sector)) { \
if (p_page->option == 1) { \
for (err = 0; (pf_u16)err < p_vol->bpb.num_active_FATs; err++) { \
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + (pf_u16)err * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector); \
} \
} \
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, sector + (next_sector), 0, p_vol->bpb.bytes_per_sector); \
if (err != 0) { continue; } \
p_page->sector = sector + (next_sector); \
}
offset = (pf_u16)(cluster + (cluster >> 1));
sector = p_vol->bpb.active_FAT_sector + (offset >> p_vol->bpb.log2_bytes_per_sector) & 0xFFFF;
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & (0x01 | 0x02 | 0x04);
} else {
current_fat = 1;
}
err = 0;
while (PF_TRUE) {
if (err == 0x1000 && p_vol->p_callback != PF_NULL) {
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result == 0) {
err = 0;
continue;
}
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
sector += p_vol->bpb.sectors_per_FAT;
err = 0;
continue;
}
} else {
LOAD_FAT_SECTOR(0);
offset &= p_vol->bpb.bytes_per_sector - 1;
if (offset == (p_vol->bpb.bytes_per_sector - 1)) {
*p_value = *(p_page->p_buf + offset);
if (p_page->option == 1) {
for (err = 0; (pf_u16)err < p_vol->bpb.num_active_FATs; err++) {
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + (pf_u16)err * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
}
}
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, sector + 1, 0, p_vol->bpb.bytes_per_sector);
if (err != 0) { continue; }
p_page->sector = sector + 1;
*p_value += (pf_u16)(*p_page->p_buf) << 8;
} else {
*p_value = ((pf_u16)p_page->p_buf[offset + 1] << 8) + *(p_page->p_buf + offset);
}
}
break;
}
if (err != 0) {
*p_value = -1;
return err;
}
if ((cluster & 0x01) != 0) {
*p_value = *p_value >> 4;
} else {
*p_value &= 0xFFF;
}
return 0;
#undef LOAD_FAT_SECTOR
}

View File

@@ -0,0 +1,158 @@
#define PF_FA_STR_LAYOUT
#define VFiPFCACHE_ReadFATPage PFCACHE_ReadFATPage
#define VFiPFCACHE_UpdateModifiedSector PFCACHE_UpdateModifiedSector
#define VFiPFFAT16_ReadFATEntry PFFAT16_ReadFATEntry
#define VFiPFFAT16_ReadFATEntryPage PFFAT16_ReadFATEntryPage
#define VFiPFFAT16_WriteFATEntry PFFAT16_WriteFATEntry
#define VFiPFFAT16_WriteFATEntryPage PFFAT16_WriteFATEntryPage
#define VFiPFFAT_UpdateFATEntry PFFAT_UpdateFATEntry
#define VFiPFSEC_ReadFAT PFSEC_ReadFAT
#define VFiPFSEC_WriteFAT PFSEC_WriteFAT
#include <private/fa/pf_volume.h>
#include <private/vf/PrFILE2/fatfs/pf_fat.h>
#include <private/vf/PrFILE2/fatfs/pf_fat16.h>
#include <private/vf/PrFILE2/fatfs/pf_sector.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
pf_s32 VFiPFFAT16_ReadFATEntry(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32* p_value) {
pf_u32 fat_offset;
pf_u32 fat_sector;
pf_u16 offset_in_sector;
pf_u8 buf[sizeof(pf_u16)];
pf_s32 err;
pf_u32 current_fat;
pf_s32 result;
fat_offset = cluster * sizeof(pf_u16);
fat_sector = (pf_u16)(p_vol->bpb.active_FAT_sector + ((cluster * sizeof(pf_u16)) >> p_vol->bpb.log2_bytes_per_sector));
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & (0x01 | 0x02 | 0x04);
} else {
current_fat = 1;
}
do {
err = VFiPFSEC_ReadFAT(p_vol, buf, fat_sector, offset_in_sector, 2);
if (err == 0x1000 && p_vol->p_callback != PF_NULL) {
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result == 0) {
continue;
}
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
fat_sector += p_vol->bpb.sectors_per_FAT;
continue;
}
}
if (err != 0) {
*p_value = -1;
return err;
}
} while (err != 0);
*p_value = PF_SWAP_16(*(pf_u16*)buf);
return 0;
}
pf_s32 VFiPFFAT16_WriteFATEntry(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32 value) {
pf_s32 err;
pf_u32 fat_offset;
pf_u16 fat_sector;
pf_u16 offset_in_sector;
pf_u32 current_fat;
pf_s32 result;
pf_u8 buf[sizeof(pf_u16)];
fat_offset = cluster * sizeof(pf_u16);
fat_sector = p_vol->bpb.active_FAT_sector + ((cluster * sizeof(pf_u16)) >> p_vol->bpb.log2_bytes_per_sector);
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
*(pf_u16*)buf = PF_SWAP_16(value);
result = 0;
for (current_fat = 0; current_fat < p_vol->bpb.num_active_FATs; current_fat++) {
err = VFiPFSEC_WriteFAT(p_vol, buf, fat_sector, offset_in_sector, 2);
if (err != 0 && result == 0) {
result = err;
}
fat_sector += p_vol->bpb.sectors_per_FAT;
}
return result;
}
pf_s32 PFFAT16_WriteFATEntryWithBuf(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32 value, PF_CACHE_PAGE* p_page) {
pf_u16 offset_in_sector;
pf_s32 err;
pf_u32 fat_offset;
pf_u16 fat_sector;
pf_u32 current_fat;
pf_s32 result;
fat_offset = cluster * sizeof(pf_u16);
fat_sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector));
offset_in_sector = (pf_u16)(fat_offset & (p_vol->bpb.bytes_per_sector - 1));
err = 0;
result = 0;
if (p_page->sector != fat_sector) {
for (current_fat = 0; current_fat < p_vol->bpb.num_active_FATs; current_fat++) {
err = VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + current_fat * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
if (err != 0 && result == 0) {
result = err;
}
}
p_page->sector = fat_sector;
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, fat_sector, 0, p_vol->bpb.bytes_per_sector);
}
p_page->p_buf[offset_in_sector] = value;
(offset_in_sector + p_page->p_buf)[1] = value >> 8;
if (err != 0) {
result = err;
}
return result;
}
pf_s32 PFFAT16_ReadFATEntryWithBuf(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32* p_value, PF_CACHE_PAGE* p_page) {
pf_u32 sector;
pf_s32 err;
pf_u32 offset;
pf_u32 current_fat;
pf_s32 result;
offset = cluster * sizeof(pf_u16);
sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (offset >> p_vol->bpb.log2_bytes_per_sector));
current_fat = 1;
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & 7;
}
if (p_page->sector != sector) {
if (p_page->option == 1) {
pf_u16 fat;
for (fat = 0; fat < p_vol->bpb.num_active_FATs; fat++) {
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + fat * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
}
}
do {
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, sector, 0, p_vol->bpb.bytes_per_sector);
if (err != 0x1000 || p_vol->p_callback == PF_NULL) {
goto block_22;
}
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result != 0) {
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
sector += p_vol->bpb.sectors_per_FAT;
} else {
goto block_22;
}
}
continue;
block_22:
if (err != 0) {
return err;
}
p_page->sector = sector;
} while (err != 0);
}
offset &= p_vol->bpb.bytes_per_sector - 1;
*p_value = PF_SWAP_16(*((pf_u16*)(p_page->p_buf + offset)));
return 0;
}

View File

@@ -0,0 +1,168 @@
#define PF_FA_STR_LAYOUT
#define VFiPFCACHE_ReadFATPage PFCACHE_ReadFATPage
#define VFiPFCACHE_UpdateModifiedSector PFCACHE_UpdateModifiedSector
#define VFiPFFAT32_ReadFATEntry PFFAT32_ReadFATEntry
#define VFiPFFAT32_ReadFATEntryPage PFFAT32_ReadFATEntryPage
#define VFiPFFAT32_WriteFATEntry PFFAT32_WriteFATEntry
#define VFiPFFAT32_WriteFATEntryPage PFFAT32_WriteFATEntryPage
#define VFiPFFAT_UpdateFATEntry PFFAT_UpdateFATEntry
#define VFiPFSEC_ReadFAT PFSEC_ReadFAT
#define VFiPFSEC_WriteFAT PFSEC_WriteFAT
#include <private/fa/pf_volume.h>
#include <private/vf/PrFILE2/fatfs/pf_fat.h>
#include <private/vf/PrFILE2/fatfs/pf_fat32.h>
#include <private/vf/PrFILE2/fatfs/pf_sector.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
pf_s32 VFiPFFAT32_ReadFATEntry(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32* p_value) {
pf_u32 fat_offset;
pf_u32 fat_sector;
pf_u16 offset_in_sector;
pf_u8 buf[sizeof(pf_u32)];
pf_s32 err;
pf_u32 current_fat;
pf_s32 result;
fat_offset = cluster * sizeof(pf_u32);
fat_sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector));
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & (0x01 | 0x02 | 0x04);
} else {
current_fat = 1;
}
do {
err = VFiPFSEC_ReadFAT(p_vol, buf, fat_sector, offset_in_sector, 4);
if (err == 0x1000 && p_vol->p_callback != PF_NULL) {
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result == 0) {
continue;
}
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
fat_sector += p_vol->bpb.sectors_per_FAT;
continue;
}
}
if (err != 0) {
*p_value = -1;
return err;
}
} while (err != 0);
*p_value = PF_SWAP_32(*(pf_u32*)buf) & 0x0FFFFFFF;
return 0;
}
pf_s32 VFiPFFAT32_WriteFATEntry(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32 value) {
pf_s32 err;
pf_u32 fat_offset;
pf_u32 fat_sector;
pf_u16 offset_in_sector;
pf_u16 current_fat;
pf_s32 result;
pf_u8 buf[sizeof(pf_u32)];
pf_u32 dword;
fat_offset = cluster * sizeof(pf_u32);
fat_sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector));
offset_in_sector = fat_offset & (p_vol->bpb.bytes_per_sector - 1);
err = VFiPFSEC_ReadFAT(p_vol, buf, fat_sector, offset_in_sector, 4);
if (err != 0) {
return err;
}
dword = (value & 0x0FFFFFFF) | (PF_SWAP_32(*(pf_u32*)buf) & 0xF0000000);
*(pf_u32*)buf = PF_SWAP_32(dword);
result = 0;
for (current_fat = 0; current_fat < p_vol->bpb.num_active_FATs; current_fat++) {
err = VFiPFSEC_WriteFAT(p_vol, buf, fat_sector, offset_in_sector, 4);
if (err != 0 && result == 0) {
result = err;
}
fat_sector += p_vol->bpb.sectors_per_FAT;
}
return result;
}
pf_s32 PFFAT32_WriteFATEntryWithBuf(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32 value, PF_CACHE_PAGE* p_page) {
pf_u32 merged_value;
pf_u16 offset_in_sector;
pf_s32 err;
pf_u32 fat_offset;
pf_u32 fat_sector;
pf_u16 current_fat;
pf_s32 result;
fat_offset = cluster * sizeof(pf_u32);
fat_sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (fat_offset >> p_vol->bpb.log2_bytes_per_sector));
offset_in_sector = (pf_u16)(fat_offset & (p_vol->bpb.bytes_per_sector - 1));
err = 0;
result = 0;
if (p_page->sector != fat_sector) {
for (current_fat = 0; current_fat < p_vol->bpb.num_active_FATs; current_fat++) {
err = VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + current_fat * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
if (err != 0 && result == 0) {
result = err;
}
}
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, fat_sector, 0, p_vol->bpb.bytes_per_sector);
if (err != 0) {
return err;
}
p_page->sector = fat_sector;
}
merged_value = (value & 0x0FFFFFFF) | (PF_SWAP_32(*(pf_u32*)&p_page->p_buf[offset_in_sector]) & 0xF0000000);
*(pf_u32*)&p_page->p_buf[offset_in_sector] = PF_SWAP_32(merged_value);
if (err != 0) {
result = err;
}
return result;
}
pf_s32 PFFAT32_ReadFATEntryWithBuf(PF_VOLUME* p_vol, pf_u32 cluster, pf_u32* p_value, PF_CACHE_PAGE* p_page) {
pf_u32 sector;
pf_s32 err;
pf_u32 offset;
pf_u32 current_fat;
pf_s32 result;
offset = cluster * sizeof(pf_u32);
sector = (pf_u16)(p_vol->bpb.active_FAT_sector + (offset >> p_vol->bpb.log2_bytes_per_sector));
current_fat = 1;
if ((p_vol->bpb.ext_flags & 0x80) != 0) {
current_fat = p_vol->bpb.ext_flags & 7;
}
if (p_page->sector != sector) {
if (p_page->option == 1) {
pf_u16 fat;
for (fat = 0; fat < p_vol->bpb.num_active_FATs; fat++) {
VFiPFSEC_WriteFAT(p_vol, p_page->p_buf, p_page->sector + fat * p_vol->bpb.sectors_per_FAT, 0, p_vol->bpb.bytes_per_sector);
}
}
do {
err = VFiPFSEC_ReadFAT(p_vol, p_page->p_buf, sector, 0, p_vol->bpb.bytes_per_sector);
if (err != 0x1000 || p_vol->p_callback == PF_NULL) {
goto block_22;
}
result = ((PF_VOLUME_CB)p_vol->p_callback)(p_vol->last_driver_error);
if (result != 0) {
if (result == 1 && p_vol->bpb.num_active_FATs >= 2 && current_fat < p_vol->bpb.num_active_FATs) {
current_fat++;
sector += p_vol->bpb.sectors_per_FAT;
} else {
goto block_22;
}
}
continue;
block_22:
if (err != 0) {
return err;
}
p_page->sector = sector;
} while (err != 0);
}
offset &= p_vol->bpb.bytes_per_sector - 1;
*p_value = PF_SWAP_32(*((pf_u32*)(p_page->p_buf + offset))) & 0x0FFFFFFF;
return 0;
}

View File

@@ -1,3 +1,4 @@
#define PF_FA_STR_LAYOUT
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/fatfs/pf_dir.h>
#include <private/vf/PrFILE2/fatfs/pf_path.h>
@@ -414,16 +415,24 @@ pf_s32 PFFILE_Cursor_Read(PFFILE_FILE* file, pf_u8* buffer, pf_u32 size, pf_u32*
return 0;
}
static inline void advance_write_cursor(PFFILE_FILE* file, pf_u32 size, pf_u32 sector) {
PF_VOLUME* volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
pf_u32 position = file->cursor.offset_in_sector + size;
pf_u32 next_sector = sector + (position >> volume->bpb.log2_bytes_per_sector);
if (((volume->bpb.bytes_per_sector - 1) & position) != 0) { file->cursor.sector = next_sector; }
else { file->cursor.sector = -1; }
file->cursor.position += size;
if (file->cursor.position > file->p_sfd->dir_entry.file_size) {
file->p_sfd->dir_entry.file_size = file->cursor.position;
}
PFFILE_Cursor_Recalc(file);
PFCLUSTER_UpdateLastAccessCluster(file, next_sector);
}
pf_s32 PFFILE_Cursor_WriteHeadSector(PFFILE_FILE* file, const pf_u8* buffer, pf_u32 size,
pf_u32* size_written) {
pf_s32 error;
pf_u32 success_size;
pf_u32 next_position;
pf_u32 new_position;
pf_u32 current_sector;
pf_u32 written_size;
pf_u32 sector_advance;
pf_u32 next_sector;
PF_VOLUME* volume;
*size_written = 0;
@@ -452,24 +461,7 @@ pf_s32 PFFILE_Cursor_WriteHeadSector(PFFILE_FILE* file, const pf_u8* buffer, pf_
return error;
}
*size_written = success_size;
current_sector = file->cursor.sector;
written_size = success_size;
volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
next_position = file->cursor.offset_in_sector + written_size;
sector_advance = next_position >> volume->bpb.log2_bytes_per_sector;
next_sector = current_sector + sector_advance;
if (((volume->bpb.bytes_per_sector - 1) & next_position) != 0) {
file->cursor.sector = next_sector;
} else {
file->cursor.sector = -1;
}
new_position = file->cursor.position + success_size;
file->cursor.position = new_position;
if (new_position > file->p_sfd->dir_entry.file_size) {
file->p_sfd->dir_entry.file_size = new_position;
}
PFFILE_Cursor_Recalc(file);
PFCLUSTER_UpdateLastAccessCluster(file);
advance_write_cursor(file, success_size, file->cursor.sector);
if (success_size != size) {
return error;
}
@@ -481,7 +473,6 @@ pf_s32 PFFILE_Cursor_WriteBodySectors(PFFILE_FILE* file, const pf_u8* buffer, pf
pf_s32 error;
pf_u32 num_sectors;
pf_u32 success_size;
pf_u32 next_position;
PF_VOLUME* volume;
*size_written = 0;
@@ -506,18 +497,7 @@ pf_s32 PFFILE_Cursor_WriteBodySectors(PFFILE_FILE* file, const pf_u8* buffer, pf
return error;
}
*size_written = success_size;
next_position = file->cursor.offset_in_sector + success_size;
if (((volume->bpb.bytes_per_sector - 1) & next_position) != 0) {
file->cursor.sector += next_position >> volume->bpb.log2_bytes_per_sector;
} else {
file->cursor.sector = -1;
}
file->cursor.position += success_size;
if (file->cursor.position > file->p_sfd->dir_entry.file_size) {
file->p_sfd->dir_entry.file_size = file->cursor.position;
}
PFFILE_Cursor_Recalc(file);
PFCLUSTER_UpdateLastAccessCluster(file);
advance_write_cursor(file, success_size, file->cursor.sector);
if (success_size != size - (size & (volume->bpb.bytes_per_sector - 1))) {
return error;
}
@@ -528,12 +508,6 @@ pf_s32 PFFILE_Cursor_WriteTailSector(PFFILE_FILE* file, const pf_u8* buffer, pf_
pf_u32* size_written) {
pf_s32 error;
pf_u32 success_size;
pf_u32 next_position;
pf_u32 current_sector;
pf_u32 written_size;
pf_u32 sector_advance;
pf_u32 next_sector;
pf_u32 new_position;
PF_VOLUME* volume;
*size_written = 0;
@@ -563,24 +537,7 @@ pf_s32 PFFILE_Cursor_WriteTailSector(PFFILE_FILE* file, const pf_u8* buffer, pf_
return error;
}
*size_written = success_size;
current_sector = file->cursor.sector;
written_size = success_size;
volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
next_position = file->cursor.offset_in_sector + written_size;
sector_advance = next_position >> volume->bpb.log2_bytes_per_sector;
next_sector = current_sector + sector_advance;
if (((volume->bpb.bytes_per_sector - 1) & next_position) != 0) {
file->cursor.sector = next_sector;
} else {
file->cursor.sector = -1;
}
new_position = file->cursor.position + success_size;
file->cursor.position = new_position;
if (new_position > file->p_sfd->dir_entry.file_size) {
file->p_sfd->dir_entry.file_size = new_position;
}
PFFILE_Cursor_Recalc(file);
PFCLUSTER_UpdateLastAccessCluster(file);
advance_write_cursor(file, success_size, file->cursor.sector);
if (success_size != size) {
return error;
}
@@ -697,15 +654,16 @@ PFFILE_SFD* PFFILE_GetSFD(PF_VOLUME* volume, PF_DIR_ENT* entry) {
pf_u32 index = 0;
for (; index < 5; index++, sfd++) {
if ((sfd->stat & 1) == 0 || (sfd->stat & 2) == 0) {
if ((volume_dirs->sfds[index].stat & 1) == 0 ||
((volume_dirs->sfds[index].stat & 1) != 0 && (!volume_dirs->sfds[index].stat & 2) != 0)) {
if (first_free_sfd == PF_NULL) {
first_free_sfd = sfd;
first_free_index = index;
}
} else if (entry->p_vol == sfd->dir_entry.p_vol &&
entry->entry_sector == sfd->dir_entry.entry_sector &&
entry->entry_offset == sfd->dir_entry.entry_offset) {
return sfd;
} else if (entry->p_vol == volume_dirs->sfds[index].dir_entry.p_vol &&
entry->entry_sector == volume_dirs->sfds[index].dir_entry.entry_sector &&
entry->entry_offset == volume_dirs->sfds[index].dir_entry.entry_offset) {
return &volume_dirs->sfds[index];
}
}
@@ -744,22 +702,23 @@ PFFILE_SFD* PFFILE_GetSFD(PF_VOLUME* volume, PF_DIR_ENT* entry) {
pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* filename) {
PF_DIR_ENT parent_entry = *entry;
PFFILE_FFD ffd;
PF_FAT_HINT hint;
PFFILE_FAT_HINT hint;
pf_u32 previous_sectors[2];
pf_u32* previous_sector;
pf_u32 success_size;
pf_u32 entry_position;
pf_u32 num_chars;
pf_u32 num_entries;
pf_s32 num_chars;
pf_u8 num_entries;
pf_u8 checksum;
pf_u32 ordinal;
pf_u32 sector;
pf_u32 success_size;
pf_s32 error;
pf_u8 short_entry_buffer[13];
pf_u8 long_entry_buffer[32];
num_chars = PFSTR_StrNumChar(filename, 1) & 0xFFFF;
if (num_chars + parent_entry.path_len >= 0x104 || num_chars >= 0x100) {
return 1;
}
if (num_chars + parent_entry.path_len > 0x103) { return 1; }
if (num_chars > 0xFF) { return 1; }
PFFAT_InitFFD(&ffd, &hint, parent_entry.p_vol, &parent_entry.start_cluster);
if (((PFFILE_VOLUME_DIRS*)volume)->num_opened_files >= 5) {
return 0x15;
@@ -768,9 +727,7 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file
if (error != 0 && entry->short_name[0] == 0) {
return 1;
}
if (error == 0) {
entry->long_name[0] = 0;
} else {
if (error != 0) {
error = PFENT_AdjustSFN(&parent_entry, entry->short_name);
if (error != 0) {
return error;
@@ -780,8 +737,11 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file
} else {
pf_w_strcpy(entry->long_name, (const pf_u16*)PFSTR_GetStrPos(filename, 1));
}
} else {
entry->long_name[0] = 0;
}
entry->start_cluster = volume->bpb.fat_type == FAT_32 ? 1 : 0;
if (volume->bpb.fat_type == FAT_32) { entry->start_cluster = 1; }
else { entry->start_cluster = 0; }
entry->file_size = 0;
entry->p_vol = volume;
entry->small_letter_flag = 0;
@@ -798,14 +758,16 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file
if (error != 0) {
return error;
}
if ((pf_vol_set.file_settings & 2) != 0) {
if ((pf_vol_set.file_settings & 2) == 2) {
PFPATH_AdjustExtShortName(entry->short_name, entry_position);
}
entry->num_entry_LFNs = num_entries;
sector = entry->entry_sector;
for (ordinal = num_entries; ordinal != 0; ordinal--) {
checksum = PFENT_CalcCheckSum(entry);
previous_sector = previous_sectors;
for (ordinal = num_entries; ordinal >= 1; ordinal--) {
PFENT_storeLFNEntryFieldsToBuf(long_entry_buffer, entry, ordinal,
PFENT_CalcCheckSum(entry), ordinal == num_entries);
checksum, ordinal == num_entries);
error = PFSEC_WriteData(volume, long_entry_buffer, sector, entry->entry_offset,
0x20, &success_size, 0);
if (error != 0) {
@@ -817,8 +779,7 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file
entry->entry_offset += 0x20;
if (entry->entry_offset >= volume->bpb.bytes_per_sector) {
entry->entry_offset = 0;
sector = previous_sectors[0];
previous_sectors[0] = previous_sectors[1];
sector = *previous_sector++;
}
}
entry->entry_sector = sector;
@@ -834,14 +795,25 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file
return PFENT_updateEntry(entry, 1);
}
static inline pf_u32 file_is_open(PF_DIR_ENT* entry) {
pf_s32 index;
for (index = 0; index < 5; index++) {
PFFILE_SFD* sfd = &((PFFILE_VOLUME_DIRS*)entry->p_vol)->sfds[index];
if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 &&
entry->p_vol == sfd->dir_entry.p_vol && entry->entry_sector == sfd->dir_entry.entry_sector &&
entry->entry_offset == sfd->dir_entry.entry_offset) { return 1; }
}
return 0;
}
pf_s32 PFFILE_p_remove(PF_VOLUME* volume, PF_STR* path) {
PF_STR directory;
PF_STR filename;
PF_DIR_ENT entry;
PFFILE_ENT_ITER iter;
PFFILE_VOLUME_DIRS* volume_dirs = (PFFILE_VOLUME_DIRS*)volume;
pf_s32 error;
pf_u32 index;
PFFILE_FAT_HINT hint;
pf_u32 start_cluster;
error = PFPATH_SplitPath(path, &directory, &filename);
if (error != 0) {
@@ -851,39 +823,34 @@ pf_s32 PFFILE_p_remove(PF_VOLUME* volume, PF_STR* path) {
if (error != 0) {
return error;
}
hint = *(PFFILE_FAT_HINT*)iter.ffd.p_hint;
if ((entry.attr & 0x19) != 0) {
return 0xB;
}
for (index = 0; index < 5; index++) {
if ((volume_dirs->sfds[index].stat & 1) != 0 &&
(volume_dirs->sfds[index].stat & 2) != 0 &&
entry.p_vol == volume_dirs->sfds[index].dir_entry.p_vol &&
entry.entry_sector == volume_dirs->sfds[index].dir_entry.entry_sector &&
entry.entry_offset == volume_dirs->sfds[index].dir_entry.entry_offset) {
return 0x13;
}
}
if (file_is_open(&entry) != 0) { return 0x13; }
iter.ffd.p_hint = (PF_FAT_HINT*)&hint;
start_cluster = entry.start_cluster;
error = PFENT_RemoveEntry(&entry, &iter);
if (error != 0) {
return error;
}
return PFFAT_FreeChain(&iter.ffd, entry.start_cluster, 0xFFFFFFFF, entry.file_size);
return PFFAT_FreeChain(&iter.ffd, start_cluster, 0xFFFFFFFF, entry.file_size);
}
static PFFILE_FILE* PFFILE_GetFreeUFD(PF_VOLUME* volume);
pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode,
PFFILE_FILE** result) {
PF_STR directory;
PF_STR filename;
PF_STR directory;
PF_DIR_ENT entry;
PFFILE_ENT_ITER iter;
PFFILE_FFD ffd;
PF_FAT_HINT hint;
PFFILE_FAT_HINT hint;
PFFILE_SFD* sfd;
PFFILE_FILE* file;
pf_s8 normalized_filename[0x200];
pf_u32 num_chars;
pf_u32 index;
pf_u32 success_size;
pf_s32 num_chars;
pf_u16 access_time;
pf_s32 error;
@@ -908,49 +875,7 @@ pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode,
(const pf_u16*)PFSTR_GetStrPos(&filename, 1));
}
PFSTR_SetLocalStr(&filename, normalized_filename);
if ((open_mode & 2) == 0) {
error = PFFILE_createEmptyFile(volume, &entry, &filename);
if (error == 8) {
if ((open_mode & 0x10) != 0) {
return 8;
}
if ((open_mode & 1) != 0) {
for (index = 0; index < 5; index++) {
if ((((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].stat & 3) == 3 &&
entry.p_vol ==
((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].dir_entry.p_vol &&
entry.entry_sector ==
((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].dir_entry.entry_sector &&
entry.entry_offset ==
((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].dir_entry.entry_offset) {
return 8;
}
}
}
if ((entry.attr & 1) != 0 &&
((open_mode & 1) != 0 || (open_mode & 4) != 0 || (open_mode & 8) != 0)) {
return 0xA;
}
if ((entry.attr & 0x10) != 0) {
return 0x17;
}
if ((open_mode & 1) != 0) {
PFFAT_InitFFD(&ffd, &hint, entry.p_vol, &entry.start_cluster);
if (entry.start_cluster > 1 && entry.start_cluster != 0xFFFFFFFF &&
entry.file_size != 0) {
PFFAT_FreeChain(&ffd, entry.start_cluster, 0xFFFFFFFF, entry.file_size);
}
entry.start_cluster = 0;
entry.file_size = 0;
PFENT_getcurrentDateTimeForEnt(&entry.modify_date, &entry.modify_time);
entry.access_date = entry.modify_date;
} else {
PFENT_getcurrentDateTimeForEnt(&entry.access_date, &access_time);
}
} else if (error != 0) {
return error;
}
} else {
if ((open_mode & 2) != 0) {
PFFAT_InitFFD(&ffd, &hint, entry.p_vol, &entry.start_cluster);
error = PFENT_findEntry(&ffd, &entry, 0, &filename, 0x7F, 0);
if (error != 0) {
@@ -963,37 +888,61 @@ pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode,
return 0x17;
}
PFENT_getcurrentDateTimeForEnt(&entry.access_date, &access_time);
} else {
error = PFFILE_createEmptyFile(volume, &entry, &filename);
if (error == 8) {
if ((open_mode & 0x10) != 0) {
return 8;
}
if ((open_mode & 1) != 0) {
if (file_is_open(&entry) != 0) { return 8; }
}
if ((entry.attr & 1) != 0 &&
((open_mode & 1) != 0 || (open_mode & 4) != 0 || (open_mode & 8) != 0)) {
return 0xA;
}
if ((entry.attr & 0x10) != 0) {
return 0x17;
}
if ((open_mode & 1) != 0) {
if (entry.start_cluster >= 2 && entry.start_cluster != 0xFFFFFFFF &&
entry.file_size != 0) {
PFFAT_FreeChain(&iter.ffd, entry.start_cluster, 0xFFFFFFFF, entry.file_size);
}
entry.start_cluster = 0;
entry.file_size = 0;
PFENT_getcurrentDateTimeForEnt(&entry.modify_date, &entry.modify_time);
entry.access_date = entry.modify_date;
} else {
PFENT_getcurrentDateTimeForEnt(&entry.access_date, &access_time);
}
} else if (error != 0) {
return error;
}
}
volume = entry.p_vol;
sfd = PFFILE_GetSFD(volume, &entry);
if (sfd == PF_NULL) {
return 0x15;
}
file = PF_NULL;
for (index = 0; index < 5; index++) {
if ((((PFFILE_VOLUME_DIRS*)volume)->ufds[index].stat & 1) == 0) {
file = &((PFFILE_VOLUME_DIRS*)volume)->ufds[index];
break;
}
}
file = PFFILE_GetFreeUFD(volume);
if (file == PF_NULL) {
return 0x16;
}
file->p_sfd = sfd;
file->stat = 1;
file->open_mode = open_mode;
file->last_access_data.state.last_access_chain_index = 0;
file->last_access_data.state.last_error = 0;
file->lock_count = 0;
PFFAT_InitHint(&file->hint);
file->cursor.position = 0;
file->cursor.sector = 0xFFFFFFFF;
file->cursor.position = 0;
PFFILE_Cursor_Recalc(file);
if ((open_mode & 1) != 0) {
sfd->stat |= 4;
file->p_sfd->stat |= 4;
}
if ((open_mode & 4) != 0) {
file->cursor.position = entry.file_size;
if ((file->open_mode & 4) != 0) {
file->cursor.position = file->p_sfd->dir_entry.file_size;
PFFILE_Cursor_Recalc(file);
}
sfd->handler_count++;
@@ -1002,7 +951,26 @@ pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode,
}
pf_s32 PFFILE_p_fread(PF_VOLUME* volume, pf_u8* buffer, pf_u32 size, pf_u32 count,
PFFILE_FILE* file, pf_u32* count_read);
PFFILE_FILE* file, pf_u32* count_read) {
pf_u32 bytes_read = 0;
pf_s32 error;
*count_read = 0;
if ((file->open_mode & 8) == 0 &&
((file->open_mode & 1) != 0 || (file->open_mode & 4) != 0)) {
return 0xA;
}
if ((file->p_sfd->lock.mode & 3) != 0 && file->lock_count == 0) {
return 0x19;
}
if (file->cursor.position >= file->p_sfd->dir_entry.file_size) {
return 0x1C;
}
error = PFFILE_Cursor_Read(file, buffer, size * count, &bytes_read);
*count_read = bytes_read / size;
error &= (-error | error) >> 31;
return error;
}
pf_s32 PFFILE_p_fwrite(PF_VOLUME* volume, const pf_u8* buffer, pf_u32 size, pf_u32 count,
PFFILE_FILE* file, pf_u32* count_written) {
@@ -1028,32 +996,30 @@ pf_s32 PFFILE_p_fwrite(PF_VOLUME* volume, const pf_u8* buffer, pf_u32 size, pf_u
if (file->cursor.position > file->p_sfd->dir_entry.file_size) {
remaining = file->cursor.position - file->p_sfd->dir_entry.file_size;
file->cursor.position = file->p_sfd->dir_entry.file_size;
PFFILE_Cursor_Recalc(file);
file->cursor.file_sector_index = file->cursor.position >> volume->bpb.log2_bytes_per_sector;
file->cursor.offset_in_sector = file->cursor.position & (volume->bpb.bytes_per_sector - 1);
error = PFCACHE_AllocateDataPage(volume, 0xFFFFFFFF, &page, &allocation_option);
if (error != 0) {
return error;
}
pf_memset(page->p_buf, 0, volume->bpb.bytes_per_sector);
while (remaining != 0) {
if (remaining <= volume->bpb.bytes_per_sector) {
if (remaining > volume->bpb.bytes_per_sector) {
error = PFFILE_Cursor_Write(file, page->p_buf, volume->bpb.bytes_per_sector, &bytes_written);
if (error != 0) { return error; }
} else {
error = PFFILE_Cursor_Write(file, page->p_buf, remaining, &bytes_written);
if (error != 0) {
return error;
}
if (error != 0) { return error; }
break;
}
error = PFFILE_Cursor_Write(file, page->p_buf, volume->bpb.bytes_per_sector,
&bytes_written);
if (error != 0) {
return error;
}
remaining -= volume->bpb.bytes_per_sector;
}
PFCACHE_FreeDataPage(volume, page);
}
error = PFFILE_Cursor_Write(file, buffer, size * count, &bytes_written);
*count_written = bytes_written / size;
return error;
if (error != 0) { return error; }
return 0;
}
pf_s32 PFFILE_p_fappend(PFFILE_FILE* file, pf_u32 size, pf_u32* size_appended) {
@@ -1126,10 +1092,8 @@ pf_s32 PFFILE_p_combine(PF_VOLUME* volume, PF_STR* first_path, PF_STR* second_pa
PFFILE_ENT_ITER second_iter_copy;
PF_DIR_ENT first_entry;
PF_DIR_ENT second_entry;
PF_FAT_HINT first_hint;
PF_FAT_HINT second_hint;
pf_u32 index;
pf_s32 found;
PFFILE_FAT_HINT first_hint;
PFFILE_FAT_HINT second_hint;
pf_s32 error;
error = PFENT_ITER_GetEntryOfPath(&first_iter, &first_entry, volume, first_path, 0);
@@ -1146,41 +1110,12 @@ pf_s32 PFFILE_p_combine(PF_VOLUME* volume, PF_STR* first_path, PF_STR* second_pa
if ((first_entry.attr & 1) != 0 || (second_entry.attr & 1) != 0) {
return 0x18;
}
found = 0;
for (index = 0; index < 5; index++) {
PFFILE_SFD* sfd = &((PFFILE_VOLUME_DIRS*)first_entry.p_vol)->sfds[index];
if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 &&
first_entry.p_vol == sfd->dir_entry.p_vol &&
first_entry.entry_sector == sfd->dir_entry.entry_sector &&
first_entry.entry_offset == sfd->dir_entry.entry_offset) {
found = 1;
break;
}
}
if (found != 0) {
return 0x13;
}
found = 0;
for (index = 0; index < 5; index++) {
PFFILE_SFD* sfd = &((PFFILE_VOLUME_DIRS*)second_entry.p_vol)->sfds[index];
if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 &&
second_entry.p_vol == sfd->dir_entry.p_vol &&
second_entry.entry_sector == sfd->dir_entry.entry_sector &&
second_entry.entry_offset == sfd->dir_entry.entry_offset) {
found = 1;
break;
}
}
if (found != 0) {
return 0x13;
}
if (file_is_open(&first_entry) != 0 || file_is_open(&second_entry) != 0) { return 0x13; }
if (first_entry.entry_sector == second_entry.entry_sector &&
first_entry.entry_offset == second_entry.entry_offset) {
return 0xA;
}
if (0xFFFFFFFF - second_entry.file_size < first_entry.file_size) {
if (0xFFFFFFFF - first_entry.file_size < second_entry.file_size) {
return 0x25;
}
PFFAT_InitHint(&first_hint);
@@ -1204,24 +1139,20 @@ pf_s32 PFFILE_p_combine(PF_VOLUME* volume, PF_STR* first_path, PF_STR* second_pa
pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destination_path,
pf_u32 split_size) {
PF_STR destination_directory;
PF_STR destination_filename;
PF_STR destination_directory;
PF_DIR_ENT source_entry;
PF_DIR_ENT source_entry_copy;
PF_DIR_ENT destination_entry;
PF_DIR_ENT source_entry_copy;
PFFILE_ENT_ITER source_iter;
PFFILE_ENT_ITER destination_iter;
PFFILE_ENT_ITER destination_file_iter;
PFFILE_FFD source_ffd;
PFFILE_FFD destination_ffd;
PF_FAT_HINT source_hint;
PF_FAT_HINT destination_hint;
PFFILE_FAT_HINT source_hint;
PFFILE_FAT_HINT destination_hint;
pf_s8 normalized_filename[0x200];
pf_u32 original_start_cluster;
pf_u32 original_size;
pf_u32 index;
pf_u16 current_time;
pf_u32 original_start_cluster;
pf_s32 error;
pf_s32 divide_error;
error = PFENT_ITER_GetEntryOfPath(&source_iter, &source_entry, volume, source_path, 0);
if (error != 0) {
@@ -1233,17 +1164,7 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati
if ((source_entry.attr & 1) != 0) {
return 0x18;
}
for (index = 0; index < 5; index++) {
if ((((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].stat & 3) == 3 &&
source_entry.p_vol ==
((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].dir_entry.p_vol &&
source_entry.entry_sector ==
((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].dir_entry.entry_sector &&
source_entry.entry_offset ==
((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].dir_entry.entry_offset) {
return 0x13;
}
}
if (file_is_open(&source_entry) != 0) { return 0x13; }
if (source_entry.file_size == 0) {
return 0xA;
}
@@ -1255,7 +1176,7 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati
return 1;
}
if (PFSTR_GetCodeMode(&destination_filename) == 2) {
if ((PFSTR_StrNumChar(&destination_filename, 1) & 0xFFFF) > 0xFF) {
if ((pf_s32)(PFSTR_StrNumChar(&destination_filename, 1) & 0xFFFF) > 0xFF) {
return 1;
}
PFPATH_transformFromUnicodeToNormal(
@@ -1274,13 +1195,13 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati
if (error != 0) {
return error;
}
PFFAT_InitHint(&destination_hint);
PFFAT_InitFFD(&destination_ffd, &destination_hint, volume, &destination_entry.start_cluster);
PFFAT_InitHint(&source_hint);
PFFAT_InitFFD(&source_ffd, &source_hint, volume, &source_entry.start_cluster);
PFFAT_InitFFD(&source_iter.ffd, &source_hint, volume, &source_entry.start_cluster);
PFFAT_InitHint(&destination_hint);
PFFAT_InitFFD(&destination_iter.ffd, &destination_hint, volume, &destination_entry.start_cluster);
pf_memcpy(&source_entry_copy, &source_entry, sizeof(source_entry_copy));
original_start_cluster = source_entry.start_cluster;
original_size = source_entry.file_size;
original_start_cluster = source_entry.start_cluster;
PFENT_getcurrentDateTimeForEnt(&source_entry.modify_date, &source_entry.modify_time);
source_entry.access_date = source_entry.modify_date;
if (split_size == 0) {
@@ -1288,32 +1209,30 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati
}
source_entry.file_size = split_size;
error = PFENT_updateEntry(&source_entry, 1);
if (error == 0 &&
((((PFFILE_VOLUME_DIRS*)volume)->cache_control & 4) == 0 ||
PFCACHE_FlushDataCacheSpecific(volume, 0) == 0)) {
error = PFCLUSTER_DivideFile(&source_iter, &destination_iter, &source_entry_copy,
&destination_entry, split_size);
if (error == 0) {
destination_entry.create_time = source_entry.modify_time;
destination_entry.create_date = source_entry.modify_date;
destination_entry.modify_time = source_entry.modify_time;
destination_entry.modify_date = source_entry.modify_date;
destination_entry.access_date = source_entry.access_date;
destination_entry.attr = source_entry.attr;
error = PFENT_updateEntry(&destination_entry, 1);
return error & (-error | error) >> 31;
}
PFCACHE_FlushFATCache(volume);
source_entry.start_cluster = original_start_cluster;
source_entry.file_size = original_size;
PFENT_updateEntry(&source_entry, 1);
error = PFENT_ITER_GetEntryOfPath(&destination_file_iter, &destination_entry, volume,
destination_path, 0);
if (error == 0) {
PFENT_RemoveEntry(&destination_entry, &destination_file_iter);
}
if (error != 0) { return error; }
if ((((PFFILE_VOLUME_DIRS*)volume)->cache_control & 4) != 0) {
error = PFCACHE_FlushDataCacheSpecific(volume, 0);
if (error != 0) { return error; }
}
return error;
error = PFCLUSTER_DivideFile(&source_iter, &destination_iter, &source_entry_copy,
&destination_entry, split_size);
divide_error = error;
if (error != 0) {
PFCACHE_FlushFATCache(volume);
source_entry.file_size = original_size;
source_entry.start_cluster = original_start_cluster;
PFENT_updateEntry(&source_entry, 1);
PFENT_ITER_GetEntryOfPath(&destination_iter, &destination_entry, volume,
destination_path, 0);
PFENT_RemoveEntry(&destination_entry, &destination_iter);
return divide_error;
}
destination_entry.modify_date = source_entry.modify_date;
destination_entry.modify_time = source_entry.modify_time;
destination_entry.access_date = source_entry.access_date;
destination_entry.attr = source_entry.attr;
error = PFENT_updateEntry(&destination_entry, 1);
return error & (-error | error) >> 31;
}
pf_s32 PFFILE_p_cinsert(PF_VOLUME* volume, PF_STR* path, pf_u32 cluster_index,
@@ -1403,20 +1322,15 @@ pf_s32 PFFILE_p_cdelete(PF_VOLUME* volume, PF_STR* path, pf_u32 cluster_index,
pf_s32 PFFILE_p_flock(PFFILE_FILE* file, pf_u32 mode) {
if ((mode & 3) != 0) {
if ((file->p_sfd->lock.mode & 3) != 0 && (mode & 0x10) != 0) {
if ((mode & 1) != 0) {
if ((file->p_sfd->lock.mode & 2) != 0) {
return 0x27;
}
} else if ((mode & 2) != 0 && (file->p_sfd->lock.mode & 1) != 0) {
return 0x27;
}
if (file->p_sfd->lock.owner != 0 && file->p_sfd->lock.owner != (PF_FILE*)file) {
if ((file->p_sfd->lock.mode & 3) != 0 && (mode & 8) != 0) {
if (((mode & 1) != 0 && (file->p_sfd->lock.mode & 2) != 0) ||
((mode & 2) != 0 && (file->p_sfd->lock.mode & 1) != 0) ||
(file->p_sfd->lock.owner != 0 && file->p_sfd->lock.owner != (PF_FILE*)file)) {
return 0x27;
}
}
if ((mode & 1) != 0) {
if (file->p_sfd->lock.count == 0 || (file->p_sfd->lock.mode & 2) == 0) {
if (file->p_sfd->lock.count == 0 || (file->p_sfd->lock.mode & 2) != 0) {
file->p_sfd->lock.wcount++;
PF_LockFile((PF_FILE*)file, 0);
file->p_sfd->lock.wcount--;
@@ -1432,7 +1346,7 @@ pf_s32 PFFILE_p_flock(PFFILE_FILE* file, pf_u32 mode) {
}
file->p_sfd->lock.count++;
file->lock_count++;
return 0;
goto complete;
}
if (file->lock_count == 0 || file->p_sfd->lock.count == 0) {
return 0x27;
@@ -1440,23 +1354,14 @@ pf_s32 PFFILE_p_flock(PFFILE_FILE* file, pf_u32 mode) {
if ((file->p_sfd->lock.mode & 2) != 0 && file->p_sfd->lock.owner != (PF_FILE*)file) {
return 0x27;
}
if ((file->p_sfd->lock.mode & 1) != 0) {
file->p_sfd->lock.count -= file->lock_count;
file->lock_count = 0;
if (file->p_sfd->lock.count == 0) {
PF_UnLockFile((PF_FILE*)file);
}
file->p_sfd->lock.mode &= ~3;
} else {
if (file->p_sfd->lock.owner != (PF_FILE*)file) {
return 0x27;
}
file->p_sfd->lock.count = 0;
file->lock_count = 0;
file->p_sfd->lock.owner = 0;
file->lock_count--;
file->p_sfd->lock.count--;
if (file->p_sfd->lock.count == 0) {
PF_UnLockFile((PF_FILE*)file);
if ((file->p_sfd->lock.mode & 2) != 0) { file->p_sfd->lock.owner = 0; }
file->p_sfd->lock.mode &= ~3;
}
complete:
return 0;
}
@@ -1708,10 +1613,12 @@ close_file_complete:
pf_s32 PFFILE_fread(pf_u8* buffer, pf_u32 size, pf_u32 count,
PFFILE_FILE* file, pf_u32* count_read) {
PF_VOLUME* volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
PF_VOLUME* volume;
pf_s32 error;
pf_u32 completed_count;
*count_read = 0;
volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol;
error = PFVOL_CheckForRead(volume);
if (error != 0) {
pf_vol_set.last_error = error;
@@ -1724,7 +1631,8 @@ pf_s32 PFFILE_fread(pf_u8* buffer, pf_u32 size, pf_u32 count,
return 0x26;
}
((PFFILE_VOLUME_DIRS*)volume)->cache_signature = file;
error = PFFILE_p_fread(volume, buffer, size, count, file, count_read);
error = PFFILE_p_fread(volume, buffer, size, count, file, &completed_count);
*count_read = completed_count;
((PFFILE_VOLUME_DIRS*)volume)->cache_signature = PF_NULL;
if (error != 0) {
pf_vol_set.last_error = error;
@@ -1869,8 +1777,8 @@ pf_s32 PFFILE_fsetclstlink(PFFILE_FILE* file, pf_u32 mode,
file->p_sfd->ffd.cluster_link.interval_offset = 0;
file->p_sfd->ffd.cluster_link.position = 0;
file->p_sfd->ffd.cluster_link.save_index = 0;
if (file->p_sfd->dir_entry.file_size != 0 && settings->link_max != 0) {
settings->buffer[0] = *file->p_sfd->ffd.p_start_cluster;
if (file->p_sfd->dir_entry.file_size != 0 && file->p_sfd->ffd.cluster_link.max_count != 0) {
file->p_sfd->ffd.cluster_link.buffer[0] = *file->p_sfd->ffd.p_start_cluster;
file->p_sfd->ffd.cluster_link.position++;
}
if (file->p_sfd->ffd.p_hint != PF_NULL) {
@@ -2217,25 +2125,3 @@ pf_s32 PFFILE_flock(PFFILE_FILE* file, pf_u32 mode) {
}
return error;
}
pf_s32 PFFILE_p_fread(PF_VOLUME* volume, pf_u8* buffer, pf_u32 size, pf_u32 count,
PFFILE_FILE* file, pf_u32* count_read) {
pf_u32 bytes_read = 0;
pf_s32 error;
*count_read = 0;
if ((file->open_mode & 8) == 0 &&
((file->open_mode & 1) != 0 || (file->open_mode & 4) != 0)) {
return 0xA;
}
if ((file->p_sfd->lock.mode & 3) != 0 && file->lock_count == 0) {
return 0x19;
}
if (file->cursor.position >= file->p_sfd->dir_entry.file_size) {
return 0x1C;
}
error = PFFILE_Cursor_Read(file, buffer, size * count, &bytes_read);
*count_read = bytes_read / size;
error &= (-error | error) >> 31;
return error;
}

View File

@@ -0,0 +1,56 @@
#include <private/fa/pf_system.h>
#include <private/vf/PrFILE2/fatfs/pf_entry.h>
typedef struct PFFILELOCK_SFD {
pf_u8 descriptor[0x3c];
PF_DIR_ENT dir_entry;
pf_u16 lock_mode;
pf_u16 lock_count;
pf_u32 writer_count;
void* owner;
pf_s32 resource;
OSSemaphore semaphore;
} PFFILELOCK_SFD;
typedef struct PFFILELOCK_FILE {
pf_u32 stat;
pf_u32 open_mode;
PFFILELOCK_SFD* p_sfd;
} PFFILELOCK_FILE;
typedef struct PFFILELOCK_SEMAPHORE_PARAM {
pf_u32 initial_count;
pf_u32 max_count;
OSSemaphore* semaphore;
} PFFILELOCK_SEMAPHORE_PARAM;
extern pf_s32 pfk_create_semaphore(PFFILELOCK_SEMAPHORE_PARAM*);
extern pf_s32 pfk_get_semaphore(pf_s32);
extern pf_s32 pfk_release_semaphore(pf_s32);
extern pf_s32 pfk_delete_semaphore(pf_s32);
void PF_InitLockFile(void) {
pf_sys_set.flock_count = 0;
}
pf_s32 PF_LockFile(PFFILELOCK_FILE* p_file) {
pf_s32 result = -1;
PFFILELOCK_SEMAPHORE_PARAM param;
if (p_file->p_sfd->lock_count == 0 && p_file->p_sfd->resource == 0) {
if (pf_sys_set.flock_count < -1U) {
param.initial_count = 1;
param.max_count = 1;
param.semaphore = &p_file->p_sfd->semaphore;
p_file->p_sfd->resource = pfk_create_semaphore(&param);
result = 0;
++pf_sys_set.flock_count;
} else result = -1;
}
pfk_get_semaphore(p_file->p_sfd->resource);
return result;
}
pf_s32 PF_UnLockFile(PFFILELOCK_FILE* p_file) {
pfk_release_semaphore(p_file->p_sfd->resource);
if (p_file->p_sfd->lock_count == 0 && p_file->p_sfd->writer_count == 0 && pf_sys_set.flock_count != 0) {
pfk_delete_semaphore(p_file->p_sfd->resource);
p_file->p_sfd->resource = 0;
--pf_sys_set.flock_count;
}
return 0;
}

View File

@@ -0,0 +1,13 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFFILE_finfo PFFILE_finfo
#include <private/vf/PrFILE2/standard/pf_finfo.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
pf_int32 pf2_finfo(PF_FILE* p_file, PF_INFO* p_info) {
pf_s32 err = VFiPFFILE_finfo(p_file, p_info);
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,41 @@
#include <revolution/fa.h>
typedef struct PFF2_STR {
const s8* p_head;
const s8* p_tail;
const s8* p_current;
u32 code_mode;
} PFF2_STR;
typedef struct PFF2_VOL_SET {
u8 reserved[0x40];
s32 last_error;
} PFF2_VOL_SET;
extern PFF2_VOL_SET pf_vol_set;
extern s32 PFAPI_ParseOpenModeString(const char* mode_str);
extern s32 PFSTR_InitStr(PFF2_STR* path, const s8* text, u32 code_mode);
extern s32 PFFILE_fopen(PFF2_STR* path, s32 mode, FAFILE** result);
extern FAFILE* PFAPI_convertReturnValue2NULL(s32 err, FAFILE* p_stream);
FAFILE* pf2_fopen(const char* path, const char* mode) {
u32 open_mode;
FAFILE* p_file;
PFF2_STR path_str;
s32 err;
open_mode = PFAPI_ParseOpenModeString(mode);
if (open_mode == 0) {
pf_vol_set.last_error = 10;
p_file = NULL;
} else {
err = PFSTR_InitStr(&path_str, (const s8*)path, 1);
if (err == 0) {
err = PFFILE_fopen(&path_str, open_mode, &p_file);
} else {
pf_vol_set.last_error = err;
}
p_file = PFAPI_convertReturnValue2NULL(err, p_file);
}
return p_file;
}

View File

@@ -0,0 +1,13 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFVOL_format PFVOL_format
#include <private/vf/PrFILE2/standard/pf_format.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
pf_int32 pf2_format(pf_ch8 drive, const pf_ch8* param) {
pf_s32 err = VFiPFVOL_format(drive, (pf_u8*)param);
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,10 @@
#include <revolution/fa.h>
extern s32 PFFILE_fseek(FAFILE* stream, s32 offset, int origin);
extern s32 PFAPI_convertReturnValue(s32 err);
FAError pf2_fseek(FAFILE* stream, s32 offset, int origin) {
s32 err = PFFILE_fseek(stream, offset, origin);
err = PFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,32 @@
#include <revolution/fa.h>
typedef struct PFF2_STR {
const s8* p_head;
const s8* p_tail;
const s8* p_current;
u32 code_mode;
} PFF2_STR;
typedef struct PFF2_VOL_SET {
u8 reserved[0x40];
s32 last_error;
} PFF2_VOL_SET;
extern PFF2_VOL_SET pf_vol_set;
extern s32 PFSTR_InitStr(PFF2_STR* path, const s8* text, u32 code_mode);
extern s32 PFDIR_fsfirst(PFF2_STR* path, u8 attributes, FADta* data);
extern s32 PFAPI_convertReturnValue(s32 err);
FAError pf2_fsfirst(const char* dirName, u8 attr, FADta* dta) {
s32 err;
PFF2_STR path_str;
err = PFSTR_InitStr(&path_str, (const s8*)dirName, 1);
if (err == 0) {
err = PFDIR_fsfirst(&path_str, attr, dta);
} else {
pf_vol_set.last_error = err;
}
err = PFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,10 @@
#include <revolution/fa.h>
extern s32 PFDIR_fsnext(FADta* data);
extern s32 PFAPI_convertReturnValue(s32 err);
FAError pf2_fsnext(FADta* dta) {
s32 err = PFDIR_fsnext(dta);
err = PFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,32 @@
#include <revolution/fa.h>
typedef struct PFF2_STR {
const s8* p_head;
const s8* p_tail;
const s8* p_current;
u32 code_mode;
} PFF2_STR;
typedef struct PFF2_VOL_SET {
u8 reserved[0x40];
s32 last_error;
} PFF2_VOL_SET;
extern PFF2_VOL_SET pf_vol_set;
extern s32 PFSTR_InitStr(PFF2_STR* path, const s8* text, u32 code_mode);
extern s32 PFDIR_fstat(PFF2_STR* path, FAFileStat* file_stat);
extern s32 PFAPI_convertReturnValue(s32 err);
FAError pf2_fstat(const char* fileName, FAFileStat* stat) {
s32 err;
PFF2_STR path_str;
err = PFSTR_InitStr(&path_str, (const s8*)fileName, 1);
if (err == 0) {
err = PFDIR_fstat(&path_str, stat);
} else {
pf_vol_set.last_error = err;
}
err = PFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,13 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFVOL_getdev PFVOL_getdev
#include <private/vf/PrFILE2/standard/pf_getdev.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
pf_int32 pf2_devinf(pf_ch8 drv_char, PF_DEV_INF* dev_inf) {
pf_s32 err = VFiPFVOL_getdev(drv_char, dev_inf);
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,19 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFFATFS_initializeFATFS PFFATFS_initializeFATFS
#define VFiPFSYS_initializeSYS PFSYS_initializeSYS
#include <private/vf/PrFILE2/standard/pf_init_prfile2.h>
#include <private/vf/PrFILE2/fatfs/pf_fatfs.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
#include <private/vf/PrFILE2/system/pf_system.h>
pf_int32 pf2_init_prfile2(pf_s32 config, void* param) {
pf_s32 err = VFiPFFATFS_initializeFATFS(config, param);
if (err == 0) {
VFiPFSYS_initializeSYS();
}
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,31 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFDIR_mkdir PFDIR_mkdir
#define VFiPFSTR_InitStr PFSTR_InitStr
#include <private/vf/PrFILE2/standard/pf_mkdir.h>
typedef struct PFAPI_GLOBAL_STATE {
pf_u8 volume_state[0x40];
pf_s32 last_error;
} PFAPI_GLOBAL_STATE;
extern PFAPI_GLOBAL_STATE pf_vol_set;
#include <private/vf/PrFILE2/fatfs/pf_dir.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
#include <private/vf/PrFILE2/common/pf_str.h>
pf_int32 pf2_mkdir(const pf_ch8* sPath) {
pf_s32 err;
PF_STR path_str;
err = VFiPFSTR_InitStr(&path_str, (pf_s8*)sPath, 1U);
if (err == 0) {
err = VFiPFDIR_mkdir(&path_str);
} else {
pf_vol_set.last_error = err;
}
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,31 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFFILE_remove PFFILE_remove
#define VFiPFSTR_InitStr PFSTR_InitStr
#include <private/vf/PrFILE2/standard/pf_remove.h>
typedef struct PFAPI_GLOBAL_STATE {
pf_u8 volume_state[0x40];
pf_s32 last_error;
} PFAPI_GLOBAL_STATE;
extern PFAPI_GLOBAL_STATE pf_vol_set;
#include <private/vf/PrFILE2/fatfs/pf_file.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
#include <private/vf/PrFILE2/common/pf_str.h>
pf_int32 pf2_remove(const pf_ch8* path) {
pf_s32 err;
PF_STR path_str;
err = VFiPFSTR_InitStr(&path_str, (pf_s8*)path, 1U);
if (err == 0) {
err = VFiPFFILE_remove(&path_str);
} else {
pf_vol_set.last_error = err;
}
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,31 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFDIR_rmdir PFDIR_rmdir
#define VFiPFSTR_InitStr PFSTR_InitStr
#include <private/vf/PrFILE2/standard/pf_rmdir.h>
typedef struct PFAPI_GLOBAL_STATE {
pf_u8 volume_state[0x40];
pf_s32 last_error;
} PFAPI_GLOBAL_STATE;
extern PFAPI_GLOBAL_STATE pf_vol_set;
#include <private/vf/PrFILE2/fatfs/pf_dir.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
#include <private/vf/PrFILE2/common/pf_str.h>
pf_int32 pf2_rmdir(const pf_ch8* sPath) {
pf_s32 err;
PF_STR path_str;
err = VFiPFSTR_InitStr(&path_str, (pf_s8*)sPath, 1U);
if (err == 0) {
err = VFiPFDIR_rmdir(&path_str);
} else {
pf_vol_set.last_error = err;
}
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,216 @@
#define PF_FA_STR_LAYOUT
#define VFiPFCACHE_AllocateDataPage PFCACHE_AllocateDataPage
#define VFiPFCACHE_ReadDataNumSector PFCACHE_ReadDataNumSector
#define VFiPFCACHE_ReadDataPage PFCACHE_ReadDataPage
#define VFiPFCACHE_ReadDataPageAndFlushIfNeeded PFCACHE_ReadDataPageAndFlushIfNeeded
#define VFiPFCACHE_ReadFATPage PFCACHE_ReadFATPage
#define VFiPFCACHE_SearchDataCache PFCACHE_SearchDataCache
#define VFiPFCACHE_UpdateModifiedSector PFCACHE_UpdateModifiedSector
#define VFiPFCACHE_WriteDataNumSectorAndFreeIfNeeded PFCACHE_WriteDataNumSectorAndFreeIfNeeded
#define VFiPFCACHE_WriteDataPage PFCACHE_WriteDataPage
#define VFiPFCACHE_WriteFATPage PFCACHE_WriteFATPage
#define VFiPFDRV_IsInserted PFDRV_IsInserted
#define VFiPFDRV_IsWProtected PFDRV_IsWProtected
#define VFiPFSEC_ReadData PFSEC_ReadData
#define VFiPFSEC_ReadDataSector PFSEC_ReadDataSector
#define VFiPFSEC_ReadFAT PFSEC_ReadFAT
#define VFiPFSEC_WriteData PFSEC_WriteData
#define VFiPFSEC_WriteDataSector PFSEC_WriteDataSector
#define VFiPFSEC_WriteFAT PFSEC_WriteFAT
#define VFipf_memcpy pf_memcpy
#include <private/fa/pf_volume.h>
#include <private/vf/PrFILE2/fatfs/pf_cache.h>
#include <private/vf/PrFILE2/common/pf_clib.h>
#include <private/vf/PrFILE2/driver/pf_driver.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
pf_s32 VFiPFSEC_ReadFAT(PF_VOLUME* p_vol, pf_u8* p_buf, pf_u32 sector, pf_u16 offset, pf_u16 size) {
PF_CACHE_PAGE* p_page;
pf_s32 err;
if ((p_vol->flags & 0x01) == 0 || VFiPFDRV_IsInserted(p_vol) == PF_FALSE) {
return 9;
}
if (sector >= p_vol->bpb.total_sectors || offset >= p_vol->bpb.bytes_per_sector || offset + size > p_vol->bpb.bytes_per_sector) {
return 10;
}
err = VFiPFCACHE_ReadFATPage(p_vol, sector, &p_page);
if (err != 0) {
return err;
}
VFipf_memcpy(p_buf, &p_page->p_buf[offset], size);
return 0;
}
pf_s32 VFiPFSEC_ReadData(PF_VOLUME* p_vol, pf_u8* p_buf, pf_u32 sector, pf_u16 offset, pf_u32 size, pf_u32* p_success_size, pf_u32 set_sig) {
PF_CACHE_PAGE* p_page;
pf_u32 num_success;
pf_u32 num_sector;
pf_u32 adjust_sector;
pf_u32 rest_sector;
pf_s32 err;
*p_success_size = 0;
if ((p_vol->flags & 0x01) == 0 || VFiPFDRV_IsInserted(p_vol) == PF_FALSE) {
return 9;
}
if ((sector >= p_vol->bpb.total_sectors || offset >= p_vol->bpb.bytes_per_sector || offset + size > p_vol->bpb.bytes_per_sector) && offset != 0) {
return 10;
}
if (offset != 0 || size < p_vol->bpb.bytes_per_sector) {
err = VFiPFCACHE_ReadDataPage(p_vol, sector, &p_page, set_sig);
if (err != 0) {
return err;
}
VFipf_memcpy(p_buf, &p_page->p_buf[offset], size);
*p_success_size = size;
} else if (offset == 0 && (size & (p_vol->bpb.bytes_per_sector - 1)) == 0) {
err = VFiPFCACHE_ReadDataNumSector(p_vol, p_buf, sector, size >> p_vol->bpb.log2_bytes_per_sector, &num_success);
if (err != 0) {
return err;
}
*p_success_size += num_success << p_vol->bpb.log2_bytes_per_sector;
if (num_success != (size >> p_vol->bpb.log2_bytes_per_sector)) {
return 17;
}
} else if (offset == 0) {
p_page = VFiPFCACHE_SearchDataCache(p_vol, sector);
if (p_page != PF_NULL) {
num_sector = (p_page->sector + p_page->size) - sector;
if (num_sector <= (size >> p_vol->bpb.log2_bytes_per_sector)) {
VFipf_memcpy(p_buf, p_page->p_buf, num_sector << p_vol->bpb.log2_bytes_per_sector);
*p_success_size += num_sector << p_vol->bpb.log2_bytes_per_sector;
size -= num_sector << p_vol->bpb.log2_bytes_per_sector;
sector += num_sector;
} else if (num_sector > (size >> p_vol->bpb.log2_bytes_per_sector)) {
VFipf_memcpy(p_buf, p_page->p_buf, size);
*p_success_size += size;
size = 0;
}
}
if (size != 0) {
adjust_sector = 0;
num_sector = size >> p_vol->bpb.log2_bytes_per_sector;
rest_sector = (sector + num_sector) % p_vol->cache.data_buff_size;
if (num_sector > rest_sector) {
adjust_sector = num_sector - rest_sector;
err = VFiPFCACHE_ReadDataNumSector(p_vol, &p_buf[*p_success_size], sector, adjust_sector, &num_success);
if (err != 0) {
return err;
}
*p_success_size += num_success << p_vol->bpb.log2_bytes_per_sector;
if (num_success != adjust_sector) {
return 17;
}
sector += adjust_sector;
num_sector -= adjust_sector;
}
if (num_sector != 0) {
err = VFiPFCACHE_ReadDataPage(p_vol, sector, &p_page, set_sig);
if (err != 0) {
return err;
}
VFipf_memcpy(&p_buf[*p_success_size], p_page->p_buf, num_sector << p_vol->bpb.log2_bytes_per_sector);
*p_success_size += num_sector << p_vol->bpb.log2_bytes_per_sector;
}
}
} else {
return 10;
}
return 0;
}
pf_s32 VFiPFSEC_WriteFAT(PF_VOLUME* p_vol, const pf_u8* p_buf, pf_u32 sector, pf_u16 offset, pf_u16 size) {
PF_CACHE_PAGE* p_page;
pf_s32 err;
if ((p_vol->flags & 0x01) == 0 || !VFiPFDRV_IsInserted(p_vol) || (p_vol->flags & 2)) {
return 9;
}
if (sector >= p_vol->bpb.total_sectors || offset >= p_vol->bpb.bytes_per_sector || offset + size > p_vol->bpb.bytes_per_sector) {
return 10;
}
err = VFiPFCACHE_ReadFATPage(p_vol, sector, &p_page);
if (err != 0) {
return err;
}
VFipf_memcpy(&p_page->p_buf[offset], (pf_u8*)p_buf, size);
err = VFiPFCACHE_WriteFATPage(p_vol, p_page);
if (err != 0) {
return err;
}
return 0;
}
pf_s32 VFiPFSEC_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 err;
PF_CACHE_PAGE* p_page;
pf_u32 num_success;
pf_u32 num_sector;
pf_u32 adjust_sector;
pf_u32 rest_sector;
*p_success_size = 0;
if ((p_vol->flags & 0x01) == 0 || !VFiPFDRV_IsInserted(p_vol) || (p_vol->flags & 2)) {
return 9;
}
if ((sector >= p_vol->bpb.total_sectors || offset >= p_vol->bpb.bytes_per_sector || offset + size > p_vol->bpb.bytes_per_sector) && offset != 0) {
return 10;
}
if (offset != 0 || size < p_vol->bpb.bytes_per_sector) {
err = VFiPFCACHE_ReadDataPageAndFlushIfNeeded(p_vol, sector, &p_page, set_sig);
if (err != 0) {
return err;
}
VFipf_memcpy(&p_page->p_buf[offset], (void*)p_buf, size);
err = VFiPFCACHE_WriteDataPage(p_vol, p_page, set_sig);
if (err != 0) {
return err;
}
*p_success_size = size;
} else if (offset == 0 && (size & (p_vol->bpb.bytes_per_sector - 1)) == 0) {
err = VFiPFCACHE_WriteDataNumSectorAndFreeIfNeeded(p_vol, p_buf, sector, size >> p_vol->bpb.log2_bytes_per_sector, &num_success);
if (err != 0) {
return err;
}
*p_success_size = num_success << p_vol->bpb.log2_bytes_per_sector;
if (num_success != (size >> p_vol->bpb.log2_bytes_per_sector)) {
return 17;
}
} else if (offset == 0) {
adjust_sector = 0;
num_sector = size >> p_vol->bpb.log2_bytes_per_sector;
rest_sector = (sector + num_sector) % p_vol->cache.data_buff_size;
if (num_sector > rest_sector) {
adjust_sector = num_sector - rest_sector;
err = VFiPFCACHE_WriteDataNumSectorAndFreeIfNeeded(p_vol, p_buf, sector, adjust_sector, &num_success);
if (err != 0) {
return err;
}
*p_success_size = num_success << p_vol->bpb.log2_bytes_per_sector;
if (num_success != adjust_sector) {
return 17;
}
sector += adjust_sector;
num_sector -= adjust_sector;
}
if (num_sector != 0) {
err = VFiPFCACHE_ReadDataPageAndFlushIfNeeded(p_vol, sector, &p_page, set_sig);
if (err != 0) {
return err;
}
VFipf_memcpy(p_page->p_buf, (pf_u8*)&p_buf[*p_success_size], num_sector << p_vol->bpb.log2_bytes_per_sector);
err = VFiPFCACHE_WriteDataPage(p_vol, p_page, set_sig);
if (err != 0) {
return err;
}
*p_success_size += num_sector << p_vol->bpb.log2_bytes_per_sector;
}
} else {
return 10;
}
return 0;
}

View File

@@ -0,0 +1,24 @@
#define VFiPF_GET_LE_U16 PF_GET_LE_U16
#define VFiPF_LE16_TO_U16_STR PF_LE16_TO_U16_STR
#include <private/vf/PrFILE2/pf_types.h>
pf_u16 VFiPF_GET_LE_U16(const pf_u8* buf) {
return (pf_u16)((pf_u16)buf[1] << 8 | (pf_u16)buf[0]);
}
void VFiPF_LE16_TO_U16_STR(pf_u8* sSrc, pf_u32 num) {
pf_u32 cnt;
pf_s8 tmp_src;
for (cnt = 0; cnt < num; cnt += sizeof(pf_u16)) {
pf_s8* p = (pf_s8*)sSrc + cnt;
tmp_src = *p;
#ifdef DEBUG
*((pf_u8*)sSrc + cnt) = *((pf_u8*)sSrc + cnt + 1);
*((pf_u8*)sSrc + cnt + 1) = tmp_src;
#else
sSrc[cnt] = sSrc[cnt + 1];
sSrc[cnt + 1] = tmp_src;
#endif
}
}

View File

@@ -0,0 +1,229 @@
#include <private/vf/PrFILE2/pf_types.h>
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;
}

View File

@@ -0,0 +1,13 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue
#define VFiPFVOL_sync PFVOL_sync
#include <private/vf/PrFILE2/standard/pf_sync.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
pf_int32 pf2_sync(pf_ch8 drv_char, pf_s32 mode) {
pf_s32 err = VFiPFVOL_sync(drv_char, mode);
err = VFiPFAPI_convertReturnValue(err);
return err;
}

View File

@@ -0,0 +1,30 @@
#include <private/fa/pf_system.h>
typedef struct PFSYS_DATE { u32 sys_year, sys_month, sys_day; } PFSYS_DATE;
typedef struct PFSYS_TIME { u32 sys_hour, sys_min, sys_sec, sys_ms; } PFSYS_TIME;
typedef struct PFSYS_VOLUME_SET {
u8 volume_state[0x64];
s32 context_id;
} PFSYS_VOLUME_SET;
extern PFSYS_VOLUME_SET pf_vol_set;
extern void pfstub_init_stub(void);
PFSYS_SYSTEM_SET pf_sys_set;
void PFSYS_initializeSYS(void) {
pfstub_init_stub();
}
s32 PFSYS_GetCurrentContextID(s32* context_id) {
*context_id = pf_vol_set.context_id;
return 0;
}
void PFSYS_TimeStamp(PFSYS_DATE* sdate, PFSYS_TIME* stime) {
OSCalendarTime calendar;
OSTicksToCalendarTime(OSGetTime(), &calendar);
sdate->sys_year = calendar.year;
sdate->sys_month = calendar.mon + 1;
sdate->sys_day = calendar.mday;
stime->sys_hour = calendar.hour;
stime->sys_min = calendar.min;
stime->sys_sec = calendar.sec;
stime->sys_ms = 1;
}

View File

@@ -0,0 +1,13 @@
#define PF_FA_STR_LAYOUT
#define VFiPFAPI_convertReturnValue4unmount PFAPI_convertReturnValue4unmount
#define VFiPFVOL_unmount PFVOL_unmount
#include <private/vf/PrFILE2/standard/pf_unmount.h>
#include <private/vf/PrFILE2/fatfs/pf_volume.h>
#include <private/vf/PrFILE2/standard/pf_api_util.h>
pf_int32 pf2_unmount(pf_ch8 drive, pf_u32 mode) {
pf_s32 err = VFiPFVOL_unmount(drive, mode);
err = VFiPFAPI_convertReturnValue4unmount(err);
return err;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,947 @@
#include <private/vi.h>
#include <revolution/kbd.h>
#include <revolution/os.h>
#include <revolution/usbkbd.h>
#include <revolution/verdefs.h>
typedef union {
u32 value;
struct {
u32 locks : 26;
u32 physical : 6;
} bits;
} KBDModifierState;
typedef struct {
u8 codeCount;
u8 flags;
u16* keyMap;
u16* modifierMap;
u8 lockIndex;
u8 shiftIndex;
u8 altIndex;
u8 maxCode;
u8 keypadMap[8];
u8 keypadCount;
} KBDKeyMap;
typedef union {
KBDKeyMap maps[36];
u8 storage[0x400];
} KBDKeyMapTable;
typedef struct {
u8 channel;
u8 code;
u32 state;
u32 modifiers;
u16 translated;
} KBDKeyEventData;
typedef struct {
u8 channel;
s32 country;
u32 flags;
void* device;
u8 modifiers;
u8 reportReserved;
u8 keys[6];
KBDKeyEventData events[32];
u8 writeIndex;
u8 readIndex;
u32 lockProcessing;
u32 modState;
u8 lockCount[6];
u16 repeatDelay;
u16 repeatInterval;
u8 repeatKey;
OSAlarm alarm;
u32 lockState;
} KBDChannel;
typedef struct {
u32 callbackAddress;
void* callbackArg;
} KBDLEDCallbackData;
const char* __KBDVersion =
"<< RVL_SDK - KBD \trelease build: Apr 20 2010 11:21:43 (0x4199_60831) >>";
static BOOL kbdInitialized;
static USBKBDAttachCallback kbdDevAttachCallback;
static USBKBDDetachCallback kbdDevDetachCallback;
static void (*kbdKeyCallback)(KBDKeyEventData* event);
KBDKeyMapTable kbdKeyMaps;
typedef struct {
u32 device;
u8 leds;
u32 transfer[4];
USBKBDCmdLEDCallback callback;
void* callbackArg;
} KBDLEDCommand;
KBDLEDCommand kbdCmdBuf[12];
KBDChannel kbdData[4];
KBDLEDCallbackData kbdLCBuf[12];
u16 kbdKeyMapUS_International[500] = {
0x00FF, 0x0061, 0x0041, 0x00E1, 0x00C1, 0x003F, 0x0062, 0x0042, 0x0000, 0x0000,
0x003F, 0x0063, 0x0043, 0x00A9, 0x00A2, 0x00FF, 0x0064, 0x0044, 0x00F0, 0x00D0,
0x00FF, 0x0065, 0x0045, 0x00E9, 0x00C9, 0x003F, 0x0066, 0x0046, 0x0000, 0x0000,
0x003F, 0x0067, 0x0047, 0x0000, 0x0000, 0x003F, 0x0068, 0x0048, 0x0000, 0x0000,
0x00FF, 0x0069, 0x0049, 0x00ED, 0x00CD, 0x003F, 0x006A, 0x004A, 0x0000, 0x0000,
0x003F, 0x006B, 0x004B, 0x0000, 0x0000, 0x00FF, 0x006C, 0x004C, 0x00F8, 0x00D8,
0x003F, 0x006D, 0x004D, 0x00B5, 0x0000, 0x00FF, 0x006E, 0x004E, 0x00F1, 0x00D1,
0x00FF, 0x006F, 0x004F, 0x00F3, 0x00D3, 0x00FF, 0x0070, 0x0050, 0x00F6, 0x00D6,
0x00FF, 0x0071, 0x0051, 0x00E4, 0x00C4, 0x003F, 0x0072, 0x0052, 0x00AE, 0x0000,
0x003F, 0x0073, 0x0053, 0x00DF, 0x00A7, 0x00FF, 0x0074, 0x0054, 0x00FE, 0x00DE,
0x00FF, 0x0075, 0x0055, 0x00FA, 0x00DA, 0x003F, 0x0076, 0x0056, 0x0000, 0x0000,
0x00FF, 0x0077, 0x0057, 0x00E5, 0x00C5, 0x003F, 0x0078, 0x0058, 0x0000, 0x0000,
0x00FF, 0x0079, 0x0059, 0x00FC, 0x00DC, 0x00FF, 0x007A, 0x005A, 0x00E6, 0x00C6,
0x0000, 0x0031, 0x0021, 0x00A1, 0x00B9, 0x0000, 0x0032, 0x0040, 0x00B2, 0x0000,
0x0000, 0x0033, 0x0023, 0x00B3, 0x0000, 0x0000, 0x0034, 0x0024, 0x00A4, 0x00A3,
0x0000, 0x0035, 0x0025, 0x20AC, 0x0000, 0x0000, 0x0036, 0x0302, 0x00BC, 0x0000,
0x0000, 0x0037, 0x0026, 0x00BD, 0x0000, 0x0000, 0x0038, 0x002A, 0x00BE, 0x0000,
0x0000, 0x0039, 0x0028, 0x2018, 0x0000, 0x0000, 0x0030, 0x0029, 0x2019, 0x0000,
0x0000, 0xF1CD, 0xF1CD, 0xF1CD, 0xF1CD, 0x0000, 0xF1DB, 0xF1DB, 0xF1DB, 0xF1DB,
0x0000, 0xF1C8, 0xF1C8, 0xF1C8, 0xF1C8, 0x0000, 0xF1C9, 0xF1C9, 0xF1C9, 0xF1C9,
0x0000, 0x0020, 0x0020, 0x0020, 0x0020, 0x0000, 0x002D, 0x005F, 0x00A5, 0x0000,
0x0000, 0x003D, 0x002B, 0x00D7, 0x00F7, 0x0000, 0x005B, 0x007B, 0x00AB, 0x0000,
0x0000, 0x005D, 0x007D, 0x00BB, 0x0000, 0x0000, 0x005C, 0x007C, 0x00AC, 0x00A6,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x003B, 0x003A, 0x00B6, 0x00B0,
0x0000, 0x030D, 0x030E, 0x00B4, 0x00A8, 0x0000, 0x0300, 0x0303, 0x0000, 0x0000,
0x00C0, 0x002C, 0x003C, 0x00E7, 0x00C7, 0x0000, 0x002E, 0x003E, 0x0000, 0x0000,
0x0000, 0x002F, 0x003F, 0x00BF, 0x0000, 0xC000, 0xF008, 0xF008, 0xF008, 0xF008,
0x0000, 0xF061, 0xF061, 0xF061, 0xF061, 0x0000, 0xF062, 0xF062, 0xF062, 0xF062,
0x0000, 0xF063, 0xF063, 0xF063, 0xF063, 0x0000, 0xF064, 0xF064, 0xF064, 0xF064,
0x0000, 0xF065, 0xF065, 0xF065, 0xF065, 0x0000, 0xF066, 0xF066, 0xF066, 0xF066,
0x0000, 0xF067, 0xF067, 0xF067, 0xF067, 0x0000, 0xF068, 0xF068, 0xF068, 0xF068,
0x0000, 0xF069, 0xF069, 0xF069, 0xF069, 0x0000, 0xF06A, 0xF06A, 0xF06A, 0xF06A,
0x0000, 0xF06B, 0xF06B, 0xF06B, 0xF06B, 0x0000, 0xF06C, 0xF06C, 0xF06C, 0xF06C,
0xC000, 0xF020, 0xF020, 0xF020, 0xF020, 0xC000, 0xF021, 0xF021, 0xF021, 0xF021,
0xC000, 0xF022, 0xF022, 0xF022, 0xF022, 0x0000, 0xF1B0, 0xF1B0, 0xF1B0, 0xF1B0,
0x0000, 0xF1B7, 0xF1B7, 0xF1B7, 0xF1B7, 0x0000, 0xF1B9, 0xF1B9, 0xF1B9, 0xF1B9,
0x0000, 0xF1AE, 0xF1AE, 0xF1AE, 0xF1AE, 0x0000, 0xF1B1, 0xF1B1, 0xF1B1, 0xF1B1,
0x0000, 0xF1B3, 0xF1B3, 0xF1B3, 0xF1B3, 0x0000, 0xF1B6, 0xF1B6, 0xF1B6, 0xF1B6,
0x0000, 0xF1B4, 0xF1B4, 0xF1B4, 0xF1B4, 0x0000, 0xF1B2, 0xF1B2, 0xF1B2, 0xF1B2,
0x0000, 0xF1B8, 0xF1B8, 0xF1B8, 0xF1B8, 0xC000, 0xF007, 0xF007, 0xF007, 0xF007,
0x0000, 0xF12F, 0xF12F, 0xF12F, 0xF12F, 0x0000, 0xF12A, 0xF12A, 0xF12A, 0xF12A,
0x0000, 0xF12D, 0xF12D, 0xF12D, 0xF12D, 0x0000, 0xF12B, 0xF12B, 0xF12B, 0xF12B,
0x0000, 0xF10D, 0xF10D, 0xF10D, 0xF10D, 0x80FF, 0xF171, 0xF131, 0x0000, 0x0000,
0x80FF, 0xF172, 0xF132, 0x0000, 0x0000, 0x80FF, 0xF173, 0xF133, 0x0000, 0x0000,
0x80FF, 0xF174, 0xF134, 0x0000, 0x0000, 0x80FF, 0xF175, 0xF135, 0x0000, 0x0000,
0x80FF, 0xF176, 0xF136, 0x0000, 0x0000, 0x80FF, 0xF177, 0xF137, 0x0000, 0x0000,
0x80FF, 0xF178, 0xF138, 0x0000, 0x0000, 0x80FF, 0xF179, 0xF139, 0x0000, 0x0000,
0x80FF, 0xF170, 0xF130, 0x0000, 0x0000, 0x80FF, 0xF16E, 0xF12E, 0x0000, 0x0000,
0x0000, 0x005C, 0x007C, 0x0000, 0x0000, 0xC000, 0xF02F, 0xF02F, 0xF02F, 0xF02F,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xF13D, 0xF13D, 0xF13D, 0xF13D
};
u16 kbdModifierMapUS_International[40] = {
0xC000, 0xF000, 0xF000, 0xF000, 0xF000, 0xC000, 0xF001, 0xF001, 0xF001, 0xF001,
0xC000, 0xF002, 0xF002, 0xF002, 0xF002, 0xC000, 0xF003, 0xF003, 0xF003, 0xF003,
0xC000, 0xF000, 0xF000, 0xF000, 0xF000, 0xC000, 0xF001, 0xF001, 0xF001, 0xF001,
0xC000, 0xF005, 0xF005, 0xF005, 0xF005, 0xC000, 0xF003, 0xF003, 0xF003, 0xF003
};
static u16 noRepeatKeys[7] = {0xf006, 0xf008, 0xf007, 0xf021, 0xf020, 0xf022, 0xf02f};
USBKBDErr KBDSetModState(u32 channel, u32 value);
USBKBDErr KBDResetChannel(u32 channel);
u16 KBDTranslateHidCode(u32 keyCode, u32 modifiers, s32 country);
static void kbdAttachHandler(void* device);
static void kbdDetachHandler(void* device);
static void kbdEventHandler(void* device, char* report);
static void kbdRepeatHandler(OSAlarm* alarm, OSContext* context);
static void kbdProcKey(u32 key, u32 state, u32 channel);
static void kbdProcMod(u32 key, u32 state, u32 channel);
static void kbdSendKey(KBDKeyEventData* event);
static void kbd_led_handler(BOOL success, void* callbackArg);
static void kbdAttachHandler(void* device) {
u32 channel;
channel = 0;
for (channel = 0; channel < 4; channel++) {
if (kbdData[(u8)channel].device == NULL) {
break;
}
}
if (channel != 4) {
u8 event[1];
kbdData[channel].device = device;
kbdData[channel].flags &= ~1;
KBDResetChannel(channel);
VIResetDimmingCount();
if (kbdDevAttachCallback != NULL) {
event[0] = (u8)channel;
kbdDevAttachCallback(event);
}
}
}
static void kbdDetachHandler(void* device) {
u32 channel;
channel = 0;
for (channel = 0; channel < 4; channel++) {
if (device == kbdData[(u8)channel].device) {
break;
}
}
if (channel != 4) {
u8 event[1];
kbdData[channel].device = NULL;
kbdData[channel].flags |= 1;
if (kbdDevDetachCallback != NULL) {
event[0] = (u8)channel;
kbdDevDetachCallback(event);
}
KBDResetChannel(channel);
}
}
static void kbdEventHandler(void* device, char* report) {
u32 channel;
channel = 0;
for (channel = 0; channel < 4; channel++) {
if (device == kbdData[(u8)channel].device) {
break;
}
}
if (channel != 4) {
KBDChannel* data;
u8* bytes;
u8 status;
data = &kbdData[channel];
bytes = (u8*)report;
status = bytes[2];
if ((u8)(bytes[2] + 0xff) <= 2) {
OSCancelAlarm(&data->alarm);
if (bytes[2] == 1) {
data->flags |= 2;
} else {
data->flags |= 4;
}
} else {
s32 i;
u32 mask;
data->flags = 0;
VIResetDimmingCount();
for (i = 0, mask = 1; i < 8; i++, mask <<= 1) {
if ((data->modifiers & (u8)mask) != 0) {
if ((bytes[0] & (u8)mask) == 0) {
kbdProcKey((u8)(i + 0xe0), 0, channel);
}
} else if ((bytes[0] & (u8)mask) != 0) {
kbdProcKey((u8)(i + 0xe0), 1, channel);
}
}
for (i = 0; i < 6; i++) {
u8 key;
s32 j;
key = data->keys[(s8)i];
j = 0;
if (key != 0) {
for (j = 0; j < 6; j++) {
if (key == bytes[j + 2]) {
break;
}
}
if (j == 6) {
kbdProcKey(key, 0, channel);
data->keys[(s8)i] = 0;
}
}
}
for (i = 0; i < 6; i++) {
u8 key;
s32 j;
key = bytes[(s8)i + 2];
j = 0;
if (key != 0) {
for (j = 0; j < 6; j++) {
if (key == data->keys[j]) {
break;
}
}
if (j == 6) {
kbdProcKey(key, 1, channel);
}
}
}
data->modifiers = bytes[0];
data->keys[0] = bytes[2];
data->keys[1] = bytes[3];
data->keys[2] = bytes[4];
data->keys[3] = bytes[5];
data->keys[4] = bytes[6];
data->keys[5] = bytes[7];
}
}
}
static void kbdRepeatHandler(OSAlarm* alarm, OSContext* context) {
KBDChannel* data;
data = (KBDChannel*)OSGetAlarmUserData(alarm);
kbdProcKey(data->repeatKey, 3, data->channel);
}
static inline USBKBDErr kbdGetModState(u32 channel, u32* modifiers) {
if (!kbdInitialized) {
return 2;
}
if (channel >= 4 || modifiers == NULL) {
return 4;
}
*modifiers = kbdData[channel].modState;
return 0;
}
static void kbdProcKey(u32 key, u32 pressed, u32 channel) {
KBDChannel* data;
KBDKeyMap* map;
s32 keyCount;
s32 i;
u32 j;
u16 translated;
OSTime timeout;
KBDKeyEventData event;
data = &kbdData[channel];
event.channel = channel;
event.state = pressed;
event.modifiers = 0;
kbdGetModState(channel, &event.modifiers);
map = &kbdKeyMaps.maps[data->country];
keyCount = map->keypadCount;
for (i = 0; i < keyCount; i++) {
if (key == map->keypadMap[i * 2]) {
key = map->keypadMap[i * 2 + 1];
break;
}
}
event.code = key;
translated = KBDTranslateHidCode(key, event.modifiers,
data->country);
event.translated = translated;
if ((translated == 0xF000) || (translated == 0xF001) ||
(translated == 0xF002) || (translated == 0xF003) ||
(translated == 0xF004) || (translated == 0xF005) ||
(translated == 0xF006) || (translated == 0xF007) ||
(translated == 0xF008) || (translated == 0xF021)) {
kbdProcMod(translated, pressed, channel);
if ((translated != 0xF006) && (translated != 0xF007) &&
(translated != 0xF008) && (translated != 0xF021)) {
kbdSendKey(&event);
return;
}
}
if ((pressed & 1) == 0) {
if (key == data->repeatKey) {
OSCancelAlarm(&data->alarm);
}
kbdSendKey(&event);
return;
}
OSCancelAlarm(&data->alarm);
for (j = 0; j < 7; j++) {
if (translated == noRepeatKeys[j]) {
break;
}
}
if (j == 7) {
data->repeatKey = key;
if (data->repeatDelay != 0) {
if ((pressed & 2) != 0) {
timeout = data->repeatInterval * (OS_TIMER_CLOCK / 1000);
} else {
timeout = data->repeatDelay * (OS_TIMER_CLOCK / 1000);
}
OSSetAlarm(&data->alarm, timeout, kbdRepeatHandler);
}
}
event.translated = translated;
kbdSendKey(&event);
}
static void kbdProcMod(u32 key, u32 pressed, u32 channel) {
KBDChannel* data;
s8 delta;
u8 flags;
u32 state;
u32 finalState;
s8 value;
data = &kbdData[channel];
delta = (pressed & 1) != 0 ? 1 : -1;
flags = kbdKeyMaps.maps[data->country].flags;
state = 0;
kbdGetModState(channel, &state);
switch (key) {
case 0xF001:
if (data->lockState != 0) {
if ((pressed & 1) != 0) {
state ^= 2;
}
} else {
value = data->lockCount[1] + delta;
data->lockCount[1] = value;
state = (state & 0xFFFFFFFD) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1E & 2);
}
break;
case 0xF005:
if (data->lockState != 0) {
if ((pressed & 1) != 0) {
state ^= 0x20;
}
} else {
value = data->lockCount[4] + delta;
data->lockCount[4] = value;
state = (state & 0xFFFFFFDF) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1A & 0x20);
}
break;
case 0xF000:
if (data->lockState != 0) {
if ((pressed & 1) != 0) {
state ^= 1;
}
} else {
value = data->lockCount[0] + delta;
data->lockCount[0] = value;
state = (state & 0xFFFFFFFE) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1F);
}
break;
case 0xF008:
if (((pressed & 1) != 0) && (data->lockProcessing != 0)) {
state ^= 0x200;
}
break;
case 0xF007:
if (((pressed & 1) != 0) && (data->lockProcessing != 0)) {
state ^= 0x100;
}
break;
case 0xF006:
if (((pressed & 1) != 0) && (data->lockProcessing != 0)) {
u32 oldState;
u32 lockState;
oldState = state;
lockState = oldState & 0xC0;
switch (lockState) {
case 0:
if ((flags & 1) == 1) {
state = oldState | 0x40;
}
break;
case 0x40:
{
state = oldState & 0xFFFFFFBF;
if ((flags & 4) == 4) {
state = oldState & 0xFFFFFFBF | 0x80;
}
}
break;
case 0x80:
state = oldState & 0xFFFFFF7F;
break;
case 0xC0:
state = oldState & 0xFFFFFF3F;
break;
}
}
break;
case 0xF002:
if (data->lockState != 0) {
if ((pressed & 1) != 0) {
state ^= 4;
}
} else {
value = data->lockCount[2] + delta;
data->lockCount[2] = value;
state = (state & 0xFFFFFFFB) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1D & 4);
}
break;
case 0xF003:
if (data->lockState != 0) {
if ((pressed & 1) != 0) {
state ^= 8;
}
} else {
value = data->lockCount[3] + delta;
data->lockCount[3] = value;
state = (state & 0xFFFFFFF7) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1C & 8);
}
break;
case 0xF004:
if (data->lockState != 0) {
if ((pressed & 1) != 0) {
state ^= 0x10;
}
} else {
value = data->lockCount[5] + delta;
data->lockCount[5] = value;
state = (state & 0xFFFFFFEF) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1B & 0x10);
}
break;
case 0xF021:
if (((pressed & 1) != 0) && (data->lockProcessing != 0)) {
state ^= 0x400;
}
break;
}
finalState = state | 0x1000;
KBDSetModState(channel, finalState);
}
static void kbdSendKey(KBDKeyEventData* event) {
KBDChannel* data;
u8 head;
u8 tail;
u8 next;
if (kbdKeyCallback != NULL) {
kbdKeyCallback(event);
}
data = &kbdData[event->channel];
tail = data->readIndex;
head = data->writeIndex;
if (head != tail) {
next = (head + 1) % 0x20;
if (next == tail) {
data->events[head].channel = event->channel;
data->events[data->writeIndex].code = 0xff;
data->events[data->writeIndex].state = 0;
data->events[data->writeIndex].modifiers = 0;
data->events[data->writeIndex].translated = 0;
} else {
data->events[head] = *event;
if (data->readIndex == 0x20) {
data->readIndex = data->writeIndex;
}
}
data->writeIndex = next;
}
}
static void kbd_led_handler(BOOL success, void* callbackArg) {
u32 index;
u32 result;
u32 callbackAddress;
index = (u32)callbackArg;
callbackAddress = kbdLCBuf[index].callbackAddress;
kbdCmdBuf[index].device = 0;
if (callbackAddress == 0) {
return;
}
switch (success) {
case TRUE:
result = 0;
break;
default:
result = 7;
break;
}
((USBKBDCmdLEDCallback)kbdLCBuf[index].callbackAddress)(result, kbdLCBuf[index].callbackArg);
}
USBKBDErr KBDSetLedsAsync(u32 channel, u32 leds, USBKBDCmdLEDCallback callback, void* callbackArg) {
u32 index;
BOOL interrupts;
USBKBDErr result;
if (!kbdInitialized) {
return 2;
}
if (channel >= 4) {
return 4;
}
if ((s32)kbdData[channel].flags == 1 || (s32)kbdData[channel].flags == 4) {
return 5;
}
leds &= 0xff;
interrupts = OSDisableInterrupts();
for (index = 0; index < 12; index++) {
if (kbdCmdBuf[index].device == 0) {
kbdCmdBuf[index].device = (u32)kbdData[channel].device;
break;
}
}
OSRestoreInterrupts(interrupts);
if (index == 12) {
return 7;
}
kbdLCBuf[index].callbackAddress = (u32)callback;
kbdLCBuf[index].callbackArg = callbackArg;
result = USBKBDSetLEDAsync((u32)kbdData[channel].device, leds,
(USBKBDCmdLEDAsync*)&kbdCmdBuf[index],
kbd_led_handler, (void*)index);
if (result != 0) {
return 7;
}
return 0;
}
USBKBDErr KBDSetLeds(u32 channel, u32 leds) {
u32 index;
BOOL interrupts;
USBKBDErr result;
if (!kbdInitialized) {
return 2;
}
if (channel >= 4) {
return 4;
}
if ((s32)kbdData[channel].flags == 1 || (s32)kbdData[channel].flags == 4) {
return 5;
}
leds &= 0xff;
interrupts = OSDisableInterrupts();
for (index = 0; index < 12; index++) {
if (kbdCmdBuf[index].device == 0) {
kbdCmdBuf[index].device = (u32)kbdData[channel].device;
break;
}
}
OSRestoreInterrupts(interrupts);
if (index == 12) {
return 7;
}
result = USBKBDSetLED((u32)kbdData[channel].device, leds,
(USBKBDCmdLED*)&kbdCmdBuf[index]);
kbdCmdBuf[index].device = 0;
if (result != 0) {
return 7;
}
return 0;
}
void kbdInitMap(u32 country, u8 codeCount, u8 flags, u16* keyMap, u16* modifierMap,
u8 lockIndex, u8 shiftIndex, u8 altIndex, u8 maxCode, s32 keypadType) {
KBDKeyMap* map;
map = &kbdKeyMaps.maps[country];
map->codeCount = codeCount;
map->flags = flags;
map->keyMap = keyMap;
map->modifierMap = modifierMap;
map->lockIndex = lockIndex;
map->shiftIndex = shiftIndex;
map->altIndex = altIndex;
map->maxCode = maxCode;
switch (keypadType) {
case 0:
map->keypadMap[0] = 0x32;
map->keypadMap[1] = 0x31;
map->keypadCount = 1;
break;
case 1:
map->keypadMap[0] = 0x31;
map->keypadMap[1] = 0x32;
map->keypadMap[2] = 0x94;
map->keypadMap[3] = 0x35;
map->keypadCount = 2;
break;
case 2:
map->keypadMap[0] = 0x31;
map->keypadMap[1] = 0x32;
map->keypadCount = 1;
break;
}
}
void kbdInitMapIntl(void) {
kbdInitMap(0, 5, 0x30, kbdKeyMapUS_International,
kbdModifierMapUS_International, 0, 0, 3, 100, 0);
}
USBKBDErr KBDInit(void) {
USBKBDErr result;
u32 i;
if (kbdInitialized) {
return 3;
}
OSRegisterVersion(__KBDVersion);
kbdInitialized = TRUE;
for (i = 0; i < 4; i++) {
KBDChannel* data;
data = &kbdData[(u8)i];
data->channel = (u8)i;
data->country = 0x21;
data->flags = 1;
data->device = NULL;
data->lockProcessing = 1;
data->repeatDelay = 500;
data->repeatInterval = 0x21;
data->lockState = 0;
OSCreateAlarm(&data->alarm);
OSSetAlarmUserData(&data->alarm, data);
KBDResetChannel((u8)i);
}
if (USBKBDInitialize(kbdAttachHandler, kbdDetachHandler) != 0) {
result = 1;
} else {
result = USBKBDRegisterEventCallback(kbdEventHandler);
result = (USBKBDErr)((-(u32)result | (u32)result) >> 31);
}
return result;
}
USBKBDAttachCallback KBDSetAttachCallback(USBKBDAttachCallback callback) {
USBKBDAttachCallback previous = kbdDevAttachCallback;
kbdDevAttachCallback = callback;
return previous;
}
USBKBDDetachCallback KBDSetDetachCallback(USBKBDDetachCallback callback) {
USBKBDDetachCallback previous = kbdDevDetachCallback;
kbdDevDetachCallback = callback;
return previous;
}
void (*KBDSetKeyCallback(void (*callback)(KBDKeyEventData* event)))(KBDKeyEventData* event) {
void (*previous)(KBDKeyEventData* event) = kbdKeyCallback;
kbdKeyCallback = callback;
return previous;
}
USBKBDErr KBDResetChannel(u32 channel) {
if (!kbdInitialized) {
return 2;
}
if (channel >= 4) {
return 4;
}
{
KBDChannel* data;
data = &kbdData[channel];
data->modifiers = 0;
data->keys[0] = 0;
data->keys[1] = 0;
data->keys[2] = 0;
data->keys[3] = 0;
data->keys[4] = 0;
data->keys[5] = 0;
data->readIndex = 0x20;
KBDSetModState(channel, 0x1000);
data->lockCount[0] = 0;
data->lockCount[1] = 0;
data->lockCount[2] = 0;
data->lockCount[3] = 0;
data->lockCount[4] = 0;
data->lockCount[5] = 0;
data->repeatKey = 0;
OSCancelAlarm(&data->alarm);
return 0;
}
}
USBKBDErr KBDSetCountry(u32 channel, s32 country) {
if (!kbdInitialized) {
return 2;
}
if (channel >= 4) {
return 4;
}
if (country > 0x23) {
return 4;
}
if (kbdKeyMaps.maps[country].codeCount == 0) {
return 4;
}
kbdData[channel].country = country;
KBDResetChannel(channel);
return 0;
}
USBKBDErr KBDSetLockProcessing(u32 channel, u32 value) {
if (!kbdInitialized) {
return 2;
}
if (channel >= 4) {
return 4;
}
kbdData[channel].lockProcessing = value;
return 0;
}
USBKBDErr KBDSetModState(u32 channel, u32 value) {
if (!kbdInitialized) {
return 2;
}
if (channel >= 4) {
return 4;
}
if ((value & 0x1000) != 0) {
kbdData[channel].modState = value & ~0x1000;
} else {
BOOL interrupts;
KBDModifierState* state;
KBDModifierState oldState;
KBDModifierState newState;
interrupts = OSDisableInterrupts();
state = (KBDModifierState*)&kbdData[channel].modState;
newState.value = value & 0xfc0;
oldState = *state;
newState.bits.physical = oldState.bits.physical;
*state = newState;
OSRestoreInterrupts(interrupts);
}
return 0;
}
u16 KBDTranslateHidCode(u32 keyCode, u32 modifiers, s32 country) {
KBDKeyMap* map;
u16* table;
u32 keyIndex;
u16 entry;
u32 mask;
u32 offset;
s32 group;
u32 shiftFlag;
u32 shift;
if (kbdInitialized == FALSE) {
return 0xFFFF;
}
if (country >= 0x24) {
return 0xFFFF;
}
map = &kbdKeyMaps.maps[country];
if (map->codeCount == 0) {
return 0;
}
if (keyCode < 4) {
return 0xFFFF;
}
if ((s32)keyCode < (s32)map->maxCode + 4) {
keyIndex = (u8)(keyCode - 4);
table = map->keyMap;
} else {
if (keyCode >= 0xE0 && keyCode <= 0xE7) {
keyIndex = (u8)(keyCode - 0xe0);
table = map->modifierMap;
} else {
return 0;
}
}
keyIndex = (keyIndex & 0xFF) * map->codeCount;
entry = table[keyIndex];
mask = entry & 0xC000;
if (mask == 0xC000) {
group = 1;
offset = 0;
} else {
if ((modifiers & 0x20) == 0 && (modifiers & 5) != 5) {
if ((modifiers & 0x40) == 0) {
if ((modifiers & 0x80) == 0) {
group = 1;
shiftFlag = 1;
} else {
group = map->shiftIndex;
shiftFlag = 0x10;
}
} else {
group = map->lockIndex;
shiftFlag = 4;
}
} else {
group = map->altIndex;
shiftFlag = 0x40;
}
if ((modifiers & 0x800) == 0 && (modifiers & 0x1D) != 0) {
offset = 0;
} else {
shift = (modifiers >> 1) & 1;
offset = (shiftFlag << shift) & 0xFFFF;
if (mask == 0 && (offset & entry) != 0) {
offset = shift ^ ((modifiers >> 9) & 1);
} else if (mask == 0x8000 && (offset & entry) != 0) {
offset = 0;
if ((modifiers & 0x100) != 0 && shift == 0) {
offset = 1;
}
} else {
offset = shift;
if (mask == 0x4000 && group == 1 && (modifiers & 0x200) != 0) {
group = map->lockIndex;
}
}
}
if (offset == 0) {
if (group == map->altIndex && (map->flags & 0x10) == 0) {
return 0;
}
if (group == map->lockIndex && (map->flags & 1) == 0) {
return 0;
}
if (group == map->shiftIndex && (map->flags & 4) == 0) {
return 0;
}
} else {
if (group == map->altIndex && (map->flags & 0x20) == 0) {
return 0;
}
if (group == map->lockIndex && (map->flags & 2) == 0) {
return 0;
}
if (group == map->shiftIndex && (map->flags & 8) == 0) {
return 0;
}
}
}
return table[keyIndex + offset + group];
}

View File

@@ -0,0 +1,719 @@
#include <private/vi.h>
#include <revolution/os.h>
#include <revolution/vi.h>
static u16 gammaSet[31][17] = {
{0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
{0x0000, 0x0000, 0x0000, 0x0030, 0x0397, 0x3b49, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1000, 0x1000, 0x1000, 0x1080, 0x1b80, 0xeb00},
{0x0000, 0x0028, 0x005a, 0x02db, 0x0d8d, 0x3049, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1000, 0x1040, 0x1100, 0x1880, 0x4200, 0xeb00},
{0x0000, 0x007a, 0x023c, 0x076d, 0x129c, 0x2724, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1000, 0x10c0, 0x1580, 0x2900, 0x6200, 0xeb00},
{0x004e, 0x0199, 0x052d, 0x0b24, 0x1429, 0x20a4, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1040, 0x12c0, 0x1dc0, 0x3b00, 0x78c0, 0xeb00},
{0x00ec, 0x03d7, 0x0800, 0x0d9e, 0x143e, 0x1bdb, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x10c0, 0x16c0, 0x27c0, 0x4b80, 0x8980, 0xeb00},
{0x0276, 0x0666, 0x0a96, 0x0ef3, 0x13ac, 0x1849, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1200, 0x1c00, 0x3280, 0x59c0, 0x9600, 0xeb00},
{0x04ec, 0x08f5, 0x0c96, 0x0fcf, 0x12c6, 0x1580, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1400, 0x2200, 0x3cc0, 0x6640, 0x9fc0, 0xeb00},
{0x0800, 0x0bae, 0x0e00, 0x1030, 0x11cb, 0x1349, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1680, 0x28c0, 0x4680, 0x7100, 0xa780, 0xeb00},
{0x0bb1, 0x0e14, 0x0f2d, 0x1018, 0x10e5, 0x1180, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1980, 0x2f80, 0x4fc0, 0x7a00, 0xadc0, 0xeb00},
{0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1020, 0x4060, 0x80a0, 0xeb00, 0x1000, 0x2000, 0x4000, 0x6000, 0x8000, 0xa000, 0xeb00},
{0x14ec, 0x11c2, 0x1078, 0x0fb6, 0x0f2f, 0x0eb6, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2100, 0x3cc0, 0x5fc0, 0x8900, 0xb780, 0xeb00},
{0x19d8, 0x1333, 0x10d2, 0x0f6d, 0x0e5e, 0x0da4, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2500, 0x4300, 0x66c0, 0x8f40, 0xbb40, 0xeb00},
{0x1ec4, 0x147a, 0x110f, 0x0f0c, 0x0da1, 0x0cb6, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2900, 0x4900, 0x6d40, 0x94c0, 0xbe80, 0xeb00},
{0x2400, 0x1570, 0x110f, 0x0eaa, 0x0d0f, 0x0bdb, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2d40, 0x4ec0, 0x7300, 0x9980, 0xc180, 0xeb00},
{0x293b, 0x163d, 0x110f, 0x0e30, 0x0c7d, 0x0b24, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x3180, 0x5440, 0x7880, 0x9dc0, 0xc400, 0xeb00},
{0x2e27, 0x170a, 0x10d2, 0x0de7, 0x0beb, 0x0a80, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x3580, 0x5980, 0x7d40, 0xa1c0, 0xc640, 0xeb00},
{0x3362, 0x175c, 0x10d2, 0x0d6d, 0x0b6d, 0x09ed, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x39c0, 0x5e40, 0x8200, 0xa540, 0xc840, 0xeb00},
{0x384e, 0x17ae, 0x10b4, 0x0d0c, 0x0af0, 0x096d, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x3dc0, 0x62c0, 0x8640, 0xa880, 0xca00, 0xeb00},
{0x3d3b, 0x1800, 0x105a, 0x0cc3, 0x0a72, 0x0900, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x41c0, 0x6740, 0x8a00, 0xab80, 0xcb80, 0xeb00},
{0x41d8, 0x1828, 0x103c, 0x0c49, 0x0a1f, 0x0892, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x4580, 0x6b40, 0x8dc0, 0xae00, 0xcd00, 0xeb00},
{0x4676, 0x1851, 0x0fe1, 0x0c00, 0x09b6, 0x0836, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x4940, 0x6f40, 0x9100, 0xb080, 0xce40, 0xeb00},
{0x4ac4, 0x187a, 0x0fa5, 0x0b9e, 0x0963, 0x07db, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x4cc0, 0x7300, 0x9440, 0xb2c0, 0xcf80, 0xeb00},
{0x4f13, 0x1851, 0x0f69, 0x0b6d, 0x090f, 0x0780, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5040, 0x7640, 0x9700, 0xb500, 0xd0c0, 0xeb00},
{0x5313, 0x187a, 0x0f0f, 0x0b24, 0x08bc, 0x0736, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5380, 0x79c0, 0x99c0, 0xb700, 0xd1c0, 0xeb00},
{0x5713, 0x1851, 0x0ef0, 0x0ac3, 0x087d, 0x06ed, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x56c0, 0x7cc0, 0x9c80, 0xb8c0, 0xd2c0, 0xeb00},
{0x5b13, 0x1828, 0x0e96, 0x0a92, 0x0829, 0x06b6, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5a00, 0x7fc0, 0x9ec0, 0xba80, 0xd380, 0xeb00},
{0x5ec4, 0x1800, 0x0e78, 0x0a30, 0x0800, 0x066d, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5d00, 0x8280, 0xa140, 0xbc00, 0xd480, 0xeb00},
{0x6276, 0x17d7, 0x0e1e, 0x0a00, 0x07c1, 0x0636, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x6000, 0x8540, 0xa340, 0xbd80, 0xd540, 0xeb00},
{0x65d8, 0x17ae, 0x0de1, 0x09cf, 0x0782, 0x0600, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x62c0, 0x87c0, 0xa540, 0xbf00, 0xd600, 0xeb00},
{0x693b, 0x1785, 0x0da5, 0x0986, 0x0743, 0x05db, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x6580, 0x8a40, 0xa740, 0xc040, 0xd680, 0xeb00}
};
static u8 VINtscACPType1[0x1a] = {
0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x0f, 0x0f, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static u8 VINtscACPType2[0x1a] = {
0x3e, 0x1d, 0x11, 0x25, 0x11, 0x01, 0x07, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00
};
static u8 VINtscACPType3[0x1a] = {
0x3e, 0x17, 0x15, 0x21, 0x15, 0x05, 0x05, 0x02, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00
};
static u8 VIPalACPType1[0x1a] = {
0x36, 0x1a, 0x22, 0x2a, 0x22, 0x05, 0x02, 0x00, 0x1c, 0x3d, 0x14, 0x03, 0xfe,
0x01, 0x54, 0xfe, 0x7e, 0x60, 0x00, 0x08, 0x00, 0x04, 0x07, 0x01, 0x55, 0x01
};
static u8 VIPalACPType2[0x1a] = {
0x36, 0x1a, 0x22, 0x2a, 0x22, 0x05, 0x02, 0x00, 0x1c, 0x3d, 0x14, 0x03, 0xfe,
0x01, 0x54, 0xfe, 0x7e, 0x60, 0x00, 0x08, 0x00, 0x04, 0x07, 0x01, 0x55, 0x01
};
static u8 VIPalACPType3[0x1a] = {
0x36, 0x1a, 0x22, 0x2a, 0x22, 0x05, 0x02, 0x00, 0x1c, 0x3d, 0x14, 0x03, 0xfe,
0x01, 0x54, 0xfe, 0x7e, 0x60, 0x00, 0x08, 0x00, 0x04, 0x07, 0x01, 0x55, 0x01
};
static u8 VIEurgb60ACPType1[0x1a] = {
0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x1e, 0x1e, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
};
static u8 VIEurgb60ACPType2[0x1a] = {
0x36, 0x1d, 0x11, 0x25, 0x11, 0x01, 0x07, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x1e, 0x1e, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x01
};
static u8 VIEurgb60ACPType3[0x1a] = {
0x36, 0x17, 0x15, 0x21, 0x15, 0x05, 0x05, 0x02, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x1e, 0x1e, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x01
};
static u8 VIMpalACPType1[0x1a] = {
0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x0f, 0x0f, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static u8 VIMpalACPType2[0x1a] = {
0x36, 0x1d, 0x11, 0x25, 0x11, 0x01, 0x07, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00
};
static u8 VIMpalACPType3[0x1a] = {
0x36, 0x17, 0x15, 0x21, 0x15, 0x05, 0x05, 0x02, 0x1b, 0x1b, 0x24, 0x07, 0xf8,
0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00
};
u8 VIProgressiveACPType[0x1a] = {
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
void __VISendI2CData(u8 dev, u8* data, u8 length);
void WaitMicroTime(u32 time);
void __VISetYUVSEL(u8 value);
void __VISetGammaImm(u16* gamma);
void __VISetRevolutionMode(void);
void __VISetRevolutionModeSimple(void);
void VISetMacrovision(s32 type);
#define COPY_ACP(dst, src) \
do { \
u32 copyIndex; \
u8* destination = (dst); \
const u8* source = (src); \
for (copyIndex = 0; copyIndex < 0x1a; copyIndex++) { \
destination[copyIndex + 1] = source[copyIndex]; \
} \
destination[0] = 0x40; \
} while (0)
static u8 __wd0 = 0xff;
static u8 __wd1 = 0xff;
static u8 __wd2 = 0xff;
static u8 __gp1 = 0xff;
static u8 __gp2 = 0xff;
static u8 __gp3 = 0xff;
static u8 __gp4 = 0xff;
static u8 __cc1 = 0xff;
static u8 __cc2 = 0xff;
static u8 __cc3 = 0xff;
static u8 __cc4 = 0xff;
static u32 __tvType = 0xff;
static u8 __filter = 0xff;
u8 VIZeroACPType[0x1a];
static s32 Vdac_Flag_Region;
static s32 __type;
static s32 __gamma;
static s32 __level;
u32 Vdac_Flag_Changed_816991E0;
void __VISetVolume(u8 wd0, u8 wd1) {
u8 data[3];
data[0] = 0x71;
data[1] = wd0;
data[2] = wd1;
__VISendI2CData(0xe0, data, 3);
WaitMicroTime(2);
}
void __VISetYUVSEL(u8 value) {
s32 region = *(s32*)0x800000cc;
u8 data[2];
if (region != 2) {
if (region < 2) {
if (region == 0) {
goto region0;
}
if (region >= 0) {
goto region2;
}
} else {
switch (region) {
case 5:
goto region2;
default:
goto regionDefault;
}
}
goto regionDefault;
}
goto region1;
region2:
Vdac_Flag_Region = 2;
goto send;
region1:
Vdac_Flag_Region = 1;
goto send;
region0:
Vdac_Flag_Region = 0;
goto send;
regionDefault:
Vdac_Flag_Region = 0;
goto send;
send:
data[0] = 1;
data[1] = (value << 5) | Vdac_Flag_Region;
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
}
void __VISetFilter4EURGB60(u8 value) {
u8 data[2];
data[0] = 0x6e;
data[1] = value;
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
}
void __VISetCGMS(void) {
u8 data[3];
data[0] = 5;
data[1] = (__wd1 & 0xf) << 2 | __wd0 & 3;
data[2] = __wd2;
__VISendI2CData(0xe0, data, 3);
WaitMicroTime(2);
}
void __VISetWSS(void) {
u8 data[3];
data[0] = 8;
data[1] = (__gp2 & 0xf) << 4 | __gp1 & 0xf;
data[2] = (__gp4 & 7) << 3 | __gp3 & 7;
__VISendI2CData(0xe0, data, 3);
WaitMicroTime(2);
}
void __VISetClosedCaption(void) {
u8 data[5];
data[0] = 0x7a;
data[1] = __cc1 & 0x7f;
data[2] = __cc2 & 0x7f;
data[3] = __cc3 & 0x7f;
data[4] = __cc4 & 0x7f;
__VISendI2CData(0xe0, data, 5);
WaitMicroTime(2);
}
void __VISetMacrovision(void) {
switch (__type) {
case 2:
switch (__tvType) {
case 0: {
u8 data[0x1b];
COPY_ACP(data, VINtscACPType1);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 1: {
u8 data[0x1b];
COPY_ACP(data, VIPalACPType1);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 2: {
u8 data[0x1b];
COPY_ACP(data, VIMpalACPType1);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 5: {
u8 data[0x1b];
COPY_ACP(data, VIEurgb60ACPType1);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
}
break;
case 3:
switch (__tvType) {
case 0: {
u8 data[0x1b];
COPY_ACP(data, VINtscACPType2);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 1: {
u8 data[0x1b];
COPY_ACP(data, VIPalACPType2);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 2: {
u8 data[0x1b];
COPY_ACP(data, VIMpalACPType2);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 5: {
u8 data[0x1b];
COPY_ACP(data, VIEurgb60ACPType2);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
}
break;
case 4:
switch (__tvType) {
case 0: {
u8 data[0x1b];
COPY_ACP(data, VINtscACPType3);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 1: {
u8 data[0x1b];
COPY_ACP(data, VIPalACPType3);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 2: {
u8 data[0x1b];
COPY_ACP(data, VIMpalACPType3);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
case 5: {
u8 data[0x1b];
COPY_ACP(data, VIEurgb60ACPType3);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
}
break;
case 1: {
u8 data[0x1b];
COPY_ACP(data, VIZeroACPType);
__VISendI2CData(0xe0, data, 0x1b);
WaitMicroTime(2);
break;
}
}
}
void VISetMacrovision(s32 type) {
u8 oldType;
u8 oldWd2;
u8 oldWd0;
u8 mode;
u32 volume;
u8 newType;
u8 newWd2;
s32 tvFormat;
mode = 0;
volume = 0;
oldWd0 = __wd0;
oldType = __wd1;
oldWd2 = __wd2;
newType = oldType;
if (type == 3) {
goto type3;
}
if (type < 3) {
if (type == 1) {
goto type1;
} else if (type >= 1) {
goto type2;
}
goto done;
}
if (type >= 5) {
goto done;
}
goto type5;
type1:
mode = 0;
volume = 0;
goto done;
type2:
mode = 2;
volume = 3;
newType = 0;
goto done;
type3:
mode = 1;
volume = 3;
newType = 0;
goto done;
type5:
mode = 3;
volume = 3;
newType = 0;
done:
volume |= oldWd2 & 0xf0;
newWd2 = volume | mode << 2;
if ((oldType != newType) || (oldWd2 != newWd2)) {
__wd0 = oldWd0;
__wd1 = newType;
__wd2 = newWd2;
Vdac_Flag_Changed_816991E0 |= 1;
}
tvFormat = VIGetTvFormat();
if ((__type != type) || (__tvType != tvFormat)) {
__type = type;
__tvType = tvFormat;
Vdac_Flag_Changed_816991E0 |= 8;
}
}
void __VISetGammaImm(u16* gamma) {
u8 data[0x23];
data[0] = 0x10;
data[1] = ((u32)gamma[0] << 16) >> 24;
data[2] = gamma[0];
data[3] = ((u32)gamma[1] << 16) >> 24;
data[4] = gamma[1];
data[5] = ((u32)gamma[2] << 16) >> 24;
data[6] = gamma[2];
data[7] = ((u32)gamma[3] << 16) >> 24;
data[8] = gamma[3];
data[9] = ((u32)gamma[4] << 16) >> 24;
data[10] = gamma[4];
data[11] = ((u32)gamma[5] << 16) >> 24;
data[12] = gamma[5];
data[13] = ((u8*)gamma)[12];
data[14] = ((u8*)gamma)[13];
data[15] = ((u8*)gamma)[14];
data[16] = ((u8*)gamma)[15];
data[17] = ((u8*)gamma)[16];
data[18] = ((u8*)gamma)[17];
data[19] = ((u8*)gamma)[18];
data[20] = ((u32)gamma[10] << 16) >> 24;
data[21] = gamma[10] & 0xc0;
data[22] = ((u32)gamma[11] << 16) >> 24;
data[23] = gamma[11] & 0xc0;
data[24] = ((u32)gamma[12] << 16) >> 24;
data[25] = gamma[12] & 0xc0;
data[26] = ((u32)gamma[13] << 16) >> 24;
data[27] = gamma[13] & 0xc0;
data[28] = ((u32)gamma[14] << 16) >> 24;
data[29] = gamma[14] & 0xc0;
data[30] = ((u32)gamma[15] << 16) >> 24;
data[31] = gamma[15] & 0xc0;
data[32] = ((u32)gamma[16] << 16) >> 24;
data[33] = gamma[16] & 0xc0;
__VISendI2CData(0xe0, data, 0x22);
WaitMicroTime(2);
}
void __VISetGamma(void) {
__VISetGammaImm(gammaSet[__gamma]);
}
void __VISetTrapFilter(void) {
u8 data[2];
data[0] = 3;
if (__filter == 1) {
data[1] = 0;
} else {
data[1] = 1;
}
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
}
void VISetTrapFilter(BOOL filter) {
if (__filter == (u32)filter) {
return;
}
__filter = filter;
Vdac_Flag_Changed_816991E0 |= 0x20;
}
void __VISetRGBOverDrive(void) {
u8 data[2];
if (Vdac_Flag_Region == 3) {
data[0] = 10;
data[1] = __level << 1 | 1;
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
} else {
data[0] = 10;
data[1] = 0;
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
}
}
void VISetRGBModeImm(void) {
Vdac_Flag_Changed_816991E0 |= 0x80;
}
void __VISetRGBModeImm(void) {
u8 data[2];
Vdac_Flag_Region = 3;
data[0] = 1;
data[1] = 3;
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
}
void __VISetRevolutionMode(void) {
u8 resetCommand[2];
u8 powerCommand[2];
u8 clockCommand[2];
u8 outputCommand[2];
u8 volumeCommand[3];
u8 syncCommand[2];
u8 enableCommand[2];
resetCommand[0] = 4;
resetCommand[1] = 0;
__VISendI2CData(0xe0, resetCommand, 2);
WaitMicroTime(2);
powerCommand[0] = 0x6a;
powerCommand[1] = 1;
__VISendI2CData(0xe0, powerCommand, 2);
WaitMicroTime(2);
clockCommand[0] = 0x65;
clockCommand[1] = 1;
__VISendI2CData(0xe0, clockCommand, 2);
WaitMicroTime(2);
__VISetYUVSEL(VIGetDTVStatus());
outputCommand[0] = 0;
outputCommand[1] = 0;
__VISendI2CData(0xe0, outputCommand, 2);
WaitMicroTime(2);
volumeCommand[0] = 0x71;
volumeCommand[1] = 0x8e;
volumeCommand[2] = 0x8e;
__VISendI2CData(0xe0, volumeCommand, 3);
WaitMicroTime(2);
syncCommand[0] = 2;
syncCommand[1] = 7;
__VISendI2CData(0xe0, syncCommand, 2);
WaitMicroTime(2);
if ((__wd0 != 0) || (__wd1 != 0) || (__wd2 != 0)) {
__wd0 = 0;
__wd1 = 0;
__wd2 = 0;
Vdac_Flag_Changed_816991E0 |= 1;
}
if ((__gp1 != 0) || (__gp2 != 0) || (__gp3 != 0) || (__gp4 != 0)) {
__gp1 = 0;
__gp2 = 0;
__gp3 = 0;
__gp4 = 0;
Vdac_Flag_Changed_816991E0 |= 2;
}
if ((__cc1 != 0) || (__cc2 != 0) || (__cc3 != 0) || (__cc4 != 0)) {
__cc1 = 0;
__cc2 = 0;
__cc3 = 0;
__cc4 = 0;
Vdac_Flag_Changed_816991E0 |= 4;
}
VISetMacrovision(1);
if (__filter != 0) {
__filter = 0;
Vdac_Flag_Changed_816991E0 |= 0x20;
}
if (__level != 0) {
__level = 0;
Vdac_Flag_Changed_816991E0 |= 0x40;
}
if (__gamma != 10) {
__gamma = 10;
Vdac_Flag_Changed_816991E0 |= 0x10;
}
VIFlush();
VIWaitForRetrace();
enableCommand[0] = 4;
enableCommand[1] = 1;
__VISendI2CData(0xe0, enableCommand, 2);
WaitMicroTime(2);
}
void __VISetRevolutionModeSimple(void) {
u32 i;
u8 powerCommand[2];
u8 clockCommand[2];
u8 outputCommand[2];
u8 volumeCommand[3];
u8 syncCommand[2];
u8 cgmsCommand[3];
u8 wssCommand[3];
u8 captionCommand[5];
u8 acpCommand[0x1c];
u8 driveCommand[2];
u8 filterCommand[2];
powerCommand[0] = 0x6a;
powerCommand[1] = 1;
__VISendI2CData(0xe0, powerCommand, 2);
WaitMicroTime(2);
clockCommand[0] = 0x65;
clockCommand[1] = 1;
__VISendI2CData(0xe0, clockCommand, 2);
WaitMicroTime(2);
__VISetYUVSEL(VIGetDTVStatus());
outputCommand[0] = 0;
outputCommand[1] = 0;
__VISendI2CData(0xe0, outputCommand, 2);
WaitMicroTime(2);
volumeCommand[0] = 0x71;
volumeCommand[1] = 0x8e;
volumeCommand[2] = 0x8e;
__VISendI2CData(0xe0, volumeCommand, 3);
WaitMicroTime(2);
syncCommand[0] = 2;
syncCommand[1] = 7;
__VISendI2CData(0xe0, syncCommand, 2);
WaitMicroTime(2);
__wd0 = 0;
__wd1 = 0;
__wd2 = 0;
cgmsCommand[0] = 5;
cgmsCommand[1] = 0;
cgmsCommand[2] = 0;
__VISendI2CData(0xe0, cgmsCommand, 3);
WaitMicroTime(2);
if ((__gp1 != 0) || (__gp2 != 0) || (__gp3 != 0) || (__gp4 != 0)) {
__gp1 = 0;
__gp2 = 0;
__gp3 = 0;
__gp4 = 0;
Vdac_Flag_Changed_816991E0 |= 2;
}
wssCommand[0] = 8;
wssCommand[1] = (__gp2 & 0xf) << 4 | __gp1 & 0xf;
wssCommand[2] = (__gp4 & 7) << 3 | __gp3 & 7;
__VISendI2CData(0xe0, wssCommand, 3);
WaitMicroTime(2);
if ((__cc1 != 0) || (__cc2 != 0) || (__cc3 != 0) || (__cc4 != 0)) {
__cc1 = 0;
__cc2 = 0;
__cc3 = 0;
__cc4 = 0;
Vdac_Flag_Changed_816991E0 |= 4;
}
captionCommand[0] = 0x7a;
captionCommand[1] = __cc1 & 0x7f;
captionCommand[2] = __cc2 & 0x7f;
captionCommand[3] = __cc3 & 0x7f;
captionCommand[4] = __cc4 & 0x7f;
__VISendI2CData(0xe0, captionCommand, 5);
WaitMicroTime(2);
for (i = 0; i < 0x1a; i++) {
acpCommand[i + 1] = VIZeroACPType[i];
}
acpCommand[0] = 0x40;
__VISendI2CData(0xe0, acpCommand, 0x1b);
WaitMicroTime(2);
if (__level != 0) {
__level = 0;
Vdac_Flag_Changed_816991E0 |= 0x40;
}
if (Vdac_Flag_Region == 3) {
driveCommand[0] = 10;
driveCommand[1] = __level << 1 | 1;
__VISendI2CData(0xe0, driveCommand, 2);
WaitMicroTime(2);
} else {
driveCommand[0] = 10;
driveCommand[1] = 0;
__VISendI2CData(0xe0, driveCommand, 2);
WaitMicroTime(2);
}
filterCommand[0] = 3;
filterCommand[1] = 1;
__VISendI2CData(0xe0, filterCommand, 2);
WaitMicroTime(2);
__VISetGammaImm(gammaSet[10]);
}
void __VIInit3in1(VITVMode mode) {
u8 data[2];
s32 value = (u32)mode >> 2;
u32 flag;
if (value == 2) {
goto region1;
}
if (value < 2) {
if (value == 0) {
goto region0;
}
if (value >= 0) {
goto region2;
}
goto regionDefault;
}
if (value == 5) {
goto region2;
}
goto regionDefault;
region0:
flag = 0;
goto send;
region1:
flag = 1;
goto send;
region2:
flag = 2;
goto send;
regionDefault:
flag = 0;
send:
Vdac_Flag_Region = flag;
data[0] = 1;
data[1] = flag;
__VISendI2CData(0xe0, data, 2);
WaitMicroTime(2);
__VISetRevolutionMode();
}

View File

@@ -4,19 +4,32 @@
#include <private/cdb/CDBAttr.h>
#include <private/cdb/CDBBridge.h>
#include <revolution/types.h>
#ifdef CDB_RECORD_IMPLEMENTATION
#include <revolution/os.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
typedef struct _CDBRecordFile {
#ifdef CDB_RECORD_IMPLEMENTATION
OSMutex mutex;
BOOL used;
#else
u8 unk_0x00[0x1C - 0x00];
#endif
int unk_0x1C;
CDBAttr attr; // 0x20
CDBBridgeFile bridgeFile; // 0x42C
u8 unk_0x434[0x438 - 0x434];
CDBRecordKey key; // 0x438
#ifdef CDB_RECORD_IMPLEMENTATION
u32 database;
u8 reserved[0x480 - 0x46C];
#else
u8 unk_0x468[0x480 - 0x468];
#endif
} CDBRecordFile;
enum {

View File

@@ -21,7 +21,9 @@ typedef struct NWC24MsgObjPrivate {
u32 type; // 0x04
u32 length; // 0x08
u32 appId; // 0x0C
#if defined(NWC24_MBOX_CTRL) || defined(NWC24_MSG_COMMIT)
#ifdef NWC24_MSG_READ
u32 headerSize;
#elif defined(NWC24_MBOX_CTRL) || defined(NWC24_MSG_COMMIT)
u32 unk_0x10;
#else
u8 unk_0x10[0x4];

View File

@@ -7,6 +7,9 @@
typedef struct PF_STR {
const pf_s8* p_head; // 0x00
const pf_s8* p_tail; // 0x04
#ifdef PF_FA_STR_LAYOUT
const pf_s8* p_current;
#endif
pf_u32 code_mode; // 0x08
} PF_STR;

View File

@@ -128,7 +128,19 @@ static const pf_u16 cp932_to_unicode[45][189] = {
0x6A5F, 0x5E30, 0x6BC5, 0x6C17, 0x6C7D, 0x757F, 0x7948, 0x5B63, 0x7A00, 0x7D00, 0x5FBD, 0x898F, 0x8A18, 0x8CB4, 0x8D77, 0x8ECC,
0x8F1D, 0x98E2, 0x9A0E, 0x9B3C, 0x4E80, 0x507D, 0x5100, 0x5993, 0x5B9C, 0x622F, 0x6280, 0x64EC, 0x6B3A, 0x72A0, 0x7591, 0x7947,
0x7FA9, 0x87FB, 0x8ABC, 0x8B70, 0x63AC, 0x83CA, 0x97A0, 0x5409, 0x5403, 0x55AB, 0x6854, 0x6A58, 0x8A70, 0x7827, 0x6775, 0x9ECD,
0x5374, 0x5BA2, 0x811A, 0x8650, 0x9006, 0x4E18, 0x4E45, 0x4EC7, 0x4F11, 0x53CA, 0x5438, 0x5BAE, 0x5F13, 0x6025, 0x6551, 0x0000,
0x5374, 0x5BA2,
#ifdef PF_FA_CP932_TABLE
0x0000
#else
0x811A
#endif
,
#ifdef PF_FA_CP932_TABLE
0x0000
#else
0x8650
#endif
, 0x9006, 0x4E18, 0x4E45, 0x4EC7, 0x4F11, 0x53CA, 0x5438, 0x5BAE, 0x5F13, 0x6025, 0x6551, 0x0000,
0x673D, 0x6C42, 0x6C72, 0x6CE3, 0x7078, 0x7403, 0x7A76, 0x7AAE, 0x7B08, 0x7D1A, 0x7CFE, 0x7D66, 0x65E7, 0x725B, 0x53BB, 0x5C45,
0x5DE8, 0x62D2, 0x62E0, 0x6319, 0x6E20, 0x865A, 0x8A31, 0x8DDD, 0x92F8, 0x6F01, 0x79A6, 0x9B5A, 0x4EA8, 0x4EAB, 0x4EAC, 0x4F9B,
0x4FA0, 0x50D1, 0x5147, 0x7AF6, 0x5171, 0x51F6, 0x5354, 0x5321, 0x537F, 0x53EB, 0x55AC, 0x5883, 0x5CE1, 0x5F37, 0x5F4A, 0x602F,
@@ -236,8 +248,20 @@ static const pf_u16 cp932_to_unicode[45][189] = {
0x6065, 0x667A, 0x6C60, 0x75F4, 0x7A1A, 0x7F6E, 0x81F4, 0x8718, 0x9045, 0x99B3, 0x7BC9, 0x755C, 0x7AF9, 0x7B51, 0x84C4, 0x0000,
0x9010, 0x79E9, 0x7A92, 0x8336, 0x5AE1, 0x7740, 0x4E2D, 0x4EF2, 0x5B99, 0x5FE0, 0x62BD, 0x663C, 0x67F1, 0x6CE8, 0x866B, 0x8877,
0x8A3B, 0x914E, 0x92F3, 0x99D0, 0x6A17, 0x7026, 0x732A, 0x82E7, 0x8457, 0x8CAF, 0x4E01, 0x5146, 0x51CB, 0x558B, 0x5BF5, 0x5E16,
0x5E33, 0x5E81, 0x5F14, 0x5F35, 0x5F6B, 0x5FB4, 0x61F2, 0x6311, 0x66A2, 0x671D, 0x6F6E, 0x7252, 0x753A, 0x773A, 0x8074, 0x8139,
0x8178, 0x8776, 0x8ABF, 0x8ADC, 0x8D85, 0x8DF3, 0x929A, 0x9577, 0x9802, 0x9CE5, 0x52C5, 0x6357, 0x76F4, 0x6715, 0x6C88, 0x73CD,
0x5E33, 0x5E81, 0x5F14, 0x5F35, 0x5F6B, 0x5FB4, 0x61F2, 0x6311, 0x66A2, 0x671D, 0x6F6E, 0x7252, 0x753A, 0x773A, 0x8074,
#ifdef PF_FA_CP932_TABLE
0x0000
#else
0x8139
#endif
,
#ifdef PF_FA_CP932_TABLE
0x0000
#else
0x8178
#endif
, 0x8776, 0x8ABF, 0x8ADC, 0x8D85, 0x8DF3, 0x929A, 0x9577, 0x9802, 0x9CE5, 0x52C5, 0x6357, 0x76F4, 0x6715, 0x6C88, 0x73CD,
0x8CC3, 0x93AE, 0x9673, 0x6D25, 0x589C, 0x690E, 0x69CC, 0x8FFD, 0x939A, 0x75DB, 0x901A, 0x585A, 0x6802, 0x63B4, 0x69FB, 0x4F43,
0x6F2C, 0x67D8, 0x8FBB, 0x8526, 0x7DB4, 0x9354, 0x693F, 0x6F70, 0x576A, 0x58F7, 0x5B2C, 0x7D2C, 0x722A, 0x540A, 0x91E3, 0x9DB4,
0x4EAD, 0x4F4E, 0x505C, 0x5075, 0x5243, 0x8C9E, 0x5448, 0x5824, 0x5B9A, 0x5E1D, 0x5E95, 0x5EAD, 0x5EF7, 0x5F1F, 0x608C, 0x62B5,
@@ -500,7 +524,19 @@ static const pf_u16 cp932_to_unicode[45][189] = {
},
{
0x968B, 0x8146, 0x813E, 0x8153, 0x8151, 0x80FC, 0x8171, 0x816E, 0x8165, 0x8166, 0x8174, 0x8183, 0x8188, 0x818A, 0x8180, 0x8182,
0x968B, 0x8146, 0x813E, 0x8153, 0x8151, 0x80FC, 0x8171, 0x816E, 0x8165,
#ifdef PF_FA_CP932_TABLE
0x0000
#else
0x8166
#endif
,
#ifdef PF_FA_CP932_TABLE
0x0000
#else
0x8174
#endif
, 0x8183, 0x8188, 0x818A, 0x8180, 0x8182,
0x81A0, 0x8195, 0x81A4, 0x81A3, 0x815F, 0x8193, 0x81A9, 0x81B0, 0x81B5, 0x81BE, 0x81B8, 0x81BD, 0x81C0, 0x81C2, 0x81BA, 0x81C9,
0x81CD, 0x81D1, 0x81D9, 0x81D8, 0x81C8, 0x81DA, 0x81DF, 0x81E0, 0x81E7, 0x81FA, 0x81FB, 0x81FE, 0x8201, 0x8202, 0x8205, 0x8207,
0x820A, 0x820D, 0x8210, 0x8216, 0x8229, 0x822B, 0x8238, 0x8233, 0x8240, 0x8259, 0x8258, 0x825D, 0x825A, 0x825F, 0x8264, 0x0000,

View File

@@ -86,10 +86,26 @@ CDBErr CDBRecordClose(CDBRecord* record);
CDBErr CDBRecordGetDataSize(CDBRecord* record, u32* recordSize);
CDBErr CDBRecordGetId(CDBRecord* record, CDBId* id);
#ifdef CDB_RECORD_IMPLEMENTATION
void CDBRecordGetCalendarTimeForce(CDBRecord* record, int* year, int* month, int* day, int* hour, int* min, int* sec);
#else
CDBErr CDBRecordGetCalendarTimeForce(CDBRecord* record, int* year, int* month, int* day, int* hour, int* min, int* sec);
#endif
#ifdef CDB_RECORD_IMPLEMENTATION
void CDBRecordGetKeyForce(CDBRecord* record, CDBRecordKey* recordKey);
#else
CDBErr CDBRecordGetKeyForce(CDBRecord* record, CDBRecordKey* recordKey);
#endif
#ifdef CDB_RECORD_IMPLEMENTATION
void CDBRecordGetTypeForce(CDBRecord* record, char* type);
#else
CDBErr CDBRecordGetTypeForce(CDBRecord* record, char* type);
#endif
#ifdef CDB_RECORD_IMPLEMENTATION
void CDBRecordGetGameCodeForce(CDBRecord* record, char* gcStr);
#else
CDBErr CDBRecordGetGameCodeForce(CDBRecord* record, char* gcStr);
#endif
CDBErr CDBRecordRemove(CDBRecord* record);

View File

@@ -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);
#if defined(NWC24_MSG_SUBJECT) || defined(NWC24_MSG_READ)
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,

View File

@@ -0,0 +1,211 @@
#include <revolution/types.h>
#include <string.h>
typedef struct {
int* values;
int capacity;
int size;
int direction;
} CDBIntArray;
void CDBIntCopy(int* destination, const int* value) {
*destination = *value;
}
int CDBIntCompare(const int* left, const int* right) {
if (*left < *right) {
return -1;
}
return *left != *right;
}
void CDBIntArrayInit(CDBIntArray* array, int* values, int capacity) {
array->size = 0;
array->direction = 1;
array->capacity = capacity;
array->values = values;
}
void CDBIntArraySetReverse(CDBIntArray* array) {
array->direction = -1;
}
int CDBIntArraySize(CDBIntArray* array) {
return array->size;
}
int* CDBIntArrayAt(CDBIntArray* array, int index) {
return array->values + index;
}
BOOL CDBIntArrayEmpty(CDBIntArray* array) {
return array->size == 0;
}
BOOL CDBIntArrayFull(CDBIntArray* array) {
return array->capacity <= array->size;
}
int* CDBIntArrayEnd(CDBIntArray* array) {
return array->values + array->size;
}
#pragma dont_inline on
int CDBIntArrayDicInsertR(CDBIntArray* array, int* value, int first, int last) {
int index;
int result;
if (first == last || first == last - 1) {
result = ((*(value) < *(array->values + first)) ? -1 : (*(value) != *(array->values + first)));
if (result < 0) {
return first;
}
result = ((*(value) < *(array->values + last)) ? -1 : (*(value) != *(array->values + last)));
index = last;
if (result >= 0) {
index = last + 1;
}
return index;
}
index = first + (last - first) / 2;
result = ((*(value) < *(array->values + index)) ? -1 : (*(value) != *(array->values + index)));
if (result < 0) {
return CDBIntArrayDicInsertR(array, value, first, index);
}
if (result > 0) {
return CDBIntArrayDicInsertR(array, value, index, last);
}
return index;
}
int* CDBIntArrayDicInsert(CDBIntArray* array, int* value) {
int size = array->size;
int index;
int moveCount;
int* record;
int number;
int stored;
if (size == 0) {
if (size < array->capacity) {
record = array->values + size;
*record = *value;
array->size++;
}
return value;
}
if (array->capacity <= size) {
if (array->direction == 1) {
if (size != 0) {
record = array->values + (size - 1);
} else {
record = array->values;
}
number = *value;
stored = *record;
if ((stored < number ? -1 : stored != number) < 0) {
return record;
}
array->size--;
index = CDBIntArrayDicInsertR(array, value, 0, array->size - 1);
moveCount = (array->size - index) * sizeof(int);
if (array->capacity <= array->size) {
moveCount -= sizeof(int);
}
if (moveCount > 0) {
memmove((array->values + (index + 1)), (array->values + index), moveCount);
}
*(array->values + index) = *value;
if (array->size < array->capacity) {
array->size++;
}
return (array->values + index);
}
record = array->values;
number = *value;
if ((number < *record ? -1 : number != *record) < 0) {
return record;
}
array->size--;
if (array->size >= 0 && array->capacity - 1 >= 0) {
memmove(array->values, array->values + 1, array->size * sizeof(int));
}
index = CDBIntArrayDicInsertR(array, value, 0, array->size - 1);
moveCount = (array->size - index) * sizeof(int);
if (array->capacity <= array->size) {
moveCount -= sizeof(int);
}
if (moveCount > 0) {
memmove((array->values + (index + 1)), (array->values + index), moveCount);
}
*(array->values + index) = *value;
if (array->size < array->capacity) {
array->size++;
}
return (array->values + index);
}
index = CDBIntArrayDicInsertR(array, value, 0, size - 1);
moveCount = (array->size - index) * sizeof(int);
if (array->capacity <= array->size) {
moveCount -= sizeof(int);
}
if (moveCount > 0) {
memmove((array->values + (index + 1)), (array->values + index), moveCount);
}
*(array->values + index) = *value;
if (array->size < array->capacity) {
array->size++;
}
return (array->values + index);
}
int CDBIntArrayDicFindR(CDBIntArray* array, int* value, int first, int last) {
int index;
int result;
if (first == last || first == last - 1) {
result = ((*(value) < *(array->values + first)) ? -1 : (*(value) != *(array->values + first)));
if (result == 0) {
return first;
}
result = ((*(value) < *(array->values + last)) ? -1 : (*(value) != *(array->values + last)));
return result != 0 ? -1 : last;
}
index = first + (last - first) / 2;
result = ((*(value) < *(array->values + index)) ? -1 : (*(value) != *(array->values + index)));
if (result < 0) {
return CDBIntArrayDicFindR(array, value, first, index);
}
if (result > 0) {
return CDBIntArrayDicFindR(array, value, index, last);
}
return index;
}
#pragma dont_inline reset
int* CDBIntArrayDicFind(CDBIntArray* array, int* value) {
int size = array->size;
int index;
if (size == 0) {
return array->values + size;
}
index = CDBIntArrayDicFindR(array, value, 0, size - 1);
if (index != -1) {
return array->values + index;
}
return array->values + array->size;
}

View File

@@ -0,0 +1,953 @@
#define CDB_RECORD_IMPLEMENTATION
#include <private/cdb.h>
#include <revolution/cdb.h>
#include <revolution/net/NETDigest.h>
#include <revolution/os.h>
#include <stddef.h>
#include <string.h>
typedef struct {
u8 state[0xC010];
u32 openFlags;
} CDBRecordDatabaseState;
typedef struct {
u8 buf[0xD0];
} NETHMACContext;
typedef struct {
u8 buf[0x120];
} NETAESContext;
extern CDBErr CDBCryptBufAllocate(CDBCryptBuf** cryptBuf);
extern CDBErr CDBCryptBufFree(CDBCryptBuf** cryptBuf);
extern void CDBLock(void);
extern void CDBUnlock(void);
extern BOOL CDBRecordBelongedDBOpenedAsRW(CDBRecord* record);
extern void CDBGetWiiIdKey(char* wiiIdKey);
extern void CDBCopyWiiIdKey(char* wiiIdKey1, char* wiiIdKey2);
extern void CDBGetDeviceKey(char* devKey);
extern BOOL CDBFSIsExistFile(const char* fileName, CDBLocation location);
extern const void* NETGetSHA1Interface(void);
extern void NETHMACInit(NETHMACContext* context, const void* interface, const void* key, u32 keyLength);
extern void NETHMACUpdate(NETHMACContext* context, const void* data, u32 length);
extern void NETHMACGetDigest(NETHMACContext* context, void* digest);
extern BOOL NETAESCreate(NETAESContext* context, const void* key, u32 keyLength, const void* iv);
extern void NETAESDelete(NETAESContext* context);
extern BOOL NETAESEncrypt(NETAESContext* context, void* dst, const void* src, u32 length);
extern BOOL NETAESDecrypt(NETAESContext* context, void* dst, const void* src, u32 length);
static u8 s_cdbCryptBuffer[0x40] ALIGN32;
static u8 s_cdbCryptBufferResult[0x40] ALIGN32;
static const u8 s_cdbCryptKey[0x10] = {0};
CDBErr CDBRecordOpen_(CDBRecord* record);
CDBErr CDBRecordOpenReadOnly_(CDBRecord* record);
CDBErr CDBRecordClose_(CDBRecord* record);
CDBErr CDBRecordWrite_(CDBRecord* record, void* buffer, u32 size);
CDBErr CDBRecordRemove_(CDBRecord* record);
CDBErr CDBRecordBackupToSD_(CDBRecord* record);
CDBErr CDBRecordUpdateModifiedDate(CDBRecord* record);
CDBErr CDBRecordEncrypt(CDBRecord* record, void* buffer, CDBRecordKey* key, u32 size, u32* encryptedSize);
CDBErr CDBRecordDecrypt(CDBRecord* record, void* buffer, u32 size, u32* dataSize, CDBRecordKey* key);
void CDBRecordInstanceInit(CDBRecordFile* recordFile, CDBRecord* record, int type) {
OSLockMutex((OSMutex*)recordFile);
recordFile->used = 1;
OSUnlockMutex((OSMutex*)recordFile);
recordFile->unk_0x1C = type;
recordFile->database = record->unk_0x00;
CDBAttrInit(&recordFile->attr);
CDBRecordKeyCopy(&recordFile->key, &record->key);
}
BOOL CDBRecordInstanceIsUsed(CDBRecordFile* recordFile) {
BOOL used;
OSLockMutex((OSMutex*)recordFile);
used = recordFile->used;
OSUnlockMutex((OSMutex*)recordFile);
return used;
}
void CDBRecordInitDescriptor(CDBRecord* record, CDBDatabase* database, CDBRecordKey* key) {
CDBLock();
record->unk_0x00 = (u32)database;
CDBRecordKeyCopy(&record->key, key);
record->cryptBuf = NULL;
record->file = NULL;
CDBUnlock();
}
CDBErr CDBRecordCreateAtOnce(CDBRecord* record, CDBDatabase* database, const char* desc, char* fileType, CDBDate epoch, int gameCode, u16 makerCode,
void* buffer, u32 size) {
CDBRecordKey key;
CDBAttr attr;
CDBErr err;
if (strlen(fileType) >= 6) {
return CDB_ERROR_19;
}
if (size < CDB_RECORD_BUFFER_SIZE) {
return CDB_ERROR_20;
}
CDBRecordKeyInit(&key, epoch, gameCode, makerCode, 0, fileType, CDB_FS_LOCATION_NAND);
CDBLock();
record->unk_0x00 = (u32)database;
CDBRecordKeyCopy(&record->key, &key);
record->cryptBuf = NULL;
record->file = NULL;
CDBUnlock();
err = CDBAttrCreateOnNAND(&attr, desc, epoch);
if (err != CDB_ERROR_OK) {
return err;
}
err = CDBAttrSetModifiedCount(&attr, 1);
if (err != CDB_ERROR_OK) {
return err;
}
memcpy(buffer, &attr, CDB_RECORD_BUFFER_SIZE);
return CDBRecordFileCreateAtOnce(record, buffer, size);
}
CDBErr CDBRecordOpen(CDBRecord* record) {
CDBErr err;
CDBLock();
err = CDBRecordOpen_(record);
CDBUnlock();
return err;
}
CDBErr CDBRecordOpen_(CDBRecord* record) {
char fullPath[256];
CDBCryptBuf* cryptBuf;
CDBErr err;
CDBDatabase* database;
CDBRecordDatabaseState* instance;
database = (CDBDatabase*)record->unk_0x00;
instance = database->instance;
record->cryptBuf = NULL;
if (instance == NULL) {
CDBReportError("(CDB) error : can't open the record; the database is closed\n");
return CDB_ERROR_27;
}
if ((instance->openFlags & 2) == 0) {
CDBReportError("can't open the record; the database is READONLY\n");
return CDB_ERROR_26;
}
CDBConvKeyToFullPath(&record->key, fullPath);
err = CDBRecordFileOpen(record, fullPath, CDB_RECORD_ALLOC_RW);
if (err != CDB_ERROR_OK) {
return err;
}
err = CDBRecordFileReadAttrBuf(record);
if (err != CDB_ERROR_OK) {
return err;
}
if (record->key.location == CDB_FS_LOCATION_SD) {
err = CDBCryptBufAllocate((CDBCryptBuf**)&record->cryptBuf);
if (err != CDB_ERROR_OK) {
return err;
}
cryptBuf = (CDBCryptBuf*)record->cryptBuf;
if (record == NULL || !CDBRecordKeyIsValid(&record->key)) {
err = CDB_ERROR_1;
} else {
if (record->key.location == CDB_FS_LOCATION_SD) {
goto open_location_ok;
}
err = CDB_ERROR_2;
goto open_result_ready;
open_location_ok:
if (CDBFSSDIsMounted()) {
err = CDBRecordDecrypt(record, cryptBuf, 0x3EC00, &cryptBuf->unk_0x3EC00, NULL);
} else {
err = CDB_ERROR_SD_IS_NOT_MOUNTED;
}
}
open_result_ready:
if (err != CDB_ERROR_OK) {
CDBCryptBufFree((CDBCryptBuf**)&record->cryptBuf);
return err;
}
cryptBuf->unk_0x3EC04 = sizeof(CDBAttrBuf);
}
return CDB_ERROR_OK;
}
CDBErr CDBRecordOpenReadOnly(CDBRecord* record) {
CDBErr err;
CDBLock();
err = CDBRecordOpenReadOnly_(record);
CDBUnlock();
return err;
}
CDBErr CDBRecordOpenReadOnly_(CDBRecord* record) {
char fullPath[260];
CDBErr err;
CDBErr result;
CDBCryptBuf* cryptBuf;
record->cryptBuf = NULL;
if (!CDBRecordKeyIsValid(&record->key)) {
CDBReportError("invalid key\n");
return CDB_ERROR_5;
}
CDBConvKeyToFullPath(&record->key, fullPath);
err = CDBRecordFileOpen(record, fullPath, CDB_RECORD_ALLOC_READ);
if (err != CDB_ERROR_OK) {
return err;
}
err = CDBRecordFileReadAttrBuf(record);
if (err != CDB_ERROR_OK) {
return err;
}
if (record->key.location == CDB_FS_LOCATION_SD) {
err = CDBCryptBufAllocate((CDBCryptBuf**)&record->cryptBuf);
if (err != CDB_ERROR_OK) {
return err;
}
cryptBuf = (CDBCryptBuf*)record->cryptBuf;
if (record == NULL || !CDBRecordKeyIsValid(&record->key)) {
result = CDB_ERROR_1;
} else {
if (record->key.location == CDB_FS_LOCATION_SD) {
goto location_ok;
}
result = CDB_ERROR_2;
goto result_ready;
location_ok:
if (CDBFSSDIsMounted()) {
result = CDBRecordDecrypt(record, cryptBuf, 0x3EC00, &cryptBuf->unk_0x3EC00, NULL);
} else {
result = CDB_ERROR_SD_IS_NOT_MOUNTED;
}
}
result_ready:
if (result != CDB_ERROR_OK) {
CDBCryptBufFree((CDBCryptBuf**)&record->cryptBuf);
return result;
}
cryptBuf->unk_0x3EC04 = sizeof(CDBAttrBuf);
}
return CDB_ERROR_OK;
}
CDBErr CDBRecordClose(CDBRecord* record) {
CDBErr err;
CDBLock();
err = CDBRecordClose_(record);
CDBUnlock();
return err;
}
CDBErr CDBRecordClose_(CDBRecord* record) {
CDBRecordFile* recordFile;
CDBErr err;
recordFile = record->file;
if (record->cryptBuf != NULL) {
err = CDBCryptBufFree((CDBCryptBuf**)&record->cryptBuf);
if (err != CDB_ERROR_OK) {
return err;
}
}
if (recordFile == NULL) {
return CDB_ERROR_27;
}
err = CDBRecordFileWriteAttrBuf(record);
if (err != CDB_ERROR_OK && err != CDB_ERROR_SD_EJECTED && err != CDB_ERROR_VF_ERROR) {
return err;
}
err = CDBRecordFileClose(record);
if (err != CDB_ERROR_OK) {
return err;
}
if (record->key.location == CDB_FS_LOCATION_NAND) {
err = CDBVFSync();
if (err != CDB_ERROR_OK) {
return err;
}
}
return CDB_ERROR_OK;
}
CDBErr CDBRecordWrite(CDBRecord* record, void* buffer, u32 size) {
CDBErr err;
CDBLock();
err = CDBRecordWrite_(record, buffer, size);
CDBUnlock();
return err;
}
CDBErr CDBRecordWrite_(CDBRecord* record, void* buffer, u32 size) {
CDBRecordFile* recordFile;
CDBDatabase* database;
CDBErr err;
CDBErr result;
CDBRecordDatabaseState* instance;
database = (CDBDatabase*)record->unk_0x00;
instance = database->instance;
recordFile = record->file;
if (record->key.location == CDB_FS_LOCATION_SD) {
return CDB_ERROR_ACCESS_DENIED;
}
if ((instance->openFlags & 2) == 0) {
CDBReportError("can't write data in the record; the database is opened as READONLY\n");
return CDB_ERROR_26;
}
if (!CDBRecordBelongedDBOpenedAsRW(record)) {
CDBReportError("can't write data in the record; permission denied\n");
return CDB_ERROR_ACCESS_DENIED;
}
if (recordFile == NULL) {
CDBReportError("can't write data in the record; the record is closed\n");
return CDB_ERROR_27;
}
if ((recordFile->unk_0x1C & 2) == 0) {
CDBReportError("can't write data in the record; the record is opened as READONLY\n");
return CDB_ERROR_27;
}
err = CDBRecordFileWriteData(record, buffer, size);
if (err != CDB_ERROR_OK) {
return err;
}
err = CDBRecordUpdateModifiedDate(record);
result = CDB_ERROR_OK;
if (err != CDB_ERROR_OK) {
result = err;
}
return result;
}
CDBErr CDBRecordRead(CDBRecord* record, void* buffer, u32 size, u32* readSize) {
CDBErr err;
CDBLock();
if (record->file == NULL) {
CDBReportError("can't read data in the record; the record is closed\n");
err = CDB_ERROR_27;
} else {
err = CDBRecordFileReadData(record, buffer, size, readSize);
}
CDBUnlock();
return err;
}
CDBErr CDBRecordSeek(CDBRecord* record, s32 offset, CDBSeek seek) {
CDBErr err;
CDBLock();
if (record->file == NULL) {
err = CDB_ERROR_27;
} else {
switch (seek) {
case CDB_SEEK_CUR: {
err = CDBRecordFileSeekData(record, offset, CDB_SEEK_CUR);
break;
}
case CDB_SEEK_BEGIN: {
err = CDBRecordFileSeekData(record, offset, CDB_SEEK_BEGIN);
break;
}
case CDB_SEEK_END: {
err = CDBRecordFileSeekData(record, offset, CDB_SEEK_END);
break;
}
default:
err = CDB_ERROR_1;
break;
}
}
CDBUnlock();
return err;
}
CDBErr CDBRecordGetDataSize(CDBRecord* record, u32* size) {
CDBErr err;
CDBLock();
if (record->file == NULL) {
CDBReportError("can't get data size of the record ; the record is closed\n");
err = CDB_ERROR_27;
} else {
err = CDBRecordFileGetDataSize(record, size);
}
CDBUnlock();
return err;
}
CDBErr CDBRecordRemove(CDBRecord* record) {
CDBErr err;
CDBLock();
err = CDBRecordRemove_(record);
CDBUnlock();
return err;
}
CDBErr CDBRecordRemove_(CDBRecord* record) {
CDBErr err;
CDBErr result;
if (record->file != NULL) {
CDBReportError("can't remove the record ; the record is opened\n");
return CDB_ERROR_28;
}
if (!CDBRecordBelongedDBOpenedAsRW(record)) {
CDBReportError("can't remove the record ; permission denied\n");
return CDB_ERROR_ACCESS_DENIED;
}
err = CDBRecordFileDelete(record);
if (err != CDB_ERROR_OK) {
return err;
}
err = CDBVFSync();
result = CDB_ERROR_OK;
if (err != CDB_ERROR_OK) {
result = err;
}
return result;
}
void CDBRecordGetTypeForce(CDBRecord* record, char* type) {
CDBLock();
CDBConvKeyStrToType(record->key.keyString, type);
CDBUnlock();
}
void CDBRecordGetGameCodeForce(CDBRecord* record, char* gameCode) {
u32 value;
CDBLock();
CDBConvKeyStrToGameCode(record->key.keyString, &value);
CDBConvGCValueToGCStr(value, gameCode);
CDBUnlock();
}
void CDBRecordGetKeyForce(CDBRecord* record, CDBRecordKey* key) {
CDBLock();
CDBRecordKeyCopy(key, &record->key);
CDBUnlock();
}
void CDBRecordGetCalendarTimeForce(CDBRecord* record, int* year, int* month, int* day, int* hour, int* min, int* sec) {
char epochString[64];
CDBDate epoch;
CDBLock();
CDBConvKeyStrToEpochStr(record->key.keyString, epochString);
CDBConvEpochStrToEpochValue(epochString, &epoch);
CDBConvEpochValueToDate(epoch, year, month, day, hour, min, sec);
CDBUnlock();
}
CDBErr CDBRecordGetId(CDBRecord* record, CDBId* id) {
CDBErr err = CDB_ERROR_OK;
CDBRecordFile* recordFile;
char epochString[64];
CDBLock();
recordFile = record->file;
if (recordFile == NULL) {
CDBReportError("can't get CDBId of the record ; the record is closed\n");
err = CDB_ERROR_27;
goto get_id_done;
} else {
CDBLock();
if (record->file == NULL) {
CDBReportError("can't get CDBId of the record ; the record is closed\n");
err = CDB_ERROR_27;
} else {
CDBLock();
CDBConvKeyStrToEpochStr(record->key.keyString, epochString);
CDBConvEpochStrToEpochValue(epochString, &id->num);
CDBUnlock();
err = CDB_ERROR_OK;
}
CDBUnlock();
}
switch (err) {
case CDB_ERROR_OK:
err = CDBAttrGetIDNumber(&recordFile->attr, (CDBId*)&id->modifiedCount);
err = CDB_ERROR_OK;
break;
default:
goto get_id_done;
}
get_id_done:
CDBUnlock();
return err;
}
BOOL CDBRecordIsExistFile(CDBRecord* record) {
char fullPath[256];
CDBConvKeyToFullPath(&record->key, fullPath);
return CDBFSIsExistFile(fullPath, record->key.location);
}
CDBErr CDBRecordUpdateModifiedDate(CDBRecord* record) {
s64 ticks;
u32 modifiedDate;
u32 modifiedCount;
CDBRecordFile* recordFile;
CDBErr err;
ticks = OSGetTime();
modifiedDate = ticks / (OS_BUS_CLOCK / 4);
recordFile = record->file;
if ((((CDBRecordDatabaseState*)((CDBDatabase*)record->unk_0x00)->instance)->openFlags & 2) == 0) {
CDBReportError("can't set modified time of the record; the database is opened as READONLY\n");
return CDB_ERROR_26;
}
if (recordFile == NULL) {
CDBReportError("can't set modified time of the record ; the record is closed\n");
return CDB_ERROR_27;
}
err = CDBAttrSetModifiedDate(&recordFile->attr, modifiedDate);
if (err != CDB_ERROR_OK) {
return err;
}
err = CDBAttrGetModifiedCount(&recordFile->attr, &modifiedCount);
if (err != CDB_ERROR_OK) {
return err;
}
modifiedCount++;
err = CDBAttrSetModifiedCount(&recordFile->attr, modifiedCount);
if (err != CDB_ERROR_OK) {
return err;
}
return CDB_ERROR_OK;
}
CDBErr CDBRecordBackupToSD(CDBRecord* record) {
CDBErr err;
CDBLock();
err = CDBRecordBackupToSD_(record);
CDBUnlock();
return err;
}
CDBErr CDBRecordBackupToSD_(CDBRecord* record) {
CDBRecordFile* recordFile;
CDBCryptBuf* cryptBuf;
CDBRecord localRecord;
CDBErr err;
u32 encryptedSize;
localRecord.cryptBuf = NULL;
recordFile = NULL;
if (record == NULL || !CDBRecordKeyIsValid(&record->key)) {
return CDB_ERROR_1;
}
if (record->key.location != CDB_FS_LOCATION_NAND) {
return CDB_ERROR_2;
}
if (!CDBFSSDIsMounted()) {
return CDB_ERROR_SD_IS_NOT_MOUNTED;
}
err = CDBCryptBufAllocate((CDBCryptBuf**)&localRecord.cryptBuf);
if (err != CDB_ERROR_OK) {
CDBLock();
CDBRecordClose_(&localRecord);
CDBUnlock();
return err;
}
cryptBuf = localRecord.cryptBuf;
CDBRecordKeyCopy(&localRecord.key, &record->key);
localRecord.file = NULL;
localRecord.key.location = CDB_FS_LOCATION_SD;
localRecord.unk_0x00 = record->unk_0x00;
err = CDBRecordFileCreateBlank(&localRecord);
if (err != CDB_ERROR_OK) {
CDBLock();
CDBRecordClose_(&localRecord);
CDBUnlock();
return err;
}
err = CDBRecordEncrypt(record, cryptBuf, &localRecord.key, 0x3EC00, &encryptedSize);
if (err != CDB_ERROR_OK) {
CDBLock();
CDBRecordClose_(&localRecord);
CDBUnlock();
CDBRecordFileDelete(&localRecord);
return err;
}
err = CDBRecordFileDump(&localRecord, cryptBuf, encryptedSize);
if (err != CDB_ERROR_OK) {
CDBLock();
CDBRecordClose_(&localRecord);
CDBUnlock();
return err;
}
CDBLock();
err = CDBRecordClose_(record);
CDBUnlock();
if (err != CDB_ERROR_OK) {
CDBLock();
CDBRecordClose_(&localRecord);
CDBUnlock();
return err;
}
CDBLock();
err = CDBRecordRemove_(record);
CDBUnlock();
if (err != CDB_ERROR_OK) {
CDBLock();
CDBRecordClose_(&localRecord);
CDBUnlock();
return err;
}
CDBLock();
recordFile = localRecord.file;
CDBRecordKeyCopy(&record->key, &localRecord.key);
record->unk_0x00 = localRecord.unk_0x00;
record->file = localRecord.file;
record->cryptBuf = localRecord.cryptBuf;
CDBRecordKeyCopy(&recordFile->key, &localRecord.key);
CDBUnlock();
return CDB_ERROR_OK;
}
CDBErr CDBCryptBuffer(void* buffer, u32 size, void* iv, u32* processedSize, BOOL encrypt) {
NETAESContext context ATTRIBUTE_ALIGN(64);
u32 offset;
u32 length;
if (processedSize) {
*processedSize = 0;
}
if (!NETAESCreate(&context, s_cdbCryptKey, 16, iv)) {
CDBReportError("NETAESCreate\n");
return CDB_ERROR_14;
}
offset = 0;
while (offset < size) {
if (processedSize) {
*processedSize += 64;
}
if (offset + 64 < size) {
length = 64;
} else {
length = size - offset;
memset(s_cdbCryptBuffer, 0, 64);
}
memcpy(s_cdbCryptBuffer, (u8*)buffer + offset, length);
if (encrypt) {
if (!NETAESEncrypt(&context, s_cdbCryptBufferResult, s_cdbCryptBuffer, 64)) {
CDBReportError("NETAESEncrypt\n");
NETAESDelete(&context);
return CDB_ERROR_14;
}
} else {
if (!NETAESDecrypt(&context, s_cdbCryptBufferResult, s_cdbCryptBuffer, 64)) {
CDBReportError("NETAESDecrypt\n");
NETAESDelete(&context);
return CDB_ERROR_14;
}
}
memcpy((u8*)buffer + offset, s_cdbCryptBufferResult, 64);
offset += 64;
}
NETAESDelete(&context);
return CDB_ERROR_OK;
}
CDBErr CDBRecordEncrypt(CDBRecord* record, void* buffer, CDBRecordKey* key, u32 size, u32* encryptedSize) {
CDBRecordFile* recordFile;
CDBErr err;
u32 fileSize;
u32 dataSize;
u32 cryptSize;
int fileOffset;
u8 iv[0x10];
u8 wiiIdKey[0x40] ATTRIBUTE_ALIGN(64);
u8 digest[0x14] ATTRIBUTE_ALIGN(64);
CDBAttrSignature signature ATTRIBUTE_ALIGN(64);
NETHMACContext hmac ATTRIBUTE_ALIGN(64);
recordFile = record->file;
memset(wiiIdKey, 0, sizeof(wiiIdKey));
memset(&signature, 0, sizeof(signature));
memset(buffer, 0, size);
if ((s32)recordFile == 0) {
return CDB_ERROR_27;
}
if (recordFile->unk_0x1C == 1) {
return CDB_ERROR_26;
}
if ((s32)buffer == 0) {
return CDB_ERROR_1;
}
{
CDBErr result;
CDBRecordFile* tempFile;
tempFile = record->file;
if ((s32)tempFile == 0) {
result = CDB_ERROR_27;
} else if (tempFile->unk_0x1C == 1) {
result = CDB_ERROR_26;
} else {
CDBAttrSetWiiId(&tempFile->attr, CDBGetWiiId());
result = CDB_ERROR_OK;
}
if (result != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
}
{
CDBErr result;
if ((s32)record->file == 0) {
result = CDB_ERROR_27;
} else if (((CDBRecordFile*)record->file)->unk_0x1C == 1) {
result = CDB_ERROR_26;
} else {
CDBAttrInitIV(&((CDBRecordFile*)record->file)->attr);
result = CDB_ERROR_OK;
}
if (result != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
}
{
CDBErr result;
if ((s32)record->file == 0) {
result = CDB_ERROR_27;
} else if (((CDBRecordFile*)record->file)->unk_0x1C == 1) {
result = CDB_ERROR_26;
} else {
CDBAttrSetKeyStr(&((CDBRecordFile*)record->file)->attr, key);
result = CDB_ERROR_OK;
}
if (result != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
}
CDBLock();
if ((s32)record->file == 0) {
CDBReportError("can't get file size of the record ; the record is closed\n");
err = CDB_ERROR_27;
} else {
err = CDBRecordFileGetFileSize(record, &fileSize);
}
CDBUnlock();
CDBAttrSetFileSize(&recordFile->attr, fileSize);
if (err != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
CDBLock();
if ((s32)record->file == 0) {
CDBReportError("can't get data size of the record ; the record is closed\n");
err = CDB_ERROR_27;
} else {
err = CDBRecordFileGetDataSize(record, &dataSize);
}
CDBUnlock();
if (err != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
if (size < dataSize + CDB_RECORD_BUFFER_SIZE) {
return CDB_ERROR_20;
}
memcpy(buffer, &recordFile->attr, CDB_RECORD_BUFFER_SIZE);
CDBLock();
if ((s32)record->file == 0) {
err = CDB_ERROR_27;
} else {
fileOffset = CDBRecordFileTellData(record);
if (fileOffset < 0) {
err = CDB_ERROR_CANNOT_OPEN_FILE;
} else {
err = CDB_ERROR_OK;
}
}
CDBUnlock();
if (err != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
CDBLock();
if ((s32)record->file == 0) {
err = CDB_ERROR_27;
} else {
err = CDBRecordFileSeekData(record, 0, CDB_SEEK_BEGIN);
}
CDBUnlock();
if (err != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
CDBLock();
if ((s32)record->file == 0) {
CDBReportError("can't read data in the record; the record is closed\n");
err = CDB_ERROR_27;
} else {
err = CDBRecordFileReadData(record, (u8*)buffer + CDB_RECORD_BUFFER_SIZE, size - CDB_RECORD_BUFFER_SIZE, &dataSize);
}
CDBUnlock();
if (err != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
CDBLock();
if ((s32)record->file == 0) {
err = CDB_ERROR_27;
} else {
err = CDBRecordFileSeekData(record, fileOffset, CDB_SEEK_BEGIN);
}
CDBUnlock();
if (err != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
CDBAttrGetIV(&recordFile->attr, iv);
err = CDBCryptBuffer((u8*)buffer + CDB_RECORD_BUFFER_SIZE, dataSize, iv, &cryptSize, TRUE);
if (err != CDB_ERROR_OK) {
return err;
}
CDBGetWiiIdKey((char*)wiiIdKey);
CDBGetDeviceKey((char*)&wiiIdKey[12]);
CDBAttrClearSignature((CDBAttr*)buffer);
NETHMACInit(&hmac, NETGetSHA1Interface(), wiiIdKey, 0x40);
NETHMACUpdate(&hmac, buffer, cryptSize + CDB_RECORD_BUFFER_SIZE);
NETHMACGetDigest(&hmac, digest);
memcpy(((CDBAttrBuf*)buffer)->signature.sha1Hmac, digest, sizeof(digest));
if (encryptedSize != 0) {
*encryptedSize = cryptSize + CDB_RECORD_BUFFER_SIZE;
}
return CDB_ERROR_OK;
}
CDBErr CDBRecordDecrypt(CDBRecord* record, void* buffer, u32 size, u32* dataSize, CDBRecordKey* key) {
CDBErr status;
int fileOffset;
CDBRecordFile* recordFile;
u32 fileDataSize;
u32 fileSize;
u8 iv[16];
CDBRecordKey comparisonKey;
u8 digest[20] ATTRIBUTE_ALIGN(64);
u8 wiiIdKey[64] ATTRIBUTE_ALIGN(16);
NETHMACContext hmac;
CDBAttrSignature signature;
recordFile = record->file;
memset(wiiIdKey, 0, sizeof(wiiIdKey));
memset(&signature, 0, sizeof(signature));
memset(buffer, 0, size);
if ((s32)recordFile == 0) {
return CDB_ERROR_27;
}
if ((s32)buffer == 0) {
return CDB_ERROR_1;
}
{
CDBLock();
if ((s32)record->file == 0) {
CDBReportError("can't get data size of the record ; the record is closed\n");
status = CDB_ERROR_27;
} else {
status = CDBRecordFileGetDataSize(record, &fileDataSize);
}
CDBUnlock();
if (status != CDB_ERROR_OK) {
return CDB_ERROR_OK;
}
}
if (size < fileDataSize + CDB_RECORD_BUFFER_SIZE) {
if (fileDataSize > 0x3E800) {
return CDB_ERROR_32;
}
return CDB_ERROR_20;
}
if ((fileDataSize & 0x3F) != 0) {
return CDB_ERROR_32;
}
{
CDBErr err;
err = CDBRecordFileReadAttrBuf(record);
if (err != CDB_ERROR_OK) {
return CDB_ERROR_32;
}
}
memcpy(buffer, &recordFile->attr, CDB_RECORD_BUFFER_SIZE);
{
CDBErr err;
int offset;
if ((s32)record->file == 0) {
err = CDB_ERROR_27;
} else {
offset = CDBRecordFileTellDataFile(record);
if (offset < 0) {
err = CDB_ERROR_CANNOT_OPEN_FILE;
} else {
fileOffset = offset;
err = CDB_ERROR_OK;
}
}
if (err != CDB_ERROR_OK) {
return err;
}
}
{
CDBErr err;
if ((s32)record->file == 0) {
err = CDB_ERROR_27;
} else {
err = CDBRecordFileSeekDataFile(record, 0, CDB_SEEK_BEGIN);
}
if (err != CDB_ERROR_OK) {
return err;
}
}
{
CDBErr err;
err = CDBRecordFileReadDataFile(record, (u8*)buffer + CDB_RECORD_BUFFER_SIZE, size - CDB_RECORD_BUFFER_SIZE, &fileDataSize);
if (err != CDB_ERROR_OK) {
return err;
}
}
{
CDBErr err;
if ((s32)record->file == 0) {
err = CDB_ERROR_27;
} else {
err = CDBRecordFileSeekDataFile(record, fileOffset, CDB_SEEK_BEGIN);
}
if (err != CDB_ERROR_OK) {
return err;
}
}
CDBAttrGetSignature((CDBAttr*)buffer, &signature);
CDBAttrClearSignature((CDBAttr*)buffer);
if ((s32)key == 0) {
CDBGetWiiIdKey((char*)wiiIdKey);
} else {
CDBCopyWiiIdKey((char*)wiiIdKey, (char*)key);
}
CDBGetDeviceKey((char*)&wiiIdKey[12]);
status = fileDataSize + CDB_RECORD_BUFFER_SIZE;
NETHMACInit(&hmac, NETGetSHA1Interface(), wiiIdKey, 0x40);
NETHMACUpdate(&hmac, buffer, status);
NETHMACGetDigest(&hmac, digest);
if (memcmp(digest, signature.sha1Hmac, 0x14) != 0) {
return CDB_ERROR_32;
}
CDBAttrGetKeyStr((CDBAttr*)buffer, comparisonKey.keyString);
if (CDBRecordKeyCompareByDate(&comparisonKey, &record->key) != 0) {
if (CDBIsPrintDebugMessage(3)) {
CDBReport_(3);
OSReport("CDBRecordPrivateChangeOwner\n");
}
return CDB_ERROR_32;
}
CDBAttrGetIV(&recordFile->attr, iv);
{
CDBErr err;
err = CDBCryptBuffer((u8*)buffer + CDB_RECORD_BUFFER_SIZE, fileDataSize, iv, NULL, FALSE);
if (err != CDB_ERROR_OK) {
return err;
}
}
if (dataSize != 0) {
CDBAttrGetFileSize((CDBAttr*)buffer, &fileSize);
*dataSize = fileSize;
}
return CDB_ERROR_OK;
}

View File

@@ -0,0 +1,236 @@
#include <private/nwc24/NWC24Utils.h>
static const u8 DAYS_OF_MONTH[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static const u16 DAYS_OF_YEAR[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
s32 ConvertDateToDays(u16 year, u8 month, u8 day);
void ConvertDaysToDate(u16* year, u8* month, u8* day, s32 days);
static inline BOOL IsLeapYear(u16 year) {
BOOL leap = FALSE;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
leap = TRUE;
return leap;
}
NWC24Err NWC24iDateToMinutes(s32* minutes, const NWC24Date* date) {
s32 days;
s32 minutesInDay;
NWC24Err result;
u8 hour;
u8 minute;
days = ConvertDateToDays(date->year, date->month, date->day);
if (days == -1) {
result = NWC24_ERR_FAILED;
} else {
hour = date->hour;
minute = date->min;
if (hour > 23 || minute > 59) {
minutesInDay = -1;
} else {
minutesInDay = minute + hour * 60;
}
if (minutesInDay == -1 || date->sec > 60) {
result = NWC24_ERR_FAILED;
} else {
result = NWC24_OK;
*minutes = minutesInDay + days * 1440;
}
}
return result;
}
NWC24Err NWC24iMinutesToDate(NWC24Date* date, s32 minutes) {
s32 days;
if (minutes < 0) {
minutes = 0;
}
days = minutes / 1440;
minutes %= 1440;
date->hour = minutes / 60;
date->min = minutes % 60;
ConvertDaysToDate(&date->year, &date->month, &date->day, days);
return NWC24_OK;
}
NWC24Err NWC24iEpochSecondsToDate(NWC24Date* date, s64 seconds) {
s64 elapsedMinutes;
s32 minutes;
s32 days;
if (seconds + 2208988800LL < 0) {
seconds = -2208988800LL;
}
date->sec = (seconds + 2208988800LL) % 60;
elapsedMinutes = (seconds + 2208988800LL) / 60;
if ((s32)elapsedMinutes < 0) {
elapsedMinutes = 0;
}
minutes = elapsedMinutes;
days = minutes / 1440;
minutes %= 1440;
date->hour = minutes / 60;
date->min = minutes % 60;
ConvertDaysToDate(&date->year, &date->month, &date->day, days);
return NWC24_OK;
}
NWC24Err NWC24iMinutesToOSCalendarTime(OSCalendarTime* calendar, s32 minutes) {
s32 days;
NWC24Date date;
BOOL isLeapYear;
if (minutes < 0) {
minutes = 0;
}
days = minutes / 1440;
minutes %= 1440;
date.hour = minutes / 60;
date.min = minutes % 60;
ConvertDaysToDate(&date.year, &date.month, &date.day, days);
isLeapYear = 0;
calendar->year = date.year;
calendar->mon = date.month - 1;
calendar->mday = date.day;
calendar->hour = date.hour;
calendar->min = date.min;
calendar->sec = 0;
calendar->msec = 0;
calendar->usec = 0;
calendar->yday = date.day + DAYS_OF_YEAR[date.month - 1] - 1;
if (((date.year % 4 == 0 && date.year % 100 != 0) || date.year % 400 == 0)) {
isLeapYear = 1;
}
if (isLeapYear && date.month > 2) {
calendar->yday++;
}
calendar->wday = (days + 1) % 7;
return NWC24_OK;
}
NWC24Err NWC24iDateToOSCalendarTime(OSCalendarTime* calendar, const NWC24Date* date) {
BOOL isLeapYear;
s32 days;
isLeapYear = 0;
calendar->year = date->year;
calendar->mon = date->month - 1;
calendar->mday = date->day;
calendar->hour = date->hour;
calendar->min = date->min;
calendar->sec = date->sec;
calendar->msec = 0;
calendar->usec = 0;
calendar->yday = date->day + DAYS_OF_YEAR[date->month - 1] - 1;
if (((date->year % 4 == 0 && date->year % 100 != 0) || date->year % 400 == 0)) {
isLeapYear = 1;
}
if (isLeapYear && date->month > 2) {
calendar->yday++;
}
days = ConvertDateToDays(date->year, date->month, date->day);
calendar->wday = (days + 1) % 7;
return NWC24_OK;
}
NWC24Err NWC24iIsValidDate(u16 year, u8 month, u8 day) {
return ConvertDateToDays(year, month, day) == -1 ? NWC24_ERR_INVALID_VALUE : NWC24_OK;
}
s32 ConvertDateToDays(u16 year, u8 month, u8 day) {
s32 daysOfYear;
s32 yearOffset;
s32 centuryLeapDays;
s32 commonLeapDays;
BOOL isLeapYear;
if (year < 1900 || month < 1 || month > 12) {
return -1;
}
if (month == 2) {
isLeapYear = 0;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
isLeapYear = 1;
}
if (isLeapYear) {
if (day < 1 || day > 29) {
return -1;
}
goto validDate;
}
}
if (day < 1 || DAYS_OF_MONTH[month - 1] < day) {
return -1;
}
validDate:
daysOfYear = day - 1 + DAYS_OF_YEAR[month - 1];
if (month >= 3) {
isLeapYear = 0;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
isLeapYear = 1;
}
if (isLeapYear) {
daysOfYear++;
}
}
yearOffset = year - 1900;
centuryLeapDays = (yearOffset + 299) / 400;
daysOfYear += yearOffset * 365;
daysOfYear += centuryLeapDays;
commonLeapDays = (yearOffset - 1) / 4 - (yearOffset - 1) / 100;
return daysOfYear + commonLeapDays;
}
void ConvertDaysToDate(u16* year, u8* month, u8* day, s32 days) {
*year = 1900;
*month = 1;
*day = 1;
if (days < 0) {
return;
}
for (;;) {
u16 currentYear = *year;
s32 previousDays = days;
BOOL leapYear = (currentYear % 4 == 0 && currentYear % 100 != 0) || currentYear % 400 == 0;
days -= 365 + (leapYear != FALSE);
if (days < 0) {
days = previousDays;
break;
}
*year = *year + 1;
}
for (;;) {
s32 previousDays = days;
if (*month == 2) {
BOOL leapYear = IsLeapYear(*year);
if (leapYear) {
days -= 29;
} else {
days -= DAYS_OF_MONTH[*month - 1];
}
} else {
days -= DAYS_OF_MONTH[*month - 1];
}
if (days < 0) {
*day += previousDays;
return;
}
*month = *month + 1;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,767 @@
#include <private/nwc24.h>
#include <revolution/nwc24.h>
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)
return NWC24_ERR_INVALID_VALUE;
if (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) {
char value[1];
value[0] = encoding;
if (encoding == 'B' || encoding == 'b' || encoding == 'Q' || encoding == 'q') {
u32 length = Mail_strlen(encoded);
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 inline char* FindMarker(char* input, u32 size, const char* marker) {
u32 markerLength = Mail_strlen(marker);
u32 offset;
for (offset = 0; offset <= size; offset++) {
char* current = input + offset;
if (Mail_strncmp(current, marker, markerLength) == 0)
return current;
}
return NULL;
}
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 consumedSize;
u32 decodedLength;
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)) {
*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;
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;
inputSize = encodedSize;
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) {
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;
}
} else {
result = NWC24_ERR_OVERFLOW;
}
return result;
}
static NWC24Err ExtractCharset(char* charset, u32 charsetCapacity, u32* charsetSize, char* encoded, u32 encodedSize) {
char* start;
char* end;
u32 charsetLength;
if (charset == NULL) {
return NWC24_ERR_INVALID_VALUE;
}
start = FindMarker(encoded, encodedSize, "=?");
if (start == NULL) {
return NWC24_ERR_NOT_SUPPORTED;
}
start += 2;
end = FindMarker(start, encodedSize - (u32)(start - encoded), "?");
if (end == NULL) {
return NWC24_ERR_NOT_SUPPORTED;
}
charsetLength = (u32)(end - start);
if (charsetLength >= charsetCapacity) {
return NWC24_ERR_OVERFLOW;
}
Mail_strncpy(charset, 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) {
char* start;
char* end;
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;
start = FindMarker(encoded, encodedSize, "?");
if (start == NULL) {
return NWC24_ERR_NOT_SUPPORTED;
}
start++;
end = FindMarker(start, encodedSize - (u32)(start - encoded), "?=");
if (end == NULL) {
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, 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 - encoded) + 2;
return result;
}

View File

@@ -34,8 +34,10 @@ NWC24Err NWC24iDateToMinutes(u32* minutes, const NWC24Date* date);
NWC24Err NWC24iMinutesToDate(NWC24Date* date, u32 minutes);
static inline NWC24Err WriteString(NWC24MsgObjPrivate* msg, char* buffer) {
s32 length = Mail_strlen(buffer);
NWC24Err err = NWC24FWrite(buffer, length, m_pFile);
NWC24Err err;
s32 length;
length = Mail_strlen(buffer);
err = NWC24FWrite(buffer, length, m_pFile);
if (err == NWC24_OK)
msg->length += length;
return err;
@@ -81,11 +83,12 @@ static inline NWC24Err WriteSMTPData(NWC24MsgObjPrivate* msg, const char* text)
}
static inline NWC24Err WriteCmdField(NWC24MsgObjPrivate* msg) {
char* buffer = NWC24WorkP->stringWork;
char* buffer;
s32 length;
NWC24Err err;
if (msg->ledPattern == 0)
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-Cmd: %08X\r\n", msg->ledPattern);
length = Mail_strlen(buffer);
@@ -96,11 +99,12 @@ static inline NWC24Err WriteCmdField(NWC24MsgObjPrivate* msg) {
}
static inline NWC24Err WriteTagField(NWC24MsgObjPrivate* msg) {
char* buffer = NWC24WorkP->stringWork;
char* buffer;
s32 length;
NWC24Err err;
if (msg->tag == 0)
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-Tag: %08X\r\n", msg->tag);
length = Mail_strlen(buffer);
@@ -111,11 +115,12 @@ static inline NWC24Err WriteTagField(NWC24MsgObjPrivate* msg) {
}
static inline NWC24Err WriteDWCIdField(NWC24MsgObjPrivate* msg) {
char* buffer = NWC24WorkP->stringWork;
char* buffer;
s32 length;
NWC24Err err;
if (!(msg->type & 0x2000))
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-DWCId: %08X\r\n", msg->dwcId);
length = Mail_strlen(buffer);
@@ -126,11 +131,12 @@ static inline NWC24Err WriteDWCIdField(NWC24MsgObjPrivate* msg) {
}
static inline NWC24Err WriteIconNewField(NWC24MsgObjPrivate* msg) {
char* buffer = NWC24WorkP->stringWork;
char* buffer;
s32 length;
NWC24Err err;
if (msg->iconNew == 0 || msg->iconNew == 0x80000000)
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-IconNew: %08X\r\n", msg->iconNew);
length = Mail_strlen(buffer);
@@ -145,8 +151,8 @@ static inline NWC24Err WriteMessageIdField(NWC24MsgObjPrivate* msg) {
const char* domain;
NWC24UserId myId;
char idText[32];
s32 length;
NWC24Err err;
s32 length;
domain = NWC24GetAccountDomain();
NWC24GetMyUserId(&myId);
Mail_memset(buffer, 0, 1024);
@@ -179,6 +185,65 @@ NWC24Err NWC24CommitMsg(NWC24MsgObj* object) {
return NWC24CommitMsgInternal(msg, loopback);
}
static inline NWC24Err WriteMBNoReplyField(NWC24MsgObjPrivate* msg) {
u32 flags = msg->msgBoardFlags.raw & 0x80000000;
char* buffer;
s32 length;
NWC24Err err;
if (!flags)
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_strcpy(buffer, "X-Wii-MB-NoReply: -\r\n");
length = 21;
err = NWC24FWrite(buffer, length, m_pFile);
if (err == NWC24_OK)
msg->length += length;
return err;
}
static inline NWC24Err WriteMBRegDateField(NWC24MsgObjPrivate* msg, u32 flags) {
NWC24Err err;
s32 length;
char* buffer;
if (!flags)
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-MB-RegDate: %04X\r\n", flags);
length = STD_strnlen(buffer, 1024);
err = NWC24FWrite(buffer, length, m_pFile);
if (err == NWC24_OK)
msg->length += length;
return err;
}
static inline NWC24Err WriteMBDelayField(NWC24MsgObjPrivate* msg, u32 flags) {
NWC24Err err;
s32 length;
char* buffer;
if (!flags)
return NWC24_OK;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-MB-Delay: %02X\r\n", flags >> 16);
length = STD_strnlen(buffer, 1024);
err = NWC24FWrite(buffer, length, m_pFile);
if (err == NWC24_OK)
msg->length += length;
return err;
}
static inline NWC24Err WriteExtraFields(NWC24MsgObjPrivate* msg) {
NWC24Err err;
if (msg->unk_0xD0.size == 0)
return NWC24_OK;
err = NWC24FWrite(msg->unk_0xD0.ptr, msg->unk_0xD0.size, m_pFile);
if (err == NWC24_OK)
msg->length += msg->unk_0xD0.size;
return err;
}
static NWC24Err NWC24CommitMsgInternal(NWC24MsgObjPrivate* msg, NWC24MBoxType type) {
NWC24File file;
NWC24Data attached[2];
@@ -188,7 +253,6 @@ static NWC24Err NWC24CommitMsgInternal(NWC24MsgObjPrivate* msg, NWC24MBoxType ty
s32 initIndex;
u32 index;
char* buffer;
s32 length;
NWC24Err result, err;
NWC24Data_Init(&subject);
NWC24Data_Init(&text);
@@ -241,59 +305,12 @@ static NWC24Err NWC24CommitMsgInternal(NWC24MsgObjPrivate* msg, NWC24MBoxType ty
CHECK_WRITE(WriteXWiiFaceField(msg));
CHECK_WRITE(WriteIconNewField(msg));
if (msg->msgBoardFlags.raw != 0) {
if (msg->msgBoardFlags.raw & 0x80000000) {
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_strcpy(buffer, "X-Wii-MB-NoReply: -\r\n");
err = NWC24FWrite(buffer, 21, m_pFile);
if (err == NWC24_OK)
msg->length += 21;
if (err != NWC24_OK) {
NWC24FClose(&file);
result = err;
goto finish;
}
}
if (msg->msgBoardFlags.raw & 0xFFFF) {
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-MB-RegDate: %04X\r\n", msg->msgBoardFlags.raw & 0xFFFF);
length = STD_strnlen(buffer, 1024);
err = NWC24FWrite(buffer, length, m_pFile);
if (err == NWC24_OK)
msg->length += length;
if (err != NWC24_OK) {
NWC24FClose(&file);
result = err;
goto finish;
}
}
if (msg->msgBoardFlags.raw & 0xFF0000) {
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "X-Wii-MB-Delay: %02X\r\n", (msg->msgBoardFlags.raw >> 16) & 0xFF);
length = STD_strnlen(buffer, 1024);
err = NWC24FWrite(buffer, length, m_pFile);
if (err == NWC24_OK)
msg->length += length;
if (err != NWC24_OK) {
NWC24FClose(&file);
result = err;
goto finish;
}
}
}
}
if (msg->unk_0xD0.size != 0) {
err = NWC24FWrite(msg->unk_0xD0.ptr, msg->unk_0xD0.size, m_pFile);
if (err == NWC24_OK)
msg->length += msg->unk_0xD0.size;
if (err != NWC24_OK) {
NWC24FClose(&file);
result = err;
goto finish;
CHECK_WRITE(WriteMBNoReplyField(msg));
CHECK_WRITE(WriteMBRegDateField(msg, msg->msgBoardFlags.raw & 0xFFFF));
CHECK_WRITE(WriteMBDelayField(msg, msg->msgBoardFlags.raw & 0xFF0000));
}
}
CHECK_WRITE(WriteExtraFields(msg));
Mail_memset(MultiPartDivider, 0, 40);
Mail_sprintf(MultiPartDivider, "Boundary-NWC24-%08X%05X", msg->unk_0x28, msg->msgId);
buffer = NWC24WorkP->stringWork;
@@ -335,14 +352,15 @@ static NWC24Err NWC24CommitMsgInternal(NWC24MsgObjPrivate* msg, NWC24MBoxType ty
CHECK_WRITE(WriteMIMEAttachHeader(msg, index));
attached[index].ptr = (const void*)msg->length;
err = WriteBase64Data(msg->attached[index].ptr, msg->attached[index].size, &encodedLength);
msg->length += encodedLength;
if (err == NWC24_OK)
msg->length += encodedLength;
if (err != NWC24_OK) {
NWC24FClose(&file);
result = err;
goto finish;
}
attached[index].size = msg->length - (u32)attached[index].ptr;
if (index == msg->numAttached - 1) {
if ((s32)index == msg->numAttached - 1) {
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
Mail_sprintf(buffer, "\r\n--%s", MultiPartDivider);
@@ -576,14 +594,13 @@ static NWC24Err WriteFromField(NWC24MsgObjPrivate* msg) {
}
static NWC24Err WriteToField(NWC24MsgObjPrivate* msg) {
char* buffer = NWC24WorkP->stringWork;
char* cursor;
char* cursor = NWC24WorkP->stringWork;
s32 index, total, remaining;
u32 length;
NWC24Err err = NWC24_OK;
Mail_memset(buffer, 0, 1024);
Mail_strncat(buffer, "To: ", 1022);
cursor = buffer + 4;
Mail_memset(cursor, 0, 1024);
Mail_strncat(cursor, "To: ", 1022);
cursor += 4;
index = 0;
total = 4;
msg->unk_0x38.ptr = (const void*)(msg->length + 4);
@@ -755,7 +772,8 @@ static NWC24Err WriteMIMEAttachHeader(NWC24MsgObjPrivate* msg, u32 index) {
dispositionLength = Mail_strlen(ContentDispA);
typeLength += encodingLength;
mimeLength = Mail_strlen(mime);
if (mimeLength + (dispositionLength + typeLength) + 4 >= 1024)
mimeLength = (dispositionLength + typeLength) + mimeLength + 4;
if (mimeLength >= 1024)
return NWC24_ERR_NOMEM;
first = Mail_sprintf(buffer, (char*)ContentTypeA, mime, (char)('a' + index), msg->msgId, suffix);
if (first <= 0)
@@ -879,8 +897,8 @@ static NWC24Err WriteBase64Data(const u8* data, s32 size, u32* totalLength) {
static NWC24Err WriteQPData(const u8* data, s32 size, u32* totalLength) {
char* buffer = NWC24WorkP->stringWork;
const u8* cursor = data;
s32 total = 0;
s32 remaining = size;
s32 total = 0;
u32 consumed, length;
NWC24Err err = NWC24_OK;
for (; remaining > 0; remaining -= consumed) {

View File

@@ -0,0 +1,599 @@
#define NWC24_MSG_READ
#include <private/nwc24.h>
NWC24Err NWC24iMBoxOpenStoredMsg(NWC24MBoxType type, u32 id, NWC24File* file);
NWC24Err NWC24iMBoxCloseMsg(NWC24File* file);
BOOL Mail_isdigit(int character);
static NWC24Err ReadMsgTextInternal(const NWC24MsgObj* msg, char* text, u32 capacity, char* charset, u32 charsetCapacity, NWC24Encoding* encoding);
NWC24Err ReadBase64Data(NWC24File* file, const NWC24Data* data, u8* output, u32 capacity, u32* outputSize);
NWC24Err ReadQPText(const NWC24MsgObjPrivate* msg, NWC24File* file, char* output, u32 capacity);
static inline NWC24Err SelectMBox(const NWC24MsgObjPrivate* msg, NWC24MBoxType* type) {
if (msg->type & 0x10)
*type = NWC24_MBOX_TYPE_SEND;
else if (msg->type & 0x20)
*type = NWC24_MBOX_TYPE_RECV;
else
return NWC24_ERR_INVALID_VALUE;
return NWC24_OK;
}
NWC24Err NWC24ReadMsgField(const NWC24MsgObj* msg, char* fieldName, u8* output, u32 capacity) {
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
NWC24File file;
NWC24FileStream stream;
char* field;
u32 offset;
u32 length;
NWC24MBoxType type;
NWC24Err result;
NWC24Err closeResult;
if (!NWC24IsMsgLibOpened() && !NWC24IsMsgLibOpenedByTool())
return NWC24_ERR_LIB_NOT_OPENED;
if (!(privateMsg->type & 0x200))
return NWC24_ERR_PROTECTED;
result = SelectMBox(privateMsg, &type);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
result = NWC24iMBoxOpenStoredMsg(type, privateMsg->msgId, &file);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
result = NWC24FStreamInit(&stream, &file, 0, privateMsg->length, NWC24WorkP->mainWork, 1024);
if (result == NWC24_OK) {
result = NWC24iSearchHeaderF(&stream, fieldName, privateMsg->headerSize, &offset, &length);
if (result == NWC24_OK) {
if (length > capacity)
result = NWC24_ERR_OVERFLOW;
else {
result = NWC24FStreamSeek(&stream, offset);
if (result == NWC24_OK) {
result = NWC24FStreamGetPtr(&stream, &field, length);
if (result == NWC24_OK) {
Mail_strncpy((char*)output, field, length);
output[length - 2] = 0;
}
}
}
}
}
closeResult = NWC24iMBoxCloseMsg(&file);
if (result == NWC24_OK)
result = closeResult;
return result;
}
NWC24Err NWC24ReadMsgFaceData(const NWC24MsgObj* msg, u8* faceData) {
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
char* buffer;
u32 length;
NWC24Err result;
if ((privateMsg->type & 2) && !(privateMsg->type & 0x1000))
return NWC24_ERR_NOT_FOUND;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
result = NWC24ReadMsgField(msg, "x-wiiface", (u8*)buffer, 1024);
switch (result) {
default:
return result;
case NWC24_OK:
result = NWC24Base64Decode((u8*)buffer, STD_strnlen(buffer, 1024), faceData, 74, &length);
switch (result) {
default:
return result;
case NWC24_OK:
if (length != 74)
return NWC24_ERR_FORMAT;
return NWC24_OK;
}
}
return result;
}
NWC24Err NWC24ReadMsgAltName(const NWC24MsgObj* msg, u16* name, u32 capacity) {
char* buffer = NWC24WorkP->stringWork;
u32 length;
NWC24Err result;
NWC24Err decodeResult;
Mail_memset(buffer, 0, 1024);
result = NWC24ReadMsgField(msg, "x-wii-altname:", (u8*)buffer, 1024);
switch (result) {
default:
return result;
case NWC24_OK:
decodeResult = NWC24Base64Decode((u8*)buffer, STD_strnlen(buffer, 1024), (u8*)name, capacity * 2, &length);
result = NWC24_OK;
if (decodeResult != NWC24_OK)
result = decodeResult;
}
return result;
}
NWC24Err NWC24ReadMsgMBNoReply(const NWC24MsgObj* msg, BOOL* noReply) {
char* buffer;
NWC24Err result;
*noReply = FALSE;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
result = NWC24ReadMsgField(msg, "x-wii-mb-noreply:", (u8*)buffer, 1024);
if (result == NWC24_OK)
*noReply = TRUE;
else if (result == NWC24_ERR_NOT_FOUND)
result = NWC24_OK;
return result;
}
NWC24Err NWC24ReadMsgMBRegDate(const NWC24MsgObj* msg, u16* year, u8* month, u8* day) {
NWC24Err result;
u32 offset = 0;
u32 digits = 0;
u32 value = 0;
s32 digit;
char* buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
result = NWC24ReadMsgField(msg, "x-wii-mb-regdate:", (u8*)buffer, 1023);
switch (result) {
default:
return result;
case NWC24_OK:
break;
}
while (*buffer == '\t' || *buffer == ' ') {
buffer++;
offset++;
}
for (; offset < 1024; offset++, digits++) {
digit = Util_xtoi(*buffer);
if (digit < 0)
break;
value = (value << 4) | digit;
buffer++;
}
if (digits != 4)
result = NWC24_ERR_FORMAT;
*year = ((value >> 9) & 127) + 2000;
*month = (value >> 5) & 15;
*day = value & 31;
return result;
}
NWC24Err NWC24ReadMsgMBDelay(const NWC24MsgObj* msg, u8* delay) {
NWC24Err result;
u32 offset = 0;
u32 digits = 0;
u32 value = 0;
s32 digit;
char* buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
result = NWC24ReadMsgField(msg, "x-wii-mb-delay:", (u8*)buffer, 1023);
switch (result) {
default:
return result;
case NWC24_OK:
break;
}
while (*buffer == '\t' || *buffer == ' ') {
buffer++;
offset++;
}
for (; offset < 1024; offset++, digits++) {
digit = Util_xtoi(*buffer);
if (digit < 0)
break;
value = (value << 4) | digit;
buffer++;
}
if (digits != 2)
result = NWC24_ERR_FORMAT;
*delay = value;
return result;
}
NWC24Err NWC24ReadMsgMBUpdateSW(const NWC24MsgObj* msg, u32* update) {
NWC24Err result;
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
u32 value = 0;
char* buffer;
if (!(privateMsg->type & 0x1000)) {
*update = 0;
return NWC24_ERR_NOT_FOUND;
}
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
result = NWC24ReadMsgField(msg, "x-wii-mb-updatesw:", (u8*)buffer, 1023);
switch (result) {
default:
return result;
case NWC24_OK:
while (*buffer == '\t' || *buffer == ' ')
buffer++;
if (Mail_isdigit(*buffer))
value = *buffer - '0';
*update = value;
}
return result;
}
NWC24Err NWC24ReadMsgMBOptOutFlag(const NWC24MsgObj* msg, BOOL* optOut, u32* appId) {
NWC24Err result;
u32 offset = 0;
u32 digits = 0;
u32 value = 0;
s32 digit;
char* buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
*optOut = FALSE;
*appId = 0;
result = NWC24ReadMsgField(msg, "x-wii-mb-optout:", (u8*)buffer, 1023);
if (result == NWC24_ERR_NOT_FOUND)
return NWC24_OK;
switch (result) {
default:
return result;
case NWC24_OK:
while (*buffer == '\t' || *buffer == ' ') {
buffer++;
offset++;
}
if (*buffer == '1')
*optOut = TRUE;
{
char separator = buffer[1];
buffer += 2;
if (separator != '-')
return NWC24_OK;
{
offset += 2;
for (; offset < 1024; offset++, digits++) {
digit = Util_xtoi(*buffer);
if (digit < 0)
break;
value = (value << 4) | digit;
buffer++;
}
if (digits != 8)
result = NWC24_ERR_FORMAT;
*appId = value;
}
}
}
return result;
}
NWC24Err NWC24ReadMsgFromAddr(const NWC24MsgObj* msg, char* address, u32 capacity) {
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
NWC24MBoxType type;
NWC24File file;
NWC24FileStream stream;
char* buffer;
NWC24Err result, closeResult;
if (!NWC24IsMsgLibOpened() && !NWC24IsMsgLibOpenedByTool())
return NWC24_ERR_LIB_NOT_OPENED;
if (!(privateMsg->type & 0x200))
return NWC24_ERR_PROTECTED;
buffer = NWC24WorkP->stringWork;
Mail_memset(buffer, 0, 1024);
if (!(privateMsg->type & 2))
return NWC24_ERR_NOT_SUPPORTED;
result = SelectMBox(privateMsg, &type);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
if (privateMsg->unk_0x30.size == 0)
return NWC24_ERR_NULL;
result = NWC24iMBoxOpenStoredMsg(type, privateMsg->msgId, &file);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
result = NWC24FStreamInit(&stream, &file, 0, privateMsg->length, buffer, 1024);
if (result == NWC24_OK) {
result = NWC24FStreamSeek(&stream, (u32)privateMsg->unk_0x30.ptr);
if (result == NWC24_OK)
result = NWC24iExtractAddrSpec(&stream, privateMsg->unk_0x30.size, 0, address, capacity);
}
closeResult = NWC24iMBoxCloseMsg(&file);
if (result != NWC24_OK)
closeResult = result;
return closeResult;
return result;
}
NWC24Err NWC24ReadMsgSubject(const NWC24MsgObj* msg, char* subject, u32 capacity) {
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
NWC24MBoxType type;
NWC24File file;
u32 length;
NWC24Err result, closeResult;
if (!NWC24IsMsgLibOpened() && !NWC24IsMsgLibOpenedByTool())
return NWC24_ERR_LIB_NOT_OPENED;
if (!(privateMsg->type & 0x200))
return NWC24_ERR_PROTECTED;
result = SelectMBox(privateMsg, &type);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
length = privateMsg->subject.size;
if (length == 0)
return NWC24_ERR_NULL;
result = NWC24iMBoxOpenStoredMsg(type, privateMsg->msgId, &file);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
if (length > capacity - 1)
length = capacity - 1;
NWC24FSeek(&file, (u32)privateMsg->subject.ptr, NWC24_SEEK_BEG);
result = NWC24FRead(subject, length, &file);
if (result == NWC24_OK) {
subject[length] = 0;
if (privateMsg->subject.size > capacity - 1)
result = NWC24_ERR_OVERFLOW;
}
closeResult = NWC24iMBoxCloseMsg(&file);
if (result == NWC24_OK)
result = closeResult;
return result;
}
NWC24Err NWC24ReadMsgText(const NWC24MsgObj* msg, char* text, u32 capacity, NWC24Charset* charset, NWC24Encoding* encoding) {
char* name = NWC24WorkP->stringWork + 32;
NWC24Err result = ReadMsgTextInternal(msg, text, capacity, name, 64, encoding);
if (result == NWC24_OK)
result = NWC24ParseCharsetStr(charset, name);
return result;
}
NWC24Err NWC24ReadMsgTextEx(const NWC24MsgObj* msg, char* text, u32 capacity, char* charset, u32 charsetCapacity) {
u32 i;
NWC24Encoding encoding;
NWC24Err result = ReadMsgTextInternal(msg, text, capacity, charset, charsetCapacity, &encoding);
if (result == NWC24_OK) {
for (i = 0; i < charsetCapacity; i++) {
switch (*charset) {
case ' ':
case '\t':
case '\n':
case '\r':
case ';':
case '"':
*charset = 0;
break;
}
if (*charset == 0)
break;
charset++;
}
}
return result;
}
static NWC24Err ReadMsgTextInternal(const NWC24MsgObj* msg, char* text, u32 capacity, char* charset, u32 charsetCapacity, NWC24Encoding* encoding) {
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
NWC24MBoxType type;
NWC24File file;
NWC24Err result, closeResult;
NWC24Err overflow = NWC24_OK;
u32 length;
u32 decodedSize;
char* buffer;
if (!NWC24IsMsgLibOpened() && !NWC24IsMsgLibOpenedByTool())
return NWC24_ERR_LIB_NOT_OPENED;
if (!(privateMsg->type & 0x200))
return NWC24_ERR_PROTECTED;
buffer = NWC24WorkP->stringWork;
*encoding = 0;
result = SelectMBox(privateMsg, &type);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
length = privateMsg->textSize;
if (length == 0)
length = privateMsg->text.size;
if (length == 0)
return NWC24_ERR_NULL;
if (length > capacity - 1) {
overflow = NWC24_ERR_OVERFLOW;
length = capacity - 1;
}
result = NWC24iMBoxOpenStoredMsg(type, privateMsg->msgId, &file);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
Mail_memset(charset, 0, charsetCapacity);
if (privateMsg->unk_0x50.size >= charsetCapacity)
result = NWC24_ERR_FORMAT;
else {
if (privateMsg->unk_0x50.size != 0) {
NWC24FSeek(&file, (u32)privateMsg->unk_0x50.ptr, NWC24_SEEK_BEG);
result = NWC24FRead(charset, privateMsg->unk_0x50.size, &file);
if (result != NWC24_OK)
goto close;
}
if (privateMsg->unk_0x58.size != 0 && privateMsg->unk_0x58.size < 32) {
Mail_memset(buffer, 0, 32);
NWC24FSeek(&file, (u32)privateMsg->unk_0x58.ptr, NWC24_SEEK_BEG);
result = NWC24FRead(buffer, privateMsg->unk_0x58.size, &file);
if (result != NWC24_OK)
goto close;
result = NWC24ParseEncodingStr(encoding, buffer);
if (result != NWC24_OK)
goto close;
}
NWC24FSeek(&file, (u32)privateMsg->text.ptr, NWC24_SEEK_BEG);
switch (*encoding) {
case 0:
case 1:
result = NWC24FRead(text, length, &file);
text[length] = 0;
break;
case 2:
decodedSize = 0;
result = ReadBase64Data(&file, &privateMsg->text, (u8*)text, length, &decodedSize);
if (result == NWC24_OK && decodedSize != privateMsg->textSize)
result = NWC24_ERR_FORMAT;
text[length] = 0;
break;
case 3:
result = ReadQPText(privateMsg, &file, text, length);
break;
default:
result = NWC24_ERR_NOT_SUPPORTED;
*text = 0;
break;
}
}
close:
closeResult = NWC24iMBoxCloseMsg(&file);
if (result == NWC24_OK)
result = closeResult;
if (result == NWC24_OK)
result = overflow;
return result;
}
NWC24Err NWC24ReadMsgAttached(const NWC24MsgObj* msg, u32 index, u8* output, u32 capacity) {
const NWC24MsgObjPrivate* privateMsg = (const NWC24MsgObjPrivate*)msg;
NWC24File file;
NWC24MBoxType type;
u32 decodedSize;
NWC24Err result, closeResult;
if (!NWC24IsMsgLibOpened() && !NWC24IsMsgLibOpenedByTool())
return NWC24_ERR_LIB_NOT_OPENED;
if (!(privateMsg->type & 0x200))
return NWC24_ERR_PROTECTED;
if (index >= privateMsg->numAttached)
return NWC24_ERR_NOT_FOUND;
result = SelectMBox(privateMsg, &type);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
if (privateMsg->attached[index].size == 0 || privateMsg->attachedSize[index] == 0)
return NWC24_ERR_NULL;
result = NWC24iMBoxOpenStoredMsg(type, privateMsg->msgId, &file);
switch (result) {
case NWC24_OK:
break;
default:
return result;
}
decodedSize = 0;
result = ReadBase64Data(&file, &privateMsg->attached[index], output, capacity, &decodedSize);
if (result == NWC24_OK && decodedSize != privateMsg->attachedSize[index])
result = NWC24_ERR_FORMAT;
closeResult = NWC24iMBoxCloseMsg(&file);
if (result == NWC24_OK)
result = closeResult;
return result;
}
NWC24Err ReadBase64Data(NWC24File* file, const NWC24Data* data, u8* output, u32 capacity, u32* outputSize) {
int remaining = data->size;
int offset = (u32)data->ptr;
char* buffer = NWC24WorkP->mainWork;
u8* outPtr = output;
int total = 0;
int readSize;
int end;
char* cursor;
int i;
u32 decodedSize;
NWC24Err result = NWC24_OK;
BOOL finished = FALSE;
while (remaining > 0 && !finished) {
readSize = remaining > 1024 ? 1024 : remaining;
NWC24FSeek(file, offset, NWC24_SEEK_BEG);
result = NWC24FRead(buffer, readSize, file);
if (result != NWC24_OK)
break;
end = 0;
cursor = buffer;
for (i = 0; i < readSize; cursor++, i++) {
if (*cursor == '\r')
end = i;
if (*cursor == '=') {
end = i + 1;
finished = TRUE;
result = NWC24_OK;
break;
}
}
if (end == 0)
break;
result = NWC24Base64Decode((u8*)buffer, end, outPtr, capacity - total, &decodedSize);
if (result != NWC24_OK)
break;
offset += end;
remaining -= end;
total += decodedSize;
outPtr += decodedSize;
}
if (result == NWC24_OK)
*outputSize = total;
return result;
}
NWC24Err ReadQPText(const NWC24MsgObjPrivate* msg, NWC24File* file, char* output, u32 capacity) {
int remaining = msg->text.size;
int offset = (u32)msg->text.ptr;
char* buffer = NWC24WorkP->mainWork;
char* cursor = output;
int readSize;
u32 total = 0;
u32 consumedSize;
u32 decodedSize;
NWC24Err result = NWC24_OK;
while (remaining > 0) {
readSize = remaining > 1024 ? 1024 : remaining;
NWC24FSeek(file, offset, NWC24_SEEK_BEG);
result = NWC24FRead(buffer, readSize, file);
if (result != NWC24_OK)
break;
consumedSize = readSize;
if (readSize == 1024) {
if (buffer[readSize - 1] == '=')
consumedSize = readSize - 1;
else if (buffer[readSize - 2] == '=')
consumedSize = readSize - 2;
}
result = NWC24DecodeQuotedPrintable(cursor, capacity - total, &decodedSize, (u8*)buffer, consumedSize, &consumedSize);
if (result != NWC24_OK && result != NWC24_ERR_OVERFLOW)
break;
total += decodedSize;
cursor += decodedSize;
if (result == NWC24_ERR_OVERFLOW)
break;
offset += consumedSize;
remaining -= consumedSize;
}
*cursor = 0;
if (result == NWC24_OK && total > msg->textSize)
result = NWC24_ERR_FORMAT;
return result;
}

View File

@@ -0,0 +1,877 @@
#define NWC24_MSG_SUBJECT
#include <private/enc.h>
#include <private/nwc24.h>
#include <revolution/enc.h>
#include <revolution/nwc24.h>
#include <string.h>
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);
switch (result) {
case NWC24_OK:
break;
default:
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);
switch (result) {
case NWC24_OK:
break;
default:
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:
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) {
int endIndex;
u32 subjectBytes;
u32 textBytes;
int startIndex;
int lastIndex;
int index;
const char** names;
int numNames;
int result;
index = 0;
startIndex = 0;
lastIndex = -1;
switch (region) {
case 0:
names = JapaneseCharsets;
numNames = 3;
break;
case 1:
case 2:
names = WesternCharsets;
numNames = 8;
break;
case 3:
names = KoreanCharsets;
numNames = 3;
break;
case 4:
names = ChineseCharsets;
numNames = 2;
break;
default:
names = WesternCharsets;
numNames = 8;
break;
}
subjectBytes = subjectSize << 1;
textBytes = textSize << 1;
endIndex = numNames - 1;
while (index < endIndex) {
result = ENCCheckEncoding(&index, names + startIndex, endIndex - startIndex, subject, subjectBytes);
if (result != ENC_OK) {
return NWC24_ERR_NOT_SUPPORTED;
}
if (index == ENC_CHECK_ENCODING_NOT_FOUND) {
index = numNames - 1;
break;
}
startIndex += index;
if ((text == NULL) || (lastIndex == startIndex)) {
index = startIndex;
break;
}
result = ENCCheckEncoding(&index, names + startIndex, endIndex - startIndex, text, textBytes);
if (result != ENC_OK) {
return NWC24_ERR_NOT_SUPPORTED;
}
if (index == ENC_CHECK_ENCODING_NOT_FOUND) {
index = numNames - 1;
break;
}
lastIndex = startIndex + index;
if (lastIndex == startIndex) {
index = lastIndex;
break;
}
startIndex = lastIndex;
}
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;
u32 sourceOffset;
u8* second;
u32 subjectLength;
u32 lineLength;
s32 copied;
u32 i;
NWC24Err result;
secondSize = workSize - (workSize >> 1);
second = work + (workSize >> 1);
subjectLength = subjectSize;
lineLength = 0;
workHalf = workSize >> 1;
result = NWC24iConvertFromInternalEncoding(work, &workHalf, subject, &subjectLength, charsetName, 0x40, region, alternative);
switch (result) {
default:
goto done;
case 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 {
workHalf = secondSize;
sourceOffset = lineLength;
if (workHalf <= sourceOffset) {
result = NWC24_ERR_OVERFLOW;
goto done;
}
copied = NWC24iStrLCpy((char*)second, (char*)work, lineLength + 1);
for (; sourceOffset < subjectLength; sourceOffset += lineLength) {
if (workHalf - copied < 3) {
result = NWC24_ERR_OVERFLOW;
goto done;
}
second[copied++] = '\r';
second[copied++] = '\n';
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);
}
}
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 sourceOffset;
u32 secondSize;
u8* second;
u32 subjectLength;
u32 lineLength;
u32 outputLength;
u32 total;
u32 combinedLength;
u32 i;
u32 charsetLength;
NWC24Err result;
secondSize = workSize - (workSize >> 1);
second = work + (workSize >> 1);
subjectLength = subjectSize;
lineLength = 0;
workHalf = workSize >> 1;
result = NWC24iConvertFromInternalEncoding(work, &workHalf, subject, &subjectLength, charsetName, 0x40, region, alternative);
switch (result) {
default:
goto done;
case 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);
switch (result) {
default:
goto done;
case NWC24_OK:
sourceOffset = lineLength;
if (lineLength == subjectLength) {
result = NWC24SetMsgSubject(msg, (char*)second, outputLength - 1);
} else {
charsetLength = (0x40 - strlen(charsetName)) / 3;
total = outputLength - 1;
workHalf = secondSize;
for (; sourceOffset < subjectLength;) {
if (workHalf - total < 3) {
result = NWC24_ERR_OVERFLOW;
goto done;
}
second[total++] = '\r';
second[total++] = '\n';
second[total++] = ' ';
NWC24iDetectBreakPoint(&lineLength, charset, work + sourceOffset, subjectLength - sourceOffset, charsetLength);
result = NWC24EncodeWord(second + total, workHalf - total, &outputLength, charsetName, 0x40, 'Q', work + sourceOffset,
lineLength);
switch (result) {
case NWC24_OK:
break;
default:
goto done;
}
combinedLength = total + outputLength;
sourceOffset += lineLength;
total = combinedLength - 1;
}
result = NWC24SetMsgSubject(msg, (char*)second, total);
}
}
}
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;
}

View File

@@ -0,0 +1,112 @@
#include <private/nwc24.h>
#include <private/os/OSStateTM.h>
#include <revolution/os.h>
#include <revolution/sc.h>
#include <stdlib.h>
static s32 nwc24ShtFd = -1;
static s32 nwc24ShtRetryRest = 0;
static OSShutdownFunctionInfo ShutdownFuncInfo;
BOOL NWC24Shutdown(BOOL final, u32 event);
NWC24Err NWC24iMBoxSetLastUIDL(NWC24MBoxType type, const char* uidl);
NWC24Err NWC24EnableLedNotification(BOOL enable) {
u8 led = 0;
SCIdleModeInfo idleMode;
u32 status;
if (enable) {
do {
status = SCCheckStatus();
if (status == 2)
return NWC24_ERR_FATAL;
} while (status == 1);
SCGetIdleMode(&idleMode);
led = idleMode.led;
}
__OSSetIdleLEDMode(led);
return NWC24_OK;
}
NWC24Err NWC24iPrepareShutdown(void) {
NWC24Err result = NWC24_OK;
SCIdleModeInfo idleMode;
u32 status;
NWC24iRegister();
ShutdownFuncInfo.func = NWC24Shutdown;
ShutdownFuncInfo.priority = 110;
OSRegisterShutdownFunction(&ShutdownFuncInfo);
if (nwc24ShtFd < 0)
result = NWC24OpenResourceManager("/dev/net/kd/request", &nwc24ShtFd, 1);
nwc24ShtRetryRest = 5;
do {
status = SCCheckStatus();
if (status == 2)
goto ready;
} while (status == 1);
SCGetIdleMode(&idleMode);
__OSSetIdleLEDMode(idleMode.led);
ready:
if (OSGetAppType() == 0x40)
NWC24iSetScriptMode(1);
return result;
}
static inline NWC24Err NWC24iRequestShutdown(u32 event, NWC24Err* result) {
static u32 shtBuffer[8] ALIGN32;
static u32 shtResult[8] ALIGN32;
shtBuffer[0] = event;
return NWC24IoctlResourceManagerAsync(nwc24ShtFd, NWC24_IOCTL_SHUTDOWN, shtBuffer, sizeof(shtBuffer), shtResult, sizeof(shtResult), (s32*)result);
}
BOOL NWC24Shutdown(BOOL final, u32 event) {
static BOOL shuttingdown = FALSE;
static NWC24Err result = NWC24_OK;
if (final)
return TRUE;
if (shuttingdown) {
if (NWC24IsAsyncRequestPending())
return FALSE;
if (result >= 0)
return TRUE;
if (nwc24ShtRetryRest > 0) {
shuttingdown = FALSE;
nwc24ShtRetryRest--;
} else
return TRUE;
} else if (NWC24iRequestShutdown(event, &result) >= 0)
shuttingdown = TRUE;
return FALSE;
}
NWC24Err NWC24DoDailyTasks(void* work) {
NWC24Err result = NWC24_OK;
SCIdleModeInfo idleMode;
u32 status;
u32 restrictions;
u32 tick = OSGetTick();
u32 randomValue = rand();
if ((randomValue + tick) % 10 != 0)
return NWC24_OK;
if (NWC24IsMsgLibOpened())
return NWC24_ERR_LIB_OPENED;
do {
status = SCCheckStatus();
if (status == 2)
return NWC24_ERR_FATAL;
OSSleepTicks(OSMillisecondsToTicks((OSTime)100));
} while (status != 0);
if (!SCGetIdleMode(&idleMode))
return NWC24_ERR_NOT_FOUND;
restrictions = SCGetNetContentRestrictions() & 2;
if (idleMode.standby == 0) {
if (restrictions == 0) {
result = NWC24OpenLib(work);
if (result >= 0) {
result = NWC24iMBoxSetLastUIDL(NWC24_MBOX_TYPE_RECV, "");
NWC24CloseLib();
}
} else
result = NWC24AdjustUniversalTime();
}
return result;
}

View File

@@ -0,0 +1,310 @@
#define MYTILETTERFORM_IMPLEMENTATION
#include "keyboard/MyTiLetterForm.h"
#include "keyboard/tiUtil.h"
#include <nw4r/lyt/textbox.h>
#include <new>
namespace textinput {
namespace inputform {
class EventHandler : public nw4rmanager::TiEventHandler {
public:
EventHandler(textinput::InputForm* form) : mpInputForm(form) {}
virtual ~EventHandler() {}
virtual void onTiEvent(gui::PaneComponent*, u32, Input*);
protected:
textinput::InputForm* mpInputForm;
};
}
namespace extend {
namespace memo {
class EventHandler : public inputform::EventHandler {
public:
EventHandler(InputForm* form) : inputform::EventHandler(form), mpMemoForm(form) {}
virtual ~EventHandler() {}
virtual void onTiEvent(gui::PaneComponent*, u32, Input*);
protected:
InputForm* mpMemoForm;
};
}
namespace letter {
class EventHandler : public memo::EventHandler {
public:
EventHandler(InputForm* form) : memo::EventHandler(form) {}
virtual ~EventHandler();
virtual void onTiEvent(gui::PaneComponent*, u32, Input*);
};
class AnmPane : public nw4rmanager::AnmPane {
protected:
enum KeyType { KT_Whole, KT_Pic };
u32 meState;
KeyType meKeyType;
public:
AnmPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer)
: nw4rmanager::AnmPane(pane, observer), meState(0), meKeyType(KT_Whole) {}
virtual ~AnmPane();
virtual void init();
virtual void changeAnimation(u32 id);
virtual KeyType getKeyType() const;
virtual u32 getState();
};
class WholePane : public AnmPane {
public:
WholePane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer)
: AnmPane(pane, observer) { meKeyType = KT_Whole; }
virtual ~WholePane();
virtual void onAnmEvent(AnmPaneEvent paneEvent);
};
class PicPane : public AnmPane {
public:
PicPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer)
: AnmPane(pane, observer) { meKeyType = KT_Pic; }
virtual ~PicPane();
virtual void onAnmEvent(AnmPaneEvent paneEvent);
};
static const char* paneNames[] = {
"N_Header", "N_Body", "B_Body", "N_Footer", "Nigaoe",
"T_Nigaoe", "B_Nigaoe", "T_Letter", "T_TouchLetter"
};
struct AnimationFile { u32 id; char fileName[64]; };
static const AnimationFile animationFiles[] = {
{0, "my_LetterL_PicFocusIn.brlan"},
{1, "my_LetterL_SelectPic.brlan"},
{2, "my_LetterL_ExitPic.brlan"},
{3, "my_LetterL_PicFocusOut.brlan"},
{4, "my_LetterL_ReturnIn.brlan"},
{5, "my_LetterL_SendOut.brlan"},
{6, "my_LetterL_MailIn.brlan"},
{7, "my_LetterL_MailOut.brlan"},
};
struct PaneToAnimationGroup {
s32 type;
const char* paneName;
u32 count;
const AnimationFile* animations[12];
};
static const PaneToAnimationGroup animationGroups[] = {
{0, "N_MemoRoot", 4, {&animationFiles[4], &animationFiles[5], &animationFiles[6], &animationFiles[7]}},
{0, "SendPic", 4, {&animationFiles[4], &animationFiles[5], &animationFiles[6], &animationFiles[7]}},
{1, "N_Pic", 5, {&animationFiles[0], &animationFiles[1], &animationFiles[2], &animationFiles[3], &animationFiles[4]}},
{0, "N_SendMes", 1, {&animationFiles[5]}}
};
void InputForm::create(MEMAllocator* allocator, textinput::inputform::EditBuffer* editBuffer) {
memo::InputForm::create(allocator, editBuffer);
MEMFreeToAllocator(allocator, mpInputEventHandler);
mpInputEventHandler = new (MEMAllocFromAllocator(allocator, sizeof(EventHandler))) EventHandler(this);
mpInputEventHandler->setEventObserver(mpEventObserver);
mpPaneManager->changeEventHandler(mpInputEventHandler);
for (u16 i = 0; i < 4; i++) {
const PaneToAnimationGroup* group = &animationGroups[i];
AnmPane* pane = NULL;
switch (group->type) {
case 1:
pane = new (MEMAllocFromAllocator(allocator, sizeof(PicPane))) PicPane(
getPane(group->paneName), NULL);
break;
case 0:
pane = new (MEMAllocFromAllocator(allocator, sizeof(WholePane))) WholePane(
getPane(group->paneName), NULL);
break;
}
nw4r::ut::List_Append(&mAnmPanes, pane);
for (u16 j = 0; j < group->count; j++) {
void* resource = mpMultiArcResourceAccessor->GetResource(0, group->animations[j]->fileName);
AnimTransformPane* transform = static_cast<AnimTransformPane*>(
getLayout()->CreateAnimTransform(resource, mpMultiArcResourceAccessor));
pane->addAnimation(allocator, group->animations[j]->id, transform, false, true);
}
}
searchAnmPane("N_Pic")->changeAnimation(3);
mpLayout->Animate(0);
mpLayout->CalculateMtx(mDrawInfo);
mbPhotoScaledUp = 0;
mbPhotoDraw = false;
mbCloseWithSend = false;
}
AnmPane::~AnmPane() {}
void InputForm::drawBody() {
nw4r::lyt::Pane* bodyPane = getPane(paneNames[1]);
f32 y = 0.0f;
for (int row = 0; row < (mnLine - 1) / 4 + 1; row++) {
bodyPane->SetTranslate(nw4r::math::VEC2(0.0f, y));
bodyPane->CalculateMtx(mDrawInfo);
bodyPane->Draw(mDrawInfo);
y -= bodyPane->GetSize().height;
}
if (!mbEdited) {
getPane("T_TouchLetter")->Draw(mDrawInfo);
}
getPane("SendPic")->Draw(mDrawInfo);
getPane("N_SendMes")->Draw(mDrawInfo);
nw4r::lyt::Pane* scrollPane = getPane("N_txt_scrl");
f32 x = scrollPane->GetTranslate().x;
getPane("N_txt_scrl")->SetTranslate(nw4r::math::VEC2(x, -6.0f));
}
void InputForm::drawFooter() {
nw4r::lyt::Pane* bodyPane = getPane(paneNames[1]);
int row = (mnLine - 1) / 4;
f32 y = static_cast<f32>(row) * (bodyPane->GetSize().height * -1.0f);
nw4r::lyt::Pane* footerPane = getPane(paneNames[3]);
footerPane->SetTranslate(nw4r::math::VEC2(0.0f, y));
footerPane->CalculateMtx(mDrawInfo);
footerPane->Draw(mDrawInfo);
if (mbPhotoDraw) {
getPane("N_Pic")->Draw(mDrawInfo);
}
}
nw4r::lyt::Material* InputForm::getPhotoPaneMaterial() {
return getPane("Pic")->FindMaterialByName("Pic", true);
}
void InputForm::onPhotoTrig() {
if (getEditMode() != memo::InputForm::EM_Disp || !mbPhotoDraw) {
return;
}
}
void InputForm::onPhotoPoint() {
if (getEditMode() != memo::InputForm::EM_Disp || mbPhotoScaledUp || !mbPhotoDraw) {
return;
}
}
void InputForm::onPhotoLeft() {
if (getEditMode() != memo::InputForm::EM_Disp || mbPhotoScaledUp || !mbPhotoDraw) {
return;
}
}
void InputForm::open() {
memo::InputForm::open();
switch (meType) {
case T_MailAddressSel:
searchAnmPane("N_MemoRoot")->changeAnimation(6);
break;
case T_Address:
case T_Picture:
case T_Reply:
default:
searchAnmPane("N_MemoRoot")->changeAnimation(4);
break;
}
}
void InputForm::close() {
memo::InputForm::close();
if (mbCloseWithSend) {
searchAnmPane("N_MemoRoot")->changeAnimation(5);
searchAnmPane("SendPic")->changeAnimation(5);
searchAnmPane("N_SendMes")->changeAnimation(5);
} else {
searchAnmPane("N_MemoRoot")->changeAnimation(7);
searchAnmPane("SendPic")->changeAnimation(7);
}
}
bool InputForm::isWholePaneInAnimation() {
return searchAnmPane("N_MemoRoot")->isInAnimation();
}
void InputForm::resizePhotoPane(f32 width, f32 height) {
nw4r::lyt::Pane* pane = getPane("Pic");
pane->SetSize(nw4r::lyt::Size(412.0f, 309.0f));
nw4r::lyt::Size bounds(pane->GetSize());
nw4r::lyt::Size result(bounds);
if (0.0f == width) {
return;
}
if (0.0f == height) {
return;
}
if (width > height) {
result.height = bounds.width * height / width;
if (result.height > bounds.height) {
result.width = bounds.width * (bounds.height / result.height);
result.height = bounds.height;
}
} else {
result.width = bounds.height * width / height;
if (result.width > bounds.width) {
result.height = bounds.height * (bounds.width / result.width);
result.width = bounds.width;
}
}
pane->SetSize(result);
}
void InputForm::setSendOutMessage(const wchar_t* sendOutMessage) {
nw4r::ut::DynamicCast<nw4r::lyt::TextBox*>(
mpLayout->GetRootPane()->FindPaneByName("T_SendMes", true))->SetString(sendOutMessage);
}
void EventHandler::onTiEvent(gui::PaneComponent* paneComponent, u32 event, Input* input) {
if (!static_cast<InputForm*>(mpMemoForm)->isPhotoScaledUp()) {
memo::EventHandler::onTiEvent(paneComponent, event, input);
}
nw4r::lyt::Pane* pane = paneComponent->getPane();
const char* paneName = pane->GetName();
if (paneName[0] == 'B') {
if (event == gui::GUIComponent::EVENT_TRIG && (input->trigger & 0x800) &&
util::strcmp("B_Pic", paneName)) {
static_cast<InputForm*>(mpMemoForm)->onPhotoTrig();
}
if (event == 0 && util::strcmp("B_Pic", paneName)) {
static_cast<InputForm*>(mpMemoForm)->onPhotoPoint();
}
if (event == 1 && util::strcmp("B_Pic", paneName)) {
static_cast<InputForm*>(mpMemoForm)->onPhotoLeft();
}
}
}
bool InputForm::isPhotoScaledUp() {
return mbPhotoScaledUp;
}
u32 AnmPane::getState() {
return meState;
}
void AnmPane::changeAnimation(u32 id) {
meState = id;
nw4rmanager::AnmPane::changeAnimation(id);
}
AnmPane::KeyType AnmPane::getKeyType() const {
return meKeyType;
}
void AnmPane::init() {
meState = 0;
}
PicPane::~PicPane() {}
void PicPane::onAnmEvent(AnmPaneEvent paneEvent) {}
WholePane::~WholePane() {}
void WholePane::onAnmEvent(AnmPaneEvent paneEvent) {}
InputForm::~InputForm() {}
EventHandler::~EventHandler() {}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -44,6 +44,8 @@ namespace textinput {
};
// name made up, no dwarf (?)
inline const char* commonScrollAnimationName() { return COMMON_SCROLL_ANIM; }
inline const char* commonTextAnimationName() { return COMMON_TEXT_ANIM; }
struct PaneToAnimation {
s32 type;
char paneName[20];
@@ -85,7 +87,7 @@ namespace textinput {
{KT_ScrollButton,
"P_prdc_scrl_Rght",
7,
COMMON_SCROLL_ANIM,
commonScrollAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[4], &csAninationFile[5],
&csAninationFile[6]}},
{KT_CandidateText,
@@ -96,97 +98,97 @@ namespace textinput {
{KT_CandidateText,
"T_prdc_Text_01",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_02",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_03",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_04",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_05",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_06",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_07",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_08",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_09",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_10",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_11",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_12",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_13",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_14",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_15",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_16",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_17",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_18",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_CandidateText,
"T_prdc_Text_19",
5,
COMMON_TEXT_ANIM,
commonTextAnimationName(),
{&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}},
{KT_OnOffButton,
"P_OnBtn",

1606
src/keyboard/tiCellPhone.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,534 @@
#define TIHKBMANAGER_IMPLEMENTATION
#include "keyboard/tiHKBManager.h"
#include <revolution/os.h>
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.
struct LedCallbackData {
union {
void* pointer;
u8 device;
};
u32 leds;
};
void HKBManager::SetLedCB(_KBDEc result, void* userData) {
if (result == KBD_EC_BUSY) {
LedCallbackData received;
received.pointer = userData;
LedCallbackData callback;
callback.device = received.device;
const u8 leds = callback.leds = 0;
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.device = device;
const u8 leds = callback.leds = 0;
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<u8>(device)].Initialize(static_cast<u8>(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<u8>(device), states[static_cast<u8>(device)].country);
device++;
} while (device < 2);
}
}
void HKBManager::ClearState() {
for (u32 device = 0; device < 2; device++) {
states[static_cast<u8>(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<u8>(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<u8>(device)];
modifiers = slot->modifiers;
global = lockState & 0x700;
bool changed = global != (modifiers & 0x700);
slot->modifiers &= ~0x700;
slot->modifiers |= lockState;
if (changed &&
attached[static_cast<u8>(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<u8>(device);
mask = 1 << shiftIndex;
if ((retryDevices & mask) != 0) {
LedCallbackData callback;
callback.device = static_cast<u8>(device);
const u8 leds = callback.leds = 0;
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;
for (u32 slot = 0; slot < 8; slot++) {
previousKeys[slot] = currentKeys[slot];
currentKeys[slot] = pendingKeys[slot];
}
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<s32>(country) == 0xf ||
static_cast<s32>(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 {
s32 code = GetVCode();
if (static_cast<u16>(code) >= 0xf130 && static_cast<u16>(code) <= 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 ((static_cast<u32>(code) & 0xffff) >= 0xf140 && (static_cast<u32>(code) & 0xffff) <= 0xf17f) {
code = code + 0x40 & 0xffff;
}
}
u16 character = code;
if ((character & 0xf000) == 0xf000) {
code = 0;
} else if ((static_cast<u32>(code) & 0xffff) == 0xeeee) {
code = 0;
} else if ((static_cast<u32>(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 (; index < count; index++) {
if ((static_cast<u32>(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() {}
}
}

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