diff --git a/.gitignore b/.gitignore index 8055e8c2e3..fb1396b652 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ *.log *.exe +*.dll *.elf *.lastbuildstate *.unsuccessfulbuild @@ -39,4 +40,5 @@ /bin/VertexProgram.txt /bin/BreakPoints.dat /bin/textures +/bin/data/ rpcs3/git-version.h diff --git a/Utilities/BEType.h b/Utilities/BEType.h new file mode 100644 index 0000000000..8089f381c9 --- /dev/null +++ b/Utilities/BEType.h @@ -0,0 +1,154 @@ +#pragma once +#pragma warning(disable: 4739) + +template +class be_t +{ + static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8, "Bad be_t type"); + T m_data; + +public: + be_t() + { + } + + be_t(const T& value) + { + FromLE(value); + } + + template + be_t(const be_t& value) + { + FromBE(value.ToBE()); + } + + T ToBE() const + { + return m_data; + } + + T ToLE() const + { + T res; + + switch(sizeof(T)) + { + case 1: + (u8&)res = (u8&)m_data; + break; + + case 2: + (u16&)res = _byteswap_ushort((u16&)m_data); + break; + + case 4: + (u32&)res = _byteswap_ulong((u32&)m_data); + break; + + case 8: + (u64&)res = _byteswap_uint64((u64&)m_data); + break; + + default: + assert(0); + break; + } + + return res; + } + + void FromBE(const T& value) + { + m_data = value; + } + + void FromLE(const T& value) + { + switch(sizeof(T)) + { + case 1: + (u8&)m_data = (u8&)value; + return; + + case 2: + (u16&)m_data = _byteswap_ushort((u16&)value); + return; + + case 4: + (u32&)m_data = _byteswap_ulong((u32&)value); + return; + + case 8: + (u64&)m_data = _byteswap_uint64((u64&)value); + return; + } + + assert(0); + m_data = value; + } + + //template + operator const T() const + { + return ToLE(); + } + + template + operator const be_t() const + { + be_t res; + res.FromBE(ToBE()); + return res; + } + + be_t& operator = (const T& right) + { + FromLE(right); + return *this; + } + + be_t& operator = (const be_t& right) + { + m_data = right.m_data; + return *this; + } + + template be_t& operator += (T1 right) { return *this = T(*this) + right; } + template be_t& operator -= (T1 right) { return *this = T(*this) - right; } + template be_t& operator *= (T1 right) { return *this = T(*this) * right; } + template be_t& operator /= (T1 right) { return *this = T(*this) / right; } + template be_t& operator %= (T1 right) { return *this = T(*this) % right; } + template be_t& operator &= (T1 right) { return *this = T(*this) & right; } + template be_t& operator |= (T1 right) { return *this = T(*this) | right; } + template be_t& operator ^= (T1 right) { return *this = T(*this) ^ right; } + template be_t& operator <<= (T1 right) { return *this = T(*this) << right; } + template be_t& operator >>= (T1 right) { return *this = T(*this) >> right; } + + template be_t& operator += (const be_t& right) { return *this = ToLE() + right.ToLE(); } + template be_t& operator -= (const be_t& right) { return *this = ToLE() - right.ToLE(); } + template be_t& operator *= (const be_t& right) { return *this = ToLE() * right.ToLE(); } + template be_t& operator /= (const be_t& right) { return *this = ToLE() / right.ToLE(); } + template be_t& operator %= (const be_t& right) { return *this = ToLE() % right.ToLE(); } + template be_t& operator &= (const be_t& right) { return *this = ToBE() & right.ToBE(); } + template be_t& operator |= (const be_t& right) { return *this = ToBE() | right.ToBE(); } + template be_t& operator ^= (const be_t& right) { return *this = ToBE() ^ right.ToBE(); } + + template be_t operator & (const be_t& right) const { be_t res; res.FromBE(ToBE() & right.ToBE()); return res; } + template be_t operator | (const be_t& right) const { be_t res; res.FromBE(ToBE() | right.ToBE()); return res; } + template be_t operator ^ (const be_t& right) const { be_t res; res.FromBE(ToBE() ^ right.ToBE()); return res; } + + template bool operator == (T1 right) const { return ToLE() == right; } + template bool operator != (T1 right) const { return !(*this == right); } + template bool operator > (T1 right) const { return ToLE() > right; } + template bool operator < (T1 right) const { return ToLE() < right; } + template bool operator >= (T1 right) const { return ToLE() >= right; } + template bool operator <= (T1 right) const { return ToLE() <= right; } + + template bool operator == (const be_t& right) const { return ToBE() == right.ToBE(); } + template bool operator != (const be_t& right) const { return !(*this == right); } + template bool operator > (const be_t& right) const { return ToLE() > right.ToLE(); } + template bool operator < (const be_t& right) const { return ToLE() < right.ToLE(); } + template bool operator >= (const be_t& right) const { return ToLE() >= right.ToLE(); } + template bool operator <= (const be_t& right) const { return ToLE() <= right.ToLE(); } +}; \ No newline at end of file diff --git a/Utilities/git-version-gen.cmd b/Utilities/git-version-gen.cmd index 3cd4334b4a..d3a198846f 100644 --- a/Utilities/git-version-gen.cmd +++ b/Utilities/git-version-gen.cmd @@ -13,7 +13,7 @@ rem // A copy of the GPL 2.0 should have been included with the program. rem // If not, see http://www.gnu.org/licenses/ rem // Official git repository and contact information can be found at -rem // https://github.com/hrydgard/RPCS3 and http://www.RPCS3.org/. +rem // https://github.com/DHrpcs3/rpcs3 and http://code.google.com/p/rpcs3/. setlocal ENABLEDELAYEDEXPANSION diff --git a/bin/dev_hdd1/.gitignore b/bin/dev_hdd1/.gitignore new file mode 100644 index 0000000000..86d0cb2726 --- /dev/null +++ b/bin/dev_hdd1/.gitignore @@ -0,0 +1,4 @@ +# Ignore everything in this directory +* +# Except this file +!.gitignore \ No newline at end of file diff --git a/rpcs3.sln b/rpcs3.sln index a67317b751..819265aa30 100644 --- a/rpcs3.sln +++ b/rpcs3.sln @@ -63,6 +63,38 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "stblib", "stblib", "{9D839D stblib\stb_image.h = stblib\stb_image.h EndProjectSection EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "scetool", "scetool", "{AB33A31B-6D15-45E8-B292-D512DEF0A5B1}" + ProjectSection(SolutionItems) = preProject + scetool\aes.c = scetool\aes.c + scetool\aes.h = scetool\aes.h + scetool\aes_omac.h = scetool\aes_omac.h + scetool\bn.cpp = scetool\bn.cpp + scetool\config.h = scetool\config.h + scetool\ecdsa.h = scetool\ecdsa.h + scetool\elf.h = scetool\elf.h + scetool\elf_inlines.h = scetool\elf_inlines.h + scetool\frontend.h = scetool\frontend.h + scetool\getopt.c = scetool\getopt.c + scetool\getopt.h = scetool\getopt.h + scetool\keys.h = scetool\keys.h + scetool\list.h = scetool\list.h + scetool\mt19937.h = scetool\mt19937.h + scetool\np.h = scetool\np.h + scetool\rvk.h = scetool\rvk.h + scetool\sce.h = scetool\sce.h + scetool\sce_inlines.h = scetool\sce_inlines.h + scetool\scetool.cpp = scetool\scetool.cpp + scetool\self.h = scetool\self.h + scetool\sha1.c = scetool\sha1.c + scetool\sha1.h = scetool\sha1.h + scetool\spp.h = scetool\spp.h + scetool\tables.h = scetool\tables.h + scetool\types.h = scetool\types.h + scetool\util.h = scetool\util.h + scetool\zconf.h = scetool\zconf.h + scetool\zlib.h = scetool\zlib.h + EndProjectSection +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 diff --git a/rpcs3/Emu/ARMv7/ARMv7Decoder.h b/rpcs3/Emu/ARMv7/ARMv7Decoder.h new file mode 100644 index 0000000000..71f37e3b38 --- /dev/null +++ b/rpcs3/Emu/ARMv7/ARMv7Decoder.h @@ -0,0 +1,137 @@ +#pragma once +#include "Emu/CPU/CPUDecoder.h" +#include "ARMv7Opcodes.h" + + +class ARMv7Decoder : public CPUDecoder +{ + ARMv7Opcodes& m_op; + u8 m_last_instr_size; + +public: + ARMv7Decoder(ARMv7Opcodes& op) : m_op(op) + { + } + + u32 branchTarget(u32 imm) + { + return imm << 1; + } + + virtual u8 DecodeMemory(const u64 address) + { + using namespace ARMv7_opcodes; + const u16 code0 = Memory.Read16(address); + const u16 code1 = Memory.Read16(address + 2); + + switch(code0 >> 12) //15 - 12 + { + case T1_CBZ: + switch((code0 >> 10) & 0x1) + { + case 0: + switch((code0 >> 8) & 0x1) + { + case 1: + m_op.CBZ((code0 >> 11) & 0x1, branchTarget((((code0 >> 9) & 0x1) << 5) | (code0 >> 3) & 0x1f), code0 & 0x7, 2); + return 2; + } + break; + } + break; + + case T1_B: + m_op.B((code0 >> 8) & 0xf, branchTarget(code0 & 0xff), 2); + return 2; + } + + switch(code0 >> 11) //15 - 11 + { + case T2_B: + m_op.B(0xf, branchTarget(code0 & 0xfff), 2); + return 2; + + case T3_B: + { + u8 S = (code0 >> 10) & 0x1; + u8 J1 = (code1 >> 13) & 0x1; + u8 J2 = (code1 >> 11) & 0x1; + u8 I1 = 1 - (J1 ^ S); + u8 I2 = 1 - (J2 ^ S); + u16 imm11 = code1 & 0x7ff; + u32 imm32; + + switch(code1 >> 14) + { + case 2: //B + { + u8 cond; + switch((code1 >> 12) & 0x1) + { + case 0: + { + cond = (code0 >> 6) & 0xf; + u32 imm6 = code0 & 0x3f; + imm32 = sign<19, u32>((S << 19) | (I1 << 18) | (I2 << 17) | (imm6 << 11) | imm11); + } + break; + + case 1: + cond = 0xf; + u32 imm10 = code0 & 0x7ff; + imm32 = sign<23, u32>((S << 23) | (I1 << 22) | (I2 << 21) | (imm10 << 11) | imm11); + break; + } + + m_op.B(cond, branchTarget(imm32), 4); + } + return 4; + + case 3: //BL + switch((code1 >> 12) & 0x1) + { + case 0: + break; + + case 1: + u32 imm10 = code0 & 0x7ff; + imm32 = sign<23, u32>((S << 23) | (I1 << 22) | (I2 << 21) | (imm10 << 11) | imm11); + m_op.BL(branchTarget(imm32), 4); + return 4; + } + break; + } + } + break; + } + + switch(code0 >> 9) + { + case T1_PUSH: + m_op.PUSH((((code0 >> 8) & 0x1) << 14) | (code0 & 0xff)); + return 2; + + case T1_POP: + m_op.POP((((code0 >> 8) & 0x1) << 15) | (code0 & 0xff)); + return 2; + } + + switch(code0) + { + case T2_PUSH: + m_op.PUSH(code1); + return 4; + + case T2_POP: + m_op.POP(code1); + return 4; + + case T1_NOP: + m_op.NOP(); + return 2; + } + + m_op.UNK(code0, code1); + return 2; + } +}; diff --git a/rpcs3/Emu/ARMv7/ARMv7DisAsm.h b/rpcs3/Emu/ARMv7/ARMv7DisAsm.h new file mode 100644 index 0000000000..3217907018 --- /dev/null +++ b/rpcs3/Emu/ARMv7/ARMv7DisAsm.h @@ -0,0 +1,96 @@ +#pragma once +#include "Emu/ARMv7/ARMv7Opcodes.h" +#include "Emu/CPU/CPUDisAsm.h" +#include "Gui/DisAsmFrame.h" +#include "Emu/Memory/Memory.h" + +static const char* g_arm_cond_name[16] = +{ + "eq", "ne", "cs", "cc", + "mi", "pl", "vs", "vc", + "hi", "ls", "ge", "lt", + "gt", "le", "al", "al", +}; + +class ARMv7DisAsm + : public CPUDisAsm + , public ARMv7Opcodes +{ +public: + ARMv7DisAsm(CPUDisAsmMode mode) : CPUDisAsm(mode) + { + } + +protected: + virtual u32 DisAsmBranchTarget(const s32 imm) + { + return dump_pc + imm; + } + + wxString GetRegsListString(u16 regs_list) + { + wxString regs_str; + + for(u16 mask=0x1, i=0; mask; mask <<= 1, i++) + { + if(regs_list & mask) + { + if(!regs_str.IsEmpty()) + { + regs_str += ", "; + } + + regs_str += g_arm_reg_name[i]; + } + } + + return regs_str; + } + + void NULL_OP() + { + Write("null"); + } + + void PUSH(u16 regs_list) + { + Write(wxString::Format("push {%s}", GetRegsListString(regs_list))); + } + + void POP(u16 regs_list) + { + Write(wxString::Format("pop {%s}", GetRegsListString(regs_list))); + } + + void NOP() + { + Write("nop"); + } + + void B(u8 cond, u32 imm, u8 intstr_size) + { + if((cond & 0xe) == 0xe) + { + Write(wxString::Format("b 0x%x", DisAsmBranchTarget(imm) + intstr_size)); + } + else + { + Write(wxString::Format("b[%s] 0x%x", g_arm_cond_name[cond], DisAsmBranchTarget(imm) + intstr_size)); + } + } + + virtual void CBZ(u8 op, u32 imm, u8 rn, u8 intstr_size) + { + Write(wxString::Format("cb%sz 0x%x,%s", (op ? "n" : ""), DisAsmBranchTarget(imm) + intstr_size, g_arm_reg_name[rn])); + } + + void BL(u32 imm, u8 intstr_size) + { + Write(wxString::Format("bl 0x%x", DisAsmBranchTarget(imm) + intstr_size)); + } + + void UNK(const u16 code0, const u16 code1) + { + Write(wxString::Format("Unknown/Illegal opcode! (0x%04x : 0x%04x)", code0, code1)); + } +}; \ No newline at end of file diff --git a/rpcs3/Emu/ARMv7/ARMv7Interpreter.h b/rpcs3/Emu/ARMv7/ARMv7Interpreter.h new file mode 100644 index 0000000000..a11144e9b6 --- /dev/null +++ b/rpcs3/Emu/ARMv7/ARMv7Interpreter.h @@ -0,0 +1,322 @@ +#pragma once +#include "Emu/ARMv7/ARMv7Opcodes.h" + +class ARMv7Interpreter : public ARMv7Opcodes +{ + ARMv7Thread& CPU; + +public: + ARMv7Interpreter(ARMv7Thread& cpu) : CPU(cpu) + { + } + + enum SRType + { + SRType_None, + SRType_LSL, + SRType_LSR, + SRType_ASR, + SRType_ROR, + SRType_RRX, + }; + + template + bool IsZero(T x) + { + return x == T(0); + } + + template + bool IsOnes(T x) + { + return x == ~T(0); + } + + template + u8 IsZeroBit(T x) + { + return IsZero(x) ? 1 : 0; + } + + template + bool IsOnesBit(T x, u8 len = sizeof(T) * 8) + { + return IsOnes(x) ? 1 : 0; + } + + template + u8 BitCount(T x, u8 len = sizeof(T) * 8) + { + u8 result = 0; + + for(u8 mask=1 << (len - 1); mask; mask >>= 1) + { + if(x & mask) result++; + } + + return result; + } + + template + s8 LowestSetBit(T x, u8 len = sizeof(T) * 8) + { + if(!x) return len; + + u8 result = 0; + + for(T mask=1, i=0; i + s8 HighestSetBit(T x, u8 len = sizeof(T) * 8) + { + if(!x) return -1; + + u8 result = len; + + for(T mask=T(1) << (len - 1); (x & mask) == 0; mask >>= 1) + { + result--; + } + + return result; + } + + template + s8 CountLeadingZeroBits(T x, u8 len = sizeof(T) * 8) + { + return len - 1 - HighestSetBit(x, len); + } + + SRType DecodeImmShift(u8 type, u8 imm5, uint* shift_n) + { + SRType shift_t; + + switch(type) + { + case 0: shift_t = SRType_LSL; if(shift_n) *shift_n = imm5; break; + case 1: shift_t = SRType_LSR; if(shift_n) *shift_n = imm5 == 0 ? 32 : imm5; break; + case 2: shift_t = SRType_ASR; if(shift_n) *shift_n = imm5 == 0 ? 32 : imm5; break; + case 3: + if(imm5 == 0) + { + shift_t = SRType_RRX; if(shift_n) *shift_n = 1; + } + else + { + shift_t = SRType_ROR; if(shift_n) *shift_n = imm5; + } + break; + } + + return shift_t; + } + + SRType DecodeRegShift(u8 type) + { + SRType shift_t; + + switch(type) + { + case 0: shift_t = SRType_LSL; break; + case 1: shift_t = SRType_LSR; break; + case 2: shift_t = SRType_ASR; break; + case 3: shift_t = SRType_ROR; break; + } + + return shift_t; + } + + u32 LSL_C(u32 x, int shift, bool& carry_out) + { + u32 extended_x = x << shift; + carry_out = (extended_x >> 31) ? 1 : 0; + return extended_x & ~(1 << 31); + } + + u32 LSL(u32 x, int shift) + { + if(!shift) return x; + bool carry_out; + return LSL_C(x, shift, carry_out); + } + + u32 LSR_C(u32 x, int shift, bool& carry_out) + { + carry_out = (x >> (shift - 1)) & 0x1; + return x >> shift; + } + + u32 LSR(u32 x, int shift) + { + if(!shift) return x; + bool carry_out; + return LSR_C(x, shift, carry_out); + } + + s32 ASR_C(s32 x, int shift, bool& carry_out) + { + carry_out = (x >> (shift - 1)) & 0x1; + return x >> shift; + } + + s32 ASR(s32 x, int shift) + { + if(!shift) return x; + bool carry_out; + return ASR_C(x, shift, carry_out); + } + + u32 ROR_C(u32 x, int shift, bool& carry_out) + { + u32 result = LSR(x, shift) | LSL(x, 32 - shift); + carry_out = (result >> 30) & 0x1; + return result; + } + + s32 ROR(s32 x, int shift) + { + if(!shift) return x; + bool carry_out; + return ROR_C(x, shift, carry_out); + } + + template T RRX_C(T x, bool carry_in, bool& carry_out) + { + carry_out = x & 0x1; + return ((u32)carry_in << 31) | (x & 0x7ffffffe); + } + + s32 RRX(s32 x, int shift) + { + if(!shift) return x; + bool carry_out; + return RRX_C(x, shift, carry_out); + } + + template T Shift_C(T value, SRType type, uint amount, bool carry_in, bool& carry_out) + { + if(amount) + { + switch(type) + { + case SRType_LSL: return LSL_C(value, amount, carry_out); + case SRType_LSR: return LSR_C(value, amount, carry_out); + case SRType_ASR: return ASR_C(value, amount, carry_out); + case SRType_ROR: return ROR_C(value, amount, carry_out); + case SRType_RRX: return RRX_C(value, amount, carry_out); + } + } + + carry_out = carry_in; + return value; + } + + template T Shift(T value, SRType type, uint amount, bool carry_in) + { + bool carry_out; + return Shift_C(value, type, amount, carry_in, carry_out); + } + + template T AddWithCarry(T x, T y, bool carry_in, bool& carry_out, bool& overflow) + { + uint unsigned_sum = (uint)x + (uint)y + (uint)carry_in; + int signed_sum = (int)x + (int)y + (int)carry_in; + T result = unsigned_sum & ~(T(1) << (sizeof(T) - 1)); + carry_out = (uint)result != unsigned_sum; + overflow = (int)result != signed_sum; + return result; + } + + bool ConditionPassed(u8 cond) + { + bool result; + + switch(cond >> 1) + { + case 0: result = CPU.APSR.Z == 1; break; + case 1: result = CPU.APSR.C == 1; break; + case 2: result = CPU.APSR.N == 1; break; + case 3: result = CPU.APSR.V == 1; break; + case 4: result = CPU.APSR.C == 1 && CPU.APSR.Z == 0; break; + case 5: result = CPU.APSR.N == CPU.APSR.V; break; + case 6: result = CPU.APSR.N == CPU.APSR.V && CPU.APSR.Z == 0; break; + case 7: return true; + } + + if(cond & 0x1) + { + return !result; + } + + return result; + } + +protected: + void NULL_OP() + { + ConLog.Error("null"); + Emu.Pause(); + } + + void NOP() + { + } + + void PUSH(u16 regs_list) + { + for(u16 mask=0x1, i=0; mask; mask <<= 1, i++) + { + if(regs_list & mask) + { + CPU.SP -= 4; + Memory.Write32(CPU.SP, CPU.read_gpr(i)); + } + } + } + + void POP(u16 regs_list) + { + for(u16 mask=(0x1 << 15), i=15; mask; mask >>= 1, i--) + { + if(regs_list & mask) + { + CPU.write_gpr(i, Memory.Read32(CPU.SP)); + CPU.SP += 4; + } + } + } + + void B(u8 cond, u32 imm, u8 intstr_size) + { + if(ConditionPassed(cond)) + { + CPU.SetBranch(CPU.PC + intstr_size + imm); + } + } + + void CBZ(u8 op, u32 imm, u8 rn, u8 intstr_size) + { + if((CPU.GPR[rn] == 0) ^ op) + { + CPU.SetBranch(CPU.PC + intstr_size + imm); + } + } + + void BL(u32 imm, u8 intstr_size) + { + CPU.LR = (CPU.PC + intstr_size) | 1; + CPU.SetBranch(CPU.PC + intstr_size + imm); + } + + void UNK(const u16 code0, const u16 code1) + { + ConLog.Error("Unknown/Illegal opcode! (0x%04x : 0x%04x)", code0, code1); + Emu.Pause(); + } +}; \ No newline at end of file diff --git a/rpcs3/Emu/ARMv7/ARMv7Opcodes.h b/rpcs3/Emu/ARMv7/ARMv7Opcodes.h new file mode 100644 index 0000000000..35d3684c8e --- /dev/null +++ b/rpcs3/Emu/ARMv7/ARMv7Opcodes.h @@ -0,0 +1,49 @@ +#pragma once + +static const char* g_arm_reg_name[16] = +{ + "r0", "r1", "r2", "r3", + "r4", "r5", "r6", "r7", + "r8", "r9", "r10", "r11", + "r12", "sp", "lr", "pc", +}; + +namespace ARMv7_opcodes +{ + enum ARMv7_T1Opcodes + { + T1_CBZ = 0xb, + T1_B = 0xd, + T1_PUSH = 0x1d, + T1_POP = 0x5e, + T1_NOP = 0xBF00, + }; + + enum ARMv7_T2Opcodes + { + T2_B = 0x1c, + T2_PUSH = 0xe92d, + T2_POP = 0xe8bd, + }; + + enum ARMv7_T3Opcodes + { + T3_B = 0x1e, + }; +} + +class ARMv7Opcodes +{ +public: + virtual void NULL_OP() = 0; + virtual void NOP() = 0; + + virtual void PUSH(u16 regs_list) = 0; + virtual void POP(u16 regs_list) = 0; + + virtual void B(u8 cond, u32 imm, u8 intstr_size) = 0; + virtual void CBZ(u8 op, u32 imm, u8 rn, u8 intstr_size) = 0; + virtual void BL(u32 imm, u8 intstr_size)=0; + + virtual void UNK(const u16 code0, const u16 code1) = 0; +}; diff --git a/rpcs3/Emu/ARMv7/ARMv7Thread.cpp b/rpcs3/Emu/ARMv7/ARMv7Thread.cpp new file mode 100644 index 0000000000..ee0b69a996 --- /dev/null +++ b/rpcs3/Emu/ARMv7/ARMv7Thread.cpp @@ -0,0 +1,96 @@ +#include "stdafx.h" +#include "ARMv7Thread.h" +#include "ARMv7Decoder.h" +#include "ARMv7DisAsm.h" +#include "ARMv7Interpreter.h" + +ARMv7Thread::ARMv7Thread() : CPUThread(CPU_THREAD_ARMv7) +{ +} + +void ARMv7Thread::InitRegs() +{ + memset(GPR, 0, sizeof(GPR[0]) * 15); + APSR.APSR = 0; + IPSR.IPSR = 0; + SP = m_stack_point; +} + +void ARMv7Thread::InitStack() +{ + if(!m_stack_addr) + { + m_stack_size = 0x10000; + m_stack_addr = Memory.Alloc(0x10000, 1); + } + + m_stack_point = m_stack_addr + m_stack_size; +} + +u64 ARMv7Thread::GetFreeStackSize() const +{ + return SP - GetStackAddr(); +} + +void ARMv7Thread::SetArg(const uint pos, const u64 arg) +{ + assert(0); +} + +wxString ARMv7Thread::RegsToString() +{ + wxString result; + for(int i=0; i<15; ++i) + { + result += wxString::Format("%s\t= 0x%08x\n", g_arm_reg_name[i], GPR[i]); + } + + result += wxString::Format("APSR\t= 0x%08x [N: %d, Z: %d, C: %d, V: %d, Q: %d]\n", APSR.APSR, APSR.N, APSR.Z, APSR.C, APSR.V, APSR.Q); + + return result; +} + +wxString ARMv7Thread::ReadRegString(wxString reg) +{ + return wxEmptyString; +} + +bool ARMv7Thread::WriteRegString(wxString reg, wxString value) +{ + return true; +} + +void ARMv7Thread::DoReset() +{ +} + +void ARMv7Thread::DoRun() +{ + switch(Ini.CPUDecoderMode.GetValue()) + { + case 0: + //m_dec = new ARMv7Decoder(*new ARMv7DisAsm()); + break; + + case 1: + case 2: + m_dec = new ARMv7Decoder(*new ARMv7Interpreter(*this)); + break; + } +} + +void ARMv7Thread::DoPause() +{ +} + +void ARMv7Thread::DoResume() +{ +} + +void ARMv7Thread::DoStop() +{ +} + +void ARMv7Thread::DoCode() +{ +} \ No newline at end of file diff --git a/rpcs3/Emu/ARMv7/ARMv7Thread.h b/rpcs3/Emu/ARMv7/ARMv7Thread.h new file mode 100644 index 0000000000..7f5ad7dd52 --- /dev/null +++ b/rpcs3/Emu/ARMv7/ARMv7Thread.h @@ -0,0 +1,99 @@ +#pragma once +#include "Emu/CPU/CPUThread.h" + +class ARMv7Thread : public CPUThread +{ +public: + ARMv7Thread(); + + union + { + u32 GPR[15]; + + struct + { + u32 pad[13]; + + union + { + u32 SP; + + struct { u16 SP_main, SP_process; }; + }; + + u32 LR; + }; + }; + + union + { + struct + { + u32 N : 1; //Negative condition code flag + u32 Z : 1; //Zero condition code flag + u32 C : 1; //Carry condition code flag + u32 V : 1; //Overflow condition code flag + u32 Q : 1; //Set to 1 if an SSAT or USAT instruction changes (saturates) the input value for the signed or unsigned range of the result + u32 : 27; + }; + + u32 APSR; + } APSR; + + union + { + struct + { + u32 : 24; + u32 exception : 8; + }; + + u32 IPSR; + } IPSR; + + void write_gpr(u8 n, u32 value) + { + assert(n < 16); + + if(n < 15) + { + GPR[n] = value; + } + else + { + SetBranch(value); + } + } + + u32 read_gpr(u8 n) + { + assert(n < 16); + + if(n < 15) + { + return GPR[n]; + } + + return PC; + } + +public: + virtual void InitRegs(); + virtual void InitStack(); + virtual u64 GetFreeStackSize() const; + virtual void SetArg(const uint pos, const u64 arg); + +public: + virtual wxString RegsToString(); + virtual wxString ReadRegString(wxString reg); + virtual bool WriteRegString(wxString reg, wxString value); + +protected: + virtual void DoReset(); + virtual void DoRun(); + virtual void DoPause(); + virtual void DoResume(); + virtual void DoStop(); + + virtual void DoCode(); +}; \ No newline at end of file diff --git a/rpcs3/Emu/CPU/CPUDecoder.h b/rpcs3/Emu/CPU/CPUDecoder.h new file mode 100644 index 0000000000..430fc82b5c --- /dev/null +++ b/rpcs3/Emu/CPU/CPUDecoder.h @@ -0,0 +1,879 @@ +#pragma once +#include "CPUInstrTable.h" +#pragma warning( disable : 4800 ) + +class CPUDecoder +{ +public: + virtual u8 DecodeMemory(const u64 address)=0; +}; + +template +class InstrCaller +{ +public: + virtual ~InstrCaller() + { + } + + virtual void operator ()(TO* op, u32 code) const = 0; + + virtual u32 operator [](u32) const + { + return 0; + } +}; + +template +class InstrBinder_0 : public InstrCaller +{ + typedef void (TO::*func_t)(); + func_t m_func; + +public: + InstrBinder_0(func_t func) + : InstrCaller() + , m_func(func) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)(); + } +}; + +template +class InstrBinder_1 : public InstrCaller +{ + typedef void (TO::*func_t)(T1); + func_t m_func; + const CodeFieldBase& m_arg_func_1; + +public: + InstrBinder_1(func_t func, const CodeFieldBase& arg_func_1) + : InstrCaller() + , m_func(func) + , m_arg_func_1(arg_func_1) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)((T1)m_arg_func_1(code)); + } +}; + +template +class InstrBinder_2 : public InstrCaller +{ + typedef void (TO::*func_t)(T1, T2); + func_t m_func; + const CodeFieldBase& m_arg_func_1; + const CodeFieldBase& m_arg_func_2; + +public: + InstrBinder_2(func_t func, const CodeFieldBase& arg_func_1, const CodeFieldBase& arg_func_2) + : InstrCaller() + , m_func(func) + , m_arg_func_1(arg_func_1) + , m_arg_func_2(arg_func_2) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)( + (T1)m_arg_func_1(code), + (T2)m_arg_func_2(code) + ); + } +}; + +template +class InstrBinder_3 : public InstrCaller +{ + typedef void (TO::*func_t)(T1, T2, T3); + func_t m_func; + const CodeFieldBase& m_arg_func_1; + const CodeFieldBase& m_arg_func_2; + const CodeFieldBase& m_arg_func_3; + +public: + InstrBinder_3(func_t func, + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3) + : InstrCaller() + , m_func(func) + , m_arg_func_1(arg_func_1) + , m_arg_func_2(arg_func_2) + , m_arg_func_3(arg_func_3) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)( + (T1)m_arg_func_1(code), + (T2)m_arg_func_2(code), + (T3)m_arg_func_3(code) + ); + } +}; + +template +class InstrBinder_4 : public InstrCaller +{ + typedef void (TO::*func_t)(T1, T2, T3, T4); + func_t m_func; + const CodeFieldBase& m_arg_func_1; + const CodeFieldBase& m_arg_func_2; + const CodeFieldBase& m_arg_func_3; + const CodeFieldBase& m_arg_func_4; + +public: + InstrBinder_4(func_t func, + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3, + const CodeFieldBase& arg_func_4) + : InstrCaller() + , m_func(func) + , m_arg_func_1(arg_func_1) + , m_arg_func_2(arg_func_2) + , m_arg_func_3(arg_func_3) + , m_arg_func_4(arg_func_4) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)( + (T1)m_arg_func_1(code), + (T2)m_arg_func_2(code), + (T3)m_arg_func_3(code), + (T4)m_arg_func_4(code) + ); + } +}; + +template +class InstrBinder_5 : public InstrCaller +{ + typedef void (TO::*func_t)(T1, T2, T3, T4, T5); + func_t m_func; + const CodeFieldBase& m_arg_func_1; + const CodeFieldBase& m_arg_func_2; + const CodeFieldBase& m_arg_func_3; + const CodeFieldBase& m_arg_func_4; + const CodeFieldBase& m_arg_func_5; + +public: + InstrBinder_5(func_t func, + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3, + const CodeFieldBase& arg_func_4, + const CodeFieldBase& arg_func_5) + : InstrCaller() + , m_func(func) + , m_arg_func_1(arg_func_1) + , m_arg_func_2(arg_func_2) + , m_arg_func_3(arg_func_3) + , m_arg_func_4(arg_func_4) + , m_arg_func_5(arg_func_5) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)( + (T1)m_arg_func_1(code), + (T2)m_arg_func_2(code), + (T3)m_arg_func_3(code), + (T4)m_arg_func_4(code), + (T5)m_arg_func_5(code) + ); + } +}; + +template +class InstrBinder_6 : public InstrCaller +{ + typedef void (TO::*func_t)(T1, T2, T3, T4, T5, T6); + func_t m_func; + const CodeFieldBase& m_arg_func_1; + const CodeFieldBase& m_arg_func_2; + const CodeFieldBase& m_arg_func_3; + const CodeFieldBase& m_arg_func_4; + const CodeFieldBase& m_arg_func_5; + const CodeFieldBase& m_arg_func_6; + +public: + InstrBinder_6(func_t func, + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3, + const CodeFieldBase& arg_func_4, + const CodeFieldBase& arg_func_5, + const CodeFieldBase& arg_func_6) + : InstrCaller() + , m_func(func) + , m_arg_func_1(arg_func_1) + , m_arg_func_2(arg_func_2) + , m_arg_func_3(arg_func_3) + , m_arg_func_4(arg_func_4) + , m_arg_func_5(arg_func_5) + , m_arg_func_6(arg_func_6) + { + } + + virtual void operator ()(TO* op, u32 code) const + { + (op->*m_func)( + (T1)m_arg_func_1(code), + (T2)m_arg_func_2(code), + (T3)m_arg_func_3(code), + (T4)m_arg_func_4(code), + (T5)m_arg_func_5(code), + (T6)m_arg_func_6(code) + ); + } +}; + +template +InstrCaller* instr_bind(void (TO::*func)()) +{ + return new InstrBinder_0(func); +} + +template +InstrCaller* instr_bind(void (TO::*func)(T1), const CodeFieldBase& arg_func_1) +{ + return new InstrBinder_1(func, arg_func_1); +} + +template +InstrCaller* instr_bind(void (TO::*func)(T1, T2), + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2) +{ + return new InstrBinder_2(func, arg_func_1, arg_func_2); +} + +template +InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3), + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3) +{ + return new InstrBinder_3(func, arg_func_1, arg_func_2, arg_func_3); +} + +template +InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3, T4), + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3, + const CodeFieldBase& arg_func_4) +{ + return new InstrBinder_4(func, arg_func_1, arg_func_2, arg_func_3, arg_func_4); +} + +template +InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3, T4, T5), + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3, + const CodeFieldBase& arg_func_4, + const CodeFieldBase& arg_func_5) +{ + return new InstrBinder_5(func, arg_func_1, arg_func_2, arg_func_3, arg_func_4, arg_func_5); +} + +template +InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3, T4, T5, T6), + const CodeFieldBase& arg_func_1, + const CodeFieldBase& arg_func_2, + const CodeFieldBase& arg_func_3, + const CodeFieldBase& arg_func_4, + const CodeFieldBase& arg_func_5, + const CodeFieldBase& arg_func_6) +{ + return new InstrBinder_6(func, arg_func_1, arg_func_2, arg_func_3, arg_func_4, arg_func_5, arg_func_6); +} + +template +class InstrBase : public InstrCaller +{ +protected: + wxString m_name; + const u32 m_opcode; + CodeFieldBase** m_args; + const uint m_args_count; + +public: + InstrBase(const wxString& name, int opcode, uint args_count) + : InstrCaller() + , m_name(name) + , m_opcode(opcode) + , m_args_count(args_count) + , m_args(args_count ? new CodeFieldBase*[args_count] : nullptr) + { + m_name.MakeLower().Replace("_", "."); + } + + __forceinline const wxString& GetName() const + { + return m_name; + } + + __forceinline const uint GetArgCount() const + { + return m_args_count; + } + + __forceinline const CodeFieldBase& GetArg(uint index) const + { + assert(index < m_args_count); + return *m_args[index]; + } + + void operator ()(TO* op, u32 code) const + { + decode(op, code); + } + + u32 operator()(const Array& args) const + { + return encode(args); + } + + virtual void decode(TO* op, u32 code) const=0; + virtual u32 encode(const Array& args) const=0; +}; + +template +class InstrList : public InstrCaller +{ +public: + static const int count = _count; + +protected: + const CodeFieldBase& m_func; + InstrCaller* m_instrs[count]; + InstrBase* m_instrs_info[count]; + InstrCaller* m_error_func; + InstrCaller* m_parent; + int m_opcode; + +public: + InstrList(const CodeFieldBase& func, InstrCaller* error_func) + : InstrCaller() + , m_func(func) + , m_error_func(error_func) + , m_parent(nullptr) + , m_opcode(-1) + { + for(int i=0; i*) * count); + } + + virtual ~InstrList() + { + for(int i=0; i* parent, int opcode) + { + m_opcode = opcode; + m_parent = parent; + } + + InstrCaller* get_parent() const + { + return m_parent; + } + + u32 get_opcode() const + { + return m_opcode; + } + + void set_error_func(InstrCaller* error_func) + { + for(int i=0; i* func, InstrBase* info = nullptr) + { + assert(pos < count); + m_instrs[pos] = func; + m_instrs_info[pos] = info; + } + + InstrCaller* get_instr(int pos) const + { + assert(pos < count); + return m_instrs[pos]; + } + + InstrBase* get_instr_info(int pos) const + { + assert(pos < count); + return m_instrs_info[pos]; + } + + u32 encode(u32 entry) const + { + return m_func[entry] | (m_parent ? (*m_parent)[m_opcode] : 0); + } + + void decode(TO* op, u32 entry, u32 code) const + { + (*m_instrs[entry])(op, code); + } + + virtual void operator ()(TO* op, u32 code) const + { + decode(op, m_func(code) & (count - 1), code); + } + + virtual u32 operator [](u32 entry) const + { + return encode(entry); + } +}; + +template +static InstrList* connect_list(InstrList* parent, InstrList* child, int opcode) +{ + parent->set_instr(opcode, child); + child->set_parent(parent, opcode); + return child; +} + +template +static InstrList* connect_list(InstrList* parent, InstrList* child) +{ + parent->set_error_func(child); + child->set_parent(parent->get_parent(), parent->get_opcode()); + return child; +} + +template +class Instr0 : public InstrBase +{ + InstrList& m_list; + +public: + Instr0(InstrList* list, const wxString& name, + void (TO::*func)()) + : InstrBase(name, opcode, 0) + , m_list(*list) + { + m_list.set_instr(opcode, instr_bind(func), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode); + } + + u32 encode() const + { + return m_list.encode(opcode); + } + + u32 operator()() const + { + return encode(); + } +}; + +template +class Instr1 : public InstrBase +{ + InstrList& m_list; + +public: + Instr1(InstrList* list, const wxString& name, + void (TO::*func)(T1), + CodeFieldBase& arg_1) + : InstrBase(name, opcode, 1) + , m_list(*list) + { + m_args[0] = &arg_1; + + m_list.set_instr(opcode, instr_bind(func, arg_1), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode) | (*m_args[0])[args[0]]; + } + + u32 encode(T1 a1) const + { + return m_list.encode(opcode) | (*m_args[0])[a1]; + } + + u32 operator()(T1 a1) const + { + return encode(a1); + } +}; + +template +class Instr2 : public InstrBase +{ + InstrList& m_list; + +public: + Instr2(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2) + : InstrBase(name, opcode, 2) + , m_list(*list) + { + m_args[0] = &arg_1; + m_args[1] = &arg_2; + + m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode) | (*m_args[0])[args[0]] | (*m_args[1])[args[1]]; + } + + u32 encode(T1 a1, T2 a2) const + { + return m_list.encode(opcode) | (*m_args[0])[a1] | (*m_args[1])[a2]; + } + + u32 operator()(T1 a1, T2 a2) const + { + return encode(a1, a2); + } +}; + +template +class Instr3 : public InstrBase +{ + InstrList& m_list; + +public: + Instr3(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3) + : InstrBase(name, opcode, 3) + , m_list(*list) + { + m_args[0] = &arg_1; + m_args[1] = &arg_2; + m_args[2] = &arg_3; + + m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode) | (*m_args[0])[args[0]] | (*m_args[1])[args[1]] | (*m_args[2])[args[2]]; + } + + u32 encode(T1 a1, T2 a2, T3 a3) const + { + return m_list.encode(opcode) | (*m_args[0])[a1] | (*m_args[1])[a2] | (*m_args[2])[a3]; + } + + u32 operator()(T1 a1, T2 a2, T3 a3) const + { + return encode(a1, a2, a3); + } +}; + +template +class Instr4 : public InstrBase +{ + InstrList& m_list; + +public: + Instr4(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3, T4), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3, + CodeFieldBase& arg_4) + : InstrBase(name, opcode, 4) + , m_list(*list) + { + m_args[0] = &arg_1; + m_args[1] = &arg_2; + m_args[2] = &arg_3; + m_args[3] = &arg_4; + + m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3, arg_4), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode) | + (*m_args[0])[args[0]] | + (*m_args[1])[args[1]] | + (*m_args[2])[args[2]] | + (*m_args[3])[args[3]]; + } + + u32 encode(T1 a1, T2 a2, T3 a3, T4 a4) const + { + return m_list.encode(opcode) | + (*m_args[0])[a1] | + (*m_args[1])[a2] | + (*m_args[2])[a3] | + (*m_args[3])[a4]; + } + + u32 operator()(T1 a1, T2 a2, T3 a3, T4 a4) const + { + return encode(a1, a2, a3, a4); + } +}; + +template +class Instr5 : public InstrBase +{ + InstrList& m_list; + +public: + Instr5(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3, T4, T5), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3, + CodeFieldBase& arg_4, + CodeFieldBase& arg_5) + : InstrBase(name, opcode, 5) + , m_list(*list) + { + m_args[0] = &arg_1; + m_args[1] = &arg_2; + m_args[2] = &arg_3; + m_args[3] = &arg_4; + m_args[4] = &arg_5; + + m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3, arg_4, arg_5), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode) | + (*m_args[0])[args[0]] | + (*m_args[1])[args[1]] | + (*m_args[2])[args[2]] | + (*m_args[3])[args[3]] | + (*m_args[4])[args[4]]; + } + + u32 encode(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) const + { + return m_list.encode(opcode) | + (*m_args[0])[a1] | + (*m_args[1])[a2] | + (*m_args[2])[a3] | + (*m_args[3])[a4] | + (*m_args[4])[a5]; + } + + u32 operator()(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) const + { + return encode(a1, a2, a3, a4, a5); + } +}; + +template +class Instr6 : public InstrBase +{ + InstrList& m_list; + +public: + Instr6(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3, T4, T5, T6), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3, + CodeFieldBase& arg_4, + CodeFieldBase& arg_5, + CodeFieldBase& arg_6) + : InstrBase(name, opcode, 6) + , m_list(*list) + { + m_args[0] = &arg_1; + m_args[1] = &arg_2; + m_args[2] = &arg_3; + m_args[3] = &arg_4; + m_args[4] = &arg_5; + m_args[5] = &arg_6; + + m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6), this); + } + + virtual void decode(TO* op, u32 code) const + { + m_list.decode(op, opcode, code); + } + + virtual u32 encode(const Array& args) const + { + assert(args.GetCount() == m_args_count); + return m_list.encode(opcode) | + (*m_args[0])[args[0]] | + (*m_args[1])[args[1]] | + (*m_args[2])[args[2]] | + (*m_args[3])[args[3]] | + (*m_args[4])[args[4]] | + (*m_args[5])[args[5]]; + } + + u32 encode(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T5 a6) const + { + return m_list.encode(opcode) | + (*m_args[0])[a1] | + (*m_args[1])[a2] | + (*m_args[2])[a3] | + (*m_args[3])[a4] | + (*m_args[4])[a5] | + (*m_args[5])[a6]; + } + + u32 operator()(T1 a1, T2 a2, T3 a3, T4 a4, T4 a5, T4 a6) const + { + return encode(a1, a2, a3, a4, a5, a6); + } +}; + +template +static Instr0& make_instr(InstrList* list, const wxString& name, void (TO::*func)()) +{ + return *new Instr0(list, name, func); +} + +template +static Instr1& make_instr(InstrList* list, const wxString& name, + void (TO::*func)(T1), + CodeFieldBase& arg_1) +{ + return *new Instr1(list, name, func, arg_1); +} + +template +static Instr2& make_instr(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2) +{ + return *new Instr2(list, name, func, arg_1, arg_2); +} + +template +static Instr3& make_instr(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3) +{ + return *new Instr3(list, name, func, arg_1, arg_2, arg_3); +} + +template +static Instr4& make_instr(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3, T4), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3, + CodeFieldBase& arg_4) +{ + return *new Instr4(list, name, func, arg_1, arg_2, arg_3, arg_4); +} + +template +static Instr5& make_instr(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3, T4, T5), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3, + CodeFieldBase& arg_4, + CodeFieldBase& arg_5) +{ + return *new Instr5(list, name, func, arg_1, arg_2, arg_3, arg_4, arg_5); +} + +template +static Instr6& make_instr(InstrList* list, const wxString& name, + void (TO::*func)(T1, T2, T3, T4, T5, T6), + CodeFieldBase& arg_1, + CodeFieldBase& arg_2, + CodeFieldBase& arg_3, + CodeFieldBase& arg_4, + CodeFieldBase& arg_5, + CodeFieldBase& arg_6) +{ + return *new Instr6(list, name, func, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6); +} \ No newline at end of file diff --git a/rpcs3/Emu/CPU/CPUDisAsm.h b/rpcs3/Emu/CPU/CPUDisAsm.h new file mode 100644 index 0000000000..139dd3f1d0 --- /dev/null +++ b/rpcs3/Emu/CPU/CPUDisAsm.h @@ -0,0 +1,63 @@ +#pragma once + +#include "Emu/Memory/Memory.h" + +enum CPUDisAsmMode +{ + CPUDisAsm_DumpMode, + CPUDisAsm_InterpreterMode, + //CPUDisAsm_NormalMode, + CPUDisAsm_CompilerElfMode, +}; + +class CPUDisAsm +{ +protected: + const CPUDisAsmMode m_mode; + + virtual void Write(const wxString& value) + { + switch(m_mode) + { + case CPUDisAsm_DumpMode: + last_opcode = wxString::Format("\t%08llx:\t%02x %02x %02x %02x\t%s\n", dump_pc, + Memory.Read8(offset + dump_pc), + Memory.Read8(offset + dump_pc + 1), + Memory.Read8(offset + dump_pc + 2), + Memory.Read8(offset + dump_pc + 3), value); + break; + + case CPUDisAsm_InterpreterMode: + last_opcode = wxString::Format("[%08llx] %02x %02x %02x %02x: %s", dump_pc, + Memory.Read8(offset + dump_pc), + Memory.Read8(offset + dump_pc + 1), + Memory.Read8(offset + dump_pc + 2), + Memory.Read8(offset + dump_pc + 3), value); + break; + + case CPUDisAsm_CompilerElfMode: + last_opcode = value + "\n"; + break; + } + } + +public: + wxString last_opcode; + u64 dump_pc; + u64 offset; + +protected: + CPUDisAsm(CPUDisAsmMode mode) + : m_mode(mode) + , offset(0) + { + } + + virtual u32 DisAsmBranchTarget(const s32 imm)=0; + + wxString FixOp(wxString op) + { + op.Append(' ', max(8 - op.Len(), 0)); + return op; + } +}; \ No newline at end of file diff --git a/rpcs3/Emu/CPU/CPUInstrTable.h b/rpcs3/Emu/CPU/CPUInstrTable.h new file mode 100644 index 0000000000..1ec101a875 --- /dev/null +++ b/rpcs3/Emu/CPU/CPUInstrTable.h @@ -0,0 +1,34 @@ +#pragma once + +template __forceinline static T sign(const T value) +{ + static_assert(size > 0 && size < sizeof(T) * 8, "Bad sign size"); + + if(value & (T(1) << (size - 1))) + { + return value - (T(1) << size); + } + + return value; +} + +class CodeFieldBase +{ +public: + u32 m_type; + +public: + CodeFieldBase(u32 type) : m_type(type) + { + } + + virtual u32 operator ()(u32 data) const=0; + virtual void operator()(u32& data, u32 value) const=0; + + virtual u32 operator[](u32 value) const + { + u32 result = 0; + (*this)(result, value); + return result; + } +}; diff --git a/rpcs3/Emu/CPU/CPUThread.cpp b/rpcs3/Emu/CPU/CPUThread.cpp new file mode 100644 index 0000000000..4733867bea --- /dev/null +++ b/rpcs3/Emu/CPU/CPUThread.cpp @@ -0,0 +1,338 @@ +#include "stdafx.h" +#include "CPUThread.h" + +CPUThread* GetCurrentCPUThread() +{ + return (CPUThread*)GetCurrentNamedThread(); +} + +CPUThread::CPUThread(CPUThreadType type) + : ThreadBase(true, "CPUThread") + , m_type(type) + , m_stack_size(0) + , m_stack_addr(0) + , m_offset(0) + , m_prio(0) + , m_sync_wait(false) + , m_wait_thread_id(-1) + , m_free_data(false) + , m_dec(nullptr) + , m_is_step(false) + , m_is_branch(false) +{ +} + +CPUThread::~CPUThread() +{ + Close(); +} + +void CPUThread::Close() +{ + if(IsAlive()) + { + m_free_data = true; + } + else + { + delete m_dec; + m_dec = nullptr; + } + + Stop(); +} + +void CPUThread::Reset() +{ + CloseStack(); + + m_sync_wait = 0; + m_wait_thread_id = -1; + + SetPc(0); + cycle = 0; + m_is_branch = false; + + m_status = Stopped; + m_error = 0; + + DoReset(); +} + +void CPUThread::CloseStack() +{ + if(m_stack_addr) + { + Memory.Free(m_stack_addr); + m_stack_addr = 0; + } + + m_stack_size = 0; + m_stack_point = 0; +} + +void CPUThread::SetId(const u32 id) +{ + m_id = id; +} + +void CPUThread::SetName(const wxString& name) +{ + m_name = name; +} + +void CPUThread::Wait(bool wait) +{ + wxCriticalSectionLocker lock(m_cs_sync); + m_sync_wait = wait; +} + +void CPUThread::Wait(const CPUThread& thr) +{ + wxCriticalSectionLocker lock(m_cs_sync); + m_wait_thread_id = thr.GetId(); + m_sync_wait = true; +} + +bool CPUThread::Sync() +{ + wxCriticalSectionLocker lock(m_cs_sync); + + return m_sync_wait; +} + +int CPUThread::ThreadStatus() +{ + if(Emu.IsStopped()) + { + return CPUThread_Stopped; + } + + if(TestDestroy()) + { + return CPUThread_Break; + } + + if(m_is_step) + { + return CPUThread_Step; + } + + if(Emu.IsPaused() || Sync()) + { + return CPUThread_Sleeping; + } + + return CPUThread_Running; +} + +void CPUThread::SetEntry(const u64 pc) +{ + entry = pc; +} + +void CPUThread::NextPc(u8 instr_size) +{ + if(m_is_branch) + { + m_is_branch = false; + + SetPc(nPC); + } + else + { + PC += instr_size; + } +} + +void CPUThread::SetBranch(const u64 pc) +{ + if(!Memory.IsGoodAddr(m_offset + pc)) + { + ConLog.Error("%s branch error: bad address 0x%llx #pc: 0x%llx", GetFName(), m_offset + pc, m_offset + PC); + Emu.Pause(); + } + + m_is_branch = true; + nPC = pc; +} + +void CPUThread::SetPc(const u64 pc) +{ + PC = pc; +} + +void CPUThread::SetError(const u32 error) +{ + if(error == 0) + { + m_error = 0; + } + else + { + m_error |= error; + } +} + +wxArrayString CPUThread::ErrorToString(const u32 error) +{ + wxArrayString earr; + + if(error == 0) return earr; + + earr.Add("Unknown error"); + + return earr; +} + +void CPUThread::Run() +{ + if(IsRunning()) Stop(); + if(IsPaused()) + { + Resume(); + return; + } + + wxGetApp().SendDbgCommand(DID_START_THREAD, this); + + m_status = Running; + + SetPc(entry); + InitStack(); + InitRegs(); + DoRun(); + Emu.CheckStatus(); + + wxGetApp().SendDbgCommand(DID_STARTED_THREAD, this); +} + +void CPUThread::Resume() +{ + if(!IsPaused()) return; + + wxGetApp().SendDbgCommand(DID_RESUME_THREAD, this); + + m_status = Running; + DoResume(); + Emu.CheckStatus(); + + ThreadBase::Start(); + + wxGetApp().SendDbgCommand(DID_RESUMED_THREAD, this); +} + +void CPUThread::Pause() +{ + if(!IsRunning()) return; + + wxGetApp().SendDbgCommand(DID_PAUSE_THREAD, this); + + m_status = Paused; + DoPause(); + Emu.CheckStatus(); + + ThreadBase::Stop(false); + wxGetApp().SendDbgCommand(DID_PAUSED_THREAD, this); +} + +void CPUThread::Stop() +{ + if(IsStopped()) return; + + wxGetApp().SendDbgCommand(DID_STOP_THREAD, this); + + m_status = Stopped; + ThreadBase::Stop(false); + Reset(); + DoStop(); + Emu.CheckStatus(); + + wxGetApp().SendDbgCommand(DID_STOPED_THREAD, this); +} + +void CPUThread::Exec() +{ + m_is_step = false; + wxGetApp().SendDbgCommand(DID_EXEC_THREAD, this); + ThreadBase::Start(); +} + +void CPUThread::ExecOnce() +{ + m_is_step = true; + wxGetApp().SendDbgCommand(DID_EXEC_THREAD, this); + ThreadBase::Start(); + if(!ThreadBase::Wait()) while(m_is_step) Sleep(1); + wxGetApp().SendDbgCommand(DID_PAUSE_THREAD, this); + wxGetApp().SendDbgCommand(DID_PAUSED_THREAD, this); +} + +void CPUThread::Task() +{ + //ConLog.Write("%s enter", CPUThread::GetFName()); + + const Array& bp = Emu.GetBreakPoints(); + + try + { + for(uint i=0; iDecodeMemory(PC + m_offset)); + + if(status == CPUThread_Step) + { + m_is_step = false; + break; + } + + for(uint i=0; i + void WaitFor(T func) + { + while(func(ThreadStatus())) + { + Sleep(1); + } + } + + int ThreadStatus(); + + void NextPc(u8 instr_size); + void SetBranch(const u64 pc); + void SetPc(const u64 pc); + void SetEntry(const u64 entry); + + void SetError(const u32 error); + + static wxArrayString ErrorToString(const u32 error); + wxArrayString ErrorToString() { return ErrorToString(m_error); } + + bool IsOk() const { return m_error == 0; } + bool IsRunning() const { return m_status == Running; } + bool IsPaused() const { return m_status == Paused; } + bool IsStopped() const { return m_status == Stopped; } + + bool IsJoinable() const { return m_joinable; } + bool IsJoining() const { return m_joining; } + void SetJoinable(bool joinable) { m_joinable = joinable; } + void SetJoining(bool joining) { m_joining = joining; } + + u32 GetError() const { return m_error; } + u32 GetId() const { return m_id; } + CPUThreadType GetType() const { return m_type; } + + void Reset(); + void Close(); + void Run(); + void Pause(); + void Resume(); + void Stop(); + + virtual void AddArgv(const wxString& arg) {} + + virtual wxString RegsToString() = 0; + virtual wxString ReadRegString(wxString reg) = 0; + virtual bool WriteRegString(wxString reg, wxString value) = 0; + + virtual void Exec(); + void ExecOnce(); + +protected: + virtual void DoReset()=0; + virtual void DoRun()=0; + virtual void DoPause()=0; + virtual void DoResume()=0; + virtual void DoStop()=0; + +protected: + virtual void Task(); +}; + +CPUThread* GetCurrentCPUThread(); \ No newline at end of file diff --git a/rpcs3/Emu/CPU/CPUThreadManager.cpp b/rpcs3/Emu/CPU/CPUThreadManager.cpp new file mode 100644 index 0000000000..d4588f4930 --- /dev/null +++ b/rpcs3/Emu/CPU/CPUThreadManager.cpp @@ -0,0 +1,111 @@ +#include "stdafx.h" +#include "CPUThreadManager.h" +#include "Emu\Cell\PPUThread.h" +#include "Emu\Cell\SPUThread.h" +#include "Emu\Cell\RawSPUThread.h" +#include "Emu\ARMv7\ARMv7Thread.h" + +CPUThreadManager::CPUThreadManager() + : m_raw_spu_num(0) +{ +} + +CPUThreadManager::~CPUThreadManager() +{ + Close(); +} + +void CPUThreadManager::Close() +{ + m_raw_spu_num = 0; + while(m_threads.GetCount()) RemoveThread(m_threads[0].GetId()); +} + +CPUThread& CPUThreadManager::AddThread(CPUThreadType type) +{ + std::lock_guard lock(m_mtx_thread); + + CPUThread* new_thread; + + switch(type) + { + case CPU_THREAD_PPU: new_thread = new PPUThread(); break; + case CPU_THREAD_SPU: new_thread = new SPUThread(); break; + case CPU_THREAD_RAW_SPU: new_thread = new RawSPUThread(m_raw_spu_num++); break; + case CPU_THREAD_ARMv7: new_thread = new ARMv7Thread(); break; + default: assert(0); + } + + new_thread->SetId(Emu.GetIdManager().GetNewID(wxString::Format("%s Thread", new_thread->GetTypeString()), new_thread)); + + m_threads.Add(new_thread); + wxGetApp().SendDbgCommand(DID_CREATE_THREAD, new_thread); + + return *new_thread; +} + +void CPUThreadManager::RemoveThread(const u32 id) +{ + std::lock_guard lock(m_mtx_thread); + + for(u32 i=0; iIsAlive()) + { + thr->Close(); + } + else + { + thr->Close(); + delete thr; + } + + + m_threads.RemoveFAt(i); + i--; + } + + Emu.GetIdManager().RemoveID(id, false); + Emu.CheckStatus(); +} + +s32 CPUThreadManager::GetThreadNumById(CPUThreadType type, u32 id) +{ + s32 num = 0; + + for(u32 i=0; i m_threads; + std::mutex m_mtx_thread; + wxSemaphore m_sem_task; + Stack m_delete_threads; + u32 m_raw_spu_num; + +public: + CPUThreadManager(); + ~CPUThreadManager(); + + void Close(); + + CPUThread& AddThread(CPUThreadType type); + void RemoveThread(const u32 id); + + ArrayF& GetThreads() { return m_threads; } + s32 GetThreadNumById(CPUThreadType type, u32 id); + CPUThread* GetThread(u32 id); + + void Exec(); + void Task(); +}; \ No newline at end of file diff --git a/rpcs3/Emu/Cell/PPCDecoder.cpp b/rpcs3/Emu/Cell/PPCDecoder.cpp new file mode 100644 index 0000000000..078d383322 --- /dev/null +++ b/rpcs3/Emu/Cell/PPCDecoder.cpp @@ -0,0 +1,9 @@ +#include "stdafx.h" +#include "PPCDecoder.h" + +u8 PPCDecoder::DecodeMemory(const u64 address) +{ + Decode(Memory.Read32(address)); + + return 4; +} \ No newline at end of file diff --git a/rpcs3/Emu/Cell/PPCDecoder.h b/rpcs3/Emu/Cell/PPCDecoder.h index 68e7d6da72..3185a441a9 100644 --- a/rpcs3/Emu/Cell/PPCDecoder.h +++ b/rpcs3/Emu/Cell/PPCDecoder.h @@ -1,488 +1,15 @@ #pragma once +#include "Emu/CPU/CPUDecoder.h" #include "PPCInstrTable.h" -#pragma warning( disable : 4800 ) -template -class InstrCaller +class PPCDecoder : public CPUDecoder { public: - virtual ~InstrCaller() - { - } - - virtual void operator ()(TO* op, u32 code) const = 0; - - virtual u32 operator [](u32) const - { - return 0; - } -}; - -class PPC_Decoder -{ -protected: - u32 m_code; - -public: - u32 GetCode() const { return m_code; } - virtual void Decode(const u32 code)=0; + + virtual u8 DecodeMemory(const u64 address); }; -template -class InstrBinder_0 : public InstrCaller -{ - typedef void (TO::*func_t)(); - func_t m_func; - -public: - InstrBinder_0(func_t func) - : InstrCaller() - , m_func(func) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)(); - } -}; - -template -class InstrBinder_1 : public InstrCaller -{ - typedef void (TO::*func_t)(T1); - func_t m_func; - const CodeFieldBase& m_arg_func_1; - -public: - InstrBinder_1(func_t func, const CodeFieldBase& arg_func_1) - : InstrCaller() - , m_func(func) - , m_arg_func_1(arg_func_1) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)((T1)m_arg_func_1(code)); - } -}; - -template -class InstrBinder_2 : public InstrCaller -{ - typedef void (TO::*func_t)(T1, T2); - func_t m_func; - const CodeFieldBase& m_arg_func_1; - const CodeFieldBase& m_arg_func_2; - -public: - InstrBinder_2(func_t func, const CodeFieldBase& arg_func_1, const CodeFieldBase& arg_func_2) - : InstrCaller() - , m_func(func) - , m_arg_func_1(arg_func_1) - , m_arg_func_2(arg_func_2) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)( - (T1)m_arg_func_1(code), - (T2)m_arg_func_2(code) - ); - } -}; - -template -class InstrBinder_3 : public InstrCaller -{ - typedef void (TO::*func_t)(T1, T2, T3); - func_t m_func; - const CodeFieldBase& m_arg_func_1; - const CodeFieldBase& m_arg_func_2; - const CodeFieldBase& m_arg_func_3; - -public: - InstrBinder_3(func_t func, - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3) - : InstrCaller() - , m_func(func) - , m_arg_func_1(arg_func_1) - , m_arg_func_2(arg_func_2) - , m_arg_func_3(arg_func_3) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)( - (T1)m_arg_func_1(code), - (T2)m_arg_func_2(code), - (T3)m_arg_func_3(code) - ); - } -}; - -template -class InstrBinder_4 : public InstrCaller -{ - typedef void (TO::*func_t)(T1, T2, T3, T4); - func_t m_func; - const CodeFieldBase& m_arg_func_1; - const CodeFieldBase& m_arg_func_2; - const CodeFieldBase& m_arg_func_3; - const CodeFieldBase& m_arg_func_4; - -public: - InstrBinder_4(func_t func, - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3, - const CodeFieldBase& arg_func_4) - : InstrCaller() - , m_func(func) - , m_arg_func_1(arg_func_1) - , m_arg_func_2(arg_func_2) - , m_arg_func_3(arg_func_3) - , m_arg_func_4(arg_func_4) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)( - (T1)m_arg_func_1(code), - (T2)m_arg_func_2(code), - (T3)m_arg_func_3(code), - (T4)m_arg_func_4(code) - ); - } -}; - -template -class InstrBinder_5 : public InstrCaller -{ - typedef void (TO::*func_t)(T1, T2, T3, T4, T5); - func_t m_func; - const CodeFieldBase& m_arg_func_1; - const CodeFieldBase& m_arg_func_2; - const CodeFieldBase& m_arg_func_3; - const CodeFieldBase& m_arg_func_4; - const CodeFieldBase& m_arg_func_5; - -public: - InstrBinder_5(func_t func, - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3, - const CodeFieldBase& arg_func_4, - const CodeFieldBase& arg_func_5) - : InstrCaller() - , m_func(func) - , m_arg_func_1(arg_func_1) - , m_arg_func_2(arg_func_2) - , m_arg_func_3(arg_func_3) - , m_arg_func_4(arg_func_4) - , m_arg_func_5(arg_func_5) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)( - (T1)m_arg_func_1(code), - (T2)m_arg_func_2(code), - (T3)m_arg_func_3(code), - (T4)m_arg_func_4(code), - (T5)m_arg_func_5(code) - ); - } -}; - -template -class InstrBinder_6 : public InstrCaller -{ - typedef void (TO::*func_t)(T1, T2, T3, T4, T5, T6); - func_t m_func; - const CodeFieldBase& m_arg_func_1; - const CodeFieldBase& m_arg_func_2; - const CodeFieldBase& m_arg_func_3; - const CodeFieldBase& m_arg_func_4; - const CodeFieldBase& m_arg_func_5; - const CodeFieldBase& m_arg_func_6; - -public: - InstrBinder_6(func_t func, - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3, - const CodeFieldBase& arg_func_4, - const CodeFieldBase& arg_func_5, - const CodeFieldBase& arg_func_6) - : InstrCaller() - , m_func(func) - , m_arg_func_1(arg_func_1) - , m_arg_func_2(arg_func_2) - , m_arg_func_3(arg_func_3) - , m_arg_func_4(arg_func_4) - , m_arg_func_5(arg_func_5) - , m_arg_func_6(arg_func_6) - { - } - - virtual void operator ()(TO* op, u32 code) const - { - (op->*m_func)( - (T1)m_arg_func_1(code), - (T2)m_arg_func_2(code), - (T3)m_arg_func_3(code), - (T4)m_arg_func_4(code), - (T5)m_arg_func_5(code), - (T6)m_arg_func_6(code) - ); - } -}; - -template -InstrCaller* instr_bind(void (TO::*func)()) -{ - return new InstrBinder_0(func); -} - -template -InstrCaller* instr_bind(void (TO::*func)(T1), const CodeFieldBase& arg_func_1) -{ - return new InstrBinder_1(func, arg_func_1); -} - -template -InstrCaller* instr_bind(void (TO::*func)(T1, T2), - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2) -{ - return new InstrBinder_2(func, arg_func_1, arg_func_2); -} - -template -InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3), - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3) -{ - return new InstrBinder_3(func, arg_func_1, arg_func_2, arg_func_3); -} - -template -InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3, T4), - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3, - const CodeFieldBase& arg_func_4) -{ - return new InstrBinder_4(func, arg_func_1, arg_func_2, arg_func_3, arg_func_4); -} - -template -InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3, T4, T5), - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3, - const CodeFieldBase& arg_func_4, - const CodeFieldBase& arg_func_5) -{ - return new InstrBinder_5(func, arg_func_1, arg_func_2, arg_func_3, arg_func_4, arg_func_5); -} - -template -InstrCaller* instr_bind(void (TO::*func)(T1, T2, T3, T4, T5, T6), - const CodeFieldBase& arg_func_1, - const CodeFieldBase& arg_func_2, - const CodeFieldBase& arg_func_3, - const CodeFieldBase& arg_func_4, - const CodeFieldBase& arg_func_5, - const CodeFieldBase& arg_func_6) -{ - return new InstrBinder_6(func, arg_func_1, arg_func_2, arg_func_3, arg_func_4, arg_func_5, arg_func_6); -} - -template -class InstrBase : public InstrCaller -{ -protected: - wxString m_name; - const u32 m_opcode; - CodeFieldBase** m_args; - const uint m_args_count; - -public: - InstrBase(const wxString& name, int opcode, uint args_count) - : InstrCaller() - , m_name(name) - , m_opcode(opcode) - , m_args_count(args_count) - , m_args(args_count ? new CodeFieldBase*[args_count] : nullptr) - { - m_name.MakeLower().Replace("_", "."); - } - - __forceinline const wxString& GetName() const - { - return m_name; - } - - __forceinline const uint GetArgCount() const - { - return m_args_count; - } - - __forceinline const CodeFieldBase& GetArg(uint index) const - { - assert(index < m_args_count); - return *m_args[index]; - } - - void operator ()(TO* op, u32 code) const - { - decode(op, code); - } - - u32 operator()(const Array& args) const - { - return encode(args); - } - - virtual void decode(TO* op, u32 code) const=0; - virtual u32 encode(const Array& args) const=0; -}; - -template -class InstrList : public InstrCaller -{ -public: - static const int count = _count; - -protected: - const CodeFieldBase& m_func; - InstrCaller* m_instrs[count]; - InstrBase* m_instrs_info[count]; - InstrCaller* m_error_func; - InstrCaller* m_parent; - int m_opcode; - -public: - InstrList(const CodeFieldBase& func, InstrCaller* error_func) - : InstrCaller() - , m_func(func) - , m_error_func(error_func) - , m_parent(nullptr) - , m_opcode(-1) - { - for(int i=0; i*) * count); - } - - virtual ~InstrList() - { - for(int i=0; i* parent, int opcode) - { - m_opcode = opcode; - m_parent = parent; - } - - InstrCaller* get_parent() const - { - return m_parent; - } - - u32 get_opcode() const - { - return m_opcode; - } - - void set_error_func(InstrCaller* error_func) - { - for(int i=0; i* func, InstrBase* info = nullptr) - { - assert(pos < count); - m_instrs[pos] = func; - m_instrs_info[pos] = info; - } - - InstrCaller* get_instr(int pos) const - { - assert(pos < count); - return m_instrs[pos]; - } - - InstrBase* get_instr_info(int pos) const - { - assert(pos < count); - return m_instrs_info[pos]; - } - - u32 encode(u32 entry) const - { - return m_func[entry] | (m_parent ? (*m_parent)[m_opcode] : 0); - } - - void decode(TO* op, u32 entry, u32 code) const - { - (*m_instrs[entry])(op, code); - } - - virtual void operator ()(TO* op, u32 code) const - { - decode(op, m_func(code) & (count - 1), code); - } - - virtual u32 operator [](u32 entry) const - { - return encode(entry); - } -}; - -template -static InstrList* connect_list(InstrList* parent, InstrList* child, int opcode) -{ - parent->set_instr(opcode, child); - child->set_parent(parent, opcode); - return child; -} - -template -static InstrList* connect_list(InstrList* parent, InstrList* child) -{ - parent->set_error_func(child); - child->set_parent(parent->get_parent(), parent->get_opcode()); - return child; -} template static InstrList<1 << CodeField::size, TO>* new_list(const CodeField& func, InstrCaller* error_func = nullptr) @@ -500,403 +27,4 @@ template static InstrList<1 << CodeField::size, TO>* new_list(InstrList* parent, const CodeField& func, InstrCaller* error_func = nullptr) { return connect_list(parent, new InstrList<1 << CodeField::size, TO>(func, error_func)); -} - -template -class Instr0 : public InstrBase -{ - InstrList& m_list; - -public: - Instr0(InstrList* list, const wxString& name, - void (TO::*func)()) - : InstrBase(name, opcode, 0) - , m_list(*list) - { - m_list.set_instr(opcode, instr_bind(func), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode); - } - - u32 encode() const - { - return m_list.encode(opcode); - } - - u32 operator()() const - { - return encode(); - } -}; - -template -class Instr1 : public InstrBase -{ - InstrList& m_list; - -public: - Instr1(InstrList* list, const wxString& name, - void (TO::*func)(T1), - CodeFieldBase& arg_1) - : InstrBase(name, opcode, 1) - , m_list(*list) - { - m_args[0] = &arg_1; - - m_list.set_instr(opcode, instr_bind(func, arg_1), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode) | (*m_args[0])[args[0]]; - } - - u32 encode(T1 a1) const - { - return m_list.encode(opcode) | (*m_args[0])[a1]; - } - - u32 operator()(T1 a1) const - { - return encode(a1); - } -}; - -template -class Instr2 : public InstrBase -{ - InstrList& m_list; - -public: - Instr2(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2) - : InstrBase(name, opcode, 2) - , m_list(*list) - { - m_args[0] = &arg_1; - m_args[1] = &arg_2; - - m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode) | (*m_args[0])[args[0]] | (*m_args[1])[args[1]]; - } - - u32 encode(T1 a1, T2 a2) const - { - return m_list.encode(opcode) | (*m_args[0])[a1] | (*m_args[1])[a2]; - } - - u32 operator()(T1 a1, T2 a2) const - { - return encode(a1, a2); - } -}; - -template -class Instr3 : public InstrBase -{ - InstrList& m_list; - -public: - Instr3(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3) - : InstrBase(name, opcode, 3) - , m_list(*list) - { - m_args[0] = &arg_1; - m_args[1] = &arg_2; - m_args[2] = &arg_3; - - m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode) | (*m_args[0])[args[0]] | (*m_args[1])[args[1]] | (*m_args[2])[args[2]]; - } - - u32 encode(T1 a1, T2 a2, T3 a3) const - { - return m_list.encode(opcode) | (*m_args[0])[a1] | (*m_args[1])[a2] | (*m_args[2])[a3]; - } - - u32 operator()(T1 a1, T2 a2, T3 a3) const - { - return encode(a1, a2, a3); - } -}; - -template -class Instr4 : public InstrBase -{ - InstrList& m_list; - -public: - Instr4(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3, T4), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3, - CodeFieldBase& arg_4) - : InstrBase(name, opcode, 4) - , m_list(*list) - { - m_args[0] = &arg_1; - m_args[1] = &arg_2; - m_args[2] = &arg_3; - m_args[3] = &arg_4; - - m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3, arg_4), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode) | - (*m_args[0])[args[0]] | - (*m_args[1])[args[1]] | - (*m_args[2])[args[2]] | - (*m_args[3])[args[3]]; - } - - u32 encode(T1 a1, T2 a2, T3 a3, T4 a4) const - { - return m_list.encode(opcode) | - (*m_args[0])[a1] | - (*m_args[1])[a2] | - (*m_args[2])[a3] | - (*m_args[3])[a4]; - } - - u32 operator()(T1 a1, T2 a2, T3 a3, T4 a4) const - { - return encode(a1, a2, a3, a4); - } -}; - -template -class Instr5 : public InstrBase -{ - InstrList& m_list; - -public: - Instr5(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3, T4, T5), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3, - CodeFieldBase& arg_4, - CodeFieldBase& arg_5) - : InstrBase(name, opcode, 5) - , m_list(*list) - { - m_args[0] = &arg_1; - m_args[1] = &arg_2; - m_args[2] = &arg_3; - m_args[3] = &arg_4; - m_args[4] = &arg_5; - - m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3, arg_4, arg_5), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode) | - (*m_args[0])[args[0]] | - (*m_args[1])[args[1]] | - (*m_args[2])[args[2]] | - (*m_args[3])[args[3]] | - (*m_args[4])[args[4]]; - } - - u32 encode(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) const - { - return m_list.encode(opcode) | - (*m_args[0])[a1] | - (*m_args[1])[a2] | - (*m_args[2])[a3] | - (*m_args[3])[a4] | - (*m_args[4])[a5]; - } - - u32 operator()(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) const - { - return encode(a1, a2, a3, a4, a5); - } -}; - -template -class Instr6 : public InstrBase -{ - InstrList& m_list; - -public: - Instr6(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3, T4, T5, T6), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3, - CodeFieldBase& arg_4, - CodeFieldBase& arg_5, - CodeFieldBase& arg_6) - : InstrBase(name, opcode, 6) - , m_list(*list) - { - m_args[0] = &arg_1; - m_args[1] = &arg_2; - m_args[2] = &arg_3; - m_args[3] = &arg_4; - m_args[4] = &arg_5; - m_args[5] = &arg_6; - - m_list.set_instr(opcode, instr_bind(func, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6), this); - } - - virtual void decode(TO* op, u32 code) const - { - m_list.decode(op, opcode, code); - } - - virtual u32 encode(const Array& args) const - { - assert(args.GetCount() == m_args_count); - return m_list.encode(opcode) | - (*m_args[0])[args[0]] | - (*m_args[1])[args[1]] | - (*m_args[2])[args[2]] | - (*m_args[3])[args[3]] | - (*m_args[4])[args[4]] | - (*m_args[5])[args[5]]; - } - - u32 encode(T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T5 a6) const - { - return m_list.encode(opcode) | - (*m_args[0])[a1] | - (*m_args[1])[a2] | - (*m_args[2])[a3] | - (*m_args[3])[a4] | - (*m_args[4])[a5] | - (*m_args[5])[a6]; - } - - u32 operator()(T1 a1, T2 a2, T3 a3, T4 a4, T4 a5, T4 a6) const - { - return encode(a1, a2, a3, a4, a5, a6); - } -}; - -template -static Instr0& make_instr(InstrList* list, const wxString& name, void (TO::*func)()) -{ - return *new Instr0(list, name, func); -} - -template -static Instr1& make_instr(InstrList* list, const wxString& name, - void (TO::*func)(T1), - CodeFieldBase& arg_1) -{ - return *new Instr1(list, name, func, arg_1); -} - -template -static Instr2& make_instr(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2) -{ - return *new Instr2(list, name, func, arg_1, arg_2); -} - -template -static Instr3& make_instr(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3) -{ - return *new Instr3(list, name, func, arg_1, arg_2, arg_3); -} - -template -static Instr4& make_instr(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3, T4), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3, - CodeFieldBase& arg_4) -{ - return *new Instr4(list, name, func, arg_1, arg_2, arg_3, arg_4); -} - -template -static Instr5& make_instr(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3, T4, T5), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3, - CodeFieldBase& arg_4, - CodeFieldBase& arg_5) -{ - return *new Instr5(list, name, func, arg_1, arg_2, arg_3, arg_4, arg_5); -} - -template -static Instr6& make_instr(InstrList* list, const wxString& name, - void (TO::*func)(T1, T2, T3, T4, T5, T6), - CodeFieldBase& arg_1, - CodeFieldBase& arg_2, - CodeFieldBase& arg_3, - CodeFieldBase& arg_4, - CodeFieldBase& arg_5, - CodeFieldBase& arg_6) -{ - return *new Instr6(list, name, func, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6); } \ No newline at end of file diff --git a/rpcs3/Emu/Cell/PPCDisAsm.h b/rpcs3/Emu/Cell/PPCDisAsm.h index c3ca64fa25..40c56dda39 100644 --- a/rpcs3/Emu/Cell/PPCDisAsm.h +++ b/rpcs3/Emu/Cell/PPCDisAsm.h @@ -1,80 +1,18 @@ #pragma once +#include "Emu/CPU/CPUDisAsm.h" #include "Gui/DisAsmFrame.h" #include "Emu/Memory/Memory.h" -enum DisAsmModes -{ - DumpMode, - InterpreterMode, - NormalMode, - CompilerElfMode, -}; - -class PPC_DisAsm +class PPCDisAsm : public CPUDisAsm { protected: - DisAsmFrame* disasm_frame; - const DisAsmModes m_mode; - - virtual void Write(const wxString value) + PPCDisAsm(CPUDisAsmMode mode) : CPUDisAsm(mode) { - switch(m_mode) - { - case DumpMode: - { - wxString mem = wxString::Format("\t%08llx:\t", dump_pc); - for(u8 i=0; i < 4; ++i) - { - mem += wxString::Format("%02x", Memory.Read8(dump_pc + i)); - if(i < 3) mem += " "; - } - - last_opcode = mem + "\t" + value + "\n"; - } - break; - - case InterpreterMode: - { - last_opcode = wxString::Format("[%08llx] %02x %02x %02x %02x: %s", dump_pc, - Memory.Read8(offset + dump_pc), - Memory.Read8(offset + dump_pc + 1), - Memory.Read8(offset + dump_pc + 2), - Memory.Read8(offset + dump_pc + 3), value); - } - break; - - case CompilerElfMode: last_opcode = value + "\n"; break; - - default: if(disasm_frame) disasm_frame->AddLine(value); break; - } - } - -public: - wxString last_opcode; - u64 dump_pc; - u64 offset; - -protected: - PPC_DisAsm(PPCThread& cpu, DisAsmModes mode = NormalMode) - : m_mode(mode) - , disasm_frame(NULL) - , offset(0) - { - if(m_mode != NormalMode) return; - - disasm_frame = new DisAsmFrame(cpu); - disasm_frame->Show(); } virtual u32 DisAsmBranchTarget(const s32 imm)=0; - wxString FixOp(wxString op) - { - op.Append(' ', max(8 - op.Len(), 0)); - return op; - } - void DisAsm_V4(const wxString& op, u32 v0, u32 v1, u32 v2, u32 v3) { Write(wxString::Format("%s v%d,v%d,v%d,v%d", FixOp(op), v0, v1, v2, v3)); @@ -153,7 +91,7 @@ protected: } void DisAsm_F1_R2(const wxString& op, u32 f0, u32 r0, u32 r1) { - if(m_mode == CompilerElfMode) + if(m_mode == CPUDisAsm_CompilerElfMode) { Write(wxString::Format("%s f%d,r%d,r%d", FixOp(op), f0, r0, r1)); return; @@ -163,7 +101,7 @@ protected: } void DisAsm_F1_IMM_R1_RC(const wxString& op, u32 f0, s32 imm0, u32 r0, bool rc) { - if(m_mode == CompilerElfMode) + if(m_mode == CPUDisAsm_CompilerElfMode) { Write(wxString::Format("%s%s f%d,r%d,%d #%x", FixOp(op), rc ? "." : "", f0, r0, imm0, imm0)); return; @@ -241,7 +179,7 @@ protected: } void DisAsm_R2_IMM(const wxString& op, u32 r0, u32 r1, s32 imm0) { - if(m_mode == CompilerElfMode) + if(m_mode == CPUDisAsm_CompilerElfMode) { Write(wxString::Format("%s r%d,r%d,%d #%x", FixOp(op), r0, r1, imm0, imm0)); return; diff --git a/rpcs3/Emu/Cell/PPCInstrTable.h b/rpcs3/Emu/Cell/PPCInstrTable.h index 97f701b02d..79942b9305 100644 --- a/rpcs3/Emu/Cell/PPCInstrTable.h +++ b/rpcs3/Emu/Cell/PPCInstrTable.h @@ -1,16 +1,5 @@ #pragma once - -template __forceinline static T sign(const T value) -{ - static_assert(size > 0 && size < sizeof(T) * 8, "Bad size"); - static const T sub_value = T(1) << size; - if(value & (T(1) << (size - 1))) - { - return value - sub_value; - } - - return value; -} +#include "Emu/CPU/CPUInstrTable.h" enum CodeFieldType { @@ -22,27 +11,6 @@ enum CodeFieldType FIELD_BRANCH, }; -class CodeFieldBase -{ -public: - CodeFieldType m_type; - -public: - CodeFieldBase(CodeFieldType type = FIELD_IMM) : m_type(type) - { - } - - virtual u32 operator ()(u32 data) const=0; - virtual void operator()(u32& data, u32 value) const=0; - - virtual u32 operator[](u32 value) const - { - u32 result = 0; - (*this)(result, value); - return result; - } -}; - template class CodeField : public CodeFieldBase { diff --git a/rpcs3/Emu/Cell/PPCThread.cpp b/rpcs3/Emu/Cell/PPCThread.cpp index 938389ab5b..fb92104aa4 100644 --- a/rpcs3/Emu/Cell/PPCThread.cpp +++ b/rpcs3/Emu/Cell/PPCThread.cpp @@ -4,21 +4,17 @@ PPCThread* GetCurrentPPCThread() { - return (PPCThread*)GetCurrentNamedThread(); + CPUThread* thread = GetCurrentCPUThread(); + + if(!thread || (thread->GetType() != CPU_THREAD_PPU && thread->GetType() != CPU_THREAD_SPU && thread->GetType() != CPU_THREAD_RAW_SPU)) + { + throw wxString("GetCurrentPPCThread: bad thread"); + } + + return (PPCThread*)thread; } -PPCThread::PPCThread(PPCThreadType type) - : ThreadBase(true, "PPCThread") - , m_type(type) - , DisAsmFrame(nullptr) - , m_dec(nullptr) - , stack_size(0) - , stack_addr(0) - , m_prio(0) - , m_offset(0) - , m_sync_wait(false) - , m_wait_thread_id(-1) - , m_free_data(false) +PPCThread::PPCThread(CPUThreadType type) : CPUThread(type) { } @@ -27,323 +23,24 @@ PPCThread::~PPCThread() Close(); } -void PPCThread::Close() +void PPCThread::DoReset() { - if(IsAlive()) - { - m_free_data = true; - } - - if(DisAsmFrame) - { - DisAsmFrame->Close(); - DisAsmFrame = nullptr; - } - - Stop(); -} - -void PPCThread::Reset() -{ - CloseStack(); - - m_sync_wait = 0; - m_wait_thread_id = -1; memset(m_args, 0, sizeof(u64) * 4); - - SetPc(0); - cycle = 0; - - isBranch = false; - - m_status = Stopped; - m_error = 0; - - DoReset(); } void PPCThread::InitStack() { - if(stack_addr) return; - if(stack_size == 0) stack_size = 0x10000; - stack_addr = Memory.StackMem.Alloc(Memory.AlignAddr(stack_size, 0x100)); + if(m_stack_addr) return; + if(m_stack_size == 0) m_stack_size = 0x10000; + m_stack_addr = Memory.StackMem.Alloc(Memory.AlignAddr(m_stack_size, 0x100)); - stack_point = stack_addr + stack_size; + m_stack_point = m_stack_addr + m_stack_size; /* - stack_point += stack_size - 0x10; - stack_point &= -0x10; - Memory.Write64(stack_point, 0); - stack_point -= 0x60; - Memory.Write64(stack_point, stack_point + 0x60); + m_stack_point += m_stack_size - 0x10; + m_stack_point &= -0x10; + Memory.Write64(m_stack_point, 0); + m_stack_point -= 0x60; + Memory.Write64(m_stack_point, m_stack_point + 0x60); */ - if(wxFileExists("stack.dat")) - { - ConLog.Warning("loading stack.dat..."); - wxFile stack("stack.dat"); - stack.Read(Memory.GetMemFromAddr(stack_addr), 0x10000); - stack.Close(); - } } -void PPCThread::CloseStack() -{ - Memory.Free(stack_addr); - stack_addr = 0; - stack_size = 0; -} - -void PPCThread::SetId(const u32 id) -{ - m_id = id; -} - -void PPCThread::SetName(const wxString& name) -{ - m_name = name; -} - -void PPCThread::Wait(bool wait) -{ - wxCriticalSectionLocker lock(m_cs_sync); - m_sync_wait = wait; -} - -void PPCThread::Wait(const PPCThread& thr) -{ - wxCriticalSectionLocker lock(m_cs_sync); - m_wait_thread_id = thr.GetId(); - m_sync_wait = true; -} - -bool PPCThread::Sync() -{ - wxCriticalSectionLocker lock(m_cs_sync); - - return m_sync_wait; -} - -int PPCThread::ThreadStatus() -{ - if(Emu.IsStopped()) - { - return PPCThread_Stopped; - } - - if(TestDestroy()) - { - return PPCThread_Break; - } - - if(Emu.IsPaused() || Sync()) - { - return PPCThread_Sleeping; - } - - return PPCThread_Running; -} - -void PPCThread::NextBranchPc() -{ - SetPc(nPC); -} - -void PPCThread::NextPc() -{ - if(isBranch) - { - NextBranchPc(); - isBranch = false; - return; - } - - SetPc(PC + 4); -} - -void PPCThread::PrevPc() -{ - SetPc(PC - 4); -} - -void PPCThread::SetPc(const u64 pc) -{ - PC = pc; - nPC = PC + 4; -} - -void PPCThread::SetEntry(const u64 pc) -{ - entry = pc; -} - -void PPCThread::SetBranch(const u64 pc) -{ - if(!Memory.IsGoodAddr(m_offset + pc)) - { - ConLog.Error("%s branch error: bad address 0x%llx #pc: 0x%llx", GetFName(), m_offset+ pc, m_offset + PC); - Emu.Pause(); - } - nPC = pc; - isBranch = true; -} - -void PPCThread::SetError(const u32 error) -{ - if(error == 0) - { - m_error = 0; - } - else - { - m_error |= error; - } -} - -wxArrayString PPCThread::ErrorToString(const u32 error) -{ - wxArrayString earr; - - if(error == 0) return earr; - - earr.Add("Unknown error"); - - return earr; -} - -void PPCThread::Run() -{ - if(IsRunning()) Stop(); - if(IsPaused()) - { - Resume(); - return; - } - - wxGetApp().SendDbgCommand(DID_START_THREAD, this); - - m_status = Running; - - SetPc(entry); - InitStack(); - InitRegs(); - DoRun(); - Emu.CheckStatus(); - - wxGetApp().SendDbgCommand(DID_STARTED_THREAD, this); -} - -void PPCThread::Resume() -{ - if(!IsPaused()) return; - - wxGetApp().SendDbgCommand(DID_RESUME_THREAD, this); - - m_status = Running; - DoResume(); - Emu.CheckStatus(); - - ThreadBase::Start(); - - wxGetApp().SendDbgCommand(DID_RESUMED_THREAD, this); -} - -void PPCThread::Pause() -{ - if(!IsRunning()) return; - - wxGetApp().SendDbgCommand(DID_PAUSE_THREAD, this); - - m_status = Paused; - DoPause(); - Emu.CheckStatus(); - - ThreadBase::Stop(false); - wxGetApp().SendDbgCommand(DID_PAUSED_THREAD, this); -} - -void PPCThread::Stop() -{ - if(IsStopped()) return; - - wxGetApp().SendDbgCommand(DID_STOP_THREAD, this); - - m_status = Stopped; - ThreadBase::Stop(false); - Reset(); - DoStop(); - Emu.CheckStatus(); - - wxGetApp().SendDbgCommand(DID_STOPED_THREAD, this); -} - -void PPCThread::Exec() -{ - wxGetApp().SendDbgCommand(DID_EXEC_THREAD, this); - ThreadBase::Start(); - //std::thread thr(std::bind(std::mem_fn(&PPCThread::Task), this)); -} - -void PPCThread::ExecOnce() -{ - DoCode(Memory.Read32(m_offset + PC)); - NextPc(); -} - -void PPCThread::Task() -{ - //ConLog.Write("%s enter", PPCThread::GetFName()); - - const Array& bp = Emu.GetBreakPoints(); - - try - { - for(uint i=0; i argv_addr; - u64 m_offset; - u32 m_exit_status; - bool m_free_data; + Array m_argv_addr; public: - u64 stack_size; - u64 stack_addr; - u64 stack_point; - virtual void InitRegs()=0; - virtual void InitStack(); - virtual void CloseStack(); - - virtual u64 GetStackAddr() const { return stack_addr; } - virtual u64 GetStackSize() const { return stack_size; } - virtual u64 GetFreeStackSize() const=0; - void SetArg(const uint pos, const u64 arg) { assert(pos < 4); m_args[pos] = arg; } - - void SetId(const u32 id); - void SetName(const wxString& name); - void SetPrio(const u64 prio) { m_prio = prio; } - void SetOffset(const u64 offset) { m_offset = offset; } - void SetExitStatus(const u32 status) { m_exit_status = status; } - - u64 GetOffset() const { return m_offset; } - u32 GetExitStatus() const { return m_exit_status; } - u64 GetPrio() const { return m_prio; } - wxString GetName() const { return m_name; } - wxString GetFName() const - { - return - wxString::Format("%s[%d] Thread%s", - GetTypeString(), - m_id, - (GetName().IsEmpty() ? "" : " (" + GetName() + ")") - ); - } - - static wxString PPCThreadTypeToString(PPCThreadType type) - { - switch(type) - { - case PPC_THREAD_PPU: return "PPU"; - case PPC_THREAD_SPU: return "SPU"; - case PPC_THREAD_RAW_SPU: return "RawSPU"; - } - - return "Unknown"; - } - - wxString GetTypeString() const { return PPCThreadTypeToString(m_type); } + virtual void SetArg(const uint pos, const u64 arg) { assert(pos < 4); m_args[pos] = arg; } virtual wxString GetThreadName() const { return GetFName() + wxString::Format("[0x%08llx]", PC); } -public: - bool isBranch; - - u64 entry; - u64 PC; - u64 nPC; - u64 cycle; - protected: - PPCThread(PPCThreadType type); + PPCThread(CPUThreadType type); public: ~PPCThread(); - u32 m_wait_thread_id; - - wxCriticalSection m_cs_sync; - bool m_sync_wait; - void Wait(bool wait); - void Wait(const PPCThread& thr); - bool Sync(); - - template - void WaitFor(T func) - { - while(func(ThreadStatus())) - { - Sleep(1); - } - } - - int ThreadStatus(); - - void NextPc(); - void NextBranchPc(); - void PrevPc(); - void SetBranch(const u64 pc); - void SetPc(const u64 pc); - void SetEntry(const u64 entry); - - void SetError(const u32 error); - - static wxArrayString ErrorToString(const u32 error); - wxArrayString ErrorToString() { return ErrorToString(m_error); } - - bool IsOk() const { return m_error == 0; } - bool IsRunning() const { return m_status == Running; } - bool IsPaused() const { return m_status == Paused; } - bool IsStopped() const { return m_status == Stopped; } - - bool IsJoinable() const { return m_joinable; } - bool IsJoining() const { return m_joining; } - void SetJoinable(bool joinable) { m_joinable = joinable; } - void SetJoining(bool joining) { m_joining = joining; } - - u32 GetError() const { return m_error; } - u32 GetId() const { return m_id; } - PPCThreadType GetType() const { return m_type; } - - void Reset(); - void Close(); - void Run(); - void Pause(); - void Resume(); - void Stop(); - - virtual wxString RegsToString() { return wxEmptyString; } - virtual wxString ReadRegString(wxString reg) { return wxEmptyString; } - virtual bool WriteRegString(wxString reg, wxString value) { return false; } - - virtual void Exec(); - void ExecOnce(); - - virtual void AddArgv(const wxString& arg) {} - protected: - virtual void DoReset()=0; - virtual void DoRun()=0; - virtual void DoPause()=0; - virtual void DoResume()=0; - virtual void DoStop()=0; - -public: - virtual void Task(); - -private: - virtual void DoCode(const s32 code)=0; + virtual void DoReset() override; }; PPCThread* GetCurrentPPCThread(); \ No newline at end of file diff --git a/rpcs3/Emu/Cell/PPUDecoder.h b/rpcs3/Emu/Cell/PPUDecoder.h index cff3d3ec7a..d5973edb6a 100644 --- a/rpcs3/Emu/Cell/PPUDecoder.h +++ b/rpcs3/Emu/Cell/PPUDecoder.h @@ -4,18 +4,17 @@ #include "Emu/Cell/PPCDecoder.h" #include "PPUInstrTable.h" -class PPU_Decoder : public PPC_Decoder +class PPUDecoder : public PPCDecoder { - PPU_Opcodes* m_op; + PPUOpcodes* m_op; public: - PPU_Decoder(PPU_Opcodes& op) : m_op(&op) + PPUDecoder(PPUOpcodes& op) : m_op(&op) { } - ~PPU_Decoder() + ~PPUDecoder() { - m_op->Exit(); delete m_op; } diff --git a/rpcs3/Emu/Cell/PPUDisAsm.h b/rpcs3/Emu/Cell/PPUDisAsm.h index 2ac75b274e..458a578b3c 100644 --- a/rpcs3/Emu/Cell/PPUDisAsm.h +++ b/rpcs3/Emu/Cell/PPUDisAsm.h @@ -6,41 +6,243 @@ #include "Gui/DisAsmFrame.h" #include "Emu/Memory/Memory.h" -class PPU_DisAsm - : public PPU_Opcodes - , public PPC_DisAsm +class PPUDisAsm + : public PPUOpcodes + , public PPCDisAsm { public: - PPCThread& CPU; - - PPU_DisAsm() - : PPC_DisAsm(*(PPCThread*)NULL, DumpMode) - , CPU(*(PPCThread*)NULL) - { - } - - PPU_DisAsm(PPCThread& cpu, DisAsmModes mode = NormalMode) - : PPC_DisAsm(cpu, mode) - , CPU(cpu) - { - } - - ~PPU_DisAsm() + PPUDisAsm(CPUDisAsmMode mode) : PPCDisAsm(mode) { } private: - void Exit() - { - if(m_mode == NormalMode && !disasm_frame->exit) - { - disasm_frame->Close(); - } - } - u32 DisAsmBranchTarget(const s32 imm) { - return branchTarget(m_mode == NormalMode ? CPU.PC : dump_pc, imm); + return branchTarget(dump_pc, imm); + } + +private: + void DisAsm_V4(const wxString& op, u32 v0, u32 v1, u32 v2, u32 v3) + { + Write(wxString::Format("%s v%d,v%d,v%d,v%d", FixOp(op), v0, v1, v2, v3)); + } + void DisAsm_V3_UIMM(const wxString& op, u32 v0, u32 v1, u32 v2, u32 uimm) + { + Write(wxString::Format("%s v%d,v%d,v%d,%u #%x", FixOp(op), v0, v1, v2, uimm, uimm)); + } + void DisAsm_V3(const wxString& op, u32 v0, u32 v1, u32 v2) + { + Write(wxString::Format("%s v%d,v%d,v%d", FixOp(op), v0, v1, v2)); + } + void DisAsm_V2_UIMM(const wxString& op, u32 v0, u32 v1, u32 uimm) + { + Write(wxString::Format("%s v%d,v%d,%u #%x", FixOp(op), v0, v1, uimm, uimm)); + } + void DisAsm_V2(const wxString& op, u32 v0, u32 v1) + { + Write(wxString::Format("%s v%d,v%d", FixOp(op), v0, v1)); + } + void DisAsm_V1_SIMM(const wxString& op, u32 v0, s32 simm) + { + Write(wxString::Format("%s v%d,%d #%x", FixOp(op), v0, simm, simm)); + } + void DisAsm_V1(const wxString& op, u32 v0) + { + Write(wxString::Format("%s v%d", FixOp(op), v0)); + } + void DisAsm_V1_R2(const wxString& op, u32 v0, u32 r1, u32 r2) + { + Write(wxString::Format("%s v%d,r%d,r%d", FixOp(op), v0, r1, r2)); + } + void DisAsm_CR1_F2_RC(const wxString& op, u32 cr0, u32 f0, u32 f1, bool rc) + { + Write(wxString::Format("%s%s cr%d,f%d,f%d", FixOp(op), rc ? "." : "", cr0, f0, f1)); + } + void DisAsm_CR1_F2(const wxString& op, u32 cr0, u32 f0, u32 f1) + { + DisAsm_CR1_F2_RC(op, cr0, f0, f1, false); + } + void DisAsm_INT1_R2(const wxString& op, u32 i0, u32 r0, u32 r1) + { + Write(wxString::Format("%s %d,r%d,r%d", FixOp(op), i0, r0, r1)); + } + void DisAsm_INT1_R1_IMM(const wxString& op, u32 i0, u32 r0, s32 imm0) + { + Write(wxString::Format("%s %d,r%d,%d #%x", FixOp(op), i0, r0, imm0, imm0)); + } + void DisAsm_INT1_R1_RC(const wxString& op, u32 i0, u32 r0, bool rc) + { + Write(wxString::Format("%s%s %d,r%d", FixOp(op), rc ? "." : "", i0, r0)); + } + void DisAsm_INT1_R1(const wxString& op, u32 i0, u32 r0) + { + DisAsm_INT1_R1_RC(op, i0, r0, false); + } + void DisAsm_F4_RC(const wxString& op, u32 f0, u32 f1, u32 f2, u32 f3, bool rc) + { + Write(wxString::Format("%s%s f%d,f%d,f%d,f%d", FixOp(op), rc ? "." : "", f0, f1, f2, f3)); + } + void DisAsm_F3_RC(const wxString& op, u32 f0, u32 f1, u32 f2, bool rc) + { + Write(wxString::Format("%s%s f%d,f%d,f%d", FixOp(op), rc ? "." : "", f0, f1, f2)); + } + void DisAsm_F3(const wxString& op, u32 f0, u32 f1, u32 f2) + { + DisAsm_F3_RC(op, f0, f1, f2, false); + } + void DisAsm_F2_RC(const wxString& op, u32 f0, u32 f1, bool rc) + { + Write(wxString::Format("%s%s f%d,f%d", FixOp(op), rc ? "." : "", f0, f1)); + } + void DisAsm_F2(const wxString& op, u32 f0, u32 f1) + { + DisAsm_F2_RC(op, f0, f1, false); + } + void DisAsm_F1_R2(const wxString& op, u32 f0, u32 r0, u32 r1) + { + if(m_mode == CPUDisAsm_CompilerElfMode) + { + Write(wxString::Format("%s f%d,r%d,r%d", FixOp(op), f0, r0, r1)); + return; + } + + Write(wxString::Format("%s f%d,r%d(r%d)", FixOp(op), f0, r0, r1)); + } + void DisAsm_F1_IMM_R1_RC(const wxString& op, u32 f0, s32 imm0, u32 r0, bool rc) + { + if(m_mode == CPUDisAsm_CompilerElfMode) + { + Write(wxString::Format("%s%s f%d,r%d,%d #%x", FixOp(op), rc ? "." : "", f0, r0, imm0, imm0)); + return; + } + + Write(wxString::Format("%s%s f%d,%d(r%d) #%x", FixOp(op), rc ? "." : "", f0, imm0, r0, imm0)); + } + void DisAsm_F1_IMM_R1(const wxString& op, u32 f0, s32 imm0, u32 r0) + { + DisAsm_F1_IMM_R1_RC(op, f0, imm0, r0, false); + } + void DisAsm_F1_RC(const wxString& op, u32 f0, bool rc) + { + Write(wxString::Format("%s%s f%d", FixOp(op), rc ? "." : "", f0)); + } + void DisAsm_R1_RC(const wxString& op, u32 r0, bool rc) + { + Write(wxString::Format("%s%s r%d", FixOp(op), rc ? "." : "", r0)); + } + void DisAsm_R1(const wxString& op, u32 r0) + { + DisAsm_R1_RC(op, r0, false); + } + void DisAsm_R2_OE_RC(const wxString& op, u32 r0, u32 r1, u32 oe, bool rc) + { + Write(wxString::Format("%s%s%s r%d,r%d", FixOp(op), oe ? "o" : "", rc ? "." : "", r0, r1)); + } + void DisAsm_R2_RC(const wxString& op, u32 r0, u32 r1, bool rc) + { + DisAsm_R2_OE_RC(op, r0, r1, false, rc); + } + void DisAsm_R2(const wxString& op, u32 r0, u32 r1) + { + DisAsm_R2_RC(op, r0, r1, false); + } + void DisAsm_R3_OE_RC(const wxString& op, u32 r0, u32 r1, u32 r2, u32 oe, bool rc) + { + Write(wxString::Format("%s%s%s r%d,r%d,r%d", FixOp(op), oe ? "o" : "", rc ? "." : "", r0, r1, r2)); + } + void DisAsm_R3_INT2_RC(const wxString& op, u32 r0, u32 r1, u32 r2, s32 i0, s32 i1, bool rc) + { + Write(wxString::Format("%s%s r%d,r%d,r%d,%d,%d", FixOp(op), rc ? "." : "", r0, r1, r2, i0, i1)); + } + void DisAsm_R3_RC(const wxString& op, u32 r0, u32 r1, u32 r2, bool rc) + { + DisAsm_R3_OE_RC(op, r0, r1, r2, false, rc); + } + void DisAsm_R3(const wxString& op, u32 r0, u32 r1, u32 r2) + { + DisAsm_R3_RC(op, r0, r1, r2, false); + } + void DisAsm_R2_INT3_RC(const wxString& op, u32 r0, u32 r1, s32 i0, s32 i1, s32 i2, bool rc) + { + Write(wxString::Format("%s%s r%d,r%d,%d,%d,%d", FixOp(op), rc ? "." : "", r0, r1, i0, i1, i2)); + } + void DisAsm_R2_INT3(const wxString& op, u32 r0, u32 r1, s32 i0, s32 i1, s32 i2) + { + DisAsm_R2_INT3_RC(op, r0, r1, i0, i1, i2, false); + } + void DisAsm_R2_INT2_RC(const wxString& op, u32 r0, u32 r1, s32 i0, s32 i1, bool rc) + { + Write(wxString::Format("%s%s r%d,r%d,%d,%d", FixOp(op), rc ? "." : "", r0, r1, i0, i1)); + } + void DisAsm_R2_INT2(const wxString& op, u32 r0, u32 r1, s32 i0, s32 i1) + { + DisAsm_R2_INT2_RC(op, r0, r1, i0, i1, false); + } + void DisAsm_R2_INT1_RC(const wxString& op, u32 r0, u32 r1, s32 i0, bool rc) + { + Write(wxString::Format("%s%s r%d,r%d,%d", FixOp(op), rc ? "." : "", r0, r1, i0)); + } + void DisAsm_R2_INT1(const wxString& op, u32 r0, u32 r1, s32 i0) + { + DisAsm_R2_INT1_RC(op, r0, r1, i0, false); + } + void DisAsm_R2_IMM(const wxString& op, u32 r0, u32 r1, s32 imm0) + { + if(m_mode == CPUDisAsm_CompilerElfMode) + { + Write(wxString::Format("%s r%d,r%d,%d #%x", FixOp(op), r0, r1, imm0, imm0)); + return; + } + + Write(wxString::Format("%s r%d,%d(r%d) #%x", FixOp(op), r0, imm0, r1, imm0)); + } + void DisAsm_R1_IMM(const wxString& op, u32 r0, s32 imm0) + { + Write(wxString::Format("%s r%d,%d #%x", FixOp(op), r0, imm0, imm0)); + } + void DisAsm_IMM_R1(const wxString& op, s32 imm0, u32 r0) + { + Write(wxString::Format("%s %d,r%d #%x", FixOp(op), imm0, r0, imm0)); + } + void DisAsm_CR1_R1_IMM(const wxString& op, u32 cr0, u32 r0, s32 imm0) + { + Write(wxString::Format("%s cr%d,r%d,%d #%x", FixOp(op), cr0, r0, imm0, imm0)); + } + void DisAsm_CR1_R2_RC(const wxString& op, u32 cr0, u32 r0, u32 r1, bool rc) + { + Write(wxString::Format("%s%s cr%d,r%d,r%d", FixOp(op), rc ? "." : "", cr0, r0, r1)); + } + void DisAsm_CR1_R2(const wxString& op, u32 cr0, u32 r0, u32 r1) + { + DisAsm_CR1_R2_RC(op, cr0, r0, r1, false); + } + void DisAsm_CR2(const wxString& op, u32 cr0, u32 cr1) + { + Write(wxString::Format("%s cr%d,cr%d", FixOp(op), cr0, cr1)); + } + void DisAsm_INT3(const wxString& op, const int i0, const int i1, const int i2) + { + Write(wxString::Format("%s %d,%d,%d", FixOp(op), i0, i1, i2)); + } + void DisAsm_INT1(const wxString& op, const int i0) + { + Write(wxString::Format("%s %d", FixOp(op), i0)); + } + void DisAsm_BRANCH(const wxString& op, const int pc) + { + Write(wxString::Format("%s 0x%x", FixOp(op), DisAsmBranchTarget(pc))); + } + void DisAsm_BRANCH_A(const wxString& op, const int pc) + { + Write(wxString::Format("%s 0x%x", FixOp(op), pc)); + } + void DisAsm_B2_BRANCH(const wxString& op, u32 b0, u32 b1, const int pc) + { + Write(wxString::Format("%s %d,%d,0x%x ", FixOp(op), b0, b1, DisAsmBranchTarget(pc))); + } + void DisAsm_CR_BRANCH(const wxString& op, u32 cr, const int pc) + { + Write(wxString::Format("%s cr%d,0x%x ", FixOp(op), cr, DisAsmBranchTarget(pc))); } private: @@ -738,7 +940,7 @@ private: } void BC(u32 bo, u32 bi, s32 bd, u32 aa, u32 lk) { - if(m_mode == CompilerElfMode) + if(m_mode == CPUDisAsm_CompilerElfMode) { Write(wxString::Format("bc 0x%x, 0x%x, 0x%x, %d, %d", bo, bi, bd, aa, lk)); return; @@ -844,7 +1046,7 @@ private: } void B(s32 ll, u32 aa, u32 lk) { - if(m_mode == CompilerElfMode) + if(m_mode == CPUDisAsm_CompilerElfMode) { Write(wxString::Format("b 0x%x, %d, %d", ll, aa, lk)); return; diff --git a/rpcs3/Emu/Cell/PPUInstrTable.h b/rpcs3/Emu/Cell/PPUInstrTable.h index 82f3a6bc2a..ea524f4827 100644 --- a/rpcs3/Emu/Cell/PPUInstrTable.h +++ b/rpcs3/Emu/Cell/PPUInstrTable.h @@ -203,20 +203,20 @@ namespace PPU_instr static CodeField<9, 10> STRM; - static auto main_list = new_list(OPCD, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, OPCD)); + static auto main_list = new_list(OPCD, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, OPCD)); static auto g04_list = new_list(main_list, PPU_opcodes::G_04, GD_04); - static auto g04_0_list = new_list(g04_list, GD_04_0, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_04_0)); - static auto g13_list = new_list(main_list, PPU_opcodes::G_13, GD_13, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_13)); - static auto g1e_list = new_list(main_list, PPU_opcodes::G_1e, GD_1e, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_1e)); - static auto g1f_list = new_list(main_list, PPU_opcodes::G_1f, GD_1f, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_1f)); - static auto g3a_list = new_list(main_list, PPU_opcodes::G_3a, GD_3a, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_3a)); - static auto g3b_list = new_list(main_list, PPU_opcodes::G_3b, GD_3b, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_3b)); - static auto g3e_list = new_list(main_list, PPU_opcodes::G_3e, GD_3e, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_3e)); + static auto g04_0_list = new_list(g04_list, GD_04_0, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_04_0)); + static auto g13_list = new_list(main_list, PPU_opcodes::G_13, GD_13, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_13)); + static auto g1e_list = new_list(main_list, PPU_opcodes::G_1e, GD_1e, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_1e)); + static auto g1f_list = new_list(main_list, PPU_opcodes::G_1f, GD_1f, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_1f)); + static auto g3a_list = new_list(main_list, PPU_opcodes::G_3a, GD_3a, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_3a)); + static auto g3b_list = new_list(main_list, PPU_opcodes::G_3b, GD_3b, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_3b)); + static auto g3e_list = new_list(main_list, PPU_opcodes::G_3e, GD_3e, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_3e)); static auto g3f_list = new_list(main_list, PPU_opcodes::G_3f, GD_3f); - static auto g3f_0_list = new_list(g3f_list, GD_3f_0, instr_bind(&PPU_Opcodes::UNK, GetCode, OPCD, GD_3f_0)); + static auto g3f_0_list = new_list(g3f_list, GD_3f_0, instr_bind(&PPUOpcodes::UNK, GetCode, OPCD, GD_3f_0)); #define bind_instr(list, name, ...) \ - static const auto& name = make_instr(list, #name, &PPU_Opcodes::name, ##__VA_ARGS__) + static const auto& name = make_instr(list, #name, &PPUOpcodes::name, ##__VA_ARGS__) bind_instr(main_list, TDI, TO, RA, simm16); bind_instr(main_list, TWI, TO, RA, simm16); diff --git a/rpcs3/Emu/Cell/PPUInterpreter.h b/rpcs3/Emu/Cell/PPUInterpreter.h index ce08c505fc..604b3dd033 100644 --- a/rpcs3/Emu/Cell/PPUInterpreter.h +++ b/rpcs3/Emu/Cell/PPUInterpreter.h @@ -45,13 +45,13 @@ u64 rotr64(const u64 x, const u8 n) { return (x >> n) | (x << (64 - n)); } #define rotl64 _rotl64 #define rotr64 _rotr64 -class PPU_Interpreter : public PPU_Opcodes +class PPUInterpreter : public PPUOpcodes { private: PPUThread& CPU; public: - PPU_Interpreter(PPUThread& cpu) : CPU(cpu) + PPUInterpreter(PPUThread& cpu) : CPU(cpu) { InitRotateMask(); } @@ -61,7 +61,7 @@ private: void SysCall() { - CPU.DoSyscall(CPU.GPR[11]); + SysCalls::DoSyscall(CPU.GPR[11]); if(enable_log) ConLog.Warning("SysCall[%lld] done with code [0x%llx]! #pc: 0x%llx", CPU.GPR[11], CPU.GPR[3], CPU.PC); diff --git a/rpcs3/Emu/Cell/PPUOpcodes.h b/rpcs3/Emu/Cell/PPUOpcodes.h index 21e5fbf7c3..2f10abcfa1 100644 --- a/rpcs3/Emu/Cell/PPUOpcodes.h +++ b/rpcs3/Emu/Cell/PPUOpcodes.h @@ -428,11 +428,9 @@ namespace PPU_opcodes }; } -class PPU_Opcodes +class PPUOpcodes { public: - virtual void Exit()=0; - static u64 branchTarget(const u64 pc, const u64 imm) { return pc + (imm & ~0x3ULL); diff --git a/rpcs3/Emu/Cell/PPUProgramCompiler.cpp b/rpcs3/Emu/Cell/PPUProgramCompiler.cpp index c645a2cf7f..60c5d860c5 100644 --- a/rpcs3/Emu/Cell/PPUProgramCompiler.cpp +++ b/rpcs3/Emu/Cell/PPUProgramCompiler.cpp @@ -362,7 +362,7 @@ void CompilePPUProgram::DetectArgInfo(Arg& arg) return; } - if(GetInstruction(str)) + if(GetInstruction(str)) { arg.type = ARG_INSTR; return; @@ -1397,17 +1397,9 @@ void CompilePPUProgram::Compile() LoadArgs(); - auto instr = GetInstruction(op); + auto instr = GetInstruction(op); if(instr) { - /* - FIELD_IMM, - FIELD_R_GPR, - FIELD_R_FPR, - FIELD_R_VPR, - FIELD_R_CR, - FIELD_BRANCH, - */ uint type[] = { ARG_IMM, diff --git a/rpcs3/Emu/Cell/PPUThread.cpp b/rpcs3/Emu/Cell/PPUThread.cpp index 2f329f4b16..c939c403b6 100644 --- a/rpcs3/Emu/Cell/PPUThread.cpp +++ b/rpcs3/Emu/Cell/PPUThread.cpp @@ -10,14 +10,12 @@ PPUThread& GetCurrentPPUThread() { PPCThread* thread = GetCurrentPPCThread(); - if(!thread || thread->GetType() != PPC_THREAD_PPU) throw wxString("GetCurrentPPUThread: bad thread"); + if(!thread || thread->GetType() != CPU_THREAD_PPU) throw wxString("GetCurrentPPUThread: bad thread"); return *(PPUThread*)thread; } -PPUThread::PPUThread() - : PPCThread(PPC_THREAD_PPU) - , SysCalls(*this) +PPUThread::PPUThread() : PPCThread(CPU_THREAD_PPU) { Reset(); } @@ -29,6 +27,8 @@ PPUThread::~PPUThread() void PPUThread::DoReset() { + PPCThread::DoReset(); + //reset regs memset(VPR, 0, sizeof(VPR)); memset(FPR, 0, sizeof(FPR)); @@ -52,10 +52,10 @@ void PPUThread::DoReset() void PPUThread::AddArgv(const wxString& arg) { - stack_point -= arg.Len() + 1; - stack_point = Memory.AlignAddr(stack_point, 0x10) - 0x10; - argv_addr.AddCpy(stack_point); - Memory.WriteString(stack_point, arg); + m_stack_point -= arg.Len() + 1; + m_stack_point = Memory.AlignAddr(m_stack_point, 0x10) - 0x10; + m_argv_addr.AddCpy(m_stack_point); + Memory.WriteString(m_stack_point, arg); } void PPUThread::InitRegs() @@ -88,9 +88,9 @@ void PPUThread::InitRegs() } */ - stack_point = Memory.AlignAddr(stack_point, 0x200) - 0x200; + m_stack_point = Memory.AlignAddr(m_stack_point, 0x200) - 0x200; - GPR[1] = stack_point; + GPR[1] = m_stack_point; GPR[2] = rtoc; for(int i=4; i<32; ++i) @@ -99,14 +99,14 @@ void PPUThread::InitRegs() GPR[i] = (i+1) * 0x10000; } - if(argv_addr.GetCount()) + if(m_argv_addr.GetCount()) { - u64 argc = argv_addr.GetCount(); - stack_point -= 0xc + 4 * argc; - u64 argv = stack_point; + u64 argc = m_argv_addr.GetCount(); + m_stack_point -= 0xc + 4 * argc; + u64 argv = m_stack_point; mem64_ptr_t argv_list(argv); - for(int i=0; i 220) - { - cycle = 0; - TB++; - } - - m_dec->Decode(code); -} - bool FPRdouble::IsINF(PPCdouble d) { return ((u64&)d & 0x7FFFFFFFFFFFFFFFULL) == 0x7FF0000000000000ULL; diff --git a/rpcs3/Emu/Cell/PPUThread.h b/rpcs3/Emu/Cell/PPUThread.h index 49baf84edf..2505631ca7 100644 --- a/rpcs3/Emu/Cell/PPUThread.h +++ b/rpcs3/Emu/Cell/PPUThread.h @@ -511,9 +511,7 @@ union VPR_reg static const s32 MAX_INT_VALUE = 0x7fffffff; -class PPUThread - : public PPCThread - , public SysCalls +class PPUThread : public PPCThread { public: PPCdouble FPR[32]; //Floating Point Register @@ -727,7 +725,7 @@ public: virtual wxString RegsToString() { - wxString ret = PPCThread::RegsToString(); + wxString ret; for(uint i=0; i<32; ++i) ret += wxString::Format("GPR[%d] = 0x%llx\n", i, GPR[i]); for(uint i=0; i<32; ++i) ret += wxString::Format("FPR[%d] = %.6G\n", i, FPR[i]); @@ -768,6 +766,7 @@ public: if (reg == "CTR") return wxString::Format("%016llx", CTR); if (reg == "XER") return wxString::Format("%016llx", XER); if (reg == "FPSCR") return wxString::Format("%08x", FPSCR); + return wxEmptyString; } @@ -828,9 +827,6 @@ protected: virtual void DoPause(); virtual void DoResume(); virtual void DoStop(); - -public: - virtual void DoCode(const s32 code); }; PPUThread& GetCurrentPPUThread(); \ No newline at end of file diff --git a/rpcs3/Emu/Cell/RawSPUThread.cpp b/rpcs3/Emu/Cell/RawSPUThread.cpp index 370550cea7..6cf6b212f8 100644 --- a/rpcs3/Emu/Cell/RawSPUThread.cpp +++ b/rpcs3/Emu/Cell/RawSPUThread.cpp @@ -1,51 +1,259 @@ #include "stdafx.h" #include "Emu/Cell/RawSPUThread.h" -RawSPUThread::RawSPUThread(PPCThreadType type) : SPUThread(type) +RawSPUThread::RawSPUThread(u32 index, CPUThreadType type) + : SPUThread(type) + , m_index(index) { + Memory.MemoryBlocks.Add(MemoryBlock::SetRange(RAW_SPU_BASE_ADDR + RAW_SPU_OFFSET * index, RAW_SPU_OFFSET)); Reset(); } RawSPUThread::~RawSPUThread() { + MemoryBlock::Delete(); +} + +bool RawSPUThread::Read8(const u64 addr, u8* value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Read8(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Read8(0x%x)", m_index, offset); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Read16(const u64 addr, u16* value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Read16(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Read16(0x%x)", m_index, offset); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Read32(const u64 addr, u32* value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Read32(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + switch(offset) + { + case MFC_LSA_offs: ConLog.Warning("RawSPUThread[%d]: Read32(MFC_LSA)", m_index); *value = MFC.LSA.GetValue(); break; + case MFC_EAH_offs: ConLog.Warning("RawSPUThread[%d]: Read32(MFC_EAH)", m_index); *value = MFC.EAH.GetValue(); break; + case MFC_EAL_offs: ConLog.Warning("RawSPUThread[%d]: Read32(MFC_EAL)", m_index); *value = MFC.EAL.GetValue(); break; + case MFC_Size_Tag_offs: ConLog.Warning("RawSPUThread[%d]: Read32(MFC_Size_Tag)", m_index); *value = MFC.Size_Tag.GetValue(); break; + case MFC_CMDStatus_offs: ConLog.Warning("RawSPUThread[%d]: Read32(MFC_CMDStatus)", m_index); *value = MFC.CMDStatus.GetValue(); break; + case MFC_QStatus_offs: ConLog.Warning("RawSPUThread[%d]: Read32(MFC_QStatus)", m_index); *value = MFC.QStatus.GetValue(); break; + case Prxy_QueryType_offs: ConLog.Warning("RawSPUThread[%d]: Read32(Prxy_QueryType)", m_index); *value = Prxy.QueryType.GetValue(); break; + case Prxy_QueryMask_offs: ConLog.Warning("RawSPUThread[%d]: Read32(Prxy_QueryMask)", m_index); *value = Prxy.QueryMask.GetValue(); break; + case Prxy_TagStatus_offs: ConLog.Warning("RawSPUThread[%d]: Read32(Prxy_TagStatus)", m_index); *value = Prxy.TagStatus.GetValue(); break; + case SPU_Out_MBox_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_Out_MBox)", m_index); *value = SPU.Out_MBox.GetValue(); break; + case SPU_In_MBox_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_In_MBox)", m_index); *value = SPU.In_MBox.GetValue(); break; + case SPU_MBox_Status_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_MBox_Status)", m_index); *value = SPU.MBox_Status.GetValue(); break; + case SPU_RunCntl_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_RunCntl)", m_index); *value = SPU.RunCntl.GetValue(); break; + case SPU_Status_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_Status)", m_index); *value = SPU.Status.GetValue(); break; + case SPU_NPC_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_NPC)", m_index); *value = SPU.NPC.GetValue(); break; + case SPU_RdSigNotify1_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_RdSigNotify1)", m_index); *value = SPU.RdSigNotify1.GetValue(); break; + case SPU_RdSigNotify2_offs: ConLog.Warning("RawSPUThread[%d]: Read32(SPU_RdSigNotify2)", m_index); *value = SPU.RdSigNotify2.GetValue(); break; + + default: + ConLog.Error("RawSPUThread[%d]: Read32(0x%x)", m_index, offset); + Emu.Pause(); + break; + } + + return true; +} + +bool RawSPUThread::Read64(const u64 addr, u64* value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Read64(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Read64(0x%x)", m_index, offset); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Read128(const u64 addr, u128* value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Read128(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Read128(0x%x)", m_index, offset); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Write8(const u64 addr, const u8 value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Write8(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Write8(0x%x, 0x%x)", m_index, offset, value); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Write16(const u64 addr, const u16 value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Write16(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Write16(0x%x, 0x%x)", m_index, offset, value); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Write32(const u64 addr, const u32 value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Write32(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + + switch(offset) + { + case MFC_LSA_offs: ConLog.Warning("RawSPUThread[%d]: Write32(MFC_LSA, 0x%x)", m_index, value); MFC.LSA.SetValue(value); break; + case MFC_EAH_offs: ConLog.Warning("RawSPUThread[%d]: Write32(MFC_EAH, 0x%x)", m_index, value); MFC.EAH.SetValue(value); break; + case MFC_EAL_offs: ConLog.Warning("RawSPUThread[%d]: Write32(MFC_EAL, 0x%x)", m_index, value); MFC.EAL.SetValue(value); break; + case MFC_Size_Tag_offs: ConLog.Warning("RawSPUThread[%d]: Write32(MFC_Size_Tag, 0x%x)", m_index, value); MFC.Size_Tag.SetValue(value); break; + case MFC_CMDStatus_offs: + { + ConLog.Warning("RawSPUThread[%d]: Write32(MFC_CMDStatus, 0x%x)", m_index, value); + MFC.CMDStatus.SetValue(value); + u16 op = value & MFC_MASK_CMD; + + switch(op) + { + case MFC_PUT_CMD: + case MFC_GET_CMD: + { + u32 lsa = MFC.LSA.GetValue(); + u64 ea = (u64)MFC.EAL.GetValue() | ((u64)MFC.EAH.GetValue() << 32); + u32 size_tag = MFC.Size_Tag.GetValue(); + u16 tag = (u16)size_tag; + u16 size = size_tag >> 16; + + ConLog.Warning("RawSPUThread[%d]: DMA %s:", m_index, op == MFC_PUT_CMD ? "PUT" : "GET"); + ConLog.Warning("*** lsa = 0x%x", lsa); + ConLog.Warning("*** ea = 0x%llx", ea); + ConLog.Warning("*** tag = 0x%x", tag); + ConLog.Warning("*** size = 0x%x", size); + ConLog.SkipLn(); + + MFC.CMDStatus.SetValue(dmac.Cmd(value, tag, lsa, ea, size)); + } + break; + + default: + ConLog.Error("RawSPUThread[%d]: Unknown MFC cmd. (opcode=0x%x, cmd=0x%x)", m_index, op, value); + break; + } + } + break; + case MFC_QStatus_offs: ConLog.Warning("RawSPUThread[%d]: Write32(MFC_QStatus, 0x%x)", m_index, value); MFC.QStatus.SetValue(value); break; + case Prxy_QueryType_offs: + { + ConLog.Warning("RawSPUThread[%d]: Write32(Prxy_QueryType, 0x%x)", m_index, value); + Prxy.QueryType.SetValue(value); + + switch(value) + { + case 2: + ConLog.Warning("RawSPUThread[%d]: Prxy Query Immediate.", m_index); + break; + + default: + ConLog.Error("RawSPUThread[%d]: Unknown Prxy Query Type. (prxy_query=0x%x)", m_index, value); + break; + } + + Prxy.QueryType.SetValue(0); + MFC.QStatus.SetValue(Prxy.QueryMask.GetValue()); + } + break; + case Prxy_QueryMask_offs: ConLog.Warning("RawSPUThread[%d]: Write32(Prxy_QueryMask, 0x%x)", m_index, value); Prxy.QueryMask.SetValue(value); break; + case Prxy_TagStatus_offs: ConLog.Warning("RawSPUThread[%d]: Write32(Prxy_TagStatus, 0x%x)", m_index, value); Prxy.TagStatus.SetValue(value); break; + case SPU_Out_MBox_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_Out_MBox, 0x%x)", m_index, value); SPU.Out_MBox.SetValue(value); break; + case SPU_In_MBox_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_In_MBox, 0x%x)", m_index, value); SPU.In_MBox.SetValue(value); break; + case SPU_MBox_Status_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_MBox_Status, 0x%x)", m_index, value); SPU.MBox_Status.SetValue(value); break; + case SPU_RunCntl_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_RunCntl, 0x%x)", m_index, value); SPU.RunCntl.SetValue(value); break; + case SPU_Status_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_Status, 0x%x)", m_index, value); SPU.Status.SetValue(value); break; + case SPU_NPC_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_NPC, 0x%x)", m_index, value); SPU.NPC.SetValue(value); break; + case SPU_RdSigNotify1_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_RdSigNotify1, 0x%x)", m_index, value); SPU.RdSigNotify1.SetValue(value); break; + case SPU_RdSigNotify2_offs: ConLog.Warning("RawSPUThread[%d]: Write32(SPU_RdSigNotify2, 0x%x)", m_index, value); SPU.RdSigNotify2.SetValue(value); break; + + default: + ConLog.Error("RawSPUThread[%d]: Write32(0x%x, 0x%x)", m_index, offset, value); + Emu.Pause(); + break; + } + + return true; +} + +bool RawSPUThread::Write64(const u64 addr, const u64 value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Write64(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Write64(0x%x, 0x%llx)", m_index, offset, value); + Emu.Pause(); + return false; +} + +bool RawSPUThread::Write128(const u64 addr, const u128 value) +{ + if(addr < GetStartAddr() + RAW_SPU_PROB_OFFSET) + { + return MemoryBlock::Write128(addr, value); + } + + u32 offset = addr - GetStartAddr() - RAW_SPU_PROB_OFFSET; + ConLog.Error("RawSPUThread[%d]: Write128(0x%x, 0x%llx_%llx)", m_index, offset, value._u64[1], value._u64[0]); + Emu.Pause(); + return false; } void RawSPUThread::InitRegs() { - GPR[3]._u64[1] = m_args[0]; - GPR[4]._u64[1] = m_args[1]; - GPR[5]._u64[1] = m_args[2]; - GPR[6]._u64[1] = m_args[3]; + m_offset = GetStartAddr() + RAW_SPU_LS_OFFSET; + SPUThread::InitRegs(); +} - u32 num = Emu.GetCPU().GetThreadNumById(GetType(), GetId()); - - m_offset = RAW_SPU_BASE_ADDR + RAW_SPU_OFFSET * num + RAW_SPU_LS_OFFSET; - mfc.dmac.ls_offset = m_offset; - mfc.dmac.proxy_pos = 0; - mfc.dmac.queue_pos = 0; - mfc.MFC_LSA.SetAddr(GetRawSPURegAddrByNum(num, MFC_LSA_offs)); - mfc.MFC_EAH.SetAddr(GetRawSPURegAddrByNum(num, MFC_EAH_offs)); - mfc.MFC_EAL.SetAddr(GetRawSPURegAddrByNum(num, MFC_EAL_offs)); - mfc.MFC_Size_Tag.SetAddr(GetRawSPURegAddrByNum(num, MFC_Size_Tag_offs)); - mfc.MFC_CMDStatus.SetAddr(GetRawSPURegAddrByNum(num, MFC_CMDStatus_offs)); - mfc.MFC_QStatus.SetAddr(GetRawSPURegAddrByNum(num, MFC_QStatus_offs)); - mfc.Prxy_QueryType.SetAddr(GetRawSPURegAddrByNum(num, Prxy_QueryType_offs)); - mfc.Prxy_QueryMask.SetAddr(GetRawSPURegAddrByNum(num, Prxy_QueryMask_offs)); - mfc.Prxy_TagStatus.SetAddr(GetRawSPURegAddrByNum(num, Prxy_TagStatus_offs)); - mfc.SPU_Out_MBox.SetAddr(GetRawSPURegAddrByNum(num, SPU_Out_MBox_offs)); - mfc.SPU_In_MBox.SetAddr(GetRawSPURegAddrByNum(num, SPU_In_MBox_offs)); - mfc.SPU_MBox_Status.SetAddr(GetRawSPURegAddrByNum(num, SPU_MBox_Status_offs)); - mfc.SPU_RunCntl.SetAddr(GetRawSPURegAddrByNum(num, SPU_RunCntl_offs)); - mfc.SPU_Status.SetAddr(GetRawSPURegAddrByNum(num, SPU_Status_offs)); - mfc.SPU_NPC.SetAddr(GetRawSPURegAddrByNum(num, SPU_NPC_offs)); - mfc.SPU_RdSigNotify1.SetAddr(GetRawSPURegAddrByNum(num, SPU_RdSigNotify1_offs)); - mfc.SPU_RdSigNotify2.SetAddr(GetRawSPURegAddrByNum(num, SPU_RdSigNotify2_offs)); - - mfc.SPU_RunCntl.SetValue(SPU_RUNCNTL_STOP); - mfc.SPU_Status.SetValue(SPU_STATUS_RUNNING); - mfc.Prxy_QueryType.SetValue(0); - mfc.MFC_CMDStatus.SetValue(0); - PC = mfc.SPU_NPC.GetValue(); +u32 RawSPUThread::GetIndex() const +{ + return m_index; } void RawSPUThread::Task() @@ -70,27 +278,25 @@ void RawSPUThread::Task() { int status = ThreadStatus(); - if(status == PPCThread_Stopped || status == PPCThread_Break) + if(status == CPUThread_Stopped || status == CPUThread_Break) { break; } - if(status == PPCThread_Sleeping) + if(status == CPUThread_Sleeping) { Sleep(1); continue; } - mfc.Handle(); - - if(mfc.SPU_RunCntl.GetValue() != SPU_RUNCNTL_RUNNABLE) + if(SPU.RunCntl.GetValue() != SPU_RUNCNTL_RUNNABLE) { if(!is_last_paused) { - if(is_last_paused = mfc.SPU_RunCntl.GetValue() != SPU_RUNCNTL_RUNNABLE) + if(is_last_paused = SPU.RunCntl.GetValue() != SPU_RUNCNTL_RUNNABLE) { - mfc.SPU_NPC.SetValue(PC); - mfc.SPU_Status.SetValue(SPU_STATUS_WAITING_FOR_CHANNEL); + SPU.NPC.SetValue(PC); + SPU.Status.SetValue(SPU_STATUS_WAITING_FOR_CHANNEL); } } @@ -101,12 +307,11 @@ void RawSPUThread::Task() if(is_last_paused) { is_last_paused = false; - PC = mfc.SPU_NPC.GetValue(); - mfc.SPU_Status.SetValue(SPU_STATUS_RUNNING); + PC = SPU.NPC.GetValue(); + SPU.Status.SetValue(SPU_STATUS_RUNNING); } - DoCode(Memory.Read32(m_offset + PC)); - NextPc(); + NextPc(m_dec->DecodeMemory(PC + m_offset)); for(uint i=0; iExit(); delete m_op; } diff --git a/rpcs3/Emu/Cell/SPUDisAsm.h b/rpcs3/Emu/Cell/SPUDisAsm.h index c82b9d7a2e..c0eee0044a 100644 --- a/rpcs3/Emu/Cell/SPUDisAsm.h +++ b/rpcs3/Emu/Cell/SPUDisAsm.h @@ -6,43 +6,23 @@ #include "Gui/DisAsmFrame.h" #include "Emu/Memory/Memory.h" -class SPU_DisAsm - : public SPU_Opcodes - , public PPC_DisAsm +class SPUDisAsm + : public SPUOpcodes + , public PPCDisAsm { public: - PPCThread& CPU; - - SPU_DisAsm() - : PPC_DisAsm(*(PPCThread*)NULL, DumpMode) - , CPU(*(PPCThread*)NULL) + SPUDisAsm(CPUDisAsmMode mode) : PPCDisAsm(mode) { } - SPU_DisAsm(PPCThread& cpu, DisAsmModes mode = NormalMode) - : PPC_DisAsm(cpu, mode) - , CPU(cpu) - { - } - - ~SPU_DisAsm() + ~SPUDisAsm() { } private: - void Exit() - { - if(m_mode == NormalMode && !disasm_frame->exit) - { - disasm_frame->Close(); - } - - this->~SPU_DisAsm(); - } - virtual u32 DisAsmBranchTarget(const s32 imm) { - return branchTarget(m_mode == NormalMode ? CPU.PC : dump_pc, imm); + return branchTarget(dump_pc, imm); } private: @@ -114,7 +94,7 @@ private: } void MFSPR(u32 rt, u32 sa) { - DisAsm("mfspr", spu_reg_name[rt], spu_reg_name[sa]); // Are SPR mapped on the GPR or are there 128 additional registers ? + DisAsm("mfspr", spu_reg_name[rt], spu_reg_name[sa]); // Are SPR mapped on the GPR or are there 128 additional registers ? Yes, there are also 128 SPR making 256 registers total } void RDCH(u32 rt, u32 ra) { @@ -448,7 +428,7 @@ private: { DisAsm("sumb", spu_reg_name[rt], spu_reg_name[ra], spu_reg_name[rb]); } - void HGT(u32 rt, u32 ra, u32 rb) + void HGT(u32 rt, s32 ra, s32 rb) { DisAsm("hgt", spu_reg_name[rt], spu_reg_name[ra], spu_reg_name[rb]); } diff --git a/rpcs3/Emu/Cell/SPUInstrTable.h b/rpcs3/Emu/Cell/SPUInstrTable.h index e8446b18a4..bfbe113237 100644 --- a/rpcs3/Emu/Cell/SPUInstrTable.h +++ b/rpcs3/Emu/Cell/SPUInstrTable.h @@ -39,15 +39,15 @@ namespace SPU_instr static CodeField<18, 31> L_18_31; static CodeField<11> L_11; - static auto rrr_list = new_list(RRR); + static auto rrr_list = new_list(RRR); static auto ri18_list = new_list(rrr_list, RI18); static auto ri10_list = new_list(ri18_list, RI10); static auto ri16_list = new_list(ri10_list, RI16); static auto ri8_list = new_list(ri16_list, RI8); - static auto ri7_list = new_list(ri8_list, RI7, instr_bind(&SPU_Opcodes::UNK, GetCode, RRR, RI7)); + static auto ri7_list = new_list(ri8_list, RI7, instr_bind(&SPUOpcodes::UNK, GetCode, RRR, RI7)); #define bind_instr(list, name, ...) \ - static const auto& name = make_instr(list, #name, &SPU_Opcodes::name, ##__VA_ARGS__) + static const auto& name = make_instr(list, #name, &SPUOpcodes::name, ##__VA_ARGS__) bind_instr(ri7_list, STOP, L_18_31); bind_instr(ri7_list, LNOP); diff --git a/rpcs3/Emu/Cell/SPUInterpreter.h b/rpcs3/Emu/Cell/SPUInterpreter.h index 2097e6fe9b..69eb99009b 100644 --- a/rpcs3/Emu/Cell/SPUInterpreter.h +++ b/rpcs3/Emu/Cell/SPUInterpreter.h @@ -7,19 +7,17 @@ #define UNIMPLEMENTED() UNK(__FUNCTION__) -class SPU_Interpreter : public SPU_Opcodes +class SPUInterpreter : public SPUOpcodes { private: SPUThread& CPU; public: - SPU_Interpreter(SPUThread& cpu) : CPU(cpu) + SPUInterpreter(SPUThread& cpu) : CPU(cpu) { } private: - void Exit(){} - void SysCall() { } @@ -46,7 +44,17 @@ private: } void MFSPR(u32 rt, u32 sa) { - UNIMPLEMENTED(); + //If register is a dummy register (register labeled 0x0) + if(sa == 0x0) + { + CPU.GPR[rt]._u128.hi = 0x0; + CPU.GPR[rt]._u128.lo = 0x0; + } + else + { + CPU.GPR[rt]._u128.hi = CPU.SPR[sa]._u128.hi; + CPU.GPR[rt]._u128.lo = CPU.SPR[sa]._u128.lo; + } } void RDCH(u32 rt, u32 ra) { @@ -252,7 +260,11 @@ private: } void MTSPR(u32 rt, u32 sa) { - UNIMPLEMENTED(); + if(sa != 0) + { + CPU.SPR[sa]._u128.hi = CPU.GPR[rt]._u128.hi; + CPU.SPR[sa]._u128.lo = CPU.GPR[rt]._u128.lo; + } } void WRCH(u32 ra, u32 rt) { @@ -299,7 +311,7 @@ private: void IRET(u32 ra) { UNIMPLEMENTED(); - // SetBranch(SRR0); + //SetBranch(SRR0); } void BISLED(u32 rt, u32 ra) { @@ -620,9 +632,13 @@ private: CPU.GPR[rt]._u16[w*2 + 1] = CPU.GPR[rb]._u8[w*4] + CPU.GPR[rb]._u8[w*4 + 1] + CPU.GPR[rb]._u8[w*4 + 2] + CPU.GPR[rb]._u8[w*4 + 3]; } } - void HGT(u32 rt, u32 ra, u32 rb) + //HGT uses signed values. HLGT uses unsigned values + void HGT(u32 rt, s32 ra, s32 rb) { - UNIMPLEMENTED(); + if(CPU.GPR[ra]._i32[0] > CPU.GPR[rb]._i32[0]) + { + CPU.Stop(); + } } void CLZ(u32 rt, u32 ra) { @@ -749,7 +765,10 @@ private: } void HLGT(u32 rt, u32 ra, u32 rb) { - UNIMPLEMENTED(); + if(CPU.GPR[ra]._u32[0] > CPU.GPR[rb]._u32[0]) + { + CPU.Stop(); + } } void DFMA(u32 rt, u32 ra, u32 rb) { @@ -816,8 +835,13 @@ private: for (int w = 0; w < 4; w++) CPU.GPR[rt]._u32[w] += CPU.GPR[ra]._u16[w*2] * CPU.GPR[rb]._u16[w*2]; } + //Forced bits to 0, hence the shift: + void FSCRRD(u32 rt) { + /*CPU.GPR[rt]._u128.lo = + CPU.FPSCR.Exception0 << 20 & + CPU.FPSCR.*/ UNIMPLEMENTED(); } void FESD(u32 rt, u32 ra) @@ -892,7 +916,7 @@ private: void MPYU(u32 rt, u32 ra, u32 rb) { for (int w = 0; w < 4; w++) - CPU.GPR[rt]._u32[w] = CPU.GPR[ra]._u16[w*2 + 1] * CPU.GPR[rb]._u16[w*2 + 1]; + CPU.GPR[rt]._u32[w] = CPU.GPR[ra]._u16[w*2] * CPU.GPR[rb]._u16[w*2]; } void CEQB(u32 rt, u32 ra, u32 rb) { diff --git a/rpcs3/Emu/Cell/SPUOpcodes.h b/rpcs3/Emu/Cell/SPUOpcodes.h index e3bff38d3e..2b0a48744c 100644 --- a/rpcs3/Emu/Cell/SPUOpcodes.h +++ b/rpcs3/Emu/Cell/SPUOpcodes.h @@ -226,15 +226,13 @@ namespace SPU_opcodes }; }; -class SPU_Opcodes +class SPUOpcodes { public: static u32 branchTarget(const u64 pc, const s32 imm) { return (pc + (imm << 2)) & 0x3fffc; } - - virtual void Exit()=0; //0 - 10 virtual void STOP(u32 code) = 0; @@ -325,7 +323,7 @@ public: virtual void EQV(u32 rt, u32 ra, u32 rb) = 0; virtual void CGTB(u32 rt, u32 ra, u32 rb) = 0; virtual void SUMB(u32 rt, u32 ra, u32 rb) = 0; - virtual void HGT(u32 rt, u32 ra, u32 rb) = 0; + virtual void HGT(u32 rt, s32 ra, s32 rb) = 0; virtual void CLZ(u32 rt, u32 ra) = 0; virtual void XSWD(u32 rt, u32 ra) = 0; virtual void XSHW(u32 rt, u32 ra) = 0; diff --git a/rpcs3/Emu/Cell/SPUThread.cpp b/rpcs3/Emu/Cell/SPUThread.cpp index badacc7256..332aa605ae 100644 --- a/rpcs3/Emu/Cell/SPUThread.cpp +++ b/rpcs3/Emu/Cell/SPUThread.cpp @@ -8,13 +8,18 @@ SPUThread& GetCurrentSPUThread() { PPCThread* thread = GetCurrentPPCThread(); - if(!thread || thread->GetType() == PPC_THREAD_PPU) throw wxString("GetCurrentSPUThread: bad thread"); + if(!thread || (thread->GetType() != CPU_THREAD_SPU && thread->GetType() != CPU_THREAD_RAW_SPU)) + { + throw wxString("GetCurrentSPUThread: bad thread"); + } return *(SPUThread*)thread; } -SPUThread::SPUThread(PPCThreadType type) : PPCThread(type) +SPUThread::SPUThread(CPUThreadType type) : PPCThread(type) { + assert(type == CPU_THREAD_SPU || type == CPU_THREAD_RAW_SPU); + Reset(); } @@ -24,8 +29,10 @@ SPUThread::~SPUThread() void SPUThread::DoReset() { + PPCThread::DoReset(); + //reset regs - for(u32 i=0; i<128; ++i) GPR[i].Reset(); + memset(GPR, 0, sizeof(SPU_GPR_hdr) * 128); } void SPUThread::InitRegs() @@ -35,6 +42,16 @@ void SPUThread::InitRegs() GPR[4]._u64[1] = m_args[1]; GPR[5]._u64[1] = m_args[2]; GPR[6]._u64[1] = m_args[3]; + + dmac.ls_offset = m_offset; + dmac.proxy_pos = 0; + dmac.queue_pos = 0; + + SPU.RunCntl.SetValue(SPU_RUNCNTL_STOP); + SPU.Status.SetValue(SPU_STATUS_RUNNING); + Prxy.QueryType.SetValue(0); + MFC.CMDStatus.SetValue(0); + PC = SPU.NPC.GetValue(); } u64 SPUThread::GetFreeStackSize() const @@ -47,12 +64,12 @@ void SPUThread::DoRun() switch(Ini.CPUDecoderMode.GetValue()) { case 0: - m_dec = new SPU_Decoder(*new SPU_DisAsm(*this)); + //m_dec = new SPUDecoder(*new SPUDisAsm()); break; case 1: case 2: - m_dec = new SPU_Decoder(*new SPU_Interpreter(*this)); + m_dec = new SPUDecoder(*new SPUInterpreter(*this)); break; } } @@ -70,8 +87,3 @@ void SPUThread::DoStop() delete m_dec; m_dec = 0; } - -void SPUThread::DoCode(const s32 code) -{ - m_dec->Decode(code); -} diff --git a/rpcs3/Emu/Cell/SPUThread.h b/rpcs3/Emu/Cell/SPUThread.h index 77a260989b..2031805718 100644 --- a/rpcs3/Emu/Cell/SPUThread.h +++ b/rpcs3/Emu/Cell/SPUThread.h @@ -22,6 +22,25 @@ static const wxString spu_reg_name[128] = "$112", "$113", "$114", "$115", "$116", "$117", "$118", "$119", "$120", "$121", "$122", "$123", "$124", "$125", "$126", "$127", }; +//SPU reg $0 is a dummy reg, and is used for certain instructions. +static const wxString spu_specialreg_name[128] = { + "$0", "$1", "$2", "$3", "$4", "$5", "$6", "$7", + "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", + "$16", "$17", "$18", "$19", "$20", "$21", "$22", "$23", + "$24", "$25", "$26", "$27", "$28", "$29", "$30", "$31", + "$32", "$33", "$34", "$35", "$36", "$37", "$38", "$39", + "$40", "$41", "$42", "$43", "$44", "$45", "$46", "$47", + "$48", "$49", "$50", "$51", "$52", "$53", "$54", "$55", + "$56", "$57", "$58", "$59", "$60", "$61", "$62", "$63", + "$64", "$65", "$66", "$67", "$68", "$69", "$70", "$71", + "$72", "$73", "$74", "$75", "$76", "$77", "$78", "$79", + "$80", "$81", "$82", "$83", "$84", "$85", "$86", "$87", + "$88", "$89", "$90", "$91", "$92", "$93", "$94", "$95", + "$96", "$97", "$98", "$99", "$100", "$101", "$102", "$103", + "$104", "$105", "$106", "$107", "$108", "$109", "$110", "$111", + "$112", "$113", "$114", "$115", "$116", "$117", "$118", "$119", + "$120", "$121", "$122", "$123", "$124", "$125", "$126", "$127", +}; static const wxString spu_ch_name[128] = { @@ -98,6 +117,89 @@ enum SPU_STATUS_SINGLE_STEP = 0x10, }; +//Floating point status and control register. Unsure if this is one of the GPRs or SPRs +//Is 128 bits, but bits 0-19, 24-28, 32-49, 56-60, 64-81, 88-92, 96-115, 120-124 are unused +class FPSCR +{ +public: + u64 low; + u64 hi; + + FPSCR() {} + + wxString ToString() const + { + return "FPSCR writer not yet implemented"; //wxString::Format("%08x%08x%08x%08x", _u32[3], _u32[2], _u32[1], _u32[0]); + } + + void Reset() + { + memset(this, 0, sizeof(*this)); + } + //slice -> 0 - 1 (4 slices total, only two have rounding) + //0 -> round even + //1 -> round towards zero (truncate) + //2 -> round towards positive inf + //3 -> round towards neg inf + void setSliceRounding(u8 slice, u8 roundTo) + { + u64 mask = roundTo; + switch(slice) + { + case 0: + mask = mask << 20; + break; + case 1: + mask = mask << 22; + break; + } + + //rounding is located in the low end of the FPSCR + this->low = this->low & mask; + } + //Slice 0 or 1 + u8 checkSliceRounding(u8 slice) + { + switch(slice) + { + case 0: + return this->low >> 20 & 0x3; + + case 1: + return this->low >> 22 & 0x3; + } + } + + //Single Precision Exception Flags (all 3 slices) + //slice -> slice number (0-3) + //exception: 1 -> Overflow 2 -> Underflow 4-> Diff (could be IE^3 non compliant) + void setSinglePrecisionExceptionFlags(u8 slice, u8 exception) + { + u64 mask = exception; + switch(slice) + { + case 0: + mask = mask << 29; + this->low = this->low & mask; + break; + case 1: + mask = mask << 61; + this->low = this->low & mask; + break; + case 2: + mask = mask << 29; + this->hi = this->hi & mask; + break; + case 3: + mask = mask << 61; + this->hi = this->hi & mask; + break; + } + + } + +}; + union SPU_GPR_hdr { u128 _u128; @@ -126,32 +228,120 @@ union SPU_GPR_hdr } }; +union SPU_SPR_hdr +{ + u128 _u128; + s128 _i128; + + + SPU_SPR_hdr() {} + + wxString ToString() const + { + return wxString::Format("%16%16", _u128.hi, _u128.lo); + } + + void Reset() + { + memset(this, 0, sizeof(*this)); + } +}; + class SPUThread : public PPCThread { public: SPU_GPR_hdr GPR[128]; //General-Purpose Register - /* - SPUReg<1> MFC_LSA; - SPUReg<1> MFC_EAH; - SPUReg<1> MFC_EAL; - SPUReg<1> MFC_Size_Tag; - SPUReg<1> MFC_CMDStatus; - SPUReg<1> MFC_QStatus; - SPUReg<1> Prxy_QueryType; - SPUReg<1> Prxy_QueryMask; - SPUReg<1> Prxy_TagStatus; - SPUReg<1> SPU_Out_MBox; - SPUReg<4> SPU_In_MBox; - SPUReg<1> SPU_MBox_Status; - SPUReg<1> SPU_RunCntl; - SPUReg<1> SPU_Status; - SPUReg<1> SPU_NPC; - SPUReg<1> SPU_RdSigNotify1; - SPUReg<1> SPU_RdSigNotify2; - */ - SizedStack SPU_OutIntr_Mbox; + SPU_SPR_hdr SPR[128]; //Special-Purpose Registers + FPSCR FPSCR; + + template + class Channel + { + public: + static const size_t max_count = _max_count; + + private: + u32 m_value[max_count]; + u32 m_index; + + public: + + Channel() + { + Init(); + } + + void Init() + { + m_index = 0; + } + + __forceinline bool Pop(u32& res) + { + if(!m_index) return false; + res = m_value[--m_index]; + return true; + } + + __forceinline bool Push(u32 value) + { + if(m_index >= max_count) return false; + m_value[m_index++] = value; + return true; + } + + u32 GetCount() const + { + return m_index; + } + + u32 GetFreeCount() const + { + return max_count - m_index; + } + + void SetValue(u32 value) + { + m_value[0] = value; + } + + u32 GetValue() const + { + return m_value[0]; + } + }; + + struct + { + Channel<1> LSA; + Channel<1> EAH; + Channel<1> EAL; + Channel<1> Size_Tag; + Channel<1> CMDStatus; + Channel<1> QStatus; + } MFC; + + struct + { + Channel<1> QueryType; + Channel<1> QueryMask; + Channel<1> TagStatus; + } Prxy; + + struct + { + Channel<1> Out_MBox; + Channel<1> OutIntr_Mbox; + Channel<4> In_MBox; + Channel<1> MBox_Status; + Channel<1> RunCntl; + Channel<1> Status; + Channel<1> NPC; + Channel<1> RdSigNotify1; + Channel<1> RdSigNotify2; + } SPU; + u32 LSA; - MFC mfc; union { @@ -159,18 +349,20 @@ public: struct { u32 EAH, EAL; }; }; + DMAC dmac; + u32 GetChannelCount(u32 ch) { switch(ch) { case SPU_WrOutMbox: - return mfc.SPU_Out_MBox.GetFreeCount(); + return SPU.Out_MBox.GetFreeCount(); case SPU_RdInMbox: - return mfc.SPU_In_MBox.GetCount(); + return SPU.In_MBox.GetFreeCount(); case SPU_WrOutIntrMbox: - return 0;//return SPU_OutIntr_Mbox.GetFreeCount(); + return 0;//return SPU.OutIntr_Mbox.GetFreeCount(); default: ConLog.Error("%s error: unknown/illegal channel (%d).", __FUNCTION__, ch); @@ -188,7 +380,7 @@ public: { case SPU_WrOutIntrMbox: ConLog.Warning("SPU_WrOutIntrMbox = 0x%x", v); - if(!SPU_OutIntr_Mbox.Push(v)) + if(!SPU.OutIntr_Mbox.Push(v)) { ConLog.Warning("Not enought free rooms."); } @@ -196,11 +388,11 @@ public: case SPU_WrOutMbox: ConLog.Warning("SPU_WrOutMbox = 0x%x", v); - if(!mfc.SPU_Out_MBox.Push(v)) + if(!SPU.Out_MBox.Push(v)) { ConLog.Warning("Not enought free rooms."); } - mfc.SPU_Status.SetValue((mfc.SPU_Status.GetValue() & ~0xff) | 1); + SPU.Status.SetValue((SPU.Status.GetValue() & ~0xff) | 1); break; default: @@ -217,8 +409,8 @@ public: switch(ch) { case SPU_RdInMbox: - if(!mfc.SPU_In_MBox.Pop(v)) v = 0; - mfc.SPU_Status.SetValue((mfc.SPU_Status.GetValue() & ~0xff00) | (mfc.SPU_In_MBox.GetCount() << 8)); + if(!SPU.In_MBox.Pop(v)) v = 0; + SPU.Status.SetValue((SPU.Status.GetValue() & ~0xff00) | (SPU.In_MBox.GetCount() << 8)); break; default: @@ -241,13 +433,15 @@ public: virtual void WriteLS128(const u32 lsa, const u128& data) const { Memory.Write128(lsa + m_offset, data); } public: - SPUThread(PPCThreadType type = PPC_THREAD_SPU); + SPUThread(CPUThreadType type = CPU_THREAD_SPU); ~SPUThread(); virtual wxString RegsToString() { - wxString ret = PPCThread::RegsToString(); + wxString ret; + for(uint i=0; i<128; ++i) ret += wxString::Format("GPR[%d] = 0x%s\n", i, GPR[i].ToString()); + return ret; } @@ -262,7 +456,8 @@ public: return wxEmptyString; } - bool WriteRegString(wxString reg, wxString value) { + bool WriteRegString(wxString reg, wxString value) + { while (value.Len() < 32) value = "0"+value; if (reg.Contains("[")) { @@ -292,9 +487,6 @@ protected: virtual void DoPause(); virtual void DoResume(); virtual void DoStop(); - -protected: - virtual void DoCode(const s32 code); }; SPUThread& GetCurrentSPUThread(); \ No newline at end of file diff --git a/rpcs3/Emu/FS/VFS.cpp b/rpcs3/Emu/FS/VFS.cpp index 0a162f9f2c..fb1874f5bc 100644 --- a/rpcs3/Emu/FS/VFS.cpp +++ b/rpcs3/Emu/FS/VFS.cpp @@ -101,6 +101,28 @@ vfsDevice* VFS::GetDevice(const wxString& ps3_path, wxString& path) return &m_devices[max_i]; } +vfsDevice* VFS::GetDeviceLocal(const wxString& local_path, wxString& path) +{ + u32 max_eq; + s32 max_i=-1; + + for(u32 i=0; i max_eq) + { + max_eq = eq; + max_i = i; + } + } + + if(max_i < 0) return nullptr; + + path = vfsDevice::GetPs3Path(m_devices[max_i].GetPs3Path(), local_path(max_eq, local_path.Len() - max_eq)); + return &m_devices[max_i]; +} + void VFS::Init(const wxString& path) { Array entries; @@ -148,7 +170,12 @@ void VFS::SaveLoadDevices(Array& res, bool is_load) res[idx].path = "$(EmulatorDir)\\dev_hdd0\\"; res[idx].mount = "/dev_hdd0/"; res[idx].device = vfsDevice_LocalFile; - + + idx = res.Move(new VFSManagerEntry()); + res[idx].path = "$(EmulatorDir)\\dev_hdd1\\"; + res[idx].mount = "/dev_hdd1/"; + res[idx].device = vfsDevice_LocalFile; + /* idx = res.Move(new VFSManagerEntry()); res[idx].path = "$(GameDir)"; res[idx].mount = ""; @@ -158,6 +185,7 @@ void VFS::SaveLoadDevices(Array& res, bool is_load) res[idx].path = "$(GameDir)"; res[idx].mount = "/"; res[idx].device = vfsDevice_LocalFile; + */ idx = res.Move(new VFSManagerEntry()); res[idx].path = "$(GameDir)"; diff --git a/rpcs3/Emu/FS/VFS.h b/rpcs3/Emu/FS/VFS.h index 798e951142..49f7798a22 100644 --- a/rpcs3/Emu/FS/VFS.h +++ b/rpcs3/Emu/FS/VFS.h @@ -36,6 +36,7 @@ struct VFS void Create(const wxString& ps3_path); void Close(vfsStream*& device); vfsDevice* GetDevice(const wxString& ps3_path, wxString& path); + vfsDevice* GetDeviceLocal(const wxString& local_path, wxString& path); void Init(const wxString& path); void SaveLoadDevices(Array& res, bool is_load); diff --git a/rpcs3/Emu/FS/vfsDevice.cpp b/rpcs3/Emu/FS/vfsDevice.cpp index 2a05018c11..570e60dd52 100644 --- a/rpcs3/Emu/FS/vfsDevice.cpp +++ b/rpcs3/Emu/FS/vfsDevice.cpp @@ -36,6 +36,19 @@ u32 vfsDevice::CmpPs3Path(const wxString& ps3_path) return ret; } +u32 vfsDevice::CmpLocalPath(const wxString& local_path) +{ + const u32 lim = min(m_local_path.Len(), local_path.Len()); + u32 ret = 0; + + for(u32 i=0; iIsOpened(); +} + +bool vfsFile::Create(const wxString& path) +{ + if(wxFileExists(path)) return false; + + wxFile f; + return f.Create(path); +} + +bool vfsFile::Close() +{ + if(m_stream) + { + delete m_stream; + m_stream = nullptr; + return vfsFileBase::Close(); + } + + return false; +} + +u64 vfsFile::GetSize() +{ + return m_stream->GetSize(); +} + +u64 vfsFile::Write(const void* src, u64 size) +{ + return m_stream->Write(src, size); +} + +u64 vfsFile::Read(void* dst, u64 size) +{ + return m_stream->Read(dst, size); +} + +u64 vfsFile::Seek(s64 offset, vfsSeekMode mode) +{ + return m_stream->Seek(offset, mode); +} + +u64 vfsFile::Tell() const +{ + return m_stream->Tell(); +} + +bool vfsFile::IsOpened() const +{ + return m_stream && m_stream->IsOpened() && vfsFileBase::IsOpened(); +} diff --git a/rpcs3/Emu/FS/vfsFile.h b/rpcs3/Emu/FS/vfsFile.h new file mode 100644 index 0000000000..d9777b7203 --- /dev/null +++ b/rpcs3/Emu/FS/vfsFile.h @@ -0,0 +1,29 @@ +#pragma once +#include "vfsFileBase.h" + +class vfsFile : public vfsFileBase +{ +private: + vfsStream* m_stream; + +public: + vfsFile(); + vfsFile(const wxString path, vfsOpenMode mode = vfsRead); + ~vfsFile(); + + virtual vfsDevice* GetNew() override; + + virtual bool Open(const wxString& path, vfsOpenMode mode = vfsRead) override; + virtual bool Create(const wxString& path) override; + virtual bool Close() override; + + virtual u64 GetSize() override; + + virtual u64 Write(const void* src, u64 size) override; + virtual u64 Read(void* dst, u64 size) override; + + virtual u64 Seek(s64 offset, vfsSeekMode mode = vfsSeekSet) override; + virtual u64 Tell() const override; + + virtual bool IsOpened() const override; +}; \ No newline at end of file diff --git a/rpcs3/Emu/FS/vfsStreamMemory.cpp b/rpcs3/Emu/FS/vfsStreamMemory.cpp index 1b0900b7da..8bb08090e6 100644 --- a/rpcs3/Emu/FS/vfsStreamMemory.cpp +++ b/rpcs3/Emu/FS/vfsStreamMemory.cpp @@ -5,21 +5,32 @@ vfsStreamMemory::vfsStreamMemory() : vfsStream() { } -vfsStreamMemory::vfsStreamMemory(u64 addr) : vfsStream() +vfsStreamMemory::vfsStreamMemory(u64 addr, u64 size) : vfsStream() { - Open(addr); + Open(addr, size); } -void vfsStreamMemory::Open(u64 addr) +void vfsStreamMemory::Open(u64 addr, u64 size) { m_addr = addr; + m_size = size ? size : ~0ULL; vfsStream::Reset(); } +u64 vfsStreamMemory::GetSize() +{ + return m_size; +} + u64 vfsStreamMemory::Write(const void* src, u64 size) { - if(!Memory.IsGoodAddr(m_addr + Tell(), size)) return 0; + if(Tell() + size > GetSize()) + { + size = GetSize() - Tell(); + } + + if(!size || !Memory.IsGoodAddr(m_addr + Tell(), size)) return 0; memcpy(&Memory[m_addr + Tell()], src, size); @@ -28,7 +39,12 @@ u64 vfsStreamMemory::Write(const void* src, u64 size) u64 vfsStreamMemory::Read(void* dst, u64 size) { - if(!Memory.IsGoodAddr(m_addr + Tell(), size)) return 0; + if(Tell() + size > GetSize()) + { + size = GetSize() - Tell(); + } + + if(!size || !Memory.IsGoodAddr(m_addr + Tell(), size)) return 0; memcpy(dst, &Memory[m_addr + Tell()], size); diff --git a/rpcs3/Emu/FS/vfsStreamMemory.h b/rpcs3/Emu/FS/vfsStreamMemory.h index 086f7109d5..00cb675013 100644 --- a/rpcs3/Emu/FS/vfsStreamMemory.h +++ b/rpcs3/Emu/FS/vfsStreamMemory.h @@ -4,12 +4,15 @@ struct vfsStreamMemory : public vfsStream { u64 m_addr; + u64 m_size; public: vfsStreamMemory(); - vfsStreamMemory(u64 addr); + vfsStreamMemory(u64 addr, u64 size = 0); - void Open(u64 addr); + void Open(u64 addr, u64 size = 0); + + virtual u64 GetSize() override; virtual u64 Write(const void* src, u64 size) override; virtual u64 Read(void* dst, u64 size) override; diff --git a/rpcs3/Emu/GS/GCM.h b/rpcs3/Emu/GS/GCM.h index 80218b991e..483f67eec3 100644 --- a/rpcs3/Emu/GS/GCM.h +++ b/rpcs3/Emu/GS/GCM.h @@ -1,4 +1,5 @@ #pragma once +#include "rpcs3.h" enum { @@ -39,6 +40,104 @@ struct gcmInfo u32 control_addr; }; +struct CellGcmSurface +{ + u8 type; + u8 antialias; + + u8 color_format; + u8 color_target; + u8 color_location[4]; + u32 color_offset[4]; + u32 color_pitch[4]; + + u8 depth_format; + u8 depth_location; + u16 pad; + u32 depth_offset; + u32 depth_pitch; + + u16 width; + u16 height; + u16 x; + u16 y; +}; + +struct CellGcmReportData +{ + u64 timer; + u32 value; + u32 pad; +}; + +struct CellGcmZcullInfo +{ + u32 region; + u32 size; + u32 start; + u32 offset; + u32 status0; + u32 status1; +}; + +struct CellGcmTileInfo +{ + u32 tile; + u32 limit; + u32 pitch; + u32 format; +}; + +struct GcmZcullInfo +{ + u32 m_offset; + u32 m_width; + u32 m_height; + u32 m_cullStart; + u32 m_zFormat; + u32 m_aaFormat; + u32 m_zCullDir; + u32 m_zCullFormat; + u32 m_sFunc; + u32 m_sRef; + u32 m_sMask; + bool m_binded; + + GcmZcullInfo() + { + memset(this, 0, sizeof(*this)); + } +}; + +struct GcmTileInfo +{ + u8 m_location; + u32 m_offset; + u32 m_size; + u32 m_pitch; + u8 m_comp; + u16 m_base; + u8 m_bank; + bool m_binded; + + GcmTileInfo() + { + memset(this, 0, sizeof(*this)); + } + + CellGcmTileInfo Pack() + { + CellGcmTileInfo ret; + + re(ret.tile, (m_location + 1) | (m_bank << 4) | ((m_offset / 0x10000) << 16) | (m_location << 31)); + re(ret.limit, ((m_offset + m_size - 1) / 0x10000) << 16 | (m_location << 31)); + re(ret.pitch, (m_pitch / 0x100) << 8); + re(ret.format, m_base | ((m_base + ((m_size - 1) / 0x10000)) << 13) | (m_comp << 26) | (1 << 30)); + + return ret; + } +}; + enum { CELL_GCM_LOCATION_LOCAL, diff --git a/rpcs3/Emu/GS/GL/GLBuffers.cpp b/rpcs3/Emu/GS/GL/GLBuffers.cpp index bf4d94a177..9b14845c0d 100644 --- a/rpcs3/Emu/GS/GL/GLBuffers.cpp +++ b/rpcs3/Emu/GS/GL/GLBuffers.cpp @@ -135,11 +135,13 @@ GLrbo::~GLrbo() void GLrbo::Create(u32 count) { - if(m_id.GetCount()) + if(m_id.GetCount() == count) { return; } + Delete(); + m_id.SetCount(count); glGenRenderbuffers(count, m_id.GetPtr()); } @@ -163,6 +165,11 @@ void GLrbo::Unbind() void GLrbo::Delete() { + if(!IsCreated()) + { + return; + } + glDeleteRenderbuffers(m_id.GetCount(), m_id.GetPtr()); m_id.Clear(); } @@ -198,11 +205,15 @@ void GLfbo::Create() void GLfbo::Bind(u32 type, int id) { - if(id != -1) - assert(m_id); + glBindFramebuffer(type, id); +} + +void GLfbo::Bind(u32 type) +{ + assert(IsCreated()); m_type = type; - glBindFramebuffer(m_type, id == -1 ? m_id : id); + Bind(type, m_id); } void GLfbo::Texture1D(u32 attachment, u32 texture, int level) @@ -242,6 +253,11 @@ void GLfbo::Unbind(u32 type) void GLfbo::Delete() { + if(!IsCreated()) + { + return; + } + glDeleteFramebuffers(1, &m_id); m_id = 0; } diff --git a/rpcs3/Emu/GS/GL/GLBuffers.h b/rpcs3/Emu/GS/GL/GLBuffers.h index 0f941ffe34..0143504df7 100644 --- a/rpcs3/Emu/GS/GL/GLBuffers.h +++ b/rpcs3/Emu/GS/GL/GLBuffers.h @@ -77,12 +77,13 @@ public: ~GLfbo(); void Create(); - void Bind(u32 type = GL_FRAMEBUFFER, int id = -1); + static void Bind(u32 type, int id); + void Bind(u32 type = GL_FRAMEBUFFER); void Texture1D(u32 attachment, u32 texture, int level = 0); void Texture2D(u32 attachment, u32 texture, int level = 0); void Texture3D(u32 attachment, u32 texture, int zoffset = 0, int level = 0); void Renderbuffer(u32 attachment, u32 renderbuffer); - void Blit(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, u32 mask, u32 filter); + static void Blit(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, u32 mask, u32 filter); void Unbind(); static void Unbind(u32 type); void Delete(); diff --git a/rpcs3/Emu/GS/GL/FragmentProgram.cpp b/rpcs3/Emu/GS/GL/GLFragmentProgram.cpp similarity index 80% rename from rpcs3/Emu/GS/GL/FragmentProgram.cpp rename to rpcs3/Emu/GS/GL/GLFragmentProgram.cpp index 3cb79fdae5..f0b25a2896 100644 --- a/rpcs3/Emu/GS/GL/FragmentProgram.cpp +++ b/rpcs3/Emu/GS/GL/GLFragmentProgram.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" -#include "FragmentProgram.h" +#include "GLFragmentProgram.h" -void FragmentDecompilerThread::AddCode(wxString code, bool append_mask) +void GLFragmentDecompilerThread::AddCode(wxString code, bool append_mask) { if(!src0.exec_if_eq && !src0.exec_if_gr && !src0.exec_if_lt) return; @@ -72,13 +72,14 @@ void FragmentDecompilerThread::AddCode(wxString code, bool append_mask) code = "clamp(" + code + ", 0.0, 1.0)"; } - code = cond + (dst.set_cond ? AddCond(dst.fp16) : AddReg(dst.dest_reg, dst.fp16)) + mask + code = cond + (dst.set_cond ? m_parr.AddParam(PARAM_NONE , "vec4", wxString::Format(dst.fp16 ? "hc%d" : "rc%d", src0.cond_reg_index)) + : AddReg(dst.dest_reg, dst.fp16)) + mask + " = " + code + (append_mask ? mask : wxEmptyString); main += "\t" + code + ";\n"; } -wxString FragmentDecompilerThread::GetMask() +wxString GLFragmentDecompilerThread::GetMask() { wxString ret = wxEmptyString; @@ -95,25 +96,32 @@ wxString FragmentDecompilerThread::GetMask() return ret.IsEmpty() || strncmp(ret, dst_mask, 4) == 0 ? wxEmptyString : ("." + ret); } -wxString FragmentDecompilerThread::AddReg(u32 index, int fp16) +wxString GLFragmentDecompilerThread::AddReg(u32 index, int fp16) { - //if(!index && !fp16) return "gl_FragColor"; - return m_parr.AddParam((index || fp16) ? PARAM_NONE : PARAM_OUT, "vec4", - wxString::Format((fp16 ? "h%u" : "r%u"), index), (index || fp16) ? -1 : 0); + /* + if(HasReg(index, fp16)) + { + return wxString::Format((fp16 ? "h%u" : "r%u"), index); + } + */ + + //ConLog.Warning("%c%d: %d %d", (fp16 ? 'h' : 'r'), index, dst.tex_num, src2.use_index_reg); + return m_parr.AddParam(fp16 ? PARAM_NONE : PARAM_OUT, "vec4", + wxString::Format((fp16 ? "h%u" : "r%u"), index), fp16 ? -1 : index); } -bool FragmentDecompilerThread::HasReg(u32 index, int fp16) +bool GLFragmentDecompilerThread::HasReg(u32 index, int fp16) { - return m_parr.HasParam((index || fp16) ? PARAM_NONE : PARAM_OUT, "vec4", + return m_parr.HasParam(PARAM_OUT, "vec4", wxString::Format((fp16 ? "h%u" : "r%u"), index)); } -wxString FragmentDecompilerThread::AddCond(int fp16) +wxString GLFragmentDecompilerThread::AddCond(int fp16) { - return m_parr.AddParam(PARAM_NONE , "vec4", (fp16 ? "hc" : "rc"), -1); + return m_parr.AddParam(PARAM_NONE , "vec4", wxString::Format(fp16 ? "hc%d" : "rc%d", src0.cond_mod_reg_index)); } -wxString FragmentDecompilerThread::AddConst() +wxString GLFragmentDecompilerThread::AddConst() { mem32_ptr_t data(m_addr + m_size + m_offset); @@ -126,12 +134,12 @@ wxString FragmentDecompilerThread::AddConst() wxString::Format("vec4(%f, %f, %f, %f)", (float&)x, (float&)y, (float&)z, (float&)w)); } -wxString FragmentDecompilerThread::AddTex() +wxString GLFragmentDecompilerThread::AddTex() { return m_parr.AddParam(PARAM_UNIFORM, "sampler2D", wxString::Format("tex%d", dst.tex_num)); } -template wxString FragmentDecompilerThread::GetSRC(T src) +template wxString GLFragmentDecompilerThread::GetSRC(T src) { wxString ret = wxEmptyString; @@ -196,15 +204,10 @@ template wxString FragmentDecompilerThread::GetSRC(T src) return ret; } -wxString FragmentDecompilerThread::BuildCode() +wxString GLFragmentDecompilerThread::BuildCode() { wxString p = wxEmptyString; - if(!m_parr.HasParam(PARAM_OUT, "vec4", "r0") && m_parr.HasParam(PARAM_NONE, "vec4", "h0")) - { - main += "\t" + m_parr.AddParam(PARAM_OUT, "vec4", "r0", 0) + " = " + "h0;\n"; - } - for(u32 i=0; iStart(); #endif } -void ShaderProgram::Compile() +void GLShaderProgram::Compile() { if(id) glDeleteShader(id); @@ -396,7 +401,7 @@ void ShaderProgram::Compile() //else ConLog.Write("Shader compiled successfully!"); } -void ShaderProgram::Delete() +void GLShaderProgram::Delete() { for(u32 i=0; i> 16; } }; -struct ShaderProgram +struct GLShaderProgram { - ShaderProgram(); - ~ShaderProgram(); + GLShaderProgram(); + ~GLShaderProgram(); - FragmentDecompilerThread* m_decompiler_thread; + GLFragmentDecompilerThread* m_decompiler_thread; - ParamArray parr; + GLParamArray parr; - u32 size; - u32 addr; - u32 offset; wxString shader; u32 id; @@ -156,7 +156,7 @@ struct ShaderProgram m_decompiler_thread->Wait(); } } - void Decompile(); + void Decompile(RSXShaderProgram& prog); void Compile(); void Delete(); diff --git a/rpcs3/Emu/GS/GL/GLGSRender.cpp b/rpcs3/Emu/GS/GL/GLGSRender.cpp index 66b5e7e0e4..2a2910ae25 100644 --- a/rpcs3/Emu/GS/GL/GLGSRender.cpp +++ b/rpcs3/Emu/GS/GL/GLGSRender.cpp @@ -13,6 +13,8 @@ gcmBuffer gcmBuffers[8]; +int last_width = 0, last_height = 0, last_depth_format = 0; + void printGlError(GLenum err, const char* situation) { if(err != GL_NO_ERROR) @@ -82,18 +84,17 @@ void GLGSFrame::SetViewport(int x, int y, u32 w, u32 h) GLGSRender::GLGSRender() : GSRender() , m_frame(nullptr) - , m_rsx_thread(nullptr) , m_fp_buf_num(-1) , m_vp_buf_num(-1) + , m_context(nullptr) { - m_draw = false; m_frame = new GLGSFrame(); } GLGSRender::~GLGSRender() { - Close(); m_frame->Close(); + delete m_context; } void GLGSRender::Enable(bool enable, const u32 cap) @@ -108,150 +109,11 @@ void GLGSRender::Enable(bool enable, const u32 cap) } } -GLRSXThread::GLRSXThread(wxWindow* parent) - : ThreadBase(true, "OpenGL Thread") - , m_parent(parent) -{ -} - extern CellGcmContextData current_context; -void GLRSXThread::Task() -{ - ConLog.Write("GL RSX thread entry"); - - GLGSRender& p = *(GLGSRender*)m_parent; - wxGLContext cntxt(p.m_frame->GetCanvas()); - p.m_frame->GetCanvas()->SetCurrent(cntxt); - InitProcTable(); - - glEnable(GL_TEXTURE_2D); - glEnable(GL_SCISSOR_TEST); - glSwapInterval(Ini.GSVSyncEnable.GetValue() ? 1 : 0); - - bool draw = true; - u32 drawed = 0; - u32 skipped = 0; - - p.Init(); - - while(!TestDestroy() && p.m_frame && !p.m_frame->IsBeingDeleted()) - { - wxCriticalSectionLocker lock(p.m_cs_main); - - const u32 get = re(p.m_ctrl->get); - const u32 put = re(p.m_ctrl->put); - if(put == get || !Emu.IsRunning()) - { - if(put == get) - SemaphorePostAndWait(p.m_sem_flush); - - Sleep(1); - continue; - } - - //ConLog.Write("addr = 0x%x", p.m_ioAddress + get); - const u32 cmd = Memory.Read32(p.m_ioAddress + get); - const u32 count = (cmd >> 18) & 0x7ff; - //if(cmd == 0) continue; - - if(cmd & CELL_GCM_METHOD_FLAG_JUMP) - { - u32 addr = cmd & ~(CELL_GCM_METHOD_FLAG_JUMP | CELL_GCM_METHOD_FLAG_NON_INCREMENT); - //ConLog.Warning("rsx jump(0x%x) #addr=0x%x, cmd=0x%x, get=0x%x, put=0x%x", addr, p.m_ioAddress + get, cmd, get, put); - re(p.m_ctrl->get, addr); - continue; - } - if(cmd & CELL_GCM_METHOD_FLAG_CALL) - { - call_stack.Push(get + 4); - u32 offs = cmd & ~CELL_GCM_METHOD_FLAG_CALL; - u32 addr = p.m_ioAddress + offs; - //ConLog.Warning("rsx call(0x%x) #0x%x - 0x%x - 0x%x", offs, addr, cmd, get); - p.m_ctrl->get = re32(offs); - continue; - } - if(cmd == CELL_GCM_METHOD_FLAG_RETURN) - { - //ConLog.Warning("rsx return!"); - u32 get = call_stack.Pop(); - //ConLog.Warning("rsx return(0x%x)", get); - p.m_ctrl->get = re32(get); - continue; - } - if(cmd & CELL_GCM_METHOD_FLAG_NON_INCREMENT) - { - //ConLog.Warning("non increment cmd! 0x%x", cmd); - } - - if(cmd == 0) - { - ConLog.Warning("null cmd: addr=0x%x, put=0x%x, get=0x%x", p.m_ioAddress + get, re(p.m_ctrl->put), get); - Emu.Pause(); - continue; - } - - mem32_ptr_t args(p.m_ioAddress + get + 4); - - if(!draw) - { - if((cmd & 0x3ffff) == NV406E_SET_REFERENCE) - { - p.m_ctrl->ref = re32(args[0]); - } - } - else - { - p.DoCmd(cmd, cmd & 0x3ffff, args, count); - } - - re(p.m_ctrl->get, get + (count + 1) * 4); - //memset(Memory.GetMemFromAddr(p.m_ioAddress + get), 0, (count + 1) * 4); - } - - ConLog.Write("GL RSX thread exit..."); - - call_stack.Clear(); - p.CloseOpenGL(); -} - -void GLGSRender::Init(const u32 ioAddress, const u32 ioSize, const u32 ctrlAddress, const u32 localAddress) -{ - if(m_frame->IsShown()) return; - - m_draw_frames = 1; - m_skip_frames = 0; - m_width = 720; - m_height = 576; - - m_frame->Show(); - - m_ioAddress = ioAddress; - m_ioSize = ioSize; - m_ctrlAddress = ctrlAddress; - m_local_mem_addr = localAddress; - m_ctrl = (CellGcmControl*)Memory.GetMemFromAddr(m_ctrlAddress); - - m_cur_vertex_prog = nullptr; - m_cur_shader_prog = nullptr; - m_cur_shader_prog_num = 0; - - (m_rsx_thread = new GLRSXThread(this))->Start(); -} - -void GLGSRender::Draw() -{ - m_draw = true; - //if(m_frame && !m_frame->IsBeingDeleted()) m_frame->Flip(); -} - void GLGSRender::Close() { - if(m_rsx_thread) - { - m_rsx_thread->Stop(); - delete m_rsx_thread; - } + if(IsAlive()) Stop(); if(m_frame->IsShown()) m_frame->Hide(); m_ctrl = nullptr; @@ -259,10 +121,10 @@ void GLGSRender::Close() void GLGSRender::EnableVertexData(bool indexed_draw) { - static u32 offset_list[16]; + static u32 offset_list[m_vertex_count]; u32 cur_offset = 0; - for(u32 i=0; i<16; ++i) + for(u32 i=0; ioffset + 2 * 4 * 4; @@ -489,1321 +351,6 @@ void GLGSRender::InitFragmentData() } } -#define case_16(a, m) \ - case a + m: \ - case a + m * 2: \ - case a + m * 3: \ - case a + m * 4: \ - case a + m * 5: \ - case a + m * 6: \ - case a + m * 7: \ - case a + m * 8: \ - case a + m * 9: \ - case a + m * 10: \ - case a + m * 11: \ - case a + m * 12: \ - case a + m * 13: \ - case a + m * 14: \ - case a + m * 15: \ - index = (cmd - a) / m; \ - case a \ - -void GLGSRender::DoCmd(const u32 fcmd, const u32 cmd, mem32_ptr_t& args, const u32 count) -{ -#if CMD_DEBUG - wxString debug = GetMethodName(cmd); - debug += "("; - for(u32 i=0; i= m_skip_frames) - { - skipped = 0; - draw = true; - } - } - else - { - if(drawed++ >= m_draw_frames) - { - drawed = 0; - draw = false; - } - } - }*/ - - //if(draw) - { - //if(m_frame->GetClientSize() != wxSize(m_viewport_w, m_viewport_h)) - // m_frame->SetClientSize(m_viewport_w, m_viewport_h); - - if(m_fbo.IsCreated()) - { - m_fbo.Bind(GL_READ_FRAMEBUFFER); - m_fbo.Bind(GL_DRAW_FRAMEBUFFER, 0); - m_fbo.Blit( - m_surface_clip_x, m_surface_clip_y, m_surface_clip_x + m_surface_clip_w, m_surface_clip_y + m_surface_clip_h, - m_surface_clip_x, m_surface_clip_y, m_surface_clip_x + m_surface_clip_w, m_surface_clip_y + m_surface_clip_h, - GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); - m_fbo.Bind(); - checkForGlError("m_fbo.Blit"); - } - - m_frame->Flip(); - glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - } - - m_gcm_current_buffer = args[0]; - - m_flip_status = 0; - if(m_flip_handler) - { - m_flip_handler.Handle(1, 0, 0); - m_flip_handler.Branch(false); - } - - SemaphorePostAndWait(m_sem_flip); - } - } - break; - - case NV4097_NO_OPERATION: - break; - - case NV406E_SET_REFERENCE: - m_ctrl->ref = re32(args[0]); - break; - - case_16(NV4097_SET_TEXTURE_OFFSET, 0x20): - { - GLTexture& tex = m_frame->GetTexture(index); - const u32 offset = args[0]; - u32 a1 = args[1]; - u8 location = (a1 & 0x3) - 1; - const bool cubemap = (a1 >> 2) & 0x1; - const u8 dimension = (a1 >> 4) & 0xf; - const u8 format = (a1 >> 8) & 0xff; - const u16 mipmap = (a1 >> 16) & 0xffff; - CMD_LOG("index = %d, offset=0x%x, location=0x%x, cubemap=0x%x, dimension=0x%x, format=0x%x, mipmap=0x%x", - index, offset, location, cubemap, dimension, format, mipmap); - - if(location == 2) - { - ConLog.Error("Bad texture location."); - location = 1; - } - u32 tex_addr = GetAddress(offset, location); - //ConLog.Warning("texture addr = 0x%x #offset = 0x%x, location=%d", tex_addr, offset, location); - tex.SetOffset(tex_addr); - tex.SetFormat(cubemap, dimension, format, mipmap); - } - break; - - case_16(NV4097_SET_TEXTURE_CONTROL0, 0x20): - { - GLTexture& tex = m_frame->GetTexture(index); - u32 a0 = args[0]; - bool enable = a0 >> 31 ? true : false; - u16 minlod = (a0 >> 19) & 0xfff; - u16 maxlod = (a0 >> 7) & 0xfff; - u8 maxaniso = (a0 >> 2) & 0x7; - tex.SetControl0(enable, minlod, maxlod, maxaniso); - } - break; - - case_16(NV4097_SET_VERTEX_DATA4UB_M, 4): - { - u32 v = args[0]; - u8 v0 = v; - u8 v1 = v >> 8; - u8 v2 = v >> 16; - u8 v3 = v >> 24; - - m_vertex_data[index].size = 4; - m_vertex_data[index].type = 4; - m_vertex_data[index].data.AddCpy(v0); - m_vertex_data[index].data.AddCpy(v1); - m_vertex_data[index].data.AddCpy(v2); - m_vertex_data[index].data.AddCpy(v3); - //ConLog.Warning("index = %d, v0 = 0x%x, v1 = 0x%x, v2 = 0x%x, v3 = 0x%x", index, v0, v1, v2, v3); - } - break; - - case_16(NV4097_SET_VERTEX_DATA2F_M, 8): - { - u32 a0 = args[0]; - u32 a1 = args[1]; - - float v0 = (float&)a0; - float v1 = (float&)a1; - - m_vertex_data[index].type = 2; - m_vertex_data[index].size = 2; - m_vertex_data[index].data.SetCount(sizeof(float) * 2); - (float&)m_vertex_data[index].data[sizeof(float)*0] = v0; - (float&)m_vertex_data[index].data[sizeof(float)*1] = v1; - - //ConLog.Warning("index = %d, v0 = %f, v1 = %f", index, v0, v1); - } - break; - - case_16(NV4097_SET_VERTEX_DATA4F_M, 16): - { - u32 a0 = args[0]; - u32 a1 = args[1]; - u32 a2 = args[2]; - u32 a3 = args[3]; - - float v0 = (float&)a0; - float v1 = (float&)a1; - float v2 = (float&)a2; - float v3 = (float&)a3; - - m_vertex_data[index].type = 2; - m_vertex_data[index].size = 4; - m_vertex_data[index].data.SetCount(sizeof(float) * 4); - (float&)m_vertex_data[index].data[sizeof(float)*0] = v0; - (float&)m_vertex_data[index].data[sizeof(float)*1] = v1; - (float&)m_vertex_data[index].data[sizeof(float)*2] = v2; - (float&)m_vertex_data[index].data[sizeof(float)*3] = v3; - - //ConLog.Warning("index = %d, v0 = %f, v1 = %f, v2 = %f, v3 = %f", index, v0, v1, v2, v3); - } - break; - - case_16(NV4097_SET_TEXTURE_CONTROL1, 0x20): - { - GLTexture& tex = m_frame->GetTexture(index); - tex.SetControl1(args[0]); - } - break; - - case_16(NV4097_SET_TEXTURE_CONTROL3, 4): - { - GLTexture& tex = m_frame->GetTexture(index); - u32 a0 = args[0]; - u32 pitch = a0 & 0xFFFFF; - u16 depth = a0 >> 20; - tex.SetControl3(pitch, depth); - } - break; - - case_16(NV4097_SET_TEXTURE_FILTER, 0x20): - { - GLTexture& tex = m_frame->GetTexture(index); - u32 a0 = args[0]; - u16 bias = a0 & 0x1fff; - u8 conv = (a0 >> 13) & 0xf; - u8 min = (a0 >> 16) & 0x7; - u8 mag = (a0 >> 24) & 0x7; - u8 a_signed = (a0 >> 28) & 0x1; - u8 r_signed = (a0 >> 29) & 0x1; - u8 g_signed = (a0 >> 30) & 0x1; - u8 b_signed = (a0 >> 31) & 0x1; - - tex.SetFilter(bias, min, mag, conv, a_signed, r_signed, g_signed, b_signed); - } - break; - - case_16(NV4097_SET_TEXTURE_ADDRESS, 0x20): - { - GLTexture& tex = m_frame->GetTexture(index); - - u32 a0 = args[0]; - u8 wraps = a0 & 0xf; - u8 aniso_bias = (a0 >> 4) & 0xf; - u8 wrapt = (a0 >> 8) & 0xf; - u8 unsigned_remap = (a0 >> 12) & 0xf; - u8 wrapr = (a0 >> 16) & 0xf; - u8 gamma = (a0 >> 20) & 0xf; - u8 signed_remap = (a0 >> 24) & 0xf; - u8 zfunc = a0 >> 28; - - tex.SetAddress(wraps, wrapt, wrapr, unsigned_remap, zfunc, gamma, aniso_bias, signed_remap); - } - break; - - case_16(NV4097_SET_TEX_COORD_CONTROL, 4): - //TODO - break; - - case_16(NV4097_SET_TEXTURE_IMAGE_RECT, 32): - { - GLTexture& tex = m_frame->GetTexture(index); - - const u16 height = args[0] & 0xffff; - const u16 width = args[0] >> 16; - CMD_LOG("width=%d, height=%d", width, height); - tex.SetRect(width, height); - } - break; - - case NV4097_SET_SURFACE_FORMAT: - { - u32 a0 = args[0]; - m_set_surface_format = true; - m_surface_color_format = a0 & 0x1f; - m_surface_depth_format = (a0 >> 5) & 0x7; - m_surface_type = (a0 >> 8) & 0xf; - m_surface_antialias = (a0 >> 12) & 0xf; - m_surface_width = (a0 >> 16) & 0xff; - m_surface_height = (a0 >> 24) & 0xff; - m_surface_pitch_a = args[1]; - m_surface_offset_a = args[2]; - m_surface_offset_z = args[3]; - m_surface_offset_b = args[4]; - m_surface_pitch_b = args[5]; - - /* - ConLog.Write("surface color format: 0x%x", m_surface_color_format); - ConLog.Write("surface depth format: 0x%x", m_surface_depth_format); - ConLog.Write("surface type: 0x%x", m_surface_type); - ConLog.Write("surface antialias: 0x%x", m_surface_antialias); - ConLog.Write("surface width: 0x%x", m_surface_width); - ConLog.Write("surface height: 0x%x", m_surface_height); - ConLog.Write("surface pitch a: 0x%x", m_surface_pitch_a); - ConLog.Write("surface offset a: 0x%x", m_surface_offset_a); - ConLog.Write("surface offset z: 0x%x", m_surface_offset_z); - ConLog.Write("surface offset b: 0x%x", m_surface_offset_b); - ConLog.Write("surface pitch b: 0x%x", m_surface_pitch_b); - if(m_surface_offset_a && m_set_context_dma_color_a) - { - u32 surface_addr = GetAddress(m_surface_offset_a, (m_context_dma_color_a - 0xfeed0000)); - auto& surface = (const CellGcmSurface&)Memory[surface_addr]; - ConLog.Write("context_dma_color_a=0x%x", m_context_dma_color_a); - ConLog.Write("context a: color format: 0x%x", surface.color_format); - ConLog.Write("context a: depth format: 0x%x", surface.depth_format); - ConLog.Write("context a: type: 0x%x", surface.type); - ConLog.Write("context a: antialias: 0x%x", surface.antialias); - ConLog.Write("context a: width: 0x%x", surface.width); - ConLog.Write("context a: height: 0x%x", surface.height); - } - else if(m_surface_offset_z && m_set_context_dma_z) - { - u32 surface_addr = GetAddress(m_surface_offset_z, m_context_dma_z); - auto& surface = (const CellGcmSurface&)Memory[surface_addr]; - ConLog.Write("m_surface_offset_z=0x%x", m_surface_offset_z); - ConLog.Write("context x: color format: 0x%x", surface.color_format); - ConLog.Write("context z: depth format: 0x%x", surface.depth_format); - ConLog.Write("context z: type: 0x%x", surface.type); - ConLog.Write("context z: antialias: 0x%x", surface.antialias); - ConLog.Write("context z: width: 0x%x", surface.width); - ConLog.Write("context z: height: 0x%x", surface.height); - - m_width = surface.width; - m_height = surface.height; - } - */ - - gcmBuffer* buffers = (gcmBuffer*)Memory.GetMemFromAddr(m_gcm_buffers_addr); - m_width = re(buffers[m_gcm_current_buffer].width); - m_height = re(buffers[m_gcm_current_buffer].height); - - if(1) - { - m_rbo.Create(2); - checkForGlError("m_rbo.Create"); - m_rbo.Bind(0); - m_rbo.Storage(GL_RGBA, m_width, m_height); - checkForGlError("m_rbo.Storage(GL_RGBA)"); - m_rbo.Bind(1); - m_rbo.Storage(GL_DEPTH24_STENCIL8, m_width, m_height); - checkForGlError("m_rbo.Storage(GL_DEPTH24_STENCIL8)"); - m_fbo.Create(); - checkForGlError("m_fbo.Create"); - m_fbo.Bind(); - m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0, m_rbo.GetId(0)); - checkForGlError("m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0)"); - m_fbo.Renderbuffer(GL_DEPTH_STENCIL_ATTACHMENT, m_rbo.GetId(1)); - checkForGlError("m_fbo.Renderbuffer(GL_DEPTH_STENCIL_ATTACHMENT)"); - } - //CMD_LOG("color_format=%d, depth_format=%d, type=%d, antialias=%d, width=%d, height=%d, pitch_a=%d, offset_a=0x%x, offset_z=0x%x, offset_b=0x%x, pitch_b=%d", - // color_format, depth_format, type, antialias, width, height, pitch_a, offset_a, offset_z, offset_b, pitch_b); - } - break; - - case NV4097_SET_COLOR_MASK_MRT: - { - } - break; - - case NV4097_SET_COLOR_MASK: - { - const u32 flags = args[0]; - - m_set_color_mask = true; - m_color_mask_a = flags & 0x1000000 ? true : false; - m_color_mask_r = flags & 0x0010000 ? true : false; - m_color_mask_g = flags & 0x0000100 ? true : false; - m_color_mask_b = flags & 0x0000001 ? true : false; - } - break; - - case NV4097_SET_ALPHA_TEST_ENABLE: - m_set_alpha_test = args[0] ? true : false; - break; - - case NV4097_SET_BLEND_ENABLE: - m_set_blend = args[0] ? true : false; - break; - - case NV4097_SET_DEPTH_BOUNDS_TEST_ENABLE: - m_set_depth_bounds_test = args[0] ? true : false; - break; - - case NV4097_SET_ALPHA_FUNC: - m_set_alpha_func = true; - m_alpha_func = args[0]; - - if(count >= 2) - { - m_set_alpha_ref = true; - m_alpha_ref = args[1]; - } - break; - - case NV4097_SET_ALPHA_REF: - m_set_alpha_ref = true; - m_alpha_ref = args[0]; - break; - - case NV4097_SET_CULL_FACE: - m_set_cull_face = true; - m_cull_face = args[0]; - break; - - case NV4097_SET_VIEWPORT_VERTICAL: - { - m_set_viewport_vertical = true; - m_viewport_y = args[0] & 0xffff; - m_viewport_h = args[0] >> 16; - } - break; - - case NV4097_SET_VIEWPORT_HORIZONTAL: - { - m_set_viewport_horizontal = true; - m_viewport_x = args[0] & 0xffff; - m_viewport_w = args[0] >> 16; - - if(count == 2) - { - m_set_viewport_vertical = true; - m_viewport_y = args[1] & 0xffff; - m_viewport_h = args[1] >> 16; - } - - CMD_LOG("x=%d, y=%d, w=%d, h=%d", m_viewport_x, m_viewport_y, m_viewport_w, m_viewport_h); - } - break; - - case NV4097_SET_CLIP_MIN: - { - const u32 clip_min = args[0]; - const u32 clip_max = args[1]; - - m_set_clip = true; - m_clip_min = (float&)clip_min; - m_clip_max = (float&)clip_max; - - CMD_LOG("clip_min=%.01f, clip_max=%.01f", m_clip_min, m_clip_max); - } - break; - - case NV4097_SET_DEPTH_FUNC: - m_set_depth_func = true; - m_depth_func = args[0]; - break; - - case NV4097_SET_DEPTH_TEST_ENABLE: - m_depth_test_enable = args[0] ? true : false; - break; - - case NV4097_SET_FRONT_POLYGON_MODE: - m_set_front_polygon_mode = true; - m_front_polygon_mode = args[0]; - //glPolygonMode(GL_FRONT, args[0]); - break; - - case NV4097_CLEAR_SURFACE: - { - u32 a0 = args[0]; - GLbitfield f = 0; - if (a0 & 0x1) f |= GL_DEPTH_BUFFER_BIT; - if (a0 & 0x2) f |= GL_STENCIL_BUFFER_BIT; - if (a0 & 0xF0) f |= GL_COLOR_BUFFER_BIT; - glClear(f); - checkForGlError("glClear"); - /* - if(m_set_clear_surface) - { - m_clear_surface_mask |= args[0]; - } - else - { - m_clear_surface_mask = args[0]; - m_set_clear_surface = true; - } - */ - } - break; - - case NV4097_SET_BLEND_FUNC_SFACTOR: - { - m_set_blend_sfactor = true; - m_blend_sfactor_rgb = args[0] & 0xffff; - m_blend_sfactor_alpha = args[0] >> 16; - - if(count >= 2) - { - m_set_blend_dfactor = true; - m_blend_dfactor_rgb = args[1] & 0xffff; - m_blend_dfactor_alpha = args[1] >> 16; - } - } - break; - - case NV4097_SET_BLEND_FUNC_DFACTOR: - { - m_set_blend_dfactor = true; - m_blend_dfactor_rgb = args[0] & 0xffff; - m_blend_dfactor_alpha = args[0] >> 16; - } - break; - - case_16(NV4097_SET_VERTEX_DATA_ARRAY_OFFSET, 4): - { - const u32 addr = GetAddress(args[0] & 0x7fffffff, args[0] >> 31); - CMD_LOG("num=%d, addr=0x%x", index, addr); - m_vertex_data[index].addr = addr; - } - break; - - case_16(NV4097_SET_VERTEX_DATA_ARRAY_FORMAT, 4): - { - u32 a0 = args[0]; - const u16 frequency = a0 >> 16; - const u8 stride = (a0 >> 8) & 0xff; - const u8 size = (a0 >> 4) & 0xf; - const u8 type = a0 & 0xf; - - CMD_LOG("index=%d, frequency=%d, stride=%d, size=%d, type=%d", - index, frequency, stride, size, type); - - VertexData& cv = m_vertex_data[index]; - cv.frequency = frequency; - cv.stride = stride; - cv.size = size; - cv.type = type; - } - break; - - case NV4097_DRAW_ARRAYS: - { - for(u32 c=0; c> 24) + 1; - - LoadVertexData(first, _count); - - m_draw_array_count += _count; - } - } - break; - - case NV4097_SET_INDEX_ARRAY_ADDRESS: - { - m_indexed_array.m_addr = GetAddress(args[0], args[1] & 0xf); - m_indexed_array.m_type = args[1] >> 4; - } - break; - - case NV4097_DRAW_INDEX_ARRAY: - { - for(u32 c=0; c> 24) + 1; - - if(first < m_indexed_array.m_first) m_indexed_array.m_first = first; - - for(u32 i=first; i<_count; ++i) - { - u32 index; - switch(m_indexed_array.m_type) - { - case 0: - { - int pos = m_indexed_array.m_data.GetCount(); - m_indexed_array.m_data.InsertRoomEnd(4); - index = Memory.Read32(m_indexed_array.m_addr + i * 4); - *(u32*)&m_indexed_array.m_data[pos] = index; - //ConLog.Warning("index 4: %d", *(u32*)&m_indexed_array.m_data[pos]); - } - break; - - case 1: - { - int pos = m_indexed_array.m_data.GetCount(); - m_indexed_array.m_data.InsertRoomEnd(2); - index = Memory.Read16(m_indexed_array.m_addr + i * 2); - //ConLog.Warning("index 2: %d", index); - *(u16*)&m_indexed_array.m_data[pos] = index; - } - break; - } - - if(index < m_indexed_array.index_min) m_indexed_array.index_min = index; - if(index > m_indexed_array.index_max) m_indexed_array.index_max = index; - } - - m_indexed_array.m_count += _count; - } - } - break; - - case NV4097_SET_BEGIN_END: - { - if(args[0]) - { - //begin - if(Emu.GetCallbackManager().m_exit_callback.m_callbacks.GetCount()) - { - //Emu.GetCallbackManager().m_exit_callback.Handle(0x0121, 0); - } - m_draw_mode = args[0] - 1; - } - else - { - //end - ExecCMD(); - if(Emu.GetCallbackManager().m_exit_callback.m_callbacks.GetCount()) - { - //Emu.GetCallbackManager().m_exit_callback.Handle(0x0122, 0); - } - } - } - break; - - case NV4097_SET_COLOR_CLEAR_VALUE: - { - const u32 color = args[0]; - //m_set_clear_color = true; - m_clear_color_a = (color >> 24) & 0xff; - m_clear_color_r = (color >> 16) & 0xff; - m_clear_color_g = (color >> 8) & 0xff; - m_clear_color_b = color & 0xff; - - glClearColor( - m_clear_color_r / 255.0f, - m_clear_color_g / 255.0f, - m_clear_color_b / 255.0f, - m_clear_color_a / 255.0f); - checkForGlError("glClearColor"); - } - break; - - case NV4097_SET_SHADER_PROGRAM: - { - m_cur_shader_prog = &m_shader_progs[m_cur_shader_prog_num++]; - m_cur_shader_prog->Delete(); - u32 a0 = args[0]; - m_cur_shader_prog->offset = a0 & ~0x3; - m_cur_shader_prog->addr = GetAddress(m_cur_shader_prog->offset, (a0 & 0x3) - 1); - } - break; - - case NV4097_SET_VERTEX_ATTRIB_OUTPUT_MASK: - { - //VertexData[0].prog.attributeOutputMask = args[0]; - //FragmentData.prog.attributeInputMask = args[0]/* & ~0x20*/; - } - break; - - case NV4097_SET_SHADER_CONTROL: - { - const u32 arg0 = args[0]; - - //const u8 controlTxp = (arg0 >> 15) & 0x1; - //FragmentData.prog.registerCount = arg0 >> 24; - //FragmentData.prog. - } - break; - - case NV4097_SET_TRANSFORM_PROGRAM_LOAD: - { - m_cur_vertex_prog = &m_vertex_progs[args[0]]; - m_cur_vertex_prog->Delete(); - - if(count == 2) - { - const u32 start = args[1]; - if(start) - ConLog.Warning("NV4097_SET_TRANSFORM_PROGRAM_LOAD: start = %d", start); - } - } - break; - - case NV4097_SET_TRANSFORM_PROGRAM: - { - if(!m_cur_vertex_prog) - { - ConLog.Warning("NV4097_SET_TRANSFORM_PROGRAM: m_cur_vertex_prog == NULL"); - break; - } - - for(u32 i=0; idata.AddCpy(args[i]); - } - break; - - case NV4097_SET_TRANSFORM_TIMEOUT: - - if(!m_cur_vertex_prog) - { - ConLog.Warning("NV4097_SET_TRANSFORM_TIMEOUT: m_cur_vertex_prog == NULL"); - break; - } - - //m_cur_vertex_prog->Decompile(); - break; - - case NV4097_SET_VERTEX_ATTRIB_INPUT_MASK: - //VertexData[0].prog.attributeInputMask = args[0]; - break; - - case NV4097_INVALIDATE_VERTEX_CACHE_FILE: - break; - - case NV4097_SET_TRANSFORM_CONSTANT_LOAD: - { - if((count - 1) % 4) - { - CMD_LOG("NV4097_SET_TRANSFORM_CONSTANT_LOAD [%d]", count); - break; - } - - for(u32 id = args[0], i = 1; i= 2) - { - m_set_stencil_func_ref = true; - m_stencil_func_ref = args[1]; - - if(count >= 3) - { - m_set_stencil_func_mask = true; - m_stencil_func_mask = args[2]; - } - } - break; - - case NV4097_SET_STENCIL_FUNC_REF: - m_set_stencil_func_ref = true; - m_stencil_func_ref = args[0]; - break; - - case NV4097_SET_STENCIL_FUNC_MASK: - m_set_stencil_func_mask = true; - m_stencil_func_mask = args[0]; - break; - - case NV4097_SET_STENCIL_OP_FAIL: - m_set_stencil_fail = true; - m_stencil_fail = args[0]; - if(count >= 2) - { - m_set_stencil_zfail = true; - m_stencil_zfail = args[1]; - - if(count >= 3) - { - m_set_stencil_zpass = true; - m_stencil_zpass = args[2]; - } - } - break; - - case NV4097_SET_TWO_SIDED_STENCIL_TEST_ENABLE: - m_set_two_sided_stencil_test_enable = args[0] ? true : false; - break; - - case NV4097_SET_BACK_STENCIL_MASK: - m_set_back_stencil_mask = true; - m_back_stencil_mask = args[0]; - break; - - case NV4097_SET_BACK_STENCIL_FUNC: - m_set_back_stencil_func = true; - m_back_stencil_func = args[0]; - if(count >= 2) - { - m_set_back_stencil_func_ref = true; - m_back_stencil_func_ref = args[1]; - - if(count >= 3) - { - m_set_back_stencil_func_mask = true; - m_back_stencil_func_mask = args[2]; - } - } - break; - - case NV4097_SET_BACK_STENCIL_FUNC_REF: - m_set_back_stencil_func_ref = true; - m_back_stencil_func_ref = args[0]; - break; - - case NV4097_SET_BACK_STENCIL_FUNC_MASK: - m_set_back_stencil_func_mask = true; - m_back_stencil_func_mask = args[0]; - break; - - case NV4097_SET_BACK_STENCIL_OP_FAIL: - m_set_stencil_fail = true; - m_stencil_fail = args[0]; - if(count >= 2) - { - m_set_back_stencil_zfail = true; - m_back_stencil_zfail = args[1]; - - if(count >= 3) - { - m_set_back_stencil_zpass = true; - m_back_stencil_zpass = args[2]; - } - } - break; - - case NV4097_SET_POLY_OFFSET_FILL_ENABLE: - if(args[0]) ConLog.Error("NV4097_SET_POLY_OFFSET_FILL_ENABLE"); - break; - - case NV4097_SET_RESTART_INDEX_ENABLE: - if(args[0]) ConLog.Error("NV4097_SET_RESTART_INDEX_ENABLE"); - break; - - case NV4097_SET_POINT_PARAMS_ENABLE: - if(args[0]) ConLog.Error("NV4097_SET_POINT_PARAMS_ENABLE"); - break; - - case NV4097_SET_POINT_SPRITE_CONTROL: - if(args[0] & 0x1) - { - ConLog.Error("NV4097_SET_POINT_SPRITE_CONTROL enable"); - } - break; - - case NV4097_SET_POLY_SMOOTH_ENABLE: - m_set_poly_smooth = args[0] ? true : false; - break; - - case NV4097_SET_BLEND_COLOR: - m_set_blend_color = true; - m_blend_color_r = args[0] & 0xff; - m_blend_color_g = (args[0] >> 8) & 0xff; - m_blend_color_b = (args[0] >> 16) & 0xff; - m_blend_color_a = (args[0] >> 24) & 0xff; - break; - - case NV4097_SET_BLEND_COLOR2: - if(args[0]) ConLog.Error("NV4097_SET_BLEND_COLOR2"); - break; - - case NV4097_SET_BLEND_EQUATION: - m_set_blend_equation = true; - m_blend_equation_rgb = args[0] & 0xffff; - m_blend_equation_alpha = args[0] >> 16; - break; - - case NV4097_SET_REDUCE_DST_COLOR: - if(args[0]) ConLog.Error("NV4097_SET_REDUCE_DST_COLOR"); - break; - - case NV4097_SET_DEPTH_MASK: - m_set_depth_mask = true; - m_depth_mask = args[0]; - break; - - case NV4097_SET_SCISSOR_VERTICAL: - { - m_set_scissor_vertical = true; - m_scissor_y = args[0] & 0xffff; - m_scissor_h = args[0] >> 16; - } - break; - - case NV4097_SET_SCISSOR_HORIZONTAL: - { - m_set_scissor_horizontal = true; - m_scissor_x = args[0] & 0xffff; - m_scissor_w = args[0] >> 16; - - if(count == 2) - { - m_set_scissor_vertical = true; - m_scissor_y = args[1] & 0xffff; - m_scissor_h = args[1] >> 16; - } - } - break; - - case NV4097_INVALIDATE_VERTEX_FILE: break; - - case NV4097_SET_VIEWPORT_OFFSET: - { - //TODO - } - break; - - case NV4097_SET_SEMAPHORE_OFFSET: - case NV406E_SEMAPHORE_OFFSET: - { - m_set_semaphore_offset = true; - m_semaphore_offset = args[0]; - } - break; - - case NV4097_BACK_END_WRITE_SEMAPHORE_RELEASE: - { - if(m_set_semaphore_offset) - { - m_set_semaphore_offset = false; - u32 value = args[0]; - value = (value & 0xff00ff00) | ((value & 0xff) << 16) | ((value >> 16) & 0xff); - - Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + m_semaphore_offset, value); - } - } - break; - - case NV406E_SEMAPHORE_RELEASE: - case NV4097_TEXTURE_READ_SEMAPHORE_RELEASE: - if(m_set_semaphore_offset) - { - m_set_semaphore_offset = false; - Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + m_semaphore_offset, args[0]); - } - break; - - case NV406E_SEMAPHORE_ACQUIRE: - { - //TODO - } - break; - - case NV4097_SET_RESTART_INDEX: - { - //TODO - } - break; - - case NV4097_INVALIDATE_L2: - { - //TODO - } - break; - - case NV4097_SET_CONTEXT_DMA_COLOR_A: - { - m_set_context_dma_color_a = true; - m_context_dma_color_a = args[0]; - } - break; - - case NV4097_SET_CONTEXT_DMA_COLOR_B: - { - m_set_context_dma_color_b = true; - m_context_dma_color_b = args[0]; - } - break; - - case NV4097_SET_CONTEXT_DMA_COLOR_C: - { - m_set_context_dma_color_c = true; - m_context_dma_color_c = args[0]; - } - break; - - case NV4097_SET_CONTEXT_DMA_ZETA: - { - m_set_context_dma_z = true; - m_context_dma_z = args[0]; - } - break; - - case NV4097_SET_SURFACE_PITCH_A: - { - //TODO - } - break; - - case NV4097_SET_SURFACE_PITCH_B: - { - //TODO - } - break; - - case NV4097_SET_SURFACE_PITCH_C: - { - //TODO - } - break; - - case NV4097_SET_SURFACE_PITCH_Z: - { - //TODO - } - break; - - case NV4097_SET_SHADER_WINDOW: - { - //TODO - } - break; - - case NV4097_SET_SURFACE_CLIP_VERTICAL: - { - u32 a0 = args[0]; - m_set_surface_clip_vertical = true; - m_surface_clip_y = a0; - m_surface_clip_h = a0 >> 16; - } - break; - - case NV4097_SET_SURFACE_CLIP_HORIZONTAL: - { - u32 a0 = args[0]; - - m_set_surface_clip_horizontal = true; - m_surface_clip_x = a0; - m_surface_clip_w = a0 >> 16; - - if(count >= 2) - { - u32 a1 = args[1]; - m_set_surface_clip_vertical = true; - m_surface_clip_y = a1; - m_surface_clip_h = a1 >> 16; - } - } - break; - - case NV4097_SET_WINDOW_OFFSET: - { - //TODO - } - break; - - case NV4097_SET_SURFACE_COLOR_TARGET: - { - //TODO - } - break; - - case NV4097_SET_ANTI_ALIASING_CONTROL: - { - //TODO - } - break; - - case NV4097_SET_LINE_SMOOTH_ENABLE: - m_set_line_smooth = args[0] ? true : false; - break; - - case NV4097_SET_LINE_WIDTH: - m_set_line_width = true; - m_line_width = args[0]; - break; - - case NV4097_SET_SHADE_MODE: - m_set_shade_mode = true; - m_shade_mode = args[0]; - break; - - case NV4097_SET_ZSTENCIL_CLEAR_VALUE: - { - u32 clear_valuei = args[0]; - //double clear_valuef = (double)clear_valuei / 0xffffffff; - //glClearDepth(clear_valuef); - glClearStencil(clear_valuei); - glClear(GL_STENCIL_BUFFER_BIT); - } - break; - - case NV4097_SET_ZCULL_CONTROL0: - { - m_set_depth_func = true; - m_depth_func = args[0] >> 4; - } - break; - - case NV4097_SET_ZCULL_CONTROL1: - { - //TODO - } - break; - - case NV4097_SET_SCULL_CONTROL: - { - u32 a0 = args[0]; - m_set_stencil_func = m_set_stencil_func_ref = m_set_stencil_func_mask = true; - - m_stencil_func = a0 & 0xffff; - m_stencil_func_ref = (a0 >> 16) & 0xff; - m_stencil_func_mask = (a0 >> 24) & 0xff; - } - break; - - case NV4097_SET_ZCULL_EN: - { - u32 a0 = args[0]; - - m_depth_test_enable = a0 & 0x1 ? true : false; - m_set_stencil_test = a0 & 0x2 ? true : false; - } - break; - - case NV4097_GET_REPORT: - { - u32 a0 = args[0]; - u8 type = a0 >> 24; - u32 offset = a0 & 0xffffff; - - u64 data; - switch(type) - { - case 1: - data = std::chrono::steady_clock::now().time_since_epoch().count(); - data *= 1000000; - break; - - default: - data = 0; - ConLog.Error("NV4097_GET_REPORT: bad type %d", type); - break; - } - - Memory.Write64(m_local_mem_addr + offset, data); - } - break; - - case NV3062_SET_OFFSET_DESTIN: - m_dst_offset = args[0]; - break; - - case NV308A_COLOR: - { - TransformConstant c; - c.id = m_dst_offset; - - if(count >= 1) - { - u32 a = args[0]; - a = a << 16 | a >> 16; - c.x = (float&)a; - } - - if(count >= 2) - { - u32 a = args[1]; - a = a << 16 | a >> 16; - c.y = (float&)a; - } - - if(count >= 3) - { - u32 a = args[2]; - a = a << 16 | a >> 16; - c.z = (float&)a; - } - - if(count >= 4) - { - u32 a = args[3]; - a = a << 16 | a >> 16; - c.w = (float&)a; - } - - if(count >= 5) - { - ConLog.Warning("NV308A_COLOR: count = %d", count); - } - - //ConLog.Warning("NV308A_COLOR: [%d]: %f, %f, %f, %f", c.id, c.x, c.y, c.z, c.w); - m_fragment_constants.AddCpy(c); - } - break; - - case NV308A_POINT: - //TODO - break; - - case NV3062_SET_COLOR_FORMAT: - { - m_color_format = args[0]; - m_color_format_src_pitch = args[1]; - m_color_format_dst_pitch = args[1] >> 16; - } - break; - - case NV3089_SET_COLOR_CONVERSION: - { - m_color_conv = args[0]; - m_color_conv_fmt = args[1]; - m_color_conv_op = args[2]; - m_color_conv_in_x = args[3]; - m_color_conv_in_y = args[3] >> 16; - m_color_conv_in_w = args[4]; - m_color_conv_in_h = args[4] >> 16; - m_color_conv_out_x = args[5]; - m_color_conv_out_y = args[5] >> 16; - m_color_conv_out_w = args[6]; - m_color_conv_out_h = args[6] >> 16; - m_color_conv_dsdx = args[7]; - m_color_conv_dtdy = args[8]; - } - break; - - case NV3089_IMAGE_IN_SIZE: - { - u16 w = args[0]; - u16 h = args[0] >> 16; - u16 pitch = args[1]; - u8 origin = args[1] >> 16; - u8 inter = args[1] >> 24; - u32 offset = args[2]; - u16 u = args[3]; - u16 v = args[3] >> 16; - - u8* pixels_src = &Memory[GetAddress(offset, m_context_dma_img_src - 0xfeed0000)]; - u8* pixels_dst = &Memory[GetAddress(m_dst_offset, m_context_dma_img_dst - 0xfeed0000)]; - - for(u16 y=0; y> 4) & 0xf; - m_clip_plane_2 = (a0 >> 8) & 0xf; - m_clip_plane_3 = (a0 >> 12) & 0xf; - m_clip_plane_4 = (a0 >> 16) & 0xf; - m_clip_plane_5 = a0 >> 20; - } - break; - - case NV4097_SET_FOG_PARAMS: - { - m_set_fog_params = true; - u32 a0 = args[0]; - u32 a1 = args[1]; - m_fog_param0 = (float&)a0; - m_fog_param1 = (float&)a1; - } - break; - - default: - { - wxString log = GetMethodName(cmd); - log += "("; - for(u32 i=0; iDecompile(); + if(m_fp_buf_num == -1) m_shader_prog.Decompile(*m_cur_shader_prog); if(!m_cur_vertex_prog) { @@ -1824,37 +371,34 @@ bool GLGSRender::LoadProgram() return false; } - if(m_program.IsCreated()) - { - m_program.Use(); - return true; - } //ConLog.Write("Create program"); - m_vp_buf_num = m_prog_buffer.SearchVp(*m_cur_vertex_prog); + m_vp_buf_num = m_prog_buffer.SearchVp(*m_cur_vertex_prog, m_vertex_prog); if(m_vp_buf_num == -1) { ConLog.Warning("VP not found in buffer!"); - m_cur_vertex_prog->Decompile(); + m_vertex_prog.Decompile(*m_cur_vertex_prog); } if(m_fp_buf_num == -1) { ConLog.Warning("FP not found in buffer!"); - m_cur_shader_prog->Wait(); - m_cur_shader_prog->Compile(); + m_shader_prog.Wait(); + m_shader_prog.Compile(); + checkForGlError("m_shader_prog.Compile"); wxFile f(wxGetCwd() + "/FragmentProgram.txt", wxFile::write); - f.Write(m_cur_shader_prog->shader); + f.Write(m_shader_prog.shader); } if(m_vp_buf_num == -1) { - m_cur_vertex_prog->Wait(); - m_cur_vertex_prog->Compile(); + m_vertex_prog.Wait(); + m_vertex_prog.Compile(); + checkForGlError("m_vertex_prog.Compile"); wxFile f(wxGetCwd() + "/VertexProgram.txt", wxFile::write); - f.Write(m_cur_vertex_prog->shader); + f.Write(m_vertex_prog.shader); } if(m_fp_buf_num != -1 && m_vp_buf_num != -1) @@ -1868,9 +412,9 @@ bool GLGSRender::LoadProgram() } else { - m_program.Create(m_cur_vertex_prog->id, m_cur_shader_prog->id); + m_program.Create(m_vertex_prog.id, m_shader_prog.id); checkForGlError("m_program.Create"); - m_prog_buffer.Add(m_program, *m_cur_shader_prog, *m_cur_vertex_prog); + m_prog_buffer.Add(m_program, m_shader_prog, *m_cur_shader_prog, m_vertex_prog, *m_cur_vertex_prog); checkForGlError("m_prog_buffer.Add"); m_program.Use(); @@ -1897,284 +441,193 @@ bool GLGSRender::LoadProgram() return true; } -void GLGSRender::ExecCMD() +void GLGSRender::WriteDepthBuffer() { - if(LoadProgram()) + if(!m_set_context_dma_z) { - if(m_set_surface_clip_horizontal && m_set_surface_clip_vertical) - { - //ConLog.Write("surface clip width: %d, height: %d, x: %d, y: %d", m_width, m_height, m_surface_clip_x, m_surface_clip_y); - } - - if(m_set_color_mask) - { - glColorMask(m_color_mask_r, m_color_mask_g, m_color_mask_b, m_color_mask_a); - checkForGlError("glColorMask"); - } - - if(m_set_viewport_horizontal && m_set_viewport_vertical) - { - glViewport(m_scissor_x, m_height-m_viewport_y-m_viewport_h, m_viewport_w, m_viewport_h); - checkForGlError("glViewport"); - } - - if(m_set_scissor_horizontal && m_set_scissor_vertical) - { - glScissor(m_scissor_x, m_height-m_scissor_y-m_scissor_h, m_scissor_w, m_scissor_h); - checkForGlError("glScissor"); - } - - if(m_set_clear_color) - { - glClearColor( - m_clear_color_r / 255.0f, - m_clear_color_g / 255.0f, - m_clear_color_b / 255.0f, - m_clear_color_a / 255.0f); - } - - if(m_set_clear_surface) - { - GLbitfield f = 0; - if (m_clear_surface_mask & 0x1) f |= GL_DEPTH_BUFFER_BIT; - if (m_clear_surface_mask & 0x2) f |= GL_STENCIL_BUFFER_BIT; - if (m_clear_surface_mask & 0xF0) f |= GL_COLOR_BUFFER_BIT; - glClear(f); - } - - if(m_set_front_polygon_mode) - { - glPolygonMode(GL_FRONT, m_front_polygon_mode); - checkForGlError("glPolygonMode"); - } - - Enable(m_depth_test_enable, GL_DEPTH_TEST); - Enable(m_set_alpha_test, GL_ALPHA_TEST); - Enable(m_set_depth_bounds_test, GL_DEPTH_CLAMP); - Enable(m_set_blend, GL_BLEND); - Enable(m_set_logic_op, GL_LOGIC_OP); - Enable(m_set_cull_face_enable, GL_CULL_FACE); - Enable(m_set_dither, GL_DITHER); - Enable(m_set_stencil_test, GL_STENCIL_TEST); - Enable(m_set_line_smooth, GL_LINE_SMOOTH); - Enable(m_set_poly_smooth, GL_POLYGON_SMOOTH); - checkForGlError("glEnable"); - - if(m_set_clip_plane) - { - Enable(m_clip_plane_0, GL_CLIP_PLANE0); - Enable(m_clip_plane_1, GL_CLIP_PLANE1); - Enable(m_clip_plane_2, GL_CLIP_PLANE2); - Enable(m_clip_plane_3, GL_CLIP_PLANE3); - Enable(m_clip_plane_4, GL_CLIP_PLANE4); - Enable(m_clip_plane_5, GL_CLIP_PLANE5); - - checkForGlError("m_set_clip_plane"); - } - - if(m_set_two_sided_stencil_test_enable) - { - if(m_set_back_stencil_fail && m_set_back_stencil_zfail && m_set_back_stencil_zpass) - { - glStencilOpSeparate(GL_BACK, m_back_stencil_fail, m_back_stencil_zfail, m_back_stencil_zpass); - checkForGlError("glStencilOpSeparate(GL_BACK)"); - } - - if(m_set_back_stencil_mask) - { - glStencilMaskSeparate(GL_BACK, m_back_stencil_mask); - checkForGlError("glStencilMaskSeparate(GL_BACK)"); - } - - if(m_set_back_stencil_func && m_set_back_stencil_func_ref && m_set_back_stencil_func_mask) - { - glStencilFuncSeparate(GL_BACK, m_back_stencil_func, m_back_stencil_func_ref, m_back_stencil_func_mask); - checkForGlError("glStencilFuncSeparate(GL_BACK)"); - } - } - - if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass) - { - glStencilOpSeparate(GL_FRONT, m_stencil_fail, m_stencil_zfail, m_stencil_zpass); - checkForGlError("glStencilOpSeparate(GL_FRONT)"); - } - - if(m_set_stencil_mask) - { - glStencilMaskSeparate(GL_FRONT, m_stencil_mask); - checkForGlError("glStencilMaskSeparate(GL_FRONT)"); - } - - if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask) - { - glStencilFuncSeparate(GL_FRONT, m_stencil_func, m_stencil_func_ref, m_stencil_func_mask); - checkForGlError("glStencilFuncSeparate(GL_FRONT)"); - } - - if(m_set_shade_mode) - { - glShadeModel(m_shade_mode); - checkForGlError("glShadeModel"); - } - - if(m_set_depth_mask) - { - glDepthMask(m_depth_mask); - checkForGlError("glDepthMask"); - } - - if(m_set_depth_func) - { - glDepthFunc(m_depth_func); - checkForGlError("glDepthFunc"); - } - - if(m_set_clip) - { - glDepthRangef(m_clip_min, m_clip_max); - checkForGlError("glDepthRangef"); - } - - if(m_set_line_width) - { - glLineWidth(m_line_width / 255.f); - checkForGlError("glLineWidth"); - } - - if(m_set_blend_equation) - { - glBlendEquationSeparate(m_blend_equation_rgb, m_blend_equation_alpha); - checkForGlError("glBlendEquationSeparate"); - } - - if(m_set_blend_sfactor && m_set_blend_dfactor) - { - glBlendFuncSeparate(m_blend_sfactor_rgb, m_blend_dfactor_rgb, m_blend_sfactor_alpha, m_blend_dfactor_alpha); - checkForGlError("glBlendFuncSeparate"); - } - - if(m_set_blend_color) - { - glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a); - checkForGlError("glBlendColor"); - } - - if(m_set_cull_face) - { - glCullFace(m_cull_face); - checkForGlError("glCullFace"); - } - - if(m_set_alpha_func && m_set_alpha_ref) - { - glAlphaFunc(m_alpha_func, m_alpha_ref); - checkForGlError("glAlphaFunc"); - } - - if(m_set_fog_mode) - { - glFogi(GL_FOG_MODE, m_fog_mode); - checkForGlError("glFogi(GL_FOG_MODE)"); - } - - if(m_set_fog_params) - { - glFogf(GL_FOG_START, m_fog_param0); - checkForGlError("glFogf(GL_FOG_START)"); - glFogf(GL_FOG_END, m_fog_param1); - checkForGlError("glFogf(GL_FOG_END)"); - } - - if(m_indexed_array.m_count && m_draw_array_count) - { - ConLog.Warning("m_indexed_array.m_count && draw_array_count"); - } - - for(u32 i=0; iGetTexture(i); - if(!tex.IsEnabled()) continue; - - glActiveTexture(GL_TEXTURE0 + i); - checkForGlError("glActiveTexture"); - tex.Create(); - tex.Bind(); - checkForGlError("tex.Bind"); - m_program.SetTex(i); - tex.Init(); - checkForGlError("tex.Init"); - //tex.Save(); - } - - m_vao.Bind(); - if(m_indexed_array.m_count) - { - LoadVertexData(m_indexed_array.index_min, m_indexed_array.index_max - m_indexed_array.index_min + 1); - } - - EnableVertexData(m_indexed_array.m_count ? true : false); - - InitVertexData(); - InitFragmentData(); - - if(m_indexed_array.m_count) - { - switch(m_indexed_array.m_type) - { - case 0: - glDrawElements(m_draw_mode, m_indexed_array.m_count, GL_UNSIGNED_INT, nullptr); - checkForGlError("glDrawElements #4"); - break; - - case 1: - glDrawElements(m_draw_mode, m_indexed_array.m_count, GL_UNSIGNED_SHORT, nullptr); - checkForGlError("glDrawElements #2"); - break; - - default: - ConLog.Error("Bad indexed array type (%d)", m_indexed_array.m_type); - break; - } - - DisableVertexData(); - m_indexed_array.Reset(); - } - - if(m_draw_array_count) - { - glDrawArrays(m_draw_mode, 0, m_draw_array_count); - checkForGlError("glDrawArrays"); - DisableVertexData(); - m_draw_array_count = 0; - } - - m_fragment_constants.Clear(); - } - else - { - ConLog.Error("LoadProgram failed."); - Emu.Pause(); + return; } - Reset(); + u32 address = GetAddress(m_surface_offset_z, m_context_dma_z - 0xfeed0000); + if(!Memory.IsGoodAddr(address)) + { + ConLog.Warning("Bad depth address: address=0x%x, offset=0x%x, dma=0x%x", address, m_surface_offset_z, m_context_dma_z); + return; + } + + glReadPixels(0, 0, m_width, m_height, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, &Memory[address]); + checkForGlError("glReadPixels"); + + GLuint depth_tex; + glGenTextures(1, &depth_tex); + glBindTexture(GL_TEXTURE_2D, depth_tex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &Memory[address]); + checkForGlError("glTexImage2D"); + glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &Memory[address]); + checkForGlError("glGetTexImage"); + glDeleteTextures(1, &depth_tex); } -void GLGSRender::Reset() +void GLGSRender::WriteColourBufferA() +{ + if(!m_set_context_dma_color_a) + { + return; + } + + u32 address = GetAddress(m_surface_offset_a, m_context_dma_color_a - 0xfeed0000); + if(!Memory.IsGoodAddr(address)) + { + ConLog.Warning("Bad colour buffer a address: address=0x%x, offset=0x%x, dma=0x%x", address, m_surface_offset_a, m_context_dma_color_a); + return; + } + + glReadBuffer(GL_COLOR_ATTACHMENT0); + checkForGlError("glReadBuffer(GL_COLOR_ATTACHMENT0)"); + glReadPixels(0, 0, m_width, m_height, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &Memory[address]); + checkForGlError("glReadPixels(GL_RGBA, GL_UNSIGNED_INT_8_8_8_8)"); +} + +void GLGSRender::WriteColourBufferB() +{ + if(!m_set_context_dma_color_b) + { + return; + } + + u32 address = GetAddress(m_surface_offset_b, m_context_dma_color_b - 0xfeed0000); + if(!Memory.IsGoodAddr(address)) + { + ConLog.Warning("Bad colour buffer b address: address=0x%x, offset=0x%x, dma=0x%x", address, m_surface_offset_b, m_context_dma_color_b); + return; + } + + glReadBuffer(GL_COLOR_ATTACHMENT1); + checkForGlError("glReadBuffer(GL_COLOR_ATTACHMENT1)"); + glReadPixels(0, 0, m_width, m_height, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &Memory[address]); + checkForGlError("glReadPixels(GL_RGBA, GL_UNSIGNED_INT_8_8_8_8)"); +} + +void GLGSRender::WriteColourBufferC() +{ + if(!m_set_context_dma_color_c) + { + return; + } + + u32 address = GetAddress(m_surface_offset_c, m_context_dma_color_c - 0xfeed0000); + if(!Memory.IsGoodAddr(address)) + { + ConLog.Warning("Bad colour buffer c address: address=0x%x, offset=0x%x, dma=0x%x", address, m_surface_offset_c, m_context_dma_color_c); + return; + } + + glReadBuffer(GL_COLOR_ATTACHMENT2); + checkForGlError("glReadBuffer(GL_COLOR_ATTACHMENT2)"); + glReadPixels(0, 0, m_width, m_height, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &Memory[address]); + checkForGlError("glReadPixels(GL_RGBA, GL_UNSIGNED_INT_8_8_8_8)"); +} + +void GLGSRender::WriteColourBufferD() +{ + if(!m_set_context_dma_color_d) + { + return; + } + + u32 address = GetAddress(m_surface_offset_d, m_context_dma_color_d - 0xfeed0000); + if(!Memory.IsGoodAddr(address)) + { + ConLog.Warning("Bad colour buffer d address: address=0x%x, offset=0x%x, dma=0x%x", address, m_surface_offset_d, m_context_dma_color_d); + return; + } + + glReadBuffer(GL_COLOR_ATTACHMENT3); + checkForGlError("glReadBuffer(GL_COLOR_ATTACHMENT3)"); + glReadPixels(0, 0, m_width, m_height, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &Memory[address]); + checkForGlError("glReadPixels(GL_RGBA, GL_UNSIGNED_INT_8_8_8_8)"); +} + +void GLGSRender::WriteBuffers() +{ + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + + switch(m_surface_colour_target) + { + case 0x0: + return; + + case 0x1: + WriteColourBufferA(); + break; + + case 0x2: + WriteColourBufferB(); + break; + + case 0x13: + WriteColourBufferA(); + WriteColourBufferB(); + break; + + case 0x17: + WriteColourBufferA(); + WriteColourBufferB(); + WriteColourBufferC(); + break; + + case 0x1f: + WriteColourBufferA(); + WriteColourBufferB(); + WriteColourBufferC(); + WriteColourBufferD(); + break; + } +} + +void GLGSRender::OnInit() +{ + m_draw_frames = 1; + m_skip_frames = 0; + m_width = 720; + m_height = 576; + + last_width = 0; + last_height = 0; + last_depth_format = 0; + + m_frame->Show(); +} + +void GLGSRender::OnInitThread() +{ + m_context = new wxGLContext(m_frame->GetCanvas()); + + m_frame->GetCanvas()->SetCurrent(*m_context); + InitProcTable(); + + glEnable(GL_TEXTURE_2D); + glEnable(GL_SCISSOR_TEST); + glSwapInterval(Ini.GSVSyncEnable.GetValue() ? 1 : 0); +} + +void GLGSRender::OnExitThread() +{ + m_program.Delete(); + m_rbo.Delete(); + m_fbo.Delete(); + m_vbo.Delete(); + m_vao.Delete(); + m_prog_buffer.Clear(); +} + +void GLGSRender::OnReset() { m_program.UnUse(); - //m_prog_buffer.Clear(); - if(m_cur_shader_prog) - m_cur_shader_prog->id = 0; - if(m_cur_vertex_prog) - m_cur_vertex_prog->id = 0; - - m_cur_shader_prog_num = 0; - m_transform_constants.Clear(); - for(uint i=0; iFlip(); } \ No newline at end of file diff --git a/rpcs3/Emu/GS/GL/GLGSRender.h b/rpcs3/Emu/GS/GL/GLGSRender.h index c77eade7b9..ca8ec5cd53 100644 --- a/rpcs3/Emu/GS/GL/GLGSRender.h +++ b/rpcs3/Emu/GS/GL/GLGSRender.h @@ -3,9 +3,9 @@ #include "Emu/GS/RSXThread.h" #include "wx/glcanvas.h" #include "GLBuffers.h" -#include "Program.h" +#include "GLProgram.h" #include "OpenGL.h" -#include "ProgramBuffer.h" +#include "GLProgramBuffer.h" #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "gl.lib") @@ -15,57 +15,10 @@ void checkForGlError(const char* situation); class GLTexture { - u32 m_width, m_height; u32 m_id; - u32 m_offset; - bool m_enabled; - - bool m_cubemap; - u8 m_dimension; - u32 m_format; - u16 m_mipmap; - - u32 m_pitch; - u16 m_depth; - - u16 m_minlod; - u16 m_maxlod; - u8 m_maxaniso; - - u8 m_wraps; - u8 m_wrapt; - u8 m_wrapr; - u8 m_unsigned_remap; - u8 m_zfunc; - u8 m_gamma; - u8 m_aniso_bias; - u8 m_signed_remap; - - u16 m_bias; - u8 m_min_filter; - u8 m_mag_filter; - u8 m_conv; - u8 m_a_signed; - u8 m_r_signed; - u8 m_g_signed; - u8 m_b_signed; - - u32 m_remap; public: - GLTexture() - : m_width(0), m_height(0) - , m_id(0) - , m_offset(0) - , m_enabled(false) - - , m_cubemap(false) - , m_dimension(0) - , m_format(0) - , m_mipmap(0) - , m_minlod(0) - , m_maxlod(1000) - , m_maxaniso(0) + GLTexture() : m_id(0) { } @@ -81,85 +34,9 @@ public: glGenTextures(1, &m_id); checkForGlError("GLTexture::Init() -> glGenTextures"); Bind(); - - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } } - void SetRect(const u32 width, const u32 height) - { - m_width = width; - m_height = height; - } - - u32 GetOffset() const { return m_offset; } - - void SetFormat(const bool cubemap, const u8 dimension, const u32 format, const u16 mipmap) - { - m_cubemap = cubemap; - m_dimension = dimension; - m_format = format; - m_mipmap = mipmap; - } - - void SetAddress(u8 wraps, u8 wrapt, u8 wrapr, u8 unsigned_remap, u8 zfunc, u8 gamma, u8 aniso_bias, u8 signed_remap) - { - m_wraps = wraps; - m_wrapt = wrapt; - m_wrapr = wrapr; - m_unsigned_remap = unsigned_remap; - m_zfunc = zfunc; - m_gamma = gamma; - m_aniso_bias = aniso_bias; - m_signed_remap = signed_remap; - } - - void SetControl0(const bool enable, const u16 minlod, const u16 maxlod, const u8 maxaniso) - { - m_enabled = enable; - m_minlod = minlod; - m_maxlod = maxlod; - m_maxaniso = maxaniso; - } - - void SetControl1(u32 remap) - { - m_remap = remap; - } - - void SetControl3(u16 depth, u32 pitch) - { - m_depth = depth; - m_pitch = pitch; - } - - void SetFilter(u16 bias, u8 min, u8 mag, u8 conv, u8 a_signed, u8 r_signed, u8 g_signed, u8 b_signed) - { - m_bias = bias; - m_min_filter = min; - m_mag_filter = mag; - m_conv = conv; - m_a_signed = a_signed; - m_r_signed = r_signed; - m_g_signed = g_signed; - m_b_signed = b_signed; - } - - u32 GetFormat() const { return m_format; } - - void SetOffset(const u32 offset) - { - m_offset = offset; - } - - wxSize GetRect() const - { - return wxSize(m_width, m_height); - } - int GetGlWrap(int wrap) { switch(wrap) @@ -176,12 +53,12 @@ public: return GL_REPEAT; } - void Init() + void Init(RSXTexture& tex) { Bind(); - if(!Memory.IsGoodAddr(m_offset)) + if(!Memory.IsGoodAddr(tex.GetOffset())) { - ConLog.Error("Bad texture address=0x%x", m_offset); + ConLog.Error("Bad texture address=0x%x", tex.GetOffset()); return; } //ConLog.Warning("texture addr = 0x%x, width = %d, height = %d, max_aniso=%d, mipmap=%d, remap=0x%x, zfunc=0x%x, wraps=0x%x, wrapt=0x%x, wrapr=0x%x, minlod=0x%x, maxlod=0x%x", @@ -189,17 +66,16 @@ public: //TODO: safe init checkForGlError("GLTexture::Init() -> glBindTexture"); - glPixelStorei(GL_PACK_ROW_LENGTH, m_pitch); + int format = tex.GetFormat() & ~(0x20 | 0x40); + bool is_swizzled = (tex.GetFormat() & 0x20) == 0; - int format = m_format & ~(0x20 | 0x40); - bool is_swizzled = (m_format & 0x20) == 0; - - char* pixels = (char*)Memory.GetMemFromAddr(m_offset); + glPixelStorei(GL_PACK_ALIGNMENT, tex.m_pitch); + char* pixels = (char*)Memory.GetMemFromAddr(tex.GetOffset()); switch(format) { case 0x81: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_BLUE, GL_UNSIGNED_BYTE, pixels); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.m_width, tex.m_height, 0, GL_BLUE, GL_UNSIGNED_BYTE, pixels); checkForGlError("GLTexture::Init() -> glTexImage2D"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); @@ -211,39 +87,39 @@ public: break; case 0x85: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, pixels); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.m_width, tex.m_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, pixels); checkForGlError("GLTexture::Init() -> glTexImage2D"); break; case 0x86: { - u32 size = ((m_width + 3) / 4) * ((m_height + 3) / 4) * 8; + u32 size = ((tex.m_width + 3) / 4) * ((tex.m_height + 3) / 4) * 8; - glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, m_width, m_height, 0, size, pixels); + glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, tex.m_width, tex.m_height, 0, size, pixels); checkForGlError("GLTexture::Init() -> glCompressedTexImage2D"); } break; case 0x87: { - u32 size = ((m_width + 3) / 4) * ((m_height + 3) / 4) * 16; + u32 size = ((tex.m_width + 3) / 4) * ((tex.m_height + 3) / 4) * 16; - glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, m_width, m_height, 0, size, pixels); + glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, tex.m_width, tex.m_height, 0, size, pixels); checkForGlError("GLTexture::Init() -> glCompressedTexImage2D"); } break; case 0x88: { - u32 size = ((m_width + 3) / 4) * ((m_height + 3) / 4) * 16; + u32 size = ((tex.m_width + 3) / 4) * ((tex.m_height + 3) / 4) * 16; - glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, m_width, m_height, 0, size, pixels); + glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, tex.m_width, tex.m_height, 0, size, pixels); checkForGlError("GLTexture::Init() -> glCompressedTexImage2D"); } break; case 0x94: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RED, GL_SHORT, pixels); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.m_width, tex.m_height, 0, GL_RED, GL_SHORT, pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_ONE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ONE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ONE); @@ -252,32 +128,30 @@ public: break; case 0x9a: - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_BGRA, GL_HALF_FLOAT, pixels); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.m_width, tex.m_height, 0, GL_BGRA, GL_HALF_FLOAT, pixels); checkForGlError("GLTexture::Init() -> glTexImage2D"); break; case 0x9e: { - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, pixels); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex.m_width, tex.m_height, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, pixels); checkForGlError("GLTexture::Init() -> glTexImage2D"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); } break; - default: ConLog.Error("Init tex error: Bad tex format (0x%x | 0x%x | 0x%x)", format, m_format & 0x20, m_format & 0x40); break; + default: ConLog.Error("Init tex error: Bad tex format (0x%x | 0x%x | 0x%x)", format, tex.GetFormat() & 0x20, tex.GetFormat() & 0x40); break; } - if(m_mipmap > 1) - { - glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); - } + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, tex.m_mipmap - 1); + glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, tex.m_mipmap > 1); if(format != 0x81 && format != 0x94) { - u8 remap_a = m_remap & 0x3; - u8 remap_r = (m_remap >> 2) & 0x3; - u8 remap_g = (m_remap >> 4) & 0x3; - u8 remap_b = (m_remap >> 6) & 0x3; + u8 remap_a = tex.m_remap & 0x3; + u8 remap_r = (tex.m_remap >> 2) & 0x3; + u8 remap_g = (tex.m_remap >> 4) & 0x3; + u8 remap_b = (tex.m_remap >> 6) & 0x3; static const int gl_remap[] = { @@ -292,7 +166,7 @@ public: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, gl_remap[remap_g]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, gl_remap[remap_b]); } - + static const int gl_tex_zfunc[] = { GL_NEVER, @@ -304,17 +178,16 @@ public: GL_GEQUAL, GL_ALWAYS, }; - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GetGlWrap(m_wraps)); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GetGlWrap(m_wrapt)); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GetGlWrap(m_wrapr)); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, gl_tex_zfunc[m_zfunc]); - - glTexEnvf(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, m_bias); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, m_minlod); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, m_maxlod); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, m_maxaniso); - + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GetGlWrap(tex.m_wraps)); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GetGlWrap(tex.m_wrapt)); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GetGlWrap(tex.m_wrapr)); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, gl_tex_zfunc[tex.m_zfunc]); + + glTexEnvi(GL_TEXTURE_FILTER_CONTROL, GL_TEXTURE_LOD_BIAS, tex.m_bias); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, tex.m_minlod); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, tex.m_maxlod); + static const int gl_tex_filter[] = { GL_NEAREST, @@ -327,20 +200,20 @@ public: GL_NEAREST, }; - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_tex_filter[m_min_filter]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_tex_filter[m_mag_filter]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_tex_filter[tex.m_min_filter]); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_tex_filter[tex.m_mag_filter]); //Unbind(); } - void Save(const wxString& name) + void Save(RSXTexture& tex, const wxString& name) { - if(!m_id || !m_offset || !m_width || !m_height) return; + if(!m_id || !tex.m_offset || !tex.m_width || !tex.m_height) return; - u32* alldata = new u32[m_width * m_height]; + u32* alldata = new u32[tex.m_width * tex.m_height]; Bind(); - switch(m_format & ~(0x20 | 0x40)) + switch(tex.m_format & ~(0x20 | 0x40)) { case 0x81: glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, alldata); @@ -357,15 +230,15 @@ public: { wxFile f(name + ".raw", wxFile::write); - f.Write(alldata, m_width * m_height * 4); + f.Write(alldata, tex.m_width * tex.m_height * 4); } - u8* data = new u8[m_width * m_height * 3]; - u8* alpha = new u8[m_width * m_height]; + u8* data = new u8[tex.m_width * tex.m_height * 3]; + u8* alpha = new u8[tex.m_width * tex.m_height]; u8* src = (u8*)alldata; u8* dst_d = data; u8* dst_a = alpha; - for(u32 i=0; i m_data; - int m_type; - u32 m_first; - u32 m_count; - u32 m_addr; - u32 index_max; - u32 index_min; - - IndexArrayData() - { - Reset(); - } - - void Reset() - { - m_type = 0; - m_first = ~0; - m_count = 0; - m_addr = 0; - index_min = ~0; - index_max = 0; - m_data.Clear(); - } }; struct GLGSFrame : public GSFrame { wxGLCanvas* canvas; - GLTexture m_textures[16]; u32 m_frames; GLGSFrame(); @@ -478,7 +298,6 @@ struct GLGSFrame : public GSFrame void Flip(); wxGLCanvas* GetCanvas() const { return canvas; } - GLTexture& GetTexture(const u32 index) { return m_textures[index]; } virtual void SetViewport(int x, int y, u32 w, u32 h); @@ -486,63 +305,137 @@ private: virtual void OnSize(wxSizeEvent& event); }; -struct GLRSXThread : public ThreadBase +class PostDrawObj { - wxWindow* m_parent; - Stack call_stack; +protected: + GLShaderProgram m_fp; + GLVertexProgram m_vp; + GLProgram m_program; + GLfbo m_fbo; + GLrbo m_rbo; - GLRSXThread(wxWindow* parent); +public: + virtual void Draw() + { + static bool s_is_initialized = false; - virtual void Task(); + if(!s_is_initialized) + { + s_is_initialized = true; + Initialize(); + } + } + + virtual void InitializeShaders() = 0; + virtual void InitializeLocations() = 0; + + void Initialize() + { + InitializeShaders(); + m_fp.Compile(); + m_vp.Compile(); + m_program.Create(m_vp.id, m_fp.id); + m_program.Use(); + InitializeLocations(); + } +}; + +class DrawCursorObj : PostDrawObj +{ + u32 m_tex_id; + +public: + DrawCursorObj() : m_tex_id(0) + { + } + + virtual void Draw() + { + PostDrawObj::Draw(); + } + + virtual void InitializeShaders() + { + m_vp.shader = + "layout (location = 0) in vec4 in_pos;\n" + "layout (location = 1) in vec2 in_tc;\n" + "out vec2 tc;\n" + "\n" + "void main()\n" + "{\n" + " tc = in_tc;\n" + " gl_Position = in_pos;\n" + "}\n"; + + m_fp.shader = + "#version 330\n" + "\n" + "in vec2 tc;\n" + "uniform sampler2D tex;\n" + "layout (location = 0) out vec4 res;\n" + "\n" + "void main()\n" + "{\n" + " res = texture(tex, tc);\n" + "}\n"; + } + + void SetTexture(void* pixels, int width, int hight) + { + glUniform2i(1, width, hight); + if(!m_tex_id) + { + glGenTextures(1, &m_tex_id); + } + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_tex_id); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, hight, 0, GL_BLUE, GL_UNSIGNED_BYTE, pixels); + m_program.SetTex(0); + } + + void SetPosition(float x, float y, float z = 0.0f) + { + glUniform4f(0, x, y, z, 1.0f); + } + + void InitializeLocations() + { + } }; class GLGSRender : public wxWindow , public GSRender - , public ExecRSXCMDdata { -public: - static const uint m_vertex_count = 16; - static const uint m_fragment_count = 16; - static const uint m_textures_count = 16; - private: - GLRSXThread* m_rsx_thread; - - IndexArrayData m_indexed_array; - - ShaderProgram m_shader_progs[m_fragment_count]; - ShaderProgram* m_cur_shader_prog; - int m_cur_shader_prog_num; - VertexData m_vertex_data[m_vertex_count]; Array m_vdata; - VertexProgram m_vertex_progs[m_vertex_count]; - VertexProgram* m_cur_vertex_prog; - Array m_transform_constants; - Array m_fragment_constants; + ArrayF m_post_draw_objs; - Program m_program; + GLProgram m_program; int m_fp_buf_num; int m_vp_buf_num; - int m_draw_array_count; - int m_draw_mode; - ProgramBuffer m_prog_buffer; + GLProgramBuffer m_prog_buffer; - u32 m_width; - u32 m_height; + GLShaderProgram m_shader_prog; + GLVertexProgram m_vertex_prog; + + GLTexture m_gl_textures[m_textures_count]; GLvao m_vao; GLvbo m_vbo; GLrbo m_rbo; GLfbo m_fbo; + wxGLContext* m_context; + public: GLGSFrame* m_frame; u32 m_draw_frames; u32 m_skip_frames; GLGSRender(); - ~GLGSRender(); + virtual ~GLGSRender(); private: void EnableVertexData(bool indexed_draw=false); @@ -552,16 +445,22 @@ private: void InitFragmentData(); void Enable(bool enable, const u32 cap); - virtual void Init(const u32 ioAddress, const u32 ioSize, const u32 ctrlAddress, const u32 localAddress); - virtual void Draw(); virtual void Close(); bool LoadProgram(); + void WriteDepthBuffer(); + void WriteColourBufferA(); + void WriteColourBufferB(); + void WriteColourBufferC(); + void WriteColourBufferD(); + void WriteBuffers(); -public: - void DoCmd(const u32 fcmd, const u32 cmd, mem32_ptr_t& args, const u32 count); - void CloseOpenGL(); + void DrawObjects(); +protected: + virtual void OnInit(); + virtual void OnInitThread(); + virtual void OnExitThread(); + virtual void OnReset(); virtual void ExecCMD(); - virtual void Reset(); - void Init(); + virtual void Flip(); }; \ No newline at end of file diff --git a/rpcs3/Emu/GS/GL/GLProcTable.tbl b/rpcs3/Emu/GS/GL/GLProcTable.tbl index 6aeb2c8be4..ca6f1ca1f2 100644 --- a/rpcs3/Emu/GS/GL/GLProcTable.tbl +++ b/rpcs3/Emu/GS/GL/GLProcTable.tbl @@ -25,7 +25,7 @@ OPENGL_PROC(PFNGLDELETEPROGRAMPROC, DeleteProgram); OPENGL_PROC(PFNGLATTACHSHADERPROC, AttachShader); OPENGL_PROC(PFNGLGETATTRIBLOCATIONPROC, GetAttribLocation); OPENGL_PROC(PFNGLLINKPROGRAMPROC, LinkProgram); -OPENGL_PROC(PFNGLBINDFRAGDATALOCATIONPROC, BindFragDataLocation); +//OPENGL_PROC(PFNGLBINDFRAGDATALOCATIONPROC, BindFragDataLocation); OPENGL_PROC(PFNGLBINDATTRIBLOCATIONPROC, BindAttribLocation); OPENGL_PROC(PFNGLGETUNIFORMLOCATIONPROC, GetUniformLocation); OPENGL_PROC(PFNGLGETPROGRAMIVPROC, GetProgramiv); @@ -38,6 +38,9 @@ OPENGL_PROC(PFNGLVERTEXATTRIB3SVPROC, VertexAttrib3sv); OPENGL_PROC(PFNGLVERTEXATTRIB4SVPROC, VertexAttrib4sv); OPENGL_PROC(PFNGLVERTEXATTRIB4IVPROC, VertexAttrib4iv); OPENGL_PROC(PFNGLVERTEXATTRIB1FPROC, VertexAttrib1f); +OPENGL_PROC(PFNGLVERTEXATTRIB2FPROC, VertexAttrib2f); +OPENGL_PROC(PFNGLVERTEXATTRIB3FPROC, VertexAttrib3f); +OPENGL_PROC(PFNGLVERTEXATTRIB4FPROC, VertexAttrib4f); OPENGL_PROC(PFNGLVERTEXATTRIB2FVPROC, VertexAttrib2fv); OPENGL_PROC(PFNGLVERTEXATTRIB3FVPROC, VertexAttrib3fv); OPENGL_PROC(PFNGLVERTEXATTRIB4FVPROC, VertexAttrib4fv); @@ -95,4 +98,5 @@ OPENGL_PROC(PFNGLFRAMEBUFFERTEXTURE1DPROC, FramebufferTexture1D); OPENGL_PROC(PFNGLFRAMEBUFFERTEXTURE2DPROC, FramebufferTexture2D); OPENGL_PROC(PFNGLFRAMEBUFFERTEXTURE3DPROC, FramebufferTexture3D); OPENGL_PROC(PFNGLFRAMEBUFFERRENDERBUFFERPROC, FramebufferRenderbuffer); -OPENGL_PROC(PFNGLBLITFRAMEBUFFERPROC, BlitFramebuffer); \ No newline at end of file +OPENGL_PROC(PFNGLBLITFRAMEBUFFERPROC, BlitFramebuffer); +OPENGL_PROC(PFNGLDRAWBUFFERSPROC, DrawBuffers); \ No newline at end of file diff --git a/rpcs3/Emu/GS/GL/Program.cpp b/rpcs3/Emu/GS/GL/GLProgram.cpp similarity index 86% rename from rpcs3/Emu/GS/GL/Program.cpp rename to rpcs3/Emu/GS/GL/GLProgram.cpp index 4730f33805..1f0c21539b 100644 --- a/rpcs3/Emu/GS/GL/Program.cpp +++ b/rpcs3/Emu/GS/GL/GLProgram.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" -#include "Program.h" +#include "GLProgram.h" #include "GLGSRender.h" -Program::Program() : id(0) +GLProgram::GLProgram() : id(0) { } -int Program::GetLocation(const wxString& name) +int GLProgram::GetLocation(const wxString& name) { for(u32 i=0; i 0; } -void Program::Create(const u32 vp, const u32 fp) +void GLProgram::Create(const u32 vp, const u32 fp) { if(IsCreated()) Delete(); id = glCreateProgram(); @@ -74,19 +74,19 @@ void Program::Create(const u32 vp, const u32 fp) } } -void Program::UnUse() +void GLProgram::UnUse() { id = 0; m_locations.Clear(); } -void Program::Use() +void GLProgram::Use() { glUseProgram(id); checkForGlError("glUseProgram"); } -void Program::SetTex(u32 index) +void GLProgram::SetTex(u32 index) { int loc = GetLocation(wxString::Format("tex%u", index)); checkForGlError(wxString::Format("GetLocation(tex%u)", index)); @@ -94,7 +94,7 @@ void Program::SetTex(u32 index) checkForGlError(wxString::Format("SetTex(%u - %d - %d)", id, index, loc)); } -void Program::Delete() +void GLProgram::Delete() { if(!IsCreated()) return; glDeleteProgram(id); diff --git a/rpcs3/Emu/GS/GL/Program.h b/rpcs3/Emu/GS/GL/GLProgram.h similarity index 77% rename from rpcs3/Emu/GS/GL/Program.h rename to rpcs3/Emu/GS/GL/GLProgram.h index 71fb597ff6..b06e216767 100644 --- a/rpcs3/Emu/GS/GL/Program.h +++ b/rpcs3/Emu/GS/GL/GLProgram.h @@ -1,8 +1,8 @@ #pragma once -#include "VertexProgram.h" -#include "FragmentProgram.h" +#include "GLVertexProgram.h" +#include "GLFragmentProgram.h" -struct Program +struct GLProgram { private: struct Location @@ -16,7 +16,7 @@ private: public: u32 id; - Program(); + GLProgram(); int GetLocation(const wxString& name); bool IsCreated() const; diff --git a/rpcs3/Emu/GS/GL/ProgramBuffer.cpp b/rpcs3/Emu/GS/GL/GLProgramBuffer.cpp similarity index 54% rename from rpcs3/Emu/GS/GL/ProgramBuffer.cpp rename to rpcs3/Emu/GS/GL/GLProgramBuffer.cpp index 859bad2bce..76b6e0f602 100644 --- a/rpcs3/Emu/GS/GL/ProgramBuffer.cpp +++ b/rpcs3/Emu/GS/GL/GLProgramBuffer.cpp @@ -1,14 +1,14 @@ #include "stdafx.h" -#include "ProgramBuffer.h" +#include "GLProgramBuffer.h" -int ProgramBuffer::SearchFp(ShaderProgram& fp) +int GLProgramBuffer::SearchFp(const RSXShaderProgram& rsx_fp, GLShaderProgram& gl_fp) { for(u32 i=0; i fp_data; + Array vp_data; + ArrayString fp_shader; + ArrayString vp_shader; +}; + +struct GLProgramBuffer +{ + Array m_buf; + + int SearchFp(const RSXShaderProgram& rsx_fp, GLShaderProgram& gl_fp); + int SearchVp(const RSXVertexProgram& rsx_vp, GLVertexProgram& gl_vp); + + bool CmpVP(const u32 a, const u32 b) const; + bool CmpFP(const u32 a, const u32 b) const; + + u32 GetProg(u32 fp, u32 vp) const; + + void Add(GLProgram& prog, GLShaderProgram& gl_fp, RSXShaderProgram& rsx_fp, GLVertexProgram& gl_vp, RSXVertexProgram& rsx_vp); + void Clear(); +}; \ No newline at end of file diff --git a/rpcs3/Emu/GS/GL/ShaderParam.h b/rpcs3/Emu/GS/GL/GLShaderParam.h similarity index 57% rename from rpcs3/Emu/GS/GL/ShaderParam.h rename to rpcs3/Emu/GS/GL/GLShaderParam.h index c0f91e38fb..fe1991cede 100644 --- a/rpcs3/Emu/GS/GL/ShaderParam.h +++ b/rpcs3/Emu/GS/GL/GLShaderParam.h @@ -1,7 +1,7 @@ #pragma once #include "OpenGL.h" -enum ParamFlag +enum GLParamFlag { PARAM_IN, PARAM_OUT, @@ -10,13 +10,13 @@ enum ParamFlag PARAM_NONE, }; -struct ParamItem +struct GLParamItem { ArrayString name; ArrayString location; ArrayString value; - ParamItem(const wxString& _name, int _location, const wxString& _value = wxEmptyString) + GLParamItem(const wxString& _name, int _location, const wxString& _value = wxEmptyString) : name(_name) , location(_location > -1 ? wxString::Format("layout (location = %d) ", _location) : "") , value(_value) @@ -24,13 +24,13 @@ struct ParamItem } }; -struct ParamType +struct GLParamType { - const ParamFlag flag; + const GLParamFlag flag; ArrayString type; - Array items; + Array items; - ParamType(const ParamFlag _flag, const wxString& _type) + GLParamType(const GLParamFlag _flag, const wxString& _type) : type(_type) , flag(_flag) { @@ -68,11 +68,11 @@ struct ParamType } }; -struct ParamArray +struct GLParamArray { - Array params; + Array params; - ParamType* SearchParam(const wxString& type) + GLParamType* SearchParam(const wxString& type) { for(u32 i=0; iSearchName(name); } - wxString AddParam(const ParamFlag flag, wxString type, const wxString& name, const wxString& value) + wxString AddParam(const GLParamFlag flag, wxString type, const wxString& name, const wxString& value) { type = GetParamFlag(flag) + type; - ParamType* t = SearchParam(type); + GLParamType* t = SearchParam(type); if(t) { - if(!t->SearchName(name)) t->items.Move(new ParamItem(name, -1, value)); + if(!t->SearchName(name)) t->items.Move(new GLParamItem(name, -1, value)); } else { const u32 num = params.GetCount(); - params.Move(new ParamType(flag, type)); - params[num].items.Move(new ParamItem(name, -1, value)); + params.Move(new GLParamType(flag, type)); + params[num].items.Move(new GLParamItem(name, -1, value)); } return name; } - wxString AddParam(const ParamFlag flag, wxString type, const wxString& name, int location = -1) + wxString AddParam(const GLParamFlag flag, wxString type, const wxString& name, int location = -1) { type = GetParamFlag(flag) + type; - ParamType* t = SearchParam(type); + GLParamType* t = SearchParam(type); if(t) { - if(!t->SearchName(name)) t->items.Move(new ParamItem(name, location)); + if(!t->SearchName(name)) t->items.Move(new GLParamItem(name, location)); } else { const u32 num = params.GetCount(); - params.Move(new ParamType(flag, type)); - params[num].items.Move(new ParamItem(name, location)); + params.Move(new GLParamType(flag, type)); + params[num].items.Move(new GLParamItem(name, location)); } return name; diff --git a/rpcs3/Emu/GS/GL/VertexProgram.cpp b/rpcs3/Emu/GS/GL/GLVertexProgram.cpp similarity index 77% rename from rpcs3/Emu/GS/GL/VertexProgram.cpp rename to rpcs3/Emu/GS/GL/GLVertexProgram.cpp index 83cad2e739..50b9fc30b7 100644 --- a/rpcs3/Emu/GS/GL/VertexProgram.cpp +++ b/rpcs3/Emu/GS/GL/GLVertexProgram.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" -#include "VertexProgram.h" +#include "GLVertexProgram.h" -wxString VertexDecompilerThread::GetMask(bool is_sca) +wxString GLVertexDecompilerThread::GetMask(bool is_sca) { wxString ret = wxEmptyString; @@ -23,17 +23,17 @@ wxString VertexDecompilerThread::GetMask(bool is_sca) return ret.IsEmpty() || ret == "xyzw" ? wxEmptyString : ("." + ret); } -wxString VertexDecompilerThread::GetVecMask() +wxString GLVertexDecompilerThread::GetVecMask() { return GetMask(false); } -wxString VertexDecompilerThread::GetScaMask() +wxString GLVertexDecompilerThread::GetScaMask() { return GetMask(true); } -wxString VertexDecompilerThread::GetDST(bool isSca) +wxString GLVertexDecompilerThread::GetDST(bool isSca) { static const wxString reg_table[] = { @@ -73,7 +73,7 @@ wxString VertexDecompilerThread::GetDST(bool isSca) return ret; } -wxString VertexDecompilerThread::GetSRC(const u32 n, bool isSca) +wxString GLVertexDecompilerThread::GetSRC(const u32 n, bool isSca) { static const wxString reg_table[] = { @@ -151,7 +151,7 @@ wxString VertexDecompilerThread::GetSRC(const u32 n, bool isSca) return ret; } -void VertexDecompilerThread::AddCode(bool is_sca, wxString code, bool src_mask) +void GLVertexDecompilerThread::AddCode(bool is_sca, wxString code, bool src_mask) { if(d0.cond == 0) return; enum @@ -215,17 +215,17 @@ void VertexDecompilerThread::AddCode(bool is_sca, wxString code, bool src_mask) main += "\t" + code + ";\n"; } -void VertexDecompilerThread::AddVecCode(const wxString& code, bool src_mask) +void GLVertexDecompilerThread::AddVecCode(const wxString& code, bool src_mask) { AddCode(false, code, src_mask); } -void VertexDecompilerThread::AddScaCode(const wxString& code) +void GLVertexDecompilerThread::AddScaCode(const wxString& code) { AddCode(true, code, false); } -wxString VertexDecompilerThread::BuildCode() +wxString GLVertexDecompilerThread::BuildCode() { wxString p = wxEmptyString; @@ -243,7 +243,7 @@ wxString VertexDecompilerThread::BuildCode() return wxString::Format(prot, p, main); } -void VertexDecompilerThread::Task() +void GLVertexDecompilerThread::Task() { for(u32 i=0;;) { @@ -295,10 +295,10 @@ void VertexDecompilerThread::Task() case 0x02: AddVecCode("(" + GetSRC(0) + " * " + GetSRC(1) + ")"); break; //MUL case 0x03: AddVecCode("(" + GetSRC(0) + " + " + GetSRC(2) + ")"); break; //ADD case 0x04: AddVecCode("(" + GetSRC(0) + " * " + GetSRC(1) + " + " + GetSRC(2) + ")"); break; //MAD - case 0x05: AddVecCode("vec4(dot(" + GetSRC(0) + ".xyz, " + GetSRC(1) + ".xyz)).xxxx"); break; //DP3 - case 0x06: AddVecCode("vec4(dot(vec4(" + GetSRC(0) + ".xyz, 1), " + GetSRC(1) + ")).xxxx"); break; //DPH - case 0x07: AddVecCode("vec4(dot(" + GetSRC(0) + ", " + GetSRC(1) + ")).xxxx"); break; //DP4 - case 0x08: AddVecCode("vec4(distance(" + GetSRC(0) + ", " + GetSRC(1) + ")).xxxx"); break; //DST + case 0x05: AddVecCode("vec2(dot(" + GetSRC(0) + ".xyz, " + GetSRC(1) + ".xyz), 0).xxxx"); break; //DP3 + case 0x06: AddVecCode("vec2(dot(vec4(" + GetSRC(0) + ".xyz, 1), " + GetSRC(1) + "), 0).xxxx"); break; //DPH + case 0x07: AddVecCode("vec2(dot(" + GetSRC(0) + ", " + GetSRC(1) + "), 0).xxxx"); break; //DP4 + case 0x08: AddVecCode("vec2(distance(" + GetSRC(0) + ", " + GetSRC(1) + "), 0).xxxx"); break; //DST case 0x09: AddVecCode("min(" + GetSRC(0) + ", " + GetSRC(1) + ")"); break; //MIN case 0x0a: AddVecCode("max(" + GetSRC(0) + ", " + GetSRC(1) + ")"); break; //MAX case 0x0b: AddVecCode("vec4(lessThan(" + GetSRC(0) + ", " + GetSRC(1) + "))"); break; //SLT @@ -306,11 +306,11 @@ void VertexDecompilerThread::Task() case 0x0e: AddVecCode("fract(" + GetSRC(0) + ")"); break; //FRC case 0x0f: AddVecCode("floor(" + GetSRC(0) + ")"); break; //FLR case 0x10: AddVecCode("vec4(equal(" + GetSRC(0) + ", " + GetSRC(1) + "))"); break; //SEQ - //case 0x11: AddVecCode("vec4(0.0f, 0.0f, 0.0f, 0.0f)"); break; //SFL + //case 0x11: AddVecCode("vec4(equal(" + GetSRC(0) + ", vec4(0, 0, 0, 0)))"); break; //SFL case 0x12: AddVecCode("vec4(greaterThan(" + GetSRC(0) + ", " + GetSRC(1) + "))"); break; //SGT case 0x13: AddVecCode("vec4(lessThanEqual(" + GetSRC(0) + ", " + GetSRC(1) + "))"); break; //SLE case 0x14: AddVecCode("vec4(notEqual(" + GetSRC(0) + ", " + GetSRC(1) + "))"); break; //SNE - //case 0x15: AddVecCode("vec4(1.0f, 1.0f, 1.0f, 1.0f)"); break; //STR + //case 0x15: AddVecCode("vec4(notEqual(" + GetSRC(0) + ", vec4(0, 0, 0, 0)))"); break; //STR case 0x16: AddVecCode("sign(" + GetSRC(0) + ")"); break; //SSG default: @@ -327,13 +327,13 @@ void VertexDecompilerThread::Task() main = wxEmptyString; } -VertexProgram::VertexProgram() +GLVertexProgram::GLVertexProgram() : m_decompiler_thread(nullptr) , id(0) { } -VertexProgram::~VertexProgram() +GLVertexProgram::~GLVertexProgram() { if(m_decompiler_thread) { @@ -350,10 +350,10 @@ VertexProgram::~VertexProgram() Delete(); } -void VertexProgram::Decompile() +void GLVertexProgram::Decompile(RSXVertexProgram& prog) { #if 0 - VertexDecompilerThread(data, shader, parr).Entry(); + GLVertexDecompilerThread(data, shader, parr).Entry(); #else if(m_decompiler_thread) { @@ -367,12 +367,12 @@ void VertexProgram::Decompile() m_decompiler_thread = nullptr; } - m_decompiler_thread = new VertexDecompilerThread(data, shader, parr); + m_decompiler_thread = new GLVertexDecompilerThread(prog.data, shader, parr); m_decompiler_thread->Start(); #endif } -void VertexProgram::Compile() +void GLVertexProgram::Compile() { if(id) glDeleteShader(id); @@ -407,9 +407,8 @@ void VertexProgram::Compile() } -void VertexProgram::Delete() +void GLVertexProgram::Delete() { - data.Clear(); parr.params.Clear(); shader.Clear(); @@ -419,79 +418,3 @@ void VertexProgram::Delete() id = 0; } } - -VertexData::VertexData() - : frequency(0) - , stride(0) - , size(0) - , type(0) - , addr(0) - , data() -{ -} - -void VertexData::Reset() -{ - frequency = 0; - stride = 0; - size = 0; - type = 0; - addr = 0; - data.ClearF(); -} - -void VertexData::Load(u32 start, u32 count) -{ - if(!addr) return; - - const u32 tsize = GetTypeSize(); - - data.SetCount((start + count) * tsize * size); - - for(u32 i=start; i& m_data; - ParamArray& m_parr; + GLParamArray& m_parr; - VertexDecompilerThread(Array& data, wxString& shader, ParamArray& parr) + GLVertexDecompilerThread(Array& data, wxString& shader, GLParamArray& parr) : ThreadBase(false, "Vertex Shader Decompiler Thread") , m_data(data) , m_shader(shader) @@ -152,17 +153,16 @@ struct VertexDecompilerThread : public ThreadBase virtual void Task(); }; -struct VertexProgram -{ - wxString shader; +struct GLVertexProgram +{ + GLVertexDecompilerThread* m_decompiler_thread; + + GLVertexProgram(); + ~GLVertexProgram(); + + GLParamArray parr; u32 id; - VertexDecompilerThread* m_decompiler_thread; - - VertexProgram(); - ~VertexProgram(); - - Array data; - ParamArray parr; + wxString shader; void Wait() { @@ -171,27 +171,8 @@ struct VertexProgram m_decompiler_thread->Wait(); } } - void Decompile(); + + void Decompile(RSXVertexProgram& prog); void Compile(); void Delete(); }; - -struct VertexData -{ - u32 frequency; - u32 stride; - u32 size; - u32 type; - u32 addr; - u32 constant_count; - - Array data; - - VertexData(); - - void Reset(); - bool IsEnabled() { return size > 0; } - void Load(u32 start, u32 count); - - u32 GetTypeSize(); -}; \ No newline at end of file diff --git a/rpcs3/Emu/GS/GL/ProgramBuffer.h b/rpcs3/Emu/GS/GL/ProgramBuffer.h deleted file mode 100644 index 8d66dca99b..0000000000 --- a/rpcs3/Emu/GS/GL/ProgramBuffer.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -#include "Program.h" - -struct BufferInfo -{ - u32 prog_id; - u32 fp_id; - u32 vp_id; - Array fp_data; - Array vp_data; - ArrayString fp_shader; - ArrayString vp_shader; -}; - -struct ProgramBuffer -{ - Array m_buf; - - int SearchFp(ShaderProgram& fp); - int SearchVp(VertexProgram& vp); - - bool CmpVP(const u32 a, const u32 b) const; - bool CmpFP(const u32 a, const u32 b) const; - - u32 GetProg(u32 fp, u32 vp) const; - - void Add(Program& prog, ShaderProgram& fp, VertexProgram& vp); - void Clear(); -}; \ No newline at end of file diff --git a/rpcs3/Emu/GS/GSManager.cpp b/rpcs3/Emu/GS/GSManager.cpp index 456aa9125e..ad6ac2bedf 100644 --- a/rpcs3/Emu/GS/GSManager.cpp +++ b/rpcs3/Emu/GS/GSManager.cpp @@ -32,6 +32,7 @@ void GSManager::Close() if(m_render) { m_render->Close(); + delete m_render; m_render = nullptr; } } diff --git a/rpcs3/Emu/GS/GSRender.cpp b/rpcs3/Emu/GS/GSRender.cpp index 75664a9a1a..5a1fc4bceb 100644 --- a/rpcs3/Emu/GS/GSRender.cpp +++ b/rpcs3/Emu/GS/GSRender.cpp @@ -76,28 +76,6 @@ void GSFrame::SetSize(int width, int height) } */ - -GSRender::GSRender() - : m_ctrl(nullptr) - , m_flip_status(0) - , m_flip_mode(CELL_GCM_DISPLAY_VSYNC) - , m_main_mem_addr(0) -{ -} - -u32 GSRender::GetAddress(u32 offset, u8 location) -{ - switch(location) - { - case CELL_GCM_LOCATION_LOCAL: return m_local_mem_addr + offset; - case CELL_GCM_LOCATION_MAIN: return m_main_mem_addr + offset; - } - - ConLog.Error("GetAddress(offset=0x%x, location=0x%x", location); - assert(0); - return 0; -} - GSLockCurrent::GSLockCurrent(GSLockType type) : GSLock(Emu.GetGSManager().GetRender(), type) { } \ No newline at end of file diff --git a/rpcs3/Emu/GS/GSRender.h b/rpcs3/Emu/GS/GSRender.h index 8c79740f2e..3ae017cb39 100644 --- a/rpcs3/Emu/GS/GSRender.h +++ b/rpcs3/Emu/GS/GSRender.h @@ -1,16 +1,6 @@ #pragma once #include "Emu/GS/GCM.h" -#include "Emu/SysCalls/Callback.h" -#include "rpcs3.h" - -enum Method -{ - CELL_GCM_METHOD_FLAG_NON_INCREMENT = 0x40000000, - CELL_GCM_METHOD_FLAG_JUMP = 0x20000000, - CELL_GCM_METHOD_FLAG_CALL = 0x00000002, - CELL_GCM_METHOD_FLAG_RETURN = 0x00020000, -}; - +#include "Emu/GS/RSXThread.h" wxSize AspectRatio(wxSize rs, const wxSize as); @@ -40,138 +30,13 @@ private: DECLARE_EVENT_TABLE(); }; -struct CellGcmSurface +struct GSRender : public RSXThread { - u8 type; - u8 antialias; - - u8 color_format; - u8 color_target; - u8 color_location[4]; - u32 color_offset[4]; - u32 color_pitch[4]; - - u8 depth_format; - u8 depth_location; - u16 pad; - u32 depth_offset; - u32 depth_pitch; - - u16 width; - u16 height; - u16 x; - u16 y; -}; - -struct CellGcmReportData -{ - u64 timer; - u32 value; - u32 pad; -}; - -struct CellGcmZcullInfo -{ - u32 region; - u32 size; - u32 start; - u32 offset; - u32 status0; - u32 status1; -}; - -struct CellGcmTileInfo -{ - u32 tile; - u32 limit; - u32 pitch; - u32 format; -}; - -struct GcmZcullInfo -{ - u32 m_offset; - u32 m_width; - u32 m_height; - u32 m_cullStart; - u32 m_zFormat; - u32 m_aaFormat; - u32 m_zCullDir; - u32 m_zCullFormat; - u32 m_sFunc; - u32 m_sRef; - u32 m_sMask; - bool m_binded; - - GcmZcullInfo() + virtual ~GSRender() { - memset(this, 0, sizeof(*this)); - } -}; - -struct GcmTileInfo -{ - u8 m_location; - u32 m_offset; - u32 m_size; - u32 m_pitch; - u8 m_comp; - u16 m_base; - u8 m_bank; - bool m_binded; - - GcmTileInfo() - { - memset(this, 0, sizeof(*this)); } - CellGcmTileInfo Pack() - { - CellGcmTileInfo ret; - - re(ret.tile, (m_location + 1) | (m_bank << 4) | ((m_offset / 0x10000) << 16) | (m_location << 31)); - re(ret.limit, ((m_offset + m_size - 1) / 0x10000) << 16 | (m_location << 31)); - re(ret.pitch, (m_pitch / 0x100) << 8); - re(ret.format, m_base | ((m_base + ((m_size - 1) / 0x10000)) << 13) | (m_comp << 26) | (1 << 30)); - - return ret; - } -}; - -static const int g_tiles_count = 15; - -struct GSRender -{ - u32 m_ioAddress, m_ioSize, m_ctrlAddress; - CellGcmControl* m_ctrl; - wxCriticalSection m_cs_main; - wxSemaphore m_sem_flush; - wxSemaphore m_sem_flip; - int m_flip_status; - int m_flip_mode; - volatile bool m_draw; - Callback m_flip_handler; - - GcmTileInfo m_tiles[g_tiles_count]; - - u32 m_tiles_addr; - u32 m_zculls_addr; - u32 m_gcm_buffers_addr; - u32 m_gcm_buffers_count; - u32 m_gcm_current_buffer; - u32 m_ctxt_addr; - u32 m_report_main_addr; - - u32 m_local_mem_addr, m_main_mem_addr; - Array m_main_mem_info; - - GSRender(); - - virtual void Init(const u32 ioAddress, const u32 ioSize, const u32 ctrlAddress, const u32 localAddress)=0; - virtual void Draw()=0; virtual void Close()=0; - - u32 GetAddress(u32 offset, u8 location); }; enum GSLockType diff --git a/rpcs3/Emu/GS/Null/NullGSRender.h b/rpcs3/Emu/GS/Null/NullGSRender.h index 8b911eece4..032d34fc5c 100644 --- a/rpcs3/Emu/GS/Null/NullGSRender.h +++ b/rpcs3/Emu/GS/Null/NullGSRender.h @@ -24,168 +24,53 @@ private: } }; -struct NullRSXThread : public wxThread -{ - wxWindow* m_parent; - Stack call_stack; - - NullRSXThread(wxWindow* parent); - - virtual void OnExit(); - void Start(); - ExitCode Entry(); -}; - class NullGSRender : public wxWindow , public GSRender { -private: - NullRSXThread* m_rsx_thread; - public: NullGSFrame* m_frame; - NullGSRender() - : m_frame(nullptr) - , m_rsx_thread(nullptr) + NullGSRender() : m_frame(nullptr) { - m_draw = false; m_frame = new NullGSFrame(); } - ~NullGSRender() + virtual ~NullGSRender() { - Close(); m_frame->Close(); } private: - virtual void Init(const u32 ioAddress, const u32 ioSize, const u32 ctrlAddress, const u32 localAddress) + virtual void OnInit() { - if(m_frame->IsShown()) return; - - m_frame->SetSize(740, 480); m_frame->Show(); - - m_ioAddress = ioAddress; - m_ctrlAddress = ctrlAddress; - m_ioSize = ioSize; - m_local_mem_addr = localAddress; - m_ctrl = (CellGcmControl*)Memory.GetMemFromAddr(m_ctrlAddress); - - (m_rsx_thread = new NullRSXThread(this))->Start(); } -public: - void DoCmd(const u32 fcmd, const u32 cmd, mem32_ptr_t& args, const u32 count) + virtual void OnInitThread() { - switch(cmd) - { - case NV406E_SET_REFERENCE: - m_ctrl->ref = re32(args[0]); - break; - } } - virtual void Draw() + virtual void OnExitThread() + { + } + + virtual void OnReset() + { + } + + virtual void ExecCMD() + { + } + + virtual void Flip() { - //if(m_frame && !m_frame->IsBeingDeleted()) m_frame->Draw(); - m_draw = true; } virtual void Close() { - if(m_rsx_thread) m_rsx_thread->Delete(); + if(IsAlive()) Stop(); + if(m_frame->IsShown()) m_frame->Hide(); - m_ctrl = NULL; } }; - -NullRSXThread::NullRSXThread(wxWindow* parent) - : wxThread(wxTHREAD_DETACHED) - , m_parent(parent) -{ -} - -void NullRSXThread::OnExit() -{ - call_stack.Clear(); -} - -void NullRSXThread::Start() -{ - Create(); - Run(); -} - -wxThread::ExitCode NullRSXThread::Entry() -{ - ConLog.Write("Null RSX thread entry"); - - NullGSRender& p = *(NullGSRender*)m_parent; - - while(!TestDestroy() && p.m_frame && !p.m_frame->IsBeingDeleted()) - { - wxCriticalSectionLocker lock(p.m_cs_main); - - if(p.m_ctrl->get == p.m_ctrl->put || !Emu.IsRunning()) - { - SemaphorePostAndWait(p.m_sem_flush); - - if(p.m_draw) - { - p.m_draw = false; - p.m_flip_status = 0; - if(SemaphorePostAndWait(p.m_sem_flip)) continue; - } - - Sleep(1); - continue; - } - - const u32 get = re(p.m_ctrl->get); - const u32 cmd = Memory.Read32(p.m_ioAddress + get); - const u32 count = (cmd >> 18) & 0x7ff; - - if(cmd & CELL_GCM_METHOD_FLAG_JUMP) - { - p.m_ctrl->get = re32(cmd & ~(CELL_GCM_METHOD_FLAG_JUMP | CELL_GCM_METHOD_FLAG_NON_INCREMENT)); - ConLog.Warning("rsx jump!"); - continue; - } - if(cmd & CELL_GCM_METHOD_FLAG_CALL) - { - call_stack.Push(get + 4); - p.m_ctrl->get = re32(cmd & ~CELL_GCM_METHOD_FLAG_CALL); - ConLog.Warning("rsx call!"); - continue; - } - if(cmd & CELL_GCM_METHOD_FLAG_RETURN) - { - p.m_ctrl->get = re32(call_stack.Pop()); - ConLog.Warning("rsx return!"); - continue; - } - if(cmd & CELL_GCM_METHOD_FLAG_NON_INCREMENT) - { - //ConLog.Warning("non increment cmd! 0x%x", cmd); - } - - if(cmd == 0) - { - ConLog.Warning("null cmd: addr=0x%x, put=0x%x, get=0x%x", p.m_ioAddress + get, re(p.m_ctrl->put), get); - Emu.Pause(); - continue; - } - - p.DoCmd(cmd, cmd & 0x3ffff, mem32_ptr_t(p.m_ioAddress + get + 4), count); - re(p.m_ctrl->get, get + (count + 1) * 4); - } - - ConLog.Write("Null RSX thread exit..."); - - call_stack.Clear(); - - return (ExitCode)0; -} \ No newline at end of file diff --git a/rpcs3/Emu/GS/RSXFragmentProgram.h b/rpcs3/Emu/GS/RSXFragmentProgram.h new file mode 100644 index 0000000000..ef627a07b8 --- /dev/null +++ b/rpcs3/Emu/GS/RSXFragmentProgram.h @@ -0,0 +1,15 @@ +#pragma once + +struct RSXShaderProgram +{ + u32 size; + u32 addr; + u32 offset; + + RSXShaderProgram() + : size(0) + , addr(0) + , offset(0) + { + } +}; \ No newline at end of file diff --git a/rpcs3/Emu/GS/RSXThread.cpp b/rpcs3/Emu/GS/RSXThread.cpp index 910a7ed0e4..1ccdf4750d 100644 --- a/rpcs3/Emu/GS/RSXThread.cpp +++ b/rpcs3/Emu/GS/RSXThread.cpp @@ -1,17 +1,1399 @@ #include "stdafx.h" #include "RSXThread.h" -RSXThread::RSXThread(CellGcmControl* ctrl, u32 ioAddress) - : m_ctrl(*ctrl) - , m_ioAddress(ioAddress) +RSXVertexData::RSXVertexData() + : frequency(0) + , stride(0) + , size(0) + , type(0) + , addr(0) + , data() { } +void RSXVertexData::Reset() +{ + frequency = 0; + stride = 0; + size = 0; + type = 0; + addr = 0; + data.ClearF(); +} + +void RSXVertexData::Load(u32 start, u32 count) +{ + if(!addr) return; + + const u32 tsize = GetTypeSize(); + + data.SetCount((start + count) * tsize * size); + + for(u32 i=start; iref = re32(args[0]); + break; + + case_16(NV4097_SET_TEXTURE_OFFSET, 0x20): + { + RSXTexture& tex = m_textures[index]; + const u32 offset = args[0]; + u32 a1 = args[1]; + u8 location = (a1 & 0x3) - 1; + const bool cubemap = (a1 >> 2) & 0x1; + const u8 dimension = (a1 >> 4) & 0xf; + const u8 format = (a1 >> 8) & 0xff; + const u16 mipmap = (a1 >> 16) & 0xffff; + CMD_LOG("index = %d, offset=0x%x, location=0x%x, cubemap=0x%x, dimension=0x%x, format=0x%x, mipmap=0x%x", + index, offset, location, cubemap, dimension, format, mipmap); + + if(location == 2) + { + ConLog.Error("Bad texture location."); + location = 1; + } + u32 tex_addr = GetAddress(offset, location); + //ConLog.Warning("texture addr = 0x%x #offset = 0x%x, location=%d", tex_addr, offset, location); + tex.SetOffset(tex_addr); + tex.SetFormat(cubemap, dimension, format, mipmap); + } + break; + + case_16(NV4097_SET_TEXTURE_CONTROL0, 0x20): + { + RSXTexture& tex = m_textures[index]; + u32 a0 = args[0]; + bool enable = a0 >> 31 ? true : false; + u16 minlod = (a0 >> 19) & 0xfff; + u16 maxlod = (a0 >> 7) & 0xfff; + u8 maxaniso = (a0 >> 2) & 0x7; + tex.SetControl0(enable, minlod, maxlod, maxaniso); + } + break; + + case_16(NV4097_SET_VERTEX_DATA4UB_M, 4): + { + u32 v = args[0]; + u8 v0 = v; + u8 v1 = v >> 8; + u8 v2 = v >> 16; + u8 v3 = v >> 24; + + m_vertex_data[index].size = 4; + m_vertex_data[index].type = 4; + m_vertex_data[index].data.AddCpy(v0); + m_vertex_data[index].data.AddCpy(v1); + m_vertex_data[index].data.AddCpy(v2); + m_vertex_data[index].data.AddCpy(v3); + //ConLog.Warning("index = %d, v0 = 0x%x, v1 = 0x%x, v2 = 0x%x, v3 = 0x%x", index, v0, v1, v2, v3); + } + break; + + case_16(NV4097_SET_VERTEX_DATA2F_M, 8): + { + u32 a0 = args[0]; + u32 a1 = args[1]; + + float v0 = (float&)a0; + float v1 = (float&)a1; + + m_vertex_data[index].type = 2; + m_vertex_data[index].size = 2; + m_vertex_data[index].data.SetCount(sizeof(float) * 2); + (float&)m_vertex_data[index].data[sizeof(float)*0] = v0; + (float&)m_vertex_data[index].data[sizeof(float)*1] = v1; + + //ConLog.Warning("index = %d, v0 = %f, v1 = %f", index, v0, v1); + } + break; + + case_16(NV4097_SET_VERTEX_DATA4F_M, 16): + { + u32 a0 = args[0]; + u32 a1 = args[1]; + u32 a2 = args[2]; + u32 a3 = args[3]; + + float v0 = (float&)a0; + float v1 = (float&)a1; + float v2 = (float&)a2; + float v3 = (float&)a3; + + m_vertex_data[index].type = 2; + m_vertex_data[index].size = 4; + m_vertex_data[index].data.SetCount(sizeof(float) * 4); + (float&)m_vertex_data[index].data[sizeof(float)*0] = v0; + (float&)m_vertex_data[index].data[sizeof(float)*1] = v1; + (float&)m_vertex_data[index].data[sizeof(float)*2] = v2; + (float&)m_vertex_data[index].data[sizeof(float)*3] = v3; + + //ConLog.Warning("index = %d, v0 = %f, v1 = %f, v2 = %f, v3 = %f", index, v0, v1, v2, v3); + } + break; + + case_16(NV4097_SET_TEXTURE_CONTROL1, 0x20): + { + RSXTexture& tex = m_textures[index]; + tex.SetControl1(args[0]); + } + break; + + case_16(NV4097_SET_TEXTURE_CONTROL3, 4): + { + RSXTexture& tex = m_textures[index]; + u32 a0 = args[0]; + u32 pitch = a0 & 0xFFFFF; + u16 depth = a0 >> 20; + tex.SetControl3(pitch, depth); + } + break; + + case_16(NV4097_SET_TEXTURE_FILTER, 0x20): + { + RSXTexture& tex = m_textures[index]; + u32 a0 = args[0]; + u16 bias = a0 & 0x1fff; + u8 conv = (a0 >> 13) & 0xf; + u8 min = (a0 >> 16) & 0x7; + u8 mag = (a0 >> 24) & 0x7; + u8 a_signed = (a0 >> 28) & 0x1; + u8 r_signed = (a0 >> 29) & 0x1; + u8 g_signed = (a0 >> 30) & 0x1; + u8 b_signed = (a0 >> 31) & 0x1; + + tex.SetFilter(bias, min, mag, conv, a_signed, r_signed, g_signed, b_signed); + } + break; + + case_16(NV4097_SET_TEXTURE_ADDRESS, 0x20): + { + RSXTexture& tex = m_textures[index]; + + u32 a0 = args[0]; + u8 wraps = a0 & 0xf; + u8 aniso_bias = (a0 >> 4) & 0xf; + u8 wrapt = (a0 >> 8) & 0xf; + u8 unsigned_remap = (a0 >> 12) & 0xf; + u8 wrapr = (a0 >> 16) & 0xf; + u8 gamma = (a0 >> 20) & 0xf; + u8 signed_remap = (a0 >> 24) & 0xf; + u8 zfunc = a0 >> 28; + + tex.SetAddress(wraps, wrapt, wrapr, unsigned_remap, zfunc, gamma, aniso_bias, signed_remap); + } + break; + + case_16(NV4097_SET_TEX_COORD_CONTROL, 4): + //TODO + break; + + case_16(NV4097_SET_TEXTURE_IMAGE_RECT, 32): + { + RSXTexture& tex = m_textures[index]; + + const u16 height = args[0] & 0xffff; + const u16 width = args[0] >> 16; + CMD_LOG("width=%d, height=%d", width, height); + tex.SetRect(width, height); + } + break; + + case NV4097_SET_SURFACE_FORMAT: + { + u32 a0 = args[0]; + m_set_surface_format = true; + m_surface_color_format = a0 & 0x1f; + m_surface_depth_format = (a0 >> 5) & 0x7; + m_surface_type = (a0 >> 8) & 0xf; + m_surface_antialias = (a0 >> 12) & 0xf; + m_surface_width = (a0 >> 16) & 0xff; + m_surface_height = (a0 >> 24) & 0xff; + m_surface_pitch_a = args[1]; + m_surface_offset_a = args[2]; + m_surface_offset_z = args[3]; + m_surface_offset_b = args[4]; + m_surface_pitch_b = args[5]; + + gcmBuffer* buffers = (gcmBuffer*)Memory.GetMemFromAddr(m_gcm_buffers_addr); + m_width = re(buffers[m_gcm_current_buffer].width); + m_height = re(buffers[m_gcm_current_buffer].height); + } + break; + + case NV4097_SET_COLOR_MASK_MRT: + { + } + break; + + case NV4097_SET_COLOR_MASK: + { + const u32 flags = args[0]; + + m_set_color_mask = true; + m_color_mask_a = flags & 0x1000000 ? true : false; + m_color_mask_r = flags & 0x0010000 ? true : false; + m_color_mask_g = flags & 0x0000100 ? true : false; + m_color_mask_b = flags & 0x0000001 ? true : false; + } + break; + + case NV4097_SET_ALPHA_TEST_ENABLE: + m_set_alpha_test = args[0] ? true : false; + break; + + case NV4097_SET_BLEND_ENABLE: + m_set_blend = args[0] ? true : false; + break; + + case NV4097_SET_DEPTH_BOUNDS_TEST_ENABLE: + m_set_depth_bounds_test = args[0] ? true : false; + break; + + case NV4097_SET_ALPHA_FUNC: + m_set_alpha_func = true; + m_alpha_func = args[0]; + + if(count >= 2) + { + m_set_alpha_ref = true; + m_alpha_ref = args[1]; + } + break; + + case NV4097_SET_ALPHA_REF: + m_set_alpha_ref = true; + m_alpha_ref = args[0]; + break; + + case NV4097_SET_CULL_FACE: + m_set_cull_face = true; + m_cull_face = args[0]; + break; + + case NV4097_SET_VIEWPORT_VERTICAL: + { + m_set_viewport_vertical = true; + m_viewport_y = args[0] & 0xffff; + m_viewport_h = args[0] >> 16; + } + break; + + case NV4097_SET_VIEWPORT_HORIZONTAL: + { + m_set_viewport_horizontal = true; + m_viewport_x = args[0] & 0xffff; + m_viewport_w = args[0] >> 16; + + if(count == 2) + { + m_set_viewport_vertical = true; + m_viewport_y = args[1] & 0xffff; + m_viewport_h = args[1] >> 16; + } + + CMD_LOG("x=%d, y=%d, w=%d, h=%d", m_viewport_x, m_viewport_y, m_viewport_w, m_viewport_h); + } + break; + + case NV4097_SET_CLIP_MIN: + { + const u32 clip_min = args[0]; + const u32 clip_max = args[1]; + + m_set_clip = true; + m_clip_min = (float&)clip_min; + m_clip_max = (float&)clip_max; + + CMD_LOG("clip_min=%.01f, clip_max=%.01f", m_clip_min, m_clip_max); + } + break; + + case NV4097_SET_DEPTH_FUNC: + m_set_depth_func = true; + m_depth_func = args[0]; + break; + + case NV4097_SET_DEPTH_TEST_ENABLE: + m_depth_test_enable = args[0] ? true : false; + break; + + case NV4097_SET_FRONT_POLYGON_MODE: + m_set_front_polygon_mode = true; + m_front_polygon_mode = args[0]; + break; + + case NV4097_CLEAR_SURFACE: + { + u32 a0 = args[0]; + + if(a0 & 0x01) m_clear_surface_z = m_clear_z; + if(a0 & 0x02) m_clear_surface_s = m_clear_s; + if(a0 & 0x10) m_clear_surface_color_r = m_clear_color_r; + if(a0 & 0x20) m_clear_surface_color_g = m_clear_color_g; + if(a0 & 0x40) m_clear_surface_color_b = m_clear_color_b; + if(a0 & 0x80) m_clear_surface_color_a = m_clear_color_a; + + m_clear_surface_mask |= a0; + } + break; + + case NV4097_SET_BLEND_FUNC_SFACTOR: + { + m_set_blend_sfactor = true; + m_blend_sfactor_rgb = args[0] & 0xffff; + m_blend_sfactor_alpha = args[0] >> 16; + + if(count >= 2) + { + m_set_blend_dfactor = true; + m_blend_dfactor_rgb = args[1] & 0xffff; + m_blend_dfactor_alpha = args[1] >> 16; + } + } + break; + + case NV4097_SET_BLEND_FUNC_DFACTOR: + { + m_set_blend_dfactor = true; + m_blend_dfactor_rgb = args[0] & 0xffff; + m_blend_dfactor_alpha = args[0] >> 16; + } + break; + + case_16(NV4097_SET_VERTEX_DATA_ARRAY_OFFSET, 4): + { + const u32 addr = GetAddress(args[0] & 0x7fffffff, args[0] >> 31); + CMD_LOG("num=%d, addr=0x%x", index, addr); + m_vertex_data[index].addr = addr; + } + break; + + case_16(NV4097_SET_VERTEX_DATA_ARRAY_FORMAT, 4): + { + u32 a0 = args[0]; + const u16 frequency = a0 >> 16; + const u8 stride = (a0 >> 8) & 0xff; + const u8 size = (a0 >> 4) & 0xf; + const u8 type = a0 & 0xf; + + CMD_LOG("index=%d, frequency=%d, stride=%d, size=%d, type=%d", + index, frequency, stride, size, type); + + RSXVertexData& cv = m_vertex_data[index]; + cv.frequency = frequency; + cv.stride = stride; + cv.size = size; + cv.type = type; + } + break; + + case NV4097_DRAW_ARRAYS: + { + for(u32 c=0; c> 24) + 1; + + LoadVertexData(first, _count); + + m_draw_array_count += _count; + } + } + break; + + case NV4097_SET_INDEX_ARRAY_ADDRESS: + { + m_indexed_array.m_addr = GetAddress(args[0], args[1] & 0xf); + m_indexed_array.m_type = args[1] >> 4; + } + break; + + case NV4097_DRAW_INDEX_ARRAY: + { + for(u32 c=0; c> 24) + 1; + + if(first < m_indexed_array.m_first) m_indexed_array.m_first = first; + + for(u32 i=first; i<_count; ++i) + { + u32 index; + switch(m_indexed_array.m_type) + { + case 0: + { + int pos = m_indexed_array.m_data.GetCount(); + m_indexed_array.m_data.InsertRoomEnd(4); + index = Memory.Read32(m_indexed_array.m_addr + i * 4); + *(u32*)&m_indexed_array.m_data[pos] = index; + //ConLog.Warning("index 4: %d", *(u32*)&m_indexed_array.m_data[pos]); + } + break; + + case 1: + { + int pos = m_indexed_array.m_data.GetCount(); + m_indexed_array.m_data.InsertRoomEnd(2); + index = Memory.Read16(m_indexed_array.m_addr + i * 2); + //ConLog.Warning("index 2: %d", index); + *(u16*)&m_indexed_array.m_data[pos] = index; + } + break; + } + + if(index < m_indexed_array.index_min) m_indexed_array.index_min = index; + if(index > m_indexed_array.index_max) m_indexed_array.index_max = index; + } + + m_indexed_array.m_count += _count; + } + } + break; + + case NV4097_SET_BEGIN_END: + { + u32 a0 = args[0]; + + if(a0) + { + Begin(a0); + } + else + { + End(); + } + } + break; + + case NV4097_SET_COLOR_CLEAR_VALUE: + { + const u32 color = args[0]; + m_clear_color_a = (color >> 24) & 0xff; + m_clear_color_r = (color >> 16) & 0xff; + m_clear_color_g = (color >> 8) & 0xff; + m_clear_color_b = color & 0xff; + } + break; + + case NV4097_SET_SHADER_PROGRAM: + { + m_cur_shader_prog = &m_shader_progs[m_cur_shader_prog_num++]; + u32 a0 = args[0]; + m_cur_shader_prog->offset = a0 & ~0x3; + m_cur_shader_prog->addr = GetAddress(m_cur_shader_prog->offset, (a0 & 0x3) - 1); + } + break; + + case NV4097_SET_VERTEX_ATTRIB_OUTPUT_MASK: + { + //VertexData[0].prog.attributeOutputMask = args[0]; + //FragmentData.prog.attributeInputMask = args[0]/* & ~0x20*/; + } + break; + + case NV4097_SET_SHADER_CONTROL: + { + const u32 arg0 = args[0]; + + //const u8 controlTxp = (arg0 >> 15) & 0x1; + //FragmentData.prog.registerCount = arg0 >> 24; + //FragmentData.prog. + } + break; + + case NV4097_SET_TRANSFORM_PROGRAM_LOAD: + { + m_cur_vertex_prog = &m_vertex_progs[args[0]]; + m_cur_vertex_prog->data.Clear(); + + if(count == 2) + { + const u32 start = args[1]; + if(start) + ConLog.Warning("NV4097_SET_TRANSFORM_PROGRAM_LOAD: start = %d", start); + } + } + break; + + case NV4097_SET_TRANSFORM_PROGRAM: + { + if(!m_cur_vertex_prog) + { + ConLog.Warning("NV4097_SET_TRANSFORM_PROGRAM: m_cur_vertex_prog == NULL"); + break; + } + + for(u32 i=0; idata.AddCpy(args[i]); + } + break; + + case NV4097_SET_TRANSFORM_TIMEOUT: + + if(!m_cur_vertex_prog) + { + ConLog.Warning("NV4097_SET_TRANSFORM_TIMEOUT: m_cur_vertex_prog == NULL"); + break; + } + + //m_cur_vertex_prog->Decompile(); + break; + + case NV4097_SET_VERTEX_ATTRIB_INPUT_MASK: + //VertexData[0].prog.attributeInputMask = args[0]; + break; + + case NV4097_INVALIDATE_VERTEX_CACHE_FILE: + break; + + case NV4097_SET_TRANSFORM_CONSTANT_LOAD: + { + if((count - 1) % 4) + { + CMD_LOG("NV4097_SET_TRANSFORM_CONSTANT_LOAD [%d]", count); + break; + } + + for(u32 id = args[0], i = 1; i= 2) + { + m_set_stencil_func_ref = true; + m_stencil_func_ref = args[1]; + + if(count >= 3) + { + m_set_stencil_func_mask = true; + m_stencil_func_mask = args[2]; + } + } + break; + + case NV4097_SET_STENCIL_FUNC_REF: + m_set_stencil_func_ref = true; + m_stencil_func_ref = args[0]; + break; + + case NV4097_SET_STENCIL_FUNC_MASK: + m_set_stencil_func_mask = true; + m_stencil_func_mask = args[0]; + break; + + case NV4097_SET_STENCIL_OP_FAIL: + m_set_stencil_fail = true; + m_stencil_fail = args[0]; + if(count >= 2) + { + m_set_stencil_zfail = true; + m_stencil_zfail = args[1]; + + if(count >= 3) + { + m_set_stencil_zpass = true; + m_stencil_zpass = args[2]; + } + } + break; + + case NV4097_SET_TWO_SIDED_STENCIL_TEST_ENABLE: + m_set_two_sided_stencil_test_enable = args[0] ? true : false; + break; + + case NV4097_SET_BACK_STENCIL_MASK: + m_set_back_stencil_mask = true; + m_back_stencil_mask = args[0]; + break; + + case NV4097_SET_BACK_STENCIL_FUNC: + m_set_back_stencil_func = true; + m_back_stencil_func = args[0]; + if(count >= 2) + { + m_set_back_stencil_func_ref = true; + m_back_stencil_func_ref = args[1]; + + if(count >= 3) + { + m_set_back_stencil_func_mask = true; + m_back_stencil_func_mask = args[2]; + } + } + break; + + case NV4097_SET_BACK_STENCIL_FUNC_REF: + m_set_back_stencil_func_ref = true; + m_back_stencil_func_ref = args[0]; + break; + + case NV4097_SET_BACK_STENCIL_FUNC_MASK: + m_set_back_stencil_func_mask = true; + m_back_stencil_func_mask = args[0]; + break; + + case NV4097_SET_BACK_STENCIL_OP_FAIL: + m_set_stencil_fail = true; + m_stencil_fail = args[0]; + if(count >= 2) + { + m_set_back_stencil_zfail = true; + m_back_stencil_zfail = args[1]; + + if(count >= 3) + { + m_set_back_stencil_zpass = true; + m_back_stencil_zpass = args[2]; + } + } + break; + + case NV4097_SET_POLY_OFFSET_FILL_ENABLE: + if(args[0]) ConLog.Error("NV4097_SET_POLY_OFFSET_FILL_ENABLE"); + break; + + case NV4097_SET_RESTART_INDEX_ENABLE: + if(args[0]) ConLog.Error("NV4097_SET_RESTART_INDEX_ENABLE"); + break; + + case NV4097_SET_POINT_PARAMS_ENABLE: + if(args[0]) ConLog.Error("NV4097_SET_POINT_PARAMS_ENABLE"); + break; + + case NV4097_SET_POINT_SPRITE_CONTROL: + if(args[0] & 0x1) + { + ConLog.Error("NV4097_SET_POINT_SPRITE_CONTROL enable"); + } + break; + + case NV4097_SET_POLY_SMOOTH_ENABLE: + m_set_poly_smooth = args[0] ? true : false; + break; + + case NV4097_SET_BLEND_COLOR: + m_set_blend_color = true; + m_blend_color_r = args[0] & 0xff; + m_blend_color_g = (args[0] >> 8) & 0xff; + m_blend_color_b = (args[0] >> 16) & 0xff; + m_blend_color_a = (args[0] >> 24) & 0xff; + break; + + case NV4097_SET_BLEND_COLOR2: + if(args[0]) ConLog.Error("NV4097_SET_BLEND_COLOR2"); + break; + + case NV4097_SET_BLEND_EQUATION: + m_set_blend_equation = true; + m_blend_equation_rgb = args[0] & 0xffff; + m_blend_equation_alpha = args[0] >> 16; + break; + + case NV4097_SET_REDUCE_DST_COLOR: + if(args[0]) ConLog.Error("NV4097_SET_REDUCE_DST_COLOR"); + break; + + case NV4097_SET_DEPTH_MASK: + m_set_depth_mask = true; + m_depth_mask = args[0]; + break; + + case NV4097_SET_SCISSOR_VERTICAL: + { + m_set_scissor_vertical = true; + m_scissor_y = args[0] & 0xffff; + m_scissor_h = args[0] >> 16; + } + break; + + case NV4097_SET_SCISSOR_HORIZONTAL: + { + m_set_scissor_horizontal = true; + m_scissor_x = args[0] & 0xffff; + m_scissor_w = args[0] >> 16; + + if(count == 2) + { + m_set_scissor_vertical = true; + m_scissor_y = args[1] & 0xffff; + m_scissor_h = args[1] >> 16; + } + } + break; + + case NV4097_INVALIDATE_VERTEX_FILE: break; + + case NV4097_SET_VIEWPORT_OFFSET: + { + //TODO + } + break; + + case NV4097_SET_SEMAPHORE_OFFSET: + case NV406E_SEMAPHORE_OFFSET: + { + m_set_semaphore_offset = true; + m_semaphore_offset = args[0]; + } + break; + + case NV4097_BACK_END_WRITE_SEMAPHORE_RELEASE: + { + if(m_set_semaphore_offset) + { + m_set_semaphore_offset = false; + u32 value = args[0]; + value = (value & 0xff00ff00) | ((value & 0xff) << 16) | ((value >> 16) & 0xff); + + Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + m_semaphore_offset, value); + } + } + break; + + case NV406E_SEMAPHORE_RELEASE: + case NV4097_TEXTURE_READ_SEMAPHORE_RELEASE: + if(m_set_semaphore_offset) + { + m_set_semaphore_offset = false; + Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + m_semaphore_offset, args[0]); + } + break; + + case NV406E_SEMAPHORE_ACQUIRE: + { + //TODO + } + break; + + case NV4097_SET_RESTART_INDEX: + { + //TODO + } + break; + + case NV4097_INVALIDATE_L2: + { + //TODO + } + break; + + case NV4097_SET_CONTEXT_DMA_COLOR_A: + { + m_set_context_dma_color_a = true; + m_context_dma_color_a = args[0]; + } + break; + + case NV4097_SET_CONTEXT_DMA_COLOR_B: + { + m_set_context_dma_color_b = true; + m_context_dma_color_b = args[0]; + } + break; + + case NV4097_SET_CONTEXT_DMA_COLOR_C: + { + m_set_context_dma_color_c = true; + m_context_dma_color_c = args[0]; + + if(count > 1) + { + m_set_context_dma_color_d = true; + m_context_dma_color_d = args[1]; + } + } + break; + + case NV4097_SET_CONTEXT_DMA_ZETA: + { + m_set_context_dma_z = true; + m_context_dma_z = args[0]; + } + break; + /* + case NV4097_SET_SURFACE_PITCH_A: + { + //TODO + } + break; + + case NV4097_SET_SURFACE_PITCH_B: + { + //TODO + } + break; + */ + case NV4097_SET_SURFACE_PITCH_C: + { + if(count != 4) + { + ConLog.Error("NV4097_SET_SURFACE_PITCH_C: Bad count (%d)", count); + break; + } + + m_surface_pitch_c = args[0]; + m_surface_pitch_d = args[1]; + m_surface_offset_c = args[2]; + m_surface_offset_d = args[3]; + } + break; + + case NV4097_SET_SURFACE_PITCH_Z: + { + m_surface_pitch_z = args[0]; + } + break; + + case NV4097_SET_SHADER_WINDOW: + { + u32 a0 = args[0]; + m_shader_window_height = a0 & 0xfff; + m_shader_window_origin = (a0 >> 12) & 0xf; + m_shader_window_pixel_centers = a0 >> 16; + } + break; + + case NV4097_SET_SURFACE_CLIP_VERTICAL: + { + u32 a0 = args[0]; + m_set_surface_clip_vertical = true; + m_surface_clip_y = a0; + m_surface_clip_h = a0 >> 16; + } + break; + + case NV4097_SET_SURFACE_CLIP_HORIZONTAL: + { + u32 a0 = args[0]; + + m_set_surface_clip_horizontal = true; + m_surface_clip_x = a0; + m_surface_clip_w = a0 >> 16; + + if(count >= 2) + { + u32 a1 = args[1]; + m_set_surface_clip_vertical = true; + m_surface_clip_y = a1; + m_surface_clip_h = a1 >> 16; + } + } + break; + + case NV4097_SET_WINDOW_OFFSET: + { + //TODO + } + break; + + case NV4097_SET_SURFACE_COLOR_TARGET: + { + m_surface_colour_target = args[0]; + } + break; + + case NV4097_SET_ANTI_ALIASING_CONTROL: + { + //TODO + } + break; + + case NV4097_SET_LINE_SMOOTH_ENABLE: + m_set_line_smooth = args[0] ? true : false; + break; + + case NV4097_SET_LINE_WIDTH: + m_set_line_width = true; + m_line_width = args[0]; + break; + + case NV4097_SET_SHADE_MODE: + m_set_shade_mode = true; + m_shade_mode = args[0]; + break; + + case NV4097_SET_ZSTENCIL_CLEAR_VALUE: + { + u32 a0 = args[0]; + m_clear_s = a0 & 0xff; + m_clear_z = a0 >> 8; + } + break; + + case NV4097_SET_ZCULL_CONTROL0: + { + m_set_depth_func = true; + m_depth_func = args[0] >> 4; + } + break; + + case NV4097_SET_ZCULL_CONTROL1: + { + //TODO + } + break; + + case NV4097_SET_SCULL_CONTROL: + { + u32 a0 = args[0]; + m_set_stencil_func = m_set_stencil_func_ref = m_set_stencil_func_mask = true; + + m_stencil_func = a0 & 0xffff; + m_stencil_func_ref = (a0 >> 16) & 0xff; + m_stencil_func_mask = (a0 >> 24) & 0xff; + } + break; + + case NV4097_SET_ZCULL_EN: + { + u32 a0 = args[0]; + + m_depth_test_enable = a0 & 0x1 ? true : false; + m_set_stencil_test = a0 & 0x2 ? true : false; + } + break; + + case NV4097_GET_REPORT: + { + u32 a0 = args[0]; + u8 type = a0 >> 24; + u32 offset = a0 & 0xffffff; + + u64 data; + switch(type) + { + case 1: + data = std::chrono::steady_clock::now().time_since_epoch().count(); + data *= 1000000; + break; + + default: + data = 0; + ConLog.Error("NV4097_GET_REPORT: bad type %d", type); + break; + } + + Memory.Write64(m_local_mem_addr + offset, data); + } + break; + + case NV3062_SET_OFFSET_DESTIN: + m_dst_offset = args[0]; + break; + + case NV308A_COLOR: + { + RSXTransformConstant c; + c.id = m_dst_offset; + + if(count >= 1) + { + u32 a = args[0]; + a = a << 16 | a >> 16; + c.x = (float&)a; + } + + if(count >= 2) + { + u32 a = args[1]; + a = a << 16 | a >> 16; + c.y = (float&)a; + } + + if(count >= 3) + { + u32 a = args[2]; + a = a << 16 | a >> 16; + c.z = (float&)a; + } + + if(count >= 4) + { + u32 a = args[3]; + a = a << 16 | a >> 16; + c.w = (float&)a; + } + + if(count >= 5) + { + ConLog.Warning("NV308A_COLOR: count = %d", count); + } + + //ConLog.Warning("NV308A_COLOR: [%d]: %f, %f, %f, %f", c.id, c.x, c.y, c.z, c.w); + m_fragment_constants.AddCpy(c); + } + break; + + case NV308A_POINT: + //TODO + break; + + case NV3062_SET_COLOR_FORMAT: + { + m_color_format = args[0]; + m_color_format_src_pitch = args[1]; + m_color_format_dst_pitch = args[1] >> 16; + } + break; + + case NV3089_SET_COLOR_CONVERSION: + { + m_color_conv = args[0]; + m_color_conv_fmt = args[1]; + m_color_conv_op = args[2]; + m_color_conv_in_x = args[3]; + m_color_conv_in_y = args[3] >> 16; + m_color_conv_in_w = args[4]; + m_color_conv_in_h = args[4] >> 16; + m_color_conv_out_x = args[5]; + m_color_conv_out_y = args[5] >> 16; + m_color_conv_out_w = args[6]; + m_color_conv_out_h = args[6] >> 16; + m_color_conv_dsdx = args[7]; + m_color_conv_dtdy = args[8]; + } + break; + + case NV3089_IMAGE_IN_SIZE: + { + u16 w = args[0]; + u16 h = args[0] >> 16; + u16 pitch = args[1]; + u8 origin = args[1] >> 16; + u8 inter = args[1] >> 24; + u32 offset = args[2]; + u16 u = args[3]; + u16 v = args[3] >> 16; + + u8* pixels_src = &Memory[GetAddress(offset, m_context_dma_img_src - 0xfeed0000)]; + u8* pixels_dst = &Memory[GetAddress(m_dst_offset, m_context_dma_img_dst - 0xfeed0000)]; + + for(u16 y=0; y> 4) & 0xf; + m_clip_plane_2 = (a0 >> 8) & 0xf; + m_clip_plane_3 = (a0 >> 12) & 0xf; + m_clip_plane_4 = (a0 >> 16) & 0xf; + m_clip_plane_5 = a0 >> 20; + } + break; + + case NV4097_SET_FOG_PARAMS: + { + m_set_fog_params = true; + u32 a0 = args[0]; + u32 a1 = args[1]; + m_fog_param0 = (float&)a0; + m_fog_param1 = (float&)a1; + } + break; + + default: + { + wxString log = GetMethodName(cmd); + log += "("; + for(u32 i=0; iget); + const u32 put = re(m_ctrl->put); + if(put == get || !Emu.IsRunning()) + { + if(put == get) + SemaphorePostAndWait(m_sem_flush); + + Sleep(1); + continue; + } + + //ConLog.Write("addr = 0x%x", m_ioAddress + get); + const u32 cmd = Memory.Read32(m_ioAddress + get); + const u32 count = (cmd >> 18) & 0x7ff; + //if(cmd == 0) continue; + + if(cmd & CELL_GCM_METHOD_FLAG_JUMP) + { + u32 addr = cmd & ~(CELL_GCM_METHOD_FLAG_JUMP | CELL_GCM_METHOD_FLAG_NON_INCREMENT); + //ConLog.Warning("rsx jump(0x%x) #addr=0x%x, cmd=0x%x, get=0x%x, put=0x%x", addr, m_ioAddress + get, cmd, get, put); + re(m_ctrl->get, addr); + continue; + } + if(cmd & CELL_GCM_METHOD_FLAG_CALL) + { + m_call_stack.Push(get + 4); + u32 offs = cmd & ~CELL_GCM_METHOD_FLAG_CALL; + u32 addr = m_ioAddress + offs; + //ConLog.Warning("rsx call(0x%x) #0x%x - 0x%x - 0x%x", offs, addr, cmd, get); + m_ctrl->get = re32(offs); + continue; + } + if(cmd == CELL_GCM_METHOD_FLAG_RETURN) + { + //ConLog.Warning("rsx return!"); + u32 get = m_call_stack.Pop(); + //ConLog.Warning("rsx return(0x%x)", get); + m_ctrl->get = re32(get); + continue; + } + if(cmd & CELL_GCM_METHOD_FLAG_NON_INCREMENT) + { + //ConLog.Warning("non increment cmd! 0x%x", cmd); + } + + if(cmd == 0) + { + ConLog.Warning("null cmd: addr=0x%x, put=0x%x, get=0x%x", m_ioAddress + get, re(m_ctrl->put), get); + Emu.Pause(); + continue; + } + + mem32_ptr_t args(m_ioAddress + get + 4); + DoCmd(cmd, cmd & 0x3ffff, args, count); + + re(m_ctrl->get, get + (count + 1) * 4); + //memset(Memory.GetMemFromAddr(p.m_ioAddress + get), 0, (count + 1) * 4); + } + + ConLog.Write("RSX thread exit..."); + + OnExitThread(); +} diff --git a/rpcs3/Emu/GS/RSXThread.h b/rpcs3/Emu/GS/RSXThread.h index 78dc31eae3..22b0fbd496 100644 --- a/rpcs3/Emu/GS/RSXThread.h +++ b/rpcs3/Emu/GS/RSXThread.h @@ -1,8 +1,281 @@ #pragma once #include "GCM.h" +#include "RSXVertexProgram.h" +#include "RSXFragmentProgram.h" +#include "Emu/SysCalls/Callback.h" -class ExecRSXCMDdata +enum Method { + CELL_GCM_METHOD_FLAG_NON_INCREMENT = 0x40000000, + CELL_GCM_METHOD_FLAG_JUMP = 0x20000000, + CELL_GCM_METHOD_FLAG_CALL = 0x00000002, + CELL_GCM_METHOD_FLAG_RETURN = 0x00020000, +}; + + +class RSXTexture +{ +public: + bool m_enabled; + + u32 m_width, m_height; + u32 m_offset; + + bool m_cubemap; + u8 m_dimension; + u32 m_format; + u16 m_mipmap; + + u32 m_pitch; + u16 m_depth; + + u16 m_minlod; + u16 m_maxlod; + u8 m_maxaniso; + + u8 m_wraps; + u8 m_wrapt; + u8 m_wrapr; + u8 m_unsigned_remap; + u8 m_zfunc; + u8 m_gamma; + u8 m_aniso_bias; + u8 m_signed_remap; + + u16 m_bias; + u8 m_min_filter; + u8 m_mag_filter; + u8 m_conv; + u8 m_a_signed; + u8 m_r_signed; + u8 m_g_signed; + u8 m_b_signed; + + u32 m_remap; + +public: + RSXTexture() + : m_width(0), m_height(0) + , m_offset(0) + , m_enabled(false) + + , m_cubemap(false) + , m_dimension(0) + , m_format(0) + , m_mipmap(0) + , m_minlod(0) + , m_maxlod(1000) + , m_maxaniso(0) + { + } + + void SetRect(const u32 width, const u32 height) + { + m_width = width; + m_height = height; + } + + void SetFormat(const bool cubemap, const u8 dimension, const u32 format, const u16 mipmap) + { + m_cubemap = cubemap; + m_dimension = dimension; + m_format = format; + m_mipmap = mipmap; + } + + void SetAddress(u8 wraps, u8 wrapt, u8 wrapr, u8 unsigned_remap, u8 zfunc, u8 gamma, u8 aniso_bias, u8 signed_remap) + { + m_wraps = wraps; + m_wrapt = wrapt; + m_wrapr = wrapr; + m_unsigned_remap = unsigned_remap; + m_zfunc = zfunc; + m_gamma = gamma; + m_aniso_bias = aniso_bias; + m_signed_remap = signed_remap; + } + + void SetControl0(const bool enable, const u16 minlod, const u16 maxlod, const u8 maxaniso) + { + m_enabled = enable; + m_minlod = minlod; + m_maxlod = maxlod; + m_maxaniso = maxaniso; + } + + void SetControl1(u32 remap) + { + m_remap = remap; + } + + void SetControl3(u16 depth, u32 pitch) + { + m_depth = depth; + m_pitch = pitch; + } + + void SetFilter(u16 bias, u8 min, u8 mag, u8 conv, u8 a_signed, u8 r_signed, u8 g_signed, u8 b_signed) + { + m_bias = bias; + m_min_filter = min; + m_mag_filter = mag; + m_conv = conv; + m_a_signed = a_signed; + m_r_signed = r_signed; + m_g_signed = g_signed; + m_b_signed = b_signed; + } + + u32 GetFormat() const + { + return m_format; + } + + void SetOffset(const u32 offset) + { + m_offset = offset; + } + + wxSize GetRect() const + { + return wxSize(m_width, m_height); + } + + bool IsEnabled() const + { + return m_enabled; + } + + u32 GetOffset() const + { + return m_offset; + } +}; + +struct RSXVertexData +{ + u32 frequency; + u32 stride; + u32 size; + u32 type; + u32 addr; + u32 constant_count; + + Array data; + + RSXVertexData(); + + void Reset(); + bool IsEnabled() { return size > 0; } + void Load(u32 start, u32 count); + + u32 GetTypeSize(); +}; + +struct RSXIndexArrayData +{ + Array m_data; + int m_type; + u32 m_first; + u32 m_count; + u32 m_addr; + u32 index_max; + u32 index_min; + + RSXIndexArrayData() + { + Reset(); + } + + void Reset() + { + m_type = 0; + m_first = ~0; + m_count = 0; + m_addr = 0; + index_min = ~0; + index_max = 0; + m_data.Clear(); + } +}; + +struct RSXTransformConstant +{ + u32 id; + float x, y, z, w; + + RSXTransformConstant() + : x(0.0f) + , y(0.0f) + , z(0.0f) + , w(0.0f) + { + } + + RSXTransformConstant(u32 id, float x, float y, float z, float w) + : id(id) + , x(x) + , y(y) + , z(z) + , w(w) + { + } +}; + +class RSXThread : public ThreadBase +{ +public: + static const uint m_textures_count = 16; + static const uint m_vertex_count = 16; + static const uint m_fragment_count = 16; + static const uint m_tiles_count = 15; + +protected: + Stack m_call_stack; + CellGcmControl* m_ctrl; + +public: + GcmTileInfo m_tiles[m_tiles_count]; + RSXTexture m_textures[m_textures_count]; + RSXVertexData m_vertex_data[m_vertex_count]; + RSXIndexArrayData m_indexed_array; + Array m_fragment_constants; + Array m_transform_constants; + + u32 m_cur_shader_prog_num; + RSXShaderProgram m_shader_progs[m_fragment_count]; + RSXShaderProgram* m_cur_shader_prog; + RSXVertexProgram m_vertex_progs[m_vertex_count]; + RSXVertexProgram* m_cur_vertex_prog; + +public: + u32 m_ioAddress, m_ioSize, m_ctrlAddress; + int m_flip_status; + int m_flip_mode; + + u32 m_tiles_addr; + u32 m_zculls_addr; + u32 m_gcm_buffers_addr; + u32 m_gcm_buffers_count; + u32 m_gcm_current_buffer; + u32 m_ctxt_addr; + u32 m_report_main_addr; + + u32 m_local_mem_addr, m_main_mem_addr; + Array m_main_mem_info; + +protected: + uint m_draw_mode; + + u32 m_width, m_height; + u32 m_draw_array_count; + +public: + wxCriticalSection m_cs_main; + wxSemaphore m_sem_flush; + wxSemaphore m_sem_flip; + Callback m_flip_handler; + public: bool m_set_color_mask; bool m_color_mask_r; @@ -45,8 +318,13 @@ public: bool m_set_front_polygon_mode; u32 m_front_polygon_mode; - bool m_set_clear_surface; u32 m_clear_surface_mask; + u32 m_clear_surface_z; + u8 m_clear_surface_s; + u8 m_clear_surface_color_r; + u8 m_clear_surface_color_g; + u8 m_clear_surface_color_b; + u8 m_clear_surface_color_a; bool m_set_blend_sfactor; u16 m_blend_sfactor_rgb; @@ -119,11 +397,12 @@ public: u8 m_blend_color_b; u8 m_blend_color_a; - bool m_set_clear_color; u8 m_clear_color_r; u8 m_clear_color_g; u8 m_clear_color_b; u8 m_clear_color_a; + u8 m_clear_s; + u32 m_clear_z; u32 m_context_dma_img_src; u32 m_context_dma_img_dst; @@ -171,11 +450,6 @@ public: u8 m_surface_antialias; u8 m_surface_width; u8 m_surface_height; - u32 m_surface_pitch_a; - u32 m_surface_offset_a; - u32 m_surface_offset_z; - u32 m_surface_offset_b; - u32 m_surface_pitch_b; bool m_set_context_dma_color_a; u32 m_context_dma_color_a; @@ -186,6 +460,9 @@ public: bool m_set_context_dma_color_c; u32 m_context_dma_color_c; + bool m_set_context_dma_color_d; + u32 m_context_dma_color_d; + bool m_set_context_dma_z; u32 m_context_dma_z; @@ -205,35 +482,74 @@ public: bool m_set_alpha_ref; u32 m_alpha_ref; + u32 m_surface_pitch_a; + u32 m_surface_pitch_b; + u32 m_surface_pitch_c; + u32 m_surface_pitch_d; + u32 m_surface_pitch_z; + + u32 m_surface_offset_a; + u32 m_surface_offset_b; + u32 m_surface_offset_c; + u32 m_surface_offset_d; + u32 m_surface_offset_z; + + u16 m_shader_window_height; + u8 m_shader_window_origin; + u16 m_shader_window_pixel_centers; + + u32 m_surface_colour_target; + u8 m_begin_end; -public: - ExecRSXCMDdata() +protected: + RSXThread() + : ThreadBase(false, "RSXThread") + , m_ctrl(nullptr) + , m_flip_status(0) + , m_flip_mode(CELL_GCM_DISPLAY_VSYNC) + , m_main_mem_addr(0) + , m_local_mem_addr(0) + , m_draw_mode(0) + , m_draw_array_count(0) { - Reset(); - } - - virtual void Reset() - { - m_set_color_mask = false; m_set_alpha_test = false; m_set_blend = false; m_set_depth_bounds_test = false; + m_depth_test_enable = false; + m_set_logic_op = false; + m_set_cull_face_enable = false; + m_set_dither = false; + m_set_stencil_test = false; + m_set_line_smooth = false; + m_set_poly_smooth = false; + m_set_two_sided_stencil_test_enable = false; + m_set_surface_clip_horizontal = false; + m_set_surface_clip_vertical = false; + + m_clear_color_r = 0; + m_clear_color_g = 0; + m_clear_color_b = 0; + m_clear_color_a = 0; + m_clear_z = 0xffffff; + m_clear_s = 0; + + Reset(); + } + + void Reset() + { + m_set_color_mask = false; m_set_clip = false; m_set_depth_func = false; - m_depth_test_enable = false; m_set_viewport_horizontal = false; m_set_viewport_vertical = false; m_set_scissor_horizontal = false; m_set_scissor_vertical = false; m_set_front_polygon_mode = false; - m_set_clear_surface = false; + m_clear_surface_mask = 0; m_set_blend_sfactor = false; m_set_blend_dfactor = false; - m_set_logic_op = false; - m_set_cull_face_enable = false; - m_set_dither = false; - m_set_stencil_test = false; m_set_stencil_mask = false; m_set_stencil_func = false; m_set_stencil_func_ref = false; @@ -241,7 +557,6 @@ public: m_set_stencil_fail = false; m_set_stencil_zfail = false; m_set_stencil_zpass = false; - m_set_two_sided_stencil_test_enable = false; m_set_back_stencil_mask = false; m_set_back_stencil_func = false; m_set_back_stencil_func_ref = false; @@ -251,12 +566,9 @@ public: m_set_back_stencil_zpass = false; m_set_blend_equation = false; m_set_depth_mask = false; - m_set_line_smooth = false; - m_set_poly_smooth = false; m_set_line_width = false; m_set_shade_mode = false; m_set_blend_color = false; - m_set_clear_color = false; m_set_semaphore_offset = false; m_set_fog_mode = false; m_set_fog_params = false; @@ -265,28 +577,67 @@ public: m_set_context_dma_color_a = false; m_set_context_dma_color_b = false; m_set_context_dma_color_c = false; + m_set_context_dma_color_d = false; m_set_context_dma_z = false; - m_set_surface_clip_horizontal = false; - m_set_surface_clip_vertical = false; m_set_cull_face = false; m_set_alpha_func = false; m_set_alpha_ref = false; + + m_clear_surface_mask = 0; m_begin_end = 0; } - virtual void ExecCMD()=0; -}; + void Begin(u32 draw_mode); + void End(); -class RSXThread : public ThreadBase -{ - Array call_stack; - CellGcmControl& m_ctrl; - u32 m_ioAddress; + void DoCmd(const u32 fcmd, const u32 cmd, mem32_ptr_t& args, const u32 count); -protected: - RSXThread(CellGcmControl* ctrl, u32 ioAddress); + virtual void OnInit() = 0; + virtual void OnInitThread() = 0; + virtual void OnExitThread() = 0; + virtual void OnReset() = 0; + virtual void ExecCMD() = 0; + virtual void Flip() = 0; + + u32 GetAddress(u32 offset, u8 location) + { + switch(location) + { + case CELL_GCM_LOCATION_LOCAL: return m_local_mem_addr + offset; + case CELL_GCM_LOCATION_MAIN: return m_main_mem_addr + offset; + } + + ConLog.Error("GetAddress(offset=0x%x, location=0x%x)", location); + assert(0); + return 0; + } + + void LoadVertexData(u32 first, u32 count) + { + for(u32 i=0; i data; +}; \ No newline at end of file diff --git a/rpcs3/Emu/Memory/DynamicMemoryBlockBase.inl b/rpcs3/Emu/Memory/DynamicMemoryBlockBase.inl new file mode 100644 index 0000000000..d4f28d2feb --- /dev/null +++ b/rpcs3/Emu/Memory/DynamicMemoryBlockBase.inl @@ -0,0 +1,160 @@ + +//DynamicMemoryBlockBase +template +DynamicMemoryBlockBase::DynamicMemoryBlockBase() : m_max_size(0) +{ +} + +template +const u32 DynamicMemoryBlockBase::GetUsedSize() const +{ + u32 size = 0; + + for(u32 i=0; i +bool DynamicMemoryBlockBase::IsInMyRange(const u64 addr) +{ + return addr >= GetStartAddr() && addr < GetStartAddr() + GetSize(); +} + +template +bool DynamicMemoryBlockBase::IsInMyRange(const u64 addr, const u32 size) +{ + return IsInMyRange(addr) && IsInMyRange(addr + size - 1); +} + +template +bool DynamicMemoryBlockBase::IsMyAddress(const u64 addr) +{ + for(u32 i=0; i= m_used_mem[i].addr && addr < m_used_mem[i].addr + m_used_mem[i].size) + { + return true; + } + } + + return false; +} + +template +MemoryBlock* DynamicMemoryBlockBase::SetRange(const u64 start, const u32 size) +{ + m_max_size = size; + MemoryBlock::SetRange(start, 0); + + return this; +} + +template +void DynamicMemoryBlockBase::Delete() +{ + m_used_mem.Clear(); + m_max_size = 0; + + MemoryBlock::Delete(); +} + +template +bool DynamicMemoryBlockBase::Alloc(u64 addr, u32 size) +{ + if(!IsInMyRange(addr, size)) + { + assert(0); + return false; + } + + if(IsMyAddress(addr) || IsMyAddress(addr + size - 1)) + { + return false; + } + + for(u32 i=0; i= m_used_mem[i].addr && addr < m_used_mem[i].addr + m_used_mem[i].size) return false; + } + + AppendUsedMem(addr, size); + + return true; +} + +template +void DynamicMemoryBlockBase::AppendUsedMem(u64 addr, u32 size) +{ + m_used_mem.Move(new MemBlockInfo(addr, size)); +} + +template +u64 DynamicMemoryBlockBase::Alloc(u32 size) +{ + for(u64 addr=GetStartAddr(); addr <= GetEndAddr() - size;) + { + bool is_good_addr = true; + + for(u32 i=0; i= m_used_mem[i].addr && addr < m_used_mem[i].addr + m_used_mem[i].size) || + (m_used_mem[i].addr >= addr && m_used_mem[i].addr < addr + size)) + { + is_good_addr = false; + addr = m_used_mem[i].addr + m_used_mem[i].size; + break; + } + } + + if(!is_good_addr) continue; + + AppendUsedMem(addr, size); + + return addr; + } + + return 0; +} + +template +bool DynamicMemoryBlockBase::Alloc() +{ + return Alloc(GetSize() - GetUsedSize()) != 0; +} + +template +bool DynamicMemoryBlockBase::Free(u64 addr) +{ + for(u32 i=0; i +u8* DynamicMemoryBlockBase::GetMem(u64 addr) const +{ + for(u32 i=0; i= _addr && addr < _addr + m_used_mem[i].size) + { + return (u8*)m_used_mem[i].mem + addr - _addr; + } + } + + ConLog.Error("GetMem(%llx) from not allocated address.", addr); + assert(0); + return nullptr; +} \ No newline at end of file diff --git a/rpcs3/Emu/Memory/Memory.cpp b/rpcs3/Emu/Memory/Memory.cpp index 60d60a838b..994dc01af1 100644 --- a/rpcs3/Emu/Memory/Memory.cpp +++ b/rpcs3/Emu/Memory/Memory.cpp @@ -248,6 +248,86 @@ bool MemoryBlock::Write128(const u64 addr, const u128 value) return true; } +bool MemoryBlockLE::Read8(const u64 addr, u8* value) +{ + if(!IsMyAddress(addr)) return false; + + *value = *(u8*)GetMem(FixAddr(addr)); + return true; +} + +bool MemoryBlockLE::Read16(const u64 addr, u16* value) +{ + if(!IsMyAddress(addr)) return false; + + *value = *(u16*)GetMem(FixAddr(addr)); + return true; +} + +bool MemoryBlockLE::Read32(const u64 addr, u32* value) +{ + if(!IsMyAddress(addr)) return false; + + *value = *(u32*)GetMem(FixAddr(addr)); + return true; +} + +bool MemoryBlockLE::Read64(const u64 addr, u64* value) +{ + if(!IsMyAddress(addr)) return false; + + *value = *(u64*)GetMem(FixAddr(addr)); + return true; +} + +bool MemoryBlockLE::Read128(const u64 addr, u128* value) +{ + if(!IsMyAddress(addr)) return false; + + *value = *(u128*)GetMem(FixAddr(addr)); + return true; +} + +bool MemoryBlockLE::Write8(const u64 addr, const u8 value) +{ + if(!IsMyAddress(addr)) return false; + + *(u8*)GetMem(FixAddr(addr)) = value; + return true; +} + +bool MemoryBlockLE::Write16(const u64 addr, const u16 value) +{ + if(!IsMyAddress(addr)) return false; + + *(u16*)GetMem(FixAddr(addr)) = value; + return true; +} + +bool MemoryBlockLE::Write32(const u64 addr, const u32 value) +{ + if(!IsMyAddress(addr)) return false; + + *(u32*)GetMem(FixAddr(addr)) = value; + return true; +} + +bool MemoryBlockLE::Write64(const u64 addr, const u64 value) +{ + if(!IsMyAddress(addr)) return false; + + *(u64*)GetMem(FixAddr(addr)) = value; + return true; +} + +bool MemoryBlockLE::Write128(const u64 addr, const u128 value) +{ + if(!IsMyAddress(addr)) return false; + + *(u128*)GetMem(FixAddr(addr)) = value; + return true; +} + //NullMemoryBlock bool NullMemoryBlock::Read8(const u64 addr, u8* WXUNUSED(value)) { @@ -319,199 +399,24 @@ bool NullMemoryBlock::Write128(const u64 addr, const u128 value) return false; } -//DynamicMemoryBlock -DynamicMemoryBlock::DynamicMemoryBlock() : m_max_size(0) -{ -} - -const u32 DynamicMemoryBlock::GetUsedSize() const -{ - u32 size = 0; - - for(u32 i=0; i= GetStartAddr() && addr < GetStartAddr() + GetSize(); -} - -bool DynamicMemoryBlock::IsInMyRange(const u64 addr, const u32 size) -{ - return IsInMyRange(addr) && IsInMyRange(addr + size - 1); -} - -bool DynamicMemoryBlock::IsMyAddress(const u64 addr) -{ - for(u32 i=0; i= m_used_mem[i].addr && addr < m_used_mem[i].addr + m_used_mem[i].size) - { - return true; - } - } - - return false; -} - -MemoryBlock* DynamicMemoryBlock::SetRange(const u64 start, const u32 size) -{ - m_max_size = size; - MemoryBlock::SetRange(start, 0); - - return this; -} - -void DynamicMemoryBlock::Delete() -{ - m_used_mem.Clear(); - m_max_size = 0; - - MemoryBlock::Delete(); -} - -bool DynamicMemoryBlock::Alloc(u64 addr, u32 size) -{ - if(!IsInMyRange(addr, size)) - { - assert(0); - return false; - } - - if(IsMyAddress(addr) || IsMyAddress(addr + size - 1)) - { - return false; - } - - for(u32 i=0; i= m_used_mem[i].addr && addr < m_used_mem[i].addr + m_used_mem[i].size) return false; - } - - AppendUsedMem(addr, size); - - return true; -} - -void DynamicMemoryBlock::AppendUsedMem(u64 addr, u32 size) -{ - m_used_mem.Move(new MemBlockInfo(addr, size)); -} - -u64 DynamicMemoryBlock::Alloc(u32 size) -{ - for(u64 addr=GetStartAddr(); addr <= GetEndAddr() - size;) - { - bool is_good_addr = true; - - for(u32 i=0; i= m_used_mem[i].addr && addr < m_used_mem[i].addr + m_used_mem[i].size) || - (m_used_mem[i].addr >= addr && m_used_mem[i].addr < addr + size)) - { - is_good_addr = false; - addr = m_used_mem[i].addr + m_used_mem[i].size; - break; - } - } - - if(!is_good_addr) continue; - - AppendUsedMem(addr, size); - - return addr; - } - - return 0; -} - -bool DynamicMemoryBlock::Alloc() -{ - return Alloc(GetSize() - GetUsedSize()) != 0; -} - -bool DynamicMemoryBlock::Free(u64 addr) -{ - for(u32 i=0; i= _addr && addr < _addr + m_used_mem[i].size) - { - return (u8*)m_used_mem[i].mem + addr - _addr; - } - } - - ConLog.Error("GetMem(%llx) from not allocated address.", addr); - assert(0); - return nullptr; -} - -#define DEBUG_RAWSPU_MEM 1 //MemoryBase void MemoryBase::Write8(u64 addr, const u8 data) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Write8(addr=0x%llx,data=0x%x)", addr, data); - } -#endif GetMemByAddr(addr).Write8(addr, data); } void MemoryBase::Write16(u64 addr, const u16 data) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Write16(addr=0x%llx,data=0x%x)", addr, data); - } -#endif - GetMemByAddr(addr).Write16(addr, data); } void MemoryBase::Write32(u64 addr, const u32 data) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Write32(addr=0x%llx,data=0x%x)", addr, data); - } -#endif - GetMemByAddr(addr).Write32(addr, data); } void MemoryBase::Write64(u64 addr, const u64 data) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Write64(addr=0x%llx,data=0x%llx)", addr, data); - } -#endif - GetMemByAddr(addr).Write64(addr, data); } @@ -557,83 +462,35 @@ bool MemoryBase::Write128NN(u64 addr, const u128 data) u8 MemoryBase::Read8(u64 addr) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Read8(addr=0x%llx)", addr); - } -#endif - - MemoryBlock& mem = GetMemByAddr(addr); - if(mem.IsNULL()) - { - mem.Read8(addr, NULL); - return 0; - } - return mem.FastRead8(mem.FixAddr(addr)); + u8 res; + GetMemByAddr(addr).Read8(addr, &res); + return res; } u16 MemoryBase::Read16(u64 addr) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Read16(addr=0x%llx)", addr); - } -#endif - - MemoryBlock& mem = GetMemByAddr(addr); - if(mem.IsNULL()) - { - mem.Read16(addr, NULL); - return 0; - } - return mem.FastRead16(mem.FixAddr(addr)); + u16 res; + GetMemByAddr(addr).Read16(addr, &res); + return res; } u32 MemoryBase::Read32(u64 addr) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr) && !(GetCurrentPPCThread() && GetCurrentPPCThread()->GetType() == PPC_THREAD_RAW_SPU)) - { - ConLog.Warning("Read32(addr=0x%llx)", addr); - } -#endif - - MemoryBlock& mem = GetMemByAddr(addr); - if(mem.IsNULL()) - { - mem.Read32(addr, NULL); - return 0; - } - return mem.FastRead32(mem.FixAddr(addr)); + u32 res; + GetMemByAddr(addr).Read32(addr, &res); + return res; } u64 MemoryBase::Read64(u64 addr) { -#if DEBUG_RAWSPU_MEM - if(SpuRawMem.IsMyAddress(addr)) - { - ConLog.Warning("Read64(addr=0x%llx)", addr); - } -#endif - - MemoryBlock& mem = GetMemByAddr(addr); - if(mem.IsNULL()) - { - mem.Read64(addr, NULL); - return 0; - } - return mem.FastRead64(mem.FixAddr(addr)); + u64 res; + GetMemByAddr(addr).Read64(addr, &res); + return res; } u128 MemoryBase::Read128(u64 addr) { - MemoryBlock& mem = GetMemByAddr(addr); - if(mem.IsNULL()) - { - mem.Read128(addr, NULL); - return u128::From32(0); - } - return mem.FastRead128(mem.FixAddr(addr)); + u128 res; + GetMemByAddr(addr).Read128(addr, &res); + return res; } diff --git a/rpcs3/Emu/Memory/Memory.h b/rpcs3/Emu/Memory/Memory.h index f80f2bbcbc..453a0573a6 100644 --- a/rpcs3/Emu/Memory/Memory.h +++ b/rpcs3/Emu/Memory/Memory.h @@ -1,12 +1,20 @@ #pragma once #include "MemoryBlock.h" +enum MemoryType +{ + Memory_PS3, + Memory_PSV, + Memory_PSP, +}; + class MemoryBase { NullMemoryBlock NullMem; public: ArrayF MemoryBlocks; + MemoryBlock* UserMemory; DynamicMemoryBlock MainMem; DynamicMemoryBlock PRXMem; @@ -17,6 +25,21 @@ public: MemoryBlock SpuRawMem; MemoryBlock SpuThrMem; + struct + { + DynamicMemoryBlockLE RAM; + DynamicMemoryBlockLE Userspace; + } PSVMemory; + + struct + { + DynamicMemoryBlockLE Scratchpad; + DynamicMemoryBlockLE VRAM; + DynamicMemoryBlockLE RAM; + DynamicMemoryBlockLE Kernel; + DynamicMemoryBlockLE Userspace; + } PSPMemory; + bool m_inited; MemoryBase() @@ -126,21 +149,39 @@ public: return true; } - void Init() + void Init(MemoryType type) { if(m_inited) return; m_inited = true; ConLog.Write("Initing memory..."); - MemoryBlocks.Add(MainMem.SetRange(0x00010000, 0x2FFF0000)); - MemoryBlocks.Add(PRXMem.SetRange(0x30000000, 0x10000000)); - MemoryBlocks.Add(RSXCMDMem.SetRange(0x40000000, 0x10000000)); - MemoryBlocks.Add(MmaperMem.SetRange(0xB0000000, 0x10000000)); - MemoryBlocks.Add(RSXFBMem.SetRange(0xC0000000, 0x10000000)); - MemoryBlocks.Add(StackMem.SetRange(0xD0000000, 0x10000000)); - //MemoryBlocks.Add(SpuRawMem.SetRange(0xE0000000, 0x10000000)); - //MemoryBlocks.Add(SpuThrMem.SetRange(0xF0000000, 0x10000000)); + switch(type) + { + case Memory_PS3: + MemoryBlocks.Add(MainMem.SetRange(0x00010000, 0x2FFF0000)); + MemoryBlocks.Add(UserMemory = PRXMem.SetRange(0x30000000, 0x10000000)); + MemoryBlocks.Add(RSXCMDMem.SetRange(0x40000000, 0x10000000)); + MemoryBlocks.Add(MmaperMem.SetRange(0xB0000000, 0x10000000)); + MemoryBlocks.Add(RSXFBMem.SetRange(0xC0000000, 0x10000000)); + MemoryBlocks.Add(StackMem.SetRange(0xD0000000, 0x10000000)); + //MemoryBlocks.Add(SpuRawMem.SetRange(0xE0000000, 0x10000000)); + //MemoryBlocks.Add(SpuThrMem.SetRange(0xF0000000, 0x10000000)); + break; + + case Memory_PSV: + MemoryBlocks.Add(PSVMemory.RAM.SetRange(0x81000000, 0x10000000)); + MemoryBlocks.Add(UserMemory = PSVMemory.Userspace.SetRange(0x91000000, 0x10000000)); + break; + + case Memory_PSP: + MemoryBlocks.Add(PSPMemory.Scratchpad.SetRange(0x00010000, 0x00004000)); + MemoryBlocks.Add(PSPMemory.VRAM.SetRange(0x04000000, 0x00200000)); + MemoryBlocks.Add(PSPMemory.RAM.SetRange(0x08000000, 0x02000000)); + MemoryBlocks.Add(PSPMemory.Kernel.SetRange(0x88000000, 0x00800000)); + MemoryBlocks.Add(UserMemory = PSPMemory.Userspace.SetRange(0x08800000, 0x01800000)); + break; + } ConLog.Write("Memory initialized."); } @@ -178,16 +219,7 @@ public: MemoryBlocks[i].Delete(); } - MemoryBlocks.Clear(); - } - - void Reset() - { - if(!m_inited) return; - - ConLog.Write("Resetting memory..."); - Close(); - Init(); + MemoryBlocks.ClearF(); } void Write8(const u64 addr, const u8 data); @@ -310,22 +342,22 @@ public: u32 GetUserMemTotalSize() { - return PRXMem.GetSize(); + return UserMemory->GetSize(); } u32 GetUserMemAvailSize() { - return PRXMem.GetSize() - PRXMem.GetUsedSize(); + return UserMemory->GetSize() - UserMemory->GetUsedSize(); } u64 Alloc(const u32 size, const u32 align) { - return PRXMem.Alloc(AlignAddr(size, align)); + return UserMemory->Alloc(AlignAddr(size, align)); } bool Free(const u64 addr) { - return PRXMem.Free(addr); + return UserMemory->Free(addr); } bool Map(const u64 dst_addr, const u64 src_addr, const u32 size) @@ -348,7 +380,7 @@ public: { if(MemoryBlocks[i].GetStartAddr() == addr) { - MemoryBlocks.RemoveFAt(i); + MemoryBlocks.RemoveAt(i); } } } @@ -369,24 +401,56 @@ public: extern MemoryBase Memory; -class MemoryAllocator +template class mem_struct_ptr_t { - u32 m_addr; + const u32 m_addr; public: - MemoryAllocator(u32 size, u32 align = 1) + mem_struct_ptr_t(u32 addr) : m_addr(addr) { - m_addr = Memory.Alloc(size, align); } - ~MemoryAllocator() + operator T&() { - Memory.Free(m_addr); + return (T&)Memory[m_addr]; } - operator u32() const + operator const T&() const { - return m_addr; + return (const T&)Memory[m_addr]; + } + + T* operator -> () + { + return (T*)&Memory[m_addr]; + } + + const T* operator -> () const + { + return (const T*)&Memory[m_addr]; + } + + T& operator [](uint index) + { + return (T&)Memory[m_addr + sizeof(T) * index]; + } + + const T& operator [](uint index) const + { + return (const T&)Memory[m_addr + sizeof(T) * index]; + } + + u32 GetAddr() const { return m_addr; } + + bool IsGood() const + { + return Memory.IsGoodAddr(m_addr, sizeof(T)); + } + + mem_struct_ptr_t& operator = (const T& right) + { + memcpy(&Memory[m_addr], &right, sizeof(T)); + return *this; } }; @@ -395,35 +459,20 @@ template class mem_t const u32 m_addr; public: - mem_t(u64 addr) : m_addr(addr) + mem_t(u32 addr) : m_addr(addr) { } mem_t& operator = (T right) { - switch(sizeof(T)) - { - case 1: Memory.Write8(m_addr, right); return *this; - case 2: Memory.Write16(m_addr, right); return *this; - case 4: Memory.Write32(m_addr, right); return *this; - case 8: Memory.Write64(m_addr, right); return *this; - } + (be_t&)Memory[m_addr] = right; - assert(0); return *this; } operator const T() const { - switch(sizeof(T)) - { - case 1: return Memory.Read8(m_addr); - case 2: return Memory.Read16(m_addr); - case 4: return Memory.Read32(m_addr); - case 8: return Memory.Read64(m_addr); - } - - assert(0); + return (be_t&)Memory[m_addr]; } mem_t& operator += (T right) { return *this = (*this) + right; } @@ -437,7 +486,7 @@ public: mem_t& operator <<= (T right) { return *this = (*this) << right; } mem_t& operator >>= (T right) { return *this = (*this) >> right; } - u64 GetAddr() const { return m_addr; } + u32 GetAddr() const { return m_addr; } bool IsGood() const { @@ -447,88 +496,181 @@ public: template class mem_ptr_t { - u64 m_addr; - const u64 m_iaddr; + u32 m_addr; public: - mem_ptr_t(u64 addr) - : m_addr(addr) - , m_iaddr(addr) + mem_ptr_t(u32 addr) : m_addr(addr) { } void operator = (T right) { - switch(sizeof(T)) - { - case 1: Memory.Write8(m_addr, right); return; - case 2: Memory.Write16(m_addr, right); return; - case 4: Memory.Write32(m_addr, right); return; - case 8: Memory.Write64(m_addr, right); return; - } - - ConLog.Error("Bad mem_t size! (%d : 0x%llx)", sizeof(T), m_addr); + (be_t&)Memory[m_addr] = right; } - operator u8() const { return Memory.Read8(m_addr); } - operator u16() const { return Memory.Read16(m_addr); } - operator u32() const { return Memory.Read32(m_addr); } - operator u64() const { return Memory.Read64(m_addr); } - - u64 operator += (T right) + u32 operator += (T right) { *this = right; m_addr += sizeof(T); return m_addr; } - const T operator [] (u64 i) const + u32 GetAddr() const { return m_addr; } + u32 Skip(const u32 offset) { return m_addr += offset; } + + operator be_t*() { return GetPtr(); } + operator void*() { return GetPtr(); } + operator be_t*() const { return GetPtr(); } + operator void*() const { return GetPtr(); } + + const char* GetString() const { - const u64 offset = i*sizeof(T); - (*(mem_ptr_t*)this).m_addr += offset; - const T ret = *this; - (*(mem_ptr_t*)this).m_addr -= offset; - return ret; + return (const char*)&Memory[m_addr]; } - void Reset() { m_addr = m_iaddr; } - u64 GetCurAddr() const { return m_addr; } - u64 GetAddr() const { return m_iaddr; } - u64 SetOffset(const u32 offset) { return m_addr += offset; } + be_t* GetPtr() + { + return (be_t*)&Memory[m_addr]; + } + + const be_t* GetPtr() const + { + return (const be_t*)&Memory[m_addr]; + } }; class mem_class_t { - u64 addr; - const u64 iaddr; + u32 m_addr; public: - mem_class_t(u64 _addr) - : addr(_addr) - , iaddr(_addr) + mem_class_t(u32 addr) : m_addr(addr) { } - template u64 operator += (T right) + template u32 operator += (T right) { - mem_t m(addr); + mem_t& m((mem_t&)*this); m = right; - addr += sizeof(T); - return addr; + m_addr += sizeof(T); + return m_addr; } template operator T() { - mem_t m(addr); + mem_t& m((mem_t&)*this); const T ret = m; - addr += sizeof(T); + m_addr += sizeof(T); return ret; } - void Reset() { addr = iaddr; } - u64 GetCurAddr() const { return addr; } - u64 GetAddr() const { return iaddr; } - void SetAddr(const u64 _addr) { addr = _addr; } + u64 GetAddr() const { return m_addr; } + void SetAddr(const u64 addr) { m_addr = addr; } +}; + +template +class MemoryAllocator +{ + u32 m_addr; + u32 m_size; + T* m_ptr; + +public: + MemoryAllocator(u32 size = sizeof(T), u32 align = 1) + : m_size(size) + , m_addr(Memory.Alloc(size, align)) + , m_ptr((T*)&Memory[m_addr]) + { + } + + ~MemoryAllocator() + { + Memory.Free(m_addr); + } + + T* operator -> () + { + return m_ptr; + } + + T* GetPtr() + { + return m_ptr; + } + + const T* GetPtr() const + { + return m_ptr; + } + + const T* operator -> () const + { + return m_ptr; + } + + u32 GetAddr() const + { + return m_addr; + } + + u32 GetSize() const + { + return m_size; + } + + bool IsGood() const + { + return Memory.IsGoodAddr(m_addr, sizeof(T)); + } + + template + operator const T1() const + { + return T1(*m_ptr); + } + + template + operator T1() + { + return T1(*m_ptr); + } + + operator const T&() const + { + return *m_ptr; + } + + operator T&() + { + return *m_ptr; + } + + operator const T*() const + { + return m_ptr; + } + + operator T*() + { + return m_ptr; + } + + template + operator const mem_t() const + { + return GetAddr(); + } + + operator const mem_struct_ptr_t() const + { + return GetAddr(); + } + + template + NT* To(uint offset = 0) + { + return (NT*)(m_ptr + offset); + } }; typedef mem_t mem8_t; diff --git a/rpcs3/Emu/Memory/MemoryBlock.h b/rpcs3/Emu/Memory/MemoryBlock.h index 94d6739090..a35757468e 100644 --- a/rpcs3/Emu/Memory/MemoryBlock.h +++ b/rpcs3/Emu/Memory/MemoryBlock.h @@ -98,8 +98,30 @@ public: const u64 GetStartAddr() const { return range_start; } const u64 GetEndAddr() const { return GetStartAddr() + GetSize() - 1; } virtual const u32 GetSize() const { return range_size; } + virtual const u32 GetUsedSize() const { return GetSize(); } u8* GetMem() const { return mem; } virtual u8* GetMem(u64 addr) const { return mem + addr; } + + virtual bool Alloc(u64 addr, u32 size) { return false; } + virtual u64 Alloc(u32 size) { return 0; } + virtual bool Alloc() { return false; } + virtual bool Free(u64 addr) { return false; } +}; + +class MemoryBlockLE : public MemoryBlock +{ +public: + virtual bool Read8(const u64 addr, u8* value) override; + virtual bool Read16(const u64 addr, u16* value) override; + virtual bool Read32(const u64 addr, u32* value) override; + virtual bool Read64(const u64 addr, u64* value) override; + virtual bool Read128(const u64 addr, u128* value) override; + + virtual bool Write8(const u64 addr, const u8 value) override; + virtual bool Write16(const u64 addr, const u16 value) override; + virtual bool Write32(const u64 addr, const u32 value) override; + virtual bool Write64(const u64 addr, const u64 value) override; + virtual bool Write128(const u64 addr, const u128 value) override; }; class MemoryMirror : public MemoryBlock @@ -145,32 +167,38 @@ class NullMemoryBlock : public MemoryBlock virtual bool Write128(const u64 addr, const u128 value); }; -class DynamicMemoryBlock : public MemoryBlock +template +class DynamicMemoryBlockBase : public PT { Array m_used_mem; u32 m_max_size; public: - DynamicMemoryBlock(); + DynamicMemoryBlockBase(); const u32 GetSize() const { return m_max_size; } const u32 GetUsedSize() const; - bool IsInMyRange(const u64 addr); - bool IsInMyRange(const u64 addr, const u32 size); - bool IsMyAddress(const u64 addr); + virtual bool IsInMyRange(const u64 addr); + virtual bool IsInMyRange(const u64 addr, const u32 size); + virtual bool IsMyAddress(const u64 addr); - MemoryBlock* SetRange(const u64 start, const u32 size); + virtual MemoryBlock* SetRange(const u64 start, const u32 size); virtual void Delete(); - bool Alloc(u64 addr, u32 size); - u64 Alloc(u32 size); - bool Alloc(); - bool Free(u64 addr); + virtual bool Alloc(u64 addr, u32 size); + virtual u64 Alloc(u32 size); + virtual bool Alloc(); + virtual bool Free(u64 addr); virtual u8* GetMem(u64 addr) const; private: void AppendUsedMem(u64 addr, u32 size); }; + +#include "DynamicMemoryBlockBase.inl" + +typedef DynamicMemoryBlockBase DynamicMemoryBlock; +typedef DynamicMemoryBlockBase DynamicMemoryBlockLE; diff --git a/rpcs3/Emu/SysCalls/Callback.cpp b/rpcs3/Emu/SysCalls/Callback.cpp index def71a0e83..c062292092 100644 --- a/rpcs3/Emu/SysCalls/Callback.cpp +++ b/rpcs3/Emu/SysCalls/Callback.cpp @@ -50,11 +50,11 @@ void Callback::Branch(bool wait) { m_has_data = false; - PPCThread& new_thread = Emu.GetCPU().AddThread(PPC_THREAD_PPU); + CPUThread& new_thread = Emu.GetCPU().AddThread(CPU_THREAD_PPU); new_thread.SetEntry(m_addr); new_thread.SetPrio(1001); - new_thread.stack_size = 0x10000; + new_thread.SetStackSize(0x10000); new_thread.SetName("Callback"); new_thread.SetArg(0, a1); diff --git a/rpcs3/Emu/SysCalls/FuncList.cpp b/rpcs3/Emu/SysCalls/FuncList.cpp index e80e866100..0bd28091c4 100644 --- a/rpcs3/Emu/SysCalls/FuncList.cpp +++ b/rpcs3/Emu/SysCalls/FuncList.cpp @@ -356,8 +356,8 @@ s64 SysCalls::DoFunc(const u32 id) case 0xc8f3bd09: FUNC_LOG_ERROR("TODO: cellGcmGetCurrentField"); case 0xcaabd992: FUNC_LOG_ERROR("TODO: cellGcmInitDefaultFifoMode"); case 0xd01b570d: FUNC_LOG_ERROR("TODO: cellGcmSetGraphicsHandler"); - case 0xd0b1d189: ConLog.Error("TODO: cellGcmSetTile"); return SC_ARGS_1; - case 0xd34a420d: ConLog.Error("TODO: cellGcmSetZcull"); return SC_ARGS_1; + case 0xd0b1d189: FUNC_LOG_ERROR("TODO: cellGcmSetTile"); + case 0xd34a420d: FUNC_LOG_ERROR("TODO: cellGcmSetZcull"); case 0xd8f88e1a: FUNC_LOG_ERROR("TODO: _cellGcmSetFlipCommandWithWaitLabel"); case 0xd9a0a879: FUNC_LOG_ERROR("TODO: cellGcmGetZcullInfo"); case 0xd9b7653e: FUNC_LOG_ERROR("TODO: cellGcmUnbindTile"); @@ -817,9 +817,9 @@ s64 SysCalls::DoFunc(const u32 id) case 0x516ee89e: FUNC_LOG_ERROR("TODO: cellRescInit"); case 0x5a338cdb: FUNC_LOG_ERROR("TODO: cellRescGetBufferSize"); case 0x66f5e388: FUNC_LOG_ERROR("TODO: cellRescGetLastFlipTime"); - case 0x6cd0f95f: return cellRescSetSrc(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellRescSetSrc"); + case 0x6cd0f95f: FUNC_LOG_ERROR("TODO: cellRescSetSrc"); case 0x7af8a37f: FUNC_LOG_ERROR("TODO: cellRescSetRegisterCount"); - case 0x8107277c: return cellRescSetBufferAddress(SC_ARGS_3); //FUNC_LOG_ERROR("TODO: cellRescSetBufferAddress"); + case 0x8107277c: FUNC_LOG_ERROR("TODO: cellRescSetBufferAddress"); case 0xc47c5c22: FUNC_LOG_ERROR("TODO: cellRescGetFlipStatus"); case 0xd1ca0503: FUNC_LOG_ERROR("TODO: cellRescVideoOutResolutionId2RescBufferMode"); case 0xd3758645: FUNC_LOG_ERROR("TODO: cellRescSetVBlankHandler"); @@ -1410,19 +1410,19 @@ s64 SysCalls::DoFunc(const u32 id) case 0xa193143c: FUNC_LOG_ERROR("TODO: cellSysmoduleSetMemcontainer"); case 0x018a1381: FUNC_LOG_ERROR("TODO: cellSysutilAvcSetLayoutMode"); case 0x01f04d94: FUNC_LOG_ERROR("TODO: cellSysutilGamePowerOff_I"); - case 0x02ff3c1b: return cellSysutilUnregisterCallback(SC_ARGS_1); //FUNC_LOG_ERROR("TODO: cellSysutilUnregisterCallback"); + case 0x02ff3c1b: FUNC_LOG_ERROR("TODO: cellSysutilUnregisterCallback"); case 0x073b89d5: FUNC_LOG_ERROR("TODO: cellSysutilAvcGetSpeakerVolumeLevel"); case 0x08269f37: FUNC_LOG_ERROR("TODO: cellSysutilAvcGetShowStatus"); - case 0x0bae8772: return cellVideoOutConfigure(SC_ARGS_4); //FUNC_LOG_ERROR("TODO: cellVideoOutConfigure"); + case 0x0bae8772: FUNC_LOG_ERROR("TODO: cellVideoOutConfigure"); case 0x0c316b87: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigGetHeapSize2"); case 0x0e091c36: FUNC_LOG_ERROR("TODO: cellSaveDataUserListAutoSave"); case 0x0f03cfb0: FUNC_LOG_ERROR("TODO: cellSaveDataUserListSave"); case 0x0f8a3b6b: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigSetMimeSet"); case 0x10cabeff: FUNC_LOG_ERROR("TODO: cellWebBrowserGetUsrdataOnGameExit"); - case 0x15b0b0cd: return cellVideoOutGetConfiguration(SC_ARGS_3); //FUNC_LOG_ERROR("TODO: cellVideoOutGetConfiguration"); + case 0x15b0b0cd: FUNC_LOG_ERROR("TODO: cellVideoOutGetConfiguration"); case 0x15df71ed: FUNC_LOG_ERROR("TODO: cellSysutilAvcLoadAsync"); case 0x17dbe8b3: FUNC_LOG_ERROR("TODO: cellSysutilAvcJoinRequest"); - case 0x189a74da: return cellSysutilCheckCallback(); //FUNC_LOG_ERROR("TODO: cellSysutilCheckCallback"); + case 0x189a74da: FUNC_LOG_ERROR("TODO: cellSysutilCheckCallback"); case 0x1a91874b: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigSetFullScreen2"); case 0x1d99c3ee: FUNC_LOG_ERROR("TODO: cellOskDialogGetInputText"); case 0x1dfbfdd6: FUNC_LOG_ERROR("TODO: cellSaveDataListLoad2"); @@ -1484,8 +1484,8 @@ s64 SysCalls::DoFunc(const u32 id) case 0x71acb8d3: FUNC_LOG_ERROR("TODO: cellSysutilAvcSetVideoMuting"); case 0x744c1544: FUNC_LOG_ERROR("TODO: cellSysCacheClear"); case 0x749c9b5f: FUNC_LOG_ERROR("TODO: cellWebBrowserInitialize"); - case 0x75bbb672: return cellVideoOutGetNumberOfDevice(SC_ARGS_1); //FUNC_LOG_ERROR("TODO: cellVideoOutGetNumberOfDevice"); - case 0x7603d3db: return cellMsgDialogOpen2(SC_ARGS_5); //FUNC_LOG_ERROR("TODO: cellMsgDialogOpen2"); + case 0x75bbb672: FUNC_LOG_ERROR("TODO: cellVideoOutGetNumberOfDevice"); + case 0x7603d3db: FUNC_LOG_ERROR("TODO: cellMsgDialogOpen2"); case 0x7663e368: FUNC_LOG_ERROR("TODO: cellAudioOutGetDeviceInfo"); case 0x76948bfc: FUNC_LOG_ERROR("TODO: cellSysconfAbort"); case 0x76fc8fb1: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigSetHeapSize"); @@ -1498,7 +1498,7 @@ s64 SysCalls::DoFunc(const u32 id) case 0x7fb3c6a5: FUNC_LOG_ERROR("TODO: cellWebBrowserConfig2"); case 0x7fcfc915: FUNC_LOG_ERROR("TODO: cellOskDialogLoadAsync"); case 0x83668b8e: FUNC_LOG_ERROR("TODO: cellWebBrowserConfig"); - case 0x887572d5: return cellVideoOutGetState(SC_ARGS_3);//FUNC_LOG_ERROR("TODO: cellVideoOutGetState"); + case 0x887572d5: FUNC_LOG_ERROR("TODO: cellVideoOutGetState"); case 0x8a4cb646: FUNC_LOG_ERROR("TODO: cellWebBrowserCreateWithConfig"); case 0x8a5dbb58: FUNC_LOG_ERROR("TODO: cellWebComponentCreate"); case 0x8b7ed64b: FUNC_LOG_ERROR("TODO: cellSaveDataAutoSave2"); @@ -1515,11 +1515,11 @@ s64 SysCalls::DoFunc(const u32 id) case 0x9c9fe6a4: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigSetFunction"); case 0x9ca9ffa7: FUNC_LOG_ERROR("TODO: cellHddGameSetSystemVer"); case 0x9d6af72a: FUNC_LOG_ERROR("TODO: cellMsgDialogProgressBarSetMsg"); - case 0x9d98afa0: return cellSysutilRegisterCallback(SC_ARGS_3); //FUNC_LOG_ERROR("TODO: cellSysutilRegisterCallback"); + case 0x9d98afa0: FUNC_LOG_ERROR("TODO: cellSysutilRegisterCallback"); case 0x9dfdad46: FUNC_LOG_ERROR("TODO: cellAudioOutUnregisterCallback"); case 0x9fb97b10: FUNC_LOG_ERROR("TODO: cellWebBrowserNavigate2"); case 0xa11552f6: FUNC_LOG_ERROR("TODO: cellSysutilGetBgmPlaybackStatus"); - case 0xa322db75: return cellVideoOutGetResolutionAvailability(SC_ARGS_4); //FUNC_LOG_ERROR("TODO: cellVideoOutGetResolutionAvailability"); + case 0xa322db75: FUNC_LOG_ERROR("TODO: cellVideoOutGetResolutionAvailability"); case 0xa36335a5: FUNC_LOG_ERROR("TODO: cellSysutilDisableBgmPlaybackEx"); case 0xa4dd11cc: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigGetHeapSize"); case 0xa4ed7dfe: FUNC_LOG_ERROR("TODO: cellSaveDataDelete"); @@ -1556,7 +1556,7 @@ s64 SysCalls::DoFunc(const u32 id) case 0xdce51399: FUNC_LOG_ERROR("TODO: cellWebComponentDestroy"); case 0xdfdd302e: FUNC_LOG_ERROR("TODO: cellDiscGameRegisterDiscChangeCallback"); case 0xe22ed55d: FUNC_LOG_ERROR("TODO: cellWebBrowserConfigSetFunction2"); - case 0xe558748d: return cellVideoOutGetResolution(SC_ARGS_2); //FUNC_LOG_ERROR("TODO: cellVideoOutGetResolution"); + case 0xe558748d: FUNC_LOG_ERROR("TODO: cellVideoOutGetResolution"); case 0xe5e2b09d: FUNC_LOG_ERROR("TODO: cellAudioOutGetNumberOfDevice"); case 0xe7951dee: FUNC_LOG_ERROR("TODO: cellGameDataCheckCreate"); case 0xe7fa820b: FUNC_LOG_ERROR("TODO: cellSaveDataEnableOverlay"); @@ -2297,22 +2297,22 @@ s64 SysCalls::DoFunc(const u32 id) case 0x1ea02e2f: FUNC_LOG_ERROR("TODO: cellFsArcadeHddSerialNumber"); case 0x2664c8ae: FUNC_LOG_ERROR("TODO: cellFsStReadInit"); case 0x27800c6b: FUNC_LOG_ERROR("TODO: cellFsStRead"); - case 0x2796fdf3: return cellFsRmdir(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: cellFsRmdir"); - case 0x2cb51f0d: return cellFsClose(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: cellFsClose"); + case 0x2796fdf3: FUNC_LOG_ERROR("TODO: cellFsRmdir"); + case 0x2cb51f0d: FUNC_LOG_ERROR("TODO: cellFsClose"); case 0x2cf1296b: FUNC_LOG_ERROR("TODO: cellFsAllocateFileAreaByFdWithoutZeroFill"); case 0x3140f6e1: FUNC_LOG_ERROR("TODO: cellFsSetIoBuffer"); case 0x3394f037: FUNC_LOG_ERROR("TODO: cellFsAllocateFileAreaByFdWithInitialData"); case 0x3a1c8393: FUNC_LOG_ERROR("TODO: cellFsTruncate2"); - case 0x3f61245c: return cellFsOpendir(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellFsOpendir"); + case 0x3f61245c: FUNC_LOG_ERROR("TODO: cellFsOpendir"); case 0x4cef342e: FUNC_LOG_ERROR("TODO: cellFsAioWrite"); - case 0x4d5ff8e2: return cellFsRead(SC_ARGS_4);//FUNC_LOG_ERROR("TODO: cellFsRead"); - case 0x5c74903d: return cellFsReaddir(SC_ARGS_3);//FUNC_LOG_ERROR("TODO: cellFsReaddir"); + case 0x4d5ff8e2: FUNC_LOG_ERROR("TODO: cellFsRead"); + case 0x5c74903d: FUNC_LOG_ERROR("TODO: cellFsReaddir"); case 0x606f9f42: FUNC_LOG_ERROR("TODO: cellFsChangeFileSizeWithoutAllocation"); case 0x6d3bb15b: FUNC_LOG_ERROR("TODO: cellFsSdataOpenByFd"); - case 0x718bf5f8: return cellFsOpen(SC_ARGS_5);//FUNC_LOG_ERROR("TODO: cellFsOpen"); + case 0x718bf5f8: FUNC_LOG_ERROR("TODO: cellFsOpen"); case 0x75f16dc5: FUNC_LOG_ERROR("TODO: cellFsSetIoBufferFromDefaultContainer"); case 0x7a0329a1: FUNC_LOG_ERROR("TODO: cellFsAllocateFileAreaWithoutZeroFill"); - case 0x7de6dced: return cellFsStat(SC_ARGS_2); //FUNC_LOG_ERROR("TODO: cellFsStat"); + case 0x7de6dced: FUNC_LOG_ERROR("TODO: cellFsStat"); case 0x7f13fc8c: FUNC_LOG_ERROR("TODO: cellFsAioCancel"); case 0x7f4677a8: FUNC_LOG_ERROR("TODO: cellFsUnlink"); case 0x81f33783: FUNC_LOG_ERROR("TODO: cellFsStReadPutCurrentAddr"); @@ -2326,11 +2326,11 @@ s64 SysCalls::DoFunc(const u32 id) case 0x9b882495: FUNC_LOG_ERROR("TODO: cellFsGetDirectoryEntries"); case 0x9f951810: FUNC_LOG_ERROR("TODO: cellFsAioFinish"); case 0xa01ee33a: FUNC_LOG_ERROR("TODO: cellFsRegisterConversionCallback"); - case 0xa397d042: return cellFsLseek(SC_ARGS_4);//FUNC_LOG_ERROR("TODO: cellFsLseek"); + case 0xa397d042: FUNC_LOG_ERROR("TODO: cellFsLseek"); case 0xaa3b4bcd: FUNC_LOG_ERROR("TODO: cellFsGetFreeSize"); case 0xb1840b53: FUNC_LOG_ERROR("TODO: cellFsSdataOpen"); case 0xb3afee8b: FUNC_LOG_ERROR("TODO: cellFsStReadGetRingBuf"); - case 0xba901fe6: return cellFsMkdir(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellFsMkdir"); + case 0xba901fe6: FUNC_LOG_ERROR("TODO: cellFsMkdir"); case 0xbd273a88: FUNC_LOG_ERROR("TODO: cellFsStReadGetRegid"); case 0xbef554a4: FUNC_LOG_ERROR("TODO: cellFsUtime"); case 0xc1c507e7: FUNC_LOG_ERROR("TODO: cellFsAioRead"); @@ -2340,16 +2340,16 @@ s64 SysCalls::DoFunc(const u32 id) case 0xd73938df: FUNC_LOG_ERROR("TODO: cellFsStReadFinish"); case 0xdb869f20: FUNC_LOG_ERROR("TODO: cellFsAioInit"); case 0xe15939c3: FUNC_LOG_ERROR("TODO: cellFsChangeFileSizeByFdWithoutAllocation"); - case 0xecdcf2ab: return cellFsWrite(SC_ARGS_4);//FUNC_LOG_ERROR("TODO: cellFsWrite"); - case 0xef3efa34: return cellFsFstat(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellFsFstat"); - case 0xf12eecc8: return cellFsRename(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellFsRename"); + case 0xecdcf2ab: FUNC_LOG_ERROR("TODO: cellFsWrite"); + case 0xef3efa34: FUNC_LOG_ERROR("TODO: cellFsFstat"); + case 0xf12eecc8: FUNC_LOG_ERROR("TODO: cellFsRename"); case 0xf8e5d9a0: FUNC_LOG_ERROR("TODO: cellFsStReadStop"); case 0xf94baa80: FUNC_LOG_ERROR("TODO: cellFsUnregisterL10nCallbacks"); - case 0xff42dcc3: return cellFsClosedir(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: cellFsClosedir"); + case 0xff42dcc3: FUNC_LOG_ERROR("TODO: cellFsClosedir"); case 0x068fcbc6: FUNC_LOG_ERROR("TODO: sys_config_start"); case 0x0d5f2c14: FUNC_LOG_ERROR("TODO: cellPadClearBuf"); case 0x0e2dfaad: FUNC_LOG_ERROR("TODO: cellPadInfoPressMode"); - case 0x1cf98800: return cellPadInit(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: cellPadInit"); + case 0x1cf98800: FUNC_LOG_ERROR("TODO: cellPadInit"); case 0x1f71ecbe: FUNC_LOG_ERROR("TODO: cellKbGetConfiguration"); case 0x2073b7f6: FUNC_LOG_ERROR("TODO: cellKbClearBuf"); case 0x20a97ba2: FUNC_LOG_ERROR("TODO: cellPadLddRegisterController"); @@ -2365,24 +2365,24 @@ s64 SysCalls::DoFunc(const u32 id) case 0x4ab1fa77: FUNC_LOG_ERROR("TODO: cellKbCnvRawCode"); case 0x4cc9b68d: FUNC_LOG_ERROR("TODO: cellPadPeriphGetInfo"); case 0x4d0b3b1f: FUNC_LOG_ERROR("TODO: cellMouseInfoTabletMode"); - case 0x4d9b75d5: return cellPadEnd();//FUNC_LOG_ERROR("TODO: cellPadEnd"); - case 0x578e3c98: return cellPadSetPortSetting(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellPadSetPortSetting"); + case 0x4d9b75d5: FUNC_LOG_ERROR("TODO: cellPadEnd"); + case 0x578e3c98: FUNC_LOG_ERROR("TODO: cellPadSetPortSetting"); case 0x5baf30fb: FUNC_LOG_ERROR("TODO: cellMouseGetInfo"); case 0x5f81900c: FUNC_LOG_ERROR("TODO: sys_config_unregister_service"); case 0x6ae10596: FUNC_LOG_ERROR("TODO: sys_config_add_service_listener"); - case 0x6bc09c61: return cellPadGetDataExtra(SC_ARGS_3);//FUNC_LOG_ERROR("TODO: cellPadGetDataExtra"); + case 0x6bc09c61: FUNC_LOG_ERROR("TODO: cellPadGetDataExtra"); case 0x6bd131f0: FUNC_LOG_ERROR("TODO: cellMouseGetDataList"); case 0x6d367953: FUNC_LOG_ERROR("TODO: sys_config_stop"); case 0x78200559: FUNC_LOG_ERROR("TODO: cellPadInfoSensorMode"); case 0x78f058a2: FUNC_LOG_ERROR("TODO: sys_config_register_service"); case 0x7c5d5fc1: FUNC_LOG_ERROR("TODO: cellPadDbgPeriphRegisterDevice"); case 0x8a00f264: FUNC_LOG_ERROR("TODO: cellPadPeriphGetData"); - case 0x8b72cda1: return cellPadGetData(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: cellPadGetData"); + case 0x8b72cda1: FUNC_LOG_ERROR("TODO: cellPadGetData"); case 0x8b8231e5: FUNC_LOG_ERROR("TODO: cellPadLddGetPortNo"); case 0x94b98e39: FUNC_LOG_ERROR("TODO: cellPadDbgLddSetDataInsertMode"); case 0xa328cc35: FUNC_LOG_ERROR("TODO: cellMouseGetRawData"); case 0xa5f85e4d: FUNC_LOG_ERROR("TODO: cellKbSetCodeType"); - case 0xa703a51d: return cellPadGetInfo2(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: cellPadGetInfo2"); + case 0xa703a51d: FUNC_LOG_ERROR("TODO: cellPadGetInfo2"); case 0xa74396e5: FUNC_LOG_ERROR("TODO: cellPadDbgLddRegisterController"); case 0xbafd6409: FUNC_LOG_ERROR("TODO: cellPadLddDataInsert"); case 0xbe5be3ba: FUNC_LOG_ERROR("TODO: cellPadSetSensorMode"); @@ -3563,28 +3563,25 @@ s64 SysCalls::DoFunc(const u32 id) case 0x05c65656: FUNC_LOG_ERROR("TODO: sys_mempool_try_allocate_block"); case 0x0618936b: FUNC_LOG_ERROR("TODO: _sys_vsnprintf"); case 0x06574237: FUNC_LOG_ERROR("TODO: _sys_snprintf"); - case 0x1573dc3f: return sys_lwmutex_lock(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: sys_lwmutex_lock"); + case 0x1573dc3f: FUNC_LOG_ERROR("TODO: sys_lwmutex_lock"); case 0x191f0c4a: FUNC_LOG_ERROR("TODO: _sys_strrchr"); case 0x1ae10b92: FUNC_LOG_ERROR("TODO: _sys_spu_printf_attach_thread"); - case 0x1bc200f4: return sys_lwmutex_unlock(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: sys_lwmutex_unlock"); + case 0x1bc200f4: FUNC_LOG_ERROR("TODO: sys_lwmutex_unlock"); case 0x1c9a942c: FUNC_LOG_ERROR("TODO: sys_lwcond_destroy"); case 0x1ca525a2: FUNC_LOG_ERROR("TODO: _sys_strncasecmp"); case 0x1ed454ce: FUNC_LOG_ERROR("TODO: sys_spu_elf_get_information"); - case 0x24a1ea07: return sys_ppu_thread_create(SC_ARGS_7);//FUNC_LOG_ERROR("TODO: sys_ppu_thread_create"); + case 0x24a1ea07: FUNC_LOG_ERROR("TODO: sys_ppu_thread_create"); case 0x25596f51: FUNC_LOG_ERROR("TODO: sys_mempool_get_count"); case 0x26090058: FUNC_LOG_ERROR("TODO: sys_prx_load_module"); case 0x27427742: FUNC_LOG_ERROR("TODO: _sys_memmove"); case 0x2a6d9d51: FUNC_LOG_ERROR("TODO: sys_lwcond_wait"); case 0x2c847572: FUNC_LOG_ERROR("TODO: _sys_process_atexitspawn"); - case 0x2d36462b: - //FUNC_LOG_ERROR("TODO: _sys_strlen"); - ConLog.Write("sys_strlen(addr=0x%x(%s))", SC_ARGS_1, Memory.ReadString(SC_ARGS_1)); - return strlen((const char*)&Memory[SC_ARGS_1]); - case 0x2f85c0ef: return sys_lwmutex_create(SC_ARGS_2);//FUNC_LOG_ERROR("TODO: sys_lwmutex_create"); + case 0x2d36462b: FUNC_LOG_ERROR("TODO: _sys_strlen"); + case 0x2f85c0ef: FUNC_LOG_ERROR("TODO: sys_lwmutex_create"); case 0x3172759d: FUNC_LOG_ERROR("TODO: sys_game_get_temperature"); case 0x318f17e1: FUNC_LOG_ERROR("TODO: _sys_memalign"); - case 0x350d454e: return sys_ppu_thread_get_id(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: sys_ppu_thread_get_id"); - case 0x35168520: return sys_heap_malloc(SC_ARGS_2); //FUNC_LOG_ERROR("TODO: _sys_heap_malloc"); + case 0x350d454e: FUNC_LOG_ERROR("TODO: sys_ppu_thread_get_id"); + case 0x35168520: FUNC_LOG_ERROR("TODO: _sys_heap_malloc"); case 0x3bd53c7b: FUNC_LOG_ERROR("TODO: _sys_memchr"); case 0x3dd4a957: FUNC_LOG_ERROR("TODO: sys_ppu_thread_register_atexit"); case 0x409ad939: FUNC_LOG_ERROR("TODO: sys_mmapper_free_memory"); @@ -3602,28 +3599,18 @@ s64 SysCalls::DoFunc(const u32 id) case 0x608212fc: FUNC_LOG_ERROR("TODO: sys_mempool_free_block"); case 0x620e35a7: FUNC_LOG_ERROR("TODO: sys_game_get_system_sw_version"); case 0x67f9fedb: FUNC_LOG_ERROR("TODO: sys_game_process_exitspawn2"); - case 0x68b9b011: - ConLog.Warning("_sys_memset(0x%llx, 0x%lld, 0x%lld)", SC_ARGS_3); - return - (u32)memset(Memory.GetMemFromAddr(CPU.GPR[3]), CPU.GPR[4], CPU.GPR[5]) - - Memory.GetMemByAddr(CPU.GPR[3]).GetStartAddr(); - FUNC_LOG_ERROR("TODO: _sys_memset"); + case 0x68b9b011: FUNC_LOG_ERROR("TODO: _sys_memset"); case 0x6bf66ea7: FUNC_LOG_ERROR("TODO: _sys_memcpy"); case 0x6e05231d: FUNC_LOG_ERROR("TODO: sys_game_watchdog_stop"); case 0x70258515: FUNC_LOG_ERROR("TODO: sys_mmapper_allocate_memory_from_container"); case 0x71a8472a: FUNC_LOG_ERROR("TODO: sys_get_random_number"); case 0x722a0254: FUNC_LOG_ERROR("TODO: sys_spinlock_trylock"); case 0x74311398: FUNC_LOG_ERROR("TODO: sys_prx_get_my_module_id"); - case 0x744680a2: - // FUNC_LOG_ERROR("TODO: sys_initialize_tls"); - ConLog.Warning("sys_initialize_tls()"); - //CPU.GPR[4] = Emu.GetTLSFilesz(); - //CPU.GPR[5] = Emu.GetTLSMemsz(); - return 0;//Memory.MainMem.Alloc(Emu.GetTLSMemsz());//Emu.GetTLSAddr(); + case 0x744680a2: FUNC_LOG_ERROR("TODO: sys_initialize_tls"); case 0x7498887b: FUNC_LOG_ERROR("TODO: _sys_strchr"); case 0x791b9219: FUNC_LOG_ERROR("TODO: _sys_vsprintf"); case 0x80fb0c19: FUNC_LOG_ERROR("TODO: sys_prx_stop_module"); - case 0x8461e528: return sys_time_get_system_time();//FUNC_LOG_ERROR("TODO: sys_time_get_system_time"); + case 0x8461e528: FUNC_LOG_ERROR("TODO: sys_time_get_system_time"); case 0x84bb6774: FUNC_LOG_ERROR("TODO: sys_prx_get_module_info"); case 0x893305fa: FUNC_LOG_ERROR("TODO: sys_raw_spu_load"); case 0x8985b5b6: FUNC_LOG_ERROR("TODO: _sys_heap_stats"); @@ -3640,33 +3627,27 @@ s64 SysCalls::DoFunc(const u32 id) case 0x9f18429d: FUNC_LOG_ERROR("TODO: sys_prx_start_module"); case 0x9f950780: FUNC_LOG_ERROR("TODO: sys_game_get_rtc_status"); case 0xa146a143: FUNC_LOG_ERROR("TODO: sys_mempool_allocate_block"); - case 0xa1f9eafe: - ConLog.Warning("_sys_sprintf(0x%llx, 0x%llx(%s), 0x%llx)", CPU.GPR[3], CPU.GPR[4], Memory.ReadString(CPU.GPR[4]), CPU.GPR[5]); - return vsprintf((char*)Memory.GetMemFromAddr(CPU.GPR[3]), Memory.ReadString(CPU.GPR[4]), (char*)Memory.GetMemFromAddr(CPU.GPR[5])); - FUNC_LOG_ERROR("TODO: _sys_sprintf"); + case 0xa1f9eafe: FUNC_LOG_ERROR("TODO: _sys_sprintf"); case 0xa285139d: FUNC_LOG_ERROR("TODO: sys_spinlock_lock"); case 0xa2c7ba64: FUNC_LOG_ERROR("TODO: sys_prx_exitspawn_with_level"); case 0xa330ad84: FUNC_LOG_ERROR("TODO: sys_prx_load_module_on_memcontainer_by_fd"); - case 0xa3e3be68: sys_ppu_thread_once(SC_ARGS_2); return SC_ARGS_1;//FUNC_LOG_ERROR("TODO: sys_ppu_thread_once"); + case 0xa3e3be68: FUNC_LOG_ERROR("TODO: sys_ppu_thread_once"); case 0xa5d06bf0: FUNC_LOG_ERROR("TODO: sys_prx_get_module_list"); case 0xaa6d9bff: FUNC_LOG_ERROR("TODO: sys_prx_load_module_on_memcontainer"); case 0xac6fc404: FUNC_LOG_ERROR("TODO: sys_ppu_thread_unregister_atexit"); case 0xacad8fb6: FUNC_LOG_ERROR("TODO: sys_game_watchdog_clear"); - case 0xaeb78725: return sys_lwmutex_trylock(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: sys_lwmutex_trylock"); + case 0xaeb78725: FUNC_LOG_ERROR("TODO: sys_lwmutex_trylock"); case 0xaede4b03: FUNC_LOG_ERROR("TODO: _sys_heap_delete_heap"); - case 0xaff080a4: return sys_ppu_thread_exit(SC_ARGS_1);//FUNC_LOG_ERROR("TODO: sys_ppu_thread_exit"); - case 0xb257540b: return sys_mmapper_allocate_memory(SC_ARGS_3); //FUNC_LOG_ERROR("TODO: sys_mmapper_allocate_memory"); + case 0xaff080a4: FUNC_LOG_ERROR("TODO: sys_ppu_thread_exit"); + case 0xb257540b: FUNC_LOG_ERROR("TODO: sys_mmapper_allocate_memory"); case 0xb27c8ae7: FUNC_LOG_ERROR("TODO: sys_prx_load_module_list"); - case 0xb2fcf2c8: return sys_heap_create_heap(SC_ARGS_3);//FUNC_LOG_ERROR("TODO: _sys_heap_create_heap"); + case 0xb2fcf2c8: FUNC_LOG_ERROR("TODO: _sys_heap_create_heap"); case 0xb3bbcf2a: FUNC_LOG_ERROR("TODO: _sys_spu_printf_detach_thread"); case 0xb6369393: FUNC_LOG_ERROR("TODO: _sys_heap_get_total_free_size"); case 0xb995662e: FUNC_LOG_ERROR("TODO: sys_raw_spu_image_load"); case 0xb9bf1078: FUNC_LOG_ERROR("TODO: _sys_heap_alloc_heap_memory"); - case 0xbdb18f83: - ConLog.Warning("_sys_malloc(0x%llx)", SC_ARGS_1); - return Memory.Alloc(CPU.GPR[3], Emu.GetMallocPageSize()); - FUNC_LOG_ERROR("TODO: _sys_malloc"); - case 0xc3476d0c: return sys_lwmutex_destroy(SC_ARGS_1);////FUNC_LOG_ERROR("TODO: sys_lwmutex_destroy"); + case 0xbdb18f83: FUNC_LOG_ERROR("TODO: _sys_malloc"); + case 0xc3476d0c: FUNC_LOG_ERROR("TODO: sys_lwmutex_destroy"); case 0xc4fd6121: FUNC_LOG_ERROR("TODO: _sys_qsort"); case 0xca9a60bf: FUNC_LOG_ERROR("TODO: sys_mempool_create"); case 0xd0ea47a7: FUNC_LOG_ERROR("TODO: sys_prx_unregister_library"); @@ -3674,13 +3655,13 @@ s64 SysCalls::DoFunc(const u32 id) case 0xd3039d4d: FUNC_LOG_ERROR("TODO: _sys_strncpy"); case 0xda0eb71a: FUNC_LOG_ERROR("TODO: sys_lwcond_create"); case 0xdb6b3250: FUNC_LOG_ERROR("TODO: sys_spu_elf_get_segments"); - case 0xdc578057: return sys_mmapper_map_memory(SC_ARGS_3); //FUNC_LOG_ERROR("TODO: sys_mmapper_map_memory"); + case 0xdc578057: FUNC_LOG_ERROR("TODO: sys_mmapper_map_memory"); case 0xdd0c1e09: FUNC_LOG_ERROR("TODO: _sys_spu_printf_attach_group"); case 0xdd3b27ac: FUNC_LOG_ERROR("TODO: _sys_spu_printf_finalize"); case 0xe0998dbf: FUNC_LOG_ERROR("TODO: sys_prx_get_module_id_by_name"); case 0xe0da8efd: FUNC_LOG_ERROR("TODO: sys_spu_image_close"); case 0xe66bac36: FUNC_LOG_ERROR("TODO: console_putc"); - case 0xe6f2c1e7: return sys_process_exit(SC_ARGS_1);///FUNC_LOG_ERROR("TODO: sys_process_exit"); + case 0xe6f2c1e7: FUNC_LOG_ERROR("TODO: sys_process_exit"); case 0xe76964f5: FUNC_LOG_ERROR("TODO: sys_game_board_storage_read"); case 0xe7ef3a80: FUNC_LOG_ERROR("TODO: sys_prx_load_module_list_on_memcontainer"); case 0xe9a1bd84: FUNC_LOG_ERROR("TODO: sys_lwcond_signal_all"); @@ -3693,7 +3674,7 @@ s64 SysCalls::DoFunc(const u32 id) case 0xf7f7fb20: FUNC_LOG_ERROR("TODO: _sys_free"); case 0xfa7f693d: FUNC_LOG_ERROR("TODO: _sys_vprintf"); case 0xfb5db080: FUNC_LOG_ERROR("TODO: _sys_memcmp"); - case 0xfc52a7a9: return sys_game_process_exitspawn(SC_ARGS_7); FUNC_LOG_ERROR("TODO: sys_game_process_exitspawn"); + case 0xfc52a7a9: FUNC_LOG_ERROR("TODO: sys_game_process_exitspawn"); } ConLog.Error("Unknown func id: 0x%08x", id); diff --git a/rpcs3/Emu/SysCalls/Modules/cellAudio.cpp b/rpcs3/Emu/SysCalls/Modules/cellAudio.cpp index 4ec55211a8..1787456e3a 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellAudio.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellAudio.cpp @@ -2,6 +2,7 @@ #include "Emu/SysCalls/SysCalls.h" #include "Emu/SysCalls/SC_FUNC.h" +<<<<<<< HEAD // Initialization and Termination Functions; @@ -69,22 +70,98 @@ u64 nChannel; u64 nBlock; u64 attr; float level; +======= +void cellAudio_init(); +Module cellAudio(0x0011, cellAudio_init); + +enum +{ + //libaudio Error Codes + CELL_AUDIO_ERROR_ALREADY_INIT = 0x80310701, + CELL_AUDIO_ERROR_AUDIOSYSTEM = 0x80310702, + CELL_AUDIO_ERROR_NOT_INIT = 0x80310703, + CELL_AUDIO_ERROR_PARAM = 0x80310704, + CELL_AUDIO_ERROR_PORT_FULL = 0x80310705, + CELL_AUDIO_ERROR_PORT_ALREADY_RUN = 0x80310706, + CELL_AUDIO_ERROR_PORT_NOT_OPEN = 0x80310707, + CELL_AUDIO_ERROR_PORT_NOT_RUN = 0x80310708, + CELL_AUDIO_ERROR_TRANS_EVENT = 0x80310709, + CELL_AUDIO_ERROR_PORT_OPEN = 0x8031070a, + CELL_AUDIO_ERROR_SHAREDMEMORY = 0x8031070b, + CELL_AUDIO_ERROR_MUTEX = 0x8031070c, + CELL_AUDIO_ERROR_EVENT_QUEUE = 0x8031070d, + CELL_AUDIO_ERROR_AUDIOSYSTEM_NOT_FOUND = 0x8031070e, + CELL_AUDIO_ERROR_TAG_NOT_FOUND = 0x8031070f, + + //libmixer Error Codes + CELL_LIBMIXER_ERROR_NOT_INITIALIZED = 0x80310002, + CELL_LIBMIXER_ERROR_INVALID_PARAMATER = 0x80310003, + CELL_LIBMIXER_ERROR_NO_MEMORY = 0x80310005, + CELL_LIBMIXER_ERROR_ALREADY_EXIST = 0x80310006, + CELL_LIBMIXER_ERROR_FULL = 0x80310007, + CELL_LIBMIXER_ERROR_NOT_EXIST = 0x80310008, + CELL_LIBMIXER_ERROR_TYPE_MISMATCH = 0x80310009, + CELL_LIBMIXER_ERROR_NOT_FOUND = 0x8031000a, + + //libsnd3 Error Codes + CELL_SND3_ERROR_PARAM = 0x80310301, + CELL_SND3_ERROR_CREATE_MUTEX = 0x80310302, + CELL_SND3_ERROR_SYNTH = 0x80310303, + CELL_SND3_ERROR_ALREADY = 0x80310304, + CELL_SND3_ERROR_NOTINIT = 0x80310305, + CELL_SND3_ERROR_SMFFULL = 0x80310306, + CELL_SND3_ERROR_HD3ID = 0x80310307, + CELL_SND3_ERROR_SMF = 0x80310308, + CELL_SND3_ERROR_SMFCTX = 0x80310309, + CELL_SND3_ERROR_FORMAT = 0x8031030a, + CELL_SND3_ERROR_SMFID = 0x8031030b, + CELL_SND3_ERROR_SOUNDDATAFULL = 0x8031030c, + CELL_SND3_ERROR_VOICENUM = 0x8031030d, + CELL_SND3_ERROR_RESERVEDVOICE = 0x8031030e, + CELL_SND3_ERROR_REQUESTQUEFULL = 0x8031030f, + CELL_SND3_ERROR_OUTPUTMODE = 0x80310310, + + //libsynt2 Error Codes + CELL_SOUND_SYNTH2_ERROR_FATAL = 0x80310201, + CELL_SOUND_SYNTH2_ERROR_INVALID_PARAMETER = 0x80310202, + CELL_SOUND_SYNTH2_ERROR_ALREADY_INITIALIZED = 0x80310203, +}; + + +//libaudio datatypes +struct CellAudioPortParam +{ + u64 nChannel; + u64 nBlock; + u64 attr; + float level; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellAudioPortConfig { +<<<<<<< HEAD u32 readIndexAddr; u32 status; u64 nChannel; u64 nBlock; u32 portSize; u32 portAddr; +======= + u32 readIndexAddr; + u32 status; + u64 nChannel; + u64 nBlock; + u32 portSize; + u32 portAddr; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; CellAudioPortParam current_AudioPortParam; CellAudioPortConfig current_AudioPortConfig; //libmixer datatypes +<<<<<<< HEAD typedef void * CellAANHandle; @@ -93,10 +170,19 @@ struct CellSSPlayerConfig { u32 channels; u32 outputMode; +======= +typedef void * CellAANHandle; + +struct CellSSPlayerConfig +{ + u32 channels; + u32 outputMode; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSSPlayerWaveParam { +<<<<<<< HEAD void *addr; int format; u32 samples; @@ -110,33 +196,67 @@ struct CellSSPlayerCommonParam { u32 loopMode; u32 attackMode; +======= + void *addr; + int format; + u32 samples; + u32 loopStartOffset; + u32 startOffset; +}; + +struct CellSSPlayerCommonParam +{ + u32 loopMode; + u32 attackMode; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSurMixerPosition { +<<<<<<< HEAD float x; float y; float z; +======= + float x; + float y; + float z; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSSPlayerRuntimeInfo { +<<<<<<< HEAD float level; float speed; CellSurMixerPosition position; +======= + float level; + float speed; + CellSurMixerPosition position; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSurMixerConfig { +<<<<<<< HEAD s32 priority; u32 chStrips1; u32 chStrips2; u32 chStrips6; u32 chStrips8; +======= + s32 priority; + u32 chStrips1; + u32 chStrips2; + u32 chStrips6; + u32 chStrips8; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSurMixerChStripParam { +<<<<<<< HEAD u32 param; void *attribute; int dBSwitch; @@ -150,37 +270,75 @@ int intVal; struct CellSnd3DataCtx { s8 system; //[CELL_SND3_DATA_CTX_SIZE], unknown identifier +======= + u32 param; + void *attribute; + int dBSwitch; + float floatVal; + int intVal; +}; + +CellSSPlayerWaveParam current_SSPlayerWaveParam; + +//libsnd3 datatypes +struct CellSnd3DataCtx +{ + s8 system; //[CELL_SND3_DATA_CTX_SIZE], unknown identifier +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSnd3SmfCtx { +<<<<<<< HEAD s8 system; //[CELL_SND3_SMF_CTX_SIZE], unknown identifier +======= + s8 system; //[CELL_SND3_SMF_CTX_SIZE], unknown identifier +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSnd3KeyOnParam { +<<<<<<< HEAD u8 vel; u8 pan; u8 panEx; s32 addPitch; +======= + u8 vel; + u8 pan; + u8 panEx; + s32 addPitch; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSnd3VoiceBitCtx { +<<<<<<< HEAD u32 core; //[CELL_SND3_MAX_CORE], unknown identifier +======= + u32 core; //[CELL_SND3_MAX_CORE], unknown identifier +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSnd3RequestQueueCtx { +<<<<<<< HEAD void *frontQueue; u32 frontQueueSize; void *rearQueue; u32 rearQueueSize; +======= + void *frontQueue; + u32 frontQueueSize; + void *rearQueue; + u32 rearQueueSize; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; //libsynt2 datatypes struct CellSoundSynth2EffectAttr { +<<<<<<< HEAD u16 core; u16 mode; s16 depth_L; @@ -193,6 +351,20 @@ u16 feedback; bool g_is_audio_initialized = false; int cellAudioInit (void) +======= + u16 core; + u16 mode; + s16 depth_L; + s16 depth_R; + u16 delay; + u16 feedback; +}; + +// libaudio Functions +bool g_is_audio_initialized = false; + +int cellAudioInit() +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); if(g_is_audio_initialized) return CELL_AUDIO_ERROR_ALREADY_INIT; @@ -200,7 +372,11 @@ int cellAudioInit (void) return CELL_OK; } +<<<<<<< HEAD s32 cellAudioQuit(void) +======= +int cellAudioQuit() +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); if (g_is_audio_initialized) return CELL_AUDIO_ERROR_NOT_INIT; @@ -209,9 +385,16 @@ s32 cellAudioQuit(void) } // Audio Ports Setting/Operation Functions +<<<<<<< HEAD bool g_is_audio_port_open = false; int cellAudioPortOpen () //CellAudioPortParam *audioParam, u32 *portNum +======= +bool g_is_audio_port_open = false; +bool g_is_audio_port_start = false; + +int cellAudioPortOpen() //CellAudioPortParam *audioParam, u32 *portNum +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); if(g_is_audio_port_open) return CELL_AUDIO_ERROR_PORT_OPEN; @@ -219,7 +402,11 @@ int cellAudioPortOpen () //CellAudioPortParam *audioParam, u32 *portNum return CELL_OK; } +<<<<<<< HEAD int cellAudioPortClose (u32 portNum) +======= +int cellAudioPortClose(u32 portNum) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); if(g_is_audio_port_open) return CELL_AUDIO_ERROR_PORT_NOT_OPEN; @@ -227,8 +414,12 @@ int cellAudioPortClose (u32 portNum) return CELL_OK; } +<<<<<<< HEAD bool g_is_audio_port_start = false; int cellAudioPortStart (u32 portNum) +======= +int cellAudioPortStart(u32 portNum) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); if(g_is_audio_port_start) return CELL_AUDIO_ERROR_PORT_ALREADY_RUN; @@ -236,7 +427,11 @@ int cellAudioPortStart (u32 portNum) return CELL_OK; } +<<<<<<< HEAD int cellAudioPortStop (u32 portNum) +======= +int cellAudioPortStop(u32 portNum) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); if(g_is_audio_port_start) return CELL_AUDIO_ERROR_PORT_NOT_RUN; @@ -244,105 +439,174 @@ int cellAudioPortStop (u32 portNum) return CELL_OK; } +<<<<<<< HEAD int cellAudioGetPortTimestamp () //u32 portNum, u64 tag, u64 *stamp +======= +int cellAudioGetPortTimestamp() //u32 portNum, u64 tag, u64 *stamp +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioGetPortConfig () //u32 portNum, CellAudioPortConfig *portConfig +======= +int cellAudioGetPortConfig() //u32 portNum, CellAudioPortConfig *portConfig +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioGetPortBlockTag () //u32 portNum, u64 blockNo, u64 *tag +======= +int cellAudioGetPortBlockTag() //u32 portNum, u64 blockNo, u64 *tag +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC (cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioSetPortLevel (u32 portNum, float level) +======= +int cellAudioSetPortLevel(u32 portNum, float level) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD // Utility Functions int cellAudioCreateNotifyEventQueue () //u32 *id, u64 *key +======= +// Utility Functions +int cellAudioCreateNotifyEventQueue() //u32 *id, u64 *key +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioCreateNotifyEventQueueEx (u32 *id, u64 *key, u32 iFlags) +======= +int cellAudioCreateNotifyEventQueueEx(u32 *id, u64 *key, u32 iFlags) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioSetNotifyEventQueue (u64 key) +======= +int cellAudioSetNotifyEventQueue(u64 key) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioSetNotifyEventQueueEx (u64 key, u32 iFlags) +======= +int cellAudioSetNotifyEventQueueEx(u64 key, u32 iFlags) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioRemoveNotifyEventQueue (u64 key) +======= +int cellAudioRemoveNotifyEventQueue(u64 key) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioRemoveNotifyEventQueueEx (u64 key, u32 iFlags) +======= +int cellAudioRemoveNotifyEventQueueEx(u64 key, u32 iFlags) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioAddData () //u32 portNum, float *src, unsigned int samples, float volume +======= +int cellAudioAddData() //u32 portNum, float *src, unsigned int samples, float volume +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioAdd2chData () //u32 portNum, float *src, unsigned int samples, float volume +======= +int cellAudioAdd2chData() //u32 portNum, float *src, unsigned int samples, float volume +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioMiscSetAccessoryVolume (u32 devNum, float volume) +======= +int cellAudioMiscSetAccessoryVolume(u32 devNum, float volume) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioSendAck (u64 data3) +======= +int cellAudioSendAck(u64 data3) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioSetPersonalDevice (int iPersonalStream, int iDevice) +======= +int cellAudioSetPersonalDevice(int iPersonalStream, int iDevice) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioUnsetPersonalDevice (int iPersonalStream) +======= +int cellAudioUnsetPersonalDevice(int iPersonalStream) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD int cellAudioAdd6chData (u32 portNum, float *src, float volume) +======= +int cellAudioAdd6chData(u32 portNum, float *src, float volume) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; @@ -351,120 +615,197 @@ int cellAudioAdd6chData (u32 portNum, float *src, float volume) //Callback Functions typedef int (*CellSurMixerNotifyCallbackFunction)(void *arg, u32 counter, u32 samples); //Currently unused. +<<<<<<< HEAD //*libmixer Functions, NON active in this moment*// int cellAANConnect (CellAANHandle receive, u32 receivePortNo, CellAANHandle source, u32 sourcePortNo) +======= +// libmixer Functions, NOT active in this moment +int cellAANConnect(CellAANHandle receive, u32 receivePortNo, CellAANHandle source, u32 sourcePortNo) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellAANDisconnect (CellAANHandle receive, u32 receivePortNo, CellAANHandle source, u32 sourcePortNo) +======= +int cellAANDisconnect(CellAANHandle receive, u32 receivePortNo, CellAANHandle source, u32 sourcePortNo) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellAANAddData (CellAANHandle handle, u32 port, u32 offset, float *addr, u32 samples) +======= +int cellAANAddData(CellAANHandle handle, u32 port, u32 offset, float *addr, u32 samples) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSSPlayerCreate (CellAANHandle *handle, CellSSPlayerConfig *config) +======= +int cellSSPlayerCreate(CellAANHandle *handle, CellSSPlayerConfig *config) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSSPlayerRemove (CellAANHandle handle) +======= +int cellSSPlayerRemove(CellAANHandle handle) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSSPlayerSetWave () //CellAANHandle handle, CellSSPlayerWaveParam *waveInfo, CellSSPlayerCommonParam *commonInfo //mem_class_t waveInfo +======= +int cellSSPlayerSetWave() //CellAANHandle handle, CellSSPlayerWaveParam *waveInfo, CellSSPlayerCommonParam *commonInfo //mem_class_t waveInfo +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSSPlayerPlay () //CellAANHandle handle, CellSSPlayerRuntimeInfo *info +======= +int cellSSPlayerPlay() //CellAANHandle handle, CellSSPlayerRuntimeInfo *info +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSSPlayerStop () //CellAANHandle handle, u32 mode +======= +int cellSSPlayerStop() //CellAANHandle handle, u32 mode +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSSPlayerSetParam () //CellAANHandle handle, CellSSPlayerRuntimeInfo *info +======= +int cellSSPlayerSetParam() //CellAANHandle handle, CellSSPlayerRuntimeInfo *info +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD s32 cellSSPlayerGetState () //CellAANHandle handle +======= +s32 cellSSPlayerGetState() //CellAANHandle handle +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerCreate () //const CellSurMixerConfig *config +======= +int cellSurMixerCreate() //const CellSurMixerConfig *config +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerGetAANHandle () //CellAANHandle *handle +======= +int cellSurMixerGetAANHandle() //CellAANHandle *handle +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerChStripGetAANPortNo () //u32 *port, u32 type, u32 index +======= +int cellSurMixerChStripGetAANPortNo() //u32 *port, u32 type, u32 index +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerSetNotifyCallback () //CellSurMixerNotifyCallbackFunction callback, void *arg +======= +int cellSurMixerSetNotifyCallback() //CellSurMixerNotifyCallbackFunction callback, void *arg +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerRemoveNotifyCallback () //CellSurMixerNotifyCallbackFunction callback +======= +int cellSurMixerRemoveNotifyCallback() //CellSurMixerNotifyCallbackFunction callback +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerStart(void) +======= +int cellSurMixerStart() +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerSurBusAddData () //u32 busNo, u32 offset, float *addr, u32 samples +======= +int cellSurMixerSurBusAddData() //u32 busNo, u32 offset, float *addr, u32 samples +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerSetParameter () //u32 param, float value +======= +int cellSurMixerSetParameter() //u32 param, float value +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerChStripSetParameter () //u32 type, u32 index, CellSurMixerChStripParam *param +======= +int cellSurMixerChStripSetParameter() //u32 type, u32 index, CellSurMixerChStripParam *param +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; @@ -476,129 +817,210 @@ int cellSurMixerPause() //u32 switch return 0; } +<<<<<<< HEAD int cellSurMixerGetCurrentBlockTag () //u64 *tag +======= +int cellSurMixerGetCurrentBlockTag() //u64 *tag +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD int cellSurMixerGetTimestamp () //u64 tag, u64 *stamp +======= +int cellSurMixerGetTimestamp() //u64 tag, u64 *stamp +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD void cellSurMixerBeep (); //void *arg float cellSurMixerUtilGetLevelFromDB () //float dB +======= +void cellSurMixerBeep(); //void *arg + +float cellSurMixerUtilGetLevelFromDB() //float dB +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO; } +<<<<<<< HEAD float cellSurMixerUtilGetLevelFromDBIndex () //int index +======= +float cellSurMixerUtilGetLevelFromDBIndex() //int index +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO; } +<<<<<<< HEAD float cellSurMixerUtilNoteToRatio () //unsigned char refNote, unsigned char note +======= +float cellSurMixerUtilNoteToRatio() //unsigned char refNote, unsigned char note +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD int cellSurMixerFinalize(void); //Currently unused. Returns 0 (in the current release). //*libsnd3 Functions, NON active in this moment*// s32 cellSnd3Init () //u32 maxVoice, u32 samples, CellSnd3RequestQueueCtx *queue +======= +int cellSurMixerFinalize(); //Currently unused. Returns 0 (in the current release). + +//*libsnd3 Functions, NOT active in this moment +s32 cellSnd3Init() //u32 maxVoice, u32 samples, CellSnd3RequestQueueCtx *queue +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3Exit (void) +======= +s32 cellSnd3Exit() +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SetOutputMode () //u32 mode +======= +s32 cellSnd3SetOutputMode() //u32 mode +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3Synthesis () //float *pOutL, float *pOutR +======= +s32 cellSnd3Synthesis() //float *pOutL, float *pOutR +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SynthesisEx () //float *pOutL, float *pOutR, float *pOutRL, float *pOutRR +======= +s32 cellSnd3SynthesisEx() //float *pOutL, float *pOutR, float *pOutRL, float *pOutRR +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceSetReserveMode () //u32 voiceNum, u32 reserveMode +======= +s32 cellSnd3VoiceSetReserveMode() //u32 voiceNum, u32 reserveMode +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3BindSoundData () //CellSnd3DataCtx *snd3Ctx, void *hd3, u32 synthMemOffset +======= +s32 cellSnd3BindSoundData() //CellSnd3DataCtx *snd3Ctx, void *hd3, u32 synthMemOffset +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3UnbindSoundData (u32 hd3ID) +======= +s32 cellSnd3UnbindSoundData(u32 hd3ID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3NoteOnByTone () //u32 hd3ID, u32 toneIndex, u32 note, u32 keyOnID, CellSnd3KeyOnParam *keyOnParam +======= +s32 cellSnd3NoteOnByTone() //u32 hd3ID, u32 toneIndex, u32 note, u32 keyOnID, CellSnd3KeyOnParam *keyOnParam +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3KeyOnByTone () //u32 hd3ID, u32 toneIndex, u32 pitch,u32 keyOnID,CellSnd3KeyOnParam *keyOnParam +======= +s32 cellSnd3KeyOnByTone() //u32 hd3ID, u32 toneIndex, u32 pitch,u32 keyOnID,CellSnd3KeyOnParam *keyOnParam +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3VoiceNoteOnByTone () //u32 hd3ID, u32 voiceNum, u32 toneIndex, u32 note, u32 keyOnID, CellSnd3KeyOnParam *keyOnParam +======= +s32 cellSnd3VoiceNoteOnByTone() //u32 hd3ID, u32 voiceNum, u32 toneIndex, u32 note, u32 keyOnID, CellSnd3KeyOnParam *keyOnParam +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3VoiceKeyOnByTone () //u32 hd3ID, u32 voiceNum, u32 toneIndex, u32 pitch, u32 keyOnID, CellSnd3KeyOnParam *keyOnParam +======= +s32 cellSnd3VoiceKeyOnByTone() //u32 hd3ID, u32 voiceNum, u32 toneIndex, u32 pitch, u32 keyOnID, CellSnd3KeyOnParam *keyOnParam +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3VoiceSetSustainHold (u32 voiceNum, u32 sustainHold) +======= +s32 cellSnd3VoiceSetSustainHold(u32 voiceNum, u32 sustainHold) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceKeyOff (u32 voiceNum) +======= +s32 cellSnd3VoiceKeyOff(u32 voiceNum) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; @@ -610,221 +1032,361 @@ s32 cellSnd3VoiceSetPitch(u32 voiceNum, s32 addPitch) return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceSetVelocity (u32 voiceNum, u32 velocity) +======= +s32 cellSnd3VoiceSetVelocity(u32 voiceNum, u32 velocity) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceSetPanpot (u32 voiceNum, u32 panpot) +======= +s32 cellSnd3VoiceSetPanpot(u32 voiceNum, u32 panpot) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceSetPanpotEx (u32 voiceNum, u32 panpotEx) +======= +s32 cellSnd3VoiceSetPanpotEx(u32 voiceNum, u32 panpotEx) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceSetPitchBend (u32 voiceNum, u32 bendValue) +======= +s32 cellSnd3VoiceSetPitchBend(u32 voiceNum, u32 bendValue) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceAllKeyOff (void) +======= +s32 cellSnd3VoiceAllKeyOff() +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceGetEnvelope (u32 voiceNum) +======= +s32 cellSnd3VoiceGetEnvelope(u32 voiceNum) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3VoiceGetStatus () //u32 voiceNum +======= +s32 cellSnd3VoiceGetStatus() //u32 voiceNum +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD u32 cellSnd3KeyOffByID (u32 keyOnID) +======= +u32 cellSnd3KeyOffByID(u32 keyOnID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3GetVoice () //u32 midiChannel, u32 keyOnID, CellSnd3VoiceBitCtx *voiceBit +======= +s32 cellSnd3GetVoice() //u32 midiChannel, u32 keyOnID, CellSnd3VoiceBitCtx *voiceBit +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3GetVoiceByID () //u32 keyOnID, CellSnd3VoiceBitCtx *voiceBit +======= +s32 cellSnd3GetVoiceByID() //u32 keyOnID, CellSnd3VoiceBitCtx *voiceBit +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3NoteOn () //u32 hd3ID, u32 midiChannel, u32 midiProgram, u32 midiNote, u32 sustain,CellSnd3KeyOnParam *keyOnParam, u32 keyOnID +======= +s32 cellSnd3NoteOn() //u32 hd3ID, u32 midiChannel, u32 midiProgram, u32 midiNote, u32 sustain,CellSnd3KeyOnParam *keyOnParam, u32 keyOnID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3NoteOff (u32 midiChannel, u32 midiNote, u32 keyOnID) +======= +s32 cellSnd3NoteOff(u32 midiChannel, u32 midiNote, u32 keyOnID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SetSustainHold (u32 midiChannel, u32 sustainHold, u32 ID) +======= +s32 cellSnd3SetSustainHold(u32 midiChannel, u32 sustainHold, u32 ID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SetEffectType (u16 effectType, s16 returnVol, u16 delay, u16 feedback) +======= +s32 cellSnd3SetEffectType(u16 effectType, s16 returnVol, u16 delay, u16 feedback) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD u16 cellSnd3Note2Pitch () //u16 center_note, u16 center_fine, u16 note, s16 fine +======= +u16 cellSnd3Note2Pitch() //u16 center_note, u16 center_fine, u16 note, s16 fine +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD u16 cellSnd3Pitch2Note () //u16 center_note, u16 center_fine, u16 pitch +======= +u16 cellSnd3Pitch2Note() //u16 center_note, u16 center_fine, u16 pitch +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFBind () //CellSnd3SmfCtx *smfCtx, void *smf, u32 hd3ID +======= +s32 cellSnd3SMFBind() //CellSnd3SmfCtx *smfCtx, void *smf, u32 hd3ID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFUnbind () //u32 smfID +======= +s32 cellSnd3SMFUnbind() //u32 smfID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFPlay (u32 smfID, u32 playVelocity, u32 playPan, u32 playCount) +======= +s32 cellSnd3SMFPlay(u32 smfID, u32 playVelocity, u32 playPan, u32 playCount) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFPlayEx (u32 smfID, u32 playVelocity, u32 playPan, u32 playPanEx, u32 playCount) +======= +s32 cellSnd3SMFPlayEx(u32 smfID, u32 playVelocity, u32 playPan, u32 playPanEx, u32 playCount) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFPause (u32 smfID) +======= +s32 cellSnd3SMFPause(u32 smfID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFResume (u32 smfID) +======= +s32 cellSnd3SMFResume(u32 smfID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFStop (u32 smfID) +======= +s32 cellSnd3SMFStop(u32 smfID) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFAddTempo (u32 smfID, s32 addTempo) +======= +s32 cellSnd3SMFAddTempo(u32 smfID, s32 addTempo) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFGetTempo () //u32 smfID +======= +s32 cellSnd3SMFGetTempo() //u32 smfID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFSetPlayVelocity (u32 smfID, u32 playVelocity) +======= +s32 cellSnd3SMFSetPlayVelocity(u32 smfID, u32 playVelocity) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFGetPlayVelocity () //u32 smfID +======= +s32 cellSnd3SMFGetPlayVelocity() //u32 smfID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFSetPlayPanpot (u32 smfID, u32 playPanpot) +======= +s32 cellSnd3SMFSetPlayPanpot(u32 smfID, u32 playPanpot) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFSetPlayPanpotEx (u32 smfID, u32 playPanpotEx) +======= +s32 cellSnd3SMFSetPlayPanpotEx(u32 smfID, u32 playPanpotEx) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFGetPlayPanpot () //u32 smfID +======= +s32 cellSnd3SMFGetPlayPanpot() //u32 smfID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFGetPlayPanpotEx () //u32 smfID +======= +s32 cellSnd3SMFGetPlayPanpotEx() //u32 smfID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFGetPlayStatus () //u32 smfID +======= +s32 cellSnd3SMFGetPlayStatus() //u32 smfID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSnd3SMFSetPlayChannel (u32 smfID, u32 playChannelBit) +======= +s32 cellSnd3SMFSetPlayChannel(u32 smfID, u32 playChannelBit) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFGetPlayChannel () //u32 smfID, u32 *playChannelBit +======= +s32 cellSnd3SMFGetPlayChannel() //u32 smfID, u32 *playChannelBit +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; } +<<<<<<< HEAD s32 cellSnd3SMFGetKeyOnID () //u32 smfID, u32 midiChannel, u32 *keyOnID +======= +s32 cellSnd3SMFGetKeyOnID() //u32 smfID, u32 midiChannel, u32 *keyOnID +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; @@ -832,7 +1394,11 @@ s32 cellSnd3SMFGetKeyOnID () //u32 smfID, u32 midiChannel, u32 *keyOnID //*libsynth2 Functions, NON active in this moment*// +<<<<<<< HEAD s32 cellSoundSynth2Config (s16 param, s32 value) +======= +s32 cellSoundSynth2Config(s16 param, s32 value) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; @@ -844,89 +1410,145 @@ s32 cellSoundSynth2Init( s16 flag) return 0; } +<<<<<<< HEAD s32 cellSoundSynth2Exit(void) +======= +s32 cellSoundSynth2Exit() +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD void cellSoundSynth2SetParam (u16 register, u16 value) +======= +void cellSoundSynth2SetParam(u16 register, u16 value) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); //TODO } +<<<<<<< HEAD u16 cellSoundSynth2GetParam () //u16 register +======= +u16 cellSoundSynth2GetParam() //u16 register +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD void cellSoundSynth2SetSwitch (u16 register, u32 value) +======= +void cellSoundSynth2SetSwitch(u16 register, u32 value) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); //TODO } +<<<<<<< HEAD u32 cellSoundSynth2GetSwitch () //u16 register +======= +u32 cellSoundSynth2GetSwitch() //u16 register +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD u32 cellSoundSynth2SetAddr (u16 register, u32 value) +======= +u32 cellSoundSynth2SetAddr(u16 register, u32 value) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD u32 cellSoundSynth2GetAddr () //u16 register +======= +u32 cellSoundSynth2GetAddr() //u16 register +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD s32 cellSoundSynth2SetEffectAttr () //s16 bus, CellSoundSynth2EffectAttr *attr +======= +s32 cellSoundSynth2SetEffectAttr() //s16 bus, CellSoundSynth2EffectAttr *attr +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD s32 cellSoundSynth2SetEffectMode () //s16 bus, CellSoundSynth2EffectAttr *attr +======= +s32 cellSoundSynth2SetEffectMode() //s16 bus, CellSoundSynth2EffectAttr *attr +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD void cellSoundSynth2SetCoreAttr (u16 entry, u16 value) +======= +void cellSoundSynth2SetCoreAttr(u16 entry, u16 value) +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); //TODO } +<<<<<<< HEAD s32 cellSoundSynth2Generate () //u16 samples, float *left_buffer, float *right_buffer, float *left_rear, float *right_rear +======= +s32 cellSoundSynth2Generate() //u16 samples, float *left_buffer, float *right_buffer, float *left_rear, float *right_rear +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD s32 cellSoundSynth2VoiceTrans () //s16 channel, u16 mode, u8 *m_addr, u32 s_addr, u32 size +======= +s32 cellSoundSynth2VoiceTrans() //s16 channel, u16 mode, u8 *m_addr, u32 s_addr, u32 size +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return 0; } +<<<<<<< HEAD u16 cellSoundSynth2Note2Pitch () //u16 center_note, u16 center_fine, u16 note, s16 fine +======= +u16 cellSoundSynth2Note2Pitch() //u16 center_note, u16 center_fine, u16 note, s16 fine +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value //TODO } +<<<<<<< HEAD u16 cellSoundSynth2Pitch2Note () //u16 center_note, u16 center_fine, u16 pitch +======= +u16 cellSoundSynth2Pitch2Note() //u16 center_note, u16 center_fine, u16 pitch +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellAudio); return CELL_OK; //it's NOT real value @@ -934,6 +1556,7 @@ u16 cellSoundSynth2Pitch2Note () //u16 center_note, u16 center_fine, u16 pitch } +<<<<<<< HEAD void cellAudio_init () { cellAudio.AddFunc (0x0b168f92, cellAudioInit); @@ -953,4 +1576,26 @@ cellAudio.AddFunc (0xdab029aa, cellAudioAddData); cellAudio.AddFunc (0xe4046afe, cellAudioGetPortBlockTag); cellAudio.AddFunc (0xff3626fd, cellAudioRemoveNotifyEventQueue); //TODO: Find addresses for libmixer, libsnd3 and libsynth2 functions +======= +void cellAudio_init() +{ + cellAudio.AddFunc(0x0b168f92, cellAudioInit); + cellAudio.AddFunc(0x4129fe2d, cellAudioPortClose); + cellAudio.AddFunc(0x5b1e2c73, cellAudioPortStop); + cellAudio.AddFunc(0x74a66af0, cellAudioGetPortConfig); + cellAudio.AddFunc(0x89be28f2, cellAudioPortStart); + cellAudio.AddFunc(0xca5ac370, cellAudioQuit); + cellAudio.AddFunc(0xcd7bc431, cellAudioPortOpen); + cellAudio.AddFunc(0x56dfe179, cellAudioSetPortLevel); + cellAudio.AddFunc(0x04af134e, cellAudioCreateNotifyEventQueue); + cellAudio.AddFunc(0x31211f6b, cellAudioMiscSetAccessoryVolume); + cellAudio.AddFunc(0x377e0cd9, cellAudioSetNotifyEventQueue); + cellAudio.AddFunc(0x4109d08c, cellAudioGetPortTimestamp); + cellAudio.AddFunc(0x9e4b1db8, cellAudioAdd2chData); + cellAudio.AddFunc(0xdab029aa, cellAudioAddData); + cellAudio.AddFunc(0xe4046afe, cellAudioGetPortBlockTag); + cellAudio.AddFunc(0xff3626fd, cellAudioRemoveNotifyEventQueue); + + //TODO: Find addresses for libmixer, libsnd3 and libsynth2 functions +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa } diff --git a/rpcs3/Emu/SysCalls/Modules/cellGcmSys.cpp b/rpcs3/Emu/SysCalls/Modules/cellGcmSys.cpp index fa8b4a5695..9ca022ad41 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellGcmSys.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellGcmSys.cpp @@ -433,7 +433,7 @@ int cellGcmSetTileInfo(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u cellGcmSys.Warning("cellGcmSetTileInfo(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)", index, location, offset, size, pitch, comp, base, bank); - if(index >= g_tiles_count || base >= 800 || bank >= 4) + if(index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4) { return CELL_GCM_ERROR_INVALID_VALUE; } @@ -470,7 +470,7 @@ int cellGcmBindTile(u8 index) { cellGcmSys.Warning("cellGcmBindTile(index=%d)", index); - if(index >= g_tiles_count) + if(index >= RSXThread::m_tiles_count) { return CELL_GCM_ERROR_INVALID_VALUE; } @@ -485,7 +485,7 @@ int cellGcmUnbindTile(u8 index) { cellGcmSys.Warning("cellGcmUnbindTile(index=%d)", index); - if(index >= g_tiles_count) + if(index >= RSXThread::m_tiles_count) { return CELL_GCM_ERROR_INVALID_VALUE; } diff --git a/rpcs3/Emu/SysCalls/Modules/cellGifDec.cpp b/rpcs3/Emu/SysCalls/Modules/cellGifDec.cpp index 0f0b8da426..93ca74c373 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellGifDec.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellGifDec.cpp @@ -21,53 +21,95 @@ enum CELL_GIFDEC_ERROR_CB_PARAM = 0x80611307, }; +enum CellGifDecStreamSrcSel +{ + CELL_GIFDEC_FILE = 0, //Input from a file + CELL_GIFDEC_BUFFER = 1, //Input from a buffer +}; + enum CellGifDecColorSpace { CELL_GIFDEC_RGBA = 10, CELL_GIFDEC_ARGB = 20, }; +enum CellGifDecRecordType +{ + CELL_GIFDEC_RECORD_TYPE_IMAGE_DESC = 1, // Image data block + CELL_GIFDEC_RECORD_TYPE_EXTENSION = 2, // Extension block + CELL_GIFDEC_RECORD_TYPE_TERMINATE = 3, // Trailer block +}; + +enum CellGifDecDecodeStatus +{ + CELL_GIFDEC_DEC_STATUS_FINISH = 0, //Decoding finished + CELL_GIFDEC_DEC_STATUS_STOP = 1, //Decoding halted +}; + struct CellGifDecInfo { - u32 SWidth; - u32 SHeight; - u32 SGlobalColorTableFlag; - u32 SColorResolution; - u32 SSortFlag; - u32 SSizeOfGlobalColorTable; - u32 SBackGroundColor; - u32 SPixelAspectRatio; + be_t SWidth; + be_t SHeight; + be_t SGlobalColorTableFlag; + be_t SColorResolution; + be_t SSortFlag; + be_t SSizeOfGlobalColorTable; + be_t SBackGroundColor; + be_t SPixelAspectRatio; }; struct CellGifDecSrc { - u32 srcSelect; // CellGifDecStreamSrcSel - u32 fileName; // const char* - u64 fileOffset; // int64_t - u32 fileSize; - u32 streamPtr; - u32 streamSize; - u32 spuThreadEnable; // CellGifDecSpuThreadEna + be_t srcSelect; + be_t fileName; + be_t fileOffset; + be_t fileSize; + be_t streamPtr; + be_t streamSize; + be_t spuThreadEnable; }; struct CellGifDecInParam { - u32 *commandPtr; - u32 colorSpace; // CellGifDecColorSpace - u8 outputColorAlpha1; - u8 outputColorAlpha2; - u8 reserved[2]; + be_t commandPtr; + be_t colorSpace; // CellGifDecColorSpace + be_t outputColorAlpha1; + be_t outputColorAlpha2; + be_t reserved[2]; }; struct CellGifDecOutParam { - u64 outputWidthByte; - u32 outputWidth; - u32 outputHeight; - u32 outputComponents; - u32 outputBitDepth; - u32 outputColorSpace; // CellGifDecColorSpace - u32 useMemorySpace; + be_t outputWidthByte; + be_t outputWidth; + be_t outputHeight; + be_t outputComponents; + be_t outputBitDepth; + be_t outputColorSpace; // CellGifDecColorSpace + be_t useMemorySpace; +}; + +struct CellGifDecExtension +{ + be_t label; + be_t data; +}; + +struct CellGifDecDataOutInfo +{ + be_t recordType; + CellGifDecExtension outExtension; + be_t status; +}; + +struct CellGifDecOpnInfo +{ + be_t initSpaceAllocated; +}; + +struct CellGifDecDataCtrlParam +{ + be_t outputBytesPerLine; }; struct CellGifDecSubHandle //Custom struct @@ -78,7 +120,6 @@ struct CellGifDecSubHandle //Custom struct CellGifDecOutParam outParam; }; - int cellGifDecCreate(u32 mainHandle, u32 threadInParam, u32 threadOutParam) { UNIMPLEMENTED_FUNC(cellGifDec); @@ -91,164 +132,188 @@ int cellGifDecExtCreate(u32 mainHandle, u32 threadInParam, u32 threadOutParam, u return CELL_OK; } -int cellGifDecOpen(u32 mainHandle, mem32_t subHandle, u32 src_addr, u32 openInfo) +int cellGifDecOpen(u32 mainHandle, mem32_t subHandle, const mem_struct_ptr_t src, mem_struct_ptr_t openInfo) { - //u32 srcSelect = Memory.Read32(src_addr); - u32 fileName = Memory.Read32(src_addr+4); - //u64 fileOffset = Memory.Read32(src_addr+8); - //u32 fileSize = Memory.Read32(src_addr+12); - //u32 streamPtr = Memory.Read32(src_addr+16); - //u32 streamSize = Memory.Read32(src_addr+20); - //u32 spuThreadEnable = Memory.Read32(src_addr+24); + /* + vfsStream* stream; + + switch(src->srcSelect) + { + case CELL_GIFDEC_FILE: + stream = Emu.GetVFS().Open(src->fileName.GetString(), vfsRead); + stream->Seek(src->fileOffset); + src->fileSize; + break; + + case CELL_GIFDEC_BUFFER: + if(src->streamSize < 5) + return CELL_GIFDEC_ERROR_ARG; + + stream = new vfsStreamMemory(src->streamPtr.GetAddr(), src->streamSize); + break; + + default: + return CELL_GIFDEC_ERROR_ARG; + } + + if(!stream->IsOpened()) + { + return CELL_GIFDEC_ERROR_OPEN_FILE; + } + */ CellGifDecSubHandle *current_subHandle = new CellGifDecSubHandle; // Get file descriptor - u32 fd_addr = Memory.Alloc(sizeof(u32), 1); - int ret = cellFsOpen(fileName, 0, fd_addr, NULL, 0); - current_subHandle->fd = Memory.Read32(fd_addr); - Memory.Free(fd_addr); - if(ret != 0) return CELL_GIFDEC_ERROR_OPEN_FILE; + MemoryAllocator> fd; + int ret = cellFsOpen(src->fileName, 0, fd, NULL, 0); + current_subHandle->fd = fd->ToLE(); + if(ret != CELL_OK) return CELL_GIFDEC_ERROR_OPEN_FILE; // Get size of file - u32 sb_addr = Memory.Alloc(52,1); // Alloc a CellFsStat struct - cellFsFstat(current_subHandle->fd, sb_addr); - current_subHandle->fileSize = Memory.Read64(sb_addr+36); // Get CellFsStat.st_size - Memory.Free(sb_addr); + MemoryAllocator sb; // Alloc a CellFsStat struct + ret = cellFsFstat(current_subHandle->fd, sb); + if(ret != CELL_OK) return ret; + current_subHandle->fileSize = sb->st_size; // Get CellFsStat.st_size // From now, every u32 subHandle argument is a pointer to a CellPngDecSubHandle struct. - subHandle += (u32)current_subHandle; + subHandle = cellGifDec.GetNewId(current_subHandle); return CELL_OK; } -int cellGifDecReadHeader(u32 mainHandle, u32 subHandle, mem_class_t info) +int cellGifDecReadHeader(u32 mainHandle, u32 subHandle, mem_struct_ptr_t info) { - const u32& fd = ((CellGifDecSubHandle*)subHandle)->fd; - const u64& fileSize = ((CellGifDecSubHandle*)subHandle)->fileSize; - CellGifDecInfo& current_info = ((CellGifDecSubHandle*)subHandle)->info; + ID sub_handle_id_data; + if(!cellGifDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_GIFDEC_ERROR_FATAL; + + auto subHandle_data = (CellGifDecSubHandle*)sub_handle_id_data.m_data; + + const u32& fd = subHandle_data->fd; + const u64& fileSize = subHandle_data->fileSize; + CellGifDecInfo& current_info = subHandle_data->info; //Write the header to buffer - u32 buffer = Memory.Alloc(13,1); // Alloc buffer for GIF header - u32 nread = Memory.Alloc(8,1); - u32 pos_addr = Memory.Alloc(8,1); - cellFsLseek(fd, 0, 0, pos_addr); - cellFsRead(fd, buffer, 13, nread); - Memory.Free(nread); - Memory.Free(pos_addr); + MemoryAllocator buffer(13); // Alloc buffer for GIF header + MemoryAllocator> pos, nread; - if (Memory.Read32(buffer) != 0x47494638 || - (Memory.Read16(buffer+4) != 0x3961 && - Memory.Read16(buffer+4) != 0x3761)) // Error: The first 6 bytes are not a valid GIF signature + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); + cellFsRead(fd, buffer.GetAddr(), buffer.GetSize(), nread); + + if (*buffer.To>(0) != 0x47494638 || + (*buffer.To(4) != 0x6139 && *buffer.To(4) != 0x6137)) // Error: The first 6 bytes are not a valid GIF signature { - Memory.Free(buffer); return CELL_GIFDEC_ERROR_STREAM_FORMAT; // Surprisingly there is no error code related with headerss } - u8 packedField = Memory.Read8(buffer+10); - current_info.SWidth = Memory.Read8(buffer+6) + Memory.Read8(buffer+7) * 256; - current_info.SHeight = Memory.Read8(buffer+8) + Memory.Read8(buffer+9) * 256; + u8 packedField = buffer[10]; + current_info.SWidth = buffer[6] + buffer[7] * 0x100; + current_info.SHeight = buffer[8] + buffer[9] * 0x100; current_info.SGlobalColorTableFlag = packedField >> 7; current_info.SColorResolution = ((packedField >> 4) & 7)+1; current_info.SSortFlag = (packedField >> 3) & 1; current_info.SSizeOfGlobalColorTable = (packedField & 7)+1; - current_info.SBackGroundColor = Memory.Read8(buffer+11); - current_info.SPixelAspectRatio = Memory.Read8(buffer+12); + current_info.SBackGroundColor = buffer[11]; + current_info.SPixelAspectRatio = buffer[12]; - info += current_info.SWidth; - info += current_info.SHeight; - info += current_info.SGlobalColorTableFlag; - info += current_info.SColorResolution; - info += current_info.SSortFlag; - info += current_info.SSizeOfGlobalColorTable; - info += current_info.SBackGroundColor; - info += current_info.SPixelAspectRatio; - Memory.Free(buffer); + info = current_info; return CELL_OK; } -int cellGifDecSetParameter(u32 mainHandle, u32 subHandle, u32 inParam_addr, mem_class_t outParam) +int cellGifDecSetParameter(u32 mainHandle, u32 subHandle, const mem_struct_ptr_t inParam, mem_struct_ptr_t outParam) { - CellGifDecInfo& current_info = ((CellGifDecSubHandle*)subHandle)->info; - CellGifDecOutParam& current_outParam = ((CellGifDecSubHandle*)subHandle)->outParam; - + ID sub_handle_id_data; + if(!cellGifDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_GIFDEC_ERROR_FATAL; + + auto subHandle_data = (CellGifDecSubHandle*)sub_handle_id_data.m_data; + + CellGifDecInfo& current_info = subHandle_data->info; + CellGifDecOutParam& current_outParam = subHandle_data->outParam; + current_outParam.outputWidthByte = (current_info.SWidth * current_info.SColorResolution * 3)/8; - current_outParam.outputWidth = current_info.SWidth; - current_outParam.outputHeight = current_info.SHeight; - current_outParam.outputColorSpace = Memory.Read32(inParam_addr+4); + current_outParam.outputWidth = current_info.SWidth; + current_outParam.outputHeight = current_info.SHeight; + current_outParam.outputColorSpace = inParam->colorSpace; switch (current_outParam.outputColorSpace) { - case CELL_GIFDEC_RGBA: current_outParam.outputComponents = 4; break; - case CELL_GIFDEC_ARGB: current_outParam.outputComponents = 4; break; - default: return CELL_GIFDEC_ERROR_ARG; // Not supported color space + case CELL_GIFDEC_RGBA: + case CELL_GIFDEC_ARGB: current_outParam.outputComponents = 4; break; + default: return CELL_GIFDEC_ERROR_ARG; // Not supported color space } - current_outParam.outputBitDepth = 0; // Unimplemented - current_outParam.useMemorySpace = 0; // Unimplemented + current_outParam.outputBitDepth = 0; // Unimplemented + current_outParam.useMemorySpace = 0; // Unimplemented - outParam += current_outParam.outputWidthByte; - outParam += current_outParam.outputWidth; - outParam += current_outParam.outputHeight; - outParam += current_outParam.outputComponents; - outParam += current_outParam.outputBitDepth; - outParam += current_outParam.outputColorSpace; - outParam += current_outParam.useMemorySpace; + outParam = current_outParam; return CELL_OK; } -int cellGifDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, u32 dataCtrlParam_addr, mem_class_t dataOutInfo) +int cellGifDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, const mem_struct_ptr_t dataCtrlParam, mem_struct_ptr_t dataOutInfo) { - const u32& fd = ((CellGifDecSubHandle*)subHandle)->fd; - const u64& fileSize = ((CellGifDecSubHandle*)subHandle)->fileSize; - const CellGifDecOutParam& current_outParam = ((CellGifDecSubHandle*)subHandle)->outParam; // (TODO: We should use the outParam) + dataOutInfo->status = CELL_GIFDEC_DEC_STATUS_STOP; + + ID sub_handle_id_data; + if(!cellGifDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_GIFDEC_ERROR_FATAL; + + auto subHandle_data = (CellGifDecSubHandle*)sub_handle_id_data.m_data; + + const u32& fd = subHandle_data->fd; + const u64& fileSize = subHandle_data->fileSize; + const CellGifDecOutParam& current_outParam = subHandle_data->outParam; //Copy the GIF file to a buffer - u32 buffer = Memory.Alloc(fileSize,1); - u32 nread = Memory.Alloc(8,1); - u32 pos_addr = Memory.Alloc(8,1); - cellFsLseek(fd, 0, 0, pos_addr); - cellFsRead(fd, buffer, fileSize, nread); - Memory.Free(nread); - Memory.Free(pos_addr); + MemoryAllocator gif(fileSize); + MemoryAllocator pos, nread; + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); + cellFsRead(fd, gif.GetAddr(), gif.GetSize(), nread); //Decode GIF file. (TODO: Is there any faster alternative? Can we do it without external libraries?) int width, height, actual_components; - unsigned char *gif = (unsigned char*)Memory.VirtualToRealAddr(buffer); - unsigned char *image = stbi_load_from_memory(gif, fileSize, &width, &height, &actual_components, 4); - Memory.Free(buffer); + std::shared_ptr image(stbi_load_from_memory(gif, fileSize, &width, &height, &actual_components, 4)); if (!image) return CELL_GIFDEC_ERROR_STREAM_FORMAT; - u32 image_size = width * height * 4; - if (current_outParam.outputColorSpace == CELL_GIFDEC_RGBA){ - for(u32 i = 0; i < image_size; i+=4){ - data += image[i+0]; - data += image[i+1]; - data += image[i+2]; - data += image[i+3]; - } - } - if (current_outParam.outputColorSpace == CELL_GIFDEC_ARGB){ - for(u32 i = 0; i < image_size; i+=4){ - data += image[i+3]; - data += image[i+0]; - data += image[i+1]; - data += image[i+2]; - } - } - delete[] image; + uint image_size = width * height * 4; - dataOutInfo += (u32)1; // The output data is an image (dataOutInfo.recordType = 1) - dataOutInfo += (u32)0; // outExtension.label = 0 - dataOutInfo += Memory.Alloc(20,1); // outExtension.data allocated (TODO: Is this the best way to avoid exceptions when trying to access this data? Will this produce a memory leak?) + switch(current_outParam.outputColorSpace) + { + case CELL_GIFDEC_RGBA: + memcpy(data, image.get(), image_size); + break; + + case CELL_GIFDEC_ARGB: + for(uint i = 0; i < image_size; i+=4) + { + data += image.get()[i+3]; + data += image.get()[i+0]; + data += image.get()[i+1]; + data += image.get()[i+2]; + } + break; + + default: + return CELL_GIFDEC_ERROR_ARG; + } + + dataOutInfo->status = CELL_GIFDEC_DEC_STATUS_FINISH; + dataOutInfo->recordType = CELL_GIFDEC_RECORD_TYPE_IMAGE_DESC; return CELL_OK; } int cellGifDecClose(u32 mainHandle, u32 subHandle) { - cellFsClose( ((CellGifDecSubHandle*)subHandle)->fd ); - delete (CellGifDecSubHandle*)subHandle; + ID sub_handle_id_data; + if(!cellGifDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_GIFDEC_ERROR_FATAL; + + auto subHandle_data = (CellGifDecSubHandle*)sub_handle_id_data.m_data; + + cellFsClose(subHandle_data->fd); + Emu.GetIdManager().RemoveID(subHandle); return CELL_OK; } diff --git a/rpcs3/Emu/SysCalls/Modules/cellJpgDec.cpp b/rpcs3/Emu/SysCalls/Modules/cellJpgDec.cpp index b637558370..c112b1f80f 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellJpgDec.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellJpgDec.cpp @@ -34,48 +34,72 @@ enum CellJpgDecColorSpace CELL_JPG_GRAYSCALE_TO_ALPHA_ARGB = 41, }; +enum CellJpgDecDecodeStatus +{ + CELL_JPGDEC_DEC_STATUS_FINISH = 0, //Decoding finished + CELL_JPGDEC_DEC_STATUS_STOP = 1, //Decoding halted +}; + struct CellJpgDecInfo { - u32 imageWidth; - u32 imageHeight; - u32 numComponents; - u32 colorSpace; // CellJpgDecColorSpace + be_t imageWidth; + be_t imageHeight; + be_t numComponents; + be_t colorSpace; // CellJpgDecColorSpace }; struct CellJpgDecSrc { - u32 srcSelect; // CellJpgDecStreamSrcSel - u32 fileName; // const char* - u64 fileOffset; // int64_t - u32 fileSize; - u32 streamPtr; - u32 streamSize; - u32 spuThreadEnable; // CellJpgDecSpuThreadEna + be_t srcSelect; // CellJpgDecStreamSrcSel + be_t fileName; // const char* + be_t fileOffset; // int64_t + be_t fileSize; + be_t streamPtr; + be_t streamSize; + be_t spuThreadEnable; // CellJpgDecSpuThreadEna }; struct CellJpgDecInParam { - u32 *commandPtr; - u32 downScale; - u32 method; // CellJpgDecMethod - u32 outputMode; // CellJpgDecOutputMode - u32 outputColorSpace; // CellJpgDecColorSpace - u8 outputColorAlpha; - u8 reserved[3]; + be_t commandPtr; + be_t downScale; + be_t method; // CellJpgDecMethod + be_t outputMode; // CellJpgDecOutputMode + be_t outputColorSpace; // CellJpgDecColorSpace + be_t outputColorAlpha; + be_t reserved[3]; }; struct CellJpgDecOutParam { - u64 outputWidthByte; - u32 outputWidth; - u32 outputHeight; - u32 outputComponents; - u32 outputMode; // CellJpgDecOutputMode - u32 outputColorSpace; // CellJpgDecColorSpace - u32 downScale; - u32 useMemorySpace; + be_t outputWidthByte; + be_t outputWidth; + be_t outputHeight; + be_t outputComponents; + be_t outputMode; // CellJpgDecOutputMode + be_t outputColorSpace; // CellJpgDecColorSpace + be_t downScale; + be_t useMemorySpace; }; +struct CellJpgDecOpnInfo +{ + be_t initSpaceAllocated; +}; + +struct CellJpgDecDataCtrlParam +{ + be_t outputBytesPerLine; +}; + +struct CellJpgDecDataOutInfo +{ + be_t mean; + be_t outputLines; + be_t status; +}; + + struct CellJpgDecSubHandle //Custom struct { u32 fd; @@ -84,7 +108,6 @@ struct CellJpgDecSubHandle //Custom struct CellJpgDecOutParam outParam; }; - int cellJpgDecCreate(u32 mainHandle, u32 threadInParam, u32 threadOutParam) { UNIMPLEMENTED_FUNC(cellJpgDec); @@ -103,11 +126,11 @@ int cellJpgDecDestroy(u32 mainHandle) return CELL_OK; } -int cellJpgDecOpen(u32 mainHandle, mem32_t subHandle, u32 src_addr, u32 openInfo) +int cellJpgDecOpen(u32 mainHandle, mem32_t subHandle, u32 src_addr, mem_struct_ptr_t openInfo) { //u32 srcSelect = Memory.Read32(src_addr); u32 fileName = Memory.Read32(src_addr+4); - //u64 fileOffset = Memory.Read32(src_addr+8); + //u32 fileOffset = Memory.Read32(src_addr+8); //u32 fileSize = Memory.Read32(src_addr+12); //u32 streamPtr = Memory.Read32(src_addr+16); //u32 streamSize = Memory.Read32(src_addr+20); @@ -116,165 +139,200 @@ int cellJpgDecOpen(u32 mainHandle, mem32_t subHandle, u32 src_addr, u32 openInfo CellJpgDecSubHandle *current_subHandle = new CellJpgDecSubHandle; // Get file descriptor - u32 fd_addr = Memory.Alloc(sizeof(u32), 1); - int ret = cellFsOpen(fileName, 0, fd_addr, NULL, 0); - current_subHandle->fd = Memory.Read32(fd_addr); - Memory.Free(fd_addr); - if(ret != 0) return CELL_JPGDEC_ERROR_OPEN_FILE; + MemoryAllocator> fd; + int ret = cellFsOpen(fileName, 0, fd, NULL, 0); + current_subHandle->fd = fd->ToLE(); + if(ret != CELL_OK) return CELL_JPGDEC_ERROR_OPEN_FILE; // Get size of file - u32 sb_addr = Memory.Alloc(52,1); // Alloc a CellFsStat struct - cellFsFstat(current_subHandle->fd, sb_addr); - current_subHandle->fileSize = Memory.Read64(sb_addr+36); // Get CellFsStat.st_size - Memory.Free(sb_addr); + MemoryAllocator sb; // Alloc a CellFsStat struct + ret = cellFsFstat(current_subHandle->fd, sb); + if(ret != CELL_OK) return ret; + current_subHandle->fileSize = sb->st_size; // Get CellFsStat.st_size // From now, every u32 subHandle argument is a pointer to a CellPngDecSubHandle struct. - subHandle += (u32)current_subHandle; + subHandle = cellJpgDec.GetNewId(current_subHandle); return CELL_OK; } int cellJpgDecClose(u32 mainHandle, u32 subHandle) { - cellFsClose( ((CellJpgDecSubHandle*)subHandle)->fd ); - delete (CellJpgDecSubHandle*)subHandle; + ID sub_handle_id_data; + if(!cellJpgDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_JPGDEC_ERROR_FATAL; + + auto subHandle_data = (CellJpgDecSubHandle*)sub_handle_id_data.m_data; + + cellFsClose(subHandle_data->fd); + Emu.GetIdManager().RemoveID(subHandle); return CELL_OK; } -int cellJpgDecReadHeader(u32 mainHandle, u32 subHandle, mem_class_t info) +int cellJpgDecReadHeader(u32 mainHandle, u32 subHandle, mem_struct_ptr_t info) { - const u32& fd = ((CellJpgDecSubHandle*)subHandle)->fd; - const u64& fileSize = ((CellJpgDecSubHandle*)subHandle)->fileSize; - CellJpgDecInfo& current_info = ((CellJpgDecSubHandle*)subHandle)->info; + cellJpgDec.Log("cellJpgDecReadHeader(mainHandle=0x%x, subHandle=0x%x, info_addr=0x%llx)", mainHandle, subHandle, info.GetAddr()); + ID sub_handle_id_data; + if(!cellJpgDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_JPGDEC_ERROR_FATAL; + + auto subHandle_data = (CellJpgDecSubHandle*)sub_handle_id_data.m_data; + + const u32& fd = subHandle_data->fd; + const u64& fileSize = subHandle_data->fileSize; + CellJpgDecInfo& current_info = subHandle_data->info; //Copy the JPG file to a buffer - u32 buffer = Memory.Alloc(fileSize,1); - u32 nread = Memory.Alloc(8,1); - u32 pos_addr = Memory.Alloc(8,1); - cellFsLseek(fd, 0, 0, pos_addr); - cellFsRead(fd, buffer, fileSize, nread); - Memory.Free(nread); - Memory.Free(pos_addr); + MemoryAllocator buffer(fileSize); + MemoryAllocator> pos, nread; - if (Memory.Read32(buffer) != 0xFFD8FFE0 || // Error: Not a valid SOI header - Memory.Read32(buffer+6) != 0x4A464946) // Error: Not a valid JFIF string + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); + cellFsRead(fd, buffer.GetAddr(), buffer.GetSize(), nread); + + if (*buffer.To(0) != 0xE0FFD8FF || // Error: Not a valid SOI header + *buffer.To(6) != 0x4649464A) // Error: Not a valid JFIF string { - Memory.Free(buffer); return CELL_JPGDEC_ERROR_HEADER; } u32 i = 4; - u16 block_length = Memory.Read8(buffer+i)*0xFF + Memory.Read8(buffer+i+1); - while(i < fileSize) - { - i += block_length; // Increase the file index to get to the next block - if (i >= fileSize){ - Memory.Free(buffer); - return CELL_JPGDEC_ERROR_HEADER; // Check to protect against segmentation faults - } - if(Memory.Read8(buffer+i) != 0xFF){ - Memory.Free(buffer); - return CELL_JPGDEC_ERROR_HEADER; // Check that we are truly at the start of another block - } - if(Memory.Read8(buffer+i+1) == 0xC0){ - break; // 0xFFC0 is the "Start of frame" marker which contains the file size - } - i += 2; // Skip the block marker - block_length = Memory.Read8(buffer+i)*0xFF + Memory.Read8(buffer+i+1); // Go to the next block - } - - current_info.imageWidth = Memory.Read8(buffer+i+7)*256 + Memory.Read8(buffer+i+8); - current_info.imageHeight = Memory.Read8(buffer+i+5)*256 + Memory.Read8(buffer+i+6); - current_info.numComponents = 3; // Unimplemented - current_info.colorSpace = CELL_JPG_RGB; // Unimplemented - - info += current_info.imageWidth; - info += current_info.imageHeight; - info += current_info.numComponents; - info += current_info.colorSpace; - Memory.Free(buffer); + if(i >= fileSize) + return CELL_JPGDEC_ERROR_HEADER; + + u16 block_length = buffer[i] * 0xFF + buffer[i+1]; + + while(true) + { + i += block_length; // Increase the file index to get to the next block + if (i >= fileSize || // Check to protect against segmentation faults + buffer[i] != 0xFF) // Check that we are truly at the start of another block + { + return CELL_JPGDEC_ERROR_HEADER; + } + + if(buffer[i+1] == 0xC0) + break; // 0xFFC0 is the "Start of frame" marker which contains the file size + + i += 2; // Skip the block marker + block_length = buffer[i] * 0xFF + buffer[i+1]; // Go to the next block + } + + current_info.imageWidth = buffer[i+7]*0x100 + buffer[i+8]; + current_info.imageHeight = buffer[i+5]*0x100 + buffer[i+6]; + current_info.numComponents = 3; // Unimplemented + current_info.colorSpace = CELL_JPG_RGB; + + info = current_info; + return CELL_OK; } -int cellJpgDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, u32 dataCtrlParam_addr, u32 dataOutInfo_addr) +int cellJpgDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, const mem_struct_ptr_t dataCtrlParam, mem_struct_ptr_t dataOutInfo) { - const u32& fd = ((CellJpgDecSubHandle*)subHandle)->fd; - const u64& fileSize = ((CellJpgDecSubHandle*)subHandle)->fileSize; - const CellJpgDecOutParam& current_outParam = ((CellJpgDecSubHandle*)subHandle)->outParam; // (TODO: We should use the outParam) + dataOutInfo->status = CELL_JPGDEC_DEC_STATUS_STOP; + ID sub_handle_id_data; + if(!cellJpgDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_JPGDEC_ERROR_FATAL; + + auto subHandle_data = (CellJpgDecSubHandle*)sub_handle_id_data.m_data; + + const u32& fd = subHandle_data->fd; + const u64& fileSize = subHandle_data->fileSize; + const CellJpgDecOutParam& current_outParam = subHandle_data->outParam; //Copy the JPG file to a buffer - u32 buffer = Memory.Alloc(fileSize,1); - u32 nread = Memory.Alloc(8,1); - u32 pos_addr = Memory.Alloc(8,1); - cellFsLseek(fd, 0, 0, pos_addr); - cellFsRead(fd, buffer, fileSize, nread); - Memory.Free(nread); - Memory.Free(pos_addr); + MemoryAllocator jpg(fileSize); + MemoryAllocator pos, nread; + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); + cellFsRead(fd, jpg.GetAddr(), jpg.GetSize(), nread); //Decode JPG file. (TODO: Is there any faster alternative? Can we do it without external libraries?) int width, height, actual_components; - unsigned char *jpg = (unsigned char*)Memory.VirtualToRealAddr(buffer); - unsigned char *image = stbi_load_from_memory(jpg, fileSize, &width, &height, &actual_components, 4); - Memory.Free(buffer); + std::shared_ptr image(stbi_load_from_memory(jpg, fileSize, &width, &height, &actual_components, 4)); + if (!image) return CELL_JPGDEC_ERROR_STREAM_FORMAT; - u32 image_size = width * height * 4; - if (current_outParam.outputColorSpace == CELL_JPG_RGBA){ - for(u32 i = 0; i < image_size; i+=4){ - data += image[i+0]; - data += image[i+1]; - data += image[i+2]; - data += image[i+3]; + uint image_size = width * height; + switch(current_outParam.outputColorSpace) + { + case CELL_JPG_RGBA: + case CELL_JPG_RGB: + image_size *= current_outParam.outputColorSpace == CELL_JPG_RGBA ? 4 : 3; + memcpy(data, image.get(), image_size); + break; + + case CELL_JPG_ARGB: + image_size *= 4; + + for(u32 i = 0; i < image_size; i+=4) + { + data += image.get()[i+3]; + data += image.get()[i+0]; + data += image.get()[i+1]; + data += image.get()[i+2]; } + break; + + case CELL_JPG_GRAYSCALE: + case CELL_JPG_YCbCr: + case CELL_JPG_UPSAMPLE_ONLY: + case CELL_JPG_GRAYSCALE_TO_ALPHA_RGBA: + case CELL_JPG_GRAYSCALE_TO_ALPHA_ARGB: + cellJpgDec.Error("cellJpgDecDecodeData: Unsupported color space (%d)", current_outParam.outputColorSpace.ToLE()); + break; + + default: + return CELL_JPGDEC_ERROR_ARG; } - else if (current_outParam.outputColorSpace == CELL_JPG_ARGB){ - for(u32 i = 0; i < image_size; i+=4){ - data += image[i+3]; - data += image[i+0]; - data += image[i+1]; - data += image[i+2]; - } - } - delete[] image; + + dataOutInfo->status = CELL_JPGDEC_DEC_STATUS_FINISH; + + if(dataCtrlParam->outputBytesPerLine) + dataOutInfo->outputLines = image_size / dataCtrlParam->outputBytesPerLine; return CELL_OK; } -int cellJpgDecSetParameter(u32 mainHandle, u32 subHandle, u32 inParam_addr, mem_class_t outParam) +int cellJpgDecSetParameter(u32 mainHandle, u32 subHandle, const mem_struct_ptr_t inParam, mem_struct_ptr_t outParam) { - CellJpgDecInfo& current_info = ((CellJpgDecSubHandle*)subHandle)->info; - CellJpgDecOutParam& current_outParam = ((CellJpgDecSubHandle*)subHandle)->outParam; + ID sub_handle_id_data; + if(!cellJpgDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_JPGDEC_ERROR_FATAL; + + auto subHandle_data = (CellJpgDecSubHandle*)sub_handle_id_data.m_data; + + CellJpgDecInfo& current_info = subHandle_data->info; + CellJpgDecOutParam& current_outParam = subHandle_data->outParam; current_outParam.outputWidthByte = (current_info.imageWidth * current_info.numComponents); current_outParam.outputWidth = current_info.imageWidth; current_outParam.outputHeight = current_info.imageHeight; - current_outParam.outputColorSpace = Memory.Read32(inParam_addr+16); + current_outParam.outputColorSpace = inParam->outputColorSpace; + switch (current_outParam.outputColorSpace) { case CELL_JPG_GRAYSCALE: current_outParam.outputComponents = 1; break; - case CELL_JPG_RGB: current_outParam.outputComponents = 3; break; - case CELL_JPG_YCbCr: current_outParam.outputComponents = 3; break; - case CELL_JPG_RGBA: current_outParam.outputComponents = 4; break; - case CELL_JPG_UPSAMPLE_ONLY: current_outParam.outputComponents = current_info.numComponents; break; - case CELL_JPG_ARGB: current_outParam.outputComponents = 4; break; - case CELL_JPG_GRAYSCALE_TO_ALPHA_RGBA: current_outParam.outputComponents = 4; break; - case CELL_JPG_GRAYSCALE_TO_ALPHA_ARGB: current_outParam.outputComponents = 4; break; - default: return CELL_JPGDEC_ERROR_ARG; // Not supported color space - } - current_outParam.outputMode = Memory.Read32(inParam_addr+12); - current_outParam.downScale = Memory.Read32(inParam_addr+4); - current_outParam.useMemorySpace = 0; // Unimplemented - outParam += current_outParam.outputWidthByte; - outParam += current_outParam.outputWidth; - outParam += current_outParam.outputHeight; - outParam += current_outParam.outputComponents; - outParam += current_outParam.outputMode; - outParam += current_outParam.outputColorSpace; - outParam += current_outParam.downScale; - outParam += current_outParam.useMemorySpace; + case CELL_JPG_RGB: + case CELL_JPG_YCbCr: current_outParam.outputComponents = 3; break; + + case CELL_JPG_UPSAMPLE_ONLY: current_outParam.outputComponents = current_info.numComponents; break; + + case CELL_JPG_RGBA: + case CELL_JPG_ARGB: + case CELL_JPG_GRAYSCALE_TO_ALPHA_RGBA: + case CELL_JPG_GRAYSCALE_TO_ALPHA_ARGB: current_outParam.outputComponents = 4; break; + + default: return CELL_JPGDEC_ERROR_ARG; // Not supported color space + } + + current_outParam.outputMode = inParam->outputMode; + current_outParam.downScale = inParam->downScale; + current_outParam.useMemorySpace = 0; // Unimplemented + + outParam = current_outParam; return CELL_OK; } diff --git a/rpcs3/Emu/SysCalls/Modules/cellPhotoDecode.cpp b/rpcs3/Emu/SysCalls/Modules/cellPhotoDecode.cpp index b0973a3e55..78c5cb8673 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellPhotoDecode.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellPhotoDecode.cpp @@ -18,6 +18,21 @@ enum CELL_PHOTO_DECODE_ERROR_DECODE = 0x8002c906, }; +// Datatypes +struct CellPhotoDecodeSetParam +{ + u32 dstBuffer_addr; + u16 width; + u16 height; +}; + +struct CellPhotoDecodeReturnParam +{ + u16 width; + u16 height; +}; + +// Functions int cellPhotoDecodeInitialize() { UNIMPLEMENTED_FUNC(cellPhotoDecode); diff --git a/rpcs3/Emu/SysCalls/Modules/cellPhotoImport.cpp b/rpcs3/Emu/SysCalls/Modules/cellPhotoImport.cpp index f4f25ff488..5b072a0fcd 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellPhotoImport.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellPhotoImport.cpp @@ -18,6 +18,30 @@ enum CELL_PHOTO_IMPORT_ERROR_INITIALIZE = 0x8002c706, }; +// Datatypes +struct CellPhotoImportFileDataSub +{ + int width; + int height; + //CellPhotoImportFormatType format; + //CellPhotoImportTexRot rotate; +}; + +struct CellPhotoImportFileData +{ + char dstFileName; //[CELL_FS_MAX_FS_FILE_NAME_LENGTH]; + char photo_title; //[CELL_PHOTO_IMPORT_PHOTO_TITLE_MAX_LENGTH*3]; + char game_title; //[CELL_PHOTO_IMPORT_GAME_TITLE_MAX_SIZE]; + char game_comment; //[CELL_PHOTO_IMPORT_GAME_COMMENT_MAX_SIZE]; + CellPhotoImportFileDataSub* data_sub; +}; + +struct CellPhotoImportSetParam +{ + unsigned int fileSizeMax; +}; + +// Functions int _cellPhotoImport() { UNIMPLEMENTED_FUNC(cellPhotoImport); diff --git a/rpcs3/Emu/SysCalls/Modules/cellPngDec.cpp b/rpcs3/Emu/SysCalls/Modules/cellPngDec.cpp index 5cb71d7714..4f130f0a52 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellPngDec.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellPngDec.cpp @@ -32,49 +32,68 @@ enum CellPngDecColorSpace CELL_PNGDEC_ARGB = 20, }; +enum CellPngDecDecodeStatus +{ + CELL_PNGDEC_DEC_STATUS_FINISH = 0, //Decoding finished + CELL_PNGDEC_DEC_STATUS_STOP = 1, //Decoding halted +}; + +struct CellPngDecDataOutInfo +{ + be_t chunkInformation; + be_t numText; + be_t numUnknownChunk; + be_t status; +}; + +struct CellPngDecDataCtrlParam +{ + be_t outputBytesPerLine; +}; + struct CellPngDecInfo { - u32 imageWidth; - u32 imageHeight; - u32 numComponents; - u32 colorSpace; // CellPngDecColorSpace - u32 bitDepth; - u32 interlaceMethod; // CellPngDecInterlaceMode - u32 chunkInformation; + be_t imageWidth; + be_t imageHeight; + be_t numComponents; + be_t colorSpace; // CellPngDecColorSpace + be_t bitDepth; + be_t interlaceMethod; // CellPngDecInterlaceMode + be_t chunkInformation; }; struct CellPngDecSrc { - u32 srcSelect; // CellPngDecStreamSrcSel - u32 fileName; // const char* - u64 fileOffset; // int64_t - u32 fileSize; - u32 streamPtr; - u32 streamSize; - u32 spuThreadEnable; // CellPngDecSpuThreadEna + be_t srcSelect; // CellPngDecStreamSrcSel + be_t fileName; // const char* + be_t fileOffset; // int64_t + be_t fileSize; + be_t streamPtr; + be_t streamSize; + be_t spuThreadEnable; // CellPngDecSpuThreadEna }; struct CellPngDecInParam { - u32 *commandPtr; - u32 outputMode; // CellPngDecOutputMode - u32 outputColorSpace; // CellPngDecColorSpace - u32 outputBitDepth; - u32 outputPackFlag; // CellPngDecPackFlag - u32 outputAlphaSelect; // CellPngDecAlphaSelect - u32 outputColorAlpha; + be_t commandPtr; + be_t outputMode; // CellPngDecOutputMode + be_t outputColorSpace; // CellPngDecColorSpace + be_t outputBitDepth; + be_t outputPackFlag; // CellPngDecPackFlag + be_t outputAlphaSelect; // CellPngDecAlphaSelect + be_t outputColorAlpha; }; struct CellPngDecOutParam { - u64 outputWidthByte; - u32 outputWidth; - u32 outputHeight; - u32 outputComponents; - u32 outputBitDepth; - u32 outputMode; // CellPngDecOutputMode - u32 outputColorSpace; // CellPngDecColorSpace - u32 useMemorySpace; + be_t outputWidthByte; + be_t outputWidth; + be_t outputHeight; + be_t outputComponents; + be_t outputBitDepth; + be_t outputMode; // CellPngDecOutputMode + be_t outputColorSpace; // CellPngDecColorSpace + be_t useMemorySpace; }; struct CellPngDecSubHandle //Custom struct @@ -85,7 +104,6 @@ struct CellPngDecSubHandle //Custom struct CellPngDecOutParam outParam; }; - int cellPngDecCreate(u32 mainHandle, u32 threadInParam, u32 threadOutParam) { UNIMPLEMENTED_FUNC(cellPngDec); @@ -102,7 +120,7 @@ int cellPngDecOpen(u32 mainHandle, mem32_t subHandle, u32 src_addr, u32 openInfo { //u32 srcSelect = Memory.Read32(src_addr); u32 fileName = Memory.Read32(src_addr+4); - //u64 fileOffset = Memory.Read32(src_addr+8); + //u32 fileOffset = Memory.Read32(src_addr+8); //u32 fileSize = Memory.Read32(src_addr+12); //u32 streamPtr = Memory.Read32(src_addr+16); //u32 streamSize = Memory.Read32(src_addr+20); @@ -111,160 +129,183 @@ int cellPngDecOpen(u32 mainHandle, mem32_t subHandle, u32 src_addr, u32 openInfo CellPngDecSubHandle *current_subHandle = new CellPngDecSubHandle; // Get file descriptor - u32 fd_addr = Memory.Alloc(sizeof(u32), 1); - int ret = cellFsOpen(fileName, 0, fd_addr, NULL, 0); - current_subHandle->fd = Memory.Read32(fd_addr); - Memory.Free(fd_addr); - if(ret != 0) return CELL_PNGDEC_ERROR_OPEN_FILE; + MemoryAllocator> fd; + int ret = cellFsOpen(fileName, 0, fd, NULL, 0); + current_subHandle->fd = fd->ToLE(); + if(ret != CELL_OK) return CELL_PNGDEC_ERROR_OPEN_FILE; // Get size of file - u32 sb_addr = Memory.Alloc(52,1); // Alloc a CellFsStat struct - cellFsFstat(current_subHandle->fd, sb_addr); - current_subHandle->fileSize = Memory.Read64(sb_addr+36); // Get CellFsStat.st_size - Memory.Free(sb_addr); + MemoryAllocator sb; // Alloc a CellFsStat struct + ret = cellFsFstat(current_subHandle->fd, sb); + if(ret != CELL_OK) return ret; + current_subHandle->fileSize = sb->st_size; // Get CellFsStat.st_size // From now, every u32 subHandle argument is a pointer to a CellPngDecSubHandle struct. - subHandle += (u32)current_subHandle; + subHandle = cellPngDec.GetNewId(current_subHandle); return CELL_OK; } int cellPngDecClose(u32 mainHandle, u32 subHandle) { - cellFsClose( ((CellPngDecSubHandle*)subHandle)->fd ); - delete (CellPngDecSubHandle*)subHandle; + ID sub_handle_id_data; + if(!cellPngDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_PNGDEC_ERROR_FATAL; + + auto subHandle_data = (CellPngDecSubHandle*)sub_handle_id_data.m_data; + + cellFsClose(subHandle_data->fd); + Emu.GetIdManager().RemoveID(subHandle); return CELL_OK; } -int cellPngDecReadHeader(u32 mainHandle, u32 subHandle, mem_class_t info) +int cellPngDecReadHeader(u32 mainHandle, u32 subHandle, mem_struct_ptr_t info) { - const u32& fd = ((CellPngDecSubHandle*)subHandle)->fd; - const u64& fileSize = ((CellPngDecSubHandle*)subHandle)->fileSize; - CellPngDecInfo& current_info = ((CellPngDecSubHandle*)subHandle)->info; + cellPngDec.Log("cellPngDecReadHeader(mainHandle=0x%x, subHandle=0x%x, info_addr=0x%llx)", mainHandle, subHandle, info.GetAddr()); + ID sub_handle_id_data; + if(!cellPngDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_PNGDEC_ERROR_FATAL; + + auto subHandle_data = (CellPngDecSubHandle*)sub_handle_id_data.m_data; + + const u32& fd = subHandle_data->fd; + const u64& fileSize = subHandle_data->fileSize; + CellPngDecInfo& current_info = subHandle_data->info; //Check size of file if(fileSize < 29) return CELL_PNGDEC_ERROR_HEADER; // Error: The file is smaller than the length of a PNG header //Write the header to buffer - u32 buffer = Memory.Alloc(34,1); // Alloc buffer for PNG header - u32 nread = Memory.Alloc(8,1); - u32 pos_addr = Memory.Alloc(8,1); - cellFsLseek(fd, 0, 0, pos_addr); - cellFsRead(fd, buffer, 34, nread); - Memory.Free(nread); - Memory.Free(pos_addr); + MemoryAllocator> buffer(34); // Alloc buffer for PNG header + MemoryAllocator> pos, nread; - if (Memory.Read32(buffer) != 0x89504E47 || - Memory.Read32(buffer+4) != 0x0D0A1A0A || // Error: The first 8 bytes are not a valid PNG signature - Memory.Read32(buffer+12) != 0x49484452) // Error: The PNG file does not start with an IHDR chunk + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); + cellFsRead(fd, buffer.GetAddr(), buffer.GetSize(), nread); + + if (buffer[0] != 0x89504E47 || + buffer[1] != 0x0D0A1A0A || // Error: The first 8 bytes are not a valid PNG signature + buffer[3] != 0x49484452) // Error: The PNG file does not start with an IHDR chunk { - Memory.Free(buffer); return CELL_PNGDEC_ERROR_HEADER; } - current_info.imageWidth = Memory.Read32(buffer+16); - current_info.imageHeight = Memory.Read32(buffer+20); - switch (Memory.Read8(buffer+25)) + switch (buffer.To()[25]) { - case 0: current_info.colorSpace = CELL_PNGDEC_GRAYSCALE; current_info.numComponents = 1; break; - case 2: current_info.colorSpace = CELL_PNGDEC_RGB; current_info.numComponents = 3; break; - case 3: current_info.colorSpace = CELL_PNGDEC_PALETTE; current_info.numComponents = 1; break; - case 4: current_info.colorSpace = CELL_PNGDEC_GRAYSCALE_ALPHA; current_info.numComponents = 2; break; - case 6: current_info.colorSpace = CELL_PNGDEC_RGBA; current_info.numComponents = 4; break; + case 0: current_info.colorSpace = CELL_PNGDEC_GRAYSCALE; current_info.numComponents = 1; break; + case 2: current_info.colorSpace = CELL_PNGDEC_RGB; current_info.numComponents = 3; break; + case 3: current_info.colorSpace = CELL_PNGDEC_PALETTE; current_info.numComponents = 1; break; + case 4: current_info.colorSpace = CELL_PNGDEC_GRAYSCALE_ALPHA; current_info.numComponents = 2; break; + case 6: current_info.colorSpace = CELL_PNGDEC_RGBA; current_info.numComponents = 4; break; default: return CELL_PNGDEC_ERROR_HEADER; // Not supported color type } - current_info.bitDepth = Memory.Read8(buffer+24); - current_info.interlaceMethod = Memory.Read8(buffer+28); - current_info.chunkInformation = 0; // Unimplemented - info += current_info.imageWidth; - info += current_info.imageHeight; - info += current_info.numComponents; - info += current_info.colorSpace; - info += current_info.bitDepth; - info += current_info.interlaceMethod; - info += current_info.chunkInformation; - Memory.Free(buffer); - + current_info.imageWidth = buffer[4]; + current_info.imageHeight = buffer[5]; + current_info.bitDepth = buffer.To()[24]; + current_info.interlaceMethod = buffer.To()[28]; + current_info.chunkInformation = 0; // Unimplemented + + info = current_info; + return CELL_OK; } -int cellPngDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, u32 dataCtrlParam_addr, mem_class_t dataOutInfo) +int cellPngDecDecodeData(u32 mainHandle, u32 subHandle, mem8_ptr_t data, const mem_struct_ptr_t dataCtrlParam, mem_struct_ptr_t dataOutInfo) { - const u32& fd = ((CellPngDecSubHandle*)subHandle)->fd; - const u64& fileSize = ((CellPngDecSubHandle*)subHandle)->fileSize; - const CellPngDecOutParam& current_outParam = ((CellPngDecSubHandle*)subHandle)->outParam; + dataOutInfo->status = CELL_PNGDEC_DEC_STATUS_STOP; + ID sub_handle_id_data; + if(!cellPngDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_PNGDEC_ERROR_FATAL; + + auto subHandle_data = (CellPngDecSubHandle*)sub_handle_id_data.m_data; + + const u32& fd = subHandle_data->fd; + const u64& fileSize = subHandle_data->fileSize; + const CellPngDecOutParam& current_outParam = subHandle_data->outParam; //Copy the PNG file to a buffer - u32 buffer = Memory.Alloc(fileSize,1); - u32 nread = Memory.Alloc(8,1); - u32 pos_addr = Memory.Alloc(sizeof(u64),1); - cellFsLseek(fd, 0, 0, pos_addr); - cellFsRead(fd, buffer, fileSize, nread); - Memory.Free(nread); - Memory.Free(pos_addr); + MemoryAllocator png(fileSize); + MemoryAllocator pos, nread; + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); + cellFsRead(fd, png.GetAddr(), png.GetSize(), nread); //Decode PNG file. (TODO: Is there any faster alternative? Can we do it without external libraries?) int width, height, actual_components; - unsigned char *png = (unsigned char*)Memory.VirtualToRealAddr(buffer); - unsigned char *image = stbi_load_from_memory(png, fileSize, &width, &height, &actual_components, 4); - Memory.Free(buffer); + std::shared_ptr image(stbi_load_from_memory(png, fileSize, &width, &height, &actual_components, 4)); if (!image) return CELL_PNGDEC_ERROR_STREAM_FORMAT; - u32 image_size = width * height * 4; - if (current_outParam.outputColorSpace == CELL_PNGDEC_RGBA){ - for(u32 i = 0; i < image_size; i+=4){ - data += image[i+0]; - data += image[i+1]; - data += image[i+2]; - data += image[i+3]; + uint image_size = width * height; + switch(current_outParam.outputColorSpace) + { + case CELL_PNGDEC_RGB: + case CELL_PNGDEC_RGBA: + image_size *= current_outParam.outputColorSpace == CELL_PNGDEC_RGBA ? 4 : 3; + memcpy(data, image.get(), image_size); + break; + + case CELL_PNGDEC_ARGB: + image_size *= 4; + + for(uint i = 0; i < image_size; i+=4) + { + data += image.get()[i+3]; + data += image.get()[i+0]; + data += image.get()[i+1]; + data += image.get()[i+2]; } + break; + + case CELL_PNGDEC_GRAYSCALE: + case CELL_PNGDEC_PALETTE: + case CELL_PNGDEC_GRAYSCALE_ALPHA: + cellPngDec.Error("cellPngDecDecodeData: Unsupported color space (%d)", current_outParam.outputColorSpace.ToLE()); + break; + + default: + return CELL_PNGDEC_ERROR_ARG; } - else if (current_outParam.outputColorSpace == CELL_PNGDEC_ARGB){ - for(u32 i = 0; i < image_size; i+=4){ - data += image[i+3]; - data += image[i+0]; - data += image[i+1]; - data += image[i+2]; - } - } - delete[] image; + + dataOutInfo->status = CELL_PNGDEC_DEC_STATUS_FINISH; return CELL_OK; } -int cellPngDecSetParameter(u32 mainHandle, u32 subHandle, u32 inParam_addr, mem_class_t outParam) +int cellPngDecSetParameter(u32 mainHandle, u32 subHandle, const mem_struct_ptr_t inParam, mem_struct_ptr_t outParam) { - CellPngDecInfo& current_info = ((CellPngDecSubHandle*)subHandle)->info; - CellPngDecOutParam& current_outParam = ((CellPngDecSubHandle*)subHandle)->outParam; + ID sub_handle_id_data; + if(!cellPngDec.CheckId(subHandle, sub_handle_id_data)) + return CELL_PNGDEC_ERROR_FATAL; - current_outParam.outputWidthByte = (current_info.imageWidth * current_info.numComponents * current_info.bitDepth)/8; + auto subHandle_data = (CellPngDecSubHandle*)sub_handle_id_data.m_data; + + CellPngDecInfo& current_info = subHandle_data->info; + CellPngDecOutParam& current_outParam = subHandle_data->outParam; + + current_outParam.outputWidthByte = (current_info.imageWidth * current_info.numComponents * current_info.bitDepth) / 8; current_outParam.outputWidth = current_info.imageWidth; current_outParam.outputHeight = current_info.imageHeight; - current_outParam.outputColorSpace = Memory.Read32(inParam_addr+8); + current_outParam.outputColorSpace = inParam->outputColorSpace; switch (current_outParam.outputColorSpace) { + case CELL_PNGDEC_PALETTE: case CELL_PNGDEC_GRAYSCALE: current_outParam.outputComponents = 1; break; + case CELL_PNGDEC_GRAYSCALE_ALPHA: current_outParam.outputComponents = 2; break; - case CELL_PNGDEC_PALETTE: current_outParam.outputComponents = 1; break; + case CELL_PNGDEC_RGB: current_outParam.outputComponents = 3; break; - case CELL_PNGDEC_RGBA: current_outParam.outputComponents = 4; break; + + case CELL_PNGDEC_RGBA: case CELL_PNGDEC_ARGB: current_outParam.outputComponents = 4; break; - default: return CELL_PNGDEC_ERROR_ARG; // Not supported color space + + default: return CELL_PNGDEC_ERROR_ARG; // Not supported color space } - current_outParam.outputBitDepth = Memory.Read32(inParam_addr+12); - current_outParam.outputMode = Memory.Read32(inParam_addr+4); + + current_outParam.outputBitDepth = inParam->outputBitDepth; + current_outParam.outputMode = inParam->outputMode; current_outParam.useMemorySpace = 0; // Unimplemented - outParam += current_outParam.outputWidthByte; - outParam += current_outParam.outputWidth; - outParam += current_outParam.outputHeight; - outParam += current_outParam.outputComponents; - outParam += current_outParam.outputBitDepth; - outParam += current_outParam.outputMode; - outParam += current_outParam.outputColorSpace; - outParam += current_outParam.useMemorySpace; + outParam = current_outParam; return CELL_OK; } diff --git a/rpcs3/Emu/SysCalls/Modules/cellResc.cpp b/rpcs3/Emu/SysCalls/Modules/cellResc.cpp index beaa904bad..5ffa755bfe 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellResc.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellResc.cpp @@ -9,7 +9,6 @@ Module cellRecs(0x001f, cellRecs_init); int cellRescSetConvertAndFlip(s32 indx) { cellRecs.Log("cellRescSetConvertAndFlip(indx=0x%x)", indx); - Emu.GetGSManager().GetRender().Draw(); return CELL_OK; } diff --git a/rpcs3/Emu/SysCalls/Modules/cellRtc.cpp b/rpcs3/Emu/SysCalls/Modules/cellRtc.cpp index 018287e977..967b0dedf3 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellRtc.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellRtc.cpp @@ -1,267 +1,609 @@ -#include "stdafx.h" -#include "Emu/SysCalls/SysCalls.h" -#include "Emu/SysCalls/SC_FUNC.h" - -void cellRtc_init(); -Module cellRtc(0x0009, cellRtc_init); - -// Return Codes -enum -{ - CELL_RTC_ERROR_NOT_INITIALIZED = 0x80010601, - CELL_RTC_ERROR_INVALID_POINTER = 0x80010602, - CELL_RTC_ERROR_INVALID_VALUE = 0x80010603, - CELL_RTC_ERROR_INVALID_ARG = 0x80010604, - CELL_RTC_ERROR_NOT_SUPPORTED = 0x80010605, - CELL_RTC_ERROR_NO_CLOCK = 0x80010606, - CELL_RTC_ERROR_BAD_PARSE = 0x80010607, - CELL_RTC_ERROR_INVALID_YEAR = 0x80010621, - CELL_RTC_ERROR_INVALID_MONTH = 0x80010622, - CELL_RTC_ERROR_INVALID_DAY = 0x80010623, - CELL_RTC_ERROR_INVALID_HOUR = 0x80010624, - CELL_RTC_ERROR_INVALID_MINUTE = 0x80010625, - CELL_RTC_ERROR_INVALID_SECOND = 0x80010626, - CELL_RTC_ERROR_INVALID_MICROSECOND = 0x80010627, -}; - -int cellRtcGetCurrentTick() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetCurrentClock() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetCurrentClockLocalTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcFormatRfc2822() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcFormatRfc2822LocalTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcFormatRfc3339() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcFormatRfc3339LocalTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcParseDateTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcParseRfc3339() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetTick() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcSetTick() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddTicks() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddMicroseconds() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddSeconds() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddMinutes() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddHours() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddDays() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddWeeks() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddMonths() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcTickAddYears() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcConvertUtcToLocalTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcConvertLocalTimeToUtc() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetDosTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetTime_t() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetWin32FileTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcSetDosTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcSetTime_t() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcSetWin32FileTime() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcIsLeapYear() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetDaysInMonth() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcGetDayOfWeek() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcCheckValid() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -int cellRtcCompareTick() -{ - UNIMPLEMENTED_FUNC(cellRtc); - return CELL_OK; -} - -void cellRtc_init() -{ - cellRtc.AddFunc(0x9dafc0d9, cellRtcGetCurrentTick); - cellRtc.AddFunc(0x32c941cf, cellRtcGetCurrentClock); - cellRtc.AddFunc(0x2cce9cf5, cellRtcGetCurrentClockLocalTime); - - cellRtc.AddFunc(0x5491b9d5, cellRtcFormatRfc2822); - cellRtc.AddFunc(0xa07c3d2f, cellRtcFormatRfc2822LocalTime); - cellRtc.AddFunc(0xd9c0b463, cellRtcFormatRfc3339); - cellRtc.AddFunc(0x1324948a, cellRtcFormatRfc3339LocalTime); - cellRtc.AddFunc(0xc5bc0fac, cellRtcParseDateTime); - cellRtc.AddFunc(0xcf11c3d6, cellRtcParseRfc3339); - - cellRtc.AddFunc(0xc7bdb7eb, cellRtcGetTick); - cellRtc.AddFunc(0x99b13034, cellRtcSetTick); - cellRtc.AddFunc(0x269a1882, cellRtcTickAddTicks); - cellRtc.AddFunc(0xf8509925, cellRtcTickAddMicroseconds); - cellRtc.AddFunc(0xccce71bd, cellRtcTickAddSeconds); - cellRtc.AddFunc(0x2f010bfa, cellRtcTickAddMinutes); - cellRtc.AddFunc(0xd41d3bd2, cellRtcTickAddHours); - cellRtc.AddFunc(0x75744e2a, cellRtcTickAddDays); - cellRtc.AddFunc(0x64c63fd5, cellRtcTickAddWeeks); - cellRtc.AddFunc(0xe0ecbb45, cellRtcTickAddMonths); - cellRtc.AddFunc(0x332a74dd, cellRtcTickAddYears); - cellRtc.AddFunc(0xc48d5002, cellRtcConvertUtcToLocalTime); - cellRtc.AddFunc(0x46ca7fe0, cellRtcConvertLocalTimeToUtc); - - // (TODO: Time Information Manipulation Functions missing) - - cellRtc.AddFunc(0xdfff32cf, cellRtcGetDosTime); - cellRtc.AddFunc(0xcb90c761, cellRtcGetTime_t); - cellRtc.AddFunc(0xe7086f05, cellRtcGetWin32FileTime); - cellRtc.AddFunc(0x9598d4b3, cellRtcSetDosTime); - cellRtc.AddFunc(0xbb543189, cellRtcSetTime_t); - cellRtc.AddFunc(0x5f68c268, cellRtcSetWin32FileTime); - - cellRtc.AddFunc(0x5316b4a8, cellRtcIsLeapYear); - cellRtc.AddFunc(0x5b6a0a1d, cellRtcGetDaysInMonth); - cellRtc.AddFunc(0xc2d8cf95, cellRtcGetDayOfWeek); - cellRtc.AddFunc(0x7f1086e6, cellRtcCheckValid); - - cellRtc.AddFunc(0xfb51fc61, cellRtcCompareTick); +#include "stdafx.h" +#include "Emu/SysCalls/SysCalls.h" +#include "Emu/SysCalls/SC_FUNC.h" + +void cellRtc_init(); +Module cellRtc(0x0009, cellRtc_init); + +// Return Codes +enum +{ + CELL_RTC_ERROR_NOT_INITIALIZED = 0x80010601, + CELL_RTC_ERROR_INVALID_POINTER = 0x80010602, + CELL_RTC_ERROR_INVALID_VALUE = 0x80010603, + CELL_RTC_ERROR_INVALID_ARG = 0x80010604, + CELL_RTC_ERROR_NOT_SUPPORTED = 0x80010605, + CELL_RTC_ERROR_NO_CLOCK = 0x80010606, + CELL_RTC_ERROR_BAD_PARSE = 0x80010607, + CELL_RTC_ERROR_INVALID_YEAR = 0x80010621, + CELL_RTC_ERROR_INVALID_MONTH = 0x80010622, + CELL_RTC_ERROR_INVALID_DAY = 0x80010623, + CELL_RTC_ERROR_INVALID_HOUR = 0x80010624, + CELL_RTC_ERROR_INVALID_MINUTE = 0x80010625, + CELL_RTC_ERROR_INVALID_SECOND = 0x80010626, + CELL_RTC_ERROR_INVALID_MICROSECOND = 0x80010627, +}; + +struct CellRtcTick +{ + u64 tick; +}; + +struct CellRtcDateTime +{ + u16 year; + u16 month; + u16 day; + u16 hour; + u16 minute; + u16 second; + u32 microsecond; +}; + +long convertToUNIXTime(u16 seconds, u16 minutes, u16 hours, u16 days, int years) +{ + return (seconds + minutes*60 + hours*3600 + days*86400 + (years-70)*31536000 + ((years-69)/4)*86400 - ((years-1)/100)*86400 + ((years+299)/400)*86400); +} + +u64 convertToWin32FILETIME(u16 seconds, u16 minutes, u16 hours, u16 days, int years) +{ + long unixtime = convertToUNIXTime(seconds, minutes, hours, days, years); + LONGLONG win32time = Int32x32To64(unixtime, 10000000) + 116444736000000000; + u64 win32filetime = (u64) win32time | win32time >> 32; + return win32filetime; +} + +int cellRtcGetCurrentTick(mem64_t tick) +{ + cellRtc.Log("cellRtcGetCurrentTick(tick_addr=0x%x)", tick.GetAddr()); + wxDateTime unow = wxDateTime::UNow(); + tick = unow.GetTicks(); + return CELL_OK; +} + +int cellRtcGetCurrentClock(u32 clock_addr, int time_zone) +{ + cellRtc.Log("cellRtcGetCurrentClock(clock_addr=0x%x, time_zone=%d)", clock_addr, time_zone); + wxDateTime unow = wxDateTime::UNow(); + + // Add time_zone as offset in minutes. + wxTimeSpan tz = wxTimeSpan::wxTimeSpan(0, (long) time_zone, 0, 0); + unow.Add(tz); + + Memory.Write16(clock_addr, unow.GetYear(wxDateTime::TZ::UTC)); + Memory.Write16(clock_addr + 2, unow.GetMonth(wxDateTime::TZ::UTC)); + Memory.Write16(clock_addr + 4, unow.GetDay(wxDateTime::TZ::UTC)); + Memory.Write16(clock_addr + 6, unow.GetHour(wxDateTime::TZ::UTC)); + Memory.Write16(clock_addr + 8, unow.GetMinute(wxDateTime::TZ::UTC)); + Memory.Write16(clock_addr + 10, unow.GetSecond(wxDateTime::TZ::UTC)); + Memory.Write32(clock_addr + 12, unow.GetMillisecond(wxDateTime::TZ::UTC) * 1000); + + return CELL_OK; +} + +int cellRtcGetCurrentClockLocalTime(u32 clock_addr) +{ + cellRtc.Log("cellRtcGetCurrentClockLocalTime(clock_addr=0x%x)", clock_addr); + wxDateTime unow = wxDateTime::UNow(); + + Memory.Write16(clock_addr, unow.GetYear(wxDateTime::TZ::Local)); + Memory.Write16(clock_addr + 2, unow.GetMonth(wxDateTime::TZ::Local)); + Memory.Write16(clock_addr + 4, unow.GetDay(wxDateTime::TZ::Local)); + Memory.Write16(clock_addr + 6, unow.GetHour(wxDateTime::TZ::Local)); + Memory.Write16(clock_addr + 8, unow.GetMinute(wxDateTime::TZ::Local)); + Memory.Write16(clock_addr + 10, unow.GetSecond(wxDateTime::TZ::Local)); + Memory.Write32(clock_addr + 12, unow.GetMillisecond(wxDateTime::TZ::Local) * 1000); + + return CELL_OK; +} + +int cellRtcFormatRfc2822(u32 rfc_addr, u32 tick_addr, int time_zone) +{ + cellRtc.Log("cellRtcFormatRfc2822(rfc_addr=0x%x, tick_addr=0x%x, time_zone=%d)", rfc_addr, tick_addr, time_zone); + CellRtcTick current_tick; + current_tick.tick = Memory.Read64(tick_addr); + + // Add time_zone as offset in minutes. + wxTimeSpan tz = wxTimeSpan::wxTimeSpan(0, (long) time_zone, 0, 0); + + // Get date from ticks + tz. + wxDateTime date = wxDateTime::wxDateTime((time_t)current_tick.tick); + date.Add(tz); + + // Format date string in RFC2822 format (e.g.: Mon, 01 Jan 1990 12:00:00 +0000). + const wxString& str = date.Format("%a, %d %b %Y %T %z", wxDateTime::TZ::UTC); + Memory.WriteString(rfc_addr, str); + + return CELL_OK; +} + +int cellRtcFormatRfc2822LocalTime(u32 rfc_addr, u32 tick_addr) +{ + cellRtc.Log("cellRtcFormatRfc2822LocalTime(rfc_addr=0x%x, tick_addr=0x%x)", rfc_addr, tick_addr); + CellRtcTick current_tick; + current_tick.tick = Memory.Read64(tick_addr); + + // Get date from ticks. + wxDateTime date = wxDateTime::wxDateTime((time_t)current_tick.tick); + + // Format date string in RFC2822 format (e.g.: Mon, 01 Jan 1990 12:00:00 +0000). + const wxString& str = date.Format("%a, %d %b %Y %T %z", wxDateTime::TZ::Local); + Memory.WriteString(rfc_addr, str); + + return CELL_OK; +} + +int cellRtcFormatRfc3339(u32 rfc_addr, u32 tick_addr, int time_zone) +{ + cellRtc.Log("cellRtcFormatRfc3339(rfc_addr=0x%x, tick_addr=0x%x, time_zone=%d)", rfc_addr, tick_addr, time_zone); + CellRtcTick current_tick; + current_tick.tick = Memory.Read64(tick_addr); + + // Add time_zone as offset in minutes. + wxTimeSpan tz = wxTimeSpan::wxTimeSpan(0, (long) time_zone, 0, 0); + + // Get date from ticks + tz. + wxDateTime date = wxDateTime::wxDateTime((time_t)current_tick.tick); + date.Add(tz); + + // Format date string in RFC3339 format (e.g.: 1990-01-01T12:00:00.00Z). + const wxString& str = date.Format("%FT%T.%zZ", wxDateTime::TZ::UTC); + Memory.WriteString(rfc_addr, str); + + return CELL_OK; +} + +int cellRtcFormatRfc3339LocalTime(u32 rfc_addr, u32 tick_addr) +{ + cellRtc.Log("cellRtcFormatRfc3339LocalTime(rfc_addr=0x%x, tick_addr=0x%x)", rfc_addr, tick_addr); + CellRtcTick current_tick; + current_tick.tick = Memory.Read64(tick_addr); + + // Get date from ticks. + wxDateTime date = wxDateTime::wxDateTime((time_t)current_tick.tick); + + // Format date string in RFC3339 format (e.g.: 1990-01-01T12:00:00.00Z). + const wxString& str = date.Format("%FT%T.%zZ", wxDateTime::TZ::Local); + Memory.WriteString(rfc_addr, str); + + return CELL_OK; +} + +int cellRtcParseDateTime(mem64_t tick, u32 datetime_addr) +{ + cellRtc.Log("cellRtcParseDateTime(tick_addr=0x%x, datetime_addr=0x%x)", tick.GetAddr(), datetime_addr); + + const wxString& format = Memory.ReadString(datetime_addr); + + // Get date from formatted string. + wxDateTime date; + date.ParseDateTime(format); + + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcParseRfc3339(mem64_t tick, u32 datetime_addr) +{ + cellRtc.Log("cellRtcParseRfc3339(tick_addr=0x%x, datetime_addr=0x%x)", tick.GetAddr(), datetime_addr); + + const wxString& format = Memory.ReadString(datetime_addr); + + // Get date from RFC3339 formatted string. + wxDateTime date; + date.ParseDateTime(format); + + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcGetTick(u32 clock_addr, mem64_t tick) +{ + cellRtc.Log("cellRtcGetTick(clock_addr=0x%x, tick_addr=0x%x)", clock_addr, tick.GetAddr()); + + CellRtcDateTime clock; + clock.year = Memory.Read16(clock_addr); + clock.month = Memory.Read16(clock_addr + 2); + clock.day = Memory.Read16(clock_addr + 4); + clock.hour = Memory.Read16(clock_addr + 6); + clock.minute = Memory.Read16(clock_addr + 8); + clock.second = Memory.Read16(clock_addr + 10); + clock.microsecond = Memory.Read32(clock_addr + 12); + + wxDateTime datetime = wxDateTime::wxDateTime(clock.day, (wxDateTime::Month)clock.month, clock.year, clock.hour, clock.minute, clock.second, (clock.microsecond / 1000)); + tick = datetime.GetTicks(); + + return CELL_OK; +} + +int cellRtcSetTick(u32 clock_addr, u32 tick_addr) +{ + cellRtc.Log("cellRtcSetTick(clock_addr=0x%x, tick_addr=0x%x)", clock_addr, tick_addr); + CellRtcTick current_tick; + current_tick.tick = Memory.Read64(tick_addr); + + wxDateTime date = wxDateTime::wxDateTime((time_t)current_tick.tick); + + CellRtcDateTime clock; + clock.year = date.GetYear(wxDateTime::TZ::UTC); + clock.month = date.GetMonth(wxDateTime::TZ::UTC); + clock.day = date.GetDay(wxDateTime::TZ::UTC); + clock.hour = date.GetHour(wxDateTime::TZ::UTC); + clock.minute = date.GetMinute(wxDateTime::TZ::UTC); + clock.second = date.GetSecond(wxDateTime::TZ::UTC); + clock.microsecond = date.GetMillisecond(wxDateTime::TZ::UTC) * 1000; + + Memory.Write16(clock_addr, clock.year); + Memory.Write16(clock_addr + 2, clock.month); + Memory.Write16(clock_addr + 4, clock.day); + Memory.Write16(clock_addr + 6, clock.hour); + Memory.Write16(clock_addr + 8, clock.minute); + Memory.Write16(clock_addr + 10, clock.second); + Memory.Write32(clock_addr + 12, clock.microsecond); + + return CELL_OK; +} + +int cellRtcTickAddTicks(mem64_t tick, u32 tick_add_addr, long add) +{ + cellRtc.Log("cellRtcTickAddTicks(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + tick = Memory.Read64(tick_add_addr) + add; + + return CELL_OK; +} + +int cellRtcTickAddMicroseconds(mem64_t tick, u32 tick_add_addr, long add) +{ + cellRtc.Log("cellRtcTickAddMicroseconds(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxTimeSpan microseconds = wxTimeSpan::wxTimeSpan(0, 0, 0, add / 1000); + date.Add(microseconds); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddSeconds(mem64_t tick, u32 tick_add_addr, long add) +{ + cellRtc.Log("cellRtcTickAddSeconds(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxTimeSpan seconds = wxTimeSpan::wxTimeSpan(0, 0, add, 0); + date.Add(seconds); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddMinutes(mem64_t tick, u32 tick_add_addr, long add) +{ + cellRtc.Log("cellRtcTickAddMinutes(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxTimeSpan minutes = wxTimeSpan::wxTimeSpan(0, add, 0, 0); + date.Add(minutes); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddHours(mem64_t tick, u32 tick_add_addr, int add) +{ + cellRtc.Log("cellRtcTickAddHours(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxTimeSpan hours = wxTimeSpan::wxTimeSpan(add, 0, 0, 0); + date.Add(hours); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddDays(mem64_t tick, u32 tick_add_addr, int add) +{ + cellRtc.Log("cellRtcTickAddDays(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxDateSpan days = wxDateSpan::wxDateSpan(0, 0, 0, add); + date.Add(days); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddWeeks(mem64_t tick, u32 tick_add_addr, int add) +{ + cellRtc.Log("cellRtcTickAddWeeks(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxDateSpan weeks = wxDateSpan::wxDateSpan(0, 0, add, 0); + date.Add(weeks); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddMonths(mem64_t tick, u32 tick_add_addr, int add) +{ + cellRtc.Log("cellRtcTickAddMonths(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxDateSpan months = wxDateSpan::wxDateSpan(0, add, 0, 0); + date.Add(months); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcTickAddYears(mem64_t tick, u32 tick_add_addr, int add) +{ + cellRtc.Log("cellRtcTickAddYears(tick_addr=0x%x, tick_add_addr=0x%x, add=%l)", tick.GetAddr(), tick_add_addr, add); + + wxDateTime date = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_add_addr)); + wxDateSpan years = wxDateSpan::wxDateSpan(add, 0, 0, 0); + date.Add(years); + tick = date.GetTicks(); + + return CELL_OK; +} + +int cellRtcConvertUtcToLocalTime(u32 tick_utc_addr, mem64_t tick_local) +{ + cellRtc.Log("cellRtcConvertUtcToLocalTime(tick_utc_addr=0x%x, tick_local_addr=0x%x)", tick_utc_addr, tick_local.GetAddr()); + wxDateTime time = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_utc_addr)); + wxDateTime local_time = time.FromUTC(false); + tick_local = local_time.GetTicks(); + return CELL_OK; +} + +int cellRtcConvertLocalTimeToUtc(u32 tick_local_addr, mem64_t tick_utc) +{ + cellRtc.Log("cellRtcConvertLocalTimeToUtc(tick_local_addr=0x%x, tick_utc_addr=0x%x)", tick_local_addr, tick_utc.GetAddr()); + wxDateTime time = wxDateTime::wxDateTime((time_t)Memory.Read64(tick_local_addr)); + wxDateTime utc_time = time.ToUTC(false); + tick_utc = utc_time.GetTicks(); + return CELL_OK; +} + +int cellRtcGetDosTime(u32 datetime_addr, mem64_t dos_time) +{ + cellRtc.Log("cellRtcGetDosTime(datetime_addr=0x%x, dos_time_addr=0x%x)", datetime_addr, dos_time.GetAddr()); + CellRtcDateTime datetime; + datetime.year = Memory.Read16(datetime_addr); + datetime.month = Memory.Read16(datetime_addr + 2); + datetime.day = Memory.Read16(datetime_addr + 4); + datetime.hour = Memory.Read16(datetime_addr + 6); + datetime.minute = Memory.Read16(datetime_addr + 8); + datetime.second = Memory.Read16(datetime_addr + 10); + datetime.microsecond = Memory.Read32(datetime_addr + 12); + + // Convert to DOS time. + wxDateTime date_time = wxDateTime::wxDateTime(datetime.day, (wxDateTime::Month)datetime.month, datetime.year, datetime.hour, datetime.minute, datetime.second, (datetime.microsecond / 1000)); + dos_time = date_time.GetAsDOS(); + + return CELL_OK; +} + +int cellRtcGetTime_t(u32 datetime_addr, mem64_t posix_time) +{ + cellRtc.Log("cellRtcGetTime_t(datetime_addr=0x%x, posix_time_addr=0x%x)", datetime_addr, posix_time.GetAddr()); + CellRtcDateTime datetime; + datetime.year = Memory.Read16(datetime_addr); + datetime.month = Memory.Read16(datetime_addr + 2); + datetime.day = Memory.Read16(datetime_addr + 4); + datetime.hour = Memory.Read16(datetime_addr + 6); + datetime.minute = Memory.Read16(datetime_addr + 8); + datetime.second = Memory.Read16(datetime_addr + 10); + datetime.microsecond = Memory.Read32(datetime_addr + 12); + + // Convert to POSIX time_t. + wxDateTime date_time = wxDateTime::wxDateTime(datetime.day, (wxDateTime::Month)datetime.month, datetime.year, datetime.hour, datetime.minute, datetime.second, (datetime.microsecond / 1000)); + posix_time = convertToUNIXTime(date_time.GetSecond(wxDateTime::TZ::UTC), date_time.GetMinute(wxDateTime::TZ::UTC), + date_time.GetHour(wxDateTime::TZ::UTC), date_time.GetDay(wxDateTime::TZ::UTC), date_time.GetYear(wxDateTime::TZ::UTC)); + + return CELL_OK; +} + +int cellRtcGetWin32FileTime(u32 datetime_addr, mem64_t win32_time) +{ + cellRtc.Log("cellRtcGetWin32FileTime(datetime_addr=0x%x, win32_time_addr=0x%x)", datetime_addr, win32_time.GetAddr()); + CellRtcDateTime datetime; + datetime.year = Memory.Read16(datetime_addr); + datetime.month = Memory.Read16(datetime_addr + 2); + datetime.day = Memory.Read16(datetime_addr + 4); + datetime.hour = Memory.Read16(datetime_addr + 6); + datetime.minute = Memory.Read16(datetime_addr + 8); + datetime.second = Memory.Read16(datetime_addr + 10); + datetime.microsecond = Memory.Read32(datetime_addr + 12); + + // Convert to WIN32 FILETIME. + wxDateTime date_time = wxDateTime::wxDateTime(datetime.day, (wxDateTime::Month)datetime.month, datetime.year, datetime.hour, datetime.minute, datetime.second, (datetime.microsecond / 1000)); + win32_time = convertToWin32FILETIME(date_time.GetSecond(wxDateTime::TZ::UTC), date_time.GetMinute(wxDateTime::TZ::UTC), + date_time.GetHour(wxDateTime::TZ::UTC), date_time.GetDay(wxDateTime::TZ::UTC), date_time.GetYear(wxDateTime::TZ::UTC)); + + return CELL_OK; +} + +int cellRtcSetDosTime(u32 datetime_addr, u32 dos_time_addr) +{ + cellRtc.Log("cellRtcSetDosTime(datetime_addr=0x%x, dos_time_addr=0x%x)", datetime_addr, dos_time_addr); + + wxDateTime date_time; + wxDateTime dos_time = date_time.SetFromDOS(Memory.Read32(dos_time_addr)); + + CellRtcDateTime datetime; + datetime.year = dos_time.GetYear(wxDateTime::TZ::UTC); + datetime.month = dos_time.GetMonth(wxDateTime::TZ::UTC); + datetime.day = dos_time.GetDay(wxDateTime::TZ::UTC); + datetime.hour = dos_time.GetHour(wxDateTime::TZ::UTC); + datetime.minute = dos_time.GetMinute(wxDateTime::TZ::UTC); + datetime.second = dos_time.GetSecond(wxDateTime::TZ::UTC); + datetime.microsecond = dos_time.GetMillisecond(wxDateTime::TZ::UTC) * 1000; + + Memory.Write16(datetime_addr, datetime.year); + Memory.Write16(datetime_addr + 2, datetime.month); + Memory.Write16(datetime_addr + 4, datetime.day); + Memory.Write16(datetime_addr + 6, datetime.hour); + Memory.Write16(datetime_addr + 8, datetime.minute); + Memory.Write16(datetime_addr + 10, datetime.second); + Memory.Write32(datetime_addr + 12, datetime.microsecond); + + return CELL_OK; +} + +int cellRtcSetTime_t(u32 datetime_addr, u32 posix_time_addr) +{ + cellRtc.Log("cellRtcSetTime_t(datetime_addr=0x%x, posix_time_addr=0x%x)", datetime_addr, posix_time_addr); + + wxDateTime date_time = wxDateTime::wxDateTime((time_t)Memory.Read64(posix_time_addr)); + + CellRtcDateTime datetime; + datetime.year = date_time.GetYear(wxDateTime::TZ::UTC); + datetime.month = date_time.GetMonth(wxDateTime::TZ::UTC); + datetime.day = date_time.GetDay(wxDateTime::TZ::UTC); + datetime.hour = date_time.GetHour(wxDateTime::TZ::UTC); + datetime.minute = date_time.GetMinute(wxDateTime::TZ::UTC); + datetime.second = date_time.GetSecond(wxDateTime::TZ::UTC); + datetime.microsecond = date_time.GetMillisecond(wxDateTime::TZ::UTC) * 1000; + + Memory.Write16(datetime_addr, datetime.year); + Memory.Write16(datetime_addr + 2, datetime.month); + Memory.Write16(datetime_addr + 4, datetime.day); + Memory.Write16(datetime_addr + 6, datetime.hour); + Memory.Write16(datetime_addr + 8, datetime.minute); + Memory.Write16(datetime_addr + 10, datetime.second); + Memory.Write32(datetime_addr + 12, datetime.microsecond); + + return CELL_OK; +} + +int cellRtcSetWin32FileTime(u32 datetime_addr, u32 win32_time_addr) +{ + cellRtc.Log("cellRtcSetWin32FileTime(datetime_addr=0x%x, win32_time_addr=0x%x)", datetime_addr, win32_time_addr); + + wxDateTime date_time = wxDateTime::wxDateTime((time_t)Memory.Read64(win32_time_addr)); + + CellRtcDateTime datetime; + datetime.year = date_time.GetYear(wxDateTime::TZ::UTC); + datetime.month = date_time.GetMonth(wxDateTime::TZ::UTC); + datetime.day = date_time.GetDay(wxDateTime::TZ::UTC); + datetime.hour = date_time.GetHour(wxDateTime::TZ::UTC); + datetime.minute = date_time.GetMinute(wxDateTime::TZ::UTC); + datetime.second = date_time.GetSecond(wxDateTime::TZ::UTC); + datetime.microsecond = date_time.GetMillisecond(wxDateTime::TZ::UTC) * 1000; + + Memory.Write16(datetime_addr, datetime.year); + Memory.Write16(datetime_addr + 2, datetime.month); + Memory.Write16(datetime_addr + 4, datetime.day); + Memory.Write16(datetime_addr + 6, datetime.hour); + Memory.Write16(datetime_addr + 8, datetime.minute); + Memory.Write16(datetime_addr + 10, datetime.second); + Memory.Write32(datetime_addr + 12, datetime.microsecond); + + return CELL_OK; +} + +int cellRtcIsLeapYear(int year) +{ + cellRtc.Log("cellRtcIsLeapYear(year=%d)", year); + + wxDateTime datetime; + return datetime.IsLeapYear(year, wxDateTime::Gregorian); +} + +int cellRtcGetDaysInMonth(int year, int month) +{ + cellRtc.Log("cellRtcGetDaysInMonth(year=%d, month=%d)", year, month); + + wxDateTime datetime; + return datetime.GetNumberOfDays((wxDateTime::Month) month, year, wxDateTime::Gregorian); +} + +int cellRtcGetDayOfWeek(int year, int month, int day) +{ + cellRtc.Log("cellRtcGetDayOfWeek(year=%d, month=%d, day=%d)", year, month, day); + + wxDateTime datetime; + datetime.SetToWeekDay((wxDateTime::WeekDay) day, 1, (wxDateTime::Month) month, year); + return datetime.GetWeekDay(); +} + +int cellRtcCheckValid(u32 datetime_addr) +{ + cellRtc.Log("cellRtcCheckValid(datetime_addr=0x%x)", datetime_addr); + CellRtcDateTime datetime; + datetime.year = Memory.Read16(datetime_addr); + datetime.month = Memory.Read16(datetime_addr + 2); + datetime.day = Memory.Read16(datetime_addr + 4); + datetime.hour = Memory.Read16(datetime_addr + 6); + datetime.minute = Memory.Read16(datetime_addr + 8); + datetime.second = Memory.Read16(datetime_addr + 10); + datetime.microsecond = Memory.Read32(datetime_addr + 12); + + if((datetime.year < 1) || (datetime.year > 9999)) return CELL_RTC_ERROR_INVALID_YEAR; + else if((datetime.month < 1) || (datetime.month > 12)) return CELL_RTC_ERROR_INVALID_MONTH; + else if((datetime.day < 1) || (datetime.day > 31)) return CELL_RTC_ERROR_INVALID_DAY; + else if((datetime.hour < 0) || (datetime.hour > 23)) return CELL_RTC_ERROR_INVALID_HOUR; + else if((datetime.minute < 0) || (datetime.minute > 59)) return CELL_RTC_ERROR_INVALID_MINUTE; + else if((datetime.second < 0) || (datetime.second > 59)) return CELL_RTC_ERROR_INVALID_SECOND; + else if((datetime.microsecond < 0) || (datetime.microsecond > 999999)) return CELL_RTC_ERROR_INVALID_MICROSECOND; + else return CELL_OK; +} + +int cellRtcCompareTick(u32 tick_addr_1, u32 tick_addr_2) +{ + cellRtc.Log("cellRtcCompareTick(tick_addr_1=0x%x, tick_addr_2=0x%x)", tick_addr_1, tick_addr_2); + u64 tick1 = Memory.Read64(tick_addr_1); + u64 tick2 = Memory.Read64(tick_addr_2); + + if(tick1 < tick2) return -1; + else if(tick1 > tick2) return 1; + else return CELL_OK; +} + +void cellRtc_init() +{ + cellRtc.AddFunc(0x9dafc0d9, cellRtcGetCurrentTick); + cellRtc.AddFunc(0x32c941cf, cellRtcGetCurrentClock); + cellRtc.AddFunc(0x2cce9cf5, cellRtcGetCurrentClockLocalTime); + + cellRtc.AddFunc(0x5491b9d5, cellRtcFormatRfc2822); + cellRtc.AddFunc(0xa07c3d2f, cellRtcFormatRfc2822LocalTime); + cellRtc.AddFunc(0xd9c0b463, cellRtcFormatRfc3339); + cellRtc.AddFunc(0x1324948a, cellRtcFormatRfc3339LocalTime); + cellRtc.AddFunc(0xc5bc0fac, cellRtcParseDateTime); + cellRtc.AddFunc(0xcf11c3d6, cellRtcParseRfc3339); + + cellRtc.AddFunc(0xc7bdb7eb, cellRtcGetTick); + cellRtc.AddFunc(0x99b13034, cellRtcSetTick); + cellRtc.AddFunc(0x269a1882, cellRtcTickAddTicks); + cellRtc.AddFunc(0xf8509925, cellRtcTickAddMicroseconds); + cellRtc.AddFunc(0xccce71bd, cellRtcTickAddSeconds); + cellRtc.AddFunc(0x2f010bfa, cellRtcTickAddMinutes); + cellRtc.AddFunc(0xd41d3bd2, cellRtcTickAddHours); + cellRtc.AddFunc(0x75744e2a, cellRtcTickAddDays); + cellRtc.AddFunc(0x64c63fd5, cellRtcTickAddWeeks); + cellRtc.AddFunc(0xe0ecbb45, cellRtcTickAddMonths); + cellRtc.AddFunc(0x332a74dd, cellRtcTickAddYears); + cellRtc.AddFunc(0xc48d5002, cellRtcConvertUtcToLocalTime); + cellRtc.AddFunc(0x46ca7fe0, cellRtcConvertLocalTimeToUtc); + + // (TODO: Time Information Manipulation Functions missing) + + cellRtc.AddFunc(0xdfff32cf, cellRtcGetDosTime); + cellRtc.AddFunc(0xcb90c761, cellRtcGetTime_t); + cellRtc.AddFunc(0xe7086f05, cellRtcGetWin32FileTime); + cellRtc.AddFunc(0x9598d4b3, cellRtcSetDosTime); + cellRtc.AddFunc(0xbb543189, cellRtcSetTime_t); + cellRtc.AddFunc(0x5f68c268, cellRtcSetWin32FileTime); + + cellRtc.AddFunc(0x5316b4a8, cellRtcIsLeapYear); + cellRtc.AddFunc(0x5b6a0a1d, cellRtcGetDaysInMonth); + cellRtc.AddFunc(0xc2d8cf95, cellRtcGetDayOfWeek); + cellRtc.AddFunc(0x7f1086e6, cellRtcCheckValid); + + cellRtc.AddFunc(0xfb51fc61, cellRtcCompareTick); } \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/Modules/cellSaveData.cpp b/rpcs3/Emu/SysCalls/Modules/cellSaveData.cpp index f9a2e81092..059b1b4d22 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellSaveData.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellSaveData.cpp @@ -2,11 +2,18 @@ #include "Emu/SysCalls/SysCalls.h" #include "Emu/SysCalls/SC_FUNC.h" +<<<<<<< HEAD void cellSaveData_init (); Module cellSaveData ("cellSaveData", cellSaveData_init); //Error codes +======= +void cellSaveData_init(); +Module cellSaveData("cellSaveData", cellSaveData_init); + +// Error codes +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa enum { CELL_SAVEDATA_RET_OK = 0, @@ -22,6 +29,7 @@ enum CELL_SAVEDATA_ERROR_NOUSER, }; +<<<<<<< HEAD //datatyps struct CellSaveDataSetList @@ -30,67 +38,121 @@ unsigned int sortType; unsigned int sortOrder; char *dirNamePrefix; void *reserved; +======= +// Datatypes +struct CellSaveDataSetList +{ + unsigned int sortType; + unsigned int sortOrder; + char *dirNamePrefix; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataSetBuf { +<<<<<<< HEAD unsigned int dirListMax; unsigned int fileListMax; unsigned int reserved[6]; unsigned int bufSize; void *buf; +======= + unsigned int dirListMax; + unsigned int fileListMax; + unsigned int reserved[6]; + unsigned int bufSize; + void *buf; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataNewDataIcon { +<<<<<<< HEAD char *title; unsigned int iconBufSize; void *iconBuf; void *reserved; +======= + char *title; + unsigned int iconBufSize; + void *iconBuf; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataListNewData { +<<<<<<< HEAD unsigned int iconPosition; char *dirName; CellSaveDataNewDataIcon *icon; void *reserved; +======= + unsigned int iconPosition; + char *dirName; + CellSaveDataNewDataIcon *icon; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataDirList { +<<<<<<< HEAD char dirName; //[CELL_SAVEDATA_DIRNAME_SIZE]; char listParam; //[CELL_SAVEDATA_SYSP_LPARAM_SIZE]; char reserved[8]; +======= + char dirName; //[CELL_SAVEDATA_DIRNAME_SIZE]; + char listParam; //[CELL_SAVEDATA_SYSP_LPARAM_SIZE]; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataListGet { +<<<<<<< HEAD unsigned int dirNum; unsigned int dirListNum; CellSaveDataDirList *dirList; char reserved[64]; +======= + unsigned int dirNum; + unsigned int dirListNum; + CellSaveDataDirList *dirList; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataListSet { +<<<<<<< HEAD unsigned int focusPosition; char *focusDirName; unsigned int fixedListNum; CellSaveDataDirList *fixedList; CellSaveDataListNewData *newData; void *reserved; +======= + unsigned int focusPosition; + char *focusDirName; + unsigned int fixedListNum; + CellSaveDataDirList *fixedList; + CellSaveDataListNewData *newData; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataFixedSet { +<<<<<<< HEAD char *dirName; CellSaveDataNewDataIcon *newIcon; unsigned int option; +======= + char *dirName; + CellSaveDataNewDataIcon *newIcon; + unsigned int option; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataSystemFileParam { +<<<<<<< HEAD char title; //[CELL_SAVEDATA_SYSP_TITLE_SIZE]; char subTitle; //[CELL_SAVEDATA_SYSP_SUBTITLE_SIZE]; char detail; //[CELL_SAVEDATA_SYSP_DETAIL_SIZE]; @@ -98,18 +160,35 @@ unsigned int attribute; char reserved2[4]; char listParam; //[CELL_SAVEDATA_SYSP_LPARAM_SIZE]; char reserved[256]; +======= + char title; //[CELL_SAVEDATA_SYSP_TITLE_SIZE]; + char subTitle; //[CELL_SAVEDATA_SYSP_SUBTITLE_SIZE]; + char detail; //[CELL_SAVEDATA_SYSP_DETAIL_SIZE]; + unsigned int attribute; + char reserved2[4]; + char listParam; //[CELL_SAVEDATA_SYSP_LPARAM_SIZE]; + char reserved[256]; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataDirStat { +<<<<<<< HEAD s64 st_atime; s64 st_mtime; s64 st_ctime; char dirName; //[CELL_SAVEDATA_DIRNAME_SIZE]; +======= + s64 st_atime; + s64 st_mtime; + s64 st_ctime; + char dirName; //[CELL_SAVEDATA_DIRNAME_SIZE]; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataFileStat { +<<<<<<< HEAD unsigned int fileType; char reserved1[4]; u64 st_size; @@ -118,10 +197,21 @@ s64 st_mtime; s64 st_ctime; char fileName; //[CELL_SAVEDATA_FILENAME_SIZE]; char reserved2[3]; +======= + unsigned int fileType; + char reserved1[4]; + u64 st_size; + s64 st_atime; + s64 st_mtime; + s64 st_ctime; + char fileName; //[CELL_SAVEDATA_FILENAME_SIZE]; + char reserved2[3]; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataStatGet { +<<<<<<< HEAD int hddFreeSizeKB; unsigned int isNewData; CellSaveDataDirStat dir; @@ -133,33 +223,64 @@ unsigned int fileNum; unsigned int fileListNum; CellSaveDataFileStat *fileList; char reserved[64]; +======= + int hddFreeSizeKB; + unsigned int isNewData; + CellSaveDataDirStat dir; + CellSaveDataSystemFileParam getParam; + unsigned int bind; + int sizeKB; + int sysSizeKB; + unsigned int fileNum; + unsigned int fileListNum; + CellSaveDataFileStat *fileList; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataAutoIndicator { +<<<<<<< HEAD unsigned int dispPosition; unsigned int dispMode; char *dispMsg; unsigned int picBufSize; void *picBuf; void *reserved; +======= + unsigned int dispPosition; + unsigned int dispMode; + char *dispMsg; + unsigned int picBufSize; + void *picBuf; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataStatSet { +<<<<<<< HEAD CellSaveDataSystemFileParam *setParam; unsigned int reCreateMode; CellSaveDataAutoIndicator *indicator; +======= + CellSaveDataSystemFileParam *setParam; + unsigned int reCreateMode; + CellSaveDataAutoIndicator *indicator; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataFileGet { +<<<<<<< HEAD unsigned int excSize; char reserved[64]; +======= + unsigned int excSize; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataFileSet { +<<<<<<< HEAD unsigned int fileOperation; void *reserved; unsigned int fileType; @@ -169,19 +290,39 @@ unsigned int fileOffset; unsigned int fileSize; unsigned int fileBufSize; void *fileBuf; +======= + unsigned int fileOperation; + void *reserved; + unsigned int fileType; + unsigned char secureFileId; //[CELL_SAVEDATA_SECUREFILEID_SIZE]; + char *fileName; + unsigned int fileOffset; + unsigned int fileSize; + unsigned int fileBufSize; + void *fileBuf; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataCBResult { +<<<<<<< HEAD int result; unsigned int progressBarInc; int errNeedSizeKB; char *invalidMsg; void *userdata; +======= + int result; + unsigned int progressBarInc; + int errNeedSizeKB; + char *invalidMsg; + void *userdata; +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa }; struct CellSaveDataDoneGet { +<<<<<<< HEAD int excResult; char dirName; //[CELL_SAVEDATA_DIRNAME_SIZE]; int sizeKB; @@ -192,196 +333,331 @@ char reserved[64]; //functions int cellSaveDataListSave2 () //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= + int excResult; + char dirName; //[CELL_SAVEDATA_DIRNAME_SIZE]; + int sizeKB; + int hddFreeSizeKB; +}; + +// Functions +int cellSaveDataListSave2() //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataListLoad2 () //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataListLoad2() //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataFixedSave2 () //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile,sys_memory_container_t container, void *userdata +======= +int cellSaveDataFixedSave2() //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile,sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataFixedLoad2 () //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataFixedLoad2() //unsigned int version, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataAutoSave2 () //unsigned int version, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataAutoSave2() //unsigned int version, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataAutoLoad2 () //unsigned int version, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataAutoLoad2() //unsigned int version, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataListAutoSave () //unsigned int version, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile,sys_memory_container_t container, void *userdata +======= +int cellSaveDataListAutoSave() //unsigned int version, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile,sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataListAutoLoad () //unsigned int version, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataListAutoLoad() //unsigned int version, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataDelete2 () //sys_memory_container_t container +======= +int cellSaveDataDelete2() //sys_memory_container_t container +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_CANCEL; } +<<<<<<< HEAD int cellSaveDataFixedDelete () //CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataFixedDelete() //CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListSave () //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListSave() //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListLoad () //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListLoad() //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserFixedSave () //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserFixedSave() //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserFixedLoad () //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserFixedLoad() //unsigned int version, CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserAutoSave () //unsigned int version, CellSysutilUserId userId, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserAutoSave() //unsigned int version, CellSysutilUserId userId, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserAutoLoad () //unsigned int version, CellSysutilUserId userId, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserAutoLoad() //unsigned int version, CellSysutilUserId userId, const char *dirName, unsigned int errDialog, CellSaveDataSetBuf *setBuf, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListAutoSave () //unsigned int version, CellSysutilUserId userId, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListAutoSave() //unsigned int version, CellSysutilUserId userId, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListAutoLoad () //unsigned int version, CellSysutilUserId userId, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListAutoLoad() //unsigned int version, CellSysutilUserId userId, unsigned int errDialog, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataStatCallback funcStat, CellSaveDataFileCallback funcFile, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserFixedDelete () //CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserFixedDelete() //CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataFixedCallback funcFixed, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD //void cellSaveDataEnableOverlay (); //int enable //Functions (Extensions) int cellSaveDataListDelete () //CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +//void cellSaveDataEnableOverlay(); //int enable + + +// Functions (Extensions) +int cellSaveDataListDelete() //CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataListImport () //CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataListImport() //CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataListExport () //CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataListExport() //CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataFixedImport () //const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataFixedImport() //const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataFixedExport () //const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataFixedExport() //const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataGetListItem () //const char *dirName, CellSaveDataDirStat *dir, CellSaveDataSystemFileParam *sysFileParam, unsigned int *bind, int *sizeKB +======= +int cellSaveDataGetListItem() //const char *dirName, CellSaveDataDirStat *dir, CellSaveDataSystemFileParam *sysFileParam, unsigned int *bind, int *sizeKB +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListDelete () //CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataDoneCallback funcDone,sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListDelete() //CellSysutilUserId userId, CellSaveDataSetList *setList, CellSaveDataSetBuf *setBuf, CellSaveDataListCallback funcList, CellSaveDataDoneCallback funcDone,sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListImport () //CellSysutilUserId userId, CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListImport() //CellSysutilUserId userId, CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserListExport () //CellSysutilUserId userId, CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserListExport() //CellSysutilUserId userId, CellSaveDataSetList *setList, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserFixedImport () //CellSysutilUserId userId, const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserFixedImport() //CellSysutilUserId userId, const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserFixedExport () //CellSysutilUserId userId, const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +======= +int cellSaveDataUserFixedExport() //CellSysutilUserId userId, const char *dirName, unsigned int maxSizeKB, CellSaveDataDoneCallback funcDone, sys_memory_container_t container, void *userdata +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD int cellSaveDataUserGetListItem () //CellSysutilUserId userId, const char *dirName, CellSaveDataDirStat *dir, CellSaveDataSystemFileParam *sysFileParam, unsigned int *bind, int *sizeKB +======= +int cellSaveDataUserGetListItem() //CellSysutilUserId userId, const char *dirName, CellSaveDataDirStat *dir, CellSaveDataSystemFileParam *sysFileParam, unsigned int *bind, int *sizeKB +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa { UNIMPLEMENTED_FUNC(cellSaveData); return CELL_SAVEDATA_RET_OK; } +<<<<<<< HEAD //Callback Functions @@ -427,4 +703,48 @@ void cellSaveData_init () cellSaveData.AddFunc (0xcdc6aefd, cellSaveDataUserAutoLoad); cellSaveData.AddFunc (0x0e091c36, cellSaveDataUserListAutoSave); //cellSaveData.AddFunc (0xe7fa820b, cellSaveDataEnableOverlay); +======= +// Callback Functions +void (*CellSaveDataFixedCallback)(); //CellSaveDataCBResult *cbResult, CellSaveDataListGet *get, CellSaveDataFixedSet *set + +void (*CellSaveDataListCallback)(); //CellSaveDataCBResult *cbResult, CellSaveDataListGet *get, CellSaveDataListSet *set + +void (*CellSaveDataStatCallback)(); //CellSaveDataCBResult *cbResult, CellSaveDataStatGet *get, CellSaveDataStatSet *set + +void (*CellSaveDataFileCallback)(); //CellSaveDataCBResult *cbResult, CellSaveDataFileGet *get, CellSaveDataFileSet *set + +void (*CellSaveDataDoneCallback)(); //CellSaveDataCBResult *cbResult, CellSaveDataDoneGet *get + +void cellSaveData_init() +{ + cellSaveData.AddFunc(0x04c06fc2, cellSaveDataGetListItem); + cellSaveData.AddFunc(0x273d116a, cellSaveDataUserListExport); + cellSaveData.AddFunc(0x27cb8bc2, cellSaveDataListDelete); + cellSaveData.AddFunc(0x39d6ee43, cellSaveDataUserListImport); + cellSaveData.AddFunc(0x46a2d878, cellSaveDataFixedExport); + cellSaveData.AddFunc(0x491cc554, cellSaveDataListExport); + cellSaveData.AddFunc(0x52541151, cellSaveDataFixedImport); + cellSaveData.AddFunc(0x529231b0, cellSaveDataUserFixedImport); + cellSaveData.AddFunc(0x6b4e0de6, cellSaveDataListImport); + cellSaveData.AddFunc(0x7048a9ba, cellSaveDataUserListDelete); + cellSaveData.AddFunc(0x95ae2cde, cellSaveDataUserFixedExport); + cellSaveData.AddFunc(0xf6482036, cellSaveDataUserGetListItem); + cellSaveData.AddFunc(0x2de0d663, cellSaveDataListSave2); + cellSaveData.AddFunc(0x1dfbfdd6, cellSaveDataListLoad2); + cellSaveData.AddFunc(0x2aae9ef5, cellSaveDataFixedSave2); + cellSaveData.AddFunc(0x2a8eada2, cellSaveDataFixedLoad2); + cellSaveData.AddFunc(0x8b7ed64b, cellSaveDataAutoSave2); + cellSaveData.AddFunc(0xfbd5c856, cellSaveDataAutoLoad2); + cellSaveData.AddFunc(0x4dd03a4e, cellSaveDataListAutoSave); + cellSaveData.AddFunc(0x21425307, cellSaveDataListAutoLoad); + cellSaveData.AddFunc(0xedadd797, cellSaveDataDelete2); + cellSaveData.AddFunc(0x0f03cfb0, cellSaveDataUserListSave); + cellSaveData.AddFunc(0x39dd8425, cellSaveDataUserListLoad); + cellSaveData.AddFunc(0x40b34847, cellSaveDataUserFixedSave); + cellSaveData.AddFunc(0x6e7264ed, cellSaveDataUserFixedLoad); + cellSaveData.AddFunc(0x52aac4fa, cellSaveDataUserAutoSave); + cellSaveData.AddFunc(0xcdc6aefd, cellSaveDataUserAutoLoad); + cellSaveData.AddFunc(0x0e091c36, cellSaveDataUserListAutoSave); + //cellSaveData.AddFunc(0xe7fa820b, cellSaveDataEnableOverlay); +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa } \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/Modules/cellScreenshot.cpp b/rpcs3/Emu/SysCalls/Modules/cellScreenshot.cpp index f7e3f3f503..9f00f5d99e 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellScreenshot.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellScreenshot.cpp @@ -16,13 +16,22 @@ enum CELL_SCREENSHOT_ERROR_UNSUPPORTED_COLOR_FORMAT = 0x8002d105, }; -int cellScreenShotSetParameter() +// Datatypes +struct CellScreenShotSetParam +{ + const char *photo_title; + const char *game_title; + const char *game_comment; +}; + +// Functions +int cellScreenShotSetParameter() //const CellScreenShotSetParam *param { UNIMPLEMENTED_FUNC(cellScreenshot); return CELL_OK; } -int cellScreenShotSetOverlayImage() +int cellScreenShotSetOverlayImage() //const char *srcDir, const char *srcFile, s32 offset_x, s32 offset_y { UNIMPLEMENTED_FUNC(cellScreenshot); return CELL_OK; diff --git a/rpcs3/Emu/SysCalls/Modules/cellSysmodule.cpp b/rpcs3/Emu/SysCalls/Modules/cellSysmodule.cpp index 3f18a17da7..2a88e575f5 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellSysmodule.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellSysmodule.cpp @@ -1,95 +1,218 @@ -#include "stdafx.h" -#include "Emu/SysCalls/Modules.h" -#include "Emu/SysCalls/SC_FUNC.h" - -void cellSysmodule_init(); -Module cellSysmodule("cellSysmodule", cellSysmodule_init); - -enum -{ - CELL_SYSMODULE_LOADED = CELL_OK, - CELL_SYSMODULE_ERROR_DUPLICATED = 0x80012001, - CELL_SYSMODULE_ERROR_UNKNOWN = 0x80012002, - CELL_SYSMODULE_ERROR_UNLOADED = 0x80012003, - CELL_SYSMODULE_ERROR_INVALID_MEMCONTAINER = 0x80012004, - CELL_SYSMODULE_ERROR_FATAL = 0x800120ff, -}; - -int cellSysmoduleInitialize() -{ - cellSysmodule.Log("cellSysmoduleInitialize()"); - return CELL_OK; -} - -int cellSysmoduleFinalize() -{ - cellSysmodule.Log("cellSysmoduleFinalize()"); - return CELL_OK; -} - -int cellSysmoduleSetMemcontainer(u32 ct_id) -{ - cellSysmodule.Warning("TODO: cellSysmoduleSetMemcontainer(ct_id=0x%x)", ct_id); - return CELL_OK; -} - -int cellSysmoduleLoadModule(u16 id) -{ - cellSysmodule.Warning("cellSysmoduleLoadModule(id=0x%04x)", id); - Module* m = GetModuleById(id); - - if(!m) - { - return CELL_SYSMODULE_ERROR_UNKNOWN; - } - - if(m->IsLoaded()) - { - return CELL_SYSMODULE_ERROR_DUPLICATED; - } - - m->Load(); - return CELL_OK; -} - -int cellSysmoduleUnloadModule(u16 id) -{ - cellSysmodule.Warning("cellSysmoduleUnloadModule(id=0x%04x)", id); - Module* m = GetModuleById(id); - - if(!m) - { - return CELL_SYSMODULE_ERROR_UNKNOWN; - } - - if(!m->IsLoaded()) - { - return CELL_SYSMODULE_ERROR_UNLOADED; - } - - m->UnLoad(); - return CELL_OK; -} - -int cellSysmoduleIsLoaded(u16 id) -{ - cellSysmodule.Warning("cellSysmoduleIsLoaded(id=0x%04x)", id); - Module* m = GetModuleById(id); - - if(!m) - { - return CELL_SYSMODULE_ERROR_UNKNOWN; - } - - return m->IsLoaded() ? CELL_SYSMODULE_LOADED : CELL_SYSMODULE_ERROR_UNLOADED; -} - -void cellSysmodule_init() -{ - cellSysmodule.AddFunc(0x63ff6ff9, cellSysmoduleInitialize); - cellSysmodule.AddFunc(0x96c07adf, cellSysmoduleFinalize); - cellSysmodule.AddFunc(0xa193143c, cellSysmoduleSetMemcontainer); - cellSysmodule.AddFunc(0x32267a31, cellSysmoduleLoadModule); - cellSysmodule.AddFunc(0x112a5ee9, cellSysmoduleUnloadModule); - cellSysmodule.AddFunc(0x5a59e258, cellSysmoduleIsLoaded); -} +#include "stdafx.h" +#include "Emu/SysCalls/Modules.h" +#include "Emu/SysCalls/SC_FUNC.h" + +void cellSysmodule_init(); +Module cellSysmodule("cellSysmodule", cellSysmodule_init); + +enum +{ + CELL_SYSMODULE_LOADED = CELL_OK, + CELL_SYSMODULE_ERROR_DUPLICATED = 0x80012001, + CELL_SYSMODULE_ERROR_UNKNOWN = 0x80012002, + CELL_SYSMODULE_ERROR_UNLOADED = 0x80012003, + CELL_SYSMODULE_ERROR_INVALID_MEMCONTAINER = 0x80012004, + CELL_SYSMODULE_ERROR_FATAL = 0x800120ff, +}; + +const char *getModuleName(int id) { + struct + { + const char *name; + int id; + } static const entries[] = { + {"CELL_SYSMODULE_INVALID", 0x0000ffff}, + {"CELL_SYSMODULE_NET", 0x00000000}, + {"CELL_SYSMODULE_HTTP", 0x00000001}, + {"CELL_SYSMODULE_HTTP_UTIL", 0x00000002}, + {"CELL_SYSMODULE_SSL", 0x00000003}, + {"CELL_SYSMODULE_HTTPS", 0x00000004}, + {"CELL_SYSMODULE_VDEC", 0x00000005}, + {"CELL_SYSMODULE_ADEC", 0x00000006}, + {"CELL_SYSMODULE_DMUX", 0x00000007}, + {"CELL_SYSMODULE_VPOST", 0x00000008}, + {"CELL_SYSMODULE_RTC", 0x00000009}, + {"CELL_SYSMODULE_SPURS", 0x0000000a}, + {"CELL_SYSMODULE_OVIS", 0x0000000b}, + {"CELL_SYSMODULE_SHEAP", 0x0000000c}, + {"CELL_SYSMODULE_SYNC", 0x0000000d}, + {"CELL_SYSMODULE_FS", 0x0000000e}, + {"CELL_SYSMODULE_JPGDEC", 0x0000000f}, + {"CELL_SYSMODULE_GCM_SYS", 0x00000010}, + {"CELL_SYSMODULE_GCM", 0x00000010}, + {"CELL_SYSMODULE_AUDIO", 0x00000011}, + {"CELL_SYSMODULE_PAMF", 0x00000012}, + {"CELL_SYSMODULE_ATRAC3PLUS", 0x00000013}, + {"CELL_SYSMODULE_NETCTL", 0x00000014}, + {"CELL_SYSMODULE_SYSUTIL", 0x00000015}, + {"CELL_SYSMODULE_SYSUTIL_NP", 0x00000016}, + {"CELL_SYSMODULE_IO", 0x00000017}, + {"CELL_SYSMODULE_PNGDEC", 0x00000018}, + {"CELL_SYSMODULE_FONT", 0x00000019}, + {"CELL_SYSMODULE_FONTFT", 0x0000001a}, + {"CELL_SYSMODULE_FREETYPE", 0x0000001b}, + {"CELL_SYSMODULE_USBD", 0x0000001c}, + {"CELL_SYSMODULE_SAIL", 0x0000001d}, + {"CELL_SYSMODULE_L10N", 0x0000001e}, + {"CELL_SYSMODULE_RESC", 0x0000001f}, + {"CELL_SYSMODULE_DAISY", 0x00000020}, + {"CELL_SYSMODULE_KEY2CHAR", 0x00000021}, + {"CELL_SYSMODULE_MIC", 0x00000022}, + {"CELL_SYSMODULE_CAMERA", 0x00000023}, + {"CELL_SYSMODULE_VDEC_MPEG2", 0x00000024}, + {"CELL_SYSMODULE_VDEC_AVC", 0x00000025}, + {"CELL_SYSMODULE_ADEC_LPCM", 0x00000026}, + {"CELL_SYSMODULE_ADEC_AC3", 0x00000027}, + {"CELL_SYSMODULE_ADEC_ATX", 0x00000028}, + {"CELL_SYSMODULE_ADEC_AT3", 0x00000029}, + {"CELL_SYSMODULE_DMUX_PAMF", 0x0000002a}, + {"CELL_SYSMODULE_VDEC_AL", 0x0000002b}, + {"CELL_SYSMODULE_ADEC_AL", 0x0000002c}, + {"CELL_SYSMODULE_DMUX_AL", 0x0000002d}, + {"CELL_SYSMODULE_LV2DBG", 0x0000002e}, + {"CELL_SYSMODULE_USBPSPCM", 0x00000030}, + {"CELL_SYSMODULE_AVCONF_EXT", 0x00000031}, + {"CELL_SYSMODULE_SYSUTIL_USERINFO", 0x00000032}, + {"CELL_SYSMODULE_SYSUTIL_SAVEDATA", 0x00000033}, + {"CELL_SYSMODULE_SUBDISPLAY", 0x00000034}, + {"CELL_SYSMODULE_SYSUTIL_REC", 0x00000035}, + {"CELL_SYSMODULE_VIDEO_EXPORT", 0x00000036}, + {"CELL_SYSMODULE_SYSUTIL_GAME_EXEC", 0x00000037}, + {"CELL_SYSMODULE_SYSUTIL_NP2", 0x00000038}, + {"CELL_SYSMODULE_SYSUTIL_AP", 0x00000039}, + {"CELL_SYSMODULE_SYSUTIL_NP_CLANS", 0x0000003a}, + {"CELL_SYSMODULE_SYSUTIL_OSK_EXT", 0x0000003b}, + {"CELL_SYSMODULE_VDEC_DIVX", 0x0000003c}, + {"CELL_SYSMODULE_JPGENC", 0x0000003d}, + {"CELL_SYSMODULE_SYSUTIL_GAME", 0x0000003e}, + {"CELL_SYSMODULE_BGDL", 0x0000003f}, + {"CELL_SYSMODULE_FREETYPE_TT", 0x00000040}, + {"CELL_SYSMODULE_SYSUTIL_VIDEO_UPLOAD", 0x00000041}, + {"CELL_SYSMODULE_SYSUTIL_SYSCONF_EXT", 0x00000042}, + {"CELL_SYSMODULE_FIBER", 0x00000043}, + {"CELL_SYSMODULE_SYSUTIL_NP_COMMERCE2", 0x00000044}, + {"CELL_SYSMODULE_SYSUTIL_NP_TUS", 0x00000045}, + {"CELL_SYSMODULE_VOICE", 0x00000046}, + {"CELL_SYSMODULE_ADEC_CELP8", 0x00000047}, + {"CELL_SYSMODULE_CELP8ENC", 0x00000048}, + {"CELL_SYSMODULE_SYSUTIL_LICENSEAREA", 0x00000049}, + {"CELL_SYSMODULE_SYSUTIL_MUSIC2", 0x0000004a}, + {"CELL_SYSMODULE_SYSUTIL_SCREENSHOT", 0x0000004e}, + {"CELL_SYSMODULE_SYSUTIL_MUSIC_DECODE", 0x0000004f}, + {"CELL_SYSMODULE_SPURS_JQ", 0x00000050}, + {"CELL_SYSMODULE_PNGENC", 0x00000052}, + {"CELL_SYSMODULE_SYSUTIL_MUSIC_DECODE2", 0x00000053}, + {"CELL_SYSMODULE_SYNC2", 0x00000055}, + {"CELL_SYSMODULE_SYSUTIL_NP_UTIL", 0x00000056}, + {"CELL_SYSMODULE_RUDP", 0x00000057}, + {"CELL_SYSMODULE_SYSUTIL_NP_SNS", 0x00000059}, + {"CELL_SYSMODULE_GEM", 0x0000005a}, + {"CELL_SYSMODULE_CELPENC", 0x0000f00a}, + {"CELL_SYSMODULE_GIFDEC", 0x0000f010}, + {"CELL_SYSMODULE_ADEC_CELP", 0x0000f019}, + {"CELL_SYSMODULE_ADEC_M2BC", 0x0000f01b}, + {"CELL_SYSMODULE_ADEC_M4AAC", 0x0000f01d}, + {"CELL_SYSMODULE_ADEC_MP3", 0x0000f01e}, + {"CELL_SYSMODULE_IMEJP", 0x0000f023}, + {"CELL_SYSMODULE_SYSUTIL_MUSIC", 0x0000f028}, + {"CELL_SYSMODULE_PHOTO_EXPORT", 0x0000f029}, + {"CELL_SYSMODULE_PRINT", 0x0000f02a}, + {"CELL_SYSMODULE_PHOTO_IMPORT", 0x0000f02b}, + {"CELL_SYSMODULE_MUSIC_EXPORT", 0x0000f02c}, + {"CELL_SYSMODULE_PHOTO_DECODE", 0x0000f02e}, + {"CELL_SYSMODULE_SYSUTIL_SEARCH", 0x0000f02f}, + {"CELL_SYSMODULE_SYSUTIL_AVCHAT2", 0x0000f030}, + {"CELL_SYSMODULE_SAIL_REC", 0x0000f034}, + {"CELL_SYSMODULE_SYSUTIL_NP_TROPHY", 0x0000f035}, + {"CELL_SYSMODULE_LIBATRAC3MULTI", 0x0000f054}, + }; + + for (int i = 0; i < sizeof(entries) / sizeof(entries[0]); ++i) + { + if (entries[i].id == id) + { + return entries[i].name; + } + } + + return 0; +} + +int cellSysmoduleInitialize() +{ + cellSysmodule.Log("cellSysmoduleInitialize()"); + return CELL_OK; +} + +int cellSysmoduleFinalize() +{ + cellSysmodule.Log("cellSysmoduleFinalize()"); + return CELL_OK; +} + +int cellSysmoduleSetMemcontainer(u32 ct_id) +{ + cellSysmodule.Warning("TODO: cellSysmoduleSetMemcontainer(ct_id=0x%x)", ct_id); + return CELL_OK; +} + +int cellSysmoduleLoadModule(u16 id) +{ + cellSysmodule.Warning("cellSysmoduleLoadModule(%s)", getModuleName(id)); + Module* m = GetModuleById(id); + + if(!m) + { + return CELL_SYSMODULE_ERROR_UNKNOWN; + } + + if(m->IsLoaded()) + { + return CELL_SYSMODULE_ERROR_DUPLICATED; + } + + m->Load(); + return CELL_OK; +} + +int cellSysmoduleUnloadModule(u16 id) +{ + cellSysmodule.Warning("cellSysmoduleUnloadModule(%s)", getModuleName(id)); + Module* m = GetModuleById(id); + + if(!m) + { + return CELL_SYSMODULE_ERROR_UNKNOWN; + } + + if(!m->IsLoaded()) + { + return CELL_SYSMODULE_ERROR_UNLOADED; + } + + m->UnLoad(); + return CELL_OK; +} + +int cellSysmoduleIsLoaded(u16 id) +{ + cellSysmodule.Warning("cellSysmoduleIsLoaded(%s)", getModuleName(id)); + Module* m = GetModuleById(id); + + if(!m) + { + return CELL_SYSMODULE_ERROR_UNKNOWN; + } + + return m->IsLoaded() ? CELL_SYSMODULE_LOADED : CELL_SYSMODULE_ERROR_UNLOADED; +} + +void cellSysmodule_init() +{ + cellSysmodule.AddFunc(0x63ff6ff9, cellSysmoduleInitialize); + cellSysmodule.AddFunc(0x96c07adf, cellSysmoduleFinalize); + cellSysmodule.AddFunc(0xa193143c, cellSysmoduleSetMemcontainer); + cellSysmodule.AddFunc(0x32267a31, cellSysmoduleLoadModule); + cellSysmodule.AddFunc(0x112a5ee9, cellSysmoduleUnloadModule); + cellSysmodule.AddFunc(0x5a59e258, cellSysmoduleIsLoaded); +} diff --git a/rpcs3/Emu/SysCalls/Modules/cellSysutil.cpp b/rpcs3/Emu/SysCalls/Modules/cellSysutil.cpp index e6f0090ee1..f06d896fa5 100644 --- a/rpcs3/Emu/SysCalls/Modules/cellSysutil.cpp +++ b/rpcs3/Emu/SysCalls/Modules/cellSysutil.cpp @@ -102,9 +102,21 @@ enum void cellSysutil_init(); Module cellSysutil(0x0015, cellSysutil_init); -void cellVideoOutGetDeviceInfo() +int cellVideoOutGetDeviceInfo(u32 videoOut, u32 deviceIndex, mem_struct_ptr_t info) { - UNIMPLEMENTED_FUNC(cellSysutil); + cellSysutil.Error("Unimplemented function: cellVideoOutGetDeviceInfo(videoOut=%u, deviceIndex=%u, info_addr=0x%x)", + videoOut, deviceIndex, info.GetAddr()); + + if(deviceIndex) return CELL_VIDEO_OUT_ERROR_DEVICE_NOT_FOUND; + + //info->portType = CELL_VIDEO_OUT_PORT_HDMI; + info->colorSpace = Emu.GetGSManager().GetColorSpace(); + //info->latency = ; + //info->availableModeCount = ; + //info->state = CELL_VIDEO_OUT_DEVICE_STATE_AVAILABLE; + //info->rgbOutputRange = ; + + return CELL_OK; } int cellSysutilGetSystemParamInt(int id, mem32_t value) diff --git a/rpcs3/Emu/SysCalls/Modules/sys_fs.cpp b/rpcs3/Emu/SysCalls/Modules/sys_fs.cpp index 79cf6f1cba..38bb598860 100644 --- a/rpcs3/Emu/SysCalls/Modules/sys_fs.cpp +++ b/rpcs3/Emu/SysCalls/Modules/sys_fs.cpp @@ -5,9 +5,140 @@ void sys_fs_init(); Module sys_fs(0x000e, sys_fs_init); +bool sdata_check(u32 version, u32 flags, u64 filesizeInput, u64 filesizeTmp) +{ + if (version > 4 || flags & 0x7EFFFFC0){ + printf("ERROR: unknown version"); + return false; + } + + if ((version == 1 && (flags & 0x7FFFFFFE)) || + (version == 2 && (flags & 0x7EFFFFC0))){ + printf("ERROR: unknown or unsupported type"); + return false; + } + + if (filesizeTmp > filesizeInput){ + printf("ERROR: input file size is too short."); + return false; + } + + if (!(flags & 0x80000000)){ + printf("ERROR: cannot extract finalized edata."); + return false; + } + + return true; +} + +int sdata_unpack(wxString packed_file, wxString unpacked_file) +{ + vfsStream* packed_stream = Emu.GetVFS().Open(packed_file, vfsRead); + vfsStream* unpacked_stream = Emu.GetVFS().Open(unpacked_file, vfsWrite); + + if(!packed_stream || !packed_stream->IsOpened()) + { + sys_fs.Error("'%s' not found! flags: 0x%08x", packed_file, vfsRead); + delete packed_stream; + return CELL_ENOENT; + } + + if(!unpacked_stream || !unpacked_stream->IsOpened()) + { + sys_fs.Error("'%s' couldn't be created! flags: 0x%08x", unpacked_file, vfsWrite); + delete unpacked_stream; + return CELL_ENOENT; + } + + char buffer [10200]; + packed_stream->Read(buffer, 256); + if (re32(*(u32*)&buffer[0]) != 0x4E504400) // "NPD\x00" + { + printf("ERROR: illegal format."); + return CELL_EFSSPECIFIC; + } + + u32 version = re32(*(u32*)&buffer[0x04]); + u32 flags = re32(*(u32*)&buffer[0x80]); + u32 blockSize = re32(*(u32*)&buffer[0x84]); + u64 filesizeOutput = re64(*(u64*)&buffer[0x88]); + u64 filesizeInput = packed_stream->GetSize(); + u32 blockCount = (filesizeOutput + blockSize-1) / blockSize; + + // SDATA file is compressed + if (flags & 0x1) + { + sys_fs.Warning("cellFsSdataOpen: Compressed SDATA files are not supported yet."); + return CELL_EFSSPECIFIC; + } + + // SDATA file is NOT compressed + else + { + u32 t1 = (flags & 0x20) ? 0x20 : 0x10; + u32 startOffset = (blockCount * t1) + 0x100; + u64 filesizeTmp = (filesizeOutput+0xF)&0xFFFFFFF0 + startOffset; + + if (!sdata_check(version, flags, filesizeInput, filesizeTmp)) + { + sys_fs.Error("cellFsSdataOpen: Wrong header information."); + return CELL_EFSSPECIFIC; + } + + if (flags & 0x20) + packed_stream->Seek(0x100); + else + packed_stream->Seek(startOffset); + + for (u32 i = 0; i < blockCount; i++) + { + if (flags & 0x20) + packed_stream->Seek(packed_stream->Tell() + t1); + + if (!(blockCount-i-1)) + blockSize = filesizeOutput-i*blockSize; + + packed_stream->Read(buffer+256, blockSize); + unpacked_stream->Write(buffer+256, blockSize); + } + } + + packed_stream->Close(); + unpacked_stream->Close(); + + return CELL_OK; +} + + +int cellFsSdataOpen(u32 path_addr, int flags, mem32_t fd, mem32_t arg, u64 size) +{ + const wxString& path = Memory.ReadString(path_addr); + sys_fs.Warning("cellFsSdataOpen(path: %s, flags: 0x%x, fd_addr: 0x%x, arg_addr: 0x%x, size: 0x%llx)", + path, flags, fd.GetAddr(), arg.GetAddr(), size); + + if (!fd.IsGood() || (!arg.IsGood() && size)) + return CELL_EFAULT; + + if (flags != CELL_O_RDONLY) + return CELL_EINVAL; + + if (!path.Lower().EndsWith(".sdat")) + return CELL_ENOTSDATA; + + wxString unpacked_path = "/dev_hdd1/"+path.AfterLast('/')+".unpacked"; + int ret = sdata_unpack(path, unpacked_path); + if (ret) return ret; + + vfsStream* stream = Emu.GetVFS().Open(unpacked_path, vfsRead); + fd = sys_fs.GetNewId(stream, flags); + + return CELL_OK; +} + void sys_fs_init() { sys_fs.AddFunc(0x718bf5f8, cellFsOpen); + sys_fs.AddFunc(0xb1840b53, cellFsSdataOpen); sys_fs.AddFunc(0x4d5ff8e2, cellFsRead); sys_fs.AddFunc(0xecdcf2ab, cellFsWrite); sys_fs.AddFunc(0x2cb51f0d, cellFsClose); diff --git a/rpcs3/Emu/SysCalls/SC_FUNC.h b/rpcs3/Emu/SysCalls/SC_FUNC.h index 9cee74bba0..a91f5c0f25 100644 --- a/rpcs3/Emu/SysCalls/SC_FUNC.h +++ b/rpcs3/Emu/SysCalls/SC_FUNC.h @@ -32,7 +32,7 @@ class binder_func_1 : public func_caller public: binder_func_1(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_1)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0)); } }; template @@ -43,7 +43,7 @@ class binder_func_1 : public func_caller public: binder_func_1(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_1); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0); } }; template @@ -54,7 +54,7 @@ class binder_func_2 : public func_caller public: binder_func_2(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_2)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1)); } }; template @@ -65,7 +65,7 @@ class binder_func_2 : public func_caller public: binder_func_2(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_2); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1); } }; template @@ -76,7 +76,7 @@ class binder_func_3 : public func_caller public: binder_func_3(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_3)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2)); } }; template @@ -87,7 +87,7 @@ class binder_func_3 : public func_caller public: binder_func_3(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_3); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2); } }; template @@ -98,7 +98,7 @@ class binder_func_4 : public func_caller public: binder_func_4(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_4)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3)); } }; template @@ -109,7 +109,7 @@ class binder_func_4 : public func_caller public: binder_func_4(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_4); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3); } }; template @@ -120,7 +120,7 @@ class binder_func_5 : public func_caller public: binder_func_5(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_5)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4)); } }; template @@ -131,7 +131,7 @@ class binder_func_5 : public func_caller public: binder_func_5(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_5); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4); } }; template @@ -142,7 +142,7 @@ class binder_func_6 : public func_caller public: binder_func_6(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_6)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5)); } }; template @@ -153,7 +153,7 @@ class binder_func_6 : public func_caller public: binder_func_6(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_6); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5); } }; template @@ -164,7 +164,7 @@ class binder_func_7 : public func_caller public: binder_func_7(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_7)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6)); } }; template @@ -175,7 +175,7 @@ class binder_func_7 : public func_caller public: binder_func_7(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_7); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6); } }; template @@ -186,7 +186,7 @@ class binder_func_8 : public func_caller public: binder_func_8(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_8)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7)); } }; template @@ -197,7 +197,7 @@ class binder_func_8 : public func_caller public: binder_func_8(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_8); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7); } }; template @@ -208,7 +208,7 @@ class binder_func_9 : public func_caller public: binder_func_9(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_9)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8)); } }; template @@ -219,7 +219,7 @@ class binder_func_9 : public func_call public: binder_func_9(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_9); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8); } }; template @@ -230,7 +230,7 @@ class binder_func_10 : public func_caller public: binder_func_10(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_10)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8, (T10&)SC_ARG_9)); } }; template @@ -241,7 +241,7 @@ class binder_func_10 : public fun public: binder_func_10(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_10); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8, (T10&)SC_ARG_9); } }; template @@ -252,7 +252,7 @@ class binder_func_11 : public func_caller public: binder_func_11(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_11)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8, (T10&)SC_ARG_9, (T11&)SC_ARG_10)); } }; template @@ -263,7 +263,7 @@ class binder_func_11 : publi public: binder_func_11(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_11); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8, (T10&)SC_ARG_9, (T11&)SC_ARG_10); } }; template @@ -274,7 +274,7 @@ class binder_func_12 : public func_caller public: binder_func_12(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); RESULT(m_call(SC_ARGS_12)); } + virtual void operator()() { declCPU(); RESULT(m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8, (T10&)SC_ARG_9, (T11&)SC_ARG_10, (T12&)SC_ARG_11)); } }; template @@ -285,7 +285,7 @@ class binder_func_12 : public: binder_func_12(func_t call) : func_caller(), m_call(call) {} - virtual void operator()() { declCPU(); m_call(SC_ARGS_12); } + virtual void operator()() { declCPU(); m_call((T1&)SC_ARG_0, (T2&)SC_ARG_1, (T3&)SC_ARG_2, (T4&)SC_ARG_3, (T5&)SC_ARG_4, (T6&)SC_ARG_5, (T7&)SC_ARG_6, (T8&)SC_ARG_7, (T9&)SC_ARG_8, (T10&)SC_ARG_9, (T11&)SC_ARG_10, (T12&)SC_ARG_11); } }; template diff --git a/rpcs3/Emu/SysCalls/SysCalls.cpp b/rpcs3/Emu/SysCalls/SysCalls.cpp index e76bf979e3..703181c264 100644 --- a/rpcs3/Emu/SysCalls/SysCalls.cpp +++ b/rpcs3/Emu/SysCalls/SysCalls.cpp @@ -10,33 +10,85 @@ static func_caller* sc_table[1024] = { null_func, bind_func(sys_process_getpid), null_func, bind_func(sys_process_exit), null_func, //4 null_func, null_func, null_func, null_func, null_func, //9 - null_func, null_func, null_func, null_func, null_func, //14 - null_func, null_func, null_func, null_func, null_func, //19 + null_func, null_func, bind_func(sys_process_get_number_of_object), bind_func(sys_process_get_id), null_func, //14 + null_func, null_func, null_func, bind_func(sys_process_getppid), null_func, //19 null_func, null_func, bind_func(sys_process_exit), null_func, null_func, //24 null_func, null_func, null_func, null_func, null_func, //29 - null_func, null_func, null_func, null_func, null_func, //34 + bind_func(sys_process_get_paramsfo), null_func, null_func, null_func, null_func, //34 null_func, null_func, null_func, null_func, null_func, //39 - null_func, bind_func(sys_ppu_thread_exit), null_func, bind_func(sys_ppu_thread_yield), bind_func(sys_ppu_thread_join), //44 - bind_func(sys_ppu_thread_detach), bind_func(sys_ppu_thread_get_join_state), bind_func(sys_ppu_thread_set_priority), bind_func(sys_ppu_thread_get_priority), bind_func(sys_ppu_thread_get_stack_information), //49 - bind_func(sys_ppu_thread_stop), bind_func(sys_ppu_thread_restart), bind_func(sys_ppu_thread_create), null_func, null_func, //54 + null_func, //40 (0x028) + bind_func(sys_ppu_thread_exit), //41 (0x029) + null_func, //42 (0x02A) + bind_func(sys_ppu_thread_yield), //43 (0x02B) + bind_func(sys_ppu_thread_join), //44 (0x02C) + bind_func(sys_ppu_thread_detach), //45 (0x02D) + bind_func(sys_ppu_thread_get_join_state), //46 (0x02E) + bind_func(sys_ppu_thread_set_priority), //47 (0x02F) + bind_func(sys_ppu_thread_get_priority), //48 (0x030) + bind_func(sys_ppu_thread_get_stack_information), //49 (0x031) + bind_func(sys_ppu_thread_stop), //50 (0x032) + bind_func(sys_ppu_thread_restart), //51 (0x033) + bind_func(sys_ppu_thread_create), //52 (0x034) + null_func, //53 (0x035) + null_func, //54 (0x036) null_func, null_func, null_func, null_func, null_func, //59 - null_func, null_func, null_func, null_func, null_func, //64 - null_func, null_func, null_func, null_func, null_func, //69 - null_func, null_func, null_func, null_func, null_func, //74 - null_func, null_func, null_func, null_func, null_func, //49 + bind_func(sys_trace_create), //60 (0x03C) + bind_func(sys_trace_start), //61 (0x03D) + bind_func(sys_trace_stop), //62 (0x03E) + bind_func(sys_trace_update_top_index), //63 (0x03F) + bind_func(sys_trace_destroy), //64 (0x040) + bind_func(sys_trace_drain), //65 (0x041) + bind_func(sys_trace_attach_process), //66 (0x042) + bind_func(sys_trace_allocate_buffer), //67 (0x043) + bind_func(sys_trace_free_buffer), //68 (0x044) + bind_func(sys_trace_create2), //69 (0x045) + bind_func(sys_timer_create), //70 (0x046) + bind_func(sys_timer_destroy), //71 (0x047) + bind_func(sys_timer_get_information), //72 (0x048) + bind_func(sys_timer_start), //73 (0x049) + bind_func(sys_timer_stop), //74 (0x04A) + bind_func(sys_timer_connect_event_queue), //75 (0x04B) + bind_func(sys_timer_disconnect_event_queue), //76 (0x04C) + null_func, //77 (0x04D) + null_func, //78 (0x04E) + null_func, //79 (0x04F) null_func, null_func, null_func, null_func, null_func, //84 null_func, null_func, null_func, null_func, null_func, //89 - bind_func(sys_semaphore_create), bind_func(sys_semaphore_destroy), bind_func(sys_semaphore_wait), bind_func(sys_semaphore_trywait), bind_func(sys_semaphore_post), //94 - bind_func(sys_lwmutex_create), bind_func(sys_lwmutex_destroy), bind_func(sys_lwmutex_lock), bind_func(sys_lwmutex_trylock), bind_func(sys_lwmutex_unlock), //99 - bind_func(sys_mutex_create), bind_func(sys_mutex_destroy), bind_func(sys_mutex_lock), bind_func(sys_mutex_trylock), bind_func(sys_mutex_unlock), //104 - bind_func(sys_cond_create), bind_func(sys_cond_destroy), bind_func(sys_cond_wait), bind_func(sys_cond_signal), bind_func(sys_cond_signal_all), //109 + bind_func(sys_semaphore_create), //90 (0x05A) + bind_func(sys_semaphore_destroy), //91 (0x05B) + bind_func(sys_semaphore_wait), //92 (0x05C) + bind_func(sys_semaphore_trywait), //93 (0x05D) + bind_func(sys_semaphore_post), //94 (0x05E) + bind_func(sys_lwmutex_create), //95 (0x05F) + bind_func(sys_lwmutex_destroy), //96 (0x060) + bind_func(sys_lwmutex_lock), //97 (0x061) + bind_func(sys_lwmutex_trylock), //98 (0x062) + bind_func(sys_lwmutex_unlock), //99 (0x063) + bind_func(sys_mutex_create), //100 (0x064) + bind_func(sys_mutex_destroy), //101 (0x065) + bind_func(sys_mutex_lock), //102 (0x066) + bind_func(sys_mutex_trylock), //103 (0x067) + bind_func(sys_mutex_unlock), //104 (0x068) + bind_func(sys_cond_create), //105 (0x069) + bind_func(sys_cond_destroy), //106 (0x06A) + bind_func(sys_cond_wait), //107 (0x06B) + bind_func(sys_cond_signal), //108 (0x06C) + bind_func(sys_cond_signal_all), //109 (0x06D) null_func, null_func, null_func, null_func, null_func, //114 null_func, null_func, null_func, null_func, null_func, //119 - null_func, null_func, null_func, null_func, null_func, //124 - null_func, null_func, null_func, bind_func(sys_event_queue_create), null_func, //129 + bind_func(sys_rwlock_create), //120 (0x078) + bind_func(sys_rwlock_destroy), //121 (0x079) + bind_func(sys_rwlock_rlock), //122 (0x07A) + bind_func(sys_rwlock_tryrlock), //123 (0x07B) + bind_func(sys_rwlock_runlock), //124 (0x07C) + bind_func(sys_rwlock_wlock), //125 (0x07D) + bind_func(sys_rwlock_trywlock), //126 (0x07E) + bind_func(sys_rwlock_wunlock), //127 (0x07F) + bind_func(sys_event_queue_create), //128 (0x080) + null_func, //129 (0x081) bind_func(sys_event_queue_receive), null_func, null_func, null_func, bind_func(sys_event_port_create), //134 null_func, bind_func(sys_event_port_connect_local), null_func, bind_func(sys_event_port_send), null_func, //139 - null_func, null_func, null_func, null_func, null_func, //144 + null_func, bind_func(sys_timer_usleep), bind_func(sys_timer_sleep), null_func, bind_func(sys_time_get_timezone), //144 bind_func(sys_time_get_current_time), bind_func(sys_time_get_system_time), bind_func(sys_time_get_timebase_frequency), null_func, null_func, //149 null_func, null_func, null_func, null_func, null_func, //154 null_func, bind_func(sys_spu_image_open), null_func, null_func, null_func, //159 @@ -141,9 +193,21 @@ static func_caller* sc_table[1024] = null_func, null_func, null_func, null_func, null_func, //654 null_func, null_func, null_func, null_func, null_func, //659 null_func, null_func, null_func, null_func, null_func, //664 - null_func, null_func, null_func, null_func, null_func, //669 - null_func, null_func, null_func, null_func, null_func, //674 - null_func, null_func, null_func, null_func, null_func, //679 + null_func, //665 (0x299) + bind_func(sys_rsx_device_open), //666 (0x29A) + bind_func(sys_rsx_device_close), //667 (0x29B) + bind_func(sys_rsx_memory_allocate), //668 (0x29C) + bind_func(sys_rsx_memory_free), //669 (0x29D) + bind_func(sys_rsx_context_allocate), //670 (0x29E) + bind_func(sys_rsx_context_free), //671 (0x29F) + bind_func(sys_rsx_context_iomap), //672 (0x2A0) + bind_func(sys_rsx_context_iounmap), //673 (0x2A1) + bind_func(sys_rsx_context_attribute), //674 (0x2A2) + bind_func(sys_rsx_device_map), //675 (0x2A3) + bind_func(sys_rsx_device_unmap), //676 (0x2A4) + bind_func(sys_rsx_attribute), //677 (0x2A5) + null_func, //678 (0x2A6) + null_func, //679 (0x2A7) null_func, null_func, null_func, null_func, null_func, //684 null_func, null_func, null_func, null_func, null_func, //689 null_func, null_func, null_func, null_func, null_func, //694 @@ -168,9 +232,21 @@ static func_caller* sc_table[1024] = null_func, null_func, null_func, null_func, null_func, //789 null_func, null_func, null_func, null_func, null_func, //794 null_func, null_func, null_func, null_func, null_func, //799 - null_func, bind_func(cellFsOpen), bind_func(cellFsRead), bind_func(cellFsWrite), bind_func(cellFsClose), //804 - bind_func(cellFsOpendir), bind_func(cellFsReaddir), bind_func(cellFsClosedir), null_func, bind_func(cellFsFstat), //809 - null_func, bind_func(cellFsMkdir), bind_func(cellFsRename), bind_func(cellFsRmdir), null_func, //814 + null_func, //800 (0x320) + bind_func(cellFsOpen), //801 (0x321) + bind_func(cellFsRead), //802 (0x322) + bind_func(cellFsWrite), //803 (0x323) + bind_func(cellFsClose), //804 (0x324) + bind_func(cellFsOpendir), //805 (0x325) + bind_func(cellFsReaddir), //806 (0x326) + bind_func(cellFsClosedir), //807 (0x327) + bind_func(cellFsStat), //808 (0x328) + bind_func(cellFsFstat), //809 (0x329) + null_func, //810 (0x32A) + bind_func(cellFsMkdir), //811 (0x32B) + bind_func(cellFsRename), //812 (0x32C) + bind_func(cellFsRmdir), //813 (0x32D) + null_func, //814 (0x32E) null_func, null_func, null_func, bind_func(cellFsLseek), null_func, //819 null_func, null_func, null_func, null_func, null_func, //824 null_func, null_func, null_func, null_func, null_func, //829 @@ -236,13 +312,6 @@ void default_syscall() case 23: RESULT(lv2ProcessWaitForChild2(CPU)); return; case 25: RESULT(lv2ProcessGetSdkVersion(CPU)); return; */ - //timer - case 141: - case 142: - std::this_thread::sleep_for(std::chrono::nanoseconds(SC_ARGS_1)); - RESULT(0); - return; - //tty case 988: ConLog.Warning("SysCall 988! r3: 0x%llx, r4: 0x%llx, pc: 0x%llx", @@ -267,14 +336,6 @@ void default_syscall() return; } -SysCalls::SysCalls(PPUThread& cpu) : CPU(cpu) -{ -} - -SysCalls::~SysCalls() -{ -} - void SysCalls::DoSyscall(u32 code) { if(code < 1024) @@ -291,5 +352,6 @@ void SysCalls::DoSyscall(u32 code) //return 0; //TODO: remove this + declCPU(); RESULT(DoFunc(code)); } \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/SysCalls.h b/rpcs3/Emu/SysCalls/SysCalls.h index df23bcdf29..7408a91458 100644 --- a/rpcs3/Emu/SysCalls/SysCalls.h +++ b/rpcs3/Emu/SysCalls/SysCalls.h @@ -1,6 +1,8 @@ #pragma once #include "ErrorCodes.h" - +#include "lv2/SC_FileSystem.h" +#include "lv2/SC_Timer.h" +#include "lv2/SC_Rwlock.h" //#define SYSCALLS_DEBUG #define declCPU PPUThread& CPU = GetCurrentPPUThread @@ -109,7 +111,12 @@ public: //process extern int sys_process_getpid(); +extern int sys_process_getppid(); +extern int sys_process_get_number_of_object(u32 object, mem32_t nump); +extern int sys_process_get_id(u32 object, mem8_ptr_t buffer, u32 size, mem32_t set_size); +extern int sys_process_get_paramsfo(mem8_ptr_t buffer); extern int sys_process_exit(int errorcode); +extern int sys_process_is_stack(u32 addr); //TODO: Is this a lv2 SysCall? If so, where is its number? extern int sys_game_process_exitspawn(u32 path_addr, u32 argv_addr, u32 envp_addr, u32 data, u32 data_size, int prio, u64 flags ); @@ -176,14 +183,14 @@ extern int sys_mmapper_map_memory(u32 start_addr, u32 mem_id, u64 flags); //cellFs extern int cellFsOpen(u32 path_addr, int flags, mem32_t fd, mem32_t arg, u64 size); -extern int cellFsRead(u32 fd, u32 buf_addr, u64 nbytes, mem64_t nread_addr); -extern int cellFsWrite(u32 fd, u32 buf_addr, u64 nbytes, mem64_t nwrite_addr); +extern int cellFsRead(u32 fd, u32 buf_addr, u64 nbytes, mem64_t nread); +extern int cellFsWrite(u32 fd, u32 buf_addr, u64 nbytes, mem64_t nwrite); extern int cellFsClose(u32 fd); extern int cellFsOpendir(u32 path_addr, mem32_t fd); extern int cellFsReaddir(u32 fd, u32 dir_addr, mem64_t nread); extern int cellFsClosedir(u32 fd); -extern int cellFsStat(u32 path_addr, mem_class_t sb); -extern int cellFsFstat(u32 fd, mem_class_t sb); +extern int cellFsStat(u32 path_addr, mem_struct_ptr_t sb); +extern int cellFsFstat(u32 fd, mem_struct_ptr_t sb); extern int cellFsMkdir(u32 path_addr, u32 mode); extern int cellFsRename(u32 from_addr, u32 to_addr); extern int cellFsRmdir(u32 path_addr); @@ -272,52 +279,93 @@ extern int sys_spu_thread_read_ls(u32 id, u32 address, u32 value_addr, u32 type) extern int sys_spu_thread_write_spu_mb(u32 id, u32 value); //sys_time +extern int sys_time_get_timezone(mem32_t timezone, mem32_t summertime); extern int sys_time_get_current_time(u32 sec_addr, u32 nsec_addr); extern s64 sys_time_get_system_time(); extern u64 sys_time_get_timebase_frequency(); +//sys_timer +extern int sys_timer_create(mem32_t timer_id); +extern int sys_timer_destroy(u32 timer_id); +extern int sys_timer_get_information(u32 timer_id, mem_struct_ptr_t info); +extern int sys_timer_start(u32 timer_id, s64 basetime, u64 period); +extern int sys_timer_stop(u32 timer_id); +extern int sys_timer_connect_event_queue(u32 timer_id, u32 queue_id, u64 name, u64 data1, u64 data2); +extern int sys_timer_disconnect_event_queue(u32 timer_id); +extern int sys_timer_sleep(u32 sleep_time); +extern int sys_timer_usleep(u64 sleep_time); + +//sys_trace +extern int sys_trace_create(); +extern int sys_trace_start(); +extern int sys_trace_stop(); +extern int sys_trace_update_top_index(); +extern int sys_trace_destroy(); +extern int sys_trace_drain(); +extern int sys_trace_attach_process(); +extern int sys_trace_allocate_buffer(); +extern int sys_trace_free_buffer(); +extern int sys_trace_create2(); + +//sys_rwlock +extern int sys_rwlock_create(mem32_t rw_lock_id, mem_struct_ptr_t attr); +extern int sys_rwlock_destroy(u32 rw_lock_id); +extern int sys_rwlock_rlock(u32 rw_lock_id, u64 timeout); +extern int sys_rwlock_tryrlock(u32 rw_lock_id); +extern int sys_rwlock_runlock(u32 rw_lock_id); +extern int sys_rwlock_wlock(u32 rw_lock_id, u64 timeout); +extern int sys_rwlock_trywlock(u32 rw_lock_id); +extern int sys_rwlock_wunlock(u32 rw_lock_id); + +//sys_rsx +extern int sys_rsx_device_open(); +extern int sys_rsx_device_close(); +extern int sys_rsx_memory_allocate(); +extern int sys_rsx_memory_free(); +extern int sys_rsx_context_allocate(); +extern int sys_rsx_context_free(); +extern int sys_rsx_context_iomap(); +extern int sys_rsx_context_iounmap(); +extern int sys_rsx_context_attribute(s32 context_id, u64 a2, u64 a3, u64 a4, u64 a5, u64 a6); +extern int sys_rsx_device_map(mem32_t a1, mem32_t a2, u32 a3); +extern int sys_rsx_device_unmap(); +extern int sys_rsx_attribute(); + #define UNIMPLEMENTED_FUNC(module) module.Error("Unimplemented function: "__FUNCTION__) -#define SC_ARGS_1 CPU.GPR[3] -#define SC_ARGS_2 SC_ARGS_1,CPU.GPR[4] -#define SC_ARGS_3 SC_ARGS_2,CPU.GPR[5] -#define SC_ARGS_4 SC_ARGS_3,CPU.GPR[6] -#define SC_ARGS_5 SC_ARGS_4,CPU.GPR[7] -#define SC_ARGS_6 SC_ARGS_5,CPU.GPR[8] -#define SC_ARGS_7 SC_ARGS_6,CPU.GPR[9] -#define SC_ARGS_8 SC_ARGS_7,CPU.GPR[10] -#define SC_ARGS_9 SC_ARGS_8,CPU.GPR[11] -#define SC_ARGS_10 SC_ARGS_9,CPU.GPR[12] -#define SC_ARGS_11 SC_ARGS_10,CPU.GPR[13] -#define SC_ARGS_12 SC_ARGS_11,CPU.GPR[14] +#define SC_ARG_0 CPU.GPR[3] +#define SC_ARG_1 CPU.GPR[4] +#define SC_ARG_2 CPU.GPR[5] +#define SC_ARG_3 CPU.GPR[6] +#define SC_ARG_4 CPU.GPR[7] +#define SC_ARG_5 CPU.GPR[8] +#define SC_ARG_6 CPU.GPR[9] +#define SC_ARG_7 CPU.GPR[10] +#define SC_ARG_8 CPU.GPR[11] +#define SC_ARG_9 CPU.GPR[12] +#define SC_ARG_10 CPU.GPR[13] +#define SC_ARG_11 CPU.GPR[14] + +#define SC_ARGS_1 SC_ARG_0 +#define SC_ARGS_2 SC_ARGS_1,SC_ARG_1 +#define SC_ARGS_3 SC_ARGS_2,SC_ARG_2 +#define SC_ARGS_4 SC_ARGS_3,SC_ARG_3 +#define SC_ARGS_5 SC_ARGS_4,SC_ARG_4 +#define SC_ARGS_6 SC_ARGS_5,SC_ARG_5 +#define SC_ARGS_7 SC_ARGS_6,SC_ARG_6 +#define SC_ARGS_8 SC_ARGS_7,SC_ARG_7 +#define SC_ARGS_9 SC_ARGS_8,SC_ARG_8 +#define SC_ARGS_10 SC_ARGS_9,SC_ARG_9 +#define SC_ARGS_11 SC_ARGS_10,SC_ARG_10 +#define SC_ARGS_12 SC_ARGS_11,SC_ARG_11 extern bool dump_enable; -class PPUThread; class SysCalls { - PPUThread& CPU; - public: - //process - int lv2ProcessGetPid(PPUThread& CPU); - int lv2ProcessWaitForChild(PPUThread& CPU); - int lv2ProcessGetStatus(PPUThread& CPU); - int lv2ProcessDetachChild(PPUThread& CPU); - int lv2ProcessGetNumberOfObject(PPUThread& CPU); - int lv2ProcessGetId(PPUThread& CPU); - int lv2ProcessGetPpid(PPUThread& CPU); - int lv2ProcessKill(PPUThread& CPU); - int lv2ProcessWaitForChild2(PPUThread& CPU); - int lv2ProcessGetSdkVersion(PPUThread& CPU); - -protected: - SysCalls(PPUThread& cpu); - ~SysCalls(); - -public: - void DoSyscall(u32 code); - s64 DoFunc(const u32 id); + static void DoSyscall(u32 code); + static s64 DoFunc(const u32 id); }; //extern SysCalls SysCallsManager; \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Event.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Event.cpp index 8aa6f3fa00..28044cdc06 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_Event.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_Event.cpp @@ -47,7 +47,7 @@ int sys_event_queue_receive(u32 equeue_id, u32 event_addr, u32 timeout) int result; auto queue_receive = [&](int status) -> bool { - if(status == PPCThread_Stopped) + if(status == CPUThread_Stopped) { result = CELL_ECANCELED; return false; @@ -59,11 +59,11 @@ int sys_event_queue_receive(u32 equeue_id, u32 event_addr, u32 timeout) if(!equeue->ports[i]->has_data && equeue->ports[i]->thread) { SPUThread* thr = (SPUThread*)equeue->ports[i]->thread; - if(thr->SPU_OutIntr_Mbox.GetCount()) + if(thr->SPU.OutIntr_Mbox.GetCount()) { u32 val; - thr->SPU_OutIntr_Mbox.Pop(val); - if(!thr->mfc.SPU_Out_MBox.Pop(val)) val = 0; + thr->SPU.OutIntr_Mbox.Pop(val); + if(!thr->SPU.Out_MBox.Pop(val)) val = 0; equeue->ports[i]->data1 = val; equeue->ports[i]->data2 = 0; equeue->ports[i]->data3 = 0; diff --git a/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.cpp b/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.cpp index d4e78008da..1fc163f281 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.cpp @@ -1,87 +1,7 @@ #include "stdafx.h" +#include "SC_FileSystem.h" #include "Emu/SysCalls/SysCalls.h" -enum CellFsOflag -{ - LV2_O_RDONLY = 000000, - LV2_O_WRONLY = 000001, - LV2_O_RDWR = 000002, - LV2_O_ACCMODE = 000003, - LV2_O_CREAT = 000100, - LV2_O_EXCL = 000200, - LV2_O_TRUNC = 001000, - LV2_O_APPEND = 002000, - LV2_O_MSELF = 010000, -}; - -#define CELL_FS_TYPE_UNKNOWN 0 - -enum CellFsSeek -{ - LV2_SEEK_SET, - LV2_SEEK_CUR, - LV2_SEEK_END, -}; - -enum CellFsLength -{ - LV2_MAX_FS_PATH_LENGTH = 1024, - LV2_MAX_FS_FILE_NAME_LENGTH = 255, - LV2_MAX_FS_MP_LENGTH = 31, -}; - -enum -{ - CELL_FS_S_IFDIR = 0040000, //directory - CELL_FS_S_IFREG = 0100000, //regular - CELL_FS_S_IFLNK = 0120000, //symbolic link - CELL_FS_S_IFWHT = 0160000, //unknown - - CELL_FS_S_IRUSR = 0000400, //R for owner - CELL_FS_S_IWUSR = 0000200, //W for owner - CELL_FS_S_IXUSR = 0000100, //X for owner - - CELL_FS_S_IRGRP = 0000040, //R for group - CELL_FS_S_IWGRP = 0000020, //W for group - CELL_FS_S_IXGRP = 0000010, //X for group - - CELL_FS_S_IROTH = 0000004, //R for other - CELL_FS_S_IWOTH = 0000002, //W for other - CELL_FS_S_IXOTH = 0000001, //X for other -}; - -struct CellFsStat -{ - u32 st_mode; - s32 st_uid; - s32 st_gid; - u64 st_atime; - u64 st_mtime; - u64 st_ctime; - u64 st_size; - u64 st_blksize; -}; - -struct CellFsUtimbuf -{ - u64 actime; - u64 modtime; -}; - -struct CellFsDirent -{ - u8 d_type; - u8 d_namlen; - char d_name[LV2_MAX_FS_FILE_NAME_LENGTH + 1]; -}; - -enum FsDirentType -{ - CELL_FS_TYPE_DIRECTORY = 1, - CELL_FS_TYPE_REGULAR = 2, - CELL_FS_TYPE_SYMLINK = 3, -}; - extern Module sys_fs; int cellFsOpen(u32 path_addr, int flags, mem32_t fd, mem32_t arg, u64 size) @@ -94,9 +14,9 @@ int cellFsOpen(u32 path_addr, int flags, mem32_t fd, mem32_t arg, u64 size) //ConLog.Warning("path: %s [%s]", ppath, path); s32 _oflags = flags; - if(flags & LV2_O_CREAT) + if(flags & CELL_O_CREAT) { - _oflags &= ~LV2_O_CREAT; + _oflags &= ~CELL_O_CREAT; /* //create path for(uint p=1;p sb) { const wxString& path = Memory.ReadString(path_addr); sys_fs.Log("cellFsFstat(path: %s, sb_addr: 0x%x)", path, sb.GetAddr()); + sb->st_mode = + CELL_FS_S_IRUSR | CELL_FS_S_IWUSR | CELL_FS_S_IXUSR | + CELL_FS_S_IRGRP | CELL_FS_S_IWGRP | CELL_FS_S_IXGRP | + CELL_FS_S_IROTH | CELL_FS_S_IWOTH | CELL_FS_S_IXOTH; + + sb->st_uid = 0; + sb->st_gid = 0; + sb->st_atime = 0; //TODO + sb->st_mtime = 0; //TODO + sb->st_ctime = 0; //TODO + sb->st_blksize = 4096; + // Check if path is a mount point. (TODO: Add information in sb_addr) for(u32 i=0; ist_mode |= CELL_FS_S_IFDIR; return CELL_OK; } } - auto f = Emu.OpenFile(path); + vfsFile f(path); - if(!f->IsOpened()) + if(!f.IsOpened()) { sys_fs.Warning("cellFsFstat: '%s' not found.", path); return CELL_ENOENT; } - CellFsStat stat; - stat.st_mode = - CELL_FS_S_IRUSR | CELL_FS_S_IWUSR | CELL_FS_S_IXUSR | - CELL_FS_S_IRGRP | CELL_FS_S_IWGRP | CELL_FS_S_IXGRP | - CELL_FS_S_IROTH | CELL_FS_S_IWOTH | CELL_FS_S_IXOTH; - - stat.st_mode |= CELL_FS_S_IFREG; //TODO: dir CELL_FS_S_IFDIR - stat.st_uid = 0; - stat.st_gid = 0; - stat.st_atime = 0; //TODO - stat.st_mtime = 0; //TODO - stat.st_ctime = 0; //TODO - stat.st_size = f->GetSize(); - stat.st_blksize = 4096; - - sb += stat.st_mode; - sb += stat.st_uid; - sb += stat.st_gid; - sb += stat.st_atime; - sb += stat.st_mtime; - sb += stat.st_ctime; - sb += stat.st_size; - sb += stat.st_blksize; + sb->st_mode |= CELL_FS_S_IFREG; //TODO: dir CELL_FS_S_IFDIR + sb->st_size = f.GetSize(); return CELL_OK; } -int cellFsFstat(u32 fd, mem_class_t sb) +int cellFsFstat(u32 fd, mem_struct_ptr_t sb) { sys_fs.Log("cellFsFstat(fd: %d, sb_addr: 0x%x)", fd, sb.GetAddr()); ID id; if(!sys_fs.CheckId(fd, id)) return CELL_ESRCH; vfsStream& file = *(vfsStream*)id.m_data; - CellFsStat stat; - stat.st_mode = + sb->st_mode = CELL_FS_S_IRUSR | CELL_FS_S_IWUSR | CELL_FS_S_IXUSR | CELL_FS_S_IRGRP | CELL_FS_S_IWGRP | CELL_FS_S_IXGRP | CELL_FS_S_IROTH | CELL_FS_S_IWOTH | CELL_FS_S_IXOTH; - stat.st_mode |= CELL_FS_S_IFREG; //TODO: dir CELL_FS_S_IFDIR - stat.st_uid = 0; - stat.st_gid = 0; - stat.st_atime = 0; //TODO - stat.st_mtime = 0; //TODO - stat.st_ctime = 0; //TODO - stat.st_size = file.GetSize(); - stat.st_blksize = 4096; - - sb += stat.st_mode; - sb += stat.st_uid; - sb += stat.st_gid; - sb += stat.st_atime; - sb += stat.st_mtime; - sb += stat.st_ctime; - sb += stat.st_size; - sb += stat.st_blksize; + sb->st_mode |= CELL_FS_S_IFREG; //TODO: dir CELL_FS_S_IFDIR + sb->st_uid = 0; + sb->st_gid = 0; + sb->st_atime = 0; //TODO + sb->st_mtime = 0; //TODO + sb->st_ctime = 0; //TODO + sb->st_size = file.GetSize(); + sb->st_blksize = 4096; return CELL_OK; } @@ -379,9 +293,9 @@ int cellFsLseek(u32 fd, s64 offset, u32 whence, mem64_t pos) sys_fs.Log("cellFsLseek(fd: %d, offset: 0x%llx, whence: %d, pos_addr: 0x%x)", fd, offset, whence, pos.GetAddr()); switch(whence) { - case LV2_SEEK_SET: seek_mode = vfsSeekSet; break; - case LV2_SEEK_CUR: seek_mode = vfsSeekCur; break; - case LV2_SEEK_END: seek_mode = vfsSeekEnd; break; + case CELL_SEEK_SET: seek_mode = vfsSeekSet; break; + case CELL_SEEK_CUR: seek_mode = vfsSeekCur; break; + case CELL_SEEK_END: seek_mode = vfsSeekEnd; break; default: sys_fs.Error(fd, "Unknown seek whence! (%d)", whence); return CELL_EINVAL; @@ -401,19 +315,13 @@ int cellFsFtruncate(u32 fd, u64 size) vfsStream& file = *(vfsStream*)id.m_data; u64 initialSize = file.GetSize(); - if (initialSize < size) // Is there any better way to fill the remaining bytes with 0, without allocating huge buffers in memory, or writing such a spaghetti code? + if (initialSize < size) { u64 last_pos = file.Tell(); file.Seek(0, vfsSeekEnd); - char* nullblock = (char*)calloc(4096, sizeof(char)); - for(u64 i = (size-initialSize)/4096; i > 0; i--){ - file.Write(nullblock, 4096); - } - free(nullblock); - char nullbyte = 0; - for(u64 i = (size-initialSize)%4096; i > 0; i--){ - file.Write(&nullbyte, 1); - } + static const char nullbyte = 0; + file.Seek(size-initialSize-1, vfsSeekCur); + file.Write(&nullbyte, sizeof(char)); file.Seek(last_pos, vfsSeekSet); } @@ -430,29 +338,22 @@ int cellFsTruncate(u32 path_addr, u64 size) const wxString& path = Memory.ReadString(path_addr); sys_fs.Log("cellFsTruncate(path: %s, size: %lld)", path, size); - vfsStream* f = Emu.GetVFS().Open(path, vfsRead); - if(!f || !f->IsOpened()) + vfsFile f(path, vfsReadWrite); + if(!f.IsOpened()) { sys_fs.Warning("cellFsTruncate: '%s' not found.", path); - Emu.GetVFS().Close(f); return CELL_ENOENT; } - u64 initialSize = f->GetSize(); + u64 initialSize = f.GetSize(); - if (initialSize < size) // Is there any better way to fill the remaining bytes with 0, without allocating huge buffers in memory, or writing such a spaghetti code? + if (initialSize < size) { - u64 last_pos = f->Tell(); - f->Seek(0, vfsSeekEnd); - char* nullblock = (char*)calloc(4096, sizeof(char)); - for(u64 i = (size-initialSize)/4096; i > 0; i--){ - f->Write(nullblock, 4096); - } - free(nullblock); - char nullbyte = 0; - for(u64 i = (size-initialSize)%4096; i > 0; i--){ - f->Write(&nullbyte, 1); - } - f->Seek(last_pos, vfsSeekSet); + u64 last_pos = f.Tell(); + f.Seek(0, vfsSeekEnd); + static const char nullbyte = 0; + f.Seek(size-initialSize-1, vfsSeekCur); + f.Write(&nullbyte, sizeof(char)); + f.Seek(last_pos, vfsSeekSet); } if (initialSize > size) @@ -460,7 +361,6 @@ int cellFsTruncate(u32 path_addr, u64 size) // (TODO) } - Emu.GetVFS().Close(f); return CELL_OK; } diff --git a/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.h b/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.h new file mode 100644 index 0000000000..b2e515b83f --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_FileSystem.h @@ -0,0 +1,86 @@ +#pragma once + +enum CellFsOflag +{ + CELL_O_RDONLY = 000000, + CELL_O_WRONLY = 000001, + CELL_O_RDWR = 000002, + CELL_O_ACCMODE = 000003, + CELL_O_CREAT = 000100, + CELL_O_EXCL = 000200, + CELL_O_TRUNC = 001000, + CELL_O_APPEND = 002000, + CELL_O_MSELF = 010000, +}; + +static const u32 CELL_FS_TYPE_UNKNOWN = 0; + +enum CellFsSeek +{ + CELL_SEEK_SET, + CELL_SEEK_CUR, + CELL_SEEK_END, +}; + +enum CellFsLength +{ + CELL_MAX_FS_PATH_LENGTH = 1024, + CELL_MAX_FS_FILE_NAME_LENGTH = 255, + CELL_MAX_FS_MP_LENGTH = 31, +}; + +enum +{ + CELL_FS_S_IFDIR = 0040000, //directory + CELL_FS_S_IFREG = 0100000, //regular + CELL_FS_S_IFLNK = 0120000, //symbolic link + CELL_FS_S_IFWHT = 0160000, //unknown + + CELL_FS_S_IRUSR = 0000400, //R for owner + CELL_FS_S_IWUSR = 0000200, //W for owner + CELL_FS_S_IXUSR = 0000100, //X for owner + + CELL_FS_S_IRGRP = 0000040, //R for group + CELL_FS_S_IWGRP = 0000020, //W for group + CELL_FS_S_IXGRP = 0000010, //X for group + + CELL_FS_S_IROTH = 0000004, //R for other + CELL_FS_S_IWOTH = 0000002, //W for other + CELL_FS_S_IXOTH = 0000001, //X for other +}; + +enum FsDirentType +{ + CELL_FS_TYPE_DIRECTORY = 1, + CELL_FS_TYPE_REGULAR = 2, + CELL_FS_TYPE_SYMLINK = 3, +}; + +#pragma pack(4) + +struct CellFsStat +{ + be_t st_mode; + be_t st_uid; + be_t st_gid; + be_t st_atime; + be_t st_mtime; + be_t st_ctime; + be_t st_size; + be_t st_blksize; +}; + +struct CellFsUtimbuf +{ + be_t actime; + be_t modtime; +}; + +struct CellFsDirent +{ + u8 d_type; + u8 d_namlen; + char d_name[CELL_MAX_FS_FILE_NAME_LENGTH + 1]; +}; + +#pragma pack() \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Lwmutex.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Lwmutex.cpp index 8177530f34..f483e90e00 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_Lwmutex.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_Lwmutex.cpp @@ -109,7 +109,7 @@ int sys_lwmutex_unlock(u64 lwmutex_addr) if(lmtx.lock_var.info.owner = lmtx.lock_var.info.waiter) { lmtx.lock_var.info.waiter = 0; - PPCThread* thr = Emu.GetCPU().GetThread(lmtx.lock_var.info.owner); + CPUThread* thr = Emu.GetCPU().GetThread(lmtx.lock_var.info.owner); if(thr) { thr->Wait(false); diff --git a/rpcs3/Emu/SysCalls/lv2/SC_PPU_Thread.cpp b/rpcs3/Emu/SysCalls/lv2/SC_PPU_Thread.cpp index fddb80a40e..a9c712c608 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_PPU_Thread.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_PPU_Thread.cpp @@ -38,7 +38,7 @@ int sys_ppu_thread_join(u32 thread_id, u32 vptr_addr) { sysPrxForUser.Warning("sys_ppu_thread_join(thread_id=%d, vptr_addr=0x%x)", thread_id, vptr_addr); - PPCThread* thr = Emu.GetCPU().GetThread(thread_id); + CPUThread* thr = Emu.GetCPU().GetThread(thread_id); if(!thr) return CELL_ESRCH; GetCurrentPPUThread().Wait(*thr); @@ -49,6 +49,13 @@ int sys_ppu_thread_detach(u32 thread_id) { sysPrxForUser.Error("sys_ppu_thread_detach(thread_id=%d)", thread_id); + CPUThread* thr = Emu.GetCPU().GetThread(thread_id); + if(!thr) return CELL_ESRCH; + + if(!thr->IsJoinable()) + return CELL_EINVAL; + thr->SetJoinable(false); + return CELL_OK; } @@ -62,7 +69,7 @@ int sys_ppu_thread_set_priority(u32 thread_id, int prio) { sysPrxForUser.Warning("sys_ppu_thread_set_priority(thread_id=%d, prio=%d)", thread_id, prio); - PPCThread* thr = Emu.GetCPU().GetThread(thread_id); + CPUThread* thr = Emu.GetCPU().GetThread(thread_id); if(!thr) return CELL_ESRCH; thr->SetPrio(prio); @@ -74,7 +81,7 @@ int sys_ppu_thread_get_priority(u32 thread_id, u32 prio_addr) { sysPrxForUser.Log("sys_ppu_thread_get_priority(thread_id=%d, prio_addr=0x%x)", thread_id, prio_addr); - PPCThread* thr = Emu.GetCPU().GetThread(thread_id); + CPUThread* thr = Emu.GetCPU().GetThread(thread_id); if(!thr) return CELL_ESRCH; if(!Memory.IsGoodAddr(prio_addr)) return CELL_EFAULT; @@ -101,7 +108,7 @@ int sys_ppu_thread_stop(u32 thread_id) { sysPrxForUser.Warning("sys_ppu_thread_stop(thread_id=%d)", thread_id); - PPCThread* thr = Emu.GetCPU().GetThread(thread_id); + CPUThread* thr = Emu.GetCPU().GetThread(thread_id); if(!thr) return CELL_ESRCH; thr->Stop(); @@ -113,7 +120,7 @@ int sys_ppu_thread_restart(u32 thread_id) { sysPrxForUser.Warning("sys_ppu_thread_restart(thread_id=%d)", thread_id); - PPCThread* thr = Emu.GetCPU().GetThread(thread_id); + CPUThread* thr = Emu.GetCPU().GetThread(thread_id); if(!thr) return CELL_ESRCH; thr->Stop(); @@ -132,13 +139,13 @@ int sys_ppu_thread_create(u32 thread_id_addr, u32 entry, u32 arg, int prio, u32 return CELL_EFAULT; } - PPCThread& new_thread = Emu.GetCPU().AddThread(PPC_THREAD_PPU); + CPUThread& new_thread = Emu.GetCPU().AddThread(CPU_THREAD_PPU); Memory.Write32(thread_id_addr, new_thread.GetId()); new_thread.SetEntry(entry); new_thread.SetArg(0, arg); new_thread.SetPrio(prio); - new_thread.stack_size = stacksize; + new_thread.SetStackSize(stacksize); //new_thread.flags = flags; new_thread.SetName(Memory.ReadString(threadname_addr)); new_thread.Run(); @@ -155,7 +162,7 @@ void sys_ppu_thread_once(u32 once_ctrl_addr, u32 entry) { Memory.Write32(once_ctrl_addr, SYS_PPU_THREAD_DONE_INIT); - PPCThread& new_thread = Emu.GetCPU().AddThread(PPC_THREAD_PPU); + CPUThread& new_thread = Emu.GetCPU().AddThread(CPU_THREAD_PPU); new_thread.SetEntry(entry); new_thread.Run(); new_thread.Exec(); diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Process.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Process.cpp index 14a1b70868..daea57358c 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_Process.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_Process.cpp @@ -3,14 +3,43 @@ SysCallBase sc_p("Process"); +//Process Local Object +enum +{ + SYS_MEM_OBJECT = (0x08UL), + SYS_MUTEX_OBJECT = (0x85UL), + SYS_COND_OBJECT = (0x86UL), + SYS_RWLOCK_OBJECT = (0x88UL), + SYS_INTR_TAG_OBJECT = (0x0AUL), + SYS_INTR_SERVICE_HANDLE_OBJECT = (0x0BUL), + SYS_EVENT_QUEUE_OBJECT = (0x8DUL), + SYS_EVENT_PORT_OBJECT = (0x0EUL), + SYS_TRACE_OBJECT = (0x21UL), + SYS_SPUIMAGE_OBJECT = (0x22UL), + SYS_PRX_OBJECT = (0x23UL), + SYS_SPUPORT_OBJECT = (0x24UL), + SYS_LWMUTEX_OBJECT = (0x95UL), + SYS_TIMER_OBJECT = (0x11UL), + SYS_SEMAPHORE_OBJECT = (0x96UL), + SYS_FS_FD_OBJECT = (0x73UL), + SYS_LWCOND_OBJECT = (0x97UL), + SYS_EVENT_FLAG_OBJECT = (0x98UL), +}; + int sys_process_getpid() { return 1; } +int sys_process_getppid() +{ + sc_p.Warning("TODO: sys_process_getppid() returns 0"); + return 0; +} + int sys_process_exit(int errorcode) { - ConLog.Warning("sys_process_exit(%d)", errorcode); + sc_p.Warning("sys_process_exit(%d)", errorcode); #ifdef _DEBUG Emu.Pause(); #else @@ -33,6 +62,199 @@ int sys_game_process_exitspawn( u32 path_addr, u32 argv_addr, u32 envp_addr, return CELL_OK; } +int sys_process_get_number_of_object(u32 object, mem32_t nump) +{ + sc_p.Warning("TODO: sys_process_get_number_of_object(object=%d, nump_addr=0x%x)", + object, nump.GetAddr()); + + switch(object) + { + case SYS_MEM_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_MUTEX_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_COND_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_RWLOCK_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_INTR_TAG_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_INTR_SERVICE_HANDLE_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_EVENT_QUEUE_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_EVENT_PORT_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_TRACE_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_SPUIMAGE_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_PRX_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_SPUPORT_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_LWMUTEX_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_TIMER_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_SEMAPHORE_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_FS_FD_OBJECT: + nump = 0; + return CELL_OK; + + case SYS_LWCOND_OBJECT: + nump = 0; + return CELL_OK; + + default: + return CELL_EINVAL; + } +} + +int sys_process_get_id(u32 object, mem8_ptr_t buffer, u32 size, mem32_t set_size) +{ + sc_p.Warning("TODO: sys_process_get_id(object=%d, buffer_addr=0x%x, size=%d, set_size_addr=0x%x)", + object, buffer.GetAddr(), size, set_size.GetAddr()); + + switch(object) + { + case SYS_MEM_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_MUTEX_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_COND_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_RWLOCK_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_INTR_TAG_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_INTR_SERVICE_HANDLE_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_EVENT_QUEUE_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_EVENT_PORT_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_TRACE_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_SPUIMAGE_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_PRX_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_SPUPORT_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_LWMUTEX_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_TIMER_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_SEMAPHORE_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_FS_FD_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_LWCOND_OBJECT: + set_size = 0; + return CELL_OK; + + case SYS_EVENT_FLAG_OBJECT: + set_size = 0; + return CELL_OK; + + default: + return CELL_EINVAL; + } +} + +int sys_process_get_paramsfo(mem8_ptr_t buffer) +{ + sc_p.Warning("TODO: sys_process_get_paramsfo(buffer_addr=0x%x) returns CELL_ENOENT", buffer.GetAddr()); + return CELL_ENOENT; + + /*//Before uncommenting this code, we should check if it is actually working. + MemoryAllocator> fd; + char filePath [] = "/app_home/../PARAM.SFO"; + if (!cellFsOpen(Memory.RealToVirtualAddr(filePath), 0, fd, NULL, 0)) + return CELL_ENOENT; + + MemoryAllocator> pos, nread; + cellFsLseek(fd, 0, CELL_SEEK_SET, pos); //TODO: Move to the appropriate offset (probably 0x3F7) + cellFsRead(fd, buffer.GetAddr(), 40, nread); //WARNING: If offset==0x3F7: The file will end before the buffer (40 bytes) is filled! + cellFsClose(fd); + + return CELL_OK;*/ +} + +int sys_process_is_stack(u32 p) +{ + PPCThread* CPU = GetCurrentPPCThread(); + if (p >= CPU->GetStackAddr() && p <= CPU->GetStackAddr() + CPU->GetStackSize()) + return 1; + + return 0; +} + +/* int SysCalls::lv2ProcessWaitForChild(PPUThread& CPU) { ConLog.Warning("lv2ProcessWaitForChild"); @@ -73,14 +295,6 @@ int SysCalls::lv2ProcessKill(PPUThread& CPU) CPU.Close(); return CELL_OK; } -/* -int SysCalls::lv2ProcessExit(PPUThread& CPU) -{ - ConLog.Warning("lv2ProcessExit(%lld)", CPU.GPR[3]); - Emu.Pause(); - return CELL_OK; -} -*/ int SysCalls::lv2ProcessWaitForChild2(PPUThread& CPU) { ConLog.Warning("lv2ProcessWaitForChild2[r3: 0x%llx, r4: 0x%llx, r5: 0x%llx, r6: 0x%llx, r7: 0x%llx, r8: 0x%llx]", @@ -92,4 +306,5 @@ int SysCalls::lv2ProcessGetSdkVersion(PPUThread& CPU) ConLog.Warning("lv2ProcessGetSdkVersion[r3: 0x%llx, r4: 0x%llx]", CPU.GPR[3], CPU.GPR[4]); CPU.GPR[4] = 0x360001; //TODO return CELL_OK; -} \ No newline at end of file +} +*/ diff --git a/rpcs3/Emu/SysCalls/lv2/SC_RSX.cpp b/rpcs3/Emu/SysCalls/lv2/SC_RSX.cpp new file mode 100644 index 0000000000..8ede1eaa83 --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_RSX.cpp @@ -0,0 +1,76 @@ +#include "stdafx.h" +#include "Emu/SysCalls/SysCalls.h" + +SysCallBase sys_rsx("sys_rsx"); + +int sys_rsx_device_open() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_device_open()"); + return CELL_OK; +} + +int sys_rsx_device_close() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_device_close()"); + return CELL_OK; +} + +int sys_rsx_memory_allocate() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_memory_allocate()"); + return CELL_OK; +} + +int sys_rsx_memory_free() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_memory_free()"); + return CELL_OK; +} + +int sys_rsx_context_allocate() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_context_allocate()"); + return CELL_OK; +} + +int sys_rsx_context_free() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_context_free()"); + return CELL_OK; +} + +int sys_rsx_context_iomap() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_context_iomap()"); + return CELL_OK; +} + +int sys_rsx_context_iounmap() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_context_iounmap()"); + return CELL_OK; +} + +int sys_rsx_context_attribute(s32 context_id, u64 a2, u64 a3, u64 a4, u64 a5, u64 a6) +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_context_attribute(context_id=%d, a2=%llu, a3=%llu, a4=%llu, a5=%llu, a6=%llu)", context_id, a2, a3, a4, a5, a6); + return CELL_OK; +} + +int sys_rsx_device_map(mem32_t a1, mem32_t a2, u32 a3) +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_device_map(a1_addr=0x%x, a2_addr=0x%x, a3=%d)", a1.GetAddr(), a2.GetAddr(), a3); + return CELL_OK; +} + +int sys_rsx_device_unmap() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_device_unmap()"); + return CELL_OK; +} + +int sys_rsx_attribute() +{ + sys_rsx.Warning("Unimplemented function: sys_rsx_attribute()"); + return CELL_OK; +} diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Rwlock.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Rwlock.cpp new file mode 100644 index 0000000000..3af3222627 --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_Rwlock.cpp @@ -0,0 +1,53 @@ +#include "stdafx.h" +#include "SC_Rwlock.h" +#include "Emu/SysCalls/SysCalls.h" + +SysCallBase sys_rwlock("sys_rwlock"); + +int sys_rwlock_create(mem32_t rw_lock_id, mem_struct_ptr_t attr) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_create(rw_lock_id_addr=0x%x, attr_addr=0x%x)", rw_lock_id.GetAddr(), attr.GetAddr()); + return CELL_OK; +} + +int sys_rwlock_destroy(u32 rw_lock_id) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_destroy(rw_lock_id=%d)", rw_lock_id); + return CELL_OK; +} + +int sys_rwlock_rlock(u32 rw_lock_id, u64 timeout) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_rlock(rw_lock_id=%d, timeout=%llu)", rw_lock_id, timeout); + return CELL_OK; +} + +int sys_rwlock_tryrlock(u32 rw_lock_id) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_tryrlock(rw_lock_id=%d)", rw_lock_id); + return CELL_OK; +} + +int sys_rwlock_runlock(u32 rw_lock_id) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_runlock(rw_lock_id=%d)", rw_lock_id); + return CELL_OK; +} + +int sys_rwlock_wlock(u32 rw_lock_id, u64 timeout) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_wlock(rw_lock_id=%d, timeout=%llu)", rw_lock_id, timeout); + return CELL_OK; +} + +int sys_rwlock_trywlock(u32 rw_lock_id) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_trywlock(rw_lock_id=%d)", rw_lock_id); + return CELL_OK; +} + +int sys_rwlock_wunlock(u32 rw_lock_id) +{ + sys_rwlock.Warning("Unimplemented function: sys_rwlock_wunlock(rw_lock_id=%d)", rw_lock_id); + return CELL_OK; +} diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Rwlock.h b/rpcs3/Emu/SysCalls/lv2/SC_Rwlock.h new file mode 100644 index 0000000000..d986b59a98 --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_Rwlock.h @@ -0,0 +1,12 @@ +#pragma once + +struct sys_rwlock_attribute_t +{ + u32 attr_protocol; //sys_protocol_t + u32 attr_pshared; //sys_process_shared_t + u64 key; //sys_ipc_key_t + s32 flags; + u8 name[8]; +}; + +#pragma pack() \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/lv2/SC_SPU_Thread.cpp b/rpcs3/Emu/SysCalls/lv2/SC_SPU_Thread.cpp index 5ecad4f566..faebb1e416 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_SPU_Thread.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_SPU_Thread.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #include "Emu/SysCalls/SysCalls.h" #include "Loader/ELF.h" -#include "Emu/Cell/SPUThread.h" +#include "Emu/Cell/RawSPUThread.h" SysCallBase sc_spu("sys_spu"); @@ -40,12 +40,12 @@ static const u32 g_spu_group_thr_count = 255; struct SpuGroupInfo { - PPCThread* threads[g_spu_group_thr_count]; + CPUThread* threads[g_spu_group_thr_count]; sys_spu_thread_group_attribute& attr; SpuGroupInfo(sys_spu_thread_group_attribute& attr) : attr(attr) { - memset(threads, 0, sizeof(PPCThread*) * g_spu_group_thr_count); + memset(threads, 0, sizeof(CPUThread*) * g_spu_group_thr_count); } }; @@ -150,7 +150,7 @@ int sys_spu_thread_initialize(u32 thread_addr, u32 group, u32 spu_num, u32 img_a ConLog.Write("a4 = 0x%x", a4); ConLog.SkipLn(); - PPCThread& new_thread = Emu.GetCPU().AddThread(PPC_THREAD_SPU); + CPUThread& new_thread = Emu.GetCPU().AddThread(CPU_THREAD_SPU); new_thread.SetOffset(g_spu_offset); new_thread.SetEntry(entry - g_spu_offset); new_thread.SetName(name); @@ -170,9 +170,9 @@ int sys_spu_thread_initialize(u32 thread_addr, u32 group, u32 spu_num, u32 img_a int sys_spu_thread_set_argument(u32 id, u32 arg_addr) { sc_spu.Warning("sys_spu_thread_set_argument(id=0x%x, arg_addr=0x%x)", id, arg_addr); - PPCThread* thr = Emu.GetCPU().GetThread(id); + CPUThread* thr = Emu.GetCPU().GetThread(id); - if(!thr || thr->GetType() == PPC_THREAD_PPU) + if(!thr || (thr->GetType() != CPU_THREAD_SPU && thr->GetType() != CPU_THREAD_RAW_SPU)) { return CELL_ESRCH; } @@ -268,8 +268,8 @@ int sys_raw_spu_create(u32 id_addr, u32 attr_addr) sc_spu.Warning("sys_raw_spu_create(id_addr=0x%x, attr_addr=0x%x)", id_addr, attr_addr); //Emu.GetIdManager().GetNewID("sys_raw_spu", new u32(attr_addr)); - PPCThread& new_thread = Emu.GetCPU().AddThread(PPC_THREAD_RAW_SPU); - Memory.Write32(id_addr, Emu.GetCPU().GetThreadNumById(PPC_THREAD_RAW_SPU, new_thread.GetId())); + CPUThread& new_thread = Emu.GetCPU().AddThread(CPU_THREAD_RAW_SPU); + Memory.Write32(id_addr, ((RawSPUThread&)new_thread).GetIndex()); new_thread.Run(); new_thread.Exec(); @@ -286,10 +286,10 @@ int sys_spu_initialize(u32 max_usable_spu, u32 max_raw_spu) return CELL_EINVAL; } - if(!Memory.InitSpuRawMem(max_raw_spu)) - { - return CELL_ENOMEM; - } + //if(!Memory.InitSpuRawMem(max_raw_spu)) + //{ + // return CELL_ENOMEM; + //} //enable_log = true; //dump_enable = true; @@ -303,9 +303,9 @@ int sys_spu_thread_write_ls(u32 id, u32 address, u64 value, u32 type) sc_spu.Warning("sys_spu_thread_write_ls(id=0x%x, address=0x%x, value=0x%llx, type=0x%x)", id, address, value, type); - PPCThread* thr = Emu.GetCPU().GetThread(id); + CPUThread* thr = Emu.GetCPU().GetThread(id); - if(!thr || thr->GetType() == PPC_THREAD_PPU) + if(!thr || (thr->GetType() != CPU_THREAD_SPU && thr->GetType() != CPU_THREAD_RAW_SPU)) { return CELL_ESRCH; } @@ -321,9 +321,9 @@ int sys_spu_thread_read_ls(u32 id, u32 address, u32 value_addr, u32 type) sc_spu.Warning("sys_spu_thread_read_ls(id=0x%x, address=0x%x, value_addr=0x%x, type=0x%x)", id, address, value_addr, type); - PPCThread* thr = Emu.GetCPU().GetThread(id); + CPUThread* thr = Emu.GetCPU().GetThread(id); - if(!thr || thr->GetType() == PPC_THREAD_PPU) + if(!thr || (thr->GetType() != CPU_THREAD_SPU && thr->GetType() != CPU_THREAD_RAW_SPU)) { return CELL_ESRCH; } @@ -343,14 +343,14 @@ int sys_spu_thread_write_spu_mb(u32 id, u32 value) { sc_spu.Warning("sys_spu_thread_write_spu_mb(id=0x%x, value=0x%x)", id, value); - PPCThread* thr = Emu.GetCPU().GetThread(id); + CPUThread* thr = Emu.GetCPU().GetThread(id); - if(!thr || !thr->GetType() == PPC_THREAD_PPU) + if(!thr || (thr->GetType() != CPU_THREAD_SPU && thr->GetType() != CPU_THREAD_RAW_SPU)) { return CELL_ESRCH; } - if(!(*(SPUThread*)thr).mfc.SPU_In_MBox.Push(value)) + if(!(*(SPUThread*)thr).SPU.In_MBox.Push(value)) { ConLog.Warning("sys_spu_thread_write_spu_mb(id=0x%x, value=0x%x): used all mbox items."); return CELL_EBUSY; //? diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Time.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Time.cpp index 503e177dd3..42c384ac59 100644 --- a/rpcs3/Emu/SysCalls/lv2/SC_Time.cpp +++ b/rpcs3/Emu/SysCalls/lv2/SC_Time.cpp @@ -4,6 +4,17 @@ SysCallBase sys_time("sys_time"); static const u64 timebase_frequency = 79800000; +extern int cellSysutilGetSystemParamInt(int id, mem32_t value); + +int sys_time_get_timezone(mem32_t timezone, mem32_t summertime) +{ + int ret; + ret = cellSysutilGetSystemParamInt(0x0116, timezone); //0x0116 = CELL_SYSUTIL_SYSTEMPARAM_ID_TIMEZONE + if (ret != CELL_OK) return ret; + ret = cellSysutilGetSystemParamInt(0x0117, summertime); //0x0117 = CELL_SYSUTIL_SYSTEMPARAM_ID_TIMEZONE + if (ret != CELL_OK) return ret; + return CELL_OK; +} int sys_time_get_current_time(u32 sec_addr, u32 nsec_addr) { diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Timer.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Timer.cpp new file mode 100644 index 0000000000..cd5623f12f --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_Timer.cpp @@ -0,0 +1,110 @@ +#include "stdafx.h" +#include "SC_Timer.h" +#include "Emu/SysCalls/SysCalls.h" +#include "Emu/event.h" + +SysCallBase sys_timer("sys_timer"); + +int sys_timer_create(mem32_t timer_id) +{ + sys_timer.Warning("sys_timer_create(timer_id_addr=0x%x)", timer_id.GetAddr()); + + if(!Memory.IsGoodAddr(timer_id.GetAddr())) return CELL_EFAULT; + + timer_id = sys_timer.GetNewId(new timer); + return CELL_OK; +} + +int sys_timer_destroy(u32 timer_id) +{ + sys_timer.Warning("TODO: sys_timer_destroy(timer_id=%d)", timer_id); + + if(!sys_timer.CheckId(timer_id)) return CELL_ESRCH; + + Emu.GetIdManager().RemoveID(timer_id); + return CELL_OK; +} + +int sys_timer_get_information(u32 timer_id, mem_struct_ptr_t info) +{ + sys_timer.Warning("sys_timer_get_information(timer_id=%d, info_addr=0x%x)", timer_id, info.GetAddr()); + + timer* timer_data = nullptr; + if(!sys_timer.CheckId(timer_id, timer_data)) return CELL_ESRCH; + + info = timer_data->timer_information_t; + return CELL_OK; +} + +int sys_timer_start(u32 timer_id, s64 base_time, u64 period) +{ + sys_timer.Warning("sys_timer_start_periodic_absolute(timer_id=%d, basetime=%lld, period=%llu)", timer_id, base_time, period); + + timer* timer_data = nullptr; + if(!sys_timer.CheckId(timer_id, timer_data)) return CELL_ESRCH; + + if(timer_data->timer_information_t.timer_state != SYS_TIMER_STATE_STOP) return CELL_EBUSY; + if(period < 100) return CELL_EINVAL; + //TODO: if (timer is not connected to an event queue) return CELL_ENOTCONN; + + timer_data->timer_information_t.next_expiration_time = base_time; + timer_data->timer_information_t.period = period; + timer_data->timer_information_t.timer_state = SYS_TIMER_STATE_RUN; + //TODO: ? + timer_data->tmr.Start(); + return CELL_OK; +} + +int sys_timer_stop(u32 timer_id) +{ + sys_timer.Warning("TODO: sys_timer_stop()"); + + timer* timer_data = nullptr; + if(!sys_timer.CheckId(timer_id, timer_data)) return CELL_ESRCH; + + timer_data->timer_information_t.timer_state = SYS_TIMER_STATE_STOP; + timer_data->tmr.Stop(); + return CELL_OK; +} + +int sys_timer_connect_event_queue(u32 timer_id, u32 queue_id, u64 name, u64 data1, u64 data2) +{ + sys_timer.Warning("sys_timer_connect_event_queue(timer_id=%d, queue_id=%d, name=%llu, data1=%llu, data2=%llu)", + timer_id, queue_id, name, data1, data2); + + timer* timer_data = nullptr; + EventQueue* equeue = nullptr; + if(!sys_timer.CheckId(timer_id, timer_data)) return CELL_ESRCH; + if(!sys_timer.CheckId(queue_id, equeue)) return CELL_ESRCH; + + //TODO: ? + + return CELL_OK; +} + +int sys_timer_disconnect_event_queue(u32 timer_id) +{ + sys_timer.Warning("TODO: sys_timer_disconnect_event_queue(timer_id=%d)", timer_id); + + timer* timer_data = nullptr; + if(!sys_timer.CheckId(timer_id, timer_data)) return CELL_ESRCH; + + //TODO: ? + + return CELL_OK; +} + +int sys_timer_sleep(u32 sleep_time) +{ + sys_timer.Warning("sys_timer_sleep(sleep_time=%d)", sleep_time); + wxSleep(sleep_time); + return CELL_OK; +} + +int sys_timer_usleep(u64 sleep_time) +{ + sys_timer.Log("sys_timer_usleep(sleep_time=%lld)", sleep_time); + if (sleep_time > 0xFFFFFFFFFFFF) sleep_time = 0xFFFFFFFFFFFF; //2^48-1 + wxMicroSleep(sleep_time); //TODO: If (sleep_time >= 2^32) shit may happen + return CELL_OK; +} \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Timer.h b/rpcs3/Emu/SysCalls/lv2/SC_Timer.h new file mode 100644 index 0000000000..182008733b --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_Timer.h @@ -0,0 +1,23 @@ +#pragma once + +enum +{ + SYS_TIMER_STATE_STOP = 0x00U, + SYS_TIMER_STATE_RUN = 0x01U, +}; + +struct sys_timer_information_t +{ + s64 next_expiration_time; //system_time_t + u64 period; //usecond_t + u32 timer_state; + u32 pad; +}; + +struct timer +{ + wxTimer tmr; + sys_timer_information_t timer_information_t; +}; + +#pragma pack() \ No newline at end of file diff --git a/rpcs3/Emu/SysCalls/lv2/SC_Trace.cpp b/rpcs3/Emu/SysCalls/lv2/SC_Trace.cpp new file mode 100644 index 0000000000..56a28669f3 --- /dev/null +++ b/rpcs3/Emu/SysCalls/lv2/SC_Trace.cpp @@ -0,0 +1,64 @@ +#include "stdafx.h" +#include "Emu/SysCalls/SysCalls.h" + +SysCallBase sys_trace("sys_trace"); + +int sys_trace_create() +{ + sys_trace.Warning("Unimplemented function: sys_trace_create()"); + return CELL_OK; +} + +int sys_trace_start() +{ + sys_trace.Warning("Unimplemented function: sys_trace_start()"); + return CELL_OK; +} + +int sys_trace_stop() +{ + sys_trace.Warning("Unimplemented function: sys_trace_stop()"); + return CELL_OK; +} + +int sys_trace_update_top_index() +{ + sys_trace.Warning("Unimplemented function: sys_trace_update_top_index()"); + return CELL_OK; +} + +int sys_trace_destroy() +{ + sys_trace.Warning("Unimplemented function: sys_trace_destroy()"); + return CELL_OK; +} + +int sys_trace_drain() +{ + sys_trace.Warning("Unimplemented function: sys_trace_drain()"); + return CELL_OK; +} + +int sys_trace_attach_process() +{ + sys_trace.Warning("Unimplemented function: sys_trace_attach_process()"); + return CELL_OK; +} + +int sys_trace_allocate_buffer() +{ + sys_trace.Warning("Unimplemented function: sys_trace_allocate_buffer()"); + return CELL_OK; +} + +int sys_trace_free_buffer() +{ + sys_trace.Warning("Unimplemented function: sys_trace_free_buffer()"); + return CELL_OK; +} + +int sys_trace_create2() +{ + sys_trace.Warning("Unimplemented function: sys_trace_create2()"); + return CELL_OK; +} diff --git a/rpcs3/Emu/System.cpp b/rpcs3/Emu/System.cpp index 22105acae6..525eb81b36 100644 --- a/rpcs3/Emu/System.cpp +++ b/rpcs3/Emu/System.cpp @@ -3,7 +3,6 @@ #include "Emu/Memory/Memory.h" #include "Ini.h" -#include "Emu/Cell/PPCThreadManager.h" #include "Emu/Cell/PPUThread.h" #include "Emu/Cell/SPUThread.h" #include "Emu/Cell/PPUInstrTable.h" @@ -44,7 +43,7 @@ void Emulator::SetPath(const wxString& path, const wxString& elf_path) void Emulator::CheckStatus() { - ArrayF& threads = GetCPU().GetThreads(); + ArrayF& threads = GetCPU().GetThreads(); if(!threads.GetCount()) { Stop(); @@ -82,8 +81,7 @@ void Emulator::CheckStatus() void Emulator::Load() { if(!wxFileExists(m_path)) return; - ConLog.Write("loading '%s'...", m_path); - Memory.Init(); + ConLog.Write("Loading '%s'...", m_path); GetInfo().Reset(); m_vfs.Init(m_path); //m_vfs.Mount("/", vfsDevice::GetRoot(m_path), new vfsLocalFile()); @@ -99,20 +97,45 @@ void Emulator::Load() } ConLog.SkipLn(); - const auto f = m_elf_path.Len() ? OpenFile(m_elf_path) : std::shared_ptr(new vfsLocalFile(m_path)); + if(m_elf_path.IsEmpty()) + { + GetVFS().GetDeviceLocal(m_path, m_elf_path); + } - if(!f->IsOpened()) + vfsFile f(m_elf_path); + + if(!f.IsOpened()) { ConLog.Error("Elf not found! (%s - %s)", m_path, m_elf_path); return; } bool is_error; - Loader l(*f); + Loader l(f); try { - is_error = !l.Load() || l.GetMachine() == MACHINE_Unknown; + if(!(is_error = !l.Analyze() || l.GetMachine() == MACHINE_Unknown)) + { + switch(l.GetMachine()) + { + case MACHINE_SPU: + case MACHINE_PPC64: + Memory.Init(Memory_PS3); + break; + + case MACHINE_MIPS: + Memory.Init(Memory_PSP); + break; + + case MACHINE_ARM: + Memory.Init(Memory_PSV); + break; + } + + is_error = !l.Load(); + } + } catch(const wxString& e) { @@ -125,6 +148,23 @@ void Emulator::Load() is_error = true; } + CPUThreadType thread_type; + + if(!is_error) + { + switch(l.GetMachine()) + { + case MACHINE_PPC64: thread_type = CPU_THREAD_PPU; break; + case MACHINE_SPU: thread_type = CPU_THREAD_SPU; break; + case MACHINE_ARM: thread_type = CPU_THREAD_ARMv7; break; + + default: + ConLog.Error("Unimplemented thread type for machine."); + is_error = true; + break; + } + } + if(is_error) { Memory.Close(); @@ -133,17 +173,20 @@ void Emulator::Load() } LoadPoints(BreakPointsDBName); - PPCThread& thread = GetCPU().AddThread(l.GetMachine() == MACHINE_PPC64 ? PPC_THREAD_PPU : PPC_THREAD_SPU); - if(l.GetMachine() == MACHINE_SPU) + CPUThread& thread = GetCPU().AddThread(thread_type); + + switch(l.GetMachine()) { + case MACHINE_SPU: ConLog.Write("offset = 0x%llx", Memory.MainMem.GetStartAddr()); ConLog.Write("max addr = 0x%x", l.GetMaxAddr()); thread.SetOffset(Memory.MainMem.GetStartAddr()); Memory.MainMem.Alloc(Memory.MainMem.GetStartAddr() + l.GetMaxAddr(), 0xFFFFED - l.GetMaxAddr()); thread.SetEntry(l.GetEntry() - Memory.MainMem.GetStartAddr()); - } - else + break; + + case MACHINE_PPC64: { thread.SetEntry(l.GetEntry()); Memory.StackMem.Alloc(0x1000); @@ -167,6 +210,12 @@ void Emulator::Load() ppu_thr_exit_data += SC(2); ppu_thr_exit_data += BCLR(0x10 | 0x04, 0, 0, 0); } + break; + + default: + thread.SetEntry(l.GetEntry()); + break; + } if(!m_dbg_console) { @@ -317,7 +366,7 @@ void Emulator::LoadPoints(const wxString& path) if(version != bpdb_version || (sizeof(u16) + break_count * sizeof(u64) + sizeof(u32) + marked_count * sizeof(u64) + sizeof(u32)) != f.Length()) { - ConLog.Error("'%s' is borken", path); + ConLog.Error("'%s' is broken", path); return; } diff --git a/rpcs3/Emu/System.h b/rpcs3/Emu/System.h index 670e951788..bed7c5c332 100644 --- a/rpcs3/Emu/System.h +++ b/rpcs3/Emu/System.h @@ -1,7 +1,7 @@ #pragma once #include "Gui/MemoryViewer.h" -#include "Emu/Cell/PPCThreadManager.h" +#include "Emu/CPU/CPUThreadManager.h" #include "Emu/Io/Pad.h" #include "Emu/Io/Keyboard.h" #include "Emu/Io/Mouse.h" @@ -78,7 +78,7 @@ class Emulator Array m_break_points; Array m_marked_points; - PPCThreadManager m_thread_manager; + CPUThreadManager m_thread_manager; PadManager m_pad_manager; KeyboardManager m_keyboard_manager; MouseManager m_mouse_manager; @@ -109,7 +109,7 @@ public: return std::shared_ptr(m_vfs.Open(path, mode)); } - PPCThreadManager& GetCPU() { return m_thread_manager; } + CPUThreadManager& GetCPU() { return m_thread_manager; } PadManager& GetPadManager() { return m_pad_manager; } KeyboardManager& GetKeyboardManager() { return m_keyboard_manager; } MouseManager& GetMouseManager() { return m_mouse_manager; } diff --git a/rpcs3/Emu/event.h b/rpcs3/Emu/event.h index c3f72157d7..ed4084bc32 100644 --- a/rpcs3/Emu/event.h +++ b/rpcs3/Emu/event.h @@ -24,7 +24,7 @@ struct EventPort u64 data2; u64 data3; bool has_data; - PPCThread* thread; + CPUThread* thread; EventQueue* queue[127]; int pos; }; diff --git a/rpcs3/Gui/AboutDialog.cpp b/rpcs3/Gui/AboutDialog.cpp new file mode 100644 index 0000000000..38ce2abcc7 --- /dev/null +++ b/rpcs3/Gui/AboutDialog.cpp @@ -0,0 +1,92 @@ +class AboutDialog + : public wxDialog +{ + enum + { + b_id_website, + b_id_forum + }; + +public: + AboutDialog(wxWindow *parent); + + void OpenWebsite(wxCommandEvent& WXUNUSED(event)); + void OpenForum(wxCommandEvent& WXUNUSED(event)); +}; + +AboutDialog::AboutDialog(wxWindow *parent) + : wxDialog(parent, wxID_ANY, "About RPCS3", wxDefaultPosition) +{ + wxBoxSizer* s_panel(new wxBoxSizer(wxVERTICAL)); + + //Logo + wxPanel* s_panel_logo(new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(512,92))); + s_panel_logo->SetBackgroundColour(wxColor(100,100,100)); + + wxStaticText* t_name = new wxStaticText(this, wxID_ANY, "RPCS3"); + t_name->SetFont(wxFont(28, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD)); + t_name->SetBackgroundColour(wxColor(100,100,100)); + t_name->SetForegroundColour(wxColor(255,255,255)); + t_name->SetPosition(wxPoint(10,6)); + + wxStaticText* t_descr = new wxStaticText(this, wxID_ANY, "An early but promising PS3 emulator and debugger."); + t_descr->SetBackgroundColour(wxColor(100,100,100)); + t_descr->SetForegroundColour(wxColor(255,255,255)); + t_descr->SetPosition(wxPoint(12,50)); + +#ifdef _DEBUG + wxStaticText* t_version = new wxStaticText(this, wxID_ANY, wxString::Format("Version: " _PRGNAME_ " git-" RPCS3_GIT_VERSION)); +#else + wxStaticText* t_version = new wxStaticText(this, wxID_ANY, wxString::Format("Version: " _PRGNAME_ " " _PRGVER_)); +#endif + t_version->SetBackgroundColour(wxColor(100,100,100)); + t_version->SetForegroundColour(wxColor(200,200,200)); + t_version->SetPosition(wxPoint(12,66)); + + //Credits + wxBoxSizer* s_panel_credits(new wxBoxSizer(wxHORIZONTAL)); + wxStaticText* t_section1 = new wxStaticText(this, wxID_ANY, "\nDevelopers:\n\nDH\nAlexAltea", wxDefaultPosition, wxSize(156,160)); + wxStaticText* t_section2 = new wxStaticText(this, wxID_ANY, "\nThanks:\n\nBlackDaemon", wxDefaultPosition, wxSize(156,160)); + wxStaticText* t_section3 = new wxStaticText(this, wxID_ANY, "\nExternal code:\n\n - SELF Decrypter based on scetool (C) 2011-2013 by naehrwert", wxDefaultPosition, wxSize(156,160)); + s_panel_credits->AddSpacer(12); + s_panel_credits->Add(t_section1); + s_panel_credits->AddSpacer(8); + s_panel_credits->Add(t_section2); + s_panel_credits->AddSpacer(8); + s_panel_credits->Add(t_section3); + s_panel_credits->AddSpacer(12); + + //Buttons + wxBoxSizer* s_panel_buttons(new wxBoxSizer(wxHORIZONTAL)); + wxButton* b_website = new wxButton(this, b_id_website, "Website"); + wxButton* b_forum = new wxButton(this, b_id_forum, "Forum"); + Connect(b_id_website, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(AboutDialog::OpenWebsite)); + Connect(b_id_forum, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(AboutDialog::OpenForum)); + b_website->Disable(); + + s_panel_buttons->AddSpacer(12); + s_panel_buttons->Add(new wxButton(this, wxID_OK), wxLEFT, 0, 5); + s_panel_buttons->AddSpacer(256); + s_panel_buttons->Add(b_website, wxLEFT, 0, 5); + s_panel_buttons->AddSpacer(5); + s_panel_buttons->Add(b_forum, wxLEFT, 0, 5); + s_panel_buttons->AddSpacer(12); + + //Panels + s_panel->Add(s_panel_logo); + s_panel->Add(s_panel_credits); + s_panel->Add(s_panel_buttons); + + this->SetSizerAndFit(s_panel); + this->SetSize(this->GetSize()-wxSize(0,220)); +} + +void AboutDialog::OpenWebsite(wxCommandEvent& WXUNUSED(event)) +{ + wxLaunchDefaultBrowser("http://www.emunewz.net/forum/forumdisplay.php?fid=162"); +} + +void AboutDialog::OpenForum(wxCommandEvent& WXUNUSED(event)) +{ + wxLaunchDefaultBrowser("http://www.emunewz.net/forum/forumdisplay.php?fid=162"); +} \ No newline at end of file diff --git a/rpcs3/Gui/DisAsmFrame.cpp b/rpcs3/Gui/DisAsmFrame.cpp index ffc2266060..9932953eed 100644 --- a/rpcs3/Gui/DisAsmFrame.cpp +++ b/rpcs3/Gui/DisAsmFrame.cpp @@ -87,7 +87,7 @@ void DisAsmFrame::AddLine(const wxString line) { if(Emu.IsRunning()) Emu.Pause(); finished = true; - CPU.PrevPc(); + CPU.PC -= 4; return; } @@ -113,8 +113,8 @@ bool ElfType64 = false; class DumperThread : public ThreadBase { volatile uint id; - PPC_DisAsm* disasm; - PPC_Decoder* decoder; + PPCDisAsm* disasm; + PPCDecoder* decoder; volatile bool* done; volatile u8 cores; MTProgressDialog* prog_dial; @@ -135,16 +135,16 @@ public: *done = false; - if(Emu.GetCPU().GetThreads()[0].GetType() != PPC_THREAD_PPU) + if(Emu.GetCPU().GetThreads()[0].GetType() != CPU_THREAD_PPU) { - SPU_DisAsm& dis_asm = *new SPU_DisAsm(*(PPCThread*)NULL, DumpMode); - decoder = new SPU_Decoder(dis_asm); + SPUDisAsm& dis_asm = *new SPUDisAsm(CPUDisAsm_DumpMode); + decoder = new SPUDecoder(dis_asm); disasm = &dis_asm; } else { - PPU_DisAsm& dis_asm = *new PPU_DisAsm(*(PPCThread*)NULL, DumpMode); - decoder = new PPU_Decoder(dis_asm); + PPUDisAsm& dis_asm = *new PPUDisAsm(CPUDisAsm_DumpMode); + decoder = new PPUDecoder(dis_asm); disasm = &dis_asm; } } @@ -338,21 +338,28 @@ void DisAsmFrame::Dump(wxCommandEvent& WXUNUSED(event)) default: ConLog.Error("Corrupted ELF!"); return; } - PPC_DisAsm* disasm; - PPC_Decoder* decoder; + PPCDisAsm* disasm; + PPCDecoder* decoder; - if(Emu.GetCPU().GetThreads()[0].GetType() != PPC_THREAD_PPU) + switch(Emu.GetCPU().GetThreads()[0].GetType()) { - SPU_DisAsm& dis_asm = *new SPU_DisAsm(*(PPCThread*)NULL, DumpMode); - decoder = new SPU_Decoder(dis_asm); + case CPU_THREAD_PPU: + { + PPUDisAsm& dis_asm = *new PPUDisAsm(CPUDisAsm_DumpMode); + decoder = new PPUDecoder(dis_asm); disasm = &dis_asm; } - else + break; + + case CPU_THREAD_SPU: + case CPU_THREAD_RAW_SPU: { - PPU_DisAsm& dis_asm = *new PPU_DisAsm(*(PPCThread*)NULL, DumpMode); - decoder = new PPU_Decoder(dis_asm); + SPUDisAsm& dis_asm = *new SPUDisAsm(CPUDisAsm_DumpMode); + decoder = new SPUDecoder(dis_asm); disasm = &dis_asm; } + break; + } const u32 shdr_count = ElfType64 ? shdr_arr_64->GetCount() : shdr_arr_32->GetCount(); diff --git a/rpcs3/Gui/InstructionEditor.cpp b/rpcs3/Gui/InstructionEditor.cpp index cb5491e368..cc5fd53bec 100644 --- a/rpcs3/Gui/InstructionEditor.cpp +++ b/rpcs3/Gui/InstructionEditor.cpp @@ -2,21 +2,21 @@ class InstructionEditorDialog : public wxDialog { u64 pc; - PPC_DisAsm* disasm; - PPC_Decoder* decoder; + CPUDisAsm* disasm; + CPUDecoder* decoder; wxTextCtrl* t2_instr; wxStaticText* t3_preview; public: - PPCThread* CPU; + CPUThread* CPU; public: - InstructionEditorDialog(wxPanel *parent, u64 _pc, PPCThread* _CPU, PPC_Decoder* _decoder, PPC_DisAsm* _disasm); + InstructionEditorDialog(wxPanel *parent, u64 _pc, CPUThread* _CPU, CPUDecoder* _decoder, CPUDisAsm* _disasm); void updatePreview(wxCommandEvent& event); }; -InstructionEditorDialog::InstructionEditorDialog(wxPanel *parent, u64 _pc, PPCThread* _CPU, PPC_Decoder* _decoder, PPC_DisAsm* _disasm) +InstructionEditorDialog::InstructionEditorDialog(wxPanel *parent, u64 _pc, CPUThread* _CPU, CPUDecoder* _decoder, CPUDisAsm* _disasm) : wxDialog(parent, wxID_ANY, "Edit instruction", wxDefaultPosition) , pc(_pc) , CPU(_CPU) @@ -90,11 +90,18 @@ void InstructionEditorDialog::updatePreview(wxCommandEvent& event) unsigned long opcode; if (t2_instr->GetValue().ToULong(&opcode, 16)) { - decoder->Decode((u32)opcode); - wxString preview = disasm->last_opcode; - while (preview[0] != ':') preview.Remove(0,1); - preview.Remove(0,1); - t3_preview->SetLabel(preview); + if(CPU->GetType() == CPU_THREAD_ARMv7) + { + t3_preview->SetLabel("Preview for ARMv7Thread not implemented yet."); + } + else + { + disasm->dump_pc = pc; + ((PPCDecoder*)decoder)->Decode((u32)opcode); + wxString preview = disasm->last_opcode; + preview.Remove(0, preview.Find(':') + 1); + t3_preview->SetLabel(preview); + } } else { diff --git a/rpcs3/Gui/InterpreterDisAsm.cpp b/rpcs3/Gui/InterpreterDisAsm.cpp index cc671c6e9d..0742d6ee41 100644 --- a/rpcs3/Gui/InterpreterDisAsm.cpp +++ b/rpcs3/Gui/InterpreterDisAsm.cpp @@ -1,5 +1,11 @@ #include "stdafx.h" #include "InterpreterDisAsm.h" +#include "Emu/Cell/PPUDecoder.h" +#include "Emu/Cell/PPUDisAsm.h" +#include "Emu/Cell/SPUDecoder.h" +#include "Emu/Cell/SPUDisAsm.h" +#include "Emu/ARMv7/ARMv7DisAsm.h" +#include "Emu/ARMv7/ARMv7Decoder.h" #include "InstructionEditor.cpp" #include "RegisterEditor.cpp" @@ -8,12 +14,11 @@ u64 InterpreterDisAsmFrame::CentrePc(const u64 pc) const { - return pc - ((m_item_count / 2) * 4); + return pc/* - ((m_item_count / 2) * 4)*/; } InterpreterDisAsmFrame::InterpreterDisAsmFrame(wxWindow* parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(500, 700), wxTAB_TRAVERSAL) - , ThreadBase(false, "DisAsmFrame Thread") , PC(0) , CPU(nullptr) , m_item_count(30) @@ -84,7 +89,6 @@ InterpreterDisAsmFrame::InterpreterDisAsmFrame(wxWindow* parent) InterpreterDisAsmFrame::~InterpreterDisAsmFrame() { - ThreadBase::Stop(); } void InterpreterDisAsmFrame::UpdateUnitList() @@ -103,7 +107,7 @@ void InterpreterDisAsmFrame::UpdateUnitList() void InterpreterDisAsmFrame::OnSelectUnit(wxCommandEvent& event) { - CPU = (PPCThread*)event.GetClientData(); + CPU = (CPUThread*)event.GetClientData(); delete decoder; //delete disasm; @@ -112,18 +116,33 @@ void InterpreterDisAsmFrame::OnSelectUnit(wxCommandEvent& event) if(CPU) { - if(CPU->GetType() != PPC_THREAD_PPU) + switch(CPU->GetType()) { - SPU_DisAsm& dis_asm = *new SPU_DisAsm(*CPU, InterpreterMode); - decoder = new SPU_Decoder(dis_asm); + case CPU_THREAD_PPU: + { + PPUDisAsm& dis_asm = *new PPUDisAsm(CPUDisAsm_InterpreterMode); + decoder = new PPUDecoder(dis_asm); disasm = &dis_asm; } - else + break; + + case CPU_THREAD_SPU: + case CPU_THREAD_RAW_SPU: { - PPU_DisAsm& dis_asm = *new PPU_DisAsm(*CPU, InterpreterMode); - decoder = new PPU_Decoder(dis_asm); + SPUDisAsm& dis_asm = *new SPUDisAsm(CPUDisAsm_InterpreterMode); + decoder = new SPUDecoder(dis_asm); disasm = &dis_asm; } + break; + + case CPU_THREAD_ARMv7: + { + ARMv7DisAsm& dis_asm = *new ARMv7DisAsm(CPUDisAsm_InterpreterMode); + decoder = new ARMv7Decoder(dis_asm); + disasm = &dis_asm; + } + break; + } } DoUpdate(); @@ -214,16 +233,17 @@ void InterpreterDisAsmFrame::ShowAddr(const u64 addr) else { disasm->offset = CPU->GetOffset(); - for(uint i=0; iGetOffset() + PC, 4)) { m_list->SetItem(i, 0, wxString::Format("[%08llx] illegal address", PC)); + count = 2; continue; } disasm->dump_pc = PC; - decoder->Decode(Memory.Read32(CPU->GetOffset() + PC)); + count = decoder->DecodeMemory(CPU->GetOffset() + PC); if(IsBreakPoint(PC)) { @@ -236,13 +256,13 @@ void InterpreterDisAsmFrame::ShowAddr(const u64 addr) wxColour colour; - if((!CPU->IsRunning() || !Emu.IsRunning()) && PC == CPU->PC) - { - colour = wxColour("Green"); - } - else - { - colour = wxColour("White"); + if((!CPU->IsRunning() || !Emu.IsRunning()) && PC == CPU->PC) + { + colour = wxColour("Green"); + } + else + { + colour = wxColour("White"); for(u32 i=0; iExecOnce(); } void InterpreterDisAsmFrame::InstrKey(wxListEvent& event) { long i = m_list->GetFirstSelected(); - if(i < 0) return; + if(i < 0 || !CPU) + { + event.Skip(); + return; + } const u64 start_pc = PC - m_item_count*4; const u64 pc = start_pc + i*4; @@ -465,6 +489,8 @@ void InterpreterDisAsmFrame::InstrKey(wxListEvent& event) DoUpdate(); return; } + + event.Skip(); } void InterpreterDisAsmFrame::DClick(wxListEvent& event) @@ -530,35 +556,3 @@ bool InterpreterDisAsmFrame::RemoveBreakPoint(u64 pc) return false; } - -void InterpreterDisAsmFrame::Task() -{ - if(!CPU) return; - wxGetApp().SendDbgCommand(DID_RESUME_THREAD, CPU); - wxGetApp().SendDbgCommand(DID_RESUMED_THREAD, CPU); - bool dump_status = dump_enable; - - //CPU.InitTls(); - - try - { - do - { - CPU->ExecOnce(); - } - while(CPU->IsRunning() && Emu.IsRunning() && !TestDestroy() && !IsBreakPoint(CPU->PC) && dump_status == dump_enable); - } - catch(const wxString& e) - { - ConLog.Error(e); - } - catch(...) - { - ConLog.Error("Unhandled exception."); - } - - //CPU.FreeTls(); - - wxGetApp().SendDbgCommand(DID_PAUSE_THREAD, CPU); - wxGetApp().SendDbgCommand(DID_PAUSED_THREAD, CPU); -} \ No newline at end of file diff --git a/rpcs3/Gui/InterpreterDisAsm.h b/rpcs3/Gui/InterpreterDisAsm.h index f14068db35..807212e0e1 100644 --- a/rpcs3/Gui/InterpreterDisAsm.h +++ b/rpcs3/Gui/InterpreterDisAsm.h @@ -1,17 +1,13 @@ #pragma once -#include "Emu/Cell/PPCThread.h" -#include "Emu/Cell/PPUDecoder.h" -#include "Emu/Cell/PPUDisAsm.h" -#include "Emu/Cell/SPUDecoder.h" -#include "Emu/Cell/SPUDisAsm.h" +#include "Emu/CPU/CPUThread.h" +#include "Emu/CPU/CPUDecoder.h" +#include "Emu/CPU/CPUDisAsm.h" -class InterpreterDisAsmFrame - : public wxPanel - , public ThreadBase +class InterpreterDisAsmFrame : public wxPanel { wxListView* m_list; - PPC_DisAsm* disasm; - PPC_Decoder* decoder; + CPUDisAsm* disasm; + CPUDecoder* decoder; u64 PC; Array remove_markedPC; wxTextCtrl* m_regs; @@ -23,7 +19,7 @@ class InterpreterDisAsmFrame wxChoice* m_choice_units; public: - PPCThread* CPU; + CPUThread* CPU; public: InterpreterDisAsmFrame(wxWindow* parent); @@ -53,6 +49,4 @@ public: bool IsBreakPoint(u64 pc); void AddBreakPoint(u64 pc); bool RemoveBreakPoint(u64 pc); - - virtual void Task(); }; \ No newline at end of file diff --git a/rpcs3/Gui/MainFrame.cpp b/rpcs3/Gui/MainFrame.cpp index f6512eb2be..d46089ac4a 100644 --- a/rpcs3/Gui/MainFrame.cpp +++ b/rpcs3/Gui/MainFrame.cpp @@ -8,8 +8,11 @@ #include "Emu/GS/sysutil_video.h" #include "Gui/VHDDManager.h" #include "Gui/VFSManager.h" +#include "Gui/AboutDialog.cpp" #include +#include "scetool/scetool.cpp" + BEGIN_EVENT_TABLE(MainFrame, FrameBase) EVT_CLOSE(MainFrame::OnQuit) END_EVENT_TABLE() @@ -26,6 +29,7 @@ enum IDs id_config_emu, id_config_vfs_manager, id_config_vhdd_manager, + id_help_about, id_update_dbg, }; @@ -53,15 +57,17 @@ MainFrame::MainFrame() wxMenu& menu_boot(*new wxMenu()); wxMenu& menu_sys(*new wxMenu()); wxMenu& menu_conf(*new wxMenu()); + wxMenu& menu_help(*new wxMenu()); menubar.Append(&menu_boot, "Boot"); menubar.Append(&menu_sys, "System"); menubar.Append(&menu_conf, "Config"); + menubar.Append(&menu_help, "Help"); menu_boot.Append(id_boot_game, "Boot game"); menu_boot.AppendSeparator(); - menu_boot.Append(id_boot_elf, "Boot Elf"); - //menu_boot.Append(id_boot_self, "Boot Self"); + menu_boot.Append(id_boot_elf, "Boot ELF"); + menu_boot.Append(id_boot_self, "Boot SELF"); menu_sys.Append(id_sys_pause, "Pause")->Enable(false); menu_sys.Append(id_sys_stop, "Stop\tCtrl + S")->Enable(false); @@ -74,6 +80,8 @@ MainFrame::MainFrame() menu_conf.Append(id_config_vfs_manager, "Virtual File System Manager"); menu_conf.Append(id_config_vhdd_manager, "Virtual HDD Manager"); + menu_help.Append(id_help_about, "About..."); + SetMenuBar(&menubar); m_game_viewer = new GameViewer(this); @@ -92,6 +100,8 @@ MainFrame::MainFrame() Connect( id_config_vfs_manager, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainFrame::ConfigVFS) ); Connect( id_config_vhdd_manager,wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainFrame::ConfigVHDD) ); + Connect( id_help_about, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainFrame::AboutDialogHandler) ); + Connect( id_update_dbg, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainFrame::UpdateUI) ); m_app_connector.Connect(wxEVT_KEY_DOWN, wxKeyEventHandler(MainFrame::OnKeyDown), (wxObject*)0, this); @@ -188,14 +198,14 @@ void MainFrame::BootElf(wxCommandEvent& WXUNUSED(event)) return; } - ConLog.Write("Elf: booting..."); + ConLog.Write("ELF: booting..."); Emu.Stop(); Emu.SetPath(ctrl.GetPath()); Emu.Load(); - ConLog.Write("Elf: boot done."); + ConLog.Write("ELF: boot done."); } void MainFrame::BootSelf(wxCommandEvent& WXUNUSED(event)) @@ -220,9 +230,20 @@ void MainFrame::BootSelf(wxCommandEvent& WXUNUSED(event)) ConLog.Write("SELF: booting..."); Emu.Stop(); + + wxString fileIn = ctrl.GetPath(); + wxString fileOut = ctrl.GetPath()+".elf"; - Emu.SetPath(ctrl.GetPath()); + if (!scetool_decrypt((scetool::s8 *)fileIn.mb_str(), (scetool::s8 *)fileOut.mb_str())) + { + ConLog.Write("SELF: Could not decrypt file"); + return; + } + + Emu.SetPath(ctrl.GetPath()+".elf"); Emu.Load(); + if (!wxRemoveFile(ctrl.GetPath()+".elf")) + ConLog.Warning("Could not delete the decrypted ELF file"); ConLog.Write("SELF: boot done."); } @@ -323,11 +344,11 @@ void MainFrame::Config(wxCommandEvent& WXUNUSED(event)) cbox_keyboard_handler->Append("Null"); cbox_keyboard_handler->Append("Windows"); - //cbox_pad_handler->Append("DirectInput"); + //cbox_keyboard_handler->Append("DirectInput"); cbox_mouse_handler->Append("Null"); cbox_mouse_handler->Append("Windows"); - //cbox_pad_handler->Append("DirectInput"); + //cbox_mouse_handler->Append("DirectInput"); chbox_gs_vsync->SetValue(Ini.GSVSyncEnable.GetValue()); @@ -402,6 +423,11 @@ void MainFrame::ConfigVHDD(wxCommandEvent& WXUNUSED(event)) VHDDManagerDialog(this).ShowModal(); } +void MainFrame::AboutDialogHandler(wxCommandEvent& WXUNUSED(event)) +{ + AboutDialog(this).ShowModal(); +} + void MainFrame::UpdateUI(wxCommandEvent& event) { event.Skip(); diff --git a/rpcs3/Gui/MainFrame.h b/rpcs3/Gui/MainFrame.h index 43909bcd76..94fdf0e9f2 100644 --- a/rpcs3/Gui/MainFrame.h +++ b/rpcs3/Gui/MainFrame.h @@ -29,6 +29,7 @@ private: void Config(wxCommandEvent& event); void ConfigVFS(wxCommandEvent& event); void ConfigVHDD(wxCommandEvent& event); + void AboutDialogHandler(wxCommandEvent& event); void UpdateUI(wxCommandEvent& event); void OnKeyDown(wxKeyEvent& event); diff --git a/rpcs3/Gui/RegisterEditor.cpp b/rpcs3/Gui/RegisterEditor.cpp index da190f2e11..08d12378e4 100644 --- a/rpcs3/Gui/RegisterEditor.cpp +++ b/rpcs3/Gui/RegisterEditor.cpp @@ -1,24 +1,23 @@ -class RegisterEditorDialog - : public wxDialog +class RegisterEditorDialog : public wxDialog { u64 pc; - PPC_DisAsm* disasm; - PPC_Decoder* decoder; + CPUDisAsm* disasm; + CPUDecoder* decoder; wxComboBox* t1_register; wxTextCtrl* t2_value; wxStaticText* t3_preview; public: - PPCThread* CPU; + CPUThread* CPU; public: - RegisterEditorDialog(wxPanel *parent, u64 _pc, PPCThread* _CPU, PPC_Decoder* _decoder, PPC_DisAsm* _disasm); + RegisterEditorDialog(wxPanel *parent, u64 _pc, CPUThread* _CPU, CPUDecoder* _decoder, CPUDisAsm* _disasm); void updateRegister(wxCommandEvent& event); void updatePreview(wxCommandEvent& event); }; -RegisterEditorDialog::RegisterEditorDialog(wxPanel *parent, u64 _pc, PPCThread* _CPU, PPC_Decoder* _decoder, PPC_DisAsm* _disasm) +RegisterEditorDialog::RegisterEditorDialog(wxPanel *parent, u64 _pc, CPUThread* _CPU, CPUDecoder* _decoder, CPUDisAsm* _disasm) : wxDialog(parent, wxID_ANY, "Edit registers", wxDefaultPosition) , pc(_pc) , CPU(_CPU) @@ -64,10 +63,11 @@ RegisterEditorDialog::RegisterEditorDialog(wxPanel *parent, u64 _pc, PPCThread* s_panel_margin_x->Add(s_panel_margin_y); s_panel_margin_x->AddSpacer(12); - this->Connect(wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler(RegisterEditorDialog::updateRegister)); + Connect(wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler(RegisterEditorDialog::updateRegister)); - if (CPU->GetType() == PPC_THREAD_PPU) + switch(CPU->GetType()) { + case CPU_THREAD_PPU: for (int i=0; i<32; i++) t1_register->Append(wxString::Format("GPR[%d]",i)); for (int i=0; i<32; i++) t1_register->Append(wxString::Format("FPR[%d]",i)); for (int i=0; i<32; i++) t1_register->Append(wxString::Format("VPR[%d]",i)); @@ -76,20 +76,21 @@ RegisterEditorDialog::RegisterEditorDialog(wxPanel *parent, u64 _pc, PPCThread* t1_register->Append("CTR"); t1_register->Append("XER"); t1_register->Append("FPSCR"); - } - if (CPU->GetType() == PPC_THREAD_SPU) - { + break; + + case CPU_THREAD_SPU: + case CPU_THREAD_RAW_SPU: for (int i=0; i<128; i++) t1_register->Append(wxString::Format("GPR[%d]",i)); - } - if (CPU->GetType() == PPC_THREAD_RAW_SPU) - { - wxMessageBox("RawSPU threads not yet supported.","Error"); - return; + break; + + default: + wxMessageBox("Not supported thread.", "Error"); + return; } - this->SetSizerAndFit(s_panel_margin_x); + SetSizerAndFit(s_panel_margin_x); - if(this->ShowModal() == wxID_OK) + if(ShowModal() == wxID_OK) { wxString reg = t1_register->GetStringSelection(); wxString value = t2_value->GetValue(); diff --git a/rpcs3/Loader/ELF32.cpp b/rpcs3/Loader/ELF32.cpp index 74bb8a3112..6684a4f584 100644 --- a/rpcs3/Loader/ELF32.cpp +++ b/rpcs3/Loader/ELF32.cpp @@ -41,16 +41,21 @@ bool ELF32Loader::LoadEhdrInfo() if(!ehdr.CheckMagic()) return false; + if(ehdr.IsLittleEndian()) + ConLog.Warning("ELF32 LE"); + switch(ehdr.e_machine) { + case MACHINE_MIPS: case MACHINE_PPC64: case MACHINE_SPU: + case MACHINE_ARM: machine = (Elf_Machine)ehdr.e_machine; break; default: machine = MACHINE_Unknown; - ConLog.Error("Unknown elf32 type: 0x%x", ehdr.e_machine); + ConLog.Error("Unknown elf32 machine: 0x%x", ehdr.e_machine); return false; } @@ -76,10 +81,28 @@ bool ELF32Loader::LoadPhdrInfo() for(uint i=0; iLoad(elf32_f); + if(ehdr.IsLittleEndian()) phdr->LoadLE(elf32_f); + else phdr->Load(elf32_f); phdr_arr.Move(phdr); } + if(/*!Memory.IsGoodAddr(entry)*/ entry & 0x1) + { + //entry is physical, convert to virtual + + entry &= ~0x1; + + for(size_t i=0; i= entry && entry < phdr_arr[i].p_paddr + phdr_arr[i].p_memsz) + { + entry += phdr_arr[i].p_vaddr; + ConLog.Warning("virtual entry = 0x%x", entry); + break; + } + } + } + return true; } @@ -89,13 +112,14 @@ bool ELF32Loader::LoadShdrInfo() for(u32 i=0; iLoad(elf32_f); + if(ehdr.IsLittleEndian()) shdr->LoadLE(elf32_f); + else shdr->Load(elf32_f); shdr_arr.Move(shdr); } if(ehdr.e_shstrndx >= shdr_arr.GetCount()) { - ConLog.Error("LoadShdr64 error: shstrndx too big!"); + ConLog.Error("LoadShdr32 error: shstrndx too big!"); return false; } @@ -110,8 +134,7 @@ bool ELF32Loader::LoadShdrInfo() if(c == 0) break; name += c; } - - shdr_name_arr.Add(name); + shdr_name_arr.Add(name); } return true; @@ -127,8 +150,10 @@ bool ELF32Loader::LoadEhdrData(u64 offset) return true; } -bool ELF32Loader::LoadPhdrData(u64 offset) +bool ELF32Loader::LoadPhdrData(u64 _offset) { + const u64 offset = machine == MACHINE_SPU ? _offset : 0; + for(u32 i=0; i 1) return wxString::Format("%d's complement, big endian", data); @@ -39,8 +41,10 @@ const wxString Ehdr_MachineToString(const u16 machine) { switch(machine) { - case MACHINE_PPC64: return "PowerPC64"; + case MACHINE_MIPS: return "MIPS"; + case MACHINE_PPC64: return "PowerPC64"; case MACHINE_SPU: return "SPU"; + case MACHINE_ARM: return "ARM"; }; return wxString::Format("Unknown (%x)", machine); @@ -91,14 +95,24 @@ const wxString Phdr_TypeToString(const u32 type) return wxString::Format("Unknown (%x)", type); } -Loader::Loader() : m_stream(nullptr) +Loader::Loader() + : m_stream(nullptr) + , m_loader(nullptr) { } -Loader::Loader(vfsFileBase& stream) : m_stream(&stream) +Loader::Loader(vfsFileBase& stream) + : m_stream(&stream) + , m_loader(nullptr) { } +Loader::~Loader() +{ + delete m_loader; + m_loader = nullptr; +} + void Loader::Open(vfsFileBase& stream) { m_stream = &stream; @@ -119,27 +133,35 @@ LoaderBase* Loader::SearchLoader() return nullptr; } -bool Loader::Load() +bool Loader::Analyze() { - static const u64 spu_offset = 0x10000; + delete m_loader; - ScopedPtr l = SearchLoader(); + m_loader = SearchLoader(); - if(!l) + if(!m_loader) { ConLog.Error("Unknown file type"); return false; } - if(!l->LoadData(l->GetMachine() == MACHINE_SPU ? spu_offset : 0)) + machine = m_loader->GetMachine(); + entry = m_loader->GetMachine() == MACHINE_SPU ? m_loader->GetEntry() + g_spu_offset : m_loader->GetEntry(); + + return true; +} + +bool Loader::Load() +{ + if(!m_loader) + return false; + + if(!m_loader->LoadData(m_loader->GetMachine() == MACHINE_SPU ? g_spu_offset : 0)) { ConLog.Error("Broken file"); return false; } - machine = l->GetMachine(); - entry = l->GetMachine() == MACHINE_SPU ? l->GetEntry() + spu_offset : l->GetEntry(); - const wxString& root = wxFileName(wxFileName(m_stream->GetPath()).GetPath()).GetPath(); const wxString& psf_path = root + "\\" + "PARAM.SFO"; if(wxFileExists(psf_path)) diff --git a/rpcs3/Loader/Loader.h b/rpcs3/Loader/Loader.h index febec7c85c..ab5c974c20 100644 --- a/rpcs3/Loader/Loader.h +++ b/rpcs3/Loader/Loader.h @@ -8,8 +8,10 @@ enum Elf_Machine { MACHINE_Unknown, + MACHINE_MIPS = 0x08, MACHINE_PPC64 = 0x15, MACHINE_SPU = 0x17, + MACHINE_ARM = 0x28, }; enum ShdrType @@ -58,6 +60,21 @@ __forceinline static u64 Read64(vfsStream& f) return ((u64)Read32(f) << 32) | (u64)Read32(f); } +__forceinline static u16 Read16LE(vfsStream& f) +{ + return ((u16)Read8(f) | ((u16)Read8(f) << 8)); +} + +__forceinline static u32 Read32LE(vfsStream& f) +{ + return Read16LE(f) | (Read16LE(f) << 16); +} + +__forceinline static u64 Read64LE(vfsStream& f) +{ + return ((u64)Read32LE(f) | (u64)Read32LE(f) << 32); +} + __forceinline static void Write8(wxFile& f, const u8 data) { f.Write(&data, 1); @@ -81,6 +98,23 @@ __forceinline static void Write64(wxFile& f, const u64 data) Write32(f, data); } +__forceinline static void Write16LE(wxFile& f, const u16 data) +{ + Write8(f, data); + Write8(f, data >> 8); +} + +__forceinline static void Write32LE(wxFile& f, const u32 data) +{ + Write16LE(f, data); + Write16LE(f, data >> 16); +} + +__forceinline static void Write64LE(wxFile& f, const u64 data) +{ + Write32LE(f, data); + Write32LE(f, data >> 32); +} const wxString Ehdr_DataToString(const u8 data); const wxString Ehdr_TypeToString(const u16 type); @@ -160,6 +194,7 @@ public: virtual bool LoadInfo() { return false; } virtual bool LoadData(u64 offset = 0) { return false; } Elf_Machine GetMachine() { return machine; } + u32 GetEntry() { return entry; } u32 GetMinAddr() { return min_addr; } u32 GetMaxAddr() { return min_addr; } @@ -168,13 +203,16 @@ public: class Loader : public LoaderBase { vfsFileBase* m_stream; + LoaderBase* m_loader; public: Loader(); Loader(vfsFileBase& stream); + ~Loader(); void Open(const wxString& path); void Open(vfsFileBase& stream); + bool Analyze(); bool Load(); diff --git a/rpcs3/rpcs3.cpp b/rpcs3/rpcs3.cpp index f716e8b532..31aff4fa1f 100644 --- a/rpcs3/rpcs3.cpp +++ b/rpcs3/rpcs3.cpp @@ -45,7 +45,7 @@ void Rpcs3App::Exit() wxApp::Exit(); } -void Rpcs3App::SendDbgCommand(DbgCommand id, PPCThread* thr) +void Rpcs3App::SendDbgCommand(DbgCommand id, CPUThread* thr) { wxCommandEvent event(wxEVT_DBG_COMMAND, id); event.SetClientData(thr); diff --git a/rpcs3/rpcs3.h b/rpcs3/rpcs3.h index 94dddbae9b..a740a34eec 100644 --- a/rpcs3/rpcs3.h +++ b/rpcs3/rpcs3.h @@ -61,7 +61,7 @@ public: virtual bool OnInit(); virtual void Exit(); - void SendDbgCommand(DbgCommand id, PPCThread* thr=nullptr); + void SendDbgCommand(DbgCommand id, CPUThread* thr=nullptr); }; DECLARE_APP(Rpcs3App) diff --git a/rpcs3/rpcs3.vcxproj b/rpcs3/rpcs3.vcxproj index 3b04e70d4f..6e49bcdbd9 100644 --- a/rpcs3/rpcs3.vcxproj +++ b/rpcs3/rpcs3.vcxproj @@ -1,3 +1,4 @@ +<<<<<<< HEAD @@ -349,4 +350,372 @@ +======= + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {70CD65B0-91D6-4FAE-9A7B-4AF55D0D1B12} + Win32Proj + rpcs3 + + + + Application + true + MultiByte + v110 + + + Application + true + MultiByte + v110 + + + Application + false + true + MultiByte + v110 + false + + + Application + false + true + MultiByte + v110 + false + + + + + + + + + + + + + + + + + + + .\;..\wxWidgets\include;..\SDL-1.3.0-5538\include;..\SDL_image-1.2.10;..\pthreads-2.8.0;..\;$(IncludePath) + $(SolutionDir)bin\ + ..\libs\$(Configuration)\;$(LibraryPath) + $(ProjectName)-$(PlatformShortName)-dbg + + + .\;..\wxWidgets\include;..\SDL-1.3.0-5538\include;..\SDL_image-1.2.10;..\pthreads-2.8.0;..\;$(IncludePath) + $(SolutionDir)bin\ + ..\libs\$(Configuration)\;$(LibraryPath) + $(ProjectName)-$(PlatformShortName)-dbg + + + false + .\;..\wxWidgets\include;..\SDL-1.3.0-5538\include;..\SDL_image-1.2.10;..\pthreads-2.8.0;..\;$(IncludePath) + $(SolutionDir)bin\ + ..\libs\$(Configuration)\;$(LibraryPath) + false + false + $(ProjectName)-$(PlatformShortName) + + + false + .\;..\wxWidgets\include;..\SDL-1.3.0-5538\include;..\SDL_image-1.2.10;..\pthreads-2.8.0;..\;$(IncludePath) + $(SolutionDir)bin\ + ..\libs\$(Configuration)\;$(LibraryPath) + false + false + $(ProjectName)-$(PlatformShortName) + + + + Level3 + Disabled + EditAndContinue + Use + true + + + true + adv.lib;base.lib;core.lib;aui.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;odbc32.lib;odbccp32.lib;comctl32.lib;ws2_32.lib;shlwapi.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;rpcrt4.lib;%(AdditionalDependencies) + %(IgnoreSpecificDefaultLibraries) + false + + + + + + + + + Level3 + Disabled + ProgramDatabase + Use + + + true + adv.lib;base.lib;core.lib;aui.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;odbc32.lib;odbccp32.lib;comctl32.lib;ws2_32.lib;shlwapi.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;rpcrt4.lib;%(AdditionalDependencies) + %(IgnoreSpecificDefaultLibraries) + false + + + $(SolutionDir)\Utilities\git-version-gen.cmd + + + + + TurnOffAllWarnings + Full + true + true + + + MultiThreadedDLL + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + false + Use + Speed + Sync + false + + + Windows + true + true + true + adv.lib;base.lib;core.lib;aui.lib;odbc32.lib;odbccp32.lib;comctl32.lib;ws2_32.lib;shlwapi.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;rpcrt4.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregex.lib;wxexpat.lib;wsock32.lib;wininet.lib;%(AdditionalDependencies) + + + %(IgnoreSpecificDefaultLibraries) + false + + + + + + + + + Level3 + Full + true + true + + + MultiThreadedDLL + WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + false + Use + Speed + Sync + false + + + Windows + true + true + true + adv.lib;base.lib;core.lib;aui.lib;odbc32.lib;odbccp32.lib;comctl32.lib;ws2_32.lib;shlwapi.lib;winmm.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;rpcrt4.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregex.lib;wxexpat.lib;wsock32.lib;wininet.lib;%(AdditionalDependencies) + + + %(IgnoreSpecificDefaultLibraries) + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create + Create + Create + Create + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa \ No newline at end of file diff --git a/rpcs3/rpcs3.vcxproj.filters b/rpcs3/rpcs3.vcxproj.filters index 57664c5e67..fa4931e3ea 100644 --- a/rpcs3/rpcs3.vcxproj.filters +++ b/rpcs3/rpcs3.vcxproj.filters @@ -1,3 +1,4 @@ +<<<<<<< HEAD @@ -478,4 +479,522 @@ Include +======= + + + + + {29c70b04-59a5-4d5b-98f9-3584df137ed1} + + + {98fb6fa5-9a9a-48a6-a6b4-be4b9a69b76e} + + + {47155d25-741d-42c0-8850-f22aafca082a} + + + {f306c137-6d2c-4e21-ba79-ac87d0ded22c} + + + {adfec460-d940-4482-9fdb-18cb0814c3d5} + true + + + {6c36f15e-07fd-45d6-a81c-1ab43ee1b58b} + + + {57263311-75a4-4309-81aa-b86fd212794b} + + + {461eddb5-b8a8-46be-918c-98cc7eaf995b} + + + {6fb03753-064a-456d-bb6f-9ceaed3776c7} + + + {e79e49c8-6967-4776-8f50-5479c3821b51} + + + {9bd88f78-8528-48f3-b9e0-78e06476b04d} + + + {fd7cea02-e77f-41b1-8b61-f78e7d280e04} + + + {dfd581c4-aed0-4229-bb30-7ee5816049e1} + + + {718bc358-b7ef-4988-8547-2148d14bb08b} + + + {f66e37f9-5e58-443b-bcff-2e9e002ac89e} + + + {041a844e-9f8b-4b4b-a4c5-6c72ecbde475} + + + {bee6a4b4-6371-4c1b-8558-fc7888b1574e} + + + + + rpcs3 + + + rpcs3 + + + Gui + + + Gui + + + Emu + + + Gui + + + Gui + + + Emu + + + rpcs3 + + + Gui + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Gui + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Gui + + + Loader + + + Loader + + + Loader + + + Loader + + + Loader + + + Loader + + + Emu\Cell + + + Emu\Cell + + + Emu\SysCalls + + + Emu\SysCalls\lv2 + + + Emu\Io + + + Emu + + + Emu\GS + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\GS\GL + + + Emu\GS\GL + + + Emu\GS\GL + + + Emu\GS + + + Emu\SysCalls\lv2 + + + Emu\GS + + + Emu\Cell + + + Emu\SysCalls\lv2 + + + Utilities + + + Emu\SysCalls + + + Emu\SysCalls\lv2 + + + Emu\SysCalls + + + Emu\FS + + + Emu\FS + + + Emu\FS + + + Emu\FS + + + Emu\FS + + + Emu\SysCalls\lv2 + + + Emu\FS + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Gui + + + rpcs3 + + + Emu\Cell + + + Emu\SysCalls\lv2 + + + Emu\SysCalls + + + Emu\SysCalls\Modules + + + Emu\Cell + + + Emu\Cell + + + Emu\HDD + + + Gui + + + Gui + + + Gui + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\Io + + + Emu\SysCalls\lv2 + + + Emu\Io + + + Emu\SysCalls\lv2 + + + Emu\FS + + + Emu\CPU + + + Emu\CPU + + + Emu\Cell + + + Emu\ARMv7 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\lv2 + + + Emu\SysCalls\Modules + + + Emu\SysCalls\Modules + + + Emu\GS\GL + + + Emu\GS\GL + + + Emu\GS\GL + + + Emu\GS\GL + + + + + + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Include + + + Utilities + + + Utilities + + + Utilities + + + Utilities + + + Utilities + + + Include + + + Include + + + Include + + + Include + + + Include + + + Utilities + + +>>>>>>> 3dd9683b472b89358a697210798c89df5b0e5baa \ No newline at end of file diff --git a/rpcs3/stdafx.h b/rpcs3/stdafx.h index 3a02d6b320..e9f954e7cf 100644 --- a/rpcs3/stdafx.h +++ b/rpcs3/stdafx.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -186,6 +187,7 @@ enum Status Ready, }; +#include "Utilities/BEType.h" #include "Utilities/Thread.h" #include "Utilities/Array.h" #include "Utilities/Timer.h" @@ -196,12 +198,13 @@ enum Status #include "Ini.h" #include "Gui/FrameBase.h" #include "Gui/ConLog.h" -#include "Emu/System.h" #include "Emu/Memory/Memory.h" +#include "Emu/System.h" #include "Emu/Cell/PPUThread.h" #include "Emu/FS/vfsFileBase.h" #include "Emu/FS/vfsLocalFile.h" +#include "Emu/FS/vfsFile.h" #include "Emu/FS/vfsStream.h" #include "Emu/FS/vfsStreamMemory.h" #include "rpcs3.h" diff --git a/scetool/README b/scetool/README new file mode 100644 index 0000000000..728e130c9b --- /dev/null +++ b/scetool/README @@ -0,0 +1,2 @@ +scetool (C) 2011-2013 by naehrwert +NP local license handling (C) 2012 by flatz \ No newline at end of file diff --git a/scetool/aes.c b/scetool/aes.c new file mode 100644 index 0000000000..7bf3c1cd6f --- /dev/null +++ b/scetool/aes.c @@ -0,0 +1,695 @@ +/* + * FIPS-197 compliant AES implementation + * + * Copyright (C) 2006-2010, Brainspark B.V. + * + * This file is part of PolarSSL (http://www.polarssl.org) + * Lead Maintainer: Paul Bakker + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +/* + * The AES block cipher was designed by Vincent Rijmen and Joan Daemen. + * + * http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf + * http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf + */ + +#include "aes.h" + +/* + * 32-bit integer manipulation macros (little endian) + */ +#ifndef GET_ULONG_LE +#define GET_ULONG_LE(n,b,i) \ +{ \ + (n) = ( (unsigned long) (b)[(i) ] ) \ + | ( (unsigned long) (b)[(i) + 1] << 8 ) \ + | ( (unsigned long) (b)[(i) + 2] << 16 ) \ + | ( (unsigned long) (b)[(i) + 3] << 24 ); \ +} +#endif + +#ifndef PUT_ULONG_LE +#define PUT_ULONG_LE(n,b,i) \ +{ \ + (b)[(i) ] = (unsigned char) ( (n) ); \ + (b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \ + (b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \ + (b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \ +} +#endif + +/* + * Forward S-box + */ +static const unsigned char FSb[256] = +{ + 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, + 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, + 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, + 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, + 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, + 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, + 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, + 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, + 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, + 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, + 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, + 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, + 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, + 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, + 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, + 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, + 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, + 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, + 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, + 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, + 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, + 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, + 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, + 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, + 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, + 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, + 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 +}; + +/* + * Forward tables + */ +#define FT \ +\ + V(A5,63,63,C6), V(84,7C,7C,F8), V(99,77,77,EE), V(8D,7B,7B,F6), \ + V(0D,F2,F2,FF), V(BD,6B,6B,D6), V(B1,6F,6F,DE), V(54,C5,C5,91), \ + V(50,30,30,60), V(03,01,01,02), V(A9,67,67,CE), V(7D,2B,2B,56), \ + V(19,FE,FE,E7), V(62,D7,D7,B5), V(E6,AB,AB,4D), V(9A,76,76,EC), \ + V(45,CA,CA,8F), V(9D,82,82,1F), V(40,C9,C9,89), V(87,7D,7D,FA), \ + V(15,FA,FA,EF), V(EB,59,59,B2), V(C9,47,47,8E), V(0B,F0,F0,FB), \ + V(EC,AD,AD,41), V(67,D4,D4,B3), V(FD,A2,A2,5F), V(EA,AF,AF,45), \ + V(BF,9C,9C,23), V(F7,A4,A4,53), V(96,72,72,E4), V(5B,C0,C0,9B), \ + V(C2,B7,B7,75), V(1C,FD,FD,E1), V(AE,93,93,3D), V(6A,26,26,4C), \ + V(5A,36,36,6C), V(41,3F,3F,7E), V(02,F7,F7,F5), V(4F,CC,CC,83), \ + V(5C,34,34,68), V(F4,A5,A5,51), V(34,E5,E5,D1), V(08,F1,F1,F9), \ + V(93,71,71,E2), V(73,D8,D8,AB), V(53,31,31,62), V(3F,15,15,2A), \ + V(0C,04,04,08), V(52,C7,C7,95), V(65,23,23,46), V(5E,C3,C3,9D), \ + V(28,18,18,30), V(A1,96,96,37), V(0F,05,05,0A), V(B5,9A,9A,2F), \ + V(09,07,07,0E), V(36,12,12,24), V(9B,80,80,1B), V(3D,E2,E2,DF), \ + V(26,EB,EB,CD), V(69,27,27,4E), V(CD,B2,B2,7F), V(9F,75,75,EA), \ + V(1B,09,09,12), V(9E,83,83,1D), V(74,2C,2C,58), V(2E,1A,1A,34), \ + V(2D,1B,1B,36), V(B2,6E,6E,DC), V(EE,5A,5A,B4), V(FB,A0,A0,5B), \ + V(F6,52,52,A4), V(4D,3B,3B,76), V(61,D6,D6,B7), V(CE,B3,B3,7D), \ + V(7B,29,29,52), V(3E,E3,E3,DD), V(71,2F,2F,5E), V(97,84,84,13), \ + V(F5,53,53,A6), V(68,D1,D1,B9), V(00,00,00,00), V(2C,ED,ED,C1), \ + V(60,20,20,40), V(1F,FC,FC,E3), V(C8,B1,B1,79), V(ED,5B,5B,B6), \ + V(BE,6A,6A,D4), V(46,CB,CB,8D), V(D9,BE,BE,67), V(4B,39,39,72), \ + V(DE,4A,4A,94), V(D4,4C,4C,98), V(E8,58,58,B0), V(4A,CF,CF,85), \ + V(6B,D0,D0,BB), V(2A,EF,EF,C5), V(E5,AA,AA,4F), V(16,FB,FB,ED), \ + V(C5,43,43,86), V(D7,4D,4D,9A), V(55,33,33,66), V(94,85,85,11), \ + V(CF,45,45,8A), V(10,F9,F9,E9), V(06,02,02,04), V(81,7F,7F,FE), \ + V(F0,50,50,A0), V(44,3C,3C,78), V(BA,9F,9F,25), V(E3,A8,A8,4B), \ + V(F3,51,51,A2), V(FE,A3,A3,5D), V(C0,40,40,80), V(8A,8F,8F,05), \ + V(AD,92,92,3F), V(BC,9D,9D,21), V(48,38,38,70), V(04,F5,F5,F1), \ + V(DF,BC,BC,63), V(C1,B6,B6,77), V(75,DA,DA,AF), V(63,21,21,42), \ + V(30,10,10,20), V(1A,FF,FF,E5), V(0E,F3,F3,FD), V(6D,D2,D2,BF), \ + V(4C,CD,CD,81), V(14,0C,0C,18), V(35,13,13,26), V(2F,EC,EC,C3), \ + V(E1,5F,5F,BE), V(A2,97,97,35), V(CC,44,44,88), V(39,17,17,2E), \ + V(57,C4,C4,93), V(F2,A7,A7,55), V(82,7E,7E,FC), V(47,3D,3D,7A), \ + V(AC,64,64,C8), V(E7,5D,5D,BA), V(2B,19,19,32), V(95,73,73,E6), \ + V(A0,60,60,C0), V(98,81,81,19), V(D1,4F,4F,9E), V(7F,DC,DC,A3), \ + V(66,22,22,44), V(7E,2A,2A,54), V(AB,90,90,3B), V(83,88,88,0B), \ + V(CA,46,46,8C), V(29,EE,EE,C7), V(D3,B8,B8,6B), V(3C,14,14,28), \ + V(79,DE,DE,A7), V(E2,5E,5E,BC), V(1D,0B,0B,16), V(76,DB,DB,AD), \ + V(3B,E0,E0,DB), V(56,32,32,64), V(4E,3A,3A,74), V(1E,0A,0A,14), \ + V(DB,49,49,92), V(0A,06,06,0C), V(6C,24,24,48), V(E4,5C,5C,B8), \ + V(5D,C2,C2,9F), V(6E,D3,D3,BD), V(EF,AC,AC,43), V(A6,62,62,C4), \ + V(A8,91,91,39), V(A4,95,95,31), V(37,E4,E4,D3), V(8B,79,79,F2), \ + V(32,E7,E7,D5), V(43,C8,C8,8B), V(59,37,37,6E), V(B7,6D,6D,DA), \ + V(8C,8D,8D,01), V(64,D5,D5,B1), V(D2,4E,4E,9C), V(E0,A9,A9,49), \ + V(B4,6C,6C,D8), V(FA,56,56,AC), V(07,F4,F4,F3), V(25,EA,EA,CF), \ + V(AF,65,65,CA), V(8E,7A,7A,F4), V(E9,AE,AE,47), V(18,08,08,10), \ + V(D5,BA,BA,6F), V(88,78,78,F0), V(6F,25,25,4A), V(72,2E,2E,5C), \ + V(24,1C,1C,38), V(F1,A6,A6,57), V(C7,B4,B4,73), V(51,C6,C6,97), \ + V(23,E8,E8,CB), V(7C,DD,DD,A1), V(9C,74,74,E8), V(21,1F,1F,3E), \ + V(DD,4B,4B,96), V(DC,BD,BD,61), V(86,8B,8B,0D), V(85,8A,8A,0F), \ + V(90,70,70,E0), V(42,3E,3E,7C), V(C4,B5,B5,71), V(AA,66,66,CC), \ + V(D8,48,48,90), V(05,03,03,06), V(01,F6,F6,F7), V(12,0E,0E,1C), \ + V(A3,61,61,C2), V(5F,35,35,6A), V(F9,57,57,AE), V(D0,B9,B9,69), \ + V(91,86,86,17), V(58,C1,C1,99), V(27,1D,1D,3A), V(B9,9E,9E,27), \ + V(38,E1,E1,D9), V(13,F8,F8,EB), V(B3,98,98,2B), V(33,11,11,22), \ + V(BB,69,69,D2), V(70,D9,D9,A9), V(89,8E,8E,07), V(A7,94,94,33), \ + V(B6,9B,9B,2D), V(22,1E,1E,3C), V(92,87,87,15), V(20,E9,E9,C9), \ + V(49,CE,CE,87), V(FF,55,55,AA), V(78,28,28,50), V(7A,DF,DF,A5), \ + V(8F,8C,8C,03), V(F8,A1,A1,59), V(80,89,89,09), V(17,0D,0D,1A), \ + V(DA,BF,BF,65), V(31,E6,E6,D7), V(C6,42,42,84), V(B8,68,68,D0), \ + V(C3,41,41,82), V(B0,99,99,29), V(77,2D,2D,5A), V(11,0F,0F,1E), \ + V(CB,B0,B0,7B), V(FC,54,54,A8), V(D6,BB,BB,6D), V(3A,16,16,2C) + +#define V(a,b,c,d) 0x##a##b##c##d +static const unsigned long FT0[256] = { FT }; +#undef V + +#define V(a,b,c,d) 0x##b##c##d##a +static const unsigned long FT1[256] = { FT }; +#undef V + +#define V(a,b,c,d) 0x##c##d##a##b +static const unsigned long FT2[256] = { FT }; +#undef V + +#define V(a,b,c,d) 0x##d##a##b##c +static const unsigned long FT3[256] = { FT }; +#undef V + +#undef FT + +/* + * Reverse S-box + */ +static const unsigned char RSb[256] = +{ + 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, + 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, + 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, + 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, + 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, + 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, + 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, + 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, + 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, + 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, + 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, + 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, + 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, + 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, + 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, + 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, + 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, + 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, + 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, + 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, + 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, + 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, + 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, + 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, + 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, + 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, + 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, + 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, + 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, + 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, + 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D +}; + +/* + * Reverse tables + */ +#define RT \ +\ + V(50,A7,F4,51), V(53,65,41,7E), V(C3,A4,17,1A), V(96,5E,27,3A), \ + V(CB,6B,AB,3B), V(F1,45,9D,1F), V(AB,58,FA,AC), V(93,03,E3,4B), \ + V(55,FA,30,20), V(F6,6D,76,AD), V(91,76,CC,88), V(25,4C,02,F5), \ + V(FC,D7,E5,4F), V(D7,CB,2A,C5), V(80,44,35,26), V(8F,A3,62,B5), \ + V(49,5A,B1,DE), V(67,1B,BA,25), V(98,0E,EA,45), V(E1,C0,FE,5D), \ + V(02,75,2F,C3), V(12,F0,4C,81), V(A3,97,46,8D), V(C6,F9,D3,6B), \ + V(E7,5F,8F,03), V(95,9C,92,15), V(EB,7A,6D,BF), V(DA,59,52,95), \ + V(2D,83,BE,D4), V(D3,21,74,58), V(29,69,E0,49), V(44,C8,C9,8E), \ + V(6A,89,C2,75), V(78,79,8E,F4), V(6B,3E,58,99), V(DD,71,B9,27), \ + V(B6,4F,E1,BE), V(17,AD,88,F0), V(66,AC,20,C9), V(B4,3A,CE,7D), \ + V(18,4A,DF,63), V(82,31,1A,E5), V(60,33,51,97), V(45,7F,53,62), \ + V(E0,77,64,B1), V(84,AE,6B,BB), V(1C,A0,81,FE), V(94,2B,08,F9), \ + V(58,68,48,70), V(19,FD,45,8F), V(87,6C,DE,94), V(B7,F8,7B,52), \ + V(23,D3,73,AB), V(E2,02,4B,72), V(57,8F,1F,E3), V(2A,AB,55,66), \ + V(07,28,EB,B2), V(03,C2,B5,2F), V(9A,7B,C5,86), V(A5,08,37,D3), \ + V(F2,87,28,30), V(B2,A5,BF,23), V(BA,6A,03,02), V(5C,82,16,ED), \ + V(2B,1C,CF,8A), V(92,B4,79,A7), V(F0,F2,07,F3), V(A1,E2,69,4E), \ + V(CD,F4,DA,65), V(D5,BE,05,06), V(1F,62,34,D1), V(8A,FE,A6,C4), \ + V(9D,53,2E,34), V(A0,55,F3,A2), V(32,E1,8A,05), V(75,EB,F6,A4), \ + V(39,EC,83,0B), V(AA,EF,60,40), V(06,9F,71,5E), V(51,10,6E,BD), \ + V(F9,8A,21,3E), V(3D,06,DD,96), V(AE,05,3E,DD), V(46,BD,E6,4D), \ + V(B5,8D,54,91), V(05,5D,C4,71), V(6F,D4,06,04), V(FF,15,50,60), \ + V(24,FB,98,19), V(97,E9,BD,D6), V(CC,43,40,89), V(77,9E,D9,67), \ + V(BD,42,E8,B0), V(88,8B,89,07), V(38,5B,19,E7), V(DB,EE,C8,79), \ + V(47,0A,7C,A1), V(E9,0F,42,7C), V(C9,1E,84,F8), V(00,00,00,00), \ + V(83,86,80,09), V(48,ED,2B,32), V(AC,70,11,1E), V(4E,72,5A,6C), \ + V(FB,FF,0E,FD), V(56,38,85,0F), V(1E,D5,AE,3D), V(27,39,2D,36), \ + V(64,D9,0F,0A), V(21,A6,5C,68), V(D1,54,5B,9B), V(3A,2E,36,24), \ + V(B1,67,0A,0C), V(0F,E7,57,93), V(D2,96,EE,B4), V(9E,91,9B,1B), \ + V(4F,C5,C0,80), V(A2,20,DC,61), V(69,4B,77,5A), V(16,1A,12,1C), \ + V(0A,BA,93,E2), V(E5,2A,A0,C0), V(43,E0,22,3C), V(1D,17,1B,12), \ + V(0B,0D,09,0E), V(AD,C7,8B,F2), V(B9,A8,B6,2D), V(C8,A9,1E,14), \ + V(85,19,F1,57), V(4C,07,75,AF), V(BB,DD,99,EE), V(FD,60,7F,A3), \ + V(9F,26,01,F7), V(BC,F5,72,5C), V(C5,3B,66,44), V(34,7E,FB,5B), \ + V(76,29,43,8B), V(DC,C6,23,CB), V(68,FC,ED,B6), V(63,F1,E4,B8), \ + V(CA,DC,31,D7), V(10,85,63,42), V(40,22,97,13), V(20,11,C6,84), \ + V(7D,24,4A,85), V(F8,3D,BB,D2), V(11,32,F9,AE), V(6D,A1,29,C7), \ + V(4B,2F,9E,1D), V(F3,30,B2,DC), V(EC,52,86,0D), V(D0,E3,C1,77), \ + V(6C,16,B3,2B), V(99,B9,70,A9), V(FA,48,94,11), V(22,64,E9,47), \ + V(C4,8C,FC,A8), V(1A,3F,F0,A0), V(D8,2C,7D,56), V(EF,90,33,22), \ + V(C7,4E,49,87), V(C1,D1,38,D9), V(FE,A2,CA,8C), V(36,0B,D4,98), \ + V(CF,81,F5,A6), V(28,DE,7A,A5), V(26,8E,B7,DA), V(A4,BF,AD,3F), \ + V(E4,9D,3A,2C), V(0D,92,78,50), V(9B,CC,5F,6A), V(62,46,7E,54), \ + V(C2,13,8D,F6), V(E8,B8,D8,90), V(5E,F7,39,2E), V(F5,AF,C3,82), \ + V(BE,80,5D,9F), V(7C,93,D0,69), V(A9,2D,D5,6F), V(B3,12,25,CF), \ + V(3B,99,AC,C8), V(A7,7D,18,10), V(6E,63,9C,E8), V(7B,BB,3B,DB), \ + V(09,78,26,CD), V(F4,18,59,6E), V(01,B7,9A,EC), V(A8,9A,4F,83), \ + V(65,6E,95,E6), V(7E,E6,FF,AA), V(08,CF,BC,21), V(E6,E8,15,EF), \ + V(D9,9B,E7,BA), V(CE,36,6F,4A), V(D4,09,9F,EA), V(D6,7C,B0,29), \ + V(AF,B2,A4,31), V(31,23,3F,2A), V(30,94,A5,C6), V(C0,66,A2,35), \ + V(37,BC,4E,74), V(A6,CA,82,FC), V(B0,D0,90,E0), V(15,D8,A7,33), \ + V(4A,98,04,F1), V(F7,DA,EC,41), V(0E,50,CD,7F), V(2F,F6,91,17), \ + V(8D,D6,4D,76), V(4D,B0,EF,43), V(54,4D,AA,CC), V(DF,04,96,E4), \ + V(E3,B5,D1,9E), V(1B,88,6A,4C), V(B8,1F,2C,C1), V(7F,51,65,46), \ + V(04,EA,5E,9D), V(5D,35,8C,01), V(73,74,87,FA), V(2E,41,0B,FB), \ + V(5A,1D,67,B3), V(52,D2,DB,92), V(33,56,10,E9), V(13,47,D6,6D), \ + V(8C,61,D7,9A), V(7A,0C,A1,37), V(8E,14,F8,59), V(89,3C,13,EB), \ + V(EE,27,A9,CE), V(35,C9,61,B7), V(ED,E5,1C,E1), V(3C,B1,47,7A), \ + V(59,DF,D2,9C), V(3F,73,F2,55), V(79,CE,14,18), V(BF,37,C7,73), \ + V(EA,CD,F7,53), V(5B,AA,FD,5F), V(14,6F,3D,DF), V(86,DB,44,78), \ + V(81,F3,AF,CA), V(3E,C4,68,B9), V(2C,34,24,38), V(5F,40,A3,C2), \ + V(72,C3,1D,16), V(0C,25,E2,BC), V(8B,49,3C,28), V(41,95,0D,FF), \ + V(71,01,A8,39), V(DE,B3,0C,08), V(9C,E4,B4,D8), V(90,C1,56,64), \ + V(61,84,CB,7B), V(70,B6,32,D5), V(74,5C,6C,48), V(42,57,B8,D0) + +#define V(a,b,c,d) 0x##a##b##c##d +static const unsigned long RT0[256] = { RT }; +#undef V + +#define V(a,b,c,d) 0x##b##c##d##a +static const unsigned long RT1[256] = { RT }; +#undef V + +#define V(a,b,c,d) 0x##c##d##a##b +static const unsigned long RT2[256] = { RT }; +#undef V + +#define V(a,b,c,d) 0x##d##a##b##c +static const unsigned long RT3[256] = { RT }; +#undef V + +#undef RT + +/* + * Round constants + */ +static const unsigned long RCON[10] = +{ + 0x00000001, 0x00000002, 0x00000004, 0x00000008, + 0x00000010, 0x00000020, 0x00000040, 0x00000080, + 0x0000001B, 0x00000036 +}; + +/* + * AES key schedule (encryption) + */ +int aes_setkey_enc( aes_context *ctx, const unsigned char *key, unsigned int keysize ) +{ + unsigned int i; + unsigned long *RK; + + switch( keysize ) + { + case 128: ctx->nr = 10; break; + case 192: ctx->nr = 12; break; + case 256: ctx->nr = 14; break; + default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH ); + } + + ctx->rk = RK = ctx->buf; + + for( i = 0; i < (keysize >> 5); i++ ) + { + GET_ULONG_LE( RK[i], key, i << 2 ); + } + + switch( ctx->nr ) + { + case 10: + + for( i = 0; i < 10; i++, RK += 4 ) + { + RK[4] = RK[0] ^ RCON[i] ^ + ( (unsigned long) FSb[ ( RK[3] >> 8 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( RK[3] >> 16 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( RK[3] >> 24 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( RK[3] ) & 0xFF ] << 24 ); + + RK[5] = RK[1] ^ RK[4]; + RK[6] = RK[2] ^ RK[5]; + RK[7] = RK[3] ^ RK[6]; + } + break; + + case 12: + + for( i = 0; i < 8; i++, RK += 6 ) + { + RK[6] = RK[0] ^ RCON[i] ^ + ( (unsigned long) FSb[ ( RK[5] >> 8 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( RK[5] >> 16 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( RK[5] >> 24 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( RK[5] ) & 0xFF ] << 24 ); + + RK[7] = RK[1] ^ RK[6]; + RK[8] = RK[2] ^ RK[7]; + RK[9] = RK[3] ^ RK[8]; + RK[10] = RK[4] ^ RK[9]; + RK[11] = RK[5] ^ RK[10]; + } + break; + + case 14: + + for( i = 0; i < 7; i++, RK += 8 ) + { + RK[8] = RK[0] ^ RCON[i] ^ + ( (unsigned long) FSb[ ( RK[7] >> 8 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( RK[7] >> 16 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( RK[7] >> 24 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( RK[7] ) & 0xFF ] << 24 ); + + RK[9] = RK[1] ^ RK[8]; + RK[10] = RK[2] ^ RK[9]; + RK[11] = RK[3] ^ RK[10]; + + RK[12] = RK[4] ^ + ( (unsigned long) FSb[ ( RK[11] ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( RK[11] >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( RK[11] >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( RK[11] >> 24 ) & 0xFF ] << 24 ); + + RK[13] = RK[5] ^ RK[12]; + RK[14] = RK[6] ^ RK[13]; + RK[15] = RK[7] ^ RK[14]; + } + break; + + default: + + break; + } + + return( 0 ); +} + +/* + * AES key schedule (decryption) + */ +int aes_setkey_dec( aes_context *ctx, const unsigned char *key, unsigned int keysize ) +{ + int i, j; + aes_context cty; + unsigned long *RK; + unsigned long *SK; + int ret; + + switch( keysize ) + { + case 128: ctx->nr = 10; break; + case 192: ctx->nr = 12; break; + case 256: ctx->nr = 14; break; + default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH ); + } + + ctx->rk = RK = ctx->buf; + + ret = aes_setkey_enc( &cty, key, keysize ); + if( ret != 0 ) + return( ret ); + + SK = cty.rk + cty.nr * 4; + + *RK++ = *SK++; + *RK++ = *SK++; + *RK++ = *SK++; + *RK++ = *SK++; + + for( i = ctx->nr - 1, SK -= 8; i > 0; i--, SK -= 8 ) + { + for( j = 0; j < 4; j++, SK++ ) + { + *RK++ = RT0[ FSb[ ( *SK ) & 0xFF ] ] ^ + RT1[ FSb[ ( *SK >> 8 ) & 0xFF ] ] ^ + RT2[ FSb[ ( *SK >> 16 ) & 0xFF ] ] ^ + RT3[ FSb[ ( *SK >> 24 ) & 0xFF ] ]; + } + } + + *RK++ = *SK++; + *RK++ = *SK++; + *RK++ = *SK++; + *RK++ = *SK++; + + memset( &cty, 0, sizeof( aes_context ) ); + + return( 0 ); +} + +#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ +{ \ + X0 = *RK++ ^ FT0[ ( Y0 ) & 0xFF ] ^ \ + FT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y3 >> 24 ) & 0xFF ]; \ + \ + X1 = *RK++ ^ FT0[ ( Y1 ) & 0xFF ] ^ \ + FT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y0 >> 24 ) & 0xFF ]; \ + \ + X2 = *RK++ ^ FT0[ ( Y2 ) & 0xFF ] ^ \ + FT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y1 >> 24 ) & 0xFF ]; \ + \ + X3 = *RK++ ^ FT0[ ( Y3 ) & 0xFF ] ^ \ + FT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ + FT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ + FT3[ ( Y2 >> 24 ) & 0xFF ]; \ +} + +#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \ +{ \ + X0 = *RK++ ^ RT0[ ( Y0 ) & 0xFF ] ^ \ + RT1[ ( Y3 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y2 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y1 >> 24 ) & 0xFF ]; \ + \ + X1 = *RK++ ^ RT0[ ( Y1 ) & 0xFF ] ^ \ + RT1[ ( Y0 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y3 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y2 >> 24 ) & 0xFF ]; \ + \ + X2 = *RK++ ^ RT0[ ( Y2 ) & 0xFF ] ^ \ + RT1[ ( Y1 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y0 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y3 >> 24 ) & 0xFF ]; \ + \ + X3 = *RK++ ^ RT0[ ( Y3 ) & 0xFF ] ^ \ + RT1[ ( Y2 >> 8 ) & 0xFF ] ^ \ + RT2[ ( Y1 >> 16 ) & 0xFF ] ^ \ + RT3[ ( Y0 >> 24 ) & 0xFF ]; \ +} + +/* + * AES-ECB block encryption/decryption + */ +int aes_crypt_ecb( aes_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ) +{ + int i; + unsigned long *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; + + RK = ctx->rk; + + GET_ULONG_LE( X0, input, 0 ); X0 ^= *RK++; + GET_ULONG_LE( X1, input, 4 ); X1 ^= *RK++; + GET_ULONG_LE( X2, input, 8 ); X2 ^= *RK++; + GET_ULONG_LE( X3, input, 12 ); X3 ^= *RK++; + + if( mode == AES_DECRYPT ) + { + for( i = (ctx->nr >> 1) - 1; i > 0; i-- ) + { + AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); + AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 ); + } + + AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); + + X0 = *RK++ ^ \ + ( (unsigned long) RSb[ ( Y0 ) & 0xFF ] ) ^ + ( (unsigned long) RSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) RSb[ ( Y1 >> 24 ) & 0xFF ] << 24 ); + + X1 = *RK++ ^ \ + ( (unsigned long) RSb[ ( Y1 ) & 0xFF ] ) ^ + ( (unsigned long) RSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) RSb[ ( Y2 >> 24 ) & 0xFF ] << 24 ); + + X2 = *RK++ ^ \ + ( (unsigned long) RSb[ ( Y2 ) & 0xFF ] ) ^ + ( (unsigned long) RSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) RSb[ ( Y3 >> 24 ) & 0xFF ] << 24 ); + + X3 = *RK++ ^ \ + ( (unsigned long) RSb[ ( Y3 ) & 0xFF ] ) ^ + ( (unsigned long) RSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) RSb[ ( Y0 >> 24 ) & 0xFF ] << 24 ); + } + else /* AES_ENCRYPT */ + { + for( i = (ctx->nr >> 1) - 1; i > 0; i-- ) + { + AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); + AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 ); + } + + AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 ); + + X0 = *RK++ ^ \ + ( (unsigned long) FSb[ ( Y0 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( Y3 >> 24 ) & 0xFF ] << 24 ); + + X1 = *RK++ ^ \ + ( (unsigned long) FSb[ ( Y1 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( Y0 >> 24 ) & 0xFF ] << 24 ); + + X2 = *RK++ ^ \ + ( (unsigned long) FSb[ ( Y2 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( Y1 >> 24 ) & 0xFF ] << 24 ); + + X3 = *RK++ ^ \ + ( (unsigned long) FSb[ ( Y3 ) & 0xFF ] ) ^ + ( (unsigned long) FSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^ + ( (unsigned long) FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^ + ( (unsigned long) FSb[ ( Y2 >> 24 ) & 0xFF ] << 24 ); + } + + PUT_ULONG_LE( X0, output, 0 ); + PUT_ULONG_LE( X1, output, 4 ); + PUT_ULONG_LE( X2, output, 8 ); + PUT_ULONG_LE( X3, output, 12 ); + + return( 0 ); +} + +/* + * AES-CBC buffer encryption/decryption + */ +int aes_crypt_cbc( aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ) +{ + int i; + unsigned char temp[16]; + + if( length % 16 ) + return( POLARSSL_ERR_AES_INVALID_INPUT_LENGTH ); + + if( mode == AES_DECRYPT ) + { + while( length > 0 ) + { + memcpy( temp, input, 16 ); + aes_crypt_ecb( ctx, mode, input, output ); + + for( i = 0; i < 16; i++ ) + output[i] = (unsigned char)( output[i] ^ iv[i] ); + + memcpy( iv, temp, 16 ); + + input += 16; + output += 16; + length -= 16; + } + } + else + { + while( length > 0 ) + { + for( i = 0; i < 16; i++ ) + output[i] = (unsigned char)( input[i] ^ iv[i] ); + + aes_crypt_ecb( ctx, mode, output, output ); + memcpy( iv, output, 16 ); + + input += 16; + output += 16; + length -= 16; + } + } + + return( 0 ); +} + +/* + * AES-CTR buffer encryption/decryption + */ +int aes_crypt_ctr( aes_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[16], + unsigned char stream_block[16], + const unsigned char *input, + unsigned char *output ) +{ + int c, i, cb; + size_t n = *nc_off; + + while( length-- ) + { + if( n == 0 ) { + aes_crypt_ecb( ctx, AES_ENCRYPT, nonce_counter, stream_block ); + + i = 15; + do { + nonce_counter[i]++; + cb = nonce_counter[i] == 0; + } while( i-- && cb ); + + } + c = *input++; + *output++ = (unsigned char)( c ^ stream_block[n] ); + + n = (n + 1) & 0x0F; + } + + *nc_off = n; + + return( 0 ); +} diff --git a/scetool/aes.h b/scetool/aes.h new file mode 100644 index 0000000000..efac0130bf --- /dev/null +++ b/scetool/aes.h @@ -0,0 +1,144 @@ +/** + * \file aes.h + * + * \brief AES block cipher + * + * Copyright (C) 2006-2010, Brainspark B.V. + * + * This file is part of PolarSSL (http://www.polarssl.org) + * Lead Maintainer: Paul Bakker + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#ifndef POLARSSL_AES_H +#define POLARSSL_AES_H + +#include + +#define AES_ENCRYPT 1 +#define AES_DECRYPT 0 + +#define POLARSSL_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ +#define POLARSSL_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ + +/** + * \brief AES context structure + */ +typedef struct +{ + int nr; /*!< number of rounds */ + unsigned long *rk; /*!< AES round keys */ + unsigned long buf[68]; /*!< unaligned data */ +} +aes_context; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief AES key schedule (encryption) + * + * \param ctx AES context to be initialized + * \param key encryption key + * \param keysize must be 128, 192 or 256 + * + * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH + */ +int aes_setkey_enc( aes_context *ctx, const unsigned char *key, unsigned int keysize ); + +/** + * \brief AES key schedule (decryption) + * + * \param ctx AES context to be initialized + * \param key decryption key + * \param keysize must be 128, 192 or 256 + * + * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH + */ +int aes_setkey_dec( aes_context *ctx, const unsigned char *key, unsigned int keysize ); + +/** + * \brief AES-ECB block encryption/decryption + * + * \param ctx AES context + * \param mode AES_ENCRYPT or AES_DECRYPT + * \param input 16-byte input block + * \param output 16-byte output block + * + * \return 0 if successful + */ +int aes_crypt_ecb( aes_context *ctx, + int mode, + const unsigned char input[16], + unsigned char output[16] ); + +/** + * \brief AES-CBC buffer encryption/decryption + * Length should be a multiple of the block + * size (16 bytes) + * + * \param ctx AES context + * \param mode AES_ENCRYPT or AES_DECRYPT + * \param length length of the input data + * \param iv initialization vector (updated after use) + * \param input buffer holding the input data + * \param output buffer holding the output data + * + * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_INPUT_LENGTH + */ +int aes_crypt_cbc( aes_context *ctx, + int mode, + size_t length, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); + +/* + * \brief AES-CTR buffer encryption/decryption + * + * Warning: You have to keep the maximum use of your counter in mind! + * + * Note: Due to the nature of CTR you should use the same key schedule for + * both encryption and decryption. So a context initialized with + * aes_setkey_enc() for both AES_ENCRYPT and AES_DECRYPT. + * + * \param length The length of the data + * \param nc_off The offset in the current stream_block (for resuming + * within current cipher stream). The offset pointer to + * should be 0 at the start of a stream. + * \param nonce_counter The 128-bit nonce and counter. + * \param stream_block The saved stream-block for resuming. Is overwritten + * by the function. + * \param input The input data stream + * \param output The output data stream + * + * \return 0 if successful + */ +int aes_crypt_ctr( aes_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[16], + unsigned char stream_block[16], + const unsigned char *input, + unsigned char *output ); + +#ifdef __cplusplus +} +#endif + +#endif /* aes.h */ diff --git a/scetool/aes_omac.h b/scetool/aes_omac.h new file mode 100644 index 0000000000..d8c8347584 --- /dev/null +++ b/scetool/aes_omac.h @@ -0,0 +1,10 @@ +#ifndef _AES_OMAC_H_ +#define _AES_OMAC_H_ + +#include "types.h" + +#define AES_OMAC1_DIGEST_SIZE 0x10 + +void aes_omac1(scetool::u8 *digest, scetool::u8 *input, scetool::u32 length, scetool::u8 *key, scetool::u32 keybits); + +#endif diff --git a/scetool/bn.cpp b/scetool/bn.cpp new file mode 100644 index 0000000000..168270dad0 --- /dev/null +++ b/scetool/bn.cpp @@ -0,0 +1,200 @@ +// Copyright 2007,2008,2010 Segher Boessenkool +// Licensed under the terms of the GNU GPL, version 2 +// http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt + +#include +#include + +#include "types.h" + +void bn_print(char *name, scetool::u8 *a, scetool::u32 n) +{ + scetool::u32 i; + + printf("%s = ", name); + + for (i = 0; i < n; i++) + printf("%02x", a[i]); + + printf("\n"); +} + +static void bn_zero(scetool::u8 *d, scetool::u32 n) +{ + memset(d, 0, n); +} + +void bn_copy(scetool::u8 *d, scetool::u8 *a, scetool::u32 n) +{ + memcpy(d, a, n); +} + +int bn_compare(scetool::u8 *a, scetool::u8 *b, scetool::u32 n) +{ + scetool::u32 i; + + for (i = 0; i < n; i++) { + if (a[i] < b[i]) + return -1; + if (a[i] > b[i]) + return 1; + } + + return 0; +} + +static scetool::u8 bn_add_1(scetool::u8 *d, scetool::u8 *a, scetool::u8 *b, scetool::u32 n) +{ + scetool::u32 i; + scetool::u32 dig; + scetool::u8 c; + + c = 0; + for (i = n - 1; i < n; i--) { + dig = a[i] + b[i] + c; + c = dig >> 8; + d[i] = dig; + } + + return c; +} + +static scetool::u8 bn_sub_1(scetool::u8 *d, scetool::u8 *a, scetool::u8 *b, scetool::u32 n) +{ + scetool::u32 i; + scetool::u32 dig; + scetool::u8 c; + + c = 1; + for (i = n - 1; i < n; i--) { + dig = a[i] + 255 - b[i] + c; + c = dig >> 8; + d[i] = dig; + } + + return 1 - c; +} + +void bn_reduce(scetool::u8 *d, scetool::u8 *N, scetool::u32 n) +{ + if (bn_compare(d, N, n) >= 0) + bn_sub_1(d, d, N, n); +} + +void bn_add(scetool::u8 *d, scetool::u8 *a, scetool::u8 *b, scetool::u8 *N, scetool::u32 n) +{ + if (bn_add_1(d, a, b, n)) + bn_sub_1(d, d, N, n); + + bn_reduce(d, N, n); +} + +void bn_sub(scetool::u8 *d, scetool::u8 *a, scetool::u8 *b, scetool::u8 *N, scetool::u32 n) +{ + if (bn_sub_1(d, a, b, n)) + bn_add_1(d, d, N, n); +} + +static const scetool::u8 inv256[0x80] = { + 0x01, 0xab, 0xcd, 0xb7, 0x39, 0xa3, 0xc5, 0xef, + 0xf1, 0x1b, 0x3d, 0xa7, 0x29, 0x13, 0x35, 0xdf, + 0xe1, 0x8b, 0xad, 0x97, 0x19, 0x83, 0xa5, 0xcf, + 0xd1, 0xfb, 0x1d, 0x87, 0x09, 0xf3, 0x15, 0xbf, + 0xc1, 0x6b, 0x8d, 0x77, 0xf9, 0x63, 0x85, 0xaf, + 0xb1, 0xdb, 0xfd, 0x67, 0xe9, 0xd3, 0xf5, 0x9f, + 0xa1, 0x4b, 0x6d, 0x57, 0xd9, 0x43, 0x65, 0x8f, + 0x91, 0xbb, 0xdd, 0x47, 0xc9, 0xb3, 0xd5, 0x7f, + 0x81, 0x2b, 0x4d, 0x37, 0xb9, 0x23, 0x45, 0x6f, + 0x71, 0x9b, 0xbd, 0x27, 0xa9, 0x93, 0xb5, 0x5f, + 0x61, 0x0b, 0x2d, 0x17, 0x99, 0x03, 0x25, 0x4f, + 0x51, 0x7b, 0x9d, 0x07, 0x89, 0x73, 0x95, 0x3f, + 0x41, 0xeb, 0x0d, 0xf7, 0x79, 0xe3, 0x05, 0x2f, + 0x31, 0x5b, 0x7d, 0xe7, 0x69, 0x53, 0x75, 0x1f, + 0x21, 0xcb, 0xed, 0xd7, 0x59, 0xc3, 0xe5, 0x0f, + 0x11, 0x3b, 0x5d, 0xc7, 0x49, 0x33, 0x55, 0xff, +}; + +static void bn_mon_muladd_dig(scetool::u8 *d, scetool::u8 *a, scetool::u8 b, scetool::u8 *N, scetool::u32 n) +{ + scetool::u32 dig; + scetool::u32 i; + + scetool::u8 z = -(d[n-1] + a[n-1]*b) * inv256[N[n-1]/2]; + + dig = d[n-1] + a[n-1]*b + N[n-1]*z; + dig >>= 8; + + for (i = n - 2; i < n; i--) { + dig += d[i] + a[i]*b + N[i]*z; + d[i+1] = dig; + dig >>= 8; + } + + d[0] = dig; + dig >>= 8; + + if (dig) + bn_sub_1(d, d, N, n); + + bn_reduce(d, N, n); +} + +void bn_mon_mul(scetool::u8 *d, scetool::u8 *a, scetool::u8 *b, scetool::u8 *N, scetool::u32 n) +{ + scetool::u8 t[512]; + scetool::u32 i; + + bn_zero(t, n); + + for (i = n - 1; i < n; i--) + bn_mon_muladd_dig(t, a, b[i], N, n); + + bn_copy(d, t, n); +} + +void bn_to_mon(scetool::u8 *d, scetool::u8 *N, scetool::u32 n) +{ + scetool::u32 i; + + for (i = 0; i < 8*n; i++) + bn_add(d, d, d, N, n); +} + +void bn_from_mon(scetool::u8 *d, scetool::u8 *N, scetool::u32 n) +{ + scetool::u8 t[512]; + + bn_zero(t, n); + t[n-1] = 1; + bn_mon_mul(d, d, t, N, n); +} + +static void bn_mon_exp(scetool::u8 *d, scetool::u8 *a, scetool::u8 *N, scetool::u32 n, scetool::u8 *e, scetool::u32 en) +{ + scetool::u8 t[512]; + scetool::u32 i; + scetool::u8 mask; + + bn_zero(d, n); + d[n-1] = 1; + bn_to_mon(d, N, n); + + for (i = 0; i < en; i++) + for (mask = 0x80; mask != 0; mask >>= 1) { + bn_mon_mul(t, d, d, N, n); + if ((e[i] & mask) != 0) + bn_mon_mul(d, t, a, N, n); + else + bn_copy(d, t, n); + } +} + +void bn_mon_inv(scetool::u8 *d, scetool::u8 *a, scetool::u8 *N, scetool::u32 n) +{ + scetool::u8 t[512], s[512]; + + bn_zero(s, n); + s[n-1] = 2; + bn_sub_1(t, N, s, n); + bn_mon_exp(d, a, N, n, t, n); +} diff --git a/scetool/config.h b/scetool/config.h new file mode 100644 index 0000000000..d2469affd3 --- /dev/null +++ b/scetool/config.h @@ -0,0 +1,76 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _CONFIG_H_ +#define _CONFIG_H_ + +/*! scetool base version. */ +#define SCETOOL_VERSION_BASE "0.2.9" + +/*! Private build. */ +//#define CONFIG_PRIVATE_BUILD +#define BUILD_FOR "naehrwert" +//#define BUILD_FOR "unicorns" + +/*! scetool version. */ +#ifdef CONFIG_PRIVATE_BUILD + #ifdef BUILD_FOR + #define SCETOOL_VERSION SCETOOL_VERSION_BASE " " + #else + #error Specify a name in BUILD_FOR. + #endif +#else + #define SCETOOL_VERSION SCETOOL_VERSION_BASE " " +#endif + +/*! Private build options. */ +#ifdef CONFIG_PRIVATE_BUILD + #define CONFIG_CUSTOM_INDIV_SEED + #define CONFIG_DUMP_INDIV_SEED +#endif + +#if 0 +/*! scetool API. */ +#define CONFIG_EXPORTS +#ifdef CONFIG_EXPORTS +#define SCETOOL_API __declspec(dllexport) +#else +#define SCETOOL_API __declspec(dllimport) +#endif +#endif + +/*! NPDRM watermark text (16 bytes exactly). */ +//"I like kittens !" +#define CONFIG_NPDRM_WATERMARK "watermarktrololo" + +/*! Environment variables. */ +#define CONFIG_ENV_PS3 "PS3" + +/*! Path configurations. */ +#define CONFIG_KEYS_FILE "keys" +#define CONFIG_KEYS_PATH "./data" +#define CONFIG_CURVES_FILE "ldr_curves" +#define CONFIG_CURVES_PATH "./data" +#define CONFIG_VSH_CURVES_FILE "vsh_curves" +#define CONFIG_VSH_CURVES_PATH "./data" +#define CONFIG_IDPS_FILE "idps" +#define CONFIG_IDPS_PATH "./data" +#define CONFIG_ACT_DAT_FILE "act.dat" +#define CONFIG_ACT_DAT_PATH "./data" +#define CONFIG_RIF_FILE_EXT ".rif" +#define CONFIG_RIF_PATH "./rifs" +#define CONFIG_RAP_FILE_EXT ".rap" +#define CONFIG_RAP_PATH "./raps" + +/*! Key names. */ +#define CONFIG_NP_TID_KNAME "NP_tid" +#define CONFIG_NP_CI_KNAME "NP_ci" +#define CONFIG_NP_KLIC_FREE_KNAME "NP_klic_free" +#define CONFIG_NP_KLIC_KEY_KNAME "NP_klic_key" +#define CONFIG_NP_IDPS_CONST_KNAME "NP_idps_const" +#define CONFIG_NP_RIF_KEY_KNAME "NP_rif_key" +#define CONFIG_NP_SIG_KNAME "NP_sig" + +#endif diff --git a/scetool/ecdsa.h b/scetool/ecdsa.h new file mode 100644 index 0000000000..9bf232ecc0 --- /dev/null +++ b/scetool/ecdsa.h @@ -0,0 +1,10 @@ +#ifndef _ECDSA_H_ +#define _ECDSA_H_ + +int ecdsa_set_curve(scetool::u32 type); +void ecdsa_set_pub(scetool::u8 *Q); +void ecdsa_set_priv(scetool::u8 *k); +int ecdsa_verify(scetool::u8 *hash, scetool::u8 *R, scetool::u8 *S); +void ecdsa_sign(scetool::u8 *hash, scetool::u8 *R, scetool::u8 *S); + +#endif diff --git a/scetool/elf.h b/scetool/elf.h new file mode 100644 index 0000000000..7deff0b3f2 --- /dev/null +++ b/scetool/elf.h @@ -0,0 +1,2423 @@ +#ifndef _ELF_H_ +#define _ELF_H_ + +/* Standard ELF types. */ + +#include "types.h" + +/* Type for a 16-bit quantity. */ +typedef scetool::u16 Elf32_Half; +typedef scetool::u16 Elf64_Half; + +/* Types for signed and unsigned 32-bit quantities. */ +typedef scetool::u32 Elf32_Word; +typedef scetool::s32 Elf32_Sword; +typedef scetool::u32 Elf64_Word; +typedef scetool::s32 Elf64_Sword; + +/* Types for signed and unsigned 64-bit quantities. */ +typedef scetool::u64 Elf32_Xword; +typedef scetool::s64 Elf32_Sxword; +typedef scetool::u64 Elf64_Xword; +typedef scetool::s64 Elf64_Sxword; + +/* Type of addresses. */ +typedef scetool::u32 Elf32_Addr; +typedef scetool::u64 Elf64_Addr; + +/* Type of file offsets. */ +typedef scetool::u32 Elf32_Off; +typedef scetool::u64 Elf64_Off; + +/* Type for section indices, which are 16-bit quantities. */ +typedef scetool::u16 Elf32_Section; +typedef scetool::u16 Elf64_Section; + +/* Type for version symbol information. */ +typedef Elf32_Half Elf32_Versym; +typedef Elf64_Half Elf64_Versym; + + +/* The ELF file header. This appears at the start of every ELF file. */ + +#define EI_NIDENT (16) + +typedef struct +{ + unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */ + Elf32_Half e_type; /* Object file type */ + Elf32_Half e_machine; /* Architecture */ + Elf32_Word e_version; /* Object file version */ + Elf32_Addr e_entry; /* Entry point virtual address */ + Elf32_Off e_phoff; /* Program header table file offset */ + Elf32_Off e_shoff; /* Section header table file offset */ + Elf32_Word e_flags; /* Processor-specific flags */ + Elf32_Half e_ehsize; /* ELF header size in bytes */ + Elf32_Half e_phentsize; /* Program header table entry size */ + Elf32_Half e_phnum; /* Program header table entry count */ + Elf32_Half e_shentsize; /* Section header table entry size */ + Elf32_Half e_shnum; /* Section header table entry count */ + Elf32_Half e_shstrndx; /* Section header string table index */ +} Elf32_Ehdr; +#ifdef NOCOMPILE +typedef struct +{ + unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */ + Elf64_Half e_type; /* Object file type */ + Elf64_Half e_machine; /* Architecture */ + Elf64_Word e_version; /* Object file version */ + Elf64_Addr e_entry; /* Entry point virtual address */ + Elf64_Off e_phoff; /* Program header table file offset */ + Elf64_Off e_shoff; /* Section header table file offset */ + Elf64_Word e_flags; /* Processor-specific flags */ + Elf64_Half e_ehsize; /* ELF header size in bytes */ + Elf64_Half e_phentsize; /* Program header table entry size */ + Elf64_Half e_phnum; /* Program header table entry count */ + Elf64_Half e_shentsize; /* Section header table entry size */ + Elf64_Half e_shnum; /* Section header table entry count */ + Elf64_Half e_shstrndx; /* Section header string table index */ +} Elf64_Ehdr; +#endif +/* Fields in the e_ident array. The EI_* macros are indices into the + array. The macros under each EI_* macro are the values the byte + may have. */ + +#define EI_MAG0 0 /* File identification byte 0 index */ +#define ELFMAG0 0x7f /* Magic number byte 0 */ + +#define EI_MAG1 1 /* File identification byte 1 index */ +#define ELFMAG1 'E' /* Magic number byte 1 */ + +#define EI_MAG2 2 /* File identification byte 2 index */ +#define ELFMAG2 'L' /* Magic number byte 2 */ + +#define EI_MAG3 3 /* File identification byte 3 index */ +#define ELFMAG3 'F' /* Magic number byte 3 */ + +/* Conglomeration of the identification bytes, for easy testing as a word. */ +#define ELFMAG "\177ELF" +#define SELFMAG 4 + +#define EI_CLASS 4 /* File class byte index */ +#define ELFCLASSNONE 0 /* Invalid class */ +#define ELFCLASs32 1 /* 32-bit objects */ +#define ELFCLASs64 2 /* 64-bit objects */ +#define ELFCLASSNUM 3 + +#define EI_DATA 5 /* Data encoding byte index */ +#define ELFDATANONE 0 /* Invalid data encoding */ +#define ELFDATA2LSB 1 /* 2's complement, little endian */ +#define ELFDATA2MSB 2 /* 2's complement, big endian */ +#define ELFDATANUM 3 + +#define EI_VERSION 6 /* File version byte index */ + /* Value must be EV_CURRENT */ + +#define EI_OSABI 7 /* OS ABI identification */ +#define ELFOSABI_NONE 0 /* UNIX System V ABI */ +#define ELFOSABI_SYSV 0 /* Alias. */ +#define ELFOSABI_HPUX 1 /* HP-UX */ +#define ELFOSABI_NETBSD 2 /* NetBSD. */ +#define ELFOSABI_LINUX 3 /* Linux. */ +#define ELFOSABI_SOLARIS 6 /* Sun Solaris. */ +#define ELFOSABI_AIX 7 /* IBM AIX. */ +#define ELFOSABI_IRIX 8 /* SGI Irix. */ +#define ELFOSABI_FREEBSD 9 /* FreeBSD. */ +#define ELFOSABI_TRu64 10 /* Compaq TRscetool::u64 UNIX. */ +#define ELFOSABI_MODESTO 11 /* Novell Modesto. */ +#define ELFOSABI_OPENBSD 12 /* OpenBSD. */ +#define ELFOSABI_ARM 97 /* ARM */ +#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */ + +#define EI_ABIVERSION 8 /* ABI version */ + +#define EI_PAD 9 /* Byte index of padding bytes */ + +/* Legal values for e_type (object file type). */ + +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* Relocatable file */ +#define ET_EXEC 2 /* Executable file */ +#define ET_DYN 3 /* Shared object file */ +#define ET_CORE 4 /* Core file */ +#define ET_NUM 5 /* Number of defined types */ +#define ET_LOOS 0xfe00 /* OS-specific range start */ +#define ET_HIOS 0xfeff /* OS-specific range end */ +#define ET_LOPROC 0xff00 /* Processor-specific range start */ +#define ET_HIPROC 0xffff /* Processor-specific range end */ + +/* Legal values for e_machine (architecture). */ + +#define EM_NONE 0 /* No machine */ +#define EM_M32 1 /* AT&T WE 32100 */ +#define EM_SPARC 2 /* SUN SPARC */ +#define EM_386 3 /* Intel 80386 */ +#define EM_68K 4 /* Motorola m68k family */ +#define EM_88K 5 /* Motorola m88k family */ +#define EM_486 6 /* Intel 80486 */ +#define EM_860 7 /* Intel 80860 */ +#define EM_MIPS 8 /* MIPS R3000 big-endian */ +#define EM_S370 9 /* IBM System/370 */ +#define EM_MIPS_RS3_LE 10 /* MIPS R3000 little-endian */ + +#define EM_PARISC 15 /* HPPA */ +#define EM_VPP500 17 /* Fujitsu VPP500 */ +#define EM_SPARC32PLUS 18 /* Sun's "v8plus" */ +#define EM_960 19 /* Intel 80960 */ +#define EM_PPC 20 /* PowerPC */ +#define EM_PPC64 21 /* PowerPC 64-bit */ +#define EM_S390 22 /* IBM S390 */ +#define EM_SPU 23 /* Cell BE SPU. */ +#define EM_V800 36 /* NEC V800 series */ +#define EM_FR20 37 /* Fujitsu FR20 */ +#define EM_RH32 38 /* TRW RH-32 */ +#define EM_RCE 39 /* Motorola RCE */ +#define EM_ARM 40 /* ARM */ +#define EM_FAKE_ALPHA 41 /* Digital Alpha */ +#define EM_SH 42 /* Hitachi SH */ +#define EM_SPARCV9 43 /* SPARC v9 64-bit */ +#define EM_TRICORE 44 /* Siemens Tricore */ +#define EM_ARC 45 /* Argonaut RISC Core */ +#define EM_H8_300 46 /* Hitachi H8/300 */ +#define EM_H8_300H 47 /* Hitachi H8/300H */ +#define EM_H8S 48 /* Hitachi H8S */ +#define EM_H8_500 49 /* Hitachi H8/500 */ +#define EM_IA_64 50 /* Intel Merced */ +#define EM_MIPS_X 51 /* Stanford MIPS-X */ +#define EM_COLDFIRE 52 /* Motorola Coldfire */ +#define EM_68HC12 53 /* Motorola M68HC12 */ +#define EM_MMA 54 /* Fujitsu MMA Multimedia Accelerator*/ +#define EM_PCP 55 /* Siemens PCP */ +#define EM_NCPU 56 /* Sony nCPU embeeded RISC */ +#define EM_NDR1 57 /* Denso NDR1 microprocessor */ +#define EM_STARCORE 58 /* Motorola Start*Core processor */ +#define EM_ME16 59 /* Toyota ME16 processor */ +#define EM_ST100 60 /* STMicroelectronic ST100 processor */ +#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam*/ +#define EM_X86_64 62 /* AMD x86-64 architecture */ +#define EM_PDSP 63 /* Sony DSP Processor */ + +#define EM_FX66 66 /* Siemens FX66 microcontroller */ +#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */ +#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */ +#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller */ +#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller */ +#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller */ +#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller */ +#define EM_SVX 73 /* Silicon Graphics SVx */ +#define EM_ST19 74 /* STMicroelectronics ST19 8 bit mc */ +#define EM_VAX 75 /* Digital VAX */ +#define EM_CRIS 76 /* Axis Communications 32-bit embedded processor */ +#define EM_JAVELIN 77 /* Infineon Technologies 32-bit embedded processor */ +#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor */ +#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor */ +#define EM_MMIX 80 /* Donald Knuth's educational 64-bit processor */ +#define EM_HUANY 81 /* Harvard University machine-independent object files */ +#define EM_PRISM 82 /* SiTera Prism */ +#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller */ +#define EM_FR30 84 /* Fujitsu FR30 */ +#define EM_D10V 85 /* Mitsubishi D10V */ +#define EM_D30V 86 /* Mitsubishi D30V */ +#define EM_V850 87 /* NEC v850 */ +#define EM_M32R 88 /* Mitsubishi M32R */ +#define EM_MN10300 89 /* Matsushita MN10300 */ +#define EM_MN10200 90 /* Matsushita MN10200 */ +#define EM_PJ 91 /* picoJava */ +#define EM_OPENRISC 92 /* OpenRISC 32-bit embedded processor */ +#define EM_ARC_A5 93 /* ARC Cores Tangent-A5 */ +#define EM_XTENSA 94 /* Tensilica Xtensa Architecture */ +#define EM_NUM 95 + +/* If it is necessary to assign new unofficial EM_* values, please + pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the + chances of collision with official or non-GNU unofficial values. */ + +#define EM_ALPHA 0x9026 + +/* Legal values for e_version (version). */ + +#define EV_NONE 0 /* Invalid ELF version */ +#define EV_CURRENT 1 /* Current version */ +#define EV_NUM 2 + +/* Section header. */ + +typedef struct +{ + Elf32_Word sh_name; /* Section name (string tbl index) */ + Elf32_Word sh_type; /* Section type */ + Elf32_Word sh_flags; /* Section flags */ + Elf32_Addr sh_addr; /* Section virtual addr at execution */ + Elf32_Off sh_offset; /* Section file offset */ + Elf32_Word sh_size; /* Section size in bytes */ + Elf32_Word sh_link; /* Link to another section */ + Elf32_Word sh_info; /* Additional section information */ + Elf32_Word sh_addralign; /* Section alignment */ + Elf32_Word sh_entsize; /* Entry size if section holds table */ +} Elf32_Shdr; +#ifdef NOCOMPILE +typedef struct +{ + Elf64_Word sh_name; /* Section name (string tbl index) */ + Elf64_Word sh_type; /* Section type */ + Elf64_Xword sh_flags; /* Section flags */ + Elf64_Addr sh_addr; /* Section virtual addr at execution */ + Elf64_Off sh_offset; /* Section file offset */ + Elf64_Xword sh_size; /* Section size in bytes */ + Elf64_Word sh_link; /* Link to another section */ + Elf64_Word sh_info; /* Additional section information */ + Elf64_Xword sh_addralign; /* Section alignment */ + Elf64_Xword sh_entsize; /* Entry size if section holds table */ +} Elf64_Shdr; +#endif +/* Special section indices. */ + +#define SHN_UNDEF 0 /* Undefined section */ +#define SHN_LORESERVE 0xff00 /* Start of reserved indices */ +#define SHN_LOPROC 0xff00 /* Start of processor-specific */ +#define SHN_HIPROC 0xff1f /* End of processor-specific */ +#define SHN_LOOS 0xff20 /* Start of OS-specific */ +#define SHN_HIOS 0xff3f /* End of OS-specific */ +#define SHN_ABS 0xfff1 /* Associated symbol is absolute */ +#define SHN_COMMON 0xfff2 /* Associated symbol is common */ +#define SHN_XINDEX 0xffff /* Index is in extra table. */ +#define SHN_HIRESERVE 0xffff /* End of reserved indices */ + +/* Legal values for sh_type (section type). */ + +#define SHT_NULL 0 /* Section header table entry unused */ +#define SHT_PROGBITS 1 /* Program data */ +#define SHT_SYMTAB 2 /* Symbol table */ +#define SHT_STRTAB 3 /* String table */ +#define SHT_RELA 4 /* Relocation entries with addends */ +#define SHT_HASH 5 /* Symbol hash table */ +#define SHT_DYNAMIC 6 /* Dynamic linking information */ +#define SHT_NOTE 7 /* Notes */ +#define SHT_NOBITS 8 /* Program space with no data (bss) */ +#define SHT_REL 9 /* Relocation entries, no addends */ +#define SHT_SHLIB 10 /* Reserved */ +#define SHT_DYNSYM 11 /* Dynamic linker symbol table */ +#define SHT_INIT_ARRAY 14 /* Array of constructors */ +#define SHT_FINI_ARRAY 15 /* Array of destructors */ +#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */ +#define SHT_GROUP 17 /* Section group */ +#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */ +#define SHT_NUM 19 /* Number of defined types. */ +#define SHT_LOOS 0x60000000 /* Start OS-specific */ +#define SHT_GNU_LIBLIST 0x6ffffff7 /* Prelink library list */ +#define SHT_CHECKSUM 0x6ffffff8 /* Checksum for DSO content. */ +#define SHT_LOSUNW 0x6ffffffa /* Sun-specific low bound. */ +#define SHT_SUNW_move 0x6ffffffa +#define SHT_SUNW_COMDAT 0x6ffffffb +#define SHT_SUNW_syminfo 0x6ffffffc +#define SHT_GNU_verdef 0x6ffffffd /* Version definition section. */ +#define SHT_GNU_verneed 0x6ffffffe /* Version needs section. */ +#define SHT_GNU_versym 0x6fffffff /* Version symbol table. */ +#define SHT_HISUNW 0x6fffffff /* Sun-specific high bound. */ +#define SHT_HIOS 0x6fffffff /* End OS-specific type */ +#define SHT_LOPROC 0x70000000 /* Start of processor-specific */ +#define SHT_HIPROC 0x7fffffff /* End of processor-specific */ +#define SHT_LOUSER 0x80000000 /* Start of application-specific */ +#define SHT_HIUSER 0x8fffffff /* End of application-specific */ + +/* Legal values for sh_flags (section flags). */ + +#define SHF_WRITE (1 << 0) /* Writable */ +#define SHF_ALLOC (1 << 1) /* Occupies memory during execution */ +#define SHF_EXECINSTR (1 << 2) /* Executable */ +#define SHF_MERGE (1 << 4) /* Might be merged */ +#define SHF_STRINGS (1 << 5) /* Contains nul-terminated strings */ +#define SHF_INFO_LINK (1 << 6) /* `sh_info' contains SHT index */ +#define SHF_LINK_ORDER (1 << 7) /* Preserve order after combining */ +#define SHF_OS_NONCONFORMING (1 << 8) /* Non-standard OS specific handling + required */ +#define SHF_GROUP (1 << 9) /* Section is member of a group. */ +#define SHF_TLS (1 << 10) /* Section hold thread-local data. */ +#define SHF_MASKOS 0x0ff00000 /* OS-specific. */ +#define SHF_MASKPROC 0xf0000000 /* Processor-specific */ + +/* Section group handling. */ +#define GRP_COMDAT 0x1 /* Mark group as COMDAT. */ + +/* Symbol table entry. */ + +typedef struct +{ + Elf32_Word st_name; /* Symbol name (string tbl index) */ + Elf32_Addr st_value; /* Symbol value */ + Elf32_Word st_size; /* Symbol size */ + unsigned char st_info; /* Symbol type and binding */ + unsigned char st_other; /* Symbol visibility */ + Elf32_Section st_shndx; /* Section index */ +} Elf32_Sym; + +typedef struct +{ + Elf64_Word st_name; /* Symbol name (string tbl index) */ + unsigned char st_info; /* Symbol type and binding */ + unsigned char st_other; /* Symbol visibility */ + Elf64_Section st_shndx; /* Section index */ + Elf64_Addr st_value; /* Symbol value */ + Elf64_Xword st_size; /* Symbol size */ +} Elf64_Sym; + +/* The syminfo section if available contains additional information about + every dynamic symbol. */ + +typedef struct +{ + Elf32_Half si_boundto; /* Direct bindings, symbol bound to */ + Elf32_Half si_flags; /* Per symbol flags */ +} Elf32_Syminfo; + +typedef struct +{ + Elf64_Half si_boundto; /* Direct bindings, symbol bound to */ + Elf64_Half si_flags; /* Per symbol flags */ +} Elf64_Syminfo; + +/* Possible values for si_boundto. */ +#define SYMINFO_BT_SELF 0xffff /* Symbol bound to self */ +#define SYMINFO_BT_PARENT 0xfffe /* Symbol bound to parent */ +#define SYMINFO_BT_LOWRESERVE 0xff00 /* Beginning of reserved entries */ + +/* Possible bitmasks for si_flags. */ +#define SYMINFO_FLG_DIRECT 0x0001 /* Direct bound symbol */ +#define SYMINFO_FLG_PASSTHRU 0x0002 /* Pass-thru symbol for translator */ +#define SYMINFO_FLG_COPY 0x0004 /* Symbol is a copy-reloc */ +#define SYMINFO_FLG_LAZYLOAD 0x0008 /* Symbol bound to object to be lazy + loaded */ +/* Syminfo version values. */ +#define SYMINFO_NONE 0 +#define SYMINFO_CURRENT 1 +#define SYMINFO_NUM 2 + + +/* How to extract and insert information held in the st_info field. */ + +#define ELF32_ST_BIND(val) (((unsigned char) (val)) >> 4) +#define ELF32_ST_TYPE(val) ((val) & 0xf) +#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf)) + +/* Both Elf32_Sym and Elf64_Sym use the same one-byte st_info field. */ +#define ELF64_ST_BIND(val) ELF32_ST_BIND (val) +#define ELF64_ST_TYPE(val) ELF32_ST_TYPE (val) +#define ELF64_ST_INFO(bind, type) ELF32_ST_INFO ((bind), (type)) + +/* Legal values for ST_BIND subfield of st_info (symbol binding). */ + +#define STB_LOCAL 0 /* Local symbol */ +#define STB_GLOBAL 1 /* Global symbol */ +#define STB_WEAK 2 /* Weak symbol */ +#define STB_NUM 3 /* Number of defined types. */ +#define STB_LOOS 10 /* Start of OS-specific */ +#define STB_HIOS 12 /* End of OS-specific */ +#define STB_LOPROC 13 /* Start of processor-specific */ +#define STB_HIPROC 15 /* End of processor-specific */ + +/* Legal values for ST_TYPE subfield of st_info (symbol type). */ + +#define STT_NOTYPE 0 /* Symbol type is unspecified */ +#define STT_OBJECT 1 /* Symbol is a data object */ +#define STT_FUNC 2 /* Symbol is a code object */ +#define STT_SECTION 3 /* Symbol associated with a section */ +#define STT_FILE 4 /* Symbol's name is file name */ +#define STT_COMMON 5 /* Symbol is a common data object */ +#define STT_TLS 6 /* Symbol is thread-local data object*/ +#define STT_NUM 7 /* Number of defined types. */ +#define STT_LOOS 10 /* Start of OS-specific */ +#define STT_HIOS 12 /* End of OS-specific */ +#define STT_LOPROC 13 /* Start of processor-specific */ +#define STT_HIPROC 15 /* End of processor-specific */ + + +/* Symbol table indices are found in the hash buckets and chain table + of a symbol hash table section. This special index value indicates + the end of a chain, meaning no further symbols are found in that bucket. */ + +#define STN_UNDEF 0 /* End of a chain. */ + + +/* How to extract and insert information held in the st_other field. */ + +#define ELF32_ST_VISIBILITY(o) ((o) & 0x03) + +/* For ELF64 the definitions are the same. */ +#define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o) + +/* Symbol visibility specification encoded in the st_other field. */ +#define STV_DEFAULT 0 /* Default symbol visibility rules */ +#define STV_INTERNAL 1 /* Processor specific hidden class */ +#define STV_HIDDEN 2 /* Sym unavailable in other modules */ +#define STV_PROTECTED 3 /* Not preemptible, not exported */ + + +/* Relocation table entry without addend (in section of type SHT_REL). */ + +typedef struct +{ + Elf32_Addr r_offset; /* Address */ + Elf32_Word r_info; /* Relocation type and symbol index */ +} Elf32_Rel; + +/* I have seen two different definitions of the Elf64_Rel and + Elf64_Rela structures, so we'll leave them out until Novell (or + whoever) gets their act together. */ +/* The following, at least, is used on Sparc v9, MIPS, and Alpha. */ + +typedef struct +{ + Elf64_Addr r_offset; /* Address */ + Elf64_Xword r_info; /* Relocation type and symbol index */ +} Elf64_Rel; + +/* Relocation table entry with addend (in section of type SHT_RELA). */ + +typedef struct +{ + Elf32_Addr r_offset; /* Address */ + Elf32_Word r_info; /* Relocation type and symbol index */ + Elf32_Sword r_addend; /* Addend */ +} Elf32_Rela; + +typedef struct +{ + Elf64_Addr r_offset; /* Address */ + Elf64_Xword r_info; /* Relocation type and symbol index */ + Elf64_Sxword r_addend; /* Addend */ +} Elf64_Rela; + +/* How to extract and insert information held in the r_info field. */ + +#define ELF32_R_SYM(val) ((val) >> 8) +#define ELF32_R_TYPE(val) ((val) & 0xff) +#define ELF32_R_INFO(sym, type) (((sym) << 8) + ((type) & 0xff)) + +#define ELF64_R_SYM(i) ((i) >> 32) +#define ELF64_R_TYPE(i) ((i) & 0xffffffff) +#define ELF64_R_INFO(sym,type) ((((Elf64_Xword) (sym)) << 32) + (type)) + +/* Program segment header. */ + +typedef struct +{ + Elf32_Word p_type; /* Segment type */ + Elf32_Off p_offset; /* Segment file offset */ + Elf32_Addr p_vaddr; /* Segment virtual address */ + Elf32_Addr p_paddr; /* Segment physical address */ + Elf32_Word p_filesz; /* Segment size in file */ + Elf32_Word p_memsz; /* Segment size in memory */ + Elf32_Word p_flags; /* Segment flags */ + Elf32_Word p_align; /* Segment alignment */ +} Elf32_Phdr; +#ifdef NOCOMPILE +typedef struct +{ + Elf64_Word p_type; /* Segment type */ + Elf64_Word p_flags; /* Segment flags */ + Elf64_Off p_offset; /* Segment file offset */ + Elf64_Addr p_vaddr; /* Segment virtual address */ + Elf64_Addr p_paddr; /* Segment physical address */ + Elf64_Xword p_filesz; /* Segment size in file */ + Elf64_Xword p_memsz; /* Segment size in memory */ + Elf64_Xword p_align; /* Segment alignment */ +} Elf64_Phdr; +#endif +/* Legal values for p_type (segment type). */ + +#define PT_NULL 0 /* Program header table entry unused */ +#define PT_LOAD 1 /* Loadable program segment */ +#define PT_DYNAMIC 2 /* Dynamic linking information */ +#define PT_INTERP 3 /* Program interpreter */ +#define PT_NOTE 4 /* Auxiliary information */ +#define PT_SHLIB 5 /* Reserved */ +#define PT_PHDR 6 /* Entry for header table itself */ +#define PT_TLS 7 /* Thread-local storage segment */ +#define PT_NUM 8 /* Number of defined types */ +#define PT_LOOS 0x60000000 /* Start of OS-specific */ +#define PT_GNU_EH_FRAME 0x6474e550 /* GCC .eh_frame_hdr segment */ +#define PT_GNU_STACK 0x6474e551 /* Indicates stack executability */ +#define PT_LOSUNW 0x6ffffffa +#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */ +#define PT_SUNWSTACK 0x6ffffffb /* Stack segment */ +#define PT_HISUNW 0x6fffffff +#define PT_HIOS 0x6fffffff /* End of OS-specific */ +#define PT_LOPROC 0x70000000 /* Start of processor-specific */ +#define PT_HIPROC 0x7fffffff /* End of processor-specific */ + +/* Legal values for p_flags (segment flags). */ + +#define PF_X (1 << 0) /* Segment is executable */ +#define PF_W (1 << 1) /* Segment is writable */ +#define PF_R (1 << 2) /* Segment is readable */ +#define PF_MASKOS 0x0ff00000 /* OS-specific */ +#define PF_MASKPROC 0xf0000000 /* Processor-specific */ + +/* Legal values for note segment descriptor types for core files. */ + +#define NT_PRSTATUS 1 /* Contains copy of prstatus struct */ +#define NT_FPREGSET 2 /* Contains copy of fpregset struct */ +#define NT_PRPSINFO 3 /* Contains copy of prpsinfo struct */ +#define NT_PRXREG 4 /* Contains copy of prxregset struct */ +#define NT_TASKSTRUCT 4 /* Contains copy of task structure */ +#define NT_PLATFORM 5 /* String from sysinfo(SI_PLATFORM) */ +#define NT_AUXV 6 /* Contains copy of auxv array */ +#define NT_GWINDOWS 7 /* Contains copy of gwindows struct */ +#define NT_ASRS 8 /* Contains copy of asrset struct */ +#define NT_PSTATUS 10 /* Contains copy of pstatus struct */ +#define NT_PSINFO 13 /* Contains copy of psinfo struct */ +#define NT_PRCRED 14 /* Contains copy of prcred struct */ +#define NT_UTSNAME 15 /* Contains copy of utsname struct */ +#define NT_LWPSTATUS 16 /* Contains copy of lwpstatus struct */ +#define NT_LWPSINFO 17 /* Contains copy of lwpinfo struct */ +#define NT_PRFPXREG 20 /* Contains copy of fprxregset struct*/ + +/* Legal values for the note segment descriptor types for object files. */ + +#define NT_VERSION 1 /* Contains a version string. */ + + +/* Dynamic section entry. */ + +typedef struct +{ + Elf32_Sword d_tag; /* Dynamic entry type */ + union + { + Elf32_Word d_val; /* Integer value */ + Elf32_Addr d_ptr; /* Address value */ + } d_un; +} Elf32_Dyn; + +typedef struct +{ + Elf64_Sxword d_tag; /* Dynamic entry type */ + union + { + Elf64_Xword d_val; /* Integer value */ + Elf64_Addr d_ptr; /* Address value */ + } d_un; +} Elf64_Dyn; + +/* Legal values for d_tag (dynamic entry type). */ + +#define DT_NULL 0 /* Marks end of dynamic section */ +#define DT_NEEDED 1 /* Name of needed library */ +#define DT_PLTRELSZ 2 /* Size in bytes of PLT relocs */ +#define DT_PLTGOT 3 /* Processor defined value */ +#define DT_HASH 4 /* Address of symbol hash table */ +#define DT_STRTAB 5 /* Address of string table */ +#define DT_SYMTAB 6 /* Address of symbol table */ +#define DT_RELA 7 /* Address of Rela relocs */ +#define DT_RELASZ 8 /* Total size of Rela relocs */ +#define DT_RELAENT 9 /* Size of one Rela reloc */ +#define DT_STRSZ 10 /* Size of string table */ +#define DT_SYMENT 11 /* Size of one symbol table entry */ +#define DT_INIT 12 /* Address of init function */ +#define DT_FINI 13 /* Address of termination function */ +#define DT_SONAME 14 /* Name of shared object */ +#define DT_RPATH 15 /* Library search path (deprecated) */ +#define DT_SYMBOLIC 16 /* Start symbol search here */ +#define DT_REL 17 /* Address of Rel relocs */ +#define DT_RELSZ 18 /* Total size of Rel relocs */ +#define DT_RELENT 19 /* Size of one Rel reloc */ +#define DT_PLTREL 20 /* Type of reloc in PLT */ +#define DT_DEBUG 21 /* For debugging; unspecified */ +#define DT_TEXTREL 22 /* Reloc might modify .text */ +#define DT_JMPREL 23 /* Address of PLT relocs */ +#define DT_BIND_NOW 24 /* Process relocations of object */ +#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */ +#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */ +#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */ +#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */ +#define DT_RUNPATH 29 /* Library search path */ +#define DT_FLAGS 30 /* Flags for the object being loaded */ +#define DT_ENCODING 32 /* Start of encoded range */ +#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/ +#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */ +#define DT_NUM 34 /* Number used */ +#define DT_LOOS 0x6000000d /* Start of OS-specific */ +#define DT_HIOS 0x6ffff000 /* End of OS-specific */ +#define DT_LOPROC 0x70000000 /* Start of processor-specific */ +#define DT_HIPROC 0x7fffffff /* End of processor-specific */ +#define DT_PROCNUM DT_MIPS_NUM /* Most used by any processor */ + +/* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the + Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's + approach. */ +#define DT_VALRNGLO 0x6ffffd00 +#define DT_GNU_PRELINKED 0x6ffffdf5 /* Prelinking timestamp */ +#define DT_GNU_CONFLICTSZ 0x6ffffdf6 /* Size of conflict section */ +#define DT_GNU_LIBLISTSZ 0x6ffffdf7 /* Size of library list */ +#define DT_CHECKSUM 0x6ffffdf8 +#define DT_PLTPADSZ 0x6ffffdf9 +#define DT_MOVEENT 0x6ffffdfa +#define DT_MOVESZ 0x6ffffdfb +#define DT_FEATURE_1 0x6ffffdfc /* Feature selection (DTF_*). */ +#define DT_POSFLAG_1 0x6ffffdfd /* Flags for DT_* entries, effecting + the following DT_* entry. */ +#define DT_SYMINSZ 0x6ffffdfe /* Size of syminfo table (in bytes) */ +#define DT_SYMINENT 0x6ffffdff /* Entry size of syminfo */ +#define DT_VALRNGHI 0x6ffffdff +#define DT_VALTAGIDX(tag) (DT_VALRNGHI - (tag)) /* Reverse order! */ +#define DT_VALNUM 12 + +/* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the + Dyn.d_un.d_ptr field of the Elf*_Dyn structure. + + If any adjustment is made to the ELF object after it has been + built these entries will need to be adjusted. */ +#define DT_ADDRRNGLO 0x6ffffe00 +#define DT_GNU_CONFLICT 0x6ffffef8 /* Start of conflict section */ +#define DT_GNU_LIBLIST 0x6ffffef9 /* Library list */ +#define DT_CONFIG 0x6ffffefa /* Configuration information. */ +#define DT_DEPAUDIT 0x6ffffefb /* Dependency auditing. */ +#define DT_AUDIT 0x6ffffefc /* Object auditing. */ +#define DT_PLTPAD 0x6ffffefd /* PLT padding. */ +#define DT_MOVETAB 0x6ffffefe /* Move table. */ +#define DT_SYMINFO 0x6ffffeff /* Syminfo table. */ +#define DT_ADDRRNGHI 0x6ffffeff +#define DT_ADDRTAGIDX(tag) (DT_ADDRRNGHI - (tag)) /* Reverse order! */ +#define DT_ADDRNUM 10 + +/* The versioning entry types. The next are defined as part of the + GNU extension. */ +#define DT_VERSYM 0x6ffffff0 + +#define DT_RELACOUNT 0x6ffffff9 +#define DT_RELCOUNT 0x6ffffffa + +/* These were chosen by Sun. */ +#define DT_FLAGS_1 0x6ffffffb /* State flags, see DF_1_* below. */ +#define DT_VERDEF 0x6ffffffc /* Address of version definition + table */ +#define DT_VERDEFNUM 0x6ffffffd /* Number of version definitions */ +#define DT_VERNEED 0x6ffffffe /* Address of table with needed + versions */ +#define DT_VERNEEDNUM 0x6fffffff /* Number of needed versions */ +#define DT_VERSIONTAGIDX(tag) (DT_VERNEEDNUM - (tag)) /* Reverse order! */ +#define DT_VERSIONTAGNUM 16 + +/* Sun added these machine-independent extensions in the "processor-specific" + range. Be compatible. */ +#define DT_AUXILIARY 0x7ffffffd /* Shared object to load before self */ +#define DT_FILTER 0x7fffffff /* Shared object to get values from */ +#define DT_EXTRATAGIDX(tag) ((Elf32_Word)-((Elf32_Sword) (tag) <<1>>1)-1) +#define DT_EXTRANUM 3 + +/* Values of `d_un.d_val' in the DT_FLAGS entry. */ +#define DF_ORIGIN 0x00000001 /* Object may use DF_ORIGIN */ +#define DF_SYMBOLIC 0x00000002 /* Symbol resolutions starts here */ +#define DF_TEXTREL 0x00000004 /* Object contains text relocations */ +#define DF_BIND_NOW 0x00000008 /* No lazy binding for this object */ +#define DF_STATIC_TLS 0x00000010 /* Module uses the static TLS model */ + +/* State flags selectable in the `d_un.d_val' element of the DT_FLAGS_1 + entry in the dynamic section. */ +#define DF_1_NOW 0x00000001 /* Set RTLD_NOW for this object. */ +#define DF_1_GLOBAL 0x00000002 /* Set RTLD_GLOBAL for this object. */ +#define DF_1_GROUP 0x00000004 /* Set RTLD_GROUP for this object. */ +#define DF_1_NODELETE 0x00000008 /* Set RTLD_NODELETE for this object.*/ +#define DF_1_LOADFLTR 0x00000010 /* Trigger filtee loading at runtime.*/ +#define DF_1_INITFIRST 0x00000020 /* Set RTLD_INITFIRST for this object*/ +#define DF_1_NOOPEN 0x00000040 /* Set RTLD_NOOPEN for this object. */ +#define DF_1_ORIGIN 0x00000080 /* $ORIGIN must be handled. */ +#define DF_1_DIRECT 0x00000100 /* Direct binding enabled. */ +#define DF_1_TRANS 0x00000200 +#define DF_1_INTERPOSE 0x00000400 /* Object is used to interpose. */ +#define DF_1_NODEFLIB 0x00000800 /* Ignore default lib search path. */ +#define DF_1_NODUMP 0x00001000 /* Object can't be dldump'ed. */ +#define DF_1_CONFALT 0x00002000 /* Configuration alternative created.*/ +#define DF_1_ENDFILTEE 0x00004000 /* Filtee terminates filters search. */ +#define DF_1_DISPRELDNE 0x00008000 /* Disp reloc applied at build time. */ +#define DF_1_DISPRELPND 0x00010000 /* Disp reloc applied at run-time. */ + +/* Flags for the feature selection in DT_FEATURE_1. */ +#define DTF_1_PARINIT 0x00000001 +#define DTF_1_CONFEXP 0x00000002 + +/* Flags in the DT_POSFLAG_1 entry effecting only the next DT_* entry. */ +#define DF_P1_LAZYLOAD 0x00000001 /* Lazyload following object. */ +#define DF_P1_GROUPPERM 0x00000002 /* Symbols from next object are not + generally available. */ + +/* Version definition sections. */ + +typedef struct +{ + Elf32_Half vd_version; /* Version revision */ + Elf32_Half vd_flags; /* Version information */ + Elf32_Half vd_ndx; /* Version Index */ + Elf32_Half vd_cnt; /* Number of associated aux entries */ + Elf32_Word vd_hash; /* Version name hash value */ + Elf32_Word vd_aux; /* Offset in bytes to verdaux array */ + Elf32_Word vd_next; /* Offset in bytes to next verdef + entry */ +} Elf32_Verdef; + +typedef struct +{ + Elf64_Half vd_version; /* Version revision */ + Elf64_Half vd_flags; /* Version information */ + Elf64_Half vd_ndx; /* Version Index */ + Elf64_Half vd_cnt; /* Number of associated aux entries */ + Elf64_Word vd_hash; /* Version name hash value */ + Elf64_Word vd_aux; /* Offset in bytes to verdaux array */ + Elf64_Word vd_next; /* Offset in bytes to next verdef + entry */ +} Elf64_Verdef; + + +/* Legal values for vd_version (version revision). */ +#define VER_DEF_NONE 0 /* No version */ +#define VER_DEF_CURRENT 1 /* Current version */ +#define VER_DEF_NUM 2 /* Given version number */ + +/* Legal values for vd_flags (version information flags). */ +#define VER_FLG_BASE 0x1 /* Version definition of file itself */ +#define VER_FLG_WEAK 0x2 /* Weak version identifier */ + +/* Versym symbol index values. */ +#define VER_NDX_LOCAL 0 /* Symbol is local. */ +#define VER_NDX_GLOBAL 1 /* Symbol is global. */ +#define VER_NDX_LORESERVE 0xff00 /* Beginning of reserved entries. */ +#define VER_NDX_ELIMINATE 0xff01 /* Symbol is to be eliminated. */ + +/* Auxialiary version information. */ + +typedef struct +{ + Elf32_Word vda_name; /* Version or dependency names */ + Elf32_Word vda_next; /* Offset in bytes to next verdaux + entry */ +} Elf32_Verdaux; + +typedef struct +{ + Elf64_Word vda_name; /* Version or dependency names */ + Elf64_Word vda_next; /* Offset in bytes to next verdaux + entry */ +} Elf64_Verdaux; + + +/* Version dependency section. */ + +typedef struct +{ + Elf32_Half vn_version; /* Version of structure */ + Elf32_Half vn_cnt; /* Number of associated aux entries */ + Elf32_Word vn_file; /* Offset of filename for this + dependency */ + Elf32_Word vn_aux; /* Offset in bytes to vernaux array */ + Elf32_Word vn_next; /* Offset in bytes to next verneed + entry */ +} Elf32_Verneed; + +typedef struct +{ + Elf64_Half vn_version; /* Version of structure */ + Elf64_Half vn_cnt; /* Number of associated aux entries */ + Elf64_Word vn_file; /* Offset of filename for this + dependency */ + Elf64_Word vn_aux; /* Offset in bytes to vernaux array */ + Elf64_Word vn_next; /* Offset in bytes to next verneed + entry */ +} Elf64_Verneed; + + +/* Legal values for vn_version (version revision). */ +#define VER_NEED_NONE 0 /* No version */ +#define VER_NEED_CURRENT 1 /* Current version */ +#define VER_NEED_NUM 2 /* Given version number */ + +/* Auxiliary needed version information. */ + +typedef struct +{ + Elf32_Word vna_hash; /* Hash value of dependency name */ + Elf32_Half vna_flags; /* Dependency specific information */ + Elf32_Half vna_other; /* Unused */ + Elf32_Word vna_name; /* Dependency name string offset */ + Elf32_Word vna_next; /* Offset in bytes to next vernaux + entry */ +} Elf32_Vernaux; + +typedef struct +{ + Elf64_Word vna_hash; /* Hash value of dependency name */ + Elf64_Half vna_flags; /* Dependency specific information */ + Elf64_Half vna_other; /* Unused */ + Elf64_Word vna_name; /* Dependency name string offset */ + Elf64_Word vna_next; /* Offset in bytes to next vernaux + entry */ +} Elf64_Vernaux; + + +/* Legal values for vna_flags. */ +#define VER_FLG_WEAK 0x2 /* Weak version identifier */ + + +/* Auxiliary vector. */ + +/* This vector is normally only used by the program interpreter. The + usual definition in an ABI supplement uses the name auxv_t. The + vector is not usually defined in a standard file, but it + can't hurt. We rename it to avoid conflicts. The sizes of these + types are an arrangement between the exec server and the program + interpreter, so we don't fully specify them here. */ + +typedef struct +{ + int a_type; /* Entry type */ + union + { + long int a_val; /* Integer value */ + void *a_ptr; /* Pointer value */ + void (*a_fcn) (void); /* Function pointer value */ + } a_un; +} Elf32_auxv_t; + +typedef struct +{ + long int a_type; /* Entry type */ + union + { + long int a_val; /* Integer value */ + void *a_ptr; /* Pointer value */ + void (*a_fcn) (void); /* Function pointer value */ + } a_un; +} Elf64_auxv_t; + +/* Legal values for a_type (entry type). */ + +#define AT_NULL 0 /* End of vector */ +#define AT_IGNORE 1 /* Entry should be ignored */ +#define AT_EXECFD 2 /* File descriptor of program */ +#define AT_PHDR 3 /* Program headers for program */ +#define AT_PHENT 4 /* Size of program header entry */ +#define AT_PHNUM 5 /* Number of program headers */ +#define AT_PAGESZ 6 /* System page size */ +#define AT_BASE 7 /* Base address of interpreter */ +#define AT_FLAGS 8 /* Flags */ +#define AT_ENTRY 9 /* Entry point of program */ +#define AT_NOTELF 10 /* Program is not ELF */ +#define AT_UID 11 /* Real uid */ +#define AT_EUID 12 /* Effective uid */ +#define AT_GID 13 /* Real gid */ +#define AT_EGID 14 /* Effective gid */ +#define AT_CLKTCK 17 /* Frequency of times() */ + +/* Some more special a_type values describing the hardware. */ +#define AT_PLATFORM 15 /* String identifying platform. */ +#define AT_HWCAP 16 /* Machine dependent hints about + processor capabilities. */ + +/* This entry gives some information about the FPU initialization + performed by the kernel. */ +#define AT_FPUCW 18 /* Used FPU control word. */ + +/* Cache block sizes. */ +#define AT_DCACHEBSIZE 19 /* Data cache block size. */ +#define AT_ICACHEBSIZE 20 /* Instruction cache block size. */ +#define AT_UCACHEBSIZE 21 /* Unified cache block size. */ + +/* A special ignored value for PPC, used by the kernel to control the + interpretation of the AUXV. Must be > 16. */ +#define AT_IGNOREPPC 22 /* Entry should be ignored. */ + +#define AT_SECURE 23 /* Boolean, was exec setuid-like? */ + +/* Pointer to the global system page used for system calls and other + nice things. */ +#define AT_SYSINFO 32 +#define AT_SYSINFO_EHDR 33 + + +/* Note section contents. Each entry in the note section begins with + a header of a fixed form. */ + +typedef struct +{ + Elf32_Word n_namesz; /* Length of the note's name. */ + Elf32_Word n_descsz; /* Length of the note's descriptor. */ + Elf32_Word n_type; /* Type of the note. */ +} Elf32_Nhdr; + +typedef struct +{ + Elf64_Word n_namesz; /* Length of the note's name. */ + Elf64_Word n_descsz; /* Length of the note's descriptor. */ + Elf64_Word n_type; /* Type of the note. */ +} Elf64_Nhdr; + +/* Known names of notes. */ + +/* Solaris entries in the note section have this name. */ +#define ELF_NOTE_SOLARIS "SUNW Solaris" + +/* Note entries for GNU systems have this name. */ +#define ELF_NOTE_GNU "GNU" + + +/* Defined types of notes for Solaris. */ + +/* Value of descriptor (one word) is desired pagesize for the binary. */ +#define ELF_NOTE_PAGESIZE_HINT 1 + + +/* Defined note types for GNU systems. */ + +/* ABI information. The descriptor consists of words: + word 0: OS descriptor + word 1: major version of the ABI + word 2: minor version of the ABI + word 3: subminor version of the ABI +*/ +#define ELF_NOTE_ABI 1 + +/* Known OSes. These value can appear in word 0 of an ELF_NOTE_ABI + note section entry. */ +#define ELF_NOTE_OS_LINUX 0 +#define ELF_NOTE_OS_GNU 1 +#define ELF_NOTE_OS_SOLARIS2 2 +#define ELF_NOTE_OS_FREEBSD 3 + + +/* Move records. */ +typedef struct +{ + Elf32_Xword m_value; /* Symbol value. */ + Elf32_Word m_info; /* Size and index. */ + Elf32_Word m_poffset; /* Symbol offset. */ + Elf32_Half m_repeat; /* Repeat count. */ + Elf32_Half m_stride; /* Stride info. */ +} Elf32_Move; + +typedef struct +{ + Elf64_Xword m_value; /* Symbol value. */ + Elf64_Xword m_info; /* Size and index. */ + Elf64_Xword m_poffset; /* Symbol offset. */ + Elf64_Half m_repeat; /* Repeat count. */ + Elf64_Half m_stride; /* Stride info. */ +} Elf64_Move; + +/* Macro to construct move records. */ +#define ELF32_M_SYM(info) ((info) >> 8) +#define ELF32_M_SIZE(info) ((unsigned char) (info)) +#define ELF32_M_INFO(sym, size) (((sym) << 8) + (unsigned char) (size)) + +#define ELF64_M_SYM(info) ELF32_M_SYM (info) +#define ELF64_M_SIZE(info) ELF32_M_SIZE (info) +#define ELF64_M_INFO(sym, size) ELF32_M_INFO (sym, size) + + +/* Motorola 68k specific definitions. */ + +/* Values for Elf32_Ehdr.e_flags. */ +#define EF_CPu32 0x00810000 + +/* m68k relocs. */ + +#define R_68K_NONE 0 /* No reloc */ +#define R_68K_32 1 /* Direct 32 bit */ +#define R_68K_16 2 /* Direct 16 bit */ +#define R_68K_8 3 /* Direct 8 bit */ +#define R_68K_PC32 4 /* PC relative 32 bit */ +#define R_68K_PC16 5 /* PC relative 16 bit */ +#define R_68K_PC8 6 /* PC relative 8 bit */ +#define R_68K_GOT32 7 /* 32 bit PC relative GOT entry */ +#define R_68K_GOT16 8 /* 16 bit PC relative GOT entry */ +#define R_68K_GOT8 9 /* 8 bit PC relative GOT entry */ +#define R_68K_GOT32O 10 /* 32 bit GOT offset */ +#define R_68K_GOT16O 11 /* 16 bit GOT offset */ +#define R_68K_GOT8O 12 /* 8 bit GOT offset */ +#define R_68K_PLT32 13 /* 32 bit PC relative PLT address */ +#define R_68K_PLT16 14 /* 16 bit PC relative PLT address */ +#define R_68K_PLT8 15 /* 8 bit PC relative PLT address */ +#define R_68K_PLT32O 16 /* 32 bit PLT offset */ +#define R_68K_PLT16O 17 /* 16 bit PLT offset */ +#define R_68K_PLT8O 18 /* 8 bit PLT offset */ +#define R_68K_COPY 19 /* Copy symbol at runtime */ +#define R_68K_GLOB_DAT 20 /* Create GOT entry */ +#define R_68K_JMP_SLOT 21 /* Create PLT entry */ +#define R_68K_RELATIVE 22 /* Adjust by program base */ +/* Keep this the last entry. */ +#define R_68K_NUM 23 + +/* Intel 80386 specific definitions. */ + +/* i386 relocs. */ + +#define R_386_NONE 0 /* No reloc */ +#define R_386_32 1 /* Direct 32 bit */ +#define R_386_PC32 2 /* PC relative 32 bit */ +#define R_386_GOT32 3 /* 32 bit GOT entry */ +#define R_386_PLT32 4 /* 32 bit PLT address */ +#define R_386_COPY 5 /* Copy symbol at runtime */ +#define R_386_GLOB_DAT 6 /* Create GOT entry */ +#define R_386_JMP_SLOT 7 /* Create PLT entry */ +#define R_386_RELATIVE 8 /* Adjust by program base */ +#define R_386_GOTOFF 9 /* 32 bit offset to GOT */ +#define R_386_GOTPC 10 /* 32 bit PC relative offset to GOT */ +#define R_386_32PLT 11 +#define R_386_TLS_TPOFF 14 /* Offset in static TLS block */ +#define R_386_TLS_IE 15 /* Address of GOT entry for static TLS + block offset */ +#define R_386_TLS_GOTIE 16 /* GOT entry for static TLS block + offset */ +#define R_386_TLS_LE 17 /* Offset relative to static TLS + block */ +#define R_386_TLS_GD 18 /* Direct 32 bit for GNU version of + general dynamic thread local data */ +#define R_386_TLS_LDM 19 /* Direct 32 bit for GNU version of + local dynamic thread local data + in LE code */ +#define R_386_16 20 +#define R_386_PC16 21 +#define R_386_8 22 +#define R_386_PC8 23 +#define R_386_TLS_GD_32 24 /* Direct 32 bit for general dynamic + thread local data */ +#define R_386_TLS_GD_PUSH 25 /* Tag for pushl in GD TLS code */ +#define R_386_TLS_GD_CALL 26 /* Relocation for call to + __tls_get_addr() */ +#define R_386_TLS_GD_POP 27 /* Tag for popl in GD TLS code */ +#define R_386_TLS_LDM_32 28 /* Direct 32 bit for local dynamic + thread local data in LE code */ +#define R_386_TLS_LDM_PUSH 29 /* Tag for pushl in LDM TLS code */ +#define R_386_TLS_LDM_CALL 30 /* Relocation for call to + __tls_get_addr() in LDM code */ +#define R_386_TLS_LDM_POP 31 /* Tag for popl in LDM TLS code */ +#define R_386_TLS_LDO_32 32 /* Offset relative to TLS block */ +#define R_386_TLS_IE_32 33 /* GOT entry for negated static TLS + block offset */ +#define R_386_TLS_LE_32 34 /* Negated offset relative to static + TLS block */ +#define R_386_TLS_DTPMOD32 35 /* ID of module containing symbol */ +#define R_386_TLS_DTPOFF32 36 /* Offset in TLS block */ +#define R_386_TLS_TPOFF32 37 /* Negated offset in static TLS block */ +/* Keep this the last entry. */ +#define R_386_NUM 38 + +/* SUN SPARC specific definitions. */ + +/* Legal values for ST_TYPE subfield of st_info (symbol type). */ + +#define STT_REGISTER 13 /* Global register reserved to app. */ + +/* Values for Elf64_Ehdr.e_flags. */ + +#define EF_SPARCV9_MM 3 +#define EF_SPARCV9_TSO 0 +#define EF_SPARCV9_PSO 1 +#define EF_SPARCV9_RMO 2 +#define EF_SPARC_LEDATA 0x800000 /* little endian data */ +#define EF_SPARC_EXT_MASK 0xFFFF00 +#define EF_SPARC_32PLUS 0x000100 /* generic V8+ features */ +#define EF_SPARC_SUN_US1 0x000200 /* Sun UltraSPARC1 extensions */ +#define EF_SPARC_HAL_R1 0x000400 /* HAL R1 extensions */ +#define EF_SPARC_SUN_US3 0x000800 /* Sun UltraSPARCIII extensions */ + +/* SPARC relocs. */ + +#define R_SPARC_NONE 0 /* No reloc */ +#define R_SPARC_8 1 /* Direct 8 bit */ +#define R_SPARC_16 2 /* Direct 16 bit */ +#define R_SPARC_32 3 /* Direct 32 bit */ +#define R_SPARC_DISP8 4 /* PC relative 8 bit */ +#define R_SPARC_DISP16 5 /* PC relative 16 bit */ +#define R_SPARC_DISP32 6 /* PC relative 32 bit */ +#define R_SPARC_WDISP30 7 /* PC relative 30 bit shifted */ +#define R_SPARC_WDISP22 8 /* PC relative 22 bit shifted */ +#define R_SPARC_HI22 9 /* High 22 bit */ +#define R_SPARC_22 10 /* Direct 22 bit */ +#define R_SPARC_13 11 /* Direct 13 bit */ +#define R_SPARC_LO10 12 /* Truncated 10 bit */ +#define R_SPARC_GOT10 13 /* Truncated 10 bit GOT entry */ +#define R_SPARC_GOT13 14 /* 13 bit GOT entry */ +#define R_SPARC_GOT22 15 /* 22 bit GOT entry shifted */ +#define R_SPARC_PC10 16 /* PC relative 10 bit truncated */ +#define R_SPARC_PC22 17 /* PC relative 22 bit shifted */ +#define R_SPARC_WPLT30 18 /* 30 bit PC relative PLT address */ +#define R_SPARC_COPY 19 /* Copy symbol at runtime */ +#define R_SPARC_GLOB_DAT 20 /* Create GOT entry */ +#define R_SPARC_JMP_SLOT 21 /* Create PLT entry */ +#define R_SPARC_RELATIVE 22 /* Adjust by program base */ +#define R_SPARC_UA32 23 /* Direct 32 bit unaligned */ + +/* Additional Sparc64 relocs. */ + +#define R_SPARC_PLT32 24 /* Direct 32 bit ref to PLT entry */ +#define R_SPARC_HIPLT22 25 /* High 22 bit PLT entry */ +#define R_SPARC_LOPLT10 26 /* Truncated 10 bit PLT entry */ +#define R_SPARC_PCPLT32 27 /* PC rel 32 bit ref to PLT entry */ +#define R_SPARC_PCPLT22 28 /* PC rel high 22 bit PLT entry */ +#define R_SPARC_PCPLT10 29 /* PC rel trunc 10 bit PLT entry */ +#define R_SPARC_10 30 /* Direct 10 bit */ +#define R_SPARC_11 31 /* Direct 11 bit */ +#define R_SPARC_64 32 /* Direct 64 bit */ +#define R_SPARC_OLO10 33 /* 10bit with secondary 13bit addend */ +#define R_SPARC_HH22 34 /* Top 22 bits of direct 64 bit */ +#define R_SPARC_HM10 35 /* High middle 10 bits of ... */ +#define R_SPARC_LM22 36 /* Low middle 22 bits of ... */ +#define R_SPARC_PC_HH22 37 /* Top 22 bits of pc rel 64 bit */ +#define R_SPARC_PC_HM10 38 /* High middle 10 bit of ... */ +#define R_SPARC_PC_LM22 39 /* Low miggle 22 bits of ... */ +#define R_SPARC_WDISP16 40 /* PC relative 16 bit shifted */ +#define R_SPARC_WDISP19 41 /* PC relative 19 bit shifted */ +#define R_SPARC_7 43 /* Direct 7 bit */ +#define R_SPARC_5 44 /* Direct 5 bit */ +#define R_SPARC_6 45 /* Direct 6 bit */ +#define R_SPARC_DISP64 46 /* PC relative 64 bit */ +#define R_SPARC_PLT64 47 /* Direct 64 bit ref to PLT entry */ +#define R_SPARC_HIX22 48 /* High 22 bit complemented */ +#define R_SPARC_LOX10 49 /* Truncated 11 bit complemented */ +#define R_SPARC_H44 50 /* Direct high 12 of 44 bit */ +#define R_SPARC_M44 51 /* Direct mid 22 of 44 bit */ +#define R_SPARC_L44 52 /* Direct low 10 of 44 bit */ +#define R_SPARC_REGISTER 53 /* Global register usage */ +#define R_SPARC_UA64 54 /* Direct 64 bit unaligned */ +#define R_SPARC_UA16 55 /* Direct 16 bit unaligned */ +#define R_SPARC_TLS_GD_HI22 56 +#define R_SPARC_TLS_GD_LO10 57 +#define R_SPARC_TLS_GD_ADD 58 +#define R_SPARC_TLS_GD_CALL 59 +#define R_SPARC_TLS_LDM_HI22 60 +#define R_SPARC_TLS_LDM_LO10 61 +#define R_SPARC_TLS_LDM_ADD 62 +#define R_SPARC_TLS_LDM_CALL 63 +#define R_SPARC_TLS_LDO_HIX22 64 +#define R_SPARC_TLS_LDO_LOX10 65 +#define R_SPARC_TLS_LDO_ADD 66 +#define R_SPARC_TLS_IE_HI22 67 +#define R_SPARC_TLS_IE_LO10 68 +#define R_SPARC_TLS_IE_LD 69 +#define R_SPARC_TLS_IE_LDX 70 +#define R_SPARC_TLS_IE_ADD 71 +#define R_SPARC_TLS_LE_HIX22 72 +#define R_SPARC_TLS_LE_LOX10 73 +#define R_SPARC_TLS_DTPMOD32 74 +#define R_SPARC_TLS_DTPMOD64 75 +#define R_SPARC_TLS_DTPOFF32 76 +#define R_SPARC_TLS_DTPOFF64 77 +#define R_SPARC_TLS_TPOFF32 78 +#define R_SPARC_TLS_TPOFF64 79 +/* Keep this the last entry. */ +#define R_SPARC_NUM 80 + +/* For Sparc64, legal values for d_tag of Elf64_Dyn. */ + +#define DT_SPARC_REGISTER 0x70000001 +#define DT_SPARC_NUM 2 + +/* Bits present in AT_HWCAP, primarily for Sparc32. */ + +#define HWCAP_SPARC_FLUSH 1 /* The cpu supports flush insn. */ +#define HWCAP_SPARC_STBAR 2 +#define HWCAP_SPARC_SWAP 4 +#define HWCAP_SPARC_MULDIV 8 +#define HWCAP_SPARC_V9 16 /* The cpu is v9, so v8plus is ok. */ +#define HWCAP_SPARC_ULTRA3 32 + +/* MIPS R3000 specific definitions. */ + +/* Legal values for e_flags field of Elf32_Ehdr. */ + +#define EF_MIPS_NOREORDER 1 /* A .noreorder directive was used */ +#define EF_MIPS_PIC 2 /* Contains PIC code */ +#define EF_MIPS_CPIC 4 /* Uses PIC calling sequence */ +#define EF_MIPS_XGOT 8 +#define EF_MIPS_64BIT_WHIRL 16 +#define EF_MIPS_ABI2 32 +#define EF_MIPS_ABI_ON32 64 +#define EF_MIPS_ARCH 0xf0000000 /* MIPS architecture level */ + +/* Legal values for MIPS architecture level. */ + +#define EF_MIPS_ARCH_1 0x00000000 /* -mips1 code. */ +#define EF_MIPS_ARCH_2 0x10000000 /* -mips2 code. */ +#define EF_MIPS_ARCH_3 0x20000000 /* -mips3 code. */ +#define EF_MIPS_ARCH_4 0x30000000 /* -mips4 code. */ +#define EF_MIPS_ARCH_5 0x40000000 /* -mips5 code. */ +#define EF_MIPS_ARCH_32 0x60000000 /* MIPscetool::s32 code. */ +#define EF_MIPS_ARCH_64 0x70000000 /* MIPscetool::s64 code. */ + +/* The following are non-official names and should not be used. */ + +#define E_MIPS_ARCH_1 0x00000000 /* -mips1 code. */ +#define E_MIPS_ARCH_2 0x10000000 /* -mips2 code. */ +#define E_MIPS_ARCH_3 0x20000000 /* -mips3 code. */ +#define E_MIPS_ARCH_4 0x30000000 /* -mips4 code. */ +#define E_MIPS_ARCH_5 0x40000000 /* -mips5 code. */ +#define E_MIPS_ARCH_32 0x60000000 /* MIPscetool::s32 code. */ +#define E_MIPS_ARCH_64 0x70000000 /* MIPscetool::s64 code. */ + +/* Special section indices. */ + +#define SHN_MIPS_ACOMMON 0xff00 /* Allocated common symbols */ +#define SHN_MIPS_TEXT 0xff01 /* Allocated test symbols. */ +#define SHN_MIPS_DATA 0xff02 /* Allocated data symbols. */ +#define SHN_MIPS_SCOMMON 0xff03 /* Small common symbols */ +#define SHN_MIPS_SUNDEFINED 0xff04 /* Small undefined symbols */ + +/* Legal values for sh_type field of Elf32_Shdr. */ + +#define SHT_MIPS_LIBLIST 0x70000000 /* Shared objects used in link */ +#define SHT_MIPS_MSYM 0x70000001 +#define SHT_MIPS_CONFLICT 0x70000002 /* Conflicting symbols */ +#define SHT_MIPS_GPTAB 0x70000003 /* Global data area sizes */ +#define SHT_MIPS_UCODE 0x70000004 /* Reserved for SGI/MIPS compilers */ +#define SHT_MIPS_DEBUG 0x70000005 /* MIPS ECOFF debugging information*/ +#define SHT_MIPS_REGINFO 0x70000006 /* Register usage information */ +#define SHT_MIPS_PACKAGE 0x70000007 +#define SHT_MIPS_PACKSYM 0x70000008 +#define SHT_MIPS_RELD 0x70000009 +#define SHT_MIPS_IFACE 0x7000000b +#define SHT_MIPS_CONTENT 0x7000000c +#define SHT_MIPS_OPTIONS 0x7000000d /* Miscellaneous options. */ +#define SHT_MIPS_SHDR 0x70000010 +#define SHT_MIPS_FDESC 0x70000011 +#define SHT_MIPS_EXTSYM 0x70000012 +#define SHT_MIPS_DENSE 0x70000013 +#define SHT_MIPS_PDESC 0x70000014 +#define SHT_MIPS_LOCSYM 0x70000015 +#define SHT_MIPS_AUXSYM 0x70000016 +#define SHT_MIPS_OPTSYM 0x70000017 +#define SHT_MIPS_LOCSTR 0x70000018 +#define SHT_MIPS_LINE 0x70000019 +#define SHT_MIPS_RFDESC 0x7000001a +#define SHT_MIPS_DELTASYM 0x7000001b +#define SHT_MIPS_DELTAINST 0x7000001c +#define SHT_MIPS_DELTACLASS 0x7000001d +#define SHT_MIPS_DWARF 0x7000001e /* DWARF debugging information. */ +#define SHT_MIPS_DELTADECL 0x7000001f +#define SHT_MIPS_SYMBOL_LIB 0x70000020 +#define SHT_MIPS_EVENTS 0x70000021 /* Event section. */ +#define SHT_MIPS_TRANSLATE 0x70000022 +#define SHT_MIPS_PIXIE 0x70000023 +#define SHT_MIPS_XLATE 0x70000024 +#define SHT_MIPS_XLATE_DEBUG 0x70000025 +#define SHT_MIPS_WHIRL 0x70000026 +#define SHT_MIPS_EH_REGION 0x70000027 +#define SHT_MIPS_XLATE_OLD 0x70000028 +#define SHT_MIPS_PDR_EXCEPTION 0x70000029 + +/* Legal values for sh_flags field of Elf32_Shdr. */ + +#define SHF_MIPS_GPREL 0x10000000 /* Must be part of global data area */ +#define SHF_MIPS_MERGE 0x20000000 +#define SHF_MIPS_ADDR 0x40000000 +#define SHF_MIPS_STRINGS 0x80000000 +#define SHF_MIPS_NOSTRIP 0x08000000 +#define SHF_MIPS_LOCAL 0x04000000 +#define SHF_MIPS_NAMES 0x02000000 +#define SHF_MIPS_NODUPE 0x01000000 + + +/* Symbol tables. */ + +/* MIPS specific values for `st_other'. */ +#define STO_MIPS_DEFAULT 0x0 +#define STO_MIPS_INTERNAL 0x1 +#define STO_MIPS_HIDDEN 0x2 +#define STO_MIPS_PROTECTED 0x3 +#define STO_MIPS_SC_ALIGN_UNUSED 0xff + +/* MIPS specific values for `st_info'. */ +#define STB_MIPS_SPLIT_COMMON 13 + +/* Entries found in sections of type SHT_MIPS_GPTAB. */ + +typedef union +{ + struct + { + Elf32_Word gt_current_g_value; /* -G value used for compilation */ + Elf32_Word gt_unused; /* Not used */ + } gt_header; /* First entry in section */ + struct + { + Elf32_Word gt_g_value; /* If this value were used for -G */ + Elf32_Word gt_bytes; /* This many bytes would be used */ + } gt_entry; /* Subsequent entries in section */ +} Elf32_gptab; + +/* Entry found in sections of type SHT_MIPS_REGINFO. */ + +typedef struct +{ + Elf32_Word ri_gprmask; /* General registers used */ + Elf32_Word ri_cprmask[4]; /* Coprocessor registers used */ + Elf32_Sword ri_gp_value; /* $gp register value */ +} Elf32_RegInfo; + +/* Entries found in sections of type SHT_MIPS_OPTIONS. */ + +typedef struct +{ + unsigned char kind; /* Determines interpretation of the + variable part of descriptor. */ + unsigned char size; /* Size of descriptor, including header. */ + Elf32_Section section; /* Section header index of section affected, + 0 for global options. */ + Elf32_Word info; /* Kind-specific information. */ +} Elf_Options; + +/* Values for `kind' field in Elf_Options. */ + +#define ODK_NULL 0 /* Undefined. */ +#define ODK_REGINFO 1 /* Register usage information. */ +#define ODK_EXCEPTIONS 2 /* Exception processing options. */ +#define ODK_PAD 3 /* Section padding options. */ +#define ODK_HWPATCH 4 /* Hardware workarounds performed */ +#define ODK_FILL 5 /* record the fill value used by the linker. */ +#define ODK_TAGS 6 /* reserve space for desktop tools to write. */ +#define ODK_HWAND 7 /* HW workarounds. 'AND' bits when merging. */ +#define ODK_HWOR 8 /* HW workarounds. 'OR' bits when merging. */ + +/* Values for `info' in Elf_Options for ODK_EXCEPTIONS entries. */ + +#define OEX_FPU_MIN 0x1f /* FPE's which MUST be enabled. */ +#define OEX_FPU_MAX 0x1f00 /* FPE's which MAY be enabled. */ +#define OEX_PAGE0 0x10000 /* page zero must be mapped. */ +#define OEX_SMM 0x20000 /* Force sequential memory mode? */ +#define OEX_FPDBUG 0x40000 /* Force floating point debug mode? */ +#define OEX_PRECISEFP OEX_FPDBUG +#define OEX_DISMISS 0x80000 /* Dismiss invalid address faults? */ + +#define OEX_FPU_INVAL 0x10 +#define OEX_FPU_DIV0 0x08 +#define OEX_FPU_OFLO 0x04 +#define OEX_FPU_UFLO 0x02 +#define OEX_FPU_INEX 0x01 + +/* Masks for `info' in Elf_Options for an ODK_HWPATCH entry. */ + +#define OHW_R4KEOP 0x1 /* R4000 end-of-page patch. */ +#define OHW_R8KPFETCH 0x2 /* may need R8000 prefetch patch. */ +#define OHW_R5KEOP 0x4 /* R5000 end-of-page patch. */ +#define OHW_R5KCVTL 0x8 /* R5000 cvt.[ds].l bug. clean=1. */ + +#define OPAD_PREFIX 0x1 +#define OPAD_POSTFIX 0x2 +#define OPAD_SYMBOL 0x4 + +/* Entry found in `.options' section. */ + +typedef struct +{ + Elf32_Word hwp_flags1; /* Extra flags. */ + Elf32_Word hwp_flags2; /* Extra flags. */ +} Elf_Options_Hw; + +/* Masks for `info' in ElfOptions for ODK_HWAND and ODK_HWOR entries. */ + +#define OHWA0_R4KEOP_CHECKED 0x00000001 +#define OHWA1_R4KEOP_CLEAN 0x00000002 + +/* MIPS relocs. */ + +#define R_MIPS_NONE 0 /* No reloc */ +#define R_MIPS_16 1 /* Direct 16 bit */ +#define R_MIPS_32 2 /* Direct 32 bit */ +#define R_MIPS_REL32 3 /* PC relative 32 bit */ +#define R_MIPS_26 4 /* Direct 26 bit shifted */ +#define R_MIPS_HI16 5 /* High 16 bit */ +#define R_MIPS_LO16 6 /* Low 16 bit */ +#define R_MIPS_GPREL16 7 /* GP relative 16 bit */ +#define R_MIPS_LITERAL 8 /* 16 bit literal entry */ +#define R_MIPS_GOT16 9 /* 16 bit GOT entry */ +#define R_MIPS_PC16 10 /* PC relative 16 bit */ +#define R_MIPS_CALL16 11 /* 16 bit GOT entry for function */ +#define R_MIPS_GPREL32 12 /* GP relative 32 bit */ + +#define R_MIPS_SHIFT5 16 +#define R_MIPS_SHIFT6 17 +#define R_MIPS_64 18 +#define R_MIPS_GOT_DISP 19 +#define R_MIPS_GOT_PAGE 20 +#define R_MIPS_GOT_OFST 21 +#define R_MIPS_GOT_HI16 22 +#define R_MIPS_GOT_LO16 23 +#define R_MIPS_SUB 24 +#define R_MIPS_INSERT_A 25 +#define R_MIPS_INSERT_B 26 +#define R_MIPS_DELETE 27 +#define R_MIPS_HIGHER 28 +#define R_MIPS_HIGHEST 29 +#define R_MIPS_CALL_HI16 30 +#define R_MIPS_CALL_LO16 31 +#define R_MIPS_SCN_DISP 32 +#define R_MIPS_REL16 33 +#define R_MIPS_ADD_IMMEDIATE 34 +#define R_MIPS_PJUMP 35 +#define R_MIPS_RELGOT 36 +#define R_MIPS_JALR 37 +/* Keep this the last entry. */ +#define R_MIPS_NUM 38 + +/* Legal values for p_type field of Elf32_Phdr. */ + +#define PT_MIPS_REGINFO 0x70000000 /* Register usage information */ +#define PT_MIPS_RTPROC 0x70000001 /* Runtime procedure table. */ +#define PT_MIPS_OPTIONS 0x70000002 + +/* Special program header types. */ + +#define PF_MIPS_LOCAL 0x10000000 + +/* Legal values for d_tag field of Elf32_Dyn. */ + +#define DT_MIPS_RLD_VERSION 0x70000001 /* Runtime linker interface version */ +#define DT_MIPS_TIME_STAMP 0x70000002 /* Timestamp */ +#define DT_MIPS_ICHECKSUM 0x70000003 /* Checksum */ +#define DT_MIPS_IVERSION 0x70000004 /* Version string (string tbl index) */ +#define DT_MIPS_FLAGS 0x70000005 /* Flags */ +#define DT_MIPS_BASE_ADDRESS 0x70000006 /* Base address */ +#define DT_MIPS_MSYM 0x70000007 +#define DT_MIPS_CONFLICT 0x70000008 /* Address of CONFLICT section */ +#define DT_MIPS_LIBLIST 0x70000009 /* Address of LIBLIST section */ +#define DT_MIPS_LOCAL_GOTNO 0x7000000a /* Number of local GOT entries */ +#define DT_MIPS_CONFLICTNO 0x7000000b /* Number of CONFLICT entries */ +#define DT_MIPS_LIBLISTNO 0x70000010 /* Number of LIBLIST entries */ +#define DT_MIPS_SYMTABNO 0x70000011 /* Number of DYNSYM entries */ +#define DT_MIPS_UNREFEXTNO 0x70000012 /* First external DYNSYM */ +#define DT_MIPS_GOTSYM 0x70000013 /* First GOT entry in DYNSYM */ +#define DT_MIPS_HIPAGENO 0x70000014 /* Number of GOT page table entries */ +#define DT_MIPS_RLD_MAP 0x70000016 /* Address of run time loader map. */ +#define DT_MIPS_DELTA_CLASS 0x70000017 /* Delta C++ class definition. */ +#define DT_MIPS_DELTA_CLASS_NO 0x70000018 /* Number of entries in + DT_MIPS_DELTA_CLASS. */ +#define DT_MIPS_DELTA_INSTANCE 0x70000019 /* Delta C++ class instances. */ +#define DT_MIPS_DELTA_INSTANCE_NO 0x7000001a /* Number of entries in + DT_MIPS_DELTA_INSTANCE. */ +#define DT_MIPS_DELTA_RELOC 0x7000001b /* Delta relocations. */ +#define DT_MIPS_DELTA_RELOC_NO 0x7000001c /* Number of entries in + DT_MIPS_DELTA_RELOC. */ +#define DT_MIPS_DELTA_SYM 0x7000001d /* Delta symbols that Delta + relocations refer to. */ +#define DT_MIPS_DELTA_SYM_NO 0x7000001e /* Number of entries in + DT_MIPS_DELTA_SYM. */ +#define DT_MIPS_DELTA_CLASSSYM 0x70000020 /* Delta symbols that hold the + class declaration. */ +#define DT_MIPS_DELTA_CLASSSYM_NO 0x70000021 /* Number of entries in + DT_MIPS_DELTA_CLASSSYM. */ +#define DT_MIPS_CXX_FLAGS 0x70000022 /* Flags indicating for C++ flavor. */ +#define DT_MIPS_PIXIE_INIT 0x70000023 +#define DT_MIPS_SYMBOL_LIB 0x70000024 +#define DT_MIPS_LOCALPAGE_GOTIDX 0x70000025 +#define DT_MIPS_LOCAL_GOTIDX 0x70000026 +#define DT_MIPS_HIDDEN_GOTIDX 0x70000027 +#define DT_MIPS_PROTECTED_GOTIDX 0x70000028 +#define DT_MIPS_OPTIONS 0x70000029 /* Address of .options. */ +#define DT_MIPS_INTERFACE 0x7000002a /* Address of .interface. */ +#define DT_MIPS_DYNSTR_ALIGN 0x7000002b +#define DT_MIPS_INTERFACE_SIZE 0x7000002c /* Size of the .interface section. */ +#define DT_MIPS_RLD_TEXT_RESOLVE_ADDR 0x7000002d /* Address of rld_text_rsolve + function stored in GOT. */ +#define DT_MIPS_PERF_SUFFIX 0x7000002e /* Default suffix of dso to be added + by rld on dlopen() calls. */ +#define DT_MIPS_COMPACT_SIZE 0x7000002f /* (O32)Size of compact rel section. */ +#define DT_MIPS_GP_VALUE 0x70000030 /* GP value for aux GOTs. */ +#define DT_MIPS_AUX_DYNAMIC 0x70000031 /* Address of aux .dynamic. */ +#define DT_MIPS_NUM 0x32 + +/* Legal values for DT_MIPS_FLAGS Elf32_Dyn entry. */ + +#define RHF_NONE 0 /* No flags */ +#define RHF_QUICKSTART (1 << 0) /* Use quickstart */ +#define RHF_NOTPOT (1 << 1) /* Hash size not power of 2 */ +#define RHF_NO_LIBRARY_REPLACEMENT (1 << 2) /* Ignore LD_LIBRARY_PATH */ +#define RHF_NO_MOVE (1 << 3) +#define RHF_SGI_ONLY (1 << 4) +#define RHF_GUARANTEE_INIT (1 << 5) +#define RHF_DELTA_C_PLUS_PLUS (1 << 6) +#define RHF_GUARANTEE_START_INIT (1 << 7) +#define RHF_PIXIE (1 << 8) +#define RHF_DEFAULT_DELAY_LOAD (1 << 9) +#define RHF_REQUICKSTART (1 << 10) +#define RHF_REQUICKSTARTED (1 << 11) +#define RHF_CORD (1 << 12) +#define RHF_NO_UNRES_UNDEF (1 << 13) +#define RHF_RLD_ORDER_SAFE (1 << 14) + +/* Entries found in sections of type SHT_MIPS_LIBLIST. */ + +typedef struct +{ + Elf32_Word l_name; /* Name (string table index) */ + Elf32_Word l_time_stamp; /* Timestamp */ + Elf32_Word l_checksum; /* Checksum */ + Elf32_Word l_version; /* Interface version */ + Elf32_Word l_flags; /* Flags */ +} Elf32_Lib; + +typedef struct +{ + Elf64_Word l_name; /* Name (string table index) */ + Elf64_Word l_time_stamp; /* Timestamp */ + Elf64_Word l_checksum; /* Checksum */ + Elf64_Word l_version; /* Interface version */ + Elf64_Word l_flags; /* Flags */ +} Elf64_Lib; + + +/* Legal values for l_flags. */ + +#define LL_NONE 0 +#define LL_EXACT_MATCH (1 << 0) /* Require exact match */ +#define LL_IGNORE_INT_VER (1 << 1) /* Ignore interface version */ +#define LL_REQUIRE_MINOR (1 << 2) +#define LL_EXPORTS (1 << 3) +#define LL_DELAY_LOAD (1 << 4) +#define LL_DELTA (1 << 5) + +/* Entries found in sections of type SHT_MIPS_CONFLICT. */ + +typedef Elf32_Addr Elf32_Conflict; + + +/* HPPA specific definitions. */ + +/* Legal values for e_flags field of Elf32_Ehdr. */ + +#define EF_PARISC_TRAPNIL 0x00010000 /* Trap nil pointer dereference. */ +#define EF_PARISC_EXT 0x00020000 /* Program uses arch. extensions. */ +#define EF_PARISC_LSB 0x00040000 /* Program expects little endian. */ +#define EF_PARISC_WIDE 0x00080000 /* Program expects wide mode. */ +#define EF_PARISC_NO_KABP 0x00100000 /* No kernel assisted branch + prediction. */ +#define EF_PARISC_LAZYSWAP 0x00400000 /* Allow lazy swapping. */ +#define EF_PARISC_ARCH 0x0000ffff /* Architecture version. */ + +/* Defined values for `e_flags & EF_PARISC_ARCH' are: */ + +#define EFA_PARISC_1_0 0x020b /* PA-RISC 1.0 big-endian. */ +#define EFA_PARISC_1_1 0x0210 /* PA-RISC 1.1 big-endian. */ +#define EFA_PARISC_2_0 0x0214 /* PA-RISC 2.0 big-endian. */ + +/* Additional section indeces. */ + +#define SHN_PARISC_ANSI_COMMON 0xff00 /* Section for tenatively declared + symbols in ANSI C. */ +#define SHN_PARISC_HUGE_COMMON 0xff01 /* Common blocks in huge model. */ + +/* Legal values for sh_type field of Elf32_Shdr. */ + +#define SHT_PARISC_EXT 0x70000000 /* Contains product specific ext. */ +#define SHT_PARISC_UNWIND 0x70000001 /* Unwind information. */ +#define SHT_PARISC_DOC 0x70000002 /* Debug info for optimized code. */ + +/* Legal values for sh_flags field of Elf32_Shdr. */ + +#define SHF_PARISC_SHORT 0x20000000 /* Section with short addressing. */ +#define SHF_PARISC_HUGE 0x40000000 /* Section far from gp. */ +#define SHF_PARISC_SBP 0x80000000 /* Static branch prediction code. */ + +/* Legal values for ST_TYPE subfield of st_info (symbol type). */ + +#define STT_PARISC_MILLICODE 13 /* Millicode function entry point. */ + +#define STT_HP_OPAQUE (STT_LOOS + 0x1) +#define STT_HP_STUB (STT_LOOS + 0x2) + +/* HPPA relocs. */ + +#define R_PARISC_NONE 0 /* No reloc. */ +#define R_PARISC_DIR32 1 /* Direct 32-bit reference. */ +#define R_PARISC_DIR21L 2 /* Left 21 bits of eff. address. */ +#define R_PARISC_DIR17R 3 /* Right 17 bits of eff. address. */ +#define R_PARISC_DIR17F 4 /* 17 bits of eff. address. */ +#define R_PARISC_DIR14R 6 /* Right 14 bits of eff. address. */ +#define R_PARISC_PCREL32 9 /* 32-bit rel. address. */ +#define R_PARISC_PCREL21L 10 /* Left 21 bits of rel. address. */ +#define R_PARISC_PCREL17R 11 /* Right 17 bits of rel. address. */ +#define R_PARISC_PCREL17F 12 /* 17 bits of rel. address. */ +#define R_PARISC_PCREL14R 14 /* Right 14 bits of rel. address. */ +#define R_PARISC_DPREL21L 18 /* Left 21 bits of rel. address. */ +#define R_PARISC_DPREL14R 22 /* Right 14 bits of rel. address. */ +#define R_PARISC_GPREL21L 26 /* GP-relative, left 21 bits. */ +#define R_PARISC_GPREL14R 30 /* GP-relative, right 14 bits. */ +#define R_PARISC_LTOFF21L 34 /* LT-relative, left 21 bits. */ +#define R_PARISC_LTOFF14R 38 /* LT-relative, right 14 bits. */ +#define R_PARISC_SECREL32 41 /* 32 bits section rel. address. */ +#define R_PARISC_SEGBASE 48 /* No relocation, set segment base. */ +#define R_PARISC_SEGREL32 49 /* 32 bits segment rel. address. */ +#define R_PARISC_PLTOFF21L 50 /* PLT rel. address, left 21 bits. */ +#define R_PARISC_PLTOFF14R 54 /* PLT rel. address, right 14 bits. */ +#define R_PARISC_LTOFF_FPTR32 57 /* 32 bits LT-rel. function pointer. */ +#define R_PARISC_LTOFF_FPTR21L 58 /* LT-rel. fct ptr, left 21 bits. */ +#define R_PARISC_LTOFF_FPTR14R 62 /* LT-rel. fct ptr, right 14 bits. */ +#define R_PARISC_FPTR64 64 /* 64 bits function address. */ +#define R_PARISC_PLABEL32 65 /* 32 bits function address. */ +#define R_PARISC_PCREL64 72 /* 64 bits PC-rel. address. */ +#define R_PARISC_PCREL22F 74 /* 22 bits PC-rel. address. */ +#define R_PARISC_PCREL14WR 75 /* PC-rel. address, right 14 bits. */ +#define R_PARISC_PCREL14DR 76 /* PC rel. address, right 14 bits. */ +#define R_PARISC_PCREL16F 77 /* 16 bits PC-rel. address. */ +#define R_PARISC_PCREL16WF 78 /* 16 bits PC-rel. address. */ +#define R_PARISC_PCREL16DF 79 /* 16 bits PC-rel. address. */ +#define R_PARISC_DIR64 80 /* 64 bits of eff. address. */ +#define R_PARISC_DIR14WR 83 /* 14 bits of eff. address. */ +#define R_PARISC_DIR14DR 84 /* 14 bits of eff. address. */ +#define R_PARISC_DIR16F 85 /* 16 bits of eff. address. */ +#define R_PARISC_DIR16WF 86 /* 16 bits of eff. address. */ +#define R_PARISC_DIR16DF 87 /* 16 bits of eff. address. */ +#define R_PARISC_GPREL64 88 /* 64 bits of GP-rel. address. */ +#define R_PARISC_GPREL14WR 91 /* GP-rel. address, right 14 bits. */ +#define R_PARISC_GPREL14DR 92 /* GP-rel. address, right 14 bits. */ +#define R_PARISC_GPREL16F 93 /* 16 bits GP-rel. address. */ +#define R_PARISC_GPREL16WF 94 /* 16 bits GP-rel. address. */ +#define R_PARISC_GPREL16DF 95 /* 16 bits GP-rel. address. */ +#define R_PARISC_LTOFF64 96 /* 64 bits LT-rel. address. */ +#define R_PARISC_LTOFF14WR 99 /* LT-rel. address, right 14 bits. */ +#define R_PARISC_LTOFF14DR 100 /* LT-rel. address, right 14 bits. */ +#define R_PARISC_LTOFF16F 101 /* 16 bits LT-rel. address. */ +#define R_PARISC_LTOFF16WF 102 /* 16 bits LT-rel. address. */ +#define R_PARISC_LTOFF16DF 103 /* 16 bits LT-rel. address. */ +#define R_PARISC_SECREL64 104 /* 64 bits section rel. address. */ +#define R_PARISC_SEGREL64 112 /* 64 bits segment rel. address. */ +#define R_PARISC_PLTOFF14WR 115 /* PLT-rel. address, right 14 bits. */ +#define R_PARISC_PLTOFF14DR 116 /* PLT-rel. address, right 14 bits. */ +#define R_PARISC_PLTOFF16F 117 /* 16 bits LT-rel. address. */ +#define R_PARISC_PLTOFF16WF 118 /* 16 bits PLT-rel. address. */ +#define R_PARISC_PLTOFF16DF 119 /* 16 bits PLT-rel. address. */ +#define R_PARISC_LTOFF_FPTR64 120 /* 64 bits LT-rel. function ptr. */ +#define R_PARISC_LTOFF_FPTR14WR 123 /* LT-rel. fct. ptr., right 14 bits. */ +#define R_PARISC_LTOFF_FPTR14DR 124 /* LT-rel. fct. ptr., right 14 bits. */ +#define R_PARISC_LTOFF_FPTR16F 125 /* 16 bits LT-rel. function ptr. */ +#define R_PARISC_LTOFF_FPTR16WF 126 /* 16 bits LT-rel. function ptr. */ +#define R_PARISC_LTOFF_FPTR16DF 127 /* 16 bits LT-rel. function ptr. */ +#define R_PARISC_LORESERVE 128 +#define R_PARISC_COPY 128 /* Copy relocation. */ +#define R_PARISC_IPLT 129 /* Dynamic reloc, imported PLT */ +#define R_PARISC_EPLT 130 /* Dynamic reloc, exported PLT */ +#define R_PARISC_TPREL32 153 /* 32 bits TP-rel. address. */ +#define R_PARISC_TPREL21L 154 /* TP-rel. address, left 21 bits. */ +#define R_PARISC_TPREL14R 158 /* TP-rel. address, right 14 bits. */ +#define R_PARISC_LTOFF_TP21L 162 /* LT-TP-rel. address, left 21 bits. */ +#define R_PARISC_LTOFF_TP14R 166 /* LT-TP-rel. address, right 14 bits.*/ +#define R_PARISC_LTOFF_TP14F 167 /* 14 bits LT-TP-rel. address. */ +#define R_PARISC_TPREL64 216 /* 64 bits TP-rel. address. */ +#define R_PARISC_TPREL14WR 219 /* TP-rel. address, right 14 bits. */ +#define R_PARISC_TPREL14DR 220 /* TP-rel. address, right 14 bits. */ +#define R_PARISC_TPREL16F 221 /* 16 bits TP-rel. address. */ +#define R_PARISC_TPREL16WF 222 /* 16 bits TP-rel. address. */ +#define R_PARISC_TPREL16DF 223 /* 16 bits TP-rel. address. */ +#define R_PARISC_LTOFF_TP64 224 /* 64 bits LT-TP-rel. address. */ +#define R_PARISC_LTOFF_TP14WR 227 /* LT-TP-rel. address, right 14 bits.*/ +#define R_PARISC_LTOFF_TP14DR 228 /* LT-TP-rel. address, right 14 bits.*/ +#define R_PARISC_LTOFF_TP16F 229 /* 16 bits LT-TP-rel. address. */ +#define R_PARISC_LTOFF_TP16WF 230 /* 16 bits LT-TP-rel. address. */ +#define R_PARISC_LTOFF_TP16DF 231 /* 16 bits LT-TP-rel. address. */ +#define R_PARISC_HIRESERVE 255 + +/* Legal values for p_type field of Elf32_Phdr/Elf64_Phdr. */ + +#define PT_HP_TLS (PT_LOOS + 0x0) +#define PT_HP_CORE_NONE (PT_LOOS + 0x1) +#define PT_HP_CORE_VERSION (PT_LOOS + 0x2) +#define PT_HP_CORE_KERNEL (PT_LOOS + 0x3) +#define PT_HP_CORE_COMM (PT_LOOS + 0x4) +#define PT_HP_CORE_PROC (PT_LOOS + 0x5) +#define PT_HP_CORE_LOADABLE (PT_LOOS + 0x6) +#define PT_HP_CORE_STACK (PT_LOOS + 0x7) +#define PT_HP_CORE_SHM (PT_LOOS + 0x8) +#define PT_HP_CORE_MMF (PT_LOOS + 0x9) +#define PT_HP_PARALLEL (PT_LOOS + 0x10) +#define PT_HP_FASTBIND (PT_LOOS + 0x11) +#define PT_HP_OPT_ANNOT (PT_LOOS + 0x12) +#define PT_HP_HSL_ANNOT (PT_LOOS + 0x13) +#define PT_HP_STACK (PT_LOOS + 0x14) + +#define PT_PARISC_ARCHEXT 0x70000000 +#define PT_PARISC_UNWIND 0x70000001 + +/* Legal values for p_flags field of Elf32_Phdr/Elf64_Phdr. */ + +#define PF_PARISC_SBP 0x08000000 + +#define PF_HP_PAGE_SIZE 0x00100000 +#define PF_HP_FAR_SHARED 0x00200000 +#define PF_HP_NEAR_SHARED 0x00400000 +#define PF_HP_CODE 0x01000000 +#define PF_HP_MODIFY 0x02000000 +#define PF_HP_LAZYSWAP 0x04000000 +#define PF_HP_SBP 0x08000000 + + +/* Alpha specific definitions. */ + +/* Legal values for e_flags field of Elf64_Ehdr. */ + +#define EF_ALPHA_32BIT 1 /* All addresses must be < 2GB. */ +#define EF_ALPHA_CANRELAX 2 /* Relocations for relaxing exist. */ + +/* Legal values for sh_type field of Elf64_Shdr. */ + +/* These two are primerily concerned with ECOFF debugging info. */ +#define SHT_ALPHA_DEBUG 0x70000001 +#define SHT_ALPHA_REGINFO 0x70000002 + +/* Legal values for sh_flags field of Elf64_Shdr. */ + +#define SHF_ALPHA_GPREL 0x10000000 + +/* Legal values for st_other field of Elf64_Sym. */ +#define STO_ALPHA_NOPV 0x80 /* No PV required. */ +#define STO_ALPHA_STD_GPLOAD 0x88 /* PV only used for initial ldgp. */ + +/* Alpha relocs. */ + +#define R_ALPHA_NONE 0 /* No reloc */ +#define R_ALPHA_REFLONG 1 /* Direct 32 bit */ +#define R_ALPHA_REFQUAD 2 /* Direct 64 bit */ +#define R_ALPHA_GPREL32 3 /* GP relative 32 bit */ +#define R_ALPHA_LITERAL 4 /* GP relative 16 bit w/optimization */ +#define R_ALPHA_LITUSE 5 /* Optimization hint for LITERAL */ +#define R_ALPHA_GPDISP 6 /* Add displacement to GP */ +#define R_ALPHA_BRADDR 7 /* PC+4 relative 23 bit shifted */ +#define R_ALPHA_HINT 8 /* PC+4 relative 16 bit shifted */ +#define R_ALPHA_SREL16 9 /* PC relative 16 bit */ +#define R_ALPHA_SREL32 10 /* PC relative 32 bit */ +#define R_ALPHA_SREL64 11 /* PC relative 64 bit */ +#define R_ALPHA_GPRELHIGH 17 /* GP relative 32 bit, high 16 bits */ +#define R_ALPHA_GPRELLOW 18 /* GP relative 32 bit, low 16 bits */ +#define R_ALPHA_GPREL16 19 /* GP relative 16 bit */ +#define R_ALPHA_COPY 24 /* Copy symbol at runtime */ +#define R_ALPHA_GLOB_DAT 25 /* Create GOT entry */ +#define R_ALPHA_JMP_SLOT 26 /* Create PLT entry */ +#define R_ALPHA_RELATIVE 27 /* Adjust by program base */ +#define R_ALPHA_TLS_GD_HI 28 +#define R_ALPHA_TLSGD 29 +#define R_ALPHA_TLS_LDM 30 +#define R_ALPHA_DTPMOD64 31 +#define R_ALPHA_GOTDTPREL 32 +#define R_ALPHA_DTPREL64 33 +#define R_ALPHA_DTPRELHI 34 +#define R_ALPHA_DTPRELLO 35 +#define R_ALPHA_DTPREL16 36 +#define R_ALPHA_GOTTPREL 37 +#define R_ALPHA_TPREL64 38 +#define R_ALPHA_TPRELHI 39 +#define R_ALPHA_TPRELLO 40 +#define R_ALPHA_TPREL16 41 +/* Keep this the last entry. */ +#define R_ALPHA_NUM 46 + +/* Magic values of the LITUSE relocation addend. */ +#define LITUSE_ALPHA_ADDR 0 +#define LITUSE_ALPHA_BASE 1 +#define LITUSE_ALPHA_BYTOFF 2 +#define LITUSE_ALPHA_JSR 3 +#define LITUSE_ALPHA_TLS_GD 4 +#define LITUSE_ALPHA_TLS_LDM 5 + + +/* PowerPC specific declarations */ + +/* Values for Elf32/64_Ehdr.e_flags. */ +#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */ + +/* Cygnus local bits below */ +#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/ +#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib + flag */ + +/* PowerPC relocations defined by the ABIs */ +#define R_PPC_NONE 0 +#define R_PPC_ADDR32 1 /* 32bit absolute address */ +#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */ +#define R_PPC_ADDR16 3 /* 16bit absolute address */ +#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */ +#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */ +#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */ +#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */ +#define R_PPC_ADDR14_BRTAKEN 8 +#define R_PPC_ADDR14_BRNTAKEN 9 +#define R_PPC_REL24 10 /* PC relative 26 bit */ +#define R_PPC_REL14 11 /* PC relative 16 bit */ +#define R_PPC_REL14_BRTAKEN 12 +#define R_PPC_REL14_BRNTAKEN 13 +#define R_PPC_GOT16 14 +#define R_PPC_GOT16_LO 15 +#define R_PPC_GOT16_HI 16 +#define R_PPC_GOT16_HA 17 +#define R_PPC_PLTREL24 18 +#define R_PPC_COPY 19 +#define R_PPC_GLOB_DAT 20 +#define R_PPC_JMP_SLOT 21 +#define R_PPC_RELATIVE 22 +#define R_PPC_LOCAL24PC 23 +#define R_PPC_UADDR32 24 +#define R_PPC_UADDR16 25 +#define R_PPC_REL32 26 +#define R_PPC_PLT32 27 +#define R_PPC_PLTREL32 28 +#define R_PPC_PLT16_LO 29 +#define R_PPC_PLT16_HI 30 +#define R_PPC_PLT16_HA 31 +#define R_PPC_SDAREL16 32 +#define R_PPC_SECTOFF 33 +#define R_PPC_SECTOFF_LO 34 +#define R_PPC_SECTOFF_HI 35 +#define R_PPC_SECTOFF_HA 36 + +/* PowerPC relocations defined for the TLS access ABI. */ +#define R_PPC_TLS 67 /* none (sym+add)@tls */ +#define R_PPC_DTPMOD32 68 /* word32 (sym+add)@dtpmod */ +#define R_PPC_TPREL16 69 /* half16* (sym+add)@tprel */ +#define R_PPC_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */ +#define R_PPC_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */ +#define R_PPC_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */ +#define R_PPC_TPREL32 73 /* word32 (sym+add)@tprel */ +#define R_PPC_DTPREL16 74 /* half16* (sym+add)@dtprel */ +#define R_PPC_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */ +#define R_PPC_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */ +#define R_PPC_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */ +#define R_PPC_DTPREL32 78 /* word32 (sym+add)@dtprel */ +#define R_PPC_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */ +#define R_PPC_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */ +#define R_PPC_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */ +#define R_PPC_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */ +#define R_PPC_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */ +#define R_PPC_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */ +#define R_PPC_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */ +#define R_PPC_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */ +#define R_PPC_GOT_TPREL16 87 /* half16* (sym+add)@got@tprel */ +#define R_PPC_GOT_TPREL16_LO 88 /* half16 (sym+add)@got@tprel@l */ +#define R_PPC_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */ +#define R_PPC_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */ +#define R_PPC_GOT_DTPREL16 91 /* half16* (sym+add)@got@dtprel */ +#define R_PPC_GOT_DTPREL16_LO 92 /* half16* (sym+add)@got@dtprel@l */ +#define R_PPC_GOT_DTPREL16_HI 93 /* half16* (sym+add)@got@dtprel@h */ +#define R_PPC_GOT_DTPREL16_HA 94 /* half16* (sym+add)@got@dtprel@ha */ + +/* Keep this the last entry. */ +#define R_PPC_NUM 95 + +/* The remaining relocs are from the Embedded ELF ABI, and are not + in the SVR4 ELF ABI. */ +#define R_PPC_EMB_NADDR32 101 +#define R_PPC_EMB_NADDR16 102 +#define R_PPC_EMB_NADDR16_LO 103 +#define R_PPC_EMB_NADDR16_HI 104 +#define R_PPC_EMB_NADDR16_HA 105 +#define R_PPC_EMB_SDAI16 106 +#define R_PPC_EMB_SDA2I16 107 +#define R_PPC_EMB_SDA2REL 108 +#define R_PPC_EMB_SDA21 109 /* 16 bit offset in SDA */ +#define R_PPC_EMB_MRKREF 110 +#define R_PPC_EMB_RELSEC16 111 +#define R_PPC_EMB_RELST_LO 112 +#define R_PPC_EMB_RELST_HI 113 +#define R_PPC_EMB_RELST_HA 114 +#define R_PPC_EMB_BIT_FLD 115 +#define R_PPC_EMB_RELSDA 116 /* 16 bit relative offset in SDA */ + +/* Diab tool relocations. */ +#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */ +#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */ +#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */ +#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */ +#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */ +#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */ + +/* This is a phony reloc to handle any old fashioned TOC16 references + that may still be in object files. */ +#define R_PPC_TOC16 255 + + +/* PowerPC64 relocations defined by the ABIs */ +#define R_PPC64_NONE R_PPC_NONE +#define R_PPC64_ADDR32 R_PPC_ADDR32 /* 32bit absolute address */ +#define R_PPC64_ADDR24 R_PPC_ADDR24 /* 26bit address, word aligned */ +#define R_PPC64_ADDR16 R_PPC_ADDR16 /* 16bit absolute address */ +#define R_PPC64_ADDR16_LO R_PPC_ADDR16_LO /* lower 16bits of address */ +#define R_PPC64_ADDR16_HI R_PPC_ADDR16_HI /* high 16bits of address. */ +#define R_PPC64_ADDR16_HA R_PPC_ADDR16_HA /* adjusted high 16bits. */ +#define R_PPC64_ADDR14 R_PPC_ADDR14 /* 16bit address, word aligned */ +#define R_PPC64_ADDR14_BRTAKEN R_PPC_ADDR14_BRTAKEN +#define R_PPC64_ADDR14_BRNTAKEN R_PPC_ADDR14_BRNTAKEN +#define R_PPC64_REL24 R_PPC_REL24 /* PC-rel. 26 bit, word aligned */ +#define R_PPC64_REL14 R_PPC_REL14 /* PC relative 16 bit */ +#define R_PPC64_REL14_BRTAKEN R_PPC_REL14_BRTAKEN +#define R_PPC64_REL14_BRNTAKEN R_PPC_REL14_BRNTAKEN +#define R_PPC64_GOT16 R_PPC_GOT16 +#define R_PPC64_GOT16_LO R_PPC_GOT16_LO +#define R_PPC64_GOT16_HI R_PPC_GOT16_HI +#define R_PPC64_GOT16_HA R_PPC_GOT16_HA + +#define R_PPC64_COPY R_PPC_COPY +#define R_PPC64_GLOB_DAT R_PPC_GLOB_DAT +#define R_PPC64_JMP_SLOT R_PPC_JMP_SLOT +#define R_PPC64_RELATIVE R_PPC_RELATIVE + +#define R_PPC64_UADDR32 R_PPC_UADDR32 +#define R_PPC64_UADDR16 R_PPC_UADDR16 +#define R_PPC64_REL32 R_PPC_REL32 +#define R_PPC64_PLT32 R_PPC_PLT32 +#define R_PPC64_PLTREL32 R_PPC_PLTREL32 +#define R_PPC64_PLT16_LO R_PPC_PLT16_LO +#define R_PPC64_PLT16_HI R_PPC_PLT16_HI +#define R_PPC64_PLT16_HA R_PPC_PLT16_HA + +#define R_PPC64_SECTOFF R_PPC_SECTOFF +#define R_PPC64_SECTOFF_LO R_PPC_SECTOFF_LO +#define R_PPC64_SECTOFF_HI R_PPC_SECTOFF_HI +#define R_PPC64_SECTOFF_HA R_PPC_SECTOFF_HA +#define R_PPC64_ADDR30 37 /* word30 (S + A - P) >> 2 */ +#define R_PPC64_ADDR64 38 /* doubleword64 S + A */ +#define R_PPC64_ADDR16_HIGHER 39 /* half16 #higher(S + A) */ +#define R_PPC64_ADDR16_HIGHERA 40 /* half16 #highera(S + A) */ +#define R_PPC64_ADDR16_HIGHEST 41 /* half16 #highest(S + A) */ +#define R_PPC64_ADDR16_HIGHESTA 42 /* half16 #highesta(S + A) */ +#define R_PPC64_UADDR64 43 /* doubleword64 S + A */ +#define R_PPC64_REL64 44 /* doubleword64 S + A - P */ +#define R_PPC64_PLT64 45 /* doubleword64 L + A */ +#define R_PPC64_PLTREL64 46 /* doubleword64 L + A - P */ +#define R_PPC64_TOC16 47 /* half16* S + A - .TOC */ +#define R_PPC64_TOC16_LO 48 /* half16 #lo(S + A - .TOC.) */ +#define R_PPC64_TOC16_HI 49 /* half16 #hi(S + A - .TOC.) */ +#define R_PPC64_TOC16_HA 50 /* half16 #ha(S + A - .TOC.) */ +#define R_PPC64_TOC 51 /* doubleword64 .TOC */ +#define R_PPC64_PLTGOT16 52 /* half16* M + A */ +#define R_PPC64_PLTGOT16_LO 53 /* half16 #lo(M + A) */ +#define R_PPC64_PLTGOT16_HI 54 /* half16 #hi(M + A) */ +#define R_PPC64_PLTGOT16_HA 55 /* half16 #ha(M + A) */ + +#define R_PPC64_ADDR16_DS 56 /* half16ds* (S + A) >> 2 */ +#define R_PPC64_ADDR16_LO_DS 57 /* half16ds #lo(S + A) >> 2 */ +#define R_PPC64_GOT16_DS 58 /* half16ds* (G + A) >> 2 */ +#define R_PPC64_GOT16_LO_DS 59 /* half16ds #lo(G + A) >> 2 */ +#define R_PPC64_PLT16_LO_DS 60 /* half16ds #lo(L + A) >> 2 */ +#define R_PPC64_SECTOFF_DS 61 /* half16ds* (R + A) >> 2 */ +#define R_PPC64_SECTOFF_LO_DS 62 /* half16ds #lo(R + A) >> 2 */ +#define R_PPC64_TOC16_DS 63 /* half16ds* (S + A - .TOC.) >> 2 */ +#define R_PPC64_TOC16_LO_DS 64 /* half16ds #lo(S + A - .TOC.) >> 2 */ +#define R_PPC64_PLTGOT16_DS 65 /* half16ds* (M + A) >> 2 */ +#define R_PPC64_PLTGOT16_LO_DS 66 /* half16ds #lo(M + A) >> 2 */ + +/* PowerPC64 relocations defined for the TLS access ABI. */ +#define R_PPC64_TLS 67 /* none (sym+add)@tls */ +#define R_PPC64_DTPMOD64 68 /* doubleword64 (sym+add)@dtpmod */ +#define R_PPC64_TPREL16 69 /* half16* (sym+add)@tprel */ +#define R_PPC64_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */ +#define R_PPC64_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */ +#define R_PPC64_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */ +#define R_PPC64_TPREL64 73 /* doubleword64 (sym+add)@tprel */ +#define R_PPC64_DTPREL16 74 /* half16* (sym+add)@dtprel */ +#define R_PPC64_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */ +#define R_PPC64_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */ +#define R_PPC64_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */ +#define R_PPC64_DTPREL64 78 /* doubleword64 (sym+add)@dtprel */ +#define R_PPC64_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */ +#define R_PPC64_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */ +#define R_PPC64_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */ +#define R_PPC64_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */ +#define R_PPC64_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */ +#define R_PPC64_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */ +#define R_PPC64_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */ +#define R_PPC64_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */ +#define R_PPC64_GOT_TPREL16_DS 87 /* half16ds* (sym+add)@got@tprel */ +#define R_PPC64_GOT_TPREL16_LO_DS 88 /* half16ds (sym+add)@got@tprel@l */ +#define R_PPC64_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */ +#define R_PPC64_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */ +#define R_PPC64_GOT_DTPREL16_DS 91 /* half16ds* (sym+add)@got@dtprel */ +#define R_PPC64_GOT_DTPREL16_LO_DS 92 /* half16ds (sym+add)@got@dtprel@l */ +#define R_PPC64_GOT_DTPREL16_HI 93 /* half16 (sym+add)@got@dtprel@h */ +#define R_PPC64_GOT_DTPREL16_HA 94 /* half16 (sym+add)@got@dtprel@ha */ +#define R_PPC64_TPREL16_DS 95 /* half16ds* (sym+add)@tprel */ +#define R_PPC64_TPREL16_LO_DS 96 /* half16ds (sym+add)@tprel@l */ +#define R_PPC64_TPREL16_HIGHER 97 /* half16 (sym+add)@tprel@higher */ +#define R_PPC64_TPREL16_HIGHERA 98 /* half16 (sym+add)@tprel@highera */ +#define R_PPC64_TPREL16_HIGHEST 99 /* half16 (sym+add)@tprel@highest */ +#define R_PPC64_TPREL16_HIGHESTA 100 /* half16 (sym+add)@tprel@highesta */ +#define R_PPC64_DTPREL16_DS 101 /* half16ds* (sym+add)@dtprel */ +#define R_PPC64_DTPREL16_LO_DS 102 /* half16ds (sym+add)@dtprel@l */ +#define R_PPC64_DTPREL16_HIGHER 103 /* half16 (sym+add)@dtprel@higher */ +#define R_PPC64_DTPREL16_HIGHERA 104 /* half16 (sym+add)@dtprel@highera */ +#define R_PPC64_DTPREL16_HIGHEST 105 /* half16 (sym+add)@dtprel@highest */ +#define R_PPC64_DTPREL16_HIGHESTA 106 /* half16 (sym+add)@dtprel@highesta */ + +/* Keep this the last entry. */ +#define R_PPC64_NUM 107 + +/* PowerPC64 specific values for the Dyn d_tag field. */ +#define DT_PPC64_GLINK (DT_LOPROC + 0) +#define DT_PPC64_NUM 1 + + +/* ARM specific declarations */ + +/* Processor specific flags for the ELF header e_flags field. */ +#define EF_ARM_RELEXEC 0x01 +#define EF_ARM_HASENTRY 0x02 +#define EF_ARM_INTERWORK 0x04 +#define EF_ARM_APCS_26 0x08 +#define EF_ARM_APCS_FLOAT 0x10 +#define EF_ARM_PIC 0x20 +#define EF_ARM_ALIGN8 0x40 /* 8-bit structure alignment is in use */ +#define EF_ARM_NEW_ABI 0x80 +#define EF_ARM_OLD_ABI 0x100 + +/* Other constants defined in the ARM ELF spec. version B-01. */ +/* NB. These conflict with values defined above. */ +#define EF_ARM_SYMSARESORTED 0x04 +#define EF_ARM_DYNSYMSUSESEGIDX 0x08 +#define EF_ARM_MAPSYMSFIRST 0x10 +#define EF_ARM_EABIMASK 0XFF000000 + +#define EF_ARM_EABI_VERSION(flags) ((flags) & EF_ARM_EABIMASK) +#define EF_ARM_EABI_UNKNOWN 0x00000000 +#define EF_ARM_EABI_VER1 0x01000000 +#define EF_ARM_EABI_VER2 0x02000000 + +/* Additional symbol types for Thumb */ +#define STT_ARM_TFUNC 0xd + +/* ARM-specific values for sh_flags */ +#define SHF_ARM_ENTRYSECT 0x10000000 /* Section contains an entry point */ +#define SHF_ARM_COMDEF 0x80000000 /* Section may be multiply defined + in the input to a link step */ + +/* ARM-specific program header flags */ +#define PF_ARM_SB 0x10000000 /* Segment contains the location + addressed by the static base */ + +/* ARM relocs. */ +#define R_ARM_NONE 0 /* No reloc */ +#define R_ARM_PC24 1 /* PC relative 26 bit branch */ +#define R_ARM_ABs32 2 /* Direct 32 bit */ +#define R_ARM_REL32 3 /* PC relative 32 bit */ +#define R_ARM_PC13 4 +#define R_ARM_ABs16 5 /* Direct 16 bit */ +#define R_ARM_ABS12 6 /* Direct 12 bit */ +#define R_ARM_THM_ABS5 7 +#define R_ARM_ABs8 8 /* Direct 8 bit */ +#define R_ARM_SBREL32 9 +#define R_ARM_THM_PC22 10 +#define R_ARM_THM_PC8 11 +#define R_ARM_AMP_VCALL9 12 +#define R_ARM_SWI24 13 +#define R_ARM_THM_SWI8 14 +#define R_ARM_XPC25 15 +#define R_ARM_THM_XPC22 16 +#define R_ARM_COPY 20 /* Copy symbol at runtime */ +#define R_ARM_GLOB_DAT 21 /* Create GOT entry */ +#define R_ARM_JUMP_SLOT 22 /* Create PLT entry */ +#define R_ARM_RELATIVE 23 /* Adjust by program base */ +#define R_ARM_GOTOFF 24 /* 32 bit offset to GOT */ +#define R_ARM_GOTPC 25 /* 32 bit PC relative offset to GOT */ +#define R_ARM_GOT32 26 /* 32 bit GOT entry */ +#define R_ARM_PLT32 27 /* 32 bit PLT address */ +#define R_ARM_ALU_PCREL_7_0 32 +#define R_ARM_ALU_PCREL_15_8 33 +#define R_ARM_ALU_PCREL_23_15 34 +#define R_ARM_LDR_SBREL_11_0 35 +#define R_ARM_ALU_SBREL_19_12 36 +#define R_ARM_ALU_SBREL_27_20 37 +#define R_ARM_GNU_VTENTRY 100 +#define R_ARM_GNU_VTINHERIT 101 +#define R_ARM_THM_PC11 102 /* thumb unconditional branch */ +#define R_ARM_THM_PC9 103 /* thumb conditional branch */ +#define R_ARM_RXPC25 249 +#define R_ARM_RSBREL32 250 +#define R_ARM_THM_RPC22 251 +#define R_ARM_RREL32 252 +#define R_ARM_RABS22 253 +#define R_ARM_RPC24 254 +#define R_ARM_RBASE 255 +/* Keep this the last entry. */ +#define R_ARM_NUM 256 + +/* IA-64 specific declarations. */ + +/* Processor specific flags for the Ehdr e_flags field. */ +#define EF_IA_64_MASKOS 0x0000000f /* os-specific flags */ +#define EF_IA_64_ABI64 0x00000010 /* 64-bit ABI */ +#define EF_IA_64_ARCH 0xff000000 /* arch. version mask */ + +/* Processor specific values for the Phdr p_type field. */ +#define PT_IA_64_ARCHEXT (PT_LOPROC + 0) /* arch extension bits */ +#define PT_IA_64_UNWIND (PT_LOPROC + 1) /* ia64 unwind bits */ + +/* Processor specific flags for the Phdr p_flags field. */ +#define PF_IA_64_NORECOV 0x80000000 /* spec insns w/o recovery */ + +/* Processor specific values for the Shdr sh_type field. */ +#define SHT_IA_64_EXT (SHT_LOPROC + 0) /* extension bits */ +#define SHT_IA_64_UNWIND (SHT_LOPROC + 1) /* unwind bits */ + +/* Processor specific flags for the Shdr sh_flags field. */ +#define SHF_IA_64_SHORT 0x10000000 /* section near gp */ +#define SHF_IA_64_NORECOV 0x20000000 /* spec insns w/o recovery */ + +/* Processor specific values for the Dyn d_tag field. */ +#define DT_IA_64_PLT_RESERVE (DT_LOPROC + 0) +#define DT_IA_64_NUM 1 + +/* IA-64 relocations. */ +#define R_IA64_NONE 0x00 /* none */ +#define R_IA64_IMM14 0x21 /* symbol + addend, add imm14 */ +#define R_IA64_IMM22 0x22 /* symbol + addend, add imm22 */ +#define R_IA64_IMM64 0x23 /* symbol + addend, mov imm64 */ +#define R_IA64_DIR32MSB 0x24 /* symbol + addend, data4 MSB */ +#define R_IA64_DIR32LSB 0x25 /* symbol + addend, data4 LSB */ +#define R_IA64_DIR64MSB 0x26 /* symbol + addend, data8 MSB */ +#define R_IA64_DIR64LSB 0x27 /* symbol + addend, data8 LSB */ +#define R_IA64_GPREL22 0x2a /* @gprel(sym + add), add imm22 */ +#define R_IA64_GPREL64I 0x2b /* @gprel(sym + add), mov imm64 */ +#define R_IA64_GPREL32MSB 0x2c /* @gprel(sym + add), data4 MSB */ +#define R_IA64_GPREL32LSB 0x2d /* @gprel(sym + add), data4 LSB */ +#define R_IA64_GPREL64MSB 0x2e /* @gprel(sym + add), data8 MSB */ +#define R_IA64_GPREL64LSB 0x2f /* @gprel(sym + add), data8 LSB */ +#define R_IA64_LTOFF22 0x32 /* @ltoff(sym + add), add imm22 */ +#define R_IA64_LTOFF64I 0x33 /* @ltoff(sym + add), mov imm64 */ +#define R_IA64_PLTOFF22 0x3a /* @pltoff(sym + add), add imm22 */ +#define R_IA64_PLTOFF64I 0x3b /* @pltoff(sym + add), mov imm64 */ +#define R_IA64_PLTOFF64MSB 0x3e /* @pltoff(sym + add), data8 MSB */ +#define R_IA64_PLTOFF64LSB 0x3f /* @pltoff(sym + add), data8 LSB */ +#define R_IA64_FPTR64I 0x43 /* @fptr(sym + add), mov imm64 */ +#define R_IA64_FPTR32MSB 0x44 /* @fptr(sym + add), data4 MSB */ +#define R_IA64_FPTR32LSB 0x45 /* @fptr(sym + add), data4 LSB */ +#define R_IA64_FPTR64MSB 0x46 /* @fptr(sym + add), data8 MSB */ +#define R_IA64_FPTR64LSB 0x47 /* @fptr(sym + add), data8 LSB */ +#define R_IA64_PCREL60B 0x48 /* @pcrel(sym + add), brl */ +#define R_IA64_PCREL21B 0x49 /* @pcrel(sym + add), ptb, call */ +#define R_IA64_PCREL21M 0x4a /* @pcrel(sym + add), chk.s */ +#define R_IA64_PCREL21F 0x4b /* @pcrel(sym + add), fchkf */ +#define R_IA64_PCREL32MSB 0x4c /* @pcrel(sym + add), data4 MSB */ +#define R_IA64_PCREL32LSB 0x4d /* @pcrel(sym + add), data4 LSB */ +#define R_IA64_PCREL64MSB 0x4e /* @pcrel(sym + add), data8 MSB */ +#define R_IA64_PCREL64LSB 0x4f /* @pcrel(sym + add), data8 LSB */ +#define R_IA64_LTOFF_FPTR22 0x52 /* @ltoff(@fptr(s+a)), imm22 */ +#define R_IA64_LTOFF_FPTR64I 0x53 /* @ltoff(@fptr(s+a)), imm64 */ +#define R_IA64_LTOFF_FPTR32MSB 0x54 /* @ltoff(@fptr(s+a)), data4 MSB */ +#define R_IA64_LTOFF_FPTR32LSB 0x55 /* @ltoff(@fptr(s+a)), data4 LSB */ +#define R_IA64_LTOFF_FPTR64MSB 0x56 /* @ltoff(@fptr(s+a)), data8 MSB */ +#define R_IA64_LTOFF_FPTR64LSB 0x57 /* @ltoff(@fptr(s+a)), data8 LSB */ +#define R_IA64_SEGREL32MSB 0x5c /* @segrel(sym + add), data4 MSB */ +#define R_IA64_SEGREL32LSB 0x5d /* @segrel(sym + add), data4 LSB */ +#define R_IA64_SEGREL64MSB 0x5e /* @segrel(sym + add), data8 MSB */ +#define R_IA64_SEGREL64LSB 0x5f /* @segrel(sym + add), data8 LSB */ +#define R_IA64_SECREL32MSB 0x64 /* @secrel(sym + add), data4 MSB */ +#define R_IA64_SECREL32LSB 0x65 /* @secrel(sym + add), data4 LSB */ +#define R_IA64_SECREL64MSB 0x66 /* @secrel(sym + add), data8 MSB */ +#define R_IA64_SECREL64LSB 0x67 /* @secrel(sym + add), data8 LSB */ +#define R_IA64_REL32MSB 0x6c /* data 4 + REL */ +#define R_IA64_REL32LSB 0x6d /* data 4 + REL */ +#define R_IA64_REL64MSB 0x6e /* data 8 + REL */ +#define R_IA64_REL64LSB 0x6f /* data 8 + REL */ +#define R_IA64_LTV32MSB 0x74 /* symbol + addend, data4 MSB */ +#define R_IA64_LTV32LSB 0x75 /* symbol + addend, data4 LSB */ +#define R_IA64_LTV64MSB 0x76 /* symbol + addend, data8 MSB */ +#define R_IA64_LTV64LSB 0x77 /* symbol + addend, data8 LSB */ +#define R_IA64_PCREL21BI 0x79 /* @pcrel(sym + add), 21bit inst */ +#define R_IA64_PCREL22 0x7a /* @pcrel(sym + add), 22bit inst */ +#define R_IA64_PCREL64I 0x7b /* @pcrel(sym + add), 64bit inst */ +#define R_IA64_IPLTMSB 0x80 /* dynamic reloc, imported PLT, MSB */ +#define R_IA64_IPLTLSB 0x81 /* dynamic reloc, imported PLT, LSB */ +#define R_IA64_COPY 0x84 /* copy relocation */ +#define R_IA64_SUB 0x85 /* Addend and symbol difference */ +#define R_IA64_LTOFF22X 0x86 /* LTOFF22, relaxable. */ +#define R_IA64_LDXMOV 0x87 /* Use of LTOFF22X. */ +#define R_IA64_TPREL14 0x91 /* @tprel(sym + add), imm14 */ +#define R_IA64_TPREL22 0x92 /* @tprel(sym + add), imm22 */ +#define R_IA64_TPREL64I 0x93 /* @tprel(sym + add), imm64 */ +#define R_IA64_TPREL64MSB 0x96 /* @tprel(sym + add), data8 MSB */ +#define R_IA64_TPREL64LSB 0x97 /* @tprel(sym + add), data8 LSB */ +#define R_IA64_LTOFF_TPREL22 0x9a /* @ltoff(@tprel(s+a)), imm2 */ +#define R_IA64_DTPMOD64MSB 0xa6 /* @dtpmod(sym + add), data8 MSB */ +#define R_IA64_DTPMOD64LSB 0xa7 /* @dtpmod(sym + add), data8 LSB */ +#define R_IA64_LTOFF_DTPMOD22 0xaa /* @ltoff(@dtpmod(sym + add)), imm22 */ +#define R_IA64_DTPREL14 0xb1 /* @dtprel(sym + add), imm14 */ +#define R_IA64_DTPREL22 0xb2 /* @dtprel(sym + add), imm22 */ +#define R_IA64_DTPREL64I 0xb3 /* @dtprel(sym + add), imm64 */ +#define R_IA64_DTPREL32MSB 0xb4 /* @dtprel(sym + add), data4 MSB */ +#define R_IA64_DTPREL32LSB 0xb5 /* @dtprel(sym + add), data4 LSB */ +#define R_IA64_DTPREL64MSB 0xb6 /* @dtprel(sym + add), data8 MSB */ +#define R_IA64_DTPREL64LSB 0xb7 /* @dtprel(sym + add), data8 LSB */ +#define R_IA64_LTOFF_DTPREL22 0xba /* @ltoff(@dtprel(s+a)), imm22 */ + +/* SH specific declarations */ + +/* SH relocs. */ +#define R_SH_NONE 0 +#define R_SH_DIR32 1 +#define R_SH_REL32 2 +#define R_SH_DIR8WPN 3 +#define R_SH_IND12W 4 +#define R_SH_DIR8WPL 5 +#define R_SH_DIR8WPZ 6 +#define R_SH_DIR8BP 7 +#define R_SH_DIR8W 8 +#define R_SH_DIR8L 9 +#define R_SH_SWITCH16 25 +#define R_SH_SWITCH32 26 +#define R_SH_USES 27 +#define R_SH_COUNT 28 +#define R_SH_ALIGN 29 +#define R_SH_CODE 30 +#define R_SH_DATA 31 +#define R_SH_LABEL 32 +#define R_SH_SWITCH8 33 +#define R_SH_GNU_VTINHERIT 34 +#define R_SH_GNU_VTENTRY 35 +#define R_SH_TLS_GD_32 144 +#define R_SH_TLS_LD_32 145 +#define R_SH_TLS_LDO_32 146 +#define R_SH_TLS_IE_32 147 +#define R_SH_TLS_LE_32 148 +#define R_SH_TLS_DTPMOD32 149 +#define R_SH_TLS_DTPOFF32 150 +#define R_SH_TLS_TPOFF32 151 +#define R_SH_GOT32 160 +#define R_SH_PLT32 161 +#define R_SH_COPY 162 +#define R_SH_GLOB_DAT 163 +#define R_SH_JMP_SLOT 164 +#define R_SH_RELATIVE 165 +#define R_SH_GOTOFF 166 +#define R_SH_GOTPC 167 +/* Keep this the last entry. */ +#define R_SH_NUM 256 + +/* Additional s390 relocs */ + +#define R_390_NONE 0 /* No reloc. */ +#define R_390_8 1 /* Direct 8 bit. */ +#define R_390_12 2 /* Direct 12 bit. */ +#define R_390_16 3 /* Direct 16 bit. */ +#define R_390_32 4 /* Direct 32 bit. */ +#define R_390_PC32 5 /* PC relative 32 bit. */ +#define R_390_GOT12 6 /* 12 bit GOT offset. */ +#define R_390_GOT32 7 /* 32 bit GOT offset. */ +#define R_390_PLT32 8 /* 32 bit PC relative PLT address. */ +#define R_390_COPY 9 /* Copy symbol at runtime. */ +#define R_390_GLOB_DAT 10 /* Create GOT entry. */ +#define R_390_JMP_SLOT 11 /* Create PLT entry. */ +#define R_390_RELATIVE 12 /* Adjust by program base. */ +#define R_390_GOTOFF32 13 /* 32 bit offset to GOT. */ +#define R_390_GOTPC 14 /* 32 bit PC relative offset to GOT. */ +#define R_390_GOT16 15 /* 16 bit GOT offset. */ +#define R_390_PC16 16 /* PC relative 16 bit. */ +#define R_390_PC16DBL 17 /* PC relative 16 bit shifted by 1. */ +#define R_390_PLT16DBL 18 /* 16 bit PC rel. PLT shifted by 1. */ +#define R_390_PC32DBL 19 /* PC relative 32 bit shifted by 1. */ +#define R_390_PLT32DBL 20 /* 32 bit PC rel. PLT shifted by 1. */ +#define R_390_GOTPCDBL 21 /* 32 bit PC rel. GOT shifted by 1. */ +#define R_390_64 22 /* Direct 64 bit. */ +#define R_390_PC64 23 /* PC relative 64 bit. */ +#define R_390_GOT64 24 /* 64 bit GOT offset. */ +#define R_390_PLT64 25 /* 64 bit PC relative PLT address. */ +#define R_390_GOTENT 26 /* 32 bit PC rel. to GOT entry >> 1. */ +#define R_390_GOTOFF16 27 /* 16 bit offset to GOT. */ +#define R_390_GOTOFF64 28 /* 64 bit offset to GOT. */ +#define R_390_GOTPLT12 29 /* 12 bit offset to jump slot. */ +#define R_390_GOTPLT16 30 /* 16 bit offset to jump slot. */ +#define R_390_GOTPLT32 31 /* 32 bit offset to jump slot. */ +#define R_390_GOTPLT64 32 /* 64 bit offset to jump slot. */ +#define R_390_GOTPLTENT 33 /* 32 bit rel. offset to jump slot. */ +#define R_390_PLTOFF16 34 /* 16 bit offset from GOT to PLT. */ +#define R_390_PLTOFF32 35 /* 32 bit offset from GOT to PLT. */ +#define R_390_PLTOFF64 36 /* 16 bit offset from GOT to PLT. */ +#define R_390_TLS_LOAD 37 /* Tag for load insn in TLS code. */ +#define R_390_TLS_GDCALL 38 /* Tag for function call in general + dynamic TLS code. */ +#define R_390_TLS_LDCALL 39 /* Tag for function call in local + dynamic TLS code. */ +#define R_390_TLS_GD32 40 /* Direct 32 bit for general dynamic + thread local data. */ +#define R_390_TLS_GD64 41 /* Direct 64 bit for general dynamic + thread local data. */ +#define R_390_TLS_GOTIE12 42 /* 12 bit GOT offset for static TLS + block offset. */ +#define R_390_TLS_GOTIE32 43 /* 32 bit GOT offset for static TLS + block offset. */ +#define R_390_TLS_GOTIE64 44 /* 64 bit GOT offset for static TLS + block offset. */ +#define R_390_TLS_LDM32 45 /* Direct 32 bit for local dynamic + thread local data in LE code. */ +#define R_390_TLS_LDM64 46 /* Direct 64 bit for local dynamic + thread local data in LE code. */ +#define R_390_TLS_IE32 47 /* 32 bit address of GOT entry for + negated static TLS block offset. */ +#define R_390_TLS_IE64 48 /* 64 bit address of GOT entry for + negated static TLS block offset. */ +#define R_390_TLS_IEENT 49 /* 32 bit rel. offset to GOT entry for + negated static TLS block offset. */ +#define R_390_TLS_LE32 50 /* 32 bit negated offset relative to + static TLS block. */ +#define R_390_TLS_LE64 51 /* 64 bit negated offset relative to + static TLS block. */ +#define R_390_TLS_LDO32 52 /* 32 bit offset relative to TLS + block. */ +#define R_390_TLS_LDO64 53 /* 64 bit offset relative to TLS + block. */ +#define R_390_TLS_DTPMOD 54 /* ID of module containing symbol. */ +#define R_390_TLS_DTPOFF 55 /* Offset in TLS block. */ +#define R_390_TLS_TPOFF 56 /* Negated offset in static TLS + block. */ + +/* Keep this the last entry. */ +#define R_390_NUM 57 + +/* CRIS relocations. */ +#define R_CRIS_NONE 0 +#define R_CRIS_8 1 +#define R_CRIS_16 2 +#define R_CRIS_32 3 +#define R_CRIS_8_PCREL 4 +#define R_CRIS_16_PCREL 5 +#define R_CRIS_32_PCREL 6 +#define R_CRIS_GNU_VTINHERIT 7 +#define R_CRIS_GNU_VTENTRY 8 +#define R_CRIS_COPY 9 +#define R_CRIS_GLOB_DAT 10 +#define R_CRIS_JUMP_SLOT 11 +#define R_CRIS_RELATIVE 12 +#define R_CRIS_16_GOT 13 +#define R_CRIS_32_GOT 14 +#define R_CRIS_16_GOTPLT 15 +#define R_CRIS_32_GOTPLT 16 +#define R_CRIS_32_GOTREL 17 +#define R_CRIS_32_PLT_GOTREL 18 +#define R_CRIS_32_PLT_PCREL 19 + +#define R_CRIS_NUM 20 + +/* AMD x86-64 relocations. */ +#define R_X86_64_NONE 0 /* No reloc */ +#define R_X86_64_64 1 /* Direct 64 bit */ +#define R_X86_64_PC32 2 /* PC relative 32 bit signed */ +#define R_X86_64_GOT32 3 /* 32 bit GOT entry */ +#define R_X86_64_PLT32 4 /* 32 bit PLT address */ +#define R_X86_64_COPY 5 /* Copy symbol at runtime */ +#define R_X86_64_GLOB_DAT 6 /* Create GOT entry */ +#define R_X86_64_JUMP_SLOT 7 /* Create PLT entry */ +#define R_X86_64_RELATIVE 8 /* Adjust by program base */ +#define R_X86_64_GOTPCREL 9 /* 32 bit signed PC relative + offset to GOT */ +#define R_X86_64_32 10 /* Direct 32 bit zero extended */ +#define R_X86_64_32S 11 /* Direct 32 bit sign extended */ +#define R_X86_64_16 12 /* Direct 16 bit zero extended */ +#define R_X86_64_PC16 13 /* 16 bit sign extended pc relative */ +#define R_X86_64_8 14 /* Direct 8 bit sign extended */ +#define R_X86_64_PC8 15 /* 8 bit sign extended pc relative */ +#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */ +#define R_X86_64_DTPOFF64 17 /* Offset in module's TLS block */ +#define R_X86_64_TPOFF64 18 /* Offset in initial TLS block */ +#define R_X86_64_TLSGD 19 /* 32 bit signed PC relative offset + to two GOT entries for GD symbol */ +#define R_X86_64_TLSLD 20 /* 32 bit signed PC relative offset + to two GOT entries for LD symbol */ +#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */ +#define R_X86_64_GOTTPOFF 22 /* 32 bit signed PC relative offset + to GOT entry for IE symbol */ +#define R_X86_64_TPOFF32 23 /* Offset in initial TLS block */ + +#define R_X86_64_NUM 24 + +#endif /* elf.h */ diff --git a/scetool/elf_inlines.h b/scetool/elf_inlines.h new file mode 100644 index 0000000000..ce36290552 --- /dev/null +++ b/scetool/elf_inlines.h @@ -0,0 +1,136 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _ELF_INLINES_H_ +#define _ELF_INLINES_H_ + +#include + +#include "types.h" +#include "elf.h" + +static inline void _es_elf32_ehdr(Elf32_Ehdr *h) +{ + h->e_type = _Es16(h->e_type); + h->e_machine = _Es16(h->e_machine); + h->e_version = _Es32(h->e_version); + h->e_entry = _Es32(h->e_entry); + h->e_phoff = _Es32(h->e_phoff); + h->e_shoff = _Es32(h->e_shoff); + h->e_flags = _Es32(h->e_flags); + h->e_ehsize = _Es16(h->e_ehsize); + h->e_phentsize = _Es16(h->e_phentsize); + h->e_phnum = _Es16(h->e_phnum); + h->e_shentsize = _Es16(h->e_shentsize); + h->e_shnum = _Es16(h->e_shnum); + h->e_shstrndx = _Es16(h->e_shstrndx); +} + +static inline void _copy_es_elf32_ehdr(Elf32_Ehdr *dst, Elf32_Ehdr *src) +{ + memcpy(dst, src, sizeof(Elf32_Ehdr)); + _es_elf32_ehdr(dst); +} + +static inline void _es_elf64_ehdr(Elf64_Ehdr *h) +{ + h->e_type = _Es16(h->e_type); + h->e_machine = _Es16(h->e_machine); + h->e_version = _Es32(h->e_version); + h->e_entry = _Es64(h->e_entry); + h->e_phoff = _Es64(h->e_phoff); + h->e_shoff = _Es64(h->e_shoff); + h->e_flags = _Es32(h->e_flags); + h->e_ehsize = _Es16(h->e_ehsize); + h->e_phentsize = _Es16(h->e_phentsize); + h->e_phnum = _Es16(h->e_phnum); + h->e_shentsize = _Es16(h->e_shentsize); + h->e_shnum = _Es16(h->e_shnum); + h->e_shstrndx = _Es16(h->e_shstrndx); +} + +static inline void _copy_es_elf64_ehdr(Elf64_Ehdr *dst, Elf64_Ehdr *src) +{ + memcpy(dst, src, sizeof(Elf64_Ehdr)); + _es_elf64_ehdr(dst); +} + +static inline void _es_elf32_shdr(Elf32_Shdr *h) +{ + h->sh_name = _Es32(h->sh_name); + h->sh_type = _Es32(h->sh_type); + h->sh_flags = _Es32(h->sh_flags); + h->sh_addr = _Es32(h->sh_addr); + h->sh_offset = _Es32(h->sh_offset); + h->sh_size = _Es32(h->sh_size); + h->sh_link = _Es32(h->sh_link); + h->sh_info = _Es32(h->sh_info); + h->sh_addralign = _Es32(h->sh_addralign); + h->sh_entsize = _Es32(h->sh_entsize); +} + +static inline void _copy_es_elf32_shdr(Elf32_Shdr *dst, Elf32_Shdr *src) +{ + memcpy(dst, src, sizeof(Elf32_Shdr)); + _es_elf32_shdr(dst); +} + +static inline void _es_elf64_shdr(Elf64_Shdr *h) +{ + h->sh_name = _Es32(h->sh_name); + h->sh_type = _Es32(h->sh_type); + h->sh_flags = _Es64(h->sh_flags); + h->sh_addr = _Es64(h->sh_addr); + h->sh_offset = _Es64(h->sh_offset); + h->sh_size = _Es64(h->sh_size); + h->sh_link = _Es32(h->sh_link); + h->sh_info = _Es32(h->sh_info); + h->sh_addralign = _Es64(h->sh_addralign); + h->sh_entsize = _Es64(h->sh_entsize); +} + +static inline void _copy_es_elf64_shdr(Elf64_Shdr *dst, Elf64_Shdr *src) +{ + memcpy(dst, src, sizeof(Elf64_Shdr)); + _es_elf64_shdr(dst); +} + +static inline void _es_elf32_phdr(Elf32_Phdr *h) +{ + h->p_type = _Es32(h->p_type); + h->p_offset = _Es32(h->p_offset); + h->p_vaddr = _Es32(h->p_vaddr); + h->p_paddr = _Es32(h->p_paddr); + h->p_filesz = _Es32(h->p_filesz); + h->p_memsz = _Es32(h->p_memsz); + h->p_flags = _Es32(h->p_flags); + h->p_align = _Es32(h->p_align); +} + +static inline void _copy_es_elf32_phdr(Elf32_Phdr *dst, Elf32_Phdr *src) +{ + memcpy(dst, src, sizeof(Elf32_Phdr)); + _es_elf32_phdr(dst); +} + +static inline void _es_elf64_phdr(Elf64_Phdr *h) +{ + h->p_type = _Es32(h->p_type); + h->p_flags = _Es32(h->p_flags); + h->p_offset = _Es64(h->p_offset); + h->p_vaddr = _Es64(h->p_vaddr); + h->p_paddr = _Es64(h->p_paddr); + h->p_filesz = _Es64(h->p_filesz); + h->p_memsz = _Es64(h->p_memsz); + h->p_align = _Es64(h->p_align); +} + +static inline void _copy_es_elf64_phdr(Elf64_Phdr *dst, Elf64_Phdr *src) +{ + memcpy(dst, src, sizeof(Elf64_Phdr)); + _es_elf64_phdr(dst); +} + +#endif diff --git a/scetool/frontend.h b/scetool/frontend.h new file mode 100644 index 0000000000..d59b1e6b0c --- /dev/null +++ b/scetool/frontend.h @@ -0,0 +1,14 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + + +#ifndef _FRONTEND_H_ +#define _FRONTEND_H_ + +void frontend_print_infos(scetool::s8 *file); +void frontend_decrypt(scetool::s8 *file_in, scetool::s8 *file_out); +void frontend_encrypt(scetool::s8 *file_in, scetool::s8 *file_out); + +#endif diff --git a/scetool/getopt.c b/scetool/getopt.c new file mode 100644 index 0000000000..ec665ec501 --- /dev/null +++ b/scetool/getopt.c @@ -0,0 +1,529 @@ +#ifdef _WIN32 + +/* Getopt for Microsoft C +This code is a modification of the Free Software Foundation, Inc. +Getopt library for parsing command line argument the purpose was +to provide a Microsoft Visual C friendly derivative. This code +provides functionality for both Unicode and Multibyte builds. + +Date: 02/03/2011 - Ludvik Jerabek - Initial Release +Version: 1.0 +Comment: Supports getopt, getopt_long, and getopt_long_only +and POSIXLY_CORRECT environment flag +License: LGPL + +Revisions: + +02/03/2011 - Ludvik Jerabek - Initial Release +02/20/2011 - Ludvik Jerabek - Fixed compiler warnings at Level 4 +07/05/2011 - Ludvik Jerabek - Added no_argument, required_argument, optional_argument defs +08/03/2011 - Ludvik Jerabek - Fixed non-argument runtime bug which caused runtime exception +08/09/2011 - Ludvik Jerabek - Added code to export functions for DLL and LIB + +**DISCLAIMER** +THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESS OR IMPLIED, INCLUDING, BUT Not LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE +EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT +APPLY TO YOU. IN NO EVENT WILL I BE LIABLE TO ANY PARTY FOR ANY +DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY +USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST +PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON +YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN If WE ARE +EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +*/ + +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#include "getopt.h" + +enum ENUM_ORDERING { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER }; + +struct _getopt_data +{ + int optind; + int opterr; + int optopt; + TCHAR *optarg; + int __initialized; + TCHAR *__nextchar; + int __ordering; + int __posixly_correct; + int __first_nonopt; + int __last_nonopt; +}; + +static struct _getopt_data getopt_data; + +TCHAR *optarg; +int optind = 1; +int opterr = 1; +int optopt = _T('?'); + +static void exchange(TCHAR **argv, struct _getopt_data *d) +{ + int bottom = d->__first_nonopt; + int middle = d->__last_nonopt; + int top = d->optind; + TCHAR *tem; + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + int len = middle - bottom; + register int i; + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + } + top -= len; + } + else + { + int len = top - middle; + register int i; + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + } + bottom += len; + } + } + d->__first_nonopt += (d->optind - d->__last_nonopt); + d->__last_nonopt = d->optind; +} + +static const TCHAR *_getopt_initialize (const TCHAR *optstring, struct _getopt_data *d, int posixly_correct) +{ + d->__first_nonopt = d->__last_nonopt = d->optind; + d->__nextchar = NULL; + d->__posixly_correct = posixly_correct | !!_tgetenv(_T("POSIXLY_CORRECT")); + + + if (optstring[0] == _T('-')) + { + d->__ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == _T('+')) + { + d->__ordering = REQUIRE_ORDER; + ++optstring; + } + else if (d->__posixly_correct) + d->__ordering = REQUIRE_ORDER; + else + d->__ordering = PERMUTE; + return optstring; +} + +int _getopt_internal_r (int argc, TCHAR *const *argv, const TCHAR *optstring, const struct option *longopts, int *longind, int long_only, struct _getopt_data *d, int posixly_correct) +{ + int print_errors = d->opterr; + + if (argc < 1) + return -1; + + d->optarg = NULL; + + if (d->optind == 0 || !d->__initialized) + { + if (d->optind == 0) + d->optind = 1; + optstring = _getopt_initialize (optstring, d, posixly_correct); + d->__initialized = 1; + } + else if (optstring[0] == _T('-') || optstring[0] == _T('+')) + optstring++; + if (optstring[0] == _T(':')) + print_errors = 0; + + if (d->__nextchar == NULL || *d->__nextchar == _T('\0')) + { + if (d->__last_nonopt > d->optind) + d->__last_nonopt = d->optind; + if (d->__first_nonopt > d->optind) + d->__first_nonopt = d->optind; + + if (d->__ordering == PERMUTE) + { + if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind) + exchange ((TCHAR **) argv, d); + else if (d->__last_nonopt != d->optind) + d->__first_nonopt = d->optind; + + while (d->optind < argc && (argv[d->optind][0] != _T('-') || argv[d->optind][1] == _T('\0'))) + d->optind++; + d->__last_nonopt = d->optind; + } + + if (d->optind != argc && !_tcscmp(argv[d->optind], _T("--"))) + { + d->optind++; + + if (d->__first_nonopt != d->__last_nonopt && d->__last_nonopt != d->optind) + exchange ((TCHAR **) argv, d); + else if (d->__first_nonopt == d->__last_nonopt) + d->__first_nonopt = d->optind; + d->__last_nonopt = argc; + + d->optind = argc; + } + + if (d->optind == argc) + { + if (d->__first_nonopt != d->__last_nonopt) + d->optind = d->__first_nonopt; + return -1; + } + + if ((argv[d->optind][0] != _T('-') || argv[d->optind][1] == _T('\0'))) + { + if (d->__ordering == REQUIRE_ORDER) + return -1; + d->optarg = argv[d->optind++]; + return 1; + } + + d->__nextchar = (argv[d->optind] + 1 + (longopts != NULL && argv[d->optind][1] == _T('-'))); + } + + if (longopts != NULL && (argv[d->optind][1] == _T('-') || (long_only && (argv[d->optind][2] || !_tcschr(optstring, argv[d->optind][1]))))) + { + TCHAR *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = d->__nextchar; *nameend && *nameend != _T('='); nameend++); + + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!_tcsncmp(p->name, d->__nextchar, nameend - d->__nextchar)) + { + if ((unsigned int)(nameend - d->__nextchar) == (unsigned int)_tcslen(p->name)) + { + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + pfound = p; + indfound = option_index; + } + else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val) + ambig = 1; + } + + if (ambig && !exact) + { + if (print_errors) + { + _ftprintf(stderr, _T("%s: option '%s' is ambiguous\n"), + argv[0], argv[d->optind]); + } + d->__nextchar += _tcslen(d->__nextchar); + d->optind++; + d->optopt = 0; + return _T('?'); + } + + if (pfound != NULL) + { + option_index = indfound; + d->optind++; + if (*nameend) + { + if (pfound->has_arg) + d->optarg = nameend + 1; + else + { + if (print_errors) + { + if (argv[d->optind - 1][1] == _T('-')) + { + _ftprintf(stderr, _T("%s: option '--%s' doesn't allow an argument\n"),argv[0], pfound->name); + } + else + { + _ftprintf(stderr, _T("%s: option '%c%s' doesn't allow an argument\n"),argv[0], argv[d->optind - 1][0],pfound->name); + } + + } + + d->__nextchar += _tcslen(d->__nextchar); + + d->optopt = pfound->val; + return _T('?'); + } + } + else if (pfound->has_arg == 1) + { + if (d->optind < argc) + d->optarg = argv[d->optind++]; + else + { + if (print_errors) + { + _ftprintf(stderr,_T("%s: option '--%s' requires an argument\n"),argv[0], pfound->name); + } + d->__nextchar += _tcslen(d->__nextchar); + d->optopt = pfound->val; + return optstring[0] == _T(':') ? _T(':') : _T('?'); + } + } + d->__nextchar += _tcslen(d->__nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + if (!long_only || argv[d->optind][1] == _T('-') || _tcschr(optstring, *d->__nextchar) == NULL) + { + if (print_errors) + { + if (argv[d->optind][1] == _T('-')) + { + /* --option */ + _ftprintf(stderr, _T("%s: unrecognized option '--%s'\n"),argv[0], d->__nextchar); + } + else + { + /* +option or -option */ + _ftprintf(stderr, _T("%s: unrecognized option '%c%s'\n"),argv[0], argv[d->optind][0], d->__nextchar); + } + } + d->__nextchar = (TCHAR *)_T(""); + d->optind++; + d->optopt = 0; + return _T('?'); + } + } + + { + TCHAR c = *d->__nextchar++; + TCHAR *temp = (TCHAR*)_tcschr(optstring, c); + + if (*d->__nextchar == _T('\0')) + ++d->optind; + + if (temp == NULL || c == _T(':') || c == _T(';')) + { + if (print_errors) + { + _ftprintf(stderr, _T("%s: invalid option -- '%c'\n"), argv[0], c); + } + d->optopt = c; + return _T('?'); + } + if (temp[0] == _T('W') && temp[1] == _T(';')) + { + TCHAR *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + if (*d->__nextchar != _T('\0')) + { + d->optarg = d->__nextchar; + d->optind++; + } + else if (d->optind == argc) + { + if (print_errors) + { + _ftprintf(stderr, + _T("%s: option requires an argument -- '%c'\n"), + argv[0], c); + } + d->optopt = c; + if (optstring[0] == _T(':')) + c = _T(':'); + else + c = _T('?'); + return c; + } + else + d->optarg = argv[d->optind++]; + + for (d->__nextchar = nameend = d->optarg; *nameend && *nameend != _T('='); nameend++); + + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!_tcsncmp(p->name, d->__nextchar, nameend - d->__nextchar)) + { + if ((unsigned int) (nameend - d->__nextchar) == _tcslen(p->name)) + { + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + pfound = p; + indfound = option_index; + } + else if (long_only || pfound->has_arg != p->has_arg || pfound->flag != p->flag || pfound->val != p->val) + ambig = 1; + } + if (ambig && !exact) + { + if (print_errors) + { + _ftprintf(stderr, _T("%s: option '-W %s' is ambiguous\n"), + argv[0], d->optarg); + } + d->__nextchar += _tcslen(d->__nextchar); + d->optind++; + return _T('?'); + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + if (pfound->has_arg) + d->optarg = nameend + 1; + else + { + if (print_errors) + { + _ftprintf(stderr, _T("\ + %s: option '-W %s' doesn't allow an argument\n"), + argv[0], pfound->name); + } + + d->__nextchar += _tcslen(d->__nextchar); + return _T('?'); + } + } + else if (pfound->has_arg == 1) + { + if (d->optind < argc) + d->optarg = argv[d->optind++]; + else + { + if (print_errors) + { + _ftprintf(stderr, _T("\ + %s: option '-W %s' requires an argument\n"), + argv[0], pfound->name); + } + d->__nextchar += _tcslen(d->__nextchar); + return optstring[0] == _T(':') ? _T(':') : _T('?'); + } + } + else + d->optarg = NULL; + d->__nextchar += _tcslen(d->__nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + d->__nextchar = NULL; + return _T('W'); + } + if (temp[1] == _T(':')) + { + if (temp[2] == _T(':')) + { + if (*d->__nextchar != _T('\0')) + { + d->optarg = d->__nextchar; + d->optind++; + } + else + d->optarg = NULL; + d->__nextchar = NULL; + } + else + { + if (*d->__nextchar != _T('\0')) + { + d->optarg = d->__nextchar; + d->optind++; + } + else if (d->optind == argc) + { + if (print_errors) + { + _ftprintf(stderr, + _T("%s: option requires an argument -- '%c'\n"), + argv[0], c); + } + d->optopt = c; + if (optstring[0] == _T(':')) + c = _T(':'); + else + c = _T('?'); + } + else + d->optarg = argv[d->optind++]; + d->__nextchar = NULL; + } + } + return c; + } +} + +int _getopt_internal (int argc, TCHAR *const *argv, const TCHAR *optstring, const struct option *longopts, int *longind, int long_only, int posixly_correct) +{ + int result; + getopt_data.optind = optind; + getopt_data.opterr = opterr; + result = _getopt_internal_r (argc, argv, optstring, longopts,longind, long_only, &getopt_data,posixly_correct); + optind = getopt_data.optind; + optarg = getopt_data.optarg; + optopt = getopt_data.optopt; + return result; +} + +int getopt (int argc, TCHAR *const *argv, const TCHAR *optstring) +{ + return _getopt_internal (argc, argv, optstring, (const struct option *) 0, (int *) 0, 0, 0); +} + +int getopt_long (int argc, TCHAR *const *argv, const TCHAR *options, const struct option *long_options, int *opt_index) +{ + return _getopt_internal (argc, argv, options, long_options, opt_index, 0, 0); +} + +int _getopt_long_r (int argc, TCHAR *const *argv, const TCHAR *options, const struct option *long_options, int *opt_index, struct _getopt_data *d) +{ + return _getopt_internal_r (argc, argv, options, long_options, opt_index,0, d, 0); +} + +int getopt_long_only (int argc, TCHAR *const *argv, const TCHAR *options, const struct option *long_options, int *opt_index) +{ + return _getopt_internal (argc, argv, options, long_options, opt_index, 1, 0); +} + +int _getopt_long_only_r (int argc, TCHAR *const *argv, const TCHAR *options, const struct option *long_options, int *opt_index, struct _getopt_data *d) +{ + return _getopt_internal_r (argc, argv, options, long_options, opt_index, 1, d, 0); +} + +#endif diff --git a/scetool/getopt.h b/scetool/getopt.h new file mode 100644 index 0000000000..19ca90954c --- /dev/null +++ b/scetool/getopt.h @@ -0,0 +1,106 @@ +#ifdef _WIN32 + +/* Getopt for Microsoft C +This code is a modification of the Free Software Foundation, Inc. +Getopt library for parsing command line argument the purpose was +to provide a Microsoft Visual C friendly derivative. This code +provides functionality for both Unicode and Multibyte builds. + +Date: 02/03/2011 - Ludvik Jerabek - Initial Release +Version: 1.0 +Comment: Supports getopt, getopt_long, and getopt_long_only +and POSIXLY_CORRECT environment flag +License: LGPL + +Revisions: + +02/03/2011 - Ludvik Jerabek - Initial Release +02/20/2011 - Ludvik Jerabek - Fixed compiler warnings at Level 4 +07/05/2011 - Ludvik Jerabek - Added no_argument, required_argument, optional_argument defs +08/03/2011 - Ludvik Jerabek - Fixed non-argument runtime bug which caused runtime exception +08/09/2011 - Ludvik Jerabek - Added code to export functions for DLL and LIB + +**DISCLAIMER** +THIS MATERIAL IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, +EITHER EXPRESS OR IMPLIED, INCLUDING, BUT Not LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE +EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT +APPLY TO YOU. IN NO EVENT WILL I BE LIABLE TO ANY PARTY FOR ANY +DIRECT, INDIRECT, SPECIAL OR OTHER CONSEQUENTIAL DAMAGES FOR ANY +USE OF THIS MATERIAL INCLUDING, WITHOUT LIMITATION, ANY LOST +PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR OTHER DATA ON +YOUR INFORMATION HANDLING SYSTEM OR OTHERWISE, EVEN If WE ARE +EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +*/ +#ifndef __GETOPT_H_ +#define __GETOPT_H_ + +#define STATIC_GETOPT + +#ifdef _GETOPT_API + #undef _GETOPT_API +#endif + +#if defined(EXPORTS_GETOPT) && defined(STATIC_GETOPT) + #error "The preprocessor definitions of EXPORTS_GETOPT and STATIC_GETOPT can only be used individually" +#elif defined(STATIC_GETOPT) +#pragma message("Warning static builds of getopt violate the Lesser GNU Public License") + #define _GETOPT_API +#elif defined(EXPORTS_GETOPT) + #pragma message("Exporting getopt library") + #define _GETOPT_API __declspec(dllexport) +#else + #pragma message("Importing getopt library") + #define _GETOPT_API __declspec(dllimport) +#endif + + +#include + +// Standard GNU options +#define null_argument 0 /*Argument Null*/ +#define no_argument 0 /*Argument Switch Only*/ +#define required_argument 1 /*Argument Required*/ +#define optional_argument 2 /*Argument Optional*/ + +// Change behavior for C\C++ +#ifdef __cplusplus +#define _BEGIN_EXTERN_C extern "C" { +#define _END_EXTERN_C } +#define _GETOPT_THROW throw() +#else +#define _BEGIN_EXTERN_C +#define _END_EXTERN_C +#define _GETOPT_THROW +#endif + +_BEGIN_EXTERN_C + +extern _GETOPT_API TCHAR *optarg; +extern _GETOPT_API int optind; +extern _GETOPT_API int opterr; +extern _GETOPT_API int optopt; + +struct option +{ + const TCHAR* name; + int has_arg; + int *flag; + TCHAR val; +}; + +extern _GETOPT_API int getopt(int argc, TCHAR *const *argv, const TCHAR *optstring) _GETOPT_THROW; +extern _GETOPT_API int getopt_long(int ___argc, TCHAR *const *___argv, const TCHAR *__shortopts, const struct option *__longopts, int *__longind) _GETOPT_THROW; +extern _GETOPT_API int getopt_long_only(int ___argc, TCHAR *const *___argv, const TCHAR *__shortopts, const struct option *__longopts, int *__longind) _GETOPT_THROW; +_END_EXTERN_C + +// Undefine so the macros are not included +#undef _BEGIN_EXTERN_C +#undef _END_EXTERN_C +#undef _GETOPT_THROW +#undef _GETOPT_API + +#endif // __GETOPT_H_ + +#endif diff --git a/scetool/keys.h b/scetool/keys.h new file mode 100644 index 0000000000..4fc07f46a1 --- /dev/null +++ b/scetool/keys.h @@ -0,0 +1,131 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _KEYS_H_ +#define _KEYS_H_ + +#include "types.h" +#include "sce.h" + +#define KEYBITS(klen) BYTES2BITS(klen) + +#define KEYTYPE_SELF 1 +#define KEYTYPE_RVK 2 +#define KEYTYPE_PKG 3 +#define KEYTYPE_SPP 4 +#define KEYTYPE_OTHER 5 + +/*! Flag to use VSH curve. */ +#define USE_VSH_CURVE 0x40 + +/*! Length of whole curves file. */ +#define CURVES_LENGTH 0x1E40 +#define CTYPE_MIN 0 +#define CTYPE_MAX 63 + +/*! Length of the whole VSH curves file. */ +#define VSH_CURVES_LENGTH 0x168 +#define VSH_CTYPE_MIN 0 +#define VSH_CTYPE_MAX 2 + +/*! Length of the idps, act.dat, .rif and .rap files. */ +#define IDPS_LENGTH 0x10 +#define ACT_DAT_LENGTH 0x1038 +#define RIF_LENGTH 0x98 +#define RAP_LENGTH 0x10 + +/*! IDPS, RIF, act.dat key lengths. */ +#define IDPS_KEYBITS 128 +#define ACT_DAT_KEYBITS 128 +#define RIF_KEYBITS 128 +#define RAP_KEYBITS 128 + +/*! Keyset. */ +typedef struct _keyset +{ + /*! Name. */ + scetool::s8 *name; + /*! Type. */ + scetool::u32 type; + /*! Key revision. */ + scetool::u16 key_revision; + /*! Version. */ + scetool::u64 version; + /*! SELF type. */ + scetool::u32 self_type; + /*! Key length. */ + scetool::u32 erklen; + /*! Key. */ + scetool::u8 *erk; + /*! IV length. */ + scetool::u32 rivlen; + /*! IV. */ + scetool::u8 *riv; + /*! Pub. */ + scetool::u8 *pub; + /*! Priv. */ + scetool::u8 *priv; + /*! Curve type. */ + scetool::u8 ctype; +} keyset_t; + +/*! Curve entry. */ +typedef struct _curve +{ + scetool::u8 p[20]; + scetool::u8 a[20]; + scetool::u8 b[20]; + scetool::u8 N[21]; + scetool::u8 Gx[20]; + scetool::u8 Gy[20]; +} curve_t; + +/*! VSH Curve entry. */ +typedef struct _vsh_curve +{ + scetool::u8 a[20]; + scetool::u8 b[20]; + scetool::u8 N[20]; + scetool::u8 p[20]; + scetool::u8 Gx[20]; + scetool::u8 Gy[20]; +} vsh_curve_t; + +/*! act.dat. */ +typedef struct _act_dat +{ + scetool::u8 account_info[16]; + scetool::u8 primary_key_table[2048]; + scetool::u8 secondary_key_table[2048]; + scetool::u8 signature[40]; +} act_dat_t; + +/*! RIF. */ +typedef struct _rif +{ + scetool::u8 account_info[16]; + scetool::u8 content_id[48]; + scetool::u8 act_key_index[16]; + scetool::u8 klicensee[16]; + scetool::u64 timestamp; + scetool::u64 zero; + scetool::u8 signature[40]; +} rif_t; + +BOOL keys_load(const scetool::s8 *kfile); +keyset_t *keyset_find(sce_buffer_ctxt_t *ctxt); +keyset_t *keyset_find_by_name(const scetool::s8 *name); + +BOOL curves_load(const scetool::s8 *cfile); +curve_t *curve_find(scetool::u8 ctype); + +BOOL vsh_curves_load(const scetool::s8 *cfile); +curve_t *vsh_curve_find(scetool::u8 ctype); + +BOOL klicensee_by_content_id(const scetool::s8 *content_id, scetool::u8 *klicensee); + +keyset_t *keyset_from_buffer(scetool::u8 *keyset); + +#endif diff --git a/scetool/list.h b/scetool/list.h new file mode 100644 index 0000000000..09fddd3050 --- /dev/null +++ b/scetool/list.h @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _LIST_H_ +#define _LIST_H_ + +#include "types.h" + +#define LIST_FOREACH(iter, list) for(lnode_t *iter = list->head; iter != NULL; iter = iter->next) + +typedef struct _lnode +{ + void *value; + struct _lnode *next; +} lnode_t; + +typedef struct _list +{ + lnode_t *head; + scetool::u32 count; +} list_t; + +list_t *list_create(); +void list_destroy(list_t *l); +BOOL list_isempty(list_t *l); +scetool::u32 list_count(list_t *l); +BOOL list_push(list_t *l, void *value); +void *list_pop(list_t *l); +BOOL list_add_back(list_t *l, void *value); +void *list_get(list_t *l, scetool::u32 idx); +lnode_t *list_get_node(list_t *l, scetool::u32 idx); +BOOL list_remove_node(list_t *l, lnode_t *node); +BOOL list_remove_value(list_t *l, void *value); + +#endif diff --git a/scetool/mt19937.h b/scetool/mt19937.h new file mode 100644 index 0000000000..bfe5e6b82a --- /dev/null +++ b/scetool/mt19937.h @@ -0,0 +1,41 @@ +//Mersenne-Twister 19937 pseudorandom number generator. +//Reference implementation at: +//http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c + +#ifndef _MT19937_H_ +#define _MT19937_H_ + +/*! State size. */ +#define MT_N 624 +#define MT_M 397 +#define MT_MATRIX_A 0x9908b0df +#define MT_UPPER_MASK 0x80000000 +#define MT_LOWER_MASK 0x7fffffff + +/*! Mersenne-Twister 19937 context. */ +typedef struct _mt19937_ctxt +{ + /*! State. */ + unsigned int state[MT_N]; + /*! Index. */ + unsigned int idx; +} mt19937_ctxt_t; + +/*! +* \brief Initialize Mersenne-Twister 19937 context. +* +* \param ctxt Mersenne-Twister 19937 context. +* \param seed Random seed. +*/ +void mt19937_init(mt19937_ctxt_t *ctxt, unsigned int seed); + +/*! +* \brief Update Mersenne-Twister 19937 state. +* +* \param ctxt Mersenne-Twister 19937 context. +* +* \return Generated pseudorandom number. +*/ +unsigned int mt19937_update(mt19937_ctxt_t *ctxt); + +#endif diff --git a/scetool/np.h b/scetool/np.h new file mode 100644 index 0000000000..248b20cf9e --- /dev/null +++ b/scetool/np.h @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _NP_H_ +#define _NP_H_ + +#include "types.h" +#include "sce.h" + +/*! NPDRM config. */ +typedef struct _npdrm_config +{ + /*! License type. */ + scetool::u32 license_type; + /*! Application type. */ + scetool::u32 app_type; + /*! klicensee. */ + scetool::u8 *klicensee; + /*! Content ID. */ + scetool::u8 content_id[0x30]; + /*! Real file name. */ + scetool::s8 *real_fname; +} npdrm_config_t; + +/*! Set klicensee. */ +void np_set_klicensee(scetool::u8 *klicensee); + +/*! Remove NPDRM layer. */ +BOOL np_decrypt_npdrm(sce_buffer_ctxt_t *ctxt); + +/*! Add NPDRM layer. */ +BOOL np_encrypt_npdrm(sce_buffer_ctxt_t *ctxt); + +/*! Create NPDRM control info. */ +BOOL np_create_ci(npdrm_config_t *npconf, ci_data_npdrm_t *cinp); + +/*! Add NP signature to file. */ +BOOL np_sign_file(scetool::s8 *fname); + +#endif diff --git a/scetool/rvk.h b/scetool/rvk.h new file mode 100644 index 0000000000..5ecf2c9886 --- /dev/null +++ b/scetool/rvk.h @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _RVK_H_ +#define _RVK_H_ + +#include "types.h" +#include "sce.h" + +/* +header: + 00000200 00 00 00 04 00 00 00 01 00 03 00 41 00 00 00 00 + 00000210 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 +body: + 00000220 00 00 00 03 00 00 00 01 00 03 00 41 00 00 00 00 00 00 00 00 00 00 00 02 FF FF FF FF FF FF FF FF + 00000240 00 00 00 04 00 00 00 01 00 03 00 41 00 00 00 00 10 70 00 05 FF 00 00 01 FF FF FF FF FF FF FF FF + 00000260 00 00 00 04 00 00 00 01 00 03 00 41 00 00 00 00 10 70 00 05 FE 00 00 01 FF FF FF FF FF FF FF FF + 00000280 00 00 00 04 00 00 00 01 00 03 00 41 00 00 00 00 10 70 00 05 FD 00 00 01 FF FF FF FF FF FF FF FF + 000002A0 00 00 00 04 00 00 00 01 00 03 00 41 00 00 00 00 10 70 00 05 FC 00 00 01 FF FF FF FF FF FF FF FF + 000002C0 00 00 00 04 00 00 00 03 00 01 00 00 00 00 00 00 10 70 00 04 00 00 00 01 FF FF FF FF FF FF FF FF +*/ + +/* +0 self != rvk +1 self == rvk +2 !(rvk <= self) -> self < rvk +3 self <= rvk +4 !(self <= rvk) -> self > rvk +5 rvk <= self -> self >= rvk +*/ +#define CHECK_SELF_NEQU_RVK 0 +#define CHECK_SELF_EQU_RVK 1 +#define CHECK_SELF_LT_RVK 2 +#define CHECK_SELF_LTEQU_RVK 3 +#define CHECK_SELF_GT_RVK 4 +#define CHECK_SELF_GTEQU_RVK 5 + +/*! RVK header. */ +typedef struct _rvk_header +{ + scetool::u32 type_0; + scetool::u32 type_1; + scetool::u64 opaque; //Program revoke: version, Package revoke: unknown. + scetool::u32 entcnt; + scetool::u8 padding[12]; +} rvk_header_t; + +static inline void _es_rvk_header(rvk_header_t *h) +{ + h->type_0 = _Es32(h->type_0); + h->type_1 = _Es32(h->type_1); + h->opaque = _Es64(h->opaque); + h->entcnt = _Es32(h->entcnt); +} + +/*! Program revoke list entry. */ +typedef struct _prg_rvk_entry +{ + scetool::u32 self_type; //3, 4 + scetool::u32 check_type; + scetool::u64 version; + union + { + scetool::u64 auth_id; + scetool::u64 unk_3; + }; + scetool::u64 mask; +} prg_rvk_entry_t; + +static inline void _es_prg_rvk_entry(prg_rvk_entry_t *e) +{ + e->self_type = _Es32(e->self_type); + e->check_type = _Es32(e->check_type); + e->version = _Es64(e->version); + e->auth_id = _Es64(e->auth_id); + e->mask = _Es64(e->mask); +} + +/*! Print RVK infos. */ +void rvk_print(FILE *fp, sce_buffer_ctxt_t *ctxt); + +#endif diff --git a/scetool/sce.h b/scetool/sce.h new file mode 100644 index 0000000000..8450fdf757 --- /dev/null +++ b/scetool/sce.h @@ -0,0 +1,616 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _SCE_H_ +#define _SCE_H_ + +#include +#include + +#include "types.h" +#include "list.h" + +/*! SCE file align. */ +#define SCE_ALIGN 0x10 +/*! Header align. */ +#define HEADER_ALIGN 0x80 + +/*! SCE header magic value ("SCE\0"). */ +#define SCE_HEADER_MAGIC 0x53434500 + +/*! SCE header versions. */ +/*! Header version 2. */ +#define SCE_HEADER_VERSION_2 2 + +/*! Key revisions. */ +#define KEY_REVISION_0 0x00 +#define KEY_REVISION_092_330 0x01 +#define KEY_REVISION_1 0x02 +//#define KEY_REVISION_ 0x03 +#define KEY_REVISION_340_342 0x04 +//#define KEY_REVISION_ 0x05 +//#define KEY_REVISION_ 0x06 +#define KEY_REVISION_350 0x07 +//#define KEY_REVISION_ 0x08 +//#define KEY_REVISION_ 0x09 +#define KEY_REVISION_355 0x0a +//#define KEY_REVISION_ 0x0b +//#define KEY_REVISION_ 0x0c +#define KEY_REVISION_356 0x0d +//#define KEY_REVISION_ 0x0e +//#define KEY_REVISION_ 0x0f +#define KEY_REVISION_360_361 0x10 +//#define KEY_REVISION_ 0x11 +//#define KEY_REVISION_ 0x12 +#define KEY_REVISION_365 0x13 +//#define KEY_REVISION_ 0x14 +//#define KEY_REVISION_ 0x15 +#define KEY_REVISION_370_373 0x16 +//#define KEY_REVISION_ 0x17 +//#define KEY_REVISION_ 0x18 +#define KEY_REVISION_DEBUG 0x8000 + +/*! SCE header types. */ +/*! SELF header. */ +#define SCE_HEADER_TYPE_SELF 1 +/*! RVK header. */ +#define SCE_HEADER_TYPE_RVK 2 +/*! PKG header. */ +#define SCE_HEADER_TYPE_PKG 3 +/*! SPP header. */ +#define SCE_HEADER_TYPE_SPP 4 + +/*! Sub header types. */ +/*! SCE version header. */ +#define SUB_HEADER_TYPE_SCEVERSION 1 +/*! SELF header. */ +#define SUB_HEADER_TYPE_SELF 3 + +/*! Control info types. */ +/*! Control flags. */ +#define CONTROL_INFO_TYPE_FLAGS 1 +/*! Digest. */ +#define CONTROL_INFO_TYPE_DIGEST 2 +/*! NPDRM block. */ +#define CONTROL_INFO_TYPE_NPDRM 3 + +/*! Optional header types. */ +/*! Capability flags header. */ +#define OPT_HEADER_TYPE_CAP_FLAGS 1 +/*! Individuals seed header. */ +#define OPT_HEADER_TYPE_INDIV_SEED 2 + +/*! Metadata key/iv lengths. */ +#define METADATA_INFO_KEYBITS 128 +#define METADATA_INFO_KEY_LEN 16 +#define METADATA_INFO_KEYPAD_LEN 16 +#define METADATA_INFO_IV_LEN 16 +#define METADATA_INFO_IVPAD_LEN 16 + +/*! Metadata section types. */ +/*! Segment header. */ +#define METADATA_SECTION_TYPE_SHDR 1 +/*! Program header. */ +#define METADATA_SECTION_TYPE_PHDR 2 +/*! Unknown header type 3. */ +#define METADATA_SECTION_TYPE_UNK_3 3 + +/*! Section is hashed. */ +#define METADATA_SECTION_HASHED 2 +/*! Section is not encrypted. */ +#define METADATA_SECTION_NOT_ENCRYPTED 1 +/*! Section is encrypted. */ +#define METADATA_SECTION_ENCRYPTED 3 +/*! Section is not compressed. */ +#define METADATA_SECTION_NOT_COMPRESSED 1 +/*! Section is compressed. */ +#define METADATA_SECTION_COMPRESSED 2 + +/*! Signature sizes. */ +/*! Signature S part size. */ +#define SIGNATURE_S_SIZE 21 +/*! Signature R part size. */ +#define SIGNATURE_R_SIZE 21 + +/*! Compressed. */ +#define SECTION_INFO_COMPRESSED 2 +/*! Not compressed. */ +#define SECTION_INFO_NOT_COMPRESSED 1 + +/*! SCE version not present. */ +#define SCE_VERSION_NOT_PRESENT 0 +/*! SCE version present. */ +#define SCE_VERSION_PRESENT 1 + +/*! SELF types. */ +/*! lv0. */ +#define SELF_TYPE_LV0 1 +/*! lv1. */ +#define SELF_TYPE_LV1 2 +/*! lv2. */ +#define SELF_TYPE_LV2 3 +/*! Application. */ +#define SELF_TYPE_APP 4 +/*! Isolated SPU module. */ +#define SELF_TYPE_ISO 5 +/*! Secure loader. */ +#define SELF_TYPE_LDR 6 +/*! Unknown type 7. */ +#define SELF_TYPE_UNK_7 7 +/*! NPDRM application. */ +#define SELF_TYPE_NPDRM 8 + +/*! NPDRM control info magic value ("NPD\0"). */ +#define NP_CI_MAGIC 0x4E504400 + +/*! NPDRM license types. */ +#define NP_LICENSE_NETWORK 1 +#define NP_LICENSE_LOCAL 2 +#define NP_LICENSE_FREE 3 + +/*! NPDRM application types. */ +#define NP_TYPE_UPDATE 0x20 +#define NP_TYPE_SPRX 0 +#define NP_TYPE_EXEC 1 +#define NP_TYPE_USPRX (NP_TYPE_UPDATE | NP_TYPE_SPRX) +#define NP_TYPE_UEXEC (NP_TYPE_UPDATE | NP_TYPE_EXEC) + +/*! SCE header. */ +typedef struct _sce_header +{ + /*! Magic value. */ + scetool::u32 magic; + /*! Header version .*/ + scetool::u32 version; + /*! Key revision. */ + scetool::u16 key_revision; + /*! Header type. */ + scetool::u16 header_type; + /*! Metadata offset. */ + scetool::u32 metadata_offset; + /*! Header length. */ + scetool::u64 header_len; + /*! Length of encapsulated data. */ + scetool::u64 data_len; +} sce_header_t; + +/*! SELF header. */ +typedef struct _self_header +{ + /*! Header type. */ + scetool::u64 header_type; + /*! Application info offset. */ + scetool::u64 app_info_offset; + /*! ELF offset. */ + scetool::u64 elf_offset; + /*! Program headers offset. */ + scetool::u64 phdr_offset; + /*! Section headers offset. */ + scetool::u64 shdr_offset; + /*! Section info offset. */ + scetool::u64 section_info_offset; + /*! SCE version offset. */ + scetool::u64 sce_version_offset; + /*! Control info offset. */ + scetool::u64 control_info_offset; + /*! Control info size. */ + scetool::u64 control_info_size; + /*! Padding. */ + scetool::u64 padding; +} self_header_t; + +/*! Metadata info. */ +typedef struct _metadata_info +{ + /*! Key. */ + scetool::u8 key[METADATA_INFO_KEY_LEN]; + /*! Key padding. */ + scetool::u8 key_pad[METADATA_INFO_KEYPAD_LEN]; + /*! IV. */ + scetool::u8 iv[METADATA_INFO_IV_LEN]; + /*! IV padding. */ + scetool::u8 iv_pad[METADATA_INFO_IVPAD_LEN]; +} metadata_info_t; + +typedef struct _metadata_header +{ + /*! Signature input length. */ + scetool::u64 sig_input_length; + scetool::u32 unknown_0; + /*! Section count. */ + scetool::u32 section_count; + /*! Key count. */ + scetool::u32 key_count; + /*! Optional header size. */ + scetool::u32 opt_header_size; + scetool::u32 unknown_1; + scetool::u32 unknown_2; +} metadata_header_t; + +/*! Metadata section header. */ +typedef struct _metadata_section_header +{ + /*! Data offset. */ + scetool::u64 data_offset; + /*! Data size. */ + scetool::u64 data_size; + /*! Type. */ + scetool::u32 type; + /*! Index. */ + scetool::u32 index; + /*! Hashed. */ + scetool::u32 hashed; + /*! SHA1 index. */ + scetool::u32 sha1_index; + /*! Encrypted. */ + scetool::u32 encrypted; + /*! Key index. */ + scetool::u32 key_index; + /*! IV index. */ + scetool::u32 iv_index; + /*! Compressed. */ + scetool::u32 compressed; +} metadata_section_header_t; + +/*! SCE file signature. */ +typedef struct _signature +{ + scetool::u8 r[SIGNATURE_R_SIZE]; + scetool::u8 s[SIGNATURE_S_SIZE]; + scetool::u8 padding[6]; +} signature_t; + +/*! Section info. */ +typedef struct _section_info +{ + scetool::u64 offset; + scetool::u64 size; + scetool::u32 compressed; + scetool::u32 unknown_0; + scetool::u32 unknown_1; + scetool::u32 encrypted; +} section_info_t; + +/*! SCE version. */ +typedef struct _sce_version +{ + /*! Header type. */ + scetool::u32 header_type; + /*! SCE version section present? */ + scetool::u32 present; + /*! Size. */ + scetool::u32 size; + scetool::u32 unknown_3; +} sce_version_t; + +/*! SCE version data 0x30. */ +typedef struct _sce_version_data_30 +{ + scetool::u16 unknown_1; //Dunno. + scetool::u16 unknown_2; //0x0001 + scetool::u32 unknown_3; //Padding? + scetool::u32 unknown_4; //Number of sections? + scetool::u32 unknown_5; //Padding? + /*! Data offset. */ + scetool::u64 offset; + /*! Data size. */ + scetool::u64 size; +} sce_version_data_30_t; + +//(auth_id & AUTH_ONE_MASK) has to be 0x1000000000000000 +#define AUTH_ONE_MASK 0xF000000000000000 +#define AUTH_TERRITORY_MASK 0x0FF0000000000000 +#define VENDOR_TERRITORY_MASK 0xFF000000 +#define VENDOR_ID_MASK 0x00FFFFFF + +/*! Application info. */ +typedef struct _app_info +{ + /*! Auth ID. */ + scetool::u64 auth_id; + /*! Vendor ID. */ + scetool::u32 vendor_id; + /*! SELF type. */ + scetool::u32 self_type; + /*! Version. */ + scetool::u64 version; + /*! Padding. */ + scetool::u64 padding; +} app_info_t; + +/*! Control info. */ +typedef struct _control_info +{ + /*! Control info type. */ + scetool::u32 type; + /*! Size of following data. */ + scetool::u32 size; + /*! Next flag (1 if another info follows). */ + scetool::u64 next; +} control_info_t; + +#define CI_FLAG_00_80 0x80 +#define CI_FLAG_00_40 0x40 //root access +#define CI_FLAG_00_20 0x20 //kernel access + +#define CI_FLAG_17_01 0x01 +#define CI_FLAG_17_02 0x02 +#define CI_FLAG_17_04 0x04 +#define CI_FLAG_17_08 0x08 +#define CI_FLAG_17_10 0x10 + +//1B: +//bdj 0x01, 0x09 +//psp_emu 0x08 +//psp_transl 0x0C +#define CI_FLAG_1B_01 0x01 //may use shared mem? +#define CI_FLAG_1B_02 0x02 +#define CI_FLAG_1B_04 0x04 +#define CI_FLAG_1B_08 0x08 //ss + +#define CI_FLAG_1F_SHAREABLE 0x01 +#define CI_FLAG_1F_02 0x02 //internal? +#define CI_FLAG_1F_FACTORY 0x04 +#define CI_FLAG_1F_08 0x08 //??? + +/*! Control info data flags. */ +typedef struct _ci_data_flags +{ + scetool::u8 data[0x20]; +} ci_data_flags_t; + +/*! Control info data digest 0x30. */ +typedef struct _ci_data_digest_30 +{ + scetool::u8 digest[20]; + scetool::u64 unknown_0; +} ci_data_digest_30_t; + +/*! Control info data digest 0x40. */ +typedef struct _ci_data_digest_40 +{ + scetool::u8 digest1[20]; + scetool::u8 digest2[20]; + scetool::u64 fw_version; +} ci_data_digest_40_t; + +/*! Control info data NPDRM. */ +typedef struct _ci_data_npdrm +{ + /*! Magic. */ + scetool::u32 magic; + scetool::u32 unknown_0; + /*! License type. */ + scetool::u32 license_type; + /*! Application type. */ + scetool::u32 app_type; + /*! Content ID. */ + scetool::u8 content_id[0x30]; + /*! Random padding. */ + scetool::u8 rndpad[0x10]; + /*! ContentID_FileName hash. */ + scetool::u8 hash_cid_fname[0x10]; + /*! Control info hash. */ + scetool::u8 hash_ci[0x10]; + scetool::u64 unknown_1; + scetool::u64 unknown_2; +} ci_data_npdrm_t; + +/*! Optional header. */ +typedef struct _opt_header +{ + /*! Type. */ + scetool::u32 type; + /*! Size. */ + scetool::u32 size; + /*! Next flag (1 if another header follows). */ + scetool::u64 next; +} opt_header_t; + +/*! Capability flags. */ +#define CAP_FLAG_1 0x01 //only seen in PPU selfs +#define CAP_FLAG_2 0x02 //only seen in PPU selfs +#define CAP_FLAG_4 0x04 //only seen in bdj PPU self +#define CAP_FLAG_REFTOOL 0x08 +#define CAP_FLAG_DEBUG 0x10 +#define CAP_FLAG_RETAIL 0x20 +#define CAP_FLAG_SYSDBG 0x40 + +#define UNK7_2000 0x2000 //hddbind? +#define UNK7_20000 0x20000 //flashbind? +#define UNK7_40000 0x40000 //discbind? +#define UNK7_80000 0x80000 + +#define UNK7_PS3SWU 0x116000 //dunno... + +/*! SCE file capability flags. */ +typedef struct _oh_data_cap_flags +{ + scetool::u64 unk3; //0 + scetool::u64 unk4; //0 + /*! Flags. */ + scetool::u64 flags; + scetool::u32 unk6; + scetool::u32 unk7; +} oh_data_cap_flags_t; + +/*! Section context. */ +typedef struct _sce_section_ctxt +{ + /*! Data buffer. */ + void *buffer; + /*! Size. */ + scetool::u32 size; + /*! Offset. */ + scetool::u32 offset; + /*! May be compressed. */ + BOOL may_compr; +} sce_section_ctxt_t; + +typedef struct _makeself_ctxt +{ + /*! ELF file buffer (for ELF -> SELF). */ + scetool::u8 *elf; + /*! ELF file length. */ + scetool::u32 elf_len; + /*! ELF header. */ + void *ehdr; + /*! ELF header size. */ + scetool::u32 ehsize; + /*! Program headers. */ + void *phdrs; + /*! Program headers size. */ + scetool::u32 phsize; + /*! Section headers. */ + void *shdrs; + /*! Section headers size. */ + scetool::u32 shsize; + /*! Section info count. */ + scetool::u32 si_cnt; + /*! Number of section infos that are present as data sections. */ + scetool::u32 si_sec_cnt; +} makeself_ctxt_t; + +/*! SCE file buffer context. */ +typedef struct _sce_buffer_ctxt +{ + /*! SCE file buffer. */ + scetool::u8 *scebuffer; + + /*! SCE header. */ + sce_header_t *sceh; + /*! File type dependent header. */ + union + { + struct + { + /*! SELF header. */ + self_header_t *selfh; + /*! Application info. */ + app_info_t *ai; + /*! Section info. */ + section_info_t *si; + /*! SCE version. */ + sce_version_t *sv; + /*! Control infos. */ + list_t *cis; + /*! Optional headers. */ + list_t *ohs; + } self; + }; + /*! Metadata info. */ + metadata_info_t *metai; + /*! Metadata header. */ + metadata_header_t *metah; + /*! Metadata section headers. */ + metadata_section_header_t *metash; + /*! SCE file keys. */ + scetool::u8 *keys; + /*! Keys length. */ + scetool::u32 keys_len; + /*! Signature. */ + signature_t *sig; + + /*! Metadata decrypted? */ + BOOL mdec; + + /*! Data layout. */ + /*! SCE header offset. */ + scetool::u32 off_sceh; + union + { + struct + { + /*! SELF header offset. */ + scetool::u32 off_selfh; + /*! Application info offset. */ + scetool::u32 off_ai; + /*! ELF header offset. */ + scetool::u32 off_ehdr; + /*! Program header offset. */ + scetool::u32 off_phdr; + /*! Section info offset. */ + scetool::u32 off_si; + /*! SCE version offset. */ + scetool::u32 off_sv; + /*! Control infos offset. */ + scetool::u32 off_cis; + /*! Optional headers offset. */ + scetool::u32 off_ohs; + } off_self; + }; + /*! Metadata info offset. */ + scetool::u32 off_metai; + /*! Metadata header offset. */ + scetool::u32 off_metah; + /*! Metadata section headers offset. */ + scetool::u32 off_metash; + /*! Keys offset. */ + scetool::u32 off_keys; + /*! Signature offset. */ + scetool::u32 off_sig; + /*! Header padding end offset. */ + scetool::u32 off_hdrpad; + + /*! File creation type dependent data. */ + union + { + /*! ELF -> SELF. */ + makeself_ctxt_t *makeself; + }; + + /*! Data sections. */ + list_t *secs; +} sce_buffer_ctxt_t; + +/*! Create SCE file context from SCE file buffer. */ +sce_buffer_ctxt_t *sce_create_ctxt_from_buffer(scetool::u8 *scebuffer); + +/*! Create SCE file context for SELF creation. */ +sce_buffer_ctxt_t *sce_create_ctxt_build_self(scetool::u8 *elf, scetool::u32 elf_len); + +/*! Add data section to SCE context. */ +void sce_add_data_section(sce_buffer_ctxt_t *ctxt, void *buffer, scetool::u32 size, BOOL may_compr); + +/*! Set metadata section header. */ +void sce_set_metash(sce_buffer_ctxt_t *ctxt, scetool::u32 type, BOOL encrypted, scetool::u32 idx); + +/*! Compress data. */ +void sce_compress_data(sce_buffer_ctxt_t *ctxt); + +/*! Layout offsets for SCE file creation. */ +void sce_layout_ctxt(sce_buffer_ctxt_t *ctxt); + +/*! Encrypt context. */ +BOOL sce_encrypt_ctxt(sce_buffer_ctxt_t *ctxt, scetool::u8 *keyset); + +/*! Write context to file. */ +BOOL sce_write_ctxt(sce_buffer_ctxt_t *ctxt, scetool::s8 *fname); + +/*! Decrypt header (use passed metadata_into if not NULL). */ +BOOL sce_decrypt_header(sce_buffer_ctxt_t *ctxt, scetool::u8 *metadata_info, scetool::u8 *keyset); + +/*! Decrypt data. */ +BOOL sce_decrypt_data(sce_buffer_ctxt_t *ctxt); + +/*! Print SCE file info. */ +void sce_print_info(FILE *fp, sce_buffer_ctxt_t *ctxt); + +/*! Get version string from version. */ +scetool::s8 *sce_version_to_str(scetool::u64 version); + +/*! Get version from version string. */ +scetool::u64 sce_str_to_version(scetool::s8 *version); + +/*! Convert hex version to dec version. */ +scetool::u64 sce_hexver_to_decver(scetool::u64 version); + +/*! Get control info. */ +control_info_t *sce_get_ctrl_info(sce_buffer_ctxt_t *ctxt, scetool::u32 type); + +/*! Get optional header. */ +opt_header_t *sce_get_opt_header(sce_buffer_ctxt_t *ctxt, scetool::u32 type); + +#endif diff --git a/scetool/sce_inlines.h b/scetool/sce_inlines.h new file mode 100644 index 0000000000..c45735f860 --- /dev/null +++ b/scetool/sce_inlines.h @@ -0,0 +1,201 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _SCE_INLINES_H_ +#define _SCE_INLINES_H_ + +#include + +#include "types.h" +#include "sce.h" + +static inline void _es_sce_header(sce_header_t *h) +{ + h->magic = _Es32(h->magic); + h->version = _Es32(h->version); + h->key_revision = _Es16(h->key_revision); + h->header_type = _Es16(h->header_type); + h->metadata_offset = _Es32(h->metadata_offset); + h->header_len = _Es64(h->header_len); + h->data_len = _Es64(h->data_len); +} + +static inline void _copy_es_sce_header(sce_header_t *dst, sce_header_t *src) +{ + memcpy(dst, src, sizeof(sce_header_t)); + _es_sce_header(dst); +} + +static inline void _es_metadata_header(metadata_header_t *h) +{ + h->sig_input_length = _Es64(h->sig_input_length); + h->unknown_0 = _Es32(h->unknown_0); + h->section_count = _Es32(h->section_count); + h->key_count = _Es32(h->key_count); + h->opt_header_size = _Es32(h->opt_header_size); + h->unknown_1 = _Es32(h->unknown_1); + h->unknown_2 = _Es32(h->unknown_2); +} + +static inline void _copy_es_metadata_header(metadata_header_t *dst, metadata_header_t *src) +{ + memcpy(dst, src, sizeof(metadata_header_t)); + _es_metadata_header(dst); +} + +static inline void _es_metadata_section_header(metadata_section_header_t *h) +{ + h->data_offset = _Es64(h->data_offset); + h->data_size = _Es64(h->data_size); + h->type = _Es32(h->type); + h->index = _Es32(h->index); + h->hashed = _Es32(h->hashed); + h->sha1_index = _Es32(h->sha1_index); + h->encrypted = _Es32(h->encrypted); + h->key_index = _Es32(h->key_index); + h->iv_index = _Es32(h->iv_index); + h->compressed = _Es32(h->compressed); +} + +static inline void _copy_es_metadata_section_header(metadata_section_header_t *dst, metadata_section_header_t *src) +{ + memcpy(dst, src, sizeof(metadata_section_header_t)); + _es_metadata_section_header(dst); +} + +static inline void _es_self_header(self_header_t *h) +{ + h->header_type = _Es64(h->header_type); + h->app_info_offset = _Es64(h->app_info_offset); + h->elf_offset = _Es64(h->elf_offset); + h->phdr_offset = _Es64(h->phdr_offset); + h->shdr_offset = _Es64(h->shdr_offset); + h->section_info_offset = _Es64(h->section_info_offset); + h->sce_version_offset = _Es64(h->sce_version_offset); + h->control_info_offset = _Es64(h->control_info_offset); + h->control_info_size = _Es64(h->control_info_size); + h->padding = _Es64(h->padding); +} + +static inline void _copy_es_self_header(self_header_t *dst, self_header_t *src) +{ + memcpy(dst, src, sizeof(self_header_t)); + _es_self_header(dst); +} + +static inline void _es_section_info(section_info_t *si) +{ + si->offset = _Es64(si->offset); + si->size = _Es64(si->size); + si->compressed = _Es32(si->compressed); + si->unknown_0 = _Es32(si->unknown_0); + si->unknown_1 = _Es32(si->unknown_1); + si->encrypted = _Es32(si->encrypted); +} + +static inline void _copy_es_section_info(section_info_t *dst, section_info_t *src) +{ + memcpy(dst, src, sizeof(section_info_t)); + _es_section_info(dst); +} + +static inline void _es_sce_version(sce_version_t *sv) +{ + sv->header_type = _Es32(sv->header_type); + sv->present = _Es32(sv->present); + sv->size = _Es32(sv->size); + sv->unknown_3 = _Es32(sv->unknown_3); +} + +static inline void _copy_es_sce_version(sce_version_t *dst, sce_version_t *src) +{ + memcpy(dst, src, sizeof(sce_version_t)); + _es_sce_version(dst); +} + +static inline void _es_app_info(app_info_t *ai) +{ + ai->auth_id = _Es64(ai->auth_id); + ai->vendor_id = _Es32(ai->vendor_id); + ai->self_type = _Es32(ai->self_type); + ai->version = _Es64(ai->version); + ai->padding = _Es64(ai->padding); +} + +static inline void _copy_es_app_info(app_info_t *dst, app_info_t *src) +{ + memcpy(dst, src, sizeof(app_info_t)); + _es_app_info(dst); +} + +static inline void _es_control_info(control_info_t *ci) +{ + ci->type = _Es32(ci->type); + ci->size = _Es32(ci->size); + ci->next = _Es64(ci->next); +} + +static inline void _copy_es_control_info(control_info_t *dst, control_info_t *src) +{ + memcpy(dst, src, sizeof(control_info_t)); + _es_control_info(dst); +} + +static inline void _es_ci_data_digest_40(ci_data_digest_40_t *dig) +{ + dig->fw_version = _Es64(dig->fw_version); +} + +static inline void _copy_es_ci_data_digest_40(ci_data_digest_40_t *dst, ci_data_digest_40_t *src) +{ + memcpy(dst, src, sizeof(ci_data_digest_40_t)); + _es_ci_data_digest_40(dst); +} + +static inline void _es_ci_data_npdrm(ci_data_npdrm_t *np) +{ + np->magic = _Es32(np->magic); + np->unknown_0 = _Es32(np->unknown_0); + np->license_type = _Es32(np->license_type); + np->app_type = _Es32(np->app_type); + np->unknown_1 = _Es64(np->unknown_1); + np->unknown_2 = _Es64(np->unknown_2); +} + +static inline void _copy_es_ci_data_npdrm(ci_data_npdrm_t *dst, ci_data_npdrm_t *src) +{ + memcpy(dst, src, sizeof(ci_data_npdrm_t)); + _es_ci_data_npdrm(dst); +} + +static inline void _es_opt_header(opt_header_t *oh) +{ + oh->type = _Es32(oh->type); + oh->size = _Es32(oh->size); + oh->next = _Es64(oh->next); +} + +static inline void _copy_es_opt_header(opt_header_t *dst, opt_header_t *src) +{ + memcpy(dst, src, sizeof(opt_header_t)); + _es_opt_header(dst); +} + +static inline void _es_oh_data_cap_flags(oh_data_cap_flags_t *cf) +{ + cf->unk3 = _Es64(cf->unk3); + cf->unk4 = _Es64(cf->unk4); + cf->flags = _Es64(cf->flags); + cf->unk6 = _Es32(cf->unk6); + cf->unk7 = _Es32(cf->unk7); +} + +static inline void _copy_es_cap_flags(oh_data_cap_flags_t *dst, oh_data_cap_flags_t *src) +{ + memcpy(dst, src, sizeof(oh_data_cap_flags_t)); + _es_oh_data_cap_flags(dst); +} + +#endif diff --git a/scetool/scetool.cpp b/scetool/scetool.cpp new file mode 100644 index 0000000000..0ded2a40d4 --- /dev/null +++ b/scetool/scetool.cpp @@ -0,0 +1,1563 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#include +#include + +#include +#include + +#ifdef _WIN32 +#include +#include "getopt.h" +#else +#include +#include +#endif + +#include "types.h" +#include "config.h" +#include "aes.c" +#include "getopt.c" +#include "sha1.c" +#include "zlib.h" +#include "util.h" +#include "keys.h" +#include "sce.h" +#include "np.h" +#include "self.h" +#include "rvk.h" + + +/*! Verbose mode. */ +BOOL _verbose = FALSE; +/*! Raw mode. */ +BOOL _raw = FALSE; + + +/*! List keys. */ +static BOOL _list_keys = FALSE; + +/*! Parameters. */ +scetool::s8 *_template = NULL; +scetool::s8 *_file_type = NULL; +scetool::s8 *_compress_data = NULL; +scetool::s8 *_skip_sections = NULL; +scetool::s8 *_key_rev = NULL; +scetool::s8 *_meta_info = NULL; +scetool::s8 *_keyset = NULL; +scetool::s8 *_auth_id = NULL; +scetool::s8 *_vendor_id = NULL; +scetool::s8 *_self_type = NULL; +scetool::s8 *_app_version = NULL; +scetool::s8 *_fw_version = NULL; +scetool::s8 *_add_shdrs = NULL; +scetool::s8 *_ctrl_flags = NULL; +scetool::s8 *_cap_flags = NULL; +#ifdef CONFIG_CUSTOM_INDIV_SEED +scetool::s8 *_indiv_seed = NULL; +#endif +scetool::s8 *_license_type = NULL; +scetool::s8 *_app_type = NULL; +scetool::s8 *_content_id = NULL; +scetool::s8 *_klicensee = NULL; +scetool::s8 *_real_fname = NULL; +scetool::s8 *_add_sig = NULL; + +#include + + +//FILE: LIST.CPP +list_t *list_create() +{ + list_t *res; + + if((res = (list_t *)malloc(sizeof(list_t))) == NULL) + return NULL; + + res->head = NULL; + res->count = 0; + + return res; +} + +void list_destroy(list_t *l) +{ + if(l == NULL) + return; + + lnode_t *iter = l->head, *tmp; + + while(iter != NULL) + { + tmp = iter; + iter = iter->next; + free(tmp); + } + + free(l); +} + +BOOL list_push(list_t *l, void *value) +{ + if(l == NULL) + return FALSE; + + lnode_t *_new; + + //Allocate new node. + if((_new = (lnode_t *)malloc(sizeof(lnode_t))) == NULL) + return FALSE; + + //Insert. + _new->value = value; + _new->next = l->head; + l->head = _new; + l->count++; + + return TRUE; +} + +BOOL list_add_back(list_t *l, void *value) +{ + if(l == NULL) + return FALSE; + + lnode_t *n, *_new; + + //Allocate new node. + if((_new = (lnode_t *)malloc(sizeof(lnode_t))) == NULL) + return FALSE; + + _new->value = value; + _new->next = NULL; + + if(l->head == NULL) + l->head = _new; + else + { + //Move to the list end. + for(n = l->head; n->next != NULL; n = n->next); + + //Add. + n->next = _new; + l->count++; + } + + return TRUE; +} + +BOOL list_remove_node(list_t *l, lnode_t *node) +{ + if(l == NULL) + return FALSE; + + lnode_t *iter; + + if(l->head == node) + { + l->head = l->head->next; + free(node); + l->count--; + + return TRUE; + } + + iter = l->head; + while(iter->next != NULL) + { + if(iter->next == node) + { + iter->next = iter->next->next; + free(node); + l->count--; + + return TRUE; + } + iter = iter->next; + } + + return FALSE; +} + +//// + +//FILE: UTIL.CPP +scetool::u64 _x_to_u64(const scetool::s8 *hex) +{ + scetool::u64 t = 0, res = 0; + scetool::u32 len = strlen(hex); + char c; + + while(len--) + { + c = *hex++; + if(c >= '0' && c <= '9') + t = c - '0'; + else if(c >= 'a' && c <= 'f') + t = c - 'a' + 10; + else if(c >= 'A' && c <= 'F') + t = c - 'A' + 10; + else + t = 0; + res |= t << (len * 4); + } + + return res; +} + +scetool::u8 *_x_to_u8_buffer(const scetool::s8 *hex) +{ + scetool::u32 len = strlen(hex); + scetool::s8 xtmp[3] = {0, 0, 0}; + + //Must be aligned to 2. + if(len % 2 != 0) + return NULL; + + scetool::u8 *res = (scetool::u8 *)malloc(sizeof(scetool::u8) * len); + scetool::u8 *ptr = res; + + while(len--) + { + xtmp[0] = *hex++; + xtmp[1] = *hex++; + + *ptr++ = (scetool::u8)_x_to_u64(xtmp); + } + + return res; +} + +scetool::u8 *_read_buffer(const scetool::s8 *file, scetool::u32 *length) +{ + FILE *fp; + scetool::u32 size; + + if((fp = fopen(file, "rb")) == NULL) + return NULL; + + fseek(fp, 0, SEEK_END); + size = ftell(fp); + fseek(fp, 0, SEEK_SET); + + scetool::u8 *buffer = (scetool::u8 *)malloc(sizeof(scetool::u8) * size); + fread(buffer, sizeof(scetool::u8), size, fp); + + if(length != NULL) + *length = size; + + fclose(fp); + + return buffer; +} + +int _write_buffer(const scetool::s8 *file, scetool::u8 *buffer, scetool::u32 length) +{ + FILE *fp; + + if((fp = fopen(file, "wb")) == NULL) + return 0; + + /**/ + while(length > 0) + { + scetool::u32 wrlen = 1024; + if(length < 1024) + wrlen = length; + fwrite(buffer, sizeof(scetool::u8), wrlen, fp); + length -= wrlen; + buffer += 1024; + } + /**/ + + //fwrite(buffer, sizeof(scetool::u8), length, fp); + + fclose(fp); + + return 1; +} + +void _zlib_inflate(scetool::u8 *in, scetool::u64 len_in, scetool::u8 *out, scetool::u64 len_out) +{ + z_stream s; + memset(&s, 0, sizeof(z_stream)); + + s.zalloc = Z_NULL; + s.zfree = Z_NULL; + s.opaque = Z_NULL; + + inflateInit(&s); + + s.avail_in = len_in; + s.next_in = in; + s.avail_out = len_out; + s.next_out = out; + + inflate(&s, Z_FINISH); + + inflateEnd(&s); +} + +void *_memdup(void *ptr, scetool::u32 size) +{ + void *res = malloc(size); + + if(res != NULL) + memcpy(res, ptr, size); + + return res; +} + +void _print_align(FILE *fp, const scetool::s8 *str, scetool::s32 align, scetool::s32 len) +{ + scetool::s32 i, tmp; + tmp = align - len; + if(tmp < 0) + tmp = 0; + for(i = 0; i < tmp; i++) + fputs(str, fp); +} + +const scetool::s8 *_get_name(id_to_name_t *tab, scetool::u64 id) +{ + scetool::u32 i = 0; + + while(!(tab[i].name == NULL && tab[i].id == 0)) + { + if(tab[i].id == id) + return tab[i].name; + i++; + } + + return NULL; +} + +//FILE: SCE.CPP +#include "sce_inlines.h" + +sce_buffer_ctxt_t *sce_create_ctxt_from_buffer(scetool::u8 *scebuffer) +{ + sce_buffer_ctxt_t *res; + + if((res = (sce_buffer_ctxt_t *)malloc(sizeof(sce_buffer_ctxt_t))) == NULL) + return NULL; + + memset(res, 0, sizeof(sce_buffer_ctxt_t)); + + res->scebuffer = scebuffer; + res->mdec = FALSE; + + //Set pointer to SCE header. + res->sceh = (sce_header_t *)scebuffer; + _es_sce_header(res->sceh); + + //Set pointers to file type specific headers. + switch(res->sceh->header_type) + { + case SCE_HEADER_TYPE_SELF: + { + //SELF header. + res->self.selfh = (self_header_t *)(res->scebuffer + sizeof(sce_header_t)); + _es_self_header(res->self.selfh); + + //Application info. + res->self.ai = (app_info_t *)(res->scebuffer + res->self.selfh->app_info_offset); + _es_app_info(res->self.ai); + + //Section infos. + res->self.si = (section_info_t *)(res->scebuffer + res->self.selfh->section_info_offset); + + //SCE version. + if(res->self.selfh->sce_version_offset != NULL) + { + res->self.sv = (sce_version_t *)(res->scebuffer + res->self.selfh->sce_version_offset); + _es_sce_version(res->self.sv); + } + else + res->self.sv = 0; + + //Get pointers to all control infos. + scetool::u32 len = (scetool::u32)res->self.selfh->control_info_size; + if(len > 0) + { + scetool::u8 *ptr = res->scebuffer + res->self.selfh->control_info_offset; + res->self.cis = list_create(); + + while(len > 0) + { + control_info_t *tci = (control_info_t *)ptr; + _es_control_info(tci); + ptr += tci->size; + len -= tci->size; + list_add_back(res->self.cis, tci); + } + } + else + res->self.cis = NULL; + } + break; + case SCE_HEADER_TYPE_RVK: + //TODO + break; + case SCE_HEADER_TYPE_PKG: + //TODO + break; + case SCE_HEADER_TYPE_SPP: + //TODO + break; + default: + free(res); + return NULL; + break; + } + + //Set pointers to metadata headers. + res->metai = (metadata_info_t *)(scebuffer + sizeof(sce_header_t) + res->sceh->metadata_offset); + res->metah = (metadata_header_t *)((scetool::u8 *)res->metai + sizeof(metadata_info_t)); + res->metash = (metadata_section_header_t *)((scetool::u8 *)res->metah + sizeof(metadata_header_t)); + + return res; +} + +static scetool::s8 _sce_tmp_vstr[16]; +scetool::s8 *sce_version_to_str(scetool::u64 version) +{ + scetool::u32 v = version >> 32; + sprintf(_sce_tmp_vstr, "%02X.%02X", (v & 0xFFFF0000) >> 16, v & 0x0000FFFF); + return _sce_tmp_vstr; +} + +BOOL sce_decrypt_header(sce_buffer_ctxt_t *ctxt, scetool::u8 *metadata_info, scetool::u8 *keyset) +{ + scetool::u32 i; + size_t nc_off; + scetool::u8 sblk[0x10], iv[0x10]; + keyset_t *ks; + aes_context aes_ctxt; + + //Check if provided metadata info should be used. + if(metadata_info == NULL) + { + //Check if a keyset is provided. + if(keyset == NULL) + { + //Try to find keyset. + if((ks = keyset_find(ctxt)) == NULL) + return FALSE; + + _LOG_VERBOSE("Using keyset [%s 0x%04X %s]\n", ks->name, ks->key_revision, sce_version_to_str(ks->version)); + } + else + { + //Use the provided keyset. + ks = keyset_from_buffer(keyset); + } + + //Remove NPDRM layer. + if(ctxt->sceh->header_type == SCE_HEADER_TYPE_SELF && ctxt->self.ai->self_type == SELF_TYPE_NPDRM) + if(np_decrypt_npdrm(ctxt) == FALSE) + return FALSE; + + //Decrypt metadata info. + aes_setkey_dec(&aes_ctxt, ks->erk, KEYBITS(ks->erklen)); + memcpy(iv, ks->riv, 0x10); //!!! + aes_crypt_cbc(&aes_ctxt, AES_DECRYPT, sizeof(metadata_info_t), iv, (scetool::u8 *)ctxt->metai, (scetool::u8 *)ctxt->metai); + } + else + { + //Copy provided metadata info over SELF metadata. + memcpy((scetool::u8 *)ctxt->metai, metadata_info, sizeof(metadata_info)); + } + + if(ctxt->metai->key_pad[0] != 0x00 || ctxt->metai->iv_pad[0] != 0x00) + return FALSE; + + //Decrypt metadata header, metadata section headers and keys. + nc_off = 0; + aes_setkey_enc(&aes_ctxt, ctxt->metai->key, METADATA_INFO_KEYBITS); + aes_crypt_ctr(&aes_ctxt, + ctxt->sceh->header_len - (sizeof(sce_header_t) + ctxt->sceh->metadata_offset + sizeof(metadata_info_t)), + &nc_off, ctxt->metai->iv, sblk, (scetool::u8 *)ctxt->metah, (scetool::u8 *)ctxt->metah); + + //Fixup headers. + _es_metadata_header(ctxt->metah); + for(i = 0; i < ctxt->metah->section_count; i++) + _es_metadata_section_header(&ctxt->metash[i]); + + //Metadata decrypted. + ctxt->mdec = TRUE; + + //Set start of SCE file keys. + ctxt->keys = (scetool::u8 *)ctxt->metash + sizeof(metadata_section_header_t) * ctxt->metah->section_count; + ctxt->keys_len = ctxt->metah->key_count * 0x10; + + //Set SELF only headers. + if(ctxt->sceh->header_type == SCE_HEADER_TYPE_SELF) + { + //Get pointers to all optional headers. + ctxt->self.ohs = list_create(); + opt_header_t *oh = (opt_header_t *)(ctxt->keys + ctxt->metah->key_count * 0x10); + _es_opt_header(oh); + list_add_back(ctxt->self.ohs, oh); + while(oh->next != 0) + { + oh = (opt_header_t *)((scetool::u8 *)oh + oh->size); + _es_opt_header(oh); + list_add_back(ctxt->self.ohs, oh); + } + + //Signature. + ctxt->sig = (signature_t *)((scetool::u8 *)oh + oh->size); + } + else + ctxt->sig = (signature_t *)(ctxt->keys + ctxt->metah->key_count * 0x10); + + return TRUE; +} + +BOOL sce_decrypt_data(sce_buffer_ctxt_t *ctxt) +{ + scetool::u32 i; + aes_context aes_ctxt; + + //Decrypt sections. + for(i = 0; i < ctxt->metah->section_count; i++) + { + size_t nc_off = 0; + scetool::u8 buf[16]; + scetool::u8 iv[16]; + + //Only decrypt encrypted sections. + if(ctxt->metash[i].encrypted == METADATA_SECTION_ENCRYPTED) + { + if(ctxt->metash[i].key_index > ctxt->metah->key_count - 1 || ctxt->metash[i].iv_index > ctxt->metah->key_count) + printf("[*] Warning: Skipped decryption of section %03d (marked encrypted but key/iv index out of range)\n", i); + else + { + memcpy(iv, ctxt->keys + ctxt->metash[i].iv_index * 0x10, 0x10); + aes_setkey_enc(&aes_ctxt, ctxt->keys + ctxt->metash[i].key_index * 0x10, 128); + scetool::u8 *ptr = ctxt->scebuffer + ctxt->metash[i].data_offset; + aes_crypt_ctr(&aes_ctxt, ctxt->metash[i].data_size, &nc_off, iv, buf, ptr, ptr); + } + } + } + + return TRUE; +} + +//FILE: SELF.CPP +#include "elf_inlines.h" + +//TODO: maybe implement better. +BOOL self_write_to_elf(sce_buffer_ctxt_t *ctxt, const scetool::s8 *elf_out) +{ + FILE *fp; + scetool::u32 i, self_type; + + const scetool::u8 *eident; + + //Check for SELF. + if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF) + return FALSE; + + if((fp = fopen(elf_out, "wb")) == NULL) + return FALSE; + + self_type = ctxt->self.ai->self_type; + eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset; + + //SPU is 32 bit. + if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASs32) + { +#ifdef CONFIG_DUMP_INDIV_SEED + /* + //Print individuals seed. + if(self_type == SELF_TYPE_ISO) + { + scetool::u8 *indiv_seed = (scetool::u8 *)ctxt->self.ish + sizeof(iseed_header_t); + scetool::s8 ifile[256]; + sprintf(ifile, "%s.indiv_seed.bin", elf_out); + FILE *ifp = fopen(ifile, "wb"); + fwrite(indiv_seed, sizeof(scetool::u8), ctxt->self.ish->size - sizeof(iseed_header_t), ifp); + fclose(ifp); + } + */ +#endif + + //32 bit ELF. + Elf32_Ehdr ceh, *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); + _copy_es_elf32_ehdr(&ceh, eh); + + //Write ELF header. + fwrite(eh, sizeof(Elf32_Ehdr), 1, fp); + + //Write program headers. + Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); + fwrite(ph, sizeof(Elf32_Phdr), ceh.e_phnum, fp); + + //Write program data. + metadata_section_header_t *msh = ctxt->metash; + for(i = 0; i < ctxt->metah->section_count; i++) + { + if(msh[i].type == METADATA_SECTION_TYPE_PHDR) + { + _es_elf32_phdr(&ph[msh[i].index]); + fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); + fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(scetool::u8), msh[i].data_size, fp); + } + } + + //Write section headers. + if(ctxt->self.selfh->shdr_offset != 0) + { + Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); + fseek(fp, ceh.e_shoff, SEEK_SET); + fwrite(sh, sizeof(Elf32_Shdr), ceh.e_shnum, fp); + } + } + else + { + //64 bit ELF. + Elf64_Ehdr ceh, *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); + _copy_es_elf64_ehdr(&ceh, eh); + + //Write ELF header. + fwrite(eh, sizeof(Elf64_Ehdr), 1, fp); + + //Write program headers. + Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); + fwrite(ph, sizeof(Elf64_Phdr), ceh.e_phnum, fp); + + //Write program data. + metadata_section_header_t *msh = ctxt->metash; + for(i = 0; i < ctxt->metah->section_count; i++) + { + if(msh[i].type == METADATA_SECTION_TYPE_PHDR) + { + if(msh[i].compressed == METADATA_SECTION_COMPRESSED) + { + _es_elf64_phdr(&ph[msh[i].index]); + scetool::u8 *data = (scetool::u8 *)malloc(ph[msh[i].index].p_filesz); + + _zlib_inflate(ctxt->scebuffer + msh[i].data_offset, msh[i].data_size, data, ph[msh[i].index].p_filesz); + fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); + fwrite(data, sizeof(scetool::u8), ph[msh[i].index].p_filesz, fp); + + free(data); + } + else + { + _es_elf64_phdr(&ph[msh[i].index]); + fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); + fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(scetool::u8), msh[i].data_size, fp); + } + } + } + + //Write section headers. + if(ctxt->self.selfh->shdr_offset != 0) + { + Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); + fseek(fp, ceh.e_shoff, SEEK_SET); + fwrite(sh, sizeof(Elf64_Shdr), ceh.e_shnum, fp); + } + } + + fclose(fp); + + return TRUE; +} + +//FILE: NP.CPP +/*! klicensee key. */ +static scetool::u8 *_klicensee_key; + +static ci_data_npdrm_t *_sce_find_ci_npdrm(sce_buffer_ctxt_t *ctxt) +{ + if(ctxt->self.cis != NULL) + { + LIST_FOREACH(iter, ctxt->self.cis) + { + control_info_t *ci = (control_info_t *)iter->value; + + if(ci->type == CONTROL_INFO_TYPE_NPDRM) + { + ci_data_npdrm_t *np = (ci_data_npdrm_t *)((scetool::u8 *)ci + sizeof(control_info_t)); + //Fixup. + _es_ci_data_npdrm(np); + return np; + } + } + } + + return NULL; +} + +void np_set_klicensee(scetool::u8 *klicensee) +{ + _klicensee_key = klicensee; +} + +BOOL np_decrypt_npdrm(sce_buffer_ctxt_t *ctxt) +{ + aes_context aes_ctxt; + keyset_t *ks_np_klic_free, *ks_klic_key; + scetool::u8 npdrm_key[0x10]; + scetool::u8 npdrm_iv[0x10]; + ci_data_npdrm_t *np; + + if((np = _sce_find_ci_npdrm(ctxt)) == NULL) + return FALSE; + + //Try to find keysets. + ks_klic_key = keyset_find_by_name(CONFIG_NP_KLIC_KEY_KNAME); + if(ks_klic_key == NULL) + return FALSE; + if(_klicensee_key != NULL) + memcpy(npdrm_key, _klicensee_key, 0x10); + else if(np->license_type == NP_LICENSE_FREE) + { + ks_np_klic_free = keyset_find_by_name(CONFIG_NP_KLIC_FREE_KNAME); + if(ks_np_klic_free == NULL) + return FALSE; + memcpy(npdrm_key, ks_np_klic_free->erk, 0x10); + } + else if(np->license_type == NP_LICENSE_LOCAL) + { + if ((klicensee_by_content_id((scetool::s8 *)np->content_id, npdrm_key)) == FALSE) + return FALSE; + } + else + return FALSE; + + aes_setkey_dec(&aes_ctxt, ks_klic_key->erk, METADATA_INFO_KEYBITS); + aes_crypt_ecb(&aes_ctxt, AES_DECRYPT, npdrm_key, npdrm_key); + + memset(npdrm_iv, 0, 0x10); + aes_setkey_dec(&aes_ctxt, npdrm_key, METADATA_INFO_KEYBITS); + aes_crypt_cbc(&aes_ctxt, AES_DECRYPT, sizeof(metadata_info_t), npdrm_iv, (scetool::u8 *)ctxt->metai, (scetool::u8 *)ctxt->metai); + + return TRUE; +} + +//FILE: TABLES.CPP +/*! SCE header types. */ +id_to_name_t _sce_header_types[] = +{ + {SCE_HEADER_TYPE_SELF, "SELF"}, + {SCE_HEADER_TYPE_RVK, "RVK"}, + {SCE_HEADER_TYPE_PKG, "PKG"}, + {SCE_HEADER_TYPE_SPP, "SPP"}, + {0, NULL} +}; + +/*! SELF types. */ +id_to_name_t _self_types[] = +{ + {SELF_TYPE_LV0, "lv0"}, + {SELF_TYPE_LV1, "lv1"}, + {SELF_TYPE_LV2, "lv2"}, + {SELF_TYPE_APP, "Application"}, + {SELF_TYPE_ISO, "Isolated SPU Module"}, + {SELF_TYPE_LDR, "Secure Loader"}, + {SELF_TYPE_UNK_7, "Unknown 7"}, + {SELF_TYPE_NPDRM, "NPDRM Application"}, + {0, NULL} +}; + +/*! Key types. */ +id_to_name_t _key_types[] = +{ + {KEYTYPE_SELF, "SELF"}, + {KEYTYPE_RVK, "RVK"}, + {KEYTYPE_PKG, "PKG"}, + {KEYTYPE_SPP, "SPP"}, + {KEYTYPE_OTHER, "OTHER"}, + {0, NULL} +}; + +//FILE: KEYS.CPP +/*! Loaded keysets. */ +list_t *_keysets; +/*! Loaded curves. */ +curve_t *_curves; +/*! Loaded VSH curves. */ +vsh_curve_t *_vsh_curves; + +static scetool::u8 rap_init_key[0x10] = +{ + 0x86, 0x9F, 0x77, 0x45, 0xC1, 0x3F, 0xD8, 0x90, 0xCC, 0xF2, 0x91, 0x88, 0xE3, 0xCC, 0x3E, 0xDF +}; + +static scetool::u8 rap_pbox[0x10] = +{ + 0x0C, 0x03, 0x06, 0x04, 0x01, 0x0B, 0x0F, 0x08, 0x02, 0x07, 0x00, 0x05, 0x0A, 0x0E, 0x0D, 0x09 +}; + +static scetool::u8 rap_e1[0x10] = +{ + 0xA9, 0x3E, 0x1F, 0xD6, 0x7C, 0x55, 0xA3, 0x29, 0xB7, 0x5F, 0xDD, 0xA6, 0x2A, 0x95, 0xC7, 0xA5 +}; + +static scetool::u8 rap_e2[0x10] = +{ + 0x67, 0xD4, 0x5D, 0xA3, 0x29, 0x6D, 0x00, 0x6A, 0x4E, 0x7C, 0x53, 0x7B, 0xF5, 0x53, 0x8C, 0x74 +}; + +static act_dat_t *act_dat_load() +{ + scetool::s8 *ps3 = NULL, path[256]; + act_dat_t *act_dat; + scetool::u32 len = 0; + + if((ps3 = getenv(CONFIG_ENV_PS3)) != NULL) + if(_access(ps3, 0) != 0) + ps3 = NULL; + + if(ps3 != NULL) + { + sprintf(path, "%s/%s", ps3, CONFIG_ACT_DAT_FILE); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s", CONFIG_ACT_DAT_PATH, CONFIG_ACT_DAT_FILE); + } + else + sprintf(path, "%s/%s", CONFIG_ACT_DAT_PATH, CONFIG_ACT_DAT_FILE); + + act_dat = (act_dat_t *)_read_buffer(path, &len); + + if(act_dat == NULL) + return NULL; + + if(len != ACT_DAT_LENGTH) + { + free(act_dat); + return NULL; + } + + return act_dat; +} + +static rif_t *rif_load(const scetool::s8 *content_id) +{ + scetool::s8 *ps3 = NULL, path[256]; + rif_t *rif; + scetool::u32 len = 0; + + if((ps3 = getenv(CONFIG_ENV_PS3)) != NULL) + if(_access(ps3, 0) != 0) + ps3 = NULL; + + if(ps3 != NULL) + { + sprintf(path, "%s/%s%s", ps3, content_id, CONFIG_RIF_FILE_EXT); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s%s", CONFIG_RIF_PATH, content_id, CONFIG_RIF_FILE_EXT); + } + else + sprintf(path, "%s/%s%s", CONFIG_RIF_PATH, content_id, CONFIG_RIF_FILE_EXT); + + rif = (rif_t *)_read_buffer(path, &len); + if(rif == NULL) + return NULL; + + if(len < RIF_LENGTH) + { + free(rif); + return NULL; + } + + return rif; +} + +static scetool::u8 *rap_load(const scetool::s8 *content_id) +{ + scetool::s8 *ps3 = NULL, path[256]; + scetool::u8 *rap; + scetool::u32 len = 0; + + if((ps3 = getenv(CONFIG_ENV_PS3)) != NULL) + if(_access(ps3, 0) != 0) + ps3 = NULL; + + if(ps3 != NULL) + { + sprintf(path, "%s/%s%s", ps3, content_id, CONFIG_RAP_FILE_EXT); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s%s", CONFIG_RAP_PATH, content_id, CONFIG_RAP_FILE_EXT); + } + else + sprintf(path, "%s/%s%s", CONFIG_RAP_PATH, content_id, CONFIG_RAP_FILE_EXT); + + rap = (scetool::u8 *)_read_buffer(path, &len); + + if(rap == NULL) + return NULL; + + if(len != RAP_LENGTH) + { + free(rap); + return NULL; + } + + return rap; +} + +static BOOL rap_to_klicensee(const scetool::s8 *content_id, scetool::u8 *klicensee) +{ + scetool::u8 *rap; + aes_context aes_ctxt; + int round_num; + int i; + + rap = rap_load(content_id); + if(rap == NULL) + return FALSE; + + aes_setkey_dec(&aes_ctxt, rap_init_key, RAP_KEYBITS); + aes_crypt_ecb(&aes_ctxt, AES_DECRYPT, rap, rap); + + for (round_num = 0; round_num < 5; ++round_num) + { + for (i = 0; i < 16; ++i) + { + int p = rap_pbox[i]; + rap[p] ^= rap_e1[p]; + } + for (i = 15; i >= 1; --i) + { + int p = rap_pbox[i]; + int pp = rap_pbox[i - 1]; + rap[p] ^= rap[pp]; + } + int o = 0; + for (i = 0; i < 16; ++i) + { + int p = rap_pbox[i]; + scetool::u8 kc = rap[p] - o; + scetool::u8 ec2 = rap_e2[p]; + if (o != 1 || kc != 0xFF) + { + o = kc < ec2 ? 1 : 0; + rap[p] = kc - ec2; + } + else if (kc == 0xFF) + rap[p] = kc - ec2; + else + rap[p] = kc; + } + } + + memcpy(klicensee, rap, RAP_LENGTH); + free(rap); + + return TRUE; +} + +static scetool::u8 *idps_load() +{ + scetool::s8 *ps3 = NULL, path[256]; + scetool::u8 *idps; + scetool::u32 len = 0; + + if((ps3 = getenv(CONFIG_ENV_PS3)) != NULL) + if(_access(ps3, 0) != 0) + ps3 = NULL; + + if(ps3 != NULL) + { + sprintf(path, "%s/%s", ps3, CONFIG_IDPS_FILE); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s", CONFIG_IDPS_PATH, CONFIG_IDPS_FILE); + } + else + sprintf(path, "%s/%s", CONFIG_IDPS_PATH, CONFIG_IDPS_FILE); + + idps = (scetool::u8 *)_read_buffer(path, &len); + + if(idps == NULL) + return NULL; + + if(len != IDPS_LENGTH) + { + free(idps); + return NULL; + } + + return idps; +} + +BOOL klicensee_by_content_id(const scetool::s8 *content_id, scetool::u8 *klicensee) +{ + aes_context aes_ctxt; + + if(rap_to_klicensee(content_id, klicensee) == FALSE) + { + keyset_t *ks_np_idps_const, *ks_np_rif_key; + rif_t *rif; + scetool::u8 idps_const[0x10]; + scetool::u8 act_dat_key[0x10]; + scetool::u32 act_dat_key_index; + scetool::u8 *idps; + act_dat_t *act_dat; + + if((idps = idps_load()) == NULL) + { + printf("[*] Error: Could not load IDPS.\n"); + return FALSE; + } + else + _LOG_VERBOSE("IDPS loaded.\n"); + + if((act_dat = act_dat_load()) == NULL) + { + printf("[*] Error: Could not load act.dat.\n"); + return FALSE; + } + else + _LOG_VERBOSE("act.dat loaded.\n"); + + ks_np_idps_const = keyset_find_by_name(CONFIG_NP_IDPS_CONST_KNAME); + if(ks_np_idps_const == NULL) + return FALSE; + memcpy(idps_const, ks_np_idps_const->erk, 0x10); + + ks_np_rif_key = keyset_find_by_name(CONFIG_NP_RIF_KEY_KNAME); + if(ks_np_rif_key == NULL) + return FALSE; + + rif = rif_load(content_id); + if(rif == NULL) + { + printf("[*] Error: Could not obtain klicensee for '%s'.\n", content_id); + return FALSE; + } + + aes_setkey_dec(&aes_ctxt, ks_np_rif_key->erk, RIF_KEYBITS); + aes_crypt_ecb(&aes_ctxt, AES_DECRYPT, rif->act_key_index, rif->act_key_index); + + act_dat_key_index = _Es32(*(scetool::u32 *)(rif->act_key_index + 12)); + if(act_dat_key_index > 127) + { + printf("[*] Error: act.dat key index out of bounds.\n"); + return FALSE; + } + + memcpy(act_dat_key, act_dat->primary_key_table + act_dat_key_index * BITS2BYTES(ACT_DAT_KEYBITS), BITS2BYTES(ACT_DAT_KEYBITS)); + + aes_setkey_enc(&aes_ctxt, idps, IDPS_KEYBITS); + aes_crypt_ecb(&aes_ctxt, AES_ENCRYPT, idps_const, idps_const); + + aes_setkey_dec(&aes_ctxt, idps_const, IDPS_KEYBITS); + aes_crypt_ecb(&aes_ctxt, AES_DECRYPT, act_dat_key, act_dat_key); + + aes_setkey_dec(&aes_ctxt, act_dat_key, ACT_DAT_KEYBITS); + aes_crypt_ecb(&aes_ctxt, AES_DECRYPT, rif->klicensee, klicensee); + + free(rif); + + _LOG_VERBOSE("klicensee decrypted.\n"); + } + else + _LOG_VERBOSE("klicensee converted from %s.rap.\n", content_id); + + return TRUE; +} + +keyset_t *keyset_from_buffer(scetool::u8 *keyset) +{ + keyset_t *ks; + + if((ks = (keyset_t *)malloc(sizeof(keyset_t))) == NULL) + return NULL; + + ks->erk = (scetool::u8 *)_memdup(keyset, 0x20); + ks->erklen = 0x20; + ks->riv = (scetool::u8 *)_memdup(keyset + 0x20, 0x10); + ks->rivlen = 0x10; + ks->pub = (scetool::u8 *)_memdup(keyset + 0x20 + 0x10, 0x28); + ks->priv = (scetool::u8 *)_memdup(keyset + 0x20 + 0x10 + 0x28, 0x15); + ks->ctype = (scetool::u8)*(keyset + 0x20 + 0x10 + 0x28 + 0x15); + + return ks; +} + +keyset_t *keyset_find_by_name(const scetool::s8 *name) +{ + LIST_FOREACH(iter, _keysets) + { + keyset_t *ks = (keyset_t *)iter->value; + if(strcmp(ks->name, name) == 0) + return ks; + } + + printf("[*] Error: Could not find keyset '%s'.\n", name); + + return NULL; +} + +static keyset_t *_keyset_find_for_self(scetool::u32 self_type, scetool::u16 key_revision, scetool::u64 version) +{ + LIST_FOREACH(iter, _keysets) + { + keyset_t *ks = (keyset_t *)iter->value; + + if(ks->self_type == self_type) + { + switch(self_type) + { + case SELF_TYPE_LV0: + return ks; + break; + case SELF_TYPE_LV1: + if(version <= ks->version) + return ks; + break; + case SELF_TYPE_LV2: + if(version <= ks->version) + return ks; + break; + case SELF_TYPE_APP: + if(key_revision == ks->key_revision) + return ks; + break; + case SELF_TYPE_ISO: + if(version <= ks->version && key_revision == ks->key_revision) + return ks; + break; + case SELF_TYPE_LDR: + return ks; + break; + case SELF_TYPE_NPDRM: + if(key_revision == ks->key_revision) + return ks; + break; + } + } + } + + return NULL; +} + +static keyset_t *_keyset_find_for_rvk(scetool::u32 key_revision) +{ + LIST_FOREACH(iter, _keysets) + { + keyset_t *ks = (keyset_t *)iter->value; + + if(ks->type == KEYTYPE_RVK && key_revision <= ks->key_revision) + return ks; + } + + return NULL; +} + +static keyset_t *_keyset_find_for_pkg(scetool::u16 key_revision) +{ + LIST_FOREACH(iter, _keysets) + { + keyset_t *ks = (keyset_t *)iter->value; + + if(ks->type == KEYTYPE_PKG && key_revision <= ks->key_revision) + return ks; + } + + return NULL; +} + +static keyset_t *_keyset_find_for_spp(scetool::u16 key_revision) +{ + LIST_FOREACH(iter, _keysets) + { + keyset_t *ks = (keyset_t *)iter->value; + + if(ks->type == KEYTYPE_SPP && key_revision <= ks->key_revision) + return ks; + } + + return NULL; +} + +keyset_t *keyset_find(sce_buffer_ctxt_t *ctxt) +{ + keyset_t *res = NULL; + + switch(ctxt->sceh->header_type) + { + case SCE_HEADER_TYPE_SELF: + res = _keyset_find_for_self(ctxt->self.ai->self_type, ctxt->sceh->key_revision, ctxt->self.ai->version); + break; + case SCE_HEADER_TYPE_RVK: + res = _keyset_find_for_rvk(ctxt->sceh->key_revision); + break; + case SCE_HEADER_TYPE_PKG: + res = _keyset_find_for_pkg(ctxt->sceh->key_revision); + break; + case SCE_HEADER_TYPE_SPP: + res = _keyset_find_for_spp(ctxt->sceh->key_revision); + break; + } + + if(res == NULL) + printf("[*] Error: Could not find keyset for %s.\n", _get_name(_sce_header_types, ctxt->sceh->header_type)); + + return res; +} + +static void _fill_property(keyset_t *ks, scetool::s8 *prop, scetool::s8 *value) +{ + if(strcmp(prop, "type") == 0) + { + if(strcmp(value, "SELF") == 0) + ks->type = KEYTYPE_SELF; + else if(strcmp(value, "RVK") == 0) + ks->type = KEYTYPE_RVK; + else if(strcmp(value, "PKG") == 0) + ks->type = KEYTYPE_PKG; + else if(strcmp(value, "SPP") == 0) + ks->type = KEYTYPE_SPP; + else if(strcmp(value, "OTHER") == 0) + ks->type = KEYTYPE_OTHER; + else + printf("[*] Error: Unknown type '%s'.\n", value); + } + else if(strcmp(prop, "revision") == 0) + ks->key_revision = (scetool::u16)_x_to_u64(value); + else if(strcmp(prop, "version") == 0) + ks->version = _x_to_u64(value); + else if(strcmp(prop, "self_type") == 0) + { + if(strcmp(value, "LV0") == 0) + ks->self_type = SELF_TYPE_LV0; + else if(strcmp(value, "LV1") == 0) + ks->self_type = SELF_TYPE_LV1; + else if(strcmp(value, "LV2") == 0) + ks->self_type = SELF_TYPE_LV2; + else if(strcmp(value, "APP") == 0) + ks->self_type = SELF_TYPE_APP; + else if(strcmp(value, "ISO") == 0) + ks->self_type = SELF_TYPE_ISO; + else if(strcmp(value, "LDR") == 0) + ks->self_type = SELF_TYPE_LDR; + else if(strcmp(value, "UNK_7") == 0) + ks->self_type = SELF_TYPE_UNK_7; + else if(strcmp(value, "NPDRM") == 0) + ks->self_type = SELF_TYPE_NPDRM; + else + printf("[*] Error: unknown SELF type '%s'.\n", value); + } + else if(strcmp(prop, "erk") == 0 || strcmp(prop, "key") == 0) + { + ks->erk = _x_to_u8_buffer(value); + ks->erklen = strlen(value) / 2; + } + else if(strcmp(prop, "riv") == 0) + { + ks->riv = _x_to_u8_buffer(value); + ks->rivlen = strlen(value) / 2; + } + else if(strcmp(prop, "pub") == 0) + ks->pub = _x_to_u8_buffer(value); + else if(strcmp(prop, "priv") == 0) + ks->priv = _x_to_u8_buffer(value); + else if(strcmp(prop, "ctype") == 0) + ks->ctype = (scetool::u8)_x_to_u64(value); + else + printf("[*] Error: Unknown keyfile property '%s'.\n", prop); +} + +BOOL curves_load(const scetool::s8 *cfile) +{ + scetool::u32 len = 0; + + _curves = (curve_t *)_read_buffer(cfile, &len); + + if(_curves == NULL) + return FALSE; + + if(len != CURVES_LENGTH) + { + free(_curves); + return FALSE; + } + + return TRUE; +} + +BOOL vsh_curves_load(const scetool::s8 *cfile) +{ + scetool::u32 len = 0; + + _vsh_curves = (vsh_curve_t *)_read_buffer(cfile, &len); + + if(_vsh_curves == NULL) + return FALSE; + + if(len != VSH_CURVES_LENGTH) + { + free(_vsh_curves); + return FALSE; + } + + return TRUE; +} + +static scetool::s64 _compare_keysets(keyset_t *ks1, keyset_t *ks2) +{ + scetool::s64 res; + + if((res = (scetool::s64)ks1->version - (scetool::s64)ks2->version) == 0) + res = (scetool::s64)ks1->key_revision - (scetool::s64)ks2->key_revision; + + return res; +} + +static void _sort_keysets() +{ + scetool::u32 i, to = _keysets->count; + lnode_t *max; + + list_t *tmp = list_create(); + + for(i = 0; i < to; i++) + { + max = _keysets->head; + LIST_FOREACH(iter, _keysets) + { + if(_compare_keysets((keyset_t *)max->value, (keyset_t *)iter->value) < 0) + max = iter; + } + list_push(tmp, max->value); + list_remove_node(_keysets, max); + } + + list_destroy(_keysets); + _keysets = tmp; +} + +#define LINEBUFSIZE 512 +BOOL keys_load(const scetool::s8 *kfile) +{ + scetool::u32 i = 0, lblen; + FILE *fp; + scetool::s8 lbuf[LINEBUFSIZE]; + keyset_t *cks = NULL; + + if((_keysets = list_create()) == NULL) + return FALSE; + + if((fp = fopen(kfile, "r")) == NULL) + { + list_destroy(_keysets); + return FALSE; + } + + do + { + //Get next line. + lbuf[0] = 0; + fgets(lbuf, LINEBUFSIZE, fp); + lblen = strlen(lbuf); + + //Don't parse empty lines (ignore '\n') and comment lines (starting with '#'). + if(lblen > 1 && lbuf[0] != '#') + { + //Remove '\n'. + lbuf[lblen-1] = 0; + + //Check for keyset entry. + if(lblen > 2 && lbuf[0] == '[') + { + if(cks != NULL) + { + //Add to keyset list. + list_push(_keysets, cks); + cks = NULL; + } + + //Find name end. + for(i = 0; lbuf[i] != ']' && lbuf[i] != '\n' && i < lblen; i++); + lbuf[i] = 0; + + //Allocate keyset and fill name. + cks = (keyset_t *)malloc(sizeof(keyset_t)); + memset(cks, 0, sizeof(keyset_t)); + cks->name = _strdup(&lbuf[1]); + } + else if(cks != NULL) + { + //Find property name end. + for(i = 0; lbuf[i] != '=' && lbuf[i] != '\n' && i < lblen; i++); + lbuf[i] = 0; + + //Fill property. + _fill_property(cks, &lbuf[0], &lbuf[i+1]); + } + } + } while(!feof(fp)); + + //Add last keyset to keyset list. + if(cks != NULL) + list_push(_keysets, cks); + + //Sort keysets. + _sort_keysets(); + + return TRUE; +} +#undef LINEBUFSIZE + +bool frontend_decrypt(scetool::s8 *file_in, scetool::s8 *file_out) +{ + scetool::u8 *buf = _read_buffer(file_in, NULL); + if(buf != NULL) + { + sce_buffer_ctxt_t *ctxt = sce_create_ctxt_from_buffer(buf); + if(ctxt != NULL) + { + scetool::u8 *meta_info = NULL; + if(_meta_info != NULL) + { + if(strlen(_meta_info) != 0x40*2) + { + ConLog.Error("scetool: Metadata info needs to be 64 bytes.\n"); + return false; + } + meta_info = _x_to_u8_buffer(_meta_info); + } + + scetool::u8 *keyset = NULL; + if(_keyset != NULL) + { + if(strlen(_keyset) != (0x20 + 0x10 + 0x15 + 0x28 + 0x01)*2) + { + ConLog.Error("scetool: Keyset has a wrong length"); + return false; + } + keyset = _x_to_u8_buffer(_keyset); + } + + if(sce_decrypt_header(ctxt, meta_info, keyset)) + { + if(sce_decrypt_data(ctxt)) + { + if(ctxt->sceh->header_type == SCE_HEADER_TYPE_SELF) + { + if(self_write_to_elf(ctxt, file_out) == TRUE) + ConLog.Write("scetool: ELF written to %s", file_out); + else + ConLog.Error("scetool: Could not write ELF"); + } + else if(ctxt->sceh->header_type == SCE_HEADER_TYPE_RVK) + { + if(_write_buffer(file_out, ctxt->scebuffer + ctxt->metash[0].data_offset, + ctxt->metash[0].data_size + ctxt->metash[1].data_size)) + ConLog.Write("scetool: RVK written to %s", file_out); + else + ConLog.Error("scetool: Could not write RVK"); + } + else if(ctxt->sceh->header_type == SCE_HEADER_TYPE_PKG) + { + /*if(_write_buffer(file_out, ctxt->scebuffer + ctxt->metash[0].data_offset, + ctxt->metash[0].data_size + ctxt->metash[1].data_size + ctxt->metash[2].data_size)) + printf("[*] PKG written to %s.\n", file_out); + else + printf("[*] Error: Could not write PKG.\n");*/ + ConLog.Warning("scetool: Not yet supported"); + } + else if(ctxt->sceh->header_type == SCE_HEADER_TYPE_SPP) + { + if(_write_buffer(file_out, ctxt->scebuffer + ctxt->metash[0].data_offset, + ctxt->metash[0].data_size + ctxt->metash[1].data_size)) + ConLog.Write("scetool: SPP written to %s", file_out); + else + ConLog.Error("scetool: Could not write SPP"); + } + } + else + ConLog.Error("scetool: Could not decrypt data"); + } + else + ConLog.Error("scetool: Could not decrypt header"); + free(ctxt); + } + else + ConLog.Error("scetool: Could not process %s", file_in); + free(buf); + } + else + ConLog.Error("scetool: Could not load %s", file_in); + return true; +} + + +bool scetool_decrypt(scetool::s8 *_file_in, scetool::s8 *_file_out) +{ + scetool::s8 *ps3 = NULL, path[256]; + + //Try to get path from env:PS3. + if((ps3 = getenv(CONFIG_ENV_PS3)) != NULL) + if(_access(ps3, 0) != 0) + ps3 = NULL; + + //Load keysets. + if(ps3 != NULL) + { + sprintf(path, "%s/%s", ps3, CONFIG_KEYS_FILE); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s", CONFIG_KEYS_PATH, CONFIG_KEYS_FILE); + } + else + sprintf(path, "%s/%s", CONFIG_KEYS_PATH, CONFIG_KEYS_FILE); + if(!keys_load(path)) + { + ConLog.Error("scetool: Could not load keys"); + return false; + } + + //Load curves. + if(ps3 != NULL) + { + sprintf(path, "%s/%s", ps3, CONFIG_CURVES_FILE); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s", CONFIG_CURVES_PATH, CONFIG_CURVES_FILE); + } + else + sprintf(path, "%s/%s", CONFIG_CURVES_PATH, CONFIG_CURVES_FILE); + if(!curves_load(path)) + { + ConLog.Error("scetool: Could not load loader curves"); + return false; + } + + //Load curves. + if(ps3 != NULL) + { + sprintf(path, "%s/%s", ps3, CONFIG_VSH_CURVES_FILE); + if(_access(path, 0) != 0) + sprintf(path, "%s/%s", CONFIG_VSH_CURVES_PATH, CONFIG_VSH_CURVES_FILE); + } + else + sprintf(path, "%s/%s", CONFIG_VSH_CURVES_PATH, CONFIG_VSH_CURVES_FILE); + if(!vsh_curves_load(path)) + { + ConLog.Error("scetool: Could not load vsh curves"); + return false; + } + + //Set klicensee. + if(_klicensee != NULL) + { + if(strlen(_klicensee) != 0x10*2) + { + ConLog.Error("scetool: klicensee needs to be 16 bytes."); + return false; + } + np_set_klicensee(_x_to_u8_buffer(_klicensee)); + } + + + return frontend_decrypt(_file_in, _file_out);; +} diff --git a/scetool/self.h b/scetool/self.h new file mode 100644 index 0000000000..2a9ad70888 --- /dev/null +++ b/scetool/self.h @@ -0,0 +1,72 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _SELF_H_ +#define _SELF_H_ + +#include "types.h" +#include "config.h" +#include "np.h" + +/*! PS3 specific ELF constants. */ +/*! LV2 OS ABI. */ +#define ELFOSABI_CELL_LV2 0x66 +/*! PRX ELF type. */ +#define ET_PS3PRX 0xFFA4 +/*! PS3 Params. */ +#define PT_PS3_PARAMS 0x60000001 +/*! PS3 PRX. */ +#define PT_PS3_PRX 0x60000002 +/*! PRX Relocations. */ +#define PT_PS3_PRX_RELOC 0x700000A4 + +/*! SELF config. */ +typedef struct _self_config +{ + /*! Add section headers. */ + BOOL add_shdrs; + /*! Compress data. */ + BOOL compress_data; + /*! Skip sections. */ + BOOL skip_sections; + + /*! Key revision. */ + scetool::u16 key_revision; + /*! Auth ID. */ + scetool::u64 auth_id; + /*! Vendor ID. */ + scetool::u32 vendor_id; + /*! SELF type. */ + scetool::u32 self_type; + /*! Application version. */ + scetool::u64 app_version; + /*! Firmware version. */ + scetool::u64 fw_version; + + /*! Control flags. */ + scetool::u8 *ctrl_flags; + /*! Capability flags. */ + scetool::u8 *cap_flags; +#ifdef CONFIG_CUSTOM_INDIV_SEED + /*! Individuals seed. */ + scetool::u8 *indiv_seed; + /*! Individuals seed size. */ + scetool::u32 indiv_seed_size; +#endif + + /*! NPDRM config (used if not NULL). */ + npdrm_config_t *npdrm_config; +} self_config_t; + +/*! Print SELF info. */ +BOOL self_print_info(FILE *fp, sce_buffer_ctxt_t *ctxt); + +/*! Create ELF from SELF. */ +BOOL self_write_to_elf(sce_buffer_ctxt_t *ctxt, const scetool::s8 *elf_out); + +/*! Create SELF from ELF. */ +BOOL self_build_self(sce_buffer_ctxt_t *ctxt, self_config_t *sconf); + +#endif diff --git a/scetool/sha1.c b/scetool/sha1.c new file mode 100644 index 0000000000..aa3b31be39 --- /dev/null +++ b/scetool/sha1.c @@ -0,0 +1,399 @@ +/* + * FIPS-180-1 compliant SHA-1 implementation + * + * Copyright (C) 2006-2010, Brainspark B.V. + * + * This file is part of PolarSSL (http://www.polarssl.org) + * Lead Maintainer: Paul Bakker + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +/* + * The SHA-1 standard was published by NIST in 1993. + * + * http://www.itl.nist.gov/fipspubs/fip180-1.htm + */ + +#include "sha1.h" + +/* + * 32-bit integer manipulation macros (big endian) + */ +#ifndef GET_ULONG_BE +#define GET_ULONG_BE(n,b,i) \ +{ \ + (n) = ( (unsigned long) (b)[(i) ] << 24 ) \ + | ( (unsigned long) (b)[(i) + 1] << 16 ) \ + | ( (unsigned long) (b)[(i) + 2] << 8 ) \ + | ( (unsigned long) (b)[(i) + 3] ); \ +} +#endif + +#ifndef PUT_ULONG_BE +#define PUT_ULONG_BE(n,b,i) \ +{ \ + (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ + (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ + (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ + (b)[(i) + 3] = (unsigned char) ( (n) ); \ +} +#endif + +/* + * SHA-1 context setup + */ +void sha1_starts( sha1_context *ctx ) +{ + ctx->total[0] = 0; + ctx->total[1] = 0; + + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xC3D2E1F0; +} + +static void sha1_process( sha1_context *ctx, const unsigned char data[64] ) +{ + unsigned long temp, W[16], A, B, C, D, E; + + GET_ULONG_BE( W[ 0], data, 0 ); + GET_ULONG_BE( W[ 1], data, 4 ); + GET_ULONG_BE( W[ 2], data, 8 ); + GET_ULONG_BE( W[ 3], data, 12 ); + GET_ULONG_BE( W[ 4], data, 16 ); + GET_ULONG_BE( W[ 5], data, 20 ); + GET_ULONG_BE( W[ 6], data, 24 ); + GET_ULONG_BE( W[ 7], data, 28 ); + GET_ULONG_BE( W[ 8], data, 32 ); + GET_ULONG_BE( W[ 9], data, 36 ); + GET_ULONG_BE( W[10], data, 40 ); + GET_ULONG_BE( W[11], data, 44 ); + GET_ULONG_BE( W[12], data, 48 ); + GET_ULONG_BE( W[13], data, 52 ); + GET_ULONG_BE( W[14], data, 56 ); + GET_ULONG_BE( W[15], data, 60 ); + +#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) + +#define R(t) \ +( \ + temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \ + W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \ + ( W[t & 0x0F] = S(temp,1) ) \ +) + +#define P(a,b,c,d,e,x) \ +{ \ + e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ +} + + A = ctx->state[0]; + B = ctx->state[1]; + C = ctx->state[2]; + D = ctx->state[3]; + E = ctx->state[4]; + +#define F(x,y,z) (z ^ (x & (y ^ z))) +#define K 0x5A827999 + + P( A, B, C, D, E, W[0] ); + P( E, A, B, C, D, W[1] ); + P( D, E, A, B, C, W[2] ); + P( C, D, E, A, B, W[3] ); + P( B, C, D, E, A, W[4] ); + P( A, B, C, D, E, W[5] ); + P( E, A, B, C, D, W[6] ); + P( D, E, A, B, C, W[7] ); + P( C, D, E, A, B, W[8] ); + P( B, C, D, E, A, W[9] ); + P( A, B, C, D, E, W[10] ); + P( E, A, B, C, D, W[11] ); + P( D, E, A, B, C, W[12] ); + P( C, D, E, A, B, W[13] ); + P( B, C, D, E, A, W[14] ); + P( A, B, C, D, E, W[15] ); + P( E, A, B, C, D, R(16) ); + P( D, E, A, B, C, R(17) ); + P( C, D, E, A, B, R(18) ); + P( B, C, D, E, A, R(19) ); + +#undef K +#undef F + +#define F(x,y,z) (x ^ y ^ z) +#define K 0x6ED9EBA1 + + P( A, B, C, D, E, R(20) ); + P( E, A, B, C, D, R(21) ); + P( D, E, A, B, C, R(22) ); + P( C, D, E, A, B, R(23) ); + P( B, C, D, E, A, R(24) ); + P( A, B, C, D, E, R(25) ); + P( E, A, B, C, D, R(26) ); + P( D, E, A, B, C, R(27) ); + P( C, D, E, A, B, R(28) ); + P( B, C, D, E, A, R(29) ); + P( A, B, C, D, E, R(30) ); + P( E, A, B, C, D, R(31) ); + P( D, E, A, B, C, R(32) ); + P( C, D, E, A, B, R(33) ); + P( B, C, D, E, A, R(34) ); + P( A, B, C, D, E, R(35) ); + P( E, A, B, C, D, R(36) ); + P( D, E, A, B, C, R(37) ); + P( C, D, E, A, B, R(38) ); + P( B, C, D, E, A, R(39) ); + +#undef K +#undef F + +#define F(x,y,z) ((x & y) | (z & (x | y))) +#define K 0x8F1BBCDC + + P( A, B, C, D, E, R(40) ); + P( E, A, B, C, D, R(41) ); + P( D, E, A, B, C, R(42) ); + P( C, D, E, A, B, R(43) ); + P( B, C, D, E, A, R(44) ); + P( A, B, C, D, E, R(45) ); + P( E, A, B, C, D, R(46) ); + P( D, E, A, B, C, R(47) ); + P( C, D, E, A, B, R(48) ); + P( B, C, D, E, A, R(49) ); + P( A, B, C, D, E, R(50) ); + P( E, A, B, C, D, R(51) ); + P( D, E, A, B, C, R(52) ); + P( C, D, E, A, B, R(53) ); + P( B, C, D, E, A, R(54) ); + P( A, B, C, D, E, R(55) ); + P( E, A, B, C, D, R(56) ); + P( D, E, A, B, C, R(57) ); + P( C, D, E, A, B, R(58) ); + P( B, C, D, E, A, R(59) ); + +#undef K +#undef F + +#define F(x,y,z) (x ^ y ^ z) +#define K 0xCA62C1D6 + + P( A, B, C, D, E, R(60) ); + P( E, A, B, C, D, R(61) ); + P( D, E, A, B, C, R(62) ); + P( C, D, E, A, B, R(63) ); + P( B, C, D, E, A, R(64) ); + P( A, B, C, D, E, R(65) ); + P( E, A, B, C, D, R(66) ); + P( D, E, A, B, C, R(67) ); + P( C, D, E, A, B, R(68) ); + P( B, C, D, E, A, R(69) ); + P( A, B, C, D, E, R(70) ); + P( E, A, B, C, D, R(71) ); + P( D, E, A, B, C, R(72) ); + P( C, D, E, A, B, R(73) ); + P( B, C, D, E, A, R(74) ); + P( A, B, C, D, E, R(75) ); + P( E, A, B, C, D, R(76) ); + P( D, E, A, B, C, R(77) ); + P( C, D, E, A, B, R(78) ); + P( B, C, D, E, A, R(79) ); + +#undef K +#undef F + + ctx->state[0] += A; + ctx->state[1] += B; + ctx->state[2] += C; + ctx->state[3] += D; + ctx->state[4] += E; +} + +/* + * SHA-1 process buffer + */ +void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen ) +{ + size_t fill; + unsigned long left; + + if( ilen <= 0 ) + return; + + left = ctx->total[0] & 0x3F; + fill = 64 - left; + + ctx->total[0] += (unsigned long) ilen; + ctx->total[0] &= 0xFFFFFFFF; + + if( ctx->total[0] < (unsigned long) ilen ) + ctx->total[1]++; + + if( left && ilen >= fill ) + { + memcpy( (void *) (ctx->buffer + left), + (void *) input, fill ); + sha1_process( ctx, ctx->buffer ); + input += fill; + ilen -= fill; + left = 0; + } + + while( ilen >= 64 ) + { + sha1_process( ctx, input ); + input += 64; + ilen -= 64; + } + + if( ilen > 0 ) + { + memcpy( (void *) (ctx->buffer + left), + (void *) input, ilen ); + } +} + +static const unsigned char sha1_padding[64] = +{ + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* + * SHA-1 final digest + */ +void sha1_finish( sha1_context *ctx, unsigned char output[20] ) +{ + unsigned long last, padn; + unsigned long high, low; + unsigned char msglen[8]; + + high = ( ctx->total[0] >> 29 ) + | ( ctx->total[1] << 3 ); + low = ( ctx->total[0] << 3 ); + + PUT_ULONG_BE( high, msglen, 0 ); + PUT_ULONG_BE( low, msglen, 4 ); + + last = ctx->total[0] & 0x3F; + padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); + + sha1_update( ctx, (unsigned char *) sha1_padding, padn ); + sha1_update( ctx, msglen, 8 ); + + PUT_ULONG_BE( ctx->state[0], output, 0 ); + PUT_ULONG_BE( ctx->state[1], output, 4 ); + PUT_ULONG_BE( ctx->state[2], output, 8 ); + PUT_ULONG_BE( ctx->state[3], output, 12 ); + PUT_ULONG_BE( ctx->state[4], output, 16 ); +} + +/* + * output = SHA-1( input buffer ) + */ +void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ) +{ + sha1_context ctx; + + sha1_starts( &ctx ); + sha1_update( &ctx, input, ilen ); + sha1_finish( &ctx, output ); + + memset( &ctx, 0, sizeof( sha1_context ) ); +} + +/* + * SHA-1 HMAC context setup + */ +void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, size_t keylen ) +{ + size_t i; + unsigned char sum[20]; + + if( keylen > 64 ) + { + sha1( key, keylen, sum ); + keylen = 20; + key = sum; + } + + memset( ctx->ipad, 0x36, 64 ); + memset( ctx->opad, 0x5C, 64 ); + + for( i = 0; i < keylen; i++ ) + { + ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] ); + ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] ); + } + + sha1_starts( ctx ); + sha1_update( ctx, ctx->ipad, 64 ); + + memset( sum, 0, sizeof( sum ) ); +} + +/* + * SHA-1 HMAC process buffer + */ +void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, size_t ilen ) +{ + sha1_update( ctx, input, ilen ); +} + +/* + * SHA-1 HMAC final digest + */ +void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] ) +{ + unsigned char tmpbuf[20]; + + sha1_finish( ctx, tmpbuf ); + sha1_starts( ctx ); + sha1_update( ctx, ctx->opad, 64 ); + sha1_update( ctx, tmpbuf, 20 ); + sha1_finish( ctx, output ); + + memset( tmpbuf, 0, sizeof( tmpbuf ) ); +} + +/* + * SHA1 HMAC context reset + */ +void sha1_hmac_reset( sha1_context *ctx ) +{ + sha1_starts( ctx ); + sha1_update( ctx, ctx->ipad, 64 ); +} + +/* + * output = HMAC-SHA-1( hmac key, input buffer ) + */ +void sha1_hmac( const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char output[20] ) +{ + sha1_context ctx; + + sha1_hmac_starts( &ctx, key, keylen ); + sha1_hmac_update( &ctx, input, ilen ); + sha1_hmac_finish( &ctx, output ); + + memset( &ctx, 0, sizeof( sha1_context ) ); +} diff --git a/scetool/sha1.h b/scetool/sha1.h new file mode 100644 index 0000000000..9ec45b200c --- /dev/null +++ b/scetool/sha1.h @@ -0,0 +1,133 @@ +/** + * \file sha1.h + * + * \brief SHA-1 cryptographic hash function + * + * Copyright (C) 2006-2010, Brainspark B.V. + * + * This file is part of PolarSSL (http://www.polarssl.org) + * Lead Maintainer: Paul Bakker + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#ifndef POLARSSL_SHA1_H +#define POLARSSL_SHA1_H + +#include + +/** + * \brief SHA-1 context structure + */ +typedef struct +{ + unsigned long total[2]; /*!< number of bytes processed */ + unsigned long state[5]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ + + unsigned char ipad[64]; /*!< HMAC: inner padding */ + unsigned char opad[64]; /*!< HMAC: outer padding */ +} +sha1_context; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief SHA-1 context setup + * + * \param ctx context to be initialized + */ +void sha1_starts( sha1_context *ctx ); + +/** + * \brief SHA-1 process buffer + * + * \param ctx SHA-1 context + * \param input buffer holding the data + * \param ilen length of the input data + */ +void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen ); + +/** + * \brief SHA-1 final digest + * + * \param ctx SHA-1 context + * \param output SHA-1 checksum result + */ +void sha1_finish( sha1_context *ctx, unsigned char output[20] ); + +/** + * \brief Output = SHA-1( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output SHA-1 checksum result + */ +void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ); + +/** + * \brief SHA-1 HMAC context setup + * + * \param ctx HMAC context to be initialized + * \param key HMAC secret key + * \param keylen length of the HMAC key + */ +void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, size_t keylen ); + +/** + * \brief SHA-1 HMAC process buffer + * + * \param ctx HMAC context + * \param input buffer holding the data + * \param ilen length of the input data + */ +void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, size_t ilen ); + +/** + * \brief SHA-1 HMAC final digest + * + * \param ctx HMAC context + * \param output SHA-1 HMAC checksum result + */ +void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] ); + +/** + * \brief SHA-1 HMAC context reset + * + * \param ctx HMAC context to be reset + */ +void sha1_hmac_reset( sha1_context *ctx ); + +/** + * \brief Output = HMAC-SHA-1( hmac key, input buffer ) + * + * \param key HMAC secret key + * \param keylen length of the HMAC key + * \param input buffer holding the data + * \param ilen length of the input data + * \param output HMAC-SHA-1 result + */ +void sha1_hmac( const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char output[20] ); + +#ifdef __cplusplus +} +#endif + +#endif /* sha1.h */ diff --git a/scetool/spp.h b/scetool/spp.h new file mode 100644 index 0000000000..513b152062 --- /dev/null +++ b/scetool/spp.h @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _SPP_H_ +#define _SPP_H_ + +#include "types.h" +#include "sce.h" + +/*! SPP entry types. */ +#define SPP_ENTRY_TYPE_1 1 +#define SPP_ENTRY_TYPE_2 2 + +/*! SPP header. */ +typedef struct _spp_header +{ + scetool::u16 unk1; + scetool::u16 unk2; + scetool::u32 spp_size; + scetool::u32 unk3; + scetool::u32 unk4; + scetool::u64 unk5; + scetool::u32 entcnt; + scetool::u32 unk7; +} spp_header_t; + +static inline void _es_spp_header(spp_header_t *h) +{ + h->unk1 = _Es16(h->unk1); + h->unk2 = _Es16(h->unk2); + h->spp_size = _Es32(h->spp_size); + h->unk3 = _Es32(h->unk3); + h->unk4 = _Es32(h->unk4); + h->unk5 = _Es64(h->unk5); + h->entcnt = _Es32(h->entcnt); + h->unk7 = _Es32(h->unk7); +} + +/*! SPP entry header. */ +typedef struct _spp_entry_header +{ + scetool::u32 entry_size; + scetool::u32 type; + scetool::u64 laid; + scetool::u64 paid; + scetool::u8 name[0x20]; +} spp_entry_header_t; + +static inline void _es_spp_entry_header(spp_entry_header_t *h) +{ + h->entry_size = _Es32(h->entry_size); + h->type = _Es32(h->type); + h->laid = _Es64(h->laid); + h->paid = _Es64(h->paid); +} + +/*! Print SPP infos. */ +void spp_print(FILE *fp, sce_buffer_ctxt_t *ctxt); + +#endif diff --git a/scetool/tables.h b/scetool/tables.h new file mode 100644 index 0000000000..3ae352055f --- /dev/null +++ b/scetool/tables.h @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _TABLES_H_ +#define _TABLES_H_ + +#include "types.h" +#include "util.h" + +/*! SELF types. */ +extern id_to_name_t _self_types[]; + +/*! SELF types as parameter. */ +extern id_to_name_t _self_types_params[]; + +/* Control info types. */ +extern id_to_name_t _control_info_types[]; + +/*! Optional header types. */ +extern id_to_name_t _optional_header_types[]; + +/*! NPDRM application types. */ +extern id_to_name_t _np_app_types[]; + +/*! Auth IDs. */ +extern id_to_name_t _auth_ids[]; + +/*! Vendor IDs. */ +extern id_to_name_t _vendor_ids[]; + +/*! ELF machines. */ +extern id_to_name_t _e_machines[]; + +/*! ELF types. */ +extern id_to_name_t _e_types[]; + +/*! Section header types. */ +extern id_to_name_t _sh_types[]; + +/*! Program header types. */ +extern id_to_name_t _ph_types[]; + +/*! Key types. */ +extern id_to_name_t _key_types[]; + +/*! Key revisions. */ +//extern const scetool::s8 *_key_revisions[]; + +/*! SCE header types. */ +extern id_to_name_t _sce_header_types[]; + +#endif diff --git a/scetool/types.h b/scetool/types.h new file mode 100644 index 0000000000..566a612725 --- /dev/null +++ b/scetool/types.h @@ -0,0 +1,65 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +namespace scetool{ + typedef char s8; + typedef unsigned char u8; + typedef short s16; + typedef unsigned short u16; + typedef int s32; + typedef unsigned int u32; + #if defined(_WIN32) && defined(_MSC_VER) + typedef __int64 s64; + typedef unsigned __int64 u64; + #else + typedef long long int scetool::s64; + typedef unsigned long long int scetool::u64; + #endif +} + +#define BOOL int +#define TRUE 1 +#define FALSE 0 + +//Align. +#define ALIGN(x, a) (((x) + (a) - 1) & ~((a) - 1)) + +//Bits <-> bytes conversion. +#define BITS2BYTES(x) ((x) / 8) +#define BYTES2BITS(x) ((x) * 8) + +//Endian swap for scetool::u16. +#define _Es16(val) \ + ((scetool::u16)(((((scetool::u16)val) & 0xff00) >> 8) | \ + ((((scetool::u16)val) & 0x00ff) << 8))) + +//Endian swap for scetool::u32. +#define _Es32(val) \ + ((scetool::u32)(((((scetool::u32)val) & 0xff000000) >> 24) | \ + ((((scetool::u32)val) & 0x00ff0000) >> 8 ) | \ + ((((scetool::u32)val) & 0x0000ff00) << 8 ) | \ + ((((scetool::u32)val) & 0x000000ff) << 24))) + +//Endian swap for scetool::u64. +#define _Es64(val) \ + ((scetool::u64)(((((scetool::u64)val) & 0xff00000000000000ull) >> 56) | \ + ((((scetool::u64)val) & 0x00ff000000000000ull) >> 40) | \ + ((((scetool::u64)val) & 0x0000ff0000000000ull) >> 24) | \ + ((((scetool::u64)val) & 0x000000ff00000000ull) >> 8 ) | \ + ((((scetool::u64)val) & 0x00000000ff000000ull) << 8 ) | \ + ((((scetool::u64)val) & 0x0000000000ff0000ull) << 24) | \ + ((((scetool::u64)val) & 0x000000000000ff00ull) << 40) | \ + ((((scetool::u64)val) & 0x00000000000000ffull) << 56))) + +#ifdef __cplusplus +} +#endif + diff --git a/scetool/util.h b/scetool/util.h new file mode 100644 index 0000000000..15537a0691 --- /dev/null +++ b/scetool/util.h @@ -0,0 +1,60 @@ +/* +* Copyright (c) 2011-2013 by naehrwert +* This file is released under the GPLv2. +*/ + +#ifndef _UTIL_H_ +#define _UTIL_H_ + +#include + +#include "types.h" + +/*! Verbose. */ +extern BOOL _verbose; +#define _LOG_VERBOSE(...) _IF_VERBOSE(printf("[*] " __VA_ARGS__)) +#define _IF_VERBOSE(code) \ + do \ + { \ + if(_verbose == TRUE) \ + { \ + code; \ + } \ + } while(0) + +/*! Raw. */ +extern BOOL _raw; +#define _PRINT_RAW(fp, ...) _IF_RAW(fprintf(fp, __VA_ARGS__)) +#define _IF_RAW(code) \ + do \ + { \ + if(_raw == TRUE) \ + { \ + code; \ + } \ + } while(0) + +/*! ID to name entry. */ +typedef struct _id_to_name +{ + scetool::u64 id; + const scetool::s8 *name; +} id_to_name_t; + +/*! Utility functions. */ +void _hexdump(FILE *fp, const char *name, scetool::u32 offset, scetool::u8 *buf, int len, BOOL print_addr); +void _print_align(FILE *fp, const scetool::s8 *str, scetool::s32 align, scetool::s32 len); +scetool::u8 *_read_buffer(const scetool::s8 *file, scetool::u32 *length); +int _write_buffer(const scetool::s8 *file, scetool::u8 *buffer, scetool::u32 length); +const scetool::s8 *_get_name(id_to_name_t *tab, scetool::u64 id); +scetool::u64 _get_id(id_to_name_t *tab, const scetool::s8 *name); +void _zlib_inflate(scetool::u8 *in, scetool::u64 len_in, scetool::u8 *out, scetool::u64 len_out); +void _zlib_deflate(scetool::u8 *in, scetool::u64 len_in, scetool::u8 *out, scetool::u64 len_out); +scetool::u8 _get_rand_byte(); +void _fill_rand_bytes(scetool::u8 *dst, scetool::u32 len); +void _memcpy_inv(scetool::u8 *dst, scetool::u8 *src, scetool::u32 len); +void *_memdup(void *ptr, scetool::u32 size); +scetool::u64 _x_to_u64(const scetool::s8 *hex); +scetool::u8 *_x_to_u8_buffer(const scetool::s8 *hex); + +#endif diff --git a/scetool/zconf.h b/scetool/zconf.h new file mode 100644 index 0000000000..14260c938e --- /dev/null +++ b/scetool/zconf.h @@ -0,0 +1,428 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2010 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# define uncompress z_uncompress +# define zError z_zError +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# define gzFile z_gzFile +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYs16BIT +# define SYs16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYs16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYs16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef STDC +# include /* for off_t */ +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_* and off_t */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +#endif + +#ifndef SEEK_SET +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if defined(_LARGEFILE64_SOURCE) && _LFs64_LARGEFILE-0 +# define z_off64_t off64_t +#else +# define z_off64_t z_off_t +#endif + +#if defined(__OS400__) +# define NO_vsnprintf +#endif + +#if defined(__MVS__) +# define NO_vsnprintf +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/scetool/zlib.h b/scetool/zlib.h new file mode 100644 index 0000000000..2e12d7fb0a --- /dev/null +++ b/scetool/zlib.h @@ -0,0 +1,1613 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.5, April 19th, 2010 + + Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt + (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.5" +#define ZLIB_VERNUM 0x1250 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 5 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total nb of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total nb of bytes output so far */ + + char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use in the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). Some + output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed code + block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the stream + are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least the + value returned by deflateBound (see below). If deflate does not return + Z_STREAM_END, then it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect the + compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the + exact value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit() does not process any header information -- that is deferred + until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing will + resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all the uncompressed data. (The size + of the uncompressed data may have been saved by the compressor for this + purpose.) The next operation on this stream must be inflateEnd to deallocate + the decompression state. The use of Z_FINISH is never required, but can be + used to inform inflate that a faster approach may be used for the single + inflate() call. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the only effect of the flush parameter in this implementation + is on the return value of inflate(), as noted below, or when it returns early + because Z_BLOCK or Z_TREES is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the adler32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the adler32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained, so applications that need that information should + instead use raw inflate, see inflateInit2() below, or inflateBack() and + perform their own processing of the gzip header and trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. This function must be called + immediately after deflateInit, deflateInit2 or deflateReset, before any call + of deflate. The compressor and decompressor must use exactly the same + dictionary (see inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if the compression method is bsort). deflateSetDictionary does not + perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. The + stream will keep the same compression level and any other attributes that + may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression level is changed, the input available so far is + compressed with the old level (and may be flushed); the new level will take + effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to be + compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if + strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). +*/ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called + immediately after inflateInit2() or inflateReset() and before any call of + inflate() to set the dictionary. The application must insure that the + dictionary that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a full flush point (see above the + description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR + if no more input was provided, Z_DATA_ERROR if no flush point has been + found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the + success case, the application may save the current current value of total_in + which indicates where valid compressed data was found. In the error case, + the application may repeatedly call inflateSync, providing more input each + time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above or -1 << 16 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the paramaters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is more efficient than inflate() for + file i/o applications in that it avoids copying between the output and the + sliding window by simply making the window itself the output buffer. This + function trusts the application to not change the output buffer passed by + the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the normal + behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. +*/ + + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef voidp gzFile; /* opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) Also "a" + can be used instead of "w" to request that the gzip stream that will be + written be appended to the file. "+" will result in an error, since reading + and writing to the same gzip file is not supported. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Two buffers are allocated, either both of the specified size when + writing, or one of the specified size and the other twice that size when + reading. A larger buffer size of, for example, 64K or 128K bytes will + noticeably increase the speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file was not in gzip format, gzread copies the given number of + bytes into the buffer. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream, or failing that, reading the rest + of the input file directly without decompression. The entire input file + will be read if gzread is called until it returns less than the requested + len. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or 0 in case of error. The number of + uncompressed bytes written is limited to 8191, or one less than the buffer + size given to gzbuffer(). The caller should assure that this limit is not + exceeded. If it is exceeded, then gzprintf() will return an error (0) with + nothing written. In this case, there may also be a buffer overflow with + unpredictable consequences, which is possible only if zlib was compiled with + the insecure functions sprintf() or vsprintf() because the secure snprintf() + or vsnprintf() functions were not available. This can be determined using + zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatented gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. This state can change from + false to true while reading the input file if the end of a gzip stream is + reached, but is followed by data that is not another gzip stream. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the for the crc. Pre- and post-conditioning (one's + complement) is performed within this function so it shouldn't be done by the + application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, sizeof(z_stream)) + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFs64_LARGEFILE must also be true + */ +#if defined(_LARGEFILE64_SOURCE) && _LFs64_LARGEFILE-0 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFs64_LARGEFILE-0 +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# ifdef _LARGEFILE64_SOURCE + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +/* hack for buggy compilers */ +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; +#endif + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */