id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,001
|
wxCustomEvents.cpp
|
cemu-project_Cemu/src/gui/helpers/wxCustomEvents.cpp
|
#include "gui/helpers/wxCustomEvents.h"
wxDEFINE_EVENT(wxEVT_SET_STATUS_BAR_TEXT, wxSetStatusBarTextEvent);
wxDEFINE_EVENT(wxEVT_SET_GAUGE_VALUE, wxSetGaugeValue);
wxDEFINE_EVENT(wxEVT_REMOVE_ITEM, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_SET_TEXT, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_ENABLE, wxCommandEvent);
| 309
|
C++
|
.cpp
| 6
| 50.5
| 67
| 0.838284
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,002
|
wxHelpers.cpp
|
cemu-project_Cemu/src/gui/helpers/wxHelpers.cpp
|
#include "gui/helpers/wxHelpers.h"
#include <wx/wupdlock.h>
#include <wx/stattext.h>
#include <wx/slider.h>
#include <wx/dirdlg.h>
#include "gui/helpers/wxControlObject.h"
void wxAutosizeColumn(wxListCtrlBase* ctrl, int col)
{
ctrl->SetColumnWidth(col, wxLIST_AUTOSIZE_USEHEADER);
int wh = ctrl->GetColumnWidth(col);
ctrl->SetColumnWidth(col, wxLIST_AUTOSIZE);
int wc = ctrl->GetColumnWidth(col);
if (wh > wc)
ctrl->SetColumnWidth(col, wxLIST_AUTOSIZE_USEHEADER);
}
void wxAutosizeColumns(wxListCtrlBase* ctrl, int col_start, int col_end)
{
wxWindowUpdateLocker lock(ctrl);
for (int i = col_start; i <= col_end; ++i)
wxAutosizeColumn(ctrl, i);
}
void update_slider_text(wxCommandEvent& event, const wxFormatString& format /*= "%d%%"*/)
{
const auto slider = dynamic_cast<wxSlider*>(event.GetEventObject());
wxASSERT(slider);
auto slider_text = dynamic_cast<wxControlObject*>(event.GetEventUserData())->GetControl<wxStaticText>();
wxASSERT(slider_text);
slider_text->SetLabel(wxString::Format(format, slider->GetValue()));
}
uint32 fix_raw_keycode(uint32 keycode, uint32 raw_flags)
{
#if BOOST_OS_WINDOWS
const auto flags = (HIWORD(raw_flags) & 0xFFF);
if(keycode == VK_SHIFT)
{
if(flags == 0x2A)
return 160;
else if (flags == 0x36)
return 161;
}
else if (keycode == VK_CONTROL)
{
if (flags == 0x1d)
return 162;
else if (flags == 0x11d)
return 163;
}
else if (keycode == VK_MENU)
{
if ((flags & 0xFF) == 0x38)
return 164;
else if ((flags & 0xFF) == 0x38)
return 165;
}
#endif
return keycode;
}
| 1,558
|
C++
|
.cpp
| 57
| 25.192982
| 105
| 0.723861
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,003
|
wxWayland.cpp
|
cemu-project_Cemu/src/gui/helpers/wxWayland.cpp
|
#include "gui/helpers/wxWayland.h"
#if BOOST_OS_LINUX && HAS_WAYLAND
#include <dlfcn.h>
bool wxWlIsWaylandWindow(wxWindow* window)
{
GtkWidget* gtkWindow = static_cast<GtkWidget*>(window->GetHandle());
GdkWindow* gdkWindow = gtk_widget_get_window(gtkWindow);
return GDK_IS_WAYLAND_WINDOW(gdkWindow);
}
void wxWlSetAppId(wxFrame* frame, const char* applicationId)
{
GtkWidget* gtkWindow = static_cast<GtkWidget*>(frame->GetHandle());
gtk_widget_realize(gtkWindow);
GdkWindow* gdkWindow = gtk_widget_get_window(gtkWindow);
static auto gdk_wl_set_app_id = reinterpret_cast<void (*) (GdkWindow*, const char*)>(dlsym(nullptr, "gdk_wayland_window_set_application_id"));
if (gdk_wl_set_app_id)
gdk_wl_set_app_id(gdkWindow, applicationId);
}
#endif // BOOST_OS_LINUX && HAS_WAYLAND
| 789
|
C++
|
.cpp
| 19
| 39.736842
| 143
| 0.762092
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,005
|
checktree.cpp
|
cemu-project_Cemu/src/gui/wxcomponents/checktree.cpp
|
#include "gui/wxcomponents/checktree.h"
#include "gui/wxcomponents/checked2.xpm"
#include "gui/wxcomponents/checked_d.xpm"
#include "gui/wxcomponents/checked_ld.xpm"
#include "gui/wxcomponents/checked_mo.xpm"
#include "gui/wxcomponents/unchecked2.xpm"
#include "gui/wxcomponents/unchecked_d.xpm"
#include "gui/wxcomponents/unchecked_ld.xpm"
#include "gui/wxcomponents/unchecked_mo.xpm"
#include <wx/icon.h>
#include <wx/imaglist.h>
wxDEFINE_EVENT(wxEVT_CHECKTREE_FOCUS, wxTreeEvent);
wxDEFINE_EVENT(wxEVT_CHECKTREE_CHOICE, wxTreeEvent);
//IMPLEMENT_DYNAMIC_CLASS(wxCheckTree, wxTreeCtrl)
bool on_check_or_label(int flags)
{
return flags & (wxTREE_HITTEST_ONITEMSTATEICON | wxTREE_HITTEST_ONITEMLABEL) ? true : false;
}
bool on_check(int flags)
{
return flags & (wxTREE_HITTEST_ONITEMSTATEICON) ? true : false;
}
bool on_label(int flags)
{
return flags & (wxTREE_HITTEST_ONITEMLABEL) ? true : false;
}
void unhighlight(wxTreeCtrl* m_treeCtrl1, wxTreeItemId& id)
{
if (!id.IsOk())
return;
const int state = m_treeCtrl1->GetItemState(id);
if (wxCheckTree::UNCHECKED <= state && state < wxCheckTree::UNCHECKED_DISABLED)
{
m_treeCtrl1->SetItemState(id, wxCheckTree::UNCHECKED);
}
else if (wxCheckTree::CHECKED <= state && state < wxCheckTree::CHECKED_DISABLED)
{
m_treeCtrl1->SetItemState(id, wxCheckTree::CHECKED);
}
}
void mohighlight(wxTreeCtrl* m_treeCtrl1, wxTreeItemId& id, bool toggle)
{
if (!id.IsOk())
return;
const int i = m_treeCtrl1->GetItemState(id);
if (i < 0)
return;
bool is_checked = false;
if (wxCheckTree::UNCHECKED <= i && i < wxCheckTree::UNCHECKED_DISABLED)
{
m_treeCtrl1->SetItemState(id, toggle ? wxCheckTree::CHECKED_MOUSE_OVER : wxCheckTree::UNCHECKED_MOUSE_OVER);
is_checked = true;
}
else if (wxCheckTree::CHECKED <= i && i < wxCheckTree::CHECKED_DISABLED)
{
m_treeCtrl1->SetItemState(id, toggle ? wxCheckTree::UNCHECKED_MOUSE_OVER : wxCheckTree::CHECKED_MOUSE_OVER);
is_checked = false;
}
if (toggle)
{
wxTreeEvent event2(wxEVT_CHECKTREE_CHOICE, m_treeCtrl1, id);
event2.SetExtraLong(is_checked ? 1 : 0);
m_treeCtrl1->ProcessWindowEvent(event2);
}
}
void ldhighlight(wxTreeCtrl* m_treeCtrl1, wxTreeItemId& id)
{
if (!id.IsOk())
return;
const int i = m_treeCtrl1->GetItemState(id);
if (wxCheckTree::UNCHECKED <= i && i < wxCheckTree::UNCHECKED_DISABLED)
{
m_treeCtrl1->SetItemState(id, wxCheckTree::UNCHECKED_LEFT_DOWN);
}
else if (wxCheckTree::CHECKED <= i && i < wxCheckTree::CHECKED_DISABLED)
{
m_treeCtrl1->SetItemState(id, wxCheckTree::CHECKED_LEFT_DOWN);
}
}
wxIMPLEMENT_CLASS(wxCheckTree, wxTreeCtrl);
wxCheckTree::wxCheckTree()
{
Init();
}
wxCheckTree::wxCheckTree(wxWindow* parent, const wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
: wxTreeCtrl(parent, id, pos, size, style)
{
Init();
}
void wxCheckTree::Init()
{
wxIcon icons[8] =
{
wxIcon(unchecked2_xpm), wxIcon(unchecked_mo_xpm), wxIcon(unchecked_ld_xpm), wxIcon(unchecked_d_xpm), wxIcon(checked2_xpm), wxIcon(checked_mo_xpm), wxIcon(checked_ld_xpm), wxIcon(checked_d_xpm)
};
// Make an state image list containing small icons
auto states = new wxImageList(icons[0].GetWidth(), icons[0].GetHeight(), true);
for (const auto& icon : icons)
states->Add(icon);
AssignStateImageList(states);
Connect(wxEVT_TREE_SEL_CHANGING, wxTreeEventHandler( wxCheckTree::On_Tree_Sel_Changed ), nullptr, this);
Connect(wxEVT_CHAR, wxKeyEventHandler( wxCheckTree::On_Char ), nullptr, this);
Connect(wxEVT_KEY_DOWN, wxKeyEventHandler( wxCheckTree::On_KeyDown ), nullptr, this);
Connect(wxEVT_KEY_UP, wxKeyEventHandler( wxCheckTree::On_KeyUp ), nullptr, this);
Connect(wxEVT_ENTER_WINDOW, wxMouseEventHandler( wxCheckTree::On_Mouse_Enter_Tree ), nullptr, this);
Connect(wxEVT_LEAVE_WINDOW, wxMouseEventHandler( wxCheckTree::On_Mouse_Leave_Tree ), nullptr, this);
Connect(wxEVT_LEFT_DCLICK, wxMouseEventHandler( wxCheckTree::On_Left_DClick ), nullptr, this);
Connect(wxEVT_LEFT_DOWN, wxMouseEventHandler( wxCheckTree::On_Left_Down ), nullptr, this);
Connect(wxEVT_LEFT_UP, wxMouseEventHandler( wxCheckTree::On_Left_Up ), nullptr, this);
Connect(wxEVT_MOTION, wxMouseEventHandler( wxCheckTree::On_Mouse_Motion ), nullptr, this);
Connect(wxEVT_MOUSEWHEEL, wxMouseEventHandler( wxCheckTree::On_Mouse_Wheel ), nullptr, this);
Connect(wxEVT_SET_FOCUS, wxFocusEventHandler( wxCheckTree::On_Tree_Focus_Set ), nullptr, this);
Connect(wxEVT_KILL_FOCUS, wxFocusEventHandler( wxCheckTree::On_Tree_Focus_Lost ), nullptr, this);
}
void wxCheckTree::Sort(const wxTreeItemId& node, bool recursive)
{
if (recursive)
{
wxTreeItemIdValue cookie;
for(auto it = GetFirstChild(node, cookie); it.IsOk(); it = GetNextChild(it, cookie))
{
Sort(it, true);
}
}
if(GetChildrenCount(node, false) > 0)
this->SortChildren(node);
}
int wxCheckTree::OnCompareItems(const wxTreeItemId& item1, const wxTreeItemId& item2)
{
const bool check1 = GetChildrenCount(item1, false) == 0;
const bool check2 = GetChildrenCount(item2, false) == 0;
if (!check1 && check2)
return -1;
if (check1 && !check2)
return 1;
return GetItemText(item1).Lower().compare(GetItemText(item2).Lower());
}
void wxCheckTree::SetItemTextColour(const wxTreeItemId& item, const wxColour& col)
{
const auto it = m_colors.find(item);
if (it == m_colors.end())
m_colors.emplace(std::pair<wxTreeItemId,wxColor>(item, col));
else
m_colors[item] = col;
wxTreeCtrl::SetItemTextColour(item, col);
}
bool wxCheckTree::EnableCheckBox(const wxTreeItemId& item, bool enable)
{
if (!item.IsOk())
return false;
const int state = GetItemState(item);
if (state < 0 || state > CHECKED_DISABLED)
return false;
if (enable)
{
if (state == UNCHECKED_DISABLED)
SetItemState(item, UNCHECKED);
else if (state == CHECKED_DISABLED)
SetItemState(item, CHECKED);
const auto it = m_colors.find(item);
if (it != m_colors.end())
{
SetItemTextColour(item, it->second);
m_colors.erase(it);
}
return true;
}
if (state == UNCHECKED_DISABLED || state == CHECKED_DISABLED)
{
//don't disable a second time or we'll lose the
//text color information.
return true;
}
if (state == UNCHECKED || state == UNCHECKED_MOUSE_OVER || state == UNCHECKED_LEFT_DOWN)
SetItemState(item, UNCHECKED_DISABLED);
else if (state == CHECKED || state == CHECKED_MOUSE_OVER || state == CHECKED_LEFT_DOWN)
SetItemState(item, CHECKED_DISABLED);
const wxColor col = GetItemTextColour(item);
SetItemTextColour(item, wxColour(161, 161, 146));
m_colors[item] = col;
return true;
}
bool wxCheckTree::DisableCheckBox(const wxTreeItemId& item)
{
return EnableCheckBox(item, false);
}
void wxCheckTree::MakeCheckable(const wxTreeItemId& item, bool state)
{
if (!item.IsOk())
return;
const int i = GetItemState(item);
if (i < 0 || i > CHECKED_DISABLED)
SetItemState(item, state ? CHECKED : UNCHECKED);
}
bool wxCheckTree::IsCheckable(const wxTreeItemId& item)
{
if (!item.IsOk())
return false;
const int i = GetItemState(item);
return i >= 0 && i <= CHECKED_DISABLED;
}
void wxCheckTree::Check(const wxTreeItemId& item, bool state)
{
if (!item.IsOk())
return;
const int old_state = GetItemState(item);
if (UNCHECKED <= old_state && old_state <= CHECKED_DISABLED)
{
const bool enable = !(old_state == UNCHECKED_DISABLED || old_state == CHECKED_DISABLED);
int check = enable ? CHECKED : CHECKED_DISABLED;
int uncheck = enable ? UNCHECKED : UNCHECKED_DISABLED;
const int new_state = state ? check : uncheck;
if (new_state != old_state)
{
SetItemState(item, new_state);
}
}
}
void wxCheckTree::Uncheck(const wxTreeItemId& item)
{
Check(item, false);
}
void wxCheckTree::On_Tree_Sel_Changed(wxTreeEvent& event)
{
wxTreeItemId id = event.GetItem();
unhighlight(this, last_kf);
mohighlight(this, id, false);
last_kf = id;
event.Skip();
}
void wxCheckTree::On_Char(wxKeyEvent& event)
{
if (!GetSelection().IsOk() && GetCount() > 0)
{
//If there is no selection, any keypress should just select the first item
wxTreeItemIdValue cookie;
const auto new_item = HasFlag(wxTR_HIDE_ROOT) ? GetFirstChild(GetRootItem(), cookie) : GetRootItem();
SelectItem(new_item);
last_kf = new_item;
return;
}
event.Skip();
}
void wxCheckTree::On_KeyDown(wxKeyEvent& event)
{
if (event.GetKeyCode() == WXK_SPACE)
{
last_kf = this->GetSelection();
ldhighlight(this, last_kf);
}
event.Skip();
}
void wxCheckTree::On_KeyUp(wxKeyEvent& event)
{
if (event.GetKeyCode() == WXK_SPACE)
{
//last_kf = this->GetSelection();
mohighlight(this, last_kf, true);
}
else if (event.GetKeyCode() == WXK_ESCAPE)
{
unhighlight(this, last_kf);
last_kf = {};
Unselect();
}
event.Skip();
}
void wxCheckTree::On_Mouse_Enter_Tree(wxMouseEvent& event)
{
if (event.LeftIsDown())
{
mouse_entered_tree_with_left_down = true;
}
}
void wxCheckTree::On_Mouse_Leave_Tree(wxMouseEvent& event)
{
unhighlight(this, last_mouse_over);
unhighlight(this, last_left_down);
last_mouse_over = {};
last_left_down = {};
}
void wxCheckTree::On_Left_DClick(wxMouseEvent& event)
{
int flags;
HitTest(event.GetPosition(), flags);
//double clicks on buttons can be annoying, so we'll ignore those
//but all other double clicks will just have 1 more click added to them
//without this, the check boxes are not as responsive as they should be
if (!(flags & wxTREE_HITTEST_ONITEMBUTTON))
{
On_Left_Down(event);
On_Left_Up(event);
}
}
void wxCheckTree::On_Left_Down(wxMouseEvent& event)
{
int flags;
wxTreeItemId id = HitTest(event.GetPosition(), flags);
if (!id.IsOk())
return;
int i = GetItemState(id);
if (id.IsOk() && i >= 0 && on_check(flags))
{
last_left_down = id;
ldhighlight(this, id);
}
else if (on_label(flags))
event.Skip();
}
void wxCheckTree::On_Left_Up(wxMouseEvent& event)
{
SetFocus();
int flags;
wxTreeItemId id = HitTest(event.GetPosition(), flags);
if (!id.IsOk())
return;
int i = GetItemState(id);
if (mouse_entered_tree_with_left_down)
{
mouse_entered_tree_with_left_down = false;
if (i >= 0 && on_check(flags))
{
mohighlight(this, id, false);
last_mouse_over = id;
}
}
else if (id.IsOk())
{
if (flags & wxTREE_HITTEST_ONITEMBUTTON && ItemHasChildren(id))
{
if (IsExpanded(id))
{
Collapse(id);
}
else
{
Expand(id);
}
}
else if (i >= 0 && on_check(flags))
{
if (id != last_left_down)
{
unhighlight(this, last_left_down);
mohighlight(this, id, false);
}
else
{
mohighlight(this, id, true);
}
last_left_down = wxTreeItemId();
last_mouse_over = id;
}
else if (on_label(flags))
{
event.Skip();
}
else
{
unhighlight(this, last_left_down);
unhighlight(this, last_mouse_over);
last_left_down = wxTreeItemId();
last_mouse_over = wxTreeItemId();
}
}
else
{
//id is not ok
unhighlight(this, last_left_down);
unhighlight(this, last_mouse_over);
last_left_down = wxTreeItemId();
last_mouse_over = wxTreeItemId();
}
}
void wxCheckTree::On_Mouse_Motion(wxMouseEvent& event)
{
if (mouse_entered_tree_with_left_down)
{
//just ignore everything until the left button is released
return;
}
int flags;
wxTreeItemId id = HitTest(event.GetPosition(), flags);
if (!id.IsOk())
{
unhighlight(this, last_mouse_over);
last_mouse_over = {};
}
else if (event.LeftIsDown() && last_left_down.IsOk())
{
//to match the behavior of ordinary check boxes,
//if we've moved to a new item while holding the mouse button down
//we want to set the item where the left down click occured to have
//mouse over highlight. And if we return to the box where the
//left down occured, we want to return it to the having the left down highlight
//I don't understand why this is the behavior
//of ordinary check boxes, but I'm goin to match it anyway.
if (id == last_left_down)
{
const auto state = GetItemState(last_left_down);
if (state != UNCHECKED_LEFT_DOWN && state != CHECKED_LEFT_DOWN)
{
ldhighlight(this, last_left_down);
}
}
else
mohighlight(this, last_left_down, false);
}
else
{
//4 cases 1 we're still on the same item, but we've moved off the state icon or label
// 2 we're still on the same item and on the state icon or label - do nothing
// 3 we're on a new item but not on its state icon or label (or the new item has no state)
// 4 we're on a new item, it has a state icon, and we're on the state icon or label
const int state = GetItemState(id);
if (id == last_mouse_over)
{
if (state < 0 || !on_check(flags))
{
unhighlight(this, last_mouse_over);
last_mouse_over = {};
}
}
else
{
if (state < 0 || !on_check(flags))
{
unhighlight(this, last_mouse_over);
last_mouse_over = {};
}
else
{
unhighlight(this, last_mouse_over);
mohighlight(this, id, false);
last_mouse_over = id;
}
}
}
}
void wxCheckTree::On_Mouse_Wheel(wxMouseEvent& event)
{
event.Skip();
}
void wxCheckTree::On_Tree_Focus_Set(wxFocusEvent& event)
{
//event.Skip();
//skipping this event will set the last selected item
//to be highlighted and I want the tree items to only be
//highlighted by keyboard actions.
}
void wxCheckTree::On_Tree_Focus_Lost(wxFocusEvent& event)
{
unhighlight(this, last_kf);
Unselect();
event.Skip();
}
void wxCheckTree::SetFocusFromKbd()
{
if (last_kf.IsOk())
SelectItem(last_kf);
wxTreeEvent event2(wxEVT_CHECKTREE_FOCUS, this, wxTreeItemId());
ProcessWindowEvent(event2);
wxWindow::SetFocusFromKbd();
}
| 13,560
|
C++
|
.cpp
| 464
| 26.743534
| 194
| 0.721338
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,006
|
DebuggerWindow2.cpp
|
cemu-project_Cemu/src/gui/debugger/DebuggerWindow2.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/DebuggerWindow2.h"
#include <filesystem>
#include "config/ActiveSettings.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/OS/RPL/rpl_debug_symbols.h"
#include "gui/debugger/RegisterWindow.h"
#include "gui/debugger/DumpWindow.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/OS/RPL/rpl.h"
#include "gui/debugger/DisasmCtrl.h"
#include "gui/debugger/SymbolWindow.h"
#include "gui/debugger/BreakpointWindow.h"
#include "gui/debugger/ModuleWindow.h"
#include "util/helpers/helpers.h"
#include "resource/embedded/resources.h"
enum
{
// file
MENU_ID_FILE_EXIT = wxID_HIGHEST + 8000,
// settings
MENU_ID_OPTIONS_PIN_TO_MAINWINDOW,
MENU_ID_OPTIONS_BREAK_ON_START,
// window
MENU_ID_WINDOW_REGISTERS,
MENU_ID_WINDOW_DUMP,
MENU_ID_WINDOW_STACK,
MENU_ID_WINDOW_BREAKPOINTS,
MENU_ID_WINDOW_MODULE,
MENU_ID_WINDOW_SYMBOL,
// tool
TOOL_ID_GOTO,
TOOL_ID_BP,
TOOL_ID_PAUSE,
TOOL_ID_STEP_OVER,
TOOL_ID_STEP_INTO,
};
wxDEFINE_EVENT(wxEVT_DEBUGGER_CLOSE, wxCloseEvent);
wxDEFINE_EVENT(wxEVT_UPDATE_VIEW, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_BREAKPOINT_CHANGE, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_BREAKPOINT_HIT, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_MOVE_IP, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_RUN, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_NOTIFY_MODULE_LOADED, wxCommandEvent);
wxDEFINE_EVENT(wxEVT_NOTIFY_MODULE_UNLOADED, wxCommandEvent);
wxBEGIN_EVENT_TABLE(DebuggerWindow2, wxFrame)
EVT_SHOW(DebuggerWindow2::OnShow)
EVT_CLOSE(DebuggerWindow2::OnClose)
EVT_COMMAND(wxID_ANY, wxEVT_UPDATE_VIEW, DebuggerWindow2::OnUpdateView)
EVT_COMMAND(wxID_ANY, wxEVT_BREAKPOINT_CHANGE, DebuggerWindow2::OnBreakpointChange)
EVT_COMMAND(wxID_ANY, wxEVT_MOVE_IP, DebuggerWindow2::OnMoveIP)
EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_TOOL_CLICKED, DebuggerWindow2::OnToolClicked)
EVT_COMMAND(wxID_ANY, wxEVT_BREAKPOINT_HIT, DebuggerWindow2::OnBreakpointHit)
EVT_COMMAND(wxID_ANY, wxEVT_RUN, DebuggerWindow2::OnRunProgram)
EVT_COMMAND(wxID_ANY, wxEVT_NOTIFY_MODULE_LOADED, DebuggerWindow2::OnNotifyModuleLoaded)
EVT_COMMAND(wxID_ANY, wxEVT_NOTIFY_MODULE_UNLOADED, DebuggerWindow2::OnNotifyModuleUnloaded)
// file menu
EVT_MENU(MENU_ID_FILE_EXIT, DebuggerWindow2::OnExit)
// window
EVT_MENU_RANGE(MENU_ID_WINDOW_REGISTERS, MENU_ID_WINDOW_MODULE, DebuggerWindow2::OnWindowMenu)
wxEND_EVENT_TABLE()
DebuggerWindow2* g_debugger_window;
void DebuggerConfig::Load(XMLConfigParser& parser)
{
pin_to_main = parser.get("PinToMainWindow", true);
break_on_start = parser.get("break_on_start", true);
auto window_parser = parser.get("Windows");
show_register = window_parser.get("Registers", true);
show_dump = window_parser.get("MemoryDump", true);
show_stack = window_parser.get("Stack", true);
show_breakpoints = window_parser.get("Breakpoints", true);
show_modules = window_parser.get("Modules", true);
show_symbols = window_parser.get("Symbols", true);
}
void DebuggerConfig::Save(XMLConfigParser& parser)
{
parser.set("PinToMainWindow", pin_to_main);
parser.set("break_on_start", break_on_start);
auto window_parser = parser.set("Windows");
window_parser.set("Registers", show_register);
window_parser.set("MemoryDump", show_dump);
window_parser.set("Stack", show_stack);
window_parser.set("Breakpoints", show_breakpoints);
window_parser.set("Modules", show_modules);
window_parser.set("Symbols", show_symbols);
}
void DebuggerModuleStorage::Load(XMLConfigParser& parser)
{
auto breakpoints_parser = parser.get("Breakpoints");
for (auto element = breakpoints_parser.get("Entry"); element.valid(); element = breakpoints_parser.get("Entry", element))
{
const auto address_string = element.get("Address", "");
if (*address_string == '\0')
continue;
uint32 relative_address = std::stoul(address_string, nullptr, 16);
if (relative_address == 0)
continue;
auto type = element.get("Type", 0);
auto enabled = element.get("Enabled", true);
const auto comment = element.get("Comment", "");
// calculate absolute address
uint32 module_base_address = (type == DEBUGGER_BP_T_NORMAL || type == DEBUGGER_BP_T_LOGGING) ? this->rpl_module->regionMappingBase_text.GetMPTR() : this->rpl_module->regionMappingBase_data;
uint32 address = module_base_address + relative_address;
// don't change anything if there's already a breakpoint
if (debugger_getFirstBP(address) != nullptr)
continue;
// register breakpoints in debugger
if (type == DEBUGGER_BP_T_NORMAL)
debugger_createCodeBreakpoint(address, DEBUGGER_BP_T_NORMAL);
else if (type == DEBUGGER_BP_T_LOGGING)
debugger_createCodeBreakpoint(address, DEBUGGER_BP_T_LOGGING);
else if (type == DEBUGGER_BP_T_MEMORY_READ)
debugger_createMemoryBreakpoint(address, true, false);
else if (type == DEBUGGER_BP_T_MEMORY_WRITE)
debugger_createMemoryBreakpoint(address, false, true);
else
continue;
DebuggerBreakpoint* debugBreakpoint = debugger_getFirstBP(address);
if (!enabled)
debugger_toggleBreakpoint(address, false, debugBreakpoint);
debugBreakpoint->comment = boost::nowide::widen(comment);
}
auto comments_parser = parser.get("Comments");
for (XMLConfigParser element = comments_parser.get("Entry"); element.valid(); element = comments_parser.get("Entry", element))
{
const auto address_string = element.get("Address", "");
if (*address_string == '\0')
continue;
uint32 address = std::stoul(address_string, nullptr, 16);
if (address == 0)
continue;
const auto comment = element.get("Comment", "");
if (*comment == '\0')
continue;
rplDebugSymbol_createComment(address, boost::nowide::widen(comment).c_str());
}
}
void DebuggerModuleStorage::Save(XMLConfigParser& parser)
{
auto breakpoints_parser = parser.set("Breakpoints");
for (const auto& bp : debuggerState.breakpoints)
{
// check breakpoint type
if (bp->dbType != DEBUGGER_BP_T_DEBUGGER)
continue;
// check whether the breakpoint is part of the current module being saved
RPLModule* address_module;
if (bp->bpType == DEBUGGER_BP_T_NORMAL || bp->bpType == DEBUGGER_BP_T_LOGGING) address_module = RPLLoader_FindModuleByCodeAddr(bp->address);
else if (bp->isMemBP()) address_module = RPLLoader_FindModuleByDataAddr(bp->address);
else continue;
if (!address_module || !(address_module->moduleName2 == this->module_name && address_module->patchCRC == this->crc_hash))
continue;
uint32_t relative_address = bp->address - (bp->isMemBP() ? address_module->regionMappingBase_data : address_module->regionMappingBase_text.GetMPTR());
auto entry = breakpoints_parser.set("Entry");
entry.set("Address", fmt::format("{:#10x}", relative_address));
entry.set("Comment", boost::nowide::narrow(bp->comment).c_str());
entry.set("Type", bp->bpType);
entry.set("Enabled", bp->enabled);
if (this->delete_breakpoints_after_saving) debugger_deleteBreakpoint(bp);
this->delete_breakpoints_after_saving = false;
}
auto comments_parser = parser.set("Comments");
for (const auto& comment_entry : rplDebugSymbol_getSymbols())
{
// check comment type
const auto comment_address = comment_entry.first;
const auto comment = static_cast<rplDebugSymbolComment*>(comment_entry.second);
if (!comment || comment->type != RplDebugSymbolComment)
continue;
// check whether it's part of the current module being saved
RPLModule* address_module = RPLLoader_FindModuleByCodeAddr(comment_entry.first);
if (!address_module || !(address_module->moduleName2 == module_name && address_module->patchCRC == this->crc_hash))
continue;
uint32_t relative_address = comment_address - address_module->regionMappingBase_text.GetMPTR();
auto entry = comments_parser.set("Entry");
entry.set("Address", fmt::format("{:#10x}", relative_address));
entry.set("Comment", boost::nowide::narrow(comment->comment).c_str());
}
}
void DebuggerWindow2::CreateToolBar()
{
m_toolbar = wxFrame::CreateToolBar(wxTB_HORIZONTAL, wxID_ANY);
m_toolbar->SetToolBitmapSize(wxSize(16, 16));
m_toolbar->AddTool(TOOL_ID_GOTO, wxEmptyString, wxBITMAP_PNG_FROM_DATA(DEBUGGER_GOTO), wxNullBitmap, wxITEM_NORMAL, _("GoTo (CTRL + G)"), "test", NULL);
m_toolbar->AddSeparator();
m_toolbar->AddTool(TOOL_ID_BP, wxEmptyString, wxBITMAP_PNG_FROM_DATA(DEBUGGER_BP_RED), wxNullBitmap, wxITEM_NORMAL, _("Toggle Breakpoint (F9)"), wxEmptyString, NULL);
m_toolbar->AddSeparator();
m_pause = wxBITMAP_PNG_FROM_DATA(DEBUGGER_PAUSE);
m_run = wxBITMAP_PNG_FROM_DATA(DEBUGGER_PLAY);
m_toolbar->AddTool(TOOL_ID_PAUSE, wxEmptyString, m_pause, wxNullBitmap, wxITEM_NORMAL, _("Break (F5)"), wxEmptyString, NULL);
m_toolbar->AddTool(TOOL_ID_STEP_INTO, wxEmptyString, wxBITMAP_PNG_FROM_DATA(DEBUGGER_STEP_INTO), wxNullBitmap, wxITEM_NORMAL, _("Step Into (F11)"), wxEmptyString, NULL);
m_toolbar->AddTool(TOOL_ID_STEP_OVER, wxEmptyString, wxBITMAP_PNG_FROM_DATA(DEBUGGER_STEP_OVER), wxNullBitmap, wxITEM_NORMAL, _("Step Over (F10)"), wxEmptyString, NULL);
m_toolbar->AddSeparator();
m_toolbar->Realize();
m_toolbar->EnableTool(TOOL_ID_STEP_INTO, false);
m_toolbar->EnableTool(TOOL_ID_STEP_OVER, false);
}
void DebuggerWindow2::SaveModuleStorage(const RPLModule* module, bool delete_breakpoints)
{
auto path = GetModuleStoragePath(module->moduleName2, module->patchCRC);
for (auto& module_storage : m_modules_storage)
{
if (module_storage->data().module_name == module->moduleName2 && module_storage->data().crc_hash == module->patchCRC)
{
module_storage->data().delete_breakpoints_after_saving = delete_breakpoints;
module_storage->Save(path);
if (delete_breakpoints) m_modules_storage.erase(std::find(m_modules_storage.begin(), m_modules_storage.end(), module_storage));
}
}
}
void DebuggerWindow2::LoadModuleStorage(const RPLModule* module)
{
auto path = GetModuleStoragePath(module->moduleName2, module->patchCRC);
bool already_loaded = std::any_of(m_modules_storage.begin(), m_modules_storage.end(), [path](const std::unique_ptr<XMLDebuggerModuleConfig>& debug) { return debug->GetFilename() == path; });
if (!path.empty() && !already_loaded)
{
m_modules_storage.emplace_back(new XMLDebuggerModuleConfig(path, { module->moduleName2, module->patchCRC, module, false }))->Load();
}
}
DebuggerWindow2::DebuggerWindow2(wxFrame& parent, const wxRect& display_size)
: wxFrame(&parent, wxID_ANY, _("PPC Debugger"), wxDefaultPosition, wxSize(1280, 300), wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT),
m_module_address(0)
{
this->wxWindowBase::SetBackgroundColour(*wxWHITE);
const auto file = ActiveSettings::GetConfigPath("debugger/config.xml");
m_config.SetFilename(file.generic_wstring());
m_config.Load();
debuggerState.breakOnEntry = m_config.data().break_on_start;
m_main_position = parent.GetPosition();
m_main_size = parent.GetSize();
auto y = std::max<uint32>(300, (display_size.GetHeight() - 500 - 300) * 0.8);
this->SetSize(1280, y);
CreateMenuBar();
CreateToolBar();
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
// load configs for already loaded modules
const auto module_count = RPLLoader_GetModuleCount();
const auto module_list = RPLLoader_GetModuleList();
for (sint32 i = 0; i < module_count; i++)
{
const auto module = module_list[i];
LoadModuleStorage(module);
}
wxString label_text = _("> no modules loaded");
if (module_count != 0)
{
RPLModule* current_rpl_module = RPLLoader_FindModuleByCodeAddr(MEMORY_CODEAREA_ADDR);
if (current_rpl_module)
label_text = wxString::Format("> %s", current_rpl_module->moduleName2.c_str());
else
label_text = _("> unknown module");
}
m_module_label = new wxStaticText(this, wxID_ANY, label_text);
m_module_label->SetBackgroundColour(*wxWHITE);
m_module_label->SetForegroundColour(wxColour(0xFFbf52fe));
main_sizer->Add(m_module_label, 0, wxEXPAND | wxALL, 5);
m_disasm_ctrl = new DisasmCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxScrolledWindowStyle);
main_sizer->Add(m_disasm_ctrl, 1, wxEXPAND);
this->SetSizer(main_sizer);
this->wxWindowBase::Layout();
m_register_window = new RegisterWindow(*this, m_main_position, m_main_size);
m_dump_window = new DumpWindow(*this, m_main_position, m_main_size);
m_breakpoint_window = new BreakpointWindow(*this, m_main_position, m_main_size);
m_module_window = new ModuleWindow(*this, m_main_position, m_main_size);
m_symbol_window = new SymbolWindow(*this, m_main_position, m_main_size);
const bool value = m_config.data().pin_to_main;
m_config.data().pin_to_main = true;
OnParentMove(m_main_position, m_main_size);
m_config.data().pin_to_main = value;
g_debugger_window = this;
}
DebuggerWindow2::~DebuggerWindow2()
{
debuggerState.breakOnEntry = false;
g_debugger_window = nullptr;
// save configs for all modules that are still loaded
// doesn't delete breakpoints since that should (in the future) be done by unloading the rpl modules when exiting the current game
const auto module_count = RPLLoader_GetModuleCount();
const auto module_list = RPLLoader_GetModuleList();
for (sint32 i = 0; i < module_count; i++)
{
const auto module = module_list[i];
if (module)
SaveModuleStorage(module, false);
}
if (m_register_window && m_register_window->IsShown())
m_register_window->Close(true);
if (m_dump_window && m_dump_window->IsShown())
m_dump_window->Close(true);
if (m_breakpoint_window && m_breakpoint_window->IsShown())
m_breakpoint_window->Close(true);
if (m_module_window && m_module_window->IsShown())
m_module_window->Close(true);
if (m_symbol_window && m_symbol_window->IsShown())
m_symbol_window->Close(true);
m_config.Save();
}
void DebuggerWindow2::OnClose(wxCloseEvent& event)
{
debuggerState.breakOnEntry = false;
const wxCloseEvent parentEvent(wxEVT_DEBUGGER_CLOSE);
wxPostEvent(m_parent, parentEvent);
event.Skip();
}
void DebuggerWindow2::OnMoveIP(wxCommandEvent& event)
{
const auto ip = debuggerState.debugSession.instructionPointer;
UpdateModuleLabel(ip);
m_disasm_ctrl->CenterOffset(ip);
}
void DebuggerWindow2::OnParentMove(const wxPoint& main_position, const wxSize& main_size)
{
m_main_position = main_position;
m_main_size = main_size;
if (!m_config.data().pin_to_main)
return;
wxSize size(m_main_size.x, GetSize().GetHeight());
SetSize(size);
wxPoint position = m_main_position;
position.y -= size.y;
SetPosition(position);
m_register_window->OnMainMove(main_position, main_size);
m_dump_window->OnMainMove(main_position, main_size);
m_breakpoint_window->OnMainMove(main_position, main_size);
m_module_window->OnMainMove(main_position, main_size);
m_symbol_window->OnMainMove(main_position, main_size);
}
void DebuggerWindow2::OnNotifyModuleLoaded(wxCommandEvent& event)
{
RPLModule* module = (RPLModule*)event.GetClientData();
LoadModuleStorage(module);
m_module_window->OnGameLoaded();
m_symbol_window->OnGameLoaded();
m_disasm_ctrl->Init();
}
void DebuggerWindow2::OnNotifyModuleUnloaded(wxCommandEvent& event)
{
RPLModule* module = (RPLModule*)event.GetClientData();
SaveModuleStorage(module, true);
m_module_window->OnGameLoaded();
m_symbol_window->OnGameLoaded();
m_disasm_ctrl->Init();
}
void DebuggerWindow2::OnGameLoaded()
{
m_disasm_ctrl->Init();
m_dump_window->OnGameLoaded();
m_module_window->OnGameLoaded();
m_breakpoint_window->OnGameLoaded();
m_symbol_window->OnGameLoaded();
RPLModule* current_rpl_module = RPLLoader_FindModuleByCodeAddr(MEMORY_CODEAREA_ADDR);
if(current_rpl_module)
m_module_label->SetLabel(wxString::Format("> %s", current_rpl_module->moduleName2.c_str()));
this->SendSizeEvent();
}
XMLDebuggerConfig& DebuggerWindow2::GetConfig()
{
return m_config;
}
bool DebuggerWindow2::Show(bool show)
{
const bool result = wxFrame::Show(show);
if (show)
{
m_register_window->Show(m_config.data().show_register);
m_dump_window->Show(m_config.data().show_dump);
m_breakpoint_window->Show(m_config.data().show_breakpoints);
m_module_window->Show(m_config.data().show_modules);
m_symbol_window->Show(m_config.data().show_symbols);
}
else
{
m_register_window->Show(false);
m_dump_window->Show(false);
m_breakpoint_window->Show(false);
m_module_window->Show(false);
m_symbol_window->Show(false);
}
return result;
}
std::wstring DebuggerWindow2::GetModuleStoragePath(std::string module_name, uint32_t crc_hash) const
{
if (module_name.empty() || crc_hash == 0) return {};
return ActiveSettings::GetConfigPath("debugger/{}_{:#10x}.xml", module_name, crc_hash).generic_wstring();
}
void DebuggerWindow2::OnBreakpointHit(wxCommandEvent& event)
{
const auto ip = debuggerState.debugSession.instructionPointer;
UpdateModuleLabel(ip);
m_toolbar->SetToolShortHelp(TOOL_ID_PAUSE, _("Run (F5)"));
m_toolbar->SetToolNormalBitmap(TOOL_ID_PAUSE, m_run);
m_toolbar->EnableTool(TOOL_ID_STEP_INTO, true);
m_toolbar->EnableTool(TOOL_ID_STEP_OVER, true);
m_disasm_ctrl->CenterOffset(ip);
}
void DebuggerWindow2::OnRunProgram(wxCommandEvent& event)
{
m_toolbar->SetToolShortHelp(TOOL_ID_PAUSE, _("Break (F5)"));
m_toolbar->SetToolNormalBitmap(TOOL_ID_PAUSE, m_pause);
m_toolbar->EnableTool(TOOL_ID_STEP_INTO, false);
m_toolbar->EnableTool(TOOL_ID_STEP_OVER, false);
}
void DebuggerWindow2::OnToolClicked(wxCommandEvent& event)
{
switch(event.GetId())
{
case TOOL_ID_GOTO:
m_disasm_ctrl->GoToAddressDialog();
break;
case TOOL_ID_PAUSE:
if (debugger_isTrapped())
debugger_resume();
else
debugger_forceBreak();
break;
case TOOL_ID_STEP_INTO:
if (debugger_isTrapped())
debuggerState.debugSession.stepInto = true;
break;
case TOOL_ID_STEP_OVER:
if (debugger_isTrapped())
debuggerState.debugSession.stepOver = true;
break;
}
}
void DebuggerWindow2::OnBreakpointChange(wxCommandEvent& event)
{
m_breakpoint_window->OnUpdateView();
m_disasm_ctrl->RefreshControl();
UpdateModuleLabel();
}
void DebuggerWindow2::OnOptionsInput(wxCommandEvent& event)
{
switch (event.GetId())
{
case MENU_ID_OPTIONS_PIN_TO_MAINWINDOW:
{
const bool value = !m_config.data().pin_to_main;
m_config.data().pin_to_main = value;
if (value)
OnParentMove(m_main_position, m_main_size);
break;
}
case MENU_ID_OPTIONS_BREAK_ON_START:
{
const bool value = !m_config.data().break_on_start;
m_config.data().break_on_start = value;
debuggerState.breakOnEntry = value;
break;
}
default:
return;
}
m_config.Save();
}
void DebuggerWindow2::OnWindowMenu(wxCommandEvent& event)
{
switch (event.GetId())
{
case MENU_ID_WINDOW_REGISTERS:
{
const bool value = !m_config.data().show_register;
m_config.data().show_register = value;
m_register_window->Show(value);
break;
}
case MENU_ID_WINDOW_DUMP:
{
const bool value = !m_config.data().show_dump;
m_config.data().show_dump = value;
m_dump_window->Show(value);
break;
}
case MENU_ID_WINDOW_BREAKPOINTS:
{
const bool value = !m_config.data().show_breakpoints;
m_config.data().show_breakpoints = value;
m_breakpoint_window->Show(value);
break;
}
case MENU_ID_WINDOW_MODULE:
{
const bool value = !m_config.data().show_modules;
m_config.data().show_modules = value;
m_module_window->Show(value);
break;
}
case MENU_ID_WINDOW_SYMBOL:
{
const bool value = !m_config.data().show_symbols;
m_config.data().show_symbols = value;
m_symbol_window->Show(value);
break;
}
default:
return;
}
m_config.Save();
}
void DebuggerWindow2::OnUpdateView(wxCommandEvent& event)
{
UpdateModuleLabel();
m_disasm_ctrl->OnUpdateView();
m_register_window->OnUpdateView();
m_breakpoint_window->OnUpdateView();
}
void DebuggerWindow2::OnExit(wxCommandEvent& event)
{
this->Close();
}
void DebuggerWindow2::OnShow(wxShowEvent& event)
{
m_register_window->Show();
m_dump_window->Show();
m_breakpoint_window->Show();
m_module_window->Show();
m_symbol_window->Show();
event.Skip();
}
void DebuggerWindow2::CreateMenuBar()
{
auto menu_bar = new wxMenuBar;
// file
wxMenu* file_menu = new wxMenu;
file_menu->Append(MENU_ID_FILE_EXIT, _("&Exit"));
file_menu->Bind(wxEVT_MENU, &DebuggerWindow2::OnExit, this);
menu_bar->Append(file_menu, _("&File"));
// options
wxMenu* options_menu = new wxMenu;
options_menu->Append(MENU_ID_OPTIONS_PIN_TO_MAINWINDOW, _("&Pin to main window"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().pin_to_main);
options_menu->Append(MENU_ID_OPTIONS_BREAK_ON_START, _("Break on &entry point"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().break_on_start);
menu_bar->Append(options_menu, _("&Options"));
// window
wxMenu* window_menu = new wxMenu;
window_menu->Append(MENU_ID_WINDOW_REGISTERS, _("&Registers"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().show_register);
window_menu->Append(MENU_ID_WINDOW_DUMP, _("&Memory Dump"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().show_dump);
window_menu->Append(MENU_ID_WINDOW_BREAKPOINTS, _("&Breakpoints"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().show_breakpoints);
window_menu->Append(MENU_ID_WINDOW_MODULE, _("Module&list"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().show_modules);
window_menu->Append(MENU_ID_WINDOW_SYMBOL, _("&Symbols"), wxEmptyString, wxITEM_CHECK)->Check(m_config.data().show_symbols);
menu_bar->Append(window_menu, _("&Window"));
SetMenuBar(menu_bar);
options_menu->Bind(wxEVT_MENU, &DebuggerWindow2::OnOptionsInput, this);
window_menu->Bind(wxEVT_MENU, &DebuggerWindow2::OnWindowMenu, this);
}
void DebuggerWindow2::UpdateModuleLabel(uint32 address)
{
if(address == 0)
address = m_disasm_ctrl->GetViewBaseAddress();
RPLModule* module = RPLLoader_FindModuleByCodeAddr(address);
if (module && m_module_address != module->regionMappingBase_text.GetMPTR())
{
m_module_label->SetLabel(wxString::Format("> %s", module->moduleName2.c_str()));
m_module_address = module->regionMappingBase_text.GetMPTR();
}
else if (address >= mmuRange_CODECAVE.getBase() && address < mmuRange_CODECAVE.getEnd())
{
m_module_label->SetLabel(wxString::Format("> %s", "Cemu codecave"));
m_module_address = mmuRange_CODECAVE.getBase();
}
}
| 22,094
|
C++
|
.cpp
| 560
| 37.119643
| 224
| 0.749837
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,007
|
DumpWindow.cpp
|
cemu-project_Cemu/src/gui/debugger/DumpWindow.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/DumpWindow.h"
#include "gui/debugger/DebuggerWindow2.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "gui/debugger/DumpCtrl.h"
enum
{
// REGISTER
REGISTER_ADDRESS_R0 = wxID_HIGHEST + 8200,
REGISTER_LABEL_R0 = REGISTER_ADDRESS_R0 + 32,
REGISTER_LABEL_FPR0_0 = REGISTER_LABEL_R0 + 32,
REGISTER_LABEL_FPR1_0 = REGISTER_LABEL_R0 + 32,
};
DumpWindow::DumpWindow(DebuggerWindow2& parent, const wxPoint& main_position, const wxSize& main_size)
: wxFrame(&parent, wxID_ANY, _("Memory Dump"), wxDefaultPosition, wxSize(600, 250), wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT)
{
this->wxWindowBase::SetBackgroundColour(*wxWHITE);
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
m_dump_ctrl = new DumpCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxScrolledWindowStyle);
main_sizer->Add(m_dump_ctrl, 1, wxEXPAND);
this->SetSizer(main_sizer);
this->wxWindowBase::Layout();
this->Centre(wxBOTH);
if (parent.GetConfig().data().pin_to_main)
OnMainMove(main_position, main_size);
}
void DumpWindow::OnMainMove(const wxPoint& main_position, const wxSize& main_size)
{
wxSize size(600, 250);
this->SetSize(size);
wxPoint position = main_position;
position.y += main_size.GetHeight();
this->SetPosition(position);
}
void DumpWindow::OnGameLoaded()
{
m_dump_ctrl->Init();
}
| 1,401
|
C++
|
.cpp
| 38
| 35.026316
| 173
| 0.762749
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,008
|
RegisterCtrl.cpp
|
cemu-project_Cemu/src/gui/debugger/RegisterCtrl.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/RegisterCtrl.h"
#include <sstream>
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "gui/debugger/DebuggerWindow2.h"
#define COLOR_DEBUG_ACTIVE_BP 0xFFFFA0FF
#define COLOR_DEBUG_ACTIVE 0xFFFFA080
#define COLOR_DEBUG_BP 0xFF8080FF
#define SYNTAX_COLOR_GPR 0xFF000066
#define SYNTAX_COLOR_FPR 0xFF006666
#define SYNTAX_COLOR_SPR 0xFF666600
#define SYNTAX_COLOR_CR 0xFF666600
#define SYNTAX_COLOR_IMM 0xFF006600
#define SYNTAX_COLOR_IMM_OFFSET 0xFF006600
#define SYNTAX_COLOR_CIMM 0xFF880000
#define SYNTAX_COLOR_PSEUDO 0xFFA0A0A0 // color for pseudo code
#define SYNTAX_COLOR_SYMBOL 0xFF0000A0 // color for function symbol
#define OFFSET_REGISTER (60)
#define OFFSET_REGISTER_LABEL (100)
#define OFFSET_FPR (120)
RegisterCtrl::RegisterCtrl(wxWindow* parent, const wxWindowID& id, const wxPoint& pos, const wxSize& size, long style)
: TextList(parent, id, pos, size, style), m_prev_snapshot({})
{
this->SetElementCount(32 + 1 + 32);
RefreshControl();
}
void RegisterCtrl::OnDraw(wxDC& dc, sint32 start, sint32 count, const wxPoint& start_position)
{
wxPoint position = start_position;
//RPLModule* current_rpl_module = rpl3_getModuleByCodeAddr(MEMORY_CODEAREA_ADDR + start);
for (sint32 i = 0; i <= count; i++)
{
const uint32 line = start + i;
if (line < 32)
{
dc.SetTextForeground(COLOR_BLACK);
dc.DrawText(wxString::Format("R%d", line), position);
position.x += OFFSET_REGISTER;
const uint32 register_value = debuggerState.debugSession.ppcSnapshot.gpr[line];
if(register_value != m_prev_snapshot.gpr[line])
dc.SetTextForeground(COLOR_RED);
else
dc.SetTextForeground(COLOR_BLACK);
dc.DrawText(wxString::Format("%08x", register_value), position);
position.x += OFFSET_REGISTER_LABEL;
// check if address is a code offset
RPLModule* code_module = RPLLoader_FindModuleByCodeAddr(register_value);
if (code_module)
dc.DrawText(wxString::Format("<%s> + %x", code_module->moduleName2.c_str(), register_value - code_module->regionMappingBase_text.GetMPTR()), position);
// check if address is a string
uint32 string_offset = register_value;
if (string_offset >= MEMORY_DATA_AREA_ADDR && string_offset < (MEMORY_DATA_AREA_ADDR+MEMORY_DATA_AREA_SIZE) )
{
bool is_valid_string = true;
std::stringstream buffer;
uint32 string_offset = register_value;
while (string_offset < (MEMORY_DATA_AREA_ADDR + MEMORY_DATA_AREA_SIZE))
{
const uint8 c = memory_readU8(string_offset++);
if (isprint(c))
{
buffer << c;
}
else if( c == '\0' )
{
buffer << c;
break;
}
else
{
is_valid_string = false;
break;
}
}
if(is_valid_string && buffer.tellp() > 1)
{
dc.DrawText(wxString::Format("s \"%s\"", buffer.str().c_str()), position);
}
else
{
// check for widestring
is_valid_string = true;
string_offset = register_value;
std::wstringstream wbuffer;
while (string_offset < (MEMORY_DATA_AREA_ADDR + MEMORY_DATA_AREA_SIZE))
{
const uint16 c = memory_readU16(string_offset);
string_offset += 2;
if (iswprint(c))
{
wbuffer << c;
}
else if (c == L'\0')
{
wbuffer << c;
break;
}
else
{
is_valid_string = false;
break;
}
}
if (is_valid_string && buffer.tellp() > 1)
{
dc.DrawText(wxString::Format(L"ws \"%s\"", wbuffer.str().c_str()), position);
}
}
}
}
else if( 32 + 1 <= line && line <= 32 + 1 + 32)
{
const uint32 register_index = line - 32 - 1;
dc.SetTextForeground(COLOR_BLACK);
dc.DrawText(wxString::Format("F0_%d", register_index), position);
position.x += OFFSET_REGISTER;
const uint64 fpr0_value = debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp0int;
if (fpr0_value != m_prev_snapshot.fpr[register_index].fp0int)
dc.SetTextForeground(COLOR_RED);
else
dc.SetTextForeground(COLOR_BLACK);
//dc.DrawText(wxString::Format("%016llx", fpr0_value), position);
dc.DrawText(wxString::Format("%lf", debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp0), position);
position.x += OFFSET_FPR;
dc.SetTextForeground(COLOR_BLACK);
dc.DrawText(wxString::Format("F1_%d", register_index), position);
position.x += OFFSET_REGISTER;
const uint64 fpr1_value = debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp1int;
if (fpr1_value != m_prev_snapshot.fpr[register_index].fp1int)
dc.SetTextForeground(COLOR_RED);
else
dc.SetTextForeground(COLOR_BLACK);
//dc.DrawText(wxString::Format("%016llx", fpr1_value), position);
dc.DrawText(wxString::Format("%lf", debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp1), position);
}
else
{
// empty line
}
NextLine(position, &start_position);
}
memcpy(&m_prev_snapshot, &debuggerState.debugSession.ppcSnapshot, sizeof(m_prev_snapshot));
}
void RegisterCtrl::OnMouseMove(const wxPoint& position, uint32 line)
{
if (!m_mouse_down)
return;
wxPoint pos = position;
if(pos.x <= OFFSET_REGISTER)
{
}
pos.x -= OFFSET_REGISTER;
if (pos.x <= OFFSET_REGISTER_LABEL)
{
}
pos.x -= OFFSET_REGISTER_LABEL;
}
void RegisterCtrl::OnMouseDClick(const wxPoint& position, uint32 line)
{
if (!debuggerState.debugSession.isTrapped)
return;
if(line < 32)
{
const uint32 register_index = line;
if (position.x <= OFFSET_REGISTER + OFFSET_REGISTER_LABEL)
{
const uint32 register_value = debuggerState.debugSession.ppcSnapshot.gpr[register_index];
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set R%d value", register_index)), wxString::Format("%08x", register_value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const uint32 new_value = std::stoul(set_value_dialog.GetValue().ToStdString(), nullptr, 16);
debuggerState.debugSession.hCPU->gpr[register_index] = new_value;
debuggerState.debugSession.ppcSnapshot.gpr[register_index] = new_value;
wxRect update_rect(0, line * m_line_height, GetSize().x, m_line_height);
RefreshControl(&update_rect);
}
}
}
// one line empty between = line 32
else if (32 + 1 <= line && line <= 32 + 1 + 32)
{
const uint32 register_index = line - 32 - 1;
if (position.x <= OFFSET_REGISTER + OFFSET_FPR)
{
const double register_value = debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp0;
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set FP0_%d value", register_index)), wxString::Format("%lf", register_value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const double new_value = std::stod(set_value_dialog.GetValue().ToStdString());
debuggerState.debugSession.hCPU->fpr[register_index].fp0 = new_value;
debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp0 = new_value;
wxRect update_rect(0, line * m_line_height, GetSize().x, m_line_height);
RefreshControl(&update_rect);
}
}
else
{
const double register_value = debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp1;
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set FP1_%d value", register_index)), wxString::Format("%lf", register_value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const double new_value = std::stod(set_value_dialog.GetValue().ToStdString());
debuggerState.debugSession.hCPU->fpr[register_index].fp1 = new_value;
debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp1 = new_value;
wxRect update_rect(0, line * m_line_height, GetSize().x, m_line_height);
RefreshControl(&update_rect);
}
}
}
}
void RegisterCtrl::OnGameLoaded()
{
RefreshControl();
}
| 7,902
|
C++
|
.cpp
| 216
| 32.592593
| 167
| 0.699765
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,009
|
SymbolCtrl.cpp
|
cemu-project_Cemu/src/gui/debugger/SymbolCtrl.cpp
|
#include "gui/debugger/SymbolCtrl.h"
#include "gui/guiWrapper.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
enum ItemColumns
{
ColumnName = 0,
ColumnAddress,
ColumnModule,
};
SymbolListCtrl::SymbolListCtrl(wxWindow* parent, const wxWindowID& id, const wxPoint& pos, const wxSize& size) :
wxListCtrl(parent, id, pos, size, wxLC_REPORT | wxLC_VIRTUAL)
{
wxListItem col0;
col0.SetId(ColumnName);
col0.SetText(_("Name"));
col0.SetWidth(200);
InsertColumn(ColumnName, col0);
wxListItem col1;
col1.SetId(ColumnAddress);
col1.SetText(_("Address"));
col1.SetWidth(75);
col1.SetAlign(wxLIST_FORMAT_RIGHT);
InsertColumn(ColumnAddress, col1);
wxListItem col2;
col2.SetId(ColumnModule);
col2.SetText(_("Module"));
col2.SetWidth(75);
col2.SetAlign(wxLIST_FORMAT_RIGHT);
InsertColumn(ColumnModule, col2);
Bind(wxEVT_LIST_ITEM_ACTIVATED, &SymbolListCtrl::OnLeftDClick, this);
Bind(wxEVT_LIST_ITEM_RIGHT_CLICK, &SymbolListCtrl::OnRightClick, this);
m_list_filter.Clear();
OnGameLoaded();
SetItemCount(m_data.size());
}
void SymbolListCtrl::OnGameLoaded()
{
m_data.clear();
const auto symbol_map = rplSymbolStorage_lockSymbolMap();
for (auto const& [address, symbol_info] : symbol_map)
{
if (symbol_info == nullptr || symbol_info->symbolName == nullptr)
continue;
wxString libNameWX = wxString::FromAscii((const char*)symbol_info->libName);
wxString symbolNameWX = wxString::FromAscii((const char*)symbol_info->symbolName);
wxString searchNameWX = libNameWX + symbolNameWX;
searchNameWX.MakeLower();
auto new_entry = m_data.try_emplace(
symbol_info->address,
symbolNameWX,
libNameWX,
searchNameWX,
false
);
if (m_list_filter.IsEmpty())
new_entry.first->second.visible = true;
else if (new_entry.first->second.searchName.Contains(m_list_filter))
new_entry.first->second.visible = true;
}
rplSymbolStorage_unlockSymbolMap();
SetItemCount(m_data.size());
if (m_data.size() > 0)
RefreshItems(GetTopItem(), std::min<long>(m_data.size() - 1, GetTopItem() + GetCountPerPage() + 1));
}
wxString SymbolListCtrl::OnGetItemText(long item, long column) const
{
if (item >= GetItemCount())
return wxEmptyString;
long visible_idx = 0;
for (const auto& [address, symbol] : m_data)
{
if (!symbol.visible)
continue;
if (item == visible_idx)
{
if (column == ColumnName)
return wxString(symbol.name);
if (column == ColumnAddress)
return wxString::Format("%08x", address);
if (column == ColumnModule)
return wxString(symbol.libName);
}
visible_idx++;
}
return wxEmptyString;
}
void SymbolListCtrl::OnLeftDClick(wxListEvent& event)
{
long selected = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (selected == -1)
return;
const auto text = GetItemText(selected, ColumnAddress);
const auto address = std::stoul(text.ToStdString(), nullptr, 16);
if (address == 0)
return;
debuggerState.debugSession.instructionPointer = address;
debuggerWindow_moveIP();
}
void SymbolListCtrl::OnRightClick(wxListEvent& event)
{
long selected = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (selected == -1)
return;
auto text = GetItemText(selected, ColumnAddress);
text = "0x" + text;
#if BOOST_OS_WINDOWS
if (OpenClipboard(nullptr))
{
EmptyClipboard();
const HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, text.size()+1);
if (hGlobal)
{
memcpy(GlobalLock(hGlobal), text.c_str(), text.size() + 1);
GlobalUnlock(hGlobal);
SetClipboardData(CF_TEXT, hGlobal);
GlobalFree(hGlobal);
}
CloseClipboard();
}
#endif
}
void SymbolListCtrl::ChangeListFilter(std::string filter)
{
m_list_filter = wxString(filter).MakeLower();
size_t visible_entries = m_data.size();
for (auto& [address, symbol] : m_data)
{
if (m_list_filter.IsEmpty())
symbol.visible = true;
else if (symbol.searchName.Contains(m_list_filter))
symbol.visible = true;
else
{
visible_entries--;
symbol.visible = false;
}
}
SetItemCount(visible_entries);
if (visible_entries > 0)
RefreshItems(GetTopItem(), std::min<long>(visible_entries - 1, GetTopItem() + GetCountPerPage() + 1));
}
| 4,195
|
C++
|
.cpp
| 142
| 26.859155
| 112
| 0.733317
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,010
|
DisasmCtrl.cpp
|
cemu-project_Cemu/src/gui/debugger/DisasmCtrl.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/DisasmCtrl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "Cafe/OS/RPL/rpl_debug_symbols.h"
#include "Cemu/PPCAssembler/ppcAssembler.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "gui/debugger/DebuggerWindow2.h"
#include "util/helpers/helpers.h"
#include "gui/guiWrapper.h"
#include "Cemu/ExpressionParser/ExpressionParser.h"
#include "Cafe/HW/Espresso/Debugger/DebugSymbolStorage.h"
#include <wx/mstream.h> // for wxMemoryInputStream
#define MAX_SYMBOL_LEN (120)
#define COLOR_DEBUG_ACTIVE_BP 0xFFFFA0FF
#define COLOR_DEBUG_ACTIVE 0xFFFFA080
#define COLOR_DEBUG_BP 0xFF8080FF
#define SYNTAX_COLOR_GPR 0xFF000066
#define SYNTAX_COLOR_FPR 0xFF006666
#define SYNTAX_COLOR_SPR 0xFF666600
#define SYNTAX_COLOR_CR 0xFF666600
#define SYNTAX_COLOR_IMM 0xFF006600
#define SYNTAX_COLOR_IMM_OFFSET 0xFF006600
#define SYNTAX_COLOR_CIMM 0xFF880000
#define SYNTAX_COLOR_PSEUDO 0xFFA0A0A0 // color for pseudo code
#define SYNTAX_COLOR_SYMBOL 0xFF0000A0 // color for function symbol
#define OFFSET_ADDRESS (60)
#define OFFSET_ADDRESS_RELATIVE (90)
#define OFFSET_DISASSEMBLY (300)
#define OFFSET_DISASSEMBLY_OPERAND (80)
wxBitmap* g_ipArrowBitmap = nullptr;
uint8 _arrowRightPNG[] =
{
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0B,
0x08, 0x03, 0x00, 0x00, 0x00, 0x41, 0x3C, 0xFD, 0x0B, 0x00, 0x00, 0x00,
0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xAE, 0xCE, 0x1C, 0xE9, 0x00, 0x00,
0x00, 0x04, 0x67, 0x41, 0x4D, 0x41, 0x00, 0x00, 0xB1, 0x8F, 0x0B, 0xFC,
0x61, 0x05, 0x00, 0x00, 0x00, 0x06, 0x50, 0x4C, 0x54, 0x45, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xA5, 0x67, 0xB9, 0xCF, 0x00, 0x00, 0x00, 0x02,
0x74, 0x52, 0x4E, 0x53, 0xFF, 0x00, 0xE5, 0xB7, 0x30, 0x4A, 0x00, 0x00,
0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0E, 0xC3, 0x00, 0x00,
0x0E, 0xC3, 0x01, 0xC7, 0x6F, 0xA8, 0x64, 0x00, 0x00, 0x00, 0x2C, 0x49,
0x44, 0x41, 0x54, 0x18, 0x57, 0x63, 0x60, 0x84, 0x03, 0x08, 0x13, 0x59,
0x00, 0xCC, 0x46, 0x11, 0x00, 0x71, 0x80, 0x24, 0x32, 0xC0, 0x10, 0x60,
0xC0, 0x10, 0xC0, 0x00, 0x58, 0xCC, 0x80, 0xD8, 0x00, 0x02, 0x60, 0x3E,
0x7E, 0x77, 0x00, 0x31, 0x23, 0x23, 0x00, 0x21, 0x95, 0x00, 0x5B, 0x20,
0x73, 0x8D, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
0x42, 0x60, 0x82
};
DisasmCtrl::DisasmCtrl(wxWindow* parent, const wxWindowID& id, const wxPoint& pos, const wxSize& size, long style)
: TextList(parent, id, pos, size, style), m_mouse_line(-1), m_mouse_line_drawn(-1), m_active_line(-1)
{
Init();
if (!g_ipArrowBitmap)
{
wxMemoryInputStream strm(_arrowRightPNG, sizeof(_arrowRightPNG));
wxImage img(strm, wxBITMAP_TYPE_PNG);
g_ipArrowBitmap = new wxBitmap(img);
}
auto tooltip_sizer = new wxBoxSizer(wxVERTICAL);
tooltip_sizer->Add(new wxStaticText(m_tooltip_window, wxID_ANY, wxEmptyString), 0, wxALL, 5);
m_tooltip_window->SetSizer(tooltip_sizer);
}
void DisasmCtrl::Init()
{
SelectCodeRegion(mmuRange_TEXT_AREA.getBase());
}
void DisasmCtrl::SelectCodeRegion(uint32 newAddress)
{
if (newAddress >= mmuRange_TEXT_AREA.getBase() && newAddress < mmuRange_TEXT_AREA.getEnd())
{
currentCodeRegionStart = MEMORY_CODEAREA_ADDR;
currentCodeRegionEnd = RPLLoader_GetMaxCodeOffset();
currentCodeRegionEnd = std::max(currentCodeRegionEnd, currentCodeRegionStart + 0x1000);
}
MMURange* mmuRange = memory_getMMURangeByAddress(newAddress);
if (mmuRange)
{
currentCodeRegionStart = mmuRange->getBase();
currentCodeRegionEnd = mmuRange->getEnd();
}
else
{
currentCodeRegionStart = 0;
currentCodeRegionEnd = 0;
}
// update line tracking
sint32 element_count = currentCodeRegionEnd - currentCodeRegionStart;
if (element_count <= 0x00010000)
element_count = 0x00010000;
if (this->SetElementCount(element_count / 4))
{
Scroll(0, 0);
RefreshControl();
}
}
void DisasmCtrl::DrawDisassemblyLine(wxDC& dc, const wxPoint& linePosition, MPTR virtualAddress, RPLModule* rplModule)
{
wxPoint position = linePosition;
bool hasPatch = debugger_hasPatch(virtualAddress);
PPCDisassembledInstruction disasmInstr;
const DebuggerBreakpoint* bp = debugger_getFirstBP(virtualAddress);
while (bp)
{
if (bp->isExecuteBP() && bp->enabled)
break;
bp = bp->next;
}
uint32 opcode;
if (bp)
opcode = bp->originalOpcodeValue;
else
opcode = memory_readU32(virtualAddress);
ppcAssembler_disassemble(virtualAddress, opcode, &disasmInstr);
const bool is_active_bp = debuggerState.debugSession.isTrapped && debuggerState.debugSession.instructionPointer == virtualAddress;
// write virtual address
wxColour background_colour;
if (is_active_bp && bp != nullptr)
background_colour = wxColour(0xFFFFA0FF);
else if (is_active_bp)
background_colour = wxColour(0xFF80A0FF);
else if (bp != nullptr)
background_colour = wxColour(bp->bpType == DEBUGGER_BP_T_NORMAL ? 0xFF8080FF : 0x80FFFFFF);
else if(virtualAddress == m_lastGotoTarget)
background_colour = wxColour(0xFFE0E0E0);
else
background_colour = wxColour(COLOR_WHITE);
DrawLineBackground(dc, position, background_colour);
dc.SetTextForeground(COLOR_BLACK);
dc.DrawText(wxString::Format("%08x", virtualAddress), position);
position.x += OFFSET_ADDRESS;
dc.SetTextForeground(COLOR_GREY);
if (rplModule)
dc.DrawText(wxString::Format("+0x%-8x", virtualAddress - rplModule->regionMappingBase_text.GetMPTR()), position);
else
dc.DrawText("???", position);
position.x += OFFSET_ADDRESS_RELATIVE;
// draw arrow to clearly indicate instruction pointer
if(is_active_bp)
dc.DrawBitmap(*g_ipArrowBitmap, wxPoint(position.x - 24, position.y + 2), false);
// handle data symbols
auto debugSymbolDataType = DebugSymbolStorage::GetDataType(virtualAddress);
if (debugSymbolDataType == DEBUG_SYMBOL_TYPE::FLOAT)
{
dc.SetTextForeground(hasPatch ? wxColour(0xFF2020FF) : wxColour(0xFF400000));
dc.DrawText(fmt::format(".float"), position);
position.x += OFFSET_DISASSEMBLY_OPERAND;
dc.SetTextForeground(hasPatch ? wxColour(0xFF2020FF) : wxColour(SYNTAX_COLOR_IMM));
dc.DrawText(fmt::format("{}", memory_readFloat(virtualAddress)), position);
return;
}
else if (debugSymbolDataType == DEBUG_SYMBOL_TYPE::U32)
{
dc.SetTextForeground(hasPatch ? wxColour(0xFF2020FF) : wxColour(0xFF400000));
dc.DrawText(fmt::format(".uint"), position);
position.x += OFFSET_DISASSEMBLY_OPERAND;
dc.SetTextForeground(hasPatch ? wxColour(0xFF2020FF) : wxColour(SYNTAX_COLOR_IMM));
dc.DrawText(fmt::format("{}", memory_readU32(virtualAddress)), position);
return;
}
sint32 start_width = position.x;
dc.SetTextForeground(hasPatch ? wxColour(0xFF2020FF) : wxColour(0xFF400000));
char opName[32];
strcpy(opName, ppcAssembler_getInstructionName(disasmInstr.ppcAsmCode));
std::transform(opName, opName + sizeof(opName), opName, tolower);
dc.DrawText(wxString::Format("%-12s", opName), position);
position.x += OFFSET_DISASSEMBLY_OPERAND;
bool isRLWINM = disasmInstr.ppcAsmCode == PPCASM_OP_RLWINM || disasmInstr.ppcAsmCode == PPCASM_OP_RLWINM_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_CLRLWI || disasmInstr.ppcAsmCode == PPCASM_OP_CLRLWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_CLRRWI || disasmInstr.ppcAsmCode == PPCASM_OP_CLRRWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_EXTLWI || disasmInstr.ppcAsmCode == PPCASM_OP_EXTLWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_EXTRWI || disasmInstr.ppcAsmCode == PPCASM_OP_EXTRWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_SLWI || disasmInstr.ppcAsmCode == PPCASM_OP_SLWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_SRWI || disasmInstr.ppcAsmCode == PPCASM_OP_SRWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_ROTRWI || disasmInstr.ppcAsmCode == PPCASM_OP_ROTRWI_ ||
disasmInstr.ppcAsmCode == PPCASM_OP_ROTLWI || disasmInstr.ppcAsmCode == PPCASM_OP_ROTLWI_;
bool forceDecDisplay = isRLWINM;
if (disasmInstr.ppcAsmCode == PPCASM_OP_UKN)
{
// show raw bytes
WriteText(dc, wxString::Format("%02x %02x %02x %02x", (opcode >> 24) & 0xFF, (opcode >> 16) & 0xFF, (opcode >> 8) & 0xFF, (opcode >> 0) & 0xFF), position, SYNTAX_COLOR_PSEUDO);
}
bool is_first_operand = true;
for (sint32 o = 0; o < PPCASM_OPERAND_COUNT; o++)
{
if (((disasmInstr.operandMask >> o) & 1) == 0)
continue;
if (!is_first_operand)
WriteText(dc, ", ", position, COLOR_BLACK);
is_first_operand = false;
switch (disasmInstr.operand[o].type)
{
case PPCASM_OPERAND_TYPE_GPR:
WriteText(dc, wxString::Format("r%d", disasmInstr.operand[o].registerIndex), position, SYNTAX_COLOR_GPR);
break;
case PPCASM_OPERAND_TYPE_FPR:
WriteText(dc, wxString::Format("f%d", disasmInstr.operand[o].registerIndex), position, SYNTAX_COLOR_FPR);
break;
case PPCASM_OPERAND_TYPE_SPR:
WriteText(dc, wxString::Format("spr%d", disasmInstr.operand[o].registerIndex), position, SYNTAX_COLOR_SPR);
break;
case PPCASM_OPERAND_TYPE_CR:
WriteText(dc, wxString::Format("cr%d", disasmInstr.operand[o].registerIndex), position, SYNTAX_COLOR_CR);
break;
case PPCASM_OPERAND_TYPE_IMM:
{
wxString string;
if (disasmInstr.operand[o].isSignedImm)
{
sint32 sImm = disasmInstr.operand[o].immS32;
if (disasmInstr.operand[o].immWidth == 16 && (sImm & 0x8000))
sImm |= (sint32)0xFFFF0000;
if ((sImm > -10 && sImm < 10) || forceDecDisplay)
string = wxString::Format("%d", sImm);
else
{
if (sImm < 0)
string = wxString::Format("-0x%x", -sImm);
else
string = wxString::Format("0x%x", sImm);
}
}
else
{
uint32 uImm = disasmInstr.operand[o].immS32;
if ((uImm >= 0 && uImm < 10) || forceDecDisplay)
string = wxString::Format("%u", uImm);
else
string = wxString::Format("0x%x", uImm);
}
WriteText(dc, string, position, SYNTAX_COLOR_IMM);
break;
}
case PPCASM_OPERAND_TYPE_PSQMODE:
{
if (disasmInstr.operand[o].immS32)
WriteText(dc, "single", position, SYNTAX_COLOR_IMM);
else
WriteText(dc, "paired", position, SYNTAX_COLOR_IMM);
break;
}
case PPCASM_OPERAND_TYPE_CIMM:
{
wxString string;
// use symbol for function calls if available
uint32 callDest = disasmInstr.operand[o].immU32;
RPLStoredSymbol* storedSymbol = nullptr;
if (disasmInstr.ppcAsmCode == PPCASM_OP_BL || disasmInstr.ppcAsmCode == PPCASM_OP_BLA)
storedSymbol = rplSymbolStorage_getByAddress(callDest);
if (storedSymbol)
{
// if symbol is within same module then don't display libname prefix
RPLModule* rplModuleCurrent = RPLLoader_FindModuleByCodeAddr(virtualAddress); // cache this
if (rplModuleCurrent && callDest >= rplModuleCurrent->regionMappingBase_text.GetMPTR() && callDest < (rplModuleCurrent->regionMappingBase_text.GetMPTR() + rplModuleCurrent->regionSize_text))
string = wxString((char*)storedSymbol->symbolName);
else
string = wxString::Format("%s.%s", (char*)storedSymbol->libName, (char*)storedSymbol->symbolName);
// truncate name after 36 characters
if (string.Length() >= 36)
{
string.Truncate(34);
string.Append("..");
}
}
else
{
string = wxString::Format("0x%08x", disasmInstr.operand[o].immU32);
}
WriteText(dc, string, position, SYNTAX_COLOR_CIMM);
if (disasmInstr.ppcAsmCode != PPCASM_OP_BL)
{
wxString x = wxString(" ");
if (callDest <= virtualAddress)
x.Append(wxUniChar(0x2191)); // arrow up
else
x.Append(wxUniChar(0x2193)); // arrow down
WriteText(dc, x, position, COLOR_BLACK);
}
break;
}
case PPCASM_OPERAND_TYPE_MEM:
{
// offset
wxString string;
if (disasmInstr.operand[o].isSignedImm && disasmInstr.operand[o].immS32 >= 0)
string = wxString::Format("+0x%x", disasmInstr.operand[o].immS32);
else
string = wxString::Format("-0x%x", -disasmInstr.operand[o].immS32);
WriteText(dc, string, position, SYNTAX_COLOR_IMM_OFFSET);
WriteText(dc, "(", position, COLOR_BLACK);
// register
WriteText(dc, wxString::Format("r%d", disasmInstr.operand[o].registerIndex), position, SYNTAX_COLOR_GPR);
WriteText(dc, ")", position, COLOR_BLACK);
break;
}
default:
// TODO
WriteText(dc, "<TODO>", position, wxColour(0xFF444444));
}
}
position.x = start_width + OFFSET_DISASSEMBLY;
const auto comment = static_cast<rplDebugSymbolComment*>(rplDebugSymbol_getForAddress(virtualAddress));
if (comment && comment->type == RplDebugSymbolComment)
WriteText(dc, comment->comment, position, COLOR_BLACK);
else if (isRLWINM)
{
sint32 rS, rA, SH, MB, ME;
rS = (opcode >> 21) & 0x1f;
rA = (opcode >> 16) & 0x1f;
SH = (opcode >> 11) & 0x1f;
MB = (opcode >> 6) & 0x1f;
ME = (opcode >> 1) & 0x1f;
uint32 mask = ppcAssembler_generateMaskRLW(MB, ME);
wxString string;
if (SH == 0)
string = wxString::Format("r%d=r%d&0x%x", rA, rS, mask);
else if ((0xFFFFFFFF << (uint32)disasmInstr.operand[2].immS32) == mask)
string = wxString::Format("r%d=r%d<<%d", rA, rS, SH);
else if ((0xFFFFFFFF >> (32 - SH) == mask))
string = wxString::Format("r%d=r%d>>%d", rA, rS, 32 - SH);
else
string = wxString::Format("r%d=(r%d<<<%d)&0x%x", rA, rS, SH, mask);
WriteText(dc, string, position, COLOR_GREY);
}
else if (disasmInstr.ppcAsmCode == PPCASM_OP_SUBF || disasmInstr.ppcAsmCode == PPCASM_OP_SUBF_)
{
sint32 rD, rA, rB;
rD = (opcode >> 21) & 0x1f;
rA = (opcode >> 16) & 0x1f;
rB = (opcode >> 11) & 0x1f;
wxString string;
string = wxString::Format("r%d=r%d-r%d", rD, rB, rA);
WriteText(dc, string, position, COLOR_GREY);
}
}
void DisasmCtrl::DrawLabelName(wxDC& dc, const wxPoint& linePosition, MPTR virtualAddress, RPLStoredSymbol* storedSymbol)
{
wxString symbol_string = wxString::Format("%s:", (char*)storedSymbol->symbolName);
if (symbol_string.Length() > MAX_SYMBOL_LEN)
{
symbol_string.Truncate(MAX_SYMBOL_LEN - 3);
symbol_string.Append("..:");
}
wxPoint tmpPos(linePosition);
WriteText(dc, symbol_string, tmpPos, SYNTAX_COLOR_SYMBOL);
}
void DisasmCtrl::OnDraw(wxDC& dc, sint32 start, sint32 count, const wxPoint& start_position)
{
wxPoint position(0, 0);
RPLModule* current_rpl_module = RPLLoader_FindModuleByCodeAddr(GetViewBaseAddress());
if (currentCodeRegionStart == currentCodeRegionEnd)
return;
sint32 viewFirstLine = GetViewStart().y;
sint32 lineOffset = start - viewFirstLine;
cemu_assert_debug(lineOffset >= 0);
sint32 instructionIndex = 0;
sint32 numLinesToUpdate = lineOffset + count;
numLinesToUpdate = std::min(numLinesToUpdate, (sint32)m_elements_visible);
if(m_lineToAddress.size() != m_elements_visible)
m_lineToAddress.resize(m_elements_visible);
sint32 lineIndex = 0;
while(lineIndex < numLinesToUpdate)
{
const uint32 virtualAddress = GetViewBaseAddress() + instructionIndex * 4;
instructionIndex++;
if (virtualAddress < currentCodeRegionStart ||
virtualAddress >= currentCodeRegionEnd)
{
NextLine(position, &start_position);
m_lineToAddress[lineIndex] = std::nullopt;
lineIndex++;
continue;
}
// check if valid memory address
if (!memory_isAddressRangeAccessible(virtualAddress, 4))
{
NextLine(position, &start_position);
m_lineToAddress[lineIndex] = std::nullopt;
lineIndex++;
continue;
}
// draw symbol as label
RPLStoredSymbol* storedSymbol = rplSymbolStorage_getByAddress(virtualAddress);
if (storedSymbol)
{
if(lineIndex >= lineOffset)
DrawLabelName(dc, position, virtualAddress, storedSymbol);
m_lineToAddress[lineIndex] = virtualAddress;
lineIndex++;
if (lineIndex >= numLinesToUpdate)
break;
NextLine(position, &start_position);
}
m_lineToAddress[lineIndex] = virtualAddress;
if (lineIndex >= lineOffset)
DrawDisassemblyLine(dc, position, virtualAddress, current_rpl_module);
NextLine(position, &start_position);
lineIndex++;
}
// draw vertical separator lines: offset | disassembly | comment
dc.SetPen(*wxLIGHT_GREY_PEN);
wxPoint line_from = start_position;
line_from.x = OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE - 5;
wxPoint line_to = line_from;
line_to.y += (count + 1) * m_line_height;
dc.DrawLine(line_from, line_to);
line_from.x += OFFSET_DISASSEMBLY;
line_to.x += OFFSET_DISASSEMBLY;
dc.DrawLine(line_from, line_to);
}
void DisasmCtrl::OnMouseMove(const wxPoint& start_position, uint32 line)
{
/*m_mouse_line = line;
if (m_mouse_line_drawn != -1)
RefreshLine(m_mouse_line_drawn);
if (m_mouse_line != -1)
RefreshLine(m_mouse_line);*/
wxPoint position = start_position;
// address
if (position.x <= OFFSET_ADDRESS)
{
return;
}
position.x -= OFFSET_ADDRESS;
// relative offset
if (position.x <= OFFSET_ADDRESS_RELATIVE)
{
return;
}
position.x -= OFFSET_ADDRESS_RELATIVE;
// disassembly code
if (position.x <= OFFSET_DISASSEMBLY)
{
if(m_mouse_down)
{
}
if (position.x <= OFFSET_DISASSEMBLY_OPERAND)
{
return;
}
position.x -= OFFSET_DISASSEMBLY_OPERAND;
}
}
void DisasmCtrl::OnKeyPressed(sint32 key_code, const wxPoint& position)
{
auto optVirtualAddress = LinePixelPosToAddress(position.y);
switch (key_code)
{
case WXK_F9:
{
if (optVirtualAddress)
{
debugger_toggleExecuteBreakpoint(*optVirtualAddress);
wxCommandEvent evt(wxEVT_BREAKPOINT_CHANGE);
wxPostEvent(this->m_parent, evt);
}
return;
}
case 'G':
{
if(IsKeyDown(WXK_CONTROL))
{
GoToAddressDialog();
return;
}
}
}
// debugger currently in break state
if (debuggerState.debugSession.isTrapped)
{
switch (key_code)
{
case WXK_F5:
{
debuggerState.debugSession.run = true;
return;
}
case WXK_F10:
{
debuggerState.debugSession.stepOver = true;
return;
}
case WXK_F11:
{
debuggerState.debugSession.stepInto = true;
}
}
}
else
{
switch (key_code)
{
case WXK_F5:
{
debuggerState.debugSession.shouldBreak = true;
}
}
}
}
void DisasmCtrl::OnMouseDClick(const wxPoint& position, uint32 line)
{
wxPoint pos = position;
auto optVirtualAddress = LinePixelPosToAddress(position.y - GetViewStart().y * m_line_height);
if (!optVirtualAddress)
return;
MPTR virtualAddress = *optVirtualAddress;
// address
if (pos.x <= OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE)
{
// address + address relative
debugger_toggleExecuteBreakpoint(virtualAddress);
RefreshLine(line);
wxCommandEvent evt(wxEVT_BREAKPOINT_CHANGE);
wxPostEvent(this->m_parent, evt);
return;
}
else if (pos.x <= OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE + OFFSET_DISASSEMBLY)
{
// double-clicked on disassembly (operation and operand data)
wxString currentInstruction = wxEmptyString;
wxTextEntryDialog set_value_dialog(this, _("Enter a new instruction."), _(wxString::Format("Overwrite instruction at address %08x", virtualAddress)), currentInstruction);
if (set_value_dialog.ShowModal() == wxID_OK)
{
PPCAssemblerInOut ctx = { 0 };
ctx.virtualAddress = virtualAddress;
if (ppcAssembler_assembleSingleInstruction(set_value_dialog.GetValue().c_str(), &ctx))
{
debugger_createPatch(virtualAddress, { ctx.outputData.data(), ctx.outputData.size() });
RefreshLine(line);
}
}
return;
}
else
{
// comment
const auto comment = static_cast<rplDebugSymbolComment*>(rplDebugSymbol_getForAddress(virtualAddress));
wxString old_comment = wxEmptyString;
if (comment && comment->type == RplDebugSymbolComment)
old_comment = comment->comment;
wxTextEntryDialog set_value_dialog(this, _("Enter a new comment."), _(wxString::Format("Create comment at address %08x", virtualAddress)), old_comment);
if (set_value_dialog.ShowModal() == wxID_OK)
{
rplDebugSymbol_createComment(virtualAddress, set_value_dialog.GetValue().wc_str());
RefreshLine(line);
}
return;
}
}
void DisasmCtrl::CopyToClipboard(std::string text) {
#if BOOST_OS_WINDOWS
if (OpenClipboard(nullptr))
{
EmptyClipboard();
const HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, text.size() + 1);
if (hGlobal)
{
memcpy(GlobalLock(hGlobal), text.c_str(), text.size() + 1);
GlobalUnlock(hGlobal);
SetClipboardData(CF_TEXT, hGlobal);
GlobalFree(hGlobal);
}
CloseClipboard();
}
#endif
}
void DisasmCtrl::OnContextMenu(const wxPoint& position, uint32 line)
{
wxPoint pos = position;
auto optVirtualAddress = LinePixelPosToAddress(position.y - GetViewStart().y * m_line_height);
if (!optVirtualAddress)
return;
MPTR virtualAddress = *optVirtualAddress;
// address
if (pos.x <= OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE)
{
CopyToClipboard(fmt::format("{:#10x}", virtualAddress));
return;
}
else if (pos.x <= OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE + OFFSET_DISASSEMBLY)
{
// double-clicked on disassembly (operation and operand data)
return;
}
else
{
// comment
return;
}
}
bool DisasmCtrl::OnShowTooltip(const wxPoint& position, uint32 line)
{
return false;
}
void DisasmCtrl::ScrollWindow(int dx, int dy, const wxRect* prect)
{
// scroll and repaint everything
RefreshControl(nullptr);
TextList::ScrollWindow(dx, dy, nullptr);
}
wxSize DisasmCtrl::DoGetBestSize() const
{
return TextList::DoGetBestSize();
}
void DisasmCtrl::OnUpdateView()
{
RefreshControl();
}
uint32 DisasmCtrl::GetViewBaseAddress() const
{
if (GetViewStart().y < 0)
return MPTR_NULL;
return currentCodeRegionStart + GetViewStart().y * 4;
}
std::optional<MPTR> DisasmCtrl::LinePixelPosToAddress(sint32 posY)
{
if (posY < 0)
return std::nullopt;
sint32 lineIndex = posY / m_line_height;
if (lineIndex >= m_lineToAddress.size())
return std::nullopt;
return m_lineToAddress[lineIndex];
}
uint32 DisasmCtrl::AddressToScrollPos(uint32 offset) const
{
return (offset - currentCodeRegionStart) / 4;
}
void DisasmCtrl::CenterOffset(uint32 offset)
{
if (offset < currentCodeRegionStart || offset >= currentCodeRegionEnd)
SelectCodeRegion(offset);
const sint32 line = AddressToScrollPos(offset);
if (line < 0 || line >= (sint32)m_element_count)
return;
if (m_active_line != -1)
RefreshLine(m_active_line);
DoScroll(0, std::max(0, line - (sint32)(m_elements_visible / 2)));
m_active_line = line;
RefreshLine(m_active_line);
debug_printf("scroll to %x\n", debuggerState.debugSession.instructionPointer);
}
void DisasmCtrl::GoToAddressDialog()
{
wxTextEntryDialog goto_dialog(this, _("Enter a target address."), _("GoTo address"), wxEmptyString);
if (goto_dialog.ShowModal() == wxID_OK)
{
ExpressionParser parser;
auto value = goto_dialog.GetValue().ToStdString();
std::transform(value.begin(), value.end(), value.begin(), tolower);
debugger_addParserSymbols(parser);
// try to parse expression as hex value first (it should interpret 1234 as 0x1234, not 1234)
if (parser.IsConstantExpression("0x"+value))
{
const auto result = (uint32)parser.Evaluate("0x"+value);
m_lastGotoTarget = result;
CenterOffset(result);
}
else if (parser.IsConstantExpression(value))
{
const auto result = (uint32)parser.Evaluate(value);
m_lastGotoTarget = result;
CenterOffset(result);
}
else
{
try
{
const auto _ = (uint32)parser.Evaluate(value);
}
catch (const std::exception& ex)
{
wxMessageBox(ex.what(), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this);
}
}
}
}
| 23,253
|
C++
|
.cpp
| 678
| 31.367257
| 194
| 0.72701
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,011
|
SymbolWindow.cpp
|
cemu-project_Cemu/src/gui/debugger/SymbolWindow.cpp
|
#include "gui/wxgui.h"
#include "gui/guiWrapper.h"
#include "gui/debugger/SymbolWindow.h"
#include "gui/debugger/DebuggerWindow2.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
enum ItemColumns
{
ColumnName = 0,
ColumnAddress,
ColumnModule,
};
SymbolWindow::SymbolWindow(DebuggerWindow2& parent, const wxPoint& main_position, const wxSize& main_size)
: wxFrame(&parent, wxID_ANY, _("Symbols"), wxDefaultPosition, wxSize(600, 250), wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT)
{
this->wxWindowBase::SetBackgroundColour(*wxWHITE);
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
m_symbol_ctrl = new SymbolListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize);
main_sizer->Add(m_symbol_ctrl, 1, wxEXPAND);
m_filter = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_NO_VSCROLL);
m_filter->Bind(wxEVT_TEXT, &SymbolWindow::OnFilterChanged, this);
main_sizer->Add(m_filter, 0, wxALL | wxEXPAND, 5);
this->SetSizer(main_sizer);
this->wxWindowBase::Layout();
this->Centre(wxHORIZONTAL);
if (parent.GetConfig().data().pin_to_main)
OnMainMove(main_position, main_size);
}
void SymbolWindow::OnMainMove(const wxPoint& main_position, const wxSize& main_size)
{
wxSize size(420, 250);
this->SetSize(size);
wxPoint position = main_position;
position.x -= 420;
this->SetPosition(position);
}
void SymbolWindow::OnGameLoaded()
{
m_symbol_ctrl->OnGameLoaded();
}
void SymbolWindow::OnFilterChanged(wxCommandEvent& event)
{
m_symbol_ctrl->ChangeListFilter(m_filter->GetValue().ToStdString());
}
| 1,649
|
C++
|
.cpp
| 44
| 35.681818
| 169
| 0.77478
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,012
|
ModuleWindow.cpp
|
cemu-project_Cemu/src/gui/debugger/ModuleWindow.cpp
|
#include "gui/wxgui.h"
#include "gui/guiWrapper.h"
#include "gui/debugger/ModuleWindow.h"
#include <sstream>
#include "gui/debugger/DebuggerWindow2.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/GraphicPack/GraphicPack2.h"
enum ItemColumns
{
ColumnName = 0,
ColumnAddress,
ColumnSize,
};
ModuleWindow::ModuleWindow(DebuggerWindow2& parent, const wxPoint& main_position, const wxSize& main_size)
: wxFrame(&parent, wxID_ANY, _("Modules"), wxDefaultPosition, wxSize(420, 250), wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT)
{
this->SetSizeHints(wxDefaultSize, wxDefaultSize);
this->wxWindowBase::SetBackgroundColour(*wxWHITE);
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
m_modules = new wxListView(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT);
wxListItem col0;
col0.SetId(ColumnName);
col0.SetText(_("Name"));
col0.SetWidth(125);
m_modules->InsertColumn(ColumnName, col0);
wxListItem col1;
col1.SetId(ColumnAddress);
col1.SetText(_("Address"));
col1.SetWidth(75);
col1.SetAlign(wxLIST_FORMAT_RIGHT);
m_modules->InsertColumn(ColumnAddress, col1);
wxListItem col2;
col2.SetId(ColumnSize);
col2.SetText(_("Size"));
col2.SetWidth(75);
col2.SetAlign(wxLIST_FORMAT_RIGHT);
m_modules->InsertColumn(ColumnSize, col2);
main_sizer->Add(m_modules, 1, wxEXPAND);
this->SetSizer(main_sizer);
this->wxWindowBase::Layout();
this->Centre(wxBOTH);
if (parent.GetConfig().data().pin_to_main)
OnMainMove(main_position, main_size);
m_modules->Bind(wxEVT_LEFT_DCLICK, &ModuleWindow::OnLeftDClick, this);
OnGameLoaded();
}
void ModuleWindow::OnMainMove(const wxPoint& main_position, const wxSize& main_size)
{
wxSize size(420, 250);
this->SetSize(size);
wxPoint position = main_position;
position.x -= 420;
position.y += main_size.y;
this->SetPosition(position);
}
void ModuleWindow::OnGameLoaded()
{
Freeze();
m_modules->DeleteAllItems();
const auto module_count = RPLLoader_GetModuleCount();
const auto module_list = RPLLoader_GetModuleList();
for (int i = 0; i < module_count; i++)
{
const auto module = module_list[i];
if (module)
{
wxListItem item;
item.SetId(i);
item.SetText(module->moduleName2.c_str());
const auto index = m_modules->InsertItem(item);
m_modules->SetItem(index, ColumnAddress, wxString::Format("%08x", module->regionMappingBase_text.GetMPTR()));
m_modules->SetItem(index, ColumnSize, wxString::Format("%x", module->regionSize_text));
}
}
sint32 patch_count = 0;
for (auto& gfx_pack : GraphicPack2::GetGraphicPacks())
{
for (auto& patch_group : gfx_pack->GetPatchGroups())
{
if (patch_group->isApplied())
{
wxListItem item;
item.SetId(module_count + patch_count);
item.SetText(std::string(patch_group->getName()));
const auto index = m_modules->InsertItem(item);
m_modules->SetItem(index, ColumnAddress, wxString::Format("%08x", patch_group->getCodeCaveBase()));
m_modules->SetItem(index, ColumnSize, wxString::Format("%x", patch_group->getCodeCaveSize()));
patch_count++;
}
}
}
Thaw();
}
void ModuleWindow::OnLeftDClick(wxMouseEvent& event)
{
long selected = m_modules->GetFirstSelected();
if (selected == -1)
return;
const auto text = m_modules->GetItemText(selected, ColumnAddress);
const auto address = std::stoul(text.ToStdString(), nullptr, 16);
if (address == 0)
return;
debuggerState.debugSession.instructionPointer = address;
debuggerWindow_moveIP();
}
| 3,577
|
C++
|
.cpp
| 107
| 30.915888
| 169
| 0.744477
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,013
|
RegisterWindow.cpp
|
cemu-project_Cemu/src/gui/debugger/RegisterWindow.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/RegisterWindow.h"
#include <sstream>
#include "gui/debugger/DebuggerWindow2.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/HW/Espresso/EspressoISA.h"
enum
{
// REGISTER
kRegisterValueR0 = wxID_HIGHEST + 8400,
kRegisterLabelR0 = kRegisterValueR0 + 32,
kRegisterLabelLR = kRegisterLabelR0 + 32,
kRegisterValueLR = kRegisterLabelLR + 1,
kRegisterValueFPR0_0 = kRegisterValueLR + 32,
kRegisterValueFPR1_0 = kRegisterValueFPR0_0 + 32,
kRegisterValueCR0 = kRegisterValueFPR1_0 + 32,
kContextMenuZero,
kContextMenuInc,
kContextMenuDec,
kContextMenuCopy,
kContextMenuGotoDisasm,
kContextMenuGotoDump,
};
RegisterWindow::RegisterWindow(DebuggerWindow2& parent, const wxPoint& main_position, const wxSize& main_size)
: wxFrame(&parent, wxID_ANY, _("Registers"), wxDefaultPosition, wxSize(400, 975), wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT),
m_prev_snapshot({}), m_show_double_values(true), m_context_ctrl(nullptr)
{
SetSizeHints(wxDefaultSize, wxDefaultSize);
SetMaxSize({ 400, 975 });
wxWindowBase::SetBackgroundColour(*wxWHITE);
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
auto scrolled_win = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVSCROLL);
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
auto gpr_sizer = new wxFlexGridSizer(0, 3, 0, 0);
// GPRs
for(sint32 i = 0; i < 32; ++i)
{
gpr_sizer->Add(new wxStaticText(scrolled_win, wxID_ANY, wxString::Format("R%d", i)), 0, wxLEFT, 5);
auto value = new wxTextCtrl(scrolled_win, kRegisterValueR0 + i, wxString::Format("%08x", 0), wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
value->SetBackgroundColour(*wxWHITE);
value->Bind(wxEVT_LEFT_DCLICK, &RegisterWindow::OnMouseDClickEvent, this);
//value->Bind(wxEVT_CONTEXT_MENU, &RegisterWindow::OnValueContextMenu, this);
gpr_sizer->Add(value, 0, wxLEFT|wxRIGHT, 5);
auto label = new wxTextCtrl(scrolled_win, kRegisterLabelR0 + i, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
label->SetMinSize(wxSize(500, -1));
label->SetBackgroundColour(*wxWHITE);
gpr_sizer->Add(label, 0, wxEXPAND);
}
{
// LR
gpr_sizer->Add(new wxStaticText(scrolled_win, wxID_ANY, wxString::Format("LR")), 0, wxLEFT, 5);
auto value = new wxTextCtrl(scrolled_win, kRegisterValueLR, wxString::Format("%08x", 0), wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
value->SetBackgroundColour(*wxWHITE);
value->Bind(wxEVT_LEFT_DCLICK, &RegisterWindow::OnMouseDClickEvent, this);
//value->Bind(wxEVT_CONTEXT_MENU, &RegisterWindow::OnValueContextMenu, this);
gpr_sizer->Add(value, 0, wxLEFT | wxRIGHT, 5);
auto label = new wxTextCtrl(scrolled_win, kRegisterLabelLR, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
label->SetMinSize(wxSize(500, -1));
label->SetBackgroundColour(*wxWHITE);
gpr_sizer->Add(label, 0, wxEXPAND);
}
sizer->Add(gpr_sizer, 1, wxEXPAND);
auto button = new wxButton(scrolled_win, wxID_ANY, _("FP view mode"));
button->Bind(wxEVT_BUTTON, &RegisterWindow::OnFPViewModePress, this);
sizer->Add(button, 0, wxALL, 5);
auto fp_sizer = new wxFlexGridSizer(0, 3, 0, 0);
for (sint32 i = 0; i < 32; ++i)
{
fp_sizer->Add(new wxStaticText(scrolled_win, wxID_ANY, wxString::Format("FP%d", i)), 0, wxLEFT, 5);
auto value0 = new wxTextCtrl(scrolled_win, kRegisterValueFPR0_0 + i, wxString::Format("%lf", 0.0), wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
value0->SetBackgroundColour(*wxWHITE);
value0->Bind(wxEVT_LEFT_DCLICK, &RegisterWindow::OnMouseDClickEvent, this);
fp_sizer->Add(value0, 0, wxLEFT | wxRIGHT, 5);
auto value1 = new wxTextCtrl(scrolled_win, kRegisterValueFPR1_0 + i, wxString::Format("%lf", 0.0), wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
value1->SetBackgroundColour(*wxWHITE);
value1->Bind(wxEVT_LEFT_DCLICK, &RegisterWindow::OnMouseDClickEvent, this);
fp_sizer->Add(value1, 0, wxLEFT | wxRIGHT, 5);
}
sizer->Add(fp_sizer, 0, wxEXPAND);
auto cr_sizer = new wxFlexGridSizer(0, 2, 0, 0);
// CRs
for (sint32 i = 0; i < 8; ++i)
{
cr_sizer->Add(new wxStaticText(scrolled_win, wxID_ANY, wxString::Format("CR%d", i)), 0, wxLEFT, 5);
auto value = new wxTextCtrl(scrolled_win, kRegisterValueCR0 + i, "-", wxDefaultPosition, wxDefaultSize, wxTE_READONLY | wxNO_BORDER);
value->SetBackgroundColour(*wxWHITE);
//value->Bind(wxEVT_CONTEXT_MENU, &RegisterWindow::OnValueContextMenu, this);
cr_sizer->Add(value, 0, wxRIGHT, 5);
}
sizer->Add(cr_sizer, 0, wxEXPAND);
scrolled_win->SetSizerAndFit(sizer);
scrolled_win->SetScrollRate(0, GetCharWidth());
main_sizer->Add(scrolled_win, 1, wxEXPAND);
SetSizer(main_sizer);
Layout();
if (parent.GetConfig().data().pin_to_main)
OnMainMove(main_position, main_size);
//Bind(wxEVT_COMMAND_MENU_SELECTED, &RegisterWindow::OnValueContextMenuSelected, this, kContextMenuZero, kContextMenuGotoDump);
}
void RegisterWindow::OnMainMove(const wxPoint& main_position, const wxSize& main_size)
{
wxSize size(400, 255 + main_size.y + 250);
this->SetSize(size);
wxPoint position = main_position;
position.x += main_size.x;
position.y -= 255;
this->SetPosition(position);
}
void RegisterWindow::UpdateIntegerRegister(wxTextCtrl* label, wxTextCtrl* value, uint32 registerValue, bool hasChanged)
{
//const auto value = dynamic_cast<wxTextCtrl*>(GetWindowChild(kRegisterValueR0 + i));
//wxASSERT(value);
//const bool has_changed = register_value != m_prev_snapshot.gpr[i];
if (hasChanged)
value->SetForegroundColour(COLOR_RED);
else if (value->GetForegroundColour() != COLOR_BLACK)
value->SetForegroundColour(COLOR_BLACK);
value->ChangeValue(wxString::Format("%08x", registerValue));
//const auto label = dynamic_cast<wxTextCtrl*>(GetWindowChild(kRegisterLabelR0 + i));
//wxASSERT(label);
label->SetForegroundColour(hasChanged ? COLOR_RED : COLOR_BLACK);
// check if address is a string
if (registerValue >= MEMORY_DATA_AREA_ADDR && registerValue < (MEMORY_DATA_AREA_ADDR + MEMORY_DATA_AREA_SIZE))
{
bool is_valid_string = true;
std::stringstream buffer;
uint32 string_offset = registerValue;
while (string_offset < (MEMORY_DATA_AREA_ADDR + MEMORY_DATA_AREA_SIZE))
{
const uint8 c = memory_readU8(string_offset++);
if (isprint(c))
buffer << c;
else if (c == '\0')
{
buffer << c;
break;
}
else
{
is_valid_string = false;
break;
}
}
if (is_valid_string && buffer.tellp() > 1)
{
label->ChangeValue(wxString::Format("\"%s\"", buffer.str().c_str()));
return;
}
// check for widestring
is_valid_string = true;
string_offset = registerValue;
std::wstringstream wbuffer;
while (string_offset < (MEMORY_DATA_AREA_ADDR + MEMORY_DATA_AREA_SIZE - 1))
{
const uint16 c = memory_readU16(string_offset);
string_offset += 2;
if (iswprint(c))
wbuffer << c;
else if (c == L'\0')
{
wbuffer << c;
break;
}
else
{
is_valid_string = false;
break;
}
}
if (is_valid_string && buffer.tellp() > 1)
{
label->ChangeValue(wxString::Format(L"ws\"%s\"", wbuffer.str().c_str()));
return;
}
}
// check if address is a code offset
RPLModule* code_module = RPLLoader_FindModuleByCodeAddr(registerValue);
if (code_module)
{
label->ChangeValue(wxString::Format("<%s> + %x", code_module->moduleName2.c_str(), registerValue - code_module->regionMappingBase_text.GetMPTR()));
return;
}
label->ChangeValue(wxEmptyString);
}
void RegisterWindow::OnUpdateView()
{
// m_register_ctrl->RefreshControl();
for (int i = 0; i < 32; ++i)
{
const uint32 registerValue = debuggerState.debugSession.ppcSnapshot.gpr[i];
const bool hasChanged = registerValue != m_prev_snapshot.gpr[i];
const auto value = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueR0 + i));
wxASSERT(value);
const auto label = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterLabelR0 + i));
wxASSERT(label);
UpdateIntegerRegister(label, value, registerValue, hasChanged);
}
// update LR
{
const uint32 registerValue = debuggerState.debugSession.ppcSnapshot.spr_lr;
const bool hasChanged = registerValue != m_prev_snapshot.spr_lr;
const auto value = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueLR));
wxASSERT(value);
const auto label = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterLabelLR));
wxASSERT(label);
UpdateIntegerRegister(label, value, registerValue, hasChanged);
}
for (int i = 0; i < 32; ++i)
{
const uint64_t register_value = debuggerState.debugSession.ppcSnapshot.fpr[i].fp0int;
const auto value = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueFPR0_0 + i));
wxASSERT(value);
const bool has_changed = register_value != m_prev_snapshot.fpr[i].fp0int;
if (has_changed)
value->SetForegroundColour(COLOR_RED);
else if (value->GetForegroundColour() != COLOR_BLACK)
value->SetForegroundColour(COLOR_BLACK);
else
continue;
if(m_show_double_values)
value->ChangeValue(wxString::Format("%lf", debuggerState.debugSession.ppcSnapshot.fpr[i].fp0));
else
value->ChangeValue(wxString::Format("%016llx", register_value));
}
for (int i = 0; i < 32; ++i)
{
const uint64_t register_value = debuggerState.debugSession.ppcSnapshot.fpr[i].fp1int;
const auto value = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueFPR1_0 + i));
wxASSERT(value);
const bool has_changed = register_value != m_prev_snapshot.fpr[i].fp1int;
if (has_changed)
value->SetForegroundColour(COLOR_RED);
else if (value->GetForegroundColour() != COLOR_BLACK)
value->SetForegroundColour(COLOR_BLACK);
else
continue;
if (m_show_double_values)
value->ChangeValue(wxString::Format("%lf", debuggerState.debugSession.ppcSnapshot.fpr[i].fp1));
else
value->ChangeValue(wxString::Format("%016llx", register_value));
}
// update CRs
for (int i = 0; i < 8; ++i)
{
const auto value = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueCR0 + i));
wxASSERT(value);
auto cr_bits_ptr = debuggerState.debugSession.ppcSnapshot.cr + i * 4;
auto cr_bits_ptr_cmp = m_prev_snapshot.cr + i * 4;
const bool has_changed = !std::equal(cr_bits_ptr, cr_bits_ptr + 4, cr_bits_ptr_cmp);
if (has_changed)
value->SetForegroundColour(COLOR_RED);
else if (value->GetForegroundColour() != COLOR_BLACK)
value->SetForegroundColour(COLOR_BLACK);
else
continue;
std::vector<std::string> joinArray = {};
if (cr_bits_ptr[Espresso::CR_BIT_INDEX_LT] != 0)
joinArray.emplace_back("LT");
if (cr_bits_ptr[Espresso::CR_BIT_INDEX_GT] != 0)
joinArray.emplace_back("GT");
if (cr_bits_ptr[Espresso::CR_BIT_INDEX_EQ] != 0)
joinArray.emplace_back("EQ");
if (cr_bits_ptr[Espresso::CR_BIT_INDEX_SO] != 0)
joinArray.emplace_back("SO");
if (joinArray.empty())
value->ChangeValue("-");
else
value->ChangeValue(fmt::format("{}", fmt::join(joinArray, ", ")));
}
memcpy(&m_prev_snapshot, &debuggerState.debugSession.ppcSnapshot, sizeof(m_prev_snapshot));
}
void RegisterWindow::OnMouseDClickEvent(wxMouseEvent& event)
{
if (!debuggerState.debugSession.isTrapped)
{
event.Skip();
return;
}
const auto id = event.GetId();
if(kRegisterValueR0 <= id && id < kRegisterValueR0 + 32)
{
const uint32 register_index = id - kRegisterValueR0;
const uint32 register_value = debuggerState.debugSession.ppcSnapshot.gpr[register_index];
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set R%d value", register_index)), wxString::Format("%08x", register_value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const uint32 new_value = std::stoul(set_value_dialog.GetValue().ToStdString(), nullptr, 16);
debuggerState.debugSession.hCPU->gpr[register_index] = new_value;
debuggerState.debugSession.ppcSnapshot.gpr[register_index] = new_value;
OnUpdateView();
}
return;
}
if (kRegisterValueFPR0_0 <= id && id < kRegisterValueFPR0_0 + 32)
{
const uint32 register_index = id - kRegisterValueFPR0_0;
const double register_value = debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp0;
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set FP0_%d value", register_index)), wxString::Format("%lf", register_value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const double new_value = std::stod(set_value_dialog.GetValue().ToStdString());
debuggerState.debugSession.hCPU->fpr[register_index].fp0 = new_value;
debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp0 = new_value;
OnUpdateView();
}
return;
}
if (kRegisterValueFPR1_0 <= id && id < kRegisterValueFPR1_0 + 32)
{
const uint32 register_index = id - kRegisterValueFPR1_0;
const double register_value = debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp1;
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set FP1_%d value", register_index)), wxString::Format("%lf", register_value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const double new_value = std::stod(set_value_dialog.GetValue().ToStdString());
debuggerState.debugSession.hCPU->fpr[register_index].fp1 = new_value;
debuggerState.debugSession.ppcSnapshot.fpr[register_index].fp1 = new_value;
OnUpdateView();
}
return;
}
event.Skip();
}
void RegisterWindow::OnFPViewModePress(wxCommandEvent& event)
{
m_show_double_values = !m_show_double_values;
for (int i = 0; i < 32; ++i)
{
const auto value0 = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueFPR0_0 + i));
const auto value1 = dynamic_cast<wxTextCtrl*>(FindWindow(kRegisterValueFPR1_0 + i));
wxASSERT(value0);
wxASSERT(value1);
if (m_show_double_values)
{
value0->ChangeValue(wxString::Format("%lf", debuggerState.debugSession.ppcSnapshot.fpr[i].fp0));
value1->ChangeValue(wxString::Format("%lf", debuggerState.debugSession.ppcSnapshot.fpr[i].fp1));
}
else
{
value0->ChangeValue(wxString::Format("%016llx", debuggerState.debugSession.ppcSnapshot.fpr[i].fp0int));
value1->ChangeValue(wxString::Format("%016llx", debuggerState.debugSession.ppcSnapshot.fpr[i].fp1int));
}
}
}
void RegisterWindow::OnValueContextMenu(wxContextMenuEvent& event)
{
wxMenu menu;
menu.Append(kContextMenuZero, _("&Zero"));
menu.Append(kContextMenuInc, _("&Increment"));
menu.Append(kContextMenuDec, _("&Decrement"));
menu.AppendSeparator();
menu.Append(kContextMenuCopy, _("&Copy"));
menu.AppendSeparator();
menu.Append(kContextMenuGotoDisasm, _("&Goto Disasm"));
menu.Append(kContextMenuGotoDump, _("G&oto Dump"));
m_context_ctrl = dynamic_cast<wxTextCtrl*>(event.GetEventObject());
PopupMenu(&menu);
}
void RegisterWindow::OnValueContextMenuSelected(wxCommandEvent& event)
{
wxASSERT(m_context_ctrl);
switch (event.GetId())
{
case kContextMenuZero:
break;
case kContextMenuInc:
break;
case kContextMenuDec:
break;
case kContextMenuCopy:
break;
case kContextMenuGotoDisasm:
break;
case kContextMenuGotoDump:
break;
}
}
| 15,174
|
C++
|
.cpp
| 379
| 37.158311
| 172
| 0.734285
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,014
|
BreakpointWindow.cpp
|
cemu-project_Cemu/src/gui/debugger/BreakpointWindow.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/BreakpointWindow.h"
#include <sstream>
#include "gui/debugger/DebuggerWindow2.h"
#include "gui/guiWrapper.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cemu/ExpressionParser/ExpressionParser.h"
enum
{
MENU_ID_CREATE_CODE_BP_EXECUTION = 1,
MENU_ID_CREATE_CODE_BP_LOGGING,
MENU_ID_CREATE_MEM_BP_READ,
MENU_ID_CREATE_MEM_BP_WRITE,
MENU_ID_DELETE_BP,
};
enum ItemColumns
{
ColumnEnabled = 0,
ColumnAddress,
ColumnType,
ColumnComment,
};
BreakpointWindow::BreakpointWindow(DebuggerWindow2& parent, const wxPoint& main_position, const wxSize& main_size)
: wxFrame(&parent, wxID_ANY, _("Breakpoints"), wxDefaultPosition, wxSize(420, 250), wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT)
{
this->SetSizeHints(wxDefaultSize, wxDefaultSize);
this->wxWindowBase::SetBackgroundColour(*wxWHITE);
wxBoxSizer* main_sizer = new wxBoxSizer(wxVERTICAL);
m_breakpoints = new wxCheckedListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT);
wxListItem col0;
col0.SetId(ColumnEnabled);
col0.SetText(_("On"));
col0.SetWidth(32);
m_breakpoints->InsertColumn(ColumnEnabled, col0);
wxListItem col1;
col1.SetId(ColumnAddress);
col1.SetText(_("Address"));
col1.SetWidth(75);
m_breakpoints->InsertColumn(ColumnAddress, col1);
wxListItem col2;
col2.SetId(ColumnType);
col2.SetText(_("Type"));
col2.SetWidth(42);
m_breakpoints->InsertColumn(ColumnType, col2);
wxListItem col3;
col3.SetId(ColumnComment);
col3.SetText(_("Comment"));
col3.SetWidth(250);
m_breakpoints->InsertColumn(ColumnComment, col3);
main_sizer->Add(m_breakpoints, 1, wxEXPAND);
this->SetSizer(main_sizer);
this->wxWindowBase::Layout();
this->Centre(wxBOTH);
if (parent.GetConfig().data().pin_to_main)
OnMainMove(main_position, main_size);
m_breakpoints->Bind(wxEVT_COMMAND_LIST_ITEM_CHECKED, (wxObjectEventFunction)&BreakpointWindow::OnBreakpointToggled, this);
m_breakpoints->Bind(wxEVT_COMMAND_LIST_ITEM_UNCHECKED, (wxObjectEventFunction)&BreakpointWindow::OnBreakpointToggled, this);
m_breakpoints->Bind(wxEVT_LEFT_DCLICK, &BreakpointWindow::OnLeftDClick, this);
m_breakpoints->Bind(wxEVT_RIGHT_DOWN, &BreakpointWindow::OnRightDown, this);
OnUpdateView();
}
BreakpointWindow::~BreakpointWindow()
{
m_breakpoints->Unbind(wxEVT_COMMAND_LIST_ITEM_CHECKED, (wxObjectEventFunction)&BreakpointWindow::OnBreakpointToggled, this);
m_breakpoints->Unbind(wxEVT_COMMAND_LIST_ITEM_UNCHECKED, (wxObjectEventFunction)&BreakpointWindow::OnBreakpointToggled, this);
}
void BreakpointWindow::OnMainMove(const wxPoint& main_position, const wxSize& main_size)
{
wxSize size(420, 250);
this->SetSize(size);
wxPoint position = main_position;
position.x -= 420;
position.y += main_size.y - 250;
this->SetPosition(position);
}
void BreakpointWindow::OnUpdateView()
{
Freeze();
m_breakpoints->DeleteAllItems();
if (!debuggerState.breakpoints.empty())
{
uint32_t i = 0;
for (const auto bpBase : debuggerState.breakpoints)
{
DebuggerBreakpoint* bp = bpBase;
while (bp)
{
wxListItem item;
item.SetId(i++);
const auto index = m_breakpoints->InsertItem(item);
m_breakpoints->SetItem(index, ColumnAddress, wxString::Format("%08x", bp->address));
const char* typeName = "UKN";
if (bp->bpType == DEBUGGER_BP_T_NORMAL)
typeName = "X";
else if (bp->bpType == DEBUGGER_BP_T_LOGGING)
typeName = "LOG";
else if (bp->bpType == DEBUGGER_BP_T_ONE_SHOT)
typeName = "XS";
else if (bp->bpType == DEBUGGER_BP_T_MEMORY_READ)
typeName = "R";
else if (bp->bpType == DEBUGGER_BP_T_MEMORY_WRITE)
typeName = "W";
m_breakpoints->SetItem(index, ColumnType, typeName);
m_breakpoints->SetItem(index, ColumnComment, bp->comment);
m_breakpoints->SetItemPtrData(item, (wxUIntPtr)bp);
m_breakpoints->Check(index, bp->enabled);
bp = bp->next;
}
}
}
Thaw();
}
void BreakpointWindow::OnGameLoaded()
{
OnUpdateView();
}
void BreakpointWindow::OnBreakpointToggled(wxListEvent& event)
{
const int32_t index = event.GetIndex();
if (0 <= index && index < m_breakpoints->GetItemCount())
{
const bool state = m_breakpoints->IsChecked(index);
wxString line = m_breakpoints->GetItemText(index, ColumnAddress);
DebuggerBreakpoint* bp = (DebuggerBreakpoint*)m_breakpoints->GetItemData(index);
const uint32 address = std::stoul(line.c_str().AsChar(), nullptr, 16);
debugger_toggleBreakpoint(address, state, bp);
}
}
void BreakpointWindow::OnLeftDClick(wxMouseEvent& event)
{
const auto position = event.GetPosition();
const sint32 index = (position.y / m_breakpoints->GetCharHeight()) - 2;
if (index < 0 || index >= m_breakpoints->GetItemCount())
return;
sint32 x = position.x;
const auto enabled_width = m_breakpoints->GetColumnWidth(ColumnEnabled);
if (x <= enabled_width)
return;
x -= enabled_width;
const auto address_width = m_breakpoints->GetColumnWidth(ColumnAddress);
if(x <= address_width)
{
const auto item = m_breakpoints->GetItemText(index, ColumnAddress);
const auto address = std::stoul(item.ToStdString(), nullptr, 16);
debuggerState.debugSession.instructionPointer = address;
debuggerWindow_moveIP();
return;
}
x -= address_width;
const auto type_width = m_breakpoints->GetColumnWidth(ColumnType);
if (x <= type_width)
return;
x -= type_width;
const auto comment_width = m_breakpoints->GetColumnWidth(ColumnComment);
if(x <= comment_width)
{
if (index >= debuggerState.breakpoints.size())
return;
const auto item = m_breakpoints->GetItemText(index, ColumnAddress);
const auto address = std::stoul(item.ToStdString(), nullptr, 16);
auto it = debuggerState.breakpoints.begin();
std::advance(it, index);
wxTextEntryDialog set_value_dialog(this, _("Enter a new comment."), wxString::Format(_("Set comment for breakpoint at address %08x"), address), (*it)->comment);
if (set_value_dialog.ShowModal() == wxID_OK)
{
(*it)->comment = set_value_dialog.GetValue().ToStdWstring();
m_breakpoints->SetItem(index, ColumnComment, set_value_dialog.GetValue());
}
return;
}
}
void BreakpointWindow::OnRightDown(wxMouseEvent& event)
{
const auto position = event.GetPosition();
const sint32 index = (position.y / m_breakpoints->GetCharHeight()) - 2;
if (index < 0 || index >= m_breakpoints->GetItemCount())
{
wxMenu menu;
menu.Append(MENU_ID_CREATE_CODE_BP_EXECUTION, _("Create execution breakpoint"));
menu.Append(MENU_ID_CREATE_CODE_BP_LOGGING, _("Create logging breakpoint"));
menu.Append(MENU_ID_CREATE_MEM_BP_READ, _("Create memory breakpoint (read)"));
menu.Append(MENU_ID_CREATE_MEM_BP_WRITE, _("Create memory breakpoint (write)"));
menu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(BreakpointWindow::OnContextMenuClick), nullptr, this);
PopupMenu(&menu);
}
else
{
m_breakpoints->SetItemState(index, wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED);
m_breakpoints->SetItemState(index, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
wxMenu menu;
menu.Append(MENU_ID_DELETE_BP, _("Delete breakpoint"));
menu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(BreakpointWindow::OnContextMenuClickSelected), nullptr, this);
PopupMenu(&menu);
}
}
void BreakpointWindow::OnContextMenuClickSelected(wxCommandEvent& evt)
{
if (evt.GetId() == MENU_ID_DELETE_BP)
{
long sel = m_breakpoints->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (sel != -1)
{
if (sel >= debuggerState.breakpoints.size())
return;
auto it = debuggerState.breakpoints.begin();
std::advance(it, sel);
debugger_deleteBreakpoint(*it);
wxCommandEvent evt(wxEVT_BREAKPOINT_CHANGE);
wxPostEvent(this->m_parent, evt);
}
}
}
void BreakpointWindow::OnContextMenuClick(wxCommandEvent& evt)
{
wxTextEntryDialog goto_dialog(this, _("Enter a memory address"), _("Set breakpoint"), wxEmptyString);
if (goto_dialog.ShowModal() == wxID_OK)
{
ExpressionParser parser;
auto value = goto_dialog.GetValue().ToStdString();
std::transform(value.begin(), value.end(), value.begin(), tolower);
uint32_t newBreakpointAddress = 0;
try
{
debugger_addParserSymbols(parser);
newBreakpointAddress = parser.IsConstantExpression("0x"+value) ? (uint32)parser.Evaluate("0x"+value) : (uint32)parser.Evaluate(value);
}
catch (const std::exception& ex)
{
wxMessageBox(ex.what(), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this);
return;
}
switch (evt.GetId())
{
case MENU_ID_CREATE_CODE_BP_EXECUTION:
debugger_createCodeBreakpoint(newBreakpointAddress, DEBUGGER_BP_T_NORMAL);
break;
case MENU_ID_CREATE_CODE_BP_LOGGING:
debugger_createCodeBreakpoint(newBreakpointAddress, DEBUGGER_BP_T_LOGGING);
break;
case MENU_ID_CREATE_MEM_BP_READ:
debugger_createMemoryBreakpoint(newBreakpointAddress, true, false);
break;
case MENU_ID_CREATE_MEM_BP_WRITE:
debugger_createMemoryBreakpoint(newBreakpointAddress, false, true);
break;
}
this->OnUpdateView();
}
}
| 9,048
|
C++
|
.cpp
| 249
| 33.534137
| 173
| 0.747968
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,015
|
DumpCtrl.cpp
|
cemu-project_Cemu/src/gui/debugger/DumpCtrl.cpp
|
#include "gui/wxgui.h"
#include "gui/debugger/DumpCtrl.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "util/helpers/helpers.h"
#include "Cemu/ExpressionParser/ExpressionParser.h"
#define COLOR_BLACK 0xFF000000
#define COLOR_GREY 0xFFA0A0A0
#define COLOR_WHITE 0xFFFFFFFF
#define COLOR_DEBUG_ACTIVE_BP 0xFFFFA0FF
#define COLOR_DEBUG_ACTIVE 0xFFFFA080
#define COLOR_DEBUG_BP 0xFF8080FF
#define SYNTAX_COLOR_GPR 0xFF000066
#define SYNTAX_COLOR_FPR 0xFF006666
#define SYNTAX_COLOR_SPR 0xFF666600
#define SYNTAX_COLOR_CR 0xFF666600
#define SYNTAX_COLOR_IMM 0xFF006600
#define SYNTAX_COLOR_IMM_OFFSET 0xFF006600
#define SYNTAX_COLOR_CIMM 0xFF880000
#define SYNTAX_COLOR_PSEUDO 0xFFA0A0A0 // color for pseudo code
#define SYNTAX_COLOR_SYMBOL 0xFF0000A0 // color for function symbol
#define OFFSET_ADDRESS (60)
#define OFFSET_ADDRESS_RELATIVE (90)
#define OFFSET_MEMORY (450)
#define OFFSET_DISASSEMBLY_OPERAND (80)
DumpCtrl::DumpCtrl(wxWindow* parent, const wxWindowID& id, const wxPoint& pos, const wxSize& size, long style)
: TextList(parent, id, pos, size, style)
{
MMURange* range = memory_getMMURangeByAddress(0x10000000);
if (range)
{
m_memoryRegion.baseAddress = range->getBase();
m_memoryRegion.size = range->getSize();
Init();
}
else
{
m_memoryRegion.baseAddress = 0x10000000;
m_memoryRegion.size = 0x1000;
Init();
}
}
void DumpCtrl::Init()
{
uint32 element_count = m_memoryRegion.size;
this->SetElementCount(element_count / 0x10);
Scroll(0, 0);
RefreshControl();
}
void DumpCtrl::OnDraw(wxDC& dc, sint32 start, sint32 count, const wxPoint& start_position)
{
wxPoint position = start_position;
uint32 endAddr = m_memoryRegion.baseAddress + m_memoryRegion.size;
RPLModule* currentCodeRPL = RPLLoader_FindModuleByCodeAddr(m_memoryRegion.baseAddress + start);
RPLModule* currentDataRPL = RPLLoader_FindModuleByDataAddr(m_memoryRegion.baseAddress + start);
for (sint32 i = 0; i <= count; i++)
{
const uint32 virtual_address = m_memoryRegion.baseAddress + (start + i) * 0x10;
dc.SetTextForeground(wxColour(COLOR_BLACK));
dc.DrawText(wxString::Format("%08x", virtual_address), position);
position.x += OFFSET_ADDRESS;
dc.SetTextForeground(wxColour(COLOR_GREY));
if (currentCodeRPL)
{
dc.DrawText(wxString::Format("+0x%-8x", virtual_address - currentCodeRPL->regionMappingBase_text.GetMPTR()), position);
}
else if (currentDataRPL)
{
dc.DrawText(wxString::Format("+0x%-8x", virtual_address - currentDataRPL->regionMappingBase_data), position);
}
else
{
dc.DrawText("???", position);
}
position.x += OFFSET_ADDRESS_RELATIVE;
sint32 start_width = position.x;
if (!memory_isAddressRangeAccessible(virtual_address, 0x10))
{
for (sint32 f=0; f<0x10; f++)
{
wxPoint p(position);
WriteText(dc, wxString::Format("?? "), p);
position.x += (m_char_width * 3);
}
}
else
{
std::array<uint8, 0x10> data;
memory_readBytes(virtual_address, data);
for (auto b : data)
{
wxPoint p(position);
WriteText(dc, wxString::Format("%02x ", b), p);
position.x += (m_char_width * 3);
}
position.x = start_width = OFFSET_MEMORY;
dc.SetTextForeground(wxColour(COLOR_BLACK));
for (auto b : data)
{
if (isprint(b))
dc.DrawText(wxString::Format("%c ", b), position);
else
dc.DrawText(".", position);
position.x += m_char_width;
}
}
// display goto indicator
if (m_lastGotoOffset >= virtual_address && m_lastGotoOffset < (virtual_address + 16))
{
sint32 indicatorX = start_position.x + OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE + (m_lastGotoOffset - virtual_address) * m_char_width * 3;
wxPoint line1(start_position.x + indicatorX - 2, position.y);
wxPoint line2(line1.x, line1.y + m_line_height);
dc.SetPen(*wxRED_PEN);
dc.DrawLine(line1, line2);
dc.DrawLine(line1, wxPoint(line1.x + 3, line1.y));
dc.DrawLine(line2, wxPoint(line2.x + 3, line2.y));
}
NextLine(position, &start_position);
}
// draw vertical separator lines for 4 byte blocks
sint32 cursorOffsetHexBytes = start_position.x + OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE;
wxPoint line_from(
cursorOffsetHexBytes + m_char_width * (3 * 4 - 1) + m_char_width / 2,
start_position.y
);
wxPoint line_to(line_from.x, line_from.y + m_line_height * (count + 1));
dc.SetPen(*wxLIGHT_GREY_PEN);
for (sint32 i = 0; i < 3; i++)
{
dc.DrawLine(line_from, line_to);
line_from.x += m_char_width * (3 * 4);
line_to.x += m_char_width * (3 * 4);
}
}
void DumpCtrl::OnMouseMove(const wxPoint& start_position, uint32 line)
{
wxPoint position = start_position;
// address
if (position.x <= OFFSET_ADDRESS)
{
return;
}
position.x -= OFFSET_ADDRESS;
// relative offset
if (position.x <= OFFSET_ADDRESS_RELATIVE)
{
return;
}
position.x -= OFFSET_ADDRESS_RELATIVE;
// byte code
if (position.x <= OFFSET_MEMORY)
{
}
// string view
position.x -= OFFSET_MEMORY;
}
void DumpCtrl::OnMouseDClick(const wxPoint& position, uint32 line)
{
wxPoint pos = position;
if (pos.x <= OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE)
return;
pos.x -= OFFSET_ADDRESS + OFFSET_ADDRESS_RELATIVE;
if(pos.x <= OFFSET_MEMORY)
{
const uint32 byte_index = (pos.x / m_char_width) / 3;
const uint32 offset = LineToOffset(line) + byte_index;
const uint8 value = memory_readU8(offset);
wxTextEntryDialog set_value_dialog(this, _("Enter a new value."), _(wxString::Format("Set byte at address %08x", offset)), wxString::Format("%02x", value));
if (set_value_dialog.ShowModal() == wxID_OK)
{
const uint8 new_value = std::stoul(set_value_dialog.GetValue().ToStdString(), nullptr, 16);
memory_writeU8(offset, new_value);
wxRect update_rect(0, line * m_line_height, GetSize().x, m_line_height);
RefreshControl(&update_rect);
}
return;
}
}
void DumpCtrl::GoToAddressDialog()
{
wxTextEntryDialog goto_dialog(this, _("Enter a target address."), _("GoTo address"), wxEmptyString);
if (goto_dialog.ShowModal() == wxID_OK)
{
ExpressionParser parser;
auto value = goto_dialog.GetValue().ToStdString();
std::transform(value.begin(), value.end(), value.begin(), tolower);
debugger_addParserSymbols(parser);
// try to parse expression as hex value first (it should interpret 1234 as 0x1234, not 1234)
if (parser.IsConstantExpression("0x"+value))
{
const auto result = (uint32)parser.Evaluate("0x"+value);
m_lastGotoOffset = result;
CenterOffset(result);
}
else if (parser.IsConstantExpression(value))
{
const auto result = (uint32)parser.Evaluate(value);
m_lastGotoOffset = result;
CenterOffset(result);
}
else
{
try
{
const auto _ = (uint32)parser.Evaluate(value);
}
catch (const std::exception& ex)
{
wxMessageBox(ex.what(), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this);
}
}
}
}
void DumpCtrl::CenterOffset(uint32 offset)
{
// check if the offset is valid
if (!memory_isAddressRangeAccessible(offset, 1))
return;
// set region and line
MMURange* range = memory_getMMURangeByAddress(offset);
if (m_memoryRegion.baseAddress != range->getBase() || m_memoryRegion.size != range->getSize())
{
m_memoryRegion.baseAddress = range->getBase();
m_memoryRegion.size = range->getSize();
Init();
}
const sint32 line = OffsetToLine(offset);
if (line < 0 || line >= (sint32)m_element_count)
return;
DoScroll(0, std::max(0, line - ((sint32)m_elements_visible / 2)));
RefreshControl();
//RefreshLine(line);
debug_printf("scroll to %x\n", debuggerState.debugSession.instructionPointer);
}
uint32 DumpCtrl::LineToOffset(uint32 line)
{
return m_memoryRegion.baseAddress + line * 0x10;
}
uint32 DumpCtrl::OffsetToLine(uint32 offset)
{
return (offset - m_memoryRegion.baseAddress) / 0x10;
}
void DumpCtrl::OnKeyPressed(sint32 key_code, const wxPoint& position)
{
switch (key_code)
{
case 'G':
{
if (IsKeyDown(WXK_CONTROL))
{
GoToAddressDialog();
return;
}
}
}
}
wxSize DumpCtrl::DoGetBestSize() const
{
return TextList::DoGetBestSize();
}
| 8,114
|
C++
|
.cpp
| 261
| 28.375479
| 158
| 0.719175
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,016
|
DebugPPCThreadsWindow.cpp
|
cemu-project_Cemu/src/gui/windows/PPCThreadsViewer/DebugPPCThreadsWindow.cpp
|
#include "gui/wxgui.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_Scheduler.h"
#include "DebugPPCThreadsWindow.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "gui/components/wxProgressDialogManager.h"
#include <cinttypes>
#include <helpers/wxHelpers.h>
enum
{
// options
REFRESH_ID = wxID_HIGHEST + 1,
AUTO_REFRESH_ID,
CLOSE_ID,
GPLIST_ID,
// list context menu options
THREADLIST_MENU_BOOST_PRIO_1,
THREADLIST_MENU_BOOST_PRIO_5,
THREADLIST_MENU_DECREASE_PRIO_1,
THREADLIST_MENU_DECREASE_PRIO_5,
THREADLIST_MENU_SUSPEND,
THREADLIST_MENU_RESUME,
THREADLIST_MENU_DUMP_STACK_TRACE,
THREADLIST_MENU_PROFILE_THREAD,
};
wxBEGIN_EVENT_TABLE(DebugPPCThreadsWindow, wxFrame)
EVT_BUTTON(CLOSE_ID, DebugPPCThreadsWindow::OnCloseButton)
EVT_BUTTON(REFRESH_ID, DebugPPCThreadsWindow::OnRefreshButton)
EVT_CLOSE(DebugPPCThreadsWindow::OnClose)
wxEND_EVENT_TABLE()
DebugPPCThreadsWindow::DebugPPCThreadsWindow(wxFrame& parent)
: wxFrame(&parent, wxID_ANY, _("PPC threads"), wxDefaultPosition, wxSize(930, 280),
wxCLOSE_BOX | wxCLIP_CHILDREN | wxCAPTION | wxRESIZE_BORDER)
{
wxFrame::SetBackgroundColour(*wxWHITE);
auto* sizer = new wxBoxSizer(wxVERTICAL);
m_thread_list = new wxListCtrl(this, GPLIST_ID, wxPoint(0, 0), wxSize(930, 240), wxLC_REPORT);
m_thread_list->SetFont(wxFont(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, "Courier New")); //wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT));
// add columns
wxListItem col0;
col0.SetId(0);
col0.SetText("Address");
col0.SetWidth(75);
m_thread_list->InsertColumn(0, col0);
wxListItem col1;
col1.SetId(1);
col1.SetText("Entry");
col1.SetWidth(75);
m_thread_list->InsertColumn(1, col1);
wxListItem col2;
col2.SetId(2);
col2.SetText("Stack");
col2.SetWidth(145);
m_thread_list->InsertColumn(2, col2);
wxListItem col3;
col3.SetId(3);
col3.SetText("PC");
col3.SetWidth(120);
m_thread_list->InsertColumn(3, col3);
wxListItem colLR;
colLR.SetId(4);
colLR.SetText("LR");
colLR.SetWidth(75);
m_thread_list->InsertColumn(4, colLR);
wxListItem col4;
col4.SetId(5);
col4.SetText("State");
col4.SetWidth(90);
m_thread_list->InsertColumn(5, col4);
wxListItem col5;
col5.SetId(6);
col5.SetText("Affinity");
col5.SetWidth(70);
m_thread_list->InsertColumn(6, col5);
wxListItem colPriority;
colPriority.SetId(7);
colPriority.SetText("Priority");
colPriority.SetWidth(80);
m_thread_list->InsertColumn(7, colPriority);
wxListItem col6;
col6.SetId(8);
col6.SetText("SliceStart");
col6.SetWidth(110);
m_thread_list->InsertColumn(8, col6);
wxListItem col7;
col7.SetId(9);
col7.SetText("SumWakeTime");
col7.SetWidth(110);
m_thread_list->InsertColumn(9, col7);
wxListItem col8;
col8.SetId(10);
col8.SetText("ThreadName");
col8.SetWidth(180);
m_thread_list->InsertColumn(10, col8);
wxListItem col9;
col9.SetId(11);
col9.SetText("GPR");
col9.SetWidth(180);
m_thread_list->InsertColumn(11, col9);
wxListItem col10;
col10.SetId(12);
col10.SetText("Extra info");
col10.SetWidth(180);
m_thread_list->InsertColumn(12, col10);
sizer->Add(m_thread_list, 1, wxEXPAND | wxALL, 5);
auto* row = new wxBoxSizer(wxHORIZONTAL);
wxButton* button = new wxButton(this, REFRESH_ID, _("Refresh"), wxPoint(0, 0), wxSize(80, 26));
row->Add(button, 0, wxALL, 5);
m_auto_refresh = new wxCheckBox(this, AUTO_REFRESH_ID, _("Auto refresh"));
m_auto_refresh->SetValue(true);
row->Add(m_auto_refresh, 0, wxEXPAND | wxALL, 5);
sizer->Add(row, 0, wxEXPAND | wxALL, 5);
m_thread_list->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(DebugPPCThreadsWindow::OnThreadListRightClick), nullptr, this);
SetSizer(sizer);
RefreshThreadList();
m_timer = new wxTimer(this);
this->Bind(wxEVT_TIMER, &DebugPPCThreadsWindow::OnTimer, this);
m_timer->Start(250);
}
DebugPPCThreadsWindow::~DebugPPCThreadsWindow()
{
m_timer->Stop();
}
void DebugPPCThreadsWindow::OnCloseButton(wxCommandEvent& event)
{
Close();
}
void DebugPPCThreadsWindow::OnRefreshButton(wxCommandEvent& event)
{
RefreshThreadList();
}
void DebugPPCThreadsWindow::OnClose(wxCloseEvent& event)
{
Close();
}
void DebugPPCThreadsWindow::OnTimer(wxTimerEvent& event)
{
if (m_auto_refresh->IsChecked())
RefreshThreadList();
}
#define _r(__idx) _swapEndianU32(cafeThread->context.gpr[__idx])
void DebugPPCThreadsWindow::RefreshThreadList()
{
wxWindowUpdateLocker lock(m_thread_list);
long selected_thread = 0;
const int selection = m_thread_list->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (selection != wxNOT_FOUND)
selected_thread = m_thread_list->GetItemData(selection);
const int scrollPos = m_thread_list->GetScrollPos(0);
m_thread_list->DeleteAllItems();
if(activeThreadCount > 0)
{
__OSLockScheduler();
srwlock_activeThreadList.LockWrite();
for (sint32 i = 0; i < activeThreadCount; i++)
{
MPTR threadItrMPTR = activeThread[i];
OSThread_t* cafeThread = (OSThread_t*)memory_getPointerFromVirtualOffset(threadItrMPTR);
char tempStr[512];
sprintf(tempStr, "%08X", threadItrMPTR);
wxListItem item;
item.SetId(i);
item.SetText(tempStr);
m_thread_list->InsertItem(item);
m_thread_list->SetItemData(item, (long)threadItrMPTR);
// entry point
sprintf(tempStr, "%08X", cafeThread->entrypoint.GetMPTR());
m_thread_list->SetItem(i, 1, tempStr);
// stack base (low)
sprintf(tempStr, "%08X - %08X", cafeThread->stackEnd.GetMPTR(), cafeThread->stackBase.GetMPTR());
m_thread_list->SetItem(i, 2, tempStr);
// pc
RPLStoredSymbol* symbol = rplSymbolStorage_getByAddress(cafeThread->context.srr0);
if (symbol)
sprintf(tempStr, "%s (0x%08x)", (const char*)symbol->symbolName, cafeThread->context.srr0);
else
sprintf(tempStr, "%08X", cafeThread->context.srr0);
m_thread_list->SetItem(i, 3, tempStr);
// lr
sprintf(tempStr, "%08X", _swapEndianU32(cafeThread->context.lr));
m_thread_list->SetItem(i, 4, tempStr);
// state
OSThread_t::THREAD_STATE threadState = cafeThread->state;
wxString threadStateStr = "UNDEFINED";
if (cafeThread->suspendCounter != 0)
threadStateStr = "SUSPENDED";
else if (threadState == OSThread_t::THREAD_STATE::STATE_NONE)
threadStateStr = "NONE";
else if (threadState == OSThread_t::THREAD_STATE::STATE_READY)
threadStateStr = "READY";
else if (threadState == OSThread_t::THREAD_STATE::STATE_RUNNING)
threadStateStr = "RUNNING";
else if (threadState == OSThread_t::THREAD_STATE::STATE_WAITING)
threadStateStr = "WAITING";
else if (threadState == OSThread_t::THREAD_STATE::STATE_MORIBUND)
threadStateStr = "MORIBUND";
m_thread_list->SetItem(i, 5, threadStateStr);
// affinity
uint8 affinity = cafeThread->attr&7;
uint8 affinityReal = cafeThread->context.affinity;
if(affinity != affinityReal)
sprintf(tempStr, "(!) %d%d%d real: %d%d%d", (affinity >> 0) & 1, (affinity >> 1) & 1, (affinity >> 2) & 1, (affinityReal >> 0) & 1, (affinityReal >> 1) & 1, (affinityReal >> 2) & 1);
else
sprintf(tempStr, "%d%d%d", (affinity >> 0) & 1, (affinity >> 1) & 1, (affinity >> 2) & 1);
m_thread_list->SetItem(i, 6, tempStr);
// priority
sint32 effectivePriority = cafeThread->effectivePriority;
sprintf(tempStr, "%d", effectivePriority);
m_thread_list->SetItem(i, 7, tempStr);
// last awake in cycles
uint64 lastWakeUpTime = cafeThread->wakeUpTime;
sprintf(tempStr, "%" PRIu64, lastWakeUpTime);
m_thread_list->SetItem(i, 8, tempStr);
// awake time in cycles
uint64 awakeTime = cafeThread->totalCycles;
sprintf(tempStr, "%" PRIu64, awakeTime);
m_thread_list->SetItem(i, 9, tempStr);
// thread name
const char* threadName = "NULL";
if (!cafeThread->threadName.IsNull())
threadName = cafeThread->threadName.GetPtr();
m_thread_list->SetItem(i, 10, threadName);
// GPR
sprintf(tempStr, "r3 %08x r4 %08x r5 %08x r6 %08x r7 %08x", _r(3), _r(4), _r(5), _r(6), _r(7));
m_thread_list->SetItem(i, 11, tempStr);
// waiting condition / extra info
coreinit::OSMutex* mutex = cafeThread->waitingForMutex;
if (mutex)
sprintf(tempStr, "Mutex 0x%08x (Held by thread 0x%08X Lock-Count: %d)", memory_getVirtualOffsetFromPointer(mutex), mutex->owner.GetMPTR(), (uint32)mutex->lockCount);
else
sprintf(tempStr, "");
// OSSetThreadCancelState
if (cafeThread->requestFlags & OSThread_t::REQUEST_FLAG_CANCEL)
strcat(tempStr, "[Cancel requested]");
m_thread_list->SetItem(i, 12, tempStr);
if(selected_thread != 0 && selected_thread == (long)threadItrMPTR)
m_thread_list->SetItemState(i, wxLIST_STATE_FOCUSED | wxLIST_STATE_SELECTED, wxLIST_STATE_FOCUSED | wxLIST_STATE_SELECTED);
}
srwlock_activeThreadList.UnlockWrite();
__OSUnlockScheduler();
}
m_thread_list->SetScrollPos(0, scrollPos, true);
}
void DebugPPCThreadsWindow::DumpStackTrace(OSThread_t* thread)
{
cemuLog_log(LogType::Force, "Dumping stack trace for thread {0:08x} LR: {1:08x}", memory_getVirtualOffsetFromPointer(thread), _swapEndianU32(thread->context.lr));
DebugLogStackTrace(thread, _swapEndianU32(thread->context.gpr[1]), true);
}
void DebugPPCThreadsWindow::PresentProfileResults(OSThread_t* thread, const std::unordered_map<VAddr, uint32>& samples)
{
std::vector<std::pair<VAddr, uint32>> sortedSamples;
// count samples
uint32 totalSampleCount = 0;
for (auto& sample : samples)
totalSampleCount += sample.second;
cemuLog_log(LogType::Force, "--- Thread {:08x} profile results with {:} samples captured ---",
MEMPTR<OSThread_t>(thread).GetMPTR(), totalSampleCount);
cemuLog_log(LogType::Force, "Exclusive time, grouped by function:");
// print samples grouped by function
sortedSamples.clear();
for (auto& sample : samples)
{
RPLStoredSymbol* symbol = rplSymbolStorage_getByClosestAddress(sample.first);
VAddr sampleAddr = sample.first;
if (symbol)
sampleAddr = symbol->address;
auto it = std::find_if(sortedSamples.begin(), sortedSamples.end(),
[sampleAddr](const std::pair<VAddr, uint32>& a) { return a.first == sampleAddr; });
if (it != sortedSamples.end())
it->second += sample.second;
else
sortedSamples.push_back(std::make_pair(sampleAddr, sample.second));
}
std::sort(sortedSamples.begin(), sortedSamples.end(),
[](const std::pair<VAddr, uint32>& a, const std::pair<VAddr, uint32>& b) { return a.second > b.second; });
for (auto& sample : sortedSamples)
{
if (sample.second < 3)
continue;
VAddr sampleAddr = sample.first;
RPLStoredSymbol* symbol = rplSymbolStorage_getByClosestAddress(sample.first);
std::string strName;
if (symbol)
{
strName = fmt::format("{}.{}+0x{:x}", (const char*)symbol->libName, (const char*)symbol->symbolName,
sampleAddr - symbol->address);
}
else
strName = "Unknown";
cemuLog_log(LogType::Force, "[{:08x}] {:8.2f}% (Samples: {:5}) Symbol: {}", sample.first,
(double)(sample.second * 100) / (double)totalSampleCount, sample.second, strName);
}
}
void DebugPPCThreadsWindow::ProfileThreadWorker(OSThread_t* thread)
{
wxProgressDialogManager progressDialog(this);
progressDialog.Create(_("Profiling thread"),
_("Capturing samples..."),
1000, // range
wxPD_CAN_SKIP);
std::unordered_map<VAddr, uint32> samples;
// loop for one minute
uint64 startTime = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
uint32 totalSampleCount = 0;
while (true)
{
// suspend thread
coreinit::OSSuspendThread(thread);
// wait until thread is not running anymore
__OSLockScheduler();
while (coreinit::OSIsThreadRunningNoLock(thread))
{
__OSUnlockScheduler();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
__OSLockScheduler();
}
uint32 sampleIP = thread->context.srr0;
__OSUnlockScheduler();
coreinit::OSResumeThread(thread);
// count sample
samples[sampleIP]++;
totalSampleCount++;
if ((totalSampleCount % 50) == 0)
{
wxString msg = formatWxString(_("Capturing samples... ({:})\nResults will be written to log.txt\n"), totalSampleCount);
if (totalSampleCount < 30000)
msg.Append(_("Click Skip button for early results with lower accuracy"));
else
msg.Append(_("Click Skip button to finish"));
progressDialog.Update(totalSampleCount * 1000 / 30000, msg);
if (progressDialog.IsCancelledOrSkipped())
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
PresentProfileResults(thread, samples);
progressDialog.Destroy();
}
void DebugPPCThreadsWindow::ProfileThread(OSThread_t* thread)
{
std::thread profileThread(&DebugPPCThreadsWindow::ProfileThreadWorker, this, thread);
profileThread.detach();
}
void DebugPPCThreadsWindow::OnThreadListPopupClick(wxCommandEvent& evt)
{
MPTR threadMPTR = (MPTR)(size_t) static_cast<wxMenu*>(evt.GetEventObject())->GetClientData();
OSThread_t* osThread = (OSThread_t*)memory_getPointerFromVirtualOffset(threadMPTR);
__OSLockScheduler();
if (!coreinit::__OSIsThreadActive(osThread))
{
__OSUnlockScheduler();
return;
}
__OSUnlockScheduler();
// handle command
switch (evt.GetId())
{
case THREADLIST_MENU_BOOST_PRIO_5:
osThread->basePriority = osThread->basePriority - 5;
break;
case THREADLIST_MENU_BOOST_PRIO_1:
osThread->basePriority = osThread->basePriority - 1;
break;
case THREADLIST_MENU_DECREASE_PRIO_5:
osThread->basePriority = osThread->basePriority + 5;
break;
case THREADLIST_MENU_DECREASE_PRIO_1:
osThread->basePriority = osThread->basePriority + 1;
break;
case THREADLIST_MENU_SUSPEND:
coreinit::OSSuspendThread(osThread);
break;
case THREADLIST_MENU_RESUME:
coreinit::OSResumeThread(osThread);
break;
case THREADLIST_MENU_DUMP_STACK_TRACE:
DumpStackTrace(osThread);
break;
case THREADLIST_MENU_PROFILE_THREAD:
ProfileThread(osThread);
break;
}
coreinit::__OSUpdateThreadEffectivePriority(osThread);
// update thread list
RefreshThreadList();
}
void DebugPPCThreadsWindow::OnThreadListRightClick(wxMouseEvent& event)
{
// Get the item index
int hitTestFlag;
int itemIndex = m_thread_list->HitTest(event.GetPosition(), hitTestFlag);
if (itemIndex == wxNOT_FOUND)
return;
// select item
m_thread_list->SetItemState(itemIndex, wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED);
long sel = m_thread_list->GetNextItem(-1, wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
if (sel != -1)
m_thread_list->SetItemState(sel, 0, wxLIST_STATE_SELECTED);
m_thread_list->SetItemState(itemIndex, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
// check if thread is still on the list of active threads
MPTR threadMPTR = (MPTR)m_thread_list->GetItemData(itemIndex);
__OSLockScheduler();
if (!coreinit::__OSIsThreadActive(MEMPTR<OSThread_t>(threadMPTR)))
{
__OSUnlockScheduler();
return;
}
__OSUnlockScheduler();
// create menu entry
wxMenu menu;
menu.SetClientData((void*)(size_t)threadMPTR);
menu.Append(THREADLIST_MENU_BOOST_PRIO_5, _("Boost priority (-5)"));
menu.Append(THREADLIST_MENU_BOOST_PRIO_1, _("Boost priority (-1)"));
menu.AppendSeparator();
menu.Append(THREADLIST_MENU_DECREASE_PRIO_5, _("Decrease priority (+5)"));
menu.Append(THREADLIST_MENU_DECREASE_PRIO_1, _("Decrease priority (+1)"));
menu.AppendSeparator();
menu.Append(THREADLIST_MENU_RESUME, _("Resume"));
menu.Append(THREADLIST_MENU_SUSPEND, _("Suspend"));
menu.AppendSeparator();
menu.Append(THREADLIST_MENU_DUMP_STACK_TRACE, _("Write stack trace to log"));
menu.Append(THREADLIST_MENU_PROFILE_THREAD, _("Profile thread"));
menu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(DebugPPCThreadsWindow::OnThreadListPopupClick), nullptr, this);
PopupMenu(&menu);
}
void DebugPPCThreadsWindow::Close()
{
this->Destroy();
}
| 16,621
|
C++
|
.cpp
| 433
| 33.685912
| 198
| 0.696581
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,017
|
TextureRelationWindow.cpp
|
cemu-project_Cemu/src/gui/windows/TextureRelationViewer/TextureRelationWindow.cpp
|
#include "gui/wxgui.h"
#include "TextureRelationWindow.h"
#include "Cafe/HW/Latte/Core/LatteTexture.h"
enum
{
// options
REFRESH_ID,
CLOSE_ID,
TEX_LIST_A_ID,
TEX_LIST_B_ID,
CHECKBOX_SHOW_ONLY_ACTIVE,
CHECKBOX_SHOW_VIEWS,
};
wxBEGIN_EVENT_TABLE(TextureRelationViewerWindow, wxFrame)
EVT_BUTTON(CLOSE_ID, TextureRelationViewerWindow::OnCloseButton)
EVT_BUTTON(REFRESH_ID, TextureRelationViewerWindow::OnRefreshButton)
EVT_CHECKBOX(CHECKBOX_SHOW_ONLY_ACTIVE, TextureRelationViewerWindow::OnCheckbox)
EVT_CHECKBOX(CHECKBOX_SHOW_VIEWS, TextureRelationViewerWindow::OnCheckbox)
EVT_CLOSE(TextureRelationViewerWindow::OnClose)
wxEND_EVENT_TABLE()
wxListCtrl* textureRelationListA;
bool isTextureViewerOpen = false;
void openTextureViewer(wxFrame& parentFrame)
{
if (isTextureViewerOpen)
return;
auto frame = new TextureRelationViewerWindow(parentFrame);
frame->Show(true);
}
TextureRelationViewerWindow::TextureRelationViewerWindow(wxFrame& parent)
: wxFrame(&parent, wxID_ANY, _("Texture cache"), wxDefaultPosition, wxSize(1000, 480), wxCLOSE_BOX | wxCLIP_CHILDREN | wxCAPTION | wxRESIZE_BORDER)
{
isTextureViewerOpen = true;
this->showOnlyActive = false;
this->showTextureViews = true;
wxPanel* mainPane = new wxPanel(this);
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
textureRelationListA = new wxListCtrl(mainPane, TEX_LIST_A_ID, wxPoint(0, 0), wxSize(1008, 440), wxLC_REPORT);
textureRelationListA->SetFont(wxFont(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, "Courier New"));//wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT));
// add columns
wxListItem colType;
sint32 columnIndex = 0;
colType.SetId(columnIndex); columnIndex++;
colType.SetText("Type");
colType.SetWidth(85);
textureRelationListA->InsertColumn(columnIndex-1, colType);
wxListItem colPhysAddr;
colPhysAddr.SetId(columnIndex); columnIndex++;
colPhysAddr.SetText("PhysAddr");
colPhysAddr.SetWidth(80);
textureRelationListA->InsertColumn(columnIndex-1, colPhysAddr);
wxListItem colPhysMipAddr;
colPhysMipAddr.SetId(columnIndex); columnIndex++;
colPhysMipAddr.SetText("MipPAddr");
colPhysMipAddr.SetWidth(80);
textureRelationListA->InsertColumn(columnIndex-1, colPhysMipAddr);
wxListItem colDim;
colDim.SetId(columnIndex); columnIndex++;
colDim.SetText("Dim");
colDim.SetWidth(80);
textureRelationListA->InsertColumn(columnIndex-1, colDim);
wxListItem colResolution;
colResolution.SetId(columnIndex); columnIndex++;
colResolution.SetText("Resolution");
colResolution.SetWidth(110);
textureRelationListA->InsertColumn(columnIndex-1, colResolution);
wxListItem colFormat;
colFormat.SetId(columnIndex); columnIndex++;
colFormat.SetText("Format");
colFormat.SetWidth(70);
textureRelationListA->InsertColumn(columnIndex-1, colFormat);
wxListItem colPitch;
colPitch.SetId(columnIndex); columnIndex++;
colPitch.SetText("Pitch");
colPitch.SetWidth(80);
textureRelationListA->InsertColumn(columnIndex-1, colPitch);
wxListItem colTilemode;
colTilemode.SetId(columnIndex); columnIndex++;
colTilemode.SetText("Tilemode");
colTilemode.SetWidth(80);
textureRelationListA->InsertColumn(columnIndex-1, colTilemode);
wxListItem colSliceRange;
colSliceRange.SetId(columnIndex); columnIndex++;
colSliceRange.SetText("SliceRange");
colSliceRange.SetWidth(90);
textureRelationListA->InsertColumn(columnIndex-1, colSliceRange);
wxListItem colMipRange;
colMipRange.SetId(columnIndex); columnIndex++;
colMipRange.SetText("MipRange");
colMipRange.SetWidth(90);
textureRelationListA->InsertColumn(columnIndex-1, colMipRange);
wxListItem colAge;
colAge.SetId(columnIndex); columnIndex++;
colAge.SetText("Last access");
colAge.SetWidth(90);
textureRelationListA->InsertColumn(columnIndex - 1, colAge);
wxListItem colOverwriteRes;
colOverwriteRes.SetId(columnIndex); columnIndex++;
colOverwriteRes.SetText("OverwriteRes");
colOverwriteRes.SetWidth(110);
textureRelationListA->InsertColumn(columnIndex - 1, colOverwriteRes);
wxBoxSizer* sizerBottom = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(textureRelationListA, 1, wxEXPAND | wxBOTTOM, 0);
wxButton* button = new wxButton(mainPane, REFRESH_ID, _("Refresh"), wxPoint(0, 0), wxSize(80, 26));
sizerBottom->Add(button, 0, wxBOTTOM | wxTOP | wxLEFT, 10);
wxCheckBox* checkboxShowOnlyActive = new wxCheckBox(mainPane, CHECKBOX_SHOW_ONLY_ACTIVE, _("Show only active"), wxPoint(0, 0), wxSize(110, 26));
sizerBottom->Add(checkboxShowOnlyActive, 0, wxBOTTOM | wxTOP | wxLEFT, 10);
wxCheckBox* checkboxShowViews = new wxCheckBox(mainPane, CHECKBOX_SHOW_VIEWS, _("Show views"), wxPoint(0, 0), wxSize(90, 26));
sizerBottom->Add(checkboxShowViews, 0, wxBOTTOM | wxTOP | wxLEFT, 10);
checkboxShowViews->SetValue(true);
textureRelationListA->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(TextureRelationViewerWindow::OnTextureListRightClick), NULL, this);
sizer->Add(
sizerBottom,
0, // vertically unstretchable
wxALIGN_LEFT);
mainPane->SetSizer(sizer);
RefreshTextureList();
wxFrame::SetBackgroundColour(*wxWHITE);
}
TextureRelationViewerWindow::~TextureRelationViewerWindow()
{
isTextureViewerOpen = false;
}
void TextureRelationViewerWindow::OnCloseButton(wxCommandEvent& event)
{
Close();
}
void TextureRelationViewerWindow::OnRefreshButton(wxCommandEvent& event)
{
RefreshTextureList();
}
void TextureRelationViewerWindow::OnCheckbox(wxCommandEvent& event)
{
if (event.GetId() == CHECKBOX_SHOW_ONLY_ACTIVE)
{
showOnlyActive = event.IsChecked();
RefreshTextureList();
}
else if (event.GetId() == CHECKBOX_SHOW_VIEWS)
{
showTextureViews = event.IsChecked();
RefreshTextureList();
}
}
void TextureRelationViewerWindow::OnClose(wxCloseEvent& event)
{
Close();
}
void TextureRelationViewerWindow::_setTextureRelationListItemTexture(wxListCtrl* uiList, sint32 rowIndex, struct LatteTextureInformation* texInfo)
{
char tempStr[512];
// count number of alternative views for base view
sint32 alternativeViewCount = texInfo->alternativeViewCount;
if (texInfo->isUpdatedOnGPU)
sprintf(tempStr, "TEXTURE*");
else
sprintf(tempStr, "TEXTURE");
if (alternativeViewCount > 0)
{
sprintf(tempStr + strlen(tempStr), "(%d)", alternativeViewCount + 1);
}
uint32 bgColor = 0xFFEEEEEE;
wxListItem item;
item.SetId(rowIndex);
item.SetText(tempStr);
item.SetBackgroundColour(wxColour(bgColor));
uiList->InsertItem(item);
sint32 columnIndex = 1;
// phys address
sprintf(tempStr, "%08X", texInfo->physAddress);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// phys mip address
sprintf(tempStr, "%08X", texInfo->physMipAddress);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// dim
if (texInfo->dim == Latte::E_DIM::DIM_2D)
strcpy(tempStr, "2D");
else if (texInfo->dim == Latte::E_DIM::DIM_2D_ARRAY)
strcpy(tempStr, "2D_ARRAY");
else if (texInfo->dim == Latte::E_DIM::DIM_3D)
strcpy(tempStr, "3D");
else if (texInfo->dim == Latte::E_DIM::DIM_CUBEMAP)
strcpy(tempStr, "CUBEMAP");
else if (texInfo->dim == Latte::E_DIM::DIM_1D)
strcpy(tempStr, "1D");
else if (texInfo->dim == Latte::E_DIM::DIM_2D_MSAA)
strcpy(tempStr, "2D_MSAA");
else if (texInfo->dim == Latte::E_DIM::DIM_2D_ARRAY_MSAA)
strcpy(tempStr, "2D_MS_ARRAY");
else
strcpy(tempStr, "UKN");
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// resolution
if (texInfo->depth == 1)
sprintf(tempStr, "%dx%d", texInfo->width, texInfo->height);
else
sprintf(tempStr, "%dx%dx%d", texInfo->width, texInfo->height, texInfo->depth);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// format
if(texInfo->isDepth)
sprintf(tempStr, "%04x(d)", (uint32)texInfo->format);
else
sprintf(tempStr, "%04x", (uint32)texInfo->format);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// pitch
sprintf(tempStr, "%d", texInfo->pitch);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// tilemode
sprintf(tempStr, "%d", (int)texInfo->tileMode);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// sliceRange
sprintf(tempStr, "");
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// mipRange
if(texInfo->mipLevels == 1)
sprintf(tempStr, "1 mip");
else
sprintf(tempStr, "%d mips", texInfo->mipLevels);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// last access
sprintf(tempStr, "%ds", (GetTickCount() - texInfo->lastAccessTick + 499) / 1000);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// overwrite resolution
strcpy(tempStr, "");
if (texInfo->overwriteInfo.hasResolutionOverwrite)
{
if(texInfo->overwriteInfo.depth != 1 || texInfo->depth != 1)
sprintf(tempStr, "%dx%dx%d", texInfo->overwriteInfo.width, texInfo->overwriteInfo.height, texInfo->overwriteInfo.depth);
else
sprintf(tempStr, "%dx%d", texInfo->overwriteInfo.width, texInfo->overwriteInfo.height);
}
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
}
void TextureRelationViewerWindow::_setTextureRelationListItemView(wxListCtrl* uiList, sint32 rowIndex, struct LatteTextureInformation* texInfo, struct LatteTextureViewInformation* viewInfo)
{
char tempStr[512];
// count number of alternative views
sint32 alternativeViewCount = 0; // todo
// set type string
if(alternativeViewCount == 0)
sprintf(tempStr, "> VIEW");
else
sprintf(tempStr, "> VIEW(%d)", alternativeViewCount+1);
// find and handle highlight entry
uint32 bgColor = 0xFFDDDDDD;
wxListItem item;
item.SetId(rowIndex);
item.SetText(tempStr);
item.SetBackgroundColour(wxColour(bgColor));
uiList->InsertItem(item);
//uiList->SetItemPtrData(item, (wxUIntPtr)viewInfo);
sint32 columnIndex = 1;
// phys address
sprintf(tempStr, "");
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// phys mip address
sprintf(tempStr, "");
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// dim
if (viewInfo->dim == Latte::E_DIM::DIM_2D)
strcpy(tempStr, "2D");
else if (viewInfo->dim == Latte::E_DIM::DIM_2D_ARRAY)
strcpy(tempStr, "2D_ARRAY");
else if (viewInfo->dim == Latte::E_DIM::DIM_3D)
strcpy(tempStr, "3D");
else if (viewInfo->dim == Latte::E_DIM::DIM_CUBEMAP)
strcpy(tempStr, "CUBEMAP");
else if (viewInfo->dim == Latte::E_DIM::DIM_1D)
strcpy(tempStr, "1D");
else if (viewInfo->dim == Latte::E_DIM::DIM_2D_MSAA)
strcpy(tempStr, "2D_MSAA");
else if (viewInfo->dim == Latte::E_DIM::DIM_2D_ARRAY_MSAA)
strcpy(tempStr, "2D_ARRAY_MSAA");
else
strcpy(tempStr, "UKN");
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// resolution
tempStr[0] = '\0';
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// format
sprintf(tempStr, "%04x", (uint32)viewInfo->format);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// pitch
tempStr[0] = '\0';
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// tilemode
tempStr[0] = '\0';
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// sliceRange
sprintf(tempStr, "%d-%d", viewInfo->firstSlice, viewInfo->firstSlice+ viewInfo->numSlice-1);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// mipRange
sprintf(tempStr, "%d-%d", viewInfo->firstMip, viewInfo->firstMip + viewInfo->numMip - 1);
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
// last access
tempStr[0] = '\0';
uiList->SetItem(rowIndex, columnIndex, tempStr);
columnIndex++;
}
void TextureRelationViewerWindow::RefreshTextureList()
{
int scrollPos = textureRelationListA->GetScrollPos(wxVERTICAL);
textureRelationListA->DeleteAllItems();
std::vector<LatteTextureInformation> texCache = LatteTexture_QueryCacheInfo();
// sort by physAddr in ascending order
for (sint32 i1 = 0; i1 < texCache.size(); i1++)
{
for (sint32 i2 = i1+1; i2 < texCache.size(); i2++)
{
if (texCache[i1].physAddress > texCache[i2].physAddress)
{
std::swap(texCache[i1], texCache[i2]);
}
}
}
textureRelationListA->Freeze();
sint32 rowIndex = 0;
uint32 currentTick = GetTickCount();
for (auto& tex : texCache)
{
uint32 timeSinceLastAccess = currentTick - tex.lastAccessTick;
if (showOnlyActive && timeSinceLastAccess > 3000)
continue; // hide textures which haven't been updated in more than 3 seconds
_setTextureRelationListItemTexture(textureRelationListA, rowIndex, &tex);
rowIndex++;
if (showTextureViews)
{
for (auto& view : tex.views)
{
_setTextureRelationListItemView(textureRelationListA, rowIndex, &tex, &view);
rowIndex++;
}
}
}
textureRelationListA->Thaw();
long itemCount = textureRelationListA->GetItemCount();
if (itemCount > 0)
textureRelationListA->EnsureVisible(std::min<long>(itemCount - 1, scrollPos + textureRelationListA->GetCountPerPage() - 1));
}
void TextureRelationViewerWindow::OnTextureListRightClick(wxMouseEvent& event)
{
}
void TextureRelationViewerWindow::Close()
{
this->Destroy();
}
| 13,029
|
C++
|
.cpp
| 366
| 33.221311
| 189
| 0.761384
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,018
|
CafeSystem.cpp
|
cemu-project_Cemu/src/Cafe/CafeSystem.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "gui/wxgui.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/GameProfile/GameProfile.h"
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "audio/IAudioAPI.h"
#include "audio/IAudioInputAPI.h"
#include "config/ActiveSettings.h"
#include "Cafe/TitleList/GameInfo.h"
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "util/helpers/SystemException.h"
#include "Common/cpu_features.h"
#include "input/InputManager.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/TitleList/TitleList.h"
#include "Cafe/TitleList/GameInfo.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/Filesystem/FST/FST.h"
#include "Common/FileStream.h"
#include "GamePatch.h"
#include "HW/Espresso/Debugger/GDBStub.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
#include "Cafe/IOSU/legacy/iosu_act.h"
#include "Cafe/IOSU/legacy/iosu_fpd.h"
#include "Cafe/IOSU/legacy/iosu_crypto.h"
#include "Cafe/IOSU/legacy/iosu_mcp.h"
#include "Cafe/IOSU/legacy/iosu_acp.h"
#include "Cafe/IOSU/legacy/iosu_boss.h"
#include "Cafe/IOSU/legacy/iosu_nim.h"
#include "Cafe/IOSU/PDM/iosu_pdm.h"
#include "Cafe/IOSU/ccr_nfc/iosu_ccr_nfc.h"
// IOSU initializer functions
#include "Cafe/IOSU/kernel/iosu_kernel.h"
#include "Cafe/IOSU/fsa/iosu_fsa.h"
#include "Cafe/IOSU/ODM/iosu_odm.h"
// Cafe OS initializer and shutdown functions
#include "Cafe/OS/libs/avm/avm.h"
#include "Cafe/OS/libs/drmapp/drmapp.h"
#include "Cafe/OS/libs/TCL/TCL.h"
#include "Cafe/OS/libs/snd_user/snd_user.h"
#include "Cafe/OS/libs/h264_avc/h264dec.h"
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/OS/libs/gx2/GX2_Misc.h"
#include "Cafe/OS/libs/mic/mic.h"
#include "Cafe/OS/libs/nfc/nfc.h"
#include "Cafe/OS/libs/ntag/ntag.h"
#include "Cafe/OS/libs/nn_aoc/nn_aoc.h"
#include "Cafe/OS/libs/nn_pdm/nn_pdm.h"
#include "Cafe/OS/libs/nn_cmpt/nn_cmpt.h"
#include "Cafe/OS/libs/nn_ccr/nn_ccr.h"
#include "Cafe/OS/libs/nn_temp/nn_temp.h"
#include "Cafe/OS/libs/nn_save/nn_save.h"
// HW interfaces
#include "Cafe/HW/SI/si.h"
// dependency to be removed
#include "gui/guiWrapper.h"
#include <time.h>
#if BOOST_OS_LINUX
#include <sys/sysinfo.h>
#elif BOOST_OS_MACOS
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
std::string _pathToExecutable;
std::string _pathToBaseExecutable;
RPLModule* applicationRPX = nullptr;
uint32 currentBaseApplicationHash = 0;
uint32 currentUpdatedApplicationHash = 0;
bool isLaunchTypeELF = false;
MPTR _entryPoint = MPTR_NULL;
uint32 generateHashFromRawRPXData(uint8* rpxData, sint32 size)
{
uint32 h = 0x3416DCBF;
for (sint32 i = 0; i < size; i++)
{
uint32 c = rpxData[i];
h = (h << 3) | (h >> 29);
h += c;
}
return h;
}
bool ScanForRPX()
{
bool rpxFound = false;
sint32 fscStatus = 0;
FSCVirtualFile* fscDirItr = fsc_openDirIterator("/internal/current_title/code/", &fscStatus);
if (fscDirItr)
{
FSCDirEntry dirEntry;
while (fsc_nextDir(fscDirItr, &dirEntry))
{
sint32 dirItrPathLen = strlen(dirEntry.path);
if (dirItrPathLen < 4)
continue;
if (boost::iequals(dirEntry.path + dirItrPathLen - 4, ".rpx"))
{
rpxFound = true;
_pathToExecutable = fmt::format("/internal/current_title/code/{}", dirEntry.path);
break;
}
}
fsc_close(fscDirItr);
}
return rpxFound;
}
void SetEntryPoint(MPTR entryPoint)
{
_entryPoint = entryPoint;
}
// load executable into virtual memory and set entrypoint
void LoadMainExecutable()
{
isLaunchTypeELF = false;
// when launching from a disc image _pathToExecutable is initially empty
if (_pathToExecutable.empty())
{
// try to get the RPX path from the meta files
// todo
// otherwise search for first file with .rpx extension in the code folder
if (!ScanForRPX())
{
cemuLog_log(LogType::Force, "Unable to find RPX executable");
cemuLog_waitForFlush();
cemu_assert(false);
}
}
// extract and load RPX
uint32 rpxSize = 0;
uint8* rpxData = fsc_extractFile(_pathToExecutable.c_str(), &rpxSize);
if (rpxData == nullptr)
{
cemuLog_log(LogType::Force, "Failed to load \"{}\"", _pathToExecutable);
cemuLog_waitForFlush();
cemu_assert(false);
}
currentUpdatedApplicationHash = generateHashFromRawRPXData(rpxData, rpxSize);
// determine if this file is an ELF
const uint8 elfHeaderMagic[9] = { 0x7F,0x45,0x4C,0x46,0x01,0x02,0x01,0x00,0x00 };
if (rpxSize >= 10 && memcmp(rpxData, elfHeaderMagic, sizeof(elfHeaderMagic)) == 0)
{
// ELF
SetEntryPoint(ELF_LoadFromMemory(rpxData, rpxSize, _pathToExecutable.c_str()));
isLaunchTypeELF = true;
}
else
{
// RPX
RPLLoader_AddDependency(_pathToExecutable.c_str());
applicationRPX = RPLLoader_LoadFromMemory(rpxData, rpxSize, (char*)_pathToExecutable.c_str());
if (!applicationRPX)
{
wxMessageBox(_("Failed to run this title because the executable is damaged"));
cemuLog_createLogFile(false);
cemuLog_waitForFlush();
exit(0);
}
RPLLoader_SetMainModule(applicationRPX);
SetEntryPoint(RPLLoader_GetModuleEntrypoint(applicationRPX));
}
free(rpxData);
// get RPX hash of game without update
uint32 baseRpxSize = 0;
uint8* baseRpxData = fsc_extractFile(!_pathToBaseExecutable.empty() ? _pathToBaseExecutable.c_str() : _pathToExecutable.c_str(), &baseRpxSize, FSC_PRIORITY_BASE);
if (baseRpxData == nullptr)
{
currentBaseApplicationHash = currentUpdatedApplicationHash;
}
else
{
currentBaseApplicationHash = generateHashFromRawRPXData(baseRpxData, baseRpxSize);
}
free(baseRpxData);
debug_printf("RPXHash: 0x%08x\n", currentBaseApplicationHash);
}
fs::path getTitleSavePath()
{
const uint64 titleId = CafeSystem::GetForegroundTitleId();
return ActiveSettings::GetMlcPath("usr/save/{:08X}/{:08X}/user/", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
void InfoLog_TitleLoaded()
{
cemuLog_createLogFile(false);
uint64 titleId = CafeSystem::GetForegroundTitleId();
cemuLog_log(LogType::Force, "------- Loaded title -------");
cemuLog_log(LogType::Force, "TitleId: {:08x}-{:08x}", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
cemuLog_log(LogType::Force, "TitleVersion: v{}", CafeSystem::GetForegroundTitleVersion());
CafeConsoleRegion region = CafeSystem::GetForegroundTitleRegion();
if(region == CafeConsoleRegion::JPN)
cemuLog_log(LogType::Force, "TitleRegion: JP");
else if (region == CafeConsoleRegion::EUR)
cemuLog_log(LogType::Force, "TitleRegion: EU");
else if (region == CafeConsoleRegion::USA)
cemuLog_log(LogType::Force, "TitleRegion: US");
fs::path effectiveSavePath = getTitleSavePath();
std::error_code ec;
const bool saveDirExists = fs::exists(effectiveSavePath, ec);
cemuLog_log(LogType::Force, "Save path: {}{}", _pathToUtf8(effectiveSavePath), saveDirExists ? "" : " (not present)");
// log shader cache name
cemuLog_log(LogType::Force, "Shader cache file: shaderCache/transferable/{:016x}.bin", titleId);
// game profile info
std::string gameProfilePath;
if(g_current_game_profile->IsDefaultProfile())
gameProfilePath = fmt::format("gameProfiles/default/{:016x}.ini", titleId);
else
gameProfilePath = fmt::format("gameProfiles/{:016x}.ini", titleId);
cemuLog_log(LogType::Force, "gameprofile path: {}", g_current_game_profile->IsLoaded() ? gameProfilePath : std::string(" (not present)"));
// rpx hash of updated game
cemuLog_log(LogType::Force, "RPX hash (updated): {:08x}", currentUpdatedApplicationHash);
cemuLog_log(LogType::Force, "RPX hash (base): {:08x}", currentBaseApplicationHash);
memory_logModifiedMemoryRanges();
}
void InfoLog_PrintActiveSettings()
{
const auto& config = GetConfig();
cemuLog_log(LogType::Force, "------- Active settings -------");
// settings to log:
cemuLog_log(LogType::Force, "CPU-Mode: {}{}", fmt::format("{}", ActiveSettings::GetCPUMode()).c_str(), g_current_game_profile->GetCPUMode().has_value() ? " (gameprofile)" : "");
cemuLog_log(LogType::Force, "Load shared libraries: {}{}", ActiveSettings::LoadSharedLibrariesEnabled() ? "true" : "false", g_current_game_profile->ShouldLoadSharedLibraries().has_value() ? " (gameprofile)" : "");
cemuLog_log(LogType::Force, "Use precompiled shaders: {}{}", fmt::format("{}", ActiveSettings::GetPrecompiledShadersOption()), g_current_game_profile->GetPrecompiledShadersState().has_value() ? " (gameprofile)" : "");
cemuLog_log(LogType::Force, "Full sync at GX2DrawDone: {}", ActiveSettings::WaitForGX2DrawDoneEnabled() ? "true" : "false");
cemuLog_log(LogType::Force, "Strict shader mul: {}", g_current_game_profile->GetAccurateShaderMul() == AccurateShaderMulOption::True ? "true" : "false");
if (ActiveSettings::GetGraphicsAPI() == GraphicAPI::kVulkan)
{
cemuLog_log(LogType::Force, "Async compile: {}", GetConfig().async_compile.GetValue() ? "true" : "false");
if(!GetConfig().vk_accurate_barriers.GetValue())
cemuLog_log(LogType::Force, "Accurate barriers are disabled!");
}
cemuLog_log(LogType::Force, "Console language: {}", stdx::to_underlying(config.console_language.GetValue()));
}
struct SharedDataEntry
{
/* +0x00 */ uint32be name;
/* +0x04 */ uint32be fileType; // 2 = font
/* +0x08 */ uint32be kernelFilenamePtr;
/* +0x0C */ MEMPTR<void> data;
/* +0x10 */ uint32be size;
/* +0x14 */ uint32be ukn14;
/* +0x18 */ uint32be ukn18;
};
struct
{
uint32 name;
uint32 fileType;
const char* fileName;
const char* resourcePath;
const char* mlcPath;
}shareddataDef[] =
{
0xFFCAFE01, 2, "CafeCn.ttf", "resources/sharedFonts/CafeCn.ttf", "sys/title/0005001b/10042400/content/CafeCn.ttf",
0xFFCAFE02, 2, "CafeKr.ttf", "resources/sharedFonts/CafeKr.ttf", "sys/title/0005001b/10042400/content/CafeKr.ttf",
0xFFCAFE03, 2, "CafeStd.ttf", "resources/sharedFonts/CafeStd.ttf", "sys/title/0005001b/10042400/content/CafeStd.ttf",
0xFFCAFE04, 2, "CafeTw.ttf", "resources/sharedFonts/CafeTw.ttf", "sys/title/0005001b/10042400/content/CafeTw.ttf"
};
static_assert(sizeof(SharedDataEntry) == 0x1C);
uint32 LoadSharedData()
{
// check if font files are dumped
bool hasAllShareddataFiles = true;
for (sint32 i = 0; i < sizeof(shareddataDef) / sizeof(shareddataDef[0]); i++)
{
bool existsInMLC = fs::exists(ActiveSettings::GetMlcPath(shareddataDef[i].mlcPath));
bool existsInResources = fs::exists(ActiveSettings::GetDataPath(shareddataDef[i].resourcePath));
if (!existsInMLC && !existsInResources)
{
cemuLog_log(LogType::Force, "Shared font {} is not present", shareddataDef[i].fileName);
hasAllShareddataFiles = false;
break;
}
}
sint32 numEntries = sizeof(shareddataDef) / sizeof(shareddataDef[0]);
if (hasAllShareddataFiles)
{
// all shareddata font files are present -> load them
SharedDataEntry* shareddataTable = (SharedDataEntry*)memory_getPointerFromVirtualOffset(0xF8000000);
memset(shareddataTable, 0, sizeof(SharedDataEntry) * numEntries);
uint8* dataWritePtr = memory_getPointerFromVirtualOffset(0xF8000000 + sizeof(SharedDataEntry) * numEntries);
// setup entries
for (sint32 i = 0; i < numEntries; i++)
{
// try to read font from MLC first
auto path = ActiveSettings::GetMlcPath(shareddataDef[i].mlcPath);
FileStream* fontFile = FileStream::openFile2(path);
// alternatively fall back to our shared fonts
if (!fontFile)
{
path = ActiveSettings::GetDataPath(shareddataDef[i].resourcePath);
fontFile = FileStream::openFile2(path);
}
if (!fontFile)
{
cemuLog_log(LogType::Force, "Failed to load shared font {}", shareddataDef[i].fileName);
continue;
}
uint32 fileSize = fontFile->GetSize();
fontFile->readData(dataWritePtr, fileSize);
delete fontFile;
// setup entry
shareddataTable[i].name = shareddataDef[i].name;
shareddataTable[i].fileType = shareddataDef[i].fileType;
shareddataTable[i].kernelFilenamePtr = 0x00000000;
shareddataTable[i].data = dataWritePtr;
shareddataTable[i].size = fileSize;
shareddataTable[i].ukn14 = 0x00000000;
shareddataTable[i].ukn18 = 0x00000000;
// advance write offset and pad to 16 byte alignment
dataWritePtr += ((fileSize + 15) & ~15);
}
cemuLog_log(LogType::Force, "COS: System fonts found. Generated shareddata ({}KB)", (uint32)(dataWritePtr - (uint8*)shareddataTable) / 1024);
return memory_getVirtualOffsetFromPointer(dataWritePtr);
}
// alternative method: load RAM dump
const auto path = ActiveSettings::GetUserDataPath("shareddata.bin");
FileStream* ramDumpFile = FileStream::openFile2(path);
if (ramDumpFile)
{
ramDumpFile->readData(memory_getPointerFromVirtualOffset(0xF8000000), 0x02000000);
delete ramDumpFile;
return (mmuRange_SHARED_AREA.getBase() + 0x02000000);
}
return mmuRange_SHARED_AREA.getBase() + sizeof(SharedDataEntry) * numEntries;
}
void cemu_initForGame()
{
gui_updateWindowTitles(false, true, 0.0);
// input manager apply game profile
InputManager::instance().apply_game_profile();
// log info for launched title
InfoLog_TitleLoaded();
// determine cycle offset since 1.1.2000
uint64 secondsSince2000_UTC = (uint64)(time(NULL) - 946684800);
ppcCyclesSince2000_UTC = secondsSince2000_UTC * (uint64)ESPRESSO_CORE_CLOCK;
time_t theTime = (time(NULL) - 946684800);
{
tm* lt = localtime(&theTime);
#if BOOST_OS_WINDOWS
theTime = _mkgmtime(lt);
#else
theTime = timegm(lt);
#endif
}
ppcCyclesSince2000 = theTime * (uint64)ESPRESSO_CORE_CLOCK;
ppcCyclesSince2000TimerClock = ppcCyclesSince2000 / 20ULL;
PPCTimer_start();
// this must happen after the RPX/RPL files are mapped to memory (coreinit sets up heaps so that they don't overwrite RPX/RPL data)
osLib_load();
// link all modules
uint32 linkTimeStart = GetTickCount();
RPLLoader_UpdateDependencies();
RPLLoader_Link();
RPLLoader_NotifyControlPassedToApplication();
uint32 linkTime = GetTickCount() - linkTimeStart;
cemuLog_log(LogType::Force, "RPL link time: {}ms", linkTime);
// for HBL ELF: Setup OS-specifics struct
if (isLaunchTypeELF)
{
memory_writeU32(0x801500, rpl_mapHLEImport(nullptr, "coreinit", "OSDynLoad_Acquire", true));
memory_writeU32(0x801504, rpl_mapHLEImport(nullptr, "coreinit", "OSDynLoad_FindExport", true));
}
else
{
// replace any known function signatures with our HLE implementations and patch bugs in the games
GamePatch_scan();
}
LatteGPUState.isDRCPrimary = ActiveSettings::DisplayDRCEnabled();
InfoLog_PrintActiveSettings();
Latte_Start();
// check for debugger entrypoint bp
if (g_gdbstub)
{
g_gdbstub->HandleEntryStop(_entryPoint);
g_gdbstub->Initialize();
}
debugger_handleEntryBreakpoint(_entryPoint);
// load graphic packs
cemuLog_log(LogType::Force, "------- Activate graphic packs -------");
GraphicPack2::ActivateForCurrentTitle();
// print audio log
IAudioAPI::PrintLogging();
IAudioInputAPI::PrintLogging();
// everything initialized
cemuLog_log(LogType::Force, "------- Run title -------");
// wait till GPU thread is initialized
while (g_isGPUInitFinished == false) std::this_thread::sleep_for(std::chrono::milliseconds(50));
// init initial thread
OSThread_t* initialThread = coreinit::OSGetDefaultThread(1);
coreinit::OSSetThreadPriority(initialThread, 16);
coreinit::OSRunThread(initialThread, PPCInterpreter_makeCallableExportDepr(coreinit_start), 0, nullptr);
// init AX and start AX I/O thread
snd_core::AXOut_init();
}
namespace CafeSystem
{
void InitVirtualMlcStorage();
void MlcStorageMountTitle(TitleInfo& titleInfo);
void MlcStorageUnmountAllTitles();
static bool s_initialized = false;
static SystemImplementation* s_implementation{nullptr};
bool sLaunchModeIsStandalone = false;
std::optional<std::vector<std::string>> s_overrideArgs;
bool sSystemRunning = false;
TitleId sForegroundTitleId = 0;
GameInfo2 sGameInfo_ForegroundTitle;
static void _CheckForWine()
{
#if BOOST_OS_WINDOWS
const HMODULE hmodule = GetModuleHandleA("ntdll.dll");
if (!hmodule)
return;
const auto pwine_get_version = (const char*(__cdecl*)())GetProcAddress(hmodule, "wine_get_version");
if (pwine_get_version)
{
cemuLog_log(LogType::Force, "Wine version: {}", pwine_get_version());
}
#endif
}
void logCPUAndMemoryInfo()
{
std::string cpuName = g_CPUFeatures.GetCPUName();
if (!cpuName.empty())
cemuLog_log(LogType::Force, "CPU: {}", cpuName);
#if BOOST_OS_WINDOWS
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
uint32 memoryInMB = (uint32)(statex.ullTotalPhys / 1024LL / 1024LL);
cemuLog_log(LogType::Force, "RAM: {}MB", memoryInMB);
#elif BOOST_OS_LINUX
struct sysinfo info {};
sysinfo(&info);
cemuLog_log(LogType::Force, "RAM: {}MB", ((static_cast<uint64_t>(info.totalram) * info.mem_unit) / 1024LL / 1024LL));
#elif BOOST_OS_MACOS
int64_t totalRam;
size_t size = sizeof(totalRam);
int result = sysctlbyname("hw.memsize", &totalRam, &size, NULL, 0);
if (result == 0)
cemuLog_log(LogType::Force, "RAM: {}MB", (totalRam / 1024LL / 1024LL));
#endif
}
#if BOOST_OS_WINDOWS
std::string GetWindowsNamedVersion(uint32& buildNumber)
{
char productName[256];
HKEY hKey;
DWORD dwType = REG_SZ;
DWORD dwSize = sizeof(productName);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
{
if (RegQueryValueExA(hKey, "ProductName", NULL, &dwType, (LPBYTE)productName, &dwSize) != ERROR_SUCCESS)
strcpy(productName, "Windows");
RegCloseKey(hKey);
}
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
buildNumber = osvi.dwBuildNumber;
return std::string(productName);
}
#endif
void logPlatformInfo()
{
std::string buffer;
const char* platform = NULL;
#if BOOST_OS_WINDOWS
uint32 buildNumber;
std::string windowsVersionName = GetWindowsNamedVersion(buildNumber);
buffer = fmt::format("{} (Build {})", windowsVersionName, buildNumber);
platform = buffer.c_str();
#elif BOOST_OS_LINUX
if (getenv ("APPIMAGE"))
platform = "Linux (AppImage)";
else if (getenv ("SNAP"))
platform = "Linux (Snap)";
else if (platform = getenv ("container"))
{
if (strcmp (platform, "flatpak") == 0)
platform = "Linux (Flatpak)";
}
else
platform = "Linux";
#elif BOOST_OS_MACOS
platform = "MacOS";
#endif
cemuLog_log(LogType::Force, "Platform: {}", platform);
}
static std::vector<IOSUModule*> s_iosuModules =
{
// entries in this list are ordered by initialization order. Shutdown in reverse order
iosu::kernel::GetModule(),
iosu::acp::GetModule(),
iosu::fpd::GetModule(),
iosu::pdm::GetModule(),
iosu::ccr_nfc::GetModule(),
};
// initialize all subsystems which are persistent and don't depend on a game running
void Initialize()
{
if (s_initialized)
return;
s_initialized = true;
// init core systems
cemuLog_log(LogType::Force, "------- Init {} -------", BUILD_VERSION_WITH_NAME_STRING);
fsc_init();
memory_init();
cemuLog_log(LogType::Force, "Init Wii U memory space (base: 0x{:016x})", (size_t)memory_base);
PPCCore_init();
RPLLoader_InitState();
cemuLog_log(LogType::Force, "mlc01 path: {}", _pathToUtf8(ActiveSettings::GetMlcPath()));
_CheckForWine();
// CPU and RAM info
logCPUAndMemoryInfo();
logPlatformInfo();
cemuLog_log(LogType::Force, "Used CPU extensions: {}", g_CPUFeatures.GetCommaSeparatedExtensionList());
// misc systems
rplSymbolStorage_init();
// allocate memory for all SysAllocators
// must happen before COS module init, but also before iosu::kernel::Initialize()
SysAllocatorContainer::GetInstance().Initialize();
// init IOSU modules
for(auto& module : s_iosuModules)
module->SystemLaunch();
// init IOSU (deprecated manual init)
iosuCrypto_init();
iosu::fsa::Initialize();
iosuIoctl_init();
iosuAct_init_depr();
iosu::act::Initialize();
iosu::iosuMcp_init();
iosu::mcp::Init();
iosu::iosuAcp_init();
iosu::boss_init();
iosu::nim::Initialize();
iosu::odm::Initialize();
// init Cafe OS
avm::Initialize();
drmapp::Initialize();
TCL::Initialize();
nn::cmpt::Initialize();
nn::ccr::Initialize();
nn::temp::Initialize();
nn::aoc::Initialize();
nn::pdm::Initialize();
snd::user::Initialize();
H264::Initialize();
snd_core::Initialize();
mic::Initialize();
nfc::Initialize();
ntag::Initialize();
// init hardware register interfaces
HW_SI::Initialize();
}
void SetImplementation(SystemImplementation* impl)
{
s_implementation = impl;
}
void Shutdown()
{
cemu_assert_debug(s_initialized);
// if a title is running, shut it down
if (sSystemRunning)
ShutdownTitle();
// shutdown persistent subsystems (deprecated manual shutdown)
iosu::odm::Shutdown();
iosu::act::Stop();
iosu::mcp::Shutdown();
iosu::fsa::Shutdown();
// shutdown IOSU modules
for(auto it = s_iosuModules.rbegin(); it != s_iosuModules.rend(); ++it)
(*it)->SystemExit();
s_initialized = false;
}
std::string GetInternalVirtualCodeFolder()
{
return "/internal/current_title/code/";
}
void MountBaseDirectories()
{
const auto mlc = ActiveSettings::GetMlcPath();
FSCDeviceHostFS_Mount("/cemuBossStorage/", _pathToUtf8(mlc / "usr/boss/"), FSC_PRIORITY_BASE);
FSCDeviceHostFS_Mount("/vol/storage_mlc01/", _pathToUtf8(mlc / ""), FSC_PRIORITY_BASE);
}
void UnmountBaseDirectories()
{
fsc_unmount("/vol/storage_mlc01/", FSC_PRIORITY_BASE);
fsc_unmount("/cemuBossStorage/", FSC_PRIORITY_BASE);
}
PREPARE_STATUS_CODE LoadAndMountForegroundTitle(TitleId titleId)
{
cemuLog_log(LogType::Force, "Mounting title {:016x}", (uint64)titleId);
sGameInfo_ForegroundTitle = CafeTitleList::GetGameInfo(titleId);
if (!sGameInfo_ForegroundTitle.IsValid())
{
cemuLog_log(LogType::Force, "Mounting failed: Game meta information is either missing, inaccessible or not valid (missing or invalid .xml files in code and meta folder)");
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
}
// check base
TitleInfo& titleBase = sGameInfo_ForegroundTitle.GetBase();
if (!titleBase.IsValid())
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
if(!titleBase.ParseXmlInfo())
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
cemuLog_log(LogType::Force, "Base: {}", titleBase.GetPrintPath());
// mount base
if (!titleBase.Mount("/vol/content", "content", FSC_PRIORITY_BASE) || !titleBase.Mount(GetInternalVirtualCodeFolder(), "code", FSC_PRIORITY_BASE))
{
cemuLog_log(LogType::Force, "Mounting failed");
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
}
// check update
TitleInfo& titleUpdate = sGameInfo_ForegroundTitle.GetUpdate();
if (titleUpdate.IsValid())
{
if (!titleUpdate.ParseXmlInfo())
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
cemuLog_log(LogType::Force, "Update: {}", titleUpdate.GetPrintPath());
// mount update
if (!titleUpdate.Mount("/vol/content", "content", FSC_PRIORITY_PATCH) || !titleUpdate.Mount(GetInternalVirtualCodeFolder(), "code", FSC_PRIORITY_PATCH))
{
cemuLog_log(LogType::Force, "Mounting failed");
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
}
}
else
cemuLog_log(LogType::Force, "Update: Not present");
// check AOC
auto aocList = sGameInfo_ForegroundTitle.GetAOC();
if (!aocList.empty())
{
// todo - support for multi-title AOC
TitleInfo& titleAOC = aocList[0];
if (!titleAOC.ParseXmlInfo())
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
cemu_assert_debug(titleAOC.IsValid());
cemuLog_log(LogType::Force, "DLC: {}", titleAOC.GetPrintPath());
// mount AOC
if (!titleAOC.Mount(fmt::format("/vol/aoc{:016x}", titleAOC.GetAppTitleId()), "content", FSC_PRIORITY_PATCH))
{
cemuLog_log(LogType::Force, "Mounting failed");
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
}
}
else
cemuLog_log(LogType::Force, "DLC: Not present");
sForegroundTitleId = titleId;
return PREPARE_STATUS_CODE::SUCCESS;
}
void UnmountForegroundTitle()
{
if(sLaunchModeIsStandalone)
return;
cemu_assert_debug(sGameInfo_ForegroundTitle.IsValid()); // unmounting title which was never mounted?
if (!sGameInfo_ForegroundTitle.IsValid())
return;
sGameInfo_ForegroundTitle.GetBase().Unmount("/vol/content");
sGameInfo_ForegroundTitle.GetBase().Unmount(GetInternalVirtualCodeFolder());
if (sGameInfo_ForegroundTitle.HasUpdate())
{
if(auto& update = sGameInfo_ForegroundTitle.GetUpdate(); update.IsValid())
{
update.Unmount("/vol/content");
update.Unmount(GetInternalVirtualCodeFolder());
}
}
auto aocList = sGameInfo_ForegroundTitle.GetAOC();
if (!aocList.empty())
{
TitleInfo& titleAOC = aocList[0];
titleAOC.Unmount(fmt::format("/vol/aoc{:016x}", titleAOC.GetAppTitleId()));
}
}
PREPARE_STATUS_CODE SetupExecutable()
{
// set rpx path from cos.xml if available
_pathToBaseExecutable = _pathToExecutable;
if (!sLaunchModeIsStandalone)
{
std::string _argstr = CafeSystem::GetForegroundTitleArgStr();
const char* argstr = _argstr.c_str();
if (argstr && *argstr != '\0')
{
const std::string tmp = argstr;
const auto index = tmp.find(".rpx");
if (index != std::string::npos)
{
fs::path rpx = _pathToExecutable;
rpx.replace_filename(tmp.substr(0, index + 4)); // cut off after .rpx
std::string rpxPath;
rpxPath = "/internal/current_title/code/";
rpxPath.append(rpx.generic_string());
int status;
const auto file = fsc_open(rpxPath.c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &status);
if (file)
{
_pathToExecutable = std::move(rpxPath);
fsc_close(file);
}
}
}
}
LoadMainExecutable();
return PREPARE_STATUS_CODE::SUCCESS;
}
void SetupMemorySpace()
{
memory_mapForCurrentTitle();
LoadSharedData();
}
void DestroyMemorySpace()
{
memory_unmapForCurrentTitle();
}
PREPARE_STATUS_CODE PrepareForegroundTitle(TitleId titleId)
{
CafeTitleList::WaitForMandatoryScan();
sLaunchModeIsStandalone = false;
_pathToExecutable.clear();
TitleIdParser tip(titleId);
if (tip.GetType() == TitleIdParser::TITLE_TYPE::AOC || tip.GetType() == TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE)
cemuLog_log(LogType::Force, "Launched titleId is not the base of a title");
// mount mlc storage
MountBaseDirectories();
// mount title folders
PREPARE_STATUS_CODE r = LoadAndMountForegroundTitle(titleId);
if (r != PREPARE_STATUS_CODE::SUCCESS)
return r;
gameProfile_load();
// setup memory space and PPC recompiler
SetupMemorySpace();
PPCRecompiler_init();
r = SetupExecutable(); // load RPX
if (r != PREPARE_STATUS_CODE::SUCCESS)
return r;
InitVirtualMlcStorage();
return PREPARE_STATUS_CODE::SUCCESS;
}
PREPARE_STATUS_CODE PrepareForegroundTitleFromStandaloneRPX(const fs::path& path)
{
sLaunchModeIsStandalone = true;
cemuLog_log(LogType::Force, "Launching executable in standalone mode due to incorrect layout or missing meta files");
fs::path executablePath = path;
std::string dirName = _pathToUtf8(executablePath.parent_path().filename());
if (boost::iequals(dirName, "code"))
{
// check for content folder
fs::path contentPath = executablePath.parent_path().parent_path().append("content");
std::error_code ec;
if (fs::is_directory(contentPath, ec))
{
// mounting content folder
bool r = FSCDeviceHostFS_Mount(std::string("/vol/content").c_str(), _pathToUtf8(contentPath), FSC_PRIORITY_BASE);
if (!r)
{
cemuLog_log(LogType::Force, "Failed to mount {}", _pathToUtf8(contentPath));
return PREPARE_STATUS_CODE::UNABLE_TO_MOUNT;
}
}
}
// mount code folder to a virtual temporary path
FSCDeviceHostFS_Mount(std::string("/internal/code/").c_str(), _pathToUtf8(executablePath.parent_path()), FSC_PRIORITY_BASE);
std::string internalExecutablePath = "/internal/code/";
internalExecutablePath.append(_pathToUtf8(executablePath.filename()));
_pathToExecutable = internalExecutablePath;
// since a lot of systems (including save folder location) rely on a TitleId, we derive a placeholder id from the executable hash
auto execData = fsc_extractFile(_pathToExecutable.c_str());
if (!execData)
return PREPARE_STATUS_CODE::INVALID_RPX;
uint32 h = generateHashFromRawRPXData(execData->data(), execData->size());
sForegroundTitleId = 0xFFFFFFFF00000000ULL | (uint64)h;
cemuLog_log(LogType::Force, "Generated placeholder TitleId: {:016x}", sForegroundTitleId);
// setup memory space and ppc recompiler
SetupMemorySpace();
PPCRecompiler_init();
// load executable
SetupExecutable();
InitVirtualMlcStorage();
return PREPARE_STATUS_CODE::SUCCESS;
}
void _LaunchTitleThread()
{
for(auto& module : s_iosuModules)
module->TitleStart();
cemu_initForGame();
// enter scheduler
if (ActiveSettings::GetCPUMode() == CPUMode::MulticoreRecompiler)
coreinit::OSSchedulerBegin(3);
else
coreinit::OSSchedulerBegin(1);
}
void LaunchForegroundTitle()
{
PPCTimer_waitForInit();
// start system
sSystemRunning = true;
gui_notifyGameLoaded();
std::thread t(_LaunchTitleThread);
t.detach();
}
bool IsTitleRunning()
{
return sSystemRunning;
}
TitleId GetForegroundTitleId()
{
cemu_assert_debug(sForegroundTitleId != 0);
return sForegroundTitleId;
}
uint16 GetForegroundTitleVersion()
{
if (sLaunchModeIsStandalone)
return 0;
return sGameInfo_ForegroundTitle.GetVersion();
}
uint32 GetForegroundTitleSDKVersion()
{
if (sLaunchModeIsStandalone)
return 999999;
return sGameInfo_ForegroundTitle.GetSDKVersion();
}
CafeConsoleRegion GetForegroundTitleRegion()
{
if (sLaunchModeIsStandalone)
return CafeConsoleRegion::USA;
return sGameInfo_ForegroundTitle.GetRegion();
}
std::string GetForegroundTitleName()
{
if (sLaunchModeIsStandalone)
return "Unknown Game";
std::string applicationName;
applicationName = sGameInfo_ForegroundTitle.GetBase().GetMetaInfo()->GetShortName(GetConfig().console_language);
if (applicationName.empty()) //Try to get the English Title
applicationName = sGameInfo_ForegroundTitle.GetBase().GetMetaInfo()->GetShortName(CafeConsoleLanguage::EN);
if (applicationName.empty()) //Unknown Game
applicationName = "Unknown Game";
return applicationName;
}
uint32 GetForegroundTitleOlvAccesskey()
{
if (sLaunchModeIsStandalone)
return -1;
return sGameInfo_ForegroundTitle.GetBase().GetMetaInfo()->GetOlvAccesskey();
}
std::string GetForegroundTitleArgStr()
{
if (sLaunchModeIsStandalone)
return "";
auto& update = sGameInfo_ForegroundTitle.GetUpdate();
if (update.IsValid())
return update.GetArgStr();
return sGameInfo_ForegroundTitle.GetBase().GetArgStr();
}
CosCapabilityBits GetForegroundTitleCosCapabilities(CosCapabilityGroup group)
{
if (sLaunchModeIsStandalone)
return CosCapabilityBits::All;
auto& update = sGameInfo_ForegroundTitle.GetUpdate();
if (update.IsValid())
{
ParsedCosXml* cosXml = update.GetCosInfo();
if (cosXml)
return cosXml->GetCapabilityBits(group);
}
auto& base = sGameInfo_ForegroundTitle.GetBase();
if(base.IsValid())
{
ParsedCosXml* cosXml = base.GetCosInfo();
if (cosXml)
return cosXml->GetCapabilityBits(group);
}
return CosCapabilityBits::All;
}
// when switching titles custom parameters can be passed, returns true if override args are used
bool GetOverrideArgStr(std::vector<std::string>& args)
{
args.clear();
if(!s_overrideArgs)
return false;
args = *s_overrideArgs;
return true;
}
void SetOverrideArgs(std::span<std::string> args)
{
s_overrideArgs = std::vector<std::string>(args.begin(), args.end());
}
void UnsetOverrideArgs()
{
s_overrideArgs = std::nullopt;
}
// pick platform region based on title region
CafeConsoleRegion GetPlatformRegion()
{
CafeConsoleRegion titleRegion = GetForegroundTitleRegion();
CafeConsoleRegion platformRegion = CafeConsoleRegion::USA;
if (HAS_FLAG(titleRegion, CafeConsoleRegion::JPN))
platformRegion = CafeConsoleRegion::JPN;
else if (HAS_FLAG(titleRegion, CafeConsoleRegion::EUR))
platformRegion = CafeConsoleRegion::EUR;
else if (HAS_FLAG(titleRegion, CafeConsoleRegion::USA))
platformRegion = CafeConsoleRegion::USA;
return platformRegion;
}
void UnmountCurrentTitle()
{
UnmountForegroundTitle();
fsc_unmount("/internal/code/", FSC_PRIORITY_BASE);
}
void ShutdownTitle()
{
if(!sSystemRunning)
return;
coreinit::OSSchedulerEnd();
Latte_Stop();
// reset Cafe OS userspace modules
snd_core::reset();
coreinit::OSAlarm_Shutdown();
GX2::_GX2DriverReset();
nn::save::ResetToDefaultState();
coreinit::__OSDeleteAllActivePPCThreads();
RPLLoader_ResetState();
for(auto it = s_iosuModules.rbegin(); it != s_iosuModules.rend(); ++it)
(*it)->TitleStop();
// reset Cemu subsystems
PPCRecompiler_Shutdown();
GraphicPack2::Reset();
UnmountCurrentTitle();
MlcStorageUnmountAllTitles();
UnmountBaseDirectories();
DestroyMemorySpace();
sSystemRunning = false;
}
/* Virtual mlc storage */
void InitVirtualMlcStorage()
{
// starting with Cemu 1.27.0 /vol/storage_mlc01/ is virtualized, meaning that it doesn't point to one singular host os folder anymore
// instead it now uses a more complex solution to source titles with various formats (folder, wud, wua) from the game paths and host mlc path
// todo - mount /vol/storage_mlc01/ with base priority to the host mlc?
// since mounting titles is an expensive operation we have to avoid mounting all titles at once
// only the current title gets mounted immediately, every other title should be mounted lazily on first access
// always mount the currently running title
if (sGameInfo_ForegroundTitle.GetBase().IsValid())
MlcStorageMountTitle(sGameInfo_ForegroundTitle.GetBase());
if (sGameInfo_ForegroundTitle.GetUpdate().IsValid())
MlcStorageMountTitle(sGameInfo_ForegroundTitle.GetUpdate());
for(auto& it : sGameInfo_ForegroundTitle.GetAOC())
MlcStorageMountTitle(it);
// setup system for lazy-mounting of other known titles
// todo - how to handle this?
// when something iterates /vol/storage_mlc01/usr/title/ we can use a fake FS device mounted to /vol/storage_mlc01/usr/title and sys/title that simulates the title id folders
// the same device would then have to mount titles when their folders are actually accessed
}
// /vol/storage_mlc01/<usr or sys>/title/<titleIdHigh>/<titleIdLow>
std::string GetMlcStoragePath(TitleId titleId)
{
TitleIdParser tip(titleId);
return fmt::format("/vol/storage_mlc01/{}/title/{:08x}/{:08x}", tip.IsSystemTitle() ? "sys" : "usr", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
std::map<TitleId, TitleInfo*> m_mlcMountedTitles;
// mount title to our virtual MLC storage
// /vol/storage_mlc01/<usr or sys>/title/<titleIdHigh>/<titleIdLow>
void MlcStorageMountTitle(TitleInfo& titleInfo)
{
if (!titleInfo.IsValid())
{
cemu_assert_suspicious();
return;
}
TitleId titleId = titleInfo.GetAppTitleId();
if (m_mlcMountedTitles.find(titleId) != m_mlcMountedTitles.end())
return;
std::string mlcStoragePath = GetMlcStoragePath(titleId);
TitleInfo* mountTitleInfo = new TitleInfo(titleInfo);
if (!mountTitleInfo->Mount(mlcStoragePath, "", FSC_PRIORITY_BASE))
{
cemuLog_log(LogType::Force, "Failed to mount title to virtual storage");
delete mountTitleInfo;
return;
}
m_mlcMountedTitles.emplace(titleId, mountTitleInfo);
}
void MlcStorageMountTitle(TitleId titleId)
{
TitleInfo titleInfo;
if (!CafeTitleList::GetFirstByTitleId(titleId, titleInfo))
return;
MlcStorageMountTitle(titleInfo);
}
void MlcStorageMountAllTitles()
{
std::vector<uint64> titleIds = CafeTitleList::GetAllTitleIds();
for (auto& it : titleIds)
MlcStorageMountTitle(it);
}
void MlcStorageUnmountAllTitles()
{
for(auto& it : m_mlcMountedTitles)
{
std::string mlcStoragePath = GetMlcStoragePath(it.first);
it.second->Unmount(mlcStoragePath);
}
m_mlcMountedTitles.clear();
}
uint32 GetRPXHashBase()
{
return currentBaseApplicationHash;
}
uint32 GetRPXHashUpdated()
{
return currentUpdatedApplicationHash;
}
void RequestRecreateCanvas()
{
s_implementation->CafeRecreateCanvas();
}
}
| 36,962
|
C++
|
.cpp
| 1,021
| 32.875612
| 218
| 0.727602
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,019
|
GamePatch.cpp
|
cemu-project_Cemu/src/Cafe/GamePatch.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h"
#include "CafeSystem.h"
void hleExport_breathOfTheWild_busyLoop(PPCInterpreter_t* hCPU)
{
uint32 queue7C = memory_readU32(hCPU->gpr[24] + 0x7C);
uint32 queue80b = memory_readU8(hCPU->gpr[24] + 0x80);
if (!(queue80b == 0 || hCPU->gpr[22] != 0 || queue7C > 0))
{
PPCInterpreter_relinquishTimeslice();
}
hCPU->gpr[6] = hCPU->gpr[29];
hCPU->instructionPointer += 4;
}
void hleExport_breathOfTheWild_busyLoop2(PPCInterpreter_t* hCPU)
{
uint32 queue7C = memory_readU32(hCPU->gpr[24] + 0x7C);
uint32 queue80b = memory_readU8(hCPU->gpr[24] + 0x80);
if (!(queue80b == 0 || hCPU->gpr[22] != 0 || queue7C > 0))
{
PPCInterpreter_relinquishTimeslice();
}
hCPU->gpr[12] = hCPU->gpr[29];
hCPU->instructionPointer += 4;
}
void hleExport_ffl_swapEndianFloatArray(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(valueArray, uint32, 0);
ppcDefineParamS32(valueCount, 1);
for (sint32 i = 0; i < valueCount; i++)
{
valueArray[i] = _swapEndianU32(valueArray[i]);
}
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
std::atomic<uint32be> count;
uint32be ownerThreadId;
uint32 ukn08;
}xcxCS_t;
void hleExport_xcx_enterCriticalSection(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(xcxCS, xcxCS_t, 0);
uint32 threadId = MEMPTR<OSThread_t>(coreinit::OSGetCurrentThread()).GetMPTR();
cemu_assert_debug(xcxCS->ukn08 != 0);
cemu_assert_debug(threadId);
if (xcxCS->ownerThreadId == (uint32be)threadId)
{
xcxCS->count.store(xcxCS->count.load() + 1);
osLib_returnFromFunction(hCPU, 0);
return;
}
// quick check
uint32be newCount = xcxCS->count.load() + 1;
uint32be expectedCount = 0;
if(xcxCS->count.compare_exchange_strong(expectedCount, newCount))
{
xcxCS->ownerThreadId = threadId;
osLib_returnFromFunction(hCPU, 0);
return;
}
// spinloop for a bit to reduce the time we occupy the scheduler lock (via PPCCore_switchToScheduler)
while (true)
{
for (sint32 i = 0; i < 50; i++)
{
if (xcxCS->count.compare_exchange_strong(expectedCount, newCount))
{
xcxCS->ownerThreadId = threadId;
osLib_returnFromFunction(hCPU, 0);
return;
}
_mm_pause();
}
PPCCore_switchToScheduler();
}
osLib_returnFromFunction(hCPU, 0);
}
bool mh3u_raceConditionWorkaround = true;
void hleExport_mh3u_raceConditionWorkaround(PPCInterpreter_t* hCPU) // new style HLE method, does not need entry in hle_load (but can only be reached via BL and not the usual HLE instruction)
{
uint8 b = memory_readU8(hCPU->gpr[3] + 0x3E5);
b ^= 1;
if (mh3u_raceConditionWorkaround)
{
b = 0;
mh3u_raceConditionWorkaround = false;
}
osLib_returnFromFunction(hCPU, b);
}
void hleExport_pmcs_yellowPaintStarCrashWorkaround(PPCInterpreter_t* hCPU)
{
hCPU->gpr[7] = hCPU->gpr[3] * 4;
MPTR parentLR = memory_readU32(hCPU->gpr[1] + 0x4C);
if (hCPU->gpr[3] >= 0x00800000)
{
hCPU->instructionPointer = parentLR;
hCPU->gpr[1] += 0x48;
hCPU->gpr[3] = 0;
return;
}
hCPU->instructionPointer = hCPU->spr.LR;
}
uint8 hleSignature_wwhd_0173B2A0[] = {0x8D,0x43,0x00,0x01,0x7C,0xC9,0x52,0x78,0x55,0x2C,0x15,0xBA,0x7C,0x0C,0x28,0x2E,0x54,0xC8,0xC2,0x3E,0x7D,0x06,0x02,0x78,0x42,0x00,0xFF,0xE8,0x7C,0xC3,0x30,0xF8};
void hle_scan(uint8* data, sint32 dataLength, char* hleFunctionName)
{
sint32 functionIndex = osLib_getFunctionIndex("hle", hleFunctionName);
if( functionIndex < 0 )
{
debug_printf("HLE function unknown\n");
return;
}
uint8* scanStart = memory_getPointerFromVirtualOffset(0x01000000);
uint8* scanEnd = scanStart + 0x0F000000 - dataLength;
uint8* scanCurrent = scanStart;
while( scanCurrent < scanEnd )
{
if( memcmp(scanCurrent, data, dataLength) == 0 )
{
uint32 offset = (uint32)(scanCurrent - scanStart) + 0x01000000;
debug_printf("HLE signature for '%s' found at 0x%08x\n", hleFunctionName, offset);
uint32 opcode = (1<<26)|(functionIndex+0x1000); // opcode for HLE: 0x1000 + FunctionIndex
memory_write<uint32>(offset, opcode);
break;
}
scanCurrent += 4;
}
}
MPTR hle_locate(uint8* data, sint32 dataLength)
{
uint8* scanStart = memory_getPointerFromVirtualOffset(0x01000000);
uint8* scanEnd = scanStart + 0x0F000000 - dataLength;
uint8* scanCurrent = scanStart;
while( scanCurrent < scanEnd )
{
if( memcmp(scanCurrent, data, dataLength) == 0 )
{
return memory_getVirtualOffsetFromPointer(scanCurrent);
}
scanCurrent += 4;
}
return MPTR_NULL;
}
bool compareMasked(uint8* mem, uint8* compare, uint8* mask, sint32 length)
{
while( length )
{
uint8 m = *mask;
if( (*mem&m) != (*compare&m) )
return false;
mem++;
compare++;
mask++;
length--;
}
return true;
}
MPTR hle_locate(uint8* data, uint8* mask, sint32 dataLength)
{
uint8* scanStart = memory_getPointerFromVirtualOffset(MEMORY_CODEAREA_ADDR);
uint8* scanEnd = memory_getPointerFromVirtualOffset(RPLLoader_GetMaxCodeOffset() - dataLength);
uint8* scanCurrent = scanStart;
if( mask )
{
if (dataLength >= 4 && *(uint32*)mask == 0xFFFFFFFF)
{
// fast path
uint32 firstDword = *(uint32*)data;
while (scanCurrent < scanEnd)
{
if (*(uint32*)scanCurrent == firstDword && compareMasked(scanCurrent, data, mask, dataLength))
{
return memory_getVirtualOffsetFromPointer(scanCurrent);
}
scanCurrent += 4;
}
}
else
{
#ifdef CEMU_DEBUG_ASSERT
if (mask[0] != 0xFF)
assert_dbg();
#endif
uint8 firstByte = data[0];
while (scanCurrent < scanEnd)
{
if (scanCurrent[0] == firstByte && compareMasked(scanCurrent, data, mask, dataLength))
{
return memory_getVirtualOffsetFromPointer(scanCurrent);
}
scanCurrent += 4;
}
}
}
else
{
while( scanCurrent < scanEnd )
{
if( memcmp(scanCurrent, data, dataLength) == 0 )
{
return memory_getVirtualOffsetFromPointer(scanCurrent);
}
scanCurrent += 4;
}
}
return MPTR_NULL;
}
uint8 xcx_gpuHangDetection_degradeFramebuffer[] = {0x3B,0x39,0x00,0x01,0x28,0x19,0x4E,0x20,0x40,0x81,0x00,0x44};
uint8 xcx_framebufferReductionSignature[] = {0x80,0xC9,0x00,0x1C,0x38,0xA0,0x00,0x01,0x80,0x7E,0x00,0x80,0x80,0x9E,0x02,0xEC,0x80,0xE9,0x00,0x20,0x48,0x06,0x1E,0xD1,0x7E,0x73,0x1B,0x78};
uint8 xcx_framebufferReductionMask[] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF};
uint8 botw_busyLoopSignature[] = {0x80,0xE6,0x00,0x00,0x2C,0x07,0x00,0x01,0x41,0x82,0xFF,0xF8,0x7D,0x00,0x30,0x28,0x2C,0x08,0x00,0x00,0x40,0x82,0xFF,0xF8,0x7C,0x00,0x30,0x6C,0x39,0x00,0x00,0x01,0x7D,0x00,0x31,0x2D,0x40,0x82,0xFF,0xE8 };
uint8 botw_busyLoopMask[] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF };
uint8 botw_busyLoopSignature2[] = {0x80,0x0C,0x00,0x00,0x2C,0x00,0x00,0x01,0x41,0x82,0xFF,0xF8,0x7C,0xA0,0x60,0x28,0x2C,0x05,0x00,0x00,0x40,0x82,0xFF,0xF8,0x7C,0x00,0x60,0x6C,0x38,0x80,0x00,0x01,0x7C,0x80,0x61,0x2D,0x40,0x82,0xFF,0xE8};
uint8 botw_busyLoopMask2[] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
uint8 botw_crashFuncSignature[] = { 0x94,0x21,0xFF,0xD8,0x7C,0x08,0x02,0xA6,0xBF,0x41,0x00,0x10,0x7C,0xC7,0x33,0x78,0x7C,0xBE,0x2B,0x78,0x90,0x01,0x00,0x2C,0x7C,0x9D,0x23,0x78,0x38,0x00,0x00,0x00,0x7F,0xC6,0xF3,0x78,0x38,0x81,0x00,0x0C,0x90,0x01,0x00,0x0C,0x38,0xA1,0x00,0x08 };
uint8 botw_crashFuncMask[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF };
uint8 ffl_floatArrayEndianSwap[] = { 0x7C,0x08,0x02,0xA6,0x94,0x21,0xFF,0xE8,0x93,0xC1,0x00,0x10,0x7C,0x7E,0x1B,0x78,0x93,0xE1,0x00,0x14,0x93,0x81,0x00,0x08,0x7C,0x9F,0x23,0x78,0x93,0xA1,0x00,0x0C,0x90,0x01,0x00,0x1C,0x3B,0xA0,0x00,0x00,0x7C,0x1D,0xF8,0x40,0x40,0x80,0x00,0x20,0x57,0xBC,0x10,0x3A,0x7C,0x3E,0xE4,0x2E };
uint8 xcx_enterCriticalSectionSignature[] = { 0x94,0x21,0xFF,0xE0,0xBF,0x41,0x00,0x08,0x7C,0x08,0x02,0xA6,0x90,0x01,0x00,0x24,0x7C,0x7E,0x1B,0x78,0x80,0x1E,0x00,0x08,0x2C,0x00,0x00,0x00,0x41,0x82,0x00,0xC0,0x48,0x01,0xD7,0xA1,0x7C,0x7A,0x1B,0x79,0x41,0x82,0x00,0xB4,0x81,0x3E,0x00,0x04,0x7C,0x09,0xD0,0x40,0x40,0x82,0x00,0x2C,0x7D,0x20,0xF0,0x28,0x7C,0x00,0xF0,0x6C };
uint8 xcx_enterCriticalSectionMask[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF };
uint8 smash4_softlockFixV0Signature[] = { 0x2C,0x03,0x00,0x00,0x41,0x82,0x00,0x20,0x38,0x60,0x00,0x0A,0x48,0x33,0xB8,0xAD,0x7F,0xA3,0xEB,0x78,0x7F,0xC4,0xF3,0x78,0x4B,0xFF,0xFF,0x09,0x2C,0x03,0x00,0x00 };
uint8 smash4_softlockFixV0Mask[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF };
uint8 mh3u_raceConditionWorkaroundV0Signature[] = { 0x38,0x21,0x00,0x40,0x38,0x60,0x00,0x00,0x4E,0x80,0x00,0x20,0x80,0x7B,0xDB,0x9C,0x48,0x11,0x6B,0x81,0x2C,0x03,0x00,0x00 };
uint8 mh3u_raceConditionWorkaroundV0Mask[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF };
uint8 pmcs_yellowPaintStarCrashV0Signature[] = { 0x94,0x21,0xFF,0xB8,0xBE,0x61,0x00,0x14,0x7C,0x08,0x02,0xA6,0x7C,0xB3,0x2B,0x78,0x90,0x01,0x00,0x4C,0x7C,0x9D,0x23,0x78,0x83,0x3D,0x00,0x0C,0x81,0x39,0x04,0xA8,0x54,0x67,0x10,0x3A,0x7F,0xC7,0x48,0x2E,0x83,0x1E,0x00,0xDC,0x82,0xF8,0x00,0x08,0x2C,0x17,0x00,0x00 };
//uint8 mh3u_raceConditionWorkaroundV0Mask[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF };
uint8 bayo2_audioQueueFixSignature[] = { 0x80,0x03,0x00,0x3C,0x81,0x43,0x00,0x5C,0x81,0x83,0x00,0x40,0x55,0x48,0xB2,0xBE,0x3D,0x40,0x10,0x1D,0x7D,0x6C,0x42,0x14,0x39,0x4A,0x46,0xF0,0x7D,0x8B,0x00,0x50 };
uint8 bayo2_audioQueueFixMask[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0xFF,0xFF,0xFF,0xFF };
uint8 sm3dw_dynFrameBufferResScale[] = { 0x94,0x21,0xFF,0xB8,0xBF,0x21,0x00,0x2C,0x7C,0x08,0x02,0xA6,0x90,0x01,0x00,0x4C,0x7C,0x7E,0x1B,0x78,0x81,0x7E,0x07,0xD8,0x38,0x80,0x00,0x02,0x38,0x6B,0x00,0x03 };
uint8 tww_waitFunc[] = { 0x7C,0x08,0x02,0xA6,0x94,0x21,0xFF,0xF0,0x93,0xE1,0x00,0x0C,0x7C,0x7F,0x1B,0x78,0x90,0x01,0x00,0x14,0x80,0x7F,0x02,0xE0,0x81,0x83,0x00,0x0C,0x80,0x0C,0x00,0x1C,0x7C,0x09,0x03,0xA6,0x38,0xA0,0x00,0x00,0x38,0x9F,0x03,0x68 };
static_assert(sizeof(xcx_enterCriticalSectionSignature) == sizeof(xcx_enterCriticalSectionMask), "xcx_enterCriticalSection signature and size mismatch");
static_assert(sizeof(bayo2_audioQueueFixSignature) == sizeof(bayo2_audioQueueFixMask), "bayo2_audioQueueFix signature and size mismatch");
uint8 cars3_avro_schema_incref[] = { 0x2C,0x03,0x00,0x00,0x94,0x21,0xFF,0xE8,0x41,0x82,0x00,0x40,0x39,0x03,0x00,0x08,0x39,0x41,0x00,0x08,0x91,0x01,0x00,0x08,0x7D,0x80,0x50,0x28,0x2C,0x0C,0xFF,0xFF,0x41,0x82,0x00,0x28,0x39,0x21,0x00,0x0C,0x38,0x0C,0x00,0x01,0x38,0xE0,0x00,0x01,0x91,0x01,0x00,0x0C,0x7C,0x00,0x49,0x2D };
sint32 hleIndex_h000000001 = -1;
sint32 hleIndex_h000000002 = -1;
sint32 hleIndex_h000000003 = -1;
sint32 hleIndex_h000000004 = -1;
/*
* Returns true for all HLE functions that do not jump to LR
* Used by recompiler to determine function code flow
*/
bool GamePatch_IsNonReturnFunction(uint32 hleIndex)
{
if (hleIndex == hleIndex_h000000001)
return true;
if (hleIndex == hleIndex_h000000002)
return true;
if (hleIndex == hleIndex_h000000003)
return false;
if (hleIndex == hleIndex_h000000004)
return false;
return false;
}
void GamePatch_scan()
{
MPTR hleAddr;
uint32 hleInstallStart = GetTickCount();
hleAddr = hle_locate(xcx_gpuHangDetection_degradeFramebuffer, NULL, sizeof(xcx_gpuHangDetection_degradeFramebuffer));
if( hleAddr )
{
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::Force, "HLE: XCX GPU hang detection");
#endif
// remove the ADDI r25, r25, 1 instruction
memory_writeU32(hleAddr, memory_readU32(hleAddr+4));
}
hleAddr = hle_locate(xcx_framebufferReductionSignature, xcx_framebufferReductionMask, sizeof(xcx_framebufferReductionSignature));
if( hleAddr )
{
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::Force, "HLE: Prevent XCX rendertarget reduction");
#endif
uint32 bl = memory_readU32(hleAddr+0x14);
uint32 func_isReductionBuffer = hleAddr + 0x14 + (bl&0x3FFFFFC);
// patch isReductionBuffer
memory_writeU32(func_isReductionBuffer, 0x38600000); // LI R3, 0
memory_writeU32(func_isReductionBuffer+4, 0x4E800020); // BLR
}
hleIndex_h000000001 = osLib_getFunctionIndex("hle", "h000000001");
hleAddr = hle_locate(botw_busyLoopSignature, botw_busyLoopMask, sizeof(botw_busyLoopSignature));
if (hleAddr)
{
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::Force, "HLE: Patch BotW busy loop 1 at 0x{:08x}", hleAddr);
#endif
sint32 functionIndex = hleIndex_h000000001;
uint32 opcode = (1 << 26) | (functionIndex); // opcode for HLE: 0x1000 + FunctionIndex
memory_write<uint32>(hleAddr - 4, opcode);
}
hleIndex_h000000002 = osLib_getFunctionIndex("hle", "h000000002");
hleAddr = hle_locate(botw_busyLoopSignature2, botw_busyLoopMask2, sizeof(botw_busyLoopSignature2));
if (hleAddr)
{
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::Force, "HLE: Patch BotW busy loop 2 at 0x{:08x}", hleAddr);
#endif
sint32 functionIndex = hleIndex_h000000002;
uint32 opcode = (1 << 26) | (functionIndex); // opcode for HLE: 0x1000 + FunctionIndex
memory_write<uint32>(hleAddr - 4, opcode);
}
// FFL library float array endian conversion
// original function needs invalid float values to remain intact between LFSX -> STFSX, which is not supported in recompiler mode
hleIndex_h000000003 = osLib_getFunctionIndex("hle", "h000000003");
hleAddr = hle_locate(ffl_floatArrayEndianSwap, NULL, sizeof(ffl_floatArrayEndianSwap));
if (hleAddr)
{
cemuLog_logDebug(LogType::Force, "HLE: Hook FFL float array endian swap function at 0x{:08x}", hleAddr);
sint32 functionIndex = hleIndex_h000000003;
uint32 opcode = (1 << 26) | (functionIndex); // opcode for HLE: 0x1000 + FunctionIndex
memory_write<uint32>(hleAddr, opcode);
}
// XCX freeze workaround
//hleAddr = hle_locate(xcx_enterCriticalSectionSignature, xcx_enterCriticalSectionMask, sizeof(xcx_enterCriticalSectionSignature));
//if (hleAddr)
//{
// cemuLog_logDebug(LogType::Force, "HLE: Hook XCX enterCriticalSection function at 0x{:08x}", hleAddr);
// hleIndex_h000000004 = osLib_getFunctionIndex("hle", "h000000004");
// sint32 functionIndex = hleIndex_h000000004;
// uint32 opcode = (1 << 26) | (functionIndex); // opcode for HLE: 0x1000 + FunctionIndex
// memory_writeU32Direct(hleAddr, opcode);
//}
// MH3U race condition (tested for EU+US 1.2)
hleAddr = hle_locate(mh3u_raceConditionWorkaroundV0Signature, mh3u_raceConditionWorkaroundV0Mask, sizeof(mh3u_raceConditionWorkaroundV0Mask));
if (hleAddr)
{
uint32 patchAddr = hleAddr + 0x10;
cemuLog_log(LogType::Force, "HLE: Patch MH3U race condition candidate at 0x{:08x}", patchAddr);
uint32 funcAddr = PPCInterpreter_makeCallableExportDepr(hleExport_mh3u_raceConditionWorkaround);
// set absolute jump
uint32 opc = 0x48000000;
opc |= PPC_OPC_LK;
opc |= PPC_OPC_AA;
opc |= funcAddr;
memory_writeU32(patchAddr, opc);
}
// Super Smash Bros softlock fix
// fixes random softlocks that can occur after matches
hleAddr = hle_locate(smash4_softlockFixV0Signature, smash4_softlockFixV0Mask, sizeof(smash4_softlockFixV0Signature));
if (hleAddr)
{
cemuLog_logDebug(LogType::Force, "Smash softlock fix: 0x{:08x}", hleAddr);
memory_writeU32(hleAddr+0x20, memory_readU32(hleAddr+0x1C));
}
// Color Splash Yellow paint star crash workaround
// fixes the crash at the beginning of the dream sequence cutscene after collecting the yellow paint star
hleAddr = hle_locate(pmcs_yellowPaintStarCrashV0Signature, nullptr, sizeof(pmcs_yellowPaintStarCrashV0Signature));
if (hleAddr)
{
cemuLog_logDebug(LogType::Force, "Color Splash crash fix: 0x{:08x}", hleAddr);
uint32 funcAddr = PPCInterpreter_makeCallableExportDepr(hleExport_pmcs_yellowPaintStarCrashWorkaround);
// set absolute jump
uint32 opc = 0x48000000;
opc |= PPC_OPC_LK;
opc |= PPC_OPC_AA;
opc |= funcAddr;
memory_writeU32(hleAddr+0x20, opc);
}
// Bayonetta 2 sound queue patch (fixes audio starting to loop infinitely when there is stutter)
hleAddr = hle_locate(bayo2_audioQueueFixSignature, bayo2_audioQueueFixMask, sizeof(bayo2_audioQueueFixSignature));
if (hleAddr)
{
// replace CMPL with CMP
cemuLog_log(LogType::Force, "Patching Bayonetta 2 audio bug at: 0x{:08x}", hleAddr+0x34);
uint32 opc = memory_readU32(hleAddr + 0x34);
opc &= ~(0x3FF << 1); // turn CMPL to CMP
memory_writeU32(hleAddr + 0x34, opc);
}
if (CafeSystem::GetRPXHashUpdated() == 0xb1c033dd) // Wind Waker US
{
uint32 p = memory_readU32(0x02813878);
if (p == 0x40800018)
{
debug_printf("HLE: TWW US dsp kill channel patch\n");
uint32 li = 0x18;
uint32 opcode = (li & 0x3FFFFFC) | (18 << 26); // replace BGE with B instruction
memory_writeU32(0x02813878, opcode);
}
}
else if (CafeSystem::GetRPXHashUpdated() == 0xCDC68ACD) // Wind Waker EU
{
uint32 p = memory_readU32(0x2814138);
if (p == 0x40800018)
{
debug_printf("HLE: TWW EU dsp kill channel patch\n");
uint32 li = 0x18;
uint32 opcode = (li & 0x3FFFFFC) | (18 << 26); // replace BGE with B instruction
memory_writeU32(0x02814138, opcode);
}
}
// disable SM3DW dynamic resolution scaling (fixes level 1-5 spamming lots of texture creates when gradually resizing framebuffer)
hleAddr = hle_locate(sm3dw_dynFrameBufferResScale, nullptr, sizeof(sm3dw_dynFrameBufferResScale));
if (hleAddr)
{
cemuLog_log(LogType::Force, "Patching SM3DW dynamic resolution scaling at: 0x{:08x}", hleAddr);
memory_writeU32(hleAddr, 0x4E800020); // BLR
}
// remove unnecessary lock from a wait function in TWW
// this resolves a deadlock in singlecore mode
hleAddr = hle_locate(tww_waitFunc, nullptr, sizeof(tww_waitFunc));
if (hleAddr)
{
cemuLog_log(LogType::Force, "Patching TWW race conditon at: 0x{:08x}", hleAddr);
// NOP calls to Lock/Unlock mutex
memory_writeU32(hleAddr + 0x34, 0x60000000);
memory_writeU32(hleAddr + 0x48, 0x60000000);
memory_writeU32(hleAddr + 0x50, 0x60000000);
memory_writeU32(hleAddr + 0x64, 0x60000000);
}
uint32 hleInstallEnd = GetTickCount();
cemuLog_log(LogType::Force, "HLE scan time: {}ms", hleInstallEnd-hleInstallStart);
}
RunAtCemuBoot _loadGamePatchAPI([]()
{
osLib_addFunction("hle", "h000000001", hleExport_breathOfTheWild_busyLoop);
osLib_addFunction("hle", "h000000002", hleExport_breathOfTheWild_busyLoop2);
osLib_addFunction("hle", "h000000003", hleExport_ffl_swapEndianFloatArray);
osLib_addFunction("hle", "h000000004", hleExport_xcx_enterCriticalSection);
});
| 19,512
|
C++
|
.cpp
| 419
| 44.076372
| 368
| 0.756119
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,020
|
fscDeviceWua.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/fscDeviceWua.cpp
|
#include "Cafe/Filesystem/fsc.h"
#include <zarchive/zarchivereader.h>
class FSCDeviceWuaFileCtx : public FSCVirtualFile
{
friend class fscDeviceWUAC;
protected:
FSCDeviceWuaFileCtx(ZArchiveReader* archive, ZArchiveNodeHandle fstFileHandle, uint32 fscType)
{
this->m_archive = archive;
this->m_fscType = fscType;
this->m_nodeHandle = fstFileHandle;
this->m_seek = 0;
};
public:
sint32 fscGetType() override
{
return m_fscType;
}
uint32 fscDeviceWuaFile_getFileSize()
{
return (uint32)m_archive->GetFileSize(m_nodeHandle);
}
uint64 fscQueryValueU64(uint32 id) override
{
if (m_fscType == FSC_TYPE_FILE)
{
if (id == FSC_QUERY_SIZE)
return fscDeviceWuaFile_getFileSize();
else if (id == FSC_QUERY_WRITEABLE)
return 0; // WUD images are read-only
else
cemu_assert_error();
}
else
{
cemu_assert_unimplemented();
}
return 0;
}
uint32 fscWriteData(void* buffer, uint32 size) override
{
cemu_assert_error();
return 0;
}
uint32 fscReadData(void* buffer, uint32 size) override
{
if (m_fscType != FSC_TYPE_FILE)
return 0;
cemu_assert(size < (2ULL * 1024 * 1024 * 1024)); // single read operation larger than 2GiB not supported
uint32 bytesLeft = fscDeviceWuaFile_getFileSize() - m_seek;
uint32 bytesToRead = (std::min)(bytesLeft, (uint32)size);
uint32 bytesSuccessfullyRead = (uint32)m_archive->ReadFromFile(m_nodeHandle, m_seek, bytesToRead, buffer);
m_seek += bytesSuccessfullyRead;
return bytesSuccessfullyRead;
}
void fscSetSeek(uint64 seek) override
{
if (m_fscType != FSC_TYPE_FILE)
return;
cemu_assert_debug(seek <= 0xFFFFFFFFULL);
this->m_seek = (uint32)seek;
}
uint64 fscGetSeek() override
{
if (m_fscType != FSC_TYPE_FILE)
return 0;
return m_seek;
}
bool fscDirNext(FSCDirEntry* dirEntry) override
{
if (m_fscType != FSC_TYPE_DIRECTORY)
return false;
ZArchiveReader::DirEntry zarDirEntry;
if (!m_archive->GetDirEntry(m_nodeHandle, m_iteratorIndex, zarDirEntry))
return false;
m_iteratorIndex++;
if (zarDirEntry.isDirectory)
{
dirEntry->isDirectory = true;
dirEntry->isFile = false;
dirEntry->fileSize = 0;
}
else if(zarDirEntry.isFile)
{
dirEntry->isDirectory = false;
dirEntry->isFile = true;
dirEntry->fileSize = (uint32)zarDirEntry.size;
}
else
{
cemu_assert_suspicious();
}
std::memset(dirEntry->path, 0, sizeof(dirEntry->path));
std::strncpy(dirEntry->path, zarDirEntry.name.data(), std::min(sizeof(dirEntry->path) - 1, zarDirEntry.name.size()));
return true;
}
private:
ZArchiveReader* m_archive{nullptr};
sint32 m_fscType;
ZArchiveNodeHandle m_nodeHandle;
// file
uint32 m_seek{0};
// directory
uint32 m_iteratorIndex{0};
};
class fscDeviceWUAC : public fscDeviceC
{
FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override
{
ZArchiveReader* archive = (ZArchiveReader*)ctx;
cemu_assert_debug(!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::WRITE_PERMISSION)); // writing to WUA is not supported
ZArchiveNodeHandle fileHandle = archive->LookUp(path, true, true);
if (fileHandle == ZARCHIVE_INVALID_NODE)
{
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
if (archive->IsFile(fileHandle))
{
if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE))
{
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
*fscStatus = FSC_STATUS_OK;
return new FSCDeviceWuaFileCtx(archive, fileHandle, FSC_TYPE_FILE);
}
else if (archive->IsDirectory(fileHandle))
{
if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR))
{
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
*fscStatus = FSC_STATUS_OK;
return new FSCDeviceWuaFileCtx(archive, fileHandle, FSC_TYPE_DIRECTORY);
}
else
{
cemu_assert_suspicious();
}
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
// singleton
public:
static fscDeviceWUAC& instance()
{
static fscDeviceWUAC _instance;
return _instance;
}
};
bool FSCDeviceWUA_Mount(std::string_view mountPath, std::string_view destinationBaseDir, ZArchiveReader* archive, sint32 priority)
{
return fsc_mount(mountPath, destinationBaseDir, &fscDeviceWUAC::instance(), archive, priority) == FSC_STATUS_OK;
}
| 4,292
|
C++
|
.cpp
| 156
| 24.602564
| 130
| 0.733738
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,021
|
fscDeviceRedirect.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/fscDeviceRedirect.cpp
|
#include "util/helpers/helpers.h"
#include "Cafe/Filesystem/fscDeviceHostFS.h"
#include "FST/fstUtil.h"
struct RedirectEntry
{
RedirectEntry(const fs::path& dstPath, sint32 priority) : dstPath(dstPath), priority(priority) {}
fs::path dstPath;
sint32 priority;
};
FSAFileTree<RedirectEntry> redirectTree;
void fscDeviceRedirect_add(std::string_view virtualSourcePath, size_t fileSize, const fs::path& targetFilePath, sint32 priority)
{
// check if source already has a redirection
RedirectEntry* existingEntry;
if (redirectTree.getFile(virtualSourcePath, existingEntry))
{
if (existingEntry->priority >= priority)
return; // dont replace entries with equal or higher priority
// unregister existing entry
redirectTree.removeFile(virtualSourcePath);
delete existingEntry;
}
RedirectEntry* entry = new RedirectEntry(targetFilePath, priority);
redirectTree.addFile(virtualSourcePath, fileSize, entry);
}
class fscDeviceTypeRedirect : public fscDeviceC
{
FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override
{
RedirectEntry* redirectionEntry;
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE) && redirectTree.getFile(path, redirectionEntry))
return FSCVirtualFile_Host::OpenFile(redirectionEntry->dstPath, accessFlags, *fscStatus);
FSCVirtualFile* dirIterator;
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR) && redirectTree.getDirectory(path, dirIterator))
return dirIterator;
return nullptr;
}
public:
static fscDeviceTypeRedirect& instance()
{
static fscDeviceTypeRedirect _instance;
return _instance;
}
};
bool _redirectMapped = false;
void fscDeviceRedirect_map()
{
if (_redirectMapped)
return;
fsc_mount("/", "/", &fscDeviceTypeRedirect::instance(), nullptr, FSC_PRIORITY_REDIRECT);
_redirectMapped = true;
}
| 1,856
|
C++
|
.cpp
| 52
| 33.480769
| 128
| 0.795315
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,022
|
fscDeviceWud.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/fscDeviceWud.cpp
|
#include "Cafe/Filesystem/fsc.h"
#include "Cafe/Filesystem/FST/FST.h"
class FSCDeviceWudFileCtx : public FSCVirtualFile
{
friend class fscDeviceWUDC;
protected:
FSCDeviceWudFileCtx(FSTVolume* _volume, FSTFileHandle _fstFileHandle)
{
this->m_volume = _volume;
this->m_fscType = FSC_TYPE_FILE;
this->m_fstFileHandle = _fstFileHandle;
this->m_seek = 0;
};
FSCDeviceWudFileCtx(FSTVolume* _volume, FSTDirectoryIterator _dirIterator)
{
this->m_volume = _volume;
this->m_fscType = FSC_TYPE_DIRECTORY;
this->m_dirIterator = _dirIterator;
}
public:
sint32 fscGetType() override
{
return m_fscType;
}
uint32 fscDeviceWudFile_getFileSize()
{
return m_volume->GetFileSize(m_fstFileHandle);
}
uint64 fscQueryValueU64(uint32 id) override
{
if (m_fscType == FSC_TYPE_FILE)
{
if (id == FSC_QUERY_SIZE)
return fscDeviceWudFile_getFileSize();
else if (id == FSC_QUERY_WRITEABLE)
return 0; // WUD images are read-only
else
cemu_assert_error();
}
else
{
cemu_assert_unimplemented();
}
return 0;
}
uint32 fscWriteData(void* buffer, uint32 size) override
{
cemu_assert_error();
return 0;
}
uint32 fscReadData(void* buffer, uint32 size) override
{
if (m_fscType != FSC_TYPE_FILE)
return 0;
cemu_assert(size < (2ULL * 1024 * 1024 * 1024)); // single read operation larger than 2GiB not supported
uint32 bytesLeft = fscDeviceWudFile_getFileSize() - m_seek;
uint32 bytesToRead = (std::min)(bytesLeft, (uint32)size);
uint32 bytesSuccessfullyRead = m_volume->ReadFile(m_fstFileHandle, m_seek, bytesToRead, buffer);
m_seek += bytesSuccessfullyRead;
return bytesSuccessfullyRead;
}
void fscSetSeek(uint64 seek) override
{
if (m_fscType != FSC_TYPE_FILE)
return;
cemu_assert_debug(seek <= 0xFFFFFFFFULL);
this->m_seek = (uint32)seek;
}
uint64 fscGetSeek() override
{
if (m_fscType != FSC_TYPE_FILE)
return 0;
return m_seek;
}
bool fscDirNext(FSCDirEntry* dirEntry) override
{
if (m_fscType != FSC_TYPE_DIRECTORY)
return false;
FSTFileHandle entryItr;
if (!m_volume->Next(m_dirIterator, entryItr))
return false;
if (m_volume->IsDirectory(entryItr))
{
dirEntry->isDirectory = true;
dirEntry->isFile = false;
dirEntry->fileSize = 0;
}
else
{
dirEntry->isDirectory = false;
dirEntry->isFile = true;
dirEntry->fileSize = m_volume->GetFileSize(entryItr);
}
auto path = m_volume->GetName(entryItr);
std::memset(dirEntry->path, 0, sizeof(dirEntry->path));
std::strncpy(dirEntry->path, path.data(), std::min(sizeof(dirEntry->path) - 1, path.size()));
return true;
}
private:
FSTVolume* m_volume{nullptr};
sint32 m_fscType;
FSTFileHandle m_fstFileHandle;
// file
uint32 m_seek{0};
// directory
FSTDirectoryIterator m_dirIterator{};
};
class fscDeviceWUDC : public fscDeviceC
{
FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override
{
FSTVolume* mountedVolume = (FSTVolume*)ctx;
cemu_assert_debug(!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::WRITE_PERMISSION)); // writing to FST is never allowed
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE))
{
FSTFileHandle fstFileHandle;
if (mountedVolume->OpenFile(path, fstFileHandle, true) && !mountedVolume->HasLinkFlag(fstFileHandle))
{
*fscStatus = FSC_STATUS_OK;
return new FSCDeviceWudFileCtx(mountedVolume, fstFileHandle);
}
}
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR))
{
FSTDirectoryIterator dirIterator;
if (mountedVolume->OpenDirectoryIterator(path, dirIterator) && !mountedVolume->HasLinkFlag(dirIterator.GetDirHandle()))
{
*fscStatus = FSC_STATUS_OK;
return new FSCDeviceWudFileCtx(mountedVolume, dirIterator);
}
}
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
// singleton
public:
static fscDeviceWUDC& instance()
{
static fscDeviceWUDC _instance;
return _instance;
}
};
bool FSCDeviceWUD_Mount(std::string_view mountPath, std::string_view destinationBaseDir, FSTVolume* mountedVolume, sint32 priority)
{
return fsc_mount(mountPath, destinationBaseDir, &fscDeviceWUDC::instance(), mountedVolume, priority) == FSC_STATUS_OK;
}
| 4,202
|
C++
|
.cpp
| 146
| 25.945205
| 131
| 0.738926
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,023
|
fscDeviceWuhb.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/fscDeviceWuhb.cpp
|
#include "Filesystem/WUHB/WUHBReader.h"
#include "Cafe/Filesystem/fsc.h"
#include "Cafe/Filesystem/FST/FST.h"
class FSCDeviceWuhbFileCtx : public FSCVirtualFile
{
public:
FSCDeviceWuhbFileCtx(WUHBReader* reader, uint32 entryOffset, uint32 fscType)
: m_wuhbReader(reader), m_entryOffset(entryOffset), m_fscType(fscType)
{
cemu_assert(entryOffset != ROMFS_ENTRY_EMPTY);
if (fscType == FSC_TYPE_DIRECTORY)
{
romfs_direntry_t entry = reader->GetDirEntry(entryOffset);
m_dirIterOffset = entry.dirListHead;
m_fileIterOffset = entry.fileListHead;
}
}
sint32 fscGetType() override
{
return m_fscType;
}
uint64 fscQueryValueU64(uint32 id) override
{
if (m_fscType == FSC_TYPE_FILE)
{
if (id == FSC_QUERY_SIZE)
return m_wuhbReader->GetFileSize(m_entryOffset);
else if (id == FSC_QUERY_WRITEABLE)
return 0; // WUHB images are read-only
else
cemu_assert_error();
}
else
{
cemu_assert_unimplemented();
}
return 0;
}
uint32 fscWriteData(void* buffer, uint32 size) override
{
cemu_assert_error();
return 0;
}
uint32 fscReadData(void* buffer, uint32 size) override
{
if (m_fscType != FSC_TYPE_FILE)
return 0;
auto read = m_wuhbReader->ReadFromFile(m_entryOffset, m_seek, size, buffer);
m_seek += read;
return read;
}
void fscSetSeek(uint64 seek) override
{
m_seek = seek;
}
uint64 fscGetSeek() override
{
if (m_fscType != FSC_TYPE_FILE)
return 0;
return m_seek;
}
void fscSetFileLength(uint64 endOffset) override
{
cemu_assert_error();
}
bool fscDirNext(FSCDirEntry* dirEntry) override
{
if (m_dirIterOffset != ROMFS_ENTRY_EMPTY)
{
romfs_direntry_t entry = m_wuhbReader->GetDirEntry(m_dirIterOffset);
m_dirIterOffset = entry.listNext;
if(entry.name_size > 0)
{
dirEntry->isDirectory = true;
dirEntry->isFile = false;
dirEntry->fileSize = 0;
std::strncpy(dirEntry->path, entry.name.c_str(), FSC_MAX_DIR_NAME_LENGTH);
return true;
}
}
if (m_fileIterOffset != ROMFS_ENTRY_EMPTY)
{
romfs_fentry_t entry = m_wuhbReader->GetFileEntry(m_fileIterOffset);
m_fileIterOffset = entry.listNext;
if(entry.name_size > 0)
{
dirEntry->isDirectory = false;
dirEntry->isFile = true;
dirEntry->fileSize = entry.size;
std::strncpy(dirEntry->path, entry.name.c_str(), FSC_MAX_DIR_NAME_LENGTH);
return true;
}
}
return false;
}
private:
WUHBReader* m_wuhbReader{};
uint32 m_fscType;
uint32 m_entryOffset = ROMFS_ENTRY_EMPTY;
uint32 m_dirIterOffset = ROMFS_ENTRY_EMPTY;
uint32 m_fileIterOffset = ROMFS_ENTRY_EMPTY;
uint64 m_seek = 0;
};
class fscDeviceWUHB : public fscDeviceC
{
FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override
{
WUHBReader* reader = (WUHBReader*)ctx;
cemu_assert_debug(!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::WRITE_PERMISSION)); // writing to WUHB is not supported
bool isFile;
uint32 table_offset = ROMFS_ENTRY_EMPTY;
if (table_offset == ROMFS_ENTRY_EMPTY && HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR))
{
table_offset = reader->Lookup(path, false);
isFile = false;
}
if (table_offset == ROMFS_ENTRY_EMPTY && HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE))
{
table_offset = reader->Lookup(path, true);
isFile = true;
}
if (table_offset == ROMFS_ENTRY_EMPTY)
{
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
*fscStatus = FSC_STATUS_OK;
return new FSCDeviceWuhbFileCtx(reader, table_offset, isFile ? FSC_TYPE_FILE : FSC_TYPE_DIRECTORY);
}
// singleton
public:
static fscDeviceWUHB& instance()
{
static fscDeviceWUHB _instance;
return _instance;
}
};
bool FSCDeviceWUHB_Mount(std::string_view mountPath, std::string_view destinationBaseDir, WUHBReader* wuhbReader, sint32 priority)
{
return fsc_mount(mountPath, destinationBaseDir, &fscDeviceWUHB::instance(), wuhbReader, priority) == FSC_STATUS_OK;
}
| 3,953
|
C++
|
.cpp
| 141
| 25.06383
| 130
| 0.725145
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,024
|
fscDeviceHostFS.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/fscDeviceHostFS.cpp
|
#include "config/ActiveSettings.h"
#include "Cafe/Filesystem/fsc.h"
#include "Cafe/Filesystem/fscDeviceHostFS.h"
#include "Common/FileStream.h"
/* FSCVirtualFile implementation for HostFS */
FSCVirtualFile_Host::~FSCVirtualFile_Host()
{
if (m_type == FSC_TYPE_FILE)
delete m_fs;
}
sint32 FSCVirtualFile_Host::fscGetType()
{
return m_type;
}
uint32 FSCVirtualFile_Host::fscDeviceHostFSFile_getFileSize()
{
if (m_type == FSC_TYPE_FILE)
{
if (m_fileSize > 0xFFFFFFFFULL)
cemu_assert_suspicious(); // files larger than 4GB are not supported by Wii U filesystem
return (uint32)m_fileSize;
}
else if (m_type == FSC_TYPE_DIRECTORY)
{
// todo
return (uint32)0;
}
return 0;
}
uint64 FSCVirtualFile_Host::fscQueryValueU64(uint32 id)
{
if (m_type == FSC_TYPE_FILE)
{
if (id == FSC_QUERY_SIZE)
return fscDeviceHostFSFile_getFileSize();
else if (id == FSC_QUERY_WRITEABLE)
return m_isWritable;
else
cemu_assert_unimplemented();
}
else if (m_type == FSC_TYPE_DIRECTORY)
{
if (id == FSC_QUERY_SIZE)
return fscDeviceHostFSFile_getFileSize();
else
cemu_assert_unimplemented();
}
cemu_assert_unimplemented();
return 0;
}
uint32 FSCVirtualFile_Host::fscWriteData(void* buffer, uint32 size)
{
if (m_type != FSC_TYPE_FILE)
return 0;
if (size >= (2UL * 1024UL * 1024UL * 1024UL))
{
cemu_assert_suspicious();
return 0;
}
sint32 writtenBytes = m_fs->writeData(buffer, (sint32)size);
m_seek += (uint64)writtenBytes;
m_fileSize = std::max(m_fileSize, m_seek);
return (uint32)writtenBytes;
}
uint32 FSCVirtualFile_Host::fscReadData(void* buffer, uint32 size)
{
if (m_type != FSC_TYPE_FILE)
return 0;
if (size >= (2UL * 1024UL * 1024UL * 1024UL))
{
cemu_assert_suspicious();
return 0;
}
uint32 bytesLeft = (uint32)(m_fileSize - m_seek);
bytesLeft = std::min(bytesLeft, 0x7FFFFFFFu);
sint32 bytesToRead = std::min(bytesLeft, size);
uint32 bytesRead = m_fs->readData(buffer, bytesToRead);
m_seek += bytesRead;
return bytesRead;
}
void FSCVirtualFile_Host::fscSetSeek(uint64 seek)
{
if (m_type != FSC_TYPE_FILE)
return;
this->m_seek = seek;
cemu_assert_debug(seek <= m_fileSize);
m_fs->SetPosition(seek);
}
uint64 FSCVirtualFile_Host::fscGetSeek()
{
if (m_type != FSC_TYPE_FILE)
return 0;
return m_seek;
}
void FSCVirtualFile_Host::fscSetFileLength(uint64 endOffset)
{
if (m_type != FSC_TYPE_FILE)
return;
m_fs->SetPosition(endOffset);
bool r = m_fs->SetEndOfFile();
m_seek = std::min(m_seek, endOffset);
m_fileSize = m_seek;
m_fs->SetPosition(m_seek);
if (!r)
cemuLog_log(LogType::Force, "fscSetFileLength: Failed to set size to 0x{:x}", endOffset);
}
bool FSCVirtualFile_Host::fscDirNext(FSCDirEntry* dirEntry)
{
if (m_type != FSC_TYPE_DIRECTORY)
return false;
if (!m_dirIterator)
{
// init iterator on first iteration attempt
m_dirIterator.reset(new fs::directory_iterator(*m_path));
if (!m_dirIterator)
{
cemuLog_log(LogType::Force, "Failed to iterate directory: {}", _pathToUtf8(*m_path));
return false;
}
}
if (*m_dirIterator == fs::end(*m_dirIterator))
return false;
const fs::directory_entry& entry = **m_dirIterator;
std::string fileName = entry.path().filename().generic_string();
if (fileName.size() >= sizeof(dirEntry->path) - 1)
fileName.resize(sizeof(dirEntry->path) - 1);
strncpy(dirEntry->path, fileName.data(), sizeof(dirEntry->path));
if (entry.is_directory())
{
dirEntry->isDirectory = true;
dirEntry->isFile = false;
dirEntry->fileSize = 0;
}
else
{
dirEntry->isDirectory = false;
dirEntry->isFile = true;
dirEntry->fileSize = entry.file_size();
}
(*m_dirIterator)++;
return true;
}
FSCVirtualFile* FSCVirtualFile_Host::OpenFile(const fs::path& path, FSC_ACCESS_FLAG accessFlags, sint32& fscStatus)
{
if (!HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE) && !HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR))
cemu_assert_debug(false); // not allowed. At least one of both flags must be set
// attempt to open as file
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE))
{
FileStream* fs{};
bool writeAccessRequested = HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::WRITE_PERMISSION);
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::FILE_ALLOW_CREATE))
{
fs = FileStream::openFile2(path, writeAccessRequested);
if (!fs)
{
cemu_assert_debug(writeAccessRequested);
fs = FileStream::createFile2(path);
if (!fs)
cemuLog_log(LogType::Force, "FSC: File create failed for {}", _pathToUtf8(path));
}
}
else if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::FILE_ALWAYS_CREATE))
{
fs = FileStream::createFile2(path);
if (!fs)
cemuLog_log(LogType::Force, "FSC: File create failed for {}", _pathToUtf8(path));
}
else
{
fs = FileStream::openFile2(path, writeAccessRequested);
}
if (fs)
{
FSCVirtualFile_Host* vf = new FSCVirtualFile_Host(FSC_TYPE_FILE);
vf->m_fs = fs;
vf->m_isWritable = writeAccessRequested;
vf->m_fileSize = fs->GetSize();
fscStatus = FSC_STATUS_OK;
return vf;
}
}
// attempt to open as directory
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR))
{
std::error_code ec;
bool isExistingDir = fs::is_directory(path, ec);
if (isExistingDir)
{
FSCVirtualFile_Host* vf = new FSCVirtualFile_Host(FSC_TYPE_DIRECTORY);
vf->m_path.reset(new std::filesystem::path(path));
fscStatus = FSC_STATUS_OK;
return vf;
}
}
fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
/* Device implementation */
class fscDeviceHostFSC : public fscDeviceC
{
public:
FSCVirtualFile* fscDeviceOpenByPath(std::string_view path, FSC_ACCESS_FLAG accessFlags, void* ctx, sint32* fscStatus) override
{
*fscStatus = FSC_STATUS_OK;
FSCVirtualFile* vf = FSCVirtualFile_Host::OpenFile(_utf8ToPath(path), accessFlags, *fscStatus);
cemu_assert_debug((bool)vf == (*fscStatus == FSC_STATUS_OK));
return vf;
}
bool fscDeviceCreateDir(std::string_view path, void* ctx, sint32* fscStatus) override
{
fs::path dirPath = _utf8ToPath(path);
if (fs::exists(dirPath))
{
if (!fs::is_directory(dirPath))
cemuLog_log(LogType::Force, "CreateDir: {} already exists but is not a directory", path);
*fscStatus = FSC_STATUS_ALREADY_EXISTS;
return false;
}
std::error_code ec;
bool r = fs::create_directories(dirPath, ec);
if (!r)
cemuLog_log(LogType::Force, "CreateDir: Failed to create {}", path);
*fscStatus = FSC_STATUS_OK;
return true;
}
bool fscDeviceRemoveFileOrDir(std::string_view path, void* ctx, sint32* fscStatus) override
{
*fscStatus = FSC_STATUS_OK;
fs::path _path = _utf8ToPath(path);
std::error_code ec;
if (!fs::exists(_path, ec))
{
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return false;
}
if (!fs::remove(_path, ec))
{
cemu_assert_unimplemented(); // return correct error (e.g. if directory is non-empty)
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
}
return true;
}
bool fscDeviceRename(std::string_view srcPath, std::string_view dstPath, void* ctx, sint32* fscStatus) override
{
*fscStatus = FSC_STATUS_OK;
fs::path _srcPath = _utf8ToPath(srcPath);
fs::path _dstPath = _utf8ToPath(dstPath);
std::error_code ec;
if (!fs::exists(_srcPath, ec))
{
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return false;
}
fs::rename(_srcPath, _dstPath, ec);
return true;
}
// singleton
public:
static fscDeviceHostFSC& instance()
{
static fscDeviceHostFSC _instance;
return _instance;
}
};
bool FSCDeviceHostFS_Mount(std::string_view mountPath, std::string_view hostTargetPath, sint32 priority)
{
return fsc_mount(mountPath, hostTargetPath, &fscDeviceHostFSC::instance(), nullptr, priority) == FSC_STATUS_OK;
}
| 7,654
|
C++
|
.cpp
| 269
| 25.873606
| 127
| 0.715994
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,025
|
fsc.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/fsc.cpp
|
#include "Cafe/Filesystem/fsc.h"
#include "Cafe/Filesystem/FST/fstUtil.h"
struct FSCMountPathNode
{
std::string path;
std::vector<FSCMountPathNode*> subnodes;
FSCMountPathNode* parent;
// associated device target and path
fscDeviceC* device{ nullptr };
void* ctx{ nullptr };
std::string deviceTargetPath; // the destination base path for the device, utf8
// priority
sint32 priority{};
FSCMountPathNode(FSCMountPathNode* parent) : parent(parent)
{
}
void AssignDevice(fscDeviceC* device, void* ctx, std::string_view deviceBasePath)
{
this->device = device;
this->ctx = ctx;
this->deviceTargetPath = deviceBasePath;
}
void UnassignDevice()
{
this->device = nullptr;
this->ctx = nullptr;
this->deviceTargetPath.clear();
}
bool IsRootNode() const
{
return !parent;
}
~FSCMountPathNode()
{
for (auto& itr : subnodes)
delete itr;
subnodes.clear();
}
};
// compare two file or directory names using FSA rules
bool FSA_CompareNodeName(std::string_view a, std::string_view b)
{
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); i++)
{
uint8 ac = (uint8)a[i];
uint8 bc = (uint8)b[i];
// lower case compare
if (ac >= (uint8)'A' && ac <= (uint8)'Z')
ac -= ((uint8)'A' - (uint8)'a');
if (bc >= (uint8)'A' && bc <= (uint8)'Z')
bc -= ((uint8)'A' - (uint8)'a');
if (ac != bc)
return false;
}
return true;
}
FSCMountPathNode* s_fscRootNodePerPrio[FSC_PRIORITY_COUNT]{};
std::recursive_mutex s_fscMutex;
#define fscEnter() s_fscMutex.lock();
#define fscLeave() s_fscMutex.unlock();
FSCMountPathNode* fsc_lookupPathVirtualNode(const char* path, sint32 priority = FSC_PRIORITY_BASE);
void fsc_reset()
{
// delete existing nodes
for (auto& itr : s_fscRootNodePerPrio)
{
delete itr;
itr = nullptr;
}
// init root node for each priority
for (sint32 i = 0; i < FSC_PRIORITY_COUNT; i++)
s_fscRootNodePerPrio[i] = new FSCMountPathNode(nullptr);
}
/*
* Creates a node chain for the given mount path. Returns the bottom node.
* If the path already exists for the given priority, NULL is returned (we can't mount two devices to the same path with the same priority)
* But we can map devices to subdirectories. Something like this is possible:
* /vol/content -> Map to WUD (includes all subdirectories except /data, which is handled by the entry below. This exclusion rule applies only if the priority of both mount entries is the same)
* /vol/content/data -> Map to HostFS
* If overlapping paths with different priority are created, then the higher priority one will be checked first
*/
FSCMountPathNode* fsc_createMountPath(const FSCPath& mountPath, sint32 priority)
{
cemu_assert(priority >= 0 && priority < FSC_PRIORITY_COUNT);
fscEnter();
FSCMountPathNode* nodeParent = s_fscRootNodePerPrio[priority];
for (size_t i=0; i< mountPath.GetNodeCount(); i++)
{
// search for subdirectory
FSCMountPathNode* nodeSub = nullptr; // set if we found a subnode with a matching name, else this is used to store the new nodes
for (auto& nodeItr : nodeParent->subnodes)
{
if (mountPath.MatchNodeName(i, nodeItr->path))
{
// subnode found
nodeSub = nodeItr;
break;
}
}
if (nodeSub)
{
// traverse subnode
nodeParent = nodeSub;
continue;
}
// no matching subnode, add new entry
nodeSub = new FSCMountPathNode(nodeParent);
nodeSub->path = mountPath.GetNodeName(i);
nodeSub->priority = priority;
nodeParent->subnodes.emplace_back(nodeSub);
if (i == (mountPath.GetNodeCount() - 1))
{
// last node
fscLeave();
return nodeSub;
}
// traverse subnode
nodeParent = nodeSub;
}
// path is empty or already mounted
fscLeave();
if (mountPath.GetNodeCount() == 0)
return nodeParent;
return nullptr;
}
// Map a virtual FSC directory to a device. targetPath points to the destination base directory within the device
sint32 fsc_mount(std::string_view mountPath, std::string_view targetPath, fscDeviceC* fscDevice, void* ctx, sint32 priority)
{
cemu_assert(fscDevice);
std::string mountPathTmp(mountPath);
// make sure the target path ends with a slash
std::string targetPathWithSlash(targetPath);
if (!targetPathWithSlash.empty() && (targetPathWithSlash.back() != '/' && targetPathWithSlash.back() != '\\'))
targetPathWithSlash.push_back('/');
FSCPath parsedMountPath(mountPathTmp);
// register path
fscEnter();
FSCMountPathNode* node = fsc_createMountPath(parsedMountPath, priority);
if( !node )
{
// path empty, invalid or already used
cemuLog_log(LogType::Force, "fsc_mount failed (virtual path: {})", mountPath);
fscLeave();
return FSC_STATUS_INVALID_PATH;
}
node->AssignDevice(fscDevice, ctx, targetPathWithSlash);
fscLeave();
return FSC_STATUS_OK;
}
bool fsc_unmount(std::string_view mountPath, sint32 priority)
{
std::string _tmp(mountPath);
fscEnter();
FSCMountPathNode* mountPathNode = fsc_lookupPathVirtualNode(_tmp.c_str(), priority);
if (!mountPathNode)
{
fscLeave();
return false;
}
cemu_assert(mountPathNode->priority == priority);
cemu_assert(mountPathNode->device);
// unassign device
mountPathNode->UnassignDevice();
// prune empty branch
while (mountPathNode && !mountPathNode->IsRootNode() && mountPathNode->subnodes.empty() && !mountPathNode->device)
{
FSCMountPathNode* parent = mountPathNode->parent;
std::erase(parent->subnodes, mountPathNode);
delete mountPathNode;
mountPathNode = parent;
}
fscLeave();
return true;
}
void fsc_unmountAll()
{
fscEnter();
fsc_reset();
fscLeave();
}
// lookup virtual path and find mounted device and relative device directory
bool fsc_lookupPath(const char* path, std::string& devicePathOut, fscDeviceC** fscDeviceOut, void** ctxOut, sint32 priority = FSC_PRIORITY_BASE)
{
FSCPath parsedPath(path);
FSCMountPathNode* nodeParent = s_fscRootNodePerPrio[priority];
size_t i;
fscEnter();
for (i = 0; i < parsedPath.GetNodeCount(); i++)
{
// search for subdirectory
FSCMountPathNode* nodeSub = nullptr;
for(auto& nodeItr : nodeParent->subnodes)
{
if (parsedPath.MatchNodeName(i, nodeItr->path))
{
nodeSub = nodeItr;
break;
}
}
if (nodeSub)
{
nodeParent = nodeSub;
continue;
}
// no matching subnode
break;
}
// if the found node is not a device mount point, then travel back towards the root until we find one
while (nodeParent)
{
if (nodeParent->device)
{
devicePathOut = nodeParent->deviceTargetPath;
for (size_t f = i; f < parsedPath.GetNodeCount(); f++)
{
auto nodeName = parsedPath.GetNodeName(f);
devicePathOut.append(nodeName);
if (f < (parsedPath.GetNodeCount() - 1))
devicePathOut.push_back('/');
}
*fscDeviceOut = nodeParent->device;
*ctxOut = nodeParent->ctx;
fscLeave();
return true;
}
nodeParent = nodeParent->parent;
i--;
}
fscLeave();
return false;
}
// lookup path and find virtual device node
FSCMountPathNode* fsc_lookupPathVirtualNode(const char* path, sint32 priority)
{
FSCPath parsedPath(path);
FSCMountPathNode* nodeCurrentDir = s_fscRootNodePerPrio[priority];
fscEnter();
for (size_t i = 0; i < parsedPath.GetNodeCount(); i++)
{
// search for subdirectory
FSCMountPathNode* nodeSub = nullptr;
for (auto& nodeItr : nodeCurrentDir->subnodes)
{
if (parsedPath.MatchNodeName(i, nodeItr->path))
{
nodeSub = nodeItr;
break;
}
}
if (nodeSub)
{
// traverse subdirectory
nodeCurrentDir = nodeSub;
continue;
}
fscLeave();
return nullptr;
}
fscLeave();
return nodeCurrentDir;
}
// this wraps multiple iterated directories from different devices into one unified virtual representation
class FSCVirtualFileDirectoryIterator : public FSCVirtualFile
{
public:
sint32 fscGetType() override
{
return FSC_TYPE_DIRECTORY;
}
FSCVirtualFileDirectoryIterator(std::string_view path, std::span<FSCVirtualFile*> mappedFolders)
: m_path(path), m_folders(mappedFolders.begin(), mappedFolders.end())
{
dirIterator = nullptr;
}
~FSCVirtualFileDirectoryIterator()
{
// dirIterator is deleted in base constructor
for (auto& itr : m_folders)
delete itr;
}
bool fscDirNext(FSCDirEntry* dirEntry) override
{
if (!dirIterator)
{
// lazily populate list only if directory is actually iterated
PopulateIterationList();
cemu_assert_debug(dirIterator);
}
if (dirIterator->index >= dirIterator->dirEntries.size())
return false;
*dirEntry = dirIterator->dirEntries[dirIterator->index];
dirIterator->index++;
return true;
}
bool fscRewindDir() override
{
if (!dirIterator)
return true;
dirIterator->index = 0;
return true;
}
void addUniqueDirEntry(const FSCDirEntry& dirEntry)
{
// skip if already in list
for (auto& itr : dirIterator->dirEntries)
{
if (FSA_CompareNodeName(dirEntry.path, itr.path))
return;
}
dirIterator->dirEntries.emplace_back(dirEntry);
}
private:
void PopulateIterationList()
{
cemu_assert_debug(!dirIterator);
dirIterator = new FSCVirtualFile::FSCDirIteratorState();
FSCDirEntry dirEntry;
fscEnter();
for (auto& itr : m_folders)
{
while (itr->fscDirNext(&dirEntry))
addUniqueDirEntry(dirEntry);
}
for (sint32 prio = FSC_PRIORITY_COUNT - 1; prio >= 0; prio--)
{
FSCMountPathNode* nodeVirtualPath = fsc_lookupPathVirtualNode(m_path.c_str(), prio);
if (nodeVirtualPath)
{
for (auto& itr : nodeVirtualPath->subnodes)
{
dirEntry = {};
dirEntry.isDirectory = true;
strncpy(dirEntry.path, itr->path.c_str(), sizeof(dirEntry.path) - 1);
dirEntry.path[sizeof(dirEntry.path) - 1] = '\0';
dirEntry.fileSize = 0;
addUniqueDirEntry(dirEntry);
}
}
}
fscLeave();
}
private:
std::string m_path;
std::vector<FSCVirtualFile*> m_folders; // list of all folders mapped to the same directory (at different priorities)
};
// Open file or directory from virtual file system
FSCVirtualFile* fsc_open(const char* path, FSC_ACCESS_FLAG accessFlags, sint32* fscStatus, sint32 maxPriority)
{
cemu_assert_debug(HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE) || HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR)); // must open either file or directory
FSCVirtualFile* dirList[FSC_PRIORITY_COUNT];
uint8 dirListCount = 0;
std::string devicePath;
fscDeviceC* fscDevice = NULL;
*fscStatus = FSC_STATUS_UNDEFINED;
void* ctx;
fscEnter();
for (sint32 prio = maxPriority; prio >= 0; prio--)
{
if (fsc_lookupPath(path, devicePath, &fscDevice, &ctx, prio))
{
FSCVirtualFile* fscVirtualFile = fscDevice->fscDeviceOpenByPath(devicePath, accessFlags, ctx, fscStatus);
if (fscVirtualFile)
{
if (fscVirtualFile->fscGetType() == FSC_TYPE_DIRECTORY)
{
cemu_assert_debug(HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR));
// collect all folders
dirList[dirListCount] = fscVirtualFile;
dirListCount++;
}
else
{
// return first found file
cemu_assert_debug(HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_FILE));
fscVirtualFile->m_isAppend = HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::IS_APPEND);
fscLeave();
return fscVirtualFile;
}
}
}
}
// for directories we create a virtual representation of the enumerated files of all priorities as well as the FSC folder structure itself
if (HAS_FLAG(accessFlags, FSC_ACCESS_FLAG::OPEN_DIR))
{
// create a virtual directory VirtualFile that represents all the mounted folders as well as the virtual FSC folder structure
bool folderExists = dirListCount > 0;
for (sint32 prio = FSC_PRIORITY_COUNT - 1; prio >= 0; prio--)
{
if (folderExists)
break;
folderExists |= (fsc_lookupPathVirtualNode(path, prio) != 0);
}
if (folderExists)
{
FSCVirtualFileDirectoryIterator* dirIteratorFile = new FSCVirtualFileDirectoryIterator(path, { dirList, dirListCount});
*fscStatus = FSC_STATUS_OK;
fscLeave();
return dirIteratorFile;
}
}
else
{
cemu_assert_debug(dirListCount == 0);
}
fscLeave();
*fscStatus = FSC_STATUS_FILE_NOT_FOUND;
return nullptr;
}
/*
* Open file using virtual path
*/
FSCVirtualFile* fsc_openDirIterator(const char* path, sint32* fscStatus)
{
return fsc_open(path, FSC_ACCESS_FLAG::OPEN_DIR, fscStatus);
}
/*
* Iterate next node in directory
* Returns false if there is no node left
*/
bool fsc_nextDir(FSCVirtualFile* fscFile, FSCDirEntry* dirEntry)
{
fscEnter();
if (fscFile->fscGetType() != FSC_TYPE_DIRECTORY)
{
cemu_assert_suspicious();
fscLeave();
return false;
}
bool r = fscFile->fscDirNext(dirEntry);
fscLeave();
return r;
}
/*
* Create directory
*/
bool fsc_createDir(const char* path, sint32* fscStatus)
{
fscDeviceC* fscDevice = NULL;
*fscStatus = FSC_STATUS_UNDEFINED;
void* ctx;
std::string devicePath;
fscEnter();
if( fsc_lookupPath(path, devicePath, &fscDevice, &ctx) )
{
sint32 status = fscDevice->fscDeviceCreateDir(devicePath, ctx, fscStatus);
fscLeave();
return status;
}
fscLeave();
return false;
}
/*
* Rename file or directory
*/
bool fsc_rename(const char* srcPath, const char* dstPath, sint32* fscStatus)
{
std::string srcDevicePath;
std::string dstDevicePath;
void* srcCtx;
void* dstCtx;
fscDeviceC* fscSrcDevice = NULL;
fscDeviceC* fscDstDevice = NULL;
*fscStatus = FSC_STATUS_UNDEFINED;
if( fsc_lookupPath(srcPath, srcDevicePath, &fscSrcDevice, &srcCtx) && fsc_lookupPath(dstPath, dstDevicePath, &fscDstDevice, &dstCtx) )
{
if( fscSrcDevice == fscDstDevice )
return fscSrcDevice->fscDeviceRename(srcDevicePath, dstDevicePath, srcCtx, fscStatus);
}
return false;
}
/*
* Delete file or subdirectory
*/
bool fsc_remove(const char* path, sint32* fscStatus)
{
std::string devicePath;
fscDeviceC* fscDevice = NULL;
*fscStatus = FSC_STATUS_UNDEFINED;
void* ctx;
if( fsc_lookupPath(path, devicePath, &fscDevice, &ctx) )
{
return fscDevice->fscDeviceRemoveFileOrDir(devicePath, ctx, fscStatus);
}
return false;
}
/*
* Close file handle
*/
void fsc_close(FSCVirtualFile* fscFile)
{
fscEnter();
delete fscFile;
fscLeave();
}
/*
* Return size of file
*/
uint32 fsc_getFileSize(FSCVirtualFile* fscFile)
{
return (uint32)fscFile->fscQueryValueU64(FSC_QUERY_SIZE);
}
/*
* Return file position
*/
uint32 fsc_getFileSeek(FSCVirtualFile* fscFile)
{
return (uint32)fscFile->fscGetSeek();
}
/*
* Set file seek
* For writable files the seek pointer can be set past the end of the file
*/
void fsc_setFileSeek(FSCVirtualFile* fscFile, uint32 newSeek)
{
fscEnter();
uint32 fileSize = fsc_getFileSize(fscFile);
if (fsc_isWritable(fscFile) == false)
newSeek = std::min(newSeek, fileSize);
fscFile->fscSetSeek((uint64)newSeek);
fscLeave();
}
// set file length
void fsc_setFileLength(FSCVirtualFile* fscFile, uint32 newEndOffset)
{
fscEnter();
uint32 fileSize = fsc_getFileSize(fscFile);
if (!fsc_isWritable(fscFile))
{
cemuLog_log(LogType::Force, "TruncateFile called on read-only file");
}
else
{
fscFile->fscSetFileLength((uint64)newEndOffset);
}
fscLeave();
}
/*
* Returns true if the file object is a directory
*/
bool fsc_isDirectory(FSCVirtualFile* fscFile)
{
return fscFile->fscGetType() == FSC_TYPE_DIRECTORY;
}
/*
* Returns true if the file object is a file
*/
bool fsc_isFile(FSCVirtualFile* fscFile)
{
return fscFile->fscGetType() == FSC_TYPE_FILE;
}
/*
* Returns true if the file is writable
*/
bool fsc_isWritable(FSCVirtualFile* fscFile)
{
return fscFile->fscQueryValueU64(FSC_QUERY_WRITEABLE) != 0;
}
/*
* Read data from file
* Returns number of bytes successfully read
*/
uint32 fsc_readFile(FSCVirtualFile* fscFile, void* buffer, uint32 size)
{
fscEnter();
uint32 fscStatus = fscFile->fscReadData(buffer, size);
fscLeave();
return fscStatus;
}
/*
* Write data to file
* Returns number of bytes successfully written
*/
uint32 fsc_writeFile(FSCVirtualFile* fscFile, void* buffer, uint32 size)
{
fscEnter();
if (fsc_isWritable(fscFile) == false)
{
fscLeave();
return 0;
}
if (fscFile->m_isAppend)
fsc_setFileSeek(fscFile, fsc_getFileSize(fscFile));
uint32 fscStatus = fscFile->fscWriteData(buffer, size);
fscLeave();
return fscStatus;
}
// helper function to load a file into memory
uint8* fsc_extractFile(const char* path, uint32* fileSize, sint32 maxPriority)
{
fscDeviceC* fscDevice = nullptr;
sint32 fscStatus = FSC_STATUS_UNDEFINED;
fscEnter();
FSCVirtualFile* fscFile = fsc_open(path, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus, maxPriority);
if( !fscFile )
{
*fileSize = 0;
fscLeave();
return nullptr;
}
uint32 fscFileSize = fsc_getFileSize(fscFile);
*fileSize = fscFileSize;
uint8* fileMem = (uint8*)malloc(fscFileSize);
if( fsc_readFile(fscFile, fileMem, fscFileSize) != fscFileSize )
{
free(fileMem);
fsc_close(fscFile);
*fileSize = 0;
fscLeave();
return nullptr;
}
fsc_close(fscFile);
fscLeave();
return fileMem;
}
std::optional<std::vector<uint8>> fsc_extractFile(const char* path, sint32 maxPriority)
{
fscDeviceC* fscDevice = nullptr;
sint32 fscStatus = FSC_STATUS_UNDEFINED;
fscEnter();
FSCVirtualFile* fscFile = fsc_open(path, FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus, maxPriority);
if (!fscFile)
{
fscLeave();
return std::nullopt;
}
std::vector<uint8> fileData;
uint32 fscFileSize = fsc_getFileSize(fscFile);
fileData.resize(fscFileSize);
uint32 readOffset = 0;
while (readOffset < fscFileSize)
{
uint32 stepReadSize = std::min(fscFileSize - readOffset, (uint32)1024 * 1024 * 32);
uint32 numBytesRead = fsc_readFile(fscFile, fileData.data() + readOffset, stepReadSize);
if (numBytesRead != stepReadSize)
{
fsc_close(fscFile);
fscLeave();
return std::nullopt;
}
readOffset += stepReadSize;
}
fsc_close(fscFile);
fscLeave();
return fileData;
}
// helper function to check if a file exists
bool fsc_doesFileExist(const char* path, sint32 maxPriority)
{
fscDeviceC* fscDevice = nullptr;
sint32 fscStatus = FSC_STATUS_UNDEFINED;
fscEnter();
FSCVirtualFile* fscFile = fsc_open(path, FSC_ACCESS_FLAG::OPEN_FILE, &fscStatus, maxPriority);
if (!fscFile)
{
fscLeave();
return false;
}
fsc_close(fscFile);
fscLeave();
return true;
}
// helper function to check if a directory exists
bool fsc_doesDirectoryExist(const char* path, sint32 maxPriority)
{
fscDeviceC* fscDevice = nullptr;
sint32 fscStatus = FSC_STATUS_UNDEFINED;
fscEnter();
FSCVirtualFile* fscFile = fsc_open(path, FSC_ACCESS_FLAG::OPEN_DIR, &fscStatus, maxPriority);
if (!fscFile)
{
fscLeave();
return false;
}
fsc_close(fscFile);
fscLeave();
return true;
}
// initialize Cemu's virtual filesystem
void fsc_init()
{
fsc_reset();
}
| 18,692
|
C++
|
.cpp
| 684
| 24.729532
| 195
| 0.731135
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,026
|
FST.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/FST/FST.cpp
|
#include "Common/precompiled.h"
#include "Common/FileStream.h"
#include "Cemu/ncrypto/ncrypto.h"
#include "Cafe/Filesystem/WUD/wud.h"
#include "util/crypto/aes128.h"
#include "openssl/sha.h" /* SHA1 / SHA256 */
#include "fstUtil.h"
#include "FST.h"
#include "KeyCache.h"
#include "boost/range/adaptor/reversed.hpp"
#define SET_FST_ERROR(__code) if (errorCodeOut) *errorCodeOut = ErrorCode::__code
class FSTDataSource
{
public:
virtual uint64 readData(uint16 clusterIndex, uint64 clusterOffset, uint64 offset, void* data, uint64 size) = 0;
virtual ~FSTDataSource() {};
protected:
FSTDataSource() {};
bool m_isOpen;
};
class FSTDataSourceWUD : public FSTDataSource
{
public:
static FSTDataSourceWUD* Open(const fs::path& path)
{
wud_t* wudFile = wud_open(path);
if (!wudFile)
return nullptr;
FSTDataSourceWUD* ds = new FSTDataSourceWUD();
ds->m_wudFile = wudFile;
return ds;
}
void SetBaseOffset(uint64 baseOffset)
{
m_baseOffset = baseOffset;
}
uint64 GetBaseOffset() const
{
return m_baseOffset;
}
uint64 readData(uint16 clusterIndex, uint64 clusterOffset, uint64 offset, void* data, uint64 size) override
{
cemu_assert_debug(size <= 0xFFFFFFFF);
return wud_readData(m_wudFile, data, (uint32)size, clusterOffset + offset + m_baseOffset);
}
~FSTDataSourceWUD() override
{
if(m_wudFile)
wud_close(m_wudFile);
}
protected:
FSTDataSourceWUD() {}
wud_t* m_wudFile;
uint64 m_baseOffset{};
std::vector<uint64> m_clusterOffset;
};
class FSTDataSourceApp : public FSTDataSource
{
public:
static FSTDataSourceApp* Open(fs::path path, NCrypto::TMDParser& tmd)
{
std::vector<std::unique_ptr<FileStream>> clusterFile;
uint32 maxIndex = 0;
for (auto& itr : tmd.GetContentList())
maxIndex = std::max(maxIndex, (uint32)itr.index);
clusterFile.resize(maxIndex + 1);
// open all the app files
for (auto& itr : tmd.GetContentList())
{
FileStream* appFile = FileStream::openFile2(path / fmt::format("{:08x}.app", itr.contentId));
if (!appFile)
return nullptr;
clusterFile[itr.index].reset(appFile);
}
// construct FSTDataSourceApp
FSTDataSourceApp* dsApp = new FSTDataSourceApp(std::move(clusterFile));
return dsApp;
}
uint64 readData(uint16 clusterIndex, uint64 clusterOffset, uint64 offset, void* data, uint64 size) override
{
// ignore clusterOffset for .app files since each file is already relative to the cluster base
cemu_assert_debug(clusterIndex < m_clusterFile.size());
cemu_assert_debug(m_clusterFile[clusterIndex].get());
cemu_assert_debug(size <= 0xFFFFFFFF);
if (!m_clusterFile[clusterIndex].get())
return 0;
m_clusterFile[clusterIndex].get()->SetPosition(offset);
return m_clusterFile[clusterIndex].get()->readData(data, (uint32)size);
}
~FSTDataSourceApp() override
{
}
private:
FSTDataSourceApp(std::vector<std::unique_ptr<FileStream>>&& clusterFiles)
{
m_clusterFile = std::move(clusterFiles);
}
std::vector<std::unique_ptr<FileStream>> m_clusterFile;
};
constexpr size_t DISC_SECTOR_SIZE = 0x8000;
struct DiscHeaderA
{
// header in first sector (0x0)
uint8 productCode[22]; // ?
};
struct DiscHeaderB
{
// header at 0x10000
static constexpr uint32 MAGIC_VALUE = 0xCC549EB9;
/* +0x00 */ uint32be magic;
};
static_assert(sizeof(DiscHeaderB) == 0x04);
struct DiscPartitionTableHeader
{
// header at 0x18000, encrypted
static constexpr uint32 MAGIC_VALUE = 0xCCA6E67B;
/* +0x00 */ uint32be magic;
/* +0x04 */ uint32be blockSize; // must be 0x8000?
/* +0x08 */ uint8 partitionTableHash[20]; // hash of the data range at +0x800 to end of sector (0x8000)
/* +0x1C */ uint32be numPartitions;
};
static_assert(sizeof(DiscPartitionTableHeader) == 0x20);
struct DiscPartitionTableEntry
{
/* +0x00 */ uint8be partitionName[31];
/* +0x1F */ uint8be numAddresses; // ?
/* +0x20 */ uint32be partitionAddress; // this is an array?
/* +0x24 */ uint8 padding[0x80 - 0x24];
};
static_assert(sizeof(DiscPartitionTableEntry) == 0x80);
struct DiscPartitionHeader
{
// header at the beginning of each partition
static constexpr uint32 MAGIC_VALUE = 0xCC93A4F5;
/* +0x00 */ uint32be magic;
/* +0x04 */ uint32be sectorSize; // must match DISC_SECTOR_SIZE for hashed blocks
/* +0x08 */ uint32be ukn008;
/* +0x0C */ uint32be ukn00C; // h3 array size?
/* +0x10 */ uint32be h3HashNum;
/* +0x14 */ uint32be fstSize; // in bytes
/* +0x18 */ uint32be fstSector; // relative to partition start
/* +0x1C */ uint32be ukn01C;
/* +0x20 */ uint32be ukn020;
// the hash and encryption mode for the FST cluster
/* +0x24 */ uint8 fstHashType;
/* +0x25 */ uint8 fstEncryptionType; // purpose of this isn't really understood. Maybe it controls which key is being used? (1 -> disc key, 2 -> partition key)
/* +0x26 */ uint8be versionA;
/* +0x27 */ uint8be ukn027; // also a version field?
// there is an array at +0x40 ? Related to H3 list. Also related to value at +0x0C and h3HashNum
/* +0x28 */ uint8be _uknOrPadding028[0x18];
/* +0x40 */ uint8be h3HashArray[32]; // dynamic size. Only present if fstHashType != 0
};
static_assert(sizeof(DiscPartitionHeader) == 0x40+0x20);
bool FSTVolume::FindDiscKey(const fs::path& path, NCrypto::AesKey& discTitleKey)
{
std::unique_ptr<FSTDataSourceWUD> dataSource(FSTDataSourceWUD::Open(path));
if (!dataSource)
return false;
// read section of header which should only contain zero bytes if decrypted
uint8 header[16*3];
if (dataSource->readData(0, 0, 0x18000 + 0x100, header, sizeof(header)) != sizeof(header))
return false;
// try all the keys
uint8 headerDecrypted[sizeof(header)-16];
for (sint32 i = 0; i < 0x7FFFFFFF; i++)
{
uint8* key128 = KeyCache_GetAES128(i);
if (key128 == NULL)
break;
AES128_CBC_decrypt(headerDecrypted, header + 16, sizeof(headerDecrypted), key128, header);
if (std::all_of(headerDecrypted, headerDecrypted + sizeof(headerDecrypted), [](const uint8 v) {return v == 0; }))
{
// key found
std::memcpy(discTitleKey.b, key128, 16);
return true;
}
}
return false;
}
// open WUD image using key cache
// if no matching key is found then keyFound will return false
FSTVolume* FSTVolume::OpenFromDiscImage(const fs::path& path, ErrorCode* errorCodeOut)
{
SET_FST_ERROR(UNKNOWN_ERROR);
KeyCache_Prepare();
NCrypto::AesKey discTitleKey;
if (!FindDiscKey(path, discTitleKey))
{
SET_FST_ERROR(DISC_KEY_MISSING);
return nullptr;
}
return OpenFromDiscImage(path, discTitleKey, errorCodeOut);
}
// open WUD image
FSTVolume* FSTVolume::OpenFromDiscImage(const fs::path& path, NCrypto::AesKey& discTitleKey, ErrorCode* errorCodeOut)
{
// WUD images support multiple partitions, each with their own key and FST
// the process for loading game data FSTVolume from a WUD image is as follows:
// 1) parse WUD headers and verify
// 2) read SI partition FST
// 3) find main GM partition
// 4) use SI information to get titleKey for GM partition
// 5) Load FST for GM
SET_FST_ERROR(UNKNOWN_ERROR);
std::unique_ptr<FSTDataSourceWUD> dataSource(FSTDataSourceWUD::Open(path));
if (!dataSource)
return nullptr;
// check HeaderA (only contains product code?)
DiscHeaderA headerA{};
if (dataSource->readData(0, 0, 0, &headerA, sizeof(headerA)) != sizeof(headerA))
return nullptr;
// check HeaderB
DiscHeaderB headerB{};
if (dataSource->readData(0, 0, DISC_SECTOR_SIZE * 2, &headerB, sizeof(headerB)) != sizeof(headerB))
return nullptr;
if (headerB.magic != headerB.MAGIC_VALUE)
return nullptr;
// read, decrypt and parse partition table
uint8 partitionSector[DISC_SECTOR_SIZE];
if (dataSource->readData(0, 0, DISC_SECTOR_SIZE * 3, partitionSector, DISC_SECTOR_SIZE) != DISC_SECTOR_SIZE)
return nullptr;
uint8 iv[16]{};
AES128_CBC_decrypt(partitionSector, partitionSector, DISC_SECTOR_SIZE, discTitleKey.b, iv);
// parse partition info
DiscPartitionTableHeader* partitionHeader = (DiscPartitionTableHeader*)partitionSector;
if (partitionHeader->magic != DiscPartitionTableHeader::MAGIC_VALUE)
{
cemuLog_log(LogType::Force, "Disc image rejected because decryption failed");
return nullptr;
}
if (partitionHeader->blockSize != DISC_SECTOR_SIZE)
{
cemuLog_log(LogType::Force, "Disc image rejected because partition sector size is invalid");
return nullptr;
}
uint32 numPartitions = partitionHeader->numPartitions;
if (numPartitions > 30) // there is space for up to 240 partitions but we use a more reasonable limit
{
cemuLog_log(LogType::Force, "Disc image rejected due to exceeding the partition limit (has {} partitions)", numPartitions);
return nullptr;
}
DiscPartitionTableEntry* partitionArray = (DiscPartitionTableEntry*)(partitionSector + 0x800);
// validate partitions and find SI partition
uint32 siPartitionIndex = std::numeric_limits<uint32>::max();
uint32 gmPartitionIndex = std::numeric_limits<uint32>::max();
for (uint32 i = 0; i < numPartitions; i++)
{
if (partitionArray[i].numAddresses != 1)
{
cemuLog_log(LogType::Force, "Disc image has unsupported partition with {} addresses", (uint32)partitionArray[i].numAddresses);
return nullptr;
}
auto& name = partitionArray[i].partitionName;
if (name[0] == 'S' && name[1] == 'I')
{
if (siPartitionIndex != std::numeric_limits<uint32>::max())
{
cemuLog_log(LogType::Force, "Disc image has multiple SI partitions. Not supported");
return nullptr;
}
siPartitionIndex = i;
}
if (name[0] == 'G' && name[1] == 'M')
{
if (gmPartitionIndex == std::numeric_limits<uint32>::max())
gmPartitionIndex = i; // we use the first GM partition we find. This is likely not correct but it seems to work for practically all disc images
}
}
if (siPartitionIndex == std::numeric_limits<uint32>::max() || gmPartitionIndex == std::numeric_limits<uint32>::max())
{
cemuLog_log(LogType::Force, "Disc image has no SI or GM partition. Cannot read game data");
return nullptr;
}
// read and verify partition headers for SI and GM
auto readPartitionHeader = [&](DiscPartitionHeader& partitionHeader, uint32 partitionIndex) -> bool
{
cemu_assert_debug(dataSource->GetBaseOffset() == 0);
if (dataSource->readData(0, 0, partitionArray[partitionIndex].partitionAddress * DISC_SECTOR_SIZE, &partitionHeader, sizeof(DiscPartitionHeader)) != sizeof(DiscPartitionHeader))
return false;
if (partitionHeader.magic != partitionHeader.MAGIC_VALUE && partitionHeader.sectorSize != DISC_SECTOR_SIZE)
return false;
return true;
};
// SI partition
DiscPartitionHeader partitionHeaderSI{};
if (!readPartitionHeader(partitionHeaderSI, siPartitionIndex))
{
cemuLog_log(LogType::Force, "Disc image SI partition header is invalid");
return nullptr;
}
cemu_assert_debug(partitionHeaderSI.fstHashType == 0);
cemu_assert_debug(partitionHeaderSI.fstEncryptionType == 1);
// todo - check other fields?
if(partitionHeaderSI.fstHashType == 0 && partitionHeaderSI.h3HashNum != 0)
cemuLog_log(LogType::Force, "FST: Partition uses unhashed blocks but stores a non-zero amount of H3 hashes");
// GM partition
DiscPartitionHeader partitionHeaderGM{};
if (!readPartitionHeader(partitionHeaderGM, gmPartitionIndex))
{
cemuLog_log(LogType::Force, "Disc image GM partition header is invalid");
return nullptr;
}
cemu_assert_debug(partitionHeaderGM.fstHashType == 1);
cemu_assert_debug(partitionHeaderGM.fstEncryptionType == 2);
// if decryption is necessary
// load SI FST
dataSource->SetBaseOffset((uint64)partitionArray[siPartitionIndex].partitionAddress * DISC_SECTOR_SIZE);
auto siFST = OpenFST(dataSource.get(), (uint64)partitionHeaderSI.fstSector * DISC_SECTOR_SIZE, partitionHeaderSI.fstSize, &discTitleKey, static_cast<FSTVolume::ClusterHashMode>(partitionHeaderSI.fstHashType), nullptr);
if (!siFST)
return nullptr;
cemu_assert_debug(!(siFST->HashIsDisabled() && partitionHeaderSI.h3HashNum != 0)); // if hash is disabled, no H3 data may be present
// load ticket file for partition that we want to decrypt
NCrypto::ETicketParser ticketParser;
std::vector<uint8> ticketData = siFST->ExtractFile(fmt::format("{:02x}/title.tik", gmPartitionIndex));
if (ticketData.empty() || !ticketParser.parse(ticketData.data(), ticketData.size()))
{
cemuLog_log(LogType::Force, "Disc image ticket file is invalid");
return nullptr;
}
#if 0
// each SI partition seems to contain a title.tmd that we could parse and which should have information about the associated GM partition
// but the console seems to ignore this file for disc images, at least when mounting, so we shouldn't rely on it either
std::vector<uint8> tmdData = siFST->ExtractFile(fmt::format("{:02x}/title.tmd", gmPartitionIndex));
if (tmdData.empty())
{
cemuLog_log(LogType::Force, "Disc image TMD file is missing");
return nullptr;
}
// parse TMD
NCrypto::TMDParser tmdParser;
if (!tmdParser.parse(tmdData.data(), tmdData.size()))
{
cemuLog_log(LogType::Force, "Disc image TMD file is invalid");
return nullptr;
}
#endif
delete siFST;
NCrypto::AesKey gmTitleKey;
ticketParser.GetTitleKey(gmTitleKey);
// load GM partition
dataSource->SetBaseOffset((uint64)partitionArray[gmPartitionIndex].partitionAddress * DISC_SECTOR_SIZE);
FSTVolume* r = OpenFST(std::move(dataSource), (uint64)partitionHeaderGM.fstSector * DISC_SECTOR_SIZE, partitionHeaderGM.fstSize, &gmTitleKey, static_cast<FSTVolume::ClusterHashMode>(partitionHeaderGM.fstHashType), nullptr);
if (r)
SET_FST_ERROR(OK);
cemu_assert_debug(!(r->HashIsDisabled() && partitionHeaderGM.h3HashNum != 0)); // if hash is disabled, no H3 data may be present
return r;
}
FSTVolume* FSTVolume::OpenFromContentFolder(fs::path folderPath, ErrorCode* errorCodeOut)
{
SET_FST_ERROR(UNKNOWN_ERROR);
// load TMD
FileStream* tmdFile = FileStream::openFile2(folderPath / "title.tmd");
if (!tmdFile)
return nullptr;
std::vector<uint8> tmdData;
tmdFile->extract(tmdData);
delete tmdFile;
NCrypto::TMDParser tmdParser;
if (!tmdParser.parse(tmdData.data(), tmdData.size()))
{
SET_FST_ERROR(BAD_TITLE_TMD);
return nullptr;
}
// load ticket
FileStream* ticketFile = FileStream::openFile2(folderPath / "title.tik");
if (!ticketFile)
{
SET_FST_ERROR(TITLE_TIK_MISSING);
return nullptr;
}
std::vector<uint8> ticketData;
ticketFile->extract(ticketData);
delete ticketFile;
NCrypto::ETicketParser ticketParser;
if (!ticketParser.parse(ticketData.data(), ticketData.size()))
{
SET_FST_ERROR(BAD_TITLE_TIK);
return nullptr;
}
NCrypto::AesKey titleKey;
ticketParser.GetTitleKey(titleKey);
// open data source
std::unique_ptr<FSTDataSource> dataSource(FSTDataSourceApp::Open(folderPath, tmdParser));
if (!dataSource)
return nullptr;
// get info about FST from first cluster (todo - is this correct or does the TMD store info about the fst?)
ClusterHashMode fstHashMode = ClusterHashMode::RAW;
uint32 fstSize = 0;
for (auto& itr : tmdParser.GetContentList())
{
if (itr.index == 0)
{
if (HAS_FLAG(itr.contentFlags, NCrypto::TMDParser::TMDContentFlags::FLAG_HASHED_CONTENT))
fstHashMode = ClusterHashMode::HASH_INTERLEAVED;
cemu_assert_debug(itr.size <= 0xFFFFFFFF);
fstSize = (uint32)itr.size;
}
}
// load FST
// fstSize = size of first cluster?
FSTVolume* fstVolume = FSTVolume::OpenFST(std::move(dataSource), 0, fstSize, &titleKey, fstHashMode, &tmdParser);
if (fstVolume)
SET_FST_ERROR(OK);
return fstVolume;
}
FSTVolume* FSTVolume::OpenFST(FSTDataSource* dataSource, uint64 fstOffset, uint32 fstSize, NCrypto::AesKey* partitionTitleKey, ClusterHashMode fstHashMode, NCrypto::TMDParser* optionalTMD)
{
cemu_assert_debug(fstHashMode != ClusterHashMode::RAW || fstHashMode != ClusterHashMode::RAW_STREAM);
if (fstSize < sizeof(FSTHeader))
return nullptr;
constexpr uint64 FST_CLUSTER_OFFSET = 0;
uint32 fstSizePadded = (fstSize + 15) & ~15; // pad to AES block size
// read FST data and decrypt
std::vector<uint8> fstData(fstSizePadded);
if (dataSource->readData(0, FST_CLUSTER_OFFSET, fstOffset, fstData.data(), fstSizePadded) != fstSizePadded)
return nullptr;
uint8 iv[16]{};
AES128_CBC_decrypt(fstData.data(), fstData.data(), fstSizePadded, partitionTitleKey->b, iv);
// validate header
FSTHeader* fstHeader = (FSTHeader*)fstData.data();
const void* fstEnd = fstData.data() + fstSize;
if (fstHeader->magic != 0x46535400 || fstHeader->numCluster >= 0x1000)
{
cemuLog_log(LogType::Force, "FST has invalid header");
return nullptr;
}
// load cluster table
uint32 numCluster = fstHeader->numCluster;
FSTHeader_ClusterEntry* clusterDataTable = (FSTHeader_ClusterEntry*)(fstData.data() + sizeof(FSTHeader));
if ((clusterDataTable + numCluster) > fstEnd)
return nullptr;
std::vector<FSTCluster> clusterTable;
clusterTable.resize(numCluster);
for (size_t i = 0; i < numCluster; i++)
{
clusterTable[i].offset = clusterDataTable[i].offset;
clusterTable[i].size = clusterDataTable[i].size;
clusterTable[i].hashMode = static_cast<FSTVolume::ClusterHashMode>((uint8)clusterDataTable[i].hashMode);
clusterTable[i].hasContentHash = false; // from the TMD file (H4?)
}
// if the TMD is available (when opening .app files) we can use the extra info from it to validate unhashed clusters
// each content entry in the TMD corresponds to one cluster used by the FST
if(optionalTMD)
{
if(numCluster != optionalTMD->GetContentList().size())
{
cemuLog_log(LogType::Force, "FST: Number of clusters does not match TMD content list");
return nullptr;
}
auto& contentList = optionalTMD->GetContentList();
for(size_t i=0; i<contentList.size(); i++)
{
auto& cluster = clusterTable[i];
auto& content = contentList[i];
cluster.hasContentHash = true;
cluster.contentHashIsSHA1 = HAS_FLAG(contentList[i].contentFlags, NCrypto::TMDParser::TMDContentFlags::FLAG_SHA1);
cluster.contentSize = content.size;
static_assert(sizeof(content.hash32) == sizeof(cluster.contentHash32));
memcpy(cluster.contentHash32, content.hash32, sizeof(cluster.contentHash32));
// if unhashed mode, then initialize the hash context
if(cluster.hashMode == ClusterHashMode::RAW || cluster.hashMode == ClusterHashMode::RAW_STREAM)
{
cluster.singleHashCtx.reset(EVP_MD_CTX_new());
EVP_DigestInit_ex(cluster.singleHashCtx.get(), cluster.contentHashIsSHA1 ? EVP_sha1() : EVP_sha256(), nullptr);
}
}
}
// preprocess FST table
FSTHeader_FileEntry* fileTable = (FSTHeader_FileEntry*)(clusterDataTable + numCluster);
if ((fileTable + 1) > fstEnd)
return nullptr;
if (fileTable[0].GetType() != FSTHeader_FileEntry::TYPE::DIRECTORY)
return nullptr;
uint32 numFileEntries = fileTable[0].size;
if (numFileEntries == 0 || (fileTable + numFileEntries) > fstEnd)
return nullptr;
// load name string table
ptrdiff_t nameLookupTableSize = ((const uint8*)fstEnd - (const uint8*)(fileTable + numFileEntries));
if (nameLookupTableSize < 1)
return nullptr;
std::vector<char> nameStringTable(nameLookupTableSize);
std::memcpy(nameStringTable.data(), (fileTable + numFileEntries), nameLookupTableSize);
// process FST
std::vector<FSTEntry> fstEntries;
if (!ProcessFST(fileTable, numFileEntries, numCluster, nameStringTable, fstEntries))
return nullptr;
// construct FSTVolume from the processed data
FSTVolume* fstVolume = new FSTVolume();
fstVolume->m_dataSource = dataSource;
fstVolume->m_offsetFactor = fstHeader->offsetFactor;
fstVolume->m_sectorSize = DISC_SECTOR_SIZE;
fstVolume->m_partitionTitlekey = *partitionTitleKey;
fstVolume->m_hashIsDisabled = fstHeader->hashIsDisabled != 0;
fstVolume->m_cluster = std::move(clusterTable);
fstVolume->m_entries = std::move(fstEntries);
fstVolume->m_nameStringTable = std::move(nameStringTable);
return fstVolume;
}
FSTVolume* FSTVolume::OpenFST(std::unique_ptr<FSTDataSource> dataSource, uint64 fstOffset, uint32 fstSize, NCrypto::AesKey* partitionTitleKey, ClusterHashMode fstHashMode, NCrypto::TMDParser* optionalTMD)
{
FSTDataSource* ds = dataSource.release();
FSTVolume* fstVolume = OpenFST(ds, fstOffset, fstSize, partitionTitleKey, fstHashMode, optionalTMD);
if (!fstVolume)
{
delete ds;
return nullptr;
}
fstVolume->m_sourceIsOwned = true;
return fstVolume;
}
bool FSTVolume::ProcessFST(FSTHeader_FileEntry* fileTable, uint32 numFileEntries, uint32 numCluster, std::vector<char>& nameStringTable, std::vector<FSTEntry>& fstEntries)
{
struct DirHierachyInfo
{
DirHierachyInfo(uint32 parentIndex, uint32 endIndex) : parentIndex(parentIndex), endIndex(endIndex) {};
uint32 parentIndex;
uint32 endIndex;
};
std::vector<DirHierachyInfo> currentDirEnd;
currentDirEnd.reserve(32);
currentDirEnd.emplace_back(0, numFileEntries); // create a fake parent for the root directory, the root's parent index is zero (referencing itself)
uint32 currentIndex = 0;
FSTHeader_FileEntry* pFileIn = fileTable + currentIndex;
fstEntries.resize(numFileEntries);
FSTEntry* pFileOut = fstEntries.data();
// validate root directory
if (pFileIn->GetType() != FSTHeader_FileEntry::TYPE::DIRECTORY || pFileIn->GetDirectoryEndIndex() != numFileEntries || pFileIn->GetDirectoryParent() != 0)
{
cemuLog_log(LogType::Force, "FSTVolume::ProcessFST() - root node is invalid");
return false;
}
for (; currentIndex < numFileEntries; currentIndex++)
{
while (currentIndex >= currentDirEnd.back().endIndex)
currentDirEnd.pop_back();
// process entry name
uint32 nameOffset = pFileIn->GetNameOffset();
uint32 pos = nameOffset;
while (true)
{
if (pos >= nameStringTable.size())
return false; // name exceeds string table
if (nameStringTable[pos] == '\0')
break;
pos++;
}
uint32 nameLen = pos - nameOffset;
pFileOut->nameOffset = nameOffset;
pFileOut->nameHash = _QuickNameHash(nameStringTable.data() + nameOffset, nameLen);
// parent directory index
pFileOut->parentDirIndex = currentDirEnd.back().parentIndex;
//if (currentDirEnd.back().parentIndex == 0)
// pFileOut->parentDirIndex = std::numeric_limits<uint32>::max();
//else
// pFileOut->parentDirIndex = currentDirEnd.back().parentIndex;
// process type specific data
auto entryType = pFileIn->GetType();
uint8 flags = 0;
if (pFileIn->HasFlagLink())
flags |= FSTEntry::FLAG_LINK;
if (pFileIn->HasUknFlag02())
flags |= FSTEntry::FLAG_UKN02;
pFileOut->SetFlags((FSTEntry::FLAGS)flags);
if (entryType == FSTHeader_FileEntry::TYPE::FILE)
{
bool isSysLink = entryType == FSTHeader_FileEntry::TYPE::FILE;
if (pFileIn->clusterIndex >= numCluster)
{
cemuLog_log(LogType::Force, "FST: File references cluster out of range");
return false;
}
cemu_assert_debug(pFileIn->flagsOrPermissions != 0x4004);
pFileOut->SetType(FSTEntry::TYPE::FILE);
pFileOut->fileInfo.fileOffset = pFileIn->offset;
pFileOut->fileInfo.fileSize = pFileIn->size;
pFileOut->fileInfo.clusterIndex = pFileIn->clusterIndex;
}
else if (entryType == FSTHeader_FileEntry::TYPE::DIRECTORY)
{
cemu_assert_debug(pFileIn->flagsOrPermissions != 0x4004);
pFileOut->SetType(FSTEntry::TYPE::DIRECTORY);
uint32 endIndex = pFileIn->GetDirectoryEndIndex();
uint32 parentIndex = pFileIn->GetDirectoryParent();
if (endIndex < currentIndex || endIndex > currentDirEnd.back().endIndex)
{
cemuLog_log(LogType::Force, "FST: Directory range out of bounds");
return false; // dir index out of range
}
if (parentIndex != currentDirEnd.back().parentIndex)
{
cemuLog_log(LogType::Force, "FST: Parent index does not match");
cemu_assert_debug(false);
return false;
}
currentDirEnd.emplace_back(currentIndex, endIndex);
pFileOut->dirInfo.endIndex = endIndex;
}
else
{
cemuLog_log(LogType::Force, "FST: Encountered node with unknown type");
cemu_assert_debug(false);
return false;
}
pFileIn++;
pFileOut++;
}
// end remaining directory hierarchy with final index
cemu_assert_debug(currentIndex == numFileEntries);
while (!currentDirEnd.empty() && currentIndex >= currentDirEnd.back().endIndex)
currentDirEnd.pop_back();
cemu_assert_debug(currentDirEnd.empty()); // no entries should remain
return true;
}
uint32 FSTVolume::GetFileCount() const
{
uint32 fileCount = 0;
for (auto& itr : m_entries)
{
if (itr.GetType() == FSTEntry::TYPE::FILE)
fileCount++;
}
return fileCount;
}
bool FSTVolume::OpenFile(std::string_view path, FSTFileHandle& fileHandleOut, bool openOnlyFiles)
{
FSCPath fscPath(path);
if (fscPath.GetNodeCount() == 0)
{
// empty path pointers to root directory
if(openOnlyFiles)
return false;
fileHandleOut.m_fstIndex = 0;
return true;
}
// scan directory and find sub folder or file
// skips iterating subdirectories
auto findSubentry = [this](size_t firstIndex, size_t lastIndex, std::string_view nodeName) -> sint32
{
uint16 nodeHash = _QuickNameHash(nodeName.data(), nodeName.size());
size_t index = firstIndex;
while (index < lastIndex)
{
if (m_entries[index].nameHash == nodeHash && MatchFSTEntryName(m_entries[index], nodeName))
return (sint32)index;
if (m_entries[index].GetType() == FSTEntry::TYPE::DIRECTORY)
index = m_entries[index].dirInfo.endIndex;
else
index++;
}
return -1;
};
// current FST range we iterate, starting with root directory which covers all entries
uint32 parentIndex = std::numeric_limits<uint32>::max();
size_t curDirStart = 1; // skip root directory
size_t curDirEnd = m_entries[0].dirInfo.endIndex;
// find the subdirectory
for (size_t nodeIndex = 0; nodeIndex < fscPath.GetNodeCount() - 1; nodeIndex++)
{
// get hash of node name
sint32 fstIndex = findSubentry(curDirStart, curDirEnd, fscPath.GetNodeName(nodeIndex));
if (fstIndex < 0)
return false;
if (m_entries[fstIndex].GetType() != FSTEntry::TYPE::DIRECTORY)
return false;
parentIndex = fstIndex;
curDirStart = fstIndex + 1;
curDirEnd = m_entries[fstIndex].dirInfo.endIndex;
}
// find the entry
sint32 fstIndex = findSubentry(curDirStart, curDirEnd, fscPath.GetNodeName(fscPath.GetNodeCount() - 1));
if (fstIndex < 0)
return false;
if (openOnlyFiles && m_entries[fstIndex].GetType() != FSTEntry::TYPE::FILE)
return false;
fileHandleOut.m_fstIndex = fstIndex;
return true;
}
bool FSTVolume::IsDirectory(const FSTFileHandle& fileHandle) const
{
cemu_assert_debug(fileHandle.m_fstIndex < m_entries.size());
return m_entries[fileHandle.m_fstIndex].GetType() == FSTEntry::TYPE::DIRECTORY;
};
bool FSTVolume::IsFile(const FSTFileHandle& fileHandle) const
{
cemu_assert_debug(fileHandle.m_fstIndex < m_entries.size());
return m_entries[fileHandle.m_fstIndex].GetType() == FSTEntry::TYPE::FILE;
};
bool FSTVolume::HasLinkFlag(const FSTFileHandle& fileHandle) const
{
cemu_assert_debug(fileHandle.m_fstIndex < m_entries.size());
return HAS_FLAG(m_entries[fileHandle.m_fstIndex].GetFlags(), FSTEntry::FLAGS::FLAG_LINK);
};
std::string_view FSTVolume::GetName(const FSTFileHandle& fileHandle) const
{
if (fileHandle.m_fstIndex > m_entries.size())
return "";
const char* entryName = m_nameStringTable.data() + m_entries[fileHandle.m_fstIndex].nameOffset;
return entryName;
}
std::string FSTVolume::GetPath(const FSTFileHandle& fileHandle) const
{
std::string path;
auto& entry = m_entries[fileHandle.m_fstIndex];
// get parent chain
boost::container::small_vector<uint32, 8> parentChain;
if (entry.HasNonRootNodeParent())
{
parentChain.emplace_back(entry.parentDirIndex);
auto* parentItr = &m_entries[entry.parentDirIndex];
while (parentItr->HasNonRootNodeParent())
{
cemu_assert_debug(parentItr->GetType() == FSTEntry::TYPE::DIRECTORY);
parentChain.emplace_back(parentItr->parentDirIndex);
parentItr = &m_entries[parentItr->parentDirIndex];
}
}
// build path
cemu_assert_debug(parentChain.size() <= 1); // test this case
for (auto& itr : parentChain | boost::adaptors::reversed)
{
const char* name = m_nameStringTable.data() + m_entries[itr].nameOffset;
path.append(name);
path.push_back('/');
}
// append node name
const char* name = m_nameStringTable.data() + entry.nameOffset;
path.append(name);
return path;
}
uint32 FSTVolume::GetFileSize(const FSTFileHandle& fileHandle) const
{
if (m_entries[fileHandle.m_fstIndex].GetType() != FSTEntry::TYPE::FILE)
return 0;
return m_entries[fileHandle.m_fstIndex].fileInfo.fileSize;
}
uint32 FSTVolume::ReadFile(FSTFileHandle& fileHandle, uint32 offset, uint32 size, void* dataOut)
{
FSTEntry& entry = m_entries[fileHandle.m_fstIndex];
if (entry.GetType() != FSTEntry::TYPE::FILE)
return 0;
cemu_assert_debug(!HAS_FLAG(entry.GetFlags(), FSTEntry::FLAGS::FLAG_LINK));
FSTCluster& cluster = m_cluster[entry.fileInfo.clusterIndex];
if (cluster.hashMode == ClusterHashMode::RAW || cluster.hashMode == ClusterHashMode::RAW_STREAM)
return ReadFile_HashModeRaw(entry.fileInfo.clusterIndex, entry, offset, size, dataOut);
else if (cluster.hashMode == ClusterHashMode::HASH_INTERLEAVED)
return ReadFile_HashModeHashed(entry.fileInfo.clusterIndex, entry, offset, size, dataOut);
cemu_assert_debug(false);
return 0;
}
constexpr size_t BLOCK_SIZE = 0x10000;
constexpr size_t BLOCK_HASH_SIZE = 0x0400;
constexpr size_t BLOCK_FILE_SIZE = 0xFC00;
struct FSTRawBlock
{
std::vector<uint8> rawData; // unhashed block size depends on sector size field in partition header
};
struct FSTHashedBlock
{
uint8 rawData[BLOCK_SIZE];
uint8* getHashData()
{
return rawData;
}
uint8* getH0Hash(uint32 index)
{
cemu_assert_debug(index < 16);
return getHashData() + 20 * index;
}
uint8* getH1Hash(uint32 index)
{
cemu_assert_debug(index < 16);
return getHashData() + (20 * 16) * 1 + 20 * index;
}
uint8* getH2Hash(uint32 index)
{
cemu_assert_debug(index < 16);
return getHashData() + (20 * 16) * 2 + 20 * index;
}
uint8* getFileData()
{
return rawData + BLOCK_HASH_SIZE;
}
uint8* getH0Hash(size_t index)
{
cemu_assert_debug(index < 16);
return rawData + index * 20;
}
};
static_assert(sizeof(FSTHashedBlock) == BLOCK_SIZE);
struct FSTCachedRawBlock
{
FSTRawBlock blockData;
uint8 ivForNextBlock[16];
uint64 lastAccess;
};
struct FSTCachedHashedBlock
{
FSTHashedBlock blockData;
uint64 lastAccess;
};
// Checks cache fill state and if necessary drops least recently accessed block from the cache. Optionally allows to recycle the released cache entry to cut down cost of memory allocation and clearing
void FSTVolume::TrimCacheIfRequired(FSTCachedRawBlock** droppedRawBlock, FSTCachedHashedBlock** droppedHashedBlock)
{
// calculate size used by cache
size_t cacheSize = 0;
for (auto& itr : m_cacheDecryptedRawBlocks)
cacheSize += itr.second->blockData.rawData.size();
for (auto& itr : m_cacheDecryptedHashedBlocks)
cacheSize += sizeof(FSTCachedHashedBlock) + sizeof(FSTHashedBlock);
// only trim if cache is full (larger than 2MB)
if (cacheSize < 2*1024*1024) // 2MB
return;
// scan both cache lists to find least recently accessed block to drop
auto dropRawItr = std::min_element(m_cacheDecryptedRawBlocks.begin(), m_cacheDecryptedRawBlocks.end(), [](const auto& a, const auto& b) -> bool
{ return a.second->lastAccess < b.second->lastAccess; });
auto dropHashedItr = std::min_element(m_cacheDecryptedHashedBlocks.begin(), m_cacheDecryptedHashedBlocks.end(), [](const auto& a, const auto& b) -> bool
{ return a.second->lastAccess < b.second->lastAccess; });
uint64 lastAccess = std::numeric_limits<uint64>::max();
if(dropRawItr != m_cacheDecryptedRawBlocks.end())
lastAccess = dropRawItr->second->lastAccess;
if(dropHashedItr != m_cacheDecryptedHashedBlocks.end())
lastAccess = std::min<uint64>(lastAccess, dropHashedItr->second->lastAccess);
if(dropRawItr != m_cacheDecryptedRawBlocks.end() && dropRawItr->second->lastAccess == lastAccess)
{
if (droppedRawBlock)
*droppedRawBlock = dropRawItr->second;
else
delete dropRawItr->second;
m_cacheDecryptedRawBlocks.erase(dropRawItr);
return;
}
else if(dropHashedItr != m_cacheDecryptedHashedBlocks.end() && dropHashedItr->second->lastAccess == lastAccess)
{
if (droppedHashedBlock)
*droppedHashedBlock = dropHashedItr->second;
else
delete dropHashedItr->second;
m_cacheDecryptedHashedBlocks.erase(dropHashedItr);
}
}
void FSTVolume::DetermineUnhashedBlockIV(uint32 clusterIndex, uint32 blockIndex, uint8 ivOut[16])
{
memset(ivOut, 0, sizeof(ivOut));
if(blockIndex == 0)
{
ivOut[0] = (uint8)(clusterIndex >> 8);
ivOut[1] = (uint8)(clusterIndex >> 0);
}
else
{
// the last 16 encrypted bytes of the previous block are the IV (AES CBC)
// if the previous block is cached we can grab the IV from there. Otherwise we have to read the 16 bytes from the data source
uint32 prevBlockIndex = blockIndex - 1;
uint64 cacheBlockId = ((uint64)clusterIndex << (64 - 16)) | (uint64)prevBlockIndex;
auto itr = m_cacheDecryptedRawBlocks.find(cacheBlockId);
if (itr != m_cacheDecryptedRawBlocks.end())
{
memcpy(ivOut, itr->second->ivForNextBlock, 16);
}
else
{
cemu_assert(m_sectorSize >= 16);
uint64 clusterOffset = (uint64)m_cluster[clusterIndex].offset * m_sectorSize;
uint8 prevIV[16];
if (m_dataSource->readData(clusterIndex, clusterOffset, blockIndex * m_sectorSize - 16, prevIV, 16) != 16)
{
cemuLog_log(LogType::Force, "Failed to read IV for raw FST block");
m_detectedCorruption = true;
return;
}
memcpy(ivOut, prevIV, 16);
}
}
}
FSTCachedRawBlock* FSTVolume::GetDecryptedRawBlock(uint32 clusterIndex, uint32 blockIndex)
{
FSTCluster& cluster = m_cluster[clusterIndex];
uint64 clusterOffset = (uint64)cluster.offset * m_sectorSize;
// generate id for cache
uint64 cacheBlockId = ((uint64)clusterIndex << (64 - 16)) | (uint64)blockIndex;
// lookup block in cache
FSTCachedRawBlock* block = nullptr;
auto itr = m_cacheDecryptedRawBlocks.find(cacheBlockId);
if (itr != m_cacheDecryptedRawBlocks.end())
{
block = itr->second;
block->lastAccess = ++m_cacheAccessCounter;
return block;
}
// if cache already full, drop least recently accessed block and recycle FSTCachedRawBlock object if possible
TrimCacheIfRequired(&block, nullptr);
if (!block)
block = new FSTCachedRawBlock();
block->blockData.rawData.resize(m_sectorSize);
// block not cached, read new
block->lastAccess = ++m_cacheAccessCounter;
if (m_dataSource->readData(clusterIndex, clusterOffset, blockIndex * m_sectorSize, block->blockData.rawData.data(), m_sectorSize) != m_sectorSize)
{
cemuLog_log(LogType::Force, "Failed to read raw FST block");
delete block;
m_detectedCorruption = true;
return nullptr;
}
// decrypt hash data
uint8 iv[16]{};
DetermineUnhashedBlockIV(clusterIndex, blockIndex, iv);
memcpy(block->ivForNextBlock, block->blockData.rawData.data() + m_sectorSize - 16, 16);
AES128_CBC_decrypt(block->blockData.rawData.data(), block->blockData.rawData.data(), m_sectorSize, m_partitionTitlekey.b, iv);
// if this is the next block, then hash it
if(cluster.hasContentHash)
{
if(cluster.singleHashNumBlocksHashed == blockIndex)
{
cemu_assert_debug(!(cluster.contentSize % m_sectorSize)); // size should be multiple of sector size? Regardless, the hashing code below can handle non-aligned sizes
bool isLastBlock = blockIndex == (std::max<uint32>(cluster.contentSize / m_sectorSize, 1) - 1);
uint32 hashSize = m_sectorSize;
if(isLastBlock)
hashSize = cluster.contentSize - (uint64)blockIndex*m_sectorSize;
EVP_DigestUpdate(cluster.singleHashCtx.get(), block->blockData.rawData.data(), hashSize);
cluster.singleHashNumBlocksHashed++;
if(isLastBlock)
{
uint8 hash[32];
EVP_DigestFinal_ex(cluster.singleHashCtx.get(), hash, nullptr);
if(memcmp(hash, cluster.contentHash32, cluster.contentHashIsSHA1 ? 20 : 32) != 0)
{
cemuLog_log(LogType::Force, "FST: Raw section hash mismatch");
delete block;
m_detectedCorruption = true;
return nullptr;
}
}
}
}
// register in cache
m_cacheDecryptedRawBlocks.emplace(cacheBlockId, block);
return block;
}
FSTCachedHashedBlock* FSTVolume::GetDecryptedHashedBlock(uint32 clusterIndex, uint32 blockIndex)
{
const FSTCluster& cluster = m_cluster[clusterIndex];
uint64 clusterOffset = (uint64)cluster.offset * m_sectorSize;
// generate id for cache
uint64 cacheBlockId = ((uint64)clusterIndex << (64 - 16)) | (uint64)blockIndex;
// lookup block in cache
FSTCachedHashedBlock* block = nullptr;
auto itr = m_cacheDecryptedHashedBlocks.find(cacheBlockId);
if (itr != m_cacheDecryptedHashedBlocks.end())
{
block = itr->second;
block->lastAccess = ++m_cacheAccessCounter;
return block;
}
// if cache already full, drop least recently accessed block and recycle FSTCachedHashedBlock object if possible
TrimCacheIfRequired(nullptr, &block);
if (!block)
block = new FSTCachedHashedBlock();
// block not cached, read new
block->lastAccess = ++m_cacheAccessCounter;
if (m_dataSource->readData(clusterIndex, clusterOffset, blockIndex * BLOCK_SIZE, block->blockData.rawData, BLOCK_SIZE) != BLOCK_SIZE)
{
cemuLog_log(LogType::Force, "Failed to read hashed FST block");
delete block;
m_detectedCorruption = true;
return nullptr;
}
// decrypt hash data
uint8 iv[16]{};
AES128_CBC_decrypt(block->blockData.getHashData(), block->blockData.getHashData(), BLOCK_HASH_SIZE, m_partitionTitlekey.b, iv);
// decrypt file data
AES128_CBC_decrypt(block->blockData.getFileData(), block->blockData.getFileData(), BLOCK_FILE_SIZE, m_partitionTitlekey.b, block->blockData.getH0Hash(blockIndex%16));
// compare with H0 to verify data integrity
NCrypto::CHash160 h0;
SHA1(block->blockData.getFileData(), BLOCK_FILE_SIZE, h0.b);
uint32 h0Index = (blockIndex % 4096);
if (memcmp(h0.b, block->blockData.getH0Hash(h0Index & 0xF), sizeof(h0.b)) != 0)
{
cemuLog_log(LogType::Force, "FST: Hash H0 mismatch in hashed block (section {} index {})", clusterIndex, blockIndex);
delete block;
m_detectedCorruption = true;
return nullptr;
}
// register in cache
m_cacheDecryptedHashedBlocks.emplace(cacheBlockId, block);
return block;
}
uint32 FSTVolume::ReadFile_HashModeRaw(uint32 clusterIndex, FSTEntry& entry, uint32 readOffset, uint32 readSize, void* dataOut)
{
uint8* dataOutU8 = (uint8*)dataOut;
if (readOffset >= entry.fileInfo.fileSize)
return 0;
else if ((readOffset + readSize) >= entry.fileInfo.fileSize)
readSize = (entry.fileInfo.fileSize - readOffset);
uint64 absFileOffset = entry.fileInfo.fileOffset * m_offsetFactor + readOffset;
uint32 remainingReadSize = readSize;
while (remainingReadSize > 0)
{
const FSTCachedRawBlock* rawBlock = this->GetDecryptedRawBlock(clusterIndex, absFileOffset/m_sectorSize);
if (!rawBlock)
break;
uint32 blockOffset = (uint32)(absFileOffset % m_sectorSize);
uint32 bytesToRead = std::min<uint32>(remainingReadSize, m_sectorSize - blockOffset);
std::memcpy(dataOutU8, rawBlock->blockData.rawData.data() + blockOffset, bytesToRead);
dataOutU8 += bytesToRead;
remainingReadSize -= bytesToRead;
absFileOffset += bytesToRead;
}
return readSize - remainingReadSize;
}
uint32 FSTVolume::ReadFile_HashModeHashed(uint32 clusterIndex, FSTEntry& entry, uint32 readOffset, uint32 readSize, void* dataOut)
{
/*
Data is divided into 0x10000 (64KiB) blocks
Layout:
+0x0000 Hash20[16] H0 hashes
+0x0140 Hash20[16] H1 hashes
+0x0240 Hash20[16] H2 hashes
+0x03C0 uint8[64] padding
+0x0400 uint8[0xFC00] fileData
The hash part (0-0x3FF) uses AES-CBC with IV initialized to zero
The file part (0x400 - 0xFFFF) uses AES-CBC with IV initialized to block->h0Hash[blockIndex % 16]
The hash data itself is calculated over 4096 blocks. Where each individual H0 entry hashes a single 0xFC00 file data block (unencrypted)
Each H1 hash is calculated from 16 H0 hashes
Each H2 hash is calculated from 16 H1 hashes.
The H3 hash is calculated from 16 H2 hashes.
Thus for each 4096 block group we end up with:
4096 H0 hashes
256 H1 hashes
16 H2 hashes
1 H3 hash
The embedded H0/H1 hashes per block are only a slice of the larger array. Whereas H2 always get embedded as a whole, due to only having 16 hashes in total
There is also a H4 hash that covers all H3 hashes and is stored in the TMD
*/
const FSTCluster& cluster = m_cluster[clusterIndex];
uint64 fileReadOffset = entry.fileInfo.fileOffset * m_offsetFactor + readOffset;
uint32 blockIndex = (uint32)(fileReadOffset / BLOCK_FILE_SIZE);
uint32 bytesRemaining = readSize;
uint32 offsetWithinBlock = (uint32)(fileReadOffset % BLOCK_FILE_SIZE);
while (bytesRemaining > 0)
{
FSTCachedHashedBlock* block = GetDecryptedHashedBlock(clusterIndex, blockIndex);
if (!block)
return 0;
uint32 bytesToRead = std::min(bytesRemaining, (uint32)BLOCK_FILE_SIZE - offsetWithinBlock);
std::memcpy(dataOut, block->blockData.getFileData() + offsetWithinBlock, bytesToRead);
dataOut = (uint8*)dataOut + bytesToRead;
bytesRemaining -= bytesToRead;
blockIndex++;
offsetWithinBlock = 0;
}
return readSize - bytesRemaining;
}
bool FSTVolume::OpenDirectoryIterator(std::string_view path, FSTDirectoryIterator& directoryIteratorOut)
{
FSTFileHandle fileHandle;
if (!OpenFile(path, fileHandle, false))
return false;
if (!IsDirectory(fileHandle))
return false;
auto const& fstEntry = m_entries[fileHandle.m_fstIndex];
directoryIteratorOut.dirHandle = fileHandle;
directoryIteratorOut.startIndex = fileHandle.m_fstIndex + 1;
directoryIteratorOut.endIndex = fstEntry.dirInfo.endIndex;
directoryIteratorOut.currentIndex = directoryIteratorOut.startIndex;
return true;
}
bool FSTVolume::Next(FSTDirectoryIterator& directoryIterator, FSTFileHandle& fileHandleOut)
{
if (directoryIterator.currentIndex >= directoryIterator.endIndex)
return false;
auto const& fstEntry = m_entries[directoryIterator.currentIndex];
fileHandleOut.m_fstIndex = directoryIterator.currentIndex;
if (fstEntry.GetType() == FSTEntry::TYPE::DIRECTORY)
{
cemu_assert_debug(fstEntry.dirInfo.endIndex > directoryIterator.currentIndex);
directoryIterator.currentIndex = fstEntry.dirInfo.endIndex;
}
else
directoryIterator.currentIndex++;
return true;
}
FSTVolume::~FSTVolume()
{
for (auto& itr : m_cacheDecryptedRawBlocks)
delete itr.second;
for (auto& itr : m_cacheDecryptedHashedBlocks)
delete itr.second;
if (m_sourceIsOwned)
delete m_dataSource;
}
bool FSTVerifier::VerifyContentFile(FileStream* fileContent, const NCrypto::AesKey* key, uint32 contentIndex, uint32 contentSize, uint32 contentSizePadded, bool isSHA1, const uint8* tmdContentHash)
{
cemu_assert_debug(isSHA1); // test this case
cemu_assert_debug(((contentSize+0xF)&~0xF) == contentSizePadded);
std::vector<uint8> buffer;
buffer.resize(64 * 1024);
if ((uint32)fileContent->GetSize() != contentSizePadded)
return false;
fileContent->SetPosition(0);
uint8 iv[16]{};
iv[0] = (contentIndex >> 8) & 0xFF;
iv[1] = (contentIndex >> 0) & 0xFF;
// raw content
uint64 remainingBytes = contentSize;
uint8 calculatedHash[SHA256_DIGEST_LENGTH];
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
EVP_DigestInit(ctx, isSHA1 ? EVP_sha1() : EVP_sha256());
while (remainingBytes > 0)
{
uint32 bytesToRead = (uint32)std::min(remainingBytes, (uint64)buffer.size());
uint32 bytesToReadPadded = ((bytesToRead + 0xF) & ~0xF);
uint32 bytesRead = fileContent->readData(buffer.data(), bytesToReadPadded);
if (bytesRead != bytesToReadPadded)
return false;
AES128_CBC_decrypt_updateIV(buffer.data(), buffer.data(), bytesToReadPadded, key->b, iv);
EVP_DigestUpdate(ctx, buffer.data(), bytesToRead);
remainingBytes -= bytesToRead;
}
unsigned int md_len;
EVP_DigestFinal_ex(ctx, calculatedHash, &md_len);
EVP_MD_CTX_free(ctx);
return memcmp(calculatedHash, tmdContentHash, md_len) == 0;
}
bool FSTVerifier::VerifyHashedContentFile(FileStream* fileContent, const NCrypto::AesKey* key, uint32 contentIndex, uint32 contentSize, uint32 contentSizePadded, bool isSHA1, const uint8* tmdContentHash)
{
if (!isSHA1)
return false; // not supported
if ((contentSize % sizeof(FSTHashedBlock)) != 0)
return false;
if ((uint32)fileContent->GetSize() != contentSize)
return false;
fileContent->SetPosition(0);
std::vector<NCrypto::CHash160> h0List(4096);
FSTHashedBlock block;
uint32 numBlocks = contentSize / sizeof(FSTHashedBlock);
for (uint32 blockIndex = 0; blockIndex < numBlocks; blockIndex++)
{
if (fileContent->readData(&block, sizeof(FSTHashedBlock)) != sizeof(FSTHashedBlock))
return false;
uint32 h0Index = (blockIndex % 4096);
// decrypt hash data and file data
uint8 iv[16]{};
AES128_CBC_decrypt(block.getHashData(), block.getHashData(), BLOCK_HASH_SIZE, key->b, iv);
AES128_CBC_decrypt(block.getFileData(), block.getFileData(), BLOCK_FILE_SIZE, key->b, block.getH0Hash(blockIndex % 16));
// generate H0 hash and compare
NCrypto::CHash160 h0;
SHA1(block.getFileData(), BLOCK_FILE_SIZE, h0.b);
if (memcmp(h0.b, block.getH0Hash(h0Index & 0xF), sizeof(h0.b)) != 0)
return false;
std::memcpy(h0List[h0Index].b, h0.b, sizeof(h0.b));
// Sixteen H0 hashes become one H1 hash
if (((h0Index + 1) % 16) == 0 && h0Index > 0)
{
uint32 h1Index = ((h0Index - 15) / 16);
NCrypto::CHash160 h1;
SHA1((unsigned char *) (h0List.data() + h1Index * 16), sizeof(NCrypto::CHash160) * 16, h1.b);
if (memcmp(h1.b, block.getH1Hash(h1Index&0xF), sizeof(h1.b)) != 0)
return false;
}
// todo - repeat same for H1 and H2
// At the end all H3 hashes are hashed into a single H4 hash which is then compared with the content hash from the TMD
// Checking only H0 and H1 is sufficient enough for verifying if the file data is intact
// but if we wanted to be strict and only allow correctly signed data we would have to hash all the way up to H4
}
return true;
}
void FSTVolumeTest()
{
FSTPathUnitTest();
}
| 45,684
|
C++
|
.cpp
| 1,170
| 36.524786
| 224
| 0.750878
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,027
|
KeyCache.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/FST/KeyCache.cpp
|
#include <wx/msgdlg.h>
#include <mutex>
#include <gui/helpers/wxHelpers.h>
#include "config/ActiveSettings.h"
#include "util/crypto/aes128.h"
#include "Common/FileStream.h"
#include "util/helpers/StringHelpers.h"
std::mutex mtxKeyCache;
struct KeyCacheEntry
{
uint8 aes128key[16];
};
std::vector<KeyCacheEntry> g_keyCache;
bool strishex(std::string_view str)
{
for(size_t i=0; i<str.size(); i++)
{
char c = str[i];
if( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
continue;
return false;
}
return true;
}
/*
* Returns AES-128 key from the key cache
* nullptr is returned if index >= max_keys
*/
uint8* KeyCache_GetAES128(sint32 index)
{
if( index < 0 || index >= (sint32)g_keyCache.size())
return nullptr;
KeyCacheEntry* keyCacheEntry = &g_keyCache[index];
return keyCacheEntry->aes128key;
}
void KeyCache_AddKey128(uint8* key)
{
KeyCacheEntry newEntry = {0};
memcpy(newEntry.aes128key, key, 16);
g_keyCache.emplace_back(newEntry);
}
bool sKeyCachePrepared = false;
void KeyCache_Prepare()
{
mtxKeyCache.lock();
if (sKeyCachePrepared)
{
mtxKeyCache.unlock();
return;
}
sKeyCachePrepared = true;
g_keyCache.clear();
// load keys
auto keysPath = ActiveSettings::GetUserDataPath("keys.txt");
FileStream* fs_keys = FileStream::openFile2(keysPath);
if( !fs_keys )
{
fs_keys = FileStream::createFile2(keysPath);
if(fs_keys)
{
fs_keys->writeString("# this file contains keys needed for decryption of disc file system data (WUD/WUX)\r\n");
fs_keys->writeString("# 1 key per line, any text after a '#' character is considered a comment\r\n");
fs_keys->writeString("# the emulator will automatically pick the right key\r\n");
fs_keys->writeString("541b9889519b27d363cd21604b97c67a # example key (can be deleted)\r\n");
delete fs_keys;
}
else
{
wxMessageBox(_("Unable to create file keys.txt\nThis can happen if Cemu does not have write permission to its own directory, the disk is full or if anti-virus software is blocking Cemu."), _("Error"), wxOK | wxCENTRE | wxICON_ERROR);
}
mtxKeyCache.unlock();
return;
}
sint32 lineNumber = 0;
std::string line;
while( fs_keys->readLine(line) )
{
lineNumber++;
// truncate anything after '#' or ';'
for(size_t i=0; i<line.size(); i++)
{
if(line[i] == '#' || line[i] == ';' )
{
line.resize(i);
break;
}
}
// remove whitespaces and other common formatting characters
auto itr = line.begin();
while (itr != line.end())
{
char c = *itr;
if (c == ' ' || c == '\t' || c == '-' || c == '_')
itr = line.erase(itr);
else
itr++;
}
if (line.empty())
continue;
if( strishex(line) == false )
{
auto errorMsg = formatWxString(_("Error in keys.txt at line {}"), lineNumber);
wxMessageBox(errorMsg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR);
continue;
}
if(line.size() == 32 )
{
// 128-bit key
uint8 keyData128[16];
StringHelpers::ParseHexString(line, keyData128, 16);
KeyCache_AddKey128(keyData128);
}
else
{
// invalid key length
}
}
delete fs_keys;
mtxKeyCache.unlock();
}
| 3,118
|
C++
|
.cpp
| 120
| 23.375
| 236
| 0.673913
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,028
|
WUHBReader.cpp
|
cemu-project_Cemu/src/Cafe/Filesystem/WUHB/WUHBReader.cpp
|
#include "WUHBReader.h"
WUHBReader* WUHBReader::FromPath(const fs::path& path)
{
FileStream* fileIn{FileStream::openFile2(path)};
if (!fileIn)
return nullptr;
WUHBReader* ret = new WUHBReader(fileIn);
if (!ret->CheckMagicValue())
{
delete ret;
return nullptr;
}
if (!ret->ReadHeader())
{
delete ret;
return nullptr;
}
return ret;
}
static const romfs_direntry_t fallbackDirEntry{
.parent = ROMFS_ENTRY_EMPTY,
.listNext = ROMFS_ENTRY_EMPTY,
.dirListHead = ROMFS_ENTRY_EMPTY,
.fileListHead = ROMFS_ENTRY_EMPTY,
.hash = ROMFS_ENTRY_EMPTY,
.name_size = 0,
.name = ""
};
static const romfs_fentry_t fallbackFileEntry{
.parent = ROMFS_ENTRY_EMPTY,
.listNext = ROMFS_ENTRY_EMPTY,
.offset = 0,
.size = 0,
.hash = ROMFS_ENTRY_EMPTY,
.name_size = 0,
.name = ""
};
template<bool File>
const WUHBReader::EntryType<File>& WUHBReader::GetFallback()
{
if constexpr (File)
return fallbackFileEntry;
else
return fallbackDirEntry;
}
template<bool File>
WUHBReader::EntryType<File> WUHBReader::GetEntry(uint32 offset) const
{
auto fallback = GetFallback<File>();
if(offset == ROMFS_ENTRY_EMPTY)
return fallback;
const char* typeName = File ? "fentry" : "direntry";
EntryType<File> ret;
if (offset >= (File ? m_header.file_table_size : m_header.dir_table_size))
{
cemuLog_log(LogType::Force, "WUHB {} offset exceeds table size declared in header", typeName);
return fallback;
}
// read the entry
m_fileIn->SetPosition((File ? m_header.file_table_ofs : m_header.dir_table_ofs) + offset);
auto read = m_fileIn->readData(&ret, offsetof(EntryType<File>, name));
if (read != offsetof(EntryType<File>, name))
{
cemuLog_log(LogType::Force, "failed to read WUHB {} at offset: {}", typeName, offset);
return fallback;
}
// read the name
ret.name.resize(ret.name_size);
read = m_fileIn->readData(ret.name.data(), ret.name_size);
if (read != ret.name_size)
{
cemuLog_log(LogType::Force, "failed to read WUHB {} name", typeName);
return fallback;
}
return ret;
}
romfs_direntry_t WUHBReader::GetDirEntry(uint32 offset) const
{
return GetEntry<false>(offset);
}
romfs_fentry_t WUHBReader::GetFileEntry(uint32 offset) const
{
return GetEntry<true>(offset);
}
uint64 WUHBReader::GetFileSize(uint32 entryOffset) const
{
return GetFileEntry(entryOffset).size;
}
uint64 WUHBReader::ReadFromFile(uint32 entryOffset, uint64 fileOffset, uint64 length, void* buffer) const
{
const auto fileEntry = GetFileEntry(entryOffset);
if (fileOffset >= fileEntry.size)
return 0;
const uint64 readAmount = std::min(length, fileEntry.size - fileOffset);
const uint64 wuhbOffset = m_header.file_partition_ofs + fileEntry.offset + fileOffset;
m_fileIn->SetPosition(wuhbOffset);
return m_fileIn->readData(buffer, readAmount);
}
uint32 WUHBReader::GetHashTableEntryOffset(uint32 hash, bool isFile) const
{
const uint64 hash_table_size = (isFile ? m_header.file_hash_table_size : m_header.dir_hash_table_size);
const uint64 hash_table_ofs = (isFile ? m_header.file_hash_table_ofs : m_header.dir_hash_table_ofs);
const uint64 hash_table_entry_count = hash_table_size / sizeof(uint32);
const uint64 hash_table_entry_offset = hash_table_ofs + (hash % hash_table_entry_count) * sizeof(uint32);
m_fileIn->SetPosition(hash_table_entry_offset);
uint32 tableOffset;
if (!m_fileIn->readU32(tableOffset))
{
cemuLog_log(LogType::Force, "failed to read WUHB hash table entry at file offset: {}", hash_table_entry_offset);
return ROMFS_ENTRY_EMPTY;
}
return uint32be::from_bevalue(tableOffset);
}
template<bool T>
bool WUHBReader::SearchHashList(uint32& entryOffset, const fs::path& targetName) const
{
for (;;)
{
if (entryOffset == ROMFS_ENTRY_EMPTY)
return false;
auto entry = GetEntry<T>(entryOffset);
if (entry.name == targetName)
return true;
entryOffset = entry.hash;
}
return false;
}
uint32 WUHBReader::Lookup(const std::filesystem::path& path, bool isFile) const
{
uint32 currentEntryOffset = 0;
auto look = [&](const fs::path& part, bool lookInFileHT) {
const auto partString = part.string();
currentEntryOffset = GetHashTableEntryOffset(CalcPathHash(currentEntryOffset, partString.c_str(), 0, partString.size()), lookInFileHT);
if (lookInFileHT)
return SearchHashList<true>(currentEntryOffset, part);
else
return SearchHashList<false>(currentEntryOffset, part);
};
// look for the root entry
if (!look("", false))
return ROMFS_ENTRY_EMPTY;
auto it = path.begin();
while (it != path.end())
{
fs::path part = *it;
++it;
// no need to recurse after trailing forward slash (e.g. directory/)
if (part.empty() && !isFile)
break;
// skip leading forward slash
if (part == "/")
continue;
// if the lookup target is a file and this is the last iteration, look in the file hash table instead.
if (!look(part, it == path.end() && isFile))
return ROMFS_ENTRY_EMPTY;
}
return currentEntryOffset;
}
bool WUHBReader::CheckMagicValue() const
{
uint8 magic[4];
m_fileIn->SetPosition(0);
int read = m_fileIn->readData(magic, 4);
if (read != 4)
{
cemuLog_log(LogType::Force, "Failed to read WUHB magic numbers");
return false;
}
static_assert(sizeof(magic) == s_headerMagicValue.size());
return std::memcmp(&magic, s_headerMagicValue.data(), sizeof(magic)) == 0;
}
bool WUHBReader::ReadHeader()
{
m_fileIn->SetPosition(0);
auto read = m_fileIn->readData(&m_header, sizeof(m_header));
auto readSuccess = read == sizeof(m_header);
if (!readSuccess)
cemuLog_log(LogType::Force, "Failed to read WUHB header");
return readSuccess;
}
unsigned char WUHBReader::NormalizeChar(unsigned char c)
{
if (c >= 'a' && c <= 'z')
{
return c + 'A' - 'a';
}
else
{
return c;
}
}
uint32 WUHBReader::CalcPathHash(uint32 parent, const char* path, uint32 start, size_t path_len)
{
cemu_assert(path != nullptr || path_len == 0);
uint32 hash = parent ^ 123456789;
for (uint32 i = 0; i < path_len; i++)
{
hash = (hash >> 5) | (hash << 27);
hash ^= NormalizeChar(path[start + i]);
}
return hash;
}
| 6,020
|
C++
|
.cpp
| 202
| 27.668317
| 137
| 0.728433
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,030
|
elf.cpp
|
cemu-project_Cemu/src/Cafe/OS/RPL/elf.cpp
|
#include <zlib.h>
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "util/VirtualHeap/VirtualHeap.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
typedef struct
{
/* +0x00 */ uint32be magic;
/* +0x04 */ uint8 eiClass;
/* +0x05 */ uint8 eiData;
/* +0x06 */ uint8 eiVersion;
/* +0x07 */ uint8 eiOSABI;
/* +0x08 */ uint8 eiOSABIVersion;
/* +0x09 */ uint8 eiPadding[7];
/* +0x10 */ uint16be eType;
/* +0x12 */ uint16be eMachine;
/* +0x14 */ uint32be eVersion;
/* +0x18 */ uint32be entrypoint;
/* +0x1C */ uint32be phOffset;
/* +0x20 */ uint32be shOffset;
/* +0x24 */ uint32be eFlags;
/* +0x28 */ uint16be eHeaderSize;
/* +0x2A */ uint16be ePHEntrySize;
/* +0x2C */ uint16be ePHNum;
/* +0x2E */ uint16be eSHEntrySize;
/* +0x30 */ uint16be eSHNum;
/* +0x32 */ uint16be eShStrIndex;
}elfHeader_t;
static_assert(sizeof(elfHeader_t) == 0x34, "");
typedef struct
{
/* +0x00 */ uint32be nameOffset;
/* +0x04 */ uint32be shType;
/* +0x08 */ uint32be shFlags;
/* +0x0C */ uint32be shAddr;
/* +0x10 */ uint32be shOffset;
/* +0x14 */ uint32be shSize;
/* +0x18 */ uint32be shLink;
/* +0x1C */ uint32be shInfo;
/* +0x20 */ uint32be shAddrAlign;
/* +0x24 */ uint32be shEntSize;
}elfSectionEntry_t;
static_assert(sizeof(elfSectionEntry_t) == 0x28, "");
#define PF_X (1 << 0) /* Segment is executable */
#define PF_W (1 << 1) /* Segment is writable */
#define PF_R (1 << 2) /* Segment is readable */
// Map elf into memory
uint32 ELF_LoadFromMemory(uint8* elfData, sint32 size, const char* name)
{
elfHeader_t* header = (elfHeader_t*)elfData;
uint32 sectionCount = header->eSHNum;
uint32 sectionTableOffset = header->shOffset;
uint32 sectionTableEntrySize = header->eSHEntrySize;
elfSectionEntry_t* sectionTable = (elfSectionEntry_t*)(elfData + (uint32)header->shOffset);
memory_enableHBLELFCodeArea();
for (uint32 i = 0; i < sectionCount; i++)
{
debug_printf("%02d Addr %08x Size %08x Offs %08x Flags %08x Type %08x EntSize %08x\n", i, (uint32)sectionTable[i].shAddr, (uint32)sectionTable[i].shSize, (uint32)sectionTable[i].shOffset, (uint32)sectionTable[i].shFlags, (uint32)sectionTable[i].shType, (uint32)sectionTable[i].shEntSize);
uint32 shAddr = (uint32)sectionTable[i].shAddr;
uint32 shSize = (uint32)sectionTable[i].shSize;
uint32 shOffset = (uint32)sectionTable[i].shOffset;
uint32 shType = (uint32)sectionTable[i].shType;
uint32 shFlags = (uint32)sectionTable[i].shFlags;
if (shOffset > (uint32)size)
{
cemuLog_log(LogType::Force, "ELF section {} out of bounds", i);
continue;
}
uint32 copySize = std::min(shSize, size - shOffset);
// 0x00802000
if (shAddr != 0)
{
if (shType == SHT_NOBITS)
{
memset(memory_getPointerFromVirtualOffset(shAddr), 0, shSize);
}
else
{
memcpy(memory_getPointerFromVirtualOffset(shAddr), elfData + shOffset, copySize);
}
// SHT_NOBITS
}
if((shFlags & PF_X) > 0)
PPCRecompiler_allocateRange(shAddr, shSize);
}
return header->entrypoint;
}
// From Homebrew Launcher:
//#define MEM_BASE (0x00800000)
//#define ELF_DATA_ADDR (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x00))
//#define ELF_DATA_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x04))
//#define HBL_CHANNEL (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x08))
//#define RPX_MAX_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x0C))
//#define RPX_MAX_CODE_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x10))
//#define MAIN_ENTRY_ADDR (*(volatile unsigned int*)(MEM_BASE + 0x1400 + 0x00))
//#define OS_FIRMWARE (*(volatile unsigned int*)(MEM_BASE + 0x1400 + 0x04))
//
//#define OS_SPECIFICS ((OsSpecifics*)(MEM_BASE + 0x1500))
//
//#define MEM_AREA_TABLE ((s_mem_area*)(MEM_BASE + 0x1600))
//typedef struct _OsSpecifics
//{
// unsigned int addr_OSDynLoad_Acquire;
// unsigned int addr_OSDynLoad_FindExport;
// unsigned int addr_OSTitle_main_entry;
//
// unsigned int addr_KernSyscallTbl1;
// unsigned int addr_KernSyscallTbl2;
// unsigned int addr_KernSyscallTbl3;
// unsigned int addr_KernSyscallTbl4;
// unsigned int addr_KernSyscallTbl5;
//
// int(*LiWaitIopComplete)(int, int *);
// int(*LiWaitIopCompleteWithInterrupts)(int, int *);
// unsigned int addr_LiWaitOneChunk;
// unsigned int addr_PrepareTitle_hook;
// unsigned int addr_sgIsLoadingBuffer;
// unsigned int addr_gDynloadInitialized;
// unsigned int orig_LiWaitOneChunkInstr;
//} OsSpecifics;
| 4,610
|
C++
|
.cpp
| 121
| 36.066116
| 290
| 0.687528
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,031
|
rpl.cpp
|
cemu-project_Cemu/src/Cafe/OS/RPL/rpl.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/Filesystem/fsc.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_structs.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "util/VirtualHeap/VirtualHeap.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cafe/HW/Espresso/Debugger/Debugger.h"
#include "Cafe/GraphicPack/GraphicPack2.h"
#include "util/ChunkedHeap/ChunkedHeap.h"
#include <zlib.h>
#include "util/crypto/crc32.h"
#include "config/ActiveSettings.h"
#include "Cafe/OS/libs/coreinit/coreinit_DynLoad.h"
#include "gui/guiWrapper.h"
class PPCCodeHeap : public VHeap
{
public:
PPCCodeHeap(void* heapBase, uint32 heapSize) : VHeap(heapBase, heapSize) { };
void* alloc(uint32 size, uint32 alignment = 4) override
{
return VHeap::alloc(size, alignment);
}
void free(void* addr) override
{
uint32 allocSize = getAllocationSizeFromAddr(addr);
MPTR ppcAddr = memory_getVirtualOffsetFromPointer(addr);
PPCRecompiler_invalidateRange(ppcAddr, ppcAddr + allocSize);
VHeap::free(addr);
}
};
VHeap rplLoaderHeap_workarea(nullptr, MEMORY_RPLLOADER_AREA_SIZE);
PPCCodeHeap rplLoaderHeap_lowerAreaCodeMem2(nullptr, MEMORY_CODE_TRAMPOLINE_AREA_SIZE);
PPCCodeHeap rplLoaderHeap_codeArea2(nullptr, MEMORY_CODEAREA_SIZE);
ChunkedFlatAllocator<64 * 1024> g_heapTrampolineArea;
std::vector<RPLDependency*> rplDependencyList;
RPLModule* rplModuleList[256];
sint32 rplModuleCount = 0;
bool rplLoader_applicationHasMemoryControl = false;
uint32 rplLoader_maxCodeAddress = 0; // highest used code address
uint32 rplLoader_currentTLSModuleIndex = 1; // value 0 is reserved
uint32 rplLoader_currentHandleCounter = 0x00001000;
sint16 rplLoader_currentTlsModuleIndex = 0x0001;
RPLModule* rplLoader_mainModule = nullptr;
uint32 rplLoader_sdataAddr = MPTR_NULL; // r13
uint32 rplLoader_sdata2Addr = MPTR_NULL; // r2
uint32 rplLoader_currentDataAllocatorAddr = 0x10000000;
std::map<void(*)(PPCInterpreter_t* hCPU), uint32> g_map_callableExports;
struct RPLMappingRegion
{
MPTR baseAddress;
uint32 endAddress;
uint32 calcEndAddress; // used to verify endAddress
};
struct RPLRegionMappingTable
{
RPLMappingRegion region[4];
};
#define RPL_MAPPING_REGION_DATA 0
#define RPL_MAPPING_REGION_LOADERINFO 1
#define RPL_MAPPING_REGION_TEXT 2
#define RPL_MAPPING_REGION_TEMP 3
void RPLLoader_UnloadModule(RPLModule* rpl);
void RPLLoader_RemoveDependency(const char* name);
uint8* RPLLoader_AllocateTrampolineCodeSpace(RPLModule* rplLoaderContext, sint32 size)
{
if (rplLoaderContext)
{
// allocation owned by rpl
return (uint8*)rplLoaderContext->heapTrampolineArea.alloc(size, 4);
}
// allocation owned by global context
auto result = (uint8*)g_heapTrampolineArea.alloc(size, 4);
rplLoader_maxCodeAddress = std::max(rplLoader_maxCodeAddress, memory_getVirtualOffsetFromPointer(g_heapTrampolineArea.getCurrentBlockPtr()) + g_heapTrampolineArea.getCurrentBlockOffset());
return result;
}
uint8* RPLLoader_AllocateTrampolineCodeSpace(sint32 size)
{
return RPLLoader_AllocateTrampolineCodeSpace(nullptr, size);
}
MPTR RPLLoader_AllocateCodeSpace(uint32 size, uint32 alignment)
{
cemu_assert_debug((alignment & (alignment - 1)) == 0); // alignment must be a power of 2
MPTR codeAddr = memory_getVirtualOffsetFromPointer(rplLoaderHeap_codeArea2.alloc(size, alignment));
rplLoader_maxCodeAddress = std::max(rplLoader_maxCodeAddress, codeAddr + size);
PPCRecompiler_allocateRange(codeAddr, size);
return codeAddr;
}
uint32 RPLLoader_AllocateDataSpace(RPLModule* rpl, uint32 size, uint32 alignment)
{
if (rplLoader_applicationHasMemoryControl)
{
StackAllocator<uint32be> memPtr;
*(memPtr.GetPointer()) = 0;
PPCCoreCallback(rpl->funcAlloc.value(), size, alignment, memPtr.GetPointer());
return (uint32)*(memPtr.GetPointer());
}
rplLoader_currentDataAllocatorAddr = (rplLoader_currentDataAllocatorAddr + alignment - 1) & ~(alignment - 1);
uint32 mem = rplLoader_currentDataAllocatorAddr;
rplLoader_currentDataAllocatorAddr += size;
return mem;
}
void RPLLoader_FreeData(RPLModule* rpl, void* ptr)
{
PPCCoreCallback(rpl->funcFree.value(), ptr);
}
uint32 RPLLoader_GetDataAllocatorAddr()
{
return (rplLoader_currentDataAllocatorAddr + 0xFFF) & (~0xFFF);
}
uint32 RPLLoader_GetMaxCodeOffset()
{
return rplLoader_maxCodeAddress;
}
#define PPCASM_OPC_R_TEMPL_SIMM(_rD, _rA, _IMM) (((_rD)<<21)|((_rA)<<16)|((_IMM)&0xFFFF))
// generates 32-bit jump. Modifies R11 and CTR
MPTR _generateTrampolineFarJump(RPLModule* rplLoaderContext, MPTR destAddr)
{
auto itr = rplLoaderContext->trampolineMap.find(destAddr);
if (itr != rplLoaderContext->trampolineMap.end())
return itr->second;
MPTR trampolineAddr = memory_getVirtualOffsetFromPointer(RPLLoader_AllocateTrampolineCodeSpace(rplLoaderContext, 4*4));
uint32 destAddrU32 = (uint32)destAddr;
uint32 ppcOpcode = 0;
// ADDI R11, R0, ...
ppcOpcode = PPCASM_OPC_R_TEMPL_SIMM(11, 0, destAddrU32 & 0xFFFF);
ppcOpcode |= (14 << 26);
memory_writeU32(trampolineAddr + 0x0, ppcOpcode);
// ADDIS R11, R11, ...<<16
ppcOpcode = PPCASM_OPC_R_TEMPL_SIMM(11, 11, ((destAddrU32 >> 16) + ((destAddrU32 >> 15) & 1)) & 0xFFFF);
ppcOpcode |= (15 << 26);
memory_writeU32(trampolineAddr + 0x4, ppcOpcode);
// MTCTR r11
memory_writeU32(trampolineAddr + 0x8, 0x7D6903A6);
// BCTR
memory_writeU32(trampolineAddr + 0xC, 0x4E800420);
// if the destination is a known symbol, create a proxy (duplicate) symbol at the jump
rplSymbolStorage_createJumpProxySymbol(trampolineAddr, destAddr);
rplLoaderContext->trampolineMap.emplace(destAddr, trampolineAddr);
return trampolineAddr;
}
void* RPLLoader_AllocWorkarea(uint32 size, uint32 alignment, uint32* allocSize)
{
size = (size + 31)&~31;
*allocSize = size;
void* allocAddr = rplLoaderHeap_workarea.alloc(size, alignment);
cemu_assert(allocAddr != nullptr);
memset(allocAddr, 0, size);
return allocAddr;
}
void RPLLoader_FreeWorkarea(void* allocAddr)
{
rplLoaderHeap_workarea.free(allocAddr);
}
bool RPLLoader_CheckBounds(RPLModule* rplLoaderContext, uint32 offset, uint32 size)
{
if ((offset + size) > rplLoaderContext->RPLRawData.size_bytes())
return false;
return true;
}
bool RPLLoader_ProcessHeaders(std::string_view moduleName, uint8* rplData, uint32 rplSize, RPLModule** rplLoaderContextOut)
{
rplHeaderNew_t* rplHeader = (rplHeaderNew_t*)rplData;
*rplLoaderContextOut = nullptr;
if (rplHeader->version04 != 0x01)
return false;
if (rplHeader->ukn05 != 0x02)
return false;
if (rplHeader->magic2_0 != 0xCA)
return false;
if (rplHeader->magic2_1 != 0xFE)
return false;
if (rplHeader->ukn06 > 1)
return false;
if (rplHeader->ukn12 != 0x14)
return false;
if (rplHeader->ukn14 != 0x01)
return false;
if (rplHeader->sectionTableEntryCount < 2)
return false; // RPL must end with two sections: CRCS + FILEINFO
// setup RPL info struct
RPLModule* rplLoaderContext = new RPLModule();
rplLoaderContext->RPLRawData = std::span<uint8>(rplData, rplSize);
rplLoaderContext->heapTrampolineArea.setBaseAllocator(&rplLoaderHeap_lowerAreaCodeMem2);
// load section table
if ((uint32)rplHeader->sectionTableEntrySize != sizeof(rplSectionEntryNew_t))
assert_dbg();
sint32 sectionCount = (sint32)rplHeader->sectionTableEntryCount;
sint32 sectionTableSize = (sint32)rplHeader->sectionTableEntrySize * sectionCount;
rplLoaderContext->sectionTablePtr = (rplSectionEntryNew_t*)malloc(sectionTableSize);
memcpy(rplLoaderContext->sectionTablePtr, rplData + (uint32)(rplHeader->sectionTableOffset), sectionTableSize);
// copy rpl header
memcpy(&rplLoaderContext->rplHeader, rplHeader, sizeof(rplHeaderNew_t));
// verify that section n-1 is FILEINFO
rplSectionEntryNew_t* fileinfoSection = rplLoaderContext->sectionTablePtr + ((uint32)rplLoaderContext->rplHeader.sectionTableEntryCount - 1);
if (fileinfoSection->fileOffset == 0 || (uint32)fileinfoSection->fileOffset >= rplSize || (uint32)fileinfoSection->type != SHT_RPL_FILEINFO)
{
cemuLog_logDebug(LogType::Force, "RPLLoader: Last section not FILEINFO");
}
// verify that section n-2 is CRCs
rplSectionEntryNew_t* crcSection = rplLoaderContext->sectionTablePtr + ((uint32)rplLoaderContext->rplHeader.sectionTableEntryCount - 2);
if (crcSection->fileOffset == 0 || (uint32)crcSection->fileOffset >= rplSize || (uint32)crcSection->type != SHT_RPL_CRCS)
{
cemuLog_logDebug(LogType::Force, "RPLLoader: The section before FILEINFO must be CRCs");
}
// load FILEINFO section
if (fileinfoSection->sectionSize < sizeof(RPLFileInfoData))
{
cemuLog_log(LogType::Force, "RPLLoader: FILEINFO section size is below expected size");
delete rplLoaderContext;
return false;
}
// read RPL mapping info
uint8* fileInfoRawPtr = (uint8*)(rplData + fileinfoSection->fileOffset);
if (((uint64)fileinfoSection->fileOffset+fileinfoSection->sectionSize) > (uint64)rplSize)
{
cemuLog_log(LogType::Force, "RPLLoader: FILEINFO section outside of RPL file bounds");
return false;
}
rplLoaderContext->sectionData_fileInfo.resize(fileinfoSection->sectionSize);
memcpy(rplLoaderContext->sectionData_fileInfo.data(), fileInfoRawPtr, rplLoaderContext->sectionData_fileInfo.size());
RPLFileInfoData* fileInfoPtr = (RPLFileInfoData*)rplLoaderContext->sectionData_fileInfo.data();
if (fileInfoPtr->fileInfoMagic != 0xCAFE0402)
{
cemuLog_log(LogType::Force, "RPLLoader: Invalid FILEINFO magic");
return false;
}
// process FILEINFO
rplLoaderContext->fileInfo.textRegionSize = fileInfoPtr->textRegionSize;
rplLoaderContext->fileInfo.dataRegionSize = fileInfoPtr->dataRegionSize;
rplLoaderContext->fileInfo.baseAlign = fileInfoPtr->baseAlign;
rplLoaderContext->fileInfo.ukn14 = fileInfoPtr->ukn14;
rplLoaderContext->fileInfo.trampolineAdjustment = fileInfoPtr->trampolineAdjustment;
rplLoaderContext->fileInfo.ukn4C = fileInfoPtr->ukn4C;
rplLoaderContext->fileInfo.tlsModuleIndex = fileInfoPtr->tlsModuleIndex;
rplLoaderContext->fileInfo.sdataBase1 = fileInfoPtr->sdataBase1;
rplLoaderContext->fileInfo.sdataBase2 = fileInfoPtr->sdataBase2;
// init section address table
rplLoaderContext->sectionAddressTable2.resize(sectionCount);
// init modulename
rplLoaderContext->moduleName2.assign(moduleName);
// convert modulename to lower-case
for(auto& c : rplLoaderContext->moduleName2)
c = _ansiToLower(c);
// load CRC section
uint32 crcTableExpectedSize = sectionCount * sizeof(uint32be);
if (!RPLLoader_CheckBounds(rplLoaderContext, crcSection->fileOffset, crcTableExpectedSize))
{
cemuLog_log(LogType::Force, "RPLLoader: CRC section outside of RPL file bounds");
crcSection->sectionSize = 0;
}
else if (crcSection->sectionSize < crcTableExpectedSize)
{
cemuLog_log(LogType::Force, "RPLLoader: CRC section size (0x{:x}) less than required (0x{:x})", (uint32)crcSection->sectionSize, crcTableExpectedSize);
}
else if (crcSection->sectionSize != crcTableExpectedSize)
{
cemuLog_log(LogType::Force, "RPLLoader: CRC section size (0x{:x}) does not match expected size (0x{:x})", (uint32)crcSection->sectionSize, crcTableExpectedSize);
}
uint32 crcActualSectionCount = crcSection->sectionSize / sizeof(uint32); // how many CRCs are actually stored
rplLoaderContext->crcTable.resize(sectionCount);
if (crcActualSectionCount > 0)
{
uint32be* crcTableData = (uint32be*)(rplData + crcSection->fileOffset);
for (uint32 i = 0; i < crcActualSectionCount; i++)
rplLoaderContext->crcTable[i] = crcTableData[i];
}
// verify CRC of FILEINFO section
uint32 crcCalcFileinfo = crc32_calc(0, rplLoaderContext->sectionData_fileInfo.data(), rplLoaderContext->sectionData_fileInfo.size());
uint32 crcFileinfo = rplLoaderContext->GetSectionCRC(sectionCount - 1);
if (crcCalcFileinfo != crcFileinfo)
{
cemuLog_log(LogType::Force, "RPLLoader: FILEINFO section has CRC mismatch - Calculated: {:08x} Actual: {:08x}", crcCalcFileinfo, crcFileinfo);
}
rplLoaderContext->sectionAddressTable2[sectionCount - 1].ptr = rplLoaderContext->sectionData_fileInfo.data();
rplLoaderContext->sectionAddressTable2[sectionCount - 2].ptr = nullptr;// rplLoaderContext->crcTablePtr;
// set output
*rplLoaderContextOut = rplLoaderContext;
return true;
}
class RPLUncompressedSection
{
public:
std::vector<uint8> sectionData;
};
rplSectionEntryNew_t* RPLLoader_GetSection(RPLModule* rplLoaderContext, sint32 sectionIndex)
{
sint32 sectionCount = rplLoaderContext->rplHeader.sectionTableEntryCount;
if (sectionIndex < 0 || sectionIndex >= sectionCount)
{
cemuLog_log(LogType::Force, "RPLLoader: Section index out of bounds");
rplLoaderContext->hasError = true;
return nullptr;
}
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + sectionIndex;
return section;
}
RPLUncompressedSection* RPLLoader_LoadUncompressedSection(RPLModule* rplLoaderContext, sint32 sectionIndex)
{
const rplSectionEntryNew_t* section = RPLLoader_GetSection(rplLoaderContext, sectionIndex);
if (section == nullptr)
return nullptr;
RPLUncompressedSection* uSection = new RPLUncompressedSection();
if ((uint32)section->type == 0x8)
{
uSection->sectionData.resize(section->sectionSize);
std::fill(uSection->sectionData.begin(), uSection->sectionData.end(), 0);
return uSection;
}
// check if raw size does not exceed bounds of rpl
if (!RPLLoader_CheckBounds(rplLoaderContext, section->fileOffset, section->sectionSize))
{
// BSS
cemuLog_log(LogType::Force, "RPLLoader: Raw data for section {} exceeds bounds of RPL file", sectionIndex);
rplLoaderContext->hasError = true;
delete uSection;
return nullptr;
}
uint32 sectionFlags = section->flags;
if ((sectionFlags & SHF_RPL_COMPRESSED) != 0)
{
// decompress
if (!RPLLoader_CheckBounds(rplLoaderContext, section->fileOffset, sizeof(uint32be)) )
{
cemuLog_log(LogType::Force, "RPLLoader: Uncompressed data of section {} is too large", sectionIndex);
rplLoaderContext->hasError = true;
delete uSection;
return nullptr;
}
uint32 uncompressedSize = *(uint32be*)(rplLoaderContext->RPLRawData.data() + (uint32)section->fileOffset);
if (uncompressedSize >= 1*1024*1024*1024) // sections bigger than 1GB not allowed
{
cemuLog_log(LogType::Force, "RPLLoader: Uncompressed data of section {} is too large", sectionIndex);
rplLoaderContext->hasError = true;
delete uSection;
return nullptr;
}
int ret;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = inflateInit(&strm);
if (ret == Z_OK)
{
strm.avail_in = (uint32)section->sectionSize - 4;
strm.next_in = rplLoaderContext->RPLRawData.data() + (uint32)section->fileOffset + 4;
strm.avail_out = uncompressedSize;
uSection->sectionData.resize(uncompressedSize);
strm.next_out = uSection->sectionData.data();
ret = inflate(&strm, Z_FULL_FLUSH);
inflateEnd(&strm);
if ((ret != Z_OK && ret != Z_STREAM_END) || strm.avail_in != 0 || strm.avail_out != 0)
{
cemuLog_log(LogType::Force, "RPLLoader: Error while inflating data for section {}", sectionIndex);
rplLoaderContext->hasError = true;
delete uSection;
return nullptr;
}
}
}
else
{
// no decompression
uSection->sectionData.resize(section->sectionSize);
const uint8* sectionDataBegin = rplLoaderContext->RPLRawData.data() + (uint32)section->fileOffset;
std::copy(sectionDataBegin, sectionDataBegin + section->sectionSize, uSection->sectionData.data());
}
return uSection;
}
bool RPLLoader_LoadSingleSection(RPLModule* rplLoaderContext, sint32 sectionIndex, RPLMappingRegion* regionMappingInfo, MPTR mappedAddress)
{
rplSectionEntryNew_t* section = RPLLoader_GetSection(rplLoaderContext, sectionIndex);
if (section == nullptr)
return false;
uint32 mappingOffset = (uint32)section->virtualAddress - (uint32)regionMappingInfo->baseAddress;
if (mappingOffset >= 0x10000000)
cemuLog_logDebug(LogType::Force, "Suspicious section mapping offset: 0x{:08x}", mappingOffset);
uint32 sectionAddress = mappedAddress + mappingOffset;
rplLoaderContext->sectionAddressTable2[sectionIndex].ptr = memory_getPointerFromVirtualOffset(sectionAddress);
cemu_assert(rplLoaderContext->debugSectionLoadMask[sectionIndex] == false);
rplLoaderContext->debugSectionLoadMask[sectionIndex] = true;
// extract section
RPLUncompressedSection* uncompressedSection = RPLLoader_LoadUncompressedSection(rplLoaderContext, sectionIndex);
if (uncompressedSection == nullptr)
{
rplLoaderContext->hasError = true;
return false;
}
// copy to mapped address
if(section->virtualAddress < regionMappingInfo->baseAddress || (section->virtualAddress + uncompressedSection->sectionData.size()) > regionMappingInfo->endAddress)
cemuLog_log(LogType::Force, "RPLLoader: Section {} (0x{:08x} to 0x{:08x}) is not fully contained in it's bounding region (0x{:08x} to 0x{:08x})", sectionIndex, section->virtualAddress, section->virtualAddress + uncompressedSection->sectionData.size(), regionMappingInfo->baseAddress, regionMappingInfo->endAddress);
uint8* sectionAddressPtr = memory_getPointerFromVirtualOffset(sectionAddress);
std::copy(uncompressedSection->sectionData.begin(), uncompressedSection->sectionData.end(), sectionAddressPtr);
// update size in section (todo - use separate field)
if (uncompressedSection->sectionData.size() < section->sectionSize)
cemuLog_log(LogType::Force, "RPLLoader: Section {} uncompresses to {} bytes but sectionSize is {}", sectionIndex, uncompressedSection->sectionData.size(), (uint32)section->sectionSize);
section->sectionSize = uncompressedSection->sectionData.size();
delete uncompressedSection;
return true;
}
bool RPLLoader_LoadSections(sint32 aProcId, RPLModule* rplLoaderContext)
{
RPLRegionMappingTable regionMappingTable;
memset(®ionMappingTable, 0, sizeof(RPLRegionMappingTable));
regionMappingTable.region[0].baseAddress = 0xFFFFFFFF;
regionMappingTable.region[1].baseAddress = 0xFFFFFFFF;
regionMappingTable.region[2].baseAddress = 0xFFFFFFFF;
regionMappingTable.region[3].baseAddress = 0xFFFFFFFF;
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
uint32 sectionFlags = section->flags;
uint32 sectionVirtualAddr = section->virtualAddress;
uint32 sectionFileOffset = section->fileOffset;
uint32 sectionSize = section->sectionSize;
if(sectionSize == 0)
continue;
if (sectionType == SHT_RPL_CRCS)
continue;
if (sectionType == SHT_RPL_FILEINFO)
continue;
//if (sectionType == SHT_RPL_IMPORTS) -> The official loader seems to skip these, leading to incorrect boundary calculations
// continue;
if ((sectionFlags & 2) == 0)
{
uint32 endFileOffset = sectionFileOffset + sectionSize;
regionMappingTable.region[RPL_MAPPING_REGION_TEMP].baseAddress = std::min(regionMappingTable.region[RPL_MAPPING_REGION_TEMP].baseAddress, sectionFileOffset);
regionMappingTable.region[RPL_MAPPING_REGION_TEMP].endAddress = std::max(regionMappingTable.region[RPL_MAPPING_REGION_TEMP].endAddress, endFileOffset);
continue;
}
if ((sectionFlags & 4) != 0 && sectionType != SHT_RPL_EXPORTS && sectionType != SHT_RPL_IMPORTS)
{
regionMappingTable.region[RPL_MAPPING_REGION_TEXT].baseAddress = std::min(regionMappingTable.region[RPL_MAPPING_REGION_TEXT].baseAddress, sectionVirtualAddr);
continue;
}
if ((sectionFlags & 1) != 0)
{
regionMappingTable.region[RPL_MAPPING_REGION_DATA].baseAddress = std::min(regionMappingTable.region[RPL_MAPPING_REGION_DATA].baseAddress, sectionVirtualAddr);
continue;
}
else
{
regionMappingTable.region[RPL_MAPPING_REGION_LOADERINFO].baseAddress = std::min(regionMappingTable.region[RPL_MAPPING_REGION_LOADERINFO].baseAddress, sectionVirtualAddr);
continue;
}
}
for (sint32 i = 0; i < 4; i++)
{
if (regionMappingTable.region[i].baseAddress == 0xFFFFFFFF)
regionMappingTable.region[i].baseAddress = 0;
}
regionMappingTable.region[RPL_MAPPING_REGION_TEXT].endAddress = (regionMappingTable.region[RPL_MAPPING_REGION_TEXT].baseAddress + rplLoaderContext->fileInfo.textRegionSize) - rplLoaderContext->fileInfo.trampolineAdjustment;
regionMappingTable.region[RPL_MAPPING_REGION_DATA].endAddress = regionMappingTable.region[RPL_MAPPING_REGION_DATA].baseAddress + rplLoaderContext->fileInfo.dataRegionSize;
regionMappingTable.region[RPL_MAPPING_REGION_LOADERINFO].endAddress = (regionMappingTable.region[RPL_MAPPING_REGION_LOADERINFO].baseAddress + rplLoaderContext->fileInfo.ukn14) - rplLoaderContext->fileInfo.ukn4C;
// calculate region size
uint32 regionDataSize = regionMappingTable.region[RPL_MAPPING_REGION_DATA].endAddress - regionMappingTable.region[RPL_MAPPING_REGION_DATA].baseAddress;
uint32 regionLoaderinfoSize = regionMappingTable.region[RPL_MAPPING_REGION_LOADERINFO].endAddress - regionMappingTable.region[RPL_MAPPING_REGION_LOADERINFO].baseAddress;
uint32 regionTextSize = regionMappingTable.region[RPL_MAPPING_REGION_TEXT].endAddress - regionMappingTable.region[RPL_MAPPING_REGION_TEXT].baseAddress;
rplLoaderContext->regionMappingBase_data = RPLLoader_AllocateDataSpace(rplLoaderContext, regionDataSize, 0x1000);
rplLoaderContext->regionMappingBase_loaderInfo = RPLLoader_AllocateDataSpace(rplLoaderContext, regionLoaderinfoSize, 0x1000);
rplLoaderContext->regionMappingBase_text = rplLoaderHeap_codeArea2.alloc(regionTextSize + 0x1000, 0x1000);
rplLoader_maxCodeAddress = std::max(rplLoader_maxCodeAddress, rplLoaderContext->regionMappingBase_text.GetMPTR() + regionTextSize + 0x1000);
PPCRecompiler_allocateRange(rplLoaderContext->regionMappingBase_text.GetMPTR(), regionTextSize + 0x1000);
// workaround for DKC Tropical Freeze
if (boost::iequals(rplLoaderContext->moduleName2, "rs10_production"))
{
// allocate additional 12MB of unused data to get below a size of 0x3E200000 for the main ExpHeap
// otherwise the game will assume it's running on a Devkit unit with 2GB of RAM and subtract 1GB from available space
RPLLoader_AllocateDataSpace(rplLoaderContext, 12*1024*1024, 0x1000);
}
// set region sizes
rplLoaderContext->regionSize_data = regionDataSize;
rplLoaderContext->regionSize_loaderInfo = regionLoaderinfoSize;
rplLoaderContext->regionSize_text = regionTextSize;
// load data sections
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
uint32 sectionFlags = section->flags;
if (section->sectionSize == 0)
continue;
if( rplLoaderContext->sectionAddressTable2[i].ptr != nullptr )
continue;
if ((sectionFlags & 2) == 0)
continue;
if ((sectionFlags & 1) == 0)
continue;
RPLLoader_LoadSingleSection(rplLoaderContext, i, regionMappingTable.region + RPL_MAPPING_REGION_DATA, rplLoaderContext->regionMappingBase_data);
}
// load loaderinfo sections
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
uint32 sectionFlags = section->flags;
if (section->sectionSize == 0)
continue;
if (rplLoaderContext->sectionAddressTable2[i].ptr != nullptr)
continue;
if ((sectionFlags & 2) == 0)
continue;
if(sectionType != SHT_RPL_EXPORTS && sectionType != SHT_RPL_IMPORTS && (sectionFlags&5) != 0 )
continue;
bool readRaw = false;
RPLLoader_LoadSingleSection(rplLoaderContext, i, regionMappingTable.region + RPL_MAPPING_REGION_LOADERINFO, rplLoaderContext->regionMappingBase_loaderInfo);
if (sectionType == SHT_RPL_EXPORTS)
{
uint8* sectionAddress = (uint8*)rplLoaderContext->sectionAddressTable2[i].ptr;
if ((sectionFlags & 4) != 0)
{
rplLoaderContext->exportFCount = *(uint32be*)(sectionAddress + 0);
rplLoaderContext->exportFDataPtr = (rplExportTableEntry_t*)(sectionAddress + 8);
}
else
{
rplLoaderContext->exportDCount = *(uint32be*)(sectionAddress + 0);
rplLoaderContext->exportDDataPtr = (rplExportTableEntry_t*)(sectionAddress + 8);
}
}
}
// load text sections
uint32 textSectionMappedBase = rplLoaderContext->regionMappingBase_text.GetMPTR() + (uint32)rplLoaderContext->fileInfo.trampolineAdjustment; // leave some space for trampolines before the code section begins
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
uint32 sectionFlags = section->flags;
if( section->sectionSize == 0 )
continue;
if (rplLoaderContext->sectionAddressTable2[i].ptr != nullptr)
continue;
if ((sectionFlags & 2) == 0)
continue;
if ((sectionFlags & 4) == 0)
continue;
if( sectionType == SHT_RPL_EXPORTS)
continue;
if (section->type == 0x8)
{
cemuLog_log(LogType::Force, "RPLLoader: Unsupported text section type 0x8");
cemu_assert_debug(false);
}
RPLLoader_LoadSingleSection(rplLoaderContext, i, regionMappingTable.region + RPL_MAPPING_REGION_TEXT, textSectionMappedBase);
}
// load temp region sections
uint32 tempRegionSize = regionMappingTable.region[RPL_MAPPING_REGION_TEMP].endAddress - regionMappingTable.region[RPL_MAPPING_REGION_TEMP].baseAddress;
uint8* tempRegionPtr;
uint32 tempRegionAllocSize = 0;
tempRegionPtr = (uint8*)RPLLoader_AllocWorkarea(tempRegionSize, 0x20, &tempRegionAllocSize);
rplLoaderContext->tempRegionPtr = tempRegionPtr;
rplLoaderContext->tempRegionAllocSize = tempRegionAllocSize;
memcpy(tempRegionPtr, rplLoaderContext->RPLRawData.data()+regionMappingTable.region[RPL_MAPPING_REGION_TEMP].baseAddress, tempRegionSize);
// load temp region sections
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
uint32 sectionFlags = section->flags;
if (section->sectionSize == 0)
continue;
if (rplLoaderContext->sectionAddressTable2[i].ptr != nullptr)
continue;
if (sectionType == SHT_RPL_FILEINFO || sectionType == SHT_RPL_CRCS)
continue;
// calculate offset within temp section
uint32 sectionFileOffset = section->fileOffset;
uint32 sectionSize = section->sectionSize;
cemu_assert_debug(sectionFileOffset >= regionMappingTable.region[RPL_MAPPING_REGION_TEMP].baseAddress);
cemu_assert_debug((sectionFileOffset + sectionSize) <= regionMappingTable.region[RPL_MAPPING_REGION_TEMP].endAddress);
rplLoaderContext->sectionAddressTable2[i].ptr = (tempRegionPtr + (sectionFileOffset - regionMappingTable.region[RPL_MAPPING_REGION_TEMP].baseAddress));
uint32 sectionEndAddress = sectionFileOffset + sectionSize;
regionMappingTable.region[RPL_MAPPING_REGION_TEMP].calcEndAddress = std::max(regionMappingTable.region[RPL_MAPPING_REGION_TEMP].calcEndAddress, sectionEndAddress);
}
// todo: Verify calcEndAddress<=endAddress for each region
// dump loaded sections
/*
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
uint32 sectionFlags = section->flags;
if (section->sectionSize == 0)
continue;
if (rplLoaderContext->sectionAddressTable2[i].ptr == nullptr)
continue;
FileStream* fs = FileStream::createFile2(fmt::format("dump/rpl_sections/{}_{:08x}_type{:08x}.bin", i, (uint32)section->virtualAddress, (uint32)sectionType));
fs->writeData(rplLoaderContext->sectionAddressTable2[i].ptr, section->sectionSize);
delete fs;
}
*/
return true;
}
struct RPLFileSymtabEntry
{
/* +0x0 */ uint32be ukn00;
/* +0x4 */ uint32be symbolAddress;
/* +0x8 */ uint32be ukn08;
/* +0xC */ uint8 info;
/* +0xD */ uint8 ukn0D;
/* +0xE */ uint16be sectionIndex;
};
struct RPLSharedImportTracking
{
RPLModule* rplLoaderContext; // rpl loader context of module with exports
rplSectionEntryNew_t* exportSection; // export section
char modulename[RPL_MODULE_NAME_LENGTH];
};
static_assert(sizeof(RPLFileSymtabEntry) == 0x10, "rplSymtabEntry_t has invalid size");
typedef struct
{
uint64 hash1;
uint64 hash2;
uint32 address;
}mappedFunctionImport_t;
std::vector<mappedFunctionImport_t> list_mappedFunctionImports = std::vector<mappedFunctionImport_t>();
void _calculateMappedImportNameHash(const char* rplName, const char* funcName, uint64* h1Out, uint64* h2Out)
{
uint64 h1 = 0;
uint64 h2 = 0;
// rplName
while (*rplName)
{
uint64 v = (uint64)*rplName;
h1 += v;
h2 ^= v;
h1 = std::rotl<uint64>(h1, 3);
h2 = std::rotl<uint64>(h2, 7);
rplName++;
}
// funcName
while (*funcName)
{
uint64 v = (uint64)*funcName;
h1 += v;
h2 ^= v;
h1 = std::rotl<uint64>(h1, 3);
h2 = std::rotl<uint64>(h2, 7);
funcName++;
}
*h1Out = h1;
*h2Out = h2;
}
uint32 RPLLoader_MakePPCCallable(void(*ppcCallableExport)(PPCInterpreter_t* hCPU))
{
auto it = g_map_callableExports.find(ppcCallableExport);
if (it != g_map_callableExports.end())
return it->second;
// get HLE function index
sint32 functionIndex = PPCInterpreter_registerHLECall(ppcCallableExport, fmt::format("PPCCallback{:x}", (uintptr_t)ppcCallableExport));
MPTR codeAddr = memory_getVirtualOffsetFromPointer(RPLLoader_AllocateTrampolineCodeSpace(4));
uint32 opcode = (1 << 26) | functionIndex;
memory_write<uint32>(codeAddr, opcode);
g_map_callableExports[ppcCallableExport] = codeAddr;
return codeAddr;
}
uint32 rpl_mapHLEImport(RPLModule* rplLoaderContext, const char* rplName, const char* funcName, bool functionMustExist)
{
// calculate import name hash
uint64 mappedImportHash1;
uint64 mappedImportHash2;
_calculateMappedImportNameHash(rplName, funcName, &mappedImportHash1, &mappedImportHash2);
// find already mapped name
for (auto& importItr : list_mappedFunctionImports)
{
if (importItr.hash1 == mappedImportHash1 && importItr.hash2 == mappedImportHash2)
{
return importItr.address;
}
}
// copy lib file name and cut off .rpl from libName if present
char libName[512];
strcpy_s(libName, rplName);
for (sint32 i = 0; i < sizeof(libName); i++)
{
if (libName[i] == '\0')
break;
if (libName[i] == '.')
{
libName[i] = '\0';
break;
}
}
// find import in list of known exports
sint32 functionIndex = osLib_getFunctionIndex(libName, funcName);
if (functionIndex >= 0)
{
MPTR codeAddr = memory_getVirtualOffsetFromPointer(RPLLoader_AllocateTrampolineCodeSpace(4));
uint32 opcode = (1 << 26) | functionIndex;
memory_write<uint32>(codeAddr, opcode);
// register mapped import
mappedFunctionImport_t newImport;
newImport.hash1 = mappedImportHash1;
newImport.hash2 = mappedImportHash2;
newImport.address = codeAddr;
list_mappedFunctionImports.push_back(newImport);
// remember in symbol storage for debugger
rplSymbolStorage_store(libName, funcName, codeAddr);
return codeAddr;
}
else
{
if (functionMustExist == false)
return MPTR_NULL;
}
// create code for unsupported import
uint32 codeStart = memory_getVirtualOffsetFromPointer(RPLLoader_AllocateTrampolineCodeSpace(256));
uint32 currentAddress = codeStart;
uint32 opcode = (1 << 26) | (0xFFD0); // opcode for HLE: Unsupported import
memory_write<uint32>(codeStart + 0, opcode);
memory_write<uint32>(codeStart + 4, 0x4E800020);
currentAddress += 8;
// write name of lib/function
sint32 libNameLength = std::min(128, (sint32)strlen(libName));
sint32 funcNameLength = std::min(128, (sint32)strlen(funcName));
memcpy(memory_getPointerFromVirtualOffset(currentAddress), libName, libNameLength);
currentAddress += libNameLength;
memory_writeU8(currentAddress, '.');
currentAddress++;
memcpy(memory_getPointerFromVirtualOffset(currentAddress), funcName, funcNameLength);
currentAddress += funcNameLength;
memory_writeU8(currentAddress, '\0');
currentAddress++;
// align address to 4 byte boundary
currentAddress = (currentAddress + 3)&~3;
// register mapped import
mappedFunctionImport_t newImport;
newImport.hash1 = mappedImportHash1;
newImport.hash2 = mappedImportHash2;
newImport.address = codeStart;
list_mappedFunctionImports.push_back(newImport);
// remember in symbol storage for debugger
rplSymbolStorage_store(libName, funcName, codeStart);
// return address of code start
return codeStart;
}
MPTR RPLLoader_FindRPLExport(RPLModule* rplLoaderContext, const char* symbolName, bool isData)
{
if (isData)
{
cemu_assert_debug(false);
// todo - look in DDataPtr
}
if (rplLoaderContext->exportFDataPtr)
{
char* exportNameData = (char*)((uint8*)rplLoaderContext->exportFDataPtr - 8);
for (uint32 f = 0; f < rplLoaderContext->exportFCount; f++)
{
char* name = exportNameData + (uint32)rplLoaderContext->exportFDataPtr[f].nameOffset;
if (strcmp(name, symbolName) == 0)
{
return (uint32)rplLoaderContext->exportFDataPtr[f].virtualOffset;
}
}
}
return MPTR_NULL;
}
MPTR _findHLEExport(RPLModule* rplLoaderContext, RPLSharedImportTracking* sharedImportTrackingEntry, char* libname, char* symbolName, bool isData)
{
if (isData)
{
// data export
MPTR weakExportAddr = osLib_getPointer(libname, symbolName);
if (weakExportAddr != 0xFFFFFFFF)
return weakExportAddr;
cemuLog_logDebug(LogType::Force, "Unsupported data export ({}): {}.{}", rplLoaderContext->moduleName2, libname, symbolName);
return MPTR_NULL;
}
else
{
// try to find HLE/placeholder export
MPTR mappedFunctionAddr = rpl_mapHLEImport(rplLoaderContext, libname, symbolName, true);
if (mappedFunctionAddr == MPTR_NULL)
cemu_assert_debug(false);
return mappedFunctionAddr;
}
}
uint32 RPLLoader_FindModuleExport(RPLModule* rplLoaderContext, bool isData, const char* exportName)
{
if (isData == false)
{
// find function export
char* exportNameData = (char*)((uint8*)rplLoaderContext->exportFDataPtr - 8);
for (uint32 f = 0; f < rplLoaderContext->exportFCount; f++)
{
char* name = exportNameData + (uint32)rplLoaderContext->exportFDataPtr[f].nameOffset;
if (strcmp(name, exportName) == 0)
{
uint32 exportAddress = rplLoaderContext->exportFDataPtr[f].virtualOffset;
return exportAddress;
}
}
}
else
{
// find data export
char* exportNameData = (char*)((uint8*)rplLoaderContext->exportDDataPtr - 8);
for (uint32 f = 0; f < rplLoaderContext->exportDCount; f++)
{
char* name = exportNameData + (uint32)rplLoaderContext->exportDDataPtr[f].nameOffset;
if (strcmp(name, exportName) == 0)
{
uint32 exportAddress = rplLoaderContext->exportDDataPtr[f].virtualOffset;
return exportAddress;
}
}
}
return 0;
}
bool RPLLoader_FixImportSymbols(RPLModule* rplLoaderContext, sint32 symtabSectionIndex, rplSectionEntryNew_t* symTabSection, std::span<RPLSharedImportTracking> sharedImportTracking, uint32 linkMode)
{
uint32 sectionSize = symTabSection->sectionSize;
uint32 symbolEntrySize = symTabSection->ukn24;
if (symbolEntrySize == 0)
symbolEntrySize = 0x10;
cemu_assert(symbolEntrySize == 0x10);
cemu_assert((sectionSize % symbolEntrySize) == 0);
uint32 symbolCount = sectionSize / symbolEntrySize;
cemu_assert(symbolCount >= 2);
uint16 sectionCount = rplLoaderContext->rplHeader.sectionTableEntryCount;
uint8* symtabData = (uint8*)rplLoaderContext->sectionAddressTable2[symtabSectionIndex].ptr;
uint32 strtabSectionIndex = symTabSection->symtabSectionIndex;
uint8* strtabData = (uint8*)rplLoaderContext->sectionAddressTable2[strtabSectionIndex].ptr;
uint32 strtabSize = rplLoaderContext->sectionTablePtr[strtabSectionIndex].sectionSize;
for (uint32 i = 0; i < symbolCount; i++)
{
RPLFileSymtabEntry* sym = (RPLFileSymtabEntry*)(symtabData + i*symbolEntrySize);
uint16 symSectionIndex = sym->sectionIndex;
if (symSectionIndex == 0 || symSectionIndex >= sectionCount)
continue;
void* symbolSectionAddress = rplLoaderContext->sectionAddressTable2[symSectionIndex].ptr;
if (symbolSectionAddress == nullptr)
{
sym->symbolAddress = 0xCD000000 | i;
continue;
}
rplSectionEntryNew_t* symbolSection = rplLoaderContext->sectionTablePtr + symSectionIndex;
uint32 symbolOffset = sym->symbolAddress - symbolSection->virtualAddress;
if (symSectionIndex >= sharedImportTracking.size())
{
cemuLog_log(LogType::Force, "RPL-Loader: Symbol {} references invalid section", i);
}
else if (sharedImportTracking[symSectionIndex].rplLoaderContext != nullptr)
{
if (linkMode == 0)
{
continue; // ?
}
if (symbolOffset < 8)
{
cemu_assert(symbolSectionAddress >= memory_base && symbolSectionAddress <= (memory_base + 0x100000000ULL));
uint32 symbolSectionMPTR = memory_getVirtualOffsetFromPointer(symbolSectionAddress);
uint32 symbolRelativeAddress = (uint32)sym->symbolAddress - (uint32)symbolSection->virtualAddress;
sym->symbolAddress = (symbolSectionMPTR + symbolRelativeAddress);
continue; // ?
}
if (sharedImportTracking[symSectionIndex].rplLoaderContext == HLE_MODULE_PTR)
{
// get address
uint32 nameOffset = sym->ukn00;
char* symbolName = (char*)strtabData + nameOffset;
if (nameOffset >= strtabSize)
{
cemuLog_log(LogType::Force, "RPLLoader: Symbol {} in section {} has out-of-bounds name offset", i, symSectionIndex);
continue;
}
uint32 exportAddress;
if (nameOffset == 0)
{
cemu_assert_debug(symbolName[0] == '\0');
exportAddress = 0;
}
else
{
bool isDataExport = (rplLoaderContext->sectionTablePtr[symSectionIndex].flags & 0x4) == 0;
exportAddress = _findHLEExport(rplLoaderContext, sharedImportTracking.data() + symSectionIndex, sharedImportTracking[symSectionIndex].modulename, symbolName, isDataExport);
}
sym->symbolAddress = exportAddress;
}
else
{
RPLModule* ctxExportModule = sharedImportTracking[symSectionIndex].rplLoaderContext;
uint32 nameOffset = sym->ukn00;
char* symbolName = (char*)strtabData + nameOffset;
bool foundExport = false;
if ((rplLoaderContext->sectionTablePtr[symSectionIndex].flags & 0x4) != 0)
{
// find function export
char* exportNameData = (char*)((uint8*)ctxExportModule->exportFDataPtr - 8);
for (uint32 f = 0; f < ctxExportModule->exportFCount; f++)
{
char* name = exportNameData + (uint32)ctxExportModule->exportFDataPtr[f].nameOffset;
if (strcmp(name, symbolName) == 0)
{
uint32 exportAddress = ctxExportModule->exportFDataPtr[f].virtualOffset;
sym->symbolAddress = exportAddress;
foundExport = true;
break;
}
}
}
else
{
// find data export
char* exportNameData = (char*)((uint8*)ctxExportModule->exportDDataPtr - 8);
for (uint32 f = 0; f < ctxExportModule->exportDCount; f++)
{
char* name = exportNameData + (uint32)ctxExportModule->exportDDataPtr[f].nameOffset;
if (strcmp(name, symbolName) == 0)
{
uint32 exportAddress = ctxExportModule->exportDDataPtr[f].virtualOffset;
sym->symbolAddress = exportAddress;
foundExport = true;
break;
}
}
}
if (foundExport == false)
{
#ifdef CEMU_DEBUG_ASSERT
if (nameOffset > 0)
{
cemuLog_logDebug(LogType::Force, "export not found - force lookup in function exports");
// workaround - force look up export in function exports
char* exportNameData = (char*)((uint8*)ctxExportModule->exportFDataPtr - 8);
for (uint32 f = 0; f < ctxExportModule->exportFCount; f++)
{
char* name = exportNameData + (uint32)ctxExportModule->exportFDataPtr[f].nameOffset;
if (strcmp(name, symbolName) == 0)
{
uint32 exportAddress = ctxExportModule->exportFDataPtr[f].virtualOffset;
sym->symbolAddress = exportAddress;
foundExport = true;
break;
}
}
}
#endif
continue;
}
}
}
else
{
uint32 symbolType = sym->info & 0xF;
if (symbolType == 6)
continue;
if (((uint32)symbolSection->type != SHT_RPL_IMPORTS && linkMode != 2) ||
((uint32)symbolSection->type == SHT_RPL_IMPORTS && linkMode != 1 && linkMode != 2)
)
{
// update virtual address to match actual mapped address
cemu_assert(symbolSectionAddress >= memory_base && symbolSectionAddress <= (memory_base + 0x100000000ULL));
uint32 symbolSectionMPTR = memory_getVirtualOffsetFromPointer(symbolSectionAddress);
uint32 symbolRelativeAddress = (uint32)sym->symbolAddress - (uint32)symbolSection->virtualAddress;
sym->symbolAddress = (symbolSectionMPTR + symbolRelativeAddress);
}
}
}
return true;
}
bool RPLLoader_ApplySingleReloc(RPLModule* rplLoaderContext, uint32 uknR3, uint8* relocTargetSectionAddress, uint32 relocType, bool isSymbolBinding2, uint32 relocOffset, uint32 relocAddend, uint32 symbolAddress, sint16 tlsModuleIndex)
{
MPTR relocTargetSectionMPTR = memory_getVirtualOffsetFromPointer(relocTargetSectionAddress);
MPTR relocAddrMPTR = relocTargetSectionMPTR + relocOffset;
uint8* relocAddr = memory_getPointerFromVirtualOffset(relocAddrMPTR);
if (relocType == RPL_RELOC_HA16)
{
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 p = (relocDestAddr >> 16);
p += (relocDestAddr >> 15) & 1;
*(uint16be*)(relocAddr) = (uint16)p;
}
else if (relocType == RPL_RELOC_LO16)
{
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 p = relocDestAddr;
*(uint16be*)(relocAddr) = (uint16)p;
}
else if (relocType == RPL_RELOC_HI16)
{
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 p = relocDestAddr>>16;
*(uint16be*)(relocAddr) = (uint16)p;
}
else if (relocType == RPL_RELOC_REL24)
{
// todo - effect of isSymbolBinding2?
uint32 opc = *(uint32be*)relocAddr;
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 jumpDistance = relocDestAddr - memory_getVirtualOffsetFromPointer(relocAddr);
if ((jumpDistance>>25) != 0 && (jumpDistance >> 25) != 0x7F)
{
// can't reach with 24bit jump, use trampoline + absolute branch
MPTR trampolineAddr = _generateTrampolineFarJump(rplLoaderContext, relocDestAddr);
// make absolute branch
cemu_assert_debug((opc >> 26) == 18); // should be B/BL instruction
opc &= ~0x03fffffc;
opc |= (trampolineAddr & 0x3FFFFFC);
opc |= (1 << 1); // absolute jump
*(uint32be*)relocAddr = opc;
}
else
{
// within range, update jump opcode
if ((jumpDistance & 3) != 0)
cemuLog_log(LogType::Force, "RPL-Loader: Encountered unaligned RPL_RELOC_REL24");
opc &= ~0x03fffffc;
opc |= (jumpDistance &0x03fffffc);
*(uint32be*)relocAddr = opc;
}
}
else if (relocType == RPL_RELOC_REL14)
{
// seen in Your Shape: Fitness Evolved
// todo - effect of isSymbolBinding2?
uint32 opc = *(uint32be*)relocAddr;
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 jumpDistance = relocDestAddr - memory_getVirtualOffsetFromPointer(relocAddr);
if ((jumpDistance & ~0x7fff) != 0xFFFF8000 && (jumpDistance & ~0x7fff) != 0x00000000)
{
cemu_assert_debug(false);
}
else
{
// within range, update jump opcode
if ((jumpDistance & 3) != 0)
cemuLog_log(LogType::Force, "RPL-Loader: Encountered unaligned RPL_RELOC_REL14");
opc &= ~0xfffc;
opc |= (jumpDistance & 0xfffc);
*(uint32be*)relocAddr = opc;
}
}
else if (relocType == RPL_RELOC_ADDR32)
{
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 p = relocDestAddr;
*(uint32be*)(relocAddr) = (uint32)p;
}
else if (relocType == R_PPC_DTPMOD32)
{
// patch tls_index.moduleIndex
*(uint32be*)(relocAddr) = (uint32)(sint32)tlsModuleIndex;
}
else if (relocType == R_PPC_DTPREL32)
{
// patch tls_index.size
*(uint32be*)(relocAddr) = (uint32)(sint32)(symbolAddress + relocAddend);
}
else if (relocType == R_PPC_REL16_HA)
{
// used by WUT
uint32 relAddr = (symbolAddress + relocAddend) - relocAddrMPTR;
uint32 p = (relAddr >> 16);
p += (relAddr >> 15) & 1;
*(uint16be*)(relocAddr) = (uint16)p;
}
else if (relocType == R_PPC_REL16_HI)
{
// used by WUT
uint32 relAddr = (symbolAddress + relocAddend) - relocAddrMPTR;
uint32 p = (relAddr >> 16);
*(uint16be*)(relocAddr) = (uint16)p;
}
else if (relocType == R_PPC_REL16_LO)
{
// used by WUT
uint32 relAddr = (symbolAddress + relocAddend) - relocAddrMPTR;
uint32 p = (relAddr & 0xFFFF);
*(uint16be*)(relocAddr) = (uint16)p;
}
else if (relocType == 0x6D) // SDATA reloc
{
uint32 opc = *(uint32be*)relocAddr;
uint32 registerIndex = (opc >> 16) & 0x1F;
uint32 destination = (symbolAddress + relocAddend);;
if (registerIndex == 2)
{
uint32 offset = destination - rplLoader_sdata2Addr;
uint32 newOpc = (opc & 0xffe00000) | (offset & 0xffff) | (registerIndex << 16);
*(uint32be*)relocAddr = newOpc;
}
else if (registerIndex == 13)
{
uint32 offset = destination - rplLoader_sdataAddr;
uint32 newOpc = (opc & 0xffe00000) | (offset & 0xffff) | (registerIndex << 16);
*(uint32be*)relocAddr = newOpc;
}
else
{
cemuLog_log(LogType::Force, "RPLLoader: sdata reloc uses register other than r2/r13");
cemu_assert(false);
}
}
else if (relocType == 0xFB)
{
// relative offset - high
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 relativeOffset = relocDestAddr - relocAddrMPTR;
uint16 prevValue = *(uint16be*)relocAddr;
uint32 newImm = ((relativeOffset >> 16) + ((relativeOffset >> 15) & 0x1));
newImm &= 0xFFFF;
*(uint16be*)relocAddr = newImm;
if (symbolAddress != 0)
{
cemu_assert_debug((uint32)prevValue == newImm);
}
}
else if (relocType == 0xFD)
{
// relative offset - low
uint32 relocDestAddr = symbolAddress + relocAddend;
uint32 relativeOffset = relocDestAddr - relocAddrMPTR;
uint16 prevValue = *(uint16be*)relocAddr;
uint32 newImm = relativeOffset;
newImm &= 0xFFFF;
*(uint16be*)relocAddr = newImm;
if (symbolAddress != 0)
{
cemu_assert_debug((uint32)prevValue == newImm);
}
}
else
{
cemuLog_log(LogType::Force, "RPLLoader: Unsupported reloc type 0x{:02x}", relocType);
cemu_assert_debug(false); // unknown reloc type
}
return true;
}
bool RPLLoader_ApplyRelocs(RPLModule* rplLoaderContext, sint32 relaSectionIndex, rplSectionEntryNew_t* section, uint32 linkMode)
{
uint32 relocTargetSectionIndex = section->relocTargetSectionIndex;
if (relocTargetSectionIndex >= (uint32)rplLoaderContext->rplHeader.sectionTableEntryCount)
assert_dbg();
uint32 symtabSectionIndex = section->symtabSectionIndex;
uint8* relocTargetSectionAddress = (uint8*)(rplLoaderContext->sectionAddressTable2[relocTargetSectionIndex].ptr);
cemu_assert(relocTargetSectionAddress);
// get symtab info
rplSectionEntryNew_t* symtabSection = rplLoaderContext->sectionTablePtr + symtabSectionIndex;
uint32 symtabSectionSize = symtabSection->sectionSize;
uint32 symbolEntrySize = symtabSection->ukn24;
if (symbolEntrySize == 0)
symbolEntrySize = 0x10;
cemu_assert(symbolEntrySize == 0x10);
cemu_assert((symtabSectionSize % symbolEntrySize) == 0);
uint32 symbolCount = symtabSectionSize / symbolEntrySize;
cemu_assert(symbolCount >= 2);
uint8* symtabData = (uint8*)rplLoaderContext->sectionAddressTable2[symtabSectionIndex].ptr;
// decompress reloc section if needed
uint8* relocData;
uint32 relocSize;
if ((uint32)(section->flags) & SHF_RPL_COMPRESSED)
{
uint8* relocRawData = (uint8*)rplLoaderContext->sectionAddressTable2[relaSectionIndex].ptr;
uint32 relocUncompressedSize = *(uint32be*)relocRawData;
relocData = (uint8*)malloc(relocUncompressedSize);
relocSize = relocUncompressedSize;
// decompress
int ret;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = inflateInit(&strm);
if (ret == Z_OK)
{
strm.avail_in = (uint32)section->sectionSize - 4;
strm.next_in = relocRawData + 4;
strm.avail_out = relocUncompressedSize;
strm.next_out = relocData;
ret = inflate(&strm, Z_FULL_FLUSH);
cemu_assert_debug(ret == Z_OK || ret == Z_STREAM_END);
cemu_assert_debug(strm.avail_in == 0 && strm.avail_out == 0);
inflateEnd(&strm);
}
}
else
{
relocData = (uint8*)rplLoaderContext->sectionAddressTable2[relaSectionIndex].ptr;
relocSize = section->sectionSize;
}
// check CRC
uint32 calcCRC = crc32_calc(0, relocData, relocSize);
uint32 crc = rplLoaderContext->GetSectionCRC(relaSectionIndex);
if (calcCRC != crc)
{
cemuLog_log(LogType::Force, "RPLLoader {} - Relocation section {} has CRC mismatch - Calc: {:08x} Actual: {:08x}", rplLoaderContext->moduleName2.c_str(), relaSectionIndex, calcCRC, crc);
}
// process relocations
sint32 relocCount = relocSize / sizeof(rplRelocNew_t);
rplRelocNew_t* reloc = (rplRelocNew_t*)relocData;
for (sint32 i = 0; i < relocCount; i++)
{
uint32 relocType = (uint32)reloc->symbolIndexAndType & 0xFF;
uint32 relocSymbolIndex = (uint32)reloc->symbolIndexAndType >> 8;
if (relocType == 0)
{
// next
reloc++;
continue;
}
if (relocSymbolIndex >= symbolCount)
{
cemuLog_logDebug(LogType::Force, "reloc with symbol index out of range 0x{:04x}", (uint32)relocSymbolIndex);
reloc++;
continue;
}
// get symbol
RPLFileSymtabEntry* sym = (RPLFileSymtabEntry*)(symtabData + symbolEntrySize*relocSymbolIndex);
if ((uint32)sym->sectionIndex >= (uint32)rplLoaderContext->rplHeader.sectionTableEntryCount)
{
cemuLog_logDebug(LogType::Force, "reloc with sectionIndex out of range 0x{:04x}", (uint32)sym->sectionIndex);
reloc++;
continue;
}
// exclude symbols that arent ready yet
if (linkMode == 0)
{
if ((uint32)rplLoaderContext->sectionTablePtr[(uint32)sym->sectionIndex].type == SHT_RPL_IMPORTS)
{
reloc++;
continue;
}
}
uint32 symbolAddress = sym->symbolAddress;
uint8 symbolType = (sym->info >> 0) & 0xF;
uint8 symbolBinding = (sym->info >> 4) & 0xF;
if ((symbolAddress&0xFF000000) == 0xCD000000)
{
cemu_assert_unimplemented();
// next
reloc++;
continue;
}
sint16 tlsModuleIndex = -1;
if (relocType == R_PPC_DTPMOD32 || relocType == R_PPC_DTPREL32)
{
// TLS-relocation
if (symbolType != 6)
assert_dbg(); // not a TLS symbol
if (rplLoaderContext->fileInfo.tlsModuleIndex == -1)
{
cemuLog_log(LogType::Force, "RPLLoader: TLS relocs applied to non-TLS module");
cemu_assert_debug(false); // module not a TLS-module
}
tlsModuleIndex = rplLoaderContext->fileInfo.tlsModuleIndex;
}
uint32 relocOffset = (uint32)reloc->relocOffset - (uint32)rplLoaderContext->sectionTablePtr[relocTargetSectionIndex].virtualAddress;
RPLLoader_ApplySingleReloc(rplLoaderContext, 0, relocTargetSectionAddress, relocType, symbolBinding == 2, relocOffset, reloc->relocAddend, symbolAddress, tlsModuleIndex);
// next reloc
reloc++;
}
if ((uint32)(section->flags) & SHF_RPL_COMPRESSED)
free(relocData);
return true;
}
bool RPLLoader_HandleRelocs(RPLModule* rplLoaderContext, std::span<RPLSharedImportTracking> sharedImportTracking, uint32 linkMode)
{
// resolve relocs
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
if( sectionType != SHT_SYMTAB )
continue;
RPLLoader_FixImportSymbols(rplLoaderContext, i, section, sharedImportTracking, linkMode);
}
// apply relocs again after we have fixed the import section
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
if (sectionType != SHT_RELA)
continue;
RPLLoader_ApplyRelocs(rplLoaderContext, i, section, linkMode);
}
return true;
}
void _RPLLoader_ExtractModuleNameFromPath(char* output, std::string_view input)
{
// scan to last '/'
cemu_assert(!input.empty());
size_t startIndex = input.size() - 1;
while (startIndex > 0)
{
if (input[startIndex] == '/')
{
startIndex++;
break;
}
startIndex--;
}
// cut off after '.'
size_t endIndex = startIndex;
while (endIndex < input.size())
{
if (input[endIndex] == '.')
break;
endIndex++;
}
size_t nameLen = endIndex - startIndex;
cemu_assert(nameLen != 0);
nameLen = std::min<size_t>(nameLen, RPL_MODULE_NAME_LENGTH-1);
memcpy(output, input.data() + startIndex, nameLen);
output[nameLen] = '\0';
// convert to lower case
std::for_each(output, output + nameLen, [](char& c) {c = _ansiToLower(c);});
}
void RPLLoader_InitState()
{
cemu_assert_debug(!rplLoaderHeap_lowerAreaCodeMem2.hasAllocations());
cemu_assert_debug(!rplLoaderHeap_codeArea2.hasAllocations());
cemu_assert_debug(!rplLoaderHeap_workarea.hasAllocations());
rplLoaderHeap_lowerAreaCodeMem2.setHeapBase(memory_getPointerFromVirtualOffset(MEMORY_CODE_TRAMPOLINE_AREA_ADDR));
rplLoaderHeap_codeArea2.setHeapBase(memory_getPointerFromVirtualOffset(MEMORY_CODEAREA_ADDR));
rplLoaderHeap_workarea.setHeapBase(memory_getPointerFromVirtualOffset(MEMORY_RPLLOADER_AREA_ADDR));
g_heapTrampolineArea.setBaseAllocator(&rplLoaderHeap_lowerAreaCodeMem2);
RPLLoader_ResetState();
}
void RPLLoader_BeginCemuhookCRC(RPLModule* rpl)
{
// calculate some values required for CRC
sint32 sectionSymTableIndex = -1;
sint32 sectionStrTableIndex = -1;
for (sint32 i = 0; i < rpl->rplHeader.sectionTableEntryCount; i++)
{
if (rpl->sectionTablePtr[i].type == SHT_SYMTAB)
sectionSymTableIndex = i;
if (rpl->sectionTablePtr[i].type == SHT_STRTAB && i != rpl->rplHeader.nameSectionIndex && sectionStrTableIndex == -1)
sectionStrTableIndex = i;
}
// init patches CRC
rpl->patchCRC = 0;
static const uint8 rplMagic[4] = { 0x7F, 'R', 'P', 'X' };
rpl->patchCRC = crc32_calc(rpl->patchCRC, rplMagic, sizeof(rplMagic));
sint32 sectionCount = rpl->rplHeader.sectionTableEntryCount;
rpl->patchCRC = crc32_calc(rpl->patchCRC, §ionCount, sizeof(sectionCount));
rpl->patchCRC = crc32_calc(rpl->patchCRC, §ionSymTableIndex, sizeof(sectionSymTableIndex));
rpl->patchCRC = crc32_calc(rpl->patchCRC, §ionStrTableIndex, sizeof(sectionStrTableIndex));
sint32 sectionSectNameTableIndex = rpl->rplHeader.nameSectionIndex;
rpl->patchCRC = crc32_calc(rpl->patchCRC, §ionSectNameTableIndex, sizeof(sectionSectNameTableIndex));
// sections
for (sint32 i = 0; i < rpl->rplHeader.sectionTableEntryCount; i++)
{
auto sect = rpl->sectionTablePtr + i;
uint32 nameOffset = sect->nameOffset;
uint32 shType = sect->type;
uint32 flags = sect->flags;
uint32 virtualAddress = sect->virtualAddress;
uint32 alignment = sect->alignment;
uint32 sectionFileOffset = sect->fileOffset;
uint32 sectionCompressedSize = sect->sectionSize;
uint32 rawSize = 0;
bool memoryAllocated = false;
void* rawData = nullptr;
if (shType == SHT_NOBITS)
{
rawData = NULL;
rawSize = sectionCompressedSize;
}
else if ((flags&SHF_RPL_COMPRESSED) != 0)
{
uint32 decompressedSize = _swapEndianU32(*(uint32*)(rpl->RPLRawData.data() + sectionFileOffset));
rawSize = decompressedSize;
if (rawSize >= 1024*1024*1024)
{
cemuLog_logDebug(LogType::Force, "RPLLoader-CRC: Cannot load section {} which is too large ({} bytes)", i, decompressedSize);
cemu_assert_debug(false);
continue;
}
rawData = (uint8*)malloc(decompressedSize);
if (rawData == nullptr)
{
cemuLog_logDebug(LogType::Force, "RPLLoader-CRC: Failed to allocate memory for uncompressed section {} ({} bytes)", i, decompressedSize);
cemu_assert_debug(false);
continue;
}
memoryAllocated = true;
// decompress
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
inflateInit(&strm);
strm.avail_in = sectionCompressedSize - 4;
strm.next_in = rpl->RPLRawData.data() + (uint32)sectionFileOffset + 4;
strm.avail_out = decompressedSize;
strm.next_out = (Bytef*)rawData;
auto ret = inflate(&strm, Z_FULL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END || strm.avail_in != 0 || strm.avail_out != 0)
{
cemuLog_logDebug(LogType::Force, "RPLLoader-CRC: Unable to decompress section {}", i);
cemuLog_logDebug(LogType::Force, "zRet {} availIn {} availOut {}", ret, (sint32)strm.avail_in, (sint32)strm.avail_out);
cemu_assert_debug(false);
free(rawData);
inflateEnd(&strm);
continue;
}
inflateEnd(&strm);
}
else
{
rawSize = sectionCompressedSize;
rawData = rpl->RPLRawData.data() + sectionFileOffset;
}
rpl->patchCRC = crc32_calc(rpl->patchCRC, &nameOffset, sizeof(nameOffset));
rpl->patchCRC = crc32_calc(rpl->patchCRC, &shType, sizeof(shType));
rpl->patchCRC = crc32_calc(rpl->patchCRC, &flags, sizeof(flags));
rpl->patchCRC = crc32_calc(rpl->patchCRC, &virtualAddress, sizeof(virtualAddress));
rpl->patchCRC = crc32_calc(rpl->patchCRC, &rawSize, sizeof(rawSize));
rpl->patchCRC = crc32_calc(rpl->patchCRC, &alignment, sizeof(alignment));
if (rawData != nullptr && rawSize > 0)
{
rpl->patchCRC = crc32_calc(rpl->patchCRC, rawData, rawSize);
}
if (memoryAllocated && rawData)
free(rawData);
}
}
void RPLLoader_incrementModuleDependencyRefs(RPLModule* rpl)
{
for (uint32 i = 0; i < (uint32)rpl->rplHeader.sectionTableEntryCount; i++)
{
if (rpl->sectionTablePtr[i].type != (uint32be)SHT_RPL_IMPORTS)
continue;
char* libName = (char*)((uint8*)rpl->sectionAddressTable2[i].ptr + 8);
RPLLoader_AddDependency(libName);
}
}
void RPLLoader_decrementModuleDependencyRefs(RPLModule* rpl)
{
for (uint32 i = 0; i < (uint32)rpl->rplHeader.sectionTableEntryCount; i++)
{
if (rpl->sectionTablePtr[i].type != (uint32be)SHT_RPL_IMPORTS)
continue;
char* libName = (char*)((uint8*)rpl->sectionAddressTable2[i].ptr + 8);
RPLLoader_RemoveDependency(libName);
}
}
void RPLLoader_UpdateEntrypoint(RPLModule* rpl)
{
uint32 virtualEntrypoint = rpl->rplHeader.entrypoint;
uint32 entrypoint = 0xFFFFFFFF;
for (sint32 i = 0; i < (sint32)rpl->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rpl->sectionTablePtr + i;
uint32 sectionStartAddr = (uint32)section->virtualAddress;
uint32 sectionEndAddr = (uint32)section->virtualAddress + (uint32)section->sectionSize;
if (virtualEntrypoint >= sectionStartAddr && virtualEntrypoint < sectionEndAddr)
{
cemu_assert_debug(entrypoint == 0xFFFFFFFF);
entrypoint = (virtualEntrypoint - sectionStartAddr + memory_getVirtualOffsetFromPointer(rpl->sectionAddressTable2[i].ptr));
}
}
cemu_assert(entrypoint != 0xFFFFFFFF);
rpl->entrypoint = entrypoint;
}
void RPLLoader_InitModuleAllocator(RPLModule* rpl)
{
if (!rplLoader_applicationHasMemoryControl)
{
rpl->funcAlloc = 0;
rpl->funcFree = 0;
return;
}
coreinit::OSDynLoad_GetAllocator(&rpl->funcAlloc, &rpl->funcFree);
}
// map rpl into memory, but do not resolve relocs and imports yet
RPLModule* RPLLoader_LoadFromMemory(uint8* rplData, sint32 size, char* name)
{
char moduleName[RPL_MODULE_NAME_LENGTH];
_RPLLoader_ExtractModuleNameFromPath(moduleName, name);
RPLModule* rpl = nullptr;
if (RPLLoader_ProcessHeaders({ moduleName }, rplData, size, &rpl) == false)
{
delete rpl;
return nullptr;
}
RPLLoader_InitModuleAllocator(rpl);
RPLLoader_BeginCemuhookCRC(rpl);
if (RPLLoader_LoadSections(0, rpl) == false)
{
delete rpl;
return nullptr;
}
cemuLog_logDebug(LogType::Force, "Load {} Code-Offset: -0x{:x}", name, rpl->regionMappingBase_text.GetMPTR() - 0x02000000);
// sdata (r2/r13)
uint32 sdataBaseAddress = rpl->fileInfo.sdataBase1; // base + 0x8000
uint32 sdataBaseAddress2 = rpl->fileInfo.sdataBase2; // base + 0x8000
for (uint32 i = 0; i < (uint32)rpl->rplHeader.sectionTableEntryCount; i++)
{
if(rpl->sectionTablePtr[i].sectionSize == 0)
continue;
uint32 sectionFlags = rpl->sectionTablePtr[i].flags;
uint32 sectionVirtualAddress = rpl->sectionTablePtr[i].virtualAddress;
uint32 sectionSize = rpl->sectionTablePtr[i].sectionSize;
if( (sectionFlags&4) != 0 )
continue;
if(sdataBaseAddress == 0x00008000 && sdataBaseAddress2 == 0x00008000)
continue; // sdata not used (this workaround is needed for Wii U Party to boot)
// sdata 1
if ((sdataBaseAddress - 0x8000) >= (sectionVirtualAddress) &&
(sdataBaseAddress - 0x8000) <= (sectionVirtualAddress + sectionSize))
{
uint32 rplLoader_sdataAddrNew = memory_getVirtualOffsetFromPointer(rpl->sectionAddressTable2[i].ptr) + (sdataBaseAddress - sectionVirtualAddress);
rplLoader_sdataAddr = rplLoader_sdataAddrNew;
}
// sdata 2
if ((sdataBaseAddress2 - 0x8000) >= (sectionVirtualAddress) &&
(sdataBaseAddress2 - 0x8000) <= (sectionVirtualAddress + sectionSize))
{
rplLoader_sdata2Addr = memory_getVirtualOffsetFromPointer(rpl->sectionAddressTable2[i].ptr) + (sdataBaseAddress2 - sectionVirtualAddress);
}
}
// cancel if error
if (rpl->hasError)
{
cemuLog_log(LogType::Force, "RPLLoader: Unable to load RPL due to errors");
delete rpl;
return nullptr;
}
// find TLS section
uint32 tlsStartAddress = 0xFFFFFFFF;
uint32 tlsEndAddress = 0;
for (uint32 i = 0; i < (uint32)rpl->rplHeader.sectionTableEntryCount; i++)
{
if ( ((uint32)rpl->sectionTablePtr[i].flags & SHF_TLS) == 0 )
continue;
uint32 sectionVirtualAddress = rpl->sectionTablePtr[i].virtualAddress;
uint32 sectionSize = rpl->sectionTablePtr[i].sectionSize;
tlsStartAddress = std::min(tlsStartAddress, sectionVirtualAddress);
tlsEndAddress = std::max(tlsEndAddress, sectionVirtualAddress+sectionSize);
}
if (tlsStartAddress == 0xFFFFFFFF)
{
tlsStartAddress = 0;
tlsEndAddress = 0;
}
rpl->tlsStartAddress = tlsStartAddress;
rpl->tlsEndAddress = tlsEndAddress;
// add to module list
cemu_assert(rplModuleCount < 256);
rplModuleList[rplModuleCount] = rpl;
rplModuleCount++;
// track dependencies
RPLLoader_incrementModuleDependencyRefs(rpl);
// update entrypoint
RPLLoader_UpdateEntrypoint(rpl);
return rpl;
}
void RPLLoader_FlushMemory(RPLModule* rpl)
{
// invalidate recompiler cache
PPCRecompiler_invalidateRange(rpl->regionMappingBase_text.GetMPTR(), rpl->regionMappingBase_text.GetMPTR() + rpl->regionSize_text);
rpl->heapTrampolineArea.forEachBlock([](void* mem, uint32 size)
{
MEMPTR<void> memVirtual = mem;
PPCRecompiler_invalidateRange(memVirtual.GetMPTR(), memVirtual.GetMPTR() + size);
});
}
// resolve relocs and imports of all modules. Or resolve exports
void RPLLoader_LinkSingleModule(RPLModule* rplLoaderContext, bool resolveOnlyExports)
{
// setup shared import tracking
std::vector<RPLSharedImportTracking> sharedImportTracking;
sharedImportTracking.resize(rplLoaderContext->rplHeader.sectionTableEntryCount - 2);
memset(sharedImportTracking.data(), 0, sizeof(RPLSharedImportTracking) * sharedImportTracking.size());
for (uint32 i = 0; i < (uint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
if( rplLoaderContext->sectionTablePtr[i].type != (uint32be)SHT_RPL_IMPORTS )
continue;
char* libName = (char*)((uint8*)rplLoaderContext->sectionAddressTable2[i].ptr + 8);
// make module name
char _importModuleName[RPL_MODULE_NAME_LENGTH];
_RPLLoader_ExtractModuleNameFromPath(_importModuleName, libName);
// find in loaded module list
std::string importModuleName{_importModuleName};
bool foundModule = false;
for (sint32 f = 0; f < rplModuleCount; f++)
{
if (boost::iequals(rplModuleList[f]->moduleName2, importModuleName))
{
sharedImportTracking[i].rplLoaderContext = rplModuleList[f];
memset(sharedImportTracking[i].modulename, 0, sizeof(sharedImportTracking[i].modulename));
strcpy_s(sharedImportTracking[i].modulename, importModuleName.c_str());
foundModule = true;
break;
}
}
if( foundModule )
continue;
// if not found, we assume it's a HLE lib
sharedImportTracking[i].rplLoaderContext = HLE_MODULE_PTR;
sharedImportTracking[i].exportSection = nullptr;
strcpy_s(sharedImportTracking[i].modulename, libName);
}
if (resolveOnlyExports)
RPLLoader_HandleRelocs(rplLoaderContext, sharedImportTracking, 2);
else
RPLLoader_HandleRelocs(rplLoaderContext, sharedImportTracking, 0);
RPLLoader_FlushMemory(rplLoaderContext);
}
void RPLLoader_LoadSectionDebugSymbols(RPLModule* rplLoaderContext, rplSectionEntryNew_t* section, int symtabSectionIndex)
{
uint32 sectionSize = section->sectionSize;
uint32 symbolEntrySize = section->ukn24;
if (symbolEntrySize == 0)
symbolEntrySize = 0x10;
cemu_assert(symbolEntrySize == 0x10);
cemu_assert((sectionSize % symbolEntrySize) == 0);
uint32 symbolCount = sectionSize / symbolEntrySize;
cemu_assert(symbolCount >= 2);
uint16 sectionCount = rplLoaderContext->rplHeader.sectionTableEntryCount;
uint8* symtabData = (uint8*)rplLoaderContext->sectionAddressTable2[symtabSectionIndex].ptr;
uint32 strtabSectionIndex = section->symtabSectionIndex;
uint8* strtabData = (uint8*)rplLoaderContext->sectionAddressTable2[strtabSectionIndex].ptr;
for (uint32 i = 0; i < symbolCount; i++)
{
RPLFileSymtabEntry* sym = (RPLFileSymtabEntry*)(symtabData + i * symbolEntrySize);
uint16 symSectionIndex = sym->sectionIndex;
if (symSectionIndex == 0 || symSectionIndex >= sectionCount)
continue;
void* symbolSectionAddress = rplLoaderContext->sectionAddressTable2[symSectionIndex].ptr;
if (symbolSectionAddress == nullptr)
continue;
rplSectionEntryNew_t* symbolSection = rplLoaderContext->sectionTablePtr + symSectionIndex;
if(symbolSection->type == SHT_RPL_EXPORTS || symbolSection->type == SHT_RPL_IMPORTS)
continue; // exports and imports are handled separately
uint32 symbolOffset = sym->symbolAddress - symbolSection->virtualAddress;
uint32 nameOffset = sym->ukn00;
if (nameOffset > 0)
{
char* symbolName = (char*)strtabData + nameOffset;
if (sym->info == 0x12)
{
rplSymbolStorage_store(rplLoaderContext->moduleName2.c_str(), symbolName, sym->symbolAddress);
}
}
}
}
void RPLLoader_LoadDebugSymbols(RPLModule* rplLoaderContext)
{
for (sint32 i = 0; i < (sint32)rplLoaderContext->rplHeader.sectionTableEntryCount; i++)
{
rplSectionEntryNew_t* section = rplLoaderContext->sectionTablePtr + i;
uint32 sectionType = section->type;
if (sectionType != SHT_SYMTAB)
continue;
RPLLoader_LoadSectionDebugSymbols(rplLoaderContext, section, i);
}
}
void RPLLoader_UnloadModule(RPLModule* rpl)
{
/*
A note:
Mario Party 10's mg0480.rpl (minigame Spike Ball Scramble) has a bug where it keeps running code (function 0x02086BCC for example) after RPL unload
It seems to rely on the RPL loader not zeroing released memory
*/
// decrease reference counters of all dependencies
RPLLoader_decrementModuleDependencyRefs(rpl);
// save module config for this module in the debugger
debuggerWindow_notifyModuleUnloaded(rpl);
// release memory
rplLoaderHeap_codeArea2.free(rpl->regionMappingBase_text.GetPtr());
rpl->regionMappingBase_text = nullptr;
// for some reason freeing the data allocations causes a crash in MP10 on boot
//RPLLoader_FreeData(rpl, MEMPTR<void>(rpl->regionMappingBase_data).GetPtr());
//rpl->regionMappingBase_data = 0;
//RPLLoader_FreeData(rpl, MEMPTR<void>(rpl->regionMappingBase_loaderInfo).GetPtr());
//rpl->regionMappingBase_loaderInfo = 0;
rpl->heapTrampolineArea.releaseAll();
// todo - remove from rplSymbolStorage_store
if (rpl->sectionTablePtr)
{
free(rpl->sectionTablePtr);
rpl->sectionTablePtr = nullptr;
}
// unload temp region
if (rpl->tempRegionPtr)
{
RPLLoader_FreeWorkarea(rpl->tempRegionPtr);
rpl->tempRegionPtr = nullptr;
}
// remove from rpl module list
for (sint32 i = 0; i < rplModuleCount; i++)
{
if (rplModuleList[i] == rpl)
{
rplModuleList[i] = rplModuleList[rplModuleCount-1];
rplModuleCount--;
break;
}
}
delete rpl;
}
void RPLLoader_FixModuleTLSIndex(RPLModule* rplLoaderContext)
{
sint16 tlsModuleIndex = -1;
for (auto& dep : rplDependencyList)
{
if (boost::iequals(rplLoaderContext->moduleName2, dep->modulename))
{
tlsModuleIndex = dep->tlsModuleIndex;
break;
}
}
cemu_assert(tlsModuleIndex != -1);
rplLoaderContext->fileInfo.tlsModuleIndex = tlsModuleIndex;
}
void RPLLoader_Link()
{
// calculate TLS index
for (sint32 i = 0; i < rplModuleCount; i++)
{
if (rplModuleList[i]->isLinked)
continue;
RPLLoader_FixModuleTLSIndex(rplModuleList[i]);
}
// resolve relocs
for (sint32 i = 0; i < rplModuleCount; i++)
{
if(rplModuleList[i]->isLinked)
continue;
RPLLoader_LinkSingleModule(rplModuleList[i], false);
}
// resolve imports and load debug symbols
for (sint32 i = 0; i < rplModuleCount; i++)
{
if (rplModuleList[i]->isLinked)
continue;
RPLLoader_LinkSingleModule(rplModuleList[i], true);
RPLLoader_LoadDebugSymbols(rplModuleList[i]);
rplModuleList[i]->isLinked = true; // mark as linked
GraphicPack2::NotifyModuleLoaded(rplModuleList[i]);
debuggerWindow_notifyModuleLoaded(rplModuleList[i]);
}
}
uint32 RPLLoader_GetModuleEntrypoint(RPLModule* rplLoaderContext)
{
return rplLoaderContext->entrypoint;
}
// takes a module name without extension, returns true if the RPL module is a known Cafe OS module
bool RPLLoader_IsKnownCafeOSModule(std::string_view name)
{
static std::unordered_set<std::string> s_systemModules556 = {
"avm","camera","coreinit","dc","dmae","drmapp","erreula",
"gx2","h264","lzma920","mic","nfc","nio_prof","nlibcurl",
"nlibnss","nlibnss2","nn_ac","nn_acp","nn_act","nn_aoc","nn_boss",
"nn_ccr","nn_cmpt","nn_dlp","nn_ec","nn_fp","nn_hai","nn_hpad",
"nn_idbe","nn_ndm","nn_nets2","nn_nfp","nn_nim","nn_olv","nn_pdm",
"nn_save","nn_sl","nn_spm","nn_temp","nn_uds","nn_vctl","nsysccr",
"nsyshid","nsyskbd","nsysnet","nsysuhs","nsysuvd","ntag","padscore",
"proc_ui","sndcore2","snduser2","snd_core","snd_user","swkbd","sysapp",
"tcl","tve","uac","uac_rpl","usb_mic","uvc","uvd","vpad","vpadbase",
"zlib125"};
std::string nameLower{name};
std::transform(nameLower.begin(), nameLower.end(), nameLower.begin(), _ansiToLower);
return s_systemModules556.contains(nameLower);
}
// increment reference counter for module
void RPLLoader_AddDependency(const char* name)
{
cemu_assert(name[0] != '\0');
// if name includes a path, cut it off
const char* namePtr = name + strlen(name) - 1;
while (namePtr > name)
{
if (*namePtr == '/')
{
namePtr++;
break;
}
namePtr--;
}
name = namePtr;
// get module name from path
char moduleName[RPL_MODULE_NAME_LENGTH];
_RPLLoader_ExtractModuleNameFromPath(moduleName, name);
// check if dependency already exists
for (auto& dep : rplDependencyList)
{
if (strcmp(moduleName, dep->modulename) == 0)
{
dep->referenceCount++;
return;
}
}
// add new entry
RPLDependency* newDependency = new RPLDependency();
strcpy(newDependency->modulename, moduleName);
newDependency->referenceCount = 1;
newDependency->coreinitHandle = rplLoader_currentHandleCounter;
newDependency->tlsModuleIndex = rplLoader_currentTlsModuleIndex;
newDependency->isCafeOSModule = RPLLoader_IsKnownCafeOSModule(moduleName);
rplLoader_currentTlsModuleIndex++; // todo - delay handle and tls allocation until the module is actually loaded. It may not exist
rplLoader_currentHandleCounter++;
if (rplLoader_currentTlsModuleIndex == 0x7FFF)
cemuLog_log(LogType::Force, "RPLLoader: Exhausted TLS module indices pool");
// convert name to path/filename if it isn't already one
if (strchr(name, '.'))
{
strcpy_s(newDependency->filepath, name);
}
else
{
strcpy_s(newDependency->filepath, name);
strcat_s(newDependency->filepath, ".rpl");
}
newDependency->filepath[RPL_MODULE_PATH_LENGTH - 1] = '\0';
rplDependencyList.push_back(newDependency);
}
// decrement reference counter for dependency by module path
void RPLLoader_RemoveDependency(const char* name)
{
cemu_assert(*name != '\0');
// if name includes a path, cut it off
const char* namePtr = name + strlen(name) - 1;
while (namePtr > name)
{
if (*namePtr == '/')
{
namePtr++;
break;
}
namePtr--;
}
name = namePtr;
// get module name from path
char moduleName[RPL_MODULE_NAME_LENGTH];
_RPLLoader_ExtractModuleNameFromPath(moduleName, name);
// find dependency and decrement ref count
for (auto& dep : rplDependencyList)
{
if (strcmp(moduleName, dep->modulename) == 0)
{
dep->referenceCount--;
return;
}
}
}
bool RPLLoader_HasDependency(std::string_view name)
{
char moduleName[RPL_MODULE_NAME_LENGTH];
_RPLLoader_ExtractModuleNameFromPath(moduleName, name);
for (const auto& dep : rplDependencyList)
{
if (strcmp(moduleName, dep->modulename) == 0)
return true;
}
return false;
}
// decrement reference counter for dependency by module handle
void RPLLoader_RemoveDependency(uint32 handle)
{
for (auto& dep : rplDependencyList)
{
if (dep->coreinitHandle == handle)
{
cemu_assert_debug(dep->referenceCount != 0);
if(dep->referenceCount > 0)
dep->referenceCount--;
return;
}
}
}
uint32 RPLLoader_GetHandleByModuleName(const char* name)
{
// get module name from path
char moduleName[RPL_MODULE_NAME_LENGTH];
_RPLLoader_ExtractModuleNameFromPath(moduleName, name);
// search for existing dependency
for (auto& dep : rplDependencyList)
{
if (strcmp(moduleName, dep->modulename) == 0)
{
cemu_assert_debug(dep->loadAttempted);
if (!dep->isCafeOSModule && !dep->rplLoaderContext)
return RPL_INVALID_HANDLE; // module not found
return dep->coreinitHandle;
}
}
return RPL_INVALID_HANDLE;
}
uint32 RPLLoader_GetMaxTLSModuleIndex()
{
return rplLoader_currentTlsModuleIndex - 1;
}
bool RPLLoader_GetTLSDataByTLSIndex(sint16 tlsModuleIndex, uint8** tlsData, sint32* tlsSize)
{
RPLModule* rplLoaderContext = nullptr;
for (auto& dep : rplDependencyList)
{
if (dep->tlsModuleIndex == tlsModuleIndex)
{
rplLoaderContext = dep->rplLoaderContext;
break;
}
}
if (rplLoaderContext == nullptr)
return false;
cemu_assert(rplLoaderContext->tlsStartAddress != 0);
uint32 tlsDataSize = rplLoaderContext->tlsEndAddress - rplLoaderContext->tlsStartAddress;
cemu_assert_debug(tlsDataSize < 0x10000); // check for suspiciously large TLS area
*tlsData = (uint8*)memory_getPointerFromVirtualOffset(rplLoaderContext->tlsStartAddress);
*tlsSize = tlsDataSize;
return true;
}
bool RPLLoader_LoadFromVirtualPath(RPLDependency* dependency, char* filePath)
{
uint32 rplSize = 0;
uint8* rplData = fsc_extractFile(filePath, &rplSize);
if (rplData)
{
cemuLog_logDebug(LogType::Force, "Loading: {}", filePath);
dependency->rplLoaderContext = RPLLoader_LoadFromMemory(rplData, rplSize, filePath);
free(rplData);
return true;
}
return false;
}
void RPLLoader_LoadDependency(RPLDependency* dependency)
{
dependency->loadAttempted = true;
// check if module is already loaded
for (sint32 i = 0; i < rplModuleCount; i++)
{
if(!boost::iequals(rplModuleList[i]->moduleName2, dependency->modulename))
continue;
dependency->rplLoaderContext = rplModuleList[i];
return;
}
char filePath[RPL_MODULE_PATH_LENGTH];
// check if path is absolute
if (dependency->filepath[0] == '/')
{
strcpy_s(filePath, dependency->filepath);
RPLLoader_LoadFromVirtualPath(dependency, filePath);
return;
}
// attempt to load rpl from code directory of current title
strcpy_s(filePath, "/internal/current_title/code/");
strcat_s(filePath, dependency->filepath);
// except if it is blacklisted
bool isBlacklisted = false;
if (boost::iequals(dependency->filepath, "erreula.rpl"))
{
if (fsc_doesFileExist(filePath))
isBlacklisted = true;
}
if (isBlacklisted)
cemuLog_log(LogType::Force, fmt::format("Game tried to load \"{}\" but it is blacklisted (using Cemu's implementation instead)", filePath));
else if (RPLLoader_LoadFromVirtualPath(dependency, filePath))
return;
// attempt to load rpl from Cemu's /cafeLibs/ directory
if (ActiveSettings::LoadSharedLibrariesEnabled())
{
const auto filePath = ActiveSettings::GetUserDataPath("cafeLibs/{}", dependency->filepath);
auto fileData = FileStream::LoadIntoMemory(filePath);
if (fileData)
{
cemuLog_log(LogType::Force, "Loading RPL: /cafeLibs/{}", dependency->filepath);
dependency->rplLoaderContext = RPLLoader_LoadFromMemory(fileData->data(), fileData->size(),
dependency->filepath);
return;
}
}
}
// loads and unloads modules based on the current dependency list
void RPLLoader_UpdateDependencies()
{
bool repeat = true;
while (repeat)
{
repeat = false;
for(auto idx = 0; idx<rplDependencyList.size(); )
{
auto dependency = rplDependencyList[idx];
// debug_printf("DEP 0x%02x %s\n", dependency->referenceCount, dependency->modulename);
if(dependency->referenceCount == 0)
{
// unload RPLs
// todo - should we let HLE modules know if they are being unloaded?
if (dependency->rplLoaderContext)
{
RPLLoader_UnloadModule(dependency->rplLoaderContext);
dependency->rplLoaderContext = nullptr;
}
// remove from dependency list
rplDependencyList.erase(rplDependencyList.begin()+idx);
idx--;
repeat = true; // unload can effect reference count of other dependencies
break;
}
else if (!dependency->loadAttempted)
{
// load
if (dependency->rplLoaderContext == nullptr)
{
RPLLoader_LoadDependency(dependency);
repeat = true;
idx++;
break;
}
}
idx++;
}
}
RPLLoader_Link();
}
void RPLLoader_SetMainModule(RPLModule* rplLoaderContext)
{
rplLoaderContext->entrypointCalled = true;
rplLoader_mainModule = rplLoaderContext;
}
uint32 RPLLoader_GetMainModuleHandle()
{
for (auto& dep : rplDependencyList)
{
if (dep->rplLoaderContext == rplLoader_mainModule)
{
return dep->coreinitHandle;
}
}
cemu_assert(false);
return 0;
}
RPLModule* RPLLoader_FindModuleByCodeAddr(uint32 addr)
{
for (sint32 i = 0; i < rplModuleCount; i++)
{
uint32 startAddr = rplModuleList[i]->regionMappingBase_text.GetMPTR();
uint32 endAddr = rplModuleList[i]->regionMappingBase_text.GetMPTR() + rplModuleList[i]->regionSize_text;
if (addr >= startAddr && addr < endAddr)
return rplModuleList[i];
}
return nullptr;
}
RPLModule* RPLLoader_FindModuleByDataAddr(uint32 addr)
{
for (sint32 i = 0; i < rplModuleCount; i++)
{
// data
uint32 startAddr = rplModuleList[i]->regionMappingBase_data;
uint32 endAddr = rplModuleList[i]->regionMappingBase_data + rplModuleList[i]->regionSize_data;
if (addr >= startAddr && addr < endAddr)
return rplModuleList[i];
// loaderinfo
startAddr = rplModuleList[i]->regionMappingBase_loaderInfo;
endAddr = rplModuleList[i]->regionMappingBase_loaderInfo + rplModuleList[i]->regionSize_loaderInfo;
if (addr >= startAddr && addr < endAddr)
return rplModuleList[i];
}
return nullptr;
}
RPLModule* RPLLoader_FindModuleByName(std::string module)
{
for (sint32 i = 0; i < rplModuleCount; i++)
{
if (rplModuleList[i]->moduleName2 == module) return rplModuleList[i];
}
return nullptr;
}
void RPLLoader_CallEntrypoints()
{
for (sint32 i = 0; i < rplModuleCount; i++)
{
if( rplModuleList[i]->entrypointCalled )
continue;
uint32 moduleHandle = RPLLoader_GetHandleByModuleName(rplModuleList[i]->moduleName2.c_str());
MPTR entryPoint = RPLLoader_GetModuleEntrypoint(rplModuleList[i]);
PPCCoreCallback(entryPoint, moduleHandle, 1); // 1 -> load, 2 -> unload
rplModuleList[i]->entrypointCalled = true;
}
}
void RPLLoader_NotifyControlPassedToApplication()
{
rplLoader_applicationHasMemoryControl = true;
}
uint32 RPLLoader_FindModuleOrHLEExport(uint32 moduleHandle, bool isData, const char* exportName)
{
// find dependency from handle
RPLModule* rplLoaderContext = nullptr;
RPLDependency* dependency = nullptr;
for (auto& dep : rplDependencyList)
{
if (dep->coreinitHandle == moduleHandle)
{
rplLoaderContext = dep->rplLoaderContext;
dependency = dep;
break;
}
}
uint32 exportResult = 0;
if (rplLoaderContext)
{
exportResult = RPLLoader_FindModuleExport(rplLoaderContext, isData, exportName);
}
else
{
// attempt to find HLE export
if (isData)
{
MPTR weakExportAddr = osLib_getPointer(dependency->modulename, exportName);
cemu_assert_debug(weakExportAddr != 0xFFFFFFFF);
exportResult = weakExportAddr;
}
else
{
exportResult = rpl_mapHLEImport(rplLoaderContext, dependency->modulename, exportName, true);
}
}
return exportResult;
}
uint32 RPLLoader_GetSDA1Base()
{
return rplLoader_sdataAddr;
}
uint32 RPLLoader_GetSDA2Base()
{
return rplLoader_sdata2Addr;
}
RPLModule** RPLLoader_GetModuleList()
{
return rplModuleList;
}
sint32 RPLLoader_GetModuleCount()
{
return rplModuleCount;
}
template<typename TAddr, typename TSize>
class SimpleHeap
{
struct allocEntry_t
{
TAddr start;
TAddr end;
allocEntry_t(TAddr start, TAddr end) : start(start), end(end) {};
};
public:
SimpleHeap(TAddr baseAddress, TSize size) : m_base(baseAddress), m_size(size)
{
}
TAddr alloc(TSize size, TSize alignment)
{
cemu_assert_debug(alignment != 0);
TAddr allocBase = m_base;
allocBase = (allocBase + alignment - 1)&~(alignment-1);
while (true)
{
bool hasCollision = false;
for (auto& itr : list_allocatedEntries)
{
if (allocBase < itr.end && (allocBase + size) >= itr.start)
{
allocBase = itr.end;
allocBase = (allocBase + alignment - 1)&~(alignment - 1);
hasCollision = true;
break;
}
}
if(hasCollision == false)
break;
}
if ((allocBase + size) > (m_base + m_size))
return 0;
list_allocatedEntries.emplace_back(allocBase, allocBase + size);
return allocBase;
}
void free(TAddr addr)
{
for (sint32 i = 0; i < list_allocatedEntries.size(); i++)
{
if (list_allocatedEntries[i].start == addr)
{
list_allocatedEntries.erase(list_allocatedEntries.begin() + i);
return;
}
}
cemu_assert(false);
return;
}
private:
TAddr m_base;
TSize m_size;
std::vector<allocEntry_t> list_allocatedEntries;
};
SimpleHeap<uint32, uint32> heapCodeCaveArea(MEMORY_CODECAVEAREA_ADDR, MEMORY_CODECAVEAREA_SIZE);
MEMPTR<void> RPLLoader_AllocateCodeCaveMem(uint32 alignment, uint32 size)
{
uint32 addr = heapCodeCaveArea.alloc(size, 256);
return MEMPTR<void>{addr};
}
void RPLLoader_ReleaseCodeCaveMem(MEMPTR<void> addr)
{
heapCodeCaveArea.free(addr.GetMPTR());
}
void RPLLoader_ResetState()
{
// unload all RPL modules
while (rplModuleCount > 0)
RPLLoader_UnloadModule(rplModuleList[0]);
rplDependencyList.clear();
// unload all remaining symbols
rplSymbolStorage_unloadAll();
// free all code imports
g_heapTrampolineArea.releaseAll();
list_mappedFunctionImports.clear();
g_map_callableExports.clear();
rplLoader_applicationHasMemoryControl = false;
rplLoader_maxCodeAddress = 0;
rplLoader_currentDataAllocatorAddr = 0x10000000;
rplLoader_currentTLSModuleIndex = 1;
rplLoader_sdataAddr = MPTR_NULL;
rplLoader_sdata2Addr = MPTR_NULL;
rplLoader_mainModule = nullptr;
}
| 82,769
|
C++
|
.cpp
| 2,218
| 34.541028
| 317
| 0.754644
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,032
|
rpl_symbol_storage.cpp
|
cemu-project_Cemu/src/Cafe/OS/RPL/rpl_symbol_storage.cpp
|
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
struct rplSymbolLib_t
{
char* libName;
rplSymbolLib_t* next;
};
struct
{
rplSymbolLib_t* libs;
std::mutex m_symbolStorageMutex;
std::unordered_map<uint32, RPLStoredSymbol*> map_symbolByAddress;
// allocator for strings
char* strAllocatorBlock;
sint32 strAllocatorOffset;
std::vector<void*> list_strAllocatedBlocks;
}rplSymbolStorage = { 0 };
#define STR_ALLOC_BLOCK_SIZE (128*1024) // allocate 128KB blocks at once
char* rplSymbolStorage_allocDupString(const char* str)
{
sint32 len = (sint32)strlen(str);
if (rplSymbolStorage.strAllocatorBlock == nullptr || (rplSymbolStorage.strAllocatorOffset + len + 1) >= STR_ALLOC_BLOCK_SIZE)
{
// allocate new block
rplSymbolStorage.strAllocatorBlock = (char*)malloc(STR_ALLOC_BLOCK_SIZE);
rplSymbolStorage.strAllocatorOffset = 0;
rplSymbolStorage.list_strAllocatedBlocks.emplace_back(rplSymbolStorage.strAllocatorBlock);
}
cemu_assert_debug((rplSymbolStorage.strAllocatorOffset + len + 1) <= STR_ALLOC_BLOCK_SIZE);
char* allocatedStr = rplSymbolStorage.strAllocatorBlock + rplSymbolStorage.strAllocatorOffset;
rplSymbolStorage.strAllocatorOffset += len + 1;
strcpy(allocatedStr, str);
return allocatedStr;
}
char* rplSymbolStorage_storeLibname(const char* libName)
{
if (rplSymbolStorage.libs == NULL)
{
rplSymbolLib_t* libEntry = new rplSymbolLib_t();
libEntry->libName = rplSymbolStorage_allocDupString(libName);
libEntry->next = NULL;
rplSymbolStorage.libs = libEntry;
return libEntry->libName;
}
rplSymbolLib_t* libItr = rplSymbolStorage.libs;
while (libItr)
{
if (boost::iequals(libItr->libName, libName))
return libItr->libName;
// next
libItr = libItr->next;
}
// create new entry
rplSymbolLib_t* libEntry = new rplSymbolLib_t();
libEntry->libName = rplSymbolStorage_allocDupString(libName);
libEntry->next = rplSymbolStorage.libs;
rplSymbolStorage.libs = libEntry;
return libEntry->libName;
}
RPLStoredSymbol* rplSymbolStorage_store(const char* libName, const char* symbolName, MPTR address)
{
std::unique_lock<std::mutex> lck(rplSymbolStorage.m_symbolStorageMutex);
char* libNameStorage = rplSymbolStorage_storeLibname(libName);
char* symbolNameStorage = rplSymbolStorage_allocDupString(symbolName);
RPLStoredSymbol* storedSymbol = new RPLStoredSymbol();
storedSymbol->address = address;
storedSymbol->libName = libNameStorage;
storedSymbol->symbolName = symbolNameStorage;
storedSymbol->flags = 0;
rplSymbolStorage.map_symbolByAddress[address] = storedSymbol;
return storedSymbol;
}
RPLStoredSymbol* rplSymbolStorage_getByAddress(MPTR address)
{
std::unique_lock<std::mutex> lck(rplSymbolStorage.m_symbolStorageMutex);
return rplSymbolStorage.map_symbolByAddress[address];
}
RPLStoredSymbol* rplSymbolStorage_getByClosestAddress(MPTR address)
{
// highly inefficient but doesn't matter for now
std::unique_lock<std::mutex> lck(rplSymbolStorage.m_symbolStorageMutex);
for(uint32 i=0; i<4096; i++)
{
RPLStoredSymbol* symbol = rplSymbolStorage.map_symbolByAddress[address];
if(symbol)
return symbol;
address -= 4;
}
return nullptr;
}
void rplSymbolStorage_remove(RPLStoredSymbol* storedSymbol)
{
std::unique_lock<std::mutex> lck(rplSymbolStorage.m_symbolStorageMutex);
if (rplSymbolStorage.map_symbolByAddress[storedSymbol->address] == storedSymbol)
rplSymbolStorage.map_symbolByAddress[storedSymbol->address] = nullptr;
delete storedSymbol;
}
void rplSymbolStorage_removeRange(MPTR address, sint32 length)
{
while (length > 0)
{
RPLStoredSymbol* symbol = rplSymbolStorage_getByAddress(address);
if (symbol)
rplSymbolStorage_remove(symbol);
address += 4;
length -= 4;
}
}
void rplSymbolStorage_createJumpProxySymbol(MPTR jumpAddress, MPTR destAddress)
{
RPLStoredSymbol* destSymbol = rplSymbolStorage_getByAddress(destAddress);
if (destSymbol)
rplSymbolStorage_store((char*)destSymbol->libName, (char*)destSymbol->symbolName, jumpAddress);
}
std::unordered_map<uint32, RPLStoredSymbol*>& rplSymbolStorage_lockSymbolMap()
{
rplSymbolStorage.m_symbolStorageMutex.lock();
return rplSymbolStorage.map_symbolByAddress;
}
void rplSymbolStorage_unlockSymbolMap()
{
rplSymbolStorage.m_symbolStorageMutex.unlock();
}
void rplSymbolStorage_init()
{
cemu_assert_debug(rplSymbolStorage.map_symbolByAddress.empty());
cemu_assert_debug(rplSymbolStorage.strAllocatorBlock == nullptr);
}
void rplSymbolStorage_unloadAll()
{
// free symbols
for (auto& it : rplSymbolStorage.map_symbolByAddress)
delete it.second;
rplSymbolStorage.map_symbolByAddress.clear();
// free libs
rplSymbolLib_t* lib = rplSymbolStorage.libs;
while (lib)
{
rplSymbolLib_t* next = lib->next;
delete lib;
lib = next;
}
rplSymbolStorage.libs = nullptr;
// free strings
for (auto it : rplSymbolStorage.list_strAllocatedBlocks)
free(it);
rplSymbolStorage.list_strAllocatedBlocks.clear();
rplSymbolStorage.strAllocatorBlock = nullptr;
rplSymbolStorage.strAllocatorOffset = 0;
}
| 5,052
|
C++
|
.cpp
| 150
| 31.333333
| 126
| 0.791692
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,033
|
rpl_debug_symbols.cpp
|
cemu-project_Cemu/src/Cafe/OS/RPL/rpl_debug_symbols.cpp
|
#include "Cafe/OS/RPL/rpl_debug_symbols.h"
std::map<MPTR, rplDebugSymbolBase*> map_DebugSymbols;
void rplDebugSymbol_createComment(MPTR address, const wchar_t* comment)
{
auto new_comment = new rplDebugSymbolComment();
new_comment->type = RplDebugSymbolComment;
new_comment->comment = comment;
map_DebugSymbols[address] = new_comment;
}
rplDebugSymbolBase* rplDebugSymbol_getForAddress(MPTR address)
{
return map_DebugSymbols[address];
}
const std::map<MPTR, rplDebugSymbolBase*>& rplDebugSymbol_getSymbols()
{
return map_DebugSymbols;
}
| 547
|
C++
|
.cpp
| 17
| 30.647059
| 71
| 0.808349
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,034
|
avm.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/avm/avm.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "avm.h"
namespace avm
{
bool AVMIsHDCPAvailable()
{
return true;
}
bool AVMIsHDCPOn()
{
return true;
}
bool AVMGetAnalogContentsProtectionEnable(uint32be* isEnable)
{
*isEnable = 1;
return false;
}
bool AVMIsAnalogContentsProtectionOn()
{
return true;
}
bool AVMSetAnalogContentsProtectionEnable(sint32 newState)
{
return true; // returns 1 (true) if new state was applied successfully?
}
void Initialize()
{
cafeExportRegister("avm", AVMIsHDCPAvailable, LogType::Placeholder);
cafeExportRegister("avm", AVMIsHDCPOn, LogType::Placeholder);
cafeExportRegister("avm", AVMGetAnalogContentsProtectionEnable, LogType::Placeholder);
cafeExportRegister("avm", AVMIsAnalogContentsProtectionOn, LogType::Placeholder);
cafeExportRegister("avm", AVMSetAnalogContentsProtectionEnable, LogType::Placeholder);
}
}
| 893
|
C++
|
.cpp
| 34
| 23.911765
| 88
| 0.794842
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,035
|
erreula.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/erreula/erreula.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "erreula.h"
#include "Cafe/HW/Latte/Renderer/Renderer.h"
#include "util/helpers/helpers.h"
#include <imgui.h>
#include "imgui/imgui_extension.h"
#include <wx/msgdlg.h>
#include "Cafe/OS/libs/coreinit/coreinit_FS.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/vpad/vpad.h"
namespace nn
{
namespace erreula
{
enum class ErrorDialogType : uint32
{
Code = 0,
Text = 1,
TextOneButton = 2,
TextTwoButton = 3
};
static const sint32 FADE_TIME = 80;
enum class ErrEulaState : uint32
{
Hidden = 0,
Appearing = 1,
Visible = 2,
Disappearing = 3
};
enum class ResultType : uint32
{
None = 0,
Finish = 1,
Next = 2,
Jump = 3,
Password = 4
};
struct AppearError
{
AppearError() = default;
AppearError(const AppearError& o)
{
errorType = o.errorType;
screenType = o.screenType;
controllerType = o.controllerType;
holdType = o.holdType;
errorCode = o.errorCode;
framerate = o.framerate;
text = o.text;
button1Text = o.button1Text;
button2Text = o.button2Text;
title = o.title;
drawCursor = o.drawCursor;
}
betype<ErrorDialogType> errorType;
uint32be screenType;
uint32be controllerType;
uint32be holdType;
uint32be errorCode;
uint32be framerate;
MEMPTR<uint16be> text;
MEMPTR<uint16be> button1Text;
MEMPTR<uint16be> button2Text;
MEMPTR<uint16be> title;
uint8 padding[3];
bool drawCursor{};
};
using AppearArg = AppearError;
static_assert(sizeof(AppearError) == 0x2C); // maybe larger
struct HomeNixSignArg_t
{
uint32be framerate;
};
static_assert(sizeof(HomeNixSignArg_t) == 0x4); // maybe larger
struct ControllerInfo_t
{
MEMPTR<VPADStatus_t> vpadStatus;
MEMPTR<KPADStatus_t> kpadStatus[4]; // or 7 now like KPAD_MAX_CONTROLLERS?
};
static_assert(sizeof(ControllerInfo_t) == 0x14); // maybe larger
class ErrEulaInstance
{
public:
enum class BUTTON_SELECTION : uint32
{
NONE = 0xFFFFFFFF,
LEFT = 0,
RIGHT = 1,
};
void Init()
{
m_buttonSelection = BUTTON_SELECTION::NONE;
m_resultCode = -1;
m_resultCodeForLeftButton = 0;
m_resultCodeForRightButton = 0;
SetState(ErrEulaState::Hidden);
}
void DoAppearError(AppearArg* arg)
{
m_buttonSelection = BUTTON_SELECTION::NONE;
m_resultCode = -1;
m_resultCodeForLeftButton = -1;
m_resultCodeForRightButton = -1;
// for standard dialog its 0 and 1?
m_resultCodeForLeftButton = 0;
m_resultCodeForRightButton = 1;
SetState(ErrEulaState::Appearing);
}
void DoDisappearError()
{
if(m_state != ErrEulaState::Visible)
return;
SetState(ErrEulaState::Disappearing);
}
void DoCalc()
{
// appearing and disappearing state will automatically advance after some time
if (m_state == ErrEulaState::Appearing || m_state == ErrEulaState::Disappearing)
{
uint32 elapsedTick = coreinit::OSGetTime() - m_lastStateChange;
if (elapsedTick > coreinit::EspressoTime::ConvertMsToTimerTicks(FADE_TIME))
{
SetState(m_state == ErrEulaState::Appearing ? ErrEulaState::Visible : ErrEulaState::Hidden);
}
}
}
bool IsDecideSelectButtonError() const
{
return m_buttonSelection != BUTTON_SELECTION::NONE;
}
bool IsDecideSelectLeftButtonError() const
{
return m_buttonSelection != BUTTON_SELECTION::LEFT;
}
bool IsDecideSelectRightButtonError() const
{
return m_buttonSelection != BUTTON_SELECTION::RIGHT;
}
void SetButtonSelection(BUTTON_SELECTION selection)
{
cemu_assert_debug(m_buttonSelection == BUTTON_SELECTION::NONE);
m_buttonSelection = selection;
cemu_assert_debug(selection == BUTTON_SELECTION::LEFT || selection == BUTTON_SELECTION::RIGHT);
m_resultCode = selection == BUTTON_SELECTION::LEFT ? m_resultCodeForLeftButton : m_resultCodeForRightButton;
}
ErrEulaState GetState() const
{
return m_state;
}
sint32 GetResultCode() const
{
return m_resultCode;
}
ResultType GetResultType() const
{
if(m_resultCode == -1)
return ResultType::None;
if(m_resultCode < 10)
return ResultType::Finish;
if(m_resultCode >= 9999)
return ResultType::Next;
if(m_resultCode == 40)
return ResultType::Password;
return ResultType::Jump;
}
float GetFadeTransparency() const
{
if(m_state == ErrEulaState::Appearing || m_state == ErrEulaState::Disappearing)
{
uint32 elapsedTick = coreinit::OSGetTime() - m_lastStateChange;
if(m_state == ErrEulaState::Appearing)
return std::min<float>(1.0f, (float)elapsedTick / (float)coreinit::EspressoTime::ConvertMsToTimerTicks(FADE_TIME));
else
return std::max<float>(0.0f, 1.0f - (float)elapsedTick / (float)coreinit::EspressoTime::ConvertMsToTimerTicks(FADE_TIME));
}
return 1.0f;
}
private:
void SetState(ErrEulaState state)
{
m_state = state;
m_lastStateChange = coreinit::OSGetTime();
}
ErrEulaState m_state;
uint32 m_lastStateChange;
/* +0x30 */ betype<sint32> m_resultCode;
/* +0x239C */ betype<BUTTON_SELECTION> m_buttonSelection;
/* +0x23A0 */ betype<sint32> m_resultCodeForLeftButton;
/* +0x23A4 */ betype<sint32> m_resultCodeForRightButton;
};
struct ErrEula_t
{
SysAllocator<coreinit::OSMutex> mutex;
uint32 regionType;
uint32 langType;
MEMPTR<coreinit::FSClient_t> fsClient;
std::unique_ptr<ErrEulaInstance> errEulaInstance;
AppearError currentDialog;
bool homeNixSignVisible;
} g_errEula = {};
std::wstring GetText(uint16be* text)
{
std::wstringstream result;
while(*text != 0)
{
auto c = (uint16)*text;
result << static_cast<wchar_t>(c);
text++;
}
return result.str();
}
void ErrEulaCreate(void* workmem, uint32 regionType, uint32 langType, coreinit::FSClient_t* fsClient)
{
coreinit::OSLockMutex(&g_errEula.mutex);
g_errEula.regionType = regionType;
g_errEula.langType = langType;
g_errEula.fsClient = fsClient;
cemu_assert_debug(!g_errEula.errEulaInstance);
g_errEula.errEulaInstance = std::make_unique<ErrEulaInstance>();
g_errEula.errEulaInstance->Init();
coreinit::OSUnlockMutex(&g_errEula.mutex);
}
void ErrEulaDestroy()
{
g_errEula.errEulaInstance.reset();
}
// check if any dialog button was selected
bool IsDecideSelectButtonError()
{
if(!g_errEula.errEulaInstance)
return false;
return g_errEula.errEulaInstance->IsDecideSelectButtonError();
}
// check if left dialog button was selected
bool IsDecideSelectLeftButtonError()
{
if(!g_errEula.errEulaInstance)
return false;
return g_errEula.errEulaInstance->IsDecideSelectLeftButtonError();
}
// check if right dialog button was selected
bool IsDecideSelectRightButtonError()
{
if(!g_errEula.errEulaInstance)
return false;
return g_errEula.errEulaInstance->IsDecideSelectRightButtonError();
}
sint32 GetResultCode()
{
if(!g_errEula.errEulaInstance)
return -1;
return g_errEula.errEulaInstance->GetResultCode();
}
ResultType GetResultType()
{
if(!g_errEula.errEulaInstance)
return ResultType::None;
return g_errEula.errEulaInstance->GetResultType();
}
void export_AppearHomeNixSign(PPCInterpreter_t* hCPU)
{
g_errEula.homeNixSignVisible = TRUE;
osLib_returnFromFunction(hCPU, 0);
}
void ErrEulaAppearError(AppearArg* arg)
{
g_errEula.currentDialog = *arg;
if(g_errEula.errEulaInstance)
g_errEula.errEulaInstance->DoAppearError(arg);
}
void ErrEulaDisappearError()
{
if(g_errEula.errEulaInstance)
g_errEula.errEulaInstance->DoDisappearError();
}
ErrEulaState ErrEulaGetStateErrorViewer()
{
if(!g_errEula.errEulaInstance)
return ErrEulaState::Hidden;
return g_errEula.errEulaInstance->GetState();
}
void export_ChangeLang(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(langType, 0);
g_errEula.langType = langType;
osLib_returnFromFunction(hCPU, 0);
}
void export_IsAppearHomeNixSign(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction(hCPU, g_errEula.homeNixSignVisible);
}
void export_DisappearHomeNixSign(PPCInterpreter_t* hCPU)
{
g_errEula.homeNixSignVisible = FALSE;
osLib_returnFromFunction(hCPU, 0);
}
void ErrEulaCalc(ControllerInfo_t* controllerInfo)
{
if(g_errEula.errEulaInstance)
g_errEula.errEulaInstance->DoCalc();
}
void render(bool mainWindow)
{
if(!g_errEula.errEulaInstance)
return;
if(g_errEula.errEulaInstance->GetState() != ErrEulaState::Visible && g_errEula.errEulaInstance->GetState() != ErrEulaState::Appearing && g_errEula.errEulaInstance->GetState() != ErrEulaState::Disappearing)
return;
const AppearError& appearArg = g_errEula.currentDialog;
std::string text;
const uint32 errorCode = (uint32)appearArg.errorCode;
if (errorCode != 0)
{
const uint32 errorCodeHigh = errorCode / 10000;
const uint32 errorCodeLow = errorCode % 10000;
text = fmt::format("Error-Code: {:03}-{:04}\n", errorCodeHigh, errorCodeLow);
}
auto font = ImGui_GetFont(32.0f);
if (!font)
return;
const auto kPopupFlags = ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings;
auto& io = ImGui::GetIO();
ImVec2 position = { io.DisplaySize.x / 2.0f, io.DisplaySize.y / 2.0f };
ImVec2 pivot = { 0.5f, 0.5f };
ImGui::SetNextWindowPos(position, ImGuiCond_Always, pivot);
ImGui::SetNextWindowBgAlpha(0.9f);
ImGui::PushFont(font);
std::string title;
if (appearArg.title)
title = boost::nowide::narrow(GetText(appearArg.title.GetPtr()));
if (title.empty()) // ImGui doesn't allow empty titles, so set one if appearArg.title is not set or empty
title = "ErrEula";
float fadeTransparency = 1.0f;
if (g_errEula.errEulaInstance->GetState() == ErrEulaState::Appearing || g_errEula.errEulaInstance->GetState() == ErrEulaState::Disappearing)
{
fadeTransparency = g_errEula.errEulaInstance->GetFadeTransparency();
}
float originalAlpha = ImGui::GetStyle().Alpha;
ImGui::GetStyle().Alpha = fadeTransparency;
ImGui::SetNextWindowBgAlpha(0.9f * fadeTransparency);
if (ImGui::Begin(title.c_str(), nullptr, kPopupFlags))
{
const float startx = ImGui::GetWindowSize().x / 2.0f;
bool hasLeftButtonPressed = false, hasRightButtonPressed = false;
switch (appearArg.errorType)
{
default:
{
// TODO layout based on error code
ImGui::TextUnformatted(text.c_str(), text.c_str() + text.size());
ImGui::Spacing();
ImGui::SetCursorPosX(startx - 50);
hasLeftButtonPressed = ImGui::Button("OK", {100, 0});
break;
}
case ErrorDialogType::Text:
{
std::string txtTmp = "Unknown Error";
if (appearArg.text)
txtTmp = boost::nowide::narrow(GetText(appearArg.text.GetPtr()));
text += txtTmp;
ImGui::TextUnformatted(text.c_str(), text.c_str() + text.size());
ImGui::Spacing();
ImGui::SetCursorPosX(startx - 50);
hasLeftButtonPressed = ImGui::Button("OK", { 100, 0 });
break;
}
case ErrorDialogType::TextOneButton:
{
std::string txtTmp = "Unknown Error";
if (appearArg.text)
txtTmp = boost::nowide::narrow(GetText(appearArg.text.GetPtr()));
text += txtTmp;
ImGui::TextUnformatted(text.c_str(), text.c_str() + text.size());
ImGui::Spacing();
std::string button1 = "Yes";
if (appearArg.button1Text)
button1 = boost::nowide::narrow(GetText(appearArg.button1Text.GetPtr()));
float width = std::max(100.0f, ImGui::CalcTextSize(button1.c_str()).x + 10.0f);
ImGui::SetCursorPosX(startx - (width / 2.0f));
hasLeftButtonPressed = ImGui::Button(button1.c_str(), { width, 0 });
break;
}
case ErrorDialogType::TextTwoButton:
{
std::string txtTmp = "Unknown Error";
if (appearArg.text)
txtTmp = boost::nowide::narrow(GetText(appearArg.text.GetPtr()));
text += txtTmp;
ImGui::TextUnformatted(text.c_str(), text.c_str() + text.size());
ImGui::Spacing();
std::string button1 = "Yes";
if (appearArg.button1Text)
button1 = boost::nowide::narrow(GetText(appearArg.button1Text.GetPtr()));
std::string button2 = "No";
if (appearArg.button2Text)
button2 = boost::nowide::narrow(GetText(appearArg.button2Text.GetPtr()));
float width1 = std::max(100.0f, ImGui::CalcTextSize(button1.c_str()).x + 10.0f);
float width2 = std::max(100.0f, ImGui::CalcTextSize(button2.c_str()).x + 10.0f);
ImGui::SetCursorPosX(startx - (width1 / 2.0f) - (width2 / 2.0f) - 10);
hasLeftButtonPressed = ImGui::Button(button1.c_str(), { width1, 0 });
ImGui::SameLine();
hasRightButtonPressed = ImGui::Button(button2.c_str(), { width2, 0 });
break;
}
}
if (!g_errEula.errEulaInstance->IsDecideSelectButtonError())
{
if (hasLeftButtonPressed)
g_errEula.errEulaInstance->SetButtonSelection(ErrEulaInstance::BUTTON_SELECTION::LEFT);
if (hasRightButtonPressed)
g_errEula.errEulaInstance->SetButtonSelection(ErrEulaInstance::BUTTON_SELECTION::RIGHT);
}
}
ImGui::End();
ImGui::PopFont();
ImGui::GetStyle().Alpha = originalAlpha;
}
void load()
{
g_errEula.errEulaInstance.reset();
OSInitMutexEx(&g_errEula.mutex, nullptr);
cafeExportRegisterFunc(ErrEulaCreate, "erreula", "ErrEulaCreate__3RplFPUcQ3_2nn7erreula10RegionTypeQ3_2nn7erreula8LangTypeP8FSClient", LogType::Placeholder);
cafeExportRegisterFunc(ErrEulaDestroy, "erreula", "ErrEulaDestroy__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(IsDecideSelectButtonError, "erreula", "ErrEulaIsDecideSelectButtonError__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(IsDecideSelectLeftButtonError, "erreula", "ErrEulaIsDecideSelectLeftButtonError__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(IsDecideSelectRightButtonError, "erreula", "ErrEulaIsDecideSelectRightButtonError__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(GetResultCode, "erreula", "ErrEulaGetResultCode__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(GetResultType, "erreula", "ErrEulaGetResultType__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(ErrEulaAppearError, "erreula", "ErrEulaAppearError__3RplFRCQ3_2nn7erreula9AppearArg", LogType::Placeholder);
cafeExportRegisterFunc(ErrEulaDisappearError, "erreula", "ErrEulaDisappearError__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(ErrEulaGetStateErrorViewer, "erreula", "ErrEulaGetStateErrorViewer__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(ErrEulaCalc, "erreula", "ErrEulaCalc__3RplFRCQ3_2nn7erreula14ControllerInfo", LogType::Placeholder);
osLib_addFunction("erreula", "ErrEulaAppearHomeNixSign__3RplFRCQ3_2nn7erreula14HomeNixSignArg", export_AppearHomeNixSign);
osLib_addFunction("erreula", "ErrEulaChangeLang__3RplFQ3_2nn7erreula8LangType", export_ChangeLang);
osLib_addFunction("erreula", "ErrEulaIsAppearHomeNixSign__3RplFv", export_IsAppearHomeNixSign);
osLib_addFunction("erreula", "ErrEulaDisappearHomeNixSign__3RplFv", export_DisappearHomeNixSign);
}
}
}
| 14,994
|
C++
|
.cpp
| 439
| 30.624146
| 211
| 0.739621
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,036
|
nn_ccr.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_ccr/nn_ccr.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "nn_ccr.h"
namespace nn::ccr
{
sint32 CCRSysCaffeineBootCheck()
{
cemuLog_logDebug(LogType::Force, "CCRSysCaffeineBootCheck()");
return -1;
}
void Initialize()
{
cafeExportRegister("nn_ccr", CCRSysCaffeineBootCheck, LogType::Placeholder);
}
}
| 303
|
C++
|
.cpp
| 14
| 19.642857
| 78
| 0.763066
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,037
|
zlib125.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/zlib125/zlib125.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "zlib125.h"
#include "zlib.h"
typedef struct {
/* +0x00 */ MEMPTR<uint8> next_in; /* next input byte */
/* +0x04 */ uint32be avail_in; /* number of bytes available at next_in */
/* +0x08 */ uint32be total_in; /* total number of input bytes read so far */
/* +0x0C */ MEMPTR<uint8> next_out; /* next output byte should be put there */
/* +0x10 */ uint32be avail_out; /* remaining free space at next_out */
/* +0x14 */ uint32be total_out; /* total number of bytes output so far */
/* +0x18 */ MEMPTR<char> msg; /* last error message, NULL if no error */
/* +0x1C */ MEMPTR<void> state; /* not visible by applications */
/* +0x20 */ MEMPTR<void> zalloc; /* used to allocate the internal state */
/* +0x24 */ MEMPTR<void> zfree; /* used to free the internal state */
/* +0x28 */ MEMPTR<void> opaque; /* private data object passed to zalloc and zfree */
/* +0x2C */ uint32be data_type; /* best guess about the data type: binary or text */
/* +0x30 */ uint32be adler; /* adler32 value of the uncompressed data */
/* +0x34 */ uint32be reserved; /* reserved for future use */
}z_stream_ppc2;
static_assert(sizeof(z_stream_ppc2) == 0x38);
voidpf zcallocWrapper(voidpf opaque, uInt items, uInt size)
{
z_stream_ppc2* zstream = (z_stream_ppc2*)opaque;
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->gpr[3] = zstream->opaque.GetMPTR();
hCPU->gpr[4] = items;
hCPU->gpr[5] = size;
PPCCore_executeCallbackInternal(zstream->zalloc.GetMPTR());
memset(memory_getPointerFromVirtualOffset(hCPU->gpr[3]), 0, items*size);
return memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
}
void zcfreeWrapper(voidpf opaque, voidpf baseIndex)
{
z_stream_ppc2* zstream = (z_stream_ppc2*)opaque;
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->gpr[3] = zstream->opaque.GetMPTR();
hCPU->gpr[4] = memory_getVirtualOffsetFromPointer(baseIndex);
PPCCore_executeCallbackInternal(zstream->zfree.GetMPTR());
return;
}
void zlib125_zcalloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(opaque, 0);
ppcDefineParamU32(items, 1);
ppcDefineParamU32(size, 2);
hCPU->gpr[3] = items*size;
hCPU->instructionPointer = gCoreinitData->MEMAllocFromDefaultHeap.GetMPTR();
}
void zlib125_zcfree(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(opaque, 0);
ppcDefineParamMPTR(baseIndex, 1);
hCPU->gpr[3] = baseIndex;
hCPU->instructionPointer = gCoreinitData->MEMFreeToDefaultHeap.GetMPTR();
}
void zlib125_setupHostZStream(z_stream_ppc2* input, z_stream* output, bool fixInternalStreamPtr = true)
{
output->next_in = input->next_in.GetPtr();
output->avail_in = (uint32)input->avail_in;
output->total_in = (uint32)input->total_in;
output->next_out = input->next_out.GetPtr();
output->avail_out = (uint32)input->avail_out;
output->total_out = (uint32)input->total_out;
output->msg = input->msg.GetPtr();
output->state = (internal_state*)input->state.GetPtr();
output->zalloc = zcallocWrapper;
output->zfree = zcfreeWrapper;
output->opaque = (void*)input;
output->data_type = input->data_type;
output->adler = (uint32)input->adler;
output->reserved = (uint32)input->reserved;
if (fixInternalStreamPtr && output->state)
{
// in newer zLib versions the internal state has a pointer to the stream at the beginning, we have to update it manually
// todo - find better solution
(*(void**)(output->state)) = output;
}
}
void zlib125_setupUpdateZStream(z_stream* input, z_stream_ppc2* output)
{
output->next_in = input->next_in;
output->avail_in = (uint32)input->avail_in;
output->total_in = (uint32)input->total_in;
output->next_out = input->next_out;
output->avail_out = (uint32)input->avail_out;
output->total_out = (uint32)input->total_out;
output->msg = input->msg;
output->state = (void*)input->state;
output->data_type = input->data_type;
output->adler = input->adler;
output->reserved = input->reserved;
}
void zlib125Export_inflateInit_(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamStr(version, 1);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs, false);
// setup internal memory allocator if requested
if (zstream->zalloc == nullptr)
zstream->zalloc = PPCInterpreter_makeCallableExportDepr(zlib125_zcalloc);
if (zstream->zfree == nullptr)
zstream->zfree = PPCInterpreter_makeCallableExportDepr(zlib125_zcfree);
sint32 r = inflateInit_(&hzs, version, sizeof(z_stream));
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_inflateInit2_(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(windowBits, 1);
ppcDefineParamStr(version, 2);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs, false);
// setup internal memory allocator if requested
if (zstream->zalloc == nullptr)
zstream->zalloc = PPCInterpreter_makeCallableExportDepr(zlib125_zcalloc);
if (zstream->zfree == nullptr)
zstream->zfree = PPCInterpreter_makeCallableExportDepr(zlib125_zcfree);
sint32 r = inflateInit2_(&hzs, windowBits, version, sizeof(z_stream));
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_inflate(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(flushParam, 1);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = inflate(&hzs, flushParam);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_inflateEnd(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = inflateEnd(&hzs);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_inflateReset(PPCInterpreter_t* hCPU)
{
debug_printf("inflateReset(0x%08x)\n", hCPU->gpr[3]);
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = inflateReset(&hzs);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_inflateReset2(PPCInterpreter_t* hCPU)
{
debug_printf("inflateReset2(0x%08x,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(windowBits, 1);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = inflateReset2(&hzs, windowBits);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_deflateInit_(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(level, 1);
ppcDefineParamStr(version, 2);
ppcDefineParamS32(streamsize, 3);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs, false);
// setup internal memory allocator if requested
if (zstream->zalloc == nullptr)
zstream->zalloc = PPCInterpreter_makeCallableExportDepr(zlib125_zcalloc);
if (zstream->zfree == nullptr)
zstream->zfree = PPCInterpreter_makeCallableExportDepr(zlib125_zcfree);
if (streamsize != sizeof(z_stream_ppc2))
assert_dbg();
sint32 r = deflateInit_(&hzs, level, version, sizeof(z_stream));
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_deflateInit2_(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(level, 1);
ppcDefineParamS32(method, 2);
ppcDefineParamS32(windowBits, 3);
ppcDefineParamS32(memLevel, 4);
ppcDefineParamS32(strategy, 5);
ppcDefineParamStr(version, 6);
ppcDefineParamS32(streamsize, 7);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs, false);
// setup internal memory allocator if requested
if (zstream->zalloc == nullptr)
zstream->zalloc = PPCInterpreter_makeCallableExportDepr(zlib125_zcalloc);
if (zstream->zfree == nullptr)
zstream->zfree = PPCInterpreter_makeCallableExportDepr(zlib125_zcfree);
// workaround for Splatoon (it allocates a too small buffer for our version of zLib and its zalloc returns NULL)
zstream->zalloc = PPCInterpreter_makeCallableExportDepr(zlib125_zcalloc);
zstream->zfree = PPCInterpreter_makeCallableExportDepr(zlib125_zcfree);
if (streamsize != sizeof(z_stream_ppc2))
assert_dbg();
sint32 r = deflateInit2_(&hzs, level, method, windowBits, memLevel, strategy, version, sizeof(z_stream));
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_deflateBound(PPCInterpreter_t* hCPU)
{
debug_printf("deflateBound(0x%08x,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(sourceLen, 1);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = deflateBound(&hzs, sourceLen);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_deflate(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
ppcDefineParamS32(flushParam, 1);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = deflate(&hzs, flushParam);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_deflateEnd(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(zstream, z_stream_ppc2, 0);
z_stream hzs;
zlib125_setupHostZStream(zstream, &hzs);
sint32 r = deflateEnd(&hzs);
zlib125_setupUpdateZStream(&hzs, zstream);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_uncompress(PPCInterpreter_t* hCPU)
{
// Bytef * dest, uLongf * destLen, const Bytef * source, uLong sourceLen
uint8* memDst = memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint8* memSrc = memory_getPointerFromVirtualOffset(hCPU->gpr[5]);
uint32* pDestLenBE = (uint32*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
uint32 sourceLen = hCPU->gpr[6];
uLong destLen = _swapEndianU32(*pDestLenBE);
sint32 r = uncompress(memDst, &destLen, memSrc, sourceLen);
*pDestLenBE = _swapEndianU32(destLen);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_compress(PPCInterpreter_t* hCPU)
{
// Bytef* dest, uLongf* destLen, const Bytef* source, uLong sourceLen
uint8* memDst = memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint8* memSrc = memory_getPointerFromVirtualOffset(hCPU->gpr[5]);
uint32* pDestLenBE = (uint32*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
uint32 sourceLen = hCPU->gpr[6];
uLong destLen = _swapEndianU32(*pDestLenBE);
sint32 r = compress(memDst, &destLen, memSrc, sourceLen);
*pDestLenBE = _swapEndianU32(destLen);
osLib_returnFromFunction(hCPU, r);
}
void zlib125Export_crc32(PPCInterpreter_t* hCPU)
{
uint32 crc = hCPU->gpr[3];
uint8* buf = (uint8*)memory_getPointerFromVirtualOffsetAllowNull(hCPU->gpr[4]);
uint32 len = hCPU->gpr[5];
uint32 crcResult = crc32(crc, buf, len);
osLib_returnFromFunction(hCPU, crcResult);
}
void zlib125Export_compressBound(PPCInterpreter_t* hCPU)
{
uint32 result = compressBound(hCPU->gpr[3]);
osLib_returnFromFunction(hCPU, result);
}
namespace zlib
{
void load()
{
// zlib125
osLib_addFunction("zlib125", "inflateInit2_", zlib125Export_inflateInit2_);
osLib_addFunction("zlib125", "inflateInit_", zlib125Export_inflateInit_);
osLib_addFunction("zlib125", "inflateEnd", zlib125Export_inflateEnd);
osLib_addFunction("zlib125", "inflate", zlib125Export_inflate);
osLib_addFunction("zlib125", "inflateReset", zlib125Export_inflateReset);
osLib_addFunction("zlib125", "inflateReset2", zlib125Export_inflateReset2);
osLib_addFunction("zlib125", "deflateInit_", zlib125Export_deflateInit_);
osLib_addFunction("zlib125", "deflateInit2_", zlib125Export_deflateInit2_);
osLib_addFunction("zlib125", "deflateBound", zlib125Export_deflateBound);
osLib_addFunction("zlib125", "deflate", zlib125Export_deflate);
osLib_addFunction("zlib125", "deflateEnd", zlib125Export_deflateEnd);
osLib_addFunction("zlib125", "uncompress", zlib125Export_uncompress);
osLib_addFunction("zlib125", "compress", zlib125Export_compress);
osLib_addFunction("zlib125", "crc32", zlib125Export_crc32);
osLib_addFunction("zlib125", "compressBound", zlib125Export_compressBound);
}
}
| 12,251
|
C++
|
.cpp
| 297
| 39.097643
| 122
| 0.76302
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,038
|
nlibnss.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nlibnss/nlibnss.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "nlibnss.h"
namespace nlibnss
{
int NSSExportDeviceCertChain(uint8* uknPtr1, uint32be* uknLength1, uint8* uknPtr2, uint32be* uknLength2, uint32 uknR7, uint32 uknR8)
{
cemuLog_logDebug(LogType::Force, "NSSExportDeviceCertChain called but not implemented");
cemu_assert_debug(false);
// uknR3 = pointer (can be null, in which case only length is written)
// uknR4 = length
// uknR5 = pointer2
// uknR6 = length2
// uknR7 = some integer
// uknR8 = ???
*uknLength1 = 0x100;
*uknLength2 = 0x100;
return 0; // failed
}
int NSSSignatureGetSignatureLength()
{
// parameters are unknown
cemu_assert_debug(false);
return 0x1C; // signature length
}
void load()
{
cafeExportRegister("nlibnss", NSSSignatureGetSignatureLength, LogType::Placeholder);
cafeExportRegister("nlibnss", NSSExportDeviceCertChain, LogType::Placeholder);
}
}
| 915
|
C++
|
.cpp
| 30
| 27.9
| 133
| 0.750569
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,039
|
nn_uds.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_uds/nn_uds.cpp
|
#include "Cafe/OS/common/OSCommon.h"
typedef struct
{
uint32 reserved;
}udsWorkspace_t;
udsWorkspace_t* udsWorkspace = NULL;
void nnUdsExport___sti___11_uds_Api_cpp_f5d9abb2(PPCInterpreter_t* hCPU)
{
debug_printf("__sti___11_uds_Api_cpp_f5d9abb2()\n");
if( udsWorkspace == NULL )
udsWorkspace = (udsWorkspace_t*)memory_getPointerFromVirtualOffset(coreinit_allocFromSysArea(32, 32));
osLib_returnFromFunction(hCPU, memory_getVirtualOffsetFromPointer(udsWorkspace));
}
/*
* Load UDS functions
*/
void nnUds_load()
{
osLib_addFunction("nn_uds", "__sti___11_uds_Api_cpp_f5d9abb2", nnUdsExport___sti___11_uds_Api_cpp_f5d9abb2);
}
| 640
|
C++
|
.cpp
| 20
| 30.25
| 109
| 0.75974
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,040
|
drmapp.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/drmapp/drmapp.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "drmapp.h"
namespace drmapp
{
uint32 NupChkIsFinished(uint32 ukn)
{
cemuLog_logDebug(LogType::Force, "drmapp.NupChkIsFinished() - placeholder");
return 1;
}
uint32 PatchChkIsFinished()
{
cemuLog_logDebug(LogType::Force, "drmapp.PatchChkIsFinished() - placeholder");
return 1;
}
uint32 AocChkIsFinished()
{
cemuLog_logDebug(LogType::Force, "drmapp.AocChkIsFinished() - placeholder");
return 1;
}
uint32 TicketChkIsFinished()
{
cemuLog_logDebug(LogType::Force, "drmapp.TicketChkIsFinished__3RplFv() - placeholder");
return 1;
}
void Initialize()
{
cafeExportRegisterFunc(NupChkIsFinished, "drmapp", "NupChkIsFinished__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(PatchChkIsFinished, "drmapp", "PatchChkIsFinished__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(AocChkIsFinished, "drmapp", "AocChkIsFinished__3RplFv", LogType::Placeholder);
cafeExportRegisterFunc(TicketChkIsFinished, "drmapp", "TicketChkIsFinished__3RplFv", LogType::Placeholder);
}
} // namespace drmapp
| 1,078
|
C++
|
.cpp
| 32
| 31.3125
| 109
| 0.78098
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,041
|
TCL.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/TCL/TCL.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/TCL/TCL.h"
namespace TCL
{
enum class TCL_SUBMISSION_FLAG : uint32
{
SURFACE_SYNC = 0x400000, // submit surface sync packet before cmd
TRIGGER_INTERRUPT = 0x200000, // probably
UKN_20000000 = 0x20000000,
};
int TCLSubmitToRing(uint32be* cmd, uint32 cmdLen, uint32be* controlFlags, uint64* submissionTimestamp)
{
// todo - figure out all the bits of *controlFlags
// if submissionTimestamp != nullptr then set it to the timestamp of the submission. Note: We should make sure that uint64's are written atomically by the GPU command processor
cemu_assert_debug(false);
return 0;
}
void Initialize()
{
cafeExportRegister("TCL", TCLSubmitToRing, LogType::Placeholder);
}
}
| 759
|
C++
|
.cpp
| 22
| 32.090909
| 178
| 0.764706
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,042
|
nn_ndm.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_ndm/nn_ndm.cpp
|
#include "nn_ndm.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/nn_common.h"
namespace nn
{
namespace ndm
{
enum class DAEMON_NAME : uint32
{
UKN_0, // Boss related?
UKN_1, // Download Manager? scope.rpx (Download Manager app) expects this to have status 0 or 1. Otherwise it will display downloads as disabled
UKN_2,
};
enum class DAEMON_STATUS : uint32
{
STATUS_UKN_0 = 0, // probably: Ready or initializing?
RUNNING = 1, // most likely running, but not 100% sure
STATUS_UKN_2 = 2, // probably: ready, starting or something like that?
SUSPENDED = 3,
};
constexpr size_t NUM_DAEMONS = 3;
DAEMON_STATUS s_daemonStatus[NUM_DAEMONS];
uint32 s_initializeRefCount;
uint32 Initialize()
{
s_initializeRefCount++;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NDM, 0);
}
uint32 IsInitialized()
{
return s_initializeRefCount != 0 ? 1 : 0;
}
uint32 Finalize()
{
if(s_initializeRefCount == 0)
return BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NDM, 0);
s_initializeRefCount++;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NDM, 0);
}
uint32 GetDaemonStatus(betype<DAEMON_STATUS>* statusOut, DAEMON_NAME daemonName)
{
size_t daemonIndex = (size_t)daemonName;
if(daemonIndex >= NUM_DAEMONS)
return BUILD_NN_RESULT(NN_RESULT_LEVEL_STATUS, NN_RESULT_MODULE_NN_NDM, 0);
*statusOut = s_daemonStatus[daemonIndex];
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NDM, 0);
}
uint32 SuspendDaemons(uint32 daemonNameBitmask)
{
for(size_t i=0; i<NUM_DAEMONS; i++)
{
if(daemonNameBitmask & (1 << i))
s_daemonStatus[i] = DAEMON_STATUS::SUSPENDED;
}
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NDM, 0);
}
uint32 ResumeDaemons(uint32 daemonNameBitmask)
{
for(size_t i=0; i<NUM_DAEMONS; i++)
{
if(daemonNameBitmask & (1 << i))
s_daemonStatus[i] = DAEMON_STATUS::RUNNING;
}
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_NDM, 0);
}
void load()
{
for(size_t i=0; i<NUM_DAEMONS; i++)
s_daemonStatus[i] = DAEMON_STATUS::RUNNING;
s_initializeRefCount = 0;
cafeExportRegisterFunc(Initialize, "nn_ndm", "Initialize__Q2_2nn3ndmFv", LogType::Placeholder);
cafeExportRegisterFunc(Finalize, "nn_ndm", "Finalize__Q2_2nn3ndmFv", LogType::Placeholder);
cafeExportRegisterFunc(IsInitialized, "nn_ndm", "IsInitialized__Q2_2nn3ndmFv", LogType::Placeholder);
cafeExportRegisterFunc(GetDaemonStatus, "nn_ndm", "GetDaemonStatus__Q2_2nn3ndmFPQ4_2nn3ndm7IDaemon6StatusQ4_2nn3ndm4Cafe10DaemonName", LogType::Placeholder);
cafeExportRegisterFunc(SuspendDaemons, "nn_ndm", "SuspendDaemons__Q2_2nn3ndmFUi", LogType::Placeholder);
cafeExportRegisterFunc(ResumeDaemons, "nn_ndm", "ResumeDaemons__Q2_2nn3ndmFUi", LogType::Placeholder);
}
}
}
| 2,931
|
C++
|
.cpp
| 79
| 33.518987
| 160
| 0.723592
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,043
|
nn_act.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_act/nn_act.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/IOSU/legacy/iosu_act.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
#include "nn_act.h"
#include "Cafe/OS/libs/nn_common.h"
#include "Cafe/CafeSystem.h"
#include "Common/CafeString.h"
sint32 numAccounts = 1;
#define actPrepareRequest() \
StackAllocator<iosuActCemuRequest_t> _buf_actRequest; \
StackAllocator<ioBufferVector_t> _buf_bufferVector; \
iosuActCemuRequest_t* actRequest = _buf_actRequest.GetPointer(); \
ioBufferVector_t* actBufferVector = _buf_bufferVector.GetPointer(); \
memset(actRequest, 0, sizeof(iosuActCemuRequest_t)); \
memset(actBufferVector, 0, sizeof(ioBufferVector_t)); \
actBufferVector->buffer = (uint8*)actRequest;
#define actPrepareRequest2() \
StackAllocator<iosuActCemuRequest_t> _buf_actRequest; \
iosuActCemuRequest_t* actRequest = _buf_actRequest.GetPointer(); \
memset(actRequest, 0, sizeof(iosuActCemuRequest_t));
uint32 getNNReturnCode(uint32 iosError, iosuActCemuRequest_t* actRequest)
{
if ((iosError & 0x80000000) != 0)
return iosError;
return actRequest->returnCode;
}
uint32 _doCemuActRequest(iosuActCemuRequest_t* actRequest)
{
StackAllocator<ioBufferVector_t> _buf_bufferVector;
ioBufferVector_t* actBufferVector = _buf_bufferVector.GetPointer();
memset(actBufferVector, 0, sizeof(ioBufferVector_t));
actBufferVector->buffer = (uint8*)actRequest;
uint32 ioctlResult = __depr__IOS_Ioctlv(IOS_DEVICE_ACT, IOSU_ACT_REQUEST_CEMU, 1, 1, actBufferVector);
return getNNReturnCode(ioctlResult, actRequest);
}
namespace nn
{
namespace act
{
uint32 GetPersistentIdEx(uint8 slot)
{
actPrepareRequest();
actRequest->requestCode = IOSU_ARC_PERSISTENTID;
actRequest->accountSlot = slot;
__depr__IOS_Ioctlv(IOS_DEVICE_ACT, IOSU_ACT_REQUEST_CEMU, 1, 1, actBufferVector);
return actRequest->resultU32.u32;
}
uint32 GetMiiEx(void* miiData, uint8 slot)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_MIIDATA;
actRequest->accountSlot = slot;
uint32 result = _doCemuActRequest(actRequest);
memcpy(miiData, actRequest->resultBinary.binBuffer, MII_FFL_STORAGE_SIZE);
return result;
}
uint32 GetUuidEx(uint8* uuid, uint8 slot, sint32 name)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_UUID;
actRequest->accountSlot = slot;
actRequest->uuidName = name;
uint32 result = _doCemuActRequest(actRequest);
memcpy(uuid, actRequest->resultBinary.binBuffer, 16);
return result;
}
uint32 GetSimpleAddressIdEx(uint32be* simpleAddressId, uint8 slot)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_SIMPLEADDRESS;
actRequest->accountSlot = slot;
uint32 result = _doCemuActRequest(actRequest);
*simpleAddressId = actRequest->resultU32.u32;
return result;
}
uint32 GetTransferableIdEx(uint64* transferableId, uint32 unique, uint8 slot)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_TRANSFERABLEID;
actRequest->accountSlot = slot;
actRequest->unique = unique;
uint32 result = _doCemuActRequest(actRequest);
*transferableId = _swapEndianU64(actRequest->resultU64.u64);
return result;
}
uint32 AcquireIndependentServiceToken(independentServiceToken_t* token, const char* clientId, uint32 cacheDurationInSeconds)
{
memset(token, 0, sizeof(independentServiceToken_t));
actPrepareRequest();
actRequest->accountSlot = iosu::act::ACT_SLOT_CURRENT;
actRequest->requestCode = IOSU_ARC_ACQUIREINDEPENDENTTOKEN;
actRequest->titleId = CafeSystem::GetForegroundTitleId();
actRequest->titleVersion = CafeSystem::GetForegroundTitleVersion();
actRequest->expiresIn = cacheDurationInSeconds;
strcpy(actRequest->clientId, clientId);
uint32 resultCode = __depr__IOS_Ioctlv(IOS_DEVICE_ACT, IOSU_ACT_REQUEST_CEMU, 1, 1, actBufferVector);
memcpy(token, actRequest->resultBinary.binBuffer, sizeof(independentServiceToken_t));
return getNNReturnCode(resultCode, actRequest);
}
sint64 GetUtcOffset()
{
return ((ppcCyclesSince2000 / ESPRESSO_CORE_CLOCK) - (ppcCyclesSince2000_UTC / ESPRESSO_CORE_CLOCK)) * 1'000'000;
}
sint32 GetUtcOffsetEx(sint64be* pOutOffset, uint8 slotNo)
{
if (!pOutOffset)
return 0xc0712c80;
*pOutOffset = GetUtcOffset();
return 0;
}
nnResult GetTimeZoneId(CafeString<65>* outTimezoneId)
{
// return a placeholder timezone id for now
// in the future we should emulated this correctly and read the timezone from the account via IOSU
outTimezoneId->assign("Europe/London");
return 0;
}
sint32 g_initializeCount = 0; // inc in Initialize and dec in Finalize
uint32 Initialize()
{
// usually uses a mutex which is initialized in -> global constructor keyed to'_17_act_shim_util_cpp
if (g_initializeCount == 0)
{
actPrepareRequest();
actRequest->requestCode = IOSU_ARC_INIT;
__depr__IOS_Ioctlv(IOS_DEVICE_ACT, IOSU_ACT_REQUEST_CEMU, 1, 1, actBufferVector);
}
g_initializeCount++;
return 0;
}
NN_ERROR_CODE GetErrorCode(betype<nnResult>* nnResult)
{
NN_ERROR_CODE errCode = NNResultToErrorCode(*nnResult, NN_RESULT_MODULE_NN_ACT);
return errCode;
}
}
}
void nnActExport_CreateConsoleAccount(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "CreateConsoleAccount(...)");
//numAccounts++;
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetNumOfAccounts(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetNumOfAccounts()");
osLib_returnFromFunction(hCPU, numAccounts); // account count
}
void nnActExport_IsSlotOccupied(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.IsSlotOccupied({})", hCPU->gpr[3]);
ppcDefineParamU8(slot, 0);
osLib_returnFromFunction(hCPU, nn::act::GetPersistentIdEx(slot) != 0 ? 1 : 0);
}
uint32 GetAccountIdEx(char* accountId, uint8 slot)
{
// returns zero for non-network accounts?
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_ACCOUNT_ID;
actRequest->accountSlot = slot;
uint32 result = _doCemuActRequest(actRequest);
strcpy(accountId, actRequest->resultString.strBuffer);
return result;
}
uint32 GetPrincipalIdEx(uint32be* principalId, uint8 slot)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_PRINCIPALID;
actRequest->accountSlot = slot;
uint32 result = _doCemuActRequest(actRequest);
*principalId = actRequest->resultU32.u32;
return result;
}
uint32 GetCountryEx(char* country, uint8 slot)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_COUNTRY;
actRequest->accountSlot = slot;
uint32 result = _doCemuActRequest(actRequest);
strcpy(country, actRequest->resultString.strBuffer);
return result;
}
uint32 IsNetworkAccount(uint8* isNetworkAccount, uint8 slot)
{
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_ISNETWORKACCOUNT;
actRequest->accountSlot = slot;
uint32 result = _doCemuActRequest(actRequest);
*isNetworkAccount = (actRequest->resultU32.u32 != 0) ? 1 : 0;
return result;
}
void nnActExport_IsNetworkAccount(PPCInterpreter_t* hCPU)
{
//cemuLog_logDebug(LogType::Force, "nn_act.IsNetworkAccount()");
uint8 isNetAcc = 0;
IsNetworkAccount(&isNetAcc, 0xFE);
osLib_returnFromFunction(hCPU, isNetAcc);
}
void nnActExport_IsNetworkAccountEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU8(slot, 0);
cemuLog_logDebug(LogType::Force, "nn_act.IsNetworkAccountEx({})", slot);
uint8 isNetAcc = 0;
IsNetworkAccount(&isNetAcc, slot);
osLib_returnFromFunction(hCPU, isNetAcc);
}
void nnActExport_GetSimpleAddressId(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetSimpleAddressId()");
uint32be simpleAddressId;
nn::act::GetSimpleAddressIdEx(&simpleAddressId, iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, (uint32)simpleAddressId);
}
void nnActExport_GetSimpleAddressIdEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetSimpleAddressIdEx(0x{:08x}, {})", hCPU->gpr[3], hCPU->gpr[4] & 0xFF);
ppcDefineParamU32BEPtr(simpleAddressId, 0);
ppcDefineParamU8(slot, 1);
nn::act::GetSimpleAddressIdEx(simpleAddressId, slot);
osLib_returnFromFunction(hCPU, 0); // ResultSuccess
}
void nnActExport_GetPrincipalId(PPCInterpreter_t* hCPU)
{
// return error for non-nnid accounts?
uint32be principalId;
GetPrincipalIdEx(&principalId, iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, (uint32)principalId);
}
void nnActExport_GetPrincipalIdEx(PPCInterpreter_t* hCPU)
{
// return error for non-nnid accounts?
cemuLog_logDebug(LogType::Force, "nn_act.GetPrincipalIdEx(0x{:08x}, {})", hCPU->gpr[3], hCPU->gpr[4]&0xFF);
ppcDefineParamU32BEPtr(principalId, 0);
ppcDefineParamU8(slot, 1);
GetPrincipalIdEx(principalId, slot);
osLib_returnFromFunction(hCPU, 0); // ResultSuccess
}
void nnActExport_GetTransferableId(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(unique, 0);
cemuLog_logDebug(LogType::Force, "nn_act.GetTransferableId(0x{:08x})", hCPU->gpr[3]);
uint64 transferableId;
uint32 r = nn::act::GetTransferableIdEx(&transferableId, unique, iosu::act::ACT_SLOT_CURRENT);
if (NN_RESULT_IS_FAILURE(r))
{
transferableId = 0;
}
osLib_returnFromFunction64(hCPU, _swapEndianU64(transferableId));
}
void nnActExport_GetTransferableIdEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(transferableId, uint64, 0);
ppcDefineParamU32(unique, 1);
ppcDefineParamU8(slot, 2);
cemuLog_logDebug(LogType::Force, "nn_act.GetTransferableIdEx(0x{:08x}, 0x{:08x}, {})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5] & 0xFF);
uint32 r = nn::act::GetTransferableIdEx(transferableId, unique, slot);
osLib_returnFromFunction(hCPU, 0); // ResultSuccess
}
void nnActExport_GetPersistentId(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetPersistentId()");
uint32 persistentId = nn::act::GetPersistentIdEx(iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, persistentId);
}
void nnActExport_GetPersistentIdEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU8(slot, 0);
cemuLog_logDebug(LogType::Force, "nn_act.GetPersistentIdEx({})", slot);
uint32 persistentId = nn::act::GetPersistentIdEx(slot);
osLib_returnFromFunction(hCPU, persistentId);
}
void nnActExport_GetCountry(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetCountry(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStr(country, 0);
uint32 r = GetCountryEx(country, iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, r);
}
bool g_isParentalControlCheckEnabled = false;
void nnActExport_EnableParentalControlCheck(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.EnableParentalControlCheck({})", hCPU->gpr[3]);
ppcDefineParamU8(isEnabled, 0);
g_isParentalControlCheckEnabled = isEnabled != 0;
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_IsParentalControlCheckEnabled(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.IsParentalControlCheckEnabled() -> {}", g_isParentalControlCheckEnabled);
osLib_returnFromFunction(hCPU, g_isParentalControlCheckEnabled);
}
void nnActExport_GetHostServerSettings(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetHostServerSettings() - stub");
ppcDefineParamStr(ukn, 1);
strcpy(ukn, "");
osLib_returnFromFunction(hCPU, 0x00000000);
}
void nnActExport_GetMii(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetMii(...)");
ppcDefineParamUStr(miiData, 0);
uint32 r = nn::act::GetMiiEx(miiData, iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, r);
}
void nnActExport_GetMiiEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetMiiEx(...)");
ppcDefineParamUStr(miiData, 0);
ppcDefineParamU8(slot, 1);
uint32 r = nn::act::GetMiiEx(miiData, slot);
osLib_returnFromFunction(hCPU, r);
}
void nnActExport_GetMiiImageEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetMiiImageEx unimplemented");
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetMiiName(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetMiiName(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamWStrBE(miiName, 0);
StackAllocator<FFLData_t> miiData;
uint32 r = nn::act::GetMiiEx(&miiData, iosu::act::ACT_SLOT_CURRENT);
// extract name
sint32 miiNameLength = 0;
for (sint32 i = 0; i < MII_FFL_NAME_LENGTH; i++)
{
miiName[i] = miiData->miiName[i];
if (miiData->miiName[i] == (const uint16be)'\0')
break;
miiNameLength = i+1;
}
miiName[miiNameLength] = '\0';
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetMiiNameEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetMiiNameEx(0x{:08x}, {})", hCPU->gpr[3], hCPU->gpr[4] & 0xFF);
ppcDefineParamWStrBE(miiName, 0);
ppcDefineParamU8(slot, 1);
StackAllocator<FFLData_t> miiData;
uint32 r = nn::act::GetMiiEx(&miiData, slot);
// extract name
sint32 miiNameLength = 0;
for (sint32 i = 0; i < MII_FFL_NAME_LENGTH; i++)
{
miiName[i] = miiData->miiName[i];
if (miiData->miiName[i] == (const uint16be)'\0')
break;
miiNameLength = i + 1;
}
miiName[miiNameLength] = '\0';
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
uint32be ukn00;
uint32be ukn04; // transferable id high?
uint32be accountTransferableIdLow; //
uint32be ukn0C;
uint32be ukn10;
uint32be ukn14;
uint32be ukn18;
uint32be ukn1C;
uint32be ukn20;
uint32be ukn24;
uint32be ukn28;
uint32be ukn2C;
uint32be ukn30;
uint32be ukn34;
uint32be ukn38;
uint32be ukn3C;
uint32be ukn40;
uint32be ukn44;
uint32be ukn48;
uint32be ukn4C;
uint32be ukn50;
uint32be ukn54;
uint32be tlsModuleIndex;
uint32be ukn5C;
}FFLStoreDataDepr_t;
static_assert(sizeof(FFLStoreDataDepr_t) == 96);
void nnActExport_UpdateMii(PPCInterpreter_t* hCPU)
{
if (sizeof(FFLStoreDataDepr_t) != MII_FFL_STORAGE_SIZE)
assert_dbg();
ppcDefineParamU8(slot, 0);
ppcDefineParamStructPtr(fflStoreData, FFLStoreDataDepr_t, 1);
ppcDefineParamStructPtr(uknName, uint16, 2); // mii name
ppcDefineParamStructPtr(uknNameR6, uint8, 3);
ppcDefineParamStructPtr(uknNameR7, uint8, 4);
ppcDefineParamStructPtr(uknNameR8, uint8, 5);
ppcDefineParamStructPtr(uknNameR9, uint8, 6);
ppcDefineParamStructPtr(uknNameR10, uint8, 7);
ppcDefineParamStructPtr(uknNameSP4, uint8, 8);
cemu_assert_unimplemented();
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetUuid(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetUuid(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamUStr(uuid, 0);
nn::act::GetUuidEx(uuid, iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, 0); // 0 -> result ok
}
void nnActExport_GetUuidEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetUuidEx(0x{:08x},0x{:02x})", hCPU->gpr[3], hCPU->gpr[3]&0xFF);
ppcDefineParamUStr(uuid, 0);
ppcDefineParamU8(slot, 1);
nn::act::GetUuidEx(uuid, slot);
osLib_returnFromFunction(hCPU, 0); // 0 -> result ok
}
void nnActExport_GetUuidEx2(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetUuidEx(0x{:08x},0x{:02x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamUStr(uuid, 0);
ppcDefineParamU8(slot, 1);
ppcDefineParamS32(name, 2);
nn::act::GetUuidEx(uuid, iosu::act::ACT_SLOT_CURRENT, name);
osLib_returnFromFunction(hCPU, 0); // 0 -> result ok
}
void nnActExport_GetAccountId(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetAccountId(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamUStr(accId, 0);
GetAccountIdEx((char*)accId, iosu::act::ACT_SLOT_CURRENT);
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetAccountIdEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetAccountIdEx(0x{:08x}, 0x{:02x})", hCPU->gpr[3], hCPU->gpr[3] & 0xFF);
ppcDefineParamUStr(accId, 0);
ppcDefineParamU8(slot, 1);
GetAccountIdEx((char*)accId, slot);
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetParentalControlSlotNoEx(PPCInterpreter_t* hCPU)
{
// GetParentalControlSlotNoEx(uint8* output, uint8 slot)
cemuLog_logDebug(LogType::Force, "nn_act.GetParentalControlSlotNoEx(0x{:08x}, 0x{:02x})", hCPU->gpr[3], hCPU->gpr[4]);
//memory_writeU8(hCPU->gpr[3], 0x01); // returned slot no (slot indices start at 1)
memory_writeU8(hCPU->gpr[3], 1); // 0 -> No parental control for slot?
//memory_writeU8(hCPU->gpr[3], 0); // 0 -> No parental control for slot?
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_GetDefaultAccount(PPCInterpreter_t* hCPU)
{
// todo
cemuLog_logDebug(LogType::Force, "GetDefaultAccount(): Return 1?");
osLib_returnFromFunction(hCPU, 1);
}
void nnActExport_GetSlotNo(PPCInterpreter_t* hCPU)
{
// id of active account
osLib_returnFromFunction(hCPU, 1); // 1 is the first slot (0 is invalid)
}
void nnActExport_GetSlotNoEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.GetSlotNoEx(...)");
// get slot no by uuid
ppcDefineParamUStr(uuid, 0);
// get slot no for a specific uuid
for (uint8 i = 1; i < 12; i++)
{
uint8 accUuid[16]{};
nn::act::GetUuidEx(accUuid, i);
if (memcmp(uuid, accUuid, 16) == 0)
{
osLib_returnFromFunction(hCPU, i);
return;
}
}
cemu_assert_debug(false); // suspicious behavior?
osLib_returnFromFunction(hCPU, 0); // account not found
}
void nnActExport_Initialize(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_act.Initialize()");
nn::act::Initialize();
osLib_returnFromFunction(hCPU, 0);
}
void nnActExport_HasNfsAccount(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "Called nn_act.HasNfsAccount");
osLib_returnFromFunction(hCPU, 1); // Nfs = Nintendo Friend System? (Splatoon tries to call nn_fp.RegisterAccount if we set this to false)
}
typedef struct
{
/* +0x000 */ char token[0x201]; // /nex_token/token
/* +0x201 */ uint8 padding201[3];
/* +0x204 */ char nexPassword[0x41]; // /nex_token/nex_password
/* +0x245 */ uint8 padding245[3];
/* +0x248 */ char host[0x10]; // /nex_token/host
/* +0x258 */ uint16be port; // /nex_token/port
/* +0x25A */ uint16be padding25A;
}nexServiceToken_t;
static_assert(sizeof(nexServiceToken_t) == 0x25C, "nexServiceToken_t has invalid size");
void nnActExport_AcquireNexServiceToken(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(token, nexServiceToken_t, 0);
ppcDefineParamU32(serverId, 1);
memset(token, 0, sizeof(nexServiceToken_t));
actPrepareRequest();
actRequest->accountSlot = iosu::act::ACT_SLOT_CURRENT;
actRequest->requestCode = IOSU_ARC_ACQUIRENEXTOKEN;
actRequest->titleId = CafeSystem::GetForegroundTitleId();
actRequest->titleVersion = CafeSystem::GetForegroundTitleVersion();
actRequest->serverId = serverId;
uint32 resultCode = __depr__IOS_Ioctlv(IOS_DEVICE_ACT, IOSU_ACT_REQUEST_CEMU, 1, 1, actBufferVector);
memcpy(token, actRequest->resultBinary.binBuffer, sizeof(nexServiceToken_t));
cemuLog_logDebug(LogType::Force, "Called nn_act.AcquireNexServiceToken");
osLib_returnFromFunction(hCPU, getNNReturnCode(resultCode, actRequest));
}
void nnActExport_AcquireIndependentServiceToken(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(token, independentServiceToken_t, 0);
ppcDefineParamMEMPTR(clientId, const char, 1);
uint32 result = nn::act::AcquireIndependentServiceToken(token.GetPtr(), clientId.GetPtr(), 0);
osLib_returnFromFunction(hCPU, result);
}
void nnActExport_AcquireIndependentServiceToken2(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(token, independentServiceToken_t, 0);
ppcDefineParamMEMPTR(clientId, const char, 1);
ppcDefineParamU32(cacheDurationInSeconds, 2);
uint32 result = nn::act::AcquireIndependentServiceToken(token, clientId.GetPtr(), cacheDurationInSeconds);
osLib_returnFromFunction(hCPU, result);
}
void nnActExport_AcquireEcServiceToken(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(pEcServiceToken, independentServiceToken_t, 0);
uint32 result = nn::act::AcquireIndependentServiceToken(pEcServiceToken.GetPtr(), "71a6f5d6430ea0183e3917787d717c46", 0);
osLib_returnFromFunction(hCPU, result);
}
void nnActExport_AcquirePrincipalIdByAccountId(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(principalId, uint32be, 0);
ppcDefineParamMEMPTR(nnid, char, 1);
ppcDefineParamU32(ukn, 2); // some option, can be 0 or 1 ?
cemuLog_logDebug(LogType::Force, "nn_act.AcquirePrincipalIdByAccountId(0x{:08x},\"{}\", {}) - last param unknown", principalId.GetMPTR(), nnid.GetPtr(), ukn);
actPrepareRequest2();
actRequest->requestCode = IOSU_ARC_ACQUIREPIDBYNNID;
strcpy(actRequest->clientId, nnid.GetPtr());
uint32 result = _doCemuActRequest(actRequest);
*principalId.GetPtr() = actRequest->resultU32.u32;
osLib_returnFromFunction(hCPU, result);
}
// register account functions
void nnAct_load()
{
osLib_addFunction("nn_act", "Initialize__Q2_2nn3actFv", nnActExport_Initialize);
osLib_addFunction("nn_act", "CreateConsoleAccount__Q2_2nn3actFv", nnActExport_CreateConsoleAccount);
osLib_addFunction("nn_act", "GetNumOfAccounts__Q2_2nn3actFv", nnActExport_GetNumOfAccounts);
osLib_addFunction("nn_act", "IsSlotOccupied__Q2_2nn3actFUc", nnActExport_IsSlotOccupied);
osLib_addFunction("nn_act", "GetSlotNo__Q2_2nn3actFv", nnActExport_GetSlotNo);
osLib_addFunction("nn_act", "GetSlotNoEx__Q2_2nn3actFRC7ACTUuid", nnActExport_GetSlotNoEx);
osLib_addFunction("nn_act", "IsNetworkAccount__Q2_2nn3actFv", nnActExport_IsNetworkAccount);
osLib_addFunction("nn_act", "IsNetworkAccountEx__Q2_2nn3actFUc", nnActExport_IsNetworkAccountEx);
// account id
osLib_addFunction("nn_act", "GetAccountId__Q2_2nn3actFPc", nnActExport_GetAccountId);
osLib_addFunction("nn_act", "GetAccountIdEx__Q2_2nn3actFPcUc", nnActExport_GetAccountIdEx);
// simple address
osLib_addFunction("nn_act", "GetSimpleAddressId__Q2_2nn3actFv", nnActExport_GetSimpleAddressId);
osLib_addFunction("nn_act", "GetSimpleAddressIdEx__Q2_2nn3actFPUiUc", nnActExport_GetSimpleAddressIdEx);
// principal id
osLib_addFunction("nn_act", "GetPrincipalId__Q2_2nn3actFv", nnActExport_GetPrincipalId);
osLib_addFunction("nn_act", "GetPrincipalIdEx__Q2_2nn3actFPUiUc", nnActExport_GetPrincipalIdEx);
// transferable id
osLib_addFunction("nn_act", "GetTransferableId__Q2_2nn3actFUi", nnActExport_GetTransferableId);
osLib_addFunction("nn_act", "GetTransferableIdEx__Q2_2nn3actFPULUiUc", nnActExport_GetTransferableIdEx);
// persistent id
osLib_addFunction("nn_act", "GetPersistentId__Q2_2nn3actFv", nnActExport_GetPersistentId);
osLib_addFunction("nn_act", "GetPersistentIdEx__Q2_2nn3actFUc", nnActExport_GetPersistentIdEx);
// country
osLib_addFunction("nn_act", "GetCountry__Q2_2nn3actFPc", nnActExport_GetCountry);
// timezone
cafeExportRegisterFunc(nn::act::GetTimeZoneId, "nn_act", "GetTimeZoneId__Q2_2nn3actFPc", LogType::Placeholder);
// parental
osLib_addFunction("nn_act", "EnableParentalControlCheck__Q2_2nn3actFb", nnActExport_EnableParentalControlCheck);
osLib_addFunction("nn_act", "IsParentalControlCheckEnabled__Q2_2nn3actFv", nnActExport_IsParentalControlCheckEnabled);
osLib_addFunction("nn_act", "GetMii__Q2_2nn3actFP12FFLStoreData", nnActExport_GetMii);
osLib_addFunction("nn_act", "GetMiiEx__Q2_2nn3actFP12FFLStoreDataUc", nnActExport_GetMiiEx);
osLib_addFunction("nn_act", "GetMiiImageEx__Q2_2nn3actFPUiPvUi15ACTMiiImageTypeUc", nnActExport_GetMiiImageEx);
osLib_addFunction("nn_act", "GetMiiName__Q2_2nn3actFPw", nnActExport_GetMiiName);
osLib_addFunction("nn_act", "GetMiiNameEx__Q2_2nn3actFPwUc", nnActExport_GetMiiNameEx);
osLib_addFunction("nn_act", "UpdateMii__Q2_2nn3actFUcRC12FFLStoreDataPCwPCvUiT4T5T4T5T4T5T4T5T4T5T4T5T4T5T4T5", nnActExport_UpdateMii);
osLib_addFunction("nn_act", "GetUuid__Q2_2nn3actFP7ACTUuid", nnActExport_GetUuid);
osLib_addFunction("nn_act", "GetUuidEx__Q2_2nn3actFP7ACTUuidUc", nnActExport_GetUuidEx);
osLib_addFunction("nn_act", "GetUuidEx__Q2_2nn3actFP7ACTUuidUcUi", nnActExport_GetUuidEx2);
osLib_addFunction("nn_act", "GetParentalControlSlotNoEx__Q2_2nn3actFPUcUc", nnActExport_GetParentalControlSlotNoEx);
osLib_addFunction("nn_act", "GetDefaultAccount__Q2_2nn3actFv", nnActExport_GetDefaultAccount);
osLib_addFunction("nn_act", "AcquireEcServiceToken__Q2_2nn3actFPc", nnActExport_AcquireEcServiceToken);
osLib_addFunction("nn_act", "AcquireNexServiceToken__Q2_2nn3actFP26ACTNexAuthenticationResultUi", nnActExport_AcquireNexServiceToken);
osLib_addFunction("nn_act", "AcquireIndependentServiceToken__Q2_2nn3actFPcPCc", nnActExport_AcquireIndependentServiceToken);
osLib_addFunction("nn_act", "AcquireIndependentServiceToken__Q2_2nn3actFPcPCcUibT4", nnActExport_AcquireIndependentServiceToken2);
osLib_addFunction("nn_act", "AcquireIndependentServiceToken__Q2_2nn3actFPcPCcUi", nnActExport_AcquireIndependentServiceToken2);
osLib_addFunction("nn_act", "AcquirePrincipalIdByAccountId__Q2_2nn3actFPUiPA17_CcUi", nnActExport_AcquirePrincipalIdByAccountId);
cafeExportRegisterFunc(nn::act::GetErrorCode, "nn_act", "GetErrorCode__Q2_2nn3actFRCQ2_2nn6Result", LogType::Placeholder);
// placeholders / incomplete implementations
osLib_addFunction("nn_act", "HasNfsAccount__Q2_2nn3actFv", nnActExport_HasNfsAccount);
osLib_addFunction("nn_act", "GetHostServerSettings__Q2_2nn3actFPcT1Uc", nnActExport_GetHostServerSettings);
cafeExportRegisterFunc(nn::act::GetUtcOffset, "nn_act", "GetUtcOffset__Q2_2nn3actFv", LogType::Placeholder);
cafeExportRegisterFunc(nn::act::GetUtcOffsetEx, "nn_act", "GetUtcOffsetEx__Q2_2nn3actFPLUc", LogType::Placeholder);
}
| 25,336
|
C++
|
.cpp
| 607
| 39.449753
| 159
| 0.778818
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,044
|
nn_nim.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_nim/nn_nim.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
#include "Cafe/IOSU/legacy/iosu_nim.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/OS/libs/nn_common.h"
#define nimPrepareRequest() \
StackAllocator<iosu::nim::iosuNimCemuRequest_t> _buf_nimRequest; \
StackAllocator<ioBufferVector_t> _buf_bufferVector; \
iosu::nim::iosuNimCemuRequest_t* nimRequest = _buf_nimRequest.GetPointer(); \
ioBufferVector_t* nimBufferVector = _buf_bufferVector.GetPointer(); \
memset(nimRequest, 0, sizeof(iosu::nim::iosuNimCemuRequest_t)); \
memset(nimBufferVector, 0, sizeof(ioBufferVector_t)); \
nimBufferVector->buffer = (uint8*)nimRequest;
namespace nn
{
namespace nim
{
void export_NeedsNetworkUpdate(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "NeedsNetworkUpdate() - placeholder");
ppcDefineParamTypePtr(needsUpdate, uint8, 0);
*needsUpdate = 0;
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
uint32be ukn00;
uint32be ukn04;
uint32be ukn08;
uint32be ukn0C;
uint32be ukn10;
uint32be ukn14;
uint32be ukn18;
}updatePackageProgress_t;
void export_GetUpdatePackageProgress(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetUpdatePackageProgress() - placeholder");
ppcDefineParamTypePtr(updatePackageProgress, updatePackageProgress_t, 0);
// status of system update download
// values are unknown
updatePackageProgress->ukn00 = 0;
updatePackageProgress->ukn04 = 0;
updatePackageProgress->ukn18 = 0;
osLib_returnFromFunction(hCPU, 0);
}
void export_NeedsNotifyToUsers(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "NeedsNotifyToUsers() - placeholder");
ppcDefineParamTypePtr(updatePackageProgress, updatePackageProgress_t, 0);
osLib_returnFromFunction(hCPU, 0);
}
void export_GetNumTitlePackages(PPCInterpreter_t* hCPU)
{
nimPrepareRequest();
nimRequest->requestCode = IOSU_NIM_GET_PACKAGE_COUNT;
__depr__IOS_Ioctlv(IOS_DEVICE_NIM, IOSU_NIM_REQUEST_CEMU, 1, 1, nimBufferVector);
uint32 numTitlePackages = nimRequest->resultU32.u32;
osLib_returnFromFunction(hCPU, numTitlePackages);
}
static_assert(sizeof(iosu::nim::titlePackageInfo_t) == 0x50, "titlePackageInfo_t has invalid size");
static_assert(offsetof(iosu::nim::titlePackageInfo_t, ukn28DLProgressRelatedMax_u64be) == 0x28, "ukn28_u64be has invalid offset");
void export_ListTitlePackagesStatically(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "ListTitlePackagesStatically() - placeholder");
ppcDefineParamTypePtr(titleIdList, uint64, 0);
ppcDefineParamS32(maxCount, 1);
nimPrepareRequest();
nimRequest->requestCode = IOSU_NIM_GET_PACKAGES_TITLEID;
nimRequest->maxCount = maxCount;
nimRequest->ptr = (uint8*)(titleIdList);
__depr__IOS_Ioctlv(IOS_DEVICE_NIM, IOSU_NIM_REQUEST_CEMU, 1, 1, nimBufferVector);
osLib_returnFromFunction(hCPU, 0);
}
void export_GetTitlePackageInfos(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetTitlePackageInfos() - placeholder");
ppcDefineParamTypePtr(titlePackageInfo, iosu::nim::titlePackageInfo_t, 0);
ppcDefineParamTypePtr(titleIdList, uint64, 1);
ppcDefineParamU32(count, 2);
nimPrepareRequest();
nimRequest->requestCode = IOSU_NIM_GET_PACKAGES_INFO;
nimRequest->maxCount = count;
nimRequest->ptr = (uint8*)(titleIdList);
nimRequest->ptr2 = (uint8*)(titlePackageInfo);
__depr__IOS_Ioctlv(IOS_DEVICE_NIM, IOSU_NIM_REQUEST_CEMU, 1, 1, nimBufferVector);
osLib_returnFromFunction(hCPU, 0);
}
void export_NeedsNotifyToUsersTitlePackage(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "NeedsNotifyToUsers() - placeholder");
ppcDefineParamTypePtr(titlePackageInfo, iosu::nim::titlePackageInfo_t, 0);
osLib_returnFromFunction(hCPU, 0);
}
using IDBE_DATA = uint8[0x12060];
void export_GetIconDatabaseEntries(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetIconDatabaseEntries() - placeholder");
ppcDefineParamTypePtr(iconDatabaseEntries, IDBE_DATA, 0);
ppcDefineParamTypePtr(titleIdList, uint64, 1);
ppcDefineParamS32(count, 2);
cemu_assert_debug(count == 1); // other count values are untested
for (sint32 i = 0; i < count; i++)
{
nimPrepareRequest();
nimRequest->requestCode = IOSU_NIM_GET_ICON_DATABASE_ENTRY;
nimRequest->titleId = _swapEndianU64(titleIdList[i]);
nimRequest->ptr = (uint8*)(iconDatabaseEntries + i);
__depr__IOS_Ioctlv(IOS_DEVICE_NIM, IOSU_NIM_REQUEST_CEMU, 1, 1, nimBufferVector);
}
osLib_returnFromFunction(hCPU, 0);
}
void export_QuerySchedulerStatus(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "QuerySchedulerStatus() - placeholder");
// scheduler status seems to be either a 4 byte array or 8 byte array (or structs)?
// scope.rpx only checks the second byte and if it matches 0x01 then the scheduler is considered paused/stopped (displays that downloads are inactive)
// men.rpx checks the first byte for == 1 and if true, it will show the download manager icon as downloading
// downloads disabled:
//memory_writeU32(hCPU->gpr[3], (0x00010000));
// downloads enabled:
memory_writeU32(hCPU->gpr[3], (0x00000000));
osLib_returnFromFunction(hCPU, 0);
}
struct nimResultError
{
uint32be iosError;
uint32be ukn04;
};
void ConstructResultError(nimResultError* resultError, uint32be* nimErrorCodePtr, uint32 uknParam)
{
uint32 nnResultCode = *nimErrorCodePtr;
resultError->iosError = nnResultCode;
resultError->ukn04 = uknParam;
if (nnResultCode == 0xFFFFFFFF)
{
// not a valid code, used by a Wii U menu
return;
}
// IOS errors need to be translated
if ( (nnResultCode&0x18000000) == 0x18000000)
{
// alternative error format
cemu_assert_unimplemented();
}
else
{
auto moduleId = nn::nnResult_GetModule(nnResultCode);
if (moduleId == NN_RESULT_MODULE_NN_IOS)
{
// ios error
cemu_assert_unimplemented();
}
else
{
// other error
resultError->iosError = 0;
}
}
}
void export_GetECommerceInfrastructureCountry(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32BEPtr(country, 0);
cemuLog_logDebug(LogType::Force, "GetECommerceInfrastructureCountry - todo");
*country = 0;
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
betype<uint32> titleIdHigh;
betype<uint32> titleIdLow;
uint32 regionOrLanguageRelated;
uint8 uknByte0C;
uint8 applicationBoxDevice1; // this is what E-Shop app reads to determine device (0 -> mlc, 1 -> extern storage?)
uint8 uknByte0E;
uint8 applicationBoxDevice2;
uint32 ukn10;
uint8 uknByte14; // set to 0
uint8 uknByte15; // set to 1
uint8 postDownloadAction; // 0 -> ?, 1 -> ?, 2 -> Use bg install policy
uint8 uknBytes17;
}TitlePackageTaskConfig_t;
static_assert(sizeof(TitlePackageTaskConfig_t) == 0x18, "");
void export_MakeTitlePackageTaskConfigAutoUsingBgInstallPolicy(PPCInterpreter_t* hCPU)
{
ppcDefineParamPtr(titlePackageTastConfig, TitlePackageTaskConfig_t, 0);
ppcDefineParamU64(titleId, 2);
ppcDefineParamU32(regionOrLanguage, 4);
ppcDefineParamU32(uknR8, 5); // title type?
cemuLog_logDebug(LogType::Force, "MakeTitlePackageTaskConfigAutoUsingBgInstallPolicy - placeholder");
titlePackageTastConfig->titleIdHigh = (uint32)(titleId >> 32);
titlePackageTastConfig->titleIdLow = (uint32)(titleId & 0xFFFFFFFF);
titlePackageTastConfig->regionOrLanguageRelated = 0; // ?
titlePackageTastConfig->uknByte0C = uknR8;
titlePackageTastConfig->applicationBoxDevice1 = 1; // 1 -> mlc
titlePackageTastConfig->applicationBoxDevice2 = 1; // 1 -> mlc
titlePackageTastConfig->uknByte0E = 0; // ?
titlePackageTastConfig->ukn10 = 0; // ?
titlePackageTastConfig->uknByte14 = 0; // ?
titlePackageTastConfig->uknByte15 = 1; // ?
titlePackageTastConfig->postDownloadAction = 0; // ?
titlePackageTastConfig->uknBytes17 = 0; // ?
osLib_returnFromFunction(hCPU, 0);
}
void export_CalculateTitleInstallSize(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(installSize, betype<uint64>, 0);
ppcDefineParamPtr(titlePackageTastConfig, TitlePackageTaskConfig_t, 1);
// get install size of currently installed title, otherwise return -1 as size
cemuLog_logDebug(LogType::Force, "CalculateTitleInstallSize - todo");
*installSize = 0xFFFFFFFFFFFFFFFF;
osLib_returnFromFunction(hCPU, 0);
}
void load()
{
osLib_addFunction("nn_nim", "NeedsNetworkUpdate__Q2_2nn3nimFPb", export_NeedsNetworkUpdate);
osLib_addFunction("nn_nim", "GetUpdatePackageProgress__Q2_2nn3nimFPQ3_2nn3nim21UpdatePackageProgress", export_GetUpdatePackageProgress);
osLib_addFunction("nn_nim", "NeedsNotifyToUsers__Q3_2nn3nim4utilFPCQ3_2nn3nim21UpdatePackageProgress", export_NeedsNotifyToUsers);
osLib_addFunction("nn_nim", "GetNumTitlePackages__Q2_2nn3nimFv", export_GetNumTitlePackages);
osLib_addFunction("nn_nim", "GetTitlePackageInfos__Q2_2nn3nimFPQ3_2nn3nim16TitlePackageInfoPCULUi", export_GetTitlePackageInfos);
osLib_addFunction("nn_nim", "NeedsNotifyToUsers__Q3_2nn3nim4utilFPCQ3_2nn3nim16TitlePackageInfoPCQ3_2nn3nim11ResultError", export_NeedsNotifyToUsersTitlePackage);
osLib_addFunction("nn_nim", "ListTitlePackagesStatically__Q2_2nn3nimFPULUi", export_ListTitlePackagesStatically);
osLib_addFunction("nn_nim", "GetECommerceInfrastructureCountry__Q2_2nn3nimFPQ3_2nn3nim7Country", export_GetECommerceInfrastructureCountry);
osLib_addFunction("nn_nim", "QuerySchedulerStatus__Q2_2nn3nimFPQ3_2nn3nim15SchedulerStatus", export_QuerySchedulerStatus);
osLib_addFunction("nn_nim", "GetIconDatabaseEntries__Q2_2nn3nimFPQ3_2nn3nim17IconDatabaseEntryPCULUi", export_GetIconDatabaseEntries);
cafeExportRegisterFunc(ConstructResultError, "nn_nim", "Construct__Q3_2nn3nim11ResultErrorFQ2_2nn6Resulti", LogType::Placeholder);
osLib_addFunction("nn_nim", "MakeTitlePackageTaskConfigAutoUsingBgInstallPolicy__Q3_2nn3nim4utilFULiQ3_2nn4Cafe9TitleType", export_MakeTitlePackageTaskConfigAutoUsingBgInstallPolicy);
osLib_addFunction("nn_nim", "CalculateTitleInstallSize__Q2_2nn3nimFPLRCQ3_2nn3nim22TitlePackageTaskConfigPCUsUi", export_CalculateTitleInstallSize);
}
}
}
| 10,356
|
C++
|
.cpp
| 230
| 41.06087
| 186
| 0.7648
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,045
|
H264DecBackendAVC.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/h264_avc/H264DecBackendAVC.cpp
|
#include "H264DecInternal.h"
#include "util/highresolutiontimer/HighResolutionTimer.h"
extern "C"
{
#include "../dependencies/ih264d/common/ih264_typedefs.h"
#include "../dependencies/ih264d/decoder/ih264d.h"
};
namespace H264
{
bool H264_IsBotW();
class H264AVCDecoder : public H264DecoderBackend
{
static void* ivd_aligned_malloc(void* ctxt, WORD32 alignment, WORD32 size)
{
#ifdef _WIN32
return _aligned_malloc(size, alignment);
#else
// alignment is atleast sizeof(void*)
alignment = std::max<WORD32>(alignment, sizeof(void*));
//smallest multiple of 2 at least as large as alignment
alignment--;
alignment |= alignment << 1;
alignment |= alignment >> 1;
alignment |= alignment >> 2;
alignment |= alignment >> 4;
alignment |= alignment >> 8;
alignment |= alignment >> 16;
alignment ^= (alignment >> 1);
void* temp;
posix_memalign(&temp, (size_t)alignment, (size_t)size);
return temp;
#endif
}
static void ivd_aligned_free(void* ctxt, void* buf)
{
#ifdef _WIN32
_aligned_free(buf);
#else
free(buf);
#endif
}
public:
H264AVCDecoder()
{
m_decoderThread = std::thread(&H264AVCDecoder::DecoderThread, this);
}
~H264AVCDecoder()
{
m_threadShouldExit = true;
m_decodeSem.increment();
if (m_decoderThread.joinable())
m_decoderThread.join();
}
void Init(bool isBufferedMode)
{
ih264d_create_ip_t s_create_ip{ 0 };
ih264d_create_op_t s_create_op{ 0 };
s_create_ip.s_ivd_create_ip_t.u4_size = sizeof(ih264d_create_ip_t);
s_create_ip.s_ivd_create_ip_t.e_cmd = IVD_CMD_CREATE;
s_create_ip.s_ivd_create_ip_t.u4_share_disp_buf = 1; // shared display buffer mode -> We give the decoder a list of buffers that it will use (?)
s_create_op.s_ivd_create_op_t.u4_size = sizeof(ih264d_create_op_t);
s_create_ip.s_ivd_create_ip_t.e_output_format = IV_YUV_420SP_UV;
s_create_ip.s_ivd_create_ip_t.pf_aligned_alloc = ivd_aligned_malloc;
s_create_ip.s_ivd_create_ip_t.pf_aligned_free = ivd_aligned_free;
s_create_ip.s_ivd_create_ip_t.pv_mem_ctxt = NULL;
WORD32 status = ih264d_api_function(m_codecCtx, &s_create_ip, &s_create_op);
cemu_assert(!status);
m_codecCtx = (iv_obj_t*)s_create_op.s_ivd_create_op_t.pv_handle;
m_codecCtx->pv_fxns = (void*)&ih264d_api_function;
m_codecCtx->u4_size = sizeof(iv_obj_t);
SetDecoderCoreCount(1);
m_isBufferedMode = isBufferedMode;
UpdateParameters(false);
m_numDecodedFrames = 0;
m_hasBufferSizeInfo = false;
}
void Destroy()
{
if (!m_codecCtx)
return;
ih264d_delete_ip_t s_delete_ip{ 0 };
ih264d_delete_op_t s_delete_op{ 0 };
s_delete_ip.s_ivd_delete_ip_t.u4_size = sizeof(ih264d_delete_ip_t);
s_delete_ip.s_ivd_delete_ip_t.e_cmd = IVD_CMD_DELETE;
s_delete_op.s_ivd_delete_op_t.u4_size = sizeof(ih264d_delete_op_t);
WORD32 status = ih264d_api_function(m_codecCtx, &s_delete_ip, &s_delete_op);
cemu_assert_debug(!status);
m_codecCtx = nullptr;
}
void PushDecodedFrame(ivd_video_decode_op_t& s_dec_op)
{
// copy image data outside of lock since its an expensive operation
CopyImageToResultBuffer((uint8*)s_dec_op.s_disp_frm_buf.pv_y_buf, (uint8*)s_dec_op.s_disp_frm_buf.pv_u_buf, (uint8*)m_decodedSliceArray[s_dec_op.u4_ts].result.imageOutput, s_dec_op);
std::unique_lock _l(m_decodeQueueMtx);
cemu_assert(s_dec_op.u4_ts < m_decodedSliceArray.size());
auto& result = m_decodedSliceArray[s_dec_op.u4_ts];
cemu_assert_debug(result.isUsed);
cemu_assert_debug(s_dec_op.u4_output_present != 0);
result.result.isDecoded = true;
result.result.hasFrame = s_dec_op.u4_output_present != 0;
result.result.frameWidth = s_dec_op.u4_pic_wd;
result.result.frameHeight = s_dec_op.u4_pic_ht;
result.result.bytesPerRow = (s_dec_op.u4_pic_wd + 0xFF) & ~0xFF;
result.result.cropEnable = s_dec_op.u1_frame_cropping_flag;
result.result.cropTop = s_dec_op.u1_frame_cropping_rect_top_ofst;
result.result.cropBottom = s_dec_op.u1_frame_cropping_rect_bottom_ofst;
result.result.cropLeft = s_dec_op.u1_frame_cropping_rect_left_ofst;
result.result.cropRight = s_dec_op.u1_frame_cropping_rect_right_ofst;
m_displayQueue.push_back(s_dec_op.u4_ts);
_l.unlock();
coreinit::OSSignalEvent(m_displayQueueEvt);
}
// called from async worker thread
void Decode(DecodedSlice& decodedSlice)
{
if (!m_hasBufferSizeInfo)
{
uint32 numByteConsumed = 0;
if (!DetermineBufferSizes(decodedSlice.dataToDecode.m_data, decodedSlice.dataToDecode.m_length, numByteConsumed))
{
cemuLog_log(LogType::Force, "H264AVC: Unable to determine picture size. Ignoring decode input");
std::unique_lock _l(m_decodeQueueMtx);
decodedSlice.result.isDecoded = true;
decodedSlice.result.hasFrame = false;
coreinit::OSSignalEvent(m_displayQueueEvt);
return;
}
decodedSlice.dataToDecode.m_length -= numByteConsumed;
decodedSlice.dataToDecode.m_data = (uint8*)decodedSlice.dataToDecode.m_data + numByteConsumed;
m_hasBufferSizeInfo = true;
}
ivd_video_decode_ip_t s_dec_ip{ 0 };
ivd_video_decode_op_t s_dec_op{ 0 };
s_dec_ip.u4_size = sizeof(ivd_video_decode_ip_t);
s_dec_op.u4_size = sizeof(ivd_video_decode_op_t);
s_dec_ip.e_cmd = IVD_CMD_VIDEO_DECODE;
s_dec_ip.u4_ts = std::distance(m_decodedSliceArray.data(), &decodedSlice);
cemu_assert_debug(s_dec_ip.u4_ts < m_decodedSliceArray.size());
s_dec_ip.pv_stream_buffer = (uint8*)decodedSlice.dataToDecode.m_data;
s_dec_ip.u4_num_Bytes = decodedSlice.dataToDecode.m_length;
s_dec_ip.s_out_buffer.u4_min_out_buf_size[0] = 0;
s_dec_ip.s_out_buffer.u4_min_out_buf_size[1] = 0;
s_dec_ip.s_out_buffer.u4_num_bufs = 0;
BenchmarkTimer bt;
bt.Start();
WORD32 status = ih264d_api_function(m_codecCtx, &s_dec_ip, &s_dec_op);
if (status != 0 && (s_dec_op.u4_error_code&0xFF) == IVD_RES_CHANGED)
{
// resolution change
ResetDecoder();
m_hasBufferSizeInfo = false;
Decode(decodedSlice);
return;
}
else if (status != 0)
{
cemuLog_log(LogType::Force, "H264: Failed to decode frame (error 0x{:08x})", status);
decodedSlice.result.hasFrame = false;
cemu_assert_unimplemented();
return;
}
bt.Stop();
double decodeTime = bt.GetElapsedMilliseconds();
cemu_assert(s_dec_op.u4_frame_decoded_flag);
cemu_assert_debug(s_dec_op.u4_num_bytes_consumed == decodedSlice.dataToDecode.m_length);
cemu_assert_debug(m_isBufferedMode || s_dec_op.u4_output_present); // if buffered mode is disabled, then every input should output a frame (except for partial slices?)
if (s_dec_op.u4_output_present)
{
cemu_assert(s_dec_op.e_output_format == IV_YUV_420SP_UV);
if (H264_IsBotW())
{
if (s_dec_op.s_disp_frm_buf.u4_y_wd == 1920 && s_dec_op.s_disp_frm_buf.u4_y_ht == 1088)
s_dec_op.s_disp_frm_buf.u4_y_ht = 1080;
}
bt.Start();
PushDecodedFrame(s_dec_op);
bt.Stop();
double copyTime = bt.GetElapsedMilliseconds();
// release buffer
sint32 bufferId = -1;
for (size_t i = 0; i < m_displayBuf.size(); i++)
{
if (s_dec_op.s_disp_frm_buf.pv_y_buf >= m_displayBuf[i].data() && s_dec_op.s_disp_frm_buf.pv_y_buf < (m_displayBuf[i].data() + m_displayBuf[i].size()))
{
bufferId = (sint32)i;
break;
}
}
cemu_assert_debug(bufferId == s_dec_op.u4_disp_buf_id);
cemu_assert(bufferId >= 0);
ivd_rel_display_frame_ip_t s_video_rel_disp_ip{ 0 };
ivd_rel_display_frame_op_t s_video_rel_disp_op{ 0 };
s_video_rel_disp_ip.e_cmd = IVD_CMD_REL_DISPLAY_FRAME;
s_video_rel_disp_ip.u4_size = sizeof(ivd_rel_display_frame_ip_t);
s_video_rel_disp_op.u4_size = sizeof(ivd_rel_display_frame_op_t);
s_video_rel_disp_ip.u4_disp_buf_id = bufferId;
status = ih264d_api_function(m_codecCtx, &s_video_rel_disp_ip, &s_video_rel_disp_op);
cemu_assert(!status);
cemuLog_log(LogType::H264, "H264Bench | DecodeTime {}ms CopyTime {}ms", decodeTime, copyTime);
}
else
{
cemuLog_log(LogType::H264, "H264Bench | DecodeTime {}ms (no frame output)", decodeTime);
}
if (s_dec_op.u4_frame_decoded_flag)
m_numDecodedFrames++;
// get VUI
//ih264d_ctl_get_vui_params_ip_t s_ctl_get_vui_params_ip;
//ih264d_ctl_get_vui_params_op_t s_ctl_get_vui_params_op;
//s_ctl_get_vui_params_ip.e_cmd = IVD_CMD_VIDEO_CTL;
//s_ctl_get_vui_params_ip.e_sub_cmd = (IVD_CONTROL_API_COMMAND_TYPE_T)IH264D_CMD_CTL_GET_VUI_PARAMS;
//s_ctl_get_vui_params_ip.u4_size = sizeof(ih264d_ctl_get_vui_params_ip_t);
//s_ctl_get_vui_params_op.u4_size = sizeof(ih264d_ctl_get_vui_params_op_t);
//status = ih264d_api_function(mCodecCtx, &s_ctl_get_vui_params_ip, &s_ctl_get_vui_params_op);
//cemu_assert(status == 0);
}
void Flush()
{
// set flush mode
ivd_ctl_flush_ip_t s_video_flush_ip{ 0 };
ivd_ctl_flush_op_t s_video_flush_op{ 0 };
s_video_flush_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_video_flush_ip.e_sub_cmd = IVD_CMD_CTL_FLUSH;
s_video_flush_ip.u4_size = sizeof(ivd_ctl_flush_ip_t);
s_video_flush_op.u4_size = sizeof(ivd_ctl_flush_op_t);
WORD32 status = ih264d_api_function(m_codecCtx, &s_video_flush_ip, &s_video_flush_op);
if (status != 0)
cemuLog_log(LogType::Force, "H264Dec: Unexpected error during flush ({})", status);
// get all frames from the decoder
while (true)
{
ivd_video_decode_ip_t s_dec_ip{ 0 };
ivd_video_decode_op_t s_dec_op{ 0 };
s_dec_ip.u4_size = sizeof(ivd_video_decode_ip_t);
s_dec_op.u4_size = sizeof(ivd_video_decode_op_t);
s_dec_ip.e_cmd = IVD_CMD_VIDEO_DECODE;
s_dec_ip.pv_stream_buffer = NULL;
s_dec_ip.u4_num_Bytes = 0;
s_dec_ip.s_out_buffer.u4_min_out_buf_size[0] = 0;
s_dec_ip.s_out_buffer.u4_min_out_buf_size[1] = 0;
s_dec_ip.s_out_buffer.u4_num_bufs = 0;
status = ih264d_api_function(m_codecCtx, &s_dec_ip, &s_dec_op);
if (status != 0)
break;
cemu_assert_debug(s_dec_op.u4_output_present != 0); // should never be false?
if(s_dec_op.u4_output_present == 0)
continue;
if (H264_IsBotW())
{
if (s_dec_op.s_disp_frm_buf.u4_y_wd == 1920 && s_dec_op.s_disp_frm_buf.u4_y_ht == 1088)
s_dec_op.s_disp_frm_buf.u4_y_ht = 1080;
}
PushDecodedFrame(s_dec_op);
}
}
void CopyImageToResultBuffer(uint8* yIn, uint8* uvIn, uint8* bufOut, ivd_video_decode_op_t& decodeInfo)
{
uint32 imageWidth = decodeInfo.s_disp_frm_buf.u4_y_wd;
uint32 imageHeight = decodeInfo.s_disp_frm_buf.u4_y_ht;
size_t inputStride = decodeInfo.s_disp_frm_buf.u4_y_strd;
size_t outputStride = (imageWidth + 0xFF) & ~0xFF;
// copy Y
uint8* yOut = bufOut;
for (uint32 row = 0; row < imageHeight; row++)
{
memcpy(yOut, yIn, imageWidth);
yIn += inputStride;
yOut += outputStride;
}
// copy UV
uint8* uvOut = bufOut + outputStride * imageHeight;
for (uint32 row = 0; row < imageHeight/2; row++)
{
memcpy(uvOut, uvIn, imageWidth);
uvIn += inputStride;
uvOut += outputStride;
}
}
private:
void SetDecoderCoreCount(uint32 coreCount)
{
ih264d_ctl_set_num_cores_ip_t s_set_cores_ip;
ih264d_ctl_set_num_cores_op_t s_set_cores_op;
s_set_cores_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_set_cores_ip.e_sub_cmd = (IVD_CONTROL_API_COMMAND_TYPE_T)IH264D_CMD_CTL_SET_NUM_CORES;
s_set_cores_ip.u4_num_cores = coreCount; // valid numbers are 1-4
s_set_cores_ip.u4_size = sizeof(ih264d_ctl_set_num_cores_ip_t);
s_set_cores_op.u4_size = sizeof(ih264d_ctl_set_num_cores_op_t);
IV_API_CALL_STATUS_T status = ih264d_api_function(m_codecCtx, (void *)&s_set_cores_ip, (void *)&s_set_cores_op);
cemu_assert(status == IV_SUCCESS);
}
bool DetermineBufferSizes(void* data, uint32 length, uint32& numByteConsumed)
{
numByteConsumed = 0;
UpdateParameters(true);
ivd_video_decode_ip_t s_dec_ip{ 0 };
ivd_video_decode_op_t s_dec_op{ 0 };
s_dec_ip.u4_size = sizeof(ivd_video_decode_ip_t);
s_dec_op.u4_size = sizeof(ivd_video_decode_op_t);
s_dec_ip.e_cmd = IVD_CMD_VIDEO_DECODE;
s_dec_ip.pv_stream_buffer = (uint8*)data;
s_dec_ip.u4_num_Bytes = length;
s_dec_ip.s_out_buffer.u4_num_bufs = 0;
WORD32 status = ih264d_api_function(m_codecCtx, &s_dec_ip, &s_dec_op);
if (status != 0)
{
cemuLog_log(LogType::Force, "H264: Unable to determine buffer sizes for stream");
return false;
}
numByteConsumed = s_dec_op.u4_num_bytes_consumed;
cemu_assert(status == 0);
if (s_dec_op.u4_pic_wd == 0 || s_dec_op.u4_pic_ht == 0)
return false;
UpdateParameters(false);
ReinitBuffers();
return true;
}
void ReinitBuffers()
{
ivd_ctl_getbufinfo_ip_t s_ctl_ip{ 0 };
ivd_ctl_getbufinfo_op_t s_ctl_op{ 0 };
WORD32 outlen = 0;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_GETBUFINFO;
s_ctl_ip.u4_size = sizeof(ivd_ctl_getbufinfo_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_getbufinfo_op_t);
WORD32 status = ih264d_api_function(m_codecCtx, &s_ctl_ip, &s_ctl_op);
cemu_assert(!status);
// allocate
for (uint32 i = 0; i < s_ctl_op.u4_num_disp_bufs; i++)
{
m_displayBuf.emplace_back().resize(s_ctl_op.u4_min_out_buf_size[0] + s_ctl_op.u4_min_out_buf_size[1]);
}
// set
ivd_set_display_frame_ip_t s_set_display_frame_ip{ 0 }; // make sure to zero-initialize this. The codec seems to check the first 3 pointers/sizes per frame, regardless of the value of u4_num_bufs
ivd_set_display_frame_op_t s_set_display_frame_op{ 0 };
s_set_display_frame_ip.e_cmd = IVD_CMD_SET_DISPLAY_FRAME;
s_set_display_frame_ip.u4_size = sizeof(ivd_set_display_frame_ip_t);
s_set_display_frame_op.u4_size = sizeof(ivd_set_display_frame_op_t);
cemu_assert_debug(s_ctl_op.u4_min_num_out_bufs == 2);
cemu_assert_debug(s_ctl_op.u4_min_out_buf_size[0] != 0 && s_ctl_op.u4_min_out_buf_size[1] != 0);
s_set_display_frame_ip.num_disp_bufs = s_ctl_op.u4_num_disp_bufs;
for (uint32 i = 0; i < s_ctl_op.u4_num_disp_bufs; i++)
{
s_set_display_frame_ip.s_disp_buffer[i].u4_num_bufs = 2;
s_set_display_frame_ip.s_disp_buffer[i].u4_min_out_buf_size[0] = s_ctl_op.u4_min_out_buf_size[0];
s_set_display_frame_ip.s_disp_buffer[i].u4_min_out_buf_size[1] = s_ctl_op.u4_min_out_buf_size[1];
s_set_display_frame_ip.s_disp_buffer[i].pu1_bufs[0] = m_displayBuf[i].data() + 0;
s_set_display_frame_ip.s_disp_buffer[i].pu1_bufs[1] = m_displayBuf[i].data() + s_ctl_op.u4_min_out_buf_size[0];
}
status = ih264d_api_function(m_codecCtx, &s_set_display_frame_ip, &s_set_display_frame_op);
cemu_assert(!status);
// mark all as released (available)
for (uint32 i = 0; i < s_ctl_op.u4_num_disp_bufs; i++)
{
ivd_rel_display_frame_ip_t s_video_rel_disp_ip{ 0 };
ivd_rel_display_frame_op_t s_video_rel_disp_op{ 0 };
s_video_rel_disp_ip.e_cmd = IVD_CMD_REL_DISPLAY_FRAME;
s_video_rel_disp_ip.u4_size = sizeof(ivd_rel_display_frame_ip_t);
s_video_rel_disp_op.u4_size = sizeof(ivd_rel_display_frame_op_t);
s_video_rel_disp_ip.u4_disp_buf_id = i;
status = ih264d_api_function(m_codecCtx, &s_video_rel_disp_ip, &s_video_rel_disp_op);
cemu_assert(!status);
}
}
void ResetDecoder()
{
ivd_ctl_reset_ip_t s_ctl_ip;
ivd_ctl_reset_op_t s_ctl_op;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_RESET;
s_ctl_ip.u4_size = sizeof(ivd_ctl_reset_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_reset_op_t);
WORD32 status = ih264d_api_function(m_codecCtx, (void*)&s_ctl_ip, (void*)&s_ctl_op);
cemu_assert_debug(status == 0);
}
void UpdateParameters(bool headerDecodeOnly)
{
ih264d_ctl_set_config_ip_t s_h264d_ctl_ip{ 0 };
ih264d_ctl_set_config_op_t s_h264d_ctl_op{ 0 };
ivd_ctl_set_config_ip_t* ps_ctl_ip = &s_h264d_ctl_ip.s_ivd_ctl_set_config_ip_t;
ivd_ctl_set_config_op_t* ps_ctl_op = &s_h264d_ctl_op.s_ivd_ctl_set_config_op_t;
ps_ctl_ip->u4_disp_wd = 0;
ps_ctl_ip->e_frm_skip_mode = IVD_SKIP_NONE;
ps_ctl_ip->e_frm_out_mode = m_isBufferedMode ? IVD_DISPLAY_FRAME_OUT : IVD_DECODE_FRAME_OUT;
ps_ctl_ip->e_vid_dec_mode = headerDecodeOnly ? IVD_DECODE_HEADER : IVD_DECODE_FRAME;
ps_ctl_ip->e_cmd = IVD_CMD_VIDEO_CTL;
ps_ctl_ip->e_sub_cmd = IVD_CMD_CTL_SETPARAMS;
ps_ctl_ip->u4_size = sizeof(ih264d_ctl_set_config_ip_t);
ps_ctl_op->u4_size = sizeof(ih264d_ctl_set_config_op_t);
WORD32 status = ih264d_api_function(m_codecCtx, &s_h264d_ctl_ip, &s_h264d_ctl_op);
cemu_assert(status == 0);
}
private:
void DecoderThread()
{
while(!m_threadShouldExit)
{
m_decodeSem.decrementWithWait();
std::unique_lock _l(m_decodeQueueMtx);
if (m_decodeQueue.empty())
continue;
uint32 decodeIndex = m_decodeQueue.front();
m_decodeQueue.erase(m_decodeQueue.begin());
_l.unlock();
if(decodeIndex == CMD_FLUSH)
{
Flush();
_l.lock();
cemu_assert_debug(m_decodeQueue.empty()); // after flushing the queue should be empty since the sender is waiting for the flush to complete
_l.unlock();
coreinit::OSSignalEvent(m_flushEvt);
}
else
{
auto& decodedSlice = m_decodedSliceArray[decodeIndex];
Decode(decodedSlice);
}
}
}
iv_obj_t* m_codecCtx{nullptr};
bool m_hasBufferSizeInfo{ false };
bool m_isBufferedMode{ false };
uint32 m_numDecodedFrames{0};
std::vector<std::vector<uint8>> m_displayBuf;
std::thread m_decoderThread;
std::atomic_bool m_threadShouldExit{false};
};
H264DecoderBackend* CreateAVCDecoder()
{
return new H264AVCDecoder();
}
};
| 17,555
|
C++
|
.cpp
| 433
| 36.307159
| 198
| 0.677887
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,046
|
H264Dec.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/h264_avc/H264Dec.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/h264_avc/parser/H264Parser.h"
#include "Cafe/OS/libs/h264_avc/H264DecInternal.h"
#include "util/highresolutiontimer/HighResolutionTimer.h"
#include "Cafe/CafeSystem.h"
#include "h264dec.h"
enum class H264DEC_STATUS : uint32
{
SUCCESS = 0x0,
BAD_STREAM = 0x1000000,
INVALID_PARAM = 0x1010000,
};
namespace H264
{
bool H264_IsBotW()
{
// Cemuhook has a hack where it always returns a small size for H264DECMemoryRequirement (256 bytes)
// it also outputs images pre-cropped instead of giving the game raw uncropped images
// both of these are required to allow Breath of the Wild to playback the higher res (1080p) videos from the Switch version
// we mirror these hacks for user convenience and because there are no downsides
uint64 currentTitleId = CafeSystem::GetForegroundTitleId();
if (currentTitleId == 0x00050000101c9500 || currentTitleId == 0x00050000101c9400 || currentTitleId == 0x00050000101c9300)
return true;
return false;
}
struct H264Context
{
struct
{
MEMPTR<void> ptr{ nullptr };
uint32be length{ 0 };
float64be timestamp;
}BitStream;
struct
{
MEMPTR<void> outputFunc{ nullptr };
uint8be outputPerFrame{ 0 }; // whats the default?
MEMPTR<void> userMemoryParam{ nullptr };
}Param;
// misc
uint32be sessionHandle;
// decoder state
struct
{
uint32 numFramesInFlight{0};
}decoderState;
};
uint32 H264DECMemoryRequirement(uint32 codecProfile, uint32 codecLevel, uint32 width, uint32 height, uint32be* sizeRequirementOut)
{
if (H264_IsBotW())
{
static_assert(sizeof(H264Context) < 256);
*sizeRequirementOut = 256;
return 0;
}
// note: On console this seems to check if maxWidth or maxHeight < 64 but Pikmin 3 passes 32x32 and crashes if this function fails ?
if (width < 0x20 || height < 0x20 || width > 2800 || height > 1408 || sizeRequirementOut == MPTR_NULL || codecLevel >= 52 || (codecProfile != 0x42 && codecProfile != 0x4D && codecProfile != 0x64))
return 0x1010000;
uint32 workbufferSize = 0;
if (codecLevel < 0xB)
{
workbufferSize = 0x18C << 10;
}
else if (codecLevel == 0xB)
{
workbufferSize = 0x384 << 10;
}
else if (codecLevel >= 0xC && codecLevel <= 0x14)
{
workbufferSize = 0x948 << 10;
}
else if (codecLevel == 0x15)
{
workbufferSize = 0x1290 << 10;
}
else if (codecLevel >= 0x16 && codecLevel <= 0x1E)
{
workbufferSize = 0x1FA4 << 10;
}
else if (codecLevel == 0x1F)
{
workbufferSize = 0x4650 << 10;
}
else if (codecLevel == 0x20)
{
workbufferSize = 0x1400000;
}
else if (codecLevel >= 0x21 && codecLevel <= 0x29)
{
workbufferSize = 0x8000 << 10;
}
else if (codecLevel == 0x2A)
{
workbufferSize = 0x2200000;
}
else if (codecLevel >= 0x2B && codecLevel <= 0x32)
{
workbufferSize = 0x1AF40 << 10;
}
else if (codecLevel >= 0x33)
{
workbufferSize = 0x2D000 << 10;
}
workbufferSize += 0x447;
*sizeRequirementOut = workbufferSize;
return 0;
}
uint32 H264DECCheckMemSegmentation(MPTR memory, uint32 size)
{
// return 0 for valid, 1 for invalid
// currently we allow any range
return 0;
}
H264DEC_STATUS H264DECFindDecstartpoint(uint8* ptr, uint32 length, uint32be* offsetOut)
{
if (!ptr || length < 4 || !offsetOut)
return H264DEC_STATUS::INVALID_PARAM;
for (uint32 i = 0; i < length - 4; ++i)
{
uint8 b = ptr[i];
if (b != 0)
continue;
b = ptr[i + 1];
if (b != 0)
continue;
b = ptr[i + 2];
if (b != 1)
continue;
b = ptr[i + 3];
b &= 0x9F;
if (b != 7) // check for NAL type SPS
continue;
if (i > 0)
*offsetOut = i - 1;
else
*offsetOut = 0;
return H264DEC_STATUS::SUCCESS;
}
return H264DEC_STATUS::BAD_STREAM;
}
H264DEC_STATUS H264DECFindIdrpoint(uint8* ptr, uint32 length, uint32be* offsetOut)
{
if (!ptr || length < 4 || !offsetOut)
return H264DEC_STATUS::INVALID_PARAM;
for (uint32 i = 0; i < length - 4; ++i)
{
uint8 b = ptr[i];
if (b != 0)
continue;
b = ptr[i + 1];
if (b != 0)
continue;
b = ptr[i + 2];
if (b != 1)
continue;
b = ptr[i + 3];
b &= 0x9F;
if (b != 5 && b != 7 && b != 8) // check for NAL type IDR slice, but also accept SPS or PPS slices
continue;
if (i > 0)
*offsetOut = i - 1;
else
*offsetOut = 0;
return H264DEC_STATUS::SUCCESS;
}
return H264DEC_STATUS::BAD_STREAM;
}
H264DEC_STATUS H264DECGetImageSize(uint8* stream, uint32 length, uint32 offset, uint32be* outputWidth, uint32be* outputHeight)
{
if(!stream || length < 4 || !outputWidth || !outputHeight)
return H264DEC_STATUS::INVALID_PARAM;
if( (offset+4) > length )
return H264DEC_STATUS::INVALID_PARAM;
uint8* cur = stream + offset;
uint8* end = stream + length;
cur += 2; // we access cur[-2] and cur[-1] so we need to start at offset 2
while(cur < end-2)
{
// check for start code
if(*cur != 1)
{
cur++;
continue;
}
// check if this is a valid NAL header
if(cur[-2] != 0 || cur[-1] != 0 || cur[0] != 1)
{
cur++;
continue;
}
uint8 nalHeader = cur[1];
if((nalHeader & 0x1F) != 7)
{
cur++;
continue;
}
h264State_seq_parameter_set_t psp;
bool r = h264Parser_ParseSPS(cur+2, end-cur-2, psp);
if(!r)
{
cemu_assert_suspicious(); // should not happen
return H264DEC_STATUS::BAD_STREAM;
}
*outputWidth = (psp.pic_width_in_mbs_minus1 + 1) * 16;
*outputHeight = (psp.pic_height_in_map_units_minus1 + 1) * 16; // affected by frame_mbs_only_flag?
return H264DEC_STATUS::SUCCESS;
}
return H264DEC_STATUS::BAD_STREAM;
}
uint32 H264DECInitParam(uint32 workMemorySize, void* workMemory)
{
H264Context* ctx = (H264Context*)workMemory;
*ctx = {};
return 0;
}
std::unordered_map<uint32, H264DecoderBackend*> sDecoderSessions;
std::mutex sDecoderSessionsMutex;
std::atomic_uint32_t sCurrentSessionHandle{ 1 };
H264DecoderBackend* CreateAVCDecoder();
static H264DecoderBackend* _CreateDecoderSession(uint32& handleOut)
{
std::unique_lock _lock(sDecoderSessionsMutex);
handleOut = sCurrentSessionHandle.fetch_add(1);
H264DecoderBackend* session = CreateAVCDecoder();
sDecoderSessions.try_emplace(handleOut, session);
return session;
}
static H264DecoderBackend* _AcquireDecoderSession(uint32 handle)
{
std::unique_lock _lock(sDecoderSessionsMutex);
auto it = sDecoderSessions.find(handle);
if (it == sDecoderSessions.end())
return nullptr;
H264DecoderBackend* session = it->second;
if (sDecoderSessions.size() >= 5)
{
cemuLog_log(LogType::Force, "H264: Warning - more than 5 active sessions");
cemu_assert_suspicious();
}
return session;
}
static void _ReleaseDecoderSession(H264DecoderBackend* session)
{
std::unique_lock _lock(sDecoderSessionsMutex);
}
static void _DestroyDecoderSession(uint32 handle)
{
std::unique_lock _lock(sDecoderSessionsMutex);
auto it = sDecoderSessions.find(handle);
if (it == sDecoderSessions.end())
return;
H264DecoderBackend* session = it->second;
session->Destroy();
delete session;
sDecoderSessions.erase(it);
}
uint32 H264DECOpen(void* workMemory)
{
H264Context* ctx = (H264Context*)workMemory;
uint32 sessionHandle;
_CreateDecoderSession(sessionHandle);
ctx->sessionHandle = sessionHandle;
return 0;
}
uint32 H264DECClose(void* workMemory)
{
if (workMemory)
{
H264Context* ctx = (H264Context*)workMemory;
_DestroyDecoderSession(ctx->sessionHandle);
}
return 0;
}
uint32 H264DECBegin(void* workMemory)
{
H264Context* ctx = (H264Context*)workMemory;
H264DecoderBackend* session = _AcquireDecoderSession(ctx->sessionHandle);
if (!session)
{
cemuLog_log(LogType::Force, "H264DECBegin(): Invalid session");
return 0;
}
session->Init(ctx->Param.outputPerFrame == 0);
ctx->decoderState.numFramesInFlight = 0;
_ReleaseDecoderSession(session);
return 0;
}
void H264DoFrameOutputCallback(H264Context* ctx, H264DecoderBackend::DecodeResult& decodeResult);
H264DEC_STATUS H264DECEnd(void* workMemory)
{
H264Context* ctx = (H264Context*)workMemory;
H264DecoderBackend* session = _AcquireDecoderSession(ctx->sessionHandle);
if (!session)
{
cemuLog_log(LogType::Force, "H264DECEnd(): Invalid session");
return H264DEC_STATUS::SUCCESS;
}
coreinit::OSEvent* flushEvt = &session->GetFlushEvent();
coreinit::OSResetEvent(flushEvt);
session->QueueFlush();
coreinit::OSWaitEvent(flushEvt);
while(true)
{
H264DecoderBackend::DecodeResult decodeResult;
if( !session->GetFrameOutputIfReady(decodeResult) )
break;
// todo - output all frames in a single callback?
H264DoFrameOutputCallback(ctx, decodeResult);
ctx->decoderState.numFramesInFlight--;
}
cemu_assert_debug(ctx->decoderState.numFramesInFlight == 0); // no frames should be in flight anymore. Exact behavior is not well understood but we may have to output dummy frames if necessary
_ReleaseDecoderSession(session);
return H264DEC_STATUS::SUCCESS;
}
H264DEC_STATUS H264DECSetParam_FPTR_OUTPUT(H264Context* ctx, void* outputFunc)
{
ctx->Param.outputFunc = outputFunc;
return H264DEC_STATUS::SUCCESS;
}
H264DEC_STATUS H264DECSetParam_OUTPUT_PER_FRAME(H264Context* ctx, uint32 outputPerFrame)
{
ctx->Param.outputPerFrame = outputPerFrame != 0 ? 1 : 0;
return H264DEC_STATUS::SUCCESS;
}
H264DEC_STATUS H264DECSetParam_USER_MEMORY(H264Context* ctx, MEMPTR<void*>* userMemoryParamPtr)
{
ctx->Param.userMemoryParam = *userMemoryParamPtr;
return H264DEC_STATUS::SUCCESS;
}
H264DEC_STATUS H264DECSetParam(H264Context* ctx, uint32 paramId, void* paramValue)
{
const uint32 PARAMID_FPTR_OUTPUT = 0x1;
const uint32 PARAMID_OUTPUT_PER_FRAME = 0x20000002;
const uint32 PARAMID_USER_MEMORY = 0x70000001;
const uint32 PARAMID_UKN = 0x20000030;
if (paramId == PARAMID_FPTR_OUTPUT)
{
ctx->Param.outputFunc = paramValue;
}
else if (paramId == PARAMID_USER_MEMORY)
{
ctx->Param.userMemoryParam = paramValue;
}
else if (paramId == PARAMID_OUTPUT_PER_FRAME)
{
ctx->Param.outputPerFrame = *(uint8be*)paramValue != 0;
}
else if (paramId == PARAMID_UKN)
{
// unknown purpose, seen in MK8. paramValue points to a bool
}
else
{
cemuLog_log(LogType::Force, "h264Export_H264DECSetParam(): Unsupported parameterId 0x{:08x}\n", paramId);
cemu_assert_unimplemented();
}
return H264DEC_STATUS::SUCCESS;
}
uint32 H264DECSetBitstream(void* workMemory, void* ptr, uint32 length, double timestamp)
{
H264Context* ctx = (H264Context*)workMemory;
ctx->BitStream.ptr = ptr;
ctx->BitStream.length = length;
ctx->BitStream.timestamp = timestamp;
return 0;
}
struct H264DECFrameOutput
{
/* +0x00 */ uint32be result;
/* +0x04 */ uint32be padding04;
/* +0x08 */ betype<double> timestamp;
/* +0x10 */ uint32be frameWidth;
/* +0x14 */ uint32be frameHeight;
/* +0x18 */ uint32be bytesPerRow;
/* +0x1C */ uint32be cropEnable;
/* +0x20 */ uint32be cropTop;
/* +0x24 */ uint32be cropBottom;
/* +0x28 */ uint32be cropLeft;
/* +0x2C */ uint32be cropRight;
/* +0x30 */ uint32be ukn30;
/* +0x34 */ uint32be ukn34;
/* +0x38 */ uint32be ukn38;
/* +0x3C */ uint32be ukn3C;
/* +0x40 */ uint32be ukn40;
/* +0x44 */ MEMPTR<uint8> imagePtr;
/* +0x48 */ uint32 vuiEnable;
/* +0x4C */ MPTR vuiPtr;
/* +0x50 */ sint32 unused[10];
};
struct H264OutputCBStruct
{
uint32be frameCount;
MEMPTR<MEMPTR<H264DECFrameOutput>> resultArray;
uint32be userParam;
};
static_assert(sizeof(H264OutputCBStruct) == 12);
void H264DoFrameOutputCallback(H264Context* ctx, H264DecoderBackend::DecodeResult& decodeResult)
{
sint32 outputFrameCount = 1;
cemu_assert(outputFrameCount < 8);
StackAllocator<MEMPTR<void>, 8> stack_resultPtrArray;
StackAllocator<H264DECFrameOutput, 8> stack_decodedFrameResult;
for (sint32 i = 0; i < outputFrameCount; i++)
stack_resultPtrArray[i] = &stack_decodedFrameResult + i;
H264DECFrameOutput* frameOutput = &stack_decodedFrameResult + 0;
memset(frameOutput, 0x00, sizeof(H264DECFrameOutput));
frameOutput->imagePtr = (uint8*)decodeResult.imageOutput;
frameOutput->result = 100;
frameOutput->timestamp = decodeResult.timestamp;
frameOutput->frameWidth = decodeResult.frameWidth;
frameOutput->frameHeight = decodeResult.frameHeight;
frameOutput->bytesPerRow = decodeResult.bytesPerRow;
frameOutput->cropEnable = decodeResult.cropEnable;
frameOutput->cropTop = decodeResult.cropTop;
frameOutput->cropBottom = decodeResult.cropBottom;
frameOutput->cropLeft = decodeResult.cropLeft;
frameOutput->cropRight = decodeResult.cropRight;
StackAllocator<H264OutputCBStruct> stack_fptrOutputData;
stack_fptrOutputData->frameCount = outputFrameCount;
stack_fptrOutputData->resultArray = (MEMPTR<H264DECFrameOutput>*)stack_resultPtrArray.GetPointer();
stack_fptrOutputData->userParam = ctx->Param.userMemoryParam.GetBEValue();
// FPTR callback
if (!ctx->Param.outputFunc.IsNull())
{
cemuLog_log(LogType::H264, "H264: Outputting frame via callback. Timestamp: {} Buffer 0x{:08x} UserParam 0x{:08x}", (double)decodeResult.timestamp, (uint32)frameOutput->imagePtr.GetMPTR(), ctx->Param.userMemoryParam.GetMPTR());
PPCCoreCallback(ctx->Param.outputFunc.GetMPTR(), stack_fptrOutputData.GetMPTR());
}
}
uint32 H264DECExecute(void* workMemory, void* imageOutput)
{
BenchmarkTimer bt;
bt.Start();
H264Context* ctx = (H264Context*)workMemory;
H264DecoderBackend* session = _AcquireDecoderSession(ctx->sessionHandle);
if (!session)
{
cemuLog_log(LogType::Force, "H264DECExecute(): Invalid session");
return 0;
}
// feed data to backend
session->QueueForDecode((uint8*)ctx->BitStream.ptr.GetPtr(), ctx->BitStream.length, ctx->BitStream.timestamp, imageOutput);
ctx->decoderState.numFramesInFlight++;
// H264DECExecute is synchronous and will return a frame after either every call (non-buffered) or after 6 calls (buffered)
// normally frame decoding happens only during H264DECExecute, but in order to hide the latency of our CPU decoder we will decode asynchronously in buffered mode
uint32 numFramesToBuffer = (ctx->Param.outputPerFrame == 0) ? 5 : 0;
if(ctx->decoderState.numFramesInFlight > numFramesToBuffer)
{
ctx->decoderState.numFramesInFlight--;
while(true)
{
coreinit::OSEvent& evt = session->GetFrameOutputEvent();
coreinit::OSWaitEvent(&evt);
H264DecoderBackend::DecodeResult decodeResult;
if( !session->GetFrameOutputIfReady(decodeResult) )
continue;
H264DoFrameOutputCallback(ctx, decodeResult);
break;
}
}
_ReleaseDecoderSession(session);
bt.Stop();
double callTime = bt.GetElapsedMilliseconds();
cemuLog_log(LogType::H264, "H264Bench | H264DECExecute took {}ms", callTime);
return 0x80 | 100;
}
H264DEC_STATUS H264DECCheckDecunitLength(void* workMemory, uint8* data, uint32 maxLength, uint32 offset, uint32be* unitLengthOut)
{
// todo: our implementation for this currently doesn't parse slice headers and instead assumes that each frame is encoded into a single NAL slice. For all known cases this is sufficient but it doesn't match console behavior for cases where frames are split into multiple NALs
if (offset >= maxLength || maxLength < 4)
{
return H264DEC_STATUS::INVALID_PARAM;
}
data += offset;
maxLength -= offset;
NALInputBitstream nalStream(data, maxLength);
if (nalStream.hasError())
{
cemu_assert_debug(false);
return H264DEC_STATUS::BAD_STREAM;
}
// search for start code
sint32 startCodeOffset = 0;
bool hasStartcode = false;
while (startCodeOffset < (sint32)(maxLength - 3))
{
if (data[startCodeOffset + 0] == 0x00 && data[startCodeOffset + 1] == 0x00 && data[startCodeOffset + 2] == 0x01)
{
hasStartcode = true;
break;
}
startCodeOffset++;
}
if (hasStartcode == false)
return H264DEC_STATUS::BAD_STREAM;
data += startCodeOffset;
maxLength -= startCodeOffset;
// parse NAL data
while (true)
{
if (nalStream.isEndOfStream())
break;
RBSPInputBitstream rbspStream;
if (nalStream.getNextRBSP(rbspStream, true) == false)
break;
sint32 streamSubOffset = (sint32)(rbspStream.getBasePtr() - data);
sint32 streamSubLength = rbspStream.getBaseLength();
// parse NAL header
uint8 nalHeaderByte = rbspStream.readU8();
if ((nalHeaderByte & 0x80) != 0)
{
// MSB must be zero
cemu_assert_debug(false);
continue;
}
uint8 nal_ref_idc = (nalHeaderByte >> 5) & 0x3;
uint8 nal_unit_type = (nalHeaderByte >> 0) & 0x1f;
if (nal_unit_type == 14 || nal_unit_type == 20 || nal_unit_type == 21)
{
cemu_assert_debug(false);
continue;
}
switch (nal_unit_type)
{
case 1:
case 5:
{
*unitLengthOut = (sint32)((rbspStream.getBasePtr() + rbspStream.getBaseLength()) - data) + startCodeOffset;
return H264DEC_STATUS::SUCCESS;
}
case 6:
// SEI
break;
case 7:
// SPS
break;
case 8:
// PPS
break;
case 9:
// access unit delimiter
break;
case 10:
// end of sequence
break;
default:
cemuLog_logDebug(LogType::Force, "Unsupported NAL unit type {}", nal_unit_type);
cemu_assert_unimplemented();
// todo
break;
}
}
return H264DEC_STATUS::BAD_STREAM;
}
void Initialize()
{
cafeExportRegister("h264", H264DECCheckMemSegmentation, LogType::H264);
cafeExportRegister("h264", H264DECMemoryRequirement, LogType::H264);
cafeExportRegister("h264", H264DECFindDecstartpoint, LogType::H264);
cafeExportRegister("h264", H264DECFindIdrpoint, LogType::H264);
cafeExportRegister("h264", H264DECGetImageSize, LogType::H264);
cafeExportRegister("h264", H264DECInitParam, LogType::H264);
cafeExportRegister("h264", H264DECOpen, LogType::H264);
cafeExportRegister("h264", H264DECClose, LogType::H264);
cafeExportRegister("h264", H264DECBegin, LogType::H264);
cafeExportRegister("h264", H264DECEnd, LogType::H264);
cafeExportRegister("h264", H264DECSetParam_FPTR_OUTPUT, LogType::H264);
cafeExportRegister("h264", H264DECSetParam_OUTPUT_PER_FRAME, LogType::H264);
cafeExportRegister("h264", H264DECSetParam_USER_MEMORY, LogType::H264);
cafeExportRegister("h264", H264DECSetParam, LogType::H264);
cafeExportRegister("h264", H264DECSetBitstream, LogType::H264);
cafeExportRegister("h264", H264DECExecute, LogType::H264);
cafeExportRegister("h264", H264DECCheckDecunitLength, LogType::H264);
}
}
| 18,580
|
C++
|
.cpp
| 575
| 28.970435
| 277
| 0.720395
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,047
|
H264Parser.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/h264_avc/parser/H264Parser.cpp
|
#include "Cafe/OS/libs/h264_avc/parser/H264Parser.h"
void parse_hrd_parameters(h264ParserState_t* h264ParserState, RBSPInputBitstream& nalStream)
{
uint32 cpb_cnt_minus1 = nalStream.readUV_E();
uint8 bit_rate_scale = nalStream.readBits<4>();
uint8 cpb_size_scale = nalStream.readBits<4>();
for (uint8 schedSelIdx = 0; schedSelIdx <= cpb_cnt_minus1; schedSelIdx++)
{
uint32 bit_rate_value_minus1 = nalStream.readUV_E();
uint32 cpb_size_value_minus1 = nalStream.readUV_E();
uint8 cbr_flag = nalStream.readBit();
}
uint8 initial_cpb_removal_delay_length_minus1 = nalStream.readBits<5>();
uint8 cpb_removal_delay_length_minus1 = nalStream.readBits<5>();
uint8 dpb_output_delay_length_minus1 = nalStream.readBits<5>();
uint8 time_offset_length = nalStream.readBits<5>();
}
void parseNAL_scaling_list4x4(RBSPInputBitstream& rbspStream, h264_scaling_matrix4x4_t& scalingMatrix4x4)
{
if (rbspStream.readBit() == 0)
{
scalingMatrix4x4.isPresent = 0;
return;
}
scalingMatrix4x4.isPresent = 1;
cemu_assert_debug(false); // needs testing
sint32 lastScale = 8;
sint32 nextScale = 8;
for (sint32 j = 0; j < 4 * 4; j++)
{
if (nextScale != 0)
{
sint32 delta_scale = rbspStream.readSV_E();
nextScale = (lastScale + delta_scale + 256) % 256;
scalingMatrix4x4.UseDefaultScalingMatrix = (j == 0 && nextScale == 0);
}
scalingMatrix4x4.list[j] = (nextScale == 0) ? lastScale : nextScale;
lastScale = scalingMatrix4x4.list[j];
}
}
void parseNAL_scaling_list8x8(RBSPInputBitstream& rbspStream, h264_scaling_matrix8x8_t& scalingMatrix8x8)
{
if (rbspStream.readBit() == 0)
{
scalingMatrix8x8.isPresent = 0;
return;
}
scalingMatrix8x8.isPresent = 1;
cemu_assert_debug(false); // needs testing
sint32 lastScale = 8;
sint32 nextScale = 8;
for (sint32 j = 0; j < 8 * 8; j++)
{
if (nextScale != 0)
{
sint32 delta_scale = rbspStream.readSV_E();
nextScale = (lastScale + delta_scale + 256) % 256;
scalingMatrix8x8.UseDefaultScalingMatrix = (j == 0 && nextScale == 0);
}
scalingMatrix8x8.list[j] = (nextScale == 0) ? lastScale : nextScale;
lastScale = scalingMatrix8x8.list[j];
}
}
void parseNAL_pps_scaling_lists(h264ParserState_t* h264ParserState, RBSPInputBitstream& nalStream)
{
parseNAL_scaling_list4x4(nalStream, h264ParserState->pps.ScalingList4x4[0]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->pps.ScalingList4x4[1]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->pps.ScalingList4x4[2]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->pps.ScalingList4x4[3]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->pps.ScalingList4x4[4]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->pps.ScalingList4x4[5]);
if (h264ParserState->pps.transform_8x8_mode_flag)
{
parseNAL_scaling_list8x8(nalStream, h264ParserState->pps.ScalingList8x8[0]);
parseNAL_scaling_list8x8(nalStream, h264ParserState->pps.ScalingList8x8[1]);
if (h264ParserState->sps.chroma_format_idc == 3)
cemu_assert(false); // todo - more scaling lists to parse
}
}
void parseNAL_sps_scaling_lists(h264ParserState_t* h264ParserState, RBSPInputBitstream& nalStream)
{
parseNAL_scaling_list4x4(nalStream, h264ParserState->sps.ScalingList4x4[0]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->sps.ScalingList4x4[1]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->sps.ScalingList4x4[2]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->sps.ScalingList4x4[3]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->sps.ScalingList4x4[4]);
parseNAL_scaling_list4x4(nalStream, h264ParserState->sps.ScalingList4x4[5]);
parseNAL_scaling_list8x8(nalStream, h264ParserState->sps.ScalingList8x8[0]);
parseNAL_scaling_list8x8(nalStream, h264ParserState->sps.ScalingList8x8[1]);
if (h264ParserState->sps.chroma_format_idc == 3)
cemu_assert(false); // todo - more scaling lists to parse
}
bool parseNAL_seq_parameter_set_rbsp(h264ParserState_t* h264ParserState, h264ParserOutput_t* output, RBSPInputBitstream& nalStream)
{
memset(&h264ParserState->sps, 0, sizeof(h264State_seq_parameter_set_t));
h264ParserState->sps.profile_idc = nalStream.readU8(); // 0x64 = high profile
h264ParserState->sps.constraint = nalStream.readU8(); // 6 flags + 2 reserved bits
h264ParserState->sps.level_idc = nalStream.readU8(); // 0x29 = level 4.1
// some default values in case flags are not set
h264ParserState->sps.separate_colour_plane_flag = 0;
h264ParserState->sps.chroma_format_idc = 1; // Spec 7.4.2.1.1
h264ParserState->sps.qpprime_y_zero_transform_bypass_flag = 0;
h264ParserState->sps.seq_scaling_matrix_present_flag = 0;
//h264ParserState->sps.mb_adaptive_frame_field_flag = 0;
uint32 seq_parameter_set_id = nalStream.readUV_E();
if (h264ParserState->sps.profile_idc == 100 || h264ParserState->sps.profile_idc == 110 || h264ParserState->sps.profile_idc == 122 ||
h264ParserState->sps.profile_idc == 244 || h264ParserState->sps.profile_idc == 44 || h264ParserState->sps.profile_idc == 83 ||
h264ParserState->sps.profile_idc == 86 || h264ParserState->sps.profile_idc == 118 || h264ParserState->sps.profile_idc == 128 ||
h264ParserState->sps.profile_idc == 138 || h264ParserState->sps.profile_idc == 139 || h264ParserState->sps.profile_idc == 134 || h264ParserState->sps.profile_idc == 135)
{
h264ParserState->sps.chroma_format_idc = nalStream.readUV_E();
if (h264ParserState->sps.chroma_format_idc == 3)
{
h264ParserState->sps.separate_colour_plane_flag = nalStream.readBit();
}
h264ParserState->sps.bit_depth_luma_minus8 = nalStream.readUV_E();
h264ParserState->sps.bit_depth_chroma_minus8 = nalStream.readUV_E();
h264ParserState->sps.qpprime_y_zero_transform_bypass_flag = nalStream.readBit();
h264ParserState->sps.seq_scaling_matrix_present_flag = nalStream.readBit();
if (h264ParserState->sps.seq_scaling_matrix_present_flag)
{
parseNAL_sps_scaling_lists(h264ParserState, nalStream);
}
}
h264ParserState->sps.log2_max_frame_num_minus4 = nalStream.readUV_E();
h264ParserState->sps.pic_order_cnt_type = nalStream.readUV_E();
if (h264ParserState->sps.pic_order_cnt_type == 0)
{
h264ParserState->sps.log2_max_pic_order_cnt_lsb_minus4 = nalStream.readUV_E();
}
else if (h264ParserState->sps.pic_order_cnt_type == 2)
{
// nothing to parse
}
else
{
// todo - parse fields
cemu_assert_debug(false);
}
h264ParserState->sps.num_ref_frames = nalStream.readUV_E();
h264ParserState->sps.gaps_in_frame_num_value_allowed_flag = nalStream.readBit();
h264ParserState->sps.pic_width_in_mbs_minus1 = nalStream.readUV_E();
h264ParserState->sps.pic_height_in_map_units_minus1 = nalStream.readUV_E();
h264ParserState->sps.frame_mbs_only_flag = nalStream.readBit();
if (h264ParserState->sps.frame_mbs_only_flag == 0)
{
h264ParserState->sps.mb_adaptive_frame_field_flag = nalStream.readBit();
cemu_assert_debug(false);
}
else
h264ParserState->sps.mb_adaptive_frame_field_flag = 0; // default is zero?
h264ParserState->sps.direct_8x8_inference_flag = nalStream.readBit();
if (h264ParserState->sps.frame_mbs_only_flag == 0 && h264ParserState->sps.direct_8x8_inference_flag != 1)
{
cemu_assert_debug(false); // not allowed
}
h264ParserState->sps.frame_cropping_flag = nalStream.readBit();
if (h264ParserState->sps.frame_cropping_flag)
{
h264ParserState->sps.frame_crop_left_offset = nalStream.readUV_E();
h264ParserState->sps.frame_crop_right_offset = nalStream.readUV_E();
h264ParserState->sps.frame_crop_top_offset = nalStream.readUV_E();
h264ParserState->sps.frame_crop_bottom_offset = nalStream.readUV_E();
}
uint8 vui_parameters_present_flag = nalStream.readBit();
if (vui_parameters_present_flag)
{
// vui_parameters
uint8 aspect_ratio_info_present_flag = nalStream.readBit();
if (aspect_ratio_info_present_flag)
{
uint32 aspect_ratio_idc = nalStream.readBits<8>();
if (aspect_ratio_idc == 255) // Extended_SAR
{
uint16 sar_width = nalStream.readBits<16>();
uint16 sar_height = nalStream.readBits<16>();
}
}
uint8 overscan_info_present_flag = nalStream.readBit();
if (overscan_info_present_flag)
{
cemu_assert_debug(false);
}
uint8 video_signal_type_present_flag = nalStream.readBit();
if (video_signal_type_present_flag)
{
uint8 video_format = nalStream.readBits<3>();
uint8 video_full_range_flag = nalStream.readBit();
uint8 colour_description_present_flag = nalStream.readBit();
if (colour_description_present_flag)
{
uint8 colour_primaries = nalStream.readBits<8>();
uint8 transfer_characteristics = nalStream.readBits<8>();
uint8 matrix_coefficients = nalStream.readBits<8>();
}
}
uint8 chroma_loc_info_present_flag = nalStream.readBit();
if (chroma_loc_info_present_flag)
{
uint32 chroma_sample_loc_type_top_field = nalStream.readUV_E();
uint32 chroma_sample_loc_type_bottom_field = nalStream.readUV_E();
}
uint8 timing_info_present_flag = nalStream.readBit();
if (timing_info_present_flag)
{
uint32 num_units_in_tick = nalStream.readBits<32>();
uint32 time_scale = nalStream.readBits<32>();
uint8 fixed_frame_rate_flag = nalStream.readBits<1>();
}
uint8 nal_hrd_parameters_present_flag = nalStream.readBit();
if (nal_hrd_parameters_present_flag)
{
parse_hrd_parameters(h264ParserState, nalStream);
}
uint8 vcl_hrd_parameters_present_flag = nalStream.readBit();
if (vcl_hrd_parameters_present_flag)
{
parse_hrd_parameters(h264ParserState, nalStream);
}
if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag)
{
uint8 low_delay_hrd_flag = nalStream.readBit();
}
uint8 pic_struct_present_flag = nalStream.readBit();
uint8 bitstream_restriction_flag = nalStream.readBit();
if (bitstream_restriction_flag)
{
uint8 motion_vectors_over_pic_boundaries_flag = nalStream.readBit();
uint32 max_bytes_per_pic_denom = nalStream.readUV_E();
uint32 max_bits_per_mb_denom = nalStream.readUV_E();
uint32 log2_max_mv_length_horizontal = nalStream.readUV_E();
uint32 log2_max_mv_length_vertical = nalStream.readUV_E();
uint32 max_num_reorder_frames = nalStream.readUV_E();
uint32 max_dec_frame_buffering = nalStream.readUV_E();
}
}
// trailing bits
bool nalValid = true;
if (nalStream.readTrailingRBSPBits() == false)
nalValid = false;
if (nalValid)
{
if(output)
output->hasSPS = true;
h264ParserState->hasSPS = true;
}
return true;
}
bool parseNAL_pic_parameter_set_rbsp(h264ParserState_t* h264ParserState, h264ParserOutput_t* output, RBSPInputBitstream& nalStream)
{
memset(&h264ParserState->pps, 0, sizeof(h264State_pic_parameter_set_t));
h264ParserState->pps.pic_parameter_set_id = nalStream.readUV_E();
h264ParserState->pps.seq_parameter_set_id = nalStream.readUV_E();
h264ParserState->pps.entropy_coding_mode_flag = nalStream.readBit();
h264ParserState->pps.bottom_field_pic_order_in_frame_present_flag = nalStream.readBit();
h264ParserState->pps.num_slice_groups_minus1 = nalStream.readUV_E();
if (h264ParserState->pps.num_slice_groups_minus1 > 0)
{
cemu_assert_debug(false);
return false;
}
h264ParserState->pps.num_ref_idx_l0_default_active_minus1 = nalStream.readUV_E();
h264ParserState->pps.num_ref_idx_l1_default_active_minus1 = nalStream.readUV_E();
h264ParserState->pps.weighted_pred_flag = nalStream.readBit();
h264ParserState->pps.weighted_bipred_idc = nalStream.readBits<2>();
h264ParserState->pps.pic_init_qp_minus26 = nalStream.readSV_E();
h264ParserState->pps.pic_init_qs_minus26 = nalStream.readSV_E();
h264ParserState->pps.chroma_qp_index_offset = nalStream.readSV_E();
h264ParserState->pps.deblocking_filter_control_present_flag = nalStream.readBit();
h264ParserState->pps.constrained_intra_pred_flag = nalStream.readBit();
h264ParserState->pps.redundant_pic_cnt_present_flag = nalStream.readBit();
if (nalStream.more_rbsp_data())
{
h264ParserState->pps.transform_8x8_mode_flag = nalStream.readBit();
h264ParserState->pps.pic_scaling_matrix_present_flag = nalStream.readBit();
if (h264ParserState->pps.pic_scaling_matrix_present_flag)
{
parseNAL_pps_scaling_lists(h264ParserState, nalStream);
}
h264ParserState->pps.second_chroma_qp_index_offset = nalStream.readSV_E();
}
// trailing bits
bool nalValid = true;
if (nalStream.readTrailingRBSPBits() == false)
nalValid = false;
if (nalValid)
{
if(output)
output->hasPPS = true;
h264ParserState->hasPPS = true;
}
return true;
}
bool h264Parser_ParseSPS(uint8* data, uint32 length, h264State_seq_parameter_set_t& sps)
{
h264ParserState_t parserState;
RBSPInputBitstream nalStream(data, length);
bool r = parseNAL_seq_parameter_set_rbsp(&parserState, nullptr, nalStream);
if(!r || !parserState.hasSPS)
return false;
sps = parserState.sps;
return true;
}
void parseNAL_ref_pic_list_modification(const h264State_seq_parameter_set_t& sps, const h264State_pic_parameter_set_t& pps, RBSPInputBitstream& nalStream, nal_slice_header_t* sliceHeader)
{
if (!sliceHeader->slice_type.isSliceTypeI() && !sliceHeader->slice_type.isSliceTypeSI())
{
uint8 ref_pic_list_modification_flag_l0 = nalStream.readBit();
if (ref_pic_list_modification_flag_l0)
{
sliceHeader->pic_list_modification0Count = 0;
uint32 modType;
while(true)
{
if (sliceHeader->pic_list_modification0Count >= 32)
{
cemu_assert_debug(false);
return;
}
modType = nalStream.readUV_E();
sliceHeader->pic_list_modification0Array[sliceHeader->pic_list_modification0Count].type = modType;
if (modType == 0 || modType == 1)
{
sliceHeader->pic_list_modification0Array[sliceHeader->pic_list_modification0Count].abs_diff_pic_num_minus1 = nalStream.readUV_E();
}
else if (modType == 2)
{
sliceHeader->pic_list_modification0Array[sliceHeader->pic_list_modification0Count].long_term_pic_num = nalStream.readUV_E();
}
else if (modType == 3)
{
// end of list
break;
}
else
{
cemu_assert_debug(false); // invalid type
return;
}
sliceHeader->pic_list_modification0Count++;
}
}
}
if (sliceHeader->slice_type.isSliceTypeB())
{
uint8 ref_pic_list_modification_flag_l1 = nalStream.readBit();
if (ref_pic_list_modification_flag_l1)
{
cemu_assert_debug(false); // testing required
while (true)
{
if (sliceHeader->pic_list_modification1Count >= 32)
{
cemu_assert_debug(false);
return;
}
uint32 modType = nalStream.readUV_E(); // aka modification_of_pic_nums_idc
sliceHeader->pic_list_modification1Array[sliceHeader->pic_list_modification1Count].type = modType;
if (modType == 0 || modType == 1)
{
sliceHeader->pic_list_modification1Array[sliceHeader->pic_list_modification1Count].abs_diff_pic_num_minus1 = nalStream.readUV_E();
}
else if (modType == 2)
{
sliceHeader->pic_list_modification1Array[sliceHeader->pic_list_modification1Count].long_term_pic_num = nalStream.readUV_E();
}
else if(modType == 3)
{
break;
}
else
{
cemu_assert_debug(false); // invalid mode
break;
}
sliceHeader->pic_list_modification0Count++;
}
if (sliceHeader->pic_list_modification1Count > 0)
{
cemuLog_logDebug(LogType::Force, "sliceHeader->pic_list_modification1Count non-zero is not supported");
cemu_assert_unimplemented();
}
}
}
}
void parseNAL_dec_ref_pic_marking(const h264State_seq_parameter_set_t& sps, const h264State_pic_parameter_set_t& pps, RBSPInputBitstream& nalStream, nal_slice_header_t* sliceHeader)
{
sliceHeader->memory_management_control_operation_num = 0;
if (sliceHeader->IdrPicFlag)
{
uint8 no_output_of_prior_pics_flag = nalStream.readBit();
if (no_output_of_prior_pics_flag)
cemu_assert_debug(false);
uint8 long_term_reference_flag = nalStream.readBit();
if (long_term_reference_flag)
cemu_assert_debug(false);
sliceHeader->adaptive_ref_pic_marking_mode_flag = 1;
}
else
{
sliceHeader->adaptive_ref_pic_marking_mode_flag = nalStream.readBit();
if (sliceHeader->adaptive_ref_pic_marking_mode_flag)
{
while (true)
{
uint32 memory_management_control_operation = nalStream.readUV_E();
if (memory_management_control_operation == nal_slice_header_t::MEMOP_END)
break;
if (sliceHeader->memory_management_control_operation_num >= 16)
{
cemu_assert_debug(false);
return;
}
sliceHeader->memory_management_control_operation[sliceHeader->memory_management_control_operation_num].op = memory_management_control_operation;
if (memory_management_control_operation == nal_slice_header_t::MEMOP_REMOVE_REF_FROM_SHORT_TERM || memory_management_control_operation == nal_slice_header_t::MEMOP_MAKE_LONG_TERM_REF)
{
sliceHeader->memory_management_control_operation[sliceHeader->memory_management_control_operation_num].difference_of_pic_nums_minus1 = nalStream.readUV_E();
}
else if (memory_management_control_operation == nal_slice_header_t::MEMOP_REMOVE_REF_FROM_LONG_TERM)
{
sliceHeader->memory_management_control_operation[sliceHeader->memory_management_control_operation_num].long_term_pic_num = nalStream.readUV_E();
}
if (memory_management_control_operation == nal_slice_header_t::MEMOP_MAKE_LONG_TERM_REF || memory_management_control_operation == nal_slice_header_t::MEMOP_MAKE_CURRENT_LONG_TERM_REF)
{
sliceHeader->memory_management_control_operation[sliceHeader->memory_management_control_operation_num].long_term_frame_idx = nalStream.readUV_E();
}
if (memory_management_control_operation == nal_slice_header_t::MEMOP_MAX_LONG_TERM_INDEX)
{
sliceHeader->memory_management_control_operation[sliceHeader->memory_management_control_operation_num].max_long_term_frame_idx_plus1 = nalStream.readUV_E();
}
sliceHeader->memory_management_control_operation_num++;
}
}
}
}
void parseNAL_pred_weight_table(const h264State_seq_parameter_set_t& sps, const h264State_pic_parameter_set_t& pps, RBSPInputBitstream& nalStream, nal_slice_header_t* sliceHeader)
{
uint8 luma_log2_weight_denom = nalStream.readUV_E();
uint32 ChromaArrayType;
if (sps.separate_colour_plane_flag == 0)
ChromaArrayType = sps.chroma_format_idc;
else
ChromaArrayType = 0;
if (ChromaArrayType != 0)
{
uint32 chroma_log2_weight_denom = nalStream.readUV_E();
}
for (uint32 i = 0; i <= sliceHeader->num_ref_idx_l0_active_minus1; i++)
{
uint8 luma_weight_l0_flag = nalStream.readBit();
if (luma_weight_l0_flag)
{
uint32 luma_weight_l0 = nalStream.readSV_E();
uint32 luma_offset_l0 = nalStream.readSV_E();
}
if (ChromaArrayType != 0)
{
uint8 chroma_weight_l0_flag = nalStream.readBit();
if (chroma_weight_l0_flag)
{
for (sint32 j = 0; j < 2; j++)
{
uint32 chroma_weight_l0 = nalStream.readSV_E();
uint32 chroma_offset_l0 = nalStream.readSV_E();
}
}
}
}
if (sliceHeader->slice_type.isSliceTypeB())
{
for (uint32 i = 0; i <= sliceHeader->num_ref_idx_l1_active_minus1; i++)
{
uint8 luma_weight_l1_flag = nalStream.readBit();
if (luma_weight_l1_flag)
{
cemu_assert_debug(false);
//luma_weight_l1[i]
//luma_offset_l1[i]
}
if (ChromaArrayType != 0)
{
cemu_assert_debug(false);
//chroma_weight_l1_flag
//if (chroma_weight_l1_flag)
//{
// for (j = 0; j < 2; j++)
// {
// chroma_weight_l1[i][j]
// chroma_offset_l1[i][j]
// }
//}
}
}
}
}
void parseNAL_slice_header(const h264State_seq_parameter_set_t& sps, const h264State_pic_parameter_set_t& pps, RBSPInputBitstream& nalStream, uint8 nal_unit_type, uint8 nal_ref_idc, nal_slice_header_t* sliceHeader)
{
bool IdrPicFlag = nal_unit_type == 5;
memset(sliceHeader, 0, sizeof(nal_slice_header_t));
sliceHeader->nal_ref_idc = nal_ref_idc;
sliceHeader->nal_unit_type = nal_unit_type;
sliceHeader->first_mb_in_slice = nalStream.readUV_E(); // address of first macroblock in slice
sliceHeader->slice_type = { nalStream.readUV_E() };
sliceHeader->pic_parameter_set_id = nalStream.readUV_E();
if (sps.separate_colour_plane_flag == 1)
{
cemu_assert_debug(false);
return;
}
sliceHeader->frame_num = nalStream.readBits(sps.log2_max_frame_num_minus4 + 4);
if (sps.frame_mbs_only_flag == 0)
{
sliceHeader->field_pic_flag = nalStream.readBit();
if (sliceHeader->field_pic_flag)
{
sliceHeader->bottom_field_flag = nalStream.readBit();
}
}
sliceHeader->IdrPicFlag = IdrPicFlag?1:0;
if (IdrPicFlag)
{
sliceHeader->idr_pic_id = nalStream.readUV_E();
}
if (sps.pic_order_cnt_type == 0)
{
sliceHeader->pic_order_cnt_lsb = nalStream.readBits(sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
if (pps.bottom_field_pic_order_in_frame_present_flag && sliceHeader->field_pic_flag == 0)
sliceHeader->delta_pic_order_cnt_bottom = nalStream.readSV_E();
}
else if (sps.pic_order_cnt_type == 1)
{
cemu_assert(false);
}
if (pps.redundant_pic_cnt_present_flag)
{
sliceHeader->redundant_pic_cnt = nalStream.readUV_E();
}
if (sliceHeader->slice_type.isSliceTypeB())
{
sliceHeader->direct_spatial_mv_pred_flag = nalStream.readBit();
}
sliceHeader->num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1;
sliceHeader->num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1;
if (sliceHeader->slice_type.isSliceTypeP() || sliceHeader->slice_type.isSliceTypeSP() || sliceHeader->slice_type.isSliceTypeB())
{
sliceHeader->num_ref_idx_active_override_flag = nalStream.readBit();
if (sliceHeader->num_ref_idx_active_override_flag)
{
sliceHeader->num_ref_idx_l0_active_minus1 = nalStream.readUV_E();
if (sliceHeader->slice_type.isSliceTypeB())
{
sliceHeader->num_ref_idx_l1_active_minus1 = nalStream.readUV_E();
}
}
}
// todo - ref_pic_list_mvc_modification etc
if (nal_unit_type == 20 || nal_unit_type == 21)
{
cemu_assert_debug(false);
}
else
{
parseNAL_ref_pic_list_modification(sps, pps, nalStream, sliceHeader);
}
if ((pps.weighted_pred_flag && (sliceHeader->slice_type.isSliceTypeP() || sliceHeader->slice_type.isSliceTypeSP())) || (pps.weighted_bipred_idc == 1 && sliceHeader->slice_type.isSliceTypeB()))
{
parseNAL_pred_weight_table(sps, pps, nalStream, sliceHeader);
}
if (sliceHeader->nal_ref_idc != 0)
{
parseNAL_dec_ref_pic_marking(sps, pps, nalStream, sliceHeader);
}
if (pps.entropy_coding_mode_flag && !sliceHeader->slice_type.isSliceTypeI() && !sliceHeader->slice_type.isSliceTypeSI())
{
uint32 cabac_init_idc = nalStream.readUV_E();
cemu_assert_debug(cabac_init_idc <= 2); // invalid value
}
sint32 slice_qp_delta = nalStream.readSV_E();
if (sliceHeader->slice_type.isSliceTypeSP() || sliceHeader->slice_type.isSliceTypeSI())
{
if (sliceHeader->slice_type.isSliceTypeSP())
{
uint8 sp_for_switch_flag = nalStream.readBit();
}
sint32 slice_qs_delta = nalStream.readSV_E();
}
if (pps.deblocking_filter_control_present_flag)
{
uint32 disable_deblocking_filter_idc = nalStream.readUV_E();
if (disable_deblocking_filter_idc != 1)
{
sint32 slice_alpha_c0_offset_div2 = nalStream.readSV_E();
sint32 slice_beta_offset_div2 = nalStream.readSV_E();
}
}
if (pps.num_slice_groups_minus1 > 0 && pps.slice_group_map_type >= 3 && pps.slice_group_map_type <= 5)
{
cemu_assert_debug(false); // todo
}
}
void _calculateFrameOrder(h264ParserState_t* h264ParserState, const h264State_seq_parameter_set_t& sps, const h264State_pic_parameter_set_t& pps, nal_slice_header_t* sliceHeader)
{
if (sps.pic_order_cnt_type == 0)
{
// calculate TopFieldOrderCnt
uint32 prevPicOrderCntMsb;
uint32 prevPicOrderCntLsb;
if (sliceHeader->IdrPicFlag)
{
sliceHeader->calculated.TopFieldOrderCnt = 0;
prevPicOrderCntMsb = 0;
prevPicOrderCntLsb = 0;
}
else
{
uint32 prevRefPic_PicOrderCntMsb = h264ParserState->picture_order.prevPicOrderCntMsb;
uint32 prevRefPic_pic_order_cnt_lsb = h264ParserState->picture_order.prevPicOrderCntLsb; // todo
prevPicOrderCntMsb = prevRefPic_PicOrderCntMsb;
prevPicOrderCntLsb = prevRefPic_pic_order_cnt_lsb;
}
uint32 MaxPicOrderCntLsb = 1 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4); // todo - verify
uint32 PicOrderCntMsb;
if ((sliceHeader->pic_order_cnt_lsb < prevPicOrderCntLsb) && (((sint32)prevPicOrderCntLsb - (sint32)sliceHeader->pic_order_cnt_lsb) >= (sint32)(MaxPicOrderCntLsb / 2)))
PicOrderCntMsb = prevPicOrderCntMsb + MaxPicOrderCntLsb;
else if ((sliceHeader->pic_order_cnt_lsb > prevPicOrderCntLsb) && (((sint32)sliceHeader->pic_order_cnt_lsb - (sint32)prevPicOrderCntLsb) > (sint32)(MaxPicOrderCntLsb / 2)))
PicOrderCntMsb = prevPicOrderCntMsb - MaxPicOrderCntLsb;
else
PicOrderCntMsb = prevPicOrderCntMsb;
uint32 TopFieldOrderCnt = PicOrderCntMsb + sliceHeader->pic_order_cnt_lsb;
if (sliceHeader->IdrPicFlag != 0 && TopFieldOrderCnt != 0)
cemu_assert(false);
sliceHeader->calculated.TopFieldOrderCnt = TopFieldOrderCnt;
h264ParserState->picture_order.prevPicOrderCntMsb = PicOrderCntMsb;
h264ParserState->picture_order.prevPicOrderCntLsb = sliceHeader->pic_order_cnt_lsb;
}
else if (sps.pic_order_cnt_type == 2)
{
// display order matches decode order
uint32 prevFrameNum = h264ParserState->picture_order.prevFrameNum;
uint32 FrameNumOffset;
if (sliceHeader->IdrPicFlag)
{
FrameNumOffset = 0;
}
else
{
// todo - check for memory_management_control_operation 5
// prevFrameNumOffset is set equal to the value of FrameNumOffset of the previous picture in decoding order.
uint32 prevFrameNumOffset = h264ParserState->picture_order.prevFrameNumOffset;
if (prevFrameNum > sliceHeader->frame_num)
FrameNumOffset = prevFrameNumOffset + sps.getMaxFrameNum();
else
FrameNumOffset = prevFrameNumOffset;
}
uint32 tempPicOrderCnt;
if (sliceHeader->IdrPicFlag == 1)
tempPicOrderCnt = 0;
else if (sliceHeader->nal_ref_idc == 0)
tempPicOrderCnt = 2 * (FrameNumOffset + sliceHeader->frame_num) - 1;
else
tempPicOrderCnt = 2 * (FrameNumOffset + sliceHeader->frame_num);
uint32 TopFieldOrderCnt = 0;
uint32 BottomFieldOrderCnt = 0;
if (sliceHeader->field_pic_flag == 0)
{
TopFieldOrderCnt = tempPicOrderCnt;
BottomFieldOrderCnt = tempPicOrderCnt;
}
else if (sliceHeader->bottom_field_flag != 0)
{
cemu_assert_debug(false); // fields aren't supported
BottomFieldOrderCnt = tempPicOrderCnt;
}
else
{
cemu_assert_debug(false); // fields aren't supported
TopFieldOrderCnt = tempPicOrderCnt;
}
sliceHeader->calculated.TopFieldOrderCnt = TopFieldOrderCnt;
h264ParserState->picture_order.prevFrameNum = sliceHeader->frame_num;
h264ParserState->picture_order.prevFrameNumOffset = FrameNumOffset;
}
else
{
cemu_assert_debug(false);
}
}
void parseNAL_slice_layer_without_partitioning_rbsp(h264ParserState_t* h264ParserState, h264ParserOutput_t* output, sint32 streamSubOffset, sint32 streamSubLength, RBSPInputBitstream& nalStream, uint8 nal_ref_idc, uint8 nal_unit_type)
{
nal_slice_t slice = {};
cemu_assert_debug(h264ParserState->hasPPS && h264ParserState->hasSPS);
parseNAL_slice_header(h264ParserState->sps, h264ParserState->pps, nalStream, nal_unit_type, nal_ref_idc, &slice.slice_header);
_calculateFrameOrder(h264ParserState, h264ParserState->sps, h264ParserState->pps, &slice.slice_header);
if (output->sliceCount >= output->sliceInfo.size())
{
cemu_assert_debug(false); // internal slice buffer full
return;
}
output->sliceInfo[output->sliceCount].header = slice.slice_header;
output->sliceInfo[output->sliceCount].streamSubOffset = streamSubOffset;
output->sliceInfo[output->sliceCount].streamSubSize = streamSubLength;
output->sliceCount++;
}
void h264Parse(h264ParserState_t* h264ParserState, h264ParserOutput_t* output, uint8* data, uint32 length, bool parseSlices)
{
memset(output, 0, sizeof(h264ParserOutput_t));
NALInputBitstream nalStream(data, length);
if (nalStream.hasError())
{
cemu_assert_debug(false);
return;
}
// parse NAL data
while (true)
{
if (nalStream.isEndOfStream())
break;
RBSPInputBitstream rbspStream;
if (nalStream.getNextRBSP(rbspStream) == false)
break;
sint32 streamSubOffset = (sint32)(rbspStream.getBasePtr() - data);
sint32 streamSubLength = rbspStream.getBaseLength();
// parse NAL header
uint8 nalHeaderByte = rbspStream.readU8();
if ((nalHeaderByte & 0x80) != 0)
{
// MSB must be zero
cemu_assert_debug(false);
continue;
}
uint8 nal_ref_idc = (nalHeaderByte >> 5) & 0x3;
uint8 nal_unit_type = (nalHeaderByte >> 0) & 0x1f;
// nal_ref_idc -> If not 0, reference picture. Contains sequence set ??
// nal_unit_type -> RBSP type
// nal_unit_type:
// 0 - unspecified
// 1 - Coded slice of a non-IDR picture slice_layer_without_partitioning_rbsp()
// 2 - Coded slice data partition A slice_data_partition_a_layer_rbsp()
// 3 - Coded slice data partition B slice_data_partition_b_layer_rbsp()
// 4 - Coded slice data partition C slice_data_partition_c_layer_rbsp()
// 5 - Coded slice of an IDR picture slice_layer_without_partitioning_rbsp()
// 6 - Supplemental enhancement information (SEI) sei_rbsp()
// 7 - Sequence parameter set seq_parameter_set_rbsp()
// 8 - Picture parameter set pic_parameter_set_rbsp()
// 9 - Access unit delimiter access_unit_delimiter_rbsp()
// 10 - End of sequence end_of_seq_rbsp()
// 11 - End of stream end_of_stream_rbsp()
// 12 - Filler data filler_data_rbsp()
// 13 to 23 - reserved
// 24 to 31 - unspecified
// VCL NAL -> nal_unit_type 1,2,3,4,5
// non-VCL NAL -> All other nal_unit_type values
if (nal_unit_type == 14 || nal_unit_type == 20 || nal_unit_type == 21)
{
cemu_assert_debug(false);
// todo - there are fields to parse here
}
switch (nal_unit_type)
{
case 1:
if (parseSlices)
parseNAL_slice_layer_without_partitioning_rbsp(h264ParserState, output, streamSubOffset, streamSubLength, rbspStream, nal_ref_idc, nal_unit_type);
break;
case 5:
if (parseSlices)
parseNAL_slice_layer_without_partitioning_rbsp(h264ParserState, output, streamSubOffset, streamSubLength, rbspStream, nal_ref_idc, nal_unit_type);
break;
case 6:
// SEI
break;
case 7:
cemu_assert_debug(parseNAL_seq_parameter_set_rbsp(h264ParserState, output, rbspStream));
break;
case 8:
cemu_assert_debug(parseNAL_pic_parameter_set_rbsp(h264ParserState, output, rbspStream));
break;
case 9:
// access unit delimiter
break;
case 10:
// end of sequence
break;
case 12:
// filler data
// seen in Cocoto Magic Circus 2 intro video
break;
default:
cemuLog_logDebug(LogType::Force, "Unsupported NAL unit type {}", nal_unit_type);
cemu_assert_debug(false);
// todo
break;
}
}
}
sint32 h264GetUnitLength(h264ParserState_t* h264ParserState, uint8* data, uint32 length)
{
NALInputBitstream nalStream(data, length);
if (nalStream.hasError())
{
cemu_assert_debug(false);
return -1;
}
// search for start code
sint32 startCodeOffset = 0;
bool hasStartcode = false;
while (startCodeOffset < (sint32)(length - 3))
{
if (data[startCodeOffset + 0] == 0x00 && data[startCodeOffset + 1] == 0x00 && data[startCodeOffset + 2] == 0x01)
{
hasStartcode = true;
break;
}
startCodeOffset++;
}
if (hasStartcode == false)
return -1;
data += startCodeOffset;
length -= startCodeOffset;
// parse NAL data
while (true)
{
if (nalStream.isEndOfStream())
break;
RBSPInputBitstream rbspStream;
if (nalStream.getNextRBSP(rbspStream, true) == false)
break;
sint32 streamSubOffset = (sint32)(rbspStream.getBasePtr() - data);
sint32 streamSubLength = rbspStream.getBaseLength();
// parse NAL header
uint8 nalHeaderByte = rbspStream.readU8();
if ((nalHeaderByte & 0x80) != 0)
{
// MSB must be zero
cemu_assert_debug(false);
continue;
}
uint8 nal_ref_idc = (nalHeaderByte >> 5) & 0x3;
uint8 nal_unit_type = (nalHeaderByte >> 0) & 0x1f;
if (nal_unit_type == 14 || nal_unit_type == 20 || nal_unit_type == 21)
{
cemu_assert_debug(false);
continue;
}
switch (nal_unit_type)
{
case 1:
case 5:
{
// note: We cant parse the slice data because we dont have SPS and PPS data reliably available
//
// currently we just assume there is 1 slice per unit
return (sint32)((rbspStream.getBasePtr() + rbspStream.getBaseLength()) - data) + startCodeOffset;
break;
}
case 6:
// SEI
break;
case 7:
cemu_assert_debug(parseNAL_seq_parameter_set_rbsp(h264ParserState, nullptr, rbspStream));
break;
case 8:
cemu_assert_debug(parseNAL_pic_parameter_set_rbsp(h264ParserState, nullptr, rbspStream));
break;
case 9:
// access unit delimiter
break;
case 10:
// end of sequence
break;
default:
cemuLog_logDebug(LogType::Force, "Unsupported NAL unit type {}", nal_unit_type);
assert_dbg(); // todo - NAL 10 is used in DKC TF
// todo
break;
}
}
return -1;
}
static const unsigned char h264_default_4x4_Intra[16] =
{
6, 13, 13, 20,
20, 20, 28, 28,
28, 28, 32, 32,
32, 37, 37, 42
};
static const unsigned char h264_default_4x4_Inter[16] =
{
10, 14, 14, 20,
20, 20, 24, 24,
24, 24, 27, 27,
27, 30, 30, 34
};
static const unsigned char h264_default_8x8_Intra[64] =
{
6, 10, 10, 13, 11, 13, 16, 16,
16, 16, 18, 18, 18, 18, 18, 23,
23, 23, 23, 23, 23, 25, 25, 25,
25, 25, 25, 25, 27, 27, 27, 27,
27, 27, 27, 27, 29, 29, 29, 29,
29, 29, 29, 31, 31, 31, 31, 31,
31, 33, 33, 33, 33, 33, 36, 36,
36, 36, 38, 38, 38, 40, 40, 42
};
static const unsigned char h264_default_8x8_Inter[64] =
{
9, 13, 13, 15, 13, 15, 17, 17,
17, 17, 19, 19, 19, 19, 19, 21,
21, 21, 21, 21, 21, 22, 22, 22,
22, 22, 22, 22, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25,
25, 25, 25, 27, 27, 27, 27, 27,
27, 28, 28, 28, 28, 28, 30, 30,
30, 30, 32, 32, 32, 33, 33, 35
};
void h264Parser_getScalingMatrix4x4(h264State_seq_parameter_set_t* sps, h264State_pic_parameter_set_t* pps, nal_slice_header_t* sliceHeader, sint32 index, uint8* matrix4x4)
{
// use scaling lists from PPS first
if (pps->pic_scaling_matrix_present_flag)
{
if (pps->ScalingList4x4[index].isPresent)
{
cemu_assert(false); // testing needed (what about UseDefaultScalingMatrix?)
memcpy(matrix4x4, pps->ScalingList4x4[index].list, 4 * 4 * sizeof(uint8));
}
else
{
if (index < 3)
memcpy(matrix4x4, h264_default_4x4_Intra, 4 * 4 * sizeof(uint8));
else
memcpy(matrix4x4, h264_default_4x4_Inter, 4 * 4 * sizeof(uint8));
}
return;
}
// use scaling lists from SPS
if (sps->seq_scaling_matrix_present_flag)
{
if (sps->ScalingList4x4[index].isPresent)
{
cemu_assert(false); // testing needed (what about UseDefaultScalingMatrix?)
memcpy(matrix4x4, sps->ScalingList4x4[index].list, 4 * 4 * sizeof(uint8));
}
else
{
if (index < 3)
memcpy(matrix4x4, h264_default_4x4_Intra, 4 * 4 * sizeof(uint8));
else
memcpy(matrix4x4, h264_default_4x4_Inter, 4 * 4 * sizeof(uint8));
}
return;
}
// default (Flat_4x4_16)
memset(matrix4x4, 16, 4 * 4 * sizeof(uint8));
}
void h264Parser_getScalingMatrix8x8(h264State_seq_parameter_set_t* sps, h264State_pic_parameter_set_t* pps, nal_slice_header_t* sliceHeader, sint32 index, uint8* matrix8x8)
{
// use scaling lists from PPS first
if (pps->pic_scaling_matrix_present_flag)
{
if (pps->ScalingList8x8[index].isPresent)
{
cemu_assert(false); // testing needed (what about UseDefaultScalingMatrix?)
memcpy(matrix8x8, pps->ScalingList8x8[index].list, 8 * 8 * sizeof(uint8));
}
else
{
if ((index&1) == 0)
memcpy(matrix8x8, h264_default_8x8_Intra, 8 * 8 * sizeof(uint8));
else
memcpy(matrix8x8, h264_default_8x8_Inter, 8 * 8 * sizeof(uint8));
}
return;
}
// use scaling lists from SPS
if (sps->seq_scaling_matrix_present_flag)
{
if (sps->ScalingList8x8[index].isPresent)
{
cemu_assert(false); // testing needed (what about UseDefaultScalingMatrix?)
memcpy(matrix8x8, sps->ScalingList8x8[index].list, 8 * 8 * sizeof(uint8));
}
else
{
if ((index & 1) == 0)
memcpy(matrix8x8, h264_default_8x8_Intra, 8 * 8 * sizeof(uint8));
else
memcpy(matrix8x8, h264_default_8x8_Inter, 8 * 8 * sizeof(uint8));
}
return;
}
// default (Flat_8x8_16)
memset(matrix8x8, 16, 8 * 8 * sizeof(uint8));
}
| 36,267
|
C++
|
.cpp
| 992
| 33.482863
| 234
| 0.727474
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,048
|
sysapp.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/sysapp/sysapp.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "sysapp.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/OS/libs/coreinit/coreinit_FG.h"
#include "Cafe/OS/libs/coreinit/coreinit_Misc.h"
typedef struct
{
MEMPTR<char> argStr;
uint32be size;
}sysStandardArguments_t;
typedef struct
{
// guessed
/* +0x00 */ MEMPTR<uint8> sysAnchor;
/* +0x04 */ uint32be sysAnchorSize;
/* +0x08 */ MEMPTR<uint8> sysResult;
/* +0x0C */ uint32be sysResultSize;
}sysDeserializeStandardArguments_t;
typedef struct
{
// used for setting arguments, maybe wrong?
/* +0x00 */ sysStandardArguments_t standardArguments;
/* +0x08 */ uint32be mode;
/* +0x0C */ uint32be slot_id;
/* +0x10 */ MEMPTR<uint8> mii;
}sysMiiStudioArguments_t;
typedef struct
{
// used for getting arguments
/* +0x00 */ sysStandardArguments_t standardArguments; // ?
/* +0x08 */ uint32 ukn08;
/* +0x0C */ uint32 ukn0C;
/* +0x10 */ uint32be mode;
/* +0x14 */ uint32be slot_id;
/* +0x18 */ MEMPTR<uint8> mii;
/* +0x1C */ uint32be miiSize;
}sysMiiStudioArguments2_t;
typedef struct
{
/* +0x00 */ sysDeserializeStandardArguments_t standardArguments;
/* +0x10 */ uint32be jumpTo; // see below for list of available values
/* +0x14 */ uint32be needsReturn;
/* +0x18 */ uint32be firstBootMode;
}sysSettingsArguments_t;
static_assert(sizeof(sysSettingsArguments_t) == 0x1C);
static_assert(offsetof(sysSettingsArguments_t, jumpTo) == 0x10);
static_assert(offsetof(sysSettingsArguments_t, needsReturn) == 0x14);
static_assert(offsetof(sysSettingsArguments_t, firstBootMode) == 0x18);
/*
Sys settings jumpTo values:
0x00 -> Normal launch
0x01 -> Internet settings
0x02 -> Data management
0x03 -> TV remote
0x04 -> Date settings
0x05 -> Country settings
0x06 -> System update
0x64 -> Initial system configuration (after Wii U GamePad was configured)
0x65 -> Crashes
0x66 -> Delete All Content and Settings (throws erreula after a second)
0x67 -> Quick Start Settings
0x68 -> TV connection type
0x69 -> Data management
0xFF -> Data transfer
*/
typedef struct
{
/* +0x00 */ sysDeserializeStandardArguments_t standardArguments; // guessed
/* +0x10 */ uint32be ukn10;
/* +0x14 */ uint32be ukn14;
}eshopArguments_t;
static_assert(sizeof(eshopArguments_t) == 0x18);
#define SYS_STANDARD_ARGS_MAX_LEN 0x1000
#define OS_COPY_MAX_DATA_SIZE (0x400000-4)
void appendDataToBuffer(uint32 currentCopyDataSize, char* str, sint32 size)
{
cemu_assert_unimplemented();
}
sint32 _serializeArgsToBuffer(uint32 currentCopyDataSize, const char* argName, char* str, sint32 size, void (*appendFunc)(uint32 currentCopyDataSize, char* str, sint32 size))
{
if (strnlen(argName, 0x41) == 0x40)
return -0x2710;
if (size > 0x200000)
return -0x7530;
char tempStr[0x80];
if (size != 0 && str != nullptr)
{
sint32 textSize = sprintf(tempStr, "<%s %s=%u>", argName, "size", size);
if ((currentCopyDataSize + textSize + size) >= OS_COPY_MAX_DATA_SIZE)
return 0xFFFF63C0;
appendFunc(currentCopyDataSize, str, size);
appendFunc(currentCopyDataSize, tempStr, textSize);
}
else
{
sint32 textSize = sprintf(tempStr, "<%s>", argName);
appendFunc(currentCopyDataSize, tempStr, textSize);
}
return 0;
}
sint32 SYSPackArgs()
{
uint32 currentCopyDataSize = coreinit::__OSGetCopyDataSize();
char sysPackStr[128];
sint32 textSize = sprintf(sysPackStr, "<%s %s=%u>", "sys:pack", "size", currentCopyDataSize);
if ((currentCopyDataSize + textSize) > OS_COPY_MAX_DATA_SIZE)
return 0xFFFF4480;
coreinit::__OSAppendCopyData((uint8*)sysPackStr, textSize);
return 0;
}
sint32 SYSSerializeSysArgs(const char* argName, char* str, sint32 size)
{
uint32 currentCopyDataSize = coreinit::__OSGetCopyDataSize();
sint32 r = _serializeArgsToBuffer(currentCopyDataSize, argName, str, size, appendDataToBuffer);
if (r < 0)
return r;
return 0;
}
sint32 _SYSSerializeStandardArgsIn(sysStandardArguments_t* standardArgs)
{
if (strnlen(standardArgs->argStr.GetPtr(), SYS_STANDARD_ARGS_MAX_LEN + 4) > SYS_STANDARD_ARGS_MAX_LEN)
{
return 0xFFFF63C0;
}
SYSSerializeSysArgs("sys:anchor", standardArgs->argStr.GetPtr(), standardArgs->size);
SYSPackArgs();
return 0;
}
sint32 _SYSAppendCallerInfo()
{
// todo
return 0;
}
typedef struct
{
uint32be id;
uint32be type;
// union data here - todo
}sysArgSlot_t;
#define SYS_ARG_ID_END 0 // indicates end of sysArgSlot_t array
#define SYS_ARG_ID_ANCHOR 100
typedef struct
{
char* argument;
uint32 size;
uint8* data;
}deserializedArg_t;
uint32 _sysArg_packSize = 0;
void clearSysArgs()
{
_sysArg_packSize = 0;
}
void deserializeSysArg(deserializedArg_t* deserializedArg)
{
if (strcmp(deserializedArg->argument, "sys:pack") == 0)
_sysArg_packSize = deserializedArg->size;
// todo
}
sint32 _deserializeSysArgsEx2(uint8* copyDataPtr, sint32 copyDataSize, void(*cbDeserializeArg)(deserializedArg_t* deserializedArg, void* customParam), void* customParam)
{
sint32 idx = copyDataSize - 1;
sint32 argSlotIndex = 0;
while (idx >= 0)
{
if (copyDataPtr[idx] == '>')
{
// find matching '<'
sint32 idxStart = idx;
while (true)
{
idxStart--;
if (idxStart < 0)
return 1;
if (copyDataPtr[idxStart] == '<')
break;
}
sint32 idxDataEnd = idxStart;
idxStart++;
// parse argument name
char argumentName[64];
sint32 idxCurrent = idxStart;
while( idxCurrent <= idx )
{
argumentName[idxCurrent - idxStart] = copyDataPtr[idxCurrent];
if ((idxCurrent - idxStart) >= 60)
return 1;
if (copyDataPtr[idxCurrent] == ' ' || copyDataPtr[idxCurrent] == '>')
{
argumentName[idxCurrent - idxStart] = '\0';
break;
}
idxCurrent++;
}
// parse size (if any)
while (copyDataPtr[idxCurrent] == ' ')
idxCurrent++;
sint32 argumentDataSize;
if (copyDataPtr[idxCurrent] == '>')
{
argumentDataSize = 0;
}
else if ((copyDataSize - idxCurrent) >= 5 && memcmp(copyDataPtr+idxCurrent, "size", 4) == 0)
{
idxCurrent += 4;
// skip whitespaces and '='
while (copyDataPtr[idxCurrent] == ' ' || copyDataPtr[idxCurrent] == '=')
idxCurrent++;
// parse size value
char tempSizeStr[32];
sint32 sizeParamLen = idx - idxCurrent;
if (sizeParamLen < 0 || sizeParamLen >= 30)
return 1;
memcpy(tempSizeStr, copyDataPtr+idxCurrent, sizeParamLen);
tempSizeStr[sizeParamLen] = '\0';
argumentDataSize = atol(tempSizeStr);
}
else
{
assert_dbg();
return 1;
}
idx = idxStart - argumentDataSize - 1; // beginning of data
deserializedArg_t deserializedArg = { 0 };
deserializedArg.argument = argumentName;
deserializedArg.size = argumentDataSize;
deserializedArg.data = copyDataPtr + idx;
deserializeSysArg(&deserializedArg);
if (cbDeserializeArg)
cbDeserializeArg(&deserializedArg, customParam);
idx--;
}
else if (copyDataPtr[idx] == ']')
{
assert_dbg();
}
else
return 1;
}
return 0;
}
void _deserializeSysArgsEx(void(*cbDeserializeArg)(deserializedArg_t* deserializedArg, void* customParam), void* customParam)
{
sint32 copyDataSize = coreinit::__OSGetCopyDataSize();
uint8* copyDataPtr = coreinit::__OSGetCopyDataPtr();
_deserializeSysArgsEx2(copyDataPtr, copyDataSize, cbDeserializeArg, customParam);
}
void SYSDeserializeSysArgs(void(*cbDeserializeArg)(deserializedArg_t* deserializedArg, void* customParam), sysArgSlot_t* argSlots)
{
_deserializeSysArgsEx(cbDeserializeArg, argSlots);
}
sint32 _deserializeArgs(void* customParam, sint32 customParamSize, void(*cbDeserializeArg)(deserializedArg_t* deserializedArg, void* customParam))
{
memset(customParam, 0, customParamSize);
clearSysArgs();
_deserializeSysArgsEx(cbDeserializeArg, customParam);
return 0;
}
void _unpackSysWorkaround()
{
// unpack sys
clearSysArgs();
_deserializeSysArgsEx(NULL, NULL);
if (_sysArg_packSize != 0)
{
coreinit::__OSResizeCopyData(_sysArg_packSize);
}
}
void cbDeserializeArg_MiiMaker(deserializedArg_t* deserializedArg, void* customParam)
{
sysMiiStudioArguments2_t* miiStudioArgs = (sysMiiStudioArguments2_t*)customParam;
if (strcmp(deserializedArg->argument, "mode") == 0)
{
miiStudioArgs->mode = *(uint32be*)deserializedArg->data;
}
else if (strcmp(deserializedArg->argument, "mii") == 0)
{
assert_dbg();
}
else if (strcmp(deserializedArg->argument, "slot_id") == 0)
{
#ifdef CEMU_DEBUG_ASSERT
assert_dbg();
#endif
}
else
{
#ifdef CEMU_DEBUG_ASSERT
assert_dbg();
#endif
}
}
sint32 _SYSGetMiiStudioArgs(sysMiiStudioArguments2_t* miiStudioArgs)
{
_unpackSysWorkaround();
_deserializeArgs(miiStudioArgs, sizeof(sysMiiStudioArguments2_t), cbDeserializeArg_MiiMaker);
return 0;
}
void sysappExport__SYSGetMiiStudioArgs(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(miiStudioArgs, sysMiiStudioArguments2_t, 0);
sint32 r = _SYSGetMiiStudioArgs(miiStudioArgs);
osLib_returnFromFunction(hCPU, r);
}
void cbDeserializeArg_SysSettings(deserializedArg_t* deserializedArg, void* customParam)
{
sysSettingsArguments_t* settingsArgs = (sysSettingsArguments_t*)customParam;
if (boost::iequals(deserializedArg->argument, "jump_to"))
{
cemu_assert_unimplemented();
}
else if (boost::iequals(deserializedArg->argument, "first_boot_kind"))
{
cemu_assert_unimplemented();
}
else if (boost::iequals(deserializedArg->argument, "needs_return"))
{
settingsArgs->needsReturn = 1;
}
else
cemu_assert_unimplemented();
}
sint32 _SYSGetSettingsArgs(sysSettingsArguments_t* settingsArgs)
{
_unpackSysWorkaround();
memset(settingsArgs, 0, sizeof(sysSettingsArguments_t));
return _deserializeArgs(settingsArgs, sizeof(sysSettingsArguments_t), cbDeserializeArg_SysSettings);
}
void sysappExport__SYSGetSettingsArgs(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(settingsArgs, sysSettingsArguments_t, 0);
sint32 r = _SYSGetSettingsArgs(settingsArgs);
if (settingsArgs->jumpTo == 0) // workaround when launching sys settings directly
settingsArgs->jumpTo = 0x00;
osLib_returnFromFunction(hCPU, r);
}
struct
{
uint64 t0;
uint64 t1;
uint64 t2;
}systemApplicationTitleId[] = {
{ 0x5001010040000, 0x5001010040100, 0x5001010040200 }, // Wii U Menu
{ 0x5001010047000, 0x5001010047100, 0x5001010047200 }, // System Settings
{ 0x5001010048000, 0x5001010048100, 0x5001010048200 }, // Parental Controls
{ 0x5001010049000, 0x5001010049100, 0x5001010049200 }, // User Settings
{ 0x500101004A000, 0x500101004A100, 0x500101004A200 }, // Mii Maker
{ 0x500101004B000, 0x500101004B100, 0x500101004B200 }, // Account Settings
{ 0x500101004C000, 0x500101004C100, 0x500101004C200 }, // Daily Log
{ 0x500101004D000, 0x500101004D100, 0x500101004D200 }, // Notifications
{ 0x500101004E000, 0x500101004E100, 0x500101004E200 }, // Health and Safety Information
{ 0x5001B10059000, 0x5001B10059100, 0x5001B10059200 }, // Wii U Electronic Manual
{ 0x500101005A000, 0x500101005A100, 0x500101005A200 }, // Wii U Chat
{ 0x5001010062000, 0x5001010062100, 0x5001010062200 } // Software/Data Transfer
};
uint64 _SYSGetSystemApplicationTitleIdByProdArea(uint32 systemApplicationId, uint32 platformRegion)
{
if (systemApplicationId >= (sizeof(systemApplicationTitleId) / sizeof(systemApplicationTitleId[0])) )
assert_dbg();
if (platformRegion == 1)
{
return systemApplicationTitleId[systemApplicationId].t0;
}
else if (platformRegion == 4 || platformRegion == 8)
{
return systemApplicationTitleId[systemApplicationId].t2;
}
return systemApplicationTitleId[systemApplicationId].t1;
}
uint64 _SYSGetSystemApplicationTitleId(sint32 index)
{
uint32 region = (uint32)CafeSystem::GetPlatformRegion();
return _SYSGetSystemApplicationTitleIdByProdArea(index, region);
}
void sysappExport__SYSGetSystemApplicationTitleId(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(systemApplicationId, 0);
cemuLog_logDebug(LogType::Force, "_SYSGetSystemApplicationTitleId(0x{:x})", hCPU->gpr[3]);
uint64 titleId = _SYSGetSystemApplicationTitleId(systemApplicationId);
osLib_returnFromFunction64(hCPU, titleId);
}
void __LaunchMiiMaker(sysMiiStudioArguments_t* args, uint32 platformRegion)
{
coreinit::__OSClearCopyData();
if (args)
{
_SYSSerializeStandardArgsIn(&args->standardArguments);
SYSSerializeSysArgs("mode", (char*)&args->mode, 4);
SYSSerializeSysArgs("slot_id", (char*)&args->slot_id, 4);
if(args->mii)
SYSSerializeSysArgs("mii", (char*)args->mii.GetPtr(), 0x60);
}
_SYSAppendCallerInfo();
uint64 titleIdToLaunch = _SYSGetSystemApplicationTitleIdByProdArea(4, platformRegion);
cemu_assert_unimplemented();
}
void _SYSLaunchMiiStudio(sysMiiStudioArguments_t* args)
{
__LaunchMiiMaker(args, (uint32)CafeSystem::GetPlatformRegion());
}
void sysappExport__SYSLaunchMiiStudio(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(args, sysMiiStudioArguments_t, 0);
_SYSLaunchMiiStudio(args);
}
void sysappExport__SYSReturnToCallerWithStandardResult(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32BEPtr(resultPtr, 0);
cemuLog_log(LogType::Force, "_SYSReturnToCallerWithStandardResult(0x{:08x}) result: 0x{:08x}", hCPU->gpr[3], (uint32)*resultPtr);
while (true) std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void sysappExport__SYSGetEShopArgs(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(args, eshopArguments_t, 0);
cemuLog_logDebug(LogType::Force, "_SYSGetEShopArgs() - placeholder");
memset(args, 0, sizeof(eshopArguments_t));
osLib_returnFromFunction(hCPU, 0);
}
void sysappExport_SYSGetUPIDFromTitleID(PPCInterpreter_t* hCPU)
{
ppcDefineParamU64(titleId, 0);
uint32 titleIdHigh = (titleId >> 32);
uint32 titleIdLow = (uint32)(titleId & 0xFFFFFFFF);
if ((titleIdHigh & 0xFFFF0000) != 0x50000)
{
osLib_returnFromFunction(hCPU, -1);
return;
}
if ((titleIdLow & 0xF0000000) != 0x10000000)
{
osLib_returnFromFunction(hCPU, -1);
return;
}
uint32 titleId_type = (titleIdHigh & 0xFF);
if (titleId_type == 0x30)
{
// applet
uint32 ukn = ((titleIdLow >> 12) & 0xFFFF);
if (ukn < 0x10)
{
osLib_returnFromFunction(hCPU, -1);
return;
}
else if (ukn <= 0x19)
{
uint8 appletTable10[10] = { 5,6,8,3,0xA,0xB,9,4,0xC,7 };
osLib_returnFromFunction(hCPU, appletTable10[ukn - 0x10]);
return;
}
else if (ukn <= 0x20)
{
assert_dbg();
osLib_returnFromFunction(hCPU, -1);
return;
}
else if (ukn <= 0x29)
{
uint8 appletTable20[10] = {5,6,8,3,0xA,0xB,9,4,0xC,7};
osLib_returnFromFunction(hCPU, appletTable20[ukn-0x20]);
return;
}
assert_dbg();
osLib_returnFromFunction(hCPU, -1);
return;
}
else if (titleId_type == 0x10)
{
// system application
if (((titleIdLow >> 12) & 0xFFFF) == 0x40)
{
// Wii U menu
osLib_returnFromFunction(hCPU, 2);
return;
}
osLib_returnFromFunction(hCPU, 0xF);
return;
}
else if (titleId_type == 0x00 || titleId_type == 0x02)
{
osLib_returnFromFunction(hCPU, 0xF);
return;
}
osLib_returnFromFunction(hCPU, -1);
}
void sysappExport_SYSGetVodArgs(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "SYSGetVodArgs() - todo");
osLib_returnFromFunction(hCPU, 1);
}
struct SysLauncherArgs18
{
uint64be caller_id; // titleId
uint64be launch_title; // titleId
uint32be mode;
uint32be slot_id;
};
static_assert(sizeof(SysLauncherArgs18) == 0x18);
struct SysLauncherArgs28
{
uint32 ukn00;
uint32 ukn04;
uint32 ukn08;
uint32 ukn0C;
// standard args above
uint64be caller_id; // titleId
uint64be launch_title; // titleId
uint32be mode;
uint32be slot_id;
};
static_assert(sizeof(SysLauncherArgs28) == 0x28);
uint32 _SYSGetLauncherArgs(void* argsOut)
{
uint32 sdkVersion = coreinit::__OSGetProcessSDKVersion();
if(sdkVersion < 21103)
{
// old format
SysLauncherArgs18* launcherArgs18 = (SysLauncherArgs18*)argsOut;
memset(launcherArgs18, 0, sizeof(SysLauncherArgs18));
}
else
{
// new format
SysLauncherArgs28* launcherArgs28 = (SysLauncherArgs28*)argsOut;
memset(launcherArgs28, 0, sizeof(SysLauncherArgs28));
}
return 0; // return argument is todo
}
struct SysAccountArgs18
{
uint32be ukn00;
uint32be ukn04;
uint32be ukn08;
uint32be ukn0C;
// shares part above with Standard arg
uint32be slotId; // "slot_id"
uint32be mode; // "mode"
};
uint32 _SYSGetAccountArgs(SysAccountArgs18* argsOut)
{
memset(argsOut, 0, sizeof(SysAccountArgs18));
// sysDeserializeStandardArguments_t ?
return 0;
}
void sysappExport_SYSGetStandardResult(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "SYSGetStandardResult(0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
memset(memory_getPointerFromVirtualOffset(hCPU->gpr[3]), 0, 4);
// r3 = uint32be* output
// r4 = pointer to data to parse?
// r5 = size to parse?
osLib_returnFromFunction(hCPU, 0);
}
namespace sysapp
{
void SYSClearSysArgs()
{
cemuLog_logDebug(LogType::Force, "SYSClearSysArgs()");
coreinit::__OSClearCopyData();
}
uint32 _SYSLaunchTitleByPathFromLauncher(const char* path, uint32 pathLength)
{
coreinit::__OSClearCopyData();
_SYSAppendCallerInfo();
return coreinit::OSLaunchTitleByPathl(path, pathLength, 0);
}
uint32 SYSRelaunchTitle(uint32 argc, MEMPTR<char>* argv)
{
// calls ACPCheckSelfTitleNotReferAccountLaunch?
coreinit::__OSClearCopyData();
_SYSAppendCallerInfo();
return coreinit::OSRestartGame(argc, argv);
}
struct EManualArgs
{
sysStandardArguments_t stdArgs;
uint64be titleId;
};
static_assert(sizeof(EManualArgs) == 0x10);
void _SYSSwitchToEManual(EManualArgs* args)
{
// the struct has the titleId at offset 8 and standard args at 0 (total size is most likely 0x10)
cemuLog_log(LogType::Force, "SYSSwitchToEManual called. Opening the manual is not supported");
coreinit::StartBackgroundForegroundTransition();
}
void SYSSwitchToEManual()
{
EManualArgs args{};
args.titleId = coreinit::OSGetTitleID();
_SYSSwitchToEManual(&args);
}
void load()
{
cafeExportRegisterFunc(SYSClearSysArgs, "sysapp", "SYSClearSysArgs", LogType::Placeholder);
cafeExportRegisterFunc(_SYSLaunchTitleByPathFromLauncher, "sysapp", "_SYSLaunchTitleByPathFromLauncher", LogType::Placeholder);
cafeExportRegisterFunc(SYSRelaunchTitle, "sysapp", "SYSRelaunchTitle", LogType::Placeholder);
cafeExportRegister("sysapp", _SYSSwitchToEManual, LogType::Placeholder);
cafeExportRegister("sysapp", SYSSwitchToEManual, LogType::Placeholder);
}
}
// register sysapp functions
void sysapp_load()
{
osLib_addFunction("sysapp", "_SYSLaunchMiiStudio", sysappExport__SYSLaunchMiiStudio);
osLib_addFunction("sysapp", "_SYSGetMiiStudioArgs", sysappExport__SYSGetMiiStudioArgs);
osLib_addFunction("sysapp", "_SYSGetSettingsArgs", sysappExport__SYSGetSettingsArgs);
osLib_addFunction("sysapp", "_SYSReturnToCallerWithStandardResult", sysappExport__SYSReturnToCallerWithStandardResult);
osLib_addFunction("sysapp", "_SYSGetSystemApplicationTitleId", sysappExport__SYSGetSystemApplicationTitleId);
osLib_addFunction("sysapp", "SYSGetUPIDFromTitleID", sysappExport_SYSGetUPIDFromTitleID);
osLib_addFunction("sysapp", "_SYSGetEShopArgs", sysappExport__SYSGetEShopArgs);
osLib_addFunction("sysapp", "SYSGetVodArgs", sysappExport_SYSGetVodArgs);
osLib_addFunction("sysapp", "SYSGetStandardResult", sysappExport_SYSGetStandardResult);
cafeExportRegisterFunc(_SYSGetLauncherArgs, "sysapp", "_SYSGetLauncherArgs", LogType::Placeholder);
cafeExportRegisterFunc(_SYSGetAccountArgs, "sysapp", "_SYSGetAccountArgs", LogType::Placeholder);
sysapp::load();
}
| 19,372
|
C++
|
.cpp
| 614
| 29.197068
| 174
| 0.758312
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,049
|
camera.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/camera/camera.cpp
|
#include "Common/precompiled.h"
#include "Cafe/OS/common/OSCommon.h"
#include "camera.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
namespace camera
{
struct CAMInitInfo_t
{
/* +0x00 */ uint32be ukn00;
/* +0x04 */ uint32be width;
/* +0x08 */ uint32be height;
/* +0x0C */ uint32be workMemorySize;
/* +0x10 */ MEMPTR<void> workMemory;
/* +0x14 */ uint32be handlerFuncPtr;
/* +0x18 */ uint32be ukn18;
/* +0x1C */ uint32be fps;
/* +0x20 */ uint32be ukn20;
};
struct CAMTargetSurface
{
/* +0x00 */ uint32be surfaceSize;
/* +0x04 */ MEMPTR<void> surfacePtr;
/* +0x08 */ uint32be ukn08;
/* +0x0C */ uint32be ukn0C;
/* +0x10 */ uint32be ukn10;
/* +0x14 */ uint32be ukn14;
/* +0x18 */ uint32be ukn18;
/* +0x1C */ uint32be ukn1C;
};
struct CAMCallbackParam
{
// type 0 - frame decoded | field1 - imagePtr, field2 - imageSize, field3 - ukn (0)
// type 1 - ???
/* +0x0 */ uint32be type; // 0 -> Frame decoded
/* +0x4 */ uint32be field1;
/* +0x8 */ uint32be field2;
/* +0xC */ uint32be field3;
};
#define CAM_ERROR_SUCCESS 0
#define CAM_ERROR_INVALID_HANDLE -8
std::vector<struct CameraInstance*> g_table_cameraHandles;
std::vector<struct CameraInstance*> g_activeCameraInstances;
std::recursive_mutex g_mutex_camera;
std::atomic_int g_cameraCounter{ 0 };
SysAllocator<coreinit::OSAlarm_t, 1> g_alarm_camera;
SysAllocator<CAMCallbackParam, 1> g_cameraHandlerParam;
CameraInstance* GetCameraInstanceByHandle(sint32 camHandle)
{
std::unique_lock<std::recursive_mutex> _lock(g_mutex_camera);
if (camHandle <= 0)
return nullptr;
camHandle -= 1;
if (camHandle >= g_table_cameraHandles.size())
return nullptr;
return g_table_cameraHandles[camHandle];
}
struct CameraInstance
{
CameraInstance(uint32 frameWidth, uint32 frameHeight, MPTR handlerFunc) : width(frameWidth), height(frameHeight), handlerFunc(handlerFunc) { AcquireHandle(); };
~CameraInstance() { if (isOpen) { CloseCam(); } ReleaseHandle(); };
sint32 handle{ 0 };
uint32 width;
uint32 height;
bool isOpen{false};
std::queue<CAMTargetSurface> queue_targetSurfaces;
MPTR handlerFunc;
bool OpenCam()
{
if (isOpen)
return false;
isOpen = true;
g_activeCameraInstances.push_back(this);
return true;
}
bool CloseCam()
{
if (!isOpen)
return false;
isOpen = false;
vectorRemoveByValue(g_activeCameraInstances, this);
return true;
}
void QueueTargetSurface(CAMTargetSurface* targetSurface)
{
std::unique_lock<std::recursive_mutex> _lock(g_mutex_camera);
cemu_assert_debug(queue_targetSurfaces.size() < 100); // check for sane queue length
queue_targetSurfaces.push(*targetSurface);
}
private:
void AcquireHandle()
{
std::unique_lock<std::recursive_mutex> _lock(g_mutex_camera);
for (uint32 i = 0; i < g_table_cameraHandles.size(); i++)
{
if (g_table_cameraHandles[i] == nullptr)
{
g_table_cameraHandles[i] = this;
this->handle = i + 1;
return;
}
}
this->handle = (sint32)(g_table_cameraHandles.size() + 1);
g_table_cameraHandles.push_back(this);
}
void ReleaseHandle()
{
for (uint32 i = 0; i < g_table_cameraHandles.size(); i++)
{
if (g_table_cameraHandles[i] == this)
{
g_table_cameraHandles[i] = nullptr;
return;
}
}
cemu_assert_debug(false);
}
};
sint32 CAMGetMemReq(void* ukn)
{
return 1 * 1024; // always return 1KB
}
sint32 CAMCheckMemSegmentation(void* base, uint32 size)
{
return CAM_ERROR_SUCCESS; // always return success
}
void ppcCAMUpdate60(PPCInterpreter_t* hCPU)
{
// update all open camera instances
size_t numCamInstances = g_activeCameraInstances.size();
//for (auto& itr : g_activeCameraInstances)
for(size_t i=0; i<numCamInstances; i++)
{
std::unique_lock<std::recursive_mutex> _lock(g_mutex_camera);
if (i >= g_activeCameraInstances.size())
break;
CameraInstance* camInstance = g_activeCameraInstances[i];
// todo - handle 30 / 60 FPS
if (camInstance->queue_targetSurfaces.empty())
continue;
auto& targetSurface = camInstance->queue_targetSurfaces.front();
g_cameraHandlerParam->type = 0;
g_cameraHandlerParam->field1 = targetSurface.surfacePtr.GetMPTR();
g_cameraHandlerParam->field2 = targetSurface.surfaceSize;
g_cameraHandlerParam->field3 = 0;
cemu_assert_debug(camInstance->handlerFunc != MPTR_NULL);
camInstance->queue_targetSurfaces.pop();
_lock.unlock();
PPCCoreCallback(camInstance->handlerFunc, g_cameraHandlerParam.GetPtr());
}
osLib_returnFromFunction(hCPU, 0);
}
sint32 CAMInit(uint32 cameraId, CAMInitInfo_t* camInitInfo, uint32be* error)
{
CameraInstance* camInstance = new CameraInstance(camInitInfo->width, camInitInfo->height, camInitInfo->handlerFuncPtr);
std::unique_lock<std::recursive_mutex> _lock(g_mutex_camera);
if (g_cameraCounter == 0)
{
coreinit::OSCreateAlarm(g_alarm_camera.GetPtr());
coreinit::OSSetPeriodicAlarm(g_alarm_camera.GetPtr(), coreinit::coreinit_getOSTime(), (uint64)ESPRESSO_TIMER_CLOCK / 60ull, RPLLoader_MakePPCCallable(ppcCAMUpdate60));
}
g_cameraCounter++;
return camInstance->handle;
}
sint32 CAMExit(sint32 camHandle)
{
CameraInstance* camInstance = GetCameraInstanceByHandle(camHandle);
if (!camInstance)
return CAM_ERROR_INVALID_HANDLE;
CAMClose(camHandle);
delete camInstance;
std::unique_lock<std::recursive_mutex> _lock(g_mutex_camera);
g_cameraCounter--;
if (g_cameraCounter == 0)
coreinit::OSCancelAlarm(g_alarm_camera.GetPtr());
return CAM_ERROR_SUCCESS;
}
sint32 CAMOpen(sint32 camHandle)
{
CameraInstance* camInstance = GetCameraInstanceByHandle(camHandle);
if (!camInstance)
return CAM_ERROR_INVALID_HANDLE;
camInstance->OpenCam();
return CAM_ERROR_SUCCESS;
}
sint32 CAMClose(sint32 camHandle)
{
CameraInstance* camInstance = GetCameraInstanceByHandle(camHandle);
if (!camInstance)
return CAM_ERROR_INVALID_HANDLE;
camInstance->CloseCam();
return CAM_ERROR_SUCCESS;
}
sint32 CAMSubmitTargetSurface(sint32 camHandle, CAMTargetSurface* targetSurface)
{
CameraInstance* camInstance = GetCameraInstanceByHandle(camHandle);
if (!camInstance)
return CAM_ERROR_INVALID_HANDLE;
camInstance->QueueTargetSurface(targetSurface);
return CAM_ERROR_SUCCESS;
}
void reset()
{
g_cameraCounter = 0;
}
void load()
{
reset();
cafeExportRegister("camera", CAMGetMemReq, LogType::Placeholder);
cafeExportRegister("camera", CAMCheckMemSegmentation, LogType::Placeholder);
cafeExportRegister("camera", CAMInit, LogType::Placeholder);
cafeExportRegister("camera", CAMExit, LogType::Placeholder);
cafeExportRegister("camera", CAMOpen, LogType::Placeholder);
cafeExportRegister("camera", CAMClose, LogType::Placeholder);
cafeExportRegister("camera", CAMSubmitTargetSurface, LogType::Placeholder);
}
}
| 7,008
|
C++
|
.cpp
| 219
| 28.771689
| 170
| 0.728027
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,050
|
swkbd.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/swkbd/swkbd.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/OS/libs/gx2/GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Renderer/Renderer.h"
#include <imgui.h>
#include "imgui/imgui_extension.h"
#include "util/helpers/helpers.h"
#include "resource/IconsFontAwesome5.h"
#define SWKBD_FORM_STRING_MAX_LENGTH (4096) // counted in 16-bit characters
#define SWKBD_STATE_BLANK (0) // not visible
#define SWKBD_STATE_APPEARING (1) // fade-in ?
#define SWKBD_STATE_DISPLAYED (2) // visible
#define SWKBD_STATE_DISAPPEARING (3) // fade-out ?
typedef struct
{
uint32 ukn00; // constructor?
uint32 ukn04; // destructor?
uint32 ukn08; // ?
MEMPTR<void> changeString; // some function address
}SwkbdIEventReceiverVTable_t;
typedef struct
{
MEMPTR<SwkbdIEventReceiverVTable_t> vTable;
// todo - more elements? (currently separated from this struct)
}SwkbdIEventReceiver_t;
struct swkbdReceiverArg_t
{
MEMPTR<SwkbdIEventReceiver_t> IEventReceiver;
MEMPTR<sint16be> stringBuf;
sint32be stringBufSize;
sint32be fixedCharLimit;
sint32be cursorPos;
sint32be selectFrom;
};
typedef struct
{
uint32 ukn000;
uint32 controllerType;
uint32 keyboardMode; // guessed
uint32 ukn00C;
uint32 ukn010;
uint32 ukn014;
uint32 ukn018;
uint32 ukn01C; // ok string?
uint32 ukn020[4];
uint32 ukn030[4];
uint32 ukn040[4];
uint32 ukn050[4];
uint32 ukn060[4];
uint32 ukn070[4];
uint32 ukn080[4];
uint32 ukn090[4];
uint32 ukn0A0;
uint32 ukn0A4;
//uint32 ukn0A8;
//MEMPTR<SwkbdIEventReceiver_t> IEventReceiver;
swkbdReceiverArg_t receiverArg;
}SwkbdKeyboardArg_t;
typedef struct
{
// this structure resides in PPC addressable memory space
wchar_t formStringBuffer[SWKBD_FORM_STRING_MAX_LENGTH];
sint32 formStringLength;
// big endian version of the string buffer (converted whenever GetInputFormString is called)
uint16 formStringBufferBE[SWKBD_FORM_STRING_MAX_LENGTH];
bool isActive; // set when SwkbdAppearInputForm() is called
//bool isDisplayed; // set when keyboard is rendering
bool decideButtonWasPressed; // set to false when keyboard appears, and set to true when enter is pressed. Remains on true after the keyboard is disappeared (todo: Investigate how this really works)
// keyboard only mode (no input form)
bool keyboardOnlyMode;
SwkbdKeyboardArg_t keyboardArg;
// input form appear args
sint32 maxTextLength;
// imgui keyboard drawing stuff
bool shiftActivated;
bool returnState;
bool cancelState;
}swkbdInternalState_t;
swkbdInternalState_t* swkbdInternalState = NULL;
void swkbdExport_SwkbdCreate(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "swkbd.SwkbdCreate(0x{:08x},0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
if( swkbdInternalState == NULL )
{
MPTR swkbdInternalStateMPTR = coreinit_allocFromSysArea(sizeof(swkbdInternalState_t), 4);
swkbdInternalState = (swkbdInternalState_t*)memory_getPointerFromVirtualOffset(swkbdInternalStateMPTR);
memset(swkbdInternalState, 0x00, sizeof(swkbdInternalState_t));
}
osLib_returnFromFunction(hCPU, 0); // should return true?
}
void swkbdExport_SwkbdGetStateKeyboard(PPCInterpreter_t* hCPU)
{
uint32 r = SWKBD_STATE_BLANK;
if( swkbdInternalState->isActive )
r = SWKBD_STATE_DISPLAYED;
osLib_returnFromFunction(hCPU, r);
}
void swkbdExport_SwkbdGetStateInputForm(PPCInterpreter_t* hCPU)
{
//debug_printf("SwkbdGetStateInputForm__3RplFv LR: %08x\n", hCPU->sprNew.LR);
uint32 r = SWKBD_STATE_BLANK;
if( swkbdInternalState->isActive )
r = SWKBD_STATE_DISPLAYED;
osLib_returnFromFunction(hCPU, r);
}
//ReceiverArg:
//+0x00 IEventReceiver*
//+0x04 stringBuf
//+ 0x08 stringBufSize
//+ 0x0C fixedCharNumLimit(-1)
//+ 0x10 cursorPos
//+ 0x14 selectFrom(-1)
//
//IEventReceiver:
//+0x00 IEventReceiver_vTable*
//+0x04 ?
//+0x08 ?
//+0x0C ?
//
//IEventReceiver_vTable :
// +0x00 ?
// +0x04 ?
// +0x08 ?
// +0x0C functionPtr onDirtyString(const DirtyInfo& info) = 0; ->DirtyInfo is just two DWORDs.From and to ?
// ?
typedef struct
{
MPTR vTable; // guessed
}swkdbIEventReceiver_t;
typedef struct
{
uint32 ukn00;
uint32 ukn04;
uint32 ukn08;
MPTR onDirtyString;
}swkdbIEventReceiverVTable_t;
void swkbdExport_SwkbdSetReceiver(PPCInterpreter_t* hCPU)
{
debug_printf("SwkbdSetReceiver(0x%08x)\n", hCPU->gpr[3]);
swkbdReceiverArg_t* receiverArg = (swkbdReceiverArg_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
if(swkbdInternalState == nullptr)
{
osLib_returnFromFunction(hCPU, 0);
return;
}
swkbdInternalState->keyboardArg.receiverArg = *receiverArg;
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
/* +0x00 */ uint32 ukn00;
/* +0x04 */ uint32 ukn04;
/* +0x08 */ uint32 ukn08;
/* +0x0C */ uint32 ukn0C;
/* +0x10 */ uint32 ukn10;
/* +0x14 */ uint32 ukn14;
/* +0x18 */ uint32 ukn18;
/* +0x1C */ uint32 ukn1C; // pointer to OK string
/* +0x20 */ uint32 ukn20[4];
/* +0x30 */ uint32 ukn30[4];
/* +0x40 */ uint32 ukn40[4];
/* +0x50 */ uint32 ukn50[4];
/* +0x60 */ uint32 ukn60[4];
/* +0x70 */ uint32 ukn70[4];
/* +0x80 */ uint32 ukn80[4];
/* +0x90 */ uint32 ukn90[4];
/* +0xA0 */ uint32 uknA0[4];
/* +0xB0 */ uint32 uknB0[4];
/* +0xC0 */ uint32 inputFormType;
/* +0xC4 */ uint32be cursorIndex;
/* +0xC8 */ MEMPTR<uint16be> initialText;
/* +0xCC */ MEMPTR<uint16be> infoText;
/* +0xD0 */ uint32be maxTextLength;
}swkbdAppearArg_t;
static_assert(offsetof(swkbdAppearArg_t, cursorIndex) == 0xC4, "appearArg.cursorIndex has invalid offset");
void swkbdExport_SwkbdAppearInputForm(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(appearArg, swkbdAppearArg_t, 0);
cemuLog_logDebug(LogType::Force, "SwkbdAppearInputForm__3RplFRCQ3_2nn5swkbd9AppearArg");
swkbdInternalState->formStringLength = 0;
swkbdInternalState->isActive = true;
swkbdInternalState->decideButtonWasPressed = false;
swkbdInternalState->keyboardOnlyMode = false;
// setup max text length
swkbdInternalState->maxTextLength = (sint32)(uint32)appearArg->maxTextLength;
if (swkbdInternalState->maxTextLength <= 0)
swkbdInternalState->maxTextLength = SWKBD_FORM_STRING_MAX_LENGTH - 1;
else
swkbdInternalState->maxTextLength = std::min(swkbdInternalState->maxTextLength, SWKBD_FORM_STRING_MAX_LENGTH - 1);
// setup initial string
uint16be* initialString = appearArg->initialText.GetPtr();
if (initialString)
{
swkbdInternalState->formStringLength = 0;
for (sint32 i = 0; i < swkbdInternalState->maxTextLength; i++)
{
wchar_t c = (uint16)initialString[i];
if( c == '\0' )
break;
swkbdInternalState->formStringBuffer[i] = c;
swkbdInternalState->formStringLength++;
}
}
else
{
swkbdInternalState->formStringBuffer[0] = '\0';
swkbdInternalState->formStringLength = 0;
}
osLib_returnFromFunction(hCPU, 1);
}
void swkbdExport_SwkbdAppearKeyboard(PPCInterpreter_t* hCPU)
{
// todo: Figure out what the difference between AppearInputForm and AppearKeyboard is?
cemuLog_logDebug(LogType::Force, "SwkbdAppearKeyboard__3RplFRCQ3_2nn5swkbd11KeyboardArg");
SwkbdKeyboardArg_t* keyboardArg = (SwkbdKeyboardArg_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint32 argPtr = hCPU->gpr[3];
for(sint32 i=0; i<0x180; i += 4)
{
debug_printf("+0x%03x: 0x%08x\n", i, memory_readU32(argPtr+i));
}
swkbdInternalState->formStringLength = 0;
swkbdInternalState->isActive = true;
swkbdInternalState->keyboardOnlyMode = true;
swkbdInternalState->decideButtonWasPressed = false;
swkbdInternalState->formStringBuffer[0] = '\0';
swkbdInternalState->formStringLength = 0;
swkbdInternalState->keyboardArg = *keyboardArg;
osLib_returnFromFunction(hCPU, 1);
}
void swkbdExport_SwkbdDisappearInputForm(PPCInterpreter_t* hCPU)
{
debug_printf("SwkbdDisappearInputForm__3RplFv LR: %08x\n", hCPU->spr.LR);
swkbdInternalState->isActive = false;
osLib_returnFromFunction(hCPU, 1);
}
void swkbdExport_SwkbdDisappearKeyboard(PPCInterpreter_t* hCPU)
{
debug_printf("SwkbdDisappearKeyboard__3RplFv LR: %08x\n", hCPU->spr.LR);
swkbdInternalState->isActive = false;
osLib_returnFromFunction(hCPU, 1);
}
void swkbdExport_SwkbdGetInputFormString(PPCInterpreter_t* hCPU)
{
for(sint32 i=0; i<swkbdInternalState->formStringLength; i++)
{
swkbdInternalState->formStringBufferBE[i] = _swapEndianU16(swkbdInternalState->formStringBuffer[i]);
}
swkbdInternalState->formStringBufferBE[swkbdInternalState->formStringLength] = '\0';
osLib_returnFromFunction(hCPU, memory_getVirtualOffsetFromPointer(swkbdInternalState->formStringBufferBE));
}
void swkbdExport_SwkbdIsDecideOkButton(PPCInterpreter_t* hCPU)
{
if (swkbdInternalState->decideButtonWasPressed)
osLib_returnFromFunction(hCPU, 1);
else
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
uint32be ukn00;
uint32be ukn04;
uint32be ukn08;
uint32be ukn0C;
uint32be ukn10;
uint32be ukn14;
uint8 ukn18;
// there might be padding here?
}SwkbdDrawStringInfo_t;
static_assert(sizeof(SwkbdDrawStringInfo_t) != 0x19, "SwkbdDrawStringInfo_t has invalid size");
void swkbdExport_SwkbdGetDrawStringInfo(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "SwkbdGetDrawStringInfo(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(drawStringInfo, SwkbdDrawStringInfo_t, 0);
drawStringInfo->ukn00 = -1;
drawStringInfo->ukn04 = -1;
drawStringInfo->ukn08 = -1;
drawStringInfo->ukn0C = -1;
drawStringInfo->ukn10 = -1;
drawStringInfo->ukn14 = -1;
drawStringInfo->ukn18 = 0;
osLib_returnFromFunction(hCPU, 0);
}
void swkbdExport_SwkbdInitLearnDic(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "SwkbdInitLearnDic(0x{:08x})", hCPU->gpr[3]);
// todo
// this has to fail (at least once?) or MH3U will not boot
osLib_returnFromFunction(hCPU, 1);
}
bool isNeedCalc0 = true;
bool isNeedCalc1 = true;
void swkbdExport_SwkbdIsNeedCalcSubThreadFont(PPCInterpreter_t* hCPU)
{
// SwkbdIsNeedCalcSubThreadFont__3RplFv
bool r = false;
osLib_returnFromFunction(hCPU, r?1:0);
}
void swkbdExport_SwkbdIsNeedCalcSubThreadPredict(PPCInterpreter_t* hCPU)
{
// SwkbdIsNeedCalcSubThreadPredict__3RplFv
bool r = false;
osLib_returnFromFunction(hCPU, r?1:0);
}
void swkbd_keyInput(uint32 keyCode);
void swkbd_render(bool mainWindow)
{
// only render if active
if( swkbdInternalState == NULL || swkbdInternalState->isActive == false)
return;
auto& io = ImGui::GetIO();
const auto font = ImGui_GetFont(48.0f);
const auto textFont = ImGui_GetFont(24.0f);
if (!font || !textFont)
return;
const auto kPopupFlags = ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings;
ImGui::PushStyleColor(ImGuiCol_WindowBg, 0);
ImGui::SetNextWindowPos({ 0,0 }, ImGuiCond_Always);
ImGui::SetNextWindowSize(io.DisplaySize, ImGuiCond_Always);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0,0 });
ImGui::SetNextWindowBgAlpha(0.8f);
ImGui::Begin("Background overlay", nullptr, kPopupFlags | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus);
ImGui::End();
ImGui::PopStyleVar(2);
ImVec2 position = { io.DisplaySize.x / 2.0f, io.DisplaySize.y / 3.0f };
ImVec2 pivot = { 0.5f, 0.5f };
const auto button_len = font->GetCharAdvance('W');
const float len = button_len * std::max(4, std::max(swkbdInternalState->maxTextLength, (sint32)swkbdInternalState->keyboardArg.receiverArg.stringBufSize));
ImVec2 box_size = { std::min(io.DisplaySize.x * 0.9f, len + 90), 0 };
ImGui::SetNextWindowPos(position, ImGuiCond_Always, pivot);
ImGui::SetNextWindowSize(box_size, ImGuiCond_Always);
ImGui::SetNextWindowBgAlpha(0.9f);
ImGui::PushFont(font);
if (ImGui::Begin("Keyboard Input", nullptr, kPopupFlags))
{
ImGui::Text("%s", _utf8WrapperPtr(ICON_FA_KEYBOARD));
ImGui::SameLine(70);
auto text = boost::nowide::narrow(fmt::format(L"{}", swkbdInternalState->formStringBuffer));
static std::chrono::steady_clock::time_point s_last_tick = tick_cached();
static bool s_blink_state = false;
const auto now = tick_cached();
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - s_last_tick).count() >= 500)
{
s_blink_state = !s_blink_state;
s_last_tick = now;
}
if (s_blink_state)
text += "|";
ImGui::PushTextWrapPos();
ImGui::TextUnformatted(text.c_str(), text.c_str() + text.size());
ImGui::PopTextWrapPos();
position.y += ImGui::GetWindowSize().y + 100.0f;
}
ImGui::End();
ImGui::PopFont();
ImGui::SetNextWindowPos(position, ImGuiCond_Always, pivot);
//ImGui::SetNextWindowSize({ io.DisplaySize.x * 0.9f , 0.0f}, ImGuiCond_Always);
ImGui::SetNextWindowBgAlpha(0.9f);
ImGui::PushFont(textFont);
if (ImGui::Begin(fmt::format("Software keyboard##SoftwareKeyboard{}",mainWindow).c_str(), nullptr, kPopupFlags))
{
if(swkbdInternalState->shiftActivated)
{
const char* keys[] =
{
"#", "[", "]", "$", "%", "^", "&", "*", "(", ")", "_", _utf8WrapperPtr(ICON_FA_ARROW_CIRCLE_LEFT), "\n",
"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "@", "\n",
"A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "\"", "\n",
"Z", "X", "C", "V", "B", "N", "M", "<", ">", "+", "=", "\n",
_utf8WrapperPtr(ICON_FA_ARROW_UP), " ", _utf8WrapperPtr(ICON_FA_CHECK)
};
for (auto key : keys)
{
if (*key != '\n')
{
if (ImGui::Button(key, { *key == ' ' ? 537 : (button_len + 5), 0}))
{
if (strcmp(key, _utf8WrapperPtr(ICON_FA_ARROW_CIRCLE_LEFT)) == 0)
swkbd_keyInput(8);
else if (strcmp(key, _utf8WrapperPtr(ICON_FA_ARROW_UP)) == 0)
swkbdInternalState->shiftActivated = !swkbdInternalState->shiftActivated;
else if (strcmp(key, _utf8WrapperPtr(ICON_FA_CHECK)) == 0)
swkbd_keyInput(13);
else
swkbd_keyInput(*key);
}
ImGui::SameLine();
}
else
ImGui::NewLine();
}
}
else
{
const char* keys[] =
{
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", _utf8WrapperPtr(ICON_FA_ARROW_CIRCLE_LEFT), "\n",
"q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "/", "\n",
"a", "s", "d", "f", "g", "h", "j", "k", "l", ":", "'", "\n",
"z", "x", "c", "v", "b", "n", "m", ",", ".", "?", "!", "\n",
_utf8WrapperPtr(ICON_FA_ARROW_UP), " ", _utf8WrapperPtr(ICON_FA_CHECK)
};
for (auto key : keys)
{
if (*key != '\n')
{
if (ImGui::Button(key, { *key == ' ' ? 537 : (button_len + 5), 0 }))
{
if (strcmp(key, _utf8WrapperPtr(ICON_FA_ARROW_CIRCLE_LEFT)) == 0)
swkbd_keyInput(8);
else if (strcmp(key, _utf8WrapperPtr(ICON_FA_ARROW_UP)) == 0)
swkbdInternalState->shiftActivated = !swkbdInternalState->shiftActivated;
else if (strcmp(key, _utf8WrapperPtr(ICON_FA_CHECK)) == 0)
swkbd_keyInput(13);
else
swkbd_keyInput(*key);
}
ImGui::SameLine();
}
else
ImGui::NewLine();
}
}
ImGui::NewLine();
}
ImGui::End();
if (io.NavInputs[ImGuiNavInput_Cancel] > 0)
{
if(!swkbdInternalState->cancelState)
swkbd_keyInput(8); // backspace
swkbdInternalState->cancelState = true;
}
else
swkbdInternalState->cancelState = false;
if (io.NavInputs[ImGuiNavInput_Input] > 0)
{
if (!swkbdInternalState->returnState)
swkbd_keyInput(13); // return
swkbdInternalState->returnState = true;
}
else
swkbdInternalState->returnState = false;
ImGui::PopFont();
ImGui::PopStyleColor();
}
bool swkbd_hasKeyboardInputHook()
{
return swkbdInternalState != NULL && swkbdInternalState->isActive;
}
void swkbd_finishInput()
{
swkbdInternalState->decideButtonWasPressed = true; // currently we always accept the input
}
typedef struct
{
uint32be beginIndex;
uint32be endIndex;
}changeStringParam_t;
SysAllocator<changeStringParam_t> _changeStringParam;
void swkbd_inputStringChanged()
{
if( true )//swkbdInternalState->keyboardOnlyMode )
{
// write changed string to application's string buffer
uint32 stringBufferSize = swkbdInternalState->keyboardArg.receiverArg.stringBufSize; // in 2-byte words
if( stringBufferSize > 1 )
{
stringBufferSize--; // don't count the null-termination character
const auto stringBufferBE = swkbdInternalState->keyboardArg.receiverArg.stringBuf.GetPtr();
sint32 copyLength = std::min((sint32)stringBufferSize, swkbdInternalState->formStringLength);
for(sint32 i=0; i<copyLength; i++)
{
stringBufferBE[i] = swkbdInternalState->formStringBuffer[i];
}
stringBufferBE[copyLength] = '\0';
//swkbdInternalState->keyboardArg.cursorPos = copyLength;
}
// IEventReceiver callback
if (swkbdInternalState->keyboardArg.receiverArg.IEventReceiver)
{
SwkbdIEventReceiver_t* eventReceiver = swkbdInternalState->keyboardArg.receiverArg.IEventReceiver.GetPtr();
MPTR cbChangeString = eventReceiver->vTable->changeString.GetMPTR();
if (cbChangeString)
{
changeStringParam_t* changeStringParam = _changeStringParam.GetPtr();
changeStringParam->beginIndex = 0;
changeStringParam->endIndex = 0;
coreinitAsyncCallback_add(cbChangeString, 2, memory_getVirtualOffsetFromPointer(eventReceiver), _changeStringParam.GetMPTR());
}
}
}
}
void swkbd_keyInput(uint32 keyCode)
{
if (keyCode == 8 || keyCode == 127) // backspace || backwards delete
{
if (swkbdInternalState->formStringLength > 0)
swkbdInternalState->formStringLength--;
swkbdInternalState->formStringBuffer[swkbdInternalState->formStringLength] = '\0';
swkbd_inputStringChanged();
return;
}
else if (keyCode == 13) // return
{
swkbd_finishInput();
return;
}
// check if allowed character
if ((keyCode >= 'a' && keyCode <= 'z') ||
(keyCode >= 'A' && keyCode <= 'Z'))
{
// allowed
}
else if ((keyCode >= '0' && keyCode <= '9'))
{
// allowed
}
else if (keyCode == ' ' || keyCode == '.' || keyCode == '/' || keyCode == '?' || keyCode == '=')
{
// allowed
}
else if (keyCode < 32)
{
// control key
return;
}
else
;// return;
// get max length
sint32 maxLength = swkbdInternalState->maxTextLength;
if (swkbdInternalState->keyboardOnlyMode)
{
uint32 stringBufferSize = swkbdInternalState->keyboardArg.receiverArg.stringBufSize;
if (stringBufferSize > 1)
{
maxLength = stringBufferSize - 1; // don't count the null-termination character
}
else
maxLength = 0;
}
// append character
if (swkbdInternalState->formStringLength < maxLength)
{
swkbdInternalState->formStringBuffer[swkbdInternalState->formStringLength] = keyCode;
swkbdInternalState->formStringLength++;
swkbdInternalState->formStringBuffer[swkbdInternalState->formStringLength] = '\0';
swkbd_inputStringChanged();
}
}
namespace swkbd
{
void load()
{
osLib_addFunction("swkbd", "SwkbdCreate__3RplFPUcQ3_2nn5swkbd10RegionTypeUiP8FSClient", swkbdExport_SwkbdCreate);
osLib_addFunction("swkbd", "SwkbdGetStateKeyboard__3RplFv", swkbdExport_SwkbdGetStateKeyboard);
osLib_addFunction("swkbd", "SwkbdGetStateInputForm__3RplFv", swkbdExport_SwkbdGetStateInputForm);
osLib_addFunction("swkbd", "SwkbdSetReceiver__3RplFRCQ3_2nn5swkbd11ReceiverArg", swkbdExport_SwkbdSetReceiver);
osLib_addFunction("swkbd", "SwkbdAppearInputForm__3RplFRCQ3_2nn5swkbd9AppearArg", swkbdExport_SwkbdAppearInputForm);
osLib_addFunction("swkbd", "SwkbdDisappearInputForm__3RplFv", swkbdExport_SwkbdDisappearInputForm);
osLib_addFunction("swkbd", "SwkbdDisappearKeyboard__3RplFv", swkbdExport_SwkbdDisappearKeyboard);
osLib_addFunction("swkbd", "SwkbdAppearKeyboard__3RplFRCQ3_2nn5swkbd11KeyboardArg", swkbdExport_SwkbdAppearKeyboard);
osLib_addFunction("swkbd", "SwkbdGetInputFormString__3RplFv", swkbdExport_SwkbdGetInputFormString);
osLib_addFunction("swkbd", "SwkbdIsDecideOkButton__3RplFPb", swkbdExport_SwkbdIsDecideOkButton);
osLib_addFunction("swkbd", "SwkbdInitLearnDic__3RplFPv", swkbdExport_SwkbdInitLearnDic);
osLib_addFunction("swkbd", "SwkbdGetDrawStringInfo__3RplFPQ3_2nn5swkbd14DrawStringInfo", swkbdExport_SwkbdGetDrawStringInfo);
osLib_addFunction("swkbd", "SwkbdIsNeedCalcSubThreadFont__3RplFv", swkbdExport_SwkbdIsNeedCalcSubThreadFont);
osLib_addFunction("swkbd", "SwkbdIsNeedCalcSubThreadPredict__3RplFv", swkbdExport_SwkbdIsNeedCalcSubThreadPredict);
}
}
| 20,225
|
C++
|
.cpp
| 571
| 32.845884
| 199
| 0.738087
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,051
|
GX2_Blit.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Blit.cpp
|
#include "Common/precompiled.h"
#include "GX2_Blit.h"
#include "GX2_Command.h"
#include "GX2_Surface.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/OS/common/OSCommon.h"
#include "GX2_Resource.h"
namespace GX2
{
// sets the depth/stencil clear registers and updates clear values in DepthBuffer struct
void GX2SetClearDepthStencil(GX2DepthBuffer* depthBuffer, float depthClearValue, uint8 stencilClearValue)
{
GX2ReserveCmdSpace(4);
*(uint32*)&depthBuffer->clearDepth = _swapEndianU32(*(uint32*)&depthClearValue);
depthBuffer->clearStencil = _swapEndianU32(stencilClearValue);
Latte::LATTE_DB_STENCIL_CLEAR stencilClearReg;
stencilClearReg.set_clearValue(stencilClearValue);
Latte::LATTE_DB_DEPTH_CLEAR depthClearReg;
depthClearReg.set_clearValue(depthClearValue);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 2),
Latte::REGADDR::DB_STENCIL_CLEAR - 0xA000,
stencilClearReg, depthClearReg);
}
// similar to GX2SetClearDepthStencil but only sets depth
void GX2SetClearDepth(GX2DepthBuffer* depthBuffer, float depthClearValue)
{
GX2ReserveCmdSpace(3);
*(uint32*)&depthBuffer->clearDepth = _swapEndianU32(*(uint32*)&depthClearValue);
Latte::LATTE_DB_DEPTH_CLEAR depthClearReg;
depthClearReg.set_clearValue(depthClearValue);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_DEPTH_CLEAR - 0xA000,
depthClearReg);
}
// similar to GX2SetClearDepthStencil but only sets stencil
void GX2SetClearStencil(GX2DepthBuffer* depthBuffer, uint8 stencilClearValue)
{
GX2ReserveCmdSpace(3);
depthBuffer->clearStencil = _swapEndianU32(stencilClearValue);
Latte::LATTE_DB_STENCIL_CLEAR stencilClearReg;
stencilClearReg.set_clearValue(stencilClearValue);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_STENCIL_CLEAR - 0xA000,
stencilClearReg);
}
// update DB_STENCIL_CLEAR and DB_STENCIL_CLEAR based on clear flags
void _updateDepthStencilClearRegs(float depthClearValue, uint8 stencilClearValue, GX2ClearFlags clearFlags)
{
if ((clearFlags & GX2ClearFlags::SET_DEPTH_REG) != 0 && (clearFlags & GX2ClearFlags::SET_STENCIL_REG) != 0)
{
GX2ReserveCmdSpace(4);
Latte::LATTE_DB_STENCIL_CLEAR stencilClearReg;
stencilClearReg.set_clearValue(stencilClearValue);
Latte::LATTE_DB_DEPTH_CLEAR depthClearReg;
depthClearReg.set_clearValue(depthClearValue);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 2),
Latte::REGADDR::DB_STENCIL_CLEAR - 0xA000,
stencilClearReg, depthClearReg);
}
else if ((clearFlags & GX2ClearFlags::SET_DEPTH_REG) != 0)
{
GX2ReserveCmdSpace(3);
Latte::LATTE_DB_DEPTH_CLEAR depthClearReg;
depthClearReg.set_clearValue(depthClearValue);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_DEPTH_CLEAR - 0xA000,
depthClearReg);
}
else if ((clearFlags & GX2ClearFlags::SET_STENCIL_REG) != 0)
{
GX2ReserveCmdSpace(3);
Latte::LATTE_DB_STENCIL_CLEAR stencilClearReg;
stencilClearReg.set_clearValue(stencilClearValue);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_STENCIL_CLEAR - 0xA000,
stencilClearReg);
}
}
void GX2ClearColor(GX2ColorBuffer* colorBuffer, float r, float g, float b, float a)
{
GX2ReserveCmdSpace(50);
if ((colorBuffer->surface.resFlag & GX2_RESFLAG_USAGE_COLOR_BUFFER) != 0)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_CLEAR_COLOR_DEPTH_STENCIL, 23));
gx2WriteGather_submitU32AsBE(1); // color (1)
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(colorBuffer->surface.imagePtr));
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.format.value());
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.tileMode.value());
gx2WriteGather_submitU32AsBE(colorBuffer->surface.width);
gx2WriteGather_submitU32AsBE(colorBuffer->surface.height);
gx2WriteGather_submitU32AsBE(colorBuffer->surface.pitch);
gx2WriteGather_submitU32AsBE(_swapEndianU32(colorBuffer->viewFirstSlice));
gx2WriteGather_submitU32AsBE(_swapEndianU32(colorBuffer->viewNumSlices));
gx2WriteGather_submitU32AsBE(MPTR_NULL);
gx2WriteGather_submitU32AsBE(0); // depth buffer format
gx2WriteGather_submitU32AsBE(0); // tilemode for depth buffer
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE((uint32)(r * 255.0f));
gx2WriteGather_submitU32AsBE((uint32)(g * 255.0f));
gx2WriteGather_submitU32AsBE((uint32)(b * 255.0f));
gx2WriteGather_submitU32AsBE((uint32)(a * 255.0f));
gx2WriteGather_submitU32AsBE(0); // clear depth
gx2WriteGather_submitU32AsBE(0); // clear stencil
}
else
{
debug_printf("GX2ClearColor() - unsupported surface flags\n");
}
}
void GX2ClearBuffersEx(GX2ColorBuffer* colorBuffer, GX2DepthBuffer* depthBuffer, float r, float g, float b, float a, float depthClearValue, uint8 stencilClearValue, GX2ClearFlags clearFlags)
{
GX2ReserveCmdSpace(50);
_updateDepthStencilClearRegs(depthClearValue, stencilClearValue, clearFlags);
uint32 hleClearFlags = 0;
if ((clearFlags & GX2ClearFlags::CLEAR_DEPTH) != 0)
hleClearFlags |= 2;
if ((clearFlags & GX2ClearFlags::CLEAR_STENCIL) != 0)
hleClearFlags |= 4;
hleClearFlags |= 1;
// send command to clear color, depth and stencil
if (_swapEndianU32(colorBuffer->viewFirstSlice) != 0)
debugBreakpoint();
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_CLEAR_COLOR_DEPTH_STENCIL, 23));
gx2WriteGather_submitU32AsBE(hleClearFlags); // color (1), depth (2), stencil (4)
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(colorBuffer->surface.imagePtr));
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.format.value());
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.tileMode.value());
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.width);
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.height);
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.pitch);
gx2WriteGather_submitU32AsBE(_swapEndianU32(colorBuffer->viewFirstSlice));
gx2WriteGather_submitU32AsBE(_swapEndianU32(colorBuffer->viewNumSlices));
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(depthBuffer->surface.imagePtr));
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.format.value());
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.tileMode.value());
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.width);
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.height);
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.pitch);
gx2WriteGather_submitU32AsBE(_swapEndianU32(depthBuffer->viewFirstSlice));
gx2WriteGather_submitU32AsBE(_swapEndianU32(depthBuffer->viewNumSlices));
gx2WriteGather_submitU32AsBE((uint32)(r * 255.0f));
gx2WriteGather_submitU32AsBE((uint32)(g * 255.0f));
gx2WriteGather_submitU32AsBE((uint32)(b * 255.0f));
gx2WriteGather_submitU32AsBE((uint32)(a * 255.0f));
gx2WriteGather_submitU32AsBE(*(uint32*)&depthClearValue); // clear depth
gx2WriteGather_submitU32AsBE(stencilClearValue&0xFF); // clear stencil
}
// always uses passed depthClearValue/stencilClearValue for clearing, even if clear flags dont specify value updates
void GX2ClearDepthStencilEx(GX2DepthBuffer* depthBuffer, float depthClearValue, uint8 stencilClearValue, GX2ClearFlags clearFlags)
{
GX2ReserveCmdSpace(50);
if (!depthBuffer && (depthBuffer->surface.width == 0 || depthBuffer->surface.height == 0))
{
// Super Smash Bros tries to clear an uninitialized depth surface?
debug_printf("GX2ClearDepthStencilEx(): Attempting to clear invalid depthbuffer\n");
return;
}
_updateDepthStencilClearRegs(depthClearValue, stencilClearValue, clearFlags);
uint32 hleClearFlags = 0;
if ((clearFlags & GX2ClearFlags::CLEAR_DEPTH) != 0)
hleClearFlags |= 2;
if ((clearFlags & GX2ClearFlags::CLEAR_STENCIL) != 0)
hleClearFlags |= 4;
// send command to clear color, depth and stencil
if (hleClearFlags != 0)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_CLEAR_COLOR_DEPTH_STENCIL, 23));
gx2WriteGather_submitU32AsBE(hleClearFlags); // color (1), depth (2), stencil (4)
gx2WriteGather_submitU32AsBE(MPTR_NULL);
gx2WriteGather_submitU32AsBE(0); // format for color buffer
gx2WriteGather_submitU32AsBE(0); // tilemode for color buffer
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(depthBuffer->surface.imagePtr));
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.format.value());
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.tileMode.value());
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.width);
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.height);
gx2WriteGather_submitU32AsBE((uint32)depthBuffer->surface.pitch);
gx2WriteGather_submitU32AsBE(_swapEndianU32(depthBuffer->viewFirstSlice));
gx2WriteGather_submitU32AsBE(_swapEndianU32(depthBuffer->viewNumSlices));
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(*(uint32*)&depthClearValue); // clear depth
gx2WriteGather_submitU32AsBE(stencilClearValue & 0xFF); // clear stencil
}
}
void GX2BlitInit()
{
cafeExportRegister("gx2", GX2SetClearDepthStencil, LogType::GX2);
cafeExportRegister("gx2", GX2SetClearDepth, LogType::GX2);
cafeExportRegister("gx2", GX2SetClearStencil, LogType::GX2);
cafeExportRegister("gx2", GX2ClearColor, LogType::GX2);
cafeExportRegister("gx2", GX2ClearBuffersEx, LogType::GX2);
cafeExportRegister("gx2", GX2ClearDepthStencilEx, LogType::GX2);
}
}
| 10,088
|
C++
|
.cpp
| 207
| 45.458937
| 191
| 0.78767
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,052
|
GX2_Command.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Command.cpp
|
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/OS/libs/coreinit/coreinit.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "GX2.h"
#include "GX2_Command.h"
#include "GX2_Shader.h"
#include "GX2_Misc.h"
extern uint8* gxRingBufferReadPtr;
GX2WriteGatherPipeState gx2WriteGatherPipe = { 0 };
void gx2WriteGather_submitU32AsBE(uint32 v)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(PPCInterpreter_getCurrentInstance());
if (gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] == NULL)
return;
*(uint32*)(*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex]) = _swapEndianU32(v);
(*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex]) += 4;
}
void gx2WriteGather_submitU32AsLE(uint32 v)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(PPCInterpreter_getCurrentInstance());
if (gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] == NULL)
return;
*(uint32*)(*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex]) = v;
(*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex]) += 4;
}
void gx2WriteGather_submitU32AsLEArray(uint32* v, uint32 numValues)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(PPCInterpreter_getCurrentInstance());
if (gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] == NULL)
return;
memcpy_dwords((*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex]), v, numValues);
(*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex]) += 4 * numValues;
}
namespace GX2
{
sint32 gx2WriteGatherCurrentMainCoreIndex = -1;
bool gx2WriteGatherInited = false;
void GX2WriteGather_ResetToDefaultState()
{
gx2WriteGatherCurrentMainCoreIndex = -1;
gx2WriteGatherInited = false;
}
void GX2Init_writeGather() // init write gather, make current core
{
if (gx2WriteGatherPipe.gxRingBuffer == NULL)
gx2WriteGatherPipe.gxRingBuffer = (uint8*)malloc(GX2_COMMAND_RING_BUFFER_SIZE);
if (gx2WriteGatherCurrentMainCoreIndex == sGX2MainCoreIndex)
return; // write gather already configured for same core
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
{
if (i == sGX2MainCoreIndex)
{
gx2WriteGatherPipe.writeGatherPtrGxBuffer[i] = gx2WriteGatherPipe.gxRingBuffer;
gx2WriteGatherPipe.writeGatherPtrWrite[i] = &gx2WriteGatherPipe.writeGatherPtrGxBuffer[i];
}
else
{
gx2WriteGatherPipe.writeGatherPtrGxBuffer[i] = NULL;
gx2WriteGatherPipe.writeGatherPtrWrite[i] = NULL;
}
gx2WriteGatherPipe.displayListStart[i] = MPTR_NULL;
gx2WriteGatherPipe.writeGatherPtrDisplayList[i] = NULL;
gx2WriteGatherPipe.displayListMaxSize[i] = 0;
}
gx2WriteGatherCurrentMainCoreIndex = sGX2MainCoreIndex;
gx2WriteGatherInited = true;
}
void GX2WriteGather_beginDisplayList(PPCInterpreter_t* hCPU, MPTR buffer, uint32 maxSize)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
gx2WriteGatherPipe.displayListStart[coreIndex] = buffer;
gx2WriteGatherPipe.displayListMaxSize[coreIndex] = maxSize;
// set new write gather ptr
gx2WriteGatherPipe.writeGatherPtrDisplayList[coreIndex] = memory_getPointerFromVirtualOffset(gx2WriteGatherPipe.displayListStart[coreIndex]);
gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] = &gx2WriteGatherPipe.writeGatherPtrDisplayList[coreIndex];
}
uint32 GX2WriteGather_getDisplayListWriteDistance(sint32 coreIndex)
{
return (uint32)(*gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] - memory_getPointerFromVirtualOffset(gx2WriteGatherPipe.displayListStart[coreIndex]));
}
uint32 GX2WriteGather_getFifoWriteDistance(uint32 coreIndex)
{
uint32 writeDistance = (uint32)(gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] - gx2WriteGatherPipe.gxRingBuffer);
return writeDistance;
}
uint32 GX2WriteGather_endDisplayList(PPCInterpreter_t* hCPU, MPTR buffer)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
if (gx2WriteGatherPipe.displayListStart[coreIndex] != MPTR_NULL)
{
uint32 currentWriteSize = GX2WriteGather_getDisplayListWriteDistance(coreIndex);
// pad to 32 byte
if (gx2WriteGatherPipe.displayListMaxSize[coreIndex] >= ((gx2WriteGatherPipe.displayListMaxSize[coreIndex] + 0x1F) & ~0x1F))
{
while ((currentWriteSize & 0x1F) != 0)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType2Filler());
currentWriteSize += 4;
}
}
// get size of written data
currentWriteSize = GX2WriteGather_getDisplayListWriteDistance(coreIndex);
// disable current display list and restore write gather ptr
gx2WriteGatherPipe.displayListStart[coreIndex] = MPTR_NULL;
if (sGX2MainCoreIndex == coreIndex)
gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] = &gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex];
else
gx2WriteGatherPipe.writeGatherPtrWrite[coreIndex] = NULL;
// return size of (written) display list
return currentWriteSize;
}
else
{
// no active display list
// return a size of 0
return 0;
}
}
bool GX2GetCurrentDisplayList(betype<MPTR>* displayListAddr, uint32be* displayListSize)
{
uint32 coreIndex = coreinit::OSGetCoreId();
if (gx2WriteGatherPipe.displayListStart[coreIndex] == MPTR_NULL)
return false;
if (displayListAddr)
*displayListAddr = gx2WriteGatherPipe.displayListStart[coreIndex];
if (displayListSize)
*displayListSize = gx2WriteGatherPipe.displayListMaxSize[coreIndex];
return true;
}
bool GX2GetDisplayListWriteStatus()
{
// returns true if we are writing to a display list
uint32 coreIndex = coreinit::OSGetCoreId();
return gx2WriteGatherPipe.displayListStart[coreIndex] != MPTR_NULL;
}
uint32 GX2WriteGather_getReadWriteDistance()
{
uint32 coreIndex = sGX2MainCoreIndex;
uint32 writeDistance = (uint32)(gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] + GX2_COMMAND_RING_BUFFER_SIZE - gxRingBufferReadPtr);
writeDistance %= GX2_COMMAND_RING_BUFFER_SIZE;
return writeDistance;
}
void GX2WriteGather_checkAndInsertWrapAroundMark()
{
uint32 coreIndex = coreinit::OSGetCoreId();
if (coreIndex != sGX2MainCoreIndex) // only if main gx2 core
return;
if (gx2WriteGatherPipe.displayListStart[coreIndex] != MPTR_NULL)
return;
uint32 writeDistance = GX2WriteGather_getFifoWriteDistance(coreIndex);
if (writeDistance >= (GX2_COMMAND_RING_BUFFER_SIZE * 3 / 5))
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_FIFO_WRAP_AROUND, 1));
gx2WriteGather_submitU32AsBE(0); // empty word since we can't send commands with zero data words
gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] = gx2WriteGatherPipe.gxRingBuffer;
}
}
void GX2BeginDisplayList(MEMPTR<void> displayListAddr, uint32 size)
{
GX2WriteGather_beginDisplayList(PPCInterpreter_getCurrentInstance(), displayListAddr.GetMPTR(), size);
}
void GX2BeginDisplayListEx(MEMPTR<void> displayListAddr, uint32 size, bool profiling)
{
GX2WriteGather_beginDisplayList(PPCInterpreter_getCurrentInstance(), displayListAddr.GetMPTR(), size);
}
uint32 GX2EndDisplayList(MEMPTR<void> displayListAddr)
{
cemu_assert_debug(displayListAddr != nullptr);
uint32 displayListSize = GX2WriteGather_endDisplayList(PPCInterpreter_getCurrentInstance(), displayListAddr.GetMPTR());
return displayListSize;
}
void GX2CallDisplayList(MPTR addr, uint32 size)
{
cemu_assert_debug((size&3) == 0);
// write PM4 command
GX2ReserveCmdSpace(4);
gx2WriteGather_submit(pm4HeaderType3(IT_INDIRECT_BUFFER_PRIV, 3),
memory_virtualToPhysical(addr),
0, // high address bits
size / 4);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
}
void GX2DirectCallDisplayList(void* addr, uint32 size)
{
// this API submits to TCL directly and bypasses write-gatherer
// its basically a way to manually submit a command buffer to the GPU
// as such it also affects the submission and retire timestamps
uint32 coreIndex = PPCInterpreter_getCoreIndex(PPCInterpreter_getCurrentInstance());
cemu_assert_debug(coreIndex == sGX2MainCoreIndex);
coreIndex = sGX2MainCoreIndex; // always submit to main queue which is owned by GX2 main core (TCLSubmitToRing does not need this workaround)
uint32be* cmdStream = (uint32be*)(gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex]);
cmdStream[0] = pm4HeaderType3(IT_INDIRECT_BUFFER_PRIV, 3);
cmdStream[1] = memory_virtualToPhysical(MEMPTR<void>(addr).GetMPTR());
cmdStream[2] = 0;
cmdStream[3] = size / 4;
gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] += 16;
// update submission timestamp and retired timestamp
_GX2SubmitToTCL();
}
void GX2CopyDisplayList(MEMPTR<uint32be*> addr, uint32 size)
{
// copy display list to write gather
uint32* displayListDWords = (uint32*)addr.GetPtr();
uint32 dwordCount = size / 4;
if (dwordCount > 0)
{
GX2ReserveCmdSpace(dwordCount);
gx2WriteGather_submitU32AsLEArray(displayListDWords, dwordCount);
}
}
enum class GX2_PATCH_TYPE : uint32
{
FETCH_SHADER = 1,
VERTEX_SHADER = 2,
GEOMETRY_COPY_SHADER = 3,
GEOMETRY_SHADER = 4,
PIXEL_SHADER = 5,
COMPUTE_SHADER = 6
};
void GX2PatchDisplayList(uint32be* displayData, GX2_PATCH_TYPE patchType, uint32 patchOffset, void* obj)
{
cemu_assert_debug((patchOffset & 3) == 0);
if (patchType == GX2_PATCH_TYPE::VERTEX_SHADER)
{
GX2VertexShader* vertexShader = (GX2VertexShader*)obj;
displayData[patchOffset / 4 + 2] = memory_virtualToPhysical(vertexShader->GetProgramAddr()) >> 8;
}
else if (patchType == GX2_PATCH_TYPE::PIXEL_SHADER)
{
GX2PixelShader_t* pixelShader = (GX2PixelShader_t*)obj;
displayData[patchOffset / 4 + 2] = memory_virtualToPhysical(pixelShader->GetProgramAddr()) >> 8;
}
else if (patchType == GX2_PATCH_TYPE::FETCH_SHADER)
{
GX2FetchShader* fetchShader = (GX2FetchShader*)obj;
displayData[patchOffset / 4 + 2] = memory_virtualToPhysical(fetchShader->GetProgramAddr()) >> 8;
}
else if (patchType == GX2_PATCH_TYPE::GEOMETRY_COPY_SHADER)
{
GX2GeometryShader_t* geometryShader = (GX2GeometryShader_t*)obj;
displayData[patchOffset / 4 + 2] = memory_virtualToPhysical(geometryShader->GetCopyProgramAddr()) >> 8;
}
else if (patchType == GX2_PATCH_TYPE::GEOMETRY_SHADER)
{
GX2GeometryShader_t* geometryShader = (GX2GeometryShader_t*)obj;
displayData[patchOffset / 4 + 2] = memory_virtualToPhysical(geometryShader->GetGeometryProgramAddr()) >> 8;
}
else
{
cemuLog_log(LogType::Force, "GX2PatchDisplayList(): unsupported patchType {}", (uint32)patchType);
cemu_assert_debug(false);
}
}
void GX2CommandInit()
{
cafeExportRegister("gx2", GX2BeginDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2BeginDisplayListEx, LogType::GX2);
cafeExportRegister("gx2", GX2EndDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2GetCurrentDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2GetDisplayListWriteStatus, LogType::GX2);
cafeExportRegister("gx2", GX2CallDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2DirectCallDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2CopyDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2PatchDisplayList, LogType::GX2);
}
void GX2CommandResetToDefaultState()
{
GX2WriteGather_ResetToDefaultState();
}
}
| 11,259
|
C++
|
.cpp
| 274
| 37.99635
| 155
| 0.781969
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,053
|
GX2_State.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_State.cpp
|
#include "Common/precompiled.h"
#include "GX2_State.h"
#include "GX2_Command.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/OS/common/OSCommon.h"
namespace GX2
{
using namespace Latte;
void GX2InitAlphaTestReg(GX2AlphaTestReg* reg, uint32 alphaTestEnable, GX2_ALPHAFUNC alphaFunc, float alphaRef)
{
Latte::LATTE_SX_ALPHA_TEST_CONTROL tmpRegCtrl;
tmpRegCtrl.set_ALPHA_FUNC(alphaFunc);
tmpRegCtrl.set_ALPHA_TEST_ENABLE(alphaTestEnable != 0);
reg->regAlphaTestControl = tmpRegCtrl;
Latte::LATTE_SX_ALPHA_REF tmpRegRef;
tmpRegRef.set_ALPHA_TEST_REF(alphaRef);
reg->regAlphaTestRef = tmpRegRef;
}
void GX2SetAlphaTestReg(GX2AlphaTestReg* reg)
{
GX2ReserveCmdSpace(3 + 3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::SX_ALPHA_TEST_CONTROL - 0xA000,
reg->regAlphaTestControl,
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::SX_ALPHA_REF - 0xA000,
reg->regAlphaTestRef);
}
void GX2SetAlphaTest(uint32 alphaTestEnable, GX2_ALPHAFUNC alphaFunc, float alphaRef)
{
GX2AlphaTestReg tmpReg;
GX2InitAlphaTestReg(&tmpReg, alphaTestEnable, alphaFunc, alphaRef);
GX2SetAlphaTestReg(&tmpReg);
}
void GX2InitColorControlReg(GX2ColorControlReg* reg, GX2_LOGICOP logicOp, uint32 blendMask, uint32 multiwriteEnable, uint32 colorBufferEnable)
{
Latte::LATTE_CB_COLOR_CONTROL colorControlReg2;
colorControlReg2.set_MULTIWRITE_ENABLE(multiwriteEnable != 0);
if (colorBufferEnable == 0)
colorControlReg2.set_SPECIAL_OP(Latte::LATTE_CB_COLOR_CONTROL::E_SPECIALOP::DISABLE);
else
colorControlReg2.set_SPECIAL_OP(Latte::LATTE_CB_COLOR_CONTROL::E_SPECIALOP::NORMAL);
colorControlReg2.set_BLEND_MASK(blendMask);
colorControlReg2.set_ROP(logicOp);
reg->reg = colorControlReg2;
}
void GX2SetColorControlReg(GX2ColorControlReg* reg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::CB_COLOR_CONTROL - 0xA000,
reg->reg);
}
void GX2SetColorControl(GX2_LOGICOP logicOp, uint32 blendMask, uint32 multiwriteEnable, uint32 colorBufferEnable)
{
GX2ColorControlReg colorControlReg;
GX2InitColorControlReg(&colorControlReg, logicOp, blendMask, multiwriteEnable, colorBufferEnable);
GX2SetColorControlReg(&colorControlReg);
}
void GX2InitPolygonControlReg(GX2PolygonControlReg* reg,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_FRONTFACE frontFace,
uint32 cullFront,
uint32 cullBack,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_POLYGONMODE usePolygonMode,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE polyModeFront,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE polyModeBack,
uint32 polygonOffsetFrontEnable,
uint32 polygonOffsetBackEnable,
uint32 paraOffsetEnable)
{
Latte::LATTE_PA_SU_SC_MODE_CNTL v;
v.set_FRONT_FACE(frontFace);
v.set_CULL_FRONT((cullFront & 1) != 0);
v.set_CULL_BACK((cullBack & 1) != 0);
v.set_POLYGON_MODE(usePolygonMode);
v.set_FRONT_POLY_MODE(polyModeFront);
v.set_BACK_POLY_MODE(polyModeBack);
v.set_OFFSET_PARA_ENABLED((paraOffsetEnable & 1) != 0);
v.set_OFFSET_FRONT_ENABLED((polygonOffsetFrontEnable & 1) != 0);
v.set_OFFSET_BACK_ENABLED((polygonOffsetBackEnable & 1) != 0);
reg->reg = v;
}
void GX2SetPolygonControlReg(GX2PolygonControlReg* reg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_SU_SC_MODE_CNTL - 0xA000,
reg->reg);
}
void GX2SetPolygonControl(Latte::LATTE_PA_SU_SC_MODE_CNTL::E_FRONTFACE frontFace,
uint32 cullFront,
uint32 cullBack,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_POLYGONMODE usePolygonMode,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE polyModeFront,
Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE polyModeBack,
uint32 polygonOffsetFrontEnable,
uint32 polygonOffsetBackEnable,
uint32 paraOffsetEnable)
{
GX2PolygonControlReg reg{};
GX2InitPolygonControlReg(®, frontFace, cullFront, cullBack, usePolygonMode, polyModeFront, polyModeBack, polygonOffsetFrontEnable, polygonOffsetBackEnable, paraOffsetEnable);
GX2SetPolygonControlReg(®);
}
void GX2SetCullOnlyControl(Latte::LATTE_PA_SU_SC_MODE_CNTL::E_FRONTFACE frontFace, uint32 cullFront, uint32 cullBack)
{
GX2PolygonControlReg reg{};
GX2InitPolygonControlReg(®, frontFace, cullFront, cullBack, Latte::LATTE_PA_SU_SC_MODE_CNTL::E_POLYGONMODE::UKN0, Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE::POINTS, Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE::POINTS, 0, 0, 0);
GX2SetPolygonControlReg(®);
}
void GX2InitPolygonOffsetReg(GX2PolygonOffsetReg* reg, float frontOffset, float frontScale, float backOffset, float backScale, float clampOffset)
{
frontScale *= 16.0;
backScale *= 16.0;
reg->regFrontScale = Latte::LATTE_PA_SU_POLY_OFFSET_FRONT_SCALE().set_SCALE(frontScale);
reg->regFrontOffset = Latte::LATTE_PA_SU_POLY_OFFSET_FRONT_OFFSET().set_OFFSET(frontOffset);
reg->regBackScale = Latte::LATTE_PA_SU_POLY_OFFSET_BACK_SCALE().set_SCALE(backScale);
reg->regBackOffset = Latte::LATTE_PA_SU_POLY_OFFSET_BACK_OFFSET().set_OFFSET(backOffset);
reg->regClamp = Latte::LATTE_PA_SU_POLY_OFFSET_CLAMP().set_CLAMP(clampOffset);
}
void GX2SetPolygonOffsetReg(GX2PolygonOffsetReg* reg)
{
GX2ReserveCmdSpace(6 + 3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 4),
Latte::REGADDR::PA_SU_POLY_OFFSET_FRONT_SCALE - 0xA000,
reg->regFrontScale,
reg->regFrontOffset,
reg->regBackScale,
reg->regBackOffset,
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_SU_POLY_OFFSET_CLAMP - 0xA000,
reg->regClamp);
}
void GX2SetPolygonOffset(float frontOffset, float frontScale, float backOffset, float backScale, float clampOffset)
{
GX2PolygonOffsetReg tmpReg;
GX2InitPolygonOffsetReg(&tmpReg, frontOffset, frontScale, backOffset, backScale, clampOffset);
GX2SetPolygonOffsetReg(&tmpReg);
}
void GX2SetRasterizerClipControlEx(bool enableRasterizer, bool enableZClip, bool enableHalfZ)
{
GX2ReserveCmdSpace(3);
//if (enableHalfZ)
//{
// // Smash has a bug where it enables half space clipping during streamout drawcalls and shadowing and then doesn't turn it off until the next GX2SetRasterizerClipControl call
// // this leads to some stuff being rendered at the wrong z-plane (e.g. shields behind characters) if the game's default depth range -1 to 1 isn't supported (on OpenGL only Nvidia's glDepthRangedNV allows unclamped values)
// uint64 titleId = gameMeta_getTitleId();
// if (titleId == 0x0005000010144F00ULL ||
// titleId == 0x0005000010145000ULL ||
// titleId == 0x0005000010110E00ULL)
// {
// // force disable half space clipping
// if (g_renderer && g_renderer->GetType() == RendererAPI::OpenGL && LatteGPUState.glVendor != GLVENDOR_NVIDIA)
// enableHalfZ = false;
// }
//}
Latte::LATTE_PA_CL_CLIP_CNTL reg{};
reg.set_ZCLIP_NEAR_DISABLE(!enableZClip).set_ZCLIP_FAR_DISABLE(!enableZClip);
reg.set_DX_RASTERIZATION_KILL(!enableRasterizer);
reg.set_DX_CLIP_SPACE_DEF(enableHalfZ);
reg.set_DX_LINEAR_ATTR_CLIP_ENA(true);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_CL_CLIP_CNTL - 0xA000,
reg);
}
void GX2SetRasterizerClipControl(bool enableRasterizer, bool enableZClip)
{
GX2SetRasterizerClipControlEx(enableRasterizer, enableZClip, false);
}
void GX2SetRasterizerClipControlHalfZ(bool enableRasterizer, bool enableZClip, bool enableHalfZ)
{
GX2SetRasterizerClipControlEx(enableRasterizer, enableZClip, enableHalfZ);
}
void GX2InitViewportReg(GX2ViewportReg* viewportReg, float x, float y, float width, float height, float nearZ, float farZ)
{
// todo: set clipping registers and zMin/zMax registers
viewportReg->xScale = Latte::LATTE_PA_CL_VPORT_XSCALE().set_SCALE(width * 0.5f);
viewportReg->xOffset = Latte::LATTE_PA_CL_VPORT_XOFFSET().set_OFFSET(x + (width * 0.5f));
viewportReg->yScale = Latte::LATTE_PA_CL_VPORT_YSCALE().set_SCALE(height * -0.5f);
viewportReg->yOffset = Latte::LATTE_PA_CL_VPORT_YOFFSET().set_OFFSET(y + (height * 0.5f));
viewportReg->zScale = Latte::LATTE_PA_CL_VPORT_ZSCALE().set_SCALE((farZ - nearZ) * 0.5f);
viewportReg->zOffset = Latte::LATTE_PA_CL_VPORT_ZOFFSET().set_OFFSET((nearZ + farZ) * 0.5f);
}
void GX2SetViewportReg(GX2ViewportReg* viewportReg)
{
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
GX2ReserveCmdSpace(2 + 6);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 6),
Latte::REGADDR::PA_CL_VPORT_XSCALE - 0xA000,
viewportReg->xScale, viewportReg->xOffset,
viewportReg->yScale, viewportReg->yOffset,
viewportReg->zScale, viewportReg->zOffset);
}
void GX2SetViewport(float x, float y, float width, float height, float nearZ, float farZ)
{
GX2ViewportReg viewportReg;
GX2InitViewportReg(&viewportReg, x, y, width, height, nearZ, farZ);
GX2SetViewportReg(&viewportReg);
}
void GX2InitScissorReg(GX2ScissorReg* scissorReg, uint32 x, uint32 y, uint32 width, uint32 height)
{
uint32 tlx = x;
uint32 tly = y;
uint32 brx = x + width;
uint32 bry = y + height;
tlx = std::min(tlx, 8192u);
tly = std::min(tly, 8192u);
brx = std::min(brx, 8192u);
bry = std::min(bry, 8192u);
scissorReg->scissorTL = Latte::LATTE_PA_SC_GENERIC_SCISSOR_TL().set_TL_X(tlx).set_TL_Y(tly).set_WINDOW_OFFSET_DISABLE(true);
scissorReg->scissorBR = Latte::LATTE_PA_SC_GENERIC_SCISSOR_BR().set_BR_X(brx).set_BR_Y(bry);
}
void GX2SetScissorReg(GX2ScissorReg* scissorReg)
{
GX2ReserveCmdSpace(4);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 2),
Latte::REGADDR::PA_SC_GENERIC_SCISSOR_TL - 0xA000,
scissorReg->scissorTL, scissorReg->scissorBR);
}
void GX2GetScissorReg(GX2ScissorReg* scissorReg, uint32be* x, uint32be* y, uint32be* width, uint32be* height)
{
*x = scissorReg->scissorTL.value().get_TL_X();
*y = scissorReg->scissorTL.value().get_TL_Y();
*width = scissorReg->scissorBR.value().get_BR_X() - scissorReg->scissorTL.value().get_TL_X();
*height = scissorReg->scissorBR.value().get_BR_Y() - scissorReg->scissorTL.value().get_TL_Y();
}
void GX2SetScissor(uint32 x, uint32 y, uint32 width, uint32 height)
{
GX2ScissorReg scissorReg;
GX2InitScissorReg(&scissorReg, x, y, width, height);
GX2SetScissorReg(&scissorReg);
}
void GX2SetDepthOnlyControl(bool depthTestEnable, bool depthWriteEnable, LATTE_DB_DEPTH_CONTROL::E_ZFUNC depthFunction)
{
// disables any currently set stencil test
GX2ReserveCmdSpace(3);
Latte::LATTE_DB_DEPTH_CONTROL reg{};
reg.set_Z_ENABLE(depthTestEnable);
reg.set_Z_WRITE_ENABLE(depthWriteEnable);
reg.set_Z_FUNC(depthFunction);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_DEPTH_CONTROL - 0xA000,
reg);
}
void GX2SetDepthStencilControl(
bool depthTestEnable, bool depthWriteEnable, LATTE_DB_DEPTH_CONTROL::E_ZFUNC depthFunction,
bool stencilTestEnable, bool backStencilTestEnable,
LATTE_DB_DEPTH_CONTROL::E_STENCILFUNC frontStencilFunction,
LATTE_DB_DEPTH_CONTROL::E_STENCILACTION frontStencilZPass, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION frontStencilZFail, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION frontStencilFail,
LATTE_DB_DEPTH_CONTROL::E_STENCILFUNC backStencilFunction,
LATTE_DB_DEPTH_CONTROL::E_STENCILACTION backStencilZPass, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION backStencilZFail, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION backStencilFail
)
{
GX2ReserveCmdSpace(3);
Latte::LATTE_DB_DEPTH_CONTROL reg{};
reg.set_Z_ENABLE(depthTestEnable).set_Z_WRITE_ENABLE(depthWriteEnable).set_Z_FUNC(depthFunction);
reg.set_STENCIL_ENABLE(stencilTestEnable).set_BACK_STENCIL_ENABLE(backStencilTestEnable);
reg.set_STENCIL_FUNC_F(frontStencilFunction).set_STENCIL_FUNC_B(backStencilFunction);
reg.set_STENCIL_ZPASS_F(frontStencilZPass).set_STENCIL_ZFAIL_F(frontStencilZFail).set_STENCIL_FAIL_F(frontStencilFail);
reg.set_STENCIL_ZPASS_B(backStencilZPass).set_STENCIL_ZFAIL_B(backStencilZFail).set_STENCIL_FAIL_B(backStencilFail);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_DEPTH_CONTROL - 0xA000,
reg);
}
void GX2InitDepthStencilControlReg(
GX2DepthStencilControlReg* depthStencilControlReg,
bool depthTestEnable, bool depthWriteEnable, LATTE_DB_DEPTH_CONTROL::E_ZFUNC depthFunction,
bool stencilTestEnable, bool backStencilTestEnable,
LATTE_DB_DEPTH_CONTROL::E_STENCILFUNC frontStencilFunction,
LATTE_DB_DEPTH_CONTROL::E_STENCILACTION frontStencilZPass, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION frontStencilZFail, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION frontStencilFail,
LATTE_DB_DEPTH_CONTROL::E_STENCILFUNC backStencilFunction,
LATTE_DB_DEPTH_CONTROL::E_STENCILACTION backStencilZPass, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION backStencilZFail, LATTE_DB_DEPTH_CONTROL::E_STENCILACTION backStencilFail)
{
Latte::LATTE_DB_DEPTH_CONTROL reg{};
reg.set_Z_ENABLE(depthTestEnable).set_Z_WRITE_ENABLE(depthWriteEnable).set_Z_FUNC(depthFunction);
reg.set_STENCIL_ENABLE(stencilTestEnable).set_BACK_STENCIL_ENABLE(backStencilTestEnable);
reg.set_STENCIL_FUNC_F(frontStencilFunction).set_STENCIL_FUNC_B(backStencilFunction);
reg.set_STENCIL_ZPASS_F(frontStencilZPass).set_STENCIL_ZFAIL_F(frontStencilZFail).set_STENCIL_FAIL_F(frontStencilFail);
reg.set_STENCIL_ZPASS_B(backStencilZPass).set_STENCIL_ZFAIL_B(backStencilZFail).set_STENCIL_FAIL_B(backStencilFail);
depthStencilControlReg->reg = reg;
}
void GX2SetDepthStencilControlReg(GX2DepthStencilControlReg* depthStencilControlReg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::DB_DEPTH_CONTROL - 0xA000,
depthStencilControlReg->reg);
}
void GX2GetDepthStencilControlReg(
GX2DepthStencilControlReg* depthStencilControlReg,
uint32be* depthTestEnable, uint32be* depthWriteEnable, uint32be* depthFunction,
uint32be* stencilTestEnable, uint32be* backStencilTestEnable,
uint32be* frontStencilFunction,
uint32be* frontStencilZPass, uint32be* frontStencilZFail, uint32be* frontStencilFail,
uint32be* backStencilFunction,
uint32be* backStencilZPass, uint32be* backStencilZFail, uint32be* backStencilFail)
{
// used by Hyrule Warriors
*depthTestEnable = depthStencilControlReg->reg.value().get_Z_ENABLE();
*depthWriteEnable = depthStencilControlReg->reg.value().get_Z_WRITE_ENABLE();
*depthFunction = (uint32)depthStencilControlReg->reg.value().get_Z_FUNC();
*stencilTestEnable = depthStencilControlReg->reg.value().get_STENCIL_ENABLE();
*backStencilTestEnable = depthStencilControlReg->reg.value().get_BACK_STENCIL_ENABLE();
*frontStencilFunction = (uint32)depthStencilControlReg->reg.value().get_STENCIL_FUNC_F();
*backStencilFunction = (uint32)depthStencilControlReg->reg.value().get_STENCIL_FUNC_B();
*frontStencilZPass = (uint32)depthStencilControlReg->reg.value().get_STENCIL_ZPASS_F();
*frontStencilZFail = (uint32)depthStencilControlReg->reg.value().get_STENCIL_ZFAIL_F();
*frontStencilFail = (uint32)depthStencilControlReg->reg.value().get_STENCIL_FAIL_F();
*backStencilZPass = (uint32)depthStencilControlReg->reg.value().get_STENCIL_ZPASS_B();
*backStencilZFail = (uint32)depthStencilControlReg->reg.value().get_STENCIL_ZFAIL_B();
*backStencilFail = (uint32)depthStencilControlReg->reg.value().get_STENCIL_FAIL_B();
}
void GX2InitStencilMaskReg(GX2StencilMaskReg* stencilMaskReg, uint8 compareMaskFront, uint8 writeMaskFront, uint8 refFront, uint8 compareMaskBack, uint8 writeMaskBack, uint8 refBack)
{
stencilMaskReg->stencilRefMaskFrontReg = LATTE_DB_STENCILREFMASK().set_STENCILREF_F(refFront).set_STENCILMASK_F(compareMaskFront).set_STENCILWRITEMASK_F(writeMaskFront);
stencilMaskReg->stencilRefMaskBackReg = LATTE_DB_STENCILREFMASK_BF().set_STENCILREF_B(refBack).set_STENCILMASK_B(compareMaskBack).set_STENCILWRITEMASK_B(writeMaskBack);
}
void GX2SetStencilMask(uint8 compareMaskFront, uint8 writeMaskFront, uint8 refFront, uint8 compareMaskBack, uint8 writeMaskBack, uint8 refBack)
{
GX2ReserveCmdSpace(3 + 3);
LATTE_DB_STENCILREFMASK frontReg;
frontReg.set_STENCILREF_F(refFront).set_STENCILMASK_F(compareMaskFront).set_STENCILWRITEMASK_F(writeMaskFront);
LATTE_DB_STENCILREFMASK_BF backReg;
backReg.set_STENCILREF_B(refBack).set_STENCILMASK_B(compareMaskBack).set_STENCILWRITEMASK_B(writeMaskBack);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
REGADDR::DB_STENCILREFMASK - 0xA000,
frontReg,
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
REGADDR::DB_STENCILREFMASK_BF - 0xA000,
backReg);
}
void GX2SetStencilMaskReg(GX2StencilMaskReg* stencilMaskReg)
{
GX2ReserveCmdSpace(3 + 3);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
REGADDR::DB_STENCILREFMASK - 0xA000,
stencilMaskReg->stencilRefMaskFrontReg,
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
REGADDR::DB_STENCILREFMASK_BF - 0xA000,
stencilMaskReg->stencilRefMaskBackReg);
}
void GX2SetPrimitiveRestartIndex(uint32 restartIndex)
{
GX2ReserveCmdSpace(3);
Latte::LATTE_VGT_MULTI_PRIM_IB_RESET_INDX reg{};
reg.set_RESTART_INDEX(restartIndex);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::VGT_MULTI_PRIM_IB_RESET_INDX - 0xA000,
reg);
}
void GX2InitTargetChannelMasksReg(GX2TargetChannelMaskReg* reg, GX2_CHANNELMASK t0, GX2_CHANNELMASK t1, GX2_CHANNELMASK t2, GX2_CHANNELMASK t3, GX2_CHANNELMASK t4, GX2_CHANNELMASK t5, GX2_CHANNELMASK t6, GX2_CHANNELMASK t7)
{
uint32 targetMask = 0;
targetMask |= ((t0 & 0xF) << 0);
targetMask |= ((t1 & 0xF) << 4);
targetMask |= ((t2 & 0xF) << 8);
targetMask |= ((t3 & 0xF) << 12);
targetMask |= ((t4 & 0xF) << 16);
targetMask |= ((t5 & 0xF) << 20);
targetMask |= ((t6 & 0xF) << 24);
targetMask |= ((t7 & 0xF) << 28);
Latte::LATTE_CB_TARGET_MASK r;
r.set_MASK(targetMask);
reg->reg = r;
}
void GX2SetTargetChannelMasksReg(GX2TargetChannelMaskReg* reg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::CB_TARGET_MASK - 0xA000,
reg->reg);
}
void GX2SetTargetChannelMasks(GX2_CHANNELMASK t0, GX2_CHANNELMASK t1, GX2_CHANNELMASK t2, GX2_CHANNELMASK t3, GX2_CHANNELMASK t4, GX2_CHANNELMASK t5, GX2_CHANNELMASK t6, GX2_CHANNELMASK t7)
{
GX2TargetChannelMaskReg tmpReg;
GX2InitTargetChannelMasksReg(&tmpReg, t0, t1, t2, t3, t4, t5, t6, t7);
GX2SetTargetChannelMasksReg(&tmpReg);
}
static_assert(sizeof(GX2_CHANNELMASK) == 4);
void GX2GetTargetChannelMasksReg(GX2TargetChannelMaskReg* reg, betype<GX2_CHANNELMASK>* t0, betype<GX2_CHANNELMASK>* t1, betype<GX2_CHANNELMASK>* t2, betype<GX2_CHANNELMASK>* t3,
betype<GX2_CHANNELMASK>* t4, betype<GX2_CHANNELMASK>* t5, betype<GX2_CHANNELMASK>* t6, betype<GX2_CHANNELMASK>* t7)
{
uint32 maskValue = reg->reg.value().get_MASK();
*t0 = (maskValue >> 0) & 0xF;
*t1 = (maskValue >> 4) & 0xF;
*t2 = (maskValue >> 8) & 0xF;
*t3 = (maskValue >> 12) & 0xF;
*t4 = (maskValue >> 16) & 0xF;
*t5 = (maskValue >> 20) & 0xF;
*t6 = (maskValue >> 24) & 0xF;
*t7 = (maskValue >> 28) & 0xF;
}
void GX2InitBlendControlReg(GX2BlendControlReg* reg, uint32 renderTargetIndex, GX2_BLENDFACTOR colorSrcFactor, GX2_BLENDFACTOR colorDstFactor, GX2_BLENDFUNC colorCombineFunc, uint32 separateAlphaBlend, GX2_BLENDFACTOR alphaSrcFactor, GX2_BLENDFACTOR alphaDstFactor, GX2_BLENDFUNC alphaCombineFunc)
{
Latte::LATTE_CB_BLENDN_CONTROL tmpReg;
tmpReg.set_COLOR_SRCBLEND(colorSrcFactor);
tmpReg.set_COLOR_DSTBLEND(colorDstFactor);
tmpReg.set_COLOR_COMB_FCN(colorCombineFunc);
tmpReg.set_ALPHA_SRCBLEND(alphaSrcFactor);
tmpReg.set_ALPHA_DSTBLEND(alphaDstFactor);
tmpReg.set_ALPHA_COMB_FCN(alphaCombineFunc);
tmpReg.set_SEPARATE_ALPHA_BLEND(separateAlphaBlend != 0);
reg->index = renderTargetIndex;
reg->reg = tmpReg;
}
void GX2SetBlendControlReg(GX2BlendControlReg* reg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
(Latte::REGADDR::CB_BLEND0_CONTROL + (uint32)reg->index) - 0xA000,
reg->reg
);
}
void GX2SetBlendControl(uint32 renderTargetIndex, GX2_BLENDFACTOR colorSrcFactor, GX2_BLENDFACTOR colorDstFactor, GX2_BLENDFUNC colorCombineFunc, uint32 separateAlphaBlend, GX2_BLENDFACTOR alphaSrcFactor, GX2_BLENDFACTOR alphaDstFactor, GX2_BLENDFUNC alphaCombineFunc)
{
GX2BlendControlReg tmpReg;
GX2InitBlendControlReg(&tmpReg, renderTargetIndex, colorSrcFactor, colorDstFactor, colorCombineFunc, separateAlphaBlend, alphaSrcFactor, alphaDstFactor, alphaCombineFunc);
GX2SetBlendControlReg(&tmpReg);
}
void GX2InitBlendConstantColorReg(GX2BlendConstantColorReg* reg, float red, float green, float blue, float alpha)
{
reg->regRed = Latte::LATTE_CB_BLEND_RED().set_RED(red);
reg->regGreen = Latte::LATTE_CB_BLEND_GREEN().set_GREEN(green);
reg->regBlue = Latte::LATTE_CB_BLEND_BLUE().set_BLUE(blue);
reg->regAlpha = Latte::LATTE_CB_BLEND_ALPHA().set_ALPHA(alpha);
}
void GX2SetBlendConstantColorReg(GX2BlendConstantColorReg* reg)
{
GX2ReserveCmdSpace(6);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 4),
Latte::REGADDR::CB_BLEND_RED - 0xA000,
reg->regRed,
reg->regGreen,
reg->regBlue,
reg->regAlpha
);
}
void GX2SetBlendConstantColor(float red, float green, float blue, float alpha)
{
GX2BlendConstantColorReg tmpReg;
GX2InitBlendConstantColorReg(&tmpReg, red, green, blue, alpha);
GX2SetBlendConstantColorReg(&tmpReg);
}
void GX2InitHiStencilInfoRegs(GX2HiStencilInfoReg* hiStencilInfo)
{
// seen in Color Splash
// but the game never calls GX2SetHiStencilInfo thus this has no effect
}
void GX2InitPointSizeReg(GX2PointSizeReg* reg, float width, float height)
{
if (width < 0.0f || height < 0.0f)
{
cemu_assert_suspicious();
}
uint32 widthI = (uint32)(width * 8.0f);
uint32 heightI = (uint32)(height * 8.0f);
widthI = std::min<uint32>(widthI, 0xFFFF);
heightI = std::min<uint32>(heightI, 0xFFFF);
reg->reg = Latte::LATTE_PA_SU_POINT_SIZE().set_WIDTH(widthI).set_HEIGHT(heightI);
}
void GX2SetPointSizeReg(GX2PointSizeReg* reg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_SU_POINT_SIZE - 0xA000,
reg->reg
);
}
void GX2SetPointSize(float width, float height)
{
GX2PointSizeReg tmpReg;
GX2InitPointSizeReg(&tmpReg, width, height);
GX2SetPointSizeReg(&tmpReg);
}
void GX2InitPointLimitsReg(GX2PointLimitsReg* reg, float minSize, float maxSize)
{
if (minSize < 0.0f || maxSize < 0.0f)
{
cemu_assert_suspicious();
}
uint32 minSizeI = (uint32)(minSize * 8.0f);
uint32 maxSizeI = (uint32)(maxSize * 8.0f);
minSizeI = std::min<uint32>(minSizeI, 0xFFFF);
maxSizeI = std::min<uint32>(maxSizeI, 0xFFFF);
reg->reg = Latte::LATTE_PA_SU_POINT_MINMAX().set_MIN_SIZE(minSizeI).set_MAX_SIZE(maxSizeI);
}
void GX2SetPointLimitsReg(GX2PointLimitsReg* reg)
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_SU_POINT_MINMAX - 0xA000,
reg->reg
);
}
void GX2SetPointLimits(float minSize, float maxSize)
{
GX2PointLimitsReg tmpReg;
GX2InitPointLimitsReg(&tmpReg, minSize, maxSize);
GX2SetPointLimitsReg(&tmpReg);
}
enum class GX2_SPECIAL_STATE : uint32
{
FAST_CLEAR = 0,
FAST_CLEAR_HIZ = 1,
};
void _setSpecialState0(bool isEnabled)
{
GX2ReserveCmdSpace(6);
if (isEnabled)
{
// set PA_CL_VTE_CNTL to 0x300
Latte::LATTE_PA_CL_VTE_CNTL regVTE{};
regVTE.set_VTX_XY_FMT(true);
regVTE.set_VTX_Z_FMT(true);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_CL_VTE_CNTL - 0xA000,
regVTE);
// set PA_CL_CLIP_CNTL to 0x490000
Latte::LATTE_PA_CL_CLIP_CNTL regClip{};
regClip.set_CLIP_DISABLE(true); // 0x10000
regClip.set_DX_CLIP_SPACE_DEF(true); // 0x80000
regClip.set_DX_RASTERIZATION_KILL(true); // 0x400000
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_CL_CLIP_CNTL - 0xA000,
regClip);
}
else
{
// set PA_CL_VTE_CNTL to 0x43F
Latte::LATTE_PA_CL_VTE_CNTL reg{};
reg.set_VPORT_X_OFFSET_ENA(true).set_VPORT_X_SCALE_ENA(true);
reg.set_VPORT_Y_OFFSET_ENA(true).set_VPORT_Y_SCALE_ENA(true);
reg.set_VPORT_Z_OFFSET_ENA(true).set_VPORT_Z_SCALE_ENA(true);
reg.set_VTX_W0_FMT(true);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_CL_VTE_CNTL - 0xA000,
reg);
// reset PA_CL_CLIP_CNTL
GX2SetRasterizerClipControl(true, true);
}
}
void GX2SetSpecialState(GX2_SPECIAL_STATE stateId, uint32 isEnabled)
{
if (stateId == GX2_SPECIAL_STATE::FAST_CLEAR)
{
_setSpecialState0(isEnabled != 0);
}
else if (stateId == GX2_SPECIAL_STATE::FAST_CLEAR_HIZ)
{
// todo
// enables additional flags for special state 0
}
else
{
// legacy style
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_SPECIAL_STATE, 2));
gx2WriteGather_submitU32AsBE((uint32)stateId); // state id
gx2WriteGather_submitU32AsBE(isEnabled); // enable/disable bool
}
}
void GX2StateInit()
{
cafeExportRegister("gx2", GX2InitAlphaTestReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetAlphaTestReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetAlphaTest, LogType::GX2);
cafeExportRegister("gx2", GX2InitColorControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetColorControl, LogType::GX2);
cafeExportRegister("gx2", GX2SetColorControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2InitPolygonControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPolygonControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPolygonControl, LogType::GX2);
cafeExportRegister("gx2", GX2SetCullOnlyControl, LogType::GX2);
cafeExportRegister("gx2", GX2InitPolygonOffsetReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPolygonOffsetReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPolygonOffset, LogType::GX2);
cafeExportRegister("gx2", GX2SetRasterizerClipControl, LogType::GX2);
cafeExportRegister("gx2", GX2SetRasterizerClipControlHalfZ, LogType::GX2);
cafeExportRegister("gx2", GX2SetRasterizerClipControlEx, LogType::GX2);
cafeExportRegister("gx2", GX2InitViewportReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetViewportReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetViewport, LogType::GX2);
cafeExportRegister("gx2", GX2InitScissorReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetScissorReg, LogType::GX2);
cafeExportRegister("gx2", GX2GetScissorReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetScissor, LogType::GX2);
cafeExportRegister("gx2", GX2InitDepthStencilControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetDepthStencilControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2GetDepthStencilControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetDepthOnlyControl, LogType::GX2);
cafeExportRegister("gx2", GX2SetDepthStencilControl, LogType::GX2);
cafeExportRegister("gx2", GX2InitStencilMaskReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetStencilMask, LogType::GX2);
cafeExportRegister("gx2", GX2SetStencilMaskReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPrimitiveRestartIndex, LogType::GX2);
cafeExportRegister("gx2", GX2InitTargetChannelMasksReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetTargetChannelMasksReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetTargetChannelMasks, LogType::GX2);
cafeExportRegister("gx2", GX2GetTargetChannelMasksReg, LogType::GX2);
cafeExportRegister("gx2", GX2InitBlendControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetBlendControlReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetBlendControl, LogType::GX2);
cafeExportRegister("gx2", GX2InitBlendConstantColorReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetBlendConstantColorReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetBlendConstantColor, LogType::GX2);
cafeExportRegister("gx2", GX2InitHiStencilInfoRegs, LogType::GX2);
cafeExportRegister("gx2", GX2InitPointSizeReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPointSizeReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPointSize, LogType::GX2);
cafeExportRegister("gx2", GX2InitPointLimitsReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPointLimitsReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPointLimits, LogType::GX2);
cafeExportRegister("gx2", GX2SetSpecialState, LogType::GX2);
}
}
| 28,610
|
C++
|
.cpp
| 622
| 42.892283
| 298
| 0.769082
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,054
|
GX2_TilingAperture.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_TilingAperture.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "GX2.h"
#include "Cafe/HW/Latte/LatteAddrLib/LatteAddrLib.h"
#include "Cafe/HW/Latte/Core/LatteTextureLoader.h"
#define GX2_MAX_ACTIVE_TILING_APERATURES (32)
struct ActiveTilingAperature
{
uint32 addr;
uint32 size;
uint32 handle;
uint32 endianMode;
// surface info
GX2Surface surface;
uint32 sliceIndex;
uint32 mipLevel;
};
ActiveTilingAperature activeTilingAperature[GX2_MAX_ACTIVE_TILING_APERATURES];
sint32 activeTilingAperatureCount = 0;
MPTR GX2TilingAperature_allocateTilingMemory(uint32 size)
{
uint32 currentOffset = 0;
while( true )
{
// align offset
currentOffset = (currentOffset+0xFFF)&~0xFFF;
// check if out of range
if( (currentOffset+size) >= MEMORY_TILINGAPERTURE_AREA_SIZE )
break;
// check if range intersects with any already allocated range
bool isAvailable = true;
uint32 nextOffset = 0xFFFFFFFF;
for(sint32 i=0; i<activeTilingAperatureCount; i++)
{
uint32 startA = currentOffset;
uint32 endA = startA+size;
uint32 startB = activeTilingAperature[i].addr - MEMORY_TILINGAPERTURE_AREA_ADDR;
uint32 endB = startB+activeTilingAperature[i].size;
if( startA < endB && endA >= startB )
{
isAvailable = false;
nextOffset = std::min(nextOffset, endB);
}
}
if( isAvailable )
return currentOffset + MEMORY_TILINGAPERTURE_AREA_ADDR;
currentOffset = nextOffset;
}
return MPTR_NULL;
}
std::atomic<uint32> sGenAperatureHandle{1};
uint32 GX2TilingAperature_GenerateHandle()
{
return sGenAperatureHandle.fetch_add(1);
}
template<typename copyType, int count, bool isWrite>
void copyValue(uint8* outputBlockData, uint8* inputBlockData)
{
if (isWrite)
{
*(copyType*)outputBlockData = *(copyType*)inputBlockData;
if (count >= 2)
((copyType*)outputBlockData)[1] = ((copyType*)inputBlockData)[1];
if (count >= 3)
((copyType*)outputBlockData)[2] = ((copyType*)inputBlockData)[2];
if (count >= 4)
((copyType*)outputBlockData)[3] = ((copyType*)inputBlockData)[3];
}
else
{
*(copyType*)inputBlockData = *(copyType*)outputBlockData;
if (count >= 2)
((copyType*)inputBlockData)[1] = ((copyType*)outputBlockData)[1];
if (count >= 3)
((copyType*)inputBlockData)[2] = ((copyType*)outputBlockData)[2];
if (count >= 4)
((copyType*)inputBlockData)[3] = ((copyType*)outputBlockData)[3];
}
}
template<int bpp, bool isWrite, int surfaceTileMode>
void retileTexture(ActiveTilingAperature* tilingAperture, uint8* inputData, uint8* outputData, sint32 texelWidth, sint32 texelHeight, sint32 surfaceSlice, sint32 surfacePitch, sint32 surfaceHeight, sint32 surfaceDepth, LatteAddrLib::CachedSurfaceAddrInfo* cachedInfo)
{
for (sint32 y = 0; y < texelHeight; y++)
{
uint32 srcOffset;
uint8* inputBlockData;
if (bpp != 8)
{
srcOffset = (0 + y*surfacePitch)*(bpp / 8);
inputBlockData = inputData + srcOffset;
}
for (sint32 x = 0; x < texelWidth; x++)
{
// calculate address of input block
sint32 texelX = x;
sint32 texelY = y;
if (bpp == 8)
{
texelX ^= 8;
texelY ^= 2;
srcOffset = (texelX + texelY*surfacePitch)*(bpp / 8);
inputBlockData = inputData + srcOffset;
}
// calculate address of output block
uint32 dstBitPos = 0;
uint32 dstOffset = 0;
if (surfaceTileMode == 4)
dstOffset = ComputeSurfaceAddrFromCoordMacroTiledCached_tm04_sample1(x, y, cachedInfo);
else if (surfaceTileMode == 2 || surfaceTileMode == 3)
{
dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMicroTiled(x, y, cachedInfo->slice, cachedInfo->bpp, cachedInfo->pitch, cachedInfo->height, (Latte::E_HWTILEMODE)cachedInfo->tileMode, false);
}
else if (surfaceTileMode == 1 || surfaceTileMode == 0)
{
dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordLinear(x, y, cachedInfo->slice, 0, cachedInfo->bpp, cachedInfo->pitch, cachedInfo->height, cachedInfo->depth);
}
else
dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMacroTiledCached(x, y, cachedInfo);
uint8* outputBlockData = outputData + dstOffset;
if (bpp == 32)
copyValue<uint32, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 16)
copyValue<uint16, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 8)
copyValue<uint8, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 64)
copyValue<uint64, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 128)
copyValue<uint64, 2, isWrite>(outputBlockData, inputBlockData);
else
{
cemu_assert_unimplemented();
}
if (bpp != 8)
{
inputBlockData += (bpp / 8);
}
}
}
}
template<int bpp, bool isWrite>
void retileTexture_tm04_sample1(ActiveTilingAperature* tilingAperture, uint8* inputData, uint8* outputData, sint32 texelWidth, sint32 texelHeight, sint32 surfaceSlice, sint32 surfacePitch, sint32 surfaceHeight, sint32 surfaceDepth, LatteAddrLib::CachedSurfaceAddrInfo* cachedInfo)
{
uint16* tableBase = cachedInfo->microTilePixelIndexTable + ((cachedInfo->slice & 7) << 6);
for (sint32 y = 0; y < texelHeight; y++)
{
uint32 srcOffset;
uint8* inputBlockData;
if (bpp != 8)
{
srcOffset = (0 + y*surfacePitch)*(bpp / 8);
inputBlockData = inputData + srcOffset;
}
for (sint32 bx = 0; bx < texelWidth; bx += 8)
{
uint16* pixelOffsets = tableBase + ((y&7) << 3);
uint32 baseOffset = ComputeSurfaceAddrFromCoordMacroTiledCached_tm04_sample1(bx, y, cachedInfo);
for (sint32 x = bx; x < bx+8; x++)
{
// calculate address of input block
if (bpp == 8)
{
sint32 texelX = x;
sint32 texelY = y;
texelX ^= 8;
texelY ^= 2;
srcOffset = (texelX + texelY*surfacePitch)*(bpp / 8);
inputBlockData = inputData + srcOffset;
}
// calculate address of output block
uint32 dstBitPos = 0;
uint32 pixelIndex = *pixelOffsets;
pixelOffsets++;
uint32 pixelOffset = pixelIndex * (bpp/8);
uint32 elemOffset = pixelOffset;
if ((bpp * 8) > 256)
{
// separate group bytes, for small formats this step is not necessary since elemOffset is never over 0xFF (maximum is 8*8*bpp)
elemOffset = (elemOffset & 0xFF) | ((elemOffset&~0xFF) << 3);
}
sint32 offset = baseOffset + elemOffset;
uint8* outputBlockData = outputData + offset;
if (bpp == 32)
copyValue<uint32, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 16)
copyValue<uint16, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 8)
copyValue<uint8, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 64)
copyValue<uint64, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 128)
copyValue<uint64, 2, isWrite>(outputBlockData, inputBlockData);
else
{
cemu_assert_unimplemented();
}
if (bpp != 8)
{
inputBlockData += (bpp / 8);
}
}
}
// copy remaining partial block
for (sint32 x = (texelWidth&~7); x < texelWidth; x++)
{
// calculate address of input block
sint32 texelX = x;
sint32 texelY = y;
if (bpp == 8)
{
texelX ^= 8;
texelY ^= 2;
srcOffset = (texelX + texelY*surfacePitch)*(bpp / 8);
inputBlockData = inputData + srcOffset;
}
// calculate address of output block
uint32 dstBitPos = 0;
uint32 dstOffset = 0;
dstOffset = ComputeSurfaceAddrFromCoordMacroTiledCached_tm04_sample1(x, y, cachedInfo);
uint8* outputBlockData = outputData + dstOffset;
if (bpp == 32)
copyValue<uint32, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 16)
copyValue<uint16, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 8)
copyValue<uint8, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 64)
copyValue<uint64, 1, isWrite>(outputBlockData, inputBlockData);
else if (bpp == 128)
copyValue<uint64, 2, isWrite>(outputBlockData, inputBlockData);
else
{
cemu_assert_unimplemented();
}
if (bpp != 8)
{
inputBlockData += (bpp / 8);
}
}
}
}
template<int bpp, bool isWrite>
void retileTextureWrapper(ActiveTilingAperature* tilingAperture, uint8* inputData, uint8* outputData, sint32 texelWidth, sint32 texelHeight, sint32 surfaceSlice, sint32 surfaceTileMode, sint32 surfacePitch, sint32 surfaceHeight, sint32 surfaceDepth, LatteAddrLib::CachedSurfaceAddrInfo* cachedInfo)
{
if (surfaceTileMode == 0)
retileTexture<bpp, isWrite, 0>(tilingAperture, inputData, outputData, texelWidth, texelHeight, surfaceSlice, surfacePitch, surfaceHeight, surfaceDepth, cachedInfo);
else if (surfaceTileMode == 1)
retileTexture<bpp, isWrite, 1>(tilingAperture, inputData, outputData, texelWidth, texelHeight, surfaceSlice, surfacePitch, surfaceHeight, surfaceDepth, cachedInfo);
else if (surfaceTileMode == 2)
retileTexture<bpp, isWrite, 2>(tilingAperture, inputData, outputData, texelWidth, texelHeight, surfaceSlice, surfacePitch, surfaceHeight, surfaceDepth, cachedInfo);
else if (surfaceTileMode == 3)
retileTexture<bpp, isWrite, 3>(tilingAperture, inputData, outputData, texelWidth, texelHeight, surfaceSlice, surfacePitch, surfaceHeight, surfaceDepth, cachedInfo);
else if (surfaceTileMode == 4)
retileTexture<bpp, isWrite, 4>(tilingAperture, inputData, outputData, texelWidth, texelHeight, surfaceSlice, surfacePitch, surfaceHeight, surfaceDepth, cachedInfo);
else if (surfaceTileMode == 7)
retileTexture<bpp, isWrite, 7>(tilingAperture, inputData, outputData, texelWidth, texelHeight, surfaceSlice, surfacePitch, surfaceHeight, surfaceDepth, cachedInfo);
else
{
cemu_assert_unimplemented();
}
}
void LatteTextureLoader_begin(LatteTextureLoaderCtx* textureLoader, uint32 sliceIndex, uint32 mipIndex, MPTR physImagePtr, MPTR physMipPtr, Latte::E_GX2SURFFMT format, Latte::E_DIM dim, uint32 width, uint32 height, uint32 depth, uint32 mipLevels, uint32 pitch, Latte::E_HWTILEMODE tileMode, uint32 swizzle);
void GX2TilingAperature_RetileTexture(ActiveTilingAperature* tilingAperture, bool doWrite)
{
//uint64 timerTilingStart = benchmarkTimer_start();
Latte::E_GX2SURFFMT surfaceFormat = tilingAperture->surface.format;
uint32 surfaceSlice = tilingAperture->sliceIndex;
LatteAddrLib::AddrSurfaceInfo_OUT surfaceInfo = {0};
GX2::GX2CalculateSurfaceInfo(&tilingAperture->surface, tilingAperture->mipLevel, &surfaceInfo);
uint32 surfacePitch = surfaceInfo.pitch;
uint32 surfaceSwizzle = tilingAperture->surface.swizzle;
uint32 surfacePipeSwizzle = (surfaceSwizzle>>8)&1;
uint32 surfaceBankSwizzle = ((surfaceSwizzle>>9)&3);
Latte::E_HWTILEMODE surfaceTileMode = surfaceInfo.hwTileMode;
uint32 surfaceDepth = std::max<uint32>(surfaceInfo.depth, 1);
sint32 width = std::max<uint32>((uint32)tilingAperture->surface.width >> tilingAperture->mipLevel, 1);
sint32 height = std::max<uint32>((uint32)tilingAperture->surface.height >> tilingAperture->mipLevel, 1);
Latte::E_DIM surfaceDim = tilingAperture->surface.dim;
uint32 surfaceMipSwizzle = 0; // todo
uint32 mipLevels = tilingAperture->surface.numLevels;
// get texture info
uint8* inputData = (uint8*)memory_getPointerFromVirtualOffset(tilingAperture->addr);
uint8* outputData;
if( tilingAperture->mipLevel == 0 )
outputData = (uint8*)memory_getPointerFromVirtualOffset(tilingAperture->surface.imagePtr);
else if( tilingAperture->mipLevel == 1 )
outputData = (uint8*)memory_getPointerFromVirtualOffset(tilingAperture->surface.mipPtr);
else
outputData = (uint8*)memory_getPointerFromVirtualOffset(tilingAperture->surface.mipPtr + tilingAperture->surface.mipOffset[tilingAperture->mipLevel-1]);
sint32 stepX = 1;
sint32 stepY = 1;
bool isCompressed = false;
if( Latte::IsCompressedFormat(surfaceFormat) )
{
isCompressed = true;
stepX = 4;
stepY = 4;
}
uint32 bpp = surfaceInfo.bpp;
uint32 bytesPerPixel = bpp/8;
LatteAddrLib::CachedSurfaceAddrInfo computeAddrInfo = { 0 };
SetupCachedSurfaceAddrInfo(&computeAddrInfo, surfaceSlice, 0, bpp, surfacePitch, surfaceInfo.height, surfaceInfo.depth, 1 * 1, surfaceTileMode, false, surfacePipeSwizzle, surfaceBankSwizzle);
// init info for swizzle encoder/decoder
LatteTextureLoaderCtx textureLoaderCtx{};
LatteTextureLoader_begin(&textureLoaderCtx, surfaceSlice, 0, tilingAperture->surface.imagePtr, tilingAperture->surface.mipPtr, surfaceFormat, surfaceDim, width, height, surfaceDepth, mipLevels, surfacePitch, surfaceTileMode, surfaceSwizzle);
textureLoaderCtx.decodedTexelCountX = surfacePitch;
textureLoaderCtx.decodedTexelCountY = isCompressed ? (height + 3) / 4 : height;
if( doWrite )
{
if (surfaceTileMode == Latte::E_HWTILEMODE::TM_2D_TILED_THIN1 && bpp == 32 && isCompressed == false)
{
optimizedDecodeLoops<uint32, 1, true, false>(&textureLoaderCtx, inputData);
}
else if (bpp == 8)
retileTextureWrapper<8, true>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 16)
retileTextureWrapper<16, true>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 32)
retileTextureWrapper<32, true>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 64)
retileTextureWrapper<64, true>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 128)
retileTextureWrapper<128, true>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else
{
cemu_assert_unimplemented();
}
}
else
{
if (surfaceTileMode == Latte::E_HWTILEMODE::TM_2D_TILED_THIN1 && bpp == 32 && isCompressed == false)
{
optimizedDecodeLoops<uint32, 1, false, false>(&textureLoaderCtx, inputData);
}
else if (bpp == 8)
retileTextureWrapper<8, false>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 16)
retileTextureWrapper<16, false>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 32)
retileTextureWrapper<32, false>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 64)
retileTextureWrapper<64, false>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else if (bpp == 128)
retileTextureWrapper<128, false>(tilingAperture, inputData, outputData, width / stepX, height / stepY, surfaceSlice, (uint32)surfaceTileMode, surfacePitch, surfaceInfo.height, surfaceDepth, &computeAddrInfo);
else
{
cemu_assert_unimplemented();
}
}
//double benchmarkTime = benchmarkTimer_stop(timerTilingStart);
//cemuLog_logDebug(LogType::Force, "TilingAperture res {:04}x{:04} fmt {:04x} tm {:02x} mip {} isWrite {}", (uint32)tilingAperture->surface.width, (uint32)tilingAperture->surface.height, (uint32)tilingAperture->surface.format, (uint32)tilingAperture->surface.tileMode, tilingAperture->mipLevel, doWrite?1:0);
//cemuLog_logDebug(LogType::Force, "Tiling took {:.4}ms", benchmarkTime);
}
void gx2Export_GX2AllocateTilingApertureEx(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2AllocateTilingApertureEx(0x{:08x}, {}, {}, {}, 0x{:08x}, 0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7], hCPU->gpr[8]);
GX2Surface* surface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
cemuLog_log(LogType::GX2, "Tiling Tex: {:08x} {}x{} Swizzle: {:08x} tm: {} fmt: {:04x} use: {:02x}", (uint32)surface->imagePtr, (uint32)surface->width, (uint32)surface->height, (uint32)surface->swizzle, (uint32)surface->tileMode.value(), (uint32)surface->format.value(), (uint32)surface->resFlag);
if( activeTilingAperatureCount >= GX2_MAX_ACTIVE_TILING_APERATURES )
{
debugBreakpoint();
memory_writeU32(hCPU->gpr[8], MPTR_NULL);
memory_writeU32(hCPU->gpr[7], 0);
osLib_returnFromFunction(hCPU, 0);
return;
}
uint32 mipLevel = hCPU->gpr[4];
uint32 sliceIndex = hCPU->gpr[5];
uint32 tilingSize = 0;
// calculate size of texture
Latte::E_GX2SURFFMT surfaceFormat = surface->format;
uint32 bitsPerPixel = Latte::GetFormatBits(surfaceFormat);
if (Latte::IsCompressedFormat(surfaceFormat))
bitsPerPixel /= (4*4);
// get surface pitch
LatteAddrLib::AddrSurfaceInfo_OUT surfaceInfo = {0};
GX2::GX2CalculateSurfaceInfo(surface, 0, &surfaceInfo);
uint32 surfacePitch = surfaceInfo.pitch;
uint32 width = std::max<uint32>((uint32)surface->width >> mipLevel, 1);
uint32 height = std::max<uint32>((uint32)surface->height >> mipLevel, 1);
uint32 alignedWidth = (width+3)&~3;
uint32 alignedHeight = (height+3)&~3;
tilingSize = (surfacePitch*alignedHeight*bitsPerPixel+7)/8;
uint32 taHandle = GX2TilingAperature_GenerateHandle();
// allocate memory for tiling space
MPTR tilingAddress = GX2TilingAperature_allocateTilingMemory(tilingSize);
if( tilingAddress == MPTR_NULL )
{
cemu_assert_suspicious();
memory_writeU32(hCPU->gpr[8], MPTR_NULL);
memory_writeU32(hCPU->gpr[7], 0);
osLib_returnFromFunction(hCPU, 0);
return;
}
// add tiling aperture entry
activeTilingAperature[activeTilingAperatureCount].addr = tilingAddress;
activeTilingAperature[activeTilingAperatureCount].size = tilingSize;
activeTilingAperature[activeTilingAperatureCount].handle = taHandle;
activeTilingAperature[activeTilingAperatureCount].endianMode = hCPU->gpr[6];
activeTilingAperature[activeTilingAperatureCount].sliceIndex = sliceIndex;
activeTilingAperature[activeTilingAperatureCount].mipLevel = mipLevel;
memcpy(&activeTilingAperature[activeTilingAperatureCount].surface, surface, sizeof(GX2Surface));
activeTilingAperatureCount++;
// return values
memory_writeU32(hCPU->gpr[8], tilingAddress);
memory_writeU32(hCPU->gpr[7], taHandle);
// load texture data into tiling area
GX2TilingAperature_RetileTexture(activeTilingAperature+activeTilingAperatureCount-1, false);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2FreeTilingAperture(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2FreeTilingAperture(0x{:08x})", hCPU->gpr[3]);
uint32 handle = hCPU->gpr[3];
for(sint32 i=0; i<activeTilingAperatureCount; i++)
{
if( activeTilingAperature[i].handle == handle )
{
// flush texture
GX2TilingAperature_RetileTexture(activeTilingAperature+i, true);
// remove entry
if( i+1 < activeTilingAperatureCount )
{
memcpy(activeTilingAperature+i, activeTilingAperature+activeTilingAperatureCount-1, sizeof(ActiveTilingAperature));
}
activeTilingAperatureCount--;
osLib_returnFromFunction(hCPU, 0);
return;
}
}
osLib_returnFromFunction(hCPU, 0);
}
| 19,333
|
C++
|
.cpp
| 431
| 41.703016
| 309
| 0.75053
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,055
|
GX2_Streamout.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Streamout.cpp
|
#include "GX2_Streamout.h"
#include "GX2_Command.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/OS/common/OSCommon.h"
namespace GX2
{
void GX2SetStreamOutBuffer(uint32 bufferIndex, GX2StreamOutBuffer* streamOutBuffer)
{
if (bufferIndex >= GX2_MAX_STREAMOUT_BUFFERS)
{
cemu_assert_suspicious();
debug_printf("GX2SetStreamOutBuffer(): Set out-of-bounds buffer\n");
return;
}
MPTR bufferAddr;
uint32 bufferSize;
if (streamOutBuffer->dataPtr.IsNull())
{
bufferAddr = streamOutBuffer->rBuffer.GetVirtualAddr();
bufferSize = streamOutBuffer->rBuffer.GetSize();
}
else
{
bufferAddr = streamOutBuffer->dataPtr.GetMPTR();
bufferSize = streamOutBuffer->size;
}
GX2ReserveCmdSpace(3 + 3);
// set buffer size
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1));
gx2WriteGather_submitU32AsBE((mmVGT_STRMOUT_BUFFER_SIZE_0 + bufferIndex * 4) - 0xA000);
gx2WriteGather_submitU32AsBE((bufferSize >> 2));
// set buffer base
uint32 physMem = memory_virtualToPhysical(bufferAddr);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1));
gx2WriteGather_submitU32AsBE((mmVGT_STRMOUT_BUFFER_BASE_0 + bufferIndex * 4) - 0xA000);
gx2WriteGather_submitU32AsBE((physMem >> 8));
// todo: Research and send IT_STRMOUT_BASE_UPDATE (0x72)
// note: Other stream out registers maybe set in GX2SetVertexShader() or GX2SetGeometryShader()
}
void GX2SetStreamOutEnable(uint32 enable)
{
cemu_assert_debug(enable == 0 || enable == 1);
GX2ReserveCmdSpace(3);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1));
gx2WriteGather_submitU32AsBE(mmVGT_STRMOUT_EN - 0xA000);
gx2WriteGather_submitU32AsBE(enable & 1);
}
void GX2SetStreamOutContext(uint32 bufferIndex, GX2StreamOutBuffer* streamOutBuffer, uint32 mode)
{
if (bufferIndex >= GX2_MAX_STREAMOUT_BUFFERS)
{
cemu_assert_suspicious();
debug_printf("GX2SetStreamOutContext(): Set out-of-bounds buffer\n");
return;
}
GX2ReserveCmdSpace(6);
if (mode == 0)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_STRMOUT_BUFFER_UPDATE, 5));
gx2WriteGather_submitU32AsBE((2 << 1) | (bufferIndex << 8));
gx2WriteGather_submitU32AsBE(MPTR_NULL);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(streamOutBuffer->ctxPtr.GetMPTR()));
gx2WriteGather_submitU32AsBE(0);
}
else if (mode == 1)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_STRMOUT_BUFFER_UPDATE, 5));
gx2WriteGather_submitU32AsBE((0 << 1) | (bufferIndex << 8));
gx2WriteGather_submitU32AsBE(MPTR_NULL);
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(streamOutBuffer->ctxPtr.GetMPTR()));
gx2WriteGather_submitU32AsBE(0);
}
else
{
cemu_assert_unimplemented();
}
}
void GX2SaveStreamOutContext(uint32 bufferIndex, GX2StreamOutBuffer* streamOutBuffer)
{
if (bufferIndex >= GX2_MAX_STREAMOUT_BUFFERS)
{
cemu_assert_suspicious();
debug_printf("GX2SaveStreamOutContext(): Set out-of-bounds buffer\n");
return;
}
GX2ReserveCmdSpace(6);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_STRMOUT_BUFFER_UPDATE, 5));
gx2WriteGather_submitU32AsBE(1 | (3 << 1) | (bufferIndex << 8));
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(streamOutBuffer->ctxPtr.GetMPTR()));
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(MPTR_NULL);
gx2WriteGather_submitU32AsBE(0);
}
void GX2StreamoutInit()
{
cafeExportRegister("gx2", GX2SetStreamOutBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2SetStreamOutEnable, LogType::GX2);
cafeExportRegister("gx2", GX2SetStreamOutContext, LogType::GX2);
cafeExportRegister("gx2", GX2SaveStreamOutContext, LogType::GX2);
}
}
| 3,821
|
C++
|
.cpp
| 104
| 33.692308
| 98
| 0.764769
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,056
|
GX2_RenderTarget.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_RenderTarget.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/LatteAddrLib/LatteAddrLib.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "GX2_Command.h"
void gx2Export_GX2InitColorBufferRegs(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2InitColorBufferRegs(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(colorBuffer, GX2ColorBuffer, 0);
LatteAddrLib::AddrSurfaceInfo_OUT surfaceInfo;
LatteAddrLib::GX2CalculateSurfaceInfo(colorBuffer->surface.format, colorBuffer->surface.width, colorBuffer->surface.height, colorBuffer->surface.depth, colorBuffer->surface.dim, colorBuffer->surface.tileMode, colorBuffer->surface.aa, _swapEndianU32(colorBuffer->viewMip), &surfaceInfo);
uint32 pitchHeight = (surfaceInfo.height * surfaceInfo.pitch) >> 6;
#ifdef CEMU_DEBUG_ASSERT
if (colorBuffer->viewNumSlices != _swapEndianU32(1))
cemuLog_logDebug(LogType::Force, "GX2InitColorBufferRegs(): With unsupported slice count {}", _swapEndianU32(colorBuffer->viewNumSlices));
if (surfaceInfo.pitch < 7)
cemuLog_logDebug(LogType::Force, "GX2InitColorBufferRegs(): Pitch too small (pitch = {})", surfaceInfo.pitch);
if ((surfaceInfo.pitch & 7) != 0)
cemuLog_logDebug(LogType::Force, "GX2InitColorBufferRegs(): Pitch has invalid alignment (pitch = {})", surfaceInfo.pitch);
if (pitchHeight == 0)
cemuLog_logDebug(LogType::Force, "GX2InitColorBufferRegs(): Invalid value (pitchHeight = {})", pitchHeight);
#endif
uint32 cSize = ((surfaceInfo.pitch >> 3) - 1) & 0x3FF;
cSize |= (((pitchHeight - 1) & 0xFFFFF) << 10);
colorBuffer->reg_size = cSize;
colorBuffer->reg_mask = 0;
// reg color_info
Latte::E_GX2SURFFMT format = colorBuffer->surface.format;
Latte::E_HWSURFFMT hwFormat = Latte::GetHWFormat(format);
uint32 formatHighBits = (uint32)format & 0xF00;
uint32 regInfo = 0;
regInfo = (uint32)GX2::GetSurfaceFormatSwapMode(colorBuffer->surface.format);
regInfo |= ((uint32)hwFormat<<2);
cemu_assert_debug(LatteAddrLib::IsValidHWTileMode(surfaceInfo.hwTileMode));
regInfo |= ((uint32)surfaceInfo.hwTileMode << 8);
bool clampBlend = false;
if (formatHighBits == 0x000)
{
regInfo |= (0 << 12);
clampBlend = true;
}
else if (formatHighBits == 0x100) // integer
{
regInfo |= (4 << 12);
}
else if (formatHighBits == 0x200) // signed
{
regInfo |= (1 << 12);
clampBlend = true;
}
else if (formatHighBits == 0x300) // integer + signed
{
regInfo |= (5 << 12);
}
else if (formatHighBits == 0x400) // srgb
{
clampBlend = true;
regInfo |= (6 << 12);
}
else if (formatHighBits == 0x800) // float
{
regInfo |= (7 << 12);
}
else
cemu_assert_debug(false);
if (hwFormat == Latte::E_HWSURFFMT::HWFMT_5_5_5_1 || hwFormat == Latte::E_HWSURFFMT::HWFMT_10_10_10_2 )
regInfo |= (2 << 16);
else
regInfo &= ~(3 << 16); // COMP_SWAP_mask
if(colorBuffer->surface.aa != 0)
regInfo |= (2 << 18); // TILE_MODE
bool isIntegerFormat = (uint32)(format & Latte::E_GX2SURFFMT::FMT_BIT_INT) != 0;
if (isIntegerFormat == false)
regInfo |= (GX2::GetSurfaceColorBufferExportFormat(colorBuffer->surface.format) << 27); // 0 -> full, 1 -> normalized
if (isIntegerFormat
|| format ==Latte::E_GX2SURFFMT::R24_X8_UNORM
|| format ==Latte::E_GX2SURFFMT::R24_X8_FLOAT
|| format ==Latte::E_GX2SURFFMT::R32_X8_FLOAT)
{
// set the blend bypass bit for formats which dont support blending
regInfo |= (1<<22);
clampBlend = false;
}
if (clampBlend)
regInfo |= (1<<20); // BLEND_CLAMP_bit
if ((uint32)(format & Latte::E_GX2SURFFMT::FMT_BIT_FLOAT) != 0)
regInfo |= (1<<25); // ROUND_MODE_bit
colorBuffer->reg_info = regInfo;
// reg color_view
uint32 regView = 0;
if (colorBuffer->surface.tileMode != Latte::E_GX2TILEMODE::TM_LINEAR_SPECIAL)
{
regView |= (_swapEndianU32(colorBuffer->viewFirstSlice) & 0x7FF);
regView |= (((_swapEndianU32(colorBuffer->viewNumSlices) + _swapEndianU32(colorBuffer->viewFirstSlice) - 1) & 0x7FF) << 13);
}
colorBuffer->reg_view = regView;
colorBuffer->reg_mask = 0;
// todo - aa stuff
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2InitDepthBufferRegs(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2InitDepthBufferRegs(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamStructPtr(depthBuffer, GX2DepthBuffer, 0);
LatteAddrLib::AddrSurfaceInfo_OUT surfaceInfo;
LatteAddrLib::GX2CalculateSurfaceInfo(depthBuffer->surface.format, depthBuffer->surface.width, depthBuffer->surface.height, depthBuffer->surface.depth, depthBuffer->surface.dim, depthBuffer->surface.tileMode, depthBuffer->surface.aa, _swapEndianU32(depthBuffer->viewMip), &surfaceInfo);
cemu_assert_debug(depthBuffer->viewNumSlices != 0);
uint32 cSize = ((surfaceInfo.pitch >> 3) - 1) & 0x3FF;
cSize |= ((((surfaceInfo.height * surfaceInfo.pitch >> 6) - 1) & 0xFFFFF) << 10);
depthBuffer->reg_size = cSize;
// todo - other regs
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetColorBuffer(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetColorBuffer(0x{:08x}, {})", hCPU->gpr[3], hCPU->gpr[4]);
GX2ReserveCmdSpace(20);
GX2ColorBuffer* colorBufferBE = (GX2ColorBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
#ifdef CEMU_DEBUG_ASSERT
cemuLog_log(LogType::GX2, "ColorBuffer tileMode {:01x} PhysAddr {:08x} fmt {:04x} res {}x{} Mip {} Slice {}", (uint32)colorBufferBE->surface.tileMode.value(), (uint32)colorBufferBE->surface.imagePtr, (uint32)colorBufferBE->surface.format.value(), (uint32)colorBufferBE->surface.width, (uint32)colorBufferBE->surface.height, _swapEndianU32(colorBufferBE->viewMip), _swapEndianU32(colorBufferBE->viewFirstSlice));
#endif
// regs[0] = mmCB_COLOR0_SIZE
// regs[1] = mmCB_COLOR0_INFO
// regs[2] = mmCB_COLOR0_VIEW
// regs[3] = mmCB_COLOR0_MASK
// regs[4] = mmCB_COLOR0_TILE
uint32 targetIndex = hCPU->gpr[4];
uint32 viewMip = _swapEndianU32(colorBufferBE->viewMip);
uint32 colorBufferBase = memory_virtualToPhysical(colorBufferBE->surface.imagePtr);
if( viewMip != 0 )
{
uint32 baseImagePtr = colorBufferBE->surface.mipPtr;
if( viewMip == 1 )
colorBufferBase = memory_virtualToPhysical(baseImagePtr);
else
colorBufferBase = memory_virtualToPhysical(baseImagePtr+colorBufferBE->surface.mipOffset[viewMip-1]);
}
Latte::E_GX2TILEMODE tileMode = colorBufferBE->surface.tileMode;
uint32 viewMipIndex = _swapEndianU32(colorBufferBE->viewMip);
uint32 swizzle = colorBufferBE->surface.swizzle;
if (Latte::TM_IsMacroTiled(tileMode) && viewMipIndex < ((swizzle >> 16) & 0xFF))
{
// remove swizzle for small mips
colorBufferBase ^= (swizzle & 0xFFFF);
}
// set color buffer pointer for render target
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmCB_COLOR0_BASE - 0xA000 + hCPU->gpr[4]);
gx2WriteGather_submitU32AsBE(colorBufferBase);
// set color buffer size
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmCB_COLOR0_SIZE - 0xA000 + hCPU->gpr[4]);
gx2WriteGather_submitU32AsBE((uint32)colorBufferBE->reg_size);
cemu_assert_debug(tileMode != Latte::E_GX2TILEMODE::TM_LINEAR_SPECIAL);
// set mmCB_COLOR*_VIEW
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
mmCB_COLOR0_VIEW - 0xA000 + hCPU->gpr[4],
colorBufferBE->reg_view);
// todo: mmCB_COLOR0_TILE and mmCB_COLOR0_FRAG
// set mmCB_COLOR*_INFO
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
mmCB_COLOR0_INFO - 0xA000 + hCPU->gpr[4],
colorBufferBE->reg_info);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetDepthBuffer(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetDepthBuffer(0x{:08x})", hCPU->gpr[3]);
GX2ReserveCmdSpace(20);
GX2DepthBuffer* depthBufferBE = (GX2DepthBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
cemuLog_log(LogType::GX2, "DepthBuffer tileMode {:01x} PhysAddr {:08x} fmt {:04x} res {}x{}", (uint32)depthBufferBE->surface.tileMode.value(), (uint32)depthBufferBE->surface.imagePtr, (uint32)depthBufferBE->surface.format.value(), (uint32)depthBufferBE->surface.width, (uint32)depthBufferBE->surface.height);
uint32 viewMip = _swapEndianU32(depthBufferBE->viewMip);
// todo: current code for the PM4 packets is a hack, replace with proper implementation
uint32 regHTileDataBase = memory_virtualToPhysical(depthBufferBE->surface.imagePtr)>>8;
if( viewMip > 0 )
{
cemuLog_logDebug(LogType::Force, "GX2SetDepthBuffer: Unsupported non-zero mip ({}) Pointer: {:08x} Base: {:08x}", viewMip, regHTileDataBase, 0);
}
// setup depthbuffer info register
uint32 regDepthBufferInfo = 0;
uint32 depthBufferTileMode = (uint32)depthBufferBE->surface.tileMode.value();
Latte::E_GX2SURFFMT depthBufferFormat = depthBufferBE->surface.format;
regDepthBufferInfo |= ((depthBufferTileMode&0xF)<<15);
if (depthBufferFormat == Latte::E_GX2SURFFMT::D16_UNORM)
regDepthBufferInfo |= (1 << 0);
else if (depthBufferFormat == Latte::E_GX2SURFFMT::D24_S8_UNORM)
regDepthBufferInfo |= (3 << 0);
else if (depthBufferFormat == Latte::E_GX2SURFFMT::D32_FLOAT)
regDepthBufferInfo |= (6 << 0);
else if (depthBufferFormat == Latte::E_GX2SURFFMT::D32_S8_FLOAT)
regDepthBufferInfo |= (7 << 0);
else if (depthBufferFormat == Latte::E_GX2SURFFMT::D24_S8_FLOAT)
regDepthBufferInfo |= (5 << 0);
else
{
debug_printf("Unsupported depth buffer format 0x%04x\n", depthBufferFormat);
}
// set color buffer pointer for render target
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+1));
gx2WriteGather_submitU32AsBE(mmDB_DEPTH_SIZE - 0xA000);
gx2WriteGather_submitU32AsBE((uint32)depthBufferBE->reg_size); // hack
// set color buffer size
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+3));
gx2WriteGather_submitU32AsBE(mmDB_DEPTH_BASE - 0xA000);
gx2WriteGather_submitU32AsBE(0); // DB_DEPTH_BASE
gx2WriteGather_submitU32AsBE(regDepthBufferInfo); // DB_DEPTH_INFO
gx2WriteGather_submitU32AsBE(regHTileDataBase); // DB_HTILE_DATA_BASE
// set DB_DEPTH_VIEW
uint32 db_view = 0;
db_view |= (_swapEndianU32(depthBufferBE->viewFirstSlice)&0x7FF);
db_view |= (((_swapEndianU32(depthBufferBE->viewNumSlices)+_swapEndianU32(depthBufferBE->viewFirstSlice)-1)&0x7FF)<<13);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmDB_DEPTH_VIEW - 0xA000);
gx2WriteGather_submitU32AsBE(db_view);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetDRCBuffer(PPCInterpreter_t* hCPU)
{
Latte::E_GX2SURFFMT format = (Latte::E_GX2SURFFMT)hCPU->gpr[6];
LatteGPUState.drcBufferUsesSRGB = HAS_FLAG(format, Latte::E_GX2SURFFMT::FMT_BIT_SRGB);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2MarkScanBufferCopied(PPCInterpreter_t* hCPU)
{
uint32 scanTarget = hCPU->gpr[3];
if( scanTarget == GX2_SCAN_TARGET_TV )
{
GX2ReserveCmdSpace(10);
uint32 physAddr = (MEMORY_TILINGAPERTURE_AREA_ADDR+0x200000);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_COPY_COLORBUFFER_TO_SCANBUFFER, 9));
gx2WriteGather_submitU32AsBE(physAddr);
gx2WriteGather_submitU32AsBE(1920);
gx2WriteGather_submitU32AsBE(1080);
gx2WriteGather_submitU32AsBE(1920); // pitch
gx2WriteGather_submitU32AsBE(4); // tileMode
gx2WriteGather_submitU32AsBE(0); // swizzle
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE((uint32)Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM);
gx2WriteGather_submitU32AsBE(scanTarget);
}
osLib_returnFromFunction(hCPU, 0);
}
| 11,681
|
C++
|
.cpp
| 250
| 44.388
| 412
| 0.754087
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,057
|
GX2_Misc.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Misc.cpp
|
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/OS/common/OSCommon.h"
#include "GX2.h"
#include "config/CemuConfig.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "config/ActiveSettings.h"
#include "Cafe/HW/Latte/Renderer/Renderer.h"
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "GX2_Command.h"
#include "GX2_Event.h"
#include "GX2_Misc.h"
#include "GX2_Memory.h"
#include "GX2_Texture.h"
void gx2Export_GX2SetSwapInterval(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetSwapInterval({})", hCPU->gpr[3]);
if( hCPU->gpr[3] >= 20 )
{
cemuLog_log(LogType::Force, "GX2SetSwapInterval() called with out of range value ({})", hCPU->gpr[3]);
}
else
LatteGPUState.sharedArea->swapInterval = hCPU->gpr[3];
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2GetSwapInterval(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2GetSwapInterval()");
osLib_returnFromFunction(hCPU, LatteGPUState.sharedArea->swapInterval);
}
extern uint64 lastSwapTime;
void gx2Export_GX2GetSwapStatus(PPCInterpreter_t* hCPU)
{
memory_writeU32(hCPU->gpr[3], _swapEndianU32(LatteGPUState.sharedArea->flipRequestCountBE));
memory_writeU32(hCPU->gpr[4], _swapEndianU32(LatteGPUState.sharedArea->flipExecuteCountBE));
memory_writeU64(hCPU->gpr[5], lastSwapTime);
memory_writeU64(hCPU->gpr[6], lastSwapTime);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2GetGPUTimeout(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2GetGPUTimeout()");
osLib_returnFromFunction(hCPU, 0x3E8);
}
#define GX2_INVALID_COUNTER_VALUE_U64 0xFFFFFFFFFFFFFFFFULL
void gx2Export_GX2SampleTopGPUCycle(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SampleTopGPUCycle(0x{:08x})", hCPU->gpr[3]);
memory_writeU64(hCPU->gpr[3], coreinit::coreinit_getTimerTick());
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SampleBottomGPUCycle(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SampleBottomGPUCycle(0x{:08x})", hCPU->gpr[3]);
memory_writeU64(hCPU->gpr[3], GX2_INVALID_COUNTER_VALUE_U64);
osLib_returnFromFunction(hCPU, 0);
return;
// seems like implementing this correctly causes more harm than good as games will try to dynamically scale their resolution, which our texture cache and graphic packs cant handle well. If we just never return a valid timestamp, it seems like games stop dynamically scaling resolution
// Whats a good solution here? Should we implement it correctly and instead rely on graphic pack patches to patch out the dynamic scaling?
// some known affected games: Wind Waker HD, Super Mario 3D World
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_SAMPLE_TIMER, 1));
gx2WriteGather_submitU32AsBE(hCPU->gpr[3]);
osLib_returnFromFunction(hCPU, 0);
}
namespace GX2
{
SysAllocator<uint8, 640 * 480 * 4, 0x1000> _lastFrame;
uint32 sGX2MainCoreIndex = 0;
void _test_AddrLib();
void GX2Init(void* initSettings)
{
if (LatteGPUState.gx2InitCalled)
{
cemuLog_logDebug(LogType::Force, "GX2Init() called while already initialized");
return;
}
uint32 coreIndex = coreinit::OSGetCoreId();
cemuLog_log(LogType::GX2, "GX2Init() on core {} by thread 0x{:08x}", coreIndex, MEMPTR<OSThread_t>(coreinit::OSGetCurrentThread()).GetMPTR());
sGX2MainCoreIndex = coreIndex;
// init submodules
GX2::GX2Init_event();
GX2::GX2Init_writeGather();
// init shared area
if (LatteGPUState.sharedAreaAddr == MPTR_NULL)
{
LatteGPUState.sharedAreaAddr = coreinit_allocFromSysArea(sizeof(gx2GPUSharedArea_t), 0x20);
LatteGPUState.sharedArea = (gx2GPUSharedArea_t*)memory_getPointerFromVirtualOffset(LatteGPUState.sharedAreaAddr);
}
// init shared variables
LatteGPUState.sharedArea->flipRequestCountBE = _swapEndianU32(0);
LatteGPUState.sharedArea->flipExecuteCountBE = _swapEndianU32(0);
LatteGPUState.sharedArea->swapInterval = 1;
// init memory handling
GX2::GX2MEMAllocatorsInit();
// let GPU know that GX2 is initialized
LatteGPUState.gx2InitCalled++;
// run tests
_test_AddrLib();
}
void _GX2DriverReset()
{
LatteGPUState.gx2InitCalled = 0;
sGX2MainCoreIndex = 0;
GX2CommandResetToDefaultState();
GX2EventResetToDefaultState();
}
sint32 GX2GetMainCoreId(PPCInterpreter_t* hCPU)
{
if (LatteGPUState.gx2InitCalled == 0)
return -1;
return sGX2MainCoreIndex;
}
void GX2ResetGPU(uint32 ukn)
{
cemuLog_log(LogType::Force, "GX2ResetGPU()"); // always log this
GX2::GX2DrawDone();
}
void GX2SetTVBuffer(void* imageBuffePtr, uint32 imageBufferSize, E_TVRES tvResolutionMode, uint32 _surfaceFormat, E_TVBUFFERMODE bufferMode)
{
Latte::E_GX2SURFFMT surfaceFormat = (Latte::E_GX2SURFFMT)_surfaceFormat;
LatteGPUState.tvBufferUsesSRGB = HAS_FLAG(surfaceFormat, Latte::E_GX2SURFFMT::FMT_BIT_SRGB);
// todo - actually allocate a scanbuffer
}
void GX2SetTVGamma(float gamma)
{
if (abs(gamma - 1.0f) > 0.01f)
cemuLog_logDebug(LogType::Force, "TV gamma set to {} which is not supported", gamma);
}
bool GX2GetLastFrame(uint32 deviceId, GX2Texture* textureOut)
{
// return a 480p image
textureOut->viewFirstMip = 0;
textureOut->viewFirstSlice = 0;
textureOut->viewNumMips = 1;
textureOut->viewNumSlices = 1;
textureOut->compSel = 0x00010203;
textureOut->surface.width = 640;
textureOut->surface.height = 480;
textureOut->surface.depth = 1;
textureOut->surface.dim = Latte::E_DIM::DIM_2D;
textureOut->surface.format = Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM;
textureOut->surface.tileMode = Latte::E_GX2TILEMODE::TM_LINEAR_ALIGNED;
textureOut->surface.pitch = 0;
textureOut->surface.resFlag = 0;
textureOut->surface.aa = 0;
GX2CalcSurfaceSizeAndAlignment(&textureOut->surface);
textureOut->surface.imagePtr = _lastFrame.GetMPTR();
GX2InitTextureRegs(textureOut);
return true;
}
bool GX2GetLastFrameGammaA(uint32 deviceId, float32be* gamma)
{
*gamma = 1.0f;
return true;
}
bool GX2GetLastFrameGammaB(uint32 deviceId, float32be* gamma)
{
*gamma = 1.0f;
return true;
}
uint64 GX2GPUTimeToCPUTime(uint64 gpuTime)
{
return 0; // hack, see note in GX2SampleBottomGPUCycle
}
uint32 GX2GetSystemDRCMode()
{
return 1;
}
uint32 GX2IsVideoOutReady()
{
return 1;
}
void GX2Invalidate(uint32 invalidationFlags, MPTR invalidationAddr, uint32 invalidationSize)
{
uint32 surfaceSyncFlags = 0;
if (invalidationFlags & 0x04)
{
// uniform block
surfaceSyncFlags |= 0x8800000;
}
if (invalidationFlags & 0x01)
{
// attribute data
surfaceSyncFlags |= 0x800000;
}
if (invalidationFlags & 0x40)
{
// CPU cache
LatteBufferCache_notifyDCFlush(invalidationAddr, invalidationSize);
}
if (surfaceSyncFlags != 0)
{
GX2ReserveCmdSpace(5);
// write PM4 command
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SURFACE_SYNC, 4)); // IT_SURFACE_SYNC + 4 data dwords
gx2WriteGather_submitU32AsBE(surfaceSyncFlags);
gx2WriteGather_submitU32AsBE((invalidationSize + 0xFF) >> 8); // size
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(invalidationAddr) >> 8); // base address (divided by 0x100)
gx2WriteGather_submitU32AsBE(0x00000004); // poll interval
}
}
void GX2MiscInit()
{
cafeExportRegister("gx2", GX2Init, LogType::GX2);
cafeExportRegister("gx2", GX2GetMainCoreId, LogType::GX2);
cafeExportRegister("gx2", GX2ResetGPU, LogType::GX2);
cafeExportRegister("gx2", GX2SetTVBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2SetTVGamma, LogType::GX2);
cafeExportRegister("gx2", GX2GetLastFrame, LogType::GX2);
cafeExportRegister("gx2", GX2GetLastFrameGammaA, LogType::GX2);
cafeExportRegister("gx2", GX2GetLastFrameGammaB, LogType::GX2);
cafeExportRegister("gx2", GX2GPUTimeToCPUTime, LogType::GX2);
cafeExportRegister("gx2", GX2GetSystemDRCMode, LogType::GX2);
cafeExportRegister("gx2", GX2IsVideoOutReady, LogType::GX2);
cafeExportRegister("gx2", GX2Invalidate, LogType::GX2);
sGX2MainCoreIndex = 0;
}
};
| 7,985
|
C++
|
.cpp
| 218
| 33.944954
| 285
| 0.767439
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,058
|
GX2_Event.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Event.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "GX2_Command.h"
#include "GX2_Event.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/HW/MMU/MMU.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "GX2.h"
#include "Cafe/HW/Latte/Renderer/Renderer.h"
#include "config/ActiveSettings.h"
#include "util/helpers/ConcurrentQueue.h"
namespace GX2
{
SysAllocator<coreinit::OSThreadQueue> g_vsyncThreadQueue;
SysAllocator<coreinit::OSThreadQueue> g_flipThreadQueue;
SysAllocator<coreinit::OSEvent> s_updateRetirementEvent;
std::atomic<uint64> s_lastRetirementTimestamp = 0;
// called from GPU code when a command buffer is retired
void __GX2NotifyNewRetirementTimestamp(uint64 tsRetire)
{
__OSLockScheduler();
s_lastRetirementTimestamp = tsRetire;
coreinit::OSSignalEventAllInternal(s_updateRetirementEvent.GetPtr());
__OSUnlockScheduler();
}
void GX2SetGPUFence(uint32be* fencePtr, uint32 mask, uint32 compareOp, uint32 compareValue)
{
GX2ReserveCmdSpace(7);
uint8 compareOpTable[] = { 0x7,0x1,0x3,0x2,0x6,0x4,0x5,0x0 };
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_WAIT_REG_MEM, 6));
gx2WriteGather_submitU32AsBE((uint32)(compareOpTable[compareOp & 7]) | 0x10); // compare operand + memory select (0x10)
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(fencePtr)) | 2); // physical address + type size flag(?)
gx2WriteGather_submitU32AsBE(0); // ukn, always set to 0
gx2WriteGather_submitU32AsBE(compareValue); // fence value
gx2WriteGather_submitU32AsBE(mask); // fence mask
gx2WriteGather_submitU32AsBE(0xA); // unknown purpose
}
enum class GX2PipeEventType : uint32
{
TOP = 0,
BOTTOM = 1,
BOTTOM_AFTER_FLUSH = 2
};
void GX2SubmitUserTimeStamp(uint64* timestampOut, uint64 value, GX2PipeEventType eventType, uint32 triggerInterrupt)
{
GX2ReserveCmdSpace(7);
MPTR physTimestampAddr = memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(timestampOut));
uint32 valHigh = (uint32)(value >> 32);
uint32 valLow = (uint32)(value & 0xffffffff);
if (eventType == GX2PipeEventType::TOP)
{
// write when on top of pipe
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_MEM_WRITE, 4));
gx2WriteGather_submitU32AsBE(physTimestampAddr | 0x2);
gx2WriteGather_submitU32AsBE(0); // 0x40000 -> 32bit write, 0x0 -> 64bit write?
gx2WriteGather_submitU32AsBE(valLow); // low
gx2WriteGather_submitU32AsBE(valHigh); // high
if (triggerInterrupt != 0)
{
// top callback
gx2WriteGather_submitU32AsBE(0x0000304A);
gx2WriteGather_submitU32AsBE(0x40000000);
}
}
else if (eventType == GX2PipeEventType::BOTTOM_AFTER_FLUSH)
{
// write when on bottom of pipe
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_MEM_WRITE, 4));
gx2WriteGather_submitU32AsBE(physTimestampAddr | 0x2);
gx2WriteGather_submitU32AsBE(0); // 0x40000 -> 32bit write, 0x0 -> 64bit write?
gx2WriteGather_submitU32AsBE(valLow); // low
gx2WriteGather_submitU32AsBE(valHigh); // high
// trigger CB
if (triggerInterrupt != 0)
{
// bottom callback
// todo -> Fix this
gx2WriteGather_submitU32AsBE(0x0000304B); // hax -> This event is handled differently and uses a different packet?
gx2WriteGather_submitU32AsBE(0x40000000);
// trigger bottom of pipe callback
// used by Mario & Sonic Rio
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_BOTTOM_OF_PIPE_CB, 3));
gx2WriteGather_submitU32AsBE(physTimestampAddr);
gx2WriteGather_submitU32AsBE(valLow); // low
gx2WriteGather_submitU32AsBE(valHigh); // high
}
}
else if (eventType == GX2PipeEventType::BOTTOM)
{
// fix this
// write timestamp when on bottom of pipe
if (triggerInterrupt != 0)
{
// write value and trigger CB
// todo: Use correct packet
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_BOTTOM_OF_PIPE_CB, 3));
gx2WriteGather_submitU32AsBE(physTimestampAddr);
gx2WriteGather_submitU32AsBE(valLow); // low
gx2WriteGather_submitU32AsBE(valHigh); // high
}
else
{
// write value but don't trigger CB
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_MEM_WRITE, 4));
gx2WriteGather_submitU32AsBE(physTimestampAddr | 0x2);
gx2WriteGather_submitU32AsBE(0); // 0x40000 -> 32bit write, 0x0 -> 64bit write?
gx2WriteGather_submitU32AsBE(valLow); // low
gx2WriteGather_submitU32AsBE(valHigh); // high
}
}
else
{
cemu_assert_debug(false);
}
}
struct GX2EventFunc
{
MEMPTR<void> callbackFuncPtr;
MEMPTR<void> userData;
}s_eventCallback[GX2CallbackEventTypeCount]{};
void GX2SetEventCallback(GX2CallbackEventType eventType, void* callbackFuncPtr, void* userData)
{
if ((size_t)eventType >= GX2CallbackEventTypeCount)
{
cemuLog_log(LogType::Force, "GX2SetEventCallback(): Unknown eventType");
return;
}
s_eventCallback[(size_t)eventType].callbackFuncPtr = callbackFuncPtr;
s_eventCallback[(size_t)eventType].userData = userData;
}
void GX2GetEventCallback(GX2CallbackEventType eventType, MEMPTR<void>* callbackFuncPtrOut, MEMPTR<void>* userDataOut)
{
if ((size_t)eventType >= GX2CallbackEventTypeCount)
{
cemuLog_log(LogType::Force, "GX2GetEventCallback(): Unknown eventType");
return;
}
if (callbackFuncPtrOut)
*callbackFuncPtrOut = s_eventCallback[(size_t)eventType].callbackFuncPtr;
if (userDataOut)
*userDataOut = s_eventCallback[(size_t)eventType].userData;
}
// event callback thread
bool s_callbackThreadLaunched{};
SysAllocator<OSThread_t> s_eventCallbackThread;
SysAllocator<uint8, 0x2000> s_eventCallbackThreadStack;
SysAllocator<char, 64> s_eventCallbackThreadName;
// event callback queue
struct GX2EventQueueEntry
{
GX2EventQueueEntry() {};
GX2EventQueueEntry(GX2CallbackEventType eventType) : eventType(eventType) {};
GX2CallbackEventType eventType{(GX2CallbackEventType)-1};
};
SysAllocator<coreinit::OSSemaphore> s_eventCbQueueSemaphore;
ConcurrentQueue<GX2EventQueueEntry> s_eventCbQueue;
void __GX2NotifyEvent(GX2CallbackEventType eventType)
{
if ((size_t)eventType >= GX2CallbackEventTypeCount)
{
cemu_assert_debug(false);
return;
}
if (s_eventCallback[(size_t)eventType].callbackFuncPtr)
{
s_eventCbQueue.push(eventType);
coreinit::OSSignalSemaphore(s_eventCbQueueSemaphore);
}
// wake up threads that are waiting for VSYNC or FLIP event
if (eventType == GX2CallbackEventType::VSYNC)
{
__OSLockScheduler();
g_vsyncThreadQueue->wakeupEntireWaitQueue(false);
__OSUnlockScheduler();
}
else if (eventType == GX2CallbackEventType::FLIP)
{
__OSLockScheduler();
g_flipThreadQueue->wakeupEntireWaitQueue(false);
__OSUnlockScheduler();
}
}
void __GX2CallbackThread(PPCInterpreter_t* hCPU)
{
while (coreinit::OSWaitSemaphore(s_eventCbQueueSemaphore))
{
GX2EventQueueEntry entry;
if (!s_eventCbQueue.peek2(entry))
continue;
if(!s_eventCallback[(size_t)entry.eventType].callbackFuncPtr)
continue;
PPCCoreCallback(s_eventCallback[(size_t)entry.eventType].callbackFuncPtr, (sint32)entry.eventType, s_eventCallback[(size_t)entry.eventType].userData);
}
osLib_returnFromFunction(hCPU, 0);
}
uint64 GX2GetLastSubmittedTimeStamp()
{
return LatteGPUState.lastSubmittedCommandBufferTimestamp.load();
}
uint64 GX2GetRetiredTimeStamp()
{
return s_lastRetirementTimestamp;
}
void GX2WaitForVsync()
{
__OSLockScheduler();
g_vsyncThreadQueue.GetPtr()->queueAndWait(coreinit::OSGetCurrentThread());
__OSUnlockScheduler();
}
void GX2WaitForFlip()
{
if ((sint32)(_swapEndianU32(LatteGPUState.sharedArea->flipRequestCountBE) == _swapEndianU32(LatteGPUState.sharedArea->flipExecuteCountBE)))
return; // dont wait if no flip is requested
__OSLockScheduler();
g_flipThreadQueue.GetPtr()->queueAndWait(coreinit::OSGetCurrentThread());
__OSUnlockScheduler();
}
bool GX2WaitTimeStamp(uint64 tsWait)
{
__OSLockScheduler();
while (tsWait > s_lastRetirementTimestamp)
{
// GPU hasn't caught up yet
coreinit::OSWaitEventInternal(s_updateRetirementEvent.GetPtr());
}
__OSUnlockScheduler();
// return true to indicate no timeout
return true;
}
void GX2DrawDone()
{
// optional force full sync (texture readback and occlusion queries)
bool forceFullSync = false;
if (g_renderer && g_renderer->GetType() == RendererAPI::Vulkan)
forceFullSync = true;
if (forceFullSync || ActiveSettings::WaitForGX2DrawDoneEnabled())
{
GX2ReserveCmdSpace(2);
// write PM4 command
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_SYNC_ASYNC_OPERATIONS, 1));
gx2WriteGather_submitU32AsBE(0x00000000); // unused
}
// flush pipeline
if (_GX2GetUnflushedBytes(coreinit::OSGetCoreId()) > 0)
_GX2SubmitToTCL();
uint64 ts = GX2GetLastSubmittedTimeStamp();
GX2WaitTimeStamp(ts);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
}
void GX2Init_event()
{
// clear queue
// launch event callback thread
if (s_callbackThreadLaunched)
return;
s_callbackThreadLaunched = true;
strcpy(s_eventCallbackThreadName.GetPtr(), "GX2 event callback");
coreinit::OSCreateThreadType(s_eventCallbackThread, PPCInterpreter_makeCallableExportDepr(__GX2CallbackThread), 0, nullptr, (uint8*)s_eventCallbackThreadStack.GetPtr() + s_eventCallbackThreadStack.GetByteSize(), (sint32)s_eventCallbackThreadStack.GetByteSize(), 16, OSThread_t::ATTR_DETACHED, OSThread_t::THREAD_TYPE::TYPE_IO);
coreinit::OSSetThreadName(s_eventCallbackThread, s_eventCallbackThreadName);
coreinit::OSResumeThread(s_eventCallbackThread);
}
void GX2EventInit()
{
cafeExportRegister("gx2", GX2SetGPUFence, LogType::GX2);
cafeExportRegister("gx2", GX2SubmitUserTimeStamp, LogType::GX2);
cafeExportRegister("gx2", GX2SetEventCallback, LogType::GX2);
cafeExportRegister("gx2", GX2GetEventCallback, LogType::GX2);
cafeExportRegister("gx2", GX2GetLastSubmittedTimeStamp, LogType::GX2);
cafeExportRegister("gx2", GX2GetRetiredTimeStamp, LogType::GX2);
cafeExportRegister("gx2", GX2WaitForVsync, LogType::GX2);
cafeExportRegister("gx2", GX2WaitForFlip, LogType::GX2);
cafeExportRegister("gx2", GX2WaitTimeStamp, LogType::GX2);
cafeExportRegister("gx2", GX2DrawDone, LogType::GX2);
coreinit::OSInitThreadQueue(g_vsyncThreadQueue.GetPtr());
coreinit::OSInitThreadQueue(g_flipThreadQueue.GetPtr());
coreinit::OSInitEvent(s_updateRetirementEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
coreinit::OSInitSemaphore(s_eventCbQueueSemaphore, 0);
}
void GX2EventResetToDefaultState()
{
s_callbackThreadLaunched = false;
s_lastRetirementTimestamp = 0;
for(auto& it : s_eventCallback)
{
it.callbackFuncPtr = nullptr;
it.userData = nullptr;
}
}
}
| 10,850
|
C++
|
.cpp
| 289
| 34.176471
| 329
| 0.764628
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,059
|
GX2_Resource.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Resource.cpp
|
#include "Cafe/HW/Latte/Core/LatteBufferCache.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/OS/common/OSCommon.h"
#include "GX2.h"
#include "GX2_Command.h"
#include "GX2_Resource.h"
#include "GX2_Streamout.h"
#include "GX2_Draw.h"
namespace GX2
{
MPTR GX2RAllocateFunc = MPTR_NULL;
MPTR GX2RFreeFunc = MPTR_NULL;
void GX2RSetAllocator(MPTR funcAllocMPTR, MPTR funcFreeMPR)
{
GX2RAllocateFunc = funcAllocMPTR;
GX2RFreeFunc = funcFreeMPR;
}
uint32 GX2RGetBufferAllocationSize(GX2RBuffer* buffer)
{
return (buffer->GetSize() + 0x3F) & ~0x3F; // pad to 64 byte alignment
}
uint32 GX2RGetBufferAlignment(uint32 resFlags)
{
if ((resFlags & GX2R_RESFLAG_USAGE_STREAM_OUTPUT) != 0)
return 0x100;
if ((resFlags & GX2R_RESFLAG_USAGE_UNIFORM_BLOCK) != 0)
return 0x100;
if ((resFlags & GX2R_RESFLAG_USAGE_SHADER_PROGRAM) != 0)
return 0x100;
if ((resFlags & GX2R_RESFLAG_USAGE_GS_RINGBUFFER) != 0)
return 0x100;
if ((resFlags & GX2R_RESFLAG_USAGE_VERTEX_BUFFER) != 0)
return 0x40;
if ((resFlags & GX2R_RESFLAG_USAGE_INDEX_BUFFER) != 0)
return 0x40;
if ((resFlags & GX2R_RESFLAG_USAGE_DISPLAY_LIST) != 0)
return 0x40;
return 0x100;
}
bool GX2RCreateBuffer(GX2RBuffer* buffer)
{
uint32 bufferAlignment = GX2RGetBufferAlignment(buffer->resFlags);
uint32 bufferSize = GX2RGetBufferAllocationSize(buffer);
MPTR allocResult = PPCCoreCallback(GX2RAllocateFunc, (uint32)buffer->resFlags, bufferSize, bufferAlignment);
buffer->ptr = allocResult;
buffer->resFlags &= ~GX2R_RESFLAG_LOCKED;
buffer->resFlags |= GX2R_RESFLAG_ALLOCATED_BY_GX2R;
// todo: invalidation
return allocResult != MPTR_NULL;
}
bool GX2RCreateBufferUserMemory(GX2RBuffer* buffer, void* ptr, uint32 unusedSizeParameter)
{
buffer->ptr = ptr;
buffer->resFlags &= ~GX2R_RESFLAG_LOCKED;
buffer->resFlags &= ~GX2R_RESFLAG_ALLOCATED_BY_GX2R;
// todo: invalidation
return true;
}
void GX2RDestroyBufferEx(GX2RBuffer* buffer, uint32 resFlags)
{
if ((buffer->resFlags & GX2R_RESFLAG_ALLOCATED_BY_GX2R) == 0)
{
// this buffer is user-allocated
buffer->ptr = nullptr;
return;
}
PPCCoreCallback(GX2RFreeFunc, (uint32)buffer->resFlags, buffer->GetPtr());
buffer->ptr = nullptr;
}
bool GX2RBufferExists(GX2RBuffer* buffer)
{
if (!buffer)
return false;
if (!buffer->GetPtr())
return false;
return true;
}
void* GX2RLockBufferEx(GX2RBuffer* buffer, uint32 resFlags)
{
return buffer->GetPtr();
}
void GX2RUnlockBufferEx(GX2RBuffer* buffer, uint32 resFlags)
{
// todo - account for flags, not all buffer types need flushing
LatteBufferCache_notifyDCFlush(buffer->GetVirtualAddr(), buffer->GetSize());
}
void GX2RInvalidateBuffer(GX2RBuffer* buffer, uint32 resFlags)
{
// todo - account for flags, not all buffer types need flushing
LatteBufferCache_notifyDCFlush(buffer->GetVirtualAddr(), buffer->GetSize());
}
void GX2RSetAttributeBuffer(GX2RBuffer* buffer, uint32 bufferIndex, uint32 stride, uint32 offset)
{
uint32 bufferSize = buffer->GetSize();
if (offset > bufferSize)
cemuLog_log(LogType::Force, "GX2RSetAttributeBuffer(): Offset exceeds buffer size");
GX2SetAttribBuffer(bufferIndex, bufferSize - offset, stride, ((uint8be*)buffer->GetPtr()) + offset);
}
void GX2RSetStreamOutBuffer(uint32 bufferIndex, GX2StreamOutBuffer* soBuffer)
{
// seen in CoD: Ghosts and CoD: Black Ops 2
GX2SetStreamOutBuffer(bufferIndex, soBuffer);
}
bool GX2RCreateSurface(GX2Surface* surface, uint32 resFlags)
{
// seen in Transformers Prime
surface->resFlag = resFlags;
GX2CalcSurfaceSizeAndAlignment(surface);
surface->resFlag &= ~GX2R_RESFLAG_LOCKED;
surface->resFlag |= GX2R_RESFLAG_ALLOCATED_BY_GX2R;
MPTR allocResult = PPCCoreCallback(GX2RAllocateFunc, (uint32)surface->resFlag, (uint32)surface->imageSize + (uint32)surface->mipSize, (uint32)surface->alignment);
surface->imagePtr = allocResult;
if (surface->imagePtr != MPTR_NULL && surface->mipSize > 0)
{
surface->mipPtr = (uint32)surface->imagePtr + surface->imageSize;
}
else
{
surface->mipPtr = MPTR_NULL;
}
// todo: Cache invalidation based on resourceFlags?
return allocResult != MPTR_NULL;
}
bool GX2RCreateSurfaceUserMemory(GX2Surface* surface, void* imagePtr, void* mipPtr, uint32 resFlags)
{
surface->resFlag = resFlags;
surface->resFlag &= ~(GX2R_RESFLAG_LOCKED | GX2R_RESFLAG_ALLOCATED_BY_GX2R);
GX2CalcSurfaceSizeAndAlignment(surface);
surface->imagePtr = memory_getVirtualOffsetFromPointer(imagePtr);
surface->mipPtr = memory_getVirtualOffsetFromPointer(mipPtr);
if (surface->resFlag & 0x14000)
{
// memory invalidate
}
return true;
}
void GX2RDestroySurfaceEx(GX2Surface* surface, uint32 resFlags)
{
if ((surface->resFlag & GX2R_RESFLAG_ALLOCATED_BY_GX2R) == 0)
{
// this surface is user-allocated
surface->imagePtr = MPTR_NULL;
return;
}
resFlags &= (GX2R_RESFLAG_UKN_BIT_19 | GX2R_RESFLAG_UKN_BIT_20 | GX2R_RESFLAG_UKN_BIT_21 | GX2R_RESFLAG_UKN_BIT_22 | GX2R_RESFLAG_UKN_BIT_23);
PPCCoreCallback(GX2RFreeFunc, (uint32)surface->resFlag | resFlags, (uint32)surface->imagePtr);
surface->imagePtr = MPTR_NULL;
}
bool GX2RSurfaceExists(GX2Surface* surface)
{
if (!surface)
return false;
if (surface->imagePtr == MPTR_NULL)
return false;
if ((surface->resFlag & (GX2R_RESFLAG_USAGE_CPU_READ | GX2R_RESFLAG_USAGE_CPU_WRITE | GX2R_RESFLAG_USAGE_GPU_READ | GX2R_RESFLAG_USAGE_GPU_WRITE)) == 0)
return false;
return true;
}
void* GX2RLockSurfaceEx(GX2Surface* surface, uint32 mipLevel, uint32 resFlags)
{
// todo: handle invalidation
surface->resFlag |= GX2R_RESFLAG_LOCKED;
return memory_getPointerFromVirtualOffset(surface->imagePtr);
}
void GX2RUnlockSurfaceEx(GX2Surface* surface, uint32 mipLevel, uint32 resFlags)
{
// todo: handle invalidation
surface->resFlag &= ~GX2R_RESFLAG_LOCKED;
}
void GX2RBeginDisplayListEx(GX2RBuffer* buffer, bool ukn, uint32 resFlags)
{
// todo: handle invalidation
GX2::GX2BeginDisplayList(buffer->GetPtr(), buffer->GetSize());
}
uint32 GX2REndDisplayList(GX2RBuffer* buffer)
{
return GX2::GX2EndDisplayList(buffer->GetPtr());
}
void GX2RCallDisplayList(GX2RBuffer* buffer, uint32 size)
{
GX2::GX2CallDisplayList(buffer->GetVirtualAddr(), size);
}
void GX2RDirectCallDisplayList(GX2RBuffer* buffer, uint32 size)
{
GX2::GX2DirectCallDisplayList(buffer->GetPtr(), size);
}
void GX2RDrawIndexed(GX2PrimitiveMode2 primitiveMode, GX2RBuffer* indexBuffer, Latte::LATTE_VGT_DMA_INDEX_TYPE::E_INDEX_TYPE indexType, uint32 count, uint32 baseIndex, uint32 baseVertex, uint32 numInstances)
{
GX2DrawIndexedEx(primitiveMode, count, indexType, (uint8be*)indexBuffer->GetPtr() + (baseIndex * (uint32)indexBuffer->elementSize), baseVertex, numInstances);
}
void GX2ResourceInit()
{
cafeExportRegister("gx2", GX2RSetAllocator, LogType::GX2);
cafeExportRegister("gx2", GX2RGetBufferAllocationSize, LogType::GX2);
cafeExportRegister("gx2", GX2RGetBufferAlignment, LogType::GX2);
cafeExportRegister("gx2", GX2RCreateBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2RCreateBufferUserMemory, LogType::GX2);
cafeExportRegister("gx2", GX2RDestroyBufferEx, LogType::GX2);
cafeExportRegister("gx2", GX2RBufferExists, LogType::GX2);
cafeExportRegister("gx2", GX2RLockBufferEx, LogType::GX2);
cafeExportRegister("gx2", GX2RUnlockBufferEx, LogType::GX2);
cafeExportRegister("gx2", GX2RInvalidateBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2RSetAttributeBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2RSetStreamOutBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2RCreateSurface, LogType::GX2);
cafeExportRegister("gx2", GX2RCreateSurfaceUserMemory, LogType::GX2);
cafeExportRegister("gx2", GX2RDestroySurfaceEx, LogType::GX2);
cafeExportRegister("gx2", GX2RSurfaceExists, LogType::GX2);
cafeExportRegister("gx2", GX2RLockSurfaceEx, LogType::GX2);
cafeExportRegister("gx2", GX2RUnlockSurfaceEx, LogType::GX2);
cafeExportRegister("gx2", GX2RBeginDisplayListEx, LogType::GX2);
cafeExportRegister("gx2", GX2REndDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2RCallDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2RDirectCallDisplayList, LogType::GX2);
cafeExportRegister("gx2", GX2RDrawIndexed, LogType::GX2);
GX2RAllocateFunc = MPTR_NULL;
GX2RFreeFunc = MPTR_NULL;
}
};
| 8,397
|
C++
|
.cpp
| 219
| 35.52968
| 208
| 0.763413
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,060
|
GX2_AddrTest.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_AddrTest.cpp
|
#include "Cafe/OS/libs/coreinit/coreinit_DynLoad.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/LatteAddrLib/LatteAddrLib.h"
#include "util/highresolutiontimer/HighResolutionTimer.h"
namespace GX2
{
struct AddrCreate_INPUT
{
/* +0x00 */ uint32be structSize;
/* +0x04 */ uint32be ukn04_maybeGen;
/* +0x08 */ uint32be ukn08;
/* +0x0C */ uint32be revision;
/* +0x10 */ uint32be func_Alloc;
/* +0x14 */ uint32be func_Free;
/* +0x18 */ uint32be func_Debug;
/* +0x1C */ uint32be ukn1C;
/* +0x20 */ uint32be reg263C;
/* +0x24 */ uint32be ukn24;
/* +0x28 */ uint32be ukn28;
/* +0x2C */ uint32be ukn2C;
/* +0x30 */ uint32be ukn30;
/* +0x34 */ uint32be ukn34;
/* +0x38 */ uint32be ukn38;
/* +0x3C */ uint32be ukn3C;
/* +0x40 */ uint32be ukn40;
};
struct AddrCreate_OUTPUT
{
uint32be structSize;
MEMPTR<void> addrLibPtr;
};
static_assert(sizeof(AddrCreate_INPUT) == 0x44);
static_assert(sizeof(AddrCreate_OUTPUT) == 8);
struct ADDRAllocParam
{
uint32be ukn00; // alignment?
uint32be ukn04;
uint32be size;
};
struct ADDRComputeSurfaceInfo_INPUT
{
uint32be structSize;
betype<Latte::E_HWTILEMODE> tileMode;
betype<Latte::E_HWSURFFMT> format;
uint32be bpp;
uint32be numSamples;
uint32be width;
uint32be height;
uint32be numSlices;
uint32be slice;
uint32be mipLevel;
uint32be _flags;
uint32be numFrags;
MEMPTR<void> tileInfo;
uint32be tileType;
uint32be tileIndex;
enum FLAG_BITS
{
FLAG_BIT_CUBE = (1 << 27),
FLAG_BIT_VOLUME = (1 << 26),
FLAG_BIT_OPT4SPACE = (1 << 19),
};
void SetFlagCube(bool f)
{
if (f) _flags |= FLAG_BIT_CUBE;
else _flags &= ~FLAG_BIT_CUBE;
}
void SetFlagVolume(bool f)
{
if (f) _flags |= FLAG_BIT_VOLUME;
else _flags &= ~FLAG_BIT_VOLUME;
}
void SetFlagOpt4Space(bool f)
{
if (f) _flags |= FLAG_BIT_OPT4SPACE;
else _flags &= ~FLAG_BIT_OPT4SPACE;
}
};
static_assert(sizeof(ADDRComputeSurfaceInfo_INPUT) == 0x3C);
struct ADDRComputeSurfaceInfo_OUTPUT
{
/* 0x00 */ uint32be structSize;
/* 0x04 */ uint32be pitch;
/* 0x08 */ uint32be height;
/* 0x0C */ uint32be depth;
/* 0x10 */ uint64be surfSize;
/* 0x18 */ uint32be tileMode;
/* 0x1C */ uint32be baseAlign;
/* 0x20 */ uint32be pitchAlign;
/* 0x24 */ uint32be heightAlign;
/* 0x28 */ uint32be depthAlign;
/* 0x2C */ uint32be bpp;
/* 0x30 */ uint32be pixelPitch;
/* 0x34 */ uint32be pixelHeight;
/* 0x38 */ uint32be pixelBits;
/* 0x3C */ uint32be sliceSize;
/* 0x40 */ uint32be pitchTileMax;
/* 0x44 */ uint32be heightTileMax;
/* 0x48 */ uint32be sliceTileMax;
/* 0x4C */ MEMPTR<void> tileInfo;
/* 0x50 */ uint32be tileType;
/* 0x54 */ uint32be tileIndex;
/* 0x58 */ MEMPTR<void> stereoInfo;
/* 0x5C */ uint32be _padding;
};
static_assert(sizeof(ADDRComputeSurfaceInfo_OUTPUT) == 0x60);
static void _cb_alloc(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(param, ADDRAllocParam, 0);
uint32 r = coreinit_allocFromSysArea(param->size, 0x10);
osLib_returnFromFunction(hCPU, r);
}
static void _cb_free(PPCInterpreter_t* hCPU)
{
cemu_assert_unimplemented();
}
static void _cb_debug(PPCInterpreter_t* hCPU)
{
cemu_assert_unimplemented();
}
static void* sAddrLib{};
static uint32be tclFunc_AddrCreate = 0;
static uint32be tclFunc_AddrComputeSurfaceInfo = 0;
void _TestAddrLib_Init()
{
// load tcl_addr_test.rpl (from /cafelibs/)
uint32be tclHandle;
uint32 r = coreinit::OSDynLoad_Acquire("tcl_addr_test.rpl", &tclHandle);
cemu_assert_debug(r == 0);
// get imports
r = coreinit::OSDynLoad_FindExport(tclHandle, 0, "AddrCreate", &tclFunc_AddrCreate);
cemu_assert_debug(r == 0);
r = coreinit::OSDynLoad_FindExport(tclHandle, 0, "AddrComputeSurfaceInfo", &tclFunc_AddrComputeSurfaceInfo);
cemu_assert_debug(r == 0);
// call AddrCreate
StackAllocator<AddrCreate_INPUT> addrCreateIn;
memset(addrCreateIn.GetPointer(), 0, sizeof(addrCreateIn));
addrCreateIn->structSize = sizeof(addrCreateIn);
addrCreateIn->ukn04_maybeGen = 6; // R600?
addrCreateIn->ukn08 = 0x51;
addrCreateIn->revision = 71;
addrCreateIn->reg263C = 0x44902;
addrCreateIn->ukn24 = 0; // ukn
addrCreateIn->func_Alloc = PPCInterpreter_makeCallableExportDepr(_cb_alloc);
addrCreateIn->func_Free = PPCInterpreter_makeCallableExportDepr(_cb_free);
addrCreateIn->func_Debug = PPCInterpreter_makeCallableExportDepr(_cb_debug);
StackAllocator<AddrCreate_OUTPUT> addrCreateOut;
memset(addrCreateOut.GetPointer(), 0, sizeof(addrCreateOut));
addrCreateOut->structSize = sizeof(addrCreateOut);
r = PPCCoreCallback((uint32)tclFunc_AddrCreate, addrCreateIn.GetPointer(), addrCreateOut.GetPointer());
sAddrLib = addrCreateOut->addrLibPtr;
cemu_assert_debug(r == 0 && sAddrLib != nullptr);
}
void _TestAddrLib_CalculateSurfaceInfo(Latte::E_GX2SURFFMT surfaceFormat, uint32 surfaceWidth, uint32 surfaceHeight, uint32 surfaceDepth, Latte::E_DIM surfaceDim, Latte::E_GX2TILEMODE surfaceTileMode, uint32 surfaceAA, uint32 level, ADDRComputeSurfaceInfo_OUTPUT* paramOut)
{
StackAllocator<ADDRComputeSurfaceInfo_INPUT> _paramIn;
ADDRComputeSurfaceInfo_INPUT& paramIn = *_paramIn.GetPointer();
memset(¶mIn, 0, sizeof(ADDRComputeSurfaceInfo_INPUT));
memset(paramOut, 0, sizeof(ADDRComputeSurfaceInfo_OUTPUT));
Latte::E_HWSURFFMT hwFormat = GetHWFormat(surfaceFormat);
if (surfaceTileMode == Latte::E_GX2TILEMODE::TM_LINEAR_SPECIAL)
{
uint32 numSamples = 1 << surfaceAA;
uint32 blockSize = IsCompressedFormat(surfaceFormat) ? 4 : 1;
uint32 width = ((surfaceWidth >> level) + blockSize - 1) & ~(blockSize - 1);
paramOut->bpp = GetFormatBits(hwFormat);
paramOut->structSize = sizeof(ADDRComputeSurfaceInfo_OUTPUT);
paramOut->pitch = width / blockSize;
paramOut->pixelBits = paramOut->bpp;
paramOut->baseAlign = 1;
paramOut->pitchAlign = 1;
paramOut->heightAlign = 1;
paramOut->depthAlign = 1;
switch (surfaceDim)
{
case Latte::E_DIM::DIM_1D:
paramOut->height = 1;
paramOut->depth = 1;
break;
case Latte::E_DIM::DIM_2D:
paramOut->height = std::max<uint32>(surfaceHeight >> level, 1);
paramOut->depth = 1;
break;
case Latte::E_DIM::DIM_3D:
paramOut->height = surfaceHeight >> level;
paramOut->height = std::max<uint32>(paramOut->height, 1);
paramOut->depth = std::max<uint32>(surfaceDepth >> level, 1);
break;
case Latte::E_DIM::DIM_CUBEMAP:
paramOut->height = std::max<uint32>(surfaceHeight >> level, 1);
paramOut->depth = std::max<uint32>(surfaceDepth, 6);
break;
case Latte::E_DIM::DIM_1D_ARRAY:
paramOut->height = 1;
paramOut->depth = surfaceDepth;
break;
case Latte::E_DIM::DIM_2D_ARRAY:
paramOut->height = std::max<uint32>(surfaceHeight >> level, 1);
paramOut->depth = surfaceDepth;
break;
default:
break;
}
paramOut->height = ((paramOut->height + blockSize - 1) & ~(blockSize - 1)) / (uint64)blockSize;
paramOut->pixelPitch = ((surfaceWidth >> level) + blockSize - 1) & ~(blockSize - 1);
paramOut->pixelPitch = std::max<uint32>(paramOut->pixelPitch, blockSize);
paramOut->pixelHeight = ((surfaceHeight >> level) + blockSize - 1) & ~(blockSize - 1);
paramOut->pixelHeight = std::max<uint32>(paramOut->pixelHeight, blockSize);;
paramOut->pitch = std::max<uint32>(paramOut->pitch, 1);
paramOut->height = std::max<uint32>(paramOut->height, 1);
paramOut->surfSize = paramOut->bpp * numSamples * paramOut->depth * paramOut->height * paramOut->pitch >> 3;
if (surfaceDim == Latte::E_DIM::DIM_3D)
paramOut->sliceSize = (uint32)(paramOut->surfSize);
else
{
if (paramOut->surfSize == 0 && paramOut->depth == 0)
paramOut->sliceSize = 0; // edge case for (1D)_ARRAY textures with 0/0/0 res
else
paramOut->sliceSize = ((uint32)paramOut->surfSize.value() / paramOut->depth);
}
paramOut->pitchTileMax = (paramOut->pitch >> 3) - 1;
paramOut->heightTileMax = (paramOut->height >> 3) - 1;
paramOut->sliceTileMax = (paramOut->height * paramOut->pitch >> 6) - 1;
}
else
{
paramIn.structSize = sizeof(paramIn);
paramIn.tileMode = Latte::MakeHWTileMode(surfaceTileMode);
paramIn.format = hwFormat;
paramIn.bpp = GetFormatBits(hwFormat);
paramIn.numSamples = 1 << surfaceAA;
paramIn.numFrags = paramIn.numSamples;
paramIn.width = std::max<uint32>(surfaceWidth >> level, 1);
switch (surfaceDim)
{
case Latte::E_DIM::DIM_1D:
paramIn.height = 1;
paramIn.numSlices = 1;
break;
case Latte::E_DIM::DIM_2D:
paramIn.height = std::max<uint32>(surfaceHeight >> level, 1);
paramIn.numSlices = 1;
break;
case Latte::E_DIM::DIM_3D:
paramIn.height = std::max<uint32>(surfaceHeight >> level, 1);
paramIn.numSlices = std::max<uint32>(surfaceDepth >> level, 1);
break;
case Latte::E_DIM::DIM_CUBEMAP:
paramIn.height = std::max<uint32>(surfaceHeight >> level, 1);
paramIn.numSlices = std::max<uint32>(surfaceDepth, 6);
paramIn.SetFlagCube(true);
break;
case Latte::E_DIM::DIM_1D_ARRAY:
paramIn.height = 1;
paramIn.numSlices = surfaceDepth;
break;
case Latte::E_DIM::DIM_2D_ARRAY:
paramIn.height = std::max<uint32>(surfaceHeight >> level, 1);
paramIn.numSlices = surfaceDepth;
break;
case Latte::E_DIM::DIM_2D_MSAA:
paramIn.height = std::max<uint32>(surfaceHeight >> level, 1);
paramIn.numSlices = 1;
break;
case Latte::E_DIM::DIM_2D_ARRAY_MSAA:
paramIn.height = std::max<uint32>(surfaceHeight >> level, 1);
paramIn.numSlices = surfaceDepth;
break;
default:
break;
}
paramIn.slice = 0;
paramIn.mipLevel = level;
if (surfaceDim == Latte::E_DIM::DIM_3D)
paramIn.SetFlagVolume(true);
paramIn.SetFlagOpt4Space(level == 0);
paramOut->structSize = sizeof(ADDRComputeSurfaceInfo_OUTPUT);
PPCCoreCallback((uint32)tclFunc_AddrComputeSurfaceInfo, sAddrLib, _paramIn.GetPointer(), paramOut);
}
}
void _TestAddrLib_Compare(uint32 surfaceWidth, uint32 surfaceHeight, uint32 surfaceDepth, Latte::E_DIM surfaceDim, Latte::E_GX2SURFFMT surfaceFormat, Latte::E_GX2TILEMODE surfaceTileMode, uint32 surfaceAA, uint32 level)
{
// get result from tcl.rpl
StackAllocator<ADDRComputeSurfaceInfo_OUTPUT> _paramOut;
ADDRComputeSurfaceInfo_OUTPUT& tclSurfInfo = *_paramOut.GetPointer();
_TestAddrLib_CalculateSurfaceInfo(surfaceFormat, surfaceWidth, surfaceHeight, surfaceDepth, surfaceDim, surfaceTileMode, surfaceAA, level, _paramOut.GetPointer());
// get result from our implementation
LatteAddrLib::AddrSurfaceInfo_OUT ourSurfInfo;
LatteAddrLib::GX2CalculateSurfaceInfo(surfaceFormat, surfaceWidth, surfaceHeight, surfaceDepth, surfaceDim, surfaceTileMode, surfaceAA, level, &ourSurfInfo);
// compare
cemu_assert(tclSurfInfo.pitchAlign == ourSurfInfo.pitchAlign);
cemu_assert((Latte::E_HWTILEMODE)tclSurfInfo.tileMode.value() == ourSurfInfo.hwTileMode);
cemu_assert(tclSurfInfo.baseAlign == ourSurfInfo.baseAlign);
cemu_assert(tclSurfInfo.surfSize == ourSurfInfo.surfSize);
cemu_assert(tclSurfInfo.depthAlign == ourSurfInfo.depthAlign);
cemu_assert(tclSurfInfo.pitch == ourSurfInfo.pitch);
cemu_assert(tclSurfInfo.sliceSize == ourSurfInfo.sliceSize);
}
void _TestAddrLib_Run()
{
uint32 surfaceAA = 0;
std::vector<Latte::E_DIM> dimList = {
Latte::E_DIM::DIM_1D,
Latte::E_DIM::DIM_2D,
Latte::E_DIM::DIM_3D,
Latte::E_DIM::DIM_CUBEMAP,
Latte::E_DIM::DIM_1D_ARRAY,
Latte::E_DIM::DIM_2D_ARRAY,
Latte::E_DIM::DIM_2D_MSAA,
Latte::E_DIM::DIM_2D_ARRAY_MSAA
};
std::vector<Latte::E_GX2TILEMODE> tilemodeList = {
// linear
Latte::E_GX2TILEMODE::TM_LINEAR_GENERAL,
Latte::E_GX2TILEMODE::TM_LINEAR_ALIGNED,
// micro tiled
Latte::E_GX2TILEMODE::TM_1D_TILED_THIN1,
Latte::E_GX2TILEMODE::TM_1D_TILED_THICK,
// macro tiled
Latte::E_GX2TILEMODE::TM_2D_TILED_THIN1,
Latte::E_GX2TILEMODE::TM_2D_TILED_THIN4,
Latte::E_GX2TILEMODE::TM_2D_TILED_THIN2,
Latte::E_GX2TILEMODE::TM_2D_TILED_THICK,
Latte::E_GX2TILEMODE::TM_2B_TILED_THIN1,
Latte::E_GX2TILEMODE::TM_2B_TILED_THIN2,
Latte::E_GX2TILEMODE::TM_2B_TILED_THIN4,
Latte::E_GX2TILEMODE::TM_2B_TILED_THICK,
Latte::E_GX2TILEMODE::TM_3D_TILED_THIN1,
Latte::E_GX2TILEMODE::TM_3D_TILED_THICK,
Latte::E_GX2TILEMODE::TM_3B_TILED_THIN1,
Latte::E_GX2TILEMODE::TM_3B_TILED_THICK,
// special
Latte::E_GX2TILEMODE::TM_LINEAR_SPECIAL,
Latte::E_GX2TILEMODE::TM_32_SPECIAL, // note: Specific to GX2CalcSurfaceSizeAndAlignment, for AddrLib this should just be interpreted as (tm&0xF)
};
std::vector<Latte::E_GX2SURFFMT> formatList = {
Latte::E_GX2SURFFMT::HWFMT_8, Latte::E_GX2SURFFMT::HWFMT_8_8, Latte::E_GX2SURFFMT::HWFMT_8_8_8_8, // 8, 16, 32
Latte::E_GX2SURFFMT::R32_UINT, Latte::E_GX2SURFFMT::R32_G32_UINT, Latte::E_GX2SURFFMT::R32_G32_B32_A32_UINT, // 32, 64, 128
Latte::E_GX2SURFFMT::HWFMT_BC1, Latte::E_GX2SURFFMT::HWFMT_BC2, Latte::E_GX2SURFFMT::HWFMT_BC3, Latte::E_GX2SURFFMT::HWFMT_BC4, Latte::E_GX2SURFFMT::HWFMT_BC5
};
std::vector<uint32> resXYList = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17,
31, 32, 33, 50, 63, 64, 65, 127, 128, 129, 200, 253, 254, 255, 256, 257,
511, 512, 513, 1023, 1024, 1025, 2047, 2048, 2049, 4095, 4096, 4097
};
debug_printf("Running AddrLib test...\n");
BenchmarkTimer timer;
timer.Start();
size_t index = 0;
for (auto dim : dimList)
{
debug_printf("%d/%d\n", (int)index, (int)dimList.size());
index++;
for (auto tileMode : tilemodeList)
{
for (auto format : formatList)
{
for (uint32 level = 0; level < 16; level++)
{
for (auto depth : resXYList)
{
for (auto height : resXYList)
{
for (auto width : resXYList)
{
_TestAddrLib_Compare(width, height, depth, dim, format, tileMode, surfaceAA, level);
}
}
}
}
}
}
}
timer.Stop();
debug_printf("Test complete (in %d seconds)\n", (int)(timer.GetElapsedMilliseconds() * 0.001));
assert_dbg();
}
void _test_AddrLib()
{
return;
_TestAddrLib_Init();
_TestAddrLib_Run();
}
}
| 14,318
|
C++
|
.cpp
| 388
| 33.244845
| 274
| 0.70344
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,061
|
GX2_Memory.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Memory.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "GX2.h"
#include "GX2_Resource.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
// default GX2 allocator (not the same as the GX2R allocator, but GX2R uses this allocator by default)
MPTR gx2Mem_defaultAlloc = MPTR_NULL;
MPTR gx2Mem_defaultFree = MPTR_NULL;
void gx2Memory_GX2SetDefaultAllocator(MPTR defaultAllocFunc, MPTR defaulFreeFunc)
{
gx2Mem_defaultAlloc = defaultAllocFunc;
gx2Mem_defaultFree = defaulFreeFunc;
}
void _GX2DefaultAlloc_Alloc(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 uint32 userParam
// r4 uint32 size
// r5 sint32 alignment
hCPU->gpr[3] = hCPU->gpr[4];
hCPU->gpr[4] = hCPU->gpr[5];
hCPU->instructionPointer = gCoreinitData->MEMAllocFromDefaultHeapEx.GetMPTR();
}
void _GX2DefaultAlloc_Free(PPCInterpreter_t* hCPU)
{
hCPU->gpr[3] = hCPU->gpr[4];
hCPU->instructionPointer = gCoreinitData->MEMFreeToDefaultHeap.GetMPTR();
}
void gx2Export_GX2SetDefaultAllocator(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetDefaultAllocator(0x{:08x}, 0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
gx2Mem_defaultAlloc = hCPU->gpr[3];
gx2Mem_defaultFree = hCPU->gpr[4];
osLib_returnFromFunction(hCPU, 0);
}
void _GX2DefaultAllocR_Alloc(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2DefaultAllocate(0x{:08x}, 0x{:08x}, 0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
// parameters:
// r3 uint32 userParam
// r4 uint32 size
// r5 sint32 alignment
hCPU->instructionPointer = gx2Mem_defaultAlloc;
}
void _GX2DefaultAllocR_Free(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2DefaultFree(0x{:08x}, 0x{:08x})", hCPU->gpr[3], hCPU->gpr[4]);
// parameters:
// r3 uint32 userParam
// r4 void* mem
hCPU->instructionPointer = gx2Mem_defaultFree;
}
namespace GX2
{
void GX2MEMAllocatorsInit()
{
// set default allocators (can be overwritten by GX2SetDefaultAllocator)
gx2Mem_defaultAlloc = PPCInterpreter_makeCallableExportDepr(_GX2DefaultAlloc_Alloc);
gx2Mem_defaultFree = PPCInterpreter_makeCallableExportDepr(_GX2DefaultAlloc_Free);
// set resource default allocator
GX2::GX2RSetAllocator(PPCInterpreter_makeCallableExportDepr(_GX2DefaultAllocR_Alloc), PPCInterpreter_makeCallableExportDepr(_GX2DefaultAllocR_Free));
}
void GX2MemInit()
{
osLib_addFunction("gx2", "GX2SetDefaultAllocator", gx2Export_GX2SetDefaultAllocator);
}
};
| 2,440
|
C++
|
.cpp
| 68
| 34.102941
| 151
| 0.773593
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,062
|
GX2.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "GX2_Command.h"
#include "GX2_State.h"
#include "GX2_Memory.h"
#include "GX2_Event.h"
#include "GX2_Shader.h"
#include "GX2_Blit.h"
#include "GX2_Draw.h"
#include "GX2_Query.h"
#include "GX2_Misc.h"
#include "GX2_Surface.h"
#include "GX2_Surface_Copy.h"
#include "GX2_Texture.h"
#include <cinttypes>
#define GX2_TV_RENDER_NONE 0
#define GX2_TV_RENDER_480 1
#define GX2_TV_RENDER_480_WIDE 2
#define GX2_TV_RENDER_720 3
#define GX2_TV_RENDER_720I 4
#define GX2_TV_RENDER_1080 5
#define GX2_TV_RENDER_COUNT 6
struct
{
sint32 width;
sint32 height;
}tvScanBufferResolutions[GX2_TV_RENDER_COUNT] = {
0,0,
640,480,
854,480,
1280,720,
1280,720,
1920,1080
};
uint64 lastSwapTime = 0;
void gx2Export_GX2SwapScanBuffers(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SwapScanBuffers()");
bool isPokken = false;
uint64 titleId = CafeSystem::GetForegroundTitleId();
if (titleId == 0x00050000101DF500ull || titleId == 0x00050000101C5800ull || titleId == 0x00050000101DF400ull)
isPokken = true;
if (isPokken)
GX2::GX2DrawDone();
GX2ReserveCmdSpace(5+2);
uint64 tick64 = PPCInterpreter_getMainCoreCycleCounter() / 20ULL;
lastSwapTime = tick64;
// count flip request
// is this updated via a PM4 MEM_WRITE operation?
// Orochi Warriors seems to call GX2SwapScanBuffers on arbitrary threads/cores. The PM4 commands should go through to the GPU as long as there is no active display list and no other core is submitting commands simultaneously
// right now, we work around this by avoiding the infinite loop below (request counter incremented, but PM4 not sent)
uint32 coreIndex = coreinit::OSGetCoreId();
if (GX2::sGX2MainCoreIndex == coreIndex)
LatteGPUState.sharedArea->flipRequestCountBE = _swapEndianU32(_swapEndianU32(LatteGPUState.sharedArea->flipRequestCountBE) + 1);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_REQUEST_SWAP_BUFFERS, 1));
gx2WriteGather_submitU32AsBE(0); // reserved
// swap frames
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_TRIGGER_SCANBUFFER_SWAP, 1));
gx2WriteGather_submitU32AsBE(0); // reserved
// wait for flip if the CPU is too far ahead
// doing it after swap request is how the actual console does it, but that still causes issues in Pokken
while ((sint32)(_swapEndianU32(LatteGPUState.sharedArea->flipRequestCountBE) - _swapEndianU32(LatteGPUState.sharedArea->flipExecuteCountBE)) > 5)
{
GX2::GX2WaitForFlip();
}
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2CopyColorBufferToScanBuffer(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2CopyColorBufferToScanBuffer(0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4]);
GX2ReserveCmdSpace(5);
// todo: proper implementation
// hack: Avoid running to far ahead of GPU. Normally this would be guaranteed by the circular buffer model, which we currently dont fully emulate
if(GX2::GX2WriteGather_getReadWriteDistance() > 32*1024*1024 )
{
debug_printf("Waiting for GPU to catch up...\n");
PPCInterpreter_relinquishTimeslice(); // release current thread
return;
}
GX2ColorBuffer* colorBuffer = (GX2ColorBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_COPY_COLORBUFFER_TO_SCANBUFFER, 9));
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(colorBuffer->surface.imagePtr));
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.width);
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.height);
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.pitch);
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.tileMode.value());
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.swizzle);
gx2WriteGather_submitU32AsBE(_swapEndianU32(colorBuffer->viewFirstSlice));
gx2WriteGather_submitU32AsBE((uint32)colorBuffer->surface.format.value());
gx2WriteGather_submitU32AsBE(hCPU->gpr[4]);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2WaitForFreeScanBuffer(PPCInterpreter_t* hCPU)
{
// todo: proper implementation
debug_printf("GX2WaitForFreeScanBuffer(): Unimplemented\n");
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2GetCurrentScanBuffer(PPCInterpreter_t* hCPU)
{
// todo: proper implementation
uint32 scanTarget = hCPU->gpr[3];
GX2ColorBuffer* colorBufferBE = (GX2ColorBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
memset(colorBufferBE, 0x00, sizeof(GX2ColorBuffer));
colorBufferBE->surface.width = 100;
colorBufferBE->surface.height = 100;
// note: For now we abuse the tiling aperture memory area as framebuffer pointers
if( scanTarget == GX2_SCAN_TARGET_TV )
{
colorBufferBE->surface.imagePtr = MEMORY_TILINGAPERTURE_AREA_ADDR+0x200000;
}
else if( scanTarget == GX2_SCAN_TARGET_DRC_FIRST )
{
colorBufferBE->surface.imagePtr = MEMORY_TILINGAPERTURE_AREA_ADDR+0x40000;
}
osLib_returnFromFunction(hCPU, 0);
}
void coreinitExport_GX2GetSystemTVScanMode(PPCInterpreter_t* hCPU)
{
// 1080p = 7
osLib_returnFromFunction(hCPU, 7);
}
void coreinitExport_GX2GetSystemTVAspectRatio(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction(hCPU, 1); // 16:9
}
void gx2Export_GX2TempGetGPUVersion(PPCInterpreter_t* hCPU)
{
osLib_returnFromFunction(hCPU, 2);
}
void _GX2InitScanBuffer(GX2ColorBuffer* colorBuffer, sint32 width, sint32 height, Latte::E_GX2SURFFMT format)
{
colorBuffer->surface.resFlag = GX2_RESFLAG_USAGE_TEXTURE | GX2_RESFLAG_USAGE_COLOR_BUFFER;
colorBuffer->surface.width = width;
colorBuffer->surface.height = height;
colorBuffer->viewFirstSlice = _swapEndianU32(0);
colorBuffer->viewNumSlices = _swapEndianU32(1);
colorBuffer->viewMip = _swapEndianU32(0);
colorBuffer->surface.numLevels = 1;
colorBuffer->surface.dim = Latte::E_DIM::DIM_2D;
colorBuffer->surface.swizzle = 0;
colorBuffer->surface.depth = 1;
colorBuffer->surface.tileMode = Latte::E_GX2TILEMODE::TM_LINEAR_GENERAL;
colorBuffer->surface.format = format;
colorBuffer->surface.mipPtr = MPTR_NULL;
colorBuffer->surface.aa = 0;
GX2::GX2CalcSurfaceSizeAndAlignment(&colorBuffer->surface);
colorBuffer->surface.resFlag = GX2_RESFLAG_USAGE_TEXTURE | GX2_RESFLAG_USAGE_COLOR_BUFFER | GX2_RESFLAG_USAGE_SCAN_BUFFER;
}
void gx2Export_GX2CalcTVSize(PPCInterpreter_t* hCPU)
{
uint32 tvRenderMode = hCPU->gpr[3];
Latte::E_GX2SURFFMT format = (Latte::E_GX2SURFFMT)hCPU->gpr[4];
uint32 bufferingMode = hCPU->gpr[5];
uint32 outputSizeMPTR = hCPU->gpr[6];
uint32 outputScaleNeededMPTR = hCPU->gpr[7];
cemu_assert(tvRenderMode < GX2_TV_RENDER_COUNT);
uint32 width = tvScanBufferResolutions[tvRenderMode].width;
uint32 height = tvScanBufferResolutions[tvRenderMode].height;
GX2ColorBuffer colorBuffer;
memset(&colorBuffer, 0, sizeof(GX2ColorBuffer));
_GX2InitScanBuffer(&colorBuffer, width, height, format);
uint32 imageSize = colorBuffer.surface.imageSize;
uint32 alignment = colorBuffer.surface.alignment;
uint32 alignmentPaddingSize = (alignment - (imageSize%alignment)) % alignment;
uint32 uknMult = 1; // probably for interlaced?
if (tvRenderMode == GX2_TV_RENDER_720I)
uknMult = 2;
uint32 adjustedBufferingMode = bufferingMode;
if (tvRenderMode < GX2_TV_RENDER_720)
adjustedBufferingMode = 4;
uint32 bufferedImageSize = (imageSize + alignmentPaddingSize) * adjustedBufferingMode;
bufferedImageSize = bufferedImageSize * uknMult - alignmentPaddingSize;
memory_writeU32(outputSizeMPTR, bufferedImageSize);
memory_writeU32(outputScaleNeededMPTR, 0); // todo
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2CalcDRCSize(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(drcMode, 0);
ppcDefineParamU32(format, 1);
ppcDefineParamU32(bufferingMode, 2);
ppcDefineParamMPTR(sizeMPTR, 3);
ppcDefineParamMPTR(scaleNeededMPTR, 4);
uint32 width = 0;
uint32 height = 0;
if (drcMode > 0)
{
width = 854;
height = 480;
}
GX2ColorBuffer colorBuffer = {};
memset(&colorBuffer, 0, sizeof(colorBuffer));
_GX2InitScanBuffer(&colorBuffer, width, height, (Latte::E_GX2SURFFMT)format);
uint32 imageSize = colorBuffer.surface.imageSize;
uint32 alignment = colorBuffer.surface.alignment;
uint32 alignmentPaddingSize = (alignment - (imageSize%alignment)) % alignment;
uint32 adjustedBufferingMode = bufferingMode;
uint32 bufferedImageSize = (imageSize + alignmentPaddingSize) * adjustedBufferingMode;
bufferedImageSize = bufferedImageSize - alignmentPaddingSize;
memory_writeU32(sizeMPTR, bufferedImageSize);
memory_writeU32(scaleNeededMPTR, 0);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetDRCScale(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetDRCScale({},{})", hCPU->gpr[3], hCPU->gpr[4]);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetDRCConnectCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(channel, 0);
ppcDefineParamMEMPTR(callback, void, 1);
cemuLog_log(LogType::GX2, "GX2SetDRCConnectCallback({}, 0x{:08x})", channel, callback.GetMPTR());
if(callback.GetPtr())
PPCCoreCallback(callback, channel, TRUE);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetSemaphore(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetSemaphore(0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamMPTR(semaphoreMPTR, 0);
ppcDefineParamS32(mode, 1);
uint32 SEM_SEL;
if (mode == 0)
{
// wait
SEM_SEL = 7;
}
else if (mode == 1)
{
// signal
SEM_SEL = 6;
}
else
{
cemu_assert_debug(false);
osLib_returnFromFunction(hCPU, 0);
return;
}
uint32 semaphoreControl = (SEM_SEL << 29);
semaphoreControl |= 0x1000; // WAIT_ON_SIGNAL
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_MEM_SEMAPHORE, 2));
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(semaphoreMPTR)); // semaphore physical address
gx2WriteGather_submitU32AsBE(semaphoreControl); // control
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2Flush(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2Flush()");
_GX2SubmitToTCL();
osLib_returnFromFunction(hCPU, 0);
}
uint8* _GX2LastFlushPtr[PPC_CORE_COUNT] = {NULL};
uint64 _prevReturnedGPUTime = 0;
uint64 Latte_GetTime()
{
uint64 gpuTime = coreinit::coreinit_getTimerTick();
gpuTime *= 20000ULL;
if (gpuTime <= _prevReturnedGPUTime)
gpuTime = _prevReturnedGPUTime + 1; // avoid ever returning identical timestamps
_prevReturnedGPUTime = gpuTime;
return gpuTime;
}
void _GX2SubmitToTCL()
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(PPCInterpreter_getCurrentInstance());
// do nothing if called from non-main GX2 core
if (GX2::sGX2MainCoreIndex != coreIndex)
{
cemuLog_logDebug(LogType::Force, "_GX2SubmitToTCL() called on non-main GX2 core");
return;
}
if( gx2WriteGatherPipe.displayListStart[coreIndex] != MPTR_NULL )
return; // quit if in display list
_GX2LastFlushPtr[coreIndex] = (gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex]);
// update last submitted CB timestamp
uint64 commandBufferTimestamp = Latte_GetTime();
LatteGPUState.lastSubmittedCommandBufferTimestamp.store(commandBufferTimestamp);
cemuLog_log(LogType::GX2, "Submitting GX2 command buffer with timestamp {:016x}", commandBufferTimestamp);
// submit HLE packet to write retirement timestamp
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_SET_CB_RETIREMENT_TIMESTAMP, 2));
gx2WriteGather_submitU32AsBE((uint32)(commandBufferTimestamp>>32ULL));
gx2WriteGather_submitU32AsBE((uint32)(commandBufferTimestamp&0xFFFFFFFFULL));
}
uint32 _GX2GetUnflushedBytes(uint32 coreIndex)
{
uint32 unflushedBytes = 0;
if (_GX2LastFlushPtr[coreIndex] != NULL)
{
if (_GX2LastFlushPtr[coreIndex] > gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex])
unflushedBytes = (uint32)(gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] - gx2WriteGatherPipe.gxRingBuffer + 4); // this isn't 100% correct since we ignore the bytes between the last flush address and the start of the wrap around
else
unflushedBytes = (uint32)(gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] - _GX2LastFlushPtr[coreIndex]);
}
else
unflushedBytes = (uint32)(gx2WriteGatherPipe.writeGatherPtrGxBuffer[coreIndex] - gx2WriteGatherPipe.gxRingBuffer);
return unflushedBytes;
}
/*
* Guarantees that the requested amount of space is available on the current command buffer
* If the space is not available, the current command buffer is pushed to the GPU and a new one is allocated
*/
void GX2ReserveCmdSpace(uint32 reservedFreeSpaceInU32)
{
uint32 coreIndex = coreinit::OSGetCoreId();
// if we are in a display list then do nothing
if( gx2WriteGatherPipe.displayListStart[coreIndex] != MPTR_NULL )
return;
uint32 unflushedBytes = _GX2GetUnflushedBytes(coreIndex);
if( unflushedBytes >= 0x1000 )
{
_GX2SubmitToTCL();
}
}
void gx2_load()
{
osLib_addFunction("gx2", "GX2GetContextStateDisplayList", gx2Export_GX2GetContextStateDisplayList);
// swap, vsync & timing
osLib_addFunction("gx2", "GX2SwapScanBuffers", gx2Export_GX2SwapScanBuffers);
osLib_addFunction("gx2", "GX2GetSwapStatus", gx2Export_GX2GetSwapStatus);
osLib_addFunction("gx2", "GX2CopyColorBufferToScanBuffer", gx2Export_GX2CopyColorBufferToScanBuffer);
osLib_addFunction("gx2", "GX2WaitForFreeScanBuffer", gx2Export_GX2WaitForFreeScanBuffer);
osLib_addFunction("gx2", "GX2GetCurrentScanBuffer", gx2Export_GX2GetCurrentScanBuffer);
// shader stuff
osLib_addFunction("gx2", "GX2SetPixelShader", gx2Export_GX2SetPixelShader);
osLib_addFunction("gx2", "GX2SetGeometryShader", gx2Export_GX2SetGeometryShader);
osLib_addFunction("gx2", "GX2SetComputeShader", gx2Export_GX2SetComputeShader);
osLib_addFunction("gx2", "GX2SetVertexUniformBlock", gx2Export_GX2SetVertexUniformBlock);
osLib_addFunction("gx2", "GX2RSetVertexUniformBlock", gx2Export_GX2RSetVertexUniformBlock);
osLib_addFunction("gx2", "GX2SetPixelUniformBlock", gx2Export_GX2SetPixelUniformBlock);
osLib_addFunction("gx2", "GX2SetGeometryUniformBlock", gx2Export_GX2SetGeometryUniformBlock);
osLib_addFunction("gx2", "GX2SetShaderModeEx", gx2Export_GX2SetShaderModeEx);
osLib_addFunction("gx2", "GX2CalcGeometryShaderInputRingBufferSize", gx2Export_GX2CalcGeometryShaderInputRingBufferSize);
osLib_addFunction("gx2", "GX2CalcGeometryShaderOutputRingBufferSize", gx2Export_GX2CalcGeometryShaderOutputRingBufferSize);
// color/depth buffers
osLib_addFunction("gx2", "GX2InitColorBufferRegs", gx2Export_GX2InitColorBufferRegs);
osLib_addFunction("gx2", "GX2InitDepthBufferRegs", gx2Export_GX2InitDepthBufferRegs);
osLib_addFunction("gx2", "GX2SetColorBuffer", gx2Export_GX2SetColorBuffer);
osLib_addFunction("gx2", "GX2SetDepthBuffer", gx2Export_GX2SetDepthBuffer);
osLib_addFunction("gx2", "GX2SetDRCBuffer", gx2Export_GX2SetDRCBuffer);
osLib_addFunction("gx2", "GX2MarkScanBufferCopied", gx2Export_GX2MarkScanBufferCopied);
// misc
osLib_addFunction("gx2", "GX2TempGetGPUVersion", gx2Export_GX2TempGetGPUVersion);
osLib_addFunction("gx2", "GX2CalcTVSize", gx2Export_GX2CalcTVSize);
osLib_addFunction("gx2", "GX2CalcDRCSize", gx2Export_GX2CalcDRCSize);
osLib_addFunction("gx2", "GX2SetDRCScale", gx2Export_GX2SetDRCScale);
osLib_addFunction("gx2", "GX2SetDRCConnectCallback", gx2Export_GX2SetDRCConnectCallback);
osLib_addFunction("gx2", "GX2GetSystemTVScanMode", coreinitExport_GX2GetSystemTVScanMode);
osLib_addFunction("gx2", "GX2GetSystemTVAspectRatio", coreinitExport_GX2GetSystemTVAspectRatio);
osLib_addFunction("gx2", "GX2SetSwapInterval", gx2Export_GX2SetSwapInterval);
osLib_addFunction("gx2", "GX2GetSwapInterval", gx2Export_GX2GetSwapInterval);
osLib_addFunction("gx2", "GX2GetGPUTimeout", gx2Export_GX2GetGPUTimeout);
osLib_addFunction("gx2", "GX2SampleTopGPUCycle", gx2Export_GX2SampleTopGPUCycle);
osLib_addFunction("gx2", "GX2SampleBottomGPUCycle", gx2Export_GX2SampleBottomGPUCycle);
osLib_addFunction("gx2", "GX2AllocateTilingApertureEx", gx2Export_GX2AllocateTilingApertureEx);
osLib_addFunction("gx2", "GX2FreeTilingAperture", gx2Export_GX2FreeTilingAperture);
// context state
osLib_addFunction("gx2", "GX2SetDefaultState", gx2Export_GX2SetDefaultState);
osLib_addFunction("gx2", "GX2SetupContextStateEx", gx2Export_GX2SetupContextStateEx);
osLib_addFunction("gx2", "GX2SetContextState", gx2Export_GX2SetContextState);
// semaphore
osLib_addFunction("gx2", "GX2SetSemaphore", gx2Export_GX2SetSemaphore);
// command buffer
osLib_addFunction("gx2", "GX2Flush", gx2Export_GX2Flush);
GX2::GX2Init_writeGather();
GX2::GX2MemInit();
GX2::GX2ResourceInit();
GX2::GX2CommandInit();
GX2::GX2SurfaceInit();
GX2::GX2SurfaceCopyInit();
GX2::GX2TextureInit();
GX2::GX2StateInit();
GX2::GX2ShaderInit();
GX2::GX2EventInit();
GX2::GX2BlitInit();
GX2::GX2DrawInit();
GX2::GX2StreamoutInit();
GX2::GX2QueryInit();
GX2::GX2MiscInit();
}
| 17,019
|
C++
|
.cpp
| 389
| 41.714653
| 238
| 0.798127
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,063
|
GX2_Texture.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Texture.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "GX2.h"
#include "GX2_Texture.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
namespace GX2
{
using namespace Latte;
/****** Texture functions ******/
void GX2InitTextureRegs(GX2Texture* texture)
{
uint32 _regs[5] = { 0 };
// some values may not be zero
if (texture->viewNumMips == 0)
texture->viewNumMips = 1;
if (texture->viewNumSlices == 0)
texture->viewNumSlices = 1;
if (texture->surface.height == 0)
texture->surface.height = 1;
if (texture->surface.depth == 0)
texture->surface.depth = 1;
if (texture->surface.numLevels == 0)
texture->surface.numLevels = 1;
// texture parameters
uint32 viewNumMips = texture->viewNumMips;
uint32 viewNumSlices = texture->viewNumSlices;
uint32 viewFirstMip = texture->viewFirstMip;
uint32 viewFirstSlice = texture->viewFirstSlice;
uint32 compSel = texture->compSel;
// surface parameters
uint32 width = texture->surface.width;
uint32 height = texture->surface.height;
uint32 depth = texture->surface.depth;
uint32 pitch = texture->surface.pitch;
uint32 numMips = texture->surface.numLevels;
Latte::E_GX2SURFFMT format = texture->surface.format;
Latte::E_DIM dim = texture->surface.dim;
uint32 tileMode = (uint32)texture->surface.tileMode.value();
uint32 surfaceFlags = texture->surface.resFlag;
uint32 surfaceAA = texture->surface.aa;
// calculate register word 0
Latte::E_HWSURFFMT formatHw = Latte::GetHWFormat(format);
Latte::LATTE_SQ_TEX_RESOURCE_WORD0_N newRegWord0;
newRegWord0.set_DIM(dim);
newRegWord0.set_TILE_MODE(Latte::MakeHWTileMode(texture->surface.tileMode));
newRegWord0.set_TILE_TYPE((surfaceFlags&4) != 0);
uint32 pixelPitch = pitch;
if (Latte::IsCompressedFormat(formatHw))
pixelPitch *= 4;
if(pixelPitch == 0)
newRegWord0.set_PITCH(0x7FF);
else
newRegWord0.set_PITCH((pixelPitch >> 3) - 1);
if (width == 0)
newRegWord0.set_WIDTH(0x1FFF);
else
newRegWord0.set_WIDTH(width - 1);
texture->regTexWord0 = newRegWord0;
// calculate register word 1
Latte::LATTE_SQ_TEX_RESOURCE_WORD1_N newRegWord1;
newRegWord1.set_HEIGHT(height - 1);
if (dim == Latte::E_DIM::DIM_CUBEMAP)
{
newRegWord1.set_DEPTH((depth / 6) - 1);
}
else if (dim == E_DIM::DIM_3D ||
dim == E_DIM::DIM_2D_ARRAY_MSAA ||
dim == E_DIM::DIM_2D_ARRAY ||
dim == E_DIM::DIM_1D_ARRAY)
{
newRegWord1.set_DEPTH(depth - 1);
}
else
{
newRegWord1.set_DEPTH(0);
}
newRegWord1.set_DATA_FORMAT(formatHw);
texture->regTexWord1 = newRegWord1;
// calculate register word 2
LATTE_SQ_TEX_RESOURCE_WORD4_N newRegWord4;
LATTE_SQ_TEX_RESOURCE_WORD4_N::E_FORMAT_COMP formatComp;
if (HAS_FLAG(format, Latte::E_GX2SURFFMT::FMT_BIT_SIGNED))
formatComp = LATTE_SQ_TEX_RESOURCE_WORD4_N::E_FORMAT_COMP::COMP_SIGNED;
else
formatComp = LATTE_SQ_TEX_RESOURCE_WORD4_N::E_FORMAT_COMP::COMP_UNSIGNED;
newRegWord4.set_FORMAT_COMP_X(formatComp);
newRegWord4.set_FORMAT_COMP_Y(formatComp);
newRegWord4.set_FORMAT_COMP_Z(formatComp);
newRegWord4.set_FORMAT_COMP_W(formatComp);
if (HAS_FLAG(format, Latte::E_GX2SURFFMT::FMT_BIT_FLOAT))
newRegWord4.set_NUM_FORM_ALL(LATTE_SQ_TEX_RESOURCE_WORD4_N::E_NUM_FORMAT_ALL::NUM_FORMAT_SCALED);
else if (HAS_FLAG(format, Latte::E_GX2SURFFMT::FMT_BIT_INT))
newRegWord4.set_NUM_FORM_ALL(LATTE_SQ_TEX_RESOURCE_WORD4_N::E_NUM_FORMAT_ALL::NUM_FORMAT_INT);
else
newRegWord4.set_NUM_FORM_ALL(LATTE_SQ_TEX_RESOURCE_WORD4_N::E_NUM_FORMAT_ALL::NUM_FORMAT_NORM);
if (HAS_FLAG(format, Latte::E_GX2SURFFMT::FMT_BIT_SRGB))
newRegWord4.set_FORCE_DEGAMMA(true);
newRegWord4.set_ENDIAN_SWAP(GX2::GetSurfaceFormatSwapMode((Latte::E_GX2SURFFMT)format));
newRegWord4.set_REQUEST_SIZE(2);
newRegWord4.set_DST_SEL_X((Latte::LATTE_SQ_TEX_RESOURCE_WORD4_N::E_SEL)((compSel >> 24) & 0x7));
newRegWord4.set_DST_SEL_Y((Latte::LATTE_SQ_TEX_RESOURCE_WORD4_N::E_SEL)((compSel >> 16) & 0x7));
newRegWord4.set_DST_SEL_Z((Latte::LATTE_SQ_TEX_RESOURCE_WORD4_N::E_SEL)((compSel >> 8) & 0x7));
newRegWord4.set_DST_SEL_W((Latte::LATTE_SQ_TEX_RESOURCE_WORD4_N::E_SEL)((compSel >> 0) & 0x7));
newRegWord4.set_BASE_LEVEL(viewFirstMip);
texture->regTexWord4 = newRegWord4;
// calculate register word 3
LATTE_SQ_TEX_RESOURCE_WORD5_N newRegWord5;
newRegWord5.set_LAST_LEVEL(viewFirstMip + viewNumMips - 1);
newRegWord5.set_BASE_ARRAY(viewFirstSlice);
newRegWord5.set_LAST_ARRAY(viewFirstSlice + viewNumSlices - 1);
if (dim == Latte::E_DIM::DIM_CUBEMAP && ((depth / 6) - 1) != 0)
newRegWord5.set_UKN_BIT_30(true);
if(surfaceAA >= 1 && surfaceAA <= 3)
newRegWord5.set_LAST_LEVEL(surfaceAA);
texture->regTexWord5 = newRegWord5;
// calculate register word 4
LATTE_SQ_TEX_RESOURCE_WORD6_N newRegWord6;
newRegWord6.set_MAX_ANISO(4);
newRegWord6.set_PERF_MODULATION(7);
newRegWord6.set_TYPE(Latte::LATTE_SQ_TEX_RESOURCE_WORD6_N::E_TYPE::VTX_VALID_TEXTURE);
texture->regTexWord6 = newRegWord6;
}
void _GX2SetTexture(GX2Texture* tex, Latte::REGADDR baseRegister, uint32 textureUnitIndex)
{
GX2ReserveCmdSpace(2 + 7);
MPTR imagePtr = tex->surface.imagePtr;
MPTR mipPtr = tex->surface.mipPtr;
if (mipPtr == MPTR_NULL)
mipPtr = imagePtr;
uint32 swizzle = tex->surface.swizzle;
cemu_assert_debug((swizzle & 0xFF) == 0); // does the low byte in swizzle field have any meaning?
if (Latte::TM_IsMacroTiled(tex->surface.tileMode))
{
uint32 swizzleStopLevel = (swizzle >> 16) & 0xFF;
// combine swizzle with image ptr if base level is macro tiled
if (swizzleStopLevel > 0)
imagePtr ^= (swizzle & 0xFFFF);
// combine swizzle with mip ptr if first mip (level 1) is macro tiled
if (swizzleStopLevel > 1)
mipPtr ^= (swizzle & 0xFFFF);
}
gx2WriteGather_submit(pm4HeaderType3(IT_SET_RESOURCE, 8),
baseRegister + textureUnitIndex * 7 - mmSQ_TEX_RESOURCE_WORD0,
tex->regTexWord0,
tex->regTexWord1,
memory_virtualToPhysical(imagePtr) >> 8,
memory_virtualToPhysical(mipPtr) >> 8,
tex->regTexWord4,
tex->regTexWord5,
tex->regTexWord6);
}
void GX2SetPixelTexture(GX2Texture* tex, uint32 texUnit)
{
cemu_assert_debug(texUnit < Latte::GPU_LIMITS::NUM_TEXTURES_PER_STAGE);
_GX2SetTexture(tex, Latte::REGADDR::SQ_TEX_RESOURCE_WORD0_N_PS, texUnit);
}
void GX2SetVertexTexture(GX2Texture* tex, uint32 texUnit)
{
cemu_assert_debug(texUnit < Latte::GPU_LIMITS::NUM_TEXTURES_PER_STAGE);
_GX2SetTexture(tex, Latte::REGADDR::SQ_TEX_RESOURCE_WORD0_N_VS, texUnit);
}
void GX2SetGeometryTexture(GX2Texture* tex, uint32 texUnit)
{
cemu_assert_debug(texUnit < Latte::GPU_LIMITS::NUM_TEXTURES_PER_STAGE);
_GX2SetTexture(tex, Latte::REGADDR::SQ_TEX_RESOURCE_WORD0_N_GS, texUnit);
}
void GX2SetComputeTexture(GX2Texture* tex, uint32 texUnit)
{
GX2SetVertexTexture(tex, texUnit);
}
/****** Sampler functions ******/
void GX2InitSampler(GX2Sampler* sampler, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_CLAMP clampXYZ, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER filterMinMag)
{
LATTE_SQ_TEX_SAMPLER_WORD0_0 word0{};
word0.set_CLAMP_X(clampXYZ).set_CLAMP_Y(clampXYZ).set_CLAMP_Z(clampXYZ);
word0.set_XY_MAG_FILTER(filterMinMag).set_XY_MIN_FILTER(filterMinMag);
word0.set_Z_FILTER(LATTE_SQ_TEX_SAMPLER_WORD0_0::E_Z_FILTER::POINT);
word0.set_MIP_FILTER(LATTE_SQ_TEX_SAMPLER_WORD0_0::E_Z_FILTER::POINT);
word0.set_TEX_ARRAY_OVERRIDE(true);
LATTE_SQ_TEX_SAMPLER_WORD1_0 word1{};
word1.set_MAX_LOD(0x3FF);
LATTE_SQ_TEX_SAMPLER_WORD2_0 word2{};
word2.set_TYPE(LATTE_SQ_TEX_SAMPLER_WORD2_0::E_SAMPLER_TYPE::UKN1);
sampler->word0 = word0;
sampler->word1 = word1;
sampler->word2 = word2;
}
void GX2InitSamplerXYFilter(GX2Sampler* sampler, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER magFilter, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER minFilter, uint32 maxAnisoRatio)
{
LATTE_SQ_TEX_SAMPLER_WORD0_0 word0 = sampler->word0;
if (maxAnisoRatio == 0)
{
word0.set_XY_MAG_FILTER(magFilter);
word0.set_XY_MIN_FILTER(minFilter);
word0.set_MAX_ANISO_RATIO(0);
}
else
{
auto getAnisoFilter = [](LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER filter) -> LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER
{
if (filter == LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER::POINT)
return LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER::ANISO_POINT;
else if (filter == LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER::BILINEAR)
return LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER::ANISO_BILINEAR;
else
cemu_assert_debug(false);
return LATTE_SQ_TEX_SAMPLER_WORD0_0::E_XY_FILTER::POINT;
};
word0.set_XY_MAG_FILTER(getAnisoFilter(magFilter));
word0.set_XY_MIN_FILTER(getAnisoFilter(minFilter));
word0.set_MAX_ANISO_RATIO(maxAnisoRatio);
}
sampler->word0 = word0;
}
void GX2InitSamplerZMFilter(GX2Sampler* sampler, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_Z_FILTER zFilter, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_Z_FILTER mipFilter)
{
LATTE_SQ_TEX_SAMPLER_WORD0_0 word0 = sampler->word0;
word0.set_Z_FILTER(zFilter);
word0.set_MIP_FILTER(mipFilter);
sampler->word0 = word0;
}
void GX2InitSamplerLOD(GX2Sampler* sampler, float minLod, float maxLod, float lodBias)
{
// known special cases: Mario & Sonic Rio passes minimum and maximum float values for minLod/maxLod
if (minLod < 0.0)
minLod = 0.0;
if (maxLod > 16.0)
maxLod = 16.0;
uint32 iMinLod = ((uint32)floorf(minLod * 64.0f));
uint32 iMaxLod = ((uint32)floorf(maxLod * 64.0f));
sint32 iLodBias = (sint32)((sint32)floorf(lodBias * 64.0f)); // input range: -32.0 to 32.0
iMinLod = std::clamp(iMinLod, 0u, 1023u);
iMaxLod = std::clamp(iMaxLod, 0u, 1023u);
iLodBias = std::clamp(iLodBias, -2048, 2047);
LATTE_SQ_TEX_SAMPLER_WORD1_0 word1 = sampler->word1;
word1.set_MIN_LOD(iMinLod);
word1.set_MAX_LOD(iMaxLod);
word1.set_LOD_BIAS(iLodBias);
sampler->word1 = word1;
}
void GX2InitSamplerClamping(GX2Sampler* sampler, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_CLAMP clampX, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_CLAMP clampY, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_CLAMP clampZ)
{
LATTE_SQ_TEX_SAMPLER_WORD0_0 word0 = sampler->word0;
word0.set_CLAMP_X(clampX);
word0.set_CLAMP_Y(clampY);
word0.set_CLAMP_Z(clampZ);
sampler->word0 = word0;
}
void GX2InitSamplerBorderType(GX2Sampler* sampler, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_BORDER_COLOR_TYPE borderColorType)
{
LATTE_SQ_TEX_SAMPLER_WORD0_0 word0 = sampler->word0;
word0.set_BORDER_COLOR_TYPE(borderColorType);
sampler->word0 = word0;
}
void GX2InitSamplerDepthCompare(GX2Sampler* sampler, LATTE_SQ_TEX_SAMPLER_WORD0_0::E_DEPTH_COMPARE depthCompareFunction)
{
LATTE_SQ_TEX_SAMPLER_WORD0_0 word0 = sampler->word0;
word0.set_DEPTH_COMPARE_FUNCTION(depthCompareFunction);
sampler->word0 = word0;
}
void _GX2SetSampler(GX2Sampler* sampler, uint32 samplerIndex)
{
GX2ReserveCmdSpace(5);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_SAMPLER, 1 + 3),
samplerIndex * 3,
sampler->word0, sampler->word1, sampler->word2);
}
void GX2SetPixelSampler(GX2Sampler* sampler, uint32 samplerIndex)
{
_GX2SetSampler(sampler, samplerIndex + SAMPLER_BASE_INDEX_PIXEL);
}
void GX2SetVertexSampler(GX2Sampler* sampler, uint32 vertexSamplerIndex)
{
_GX2SetSampler(sampler, vertexSamplerIndex + SAMPLER_BASE_INDEX_VERTEX);
}
void GX2SetGeometrySampler(GX2Sampler* sampler, uint32 geometrySamplerIndex)
{
_GX2SetSampler(sampler, geometrySamplerIndex + SAMPLER_BASE_INDEX_GEOMETRY);
}
void GX2SetComputeSampler(GX2Sampler* sampler, uint32 computeSamplerIndex)
{
_GX2SetSampler(sampler, computeSamplerIndex + SAMPLER_BASE_INDEX_VERTEX); // uses vertex shader stage
}
void GX2SetSamplerBorderColor(uint32 registerBaseOffset, uint32 samplerIndex, float red, float green, float blue, float alpha)
{
GX2ReserveCmdSpace(6);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONFIG_REG, 1 + 4),
registerBaseOffset + samplerIndex * 4 - LATTE_REG_BASE_CONFIG,
red, green, blue, alpha);
}
void GX2SetPixelSamplerBorderColor(uint32 pixelSamplerIndex, float red, float green, float blue, float alpha)
{
GX2SetSamplerBorderColor(REGADDR::TD_PS_SAMPLER0_BORDER_RED, pixelSamplerIndex, red, green, blue, alpha);
}
void GX2SetVertexSamplerBorderColor(uint32 vertexSamplerIndex, float red, float green, float blue, float alpha)
{
GX2SetSamplerBorderColor(REGADDR::TD_VS_SAMPLER0_BORDER_RED, vertexSamplerIndex, red, green, blue, alpha);
}
void GX2SetGeometrySamplerBorderColor(uint32 geometrySamplerIndex, float red, float green, float blue, float alpha)
{
GX2SetSamplerBorderColor(REGADDR::TD_GS_SAMPLER0_BORDER_RED, geometrySamplerIndex, red, green, blue, alpha);
}
void GX2TextureInit()
{
// texture
cafeExportRegister("gx2", GX2InitTextureRegs, LogType::GX2);
cafeExportRegister("gx2", GX2SetPixelTexture, LogType::GX2);
cafeExportRegister("gx2", GX2SetVertexTexture, LogType::GX2);
cafeExportRegister("gx2", GX2SetGeometryTexture, LogType::GX2);
cafeExportRegister("gx2", GX2SetComputeTexture, LogType::GX2);
// sampler
cafeExportRegister("gx2", GX2InitSampler, LogType::GX2);
cafeExportRegister("gx2", GX2InitSamplerXYFilter, LogType::GX2);
cafeExportRegister("gx2", GX2InitSamplerZMFilter, LogType::GX2);
cafeExportRegister("gx2", GX2InitSamplerLOD, LogType::GX2);
cafeExportRegister("gx2", GX2InitSamplerClamping, LogType::GX2);
cafeExportRegister("gx2", GX2InitSamplerBorderType, LogType::GX2);
cafeExportRegister("gx2", GX2InitSamplerDepthCompare, LogType::GX2);
cafeExportRegister("gx2", GX2SetPixelSampler, LogType::GX2);
cafeExportRegister("gx2", GX2SetVertexSampler, LogType::GX2);
cafeExportRegister("gx2", GX2SetGeometrySampler, LogType::GX2);
cafeExportRegister("gx2", GX2SetComputeSampler, LogType::GX2);
cafeExportRegister("gx2", GX2SetPixelSamplerBorderColor, LogType::GX2);
cafeExportRegister("gx2", GX2SetVertexSamplerBorderColor, LogType::GX2);
cafeExportRegister("gx2", GX2SetGeometrySamplerBorderColor, LogType::GX2);
}
};
| 14,108
|
C++
|
.cpp
| 331
| 39.495468
| 187
| 0.746355
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,064
|
GX2_ContextState.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_ContextState.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "GX2_Command.h"
#include "GX2_State.h"
#include "Cafe/CafeSystem.h"
#define GPU7_REG_AREA_SIZE_CONFIG_REG 0xB00
#define GPU7_REG_AREA_SIZE_CONTEXT_REG 0x400
#define GPU7_REG_AREA_SIZE_ALU_CONST 0x800
#define GPU7_REG_AREA_SIZE_LOOP_CONST 0x60
#define GPU7_REG_AREA_SIZE_RESOURCE 0xD9E
#define GPU7_REG_AREA_SIZE_SAMPLER 0xA2 // (guessed)
#define _GX2_CALC_SHADOWMEM_NUM_U32(__v) (((((__v)*4)+0xFF)&~0xFF)/4)
MPTR gx2CurrentContextStateMPTR = MPTR_NULL;
typedef struct
{
uint32 regOffset;
uint32 regCount;
}GX2RegLoadPktEntry_t;
GX2RegLoadPktEntry_t aluConst_loadPktEntries[1] = // base: 0xC000
{
{0, 0x800},
};
GX2RegLoadPktEntry_t loopConst_loadPktEntries[1] = // base: 0xF880
{
{0, 0x60},
};
GX2RegLoadPktEntry_t samplerReg_loadPktEntries[3] = // base: 0xF000
{
{0, 0x36},
{0x36, 0x36},
{0x6C, 0x36},
};
GX2RegLoadPktEntry_t configReg_loadPktEntries[0xF] = // base: 0x2000
{
{0x300, 0x6},
{0x900, 0x48},
{0x980, 0x48},
{0xA00, 0x48},
{0x310, 0xC},
{0x542, 0x1},
{0x235, 0x1},
{0x232, 0x2},
{0x23A, 0x1},
{0x256, 0x1},
{0x60C, 0x1},
{0x5C5, 0x1},
{0x2C8, 0x1},
{0x363, 0x1},
{0x404, 0x2}
};
GX2RegLoadPktEntry_t contextReg_loadPktEntries[0x2D] = // base: 0xA000
{
{0x0, 0x2},
{0x3, 0x3},
{0xA, 0x4},
{0x10, 0x38},
{0x50, 0x34},
{0x8E, 0x4},
{0x94, 0x40},
{0x100, 0x9},
{0x10C, 0x3},
{0x10F, 0x60},
{0x185, 0xA},
{0x191, 0x27},
{0x1E0, 0x9},
{0x200, 0x1},
{0x202, 0x7},
{0xE0, 0x20},
{0x210, 0x29},
{0x250, 0x34},
{0x290, 0x1},
{0x292, 0x2},
{0x2A1, 0x1},
{0x2A5, 0x1},
{0x2A8, 0x2},
{0x2AC, 0x3},
{0x2CA, 0x1},
{0x2CC, 0x1},
{0x2CE, 0x1},
{0x300, 0x9},
{0x30C, 0x1},
{0x312, 0x1},
{0x316, 0x2},
{0x343, 0x2},
{0x349, 0x3},
{0x34C, 0x2},
{0x351, 0x1},
{0x37E, 0x6},
{0x2B4, 0x3},
{0x2B8, 0x3},
{0x2BC, 0x3},
{0x2C0, 0x3},
{0x2C8, 0x1},
{0x29B, 0x1},
{0x8C, 0x1},
{0xD5, 0x1},
{0x284, 0xC}
};
GX2RegLoadPktEntry_t resourceReg_loadPktEntries[9] = // base: 0xE000
{
{0, 0x70}, // ps tex
{0x380, 0x70},
{0x460, 0x70}, // vs tex
{0x7E0, 0x70},
{0x8B9, 0x7},
{0x8C0, 0x70},
{0x930, 0x70}, // gs tex
{0xCB0, 0x70},
{0xD89, 0x7}
};
typedef struct
{
// Hardware view of context state (register areas)
uint32 areaConfigReg[_GX2_CALC_SHADOWMEM_NUM_U32(GPU7_REG_AREA_SIZE_CONFIG_REG)];
uint32 areaContextReg[_GX2_CALC_SHADOWMEM_NUM_U32(GPU7_REG_AREA_SIZE_CONTEXT_REG)];
uint32 areaALUConst[_GX2_CALC_SHADOWMEM_NUM_U32(GPU7_REG_AREA_SIZE_ALU_CONST)];
uint32 areaLoopConst[_GX2_CALC_SHADOWMEM_NUM_U32(GPU7_REG_AREA_SIZE_LOOP_CONST)];
uint32 areaResource[_GX2_CALC_SHADOWMEM_NUM_U32(GPU7_REG_AREA_SIZE_RESOURCE)];
uint32 areaSampler[_GX2_CALC_SHADOWMEM_NUM_U32(GPU7_REG_AREA_SIZE_SAMPLER)];
}GX2HwContextState_t;
typedef struct
{
GX2HwContextState_t hwContext;
uint32 enableProfling;
/* + 0x9804 */ uint32be loadDL_size;
uint8 ukn9808[0x3FC-4];
uint8 ukn9C00[0x200];
/* +0x9E00 */ uint8 loadDL_buffer[0x300]; // this displaylist caches the IT_LOAD_* commands for swapping out context
}GX2ContextState_t;
static_assert(offsetof(GX2ContextState_t, loadDL_size) == 0x9804);
static_assert(sizeof(GX2ContextState_t) == 0xA100);
uint32 _GX2Context_CalcShadowMemSize(uint32 regCount)
{
return (regCount*4+0xFF)&~0xFF;
}
uint32 _GX2Context_CalcStateSize()
{
uint32 contextStateSize = 0;
contextStateSize += _GX2Context_CalcShadowMemSize(GPU7_REG_AREA_SIZE_CONFIG_REG);
contextStateSize += _GX2Context_CalcShadowMemSize(GPU7_REG_AREA_SIZE_CONTEXT_REG);
contextStateSize += _GX2Context_CalcShadowMemSize(GPU7_REG_AREA_SIZE_ALU_CONST);
contextStateSize += _GX2Context_CalcShadowMemSize(GPU7_REG_AREA_SIZE_LOOP_CONST);
contextStateSize += _GX2Context_CalcShadowMemSize(GPU7_REG_AREA_SIZE_RESOURCE);
contextStateSize += _GX2Context_CalcShadowMemSize(GPU7_REG_AREA_SIZE_SAMPLER);
return contextStateSize;
}
void _GX2Context_CreateLoadDL()
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_CONTEXT_CONTROL, 2));
gx2WriteGather_submitU32AsBE(0x80000077);
gx2WriteGather_submitU32AsBE(0x80000077);
}
void _GX2Context_WriteCmdDisableStateShadowing()
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_CONTEXT_CONTROL, 2));
gx2WriteGather_submitU32AsBE(0x80000000);
gx2WriteGather_submitU32AsBE(0x80000000);
}
void _GX2Context_cmdLoad(void* gx2ukn, uint32 pm4Header, MPTR physAddrRegArea, uint32 waitForIdle, uint32 numRegOffsetEntries, GX2RegLoadPktEntry_t* regOffsetEntries)
{
GX2ReserveCmdSpace(3 + numRegOffsetEntries*2);
gx2WriteGather_submitU32AsBE(pm4Header);
gx2WriteGather_submitU32AsBE(physAddrRegArea);
gx2WriteGather_submitU32AsBE(waitForIdle);
for(uint32 i=0; i<numRegOffsetEntries; i++)
{
gx2WriteGather_submitU32AsBE(regOffsetEntries[i].regOffset); // regOffset
gx2WriteGather_submitU32AsBE(regOffsetEntries[i].regCount); // regCount
}
}
#define __cmdStateLoad(__gx2State, __pm4Command, __regArea, __waitForIdle, __regLoadPktEntries) _GX2Context_cmdLoad(NULL, pm4HeaderType3(__pm4Command, 2+sizeof(__regLoadPktEntries)/sizeof(__regLoadPktEntries[0])*2), memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(__regArea)), __waitForIdle, sizeof(__regLoadPktEntries)/sizeof(__regLoadPktEntries[0]), __regLoadPktEntries)
void _GX2Context_WriteCmdRestoreState(GX2ContextState_t* gx2ContextState, uint32 ukn)
{
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
MPTR physAddrContextState = memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(gx2ContextState));
_GX2Context_CreateLoadDL();
__cmdStateLoad(NULL, IT_LOAD_CONFIG_REG, gx2ContextState->hwContext.areaConfigReg, 0x80000000, configReg_loadPktEntries);
__cmdStateLoad(NULL, IT_LOAD_CONTEXT_REG, gx2ContextState->hwContext.areaContextReg, 0, contextReg_loadPktEntries);
__cmdStateLoad(NULL, IT_LOAD_ALU_CONST, gx2ContextState->hwContext.areaALUConst, 0, aluConst_loadPktEntries);
__cmdStateLoad(NULL, IT_LOAD_LOOP_CONST, gx2ContextState->hwContext.areaLoopConst, 0, loopConst_loadPktEntries);
__cmdStateLoad(NULL, IT_LOAD_RESOURCE, gx2ContextState->hwContext.areaResource, 0, resourceReg_loadPktEntries);
__cmdStateLoad(NULL, IT_LOAD_SAMPLER, gx2ContextState->hwContext.areaSampler, 0, samplerReg_loadPktEntries);
}
void GX2SetDefaultState()
{
GX2ReserveCmdSpace(0x100);
Latte::LATTE_PA_CL_VTE_CNTL reg{};
reg.set_VPORT_X_OFFSET_ENA(true).set_VPORT_X_SCALE_ENA(true);
reg.set_VPORT_Y_OFFSET_ENA(true).set_VPORT_Y_SCALE_ENA(true);
reg.set_VPORT_Z_OFFSET_ENA(true).set_VPORT_Z_SCALE_ENA(true);
reg.set_VTX_W0_FMT(true);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 1 + 1),
Latte::REGADDR::PA_CL_VTE_CNTL - 0xA000,
reg);
uint32 stencilTestEnable = GX2_FALSE;
uint32 backStencilEnable = GX2_FALSE;
uint32 frontStencilFunc = 0;
uint32 frontStencilZPass = 0;
uint32 frontStencilZFail = 0;
uint32 frontStencilFail = 0;
uint32 backStencilFunc = 0;
uint32 backStencilZPass = 0;
uint32 backStencilZFail = 0;
uint32 backStencilFail = 0;
uint32 depthControlReg = 0;
// depth stuff
depthControlReg |= (1<<1);
depthControlReg |= (1<<2);
depthControlReg |= ((1&7)<<4);
// stencil stuff
depthControlReg |= ((stencilTestEnable&1)<<0);
depthControlReg |= ((backStencilEnable&1)<<7);
depthControlReg |= ((frontStencilFunc&7)<<8);
depthControlReg |= ((frontStencilZPass&7)<<14);
depthControlReg |= ((frontStencilZFail&7)<<17);
depthControlReg |= ((frontStencilFail&7)<<11);
depthControlReg |= ((backStencilFunc&7)<<20);
depthControlReg |= ((backStencilZPass&7)<<26);
depthControlReg |= ((backStencilZFail&3)<<29);
depthControlReg |= ((backStencilFail&7)<<23);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+1));
gx2WriteGather_submitU32AsBE(Latte::REGADDR::DB_DEPTH_CONTROL-0xA000);
gx2WriteGather_submitU32AsBE(depthControlReg);
GX2::GX2SetAlphaTest(GX2_DISABLE, GX2::GX2_ALPHAFUNC::LESS, 0.0f);
GX2::GX2SetPolygonControl(Latte::LATTE_PA_SU_SC_MODE_CNTL::E_FRONTFACE::CCW, GX2_DISABLE, GX2_DISABLE, Latte::LATTE_PA_SU_SC_MODE_CNTL::E_POLYGONMODE::UKN0, Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE::TRIANGLES, Latte::LATTE_PA_SU_SC_MODE_CNTL::E_PTYPE::TRIANGLES, GX2_DISABLE, GX2_DISABLE, GX2_DISABLE);
GX2::GX2SetPolygonOffset(0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
GX2::GX2SetPrimitiveRestartIndex(0xffffffff);
GX2::GX2SetTargetChannelMasks(0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF);
GX2::GX2SetBlendConstantColor(0.0f, 0.0f, 0.0f, 0.0f);
GX2::GX2SetPointSize(1.0f, 1.0f);
GX2::GX2SetPointLimits(1.0f, 1.0f);
GX2::GX2SetColorControl(GX2::GX2_LOGICOP::COPY, GX2_DISABLE, GX2_DISABLE, GX2_ENABLE);
GX2::GX2SetRasterizerClipControlEx(true, true, false);
// Set clear depth to 1.0 (workaround for Darksiders 2. Investigate whether actual GX2 driver also sets this)
float depth = 1.0;
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+1));
gx2WriteGather_submitU32AsBE(mmDB_DEPTH_CLEAR - 0xA000);
gx2WriteGather_submitU32AsBE(*(uint32*)&depth); // depth (as float)
// reset HLE special states
for (sint32 i = 0; i <= GX2_SPECIAL_STATE_COUNT; i++)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_SPECIAL_STATE, 2));
gx2WriteGather_submitU32AsBE(i); // state id
gx2WriteGather_submitU32AsBE(0); // disable
}
}
void gx2Export_GX2SetDefaultState(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetDefaultState()");
GX2SetDefaultState();
osLib_returnFromFunction(hCPU, 0);
}
void _GX2ContextCreateRestoreStateDL(GX2ContextState_t* gx2ContextState)
{
// begin display list
cemu_assert_debug(!GX2::GX2GetDisplayListWriteStatus()); // must not already be writing to a display list
GX2::GX2BeginDisplayList((void*)gx2ContextState->loadDL_buffer, sizeof(gx2ContextState->loadDL_buffer));
_GX2Context_WriteCmdRestoreState(gx2ContextState, 0);
uint32 displayListSize = GX2::GX2EndDisplayList((void*)gx2ContextState->loadDL_buffer);
gx2ContextState->loadDL_size = displayListSize;
}
void gx2Export_GX2SetupContextStateEx(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetupContextStateEx(0x{:08x})", hCPU->gpr[3]);
cemu_assert_debug(hCPU->gpr[4] == 0 || hCPU->gpr[4] == 1);
GX2ContextState_t* gx2ContextState = (GX2ContextState_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint32 hwContextSize = _GX2Context_CalcStateSize();
if( hwContextSize != sizeof(GX2HwContextState_t) )
assert_dbg();
if( sizeof(GX2HwContextState_t) != 0x9800 )
assert_dbg(); // GX2 HW context size mismatch
if( sizeof(GX2ContextState_t) != 0xA100 )
assert_dbg(); // GX2 context size mismatch
memset(gx2ContextState, 0x00, sizeof(GX2ContextState_t));
gx2ContextState->enableProfling = _swapEndianU32(hCPU->gpr[4]&1);
_GX2Context_WriteCmdRestoreState(gx2ContextState, 1);
gx2CurrentContextStateMPTR = hCPU->gpr[3];
_GX2Context_CreateLoadDL();
GX2SetDefaultState();
_GX2ContextCreateRestoreStateDL(gx2ContextState);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetContextState(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetContextState(0x{:08x})", hCPU->gpr[3]);
// parameters:
if( hCPU->gpr[3] == MPTR_NULL )
{
// disable state shadowing
_GX2Context_WriteCmdDisableStateShadowing();
osLib_returnFromFunction(hCPU, 0);
return;
}
// check if context state changed
bool boiWorkaround = CafeSystem::GetRPXHashBase() == 0x6BCD618E; // workaround for a bug in Binding of Isaac to avoid flicker
if( boiWorkaround )
{
if( hCPU->gpr[3] != gx2CurrentContextStateMPTR ) // dont reload same state
{
GX2ContextState_t* gx2ContextState = (GX2ContextState_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
_GX2Context_WriteCmdRestoreState(gx2ContextState, 0);
_GX2Context_CreateLoadDL();
// set new context state
gx2CurrentContextStateMPTR = hCPU->gpr[3];
}
else
{
// even if it's the same context, make sure state shadowing is enabled.
_GX2Context_CreateLoadDL();
}
}
else
{
GX2ContextState_t* gx2ContextState = (GX2ContextState_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
if (gx2ContextState->loadDL_size == 0)
{
_GX2Context_CreateLoadDL();
_GX2Context_WriteCmdRestoreState(gx2ContextState, 0);
}
else
{
_GX2Context_CreateLoadDL();
GX2::GX2CallDisplayList(memory_getVirtualOffsetFromPointer(gx2ContextState->loadDL_buffer), gx2ContextState->loadDL_size);
}
// set new context state
gx2CurrentContextStateMPTR = hCPU->gpr[3];
}
// todo: Save/restore GX2 special state as well -> handle this by correctly emulating the state
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2GetContextStateDisplayList(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2GetContextStateDisplayList(0x{:08x}, 0x{:08x}, 0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamStructPtr(gx2ContextState, GX2ContextState_t, 0);
ppcDefineParamU32BEPtr(displayListPtrOut, 1);
ppcDefineParamU32BEPtr(displayListSizeOut, 2);
*displayListPtrOut = memory_getVirtualOffsetFromPointer(gx2ContextState->loadDL_buffer);
*displayListSizeOut = gx2ContextState->loadDL_size;
osLib_returnFromFunction(hCPU, 0);
}
| 13,204
|
C++
|
.cpp
| 346
| 36.101156
| 384
| 0.765454
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,065
|
GX2_Surface_Copy.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Surface_Copy.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Core/LatteAsyncCommands.h"
#include "Cafe/HW/Latte/LatteAddrLib/LatteAddrLib.h"
#include "util/highresolutiontimer/HighResolutionTimer.h"
#include "GX2.h"
#include "GX2_Resource.h"
template<uint32 copyBpp>
void gx2SurfaceCopySoftware_specialized(
uint8* inputData, sint32 surfSrcHeight, sint32 srcPitch, sint32 srcDepth, uint32 srcSlice, uint32 srcSwizzle, uint32 srcHwTileMode,
uint8* outputData, sint32 surfDstHeight, sint32 dstPitch, sint32 dstDepth, uint32 dstSlice, uint32 dstSwizzle, uint32 dstHwTileMode,
uint32 copyWidth, uint32 copyHeight)
{
uint32 srcPipeSwizzle = (srcSwizzle >> 8) & 1;
uint32 srcBankSwizzle = ((srcSwizzle >> 9) & 3);
uint32 dstPipeSwizzle = (dstSwizzle >> 8) & 1;
uint32 dstBankSwizzle = ((dstSwizzle >> 9) & 3);
for (uint32 y = 0; y < copyHeight; y++)
{
for (uint32 x = 0; x < copyWidth; x++)
{
// calculate address of input block
uint32 srcOffset = 0;
if (srcHwTileMode == 0 || srcHwTileMode == 1)
srcOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordLinear(x, y, srcSlice, 0, copyBpp, srcPitch, surfSrcHeight, srcDepth);
else if (srcHwTileMode == 2 || srcHwTileMode == 3)
srcOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMicroTiled(x, y, srcSlice, copyBpp, srcPitch, surfSrcHeight, (Latte::E_HWTILEMODE)srcHwTileMode, false);
else
srcOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMacroTiled(x, y, srcSlice, 0, copyBpp, srcPitch, surfSrcHeight, 1 * 1, (Latte::E_HWTILEMODE)srcHwTileMode, false, srcPipeSwizzle, srcBankSwizzle);
uint8* inputBlockData = inputData + srcOffset;
// calculate address of output block
uint32 dstOffset = 0;
if (dstHwTileMode == 0 || dstHwTileMode == 1)
dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordLinear(x, y, dstSlice, 0, copyBpp, dstPitch, surfDstHeight, dstDepth);
else if (dstHwTileMode == 2 || dstHwTileMode == 3)
dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMicroTiled(x, y, dstSlice, copyBpp, dstPitch, surfDstHeight, (Latte::E_HWTILEMODE)dstHwTileMode, false);
else
dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMacroTiled(x, y, dstSlice, 0, copyBpp, dstPitch, surfDstHeight, 1 * 1, (Latte::E_HWTILEMODE)dstHwTileMode, false, dstPipeSwizzle, dstBankSwizzle);
uint8* outputBlockData = outputData + dstOffset;
if constexpr (copyBpp == 8)
{
outputBlockData[0] = inputBlockData[0];
}
else if constexpr (copyBpp == 16)
{
*(uint16*)outputBlockData = *(uint16*)inputBlockData;
}
else if constexpr (copyBpp == 32)
{
*(uint32*)outputBlockData = *(uint32*)inputBlockData;
}
else if constexpr (copyBpp == 64)
{
*(uint32*)(outputBlockData + 0) = *(uint32*)(inputBlockData + 0);
*(uint32*)(outputBlockData + 4) = *(uint32*)(inputBlockData + 4);
}
else if constexpr (copyBpp == 128)
{
*(uint32*)(outputBlockData + 0) = *(uint32*)(inputBlockData + 0);
*(uint32*)(outputBlockData + 4) = *(uint32*)(inputBlockData + 4);
*(uint32*)(outputBlockData + 8) = *(uint32*)(inputBlockData + 8);
*(uint32*)(outputBlockData + 12) = *(uint32*)(inputBlockData + 12);
}
}
}
}
// fast copy for tilemode 4 to tilemode 4
// assumes aa 1
// this only supports the cases where every micro tile fits within 256 bytes (group size)
// we could accelerate this even further if we copied whole macro blocks
void gx2SurfaceCopySoftware_fastPath_tm4Copy(uint8* inputData, sint32 surfSrcHeight, sint32 srcPitch, sint32 srcDepth, uint32 srcSlice, uint32 srcSwizzle,
uint8* outputData, sint32 surfDstHeight, sint32 dstPitch, sint32 dstDepth, uint32 dstSlice, uint32 dstSwizzle,
uint32 copyWidth, uint32 copyHeight, uint32 copyBpp)
{
cemu_assert_debug((copyWidth & 7) == 0);
cemu_assert_debug((copyHeight & 7) == 0);
uint32 srcPipeSwizzle = (srcSwizzle >> 8) & 1;
uint32 srcBankSwizzle = ((srcSwizzle >> 9) & 3);
uint32 dstPipeSwizzle = (dstSwizzle >> 8) & 1;
uint32 dstBankSwizzle = ((dstSwizzle >> 9) & 3);
uint32 texelBytes = copyBpp / 8;
if (srcSlice == dstSlice && srcSwizzle == dstSwizzle && surfSrcHeight == surfDstHeight && srcPitch == dstPitch)
{
// shared tile offsets
for (uint32 y = 0; y < copyHeight; y += 8)
{
for (uint32 x = 0; x < copyWidth; x += 8)
{
// copy 8x8 micro tile
uint32 offset = LatteAddrLib::ComputeSurfaceAddrFromCoordMacroTiled(x, y, srcSlice, 0, copyBpp, srcPitch, surfSrcHeight, 1 * 1, Latte::E_HWTILEMODE::TM_2D_TILED_THIN1, false, srcPipeSwizzle, srcBankSwizzle);
uint8* inputBlockData = inputData + offset;
uint8* outputBlockData = outputData + offset;
memcpy(outputBlockData, inputBlockData, texelBytes * (8 * 8));
}
}
}
else
{
// separate tile offsets
for (uint32 y = 0; y < copyHeight; y += 8)
{
for (uint32 x = 0; x < copyWidth; x += 8)
{
// copy 8x8 micro tile
uint32 srcOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMacroTiled(x, y, srcSlice, 0, copyBpp, srcPitch, surfSrcHeight, 1 * 1, Latte::E_HWTILEMODE::TM_2D_TILED_THIN1, false, srcPipeSwizzle, srcBankSwizzle);
uint8* inputBlockData = inputData + srcOffset;
uint32 dstOffset = LatteAddrLib::ComputeSurfaceAddrFromCoordMacroTiled(x, y, dstSlice, 0, copyBpp, dstPitch, surfDstHeight, 1 * 1, Latte::E_HWTILEMODE::TM_2D_TILED_THIN1, false, dstPipeSwizzle, dstBankSwizzle);
uint8* outputBlockData = outputData + dstOffset;
memcpy(outputBlockData, inputBlockData, texelBytes * (8 * 8));
}
}
}
}
void gx2SurfaceCopySoftware(
uint8* inputData, sint32 surfSrcHeight, sint32 srcPitch, sint32 srcDepth, uint32 srcSlice, uint32 srcSwizzle, uint32 srcHwTileMode,
uint8* outputData, sint32 surfDstHeight, sint32 dstPitch, sint32 dstDepth, uint32 dstSlice, uint32 dstSwizzle, uint32 dstHwTileMode,
uint32 copyWidth, uint32 copyHeight, uint32 copyBpp)
{
if (srcHwTileMode == 4 && dstHwTileMode == 4 && (copyWidth & 7) == 0 && (copyHeight & 7) == 0 && copyBpp <= 32) // todo - check sample == 1
{
gx2SurfaceCopySoftware_fastPath_tm4Copy(inputData, surfSrcHeight, srcPitch, srcDepth, srcSlice, srcSwizzle, outputData, surfDstHeight, dstPitch, dstDepth, dstSlice, dstSwizzle, copyWidth, copyHeight, copyBpp);
return;
}
if (copyBpp == 8)
gx2SurfaceCopySoftware_specialized<8>(inputData, surfSrcHeight, srcPitch, srcDepth, srcSlice, srcSwizzle, srcHwTileMode, outputData, surfDstHeight, dstPitch, dstDepth, dstSlice, dstSwizzle, dstHwTileMode, copyWidth, copyHeight);
else if (copyBpp == 16)
gx2SurfaceCopySoftware_specialized<16>(inputData, surfSrcHeight, srcPitch, srcDepth, srcSlice, srcSwizzle, srcHwTileMode, outputData, surfDstHeight, dstPitch, dstDepth, dstSlice, dstSwizzle, dstHwTileMode, copyWidth, copyHeight);
else if (copyBpp == 32)
gx2SurfaceCopySoftware_specialized<32>(inputData, surfSrcHeight, srcPitch, srcDepth, srcSlice, srcSwizzle, srcHwTileMode, outputData, surfDstHeight, dstPitch, dstDepth, dstSlice, dstSwizzle, dstHwTileMode, copyWidth, copyHeight);
else if (copyBpp == 64)
gx2SurfaceCopySoftware_specialized<64>(inputData, surfSrcHeight, srcPitch, srcDepth, srcSlice, srcSwizzle, srcHwTileMode, outputData, surfDstHeight, dstPitch, dstDepth, dstSlice, dstSwizzle, dstHwTileMode, copyWidth, copyHeight);
else if (copyBpp == 128)
gx2SurfaceCopySoftware_specialized<128>(inputData, surfSrcHeight, srcPitch, srcDepth, srcSlice, srcSwizzle, srcHwTileMode, outputData, surfDstHeight, dstPitch, dstDepth, dstSlice, dstSwizzle, dstHwTileMode, copyWidth, copyHeight);
else
cemu_assert_debug(false);
}
void gx2Surface_GX2CopySurface(GX2Surface* srcSurface, uint32 srcMip, uint32 srcSlice, GX2Surface* dstSurface, uint32 dstMip, uint32 dstSlice)
{
sint32 dstWidth = dstSurface->width;
sint32 dstHeight = dstSurface->height;
sint32 srcWidth = srcSurface->width;
sint32 srcHeight = srcSurface->height;
sint32 dstMipWidth = std::max(dstWidth>>dstMip, 1);
sint32 dstMipHeight = std::max(dstHeight>>dstMip, 1);
sint32 srcMipWidth = std::max(srcWidth>>srcMip, 1);
sint32 srcMipHeight = std::max(srcHeight>>srcMip, 1);
if( dstMipWidth != srcMipWidth || dstMipHeight != srcMipHeight )
{
cemu_assert_debug(false);
return;
}
// handle format
Latte::E_GX2SURFFMT srcFormat = srcSurface->format;
Latte::E_GX2SURFFMT dstFormat = dstSurface->format;
uint32 srcBPP = Latte::GetFormatBits(srcFormat);
uint32 dstBPP = Latte::GetFormatBits(dstFormat);
auto srcHwFormat = Latte::GetHWFormat(srcFormat);
auto dstHwFormat = Latte::GetHWFormat(dstFormat);
// get texture info
LatteAddrLib::AddrSurfaceInfo_OUT surfOutSrc = {0};
GX2::GX2CalculateSurfaceInfo(srcSurface, srcMip, &surfOutSrc);
LatteAddrLib::AddrSurfaceInfo_OUT surfOutDst = {0};
GX2::GX2CalculateSurfaceInfo(dstSurface, dstMip, &surfOutDst);
// check parameters
if (srcSurface->numLevels == 0)
{
debug_printf("GX2CopySurface(): mip count is 0\n");
return;
}
// get input pointer
uint8* inputData = NULL;
cemu_assert(srcMip < srcSurface->numLevels);
if( srcMip == 0 )
inputData = (uint8*)memory_getPointerFromVirtualOffset(srcSurface->imagePtr);
else if( srcMip == 1 )
inputData = (uint8*)memory_getPointerFromVirtualOffset(srcSurface->mipPtr);
else
{
inputData = (uint8*)memory_getPointerFromVirtualOffset(srcSurface->mipPtr + srcSurface->mipOffset[srcMip - 1]);
}
// get output pointer
uint8* outputData = NULL;
cemu_assert(dstMip < dstSurface->numLevels);
if( dstMip == 0 )
outputData = (uint8*)memory_getPointerFromVirtualOffset(dstSurface->imagePtr);
else if( dstMip == 1 )
outputData = (uint8*)memory_getPointerFromVirtualOffset(dstSurface->mipPtr);
else
{
outputData = (uint8*)memory_getPointerFromVirtualOffset(dstSurface->mipPtr + dstSurface->mipOffset[dstMip - 1]);
}
if( srcHwFormat != dstHwFormat )
{
// mismatching format
cemuLog_logDebug(LogType::Force, "GX2CopySurface(): Format mismatch");
return;
}
// note: Do not trust values from the input GX2Surface* structs but rely on surfOutDst/surfOutSrc instead if possible.
// src
uint32 srcPitch = surfOutSrc.pitch;
uint32 srcSwizzle = srcSurface->swizzle;
uint32 srcHwTileMode = (uint32)surfOutSrc.hwTileMode;
uint32 srcDepth = std::max<uint32>(surfOutSrc.depth, 1);
if (srcHwTileMode == 0) // linear
{
srcPitch = srcSurface->pitch >> srcMip;
srcPitch = std::max<uint32>(srcPitch, 1);
}
// dst
uint32 dstPitch = surfOutDst.pitch;
uint32 dstSwizzle = dstSurface->swizzle;
uint32 dstHwTileMode = (uint32)surfOutDst.hwTileMode;
uint32 dstDepth = std::max<uint32>(surfOutDst.depth, 1);
uint32 dstBpp = surfOutDst.bpp;
//debug_printf("Src Tex: %08X %dx%d Swizzle: %08x tm: %d fmt: %04x use: %02x\n", _swapEndianU32(srcSurface->imagePtr), _swapEndianU32(srcSurface->width), _swapEndianU32(srcSurface->height), _swapEndianU32(srcSurface->swizzle), _swapEndianU32(srcSurface->tileMode), _swapEndianU32(srcSurface->format), (uint32)srcSurface->resFlag);
//debug_printf("Dst Tex: %08X %dx%d Swizzle: %08x tm: %d fmt: %04x use: %02x\n", _swapEndianU32(dstSurface->imagePtr), _swapEndianU32(dstSurface->width), _swapEndianU32(dstSurface->height), _swapEndianU32(dstSurface->swizzle), _swapEndianU32(dstSurface->tileMode), _swapEndianU32(dstSurface->format), (uint32)dstSurface->resFlag);
bool requestGPURAMCopy = false;
bool debugTestForceCPUCopy = false;
if (srcSurface->tileMode == Latte::E_GX2TILEMODE::TM_LINEAR_SPECIAL && dstSurface->tileMode == Latte::E_GX2TILEMODE::TM_2D_TILED_THIN1)
debugTestForceCPUCopy = true;
if (srcSurface->tileMode == Latte::E_GX2TILEMODE::TM_2D_TILED_THIN1 && dstSurface->tileMode == Latte::E_GX2TILEMODE::TM_LINEAR_SPECIAL )
{
LatteAsyncCommands_queueForceTextureReadback(
srcSurface->imagePtr,
srcSurface->mipPtr,
srcSurface->swizzle,
(uint32)srcSurface->format.value(),
srcSurface->width,
srcSurface->height,
srcSurface->depth,
srcSurface->pitch,
srcSlice,
(uint32)srcSurface->dim.value(),
Latte::MakeHWTileMode(srcSurface->tileMode),
srcSurface->aa,
srcMip);
LatteAsyncCommands_waitUntilAllProcessed();
debugTestForceCPUCopy = true;
}
// send copy command to GPU
if( srcHwTileMode > 0 && srcHwTileMode < 16 && dstHwTileMode > 0 && dstHwTileMode < 16 || requestGPURAMCopy )
{
GX2ReserveCmdSpace(1+13*2);
gx2WriteGather_submit(pm4HeaderType3(IT_HLE_COPY_SURFACE_NEW, 13*2),
// src
(uint32)srcSurface->imagePtr,
(uint32)srcSurface->mipPtr,
(uint32)srcSurface->swizzle,
(uint32)srcSurface->format.value(),
(uint32)srcSurface->width,
(uint32)srcSurface->height,
(uint32)srcSurface->depth,
(uint32)srcSurface->pitch,
srcSlice,
(uint32)srcSurface->dim.value(),
(uint32)srcSurface->tileMode.value(),
(uint32)srcSurface->aa,
srcMip,
// dst
(uint32)dstSurface->imagePtr,
(uint32)dstSurface->mipPtr,
(uint32)dstSurface->swizzle,
(uint32)dstSurface->format.value(),
(uint32)dstSurface->width,
(uint32)dstSurface->height,
(uint32)dstSurface->depth,
(uint32)dstSurface->pitch,
dstSlice,
(uint32)dstSurface->dim.value(),
(uint32)dstSurface->tileMode.value(),
(uint32)dstSurface->aa,
dstMip);
}
if (requestGPURAMCopy)
return; // if RAM copy happens on the GPU side we skip it here
// manually exclude expensive CPU texture copies for some known game framebuffer textures
// todo - find a better way to solve this
bool isDynamicTexCopy = false;
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width >= 800 && srcFormat == Latte::E_GX2SURFFMT::R11_G11_B10_FLOAT); // SM3DW
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width >= 800 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM); // Trine 2
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 0xA0 && srcFormat == Latte::E_GX2SURFFMT::R32_FLOAT); // Little Inferno
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 1280 && srcFormat == Latte::E_GX2SURFFMT::R32_FLOAT); // Donkey Kong Tropical Freeze
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 640 && srcSurface->height == 320 && srcFormat == Latte::E_GX2SURFFMT::R11_G11_B10_FLOAT); // SM3DW Switch Scramble Circus
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1280 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM && srcSurface->tileMode != Latte::E_GX2TILEMODE::TM_LINEAR_ALIGNED ); // Affordable Space Adventures
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 854 && srcSurface->height == 480 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM); // Affordable Space Adventures
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 1152 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R11_G11_B10_FLOAT && (srcSurface->resFlag&GX2_RESFLAG_USAGE_COLOR_BUFFER) != 0 ); // Star Fox Zero
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 680 && srcSurface->height == 480 && srcFormat == Latte::E_GX2SURFFMT::R11_G11_B10_FLOAT && (srcSurface->resFlag&GX2_RESFLAG_USAGE_COLOR_BUFFER) != 0 ); // Star Fox Zero
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 1280 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT ); // Qube
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 322 && srcSurface->height == 182 && srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_UNORM ); // Qube
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 640 && srcSurface->height == 360 && srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT ); // Qube
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1920 && srcSurface->height == 1080 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM && dstSurface->resFlag == 0x80000003); // Cosmophony
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 854 && srcSurface->height == 480 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM && dstSurface->resFlag == 0x3); // Cosmophony
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1280 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SRGB && dstSurface->resFlag == 0x3); // The Fall
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 854 && srcSurface->height == 480 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SRGB && dstSurface->resFlag == 0x3); // The Fall
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1280 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SRGB && dstSurface->resFlag == 0x80000003); // The Fall
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1280 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SRGB && srcSurface->resFlag == 0x80000003); // Nano Assault Neo
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 1280 && srcSurface->height == 720 && srcFormat == Latte::E_GX2SURFFMT::R10_G10_B10_A2_UNORM); // Mario Party 10
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->imagePtr >= 0xF4000000 && srcSurface->width == 854 && srcSurface->height == 480 && srcFormat == Latte::E_GX2SURFFMT::R10_G10_B10_A2_UNORM); // Mario Party 10
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1920 && srcSurface->height == 1080 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM && dstSurface->resFlag == 0x3); // Hello Kitty Kruisers
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1024 && srcSurface->height == 1024 && srcFormat == Latte::E_GX2SURFFMT::R32_FLOAT && dstSurface->resFlag == 0x5); // Art Academy
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 260 && srcSurface->height == 148 && srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT && dstSurface->resFlag == 0x3); // Transformers: Rise of the Dark Spark
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1040 && srcSurface->height == 592 && srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT && dstSurface->resFlag == 0x3); // Transformers: Rise of the Dark Spark
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 854 && srcSurface->height == 480 && srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_SRGB && srcSurface->resFlag == 0x3); // Nano Assault Neo
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1024 && srcSurface->height == 576 && srcFormat == Latte::E_GX2SURFFMT::D24_S8_UNORM && srcSurface->resFlag == 0x1); // Skylanders SuperChargers
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 1152 && srcSurface->height == 648 && (srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM || srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT) && srcSurface->resFlag == 0x1); // Watch Dogs
isDynamicTexCopy = isDynamicTexCopy || (srcSurface->width == 576 && srcSurface->height == 324 && (srcFormat == Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM || srcFormat == Latte::E_GX2SURFFMT::R16_G16_B16_A16_FLOAT) && srcSurface->resFlag == 0x1); // Watch Dogs
if( isDynamicTexCopy && debugTestForceCPUCopy == false)
{
debug_printf("Software tex copy blocked\n");
return;
}
sint32 copyWidth = dstMipWidth;
sint32 copyHeight = dstMipHeight;
if (Latte::IsCompressedFormat(dstHwFormat))
{
copyWidth = (copyWidth + 3) / 4;
copyHeight = (copyHeight + 3) / 4;
}
gx2SurfaceCopySoftware(inputData, surfOutSrc.height, srcPitch, srcDepth, srcSlice, srcSwizzle, srcHwTileMode,
outputData, surfOutDst.height, dstPitch, dstDepth, dstSlice, dstSwizzle, dstHwTileMode,
copyWidth, copyHeight, dstBpp);
}
void gx2Export_GX2CopySurface(PPCInterpreter_t* hCPU)
{
GX2Surface* srcSurface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint32 srcMip = hCPU->gpr[4];
uint32 srcSlice = hCPU->gpr[5];
GX2Surface* dstSurface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[6]);
uint32 dstMip = hCPU->gpr[7];
uint32 dstSlice = hCPU->gpr[8];
gx2Surface_GX2CopySurface(srcSurface, srcMip, srcSlice, dstSurface, dstMip, dstSlice);
osLib_returnFromFunction(hCPU, 0);
}
typedef struct
{
sint32 left;
sint32 top;
sint32 right;
sint32 bottom;
}GX2Rect_t;
typedef struct
{
sint32 x;
sint32 y;
}GX2Point_t;
void gx2Export_GX2CopySurfaceEx(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GX2CopySurfaceEx(0x{:08x},{},{},0x{:08x},{},{},{},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7], hCPU->gpr[8], hCPU->gpr[9], hCPU->gpr[10], memory_readU32(hCPU->gpr[1]+0x8));
GX2Surface* srcSurface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint32 srcMip = hCPU->gpr[4];
uint32 srcSlice = hCPU->gpr[5];
GX2Surface* dstSurface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[6]);
uint32 dstMip = hCPU->gpr[7];
uint32 dstSlice = hCPU->gpr[8];
sint32 rectCount = hCPU->gpr[9];
MPTR rectSrcArrayMPTR = hCPU->gpr[10];
MPTR pointDstArrayMPTR = memory_readU32(hCPU->gpr[1]+0x8);
GX2Rect_t* rectSrc = (GX2Rect_t*)memory_getPointerFromVirtualOffset(rectSrcArrayMPTR);
GX2Point_t* rectDst = (GX2Point_t*)memory_getPointerFromVirtualOffset(pointDstArrayMPTR);
for (sint32 i = 0; i < rectCount; i++)
{
cemuLog_logDebug(LogType::Force, "rect left-top: {}/{} size: {}/{}", _swapEndianU32(rectSrc->left), _swapEndianU32(rectSrc->top), _swapEndianU32(rectSrc->right) - _swapEndianU32(rectSrc->left), _swapEndianU32(rectSrc->bottom) - _swapEndianU32(rectSrc->top));
}
#ifdef CEMU_DEBUG_ASSERT
if( rectCount != 1 )
assert_dbg();
if( srcMip != 0 )
assert_dbg();
if( srcSlice != 0 )
assert_dbg();
if( dstMip != 0 )
assert_dbg();
if( dstSlice != 0 )
assert_dbg();
#endif
for(sint32 i=0; i<rectCount; i++)
{
uint32 srcWidth = srcSurface->width;
uint32 srcHeight = srcSurface->height;
// calculate rect size
sint32 rectSrcX = (sint32)_swapEndianU32((uint32)rectSrc[i].left);
sint32 rectSrcY = (sint32)_swapEndianU32((uint32)rectSrc[i].top);
sint32 rectWidth = (sint32)_swapEndianU32((uint32)rectSrc[i].right) - rectSrcX;
sint32 rectHeight = (sint32)_swapEndianU32((uint32)rectSrc[i].bottom) - rectSrcY;
if( rectSrcX == 0 && rectSrcY == 0 && rectWidth == srcWidth && rectHeight == srcHeight )
{
// special case in which GX2CopySurfaceEx acts like GX2CopySurface()
gx2Surface_GX2CopySurface(srcSurface, srcMip, srcSlice, dstSurface, dstMip, dstSlice);
}
}
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2ResolveAAColorBuffer(PPCInterpreter_t* hCPU)
{
debug_printf("GX2ResolveAAColorBuffer(0x%08x,0x%08x,%d,%d)\n", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
GX2ColorBuffer* srcColorBuffer = (GX2ColorBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
GX2Surface* srcSurface = &srcColorBuffer->surface;
GX2Surface* dstSurface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
uint32 srcMip = _swapEndianU32(srcColorBuffer->viewMip);
uint32 dstMip = hCPU->gpr[5];
uint32 srcSlice = _swapEndianU32(srcColorBuffer->viewFirstSlice);
uint32 dstSlice = hCPU->gpr[6];
#ifdef CEMU_DEBUG_ASSERT
if( _swapEndianU32(srcColorBuffer->viewMip) != 0 || _swapEndianU32(srcColorBuffer->viewFirstSlice) != 0 )
assert_dbg();
#endif
// allocate pixel buffer
sint32 dstWidth = dstSurface->width;
sint32 dstHeight = dstSurface->height;
sint32 srcWidth = srcSurface->width;
sint32 srcHeight = srcSurface->height;
uint32 dstMipWidth = std::max(dstWidth>>dstMip, 1);
uint32 dstMipHeight = std::max(dstHeight>>dstMip, 1);
uint32 srcMipWidth = std::max(srcWidth>>srcMip, 1);
uint32 srcMipHeight = std::max(srcHeight>>srcMip, 1);
// check if surface properties match
if( srcSurface->width != dstSurface->width || srcSurface->height != dstSurface->height )
{
osLib_returnFromFunction(hCPU, 0);
return;
}
if( dstMipWidth != srcMipWidth || dstMipHeight != srcMipHeight )
{
cemu_assert_suspicious();
osLib_returnFromFunction(hCPU, 0);
return;
}
// handle format
Latte::E_GX2SURFFMT srcFormat = srcSurface->format;
Latte::E_GX2SURFFMT dstFormat = dstSurface->format;
uint32 srcBPP = Latte::GetFormatBits(srcFormat);
uint32 dstBPP = Latte::GetFormatBits(dstFormat);
sint32 srcStepX = 1;
sint32 srcStepY = 1;
sint32 dstStepX = 1;
sint32 dstStepY = 1;
auto srcHwFormat = Latte::GetHWFormat(srcFormat);
auto dstHwFormat = Latte::GetHWFormat(dstFormat);
// get texture info
LatteAddrLib::AddrSurfaceInfo_OUT surfOutSrc = {0};
GX2::GX2CalculateSurfaceInfo(srcSurface, srcMip, &surfOutSrc);
LatteAddrLib::AddrSurfaceInfo_OUT surfOutDst = {0};
GX2::GX2CalculateSurfaceInfo(dstSurface, dstMip, &surfOutDst);
// get input pointer
uint8* inputData = NULL;
cemu_assert(srcMip < srcSurface->numLevels);
if( srcMip == 0 )
inputData = (uint8*)memory_getPointerFromVirtualOffset(srcSurface->imagePtr);
else if( srcMip == 1 )
inputData = (uint8*)memory_getPointerFromVirtualOffset(srcSurface->mipPtr);
else
inputData = (uint8*)memory_getPointerFromVirtualOffset(srcSurface->mipPtr+srcSurface->mipOffset[srcMip-1]);
// get output pointer
uint8* outputData = NULL;
cemu_assert(dstMip < dstSurface->numLevels);
if( dstMip == 0 )
outputData = (uint8*)memory_getPointerFromVirtualOffset(dstSurface->imagePtr);
else if( dstMip == 1 )
outputData = (uint8*)memory_getPointerFromVirtualOffset(dstSurface->mipPtr);
else
outputData = (uint8*)memory_getPointerFromVirtualOffset(dstSurface->mipPtr+dstSurface->mipOffset[dstMip-1]);
// calculate step size for compressed textures
if( Latte::IsCompressedFormat(srcHwFormat) )
{
srcStepX = 4;
srcStepY = 4;
}
if(Latte::IsCompressedFormat(dstHwFormat) )
{
dstStepX = 4;
dstStepY = 4;
}
if( srcStepX != dstStepX || srcStepY != dstStepY )
assert_dbg();
if( srcHwFormat != dstHwFormat )
{
// mismatching format
debug_printf("GX2CopySurface(): Format mismatch\n");
osLib_returnFromFunction(hCPU, 0);
return;
}
// src
uint32 srcPitch = surfOutSrc.pitch;
uint32 srcSwizzle = srcSurface->swizzle;
uint32 srcPipeSwizzle = (srcSwizzle>>8)&1;
uint32 srcBankSwizzle = ((srcSwizzle>>9)&3);
uint32 srcTileMode = (uint32)surfOutSrc.hwTileMode;
uint32 srcDepth = std::max<uint32>(surfOutSrc.depth, 1);
// dst
uint32 dstPitch = surfOutDst.pitch;
uint32 dstSwizzle = dstSurface->swizzle;
uint32 dstPipeSwizzle = (dstSwizzle>>8)&1;
uint32 dstBankSwizzle = ((dstSwizzle>>9)&3);
uint32 dstTileMode = (uint32)surfOutDst.hwTileMode;
uint32 dstDepth = std::max<uint32>(surfOutDst.depth, 1);
// send copy command to GPU
GX2ReserveCmdSpace(1 + 13 * 2);
gx2WriteGather_submit(pm4HeaderType3(IT_HLE_COPY_SURFACE_NEW, 13 * 2),
// src
(uint32)srcSurface->imagePtr,
(uint32)srcSurface->mipPtr,
(uint32)srcSurface->swizzle,
(uint32)srcSurface->format.value(),
(uint32)srcSurface->width,
(uint32)srcSurface->height,
(uint32)srcSurface->depth,
(uint32)srcSurface->pitch,
srcSlice,
(uint32)srcSurface->dim.value(),
(uint32)srcSurface->tileMode.value(),
(uint32)srcSurface->aa,
srcMip,
// dst
(uint32)dstSurface->imagePtr,
(uint32)dstSurface->mipPtr,
(uint32)dstSurface->swizzle,
(uint32)dstSurface->format.value(),
(uint32)dstSurface->width,
(uint32)dstSurface->height,
(uint32)dstSurface->depth,
(uint32)dstSurface->pitch,
dstSlice,
(uint32)dstSurface->dim.value(),
(uint32)dstSurface->tileMode.value(),
(uint32)dstSurface->aa,
dstMip);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2ConvertDepthBufferToTextureSurface(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2ConvertDepthBufferToTextureSurface(0x{:x}, 0x{:x}, {}, {})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
GX2DepthBuffer* depthBuffer = (GX2DepthBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
GX2Surface* dstSurface = (GX2Surface*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
uint32 dstMip = hCPU->gpr[5];
uint32 dstSlice = hCPU->gpr[6];
if (dstMip != 0 || dstSlice != 0)
debugBreakpoint();
// get texture info
LatteAddrLib::AddrSurfaceInfo_OUT surfOutSrc = { 0 };
GX2::GX2CalculateSurfaceInfo(&depthBuffer->surface, 0, &surfOutSrc);
LatteAddrLib::AddrSurfaceInfo_OUT surfOutDst = { 0 };
GX2::GX2CalculateSurfaceInfo(dstSurface, 0, &surfOutDst);
if (depthBuffer->surface.imagePtr == dstSurface->imagePtr)
{
// in-place re-tiling doesn't need any actual copy operation?
if (dstMip != 0 || dstSlice != 0)
debugBreakpoint();
debug_printf("In-place re-tiling\n");
osLib_returnFromFunction(hCPU, 0);
return;
}
// note: Do not trust values from the input GX2Surface* structs but rely on surfOutDst/surfOutSrc instead if possible.
// src
uint32 srcPitch = surfOutSrc.pitch;
uint32 srcSwizzle = depthBuffer->surface.swizzle;
uint32 srcPipeSwizzle = (srcSwizzle >> 8) & 1;
uint32 srcBankSwizzle = ((srcSwizzle >> 9) & 3);
uint32 srcTileMode = (uint32)surfOutSrc.hwTileMode;
uint32 srcDepth = std::max<uint32>(surfOutSrc.depth, 1);
// dst
uint32 dstPitch = surfOutDst.pitch;
uint32 dstSwizzle = dstSurface->swizzle;
uint32 dstPipeSwizzle = (dstSwizzle >> 8) & 1;
uint32 dstBankSwizzle = ((dstSwizzle >> 9) & 3);
uint32 dstTileMode = (uint32)surfOutDst.hwTileMode;
uint32 dstDepth = srcDepth;
sint32 srcMip = 0;
uint32 numSlices = std::max<uint32>(_swapEndianU32(depthBuffer->viewNumSlices), 1);
GX2ReserveCmdSpace((1 + 13 * 2) * numSlices);
for (uint32 subSliceIndex = 0; subSliceIndex < numSlices; subSliceIndex++)
{
// send copy command to GPU
gx2WriteGather_submit(pm4HeaderType3(IT_HLE_COPY_SURFACE_NEW, 13 * 2),
// src
(uint32)(depthBuffer->surface.imagePtr),
(uint32)(depthBuffer->surface.mipPtr),
(uint32)(depthBuffer->surface.swizzle),
(uint32)(depthBuffer->surface.format.value()),
(uint32)(depthBuffer->surface.width),
(uint32)(depthBuffer->surface.height),
(uint32)(depthBuffer->surface.depth),
(uint32)(depthBuffer->surface.pitch),
(uint32)(depthBuffer->viewFirstSlice) + subSliceIndex,
(uint32)(depthBuffer->surface.dim.value()),
(uint32)(depthBuffer->surface.tileMode.value()),
(uint32)(depthBuffer->surface.aa),
srcMip,
// dst
(uint32)(dstSurface->imagePtr),
(uint32)(dstSurface->mipPtr),
(uint32)(dstSurface->swizzle),
(uint32)(dstSurface->format.value()),
(uint32)(dstSurface->width),
(uint32)(dstSurface->height),
(uint32)(dstSurface->depth),
(uint32)(dstSurface->pitch),
dstSlice + subSliceIndex,
(uint32)(dstSurface->dim.value()),
(uint32)(dstSurface->tileMode.value()),
(uint32)(dstSurface->aa),
dstMip);
}
osLib_returnFromFunction(hCPU, 0);
}
namespace GX2
{
void GX2SurfaceCopyInit()
{
osLib_addFunction("gx2", "GX2CopySurface", gx2Export_GX2CopySurface);
osLib_addFunction("gx2", "GX2CopySurfaceEx", gx2Export_GX2CopySurfaceEx);
osLib_addFunction("gx2", "GX2ResolveAAColorBuffer", gx2Export_GX2ResolveAAColorBuffer);
osLib_addFunction("gx2", "GX2ConvertDepthBufferToTextureSurface", gx2Export_GX2ConvertDepthBufferToTextureSurface);
}
};
void gx2CopySurfaceTest()
{
return;
BenchmarkTimer bt;
// copy 0
bt.Start();
for(sint32 i=0; i<100; i++)
gx2SurfaceCopySoftware(
memory_base + 0x10000000, 256, 256, 1, 0, 0, 4,
memory_base + 0x20000000, 256, 256, 1, 0, 0, 4,
64, 64, 32
);
bt.Stop();
debug_printf("Copy 0 - %lfms\n", bt.GetElapsedMilliseconds());
// copy 1
bt.Start();
for (sint32 i = 0; i < 100; i++)
gx2SurfaceCopySoftware(
memory_base + 0x11000000, 256, 256, 1, 0, 0, 4,
memory_base + 0x21000000, 256, 256, 1, 0, 0, 2,
64, 64, 32
);
bt.Stop();
debug_printf("Copy 1 - %lfms\n", bt.GetElapsedMilliseconds());
// copy 2
bt.Start();
for (sint32 i = 0; i < 100; i++)
gx2SurfaceCopySoftware(
memory_base + 0x12000000, 256, 256, 1, 0, 0, 1,
memory_base + 0x22000000, 256, 256, 1, 0, 0, 4,
64, 64, 128
);
bt.Stop();
debug_printf("Copy 2 - %lfms\n", bt.GetElapsedMilliseconds());
// copy 3
bt.Start();
for (sint32 i = 0; i < 100; i++)
gx2SurfaceCopySoftware(
memory_base + 0x12000000, 256, 256, 1, 0, 0, 4,
memory_base + 0x22000000, 256, 256, 1, 0, 0, 4,
64, 512, 32
);
bt.Stop();
debug_printf("Copy 3 - %lfms\n", bt.GetElapsedMilliseconds());
cemu_assert_debug(false);
// with bpp switch optimized away:
// Copy 0 - 19.777100ms
// Copy 1 - 14.311300ms
// Copy 2 - 10.837700ms
// Copy 3 - 158.174400ms
// Copy 0 - 19.846800ms
// Copy 1 - 14.054000ms
// Copy 2 - 11.013500ms
// Copy 3 - 159.916000ms
// with fast path added:
// Copy 0 - 0.222400ms
// Copy 1 - 14.125700ms
// Copy 2 - 13.298100ms
// Copy 3 - 1.764500ms
// with shared offset:
// Copy 0 - 0.143300ms
// Copy 1 - 13.814200ms
// Copy 2 - 10.309500ms
// Copy 3 - 1.191900ms
}
| 32,896
|
C++
|
.cpp
| 682
| 45.570381
| 331
| 0.735444
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,066
|
GX2_Query.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Query.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "GX2.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/CafeSystem.h"
#include "GX2_Query.h"
#define LATTE_GC_NUM_RB 2
#define _QUERY_REG_COUNT 8 // each reg/result is 64bits, little endian
namespace GX2
{
struct GX2Query
{
// 4*2 sets of uint64 results
uint32 reg[_QUERY_REG_COUNT * 2];
};
static_assert(sizeof(GX2Query) == 0x40);
void _BeginOcclusionQuery(GX2Query* queryInfo, bool isGPUQuery)
{
if (isGPUQuery)
{
uint64 titleId = CafeSystem::GetForegroundTitleId();
if (titleId == 0x00050000101c4c00ULL || titleId == 0x00050000101c4d00 || titleId == 0x0005000010116100) // XCX EU, US, JPN
{
// in XCX queries are used to determine if certain objects are visible
// if we are not setting the result fast enough and the query still holds a value of 0 (which is the default for GPU queries)
// then XCX will not render affected objects, causing flicker
// note: This is a very old workaround. It may no longer be necessary since the introduction of full sync. Investigate
*(uint64*)(queryInfo->reg + 2) = 0x100000;
}
else
{
GX2ReserveCmdSpace(5 * _QUERY_REG_COUNT);
MPTR queryInfoPhys = memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(queryInfo));
for (sint32 i = 0; i < _QUERY_REG_COUNT; i++)
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_MEM_WRITE, 4));
gx2WriteGather_submitU32AsBE((queryInfoPhys + i * 8) | 0x2);
gx2WriteGather_submitU32AsBE(0x20000); // 0x20000 -> ?
uint32 v = 0;
if (i >= LATTE_GC_NUM_RB * 2)
v |= 0x80000000;
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(v);
}
}
}
else
{
memset(queryInfo, 0, 0x10); // size maybe GPU7_GC_NUM_RB*2*4 ?
queryInfo->reg[LATTE_GC_NUM_RB * 4 + 0] = 0;
queryInfo->reg[LATTE_GC_NUM_RB * 4 + 1] = _swapEndianU32('OCPU');
}
// todo: Set mmDB_RENDER_CONTROL
}
void GX2QueryBegin(uint32 queryType, GX2Query* query)
{
if (queryType == GX2_QUERY_TYPE_OCCLUSION_CPU)
{
_BeginOcclusionQuery(query, false);
}
else if (queryType == GX2_QUERY_TYPE_OCCLUSION_GPU)
{
_BeginOcclusionQuery(query, true);
}
else
{
debug_printf("GX2QueryBegin(): Unsupported type %d\n", queryType);
debugBreakpoint();
return;
}
// HLE packet
GX2ReserveCmdSpace(2);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_BEGIN_OCCLUSION_QUERY, 1));
gx2WriteGather_submitU32AsBE(MEMPTR<GX2Query>(query).GetMPTR());
}
void GX2QueryEnd(uint32 queryType, GX2Query* query)
{
GX2ReserveCmdSpace(2);
if (queryType == GX2_QUERY_TYPE_OCCLUSION_CPU || queryType == GX2_QUERY_TYPE_OCCLUSION_GPU)
{
// HLE packet
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_HLE_END_OCCLUSION_QUERY, 1));
gx2WriteGather_submitU32AsBE(MEMPTR<GX2Query>(query).GetMPTR());
}
else
{
debug_printf("GX2QueryBegin(): Unsupported %d\n", queryType);
debugBreakpoint();
return;
}
}
uint32 GX2QueryGetOcclusionResult(GX2Query* query, uint64be* resultOut)
{
if (query->reg[LATTE_GC_NUM_RB * 4 + 1] == _swapEndianU32('OCPU') && query->reg[LATTE_GC_NUM_RB * 4 + 0] == 0)
{
// CPU query result not ready
return GX2_FALSE;
}
uint64 startValue = *(uint64*)(query->reg + 0);
uint64 endValue = *(uint64*)(query->reg + 2);
if ((startValue & 0x8000000000000000ULL) || (endValue & 0x8000000000000000ULL))
{
return GX2_FALSE;
}
*resultOut = endValue - startValue;
return GX2_TRUE;
}
void GX2QueryBeginConditionalRender(uint32 queryType, GX2Query* query, uint32 dontWaitBool, uint32 pixelsMustPassBool)
{
GX2ReserveCmdSpace(3);
uint32 flags = 0;
if (pixelsMustPassBool)
flags |= (1<<31);
if (queryType == GX2_QUERY_TYPE_OCCLUSION_GPU)
flags |= (1 << 13);
else
flags |= (2 << 13);
flags |= ((dontWaitBool != 0) << 19);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_PREDICATION, 2));
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(MEMPTR<GX2Query>(query).GetMPTR()));
gx2WriteGather_submitU32AsBE(flags);
}
void GX2QueryEndConditionalRender()
{
GX2ReserveCmdSpace(3);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_PREDICATION, 2));
gx2WriteGather_submitU32AsBE(MPTR_NULL);
gx2WriteGather_submitU32AsBE(0); // unknown / todo
}
void GX2QueryInit()
{
cafeExportRegister("gx2", GX2QueryBegin, LogType::GX2);
cafeExportRegister("gx2", GX2QueryEnd, LogType::GX2);
cafeExportRegister("gx2", GX2QueryGetOcclusionResult, LogType::GX2);
cafeExportRegister("gx2", GX2QueryBeginConditionalRender, LogType::GX2);
cafeExportRegister("gx2", GX2QueryEndConditionalRender, LogType::GX2);
}
};
| 4,704
|
C++
|
.cpp
| 138
| 30.804348
| 129
| 0.719244
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,067
|
GX2_Shader.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Shader.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "GX2.h"
#include "GX2_Shader.h"
#include "Cafe/HW/Latte/Core/LatteConst.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/ISA/LatteInstructions.h"
uint32 memory_getVirtualOffsetFromPointer(void* ptr); // remove once we updated everything to MEMPTR
namespace GX2
{
using namespace Latte;
LatteConst::VertexFetchEndianMode _getVtxFormatEndianSwapDefault(uint32 vertexFormat)
{
switch (vertexFormat)
{
case 0:
case 1:
case 4:
case 10:
return LatteConst::VertexFetchEndianMode::SWAP_NONE; // 0
case 2:
case 3:
case 7:
case 8:
case 14:
case 15:
return LatteConst::VertexFetchEndianMode::SWAP_U16; // 1
case 5:
case 6:
case 9:
case 11:
case 12:
case 13:
case 16:
case 17:
case 18:
case 19:
return LatteConst::VertexFetchEndianMode::SWAP_U32; // 2
default:
break;
}
cemu_assert_suspicious();
return LatteConst::VertexFetchEndianMode::SWAP_NONE;
}
uint32 rawFormatToFetchFormat[] =
{
1, 2, 5, 6,
7, 0xD, 0xE, 0xF,
0x10, 0x16, 0x1A, 0x19,
0x1D, 0x1E, 0x1F, 0x20,
0x2F, 0x30, 0x22, 0x23,
};
struct GX2AttribDescription
{
/* +0x00 */ uint32 location;
/* +0x04 */ uint32 buffer;
/* +0x08 */ uint32be offset;
/* +0x0C */ uint32 format;
/* +0x10 */ uint32 indexType;
/* +0x14 */ uint32 aluDivisor;
/* +0x18 */ uint32 destSel;
/* +0x1C */ betype<LatteConst::VertexFetchEndianMode> endianSwap;
};
static_assert(sizeof(GX2AttribDescription) == 0x20);
static_assert(sizeof(betype<LatteConst::VertexFetchEndianMode>) == 0x4);
// calculate size of CF program subpart, includes alignment padding for clause instructions
size_t _calcFetchShaderCFCodeSize(uint32 attributeCount, GX2FetchShader::FetchShaderType fetchShaderType, uint32 tessellationMode)
{
cemu_assert_debug(fetchShaderType == GX2FetchShader::FetchShaderType::NO_TESSELATION);
cemu_assert_debug(tessellationMode == 0);
uint32 numCFInstructions = ((attributeCount + 15) / 16) + 1; // one VTX clause can have up to 16 instructions + final CF instruction is RETURN
size_t cfSize = numCFInstructions * 8;
cfSize = (cfSize + 0xF) & ~0xF; // pad to 16 byte alignment
return cfSize;
}
size_t _calcFetchShaderClauseCodeSize(uint32 attributeCount, GX2FetchShader::FetchShaderType fetchShaderType, uint32 tessellationMode)
{
cemu_assert_debug(fetchShaderType == GX2FetchShader::FetchShaderType::NO_TESSELATION);
cemu_assert_debug(tessellationMode == 0);
uint32 numClauseInstructions = attributeCount;
size_t clauseSize = numClauseInstructions * 16;
return clauseSize;
}
void _writeFetchShaderCFCode(void* programBufferOut, uint32 attributeCount, GX2FetchShader::FetchShaderType fetchShaderType, uint32 tessellationMode)
{
LatteCFInstruction* cfInstructionWriter = (LatteCFInstruction*)programBufferOut;
uint32 attributeIndex = 0;
uint32 cfSize = (uint32)_calcFetchShaderCFCodeSize(attributeCount, fetchShaderType, tessellationMode);
while (attributeIndex < attributeCount)
{
LatteCFInstruction_DEFAULT defaultInstr;
defaultInstr.setField_Opcode(LatteCFInstruction::INST_VTX_TC);
defaultInstr.setField_COUNT(std::min(attributeCount - attributeIndex, 16u));
defaultInstr.setField_ADDR(cfSize + attributeIndex*16);
memcpy(cfInstructionWriter, &defaultInstr, sizeof(LatteCFInstruction));
attributeIndex += 16;
cfInstructionWriter++;
}
// write RETURN instruction
LatteCFInstruction_DEFAULT returnInstr;
returnInstr.setField_Opcode(LatteCFInstruction::INST_RETURN);
returnInstr.setField_BARRIER(true);
memcpy(cfInstructionWriter, &returnInstr, sizeof(LatteCFInstruction));
}
void _writeFetchShaderVTXCode(GX2FetchShader* fetchShader, void* programOut, uint32 attributeCount, GX2AttribDescription* attributeDescription, GX2FetchShader::FetchShaderType fetchShaderType, uint32 tessellationMode)
{
uint8* writePtr = (uint8*)programOut;
// one instruction per attribute (hardcoded into _writeFetchShaderCFCode)
for (uint32 i = 0; i < attributeCount; i++)
{
uint32 attrFormat = _swapEndianU32(attributeDescription[i].format);
uint32 attrDestSel = _swapEndianU32(attributeDescription[i].destSel);
uint32 attrLocation = _swapEndianU32(attributeDescription[i].location);
uint32 attrBufferId = _swapEndianU32(attributeDescription[i].buffer);
uint32 attrIndexType = _swapEndianU32(attributeDescription[i].indexType);
uint32 attrAluDivisor = _swapEndianU32(attributeDescription[i].aluDivisor);
cemu_assert_debug(attrIndexType <= 1);
LatteConst::VertexFetchEndianMode endianSwap = attributeDescription[i].endianSwap;
if (endianSwap == LatteConst::VertexFetchEndianMode::SWAP_DEFAULT) // use per-format default
endianSwap = _getVtxFormatEndianSwapDefault(attrFormat & 0x3F);
uint32 srcSelX = 0; // this field is used to store the divisor index/mode (0 -> per-vertex index, 1 -> alu divisor 0, 2 -> alu divisor 1, 3 -> per-instance index)
if (attrIndexType == 0)
{
srcSelX = 0; // increase index per vertex
}
else if (attrIndexType == 1)
{
// instance based index
if (attrAluDivisor == 1)
{
// special encoding if alu divisor is 1
srcSelX = 3;
}
else
{
cemu_assert_debug(attrAluDivisor != 0); // divisor should not be zero if instance based index is selected?
// store alu divisor in divisor table (up to two entries)
uint32 numDivisors = _swapEndianU32(fetchShader->divisorCount);
bool divisorFound = false;
for (uint32 i = 0; i < numDivisors; i++)
{
if (fetchShader->divisors[i] == attrAluDivisor)
{
srcSelX = i != 0 ? 2 : 1;
divisorFound = true;
break;
}
}
if (divisorFound == false)
{
// add new divisor
if (numDivisors >= 2)
{
cemu_assert_debug(false); // not enough space for additional divisor
}
else
{
srcSelX = numDivisors != 0 ? 2 : 1;
fetchShader->divisors[numDivisors] = attrAluDivisor;
numDivisors++;
fetchShader->divisorCount = _swapEndianU32(numDivisors);
}
}
}
}
else
{
cemu_assert_debug(false);
}
// convert attribute format to fetch format
uint32 fetchFormat = rawFormatToFetchFormat[attrFormat & 0x3F] & 0x3F;
uint32 nfa = 0;
if ((attrFormat & 0x800) != 0)
nfa = 2;
else if ((attrFormat & 0x100) != 0)
nfa = 1;
else
nfa = 0;
LatteClauseInstruction_VTX vtxInstruction;
vtxInstruction.setField_VTX_INST(LatteClauseInstruction_VTX::VTX_INST::_VTX_INST_SEMANTIC);
vtxInstruction.setFieldSEM_SEMANTIC_ID(attrLocation&0xFF);
vtxInstruction.setField_BUFFER_ID(attrBufferId + 0xA0);
vtxInstruction.setField_FETCH_TYPE((LatteConst::VertexFetchType2)attrIndexType);
vtxInstruction.setField_SRC_SEL_X((LatteClauseInstruction_VTX::SRC_SEL)srcSelX);
vtxInstruction.setField_DATA_FORMAT((LatteConst::VertexFetchFormat)fetchFormat);
vtxInstruction.setField_NUM_FORMAT_ALL((LatteClauseInstruction_VTX::NUM_FORMAT_ALL)nfa);
vtxInstruction.setField_OFFSET(attributeDescription[i].offset);
if ((attrFormat & 0x200) != 0)
vtxInstruction.setField_FORMAT_COMP_ALL(LatteClauseInstruction_VTX::FORMAT_COMP::COMP_SIGNED);
vtxInstruction.setField_ENDIAN_SWAP((LatteConst::VertexFetchEndianMode)endianSwap);
vtxInstruction.setField_DST_SEL(0, (LatteClauseInstruction_VTX::DST_SEL)((attrDestSel >> 24) & 0x7));
vtxInstruction.setField_DST_SEL(1, (LatteClauseInstruction_VTX::DST_SEL)((attrDestSel >> 16) & 0x7));
vtxInstruction.setField_DST_SEL(2, (LatteClauseInstruction_VTX::DST_SEL)((attrDestSel >> 8) & 0x7));
vtxInstruction.setField_DST_SEL(3, (LatteClauseInstruction_VTX::DST_SEL)((attrDestSel >> 0) & 0x7));
memcpy(writePtr, &vtxInstruction, 16);
writePtr += 16;
}
}
uint32 GX2CalcFetchShaderSizeEx(uint32 attributeCount, GX2FetchShader::FetchShaderType fetchShaderType, uint32 tessellationMode)
{
cemu_assert_debug(fetchShaderType == GX2FetchShader::FetchShaderType::NO_TESSELATION); // other types are todo
cemu_assert_debug(tessellationMode == 0); // other modes are todo
uint32 finalSize =
(uint32)_calcFetchShaderCFCodeSize(attributeCount, fetchShaderType, tessellationMode) +
(uint32)_calcFetchShaderClauseCodeSize(attributeCount, fetchShaderType, tessellationMode);
return finalSize;
}
void GX2InitFetchShaderEx(GX2FetchShader* fetchShader, void* programBufferOut, uint32 attributeCount, GX2AttribDescription* attributeDescription, GX2FetchShader::FetchShaderType fetchShaderType, uint32 tessellationMode)
{
cemu_assert_debug(fetchShaderType == GX2FetchShader::FetchShaderType::NO_TESSELATION);
cemu_assert_debug(tessellationMode == 0);
/*
Fetch shader program:
[CF_PROGRAM]
[Last CF instruction: 0x0 0x8A000000 (INST_RETURN)]
[PAD_TO_16_ALIGNMENT]
[CLAUSES]
*/
memset(fetchShader, 0x00, sizeof(GX2FetchShader));
fetchShader->attribCount = _swapEndianU32(attributeCount);
fetchShader->shaderPtr = (MPTR)_swapEndianU32(memory_getVirtualOffsetFromPointer(programBufferOut));
uint8* shaderStart = (uint8*)programBufferOut;
uint8* shaderOutput = shaderStart;
_writeFetchShaderCFCode(shaderOutput, attributeCount, fetchShaderType, tessellationMode);
shaderOutput += _calcFetchShaderCFCodeSize(attributeCount, fetchShaderType, tessellationMode);
_writeFetchShaderVTXCode(fetchShader, shaderOutput, attributeCount, attributeDescription, fetchShaderType, tessellationMode);
shaderOutput += _calcFetchShaderClauseCodeSize(attributeCount, fetchShaderType, tessellationMode);
uint32 shaderSize = (uint32)(shaderOutput - shaderStart);
cemu_assert_debug(shaderSize == GX2CalcFetchShaderSizeEx(attributeCount, GX2FetchShader::FetchShaderType::NO_TESSELATION, tessellationMode));
fetchShader->shaderSize = _swapEndianU32((uint32)(shaderOutput - shaderStart));
fetchShader->reg_SQ_PGM_RESOURCES_FS = Latte::LATTE_SQ_PGM_RESOURCES_FS().set_NUM_GPRS(2); // todo - affected by tesselation params?
}
uint32 GX2GetVertexShaderGPRs(GX2VertexShader* vertexShader)
{
return vertexShader->regs.SQ_PGM_RESOURCES_VS.value().get_NUM_GPRS();
}
uint32 GX2GetVertexShaderStackEntries(GX2VertexShader* vertexShader)
{
return vertexShader->regs.SQ_PGM_RESOURCES_VS.value().get_NUM_STACK_ENTRIES();
}
uint32 GX2GetPixelShaderGPRs(GX2PixelShader_t* pixelShader)
{
return _swapEndianU32(pixelShader->regs[0])&0xFF;
}
uint32 GX2GetPixelShaderStackEntries(GX2PixelShader_t* pixelShader)
{
return (_swapEndianU32(pixelShader->regs[0]>>8))&0xFF;
}
void GX2SetFetchShader(GX2FetchShader* fetchShaderPtr)
{
GX2ReserveCmdSpace(11);
cemu_assert_debug((_swapEndianU32(fetchShaderPtr->shaderPtr) & 0xFF) == 0);
gx2WriteGather_submit(
// setup fetch shader
pm4HeaderType3(IT_SET_CONTEXT_REG, 1+5),
Latte::REGADDR::SQ_PGM_START_FS-0xA000,
_swapEndianU32(fetchShaderPtr->shaderPtr)>>8,
_swapEndianU32(fetchShaderPtr->shaderSize)>>3,
0x10000, // ukn (ring buffer size?)
0x10000, // ukn (ring buffer size?)
fetchShaderPtr->reg_SQ_PGM_RESOURCES_FS,
// write instance step
pm4HeaderType3(IT_SET_CONTEXT_REG, 1+2),
Latte::REGADDR::VGT_INSTANCE_STEP_RATE_0-0xA000,
fetchShaderPtr->divisors[0],
fetchShaderPtr->divisors[1]);
}
void GX2SetVertexShader(GX2VertexShader* vertexShader)
{
GX2ReserveCmdSpace(100);
MPTR shaderProgramAddr;
uint32 shaderProgramSize;
if (vertexShader->shaderPtr)
{
// without R API
shaderProgramAddr = vertexShader->shaderPtr.GetMPTR();
shaderProgramSize = vertexShader->shaderSize;
}
else
{
shaderProgramAddr = vertexShader->rBuffer.GetVirtualAddr();
shaderProgramSize = vertexShader->rBuffer.GetSize();
}
cemu_assert_debug(shaderProgramAddr != 0);
cemu_assert_debug(shaderProgramSize != 0);
if (vertexShader->shaderMode == GX2_SHADER_MODE::GEOMETRY_SHADER)
{
// in geometry shader mode the vertex shader is written to _ES register and almost all vs control registers are set by GX2SetGeometryShader
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 6),
Latte::REGADDR::SQ_PGM_START_ES-0xA000,
memory_virtualToPhysical(shaderProgramAddr)>>8,
shaderProgramSize>>3,
0x100000,
0x100000,
vertexShader->regs.SQ_PGM_RESOURCES_VS); // SQ_PGM_RESOURCES_VS/SQ_PGM_RESOURCES_ES
}
else
{
gx2WriteGather_submit(
/* vertex shader program */
pm4HeaderType3(IT_SET_CONTEXT_REG, 6),
Latte::REGADDR::SQ_PGM_START_VS-0xA000,
memory_virtualToPhysical(shaderProgramAddr)>>8, // physical address
shaderProgramSize>>3,
0x100000,
0x100000,
vertexShader->regs.SQ_PGM_RESOURCES_VS, // SQ_PGM_RESOURCES_VS/ES
/* primitive id enable */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::VGT_PRIMITIVEID_EN-0xA000,
vertexShader->regs.VGT_PRIMITIVEID_EN,
/* output config */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::SPI_VS_OUT_CONFIG-0xA000,
vertexShader->regs.SPI_VS_OUT_CONFIG,
/* PA_CL_VS_OUT_CNTL */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::PA_CL_VS_OUT_CNTL-0xA000,
vertexShader->regs.PA_CL_VS_OUT_CNTL
);
cemu_assert_debug(vertexShader->regs.SPI_VS_OUT_CONFIG.value().get_VS_PER_COMPONENT() == false); // not handled on the GPU side
uint32 numOutputIds = vertexShader->regs.vsOutIdTableSize;
numOutputIds = std::min<uint32>(numOutputIds, 0xA);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+numOutputIds));
gx2WriteGather_submitU32AsBE(Latte::REGADDR::SPI_VS_OUT_ID_0-0xA000);
for(uint32 i=0; i<numOutputIds; i++)
gx2WriteGather_submitU32AsBE(vertexShader->regs.LATTE_SPI_VS_OUT_ID_N[i].value().getRawValue());
// todo: SQ_PGM_CF_OFFSET_VS
// todo: VGT_STRMOUT_BUFFER_EN
// stream out
if (vertexShader->usesStreamOut != 0)
{
// stride 0
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::VGT_STRMOUT_VTX_STRIDE_0-0xA000,
vertexShader->streamOutVertexStride[0]>>2,
// stride 1
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::VGT_STRMOUT_VTX_STRIDE_1-0xA000,
vertexShader->streamOutVertexStride[1]>>2,
// stride 2
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::VGT_STRMOUT_VTX_STRIDE_2-0xA000,
vertexShader->streamOutVertexStride[2]>>2,
// stride 3
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::VGT_STRMOUT_VTX_STRIDE_3-0xA000,
vertexShader->streamOutVertexStride[3]>>2);
}
}
// update semantic table
uint32 vsSemanticTableSize = vertexShader->regs.semanticTableSize;
if (vsSemanticTableSize > 0)
{
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1+1),
Latte::REGADDR::SQ_VTX_SEMANTIC_CLEAR-0xA000,
0xFFFFFFFF);
if (vsSemanticTableSize == 0)
{
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 1+1),
Latte::REGADDR::SQ_VTX_SEMANTIC_0-0xA000,
0xFFFFFFFF);
}
else
{
uint32* vsSemanticTable = (uint32*)vertexShader->regs.SQ_VTX_SEMANTIC_N;
vsSemanticTableSize = std::min<uint32>(vsSemanticTableSize, 32);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+vsSemanticTableSize));
gx2WriteGather_submitU32AsBE(Latte::REGADDR::SQ_VTX_SEMANTIC_0-0xA000);
gx2WriteGather_submitU32AsLEArray(vsSemanticTable, vsSemanticTableSize);
}
}
}
void _GX2SubmitUniformReg(uint32 offsetRegBase, uint32 aluRegisterOffset, uint32be* dataWords, uint32 sizeInU32s)
{
if(aluRegisterOffset&0x8000)
{
cemuLog_logDebug(LogType::Force, "_GX2SubmitUniformReg(): Unhandled loop const special case or invalid offset");
return;
}
if((aluRegisterOffset+sizeInU32s) > 0x400)
{
cemuLog_logOnce(LogType::APIErrors, "GX2SetVertexUniformReg values are out of range (offset {} + size {} must be equal or smaller than 1024)", aluRegisterOffset, sizeInU32s);
}
if( (sizeInU32s&3) != 0)
{
cemuLog_logOnce(LogType::APIErrors, "GX2Set*UniformReg must be called with a size that is a multiple of 4 (size: {:})", sizeInU32s);
sizeInU32s &= ~3;
}
GX2ReserveCmdSpace(2 + sizeInU32s);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_ALU_CONST, 1 + sizeInU32s), offsetRegBase + aluRegisterOffset);
gx2WriteGather_submitU32AsLEArray((uint32*)dataWords, sizeInU32s);
}
void GX2SetVertexUniformReg(uint32 offset, uint32 sizeInU32s, uint32be* values)
{
_GX2SubmitUniformReg(0x400, offset, values, sizeInU32s);
}
void GX2SetPixelUniformReg(uint32 offset, uint32 sizeInU32s, uint32be* values)
{
_GX2SubmitUniformReg(0, offset, values, sizeInU32s);
}
void GX2ShaderInit()
{
cafeExportRegister("gx2", GX2CalcFetchShaderSizeEx, LogType::GX2);
cafeExportRegister("gx2", GX2InitFetchShaderEx, LogType::GX2);
cafeExportRegister("gx2", GX2GetVertexShaderGPRs, LogType::GX2);
cafeExportRegister("gx2", GX2GetVertexShaderStackEntries, LogType::GX2);
cafeExportRegister("gx2", GX2GetPixelShaderGPRs, LogType::GX2);
cafeExportRegister("gx2", GX2GetPixelShaderStackEntries, LogType::GX2);
cafeExportRegister("gx2", GX2SetFetchShader, LogType::GX2);
cafeExportRegister("gx2", GX2SetVertexShader, LogType::GX2);
cafeExportRegister("gx2", GX2SetVertexUniformReg, LogType::GX2);
cafeExportRegister("gx2", GX2SetPixelUniformReg, LogType::GX2);
}
}
| 17,392
|
C++
|
.cpp
| 418
| 37.705742
| 220
| 0.751758
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,068
|
GX2_shader_legacy.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_shader_legacy.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "GX2.h"
#include "GX2_Shader.h"
void gx2Export_GX2SetPixelShader(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetPixelShader(0x{:08x})", hCPU->gpr[3]);
GX2ReserveCmdSpace(100);
GX2PixelShader_t* pixelShader = (GX2PixelShader_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
MPTR shaderProgramAddr;
uint32 shaderProgramSize;
if( _swapEndianU32(pixelShader->shaderPtr) != MPTR_NULL )
{
// old format
shaderProgramAddr = _swapEndianU32(pixelShader->shaderPtr);
shaderProgramSize = _swapEndianU32(pixelShader->shaderSize);
}
else
{
shaderProgramAddr = pixelShader->rBuffer.GetVirtualAddr();
shaderProgramSize = pixelShader->rBuffer.GetSize();
}
gx2WriteGather_submit(
/* pixel shader program */
pm4HeaderType3(IT_SET_CONTEXT_REG, 6),
mmSQ_PGM_START_PS - 0xA000,
memory_virtualToPhysical(shaderProgramAddr)>>8, // address
shaderProgramSize>>3, // size
0x100000,
0x100000,
_swapEndianU32(pixelShader->regs[0]), // ukn
/* setup pixel shader input control */
pm4HeaderType3(IT_SET_CONTEXT_REG, 3),
mmSPI_PS_IN_CONTROL_0-0xA000,
_swapEndianU32(pixelShader->regs[2]),
_swapEndianU32(pixelShader->regs[3]));
// setup pixel shader extended inputs control
uint32 numInputs = _swapEndianU32(pixelShader->regs[4]);
if( numInputs > 0x20 )
numInputs = 0x20;
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+numInputs));
gx2WriteGather_submitU32AsBE(mmSPI_PS_INPUT_CNTL_0-0xA000);
for(uint32 i=0; i<numInputs; i++)
{
uint32 inputData = _swapEndianU32(pixelShader->regs[5+i]);
gx2WriteGather_submitU32AsBE(inputData);
}
gx2WriteGather_submit(
/* mmCB_SHADER_MASK */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
mmCB_SHADER_MASK-0xA000,
_swapEndianU32(pixelShader->regs[37]),
/* mmCB_SHADER_CONTROL */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
mmCB_SHADER_CONTROL-0xA000,
_swapEndianU32(pixelShader->regs[38]),
/* mmDB_SHADER_CONTROL */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
mmDB_SHADER_CONTROL-0xA000,
_swapEndianU32(pixelShader->regs[39]),
/* SPI_INPUT_Z */
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
mmSPI_INPUT_Z-0xA000,
_swapEndianU32(pixelShader->regs[40]));
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetGeometryShader(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetGeometryShader(0x{:08x})", hCPU->gpr[3]);
GX2ReserveCmdSpace(100);
GX2GeometryShader_t* geometryShader = (GX2GeometryShader_t*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
MPTR shaderProgramAddr;
uint32 shaderProgramSize;
if( _swapEndianU32(geometryShader->shaderPtr) != MPTR_NULL )
{
// old format
shaderProgramAddr = _swapEndianU32(geometryShader->shaderPtr);
shaderProgramSize = _swapEndianU32(geometryShader->shaderSize);
}
else
{
shaderProgramAddr = geometryShader->rBuffer.GetVirtualAddr();
shaderProgramSize = geometryShader->rBuffer.GetSize();
}
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 6));
gx2WriteGather_submitU32AsBE(mmSQ_PGM_START_GS-0xA000);
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(shaderProgramAddr)>>8);
gx2WriteGather_submitU32AsBE(shaderProgramSize>>3);
gx2WriteGather_submitU32AsBE(0x100000);
gx2WriteGather_submitU32AsBE(0x100000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->regs[0])); // unknown content (SQ_PGM_RESOURCES_GS)
uint32 primitiveOut = _swapEndianU32(geometryShader->regs[1]);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmVGT_GS_OUT_PRIM_TYPE-0xA000);
gx2WriteGather_submitU32AsLE(geometryShader->regs[1]);
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_CONTEXT_REG, 2),
Latte::REGADDR::VGT_GS_MODE - 0xA000,
geometryShader->reg.VGT_GS_MODE
);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmSQ_PGM_RESOURCES_GS-0xA000);
gx2WriteGather_submitU32AsLE(geometryShader->regs[0]);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmSQ_GS_VERT_ITEMSIZE-0xA000);
gx2WriteGather_submitU32AsLE(geometryShader->regs[5]);
if( _swapEndianU32(geometryShader->useStreamout) != 0 )
{
// stride 0
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmVGT_STRMOUT_VTX_STRIDE_0-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->streamoutStride[0])>>2);
// stride 1
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmVGT_STRMOUT_VTX_STRIDE_1-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->streamoutStride[1])>>2);
// stride 2
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmVGT_STRMOUT_VTX_STRIDE_2-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->streamoutStride[2])>>2);
// stride 3
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmVGT_STRMOUT_VTX_STRIDE_3-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->streamoutStride[3])>>2);
}
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmVGT_STRMOUT_BUFFER_EN-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->regs[18]));
// set copy shader (written to vertex shader registers, vs in turn is written to es registers)
MPTR copyShaderProgramAddr;
uint32 copyShaderProgramSize;
if( _swapEndianU32(geometryShader->copyShaderPtr) != MPTR_NULL )
{
copyShaderProgramAddr = _swapEndianU32(geometryShader->copyShaderPtr);
copyShaderProgramSize = _swapEndianU32(geometryShader->copyShaderSize);
}
else
{
copyShaderProgramAddr = geometryShader->rBufferCopyProgram.GetVirtualAddr();
copyShaderProgramSize = geometryShader->rBufferCopyProgram.GetSize();
}
cemu_assert_debug((copyShaderProgramAddr>>8) != 0);
cemu_assert_debug((copyShaderProgramSize>>3) != 0);
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 6));
gx2WriteGather_submitU32AsBE(mmSQ_PGM_START_VS-0xA000);
gx2WriteGather_submitU32AsBE(memory_virtualToPhysical(copyShaderProgramAddr)>>8);
gx2WriteGather_submitU32AsBE(copyShaderProgramSize>>3);
gx2WriteGather_submitU32AsBE(0x100000);
gx2WriteGather_submitU32AsBE(0x100000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->regs[4])); // mmSQ_PGM_RESOURCES_VS
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmPA_CL_VS_OUT_CNTL-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->regs[3]));
// GS outputs
uint32 numOutputIds = _swapEndianU32(geometryShader->regs[7]);
numOutputIds = std::min<uint32>(numOutputIds, 0xA);
if( numOutputIds != 0 )
{
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 1+numOutputIds));
gx2WriteGather_submitU32AsBE(mmSPI_VS_OUT_ID_0-0xA000);
for(uint32 i=0; i<numOutputIds; i++)
{
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->regs[8+i]));
}
}
// output config
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmSPI_VS_OUT_CONFIG-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->regs[6]));
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(mmSQ_GSVS_RING_ITEMSIZE-0xA000);
gx2WriteGather_submitU32AsBE(_swapEndianU32(geometryShader->ringItemsize)&0x7FFF);
/*
Geometry shader registers in regs[19]:
0 SQ_PGM_RESOURCES_GS ?
1 mmVGT_GS_OUT_PRIM_TYPE
2 mmVGT_GS_MODE
3 mmPA_CL_VS_OUT_CNTL
4 mmSQ_PGM_RESOURCES_VS (set in combination with mmSQ_PGM_START_VS)
5 mmSQ_GS_VERT_ITEMSIZE
6 mmSPI_VS_OUT_CONFIG
7 number of active mmSPI_VS_OUT_ID_* fields?
8-17 mmSPI_VS_OUT_ID_*
18 mmVGT_STRMOUT_BUFFER_EN
*/
osLib_returnFromFunction(hCPU, 0);
}
struct GX2ComputeShader
{
/* +0x00 */ uint32be regs[12];
/* +0x30 */ uint32be programSize;
/* +0x34 */ uint32be programPtr;
/* +0x38 */ uint32be ukn38;
/* +0x3C */ uint32be ukn3C;
/* +0x40 */ uint32be ukn40[8];
/* +0x60 */ uint32be workgroupSizeX;
/* +0x64 */ uint32be workgroupSizeY;
/* +0x68 */ uint32be workgroupSizeZ;
/* +0x6C */ uint32be workgroupSizeSpecial;
/* +0x70 */ uint32be ukn70;
/* +0x74 */ GX2RBuffer rBuffer;
};
static_assert(offsetof(GX2ComputeShader, programSize) == 0x30);
static_assert(offsetof(GX2ComputeShader, workgroupSizeX) == 0x60);
static_assert(offsetof(GX2ComputeShader, rBuffer) == 0x74);
void gx2Export_GX2SetComputeShader(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(computeShader, GX2ComputeShader, 0);
cemuLog_log(LogType::GX2, "GX2SetComputeShader(0x{:08x})", hCPU->gpr[3]);
MPTR shaderPtr;
uint32 shaderSize;
if (computeShader->programPtr)
{
shaderPtr = computeShader->programPtr;
shaderSize = computeShader->programSize;
}
else
{
shaderPtr = computeShader->rBuffer.GetVirtualAddr();
shaderSize = computeShader->rBuffer.GetSize();
}
GX2ReserveCmdSpace(0x11);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_CONTEXT_REG, 6),
mmSQ_PGM_START_ES-0xA000,
memory_virtualToPhysical(shaderPtr) >> 8,
shaderSize >> 3,
0x100000,
0x100000,
computeShader->regs[0]);
// todo: Other registers
osLib_returnFromFunction(hCPU, 0);
}
void _GX2SubmitUniformBlock(uint32 registerBase, uint32 index, MPTR virtualAddress, uint32 size)
{
GX2ReserveCmdSpace(9);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_RESOURCE, 8),
registerBase + index * 7,
memory_virtualToPhysical(virtualAddress),
size - 1,
0,
1,
0, // ukn
0, // ukn
0xC0000000);
}
void gx2Export_GX2SetVertexUniformBlock(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetVertexUniformBlock(0x{:08x},0x{:x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
_GX2SubmitUniformBlock(mmSQ_VTX_UNIFORM_BLOCK_START - mmSQ_TEX_RESOURCE_WORD0, hCPU->gpr[3], hCPU->gpr[5], hCPU->gpr[4]);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetPixelUniformBlock(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetPixelUniformBlock(0x{:08x},0x{:x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
_GX2SubmitUniformBlock(mmSQ_PS_UNIFORM_BLOCK_START - mmSQ_TEX_RESOURCE_WORD0, hCPU->gpr[3], hCPU->gpr[5], hCPU->gpr[4]);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetGeometryUniformBlock(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::GX2, "GX2SetGeometryUniformBlock(0x{:08x},0x{:x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
_GX2SubmitUniformBlock(mmSQ_GS_UNIFORM_BLOCK_START - mmSQ_TEX_RESOURCE_WORD0, hCPU->gpr[3], hCPU->gpr[5], hCPU->gpr[4]);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2RSetVertexUniformBlock(PPCInterpreter_t* hCPU)
{
GX2ReserveCmdSpace(9);
GX2RBuffer* bufferPtr = (GX2RBuffer*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
uint32 index = hCPU->gpr[4];
uint32 offset = hCPU->gpr[5];
_GX2SubmitUniformBlock(mmSQ_VTX_UNIFORM_BLOCK_START - mmSQ_TEX_RESOURCE_WORD0, index, bufferPtr->GetVirtualAddr() + offset, bufferPtr->GetSize() - offset);
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2SetShaderModeEx(PPCInterpreter_t* hCPU)
{
GX2ReserveCmdSpace(8+4);
uint32 mode = hCPU->gpr[3];
uint32 sqConfig = hCPU->gpr[3] == 0 ? 4 : 0;
if (mode == GX2_SHADER_MODE_COMPUTE_SHADER)
sqConfig |= 0xE4000000; // ES/GS/PS priority?
// todo - other sqConfig bits
gx2WriteGather_submit((uint32)(pm4HeaderType3(IT_SET_CONFIG_REG, 7)),
(uint32)(mmSQ_CONFIG - 0x2000),
sqConfig,
0, // ukn / todo
0, // ukn / todo
0, // ukn / todo
0, // ukn / todo
0 // ukn / todo
);
// if not GS, then update mmVGT_GS_MODE
if( mode != GX2_SHADER_MODE_GEOMETRY_SHADER )
{
// update VGT_GS_MODE only if no geometry shader is used (else this register is already set by GX2SetGeometryShader)
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONTEXT_REG, 2));
gx2WriteGather_submitU32AsBE(Latte::REGADDR::VGT_GS_MODE-0xA000);
if (mode == GX2_SHADER_MODE_COMPUTE_SHADER)
gx2WriteGather_submitU32AsBE(Latte::LATTE_VGT_GS_MODE().set_MODE(Latte::LATTE_VGT_GS_MODE::E_MODE::SCENARIO_G).set_COMPUTE_MODE(Latte::LATTE_VGT_GS_MODE::E_COMPUTE_MODE::ON).set_PARTIAL_THD_AT_EOI(true).getRawValueBE());
else
gx2WriteGather_submitU32AsBE(_swapEndianU32(0));
}
osLib_returnFromFunction(hCPU, 0);
}
void gx2Export_GX2CalcGeometryShaderInputRingBufferSize(PPCInterpreter_t* hCPU)
{
uint32 size = (hCPU->gpr[3]*4) * 0x1000;
osLib_returnFromFunction(hCPU, size);
}
void gx2Export_GX2CalcGeometryShaderOutputRingBufferSize(PPCInterpreter_t* hCPU)
{
uint32 size = (hCPU->gpr[3]*4) * 0x1000;
osLib_returnFromFunction(hCPU, size);
}
| 12,963
|
C++
|
.cpp
| 316
| 38.563291
| 223
| 0.773323
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,069
|
GX2_Surface.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Surface.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "GX2.h"
#include "GX2_Surface.h"
#include "GX2_Resource.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/HW/Latte/LatteAddrLib/LatteAddrLib.h"
namespace GX2
{
uint32 GX2GetSurfaceMipPitch(GX2Surface* surface, uint32 level)
{
LatteAddrLib::AddrSurfaceInfo_OUT surfOut;
GX2::GX2CalculateSurfaceInfo(surface, level, &surfOut);
return surfOut.pitch;
}
uint32 GX2GetSurfaceFormatBits(Latte::E_GX2SURFFMT surfaceFormat)
{
uint32 bpp = Latte::GetFormatBits(surfaceFormat);
if (Latte::IsCompressedFormat(surfaceFormat))
{
cemu_assert_debug((bpp & 0xF) == 0);
bpp /= (4 * 4);
}
return bpp;
}
uint32 _GX2CalculateSliceSize(GX2Surface* surface, const LatteAddrLib::AddrSurfaceInfo_OUT* surfaceInfo)
{
uint32 aaScaler = 1 << surface->aa;
return aaScaler * (surfaceInfo->bpp >> 3) * surfaceInfo->height * surfaceInfo->pitch;
}
uint32 GX2GetSurfaceMipSliceSize(GX2Surface* surface, uint32 level)
{
LatteAddrLib::AddrSurfaceInfo_OUT surfOut;
GX2::GX2CalculateSurfaceInfo(surface, level, &surfOut);
return _GX2CalculateSliceSize(surface, &surfOut);
}
uint32 GX2GetSurfaceSwizzleOffset(GX2Surface* surface, uint32 level)
{
uint32 swizzleOffset = 0;
uint32 swizzle = surface->swizzle;
if (!Latte::TM_IsMacroTiled(surface->tileMode) || level >= ((swizzle >> 16) & 0xFF))
swizzleOffset = 0;
else
swizzleOffset = swizzle & 0xFFFF;
return swizzleOffset;
}
uint32 GX2GetSurfaceSwizzle(GX2Surface* surface)
{
uint32 swizzle = surface->swizzle;
swizzle = (swizzle >> 8) & 0xFF;
return swizzle;
}
uint32 GX2SurfaceIsCompressed(Latte::E_GX2SURFFMT surfaceFormat)
{
return Latte::IsCompressedFormat(surfaceFormat) ? GX2_TRUE : GX2_FALSE;
}
void GX2CalcDepthBufferHiZInfo(GX2DepthBuffer* depthBuffer, uint32be* sizeOut, uint32be* alignOut)
{
*sizeOut = 0x1000;
*alignOut = 0x100;
// todo: implement
}
void GX2CalcColorBufferAuxInfo(GX2ColorBuffer* colorBuffer, uint32be* sizeOut, uint32be* alignOut)
{
*sizeOut = 0x1000;
*alignOut = 0x100;
// todo: implement
}
void GX2CalculateSurfaceInfo(GX2Surface* surfacePtr, uint32 level, LatteAddrLib::AddrSurfaceInfo_OUT* pSurfOut)
{
bool optimizeForDepthBuffer = (surfacePtr->resFlag & GX2_RESFLAG_USAGE_DEPTH_BUFFER) != 0;
bool optimizeForScanBuffer = (surfacePtr->resFlag & GX2_RESFLAG_USAGE_SCAN_BUFFER) != 0;
LatteAddrLib::GX2CalculateSurfaceInfo(surfacePtr->format, surfacePtr->width, surfacePtr->height, surfacePtr->depth, surfacePtr->dim, surfacePtr->tileMode, surfacePtr->aa, level, pSurfOut, optimizeForDepthBuffer, optimizeForScanBuffer);
}
uint32 _CalculateLevels(uint32 resolution)
{
uint32 x = 0x80000000;
uint32 v = resolution;
uint32 n = 0;
while (!(v & x))
{
n++;
if (n == 32)
break;
x >>= 1;
}
return 32 - n;
}
uint32 _GX2AdjustLevelCount(GX2Surface* surfacePtr)
{
if (surfacePtr->numLevels <= 1)
return 1;
uint32 levels = std::max(_CalculateLevels(surfacePtr->width), _CalculateLevels(surfacePtr->height));
if (surfacePtr->dim == Latte::E_DIM::DIM_3D)
levels = std::max(levels, _CalculateLevels(surfacePtr->depth));
return levels;
}
void _GX2CalcSurfaceSizeAndAlignmentWorkaround(GX2Surface* surface)
{
// this workaround catches an issue where the FFL (Mii) library embedded into games tries to use an uninitialized texture
// and subsequently crashes. It only happens when FFL files are not present in mlc.
// seen in Sonic Lost World and in Super Mario 3D World
if ((uint32)surface->dim.value() >= 50 || surface->aa.value() >= 0x100 || (uint32)surface->width.value() >= 0x01000000 ||
(uint32)surface->height.value() >= 0x01000000 || (uint32)surface->depth.value() >= 0x01000000 || (uint32)surface->format.value() >= 0x10000)
{
cemuLog_log(LogType::Force, "GX2CalcSurfaceSizeAndAlignment(): Uninitialized surface encountered\n");
// overwrite surface parameters with placeholder values to avoid crashing later down the line
surface->dim = Latte::E_DIM::DIM_2D;
surface->width = 8;
surface->height = 8;
surface->depth = 1;
surface->tileMode = Latte::E_GX2TILEMODE::TM_2D_TILED_THIN1;
surface->pitch = 8;
surface->numLevels = 0;
surface->imagePtr = MEMORY_TILINGAPERTURE_AREA_ADDR;
surface->swizzle = 0;
surface->aa = 0;
surface->format = Latte::E_GX2SURFFMT::R8_G8_B8_A8_UNORM;
surface->alignment = 0x400;
}
}
void GX2CalcSurfaceSizeAndAlignment(GX2Surface* surface)
{
_GX2CalcSurfaceSizeAndAlignmentWorkaround(surface);
LatteAddrLib::AddrSurfaceInfo_OUT surfOut = { 0 };
uint32 firstMipOffset = 0;
bool changeTilemode = false;
Latte::E_GX2TILEMODE lastTilemode = surface->tileMode;
bool hasTileMode32 = surface->tileMode == Latte::E_GX2TILEMODE::TM_32_SPECIAL;
if (surface->tileMode == Latte::E_GX2TILEMODE::TM_LINEAR_GENERAL || hasTileMode32)
{
if (surface->dim != Latte::E_DIM::DIM_1D || (surface->resFlag & GX2_RESFLAG_USAGE_DEPTH_BUFFER) != 0 || surface->aa)
{
if (surface->dim != Latte::E_DIM::DIM_3D || (surface->resFlag & GX2_RESFLAG_USAGE_COLOR_BUFFER) != 0)
surface->tileMode = Latte::E_GX2TILEMODE::TM_2D_TILED_THIN1;
else
surface->tileMode = Latte::E_GX2TILEMODE::TM_2D_TILED_THICK;
changeTilemode = true;
}
else
{
surface->tileMode = Latte::E_GX2TILEMODE::TM_LINEAR_ALIGNED;
}
lastTilemode = surface->tileMode;
}
if (surface->numLevels == 0)
surface->numLevels = 1;
surface->numLevels = std::min<uint32>(surface->numLevels, _GX2AdjustLevelCount(surface));
surface->mipOffset[0] = 0;
if (Latte::TM_IsMacroTiled(surface->tileMode))
surface->swizzle = (surface->swizzle & 0xFF00FFFF) | 0xD0000;
else
surface->swizzle = surface->swizzle & 0xFF00FFFF;
// FIX 32
uint32 fix32Mode;
if (hasTileMode32)
{
if (Latte::IsCompressedFormat(surface->format))
fix32Mode = 2;
else
fix32Mode = 0;
}
else
{
fix32Mode = 0;
}
// setup levels
uint32 prevSize = 0;
for (uint32 level = 0; level < surface->numLevels; ++level)
{
GX2CalculateSurfaceInfo(surface, level, &surfOut);
if (level)
{
uint32 pad = 0;
if (Latte::TM_IsMacroTiled(lastTilemode) && !Latte::TM_IsMacroTiled(surfOut.hwTileMode))
{
surface->swizzle = (surface->swizzle & 0xFF00FFFF) | (level << 16);
lastTilemode = (Latte::E_GX2TILEMODE)surfOut.hwTileMode;
if (level > 1)
pad = surface->swizzle & 0xFFFF;
}
pad += (surfOut.baseAlign - prevSize % surfOut.baseAlign) % surfOut.baseAlign;
if (level == 1)
{
firstMipOffset = pad + prevSize;
}
else if (level > 1)
{
surface->mipOffset[level - 1] = pad + prevSize + surface->mipOffset[level - 2];
}
}
else
{
if (changeTilemode)
{
if (surface->tileMode != (Latte::E_GX2TILEMODE)surfOut.hwTileMode)
{
surface->tileMode = (Latte::E_GX2TILEMODE)surfOut.hwTileMode;
GX2CalculateSurfaceInfo(surface, 0, &surfOut);
if (!Latte::TM_IsMacroTiled(surface->tileMode))
surface->swizzle = surface->swizzle & 0xFF00FFFF;
lastTilemode = surface->tileMode;
}
if (surface->width < (surfOut.pitchAlign << fix32Mode)
&& surface->height < (surfOut.heightAlign << fix32Mode))
{
if (surface->tileMode == Latte::E_GX2TILEMODE::TM_2D_TILED_THICK)
surface->tileMode = Latte::E_GX2TILEMODE::TM_1D_TILED_THICK;
else
surface->tileMode = Latte::E_GX2TILEMODE::TM_1D_TILED_THIN1;
GX2CalculateSurfaceInfo(surface, 0, &surfOut);
surface->swizzle = surface->swizzle & 0xFF00FFFF;
lastTilemode = surface->tileMode;
}
}
surface->imageSize = (uint32)(surfOut.surfSize);
surface->alignment = surfOut.baseAlign;
surface->pitch = surfOut.pitch;
}
prevSize = (uint32)(surfOut.surfSize);
}
if (surface->numLevels > 1)
surface->mipSize = prevSize + surface->mipOffset[surface->numLevels - 2];
else
surface->mipSize = 0;
surface->mipOffset[0] = firstMipOffset;
if (surface->format == Latte::E_GX2SURFFMT::NV12_UNORM)
{
uint32 padding = (surface->alignment - surface->imageSize % surface->alignment) % surface->alignment;
surface->mipOffset[0] = padding + surface->imageSize;
surface->imageSize = surface->mipOffset[0] + ((uint32)surface->imageSize >> 1);
}
}
Latte::E_ENDIAN_SWAP GetSurfaceFormatSwapMode(Latte::E_GX2SURFFMT fmt)
{
// swap mode is 0 for all formats
return Latte::E_ENDIAN_SWAP::SWAP_NONE;
}
uint32 GetSurfaceColorBufferExportFormat(Latte::E_GX2SURFFMT fmt)
{
const uint8 table[0x40] = {
0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint32 fmtHW = (uint32)fmt & 0x3F;
return table[fmtHW];
}
uint32 GX2CheckSurfaceUseVsFormat(uint32 resFlags, uint32 surfaceFormat)
{
cemuLog_logDebug(LogType::Force, "GX2CheckSurfaceUseVsFormat - stub");
return 1;
}
void GX2SetSurfaceSwizzle(GX2Surface* surface, uint32 newSwizzle)
{
uint32 currentSwizzle = surface->swizzle;
currentSwizzle &= ~0xFF00;
currentSwizzle |= (newSwizzle << 8); // newSwizzle isn't actually masked and some games set it to values above 0xFF
surface->swizzle = currentSwizzle;
}
void GX2SurfaceInit()
{
cafeExportRegister("gx2", GX2GetSurfaceMipPitch, LogType::GX2);
cafeExportRegister("gx2", GX2GetSurfaceFormatBits, LogType::GX2);
cafeExportRegister("gx2", GX2GetSurfaceMipSliceSize, LogType::GX2);
cafeExportRegister("gx2", GX2GetSurfaceSwizzleOffset, LogType::GX2);
cafeExportRegister("gx2", GX2GetSurfaceSwizzle, LogType::GX2);
cafeExportRegister("gx2", GX2SurfaceIsCompressed, LogType::GX2);
cafeExportRegister("gx2", GX2CalcDepthBufferHiZInfo, LogType::GX2);
cafeExportRegister("gx2", GX2CalcColorBufferAuxInfo, LogType::GX2);
cafeExportRegister("gx2", GX2CalcSurfaceSizeAndAlignment, LogType::GX2);
cafeExportRegister("gx2", GX2CheckSurfaceUseVsFormat, LogType::GX2);
cafeExportRegister("gx2", GX2SetSurfaceSwizzle, LogType::GX2);
}
};
| 10,396
|
C++
|
.cpp
| 280
| 33.589286
| 237
| 0.720499
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,070
|
GX2_Draw.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/gx2/GX2_Draw.cpp
|
#include "Cafe/HW/Latte/ISA/RegDefines.h"
#include "GX2.h"
#include "Cafe/HW/Latte/Core/Latte.h"
#include "Cafe/HW/Latte/Core/LatteDraw.h"
#include "Cafe/HW/Latte/ISA/LatteReg.h"
#include "Cafe/HW/Latte/Core/LattePM4.h"
#include "Cafe/OS/common/OSCommon.h"
#include "GX2_Command.h"
#include "GX2_Draw.h"
namespace GX2
{
void GX2SetAttribBuffer(uint32 bufferIndex, uint32 sizeInBytes, uint32 stride, void* data)
{
GX2ReserveCmdSpace(9);
MPTR physicalAddress = memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(data));
// write PM4 command
gx2WriteGather_submit(
pm4HeaderType3(IT_SET_RESOURCE, 8),
0x8C0 + bufferIndex * 7,
physicalAddress,
sizeInBytes - 1, // size
(stride & 0xFFFF) << 11, // stride
0, // ukn
0, // ukn
0, // ukn
0xC0000000); // ukn
}
void GX2DrawIndexedEx(GX2PrimitiveMode2 primitiveMode, uint32 count, GX2IndexType indexType, void* indexData, uint32 baseVertex, uint32 numInstances)
{
GX2ReserveCmdSpace(3 + 3 + 2 + 2 + 6);
gx2WriteGather_submit(
// IT_SET_CTL_CONST
pm4HeaderType3(IT_SET_CTL_CONST, 2), 0,
baseVertex,
// IT_SET_CONFIG_REG
pm4HeaderType3(IT_SET_CONFIG_REG, 2), Latte::REGADDR::VGT_PRIMITIVE_TYPE - 0x2000,
(uint32)primitiveMode,
// IT_INDEX_TYPE
pm4HeaderType3(IT_INDEX_TYPE, 1),
(uint32)indexType,
// IT_NUM_INSTANCES
pm4HeaderType3(IT_NUM_INSTANCES, 1),
numInstances,
// IT_DRAW_INDEX_2
pm4HeaderType3(IT_DRAW_INDEX_2, 5) | 0x00000001,
-1,
memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(indexData)),
0,
count,
0);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
}
void GX2DrawIndexedEx2(GX2PrimitiveMode2 primitiveMode, uint32 count, GX2IndexType indexType, void* indexData, uint32 baseVertex, uint32 numInstances, uint32 baseInstance)
{
GX2ReserveCmdSpace(3 + 3 + 2 + 2 + 6);
gx2WriteGather_submit(
// IT_SET_CTL_CONST
pm4HeaderType3(IT_SET_CTL_CONST, 2), 0,
baseVertex,
// set base instance
pm4HeaderType3(IT_SET_CTL_CONST, 2), 1,
baseInstance,
// IT_SET_CONFIG_REG
pm4HeaderType3(IT_SET_CONFIG_REG, 2), Latte::REGADDR::VGT_PRIMITIVE_TYPE - 0x2000,
(uint32)primitiveMode,
// IT_INDEX_TYPE
pm4HeaderType3(IT_INDEX_TYPE, 1),
(uint32)indexType,
// IT_NUM_INSTANCES
pm4HeaderType3(IT_NUM_INSTANCES, 1),
numInstances,
// IT_DRAW_INDEX_2
pm4HeaderType3(IT_DRAW_INDEX_2, 5) | 0x00000001,
-1,
memory_virtualToPhysical(memory_getVirtualOffsetFromPointer(indexData)),
0,
count,
0,
// reset base instance
pm4HeaderType3(IT_SET_CTL_CONST, 2), 1,
0 // baseInstance
);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
}
void GX2DrawEx(GX2PrimitiveMode2 primitiveMode, uint32 count, uint32 baseVertex, uint32 numInstances)
{
GX2ReserveCmdSpace(3 + 3 + 2 + 2 + 6);
gx2WriteGather_submit(
// IT_SET_CTL_CONST
pm4HeaderType3(IT_SET_CTL_CONST, 2), 0,
baseVertex,
// IT_SET_CONFIG_REG
pm4HeaderType3(IT_SET_CONFIG_REG, 2), Latte::REGADDR::VGT_PRIMITIVE_TYPE - 0x2000,
(uint32)primitiveMode,
// IT_INDEX_TYPE
pm4HeaderType3(IT_INDEX_TYPE, 1),
(uint32)GX2IndexType::U32_BE,
// IT_NUM_INSTANCES
pm4HeaderType3(IT_NUM_INSTANCES, 1),
numInstances,
// IT_DRAW_INDEX_2
pm4HeaderType3(IT_DRAW_INDEX_AUTO, 2) | 0x00000001,
count,
0 // DRAW_INITIATOR
);
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
}
void GX2DrawIndexedImmediateEx(GX2PrimitiveMode2 primitiveMode, uint32 count, GX2IndexType indexType, void* indexData, uint32 baseVertex, uint32 numInstances)
{
uint32* indexDataU32 = (uint32*)indexData;
uint32 numIndexU32s;
bool use32BitIndices = false;
if (indexType == GX2IndexType::U16_BE || indexType == GX2IndexType::U16_LE)
{
// 16bit indices
numIndexU32s = (count + 1) / 2;
}
else if (indexType == GX2IndexType::U32_BE || indexType == GX2IndexType::U32_LE)
{
// 32bit indices
numIndexU32s = count;
use32BitIndices = true;
}
else
{
cemu_assert_unimplemented();
}
GX2ReserveCmdSpace(3 + 3 + 3 + 2 + 2 + 6 + 3 + numIndexU32s);
if (numIndexU32s > 0x4000 - 2)
{
cemuLog_log(LogType::Force, "GX2DrawIndexedImmediateEx(): Draw exceeds maximum PM4 command size. Keep index size below 16KiB minus 8 byte");
return;
}
// set base vertex
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CTL_CONST, 2));
gx2WriteGather_submitU32AsBE(0);
gx2WriteGather_submitU32AsBE(baseVertex);
// set primitive mode
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONFIG_REG, 2));
gx2WriteGather_submitU32AsBE(Latte::REGADDR::VGT_PRIMITIVE_TYPE - 0x2000);
gx2WriteGather_submitU32AsBE((uint32)primitiveMode);
// set index type
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_INDEX_TYPE, 1));
gx2WriteGather_submitU32AsBE((uint32)indexType);
// set number of instances
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_NUM_INSTANCES, 1));
gx2WriteGather_submitU32AsBE((uint32)numInstances);
// request indexed draw with indices embedded into command buffer
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_DRAW_INDEX_IMMD, 2 + numIndexU32s) | 0x00000001);
gx2WriteGather_submitU32AsBE(count);
gx2WriteGather_submitU32AsBE(0); // ukn
if (use32BitIndices)
{
for (uint32 i = 0; i < numIndexU32s; i++)
{
gx2WriteGather_submitU32AsLE(indexDataU32[i]);
}
}
else
{
for (uint32 i = 0; i < numIndexU32s; i++)
{
uint32 indexPair = indexDataU32[i];
// swap index pair
indexPair = (indexPair >> 16) | (indexPair << 16);
gx2WriteGather_submitU32AsLE(indexPair);
}
}
GX2::GX2WriteGather_checkAndInsertWrapAroundMark();
}
struct GX2DispatchComputeParam
{
/* +0x00 */ uint32be worksizeX;
/* +0x04 */ uint32be worksizeY;
/* +0x08 */ uint32be worksizeZ;
};
void GX2DispatchCompute(GX2DispatchComputeParam* dispatchParam)
{
GX2ReserveCmdSpace(9 + 10);
gx2WriteGather_submit(pm4HeaderType3(IT_SET_RESOURCE, 8),
(mmSQ_CS_DISPATCH_PARAMS - mmSQ_TEX_RESOURCE_WORD0),
memory_virtualToPhysical(MEMPTR<GX2DispatchComputeParam>(dispatchParam).GetMPTR()),
0xF,
0x862000,
1,
0xABCD1234,
0xABCD1234,
0xC0000000);
// IT_EVENT_WRITE with RST_VTX_CNT?
// set primitive mode
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_SET_CONFIG_REG, 2));
gx2WriteGather_submitU32AsBE(Latte::REGADDR::VGT_PRIMITIVE_TYPE - 0x2000);
gx2WriteGather_submitU32AsBE(1); // mode
// set number of instances
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_NUM_INSTANCES, 1));
gx2WriteGather_submitU32AsBE(1); // numInstances
uint32 workCount = (uint32)dispatchParam->worksizeX * (uint32)dispatchParam->worksizeY * (uint32)dispatchParam->worksizeZ;
gx2WriteGather_submitU32AsBE(pm4HeaderType3(IT_DRAW_INDEX_AUTO, 2) | 0x00000001);
gx2WriteGather_submitU32AsBE(workCount);
gx2WriteGather_submitU32AsBE(0); // DRAW_INITIATOR (has source select for index generator + other unknown info)
}
void GX2DrawInit()
{
cafeExportRegister("gx2", GX2SetAttribBuffer, LogType::GX2);
cafeExportRegister("gx2", GX2DrawIndexedEx, LogType::GX2);
cafeExportRegister("gx2", GX2DrawIndexedEx2, LogType::GX2);
cafeExportRegister("gx2", GX2DrawEx, LogType::GX2);
cafeExportRegister("gx2", GX2DrawIndexedImmediateEx, LogType::GX2);
cafeExportRegister("gx2", GX2DispatchCompute, LogType::GX2);
}
}
| 7,335
|
C++
|
.cpp
| 211
| 31.417062
| 172
| 0.743243
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,071
|
nn_spm.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_spm/nn_spm.cpp
|
#include "nn_spm.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/nn_common.h"
namespace nn
{
namespace spm
{
struct StorageIndex
{
void SetInvalid() { idHigh = 0; idLow = 0; }
void Set(uint64 id) { idHigh = id >> 32; idLow = id & 0xFFFFFFFF; }
uint64 Get() const { return ((uint64)idHigh << 32) | (uint64)idLow; }
uint32be idHigh;
uint32be idLow;
};
enum class CemuStorageIndex
{
MLC = 1,
SLC = 2,
USB = 3,
};
static_assert(sizeof(StorageIndex) == 8);
struct VolumeId
{
char id[16];
};
static_assert(sizeof(VolumeId) == 16);
enum class StorageType : uint32
{
RAW,
WFS,
};
struct StorageInfo
{
char mountPath[640]; // For example: /vol/storage_usb01
char connectionType[8]; // usb
char formatStr[8]; // raw / wfs
uint8 ukn[4];
betype<StorageType> type;
VolumeId volumeId;
};
static_assert(sizeof(StorageInfo) == 680);
struct StorageListItem
{
StorageIndex index;
uint32be ukn04;
betype<StorageType> type;
};
static_assert(sizeof(StorageListItem) == 16);
sint32 GetDefaultExtendedStorageVolumeId(StorageIndex* storageIndex)
{
cemuLog_logDebug(LogType::Force, "GetDefaultExtendedStorageVolumeId() - stub");
storageIndex->SetInvalid(); // we dont emulate USB storage yet
return 0;
}
sint32 GetExtendedStorageIndex(StorageIndex* storageIndex)
{
cemuLog_logDebug(LogType::Force, "GetExtendedStorageIndex() - stub");
storageIndex->SetInvalid(); // we dont emulate USB storage yet
return -1; // this fails if there is none?
}
// nn::spm::GetStorageList((nn::spm::StorageListItem *, unsigned int))
uint32 GetStorageList(StorageListItem* storageList, uint32 maxItems)
{
cemu_assert(maxItems >= 2);
uint32 numItems = 0;
// This should only return USB storages?
// If we return two entries (for SLC and MLC supposedly) then the Wii U menu will complain about two usb storages
// // mlc
// storageList[numItems].index.Set((uint32)CemuStorageIndex::MLC);
// storageList[numItems].ukn04 = 0;
// storageList[numItems].type = StorageType::WFS;
// numItems++;
// // slc
// storageList[numItems].index.Set((uint32)CemuStorageIndex::SLC);
// storageList[numItems].ukn04 = 0;
// storageList[numItems].type = StorageType::WFS;
numItems++;
return numItems;
}
sint32 GetStorageInfo(StorageInfo* storageInfo, StorageIndex* storageIndex)
{
cemuLog_logDebug(LogType::Force, "GetStorageInfo() - stub");
if(storageIndex->Get() == (uint64)CemuStorageIndex::MLC)
{
cemu_assert_unimplemented();
}
else if(storageIndex->Get() == (uint64)CemuStorageIndex::SLC)
{
cemu_assert_unimplemented();
}
else
{
cemu_assert_unimplemented();
}
return 0;
}
sint32 VolumeId_Compare(VolumeId* volumeIdThis, VolumeId* volumeIdOther)
{
auto r = strncmp(volumeIdThis->id, volumeIdOther->id, 16);
cemuLog_logDebug(LogType::Force, "VolumeId_Compare(\"{}\", \"{}\")", volumeIdThis->id, volumeIdOther->id);
return (sint32)r;
}
sint32 WaitStateUpdated(uint64be* waitState)
{
// WaitStateUpdated__Q2_2nn3spmFPUL
cemuLog_logDebug(LogType::Force, "WaitStateUpdated() called");
*waitState = 1;
return 0;
}
void load()
{
cafeExportRegisterFunc(GetDefaultExtendedStorageVolumeId, "nn_spm", "GetDefaultExtendedStorageVolumeId__Q2_2nn3spmFv", LogType::Placeholder);
cafeExportRegisterFunc(GetExtendedStorageIndex, "nn_spm", "GetExtendedStorageIndex__Q2_2nn3spmFPQ3_2nn3spm12StorageIndex", LogType::Placeholder);
cafeExportRegisterFunc(GetStorageList, "nn_spm", "GetStorageList__Q2_2nn3spmFPQ3_2nn3spm15StorageListItemUi", LogType::Placeholder);
cafeExportRegisterFunc(GetStorageInfo, "nn_spm", "GetStorageInfo__Q2_2nn3spmFPQ3_2nn3spm11StorageInfoQ3_2nn3spm12StorageIndex", LogType::Placeholder);
cafeExportRegisterFunc(VolumeId_Compare, "nn_spm", "Compare__Q3_2nn3spm8VolumeIdCFRCQ3_2nn3spm8VolumeId", LogType::Placeholder);
cafeExportRegisterFunc(WaitStateUpdated, "nn_spm", "WaitStateUpdated__Q2_2nn3spmFPUL", LogType::Placeholder);
}
}
}
| 4,109
|
C++
|
.cpp
| 121
| 30.479339
| 153
| 0.725436
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,072
|
proc_ui.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/proc_ui/proc_ui.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_MessageQueue.h"
#include "Cafe/OS/libs/coreinit/coreinit_Misc.h"
#include "Cafe/OS/libs/coreinit/coreinit_Memory.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_ExpHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_FG.h"
#include "Cafe/OS/libs/coreinit/coreinit_DynLoad.h"
#include "Cafe/OS/libs/gx2/GX2_Misc.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Common/CafeString.h"
#include "proc_ui.h"
// proc_ui is a utility wrapper to help apps with the transition between foreground and background
// some games (like Xenoblades Chronicles X) bypass proc_ui.rpl and listen to OSGetSystemMessageQueue() directly
using namespace coreinit;
namespace proc_ui
{
enum class ProcUICoreThreadCommand
{
AcquireForeground = 0x0,
ReleaseForeground = 0x1,
Exit = 0x2,
NetIoStart = 0x3,
NetIoStop = 0x4,
HomeButtonDenied = 0x5,
Initial = 0x6
};
struct ProcUIInternalCallbackEntry
{
coreinit::OSAlarm_t alarm;
uint64be tickDelay;
MEMPTR<void> funcPtr;
MEMPTR<void> userParam;
sint32be priority;
MEMPTR<ProcUIInternalCallbackEntry> next;
};
static_assert(sizeof(ProcUIInternalCallbackEntry) == 0x70);
struct ProcUICallbackList
{
MEMPTR<ProcUIInternalCallbackEntry> first;
};
static_assert(sizeof(ProcUICallbackList) == 0x4);
std::atomic_bool s_isInitialized;
bool s_isInForeground;
bool s_isInShutdown;
bool s_isForegroundProcess;
bool s_previouslyWasBlocking;
ProcUIStatus s_currentProcUIStatus;
MEMPTR<void> s_saveCallback; // no param and no return value, set by ProcUIInit()
MEMPTR<void> s_saveCallbackEx; // with custom param and return value, set by ProcUIInitEx()
MEMPTR<void> s_saveCallbackExUserParam;
MEMPTR<coreinit::OSMessageQueue> s_systemMessageQueuePtr;
SysAllocator<coreinit::OSEvent> s_eventStateMessageReceived;
SysAllocator<coreinit::OSEvent> s_eventWaitingBeforeReleaseForeground;
SysAllocator<coreinit::OSEvent> s_eventBackgroundThreadGotMessage;
// procUI core threads
uint32 s_coreThreadStackSize;
bool s_coreThreadsCreated;
std::atomic<ProcUICoreThreadCommand> s_commandForCoreThread;
SysAllocator<OSThread_t> s_coreThreadArray[Espresso::CORE_COUNT];
MEMPTR<void> s_coreThreadStackPerCore[Espresso::CORE_COUNT];
SysAllocator<CafeString<22>> s_coreThread0NameBuffer;
SysAllocator<CafeString<22>> s_coreThread1NameBuffer;
SysAllocator<CafeString<22>> s_coreThread2NameBuffer;
SysAllocator<coreinit::OSEvent> s_eventCoreThreadsNewCommandReady;
SysAllocator<coreinit::OSEvent> s_eventCoreThreadsCommandDone;
SysAllocator<coreinit::OSRendezvous> s_coreThreadRendezvousA;
SysAllocator<coreinit::OSRendezvous> s_coreThreadRendezvousB;
SysAllocator<coreinit::OSRendezvous> s_coreThreadRendezvousC;
// background thread
MEMPTR<void> s_backgroundThreadStack;
SysAllocator<OSThread_t> s_backgroundThread;
// user defined heap
MEMPTR<void> s_memoryPoolHeapPtr;
MEMPTR<void> s_memAllocPtr;
MEMPTR<void> s_memFreePtr;
// draw done release
bool s_drawDoneReleaseCalled;
// memory storage
MEMPTR<void> s_bucketStorageBasePtr;
MEMPTR<void> s_mem1StorageBasePtr;
// callbacks
ProcUICallbackList s_callbacksType0_AcquireForeground[Espresso::CORE_COUNT];
ProcUICallbackList s_callbacksType1_ReleaseForeground[Espresso::CORE_COUNT];
ProcUICallbackList s_callbacksType2_Exit[Espresso::CORE_COUNT];
ProcUICallbackList s_callbacksType3_NetIoStart[Espresso::CORE_COUNT];
ProcUICallbackList s_callbacksType4_NetIoStop[Espresso::CORE_COUNT];
ProcUICallbackList s_callbacksType5_HomeButtonDenied[Espresso::CORE_COUNT];
ProcUICallbackList* const s_CallbackTables[stdx::to_underlying(ProcUICallbackId::COUNT)] =
{s_callbacksType0_AcquireForeground, s_callbacksType1_ReleaseForeground, s_callbacksType2_Exit, s_callbacksType3_NetIoStart, s_callbacksType4_NetIoStop, s_callbacksType5_HomeButtonDenied};
ProcUICallbackList s_backgroundCallbackList;
// driver
bool s_driverIsActive;
uint32be s_driverArgUkn1;
uint32be s_driverArgUkn2;
bool s_driverInBackground;
SysAllocator<OSDriverInterface> s_ProcUIDriver;
SysAllocator<CafeString<16>> s_ProcUIDriverName;
void* _AllocMem(uint32 size)
{
MEMPTR<void> r{PPCCoreCallback(s_memAllocPtr, size)};
return r.GetPtr();
}
void _FreeMem(void* ptr)
{
PPCCoreCallback(s_memFreePtr.GetMPTR(), ptr);
}
void ClearCallbacksWithoutMemFree()
{
for (sint32 coreIndex = 0; coreIndex < Espresso::CORE_COUNT; coreIndex++)
{
for (sint32 i = 0; i < stdx::to_underlying(ProcUICallbackId::COUNT); i++)
s_CallbackTables[i][coreIndex].first = nullptr;
}
s_backgroundCallbackList.first = nullptr;
}
void ShutdownThreads()
{
if ( !s_coreThreadsCreated)
return;
s_commandForCoreThread = ProcUICoreThreadCommand::Initial;
coreinit::OSMemoryBarrier();
OSSignalEvent(&s_eventCoreThreadsNewCommandReady);
for (sint32 coreIndex = 0; coreIndex < Espresso::CORE_COUNT; coreIndex++)
{
coreinit::OSJoinThread(&s_coreThreadArray[coreIndex], nullptr);
for (sint32 i = 0; i < stdx::to_underlying(ProcUICallbackId::COUNT); i++)
{
s_CallbackTables[i][coreIndex].first = nullptr; // memory is not cleanly released?
}
}
OSResetEvent(&s_eventCoreThreadsNewCommandReady);
for (sint32 coreIndex = 0; coreIndex < Espresso::CORE_COUNT; coreIndex++)
{
_FreeMem(s_coreThreadStackPerCore[coreIndex]);
s_coreThreadStackPerCore[coreIndex] = nullptr;
}
_FreeMem(s_backgroundThreadStack);
s_backgroundThreadStack = nullptr;
s_backgroundCallbackList.first = nullptr; // memory is not cleanly released?
s_coreThreadsCreated = false;
}
void DoCallbackChain(ProcUIInternalCallbackEntry* entry)
{
while (entry)
{
uint32 r = PPCCoreCallback(entry->funcPtr, entry->userParam);
if ( r )
cemuLog_log(LogType::APIErrors, "ProcUI: Callback returned error {}\n", r);
entry = entry->next;
}
}
void AlarmDoBackgroundCallback(PPCInterpreter_t* hCPU)
{
coreinit::OSAlarm_t* arg = MEMPTR<coreinit::OSAlarm_t>(hCPU->gpr[3]);
ProcUIInternalCallbackEntry* entry = (ProcUIInternalCallbackEntry*)arg;
uint32 r = PPCCoreCallback(entry->funcPtr, entry->userParam);
if ( r )
cemuLog_log(LogType::APIErrors, "ProcUI: Background callback returned error {}\n", r);
osLib_returnFromFunction(hCPU, 0); // return type is void
}
void StartBackgroundAlarms()
{
ProcUIInternalCallbackEntry* cb = s_backgroundCallbackList.first;
while(cb)
{
coreinit::OSCreateAlarm(&cb->alarm);
uint64 currentTime = coreinit::OSGetTime();
coreinit::OSSetPeriodicAlarm(&cb->alarm, currentTime, cb->tickDelay, RPLLoader_MakePPCCallable(AlarmDoBackgroundCallback));
cb = cb->next;
}
}
void CancelBackgroundAlarms()
{
ProcUIInternalCallbackEntry* entry = s_backgroundCallbackList.first;
while (entry)
{
OSCancelAlarm(&entry->alarm);
entry = entry->next;
}
}
void ProcUICoreThread(PPCInterpreter_t* hCPU)
{
uint32 coreIndex = hCPU->gpr[3];
cemu_assert_debug(coreIndex == OSGetCoreId());
while (true)
{
OSWaitEvent(&s_eventCoreThreadsNewCommandReady);
ProcUIInternalCallbackEntry* cbChain = nullptr;
cemuLog_logDebug(LogType::Force, "ProcUI: Core {} got command {}", coreIndex, (uint32)s_commandForCoreThread.load());
auto cmd = s_commandForCoreThread.load();
switch(cmd)
{
case ProcUICoreThreadCommand::Initial:
{
// signal to shut down thread
osLib_returnFromFunction(hCPU, 0);
return;
}
case ProcUICoreThreadCommand::AcquireForeground:
cbChain = s_callbacksType0_AcquireForeground[coreIndex].first;
break;
case ProcUICoreThreadCommand::ReleaseForeground:
cbChain = s_callbacksType1_ReleaseForeground[coreIndex].first;
break;
case ProcUICoreThreadCommand::Exit:
cbChain = s_callbacksType2_Exit[coreIndex].first;
break;
case ProcUICoreThreadCommand::NetIoStart:
cbChain = s_callbacksType3_NetIoStart[coreIndex].first;
break;
case ProcUICoreThreadCommand::NetIoStop:
cbChain = s_callbacksType4_NetIoStop[coreIndex].first;
break;
case ProcUICoreThreadCommand::HomeButtonDenied:
cbChain = s_callbacksType5_HomeButtonDenied[coreIndex].first;
break;
default:
cemu_assert_suspicious(); // invalid command
}
if(cmd == ProcUICoreThreadCommand::AcquireForeground)
{
if (coreIndex == 2)
CancelBackgroundAlarms();
cbChain = s_callbacksType0_AcquireForeground[coreIndex].first;
}
else if(cmd == ProcUICoreThreadCommand::ReleaseForeground)
{
if (coreIndex == 2)
StartBackgroundAlarms();
cbChain = s_callbacksType1_ReleaseForeground[coreIndex].first;
}
DoCallbackChain(cbChain);
OSWaitRendezvous(&s_coreThreadRendezvousA, 7);
if ( !coreIndex )
{
OSInitRendezvous(&s_coreThreadRendezvousC);
OSResetEvent(&s_eventCoreThreadsNewCommandReady);
}
OSWaitRendezvous(&s_coreThreadRendezvousB, 7);
if ( !coreIndex )
{
OSInitRendezvous(&s_coreThreadRendezvousA);
OSSignalEvent(&s_eventCoreThreadsCommandDone);
}
OSWaitRendezvous(&s_coreThreadRendezvousC, 7);
if ( !coreIndex )
OSInitRendezvous(&s_coreThreadRendezvousB);
if (cmd == ProcUICoreThreadCommand::ReleaseForeground)
{
OSWaitEvent(&s_eventWaitingBeforeReleaseForeground);
OSReleaseForeground();
}
}
osLib_returnFromFunction(hCPU, 0);
}
void RecreateProcUICoreThreads()
{
ShutdownThreads();
for (sint32 coreIndex = 0; coreIndex < Espresso::CORE_COUNT; coreIndex++)
{
s_coreThreadStackPerCore[coreIndex] = _AllocMem(s_coreThreadStackSize);
}
s_backgroundThreadStack = _AllocMem(s_coreThreadStackSize);
for (sint32 coreIndex = 0; coreIndex < Espresso::CORE_COUNT; coreIndex++)
{
__OSCreateThreadType(&s_coreThreadArray[coreIndex], RPLLoader_MakePPCCallable(ProcUICoreThread), coreIndex, nullptr,
(uint8*)s_coreThreadStackPerCore[coreIndex].GetPtr() + s_coreThreadStackSize, s_coreThreadStackSize, 16,
(1<<coreIndex), OSThread_t::THREAD_TYPE::TYPE_DRIVER);
OSResumeThread(&s_coreThreadArray[coreIndex]);
}
s_coreThread0NameBuffer->assign("{SYS ProcUI Core 0}");
s_coreThread1NameBuffer->assign("{SYS ProcUI Core 1}");
s_coreThread2NameBuffer->assign("{SYS ProcUI Core 2}");
OSSetThreadName(&s_coreThreadArray[0], s_coreThread0NameBuffer->c_str());
OSSetThreadName(&s_coreThreadArray[1], s_coreThread1NameBuffer->c_str());
OSSetThreadName(&s_coreThreadArray[2], s_coreThread2NameBuffer->c_str());
s_coreThreadsCreated = true;
}
void _SubmitCommandToCoreThreads(ProcUICoreThreadCommand cmd)
{
s_commandForCoreThread = cmd;
OSMemoryBarrier();
OSResetEvent(&s_eventCoreThreadsCommandDone);
OSSignalEvent(&s_eventCoreThreadsNewCommandReady);
OSWaitEvent(&s_eventCoreThreadsCommandDone);
}
void ProcUIInitInternal()
{
if( s_isInitialized.exchange(true) )
return;
if (!s_memoryPoolHeapPtr)
{
// user didn't specify a custom heap, use default heap instead
s_memAllocPtr = gCoreinitData->MEMAllocFromDefaultHeap.GetMPTR();
s_memFreePtr = gCoreinitData->MEMFreeToDefaultHeap.GetMPTR();
}
OSInitEvent(&s_eventStateMessageReceived, OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_MANUAL);
OSInitEvent(&s_eventCoreThreadsNewCommandReady, OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_MANUAL);
OSInitEvent(&s_eventWaitingBeforeReleaseForeground, OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_MANUAL);
OSInitEvent(&s_eventCoreThreadsCommandDone, OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_MANUAL);
OSInitRendezvous(&s_coreThreadRendezvousA);
OSInitRendezvous(&s_coreThreadRendezvousB);
OSInitRendezvous(&s_coreThreadRendezvousC);
OSInitEvent(&s_eventBackgroundThreadGotMessage, OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_MANUAL);
s_currentProcUIStatus = ProcUIStatus::Foreground;
s_drawDoneReleaseCalled = false;
s_isInForeground = true;
s_coreThreadStackSize = 0x2000;
s_systemMessageQueuePtr = coreinit::OSGetSystemMessageQueue();
uint32 upid = coreinit::OSGetUPID();
s_isForegroundProcess = upid == 2 || upid == 15; // either Wii U Menu or game title, both are RAMPID 7 (foreground process)
RecreateProcUICoreThreads();
ClearCallbacksWithoutMemFree();
}
void ProcUIInit(MEMPTR<void> callbackReadyToRelease)
{
s_saveCallback = callbackReadyToRelease;
s_saveCallbackEx = nullptr;
s_saveCallbackExUserParam = nullptr;
ProcUIInitInternal();
}
void ProcUIInitEx(MEMPTR<void> callbackReadyToReleaseEx, MEMPTR<void> userParam)
{
s_saveCallback = nullptr;
s_saveCallbackEx = callbackReadyToReleaseEx;
s_saveCallbackExUserParam = userParam;
ProcUIInitInternal();
}
void ProcUIShutdown()
{
if (!s_isInitialized.exchange(false))
return;
if ( !s_isInForeground )
CancelBackgroundAlarms();
for (sint32 i = 0; i < Espresso::CORE_COUNT; i++)
OSSetThreadPriority(&s_coreThreadArray[i], 0);
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::Exit);
ProcUIClearCallbacks();
ShutdownThreads();
}
bool ProcUIIsRunning()
{
return s_isInitialized;
}
bool ProcUIInForeground()
{
return s_isInForeground;
}
bool ProcUIInShutdown()
{
return s_isInShutdown;
}
void AddCallbackInternal(void* funcPtr, void* userParam, uint64 tickDelay, sint32 priority, ProcUICallbackList& callbackList)
{
if ( __OSGetProcessSDKVersion() < 21102 )
{
// in earlier COS versions it was possible/allowed to register a callback before initializing ProcUI
s_memAllocPtr = gCoreinitData->MEMAllocFromDefaultHeap.GetMPTR();
s_memFreePtr = gCoreinitData->MEMFreeToDefaultHeap.GetMPTR();
}
else if ( !s_isInitialized )
{
cemuLog_log(LogType::Force, "ProcUI: Trying to register callback before init");
cemu_assert_suspicious();
// this shouldn't happen but lets set the memory pointers anyway to prevent a crash in case the user has incorrect meta info
s_memAllocPtr = gCoreinitData->MEMAllocFromDefaultHeap.GetMPTR();
s_memFreePtr = gCoreinitData->MEMFreeToDefaultHeap.GetMPTR();
}
ProcUIInternalCallbackEntry* entry = (ProcUIInternalCallbackEntry*)_AllocMem(sizeof(ProcUIInternalCallbackEntry));
entry->funcPtr = funcPtr;
entry->userParam = userParam;
entry->tickDelay = tickDelay;
entry->priority = priority;
ProcUIInternalCallbackEntry* cur = callbackList.first;
cur = callbackList.first;
if (!cur || cur->priority > priority)
{
// insert as the first element
entry->next = cur;
callbackList.first = entry;
}
else
{
// find the correct position to insert
while (cur->next && cur->next->priority < priority)
cur = cur->next;
entry->next = cur->next;
cur->next = entry;
}
}
void ProcUIRegisterCallbackCore(ProcUICallbackId callbackType, void* funcPtr, void* userParam, sint32 priority, uint32 coreIndex)
{
if(callbackType >= ProcUICallbackId::COUNT)
{
cemuLog_log(LogType::Force, "ProcUIRegisterCallback: Invalid callback type {}", stdx::to_underlying(callbackType));
return;
}
if(callbackType != ProcUICallbackId::AcquireForeground)
priority = -priority;
AddCallbackInternal(funcPtr, userParam, 0, priority, s_CallbackTables[stdx::to_underlying(callbackType)][coreIndex]);
}
void ProcUIRegisterCallback(ProcUICallbackId callbackType, void* funcPtr, void* userParam, sint32 priority)
{
ProcUIRegisterCallbackCore(callbackType, funcPtr, userParam, priority, OSGetCoreId());
}
void ProcUIRegisterBackgroundCallback(void* funcPtr, void* userParam, uint64 tickDelay)
{
AddCallbackInternal(funcPtr, userParam, tickDelay, 0, s_backgroundCallbackList);
}
void FreeCallbackChain(ProcUICallbackList& callbackList)
{
ProcUIInternalCallbackEntry* entry = callbackList.first;
while (entry)
{
ProcUIInternalCallbackEntry* next = entry->next;
_FreeMem(entry);
entry = next;
}
callbackList.first = nullptr;
}
void ProcUIClearCallbacks()
{
for (sint32 coreIndex = 0; coreIndex < Espresso::CORE_COUNT; coreIndex++)
{
for (sint32 i = 0; i < stdx::to_underlying(ProcUICallbackId::COUNT); i++)
{
FreeCallbackChain(s_CallbackTables[i][coreIndex]);
}
}
if (!s_isInForeground)
CancelBackgroundAlarms();
FreeCallbackChain(s_backgroundCallbackList);
}
void ProcUISetSaveCallback(void* funcPtr, void* userParam)
{
s_saveCallback = nullptr;
s_saveCallbackEx = funcPtr;
s_saveCallbackExUserParam = userParam;
}
void ProcUISetCallbackStackSize(uint32 newStackSize)
{
s_coreThreadStackSize = newStackSize;
if( s_isInitialized )
RecreateProcUICoreThreads();
}
uint32 ProcUICalcMemorySize(uint32 numCallbacks)
{
// each callback entry is 0x70 bytes with 0x14 bytes of allocator overhead (for ExpHeap). But for some reason proc_ui on 5.5.5 seems to reserve 0x8C0 bytes per callback?
uint32 stackReserveSize = (Espresso::CORE_COUNT + 1) * s_coreThreadStackSize; // 3 core threads + 1 message receive thread
uint32 callbackReserveSize = 0x8C0 * numCallbacks;
return stackReserveSize + callbackReserveSize + 100;
}
void _MemAllocFromMemoryPool(PPCInterpreter_t* hCPU)
{
uint32 size = hCPU->gpr[3];
MEMPTR<void> r = MEMAllocFromExpHeapEx((MEMHeapHandle)s_memoryPoolHeapPtr.GetPtr(), size, 4);
osLib_returnFromFunction(hCPU, r.GetMPTR());
}
void _FreeToMemoryPoolExpHeap(PPCInterpreter_t* hCPU)
{
MEMPTR<void> mem{hCPU->gpr[3]};
MEMFreeToExpHeap((MEMHeapHandle)s_memoryPoolHeapPtr.GetPtr(), mem.GetPtr());
osLib_returnFromFunction(hCPU, 0);
}
sint32 ProcUISetMemoryPool(void* memBase, uint32 size)
{
s_memAllocPtr = RPLLoader_MakePPCCallable(_MemAllocFromMemoryPool);
s_memFreePtr = RPLLoader_MakePPCCallable(_FreeToMemoryPoolExpHeap);
s_memoryPoolHeapPtr = MEMCreateExpHeapEx(memBase, size, MEM_HEAP_OPTION_THREADSAFE);
return s_memoryPoolHeapPtr ? 0 : -1;
}
void ProcUISetBucketStorage(void* memBase, uint32 size)
{
MEMPTR<void> fgBase;
uint32be fgFreeSize;
OSGetForegroundBucketFreeArea(&fgBase, &fgFreeSize);
if(fgFreeSize < size)
cemuLog_log(LogType::Force, "ProcUISetBucketStorage: Buffer size too small");
s_bucketStorageBasePtr = memBase;
}
void ProcUISetMEM1Storage(void* memBase, uint32 size)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(1, &memBound, &memBoundSize);
if(memBoundSize < size)
cemuLog_log(LogType::Force, "ProcUISetMEM1Storage: Buffer size too small");
s_mem1StorageBasePtr = memBase;
}
void ProcUIDrawDoneRelease()
{
s_drawDoneReleaseCalled = true;
}
OSMessage g_lastMsg;
void ProcUI_BackgroundThread_ReceiveSingleMessage(PPCInterpreter_t* hCPU)
{
// the background thread receives messages in a loop until the title is either exited or foreground is acquired
while ( true )
{
OSReceiveMessage(s_systemMessageQueuePtr, &g_lastMsg, OS_MESSAGE_BLOCK); // blocking receive
SysMessageId lastMsgId = static_cast<SysMessageId>((uint32)g_lastMsg.data0);
if(lastMsgId == SysMessageId::MsgExit || lastMsgId == SysMessageId::MsgAcquireForeground)
break;
else if (lastMsgId == SysMessageId::HomeButtonDenied)
{
cemu_assert_suspicious(); // Home button denied should not be sent to background app
}
else if ( lastMsgId == SysMessageId::NetIoStartOrStop )
{
if (g_lastMsg.data1 )
{
// NetIo start message
for (sint32 i = 0; i < Espresso::CORE_COUNT; i++)
DoCallbackChain(s_callbacksType3_NetIoStart[i].first);
}
else
{
// NetIo stop message
for (sint32 i = 0; i < Espresso::CORE_COUNT; i++)
DoCallbackChain(s_callbacksType4_NetIoStop[i].first);
}
}
else
{
cemuLog_log(LogType::Force, "ProcUI: BackgroundThread received invalid message 0x{:08x}", lastMsgId);
}
}
OSSignalEvent(&s_eventBackgroundThreadGotMessage);
osLib_returnFromFunction(hCPU, 0);
}
// handle received message
// if the message is Exit this function returns false, in all other cases it returns true
bool ProcessSysMessage(OSMessage* msg)
{
SysMessageId lastMsgId = static_cast<SysMessageId>((uint32)msg->data0);
if ( lastMsgId == SysMessageId::MsgAcquireForeground )
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Acquire Foreground message");
s_isInShutdown = false;
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::AcquireForeground);
s_currentProcUIStatus = ProcUIStatus::Foreground;
s_isInForeground = true;
OSMemoryBarrier();
OSSignalEvent(&s_eventStateMessageReceived);
return true;
}
else if (lastMsgId == SysMessageId::MsgExit)
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Exit message");
s_isInShutdown = true;
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::Exit);
for (sint32 i = 0; i < Espresso::CORE_COUNT; i++)
FreeCallbackChain(s_callbacksType2_Exit[i]);
s_currentProcUIStatus = ProcUIStatus::Exit;
OSMemoryBarrier();
OSSignalEvent(&s_eventStateMessageReceived);
return 0;
}
if (lastMsgId == SysMessageId::MsgReleaseForeground)
{
if (msg->data1 != 0)
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Release Foreground message as part of shutdown initiation");
s_isInShutdown = true;
}
else
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Release Foreground message");
}
s_currentProcUIStatus = ProcUIStatus::Releasing;
OSResetEvent(&s_eventStateMessageReceived);
// dont submit a command for the core threads yet, we need to wait for ProcUIDrawDoneRelease()
}
else if (lastMsgId == SysMessageId::HomeButtonDenied)
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Home Button Denied message");
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::HomeButtonDenied);
}
else if ( lastMsgId == SysMessageId::NetIoStartOrStop )
{
if (msg->data1 != 0)
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Net IO Start message");
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::NetIoStart);
}
else
{
cemuLog_logDebug(LogType::Force, "ProcUI: Received Net IO Stop message");
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::NetIoStop);
}
}
else
{
cemuLog_log(LogType::Force, "ProcUI: Received unknown message 0x{:08x}", (uint32)lastMsgId);
}
return true;
}
ProcUIStatus ProcUIProcessMessages(bool isBlockingInBackground)
{
OSMessage msg;
if (!s_isInitialized)
{
cemuLog_logOnce(LogType::Force, "ProcUIProcessMessages: ProcUI not initialized");
cemu_assert_suspicious();
return ProcUIStatus::Foreground;
}
if ( !isBlockingInBackground && OSGetCoreId() != 2 )
{
cemuLog_logOnce(LogType::Force, "ProcUIProcessMessages: Non-blocking call must run on core 2");
}
if (s_previouslyWasBlocking && isBlockingInBackground )
{
cemuLog_logOnce(LogType::Force, "ProcUIProcessMessages: Cannot switch to blocking mode when in background");
}
s_currentProcUIStatus = s_isInForeground ? ProcUIStatus::Foreground : ProcUIStatus::Background;
if (s_drawDoneReleaseCalled)
{
s_isInForeground = false;
s_currentProcUIStatus = ProcUIStatus::Background;
_SubmitCommandToCoreThreads(ProcUICoreThreadCommand::ReleaseForeground);
OSResetEvent(&s_eventWaitingBeforeReleaseForeground);
if(s_saveCallback)
PPCCoreCallback(s_saveCallback);
if(s_saveCallbackEx)
PPCCoreCallback(s_saveCallbackEx, s_saveCallbackExUserParam);
if (s_isForegroundProcess && isBlockingInBackground)
{
// start background thread
__OSCreateThreadType(&s_backgroundThread, RPLLoader_MakePPCCallable(ProcUI_BackgroundThread_ReceiveSingleMessage),
0, nullptr, (uint8*)s_backgroundThreadStack.GetPtr() + s_coreThreadStackSize, s_coreThreadStackSize,
16, (1<<2), OSThread_t::THREAD_TYPE::TYPE_DRIVER);
OSResumeThread(&s_backgroundThread);
s_previouslyWasBlocking = true;
}
cemuLog_logDebug(LogType::Force, "ProcUI: Releasing foreground");
OSSignalEvent(&s_eventWaitingBeforeReleaseForeground);
s_drawDoneReleaseCalled = false;
}
if (s_isInForeground || !isBlockingInBackground)
{
// non-blocking mode
if ( OSReceiveMessage(s_systemMessageQueuePtr, &msg, 0) )
{
s_previouslyWasBlocking = false;
if ( !ProcessSysMessage(&msg) )
return s_currentProcUIStatus;
// continue below, if we are now in background then ProcUIProcessMessages enters blocking mode
}
}
// blocking mode (if in background and param is true)
while (!s_isInForeground && isBlockingInBackground)
{
if ( !s_isForegroundProcess)
{
OSReceiveMessage(s_systemMessageQueuePtr, &msg, OS_MESSAGE_BLOCK);
s_previouslyWasBlocking = false;
if ( !ProcessSysMessage(&msg) )
return s_currentProcUIStatus;
}
// this code should only run if the background thread was started? Maybe rearrange the code to make this more clear
OSWaitEvent(&s_eventBackgroundThreadGotMessage);
OSResetEvent(&s_eventBackgroundThreadGotMessage);
OSJoinThread(&s_backgroundThread, nullptr);
msg = g_lastMsg; // g_lastMsg is set by the background thread
s_previouslyWasBlocking = false;
if ( !ProcessSysMessage(&msg) )
return s_currentProcUIStatus;
}
return s_currentProcUIStatus;
}
ProcUIStatus ProcUISubProcessMessages(bool isBlockingInBackground)
{
if (isBlockingInBackground)
{
while (s_currentProcUIStatus == ProcUIStatus::Background)
OSWaitEvent(&s_eventStateMessageReceived);
}
return s_currentProcUIStatus;
}
const char* ProcUIDriver_GetName()
{
s_ProcUIDriverName->assign("ProcUI");
return s_ProcUIDriverName->c_str();
}
void ProcUIDriver_Init(/* parameters unknown */)
{
s_driverIsActive = true;
OSMemoryBarrier();
}
void ProcUIDriver_OnDone(/* parameters unknown */)
{
if (s_driverIsActive)
{
ProcUIShutdown();
s_driverIsActive = false;
OSMemoryBarrier();
}
}
void StoreMEM1AndFGBucket()
{
if (s_mem1StorageBasePtr)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(1, &memBound, &memBoundSize);
OSBlockMove(s_mem1StorageBasePtr.GetPtr(), memBound.GetPtr(), memBoundSize, true);
}
if (s_bucketStorageBasePtr)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetForegroundBucketFreeArea(&memBound, &memBoundSize);
OSBlockMove(s_bucketStorageBasePtr.GetPtr(), memBound.GetPtr(), memBoundSize, true);
}
}
void RestoreMEM1AndFGBucket()
{
if (s_mem1StorageBasePtr)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetMemBound(1, &memBound, &memBoundSize);
OSBlockMove(memBound.GetPtr(), s_mem1StorageBasePtr, memBoundSize, true);
GX2::GX2Invalidate(0x40, s_mem1StorageBasePtr.GetMPTR(), memBoundSize);
}
if (s_bucketStorageBasePtr)
{
MEMPTR<void> memBound;
uint32be memBoundSize;
OSGetForegroundBucketFreeArea(&memBound, &memBoundSize);
OSBlockMove(memBound.GetPtr(), s_bucketStorageBasePtr, memBoundSize, true);
GX2::GX2Invalidate(0x40, memBound.GetMPTR(), memBoundSize);
}
}
void ProcUIDriver_OnAcquiredForeground(/* parameters unknown */)
{
if (s_driverInBackground)
{
ProcUIDriver_Init();
s_driverInBackground = false;
}
else
{
RestoreMEM1AndFGBucket();
s_driverIsActive = true;
OSMemoryBarrier();
}
}
void ProcUIDriver_OnReleaseForeground(/* parameters unknown */)
{
StoreMEM1AndFGBucket();
s_driverIsActive = false;
OSMemoryBarrier();
}
sint32 rpl_entry(uint32 moduleHandle, RplEntryReason reason)
{
if ( reason == RplEntryReason::Loaded )
{
s_ProcUIDriver->getDriverName = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) {MEMPTR<const char> namePtr(ProcUIDriver_GetName()); osLib_returnFromFunction(hCPU, namePtr.GetMPTR()); });
s_ProcUIDriver->init = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) {ProcUIDriver_Init(); osLib_returnFromFunction(hCPU, 0); });
s_ProcUIDriver->onAcquireForeground = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) {ProcUIDriver_OnAcquiredForeground(); osLib_returnFromFunction(hCPU, 0); });
s_ProcUIDriver->onReleaseForeground = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) {ProcUIDriver_OnReleaseForeground(); osLib_returnFromFunction(hCPU, 0); });
s_ProcUIDriver->done = RPLLoader_MakePPCCallable([](PPCInterpreter_t* hCPU) {ProcUIDriver_OnDone(); osLib_returnFromFunction(hCPU, 0); });
s_driverIsActive = false;
s_driverArgUkn1 = 0;
s_driverArgUkn2 = 0;
s_driverInBackground = false;
uint32be ukn3;
OSDriver_Register(moduleHandle, 200, &s_ProcUIDriver, 0, &s_driverArgUkn1, &s_driverArgUkn2, &ukn3);
if ( ukn3 )
{
if ( OSGetForegroundBucket(nullptr, nullptr) )
{
ProcUIDriver_Init();
OSMemoryBarrier();
return 0;
}
s_driverInBackground = true;
}
OSMemoryBarrier();
}
else if ( reason == RplEntryReason::Unloaded )
{
ProcUIDriver_OnDone();
OSDriver_Deregister(moduleHandle, 0);
}
return 0;
}
void reset()
{
// set variables to their initial state as if the RPL was just loaded
s_isInitialized = false;
s_isInShutdown = false;
s_isInForeground = false; // ProcUIInForeground returns false until ProcUIInit(Ex) is called
s_isForegroundProcess = true;
s_saveCallback = nullptr;
s_saveCallbackEx = nullptr;
s_systemMessageQueuePtr = nullptr;
ClearCallbacksWithoutMemFree();
s_currentProcUIStatus = ProcUIStatus::Foreground;
s_bucketStorageBasePtr = nullptr;
s_mem1StorageBasePtr = nullptr;
s_drawDoneReleaseCalled = false;
s_previouslyWasBlocking = false;
// core threads
s_coreThreadStackSize = 0;
s_coreThreadsCreated = false;
s_commandForCoreThread = ProcUICoreThreadCommand::Initial;
// background thread
s_backgroundThreadStack = nullptr;
// user defined heap
s_memoryPoolHeapPtr = nullptr;
s_memAllocPtr = nullptr;
s_memFreePtr = nullptr;
// driver
s_driverIsActive = false;
s_driverInBackground = false;
}
void load()
{
reset();
cafeExportRegister("proc_ui", ProcUIInit, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIInitEx, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIShutdown, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIIsRunning, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIInForeground, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIInShutdown, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIRegisterCallbackCore, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIRegisterCallback, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIRegisterBackgroundCallback, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIClearCallbacks, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUISetSaveCallback, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUISetCallbackStackSize, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUICalcMemorySize, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUISetMemoryPool, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUISetBucketStorage, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUISetMEM1Storage, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIDrawDoneRelease, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUIProcessMessages, LogType::ProcUi);
cafeExportRegister("proc_ui", ProcUISubProcessMessages, LogType::ProcUi);
// manually call rpl_entry for now
rpl_entry(-1, RplEntryReason::Loaded);
}
};
| 31,320
|
C++
|
.cpp
| 847
| 33.729634
| 195
| 0.766967
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,073
|
nn_olv_InitializeTypes.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_InitializeTypes.cpp
|
#pragma once
#include "nn_olv_InitializeTypes.h"
#include "CafeSystem.h"
#include "Cafe/OS/libs/nn_act/nn_act.h"
#include <time.h>
namespace nn
{
namespace olv
{
uint32_t g_ReportTypes = 0;
bool g_IsOnlineMode = false;
bool g_IsInitialized = false;
bool g_IsOfflineDBMode = false;
ParamPackStorage g_ParamPack;
DiscoveryResultStorage g_DiscoveryResults;
sint32 GetOlvAccessKey(uint32_t* pOutKey)
{
*pOutKey = 0;
uint32_t accessKey = CafeSystem::GetForegroundTitleOlvAccesskey();
if (accessKey == -1)
return OLV_RESULT_STATUS(1102);
*pOutKey = accessKey;
return OLV_RESULT_SUCCESS;
}
sint32 CreateParamPack(uint64_t titleId, uint32_t accessKey)
{
g_ParamPack.languageId = uint8(GetConfig().console_language.GetValue());
uint32be simpleAddress = 0;
nn::act::GetSimpleAddressIdEx(&simpleAddress, nn::act::ACT_SLOT_CURRENT);
uint32 countryCode = nn::act::getCountryCodeFromSimpleAddress(simpleAddress);
g_ParamPack.countryId = countryCode;
g_ParamPack.titleId = titleId;
g_ParamPack.platformId = 1;
g_ParamPack.areaId = (simpleAddress >> 8) & 0xff;
MCPHANDLE handle = MCP_Open();
SysProdSettings sysProdSettings;
MCP_GetSysProdSettings(handle, &sysProdSettings);
MCP_Close(handle);
g_ParamPack.regionId = sysProdSettings.platformRegion;
g_ParamPack.accessKey = accessKey;
g_ParamPack.networkRestriction = 0;
g_ParamPack.friendRestriction = 0;
g_ParamPack.ratingRestriction = 18;
g_ParamPack.ratingOrganization = 4; // PEGI ?
uint64 transferrableId;
nn::act::GetTransferableIdEx(&transferrableId, (titleId >> 8) & 0xFFFFF, nn::act::ACT_SLOT_CURRENT);
g_ParamPack.transferableId = transferrableId;
strcpy(g_ParamPack.tzName, "CEMU/Olive"); // Should be nn::act::GetTimeZoneId
g_ParamPack.utcOffset = (uint64_t)nn::act::GetUtcOffset() / 1'000'000;
char paramPackStr[1024];
snprintf(
paramPackStr,
sizeof(paramPackStr),
"\\%s\\%llu\\%s\\%u\\%s\\%u\\%s\\%d\\%s\\%d\\%s\\%d\\%s\\%d\\%s\\%d\\%s\\%d\\%s\\%u\\%s\\%d\\%s\\%llu\\"
"%s\\%s\\%s\\%lld\\",
"title_id",
g_ParamPack.titleId,
"access_key",
g_ParamPack.accessKey,
"platform_id",
g_ParamPack.platformId,
"region_id",
g_ParamPack.regionId,
"language_id",
g_ParamPack.languageId,
"country_id",
g_ParamPack.countryId,
"area_id",
g_ParamPack.areaId,
"network_restriction",
g_ParamPack.networkRestriction,
"friend_restriction",
g_ParamPack.friendRestriction,
"rating_restriction",
g_ParamPack.ratingRestriction,
"rating_organization",
g_ParamPack.ratingOrganization,
"transferable_id",
g_ParamPack.transferableId,
"tz_name",
g_ParamPack.tzName,
"utc_offset",
g_ParamPack.utcOffset);
std::string encodedParamPack = NCrypto::base64Encode(paramPackStr, strnlen(paramPackStr, 1024));
memset(&g_ParamPack.encodedParamPack, 0, sizeof(g_ParamPack.encodedParamPack));
memcpy(&g_ParamPack.encodedParamPack, encodedParamPack.data(), encodedParamPack.size());
return OLV_RESULT_SUCCESS;
}
sint32 MakeDiscoveryRequest_AsyncRequestImpl(CurlRequestHelper& req, const char* reqUrl)
{
bool reqResult = req.submitRequest();
long httpCode = 0;
curl_easy_getinfo(req.getCURL(), CURLINFO_RESPONSE_CODE, &httpCode);
if (!reqResult)
{
cemuLog_log(LogType::Force, "Failed request: {} ({})", reqUrl, httpCode);
if (!(httpCode >= 400))
return OLV_RESULT_FAILED_REQUEST;
}
pugi::xml_document doc;
if (!doc.load_buffer(req.getReceivedData().data(), req.getReceivedData().size()))
{
cemuLog_log(LogType::Force, fmt::format("Invalid XML in discovery service response"));
return OLV_RESULT_INVALID_XML;
}
sint32 responseError = CheckOliveResponse(doc);
if (responseError < 0)
return responseError;
if (httpCode != 200)
return OLV_RESULT_STATUS(httpCode + 4000);
/*
<result>
<has_error>0</has_error>
<version>1</version>
<endpoint>
<host>api.olv.pretendo.cc</host>
<api_host>api.olv.pretendo.cc</api_host>
<portal_host>portal.olv.pretendo.cc</portal_host>
<n3ds_host>ctr.olv.pretendo.cc</n3ds_host>
</endpoint>
</result>
*/
pugi::xml_node resultNode = doc.child("result");
if (!resultNode)
{
cemuLog_log(LogType::Force, "Discovery response doesn't contain <result>");
return OLV_RESULT_INVALID_XML;
}
pugi::xml_node endpointNode = resultNode.child("endpoint");
if (!endpointNode)
{
cemuLog_log(LogType::Force, "Discovery response doesn't contain <result><endpoint>");
return OLV_RESULT_INVALID_XML;
}
// Yes it only uses <host> and <portal_host>
std::string_view host = endpointNode.child_value("host");
std::string_view portal_host = endpointNode.child_value("portal_host");
snprintf(g_DiscoveryResults.apiEndpoint, sizeof(g_DiscoveryResults.apiEndpoint), "https://%s", host.data());
snprintf(g_DiscoveryResults.portalEndpoint, sizeof(g_DiscoveryResults.portalEndpoint), "https://%s", portal_host.data());
return OLV_RESULT_SUCCESS;
}
sint32 MakeDiscoveryRequest_AsyncRequest(CurlRequestHelper& req, const char* reqUrl, coreinit::OSEvent* requestDoneEvent)
{
sint32 res = MakeDiscoveryRequest_AsyncRequestImpl(req, reqUrl);
coreinit::OSSignalEvent(requestDoneEvent);
return res;
}
sint32 MakeDiscoveryRequest()
{
// =============================================================================
// Discovery request | https://discovery.olv.nintendo.net/v1/endpoint
// =============================================================================
CurlRequestHelper req;
std::string requestUrl;
switch (ActiveSettings::GetNetworkService())
{
case NetworkService::Pretendo:
requestUrl = PretendoURLs::OLVURL;
break;
case NetworkService::Custom:
requestUrl = GetNetworkConfig().urls.OLV.GetValue();
break;
case NetworkService::Nintendo:
default:
requestUrl = NintendoURLs::OLVURL;
break;
}
req.initate(ActiveSettings::GetNetworkService(), requestUrl, CurlRequestHelper::SERVER_SSL_CONTEXT::OLIVE);
InitializeOliveRequest(req);
StackAllocator<coreinit::OSEvent> requestDoneEvent;
coreinit::OSInitEvent(&requestDoneEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_MANUAL);
std::future<sint32> requestRes = std::async(std::launch::async, MakeDiscoveryRequest_AsyncRequest, std::ref(req), requestUrl.c_str(), requestDoneEvent.GetPointer());
coreinit::OSWaitEvent(&requestDoneEvent);
return requestRes.get();
}
sint32 Initialize(nn::olv::InitializeParam* pParam)
{
if (g_IsInitialized)
return OLV_RESULT_ALREADY_INITIALIZED;
if (!pParam->m_Work)
{
g_IsInitialized = false;
return OLV_RESULT_INVALID_PTR;
}
if (pParam->m_WorkSize < 0x10000)
{
g_IsInitialized = false;
return OLV_RESULT_INVALID_SIZE;
}
uint32_t accessKey;
int32_t olvAccessKeyStatus = GetOlvAccessKey(&accessKey);
if (olvAccessKeyStatus < 0)
{
g_IsInitialized = false;
return olvAccessKeyStatus;
}
uint64_t tid = CafeSystem::GetForegroundTitleId();
int32_t createParamPackResult = CreateParamPack(tid, accessKey);
if (createParamPackResult < 0)
{
g_IsInitialized = false;
return createParamPackResult;
}
g_IsInitialized = true;
if(ActiveSettings::GetNetworkService() == NetworkService::Nintendo)
{
// since the official Miiverse was shut down, use local post archive instead
g_IsOnlineMode = true;
g_IsOfflineDBMode = true;
return OLV_RESULT_SUCCESS;
}
if ((pParam->m_Flags & InitializeParam::FLAG_OFFLINE_MODE) == 0)
{
g_IsOnlineMode = true;
independentServiceToken_t token;
sint32 res = (sint32)nn::act::AcquireIndependentServiceToken(&token, OLV_CLIENT_ID, 0);
if (res < 0)
{
g_IsInitialized = false;
return res;
}
// Assuming we're always a production WiiU (non-dev)
uint32 uniqueId = (CafeSystem::GetForegroundTitleId() >> 8) & 0xFFFFF;
char versionBuffer[32];
snprintf(versionBuffer, sizeof(versionBuffer), "%d.%d.%d", OLV_VERSION_MAJOR, OLV_VERSION_MINOR, OLV_VERSION_PATCH);
snprintf(g_DiscoveryResults.userAgent, sizeof(g_DiscoveryResults.userAgent), "%s/%s-%s/%d", "WiiU", "POLV", versionBuffer, uniqueId);
memcpy(g_DiscoveryResults.serviceToken, token.token, sizeof(g_DiscoveryResults.serviceToken));
sint32 discoveryRes = MakeDiscoveryRequest();
if (discoveryRes < 0)
g_IsInitialized = false;
return discoveryRes;
}
return OLV_RESULT_SUCCESS;
}
namespace Report
{
uint32 GetReportTypes()
{
return g_ReportTypes;
}
void SetReportTypes(uint32 reportTypes)
{
g_ReportTypes = reportTypes | 0x1000;
}
}
bool IsInitialized()
{
return g_IsInitialized;
}
}
}
| 9,232
|
C++
|
.cpp
| 251
| 31.163347
| 169
| 0.679874
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,074
|
nn_olv_UploadFavoriteTypes.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_UploadFavoriteTypes.cpp
|
#include "nn_olv_UploadFavoriteTypes.h"
#include <algorithm>
namespace nn
{
namespace olv
{
sint32 UploadFavoriteToCommunityData_AsyncRequestImpl(CurlRequestHelper& req, const char* reqUrl,
UploadedFavoriteToCommunityData* pOutData, const UploadFavoriteToCommunityDataParam* pParam
);
sint32 UploadFavoriteToCommunityData_AsyncRequest(CurlRequestHelper& req, const char* reqUrl, coreinit::OSEvent* requestDoneEvent,
UploadedFavoriteToCommunityData* pOutData, const UploadFavoriteToCommunityDataParam* pParam
)
{
sint32 res = UploadFavoriteToCommunityData_AsyncRequestImpl(req, reqUrl, pOutData, pParam);
coreinit::OSSignalEvent(requestDoneEvent);
return res;
}
sint32 UploadFavoriteToCommunityData(UploadedFavoriteToCommunityData* pOutData, const UploadFavoriteToCommunityDataParam* pParam)
{
if (!nn::olv::g_IsInitialized)
return OLV_RESULT_NOT_INITIALIZED;
if (!nn::olv::g_IsOnlineMode)
return OLV_RESULT_OFFLINE_MODE_REQUEST;
if (!pParam)
return OLV_RESULT_INVALID_PTR;
if (pOutData)
UploadedFavoriteToCommunityData::Clean(pOutData);
char requestUrl[512];
if (pParam->flags & UploadFavoriteToCommunityDataParam::FLAG_DELETION)
snprintf(requestUrl, sizeof(requestUrl), "%s/v1/communities/%lu.unfavorite", g_DiscoveryResults.apiEndpoint, pParam->communityId.value());
else
snprintf(requestUrl, sizeof(requestUrl), "%s/v1/communities/%lu.favorite", g_DiscoveryResults.apiEndpoint, pParam->communityId.value());
CurlRequestHelper req;
req.initate(ActiveSettings::GetNetworkService(), requestUrl, CurlRequestHelper::SERVER_SSL_CONTEXT::OLIVE);
InitializeOliveRequest(req);
StackAllocator<coreinit::OSEvent> requestDoneEvent;
coreinit::OSInitEvent(&requestDoneEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_MANUAL);
std::future<sint32> requestRes = std::async(std::launch::async, UploadFavoriteToCommunityData_AsyncRequest, std::ref(req), requestUrl, requestDoneEvent.GetPointer(), pOutData, pParam);
coreinit::OSWaitEvent(&requestDoneEvent);
return requestRes.get();
}
sint32 UploadFavoriteToCommunityData(const UploadFavoriteToCommunityDataParam* pParam)
{
return UploadFavoriteToCommunityData(nullptr, pParam);
}
sint32 UploadFavoriteToCommunityData_AsyncRequestImpl(CurlRequestHelper& req, const char* reqUrl,
UploadedFavoriteToCommunityData* pOutData, const UploadFavoriteToCommunityDataParam* pParam
)
{
bool reqResult = req.submitRequest(true);
long httpCode = 0;
curl_easy_getinfo(req.getCURL(), CURLINFO_RESPONSE_CODE, &httpCode);
if (!reqResult)
{
cemuLog_log(LogType::Force, "Failed request: {} ({})", reqUrl, httpCode);
if (!(httpCode >= 400))
return OLV_RESULT_FAILED_REQUEST;
}
pugi::xml_document doc;
if (!doc.load_buffer(req.getReceivedData().data(), req.getReceivedData().size()))
{
cemuLog_log(LogType::Force, fmt::format("Invalid XML in community favorite upload response"));
return OLV_RESULT_INVALID_XML;
}
sint32 responseError = CheckOliveResponse(doc);
if (responseError < 0)
return responseError;
if (httpCode != 200)
return OLV_RESULT_STATUS(httpCode + 4000);
if (pOutData)
{
std::string_view app_data = doc.select_single_node("//app_data").node().child_value();
std::string_view community_id = doc.select_single_node("//community_id").node().child_value();
std::string_view name = doc.select_single_node("//name").node().child_value();
std::string_view description = doc.select_single_node("//description").node().child_value();
std::string_view pid = doc.select_single_node("//pid").node().child_value();
std::string_view icon = doc.select_single_node("//icon").node().child_value();
if (app_data.size() != 0)
{
auto app_data_bin = NCrypto::base64Decode(app_data);
if (app_data_bin.size() != 0)
{
memcpy(pOutData->appData, app_data_bin.data(), std::min(size_t(0x400), app_data_bin.size()));
pOutData->flags |= UploadedFavoriteToCommunityData::FLAG_HAS_APP_DATA;
pOutData->appDataLen = app_data_bin.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
sint64 community_id_val = StringHelpers::ToInt64(community_id, -1);
if (community_id_val == -1)
return OLV_RESULT_INVALID_INTEGER_FIELD;
pOutData->communityId = community_id_val;
if (name.size() != 0)
{
auto name_utf16 = StringHelpers::FromUtf8(name).substr(0, 128);
if (name_utf16.size() != 0)
{
for (int i = 0; i < name_utf16.size(); i++)
pOutData->titleText[i] = name_utf16.at(i);
pOutData->flags |= UploadedFavoriteToCommunityData::FLAG_HAS_TITLE_TEXT;
pOutData->titleTextMaxLen = name_utf16.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
if (description.size() != 0)
{
auto description_utf16 = StringHelpers::FromUtf8(description).substr(0, 256);
if (description_utf16.size() != 0)
{
for (int i = 0; i < description_utf16.size(); i++)
pOutData->description[i] = description_utf16.at(i);
pOutData->flags |= UploadedFavoriteToCommunityData::FLAG_HAS_DESC_TEXT;
pOutData->descriptionMaxLen = description_utf16.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
sint64 pid_val = StringHelpers::ToInt64(pid, -1);
if (pid_val == -1)
return OLV_RESULT_INVALID_INTEGER_FIELD;
pOutData->pid = pid_val;
if (icon.size() != 0)
{
auto icon_bin = NCrypto::base64Decode(icon);
if (icon_bin.size() != 0)
{
memcpy(pOutData->iconData, icon_bin.data(), std::min(size_t(0x1002c), icon_bin.size()));
pOutData->flags |= UploadedFavoriteToCommunityData::FLAG_HAS_ICON_DATA;
pOutData->iconDataSize = icon_bin.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
}
return OLV_RESULT_SUCCESS;
}
}
}
| 6,139
|
C++
|
.cpp
| 140
| 37.692857
| 188
| 0.698889
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,075
|
nn_olv_PostTypes.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_PostTypes.cpp
|
#include "Cafe/OS/libs/nn_olv/nn_olv_Common.h"
#include "nn_olv_PostTypes.h"
#include "nn_olv_OfflineDB.h"
#include "Cemu/ncrypto/ncrypto.h" // for base64 decoder
#include "util/helpers/helpers.h"
#include <pugixml.hpp>
#include <zlib.h>
namespace nn
{
namespace olv
{
bool ParseXml_DownloadedDataBase(DownloadedDataBase& obj, pugi::xml_node& xmlNode)
{
// todo:
// painting with url?
pugi::xml_node tokenNode;
if(tokenNode = xmlNode.child("body"); tokenNode)
{
obj.bodyTextLength = SetStringUC2(obj.bodyText, tokenNode.child_value(), true);
if(obj.bodyTextLength > 0)
obj.SetFlag(DownloadedDataBase::FLAGS::HAS_BODY_TEXT);
}
if(tokenNode = xmlNode.child("topic_tag"); tokenNode)
{
SetStringUC2(obj.topicTag, tokenNode.child_value(), true);
}
if(tokenNode = xmlNode.child("feeling_id"); tokenNode)
{
obj.feeling = ConvertString<sint8>(tokenNode.child_value());
if(obj.feeling < 0 || obj.feeling >= 5)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedDataBase::ParseXml: feeling_id out of range");
return false;
}
}
if(tokenNode = xmlNode.child("id"); tokenNode)
{
std::string_view id_sv = tokenNode.child_value();
if(id_sv.size() > 22)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedDataBase::ParseXml: id too long");
return false;
}
memcpy(obj.postId, id_sv.data(), id_sv.size());
obj.postId[id_sv.size()] = '\0';
}
if(tokenNode = xmlNode.child("is_autopost"); tokenNode)
{
uint8 isAutopost = ConvertString<sint8>(tokenNode.child_value());
if(isAutopost == 1)
obj.SetFlag(DownloadedDataBase::FLAGS::IS_AUTOPOST);
else if(isAutopost == 0)
obj.SetFlag(DownloadedDataBase::FLAGS::IS_NOT_AUTOPOST);
else
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedDataBase::ParseXml: is_autopost has invalid value");
return false;
}
}
if(tokenNode = xmlNode.child("empathy_added"); tokenNode)
{
if(ConvertString<sint32>(tokenNode.child_value()) > 0)
obj.SetFlag(DownloadedDataBase::FLAGS::HAS_EMPATHY_ADDED);
}
if(tokenNode = xmlNode.child("is_spoiler"); tokenNode)
{
if(ConvertString<sint32>(tokenNode.child_value()) > 0)
obj.SetFlag(DownloadedDataBase::FLAGS::IS_SPOILER);
}
if(tokenNode = xmlNode.child("mii"); tokenNode)
{
std::vector<uint8> miiData = NCrypto::base64Decode(tokenNode.child_value());
if(miiData.size() != 96)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedSystemTopicData mii data is not valid (incorrect size)");
return false;
}
memcpy(obj.miiData, miiData.data(), miiData.size());
obj.SetFlag(DownloadedDataBase::FLAGS::HAS_MII_DATA);
}
if(tokenNode = xmlNode.child("pid"); tokenNode)
{
obj.userPid = ConvertString<uint32>(tokenNode.child_value());
}
if(tokenNode = xmlNode.child("screen_name"); tokenNode)
{
SetStringUC2(obj.miiNickname, tokenNode.child_value(), true);
}
if(tokenNode = xmlNode.child("region_id"); tokenNode)
{
obj.regionId = ConvertString<uint32>(tokenNode.child_value());
}
if(tokenNode = xmlNode.child("platform_id"); tokenNode)
{
obj.platformId = ConvertString<uint8>(tokenNode.child_value());
}
if(tokenNode = xmlNode.child("language_id"); tokenNode)
{
obj.languageId = ConvertString<uint8>(tokenNode.child_value());
}
if(tokenNode = xmlNode.child("country_id"); tokenNode)
{
obj.countryId = ConvertString<uint8>(tokenNode.child_value());
}
if(tokenNode = xmlNode.child("painting"); tokenNode)
{
if(pugi::xml_node subNode = tokenNode.child("content"); subNode)
{
std::vector<uint8> paintingData = NCrypto::base64Decode(subNode.child_value());
if (paintingData.size() > 0xA000)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedDataBase painting content is too large");
return false;
}
memcpy(obj.compressedMemoBody, paintingData.data(), paintingData.size());
obj.SetFlag(DownloadedDataBase::FLAGS::HAS_BODY_MEMO);
}
if(pugi::xml_node subNode = tokenNode.child("size"); subNode)
{
obj.compressedMemoBodySize = ConvertString<uint32>(subNode.child_value());
}
}
if(tokenNode = xmlNode.child("app_data"); tokenNode)
{
std::vector<uint8> appData = NCrypto::base64Decode(tokenNode.child_value());
if (appData.size() > 0x400)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedDataBase AppData is too large");
return false;
}
memcpy(obj.appData, appData.data(), appData.size());
obj.appDataLength = appData.size();
obj.SetFlag(DownloadedDataBase::FLAGS::HAS_APP_DATA);
}
return true;
}
bool ParseXML_DownloadedPostData(DownloadedPostData& obj, pugi::xml_node& xmlNode)
{
pugi::xml_node tokenNode;
if(tokenNode = xmlNode.child("community_id"); tokenNode)
obj.communityId = ConvertString<uint32>(tokenNode.child_value());
if(tokenNode = xmlNode.child("empathy_count"); tokenNode)
obj.empathyCount = ConvertString<uint32>(tokenNode.child_value());
if(tokenNode = xmlNode.child("reply_count"); tokenNode)
obj.commentCount = ConvertString<uint32>(tokenNode.child_value());
return ParseXml_DownloadedDataBase(obj.downloadedDataBase, xmlNode);
}
bool ParseXML_DownloadedSystemPostData(hidden::DownloadedSystemPostData& obj, pugi::xml_node& xmlNode)
{
pugi::xml_node tokenNode;
if(tokenNode = xmlNode.child("title_id"); tokenNode)
obj.titleId = ConvertString<uint64>(tokenNode.child_value());
return ParseXML_DownloadedPostData(obj.downloadedPostData, xmlNode);
}
bool ParseXML_DownloadedTopicData(DownloadedTopicData& obj, pugi::xml_node& xmlNode)
{
pugi::xml_node tokenNode;
if(tokenNode = xmlNode.child("community_id"); tokenNode)
obj.communityId = ConvertString<uint32>(tokenNode.child_value());
return true;
}
bool Parse_DownloadedSystemTopicData(hidden::DownloadedSystemTopicData& obj, pugi::xml_node& xmlNode)
{
if(!ParseXML_DownloadedTopicData(obj.downloadedTopicData, xmlNode))
return false;
pugi::xml_node tokenNode;
if(tokenNode = xmlNode.child("name"); tokenNode)
{
SetStringUC2(obj.titleText, tokenNode.child_value(), true);
obj.downloadedTopicData.SetFlag(DownloadedTopicData::FLAGS::HAS_TITLE);
}
if(tokenNode = xmlNode.child("is_recommended"); tokenNode)
{
uint32 isRecommended = ConvertString<uint32>(tokenNode.child_value());
if(isRecommended != 0)
obj.downloadedTopicData.SetFlag(DownloadedTopicData::FLAGS::IS_RECOMMENDED);
}
if(tokenNode = xmlNode.child("title_id"); tokenNode)
{
obj.titleId = ConvertString<uint64>(tokenNode.child_value());
}
if(tokenNode = xmlNode.child("title_ids"); tokenNode)
{
cemu_assert_unimplemented();
}
if(tokenNode = xmlNode.child("icon"); tokenNode)
{
std::vector<uint8> iconData = NCrypto::base64Decode(tokenNode.child_value());
if(iconData.size() > sizeof(obj.iconData))
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedSystemTopicData icon data is not valid");
return false;
}
obj.iconDataSize = iconData.size();
memcpy(obj.iconData, iconData.data(), iconData.size());
obj.downloadedTopicData.SetFlag(DownloadedTopicData::FLAGS::HAS_ICON_DATA);
}
return true;
}
uint32 GetSystemTopicDataListFromRawData(hidden::DownloadedSystemTopicDataList* downloadedSystemTopicDataList, hidden::DownloadedSystemPostData* downloadedSystemPostData, uint32be* postCountOut, uint32 postCountMax, void* xmlData, uint32 xmlDataSize)
{
// copy xmlData into a temporary buffer since load_buffer_inplace will modify it
std::vector<uint8> buffer;
buffer.resize(xmlDataSize);
memcpy(buffer.data(), xmlData, xmlDataSize);
pugi::xml_document doc;
if (!doc.load_buffer_inplace(buffer.data(), xmlDataSize, pugi::parse_default, pugi::xml_encoding::encoding_utf8))
return -1;
memset(downloadedSystemTopicDataList, 0, sizeof(hidden::DownloadedSystemTopicDataList));
downloadedSystemTopicDataList->topicDataNum = 0;
cemu_assert_debug(doc.child("result").child("topics"));
size_t postCount = 0;
// parse topics
for (pugi::xml_node topicsChildNode : doc.child("result").child("topics").children())
{
const char* name = topicsChildNode.name();
cemuLog_logDebug(LogType::Force, "topicsChildNode.name() = {}", name);
if (strcmp(topicsChildNode.name(), "topic"))
continue;
// parse topic
if(downloadedSystemTopicDataList->topicDataNum > 10)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedSystemTopicDataList exceeded maximum topic count (10)");
return false;
}
auto& topicEntry = downloadedSystemTopicDataList->topicData[downloadedSystemTopicDataList->topicDataNum];
memset(&topicEntry, 0, sizeof(hidden::DownloadedSystemTopicDataList::DownloadedSystemTopicWrapped));
Parse_DownloadedSystemTopicData(topicEntry.downloadedSystemTopicData, topicsChildNode);
downloadedSystemTopicDataList->topicDataNum = downloadedSystemTopicDataList->topicDataNum + 1;
topicEntry.postDataNum = 0;
// parse all posts within the current topic
for (pugi::xml_node personNode : topicsChildNode.child("people").children("person"))
{
for (pugi::xml_node postNode : personNode.child("posts").children("post"))
{
if(postCount >= postCountMax)
{
cemuLog_log(LogType::Force, "[Olive-XML] GetSystemTopicDataListFromRawData exceeded maximum post count");
return false;
}
auto& postEntry = downloadedSystemPostData[postCount];
memset(&postEntry, 0, sizeof(hidden::DownloadedSystemPostData));
bool r = ParseXML_DownloadedSystemPostData(postEntry, postNode);
if(!r)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedSystemPostData parsing failed");
return false;
}
postCount++;
// add post to topic
if(topicEntry.postDataNum >= hidden::DownloadedSystemTopicDataList::MAX_POSTS_PER_TOPIC)
{
cemuLog_log(LogType::Force, "[Olive-XML] DownloadedSystemTopicDataList has too many posts for a single topic (up to {})", hidden::DownloadedSystemTopicDataList::MAX_POSTS_PER_TOPIC);
return false;
}
topicEntry.postDataList[topicEntry.postDataNum] = &postEntry;
topicEntry.postDataNum = topicEntry.postDataNum + 1;
}
}
}
*postCountOut = postCount;
return 0;
}
nnResult DownloadedDataBase::DownloadExternalImageData(DownloadedDataBase* _this, void* imageDataOut, uint32be* imageSizeOut, uint32 maxSize)
{
if(g_IsOfflineDBMode)
return OfflineDB_DownloadPostDataListParam_DownloadExternalImageData(_this, imageDataOut, imageSizeOut, maxSize);
if(!g_IsOnlineMode)
return OLV_RESULT_OFFLINE_MODE_REQUEST;
if (!TestFlags(_this, FLAGS::HAS_EXTERNAL_IMAGE))
return OLV_RESULT_MISSING_DATA;
cemuLog_logDebug(LogType::Force, "DownloadedDataBase::DownloadExternalImageData not implemented");
return OLV_RESULT_FAILED_REQUEST; // placeholder error
}
nnResult DownloadPostDataListParam::GetRawDataUrl(DownloadPostDataListParam* _this, char* urlOut, uint32 urlMaxSize)
{
if(!g_IsOnlineMode)
return OLV_RESULT_OFFLINE_MODE_REQUEST;
//if(_this->communityId == 0)
// cemuLog_log(LogType::Force, "DownloadPostDataListParam::GetRawDataUrl called with invalid communityId");
// get base url
std::string baseUrl;
baseUrl.append(g_DiscoveryResults.apiEndpoint);
//baseUrl.append(fmt::format("/v1/communities/{}/posts", (uint32)_this->communityId));
cemu_assert_debug(_this->communityId == 0);
baseUrl.append(fmt::format("/v1/posts.search", (uint32)_this->communityId));
// "v1/posts.search"
// build parameter string
std::string params;
// this function behaves differently for the Wii U menu? Where it can lookup posts by titleId?
if(_this->titleId != 0)
{
cemu_assert_unimplemented(); // Wii U menu mode
}
// todo: Generic parameters. Which includes: language_id, limit, type=text/memo
// handle postIds
for(size_t i=0; i<_this->MAX_NUM_POST_ID; i++)
{
if(_this->searchPostId[i].str[0] == '\0')
continue;
cemu_assert_unimplemented(); // todo
// todo - postId parameter
// handle filters
if(_this->_HasFlag(DownloadPostDataListParam::FLAGS::WITH_MII))
params.append("&with_mii=1");
if(_this->_HasFlag(DownloadPostDataListParam::FLAGS::WITH_EMPATHY))
params.append("&with_empathy_added=1");
if(_this->bodyTextMaxLength != 0)
params.append(fmt::format("&max_body_length={}", _this->bodyTextMaxLength));
}
if(_this->titleId != 0)
params.append(fmt::format("&title_id={}", (uint64)_this->titleId));
if (_this->_HasFlag(DownloadPostDataListParam::FLAGS::FRIENDS_ONLY))
params.append("&by=friend");
if (_this->_HasFlag(DownloadPostDataListParam::FLAGS::FOLLOWERS_ONLY))
params.append("&by=followings");
if (_this->_HasFlag(DownloadPostDataListParam::FLAGS::SELF_ONLY))
params.append("&by=self");
if(!params.empty())
params[0] = '?'; // replace the leading ampersand
baseUrl.append(params);
if(baseUrl.size()+1 > urlMaxSize)
return OLV_RESULT_NOT_ENOUGH_SIZE;
strncpy(urlOut, baseUrl.c_str(), urlMaxSize);
return OLV_RESULT_SUCCESS;
}
nnResult DownloadPostDataList(DownloadedTopicData* downloadedTopicData, DownloadedPostData* downloadedPostData, uint32be* postCountOut, uint32 maxCount, DownloadPostDataListParam* param)
{
if(g_IsOfflineDBMode)
return OfflineDB_DownloadPostDataListParam_DownloadPostDataList(downloadedTopicData, downloadedPostData, postCountOut, maxCount, param);
memset(downloadedTopicData, 0, sizeof(DownloadedTopicData));
downloadedTopicData->communityId = param->communityId;
*postCountOut = 0;
char urlBuffer[2048];
if (NN_RESULT_IS_FAILURE(DownloadPostDataListParam::GetRawDataUrl(param, urlBuffer, sizeof(urlBuffer))))
return OLV_RESULT_INVALID_PARAMETER;
/*
CurlRequestHelper req;
req.initate(urlBuffer, CurlRequestHelper::SERVER_SSL_CONTEXT::OLIVE);
InitializeOliveRequest(req);
bool reqResult = req.submitRequest();
if (!reqResult)
{
long httpCode = 0;
curl_easy_getinfo(req.getCURL(), CURLINFO_RESPONSE_CODE, &httpCode);
cemuLog_log(LogType::Force, "Failed request: {} ({})", urlBuffer, httpCode);
if (!(httpCode >= 400))
return OLV_RESULT_FAILED_REQUEST;
}
pugi::xml_document doc;
if (!doc.load_buffer(req.getReceivedData().data(), req.getReceivedData().size()))
{
cemuLog_log(LogType::Force, fmt::format("Invalid XML in community download response"));
return OLV_RESULT_INVALID_XML;
}
*/
*postCountOut = 0;
return OLV_RESULT_SUCCESS;
}
void loadOlivePostAndTopicTypes()
{
cafeExportRegisterFunc(GetSystemTopicDataListFromRawData, "nn_olv", "GetSystemTopicDataListFromRawData__Q3_2nn3olv6hiddenFPQ4_2nn3olv6hidden29DownloadedSystemTopicDataListPQ4_2nn3olv6hidden24DownloadedSystemPostDataPUiUiPCUcT4", LogType::NN_OLV);
// DownloadedDataBase getters
cafeExportRegisterFunc(DownloadedDataBase::TestFlags, "nn_olv", "TestFlags__Q3_2nn3olv18DownloadedDataBaseCFUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetUserPid, "nn_olv", "GetUserPid__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetPostDate, "nn_olv", "GetPostDate__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetFeeling, "nn_olv", "GetFeeling__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetRegionId, "nn_olv", "GetRegionId__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetPlatformId, "nn_olv", "GetPlatformId__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetLanguageId, "nn_olv", "GetLanguageId__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetCountryId, "nn_olv", "GetCountryId__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetExternalUrl, "nn_olv", "GetExternalUrl__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetMiiData1, "nn_olv", "GetMiiData__Q3_2nn3olv18DownloadedDataBaseCFP12FFLStoreData", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetMiiNickname, "nn_olv", "GetMiiNickname__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetBodyText, "nn_olv", "GetBodyText__Q3_2nn3olv18DownloadedDataBaseCFPwUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetBodyMemo, "nn_olv", "GetBodyMemo__Q3_2nn3olv18DownloadedDataBaseCFPUcPUiUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetTopicTag, "nn_olv", "GetTopicTag__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetAppData, "nn_olv", "GetAppData__Q3_2nn3olv18DownloadedDataBaseCFPUcPUiUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetAppDataSize, "nn_olv", "GetAppDataSize__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetPostId, "nn_olv", "GetPostId__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetMiiData2, "nn_olv", "GetMiiData__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::DownloadExternalImageData, "nn_olv", "DownloadExternalImageData__Q3_2nn3olv18DownloadedDataBaseCFPvPUiUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedDataBase::GetExternalImageDataSize, "nn_olv", "GetExternalImageDataSize__Q3_2nn3olv18DownloadedDataBaseCFv", LogType::NN_OLV);
// DownloadedPostData getters
cafeExportRegisterFunc(DownloadedPostData::GetCommunityId, "nn_olv", "GetCommunityId__Q3_2nn3olv18DownloadedPostDataCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedPostData::GetEmpathyCount, "nn_olv", "GetEmpathyCount__Q3_2nn3olv18DownloadedPostDataCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedPostData::GetCommentCount, "nn_olv", "GetCommentCount__Q3_2nn3olv18DownloadedPostDataCFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadedPostData::GetPostId, "nn_olv", "GetPostId__Q3_2nn3olv18DownloadedPostDataCFv", LogType::NN_OLV);
// DownloadedSystemPostData getters
cafeExportRegisterFunc(hidden::DownloadedSystemPostData::GetTitleId, "nn_olv", "GetTitleId__Q4_2nn3olv6hidden24DownloadedSystemPostDataCFv", LogType::NN_OLV);
// DownloadedTopicData getters
cafeExportRegisterFunc(DownloadedTopicData::GetCommunityId, "nn_olv", "GetCommunityId__Q3_2nn3olv19DownloadedTopicDataCFv", LogType::NN_OLV);
// DownloadedSystemTopicData getters
cafeExportRegisterFunc(hidden::DownloadedSystemTopicData::TestFlags, "nn_olv", "TestFlags__Q4_2nn3olv6hidden25DownloadedSystemTopicDataCFUi", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicData::GetTitleId, "nn_olv", "GetTitleId__Q4_2nn3olv6hidden25DownloadedSystemTopicDataCFv", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicData::GetTitleIdNum, "nn_olv", "GetTitleIdNum__Q4_2nn3olv6hidden25DownloadedSystemTopicDataCFv", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicData::GetTitleText, "nn_olv", "GetTitleText__Q4_2nn3olv6hidden25DownloadedSystemTopicDataCFPwUi", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicData::GetTitleIconData, "nn_olv", "GetTitleIconData__Q4_2nn3olv6hidden25DownloadedSystemTopicDataCFPUcPUiUi", LogType::NN_OLV);
// DownloadedSystemTopicDataList getters
cafeExportRegisterFunc(hidden::DownloadedSystemTopicDataList::GetDownloadedSystemTopicDataNum, "nn_olv", "GetDownloadedSystemTopicDataNum__Q4_2nn3olv6hidden29DownloadedSystemTopicDataListCFv", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicDataList::GetDownloadedSystemPostDataNum, "nn_olv", "GetDownloadedSystemPostDataNum__Q4_2nn3olv6hidden29DownloadedSystemTopicDataListCFi", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicDataList::GetDownloadedSystemTopicData, "nn_olv", "GetDownloadedSystemTopicData__Q4_2nn3olv6hidden29DownloadedSystemTopicDataListCFi", LogType::NN_OLV);
cafeExportRegisterFunc(hidden::DownloadedSystemTopicDataList::GetDownloadedSystemPostData, "nn_olv", "GetDownloadedSystemPostData__Q4_2nn3olv6hidden29DownloadedSystemTopicDataListCFiT1", LogType::NN_OLV);
// DownloadPostDataListParam constructor and getters
cafeExportRegisterFunc(DownloadPostDataListParam::Construct, "nn_olv", "__ct__Q3_2nn3olv25DownloadPostDataListParamFv", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetFlags, "nn_olv", "SetFlags__Q3_2nn3olv25DownloadPostDataListParamFUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetLanguageId, "nn_olv", "SetLanguageId__Q3_2nn3olv25DownloadPostDataListParamFUc", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetCommunityId, "nn_olv", "SetCommunityId__Q3_2nn3olv25DownloadPostDataListParamFUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetSearchKey, "nn_olv", "SetSearchKey__Q3_2nn3olv25DownloadPostDataListParamFPCwUc", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetSearchKeySingle, "nn_olv", "SetSearchKey__Q3_2nn3olv25DownloadPostDataListParamFPCw", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetSearchPid, "nn_olv", "SetSearchPid__Q3_2nn3olv25DownloadPostDataListParamFUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetPostId, "nn_olv", "SetPostId__Q3_2nn3olv25DownloadPostDataListParamFPCcUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetPostDate, "nn_olv", "SetPostDate__Q3_2nn3olv25DownloadPostDataListParamFL", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetPostDataMaxNum, "nn_olv", "SetPostDataMaxNum__Q3_2nn3olv25DownloadPostDataListParamFUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataListParam::SetBodyTextMaxLength, "nn_olv", "SetBodyTextMaxLength__Q3_2nn3olv25DownloadPostDataListParamFUi", LogType::NN_OLV);
// URL and downloading functions
cafeExportRegisterFunc(DownloadPostDataListParam::GetRawDataUrl, "nn_olv", "GetRawDataUrl__Q3_2nn3olv25DownloadPostDataListParamCFPcUi", LogType::NN_OLV);
cafeExportRegisterFunc(DownloadPostDataList, "nn_olv", "DownloadPostDataList__Q2_2nn3olvFPQ3_2nn3olv19DownloadedTopicDataPQ3_2nn3olv18DownloadedPostDataPUiUiPCQ3_2nn3olv25DownloadPostDataListParam", LogType::NN_OLV);
}
}
}
| 22,886
|
C++
|
.cpp
| 421
| 49.80285
| 252
| 0.759611
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,076
|
nn_olv_Common.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_Common.cpp
|
#include "nn_olv_Common.h"
#include <zlib.h>
namespace nn
{
namespace olv
{
sint32 olv_copy_wstr(char16_t* dest, const char16_t* src, uint32_t maxSize, uint32_t destSize)
{
size_t len = maxSize + 1;
if (olv_wstrnlen(src, len) > maxSize)
return OLV_RESULT_NOT_ENOUGH_SIZE;
memset(dest, 0, 2 * destSize);
olv_wstrncpy(dest, src, len);
return OLV_RESULT_SUCCESS;
}
size_t olv_wstrnlen(const char16_t* str, size_t max_len)
{
size_t len = 0;
while (len < max_len && str[len] != u'\0')
len++;
return len;
}
char16_t* olv_wstrncpy(char16_t* dest, const char16_t* src, size_t n)
{
char16_t* ret = dest;
while (n > 0 && *src != u'\0')
{
*dest++ = *src++;
n--;
}
while (n > 0)
{
*dest++ = u'\0';
n--;
}
return ret;
}
bool CheckTGA(const uint8* pTgaFile, uint32 pTgaFileLen, TGACheckType checkType)
{
const TGAHeader* header = (const TGAHeader*)pTgaFile;
try
{
if (checkType == TGACheckType::CHECK_PAINTING)
{
if (
header->idLength ||
header->colorMapType ||
header->imageType != 2 || // Uncompressed true color
header->first_entry_idx ||
header->colormap_length ||
header->bpp ||
header->x_origin ||
header->y_origin ||
header->width != 320 ||
header->height != 120 ||
header->pixel_depth_bpp != 32 ||
header->image_desc_bits != 8
)
{
throw std::runtime_error("TGACheckType::CHECK_PAINTING - Invalid TGA file!");
}
}
else if (checkType == TGACheckType::CHECK_COMMUNITY_ICON)
{
if (header->width != 128 || header->height != 128 || header->pixel_depth_bpp != 32)
throw std::runtime_error("TGACheckType::CHECK_COMMUNITY_ICON - Invalid TGA file -> width, height or bpp is wrong");
}
else if (checkType == TGACheckType::CHECK_100x100_200x200)
{
if (header->pixel_depth_bpp != 32)
throw std::runtime_error("TGACheckType::CHECK_100x100_200x200 - Invalid TGA file -> bpp is wrong");
if (header->width == 100)
{
if (header->height != 100)
throw std::runtime_error("TGACheckType::CHECK_100x100_200x200 - Invalid TGA file -> Not 100x100");
}
else if (header->width != 200 || header->height != 200)
throw std::runtime_error("TGACheckType::CHECK_100x100_200x200 - Invalid TGA file -> Not 100x100 or 200x200");
}
}
catch (const std::runtime_error& error)
{
// TGA Check Error! illegal format
cemuLog_log(LogType::Force, error.what());
return false;
}
return true;
}
sint32 DecodeTGA(uint8* pInBuffer, uint32 inSize, uint8* pOutBuffer, uint32 outSize, TGACheckType checkType)
{
uint32 decompressedSize = outSize;
if (DecompressTGA(pOutBuffer, &decompressedSize, pInBuffer, inSize))
{
if (CheckTGA(pOutBuffer, decompressedSize, checkType))
return decompressedSize;
return -2;
}
else
{
cemuLog_log(LogType::Force, "OLIVE uncompress error.\n");
return -1;
}
}
sint32 EncodeTGA(uint8* pInBuffer, uint32 inSize, uint8* pOutBuffer, uint32 outSize, TGACheckType checkType)
{
if (inSize == outSize)
{
if (!CheckTGA(pInBuffer, inSize, checkType))
return -1;
uint32 compressedSize = outSize;
if (CompressTGA(pOutBuffer, &compressedSize, pInBuffer, inSize))
return compressedSize;
else
{
cemuLog_log(LogType::Force, "OLIVE compress error.\n");
return -1;
}
}
else
{
cemuLog_log(LogType::Force, "compress buffer size check error. uSrcBufSize({}) != uDstBufSize({})\n", inSize, outSize);
return -1;
}
}
bool DecompressTGA(uint8* pOutBuffer, uint32* pOutSize, uint8* pInBuffer, uint32 inSize)
{
if (pOutBuffer == nullptr || pOutSize == nullptr || pInBuffer == nullptr || inSize == 0)
return false;
uLongf bufferSize = *pOutSize;
int result = uncompress(pOutBuffer, &bufferSize, pInBuffer, inSize);
if (result == Z_OK)
{
*pOutSize = static_cast<unsigned int>(bufferSize);
return true;
}
else
{
const char* error_msg = (result == Z_MEM_ERROR) ? "Insufficient memory" : "Unknown decompression error";
cemuLog_log(LogType::Force, "OLIVE ZLIB - ERROR: {}\n", error_msg);
return false;
}
}
bool CompressTGA(uint8* pOutBuffer, uint32* pOutSize, uint8* pInBuffer, uint32 inSize)
{
if (pOutBuffer == nullptr || pOutSize == nullptr || pInBuffer == nullptr || inSize == 0)
return false;
uLongf bufferSize = *pOutSize;
int result = compress(pOutBuffer, &bufferSize, pInBuffer, inSize);
if (result == Z_OK)
{
*pOutSize = static_cast<unsigned int>(bufferSize);
return true;
}
else
{
const char* error_msg = (result == Z_MEM_ERROR) ? "Insufficient memory" : "Unknown compression error";
cemuLog_log(LogType::Force, "OLIVE ZLIB - ERROR: {}\n", error_msg);
return false;
}
}
constexpr uint32 CreateCommunityCodeById(uint32 communityId)
{
uint32 res = communityId ^ (communityId << 18) ^ (communityId << 24) ^ (communityId << 30);
return res ^ (16 * (res & 0xF0F0F0F)) ^ ((res ^ (16 * (res & 0xF0F0F0F))) >> 17) ^ ((res ^ (16 * (res & 0xF0F0F0F))) >> 23) ^ ((res ^ (16 * (res & 0xF0F0F0F))) >> 29) ^ 0x20121002;
}
constexpr uint32 CreateCommunityIdByCode(uint32 code)
{
uint32 res = code ^ 0x20121002 ^ ((code ^ 0x20121002u) >> 17) ^ ((code ^ 0x20121002u) >> 23) ^ ((code ^ 0x20121002u) >> 29);
return res ^ (16 * (res & 0xF0F0F0F)) ^ ((res ^ (16 * (res & 0xF0F0F0F))) << 18) ^ ((res ^ (16 * (res & 0xF0F0F0F))) << 24) ^ ((res ^ (16 * (res & 0xF0F0F0F))) << 30);
}
constexpr uint32 GetCommunityCodeTopByte(uint32 communityId)
{
uint8 code_byte3 = (uint8_t)(communityId >> 0x18);
uint8 code_byte2 = (uint8_t)(communityId >> 0x10);
uint8 code_byte1 = (uint8_t)(communityId >> 8);
uint8 code_byte0 = (uint8_t)(communityId >> 0);
return code_byte3 ^ code_byte2 ^ code_byte1 ^ code_byte0 ^ 0xff;
}
constexpr uint64 GetRealCommunityCode(uint32_t communityId)
{
uint64 topByte = GetCommunityCodeTopByte(communityId);
if ((0xe7 < topByte) && ((0xe8 < topByte || (0xd4a50fff < communityId))))
return ((topByte << 32) | communityId) & 0x7fffffffff;
return ((topByte << 32) | communityId);
}
void WriteCommunityCode(char* pOutCode, uint32 communityId)
{
uint32 code = CreateCommunityCodeById(communityId);
uint64 communityCode = GetRealCommunityCode(code);
sprintf(pOutCode, "%012llu", communityCode);
}
bool EnsureCommunityCode(char* pCode)
{
uint64 code;
if (sscanf(pCode, "%012llu", &code) > 0)
{
uint32 lowerCode = code;
uint64 newCode = GetRealCommunityCode(code);
return code == newCode;
}
return false;
}
bool FormatCommunityCode(char* pOutCode, uint32* outLen, uint32 communityId)
{
bool result = false;
if (communityId != -1)
{
if (communityId)
{
WriteCommunityCode(pOutCode, communityId);
*outLen = strnlen(pOutCode, 12);
if (EnsureCommunityCode(pOutCode))
result = 1;
}
}
return result;
}
static_assert(GetRealCommunityCode(CreateCommunityCodeById(140500)) == 717651734336, "Wrong community code generation code, result must match.");
uint32 ExtractCommunityIdFromCode(char* pCode)
{
uint32 id = 0;
uint64 code;
if (sscanf(pCode, "%012llu", &code) > 0)
{
uint32 lower_code = code;
id = CreateCommunityIdByCode(lower_code);
}
return id;
}
bool GetCommunityIdFromCode(uint32* pOutId, const char* pCode)
{
if (!EnsureCommunityCode((char*)pCode))
return false;
*pOutId = ExtractCommunityIdFromCode((char*)pCode);
return true;
}
sint32 olv_curlformcode_to_error(CURLFORMcode code)
{
switch (code)
{
case CURL_FORMADD_OK:
return OLV_RESULT_SUCCESS;
case CURL_FORMADD_MEMORY:
return OLV_RESULT_FATAL(25);
case CURL_FORMADD_OPTION_TWICE:
default:
return OLV_RESULT_LVL6(50);
}
}
}
}
| 8,285
|
C++
|
.cpp
| 251
| 27.358566
| 184
| 0.63312
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,077
|
nn_olv_OfflineDB.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_OfflineDB.cpp
|
#include "nn_olv_Common.h"
#include "nn_olv_PostTypes.h"
#include "nn_olv_OfflineDB.h"
#include "Cemu/ncrypto/ncrypto.h" // for base64 encoder/decoder
#include "util/helpers/helpers.h"
#include "config/ActiveSettings.h"
#include "Cafe/CafeSystem.h"
#include <pugixml.hpp>
#include <zlib.h>
#include <zarchive/zarchivereader.h>
namespace nn
{
namespace olv
{
std::mutex g_offlineDBMutex;
bool g_offlineDBInitialized = false;
ZArchiveReader* g_offlineDBArchive{nullptr};
void OfflineDB_LazyInit()
{
std::scoped_lock _l(g_offlineDBMutex);
if(g_offlineDBInitialized)
return;
// open archive
g_offlineDBArchive = ZArchiveReader::OpenFromFile(ActiveSettings::GetUserDataPath("resources/miiverse/OfflineDB.zar"));
if(!g_offlineDBArchive)
cemuLog_log(LogType::Force, "Offline miiverse posts are not available");
g_offlineDBInitialized = true;
}
void OfflineDB_Shutdown()
{
std::scoped_lock _l(g_offlineDBMutex);
if(!g_offlineDBInitialized)
return;
delete g_offlineDBArchive;
g_offlineDBInitialized = false;
}
bool CheckForOfflineDBFile(const char* filePath, uint32* fileSize)
{
if(!g_offlineDBArchive)
return false;
ZArchiveNodeHandle fileHandle = g_offlineDBArchive->LookUp(filePath);
if (!g_offlineDBArchive->IsFile(fileHandle))
return false;
if(fileSize)
*fileSize = g_offlineDBArchive->GetFileSize(fileHandle);
return true;
}
bool LoadOfflineDBFile(const char* filePath, std::vector<uint8>& fileData)
{
fileData.clear();
if(!g_offlineDBArchive)
return false;
ZArchiveNodeHandle fileHandle = g_offlineDBArchive->LookUp(filePath);
if (!g_offlineDBArchive->IsFile(fileHandle))
return false;
fileData.resize(g_offlineDBArchive->GetFileSize(fileHandle));
g_offlineDBArchive->ReadFromFile(fileHandle, 0, fileData.size(), fileData.data());
return true;
}
void TryLoadCompressedMemoImage(DownloadedPostData& downloadedPostData)
{
const unsigned char tgaHeader_320x120_32BPP[] = {0x0,0x0,0x2,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40,0x1,0x78,0x0,0x20,0x8};
std::string memoImageFilename = fmt::format("memo/{}", (char*)downloadedPostData.downloadedDataBase.postId);
std::vector<uint8> bitmaskCompressedImg;
if (!LoadOfflineDBFile(memoImageFilename.c_str(), bitmaskCompressedImg))
return;
if (bitmaskCompressedImg.size() != (320*120)/8)
return;
std::vector<uint8> decompressedImage;
decompressedImage.resize(sizeof(tgaHeader_320x120_32BPP) + 320 * 120 * 4);
memcpy(decompressedImage.data(), tgaHeader_320x120_32BPP, sizeof(tgaHeader_320x120_32BPP));
uint8* pOut = decompressedImage.data() + sizeof(tgaHeader_320x120_32BPP);
for(int i=0; i<320*120; i++)
{
bool isWhite = (bitmaskCompressedImg[i/8] & (1 << (i%8))) != 0;
if(isWhite)
{
pOut[0] = pOut[1] = pOut[2] = pOut[3] = 0xFF;
}
else
{
pOut[0] = pOut[1] = pOut[2] = 0;
pOut[3] = 0xFF;
}
pOut += 4;
}
// store compressed image
uLongf compressedDestLen = 40960;
int r = compress((uint8*)downloadedPostData.downloadedDataBase.compressedMemoBody, &compressedDestLen, decompressedImage.data(), decompressedImage.size());
if( r != Z_OK)
return;
downloadedPostData.downloadedDataBase.compressedMemoBodySize = compressedDestLen;
downloadedPostData.downloadedDataBase.SetFlag(DownloadedDataBase::FLAGS::HAS_BODY_MEMO);
}
void CheckForExternalImage(DownloadedPostData& downloadedPostData)
{
std::string externalImageFilename = fmt::format("image/{}.jpg", (char*)downloadedPostData.downloadedDataBase.postId);
uint32 fileSize;
if (!CheckForOfflineDBFile(externalImageFilename.c_str(), &fileSize))
return;
strcpy((char*)downloadedPostData.downloadedDataBase.externalImageDataUrl, externalImageFilename.c_str());
downloadedPostData.downloadedDataBase.SetFlag(DownloadedDataBase::FLAGS::HAS_EXTERNAL_IMAGE);
downloadedPostData.downloadedDataBase.externalImageDataSize = fileSize;
}
nnResult _Async_OfflineDB_DownloadPostDataListParam_DownloadPostDataList(coreinit::OSEvent* event, DownloadedTopicData* downloadedTopicData, DownloadedPostData* downloadedPostData, uint32be* postCountOut, uint32 maxCount, DownloadPostDataListParam* param)
{
stdx::scope_exit _se([&](){coreinit::OSSignalEvent(event);});
uint64 titleId = CafeSystem::GetForegroundTitleId();
memset(downloadedTopicData, 0, sizeof(DownloadedTopicData));
memset(downloadedPostData, 0, sizeof(DownloadedPostData) * maxCount);
*postCountOut = 0;
const char* postXmlFilename = nullptr;
if(titleId == 0x0005000010143400 || titleId == 0x0005000010143500 || titleId == 0x0005000010143600)
postXmlFilename = "PostList_WindWakerHD.xml";
if (!postXmlFilename)
return OLV_RESULT_SUCCESS;
// load post XML
std::vector<uint8> xmlData;
if (!LoadOfflineDBFile(postXmlFilename, xmlData))
return OLV_RESULT_SUCCESS;
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_buffer(xmlData.data(), xmlData.size());
if (!result)
return OLV_RESULT_SUCCESS;
// collect list of all post xml nodes
std::vector<pugi::xml_node> postXmlNodes;
for (pugi::xml_node postNode = doc.child("posts").child("post"); postNode; postNode = postNode.next_sibling("post"))
postXmlNodes.push_back(postNode);
// randomly select up to maxCount posts
srand(GetTickCount());
uint32 postCount = 0;
while(!postXmlNodes.empty() && postCount < maxCount)
{
uint32 index = rand() % postXmlNodes.size();
pugi::xml_node& postNode = postXmlNodes[index];
auto& addedPost = downloadedPostData[postCount];
memset(&addedPost, 0, sizeof(DownloadedPostData));
if (!ParseXML_DownloadedPostData(addedPost, postNode) )
continue;
TryLoadCompressedMemoImage(addedPost);
CheckForExternalImage(addedPost);
postCount++;
// remove from post list
postXmlNodes[index] = postXmlNodes.back();
postXmlNodes.pop_back();
}
*postCountOut = postCount;
return OLV_RESULT_SUCCESS;
}
nnResult OfflineDB_DownloadPostDataListParam_DownloadPostDataList(DownloadedTopicData* downloadedTopicData, DownloadedPostData* downloadedPostData, uint32be* postCountOut, uint32 maxCount, DownloadPostDataListParam* param)
{
OfflineDB_LazyInit();
memset(downloadedTopicData, 0, sizeof(DownloadedTopicData));
downloadedTopicData->communityId = param->communityId;
*postCountOut = 0;
if(param->_HasFlag(DownloadPostDataListParam::FLAGS::SELF_ONLY))
return OLV_RESULT_SUCCESS; // the offlineDB doesn't contain any self posts
StackAllocator<coreinit::OSEvent> doneEvent;
coreinit::OSInitEvent(&doneEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_MANUAL);
auto asyncTask = std::async(std::launch::async, _Async_OfflineDB_DownloadPostDataListParam_DownloadPostDataList, doneEvent.GetPointer(), downloadedTopicData, downloadedPostData, postCountOut, maxCount, param);
coreinit::OSWaitEvent(&doneEvent);
nnResult r = asyncTask.get();
return r;
}
nnResult _Async_OfflineDB_DownloadPostDataListParam_DownloadExternalImageData(coreinit::OSEvent* event, DownloadedDataBase* _this, void* imageDataOut, uint32be* imageSizeOut, uint32 maxSize)
{
stdx::scope_exit _se([&](){coreinit::OSSignalEvent(event);});
if (!_this->TestFlags(_this, DownloadedDataBase::FLAGS::HAS_EXTERNAL_IMAGE))
return OLV_RESULT_MISSING_DATA;
// not all games may use JPEG files?
std::string externalImageFilename = fmt::format("image/{}.jpg", (char*)_this->postId);
std::vector<uint8> jpegData;
if (!LoadOfflineDBFile(externalImageFilename.c_str(), jpegData))
return OLV_RESULT_FAILED_REQUEST;
memcpy(imageDataOut, jpegData.data(), jpegData.size());
*imageSizeOut = jpegData.size();
return OLV_RESULT_SUCCESS;
}
nnResult OfflineDB_DownloadPostDataListParam_DownloadExternalImageData(DownloadedDataBase* _this, void* imageDataOut, uint32be* imageSizeOut, uint32 maxSize)
{
StackAllocator<coreinit::OSEvent> doneEvent;
coreinit::OSInitEvent(&doneEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_MANUAL);
auto asyncTask = std::async(std::launch::async, _Async_OfflineDB_DownloadPostDataListParam_DownloadExternalImageData, doneEvent.GetPointer(), _this, imageDataOut, imageSizeOut, maxSize);
coreinit::OSWaitEvent(&doneEvent);
nnResult r = asyncTask.get();
return r;
}
}
}
| 8,481
|
C++
|
.cpp
| 189
| 40.904762
| 257
| 0.755655
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,078
|
nn_olv_DownloadCommunityTypes.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_DownloadCommunityTypes.cpp
|
#include "nn_olv_DownloadCommunityTypes.h"
namespace nn
{
namespace olv
{
sint32 DownloadCommunityDataList_AsyncRequestImpl(
CurlRequestHelper& req, const char* reqUrl,
DownloadedCommunityData* pOutList, uint32* pOutNum, uint32 numMaxList, const DownloadCommunityDataListParam* pParam);
sint32 DownloadCommunityDataList_AsyncRequest(
CurlRequestHelper& req, const char* reqUrl, coreinit::OSEvent* requestDoneEvent,
DownloadedCommunityData* pOutList, uint32* pOutNum, uint32 numMaxList, const DownloadCommunityDataListParam* pParam
)
{
sint32 res = DownloadCommunityDataList_AsyncRequestImpl(req, reqUrl, pOutList, pOutNum, numMaxList, pParam);
coreinit::OSSignalEvent(requestDoneEvent);
return res;
}
sint32 DownloadCommunityDataList(DownloadedCommunityData* pOutList, uint32* pOutNum, uint32 numMaxList, const DownloadCommunityDataListParam* pParam)
{
if (!g_IsInitialized)
return OLV_RESULT_NOT_INITIALIZED;
if (!g_IsOnlineMode)
return OLV_RESULT_OFFLINE_MODE_REQUEST;
if (!pOutList || !pOutNum || !pParam)
return OLV_RESULT_INVALID_PTR;
if (!numMaxList)
return OLV_RESULT_NOT_ENOUGH_SIZE;
for (int i = 0; i < numMaxList; i++)
DownloadedCommunityData::Clean(&pOutList[i]);
char reqUrl[2048];
sint32 res = pParam->GetRawDataUrl(reqUrl, sizeof(reqUrl));
if (res < 0)
return res;
CurlRequestHelper req;
req.initate(ActiveSettings::GetNetworkService(), reqUrl, CurlRequestHelper::SERVER_SSL_CONTEXT::OLIVE);
InitializeOliveRequest(req);
StackAllocator<coreinit::OSEvent> requestDoneEvent;
coreinit::OSInitEvent(&requestDoneEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_MANUAL);
std::future<sint32> requestRes = std::async(std::launch::async, DownloadCommunityDataList_AsyncRequest,
std::ref(req), reqUrl, requestDoneEvent.GetPointer(), pOutList, pOutNum, numMaxList, pParam);
coreinit::OSWaitEvent(&requestDoneEvent);
return requestRes.get();
}
sint32 DownloadCommunityDataList_AsyncRequestImpl(
CurlRequestHelper& req, const char* reqUrl,
DownloadedCommunityData* pOutList, uint32* pOutNum, uint32 numMaxList, const DownloadCommunityDataListParam* pParam
)
{
bool reqResult = req.submitRequest();
long httpCode = 0;
curl_easy_getinfo(req.getCURL(), CURLINFO_RESPONSE_CODE, &httpCode);
if (!reqResult)
{
cemuLog_log(LogType::Force, "Failed request: {} ({})", reqUrl, httpCode);
if (!(httpCode >= 400))
return OLV_RESULT_FAILED_REQUEST;
}
pugi::xml_document doc;
if (!doc.load_buffer(req.getReceivedData().data(), req.getReceivedData().size()))
{
cemuLog_log(LogType::Force, fmt::format("Invalid XML in community download response"));
return OLV_RESULT_INVALID_XML;
}
sint32 responseError = CheckOliveResponse(doc);
if (responseError < 0)
return responseError;
if (httpCode != 200)
return OLV_RESULT_STATUS(httpCode + 4000);
std::string request_name = doc.select_single_node("//request_name").node().child_value();
if (request_name.size() == 0)
{
cemuLog_log(LogType::Force, "Community download response doesn't contain <request_name>");
return OLV_RESULT_INVALID_XML;
}
if ((request_name.compare("communities") != 0) && (request_name.compare("specified_communities") != 0))
{
cemuLog_log(LogType::Force, "Community download response <request_name> isn't \"communities\" or \"specified_communities\"");
return OLV_RESULT_INVALID_XML;
}
pugi::xml_node communities = doc.select_single_node("//communities").node();
if (!communities)
{
cemuLog_log(LogType::Force, "Community download response doesn't contain <communities>");
return OLV_RESULT_INVALID_XML;
}
int idx = 0;
for (pugi::xml_node communityNode : communities.children("community"))
{
if (idx >= numMaxList)
break;
DownloadedCommunityData* pOutData = &pOutList[idx];
std::string_view app_data = communityNode.child_value("app_data");
std::string_view community_id = communityNode.child_value("community_id");
std::string_view name = communityNode.child_value("name");
std::string_view description = communityNode.child_value("description");
std::string_view pid = communityNode.child_value("pid");
std::string_view icon = communityNode.child_value("icon");
std::string_view mii = communityNode.child_value("mii");
std::string_view screen_name = communityNode.child_value("screen_name");
if (app_data.size() != 0)
{
auto app_data_bin = NCrypto::base64Decode(app_data);
if (app_data_bin.size() != 0)
{
memcpy(pOutData->appData, app_data_bin.data(), std::min(size_t(0x400), app_data_bin.size()));
pOutData->flags |= DownloadedCommunityData::FLAG_HAS_APP_DATA;
pOutData->appDataLen = app_data_bin.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
sint64 community_id_val = StringHelpers::ToInt64(community_id, -1);
if (community_id_val == -1)
return OLV_RESULT_INVALID_INTEGER_FIELD;
pOutData->communityId = community_id_val;
if (name.size() != 0)
{
auto name_utf16 = StringHelpers::FromUtf8(name).substr(0, 128);
if (name_utf16.size() != 0)
{
for (int i = 0; i < name_utf16.size(); i++)
pOutData->titleText[i] = name_utf16.at(i).bevalue();
pOutData->flags |= DownloadedCommunityData::FLAG_HAS_TITLE_TEXT;
pOutData->titleTextMaxLen = name_utf16.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
if (description.size() != 0)
{
auto description_utf16 = StringHelpers::FromUtf8(description).substr(0, 256);
if (description_utf16.size() != 0)
{
for (int i = 0; i < description_utf16.size(); i++)
pOutData->description[i] = description_utf16.at(i).bevalue();
pOutData->flags |= DownloadedCommunityData::FLAG_HAS_DESC_TEXT;
pOutData->descriptionMaxLen = description_utf16.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
sint64 pid_val = StringHelpers::ToInt64(pid, -1);
if (pid_val == -1)
return OLV_RESULT_INVALID_INTEGER_FIELD;
pOutData->pid = pid_val;
if (icon.size() != 0)
{
auto icon_bin = NCrypto::base64Decode(icon);
if (icon_bin.size() != 0)
{
memcpy(pOutData->iconData, icon_bin.data(), std::min(size_t(0x1002c), icon_bin.size()));
pOutData->flags |= DownloadedCommunityData::FLAG_HAS_ICON_DATA;
pOutData->iconDataSize = icon_bin.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
if (mii.size() != 0)
{
auto mii_bin = NCrypto::base64Decode(mii);
if (mii_bin.size() != 0)
{
memcpy(pOutData->miiFFLStoreData, mii_bin.data(), std::min(size_t(96), mii_bin.size()));
pOutData->flags |= DownloadedCommunityData::FLAG_HAS_MII_DATA;
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
if (screen_name.size() != 0)
{
auto screen_name_utf16 = StringHelpers::FromUtf8(screen_name).substr(0, 32);
if (screen_name_utf16.size() != 0)
{
for (int i = 0; i < screen_name_utf16.size(); i++)
pOutData->miiDisplayName[i] = screen_name_utf16.at(i).bevalue();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
idx++;
}
*pOutNum = _swapEndianU32(idx);
sint32 res = OLV_RESULT_SUCCESS;
if (idx > 0)
res = 0; // nn_olv doesn't do it like that, but it's the same effect. I have no clue why it returns 0 when you have 1+ communities downloaded
return res;
}
}
}
| 7,858
|
C++
|
.cpp
| 189
| 35.248677
| 152
| 0.675059
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,079
|
nn_olv.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv.cpp
|
#include "nn_olv.h"
#include "nn_olv_InitializeTypes.h"
#include "nn_olv_UploadCommunityTypes.h"
#include "nn_olv_DownloadCommunityTypes.h"
#include "nn_olv_UploadFavoriteTypes.h"
#include "nn_olv_PostTypes.h"
#include "nn_olv_OfflineDB.h"
#include "Cafe/OS/libs/proc_ui/proc_ui.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_Misc.h"
namespace nn
{
namespace olv
{
struct PortalAppParam_t
{
/* +0x1A663B */ char serviceToken[32]; // size is unknown
};
void exportPortalAppParam_GetServiceToken(PPCInterpreter_t* hCPU)
{
// r3 = PortalAppParam
ppcDefineParamTypePtr(portalAppParam, PortalAppParam_t, 0);
strcpy(portalAppParam->serviceToken, "servicetoken");
// this token is probably just the act IndependentServiceToken for the Miiverse title?
osLib_returnFromFunction(hCPU, memory_getVirtualOffsetFromPointer(&portalAppParam->serviceToken));
}
static SysAllocator<OSThread_t> s_OlvReleaseBgThread;
SysAllocator<uint8, 1024> s_OlvReleaseBgThreadStack;
SysAllocator<char, 32> s_OlvReleaseBgThreadName;
void StubPostAppReleaseBackground(PPCInterpreter_t* hCPU)
{
coreinit::OSSleepTicks(ESPRESSO_TIMER_CLOCK * 2); // Sleep 2s
coreinit::StartBackgroundForegroundTransition();
}
sint32 StubPostApp(void* pAnyPostParam)
{
coreinit::OSCreateThreadType(s_OlvReleaseBgThread.GetPtr(), RPLLoader_MakePPCCallable(StubPostAppReleaseBackground), 0, nullptr, s_OlvReleaseBgThreadStack.GetPtr() + s_OlvReleaseBgThreadStack.GetByteSize(), (sint32)s_OlvReleaseBgThreadStack.GetByteSize(), 0, (1 << 1) | (1 << 3), OSThread_t::THREAD_TYPE::TYPE_APP);
coreinit::OSResumeThread(s_OlvReleaseBgThread.GetPtr());
strcpy(s_OlvReleaseBgThreadName.GetPtr(), "StubPostApp!");
coreinit::OSSetThreadName(s_OlvReleaseBgThread.GetPtr(),s_OlvReleaseBgThreadName.GetPtr());
return OLV_RESULT_SUCCESS;
}
sint32 StubPostAppResult()
{
return OLV_RESULT_STATUS(301); // Cancelled post app
}
// Somehow required, MK8 doesn't even seem to care about the error codes lol
char* UploadedPostData_GetPostId(char* pPostData)
{
pPostData[4] = '\0';
return &pPostData[4];
}
// https://github.com/kinnay/NintendoClients/wiki/Wii-U-Error-Codes#act-error-codes
constexpr uint32 GetErrorCodeImpl(uint32 in)
{
uint32_t errorCode = in;
uint32_t errorVersion = (errorCode >> 27) & 3;
uint32_t errorModuleMask = (errorVersion != 3) ? 0x1FF00000 : 0x7F00000;
bool isCodeFailure = errorCode & 0x80000000;
if (((errorCode & errorModuleMask) >> 20) == NN_RESULT_MODULE_NN_ACT)
{
// BANNED_ACCOUNT_IN_INDEPENDENT_SERVICE or BANNED_ACCOUNT_IN_INDEPENDENT_SERVICE_TEMPORARILY
if (errorCode == OLV_ACT_RESULT_STATUS(2805) || errorCode == OLV_ACT_RESULT_STATUS(2825))
{
uint32 tmpCode = OLV_RESULT_STATUS(1008);
return GetErrorCodeImpl(tmpCode);
}
// BANNED_DEVICE_IN_INDEPENDENT_SERVICE or BANNED_DEVICE_IN_INDEPENDENT_SERVICE_TEMPORARILY
else if (errorCode == OLV_ACT_RESULT_STATUS(2815) || errorCode == OLV_ACT_RESULT_STATUS(2835))
{
uint32 tmpCode = OLV_RESULT_STATUS(1009);
return GetErrorCodeImpl(tmpCode);
}
else
{
// Check ACT error code
return 1159999;
}
}
else
{
if (((errorCode & errorModuleMask) >> 20) == NN_RESULT_MODULE_NN_OLV && isCodeFailure)
{
uint32_t errorValueMask = (errorVersion != 3) ? 0xFFFFF : 0x3FF;
return ((errorCode & errorValueMask) >> 7) + 1150000;
}
else
{
return 1159999;
}
}
}
uint32 GetErrorCode(uint32be* pResult)
{
return GetErrorCodeImpl(pResult->value());
}
static_assert(GetErrorCodeImpl(0xa119c600) == 1155004);
void load()
{
g_ReportTypes = 0;
g_IsOnlineMode = false;
g_IsInitialized = false;
g_IsOfflineDBMode = false;
loadOliveInitializeTypes();
loadOliveUploadCommunityTypes();
loadOliveDownloadCommunityTypes();
loadOliveUploadFavoriteTypes();
loadOlivePostAndTopicTypes();
cafeExportRegisterFunc(GetErrorCode, "nn_olv", "GetErrorCode__Q2_2nn3olvFRCQ2_2nn6Result", LogType::NN_OLV);
osLib_addFunction("nn_olv", "GetServiceToken__Q4_2nn3olv6hidden14PortalAppParamCFv", exportPortalAppParam_GetServiceToken);
cafeExportRegisterFunc(StubPostApp, "nn_olv", "UploadPostDataByPostApp__Q2_2nn3olvFPCQ3_2nn3olv28UploadPostDataByPostAppParam", LogType::NN_OLV);
cafeExportRegisterFunc(StubPostApp, "nn_olv", "UploadCommentDataByPostApp__Q2_2nn3olvFPCQ3_2nn3olv31UploadCommentDataByPostAppParam", LogType::NN_OLV);
cafeExportRegisterFunc(StubPostApp, "nn_olv", "UploadDirectMessageDataByPostApp__Q2_2nn3olvFPCQ3_2nn3olv37UploadDirectMessageDataByPostAppParam", LogType::NN_OLV);
cafeExportRegisterFunc(StubPostAppResult, "nn_olv", "GetResultByPostApp__Q2_2nn3olvFv", LogType::NN_OLV);
cafeExportRegisterFunc(StubPostAppResult, "nn_olv", "GetResultWithUploadedPostDataByPostApp__Q2_2nn3olvFPQ3_2nn3olv16UploadedPostData", LogType::NN_OLV);
cafeExportRegisterFunc(StubPostAppResult, "nn_olv", "GetResultWithUploadedDirectMessageDataByPostApp__Q2_2nn3olvFPQ3_2nn3olv25UploadedDirectMessageData", LogType::NN_OLV);
cafeExportRegisterFunc(StubPostAppResult, "nn_olv", "GetResultWithUploadedCommentDataByPostApp__Q2_2nn3olvFPQ3_2nn3olv19UploadedCommentData", LogType::NN_OLV);
cafeExportRegisterFunc(UploadedPostData_GetPostId, "nn_olv", "GetPostId__Q3_2nn3olv16UploadedPostDataCFv", LogType::NN_OLV);
}
void unload() // not called yet
{
OfflineDB_Shutdown();
}
}
}
| 5,532
|
C++
|
.cpp
| 125
| 40.44
| 318
| 0.761701
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,080
|
nn_olv_UploadCommunityTypes.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_olv/nn_olv_UploadCommunityTypes.cpp
|
#include "nn_olv_UploadCommunityTypes.h"
#include <algorithm>
namespace nn
{
namespace olv
{
sint32 UploadCommunityData_AsyncRequestImpl(CurlRequestHelper& req, const char* reqUrl,
UploadedCommunityData* pOutData, UploadCommunityDataParam const* pParam);
sint32 UploadCommunityData_AsyncRequest(CurlRequestHelper& req, const char* reqUrl, coreinit::OSEvent* requestDoneEvent,
UploadedCommunityData* pOutData, UploadCommunityDataParam const* pParam
)
{
sint32 res = UploadCommunityData_AsyncRequestImpl(req, reqUrl, pOutData, pParam);
coreinit::OSSignalEvent(requestDoneEvent);
return res;
}
sint32 UploadCommunityData(UploadedCommunityData* pOutData, UploadCommunityDataParam const* pParam)
{
if (!nn::olv::g_IsInitialized)
return OLV_RESULT_NOT_INITIALIZED;
if (!nn::olv::g_IsOnlineMode)
return OLV_RESULT_OFFLINE_MODE_REQUEST;
if (!pParam)
return OLV_RESULT_INVALID_PTR;
if (pOutData)
UploadedCommunityData::Clean(pOutData);
char requestUrl[512];
if (pParam->flags & UploadCommunityDataParam::FLAG_DELETION)
{
if (!pParam->communityId)
return OLV_RESULT_INVALID_PARAMETER;
snprintf(requestUrl, sizeof(requestUrl), "%s/v1/communities/%lu.delete", g_DiscoveryResults.apiEndpoint, pParam->communityId.value());
}
else
{
if (pParam->communityId)
snprintf(requestUrl, sizeof(requestUrl), "%s/v1/communities/%lu", g_DiscoveryResults.apiEndpoint, pParam->communityId.value());
else
snprintf(requestUrl, sizeof(requestUrl), "%s/v1/communities", g_DiscoveryResults.apiEndpoint);
}
CurlRequestHelper req;
req.initate(ActiveSettings::GetNetworkService(), requestUrl, CurlRequestHelper::SERVER_SSL_CONTEXT::OLIVE);
InitializeOliveRequest(req);
StackAllocator<coreinit::OSEvent> requestDoneEvent;
coreinit::OSInitEvent(&requestDoneEvent, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_MANUAL);
std::future<sint32> requestRes = std::async(std::launch::async, UploadCommunityData_AsyncRequest, std::ref(req), requestUrl, requestDoneEvent.GetPointer(), pOutData, pParam);
coreinit::OSWaitEvent(&requestDoneEvent);
return requestRes.get();
}
sint32 UploadCommunityData(UploadCommunityDataParam const* pParam)
{
return UploadCommunityData(nullptr, pParam);
}
sint32 UploadCommunityData_AsyncRequestImpl(CurlRequestHelper& req, const char* reqUrl,
UploadedCommunityData* pOutData, UploadCommunityDataParam const* pParam)
{
sint32 res = OLV_RESULT_SUCCESS;
std::string base64icon;
std::string form_name;
std::string form_desc;
std::string form_searchKey[5];
std::string encodedAppData;
uint8* encodedIcon = nullptr;
struct curl_httppost* post = nullptr;
struct curl_httppost* last = nullptr;
try
{
if (!pParam->iconData.IsNull())
{
encodedIcon = new uint8[pParam->iconDataLen];
if (encodedIcon)
{
sint32 iconEncodeRes = EncodeTGA(pParam->iconData.GetPtr(), pParam->iconDataLen, encodedIcon, pParam->iconDataLen, TGACheckType::CHECK_COMMUNITY_ICON);
if (iconEncodeRes <= 0)
{
delete[] encodedIcon;
return OLV_RESULT_NOT_ENOUGH_SIZE; // ?
}
base64icon = NCrypto::base64Encode(encodedIcon, iconEncodeRes);
res = olv_curlformcode_to_error(
curl_formadd(&post, &last,
CURLFORM_COPYNAME, "icon",
CURLFORM_PTRCONTENTS, base64icon.data(),
CURLFORM_CONTENTSLENGTH, base64icon.size(),
CURLFORM_END)
);
if (res < 0)
throw std::runtime_error("curl_formadd() error! - icon");
}
}
if (pParam->titleText[0])
{
form_name = StringHelpers::ToUtf8((const uint16be*)pParam->titleText, 127);
res = olv_curlformcode_to_error(
curl_formadd(&post, &last,
CURLFORM_COPYNAME, "name",
CURLFORM_PTRCONTENTS, form_name.data(),
CURLFORM_CONTENTSLENGTH, form_name.size(),
CURLFORM_END)
);
if (res < 0)
throw std::runtime_error("curl_formadd() error! - name");
}
if (pParam->description[0])
{
form_desc = StringHelpers::ToUtf8((const uint16be*)pParam->description, 255);
res = olv_curlformcode_to_error(
curl_formadd(&post, &last,
CURLFORM_COPYNAME, "description",
CURLFORM_PTRCONTENTS, form_desc.data(),
CURLFORM_CONTENTSLENGTH, form_desc.size(),
CURLFORM_END)
);
if (res < 0)
throw std::runtime_error("curl_formadd() error! - description");
}
for (int i = 0; i < 5; i++)
{
if (pParam->searchKeys[i][0])
{
form_searchKey[i] = StringHelpers::ToUtf8((const uint16be*)pParam->searchKeys[i], 151);
res = olv_curlformcode_to_error(
curl_formadd(&post, &last,
CURLFORM_COPYNAME, "search_key",
CURLFORM_PTRCONTENTS, form_searchKey[i].data(),
CURLFORM_CONTENTSLENGTH, form_searchKey[i].size(),
CURLFORM_END)
);
if (res < 0)
throw std::runtime_error("curl_formadd() error! - search_key");
}
}
if (!pParam->appData.IsNull())
{
encodedAppData = NCrypto::base64Encode(pParam->appData.GetPtr(), pParam->appDataLen);
if (encodedAppData.size() < pParam->appDataLen)
res = OLV_RESULT_FATAL(101);
else
{
res = olv_curlformcode_to_error(
curl_formadd(&post, &last,
CURLFORM_COPYNAME, "app_data",
CURLFORM_PTRCONTENTS, encodedAppData.data(),
CURLFORM_CONTENTSLENGTH, encodedAppData.size(),
CURLFORM_END)
);
if (res < 0)
throw std::runtime_error("curl_formadd() error! - app_data");
}
}
}
catch (const std::runtime_error& error)
{
cemuLog_log(LogType::Force, "Error in multipart curl -> {}", error.what());
curl_formfree(post);
if (encodedIcon)
delete[] encodedIcon;
return res;
}
curl_easy_setopt(req.getCURL(), CURLOPT_HTTPPOST, post);
req.setUseMultipartFormData(true);
bool reqResult = req.submitRequest(true);
long httpCode = 0;
curl_easy_getinfo(req.getCURL(), CURLINFO_RESPONSE_CODE, &httpCode);
if (encodedIcon)
delete[] encodedIcon;
if (!reqResult)
{
cemuLog_log(LogType::Force, "Failed request: {} ({})", reqUrl, httpCode);
if (!(httpCode >= 400))
return OLV_RESULT_FAILED_REQUEST;
}
pugi::xml_document doc;
if (!doc.load_buffer(req.getReceivedData().data(), req.getReceivedData().size()))
{
cemuLog_log(LogType::Force, fmt::format("Invalid XML in community upload response"));
return OLV_RESULT_INVALID_XML;
}
sint32 responseError = CheckOliveResponse(doc);
if (responseError < 0)
return responseError;
if (httpCode != 200)
return OLV_RESULT_STATUS(httpCode + 4000);
if (pOutData)
{
std::string_view app_data = doc.select_single_node("//app_data").node().child_value();
std::string_view community_id = doc.select_single_node("//community_id").node().child_value();
std::string_view name = doc.select_single_node("//name").node().child_value();
std::string_view description = doc.select_single_node("//description").node().child_value();
std::string_view pid = doc.select_single_node("//pid").node().child_value();
std::string_view icon = doc.select_single_node("//icon").node().child_value();
if (app_data.size() != 0)
{
auto app_data_bin = NCrypto::base64Decode(app_data);
if (app_data_bin.size() != 0) {
memcpy(pOutData->appData, app_data_bin.data(), std::min(size_t(0x400), app_data_bin.size()));
pOutData->flags |= UploadedCommunityData::FLAG_HAS_APP_DATA;
pOutData->appDataLen = app_data_bin.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
sint64 community_id_val = StringHelpers::ToInt64(community_id, -1);
if (community_id_val == -1)
return OLV_RESULT_INVALID_INTEGER_FIELD;
pOutData->communityId = community_id_val;
if (name.size() != 0)
{
auto name_utf16 = StringHelpers::FromUtf8(name).substr(0, 128);
if (name_utf16.size() != 0)
{
for (int i = 0; i < name_utf16.size(); i++)
pOutData->titleText[i] = name_utf16.at(i);
pOutData->flags |= UploadedCommunityData::FLAG_HAS_TITLE_TEXT;
pOutData->titleTextMaxLen = name_utf16.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
if (description.size() != 0)
{
auto description_utf16 = StringHelpers::FromUtf8(description).substr(0, 256);
if (description_utf16.size() != 0)
{
for (int i = 0; i < description_utf16.size(); i++)
pOutData->description[i] = description_utf16.at(i);
pOutData->flags |= UploadedCommunityData::FLAG_HAS_DESC_TEXT;
pOutData->descriptionMaxLen = description_utf16.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
sint64 pid_val = StringHelpers::ToInt64(pid, -1);
if (pid_val == -1)
return OLV_RESULT_INVALID_INTEGER_FIELD;
pOutData->pid = pid_val;
if (icon.size() != 0)
{
auto icon_bin = NCrypto::base64Decode(icon);
if (icon_bin.size() != 0)
{
memcpy(pOutData->iconData, icon_bin.data(), std::min(size_t(0x1002c), icon_bin.size()));
pOutData->flags |= UploadedCommunityData::FLAG_HAS_ICON_DATA;
pOutData->iconDataSize = icon_bin.size();
}
else
return OLV_RESULT_INVALID_TEXT_FIELD;
}
}
return OLV_RESULT_SUCCESS;
}
}
}
| 9,773
|
C++
|
.cpp
| 253
| 31.794466
| 178
| 0.658342
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,081
|
vpad.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/vpad/vpad.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "gui/wxgui.h"
#include "Cafe/OS/libs/vpad/vpad.h"
#include "audio/IAudioAPI.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "config/ActiveSettings.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "input/InputManager.h"
#ifdef PUBLIC_RELASE
#define vpadbreak()
#else
#define vpadbreak()// __debugbreak();
#endif
#define VPAD_READ_ERR_NONE 0
#define VPAD_READ_ERR_NO_DATA -1
#define VPAD_READ_ERR_NO_CONTROLLER -2
#define VPAD_READ_ERR_SETUP -3
#define VPAD_READ_ERR_LOCKED -4
#define VPAD_READ_ERR_INIT -5
#define VPAD_TP_VALIDITY_VALID 0
#define VPAD_TP_VALIDITY_INVALID_X 1
#define VPAD_TP_VALIDITY_INVALID_Y 2
#define VPAD_TP_VALIDITY_INVALID_XY (VPAD_TP_VALIDITY_INVALID_X | VPAD_TP_VALIDITY_INVALID_Y)
#define VPAD_GYRO_ZERODRIFT_LOOSE 0
#define VPAD_GYRO_ZERODRIFT_STANDARD 1
#define VPAD_GYRO_ZERODRIFT_TIGHT 2
#define VPAD_GYRO_ZERODRIFT_NONE 3
#define VPAD_PLAY_MODE_LOOSE 0
#define VPAD_PLAY_MODE_TIGHT 1
#define VPAD_BUTTON_PROC_MODE_LOOSE 0
#define VPAD_BUTTON_PROC_MODE_TIGHT 1
#define VPAD_LCD_MODE_MUTE 0
#define VPAD_LCD_MODE_GAME_CONTROLLER 1
#define VPAD_LCD_MODE_ON 0xFF
#define VPAD_MOTOR_PATTERN_SIZE_MAX 15
#define VPAD_MOTOR_PATTERN_LENGTH_MAX 120
#define VPAD_TP_1920x1080 0
#define VPAD_TP_1280x720 1
#define VPAD_TP_854x480 2
extern bool isLaunchTypeELF;
VPADDir g_vpadGyroDirOverwrite[VPAD_MAX_CONTROLLERS] =
{
{{1.0f,0.0f,0.0f}, {0.0f,1.0f,0.0f}, {0.0f, 0.0f, 0.1f}},
{{1.0f,0.0f,0.0f}, {0.0f,1.0f,0.0f}, {0.0f, 0.0f, 0.1f}}
};
uint32 g_vpadGyroZeroDriftMode[VPAD_MAX_CONTROLLERS] = { VPAD_GYRO_ZERODRIFT_STANDARD, VPAD_GYRO_ZERODRIFT_STANDARD };
struct VPACGyroDirRevise_t
{
bool enabled;
VPADDir vpadGyroDirReviseBase;
float weight;
} g_vpadGyroDirRevise[VPAD_MAX_CONTROLLERS] = {};
struct VPADAccParam_t
{ // TODO P: use
float playRadius;
float sensitivity;
} g_vpadAccParam[VPAD_MAX_CONTROLLERS] = { {0, 1}, {0, 1} };
uint32 g_vpadPlayMode[VPAD_MAX_CONTROLLERS] = { VPAD_PLAY_MODE_TIGHT, VPAD_PLAY_MODE_TIGHT }; // TODO P: use
#define VPAD_MIN_CLAMP (0x102)
#define VPAD_MAX_CLAMP (0x397)
struct VPADStickClamp
{ // TODO P: use
bool crossMode; // default is circular mode
sint32 leftMax;
sint32 leftMin;
sint32 rightMax;
sint32 rightMin;
} vpadStickClamp[VPAD_MAX_CONTROLLERS] = { {false, VPAD_MAX_CLAMP, VPAD_MIN_CLAMP}, {false, VPAD_MAX_CLAMP, VPAD_MIN_CLAMP} };
struct VPADCrossStickEmulationParams
{ // TODO P: use
float leftRotation;
float leftInputRange;
float leftRadius;
float rightRotation;
float rightInputRange;
float rightRadius;
} vpadCrossStickEmulationParams[VPAD_MAX_CONTROLLERS] = {};
uint8 vpadButtonProcMode[VPAD_MAX_CONTROLLERS] = { VPAD_BUTTON_PROC_MODE_TIGHT, VPAD_BUTTON_PROC_MODE_TIGHT }; // TODO P: use
uint32 vpadLcdMode[VPAD_MAX_CONTROLLERS] = { VPAD_LCD_MODE_ON, VPAD_LCD_MODE_ON };
struct VPADTPCalibrationParam
{ // TODO P: use
uint16be offsetX;
uint16be offsetY;
float32be scaleX;
float32be scaleY;
} vpadTPCalibrationParam[VPAD_MAX_CONTROLLERS] = { {92, 254, (1280.0f / 3883.0f), (720.0f / 3694.0f)}, {92, 254, (1280.0f / 3883.0f), (720.0f / 3694.0f)} };
void _tpRawToResolution(sint32 x, sint32 y, sint32* outX, sint32* outY, sint32 width, sint32 height)
{
x -= 92;
y = 4095.0 - y - 254;
x = std::max(x, 0);
y = std::max(y, 0);
*outX = (sint32)(((double)x / 3883.0) * (double)width);
*outY = (sint32)(((double)y / 3694.0) * (double)height);
}
namespace vpad
{
enum class PlayMode : sint32
{
Loose = 0,
Tight = 1
};
enum class LcdMode
{
Off = 0,
ControllerOnly = 1,
On = 0xFF,
};
struct VPADTPCalibrationParam
{
sint16be x, y;
float32be scale_x, scale_y;
};
struct VPADTPData
{
uint16be x, y, touch, valid;
};
enum class VPADTPResolution
{
_1920x1080 = 0,
_1280x720 = 1,
_854_480 = 2,
};
enum class ButtonProcMode : uint8
{
Loose = 0,
Tight = 1,
};
struct
{
SysAllocator<coreinit::OSAlarm_t> alarm;
struct
{
uint64 drcLastCallTime = 0;
struct AccParam
{
float radius, sensitivity;
} acc_param;
BtnRepeat btn_repeat;
MEMPTR<void> sampling_callback;
PlayMode acc_play_mode;
VPADTPCalibrationParam tp_calibration_param{};
uint16 tp_size = 0xc;
struct
{
float rotation, range, radius;
}cross_stick_emulation_l{}, cross_stick_emulation_r{};
ButtonProcMode button_proc_mode;
struct
{
bool enabled = false;
struct
{
sint32 min = 0x102, max = 0x397;
} left{}, right{};
}stick_cross_clamp{};
}controller_data[VPAD_MAX_CONTROLLERS]{};
} g_vpad;
void VPADSetAccParam(sint32 channel, float radius, float sensitivity)
{
cemuLog_log(LogType::InputAPI, "VPADSetAccParam({}, {}, {})", channel, radius, sensitivity);
vpadbreak();
g_vpad.controller_data[channel].acc_param.radius = radius;
g_vpad.controller_data[channel].acc_param.sensitivity = sensitivity;
}
void VPADGetAccParam(sint32 channel, float* radius, float* sensitivity)
{
cemuLog_log(LogType::InputAPI, "VPADGetAccParam({}, {}, {})", channel, (void*)radius, (void*)sensitivity);
vpadbreak();
*radius = g_vpad.controller_data[channel].acc_param.radius;
*sensitivity = g_vpad.controller_data[channel].acc_param.sensitivity;
}
sint32 VPADRead(sint32 channel, VPADStatus* status, uint32 length, sint32be* error)
{
//printf("VPADRead(%d,0x%08X,%d,0x%08x)\n", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
/*ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(status, VPADStatus_t, 1);
ppcDefineParamU32(length, 2);
ppcDefineParamPtr(error, uint32be, 3);
cemuLog_log(LogType::InputAPI, "VPADRead({}, _, {})", channel, length);*/
// default init which should be always set
memset(status, 0x00, sizeof(VPADStatus_t));
// default misc
status->batteryLevel = 0xC0; // full battery
status->slideVolume = status->slideVolume2 = (uint8)((g_padVolume * 0xFF) / 100);
// default touch
status->tpData.validity = VPAD_TP_VALIDITY_INVALID_XY;
status->tpProcessed1.validity = VPAD_TP_VALIDITY_INVALID_XY;
status->tpProcessed2.validity = VPAD_TP_VALIDITY_INVALID_XY;
const auto controller = InputManager::instance().get_vpad_controller(channel);
if (!controller)
{
// most games expect the Wii U GamePad to be connected, so even if the user has not set it up we should still return empty samples for channel 0
if(channel != 0)
{
if (error)
*error = VPAD_READ_ERR_NO_CONTROLLER;
if (length > 0)
status->vpadErr = -1;
return 0;
}
if (error)
*error = VPAD_READ_ERR_NONE;
return 1;
}
const bool vpadDelayEnabled = ActiveSettings::VPADDelayEnabled();
if (isLaunchTypeELF)
{
// hacky workaround for homebrew games calling VPADRead in an infinite loop
PPCCore_switchToScheduler();
}
if (!g_inputConfigWindowHasFocus)
{
if (channel <= 1 && vpadDelayEnabled)
{
uint64 currentTime = coreinit::coreinit_getOSTime();
const auto dif = currentTime - vpad::g_vpad.controller_data[channel].drcLastCallTime;
if (dif <= (ESPRESSO_TIMER_CLOCK / 60ull))
{
// not ready yet
if (error)
*error = VPAD_READ_ERR_NONE;
return 0;
}
else if (dif <= ESPRESSO_TIMER_CLOCK)
{
vpad::g_vpad.controller_data[channel].drcLastCallTime += (ESPRESSO_TIMER_CLOCK / 60ull);
}
else
{
vpad::g_vpad.controller_data[channel].drcLastCallTime = currentTime;
}
}
controller->VPADRead(*status, vpad::g_vpad.controller_data[channel].btn_repeat);
if (error)
*error = VPAD_READ_ERR_NONE;
return 1;
}
else
{
if (error)
*error = VPAD_READ_ERR_NONE;
return 1;
}
}
void VPADSetBtnRepeat(sint32 channel, float delay, float pulse)
{
cemuLog_log(LogType::InputAPI, "VPADSetBtnRepeat({}, {}, {})", channel, delay, pulse);
if(pulse == 0)
{
g_vpad.controller_data[channel].btn_repeat.delay = 40000;
g_vpad.controller_data[channel].btn_repeat.pulse = 0;
}
else
{
g_vpad.controller_data[channel].btn_repeat.delay = (sint32)((delay * 200.0f) + 0.5f);
g_vpad.controller_data[channel].btn_repeat.pulse = (sint32)((pulse * 200.0f) + 0.5f);
}
}
void VPADSetAccPlayMode(sint32 channel, PlayMode play_mode)
{
cemuLog_log(LogType::InputAPI, "VPADSetAccPlayMode({}, {})", channel, (int)play_mode);
vpadbreak();
g_vpad.controller_data[channel].acc_play_mode = play_mode;
}
PlayMode VPADGetAccPlayMode(sint32 channel)
{
cemuLog_log(LogType::InputAPI, "VPADGetAccPlayMode({})", channel);
vpadbreak();
return g_vpad.controller_data[channel].acc_play_mode;
}
void* VPADSetSamplingCallback(sint32 channel, void* callback)
{
cemuLog_log(LogType::InputAPI, "VPADSetSamplingCallback({}, 0x{:x})", channel, MEMPTR(callback).GetMPTR());
vpadbreak();
void* result = g_vpad.controller_data[channel].sampling_callback;
g_vpad.controller_data[channel].sampling_callback = callback;
return result;
}
sint32 VPADCalcTPCalibrationParam(VPADTPCalibrationParam* p, uint16 raw_x1, uint16 raw_y1, uint16 x1, uint16 y1, uint16 raw_x2, uint16 raw_y2, uint16 x2, uint16 y2)
{
cemu_assert_unimplemented();
return 1;
}
void VPADGetTPCalibrationParam(sint32 channel, VPADTPCalibrationParam* param)
{
cemuLog_log(LogType::InputAPI, "VPADGetTPCalibrationParam({}, 0x{:x})", channel, MEMPTR(param).GetMPTR());
vpadbreak();
*param = g_vpad.controller_data[channel].tp_calibration_param;
}
void VPADSetTPCalibrationParam(sint32 channel, VPADTPCalibrationParam* param)
{
cemuLog_log(LogType::InputAPI, "VPADSetTPCalibrationParam({}, 0x{:x})", channel, MEMPTR(param).GetMPTR());
vpadbreak();
g_vpad.controller_data[channel].tp_calibration_param = *param;
}
void VPADGetTPCalibratedPoint(sint32 channel, VPADTPData* data, VPADTPData* raw)
{
cemuLog_log(LogType::InputAPI, "VPADGetTPCalibratedPoint({}, 0x{:x}, 0x{:x})", channel, MEMPTR(data).GetMPTR(), MEMPTR(raw).GetMPTR());
vpadbreak();
const auto& controller_data = g_vpad.controller_data[channel];
uint16 x = (uint16)((float)raw->x - ((float)controller_data.tp_calibration_param.x * controller_data.tp_calibration_param.scale_x));
uint16 y = (uint16)((float)raw->x - ((float)controller_data.tp_calibration_param.y * controller_data.tp_calibration_param.scale_y));
const int tp_size = (int)controller_data.tp_size;
int tmpx = x;
if(x <= (int)controller_data.tp_size)
tmpx = (int)controller_data.tp_size;
int tmpy = y;
if(y <= (int)controller_data.tp_size)
tmpy = (int)controller_data.tp_size;
if((0x500 - tp_size) <= tmpx)
x = (0x500 - tp_size);
if((0x2d0 - tp_size) <= tmpy)
y = (0x2d0 - tp_size);
data->x = x;
data->y = y;
data->touch = raw->touch;
data->valid = raw->valid;
}
void VPADGetTPCalibratedPointEx(sint32 channel, VPADTPResolution resolution, VPADTPData* data, VPADTPData* raw)
{
cemuLog_log(LogType::InputAPI, "VPADGetTPCalibratedPointEx({}, {}, 0x{:x}, 0x{:x})", channel, (int)resolution, MEMPTR(data).GetMPTR(), MEMPTR(raw).GetMPTR());
vpadbreak();
}
void VPADSetCrossStickEmulationParamsL(sint32 channel, float rotation, float range, float radius)
{
cemuLog_log(LogType::InputAPI, "VPADSetCrossStickEmulationParamsL({}, {}, {}, {})", channel, rotation, range, radius);
vpadbreak();
if (range < 0 || 90.0f < range)
return;
if (radius < 0 || 1.0f < radius)
return;
g_vpad.controller_data[channel].cross_stick_emulation_l.rotation = rotation;
g_vpad.controller_data[channel].cross_stick_emulation_l.range = range;
g_vpad.controller_data[channel].cross_stick_emulation_l.radius = radius;
}
void VPADSetCrossStickEmulationParamsR(sint32 channel, float rotation, float range, float radius)
{
cemuLog_log(LogType::InputAPI, "VPADSetCrossStickEmulationParamsR({}, {}, {}, {})", channel, rotation, range, radius);
vpadbreak();
if (range < 0 || 90.0f < range)
return;
if (radius < 0 || 1.0f < radius)
return;
g_vpad.controller_data[channel].cross_stick_emulation_r.rotation = rotation;
g_vpad.controller_data[channel].cross_stick_emulation_r.range = range;
g_vpad.controller_data[channel].cross_stick_emulation_r.radius = radius;
}
void VPADGetCrossStickEmulationParamsL(sint32 channel, float* rotation, float* range, float* radius)
{
cemuLog_log(LogType::InputAPI, "VPADGetCrossStickEmulationParamsL({}, 0x{:x}, 0x{:x}, 0x{:x})", channel, MEMPTR(rotation).GetMPTR(), MEMPTR(range).GetMPTR(), MEMPTR(radius).GetMPTR());
vpadbreak();
*rotation = g_vpad.controller_data[channel].cross_stick_emulation_l.rotation;
*range = g_vpad.controller_data[channel].cross_stick_emulation_l.range;
*radius = g_vpad.controller_data[channel].cross_stick_emulation_l.radius;
}
void VPADGetCrossStickEmulationParamsR(sint32 channel, float* rotation, float* range, float* radius)
{
cemuLog_log(LogType::InputAPI, "VPADGetCrossStickEmulationParamsR({}, 0x{:x}, 0x{:x}, 0x{:x})", channel, MEMPTR(rotation).GetMPTR(), MEMPTR(range).GetMPTR(), MEMPTR(radius).GetMPTR());
vpadbreak();
*rotation = g_vpad.controller_data[channel].cross_stick_emulation_r.rotation;
*range = g_vpad.controller_data[channel].cross_stick_emulation_r.range;
*radius = g_vpad.controller_data[channel].cross_stick_emulation_r.radius;
}
ButtonProcMode VPADGetButtonProcMode(sint32 channel)
{
cemuLog_log(LogType::InputAPI, "VPADGetButtonProcMode({})", channel);
vpadbreak();
return g_vpad.controller_data[channel].button_proc_mode;
}
void VPADSetButtonProcMode(sint32 channel, ButtonProcMode mode)
{
cemuLog_log(LogType::InputAPI, "VPADSetButtonProcMode({}, {})", channel, (int)mode);
vpadbreak();
g_vpad.controller_data[channel].button_proc_mode = mode;
}
void VPADEnableStickCrossClamp(sint32 channel)
{
cemuLog_log(LogType::InputAPI, "VPADEnableStickCrossClamp({})", channel);
vpadbreak();
g_vpad.controller_data[channel].stick_cross_clamp.enabled = true;
}
void VPADDisableStickCrossClamp(sint32 channel)
{
cemuLog_log(LogType::InputAPI, "VPADDisableStickCrossClamp({})", channel);
vpadbreak();
g_vpad.controller_data[channel].stick_cross_clamp.enabled = false;
}
void VPADSetLStickClampThreshold(sint32 channel, sint32 max, sint32 min)
{
cemuLog_log(LogType::InputAPI, "VPADSetLStickClampThreshold({}, {}, {})", channel, max, min);
vpadbreak();
g_vpad.controller_data[channel].stick_cross_clamp.left.max = std::min(0x397, max);
g_vpad.controller_data[channel].stick_cross_clamp.left.min = std::max(0x102, min);
}
void VPADSetRStickClampThreshold(sint32 channel, sint32 max, sint32 min)
{
cemuLog_log(LogType::InputAPI, "VPADSetRStickClampThreshold({}, {}, {})", channel, max, min);
vpadbreak();
g_vpad.controller_data[channel].stick_cross_clamp.right.max = std::min(0x397, max);
g_vpad.controller_data[channel].stick_cross_clamp.right.min = std::max(0x102, min);
}
void VPADGetLStickClampThreshold(sint32 channel, sint32* max, sint32* min)
{
cemuLog_log(LogType::InputAPI, "VPADGetLStickClampThreshold({}, 0x{:x}, 0x{:x})", channel, MEMPTR(max).GetMPTR(), MEMPTR(min).GetMPTR());
vpadbreak();
*max = g_vpad.controller_data[channel].stick_cross_clamp.left.max;
*min = g_vpad.controller_data[channel].stick_cross_clamp.left.min;
}
void VPADGetRStickClampThreshold(sint32 channel, sint32* max, sint32* min)
{
cemuLog_log(LogType::InputAPI, "VPADGetRStickClampThreshold({}, 0x{:x}, 0x{:x})", channel, MEMPTR(max).GetMPTR(), MEMPTR(min).GetMPTR());
vpadbreak();
*max = g_vpad.controller_data[channel].stick_cross_clamp.right.max;
*min = g_vpad.controller_data[channel].stick_cross_clamp.right.min;
}
}
void vpadExport_VPADGetAccParam(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(playRadius, float32be, 1);
ppcDefineParamPtr(sensitivity, float32be, 2);
cemuLog_log(LogType::InputAPI, "VPADGetAccParam({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*playRadius = g_vpadAccParam[channel].playRadius;
*sensitivity = g_vpadAccParam[channel].sensitivity;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetAccParam(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADSetAccParam({}, {}, {})", channel, hCPU->fpr[1].fpr, hCPU->fpr[2].fpr);
if (channel < VPAD_MAX_CONTROLLERS)
{
g_vpadAccParam[channel].playRadius = hCPU->fpr[1].fpr;
g_vpadAccParam[channel].sensitivity = hCPU->fpr[2].fpr;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetAccPlayMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADGetAccPlayMode({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
osLib_returnFromFunction(hCPU, g_vpadPlayMode[channel]);
}
else
{
debugBreakpoint();
osLib_returnFromFunction(hCPU, VPAD_PLAY_MODE_TIGHT);
}
}
void vpadExport_VPADSetAccPlayMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU32(playMode, 1);
cemuLog_log(LogType::InputAPI, "VPADSetAccPlayMode({}, {})", channel, playMode);
if (channel < VPAD_MAX_CONTROLLERS)
{
g_vpadPlayMode[channel] = playMode;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADEnableStickCrossClamp(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADEnableStickCrossClamp({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadStickClamp[channel].crossMode = true;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADDisableStickCrossClamp(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADDisableStickCrossClamp({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadStickClamp[channel].crossMode = false;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetLStickClampThreshold(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamS32(maxValue, 1);
ppcDefineParamS32(minValue, 2);
cemuLog_log(LogType::InputAPI, "VPADSetLStickClampThreshold({}, {}, {})", channel, maxValue, minValue);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadStickClamp[channel].leftMax = std::min(VPAD_MAX_CLAMP, maxValue);
vpadStickClamp[channel].leftMin = std::max(VPAD_MIN_CLAMP, minValue);
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetRStickClampThreshold(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamS32(maxValue, 1);
ppcDefineParamS32(minValue, 2);
cemuLog_log(LogType::InputAPI, "VPADSetRStickClampThreshold({}, {}, {})", channel, maxValue, minValue);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadStickClamp[channel].rightMax = std::min(VPAD_MAX_CLAMP, maxValue);
vpadStickClamp[channel].rightMin = std::max(VPAD_MIN_CLAMP, minValue);
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetLStickClampThreshold(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(maxValue, uint32be, 1);
ppcDefineParamPtr(minValue, uint32be, 2);
cemuLog_log(LogType::InputAPI, "VPADGetLStickClampThreshold({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*maxValue = vpadStickClamp[channel].leftMax;
*minValue = vpadStickClamp[channel].leftMin;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetRStickClampThreshold(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(maxValue, uint32be, 1);
ppcDefineParamPtr(minValue, uint32be, 2);
cemuLog_log(LogType::InputAPI, "VPADGetRStickClampThreshold({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*maxValue = vpadStickClamp[channel].rightMax;
*minValue = vpadStickClamp[channel].rightMin;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetCrossStickEmulationParamsL(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADSetCrossStickEmulationParamsL({}, {}, {}, {})", channel, hCPU->fpr[1].fpr, hCPU->fpr[2].fpr, hCPU->fpr[3].fpr);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadCrossStickEmulationParams[channel].leftRotation = hCPU->fpr[1].fpr;
vpadCrossStickEmulationParams[channel].leftInputRange = hCPU->fpr[2].fpr;
vpadCrossStickEmulationParams[channel].leftRadius = hCPU->fpr[3].fpr;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetCrossStickEmulationParamsR(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADSetCrossStickEmulationParamsR({}, {}, {}, {})", channel, hCPU->fpr[1].fpr, hCPU->fpr[2].fpr, hCPU->fpr[3].fpr);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadCrossStickEmulationParams[channel].rightRotation = hCPU->fpr[1].fpr;
vpadCrossStickEmulationParams[channel].rightInputRange = hCPU->fpr[2].fpr;
vpadCrossStickEmulationParams[channel].rightRadius = hCPU->fpr[3].fpr;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetCrossStickEmulationParamsL(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(rotation, float32be, 1);
ppcDefineParamPtr(inputRange, float32be, 2);
ppcDefineParamPtr(radius, float32be, 3);
cemuLog_log(LogType::InputAPI, "VPADGetCrossStickEmulationParamsL({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*rotation = vpadCrossStickEmulationParams[channel].leftRotation;
*inputRange = vpadCrossStickEmulationParams[channel].leftInputRange;
*radius = vpadCrossStickEmulationParams[channel].leftRadius;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetCrossStickEmulationParamsR(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(rotation, float32be, 1);
ppcDefineParamPtr(inputRange, float32be, 2);
ppcDefineParamPtr(radius, float32be, 3);
cemuLog_log(LogType::InputAPI, "VPADGetCrossStickEmulationParamsR({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*rotation = vpadCrossStickEmulationParams[channel].rightRotation;
*inputRange = vpadCrossStickEmulationParams[channel].rightInputRange;
*radius = vpadCrossStickEmulationParams[channel].rightRadius;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetButtonProcMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADGetButtonProcMode({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
osLib_returnFromFunction(hCPU, vpadButtonProcMode[channel]);
}
else
{
debugBreakpoint();
osLib_returnFromFunction(hCPU, VPAD_BUTTON_PROC_MODE_TIGHT);
}
}
void vpadExport_VPADSetButtonProcMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU8(mode, 1);
cemuLog_log(LogType::InputAPI, "VPADSetButtonProcMode({}, {})", channel, mode);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadButtonProcMode[channel] = mode;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetLcdMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU32(mode, 1);
cemuLog_log(LogType::InputAPI, "VPADSetLcdMode({}, {})", channel, mode);
if (channel < VPAD_MAX_CONTROLLERS)
{
vpadLcdMode[channel] = mode;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetLcdMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamPtr(mode, uint32be, 1);
cemuLog_log(LogType::InputAPI, "VPADGetLcdMode({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*mode = vpadLcdMode[channel];
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADControlMotor(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamUStr(pattern, 1);
ppcDefineParamU8(length, 2);
cemuLog_log(LogType::InputAPI, "VPADControlMotor({}, _, {})", channel, length);
if (length > 120)
{
cemuLog_log(LogType::InputAPI, "VPADControlMotor() - length too high with {} of 120", length);
length = 120;
}
if (const auto controller = InputManager::instance().get_vpad_controller(channel))
{
// if length is zero -> stop vibration
if (length == 0)
{
controller->clear_rumble();
}
else
{
// check for max queue length
if (!controller->push_rumble(pattern, length))
{
osLib_returnFromFunction(hCPU, -1); // TODO P: not sure about the exact return value
return;
}
}
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADStopMotor(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
cemuLog_log(LogType::InputAPI, "VPADStopMotor({})", channel);
if (const auto controller = InputManager::instance().get_vpad_controller(channel))
{
controller->clear_rumble();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetTPCalibrationParam(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamMEMPTR(params, VPADTPCalibrationParam, 1);
debugBreakpoint();
if (channel < VPAD_MAX_CONTROLLERS)
{
VPADTPCalibrationParam* calibrationParam = params.GetPtr();
cemuLog_log(LogType::InputAPI, "VPADSetTPCalibrationParam({}, {}, {}, {}, {})", channel, (uint16)calibrationParam->offsetX, (uint16)calibrationParam->offsetX, (float)calibrationParam->scaleX, (float)calibrationParam->scaleY);
vpadTPCalibrationParam[channel].offsetX = calibrationParam->offsetX;
vpadTPCalibrationParam[channel].offsetX = calibrationParam->offsetY;
vpadTPCalibrationParam[channel].scaleX = calibrationParam->scaleX;
vpadTPCalibrationParam[channel].scaleY = calibrationParam->scaleY;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetTPCalibrationParam(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(calibrationParam, VPADTPCalibrationParam, 1);
cemuLog_log(LogType::InputAPI, "VPADSetTPCalibrationParam({})", channel);
calibrationParam->offsetX = vpadTPCalibrationParam[channel].offsetX;
calibrationParam->offsetY = vpadTPCalibrationParam[channel].offsetY;
calibrationParam->scaleX = vpadTPCalibrationParam[channel].scaleX;
calibrationParam->scaleY = vpadTPCalibrationParam[channel].scaleY;
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetTPCalibratedPoint(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(outputDisplay, VPADTPData_t, 1);
ppcDefineParamStructPtr(inputRaw, VPADTPData_t, 2);
cemuLog_log(LogType::InputAPI, "VPADGetTPCalibratedPoint({})", channel);
memmove(outputDisplay, inputRaw, sizeof(VPADTPData_t));
// vpadTPCalibrationParam[channel]
sint16 x = outputDisplay->x;
sint16 y = outputDisplay->y;
sint32 outputX;
sint32 outputY;
_tpRawToResolution(x, y, &outputX, &outputY, 1280, 720);
outputDisplay->x = outputX;
outputDisplay->y = outputY;
outputDisplay->touch = inputRaw->touch;
outputDisplay->validity = inputRaw->validity;
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetTPCalibratedPointEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamS32(tpResolution, 1);
ppcDefineParamStructPtr(outputDisplay, VPADTPData_t, 2);
ppcDefineParamStructPtr(inputRaw, VPADTPData_t, 3);
cemuLog_log(LogType::InputAPI, "VPADGetTPCalibratedPointEx({})", channel);
//debug_printf("TPInput: %d %d %04x %04x\n", _swapEndianU16(inputRaw->touch), _swapEndianU16(inputRaw->validity), _swapEndianU16(inputRaw->x), _swapEndianU16(inputRaw->y));
memmove(outputDisplay, inputRaw, sizeof(VPADTPData_t));
//debug_printf("VPADGetTPCalibratedPointEx(): Resolution %d\n", hCPU->gpr[4]);
sint16 x = outputDisplay->x;
sint16 y = outputDisplay->y;
sint32 outputX = 0;
sint32 outputY = 0;
if (tpResolution == VPAD_TP_1920x1080)
{
_tpRawToResolution(x, y, &outputX, &outputY, 1920, 1080);
}
else if (tpResolution == VPAD_TP_1280x720)
{
_tpRawToResolution(x, y, &outputX, &outputY, 1280, 720);
}
else if (tpResolution == VPAD_TP_854x480)
{
_tpRawToResolution(x, y, &outputX, &outputY, 854, 480);
}
else
{
debugBreakpoint();
debug_printf("VPADGetTPCalibratedPointEx(): Unsupported tp resolution\n");
}
outputDisplay->x = outputX;
outputDisplay->y = outputY;
outputDisplay->touch = inputRaw->touch;
outputDisplay->validity = inputRaw->validity;
//debug_printf("VPADGetTPCalibratedPointEx %d %d\n", _swapEndianU16(outputDisplay->x), _swapEndianU16(outputDisplay->y));
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetGyroDirection(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(dir, VPADDir, 1);
cemuLog_log(LogType::InputAPI, "VPADSetGyroDirection({}, <<{:f}, {:f}, {:f}>, <{:f}, {:f}, {:f}>, <{:f}, {:f}, {:f}>>)", channel
, (float)dir->x.x, (float)dir->x.y, (float)dir->x.z
, (float)dir->y.x, (float)dir->y.y, (float)dir->y.z
, (float)dir->z.x, (float)dir->z.y, (float)dir->z.z);
if (channel < VPAD_MAX_CONTROLLERS)
{
g_vpadGyroDirOverwrite[channel] = *dir;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADGetGyroZeroDriftMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamMEMPTR(gyroMode, uint32be, 1);
cemuLog_log(LogType::InputAPI, "VPADGetGyroZeroDriftMode({})", channel);
if (channel < VPAD_MAX_CONTROLLERS)
{
*gyroMode = g_vpadGyroZeroDriftMode[channel];
}
else
{
debugBreakpoint();
*gyroMode = VPAD_GYRO_ZERODRIFT_NONE;
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetGyroZeroDriftMode(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamU32(gyroMode, 1);
cemuLog_log(LogType::InputAPI, "VPADSetGyroZeroDriftMode({}, {})", channel, gyroMode);
if (channel < VPAD_MAX_CONTROLLERS)
{
if (gyroMode > VPAD_GYRO_ZERODRIFT_NONE)
{
debugBreakpoint();
}
else
{
g_vpadGyroZeroDriftMode[channel] = gyroMode;
}
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetGyroDirReviseBase(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
ppcDefineParamStructPtr(dir, VPADDir, 1);
if (channel < VPAD_MAX_CONTROLLERS)
{
g_vpadGyroDirRevise[channel].vpadGyroDirReviseBase = *dir;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADDisableGyroDirRevise(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
if (channel < VPAD_MAX_CONTROLLERS)
{
g_vpadGyroDirRevise[channel].enabled = false;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
void vpadExport_VPADSetGyroDirReviseParam(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(channel, 0);
if (channel < VPAD_MAX_CONTROLLERS)
{
g_vpadGyroDirRevise[channel].weight = (float)hCPU->fpr[1].fpr;
}
else
{
debugBreakpoint();
}
osLib_returnFromFunction(hCPU, 0);
}
namespace vpad
{
void TickFunction(PPCInterpreter_t* hCPU)
{
// check if homebutton is pressed
// check connection to drc
const auto& instance = InputManager::instance();
for (auto i = 0; i < InputManager::kMaxVPADControllers; ++i)
{
if (!g_vpad.controller_data[i].sampling_callback)
continue;
if(const auto controller = instance.get_vpad_controller(i))
{
cemuLog_log(LogType::InputAPI, "Calling VPADSamplingCallback({})", i);
PPCCoreCallback(g_vpad.controller_data[i].sampling_callback, i);
}
}
osLib_returnFromFunction(hCPU, 0);
}
void start()
{
coreinit::OSCreateAlarm(&g_vpad.alarm);
const uint64 start_tick = coreinit::coreinit_getOSTime();
const uint64 period_tick = coreinit::EspressoTime::GetTimerClock() * 5 / 1000;
const MPTR handler = PPCInterpreter_makeCallableExportDepr(TickFunction);
coreinit::OSSetPeriodicAlarm(&g_vpad.alarm, start_tick, period_tick, handler);
}
void load()
{
cafeExportRegister("vpad", VPADSetBtnRepeat, LogType::InputAPI);
cafeExportRegister("vpad", VPADSetSamplingCallback, LogType::InputAPI);
cafeExportRegister("vpad", VPADRead, LogType::InputAPI);
osLib_addFunction("vpad", "VPADGetAccParam", vpadExport_VPADGetAccParam);
osLib_addFunction("vpad", "VPADSetAccParam", vpadExport_VPADSetAccParam);
osLib_addFunction("vpad", "VPADGetAccPlayMode", vpadExport_VPADGetAccPlayMode);
osLib_addFunction("vpad", "VPADSetAccPlayMode", vpadExport_VPADSetAccPlayMode);
osLib_addFunction("vpad", "VPADEnableStickCrossClamp", vpadExport_VPADEnableStickCrossClamp);
osLib_addFunction("vpad", "VPADDisableStickCrossClamp", vpadExport_VPADDisableStickCrossClamp);
osLib_addFunction("vpad", "VPADSetLStickClampThreshold", vpadExport_VPADSetLStickClampThreshold);
osLib_addFunction("vpad", "VPADSetRStickClampThreshold", vpadExport_VPADSetRStickClampThreshold);
osLib_addFunction("vpad", "VPADGetLStickClampThreshold", vpadExport_VPADGetLStickClampThreshold);
osLib_addFunction("vpad", "VPADGetRStickClampThreshold", vpadExport_VPADGetRStickClampThreshold);
osLib_addFunction("vpad", "VPADSetCrossStickEmulationParamsL", vpadExport_VPADSetCrossStickEmulationParamsL);
osLib_addFunction("vpad", "VPADSetCrossStickEmulationParamsR", vpadExport_VPADSetCrossStickEmulationParamsR);
osLib_addFunction("vpad", "VPADGetCrossStickEmulationParamsL", vpadExport_VPADGetCrossStickEmulationParamsL);
osLib_addFunction("vpad", "VPADGetCrossStickEmulationParamsR", vpadExport_VPADGetCrossStickEmulationParamsR);
osLib_addFunction("vpad", "VPADGetButtonProcMode", vpadExport_VPADGetButtonProcMode);
osLib_addFunction("vpad", "VPADSetButtonProcMode", vpadExport_VPADSetButtonProcMode);
osLib_addFunction("vpad", "VPADGetLcdMode", vpadExport_VPADGetLcdMode);
osLib_addFunction("vpad", "VPADSetLcdMode", vpadExport_VPADSetLcdMode);
osLib_addFunction("vpad", "VPADControlMotor", vpadExport_VPADControlMotor);
osLib_addFunction("vpad", "VPADStopMotor", vpadExport_VPADStopMotor);
osLib_addFunction("vpad", "VPADGetTPCalibrationParam", vpadExport_VPADGetTPCalibrationParam);
osLib_addFunction("vpad", "VPADSetTPCalibrationParam", vpadExport_VPADSetTPCalibrationParam);
osLib_addFunction("vpad", "VPADGetTPCalibratedPoint", vpadExport_VPADGetTPCalibratedPoint);
osLib_addFunction("vpad", "VPADGetTPCalibratedPointEx", vpadExport_VPADGetTPCalibratedPointEx);
//osLib_addFunction("vpad", "VPADRead", vpadExport_VPADRead);
//osLib_addFunction("vpad", "VPADSetSamplingCallback", vpadExport_VPADSetSamplingCallback);
//osLib_addFunction("vpad", "VPADSetBtnRepeat", vpadExport_VPADSetBtnRepeat);
osLib_addFunction("vpad", "VPADGetGyroZeroDriftMode", vpadExport_VPADGetGyroZeroDriftMode);
osLib_addFunction("vpad", "VPADSetGyroDirection", vpadExport_VPADSetGyroDirection);
osLib_addFunction("vpad", "VPADSetGyroZeroDriftMode", vpadExport_VPADSetGyroZeroDriftMode);
osLib_addFunction("vpad", "VPADSetGyroDirReviseBase", vpadExport_VPADSetGyroDirReviseBase);
osLib_addFunction("vpad", "VPADDisableGyroDirRevise", vpadExport_VPADDisableGyroDirRevise);
osLib_addFunction("vpad", "VPADSetGyroDirReviseParam", vpadExport_VPADSetGyroDirReviseParam);
}
}
| 35,137
|
C++
|
.cpp
| 995
| 32.758794
| 227
| 0.754385
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,082
|
nsysnet.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nsysnet/nsysnet.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "nsysnet.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/IOSU/legacy/iosu_crypto.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Common/socket.h"
#if BOOST_OS_UNIX
#define WSAEWOULDBLOCK EWOULDBLOCK
#define WSAEINPROGRESS EINPROGRESS
#define WSAESHUTDOWN ESHUTDOWN
#define WSAECONNABORTED ECONNABORTED
#define WSAHOST_NOT_FOUND EAI_NONAME
#define WSAENOTCONN ENOTCONN
#define GETLASTERR errno
#endif // BOOST_OS_UNIX
#if BOOST_OS_WINDOWS
#define GETLASTERR WSAGetLastError()
#endif //BOOST_OS_WINDOWS
#define WU_AF_INET 2
#define WU_SOCK_STREAM 1
#define WU_SOCK_DGRAM 2
#define WU_IPPROTO_IP 0
#define WU_IPPROTO_TCP 6
#define WU_IPPROTO_UDP 17
#define WU_SO_REUSEADDR 0x0004
#define WU_SO_KEEPALIVE 0x0008
#define WU_SO_DONTROUTE 0x0010
#define WU_SO_BROADCAST 0x0020
#define WU_SO_LINGER 0x0080
#define WU_SO_OOBINLINE 0x0100
#define WU_SO_TCPSACK 0x0200
#define WU_SO_WINSCALE 0x0400
#define WU_SO_SNDBUF 0x1001
#define WU_SO_RCVBUF 0x1002
#define WU_SO_SNDLOWAT 0x1003
#define WU_SO_RCVLOWAT 0x1004
#define WU_SO_LASTERROR 0x1007
#define WU_SO_TYPE 0x1008
#define WU_SO_HOPCNT 0x1009
#define WU_SO_MAXMSG 0x1010
#define WU_SO_RXDATA 0x1011
#define WU_SO_TXDATA 0x1012
#define WU_SO_MYADDR 0x1013
#define WU_SO_NBIO 0x1014
#define WU_SO_BIO 0x1015
#define WU_SO_NONBLOCK 0x1016
#define WU_SO_UNKNOWN1019 0x1019 // tcp related
#define WU_SO_UNKNOWN101A 0x101A // tcp related
#define WU_SO_UNKNOWN101B 0x101B // tcp related
#define WU_SO_NOSLOWSTART 0x4000
#define WU_SO_RUSRBUF 0x10000
#define WU_TCP_ACKDELAYTIME 0x2001
#define WU_TCP_NOACKDELAY 0x2002
#define WU_TCP_MAXSEG 0x2003
#define WU_TCP_NODELAY 0x2004
#define WU_TCP_UNKNOWN 0x2005 // amount of mss received before sending an ack
#define WU_IP_TOS 3
#define WU_IP_TTL 4
#define WU_IP_MULTICAST_IF 9
#define WU_IP_MULTICAST_TTL 10
#define WU_IP_MULTICAST_LOOP 11
#define WU_IP_ADD_MEMBERSHIP 12
#define WU_IP_DROP_MEMBERSHIP 13
#define WU_IP_UNKNOWN 14
#define WU_SOL_SOCKET -1 // this constant differs from Win32 socket API
#define WU_MSG_PEEK 0x02
#define WU_MSG_DONTWAIT 0x20
// error codes
#define WU_SO_SUCCESS 0x0000
#define WU_SO_EWOULDBLOCK 0x0006
#define WU_SO_ECONNRESET 0x0008
#define WU_SO_ENOTCONN 0x0009
#define WU_SO_EINVAL 0x000B
#define WU_SO_EINPROGRESS 0x0016
#define WU_SO_EAFNOSUPPORT 0x0021
#define WU_SO_ESHUTDOWN 0x000F
typedef signed int WUSOCKET;
bool sockLibReady = false;
void nsysnetExport_socket_lib_init(PPCInterpreter_t* hCPU)
{
sockLibReady = true;
#if BOOST_OS_WINDOWS
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#endif // BOOST_OS_WINDOWS
osLib_returnFromFunction(hCPU, 0); // 0 -> Success
}
void nsysnetExport_socket_lib_finish(PPCInterpreter_t* hCPU)
{
sockLibReady = false;
#if BOOST_OS_WINDOWS
WSACleanup();
#endif // BOOST_OS_WINDOWS
osLib_returnFromFunction(hCPU, 0); // 0 -> Success
}
static uint32be* __gh_errno_ptr()
{
OSThread_t* osThread = coreinit::OSGetCurrentThread();
return &osThread->context.ghs_errno;
}
void _setSockError(sint32 errCode)
{
*(uint32be*)__gh_errno_ptr() = (uint32)errCode;
}
sint32 _getSockError()
{
return (sint32)*(uint32be*)__gh_errno_ptr();
}
// error translation modes for _translateError
#define _ERROR_MODE_DEFAULT 0
#define _ERROR_MODE_CONNECT 1
#define _ERROR_MODE_ACCEPT 2
sint32 _translateError(sint32 returnCode, sint32 wsaError, sint32 mode = _ERROR_MODE_DEFAULT)
{
if (mode == _ERROR_MODE_ACCEPT)
{
// accept mode
if (returnCode >= 0)
{
_setSockError(WU_SO_SUCCESS);
return returnCode;
}
}
else
{
// any other mode
if (returnCode == 0)
{
_setSockError(WU_SO_SUCCESS);
return 0;
}
}
// handle WSA error
switch (wsaError)
{
case 0:
_setSockError(WU_SO_SUCCESS);
break;
case WSAEWOULDBLOCK:
if( mode == _ERROR_MODE_CONNECT )
_setSockError(WU_SO_EINPROGRESS);
else
_setSockError(WU_SO_EWOULDBLOCK);
break;
case WSAEINPROGRESS:
_setSockError(WU_SO_EINPROGRESS);
break;
case WSAECONNABORTED:
debug_printf("WSAECONNABORTED\n");
#ifdef CEMU_DEBUG_ASSERT
assert_dbg();
#endif
break;
case WSAESHUTDOWN:
_setSockError(WU_SO_ESHUTDOWN);
break;
case WSAENOTCONN:
_setSockError(WU_SO_ENOTCONN);
break;
default:
cemuLog_logDebug(LogType::Force, "Unhandled wsaError {}", wsaError);
_setSockError(99999); // unhandled error
}
return -1;
}
void nsysnetExport_socketlasterr(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Socket, "socketlasterr() -> {}", _getSockError());
osLib_returnFromFunction(hCPU, _getSockError());
}
typedef struct
{
uint32 handle;
bool isShutdownRecv;
bool isShutdownSend;
// socket creation info
sint32 family;
sint32 type;
sint32 protocol;
// host side info
SOCKET s;
// socket options
bool isNonBlocking;
}virtualSocket_t;
typedef struct
{
uint32 wu_s_addr;
}wu_in_addr;
struct wu_sockaddr
{
uint16 sa_family;
uint8 sa_data[14]; // IPv4
};
void sockaddr_guest2host(wu_sockaddr* input, sockaddr* output)
{
output->sa_family = _swapEndianU16(input->sa_family);
memcpy(output->sa_data, input->sa_data, 14);
}
void sockaddr_host2guest(sockaddr* input, wu_sockaddr* output)
{
output->sa_family = _swapEndianU16(input->sa_family);
memcpy(output->sa_data, input->sa_data, 14);
}
struct wu_addrinfo
{
sint32 ai_flags;
sint32 ai_family;
sint32 ai_socktype;
sint32 ai_protocol;
sint32 ai_addrlen;
MPTR ai_canonname;
MPTR ai_addr;
MPTR ai_next;
};
#define WU_SOCKET_LIMIT (32) // only 32 socket handles are supported per running process
virtualSocket_t* virtualSocketTable[WU_SOCKET_LIMIT] = { 0 };
sint32 _getFreeSocketHandle()
{
for (sint32 i = 0; i < WU_SOCKET_LIMIT; i++)
{
if (virtualSocketTable[i] == NULL)
return i + 1;
}
return 0;
}
#if BOOST_OS_WINDOWS
#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
#endif // BOOST_OS_WINDOWS
WUSOCKET nsysnet_createVirtualSocket(sint32 family, sint32 type, sint32 protocol)
{
sint32 s = _getFreeSocketHandle();
if (s == 0)
{
cemuLog_logDebug(LogType::Force, "Ran out of socket handles");
cemu_assert(false);
}
virtualSocket_t* vs = (virtualSocket_t*)malloc(sizeof(virtualSocket_t));
memset(vs, 0, sizeof(virtualSocket_t));
vs->family = family;
vs->type = type;
vs->protocol = protocol;
vs->handle = s;
virtualSocketTable[s - 1] = vs;
// init host socket
vs->s = socket(family, type, protocol);
#if BOOST_OS_WINDOWS
// disable reporting of PORT_UNREACHABLE for UDP sockets
if (protocol == IPPROTO_UDP)
{
BOOL bNewBehavior = FALSE;
DWORD dwBytesReturned = 0;
WSAIoctl(vs->s, SIO_UDP_CONNRESET, &bNewBehavior, sizeof bNewBehavior, NULL, 0, &dwBytesReturned, NULL, NULL);
}
#endif // BOOST_OS_WINDOWS
return vs->handle;
}
WUSOCKET nsysnet_createVirtualSocketFromExistingSocket(SOCKET existingSocket)
{
cemuLog_logDebug(LogType::Force, "nsysnet_createVirtualSocketFromExistingSocket - incomplete");
sint32 s = _getFreeSocketHandle();
if (s == 0)
{
cemuLog_logDebug(LogType::Force, "Ran out of socket handles");
cemu_assert(false);
}
virtualSocket_t* vs = (virtualSocket_t*)malloc(sizeof(virtualSocket_t));
memset(vs, 0, sizeof(virtualSocket_t));
#if BOOST_OS_WINDOWS
// SO_TYPE -> type
// SO_BSP_STATE -> protocol + other info
// SO_PROTOCOL_INFO -> protocol + type?
WSAPROTOCOL_INFO protocolInfo = { 0 };
int optLen = sizeof(protocolInfo);
getsockopt(existingSocket, SOL_SOCKET, SO_PROTOCOL_INFO, (char*)&protocolInfo, &optLen);
// todo - translate protocolInfo
vs->family = protocolInfo.iAddressFamily;
vs->type = protocolInfo.iSocketType;
vs->protocol = protocolInfo.iSocketType;
#else
{
int type;
socklen_t optlen;
getsockopt(vs->s, SOL_SOCKET, SO_TYPE, &type, &optlen);
vs->type = type;
vs->protocol = type;
}
{
sockaddr saddr;
socklen_t len;
getsockname(vs->s, &saddr, &len);
vs->family = saddr.sa_family;
}
#endif
vs->handle = s;
virtualSocketTable[s - 1] = vs;
vs->s = existingSocket;
return vs->handle;
}
void nsysnet_notifyCloseSharedSocket(SOCKET existingSocket)
{
for (sint32 i = 0; i < WU_SOCKET_LIMIT; i++)
{
if (virtualSocketTable[i] && virtualSocketTable[i]->s == existingSocket)
{
// remove entry
free(virtualSocketTable[i]);
virtualSocketTable[i] = nullptr;
return;
}
}
}
virtualSocket_t* nsysnet_getVirtualSocketObject(WUSOCKET s)
{
uint8 handleType = 0;
s--;
if (s < 0 || s >= WU_SOCKET_LIMIT)
return NULL;
return virtualSocketTable[s];
}
sint32 nsysnet_getVirtualSocketHandleFromHostHandle(SOCKET s)
{
for (sint32 i = 0; i < WU_SOCKET_LIMIT; i++)
{
if (virtualSocketTable[i] && virtualSocketTable[i]->s == s)
return i + 1;
}
return -1;
}
void nsysnetExport_socket(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "socket({},{},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamS32(family, 0);
ppcDefineParamS32(type, 1);
ppcDefineParamS32(protocol, 2);
if (sockLibReady == false)
{
_setSockError(0x2B);
osLib_returnFromFunction(hCPU, -1);
return;
}
// below here Ioctl code should start
// check family param
if (family != WU_AF_INET)
{
cemuLog_logDebug(LogType::Force, "socket(): Unsupported family");
// todo - error code
osLib_returnFromFunction(hCPU, -1);
return;
}
// check type param
if (type != WU_SOCK_STREAM && type != WU_SOCK_DGRAM)
{
cemuLog_logDebug(LogType::Force, "socket(): Unsupported family");
// todo - error code
osLib_returnFromFunction(hCPU, -1);
return;
}
if (protocol != WU_IPPROTO_TCP && protocol != WU_IPPROTO_UDP && protocol != WU_IPPROTO_IP)
{
cemuLog_logDebug(LogType::Force, "socket(): Unsupported protocol");
// todo - error code
osLib_returnFromFunction(hCPU, -1);
return;
}
WUSOCKET s = nsysnet_createVirtualSocket(family, type, protocol);
cemuLog_log(LogType::Socket, "Created socket handle {}", s);
osLib_returnFromFunction(hCPU, s);
}
void nsysnetExport_mw_socket(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "mw_socket");
nsysnetExport_socket(hCPU);
}
void nsysnetExport_shutdown(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "shutdown({},{})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamS32(s, 0);
ppcDefineParamS32(how, 1);
sint32 r = 0;
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
assert_dbg();
}
else
{
r = shutdown(vs->s, how);
if (how == 0)
{
// shutdown recv
vs->isShutdownRecv = true;
}
else if (how == 1)
{
// shutdown send
vs->isShutdownSend = true;
}
else if (how == 2)
{
// shutdown recv & send
vs->isShutdownRecv = true;
vs->isShutdownSend = true;
}
else
assert_dbg();
}
_setSockError(0); // todo
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_socketclose(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "socketclose({})", hCPU->gpr[3]);
ppcDefineParamS32(s, 0);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs)
{
closesocket(vs->s);
free(vs);
virtualSocketTable[s - 1] = NULL;
}
osLib_returnFromFunction(hCPU, 0);
}
sint32 _socket_nonblock(SOCKET s, u_long mode)
{
#if BOOST_OS_WINDOWS
return ioctlsocket(s, FIONBIO, &mode);
#else
int flags = fcntl(s, F_GETFL);
if(mode)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
return fcntl(s, F_SETFL, flags);
#endif
}
void nsysnetExport_setsockopt(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "setsockopt({},0x{:x},0x{:05x},0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
ppcDefineParamS32(s, 0);
ppcDefineParamS32(level, 1);
ppcDefineParamS32(optname, 2);
ppcDefineParamStr(optval, 3);
ppcDefineParamS32(optlen, 4);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (!vs)
{
cemu_assert_suspicious();
}
else
{
// translate level to host API
sint32 hostLevel;
if (level == WU_SOL_SOCKET)
{
hostLevel = SOL_SOCKET;
// handle op
if (optname == WU_SO_REUSEADDR)
{
if (optlen != 4)
cemu_assert_suspicious();
sint32 optvalLE = _swapEndianU32(*(uint32*)optval);
sint32 r = setsockopt(vs->s, hostLevel, SO_REUSEADDR, (char*)&optvalLE, 4);
if (r != 0)
cemu_assert_suspicious();
}
else if (optname == WU_SO_NBIO || optname == WU_SO_BIO)
{
// similar to WU_SO_NONBLOCK but always sets blocking (_BIO) or non-blocking (_NBIO) mode regardless of option value
if (optlen == 4)
{
sint32 optvalLE = _swapEndianU32(*(uint32*)optval);
}
else if (optlen == 0)
{
// no opt needed
}
else
cemu_assert_suspicious();
bool setNonBlocking = optname == WU_SO_NBIO;
u_long mode = setNonBlocking ? 1 : 0;
_socket_nonblock(vs->s, mode);
vs->isNonBlocking = setNonBlocking;
}
else if (optname == WU_SO_NONBLOCK)
{
if (optlen != 4)
assert_dbg();
sint32 optvalLE = _swapEndianU32(*(uint32*)optval);
u_long mode = optvalLE; // 1 -> enable, 0 -> disable
_socket_nonblock(vs->s, mode);
vs->isNonBlocking = mode != 0;
}
else if (optname == WU_SO_KEEPALIVE)
{
cemuLog_logDebug(LogType::Socket, "todo: setsockopt() for WU_SO_KEEPALIVE");
}
else if (optname == WU_SO_WINSCALE)
{
cemuLog_logDebug(LogType::Socket, "todo: setsockopt() for WU_SO_WINSCALE");
}
else if (optname == WU_SO_RCVBUF)
{
cemuLog_log(LogType::Socket, "Set receive buffer size to 0x{:08x}", _swapEndianU32(*(uint32*)optval));
if (optlen != 4)
assert_dbg();
sint32 optvalLE = _swapEndianU32(*(uint32*)optval);
u_long mode = optvalLE;
if (setsockopt(vs->s, SOL_SOCKET, SO_RCVBUF, (const char*)&mode, sizeof(u_long)) != 0)
assert_dbg();
}
else if (optname == WU_SO_SNDBUF)
{
cemuLog_log(LogType::Socket, "Set send buffer size to 0x{:08x}", _swapEndianU32(*(uint32*)optval));
if (optlen != 4)
assert_dbg();
sint32 optvalLE = _swapEndianU32(*(uint32*)optval);
u_long mode = optvalLE;
if (setsockopt(vs->s, SOL_SOCKET, SO_SNDBUF, (const char*)&mode, sizeof(u_long)) != 0)
assert_dbg();
}
else
{
cemuLog_logDebug(LogType::Force, "setsockopt(WU_SOL_SOCKET): Unsupported optname 0x{:08x}", optname);
}
}
else if (level == WU_IPPROTO_TCP)
{
hostLevel = IPPROTO_TCP;
if (optname == WU_TCP_NODELAY)
{
if (optlen != 4)
assert_dbg();
sint32 optvalLE = _swapEndianU32(*(uint32*)optval);
u_long mode = optvalLE; // 1 -> enable, 0 -> disable
if (setsockopt(vs->s, IPPROTO_TCP, TCP_NODELAY, (const char*)&mode, sizeof(u_long)) != 0)
assert_dbg();
}
else
{
cemuLog_logDebug(LogType::Force, "setsockopt(WU_IPPROTO_TCP): Unsupported optname 0x{:08x}", optname);
}
}
else if (level == WU_IPPROTO_IP)
{
hostLevel = IPPROTO_IP;
if (optname == WU_IP_MULTICAST_IF || optname == WU_IP_MULTICAST_TTL ||
optname == WU_IP_MULTICAST_LOOP || optname == WU_IP_ADD_MEMBERSHIP ||
optname == WU_IP_DROP_MEMBERSHIP)
{
cemuLog_logDebug(LogType::Socket, "todo: setsockopt() for multicast");
}
else if(optname == WU_IP_TTL || optname == WU_IP_TOS)
{
cemuLog_logDebug(LogType::Force, "setsockopt(WU_IPPROTO_IP): Unsupported optname 0x{:08x}", optname);
}
else
assert_dbg();
}
else
assert_dbg();
}
osLib_returnFromFunction(hCPU, 0);
}
void nsysnetExport_getsockopt(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "getsockopt({},0x{:x},0x{:05x},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
ppcDefineParamS32(s, 0);
ppcDefineParamS32(level, 1);
ppcDefineParamS32(optname, 2);
ppcDefineParamStr(optval, 3);
ppcDefineParamMPTR(optlenMPTR, 4);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
cemu_assert_debug(false); // todo
return;
}
sint32 r = 0;
// translate level to host API
sint32 hostLevel;
if (level == WU_SOL_SOCKET)
{
hostLevel = SOL_SOCKET;
// handle op
if (optname == WU_SO_LASTERROR)
{
int optvalLE = 0;
socklen_t optlenLE = 4;
r = getsockopt(vs->s, hostLevel, SO_ERROR, (char*)&optvalLE, &optlenLE);
r = _translateError(r, GETLASTERR);
if (memory_readU32(optlenMPTR) != 4)
assert_dbg();
memory_writeU32(optlenMPTR, 4);
if (optvalLE != 0)
assert_dbg(); // todo -> Translate error code/status
*(uint32*)optval = _swapEndianU32(optvalLE);
// YouTube app uses this to check if the connection attempt was successful after non-blocking connect()
}
else if (optname == WU_SO_RCVBUF)
{
int optvalLE = 0;
socklen_t optlenLE = 4;
r = getsockopt(vs->s, hostLevel, SO_RCVBUF, (char*)&optvalLE, &optlenLE);
r = _translateError(r, GETLASTERR);
if (memory_readU32(optlenMPTR) != 4)
assert_dbg();
memory_writeU32(optlenMPTR, 4);
*(uint32*)optval = _swapEndianU32(optvalLE);
// used by Amazon Video app when a video starts playing
}
else if (optname == WU_SO_SNDBUF)
{
int optvalLE = 0;
socklen_t optlenLE = 4;
r = getsockopt(vs->s, hostLevel, SO_SNDBUF, (char*)&optvalLE, &optlenLE);
r = _translateError(r, GETLASTERR);
if (memory_readU32(optlenMPTR) != 4)
assert_dbg();
memory_writeU32(optlenMPTR, 4);
*(uint32*)optval = _swapEndianU32(optvalLE);
// used by Lost Reavers after some loading screens
}
else if (optname == WU_SO_TYPE)
{
if (memory_readU32(optlenMPTR) != 4)
assert_dbg();
int optvalLE = 0;
socklen_t optlenLE = 4;
memory_writeU32(optlenMPTR, 4);
*(uint32*)optval = _swapEndianU32(vs->type);
r = WU_SO_SUCCESS;
}
else if (optname == WU_SO_NONBLOCK)
{
if (memory_readU32(optlenMPTR) != 4)
assert_dbg();
int optvalLE = 0;
socklen_t optlenLE = 4;
memory_writeU32(optlenMPTR, 4);
*(uint32*)optval = _swapEndianU32(vs->isNonBlocking ? 1 : 0);
r = WU_SO_SUCCESS;
}
else
{
cemuLog_logDebug(LogType::Force, "getsockopt(WU_SOL_SOCKET): Unsupported optname 0x{:08x}", optname);
}
}
else
{
cemuLog_logDebug(LogType::Force, "getsockopt(): Unsupported level 0x{:08x}", level);
}
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_inet_aton(PPCInterpreter_t* hCPU)
{
ppcDefineParamStr(ip, 0);
ppcDefineParamStructPtr(addr, wu_in_addr, 1);
cemuLog_log(LogType::Socket, "inet_aton(\"{}\",0x{:08x})", ip, hCPU->gpr[4]);
// _parse_ipad -> todo
sint32 d0, d1, d2, d3;
if (sscanf(ip, "%d.%d.%d.%d", &d0, &d1, &d2, &d3) != 4)
{
cemu_assert_debug(false);
osLib_returnFromFunction(hCPU, 0); // todo - return correct error code
return;
}
if (d0 < 0 || d0 > 255 ||
d1 < 0 || d1 > 255 ||
d2 < 0 || d2 > 255 ||
d3 < 0 || d3 > 255)
{
cemu_assert_debug(false);
osLib_returnFromFunction(hCPU, 0);
return;
}
addr->wu_s_addr = _swapEndianU32((d0 << 24) | (d1 << 16) | (d2 << 8) | (d3 << 0));
osLib_returnFromFunction(hCPU, 1); // 0 -> error, 1 -> success
}
void nsysnetExport_inet_pton(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(af, 0);
ppcDefineParamStr(ip, 1);
ppcDefineParamStructPtr(addr, wu_in_addr, 2);
if (af != 2)
{
cemuLog_log(LogType::Force, "inet_pton() only supports AF_INET");
osLib_returnFromFunction(hCPU, 0);
return;
}
sint32 d0, d1, d2, d3;
bool invalidIp = false;
if (sscanf(ip, "%d.%d.%d.%d", &d0, &d1, &d2, &d3) != 4)
invalidIp = true;
if (d0 < 0 || d0 > 255)
invalidIp = true;
if (d1 < 0 || d1 > 255)
invalidIp = true;
if (d2 < 0 || d2 > 255)
invalidIp = true;
if (d3 < 0 || d3 > 255)
invalidIp = true;
if (invalidIp)
{
cemuLog_log(LogType::Socket, "inet_pton({}, \"{}\", 0x{:08x}) -> Invalid ip", af, ip, hCPU->gpr[5]);
_setSockError(WU_SO_EAFNOSUPPORT);
osLib_returnFromFunction(hCPU, 0); // 0 -> invalid address
return;
}
addr->wu_s_addr = _swapEndianU32((d0 << 24) | (d1 << 16) | (d2 << 8) | (d3 << 0));
cemuLog_log(LogType::Socket, "inet_pton({}, \"{}\", 0x{:08x}) -> Ok", af, ip, hCPU->gpr[5]);
osLib_returnFromFunction(hCPU, 1); // 1 -> success
}
namespace nsysnet
{
const char* inet_ntop(sint32 af, const void* src, char* dst, uint32 size)
{
if( af != WU_AF_INET)
{
// set error
_setSockError(WU_SO_EAFNOSUPPORT);
return nullptr;
}
const uint8* ip = (const uint8*)src;
char buf[32];
sprintf(buf, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
size_t bufLen = strlen(buf);
if( (bufLen+1) > size )
{
// set error
_setSockError(WU_SO_EAFNOSUPPORT);
return nullptr;
}
strcpy(dst, buf);
cemuLog_log(LogType::Socket, "inet_ntop -> {}", buf);
return dst;
}
}
MEMPTR<char> _ntoa_tempString = nullptr;
void nsysnetExport_inet_ntoa(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(addr, wu_in_addr, 0);
cemuLog_log(LogType::Socket, "inet_ntoa(0x{:08x})", hCPU->gpr[3]);
if (_ntoa_tempString == nullptr)
_ntoa_tempString = (char*)memory_getPointerFromVirtualOffset(OSAllocFromSystem(64, 4));
sprintf(_ntoa_tempString.GetPtr(), "%d.%d.%d.%d", ((uint8*)addr)[0], ((uint8*)addr)[1], ((uint8*)addr)[2], ((uint8*)addr)[3]);
osLib_returnFromFunction(hCPU, _ntoa_tempString.GetMPTR());
}
void nsysnetExport_htons(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "htons(0x{:04x})", hCPU->gpr[3]);
ppcDefineParamU32(v, 0);
osLib_returnFromFunction(hCPU, v); // return value as-is
}
void nsysnetExport_htonl(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "htonl(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamU32(v, 0);
osLib_returnFromFunction(hCPU, v); // return value as-is
}
void nsysnetExport_ntohs(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "ntohs(0x{:04x})", hCPU->gpr[3]);
ppcDefineParamU32(v, 0);
osLib_returnFromFunction(hCPU, v); // return value as-is
}
void nsysnetExport_ntohl(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "ntohl(0x{:08x})", hCPU->gpr[3]);
ppcDefineParamU32(v, 0);
osLib_returnFromFunction(hCPU, v); // return value as-is
}
void nsysnetExport_bind(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "bind({},0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamS32(s, 0);
ppcDefineParamStructPtr(addr, struct wu_sockaddr, 1);
ppcDefineParamS32(len, 2);
if (len != sizeof(struct wu_sockaddr))
assert_dbg();
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
}
else
{
if (sizeof(sockaddr) != 16)
assert_dbg();
sockaddr hostAddr;
hostAddr.sa_family = _swapEndianU16(addr->sa_family);
memcpy(hostAddr.sa_data, addr->sa_data, 14);
sint32 hr = bind(vs->s, &hostAddr, sizeof(sockaddr));
r = _translateError(hr, GETLASTERR);
cemuLog_log(LogType::Socket, "bind address: {}.{}.{}.{}:{} result: {}", addr->sa_data[2], addr->sa_data[3], addr->sa_data[4], addr->sa_data[5], _swapEndianU16(*(uint16*)addr->sa_data), hr);
}
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_listen(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "listen({},{})", hCPU->gpr[3], hCPU->gpr[4]);
ppcDefineParamS32(s, 0);
ppcDefineParamS32(queueSize, 1);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
}
else
{
sint32 hr = listen(vs->s, queueSize);
if (hr != 0)
r = -1;
// todo: Set proper coreinit errno (via _setSockError)
}
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_accept(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "accept({},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamS32(s, 0);
ppcDefineParamStructPtr(addr, struct wu_sockaddr, 1);
ppcDefineParamMPTR(lenMPTR, 2);
sint32 r = 0;
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
assert_dbg();
// todo
return;
}
if (memory_readU32(lenMPTR) != 16)
{
cemuLog_log(LogType::Force, "invalid sockaddr len in accept()");
cemu_assert_debug(false);
osLib_returnFromFunction(hCPU, 0);
return;
}
if (vs->isNonBlocking)
{
sockaddr hostAddr;
socklen_t hostLen = sizeof(sockaddr);
SOCKET hr = accept(vs->s, &hostAddr, &hostLen);
if (hr != SOCKET_ERROR)
{
r = nsysnet_createVirtualSocketFromExistingSocket(hr);
_setSockError(WU_SO_SUCCESS);
}
else
{
r = _translateError((sint32)hr, (sint32)GETLASTERR, _ERROR_MODE_ACCEPT);
}
sockaddr_host2guest(&hostAddr, addr);
}
else
{
// blocking accept is not supported yet
cemuLog_log(LogType::Force, "blocking accept() not supported");
cemu_assert_debug(false);
}
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_connect(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "connect({},0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamS32(s, 0);
ppcDefineParamStructPtr(addr, struct wu_sockaddr, 1);
ppcDefineParamS32(len, 2);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
return;
}
if (sizeof(sockaddr) != 16)
assert_dbg();
sockaddr hostAddr;
hostAddr.sa_family = _swapEndianU16(addr->sa_family);
memcpy(hostAddr.sa_data, addr->sa_data, 14);
sint32 hr = connect(vs->s, &hostAddr, sizeof(sockaddr));
cemuLog_log(LogType::Force, "Attempt connect to {}.{}.{}.{}:{}", (sint32)(uint8)hostAddr.sa_data[2], (sint32)(uint8)hostAddr.sa_data[3], (sint32)(uint8)hostAddr.sa_data[4], (sint32)(uint8)hostAddr.sa_data[5], _swapEndianU16(*(uint16*)hostAddr.sa_data+0));
r = _translateError(hr, GETLASTERR, _ERROR_MODE_CONNECT);
osLib_returnFromFunction(hCPU, r);
}
void _setSocketSendRecvNonBlockingMode(SOCKET s, bool isNonBlocking)
{
u_long mode = isNonBlocking ? 1 : 0;
sint32 r = _socket_nonblock(s, mode);
}
void nsysnetExport_send(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "send({},0x{:08x},{},0x{:x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
ppcDefineParamS32(s, 0);
ppcDefineParamStr(msg, 1);
ppcDefineParamS32(len, 2);
ppcDefineParamS32(flags, 3);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
return;
}
int hostFlags = 0;
bool requestIsNonBlocking = (flags&WU_MSG_DONTWAIT) != 0;
flags &= ~WU_MSG_DONTWAIT;
if (requestIsNonBlocking != vs->isNonBlocking && vs->isNonBlocking == false)
assert_dbg();
if (flags)
assert_dbg();
sint32 hr = send(vs->s, msg, len, hostFlags);
cemuLog_log(LogType::Socket, "Sent {} bytes", hr);
_translateError(hr <= 0 ? -1 : 0, GETLASTERR);
r = hr;
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_recv(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "recv({},0x{:08x},{},0x{:x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
ppcDefineParamS32(s, 0);
ppcDefineParamStr(msg, 1);
ppcDefineParamS32(len, 2);
ppcDefineParamS32(flags, 3);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
return;
}
int hostFlags = 0;
bool requestIsNonBlocking = (flags&WU_MSG_DONTWAIT) != 0;
flags &= ~WU_MSG_DONTWAIT;
if (flags&WU_MSG_PEEK)
{
hostFlags |= MSG_PEEK;
flags &= ~WU_MSG_PEEK;
}
if (vs->isNonBlocking)
requestIsNonBlocking = vs->isNonBlocking; // non-blocking sockets always operate in MSG_DONTWAIT mode?
if (flags)
assert_dbg();
if (requestIsNonBlocking != vs->isNonBlocking)
_setSocketSendRecvNonBlockingMode(vs->s, requestIsNonBlocking);
// if blocking, yield thread until there is an error or at least 1 byte was received
if (requestIsNonBlocking == false)
{
_setSocketSendRecvNonBlockingMode(vs->s, true);
while (true)
{
char tempBuffer[1];
sint32 tr = recv(vs->s, tempBuffer, 1, MSG_PEEK);
if (tr == 1)
break;
if (tr == 0)
break; // connection closed
if (tr < 0 && GETLASTERR != WSAEWOULDBLOCK)
break;
// yield thread
coreinit::OSSleepTicks(coreinit::EspressoTime::GetTimerClock() / 5000); // let thread wait 0.2ms to give other threads CPU time
// todo - eventually we should find a way to asynchronously signal recv instead of busy-looping here
}
_setSocketSendRecvNonBlockingMode(vs->s, requestIsNonBlocking);
}
// receive
sint32 hr = recv(vs->s, msg, len, hostFlags);
_translateError(hr <= 0 ? -1 : 0, GETLASTERR);
if (requestIsNonBlocking != vs->isNonBlocking)
_setSocketSendRecvNonBlockingMode(vs->s, vs->isNonBlocking);
cemuLog_log(LogType::Socket, "Received {} bytes", hr);
r = hr;
osLib_returnFromFunction(hCPU, r);
}
struct wu_timeval
{
uint32 tv_sec;
uint32 tv_usec;
};
void _translateFDSet(fd_set* hostSet, struct wu_fd_set* fdset, sint32 nfds, int *hostnfds)
{
FD_ZERO(hostSet);
if (fdset == NULL)
return;
#if BOOST_OS_UNIX
int maxfd;
if(hostnfds)
maxfd = *hostnfds;
else
maxfd = -1;
#endif
uint32 mask = fdset->mask;
for (sint32 i = 0; i < nfds; i++)
{
if( ((mask>>i)&1) == 0 )
continue;
sint32 socketHandle = i;
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(socketHandle);
if(vs == NULL)
continue; // socket invalid
#if BOOST_OS_UNIX
if(vs->s > maxfd)
maxfd = vs->s;
#endif
FD_SET(vs->s, hostSet);
}
#if BOOST_OS_UNIX
if(hostnfds)
*hostnfds = maxfd;
#endif
}
void _translateFDSetRev(struct wu_fd_set* fdset, fd_set* hostSet, sint32 nfds)
{
if (fdset == NULL)
return;
uint32 mask = _swapEndianU32(0);
#if BOOST_OS_WINDOWS
for (sint32 i = 0; i < (sint32)hostSet->fd_count; i++)
{
sint32 virtualSocketHandle = nsysnet_getVirtualSocketHandleFromHostHandle(hostSet->fd_array[i]);
if (virtualSocketHandle < 0)
cemu_assert_debug(false);
mask |= (1<<virtualSocketHandle);
}
#else
for (sint32 i = 0; i < WU_SOCKET_LIMIT; i++)
{
if (virtualSocketTable[i] && virtualSocketTable[i]->s && FD_ISSET(virtualSocketTable[i]->s, hostSet))
mask |= (1 << virtualSocketTable[i]->handle);
}
#endif
fdset->mask = mask;
}
void nsysnetExport_select(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "select({},0x{:08x},0x{:08x},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7]);
ppcDefineParamS32(nfds, 0);
ppcDefineParamStructPtr(readfds, struct wu_fd_set, 1);
ppcDefineParamStructPtr(writefds, struct wu_fd_set, 2);
ppcDefineParamStructPtr(exceptfds, struct wu_fd_set, 3);
ppcDefineParamStructPtr(timeOut, struct wu_timeval, 4);
//cemuLog_log(LogType::Socket, "rm {:08x} wm {:08x} em {:08x}", readfds ? _swapEndianU32(readfds->mask) : 0, writefds ? _swapEndianU32(writefds->mask) : 0, exceptfds ? _swapEndianU32(exceptfds->mask) : 0);
sint32 r = 0;
// translate fd_set
fd_set _readfds, _writefds, _exceptfds;
// handle empty select
if ((readfds == NULL || readfds->mask == 0) && (writefds == NULL || writefds->mask == 0) && (exceptfds == NULL || exceptfds->mask == 0))
{
if (timeOut == NULL || (timeOut->tv_sec == 0 && timeOut->tv_usec == 0))
{
// return immediately
cemuLog_log(LogType::Socket, "select returned immediately because of empty fdsets without timeout");
osLib_returnFromFunction(hCPU, 0);
return;
}
else
{
//// empty select with timeout is not allowed
//_setSockError(WU_SO_EINVAL);
//osLib_returnFromFunction(hCPU, -1);
//cemuLog_log(LogType::Socket, "select returned SO_EINVAL because of empty fdsets with timeout");
// when fd sets are empty but timeout is set, then just wait and do nothing?
// Lost Reavers seems to expect this case to return 0 (it hardcodes empty fd sets and timeout comes from curl_multi_timeout)
timeval tv;
tv.tv_sec = timeOut->tv_sec;
tv.tv_usec = timeOut->tv_usec;
select(0, nullptr, nullptr, nullptr, &tv);
cemuLog_log(LogType::Socket, "select returned 0 because of empty fdsets with timeout");
osLib_returnFromFunction(hCPU, 0);
return;
}
}
timeval tv = { 0 };
if (timeOut == NULL)
{
// return immediately
cemuLog_log(LogType::Socket, "select returned immediately because of null timeout");
osLib_returnFromFunction(hCPU, 0);
return;
}
uint64 msTimeout = (_swapEndianU32(timeOut->tv_usec) / 1000) + (_swapEndianU32(timeOut->tv_sec) * 1000);
uint32 startTime = GetTickCount();
while (true)
{
int hostnfds = -1;
_translateFDSet(&_readfds, readfds, nfds, &hostnfds);
_translateFDSet(&_writefds, writefds, nfds, &hostnfds);
_translateFDSet(&_exceptfds, exceptfds, nfds, &hostnfds);
r = select(hostnfds + 1, readfds ? &_readfds : NULL, writefds ? &_writefds : NULL, exceptfds ? &_exceptfds : NULL, &tv);
if (r < 0)
{
cemuLog_logDebug(LogType::Force, "select() failed");
// timeout
_translateError(r, GETLASTERR);
//_setSockError(WU_SO_SUCCESS);
// in case of error, clear all FD sets (?)
if (readfds)
readfds->mask = 0;
if (writefds)
writefds->mask = 0;
if (exceptfds)
exceptfds->mask = 0;
break;
}
else if (r == 0)
{
// check for timeout
if ((GetTickCount() - startTime) >= msTimeout )
{
// timeout
_setSockError(WU_SO_SUCCESS);
r = 0;
// in case of timeout, clear all FD sets
if (readfds)
readfds->mask = 0;
if (writefds)
writefds->mask = 0;
if (exceptfds)
exceptfds->mask = 0;
break;
}
// yield thread
PPCCore_switchToScheduler();
}
else
{
// cemuLog_log(LogType::Socket, "select returned {}. Read {} Write {} Except {}", r, _readfds.fd_count, _writefds.fd_count, _exceptfds.fd_count);
cemuLog_log(LogType::Socket, "select returned {}.", r);
_translateFDSetRev(readfds, &_readfds, nfds);
_translateFDSetRev(writefds, &_writefds, nfds);
_translateFDSetRev(exceptfds, &_exceptfds, nfds);
break;
}
}
//cemuLog_log(LogType::Force, "selectEndTime {}", timeGetTime());
//extern int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
// struct timeval *timeout);
cemuLog_log(LogType::Socket, "select returned {}", r);
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_getsockname(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "getsockname({},0x{:08x},0x{:08x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5]);
ppcDefineParamS32(s, 0);
ppcDefineParamStructPtr(addr, struct wu_sockaddr, 1);
ppcDefineParamStructPtr(lenPtr, uint32, 2);
sint32 r = 0;
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
assert_dbg();
}
else
{
struct sockaddr hostAddr;
socklen_t hostLen = sizeof(struct sockaddr);
sint32 hr = getsockname(vs->s, &hostAddr, &hostLen);
if (hr == 0)
{
addr->sa_family = _swapEndianU16(hostAddr.sa_family);
memcpy(addr->sa_data, hostAddr.sa_data, 14);
}
else
{
assert_dbg();
}
//sint32 hr = listen(vs->s, queueSize);
//if (hr != 0)
// r = -1;
//// todo: Set proper coreinit errno (via _setSockError)
}
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_getpeername(PPCInterpreter_t* hCPU)
{
ppcDefineParamS32(s, 0);
ppcDefineParamStructPtr(name, struct wu_sockaddr, 1);
ppcDefineParamU32BEPtr(nameLen, 2);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
// todo: Return correct error
osLib_returnFromFunction(hCPU, -1);
return;
}
sockaddr saddr;
socklen_t saddrLen = sizeof(sockaddr);
if (*nameLen < (uint32be)16)
assert_dbg();
sint32 r = getpeername(vs->s, &saddr, &saddrLen);
r = _translateError(r, GETLASTERR);
name->sa_family = _swapEndianU16(saddr.sa_family);
memcpy(name->sa_data, saddr.sa_data, 14);
*nameLen = 16;
osLib_returnFromFunction(hCPU, r);
}
typedef struct
{
MPTR h_name;
MPTR h_aliases;
sint32 h_addrType;
sint32 h_length;
MPTR h_addr_list;
}wu_hostent;
MPTR _allocString(char* str)
{
sint32 len = (sint32)strlen(str);
MPTR strMPTR = coreinit_allocFromSysArea(len+1, 4);
strcpy((char*)memory_getPointerFromVirtualOffset(strMPTR), str);
return strMPTR;
}
void nsysnetExport_gethostbyname(PPCInterpreter_t* hCPU)
{
ppcDefineParamStr(name, 0);
cemuLog_log(LogType::Socket, "gethostbyname(\"{}\")", name);
hostent* he = gethostbyname(name);
if (he == NULL)
{
osLib_returnFromFunction(hCPU, MPTR_NULL);
return;
}
MPTR hostentMPTR = coreinit_allocFromSysArea(sizeof(wu_hostent)*1, 4);
MPTR hostentAddrListMPTR = coreinit_allocFromSysArea(sizeof(MPTR) * 2, 4);
MPTR hostentAddrListEntriesMPTR = coreinit_allocFromSysArea(sizeof(wu_in_addr) * 1, 4);
wu_hostent* wuHostent = (wu_hostent*)memory_getPointerFromVirtualOffset(hostentMPTR);
MPTR* addrList = (MPTR*)memory_getPointerFromVirtualOffset(hostentAddrListMPTR);
wuHostent->h_addrType = _swapEndianU32((uint32)he->h_addrtype);
wuHostent->h_length = _swapEndianU32((uint32)he->h_length);
wuHostent->h_name = _swapEndianU32(_allocString(he->h_name));
wuHostent->h_addr_list = _swapEndianU32(hostentAddrListMPTR);
//memory_writeU32(hostentAddrListEntriesMPTR, _swapEndianU32(*(uint32*)he->h_addr_list[0]));
wu_in_addr* addrListEntries = (wu_in_addr*)memory_getPointerFromVirtualOffset(hostentAddrListEntriesMPTR);
addrListEntries->wu_s_addr = *(uint32*)he->h_addr_list[0]; // address is already in network (big-endian) order
memory_writeU32(hostentAddrListMPTR + 4 * 0, hostentAddrListEntriesMPTR);
memory_writeU32(hostentAddrListMPTR + 4 * 1, MPTR_NULL);
osLib_returnFromFunction(hCPU, hostentMPTR);
return;
}
SysAllocator<wu_hostent> _staticHostent;
SysAllocator<char, 256> _staticHostentName;
SysAllocator<MPTR, 32> _staticHostentPtrList;
SysAllocator<wu_in_addr> _staticHostentEntries;
void nsysnetExport_gethostbyaddr(PPCInterpreter_t* hCPU)
{
ppcDefineParamStr(addr, 0);
ppcDefineParamS32(len, 1);
ppcDefineParamS32(type, 2);
sint32 maxNumEntries = 31;
cemuLog_log(LogType::Socket, "gethostbyaddr(\"{}\", {}, {})", addr, len, type);
hostent* he = gethostbyaddr(addr, len, type);
if (he == nullptr)
{
cemuLog_log(LogType::Socket, "gethostbyaddr(\"{}\", {}, {}) failed", addr, len, type);
osLib_returnFromFunction(hCPU, MPTR_NULL);
return;
}
#ifdef CEMU_DEBUG_ASSERT
if (he->h_addrtype != AF_INET)
assert_dbg();
if (he->h_length != sizeof(in_addr))
assert_dbg();
#endif
wu_hostent* wuHostent = _staticHostent.GetPtr();
// setup wuHostent->h_name
wuHostent->h_name = _swapEndianU32(_staticHostentName.GetMPTR());
if (he->h_name && strlen(he->h_name) < 255)
{
strcpy(_staticHostentName.GetPtr(), he->h_name);
}
else
{
cemuLog_log(LogType::Force, "he->h_name not set or name too long");
strcpy(_staticHostentName.GetPtr(), "");
}
// setup wuHostent address list
wuHostent->h_addrType = _swapEndianU32(WU_AF_INET);
wuHostent->h_addr_list = _swapEndianU32(_staticHostentPtrList.GetMPTR());
wuHostent->h_length = _swapEndianU32(sizeof(wu_in_addr));
for (sint32 i = 0; i < maxNumEntries; i++)
{
if (he->h_addr_list[i] == nullptr)
{
_staticHostentPtrList.GetPtr()[i] = MPTR_NULL;
break;
}
memcpy(_staticHostentEntries.GetPtr() + i, he->h_addr_list[i], sizeof(in_addr));
_staticHostentPtrList.GetPtr()[i] = _swapEndianU32(memory_getVirtualOffsetFromPointer(_staticHostentEntries.GetPtr() + i));
}
_staticHostentPtrList.GetPtr()[31] = MPTR_NULL;
// aliases are ignored for now
wuHostent->h_aliases = MPTR_NULL;
osLib_returnFromFunction(hCPU, _staticHostent.GetMPTR());
return;
}
void nsysnetExport_getaddrinfo(PPCInterpreter_t* hCPU)
{
ppcDefineParamStr(nodeName, 0);
ppcDefineParamStr(serviceName, 1);
ppcDefineParamStructPtr(hints, struct wu_addrinfo, 2);
ppcDefineParamMPTR(results, 3);
cemuLog_log(LogType::Socket, "getaddrinfo(\"{}\",0x{:08x},0x{:08x},0x{:08x})", nodeName, hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
sint32 r = 0;
// todo1: This is really slow. Make it asynchronous
// todo2: Should this set the socket last error code?
struct addrinfo hint = { 0 };
if (hints)
{
hint.ai_family = _swapEndianU32(hints->ai_family);
hint.ai_socktype = _swapEndianU32(hints->ai_socktype);
hint.ai_flags = _swapEndianU32(hints->ai_flags);
hint.ai_protocol = _swapEndianU32(hints->ai_protocol);
}
else
{
hint.ai_family = 0;
hint.ai_socktype = 0;
hint.ai_flags = 0;
hint.ai_protocol = 0;
}
struct addrinfo* result;
sint32 hr = getaddrinfo(nodeName, serviceName, &hint, &result);
if (hr != 0)
{
cemuLog_log(LogType::Socket, "getaddrinfo failed with error {}", hr);
switch (hr)
{
case WSAHOST_NOT_FOUND:
r = WU_SO_ECONNRESET; // todo - verify error code
break;
default:
// unhandled error
cemu_assert_debug(false);
cemuLog_log(LogType::Socket, "getaddrinfo unhandled error code");
r = 1;
break;
}
}
else
{
// count how many results there are
sint32 resultCount = 0;
struct addrinfo* currentAddrInfo = result;
while (currentAddrInfo)
{
resultCount++;
currentAddrInfo = currentAddrInfo->ai_next;
}
if (resultCount == 0)
{
cemu_assert_debug(false);
}
// allocate entries
MPTR addrInfoMPTR = coreinit_allocFromSysArea(sizeof(wu_addrinfo)*resultCount + sizeof(wu_sockaddr)*resultCount, 4);
MPTR addrInfoSockAddrMPTR = addrInfoMPTR + sizeof(wu_addrinfo)*resultCount;
wu_addrinfo* wuAddrInfo = (wu_addrinfo*)memory_getPointerFromVirtualOffset(addrInfoMPTR);
// fill entries
currentAddrInfo = result;
sint32 entryIndex = 0;
wu_addrinfo* previousWuAddrInfo = NULL;
while (currentAddrInfo)
{
if (currentAddrInfo->ai_addrlen != 16)
{
// skip this entry (IPv6)
currentAddrInfo = currentAddrInfo->ai_next;
continue;
}
memset(&wuAddrInfo[entryIndex], 0, sizeof(wu_addrinfo));
// setup pointers
wuAddrInfo[entryIndex].ai_addr = _swapEndianU32(addrInfoSockAddrMPTR + sizeof(wu_sockaddr)*entryIndex);
wuAddrInfo[entryIndex].ai_next = MPTR_NULL;
wuAddrInfo[entryIndex].ai_canonname = _swapEndianU32(MPTR_NULL);
// set ai_next for previous element
if (previousWuAddrInfo)
{
previousWuAddrInfo->ai_next = _swapEndianU32(memory_getVirtualOffsetFromPointer(&wuAddrInfo[entryIndex]));
}
previousWuAddrInfo = &wuAddrInfo[entryIndex];
// fill addrinfo struct
wuAddrInfo[entryIndex].ai_addrlen = _swapEndianU32((uint32)currentAddrInfo->ai_addrlen);
//wuAddrInfo[entryIndex].ai_canonname; todo
wuAddrInfo[entryIndex].ai_family = _swapEndianU32(currentAddrInfo->ai_family);
wuAddrInfo[entryIndex].ai_flags = _swapEndianU32(currentAddrInfo->ai_flags); // todo: These flags might need to be translated
wuAddrInfo[entryIndex].ai_protocol = _swapEndianU32(currentAddrInfo->ai_protocol);
wuAddrInfo[entryIndex].ai_socktype = _swapEndianU32(currentAddrInfo->ai_socktype);
// fill ai_addr
wu_sockaddr* sockAddr = (wu_sockaddr*)memory_getPointerFromVirtualOffset(_swapEndianU32(wuAddrInfo[entryIndex].ai_addr));
sockAddr->sa_family = _swapEndianU16(currentAddrInfo->ai_addr->sa_family);
memcpy(sockAddr->sa_data, currentAddrInfo->ai_addr->sa_data, 14);
// next
entryIndex++;
currentAddrInfo = currentAddrInfo->ai_next;
}
if (entryIndex == 0)
assert_dbg();
// set results
memory_writeU32(results, addrInfoMPTR);
}
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_recvfrom(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "recvfrom({},0x{:08x},{},0x{:x},0x{:x},0x{:x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7], hCPU->gpr[8]);
ppcDefineParamS32(s, 0);
ppcDefineParamStr(msg, 1);
ppcDefineParamS32(len, 2);
ppcDefineParamS32(flags, 3);
ppcDefineParamStructPtr(fromAddr, wu_sockaddr, 4);
ppcDefineParamU32BEPtr(fromLen, 5);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
return;
}
int hostFlags = 0;
bool requestIsNonBlocking = (flags&WU_MSG_DONTWAIT) != 0;
flags &= ~WU_MSG_DONTWAIT;
if (flags&WU_MSG_PEEK)
{
assert_dbg();
hostFlags |= MSG_PEEK;
flags &= ~WU_MSG_PEEK;
}
if (vs->isNonBlocking)
requestIsNonBlocking = vs->isNonBlocking;
sockaddr fromAddrHost;
socklen_t fromLenHost = sizeof(fromAddrHost);
sint32 wsaError = 0;
while( true )
{
// is socket recv shutdown?
if (vs->isShutdownRecv)
{
// return with error
_setSockError(WU_SO_ESHUTDOWN);
osLib_returnFromFunction(hCPU, -1);
return;
}
// use select to check for exceptions and read data
fd_set fd_read;
fd_set fd_exceptions;
FD_ZERO(&fd_read);
FD_ZERO(&fd_exceptions);
FD_SET(vs->s, &fd_read);
FD_SET(vs->s, &fd_exceptions);
timeval t;
t.tv_sec = 0;
t.tv_usec = 0;
int nfds = 0;
#if BOOST_OS_UNIX
nfds = vs->s + 1;
#endif
sint32 count = select(nfds, &fd_read, NULL, &fd_exceptions, &t);
if (count > 0)
{
if (FD_ISSET(vs->s, &fd_exceptions))
{
assert_dbg(); // exception
}
if (FD_ISSET(vs->s, &fd_read))
{
// data available
r = recvfrom(vs->s, msg, len, hostFlags, &fromAddrHost, &fromLenHost);
wsaError = GETLASTERR;
if (r < 0)
cemu_assert_debug(false);
cemuLog_logDebug(LogType::Force, "recvfrom returned {} bytes", r);
// fromAddr and fromLen can be NULL
if (fromAddr && fromLen) {
*fromLen = fromLenHost;
fromAddr->sa_family = _swapEndianU16(fromAddrHost.sa_family);
memcpy(fromAddr->sa_data, fromAddrHost.sa_data, 14);
}
_setSockError(0);
osLib_returnFromFunction(hCPU, r);
return;
}
}
// nothing to do
if (requestIsNonBlocking)
{
// return with error
_setSockError(WU_SO_EWOULDBLOCK);
osLib_returnFromFunction(hCPU, -1);
return;
}
else
{
// pause for a while and check again later
coreinit::OSSleepTicks(ESPRESSO_CORE_CLOCK / 1000); // pause for 1ms
PPCCore_switchToScheduler();
}
}
assert_dbg(); // should no longer be reached
if (requestIsNonBlocking == false)
{
// blocking
_setSocketSendRecvNonBlockingMode(vs->s, true);
while (true)
{
r = recvfrom(vs->s, msg, len, hostFlags, &fromAddrHost, &fromLenHost);
wsaError = GETLASTERR;
if (r < 0)
{
if (wsaError != WSAEWOULDBLOCK)
break;
coreinit::OSSleepTicks(ESPRESSO_CORE_CLOCK/100); // pause for 10ms
PPCCore_switchToScheduler();
continue;
}
assert_dbg();
}
_setSocketSendRecvNonBlockingMode(vs->s, vs->isNonBlocking);
}
else
{
// non blocking
assert_dbg();
}
// fromAddr and fromLen can be NULL
if (fromAddr && fromLen) {
*fromLen = fromLenHost;
fromAddr->sa_family = _swapEndianU16(fromAddrHost.sa_family);
memcpy(fromAddr->sa_data, fromAddrHost.sa_data, 14);
}
_translateError(r <= 0 ? -1 : 0, wsaError);
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_recvfrom_ex(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "recvfrom_ex({},0x{:08x},{},0x{:x},0x{:08x},0x{:08x},0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6], hCPU->gpr[7], hCPU->gpr[8], hCPU->gpr[9], hCPU->gpr[10]);
ppcDefineParamS32(s, 0);
ppcDefineParamStr(msg, 1);
ppcDefineParamS32(len, 2);
ppcDefineParamS32(flags, 3);
ppcDefineParamStructPtr(fromAddr, wu_sockaddr, 4);
ppcDefineParamU32BEPtr(fromLen, 5);
ppcDefineParamUStr(extraData, 6);
ppcDefineParamS32(extraDataLen, 7);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
cemu_assert_debug(false);
return;
}
int hostFlags = 0;
bool requestIsNonBlocking = (flags&WU_MSG_DONTWAIT) != 0;
flags &= ~WU_MSG_DONTWAIT;
if (flags&WU_MSG_PEEK)
{
cemu_assert_debug(false);
hostFlags |= MSG_PEEK;
flags &= ~WU_MSG_PEEK;
}
if (flags & 0x40)
{
// read TTL
if (extraDataLen != 1)
{
cemu_assert_debug(false);
}
extraData[0] = 0x5; // we currently always return 5 as TTL
flags &= ~0x40;
}
if (vs->isNonBlocking)
requestIsNonBlocking = vs->isNonBlocking;
socklen_t fromLenHost = *fromLen;
sockaddr fromAddrHost;
sint32 wsaError = 0;
while (true)
{
// is socket recv shutdown?
if (vs->isShutdownRecv)
{
// return with error
_setSockError(WU_SO_ESHUTDOWN);
osLib_returnFromFunction(hCPU, -1);
return;
}
// use select to check for exceptions and read data
fd_set fd_read;
fd_set fd_exceptions;
FD_ZERO(&fd_read);
FD_ZERO(&fd_exceptions);
FD_SET(vs->s, &fd_read);
FD_SET(vs->s, &fd_exceptions);
timeval t;
t.tv_sec = 0;
t.tv_usec = 0;
int nfds = 0;
#if BOOST_OS_UNIX
nfds = vs->s + 1;
#endif
sint32 count = select(nfds, &fd_read, NULL, &fd_exceptions, &t);
if (count > 0)
{
if (FD_ISSET(vs->s, &fd_exceptions))
{
cemu_assert_debug(false); // exception
}
if (FD_ISSET(vs->s, &fd_read))
{
// data available
r = recvfrom(vs->s, msg, len, hostFlags, &fromAddrHost, &fromLenHost);
wsaError = GETLASTERR;
if (r < 0)
{
cemu_assert_debug(false);
}
*fromLen = fromLenHost;
fromAddr->sa_family = _swapEndianU16(fromAddrHost.sa_family);
memcpy(fromAddr->sa_data, fromAddrHost.sa_data, 14);
_setSockError(0);
osLib_returnFromFunction(hCPU, r);
return;
}
}
// nothing to do
if (requestIsNonBlocking)
{
// return with error
_setSockError(WU_SO_EWOULDBLOCK);
osLib_returnFromFunction(hCPU, -1);
return;
}
else
{
// pause for a while and check again later
coreinit::OSSleepTicks(ESPRESSO_CORE_CLOCK / 100); // pause for 10ms
PPCCore_switchToScheduler();
}
}
cemu_assert_debug(false); // should no longer be reached
}
void _convertSockaddrToHostFormat(wu_sockaddr* sockaddru, sockaddr* sockaddrHost)
{
sockaddrHost->sa_family = _swapEndianU16(sockaddru->sa_family);
memcpy(sockaddrHost->sa_data, sockaddru->sa_data, 14);
}
void nsysnetExport_sendto(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "sendto({},0x{:08x},{},0x{:x})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
ppcDefineParamS32(s, 0);
ppcDefineParamStr(msg, 1);
ppcDefineParamS32(len, 2);
ppcDefineParamS32(flags, 3);
ppcDefineParamStructPtr(toAddr, wu_sockaddr, 4);
ppcDefineParamU32(toLen, 5);
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
sint32 r = 0;
if (vs == NULL)
{
assert_dbg();
return;
}
int hostFlags = 0;
bool requestIsNonBlocking = (flags&WU_MSG_DONTWAIT) != 0;
flags &= ~WU_MSG_DONTWAIT;
if (flags&WU_MSG_PEEK)
{
assert_dbg();
hostFlags |= MSG_PEEK;
flags &= ~WU_MSG_PEEK;
}
if (vs->isNonBlocking)
requestIsNonBlocking = vs->isNonBlocking;
sockaddr toAddrHost;
toAddrHost.sa_family = _swapEndianU16(toAddr->sa_family);
memcpy(toAddrHost.sa_data, toAddr->sa_data, 14);
sint32 wsaError = 0;
if (requestIsNonBlocking == false)
{
// blocking
_setSocketSendRecvNonBlockingMode(vs->s, true);
while (true)
{
r = sendto(vs->s, msg, len, hostFlags, &toAddrHost, toLen);
wsaError = GETLASTERR;
if (r < 0)
{
if (wsaError != WSAEWOULDBLOCK)
break;
coreinit::OSSleepTicks(ESPRESSO_CORE_CLOCK / 100); // pause for 10ms
PPCCore_switchToScheduler();
continue;
}
break;
}
_setSocketSendRecvNonBlockingMode(vs->s, vs->isNonBlocking);
}
else
{
// non blocking
_setSocketSendRecvNonBlockingMode(vs->s, true);
r = sendto(vs->s, msg, len, hostFlags, &toAddrHost, toLen);
wsaError = GETLASTERR;
_setSocketSendRecvNonBlockingMode(vs->s, vs->isNonBlocking);
}
_translateError(r <= 0 ? -1 : 0, wsaError);
osLib_returnFromFunction(hCPU, r);
}
void nsysnetExport_sendto_multi(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "sendto_multi({},0x{:08x},0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
ppcDefineParamS32(s, 0);
ppcDefineParamStr(data, 1);
ppcDefineParamS32(dataLen, 2);
ppcDefineParamU32(flags, 3);
ppcDefineParamStructPtr(destinationArray, wu_sockaddr, 4);
ppcDefineParamU32(destinationCount, 5);
if (flags != 0)
assert_dbg();
// todo - somehow handle non-blocking
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
assert_dbg();
return;
}
for (uint32 i = 0; i < destinationCount; i++)
{
sockaddr destinationHost;
_convertSockaddrToHostFormat(&destinationArray[i], &destinationHost);
sint32 r = sendto(vs->s, (char*)data, (int)dataLen, 0, &destinationHost, sizeof(sockaddr));
if (r < dataLen)
assert_dbg(); // todo
}
// success
_setSockError(0);
osLib_returnFromFunction(hCPU, dataLen);
}
typedef struct
{
MEMPTR<uint8> data;
uint32be dataLen;
MEMPTR<uint32be> sendLenArray;
uint32be sendLenArraySize;
MEMPTR<wu_sockaddr> destArray;
uint32be destArraySize;
MEMPTR<uint32be> resultArray;
uint32be resultArrayLen;
}sendtomultiBuffer_t;
void nsysnetExport_sendto_multi_ex(PPCInterpreter_t* hCPU)
{
cemuLog_log(LogType::Socket, "sendto_multi_ex({},0x{:08x},0x{:08x},{})", hCPU->gpr[3], hCPU->gpr[4], hCPU->gpr[5], hCPU->gpr[6]);
ppcDefineParamS32(s, 0);
ppcDefineParamU32(flags, 1);
ppcDefineParamStructPtr(multiBuf, sendtomultiBuffer_t, 2);
ppcDefineParamU32(num, 3);
assert_dbg(); // todo - needs testing
virtualSocket_t* vs = nsysnet_getVirtualSocketObject(s);
if (vs == NULL)
{
assert_dbg();
return;
}
// todo - lots of validation for multiBuf parameters (pointers must not be null and must be aligned, lens must be padded to alignment too)
// verify multiBuf
if ((uint32)multiBuf->sendLenArraySize < num ||
(uint32)multiBuf->destArraySize < num ||
(uint32)multiBuf->resultArrayLen < num )
{
cemu_assert_debug(false);
}
for (uint32 i = 0; i < num; i++)
{
multiBuf->resultArray[i] = 0;
}
uint8* data = multiBuf->data.GetPtr();
sint32 sendLenSum = 0;
for (uint32 i = 0; i < num; i++)
{
sockaddr destination;
_convertSockaddrToHostFormat(&multiBuf->destArray[i], &destination);
uint32 sendLen = (uint32)(multiBuf->sendLenArray[i]);
sint32 r = sendto(vs->s, (char*)data, (int)sendLen, 0, &destination, sizeof(sockaddr));
if (r < (sint32)sendLen)
cemu_assert_debug(false);
else
multiBuf->resultArray[i] = r;
data += sendLen;
sendLenSum += sendLenSum;
}
osLib_returnFromFunction(hCPU, sendLenSum); // return value correct?
}
namespace nsysnet
{
std::vector<NSSLInternalState_t> g_nsslInternalStates;
NSSLInternalState_t* GetNSSLContext(sint32 index)
{
if (g_nsslInternalStates.size() <= index)
return nullptr;
if (g_nsslInternalStates[index].destroyed)
cemu_assert_suspicious();
return &g_nsslInternalStates[index];
}
void export_NSSLCreateContext(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(version, 0);
NSSLInternalState_t ssl = {};
ssl.sslVersion = version;
g_nsslInternalStates.push_back(ssl);
uint32 nsslHandle = (uint32)g_nsslInternalStates.size() - 1;
cemuLog_logDebug(LogType::Force, "NSSLCreateContext(0x{:x}) -> 0x{:x}", version, nsslHandle);
osLib_returnFromFunction(hCPU, nsslHandle);
}
void export_NSSLSetClientPKI(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(nsslHandle, 0);
ppcDefineParamU32(clientPKI, 1);
cemuLog_logDebug(LogType::Force, "NSSLSetClientPKI(0x{:x}, 0x{:x})", nsslHandle, clientPKI);
if (g_nsslInternalStates.size() <= nsslHandle || g_nsslInternalStates[nsslHandle].destroyed)
{
osLib_returnFromFunction(hCPU, NSSL_INVALID_CTX);
return;
}
g_nsslInternalStates[nsslHandle].clientPKI = clientPKI;
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void export_NSSLAddServerPKI(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(nsslHandle, 0);
ppcDefineParamU32(serverPKI, 1);
cemuLog_logDebug(LogType::Force, "NSSLAddServerPKI(0x{:x}, 0x{:x})", nsslHandle, serverPKI);
if (g_nsslInternalStates.size() <= nsslHandle || g_nsslInternalStates[nsslHandle].destroyed)
{
osLib_returnFromFunction(hCPU, NSSL_INVALID_CTX);
return;
}
g_nsslInternalStates[nsslHandle].serverPKIs.insert(serverPKI);
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void export_NSSLAddServerPKIExternal(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(nsslHandle, 0);
ppcDefineParamMEMPTR(certData, uint8, 1);
ppcDefineParamS32(certLen, 2);
ppcDefineParamS32(certType, 3);
cemuLog_logDebug(LogType::Force, "NSSLAddServerPKIExternal(0x{:x}, 0x{:08x}, 0x{:x}, {})", nsslHandle, certData.GetMPTR(), certLen, certType);
if (g_nsslInternalStates.size() <= nsslHandle || g_nsslInternalStates[nsslHandle].destroyed)
{
osLib_returnFromFunction(hCPU, NSSL_INVALID_CTX);
return;
}
g_nsslInternalStates[nsslHandle].serverCustomPKIs.push_back(std::vector<uint8>(certData.GetPtr(), certData.GetPtr()+certLen));
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void export_NSSLAddServerPKIGroups(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(nsslHandle, 0);
ppcDefineParamU32(groupMask, 1);
ppcDefineParamMEMPTR(validCountOut, sint32, 2);
ppcDefineParamMEMPTR(invalidCountOut, sint32, 3);
cemuLog_logDebug(LogType::Force, "NSSLAddServerPKIGroups(0x{:x}, 0x{:x}, 0x{:08x}, 0x{:08x})", nsslHandle, groupMask, validCountOut.GetMPTR(), invalidCountOut.GetMPTR());
if (g_nsslInternalStates.size() <= nsslHandle || g_nsslInternalStates[nsslHandle].destroyed)
{
osLib_returnFromFunction(hCPU, NSSL_INVALID_CTX);
return;
}
if (HAS_FLAG(groupMask, 1))
{
g_nsslInternalStates[nsslHandle].serverPKIs.insert({ 100,101,102,103,104,105 });
}
if (HAS_FLAG(groupMask, 2))
{
g_nsslInternalStates[nsslHandle].serverPKIs.insert({
1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009,
1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019,
1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029,
1030, 1031, 1032, 1033 });
}
if (validCountOut)
*validCountOut = (sint32)g_nsslInternalStates[nsslHandle].serverPKIs.size();
if (invalidCountOut)
*invalidCountOut = 0;
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void export_NSSLDestroyContext(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(nsslHandle, 0);
cemuLog_logDebug(LogType::Force, "NSSLDestroyContext(0x{:x})", nsslHandle);
if (g_nsslInternalStates.size() <= nsslHandle || g_nsslInternalStates[nsslHandle].destroyed)
{
osLib_returnFromFunction(hCPU, NSSL_INVALID_CTX);
return;
}
g_nsslInternalStates[nsslHandle].destroyed = true;
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void export_NSSLExportInternalServerCertificate(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(serverCertId, 0);
ppcDefineParamUStr(output, 1);
ppcDefineParamU32BEPtr(outputSize, 2);
ppcDefineParamU32BEPtr(certType, 3);
sint32 certificateSize = 0;
uint8* certificateData = iosuCrypto_getCertificateDataById(serverCertId, &certificateSize);
if (certificateData == nullptr)
{
cemu_assert_debug(false);
}
if( output )
memcpy(output, certificateData, certificateSize);
*outputSize = (uint32)certificateSize;
*certType = 0;
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void export_NSSLExportInternalClientCertificate(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(serverCertId, 0);
ppcDefineParamUStr(output, 1);
ppcDefineParamU32BEPtr(outputSize, 2);
ppcDefineParamU32BEPtr(certType, 3);
ppcDefineParamUStr(pkeyOutput, 4);
ppcDefineParamU32BEPtr(pkeyOutputSize, 5);
ppcDefineParamU32BEPtr(pkeyCertType, 6);
// certificate
sint32 certificateSize = 0;
uint8* certificateData = iosuCrypto_getCertificateDataById(serverCertId, &certificateSize);
if (certificateData == nullptr)
{
assert_dbg(); // todo
}
if (output)
memcpy(output, certificateData, certificateSize);
*outputSize = (uint32)certificateSize;
*certType = 0;
// private key
sint32 pkeySize = 0;
uint8* pkeyData = iosuCrypto_getCertificatePrivateKeyById(serverCertId, &pkeySize);
if (pkeyData == nullptr)
{
assert_dbg(); // todo
}
if (pkeyOutput)
memcpy(pkeyOutput, pkeyData, pkeySize);
*pkeyOutputSize = (uint32)pkeySize;
*pkeyCertType = 0;
osLib_returnFromFunction(hCPU, NSSL_OK);
}
void wuResetFD(struct wu_fd_set* fdset)
{
fdset->mask = 0;
}
void wuSetFD(struct wu_fd_set* fdset, sint32 fd)
{
fdset->mask |= (1 << fd);
}
}
namespace nsysnet
{
void Initialize()
{
cafeExportRegister("nsysnet", inet_ntop, LogType::Socket);
}
}
// register nsysnet functions
void nsysnet_load()
{
nsysnet::Initialize();
// the below code is the old way of registering API which is deprecated
osLib_addFunction("nsysnet", "socket_lib_init", nsysnetExport_socket_lib_init);
osLib_addFunction("nsysnet", "socket_lib_finish", nsysnetExport_socket_lib_finish);
// socket API
osLib_addFunction("nsysnet", "socket", nsysnetExport_socket);
osLib_addFunction("nsysnet", "mw_socket", nsysnetExport_mw_socket);
osLib_addFunction("nsysnet", "shutdown", nsysnetExport_shutdown);
osLib_addFunction("nsysnet", "socketclose", nsysnetExport_socketclose);
osLib_addFunction("nsysnet", "setsockopt", nsysnetExport_setsockopt);
osLib_addFunction("nsysnet", "getsockopt", nsysnetExport_getsockopt);
osLib_addFunction("nsysnet", "bind", nsysnetExport_bind);
osLib_addFunction("nsysnet", "listen", nsysnetExport_listen);
osLib_addFunction("nsysnet", "accept", nsysnetExport_accept);
osLib_addFunction("nsysnet", "connect", nsysnetExport_connect);
osLib_addFunction("nsysnet", "send", nsysnetExport_send);
osLib_addFunction("nsysnet", "recv", nsysnetExport_recv);
osLib_addFunction("nsysnet", "select", nsysnetExport_select);
osLib_addFunction("nsysnet", "getsockname", nsysnetExport_getsockname);
osLib_addFunction("nsysnet", "getpeername", nsysnetExport_getpeername);
osLib_addFunction("nsysnet", "inet_aton", nsysnetExport_inet_aton);
osLib_addFunction("nsysnet", "inet_pton", nsysnetExport_inet_pton);
osLib_addFunction("nsysnet", "inet_ntoa", nsysnetExport_inet_ntoa);
osLib_addFunction("nsysnet", "htons", nsysnetExport_htons);
osLib_addFunction("nsysnet", "htonl", nsysnetExport_htonl);
osLib_addFunction("nsysnet", "ntohs", nsysnetExport_ntohs);
osLib_addFunction("nsysnet", "ntohl", nsysnetExport_ntohl);
osLib_addFunction("nsysnet", "gethostbyname", nsysnetExport_gethostbyname);
osLib_addFunction("nsysnet", "gethostbyaddr", nsysnetExport_gethostbyaddr);
osLib_addFunction("nsysnet", "getaddrinfo", nsysnetExport_getaddrinfo);
osLib_addFunction("nsysnet", "socketlasterr", nsysnetExport_socketlasterr);
// unfinished implementations
osLib_addFunction("nsysnet", "recvfrom", nsysnetExport_recvfrom);
osLib_addFunction("nsysnet", "recvfrom_ex", nsysnetExport_recvfrom_ex);
osLib_addFunction("nsysnet", "sendto", nsysnetExport_sendto);
osLib_addFunction("nsysnet", "sendto_multi", nsysnetExport_sendto_multi);
osLib_addFunction("nsysnet", "sendto_multi_ex", nsysnetExport_sendto_multi_ex);
// NSSL API
osLib_addFunction("nsysnet", "NSSLCreateContext", nsysnet::export_NSSLCreateContext);
osLib_addFunction("nsysnet", "NSSLSetClientPKI", nsysnet::export_NSSLSetClientPKI);
osLib_addFunction("nsysnet", "NSSLAddServerPKI", nsysnet::export_NSSLAddServerPKI);
osLib_addFunction("nsysnet", "NSSLAddServerPKIExternal", nsysnet::export_NSSLAddServerPKIExternal);
osLib_addFunction("nsysnet", "NSSLAddServerPKIGroups", nsysnet::export_NSSLAddServerPKIGroups);
osLib_addFunction("nsysnet", "NSSLDestroyContext", nsysnet::export_NSSLDestroyContext);
osLib_addFunction("nsysnet", "NSSLExportInternalServerCertificate", nsysnet::export_NSSLExportInternalServerCertificate);
osLib_addFunction("nsysnet", "NSSLExportInternalClientCertificate", nsysnet::export_NSSLExportInternalClientCertificate);
}
| 62,923
|
C++
|
.cpp
| 2,010
| 28.441294
| 256
| 0.70941
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,083
|
nn_ac.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_ac/nn_ac.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/nn_common.h"
#include "nn_ac.h"
#if BOOST_OS_WINDOWS
#include <iphlpapi.h>
#endif
// AC lib (manages internet connection)
enum class AC_STATUS : uint32
{
FAILED = (uint32)-1,
OK = 0,
};
static_assert(TRUE == 1, "TRUE not 1");
void _GetLocalIPAndSubnetMaskFallback(uint32& localIp, uint32& subnetMask)
{
// default to some hardcoded values
localIp = (192 << 24) | (168 << 16) | (0 << 8) | (100 << 0);
subnetMask = (255 << 24) | (255 << 16) | (255 << 8) | (0 << 0);
}
#if BOOST_OS_WINDOWS
void _GetLocalIPAndSubnetMask(uint32& localIp, uint32& subnetMask)
{
std::vector<IP_ADAPTER_ADDRESSES> buf_adapter_addresses;
buf_adapter_addresses.resize(32);
DWORD buf_size;
DWORD r;
for (uint32 i = 0; i < 6; i++)
{
buf_size = (uint32)(buf_adapter_addresses.size() * sizeof(IP_ADAPTER_ADDRESSES));
r = GetAdaptersAddresses(AF_INET, GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_INCLUDE_GATEWAYS, nullptr, buf_adapter_addresses.data(), &buf_size);
if (r != ERROR_BUFFER_OVERFLOW)
break;
buf_adapter_addresses.resize(buf_adapter_addresses.size() * 2);
}
if (r != ERROR_SUCCESS)
{
cemuLog_log(LogType::Force, "Failed to acquire local IP and subnet mask");
_GetLocalIPAndSubnetMaskFallback(localIp, subnetMask);
return;
}
IP_ADAPTER_ADDRESSES* currentAddress = buf_adapter_addresses.data();
while (currentAddress)
{
if (currentAddress->OperStatus != IfOperStatusUp)
{
currentAddress = currentAddress->Next;
continue;
}
if (!currentAddress->FirstUnicastAddress || !currentAddress->FirstUnicastAddress->Address.lpSockaddr)
{
currentAddress = currentAddress->Next;
continue;
}
if (!currentAddress->FirstGatewayAddress)
{
currentAddress = currentAddress->Next;
continue;
}
SOCKADDR* sockAddr = currentAddress->FirstUnicastAddress->Address.lpSockaddr;
if (sockAddr->sa_family == AF_INET)
{
ULONG mask = 0;
if (ConvertLengthToIpv4Mask(currentAddress->FirstUnicastAddress->OnLinkPrefixLength, &mask) != NO_ERROR)
mask = 0;
sockaddr_in* inAddr = (sockaddr_in*)sockAddr;
localIp = _byteswap_ulong(inAddr->sin_addr.S_un.S_addr);
subnetMask = _byteswap_ulong(mask);
return;
}
currentAddress = currentAddress->Next;
}
cemuLog_logDebug(LogType::Force, "_GetLocalIPAndSubnetMask(): Failed to find network IP and subnet mask");
_GetLocalIPAndSubnetMaskFallback(localIp, subnetMask);
}
#else
void _GetLocalIPAndSubnetMask(uint32& localIp, uint32& subnetMask)
{
cemuLog_logDebug(LogType::Force, "_GetLocalIPAndSubnetMask(): Not implemented");
_GetLocalIPAndSubnetMaskFallback(localIp, subnetMask);
}
#endif
void nnAcExport_GetAssignedAddress(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetAssignedAddress() called");
ppcDefineParamU32BEPtr(ipAddrOut, 0);
uint32 localIp;
uint32 subnetMask;
_GetLocalIPAndSubnetMask(localIp, subnetMask);
*ipAddrOut = localIp;
const uint32 nnResultCode = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
osLib_returnFromFunction(hCPU, nnResultCode);
}
void nnAcExport_GetAssignedSubnet(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "GetAssignedSubnet() called");
ppcDefineParamU32BEPtr(subnetMaskOut, 0);
uint32 localIp;
uint32 subnetMask;
_GetLocalIPAndSubnetMask(localIp, subnetMask);
*subnetMaskOut = subnetMask;
const uint32 nnResultCode = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
osLib_returnFromFunction(hCPU, nnResultCode);
}
void nnAcExport_ACGetAssignedAddress(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32BEPtr(ipAddrOut, 0);
uint32 localIp;
uint32 subnetMask;
_GetLocalIPAndSubnetMask(localIp, subnetMask);
*ipAddrOut = localIp;
const uint32 nnResultCode = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
osLib_returnFromFunction(hCPU, nnResultCode);
}
void nnAcExport_IsSystemConnected(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(isConnectedOut, uint8, 0);
ppcDefineParamTypePtr(apTypeOut, uint32be, 1);
cemuLog_logDebug(LogType::Force, "nn_ac.IsSystemConnected() - placeholder");
*apTypeOut = 0; // ukn
*isConnectedOut = 1;
osLib_returnFromFunction(hCPU, 0);
}
void nnAcExport_IsConfigExisting(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "nn_ac.IsConfigExisting() - placeholder");
ppcDefineParamU32(configId, 0);
ppcDefineParamTypePtr(isConfigExisting, uint8, 1);
*isConfigExisting = 0;
osLib_returnFromFunction(hCPU, 0);
}
namespace nn_ac
{
nnResult Initialize()
{
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
}
nnResult ConnectAsync()
{
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
}
nnResult IsApplicationConnected(uint8be* connected)
{
if (connected)
*connected = TRUE;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
}
uint32 Connect()
{
// Terraria expects this (or GetLastErrorCode) to return 0 on success
// investigate on the actual console
// maybe all success codes are always 0 and dont have any of the other fields set?
uint32 nnResultCode = 0;// BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0); // Splatoon freezes if this function fails?
return nnResultCode;
}
nnResult GetConnectStatus(betype<AC_STATUS>* status)
{
if (status)
*status = AC_STATUS::OK;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
}
nnResult GetStatus(betype<AC_STATUS>* status)
{
return GetConnectStatus(status);
}
nnResult GetLastErrorCode(uint32be* errorCode)
{
if (errorCode)
*errorCode = 0;
return BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
}
nnResult GetConnectResult(uint32be* connectResult)
{
const uint32 nnResultCode = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_AC, 0);
if (connectResult)
*connectResult = nnResultCode;
return nnResultCode;
}
static_assert(sizeof(betype<AC_STATUS>) == 4);
static_assert(sizeof(betype<nnResult>) == 4);
nnResult ACInitialize()
{
return Initialize();
}
bool ACIsSuccess(betype<nnResult>* r)
{
return NN_RESULT_IS_SUCCESS(*r) ? 1 : 0;
}
bool ACIsFailure(betype<nnResult>* r)
{
return NN_RESULT_IS_FAILURE(*r) ? 1 : 0;
}
nnResult ACGetConnectStatus(betype<AC_STATUS>* connectionStatus)
{
return GetConnectStatus(connectionStatus);
}
nnResult ACGetStatus(betype<AC_STATUS>* connectionStatus)
{
return GetStatus(connectionStatus);
}
nnResult ACConnectAsync()
{
return ConnectAsync();
}
nnResult ACIsApplicationConnected(uint32be* connectedU32)
{
uint8be connected = 0;
nnResult r = IsApplicationConnected(&connected);
*connectedU32 = connected; // convert to uint32
return r;
}
void load()
{
cafeExportRegisterFunc(Initialize, "nn_ac", "Initialize__Q2_2nn2acFv", LogType::Placeholder);
cafeExportRegisterFunc(Connect, "nn_ac", "Connect__Q2_2nn2acFv", LogType::Placeholder);
cafeExportRegisterFunc(ConnectAsync, "nn_ac", "ConnectAsync__Q2_2nn2acFv", LogType::Placeholder);
cafeExportRegisterFunc(GetConnectResult, "nn_ac", "GetConnectResult__Q2_2nn2acFPQ2_2nn6Result", LogType::Placeholder);
cafeExportRegisterFunc(GetLastErrorCode, "nn_ac", "GetLastErrorCode__Q2_2nn2acFPUi", LogType::Placeholder);
cafeExportRegisterFunc(GetConnectStatus, "nn_ac", "GetConnectStatus__Q2_2nn2acFPQ3_2nn2ac6Status", LogType::Placeholder);
cafeExportRegisterFunc(GetStatus, "nn_ac", "GetStatus__Q2_2nn2acFPQ3_2nn2ac6Status", LogType::Placeholder);
cafeExportRegisterFunc(IsApplicationConnected, "nn_ac", "IsApplicationConnected__Q2_2nn2acFPb", LogType::Placeholder);
// AC also offers C-style wrappers
cafeExportRegister("nn_ac", ACInitialize, LogType::Placeholder);
cafeExportRegister("nn_ac", ACIsSuccess, LogType::Placeholder);
cafeExportRegister("nn_ac", ACIsFailure, LogType::Placeholder);
cafeExportRegister("nn_ac", ACGetConnectStatus, LogType::Placeholder);
cafeExportRegister("nn_ac", ACGetStatus, LogType::Placeholder);
cafeExportRegister("nn_ac", ACConnectAsync, LogType::Placeholder);
cafeExportRegister("nn_ac", ACIsApplicationConnected, LogType::Placeholder);
}
}
void nnAc_load()
{
osLib_addFunction("nn_ac", "GetAssignedAddress__Q2_2nn2acFPUl", nnAcExport_GetAssignedAddress);
osLib_addFunction("nn_ac", "GetAssignedSubnet__Q2_2nn2acFPUl", nnAcExport_GetAssignedSubnet);
osLib_addFunction("nn_ac", "IsSystemConnected__Q2_2nn2acFPbPQ3_2nn2ac6ApType", nnAcExport_IsSystemConnected);
osLib_addFunction("nn_ac", "IsConfigExisting__Q2_2nn2acFQ3_2nn2ac11ConfigIdNumPb", nnAcExport_IsConfigExisting);
osLib_addFunction("nn_ac", "ACGetAssignedAddress", nnAcExport_ACGetAssignedAddress);
nn_ac::load();
}
| 8,753
|
C++
|
.cpp
| 239
| 34.154812
| 166
| 0.769149
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,084
|
nn_save.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_save/nn_save.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "gui/wxgui.h"
#include "nn_save.h"
#include "Cafe/OS/libs/nn_acp/nn_acp.h"
#include "Cafe/OS/libs/nn_act/nn_act.h"
#include <filesystem>
#include <sstream>
#include "config/ActiveSettings.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_FS.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/Filesystem/fsc.h"
#define SAVE_STATUS_OK ((FSStatus)FS_RESULT::SUCCESS)
#define SAVE_MAX_PATH_SIZE (FSA_CMD_PATH_MAX_LENGTH)
#define SAVE_ACCOUNT_ID_MIN (1)
#define SAVE_ACCOUNT_ID_MAX (0xC)
#define SAVE_UNIQUE_TO_TITLE_ID(_unique_) (((((uint64)_unique_ >> 24ULL) | 0x50000) << 32ULL) | ((_unique_ << 8) | 0x10000000))
#define SAVE_UNIQUE_TO_TITLE_ID_VARIATION(_unique_,_variation_) (((((uint64)_unique_ >> 24ULL) | 0x50000 ) << 32) | ((_unique_ << 8) | 0x10000000 | _variation_))
#define SAVE_UNIQUE_DEMO_TO_TITLE_ID(_unique_) (((((uint64)_unique_ >> 24ULL) | 0x50002) << 32ULL) | ((_unique_ << 8) | 0x10000000))
#define SAVE_UNIQUE_DEMO_TO_TITLE_ID_VARIATION(_unique_,_variation_) (((((uint64)_unique_ >> 24ULL) | 0x50002 ) << 32ULL) | ((_unique_ << 8) | 0x10000000 | _variation_))
namespace nn
{
namespace save
{
typedef FSStatus SAVEStatus;
typedef struct
{
bool initialized;
coreinit::OSMutex mutex;
coreinit::FSClient_t fsClient;
coreinit::FSCmdBlock_t fsCmdBlock;
uint32 persistentIdCache[0xC];
}nn_save_t;
SysAllocator<nn_save_t> g_nn_save;
uint32 GetPersistentIdFromLocalCache(uint8 accountSlot)
{
accountSlot--;
if (accountSlot >= 0xC)
return 0;
return g_nn_save->persistentIdCache[accountSlot];
}
void SetPersistentIdToLocalCache(uint8 accountSlot, uint32 persistentId)
{
accountSlot--;
if (accountSlot >= 0xC)
return;
g_nn_save->persistentIdCache[accountSlot] = persistentId;
}
bool GetPersistentIdEx(uint8 accountSlot, uint32* persistentId)
{
if (accountSlot == 0xFF)
{
*persistentId = 0;
return true;
}
const uint32 result = GetPersistentIdFromLocalCache(accountSlot);
*persistentId = result;
return result != 0;
}
bool GetCurrentTitleApplicationBox(nn::acp::ACPDeviceType* deviceType)
{
if (deviceType)
{
*deviceType = nn::acp::ACPDeviceType::InternalDeviceType;
return true;
}
return false;
}
void UpdateSaveTimeStamp(uint32 persistentId)
{
nn::acp::ACPDeviceType deviceType;
if (GetCurrentTitleApplicationBox(&deviceType))
ACPUpdateSaveTimeStamp(persistentId, CafeSystem::GetForegroundTitleId(), deviceType);
}
SAVEStatus ConvertACPToSaveStatus(acp::ACPStatus status)
{
cemu_assert_debug(status == 0); // todo
return 0;
}
bool GetAbsoluteFullPath(uint32 persistentId, const char* subDir, char* outPath)
{
int size;
if (persistentId != 0)
{
if (subDir)
size = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/save/%08x/%s", persistentId, subDir);
else
size = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/save/%08x/", persistentId);
}
else
{
if (subDir)
size = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/save/common/%s", subDir);
else
size = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/save/common/");
}
if (size < SAVE_MAX_PATH_SIZE - 1)
return true;
return false;
}
FS_RESULT GetAbsoluteFullPathOtherApplication(uint32 persistentId, uint64 titleId, const char* subDir, char* outPath)
{
uint32be applicationBox;
if(acp::ACPGetApplicationBox(&applicationBox, titleId) != acp::ACPStatus::SUCCESS)
return FS_RESULT::NOT_FOUND;
sint32 written = 0;
if(applicationBox == 3)
{
if(persistentId != 0)
{
if (subDir)
written = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/storage_mlc01/usr/save/%08x/%08x/user/%08x/%s",
GetTitleIdHigh(titleId), GetTitleIdLow(titleId), persistentId, subDir);
else
written = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/storage_mlc01/usr/save/%08x/%08x/user/%08x/",
GetTitleIdHigh(titleId), GetTitleIdLow(titleId), persistentId);
}
else
{
if (subDir)
written = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/storage_mlc01/usr/save/%08x/%08x/user/common/%s",
GetTitleIdHigh(titleId), GetTitleIdLow(titleId), subDir);
else
written = snprintf(outPath, SAVE_MAX_PATH_SIZE - 1, "/vol/storage_mlc01/usr/save/%08x/%08x/user/common/",
GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
}
}
else if(applicationBox == 4)
{
cemu_assert_unimplemented();
}
else
return FS_RESULT::NOT_FOUND;
if (written < SAVE_MAX_PATH_SIZE - 1)
return FS_RESULT::SUCCESS;
cemu_assert_suspicious();
return FS_RESULT::FATAL_ERROR;
}
struct AsyncResultData
{
MEMPTR<coreinit::OSEvent> event;
betype<SAVEStatus> returnStatus;
};
void SaveAsyncFinishCallback(PPCInterpreter_t* hCPU);
struct AsyncToSyncWrapper : public FSAsyncParams
{
AsyncToSyncWrapper()
{
coreinit::OSInitEvent(&_event, coreinit::OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, coreinit::OSEvent::EVENT_MODE::MODE_AUTO);
ioMsgQueue = nullptr;
userContext = &_result;
userCallback = RPLLoader_MakePPCCallable(SaveAsyncFinishCallback);
_result.returnStatus = 0;
_result.event = &_event;
}
~AsyncToSyncWrapper()
{
}
FSAsyncParams* GetAsyncParams()
{
return this;
}
SAVEStatus GetResult()
{
return _result.returnStatus;
}
void WaitForEvent()
{
coreinit::OSWaitEvent(&_event);
}
private:
coreinit::OSEvent _event;
AsyncResultData _result;
};
void SaveAsyncFinishCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamMEMPTR(client, coreinit::FSClient_t, 0);
ppcDefineParamMEMPTR(block, coreinit::FSCmdBlock_t, 1);
ppcDefineParamU32(returnStatus, 2);
ppcDefineParamMEMPTR(userContext, void, 3);
MEMPTR<AsyncResultData> resultPtr{ userContext };
resultPtr->returnStatus = returnStatus;
coreinit::OSSignalEvent(resultPtr->event);
osLib_returnFromFunction(hCPU, 0);
}
SAVEStatus SAVEMountSaveDir()
{
acp::ACPStatus status = acp::ACPMountSaveDir();
return ConvertACPToSaveStatus(status);
}
SAVEStatus SAVEUnmountSaveDir()
{
return ConvertACPToSaveStatus(acp::ACPUnmountSaveDir());
}
void _CheckAndMoveLegacySaves()
{
const uint64 titleId = CafeSystem::GetForegroundTitleId();
fs::path targetPath, sourcePath;
try
{
bool copiedUser = false, copiedCommon = false;
const auto sourceSavePath = ActiveSettings::GetMlcPath("emulatorSave/{:08x}", CafeSystem::GetRPXHashBase());
sourcePath = sourceSavePath;
if (fs::exists(sourceSavePath) && is_directory(sourceSavePath))
{
targetPath = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/{:08x}", GetTitleIdHigh(titleId), GetTitleIdLow(titleId), 0x80000001);
fs::create_directories(targetPath);
copy(sourceSavePath, targetPath, fs::copy_options::overwrite_existing | fs::copy_options::recursive);
copiedUser = true;
}
const auto sourceCommonPath = ActiveSettings::GetMlcPath("emulatorSave/{:08x}_255", CafeSystem::GetRPXHashBase());
sourcePath = sourceCommonPath;
if (fs::exists(sourceCommonPath) && is_directory(sourceCommonPath))
{
targetPath = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/common", GetTitleIdHigh(titleId), GetTitleIdLow(titleId));
fs::create_directories(targetPath);
copy(sourceCommonPath, targetPath, fs::copy_options::overwrite_existing | fs::copy_options::recursive);
copiedCommon = true;
}
if (copiedUser)
fs::remove_all(sourceSavePath);
if (copiedCommon)
fs::remove_all(sourceCommonPath);
}
catch (const std::exception& ex)
{
#if BOOST_OS_WINDOWS
std::wstringstream errorMsg;
errorMsg << L"Couldn't move your save files!" << std::endl << std::endl;
errorMsg << L"Error: " << ex.what() << std::endl << std::endl;
errorMsg << L"From:" << std::endl << sourcePath << std::endl << std::endl << "To:" << std::endl << targetPath;
const DWORD lastError = GetLastError();
if (lastError != ERROR_SUCCESS)
{
LPTSTR lpMsgBuf = nullptr;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, lastError, 0, (LPTSTR)&lpMsgBuf, 0, nullptr);
if (lpMsgBuf)
{
errorMsg << std::endl << std::endl << L"Details: " << lpMsgBuf;
LocalFree(lpMsgBuf);
}
else
{
errorMsg << std::endl << std::endl << L"Error Code: 0x" << std::hex << lastError;
}
}
errorMsg << std::endl << std::endl << "Continuing will create a new save at the target location." << std::endl << "Do you want to continue?";
int result = wxMessageBox(errorMsg.str(), "Save Migration - Error", wxCENTRE | wxYES_NO | wxICON_ERROR);
if (result != wxYES)
{
exit(0);
return;
}
#endif
}
}
SAVEStatus SAVEInit()
{
const uint64 titleId = CafeSystem::GetForegroundTitleId();
if (!g_nn_save->initialized)
{
OSInitMutexEx(&g_nn_save->mutex, nullptr);
act::Initialize();
coreinit::FSAddClientEx(&g_nn_save->fsClient, 0, 0);
coreinit::FSInitCmdBlock(&g_nn_save->fsCmdBlock);
for(uint8 accountId = SAVE_ACCOUNT_ID_MIN; accountId <= SAVE_ACCOUNT_ID_MAX; ++accountId)
{
uint32 persistentId = act::GetPersistentIdEx(accountId);
SetPersistentIdToLocalCache(accountId, persistentId);
}
SAVEMountSaveDir();
g_nn_save->initialized = true;
_CheckAndMoveLegacySaves();
uint32 high = GetTitleIdHigh(titleId) & (~0xC);
uint32 low = GetTitleIdLow(titleId);
sint32 fscStatus = FSC_STATUS_FILE_NOT_FOUND;
char path[256];
sprintf(path, "%susr/save/%08x/", "/vol/storage_mlc01/", high);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
sprintf(path, "%susr/save/%08x/%08x/meta/", "/vol/storage_mlc01/", high, low);
fsc_createDir(path, &fscStatus);
iosu::acp::CreateSaveMetaFiles(ActiveSettings::GetPersistentId(), titleId);
}
return SAVE_STATUS_OK;
}
SAVEStatus SAVEInitSaveDir(uint8 accountSlot)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
acp::ACPStatus status = nn::acp::ACPCreateSaveDir(persistentId, iosu::acp::ACPDeviceType::InternalDeviceType);
result = ConvertACPToSaveStatus(status);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEOpenDirAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, path, fullPath))
result = coreinit::FSOpenDirAsync(client, block, fullPath, hDir, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEOpenDir(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEOpenDirAsync(client, block, accountSlot, path, hDir, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEOpenDirOtherApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint64 titleId, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPathOtherApplication(persistentId, titleId, path, fullPath) == FS_RESULT::SUCCESS)
result = coreinit::FSOpenDirAsync(client, block, fullPath, hDir, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEOpenDirOtherApplication(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint64 titleId, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEOpenDirOtherApplicationAsync(client, block, titleId, accountSlot, path, hDir, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEOpenDirOtherNormalApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID(uniqueId);
return SAVEOpenDirOtherApplicationAsync(client, block, titleId, accountSlot, path, hDir, errHandling, asyncParams);
}
SAVEStatus SAVEOpenDirOtherNormalApplication(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID(uniqueId);
return SAVEOpenDirOtherApplication(client, block, titleId, accountSlot, path, hDir, errHandling);
}
SAVEStatus SAVEOpenDirOtherNormalApplicationVariationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEOpenDirOtherApplicationAsync(client, block, titleId, accountSlot, path, hDir, errHandling, asyncParams);
}
SAVEStatus SAVEOpenDirOtherNormalApplicationVariation(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, FSDirHandlePtr hDir, FS_ERROR_MASK errHandling)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEOpenDirOtherApplication(client, block, titleId, accountSlot, path, hDir, errHandling);
}
SAVEStatus SAVEOpenFileAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, path, fullPath))
result = coreinit::FSOpenFileAsync(client, block, fullPath, (char*)mode, outFileHandle, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEOpenFileOtherApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint64 titleId, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
if (strcmp(mode, "r") != 0)
return (SAVEStatus)(FS_RESULT::PERMISSION_ERROR);
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPathOtherApplication(persistentId, titleId, path, fullPath) == FS_RESULT::SUCCESS)
result = coreinit::FSOpenFileAsync(client, block, fullPath, (char*)mode, outFileHandle, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEOpenFileOtherApplication(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint64 titleId, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEOpenFileOtherApplicationAsync(client, block, titleId, accountSlot, path, mode, outFileHandle, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEOpenFileOtherNormalApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID(uniqueId);
return SAVEOpenFileOtherApplicationAsync(client, block, titleId, accountSlot, path, mode, outFileHandle, errHandling, asyncParams);
}
SAVEStatus SAVEOpenFileOtherNormalApplication(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID(uniqueId);
return SAVEOpenFileOtherApplication(client, block, titleId, accountSlot, path, mode, outFileHandle, errHandling);
}
SAVEStatus SAVEOpenFileOtherNormalApplicationVariationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEOpenFileOtherApplicationAsync(client, block, titleId, accountSlot, path, mode, outFileHandle, errHandling, asyncParams);
}
SAVEStatus SAVEOpenFileOtherNormalApplicationVariation(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEOpenFileOtherApplication(client, block, titleId, accountSlot, path, mode, outFileHandle, errHandling);
}
SAVEStatus SAVEGetStatAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, path, fullPath))
result = coreinit::__FSQueryInfoAsync(client, block, (uint8*)fullPath, FSA_QUERY_TYPE_STAT, stat, errHandling, (FSAsyncParams*)asyncParams); // FSGetStatAsync(...)
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEGetStat(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEGetStatAsync(client, block, accountSlot, path, stat, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEGetStatOtherApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint64 titleId, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPathOtherApplication(persistentId, titleId, path, fullPath) == FS_RESULT::SUCCESS)
result = coreinit::__FSQueryInfoAsync(client, block, (uint8*)fullPath, FSA_QUERY_TYPE_STAT, stat, errHandling, (FSAsyncParams*)asyncParams); // FSGetStatAsync(...)
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEGetStatOtherApplication(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint64 titleId, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEGetStatOtherApplicationAsync(client, block, titleId, accountSlot, path, stat, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEGetStatOtherNormalApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID(uniqueId);
return SAVEGetStatOtherApplicationAsync(client, block, titleId, accountSlot, path, stat, errHandling, asyncParams);
}
SAVEStatus SAVEGetStatOtherNormalApplication(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID(uniqueId);
return SAVEGetStatOtherApplication(client, block, titleId, accountSlot, path, stat, errHandling);
}
SAVEStatus SAVEGetStatOtherDemoApplicationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_DEMO_TO_TITLE_ID(uniqueId);
return SAVEGetStatOtherApplicationAsync(client, block, titleId, accountSlot, path, stat, errHandling, asyncParams);
}
SAVEStatus SAVEGetStatOtherNormalApplicationVariationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEGetStatOtherApplicationAsync(client, block, titleId, accountSlot, path, stat, errHandling, asyncParams);
}
SAVEStatus SAVEGetStatOtherDemoApplicationVariationAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
uint64 titleId = SAVE_UNIQUE_DEMO_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEGetStatOtherApplicationAsync(client, block, titleId, accountSlot, path, stat, errHandling, asyncParams);
}
SAVEStatus SAVEGetStatOtherNormalApplicationVariation(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint32 uniqueId, uint8 variation, uint8 accountSlot, const char* path, FSStat_t* stat, FS_ERROR_MASK errHandling)
{
//peterBreak();
uint64 titleId = SAVE_UNIQUE_TO_TITLE_ID_VARIATION(uniqueId, variation);
return SAVEGetStatOtherApplication(client, block, titleId, accountSlot, path, stat, errHandling);
}
SAVEStatus SAVEGetFreeSpaceSizeAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, FSLargeSize* freeSize, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, nullptr, fullPath))
result = coreinit::FSGetFreeSpaceSizeAsync(client, block, fullPath, freeSize, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEGetFreeSpaceSize(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, FSLargeSize* freeSize, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEGetFreeSpaceSizeAsync(client, block, accountSlot, freeSize, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVERemoveAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, path, fullPath))
result = coreinit::FSRemoveAsync(client, block, (uint8*)fullPath, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVERemove(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVERemoveAsync(client, block, accountSlot, path, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVERenameAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* oldPath, const char* newPath, FS_ERROR_MASK errHandling, FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullOldPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, oldPath, fullOldPath))
{
char fullNewPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, newPath, fullNewPath))
result = coreinit::FSRenameAsync(client, block, fullOldPath, fullNewPath, errHandling, asyncParams);
}
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVERename(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* oldPath, const char* newPath, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVERenameAsync(client, block, accountSlot, oldPath, newPath, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEMakeDirAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, path, fullPath))
result = coreinit::FSMakeDirAsync(client, block, fullPath, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEMakeDir(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEMakeDirAsync(client, block, accountSlot, path, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEOpenFile(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, const char* mode, FSFileHandlePtr outFileHandle, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEOpenFileAsync(client, block, accountSlot, path, mode, outFileHandle, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEGetSharedDataTitlePath(uint64 titleId, const char* dataFileName, char* output, sint32 outputLength)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
sint32 written = snprintf(output, outputLength, "/vol/storage_mlc01/sys/title/%08x/%08x/content/%s", GetTitleIdHigh(titleId), GetTitleIdLow(titleId), dataFileName);
if (written >= 0 && written < outputLength)
result = (FSStatus)FS_RESULT::SUCCESS;
cemu_assert_debug(result != (FSStatus)(FS_RESULT::FATAL_ERROR));
return result;
}
SAVEStatus SAVEGetSharedSaveDataPath(uint64 titleId, const char* dataFileName, char* output, uint32 outputLength)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
int written = snprintf(output, outputLength, "/vol/storage_mlc01/usr/save/%08x/%08x/user/common/%s", GetTitleIdHigh(titleId), GetTitleIdLow(titleId), dataFileName);
if (written >= 0 && written < (sint32)outputLength)
result = (FSStatus)FS_RESULT::SUCCESS;
cemu_assert_debug(result != (FSStatus)(FS_RESULT::FATAL_ERROR));
return result;
}
SAVEStatus SAVEChangeDirAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, path, fullPath))
result = coreinit::FSChangeDirAsync(client, block, fullPath, errHandling, (FSAsyncParams*)asyncParams);
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEChangeDir(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, const char* path, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEChangeDirAsync(client, block, accountSlot, path, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
SAVEStatus SAVEFlushQuotaAsync(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, FS_ERROR_MASK errHandling, const FSAsyncParams* asyncParams)
{
SAVEStatus result = (FSStatus)(FS_RESULT::FATAL_ERROR);
OSLockMutex(&g_nn_save->mutex);
uint32 persistentId;
if (GetPersistentIdEx(accountSlot, &persistentId))
{
char fullPath[SAVE_MAX_PATH_SIZE];
if (GetAbsoluteFullPath(persistentId, nullptr, fullPath))
{
result = coreinit::FSFlushQuotaAsync(client, block, fullPath, errHandling, (FSAsyncParams*)asyncParams);
// if(OSGetUPID != 0xF)
UpdateSaveTimeStamp(persistentId);
}
}
else
result = (FSStatus)FS_RESULT::NOT_FOUND;
OSUnlockMutex(&g_nn_save->mutex);
return result;
}
SAVEStatus SAVEFlushQuota(coreinit::FSClient_t* client, coreinit::FSCmdBlock_t* block, uint8 accountSlot, FS_ERROR_MASK errHandling)
{
StackAllocator<AsyncToSyncWrapper> asyncData;
SAVEStatus status = SAVEFlushQuotaAsync(client, block, accountSlot, errHandling, asyncData->GetAsyncParams());
if (status != (FSStatus)FS_RESULT::SUCCESS)
return status;
asyncData->WaitForEvent();
return asyncData->GetResult();
}
void load()
{
cafeExportRegister("nn_save", SAVEInit, LogType::Save);
cafeExportRegister("nn_save", SAVEInitSaveDir, LogType::Save);
cafeExportRegister("nn_save", SAVEGetSharedDataTitlePath, LogType::Save);
cafeExportRegister("nn_save", SAVEGetSharedSaveDataPath, LogType::Save);
cafeExportRegister("nn_save", SAVEGetFreeSpaceSize, LogType::Save);
cafeExportRegister("nn_save", SAVEGetFreeSpaceSizeAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEMakeDir, LogType::Save);
cafeExportRegister("nn_save", SAVEMakeDirAsync, LogType::Save);
cafeExportRegister("nn_save", SAVERemove, LogType::Save);
cafeExportRegister("nn_save", SAVERemoveAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEChangeDir, LogType::Save);
cafeExportRegister("nn_save", SAVEChangeDirAsync, LogType::Save);
cafeExportRegister("nn_save", SAVERename, LogType::Save);
cafeExportRegister("nn_save", SAVERenameAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEFlushQuota, LogType::Save);
cafeExportRegister("nn_save", SAVEFlushQuotaAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStat, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatOtherApplication, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatOtherApplicationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatOtherNormalApplication, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatOtherNormalApplicationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatOtherNormalApplicationVariation, LogType::Save);
cafeExportRegister("nn_save", SAVEGetStatOtherNormalApplicationVariationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFile, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileOtherApplication, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileOtherApplicationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileOtherNormalApplication, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileOtherNormalApplicationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileOtherNormalApplicationVariation, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenFileOtherNormalApplicationVariationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDir, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirOtherApplication, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirOtherApplicationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirOtherNormalApplication, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirOtherNormalApplicationVariation, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirOtherNormalApplicationAsync, LogType::Save);
cafeExportRegister("nn_save", SAVEOpenDirOtherNormalApplicationVariationAsync, LogType::Save);
}
void ResetToDefaultState()
{
if(g_nn_save->initialized)
{
SAVEUnmountSaveDir();
g_nn_save->initialized = false;
}
}
}
}
| 35,782
|
C++
|
.cpp
| 754
| 44.124668
| 302
| 0.764094
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,085
|
nn_acp.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_acp/nn_acp.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/Filesystem/fsc.h"
#include "nn_acp.h"
#include "Cafe/OS/libs/nn_common.h"
#include "Cafe/OS/libs/coreinit/coreinit_IOS.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include <cinttypes>
#include <filesystem>
#include <fstream>
#include "config/ActiveSettings.h"
#include "Cafe/IOSU/legacy/iosu_acp.h"
#include "Cafe/IOSU/legacy/iosu_ioctl.h"
#include "Cafe/OS/libs/sysapp/sysapp.h"
#include "Common/FileStream.h"
#include "Cafe/CafeSystem.h"
using ACPDeviceType = iosu::acp::ACPDeviceType;
#define acpPrepareRequest() \
StackAllocator<iosuAcpCemuRequest_t> _buf_acpRequest; \
StackAllocator<ioBufferVector_t> _buf_bufferVector; \
iosuAcpCemuRequest_t* acpRequest = _buf_acpRequest.GetPointer(); \
ioBufferVector_t* acpBufferVector = _buf_bufferVector.GetPointer(); \
memset(acpRequest, 0, sizeof(iosuAcpCemuRequest_t)); \
memset(acpBufferVector, 0, sizeof(ioBufferVector_t)); \
acpBufferVector->buffer = (uint8*)acpRequest;
namespace nn
{
namespace acp
{
ACPStatus ACPConvertResultToACPStatus(uint32* nnResult, const char* functionName, uint32 lineNumber)
{
// todo
return ACPStatus::SUCCESS;
}
#define _ACPConvertResultToACPStatus(nnResult) ACPConvertResultToACPStatus(nnResult, __func__, __LINE__)
ACPStatus ACPGetApplicationBox(uint32be* applicationBox, uint64 titleId)
{
// todo
*applicationBox = 3; // storage mlc
return ACPStatus::SUCCESS;
}
ACPStatus ACPGetOlvAccesskey(uint32be* accessKey)
{
nnResult r = iosu::acp::ACPGetOlvAccesskey(accessKey);
return _ACPConvertResultToACPStatus(&r);
}
bool sSaveDirMounted{false};
ACPStatus ACPMountSaveDir()
{
cemu_assert_debug(!sSaveDirMounted);
uint64 titleId = CafeSystem::GetForegroundTitleId();
uint32 high = GetTitleIdHigh(titleId) & (~0xC);
uint32 low = GetTitleIdLow(titleId);
// mount save path
const auto mlc = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/", high, low);
FSCDeviceHostFS_Mount("/vol/save/", _pathToUtf8(mlc), FSC_PRIORITY_BASE);
nnResult mountResult = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_ACP, 0);
return _ACPConvertResultToACPStatus(&mountResult);
}
ACPStatus ACPUnmountSaveDir()
{
cemu_assert_debug(!sSaveDirMounted);
fsc_unmount("/vol/save/", FSC_PRIORITY_BASE);
return ACPStatus::SUCCESS;
}
ACPStatus ACPUpdateSaveTimeStamp(uint32 persistentId, uint64 titleId, ACPDeviceType deviceType)
{
nnResult r = iosu::acp::ACPUpdateSaveTimeStamp(persistentId, titleId, deviceType);
return ACPStatus::SUCCESS;
}
ACPStatus ACPCheckApplicationDeviceEmulation(uint32be* isEmulated)
{
*isEmulated = 0;
return ACPStatus::SUCCESS;
}
ACPStatus ACPCreateSaveDir(uint32 persistentId, ACPDeviceType type)
{
nnResult result = iosu::acp::ACPCreateSaveDir(persistentId, type);
return _ACPConvertResultToACPStatus(&result);
}
nnResult ACPCreateSaveDirEx(uint8 accountSlot, uint64 titleId)
{
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_CREATE_SAVE_DIR_EX;
acpRequest->accountSlot = accountSlot;
acpRequest->titleId = titleId;
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
nnResult result = BUILD_NN_RESULT(NN_RESULT_LEVEL_SUCCESS, NN_RESULT_MODULE_NN_ACP, 0);
return result;
}
void nnACPExport_ACPCreateSaveDirEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU8(accountSlot, 0);
ppcDefineParamU64(titleId, 2); // index 2 because of alignment -> guessed parameters
nnResult result = ACPCreateSaveDirEx(accountSlot, titleId);
osLib_returnFromFunction(hCPU, _ACPConvertResultToACPStatus(&result));
}
void export_ACPGetSaveDataTitleIdList(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(uknType, 0);
ppcDefineParamStructPtr(titleIdList, acpTitleId_t, 1);
ppcDefineParamU32(maxCount, 2);
ppcDefineParamU32BEPtr(count, 3);
if (uknType != 3)
assert_dbg();
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_SAVE_DATA_TITLE_ID_LIST;
acpRequest->ptr = titleIdList;
acpRequest->maxCount = maxCount;
acpRequest->type = uknType;
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
*count = acpRequest->resultU32.u32;
osLib_returnFromFunction(hCPU, acpRequest->returnCode);
}
void export_ACPGetTitleSaveMetaXml(PPCInterpreter_t* hCPU)
{
// r3/r4 = titleId
// r5 = pointer
// r6 = 3 (probably some sort of type? Same as in ACPGetSaveDataTitleIdList?)
ppcDefineParamU64(titleId, 0);
ppcDefineParamStructPtr(acpMetaXml, acpMetaXml_t, 2);
ppcDefineParamU32(uknR6, 3);
if (uknR6 != 3)
assert_dbg();
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_TITLE_SAVE_META_XML;
acpRequest->ptr = acpMetaXml;
acpRequest->titleId = titleId;
acpRequest->type = uknR6;
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
osLib_returnFromFunction(hCPU, acpRequest->returnCode);
}
static_assert(sizeof(acpSaveDirInfo_t) == 0x80, "acpSaveDirInfo_t has invalid size");
void export_ACPGetTitleSaveDirEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU64(titleId, 0);
ppcDefineParamU32(uknR5, 2); // storage device id?
ppcDefineParamU32(uknR6, 3); // ukn
ppcDefineParamStructPtr(saveDirInfoOut, acpSaveDirInfo_t, 4);
ppcDefineParamU32(uknR8, 5); // max count?
ppcDefineParamU32BEPtr(countOut, 6);
if (uknR5 != 3)
assert_dbg();
if (uknR6 != 0)
assert_dbg();
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_TITLE_SAVE_DIR;
acpRequest->ptr = saveDirInfoOut;
acpRequest->titleId = titleId;
acpRequest->type = uknR5;
acpRequest->maxCount = uknR8;
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
*countOut = acpRequest->resultU32.u32;
osLib_returnFromFunction(hCPU, acpRequest->returnCode);
}
void export_ACPCheckTitleNotReferAccountLaunch(PPCInterpreter_t* hCPU)
{
ppcDefineParamU64(titleId, 0);
cemuLog_logDebug(LogType::Force, "ACPCheckTitleNotReferAccountLaunch(): Placeholder");
osLib_returnFromFunction(hCPU, 0);
}
void export_ACPGetLaunchMetaData(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(acpMetaData, acpMetaData_t, 0);
cemuLog_logDebug(LogType::Force, "ACPGetLaunchMetaData(): Placeholder");
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_TITLE_META_DATA;
acpRequest->ptr = acpMetaData;
acpRequest->titleId = CafeSystem::GetForegroundTitleId();
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
osLib_returnFromFunction(hCPU, acpRequest->returnCode);
}
void export_ACPGetLaunchMetaXml(PPCInterpreter_t* hCPU)
{
ppcDefineParamStructPtr(acpMetaXml, acpMetaXml_t, 0);
cemuLog_logDebug(LogType::Force, "ACPGetLaunchMetaXml(): Placeholder");
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_TITLE_META_XML;
acpRequest->ptr = acpMetaXml;
acpRequest->titleId = CafeSystem::GetForegroundTitleId();
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
osLib_returnFromFunction(hCPU, acpRequest->returnCode);
}
void export_ACPGetTitleIdOfMainApplication(PPCInterpreter_t* hCPU)
{
ppcDefineParamTypePtr(titleId, uint64be, 0);
uint64 currentTitleId = CafeSystem::GetForegroundTitleId();
*titleId = currentTitleId;
// for applets we return the menu titleId
if (((currentTitleId >> 32) & 0xFF) == 0x30)
{
// get menu titleId
uint64 menuTitleId = _SYSGetSystemApplicationTitleId(0);
*titleId = menuTitleId;
}
osLib_returnFromFunction(hCPU, 0);
}
void export_ACPGetTitleMetaDirByDevice(PPCInterpreter_t* hCPU)
{
ppcDefineParamU64(titleId, 0);
ppcDefineParamStr(path, 2);
ppcDefineParamU32(pathSize, 3);
ppcDefineParamU32(deviceId, 4);
if (deviceId != 3)
assert_dbg();
if (((titleId >> 32) & 0xFF) == 0x10 || ((titleId >> 32) & 0xFF) == 0x30)
{
sprintf(path, "/vol/storage_mlc01/sys/title/%08x/%08x/meta", (uint32)(titleId>>32), (uint32)(titleId&0xFFFFFFFF));
}
else
{
sprintf(path, "/vol/storage_mlc01/usr/title/%08x/%08x/meta", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF));
}
osLib_returnFromFunction(hCPU, 0);
}
void export_ACPGetTitleMetaXmlByDevice(PPCInterpreter_t* hCPU)
{
ppcDefineParamU64(titleId, 0);
ppcDefineParamStructPtr(acpMetaXml, acpMetaXml_t, 2);
ppcDefineParamU32(deviceId, 3);
if (deviceId != 3)
cemuLog_logDebug(LogType::Force, "ACPGetTitleMetaXmlByDevice(): Unsupported deviceId");
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_TITLE_META_XML;
acpRequest->ptr = acpMetaXml;
acpRequest->titleId = titleId;//CafeSystem::GetForegroundTitleId();
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
osLib_returnFromFunction(hCPU, acpRequest->returnCode);
}
uint32 ACPGetTitleMetaXml(uint64 titleId, acpMetaXml_t* acpMetaXml)
{
acpPrepareRequest();
acpRequest->requestCode = IOSU_ACP_GET_TITLE_META_XML;
acpRequest->ptr = acpMetaXml;
acpRequest->titleId = titleId;
__depr__IOS_Ioctlv(IOS_DEVICE_ACP_MAIN, IOSU_ACP_REQUEST_CEMU, 1, 1, acpBufferVector);
return acpRequest->returnCode;
}
void export_ACPIsOverAgeEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(age, 0);
ppcDefineParamU8(slot, 1);
bool isOverAge = true;
osLib_returnFromFunction(hCPU, isOverAge ? 1 : 0);
}
void export_ACPGetNetworkTime(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32BEPtr(timestamp64, 0);
ppcDefineParamU32BEPtr(ukn, 1); // probably timezone or offset? Could also be a bool for success/failed
uint64 t = coreinit::coreinit_getOSTime() + (uint64)((sint64)(ppcCyclesSince2000_UTC - ppcCyclesSince2000) / 20LL);
timestamp64[0] = (uint32)(t >> 32);
timestamp64[1] = (uint32)(t & 0xFFFFFFFF);
*ukn = 1; // E-Shop doesnt want this to be zero (games also check for it)
osLib_returnFromFunction(hCPU, 0); // error code
}
void export_ACPConvertNetworkTimeToOSCalendarTime(PPCInterpreter_t* hCPU)
{
ppcDefineParamU64(networkTime, 0);
ppcDefineParamStructPtr(calendarTime, coreinit::OSCalendarTime_t, 2);
coreinit::OSTicksToCalendarTime(networkTime, calendarTime);
osLib_returnFromFunction(hCPU, 0);
}
void load()
{
cafeExportRegister("nn_acp", ACPCheckApplicationDeviceEmulation, LogType::Placeholder);
osLib_addFunction("nn_acp", "ACPCreateSaveDirEx", nnACPExport_ACPCreateSaveDirEx);
cafeExportRegister("nn_acp", ACPUpdateSaveTimeStamp, LogType::Placeholder);
osLib_addFunction("nn_acp", "ACPGetSaveDataTitleIdList", export_ACPGetSaveDataTitleIdList);
osLib_addFunction("nn_acp", "ACPGetTitleSaveMetaXml", export_ACPGetTitleSaveMetaXml);
osLib_addFunction("nn_acp", "ACPGetTitleSaveDirEx", export_ACPGetTitleSaveDirEx);
osLib_addFunction("nn_acp", "ACPCheckTitleNotReferAccountLaunch", export_ACPCheckTitleNotReferAccountLaunch);
osLib_addFunction("nn_acp", "ACPGetLaunchMetaData", export_ACPGetLaunchMetaData);
osLib_addFunction("nn_acp", "ACPGetLaunchMetaXml", export_ACPGetLaunchMetaXml);
osLib_addFunction("nn_acp", "ACPGetTitleIdOfMainApplication", export_ACPGetTitleIdOfMainApplication);
osLib_addFunction("nn_acp", "ACPGetTitleMetaDirByDevice", export_ACPGetTitleMetaDirByDevice);
osLib_addFunction("nn_acp", "ACPGetTitleMetaXmlByDevice", export_ACPGetTitleMetaXmlByDevice);
cafeExportRegister("nn_acp", ACPGetTitleMetaXml, LogType::Placeholder);
cafeExportRegister("nn_acp", ACPGetApplicationBox, LogType::Placeholder);
cafeExportRegister("nn_acp", ACPGetOlvAccesskey, LogType::Placeholder);
osLib_addFunction("nn_acp", "ACPIsOverAgeEx", export_ACPIsOverAgeEx);
osLib_addFunction("nn_acp", "ACPGetNetworkTime", export_ACPGetNetworkTime);
osLib_addFunction("nn_acp", "ACPConvertNetworkTimeToOSCalendarTime", export_ACPConvertNetworkTimeToOSCalendarTime);
}
}
}
| 11,853
|
C++
|
.cpp
| 284
| 38.735915
| 121
| 0.770926
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,086
|
nn_pdm.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/nn_pdm/nn_pdm.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "config/ActiveSettings.h"
#include "Cafe/TitleList/TitleId.h"
#include "Cafe/IOSU/PDM/iosu_pdm.h"
#include "nn_pdm.h"
namespace nn
{
namespace pdm
{
using PlayDiary = iosu::pdm::PlayDiaryEntry;
uint32 GetPlayDiaryMaxLength(uint32be* count)
{
*count = iosu::pdm::NUM_PLAY_DIARY_ENTRIES_MAX;
return 0;
}
uint32 GetPlayStatsMaxLength(uint32be* count)
{
*count = iosu::pdm::NUM_PLAY_STATS_ENTRIES;
return 0;
}
uint32 GetPlayDiary(uint32be* ukn1, PlayDiary* playDiary, uint32 accountSlot, uint32 maxNumEntries)
{
uint32 numReadEntries = iosu::pdm::GetDiaryEntries(accountSlot, playDiary, maxNumEntries);
*ukn1 = numReadEntries;
return 0;
}
void Initialize()
{
cafeExportRegisterFunc(GetPlayDiaryMaxLength, "nn_pdm", "GetPlayDiaryMaxLength__Q2_2nn3pdmFPi", LogType::NN_PDM);
cafeExportRegisterFunc(GetPlayStatsMaxLength, "nn_pdm", "GetPlayStatsMaxLength__Q2_2nn3pdmFPi", LogType::NN_PDM);
cafeExportRegisterFunc(GetPlayDiary, "nn_pdm", "GetPlayDiary__Q2_2nn3pdmFPiPQ3_2nn3pdm9PlayDiaryiT3", LogType::NN_PDM);
}
}
}
| 1,122
|
C++
|
.cpp
| 34
| 30.029412
| 122
| 0.761111
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,087
|
coreinit_OverlayArena.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_OverlayArena.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/common/OSCommon.h"
#include "coreinit_OverlayArena.h"
namespace coreinit
{
struct
{
bool isEnabled;
}g_coreinitOverlayArena = { 0 };
uint32 OSIsEnabledOverlayArena()
{
return g_coreinitOverlayArena.isEnabled ? 1 : 0;
}
void OSEnableOverlayArena(uint32 uknParam, uint32be* areaOffset, uint32be* areaSize)
{
if (g_coreinitOverlayArena.isEnabled == false)
{
memory_enableOverlayArena();
g_coreinitOverlayArena.isEnabled = true;
}
*areaOffset = MEMORY_OVERLAY_AREA_OFFSET;
*areaSize = MEMORY_OVERLAY_AREA_SIZE;
}
void InitializeOverlayArena()
{
cafeExportRegister("coreinit", OSIsEnabledOverlayArena, LogType::Placeholder);
cafeExportRegister("coreinit", OSEnableOverlayArena, LogType::Placeholder);
g_coreinitOverlayArena.isEnabled = false;
}
}
| 838
|
C++
|
.cpp
| 30
| 25.566667
| 85
| 0.782609
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,088
|
coreinit_Coroutine.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Coroutine.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Coroutine.h"
#include "Cafe/HW/Espresso/PPCState.h"
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h"
#include "Cafe/HW/MMU/MMU.h"
#include "Cafe/OS/RPL/rpl.h"
namespace coreinit
{
static_assert(sizeof(OSCoroutine) == 0x180);
static uint32 s_PPCAddrOSSwitchCoroutineAfterOSLoadCoroutine = 0;
void coreinitExport_OSInitCoroutine(PPCInterpreter_t* hCPU)
{
OSCoroutine* coroutine = (OSCoroutine*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
coroutine->lr = _swapEndianU32(hCPU->gpr[4]);
coroutine->r1 = _swapEndianU32(hCPU->gpr[5]);
osLib_returnFromFunction(hCPU, 0);
}
void coreinitCoroutine_OSSaveCoroutine(OSCoroutine* coroutine, PPCInterpreter_t* hCPU)
{
coroutine->lr = _swapEndianU32(hCPU->spr.LR);
coroutine->cr = _swapEndianU32(ppc_getCR(hCPU));
coroutine->gqr1 = _swapEndianU32(hCPU->spr.UGQR[1]);
coroutine->r1 = _swapEndianU32(hCPU->gpr[1]);
coroutine->r2 = _swapEndianU32(hCPU->gpr[2]);
coroutine->r13 = _swapEndianU32(hCPU->gpr[13]);
for (sint32 i = 14; i < 32; i++)
coroutine->gpr[i - 14] = _swapEndianU32(hCPU->gpr[i]);
for (sint32 i = 14; i < 32; i++)
{
coroutine->fpr[i - 14] = _swapEndianU64(hCPU->fpr[i].fp0int);
}
for (sint32 i = 14; i < 32; i++)
{
coroutine->psr[i - 14] = _swapEndianU64(hCPU->fpr[i].fp1int);
}
}
void coreinitCoroutine_OSLoadCoroutine(OSCoroutine* coroutine, PPCInterpreter_t* hCPU)
{
hCPU->spr.LR = _swapEndianU32(coroutine->lr);
ppc_setCR(hCPU, _swapEndianU32(coroutine->cr));
hCPU->spr.UGQR[1] = _swapEndianU32(coroutine->gqr1);
hCPU->gpr[1] = _swapEndianU32(coroutine->r1);
hCPU->gpr[2] = _swapEndianU32(coroutine->r2);
hCPU->gpr[13] = _swapEndianU32(coroutine->r13);
for (sint32 i = 14; i < 32; i++)
hCPU->gpr[i] = _swapEndianU32(coroutine->gpr[i - 14]);
for (sint32 i = 14; i < 32; i++)
{
hCPU->fpr[i].fp0int = _swapEndianU64(coroutine->fpr[i - 14]);
}
for (sint32 i = 14; i < 32; i++)
{
hCPU->fpr[i].fp1int = _swapEndianU64(coroutine->psr[i - 14]);
}
}
void coreinitExport_OSSwitchCoroutine(PPCInterpreter_t* hCPU)
{
// OSSwitchCoroutine is a wrapper for OSSaveCoroutine + OSLoadCoroutine but it has side effects that we need to care about:
// r31 is saved and restored via the stack in OSSwitchCoroutine
// r4 is stored in the r31 field of coroutineCurrent. Injustice: Gods Among Us reads the r31 field and expects it to match coroutineCurrent (0x027183D4 @ EU v16)
OSCoroutine* coroutineCurrent = MEMPTR<OSCoroutine>(hCPU->gpr[3]);
OSCoroutine* coroutineNext = MEMPTR<OSCoroutine>(hCPU->gpr[4]);
hCPU->gpr[1] -= 0x10;
memory_writeU32(hCPU->gpr[1]+0xC, hCPU->gpr[31]);
memory_writeU32(hCPU->gpr[1]+0x14, hCPU->spr.LR);
hCPU->spr.LR = s_PPCAddrOSSwitchCoroutineAfterOSLoadCoroutine;
hCPU->gpr[31] = hCPU->gpr[4];
coreinitCoroutine_OSSaveCoroutine(coroutineCurrent, hCPU);
hCPU->gpr[3] = hCPU->gpr[31];
hCPU->gpr[4] = 1;
coreinitCoroutine_OSLoadCoroutine(coroutineNext, hCPU);
hCPU->instructionPointer = hCPU->spr.LR;
}
void coreinitExport_OSSwitchCoroutineAfterOSLoadCoroutine(PPCInterpreter_t* hCPU)
{
// resuming after OSSaveCoroutine
hCPU->gpr[31] = memory_readU32(hCPU->gpr[1]+0xC);
hCPU->spr.LR = memory_readU32(hCPU->gpr[1]+0x14);
hCPU->gpr[1] += 0x10;
hCPU->instructionPointer = hCPU->spr.LR;
}
void coreinitExport_OSSwitchFiberEx(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(param0, 0);
ppcDefineParamU32(param1, 1);
ppcDefineParamU32(param2, 2);
ppcDefineParamU32(param3, 3);
ppcDefineParamMPTR(newInstructionPointer, 4);
ppcDefineParamMPTR(newStackPointer, 5);
MPTR prevStackpointer = hCPU->gpr[1];
hCPU->gpr[1] = newStackPointer;
hCPU->gpr[3] = param0;
hCPU->gpr[4] = param1;
hCPU->gpr[5] = param2;
hCPU->gpr[6] = param3;
PPCCore_executeCallbackInternal(newInstructionPointer);
uint32 returnValue = hCPU->gpr[3];
hCPU->gpr[1] = prevStackpointer;
osLib_returnFromFunction(hCPU, returnValue);
}
void InitializeCoroutine()
{
osLib_addFunction("coreinit", "OSInitCoroutine", coreinitExport_OSInitCoroutine);
osLib_addFunction("coreinit", "OSSwitchCoroutine", coreinitExport_OSSwitchCoroutine);
osLib_addFunction("coreinit", "OSSwitchFiberEx", coreinitExport_OSSwitchFiberEx);
s_PPCAddrOSSwitchCoroutineAfterOSLoadCoroutine = RPLLoader_MakePPCCallable(coreinitExport_OSSwitchCoroutineAfterOSLoadCoroutine);
}
}
| 4,451
|
C++
|
.cpp
| 108
| 38.416667
| 163
| 0.736721
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,089
|
coreinit_ThreadQueue.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_ThreadQueue.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
namespace coreinit
{
// puts the thread on the waiting queue and changes state to WAITING
// relinquishes timeslice
// always uses thread->waitQueueLink
void OSThreadQueueInternal::queueAndWait(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
cemu_assert_debug(thread->waitQueueLink.next == nullptr && thread->waitQueueLink.prev == nullptr);
thread->currentWaitQueue = this;
this->addThreadByPriority(thread, &thread->waitQueueLink);
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING);
thread->state = OSThread_t::THREAD_STATE::STATE_WAITING;
PPCCore_switchToSchedulerWithLock();
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING);
}
void OSThreadQueueInternal::queueOnly(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
cemu_assert_debug(thread->waitQueueLink.next == nullptr && thread->waitQueueLink.prev == nullptr);
thread->currentWaitQueue = this;
this->addThreadByPriority(thread, &thread->waitQueueLink);
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING);
thread->state = OSThread_t::THREAD_STATE::STATE_WAITING;
}
// remove thread from wait queue and wake it up
void OSThreadQueueInternal::cancelWait(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
this->removeThread(thread, &thread->waitQueueLink);
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
thread->currentWaitQueue = nullptr;
coreinit::__OSAddReadyThreadToRunQueue(thread);
// todo - if waking up a thread on the same core with higher priority, reschedule
}
void OSThreadQueueInternal::addThread(OSThread_t* thread, OSThreadLink* threadLink)
{
cemu_assert_debug(__OSHasSchedulerLock());
size_t linkOffset = getLinkOffset(thread, threadLink);
// insert after tail
if (tail.IsNull())
{
threadLink->next = nullptr;
threadLink->prev = nullptr;
head = thread;
tail = thread;
}
else
{
threadLink->next = nullptr;
threadLink->prev = tail;
_getThreadLink(tail.GetPtr(), linkOffset)->next = thread;
tail = thread;
}
_debugCheckChain(thread, threadLink);
}
void OSThreadQueueInternal::addThreadByPriority(OSThread_t* thread, OSThreadLink* threadLink)
{
cemu_assert_debug(tail.IsNull() == head.IsNull()); // either must be set or none at all
cemu_assert_debug(__OSHasSchedulerLock());
size_t linkOffset = getLinkOffset(thread, threadLink);
if (tail.IsNull())
{
threadLink->next = nullptr;
threadLink->prev = nullptr;
head = thread;
tail = thread;
}
else
{
// insert towards tail based on priority
OSThread_t* threadItr = tail.GetPtr();
while (threadItr && threadItr->effectivePriority > thread->effectivePriority)
threadItr = _getThreadLink(threadItr, linkOffset)->prev.GetPtr();
if (threadItr == nullptr)
{
// insert in front
threadLink->next = head;
threadLink->prev = nullptr;
_getThreadLink(head.GetPtr(), linkOffset)->prev = thread;
head = thread;
}
else
{
threadLink->prev = threadItr;
threadLink->next = _getThreadLink(threadItr, linkOffset)->next;
if (_getThreadLink(threadItr, linkOffset)->next)
{
OSThread_t* threadAfterItr = _getThreadLink(threadItr, linkOffset)->next.GetPtr();
_getThreadLink(threadAfterItr, linkOffset)->prev = thread;
_getThreadLink(threadItr, linkOffset)->next = thread;
}
else
{
tail = thread;
_getThreadLink(threadItr, linkOffset)->next = thread;
}
}
}
_debugCheckChain(thread, threadLink);
}
void OSThreadQueueInternal::removeThread(OSThread_t* thread, OSThreadLink* threadLink)
{
cemu_assert_debug(__OSHasSchedulerLock());
size_t linkOffset = getLinkOffset(thread, threadLink);
_debugCheckChain(thread, threadLink);
if (threadLink->prev)
_getThreadLink(threadLink->prev.GetPtr(), linkOffset)->next = threadLink->next;
else
head = threadLink->next;
if (threadLink->next)
_getThreadLink(threadLink->next.GetPtr(), linkOffset)->prev = threadLink->prev;
else
tail = threadLink->prev;
threadLink->next = nullptr;
threadLink->prev = nullptr;
}
// counterpart for queueAndWait
// if reschedule is true then scheduler will switch to woken up thread (if it is runnable on the same core)
// sharedPriorityAndAffinityWorkaround is currently a hack/placeholder for some special cases. A proper fix likely involves handling all the nuances of thread effective priority
void OSThreadQueueInternal::wakeupEntireWaitQueue(bool reschedule, bool sharedPriorityAndAffinityWorkaround)
{
cemu_assert_debug(__OSHasSchedulerLock());
bool shouldReschedule = false;
while (OSThread_t* thread = takeFirstFromQueue(offsetof(OSThread_t, waitQueueLink)))
{
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_WAITING);
//cemu_assert_debug(thread->suspendCounter == 0);
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
thread->currentWaitQueue = nullptr;
coreinit::__OSAddReadyThreadToRunQueue(thread);
if (reschedule && thread->suspendCounter == 0 && PPCInterpreter_getCurrentInstance() && __OSCoreShouldSwitchToThread(coreinit::OSGetCurrentThread(), thread, sharedPriorityAndAffinityWorkaround))
shouldReschedule = true;
}
if (shouldReschedule)
PPCCore_switchToSchedulerWithLock();
}
// counterpart for queueAndWait
// if reschedule is true then scheduler will switch to woken up thread (if it is runnable on the same core)
void OSThreadQueueInternal::wakeupSingleThreadWaitQueue(bool reschedule, bool sharedPriorityAndAffinityWorkaround)
{
cemu_assert_debug(__OSHasSchedulerLock());
OSThread_t* thread = takeFirstFromQueue(offsetof(OSThread_t, waitQueueLink));
cemu_assert_debug(thread);
bool shouldReschedule = false;
if (thread)
{
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
thread->currentWaitQueue = nullptr;
coreinit::__OSAddReadyThreadToRunQueue(thread);
if (reschedule && thread->suspendCounter == 0 && PPCInterpreter_getCurrentInstance() && __OSCoreShouldSwitchToThread(coreinit::OSGetCurrentThread(), thread, sharedPriorityAndAffinityWorkaround))
shouldReschedule = true;
}
if (shouldReschedule)
PPCCore_switchToSchedulerWithLock();
}
}
| 6,333
|
C++
|
.cpp
| 159
| 36.503145
| 197
| 0.751744
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,090
|
coreinit_HWInterface.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_HWInterface.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "coreinit_HWInterface.h"
namespace coreinit
{
enum class RegisterInterfaceId : uint32 // for __OSRead/__OSWrite API (register access in userspace)
{
INTERFACE_VI_UKN = 0, // 0x0C1E0000
INTERFACE_VI2_UKN = 3, // might also be some other interface?
};
enum class SysRegisterInterfaceId : uint32 // for __OSRead/__OSWriteRegister (register access via kernel systemcall)
{
INTERFACE_UKN = 0,
INTERFACE_3_ACR_VI = 3, // 0x0D00021C
INTERFACE_6_SI = 6, // 0x0D006400
INTERFACE_7_AI_PROBABLY = 7, // 0x0D046C00 // AI or some secondary AI interface?
};
PAddr _GetRegisterPhysicalAddress(RegisterInterfaceId interfaceId, uint32 offset)
{
PAddr base = 0;
switch (interfaceId)
{
case RegisterInterfaceId::INTERFACE_VI_UKN:
base = 0x0C1E0000;
break;
default:
cemu_assert_debug(false); // todo
return 0;
}
return base + offset;
}
PAddr _GetSysRegisterPhysicalAddress(SysRegisterInterfaceId interfaceId, uint32 offset)
{
PAddr base = 0;
switch (interfaceId)
{
case SysRegisterInterfaceId::INTERFACE_3_ACR_VI:
base = 0x0D00021C;
break;
case SysRegisterInterfaceId::INTERFACE_6_SI:
base = 0x0D006400;
break;
default:
cemu_assert_debug(false); // todo
return 0;
}
return base + offset;
}
/* Userspace register interface */
uint32 OSReadRegister32(RegisterInterfaceId interfaceId, uint32 offset)
{
PAddr regAddr = _GetRegisterPhysicalAddress(interfaceId, offset);
cemu_assert_debug(regAddr);
return MMU::ReadMMIO_32(regAddr);
}
uint16 OSReadRegister16(RegisterInterfaceId interfaceId, uint32 offset)
{
PAddr regAddr = _GetRegisterPhysicalAddress(interfaceId, offset);
cemu_assert_debug(regAddr);
return MMU::ReadMMIO_16(regAddr);
}
void OSWriteRegister16(uint16 newValue, RegisterInterfaceId interfaceId, uint32 offset)
{
static bool s_dbg = false;
if (!s_dbg)
{
cemu_assert_debug(false);
s_dbg = true;
}
}
void OSWriteRegister32(uint16 newValue, RegisterInterfaceId interfaceId, uint32 offset)
{
static bool s_dbg = false;
if (!s_dbg)
{
cemu_assert_debug(false);
s_dbg = true;
}
}
void OSModifyRegister16(RegisterInterfaceId interfaceId, uint32 uknR4, uint32 uknR5, uint32 uknR6)
{
static bool s_dbg = false;
if (!s_dbg)
{
cemu_assert_debug(false);
s_dbg = true;
}
}
/* Kernel register interface */
uint32 __OSReadRegister32Ex(SysRegisterInterfaceId interfaceId, uint32 registerId)
{
uint32 offset = registerId * 4;
cemu_assert_debug(offset < 0x40);
PAddr regAddr = _GetSysRegisterPhysicalAddress(interfaceId, offset);
cemu_assert_debug(regAddr);
return MMU::ReadMMIO_32(regAddr);
}
void __OSWriteRegister32Ex(SysRegisterInterfaceId interfaceId, uint32 registerId, uint32 newValue)
{
uint32 offset = registerId * 4;
cemu_assert_debug(offset < 0x40);
PAddr regAddr = _GetSysRegisterPhysicalAddress(interfaceId, offset);
cemu_assert_debug(regAddr);
MMU::WriteMMIO_32(regAddr, newValue);
}
void InitializeHWInterface()
{
cafeExportRegister("coreinit", OSReadRegister32, LogType::Placeholder);
cafeExportRegister("coreinit", OSReadRegister16, LogType::Placeholder);
cafeExportRegister("coreinit", OSWriteRegister16, LogType::Placeholder);
cafeExportRegister("coreinit", OSWriteRegister32, LogType::Placeholder);
cafeExportRegister("coreinit", OSModifyRegister16, LogType::Placeholder);
cafeExportRegister("coreinit", __OSReadRegister32Ex, LogType::Placeholder);
cafeExportRegister("coreinit", __OSWriteRegister32Ex, LogType::Placeholder);
};
};
| 3,589
|
C++
|
.cpp
| 115
| 28.295652
| 117
| 0.761008
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,091
|
coreinit.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Common/SysAllocator.h"
#include "Cafe/OS/RPL/rpl_symbol_storage.h"
#include "Cafe/OS/libs/coreinit/coreinit_Misc.h"
// includes for Initialize coreinit submodules
#include "Cafe/OS/libs/coreinit/coreinit_BSP.h"
#include "Cafe/OS/libs/coreinit/coreinit_Scheduler.h"
#include "Cafe/OS/libs/coreinit/coreinit_Atomic.h"
#include "Cafe/OS/libs/coreinit/coreinit_OverlayArena.h"
#include "Cafe/OS/libs/coreinit/coreinit_DynLoad.h"
#include "Cafe/OS/libs/coreinit/coreinit_GHS.h"
#include "Cafe/OS/libs/coreinit/coreinit_HWInterface.h"
#include "Cafe/OS/libs/coreinit/coreinit_Memory.h"
#include "Cafe/OS/libs/coreinit/coreinit_IM.h"
#include "Cafe/OS/libs/coreinit/coreinit_LockedCache.h"
#include "Cafe/OS/libs/coreinit/coreinit_MemoryMapping.h"
#include "Cafe/OS/libs/coreinit/coreinit_IPC.h"
#include "Cafe/OS/libs/coreinit/coreinit_IPCBuf.h"
#include "Cafe/OS/libs/coreinit/coreinit_Coroutine.h"
#include "Cafe/OS/libs/coreinit/coreinit_OSScreen.h"
#include "Cafe/OS/libs/coreinit/coreinit_FG.h"
#include "Cafe/OS/libs/coreinit/coreinit_SystemInfo.h"
#include "Cafe/OS/libs/coreinit/coreinit_SysHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_MCP.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/coreinit/coreinit_CodeGen.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_MPQueue.h"
#include "Cafe/OS/libs/coreinit/coreinit_FS.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_UnitHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_FrmHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_BlockHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_ExpHeap.h"
CoreinitSharedData* gCoreinitData = nullptr;
sint32 ScoreStackTrace(OSThread_t* thread, MPTR sp)
{
uint32 stackMinAddr = thread->stackEnd.GetMPTR();
uint32 stackMaxAddr = thread->stackBase.GetMPTR();
sint32 score = 0;
uint32 currentStackPtr = sp;
for (sint32 i = 0; i < 50; i++)
{
uint32 nextStackPtr = memory_readU32(currentStackPtr);
if (nextStackPtr < currentStackPtr)
break;
if (nextStackPtr < stackMinAddr || nextStackPtr > stackMaxAddr)
break;
if ((nextStackPtr & 3) != 0)
break;
score += 10;
uint32 returnAddress = 0;
returnAddress = memory_readU32(nextStackPtr + 4);
//cemuLog_log(LogType::Force, fmt::format("SP {0:08x} ReturnAddress {1:08x}", nextStackPtr, returnAddress));
if (returnAddress > 0 && returnAddress < 0x10000000 && (returnAddress&3) == 0)
score += 5; // within code region
else
score -= 5;
currentStackPtr = nextStackPtr;
}
return score;
}
void DebugLogStackTrace(OSThread_t* thread, MPTR sp, bool printSymbols)
{
// sp might not point to a valid stackframe
// scan stack and evaluate which sp is most likely the beginning of the stackframe
// scan 0x400 bytes
sint32 highestScore = -1;
uint32 highestScoreSP = sp;
for (sint32 i = 0; i < 0x100; i++)
{
uint32 sampleSP = sp + i * 4;
sint32 score = ScoreStackTrace(thread, sampleSP);
if (score > highestScore)
{
highestScore = score;
highestScoreSP = sampleSP;
}
}
if (highestScoreSP != sp)
cemuLog_log(LogType::Force, fmt::format("Trace starting at SP {0:08x} r1 = {1:08x}", highestScoreSP, sp));
else
cemuLog_log(LogType::Force, fmt::format("Trace starting at SP/r1 {0:08x}", highestScoreSP));
// print stack trace
uint32 currentStackPtr = highestScoreSP;
uint32 stackMinAddr = thread->stackEnd.GetMPTR();
uint32 stackMaxAddr = thread->stackBase.GetMPTR();
for (sint32 i = 0; i < 20; i++)
{
uint32 nextStackPtr = memory_readU32(currentStackPtr);
if (nextStackPtr < currentStackPtr)
break;
if (nextStackPtr < stackMinAddr || nextStackPtr > stackMaxAddr)
break;
uint32 returnAddress = 0;
returnAddress = memory_readU32(nextStackPtr + 4);
RPLStoredSymbol* symbol = nullptr;
if(printSymbols)
symbol = rplSymbolStorage_getByClosestAddress(returnAddress);
if(symbol)
cemuLog_log(LogType::Force, fmt::format("SP {:08x} ReturnAddr {:08x} ({}.{}+0x{:x})", nextStackPtr, returnAddress, (const char*)symbol->libName, (const char*)symbol->symbolName, returnAddress - symbol->address));
else
cemuLog_log(LogType::Force, fmt::format("SP {:08x} ReturnAddr {:08x}", nextStackPtr, returnAddress));
currentStackPtr = nextStackPtr;
}
}
typedef struct
{
/* +0x00 */ uint32be name;
/* +0x04 */ uint32be fileType; // 2 = font
/* +0x08 */ uint32be kernelFilenamePtr;
/* +0x0C */ MEMPTR<void> data;
/* +0x10 */ uint32be size;
/* +0x14 */ uint32be ukn14;
/* +0x18 */ uint32be ukn18;
}coreinitShareddataEntry_t;
static_assert(sizeof(coreinitShareddataEntry_t) == 0x1C, "");
uint8* extractCafeDefaultFont(sint32* size);
MPTR placeholderFont = MPTR_NULL;
sint32 placeholderFontSize = 0;
void coreinitExport_OSGetSharedData(PPCInterpreter_t* hCPU)
{
// parameters:
// r3 sharedAreaId
// r4 flags
// r5 areaPtrPtr
// r6 areaSizePtr
// on real Wii U hw/sw there is a list of shared area entries starting at offset +0xF8000000
// properly formated (each entry is 0x1C bytes) it looks like this:
// FF CA FE 01 00 00 00 02 FF E8 47 AC F8 00 00 70 00 C8 0D 4C 00 00 00 00 FF FF FF FC
// FF CA FE 02 00 00 00 02 FF E8 47 B7 F8 C8 0D C0 00 22 7E B4 00 00 00 00 00 00 11 D5
// FF CA FE 03 00 00 00 02 FF E8 47 A0 F8 EA 8C 80 00 25 44 E0 00 00 00 00 FF A0 00 00
// FF CA FE 04 00 00 00 02 FF E8 47 C2 F9 0F D1 60 00 7D 93 5C 00 00 00 00 FF FF FF FC
uint32 sharedAreaId = hCPU->gpr[3];
coreinitShareddataEntry_t* shareddataTable = (coreinitShareddataEntry_t*)memory_getPointerFromVirtualOffset(MEMORY_SHAREDDATA_AREA_ADDR);
uint32 name = 0xFFCAFE01 + sharedAreaId;
for (sint32 i = 0; i < 4; i++)
{
if ((uint32)shareddataTable[i].name == name)
{
memory_writeU32(hCPU->gpr[5], shareddataTable[i].data.GetMPTR());
memory_writeU32(hCPU->gpr[6], (uint32)shareddataTable[i].size);
osLib_returnFromFunction(hCPU, 1);
return;
}
}
// some games require a valid result or they will crash, return a pointer to our placeholder font
cemuLog_log(LogType::Force, "OSGetSharedData() called by game but no shareddata fonts loaded. Use placeholder font");
if (placeholderFont == MPTR_NULL)
{
// load and then return placeholder font
uint8* placeholderFontPtr = extractCafeDefaultFont(&placeholderFontSize);
placeholderFont = coreinit_allocFromSysArea(placeholderFontSize, 256);
if (placeholderFont == MPTR_NULL)
cemuLog_log(LogType::Force, "Failed to alloc placeholder font sys memory");
memcpy(memory_getPointerFromVirtualOffset(placeholderFont), placeholderFontPtr, placeholderFontSize);
free(placeholderFontPtr);
}
// return placeholder font
memory_writeU32(hCPU->gpr[5], placeholderFont);
memory_writeU32(hCPU->gpr[6], placeholderFontSize);
osLib_returnFromFunction(hCPU, 1);
}
namespace coreinit
{
sint32 OSGetCoreId()
{
return PPCInterpreter_getCoreIndex(PPCInterpreter_getCurrentInstance());
}
uint32 OSGetCoreCount()
{
return Espresso::CORE_COUNT;
}
uint32 OSIsDebuggerInitialized()
{
return 0;
}
uint32 OSIsDebuggerPresent()
{
return 0;
}
uint32 OSGetConsoleType()
{
return 0x03000050;
}
uint32 OSGetMainCoreId()
{
return 1;
}
bool OSIsMainCore()
{
return OSGetCoreId() == OSGetMainCoreId();
}
uint32 OSGetStackPointer()
{
return PPCInterpreter_getCurrentInstance()->gpr[1];
}
void coreinitExport_ENVGetEnvironmentVariable(PPCInterpreter_t* hCPU)
{
cemuLog_logDebug(LogType::Force, "ENVGetEnvironmentVariable(\"{}\",0x08x,0x{:x})", (char*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]), hCPU->gpr[4], hCPU->gpr[5]);
char* envKeyStr = (char*)memory_getPointerFromVirtualOffset(hCPU->gpr[3]);
char* outputString = (char*)memory_getPointerFromVirtualOffset(hCPU->gpr[4]);
sint32 outputStringMaxLen = (sint32)hCPU->gpr[5];
// also return the string "" just in case
if (outputStringMaxLen > 0)
{
outputString[0] = '\0';
}
osLib_returnFromFunction(hCPU, 1);
}
void coreinit_exit(uint32 r)
{
cemuLog_log(LogType::Force, "The title terminated the process by calling coreinit.exit({})", (sint32)r);
DebugLogStackTrace(coreinit::OSGetCurrentThread(), coreinit::OSGetStackPointer());
cemu_assert_debug(false);
// never return
while (true) std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
bool OSIsOffBoot()
{
return true;
}
uint32 OSGetBootPMFlags()
{
cemuLog_logDebug(LogType::Force, "OSGetBootPMFlags() - placeholder");
return 0;
}
uint32 OSGetSystemMode()
{
cemuLog_logDebug(LogType::Force, "OSGetSystemMode() - placeholder");
// if this returns 2, barista softlocks shortly after boot
return 0;
}
void OSPanic(const char* file, sint32 lineNumber, const char* msg)
{
cemuLog_log(LogType::Force, "OSPanic!");
cemuLog_log(LogType::Force, "File: {}:{}", file, lineNumber);
cemuLog_log(LogType::Force, "Msg: {}", msg);
DebugLogStackTrace(coreinit::OSGetCurrentThread(), coreinit::OSGetStackPointer());
#ifdef CEMU_DEBUG_ASSERT
while (true) std::this_thread::sleep_for(std::chrono::milliseconds(100));
#endif
}
void InitializeCore()
{
cafeExportRegister("coreinit", OSGetCoreId, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetCoreCount, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSIsDebuggerInitialized, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSIsDebuggerPresent, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetConsoleType, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetMainCoreId, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSIsMainCore, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetStackPointer, LogType::CoreinitThread);
osLib_addFunction("coreinit", "ENVGetEnvironmentVariable", coreinitExport_ENVGetEnvironmentVariable);
cafeExportRegisterFunc(coreinit_exit, "coreinit", "exit", LogType::CoreinitThread);
cafeExportRegister("coreinit", OSIsOffBoot, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetBootPMFlags, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetSystemMode, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSPanic, LogType::Placeholder);
}
};
void coreinit_load()
{
coreinit::InitializeCore();
coreinit::InitializeSchedulerLock();
coreinit::InitializeSysHeap();
// allocate coreinit global data
gCoreinitData = (CoreinitSharedData*)memory_getPointerFromVirtualOffset(coreinit_allocFromSysArea(sizeof(CoreinitSharedData), 32));
memset(gCoreinitData, 0x00, sizeof(CoreinitSharedData));
// coreinit weak links
osLib_addVirtualPointer("coreinit", "MEMAllocFromDefaultHeap", memory_getVirtualOffsetFromPointer(&gCoreinitData->MEMAllocFromDefaultHeap));
osLib_addVirtualPointer("coreinit", "MEMAllocFromDefaultHeapEx", memory_getVirtualOffsetFromPointer(&gCoreinitData->MEMAllocFromDefaultHeapEx));
osLib_addVirtualPointer("coreinit", "MEMFreeToDefaultHeap", memory_getVirtualOffsetFromPointer(&gCoreinitData->MEMFreeToDefaultHeap));
osLib_addVirtualPointer("coreinit", "__atexit_cleanup", memory_getVirtualOffsetFromPointer(&gCoreinitData->__atexit_cleanup));
osLib_addVirtualPointer("coreinit", "__stdio_cleanup", memory_getVirtualOffsetFromPointer(&gCoreinitData->__stdio_cleanup));
osLib_addVirtualPointer("coreinit", "__cpp_exception_cleanup_ptr", memory_getVirtualOffsetFromPointer(&gCoreinitData->__cpp_exception_cleanup_ptr));
osLib_addVirtualPointer("coreinit", "__cpp_exception_init_ptr", memory_getVirtualOffsetFromPointer(&gCoreinitData->__cpp_exception_init_ptr));
// init GHS and threads
coreinit::PrepareGHSRuntime();
coreinit::InitializeThread();
// reset threads
activeThreadCount = 0;
// init submodules
coreinit::InitializeMEM();
coreinit::InitializeMEMFrmHeap();
coreinit::InitializeMEMUnitHeap();
coreinit::InitializeMEMBlockHeap();
coreinit::InitializeFG();
coreinit::InitializeBSP();
coreinit::InitializeMCP();
coreinit::InitializeOverlayArena();
coreinit::InitializeDynLoad();
coreinit::InitializeGHS();
coreinit::InitializeHWInterface();
coreinit::InitializeAtomic();
coreinit::InitializeMemory();
coreinit::InitializeIM();
coreinit::InitializeLC();
coreinit::InitializeMP();
coreinit::InitializeTimeAndCalendar();
coreinit::InitializeAlarm();
coreinit::InitializeFS();
coreinit::InitializeSystemInfo();
coreinit::InitializeConcurrency();
coreinit::InitializeSpinlock();
coreinit::InitializeMessageQueue();
coreinit::InitializeIPC();
coreinit::InitializeIPCBuf();
coreinit::InitializeMemoryMapping();
coreinit::InitializeCodeGen();
coreinit::InitializeCoroutine();
coreinit::InitializeOSScreen();
// legacy mem stuff
coreinit::expheap_load();
// misc exports
coreinit::miscInit();
osLib_addFunction("coreinit", "OSGetSharedData", coreinitExport_OSGetSharedData);
osLib_addFunction("coreinit", "UCReadSysConfig", coreinitExport_UCReadSysConfig);
// async callbacks
InitializeAsyncCallback();
}
| 12,975
|
C++
|
.cpp
| 321
| 38.049844
| 217
| 0.767894
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,092
|
coreinit_Synchronization.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Synchronization.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "util/helpers/fspinlock.h"
namespace coreinit
{
/************* OSEvent ************/
void OSInitEvent(OSEvent* event, OSEvent::EVENT_STATE initialState, OSEvent::EVENT_MODE mode)
{
event->magic = 'eVnT';
cemu_assert_debug(event->magic == 0x65566e54);
event->userData = nullptr;
event->ukn08 = 0;
event->state = initialState;
event->mode = mode;
OSInitThreadQueueEx(&event->threadQueue, event);
}
void OSInitEventEx(OSEvent* event, OSEvent::EVENT_STATE initialState, OSEvent::EVENT_MODE mode, void* userData)
{
OSInitEvent(event, initialState, mode);
event->userData = userData;
}
void OSResetEvent(OSEvent* event)
{
__OSLockScheduler();
if (event->state == OSEvent::EVENT_STATE::STATE_SIGNALED)
event->state = OSEvent::EVENT_STATE::STATE_NOT_SIGNALED;
__OSUnlockScheduler();
}
void OSWaitEventInternal(OSEvent* event)
{
if (event->state == OSEvent::EVENT_STATE::STATE_SIGNALED)
{
if (event->mode == OSEvent::EVENT_MODE::MODE_AUTO)
event->state = OSEvent::EVENT_STATE::STATE_NOT_SIGNALED;
}
else
{
// enter wait queue
event->threadQueue.queueAndWait(OSGetCurrentThread());
}
}
void OSWaitEvent(OSEvent* event)
{
__OSLockScheduler();
OSWaitEventInternal(event);
__OSUnlockScheduler();
}
struct WaitEventWithTimeoutData
{
OSThread_t* thread;
OSThreadQueue* threadQueue;
std::atomic_bool hasTimeout;
};
void _OSWaitEventWithTimeoutHandler(uint64 currentTick, void* context)
{
cemu_assert_debug(__OSHasSchedulerLock());
WaitEventWithTimeoutData* data = (WaitEventWithTimeoutData*)context;
if (data->thread->state == OSThread_t::THREAD_STATE::STATE_WAITING)
{
data->hasTimeout = true;
data->threadQueue->cancelWait(data->thread);
}
}
uint64 coreinit_getOSTime();
bool OSWaitEventWithTimeout(OSEvent* event, uint64 timeout)
{
__OSLockScheduler();
if (event->state == OSEvent::EVENT_STATE::STATE_SIGNALED)
{
if (event->mode == OSEvent::EVENT_MODE::MODE_AUTO)
event->state = OSEvent::EVENT_STATE::STATE_NOT_SIGNALED;
}
else
{
if (timeout == 0)
{
// fail immediately
__OSUnlockScheduler();
return false;
}
// wait and set timeout
// workaround for a bad implementation in some Unity games (like Qube Directors Cut, see FEventWiiU::Wait)
// where the the return value of OSWaitEventWithTimeout is ignored and instead the game measures the elapsed time to determine if a timeout occurred
timeout = timeout * 98ULL / 100ULL; // 98% (we want the function to return slightly before the actual timeout)
WaitEventWithTimeoutData data;
data.thread = OSGetCurrentThread();
data.threadQueue = &event->threadQueue;
data.hasTimeout = false;
auto hostAlarm = coreinit::OSHostAlarmCreate(coreinit::coreinit_getOSTime() + coreinit::EspressoTime::ConvertNsToTimerTicks(timeout), 0, _OSWaitEventWithTimeoutHandler, &data);
event->threadQueue.queueAndWait(OSGetCurrentThread());
coreinit::OSHostAlarmDestroy(hostAlarm);
if (data.hasTimeout)
{
__OSUnlockScheduler();
return false;
}
}
__OSUnlockScheduler();
return true;
}
void OSSignalEventInternal(OSEvent* event)
{
cemu_assert_debug(__OSHasSchedulerLock());
if (event->state == OSEvent::EVENT_STATE::STATE_SIGNALED)
{
return;
}
if (event->mode == OSEvent::EVENT_MODE::MODE_AUTO)
{
// in auto mode wake up one thread or if there is none then set signaled
if (event->threadQueue.isEmpty())
event->state = OSEvent::EVENT_STATE::STATE_SIGNALED;
else
event->threadQueue.wakeupSingleThreadWaitQueue(true);
}
else
{
// in manual mode wake up all threads and set to signaled
event->state = OSEvent::EVENT_STATE::STATE_SIGNALED;
event->threadQueue.wakeupEntireWaitQueue(true);
}
}
void OSSignalEvent(OSEvent* event)
{
__OSLockScheduler();
OSSignalEventInternal(event);
__OSUnlockScheduler();
}
void OSSignalEventAllInternal(OSEvent* event)
{
if (event->state == OSEvent::EVENT_STATE::STATE_SIGNALED)
{
return;
}
if (event->mode == OSEvent::EVENT_MODE::MODE_AUTO)
{
// in auto mode wake up one thread or if there is none then set signaled
if (event->threadQueue.isEmpty())
event->state = OSEvent::EVENT_STATE::STATE_SIGNALED;
else
event->threadQueue.wakeupEntireWaitQueue(true);
}
else
{
// in manual mode wake up all threads and set to signaled
event->state = OSEvent::EVENT_STATE::STATE_SIGNALED;
event->threadQueue.wakeupEntireWaitQueue(true);
}
}
void OSSignalEventAll(OSEvent* event)
{
__OSLockScheduler();
OSSignalEventAllInternal(event);
__OSUnlockScheduler();
}
/************* OSRendezvous ************/
SysAllocator<OSEvent> g_rendezvousEvent;
void OSInitRendezvous(OSRendezvous* rendezvous)
{
__OSLockScheduler();
rendezvous->userData = rendezvous;
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
rendezvous->coreHit[i] = 0;
__OSUnlockScheduler();
}
bool OSWaitRendezvous(OSRendezvous* rendezvous, uint32 coreMask)
{
__OSLockScheduler();
rendezvous->coreHit[OSGetCoreId()] = 1;
OSSignalEventAllInternal(g_rendezvousEvent.GetPtr());
while (true)
{
bool metAll = true;
for(sint32 i=0; i<PPC_CORE_COUNT; i++)
{
if( (coreMask & (1<<i)) == 0 )
continue; // core not required by core mask
if (rendezvous->coreHit[i] == 0)
{
metAll = false;
break;
}
}
if (metAll)
break;
OSWaitEventInternal(g_rendezvousEvent.GetPtr());
}
__OSUnlockScheduler();
return true;
}
/************* OSMutex ************/
void OSInitMutexEx(OSMutex* mutex, void* userData)
{
mutex->magic = 'mUtX';
mutex->userData = userData;
mutex->ukn08 = 0;
mutex->owner = nullptr;
mutex->lockCount = 0;
OSInitThreadQueueEx(&mutex->threadQueue, mutex);
}
void OSInitMutex(OSMutex* mutex)
{
OSInitMutexEx(mutex, nullptr);
}
void OSLockMutexInternal(OSMutex* mutex)
{
OSThread_t* currentThread = OSGetCurrentThread();
int_fast32_t failedAttempts = 0;
while (true)
{
if (mutex->owner == nullptr)
{
// acquire lock
mutex->owner = currentThread;
cemu_assert_debug(mutex->lockCount == 0);
mutex->lockCount = 1;
// cemu_assert_debug(mutex->next == nullptr && mutex->prev == nullptr); -> not zero initialized
currentThread->mutexQueue.addMutex(mutex);
break;
}
else if (mutex->owner == currentThread)
{
mutex->lockCount = mutex->lockCount + 1;
break;
}
else
{
if (failedAttempts >= 0x800)
cemuLog_log(LogType::Force, "Detected long-term contested OSLockMutex");
currentThread->waitingForMutex = mutex;
mutex->threadQueue.queueAndWait(currentThread);
currentThread->waitingForMutex = nullptr;
failedAttempts++;
}
}
}
void OSLockMutex(OSMutex* mutex)
{
__OSLockScheduler();
OSTestThreadCancelInternal();
OSLockMutexInternal(mutex);
__OSUnlockScheduler();
}
bool OSTryLockMutex(OSMutex* mutex)
{
OSThread_t* currentThread = OSGetCurrentThread();
__OSLockScheduler();
OSTestThreadCancelInternal();
if (mutex->owner == nullptr)
{
// acquire lock
mutex->owner = currentThread;
cemu_assert_debug(mutex->lockCount == 0);
mutex->lockCount = 1;
// cemu_assert_debug(mutex->next == nullptr && mutex->prev == nullptr); -> not zero initialized
currentThread->mutexQueue.addMutex(mutex);
// currentThread->cancelState = currentThread->cancelState | 0x10000;
}
else if (mutex->owner == currentThread)
{
mutex->lockCount = mutex->lockCount + 1;
}
else
{
__OSUnlockScheduler();
return false;
}
__OSUnlockScheduler();
return true;
}
void OSUnlockMutexInternal(OSMutex* mutex)
{
OSThread_t* currentThread = OSGetCurrentThread();
cemu_assert_debug(mutex->owner == currentThread);
cemu_assert_debug(mutex->lockCount > 0);
mutex->lockCount = mutex->lockCount - 1;
if (mutex->lockCount == 0)
{
currentThread->mutexQueue.removeMutex(mutex);
mutex->owner = nullptr;
if (!mutex->threadQueue.isEmpty())
mutex->threadQueue.wakeupSingleThreadWaitQueue(true, true);
}
// currentThread->cancelState = currentThread->cancelState & ~0x10000;
}
void OSUnlockMutex(OSMutex* mutex)
{
__OSLockScheduler();
OSUnlockMutexInternal(mutex);
__OSUnlockScheduler();
}
/************* OSCond ************/
void OSInitCond(OSCond* cond)
{
cond->magic = 0x634e6456;
cond->userData = nullptr;
cond->ukn08 = 0;
OSInitThreadQueueEx(&cond->threadQueue, cond);
}
void OSInitCondEx(OSCond* cond, void* userData)
{
OSInitCond(cond);
cond->userData = userData;
}
void OSSignalCond(OSCond* cond)
{
OSWakeupThread(&cond->threadQueue);
}
void OSWaitCond(OSCond* cond, OSMutex* mutex)
{
// seen in Bayonetta 2
// releases the mutex while waiting for the condition to be signaled
__OSLockScheduler();
OSThread_t* currentThread = OSGetCurrentThread();
cemu_assert_debug(mutex->owner == currentThread);
sint32 prevLockCount = mutex->lockCount;
// unlock mutex
mutex->lockCount = 0;
currentThread->mutexQueue.removeMutex(mutex);
mutex->owner = nullptr;
if (!mutex->threadQueue.isEmpty())
mutex->threadQueue.wakeupEntireWaitQueue(false);
// wait on condition
cond->threadQueue.queueAndWait(currentThread);
// reacquire mutex
OSLockMutexInternal(mutex);
mutex->lockCount = prevLockCount;
__OSUnlockScheduler();
}
/************* OSSemaphore ************/
void OSInitSemaphoreEx(OSSemaphore* semaphore, sint32 initialCount, void* userData)
{
__OSLockScheduler();
semaphore->magic = 0x73506852;
semaphore->userData = userData;
semaphore->ukn08 = 0;
semaphore->count = initialCount;
OSInitThreadQueueEx(&semaphore->threadQueue, semaphore);
__OSUnlockScheduler();
}
void OSInitSemaphore(OSSemaphore* semaphore, sint32 initialCount)
{
OSInitSemaphoreEx(semaphore, initialCount, nullptr);
}
sint32 OSWaitSemaphoreInternal(OSSemaphore* semaphore)
{
cemu_assert_debug(__OSHasSchedulerLock());
while (true)
{
sint32 prevCount = semaphore->count;
if (prevCount > 0)
{
semaphore->count = prevCount - 1;
return prevCount;
}
semaphore->threadQueue.queueAndWait(OSGetCurrentThread());
}
}
sint32 OSWaitSemaphore(OSSemaphore* semaphore)
{
__OSLockScheduler();
sint32 r = OSWaitSemaphoreInternal(semaphore);
__OSUnlockScheduler();
return r;
}
sint32 OSTryWaitSemaphore(OSSemaphore* semaphore)
{
__OSLockScheduler();
sint32 prevCount = semaphore->count;
if (prevCount > 0)
{
semaphore->count = prevCount - 1;
}
__OSUnlockScheduler();
return prevCount;
}
sint32 OSSignalSemaphoreInternal(OSSemaphore* semaphore, bool reschedule)
{
cemu_assert_debug(__OSHasSchedulerLock());
sint32 prevCount = semaphore->count;
semaphore->count = prevCount + 1;
semaphore->threadQueue.wakeupEntireWaitQueue(reschedule);
return prevCount;
}
sint32 OSSignalSemaphore(OSSemaphore* semaphore)
{
__OSLockScheduler();
sint32 r = OSSignalSemaphoreInternal(semaphore, true);
__OSUnlockScheduler();
return r;
}
sint32 OSGetSemaphoreCount(OSSemaphore* semaphore)
{
// seen in Assassin's Creed 4
__OSLockScheduler();
sint32 currentCount = semaphore->count;
__OSUnlockScheduler();
return currentCount;
}
/************* OSFastMutex ************/
void OSFastMutex_Init(OSFastMutex* fastMutex, void* userData)
{
fastMutex->magic = 0x664d7458;
fastMutex->userData = userData;
fastMutex->owner = nullptr;
fastMutex->lockCount = 0;
fastMutex->contendedState = 0;
fastMutex->threadQueueSmall.head = nullptr;
fastMutex->threadQueueSmall.tail = nullptr;
fastMutex->ownedLink.next = nullptr;
fastMutex->ownedLink.prev = nullptr;
fastMutex->contendedLink.next = nullptr;
fastMutex->contendedLink.prev = nullptr;
}
FSpinlock g_fastMutexSpinlock;
void _OSFastMutex_AcquireContention(OSFastMutex* fastMutex)
{
g_fastMutexSpinlock.lock();
}
void _OSFastMutex_ReleaseContention(OSFastMutex* fastMutex)
{
g_fastMutexSpinlock.unlock();
}
void OSFastMutex_LockInternal(OSFastMutex* fastMutex)
{
cemu_assert_debug(!__OSHasSchedulerLock());
OSThread_t* currentThread = OSGetCurrentThread();
_OSFastMutex_AcquireContention(fastMutex);
while (true)
{
if (fastMutex->owner.atomic_compare_exchange(nullptr, currentThread))//(fastMutex->owner == nullptr)
{
// acquire lock
cemu_assert_debug(fastMutex->owner == currentThread);
cemu_assert_debug(fastMutex->lockCount == 0);
fastMutex->lockCount = 1;
// todo - add to thread owned fast mutex queue
break;
}
else if (fastMutex->owner == currentThread)
{
fastMutex->lockCount = fastMutex->lockCount + 1;
break;
}
else
{
currentThread->waitingForFastMutex = fastMutex;
__OSLockScheduler();
fastMutex->threadQueueSmall.queueOnly(currentThread);
_OSFastMutex_ReleaseContention(fastMutex);
PPCCore_switchToSchedulerWithLock();
currentThread->waitingForFastMutex = nullptr;
__OSUnlockScheduler();
_OSFastMutex_AcquireContention(fastMutex);
continue;
}
}
_OSFastMutex_ReleaseContention(fastMutex);
}
void OSFastMutex_Lock(OSFastMutex* fastMutex)
{
OSFastMutex_LockInternal(fastMutex);
}
bool OSFastMutex_TryLock(OSFastMutex* fastMutex)
{
OSThread_t* currentThread = OSGetCurrentThread();
_OSFastMutex_AcquireContention(fastMutex);
if (fastMutex->owner.atomic_compare_exchange(nullptr, currentThread))
{
// acquire lock
cemu_assert_debug(fastMutex->owner == currentThread);
cemu_assert_debug(fastMutex->lockCount == 0);
fastMutex->lockCount = 1;
// todo - add to thread owned fast mutex queue
}
else if (fastMutex->owner == currentThread)
{
fastMutex->lockCount = fastMutex->lockCount + 1;
}
else
{
_OSFastMutex_ReleaseContention(fastMutex);
return false;
}
_OSFastMutex_ReleaseContention(fastMutex);
return true;
}
void OSFastMutex_UnlockInternal(OSFastMutex* fastMutex)
{
cemu_assert_debug(!__OSHasSchedulerLock());
OSThread_t* currentThread = OSGetCurrentThread();
_OSFastMutex_AcquireContention(fastMutex);
if (fastMutex->owner != currentThread)
{
// seen in Paper Mario Color Splash
//cemuLog_log(LogType::Force, "OSFastMutex_Unlock() called on mutex which is not owned by current thread");
_OSFastMutex_ReleaseContention(fastMutex);
return;
}
cemu_assert_debug(fastMutex->lockCount > 0);
fastMutex->lockCount = fastMutex->lockCount - 1;
if (fastMutex->lockCount == 0)
{
// set owner to null
if (!fastMutex->owner.atomic_compare_exchange(currentThread, nullptr))
{
cemu_assert_debug(false); // should never happen
}
if (!fastMutex->threadQueueSmall.isEmpty())
{
__OSLockScheduler();
fastMutex->threadQueueSmall.wakeupSingleThreadWaitQueue(false);
__OSUnlockScheduler();
}
}
_OSFastMutex_ReleaseContention(fastMutex);
}
void OSFastMutex_Unlock(OSFastMutex* fastMutex)
{
//__OSLockScheduler();
OSFastMutex_UnlockInternal(fastMutex);
//__OSUnlockScheduler();
}
/************* OSFastCond ************/
void OSFastCond_Init(OSFastCond* fastCond, void* userData)
{
fastCond->magic = 0x664e6456;
fastCond->userData = userData;
fastCond->ukn08 = 0;
OSInitThreadQueueEx(&fastCond->threadQueue, fastCond);
}
void OSFastCond_Wait(OSFastCond* fastCond, OSFastMutex* fastMutex)
{
// releases the mutex while waiting for the condition to be signaled
__OSLockScheduler();
cemu_assert_debug(fastMutex->owner == OSGetCurrentThread());
sint32 prevLockCount = fastMutex->lockCount;
// unlock mutex
fastMutex->lockCount = 0;
fastMutex->owner = nullptr;
if (!fastMutex->threadQueueSmall.isEmpty())
fastMutex->threadQueueSmall.wakeupEntireWaitQueue(false);
// wait on condition
fastCond->threadQueue.queueAndWait(OSGetCurrentThread());
// reacquire mutex
__OSUnlockScheduler();
OSFastMutex_LockInternal(fastMutex);
fastMutex->lockCount = prevLockCount;
}
void OSFastCond_Signal(OSFastCond* fastCond)
{
OSWakeupThread(&fastCond->threadQueue);
}
/************* init ************/
void InitializeConcurrency()
{
OSInitEvent(g_rendezvousEvent.GetPtr(), OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_AUTO);
// OSEvent
cafeExportRegister("coreinit", OSInitEvent, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSInitEventEx, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSResetEvent, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSWaitEvent, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSWaitEventWithTimeout, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSSignalEvent, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSSignalEventAll, LogType::CoreinitThreadSync);
// OSRendezvous
cafeExportRegister("coreinit", OSInitRendezvous, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSWaitRendezvous, LogType::CoreinitThreadSync);
// OSMutex
cafeExportRegister("coreinit", OSInitMutex, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSInitMutexEx, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSLockMutex, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSTryLockMutex, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSUnlockMutex, LogType::CoreinitThreadSync);
// OSCond
cafeExportRegister("coreinit", OSInitCond, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSInitCondEx, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSSignalCond, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSWaitCond, LogType::CoreinitThreadSync);
// OSSemaphore
cafeExportRegister("coreinit", OSInitSemaphore, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSInitSemaphoreEx, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSWaitSemaphore, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSTryWaitSemaphore, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSSignalSemaphore, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSGetSemaphoreCount, LogType::CoreinitThreadSync);
// OSFastMutex
cafeExportRegister("coreinit", OSFastMutex_Init, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSFastMutex_Lock, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSFastMutex_TryLock, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSFastMutex_Unlock, LogType::CoreinitThreadSync);
// OSFastCond
cafeExportRegister("coreinit", OSFastCond_Init, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSFastCond_Wait, LogType::CoreinitThreadSync);
cafeExportRegister("coreinit", OSFastCond_Signal, LogType::CoreinitThreadSync);
}
};
| 19,044
|
C++
|
.cpp
| 600
| 28.525
| 179
| 0.738721
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,093
|
coreinit_MemoryMapping.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MemoryMapping.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "util/MemMapper/MemMapper.h"
#define OS_MAP_READ_ONLY (1)
#define OS_MAP_READ_WRITE (2)
#define VIRT_RANGE_ADDR (0xA0000000) // todo: Process specific. For the main ram pid this overlaps with the overlay arena?
#define VIRT_RANGE_SIZE (0x40000000)
#define PHYS_RANGE_ADDR (0x10000000) // todo: Process specific
#define PHYS_RANGE_SIZE (0x40000000)
namespace coreinit
{
std::mutex s_memMappingMtx;
struct OSVirtMemoryEntry
{
OSVirtMemoryEntry(MPTR virtualAddress, uint32 size, uint32 alignment) : virtualAddress(virtualAddress), size(size), alignment(alignment) {};
MPTR virtualAddress;
uint32 size;
uint32 alignment;
};
std::vector<OSVirtMemoryEntry> s_allocatedVirtMemory;
MPTR _OSAllocVirtAddr(uint32 size, uint32 alignment)
{
std::lock_guard _l(s_memMappingMtx);
uint32 currentAddress = VIRT_RANGE_ADDR;
uint32 endAddress = VIRT_RANGE_ADDR + VIRT_RANGE_SIZE;
uint32 pageSize = (uint32)MemMapper::GetPageSize();
pageSize = std::max<uint32>(pageSize, Espresso::MEM_PAGE_SIZE);
while (true)
{
// calculated aligned start and end address for current region
currentAddress = (currentAddress + alignment - 1) & ~(alignment - 1);
currentAddress = (currentAddress + pageSize - 1) & ~(pageSize - 1);
uint32 currentEndAddress = currentAddress + size;
currentEndAddress = (currentEndAddress + pageSize - 1) & ~(pageSize - 1);
// check if out of available space
if (currentEndAddress > endAddress)
{
cemuLog_log(LogType::APIErrors, "_OSAllocVirtAddr(): Unable to allocate memory\n");
return MPTR_NULL;
}
// check for overlapping regions
bool emptySpaceFound = true;
for(auto& virtMemIt : s_allocatedVirtMemory)
{
// check for range collision
if (currentAddress < (virtMemIt.virtualAddress + virtMemIt.size) && currentEndAddress > virtMemIt.virtualAddress)
{
// regions overlap
// adjust current address and keep looking
currentAddress = virtMemIt.virtualAddress + virtMemIt.size;
emptySpaceFound = false;
break;
}
}
if (emptySpaceFound)
{
// add entry
s_allocatedVirtMemory.emplace_back(currentAddress, currentEndAddress - currentAddress, alignment);
return currentAddress;
}
}
return MPTR_NULL;
}
bool _OSFreeVirtAddr(MPTR virtAddr)
{
std::lock_guard _l(s_memMappingMtx);
auto it = s_allocatedVirtMemory.begin();
while (it != s_allocatedVirtMemory.end())
{
if (it->virtualAddress == virtAddr)
{
s_allocatedVirtMemory.erase(it);
return true;
}
++it;
}
return false;
}
void OSGetAvailPhysAddrRange(uint32be* physRangeStart, uint32be* physRangeSize)
{
*physRangeStart = PHYS_RANGE_ADDR;
*physRangeSize = PHYS_RANGE_SIZE;
}
void* OSAllocVirtAddr(MEMPTR<void> address, uint32 size, uint32 align)
{
if (align == 0)
align = 1;
if (align != 0 && align != 1)
assert_dbg();
cemu_assert_debug(address == nullptr); // todo - support for allocation with fixed address
address = _OSAllocVirtAddr(size, align);
debug_printf("OSAllocVirtAddr(): Allocated virtual memory at 0x%08x\n", address.GetMPTR());
return MEMPTR<void>(address);
}
uint32 OSFreeVirtAddr(MEMPTR<void> address)
{
bool r = _OSFreeVirtAddr(address.GetMPTR());
if(!r)
cemuLog_log(LogType::APIErrors, "OSFreeVirtAddr: Could not find allocation with address 0x{:08x}\n", address.GetMPTR());
return r ? 1 : 0;
}
uint32 OSMapMemory(MPTR virtualAddress, MPTR physicalAddress, uint32 size, uint32 mode)
{
if (virtualAddress < VIRT_RANGE_ADDR || virtualAddress >= (VIRT_RANGE_ADDR + VIRT_RANGE_SIZE))
{
cemuLog_log(LogType::APIErrors, "OSMapMemory: Virtual address out of bounds\n");
return 0;
}
uint8* virtualPtr = memory_getPointerFromVirtualOffset(virtualAddress);
MemMapper::PAGE_PERMISSION pageProtect = MemMapper::PAGE_PERMISSION::P_NONE;
if (mode == OS_MAP_READ_ONLY)
pageProtect = MemMapper::PAGE_PERMISSION::P_READ;
else if (mode == OS_MAP_READ_WRITE)
pageProtect = MemMapper::PAGE_PERMISSION::P_RW;
else
cemu_assert_unimplemented();
void* allocationResult = MemMapper::AllocateMemory(virtualPtr, size, pageProtect, true);
if (!allocationResult)
{
cemuLog_log(LogType::Force, "OSMapMemory failed");
return 0;
}
return 1;
}
uint32 OSUnmapMemory(MPTR virtualAddress, uint32 size)
{
if (virtualAddress < VIRT_RANGE_ADDR || virtualAddress >= (VIRT_RANGE_ADDR + VIRT_RANGE_SIZE))
cemu_assert_suspicious();
cemu_assert((size % MemMapper::GetPageSize()) == 0);
uint8* virtualPtr = memory_getPointerFromVirtualOffset(virtualAddress);
MemMapper::FreeMemory(virtualPtr, size, true);
return 1;
}
void InitializeMemoryMapping()
{
s_allocatedVirtMemory.clear();
cafeExportRegister("coreinit", OSGetAvailPhysAddrRange, LogType::CoreinitMemoryMapping);
cafeExportRegister("coreinit", OSAllocVirtAddr, LogType::CoreinitMemoryMapping);
cafeExportRegister("coreinit", OSFreeVirtAddr, LogType::CoreinitMemoryMapping);
cafeExportRegister("coreinit", OSMapMemory, LogType::CoreinitMemoryMapping);
cafeExportRegister("coreinit", OSUnmapMemory, LogType::CoreinitMemoryMapping);
}
}
| 5,181
|
C++
|
.cpp
| 142
| 33.21831
| 142
| 0.74198
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,094
|
coreinit_MEM_FrmHeap.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MEM_FrmHeap.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_FrmHeap.h"
namespace coreinit
{
bool __FrmHeapDebug_IsValid(MEMFrmHeap* frmHeap, const char* funcName)
{
if (!frmHeap)
{
cemuLog_log(LogType::APIErrors, "{}: Heap is nullptr", funcName);
return false;
}
if (frmHeap->magic != MEMHeapMagic::FRAME_HEAP)
{
cemuLog_log(LogType::APIErrors, "{}: Heap has bad magic. Not initialized?", funcName);
return false;
}
return true;
}
MEMFrmHeap* MEMCreateFrmHeapEx(void* memStart, uint32 size, uint32 createFlags)
{
cemu_assert_debug(memStart);
uintptr_t startAddr = (uintptr_t)memStart;
uintptr_t endAddr = startAddr + size;
// align and pad address
startAddr = (startAddr + 3) & ~3;
endAddr &= ~3;
if (startAddr == 0)
return nullptr;
if (startAddr > endAddr || (endAddr - startAddr) < sizeof(MEMFrmHeap))
return nullptr;
MEMFrmHeap* frmHeap = (MEMFrmHeap*)startAddr;
MEMInitHeapBase(frmHeap, MEMHeapMagic::FRAME_HEAP, (void*)((uintptr_t)startAddr + sizeof(MEMFrmHeap)), (void*)endAddr, createFlags);
frmHeap->allocationHead = frmHeap->heapStart;
frmHeap->allocationTail = frmHeap->heapEnd;
frmHeap->recordedStates = nullptr;
MEMHeapTable_Add(frmHeap);
return frmHeap;
}
void* MEMDestroyFrmHeap(MEMFrmHeap* frmHeap)
{
if (!__FrmHeapDebug_IsValid(frmHeap, "MEMDestroyFrmHeap"))
return nullptr;
MEMBaseDestroyHeap(frmHeap);
MEMHeapTable_Remove(frmHeap);
return frmHeap;
}
uint32 MEMGetAllocatableSizeForFrmHeapEx(MEMFrmHeap* frmHeap, sint32 alignment)
{
if (!__FrmHeapDebug_IsValid(frmHeap, "MEMGetAllocatableSizeForFrmHeapEx"))
return 0;
frmHeap->AcquireLock();
uint32 allocatableSize = 0;
bool negativeAlignment = alignment < 0;
if (negativeAlignment)
alignment = -alignment;
uint32 bits = (uint32)alignment;
if (bits == 0 || (bits & (bits - 1)) != 0)
{
cemuLog_log(LogType::APIErrors, "MEMGetAllocatableSizeForFrmHeapEx(): Invalid alignment");
return 0;
}
if (negativeAlignment)
{
cemu_assert_unimplemented();
}
else
{
uint32 headAllocator = frmHeap->allocationHead.GetMPTR();
uint32 tailAllocator = frmHeap->allocationTail.GetMPTR();
uint32 allocStart = (headAllocator + alignment - 1) & ~(alignment - 1);
if (allocStart <= tailAllocator)
{
allocatableSize = tailAllocator - allocStart;
}
}
frmHeap->ReleaseLock();
return allocatableSize;
}
void* MEMiGetFreeStartForFrmHeap(MEMFrmHeap* heap)
{
if (!__FrmHeapDebug_IsValid(heap, "MEMiGetFreeStartForFrmHeap"))
return nullptr;
return heap->allocationHead;
}
void* MEMiGetFreeEndForFrmHeap(MEMFrmHeap* heap)
{
if (!__FrmHeapDebug_IsValid(heap, "MEMiGetFreeEndForFrmHeap"))
return nullptr;
return heap->allocationTail;
}
void* __FrmHeap_AllocFromHead(MEMFrmHeap* frmHeap, uint32 size, sint32 alignment)
{
uint32 head = frmHeap->allocationHead.GetMPTR();
uint32 tail = frmHeap->allocationTail.GetMPTR();
uint32 allocStart = (head + alignment - 1) & ~(alignment - 1);
if ((allocStart + size) <= tail)
{
auto prevHead = frmHeap->allocationHead;
frmHeap->allocationHead = allocStart + size;
if (frmHeap->HasOptionClear())
memset(prevHead.GetPtr(), 0, frmHeap->allocationHead.GetMPTR() - prevHead.GetMPTR());
return MEMPTR<void>(allocStart).GetPtr();
}
return nullptr;
}
void* __FrmHeap_AllocFromTail(MEMFrmHeap* frmHeap, uint32 size, sint32 alignment)
{
uint32 head = frmHeap->allocationHead.GetMPTR();
uint32 tail = frmHeap->allocationTail.GetMPTR();
uint32 allocStart = (tail - size) & ~(alignment - 1);
if (allocStart >= head)
{
auto prevTail = frmHeap->allocationTail;
frmHeap->allocationTail = allocStart;
if (frmHeap->HasOptionClear())
memset(frmHeap->allocationTail.GetPtr(), 0, prevTail.GetMPTR() - frmHeap->allocationTail.GetMPTR());
return MEMPTR<void>(allocStart).GetPtr();
}
return nullptr;
}
void* MEMAllocFromFrmHeapEx(MEMFrmHeap* frmHeap, uint32 size, sint32 alignment)
{
if (!__FrmHeapDebug_IsValid(frmHeap, "MEMAllocFromFrmHeapEx"))
return nullptr;
if (size == 0)
size = 4;
size = (size + 3) & ~3; // pad to 4 byte alignment
frmHeap->AcquireLock();
void* mem;
if (alignment >= 0)
mem = __FrmHeap_AllocFromHead(frmHeap, size, alignment);
else
mem = __FrmHeap_AllocFromTail(frmHeap, size, -alignment);
frmHeap->ReleaseLock();
return mem;
}
void __FrmHeap_FreeFromHead(MEMFrmHeap* frmHeap)
{
cemu_assert_debug(frmHeap->recordedStates.IsNull());
frmHeap->recordedStates = nullptr;
frmHeap->allocationHead = frmHeap->heapStart;
}
void __FrmHeap_FreeFromTail(MEMFrmHeap* frmHeap)
{
cemu_assert_debug(frmHeap->recordedStates.IsNull());
frmHeap->recordedStates = nullptr;
void* heapEnd = frmHeap->heapEnd.GetPtr();
frmHeap->allocationTail = heapEnd;
}
void MEMFreeToFrmHeap(MEMFrmHeap* frmHeap, FrmHeapMode mode)
{
if (!__FrmHeapDebug_IsValid(frmHeap, "MEMFreeToFrmHeap"))
return;
frmHeap->AcquireLock();
if ((mode & FrmHeapMode::Head) != 0)
__FrmHeap_FreeFromHead(frmHeap);
if ((mode & FrmHeapMode::Tail) != 0)
__FrmHeap_FreeFromTail(frmHeap);
frmHeap->ReleaseLock();
}
bool MEMRecordStateForFrmHeap(MEMFrmHeap* frmHeap, uint32 id)
{
if (!__FrmHeapDebug_IsValid(frmHeap, "MEMRecordStateForFrmHeap"))
return false;
frmHeap->AcquireLock();
auto allocationHead = frmHeap->allocationHead;
auto allocationTail = frmHeap->allocationTail;
MEMFrmHeapRecordedState* rState = (MEMFrmHeapRecordedState*)__FrmHeap_AllocFromHead(frmHeap, sizeof(MEMFrmHeapRecordedState), 4); // modifies memHeap->allocationHead
cemu_assert_debug(rState);
if (!rState)
{
frmHeap->ReleaseLock();
return false;
}
rState->id = id;
rState->allocationHead = allocationHead;
rState->allocationTail = allocationTail;
rState->prevRecordedState = frmHeap->recordedStates;
frmHeap->recordedStates = rState;
frmHeap->ReleaseLock();
return true;
}
bool MEMFreeByStateToFrmHeap(MEMFrmHeap* frmHeap, uint32 id)
{
if (!__FrmHeapDebug_IsValid(frmHeap, "MEMFreeByStateToFrmHeap"))
return false;
frmHeap->AcquireLock();
// find matching state
MEMFrmHeapRecordedState* rState = frmHeap->recordedStates.GetPtr();
while (rState)
{
if (id == 0)
break;
if (rState->id == id)
break;
rState = rState->prevRecordedState.GetPtr();
}
if (!rState)
{
frmHeap->ReleaseLock();
return false;
}
// apply state
frmHeap->allocationHead = rState->allocationHead;
frmHeap->allocationTail = rState->allocationTail;
frmHeap->recordedStates = rState->prevRecordedState;
frmHeap->ReleaseLock();
return true;
}
void InitializeMEMFrmHeap()
{
cafeExportRegister("coreinit", MEMCreateFrmHeapEx, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMDestroyFrmHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetAllocatableSizeForFrmHeapEx, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMiGetFreeStartForFrmHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMiGetFreeEndForFrmHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMAllocFromFrmHeapEx, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMFreeToFrmHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMFreeToFrmHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMRecordStateForFrmHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMFreeByStateToFrmHeap, LogType::CoreinitMem);
}
}
| 7,538
|
C++
|
.cpp
| 224
| 30.566964
| 167
| 0.744789
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,095
|
coreinit_Alarm.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Alarm.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "Cafe/OS/RPL/rpl.h"
// #define ALARM_LOGGING
namespace coreinit
{
SysAllocator<OSEvent> g_alarmEvent;
SysAllocator<OSThread_t> g_alarmThread;
SysAllocator<uint8, 1024 * 128> _g_alarmThreadStack;
SysAllocator<char, 32> _g_alarmThreadName;
class OSHostAlarm
{
public:
OSHostAlarm(uint64 nextFire, uint64 period, void(*callbackFunc)(uint64 currentTick, void* context), void* context) : m_nextFire(nextFire), m_period(period), m_callbackFunc(callbackFunc), m_context(context)
{
cemu_assert_debug(__OSHasSchedulerLock()); // must hold lock
auto r = g_activeAlarmList.emplace(this);
cemu_assert_debug(r.second); // check if insertion was successful
m_isActive = true;
updateEarliestAlarmAtomic();
}
~OSHostAlarm()
{
cemu_assert_debug(__OSHasSchedulerLock()); // must hold lock
if (m_isActive)
{
g_activeAlarmList.erase(g_activeAlarmList.find(this));
updateEarliestAlarmAtomic();
}
}
uint64 getFireTick() const
{
return m_nextFire;
}
void triggerAlarm(uint64 currentTick)
{
m_callbackFunc(currentTick, m_context);
}
static void updateEarliestAlarmAtomic()
{
cemu_assert_debug(__OSHasSchedulerLock());
if (!g_activeAlarmList.empty())
{
auto firstAlarm = g_activeAlarmList.begin();
g_soonestAlarm = (*firstAlarm)->m_nextFire;
}
else
{
g_soonestAlarm = std::numeric_limits<uint64>::max();
}
}
static void updateAlarms(uint64 currentTick)
{
cemu_assert_debug(__OSHasSchedulerLock());
if (g_activeAlarmList.empty())
return;
// debug begin
#ifdef CEMU_DEBUG_ASSERT
uint64 prevTick = 0;
auto itr = g_activeAlarmList.begin();
while (itr != g_activeAlarmList.end())
{
uint64 t = (*itr)->m_nextFire;
if (t < prevTick)
cemu_assert_suspicious();
prevTick = t;
++itr;
}
#endif
// debug end
while (true)
{
auto firstAlarm = g_activeAlarmList.begin();
if (currentTick >= (*firstAlarm)->m_nextFire)
{
OSHostAlarm* alarm = *firstAlarm;
g_activeAlarmList.erase(firstAlarm);
alarm->triggerAlarm(currentTick);
// if periodic alarm then requeue
if (alarm->m_period > 0)
{
alarm->m_nextFire += alarm->m_period;
g_activeAlarmList.emplace(alarm);
}
else
alarm->m_isActive = false;
updateEarliestAlarmAtomic();
}
else
break;
}
}
uint64 getNextFire() const
{
return m_nextFire;
}
static bool quickCheckForAlarm(uint64 currentTick)
{
// fast way to check if any alarm was triggered without requiring scheduler lock
return currentTick >= g_soonestAlarm;
}
static void Reset()
{
g_activeAlarmList.clear();
g_soonestAlarm = 0;
}
public:
struct ComparatorFireTime
{
bool operator ()(OSHostAlarm* const & p1, OSHostAlarm* const & p2) const
{
auto p1Fire = p1->getNextFire();
auto p2Fire = p2->getNextFire();
if (p1Fire == p2Fire)
return (uintptr_t)p1 < (uintptr_t)p2; // if time is equal, differ by pointer (to allow storing multiple alarms with same firing time)
return p1Fire < p2Fire;
}
};
private:
uint64 m_nextFire;
uint64 m_period; // if zero then repeat is disabled
bool m_isActive{ false };
void (*m_callbackFunc)(uint64 currentTick, void* context);
void* m_context;
static std::set<class OSHostAlarm*, ComparatorFireTime> g_activeAlarmList;
static std::atomic_uint64_t g_soonestAlarm;
};
std::set<class OSHostAlarm*, OSHostAlarm::ComparatorFireTime> OSHostAlarm::g_activeAlarmList;
std::atomic_uint64_t OSHostAlarm::g_soonestAlarm{};
OSHostAlarm* OSHostAlarmCreate(uint64 nextFire, uint64 period, void(*callbackFunc)(uint64 currentTick, void* context), void* context)
{
OSHostAlarm* hostAlarm = new OSHostAlarm(nextFire, period, callbackFunc, context);
return hostAlarm;
}
void OSHostAlarmDestroy(OSHostAlarm* hostAlarm)
{
delete hostAlarm;
}
void alarm_update()
{
cemu_assert_debug(!__OSHasSchedulerLock());
uint64 currentTick = coreinit::coreinit_getOSTime();
if (!OSHostAlarm::quickCheckForAlarm(currentTick))
return;
__OSLockScheduler();
OSHostAlarm::updateAlarms(currentTick);
__OSUnlockScheduler();
}
/* alarm API */
void OSCreateAlarm(OSAlarm_t* alarm)
{
memset(alarm, 0, sizeof(OSAlarm_t));
alarm->setMagic();
}
void OSCreateAlarmEx(OSAlarm_t* alarm, const char* alarmName)
{
memset(alarm, 0, sizeof(OSAlarm_t));
alarm->setMagic();
alarm->name = alarmName;
}
std::unordered_map<OSAlarm_t*, OSHostAlarm*> g_activeAlarms;
bool OSCancelAlarm(OSAlarm_t* alarm)
{
__OSLockScheduler();
bool alarmWasActive = false;
auto itr = g_activeAlarms.find(alarm);
if (itr != g_activeAlarms.end())
{
OSHostAlarmDestroy(itr->second);
g_activeAlarms.erase(itr);
alarmWasActive = true;
}
__OSUnlockScheduler();
return alarmWasActive;
}
void __OSHostAlarmTriggered(uint64 currentTick, void* context)
{
#ifdef ALARM_LOGGING
cemuLog_log(LogType::Force, "[Alarm] Alarm ready and alarm thread signalled. Current tick: {}", currentTick);
#endif
OSSignalEventInternal(g_alarmEvent.GetPtr());
}
void __OSInitiateAlarm(OSAlarm_t* alarm, uint64 startTime, uint64 period, MPTR handlerFunc, bool isPeriodic)
{
cemu_assert_debug(MMU_IsInPPCMemorySpace(alarm));
cemu_assert_debug(__OSHasSchedulerLock());
uint64 nextTime = startTime;
#ifdef ALARM_LOGGING
double periodInMS = (double)period * 1000.0 / (double)EspressoTime::GetTimerClock();
cemuLog_log(LogType::Force, "[Alarm] Start alarm 0x{:08x}. Func 0x{:08x}. Period: {}ms", MEMPTR(alarm).GetMPTR(), handlerFunc, periodInMS);
#endif
if (isPeriodic)
{
cemu_assert_debug(period != 0);
if (period == 0)
return;
uint64 currentTime = coreinit_getOSTime();
uint64 ticksSinceStart = currentTime - startTime;
uint64 numPeriods = ticksSinceStart / period;
nextTime = startTime + (numPeriods + 1ull) * period;
alarm->startTime = _swapEndianU64(startTime);
alarm->nextTime = _swapEndianU64(nextTime);
alarm->period = _swapEndianU64(period);
alarm->handler = _swapEndianU32(handlerFunc);
}
else
{
alarm->nextTime = _swapEndianU64(startTime);
alarm->period = 0;
alarm->handler = _swapEndianU32(handlerFunc);
}
auto existingAlarmItr = g_activeAlarms.find(alarm);
if (existingAlarmItr != g_activeAlarms.end())
{
// delete existing alarm
cemuLog_logDebug(LogType::Force, "__OSInitiateAlarm() called on alarm which was already active");
OSHostAlarmDestroy(existingAlarmItr->second);
g_activeAlarms.erase(existingAlarmItr);
}
g_activeAlarms[alarm] = OSHostAlarmCreate(nextTime, period, __OSHostAlarmTriggered, nullptr);
}
void OSSetAlarm(OSAlarm_t* alarm, uint64 delayInTicks, MPTR handlerFunc)
{
__OSLockScheduler();
__OSInitiateAlarm(alarm, coreinit_getOSTime() + delayInTicks, 0, handlerFunc, false);
__OSUnlockScheduler();
}
void OSSetPeriodicAlarm(OSAlarm_t* alarm, uint64 nextFire, uint64 period, MPTR handlerFunc)
{
__OSLockScheduler();
__OSInitiateAlarm(alarm, nextFire, period, handlerFunc, true);
__OSUnlockScheduler();
}
void OSSetAlarmUserData(OSAlarm_t* alarm, uint32 userData)
{
alarm->userData = userData;
}
uint32 OSGetAlarmUserData(OSAlarm_t* alarm)
{
return alarm->userData;
}
void OSAlarm_Shutdown()
{
__OSLockScheduler();
if(g_activeAlarms.empty())
{
__OSUnlockScheduler();
return;
}
for(auto& itr : g_activeAlarms)
{
OSHostAlarmDestroy(itr.second);
}
g_activeAlarms.clear();
OSHostAlarm::Reset();
__OSUnlockScheduler();
}
void _OSAlarmThread(PPCInterpreter_t* hCPU)
{
while( true )
{
OSWaitEvent(g_alarmEvent.GetPtr());
uint64 currentTick = coreinit_getOSTime();
while (true)
{
// get alarm to fire
OSAlarm_t* alarm = nullptr;
__OSLockScheduler();
auto itr = g_activeAlarms.begin();
while(itr != g_activeAlarms.end())
{
if (currentTick >= _swapEndianU64(itr->first->nextTime))
{
alarm = itr->first;
if (alarm->period == 0)
{
// end alarm
g_activeAlarms.erase(itr);
break;
}
else
{
alarm->nextTime = _swapEndianU64(_swapEndianU64(alarm->nextTime) + _swapEndianU64(alarm->period));
}
break;
}
++itr;
}
__OSUnlockScheduler();
if (!alarm)
break;
// do callback for alarm
#ifdef ALARM_LOGGING
double periodInMS = (double)_swapEndianU64(alarm->period) * 1000.0 / (double)EspressoTime::GetTimerClock();
cemuLog_log(LogType::Force, "[Alarm] Callback 0x{:08x} for alarm 0x{:08x}. Current tick: {}. Period: {}ms", _swapEndianU32(alarm->handler), MEMPTR(alarm).GetMPTR(), currentTick, periodInMS);
#endif
PPCCoreCallback(_swapEndianU32(alarm->handler), alarm, &(g_alarmThread.GetPtr()->context));
}
}
}
void InitializeAlarm()
{
cafeExportRegister("coreinit", OSCreateAlarm, LogType::CoreinitAlarm);
cafeExportRegister("coreinit", OSCreateAlarmEx, LogType::CoreinitAlarm);
cafeExportRegister("coreinit", OSCancelAlarm, LogType::CoreinitAlarm);
cafeExportRegister("coreinit", OSSetAlarm, LogType::CoreinitAlarm);
cafeExportRegister("coreinit", OSSetPeriodicAlarm, LogType::CoreinitAlarm);
cafeExportRegister("coreinit", OSSetAlarmUserData, LogType::CoreinitAlarm);
cafeExportRegister("coreinit", OSGetAlarmUserData, LogType::CoreinitAlarm);
// init event
OSInitEvent(g_alarmEvent.GetPtr(), OSEvent::EVENT_STATE::STATE_NOT_SIGNALED, OSEvent::EVENT_MODE::MODE_AUTO);
// create alarm callback handler thread
coreinit::OSCreateThreadType(g_alarmThread.GetPtr(), RPLLoader_MakePPCCallable(_OSAlarmThread), 0, nullptr, _g_alarmThreadStack.GetPtr() + _g_alarmThreadStack.GetByteSize(), (sint32)_g_alarmThreadStack.GetByteSize(), 0, 0x7, OSThread_t::THREAD_TYPE::TYPE_IO);
OSResumeThread(g_alarmThread.GetPtr());
strcpy(_g_alarmThreadName.GetPtr(), "Alarm Thread");
coreinit::OSSetThreadName(g_alarmThread.GetPtr(), _g_alarmThreadName.GetPtr());
}
}
| 10,402
|
C++
|
.cpp
| 322
| 28.263975
| 261
| 0.710996
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,096
|
coreinit_MEM_UnitHeap.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MEM_UnitHeap.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_UnitHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_Spinlock.h"
namespace coreinit
{
void _MEMUnitHeap_IsValidHeap(MEMHeapHandle heap)
{
cemu_assert(heap != MEM_HEAP_INVALID_HANDLE);
cemu_assert(heap->magic == MEMHeapMagic::UNIT_HEAP);
}
MEMHeapBase* MEMCreateUnitHeapEx(void* memStart, uint32 heapSize, uint32 blockSize, uint32 alignment, uint32 createFlags)
{
cemu_assert_debug(memStart != nullptr);
cemu_assert_debug(alignment % MIN_ALIGNMENT == 0);
cemu_assert_debug(MIN_ALIGNMENT <= alignment && alignment <= 32);
uintptr_t startAddr = (uintptr_t)memStart;
uintptr_t endAddr = startAddr + heapSize;
startAddr = (startAddr + MIN_ALIGNMENT_MINUS_ONE) & (~MIN_ALIGNMENT_MINUS_ONE);
endAddr &= (~MIN_ALIGNMENT_MINUS_ONE);
if (startAddr > endAddr)
return nullptr;
const uint32 alignmentMinusOne = alignment - 1;
MEMUnitHeap* unitHeap = (MEMUnitHeap*)startAddr;
uintptr_t alignedStart = startAddr + sizeof(MEMUnitHeap) + alignmentMinusOne & ~((uintptr_t)alignmentMinusOne);
if (alignedStart > endAddr)
return nullptr;
blockSize = blockSize + alignmentMinusOne & ~alignmentMinusOne;
uint32 totalBlockSize = (uint32)(endAddr - alignedStart);
uint32 numBlocks = totalBlockSize / blockSize;
if (numBlocks == 0)
return nullptr;
MEMInitHeapBase(unitHeap, MEMHeapMagic::UNIT_HEAP, (void*)alignedStart, (void*)(alignedStart + (numBlocks * blockSize)), createFlags);
unitHeap->firstFreeBlock = (MEMUnitHeapBlock*)alignedStart;
unitHeap->blockSize = blockSize;
MEMUnitHeapBlock* currentBlock = (MEMUnitHeapBlock*)alignedStart;
for (uint32 i = 0; i < numBlocks - 1; ++i)
{
MEMUnitHeapBlock* nextBlock = (MEMUnitHeapBlock*)((uintptr_t)currentBlock + blockSize);
currentBlock->nextBlock = nextBlock;
currentBlock = nextBlock;
}
currentBlock->nextBlock = nullptr;
if ((MEMHeapHandle*)startAddr != nullptr)
{
MEMHeapTable_Add((MEMHeapHandle)startAddr);
}
return (MEMHeapBase*)startAddr;
}
void* MEMDestroyUnitHeap(MEMHeapHandle heap)
{
_MEMUnitHeap_IsValidHeap(heap);
MEMBaseDestroyHeap(heap);
MEMHeapTable_Remove(heap);
return heap;
}
uint32 MEMCalcHeapSizeForUnitHeap(uint32 blockSize, uint32 blockCount, uint32 alignment)
{
uint32 alignedBlockSize = (blockSize + (alignment - 1)) & ~(alignment - 1);
uint32 blockTotalSize = blockCount * alignedBlockSize;
uint32 heapSize = blockTotalSize + (alignment - 4) + sizeof(MEMUnitHeap);
return heapSize;
}
uint32 MEMCountFreeBlockForUnitHeap(coreinit::MEMUnitHeap* heap)
{
_MEMUnitHeap_IsValidHeap(heap);
heap->AcquireLock();
MEMUnitHeapBlock* currentBlock = heap->firstFreeBlock;
uint32 blockCount = 0;
while (currentBlock)
{
blockCount++;
currentBlock = currentBlock->nextBlock;
}
heap->ReleaseLock();
return blockCount;
}
void* MEMAllocFromUnitHeap(MEMUnitHeap* heap)
{
_MEMUnitHeap_IsValidHeap(heap);
heap->AcquireLock();
MEMUnitHeapBlock* currentBlock = heap->firstFreeBlock;
if (!currentBlock)
{
heap->ReleaseLock();
return nullptr;
}
// remove from list of free blocks
heap->firstFreeBlock = currentBlock->nextBlock;
// fill block
if (heap->HasOptionClear())
{
memset(currentBlock, 0, heap->blockSize);
}
else if (heap->HasOptionFill())
{
memset(currentBlock, coreinit::MEMGetFillValForHeap(coreinit::HEAP_FILL_TYPE::ON_ALLOC), heap->blockSize);
}
heap->ReleaseLock();
return currentBlock;
}
void MEMFreeToUnitHeap(MEMUnitHeap* heap, void* mem)
{
_MEMUnitHeap_IsValidHeap(heap);
if (!mem)
return;
heap->AcquireLock();
cemu_assert_debug(mem >= heap->heapStart.GetPtr() && mem < heap->heapEnd.GetPtr());
// add to list of free blocks
MEMUnitHeapBlock* releasedBlock = (MEMUnitHeapBlock*)mem;
releasedBlock->nextBlock = heap->firstFreeBlock;
heap->firstFreeBlock = releasedBlock;
if (heap->HasOptionFill())
memset(releasedBlock, coreinit::MEMGetFillValForHeap(coreinit::HEAP_FILL_TYPE::ON_FREE), heap->blockSize);
heap->ReleaseLock();
}
void InitializeMEMUnitHeap()
{
cafeExportRegister("coreinit", MEMCreateUnitHeapEx, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMDestroyUnitHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMCalcHeapSizeForUnitHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMCountFreeBlockForUnitHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMAllocFromUnitHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMFreeToUnitHeap, LogType::CoreinitMem);
}
}
| 4,649
|
C++
|
.cpp
| 126
| 33.920635
| 136
| 0.760382
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,097
|
coreinit_DynLoad.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_DynLoad.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/coreinit/coreinit_DynLoad.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
namespace coreinit
{
MPTR _osDynLoadFuncAlloc = MPTR_NULL;
MPTR _osDynLoadFuncFree = MPTR_NULL;
MPTR _osDynLoadTLSFuncAlloc = MPTR_NULL;
MPTR _osDynLoadTLSFuncFree = MPTR_NULL;
uint32 OSDynLoad_SetAllocator(MPTR allocFunc, MPTR freeFunc)
{
_osDynLoadFuncAlloc = allocFunc;
_osDynLoadFuncFree = freeFunc;
return 0;
}
void OSDynLoad_SetTLSAllocator(MPTR allocFunc, MPTR freeFunc)
{
_osDynLoadTLSFuncAlloc = allocFunc;
_osDynLoadTLSFuncFree = freeFunc;
}
uint32 OSDynLoad_GetAllocator(betype<MPTR>* funcAlloc, betype<MPTR>* funcFree)
{
*funcAlloc = _osDynLoadFuncAlloc;
*funcFree = _osDynLoadFuncFree;
return 0;
}
void OSDynLoad_GetTLSAllocator(betype<MPTR>* funcAlloc, betype<MPTR>* funcFree)
{
*funcAlloc = _osDynLoadTLSFuncAlloc;
*funcFree = _osDynLoadTLSFuncFree;
}
void* OSDynLoad_AllocatorAlloc(sint32 size, sint32 alignment)
{
if (_osDynLoadFuncAlloc == MPTR_NULL)
return MPTR_NULL;
StackAllocator<MEMPTR<void>> _ptrStorage;
int r = PPCCoreCallback(_osDynLoadFuncAlloc, size, alignment, _ptrStorage.GetMPTR());
if (r != 0)
{
cemu_assert_debug(false);
return MPTR_NULL;
}
return _ptrStorage->GetPtr();
}
void OSDynLoad_AllocatorFree(void* mem)
{
if (_osDynLoadFuncFree == MPTR_NULL)
return;
MEMPTR<void> _mem = mem;
PPCCoreCallback(_osDynLoadFuncFree, _mem);
}
uint32 OSDynLoad_Acquire(const char* libName, uint32be* moduleHandleOut)
{
// truncate path
sint32 fileNameStartIndex = 0;
sint32 tempLen = (sint32)strlen(libName);
for (sint32 i = tempLen - 1; i >= 0; i--)
{
if (libName[i] == '/')
{
fileNameStartIndex = i + 1;
break;
}
}
// truncate file extension
char tempLibName[512];
strcpy(tempLibName, libName + fileNameStartIndex);
tempLen = (sint32)strlen(tempLibName);
for (sint32 i = tempLen - 1; i >= 0; i--)
{
if (tempLibName[i] == '.')
{
tempLibName[i] = '\0';
break;
}
}
// search for loaded modules with matching name
uint32 rplHandle = RPLLoader_GetHandleByModuleName(libName);
if (rplHandle == RPL_INVALID_HANDLE && !RPLLoader_HasDependency(libName))
{
RPLLoader_AddDependency(libName);
RPLLoader_UpdateDependencies();
RPLLoader_Link();
RPLLoader_CallEntrypoints();
rplHandle = RPLLoader_GetHandleByModuleName(libName);
}
if (rplHandle == RPL_INVALID_HANDLE)
*moduleHandleOut = 0;
else
*moduleHandleOut = rplHandle;
if (rplHandle == RPL_INVALID_HANDLE)
{
cemuLog_logDebug(LogType::Force, "OSDynLoad_Acquire() failed to load module '{}'", libName);
return 0xFFFCFFE9; // module not found
}
return 0;
}
void OSDynLoad_Release(uint32 moduleHandle)
{
if (moduleHandle == RPL_INVALID_HANDLE)
return;
RPLLoader_RemoveDependency(moduleHandle);
RPLLoader_UpdateDependencies();
}
uint32 OSDynLoad_FindExport(uint32 moduleHandle, uint32 isData, const char* exportName, betype<MPTR>* addrOut)
{
if (moduleHandle == 0xFFFFFFFF)
{
// main module
// Assassins Creed 4 has this handle hardcoded
moduleHandle = RPLLoader_GetMainModuleHandle();
}
MPTR exportResult = RPLLoader_FindModuleOrHLEExport(moduleHandle, isData, exportName);
*addrOut = exportResult;
if (exportResult == MPTR_NULL)
return 0xFFFFFFFF;
return 0;
}
void InitializeDynLoad()
{
cafeExportRegister("coreinit", OSDynLoad_SetAllocator, LogType::Placeholder);
cafeExportRegister("coreinit", OSDynLoad_SetTLSAllocator, LogType::Placeholder);
cafeExportRegister("coreinit", OSDynLoad_GetAllocator, LogType::Placeholder);
cafeExportRegister("coreinit", OSDynLoad_GetTLSAllocator, LogType::Placeholder);
cafeExportRegister("coreinit", OSDynLoad_Acquire, LogType::Placeholder);
cafeExportRegister("coreinit", OSDynLoad_Release, LogType::Placeholder);
cafeExportRegister("coreinit", OSDynLoad_FindExport, LogType::Placeholder);
}
}
| 4,057
|
C++
|
.cpp
| 131
| 28
| 111
| 0.747764
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,098
|
coreinit_MEM_BlockHeap.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_MEM_BlockHeap.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM_BlockHeap.h"
namespace coreinit
{
MEMHeapHandle MEMInitBlockHeap(MEMBlockHeap2_t* memStart, void* startAddr, void* endAddr, void* initTrackMem, uint32 initTrackMemSize, uint32 createFlags)
{
if (memStart == nullptr || startAddr == nullptr || endAddr == nullptr || (uintptr_t)startAddr >= (uintptr_t)endAddr)
return nullptr;
if (initTrackMemSize == 0)
initTrackMem = nullptr;
else if (initTrackMem == nullptr)
initTrackMemSize = 0;
MEMInitHeapBase(memStart, MEMHeapMagic::BLOCK_HEAP, startAddr, endAddr, createFlags);
memStart->track.addrStart = startAddr;
memStart->track.addrEnd = (void*)((uintptr_t)endAddr - 1);
memStart->track.isFree = 1;
memStart->track.previousBlock = nullptr;
memStart->track.nextBlock = nullptr;
memStart->headBlock = &memStart->track;
memStart->tailBlock = &memStart->track;
memStart->nextFreeBlock = nullptr;
memStart->freeBlocksLeft = 0;
uint8 flags = memStart->flags;
if(HAS_FLAG(flags, MEM_HEAP_OPTION_FILL))
{
cemu_assert_unimplemented();
}
if(initTrackMemSize != 0)
{
sint32 result = MEMAddBlockHeapTracking(MEMPTR<void>(memStart).GetMPTR(), MEMPTR<void>(initTrackMem).GetMPTR(), initTrackMemSize);
if(result != 0)
{
MEMBaseDestroyHeap(memStart);
return nullptr;
}
}
MEMHeapTable_Add(memStart);
return memStart;
}
void* MEMDestroyBlockHeap(MEMHeapHandle hHeap)
{
if (!hHeap)
return nullptr;
cemu_assert_debug(hHeap->magic == MEMHeapMagic::BLOCK_HEAP);
MEMBaseDestroyHeap(hHeap);
MEMHeapTable_Remove(hHeap);
memset(hHeap, 0x00, sizeof(MEMBlockHeap2_t));
return hHeap;
}
sint32 MEMGetAllocatableSizeForBlockHeapEx(MEMBlockHeap2_t* blockHeap, sint32 alignment)
{
if (!blockHeap || blockHeap->magic != MEMHeapMagic::BLOCK_HEAP)
{
cemuLog_log(LogType::Force, "MEMGetAllocatableSizeForBlockHeapEx(): Not a valid block heap");
return 0;
}
if (alignment < 0)
alignment = -alignment;
else if (alignment == 0)
alignment = 4;
if (HAS_FLAG(blockHeap->flags, MEM_HEAP_OPTION_THREADSAFE))
OSUninterruptibleSpinLock_Acquire(&blockHeap->spinlock);
MEMBlockHeapTrack2_t* track = (MEMBlockHeapTrack2_t*)blockHeap->headBlock.GetPtr();
uint32 allocatableSize = 0;
while (track)
{
if (track->isFree != 0)
{
uint32 addrStart = track->addrStart.GetMPTR();
uint32 addrEnd = track->addrEnd.GetMPTR();
uint32 alignmentMinusOne = alignment - 1;
uint32 alignedAddrStart = ((addrStart + alignmentMinusOne) / alignment) * alignment;
if (alignedAddrStart <= addrEnd)
{
uint32 size = (addrEnd + 1) - alignedAddrStart;
allocatableSize = std::max(allocatableSize, size);
}
}
// next
track = (MEMBlockHeapTrack2_t*)track->nextBlock.GetPtr();
}
if (HAS_FLAG(blockHeap->flags, MEM_HEAP_OPTION_THREADSAFE))
OSUninterruptibleSpinLock_Release(&blockHeap->spinlock);
return allocatableSize;
}
void MEMDumpBlockHeap(MPTR heap);
typedef struct
{
/* +0x00 */ uint32 addrStart;
/* +0x04 */ uint32 addrEnd;
/* +0x08 */ uint32 isFree; // if 0 -> block is used
/* +0x0C */ MPTR previousBlock;
/* +0x10 */ MPTR nextBlock;
}MEMBlockHeapTrackDEPR;
typedef struct
{
/* +0x00 */ uint32 ukn00;
/* +0x04 */ uint32 ukn04;
/* +0x08 */ uint32 trackArray;
/* +0x0C */ uint32 trackCount;
}MEMBlockHeapGroupDEPR;
typedef struct
{
/* +0x000 */ betype<MEMHeapMagic> magic;
/* +0x004 */ MEMLink_t link;
/* +0x00C */ MEMList_t childList;
/* +0x018 */ MPTR heapStart;
/* +0x01C */ MPTR heapEnd;
/* +0x020 */ coreinit::OSSpinLock spinlock;
/* +0x030 */
union
{
uint32 val;
uint32 flags;
}
attribute;
// start of block heap header
/* +0x034 */ uint8 ukn034[0x50 - 0x34]; // ?
/* +0x050 */ MEMBlockHeapTrackDEPR nullBlockTrack;
/* +0x064 */ MPTR headBlock;
/* +0x068 */ MPTR tailBlock;
/* +0x06C */ MPTR nextFreeBlock;
/* +0x070 */ uint32 freeBlocksLeft;
}MEMBlockHeapDEPR;
void _blockHeapDebugVerifyIfBlockIsLinked(MEMBlockHeapDEPR* blockHeapHead, MEMBlockHeapTrackDEPR* track)
{
//MEMBlockHeapTrack_t* trackItr = (MEMBlockHeapTrack_t*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->firstBlock));
//MEMBlockHeapTrack_t* prevHistory[4];
//while( trackItr )
//{
// if( trackItr == track )
// {
// debug_printf("PrevBlock3 %08x\n", memory_getVirtualOffsetFromPointer(prevHistory[0]));
// debug_printf("PrevBlock2 %08x\n", memory_getVirtualOffsetFromPointer(prevHistory[1]));
// debug_printf("PrevBlock1 %08x\n", memory_getVirtualOffsetFromPointer(prevHistory[2]));
// debug_printf("PrevBlock0 %08x\n", memory_getVirtualOffsetFromPointer(prevHistory[3]));
// assert_dbg();
// }
// prevHistory[3] = prevHistory[2];
// prevHistory[2] = prevHistory[1];
// prevHistory[1] = prevHistory[0];
// prevHistory[0] = trackItr;
// // next
// trackItr = (MEMBlockHeapTrack_t*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(trackItr->nextBlock));
//}
}
void _blockHeapDebugVerifyLinkOrder(MEMBlockHeapDEPR* blockHeapHead)
{
//MEMBlockHeapTrack_t* trackItr = (MEMBlockHeapTrack_t*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->firstBlock));
//MEMBlockHeapTrack_t* prev = NULL;
//while( trackItr )
//{
// MPTR prevMPTR = memory_getVirtualOffsetFromPointer(prev);
// if( _swapEndianU32(trackItr->previousBlock) != prevMPTR )
// assert_dbg();
// // next
// prev = trackItr;
// trackItr = (MEMBlockHeapTrack_t*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(trackItr->nextBlock));
//}
}
sint32 MEMAddBlockHeapTracking(MPTR heap, MPTR trackMem, uint32 trackMemSize)
{
MEMBlockHeapDEPR* blockHeapHead = (MEMBlockHeapDEPR*)memory_getPointerFromVirtualOffset(heap);
if (blockHeapHead->magic != MEMHeapMagic::BLOCK_HEAP)
{
return 0;
}
if (trackMem == MPTR_NULL || trackMemSize <= (sizeof(MEMBlockHeapGroupDEPR) + sizeof(MEMBlockHeapTrackDEPR)))
{
return -4;
}
uint32 trackCount = (trackMemSize - sizeof(MEMBlockHeapGroupDEPR)) / sizeof(MEMBlockHeapTrackDEPR);
MEMBlockHeapGroupDEPR* group = (MEMBlockHeapGroupDEPR*)memory_getPointerFromVirtualOffset(trackMem);
group->ukn00 = _swapEndianU32(0);
group->ukn04 = _swapEndianU32(0);
group->trackArray = _swapEndianU32(trackMem + sizeof(MEMBlockHeapGroupDEPR));
group->trackCount = _swapEndianU32(trackCount);
MEMBlockHeapTrackDEPR* track = (MEMBlockHeapTrackDEPR*)(group + 1);
track[0].previousBlock = _swapEndianU32(0);
if (trackCount > 1)
{
for (uint32 i = 0; i < trackCount - 1; i++)
{
track[i].nextBlock = _swapEndianU32(memory_getVirtualOffsetFromPointer(track + i + 1));
track[i + 1].previousBlock = _swapEndianU32(0);
}
}
// todo: Use spinlock from heap (and only use it if threadsafe heap flag is set)
__OSLockScheduler();
track[trackCount - 1].nextBlock = blockHeapHead->nextFreeBlock;
blockHeapHead->nextFreeBlock = _swapEndianU32(memory_getVirtualOffsetFromPointer(track));
blockHeapHead->freeBlocksLeft = _swapEndianU32(_swapEndianU32(blockHeapHead->freeBlocksLeft) + trackCount);
__OSUnlockScheduler();
return 0;
}
uint32 MEMGetTrackingLeftInBlockHeap(MPTR heap)
{
MEMBlockHeapDEPR* blockHeapHead = (MEMBlockHeapDEPR*)memory_getPointerFromVirtualOffset(heap);
if (blockHeapHead->magic != MEMHeapMagic::BLOCK_HEAP)
{
return 0;
}
return _swapEndianU32(blockHeapHead->freeBlocksLeft);
}
MPTR _MEMBlockHeap_GetFreeBlockTrack(MEMBlockHeapDEPR* blockHeapHead)
{
MPTR trackMPTR = _swapEndianU32(blockHeapHead->nextFreeBlock);
MEMBlockHeapTrackDEPR* track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(trackMPTR);
MPTR nextFreeBlockMPTR = _swapEndianU32(track->nextBlock); // for unreserved tracks, nextBlock holds the next unreserved block
track->nextBlock = _swapEndianU32(MPTR_NULL);
blockHeapHead->nextFreeBlock = _swapEndianU32(nextFreeBlockMPTR);
if (_swapEndianU32(blockHeapHead->freeBlocksLeft) == 0)
{
cemuLog_log(LogType::Force, "BlockHeap: No free blocks left");
assert_dbg();
}
blockHeapHead->freeBlocksLeft = _swapEndianU32(_swapEndianU32(blockHeapHead->freeBlocksLeft) - 1);
return trackMPTR;
}
/*
* Release MEMBlockHeapTrack_t struct for block heap
*/
void _MEMBlockHeap_ReleaseBlockTrack(MEMBlockHeapDEPR* blockHeapHead, MPTR trackMPTR)
{
MEMBlockHeapTrackDEPR* track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(trackMPTR);
track->nextBlock = blockHeapHead->nextFreeBlock;
blockHeapHead->nextFreeBlock = _swapEndianU32(trackMPTR);
blockHeapHead->freeBlocksLeft = _swapEndianU32(_swapEndianU32(blockHeapHead->freeBlocksLeft) + 1);
}
sint32 _MEMBlockHeap_AllocAtBlock(MEMBlockHeapDEPR* blockHeapHead, MEMBlockHeapTrackDEPR* track, MPTR allocationAddress, uint32 size)
{
MPTR trackMPTR = memory_getVirtualOffsetFromPointer(track);
uint32 trackEndAddr = _swapEndianU32(track->addrEnd);
uint32 prefixBlockSize = allocationAddress - _swapEndianU32(track->addrStart);
uint32 suffixBlockSize = (_swapEndianU32(track->addrEnd) + 1) - (allocationAddress + size);
if (prefixBlockSize > 0 && suffixBlockSize > 0)
{
// requires two free blocks
if (_swapEndianU32(blockHeapHead->freeBlocksLeft) < 2)
return -1;
}
else if (prefixBlockSize > 0 || suffixBlockSize > 0)
{
// requires one free block
if (_swapEndianU32(blockHeapHead->freeBlocksLeft) < 1)
return -2;
}
MPTR currentPreviousTrack = _swapEndianU32(track->previousBlock);
// remove used block from chain of free blocks (debug)
if (track->isFree != _swapEndianU32(0))
{
// check if block is in list of free blocks (it shouldnt be)
MEMBlockHeapTrackDEPR* trackItr = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->nextFreeBlock));
while (trackItr)
{
if (trackItr == track)
assert_dbg();
// next
trackItr = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(trackItr->nextBlock));
}
}
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
// create prefix block
if (prefixBlockSize > 0)
{
uint32 blockRangeStart = _swapEndianU32(track->addrStart);
uint32 blockRangeEnd = allocationAddress - 1;
MPTR prefixTrackMPTR = _MEMBlockHeap_GetFreeBlockTrack(blockHeapHead);
MEMBlockHeapTrackDEPR* prefixTrack = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(prefixTrackMPTR);
prefixTrack->isFree = _swapEndianU32(1);
prefixTrack->addrStart = _swapEndianU32(blockRangeStart);
prefixTrack->addrEnd = _swapEndianU32(blockRangeEnd);
// register new firstBlock
if (blockHeapHead->headBlock == _swapEndianU32(trackMPTR))
blockHeapHead->headBlock = _swapEndianU32(prefixTrackMPTR);
// update link in original previous block
if (_swapEndianU32(track->previousBlock) != MPTR_NULL)
{
MEMBlockHeapTrackDEPR* tempTrack = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(_swapEndianU32(track->previousBlock));
tempTrack->nextBlock = _swapEndianU32(prefixTrackMPTR);
}
// update previous/next track link
prefixTrack->nextBlock = _swapEndianU32(trackMPTR);
prefixTrack->previousBlock = _swapEndianU32(currentPreviousTrack);
// set prefix track as current previous track
currentPreviousTrack = prefixTrackMPTR;
}
// update used block
track->isFree = _swapEndianU32(0);
track->addrStart = _swapEndianU32(allocationAddress);
track->addrEnd = _swapEndianU32(allocationAddress + size - 1);
track->previousBlock = _swapEndianU32(currentPreviousTrack);
currentPreviousTrack = trackMPTR;
// create suffix block
if (suffixBlockSize > 0)
{
uint32 blockRangeStart = allocationAddress + size;
uint32 blockRangeEnd = trackEndAddr;
// get suffix track
MPTR suffixTrackMPTR = _MEMBlockHeap_GetFreeBlockTrack(blockHeapHead);
MEMBlockHeapTrackDEPR* suffixTrack = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(suffixTrackMPTR);
suffixTrack->isFree = _swapEndianU32(1);
suffixTrack->addrStart = _swapEndianU32(blockRangeStart);
suffixTrack->addrEnd = _swapEndianU32(blockRangeEnd);
// update previous/next track link
suffixTrack->previousBlock = _swapEndianU32(currentPreviousTrack);
suffixTrack->nextBlock = track->nextBlock;
// update last block of heap
if (_swapEndianU32(blockHeapHead->tailBlock) == trackMPTR)
blockHeapHead->tailBlock = _swapEndianU32(suffixTrackMPTR);
// update link in original next block
if (_swapEndianU32(track->nextBlock) != MPTR_NULL)
{
MEMBlockHeapTrackDEPR* tempTrack = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(_swapEndianU32(track->nextBlock));
tempTrack->previousBlock = _swapEndianU32(suffixTrackMPTR);
}
// update next block
track->nextBlock = _swapEndianU32(suffixTrackMPTR);
}
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
// todo: Get fill value via MEMGetFillValForHeap
memset(memory_getPointerFromVirtualOffset(allocationAddress), 0x00, size);
return 0;
}
MEMBlockHeapTrackDEPR* _MEMBlockHeap_FindBlockContaining(MEMBlockHeapDEPR* blockHeapHead, MPTR memAddr)
{
MPTR heapStart = _swapEndianU32(blockHeapHead->heapStart);
MPTR heapEnd = _swapEndianU32(blockHeapHead->heapEnd);
if (memAddr < heapStart)
return NULL;
if (memAddr > heapEnd)
return NULL;
uint32 distanceToStart = memAddr - heapStart;
uint32 distanceToEnd = heapEnd - memAddr;
// todo: If distanceToStart < distanceToEnd -> Iterate starting from firstBlock, else iterate starting from lastBlock (and continue via track->previousBlock)
MEMBlockHeapTrackDEPR* track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->headBlock));
if (track == NULL)
return NULL;
while (track)
{
if (_swapEndianU32(track->addrStart) == memAddr)
return track;
// next
// todo: Should this be ->previousBlock ?
track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(track->nextBlock));
}
return NULL;
}
MPTR MEMAllocFromBlockHeapEx(MPTR heap, uint32 size, sint32 alignment)
{
MEMBlockHeapDEPR* blockHeapHead = (MEMBlockHeapDEPR*)memory_getPointerFromVirtualOffset(heap);
if (blockHeapHead->magic != MEMHeapMagic::BLOCK_HEAP)
{
return MPTR_NULL;
}
// find free block which can hold the data (including alignment)
__OSLockScheduler(); // todo: replace with spinlock from heap
if (alignment == 0)
alignment = 4;
bool allocateAtEndOfBlock = false;
if (alignment < 0)
{
allocateAtEndOfBlock = true;
alignment = -alignment;
}
MEMBlockHeapTrackDEPR* track;
if (allocateAtEndOfBlock)
track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->tailBlock));
else
track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->headBlock));
cemu_assert_debug(std::popcount<unsigned int>(alignment) == 1); // not a supported alignment value
while (track)
{
if (track->isFree != _swapEndianU32(0))
{
uint32 blockRangeStart = _swapEndianU32(track->addrStart);
uint32 blockRangeEnd = _swapEndianU32(track->addrEnd) + 1;
if (allocateAtEndOfBlock == false)
{
// calculate remaining size with proper alignment
uint32 alignedBlockRangeStart = (blockRangeStart + alignment - 1) & ~(alignment - 1);
if (alignedBlockRangeStart < blockRangeEnd)
{
uint32 allocRange = blockRangeEnd - alignedBlockRangeStart;
if (allocRange >= size)
{
sint32 allocError = _MEMBlockHeap_AllocAtBlock(blockHeapHead, track, alignedBlockRangeStart, size);
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
__OSUnlockScheduler();
if (allocError == 0)
return alignedBlockRangeStart;
return MPTR_NULL;
}
}
}
else
{
uint32 alignedBlockRangeStart = (blockRangeEnd + 1 - size) & ~(alignment - 1);
if (alignedBlockRangeStart >= blockRangeStart)
{
sint32 allocError = _MEMBlockHeap_AllocAtBlock(blockHeapHead, track, alignedBlockRangeStart, size);
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
__OSUnlockScheduler();
if (allocError == 0)
return alignedBlockRangeStart;
return MPTR_NULL;
}
}
}
// next
if (allocateAtEndOfBlock)
track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(track->previousBlock));
else
track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(track->nextBlock));
if (track == nullptr)
break;
}
__OSUnlockScheduler();
return MPTR_NULL;
}
void MEMFreeToBlockHeap(MPTR heap, MPTR memAddr)
{
MEMBlockHeapDEPR* blockHeapHead = (MEMBlockHeapDEPR*)memory_getPointerFromVirtualOffset(heap);
if (blockHeapHead->magic != MEMHeapMagic::BLOCK_HEAP)
{
return;
}
__OSLockScheduler(); // todo: replace with spinlock from heap (if heap threadsafe flag is set)
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
MEMBlockHeapTrackDEPR* block = _MEMBlockHeap_FindBlockContaining(blockHeapHead, memAddr);
if (block != NULL)
{
MPTR blockMPTR = memory_getVirtualOffsetFromPointer(block);
#ifdef CEMU_DEBUG_ASSERT
if (block->isFree != 0)
assert_dbg();
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
#endif
// mark current block as free
block->isFree = _swapEndianU32(1);
// attempt to merge with previous block
if (_swapEndianU32(block->previousBlock) != MPTR_NULL)
{
MPTR previousBlockMPTR = _swapEndianU32(block->previousBlock);
MEMBlockHeapTrackDEPR* previousBlock = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(previousBlockMPTR);
if (_swapEndianU32(previousBlock->isFree) != 0)
{
// merge
previousBlock->addrEnd = block->addrEnd;
previousBlock->nextBlock = block->nextBlock;
if (_swapEndianU32(block->nextBlock) != MPTR_NULL)
{
MEMBlockHeapTrackDEPR* tempNextBlock = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(_swapEndianU32(block->nextBlock));
tempNextBlock->previousBlock = _swapEndianU32(previousBlockMPTR);
}
// release removed block
_MEMBlockHeap_ReleaseBlockTrack(blockHeapHead, blockMPTR);
// debug
_blockHeapDebugVerifyIfBlockIsLinked(blockHeapHead, (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(blockMPTR));
// merged block becomes the new current block
blockMPTR = previousBlockMPTR;
block = previousBlock;
}
}
// attempt to merge with next block
if (_swapEndianU32(block->nextBlock) != MPTR_NULL)
{
MPTR nextBlockMPTR = _swapEndianU32(block->nextBlock);
MEMBlockHeapTrackDEPR* nextBlock = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(nextBlockMPTR);
if (_swapEndianU32(nextBlock->isFree) != 0)
{
// merge
block->addrEnd = nextBlock->addrEnd;
block->nextBlock = nextBlock->nextBlock;
if (_swapEndianU32(nextBlock->nextBlock) != MPTR_NULL)
{
MEMBlockHeapTrackDEPR* tempNextBlock = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(_swapEndianU32(nextBlock->nextBlock));
tempNextBlock->previousBlock = _swapEndianU32(blockMPTR);
}
//// merged block becomes the new current block
//blockMPTR = previousBlockMPTR;
//block = previousBlock;
// update last block
if (_swapEndianU32(blockHeapHead->tailBlock) == nextBlockMPTR)
{
blockHeapHead->tailBlock = _swapEndianU32(blockMPTR);
}
// release removed block
_MEMBlockHeap_ReleaseBlockTrack(blockHeapHead, nextBlockMPTR);
// debug
_blockHeapDebugVerifyIfBlockIsLinked(blockHeapHead, (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(nextBlockMPTR));
}
}
}
_blockHeapDebugVerifyLinkOrder(blockHeapHead);
__OSUnlockScheduler();
}
uint32 MEMGetTotalFreeSizeForBlockHeap(MEMBlockHeapDEPR* blockHeap)
{
if (!blockHeap || blockHeap->magic != MEMHeapMagic::BLOCK_HEAP)
{
cemu_assert_suspicious();
return 0;
}
__OSLockScheduler(); // todo: replace with spinlock from heap (if heap threadsafe flag is set)
uint32 totalSize = 0;
// sum up all free blocks
MPTR blockMPTR = _swapEndianU32(blockHeap->headBlock);
while (blockMPTR)
{
MEMBlockHeapTrackDEPR* track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffset(blockMPTR);
if (track->isFree != _swapEndianU32(0))
{
// get block size
uint32 blockSize = _swapEndianU32(track->addrEnd) - _swapEndianU32(track->addrStart) + 1;
// add to totalSize
totalSize += blockSize;
}
// next
blockMPTR = _swapEndianU32(track->nextBlock);
}
__OSUnlockScheduler(); // todo: replace with spinlock from heap (if heap threadsafe flag is set)
return totalSize;
}
void MEMDumpBlockHeap(MPTR heap)
{
MEMBlockHeapDEPR* blockHeapHead = (MEMBlockHeapDEPR*)memory_getPointerFromVirtualOffset(heap);
if (blockHeapHead->magic != MEMHeapMagic::BLOCK_HEAP)
{
cemu_assert_suspicious();
return;
}
// iterate reserved/sized blocks
debug_printf("### MEMDumpBlockHeap ###\n");
__OSLockScheduler(); // todo: replace with spinlock from heap
MEMBlockHeapTrackDEPR* track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(blockHeapHead->headBlock));
while (track)
{
uint32 blockRangeStart = _swapEndianU32(track->addrStart);
uint32 blockRangeEnd = _swapEndianU32(track->addrEnd) + 1;
debug_printf(" %08x %08x - %08x prev/next %08x %08x isFree: %d\n", memory_getVirtualOffsetFromPointer(track), blockRangeStart, blockRangeEnd, _swapEndianU32(track->previousBlock), _swapEndianU32(track->nextBlock), _swapEndianU32(track->isFree));
// next
track = (MEMBlockHeapTrackDEPR*)memory_getPointerFromVirtualOffsetAllowNull(_swapEndianU32(track->nextBlock));
}
debug_printf("\n");
__OSUnlockScheduler();
}
void InitializeMEMBlockHeap()
{
cafeExportRegister("coreinit", MEMInitBlockHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMDestroyBlockHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetAllocatableSizeForBlockHeapEx, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMAddBlockHeapTracking, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetTrackingLeftInBlockHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMAllocFromBlockHeapEx, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMFreeToBlockHeap, LogType::CoreinitMem);
cafeExportRegister("coreinit", MEMGetTotalFreeSizeForBlockHeap, LogType::CoreinitMem);
}
}
| 22,739
|
C++
|
.cpp
| 560
| 36.883929
| 248
| 0.750237
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,099
|
coreinit_FS.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_FS.cpp
|
#include <OS/RPL/rpl.h>
#include "config/ActiveSettings.h"
#include "Cafe/OS/libs/coreinit/coreinit_SystemInfo.h"
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_FS.h"
#include "Cafe/OS/libs/coreinit/coreinit_MessageQueue.h"
#include "util/helpers/Semaphore.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/IOSU/iosu_ipc_common.h"
#include "coreinit_IPC.h"
#include "Cafe/Filesystem/fsc.h"
#include "coreinit_IPCBuf.h"
#include "Cafe/CafeSystem.h"
#include "Cafe/TitleList/TitleInfo.h"
#define FS_CB_PLACEHOLDER_FINISHCMD (MPTR)(0xF122330E)
// return false if src+'\0' does not fit into dst
template<std::size_t Size>
bool strcpy_whole(char (&dst)[Size], const char* src)
{
size_t inputLength = strlen(src);
if ((inputLength + 1) > Size)
{
dst[0] = '\0';
return false;
}
strcpy(dst, src);
return true;
}
bool strcpy_whole(char* dst, size_t dstLength, const char* src)
{
size_t inputLength = strlen(src);
if ((inputLength + 1) > dstLength)
{
dst[0] = '\0';
return false;
}
strcpy(dst, src);
return true;
}
namespace coreinit
{
SysAllocator<OSMutex> s_fsGlobalMutex;
inline void FSLockMutex()
{
OSLockMutex(&s_fsGlobalMutex);
}
inline void FSUnlockMutex()
{
OSUnlockMutex(&s_fsGlobalMutex);
}
void _debugVerifyCommand(const char* stage, FSCmdBlockBody* fsCmdBlockBody);
bool sFSInitialized = true; // this should be false but it seems like some games rely on FSInit being called before main()? Twilight Princess for example reads files before it calls FSInit
bool sFSShutdown = false;
enum class MOUNT_TYPE : uint32
{
SD = 0,
// 1 = usb?
};
struct FS_MOUNT_SOURCE
{
uint32be sourceType; // ukn values
char path[128]; // todo - determine correct length
};
FS_RESULT FSGetMountSourceNext(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, MOUNT_TYPE mountSourceType, FS_MOUNT_SOURCE* mountSourceInfo, FS_ERROR_MASK errMask)
{
if (mountSourceType == MOUNT_TYPE::SD)
{
// This function is supposed to be called after an initial FSGetMountSource call => always returns FS_RESULT::END_ITERATION because we only have one SD Card
// It *might* causes issues if this function is called for getting the first MountSource (instead of "FSGetMountSource")
cemu_assert_suspicious();
return FS_RESULT::END_ITERATION;
}
else
{
cemu_assert_unimplemented();
}
return FS_RESULT::END_ITERATION;
}
FS_RESULT FSGetMountSource(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, MOUNT_TYPE mountSourceType, FS_MOUNT_SOURCE* mountSourceInfo, FS_ERROR_MASK errMask)
{
// This implementation is simplified A LOT compared to what the Wii U is actually doing. On Cemu we expect to only have one mountable source (SD Card) anyway,
// so we can just hard code it. Other mount types are not (yet) supported.
if (mountSourceType == MOUNT_TYPE::SD)
{
// check for SD card permissions (from cos.xml)
// One Piece relies on failing here, otherwise it will call FSGetMountSource in an infinite loop
CosCapabilityBitsFS perms = static_cast<CosCapabilityBitsFS>(CafeSystem::GetForegroundTitleCosCapabilities(CosCapabilityGroup::FS));
if(!HAS_FLAG(perms, CosCapabilityBitsFS::SDCARD_MOUNT))
{
cemuLog_logOnce(LogType::Force, "Title is trying to access SD card mount info without having SD card permissions. This may not be a bug");
return FS_RESULT::END_ITERATION;
}
mountSourceInfo->sourceType = 0;
strcpy(mountSourceInfo->path, "/sd");
return FS_RESULT::SUCCESS;
}
else
{
cemu_assert_unimplemented();
}
return FS_RESULT::END_ITERATION;
}
bool _sdCard01Mounted = false;
bool _mlc01Mounted = false;
void mountSDCard()
{
if (_sdCard01Mounted)
return;
std::error_code ec;
const auto path = ActiveSettings::GetUserDataPath("sdcard/");
fs::create_directories(path, ec);
FSCDeviceHostFS_Mount("/vol/external01", _pathToUtf8(path), FSC_PRIORITY_BASE);
_sdCard01Mounted = true;
}
FS_RESULT FSMount(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FS_MOUNT_SOURCE* mountSourceInfo, char* mountPathOut, sint32 mountPathMaxLength, FS_ERROR_MASK errMask)
{
if (mountSourceInfo->sourceType != 0)
{
return FS_RESULT::ERR_PLACEHOLDER;
}
if (!strcmp(mountSourceInfo->path, "/sd"))
{
const char* sdMountPath = "/vol/external01";
// note: mount path should not end with a slash
if (!strcpy_whole(mountPathOut, mountPathMaxLength, sdMountPath))
return FS_RESULT::ERR_PLACEHOLDER; // string does not fit
mountSDCard();
}
return FS_RESULT::SUCCESS;
}
FS_RESULT FSBindMount(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* mountPathSrc, char* mountPathOut, FS_ERROR_MASK errMask)
{
if (strcmp(mountPathSrc, "/dev/sdcard01") == 0)
{
if (_sdCard01Mounted)
return FS_RESULT::ERR_PLACEHOLDER;
std::error_code ec;
const auto path = ActiveSettings::GetUserDataPath("sdcard/");
fs::create_directories(path, ec);
if (!FSCDeviceHostFS_Mount(mountPathOut, _pathToUtf8(path), FSC_PRIORITY_BASE))
return FS_RESULT::ERR_PLACEHOLDER;
_sdCard01Mounted = true;
}
else if (strcmp(mountPathSrc, "/dev/mlc01") == 0)
{
if (_mlc01Mounted)
return FS_RESULT::ERR_PLACEHOLDER;
if (!FSCDeviceHostFS_Mount(mountPathOut, _pathToUtf8(ActiveSettings::GetMlcPath()), FSC_PRIORITY_BASE))
return FS_RESULT::ERR_PLACEHOLDER;
_mlc01Mounted = true;
}
else
{
return FS_RESULT::ERR_PLACEHOLDER;
}
return FS_RESULT::SUCCESS;
}
// return the aligned FSClientBody struct inside a FSClient struct
FSClientBody_t* __FSGetClientBody(FSClient_t* fsClient)
{
// align pointer to 64 bytes
if (fsClient == nullptr)
return nullptr;
FSClientBody_t* fsClientBody = (FSClientBody_t*)(((uintptr_t)fsClient + 0x3F) & ~0x3F);
fsClientBody->selfClient = fsClient;
return fsClientBody;
}
// return the aligned FSClientBody struct inside a FSClient struct
FSCmdBlockBody* __FSGetCmdBlockBody(FSCmdBlock_t* fsCmdBlock)
{
// align pointer to 64 bytes
if (fsCmdBlock == nullptr)
return nullptr;
FSCmdBlockBody* fsCmdBlockBody = (FSCmdBlockBody*)(((uintptr_t)fsCmdBlock + 0x3F) & ~0x3F);
fsCmdBlockBody->selfCmdBlock = fsCmdBlock;
return fsCmdBlockBody;
}
void __FSErrorAndBlock(std::string_view msg)
{
cemuLog_log(LogType::Force, "Critical error in FS: {}", msg);
while (true)
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
/* FS client management */
FSClientBody_t* g_fsRegisteredClientBodies = nullptr;
sint32 FSGetClientNum()
{
sint32 clientNum = 0;
FSClientBody_t* fsBodyItr = g_fsRegisteredClientBodies;
while (fsBodyItr)
{
clientNum++;
fsBodyItr = fsBodyItr->fsClientBodyNext.GetPtr();
}
return clientNum;
}
bool __FSIsClientRegistered(FSClientBody_t* fsClientBody)
{
FSLockMutex();
FSClientBody_t* fsClientBodyFirst = g_fsRegisteredClientBodies;
FSClientBody_t* fsClientBodyItr = fsClientBodyFirst;
if (fsClientBodyItr == NULL)
{
FSUnlockMutex();
return false;
}
while (true)
{
if (fsClientBody == fsClientBodyItr)
{
FSUnlockMutex();
return true;
}
// next
fsClientBodyItr = fsClientBodyItr->fsClientBodyNext.GetPtr();
if (fsClientBodyItr == MPTR_NULL)
break;
if (fsClientBodyItr == fsClientBodyFirst)
break;
}
FSUnlockMutex();
return false;
}
void __FSInitCmdQueue(FSCmdQueue* fsCmdQueueBE, MPTR dequeueHandlerFuncMPTR, uint32 numMaxCommandsInFlight)
{
cemu_assert(numMaxCommandsInFlight > 0);
fsCmdQueueBE->dequeueHandlerFuncMPTR = _swapEndianU32(dequeueHandlerFuncMPTR);
fsCmdQueueBE->numCommandsInFlight = 0;
fsCmdQueueBE->numMaxCommandsInFlight = numMaxCommandsInFlight;
coreinit::OSFastMutex_Init(&fsCmdQueueBE->fastMutex, nullptr);
fsCmdQueueBE->first = nullptr;
fsCmdQueueBE->last = nullptr;
}
void FSInit()
{
sFSInitialized = true;
}
void FSShutdown()
{
cemuLog_log(LogType::Force, "FSShutdown called");
}
FS_RESULT FSAddClientEx(FSClient_t* fsClient, uint32 uknR4, uint32 errHandling)
{
if (!sFSInitialized || sFSShutdown || !fsClient)
{
__FSErrorAndBlock("Called FSAddClient(Ex) with invalid parameters or while FS is not initialized");
return FS_RESULT::FATAL_ERROR;
}
FSLockMutex();
if (uknR4 != 0)
{
uint32 uknValue = memory_readU32(uknR4 + 0x00);
if (uknValue == 0)
{
FSUnlockMutex();
__FSErrorAndBlock("FSAddClientEx - unknown error");
return FS_RESULT::FATAL_ERROR;
}
}
if (__FSIsClientRegistered(__FSGetClientBody(fsClient)))
{
FSUnlockMutex();
__FSErrorAndBlock("Called FSAddClient(Ex) on client that was already added");
return FS_RESULT::FATAL_ERROR;
}
FSClientBody_t* fsClientBody = __FSGetClientBody(fsClient);
__FSInitCmdQueue(&fsClientBody->fsCmdQueue, MPTR_NULL, 1);
IOSDevHandle devHandle = IOS_Open("/dev/fsa", 0);
if (IOS_ResultIsError((IOS_ERROR)devHandle))
{
cemuLog_log(LogType::Force, "FSAddClientEx(): Exhausted device handles");
cemu_assert(IOS_ResultIsError((IOS_ERROR)devHandle));
FSUnlockMutex();
return FS_RESULT::FATAL_ERROR;
}
fsClientBody->iosuFSAHandle = devHandle;
// add to list of registered clients
if (g_fsRegisteredClientBodies != MPTR_NULL)
{
fsClientBody->fsClientBodyNext = g_fsRegisteredClientBodies;
g_fsRegisteredClientBodies = fsClientBody;
}
else
{
g_fsRegisteredClientBodies = fsClientBody;
fsClientBody->fsClientBodyNext = nullptr;
}
FSUnlockMutex();
return FS_RESULT::SUCCESS;
}
FS_RESULT FSAddClient(FSClient_t* fsClient, uint32 errHandling)
{
return FSAddClientEx(fsClient, 0, errHandling);
}
FS_RESULT FSDelClient(FSClient_t* fsClient, uint32 errHandling)
{
if (sFSInitialized == false || sFSShutdown == true || !fsClient)
{
__FSErrorAndBlock("Called FSDelClient with invalid parameters or while FS is not initialized");
return FS_RESULT::FATAL_ERROR;
}
FSClientBody_t* fsClientBody = __FSGetClientBody(fsClient);
FSLockMutex();
IOS_Close(fsClientBody->iosuFSAHandle);
// todo: wait till in-flight transactions are done
// remove from list
if (g_fsRegisteredClientBodies == fsClientBody)
{
// first entry in list
g_fsRegisteredClientBodies = fsClientBody->fsClientBodyNext.GetPtr();
}
else
{
// scan for entry in list
FSClientBody_t* fsBodyItr = g_fsRegisteredClientBodies;
FSClientBody_t* fsBodyPrev = g_fsRegisteredClientBodies;
bool entryFound = false;
while (fsBodyItr)
{
if (fsBodyItr == fsClientBody)
{
fsBodyPrev->fsClientBodyNext = fsClientBody->fsClientBodyNext;
entryFound = true;
break;
}
// next
fsBodyPrev = fsBodyItr;
fsBodyItr = fsBodyItr->fsClientBodyNext.GetPtr();
}
if (entryFound == false)
{
#ifdef CEMU_DEBUG_ASSERT
assert_dbg();
#endif
}
}
FSUnlockMutex();
return FS_RESULT::SUCCESS;
}
/* FS command queue */
Semaphore g_semaphoreQueuedCmds;
void __FSQueueCmdByPriority(FSCmdQueue* fsCmdQueueBE, FSCmdBlockBody* fsCmdBlockBody, bool stopAtEqualPriority)
{
if (!fsCmdQueueBE->first)
{
// queue is currently empty
cemu_assert(!fsCmdQueueBE->last);
fsCmdQueueBE->first = fsCmdBlockBody;
fsCmdQueueBE->last = fsCmdBlockBody;
fsCmdBlockBody->next = nullptr;
fsCmdBlockBody->previous = nullptr;
return;
}
// iterate from last to first element as long as iterated priority is lower
FSCmdBlockBody* fsCmdBlockBodyItrPrev = nullptr;
FSCmdBlockBody* fsCmdBlockBodyItr = fsCmdQueueBE->last;
while (true)
{
if (!fsCmdBlockBodyItr)
{
// insert at the head of the list
fsCmdQueueBE->first = fsCmdBlockBody;
fsCmdBlockBody->next = fsCmdBlockBodyItrPrev;
fsCmdBlockBody->previous = nullptr;
fsCmdBlockBodyItrPrev->previous = fsCmdBlockBody;
return;
}
// compare priority
if ((stopAtEqualPriority && fsCmdBlockBodyItr->priority >= fsCmdBlockBody->priority) || (stopAtEqualPriority == false && fsCmdBlockBodyItr->priority > fsCmdBlockBody->priority))
{
// insert cmd here
if (fsCmdBlockBodyItrPrev)
{
fsCmdBlockBody->next = fsCmdBlockBodyItrPrev;
}
else
{
fsCmdBlockBody->next = nullptr;
fsCmdQueueBE->last = fsCmdBlockBody;
}
fsCmdBlockBody->previous = fsCmdBlockBodyItr;
if (fsCmdBlockBodyItrPrev)
fsCmdBlockBodyItrPrev->previous = fsCmdBlockBody;
fsCmdBlockBodyItr->next = fsCmdBlockBody;
return;
}
// next
fsCmdBlockBodyItrPrev = fsCmdBlockBodyItr;
fsCmdBlockBodyItr = fsCmdBlockBodyItr->previous;
}
}
FSCmdBlockBody* __FSTakeCommandFromQueue(FSCmdQueue* cmdQueue)
{
if (!cmdQueue->first)
return nullptr;
// dequeue cmd
FSCmdBlockBody* dequeuedCmd = cmdQueue->first;
if (cmdQueue->first == cmdQueue->last)
cmdQueue->last = nullptr;
cmdQueue->first = dequeuedCmd->next;
dequeuedCmd->next = nullptr;
if (dequeuedCmd->next)
{
FSCmdBlockBody* fsCmdBodyNext = dequeuedCmd->next;
fsCmdBodyNext->previous = nullptr;
}
return dequeuedCmd;
}
void __FSAIoctlResponseCallback(PPCInterpreter_t* hCPU);
void __FSAIPCSubmitCommandAsync(iosu::fsa::FSAShimBuffer* shimBuffer, const MEMPTR<void>& callback, void* context)
{
if (shimBuffer->ipcReqType == 0)
{
IOS_ERROR r = IOS_IoctlAsync(shimBuffer->fsaDevHandle, shimBuffer->operationType, &shimBuffer->request, sizeof(shimBuffer->request), &shimBuffer->response, sizeof(shimBuffer->response), callback, context);
cemu_assert(!IOS_ResultIsError(r));
}
else if (shimBuffer->ipcReqType == 1)
{
IOS_ERROR r = IOS_IoctlvAsync(shimBuffer->fsaDevHandle, shimBuffer->operationType, shimBuffer->ioctlvVecIn, shimBuffer->ioctlvVecOut, shimBuffer->ioctlvVec, callback, context);
cemu_assert(!IOS_ResultIsError(r));
}
else
{
cemu_assert_error();
}
}
FSA_RESULT __FSADecodeIOSErrorToFSA(IOS_ERROR result)
{
return (FSA_RESULT)result;
}
FSA_RESULT __FSAIPCSubmitCommand(iosu::fsa::FSAShimBuffer* shimBuffer)
{
if (shimBuffer->ipcReqType == 0)
{
IOS_ERROR result = IOS_Ioctl(shimBuffer->fsaDevHandle, shimBuffer->operationType, &shimBuffer->request, sizeof(shimBuffer->request), &shimBuffer->response, sizeof(shimBuffer->response));
return __FSADecodeIOSErrorToFSA(result);
}
else if (shimBuffer->ipcReqType == 1)
{
IOS_ERROR result = IOS_Ioctlv(shimBuffer->fsaDevHandle, shimBuffer->operationType, shimBuffer->ioctlvVecIn, shimBuffer->ioctlvVecOut, shimBuffer->ioctlvVec);
return __FSADecodeIOSErrorToFSA(result);
}
return FSA_RESULT::FATAL_ERROR;
}
void __FSUpdateQueue(FSCmdQueue* cmdQueue)
{
FSLockMutex();
if (cmdQueue->numCommandsInFlight < cmdQueue->numMaxCommandsInFlight)
{
FSCmdBlockBody* dequeuedCommand = __FSTakeCommandFromQueue(cmdQueue);
if (dequeuedCommand)
{
cmdQueue->numCommandsInFlight += 1;
if (cmdQueue->numCommandsInFlight >= cmdQueue->numMaxCommandsInFlight)
cmdQueue->queueFlags = cmdQueue->queueFlags | FSCmdQueue::QUEUE_FLAG::IS_FULL;
cemu_assert_debug(cmdQueue->dequeueHandlerFuncMPTR == 0); // not supported. We HLE call the handler here
__FSAIPCSubmitCommandAsync(&dequeuedCommand->fsaShimBuffer, MEMPTR<void>(PPCInterpreter_makeCallableExportDepr(__FSAIoctlResponseCallback)), &dequeuedCommand->fsaShimBuffer);
}
}
FSUnlockMutex();
}
void __FSQueueDefaultFinishFunc(FSCmdBlockBody* fsCmdBlockBody, FS_RESULT result)
{
switch ((FSA_CMD_OPERATION_TYPE)fsCmdBlockBody->fsaShimBuffer.operationType.value())
{
case FSA_CMD_OPERATION_TYPE::OPENFILE:
{
*fsCmdBlockBody->returnValues.cmdOpenFile.handlePtr = fsCmdBlockBody->fsaShimBuffer.response.cmdOpenFile.fileHandleOutput;
break;
}
case FSA_CMD_OPERATION_TYPE::GETCWD:
{
auto transferSize = fsCmdBlockBody->returnValues.cmdGetCwd.transferSize;
if (transferSize < 0 && transferSize > sizeof(fsCmdBlockBody->fsaShimBuffer.response.cmdGetCWD.path))
{
cemu_assert_error();
}
memcpy(fsCmdBlockBody->returnValues.cmdGetCwd.pathPtr, fsCmdBlockBody->fsaShimBuffer.response.cmdGetCWD.path, transferSize);
break;
}
case FSA_CMD_OPERATION_TYPE::OPENDIR:
{
*fsCmdBlockBody->returnValues.cmdOpenDir.handlePtr = fsCmdBlockBody->fsaShimBuffer.response.cmdOpenDir.dirHandleOutput;
break;
}
case FSA_CMD_OPERATION_TYPE::READDIR:
{
*fsCmdBlockBody->returnValues.cmdReadDir.dirEntryPtr = fsCmdBlockBody->fsaShimBuffer.response.cmdReadDir.dirEntry;
break;
}
case FSA_CMD_OPERATION_TYPE::GETPOS:
{
*fsCmdBlockBody->returnValues.cmdGetPosFile.filePosPtr = fsCmdBlockBody->fsaShimBuffer.response.cmdGetPosFile.filePos;
break;
}
case FSA_CMD_OPERATION_TYPE::GETSTATFILE:
{
*((FSStat_t*)fsCmdBlockBody->returnValues.cmdStatFile.resultPtr.GetPtr()) = fsCmdBlockBody->fsaShimBuffer.response.cmdStatFile.statOut;
break;
}
case FSA_CMD_OPERATION_TYPE::QUERYINFO:
{
if (fsCmdBlockBody->fsaShimBuffer.request.cmdQueryInfo.queryType == FSA_QUERY_TYPE_FREESPACE)
{
*((uint64be*)fsCmdBlockBody->returnValues.cmdQueryInfo.queryResultPtr.GetPtr()) = fsCmdBlockBody->fsaShimBuffer.response.cmdQueryInfo.queryFreeSpace.freespace;
}
else if (fsCmdBlockBody->fsaShimBuffer.request.cmdQueryInfo.queryType == FSA_QUERY_TYPE_STAT)
{
*((FSStat_t*)fsCmdBlockBody->returnValues.cmdQueryInfo.queryResultPtr.GetPtr()) = fsCmdBlockBody->fsaShimBuffer.response.cmdQueryInfo.queryStat.stat;
}
else
{
cemu_assert_unimplemented();
}
break;
}
case FSA_CMD_OPERATION_TYPE::CHANGEDIR:
case FSA_CMD_OPERATION_TYPE::MAKEDIR:
case FSA_CMD_OPERATION_TYPE::REMOVE:
case FSA_CMD_OPERATION_TYPE::RENAME:
case FSA_CMD_OPERATION_TYPE::CLOSEDIR:
case FSA_CMD_OPERATION_TYPE::READ:
case FSA_CMD_OPERATION_TYPE::WRITE:
case FSA_CMD_OPERATION_TYPE::SETPOS:
case FSA_CMD_OPERATION_TYPE::ISEOF:
case FSA_CMD_OPERATION_TYPE::CLOSEFILE:
case FSA_CMD_OPERATION_TYPE::APPENDFILE:
case FSA_CMD_OPERATION_TYPE::TRUNCATEFILE:
case FSA_CMD_OPERATION_TYPE::FLUSHQUOTA:
{
break;
}
default:
{
cemu_assert_unimplemented();
}
}
}
void export___FSQueueDefaultFinishFunc(PPCInterpreter_t* hCPU)
{
ppcDefineParamPtr(cmd, FSCmdBlockBody, 0);
FS_RESULT result = (FS_RESULT)PPCInterpreter_getCallParamU32(hCPU, 1);
__FSQueueDefaultFinishFunc(cmd, static_cast<FS_RESULT>(result));
osLib_returnFromFunction(hCPU, 0);
}
void __FSQueueCmd(FSCmdQueue* cmdQueue, FSCmdBlockBody* fsCmdBlockBody, MPTR finishCmdFunc)
{
fsCmdBlockBody->cmdFinishFuncMPTR = finishCmdFunc;
FSLockMutex();
fsCmdBlockBody->statusCode = _swapEndianU32(FSA_CMD_STATUS_CODE_D900A22);
__FSQueueCmdByPriority(cmdQueue, fsCmdBlockBody, true);
FSUnlockMutex();
__FSUpdateQueue(cmdQueue);
}
FSA_RESULT _FSIosErrorToFSAStatus(IOS_ERROR iosError)
{
return (FSA_RESULT)iosError;
}
FS_RESULT _FSAStatusToFSStatus(FSA_RESULT err)
{
if ((int)err > 0)
{
return (FS_RESULT)err;
}
switch (err)
{
case FSA_RESULT::OK:
{
return FS_RESULT::SUCCESS;
}
case FSA_RESULT::END_OF_DIRECTORY:
case FSA_RESULT::END_OF_FILE:
{
return FS_RESULT::END_ITERATION;
}
case FSA_RESULT::ALREADY_EXISTS:
{
return FS_RESULT::ALREADY_EXISTS;
}
case FSA_RESULT::NOT_FOUND:
{
return FS_RESULT::NOT_FOUND;
}
case FSA_RESULT::PERMISSION_ERROR:
{
return FS_RESULT::PERMISSION_ERROR;
}
case FSA_RESULT::NOT_FILE:
{
return FS_RESULT::NOT_FILE;
}
case FSA_RESULT::NOT_DIR:
{
return FS_RESULT::NOT_DIR;
}
case FSA_RESULT::MAX_FILES:
case FSA_RESULT::MAX_DIRS:
{
return FS_RESULT::MAX_HANDLES;
}
case FSA_RESULT::INVALID_CLIENT_HANDLE:
case FSA_RESULT::INVALID_FILE_HANDLE:
case FSA_RESULT::INVALID_DIR_HANDLE:
case FSA_RESULT::INVALID_PARAM:
case FSA_RESULT::INVALID_PATH:
case FSA_RESULT::INVALID_BUFFER:
case FSA_RESULT::INVALID_ALIGNMENT:
case FSA_RESULT::NOT_INIT:
case FSA_RESULT::MAX_CLIENTS:
case FSA_RESULT::OUT_OF_RESOURCES:
case FSA_RESULT::FATAL_ERROR:
{
return FS_RESULT::FATAL_ERROR;
}
}
cemu_assert_unimplemented();
return FS_RESULT::FATAL_ERROR;
}
void __FSCmdSubmitResult(FSCmdBlockBody* fsCmdBlockBody, FS_RESULT result)
{
_debugVerifyCommand("FSCmdSubmitResult", fsCmdBlockBody);
FSClientBody_t* fsClientBody = fsCmdBlockBody->fsClientBody.GetPtr();
OSFastMutex_Lock(&fsClientBody->fsCmdQueue.fastMutex);
fsCmdBlockBody->cancelState &= ~(1 << 0); // clear cancel bit
if (fsClientBody->currentCmdBlockBody.GetPtr() == fsCmdBlockBody)
fsClientBody->currentCmdBlockBody = nullptr;
fsCmdBlockBody->statusCode = _swapEndianU32(FSA_CMD_STATUS_CODE_D900A24);
OSFastMutex_Unlock(&fsClientBody->fsCmdQueue.fastMutex);
// send result via msg queue or callback
cemu_assert_debug(!fsCmdBlockBody->asyncResult.fsAsyncParamsNew.ioMsgQueue != !fsCmdBlockBody->asyncResult.fsAsyncParamsNew.userCallback); // either must be set
fsCmdBlockBody->ukn09EA = 0;
fsCmdBlockBody->ukn9F4_lastErrorRelated = 0;
if (fsCmdBlockBody->asyncResult.fsAsyncParamsNew.ioMsgQueue)
{
// msg queue
_debugVerifyCommand("SubmitResultQueue", fsCmdBlockBody);
coreinit::OSMessageQueue* ioMsgQueue = fsCmdBlockBody->asyncResult.fsAsyncParamsNew.ioMsgQueue.GetPtr();
fsCmdBlockBody->asyncResult.fsCmdBlock = fsCmdBlockBody->selfCmdBlock;
fsCmdBlockBody->asyncResult.fsStatusNew = (uint32)result;
while (OSSendMessage(ioMsgQueue, &fsCmdBlockBody->asyncResult.msgUnion.osMsg, 0) == 0)
{
cemuLog_log(LogType::Force, "FS driver: Failed to add message to result queue. Retrying...");
if (PPCInterpreter_getCurrentInstance())
PPCCore_switchToScheduler();
else
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
else
{
// callback
_debugVerifyCommand("SubmitResultCallback", fsCmdBlockBody);
FSClient_t* fsClient = fsCmdBlockBody->asyncResult.fsClient.GetPtr();
FSCmdBlock_t* fsCmdBlock = fsCmdBlockBody->asyncResult.fsCmdBlock.GetPtr();
PPCCoreCallback(fsCmdBlockBody->asyncResult.fsAsyncParamsNew.userCallback, fsClient, fsCmdBlock, (sint32)result, fsCmdBlockBody->asyncResult.fsAsyncParamsNew.userContext);
}
}
void __FSAIoctlResponseCallback(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(iosResult, 0);
ppcDefineParamPtr(cmd, FSCmdBlockBody, 1);
FSA_RESULT fsaStatus = _FSIosErrorToFSAStatus((IOS_ERROR)iosResult);
cmd->statusCode = _swapEndianU32(FSA_CMD_STATUS_CODE_D900A26);
cmd->lastFSAStatus = fsaStatus;
// translate error code to FSStatus
FS_RESULT fsStatus = _FSAStatusToFSStatus(fsaStatus);
// On actual hardware this delegates the processing to the AppIO threads, but for now we just run it directly from the IPC thread
FSClientBody_t* client = cmd->fsClientBody;
FSCmdQueue& cmdQueue = client->fsCmdQueue;
FSLockMutex();
cmdQueue.numCommandsInFlight -= 1;
cmdQueue.queueFlags = cmdQueue.queueFlags & ~FSCmdQueue::QUEUE_FLAG::IS_FULL;
FSUnlockMutex();
if (cmd->cmdFinishFuncMPTR)
{
if (cmd->cmdFinishFuncMPTR != FS_CB_PLACEHOLDER_FINISHCMD)
PPCCoreCallback(MEMPTR<void>(cmd->cmdFinishFuncMPTR), cmd, fsStatus);
}
__FSCmdSubmitResult(cmd, fsStatus);
__FSUpdateQueue(&cmd->fsClientBody->fsCmdQueue);
osLib_returnFromFunction(hCPU, 0);
}
/* FS commands */
void FSInitCmdBlock(FSCmdBlock_t* fsCmdBlock)
{
memset(fsCmdBlock, 0x00, sizeof(FSCmdBlock_t));
FSCmdBlockBody* fsCmdBlockBody = __FSGetCmdBlockBody(fsCmdBlock);
fsCmdBlockBody->statusCode = _swapEndianU32(FSA_CMD_STATUS_CODE_D900A21);
fsCmdBlockBody->priority = 0x10;
}
void __FSAsyncToSyncInit(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSAsyncParams* asyncParams)
{
if (fsClient == nullptr || fsCmdBlock == nullptr || asyncParams == nullptr)
assert_dbg();
FSCmdBlockBody* fsCmdBlockBody = __FSGetCmdBlockBody(fsCmdBlock);
coreinit::OSInitMessageQueue(&fsCmdBlockBody->syncTaskMsgQueue, fsCmdBlockBody->_syncTaskMsg, 1);
asyncParams->userCallback = nullptr;
asyncParams->userContext = nullptr;
asyncParams->ioMsgQueue = &fsCmdBlockBody->syncTaskMsgQueue;
}
void __FSPrepareCmdAsyncResult(FSClientBody_t* fsClientBody, FSCmdBlockBody* fsCmdBlockBody, FSAsyncResult* fsCmdBlockAsyncResult, FSAsyncParams* fsAsyncParams)
{
memcpy(&fsCmdBlockAsyncResult->fsAsyncParamsNew, fsAsyncParams, sizeof(FSAsyncParams));
fsCmdBlockAsyncResult->fsClient = fsClientBody->selfClient;
fsCmdBlockAsyncResult->fsCmdBlock = fsCmdBlockBody->selfCmdBlock;
fsCmdBlockAsyncResult->msgUnion.fsMsg.fsAsyncResult = fsCmdBlockAsyncResult;
fsCmdBlockAsyncResult->msgUnion.fsMsg.commandType = _swapEndianU32(8);
}
sint32 __FSPrepareCmd(FSClientBody_t* fsClientBody, FSCmdBlockBody* fsCmdBlockBody, uint32 errHandling, FSAsyncParams* fsAsyncParams)
{
if (sFSInitialized == false || sFSShutdown == true)
return -0x400;
if (!fsClientBody || !fsCmdBlockBody)
{
cemu_assert(false);
return -0x400;
}
if (_swapEndianU32(fsCmdBlockBody->statusCode) != FSA_CMD_STATUS_CODE_D900A21 && _swapEndianU32(fsCmdBlockBody->statusCode) != FSA_CMD_STATUS_CODE_D900A24)
{
cemu_assert(false);
return -0x400;
}
if ((fsAsyncParams->userCallback == nullptr && fsAsyncParams->ioMsgQueue == nullptr) ||
(fsAsyncParams->userCallback != nullptr && fsAsyncParams->ioMsgQueue != nullptr))
{
// userCallback and ioMsgQueue both set or none set
cemu_assert(false);
return -0x400;
}
fsCmdBlockBody->fsClientBody = fsClientBody;
fsCmdBlockBody->errHandling = _swapEndianU32(errHandling);
fsCmdBlockBody->uknStatusGuessed09E9 = 0;
fsCmdBlockBody->cancelState &= ~(1 << 0); // clear cancel bit
fsCmdBlockBody->fsaShimBuffer.fsaDevHandle = fsClientBody->iosuFSAHandle;
__FSPrepareCmdAsyncResult(fsClientBody, fsCmdBlockBody, &fsCmdBlockBody->asyncResult, fsAsyncParams);
return 0;
}
#define _FSCmdIntro() \
FSClientBody_t* fsClientBody = __FSGetClientBody(fsClient); \
FSCmdBlockBody* fsCmdBlockBody = __FSGetCmdBlockBody(fsCmdBlock); \
sint32 fsError = __FSPrepareCmd(fsClientBody, fsCmdBlockBody, errorMask, fsAsyncParams); \
if (fsError != 0) \
return fsError;
void _debugVerifyCommand(const char* stage, FSCmdBlockBody* fsCmdBlockBody)
{
if (fsCmdBlockBody->asyncResult.msgUnion.fsMsg.commandType != _swapEndianU32(8))
{
cemuLog_log(LogType::Force, "Corrupted FS command detected in stage {}", stage);
cemuLog_log(LogType::Force, "Printing CMD block: ");
for (uint32 i = 0; i < (sizeof(FSCmdBlockBody) + 31) / 32; i++)
{
uint8* p = ((uint8*)fsCmdBlockBody) + i * 32;
cemuLog_log(LogType::Force, "{:04x}: {:02x} {:02x} {:02x} {:02x} - {:02x} {:02x} {:02x} {:02x} - {:02x} {:02x} {:02x} {:02x} - {:02x} {:02x} {:02x} {:02x} | {:02x} {:02x} {:02x} {:02x} - {:02x} {:02x} {:02x} {:02x} - {:02x} {:02x} {:02x} {:02x} - {:02x} {:02x} {:02x} {:02x}",
i * 32,
p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15],
p[16], p[17], p[18], p[19], p[20], p[21], p[22], p[23], p[24], p[25], p[26], p[27], p[28], p[29], p[30], p[31]);
}
}
}
FSAsyncResult* FSGetAsyncResult(OSMessage* msg)
{
return (FSAsyncResult*)memory_getPointerFromVirtualOffset(msg->message);
}
sint32 __FSProcessAsyncResult(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, sint32 fsStatus, uint32 errHandling)
{
// a positive result (or zero) means success. Most operations return zero in case of success. Read and write operations return the number of transferred units
if (fsStatus >= 0)
{
FSCmdBlockBody* fsCmdBlockBody = __FSGetCmdBlockBody(fsCmdBlock);
OSMessage msg;
OSReceiveMessage(&fsCmdBlockBody->syncTaskMsgQueue, &msg, OS_MESSAGE_BLOCK);
_debugVerifyCommand("handleAsyncResult", fsCmdBlockBody);
FSAsyncResult* asyncResult = FSGetAsyncResult(&msg);
return asyncResult->fsStatusNew;
}
else
{
// todo - error handling
cemuLog_log(LogType::Force, "FS handleAsyncResult(): unexpected error {:08x}", errHandling);
cemu_assert_debug(false);
return 0;
}
}
FSA_RESULT __FSPrepareCmd_OpenFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, char* path, char* mode, uint32 createMode, uint32 openFlags, uint32 preallocSize)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
if (path == NULL)
return FSA_RESULT::INVALID_PATH;
if (mode == NULL)
return FSA_RESULT::INVALID_PARAM;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::OPENFILE;
// path
size_t pathLen = strlen((char*)path);
if (pathLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
pathLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < pathLen; i++)
fsaShimBuffer->request.cmdOpenFile.path[i] = path[i];
for (size_t i = pathLen; i < FSA_CMD_PATH_MAX_LENGTH; i++)
fsaShimBuffer->request.cmdOpenFile.path[i] = '\0';
// mode
size_t modeLen = strlen((char*)mode);
if (modeLen >= 12)
{
cemu_assert_debug(false);
modeLen = 12 - 1;
}
for (sint32 i = 0; i < modeLen; i++)
fsaShimBuffer->request.cmdOpenFile.mode[i] = mode[i];
for (size_t i = modeLen; i < 12; i++)
fsaShimBuffer->request.cmdOpenFile.mode[i] = '\0';
// createMode
fsaShimBuffer->request.cmdOpenFile.createMode = createMode;
// openFlags
fsaShimBuffer->request.cmdOpenFile.openFlags = openFlags;
// preallocSize
fsaShimBuffer->request.cmdOpenFile.preallocSize = preallocSize;
fsaShimBuffer->response.cmdOpenFile.fileHandleOutput = 0xFFFFFFFF;
return FSA_RESULT::OK;
}
sint32 FSOpenFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, char* mode, FSFileHandlePtr outFileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
if (outFileHandle == nullptr || path == nullptr || mode == nullptr)
return -0x400;
fsCmdBlockBody->returnValues.cmdOpenFile.handlePtr = outFileHandle;
fsError = (FSStatus)__FSPrepareCmd_OpenFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, path, mode, 0x660, 0, 0);
if (fsError != (FSStatus)FS_RESULT::SUCCESS)
return fsError;
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSOpenFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, char* mode, FSFileHandlePtr outFileHandle, uint32 errHandling)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSOpenFileAsync(fsClient, fsCmdBlock, path, mode, outFileHandle, errHandling, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errHandling);
}
sint32 FSOpenFileExAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, char* mode, uint32 createMode, uint32 openFlag, uint32 preallocSize, FSFileHandlePtr outFileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
if (openFlag != 0)
{
cemuLog_log(LogType::Force, "FSOpenFileEx called with unsupported flags!");
cemu_assert_debug(false);
}
_FSCmdIntro();
if (outFileHandle == nullptr || path == nullptr || mode == nullptr)
return -0x400;
fsCmdBlockBody->returnValues.cmdOpenFile.handlePtr = outFileHandle;
FSA_RESULT prepareResult = __FSPrepareCmd_OpenFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, path, mode, createMode, openFlag, preallocSize);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSOpenFileEx(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, char* mode, uint32 createMode, uint32 openFlag, uint32 preallocSize, FSFileHandlePtr outFileHandle, uint32 errHandling)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSOpenFileExAsync(fsClient, fsCmdBlock, path, mode, createMode, openFlag, preallocSize, outFileHandle, errHandling, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errHandling);
}
FSA_RESULT __FSPrepareCmd_CloseFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, uint32 fileHandle)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::CLOSEFILE;
fsaShimBuffer->request.cmdCloseFile.fileHandle = fileHandle;
return FSA_RESULT::OK;
}
sint32 FSCloseFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_CloseFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSCloseFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 errHandling)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSCloseFileAsync(fsClient, fsCmdBlock, fileHandle, errHandling, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errHandling);
}
FSA_RESULT __FSPrepareCmd_FlushFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, uint32 fileHandle)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::FLUSHFILE;
fsaShimBuffer->request.cmdFlushFile.fileHandle = fileHandle;
return FSA_RESULT::OK;
}
sint32 FSFlushFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_FlushFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSFlushFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 errHandling)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSFlushFileAsync(fsClient, fsCmdBlock, fileHandle, errHandling, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errHandling);
}
FSA_RESULT __FSPrepareCmd_ReadFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, void* dest, uint32 size, uint32 count, uint32 filePos, uint32 fileHandle, uint32 flag)
{
if (fsaShimBuffer == NULL || dest == NULL)
return FSA_RESULT::INVALID_BUFFER;
MPTR destMPTR = memory_getVirtualOffsetFromPointer(dest);
if ((destMPTR & 0x3F) != 0)
return FSA_RESULT::INVALID_ALIGNMENT;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 1;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::READ;
fsaShimBuffer->ioctlvVecIn = 1;
fsaShimBuffer->ioctlvVecOut = 2;
fsaShimBuffer->ioctlvVec[0].baseVirt = fsaShimBuffer;
fsaShimBuffer->ioctlvVec[0].size = sizeof(iosu::fsa::FSARequest);
fsaShimBuffer->ioctlvVec[1].baseVirt = destMPTR;
fsaShimBuffer->ioctlvVec[1].size = size * count;
fsaShimBuffer->ioctlvVec[2].baseVirt = &fsaShimBuffer->response;
fsaShimBuffer->ioctlvVec[2].size = sizeof(iosu::fsa::FSAResponse);
fsaShimBuffer->request.cmdReadFile.dest = dest;
fsaShimBuffer->request.cmdReadFile.size = size;
fsaShimBuffer->request.cmdReadFile.count = count;
fsaShimBuffer->request.cmdReadFile.filePos = filePos;
fsaShimBuffer->request.cmdReadFile.fileHandle = fileHandle;
fsaShimBuffer->request.cmdReadFile.flag = flag;
return FSA_RESULT::OK;
}
SysAllocator<uint8, 128, 64> _tempFSSpace;
sint32 __FSReadFileAsyncEx(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* dest, uint32 size, uint32 count, bool usePos, uint32 filePos, uint32 fileHandle, uint32 flag, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
if (size == 0 || count == 0 || dest == NULL)
dest = _tempFSSpace.GetPtr();
sint64 transferSizeS64 = (sint64)size * (sint64)count;
if (transferSizeS64 < 0 || (transferSizeS64 >= 2LL * 1024LL * 1024LL * 1024LL))
{
// size below 0 or over 2GB
cemu_assert(false);
return -0x400;
}
// coreinit.rpl splits up each read into smaller chunks (probably to support canceling big writes). This is handled by a specific
// callback for the __FSQueueCmd functions. Whenever a chunk is read, it's getting re-queued until the reading has been completed.
// For this it writes values into the fsCmdBlockBody->returnValues struct. At the moment we go the lazy route of just reading everything
// at once, so we can skip the initialization of these values.
if (usePos)
flag |= FSA_CMD_FLAG_SET_POS;
else
flag &= ~FSA_CMD_FLAG_SET_POS;
FSA_RESULT prepareResult = __FSPrepareCmd_ReadFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, dest, size, count, filePos, fileHandle, flag);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSReadFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* dst, uint32 size, uint32 count, uint32 fileHandle, uint32 flag, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
cemu_assert_debug(flag == 0); // todo
return __FSReadFileAsyncEx(fsClient, fsCmdBlock, dst, size, count, false, 0, fileHandle, flag, errorMask, fsAsyncParams);
}
sint32 FSReadFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* dst, uint32 size, uint32 count, uint32 fileHandle, uint32 flag, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSReadFileAsync(fsClient, fsCmdBlock, dst, size, count, fileHandle, flag, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
sint32 FSReadFileWithPosAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* dst, uint32 size, uint32 count, uint32 filePos, uint32 fileHandle, uint32 flag, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
cemu_assert_debug(flag == 0); // todo
sint32 fsStatus = __FSReadFileAsyncEx(fsClient, fsCmdBlock, dst, size, count, true, filePos, fileHandle, flag, errorMask, fsAsyncParams);
return fsStatus;
}
sint32 FSReadFileWithPos(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* dst, uint32 size, uint32 count, uint32 filePos, uint32 fileHandle, uint32 flag, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSReadFileWithPosAsync(fsClient, fsCmdBlock, dst, size, count, filePos, fileHandle, flag, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_WriteFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, void* dest, uint32 size, uint32 count, uint32 filePos, uint32 fileHandle, uint32 flag)
{
if (fsaShimBuffer == NULL || dest == NULL)
return FSA_RESULT::INVALID_BUFFER;
MPTR destMPTR = memory_getVirtualOffsetFromPointer(dest);
if ((destMPTR & 0x3F) != 0)
return FSA_RESULT::INVALID_ALIGNMENT;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 1;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::WRITE;
fsaShimBuffer->ioctlvVecIn = 2;
fsaShimBuffer->ioctlvVecOut = 1;
fsaShimBuffer->ioctlvVec[0].baseVirt = fsaShimBuffer;
fsaShimBuffer->ioctlvVec[0].size = sizeof(iosu::fsa::FSARequest);
fsaShimBuffer->ioctlvVec[1].baseVirt = destMPTR;
fsaShimBuffer->ioctlvVec[1].size = size * count;
fsaShimBuffer->ioctlvVec[2].baseVirt = &fsaShimBuffer->response;
fsaShimBuffer->ioctlvVec[2].size = sizeof(iosu::fsa::FSAResponse);
fsaShimBuffer->request.cmdWriteFile.dest = dest;
fsaShimBuffer->request.cmdWriteFile.size = size;
fsaShimBuffer->request.cmdWriteFile.count = count;
fsaShimBuffer->request.cmdWriteFile.filePos = filePos;
fsaShimBuffer->request.cmdWriteFile.fileHandle = fileHandle;
fsaShimBuffer->request.cmdWriteFile.flag = flag;
return FSA_RESULT::OK;
}
sint32 __FSWriteFileWithPosAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* dest, uint32 size, uint32 count, bool useFilePos, uint32 filePos, uint32 fileHandle, uint32 flag, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
if (size == 0 || count == 0 || dest == nullptr)
dest = _tempFSSpace.GetPtr();
sint64 transferSizeS64 = (sint64)size * (sint64)count;
if (transferSizeS64 < 0 || (transferSizeS64 >= 2LL * 1024LL * 1024LL * 1024LL))
{
// size below 0 or over 2GB
cemu_assert(false);
return -0x400;
}
// coreinit.rpl splits up each write into smaller chunks (probably to support canceling big writes). This is handled by a specific
// callback for the __FSQueueCmd functions. Whenever a chunk is written, it's getting re-queued until the writing has been completed.
// For this it writes values into the fsCmdBlockBody->returnValues struct. At the moment we go the lazy route of just writing everything
// at once, so we can skip the initialization of these values.
if (useFilePos)
flag |= FSA_CMD_FLAG_SET_POS;
else
flag &= ~FSA_CMD_FLAG_SET_POS;
FSA_RESULT prepareResult = __FSPrepareCmd_WriteFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, dest, size, count, filePos, fileHandle, flag);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSWriteFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* src, uint32 size, uint32 count, uint32 fileHandle, uint32 flag, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
return __FSWriteFileWithPosAsync(fsClient, fsCmdBlock, src, size, count, false, 0, fileHandle, flag, errorMask, fsAsyncParams);
}
sint32 FSWriteFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* src, uint32 size, uint32 count, uint32 fileHandle, uint32 flag, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSWriteFileAsync(fsClient, fsCmdBlock, src, size, count, fileHandle, flag, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
sint32 FSWriteFileWithPosAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* src, uint32 size, uint32 count, uint32 filePos, uint32 fileHandle, uint32 flag, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
return __FSWriteFileWithPosAsync(fsClient, fsCmdBlock, src, size, count, true, filePos, fileHandle, flag, errorMask, fsAsyncParams);
}
sint32 FSWriteFileWithPos(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, void* src, uint32 size, uint32 count, uint32 filePos, uint32 fileHandle, uint32 flag, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSWriteFileWithPosAsync(fsClient, fsCmdBlock, src, size, count, filePos, fileHandle, flag, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_SetPosFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, uint32 fileHandle, uint32 filePos)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->request.cmdSetPosFile.fileHandle = fileHandle;
fsaShimBuffer->request.cmdSetPosFile.filePos = filePos;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::SETPOS;
return FSA_RESULT::OK;
}
sint32 FSSetPosFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 filePos, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_SetPosFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle, filePos);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSSetPosFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 filePos, uint32 errorMask)
{
// used by games: Mario Kart 8
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSSetPosFileAsync(fsClient, fsCmdBlock, fileHandle, filePos, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_GetPosFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, uint32 fileHandle)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->request.cmdGetPosFile.fileHandle = fileHandle;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::GETPOS;
return FSA_RESULT::OK;
}
sint32 FSGetPosFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32be* returnedFilePos, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// games using this: Darksiders Warmastered Edition
_FSCmdIntro();
fsCmdBlockBody->returnValues.cmdGetPosFile.filePosPtr = returnedFilePos;
FSA_RESULT prepareResult = __FSPrepareCmd_GetPosFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSGetPosFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32be* returnedFilePos, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSGetPosFileAsync(fsClient, fsCmdBlock, fileHandle, returnedFilePos, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_OpenDir(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, char* path)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
if (path == nullptr)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::OPENDIR;
// path
sint32 pathLen = (sint32)strlen((char*)path);
if (pathLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
pathLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < pathLen; i++)
fsaShimBuffer->request.cmdOpenDir.path[i] = path[i];
for (sint32 i = pathLen; i < FSA_CMD_PATH_MAX_LENGTH; i++)
fsaShimBuffer->request.cmdOpenDir.path[i] = '\0';
fsaShimBuffer->response.cmdOpenDir.dirHandleOutput = -1;
return FSA_RESULT::OK;
}
sint32 FSOpenDirAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, FSDirHandlePtr dirHandleOut, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
cemu_assert(dirHandleOut && path);
fsCmdBlockBody->returnValues.cmdOpenDir.handlePtr = dirHandleOut.GetMPTR();
FSA_RESULT prepareResult = __FSPrepareCmd_OpenDir(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, path);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSOpenDir(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, FSDirHandlePtr dirHandleOut, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSOpenDirAsync(fsClient, fsCmdBlock, path, dirHandleOut, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_ReadDir(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, FSDirHandle2 dirHandle)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::READDIR;
fsaShimBuffer->request.cmdReadDir.dirHandle = dirHandle;
return FSA_RESULT::OK;
}
sint32 FSReadDirAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSDirHandle2 dirHandle, FSDirEntry_t* dirEntryOut, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_ReadDir(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, dirHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
fsCmdBlockBody->returnValues.cmdReadDir.dirEntryPtr = dirEntryOut;
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSReadDir(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSDirHandle2 dirHandle, FSDirEntry_t* dirEntryOut, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSReadDirAsync(fsClient, fsCmdBlock, dirHandle, dirEntryOut, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_CloseDir(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, FSDirHandle2 dirHandle)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::CLOSEDIR;
fsaShimBuffer->request.cmdCloseDir.dirHandle = dirHandle;
return FSA_RESULT::OK;
}
sint32 FSCloseDirAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSDirHandle2 dirHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_CloseDir(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, dirHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSCloseDir(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSDirHandle2 dirHandle, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSCloseDirAsync(fsClient, fsCmdBlock, dirHandle, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_RewindDir(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, FSDirHandle2 dirHandle)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::REWINDDIR;
fsaShimBuffer->request.cmdRewindDir.dirHandle = dirHandle;
return FSA_RESULT::OK;
}
sint32 FSRewindDirAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSDirHandle2 dirHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_RewindDir(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, dirHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSRewindDir(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSDirHandle2 dirHandle, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSRewindDirAsync(fsClient, fsCmdBlock, dirHandle, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_AppendFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, uint32 size, uint32 count, uint32 fileHandle, uint32 uknParam)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::APPENDFILE;
fsaShimBuffer->request.cmdAppendFile.fileHandle = fileHandle;
fsaShimBuffer->request.cmdAppendFile.count = count;
fsaShimBuffer->request.cmdAppendFile.size = size;
fsaShimBuffer->request.cmdAppendFile.uknParam = uknParam;
return FSA_RESULT::OK;
}
sint32 FSAppendFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 size, uint32 count, uint32 fileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_AppendFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, size, count, fileHandle, 0);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSAppendFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 size, uint32 count, uint32 fileHandle, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSAppendFileAsync(fsClient, fsCmdBlock, size, count, fileHandle, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_TruncateFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, FSFileHandle2 fileHandle)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::TRUNCATEFILE;
fsaShimBuffer->request.cmdTruncateFile.fileHandle = fileHandle;
return FSA_RESULT::OK;
}
sint32 FSTruncateFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSFileHandle2 fileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_TruncateFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSTruncateFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSFileHandle2 fileHandle, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSTruncateFileAsync(fsClient, fsCmdBlock, fileHandle, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_Rename(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, char* srcPath, char* dstPath)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
if (srcPath == NULL || dstPath == NULL)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::RENAME;
// source path
size_t stringLen = strlen((char*)srcPath);
if (stringLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
stringLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < stringLen; i++)
{
fsaShimBuffer->request.cmdRename.srcPath[i] = srcPath[i];
}
fsaShimBuffer->request.cmdRename.srcPath[stringLen] = '\0';
// destination path
stringLen = strlen((char*)dstPath);
if (stringLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
stringLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < stringLen; i++)
{
fsaShimBuffer->request.cmdRename.dstPath[i] = dstPath[i];
}
fsaShimBuffer->request.cmdRename.dstPath[stringLen] = '\0';
return FSA_RESULT::OK;
}
sint32 FSRenameAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* srcPath, char* dstPath, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// used by titles: XCX (via SAVERenameAsync)
_FSCmdIntro();
if (srcPath == NULL || dstPath == NULL)
{
cemu_assert_debug(false); // path must not be NULL
return -0x400;
}
FSA_RESULT prepareResult = __FSPrepareCmd_Rename(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, srcPath, dstPath);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSRename(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* srcPath, char* dstPath, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSRenameAsync(fsClient, fsCmdBlock, srcPath, dstPath, errorMask, asyncParams.GetPointer());
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_Remove(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, uint8* path)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
if (path == NULL)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::REMOVE;
size_t pathLen = strlen((char*)path);
if (pathLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
pathLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < pathLen; i++)
{
fsaShimBuffer->request.cmdRemove.path[i] = path[i];
}
fsaShimBuffer->request.cmdRemove.path[pathLen] = '\0';
return FSA_RESULT::OK;
}
sint32 FSRemoveAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint8* filePath, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// used by titles: XCX (via SAVERemoveAsync)
_FSCmdIntro();
if (filePath == NULL)
{
cemu_assert_debug(false); // path must not be NULL
return -0x400;
}
FSA_RESULT prepareResult = __FSPrepareCmd_Remove(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, filePath);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSRemove(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint8* filePath, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSRemoveAsync(fsClient, fsCmdBlock, filePath, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_MakeDir(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, const char* path, uint32 uknVal660)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
if (path == NULL)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::MAKEDIR;
size_t pathLen = strlen((char*)path);
if (pathLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
pathLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < pathLen; i++)
{
fsaShimBuffer->request.cmdMakeDir.path[i] = path[i];
}
fsaShimBuffer->request.cmdMakeDir.path[pathLen] = '\0';
fsaShimBuffer->request.cmdMakeDir.uknParam = uknVal660;
return FSA_RESULT::OK;
}
sint32 FSMakeDirAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, const char* dirPath, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// used by titles: XCX (via SAVEMakeDirAsync)
_FSCmdIntro();
if (dirPath == NULL)
{
cemu_assert_debug(false); // path must not be NULL
return -0x400;
}
FSA_RESULT prepareResult = __FSPrepareCmd_MakeDir(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, dirPath, 0x660);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSMakeDir(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, const char* path, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSMakeDirAsync(fsClient, fsCmdBlock, path, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_ChangeDir(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, uint8* path)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
if (path == NULL)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::CHANGEDIR;
size_t pathLen = strlen((char*)path);
if (pathLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
pathLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < pathLen; i++)
fsaShimBuffer->request.cmdChangeDir.path[i] = path[i];
fsaShimBuffer->request.cmdChangeDir.path[pathLen] = '\0';
return FSA_RESULT::OK;
}
sint32 FSChangeDirAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
if (path == NULL)
{
cemu_assert_debug(false); // path must not be NULL
return -0x400;
}
FSA_RESULT prepareResult = __FSPrepareCmd_ChangeDir(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, (uint8*)path);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSChangeDir(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSChangeDirAsync(fsClient, fsCmdBlock, path, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_GetCwd(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::GETCWD;
return FSA_RESULT::OK;
}
sint32 FSGetCwdAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* dirPathOut, sint32 dirPathMaxLen, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// used by titles: Super Mario Maker
_FSCmdIntro();
fsCmdBlockBody->returnValues.cmdGetCwd.pathPtr = dirPathOut;
fsCmdBlockBody->returnValues.cmdGetCwd.transferSize = dirPathMaxLen;
FSA_RESULT prepareResult = __FSPrepareCmd_GetCwd(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSGetCwd(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* dirPathOut, sint32 dirPathMaxLen, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSGetCwdAsync(fsClient, fsCmdBlock, dirPathOut, dirPathMaxLen, errorMask, &asyncParams);
auto r = __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
return r;
}
FSA_RESULT __FSPrepareCmd_FlushQuota(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, char* path)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
if (path == NULL)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::FLUSHQUOTA;
size_t pathLen = strlen((char*)path);
if (pathLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
pathLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < pathLen; i++)
fsaShimBuffer->request.cmdFlushQuota.path[i] = path[i];
fsaShimBuffer->request.cmdFlushQuota.path[pathLen] = '\0';
return FSA_RESULT::OK;
}
sint32 FSFlushQuotaAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_FlushQuota(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, path);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSFlushQuota(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, char* path, uint32 errorMask)
{
StackAllocator<FSAsyncParams> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSFlushQuotaAsync(fsClient, fsCmdBlock, path, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_QueryInfo(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, uint8* queryString, uint32 queryType)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
if (queryString == NULL)
return FSA_RESULT::INVALID_PATH;
if (queryType > 8)
return FSA_RESULT::INVALID_PARAM;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::QUERYINFO;
size_t stringLen = strlen((char*)queryString);
if (stringLen >= FSA_CMD_PATH_MAX_LENGTH)
{
cemu_assert_debug(false);
stringLen = FSA_CMD_PATH_MAX_LENGTH - 1;
}
for (sint32 i = 0; i < stringLen; i++)
{
fsaShimBuffer->request.cmdQueryInfo.query[i] = queryString[i];
}
fsaShimBuffer->request.cmdQueryInfo.query[stringLen] = '\0';
fsaShimBuffer->request.cmdQueryInfo.queryType = queryType;
return FSA_RESULT::OK;
}
sint32 __FSQueryInfoAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint8* queryString, uint32 queryType, void* queryResult, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
cemu_assert(queryString && queryResult); // query string and result must not be null
fsCmdBlockBody->returnValues.cmdQueryInfo.queryResultPtr = queryResult;
FSA_RESULT prepareResult = __FSPrepareCmd_QueryInfo(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, queryString, queryType);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSGetStatAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, const char* path, FSStat_t* statOut, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
sint32 fsStatus = __FSQueryInfoAsync(fsClient, fsCmdBlock, (uint8*)path, FSA_QUERY_TYPE_STAT, statOut, errorMask, fsAsyncParams);
return fsStatus;
}
sint32 FSGetStat(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, const char* path, FSStat_t* statOut, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSGetStatAsync(fsClient, fsCmdBlock, path, statOut, errorMask, &asyncParams);
sint32 ret = __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
return ret;
}
FSA_RESULT __FSPrepareCmd_GetStatFile(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, FSFileHandle2 fileHandle)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::GETSTATFILE;
fsaShimBuffer->request.cmdGetStatFile.fileHandle = fileHandle;
return FSA_RESULT::OK;
}
sint32 FSGetStatFileAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSFileHandle2 fileHandle, FSStat_t* statOut, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
_FSCmdIntro();
cemu_assert(statOut); // statOut must not be null
fsCmdBlockBody->returnValues.cmdStatFile.resultPtr = statOut;
FSA_RESULT prepareResult = __FSPrepareCmd_GetStatFile(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSGetStatFile(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, FSFileHandle2 fileHandle, FSStat_t* statOut, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSGetStatFileAsync(fsClient, fsCmdBlock, fileHandle, statOut, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
sint32 FSGetFreeSpaceSizeAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, const char* path, FSLargeSize* returnedFreeSize, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// used by: Wii U system settings app, Art Academy, Unity (e.g. Snoopy's Grand Adventure), Super Smash Bros
sint32 fsStatus = __FSQueryInfoAsync(fsClient, fsCmdBlock, (uint8*)path, FSA_QUERY_TYPE_FREESPACE, returnedFreeSize, errorMask, fsAsyncParams);
return fsStatus;
}
sint32 FSGetFreeSpaceSize(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, const char* path, FSLargeSize* returnedFreeSize, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSGetFreeSpaceSizeAsync(fsClient, fsCmdBlock, path, returnedFreeSize, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
FSA_RESULT __FSPrepareCmd_IsEof(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle devHandle, uint32 fileHandle)
{
if (fsaShimBuffer == NULL)
return FSA_RESULT::INVALID_BUFFER;
fsaShimBuffer->fsaDevHandle = devHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::ISEOF;
fsaShimBuffer->request.cmdIsEof.fileHandle = fileHandle;
return FSA_RESULT::OK;
}
sint32 FSIsEofAsync(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 errorMask, FSAsyncParams* fsAsyncParams)
{
// used by Paper Monsters Recut
_FSCmdIntro();
FSA_RESULT prepareResult = __FSPrepareCmd_IsEof(&fsCmdBlockBody->fsaShimBuffer, fsClientBody->iosuFSAHandle, fileHandle);
if (prepareResult != FSA_RESULT::OK)
return (FSStatus)_FSAStatusToFSStatus(prepareResult);
__FSQueueCmd(&fsClientBody->fsCmdQueue, fsCmdBlockBody, RPLLoader_MakePPCCallable(export___FSQueueDefaultFinishFunc));
return (FSStatus)FS_RESULT::SUCCESS;
}
sint32 FSIsEof(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock, uint32 fileHandle, uint32 errorMask)
{
StackAllocator<FSAsyncParams, 1> asyncParams;
__FSAsyncToSyncInit(fsClient, fsCmdBlock, &asyncParams);
sint32 fsAsyncRet = FSIsEofAsync(fsClient, fsCmdBlock, fileHandle, errorMask, &asyncParams);
return __FSProcessAsyncResult(fsClient, fsCmdBlock, fsAsyncRet, errorMask);
}
void FSSetUserData(FSCmdBlock_t* fsCmdBlock, void* userData)
{
FSCmdBlockBody* fsCmdBlockBody = __FSGetCmdBlockBody(fsCmdBlock);
if (fsCmdBlockBody)
fsCmdBlockBody->userData = userData;
}
void* FSGetUserData(FSCmdBlock_t* fsCmdBlock)
{
FSCmdBlockBody* fsCmdBlockBody = __FSGetCmdBlockBody(fsCmdBlock);
void* userData = nullptr;
if (fsCmdBlockBody)
userData = fsCmdBlockBody->userData.GetPtr();
return userData;
}
FS_VOLSTATE FSGetVolumeState(FSClient_t* fsClient)
{
// todo
return FS_VOLSTATE_READY;
}
sint32 FSGetErrorCodeForViewer(FSClient_t* fsClient, FSCmdBlock_t* fsCmdBlock)
{
// todo
return 0; // no error
}
FSCmdBlock_t* FSGetCurrentCmdBlock(FSClient_t* fsClient)
{
FSClientBody_t* fsClientBody = __FSGetClientBody(fsClient);
if (!fsClientBody)
return nullptr;
FSCmdBlockBody* cmdBlockBody = fsClientBody->currentCmdBlockBody;
if (!cmdBlockBody)
return nullptr;
return cmdBlockBody->selfCmdBlock;
}
sint32 FSGetLastErrorCodeForViewer(FSClient_t* fsClient)
{
FSCmdBlock_t* cmdBlock = FSGetCurrentCmdBlock(fsClient);
if (cmdBlock)
{
cemu_assert_unimplemented();
}
return 0; // no error
}
std::vector<FSAClientHandle> s_fsa_activeClients;
std::mutex s_fsa_activeClientsMutex;
FSAClientHandle FSAAddClientEx(void* data)
{
if (data != NULL)
{
// TODO
cemu_assert_unimplemented();
}
IOSDevHandle handle = IOS_Open("/dev/fsa", 0);
if (handle < IOS_ERROR::IOS_ERROR_OK)
{
return (FSAClientHandle)FSA_RESULT::PERMISSION_ERROR;
}
s_fsa_activeClientsMutex.lock();
s_fsa_activeClients.push_back((FSAClientHandle)handle);
s_fsa_activeClientsMutex.unlock();
return (FSAClientHandle)handle;
}
FSAClientHandle FSAAddClient(void* data)
{
return FSAAddClientEx(data);
}
FSA_RESULT FSADelClient(FSAClientHandle clientHandle)
{
if (clientHandle == 0)
{
return FSA_RESULT::INVALID_CLIENT_HANDLE;
}
s_fsa_activeClientsMutex.lock();
auto it = std::find(s_fsa_activeClients.begin(), s_fsa_activeClients.end(), clientHandle);
if (it != s_fsa_activeClients.end())
{
IOS_Close(clientHandle);
s_fsa_activeClients.erase(it);
}
s_fsa_activeClientsMutex.unlock();
return FSA_RESULT::OK;
}
SysAllocator<coreinit::IPCBufPool_t*> s_fsaIpcPool;
SysAllocator<uint8, 0x37500> s_fsaIpcPoolBuffer;
SysAllocator<uint32be> s_fsaIpcPoolBufferNumItems;
std::mutex sFSAIPCBufferLock;
bool s_fsaInitDone = false;
void FSAInit()
{
if (!s_fsaInitDone)
{
s_fsaIpcPool = IPCBufPoolCreate(s_fsaIpcPoolBuffer.GetPtr(), s_fsaIpcPoolBuffer.GetByteSize(), sizeof(iosu::fsa::FSAShimBuffer), &s_fsaIpcPoolBufferNumItems, 0);
s_fsaInitDone = true;
}
}
bool FSAShimCheckClientHandle(FSAClientHandle clientHandle)
{
std::scoped_lock lock(s_fsa_activeClientsMutex);
if (std::find(s_fsa_activeClients.begin(), s_fsa_activeClients.end(), clientHandle) != s_fsa_activeClients.end())
{
return true;
}
return false;
}
FSA_RESULT FSAShimAllocateBuffer(MEMPTR<MEMPTR<iosu::fsa::FSAShimBuffer>> outBuffer)
{
if (!s_fsaInitDone)
return FSA_RESULT::NOT_INIT;
sFSAIPCBufferLock.lock();
auto ptr = IPCBufPoolAllocate(s_fsaIpcPool, sizeof(iosu::fsa::FSAShimBuffer));
sFSAIPCBufferLock.unlock();
if (!ptr)
return FSA_RESULT::OUT_OF_RESOURCES;
std::memset(ptr, 0, sizeof(iosu::fsa::FSAShimBuffer));
outBuffer[0] = reinterpret_cast<iosu::fsa::FSAShimBuffer*>(ptr);
return FSA_RESULT::OK;
}
FSA_RESULT FSAShimFreeBuffer(iosu::fsa::FSAShimBuffer* buffer)
{
sFSAIPCBufferLock.lock();
IPCBufPoolFree(s_fsaIpcPool, (uint8_t*)buffer);
sFSAIPCBufferLock.unlock();
return FSA_RESULT::OK;
}
FSA_RESULT FSACloseFile(FSAClientHandle client, uint32 fileHandle)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_CloseFile(shimBuffer->GetPtr(), client, fileHandle);
if (result == FSA_RESULT::OK)
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAFlushFile(FSAClientHandle client, uint32_t fileHandle)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_FlushFile(shimBuffer->GetPtr(), client, fileHandle);
if (result == FSA_RESULT::OK)
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAMakeDir(FSAClientHandle client, const char* path, uint32 uknVal660)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_MakeDir(shimBuffer->GetPtr(), client, path, uknVal660);
if (result == FSA_RESULT::OK)
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSARename(FSAClientHandle client, char* oldPath, char* newPath)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_Rename(shimBuffer->GetPtr(), client, oldPath, newPath);
if (result == FSA_RESULT::OK)
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAChangeDir(FSAClientHandle client, char* path)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_ChangeDir(shimBuffer->GetPtr(), client, (uint8_t*)path);
if (result == FSA_RESULT::OK)
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAReadDir(FSAClientHandle client, FSDirHandle2 dirHandle, MEMPTR<FSDirEntry_t> directoryEntry)
{
if (directoryEntry.IsNull())
return FSA_RESULT::INVALID_BUFFER;
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_ReadDir(shimBuffer->GetPtr(), client, dirHandle);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
if (result == FSA_RESULT::OK)
{
*directoryEntry = shimBuffer->GetPtr()->response.cmdReadDir.dirEntry;
}
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAOpenDir(FSAClientHandle client, char* path, MEMPTR<uint32be> dirHandle)
{
if (dirHandle.IsNull())
return FSA_RESULT::INVALID_BUFFER;
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_OpenDir(shimBuffer->GetPtr(), client, path);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
if (result == FSA_RESULT::OK)
{
*dirHandle = shimBuffer->GetPtr()->response.cmdOpenDir.dirHandleOutput;
}
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSACloseDir(FSAClientHandle client, FSDirHandle2 dirHandle)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_CloseDir(shimBuffer->GetPtr(), client, dirHandle);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSARewindDir(FSAClientHandle client, FSDirHandle2 dirHandle)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_RewindDir(shimBuffer->GetPtr(), client, dirHandle);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAOpenFileEx(FSAClientHandle client, char* path, char* mode, uint32 createMode, uint32 openFlag, uint32_t preallocSize, MEMPTR<uint32be> outFileHandle)
{
if (outFileHandle.IsNull())
return FSA_RESULT::INVALID_BUFFER;
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_OpenFile(shimBuffer->GetPtr(), client, path, mode, createMode, openFlag, preallocSize);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
if (result == FSA_RESULT::OK)
{
*outFileHandle = shimBuffer->GetPtr()->response.cmdOpenFile.fileHandleOutput;
}
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAGetStatFile(FSAClientHandle client, FSFileHandle2 fileHandle, MEMPTR<FSStat_t> outStat)
{
if (outStat.IsNull())
return FSA_RESULT::INVALID_BUFFER;
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_GetStatFile(shimBuffer->GetPtr(), client, fileHandle);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
if (result == FSA_RESULT::OK)
{
*outStat = shimBuffer->GetPtr()->response.cmdStatFile.statOut;
}
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSASetPosFile(FSAClientHandle client, FSFileHandle2 fileHandle, uint32_t pos)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_SetPosFile(shimBuffer->GetPtr(), client, fileHandle, pos);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSATruncateFile(FSAClientHandle client, FSFileHandle2 fileHandle)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_TruncateFile(shimBuffer->GetPtr(), client, fileHandle);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSARemove(FSAClientHandle client, char* path)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_Remove(shimBuffer->GetPtr(), client, (uint8_t*)path);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT __FSPrepareCmd_ChangeMode(iosu::fsa::FSAShimBuffer* fsaShimBuffer, IOSDevHandle fsaHandle, uint8_t* path, uint32 permission, uint32 permissionMask)
{
if (fsaShimBuffer == nullptr)
return FSA_RESULT::INVALID_BUFFER;
if (path == nullptr)
return FSA_RESULT::INVALID_PATH;
fsaShimBuffer->fsaDevHandle = fsaHandle;
fsaShimBuffer->ipcReqType = 0;
fsaShimBuffer->operationType = (uint32)FSA_CMD_OPERATION_TYPE::REWINDDIR;
size_t pathLen = strlen((char*)path);
for (sint32 i = 0; i < pathLen; i++)
fsaShimBuffer->request.cmdChangeMode.path[i] = path[i];
for (size_t i = pathLen; i < FSA_CMD_PATH_MAX_LENGTH; i++)
fsaShimBuffer->request.cmdChangeMode.path[i] = '\0';
fsaShimBuffer->request.cmdChangeMode.mode1 = permission;
fsaShimBuffer->request.cmdChangeMode.mode2 = permissionMask;
return FSA_RESULT::OK;
}
FSA_RESULT FSAChangeMode(FSAClientHandle client, const char* path, uint32 permission)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_ChangeMode(shimBuffer->GetPtr(), client, (uint8_t*)path, permission, 0x666);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAReadFile(FSAClientHandle client, void* buffer, uint32_t size, uint32_t count, FSFileHandle2 handle, uint32_t flags)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_ReadFile(shimBuffer->GetPtr(), client, buffer, size, count, 0, handle, flags & ~0x2);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAWriteFile(FSAClientHandle client, void* buffer, uint32_t size, uint32_t count, FSFileHandle2 handle, uint32_t flags)
{
if (!FSAShimCheckClientHandle(client))
return FSA_RESULT::INVALID_CLIENT_HANDLE;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_WriteFile(shimBuffer->GetPtr(), client, buffer, size, count, 0, handle, flags & ~0x2);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAGetInfoByQuery(FSAClientHandle client, char* path, uint32_t queryType, MEMPTR<void> outData)
{
if (outData.IsNull())
return FSA_RESULT::INVALID_BUFFER;
StackAllocator<MEMPTR<iosu::fsa::FSAShimBuffer>, 1> shimBuffer;
FSA_RESULT result = FSAShimAllocateBuffer(shimBuffer.GetPointer());
if (result != FSA_RESULT::OK)
return result;
result = __FSPrepareCmd_QueryInfo(shimBuffer->GetPtr(), client, (uint8_t*)path, queryType);
if (result == FSA_RESULT::OK)
{
result = __FSAIPCSubmitCommand(shimBuffer->GetPtr());
if (result == FSA_RESULT::OK)
{
if (queryType == FSA_QUERY_TYPE_FREESPACE)
{
*MEMPTR<uint64be>(outData.GetMPTR()) = shimBuffer->GetPtr()->response.cmdQueryInfo.queryFreeSpace.freespace;
}
else if (queryType == FSA_QUERY_TYPE_DEVICE_INFO)
{
*MEMPTR<FSADeviceInfo_t>(outData.GetMPTR()) = shimBuffer->GetPtr()->response.cmdQueryInfo.queryDeviceInfo.info;
}
else if (queryType == FSA_QUERY_TYPE_STAT)
{
*MEMPTR<FSStat_t>(outData.GetMPTR()) = shimBuffer->GetPtr()->response.cmdQueryInfo.queryStat.stat;
}
else
{
// TODO: implement other query types
cemu_assert_unimplemented();
result = FSA_RESULT::FATAL_ERROR;
}
}
}
FSAShimFreeBuffer(shimBuffer->GetPtr());
return result;
}
FSA_RESULT FSAGetStat(FSAClientHandle client, char* path, FSStat_t* outStat)
{
return FSAGetInfoByQuery(client, path, FSA_QUERY_TYPE_STAT, outStat);
}
FSA_RESULT FSAGetFreeSpaceSize(FSAClientHandle client, char* path, uint64* outSize)
{
return FSAGetInfoByQuery(client, path, FSA_QUERY_TYPE_DEVICE_INFO, outSize);
}
FSA_RESULT FSAGetDeviceInfo(FSAClientHandle client, char* path, void* outSize)
{
return FSAGetInfoByQuery(client, path, FSA_QUERY_TYPE_FREESPACE, outSize);
}
SysAllocator s_fsaStr_OK("FSA_STATUS_OK");
SysAllocator s_fsaStr_NOT_INIT("FSA_STATUS_NOT_INIT");
SysAllocator s_fsaStr_END_OF_DIRECTORY("FSA_STATUS_END_OF_DIRECTORY");
SysAllocator s_fsaStr_END_OF_FILE("FSA_STATUS_END_OF_FILE");
SysAllocator s_fsaStr_MAX_CLIENTS("FSA_STATUS_MAX_CLIENTS");
SysAllocator s_fsaStr_MAX_FILES("FSA_STATUS_MAX_FILES");
SysAllocator s_fsaStr_MAX_DIRS("FSA_STATUS_MAX_DIRS");
SysAllocator s_fsaStr_ALREADY_EXISTS("FSA_STATUS_ALREADY_EXISTS");
SysAllocator s_fsaStr_NOT_FOUND("FSA_STATUS_NOT_FOUND");
SysAllocator s_fsaStr_PERMISSION_ERROR("FSA_STATUS_PERMISSION_ERROR");
SysAllocator s_fsaStr_INVALID_PARAM("FSA_STATUS_INVALID_PARAM");
SysAllocator s_fsaStr_INVALID_PATH("FSA_STATUS_INVALID_PATH");
SysAllocator s_fsaStr_INVALID_BUFFER("FSA_STATUS_INVALID_BUFFER");
SysAllocator s_fsaStr_INVALID_ALIGNMENT("FSA_STATUS_INVALID_ALIGNMENT");
SysAllocator s_fsaStr_INVALID_CLIENT_HANDLE("FSA_STATUS_INVALID_CLIENT_HANDLE");
SysAllocator s_fsaStr_INVALID_FILE_HANDLE("FSA_STATUS_INVALID_FILE_HANDLE");
SysAllocator s_fsaStr_INVALID_DIR_HANDLE("FSA_STATUS_INVALID_DIR_HANDLE");
SysAllocator s_fsaStr_NOT_FILE("FSA_STATUS_NOT_FILE");
SysAllocator s_fsaStr_NOT_DIR("FSA_STATUS_NOT_DIR");
SysAllocator s_fsaStr_OUT_OF_RESOURCES("FSA_STATUS_OUT_OF_RESOURCES");
SysAllocator s_fsaStr_UNKNOWN("FSA_STATUS_???");
const char* FSAGetStatusStr(FSA_RESULT status)
{
switch (status)
{
case FSA_RESULT::OK:
{
return s_fsaStr_OK.GetPtr();
}
case FSA_RESULT::NOT_INIT:
{
return s_fsaStr_NOT_INIT.GetPtr();
}
case FSA_RESULT::END_OF_DIRECTORY:
{
return s_fsaStr_END_OF_DIRECTORY.GetPtr();
}
case FSA_RESULT::END_OF_FILE:
{
return s_fsaStr_END_OF_FILE.GetPtr();
}
case FSA_RESULT::MAX_CLIENTS:
{
return s_fsaStr_MAX_CLIENTS.GetPtr();
}
case FSA_RESULT::MAX_FILES:
{
return s_fsaStr_MAX_FILES.GetPtr();
}
case FSA_RESULT::MAX_DIRS:
{
return s_fsaStr_MAX_DIRS.GetPtr();
}
case FSA_RESULT::ALREADY_EXISTS:
{
return s_fsaStr_ALREADY_EXISTS.GetPtr();
}
case FSA_RESULT::NOT_FOUND:
{
return s_fsaStr_NOT_FOUND.GetPtr();
}
case FSA_RESULT::PERMISSION_ERROR:
{
return s_fsaStr_PERMISSION_ERROR.GetPtr();
}
case FSA_RESULT::INVALID_PARAM:
{
return s_fsaStr_INVALID_PARAM.GetPtr();
}
case FSA_RESULT::INVALID_PATH:
{
return s_fsaStr_INVALID_PATH.GetPtr();
}
case FSA_RESULT::INVALID_BUFFER:
{
return s_fsaStr_INVALID_BUFFER.GetPtr();
}
case FSA_RESULT::INVALID_ALIGNMENT:
{
return s_fsaStr_INVALID_ALIGNMENT.GetPtr();
}
case FSA_RESULT::INVALID_CLIENT_HANDLE:
{
return s_fsaStr_INVALID_CLIENT_HANDLE.GetPtr();
}
case FSA_RESULT::INVALID_FILE_HANDLE:
{
return s_fsaStr_INVALID_FILE_HANDLE.GetPtr();
}
case FSA_RESULT::INVALID_DIR_HANDLE:
{
return s_fsaStr_INVALID_DIR_HANDLE.GetPtr();
}
case FSA_RESULT::NOT_FILE:
{
return s_fsaStr_NOT_FILE.GetPtr();
}
case FSA_RESULT::NOT_DIR:
{
return s_fsaStr_NOT_DIR.GetPtr();
}
case FSA_RESULT::OUT_OF_RESOURCES:
{
return s_fsaStr_OUT_OF_RESOURCES.GetPtr();
}
case FSA_RESULT::FATAL_ERROR:
{
return s_fsaStr_UNKNOWN.GetPtr();
}
}
cemu_assert_unimplemented();
return s_fsaStr_UNKNOWN.GetPtr();
}
FSA_RESULT FSAMount(FSAClientHandle client, const char* source, const char* target, uint32 flags, void* arg_buf, uint32_t arg_len)
{
if ("/dev/sdcard01" == std::string_view(source) && "/vol/external01" == std::string_view(target) && flags == 0 && arg_buf == nullptr && arg_len == 0)
{
mountSDCard();
return FSA_RESULT::OK;
}
else
{
cemu_assert_unimplemented();
}
return FSA_RESULT::FATAL_ERROR;
}
FSA_RESULT FSAUnmount(FSAClientHandle client,
const char* mountedTarget,
uint32 flags)
{
return FSA_RESULT::OK;
}
void InitializeFS()
{
OSInitMutex(&s_fsGlobalMutex);
cafeExportRegister("coreinit", FSInit, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSShutdown, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetMountSource, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetMountSourceNext, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSMount, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSBindMount, LogType::CoreinitFile);
// client management
cafeExportRegister("coreinit", FSAddClientEx, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSAddClient, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSDelClient, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetClientNum, LogType::CoreinitFile);
// cmd
cafeExportRegister("coreinit", FSInitCmdBlock, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetAsyncResult, LogType::CoreinitFile);
// file operations
cafeExportRegister("coreinit", FSOpenFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSOpenFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSOpenFileExAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSOpenFileEx, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSCloseFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSCloseFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSReadFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSReadFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSReadFileWithPosAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSReadFileWithPos, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSWriteFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSWriteFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSWriteFileWithPosAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSWriteFileWithPos, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSSetPosFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSSetPosFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetPosFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetPosFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSAppendFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSAppendFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSTruncateFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSTruncateFile, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSRenameAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSRename, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSRemoveAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSRemove, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSMakeDirAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSMakeDir, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSChangeDirAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSChangeDir, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetCwdAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetCwd, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSIsEofAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSIsEof, LogType::CoreinitFile);
// directory operations
cafeExportRegister("coreinit", FSOpenDirAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSOpenDir, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSReadDirAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSReadDir, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSCloseDirAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSCloseDir, LogType::CoreinitFile);
// stat
cafeExportRegister("coreinit", FSGetFreeSpaceSizeAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetFreeSpaceSize, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetStatAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetStat, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetStatFileAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetStatFile, LogType::CoreinitFile);
// misc
cafeExportRegister("coreinit", FSFlushQuotaAsync, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSFlushQuota, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSSetUserData, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetUserData, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetCurrentCmdBlock, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetVolumeState, LogType::CoreinitFile);
cafeExportRegister("coreinit", FSGetErrorCodeForViewer, LogType::Placeholder);
cafeExportRegister("coreinit", FSGetLastErrorCodeForViewer, LogType::Placeholder);
cafeExportRegister("coreinit", FSAMakeDir, LogType::Placeholder);
cafeExportRegister("coreinit", FSAInit, LogType::Placeholder);
cafeExportRegister("coreinit", FSAAddClient, LogType::Placeholder);
cafeExportRegister("coreinit", FSADelClient, LogType::Placeholder);
cafeExportRegister("coreinit", FSARewindDir, LogType::Placeholder);
cafeExportRegister("coreinit", FSAGetDeviceInfo, LogType::Placeholder);
cafeExportRegister("coreinit", FSARename, LogType::Placeholder);
cafeExportRegister("coreinit", FSAChangeDir, LogType::Placeholder);
cafeExportRegister("coreinit", FSAMount, LogType::Placeholder);
cafeExportRegister("coreinit", FSAUnmount, LogType::Placeholder);
cafeExportRegister("coreinit", FSAChangeMode, LogType::Placeholder);
cafeExportRegister("coreinit", FSAReadDir, LogType::Placeholder);
cafeExportRegister("coreinit", FSAOpenDir, LogType::Placeholder);
cafeExportRegister("coreinit", FSACloseDir, LogType::Placeholder);
cafeExportRegister("coreinit", FSACloseFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSAFlushFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSAOpenFileEx, LogType::Placeholder);
cafeExportRegister("coreinit", FSAGetStatFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSAGetFreeSpaceSize, LogType::Placeholder);
cafeExportRegister("coreinit", FSASetPosFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSATruncateFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSARemove, LogType::Placeholder);
cafeExportRegister("coreinit", FSAReadFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSAWriteFile, LogType::Placeholder);
cafeExportRegister("coreinit", FSAGetStat, LogType::Placeholder);
cafeExportRegister("coreinit", FSAGetStatusStr, LogType::Placeholder);
g_fsRegisteredClientBodies = nullptr;
}
} // namespace coreinit
| 102,490
|
C++
|
.cpp
| 2,386
| 39.773261
| 280
| 0.763293
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,100
|
coreinit_Init.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Init.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/libs/coreinit/coreinit.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/padscore/padscore.h"
#include "Cafe/OS/libs/coreinit/coreinit_SysHeap.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/vpad/vpad.h"
#include "Cafe/OS/libs/coreinit/coreinit_GHS.h"
#include "Cafe/OS/libs/coreinit/coreinit_DynLoad.h"
#include "Cafe/OS/libs/coreinit/coreinit_MEM.h"
#include "Cafe/OS/libs/coreinit/coreinit_FG.h"
#include "Cafe/CafeSystem.h"
extern MPTR _entryPoint;
extern RPLModule* applicationRPX;
typedef struct
{
MPTR argv[32];
uint32be argc;
char argStorage[0x1000];
}coreinitInit_t;
coreinitInit_t* _coreinitInfo = nullptr;
MPTR OSAllocFromSystem(uint32 size, uint32 alignment)
{
return coreinit_allocFromSysArea(size, alignment);
}
void OSFreeToSystem(MPTR mem)
{
coreinit_freeToSysArea(mem);
}
extern std::string _pathToExecutable;
sint32 argStorageIndex;
void _AddArg(const char* arg, sint32 len)
{
uint32 argc = _coreinitInfo->argc;
char* argStorageStr = _coreinitInfo->argStorage + argStorageIndex;
memcpy(argStorageStr, arg, len);
argStorageStr[len] = '\0';
argStorageIndex += (sint32)strlen(arg) + 1;
_coreinitInfo->argv[argc] = _swapEndianU32(memory_getVirtualOffsetFromPointer(argStorageStr));
_coreinitInfo->argc = argc+1;
}
sint32 _GetArgLength(const char* arg)
{
sint32 c = 0;
while (*arg)
{
if (*arg == ' ')
break; // end at whitespace
cemu_assert_debug(*arg != '\"' && *arg != '\''); // todo
arg++;
c++;
}
return c;
}
static std::string GetLaunchArgs()
{
std::string argStr = CafeSystem::GetForegroundTitleArgStr();
if(std::vector<std::string> overrideArgs; CafeSystem::GetOverrideArgStr(overrideArgs))
{
// args are overriden by launch directive (OSLaunchTitleByPath)
// keep the rpx path but use the arguments from the override
if (size_t pos = argStr.find(' '); pos != std::string::npos)
argStr.resize(pos);
for(size_t i=0; i<overrideArgs.size(); i++)
{
argStr += " ";
argStr += overrideArgs[i];
}
}
return argStr;
}
void CafeInit()
{
// extract executable filename
sint32 rpxPathStart = (sint32)_pathToExecutable.size() - 1;
if (rpxPathStart > 0)
{
while (rpxPathStart > 0 && _pathToExecutable[rpxPathStart-1] != '/')
rpxPathStart--;
}
else
{
rpxPathStart = 0;
}
std::string_view rpxFileName(_pathToExecutable.data() + rpxPathStart, _pathToExecutable.size() - rpxPathStart);
argStorageIndex = 0;
_coreinitInfo->argc = 0;
_AddArg(rpxFileName.data(), rpxFileName.size());
strcpy((char*)_coreinitInfo->argStorage, std::string(rpxFileName).c_str());
std::string _argStr = GetLaunchArgs();
CafeSystem::UnsetOverrideArgs(); // make sure next launch doesn't accidentally use the same arguments
const char* argString = _argStr.c_str();
// attach parameters from arg string
if (argString && argString[0] != '\0')
{
const char* t = strstr(argString, ".rpx");
if (t)
{
t += 4;
while (*t)
{
// skip all whitespace
while (*t)
{
if (*t == ' ')
{
t++;
}
else
break;
}
// get length of arg
sint32 argLength = _GetArgLength(t);
if (argLength > 0)
{
// add arg
_AddArg(t, argLength);
// next
t += argLength;
}
}
}
else
{
cemuLog_logDebug(LogType::Force, "Unable to find end of rpx file name in arg string");
}
}
// setup UGQR
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->spr.UGQR[0 + 2] = 0x00040004;
hCPU->spr.UGQR[0 + 3] = 0x00050005;
hCPU->spr.UGQR[0 + 4] = 0x00060006;
hCPU->spr.UGQR[0 + 5] = 0x00070007;
coreinit::InitForegroundBucket();
coreinit::InitSysHeap();
}
struct PreinitUserHeapStruct
{
MEMPTR<coreinit::MEMHeapBase> heapTempMEM1;
MEMPTR<coreinit::MEMHeapBase> heapTempFG;
MEMPTR<coreinit::MEMHeapBase> heapTempMEM2;
};
SysAllocator<PreinitUserHeapStruct> g_preinitUserParam;
void InitCafeHeaps()
{
// init default heaps
g_preinitUserParam->heapTempMEM1 = nullptr;
g_preinitUserParam->heapTempFG = nullptr;
g_preinitUserParam->heapTempMEM2 = nullptr;
coreinit::InitDefaultHeaps(g_preinitUserParam->heapTempMEM1, g_preinitUserParam->heapTempFG, g_preinitUserParam->heapTempMEM2);
// if __preinit_user export exists in main executable, run it and pass our heaps
MPTR exportAddr = applicationRPX ? RPLLoader_FindRPLExport(applicationRPX, "__preinit_user", false) : MPTR_NULL;
if (exportAddr != MPTR_NULL)
{
PPCCoreCallback(exportAddr, &g_preinitUserParam->heapTempMEM1, &g_preinitUserParam->heapTempFG, &g_preinitUserParam->heapTempMEM2);
}
// setup heaps
if (g_preinitUserParam->heapTempMEM1 != nullptr)
coreinit::MEMSetBaseHeapHandle(0, g_preinitUserParam->heapTempMEM1);
if (g_preinitUserParam->heapTempFG != nullptr)
coreinit::MEMSetBaseHeapHandle(8, g_preinitUserParam->heapTempFG);
if (g_preinitUserParam->heapTempMEM2 != nullptr)
coreinit::MEMSetBaseHeapHandle(1, g_preinitUserParam->heapTempMEM2);
}
MPTR CoreInitEntry(sint32 argc, MPTR argv)
{
const char* rpxPath = (char*)memory_getPointerFromVirtualOffset(memory_readU32(argv + 0));
InitCafeHeaps();
// do a dummy allocation via the OSDynLoad allocator
// Watch Dogs relies on this to correctly set up its malloc() allocator
// must be larger than 0x190 to trigger creation of a new memory segment. But also must not be close to page alignment (0x1000) or else the bug will trigger
void* dummyAlloc = coreinit::OSDynLoad_AllocatorAlloc(0x500, 0x4);
if (dummyAlloc)
coreinit::OSDynLoad_AllocatorFree(dummyAlloc);
return _entryPoint;
}
sint32 _coreinitTitleEntryPoint;
void coreinit_start(PPCInterpreter_t* hCPU)
{
_coreinitInfo = (coreinitInit_t*)memory_getPointerFromVirtualOffset(coreinit_allocFromSysArea(sizeof(coreinitInit_t), 32));
memset(_coreinitInfo, 0, sizeof(coreinitInit_t));
CafeInit();
_coreinitTitleEntryPoint = CoreInitEntry(_coreinitInfo->argc, memory_getVirtualOffsetFromPointer(_coreinitInfo->argv));
RPLLoader_CallEntrypoints();
// init vpadbase (todo - simulate entrypoints for HLE modules)
padscore::start();
vpad::start();
// continue at main executable entrypoint
hCPU->gpr[4] = memory_getVirtualOffsetFromPointer(_coreinitInfo->argv);
hCPU->gpr[3] = _coreinitInfo->argc;
hCPU->instructionPointer = _coreinitTitleEntryPoint;
}
| 6,348
|
C++
|
.cpp
| 193
| 30.440415
| 157
| 0.744941
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,101
|
coreinit_Thread.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Thread.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include "Cafe/HW/Espresso/PPCCallback.h"
#include "Cafe/OS/RPL/rpl.h"
#include "Cafe/OS/libs/coreinit/coreinit_Thread.h"
#include "Cafe/OS/libs/coreinit/coreinit_Time.h"
#include "Cafe/OS/libs/coreinit/coreinit_Alarm.h"
#include "Cafe/OS/libs/snd_core/ax.h"
#include "Cafe/HW/Espresso/Debugger/GDBStub.h"
#include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h"
#include "Cafe/HW/Espresso/Recompiler/PPCRecompiler.h"
#include "util/helpers/Semaphore.h"
#include "util/helpers/ConcurrentQueue.h"
#include "util/Fiber/Fiber.h"
#include "util/helpers/helpers.h"
SlimRWLock srwlock_activeThreadList;
// public list of active threads
MPTR activeThread[256];
sint32 activeThreadCount = 0;
void nnNfp_update();
namespace coreinit
{
void __OSFiberThreadEntry(void* thread);
void __OSAddReadyThreadToRunQueue(OSThread_t* thread);
void __OSRemoveThreadFromRunQueues(OSThread_t* thread);
};
namespace coreinit
{
// scheduler state
std::atomic<bool> sSchedulerActive;
std::vector<std::thread> sSchedulerThreads;
std::mutex sSchedulerStateMtx;
SysAllocator<OSThreadQueue> g_activeThreadQueue; // list of all threads (can include non-detached inactive threads)
SysAllocator<OSThreadQueue, 3> g_coreRunQueue;
CounterSemaphore g_coreRunQueueThreadCount[3];
bool g_isMulticoreMode;
thread_local uint32 t_assignedCoreIndex;
thread_local Fiber* t_schedulerFiber;
struct OSHostThread
{
OSHostThread(OSThread_t* thread) : m_thread(thread), m_fiber(__OSFiberThreadEntry, this, this)
{
}
~OSHostThread() = default;
OSThread_t* m_thread;
Fiber m_fiber;
// padding (used as stack memory in recompiler)
uint8 padding[1024 * 128];
PPCInterpreter_t ppcInstance;
uint32 selectedCore;
};
std::unordered_map<OSThread_t*, OSHostThread*> s_threadToFiber;
bool __CemuIsMulticoreMode()
{
return g_isMulticoreMode;
}
// create host thread (fiber) that will be used to run the PPC instance
// note that host threads are fibers and not actual threads
void __OSCreateHostThread(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
cemu_assert_debug(s_threadToFiber.find(thread) == s_threadToFiber.end());
OSHostThread* hostThread = new OSHostThread(thread);
s_threadToFiber.emplace(thread, hostThread);
}
// delete host thread
void __OSDeleteHostThread(OSThread_t* thread)
{
static OSHostThread* _deleteQueue = nullptr;
cemu_assert_debug(__OSHasSchedulerLock());
if (_deleteQueue)
{
delete _deleteQueue;
_deleteQueue = nullptr;
}
// delete with a delay (using queue of length 1)
// since the fiber might still be in use right now we have to delay the deletion
auto hostThread = s_threadToFiber[thread];
s_threadToFiber.erase(thread);
_deleteQueue = hostThread;
}
// add thread to active queue
void __OSActivateThread(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
g_activeThreadQueue->addThread(thread, &thread->activeThreadChain); // todo - check if thread already in queue
MPTR threadMPTR = memory_getVirtualOffsetFromPointer(thread);
srwlock_activeThreadList.LockWrite();
bool alreadyActive = false;
for (sint32 i = 0; i < activeThreadCount; i++)
{
if (activeThread[i] == threadMPTR)
{
cemu_assert_debug(false); // should not happen
alreadyActive = true;
}
}
if (alreadyActive == false)
{
activeThread[activeThreadCount] = threadMPTR;
activeThreadCount++;
}
__OSCreateHostThread(thread);
srwlock_activeThreadList.UnlockWrite();
}
// remove thread from active queue. Reset id and state
void __OSDeactivateThread(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
// remove thread from active thread list
MPTR t = memory_getVirtualOffsetFromPointer(thread);
srwlock_activeThreadList.LockWrite();
bool noHit = true;
for (sint32 i = 0; i < activeThreadCount; i++)
{
if (activeThread[i] == t)
{
activeThread[i] = activeThread[activeThreadCount - 1];
activeThreadCount--;
noHit = false;
break;
}
}
cemu_assert_debug(noHit == false);
srwlock_activeThreadList.UnlockWrite();
g_activeThreadQueue->removeThread(thread, &thread->activeThreadChain); // todo - check if thread in queue
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_NONE);
thread->id = 0x8000;
__OSDeleteHostThread(thread);
}
bool __OSIsThreadActive(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
MPTR threadMPTR = memory_getVirtualOffsetFromPointer(thread);
srwlock_activeThreadList.LockWrite();
bool isRunable = false;
for (sint32 i = 0; i < activeThreadCount; i++)
{
if (activeThread[i] == threadMPTR)
{
srwlock_activeThreadList.UnlockWrite();
return true;
}
}
srwlock_activeThreadList.UnlockWrite();
return false;
}
// thread
OSThread_t* __currentCoreThread[3] = {};
void OSSetCurrentThread(uint32 coreIndex, OSThread_t* thread)
{
if (coreIndex < 3)
__currentCoreThread[coreIndex] = thread;
}
OSThread_t* OSGetCurrentThread()
{
PPCInterpreter_t* currentInstance = PPCInterpreter_getCurrentInstance();
if (currentInstance == nullptr)
return nullptr;
return __currentCoreThread[currentInstance->spr.UPIR];
}
void threadEntry(PPCInterpreter_t* hCPU)
{
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
uint32 r3 = hCPU->gpr[3];
uint32 r4 = hCPU->gpr[4];
uint32 lr = hCPU->spr.LR;
// cpp exception init callback
//const uint32 im = OSDisableInterrupts(); -> on an actual Wii U interrupts are disabled for this callback, but there are games that yield the thread in the callback (see Angry Birds Star Wars)
if (gCoreinitData->__cpp_exception_init_ptr != MPTR_NULL)
{
PPCCoreCallback(_swapEndianU32(gCoreinitData->__cpp_exception_init_ptr), ¤tThread->crt.eh_globals);
}
//OSRestoreInterrupts(im);
// forward to thread entrypoint
hCPU->spr.LR = lr;
hCPU->gpr[3] = r3;
hCPU->gpr[4] = r4;
hCPU->instructionPointer = currentThread->entrypoint.GetMPTR();
}
void coreinitExport_OSExitThreadDepr(PPCInterpreter_t* hCPU);
void __OSInitContext(OSContext_t* ctx, MEMPTR<void> initialIP, MEMPTR<void> initialStackPointer)
{
ctx->SetContextMagic();
ctx->gpr[0] = 0; // r0 is left uninitialized on console?
for(auto& it : ctx->gpr)
it = 0;
ctx->gpr[1] = _swapEndianU32(initialStackPointer.GetMPTR());
ctx->gpr[2] = _swapEndianU32(RPLLoader_GetSDA2Base());
ctx->gpr[13] = _swapEndianU32(RPLLoader_GetSDA1Base());
ctx->srr0 = initialIP.GetMPTR();
ctx->cr = 0;
ctx->ukn0A8 = 0;
ctx->ukn0AC = 0;
ctx->gqr[0] = 0;
ctx->gqr[1] = 0;
ctx->gqr[2] = 0;
ctx->gqr[3] = 0;
ctx->gqr[4] = 0;
ctx->gqr[5] = 0;
ctx->gqr[6] = 0;
ctx->gqr[7] = 0;
ctx->dsi_dar = 0;
ctx->srr1 = 0x9032;
ctx->xer = 0;
ctx->dsi_dsisr = 0;
ctx->upir = 0;
ctx->boostCount = 0;
ctx->state = 0;
for(auto& it : ctx->coretime)
it = 0;
ctx->starttime = 0;
ctx->ghs_errno = 0;
ctx->upmc1 = 0;
ctx->upmc2 = 0;
ctx->upmc3 = 0;
ctx->upmc4 = 0;
ctx->ummcr0 = 0;
ctx->ummcr1 = 0;
}
void __OSThreadInit(OSThread_t* thread, MEMPTR<void> entrypoint, uint32 argInt, MEMPTR<void> argPtr, MEMPTR<void> stackTop, uint32 stackSize, sint32 priority, uint32 upirCoreIndex, OSThread_t::THREAD_TYPE threadType)
{
thread->effectivePriority = priority;
thread->type = threadType;
thread->basePriority = priority;
thread->SetThreadMagic();
thread->id = 0x8000;
thread->waitAlarm = nullptr;
thread->entrypoint = entrypoint;
thread->quantumTicks = 0;
if(entrypoint)
{
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
thread->suspendCounter = 1;
}
else
{
thread->state = OSThread_t::THREAD_STATE::STATE_NONE;
thread->suspendCounter = 0;
}
thread->exitValue = (uint32)-1;
thread->requestFlags = OSThread_t::REQUEST_FLAG_BIT::REQUEST_FLAG_NONE;
thread->pendingSuspend = 0;
thread->suspendResult = 0xFFFFFFFF;
thread->coretimeSumQuantumStart = 0;
thread->deallocatorFunc = nullptr;
thread->cleanupCallback = nullptr;
thread->waitingForFastMutex = nullptr;
thread->stateFlags = 0;
thread->waitingForMutex = nullptr;
memset(&thread->crt, 0, sizeof(thread->crt));
static_assert(sizeof(thread->crt) == 0x1D8);
thread->tlsBlocksMPTR = 0;
thread->numAllocatedTLSBlocks = 0;
thread->tlsStatus = 0;
OSInitThreadQueueEx(&thread->joinQueue, thread);
OSInitThreadQueueEx(&thread->suspendQueue, thread);
thread->mutexQueue.ukn08 = thread;
thread->mutexQueue.ukn0C = 0;
thread->mutexQueue.tail = nullptr;
thread->mutexQueue.head = nullptr;
thread->ownedFastMutex.next = nullptr;
thread->ownedFastMutex.prev = nullptr;
thread->contendedFastMutex.next = nullptr;
thread->contendedFastMutex.prev = nullptr;
MEMPTR<void> alignedStackTop{MEMPTR<void>(stackTop).GetMPTR() & 0xFFFFFFF8};
MEMPTR<uint32be> alignedStackTop32{alignedStackTop};
alignedStackTop32[-1] = 0;
alignedStackTop32[-2] = 0;
__OSInitContext(&thread->context, MEMPTR<void>(PPCInterpreter_makeCallableExportDepr(threadEntry)), (void*)(alignedStackTop32.GetPtr() - 2));
thread->stackBase = stackTop; // without alignment
thread->stackEnd = ((uint8*)stackTop.GetPtr() - stackSize);
thread->context.upir = upirCoreIndex;
thread->context.lr = _swapEndianU32(PPCInterpreter_makeCallableExportDepr(coreinitExport_OSExitThreadDepr));
thread->context.gpr[3] = _swapEndianU32(argInt);
thread->context.gpr[4] = _swapEndianU32(argPtr.GetMPTR());
*(uint32be*)((uint8*)stackTop.GetPtr() - stackSize) = 0xDEADBABE;
thread->alarmRelatedUkn = 0;
for(auto& it : thread->specificArray)
it = nullptr;
thread->context.fpscr.fpscr = 4;
for(sint32 i=0; i<32; i++)
{
thread->context.fp_ps0[i] = 0.0;
thread->context.fp_ps1[i] = 0.0;
}
thread->context.gqr[2] = 0x40004;
thread->context.gqr[3] = 0x50005;
thread->context.gqr[4] = 0x60006;
thread->context.gqr[5] = 0x70007;
for(sint32 i=0; i<Espresso::CORE_COUNT; i++)
thread->context.coretime[i] = 0;
// currentRunQueue and waitQueueLink is not initialized by COS and instead overwritten without validation
// since we already have integrity checks in other functions, lets initialize it here
for(sint32 i=0; i<Espresso::CORE_COUNT; i++)
thread->currentRunQueue[i] = nullptr;
thread->waitQueueLink.prev = nullptr;
thread->waitQueueLink.next = nullptr;
thread->wakeTimeRelatedUkn2 = 0;
thread->wakeUpCount = 0;
thread->wakeUpTime = 0;
thread->wakeTimeRelatedUkn1 = 0x7FFFFFFFFFFFFFFF;
thread->quantumTicks = 0;
thread->coretimeSumQuantumStart = 0;
thread->totalCycles = 0;
for(auto& it : thread->padding68C)
it = 0;
}
void SetThreadAffinityToCore(OSThread_t* thread, uint32 coreIndex)
{
cemu_assert_debug(coreIndex < 3);
thread->attr &= ~(OSThread_t::ATTR_BIT::ATTR_AFFINITY_CORE0 | OSThread_t::ATTR_BIT::ATTR_AFFINITY_CORE1 | OSThread_t::ATTR_BIT::ATTR_AFFINITY_CORE2 | OSThread_t::ATTR_BIT::ATTR_UKN_010);
thread->context.affinity &= 0xFFFFFFF8;
if (coreIndex == 0)
{
thread->attr |= OSThread_t::ATTR_BIT::ATTR_AFFINITY_CORE0;
thread->context.affinity |= (1<<0);
}
else if (coreIndex == 1)
{
thread->attr |= OSThread_t::ATTR_BIT::ATTR_AFFINITY_CORE1;
thread->context.affinity |= (1<<1);
}
else // if (coreIndex == 2)
{
thread->attr |= OSThread_t::ATTR_BIT::ATTR_AFFINITY_CORE2;
thread->context.affinity |= (1<<2);
}
}
void __OSCreateThreadOnActiveThreadWorkaround(OSThread_t* thread)
{
__OSLockScheduler();
bool isThreadStillActive = __OSIsThreadActive(thread);
if (isThreadStillActive)
{
// workaround for games that restart threads before they correctly entered stopped/moribund state
// seen in Fast Racing Neo at boot (0x020617BC OSCreateThread)
cemuLog_log(LogType::Force, "Game attempting to re-initialize existing thread");
while ((thread->state == OSThread_t::THREAD_STATE::STATE_READY || thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING) && thread->suspendCounter == 0)
{
// wait for thread to finish
__OSUnlockScheduler();
OSSleepTicks(ESPRESSO_TIMER_CLOCK / 2000); // sleep 0.5ms
__OSLockScheduler();
}
if (__OSIsThreadActive(thread) && thread->state == OSThread_t::THREAD_STATE::STATE_MORIBUND)
{
cemuLog_log(LogType::Force, "Calling OSCreateThread() on thread which is still active (Thread exited without detached flag). Forcing OSDetachThread()...");
__OSUnlockScheduler();
OSDetachThread(thread);
__OSLockScheduler();
}
}
cemu_assert_debug(__OSIsThreadActive(thread) == false);
__OSUnlockScheduler();
}
bool __OSCreateThreadInternal2(OSThread_t* thread, MEMPTR<void> entrypoint, uint32 argInt, MEMPTR<void> argPtr, MEMPTR<void> stackBase, uint32 stackSize, sint32 priority, uint32 attrBits, OSThread_t::THREAD_TYPE threadType)
{
__OSCreateThreadOnActiveThreadWorkaround(thread);
OSThread_t* currentThread = OSGetCurrentThread();
if (priority < 0 || priority >= 32)
{
cemuLog_log(LogType::APIErrors, "OSCreateThreadInternal: Thread priority must be in range 0-31");
return false;
}
if (threadType == OSThread_t::THREAD_TYPE::TYPE_IO)
{
priority = priority + 0x20;
}
else if (threadType == OSThread_t::THREAD_TYPE::TYPE_APP)
{
priority = priority + 0x40;
}
if(attrBits >= 0x20 || stackBase == nullptr || stackSize == 0)
{
cemuLog_logDebug(LogType::APIErrors, "OSCreateThreadInternal: Invalid attributes, stack base or size");
return false;
}
uint32 im = OSDisableInterrupts();
__OSLockScheduler(thread);
uint32 coreIndex = PPCInterpreter_getCurrentInstance() ? OSGetCoreId() : 1;
__OSThreadInit(thread, entrypoint, argInt, argPtr, stackBase, stackSize, priority, coreIndex, threadType);
thread->threadName = nullptr;
thread->context.affinity = attrBits & 7;
thread->attr = attrBits;
if ((attrBits & 7) == 0) // if no explicit affinity is given, use the current core
SetThreadAffinityToCore(thread, OSGetCoreId());
if(currentThread)
{
for(sint32 i=0; i<Espresso::CORE_COUNT; i++)
{
thread->dsiCallback[i] = currentThread->dsiCallback[i];
thread->isiCallback[i] = currentThread->isiCallback[i];
thread->programCallback[i] = currentThread->programCallback[i];
thread->perfMonCallback[i] = currentThread->perfMonCallback[i];
thread->alignmentExceptionCallback[i] = currentThread->alignmentExceptionCallback[i];
}
thread->context.srr1 = thread->context.srr1 | (currentThread->context.srr1 & 0x900);
thread->context.fpscr.fpscr = thread->context.fpscr.fpscr | (currentThread->context.fpscr.fpscr & 0xF8);
}
else
{
for(sint32 i=0; i<Espresso::CORE_COUNT; i++)
{
thread->dsiCallback[i] = 0;
thread->isiCallback[i] = 0;
thread->programCallback[i] = 0;
thread->perfMonCallback[i] = 0;
thread->alignmentExceptionCallback[i] = nullptr;
}
}
if (entrypoint)
{
thread->id = 0x8000;
__OSActivateThread(thread); // also handles adding the thread to g_activeThreadQueue
}
__OSUnlockScheduler(thread);
OSRestoreInterrupts(im);
// recompile entry point function
if (entrypoint)
PPCRecompiler_recompileIfUnvisited(entrypoint.GetMPTR());
return true;
}
bool OSCreateThreadType(OSThread_t* thread, MPTR entryPoint, sint32 numParam, void* ptrParam, void* stackTop, sint32 stackSize, sint32 priority, uint32 attr, OSThread_t::THREAD_TYPE threadType)
{
if(threadType != OSThread_t::THREAD_TYPE::TYPE_APP && threadType != OSThread_t::THREAD_TYPE::TYPE_IO)
{
cemuLog_logDebug(LogType::APIErrors, "OSCreateThreadType: Invalid thread type");
cemu_assert_suspicious();
return false;
}
return __OSCreateThreadInternal2(thread, MEMPTR<void>(entryPoint), numParam, ptrParam, stackTop, stackSize, priority, attr, threadType);
}
bool OSCreateThread(OSThread_t* thread, MPTR entryPoint, sint32 numParam, void* ptrParam, void* stackTop, sint32 stackSize, sint32 priority, uint32 attr)
{
return __OSCreateThreadInternal2(thread, MEMPTR<void>(entryPoint), numParam, ptrParam, stackTop, stackSize, priority, attr, OSThread_t::THREAD_TYPE::TYPE_APP);
}
// similar to OSCreateThreadType, but can be used to create any type of thread
bool __OSCreateThreadType(OSThread_t* thread, MPTR entryPoint, sint32 numParam, void* ptrParam, void* stackTop, sint32 stackSize, sint32 priority, uint32 attr, OSThread_t::THREAD_TYPE threadType)
{
return __OSCreateThreadInternal2(thread, MEMPTR<void>(entryPoint), numParam, ptrParam, stackTop, stackSize, priority, attr, threadType);
}
bool OSRunThread(OSThread_t* thread, MPTR funcAddress, sint32 numParam, void* ptrParam)
{
__OSLockScheduler();
cemu_assert_debug(PPCInterpreter_getCurrentInstance() == nullptr || OSGetCurrentThread() != thread); // called on self, what should this function do?
if (thread->state != OSThread_t::THREAD_STATE::STATE_NONE && thread->state != OSThread_t::THREAD_STATE::STATE_MORIBUND)
{
// unsure about this case
cemuLog_logDebug(LogType::Force, "OSRunThread called on thread which cannot be ran");
__OSUnlockScheduler();
return false;
}
if (thread->state == OSThread_t::THREAD_STATE::STATE_MORIBUND)
{
thread->state = OSThread_t::THREAD_STATE::STATE_NONE;
coreinit::__OSDeactivateThread(thread);
coreinit::__OSRemoveThreadFromRunQueues(thread);
}
// set thread state
// todo - this should fully reinitialize the thread?
thread->entrypoint = funcAddress;
thread->context.srr0 = PPCInterpreter_makeCallableExportDepr(threadEntry);
thread->context.lr = _swapEndianU32(PPCInterpreter_makeCallableExportDepr(coreinitExport_OSExitThreadDepr));
thread->context.gpr[3] = _swapEndianU32(numParam);
thread->context.gpr[4] = _swapEndianU32(memory_getVirtualOffsetFromPointer(ptrParam));
thread->suspendCounter = 0; // verify
MPTR threadMPTR = memory_getVirtualOffsetFromPointer(thread);
coreinit::__OSActivateThread(thread);
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
__OSAddReadyThreadToRunQueue(thread);
__OSUnlockScheduler();
return true;
}
void OSExitThread(sint32 exitValue)
{
PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance();
hCPU->gpr[3] = exitValue;
OSThread_t* currentThread = coreinit::OSGetCurrentThread();
// thread cleanup callback
if (currentThread->cleanupCallback)
{
currentThread->stateFlags = _swapEndianU32(_swapEndianU32(currentThread->stateFlags) | 0x00000001);
PPCCoreCallback(currentThread->cleanupCallback.GetMPTR(), currentThread, currentThread->stackEnd);
}
// cpp exception cleanup
if (gCoreinitData->__cpp_exception_cleanup_ptr != 0 && currentThread->crt.eh_globals != nullptr)
{
PPCCoreCallback(_swapEndianU32(gCoreinitData->__cpp_exception_cleanup_ptr), ¤tThread->crt.eh_globals);
currentThread->crt.eh_globals = nullptr;
}
// set exit code
currentThread->exitValue = exitValue;
__OSLockScheduler();
// release held synchronization primitives
if (!currentThread->mutexQueue.isEmpty())
{
cemuLog_log(LogType::Force, "OSExitThread: Thread is holding mutexes");
while (true)
{
OSMutex* mutex = currentThread->mutexQueue.getFirst();
if (!mutex)
break;
if (mutex->owner != currentThread)
{
cemuLog_log(LogType::Force, "OSExitThread: Thread is holding mutex which it doesn't own");
currentThread->mutexQueue.removeMutex(mutex);
continue;
}
coreinit::OSUnlockMutexInternal(mutex);
}
}
// todo - release all fast mutexes
// handle join queue
if (!currentThread->joinQueue.isEmpty())
currentThread->joinQueue.wakeupEntireWaitQueue(false);
if ((currentThread->attr & 8) != 0)
{
// deactivate thread since it is detached
currentThread->state = OSThread_t::THREAD_STATE::STATE_NONE;
coreinit::__OSDeactivateThread(currentThread);
// queue call to thread deallocator if set
if (!currentThread->deallocatorFunc.IsNull())
__OSQueueThreadDeallocation(currentThread);
}
else
{
// non-detached threads remain active
currentThread->state = OSThread_t::THREAD_STATE::STATE_MORIBUND;
}
PPCCore_switchToSchedulerWithLock();
}
void OSSetThreadSpecific(uint32 index, void* value)
{
OSThread_t* currentThread = OSGetCurrentThread();
if (index >= (uint32)currentThread->specificArray.size())
return;
currentThread->specificArray[index] = value;
}
void* OSGetThreadSpecific(uint32 index)
{
OSThread_t* currentThread = OSGetCurrentThread();
if (index >= (uint32)currentThread->specificArray.size())
return nullptr;
return currentThread->specificArray[index].GetPtr();
}
void OSSetThreadName(OSThread_t* thread, const char* name)
{
thread->threadName = name;
}
const char* OSGetThreadName(OSThread_t* thread)
{
return thread->threadName.GetPtr();
}
void coreinitExport_OSExitThreadDepr(PPCInterpreter_t* hCPU)
{
ppcDefineParamU32(exitCode, 0);
OSExitThread(exitCode);
}
void OSYieldThread()
{
PPCCore_switchToScheduler();
}
void _OSSleepTicks_alarmHandler(uint64 currentTick, void* context)
{
cemu_assert_debug(__OSHasSchedulerLock());
OSThreadQueue* threadQueue = (OSThreadQueue*)context;
threadQueue->wakeupEntireWaitQueue(false);
}
void OSSleepTicks(uint64 ticks)
{
cemu_assert_debug(__OSHasSchedulerLock() == false);
StackAllocator<OSThreadQueue> _threadQueue;
OSInitThreadQueue(_threadQueue.GetPointer());
__OSLockScheduler();
OSHostAlarm* hostAlarm = OSHostAlarmCreate(coreinit_getOSTime() + ticks, 0, _OSSleepTicks_alarmHandler, _threadQueue.GetPointer());
_threadQueue.GetPointer()->queueAndWait(OSGetCurrentThread());
OSHostAlarmDestroy(hostAlarm);
__OSUnlockScheduler();
}
void OSDetachThread(OSThread_t* thread)
{
__OSLockScheduler();
thread->attr |= OSThread_t::ATTR_BIT::ATTR_DETACHED;
if (thread->state == OSThread_t::THREAD_STATE::STATE_MORIBUND)
{
// exit thread
// ?
// todo -> call deallocator
thread->state = OSThread_t::THREAD_STATE::STATE_NONE;
thread->id = 0x8000;
coreinit::__OSDeactivateThread(thread);
if (!thread->joinQueue.isEmpty())
{
// handle join queue
thread->joinQueue.wakeupEntireWaitQueue(true);
}
}
__OSUnlockScheduler();
}
bool OSJoinThread(OSThread_t* thread, uint32be* exitValue)
{
__OSLockScheduler();
if ((thread->attr & OSThread_t::ATTR_DETACHED) == 0 && thread->state != OSThread_t::THREAD_STATE::STATE_MORIBUND)
{
cemu_assert_debug(thread->joinQueue.isEmpty());
// thread still running, wait in join queue
thread->joinQueue.queueAndWait(OSGetCurrentThread());
}
else if (thread->state != OSThread_t::THREAD_STATE::STATE_MORIBUND)
{
// cannot join detached and active threads
cemuLog_logDebug(LogType::Force, "Cannot join detached active thread");
__OSUnlockScheduler();
return false;
}
// thread already ended and is still attached, get return value
cemu_assert_debug(thread->state == OSThread_t::THREAD_STATE::STATE_MORIBUND);
cemu_assert_debug((thread->attr & OSThread_t::ATTR_DETACHED) == 0);
if (exitValue)
*exitValue = thread->exitValue;
// end thread
thread->state = OSThread_t::THREAD_STATE::STATE_NONE;
__OSDeactivateThread(thread);
coreinit::__OSRemoveThreadFromRunQueues(thread);
thread->id = 0x8000;
if (!thread->deallocatorFunc.IsNull())
__OSQueueThreadDeallocation(thread);
__OSUnlockScheduler();
return true;
}
// adds the thread to each core's run queue if in runable state
void __OSAddReadyThreadToRunQueue(OSThread_t* thread)
{
cemu_assert_debug(MMU_IsInPPCMemorySpace(thread));
cemu_assert_debug(thread->IsValidMagic());
cemu_assert_debug(__OSHasSchedulerLock());
if (thread->state != OSThread_t::THREAD_STATE::STATE_READY)
return;
if (thread->suspendCounter != 0)
return;
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
{
if (thread->currentRunQueue[i] != nullptr)
continue; // already on the queue
// check affinity
if(!thread->context.hasCoreAffinitySet(i))
continue;
g_coreRunQueue.GetPtr()[i].addThread(thread, thread->linkRun + i);
thread->currentRunQueue[i] = (g_coreRunQueue.GetPtr() + i);
g_coreRunQueueThreadCount[i].increment();
}
}
void __OSRemoveThreadFromRunQueues(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
{
if(thread->currentRunQueue[i] == nullptr)
continue;
g_coreRunQueue.GetPtr()[i].removeThread(thread, thread->linkRun + i);
thread->currentRunQueue[i] = nullptr;
g_coreRunQueueThreadCount[i].decrement();
}
}
// returns true if thread runs on same core and has higher priority
bool __OSCoreShouldSwitchToThread(OSThread_t* currentThread, OSThread_t* newThread, bool sharedPriorityAndAffinityWorkaround)
{
uint32 coreIndex = OSGetCoreId();
if (!newThread->context.hasCoreAffinitySet(coreIndex))
return false;
// special case: if current and new thread are running only on the same core then reschedule even if priority is equal
// this resolves a deadlock in Just Dance 2019 where one thread would always reacquire the same mutex within it's timeslice, blocking another thread on the same core from acquiring it
if (sharedPriorityAndAffinityWorkaround && (1<<coreIndex) == newThread->context.affinity && currentThread->context.affinity == newThread->context.affinity && currentThread->effectivePriority == newThread->effectivePriority)
return true;
// otherwise reschedule if new thread has higher priority
return newThread->effectivePriority < currentThread->effectivePriority;
}
sint32 __OSResumeThreadInternal(OSThread_t* thread, sint32 resumeCount)
{
cemu_assert_debug(__OSHasSchedulerLock());
sint32 previousSuspendCount = thread->suspendCounter;
cemu_assert_debug(previousSuspendCount >= 0);
if (previousSuspendCount == 0)
{
cemuLog_log(LogType::APIErrors, "OSResumeThread: Resuming thread 0x{:08x} which isn't suspended", MEMPTR<OSThread_t>(thread).GetMPTR());
return 0;
}
thread->suspendCounter = previousSuspendCount - resumeCount;
if (thread->suspendCounter < 0)
thread->suspendCounter = 0;
if (thread->suspendCounter == 0)
{
__OSAddReadyThreadToRunQueue(thread);
// set awakened time if thread is ready
// todo - only set this once?
thread->wakeUpTime = PPCInterpreter_getMainCoreCycleCounter();
// reschedule if thread has higher priority
if (PPCInterpreter_getCurrentInstance() && __OSCoreShouldSwitchToThread(coreinit::OSGetCurrentThread(), thread, false))
PPCCore_switchToSchedulerWithLock();
}
return previousSuspendCount;
}
sint32 OSResumeThread(OSThread_t* thread)
{
__OSLockScheduler();
sint32 previousSuspendCount = __OSResumeThreadInternal(thread, 1);
__OSUnlockScheduler();
return previousSuspendCount;
}
void OSContinueThread(OSThread_t* thread)
{
__OSLockScheduler();
__OSResumeThreadInternal(thread, thread->suspendCounter);
__OSUnlockScheduler();
}
void __OSSuspendThreadInternal(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
cemu_assert_debug(thread->state != OSThread_t::THREAD_STATE::STATE_NONE && thread->state != OSThread_t::THREAD_STATE::STATE_MORIBUND); // how to handle these?
sint32 previousSuspendCount = thread->suspendCounter;
if (OSGetCurrentThread() == thread)
{
thread->suspendCounter = thread->suspendCounter + 1;
PPCCore_switchToSchedulerWithLock();
}
else
{
thread->suspendCounter = thread->suspendCounter + 1;
if (previousSuspendCount == 0)
{
__OSRemoveThreadFromRunQueues(thread);
// todo - if thread is still running find a way to cancel it's timeslice immediately
}
}
}
void OSSuspendThread(OSThread_t* thread)
{
__OSLockScheduler();
__OSSuspendThreadInternal(thread);
__OSUnlockScheduler();
}
void __OSSuspendThreadNolock(OSThread_t* thread)
{
__OSSuspendThreadInternal(thread);
}
void OSSleepThread(OSThreadQueue* threadQueue)
{
__OSLockScheduler();
threadQueue->queueAndWait(OSGetCurrentThread());
__OSUnlockScheduler();
}
void OSWakeupThread(OSThreadQueue* threadQueue)
{
__OSLockScheduler();
threadQueue->wakeupEntireWaitQueue(true);
__OSUnlockScheduler();
}
bool OSSetThreadAffinity(OSThread_t* thread, uint32 affinityMask)
{
cemu_assert_debug((affinityMask & ~7) == 0);
__OSLockScheduler();
uint32 prevAffinityMask = thread->context.getAffinity();
if (thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING)
{
thread->attr = (thread->attr & ~7) | (affinityMask & 7);
thread->context.setAffinity(affinityMask);
// should this reschedule the thread?
}
else if (prevAffinityMask != affinityMask)
{
if(thread->state != OSThread_t::THREAD_STATE::STATE_NONE)
{
__OSRemoveThreadFromRunQueues(thread);
thread->attr = (thread->attr & ~7) | (affinityMask & 7);
thread->context.setAffinity(affinityMask);
__OSAddReadyThreadToRunQueue(thread);
}
else
{
thread->attr = (thread->attr & ~7) | (affinityMask & 7);
thread->context.setAffinity(affinityMask);
}
}
__OSUnlockScheduler();
return true;
}
uint32 OSGetThreadAffinity(OSThread_t* thread)
{
auto affinityMask = thread->context.getAffinity();
cemu_assert_debug((affinityMask & ~7) == 0);
return affinityMask;
}
void* OSSetThreadDeallocator(OSThread_t* thread, void* newDeallocatorFunc)
{
__OSLockScheduler();
void* previousFunc = thread->deallocatorFunc.GetPtr();
thread->deallocatorFunc = newDeallocatorFunc;
__OSUnlockScheduler();
return previousFunc;
}
void* OSSetThreadCleanupCallback(OSThread_t* thread, void* cleanupCallback)
{
__OSLockScheduler();
void* previousFunc = thread->cleanupCallback.GetPtr();
thread->cleanupCallback = cleanupCallback;
__OSUnlockScheduler();
return previousFunc;
}
void __OSSetThreadBasePriority(OSThread_t* thread, sint32 newPriority)
{
cemu_assert_debug(newPriority >= 0 && newPriority < 32);
newPriority += OSThread_t::GetTypePriorityBase(thread->type);
thread->basePriority = newPriority;
}
void __OSUpdateThreadEffectivePriority(OSThread_t* thread)
{
if (thread->context.boostCount != 0)
{
// temporarily boosted threads have their priority set to 0 (maximum)
thread->effectivePriority = 0;
return;
}
thread->effectivePriority = thread->basePriority;
}
bool OSSetThreadPriority(OSThread_t* thread, sint32 newPriority)
{
if (newPriority < 0 || newPriority >= 0x20)
{
cemu_assert_debug(false);
return false; // invalid priority value
}
__OSLockScheduler();
__OSSetThreadBasePriority(thread, newPriority);
__OSUpdateThreadEffectivePriority(thread);
// reschedule if needed
OSThread_t* currentThread = OSGetCurrentThread();
if (currentThread && currentThread != thread)
{
if (__OSCoreShouldSwitchToThread(currentThread, thread, false))
PPCCore_switchToSchedulerWithLock();
}
__OSUnlockScheduler();
return true;
}
sint32 OSGetThreadPriority(OSThread_t* thread)
{
sint32 threadPriority = thread->basePriority;
OSThread_t::THREAD_TYPE threadType = thread->type;
threadPriority -= OSThread_t::GetTypePriorityBase(threadType);
cemu_assert_debug(threadPriority >= 0 && threadPriority < 32);
return threadPriority;
}
bool OSIsThreadTerminated(OSThread_t* thread)
{
__OSLockScheduler();
bool isTerminated = false;
if (thread->state == OSThread_t::THREAD_STATE::STATE_MORIBUND || thread->state == OSThread_t::THREAD_STATE::STATE_NONE)
isTerminated = true;
__OSUnlockScheduler();
return isTerminated;
}
bool OSIsThreadSuspended(OSThread_t* thread)
{
__OSLockScheduler();
sint32 suspendCounter = thread->suspendCounter;
__OSUnlockScheduler();
return suspendCounter > 0;
}
bool OSIsThreadRunningNoLock(OSThread_t* thread)
{
cemu_assert_debug(__OSHasSchedulerLock());
return thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING;
}
bool OSIsThreadRunning(OSThread_t* thread)
{
bool isRunning = false;
__OSLockScheduler();
isRunning = OSIsThreadRunningNoLock(thread);
__OSUnlockScheduler();
return isRunning;
}
void OSCancelThread(OSThread_t* thread)
{
__OSLockScheduler();
cemu_assert_debug(thread->requestFlags == 0 || thread->requestFlags == OSThread_t::REQUEST_FLAG_CANCEL); // todo - how to handle cases where other flags are already set?
thread->requestFlags = OSThread_t::REQUEST_FLAG_CANCEL;
__OSUnlockScheduler();
// if the canceled thread is self, then exit immediately
if (thread == OSGetCurrentThread())
OSExitThread(-1);
}
void OSTestThreadCancelInternal()
{
// also handles suspend request ?
cemu_assert_debug(__OSHasSchedulerLock());
OSThread_t* thread = OSGetCurrentThread();
if (thread->requestFlags == OSThread_t::REQUEST_FLAG_CANCEL)
{
__OSUnlockScheduler();
OSExitThread(-1);
}
}
void OSTestThreadCancel()
{
__OSLockScheduler();
OSTestThreadCancelInternal();
__OSUnlockScheduler();
}
void __OSSwitchToThreadFiber(OSThread_t* thread, uint32 coreIndex)
{
cemu_assert_debug(__OSHasSchedulerLock());
cemu_assert_debug(s_threadToFiber.find(thread) != s_threadToFiber.end());
OSHostThread* hostThread = s_threadToFiber.find(thread)->second;
hostThread->selectedCore = coreIndex;
Fiber::Switch(hostThread->m_fiber);
}
void __OSThreadLoadContext(PPCInterpreter_t* hCPU, OSThread_t* thread)
{
// load GPR
for (uint32 i = 0; i < 32; i++)
hCPU->gpr[i] = _swapEndianU32(thread->context.gpr[i]);
// load SPR cr, lr, ctr, xer
ppc_setCR(hCPU, thread->context.cr);
hCPU->spr.LR = _swapEndianU32(thread->context.lr);
hCPU->spr.CTR = thread->context.ctr;
PPCInterpreter_setXER(hCPU, thread->context.xer);
hCPU->fpscr = thread->context.fpscr.fpscr;
// store floating point and Gekko registers
for (uint32 i = 0; i < 32; i++)
{
hCPU->fpr[i].fp0int = thread->context.fp_ps0[i];
hCPU->fpr[i].fp1int = thread->context.fp_ps1[i];
}
for (uint32 i = 0; i < 8; i++)
{
hCPU->spr.UGQR[0 + i] = thread->context.gqr[i];
}
hCPU->instructionPointer = thread->context.srr0;
}
void __OSThreadStoreContext(PPCInterpreter_t* hCPU, OSThread_t* thread)
{
// store GPR
for (uint32 i = 0; i < 32; i++)
thread->context.gpr[i] = _swapEndianU32(hCPU->gpr[i]);
// store SPRs
thread->context.cr = ppc_getCR(hCPU);
thread->context.lr = _swapEndianU32(hCPU->spr.LR);
thread->context.ctr = hCPU->spr.CTR;
thread->context.xer = PPCInterpreter_getXER(hCPU);
thread->context.fpscr.fpscr = hCPU->fpscr;
thread->context.fpscr.padding = 0;
// store floating point and Gekko registers
for (uint32 i = 0; i < 32; i++)
{
thread->context.fp_ps0[i] = hCPU->fpr[i].fp0int;
thread->context.fp_ps1[i] = hCPU->fpr[i].fp1int;
}
for (uint32 i = 0; i < 8; i++)
{
thread->context.gqr[i] = hCPU->spr.UGQR[0 + i];
}
thread->context.srr0 = hCPU->instructionPointer;
}
void __OSStoreThread(OSThread_t* thread, PPCInterpreter_t* hCPU)
{
if (thread->state == OSThread_t::THREAD_STATE::STATE_RUNNING)
{
thread->state = OSThread_t::THREAD_STATE::STATE_READY;
__OSAddReadyThreadToRunQueue(thread);
}
else if (thread->state == OSThread_t::THREAD_STATE::STATE_MORIBUND || thread->state == OSThread_t::THREAD_STATE::STATE_NONE || thread->state == OSThread_t::THREAD_STATE::STATE_WAITING)
{
// thread exited or suspending/waiting
}
else
{
cemu_assert_debug(false);
}
thread->requestFlags = (OSThread_t::REQUEST_FLAG_BIT)(thread->requestFlags & OSThread_t::REQUEST_FLAG_CANCEL); // remove all flags except cancel flag
// update total cycles
uint64 remainingCycles = std::min((uint64)hCPU->remainingCycles, (uint64)thread->quantumTicks);
uint64 executedCycles = thread->quantumTicks - remainingCycles;
if (executedCycles < hCPU->skippedCycles)
executedCycles = 0;
else
executedCycles -= hCPU->skippedCycles;
thread->totalCycles += executedCycles;
// store context and set current thread to null
__OSThreadStoreContext(hCPU, thread);
OSSetCurrentThread(OSGetCoreId(), nullptr);
PPCInterpreter_setCurrentInstance(nullptr);
}
void __OSLoadThread(OSThread_t* thread, PPCInterpreter_t* hCPU, uint32 coreIndex)
{
hCPU->LSQE = 1;
hCPU->PSE = 1;
hCPU->reservedMemAddr = MPTR_NULL;
hCPU->reservedMemValue = 0;
hCPU->spr.UPIR = coreIndex;
hCPU->coreInterruptMask = 1;
PPCInterpreter_setCurrentInstance(hCPU);
OSSetCurrentThread(OSGetCoreId(), thread);
__OSThreadLoadContext(hCPU, thread);
thread->context.upir = coreIndex;
thread->quantumTicks = ppcThreadQuantum;
// statistics
thread->wakeUpTime = PPCInterpreter_getMainCoreCycleCounter();
thread->wakeUpCount = thread->wakeUpCount + 1;
}
uint32 s_lehmer_lcg[PPC_CORE_COUNT] = { 0 };
void __OSThreadStartTimeslice(OSThread_t* thread, PPCInterpreter_t* hCPU)
{
uint32 coreIndex = PPCInterpreter_getCoreIndex(hCPU);
// run one timeslice
hCPU->remainingCycles = ppcThreadQuantum;
hCPU->skippedCycles = 0;
// we add a slight randomized variance to the thread quantum to avoid getting stuck in repeated code sequences where one or multiple threads always unload inside a lock
// this was seen in Mario Party 10 during early boot where several OSLockMutex operations would align in such a way that one thread would never successfully acquire the lock
if (s_lehmer_lcg[coreIndex] == 0)
s_lehmer_lcg[coreIndex] = 12345;
hCPU->remainingCycles += (s_lehmer_lcg[coreIndex] & 0x7F);
s_lehmer_lcg[coreIndex] = (uint32)((uint64)s_lehmer_lcg[coreIndex] * 279470273ull % 0xfffffffbull);
}
OSThread_t* __OSGetNextRunableThread(uint32 coreIndex)
{
cemu_assert_debug(__OSHasSchedulerLock());
// pick thread, then remove from run queue
OSThreadQueue* runQueue = g_coreRunQueue.GetPtr() + coreIndex;
OSThread_t* threadItr = runQueue->head.GetPtr();
OSThread_t* selectedThread = nullptr;
if (!threadItr)
return nullptr;
selectedThread = threadItr;
while (threadItr)
{
if (threadItr->effectivePriority < selectedThread->effectivePriority)
selectedThread = threadItr;
threadItr = threadItr->linkRun[coreIndex].next.GetPtr();
}
cemu_assert_debug(selectedThread->state == OSThread_t::THREAD_STATE::STATE_READY);
__OSRemoveThreadFromRunQueues(selectedThread);
selectedThread->state = OSThread_t::THREAD_STATE::STATE_RUNNING;
return selectedThread;
}
void __OSDeleteAllActivePPCThreads()
{
__OSLockScheduler();
while(activeThreadCount > 0)
{
MEMPTR<OSThread_t> t{activeThread[0]};
t->state = OSThread_t::THREAD_STATE::STATE_NONE;
__OSDeactivateThread(t.GetPtr());
}
__OSUnlockScheduler();
}
void __OSCheckSystemEvents()
{
// AX update
snd_core::AXOut_update();
// alarm update
coreinit::alarm_update();
// nfp update
nnNfp_update();
}
Fiber* g_idleLoopFiber[3]{};
// idle fiber per core if no thread is runnable
// this is necessary since we can't block in __OSThreadSwitchToNext() (__OSStoreThread + thread switch must happen inside same scheduler lock)
void __OSThreadCoreIdle(void* unusedParam)
{
bool isMainCore = g_isMulticoreMode == false || t_assignedCoreIndex == 1;
sint32 coreIndex = t_assignedCoreIndex;
__OSUnlockScheduler();
while (true)
{
if (!g_coreRunQueueThreadCount[coreIndex].isZero()) // avoid hammering the lock on the main core if there is no runable thread
{
__OSLockScheduler();
OSThread_t* nextThread = __OSGetNextRunableThread(coreIndex);
if (nextThread)
{
cemu_assert_debug(nextThread->state == OSThread_t::THREAD_STATE::STATE_RUNNING);
__OSSwitchToThreadFiber(nextThread, coreIndex);
}
__OSUnlockScheduler();
}
if (isMainCore)
{
__OSCheckSystemEvents();
if(g_isMulticoreMode == false)
coreIndex = (coreIndex + 1) % 3;
}
else
{
// wait for semaphore (only in multicore mode)
g_coreRunQueueThreadCount[t_assignedCoreIndex].waitUntilNonZero();
if (!sSchedulerActive.load(std::memory_order::relaxed))
Fiber::Switch(*t_schedulerFiber); // switch back to original thread to exit
}
}
}
void __OSThreadSwitchToNext()
{
cemu_assert_debug(__OSHasSchedulerLock());
OSHostThread* hostThread = (OSHostThread*)Fiber::GetFiberPrivateData();
cemu_assert_debug(hostThread);
//if (ppcInterpreterCurrentInstance)
// debug_printf("Core %d store thread %08x (t = %d)\n", hostThread->ppcInstance.sprNew.UPIR, memory_getVirtualOffsetFromPointer(hostThread->thread), t_assignedCoreIndex);
// store context of current thread
__OSStoreThread(OSGetCurrentThread(), &hostThread->ppcInstance);
cemu_assert_debug(PPCInterpreter_getCurrentInstance() == nullptr);
if (!sSchedulerActive.load(std::memory_order::relaxed))
{
__OSUnlockScheduler();
Fiber::Switch(*t_schedulerFiber); // switch back to original thread entry for it to exit
}
// choose core
static uint32 _coreCounter = 0;
sint32 coreIndex;
if (g_isMulticoreMode)
coreIndex = t_assignedCoreIndex;
else
{
coreIndex = _coreCounter;
_coreCounter = (_coreCounter + 1) % 3;
}
// if main thread then dont forget to do update checks
bool isMainThread = g_isMulticoreMode == false || t_assignedCoreIndex == 1;
// find next thread to run
// for main thread we force switching to the idle loop since it calls __OSCheckSystemEvents()
if(isMainThread)
Fiber::Switch(*g_idleLoopFiber[t_assignedCoreIndex]);
else if (OSThread_t* nextThread = __OSGetNextRunableThread(coreIndex))
{
cemu_assert_debug(nextThread->state == OSThread_t::THREAD_STATE::STATE_RUNNING);
__OSSwitchToThreadFiber(nextThread, coreIndex);
}
else
{
Fiber::Switch(*g_idleLoopFiber[t_assignedCoreIndex]);
}
cemu_assert_debug(__OSHasSchedulerLock());
cemu_assert_debug(g_isMulticoreMode == false || hostThread->selectedCore == t_assignedCoreIndex);
// received next time slice, load self again
__OSLoadThread(hostThread->m_thread, &hostThread->ppcInstance, hostThread->selectedCore);
__OSThreadStartTimeslice(hostThread->m_thread, &hostThread->ppcInstance);
}
void __OSFiberThreadEntry(void* _thread)
{
OSHostThread* hostThread = (OSHostThread*)_thread;
#if defined(ARCH_X86_64)
_mm_setcsr(_mm_getcsr() | 0x8000); // flush denormals to zero
#endif
PPCInterpreter_t* hCPU = &hostThread->ppcInstance;
__OSLoadThread(hostThread->m_thread, hCPU, hostThread->selectedCore);
__OSThreadStartTimeslice(hostThread->m_thread, &hostThread->ppcInstance);
__OSUnlockScheduler(); // lock is always held when switching to a fiber, so we need to unlock it here
while (true)
{
if (hCPU->remainingCycles > 0)
{
// try to enter recompiler immediately
PPCRecompiler_attemptEnterWithoutRecompile(hCPU, hCPU->instructionPointer);
// keep executing as long as there are cycles left
while ((--hCPU->remainingCycles) >= 0)
PPCInterpreterSlim_executeInstruction(hCPU);
}
// reset reservation
hCPU->reservedMemAddr = 0;
hCPU->reservedMemValue = 0;
// reschedule
__OSLockScheduler();
__OSThreadSwitchToNext();
__OSUnlockScheduler();
}
}
#if BOOST_OS_LINUX
#include <unistd.h>
#include <sys/prctl.h>
std::vector<pid_t> g_schedulerThreadIds;
std::mutex g_schedulerThreadIdsLock;
std::vector<pid_t>& OSGetSchedulerThreadIds()
{
std::lock_guard schedulerThreadIdsLockGuard(g_schedulerThreadIdsLock);
return g_schedulerThreadIds;
}
#endif
void OSSchedulerCoreEmulationThread(void* _assignedCoreIndex)
{
SetThreadName(fmt::format("OSSched[core={}]", (uintptr_t)_assignedCoreIndex).c_str());
t_assignedCoreIndex = (sint32)(uintptr_t)_assignedCoreIndex;
#if defined(ARCH_X86_64)
_mm_setcsr(_mm_getcsr() | 0x8000); // flush denormals to zero
#endif
#if BOOST_OS_LINUX
if (g_gdbstub)
{
// need to allow the GDBStub to attach to our thread
prctl(PR_SET_DUMPABLE, (unsigned long)1);
prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
}
pid_t tid = gettid();
{
std::lock_guard schedulerThreadIdsLockGuard(g_schedulerThreadIdsLock);
g_schedulerThreadIds.emplace_back(tid);
}
#endif
t_schedulerFiber = Fiber::PrepareCurrentThread();
// create scheduler idle fiber and switch to it
g_idleLoopFiber[t_assignedCoreIndex] = new Fiber(__OSThreadCoreIdle, nullptr, nullptr);
cemu_assert_debug(PPCInterpreter_getCurrentInstance() == nullptr);
__OSLockScheduler();
Fiber::Switch(*g_idleLoopFiber[t_assignedCoreIndex]);
// returned from scheduler loop, exit thread
cemu_assert_debug(!__OSHasSchedulerLock());
}
std::vector<std::thread::native_handle_type> g_schedulerThreadHandles;
std::vector<std::thread::native_handle_type>& OSGetSchedulerThreads()
{
return g_schedulerThreadHandles;
}
// starts PPC core emulation
void OSSchedulerBegin(sint32 numCPUEmulationThreads)
{
std::unique_lock _lock(sSchedulerStateMtx);
if (sSchedulerActive.exchange(true))
return;
cemu_assert_debug(numCPUEmulationThreads == 1 || numCPUEmulationThreads == 3);
g_isMulticoreMode = numCPUEmulationThreads > 1;
if (numCPUEmulationThreads == 1)
sSchedulerThreads.emplace_back(OSSchedulerCoreEmulationThread, (void*)0);
else if (numCPUEmulationThreads == 3)
{
for (size_t i = 0; i < 3; i++)
sSchedulerThreads.emplace_back(OSSchedulerCoreEmulationThread, (void*)i);
}
else
cemu_assert_debug(false);
for (auto& it : sSchedulerThreads)
g_schedulerThreadHandles.emplace_back(it.native_handle());
}
// shuts down all scheduler host threads and deletes all fibers and ppc threads
void OSSchedulerEnd()
{
std::unique_lock _lock(sSchedulerStateMtx);
sSchedulerActive.store(false);
for (size_t i = 0; i < Espresso::CORE_COUNT; i++)
g_coreRunQueueThreadCount[i].increment(); // make sure to wake up cores if they are paused and waiting for runnable threads
// wait for threads to stop execution
for (auto& threadItr : sSchedulerThreads)
threadItr.join();
sSchedulerThreads.clear();
g_schedulerThreadHandles.clear();
#if BOOST_OS_LINUX
{
std::lock_guard schedulerThreadIdsLockGuard(g_schedulerThreadIdsLock);
g_schedulerThreadIds.clear();
}
#endif
// clean up all fibers
for (auto& it : g_idleLoopFiber)
{
delete it;
it = nullptr;
}
for (auto& it : s_threadToFiber)
{
OSHostThread* hostThread = it.second;
delete hostThread;
}
s_threadToFiber.clear();
}
SysAllocator<OSThread_t, PPC_CORE_COUNT> s_defaultThreads;
SysAllocator<uint8, PPC_CORE_COUNT * 1024 * 1024> s_stack;
OSThread_t* OSGetDefaultThread(sint32 coreIndex)
{
if (coreIndex < 0 || coreIndex >= PPC_CORE_COUNT)
return nullptr;
return s_defaultThreads.GetPtr() + coreIndex;
}
void* OSGetDefaultThreadStack(sint32 coreIndex, uint32& size)
{
if (coreIndex < 0 || coreIndex >= PPC_CORE_COUNT)
return nullptr;
size = 1024 * 1024;
return s_stack.GetPtr() + coreIndex * size;
}
void OSInitThreadQueue(OSThreadQueue* threadQueue)
{
threadQueue->head = nullptr;
threadQueue->tail = nullptr;
threadQueue->userData = nullptr;
threadQueue->ukn0C = 0;
}
void OSInitThreadQueueEx(OSThreadQueue* threadQueue, void* userData)
{
threadQueue->head = nullptr;
threadQueue->tail = nullptr;
threadQueue->userData = userData;
threadQueue->ukn0C = 0;
}
/* Thread terminator threads (for calling thread deallocators) */
struct TerminatorThread
{
struct DeallocatorQueueEntry
{
DeallocatorQueueEntry() = default;
DeallocatorQueueEntry(OSThread_t* thread, MEMPTR<void> stack, MEMPTR<void> deallocatorFunc) : thread(thread), stack(stack), deallocatorFunc(deallocatorFunc) {};
OSThread_t* thread{};
MEMPTR<void> stack;
MEMPTR<void> deallocatorFunc;
};
SysAllocator<OSThread_t> terminatorThread;
SysAllocator<uint8, 16 * 1024> threadStack;
SysAllocator<char, 64> threadName;
SysAllocator<OSSemaphore> semaphoreQueuedDeallocators;
ConcurrentQueue<DeallocatorQueueEntry> queueDeallocators;
};
TerminatorThread s_terminatorThreads[PPC_CORE_COUNT];
void __OSTerminatorThreadFunc(PPCInterpreter_t* hCPU)
{
uint32 coreIndex = OSGetCoreId();
while (OSWaitSemaphore(s_terminatorThreads[coreIndex].semaphoreQueuedDeallocators.GetPtr()))
{
TerminatorThread::DeallocatorQueueEntry queueEntry;
s_terminatorThreads[coreIndex].queueDeallocators.pop(queueEntry);
PPCCoreCallback(queueEntry.deallocatorFunc, queueEntry.thread, queueEntry.stack);
}
osLib_returnFromFunction(hCPU, 0);
}
// queue thread deallocation to run after current thread finishes
// the termination threads run at a higher priority on the same threads
void __OSQueueThreadDeallocation(OSThread_t* thread)
{
uint32 coreIndex = OSGetCoreId();
TerminatorThread::DeallocatorQueueEntry queueEntry(thread, thread->stackEnd, thread->deallocatorFunc);
s_terminatorThreads[coreIndex].queueDeallocators.push(queueEntry);
OSSignalSemaphoreInternal(s_terminatorThreads[coreIndex].semaphoreQueuedDeallocators.GetPtr(), false); // do not reschedule here! Current thread must not be interrupted otherwise deallocator will run too early
}
void __OSInitTerminatorThreads()
{
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
{
OSInitSemaphore(s_terminatorThreads[i].semaphoreQueuedDeallocators.GetPtr(), 0);
sprintf(s_terminatorThreads[i].threadName.GetPtr(), "{SYS Thread Terminator Core %d}", i);
OSCreateThreadType(s_terminatorThreads[i].terminatorThread.GetPtr(), PPCInterpreter_makeCallableExportDepr(__OSTerminatorThreadFunc), 0, nullptr, (uint8*)s_terminatorThreads[i].threadStack.GetPtr() + s_terminatorThreads[i].threadStack.GetByteSize(), (sint32)s_terminatorThreads[i].threadStack.GetByteSize(), 0, 1 << i, OSThread_t::THREAD_TYPE::TYPE_IO);
OSSetThreadName(s_terminatorThreads[i].terminatorThread.GetPtr(), s_terminatorThreads[i].threadName.GetPtr());
OSResumeThread(s_terminatorThreads[i].terminatorThread.GetPtr());
}
}
SysAllocator<char, 64> _defaultThreadName[PPC_CORE_COUNT];
void __OSInitDefaultThreads()
{
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
{
sprintf(_defaultThreadName[i].GetPtr(), "Default Core %d", i);
OSThread_t* coreDefaultThread = coreinit::OSGetDefaultThread(i);
uint32 stackSize;
void* stackBase = coreinit::OSGetDefaultThreadStack(i, stackSize);
coreinit::OSCreateThreadType(coreDefaultThread, MPTR_NULL, 0, nullptr, (uint8*)stackBase + stackSize, stackSize, 16, 1 << i, OSThread_t::THREAD_TYPE::TYPE_APP);
coreinit::OSSetThreadName(coreDefaultThread, _defaultThreadName[i].GetPtr());
}
}
void InitializeThread()
{
cafeExportRegister("coreinit", OSCreateThreadType, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSCreateThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", __OSCreateThreadType, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSExitThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetCurrentThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSetThreadSpecific, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetThreadSpecific, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSetThreadName, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetThreadName, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSRunThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSDetachThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSJoinThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSResumeThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSContinueThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSuspendThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", __OSSuspendThreadNolock, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSleepThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSWakeupThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSYieldThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSleepTicks, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSetThreadDeallocator, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSetThreadCleanupCallback, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSetThreadPriority, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetThreadPriority, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSSetThreadAffinity, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetThreadAffinity, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSIsThreadTerminated, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSIsThreadSuspended, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSCancelThread, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSTestThreadCancel, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSGetDefaultThread, LogType::CoreinitThread);
// OSThreadQueue
cafeExportRegister("coreinit", OSInitThreadQueue, LogType::CoreinitThread);
cafeExportRegister("coreinit", OSInitThreadQueueEx, LogType::CoreinitThread);
OSInitThreadQueue(g_activeThreadQueue.GetPtr());
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
OSInitThreadQueue(g_coreRunQueue.GetPtr() + i);
for (sint32 i = 0; i < PPC_CORE_COUNT; i++)
__currentCoreThread[i] = nullptr;
__OSInitDefaultThreads();
__OSInitTerminatorThreads();
}
}
| 53,581
|
C++
|
.cpp
| 1,407
| 34.666667
| 356
| 0.739493
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
23,102
|
coreinit_Atomic.cpp
|
cemu-project_Cemu/src/Cafe/OS/libs/coreinit/coreinit_Atomic.cpp
|
#include "Cafe/OS/common/OSCommon.h"
#include <atomic>
#include "coreinit_Atomic.h"
namespace coreinit
{
/* 32bit atomic operations */
uint32 OSSwapAtomic(std::atomic<uint32be>* mem, uint32 newValue)
{
uint32be _newValue = newValue;
uint32be previousValue = mem->exchange(_newValue);
return previousValue;
}
bool OSCompareAndSwapAtomic(std::atomic<uint32be>* mem, uint32 compareValue, uint32 swapValue)
{
// seen in GTA3 homebrew port
uint32be _compareValue = compareValue;
uint32be _swapValue = swapValue;
return mem->compare_exchange_strong(_compareValue, _swapValue);
}
bool OSCompareAndSwapAtomicEx(std::atomic<uint32be>* mem, uint32 compareValue, uint32 swapValue, uint32be* previousValue)
{
// seen in GTA3 homebrew port
uint32be _compareValue = compareValue;
uint32be _swapValue = swapValue;
bool r = mem->compare_exchange_strong(_compareValue, _swapValue);
*previousValue = _compareValue;
return r;
}
uint32 OSAddAtomic(std::atomic<uint32be>* mem, uint32 adder)
{
// used by SDL Wii U port
uint32be knownValue;
while (true)
{
knownValue = mem->load();
uint32be newValue = knownValue + adder;
if (mem->compare_exchange_strong(knownValue, newValue))
break;
}
return knownValue;
}
/* 64bit atomic operations */
uint64 OSSwapAtomic64(std::atomic<uint64be>* mem, uint64 newValue)
{
uint64be _newValue = newValue;
uint64be previousValue = mem->exchange(_newValue);
return previousValue;
}
uint64 OSSetAtomic64(std::atomic<uint64be>* mem, uint64 newValue)
{
return OSSwapAtomic64(mem, newValue);
}
uint64 OSGetAtomic64(std::atomic<uint64be>* mem)
{
return mem->load();
}
uint64 OSAddAtomic64(std::atomic<uint64be>* mem, uint64 adder)
{
uint64be knownValue;
while (true)
{
knownValue = mem->load();
uint64be newValue = knownValue + adder;
if (mem->compare_exchange_strong(knownValue, newValue))
break;
}
return knownValue;
}
uint64 OSAndAtomic64(std::atomic<uint64be>* mem, uint64 val)
{
uint64be knownValue;
while (true)
{
knownValue = mem->load();
uint64be newValue = knownValue & val;
if (mem->compare_exchange_strong(knownValue, newValue))
break;
}
return knownValue;
}
uint64 OSOrAtomic64(std::atomic<uint64be>* mem, uint64 val)
{
uint64be knownValue;
while (true)
{
knownValue = mem->load();
uint64be newValue = knownValue | val;
if (mem->compare_exchange_strong(knownValue, newValue))
break;
}
return knownValue;
}
bool OSCompareAndSwapAtomic64(std::atomic<uint64be>* mem, uint64 compareValue, uint64 swapValue)
{
uint64be _compareValue = compareValue;
uint64be _swapValue = swapValue;
return mem->compare_exchange_strong(_compareValue, _swapValue);
}
bool OSCompareAndSwapAtomicEx64(std::atomic<uint64be>* mem, uint64 compareValue, uint64 swapValue, uint64be* previousValue)
{
uint64be _compareValue = compareValue;
uint64be _swapValue = swapValue;
bool r = mem->compare_exchange_strong(_compareValue, _swapValue);
*previousValue = _compareValue;
return r;
}
void InitializeAtomic()
{
// 32bit atomic operations
cafeExportRegister("coreinit", OSSwapAtomic, LogType::Placeholder);
cafeExportRegister("coreinit", OSCompareAndSwapAtomic, LogType::Placeholder);
cafeExportRegister("coreinit", OSCompareAndSwapAtomicEx, LogType::Placeholder);
cafeExportRegister("coreinit", OSAddAtomic, LogType::Placeholder);
// 64bit atomic operations
cafeExportRegister("coreinit", OSSetAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSGetAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSSwapAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSAddAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSAndAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSOrAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSCompareAndSwapAtomic64, LogType::Placeholder);
cafeExportRegister("coreinit", OSCompareAndSwapAtomicEx64, LogType::Placeholder);
}
}
| 4,058
|
C++
|
.cpp
| 124
| 29.806452
| 124
| 0.763595
|
cemu-project/Cemu
| 7,119
| 558
| 254
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.