diff options
Diffstat (limited to 'src/core')
47 files changed, 1710 insertions, 1384 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 0fc8bf318..5578fa680 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -41,6 +41,7 @@ set(SRCS hle/service/apt_s.cpp hle/service/apt_u.cpp hle/service/boss_u.cpp + hle/service/cam_u.cpp hle/service/cecd_u.cpp hle/service/cfg/cfg.cpp hle/service/cfg/cfg_i.cpp @@ -53,7 +54,9 @@ set(SRCS hle/service/fs/archive.cpp hle/service/fs/fs_user.cpp hle/service/gsp_gpu.cpp - hle/service/hid_user.cpp + hle/service/hid/hid.cpp + hle/service/hid/hid_user.cpp + hle/service/hid/hid_spvr.cpp hle/service/http_c.cpp hle/service/ir_rst.cpp hle/service/ir_u.cpp @@ -64,6 +67,7 @@ set(SRCS hle/service/nim_aoc.cpp hle/service/nwm_uds.cpp hle/service/pm_app.cpp + hle/service/ptm_play.cpp hle/service/ptm_u.cpp hle/service/ptm_sysm.cpp hle/service/service.cpp @@ -138,6 +142,7 @@ set(HEADERS hle/service/apt_s.h hle/service/apt_u.h hle/service/boss_u.h + hle/service/cam_u.h hle/service/cecd_u.h hle/service/cfg/cfg.h hle/service/cfg/cfg_i.h @@ -150,7 +155,9 @@ set(HEADERS hle/service/fs/archive.h hle/service/fs/fs_user.h hle/service/gsp_gpu.h - hle/service/hid_user.h + hle/service/hid/hid.h + hle/service/hid/hid_spvr.h + hle/service/hid/hid_user.h hle/service/http_c.h hle/service/ir_rst.h hle/service/ir_u.h @@ -161,6 +168,7 @@ set(HEADERS hle/service/nim_aoc.h hle/service/nwm_uds.h hle/service/pm_app.h + hle/service/ptm_play.h hle/service/ptm_u.h hle/service/ptm_sysm.h hle/service/service.h diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp index d0347566c..81427720e 100644 --- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp +++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp @@ -24,37 +24,29 @@ using namespace std; #include "core/hle/hle.h" enum { - COND = (1 << 0), - NON_BRANCH = (1 << 1), - DIRECT_BRANCH = (1 << 2), + COND = (1 << 0), + NON_BRANCH = (1 << 1), + DIRECT_BRANCH = (1 << 2), INDIRECT_BRANCH = (1 << 3), - CALL = (1 << 4), - RET = (1 << 5), - END_OF_PAGE = (1 << 6), - THUMB = (1 << 7) + CALL = (1 << 4), + RET = (1 << 5), + END_OF_PAGE = (1 << 6), + THUMB = (1 << 7) }; -#define USER_MODE_OPT 1 -#define HYBRID_MODE 0 // Enable for JIT mode - -#define THRESHOLD 1000 -#define DURATION 500 - -#define CHECK_RS if(RS == 15) rs += 8 -#define CHECK_RM if(RM == 15) rm += 8 - #undef BITS +#undef BIT #define BITS(s, a, b) ((s << ((sizeof(s) * 8 - 1) - b)) >> (sizeof(s) * 8 - b + a - 1)) #define BIT(s, n) ((s >> (n)) & 1) #define RM BITS(sht_oper, 0, 3) #define RS BITS(sht_oper, 8, 11) -#define glue(x, y) x ## y -#define DPO(s) glue(DataProcessingOperands, s) -#define ROTATE_RIGHT(n, i, l) ((n << (l - i)) | (n >> i)) -#define ROTATE_LEFT(n, i, l) ((n >> (l - i)) | (n << i)) -#define ROTATE_RIGHT_32(n, i) ROTATE_RIGHT(n, i, 32) -#define ROTATE_LEFT_32(n, i) ROTATE_LEFT(n, i, 32) +#define glue(x, y) x ## y +#define DPO(s) glue(DataProcessingOperands, s) +#define ROTATE_RIGHT(n, i, l) ((n << (l - i)) | (n >> i)) +#define ROTATE_LEFT(n, i, l) ((n >> (l - i)) | (n << i)) +#define ROTATE_RIGHT_32(n, i) ROTATE_RIGHT(n, i, 32) +#define ROTATE_LEFT_32(n, i) ROTATE_LEFT(n, i, 32) #define rotr(x,n) ( (x >> n) | ((x & ((1 << (n + 1)) - 1)) << (32 - n)) ) @@ -410,10 +402,21 @@ void LnSWoUB(ScaledRegisterPreIndexed)(arm_processor *cpu, unsigned int inst, un } break; case 2: - DEBUG_MSG; + if (shift_imm == 0) { // ASR #32 + if (BIT(rm, 31) == 1) + index = 0xFFFFFFFF; + else + index = 0; + } else { + index = static_cast<int>(rm) >> shift_imm; + } break; case 3: - DEBUG_MSG; + if (shift_imm == 0) { + index = (cpu->CFlag << 31) | (rm >> 1); + } else { + index = ROTATE_RIGHT_32(rm, shift_imm); + } break; } @@ -449,10 +452,21 @@ void LnSWoUB(ScaledRegisterPostIndexed)(arm_processor *cpu, unsigned int inst, u } break; case 2: - DEBUG_MSG; + if (shift_imm == 0) { // ASR #32 + if (BIT(rm, 31) == 1) + index = 0xFFFFFFFF; + else + index = 0; + } else { + index = static_cast<int>(rm) >> shift_imm; + } break; case 3: - DEBUG_MSG; + if (shift_imm == 0) { + index = (cpu->CFlag << 31) | (rm >> 1); + } else { + index = ROTATE_RIGHT_32(rm, shift_imm); + } break; } @@ -654,8 +668,8 @@ void LnSWoUB(ScaledRegisterOffset)(arm_processor *cpu, unsigned int inst, unsign } break; case 2: - if (shift_imm == 0){ // ASR #32 - if (rm >> 31) + if (shift_imm == 0) { // ASR #32 + if (BIT(rm, 31) == 1) index = 0xFFFFFFFF; else index = 0; @@ -664,7 +678,11 @@ void LnSWoUB(ScaledRegisterOffset)(arm_processor *cpu, unsigned int inst, unsign } break; case 3: - DEBUG_MSG; + if (shift_imm == 0) { + index = (cpu->CFlag << 31) | (rm >> 1); + } else { + index = ROTATE_RIGHT_32(rm, shift_imm); + } break; } @@ -676,9 +694,6 @@ void LnSWoUB(ScaledRegisterOffset)(arm_processor *cpu, unsigned int inst, unsign virt_addr = addr; } -#define ISNEG(n) (n < 0) -#define ISPOS(n) (n >= 0) - typedef struct _arm_inst { unsigned int idx; unsigned int cond; @@ -1298,15 +1313,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(adc)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(adc_inst)); adc_inst *inst_cream = (adc_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1321,15 +1336,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(add)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(add_inst)); add_inst *inst_cream = (add_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1344,15 +1359,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(and)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(and_inst)); and_inst *inst_cream = (and_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1369,9 +1384,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(bbl)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(bbl_inst)); bbl_inst *inst_cream = (bbl_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = DIRECT_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = DIRECT_BRANCH; if (BIT(inst, 24)) inst_base->br = CALL; @@ -1388,15 +1403,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(bic)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(bic_inst)); bic_inst *inst_cream = (bic_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1412,9 +1427,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(blx)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(blx_inst)); blx_inst *inst_cream = (blx_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = INDIRECT_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = INDIRECT_BRANCH; inst_cream->inst = inst; if (BITS(inst, 20, 27) == 0x12 && BITS(inst, 4, 7) == 0x3) { @@ -1446,17 +1461,18 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(bxj)(unsigned int inst, int index) ARM_INST_PTR INTERPRETER_TRANSLATE(cdp)(unsigned int inst, int index){ arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(cdp_inst)); cdp_inst *inst_cream = (cdp_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->CRm = BITS(inst, 0, 3); - inst_cream->CRd = BITS(inst, 12, 15); - inst_cream->CRn = BITS(inst, 16, 19); + inst_cream->CRm = BITS(inst, 0, 3); + inst_cream->CRd = BITS(inst, 12, 15); + inst_cream->CRn = BITS(inst, 16, 19); inst_cream->cp_num = BITS(inst, 8, 11); - inst_cream->opcode_2 = BITS(inst, 5, 7); - inst_cream->opcode_1 = BITS(inst, 20, 23); + inst_cream->opcode_2 = BITS(inst, 5, 7); + inst_cream->opcode_1 = BITS(inst, 20, 23); inst_cream->inst = inst; LOG_TRACE(Core_ARM11, "inst %x index %x", inst, index); @@ -1465,9 +1481,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(cdp)(unsigned int inst, int index){ ARM_INST_PTR INTERPRETER_TRANSLATE(clrex)(unsigned int inst, int index) { arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(clrex_inst)); - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; return inst_base; } @@ -1476,13 +1492,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(clz)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(clz_inst)); clz_inst *inst_cream = (clz_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->Rm = BITS(inst, 0, 3); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->Rm = BITS(inst, 0, 3); + inst_cream->Rd = BITS(inst, 12, 15); if (CHECK_RM) inst_base->load_r15 = 1; @@ -1493,15 +1509,14 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(cmn)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(cmn_inst)); cmn_inst *inst_cream = (cmn_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - //inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - //inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->Rn = BITS(inst, 16, 19); + if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1513,13 +1528,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(cmp)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(cmp_inst)); cmp_inst *inst_cream = (cmp_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->I = BIT(inst, 25); + inst_cream->Rn = BITS(inst, 16, 19); if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1531,16 +1546,16 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(cps)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(cps_inst)); cps_inst *inst_cream = (cps_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->imod0 = BIT(inst, 18); inst_cream->imod1 = BIT(inst, 19); inst_cream->mmod = BIT(inst, 17); - inst_cream->A = BIT(inst, 8); - inst_cream->I = BIT(inst, 7); - inst_cream->F = BIT(inst, 6); + inst_cream->A = BIT(inst, 8); + inst_cream->I = BIT(inst, 7); + inst_cream->F = BIT(inst, 6); inst_cream->mode = BITS(inst, 0, 4); return inst_base; @@ -1550,13 +1565,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(cpy)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mov_inst)); mov_inst *inst_cream = (mov_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); @@ -1570,15 +1585,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(eor)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(eor_inst)); eor_inst *inst_cream = (eor_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); if (CHECK_RN) inst_base->load_r15 = 1; inst_cream->shifter_operand = BITS(inst, 0, 11); @@ -1591,9 +1606,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(eor)(unsigned int inst, int index) ARM_INST_PTR INTERPRETER_TRANSLATE(ldc)(unsigned int inst, int index) { arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(ldc_inst)); - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; return inst_base; } @@ -1603,8 +1618,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldm)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -1619,9 +1634,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(sxth)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(sxtb_inst)); sxtb_inst *inst_cream = (sxtb_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rd = BITS(inst, 12, 15); @@ -1637,9 +1652,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(ldst_inst)); ldst_inst *inst_cream = (ldst_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->inst = inst; @@ -1656,9 +1671,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldrcond)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(ldst_inst)); ldst_inst *inst_cream = (ldst_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->inst = inst; @@ -1675,9 +1690,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(uxth)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(uxth_inst)); uxth_inst *inst_cream = (uxth_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rd = BITS(inst, 12, 15); @@ -1693,9 +1708,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(uxtah)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(uxtah_inst)); uxtah_inst *inst_cream = (uxtah_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rn = BITS(inst, 16, 19); @@ -1713,8 +1728,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldrb)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -1753,8 +1768,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldrd)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -1793,8 +1808,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldrh)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -1810,8 +1825,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldrsb)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -1827,8 +1842,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ldrsh)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -1870,9 +1885,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mcr)(unsigned int inst, int index) { arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mcr_inst)); mcr_inst *inst_cream = (mcr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->crn = BITS(inst, 16, 19); inst_cream->crm = BITS(inst, 0, 3); @@ -1889,16 +1904,16 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mla)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mla_inst)); mla_inst *inst_cream = (mla_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 12, 15); - inst_cream->Rd = BITS(inst, 16, 19); - inst_cream->Rs = BITS(inst, 8, 11); - inst_cream->Rm = BITS(inst, 0, 3); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 12, 15); + inst_cream->Rd = BITS(inst, 16, 19); + inst_cream->Rs = BITS(inst, 8, 11); + inst_cream->Rm = BITS(inst, 0, 3); if (CHECK_RM || CHECK_RN || CHECK_RS) inst_base->load_r15 = 1; @@ -1910,13 +1925,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mov)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mov_inst)); mov_inst *inst_cream = (mov_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); @@ -1929,9 +1944,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mrc)(unsigned int inst, int index) { arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mrc_inst)); mrc_inst *inst_cream = (mrc_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->crn = BITS(inst, 16, 19); inst_cream->crm = BITS(inst, 0, 3); @@ -1948,12 +1963,12 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mrs)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mrs_inst)); mrs_inst *inst_cream = (mrs_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; - inst_cream->Rd = BITS(inst, 12, 15); - inst_cream->R = BIT(inst, 22); + inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->R = BIT(inst, 22); return inst_base; } @@ -1962,9 +1977,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(msr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(msr_inst)); msr_inst *inst_cream = (msr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->field_mask = BITS(inst, 16, 19); inst_cream->R = BIT(inst, 22); @@ -1977,15 +1992,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mul)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mul_inst)); mul_inst *inst_cream = (mul_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->S = BIT(inst, 20); - inst_cream->Rm = BITS(inst, 0, 3); - inst_cream->Rs = BITS(inst, 8, 11); - inst_cream->Rd = BITS(inst, 16, 19); + inst_cream->S = BIT(inst, 20); + inst_cream->Rm = BITS(inst, 0, 3); + inst_cream->Rs = BITS(inst, 8, 11); + inst_cream->Rd = BITS(inst, 16, 19); if (CHECK_RM || CHECK_RS) inst_base->load_r15 = 1; @@ -1996,13 +2011,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(mvn)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(mvn_inst)); mvn_inst *inst_cream = (mvn_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); @@ -2017,15 +2032,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(orr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(orr_inst)); orr_inst *inst_cream = (orr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rd = BITS(inst, 12, 15); - inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->Rn = BITS(inst, 16, 19); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); @@ -2064,9 +2079,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(pld)(unsigned int inst, int index) { arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(pld_inst)); - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; return inst_base; @@ -2173,15 +2188,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(rsb)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(rsb_inst)); rsb_inst *inst_cream = (rsb_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); if (CHECK_RN) @@ -2197,15 +2212,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(rsc)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(rsc_inst)); rsc_inst *inst_cream = (rsc_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); if (CHECK_RN) @@ -2260,15 +2275,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(sbc)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(sbc_inst)); sbc_inst *inst_cream = (sbc_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); if (CHECK_RN) @@ -2344,15 +2359,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(smla)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(smla_inst)); smla_inst *inst_cream = (smla_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->x = BIT(inst, 5); - inst_cream->y = BIT(inst, 6); - inst_cream->Rm = BITS(inst, 0, 3); - inst_cream->Rs = BITS(inst, 8, 11); + inst_cream->x = BIT(inst, 5); + inst_cream->y = BIT(inst, 6); + inst_cream->Rm = BITS(inst, 0, 3); + inst_cream->Rs = BITS(inst, 8, 11); inst_cream->Rd = BITS(inst, 16, 19); inst_cream->Rn = BITS(inst, 12, 15); @@ -2397,14 +2412,14 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(smlal)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(umlal_inst)); umlal_inst *inst_cream = (umlal_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->S = BIT(inst, 20); - inst_cream->Rm = BITS(inst, 0, 3); - inst_cream->Rs = BITS(inst, 8, 11); + inst_cream->S = BIT(inst, 20); + inst_cream->Rm = BITS(inst, 0, 3); + inst_cream->Rs = BITS(inst, 8, 11); inst_cream->RdHi = BITS(inst, 16, 19); inst_cream->RdLo = BITS(inst, 12, 15); @@ -2511,9 +2526,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(smul)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(smul_inst)); smul_inst *inst_cream = (smul_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rd = BITS(inst, 16, 19); @@ -2533,14 +2548,14 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(smull)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(umull_inst)); umull_inst *inst_cream = (umull_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->S = BIT(inst, 20); - inst_cream->Rm = BITS(inst, 0, 3); - inst_cream->Rs = BITS(inst, 8, 11); + inst_cream->S = BIT(inst, 20); + inst_cream->Rm = BITS(inst, 0, 3); + inst_cream->Rs = BITS(inst, 8, 11); inst_cream->RdHi = BITS(inst, 16, 19); inst_cream->RdLo = BITS(inst, 12, 15); @@ -2554,14 +2569,14 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(smulw)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(smlad_inst)); smlad_inst *inst_cream = (smlad_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->m = BIT(inst, 6); - inst_cream->Rm = BITS(inst, 8, 11); - inst_cream->Rn = BITS(inst, 0, 3); + inst_cream->m = BIT(inst, 6); + inst_cream->Rm = BITS(inst, 8, 11); + inst_cream->Rn = BITS(inst, 0, 3); inst_cream->Rd = BITS(inst, 16, 19); if (CHECK_RM || CHECK_RN) @@ -2607,9 +2622,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(ssat16)(unsigned int inst, int index) ARM_INST_PTR INTERPRETER_TRANSLATE(stc)(unsigned int inst, int index) { arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(stc_inst)); - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; return inst_base; } @@ -2619,8 +2634,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(stm)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -2631,9 +2646,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(sxtb)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(sxtb_inst)); sxtb_inst *inst_cream = (sxtb_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rd = BITS(inst, 12, 15); @@ -2650,8 +2665,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(str)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -2666,9 +2681,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(uxtb)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(uxth_inst)); uxth_inst *inst_cream = (uxth_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rd = BITS(inst, 12, 15); @@ -2684,9 +2699,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(uxtab)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(uxtab_inst)); uxtab_inst *inst_cream = (uxtab_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->Rd = BITS(inst, 12, 15); @@ -2702,8 +2717,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(strb)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -2742,8 +2757,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(strd)(unsigned int inst, int index){ ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -2786,8 +2801,8 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(strh)(unsigned int inst, int index) ldst_inst *inst_cream = (ldst_inst *)inst_base->component; inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_cream->inst = inst; inst_cream->get_addr = get_calc_addr_op(inst); @@ -2830,15 +2845,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(sub)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(sub_inst)); sub_inst *inst_cream = (sub_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->I = BIT(inst, 25); - inst_cream->S = BIT(inst, 20); - inst_cream->Rn = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->I = BIT(inst, 25); + inst_cream->S = BIT(inst, 20); + inst_cream->Rn = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); inst_cream->shifter_operand = BITS(inst, 0, 11); inst_cream->shtop_func = get_shtop(inst); if (inst_cream->Rd == 15) { @@ -3099,9 +3114,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(umlal)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(umlal_inst)); umlal_inst *inst_cream = (umlal_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->S = BIT(inst, 20); @@ -3141,10 +3156,10 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(b_2_thumb)(unsigned int tinst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(b_2_thumb)); b_2_thumb *inst_cream = (b_2_thumb *)inst_base->component; - inst_cream->imm = ((tinst & 0x3FF) << 1) | ((tinst & (1 << 10)) ? 0xFFFFF800 : 0); + inst_cream->imm = ((tinst & 0x3FF) << 1) | ((tinst & (1 << 10)) ? 0xFFFFF800 : 0); - inst_base->idx = index; - inst_base->br = DIRECT_BRANCH; + inst_base->idx = index; + inst_base->br = DIRECT_BRANCH; return inst_base; } @@ -3154,10 +3169,10 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(b_cond_thumb)(unsigned int tinst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(b_cond_thumb)); b_cond_thumb *inst_cream = (b_cond_thumb *)inst_base->component; - inst_cream->imm = (((tinst & 0x7F) << 1) | ((tinst & (1 << 7)) ? 0xFFFFFF00 : 0)); - inst_cream->cond = ((tinst >> 8) & 0xf); - inst_base->idx = index; - inst_base->br = DIRECT_BRANCH; + inst_cream->imm = (((tinst & 0x7F) << 1) | ((tinst & (1 << 7)) ? 0xFFFFFF00 : 0)); + inst_cream->cond = ((tinst >> 8) & 0xf); + inst_base->idx = index; + inst_base->br = DIRECT_BRANCH; return inst_base; } @@ -3167,10 +3182,10 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(bl_1_thumb)(unsigned int tinst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(bl_1_thumb)); bl_1_thumb *inst_cream = (bl_1_thumb *)inst_base->component; - inst_cream->imm = (((tinst & 0x07FF) << 12) | ((tinst & (1 << 10)) ? 0xFF800000 : 0)); + inst_cream->imm = (((tinst & 0x07FF) << 12) | ((tinst & (1 << 10)) ? 0xFF800000 : 0)); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->idx = index; + inst_base->br = NON_BRANCH; return inst_base; } ARM_INST_PTR INTERPRETER_TRANSLATE(bl_2_thumb)(unsigned int tinst, int index) @@ -3178,10 +3193,10 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(bl_2_thumb)(unsigned int tinst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(bl_2_thumb)); bl_2_thumb *inst_cream = (bl_2_thumb *)inst_base->component; - inst_cream->imm = (tinst & 0x07FF) << 1; + inst_cream->imm = (tinst & 0x07FF) << 1; - inst_base->idx = index; - inst_base->br = DIRECT_BRANCH; + inst_base->idx = index; + inst_base->br = DIRECT_BRANCH; return inst_base; } ARM_INST_PTR INTERPRETER_TRANSLATE(blx_1_thumb)(unsigned int tinst, int index) @@ -3507,7 +3522,6 @@ void insert_bb(unsigned int addr, int start) { CreamCache[addr] = start; } -#define TRANS_THRESHOLD 65000 int find_bb(unsigned int addr, int &start) { int ret = -1; bb_map::const_iterator it = CreamCache.find(addr); @@ -4151,7 +4165,7 @@ unsigned InterpreterMainLoop(ARMul_State* state) { cpu->Reg[14] = (cpu->Reg[15] + GET_INST_SIZE(cpu)); cpu->TFlag = 0x1; int signed_int = inst_cream->val.signed_immed_24; - signed_int = (signed_int) & 0x800000 ? (0x3F000000 | signed_int) : signed_int; + signed_int = (signed_int & 0x800000) ? (0x3F000000 | signed_int) : signed_int; signed_int = signed_int << 2; cpu->Reg[15] = cpu->Reg[15] + 8 + signed_int + (BIT(inst, 24) << 1); } diff --git a/src/core/arm/skyeye_common/vfp/vfpdouble.cpp b/src/core/arm/skyeye_common/vfp/vfpdouble.cpp index da7de6e65..15a5d1265 100644 --- a/src/core/arm/skyeye_common/vfp/vfpdouble.cpp +++ b/src/core/arm/skyeye_common/vfp/vfpdouble.cpp @@ -1397,7 +1397,7 @@ u32 vfp_double_cpdo(ARMul_State* state, u32 inst, u32 fpscr) u32 except; char type; - type = fop->flags & OP_SD ? 's' : 'd'; + type = (fop->flags & OP_SD) ? 's' : 'd'; if (op == FOP_EXT) LOG_TRACE(Core_ARM11, "VFP: itr%d (%c%u) = op[%u] (d%u)\n", vecitr >> FPSCR_LENGTH_BIT, diff --git a/src/core/arm/skyeye_common/vfp/vfpinstr.cpp b/src/core/arm/skyeye_common/vfp/vfpinstr.cpp index cf459222c..1bdbfec8e 100644 --- a/src/core/arm/skyeye_common/vfp/vfpinstr.cpp +++ b/src/core/arm/skyeye_common/vfp/vfpinstr.cpp @@ -24,9 +24,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmla)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmla_inst)); vmla_inst *inst_cream = (vmla_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -141,9 +141,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmls)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmls_inst)); vmls_inst *inst_cream = (vmls_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -259,9 +259,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vnmla)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vnmla_inst)); vnmla_inst *inst_cream = (vnmla_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -379,9 +379,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vnmls)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vnmls_inst)); vnmls_inst *inst_cream = (vnmls_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -498,9 +498,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vnmul)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vnmul_inst)); vnmul_inst *inst_cream = (vnmul_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -607,9 +607,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmul)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmul_inst)); vmul_inst *inst_cream = (vmul_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -728,9 +728,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vadd)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vadd_inst)); vadd_inst *inst_cream = (vadd_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -845,9 +845,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vsub)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vsub_inst)); vsub_inst *inst_cream = (vsub_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -960,9 +960,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vdiv)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vdiv_inst)); vdiv_inst *inst_cream = (vdiv_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1079,13 +1079,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovi)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovi_inst)); vmovi_inst *inst_cream = (vmovi_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->single = BIT(inst, 8) == 0; - inst_cream->d = (inst_cream->single ? BITS(inst,12,15)<<1 | BIT(inst,22) : BITS(inst,12,15) | BIT(inst,22)<<4); + inst_cream->single = BIT(inst, 8) == 0; + inst_cream->d = (inst_cream->single ? BITS(inst,12,15)<<1 | BIT(inst,22) : BITS(inst,12,15) | BIT(inst,22)<<4); unsigned int imm8 = BITS(inst, 16, 19) << 4 | BITS(inst, 0, 3); if (inst_cream->single) inst_cream->imm = BIT(imm8, 7)<<31 | (BIT(imm8, 6)==0)<<30 | (BIT(imm8, 6) ? 0x1f : 0)<<25 | BITS(imm8, 0, 5)<<19; @@ -1168,14 +1168,14 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovr_inst)); vmovr_inst *inst_cream = (vmovr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->single = BIT(inst, 8) == 0; - inst_cream->d = (inst_cream->single ? BITS(inst,12,15)<<1 | BIT(inst,22) : BITS(inst,12,15) | BIT(inst,22)<<4); - inst_cream->m = (inst_cream->single ? BITS(inst, 0, 3)<<1 | BIT(inst, 5) : BITS(inst, 0, 3) | BIT(inst, 5)<<4); + inst_cream->single = BIT(inst, 8) == 0; + inst_cream->d = (inst_cream->single ? BITS(inst,12,15)<<1 | BIT(inst,22) : BITS(inst,12,15) | BIT(inst,22)<<4); + inst_cream->m = (inst_cream->single ? BITS(inst, 0, 3)<<1 | BIT(inst, 5) : BITS(inst, 0, 3) | BIT(inst, 5)<<4); return inst_base; } #endif @@ -1245,9 +1245,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vabs)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vabs_inst)); vabs_inst *inst_cream = (vabs_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1347,9 +1347,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vneg)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vneg_inst)); vneg_inst *inst_cream = (vneg_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1450,9 +1450,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vsqrt)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vsqrt_inst)); vsqrt_inst *inst_cream = (vsqrt_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1541,9 +1541,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vcmp)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vcmp_inst)); vcmp_inst *inst_cream = (vcmp_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1659,9 +1659,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vcmp2)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vcmp2_inst)); vcmp2_inst *inst_cream = (vcmp2_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1777,9 +1777,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vcvtbds)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vcvtbds_inst)); vcvtbds_inst *inst_cream = (vcvtbds_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -1941,9 +1941,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vcvtbfi)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vcvtbfi_inst)); vcvtbfi_inst *inst_cream = (vcvtbfi_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->dp_operation = BIT(inst, 8); @@ -2106,14 +2106,14 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovbrs)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovbrs_inst)); vmovbrs_inst *inst_cream = (vmovbrs_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->to_arm = BIT(inst, 20) == 1; - inst_cream->t = BITS(inst, 12, 15); - inst_cream->n = BIT(inst, 7) | BITS(inst, 16, 19)<<1; + inst_cream->to_arm = BIT(inst, 20) == 1; + inst_cream->t = BITS(inst, 12, 15); + inst_cream->n = BIT(inst, 7) | BITS(inst, 16, 19)<<1; return inst_base; } @@ -2180,13 +2180,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmsr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmsr_inst)); vmsr_inst *inst_cream = (vmsr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->reg = BITS(inst, 16, 19); - inst_cream->Rd = BITS(inst, 12, 15); + inst_cream->reg = BITS(inst, 16, 19); + inst_cream->Rd = BITS(inst, 12, 15); return inst_base; } @@ -2271,9 +2271,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovbrc)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovbrc_inst)); vmovbrc_inst *inst_cream = (vmovbrc_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->d = BITS(inst, 16, 19)|BIT(inst, 7)<<4; @@ -2338,13 +2338,13 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmrs)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmrs_inst)); vmrs_inst *inst_cream = (vmrs_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->reg = BITS(inst, 16, 19); - inst_cream->Rt = BITS(inst, 12, 15); + inst_cream->reg = BITS(inst, 16, 19); + inst_cream->Rt = BITS(inst, 12, 15); return inst_base; } @@ -2480,9 +2480,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovbcr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovbcr_inst)); vmovbcr_inst *inst_cream = (vmovbcr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->d = BITS(inst, 16, 19)|BIT(inst, 7)<<4; @@ -2554,15 +2554,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovbrrss)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovbrrss_inst)); vmovbrrss_inst *inst_cream = (vmovbrrss_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->to_arm = BIT(inst, 20) == 1; - inst_cream->t = BITS(inst, 12, 15); - inst_cream->t2 = BITS(inst, 16, 19); - inst_cream->m = BITS(inst, 0, 3)<<1|BIT(inst, 5); + inst_cream->to_arm = BIT(inst, 20) == 1; + inst_cream->t = BITS(inst, 12, 15); + inst_cream->t2 = BITS(inst, 16, 19); + inst_cream->m = BITS(inst, 0, 3)<<1|BIT(inst, 5); return inst_base; } @@ -2636,15 +2636,15 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vmovbrrd)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vmovbrrd_inst)); vmovbrrd_inst *inst_cream = (vmovbrrd_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; - inst_cream->to_arm = BIT(inst, 20) == 1; - inst_cream->t = BITS(inst, 12, 15); - inst_cream->t2 = BITS(inst, 16, 19); - inst_cream->m = BIT(inst, 5)<<4 | BITS(inst, 0, 3); + inst_cream->to_arm = BIT(inst, 20) == 1; + inst_cream->t = BITS(inst, 12, 15); + inst_cream->t2 = BITS(inst, 16, 19); + inst_cream->m = BIT(inst, 5)<<4 | BITS(inst, 0, 3); return inst_base; } @@ -2722,16 +2722,16 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vstr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vstr_inst)); vstr_inst *inst_cream = (vstr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->single = BIT(inst, 8) == 0; - inst_cream->add = BIT(inst, 23); + inst_cream->add = BIT(inst, 23); inst_cream->imm32 = BITS(inst, 0,7) << 2; inst_cream->d = (inst_cream->single ? BITS(inst, 12, 15)<<1|BIT(inst, 22) : BITS(inst, 12, 15)|BIT(inst, 22)<<4); - inst_cream->n = BITS(inst, 16, 19); + inst_cream->n = BITS(inst, 16, 19); return inst_base; } @@ -2782,10 +2782,10 @@ int DYNCOM_TAG(vstr)(cpu_t *cpu, addr_t pc, uint32_t instr, tag_t *tag, addr_t * #ifdef VFP_DYNCOM_TRANS int DYNCOM_TRANS(vstr)(cpu_t *cpu, uint32_t instr, BasicBlock *bb, addr_t pc){ int single = BIT(8) == 0; - int add = BIT(23); + int add = BIT(23); int imm32 = BITS(0,7) << 2; int d = (single ? BITS(12, 15)<<1|BIT(22) : BITS(12, 15)|(BIT(22)<<4)); - int n = BITS(16, 19); + int n = BITS(16, 19); Value* base = (n == 15) ? ADD(AND(R(n), CONST(0xFFFFFFFC)), CONST(8)): R(n); Value* Addr = add ? ADD(base, CONST(imm32)) : SUB(base, CONST(imm32)); @@ -2828,9 +2828,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vpush)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vpush_inst)); vpush_inst *inst_cream = (vpush_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->single = BIT(inst, 8) == 0; @@ -2846,13 +2846,12 @@ VPUSH_INST: { if ((inst_base->cond == 0xe) || CondPassed(cpu, inst_base->cond)) { CHECK_VFP_ENABLED; - int i; vpush_inst *inst_cream = (vpush_inst *)inst_base->component; addr = cpu->Reg[R13] - inst_cream->imm32; - for (i = 0; i < inst_cream->regs; i++) + for (int i = 0; i < inst_cream->regs; i++) { if (inst_cream->single) { @@ -2902,8 +2901,8 @@ int DYNCOM_TRANS(vpush)(cpu_t *cpu, uint32_t instr, BasicBlock *bb, addr_t pc){ //else // bb = arch_check_mm(cpu, bb, Addr, regs * 8, 0, cpu->dyncom_engine->bb_trap); //Value* phys_addr; - int i; - for (i = 0; i < regs; i++) + + for (int i = 0; i < regs; i++) { if (single) { @@ -2952,9 +2951,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vstm)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vstm_inst)); vstm_inst *inst_cream = (vstm_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->single = BIT(inst, 8) == 0; @@ -2974,13 +2973,11 @@ VSTM_INST: /* encoding 1 */ if ((inst_base->cond == 0xe) || CondPassed(cpu, inst_base->cond)) { CHECK_VFP_ENABLED; - int i; - vstm_inst *inst_cream = (vstm_inst *)inst_base->component; addr = (inst_cream->add ? cpu->Reg[inst_cream->n] : cpu->Reg[inst_cream->n] - inst_cream->imm32); - for (i = 0; i < inst_cream->regs; i++) + for (int i = 0; i < inst_cream->regs; i++) { if (inst_cream->single) { @@ -3094,9 +3091,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vpop)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vpop_inst)); vpop_inst *inst_cream = (vpop_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->single = BIT(inst, 8) == 0; @@ -3113,14 +3110,13 @@ VPOP_INST: if ((inst_base->cond == 0xe) || CondPassed(cpu, inst_base->cond)) { CHECK_VFP_ENABLED; - int i; unsigned int value1, value2; vpop_inst *inst_cream = (vpop_inst *)inst_base->component; addr = cpu->Reg[R13]; - for (i = 0; i < inst_cream->regs; i++) + for (int i = 0; i < inst_cream->regs; i++) { if (inst_cream->single) { @@ -3229,16 +3225,16 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vldr)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vldr_inst)); vldr_inst *inst_cream = (vldr_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->single = BIT(inst, 8) == 0; - inst_cream->add = BIT(inst, 23); + inst_cream->add = BIT(inst, 23); inst_cream->imm32 = BITS(inst, 0,7) << 2; inst_cream->d = (inst_cream->single ? BITS(inst, 12, 15)<<1|BIT(inst, 22) : BITS(inst, 12, 15)|BIT(inst, 22)<<4); - inst_cream->n = BITS(inst, 16, 19); + inst_cream->n = BITS(inst, 16, 19); return inst_base; } @@ -3356,9 +3352,9 @@ ARM_INST_PTR INTERPRETER_TRANSLATE(vldm)(unsigned int inst, int index) arm_inst *inst_base = (arm_inst *)AllocBuffer(sizeof(arm_inst) + sizeof(vldm_inst)); vldm_inst *inst_cream = (vldm_inst *)inst_base->component; - inst_base->cond = BITS(inst, 28, 31); - inst_base->idx = index; - inst_base->br = NON_BRANCH; + inst_base->cond = BITS(inst, 28, 31); + inst_base->idx = index; + inst_base->br = NON_BRANCH; inst_base->load_r15 = 0; inst_cream->single = BIT(inst, 8) == 0; @@ -3378,13 +3374,11 @@ VLDM_INST: if ((inst_base->cond == 0xe) || CondPassed(cpu, inst_base->cond)) { CHECK_VFP_ENABLED; - int i; - vldm_inst *inst_cream = (vldm_inst *)inst_base->component; addr = (inst_cream->add ? cpu->Reg[inst_cream->n] : cpu->Reg[inst_cream->n] - inst_cream->imm32); - for (i = 0; i < inst_cream->regs; i++) + for (int i = 0; i < inst_cream->regs; i++) { if (inst_cream->single) { diff --git a/src/core/arm/skyeye_common/vfp/vfpsingle.cpp b/src/core/arm/skyeye_common/vfp/vfpsingle.cpp index 77b528607..b7872bdc4 100644 --- a/src/core/arm/skyeye_common/vfp/vfpsingle.cpp +++ b/src/core/arm/skyeye_common/vfp/vfpsingle.cpp @@ -1290,7 +1290,7 @@ u32 vfp_single_cpdo(ARMul_State* state, u32 inst, u32 fpscr) u32 except; char type; - type = fop->flags & OP_DD ? 'd' : 's'; + type = (fop->flags & OP_DD) ? 'd' : 's'; if (op == FOP_EXT) pr_debug("VFP: itr%d (%c%u) = op[%u] (s%u=%08x)\n", vecitr >> FPSCR_LENGTH_BIT, type, dest, sn, diff --git a/src/core/core_timing.cpp b/src/core/core_timing.cpp index ec9d52a08..3aebd7e9d 100644 --- a/src/core/core_timing.cpp +++ b/src/core/core_timing.cpp @@ -33,7 +33,7 @@ struct EventType const char* name; }; -std::vector<EventType> event_types; +static std::vector<EventType> event_types; struct BaseEvent { @@ -44,30 +44,30 @@ struct BaseEvent typedef LinkedListItem<BaseEvent> Event; -Event* first; -Event* ts_first; -Event* ts_last; +static Event* first; +static Event* ts_first; +static Event* ts_last; // event pools -Event* event_pool = 0; -Event* event_ts_pool = 0; -int allocated_ts_events = 0; +static Event* event_pool = nullptr; +static Event* event_ts_pool = nullptr; +static int allocated_ts_events = 0; // Optimization to skip MoveEvents when possible. -std::atomic<bool> has_ts_events(false); +static std::atomic<bool> has_ts_events(false); int g_slice_length; -s64 global_timer; -s64 idled_cycles; -s64 last_global_time_ticks; -s64 last_global_time_us; +static s64 global_timer; +static s64 idled_cycles; +static s64 last_global_time_ticks; +static s64 last_global_time_us; static std::recursive_mutex external_event_section; // Warning: not included in save state. using AdvanceCallback = void(int cycles_executed); -AdvanceCallback* advance_callback = nullptr; -std::vector<MHzChangeCallback> mhz_change_callbacks; +static AdvanceCallback* advance_callback = nullptr; +static std::vector<MHzChangeCallback> mhz_change_callbacks; void FireMhzChange() { for (auto callback : mhz_change_callbacks) diff --git a/src/core/hle/hle.cpp b/src/core/hle/hle.cpp index 11570c8b4..5a2edeb4a 100644 --- a/src/core/hle/hle.cpp +++ b/src/core/hle/hle.cpp @@ -12,6 +12,7 @@ #include "core/hle/service/service.h" #include "core/hle/service/fs/archive.h" #include "core/hle/service/cfg/cfg.h" +#include "core/hle/service/hid/hid.h" //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -70,6 +71,7 @@ void Init() { Service::Init(); Service::FS::ArchiveInit(); Service::CFG::CFGInit(); + Service::HID::HIDInit(); RegisterAllModules(); @@ -79,6 +81,7 @@ void Init() { } void Shutdown() { + Service::HID::HIDShutdown(); Service::CFG::CFGShutdown(); Service::FS::ArchiveShutdown(); Service::Shutdown(); diff --git a/src/core/hle/kernel/address_arbiter.cpp b/src/core/hle/kernel/address_arbiter.cpp index b7434aaf2..9e855b0bf 100644 --- a/src/core/hle/kernel/address_arbiter.cpp +++ b/src/core/hle/kernel/address_arbiter.cpp @@ -30,7 +30,8 @@ public: /// Arbitrate an address ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s32 value, u64 nanoseconds) { - Object* object = Kernel::g_handle_table.GetGeneric(handle).get(); + AddressArbiter* object = Kernel::g_handle_table.Get<AddressArbiter>(handle).get(); + if (object == nullptr) return InvalidHandle(ErrorModule::Kernel); @@ -40,24 +41,24 @@ ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s3 case ArbitrationType::Signal: // Negative value means resume all threads if (value < 0) { - ArbitrateAllThreads(object, address); + ArbitrateAllThreads(address); } else { // Resume first N threads for(int i = 0; i < value; i++) - ArbitrateHighestPriorityThread(object, address); + ArbitrateHighestPriorityThread(address); } break; // Wait current thread (acquire the arbiter)... case ArbitrationType::WaitIfLessThan: if ((s32)Memory::Read32(address) <= value) { - Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address); + Kernel::WaitCurrentThread_ArbitrateAddress(address); HLE::Reschedule(__func__); } break; case ArbitrationType::WaitIfLessThanWithTimeout: if ((s32)Memory::Read32(address) <= value) { - Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address); + Kernel::WaitCurrentThread_ArbitrateAddress(address); Kernel::WakeThreadAfterDelay(GetCurrentThread(), nanoseconds); HLE::Reschedule(__func__); } @@ -67,7 +68,7 @@ ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s3 s32 memory_value = Memory::Read32(address) - 1; Memory::Write32(address, memory_value); if (memory_value <= value) { - Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address); + Kernel::WaitCurrentThread_ArbitrateAddress(address); HLE::Reschedule(__func__); } break; @@ -77,7 +78,7 @@ ResultCode ArbitrateAddress(Handle handle, ArbitrationType type, u32 address, s3 s32 memory_value = Memory::Read32(address) - 1; Memory::Write32(address, memory_value); if (memory_value <= value) { - Kernel::WaitCurrentThread(WAITTYPE_ARB, object, address); + Kernel::WaitCurrentThread_ArbitrateAddress(address); Kernel::WakeThreadAfterDelay(GetCurrentThread(), nanoseconds); HLE::Reschedule(__func__); } diff --git a/src/core/hle/kernel/event.cpp b/src/core/hle/kernel/event.cpp index 271190dbe..a48125965 100644 --- a/src/core/hle/kernel/event.cpp +++ b/src/core/hle/kernel/event.cpp @@ -14,7 +14,7 @@ namespace Kernel { -class Event : public Object { +class Event : public WaitObject { public: std::string GetTypeName() const override { return "Event"; } std::string GetName() const override { return name; } @@ -25,99 +25,40 @@ public: ResetType intitial_reset_type; ///< ResetType specified at Event initialization ResetType reset_type; ///< Current ResetType - bool locked; ///< Event signal wait - bool permanent_locked; ///< Hack - to set event permanent state (for easy passthrough) - std::vector<Handle> waiting_threads; ///< Threads that are waiting for the event + bool signaled; ///< Whether the event has already been signaled std::string name; ///< Name of event (optional) - ResultVal<bool> WaitSynchronization() override { - bool wait = locked; - if (locked) { - Handle thread = GetCurrentThread()->GetHandle(); - if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) { - waiting_threads.push_back(thread); - } - Kernel::WaitCurrentThread(WAITTYPE_EVENT, this); - } - if (reset_type != RESETTYPE_STICKY && !permanent_locked) { - locked = true; - } - return MakeResult<bool>(wait); + bool ShouldWait() override { + return !signaled; } -}; - -/** - * Hackish function to set an events permanent lock state, used to pass through synch blocks - * @param handle Handle to event to change - * @param permanent_locked Boolean permanent locked value to set event - * @return Result of operation, 0 on success, otherwise error code - */ -ResultCode SetPermanentLock(Handle handle, const bool permanent_locked) { - Event* evt = g_handle_table.Get<Event>(handle).get(); - if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); - - evt->permanent_locked = permanent_locked; - return RESULT_SUCCESS; -} -/** - * Changes whether an event is locked or not - * @param handle Handle to event to change - * @param locked Boolean locked value to set event - * @return Result of operation, 0 on success, otherwise error code - */ -ResultCode SetEventLocked(const Handle handle, const bool locked) { - Event* evt = g_handle_table.Get<Event>(handle).get(); - if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); + void Acquire() override { + _assert_msg_(Kernel, !ShouldWait(), "object unavailable!"); - if (!evt->permanent_locked) { - evt->locked = locked; + // Release the event if it's not sticky... + if (reset_type != RESETTYPE_STICKY) + signaled = false; } - return RESULT_SUCCESS; -} +}; -/** - * Signals an event - * @param handle Handle to event to signal - * @return Result of operation, 0 on success, otherwise error code - */ ResultCode SignalEvent(const Handle handle) { Event* evt = g_handle_table.Get<Event>(handle).get(); - if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); - - // Resume threads waiting for event to signal - bool event_caught = false; - for (size_t i = 0; i < evt->waiting_threads.size(); ++i) { - Thread* thread = Kernel::g_handle_table.Get<Thread>(evt->waiting_threads[i]).get(); - if (thread != nullptr) - thread->ResumeFromWait(); - - // If any thread is signalled awake by this event, assume the event was "caught" and reset - // the event. This will result in the next thread waiting on the event to block. Otherwise, - // the event will not be reset, and the next thread to call WaitSynchronization on it will - // not block. Not sure if this is correct behavior, but it seems to work. - event_caught = true; - } - evt->waiting_threads.clear(); + if (evt == nullptr) + return InvalidHandle(ErrorModule::Kernel); + + evt->signaled = true; + evt->WakeupAllWaitingThreads(); - if (!evt->permanent_locked) { - evt->locked = event_caught; - } return RESULT_SUCCESS; } -/** - * Clears an event - * @param handle Handle to event to clear - * @return Result of operation, 0 on success, otherwise error code - */ ResultCode ClearEvent(Handle handle) { Event* evt = g_handle_table.Get<Event>(handle).get(); - if (evt == nullptr) return InvalidHandle(ErrorModule::Kernel); + if (evt == nullptr) + return InvalidHandle(ErrorModule::Kernel); + + evt->signaled = false; - if (!evt->permanent_locked) { - evt->locked = true; - } return RESULT_SUCCESS; } @@ -134,20 +75,13 @@ Event* CreateEvent(Handle& handle, const ResetType reset_type, const std::string // TOOD(yuriks): Fix error reporting handle = Kernel::g_handle_table.Create(evt).ValueOr(INVALID_HANDLE); - evt->locked = true; - evt->permanent_locked = false; + evt->signaled = false; evt->reset_type = evt->intitial_reset_type = reset_type; evt->name = name; return evt; } -/** - * Creates an event - * @param reset_type ResetType describing how to create event - * @param name Optional name of event - * @return Handle to newly created Event object - */ Handle CreateEvent(const ResetType reset_type, const std::string& name) { Handle handle; Event* evt = CreateEvent(handle, reset_type, name); diff --git a/src/core/hle/kernel/event.h b/src/core/hle/kernel/event.h index da793df1a..c08b12ee1 100644 --- a/src/core/hle/kernel/event.h +++ b/src/core/hle/kernel/event.h @@ -12,28 +12,16 @@ namespace Kernel { /** - * Changes whether an event is locked or not - * @param handle Handle to event to change - * @param locked Boolean locked value to set event - */ -ResultCode SetEventLocked(const Handle handle, const bool locked); - -/** - * Hackish function to set an events permanent lock state, used to pass through synch blocks - * @param handle Handle to event to change - * @param permanent_locked Boolean permanent locked value to set event - */ -ResultCode SetPermanentLock(Handle handle, const bool permanent_locked); - -/** * Signals an event * @param handle Handle to event to signal + * @return Result of operation, 0 on success, otherwise error code */ ResultCode SignalEvent(const Handle handle); /** * Clears an event * @param handle Handle to event to clear + * @return Result of operation, 0 on success, otherwise error code */ ResultCode ClearEvent(Handle handle); diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp index d3684896f..d7fa4dcea 100644 --- a/src/core/hle/kernel/kernel.cpp +++ b/src/core/hle/kernel/kernel.cpp @@ -18,6 +18,41 @@ SharedPtr<Thread> g_main_thread = nullptr; HandleTable g_handle_table; u64 g_program_id = 0; +void WaitObject::AddWaitingThread(Thread* thread) { + auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread); + if (itr == waiting_threads.end()) + waiting_threads.push_back(thread); +} + +void WaitObject::RemoveWaitingThread(Thread* thread) { + auto itr = std::find(waiting_threads.begin(), waiting_threads.end(), thread); + if (itr != waiting_threads.end()) + waiting_threads.erase(itr); +} + +Thread* WaitObject::WakeupNextThread() { + if (waiting_threads.empty()) + return nullptr; + + auto next_thread = waiting_threads.front(); + waiting_threads.erase(waiting_threads.begin()); + + next_thread->ReleaseWaitObject(this); + + return next_thread; +} + +void WaitObject::WakeupAllWaitingThreads() { + auto waiting_threads_copy = waiting_threads; + + // We use a copy because ReleaseWaitObject will remove the thread from this object's + // waiting_threads list + for (auto thread : waiting_threads_copy) + thread->ReleaseWaitObject(this); + + _assert_msg_(Kernel, waiting_threads.empty(), "failed to awaken all waiting threads!"); +} + HandleTable::HandleTable() { next_generation = 1; Clear(); diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h index 5e5217b78..3828efbea 100644 --- a/src/core/hle/kernel/kernel.h +++ b/src/core/hle/kernel/kernel.h @@ -8,6 +8,8 @@ #include <array> #include <string> +#include <vector> + #include "common/common.h" #include "core/hle/result.h" @@ -58,17 +60,35 @@ class Object : NonCopyable { public: virtual ~Object() {} Handle GetHandle() const { return handle; } + virtual std::string GetTypeName() const { return "[BAD KERNEL OBJECT TYPE]"; } virtual std::string GetName() const { return "[UNKNOWN KERNEL OBJECT]"; } virtual Kernel::HandleType GetHandleType() const = 0; /** - * Wait for kernel object to synchronize. - * @return True if the current thread should wait as a result of the wait + * Check if a thread can wait on the object + * @return True if a thread can wait on the object, otherwise false */ - virtual ResultVal<bool> WaitSynchronization() { - LOG_ERROR(Kernel, "(UNIMPLEMENTED)"); - return UnimplementedFunction(ErrorModule::Kernel); + bool IsWaitable() const { + switch (GetHandleType()) { + case HandleType::Session: + case HandleType::Event: + case HandleType::Mutex: + case HandleType::Thread: + case HandleType::Semaphore: + case HandleType::Timer: + return true; + + case HandleType::Unknown: + case HandleType::Port: + case HandleType::SharedMemory: + case HandleType::Redirection: + case HandleType::Process: + case HandleType::AddressArbiter: + return false; + } + + return false; } private: @@ -92,6 +112,44 @@ inline void intrusive_ptr_release(Object* object) { template <typename T> using SharedPtr = boost::intrusive_ptr<T>; +/// Class that represents a Kernel object that a thread can be waiting on +class WaitObject : public Object { +public: + + /** + * Check if the current thread should wait until the object is available + * @return True if the current thread should wait due to this object being unavailable + */ + virtual bool ShouldWait() = 0; + + /// Acquire/lock the object if it is available + virtual void Acquire() = 0; + + /** + * Add a thread to wait on this object + * @param thread Pointer to thread to add + */ + void AddWaitingThread(Thread* thread); + + /** + * Removes a thread from waiting on this object (e.g. if it was resumed already) + * @param thread Pointer to thread to remove + */ + void RemoveWaitingThread(Thread* thead); + + /** + * Wake up the next thread waiting on this object + * @return Pointer to the thread that was resumed, nullptr if no threads are waiting + */ + Thread* WakeupNextThread(); + + /// Wake up all threads waiting on this object + void WakeupAllWaitingThreads(); + +private: + std::vector<Thread*> waiting_threads; ///< Threads waiting for this object to become available +}; + /** * This class allows the creation of Handles, which are references to objects that can be tested * for validity and looked up. Here they are used to pass references to kernel objects to/from the @@ -146,14 +204,14 @@ public: /** * Looks up a handle. - * @returns Pointer to the looked-up object, or `nullptr` if the handle is not valid. + * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid. */ SharedPtr<Object> GetGeneric(Handle handle) const; /** * Looks up a handle while verifying its type. - * @returns Pointer to the looked-up object, or `nullptr` if the handle is not valid or its - * type differs from the handle type `T::HANDLE_TYPE`. + * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid or its + * type differs from the handle type `T::HANDLE_TYPE`. */ template <class T> SharedPtr<T> Get(Handle handle) const { @@ -164,6 +222,19 @@ public: return nullptr; } + /** + * Looks up a handle while verifying that it is an object that a thread can wait on + * @return Pointer to the looked-up object, or `nullptr` if the handle is not valid or it is + * not a waitable object. + */ + SharedPtr<WaitObject> GetWaitObject(Handle handle) const { + SharedPtr<Object> object = GetGeneric(handle); + if (object != nullptr && object->IsWaitable()) { + return boost::static_pointer_cast<WaitObject>(std::move(object)); + } + return nullptr; + } + /// Closes all handles held in this table. void Clear(); diff --git a/src/core/hle/kernel/mutex.cpp b/src/core/hle/kernel/mutex.cpp index 853a5dd74..cd05a1397 100644 --- a/src/core/hle/kernel/mutex.cpp +++ b/src/core/hle/kernel/mutex.cpp @@ -13,7 +13,7 @@ namespace Kernel { -class Mutex : public Object { +class Mutex : public WaitObject { public: std::string GetTypeName() const override { return "Mutex"; } std::string GetName() const override { return name; } @@ -23,39 +23,26 @@ public: bool initial_locked; ///< Initial lock state when mutex was created bool locked; ///< Current locked state - Handle lock_thread; ///< Handle to thread that currently has mutex - std::vector<Handle> waiting_threads; ///< Threads that are waiting for the mutex std::string name; ///< Name of mutex (optional) + SharedPtr<Thread> holding_thread; ///< Thread that has acquired the mutex - ResultVal<bool> WaitSynchronization() override; + bool ShouldWait() override; + void Acquire() override; }; //////////////////////////////////////////////////////////////////////////////////////////////////// -typedef std::multimap<Handle, Handle> MutexMap; +typedef std::multimap<SharedPtr<Thread>, SharedPtr<Mutex>> MutexMap; static MutexMap g_mutex_held_locks; /** * Acquires the specified mutex for the specified thread * @param mutex Mutex that is to be acquired - * @param thread Thread that will acquired + * @param thread Thread that will acquire the mutex */ -void MutexAcquireLock(Mutex* mutex, Handle thread = GetCurrentThread()->GetHandle()) { - g_mutex_held_locks.insert(std::make_pair(thread, mutex->GetHandle())); - mutex->lock_thread = thread; -} - -bool ReleaseMutexForThread(Mutex* mutex, Handle thread_handle) { - MutexAcquireLock(mutex, thread_handle); - - Thread* thread = Kernel::g_handle_table.Get<Thread>(thread_handle).get(); - if (thread == nullptr) { - LOG_ERROR(Kernel, "Called with invalid handle: %08X", thread_handle); - return false; - } - - thread->ResumeFromWait(); - return true; +void MutexAcquireLock(Mutex* mutex, Thread* thread) { + g_mutex_held_locks.insert(std::make_pair(thread, mutex)); + mutex->holding_thread = thread; } /** @@ -64,56 +51,41 @@ bool ReleaseMutexForThread(Mutex* mutex, Handle thread_handle) { */ void ResumeWaitingThread(Mutex* mutex) { // Find the next waiting thread for the mutex... - if (mutex->waiting_threads.empty()) { + auto next_thread = mutex->WakeupNextThread(); + if (next_thread != nullptr) { + MutexAcquireLock(mutex, next_thread); + } else { // Reset mutex lock thread handle, nothing is waiting mutex->locked = false; - mutex->lock_thread = -1; - } - else { - // Resume the next waiting thread and re-lock the mutex - std::vector<Handle>::iterator iter = mutex->waiting_threads.begin(); - ReleaseMutexForThread(mutex, *iter); - mutex->waiting_threads.erase(iter); + mutex->holding_thread = nullptr; } } -void MutexEraseLock(Mutex* mutex) { - Handle handle = mutex->GetHandle(); - auto locked = g_mutex_held_locks.equal_range(mutex->lock_thread); - for (MutexMap::iterator iter = locked.first; iter != locked.second; ++iter) { - if (iter->second == handle) { - g_mutex_held_locks.erase(iter); - break; - } - } - mutex->lock_thread = -1; -} - -void ReleaseThreadMutexes(Handle thread) { +void ReleaseThreadMutexes(Thread* thread) { auto locked = g_mutex_held_locks.equal_range(thread); // Release every mutex that the thread holds, and resume execution on the waiting threads - for (MutexMap::iterator iter = locked.first; iter != locked.second; ++iter) { - Mutex* mutex = g_handle_table.Get<Mutex>(iter->second).get(); - ResumeWaitingThread(mutex); + for (auto iter = locked.first; iter != locked.second; ++iter) { + ResumeWaitingThread(iter->second.get()); } // Erase all the locks that this thread holds g_mutex_held_locks.erase(thread); } -bool LockMutex(Mutex* mutex) { - // Mutex alread locked? +bool ReleaseMutex(Mutex* mutex) { if (mutex->locked) { - return false; - } - MutexAcquireLock(mutex); - return true; -} + auto locked = g_mutex_held_locks.equal_range(mutex->holding_thread); -bool ReleaseMutex(Mutex* mutex) { - MutexEraseLock(mutex); - ResumeWaitingThread(mutex); + for (MutexMap::iterator iter = locked.first; iter != locked.second; ++iter) { + if (iter->second == mutex) { + g_mutex_held_locks.erase(iter); + break; + } + } + + ResumeWaitingThread(mutex); + } return true; } @@ -148,15 +120,12 @@ Mutex* CreateMutex(Handle& handle, bool initial_locked, const std::string& name) mutex->locked = mutex->initial_locked = initial_locked; mutex->name = name; + mutex->holding_thread = nullptr; // Acquire mutex with current thread if initialized as locked... - if (mutex->locked) { - MutexAcquireLock(mutex); + if (mutex->locked) + MutexAcquireLock(mutex, GetCurrentThread()); - // Otherwise, reset lock thread handle - } else { - mutex->lock_thread = -1; - } return mutex; } @@ -172,17 +141,14 @@ Handle CreateMutex(bool initial_locked, const std::string& name) { return handle; } -ResultVal<bool> Mutex::WaitSynchronization() { - bool wait = locked; - if (locked) { - waiting_threads.push_back(GetCurrentThread()->GetHandle()); - Kernel::WaitCurrentThread(WAITTYPE_MUTEX, this); - } else { - // Lock the mutex when the first thread accesses it - locked = true; - MutexAcquireLock(this); - } +bool Mutex::ShouldWait() { + return locked && holding_thread != GetCurrentThread(); +} - return MakeResult<bool>(wait); +void Mutex::Acquire() { + _assert_msg_(Kernel, !ShouldWait(), "object unavailable!"); + locked = true; + MutexAcquireLock(this, GetCurrentThread()); } + } // namespace diff --git a/src/core/hle/kernel/mutex.h b/src/core/hle/kernel/mutex.h index a8ca97014..bb8778c98 100644 --- a/src/core/hle/kernel/mutex.h +++ b/src/core/hle/kernel/mutex.h @@ -28,6 +28,6 @@ Handle CreateMutex(bool initial_locked, const std::string& name="Unknown"); * Releases all the mutexes held by the specified thread * @param thread Thread that is holding the mutexes */ -void ReleaseThreadMutexes(Handle thread); +void ReleaseThreadMutexes(Thread* thread); } // namespace diff --git a/src/core/hle/kernel/semaphore.cpp b/src/core/hle/kernel/semaphore.cpp index 88ec9a104..135d8fb2a 100644 --- a/src/core/hle/kernel/semaphore.cpp +++ b/src/core/hle/kernel/semaphore.cpp @@ -12,7 +12,7 @@ namespace Kernel { -class Semaphore : public Object { +class Semaphore : public WaitObject { public: std::string GetTypeName() const override { return "Semaphore"; } std::string GetName() const override { return name; } @@ -22,28 +22,15 @@ public: s32 max_count; ///< Maximum number of simultaneous holders the semaphore can have s32 available_count; ///< Number of free slots left in the semaphore - std::queue<Handle> waiting_threads; ///< Threads that are waiting for the semaphore std::string name; ///< Name of semaphore (optional) - /** - * Tests whether a semaphore still has free slots - * @return Whether the semaphore is available - */ - bool IsAvailable() const { - return available_count > 0; + bool ShouldWait() override { + return available_count <= 0; } - ResultVal<bool> WaitSynchronization() override { - bool wait = !IsAvailable(); - - if (wait) { - Kernel::WaitCurrentThread(WAITTYPE_SEMA, this); - waiting_threads.push(GetCurrentThread()->GetHandle()); - } else { - --available_count; - } - - return MakeResult<bool>(wait); + void Acquire() override { + _assert_msg_(Kernel, !ShouldWait(), "object unavailable!"); + --available_count; } }; @@ -83,12 +70,8 @@ ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) { // Notify some of the threads that the semaphore has been released // stop once the semaphore is full again or there are no more waiting threads - while (!semaphore->waiting_threads.empty() && semaphore->IsAvailable()) { - Thread* thread = Kernel::g_handle_table.Get<Thread>(semaphore->waiting_threads.front()).get(); - if (thread != nullptr) - thread->ResumeFromWait(); - semaphore->waiting_threads.pop(); - --semaphore->available_count; + while (!semaphore->ShouldWait() && semaphore->WakeupNextThread() != nullptr) { + semaphore->Acquire(); } return RESULT_SUCCESS; diff --git a/src/core/hle/kernel/session.h b/src/core/hle/kernel/session.h index 91f3ffc2c..1788e4375 100644 --- a/src/core/hle/kernel/session.h +++ b/src/core/hle/kernel/session.h @@ -41,7 +41,7 @@ inline static u32* GetCommandBuffer(const int offset=0) { * CTR-OS so that IPC calls can be optionally handled by the real implementations of processes, as * opposed to HLE simulations. */ -class Session : public Object { +class Session : public WaitObject { public: std::string GetTypeName() const override { return "Session"; } @@ -53,6 +53,17 @@ public: * aren't supported yet. */ virtual ResultVal<bool> SyncRequest() = 0; + + // TODO(bunnei): These functions exist to satisfy a hardware test with a Session object + // passed into WaitSynchronization. Figure out the meaning of them. + + bool ShouldWait() override { + return true; + } + + void Acquire() override { + _assert_msg_(Kernel, !ShouldWait(), "object unavailable!"); + } }; } diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp index bc86a7c59..03b492c75 100644 --- a/src/core/hle/kernel/thread.cpp +++ b/src/core/hle/kernel/thread.cpp @@ -22,17 +22,12 @@ namespace Kernel { -ResultVal<bool> Thread::WaitSynchronization() { - const bool wait = status != THREADSTATUS_DORMANT; - if (wait) { - Thread* thread = GetCurrentThread(); - if (std::find(waiting_threads.begin(), waiting_threads.end(), thread) == waiting_threads.end()) { - waiting_threads.push_back(thread); - } - WaitCurrentThread(WAITTYPE_THREADEND, this); - } +bool Thread::ShouldWait() { + return status != THREADSTATUS_DORMANT; +} - return MakeResult<bool>(wait); +void Thread::Acquire() { + _assert_msg_(Kernel, !ShouldWait(), "object unavailable!"); } // Lists all thread ids that aren't deleted/etc. @@ -67,8 +62,8 @@ static void ResetThread(Thread* t, u32 arg, s32 lowest_priority) { if (t->current_priority < lowest_priority) { t->current_priority = t->initial_priority; } - t->wait_type = WAITTYPE_NONE; - t->wait_object = nullptr; + + t->wait_objects.clear(); t->wait_address = 0; } @@ -88,37 +83,32 @@ static void ChangeReadyState(Thread* t, bool ready) { } } -/// Check if a thread is blocking on a specified wait type -static bool CheckWaitType(const Thread* thread, WaitType type) { - return (type == thread->wait_type) && (thread->IsWaiting()); -} +/// Check if a thread is waiting on a the specified wait object +static bool CheckWait_WaitObject(const Thread* thread, WaitObject* wait_object) { + auto itr = std::find(thread->wait_objects.begin(), thread->wait_objects.end(), wait_object); + + if (itr != thread->wait_objects.end()) + return thread->IsWaiting(); -/// Check if a thread is blocking on a specified wait type with a specified handle -static bool CheckWaitType(const Thread* thread, WaitType type, Object* wait_object) { - return CheckWaitType(thread, type) && wait_object == thread->wait_object; + return false; } -/// Check if a thread is blocking on a specified wait type with a specified handle and address -static bool CheckWaitType(const Thread* thread, WaitType type, Object* wait_object, VAddr wait_address) { - return CheckWaitType(thread, type, wait_object) && (wait_address == thread->wait_address); +/// Check if the specified thread is waiting on the specified address to be arbitrated +static bool CheckWait_AddressArbiter(const Thread* thread, VAddr wait_address) { + return thread->IsWaiting() && thread->wait_objects.empty() && wait_address == thread->wait_address; } /// Stops the current thread void Thread::Stop(const char* reason) { // Release all the mutexes that this thread holds - ReleaseThreadMutexes(GetHandle()); + ReleaseThreadMutexes(this); ChangeReadyState(this, false); status = THREADSTATUS_DORMANT; - for (auto& waiting_thread : waiting_threads) { - if (CheckWaitType(waiting_thread.get(), WAITTYPE_THREADEND, this)) - waiting_thread->ResumeFromWait(); - } - waiting_threads.clear(); + WakeupAllWaitingThreads(); // Stopped threads are never waiting. - wait_type = WAITTYPE_NONE; - wait_object = nullptr; + wait_objects.clear(); wait_address = 0; } @@ -129,26 +119,20 @@ static void ChangeThreadState(Thread* t, ThreadStatus new_status) { } ChangeReadyState(t, (new_status & THREADSTATUS_READY) != 0); t->status = new_status; - - if (new_status == THREADSTATUS_WAIT) { - if (t->wait_type == WAITTYPE_NONE) { - LOG_ERROR(Kernel, "Waittype none not allowed"); - } - } } /// Arbitrate the highest priority thread that is waiting -Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address) { +Thread* ArbitrateHighestPriorityThread(u32 address) { Thread* highest_priority_thread = nullptr; s32 priority = THREADPRIO_LOWEST; // Iterate through threads, find highest priority thread that is waiting to be arbitrated... for (auto& thread : thread_list) { - if (!CheckWaitType(thread.get(), WAITTYPE_ARB, arbiter, address)) + if (!CheckWait_AddressArbiter(thread.get(), address)) continue; if (thread == nullptr) - continue; // TODO(yuriks): Thread handle will hang around forever. Should clean up. + continue; if(thread->current_priority <= priority) { highest_priority_thread = thread.get(); @@ -165,11 +149,11 @@ Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address) { } /// Arbitrate all threads currently waiting -void ArbitrateAllThreads(Object* arbiter, u32 address) { +void ArbitrateAllThreads(u32 address) { // Iterate through threads, find highest priority thread that is waiting to be arbitrated... for (auto& thread : thread_list) { - if (CheckWaitType(thread.get(), WAITTYPE_ARB, arbiter, address)) + if (CheckWait_AddressArbiter(thread.get(), address)) thread->ResumeFromWait(); } } @@ -177,9 +161,6 @@ void ArbitrateAllThreads(Object* arbiter, u32 address) { /// Calls a thread by marking it as "ready" (note: will not actually execute until current thread yields) static void CallThread(Thread* t) { // Stop waiting - if (t->wait_type != WAITTYPE_NONE) { - t->wait_type = WAITTYPE_NONE; - } ChangeThreadState(t, THREADSTATUS_READY); } @@ -200,7 +181,6 @@ static void SwitchContext(Thread* t) { current_thread = t; ChangeReadyState(t, false); t->status = (t->status | THREADSTATUS_RUNNING) & ~THREADSTATUS_READY; - t->wait_type = WAITTYPE_NONE; Core::g_app_core->LoadContext(t->context); } else { current_thread = nullptr; @@ -223,16 +203,27 @@ static Thread* NextThread() { return next; } -void WaitCurrentThread(WaitType wait_type, Object* wait_object) { +void WaitCurrentThread_Sleep() { Thread* thread = GetCurrentThread(); - thread->wait_type = wait_type; - thread->wait_object = wait_object; ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND))); } -void WaitCurrentThread(WaitType wait_type, Object* wait_object, VAddr wait_address) { - WaitCurrentThread(wait_type, wait_object); - GetCurrentThread()->wait_address = wait_address; +void WaitCurrentThread_WaitSynchronization(SharedPtr<WaitObject> wait_object, bool wait_set_output, bool wait_all) { + Thread* thread = GetCurrentThread(); + thread->wait_set_output = wait_set_output; + thread->wait_all = wait_all; + + // It's possible to call WaitSynchronizationN without any objects passed in... + if (wait_object != nullptr) + thread->wait_objects.push_back(wait_object); + + ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND))); +} + +void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) { + Thread* thread = GetCurrentThread(); + thread->wait_address = wait_address; + ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND))); } /// Event type for the thread wake up event @@ -247,6 +238,12 @@ static void ThreadWakeupCallback(u64 parameter, int cycles_late) { return; } + thread->SetWaitSynchronizationResult(ResultCode(ErrorDescription::Timeout, ErrorModule::OS, + ErrorSummary::StatusChanged, ErrorLevel::Info)); + + if (thread->wait_set_output) + thread->SetWaitSynchronizationOutput(-1); + thread->ResumeFromWait(); } @@ -261,14 +258,63 @@ void WakeThreadAfterDelay(Thread* thread, s64 nanoseconds) { CoreTiming::ScheduleEvent(usToCycles(microseconds), ThreadWakeupEventType, thread->GetHandle()); } -/// Resumes a thread from waiting by marking it as "ready" +void Thread::ReleaseWaitObject(WaitObject* wait_object) { + if (wait_objects.empty()) { + LOG_CRITICAL(Kernel, "thread is not waiting on any objects!"); + return; + } + + // Remove this thread from the waiting object's thread list + wait_object->RemoveWaitingThread(this); + + unsigned index = 0; + bool wait_all_failed = false; // Will be set to true if any object is unavailable + + // Iterate through all waiting objects to check availability... + for (auto itr = wait_objects.begin(); itr != wait_objects.end(); ++itr) { + if ((*itr)->ShouldWait()) + wait_all_failed = true; + + // The output should be the last index of wait_object + if (*itr == wait_object) + index = itr - wait_objects.begin(); + } + + // If we are waiting on all objects... + if (wait_all) { + // Resume the thread only if all are available... + if (!wait_all_failed) { + SetWaitSynchronizationResult(RESULT_SUCCESS); + SetWaitSynchronizationOutput(-1); + + ResumeFromWait(); + } + } else { + // Otherwise, resume + SetWaitSynchronizationResult(RESULT_SUCCESS); + + if (wait_set_output) + SetWaitSynchronizationOutput(index); + + ResumeFromWait(); + } +} + void Thread::ResumeFromWait() { // Cancel any outstanding wakeup events CoreTiming::UnscheduleEvent(ThreadWakeupEventType, GetHandle()); status &= ~THREADSTATUS_WAIT; - wait_object = nullptr; - wait_type = WAITTYPE_NONE; + + // Remove this thread from all other WaitObjects + for (auto wait_object : wait_objects) + wait_object->RemoveWaitingThread(this); + + wait_objects.clear(); + wait_set_output = false; + wait_all = false; + wait_address = 0; + if (!(status & (THREADSTATUS_WAITSUSPEND | THREADSTATUS_DORMANT | THREADSTATUS_DEAD))) { ChangeReadyState(this, true); } @@ -334,8 +380,9 @@ ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, thread->stack_size = stack_size; thread->initial_priority = thread->current_priority = priority; thread->processor_id = processor_id; - thread->wait_type = WAITTYPE_NONE; - thread->wait_object = nullptr; + thread->wait_set_output = false; + thread->wait_all = false; + thread->wait_objects.clear(); thread->wait_address = 0; thread->name = std::move(name); @@ -419,13 +466,20 @@ void Reschedule() { LOG_TRACE(Kernel, "cannot context switch from 0x%08X, no higher priority thread!", prev->GetHandle()); for (auto& thread : thread_list) { - LOG_TRACE(Kernel, "\thandle=0x%08X prio=0x%02X, status=0x%08X wait_type=0x%08X wait_handle=0x%08X", - thread->GetHandle(), thread->current_priority, thread->status, thread->wait_type, - (thread->wait_object ? thread->wait_object->GetHandle() : INVALID_HANDLE)); + LOG_TRACE(Kernel, "\thandle=0x%08X prio=0x%02X, status=0x%08X", thread->GetHandle(), + thread->current_priority, thread->status); } } } +void Thread::SetWaitSynchronizationResult(ResultCode result) { + context.cpu_registers[0] = result.raw; +} + +void Thread::SetWaitSynchronizationOutput(s32 output) { + context.cpu_registers[1] = output; +} + //////////////////////////////////////////////////////////////////////////////////////////////////// void ThreadingInit() { diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h index 284dec400..5fab1ab58 100644 --- a/src/core/hle/kernel/thread.h +++ b/src/core/hle/kernel/thread.h @@ -38,21 +38,9 @@ enum ThreadStatus { THREADSTATUS_WAITSUSPEND = THREADSTATUS_WAIT | THREADSTATUS_SUSPEND }; -enum WaitType { - WAITTYPE_NONE, - WAITTYPE_SLEEP, - WAITTYPE_SEMA, - WAITTYPE_EVENT, - WAITTYPE_THREADEND, - WAITTYPE_MUTEX, - WAITTYPE_SYNCH, - WAITTYPE_ARB, - WAITTYPE_TIMER, -}; - namespace Kernel { -class Thread : public Kernel::Object { +class Thread : public WaitObject { public: static ResultVal<SharedPtr<Thread>> Create(std::string name, VAddr entry_point, s32 priority, u32 arg, s32 processor_id, VAddr stack_top, u32 stack_size); @@ -70,7 +58,8 @@ public: inline bool IsSuspended() const { return (status & THREADSTATUS_SUSPEND) != 0; } inline bool IsIdle() const { return idle; } - ResultVal<bool> WaitSynchronization() override; + bool ShouldWait() override; + void Acquire() override; s32 GetPriority() const { return current_priority; } void SetPriority(s32 priority); @@ -78,9 +67,28 @@ public: u32 GetThreadId() const { return thread_id; } void Stop(const char* reason); - /// Resumes a thread from waiting by marking it as "ready". + + /** + * Release an acquired wait object + * @param wait_object WaitObject to release + */ + void ReleaseWaitObject(WaitObject* wait_object); + + /// Resumes a thread from waiting by marking it as "ready" void ResumeFromWait(); + /** + * Sets the result after the thread awakens (from either WaitSynchronization SVC) + * @param result Value to set to the returned result + */ + void SetWaitSynchronizationResult(ResultCode result); + + /** + * Sets the output parameter value after the thread awakens (from WaitSynchronizationN SVC only) + * @param output Value to set to the output parameter + */ + void SetWaitSynchronizationOutput(s32 output); + Core::ThreadContext context; u32 thread_id; @@ -95,11 +103,11 @@ public: s32 processor_id; - WaitType wait_type; - Object* wait_object; - VAddr wait_address; + std::vector<SharedPtr<WaitObject>> wait_objects; ///< Objects that the thread is waiting on - std::vector<SharedPtr<Thread>> waiting_threads; + VAddr wait_address; ///< If waiting on an AddressArbiter, this is the arbitration address + bool wait_all; ///< True if the thread is waiting on all objects before resuming + bool wait_set_output; ///< True if the output parameter should be set on thread wakeup std::string name; @@ -107,6 +115,7 @@ public: bool idle = false; private: + Thread() = default; }; @@ -117,20 +126,30 @@ SharedPtr<Thread> SetupMainThread(s32 priority, u32 stack_size); void Reschedule(); /// Arbitrate the highest priority thread that is waiting -Thread* ArbitrateHighestPriorityThread(Object* arbiter, u32 address); +Thread* ArbitrateHighestPriorityThread(u32 address); /// Arbitrate all threads currently waiting... -void ArbitrateAllThreads(Object* arbiter, u32 address); +void ArbitrateAllThreads(u32 address); /// Gets the current thread Thread* GetCurrentThread(); +/// Waits the current thread on a sleep +void WaitCurrentThread_Sleep(); + /** - * Puts the current thread in the wait state for the given type - * @param wait_type Type of wait - * @param wait_object Kernel object that we are waiting on, defaults to current thread + * Waits the current thread from a WaitSynchronization call + * @param wait_object Kernel object that we are waiting on + * @param wait_set_output If true, set the output parameter on thread wakeup (for WaitSynchronizationN only) + * @param wait_all If true, wait on all objects before resuming (for WaitSynchronizationN only) */ -void WaitCurrentThread(WaitType wait_type, Object* wait_object = GetCurrentThread()); +void WaitCurrentThread_WaitSynchronization(SharedPtr<WaitObject> wait_object, bool wait_set_output, bool wait_all); + +/** + * Waits the current thread from an ArbitrateAddress call + * @param wait_address Arbitration address used to resume from wait + */ +void WaitCurrentThread_ArbitrateAddress(VAddr wait_address); /** * Schedules an event to wake up the specified thread after the specified delay. @@ -140,22 +159,13 @@ void WaitCurrentThread(WaitType wait_type, Object* wait_object = GetCurrentThrea void WakeThreadAfterDelay(Thread* thread, s64 nanoseconds); /** - * Puts the current thread in the wait state for the given type - * @param wait_type Type of wait - * @param wait_object Kernel object that we are waiting on - * @param wait_address Arbitration address used to resume from wait - */ -void WaitCurrentThread(WaitType wait_type, Object* wait_object, VAddr wait_address); - - - -/** * Sets up the idle thread, this is a thread that is intended to never execute instructions, * only to advance the timing. It is scheduled when there are no other ready threads in the thread queue * and will try to yield on every call. * @returns The handle of the idle thread */ Handle SetupIdleThread(); + /// Initialize threading void ThreadingInit(); diff --git a/src/core/hle/kernel/timer.cpp b/src/core/hle/kernel/timer.cpp index 3b0452d4d..ec0b2c323 100644 --- a/src/core/hle/kernel/timer.cpp +++ b/src/core/hle/kernel/timer.cpp @@ -13,7 +13,7 @@ namespace Kernel { -class Timer : public Object { +class Timer : public WaitObject { public: std::string GetTypeName() const override { return "Timer"; } std::string GetName() const override { return name; } @@ -24,19 +24,17 @@ public: ResetType reset_type; ///< The ResetType of this timer bool signaled; ///< Whether the timer has been signaled or not - std::set<Handle> waiting_threads; ///< Threads that are waiting for the timer std::string name; ///< Name of timer (optional) u64 initial_delay; ///< The delay until the timer fires for the first time u64 interval_delay; ///< The delay until the timer fires after the first time - ResultVal<bool> WaitSynchronization() override { - bool wait = !signaled; - if (wait) { - waiting_threads.insert(GetCurrentThread()->GetHandle()); - Kernel::WaitCurrentThread(WAITTYPE_TIMER, this); - } - return MakeResult<bool>(wait); + bool ShouldWait() override { + return !signaled; + } + + void Acquire() override { + _assert_msg_(Kernel, !ShouldWait(), "object unavailable!"); } }; @@ -92,12 +90,7 @@ static void TimerCallback(u64 timer_handle, int cycles_late) { timer->signaled = true; // Resume all waiting threads - for (Handle thread_handle : timer->waiting_threads) { - if (SharedPtr<Thread> thread = Kernel::g_handle_table.Get<Thread>(thread_handle)) - thread->ResumeFromWait(); - } - - timer->waiting_threads.clear(); + timer->WakeupAllWaitingThreads(); if (timer->reset_type == RESETTYPE_ONESHOT) timer->signaled = false; diff --git a/src/core/hle/kernel/timer.h b/src/core/hle/kernel/timer.h index f8aa66b60..8170e82d4 100644 --- a/src/core/hle/kernel/timer.h +++ b/src/core/hle/kernel/timer.h @@ -33,7 +33,7 @@ ResultCode ClearTimer(Handle handle); /** * Creates a timer - * @param Handle to newly created Timer object + * @param handle Handle to the newly created Timer object * @param reset_type ResetType describing how to create the timer * @param name Optional name of timer * @return ResultCode of the error diff --git a/src/core/hle/service/apt_a.cpp b/src/core/hle/service/apt_a.cpp index 37be4b027..42f2879c1 100644 --- a/src/core/hle/service/apt_a.cpp +++ b/src/core/hle/service/apt_a.cpp @@ -11,6 +11,7 @@ namespace APT_U { extern void GetLockHandle(Service::Interface* self); extern void ReceiveParameter(Service::Interface* self); extern void GlanceParameter(Service::Interface* self); + extern void GetSharedFont(Service::Interface* self); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -29,6 +30,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x000E0080, APT_U::GlanceParameter, "GlanceParameter?"}, {0x003B0040, nullptr, "CancelLibraryApplet?"}, {0x00430040, nullptr, "NotifyToWait?"}, + {0x00440000, APT_U::GetSharedFont, "GetSharedFont?"}, {0x004B00C2, nullptr, "AppletUtility?"}, {0x00550040, nullptr, "WriteInputToNsState?"}, }; diff --git a/src/core/hle/service/apt_s.cpp b/src/core/hle/service/apt_s.cpp index f4599e19d..31e6653ef 100644 --- a/src/core/hle/service/apt_s.cpp +++ b/src/core/hle/service/apt_s.cpp @@ -20,6 +20,7 @@ namespace APT_U { extern void Initialize(Service::Interface* self); extern void Enable(Service::Interface* self); extern void InquireNotification(Service::Interface* self); + extern void NotifyToWait(Service::Interface* self); extern void GetSharedFont(Service::Interface* self); extern void AppletUtility(Service::Interface* self); extern void GlanceParameter(Service::Interface* self); @@ -95,7 +96,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00400042, nullptr, "SendCaptureBufferInfo"}, {0x00410040, nullptr, "ReceiveCaptureBufferInfo"}, {0x00420080, nullptr, "SleepSystem"}, - {0x00430040, nullptr, "NotifyToWait"}, + {0x00430040, APT_U::NotifyToWait, "NotifyToWait"}, {0x00440000, APT_U::GetSharedFont, "GetSharedFont"}, {0x00450040, nullptr, "GetWirelessRebootInfo"}, {0x00460104, nullptr, "Wrap"}, diff --git a/src/core/hle/service/apt_u.cpp b/src/core/hle/service/apt_u.cpp index 69a7bcf92..d318de3d2 100644 --- a/src/core/hle/service/apt_u.cpp +++ b/src/core/hle/service/apt_u.cpp @@ -50,8 +50,8 @@ void Initialize(Service::Interface* self) { cmd_buff[3] = notification_event_handle; cmd_buff[4] = pause_event_handle; - Kernel::SetEventLocked(notification_event_handle, true); - Kernel::SetEventLocked(pause_event_handle, false); // Fire start event + Kernel::ClearEvent(notification_event_handle); + Kernel::SignalEvent(pause_event_handle); // Fire start event _assert_msg_(KERNEL, (0 != lock_handle), "Cannot initialize without lock"); Kernel::ReleaseMutex(lock_handle); diff --git a/src/core/hle/service/cam_u.cpp b/src/core/hle/service/cam_u.cpp new file mode 100644 index 000000000..549095339 --- /dev/null +++ b/src/core/hle/service/cam_u.cpp @@ -0,0 +1,24 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "common/log.h" +#include "core/hle/hle.h" +#include "core/hle/service/cam_u.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace CAM_U + +namespace CAM_U { + +// Empty arrays are illegal -- commented out until an entry is added. +//const Interface::FunctionInfo FunctionTable[] = { }; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Interface class + +Interface::Interface() { + //Register(FunctionTable, ARRAY_SIZE(FunctionTable)); +} + +} // namespace diff --git a/src/core/hle/service/cam_u.h b/src/core/hle/service/cam_u.h new file mode 100644 index 000000000..878c20a84 --- /dev/null +++ b/src/core/hle/service/cam_u.h @@ -0,0 +1,23 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "core/hle/service/service.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace CAM_U + +namespace CAM_U { + +class Interface : public Service::Interface { +public: + Interface(); + + std::string GetPortName() const override { + return "cam:u"; + } +}; + +} // namespace diff --git a/src/core/hle/service/cfg/cfg.h b/src/core/hle/service/cfg/cfg.h index c74527ca4..e818d7bdc 100644 --- a/src/core/hle/service/cfg/cfg.h +++ b/src/core/hle/service/cfg/cfg.h @@ -110,7 +110,7 @@ ResultCode GetConfigInfoBlock(u32 block_id, u32 size, u32 flag, u8* output); * The config savegame file in the filesystem is not updated. * @param block_id The id of the block we want to create * @param size The size of the block we want to create - * @param flag The flags of the new block + * @param flags The flags of the new block * @param data A pointer containing the data we will write to the new block * @returns ResultCode indicating the result of the operation, 0 on success */ diff --git a/src/core/hle/service/fs/archive.h b/src/core/hle/service/fs/archive.h index b3f2134f2..2cdfaa7e9 100644 --- a/src/core/hle/service/fs/archive.h +++ b/src/core/hle/service/fs/archive.h @@ -42,7 +42,7 @@ ResultVal<ArchiveHandle> OpenArchive(ArchiveIdCode id_code, FileSys::Path& archi /** * Closes an archive - * @param id_code IdCode of the archive to open + * @param handle Handle to the archive to close */ ResultCode CloseArchive(ArchiveHandle handle); diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp new file mode 100644 index 000000000..5abcb2596 --- /dev/null +++ b/src/core/hle/service/hid/hid.cpp @@ -0,0 +1,138 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "core/hle/service/hid/hid.h" + +#include "core/arm/arm_interface.h" +#include "core/hle/kernel/event.h" +#include "core/hle/kernel/shared_memory.h" +#include "core/hle/hle.h" + +namespace Service { +namespace HID { + +Handle g_shared_mem = 0; + +Handle g_event_pad_or_touch_1 = 0; +Handle g_event_pad_or_touch_2 = 0; +Handle g_event_accelerometer = 0; +Handle g_event_gyroscope = 0; +Handle g_event_debug_pad = 0; + +// Next Pad state update information +static PadState next_state = {{0}}; +static u32 next_index = 0; +static s16 next_circle_x = 0; +static s16 next_circle_y = 0; + +/** + * Gets a pointer to the PadData structure inside HID shared memory + */ +static inline PadData* GetPadData() { + return reinterpret_cast<PadData*>(Kernel::GetSharedMemoryPointer(g_shared_mem, 0).ValueOr(nullptr)); +} + +/** + * Circle Pad from keys. + * + * This is implemented as "pushed all the way to an edge (max) or centered (0)". + * + * Indicate the circle pad is pushed completely to the edge in 1 of 8 directions. + */ +static void UpdateNextCirclePadState() { + static const s16 max_value = 0x9C; + next_circle_x = next_state.circle_left ? -max_value : 0x0; + next_circle_x += next_state.circle_right ? max_value : 0x0; + next_circle_y = next_state.circle_down ? -max_value : 0x0; + next_circle_y += next_state.circle_up ? max_value : 0x0; +} + +/** + * Sets a Pad state (button or button combo) as pressed + */ +void PadButtonPress(const PadState& pad_state) { + next_state.hex |= pad_state.hex; + UpdateNextCirclePadState(); +} + +/** + * Sets a Pad state (button or button combo) as released + */ +void PadButtonRelease(const PadState& pad_state) { + next_state.hex &= ~pad_state.hex; + UpdateNextCirclePadState(); +} + +/** + * Called after all Pad changes to be included in this update have been made, + * including both Pad key changes and analog circle Pad changes. + */ +void PadUpdateComplete() { + PadData* pad_data = GetPadData(); + + if (pad_data == nullptr) { + return; + } + + // Update PadData struct + pad_data->current_state.hex = next_state.hex; + pad_data->index = next_index; + next_index = (next_index + 1) % pad_data->entries.size(); + + // Get the previous Pad state + u32 last_entry_index = (pad_data->index - 1) % pad_data->entries.size(); + PadState old_state = pad_data->entries[last_entry_index].current_state; + + // Compute bitmask with 1s for bits different from the old state + PadState changed; + changed.hex = (next_state.hex ^ old_state.hex); + + // Compute what was added + PadState additions; + additions.hex = changed.hex & next_state.hex; + + // Compute what was removed + PadState removals; + removals.hex = changed.hex & old_state.hex; + + // Get the current Pad entry + PadDataEntry* current_pad_entry = &pad_data->entries[pad_data->index]; + + // Update entry properties + current_pad_entry->current_state.hex = next_state.hex; + current_pad_entry->delta_additions.hex = additions.hex; + current_pad_entry->delta_removals.hex = removals.hex; + + // Set circle Pad + current_pad_entry->circle_pad_x = next_circle_x; + current_pad_entry->circle_pad_y = next_circle_y; + + // If we just updated index 0, provide a new timestamp + if (pad_data->index == 0) { + pad_data->index_reset_ticks_previous = pad_data->index_reset_ticks; + pad_data->index_reset_ticks = (s64)Core::g_app_core->GetTicks(); + } + + // Signal both handles when there's an update to Pad or touch + Kernel::SignalEvent(g_event_pad_or_touch_1); + Kernel::SignalEvent(g_event_pad_or_touch_2); +} + +void HIDInit() { + g_shared_mem = Kernel::CreateSharedMemory("HID:SharedMem"); // Create shared memory object + + // Create event handles + g_event_pad_or_touch_1 = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID:EventPadOrTouch1"); + g_event_pad_or_touch_2 = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID:EventPadOrTouch2"); + g_event_accelerometer = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID:EventAccelerometer"); + g_event_gyroscope = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID:EventGyroscope"); + g_event_debug_pad = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID:EventDebugPad"); +} + +void HIDShutdown() { + +} + +} +} diff --git a/src/core/hle/service/hid_user.h b/src/core/hle/service/hid/hid.h index 5b96dda60..73cdaa527 100644 --- a/src/core/hle/service/hid_user.h +++ b/src/core/hle/service/hid/hid.h @@ -1,19 +1,26 @@ -// Copyright 2014 Citra Emulator Project +// Copyright 2015 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #pragma once -#include "core/hle/service/service.h" +#include <array> + +#include "core/hle/kernel/kernel.h" #include "common/bit_field.h" -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Namespace HID_User +namespace Service { +namespace HID { -// This service is used for interfacing to physical user controls. -// Uses include game pad controls, touchscreen, accelerometers, gyroscopes, and debug pad. +// Handle to shared memory region designated to HID_User service +extern Handle g_shared_mem; -namespace HID_User { +// Event handles +extern Handle g_event_pad_or_touch_1; +extern Handle g_event_pad_or_touch_2; +extern Handle g_event_accelerometer; +extern Handle g_event_gyroscope; +extern Handle g_event_debug_pad; /** * Structure of a Pad controller state. @@ -97,16 +104,8 @@ void PadButtonPress(const PadState& pad_state); void PadButtonRelease(const PadState& pad_state); void PadUpdateComplete(); -/** - * HID service interface. - */ -class Interface : public Service::Interface { -public: - Interface(); - - std::string GetPortName() const override { - return "hid:USER"; - } -}; +void HIDInit(); +void HIDShutdown(); -} // namespace +} +} diff --git a/src/core/hle/service/hid/hid_spvr.cpp b/src/core/hle/service/hid/hid_spvr.cpp new file mode 100644 index 000000000..76c40b659 --- /dev/null +++ b/src/core/hle/service/hid/hid_spvr.cpp @@ -0,0 +1,38 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "common/log.h" +#include "core/hle/hle.h" +#include "core/hle/service/hid/hid_spvr.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace HID_SPVR + +namespace HID_User { + extern void GetIPCHandles(Service::Interface* self); +} + +namespace HID_SPVR { + +const Interface::FunctionInfo FunctionTable[] = { + {0x000A0000, HID_User::GetIPCHandles, "GetIPCHandles"}, + {0x000B0000, nullptr, "StartAnalogStickCalibration"}, + {0x000E0000, nullptr, "GetAnalogStickCalibrateParam"}, + {0x00110000, nullptr, "EnableAccelerometer"}, + {0x00120000, nullptr, "DisableAccelerometer"}, + {0x00130000, nullptr, "EnableGyroscopeLow"}, + {0x00140000, nullptr, "DisableGyroscopeLow"}, + {0x00150000, nullptr, "GetGyroscopeLowRawToDpsCoefficient"}, + {0x00160000, nullptr, "GetGyroscopeLowCalibrateParam"}, + {0x00170000, nullptr, "GetSoundVolume"}, +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Interface class + +Interface::Interface() { + Register(FunctionTable, ARRAY_SIZE(FunctionTable)); +} + +} // namespace diff --git a/src/core/hle/service/hid/hid_spvr.h b/src/core/hle/service/hid/hid_spvr.h new file mode 100644 index 000000000..53ddc8569 --- /dev/null +++ b/src/core/hle/service/hid/hid_spvr.h @@ -0,0 +1,23 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "core/hle/service/service.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace HID_SPVR + +namespace HID_SPVR { + +class Interface : public Service::Interface { +public: + Interface(); + + std::string GetPortName() const override { + return "hid:SPVR"; + } +}; + +} // namespace diff --git a/src/core/hle/service/hid/hid_user.cpp b/src/core/hle/service/hid/hid_user.cpp new file mode 100644 index 000000000..3a6275707 --- /dev/null +++ b/src/core/hle/service/hid/hid_user.cpp @@ -0,0 +1,75 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "common/log.h" + +#include "core/hle/hle.h" +#include "core/hle/service/hid/hid.h" +#include "hid_user.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace HID_User + +namespace HID_User { + + +// TODO(peachum): +// Add a method for setting analog input from joystick device for the circle Pad. +// +// This method should: +// * Be called after both PadButton<Press, Release>(). +// * Be called before PadUpdateComplete() +// * Set current PadEntry.circle_pad_<axis> using analog data +// * Set PadData.raw_circle_pad_data +// * Set PadData.current_state.circle_right = 1 if current PadEntry.circle_pad_x >= 41 +// * Set PadData.current_state.circle_up = 1 if current PadEntry.circle_pad_y >= 41 +// * Set PadData.current_state.circle_left = 1 if current PadEntry.circle_pad_x <= -41 +// * Set PadData.current_state.circle_right = 1 if current PadEntry.circle_pad_y <= -41 + + +/** + * HID_User::GetIPCHandles service function + * Inputs: + * None + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : Unused + * 3 : Handle to HID_User shared memory + * 4 : Event signaled by HID_User + * 5 : Event signaled by HID_User + * 6 : Event signaled by HID_User + * 7 : Gyroscope event + * 8 : Event signaled by HID_User + */ +void GetIPCHandles(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[1] = 0; // No error + cmd_buff[3] = Service::HID::g_shared_mem; + cmd_buff[4] = Service::HID::g_event_pad_or_touch_1; + cmd_buff[5] = Service::HID::g_event_pad_or_touch_2; + cmd_buff[6] = Service::HID::g_event_accelerometer; + cmd_buff[7] = Service::HID::g_event_gyroscope; + cmd_buff[8] = Service::HID::g_event_debug_pad; +} + +const Interface::FunctionInfo FunctionTable[] = { + {0x000A0000, GetIPCHandles, "GetIPCHandles"}, + {0x00110000, nullptr, "EnableAccelerometer"}, + {0x00120000, nullptr, "DisableAccelerometer"}, + {0x00130000, nullptr, "EnableGyroscopeLow"}, + {0x00140000, nullptr, "DisableGyroscopeLow"}, + {0x00150000, nullptr, "GetGyroscopeLowRawToDpsCoefficient"}, + {0x00160000, nullptr, "GetGyroscopeLowCalibrateParam"}, + {0x00170000, nullptr, "GetSoundVolume"}, +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Interface class + +Interface::Interface() { + Register(FunctionTable, ARRAY_SIZE(FunctionTable)); +} + +} // namespace diff --git a/src/core/hle/service/hid/hid_user.h b/src/core/hle/service/hid/hid_user.h new file mode 100644 index 000000000..1d9929e67 --- /dev/null +++ b/src/core/hle/service/hid/hid_user.h @@ -0,0 +1,29 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "core/hle/service/service.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace HID_User + +// This service is used for interfacing to physical user controls. +// Uses include game pad controls, touchscreen, accelerometers, gyroscopes, and debug pad. + +namespace HID_User { + +/** + * HID service interface. + */ +class Interface : public Service::Interface { +public: + Interface(); + + std::string GetPortName() const override { + return "hid:USER"; + } +}; + +} // namespace diff --git a/src/core/hle/service/hid_user.cpp b/src/core/hle/service/hid_user.cpp deleted file mode 100644 index 1403b1de9..000000000 --- a/src/core/hle/service/hid_user.cpp +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2014 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#include "common/log.h" - -#include "core/arm/arm_interface.h" -#include "core/hle/hle.h" -#include "core/hle/kernel/event.h" -#include "core/hle/kernel/shared_memory.h" -#include "hid_user.h" - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Namespace HID_User - -namespace HID_User { - -// Handle to shared memory region designated to HID_User service -static Handle shared_mem = 0; - -// Event handles -static Handle event_pad_or_touch_1 = 0; -static Handle event_pad_or_touch_2 = 0; -static Handle event_accelerometer = 0; -static Handle event_gyroscope = 0; -static Handle event_debug_pad = 0; - -// Next Pad state update information -static PadState next_state = {{0}}; -static u32 next_index = 0; -static s16 next_circle_x = 0; -static s16 next_circle_y = 0; - -/** - * Gets a pointer to the PadData structure inside HID shared memory - */ -static inline PadData* GetPadData() { - return reinterpret_cast<PadData*>(Kernel::GetSharedMemoryPointer(shared_mem, 0).ValueOr(nullptr)); -} - -/** - * Circle Pad from keys. - * - * This is implemented as "pushed all the way to an edge (max) or centered (0)". - * - * Indicate the circle pad is pushed completely to the edge in 1 of 8 directions. - */ -static void UpdateNextCirclePadState() { - static const s16 max_value = 0x9C; - next_circle_x = next_state.circle_left ? -max_value : 0x0; - next_circle_x += next_state.circle_right ? max_value : 0x0; - next_circle_y = next_state.circle_down ? -max_value : 0x0; - next_circle_y += next_state.circle_up ? max_value : 0x0; -} - -/** - * Sets a Pad state (button or button combo) as pressed - */ -void PadButtonPress(const PadState& pad_state) { - next_state.hex |= pad_state.hex; - UpdateNextCirclePadState(); -} - -/** - * Sets a Pad state (button or button combo) as released - */ -void PadButtonRelease(const PadState& pad_state) { - next_state.hex &= ~pad_state.hex; - UpdateNextCirclePadState(); -} - -/** - * Called after all Pad changes to be included in this update have been made, - * including both Pad key changes and analog circle Pad changes. - */ -void PadUpdateComplete() { - PadData* pad_data = GetPadData(); - - if (pad_data == nullptr) { - return; - } - - // Update PadData struct - pad_data->current_state.hex = next_state.hex; - pad_data->index = next_index; - next_index = (next_index + 1) % pad_data->entries.size(); - - // Get the previous Pad state - u32 last_entry_index = (pad_data->index - 1) % pad_data->entries.size(); - PadState old_state = pad_data->entries[last_entry_index].current_state; - - // Compute bitmask with 1s for bits different from the old state - PadState changed; - changed.hex = (next_state.hex ^ old_state.hex); - - // Compute what was added - PadState additions; - additions.hex = changed.hex & next_state.hex; - - // Compute what was removed - PadState removals; - removals.hex = changed.hex & old_state.hex; - - // Get the current Pad entry - PadDataEntry* current_pad_entry = &pad_data->entries[pad_data->index]; - - // Update entry properties - current_pad_entry->current_state.hex = next_state.hex; - current_pad_entry->delta_additions.hex = additions.hex; - current_pad_entry->delta_removals.hex = removals.hex; - - // Set circle Pad - current_pad_entry->circle_pad_x = next_circle_x; - current_pad_entry->circle_pad_y = next_circle_y; - - // If we just updated index 0, provide a new timestamp - if (pad_data->index == 0) { - pad_data->index_reset_ticks_previous = pad_data->index_reset_ticks; - pad_data->index_reset_ticks = (s64)Core::g_app_core->GetTicks(); - } - - // Signal both handles when there's an update to Pad or touch - Kernel::SignalEvent(event_pad_or_touch_1); - Kernel::SignalEvent(event_pad_or_touch_2); -} - - -// TODO(peachum): -// Add a method for setting analog input from joystick device for the circle Pad. -// -// This method should: -// * Be called after both PadButton<Press, Release>(). -// * Be called before PadUpdateComplete() -// * Set current PadEntry.circle_pad_<axis> using analog data -// * Set PadData.raw_circle_pad_data -// * Set PadData.current_state.circle_right = 1 if current PadEntry.circle_pad_x >= 41 -// * Set PadData.current_state.circle_up = 1 if current PadEntry.circle_pad_y >= 41 -// * Set PadData.current_state.circle_left = 1 if current PadEntry.circle_pad_x <= -41 -// * Set PadData.current_state.circle_right = 1 if current PadEntry.circle_pad_y <= -41 - - -/** - * HID_User::GetIPCHandles service function - * Inputs: - * None - * Outputs: - * 1 : Result of function, 0 on success, otherwise error code - * 2 : Unused - * 3 : Handle to HID_User shared memory - * 4 : Event signaled by HID_User - * 5 : Event signaled by HID_User - * 6 : Event signaled by HID_User - * 7 : Gyroscope event - * 8 : Event signaled by HID_User - */ -static void GetIPCHandles(Service::Interface* self) { - u32* cmd_buff = Kernel::GetCommandBuffer(); - - cmd_buff[1] = 0; // No error - cmd_buff[3] = shared_mem; - cmd_buff[4] = event_pad_or_touch_1; - cmd_buff[5] = event_pad_or_touch_2; - cmd_buff[6] = event_accelerometer; - cmd_buff[7] = event_gyroscope; - cmd_buff[8] = event_debug_pad; -} - -const Interface::FunctionInfo FunctionTable[] = { - {0x000A0000, GetIPCHandles, "GetIPCHandles"}, - {0x000B0000, nullptr, "StartAnalogStickCalibration"}, - {0x000E0000, nullptr, "GetAnalogStickCalibrateParam"}, - {0x00110000, nullptr, "EnableAccelerometer"}, - {0x00120000, nullptr, "DisableAccelerometer"}, - {0x00130000, nullptr, "EnableGyroscopeLow"}, - {0x00140000, nullptr, "DisableGyroscopeLow"}, - {0x00150000, nullptr, "GetGyroscopeLowRawToDpsCoefficient"}, - {0x00160000, nullptr, "GetGyroscopeLowCalibrateParam"}, - {0x00170000, nullptr, "GetSoundVolume"}, -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Interface class - -Interface::Interface() { - shared_mem = Kernel::CreateSharedMemory("HID_User:SharedMem"); // Create shared memory object - - // Create event handles - event_pad_or_touch_1 = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID_User:EventPadOrTouch1"); - event_pad_or_touch_2 = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID_User:EventPadOrTouch2"); - event_accelerometer = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID_User:EventAccelerometer"); - event_gyroscope = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID_User:EventGyroscope"); - event_debug_pad = Kernel::CreateEvent(RESETTYPE_ONESHOT, "HID_User:EventDebugPad"); - - Register(FunctionTable, ARRAY_SIZE(FunctionTable)); -} - -} // namespace diff --git a/src/core/hle/service/ptm_play.cpp b/src/core/hle/service/ptm_play.cpp new file mode 100644 index 000000000..ae9e2925c --- /dev/null +++ b/src/core/hle/service/ptm_play.cpp @@ -0,0 +1,28 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "common/log.h" +#include "core/hle/hle.h" +#include "core/hle/service/ptm_play.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace PTM_PLAY + +namespace PTM_PLAY { + +const Interface::FunctionInfo FunctionTable[] = { + { 0x08070082, nullptr, "GetPlayHistory" }, + { 0x08080000, nullptr, "GetPlayHistoryStart" }, + { 0x08090000, nullptr, "GetPlayHistoryLength" }, + { 0x080B0080, nullptr, "CalcPlayHistoryStart" }, +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Interface class + +Interface::Interface() { + Register(FunctionTable, ARRAY_SIZE(FunctionTable)); +} + +} // namespace diff --git a/src/core/hle/service/ptm_play.h b/src/core/hle/service/ptm_play.h new file mode 100644 index 000000000..2f4f0d6fd --- /dev/null +++ b/src/core/hle/service/ptm_play.h @@ -0,0 +1,23 @@ +// Copyright 2015 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include "core/hle/service/service.h" + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// Namespace PTM_PLAY + +namespace PTM_PLAY { + +class Interface : public Service::Interface { +public: + Interface(); + +std::string GetPortName() const override { + return "ptm:play"; +} +}; + +} // namespace diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index 446ed5164..444a4eab1 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -14,6 +14,7 @@ #include "core/hle/service/apt_s.h" #include "core/hle/service/apt_u.h" #include "core/hle/service/boss_u.h" +#include "core/hle/service/cam_u.h" #include "core/hle/service/cecd_u.h" #include "core/hle/service/cfg/cfg_i.h" #include "core/hle/service/cfg/cfg_s.h" @@ -24,7 +25,8 @@ #include "core/hle/service/fs/fs_user.h" #include "core/hle/service/frd_u.h" #include "core/hle/service/gsp_gpu.h" -#include "core/hle/service/hid_user.h" +#include "core/hle/service/hid/hid_spvr.h" +#include "core/hle/service/hid/hid_user.h" #include "core/hle/service/http_c.h" #include "core/hle/service/ir_rst.h" #include "core/hle/service/ir_u.h" @@ -35,6 +37,7 @@ #include "core/hle/service/nim_aoc.h" #include "core/hle/service/nwm_uds.h" #include "core/hle/service/pm_app.h" +#include "core/hle/service/ptm_play.h" #include "core/hle/service/ptm_u.h" #include "core/hle/service/ptm_sysm.h" #include "core/hle/service/soc_u.h" @@ -91,6 +94,7 @@ void Init() { g_manager->AddService(new APT_S::Interface); g_manager->AddService(new APT_U::Interface); g_manager->AddService(new BOSS_U::Interface); + g_manager->AddService(new CAM_U::Interface); g_manager->AddService(new CECD_U::Interface); g_manager->AddService(new CFG_I::Interface); g_manager->AddService(new CFG_S::Interface); @@ -101,6 +105,7 @@ void Init() { g_manager->AddService(new FRD_U::Interface); g_manager->AddService(new FS::FSUserInterface); g_manager->AddService(new GSP_GPU::Interface); + g_manager->AddService(new HID_SPVR::Interface); g_manager->AddService(new HID_User::Interface); g_manager->AddService(new HTTP_C::Interface); g_manager->AddService(new IR_RST::Interface); @@ -112,6 +117,7 @@ void Init() { g_manager->AddService(new NIM_AOC::Interface); g_manager->AddService(new NWM_UDS::Interface); g_manager->AddService(new PM_APP::Interface); + g_manager->AddService(new PTM_PLAY::Interface); g_manager->AddService(new PTM_U::Interface); g_manager->AddService(new PTM_SYSM::Interface); g_manager->AddService(new SOC_U::Interface); diff --git a/src/core/hle/service/srv.cpp b/src/core/hle/service/srv.cpp index ac5f30a28..082834cfe 100644 --- a/src/core/hle/service/srv.cpp +++ b/src/core/hle/service/srv.cpp @@ -24,7 +24,7 @@ static void GetProcSemaphore(Service::Interface* self) { // TODO(bunnei): Change to a semaphore once these have been implemented g_event_handle = Kernel::CreateEvent(RESETTYPE_ONESHOT, "SRV:Event"); - Kernel::SetEventLocked(g_event_handle, false); + Kernel::ClearEvent(g_event_handle); cmd_buff[1] = 0; // No error cmd_buff[3] = g_event_handle; diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp index a487f757c..2d922046e 100644 --- a/src/core/hle/svc.cpp +++ b/src/core/hle/svc.cpp @@ -29,6 +29,9 @@ using Kernel::SharedPtr; namespace SVC { +/// An invalid result code that is meant to be overwritten when a thread resumes from waiting +const ResultCode RESULT_INVALID(0xDEADC0DE); + enum ControlMemoryOperation { MEMORY_OPERATION_HEAP = 0x00000003, MEMORY_OPERATION_GSP_HEAP = 0x00010003, @@ -103,12 +106,7 @@ static Result SendSyncRequest(Handle handle) { LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s)", handle, session->GetName().c_str()); - ResultVal<bool> wait = session->SyncRequest(); - if (wait.Succeeded() && *wait) { - Kernel::WaitCurrentThread(WAITTYPE_SYNCH); // TODO(bunnei): Is this correct? - } - - return wait.Code().raw; + return session->SyncRequest().Code().raw; } /// Close a handle @@ -120,64 +118,122 @@ static Result CloseHandle(Handle handle) { /// Wait for a handle to synchronize, timeout after the specified nanoseconds static Result WaitSynchronization1(Handle handle, s64 nano_seconds) { - SharedPtr<Kernel::Object> object = Kernel::g_handle_table.GetGeneric(handle); + auto object = Kernel::g_handle_table.GetWaitObject(handle); if (object == nullptr) return InvalidHandle(ErrorModule::Kernel).raw; LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s:%s), nanoseconds=%lld", handle, object->GetTypeName().c_str(), object->GetName().c_str(), nano_seconds); - ResultVal<bool> wait = object->WaitSynchronization(); - // Check for next thread to schedule - if (wait.Succeeded() && *wait) { + if (object->ShouldWait()) { + + object->AddWaitingThread(Kernel::GetCurrentThread()); + Kernel::WaitCurrentThread_WaitSynchronization(object, false, false); + // Create an event to wake the thread up after the specified nanosecond delay has passed Kernel::WakeThreadAfterDelay(Kernel::GetCurrentThread(), nano_seconds); + HLE::Reschedule(__func__); + + // NOTE: output of this SVC will be set later depending on how the thread resumes + return RESULT_INVALID.raw; } - return wait.Code().raw; + object->Acquire(); + + return RESULT_SUCCESS.raw; } /// Wait for the given handles to synchronize, timeout after the specified nanoseconds -static Result WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, bool wait_all, - s64 nano_seconds) { - - // TODO(bunnei): Do something with nano_seconds, currently ignoring this - bool unlock_all = true; - bool wait_infinite = (nano_seconds == -1); // Used to wait until a thread has terminated - - LOG_TRACE(Kernel_SVC, "called handle_count=%d, wait_all=%s, nanoseconds=%lld", - handle_count, (wait_all ? "true" : "false"), nano_seconds); - - // Iterate through each handle, synchronize kernel object - for (s32 i = 0; i < handle_count; i++) { - SharedPtr<Kernel::Object> object = Kernel::g_handle_table.GetGeneric(handles[i]); - if (object == nullptr) - return InvalidHandle(ErrorModule::Kernel).raw; - - LOG_TRACE(Kernel_SVC, "\thandle[%d] = 0x%08X(%s:%s)", i, handles[i], - object->GetTypeName().c_str(), object->GetName().c_str()); - - // TODO(yuriks): Verify how the real function behaves when an error happens here - ResultVal<bool> wait_result = object->WaitSynchronization(); - bool wait = wait_result.Succeeded() && *wait_result; - - if (!wait && !wait_all) { - *out = i; - return RESULT_SUCCESS.raw; - } else { - unlock_all = false; +static Result WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, bool wait_all, s64 nano_seconds) { + bool wait_thread = !wait_all; + int handle_index = 0; + + // Check if 'handles' is invalid + if (handles == nullptr) + return ResultCode(ErrorDescription::InvalidPointer, ErrorModule::Kernel, ErrorSummary::InvalidArgument, ErrorLevel::Permanent).raw; + + // NOTE: on real hardware, there is no nullptr check for 'out' (tested with firmware 4.4). If + // this happens, the running application will crash. + _assert_msg_(Kernel, out != nullptr, "invalid output pointer specified!"); + + // Check if 'handle_count' is invalid + if (handle_count < 0) + return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS, ErrorSummary::InvalidArgument, ErrorLevel::Usage).raw; + + // If 'handle_count' is non-zero, iterate through each handle and wait the current thread if + // necessary + if (handle_count != 0) { + bool selected = false; // True once an object has been selected + for (int i = 0; i < handle_count; ++i) { + auto object = Kernel::g_handle_table.GetWaitObject(handles[i]); + if (object == nullptr) + return InvalidHandle(ErrorModule::Kernel).raw; + + // Check if the current thread should wait on this object... + if (object->ShouldWait()) { + + // Check we are waiting on all objects... + if (wait_all) + // Wait the thread + wait_thread = true; + } else { + // Do not wait on this object, check if this object should be selected... + if (!wait_all && !selected) { + // Do not wait the thread + wait_thread = false; + handle_index = i; + selected = true; + } + } + } + } else { + // If no handles were passed in, put the thread to sleep only when 'wait_all' is false + // NOTE: This should deadlock the current thread if no timeout was specified + if (!wait_all) { + wait_thread = true; + Kernel::WaitCurrentThread_WaitSynchronization(nullptr, true, wait_all); + } + } + + // If thread should wait, then set its state to waiting and then reschedule... + if (wait_thread) { + + // Actually wait the current thread on each object if we decided to wait... + for (int i = 0; i < handle_count; ++i) { + auto object = Kernel::g_handle_table.GetWaitObject(handles[i]); + object->AddWaitingThread(Kernel::GetCurrentThread()); + Kernel::WaitCurrentThread_WaitSynchronization(object, true, wait_all); } + + // Create an event to wake the thread up after the specified nanosecond delay has passed + Kernel::WakeThreadAfterDelay(Kernel::GetCurrentThread(), nano_seconds); + + HLE::Reschedule(__func__); + + // NOTE: output of this SVC will be set later depending on how the thread resumes + return RESULT_INVALID.raw; } - if (wait_all && unlock_all) { - *out = handle_count; - return RESULT_SUCCESS.raw; + // Acquire objects if we did not wait... + for (int i = 0; i < handle_count; ++i) { + auto object = Kernel::g_handle_table.GetWaitObject(handles[i]); + + // Acquire the object if it is not waiting... + if (!object->ShouldWait()) { + object->Acquire(); + + // If this was the first non-waiting object and 'wait_all' is false, don't acquire + // any other objects + if (!wait_all) + break; + } } - // Check for next thread to schedule - HLE::Reschedule(__func__); + // TODO(bunnei): If 'wait_all' is true, this is probably wrong. However, real hardware does + // not seem to set it to any meaningful value. + *out = wait_all ? 0 : handle_index; return RESULT_SUCCESS.raw; } @@ -351,6 +407,7 @@ static Result DuplicateHandle(Handle* out, Handle handle) { /// Signals an event static Result SignalEvent(Handle evt) { LOG_TRACE(Kernel_SVC, "called event=0x%08X", evt); + HLE::Reschedule(__func__); return Kernel::SignalEvent(evt).raw; } @@ -391,7 +448,7 @@ static void SleepThread(s64 nanoseconds) { LOG_TRACE(Kernel_SVC, "called nanoseconds=%lld", nanoseconds); // Sleep current thread and check for next thread to schedule - Kernel::WaitCurrentThread(WAITTYPE_SLEEP); + Kernel::WaitCurrentThread_Sleep(); // Create an event to wake the thread up after the specified nanosecond delay has passed Kernel::WakeThreadAfterDelay(Kernel::GetCurrentThread(), nanoseconds); diff --git a/src/core/loader/3dsx.cpp b/src/core/loader/3dsx.cpp index 4d072871a..958dd03e8 100644 --- a/src/core/loader/3dsx.cpp +++ b/src/core/loader/3dsx.cpp @@ -13,11 +13,9 @@ #include "3dsx.h" - namespace Loader { - -/** +/** * File layout: * - File header * - Code, rodata and data relocation table headers @@ -46,7 +44,6 @@ enum THREEDSX_Error { static const u32 RELOCBUFSIZE = 512; // File header -static const u32 THREEDSX_MAGIC = 0x58534433; // '3DSX' #pragma pack(1) struct THREEDSX_Header { @@ -64,9 +61,9 @@ struct THREEDSX_Header struct THREEDSX_RelocHdr { // # of absolute relocations (that is, fix address to post-relocation memory layout) - u32 cross_segment_absolute; + u32 cross_segment_absolute; // # of cross-segment relative relocations (that is, 32bit signed offsets that need to be patched) - u32 cross_segment_relative; + u32 cross_segment_relative; // more? // Relocations are written in this order: @@ -88,12 +85,7 @@ struct THREEloadinfo u32 seg_sizes[3]; }; -class THREEDSXReader { -public: - static int Load3DSXFile(const std::string& filename, u32 base_addr); -}; - -static u32 TranslateAddr(u32 addr, THREEloadinfo *loadinfo, u32* offsets) +static u32 TranslateAddr(u32 addr, const THREEloadinfo *loadinfo, u32* offsets) { if (addr < offsets[0]) return loadinfo->seg_addrs[0] + addr; @@ -102,12 +94,14 @@ static u32 TranslateAddr(u32 addr, THREEloadinfo *loadinfo, u32* offsets) return loadinfo->seg_addrs[2] + addr - offsets[1]; } -int THREEDSXReader::Load3DSXFile(const std::string& filename, u32 base_addr) +static THREEDSX_Error Load3DSXFile(FileUtil::IOFile& file, u32 base_addr) { - FileUtil::IOFile file(filename, "rb"); - if (!file.IsOpen()) { + if (!file.IsOpen()) return ERROR_FILE; - } + + // Reset read pointer in case this file has been read before. + file.Seek(0, SEEK_SET); + THREEDSX_Header hdr; if (file.ReadBytes(&hdr, sizeof(hdr)) != sizeof(hdr)) return ERROR_READ; @@ -136,8 +130,9 @@ int THREEDSXReader::Load3DSXFile(const std::string& filename, u32 base_addr) // Read the relocation headers u32* relocs = (u32*)(loadinfo.seg_ptrs[2] + hdr.data_seg_size); - for (u32 current_segment = 0; current_segment < 3; current_segment++) { - if (file.ReadBytes(&relocs[current_segment*n_reloc_tables], n_reloc_tables * 4) != n_reloc_tables * 4) + for (unsigned current_segment : {0, 1, 2}) { + size_t size = n_reloc_tables * 4; + if (file.ReadBytes(&relocs[current_segment * n_reloc_tables], size) != size) return ERROR_READ; } @@ -153,9 +148,9 @@ int THREEDSXReader::Load3DSXFile(const std::string& filename, u32 base_addr) memset((char*)loadinfo.seg_ptrs[2] + hdr.data_seg_size - hdr.bss_size, 0, hdr.bss_size); // Relocate the segments - for (u32 current_segment = 0; current_segment < 3; current_segment++) { - for (u32 current_segment_reloc_table = 0; current_segment_reloc_table < n_reloc_tables; current_segment_reloc_table++) { - u32 n_relocs = relocs[current_segment*n_reloc_tables + current_segment_reloc_table]; + for (unsigned current_segment : {0, 1, 2}) { + for (unsigned current_segment_reloc_table = 0; current_segment_reloc_table < n_reloc_tables; current_segment_reloc_table++) { + u32 n_relocs = relocs[current_segment * n_reloc_tables + current_segment_reloc_table]; if (current_segment_reloc_table >= 2) { // We are not using this table - ignore it because we don't know what it dose file.Seek(n_relocs*sizeof(THREEDSX_Reloc), SEEK_CUR); @@ -164,29 +159,35 @@ int THREEDSXReader::Load3DSXFile(const std::string& filename, u32 base_addr) static THREEDSX_Reloc reloc_table[RELOCBUFSIZE]; u32* pos = (u32*)loadinfo.seg_ptrs[current_segment]; - u32* end_pos = pos + (loadinfo.seg_sizes[current_segment] / 4); + const u32* end_pos = pos + (loadinfo.seg_sizes[current_segment] / 4); while (n_relocs) { u32 remaining = std::min(RELOCBUFSIZE, n_relocs); n_relocs -= remaining; - if (file.ReadBytes(reloc_table, remaining*sizeof(THREEDSX_Reloc)) != remaining*sizeof(THREEDSX_Reloc)) + if (file.ReadBytes(reloc_table, remaining * sizeof(THREEDSX_Reloc)) != remaining * sizeof(THREEDSX_Reloc)) return ERROR_READ; - for (u32 current_inprogress = 0; current_inprogress < remaining && pos < end_pos; current_inprogress++) { - LOG_TRACE(Loader, "(t=%d,skip=%u,patch=%u)\n", - current_segment_reloc_table, (u32)reloc_table[current_inprogress].skip, (u32)reloc_table[current_inprogress].patch); - pos += reloc_table[current_inprogress].skip; - s32 num_patches = reloc_table[current_inprogress].patch; + for (unsigned current_inprogress = 0; current_inprogress < remaining && pos < end_pos; current_inprogress++) { + const auto& table = reloc_table[current_inprogress]; + LOG_TRACE(Loader, "(t=%d,skip=%u,patch=%u)\n", current_segment_reloc_table, + (u32)table.skip, (u32)table.patch); + pos += table.skip; + s32 num_patches = table.patch; while (0 < num_patches && pos < end_pos) { u32 in_addr = (char*)pos - (char*)&all_mem[0]; u32 addr = TranslateAddr(*pos, &loadinfo, offsets); LOG_TRACE(Loader, "Patching %08X <-- rel(%08X,%d) (%08X)\n", - base_addr + in_addr, addr, current_segment_reloc_table, *pos); + base_addr + in_addr, addr, current_segment_reloc_table, *pos); switch (current_segment_reloc_table) { - case 0: *pos = (addr); break; - case 1: *pos = (addr - in_addr); break; - default: break; //this should never happen + case 0: + *pos = (addr); + break; + case 1: + *pos = (addr - in_addr); + break; + default: + break; //this should never happen } pos++; num_patches--; @@ -207,28 +208,30 @@ int THREEDSXReader::Load3DSXFile(const std::string& filename, u32 base_addr) return ERROR_NONE; } - /// AppLoader_DSX constructor - AppLoader_THREEDSX::AppLoader_THREEDSX(const std::string& filename) : filename(filename) { - } +FileType AppLoader_THREEDSX::IdentifyType(FileUtil::IOFile& file) { + u32 magic; + file.Seek(0, SEEK_SET); + if (1 != file.ReadArray<u32>(&magic, 1)) + return FileType::Error; - /// AppLoader_DSX destructor - AppLoader_THREEDSX::~AppLoader_THREEDSX() { - } + if (MakeMagic('3', 'D', 'S', 'X') == magic) + return FileType::THREEDSX; - /** - * Loads a 3DSX file - * @return Success on success, otherwise Error - */ - ResultStatus AppLoader_THREEDSX::Load() { - LOG_INFO(Loader, "Loading 3DSX file %s...", filename.c_str()); - FileUtil::IOFile file(filename, "rb"); - if (file.IsOpen()) { - THREEDSXReader::Load3DSXFile(filename, 0x00100000); - Kernel::LoadExec(0x00100000); - } else { - return ResultStatus::Error; - } - return ResultStatus::Success; - } + return FileType::Error; +} + +ResultStatus AppLoader_THREEDSX::Load() { + if (is_loaded) + return ResultStatus::ErrorAlreadyLoaded; + + if (!file->IsOpen()) + return ResultStatus::Error; + + Load3DSXFile(*file, 0x00100000); + Kernel::LoadExec(0x00100000); + + is_loaded = true; + return ResultStatus::Success; +} } // namespace Loader diff --git a/src/core/loader/3dsx.h b/src/core/loader/3dsx.h index da8836662..a11667400 100644 --- a/src/core/loader/3dsx.h +++ b/src/core/loader/3dsx.h @@ -15,18 +15,20 @@ namespace Loader { /// Loads an 3DSX file class AppLoader_THREEDSX final : public AppLoader { public: - AppLoader_THREEDSX(const std::string& filename); - ~AppLoader_THREEDSX() override; + AppLoader_THREEDSX(std::unique_ptr<FileUtil::IOFile>&& file) : AppLoader(std::move(file)) { } + + /** + * Returns the type of the file + * @param file FileUtil::IOFile open file + * @return FileType found, or FileType::Error if this loader doesn't know it + */ + static FileType IdentifyType(FileUtil::IOFile& file); /** * Load the bootable file * @return ResultStatus result of function */ ResultStatus Load() override; - -private: - std::string filename; - bool is_loaded; }; } // namespace Loader diff --git a/src/core/loader/elf.cpp b/src/core/loader/elf.cpp index 3ca60c072..e7e5df408 100644 --- a/src/core/loader/elf.cpp +++ b/src/core/loader/elf.cpp @@ -18,25 +18,25 @@ // File type enum ElfType { - ET_NONE = 0, - ET_REL = 1, - ET_EXEC = 2, - ET_DYN = 3, - ET_CORE = 4, + ET_NONE = 0, + ET_REL = 1, + ET_EXEC = 2, + ET_DYN = 3, + ET_CORE = 4, ET_LOPROC = 0xFF00, ET_HIPROC = 0xFFFF, }; // Machine/Architecture enum ElfMachine { - EM_NONE = 0, - EM_M32 = 1, + EM_NONE = 0, + EM_M32 = 1, EM_SPARC = 2, - EM_386 = 3, - EM_68K = 4, - EM_88K = 5, - EM_860 = 7, - EM_MIPS = 8 + EM_386 = 3, + EM_68K = 4, + EM_88K = 5, + EM_860 = 7, + EM_MIPS = 8 }; // File version @@ -54,12 +54,6 @@ enum ElfMachine { #define EI_PAD 7 #define EI_NIDENT 16 -// Magic number -#define ELFMAG0 0x7F -#define ELFMAG1 'E' -#define ELFMAG2 'L' -#define ELFMAG3 'F' - // Sections constants // Section types @@ -83,10 +77,10 @@ enum ElfMachine { // Section flags enum ElfSectionFlags { - SHF_WRITE = 0x1, - SHF_ALLOC = 0x2, + SHF_WRITE = 0x1, + SHF_ALLOC = 0x2, SHF_EXECINSTR = 0x4, - SHF_MASKPROC = 0xF0000000, + SHF_MASKPROC = 0xF0000000, }; // Segment types @@ -100,11 +94,11 @@ enum ElfSectionFlags #define PT_LOPROC 0x70000000 #define PT_HIPROC 0x7FFFFFFF -typedef unsigned int Elf32_Addr; +typedef unsigned int Elf32_Addr; typedef unsigned short Elf32_Half; -typedef unsigned int Elf32_Off; -typedef signed int Elf32_Sword; -typedef unsigned int Elf32_Word; +typedef unsigned int Elf32_Off; +typedef signed int Elf32_Sword; +typedef unsigned int Elf32_Word; //////////////////////////////////////////////////////////////////////////////////////////////////// // ELF file header @@ -188,7 +182,6 @@ private: public: ElfReader(void *ptr); - ~ElfReader() { } u32 Read32(int off) const { return base32[off >> 2]; } @@ -197,7 +190,7 @@ public: ElfMachine GetMachine() const { return (ElfMachine)(header->e_machine); } u32 GetEntryPoint() const { return entryPoint; } u32 GetFlags() const { return (u32)(header->e_flags); } - bool LoadInto(u32 vaddr); + void LoadInto(u32 vaddr); bool LoadSymbols(); int GetNumSegments() const { return (int)(header->e_phnum); } @@ -229,11 +222,11 @@ public: ElfReader::ElfReader(void *ptr) { base = (char*)ptr; - base32 = (u32 *)ptr; + base32 = (u32*)ptr; header = (Elf32_Ehdr*)ptr; - segments = (Elf32_Phdr *)(base + header->e_phoff); - sections = (Elf32_Shdr *)(base + header->e_shoff); + segments = (Elf32_Phdr*)(base + header->e_phoff); + sections = (Elf32_Shdr*)(base + header->e_shoff); entryPoint = header->e_entry; @@ -245,7 +238,7 @@ const char *ElfReader::GetSectionName(int section) const { return nullptr; int name_offset = sections[section].sh_name; - char *ptr = (char*)GetSectionDataPtr(header->e_shstrndx); + const char* ptr = (char*)GetSectionDataPtr(header->e_shstrndx); if (ptr) return ptr + name_offset; @@ -253,7 +246,7 @@ const char *ElfReader::GetSectionName(int section) const { return nullptr; } -bool ElfReader::LoadInto(u32 vaddr) { +void ElfReader::LoadInto(u32 vaddr) { LOG_DEBUG(Loader, "String section: %i", header->e_shstrndx); // Should we relocate? @@ -271,20 +264,19 @@ bool ElfReader::LoadInto(u32 vaddr) { u32 segment_addr[32]; u32 base_addr = relocate ? vaddr : 0; - for (int i = 0; i < header->e_phnum; i++) { - Elf32_Phdr *p = segments + i; + for (unsigned i = 0; i < header->e_phnum; i++) { + Elf32_Phdr* p = segments + i; LOG_DEBUG(Loader, "Type: %i Vaddr: %08x Filesz: %i Memsz: %i ", p->p_type, p->p_vaddr, - p->p_filesz, p->p_memsz); + p->p_filesz, p->p_memsz); if (p->p_type == PT_LOAD) { segment_addr[i] = base_addr + p->p_vaddr; memcpy(Memory::GetPointer(segment_addr[i]), GetSegmentPtr(i), p->p_filesz); LOG_DEBUG(Loader, "Loadable Segment Copied to %08x, size %08x", segment_addr[i], - p->p_memsz); + p->p_memsz); } } LOG_DEBUG(Loader, "Done loading."); - return true; } SectionID ElfReader::GetSectionByName(const char *name, int firstSection) const { @@ -305,9 +297,9 @@ bool ElfReader::LoadSymbols() { const char *stringBase = (const char *)GetSectionDataPtr(stringSection); //We have a symbol table! - Elf32_Sym *symtab = (Elf32_Sym *)(GetSectionDataPtr(sec)); + Elf32_Sym* symtab = (Elf32_Sym *)(GetSectionDataPtr(sec)); int numSymbols = sections[sec].sh_size / sizeof(Elf32_Sym); - for (int sym = 0; sym < numSymbols; sym++) { + for (unsigned sym = 0; sym < numSymbols; sym++) { int size = symtab[sym].st_size; if (size == 0) continue; @@ -330,40 +322,38 @@ bool ElfReader::LoadSymbols() { namespace Loader { -/// AppLoader_ELF constructor -AppLoader_ELF::AppLoader_ELF(const std::string& filename) : is_loaded(false) { - this->filename = filename; -} +FileType AppLoader_ELF::IdentifyType(FileUtil::IOFile& file) { + u32 magic; + file.Seek(0, SEEK_SET); + if (1 != file.ReadArray<u32>(&magic, 1)) + return FileType::Error; + + if (MakeMagic('\x7f', 'E', 'L', 'F') == magic) + return FileType::ELF; -/// AppLoader_NCCH destructor -AppLoader_ELF::~AppLoader_ELF() { + return FileType::Error; } -/** - * Loads an NCCH file (e.g. from a CCI, or the first NCCH in a CXI) - * @param error_string Pointer to string to put error message if an error has occurred - * @todo Move NCSD parsing out of here and create a separate function for loading these - * @return True on success, otherwise false - */ ResultStatus AppLoader_ELF::Load() { - LOG_INFO(Loader, "Loading ELF file %s...", filename.c_str()); - if (is_loaded) return ResultStatus::ErrorAlreadyLoaded; - FileUtil::IOFile file(filename, "rb"); + if (!file->IsOpen()) + return ResultStatus::Error; - if (file.IsOpen()) { - u32 size = (u32)file.GetSize(); - std::unique_ptr<u8[]> buffer(new u8[size]); - file.ReadBytes(&buffer[0], size); + // Reset read pointer in case this file has been read before. + file->Seek(0, SEEK_SET); - ElfReader elf_reader(&buffer[0]); - elf_reader.LoadInto(0x00100000); - Kernel::LoadExec(elf_reader.GetEntryPoint()); - } else { + u32 size = static_cast<u32>(file->GetSize()); + std::unique_ptr<u8[]> buffer(new u8[size]); + if (file->ReadBytes(&buffer[0], size) != size) return ResultStatus::Error; - } + + ElfReader elf_reader(&buffer[0]); + elf_reader.LoadInto(0x00100000); + Kernel::LoadExec(elf_reader.GetEntryPoint()); + + is_loaded = true; return ResultStatus::Success; } diff --git a/src/core/loader/elf.h b/src/core/loader/elf.h index c221cce6d..b6e6651f5 100644 --- a/src/core/loader/elf.h +++ b/src/core/loader/elf.h @@ -15,18 +15,20 @@ namespace Loader { /// Loads an ELF/AXF file class AppLoader_ELF final : public AppLoader { public: - AppLoader_ELF(const std::string& filename); - ~AppLoader_ELF() override; + AppLoader_ELF(std::unique_ptr<FileUtil::IOFile>&& file) : AppLoader(std::move(file)) { } + + /** + * Returns the type of the file + * @param file FileUtil::IOFile open file + * @return FileType found, or FileType::Error if this loader doesn't know it + */ + static FileType IdentifyType(FileUtil::IOFile& file); /** * Load the bootable file * @return ResultStatus result of function */ ResultStatus Load() override; - -private: - std::string filename; - bool is_loaded; }; } // namespace Loader diff --git a/src/core/loader/loader.cpp b/src/core/loader/loader.cpp index 45cf425df..60460292d 100644 --- a/src/core/loader/loader.cpp +++ b/src/core/loader/loader.cpp @@ -19,11 +19,32 @@ namespace Loader { /** * Identifies the type of a bootable file + * @param file open file + * @return FileType of file + */ +static FileType IdentifyFile(FileUtil::IOFile& file) { + FileType type; + +#define CHECK_TYPE(loader) \ + type = AppLoader_##loader::IdentifyType(file); \ + if (FileType::Error != type) \ + return type; + + CHECK_TYPE(THREEDSX) + CHECK_TYPE(ELF) + CHECK_TYPE(NCCH) + +#undef CHECK_TYPE + + return FileType::Unknown; +} + +/** + * Guess the type of a bootable file from its extension * @param filename String filename of bootable file - * @todo (ShizZy) this function sucks... make it actually check file contents etc. * @return FileType of file */ -FileType IdentifyFile(const std::string &filename) { +static FileType GuessFromFilename(const std::string& filename) { if (filename.size() == 0) { LOG_ERROR(Loader, "invalid filename %s", filename.c_str()); return FileType::Error; @@ -34,47 +55,74 @@ FileType IdentifyFile(const std::string &filename) { return FileType::Unknown; std::string extension = Common::ToLower(filename.substr(extension_loc)); - // TODO(bunnei): Do actual filetype checking instead of naively checking the extension - if (extension == ".elf") { + if (extension == ".elf") return FileType::ELF; - } else if (extension == ".axf") { + else if (extension == ".axf") return FileType::ELF; - } else if (extension == ".cxi") { + else if (extension == ".cxi") return FileType::CXI; - } else if (extension == ".cci") { + else if (extension == ".cci") return FileType::CCI; - } else if (extension == ".bin") { + else if (extension == ".bin") return FileType::BIN; - } else if (extension == ".3ds") { + else if (extension == ".3ds") return FileType::CCI; - } else if (extension == ".3dsx") { + else if (extension == ".3dsx") return FileType::THREEDSX; - } return FileType::Unknown; } -/** - * Identifies and loads a bootable file - * @param filename String filename of bootable file - * @return ResultStatus result of function - */ +static const char* GetFileTypeString(FileType type) { + switch (type) { + case FileType::CCI: + return "NCSD"; + case FileType::CXI: + return "NCCH"; + case FileType::ELF: + return "ELF"; + case FileType::THREEDSX: + return "3DSX"; + case FileType::BIN: + return "raw"; + case FileType::Error: + case FileType::Unknown: + return "unknown"; + } +} + ResultStatus LoadFile(const std::string& filename) { - LOG_INFO(Loader, "Loading file %s...", filename.c_str()); + std::unique_ptr<FileUtil::IOFile> file(new FileUtil::IOFile(filename, "rb")); + if (!file->IsOpen()) { + LOG_ERROR(Loader, "Failed to load file %s", filename.c_str()); + return ResultStatus::Error; + } + + FileType type = IdentifyFile(*file); + FileType filename_type = GuessFromFilename(filename); + + if (type != filename_type) { + LOG_WARNING(Loader, "File %s has a different type than its extension.", filename.c_str()); + if (FileType::Unknown == type) + type = filename_type; + } - switch (IdentifyFile(filename)) { + LOG_INFO(Loader, "Loading file %s as %s...", filename.c_str(), GetFileTypeString(type)); + + switch (type) { //3DSX file format... case FileType::THREEDSX: - return AppLoader_THREEDSX(filename).Load(); + return AppLoader_THREEDSX(std::move(file)).Load(); // Standard ELF file format... case FileType::ELF: - return AppLoader_ELF(filename).Load(); + return AppLoader_ELF(std::move(file)).Load(); // NCCH/NCSD container formats... case FileType::CXI: - case FileType::CCI: { - AppLoader_NCCH app_loader(filename); + case FileType::CCI: + { + AppLoader_NCCH app_loader(std::move(file)); // Load application and RomFS if (ResultStatus::Success == app_loader.Load()) { @@ -88,16 +136,11 @@ ResultStatus LoadFile(const std::string& filename) { // Raw BIN file format... case FileType::BIN: { - LOG_INFO(Loader, "Loading BIN file %s...", filename.c_str()); - - FileUtil::IOFile file(filename, "rb"); - - if (file.IsOpen()) { - file.ReadBytes(Memory::GetPointer(Memory::EXEFS_CODE_VADDR), (size_t)file.GetSize()); - Kernel::LoadExec(Memory::EXEFS_CODE_VADDR); - } else { + size_t size = (size_t)file->GetSize(); + if (file->ReadBytes(Memory::GetPointer(Memory::EXEFS_CODE_VADDR), size) != size) return ResultStatus::Error; - } + + Kernel::LoadExec(Memory::EXEFS_CODE_VADDR); return ResultStatus::Success; } @@ -106,10 +149,11 @@ ResultStatus LoadFile(const std::string& filename) { // IdentifyFile could know identify file type... case FileType::Unknown: - - default: + { + LOG_CRITICAL(Loader, "File %s is of unknown type."); return ResultStatus::ErrorInvalidFormat; } + } return ResultStatus::Error; } diff --git a/src/core/loader/loader.h b/src/core/loader/loader.h index ec5534d41..7456b019b 100644 --- a/src/core/loader/loader.h +++ b/src/core/loader/loader.h @@ -7,6 +7,7 @@ #include <vector> #include "common/common.h" +#include "common/file_util.h" //////////////////////////////////////////////////////////////////////////////////////////////////// // Loader namespace @@ -37,10 +38,14 @@ enum class ResultStatus { ErrorMemoryAllocationFailed, }; +static u32 MakeMagic(char a, char b, char c, char d) { + return a | b << 8 | c << 16 | d << 24; +} + /// Interface for loading an application class AppLoader : NonCopyable { public: - AppLoader() { } + AppLoader(std::unique_ptr<FileUtil::IOFile>&& file) : file(std::move(file)) { } virtual ~AppLoader() { } /** @@ -93,14 +98,11 @@ public: virtual ResultStatus ReadRomFS(std::vector<u8>& buffer) const { return ResultStatus::ErrorNotImplemented; } -}; -/** - * Identifies the type of a bootable file - * @param filename String filename of bootable file - * @return FileType of file - */ -FileType IdentifyFile(const std::string &filename); +protected: + std::unique_ptr<FileUtil::IOFile> file; + bool is_loaded = false; +}; /** * Identifies and loads a bootable file diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp index 0dc21699e..aaaa4d650 100644 --- a/src/core/loader/ncch.cpp +++ b/src/core/loader/ncch.cpp @@ -4,8 +4,6 @@ #include <memory> -#include "common/file_util.h" - #include "core/loader/ncch.h" #include "core/hle/kernel/kernel.h" #include "core/mem_map.h" @@ -15,8 +13,8 @@ namespace Loader { -static const int kMaxSections = 8; ///< Maximum number of sections (files) in an ExeFs -static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes) +static const int kMaxSections = 8; ///< Maximum number of sections (files) in an ExeFs +static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes) /** * Get the decompressed size of an LZSS compressed ExeFS file @@ -24,7 +22,7 @@ static const int kBlockSize = 0x200; ///< Size of ExeFS blocks (in bytes) * @param size Size of compressed buffer * @return Size of decompressed buffer */ -static u32 LZSS_GetDecompressedSize(u8* buffer, u32 size) { +static u32 LZSS_GetDecompressedSize(const u8* buffer, u32 size) { u32 offset_size = *(u32*)(buffer + size - 4); return offset_size + size; } @@ -37,9 +35,9 @@ static u32 LZSS_GetDecompressedSize(u8* buffer, u32 size) { * @param decompressed_size Size of decompressed buffer * @return True on success, otherwise false */ -static bool LZSS_Decompress(u8* compressed, u32 compressed_size, u8* decompressed, u32 decompressed_size) { - u8* footer = compressed + compressed_size - 8; - u32 buffer_top_and_bottom = *(u32*)footer; +static bool LZSS_Decompress(const u8* compressed, u32 compressed_size, u8* decompressed, u32 decompressed_size) { + const u8* footer = compressed + compressed_size - 8; + u32 buffer_top_and_bottom = *reinterpret_cast<const u32*>(footer); u32 out = decompressed_size; u32 index = compressed_size - ((buffer_top_and_bottom >> 24) & 0xFF); u32 stop_index = compressed_size - (buffer_top_and_bottom & 0xFFFFFF); @@ -47,22 +45,21 @@ static bool LZSS_Decompress(u8* compressed, u32 compressed_size, u8* decompresse memset(decompressed, 0, decompressed_size); memcpy(decompressed, compressed, compressed_size); - while(index > stop_index) { + while (index > stop_index) { u8 control = compressed[--index]; - for(u32 i = 0; i < 8; i++) { - if(index <= stop_index) + for (unsigned i = 0; i < 8; i++) { + if (index <= stop_index) break; - if(index <= 0) + if (index <= 0) break; - if(out <= 0) + if (out <= 0) break; - if(control & 0x80) { + if (control & 0x80) { // Check if compression is out of bounds - if(index < 2) { + if (index < 2) return false; - } index -= 2; u32 segment_offset = compressed[index] | (compressed[index + 1] << 8); @@ -71,23 +68,21 @@ static bool LZSS_Decompress(u8* compressed, u32 compressed_size, u8* decompresse segment_offset += 2; // Check if compression is out of bounds - if(out < segment_size) { + if (out < segment_size) return false; - } - for(u32 j = 0; j < segment_size; j++) { + + for (unsigned j = 0; j < segment_size; j++) { // Check if compression is out of bounds - if(out + segment_offset >= decompressed_size) { + if (out + segment_offset >= decompressed_size) return false; - } - u8 data = decompressed[out + segment_offset]; + u8 data = decompressed[out + segment_offset]; decompressed[--out] = data; } } else { // Check if compression is out of bounds - if(out < 1) { + if (out < 1) return false; - } decompressed[--out] = compressed[--index]; } control <<= 1; @@ -99,24 +94,21 @@ static bool LZSS_Decompress(u8* compressed, u32 compressed_size, u8* decompresse //////////////////////////////////////////////////////////////////////////////////////////////////// // AppLoader_NCCH class -/// AppLoader_NCCH constructor -AppLoader_NCCH::AppLoader_NCCH(const std::string& filename) { - this->filename = filename; - is_loaded = false; - is_compressed = false; - entry_point = 0; - ncch_offset = 0; - exefs_offset = 0; -} +FileType AppLoader_NCCH::IdentifyType(FileUtil::IOFile& file) { + u32 magic; + file.Seek(0x100, SEEK_SET); + if (1 != file.ReadArray<u32>(&magic, 1)) + return FileType::Error; + + if (MakeMagic('N', 'C', 'S', 'D') == magic) + return FileType::CCI; -/// AppLoader_NCCH destructor -AppLoader_NCCH::~AppLoader_NCCH() { + if (MakeMagic('N', 'C', 'C', 'H') == magic) + return FileType::CXI; + + return FileType::Error; } -/** - * Loads .code section into memory for booting - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::LoadExec() const { if (!is_loaded) return ResultStatus::ErrorNotLoaded; @@ -130,189 +122,144 @@ ResultStatus AppLoader_NCCH::LoadExec() const { return ResultStatus::Error; } -/** - * Reads an application ExeFS section of an NCCH file into AppLoader (e.g. .code, .logo, etc.) - * @param name Name of section to read out of NCCH file - * @param buffer Vector to read data into - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::LoadSectionExeFS(const char* name, std::vector<u8>& buffer) const { + if (!file->IsOpen()) + return ResultStatus::Error; + + LOG_DEBUG(Loader, "%d sections:", kMaxSections); // Iterate through the ExeFs archive until we find the .code file... - FileUtil::IOFile file(filename, "rb"); - if (file.IsOpen()) { - LOG_DEBUG(Loader, "%d sections:", kMaxSections); - for (int i = 0; i < kMaxSections; i++) { - // Load the specified section... - if (strcmp((const char*)exefs_header.section[i].name, name) == 0) { - LOG_DEBUG(Loader, "%d - offset: 0x%08X, size: 0x%08X, name: %s", i, - exefs_header.section[i].offset, exefs_header.section[i].size, - exefs_header.section[i].name); - - s64 section_offset = (exefs_header.section[i].offset + exefs_offset + - sizeof(ExeFs_Header)+ncch_offset); - file.Seek(section_offset, 0); - - // Section is compressed... - if (i == 0 && is_compressed) { - // Read compressed .code section... - std::unique_ptr<u8[]> temp_buffer; - try { - temp_buffer.reset(new u8[exefs_header.section[i].size]); - } catch (std::bad_alloc&) { - return ResultStatus::ErrorMemoryAllocationFailed; - } - file.ReadBytes(&temp_buffer[0], exefs_header.section[i].size); - - // Decompress .code section... - u32 decompressed_size = LZSS_GetDecompressedSize(&temp_buffer[0], - exefs_header.section[i].size); - buffer.resize(decompressed_size); - if (!LZSS_Decompress(&temp_buffer[0], exefs_header.section[i].size, &buffer[0], - decompressed_size)) { - return ResultStatus::ErrorInvalidFormat; - } - // Section is uncompressed... - } - else { - buffer.resize(exefs_header.section[i].size); - file.ReadBytes(&buffer[0], exefs_header.section[i].size); + for (unsigned section_number = 0; section_number < kMaxSections; section_number++) { + const auto& section = exefs_header.section[section_number]; + + // Load the specified section... + if (strcmp(section.name, name) == 0) { + LOG_DEBUG(Loader, "%d - offset: 0x%08X, size: 0x%08X, name: %s", section_number, + section.offset, section.size, section.name); + + s64 section_offset = (section.offset + exefs_offset + sizeof(ExeFs_Header) + ncch_offset); + file->Seek(section_offset, SEEK_SET); + + if (is_compressed) { + // Section is compressed, read compressed .code section... + std::unique_ptr<u8[]> temp_buffer; + try { + temp_buffer.reset(new u8[section.size]); + } catch (std::bad_alloc&) { + return ResultStatus::ErrorMemoryAllocationFailed; } - return ResultStatus::Success; + + if (file->ReadBytes(&temp_buffer[0], section.size) != section.size) + return ResultStatus::Error; + + // Decompress .code section... + u32 decompressed_size = LZSS_GetDecompressedSize(&temp_buffer[0], section.size); + buffer.resize(decompressed_size); + if (!LZSS_Decompress(&temp_buffer[0], section.size, &buffer[0], decompressed_size)) + return ResultStatus::ErrorInvalidFormat; + } else { + // Section is uncompressed... + buffer.resize(section.size); + if (file->ReadBytes(&buffer[0], section.size) != section.size) + return ResultStatus::Error; } + return ResultStatus::Success; } - } else { - LOG_ERROR(Loader, "Unable to read file %s!", filename.c_str()); - return ResultStatus::Error; } return ResultStatus::ErrorNotUsed; } -/** - * Loads an NCCH file (e.g. from a CCI, or the first NCCH in a CXI) - * @param error_string Pointer to string to put error message if an error has occurred - * @todo Move NCSD parsing out of here and create a separate function for loading these - * @return True on success, otherwise false - */ ResultStatus AppLoader_NCCH::Load() { - LOG_INFO(Loader, "Loading NCCH file %s...", filename.c_str()); - if (is_loaded) return ResultStatus::ErrorAlreadyLoaded; - FileUtil::IOFile file(filename, "rb"); - if (file.IsOpen()) { - file.ReadBytes(&ncch_header, sizeof(NCCH_Header)); + if (!file->IsOpen()) + return ResultStatus::Error; - // Skip NCSD header and load first NCCH (NCSD is just a container of NCCH files)... - if (0 == memcmp(&ncch_header.magic, "NCSD", 4)) { - LOG_WARNING(Loader, "Only loading the first (bootable) NCCH within the NCSD file!"); - ncch_offset = 0x4000; - file.Seek(ncch_offset, 0); - file.ReadBytes(&ncch_header, sizeof(NCCH_Header)); - } + // Reset read pointer in case this file has been read before. + file->Seek(0, SEEK_SET); - // Verify we are loading the correct file type... - if (0 != memcmp(&ncch_header.magic, "NCCH", 4)) - return ResultStatus::ErrorInvalidFormat; + if (file->ReadBytes(&ncch_header, sizeof(NCCH_Header)) != sizeof(NCCH_Header)) + return ResultStatus::Error; - // Read ExHeader... + // Skip NCSD header and load first NCCH (NCSD is just a container of NCCH files)... + if (MakeMagic('N', 'C', 'S', 'D') == ncch_header.magic) { + LOG_WARNING(Loader, "Only loading the first (bootable) NCCH within the NCSD file!"); + ncch_offset = 0x4000; + file->Seek(ncch_offset, SEEK_SET); + file->ReadBytes(&ncch_header, sizeof(NCCH_Header)); + } - file.ReadBytes(&exheader_header, sizeof(ExHeader_Header)); + // Verify we are loading the correct file type... + if (MakeMagic('N', 'C', 'C', 'H') != ncch_header.magic) + return ResultStatus::ErrorInvalidFormat; - is_compressed = (exheader_header.codeset_info.flags.flag & 1) == 1; - entry_point = exheader_header.codeset_info.text.address; + // Read ExHeader... - LOG_INFO(Loader, "Name: %s", exheader_header.codeset_info.name); - LOG_DEBUG(Loader, "Code compressed: %s", is_compressed ? "yes" : "no"); - LOG_DEBUG(Loader, "Entry point: 0x%08X", entry_point); + if (file->ReadBytes(&exheader_header, sizeof(ExHeader_Header)) != sizeof(ExHeader_Header)) + return ResultStatus::Error; - // Read ExeFS... + is_compressed = (exheader_header.codeset_info.flags.flag & 1) == 1; + entry_point = exheader_header.codeset_info.text.address; - exefs_offset = ncch_header.exefs_offset * kBlockSize; - u32 exefs_size = ncch_header.exefs_size * kBlockSize; + LOG_INFO(Loader, "Name: %s", exheader_header.codeset_info.name); + LOG_DEBUG(Loader, "Code compressed: %s", is_compressed ? "yes" : "no"); + LOG_DEBUG(Loader, "Entry point: 0x%08X", entry_point); - LOG_DEBUG(Loader, "ExeFS offset: 0x%08X", exefs_offset); - LOG_DEBUG(Loader, "ExeFS size: 0x%08X", exefs_size); + // Read ExeFS... - file.Seek(exefs_offset + ncch_offset, 0); - file.ReadBytes(&exefs_header, sizeof(ExeFs_Header)); + exefs_offset = ncch_header.exefs_offset * kBlockSize; + u32 exefs_size = ncch_header.exefs_size * kBlockSize; - is_loaded = true; // Set state to loaded + LOG_DEBUG(Loader, "ExeFS offset: 0x%08X", exefs_offset); + LOG_DEBUG(Loader, "ExeFS size: 0x%08X", exefs_size); - LoadExec(); // Load the executable into memory for booting + file->Seek(exefs_offset + ncch_offset, SEEK_SET); + if (file->ReadBytes(&exefs_header, sizeof(ExeFs_Header)) != sizeof(ExeFs_Header)) + return ResultStatus::Error; - return ResultStatus::Success; - } else { - LOG_ERROR(Loader, "Unable to read file %s!", filename.c_str()); - } - return ResultStatus::Error; + is_loaded = true; // Set state to loaded + + return LoadExec(); // Load the executable into memory for booting } -/** - * Get the code (typically .code section) of the application - * @param buffer Reference to buffer to store data - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::ReadCode(std::vector<u8>& buffer) const { return LoadSectionExeFS(".code", buffer); } -/** - * Get the icon (typically icon section) of the application - * @param buffer Reference to buffer to store data - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::ReadIcon(std::vector<u8>& buffer) const { return LoadSectionExeFS("icon", buffer); } -/** - * Get the banner (typically banner section) of the application - * @param buffer Reference to buffer to store data - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::ReadBanner(std::vector<u8>& buffer) const { return LoadSectionExeFS("banner", buffer); } -/** - * Get the logo (typically logo section) of the application - * @param buffer Reference to buffer to store data - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::ReadLogo(std::vector<u8>& buffer) const { return LoadSectionExeFS("logo", buffer); } -/** - * Get the RomFS of the application - * @param buffer Reference to buffer to store data - * @return ResultStatus result of function - */ ResultStatus AppLoader_NCCH::ReadRomFS(std::vector<u8>& buffer) const { - FileUtil::IOFile file(filename, "rb"); - if (file.IsOpen()) { - // Check if the NCCH has a RomFS... - if (ncch_header.romfs_offset != 0 && ncch_header.romfs_size != 0) { - u32 romfs_offset = ncch_offset + (ncch_header.romfs_offset * kBlockSize) + 0x1000; - u32 romfs_size = (ncch_header.romfs_size * kBlockSize) - 0x1000; + if (!file->IsOpen()) + return ResultStatus::Error; - LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset); - LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size); + // Check if the NCCH has a RomFS... + if (ncch_header.romfs_offset != 0 && ncch_header.romfs_size != 0) { + u32 romfs_offset = ncch_offset + (ncch_header.romfs_offset * kBlockSize) + 0x1000; + u32 romfs_size = (ncch_header.romfs_size * kBlockSize) - 0x1000; - buffer.resize(romfs_size); + LOG_DEBUG(Loader, "RomFS offset: 0x%08X", romfs_offset); + LOG_DEBUG(Loader, "RomFS size: 0x%08X", romfs_size); - file.Seek(romfs_offset, 0); - file.ReadBytes(&buffer[0], romfs_size); + buffer.resize(romfs_size); - return ResultStatus::Success; - } - LOG_DEBUG(Loader, "NCCH has no RomFS"); - return ResultStatus::ErrorNotUsed; - } else { - LOG_ERROR(Loader, "Unable to read file %s!", filename.c_str()); + file->Seek(romfs_offset, SEEK_SET); + if (file->ReadBytes(&buffer[0], romfs_size) != romfs_size) + return ResultStatus::Error; + + return ResultStatus::Success; } - return ResultStatus::Error; + LOG_DEBUG(Loader, "NCCH has no RomFS"); + return ResultStatus::ErrorNotUsed; } u64 AppLoader_NCCH::GetProgramId() const { diff --git a/src/core/loader/ncch.h b/src/core/loader/ncch.h index fd9258970..9ae2de99f 100644 --- a/src/core/loader/ncch.h +++ b/src/core/loader/ncch.h @@ -5,7 +5,6 @@ #pragma once #include "common/common.h" -#include "common/file_util.h" #include "core/loader/loader.h" @@ -14,7 +13,7 @@ struct NCCH_Header { u8 signature[0x100]; - char magic[4]; + u32 magic; u32 content_size; u8 partition_id[8]; u16 maker_code; @@ -147,8 +146,14 @@ namespace Loader { /// Loads an NCCH file (e.g. from a CCI, or the first NCCH in a CXI) class AppLoader_NCCH final : public AppLoader { public: - AppLoader_NCCH(const std::string& filename); - ~AppLoader_NCCH() override; + AppLoader_NCCH(std::unique_ptr<FileUtil::IOFile>&& file) : AppLoader(std::move(file)) { } + + /** + * Returns the type of the file + * @param file FileUtil::IOFile open file + * @return FileType found, or FileType::Error if this loader doesn't know it + */ + static FileType IdentifyType(FileUtil::IOFile& file); /** * Load the application @@ -213,14 +218,11 @@ private: */ ResultStatus LoadExec() const; - std::string filename; - - bool is_loaded; - bool is_compressed; + bool is_compressed = false; - u32 entry_point; - u32 ncch_offset; // Offset to NCCH header, can be 0 or after NCSD header - u32 exefs_offset; + u32 entry_point = 0; + u32 ncch_offset = 0; // Offset to NCCH header, can be 0 or after NCSD header + u32 exefs_offset = 0; NCCH_Header ncch_header; ExeFs_Header exefs_header; |