diff --git a/.github/workflows/ci_gcc.yml b/.github/workflows/ci_gcc.yml index 1ea1413..342cdd9 100644 --- a/.github/workflows/ci_gcc.yml +++ b/.github/workflows/ci_gcc.yml @@ -14,7 +14,7 @@ jobs: fail-fast: false matrix: version: [L] # [H, I, I_patch, J, K, L] - suffix: [_rom] # [, _d, _rom] + suffix: [~, _d, _rom] steps: - name: Checkout reposistory diff --git a/.gitignore b/.gitignore index 669011d..d4c09ae 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ build/ expected/ notes/ tools/gcc +tools/ido *.elf *.o *.a diff --git a/Makefile b/Makefile index 3700641..8c5ab03 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,12 @@ NON_MATCHING ?= 0 -TARGET := libgultra_rom +# One of libgultra_rom, libgultra_d, libgultra +TARGET ?= libgultra_rom + BASE_DIR := base_$(TARGET) BASE_AR := $(TARGET).a -BUILD_DIR := build +BUILD_ROOT := build +BUILD_DIR := $(BUILD_ROOT)/$(TARGET) BUILD_AR := $(BUILD_DIR)/$(TARGET).a WORKING_DIR := $(shell pwd) @@ -16,19 +19,24 @@ AR_OLD := tools/gcc/ar export COMPILER_PATH := $(WORKING_DIR)/tools/gcc -CFLAGS := -w -nostdinc -c -G 0 -mgp32 -mfp32 -mips3 -D_LANGUAGE_C +CFLAGS := -w -nostdinc -c -G 0 -mgp32 -mfp32 -mips3 -D_LANGUAGE_C ASFLAGS := -w -nostdinc -c -G 0 -mgp32 -mfp32 -mips3 -DMIPSEB -D_LANGUAGE_ASSEMBLY -D_MIPS_SIM=1 -D_ULTRA64 -x assembler-with-cpp GBIDEFINE := -DF3DEX_GBI_2 -CPPFLAGS = -D_MIPS_SZLONG=32 -D__USE_ISOC99 -I $(WORKING_DIR)/include -I $(WORKING_DIR)/include/gcc -I $(WORKING_DIR)/include/PR $(GBIDEFINE) +CPPFLAGS = -D_MIPS_SZLONG=32 -D__USE_ISOC99 $(GBIDEFINE) +INCLUDES = -I . -I $(WORKING_DIR)/include -I $(WORKING_DIR)/include/gcc -I $(WORKING_DIR)/include/PR ifeq ($(findstring _d,$(TARGET)),_d) CPPFLAGS += -D_DEBUG OPTFLAGS := -O0 else -CPPFLAGS += -DNDEBUG -D_FINALROM +CPPFLAGS += -DNDEBUG OPTFLAGS := -O3 endif +ifeq ($(findstring _rom,$(TARGET)),_rom) +CPPFLAGS += -D_FINALROM +endif + SRC_DIRS := $(shell find src -type d) ASM_DIRS := $(shell find asm -type d -not -path "asm/non_matchings*") C_FILES := $(foreach dir,$(SRC_DIRS),$(wildcard $(dir)/*.c)) @@ -74,7 +82,7 @@ ifneq ($(NON_MATCHING),1) endif clean: - $(RM) -rf $(BUILD_DIR) + $(RM) -rf $(BUILD_ROOT) distclean: clean $(MAKE) -C tools distclean @@ -110,26 +118,31 @@ STRIP = $(BUILD_DIR)/src/os/initialize_isv.marker: OPTFLAGS := -O2 $(BUILD_DIR)/src/os/initialize_isv.marker: STRIP = && tools/gcc/strip-2.7 -N initialize_isv.c $(WORKING_DIR)/$(@:.marker=.o) $(WORKING_DIR)/$(@:.marker=.o) $(BUILD_DIR)/src/os/assert.marker: OPTFLAGS := -O0 -$(BUILD_DIR)/src/os/ackramromread.marker: OPTFLAGS := -O0 -$(BUILD_DIR)/src/os/ackramromwrite.marker: OPTFLAGS := -O0 -$(BUILD_DIR)/src/os/exit.marker: OPTFLAGS := -O0 $(BUILD_DIR)/src/os/seterrorhandler.marker: OPTFLAGS := -O0 +$(BUILD_DIR)/src/gu/parse_gbi.marker: GBIDEFINE := $(BUILD_DIR)/src/gu/us2dex_emu.marker: GBIDEFINE := -DF3DEX_GBI $(BUILD_DIR)/src/sp/sprite.marker: GBIDEFINE := $(BUILD_DIR)/src/sp/spriteex.marker: GBIDEFINE := $(BUILD_DIR)/src/sp/spriteex2.marker: GBIDEFINE := -$(BUILD_DIR)/src/sp/spriteex2.marker: GBIDEFINE := $(BUILD_DIR)/src/mgu/%.marker: export VR4300MUL := OFF $(BUILD_DIR)/src/mgu/rotate.marker: export VR4300MUL := ON +$(BUILD_DIR)/src/debug/%.marker: ASFLAGS += -P +$(BUILD_DIR)/src/error/%.marker: ASFLAGS += -P +$(BUILD_DIR)/src/log/%.marker: ASFLAGS += -P $(BUILD_DIR)/src/os/%.marker: ASFLAGS += -P $(BUILD_DIR)/src/gu/%.marker: ASFLAGS += -P $(BUILD_DIR)/src/libc/%.marker: ASFLAGS += -P $(BUILD_DIR)/src/rmon/%.marker: ASFLAGS += -P $(BUILD_DIR)/src/voice/%.marker: OPTFLAGS += -DLANG_JAPANESE -I$(WORKING_DIR)/src -I$(WORKING_DIR)/src/voice -$(BUILD_DIR)/src/voice/%.marker: CC := tools/compile_sjis.py -D__CC=$(WORKING_DIR)/$(CC) +$(BUILD_DIR)/src/voice/%.marker: CC := tools/compile_sjis.py -D__CC=$(WORKING_DIR)/$(CC) -D__BUILD_DIR=$(BUILD_DIR) +$(BUILD_DIR)/src/host/host_ptn64.marker: CFLAGS += -fno-builtin # Probably a better way to solve this + +MDEBUG_FILES := $(BUILD_DIR)/src/monutil.marker +$(BUILD_DIR)/src/monutil.marker: CC := tools/ido/cc +$(BUILD_DIR)/src/monutil.marker: ASFLAGS := -non_shared -mips2 -fullwarn -verbose -Xcpluscomm -G 0 -woff 516,649,838,712 -Wab,-r4300_mul -nostdinc -o32 -c $(BUILD_DIR)/%.marker: %.c - cd $( diff --git a/include/assert.h b/include/assert.h index 7f1989a..bfbf255 100644 --- a/include/assert.h +++ b/include/assert.h @@ -6,7 +6,7 @@ #define assert(EX) ((void)0) #else extern void __assert(const char *, const char *, int); -#define assert(EX) ((EX)?((void)0):__assert( # EX , __FILE__, __LINE__)) +#define assert(EX) ((EX)?((void)0):__assert("EX", __FILE__, __LINE__)) #endif /* NDEBUG */ #endif /* !__ASSERT_H__ */ diff --git a/include/fpregdef.h b/include/fpregdef.h new file mode 100644 index 0000000..e69de29 diff --git a/include/regdef.h b/include/regdef.h new file mode 100644 index 0000000..c29cc69 --- /dev/null +++ b/include/regdef.h @@ -0,0 +1,3 @@ +#include +#include +#include diff --git a/include/sgidefs.h b/include/sgidefs.h new file mode 100644 index 0000000..e69de29 diff --git a/include/sys/fpregdef.h b/include/sys/fpregdef.h new file mode 100644 index 0000000..e69de29 diff --git a/src/audio/csplayer.c b/src/audio/csplayer.c index 621ce02..66999f7 100644 --- a/src/audio/csplayer.c +++ b/src/audio/csplayer.c @@ -43,11 +43,8 @@ #include "seqp.h" #include "cseqp.h" #include "cseq.h" - // TODO: this comes from a header #ident "$Revision: 1.17 $" - - static ALMicroTime __CSPVoiceHandler(void *node); static void __CSPHandleNextSeqEvent(ALCSPlayer *seqp); static void __CSPHandleMIDIMsg(ALCSPlayer *seqp, ALEvent *event); diff --git a/src/audio/drvrnew.c b/src/audio/drvrnew.c index ef9e27f..7ca2e10 100644 --- a/src/audio/drvrnew.c +++ b/src/audio/drvrnew.c @@ -17,16 +17,13 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - #include #include "synthInternals.h" #include #include #include "initfx.h" - // TODO: this comes from a header #ident "$Revision: 1.49 $" - /* * WARNING: THE FOLLOWING CONSTANT MUST BE KEPT IN SYNC * WITH SCALING IN MICROCODE!!! diff --git a/src/audio/env.c b/src/audio/env.c index bc7369a..9a11e23 100644 --- a/src/audio/env.c +++ b/src/audio/env.c @@ -17,24 +17,20 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - #include #include "synthInternals.h" #include #include #include #include - // TODO: these come from headers #ident "$Revision: 1.49 $" #ident "$Revision: 1.17 $" - #ifdef AUD_PROFILE extern u32 cnt_index, env_num, env_cnt, env_max, env_min, lastCnt[]; extern u32 rate_num, rate_cnt, rate_max, rate_min; extern u32 vol_num, vol_cnt, vol_max, vol_min; #endif - #define EQPOWER_LENGTH 128 static s16 eqpower[ EQPOWER_LENGTH ] = { 32767, 32764, 32757, 32744, 32727, 32704, diff --git a/src/audio/reverb.c b/src/audio/reverb.c index 292ed0f..8558169 100644 --- a/src/audio/reverb.c +++ b/src/audio/reverb.c @@ -8,7 +8,6 @@ * Inc.; the contents of this file may not be disclosed to third * parties, copied or duplicated in any form, in whole or in part, * without the prior written permission of Silicon Graphics, Inc. - * * RESTRICTED RIGHTS LEGEND: * Use, duplication or disclosure by the Government is subject to * restrictions as set forth in subdivision (c)(1)(ii) of the Rights @@ -17,7 +16,6 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - #include #include #include "synthInternals.h" @@ -26,11 +24,9 @@ #include #include #include "initfx.h" - // TODO: these come from headers #ident "$Revision: 1.49 $" #ident "$Revision: 1.17 $" - #define RANGE 2.0 extern ALGlobals *alGlobals; diff --git a/src/audio/save.c b/src/audio/save.c index bc15294..ec6a0bf 100644 --- a/src/audio/save.c +++ b/src/audio/save.c @@ -3,7 +3,6 @@ * * Copyright 1993, Silicon Graphics, Inc. * All Rights Reserved. - * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, * Inc.; the contents of this file may not be disclosed to third * parties, copied or duplicated in any form, in whole or in part, @@ -17,12 +16,10 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - #include #include "synthInternals.h" #include #include - // TODO: this comes from a header #ident "$Revision: 1.17 $" diff --git a/src/audio/seqpdelete.c b/src/audio/seqpdelete.c index b4f11fd..8e283b1 100644 --- a/src/audio/seqpdelete.c +++ b/src/audio/seqpdelete.c @@ -1,8 +1,6 @@ /*==================================================================== * seqpdelete.c * - * Synopsis: - * * Copyright 1995, Silicon Graphics, Inc. * All Rights Reserved. * @@ -22,7 +20,6 @@ #include #include - // TODO: this comes from a header #ident "$Revision: 1.17 $" diff --git a/src/audio/seqplayer.c b/src/audio/seqplayer.c index 3b83257..a25d624 100644 --- a/src/audio/seqplayer.c +++ b/src/audio/seqplayer.c @@ -3,12 +3,10 @@ * * Copyright 1993, Silicon Graphics, Inc. * All Rights Reserved. - * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, * Inc.; the contents of this file may not be disclosed to third * parties, copied or duplicated in any form, in whole or in part, * without the prior written permission of Silicon Graphics, Inc. - * * RESTRICTED RIGHTS LEGEND: * Use, duplication or disclosure by the Government is subject to * restrictions as set forth in subdivision (c)(1)(ii) of the Rights @@ -17,7 +15,6 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - /* * Notes: * diff --git a/src/audio/sndplayer.c b/src/audio/sndplayer.c index 391e6ac..8f44b43 100644 --- a/src/audio/sndplayer.c +++ b/src/audio/sndplayer.c @@ -3,12 +3,10 @@ * * Copyright 1993, Silicon Graphics, Inc. * All Rights Reserved. - * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, * Inc.; the contents of this file may not be disclosed to third * parties, copied or duplicated in any form, in whole or in part, * without the prior written permission of Silicon Graphics, Inc. - * * RESTRICTED RIGHTS LEGEND: * Use, duplication or disclosure by the Government is subject to * restrictions as set forth in subdivision (c)(1)(ii) of the Rights diff --git a/src/audio/synthesizer.c b/src/audio/synthesizer.c index d42a21a..e499691 100644 --- a/src/audio/synthesizer.c +++ b/src/audio/synthesizer.c @@ -3,12 +3,10 @@ * * Copyright 1993, Silicon Graphics, Inc. * All Rights Reserved. - * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, * Inc.; the contents of this file may not be disclosed to third * parties, copied or duplicated in any form, in whole or in part, * without the prior written permission of Silicon Graphics, Inc. - * * RESTRICTED RIGHTS LEGEND: * Use, duplication or disclosure by the Government is subject to * restrictions as set forth in subdivision (c)(1)(ii) of the Rights @@ -17,7 +15,6 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - #include "synthInternals.h" #include diff --git a/src/os/assert.c b/src/debug/assert.c similarity index 100% rename from src/os/assert.c rename to src/debug/assert.c diff --git a/src/debug/assertbreak.s b/src/debug/assertbreak.s new file mode 100644 index 0000000..2837980 --- /dev/null +++ b/src/debug/assertbreak.s @@ -0,0 +1,12 @@ +#ifndef _FINALROM +#include "sys/asm.h" +#include "sys/regdef.h" + +.set noreorder + +LEAF(__assertBreak) + break 0 + j ra +END(__assertBreak) + +#endif diff --git a/src/debug/atomic.c b/src/debug/atomic.c new file mode 100644 index 0000000..a0bd8fe --- /dev/null +++ b/src/debug/atomic.c @@ -0,0 +1,16 @@ +#include "PR/os_internal.h" + +int __osAtomicDec(unsigned int* p) { + u32 mask; + int result; + + mask = __osDisableInt(); + if (*p) { + (*p)--; + result = 1; + } else { + result = 0; + } + __osRestoreInt(mask); + return result; +} diff --git a/src/os/kdebugserver.c b/src/debug/kdebugserver.c similarity index 94% rename from src/os/kdebugserver.c rename to src/debug/kdebugserver.c index 85dc172..e1c5e23 100644 --- a/src/os/kdebugserver.c +++ b/src/debug/kdebugserver.c @@ -1,7 +1,7 @@ #include "PR/os_internal.h" #include "PR/rcp.h" #include "PR/rdb.h" -#include "osint.h" +#include "../os/osint.h" extern u32 __osRdb_IP6_Empty; @@ -34,14 +34,14 @@ static void send_packet(u8* s, u32 n) { for (i = 0; i < n; i++) { packet.buf[i] = s[i]; } - *(rdbPacket*)RDB_BASE_REG = packet; + *(volatile rdbPacket*)RDB_BASE_REG = packet; } static void clear_IP6(void) { while (!(__osGetCause() & CAUSE_IP6)) { ; } - *(u32*)RDB_READ_INTR_REG = 0; + *(vu32*)RDB_READ_INTR_REG = 0; while (__osGetCause() & CAUSE_IP6) { ; diff --git a/src/debug/profile.c b/src/debug/profile.c new file mode 100644 index 0000000..e409382 --- /dev/null +++ b/src/debug/profile.c @@ -0,0 +1,177 @@ +#include "PR/rdb.h" +#include "PR/ultratypes.h" +#include "PR/os.h" +#include "stdarg.h" +#include "PR/ultraerror.h" +#include "PR/ultralog.h" +#include "PR/sptask.h" +#include "../os/osint.h" +#include "macros.h" + +#ifndef _FINALROM + +static u32 __osProfileActive = FALSE; +static u32 __osProfileIOActive = FALSE; + +static OSThread __osProfileIOThread; +unsigned char __osProfileIOStack[2400] ALIGNED(16); + +OSTimer __osProfTimer; +OSMesg __osProfTimerMsg; +u32 __osProfTimerPeriod; + +OSMesgQueue __osProfFlushMQ ALIGNED(8); +OSMesg __osProfFlushMesg; + +OSMesgQueue __osProfAckMQ ALIGNED(8); +OSMesg __osProfAckMesg; + +u32 __osProfNumSections; + +void __osProfileIO(void* arg) { + s32 totalBytes; + u32 bytesThisBlock; + u32 ct; + u8* sendPtr; + OSProf* t; + + while (TRUE) { + osRecvMesg(&__osProfFlushMQ, NULL, OS_MESG_BLOCK); + osProfSendWord(__osProfNumSections); + osProfSendWord(__osProfTimerPeriod); + osProfSendWord(__osProfileOverflowBin); + + t = __osProfileList; + while (t < __osProfileListEnd) { + osProfSendWord(t->text_start); + osProfSendWord(t->histo_size); + osRecvMesg(&__osProfAckMQ, NULL, OS_MESG_BLOCK); + + totalBytes = t->histo_size * 2; + sendPtr = t->histo_base; + while (totalBytes > 0) { + bytesThisBlock = (totalBytes < 0x800U) ? totalBytes : 0x800U; + + ct = 0; + while (ct < bytesThisBlock) { + ct += __osRdbSend(sendPtr + ct, bytesThisBlock - ct, RDB_TYPE_GtoH_PROF_DATA); + } + + sendPtr += bytesThisBlock; + totalBytes -= bytesThisBlock; + osRecvMesg(&__osProfAckMQ, NULL, OS_MESG_BLOCK); + } + t++; + } + } +} + +void osProfSendWord(u32 word) { + u32 ct; + u8* sendPtr; + + ct = 0; + sendPtr = &word; + + while (ct < sizeof(word)) { + ct += __osRdbSend(sendPtr + ct, sizeof(word) - ct, RDB_TYPE_GtoH_PROF_DATA); + } +} + +void osProfileFlush(void) { + osSendMesg(&__osProfFlushMQ, NULL, OS_MESG_BLOCK); +} + +void osProfileInit(OSProf* profp, u32 profcnt) { + u32 i; + OSProf* t; + +#ifndef NDEBUG + if (__osProfileActive) { + __osError(ERR_OSPROFILEINIT_STR, 0); + return; + } + + if (profcnt == 0) { + __osError(ERR_OSPROFILEINIT_CNT, 1, profcnt); + return; + } +#endif + + for (t = profp; t < profp + profcnt; t++) { +#ifndef NDEBUG + if ((u32)t->histo_base & 1) { + __osError(ERR_OSPROFILEINIT_ALN, 1, t->histo_base); + return; + } + + if (t->text_start >= t->text_end) { + __osError(ERR_OSPROFILEINIT_ORD, 2, t->text_start, t->text_end); + return; + } + + if (((u32)(t->text_end - t->text_start) / 4) > t->histo_size) { + __osError(ERR_OSPROFILEINIT_SIZ, 1, t->histo_size); + return; + } +#endif + + for (i = 0; i < t->histo_size; i++) { + t->histo_base[i] = 0; + } + } + + __osProfileActive = FALSE; + __osProfileOverflowBin = 0; + __osProfileList = profp; + __osProfileListEnd = profp + profcnt; + __osProfNumSections = profcnt; + if (!__osProfileIOActive) { + osCreateMesgQueue(&__osProfFlushMQ, &__osProfFlushMesg, 1); + osSetEventMesg(OS_EVENT_RDB_FLUSH_PROF, &__osProfFlushMQ, 0); + osCreateMesgQueue(&__osProfAckMQ, &__osProfAckMesg, 1); + osSetEventMesg(OS_EVENT_RDB_ACK_PROF, &__osProfAckMQ, 0); + osCreateThread(&__osProfileIOThread, 0, __osProfileIO, NULL, &__osProfileIOStack[2400], 0x81); + osStartThread(&__osProfileIOThread); + __osProfileIOActive = TRUE; + } +} + +void osProfileStart(u32 microseconds) { +#ifndef NDEBUG + if (microseconds < 50) { + __osError(ERR_OSPROFILESTART_TIME, 1, microseconds); + return; + } + + if (__osProfileActive) { + __osError(ERR_OSPROFILESTART_FLAG, 0); + return; + } +#endif + + osCreateMesgQueue(&__osProfTimerQ, &__osProfTimerMsg, 1); + osSetTimer(&__osProfTimer, 0, OS_USEC_TO_CYCLES(microseconds), &__osProfTimerQ, NULL); + __osProfTimerPeriod = microseconds; + __osProfileActive = TRUE; +} + +void osProfileStop(void) { +#ifndef NDEBUG + if (!__osProfileActive) { + __osError(ERR_OSPROFILESTOP_FLAG, 0); + return; + } +#endif + + if (osStopTimer(&__osProfTimer) < 0) { +#ifndef NDEBUG + __osError(ERR_OSPROFILESTOP_TIMER, 0); + return; +#endif + } + + __osProfileActive = FALSE; +} + +#endif diff --git a/src/debug/threadprofilereadcount.c b/src/debug/threadprofilereadcount.c index c12d313..3237987 100644 --- a/src/debug/threadprofilereadcount.c +++ b/src/debug/threadprofilereadcount.c @@ -1,13 +1,17 @@ #include "osint_debug.h" u32 osThreadProfileReadCount(OSId id) { +#ifndef NDEBUG if (!__osThprofFlag) { __osError(139, 0); return 0; } +#endif if (id >= THPROF_IDMAX) { +#ifndef NDEBUG __osError(143, 1, id); +#endif return 0; } return thprof[id].count; @@ -16,15 +20,19 @@ u32 osThreadProfileReadCount(OSId id) { u32 osThreadProfileReadCountTh(OSThread* thread) { OSId id; +#ifndef NDEBUG if (!__osThprofFlag) { __osError(141, 0); return 0; } +#endif id = osGetThreadId(thread); if (id >= THPROF_IDMAX) { +#ifndef NDEBUG __osError(145, 1, id); +#endif return 0; } return thprof[id].count; diff --git a/src/debug/threadprofilereadtime.c b/src/debug/threadprofilereadtime.c index c5c4cca..9930cac 100644 --- a/src/debug/threadprofilereadtime.c +++ b/src/debug/threadprofilereadtime.c @@ -4,12 +4,16 @@ OSTime osThreadProfileReadTime(OSId id) { OSTime adjust = 0; u32 now_time = osGetCount(); +#ifndef NDEBUG if (!__osThprofFlag) { __osError(140, 0); return 0; } +#endif if (id >= THPROF_IDMAX) { +#ifndef NDEBUG __osError(144, 1, id); +#endif return 0; } @@ -24,15 +28,19 @@ OSTime osThreadProfileReadTimeTh(OSThread* thread) { OSTime adjust = 0; u32 now_time = osGetCount(); +#ifndef NDEBUG if (!__osThprofFlag) { __osError(142, 0); return 0; } +#endif id = osGetThreadId(thread); if (id >= THPROF_IDMAX) { +#ifndef NDEBUG __osError(146, 1, id); +#endif return 0; } diff --git a/src/debug/threadprofilestart.c b/src/debug/threadprofilestart.c index dc341fb..3ef8fa7 100644 --- a/src/debug/threadprofilestart.c +++ b/src/debug/threadprofilestart.c @@ -3,6 +3,7 @@ void osThreadProfileStart(void) { register u32 saveMask; +#ifndef NDEBUG if (!__osThprofFlag) { __osError(136, 0); return; @@ -11,6 +12,7 @@ void osThreadProfileStart(void) { __osError(137, 0); return; } +#endif saveMask = __osDisableInt(); diff --git a/src/debug/threadprofilestop.c b/src/debug/threadprofilestop.c index 666d7cd..7cc20e7 100644 --- a/src/debug/threadprofilestop.c +++ b/src/debug/threadprofilestop.c @@ -8,11 +8,13 @@ void osThreadProfileStop(void) { saveMask = __osDisableInt(); +#ifndef NDEBUG if (__osThprofFlag == 0) { __osRestoreInt(saveMask); __osError(138, 0); return; } +#endif if (__osThprofFunc != NULL) { id = osGetThreadId(0); @@ -20,9 +22,11 @@ void osThreadProfileStop(void) { if (id < THPROF_IDMAX) { thprof[id].time += now_time - __osThprofLastTimer; } else { +#ifndef NDEBUG __osRestoreInt(saveMask); __osError(147, 1, id); saveMask = __osDisableInt(); +#endif } } __osThprofFunc = NULL; diff --git a/src/error/commonerror.c b/src/error/commonerror.c new file mode 100644 index 0000000..53cca55 --- /dev/null +++ b/src/error/commonerror.c @@ -0,0 +1,185 @@ +#include "PR/os.h" +#include "PR/os_internal.h" +#include "PR/sptask.h" +#include "PR/ultraerror.h" +#include "PR/ultralog.h" +#include "macros.h" +#include "stdarg.h" + +#ifndef _FINALROM + +static u32 errorLogData[19] ALIGNED(8); +static OSLog errorLog = { OS_ERROR_MAGIC, 76, errorLogData, 0, 0 }; + +static void __commonErrorHandler(s16 code, s16 numArgs, ...); +OSErrorHandler __osCommonHandler = __commonErrorHandler; + +char NULSTR[] = { '\0' }; + +const char* __os_error_message[] = { + NULSTR, + "osCreateThread: stack pointer not aligned to 8 bytes (0x%x)", + "osCreateThread: priority not in range [0-255] (%d)", + "osStartThread: thread has bad state (running/runnable/other)", + "osSetThreadPri: priority not in range [0-255] (%d)", + "osCreateMesgQueue: message count not > 0 (%d)", + "osSendMesg: flag not OS_MESG_NOBLOCK or OS_MESG_BLOCK (%d)", + "osJamMesg: flag not OS_MESG_NOBLOCK or OS_MESG_BLOCK (%d)", + "osRecvMesg: flag not OS_MESG_NOBLOCK or OS_MESG_BLOCK (%d)", + "osSetEventMesg: unknown event type (%d)", + "osMapTLB: index not in range [0-30] (%d)", + "osMapTLB: asid argument not -1 or in range [0-255] (%d)", + "osUnmapTLB: index not in range [0-30] (%d)", + "osSetTLBASID: asid not in range [0-255] (%d)", + "osAiSetFrequency: freq not in range [%d-%d] (%d)", + "osAiSetNextBuffer: address not aligned to 8 bytes (0x%x)", + "osAiSetNextBuffer: size not aligned to 8 bytes (0x%x)", + "osDpSetNextBuffer: address not aligned to 8 bytes (0x%x)", + "osDpSetNextBuffer: size not aligned to 8 bytes (0x%x)", + "osPiRawReadIo: address not aligned to 4 bytes (0x%x)", + "osPiRawWriteIo: address not aligned to 4 bytes (0x%x)", + "osPiRawStartDma: direction not OS_READ or OS_WRITE (%d)", + "osPiRawStartDma: device address not aligned to 2 bytes (0x%x)", + "osPiRawStartDma: DRAM address not aligned to 8 bytes (0x%x)", + "osPiRawStartDma: size not aligned to 2 bytes (%d)", + "osPiRawStartDma: size not in range [0,16777216] (%d)", + "osPiReadIo: address not aligned to 4 bytes (0x%x)", + "osPiWriteIo: address not aligned to 4 bytes (0x%x)", + "osPiStartDma: PI Manager not yet begun by osCreatePiManager", + "osPiStartDma: priority not OS_MESG_PRI_[NORMAL|HIGH] (%d)", + "osPiStartDma: direction not OS_READ or OS_WRITE (%d)", + "osPiStartDma: device address not aligned to 2 bytes (0x%x)", + "osPiStartDma: DRAM address not aligned to 8 bytes (0x%x)", + "osPiStartDma: size not aligned to 2 bytes (%d)", + "osPiStartDma: size not in range [0,16777216] (%d)", + "osCreatePiManager: priority not in range [0-255] (%d)", + "osViGetCurrentMode: VI Manager not yet begun", + "osViGetCurrentFramebuffer: VI Manager not yet begun", + "osViGetNextFramebuffer: VI Manager not yet begun", + "osViSetXScale: value not in range [0.25,1.0] (%f)", + "osViSetXScale: VI Manager not yet begun by osCreateViManager", + "osViSetYScale: value not in range [0.05,1.0] (%f)", + "osViSetYScale: VI Manager not yet begun by osCreateViManager", + "osViSetSpecialFeatures: not a known feature value (%d)", + "osViSetSpecialFeatures: VI Manager not yet begun", + "osViSetMode: VI Manager not yet begun by osCreateViManager", + "osViSetEvent: VI Manager not yet begun by osCreateViManager", + "osViSwapBuffer: frame buffer not aligned to 64 bytes (0x%x)", + "osViSwapBuffer: VI Manager not yet begun", + "osCreateViManager: priority not in range [0-255] (%d)", + "osCreateRegion: not a known alignment (%d)", + "osCreateRegion: length (%d) too small for buffer size (%d)", + "osMalloc: invalid or corrupt region (0x%x)", + "osFree: invalid or corrupt region (0x%x)", + "osFree: invalid address (0x%x) or\n corrupt region (0x%x)", + "osGetRegionBufCount: invalid or corrupt region (0x%x)", + "osGetRegionBufSize: invalid or corrupt region (0x%x)", + "osSpTaskLoad: dram_stack not aligned to 16 bytes (0x%x)", + "osSpTaskLoad: output_buff not aligned to 16 bytes (0x%x)", + "osSpTaskLoad: output_buff_size not aligned to 16 bytes (0x%x)", + "osSpTaskLoad: yield_data_ptr not aligned to 16 bytes (0x%x)", + "osProfileInit: profile counter is running, call osProfileStop before init", + "osProfileInit: profcnt is %d", + "osProfileInit: histo_base pointer must be 32-bit aligned (%x)", + "osProfileInit: text_start (%x) >= text_end (%x)", + "osProfileInit: histo_size is an illegal size (%d)", + "osProfileStart: microseconds is < PROF_MIN_INTERVAL (%d)", + "osProfileStart: profiling has already been started", + "osProfileStop: profiling has already been stopped", + "osProfileStop: no profile timer to stop", + "osReadHost: address not aligned to 8 bytes (0x%x)", + "osReadHost: size either 0 or not aligned to 4 bytes (0x%x)", + "osWriteHost: address not aligned to 8 bytes (0x%x)", + "osWriteHost: size either 0 or not aligned to 4 bytes (0x%x)", + "osGetTime: VI manager not yet begun by osCreateViManager", + "osSetTime: VI manager not yet begun by osCreateViManager", + "osSetTimer: VI manager not yet begun by osCreateViManager", + "osStopTimer: VI manager not yet begun by osCreateViManager", + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + NULSTR, + "_handleMIDIMsg: no sound mapped", + "_handleMIDIMsg: no free voices", + "_handleMIDIMsg: couldn't map voice", + "_handleMIDIMsg: note off - couldn't find voice", + "_handleMIDIMsg: poly pressure - couldn't find voice", + "_handleEvent: no free voices", + "Synthesizer: no free updates", + "alSndPDeallocate: attempt to deallocate a sound which is playing", + "alSndpDelete: attempt to delete player with playing sounds", + "alSndpPlay: attempt to play a sound which is playing", + "alSndpSetSound: sound id (%d) out of range (0 - %d)", + "alSndpSetPriority: sound id (%d) out of range (0 - %d)", + "alSndpSet Parameter: target (%d) out of range (0 - %d)", + "alBnkfNew: bank file out of date", + "alSeqNew: 0x%x is not a midi file", + "alSeqNew: 0x%x is not a type 0 midi file", + "alSeqNew: 0x%x has more than 1 track", + "alSeqNew: SMPTE delta times not supported", + "alSeqNew: Error parsing file 0x%x (no track header)", + "alSeqNextEvent: Unsupported system exclusive", + "alSeqNextEvent: Unsupported midi meta event 0x%x", + "_handleMIDIMsg: Invalid program change to %d, max instruments %d", + "_handleMIDIMsg: Unknown midi message 0x%x", + "_unmapVoice: Couldn't unmap voice 0x%x", + "alEvtqPostEvent: Out of free events", + "alHeapAlloc: Can't allocate %d bytes", + "alHeapCheck: Heap corrupt", + "alHeapCheck: Heap corrupt - first block is bad", + "alCSeqGetTrackEvent: Running status of zero on track %d", + "alCSeqGetTrackEvent: Note on velocity of zero on track %d", + "alCSPVoiceHandler: Stopping sequence but voice not free chan %d, key %d", + "alSeqNextEvent: Read past end of sequence", + "osAiSetNextBuffer: DMA buffer location may cause audio clicks (0x%x)", + "_loadOutputBuffer: Modulated delay greater than total delay by %d samples", + "osViExtendVStart: VI Manager not yet begun by osCreateViManager", + "osViExtendVStart: value not in range [0-48] %d", + "osThreadProfileStart: thread profiler is not initialized", + "osThreadProfileStart: profiling has already been started", + "osThreadProfileStop: thread profiler is not initialized", + "osThreadProfileReadCount: thread profiler is not initialized", + "osThreadProfileReadCountTh: thread profiler is not initialized", + "osThreadProfileReadTime: thread profiler is not initialized", + "osThreadProfileReadTimeTh: thread profiler is not initialized", + "osThreadProfileReadCount: thread ID is too large(%d)", + "osThreadProfileReadTime: thread ID is too large(%d)", + "osThreadProfileReadCountTh: thread ID is too large(%d)", + "osThreadProfileReadTimeTh: thread ID is too large(%d)", + "osThreadProfileStop: current thread ID is too large(%d)", + NULSTR, +}; + +void __commonErrorHandler(s16 code, s16 numArgs, ...) { + va_list argPtr; + const char* fmt; + + fmt = __os_error_message[code]; + va_start(argPtr, numArgs); + + osSyncPrintf("0x%08X (%04d):", osGetCount(), code); + __osSyncVPrintf(fmt, argPtr); + osSyncPrintf("\n"); + + va_end(argPtr); +} + +#endif diff --git a/src/error/errorasm.s b/src/error/errorasm.s new file mode 100644 index 0000000..c3e3120 --- /dev/null +++ b/src/error/errorasm.s @@ -0,0 +1,13 @@ +#ifndef _FINALROM +#include "sys/asm.h" +#include "sys/regdef.h" + +LEAF(__osError) + lw t0,__osCommonHandler + beqz t0,1f + jr t0 +1: + j ra +END(__osError) + +#endif diff --git a/src/flash/flashcheckeraseend.c b/src/flash/flashcheckeraseend.c index 47faf5c..743d24d 100644 --- a/src/flash/flashcheckeraseend.c +++ b/src/flash/flashcheckeraseend.c @@ -5,17 +5,18 @@ s32 osFlashCheckEraseEnd(void) { osFlashReadStatus(&status); - if (!(status & FLASH_STATUS_ERASE_BUSY)) { + if (status & FLASH_STATUS_ERASE_BUSY) { + return FLASH_STATUS_ERASE_BUSY; + } else { // not busy, read and clear status osFlashReadStatus(&status); - osFlashClearStatus(); - - // check for success - if (((status & 0xFF) == 8) || ((status & 0xFF) == 0x48) || ((status & 8) == 8)) { - return FLASH_STATUS_ERASE_OK; - } else { - return FLASH_STATUS_ERASE_ERROR; - } } - return FLASH_STATUS_ERASE_BUSY; + osFlashClearStatus(); + + // check for success + if (((status & 0xFF) == 8) || ((status & 0xFF) == 0x48) || ((status & 8) == 8)) { + return FLASH_STATUS_ERASE_OK; + } else { + return FLASH_STATUS_ERASE_ERROR; + } } diff --git a/src/flash/flashgetaddr.c b/src/flash/flashgetaddr.c index 3fe2e37..a5a9631 100644 --- a/src/flash/flashgetaddr.c +++ b/src/flash/flashgetaddr.c @@ -1,7 +1,13 @@ #include "PR/os_internal.h" u32 __osFlashGetAddr(u32 page_num) { - u32 devAddr = (__osFlashVersion == OLD_FLASH) ? page_num << 6 : page_num << 7; + u32 devAddr; + + if (__osFlashVersion == OLD_FLASH) { + devAddr = page_num * 64; + } else { + devAddr = page_num * 128; + } return devAddr; } diff --git a/src/gio/giorawinterrupt.c b/src/gio/giorawinterrupt.c index 64652d3..2fdc909 100644 --- a/src/gio/giorawinterrupt.c +++ b/src/gio/giorawinterrupt.c @@ -1,18 +1,13 @@ #include "PR/os_internal.h" #include "PR/rcp.h" +#include "../io/piint.h" void __osGIORawInterrupt(s32 value) { register u32 stat; - stat = IO_READ(PI_STATUS_REG); - while (stat & (PI_STATUS_DMA_BUSY | PI_STATUS_IO_BUSY)) { - stat = IO_READ(PI_STATUS_REG); - } + WAIT_ON_IOBUSY(stat); IO_WRITE(GIO_GIO_INTR_REG, value); - stat = IO_READ(PI_STATUS_REG); - while (stat & (PI_STATUS_DMA_BUSY | PI_STATUS_IO_BUSY)) { - stat = IO_READ(PI_STATUS_REG); - } + WAIT_ON_IOBUSY(stat); } diff --git a/src/gt/dumpturbo.c b/src/gt/dumpturbo.c index 095c8a4..59930bc 100644 --- a/src/gt/dumpturbo.c +++ b/src/gt/dumpturbo.c @@ -18,13 +18,14 @@ #include #include +#include "macros.h" #undef PRINTF #define PRINTF rmonPrintf #define TX_MAX 100 -static u32 textures[TX_MAX]; +static u32 textures[TX_MAX] ALIGNED(8); static u32 numtextures; #define UNSEG_ADDR(sa) ((u32 *) (((globp)? \ diff --git a/src/gu/loadtextureblockmipmap.c b/src/gu/loadtextureblockmipmap.c index 786f64a..30ffc65 100644 --- a/src/gu/loadtextureblockmipmap.c +++ b/src/gu/loadtextureblockmipmap.c @@ -16,6 +16,7 @@ #include "guint.h" #include #include "ultra64.h" +#include "macros.h" // TODO: this comes from a header #ident "$Revision: 1.49 $" @@ -43,7 +44,7 @@ struct Tile }; /* tram mipmaps */ -static struct Tile mipmap[MM_MAX_LEVEL+1]; +static struct Tile mipmap[MM_MAX_LEVEL+1] ALIGNED(8); static struct texelSizeParams sizeParams[4] = { 16, 3, 1, 0, 8, 2, 2, 1, diff --git a/src/host/host_ptn64.c b/src/host/host_ptn64.c index 3a5a311..154d0d1 100644 --- a/src/host/host_ptn64.c +++ b/src/host/host_ptn64.c @@ -9,7 +9,7 @@ static volatile unsigned int* ptstat = (unsigned*)0xbff08004; static volatile unsigned int* ptport = (unsigned*)0xbff08000; static volatile unsigned int* n64piok = (unsigned*)PHYS_TO_K1(PI_STATUS_REG); -static OSMesgQueue waitPtQueue; +static OSMesgQueue waitPtQueue ALIGNED(8); static OSMesg waitPtQueueBuf; static u32 isWaitPtQueueCreated = FALSE; diff --git a/src/host/readhost.c b/src/host/readhost.c index 43b9a05..d9ae077 100644 --- a/src/host/readhost.c +++ b/src/host/readhost.c @@ -9,7 +9,7 @@ u32 __osRdb_Read_Data_Buf; u32 __osRdb_Read_Data_Ct; static int readHostInitialized = FALSE; -static OSMesgQueue readHostMesgQueue; +static OSMesgQueue readHostMesgQueue ALIGNED(8); static OSMesg readHostMesgBuf[1]; void osReadHost(void* dramAddr, u32 nbytes) { @@ -30,6 +30,7 @@ void osReadHost(void* dramAddr, u32 nbytes) { } osRecvMesg(&readHostMesgQueue, NULL, OS_MESG_BLOCK); + return; } #endif diff --git a/src/host/writehost.c b/src/host/writehost.c index 0e06605..c7477e6 100644 --- a/src/host/writehost.c +++ b/src/host/writehost.c @@ -2,11 +2,12 @@ #include "PR/os_internal.h" #include "PR/rdb.h" +#include "PR/ultraerror.h" #include "macros.h" static int writeHostInitialized = FALSE; -static OSMesgQueue writeHostMesgQueue; +static OSMesgQueue writeHostMesgQueue ALIGNED(8); static OSMesg writeHostMesgBuf[1]; #define MIN(a, b) (((a) < (b)) ? (a) : (b)) @@ -17,10 +18,12 @@ void osWriteHost(void* dramAddr, u32 nbytes) { u8 dCount[3]; u32 count; +#ifndef NDEBUG if (nbytes == 0) { - __osError(73, 1, nbytes); + __osError(ERR_OSWRITEHOST_SIZE, 1, nbytes); return; } +#endif if (writeHostInitialized == FALSE) { osCreateMesgQueue(&writeHostMesgQueue, writeHostMesgBuf, ARRLEN(writeHostMesgBuf)); diff --git a/src/io/ai.c b/src/io/ai.c index be3a735..4ece0f1 100644 --- a/src/io/ai.c +++ b/src/io/ai.c @@ -9,7 +9,7 @@ s32 __osAiDeviceBusy(void) { if (status & AI_STATUS_FIFO_FULL) { return TRUE; + } else { + return FALSE; } - - return FALSE; } diff --git a/src/io/aisetfreq.c b/src/io/aisetfreq.c index 2cdee35..4f9afb5 100644 --- a/src/io/aisetfreq.c +++ b/src/io/aisetfreq.c @@ -1,4 +1,5 @@ #include "PR/rcp.h" +#include "PR/ultraerror.h" #include "../os/osint.h" // TODO: this comes from a header @@ -9,6 +10,25 @@ s32 osAiSetFrequency(u32 frequency) { register unsigned char bitRate; register float f; +#ifdef _DEBUG + if (osViClock == VI_PAL_CLOCK) { + if (frequency < AI_PAL_MIN_FREQ || frequency > AI_PAL_MAX_FREQ) { + __osError(ERR_OSAISETFREQUENCY, 3, AI_PAL_MIN_FREQ, AI_PAL_MAX_FREQ, frequency); + return -1; + } + } else if (osViClock == VI_MPAL_CLOCK) { + if (frequency < AI_MPAL_MIN_FREQ || frequency > AI_MPAL_MAX_FREQ) { + __osError(ERR_OSAISETFREQUENCY, 3, AI_MPAL_MIN_FREQ, AI_MPAL_MAX_FREQ, frequency); + return -1; + } + } else { + if (frequency < AI_NTSC_MIN_FREQ || frequency > AI_NTSC_MAX_FREQ) { + __osError(ERR_OSAISETFREQUENCY, 3, AI_NTSC_MIN_FREQ, AI_NTSC_MAX_FREQ, frequency); + return -1; + } + } +#endif + f = osViClock / (float)frequency + .5f; dacRate = f; @@ -24,6 +44,5 @@ s32 osAiSetFrequency(u32 frequency) { IO_WRITE(AI_DACRATE_REG, dacRate - 1); IO_WRITE(AI_BITRATE_REG, bitRate - 1); - // IO_WRITE(AI_CONTROL_REG, AI_CONTROL_DMA_ON); return osViClock / (s32)dacRate; } diff --git a/src/io/aisetnextbuf.c b/src/io/aisetnextbuf.c index 15759ca..23fd81b 100644 --- a/src/io/aisetnextbuf.c +++ b/src/io/aisetnextbuf.c @@ -1,4 +1,5 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "PR/rcp.h" #include "../os/osint.h" @@ -13,10 +14,22 @@ s32 osAiSetNextBuffer(void* bufPtr, u32 size) { return -1; } +#ifdef _DEBUG + if ((u32)bufPtr & (8 - 1)) { + __osError(ERR_OSAISETNEXTBUFFER_ADDR, 1, bufPtr); + return -1; + } + + if ((u32)size & (8 - 1)) { + __osError(ERR_OSAISETNEXTBUFFER_SIZE, 1, size); + return -1; + } +#endif + bptr = bufPtr; if (hdwrBugFlag) { - bptr -= 0x2000; + bptr = (u8*)bufPtr - 0x2000; } if ((((u32)bufPtr + size) & 0x1fff) == 0) { diff --git a/src/io/cartrominit.c b/src/io/cartrominit.c index efa93b8..9651878 100644 --- a/src/io/cartrominit.c +++ b/src/io/cartrominit.c @@ -2,10 +2,11 @@ #include "PR/os_internal.h" #include "PR/R4300.h" #include "PR/rcp.h" +#include "piint.h" OSPiHandle __CartRomHandle ALIGNED(8); OSPiHandle* osCartRomInit(void) { - u32 value; + u32 value = 0; u32 saveMask; static int first = 1; register u32 stat; @@ -29,9 +30,7 @@ OSPiHandle* osCartRomInit(void) { bzero(&__CartRomHandle.transferInfo, sizeof(__OSTranxInfo)); - while (stat = IO_READ(PI_STATUS_REG), stat & (PI_STATUS_DMA_BUSY | PI_STATUS_IO_BUSY)) { - ; - } + WAIT_ON_IOBUSY(stat); latency = IO_READ(PI_BSD_DOM1_LAT_REG); pageSize = IO_READ(PI_BSD_DOM1_PGS_REG); diff --git a/src/io/conteepread.c b/src/io/conteepread.c index f62e815..674254c 100644 --- a/src/io/conteepread.c +++ b/src/io/conteepread.c @@ -20,27 +20,24 @@ s32 osEepromRead(OSMesgQueue* mq, u8 address, u8* buffer) { ret = __osEepStatus(mq, &sdata); type = sdata.type & (CONT_EEPROM | CONT_EEP16K); - if (ret != 0) { - __osSiRelAccess(); - return ret; - } - - switch (type) { - case CONT_EEPROM: - if (address >= EEPROM_MAXBLOCKS) { - ret = CONT_RANGE_ERROR; - } - break; - case CONT_EEPROM | CONT_EEP16K: - __osEepromRead16K = 1; - if (address >= EEP16K_MAXBLOCKS) { - // not technically possible - ret = CONT_RANGE_ERROR; - } - break; - default: - ret = CONT_NO_RESPONSE_ERROR; - break; + if (ret == 0) { + switch (type) { + case CONT_EEPROM: + if (address >= EEPROM_MAXBLOCKS) { + ret = CONT_RANGE_ERROR; + } + break; + case CONT_EEPROM | CONT_EEP16K: + if (address >= EEP16K_MAXBLOCKS) { + // not technically possible + ret = CONT_RANGE_ERROR; + } else { + __osEepromRead16K = 1; + } + break; + default: + ret = CONT_NO_RESPONSE_ERROR; + } } if (ret != 0) { @@ -72,7 +69,6 @@ s32 osEepromRead(OSMesgQueue* mq, u8 address, u8* buffer) { *buffer++ = eepromformat.data[i]; } } - __osSiRelAccess(); return ret; } diff --git a/src/io/conteepwrite.c b/src/io/conteepwrite.c index 535e69e..5c4f4e2 100644 --- a/src/io/conteepwrite.c +++ b/src/io/conteepwrite.c @@ -17,32 +17,27 @@ s32 osEepromWrite(OSMesgQueue* mq, u8 address, u8* buffer) { type = sdata.type & (CONT_EEPROM | CONT_EEP16K); - if (ret != 0) { - __osSiRelAccess(); - return ret; - } - - switch (type) { - case CONT_EEPROM: - if (address >= EEPROM_MAXBLOCKS) { - ret = CONT_RANGE_ERROR; - } - break; - case CONT_EEPROM | CONT_EEP16K: - if (address >= EEP16K_MAXBLOCKS) { - // not technically possible - ret = CONT_RANGE_ERROR; - } - if (__osEepromRead16K) { - __osEepromRead16K = 0; - __osSiRelAccess(); - osEepromRead(mq, (address ^ 1), temp); - __osSiGetAccess(); - } - break; - default: - ret = CONT_NO_RESPONSE_ERROR; - break; + if (ret == 0) { + switch (type) { + case CONT_EEPROM: + if (address >= EEPROM_MAXBLOCKS) { + ret = CONT_RANGE_ERROR; + } + break; + case CONT_EEPROM | CONT_EEP16K: + if (address >= EEP16K_MAXBLOCKS) { + // not technically possible + ret = CONT_RANGE_ERROR; + } else if (__osEepromRead16K) { + __osEepromRead16K = 0; + __osSiRelAccess(); + osEepromRead(mq, (address ^ 1), temp); + __osSiGetAccess(); + } + break; + default: + ret = CONT_NO_RESPONSE_ERROR; + } } if (ret != 0) { diff --git a/src/io/contpfs.c b/src/io/contpfs.c index 0e4a7cb..bb8e0bf 100644 --- a/src/io/contpfs.c +++ b/src/io/contpfs.c @@ -22,8 +22,7 @@ s32 __osIdCheckSum(u16* ptr, u16* csum, u16* icsum) { u16 data = 0; u32 j; - *icsum = 0; - *csum = *icsum; + *csum = *icsum = 0; for (j = 0; j < ((sizeof(__OSPackId) - sizeof(u32)) / sizeof(u8)); j += 2) { data = *(u16*)((u8*)ptr + j); @@ -87,11 +86,7 @@ s32 __osRepairPackId(OSPfs* pfs, __OSPackId* badid, __OSPackId* newid) { SET_ACTIVEBANK_TO_ZERO; - if (j > 0) { - mask = 1; - } else { - mask = 0; - } + mask = (j > 0) ? 1 : 0; newid->deviceid = (badid->deviceid & (u16)~1) | mask; newid->banks = j; @@ -151,7 +146,6 @@ s32 __osCheckPackId(OSPfs* pfs, __OSPackId* temp) { } s32 __osGetId(OSPfs* pfs) { - int k; u16 sum; u16 isum; u8 temp[BLOCKSIZE]; @@ -217,9 +211,8 @@ s32 __osCheckId(OSPfs* pfs) { if (ret != 0) { if (ret != PFS_ERR_NEW_PACK) { return ret; - } else { - ERRCK(__osContRamRead(pfs->queue, pfs->channel, PFS_ID_0AREA, (u8*)temp)); } + ERRCK(__osContRamRead(pfs->queue, pfs->channel, PFS_ID_0AREA, (u8*)temp)); } if (bcmp(pfs->id, temp, BLOCKSIZE) != 0) { @@ -243,11 +236,7 @@ s32 __osPfsRWInode(OSPfs* pfs, __OSInode* inode, u8 flag, u8 bank) { SET_ACTIVEBANK_TO_ZERO; - if (bank > 0) { - offset = 1; - } else { - offset = pfs->inode_start_page; - } + offset = (bank > 0) ? 1 : pfs->inode_start_page; if (flag == PFS_WRITE) { inode->inode_page[0].inode_t.page = @@ -297,3 +286,25 @@ s32 __osPfsRWInode(OSPfs* pfs, __OSInode* inode, u8 flag, u8 bank) { return 0; } + +#ifdef _DEBUG +s32 __osDumpId(OSPfs* pfs) { + u8 id[BLOCKSIZE]; + __OSPackId* temp; + s32 ret; + + ERRCK(__osContRamRead(pfs->queue, pfs->channel, PFS_ID_0AREA, id)); + + temp = (__OSPackId*)id; + rmonPrintf("repaired %x\n", temp->repaired); + rmonPrintf("random %x\n", temp->random); + rmonPrintf("serial_mid %llu\n", temp->serial_mid); + rmonPrintf("serial_low %llu\n", temp->serial_low); + rmonPrintf("deviceid %x\n", temp->deviceid); + rmonPrintf("banks %x\n", temp->banks); + rmonPrintf("version %x\n", temp->version); + rmonPrintf("checksum %x\n", temp->checksum); + rmonPrintf("inverted_checksum %x\n", temp->inverted_checksum); + return 0; +} +#endif diff --git a/src/io/contramread.c b/src/io/contramread.c index 0afa93a..3ddf264 100644 --- a/src/io/contramread.c +++ b/src/io/contramread.c @@ -8,7 +8,7 @@ s32 __osPfsLastChannel = -1; #define READFORMAT(ptr) ((__OSContRamReadFormat*)(ptr)) s32 __osContRamRead(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { - s32 ret; + s32 ret = 0; s32 i; u8* ptr; s32 retry = 2; @@ -40,12 +40,12 @@ s32 __osContRamRead(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { } READFORMAT(ptr)->addrh = address >> 3; - READFORMAT(ptr)->addrl = (u8)(__osContAddressCrc(address) | (address << 5)); + READFORMAT(ptr)->addrl = (u8)((address << 5) | __osContAddressCrc(address)); - __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_READ, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); ret = CHNL_ERR(*READFORMAT(ptr)); @@ -56,20 +56,16 @@ s32 __osContRamRead(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { if (ret) { break; + } else { + ret = PFS_ERR_CONTRFAIL; } - - ret = PFS_ERR_CONTRFAIL; } else { bcopy(&READFORMAT(ptr)->data, buffer, BLOCKSIZE); } } else { ret = PFS_ERR_NOPACK; } - if (ret != PFS_ERR_CONTRFAIL) { - break; - } - } while (0 <= retry--); + } while ((ret == PFS_ERR_CONTRFAIL) && (retry-- >= 0)); __osSiRelAccess(); - return ret; } diff --git a/src/io/controller.c b/src/io/controller.c index db9b769..b397d50 100644 --- a/src/io/controller.c +++ b/src/io/controller.c @@ -53,20 +53,21 @@ s32 osContInit(OSMesgQueue* mq, u8* bitpattern, OSContStatus* data) { void __osContGetInitData(u8* pattern, OSContStatus* data) { u8* ptr; __OSContRequesFormat requestHeader; - s32 i; - u8 bits; + int i; + u8 bits = 0; - bits = 0; - ptr = __osContPifRam.ramarray; + ptr = (u8*)__osContPifRam.ramarray; for (i = 0; i < __osMaxControllers; i++, ptr += sizeof(requestHeader), data++) { requestHeader = *(__OSContRequesFormat*)ptr; data->errno = CHNL_ERR(requestHeader); - if (data->errno == 0) { - data->type = requestHeader.typel << 8 | requestHeader.typeh; - data->status = requestHeader.status; - bits |= 1 << i; + if (data->errno != 0) { + continue; } + + data->type = requestHeader.typel << 8 | requestHeader.typeh; + data->status = requestHeader.status; + bits |= 1 << i; } *pattern = bits; } diff --git a/src/io/controller_voice.h b/src/io/controller_voice.h index 7223d06..1b9dee6 100644 --- a/src/io/controller_voice.h +++ b/src/io/controller_voice.h @@ -1,7 +1,7 @@ #ifndef CONTROLLER_VOICE_H #define CONTROLLER_VOICE_H -#include +#include "PR/ultratypes.h" typedef struct { /* 0x0 */ u8 dummy; diff --git a/src/io/crc.c b/src/io/crc.c index 6c48e3a..4463ee3 100644 --- a/src/io/crc.c +++ b/src/io/crc.c @@ -2,9 +2,9 @@ u8 __osContAddressCrc(u16 addr) { u32 temp = 0; - u32 i; + u32 i = 0x400; - for (i = 0x400; i != 0;) { + do { temp <<= 1; if (addr & i) { @@ -18,14 +18,16 @@ u8 __osContAddressCrc(u16 addr) { } i >>= 1; - } + } while (i != 0); - for (i = 5; i != 0; --i) { + i = 5; + + do { temp <<= 1; if (temp & 0x20) { temp ^= 0x15; } - } + } while (--i != 0); return temp & 0x1F; } diff --git a/src/io/devmgr.c b/src/io/devmgr.c index 34811a3..616dee5 100644 --- a/src/io/devmgr.c +++ b/src/io/devmgr.c @@ -3,13 +3,17 @@ #include "piint.h" void __osDevMgrMain(void* args) { - OSIoMesg* mb = NULL; + OSIoMesg* mb; OSMesg em; OSMesg dummy; - s32 ret = 0; - OSDevMgr* dm = (OSDevMgr*)args; + s32 ret; + OSDevMgr* dm; s32 messageSend = 0; + dm = (OSDevMgr*)args; + mb = NULL; + ret = 0; + while (TRUE) { osRecvMesg(dm->cmdQueue, (OSMesg)&mb, OS_MESG_BLOCK); diff --git a/src/io/dp.c b/src/io/dp.c index 8056028..e636217 100644 --- a/src/io/dp.c +++ b/src/io/dp.c @@ -9,7 +9,7 @@ int __osDpDeviceBusy(void) { if (stat & DPC_STATUS_DMA_BUSY) { return TRUE; + } else { + return FALSE; } - - return FALSE; } diff --git a/src/io/dpsetnextbuf.c b/src/io/dpsetnextbuf.c index 4e4996c..6314472 100644 --- a/src/io/dpsetnextbuf.c +++ b/src/io/dpsetnextbuf.c @@ -1,4 +1,5 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "PR/rcp.h" #include "../os/osint.h" @@ -8,15 +9,29 @@ s32 osDpSetNextBuffer(void* bufPtr, u64 size) { register u32 stat; +#ifdef _DEBUG + if ((u32)bufPtr & 0x7) { + __osError(ERR_OSDPSETNEXTBUFFER_ADDR, 1, bufPtr); + return -1; + } + if (size & 0x7) { + __osError(ERR_OSDPSETNEXTBUFFER_SIZE, 1, size); + return -1; + } +#endif + if (__osDpDeviceBusy()) { return -1; } IO_WRITE(DPC_STATUS_REG, DPC_CLR_XBUS_DMEM_DMA); - do { + while (TRUE) { stat = IO_READ(DPC_STATUS_REG); - } while (stat & DPC_STATUS_XBUS_DMEM_DMA); + if ((stat & DPC_STATUS_XBUS_DMEM_DMA) == 0) { + break; + } + } IO_WRITE(DPC_START_REG, osVirtualToPhysical(bufPtr)); IO_WRITE(DPC_END_REG, osVirtualToPhysical(bufPtr) + size); diff --git a/src/io/epidma.c b/src/io/epidma.c index d122791..06a9f69 100644 --- a/src/io/epidma.c +++ b/src/io/epidma.c @@ -1,11 +1,48 @@ #include "piint.h" +#include "PR/ultraerror.h" s32 osEPiStartDma(OSPiHandle* pihandle, OSIoMesg* mb, s32 direction) { - s32 ret; + register s32 ret; if (!__osPiDevMgr.active) { +#ifdef _DEBUG + __osError(ERR_OSPISTARTDMA_PIMGR, 0); +#endif return -1; } + +#ifdef _DEBUG + if ((mb->hdr.pri != OS_MESG_PRI_NORMAL) && (mb->hdr.pri != OS_MESG_PRI_HIGH)) { + __osError(ERR_OSPISTARTDMA_PRI, 1, mb->hdr.pri); + return -1; + } + + if ((direction != OS_READ) && (direction != OS_WRITE)) { + __osError(ERR_OSPISTARTDMA_DIR, 1, direction); + return -1; + } + + if (mb->devAddr & 0x1) { + __osError(ERR_OSPISTARTDMA_DEVADDR, 1, mb->devAddr); + return -1; + } + + if ((u32)mb->dramAddr & 0x7) { + __osError(ERR_OSPISTARTDMA_ADDR, 1, mb->dramAddr); + return -1; + } + + if (mb->size & 0x1) { + __osError(ERR_OSPISTARTDMA_SIZE, 1, mb->size); + return -1; + } + + if ((mb->size == 0) || (mb->size > (16 * 1024 * 1024))) { + __osError(ERR_OSPISTARTDMA_RANGE, 1, mb->size); + return -1; + } +#endif + mb->piHandle = pihandle; if (direction == OS_READ) { diff --git a/src/io/epilinkhandle.c b/src/io/epilinkhandle.c index bc3c116..5f51854 100644 --- a/src/io/epilinkhandle.c +++ b/src/io/epilinkhandle.c @@ -1,7 +1,7 @@ #include "piint.h" s32 osEPiLinkHandle(OSPiHandle* EPiHandle) { - register s32 saveMask = __osDisableInt(); + u32 saveMask = __osDisableInt(); EPiHandle->next = __osPiTable; __osPiTable = EPiHandle; diff --git a/src/io/epirawdma.c b/src/io/epirawdma.c index 0b1cdcd..69a404d 100644 --- a/src/io/epirawdma.c +++ b/src/io/epirawdma.c @@ -1,4 +1,5 @@ #include "piint.h" +#include "PR/ultraerror.h" // TODO: this comes from a header #ident "$Revision: 1.17 $" @@ -7,6 +8,33 @@ s32 __osEPiRawStartDma(OSPiHandle* pihandle, s32 direction, u32 devAddr, void* d u32 stat; u32 domain; +#ifdef _DEBUG + if ((direction != OS_READ) && (direction != OS_WRITE)) { + __osError(ERR_OSPIRAWSTARTDMA_DIR, 1, direction); + return -1; + } + + if (devAddr & 0x1) { + __osError(ERR_OSPIRAWSTARTDMA_DEVADDR, 1, devAddr); + return -1; + } + + if ((u32)dramAddr & 0x7) { + __osError(ERR_OSPIRAWSTARTDMA_ADDR, 1, dramAddr); + return -1; + } + + if (size & 0x1) { + __osError(ERR_OSPIRAWSTARTDMA_SIZE, 1, size); + return -1; + } + + if ((size == 0) || (size > (16 * 1024 * 1024))) { + __osError(ERR_OSPIRAWSTARTDMA_RANGE, 1, size); + return -1; + } +#endif + EPI_SYNC(pihandle, stat, domain); IO_WRITE(PI_DRAM_ADDR_REG, osVirtualToPhysical(dramAddr)); IO_WRITE(PI_CART_ADDR_REG, K1_TO_PHYS(pihandle->baseAddress | devAddr)); diff --git a/src/io/epirawread.c b/src/io/epirawread.c index 7871f56..7794eb8 100644 --- a/src/io/epirawread.c +++ b/src/io/epirawread.c @@ -1,11 +1,46 @@ #include "piint.h" +#include "PR/ultraerror.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osEPiRawReadIo(OSPiHandle* pihandle, u32 devAddr, u32* data) { - u32 stat; - u32 domain; + register u32 stat; + register u32 domain; + +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIRAWREADIO, 1, devAddr); + return -1; + } + + assert(data != NULL); +#endif EPI_SYNC(pihandle, stat, domain); *data = IO_READ(pihandle->baseAddress | devAddr); diff --git a/src/io/epirawwrite.c b/src/io/epirawwrite.c index 5cc1752..79fba31 100644 --- a/src/io/epirawwrite.c +++ b/src/io/epirawwrite.c @@ -1,11 +1,19 @@ #include "piint.h" +#include "PR/ultraerror.h" // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osEPiRawWriteIo(OSPiHandle* pihandle, u32 devAddr, u32 data) { - u32 stat; - u32 domain; + register u32 stat; + register u32 domain; + +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIRAWWRITEIO, 1, devAddr); + return -1; + } +#endif EPI_SYNC(pihandle, stat, domain); IO_WRITE(pihandle->baseAddress | devAddr, data); diff --git a/src/io/epiread.c b/src/io/epiread.c index c5b1bae..08cd0be 100644 --- a/src/io/epiread.c +++ b/src/io/epiread.c @@ -1,10 +1,16 @@ #include "piint.h" - - +#include "PR/ultraerror.h" s32 osEPiReadIo(OSPiHandle* pihandle, u32 devAddr, u32* data) { register s32 ret; +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIREADIO, 1, devAddr); + return -1; + } +#endif + __osPiGetAccess(); ret = __osEPiRawReadIo(pihandle, devAddr, data); __osPiRelAccess(); diff --git a/src/io/epiwrite.c b/src/io/epiwrite.c index 22e1fd4..42a239e 100644 --- a/src/io/epiwrite.c +++ b/src/io/epiwrite.c @@ -1,10 +1,16 @@ #include "piint.h" - - +#include "PR/ultraerror.h" s32 osEPiWriteIo(OSPiHandle* pihandle, u32 devAddr, u32 data) { register s32 ret; +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIWRITEIO, 1, devAddr); + return -1; + } +#endif + __osPiGetAccess(); ret = __osEPiRawWriteIo(pihandle, devAddr, data); __osPiRelAccess(); diff --git a/src/io/gbpakinit.c b/src/io/gbpakinit.c index 22afcff..c8bc07e 100644 --- a/src/io/gbpakinit.c +++ b/src/io/gbpakinit.c @@ -15,8 +15,8 @@ s32 osGbpakInit(OSMesgQueue* mq, OSPfs* pfs, int channel) { pfs->status = 0; // Turn off the transfer pak - for (i = 0; i < BLOCKSIZE; i++) { - temp[i] = GB_POWER_OFF; + for (i = 0; i < BLOCKSIZE; temp[i++] = GB_POWER_OFF) { + ; } ret = __osContRamWrite(mq, channel, CONT_BLOCK_GB_POWER, temp, FALSE); @@ -44,8 +44,8 @@ s32 osGbpakInit(OSMesgQueue* mq, OSPfs* pfs, int channel) { } // Turn on the transfer pak - for (i = 0; i < BLOCKSIZE; i++) { - temp[i] = GB_POWER_ON; + for (i = 0; i < BLOCKSIZE; temp[i++] = GB_POWER_ON) { + ; } ret = __osContRamWrite(mq, channel, CONT_BLOCK_GB_POWER, temp, FALSE); diff --git a/src/io/gbpakpower.c b/src/io/gbpakpower.c index 756f669..3d4a8f4 100644 --- a/src/io/gbpakpower.c +++ b/src/io/gbpakpower.c @@ -7,8 +7,8 @@ s32 osGbpakPower(OSPfs* pfs, s32 flag) { s32 ret; u8 temp[BLOCKSIZE]; - for (i = 0; i < BLOCKSIZE; i++) { - temp[i] = (u8)flag; + for (i = 0; i < BLOCKSIZE; temp[i++] = (u8)flag) { + ; } ret = __osContRamWrite(pfs->queue, pfs->channel, CONT_BLOCK_GB_STATUS, temp, 0); diff --git a/src/io/gbpakreadid.c b/src/io/gbpakreadid.c index d7d9e27..f35ef25 100644 --- a/src/io/gbpakreadid.c +++ b/src/io/gbpakreadid.c @@ -32,7 +32,7 @@ s32 osGbpakReadId(OSPfs* pfs, OSGbpakId* id, u8* status) { ret = osGbpakGetStatus(pfs, status); - if (ret == 0xD) { + if (ret == PFS_ERR_NEW_GBCART) { ret = PFS_ERR_CONTRFAIL; } @@ -45,8 +45,8 @@ s32 osGbpakReadId(OSPfs* pfs, OSGbpakId* id, u8* status) { } if (bcmp(nintendo, buf + 4, ARRLEN(nintendo))) { - for (i = 0; i < ARRLEN(temp); i++) { - temp[i] = 0; + for (i = 0; i < ARRLEN(temp); temp[i++] = 0) { + ; } ERRCK(osGbpakReadWrite(pfs, OS_WRITE, 0x6000U, temp, ARRLEN(temp))); diff --git a/src/io/gbpaksetbank.c b/src/io/gbpaksetbank.c index 134cad8..7a08646 100644 --- a/src/io/gbpaksetbank.c +++ b/src/io/gbpaksetbank.c @@ -10,8 +10,8 @@ s32 __osGbpakSetBank(OSPfs* pfs, u8 bank) { return PFS_ERR_INVALID; } - for (i = 0; i < BLOCKSIZE; i++) { - temp[i] = bank; + for (i = 0; i < BLOCKSIZE; temp[i++] = bank) { + ; } ret = __osContRamWrite(pfs->queue, pfs->channel, CONT_BLOCK_GB_BANK, temp, FALSE); diff --git a/src/io/motor.c b/src/io/motor.c index 00df31e..8ad1b08 100644 --- a/src/io/motor.c +++ b/src/io/motor.c @@ -3,7 +3,7 @@ #include "controller.h" #include "siint.h" -static OSPifRam __MotorDataBuf[MAXCONTROLLERS]; +static OSPifRam __MotorDataBuf[MAXCONTROLLERS] ALIGNED(8); #define READFORMAT(ptr) ((__OSContRamReadFormat*)(ptr)) @@ -27,7 +27,7 @@ s32 __osMotorAccess(OSPfs* pfs, s32 flag) { __osContLastCmd = CONT_CMD_END; __osSiRawStartDma(OS_WRITE, &__MotorDataBuf[pfs->channel]); osRecvMesg(pfs->queue, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__MotorDataBuf[pfs->channel]); + ret = __osSiRawStartDma(OS_READ, &__MotorDataBuf[pfs->channel]); osRecvMesg(pfs->queue, NULL, OS_MESG_BLOCK); ret = READFORMAT(ptr)->rxsize & CHNL_ERR_MASK; @@ -48,7 +48,7 @@ s32 __osMotorAccess(OSPfs* pfs, s32 flag) { return ret; } -static void _MakeMotorData(int channel, OSPifRam* mdata) { +static void __osMakeMotorData(int channel, OSPifRam* mdata) { u8* ptr = (u8*)mdata->ramarray; __OSContRamReadFormat ramreadformat; int i; @@ -98,9 +98,7 @@ s32 osMotorInit(OSMesgQueue* mq, OSPfs* pfs, int channel) { if (ret != 0) { return ret; - } - - if (temp[31] == 254) { + } else if (temp[31] == 254) { return PFS_ERR_DEVICE; } @@ -120,14 +118,12 @@ s32 osMotorInit(OSMesgQueue* mq, OSPfs* pfs, int channel) { if (ret != 0) { return ret; - } - - if (temp[31] != 0x80) { + } else if (temp[31] != 0x80) { return PFS_ERR_DEVICE; } if (!(pfs->status & PFS_MOTOR_INITIALIZED)) { - _MakeMotorData(channel, &__MotorDataBuf[channel]); + __osMakeMotorData(channel, &__MotorDataBuf[channel]); } pfs->status = PFS_MOTOR_INITIALIZED; diff --git a/src/io/pfsallocatefile.c b/src/io/pfsallocatefile.c index 5a72ad5..77dcf23 100644 --- a/src/io/pfsallocatefile.c +++ b/src/io/pfsallocatefile.c @@ -26,12 +26,9 @@ s32 osPfsAllocateFile(OSPfs* pfs, u16 company_code, u32 game_code, u8* game_name file_size_in_pages = ROUND_UP_DIVIDE(file_size_in_bytes, BLOCKSIZE * PFS_ONE_PAGE); - ret = osPfsFindFile(pfs, company_code, game_code, game_name, ext_name, file_no); - - if (ret != 0) { - if (ret != PFS_ERR_INVALID) { - return ret; - } + if (((ret = osPfsFindFile(pfs, company_code, game_code, game_name, ext_name, file_no)) != 0) && + ret != PFS_ERR_INVALID) { + return ret; } if (*file_no != -1) { @@ -48,11 +45,8 @@ s32 osPfsAllocateFile(OSPfs* pfs, u16 company_code, u32 game_code, u8* game_name return PFS_ERR_INVALID; } - ret = osPfsFindFile(pfs, 0, 0, NULL, NULL, file_no); - if (ret != 0) { - if (ret != PFS_ERR_INVALID) { - return ret; - } + if (((ret = osPfsFindFile(pfs, 0, 0, NULL, NULL, file_no)) != 0) && ret != PFS_ERR_INVALID) { + return ret; } if (*file_no == -1) { @@ -99,7 +93,8 @@ s32 osPfsAllocateFile(OSPfs* pfs, u16 company_code, u32 game_code, u8* game_name bcopy(game_name, dir.game_name, PFS_FILE_NAME_LEN); bcopy(ext_name, dir.ext_name, PFS_FILE_EXT_LEN); - return __osContRamWrite(pfs->queue, pfs->channel, pfs->dir_table + *file_no, (u8*)&dir, FALSE); + ret = __osContRamWrite(pfs->queue, pfs->channel, pfs->dir_table + *file_no, (u8*)&dir, FALSE); + return ret; } s32 __osPfsDeclearPage(OSPfs* pfs, __OSInode* inode, int file_size_in_pages, int* first_page, u8 bank, int* decleared, @@ -107,7 +102,6 @@ s32 __osPfsDeclearPage(OSPfs* pfs, __OSInode* inode, int file_size_in_pages, int int j; int spage; int old_page; - int i; s32 ret = 0; int offset = bank > 0 ? 1 : pfs->inode_start_page; @@ -124,7 +118,8 @@ s32 __osPfsDeclearPage(OSPfs* pfs, __OSInode* inode, int file_size_in_pages, int spage = j; *decleared = 1; - old_page = j++; + old_page = j; + j++; while (file_size_in_pages > *decleared && j < ARRLEN(inode->inode_page)) { if (inode->inode_page[j].ipage == 3) { @@ -147,3 +142,34 @@ s32 __osPfsDeclearPage(OSPfs* pfs, __OSInode* inode, int file_size_in_pages, int return ret; } + +#ifdef _DEBUG +s32 __osDumpInode(OSPfs* pfs) { + int j; + __OSInode inode; + s32 ret = 0; + __OSDir dir; + u8 bank; + u8 startbank = PFS_ID_BANK_256K; + + rmonPrintf("INODE:\n"); + + for (bank = startbank; bank < pfs->banks; bank++) { + rmonPrintf("\nBank %d:\n", bank); + ret = __osPfsRWInode(pfs, &inode, PFS_READ, bank); + for (j = 0; j < PFS_INODE_SIZE_PER_PAGE; j++) { + rmonPrintf("%x ", inode.inode_page[j].ipage); + } + } + + rmonPrintf("dir_size %d %d\n", pfs->dir_size, pfs->inode_start_page); + + for (j = 0; j < pfs->dir_size; j++) { + __osContRamRead(pfs->queue, pfs->channel, (u16)(pfs->dir_table + (int)j), (u8*)&dir); + rmonPrintf("file %d game_code %d page %x c_code %d sum %d\n", j, dir.game_code, dir.start_page.ipage, + dir.company_code, dir.data_sum); + } + rmonPrintf("End of Dump\n"); + return ret; +} +#endif diff --git a/src/io/pfschecker.c b/src/io/pfschecker.c index abfcd9f..d813442 100644 --- a/src/io/pfschecker.c +++ b/src/io/pfschecker.c @@ -61,9 +61,7 @@ s32 osPfsChecker(OSPfs* pfs) { } } - cc = corrupted(pfs, next_page, &cache) - cl; - - if (cc != 0) { + if (cc = corrupted(pfs, next_page, &cache) - cl) { break; } diff --git a/src/io/pfsfilestate.c b/src/io/pfsfilestate.c index bf3b32f..e85cb96 100644 --- a/src/io/pfsfilestate.c +++ b/src/io/pfsfilestate.c @@ -23,16 +23,14 @@ s32 osPfsFileState(OSPfs* pfs, s32 file_no, OSPfsState* state) { return PFS_ERR_INVALID; } - next_page = dir.start_page; pages = 0; + next_page = dir.start_page; bank = 0xFF; while (TRUE) { if (next_page.ipage < pfs->inode_start_page) { break; - } - - if (next_page.inode_t.bank != bank) { + } else if (next_page.inode_t.bank != bank) { bank = next_page.inode_t.bank; ERRCK(__osPfsRWInode(pfs, &inode, PFS_READ, bank)); } @@ -51,5 +49,6 @@ s32 osPfsFileState(OSPfs* pfs, s32 file_no, OSPfsState* state) { bcopy(&dir.game_name, state->game_name, PFS_FILE_NAME_LEN); bcopy(&dir.ext_name, state->ext_name, PFS_FILE_EXT_LEN); - return __osPfsGetStatus(pfs->queue, pfs->channel); + ret = __osPfsGetStatus(pfs->queue, pfs->channel); + return ret; } diff --git a/src/io/pfsgetstatus.c b/src/io/pfsgetstatus.c index 99ba30c..0fdcdaa 100644 --- a/src/io/pfsgetstatus.c +++ b/src/io/pfsgetstatus.c @@ -71,8 +71,10 @@ void __osPfsGetOneChannelData(int channel, OSContStatus* data) { requestformat = *(__OSContRequesFormatShort*)ptr; data->errno = CHNL_ERR(requestformat); - if (data->errno == 0) { - data->type = (requestformat.typel << 8) | (requestformat.typeh); - data->status = requestformat.status; + if (data->errno != 0) { + return; } + + data->type = (requestformat.typel << 8) | (requestformat.typeh); + data->status = requestformat.status; } diff --git a/src/io/pfsinitpak.c b/src/io/pfsinitpak.c index 927636f..5026335 100644 --- a/src/io/pfsinitpak.c +++ b/src/io/pfsinitpak.c @@ -4,7 +4,7 @@ static s32 __osPfsCheckRamArea(OSPfs* pfs); s32 osPfsInitPak(OSMesgQueue* queue, OSPfs* pfs, int channel) { - s32 ret; + s32 ret = 0; u16 sum; u16 isum; u8 temp[BLOCKSIZE]; @@ -77,13 +77,13 @@ s32 osPfsInitPak(OSMesgQueue* queue, OSPfs* pfs, int channel) { } static s32 __osPfsCheckRamArea(OSPfs* pfs) { - s32 i = 0; + s32 i; s32 ret = 0; u8 temp1[BLOCKSIZE]; u8 temp2[BLOCKSIZE]; u8 save[BLOCKSIZE]; - ERRCK(__osPfsSelectBank(pfs, 0)); + ERRCK(__osPfsSelectBank(pfs, PFS_ID_BANK_256K)); ERRCK(__osContRamRead(pfs->queue, pfs->channel, 0, save)); for (i = 0; i < BLOCKSIZE; i++) { @@ -97,5 +97,6 @@ static s32 __osPfsCheckRamArea(OSPfs* pfs) { return PFS_ERR_DEVICE; } - return __osContRamWrite(pfs->queue, pfs->channel, 0, save, FALSE); + ret = __osContRamWrite(pfs->queue, pfs->channel, 0, save, FALSE); + return ret; } diff --git a/src/io/pfsisplug.c b/src/io/pfsisplug.c index 71a18d9..6c425e9 100644 --- a/src/io/pfsisplug.c +++ b/src/io/pfsisplug.c @@ -84,7 +84,7 @@ void __osPfsGetInitData(u8* pattern, OSContStatus* data) { requestformat = *((__OSContRequesFormat*)ptr); data->errno = CHNL_ERR(requestformat); - if (data->errno) { + if (data->errno != 0) { continue; } diff --git a/src/io/pfsnumfiles.c b/src/io/pfsnumfiles.c index 5c47ead..9f52fb4 100644 --- a/src/io/pfsnumfiles.c +++ b/src/io/pfsnumfiles.c @@ -20,5 +20,7 @@ s32 osPfsNumFiles(OSPfs* pfs, s32* max_files, s32* files_used) { } *files_used = files; *max_files = pfs->dir_size; - return __osPfsGetStatus(pfs->queue, pfs->channel); + + ret = __osPfsGetStatus(pfs->queue, pfs->channel); + return ret; } diff --git a/src/io/pfsreadwritefile.c b/src/io/pfsreadwritefile.c index bc302c4..7a6e691 100644 --- a/src/io/pfsreadwritefile.c +++ b/src/io/pfsreadwritefile.c @@ -33,15 +33,15 @@ s32 osPfsReadWriteFile(OSPfs* pfs, s32 file_no, u8 flag, int offset, int size_in u8 bank; u16 blockno; - if (file_no >= pfs->dir_size || file_no < 0) { + if ((file_no >= (s32)pfs->dir_size) || (file_no < 0)) { return PFS_ERR_INVALID; } - if (size_in_bytes <= 0 || ((size_in_bytes & (BLOCKSIZE - 1)) != 0)) { + if ((size_in_bytes <= 0) || ((size_in_bytes % BLOCKSIZE) != 0)) { return PFS_ERR_INVALID; } - if (offset < 0 || ((offset & (BLOCKSIZE - 1)) != 0)) { + if ((offset < 0) || ((offset % BLOCKSIZE) != 0)) { return PFS_ERR_INVALID; } @@ -111,5 +111,6 @@ s32 osPfsReadWriteFile(OSPfs* pfs, s32 file_no, u8 flag, int offset, int size_in ERRCK(__osContRamWrite(pfs->queue, pfs->channel, pfs->dir_table + file_no, (u8*)&dir, FALSE)); } - return __osPfsGetStatus(pfs->queue, pfs->channel); + ret = __osPfsGetStatus(pfs->queue, pfs->channel); + return ret; } diff --git a/src/io/pi.c b/src/io/pi.c index aff4de6..a9cde68 100644 --- a/src/io/pi.c +++ b/src/io/pi.c @@ -9,6 +9,7 @@ int __osPiDeviceBusy() { register u32 stat = IO_READ(PI_STATUS_REG); if (stat & (PI_STATUS_DMA_BUSY | PI_STATUS_IO_BUSY)) { return 1; -} - return 0; + } else { + return 0; + } } diff --git a/src/io/piacs.c b/src/io/piacs.c index 298ae85..bd896fb 100644 --- a/src/io/piacs.c +++ b/src/io/piacs.c @@ -16,7 +16,7 @@ void __osPiGetAccess(void) { OSMesg dummyMesg; if (!__osPiAccessQueueEnabled) { __osPiCreateAccessQueue(); -} + } osRecvMesg(&__osPiAccessQueue, &dummyMesg, OS_MESG_BLOCK); } diff --git a/src/io/pidma.c b/src/io/pidma.c index 6bde859..0584e12 100644 --- a/src/io/pidma.c +++ b/src/io/pidma.c @@ -1,12 +1,48 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "piint.h" s32 osPiStartDma(OSIoMesg* mb, s32 priority, s32 direction, u32 devAddr, void* dramAddr, u32 size, OSMesgQueue* mq) { register s32 ret; if (!__osPiDevMgr.active) { +#ifdef _DEBUG + __osError(ERR_OSPISTARTDMA_PIMGR, 0); +#endif return -1; } +#ifdef _DEBUG + if ((priority != OS_MESG_PRI_NORMAL) && (priority != OS_MESG_PRI_HIGH)) { + __osError(ERR_OSPISTARTDMA_PRI, 1, priority); + return -1; + } + + if ((direction != OS_READ) && (direction != OS_WRITE)) { + __osError(ERR_OSPISTARTDMA_DIR, 1, direction); + return -1; + } + + if (devAddr & 0x1) { + __osError(ERR_OSPISTARTDMA_DEVADDR, 1, devAddr); + return -1; + } + + if ((u32)dramAddr & 0x7) { + __osError(ERR_OSPISTARTDMA_ADDR, 1, dramAddr); + return -1; + } + + if (size & 0x1) { + __osError(ERR_OSPISTARTDMA_SIZE, 1, size); + return -1; + } + + if ((size == 0) || (size > (16 * 1024 * 1024))) { + __osError(ERR_OSPISTARTDMA_RANGE, 1, size); + return -1; + } +#endif + if (direction == OS_READ) { mb->hdr.type = OS_MESG_TYPE_DMAREAD; } else { diff --git a/src/io/pigetcmdq.c b/src/io/pigetcmdq.c index 8a57147..4724301 100644 --- a/src/io/pigetcmdq.c +++ b/src/io/pigetcmdq.c @@ -4,7 +4,7 @@ OSMesgQueue* osPiGetCmdQueue(void) { if (!__osPiDevMgr.active) { return NULL; + } else { + return __osPiDevMgr.cmdQueue; } - - return __osPiDevMgr.cmdQueue; } diff --git a/src/io/piint.h b/src/io/piint.h index 734fdde..0c505fa 100644 --- a/src/io/piint.h +++ b/src/io/piint.h @@ -114,9 +114,11 @@ s32 __osEPiRawStartDma(OSPiHandle *, s32 , u32 , void *, u32 ); OSMesgQueue *osPiGetCmdQueue(void); #define WAIT_ON_IOBUSY(stat) \ - while (stat = IO_READ(PI_STATUS_REG), stat & (PI_STATUS_IO_BUSY | PI_STATUS_DMA_BUSY)) \ - ; \ - (void)0 + { \ + stat = IO_READ(PI_STATUS_REG); \ + while (stat & (PI_STATUS_IO_BUSY | PI_STATUS_DMA_BUSY)) \ + stat = IO_READ(PI_STATUS_REG); \ + } (void)0 #define UPDATE_REG(pihandle, reg, var) \ if (cHandle->var != pihandle->var) \ diff --git a/src/io/pimgr.c b/src/io/pimgr.c index bcfd6e0..56a92ad 100644 --- a/src/io/pimgr.c +++ b/src/io/pimgr.c @@ -1,53 +1,108 @@ #include "macros.h" #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "piint.h" +#include "PR/rdb.h" + +static OSThread piThread ALIGNED(8); +static char piThreadStack[OS_PIM_STACKSIZE] ALIGNED(16); + +#ifndef _FINALROM +static OSThread ramromThread ALIGNED(8); +static char ramromThreadStack[1024] ALIGNED(16); +static OSMesgQueue getRamromQ ALIGNED(8); +static OSMesg getRamromBuf[1]; +static OSMesgQueue freeRamromQ ALIGNED(8); +static OSMesg freeRamromBuf[1]; +static void ramromMain(void*); +#endif + +static OSMesgQueue piEventQueue ALIGNED(8); +static OSMesg piEventBuf[1]; OSDevMgr __osPiDevMgr = { 0 }; OSPiHandle* __osPiTable = NULL; OSPiHandle __Dom1SpeedParam ALIGNED(8); OSPiHandle __Dom2SpeedParam ALIGNED(8); OSPiHandle* __osCurrentHandle[2] ALIGNED(8) = { &__Dom1SpeedParam, &__Dom2SpeedParam }; -static OSThread piThread; -static char piThreadStack[OS_PIM_STACKSIZE]; -static OSMesgQueue piEventQueue; -static OSMesg piEventBuf[1]; void osCreatePiManager(OSPri pri, OSMesgQueue* cmdQ, OSMesg* cmdBuf, s32 cmdMsgCnt) { u32 savedMask; OSPri oldPri; OSPri myPri; - if (!__osPiDevMgr.active) { - osCreateMesgQueue(cmdQ, cmdBuf, cmdMsgCnt); - osCreateMesgQueue(&piEventQueue, (OSMesg*)piEventBuf, 1); +#ifdef _DEBUG + if ((pri < OS_PRIORITY_IDLE) || (pri > OS_PRIORITY_MAX)) { + __osError(ERR_OSCREATEPIMANAGER, 1, pri); + return; + } +#endif - if (!__osPiAccessQueueEnabled) { - __osPiCreateAccessQueue(); - } + if (__osPiDevMgr.active) { + return; + } + osCreateMesgQueue(cmdQ, cmdBuf, cmdMsgCnt); + osCreateMesgQueue(&piEventQueue, (OSMesg*)piEventBuf, 1); - osSetEventMesg(OS_EVENT_PI, &piEventQueue, (OSMesg)0x22222222); - oldPri = -1; - myPri = osGetThreadPri(NULL); + if (!__osPiAccessQueueEnabled) { + __osPiCreateAccessQueue(); + } - if (myPri < pri) { - oldPri = myPri; - osSetThreadPri(NULL, pri); - } + osSetEventMesg(OS_EVENT_PI, &piEventQueue, (OSMesg)0x22222222); + oldPri = -1; + myPri = osGetThreadPri(NULL); - savedMask = __osDisableInt(); - __osPiDevMgr.active = 1; - __osPiDevMgr.thread = &piThread; - __osPiDevMgr.cmdQueue = cmdQ; - __osPiDevMgr.evtQueue = &piEventQueue; - __osPiDevMgr.acsQueue = &__osPiAccessQueue; - __osPiDevMgr.dma = __osPiRawStartDma; - __osPiDevMgr.edma = __osEPiRawStartDma; - osCreateThread(&piThread, 0, __osDevMgrMain, &__osPiDevMgr, &piThreadStack[OS_PIM_STACKSIZE], pri); - osStartThread(&piThread); - __osRestoreInt(savedMask); + if (myPri < pri) { + oldPri = myPri; + osSetThreadPri(NULL, pri); + } - if (oldPri != -1) { - osSetThreadPri(NULL, oldPri); - } + savedMask = __osDisableInt(); + __osPiDevMgr.active = 1; + __osPiDevMgr.thread = &piThread; + __osPiDevMgr.cmdQueue = cmdQ; + __osPiDevMgr.evtQueue = &piEventQueue; + __osPiDevMgr.acsQueue = &__osPiAccessQueue; + __osPiDevMgr.dma = __osPiRawStartDma; + __osPiDevMgr.edma = __osEPiRawStartDma; + osCreateThread(&piThread, 0, __osDevMgrMain, &__osPiDevMgr, &piThreadStack[OS_PIM_STACKSIZE], pri); + osStartThread(&piThread); + +#ifndef _FINALROM + osCreateThread(&ramromThread, 0, ramromMain, NULL, ramromThreadStack + 1024, (OSPri)pri - 1); + osStartThread(&ramromThread); +#endif + __osRestoreInt(savedMask); + + if (oldPri != -1) { + osSetThreadPri(NULL, oldPri); } } + +#ifndef _FINALROM +static void ramromMain(void* arg) { + u32 sent; + u8 tmp[3]; + + osCreateMesgQueue(&getRamromQ, getRamromBuf, 1); + osCreateMesgQueue(&freeRamromQ, freeRamromBuf, 1); + osSetEventMesg(OS_EVENT_RDB_REQ_RAMROM, &getRamromQ, NULL); + osSetEventMesg(OS_EVENT_RDB_FREE_RAMROM, &freeRamromQ, NULL); + + while (TRUE) { + osRecvMesg(&getRamromQ, NULL, OS_MESG_BLOCK); + + __osPiGetAccess(); + + sent = 0; + + while (sent < 1) { + sent += __osRdbSend(tmp, 1, RDB_TYPE_GtoH_RAMROM); + } + + osRecvMesg(&freeRamromQ, NULL, OS_MESG_BLOCK); + + __osPiRelAccess(); + } +} +#endif diff --git a/src/io/pirawdma.c b/src/io/pirawdma.c index d766064..d5ea8c3 100644 --- a/src/io/pirawdma.c +++ b/src/io/pirawdma.c @@ -1,4 +1,5 @@ #include "piint.h" +#include "PR/ultraerror.h" // TODO: this comes from a header #ident "$Revision: 1.17 $" @@ -6,6 +7,33 @@ s32 __osPiRawStartDma(s32 direction, u32 devAddr, void* dramAddr, u32 size) { register u32 stat; +#ifdef _DEBUG + if ((direction != OS_READ) && (direction != OS_WRITE)) { + __osError(ERR_OSPIRAWSTARTDMA_DIR, 1, direction); + return -1; + } + + if (devAddr & 0x1) { + __osError(ERR_OSPIRAWSTARTDMA_DEVADDR, 1, devAddr); + return -1; + } + + if ((u32)dramAddr & 0x7) { + __osError(ERR_OSPIRAWSTARTDMA_ADDR, 1, dramAddr); + return -1; + } + + if (size & 0x1) { + __osError(ERR_OSPIRAWSTARTDMA_SIZE, 1, size); + return -1; + } + + if ((size == 0) || (size > (16 * 1024 * 1024))) { + __osError(ERR_OSPIRAWSTARTDMA_RANGE, 1, size); + return -1; + } +#endif + WAIT_ON_IOBUSY(stat); IO_WRITE(PI_DRAM_ADDR_REG, osVirtualToPhysical(dramAddr)); diff --git a/src/io/pirawread.c b/src/io/pirawread.c index 8531d17..0fd6a2e 100644 --- a/src/io/pirawread.c +++ b/src/io/pirawread.c @@ -1,4 +1,49 @@ #include "piint.h" +#include "assert.h" +#include "PR/ultraerror.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" @@ -6,6 +51,15 @@ s32 __osPiRawReadIo(u32 devAddr, u32* data) { register u32 stat; +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIRAWREADIO, 1, devAddr); + return -1; + } + + assert(data != NULL); +#endif + WAIT_ON_IOBUSY(stat); *data = IO_READ((u32)osRomBase | devAddr); diff --git a/src/io/pirawwrite.c b/src/io/pirawwrite.c index 5e9d7c5..92eba84 100644 --- a/src/io/pirawwrite.c +++ b/src/io/pirawwrite.c @@ -1,4 +1,5 @@ #include "piint.h" +#include "PR/ultraerror.h" // TODO: this comes from a header #ident "$Revision: 1.17 $" @@ -6,6 +7,13 @@ s32 __osPiRawWriteIo(u32 devAddr, u32 data) { register u32 stat; +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIRAWWRITEIO, 1, devAddr); + return -1; + } +#endif + WAIT_ON_IOBUSY(stat); IO_WRITE((u32)osRomBase | devAddr, data); diff --git a/src/io/piread.c b/src/io/piread.c index d6a1213..42bcf3e 100644 --- a/src/io/piread.c +++ b/src/io/piread.c @@ -1,10 +1,16 @@ #include "piint.h" - - +#include "PR/ultraerror.h" s32 osPiReadIo(u32 devAddr, u32* data) { register s32 ret; +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIREADIO, 1, devAddr); + return -1; + } +#endif + __osPiGetAccess(); ret = __osPiRawReadIo(devAddr, data); __osPiRelAccess(); diff --git a/src/io/piwrite.c b/src/io/piwrite.c index bd8f611..75c00d1 100644 --- a/src/io/piwrite.c +++ b/src/io/piwrite.c @@ -1,10 +1,16 @@ #include "piint.h" - - +#include "PR/ultraerror.h" s32 osPiWriteIo(u32 devAddr, u32 data) { register s32 ret; +#ifdef _DEBUG + if (devAddr & 0x3) { + __osError(ERR_OSPIWRITEIO, 1, devAddr); + return -1; + } +#endif + __osPiGetAccess(); ret = __osPiRawWriteIo(devAddr, data); __osPiRelAccess(); diff --git a/src/io/si.c b/src/io/si.c index f97691b..0188927 100644 --- a/src/io/si.c +++ b/src/io/si.c @@ -9,7 +9,7 @@ int __osSiDeviceBusy() { if (stat & (SI_STATUS_DMA_BUSY | SI_STATUS_RD_BUSY)) { return TRUE; + } else { + return FALSE; } - - return FALSE; } diff --git a/src/io/siacs.c b/src/io/siacs.c index 4b2fd06..8ef5b3f 100644 --- a/src/io/siacs.c +++ b/src/io/siacs.c @@ -16,7 +16,7 @@ void __osSiGetAccess(void) { OSMesg dummyMesg; if (!__osSiAccessQueueEnabled) { __osSiCreateAccessQueue(); -} + } osRecvMesg(&__osSiAccessQueue, &dummyMesg, OS_MESG_BLOCK); } diff --git a/src/io/sirawdma.c b/src/io/sirawdma.c index 6e5fd09..e2dd03f 100644 --- a/src/io/sirawdma.c +++ b/src/io/sirawdma.c @@ -1,10 +1,60 @@ #include "PR/os_internal.h" +#include "assert.h" #include "siint.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osSiRawStartDma(s32 direction, void* dramAddr) { +#ifdef _DEBUG + assert(((u32)dramAddr & 0x3) == 0); +#endif if (IO_READ(SI_STATUS_REG) & (SI_STATUS_DMA_BUSY | SI_STATUS_RD_BUSY)) { return -1; } diff --git a/src/io/sirawread.c b/src/io/sirawread.c index 0d759c7..0b605db 100644 --- a/src/io/sirawread.c +++ b/src/io/sirawread.c @@ -1,10 +1,58 @@ #include "PR/os_internal.h" +#include "assert.h" #include "siint.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osSiRawReadIo(u32 devAddr, u32* data) { +#ifdef _DEBUG + assert((devAddr & 0x3) == 0); + assert(data != NULL); +#endif if (__osSiDeviceBusy()) { return -1; } diff --git a/src/io/sirawwrite.c b/src/io/sirawwrite.c index 5be1441..0a50ace 100644 --- a/src/io/sirawwrite.c +++ b/src/io/sirawwrite.c @@ -1,10 +1,57 @@ #include "PR/os_internal.h" #include "siint.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osSiRawWriteIo(u32 devAddr, u32 data) { +#ifdef _DEBUG + assert((devAddr & 0x3) == 0); +#endif if (__osSiDeviceBusy()) { return -1; } diff --git a/src/io/sp.c b/src/io/sp.c index 95d5b20..3ad9076 100644 --- a/src/io/sp.c +++ b/src/io/sp.c @@ -11,7 +11,7 @@ int __osSpDeviceBusy() { if (stat & (SP_STATUS_DMA_BUSY | SP_STATUS_DMA_FULL | SP_STATUS_IO_FULL)) { return TRUE; + } else { + return FALSE; } - - return FALSE; } diff --git a/src/io/sprawdma.c b/src/io/sprawdma.c index 2f9f46e..6224b1f 100644 --- a/src/io/sprawdma.c +++ b/src/io/sprawdma.c @@ -3,12 +3,59 @@ #include "../os/osint.h" #include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osSpRawStartDma(s32 direction, u32 devAddr, void* dramAddr, u32 size) { - // These asserts are present in debug builds, but the line numbers won't match as-is - // TODO Add an assert spoofing macro that lets you specify a line number assert(((u32)devAddr & 0x7) == 0); assert(((u32)dramAddr & 0x7) == 0); assert(((u32)size & 0x7) == 0); diff --git a/src/io/sprawread.c b/src/io/sprawread.c index 125dae0..4609ebc 100644 --- a/src/io/sprawread.c +++ b/src/io/sprawread.c @@ -1,11 +1,57 @@ #include "PR/os_internal.h" #include "PR/rcp.h" #include "../os/osint.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osSpRawReadIo(u32 devAddr, u32* data) { +#ifdef _DEBUG + assert((devAddr & 0x3) == 0); + assert(data != NULL); +#endif if (__osSpDeviceBusy()) { return -1; } diff --git a/src/io/sprawwrite.c b/src/io/sprawwrite.c index f6451ae..66510d1 100644 --- a/src/io/sprawwrite.c +++ b/src/io/sprawwrite.c @@ -1,11 +1,57 @@ #include "PR/os_internal.h" #include "PR/rcp.h" #include "../os/osint.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 __osSpRawWriteIo(u32 devAddr, u32 data) { +#ifdef _DEBUG + assert((devAddr & 0x3) == 0); +#endif if (__osSpDeviceBusy()) { return -1; } diff --git a/src/io/sptask.c b/src/io/sptask.c index 7ddcef3..6b5e903 100644 --- a/src/io/sptask.c +++ b/src/io/sptask.c @@ -1,4 +1,5 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "PR/sptask.h" #include "PR/rcp.h" #include "../os/osint.h" @@ -28,6 +29,25 @@ static OSTask* _VirtualToPhysicalTask(OSTask* intp) { void osSpTaskLoad(OSTask* intp) { OSTask* tp; +#ifdef _DEBUG + if ((intp->t.dram_stack != 0x0) && ((u32)intp->t.dram_stack & 0xf)) { + __osError(ERR_OSSPTASKLOAD_DRAM, 1, intp->t.dram_stack); + return; + } + if ((intp->t.output_buff != 0x0) && ((u32)intp->t.output_buff & 0xf)) { + __osError(ERR_OSSPTASKLOAD_OUT, 1, intp->t.output_buff); + return; + } + if ((intp->t.output_buff_size != 0x0) && ((u32)intp->t.output_buff_size & 0xf)) { + __osError(ERR_OSSPTASKLOAD_OUTSIZE, 1, intp->t.output_buff_size); + return; + } + if ((intp->t.yield_data_ptr != 0x0) && ((u32)intp->t.yield_data_ptr & 0xf)) { + __osError(ERR_OSSPTASKLOAD_YIELD, 1, intp->t.yield_data_ptr); + return; + } +#endif + tp = _VirtualToPhysicalTask(intp); if (tp->t.flags & OS_TASK_YIELDED) { @@ -36,7 +56,7 @@ void osSpTaskLoad(OSTask* intp) { intp->t.flags &= ~OS_TASK_YIELDED; if (tp->t.flags & OS_TASK_LOADABLE) { tp->t.ucode = (u64*)IO_READ((u32)intp->t.yield_data_ptr + OS_YIELD_DATA_SIZE - 4); -} + } } osWritebackDCache(tp, sizeof(OSTask)); diff --git a/src/io/sptaskyielded.c b/src/io/sptaskyielded.c index e301630..3ecab55 100644 --- a/src/io/sptaskyielded.c +++ b/src/io/sptaskyielded.c @@ -7,11 +7,11 @@ OSYieldResult osSpTaskYielded(OSTask* tp) { OSYieldResult result; status = __osSpGetStatus(); - result = status >> 8; - result &= 1; + result = (status & SP_STATUS_YIELDED) ? OS_TASK_YIELDED : 0; if (status & SP_STATUS_YIELD) { - tp->t.flags = ~(OS_TASK_DP_WAIT) & (tp->t.flags | result); + tp->t.flags |= result; + tp->t.flags &= ~(OS_TASK_DP_WAIT); } return result; diff --git a/src/io/vi.c b/src/io/vi.c index 0d6248c..246f01f 100644 --- a/src/io/vi.c +++ b/src/io/vi.c @@ -1,7 +1,7 @@ -#include -#include -#include -#include +#include "macros.h" +#include "PR/os_internal.h" +#include "PR/R4300.h" +#include "PR/rcp.h" #include "viint.h" // TODO: this comes from a header diff --git a/src/io/viblack.c b/src/io/viblack.c index 21ea939..30dd85c 100644 --- a/src/io/viblack.c +++ b/src/io/viblack.c @@ -1,4 +1,4 @@ -#include +#include "PR/os_internal.h" #include "viint.h" // TODO: this comes from a header diff --git a/src/io/viextendvstart.c b/src/io/viextendvstart.c index 4c8a355..a1ca8e6 100644 --- a/src/io/viextendvstart.c +++ b/src/io/viextendvstart.c @@ -1,7 +1,19 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "viint.h" void osViExtendVStart(u32 value) { +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(134, 0); + return 0; + } + + if (value > 48) { + __osError(135, 1, value); + return 0; + } +#endif __additional_scanline = value; return; } diff --git a/src/io/vifade.c b/src/io/vifade.c index 2812860..6766871 100644 --- a/src/io/vifade.c +++ b/src/io/vifade.c @@ -1,4 +1,4 @@ -#include +#include "PR/os_internal.h" #include "viint.h" // TODO: this comes from a header diff --git a/src/io/vigetcurrcontext.c b/src/io/vigetcurrcontext.c index 355d4ba..7b1df9b 100644 --- a/src/io/vigetcurrcontext.c +++ b/src/io/vigetcurrcontext.c @@ -1,4 +1,4 @@ -#include +#include "PR/os_internal.h" #include "viint.h" // TODO: this comes from a header diff --git a/src/io/vigetcurrframebuf.c b/src/io/vigetcurrframebuf.c index 34a83e0..e83006a 100644 --- a/src/io/vigetcurrframebuf.c +++ b/src/io/vigetcurrframebuf.c @@ -1,10 +1,20 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "viint.h" void* osViGetCurrentFramebuffer(void) { - register u32 saveMask = __osDisableInt(); - void* framep = __osViCurr->framep; + register u32 saveMask; + void* framep; +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVIGETCURRENTFRAMEBUFFER, 0); + return 0; + } +#endif + + saveMask = __osDisableInt(); + framep = __osViCurr->framep; __osRestoreInt(saveMask); return framep; } diff --git a/src/io/vigetfield.c b/src/io/vigetfield.c index 395e912..9dcb7fc 100644 --- a/src/io/vigetfield.c +++ b/src/io/vigetfield.c @@ -1,5 +1,5 @@ -#include -#include +#include "PR/os_internal.h" +#include "PR/rcp.h" u32 osViGetCurrentField(void) { return IO_READ(VI_CURRENT_REG) & 1; diff --git a/src/io/vigetline.c b/src/io/vigetline.c index 1eed3cd..5667d61 100644 --- a/src/io/vigetline.c +++ b/src/io/vigetline.c @@ -1,5 +1,5 @@ -#include -#include +#include "PR/os_internal.h" +#include "PR/rcp.h" u32 osViGetCurrentLine(void) { return IO_READ(VI_CURRENT_REG); diff --git a/src/io/vigetmode.c b/src/io/vigetmode.c index bb3fcd0..2507372 100644 --- a/src/io/vigetmode.c +++ b/src/io/vigetmode.c @@ -1,10 +1,21 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "viint.h" u32 osViGetCurrentMode(void) { - register u32 savedMask = __osDisableInt(); - register u32 modeType = __osViCurr->modep->type; + register u32 saveMask; + register u32 modeType; - __osRestoreInt(savedMask); +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVIGETCURRENTMODE, 0); + return -1; + } +#endif + + saveMask = __osDisableInt(); + modeType = (u32)__osViCurr->modep->type; + + __osRestoreInt(saveMask); return modeType; } diff --git a/src/io/vigetnextcontext.c b/src/io/vigetnextcontext.c index 790df14..bb6012a 100644 --- a/src/io/vigetnextcontext.c +++ b/src/io/vigetnextcontext.c @@ -1,4 +1,4 @@ -#include +#include "PR/os_internal.h" #include "viint.h" __OSViContext* __osViGetNextContext(void) { diff --git a/src/io/vigetnextframebuf.c b/src/io/vigetnextframebuf.c index bf409cc..2985358 100644 --- a/src/io/vigetnextframebuf.c +++ b/src/io/vigetnextframebuf.c @@ -1,10 +1,20 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "viint.h" void* osViGetNextFramebuffer(void) { - register u32 saveMask = __osDisableInt(); - void* framep = __osViNext->framep; + register u32 saveMask; + void* framep; +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVIGETNEXTFRAMEBUFFER, 0); + return NULL; + } +#endif + + saveMask = __osDisableInt(); + framep = __osViNext->framep; __osRestoreInt(saveMask); return framep; } diff --git a/src/io/vigetstat.c b/src/io/vigetstat.c index eea94a7..8fc6f38 100644 --- a/src/io/vigetstat.c +++ b/src/io/vigetstat.c @@ -1,5 +1,5 @@ -#include -#include +#include "PR/os_internal.h" +#include "PR/rcp.h" u32 osViGetStatus(void) { return IO_READ(VI_STATUS_REG); diff --git a/src/io/viint.h b/src/io/viint.h index 3ae94c8..d084a50 100644 --- a/src/io/viint.h +++ b/src/io/viint.h @@ -67,4 +67,5 @@ extern __OSViContext *__osViNext; extern u32 __additional_scanline; __OSViContext *__osViGetCurrentContext(void); void __osViInit(void); +extern OSDevMgr __osViDevMgr; #endif diff --git a/src/io/vimgr.c b/src/io/vimgr.c index e9c8cdd..761ae0d 100644 --- a/src/io/vimgr.c +++ b/src/io/vimgr.c @@ -1,6 +1,7 @@ -#include -#include -#include +#include "macros.h" +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "PR/rcp.h" #include "viint.h" #include "../os/osint.h" @@ -8,7 +9,7 @@ OSDevMgr __osViDevMgr = { 0 }; u32 __additional_scanline = 0; static OSThread viThread; static unsigned char viThreadStack[OS_VIM_STACKSIZE] ALIGNED(16); -static OSMesgQueue viEventQueue; +static OSMesgQueue viEventQueue ALIGNED(8); static OSMesg viEventBuf[5] ALIGNED(8); static OSIoMesg viRetraceMsg ALIGNED(8); static OSIoMesg viCounterMsg ALIGNED(8); @@ -16,45 +17,53 @@ static OSIoMesg viCounterMsg ALIGNED(8); static void viMgrMain(void* arg); void osCreateViManager(OSPri pri) { u32 savedMask; - OSPri myPri; OSPri oldPri; + OSPri myPri; - if (!__osViDevMgr.active) { - __osTimerServicesInit(); - __additional_scanline = 0; - osCreateMesgQueue(&viEventQueue, viEventBuf, ARRLEN(viEventBuf)); - viRetraceMsg.hdr.type = OS_MESG_TYPE_VRETRACE; - viRetraceMsg.hdr.pri = OS_MESG_PRI_NORMAL; - viRetraceMsg.hdr.retQueue = NULL; - viCounterMsg.hdr.type = OS_MESG_TYPE_COUNTER; - viCounterMsg.hdr.pri = OS_MESG_PRI_NORMAL; - viCounterMsg.hdr.retQueue = NULL; - osSetEventMesg(OS_EVENT_VI, &viEventQueue, &viRetraceMsg); - osSetEventMesg(OS_EVENT_COUNTER, &viEventQueue, &viCounterMsg); - oldPri = -1; - myPri = osGetThreadPri(NULL); +#ifdef _DEBUG + if ((pri < OS_PRIORITY_IDLE) || (pri > OS_PRIORITY_MAX)) { + __osError(ERR_OSCREATEVIMANAGER, 1, pri); + return 0; + } +#endif - if (myPri < pri) { - oldPri = myPri; - osSetThreadPri(NULL, pri); - } + if (__osViDevMgr.active) { + return 0; + } + __osTimerServicesInit(); + __additional_scanline = 0; + osCreateMesgQueue(&viEventQueue, viEventBuf, ARRLEN(viEventBuf)); + viRetraceMsg.hdr.type = OS_MESG_TYPE_VRETRACE; + viRetraceMsg.hdr.pri = OS_MESG_PRI_NORMAL; + viRetraceMsg.hdr.retQueue = NULL; + viCounterMsg.hdr.type = OS_MESG_TYPE_COUNTER; + viCounterMsg.hdr.pri = OS_MESG_PRI_NORMAL; + viCounterMsg.hdr.retQueue = NULL; + osSetEventMesg(OS_EVENT_VI, &viEventQueue, &viRetraceMsg); + osSetEventMesg(OS_EVENT_COUNTER, &viEventQueue, &viCounterMsg); + oldPri = -1; + myPri = osGetThreadPri(NULL); - savedMask = __osDisableInt(); - __osViDevMgr.active = TRUE; - __osViDevMgr.thread = &viThread; - __osViDevMgr.cmdQueue = &viEventQueue; - __osViDevMgr.evtQueue = &viEventQueue; - __osViDevMgr.acsQueue = NULL; - __osViDevMgr.dma = NULL; - __osViDevMgr.edma = NULL; - osCreateThread(&viThread, 0, viMgrMain, &__osViDevMgr, &viThreadStack[OS_VIM_STACKSIZE], pri); - __osViInit(); - osStartThread(&viThread); - __osRestoreInt(savedMask); + if (myPri < pri) { + oldPri = myPri; + osSetThreadPri(NULL, pri); + } - if (oldPri != -1) { - osSetThreadPri(0, oldPri); - } + savedMask = __osDisableInt(); + __osViDevMgr.active = TRUE; + __osViDevMgr.thread = &viThread; + __osViDevMgr.cmdQueue = &viEventQueue; + __osViDevMgr.evtQueue = &viEventQueue; + __osViDevMgr.acsQueue = NULL; + __osViDevMgr.dma = NULL; + __osViDevMgr.edma = NULL; + osCreateThread(&viThread, 0, viMgrMain, &__osViDevMgr, &viThreadStack[OS_VIM_STACKSIZE], pri); + __osViInit(); + osStartThread(&viThread); + __osRestoreInt(savedMask); + + if (oldPri != -1) { + osSetThreadPri(NULL, oldPri); } } @@ -72,7 +81,7 @@ static void viMgrMain(void* arg) { retrace = vc->retraceCount; if (retrace == 0) { retrace = 1; -} + } dm = (OSDevMgr*)arg; while (TRUE) { @@ -86,7 +95,7 @@ static void viMgrMain(void* arg) { vc = __osViGetCurrentContext(); if (vc->msgq != NULL) { osSendMesg(vc->msgq, vc->msg, OS_MESG_NOBLOCK); -} + } retrace = vc->retraceCount; } @@ -106,6 +115,8 @@ static void viMgrMain(void* arg) { case OS_MESG_TYPE_COUNTER: __osTimerInterrupt(); break; + default: + break; } } } diff --git a/src/io/virepeatline.c b/src/io/virepeatline.c index 29ce3a9..1bc4984 100644 --- a/src/io/virepeatline.c +++ b/src/io/virepeatline.c @@ -1,4 +1,4 @@ -#include +#include "PR/os_internal.h" #include "viint.h" // TODO: this comes from a header diff --git a/src/io/visetevent.c b/src/io/visetevent.c index 19fbfce..ebf3f82 100644 --- a/src/io/visetevent.c +++ b/src/io/visetevent.c @@ -1,11 +1,67 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "assert.h" #include "viint.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" void osViSetEvent(OSMesgQueue* mq, OSMesg m, u32 retraceCount) { - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVISETEVENT, 0); + return 0; + } + + assert(mq != NULL); +#endif + + saveMask = __osDisableInt(); __osViNext->msgq = mq; __osViNext->msg = m; diff --git a/src/io/visetmode.c b/src/io/visetmode.c index 04d58cb..1f69993 100644 --- a/src/io/visetmode.c +++ b/src/io/visetmode.c @@ -1,11 +1,64 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "assert.h" #include "viint.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" void osViSetMode(OSViMode* modep) { - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVISETMODE, 0); + return 0; + } + + assert(modep != NULL); +#endif + + saveMask = __osDisableInt(); __osViNext->modep = modep; __osViNext->state = VI_STATE_MODE_UPDATED; diff --git a/src/io/visetspecial.c b/src/io/visetspecial.c index 7059dcf..1b22dd4 100644 --- a/src/io/visetspecial.c +++ b/src/io/visetspecial.c @@ -1,12 +1,31 @@ -#include -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "PR/rcp.h" #include "viint.h" // TODO: this comes from a header #ident "$Revision: 1.17 $" +#define OS_VI_SPECIAL_MAX \ + (OS_VI_GAMMA_ON | OS_VI_GAMMA_OFF | OS_VI_GAMMA_DITHER_ON | OS_VI_GAMMA_DITHER_OFF | OS_VI_DIVOT_ON | \ + OS_VI_DIVOT_OFF | OS_VI_DITHER_FILTER_ON | OS_VI_DITHER_FILTER_OFF) + void osViSetSpecialFeatures(u32 func) { - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVISETSPECIAL_VIMGR, 0); + return 0; + } + + if ((func < OS_VI_GAMMA_ON) || (func > OS_VI_SPECIAL_MAX)) { + __osError(ERR_OSVISETSPECIAL_VALUE, 1, func); + return 0; + } +#endif + + saveMask = __osDisableInt(); if ((func & OS_VI_GAMMA_ON) != 0) { __osViNext->control |= VI_CTRL_GAMMA_ON; diff --git a/src/io/visetxscale.c b/src/io/visetxscale.c index 24ecf92..6af6535 100644 --- a/src/io/visetxscale.c +++ b/src/io/visetxscale.c @@ -1,4 +1,6 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "PR/ultralog.h" #include "viint.h" // TODO: this comes from a header @@ -6,7 +8,26 @@ void osViSetXScale(f32 value) { register u32 nomValue; - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVISETXSCALE_VIMGR, 0); + return; + } + + if ((value < 0.25f) || (value > 1.0f)) { + __osError(ERR_OSVISETXSCALE_VALUE, 1, OS_LOG_FLOAT(value)); + + if (value < 0.25f) { + value = 0.25f; + } else { + value = 1.0f; + } + } +#endif + + saveMask = __osDisableInt(); __osViNext->x.factor = value; __osViNext->state |= VI_STATE_XSCALE_UPDATED; diff --git a/src/io/visetyscale.c b/src/io/visetyscale.c index 525e0eb..c1c96f4 100644 --- a/src/io/visetyscale.c +++ b/src/io/visetyscale.c @@ -1,11 +1,32 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "PR/ultralog.h" #include "viint.h" // TODO: this comes from a header #ident "$Revision: 1.17 $" void osViSetYScale(f32 value) { - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVISETYSCALE_VIMGR, 0); + return; + } + + if ((value < 0.05f) || (value > 1.0f)) { + __osError(ERR_OSVISETYSCALE_VALUE, 1, OS_LOG_FLOAT(value)); + + if (value < 0.05f) { + value = 0.05f; + } else { + value = 1.0f; + } + } +#endif + + saveMask = __osDisableInt(); __osViNext->y.factor = value; __osViNext->state |= VI_STATE_YSCALE_UPDATED; diff --git a/src/io/viswapbuf.c b/src/io/viswapbuf.c index 327ed60..aa077cd 100644 --- a/src/io/viswapbuf.c +++ b/src/io/viswapbuf.c @@ -1,11 +1,73 @@ -#include +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "assert.h" #include "viint.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" void osViSwapBuffer(void* frameBufPtr) { - u32 saveMask = __osDisableInt(); + u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSVISWAPBUFFER_VIMGR, 0); + return; + } + + assert(frameBufPtr != NULL); + + if ((u32)frameBufPtr & 0x3f) { + __osError(ERR_OSVISWAPBUFFER_ADDR, 1, frameBufPtr); + return; + } +#endif + + saveMask = __osDisableInt(); __osViNext->framep = frameBufPtr; __osViNext->state |= VI_STATE_BUFFER_UPDATED; diff --git a/src/io/viswapcontext.c b/src/io/viswapcontext.c index b4142a2..aac7cd9 100644 --- a/src/io/viswapcontext.c +++ b/src/io/viswapcontext.c @@ -1,5 +1,5 @@ -#include -#include +#include "PR/os_internal.h" +#include "PR/rcp.h" #include "viint.h" // TODO: this comes from a header @@ -9,8 +9,8 @@ void __osViSwapContext() { register OSViMode* vm; register __OSViContext* vc; u32 origin; - u32 vStart; u32 hStart; + u32 vStart; u32 nomValue; u32 field; diff --git a/src/io/vitbl.c b/src/io/vitbl.c index 9d7a17c..24dc787 100644 --- a/src/io/vitbl.c +++ b/src/io/vitbl.c @@ -1,5 +1,5 @@ -#include -#include +#include "PR/os.h" +#include "PR/rcp.h" #include "../io/viint.h" OSViMode osViModeTable[56] = { diff --git a/src/libc/ldiv.c b/src/libc/ldiv.c index 59644e9..b0d98c4 100644 --- a/src/libc/ldiv.c +++ b/src/libc/ldiv.c @@ -11,7 +11,7 @@ ldiv_t ldiv(long num, long denom) { ret.rem = num - denom * ret.quot; if (ret.quot < 0 && ret.rem > 0) { - ret.quot++; + ret.quot += 1; ret.rem -= denom; } @@ -25,7 +25,7 @@ lldiv_t lldiv(long long num, long long denom) { ret.rem = num - denom * ret.quot; if (ret.quot < 0 && ret.rem > 0) { - ret.quot++; + ret.quot += 1; ret.rem -= denom; } diff --git a/src/libc/llbit.c b/src/libc/llbit.c index f66673a..3e7e03b 100644 --- a/src/libc/llbit.c +++ b/src/libc/llbit.c @@ -6,9 +6,10 @@ s64 __ll_bit_extract(u64* addr, unsigned int start_bit, unsigned int length) { unsigned int rbits; u64 mask; - words = start_bit >> 6; - lbits = start_bit & ((1 << 6) - 1); + words = start_bit / 64; + lbits = start_bit & (64 - 1); rbits = 64 - (lbits + length); + addr += words; mask = ((u64)1 << length) - 1; mask = mask << rbits; @@ -21,8 +22,8 @@ u64 __ull_bit_extract(u64* addr, unsigned int start_bit, unsigned int length) { unsigned int rbits; u64 mask; - words = start_bit >> 6; - lbits = start_bit & ((1 << 6) - 1); + words = start_bit / 64; + lbits = start_bit & (64 - 1); rbits = 64 - (lbits + length); addr += words; mask = ((u64)1 << length) - 1; @@ -37,7 +38,7 @@ u64 __ll_bit_insert(u64* addr, unsigned int start_bit, unsigned int length, u64 unsigned long long llval; unsigned long long mask; - words = start_bit >> 6; + words = start_bit / 64; lbits = start_bit & 0x3f; rbits = 64 - (lbits + length); addr += words; diff --git a/src/libc/string.c b/src/libc/string.c index 5158452..ed4c480 100644 --- a/src/libc/string.c +++ b/src/libc/string.c @@ -9,7 +9,7 @@ char* strchr(const char* s, int c) { while (*s != ch) { if (*s == 0) { return NULL; -} + } s++; } return (char*)s; @@ -19,7 +19,7 @@ size_t strlen(const char* s) { const char* sc = s; while (*sc) { sc++; -} + } return sc - s; } @@ -27,7 +27,9 @@ void* memcpy(void* s1, const void* s2, size_t n) { char* su1 = (char*)s1; const char* su2 = (const char*)s2; while (n > 0) { - *su1++ = *su2++; + *su1 = *su2; + su1++; + su2++; n--; } return (void*)s1; diff --git a/src/libc/syncprintf.c b/src/libc/syncprintf.c index 5663856..6e13534 100644 --- a/src/libc/syncprintf.c +++ b/src/libc/syncprintf.c @@ -1,17 +1,38 @@ #include "stdarg.h" #include "PR/os.h" +extern void* __printfunc; + void __osSyncVPrintf(const char* fmt, va_list args) { - // these functions intentionally left blank. ifdeffed out in rom release + + int ans; +#ifndef _FINALROM + if (__printfunc != NULL) { + ans = _Printf(__printfunc, NULL, fmt, args); + } +#endif } void osSyncPrintf(const char* fmt, ...) { int ans; va_list ap; - // these functions intentionally left blank. ifdeffed out in rom release + +#ifndef _FINALROM + va_start(ap, fmt); + __osSyncVPrintf(fmt, ap); + va_end(ap); +#endif } void rmonPrintf(const char* fmt, ...) { int ans; va_list ap; + +#ifndef _FINALROM + va_start(ap, fmt); + if (__printfunc != NULL) { + ans = _Printf(__printfunc, NULL, fmt, ap); + } + va_end(ap); +#endif } diff --git a/src/libc/xldtob.c b/src/libc/xldtob.c index b032e57..2929955 100644 --- a/src/libc/xldtob.c +++ b/src/libc/xldtob.c @@ -69,34 +69,36 @@ void _Ldtob(_Pft* px, char code) { nsig = 0; xexp = 0; } else { - int i; - int n; + { + int i; + int n; - if (ldval < 0) { - ldval = -ldval; - } - - // what - if ((xexp = xexp * 30103 / 100000 - 4) < 0) { - n = ALIGN(-xexp, 4), xexp = -n; - - for (i = 0; n > 0; n >>= 1, i++) { - if (n & 1) { - ldval *= pows[i]; - } - } - } else if (xexp > 0) { - f64 factor = 1; - - xexp &= ~3; - - for (n = xexp, i = 0; n > 0; n >>= 1, i++) { - if (n & 1) { - factor *= pows[i]; - } + if (ldval < 0) { + ldval = -ldval; } - ldval /= factor; + // what + if ((xexp = xexp * 30103 / 100000 - 4) < 0) { + n = ALIGN(-xexp, 4), xexp = -n; + + for (i = 0; n > 0; n >>= 1, i++) { + if (n & 1) { + ldval *= pows[i]; + } + } + } else if (xexp > 0) { + f64 factor = 1; + + xexp &= ~3; + + for (n = xexp, i = 0; n > 0; n >>= 1, i++) { + if (n & 1) { + factor *= pows[i]; + } + } + + ldval /= factor; + } } { int gen = px->prec + ((code == 'f') ? 10 + xexp : 6); @@ -107,7 +109,7 @@ void _Ldtob(_Pft* px, char code) { for (*p++ = '0'; gen > 0 && 0 < ldval; p += 8) { int j; - int lo = ldval; + long lo = ldval; if ((gen -= 8) > 0) { ldval = (ldval - lo) * 1e8; @@ -136,7 +138,7 @@ void _Ldtob(_Pft* px, char code) { } if (nsig > 0) { - char drop = nsig < gen && '5' <= p[nsig] ? '9' : '0'; + const char drop = nsig < gen && '5' <= p[nsig] ? '9' : '0'; int n; for (n = nsig; p[--n] == drop;) { @@ -182,18 +184,17 @@ void _Genld(_Pft* px, char code, u8* p, s16 nsig, s16 xexp) { const unsigned char point = '.'; if (nsig <= 0) { - nsig = 1, p = "0"; // memes + nsig = 1, p = "0"; } if (code == 'f' || (code == 'g' || code == 'G') && xexp >= -4 && xexp < px->prec) { - xexp += 1; + xexp++; if (code != 'f') { if (((px->flags & 8) == 0) && nsig < px->prec) { px->prec = nsig; } - px->prec -= xexp; - if (px->prec < 0) { + if ((px->prec -= xexp) < 0) { px->prec = 0; } } @@ -216,7 +217,7 @@ void _Genld(_Pft* px, char code, u8* p, s16 nsig, s16 xexp) { nsig = px->prec; } - memcpy(&px->s[px->n1], p, px->n2 = nsig); // , memes (this one is insane) + memcpy(&px->s[px->n1], p, px->n2 = nsig); px->nz2 = px->prec - nsig; } else if (nsig < xexp) { memcpy(&px->s[px->n1], p, nsig); @@ -224,7 +225,7 @@ void _Genld(_Pft* px, char code, u8* p, s16 nsig, s16 xexp) { px->nz1 = xexp - nsig; if (px->prec > 0 || (px->flags & 8)) { px->s[px->n1] = point; - px->n2 += 1; + px->n2++; } px->nz2 = px->prec; @@ -255,11 +256,7 @@ void _Genld(_Pft* px, char code, u8* p, s16 nsig, s16 xexp) { px->prec = 0; } - if (code == 'g') { - code = 'e'; - } else { - code = 'E'; - } + code = (code == 'g') ? 'e' : 'E'; } px->s[px->n1++] = *p++; @@ -290,11 +287,11 @@ void _Genld(_Pft* px, char code, u8* p, s16 nsig, s16 xexp) { if (xexp >= 100) { if (xexp >= 1000) { - *p++ = (xexp / 1000) + '0', xexp %= 1000; // , memes + *p++ = (xexp / 1000) + '0', xexp %= 1000; } - *p++ = (xexp / 100) + '0', xexp %= 100; // , memes + *p++ = (xexp / 100) + '0', xexp %= 100; } - *p++ = (xexp / 10) + '0', xexp %= 10; // , memes + *p++ = (xexp / 10) + '0', xexp %= 10; *p++ = xexp + '0'; px->n2 = (size_t)p - ((size_t)px->s + px->n1); diff --git a/src/libc/xlitob.c b/src/libc/xlitob.c index f297df4..2b27b3a 100644 --- a/src/libc/xlitob.c +++ b/src/libc/xlitob.c @@ -19,11 +19,7 @@ void _Litob(_Pft *args, char type) { s32 i; unsigned long long ullval; - if (type == 'X') { - digs = udigs; - } else { - digs = ldigs; - } + digs = (type == 'X') ? udigs : ldigs; base = (type == 'o') ? 8 : ((type != 'x' && type != 'X') ? 10 : 16); i = BUFF_LEN; @@ -55,9 +51,7 @@ void _Litob(_Pft *args, char type) { } if (args->prec < 0 && (args->flags & (FLAGS_ZERO | FLAGS_MINUS)) == FLAGS_ZERO) { - i = args->width - args->n0 - args->nz0 - args->n1; - - if (i > 0) { + if ((i = args->width - args->n0 - args->nz0 - args->n1) > 0) { args->nz0 += i; } } diff --git a/src/libc/xprintf.c b/src/libc/xprintf.c index d9f1003..788f42c 100644 --- a/src/libc/xprintf.c +++ b/src/libc/xprintf.c @@ -44,16 +44,16 @@ static void _Putfld(_Pft *pf, va_list *pap, char code, char *ac); int _Printf(outfun prout, char *arg, const char *fmt, va_list args) { _Pft x; - const char *s; - char c; - const char *t; - static const char fchar[] = {' ', '+', '-', '#', '0', '\0'}; - static const int fbit[] = {FLAGS_SPACE, FLAGS_PLUS, FLAGS_MINUS, FLAGS_HASH, FLAGS_ZERO, 0}; - char ac[32]; x.nchar = 0; - for (;;) { + while (TRUE) { + const char *s; + char c; + const char *t; + static const char fchar[] = {' ', '+', '-', '#', '0', '\0'}; + static const int fbit[] = {FLAGS_SPACE, FLAGS_PLUS, FLAGS_MINUS, FLAGS_HASH, FLAGS_ZERO, 0}; + char ac[32]; s = fmt; for (c = *s; c != 0 && c != '%';) { @@ -80,18 +80,21 @@ int _Printf(outfun prout, char *arg, const char *fmt, va_list args) { x.flags |= FLAGS_MINUS; } s++; - } else { + } else ATOI(x.width, s); - } + if (*s != '.') { x.prec = -1; } else if (*++s == '*') { x.prec = va_arg(args, int); ++s; - } else { - ATOI(x.prec, s); - } + } else + for (x.prec = 0; isdigit(*s); s++) { + if (x.prec < 999) + x.prec = x.prec * 10 + *s - '0'; + } + x.qual = strchr("hlL", *s) ? *s++ : '\0'; @@ -102,22 +105,35 @@ int _Printf(outfun prout, char *arg, const char *fmt, va_list args) { _Putfld(&x, &args, *s, ac); x.width -= x.n0 + x.nz0 + x.n1 + x.nz1 + x.n2 + x.nz2; - - if (!(x.flags & FLAGS_MINUS)) { - PAD(spaces, x.width); + + { + + if (!(x.flags & FLAGS_MINUS)) { + int i, j; + if (0 < (x.width)) + { + i, j = x.width; + for (; 0 < j; j -= i) + { + i = MAX_PAD < (unsigned int)j ? (int)MAX_PAD : j; + PUT(spaces, i); + } + } + } + + PUT(ac, x.n0); + PAD(zeroes, x.nz0) + + PUT(x.s, x.n1); + PAD(zeroes, x.nz1); + + PUT(x.s + x.n1, x.n2); + PAD(zeroes, x.nz2); + + if (x.flags & FLAGS_MINUS) { + PAD(spaces, x.width); + } } - - PUT(ac, x.n0); - PAD(zeroes, x.nz0); - PUT(x.s, x.n1); - PAD(zeroes, x.nz1); - PUT(x.s + x.n1, x.n2); - PAD(zeroes, x.nz2); - - if (x.flags & FLAGS_MINUS) { - PAD(spaces, x.width); - } - fmt = s + 1; } return 0; @@ -226,7 +242,7 @@ static void _Putfld(_Pft *x, va_list *args, char type, char *buff) { x->s = va_arg(*args, char *); x->n1 = strlen(x->s); - if (x->prec >= 0 && x->n1 > x->prec) { + if (x->prec >= 0 && x->prec < x->n1) { x->n1 = x->prec; } diff --git a/src/log/delay.s b/src/log/delay.s new file mode 100644 index 0000000..bbfc7dd --- /dev/null +++ b/src/log/delay.s @@ -0,0 +1,22 @@ +#ifndef _FINALROM +#include "sys/asm.h" +#include "sys/regdef.h" + +LEAF(osDelay) + sll t0,a0,2 + addu t0,a0 + sll t0,t0,2 + beqz a0,2f + +1: + subu t0,1 + NOP + NOP + bnez t0,1b + +2: + j ra + +END(osDelay) + +#endif diff --git a/src/log/log.c b/src/log/log.c new file mode 100644 index 0000000..85129d2 --- /dev/null +++ b/src/log/log.c @@ -0,0 +1,124 @@ +#include "stdarg.h" +#include "PR/rdb.h" +#include "PR/os.h" +#include "PR/os_internal.h" +#include "PR/ultraerror.h" +#include "PR/ultralog.h" +#include "macros.h" + +#ifndef _FINALROM + +static u32 __osLogOKtoWrite = TRUE; +static u32 __osLogInitialized = FALSE; + +static OSMesgQueue __osLogDoneMsgQ ALIGNED(8); +static OSMesg __osLogMsgBuf; + +void __osLogWrite(OSLog* log, s16 code, s16 numArgs, va_list argPtr); + +void osCreateLog(OSLog* log, u32* base, s32 byteLen) { + log->magic = OS_LOG_MAGIC; + log->base = base; + log->len = byteLen; + log->startCount = osGetCount(); + log->writeOffset = 0; +} + +void osLogEvent(OSLog* log, s16 code, s16 numArgs, ...) { + va_list argPtr; + + if (numArgs > 16) { + return; + } + + va_start(argPtr, numArgs); + __osLogWrite(log, code, numArgs, argPtr); + va_end(argPtr); +} + +void osFlushLog(OSLog* log) { + s32 mask; + u32 sent; + u32 count; + u32 subcount; + u8* base; + u8 dCount[3]; + + if (!__osLogInitialized) { + osCreateMesgQueue(&__osLogDoneMsgQ, &__osLogMsgBuf, 1); + osSetEventMesg(OS_EVENT_RDB_LOG_DONE, &__osLogDoneMsgQ, 0); + __osLogInitialized = 1; + } + + mask = __osDisableInt(); + __osLogOKtoWrite = 0; + base = log->base; + count = log->writeOffset * 4; + __osRestoreInt(mask); + + while (count != 0) { + subcount = (count < 0x8000) ? count : 0x8000; + dCount[0] = (subcount & 0xFF0000) >> 0x10; + dCount[1] = (subcount & 0xFF00) >> 8; + dCount[2] = subcount & 0xFF; + + sent = 0; + while (sent < 3) { + sent += __osRdbSend(dCount + sent, 3 - sent, RDB_TYPE_GtoH_LOG_CT); + } + + sent = 0; + while (sent < subcount) { + sent += __osRdbSend(base + sent, subcount - sent, RDB_TYPE_GtoH_LOG); + } + + count -= subcount; + base += subcount; + osRecvMesg(&__osLogDoneMsgQ, NULL, OS_MESG_BLOCK); + } + mask = __osDisableInt(); + log->writeOffset = 0; + __osLogOKtoWrite = 1; + __osRestoreInt(mask); +} + +void __osLogWrite(OSLog* log, s16 code, s16 numArgs, va_list argPtr) { + int i; + u32 saveEnable; + u32 buf[19]; + u32* bufp; + OSLogItem* hdr; + s32* args; + s32* dest; + int numLongs; + + bufp = buf; + hdr = buf; + args = buf + 3; + numLongs = numArgs + 3; + saveEnable = __osDisableInt(); + + hdr->magic = log->magic; + hdr->timeStamp = osGetCount() - log->startCount; + hdr->argCount = numArgs; + hdr->eventID = code; + + for (i = 0; i < numArgs; i++) { + *args++ = va_arg(argPtr, int); + } + + if (__osLogOKtoWrite) { + if ((log->writeOffset + numLongs) < (log->len >> 2)) { + dest = log->base + log->writeOffset; + for (i = 0; i < numLongs; i++) { + *dest++ = *bufp++; + } + log->writeOffset += numLongs; + } else { + __osLogOKtoWrite = FALSE; + } + } + __osRestoreInt(saveEnable); +} + +#endif diff --git a/src/log/logfloat.c b/src/log/logfloat.c new file mode 100644 index 0000000..01acab6 --- /dev/null +++ b/src/log/logfloat.c @@ -0,0 +1,9 @@ +#ifndef _FINALROM + +#include "ultralog.h" + +u32 osLogFloat(f32 f) { + return OS_LOG_FLOAT(f); +} + +#endif diff --git a/src/monutil.s b/src/monutil.s new file mode 100644 index 0000000..e5974bd --- /dev/null +++ b/src/monutil.s @@ -0,0 +1,188 @@ +#ifndef _FINALROM +#include "asm.h" +#include "sgidefs.h" +#include "regdef.h" +#include "sgidefs.h" +#include "PR/R4300.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +#define EXC(code) (EXC_##code >> CAUSE_EXCSHIFT) + +.text + +LEAF(__isExpJP); .set noreorder + j __isExp + nop + sw k0, -0x10(sp) + la k0, __isExp + jr k0 + nop +.set reorder +END(__isExpJP) + +LEAF(__isExp); .set noreorder + sw k0, -0x10(sp) + sw k1, -8(sp) + + mfc0 k0, C0_CAUSE + nop + andi k0, k0, CAUSE_EXCMASK + bnez k0, non_stop + + nop + mfc0 k0, C0_CAUSE + nop + andi k0, k0, CAUSE_IP7 + beqz k0, throw_os_exception + nop + j go_monitor + nop +non_stop: + sra k0, k0, CAUSE_EXCSHIFT + li k1, EXC(BREAK) + bne k0, k1, non_bp + nop + j go_monitor + nop + +non_bp: + li k1, EXC(RADE) + bne k0, k1, non_adrs_store_exp + nop + j go_monitor + nop +non_adrs_store_exp: + li k1, EXC(WADE) + bne k0, k1, non_adrs_load_exp + nop + j go_monitor + nop +non_adrs_load_exp: + li k1, EXC(IBE) + bne k0, k1, non_bus_code_exp + nop + j go_monitor + nop +non_bus_code_exp: + li k1, EXC(DBE) + bne k0, k1, non_bus_data_exp + nop + j go_monitor + nop +non_bus_data_exp: + li k1, EXC(MOD) + bne k0, k1, non_tlb_mod + nop + j go_monitor + nop +non_tlb_mod: + li k1, EXC(RMISS) + bne k0, k1, non_tlb_load + nop + j go_monitor + nop +non_tlb_load: + li k1, EXC(WMISS) + bne k0, k1, non_tlb_store + nop + j go_monitor + nop +non_tlb_store: + li k1, EXC(II) + bne k0, k1, non_resv + nop + j go_monitor + nop + +non_resv: + lw k1, -8(sp) + +throw_os_exception: + j ramOldVector + nop + + + + + + + + + +go_monitor: + move k0, sp + addiu sp, sp, -0x200 + sw k0, 0x78(sp) + lw k1, -8(k0) + sw k1, 0x70(sp) + lw k1, -0x10(k0) + sw k1, 0x6c(sp) + nop +w: + lui k0, (0xA4600010 >> 16) + lw k0, (0xA4600010 & 0xFFFF)(k0) /* PI_STATUS_REG */ + nop + andi k0, k0, 3 /* (PI_STATUS_DMA_BUSY | PI_STATUS_IO_BUSY) */ + bnez k0, w + nop + la k0, 0xBFF00050 + jr k0 + nop +.set reorder +END(__isExp) + + +LEAF(MonitorInitBreak); .set noreorder + nop + nop +INIT_BREAK_POSITION: + break 4 + nop + nop + nop + jr ra + nop +.set reorder +END(MonitorInitBreak) + +#endif diff --git a/src/os/atomic.c b/src/os/atomic.c index 4b7475e..a0bd8fe 100644 --- a/src/os/atomic.c +++ b/src/os/atomic.c @@ -1,15 +1,16 @@ #include "PR/os_internal.h" int __osAtomicDec(unsigned int* p) { - register u32 saveMask = __osDisableInt(); - int mask; + u32 mask; + int result; + mask = __osDisableInt(); if (*p) { (*p)--; - mask = 1; + result = 1; } else { - mask = 0; + result = 0; } - __osRestoreInt(saveMask); - return mask; + __osRestoreInt(mask); + return result; } diff --git a/src/os/createmesgqueue.c b/src/os/createmesgqueue.c index 5e68a3a..8c5e800 100644 --- a/src/os/createmesgqueue.c +++ b/src/os/createmesgqueue.c @@ -1,7 +1,16 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" void osCreateMesgQueue(OSMesgQueue* mq, OSMesg* msg, s32 msgCount) { + +#ifdef _DEBUG + if (msgCount <= 0) { + __osError(ERR_OSCREATEMESGQUEUE, 1, msgCount); + return 0; + } +#endif + mq->mtqueue = &__osThreadTail.next; mq->fullqueue = &__osThreadTail.next; mq->validCount = 0; diff --git a/src/os/createthread.c b/src/os/createthread.c index 34c6aae..ee2ef60 100644 --- a/src/os/createthread.c +++ b/src/os/createthread.c @@ -1,10 +1,26 @@ #include "PR/os_internal.h" #include "PR/R4300.h" +#include "PR/ultraerror.h" #include "osint.h" +extern __OSThreadprofile_s thprof[]; + void osCreateThread(OSThread* t, OSId id, void (*entry)(void*), void* arg, void* sp, OSPri p) { register u32 saveMask; OSIntMask mask; + +#ifdef _DEBUG + if ((u32)sp & 0x7) { + __osError(ERR_OSCREATETHREAD_SP, 1, sp); + return 0; + } + + if ((p < OS_PRIORITY_IDLE) || (p > OS_PRIORITY_MAX)) { + __osError(ERR_OSCREATETHREAD_PRI, 1, p); + return 0; + } +#endif + t->id = id; t->priority = p; t->next = NULL; @@ -14,12 +30,21 @@ void osCreateThread(OSThread* t, OSId id, void (*entry)(void*), void* arg, void* t->context.sp = (s64)(s32)sp - 16; t->context.ra = (u64)__osCleanupThread; mask = OS_IM_ALL; - t->context.sr = SR_IMASK | SR_EXL | SR_IE; + t->context.sr = (mask & (SR_IMASK | SR_IE)) | SR_EXL; t->context.rcp = (mask & RCP_IMASK) >> RCP_IMASKSHIFT; t->context.fpcsr = (u32)(FPCSR_FS | FPCSR_EV); t->fp = 0; t->state = OS_STATE_STOPPED; t->flags = 0; + +#ifndef _FINALROM + if (id < THPROF_IDMAX) { + t->thprof = &thprof[id]; + } else { + t->thprof = &thprof[THPROF_IDMAX - 1]; + } +#endif + saveMask = __osDisableInt(); t->tlnext = __osActiveQueue; __osActiveQueue = t; diff --git a/src/os/destroythread.c b/src/os/destroythread.c index baa7bc5..91ad92c 100644 --- a/src/os/destroythread.c +++ b/src/os/destroythread.c @@ -25,7 +25,6 @@ void osDestroyThread(OSThread* t) { break; } pred = succ; - succ = pred->tlnext; } } diff --git a/src/os/exit.c b/src/os/exit.c index f495177..24a873f 100644 --- a/src/os/exit.c +++ b/src/os/exit.c @@ -5,5 +5,5 @@ void osExit() { for (;;) { ; -} + } } diff --git a/src/os/getnextfaultthread.c b/src/os/getnextfaultthread.c index dd4b2c2..44d723a 100644 --- a/src/os/getnextfaultthread.c +++ b/src/os/getnextfaultthread.c @@ -5,11 +5,7 @@ OSThread* __osGetNextFaultedThread(OSThread* lastFault) { register int saveMask = __osDisableInt(); register OSThread* fault; - if (lastFault == NULL) { - fault = __osActiveQueue; - } else { - fault = lastFault; - } + fault = lastFault == NULL ? __osActiveQueue : lastFault; while (fault->priority != -1) { if ((fault->flags & OS_FLAG_FAULT) != 0 && fault != lastFault) { diff --git a/src/os/gettime.c b/src/os/gettime.c index aee799a..aab4133 100644 --- a/src/os/gettime.c +++ b/src/os/gettime.c @@ -1,11 +1,21 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" +#include "../io/viint.h" OSTime osGetTime() { u32 tmptime; u32 elapseCount; OSTime currentCount; register u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSGETTIME, 0); + return 0; + } +#endif + saveMask = __osDisableInt(); tmptime = osGetCount(); elapseCount = tmptime - __osBaseCounter; diff --git a/src/os/initrdb.c b/src/os/initrdb.c index a332c29..5537eb1 100644 --- a/src/os/initrdb.c +++ b/src/os/initrdb.c @@ -1,7 +1,8 @@ #ifndef _FINALROM +#include "PR/rdb.h" #include "PR/os_internal.h" -void* __osRdb_IP6_Data; +rdbPacket* __osRdb_IP6_Data; u32 __osRdb_IP6_Size; u32 __osRdb_IP6_Ct; u32 __osRdb_IP6_CurWrite; diff --git a/src/os/jammesg.c b/src/os/jammesg.c index 81015bf..cef68da 100644 --- a/src/os/jammesg.c +++ b/src/os/jammesg.c @@ -1,8 +1,18 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" s32 osJamMesg(OSMesgQueue* mq, OSMesg msg, s32 flag) { - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if ((flag != OS_MESG_NOBLOCK) && (flag != OS_MESG_BLOCK)) { + __osError(ERR_OSJAMMESG, 1, flag); + return -1; + } +#endif + + saveMask = __osDisableInt(); while (mq->validCount >= mq->msgCount) { if (flag == OS_MESG_BLOCK) { diff --git a/src/os/osint.h b/src/os/osint.h index 7a4c0cd..9472ae9 100644 --- a/src/os/osint.h +++ b/src/os/osint.h @@ -39,6 +39,11 @@ extern u32 __osViIntrCount; extern u32 __osTimerCounter; extern u32 __osShutdown; +extern OSMesgQueue __osProfTimerQ; +extern OSProf *__osProfileList; +extern OSProf *__osProfileListEnd; +extern u32 __osProfileOverflowBin; + extern __OSEventState __osEventStateTab[OS_NUM_EVENTS]; diff --git a/src/os/rdbsend.c b/src/os/rdbsend.c index b561d99..c9d7865 100644 --- a/src/os/rdbsend.c +++ b/src/os/rdbsend.c @@ -1 +1,76 @@ -/* this file is completely empty in the rom release */ +#include "PR/os_internal.h" +#include "PR/rdb.h" +#include "PR/R4300.h" + +#ifndef _FINALROM +extern rdbPacket* __osRdb_IP6_Data; +extern u32 __osRdb_IP6_Size; +extern u32 __osRdb_IP6_Ct; +extern u32 __osRdb_IP6_CurWrite; + +u32 __osRdb_IP6_Empty = 1; + +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) + +u32 __osRdbSend(u8* buf, u32 size, u32 type) { + rdbPacket* pPtr; + rdbPacket pkt; + u32 len; + u32 c; + u32 inCt = 0; + u32 needFirst = 0; + u32 mask; + u32 sent = 0; + + mask = __osDisableInt(); + + if (__osRdb_IP6_Empty != 0) { + __osRdb_IP6_Empty = 0; + pkt.type = type; + + len = MIN(size, sizeof(pkt.buf)); + + pkt.length = len; + + c = 0; + while (c < len) { + pkt.buf[c++] = buf[inCt++]; + } + + size -= len; + sent = len; + needFirst = 1; + } + + while (size != 0 && __osRdb_IP6_Ct < __osRdb_IP6_Size) { + len = MIN(size, sizeof(pPtr->buf)); + + pPtr = &__osRdb_IP6_Data[__osRdb_IP6_CurWrite]; + + pPtr->type = type; + pPtr->length = len; + + c = 0; + while (c < len) { + pPtr->buf[c++] = buf[inCt++]; + } + + __osRdb_IP6_CurWrite++; + if (__osRdb_IP6_CurWrite >= __osRdb_IP6_Size) { + __osRdb_IP6_CurWrite = 0; + } + + __osRdb_IP6_Ct++; + size -= len; + sent += len; + } + + if (needFirst) { + *(rdbPacket*)RDB_BASE_REG = pkt; + } + __osRestoreInt(mask); + + return sent; +} + +#endif diff --git a/src/os/recvmesg.c b/src/os/recvmesg.c index 890e7f2..043ed21 100644 --- a/src/os/recvmesg.c +++ b/src/os/recvmesg.c @@ -1,18 +1,27 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" s32 osRecvMesg(OSMesgQueue* mq, OSMesg* msg, s32 flags) { register u32 saveMask; + +#ifdef _DEBUG + if ((flags != OS_MESG_NOBLOCK) && (flags != OS_MESG_BLOCK)) { + __osError(ERR_OSRECVMESG, 1, flags); + return -1; + } +#endif + saveMask = __osDisableInt(); while (MQ_IS_EMPTY(mq)) { if (flags == OS_MESG_NOBLOCK) { __osRestoreInt(saveMask); return -1; + } else { + __osRunningThread->state = OS_STATE_WAITING; + __osEnqueueAndYield(&mq->mtqueue); } - - __osRunningThread->state = OS_STATE_WAITING; - __osEnqueueAndYield(&mq->mtqueue); } if (msg != NULL) { diff --git a/src/os/sendmesg.c b/src/os/sendmesg.c index cbafac7..19cf3de 100644 --- a/src/os/sendmesg.c +++ b/src/os/sendmesg.c @@ -1,10 +1,20 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" s32 osSendMesg(OSMesgQueue* mq, OSMesg msg, s32 flags) { register u32 saveMask; register s32 last; + +#ifdef _DEBUG + if ((flags != OS_MESG_NOBLOCK) && (flags != OS_MESG_BLOCK)) { + __osError(ERR_OSSENDMESG, 1, flags); + return -1; + } +#endif + saveMask = __osDisableInt(); + while (MQ_IS_FULL(mq)) { if (flags == OS_MESG_BLOCK) { __osRunningThread->state = OS_STATE_WAITING; diff --git a/src/os/seteventmesg.c b/src/os/seteventmesg.c index 7d2ae9d..50d7ad9 100644 --- a/src/os/seteventmesg.c +++ b/src/os/seteventmesg.c @@ -1,13 +1,25 @@ #include "macros.h" #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" __OSEventState __osEventStateTab[OS_NUM_EVENTS] ALIGNED(8); u32 __osPreNMI = FALSE; void osSetEventMesg(OSEvent event, OSMesgQueue* mq, OSMesg msg) { - register u32 saveMask = __osDisableInt(); - __OSEventState* es = &__osEventStateTab[event]; + register u32 saveMask; + __OSEventState* es; + +#ifdef _DEBUG + if (event >= OS_NUM_EVENTS) { + __osError(ERR_OSSETEVENTMESG, 1, event); + return 0; + } +#endif + + saveMask = __osDisableInt(); + + es = &__osEventStateTab[event]; es->messageQueue = mq; es->message = msg; diff --git a/src/os/setthreadpri.c b/src/os/setthreadpri.c index 0200e3d..91c9c5f 100644 --- a/src/os/setthreadpri.c +++ b/src/os/setthreadpri.c @@ -1,8 +1,18 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" void osSetThreadPri(OSThread* t, OSPri pri) { - register u32 saveMask = __osDisableInt(); + register u32 saveMask; + +#ifdef _DEBUG + if ((pri < OS_PRIORITY_IDLE) || (pri > OS_PRIORITY_MAX)) { + __osError(ERR_OSSETTHREADPRI, 1, pri); + return 0; + } +#endif + + saveMask = __osDisableInt(); if (t == NULL) { t = __osRunningThread; diff --git a/src/os/settime.c b/src/os/settime.c index 5bae2a2..5bcae42 100644 --- a/src/os/settime.c +++ b/src/os/settime.c @@ -1,6 +1,16 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" +#include "../io/viint.h" void osSetTime(OSTime time) { + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSSETTIME, 0); + return 0; + } +#endif + __osCurrentTime = time; } diff --git a/src/os/settimer.c b/src/os/settimer.c index d43c6c5..d2c5650 100644 --- a/src/os/settimer.c +++ b/src/os/settimer.c @@ -1,27 +1,33 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" +#include "../io/viint.h" int osSetTimer(OSTimer* t, OSTime countdown, OSTime interval, OSMesgQueue* mq, OSMesg msg) { - register u32 saveMask; OSTime time; OSTimer* next; u32 count; u32 value; + u32 saveMask; + +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSSETTIMER, 0); + return 0; + } +#endif t->next = NULL; t->prev = NULL; - t->value = countdown; t->interval = interval; - - if (countdown == 0) { - t->value = interval; - } - + t->value = (countdown == 0) ? interval : countdown; t->mq = mq; t->msg = msg; saveMask = __osDisableInt(); - if (__osTimerList->next != __osTimerList) { + if (__osTimerList->next == __osTimerList) { + + } else { next = __osTimerList->next; count = osGetCount(); value = count - __osTimerCounter; diff --git a/src/os/startthread.c b/src/os/startthread.c index f8d0d68..888d91c 100644 --- a/src/os/startthread.c +++ b/src/os/startthread.c @@ -1,4 +1,5 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" void osStartThread(OSThread* t) { @@ -19,6 +20,12 @@ void osStartThread(OSThread* t) { __osEnqueueThread(&__osRunQueue, __osPopThread(t->queue)); } break; +#ifdef _DEBUG + default: + __osError(ERR_OSSTARTTHREAD, 0); + __osRestoreInt(saveMask); + return 0; +#endif } if (__osRunningThread == NULL) { diff --git a/src/os/stopthread.c b/src/os/stopthread.c index 0e172c0..2f1eae4 100644 --- a/src/os/stopthread.c +++ b/src/os/stopthread.c @@ -3,11 +3,9 @@ void osStopThread(OSThread* t) { register u32 saveMask = __osDisableInt(); - register u16 state = OS_STATE_RUNNING; + register u16 state; - if (t != NULL) { - state = t->state; - } + state = (t != NULL) ? t->state : OS_STATE_RUNNING; switch (state) { case OS_STATE_RUNNING: diff --git a/src/os/stoptimer.c b/src/os/stoptimer.c index 90daf40..b6db1c1 100644 --- a/src/os/stoptimer.c +++ b/src/os/stoptimer.c @@ -1,10 +1,19 @@ #include "PR/os_internal.h" +#include "PR/ultraerror.h" #include "osint.h" +#include "../io/viint.h" int osStopTimer(OSTimer* t) { register u32 savedMask; OSTimer* timep; +#ifdef _DEBUG + if (!__osViDevMgr.active) { + __osError(ERR_OSSTOPTIMER, 0); + return 0; + } +#endif + if (t->next == NULL) { return -1; } diff --git a/src/os/thread.c b/src/os/thread.c index c8461a9..4e5e890 100644 --- a/src/os/thread.c +++ b/src/os/thread.c @@ -7,19 +7,22 @@ OSThread* __osActiveQueue = (OSThread*)&__osThreadTail; OSThread* __osRunningThread = { 0 }; OSThread* __osFaultedThread = { 0 }; -void __osDequeueThread(OSThread** queue, OSThread* t) { - register OSThread** pred; +void __osDequeueThread(register OSThread** queue, register OSThread* t) { + register OSThread* pred; register OSThread* succ; pred = queue; - succ = *pred; + succ = pred->next; while (succ != NULL) { if (succ == t) { - *pred = t->next; + pred->next = t->next; +#ifdef _DEBUG + t->next = NULL; +#endif return; } pred = succ; - succ = *pred; + succ = pred->next; } } diff --git a/src/os/timerintr.c b/src/os/timerintr.c index 37f7cbc..ffb3417 100644 --- a/src/os/timerintr.c +++ b/src/os/timerintr.c @@ -1,21 +1,27 @@ +#include "macros.h" #include "PR/os_internal.h" #include "osint.h" -OSTimer* __osTimerList = &__osBaseTimer; -OSTimer __osBaseTimer; OSTime __osCurrentTime; u32 __osBaseCounter; u32 __osViIntrCount; u32 __osTimerCounter; +OSTimer __osBaseTimer; +OSTimer* __osTimerList = &__osBaseTimer; + +#ifndef _FINALROM +OSMesgQueue __osProfTimerQ ALIGNED(8); +OSProf* __osProfileList; +OSProf* __osProfileListEnd; +u32 __osProfileOverflowBin; +#endif void __osTimerServicesInit(void) { __osCurrentTime = 0; __osBaseCounter = 0; __osViIntrCount = 0; - __osTimerList->prev = __osTimerList; - __osTimerList->next = __osTimerList->prev; - __osTimerList->value = 0; - __osTimerList->interval = __osTimerList->value; + __osTimerList->next = __osTimerList->prev = __osTimerList; + __osTimerList->interval = __osTimerList->value = 0; __osTimerList->mq = NULL; __osTimerList->msg = 0; } @@ -25,39 +31,73 @@ void __osTimerInterrupt(void) { u32 count; u32 elapsed_cycles; - if (__osTimerList->next != __osTimerList) { - while (TRUE) { - t = __osTimerList->next; - if (t == __osTimerList) { - __osSetCompare(0); - __osTimerCounter = 0; - break; - } +#ifndef _FINALROM + u32 pc; + s32 offset; + OSProf* prof = __osProfileList; +#endif - count = osGetCount(); - elapsed_cycles = count - __osTimerCounter; - __osTimerCounter = count; + if (__osTimerList->next == __osTimerList) { + return; + } + for (;;) { + t = __osTimerList->next; - if (elapsed_cycles < t->value) { - t->value -= elapsed_cycles; - __osSetTimerIntr(t->value); - break; + if (t == __osTimerList) { + __osSetCompare(0); + __osTimerCounter = 0; + break; + } + + count = osGetCount(); + elapsed_cycles = count - __osTimerCounter; + __osTimerCounter = count; + + if (elapsed_cycles < t->value) { + t->value -= elapsed_cycles; + __osSetTimerIntr(t->value); + break; + } + + t->prev->next = t->next; + t->next->prev = t->prev; + t->next = NULL; + t->prev = NULL; + + if (t->mq != NULL) { +#ifdef _FINALROM + osSendMesg(t->mq, t->msg, OS_MESG_NOBLOCK); + } +#else + if (t->mq != &__osProfTimerQ) { + osSendMesg(t->mq, t->msg, OS_MESG_NOBLOCK); } else { - t->prev->next = t->next; - t->next->prev = t->prev; - t->next = NULL; - t->prev = NULL; + pc = __osRunQueue->context.pc; + prof = __osProfileList; - if (t->mq != NULL) { - osSendMesg(t->mq, t->msg, OS_MESG_NOBLOCK); + while (prof < __osProfileListEnd) { + offset = pc - (u32)prof->text_start; + + if (offset >= 0) { + if ((s32)prof->text_end - (s32)pc > 0) { + prof->histo_base[offset >> 2]++; + goto __ProfDone; + } + } + prof++; } - if (t->interval != 0) { - t->value = t->interval; - __osInsertTimer(t); - } + __osProfileOverflowBin++; } } +#endif + + __ProfDone: + + if (t->interval != 0) { + t->value = t->interval; + __osInsertTimer(t); + } } } diff --git a/src/rg/free.c b/src/rg/free.c index ca89a67..3a267e2 100644 --- a/src/rg/free.c +++ b/src/rg/free.c @@ -1,5 +1,44 @@ #include "PR/region.h" #include "PR/R4300.h" +#include "PR/ultraerror.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" @@ -8,8 +47,27 @@ void osFree(void* region, void* addr) { register OSRegion* rp = region; int i; - rp = region; +#ifdef _DEBUG + assert((region != NULL) && (addr != NULL)); + if (((char*)rp + ALIGN(sizeof(OSRegion), rp->r_alignSize)) != rp->r_startBufferAddress) { + __osError(ERR_OSFREE_REGION, 1, region); + return 0; + } +#endif + i = ((u8*)addr - rp->r_startBufferAddress) / rp->r_bufferSize; + +#ifdef _DEBUG + if ((i < 0) || (i >= rp->r_bufferCount)) { + __osError(ERR_OSFREE_ADDR, 2, addr, region); + return 0; + } + + if (((unsigned char*)addr - rp->r_startBufferAddress) % (rp->r_bufferSize) != 0) { + __osError(ERR_OSFREE_ADDR, 2, addr, region); + return 0; + } +#endif *(u16*)(&rp->r_startBufferAddress[i * rp->r_bufferSize]) = rp->r_freeList; rp->r_freeList = i; } diff --git a/src/rg/getbufcount.c b/src/rg/getbufcount.c index 7292ea0..ea5f7b2 100644 --- a/src/rg/getbufcount.c +++ b/src/rg/getbufcount.c @@ -1,9 +1,57 @@ #include "PR/region.h" +#include "PR/ultraerror.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 osGetRegionBufCount(void* region) { register OSRegion* rp = region; + +#ifdef _DEBUG + assert(rp != NULL); + if (((char*)rp + ALIGN(sizeof(OSRegion), rp->r_alignSize)) != rp->r_startBufferAddress) { + __osError(ERR_OSGETREGIONBUFCOUNT, 1, region); + return 0; + } +#endif return rp->r_bufferCount; } diff --git a/src/rg/getsize.c b/src/rg/getsize.c index 57ef530..0571d04 100644 --- a/src/rg/getsize.c +++ b/src/rg/getsize.c @@ -1,9 +1,57 @@ #include "PR/region.h" +#include "PR/ultraerror.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" s32 osGetRegionBufSize(void* region) { register OSRegion* rp = region; + +#ifdef _DEBUG + assert(rp != NULL); + if (((char*)rp + ALIGN(sizeof(OSRegion), rp->r_alignSize)) != rp->r_startBufferAddress) { + __osError(ERR_OSGETREGIONBUFSIZE, 1, region); + return 0; + } +#endif + return rp->r_bufferSize; } diff --git a/src/rg/malloc.c b/src/rg/malloc.c index b34682a..cd14245 100644 --- a/src/rg/malloc.c +++ b/src/rg/malloc.c @@ -1,11 +1,64 @@ #include "PR/region.h" +#include "PR/ultraerror.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" void* osMalloc(void* region) { register OSRegion* rp = region; - unsigned char* addr; + char* addr; + +#ifdef _DEBUG + assert(rp != NULL); + if (((char*)rp + ALIGN(sizeof(OSRegion), rp->r_alignSize)) != rp->r_startBufferAddress) { + __osError(ERR_OSMALLOC, 1, region); + return 0; + } +#endif if (rp->r_freeList == MAX_BUFCOUNT) { return NULL; diff --git a/src/rg/printregion.c b/src/rg/printregion.c new file mode 100644 index 0000000..2f84319 --- /dev/null +++ b/src/rg/printregion.c @@ -0,0 +1,26 @@ +#ifndef _FINALROM + +#include "../os/osint.h" +#include "PR/rmon.h" +#include "PR/region.h" + +void __osPrintRegion(void* region) { + register OSRegion* rp = region; + int i; + + rmonPrintf("Region = 0x%x\n", rp); + rmonPrintf("\tstartBufferAddress = 0x%x\n", RP(startBufferAddress)); + rmonPrintf("\tendAddress = 0x%x\n", RP(endAddress)); + rmonPrintf("\tbufferSize = %d\n", RP(bufferSize)); + rmonPrintf("\tbufferCount = %d\n", RP(bufferCount)); + rmonPrintf("\tfreeList = %d\n", RP(freeList)); + rmonPrintf("\talignSize = %d\n", RP(alignSize)); + rmonPrintf("\tMemory Header Layout:\n"); + + for (i = 0; i < RP(bufferCount); i++) { + rmonPrintf("\tBuf[%d]:\tAddress: 0x%x Value: 0x%x\n", i, RP(startBufferAddress) + i * RP(bufferSize), + *(u16*)(RP(startBufferAddress) + i * RP(bufferSize))); + } +} + +#endif diff --git a/src/rg/region.c b/src/rg/region.c index d109d32..b0c4746 100644 --- a/src/rg/region.c +++ b/src/rg/region.c @@ -1,4 +1,183 @@ #include "PR/region.h" +#include "PR/ultraerror.h" +#include "assert.h" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // TODO: this comes from a header #ident "$Revision: 1.17 $" @@ -6,7 +185,17 @@ void* osCreateRegion(void* startAddress, u32 length, u32 bufferSize, u32 alignSize) { register OSRegion* rp; register int i; - register unsigned char* addr; + register char* addr; + + assert(startAddress != NULL); + +#ifdef _DEBUG + if ((alignSize != 0) && (alignSize != OS_RG_ALIGN_2B) && (alignSize != OS_RG_ALIGN_4B) && + (alignSize != OS_RG_ALIGN_8B) && (alignSize != OS_RG_ALIGN_16B)) { + __osError(ERR_OSCREATEREGION_ALIGN, 1, alignSize); + return 0; + } +#endif if (alignSize == 0) { alignSize = OS_RG_ALIGN_DEFAULT; @@ -17,6 +206,13 @@ void* osCreateRegion(void* startAddress, u32 length, u32 bufferSize, u32 alignSi rp->r_bufferSize = ALIGN(bufferSize, alignSize); rp->r_bufferCount = (s32)(length - ALIGN(sizeof(OSRegion), alignSize)) / rp->r_bufferSize; +#ifdef _DEBUG + if (rp->r_bufferCount <= 0) { + __osError(ERR_OSCREATEREGION_SIZE, 2, length, bufferSize); + return 0; + } +#endif + if (rp->r_bufferCount > MAX_BUFCOUNT) { rp->r_bufferCount = MAX_BUFCOUNT; } diff --git a/src/rmon/rmonmain.c b/src/rmon/rmonmain.c index 6e2ee6d..7a63cc8 100644 --- a/src/rmon/rmonmain.c +++ b/src/rmon/rmonmain.c @@ -69,11 +69,12 @@ void __rmonSendData(char* const block, unsigned int blockSize) { __rmonIOputw(*(blockPointer++)); } } - } else while (wordCount--) { - __rmonMemcpy((u8*)buffer.bufBytes, (u8*)blockPointer, sizeof(buffer)); - __rmonIOputw(buffer.bufWord); - blockPointer++; - } + } else + while (wordCount--) { + __rmonMemcpy((u8*)buffer.bufBytes, (u8*)blockPointer, sizeof(buffer)); + __rmonIOputw(buffer.bufWord); + blockPointer++; + } __rmonIOflush(); } diff --git a/src/rmon/rmonmem.c b/src/rmon/rmonmem.c index 51c7eef..709c4a1 100644 --- a/src/rmon/rmonmem.c +++ b/src/rmon/rmonmem.c @@ -23,7 +23,7 @@ void __rmonWriteWordTo(u32* addr, u32 val) { u32 __rmonReadWordAt(u32* addr) { u32 data; - if (addr >= (u32*)SP_DMEM_START && addr < (u32*)0x05000000) { + if ((u32)addr >= SP_DMEM_START && (u32)addr < 0x05000000) { __osSpRawReadIo((u32)addr, &data); return data; } diff --git a/src/rmon/rmonmisc.c b/src/rmon/rmonmisc.c index ac6d5bf..4bfe176 100644 --- a/src/rmon/rmonmisc.c +++ b/src/rmon/rmonmisc.c @@ -28,7 +28,7 @@ int __rmonSetFault(KKHeader* req) { static OSThread rmonIOThread ALIGNED(8); static OSMesg rmonMsgs[8] ALIGNED(8); -static u64 rmonIOStack[2048] ALIGNED(8); +static u64 rmonIOStack[2048] ALIGNED(16); static OSMesg rmonPiMsgs[8] ALIGNED(8); static OSMesgQueue rmonPiMQ ALIGNED(8); diff --git a/src/rmon/rmonregs.c b/src/rmon/rmonregs.c index 859b2c9..06b3e2c 100644 --- a/src/rmon/rmonregs.c +++ b/src/rmon/rmonregs.c @@ -18,7 +18,7 @@ static u32 RCPpc; static u32 oldIMEMvalue; -static u32 DMEMbuffer[4]; +static u32 DMEMbuffer[4] ALIGNED(8); typedef union { u32 everything; diff --git a/src/rmon/rmonsio.c b/src/rmon/rmonsio.c index ffeca17..c239376 100644 --- a/src/rmon/rmonsio.c +++ b/src/rmon/rmonsio.c @@ -15,7 +15,7 @@ // TODO: this comes from a header #ident "$Revision: 1.4 $" -static OSMesgQueue IOmq; +static OSMesgQueue IOmq ALIGNED(8); static OSMesg IOmsgs; void* __osRdb_DbgRead_Buf; diff --git a/src/rmon/rmontask.c b/src/rmon/rmontask.c index a537602..f1c73f0 100644 --- a/src/rmon/rmontask.c +++ b/src/rmon/rmontask.c @@ -4,7 +4,7 @@ #include "PR/os_internal.h" #include "rmonint.h" #include "PR/rcp.h" -#include "sptask.h" +#include "PR/sptask.h" #include "macros.h" diff --git a/src/sched/sched.c b/src/sched/sched.c index 7cf59dd..70ebf55 100644 --- a/src/sched/sched.c +++ b/src/sched/sched.c @@ -2,7 +2,6 @@ * * Copyright 1995, Silicon Graphics, Inc. * All Rights Reserved. - * * This is UNPUBLISHED PROPRIETARY SOURCE CODE of Silicon Graphics, * Inc.; the contents of this file may not be disclosed to third * parties, copied or duplicated in any form, in whole or in part, @@ -16,11 +15,9 @@ * DOD or NASA FAR Supplement. Unpublished - rights reserved under the * Copyright Laws of the United States. *====================================================================*/ - #include #include #include - // TODO: this comes from a header #ident "$Revision: 1.17 $" diff --git a/src/sp/sprite.c b/src/sp/sprite.c index 0779f1f..f0732b4 100644 --- a/src/sp/sprite.c +++ b/src/sp/sprite.c @@ -1,11 +1,9 @@ /* * Copyright 1995, Silicon Graphics, Inc. * ALL RIGHTS RESERVED - * * UNPUBLISHED -- Rights reserved under the copyright laws of the United * States. Use of a copyright notice is precautionary only and does not * imply publication or disclosure. - * * U.S. GOVERNMENT RESTRICTED RIGHTS LEGEND: * Use, duplication or disclosure by the Government is subject to restrictions * as set forth in FAR 52.227.19(c)(2) or subparagraph (c)(1)(ii) of the Rights @@ -20,7 +18,6 @@ * PROHIBITED WITHOUT THE PRIOR EXPRESS WRITTEN PERMISSION OF SILICON * GRAPHICS, INC. */ - #include #include diff --git a/src/voice/voicecheckword.c b/src/voice/voicecheckword.c index ec58334..05c2a59 100644 --- a/src/voice/voicecheckword.c +++ b/src/voice/voicecheckword.c @@ -67,9 +67,9 @@ s32 osVoiceCheckWord(u8* word) { if (ret != 0) { return ret; + } else { + old = sjis; } - - old = sjis; } if ((sjis == 'っ') || (sjis == 'ッ')) { diff --git a/src/voice/voicecleardictionary.c b/src/voice/voicecleardictionary.c index 2d56959..267724f 100644 --- a/src/voice/voicecleardictionary.c +++ b/src/voice/voicecleardictionary.c @@ -7,9 +7,10 @@ s32 osVoiceClearDictionary(OSVoiceHandle* hd, u8 words) { u8 stat; u8 buf[4]; - ERRCK(__osVoiceGetStatus(hd->__mq, hd->__channel, &stat)); - - if (stat & 2) { + ret = (__osVoiceGetStatus(hd->__mq, hd->__channel, &stat)); + if (ret != 0) { + return ret; + } else if (stat & 2) { return CONT_ERR_VOICE_NO_RESPONSE; } diff --git a/src/voice/voicecontread2.c b/src/voice/voicecontread2.c index 0a3515b..c16a198 100644 --- a/src/voice/voicecontread2.c +++ b/src/voice/voicecontread2.c @@ -7,7 +7,7 @@ #define READ2FORMAT(p) ((__OSVoiceRead2Format*)(ptr)) s32 __osVoiceContRead2(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { - s32 ret; + s32 ret = 0; u8 status; int i; u8* ptr; @@ -39,15 +39,15 @@ s32 __osVoiceContRead2(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { ptr[sizeof(__OSVoiceRead2Format)] = CONT_CMD_END; } else { - ptr = (u8*)&__osPfsPifRam.ramarray + channel; + ptr += channel; } READ2FORMAT(ptr)->addrh = address >> 3; - READ2FORMAT(ptr)->addrl = __osContAddressCrc(address) | (address << 5); + READ2FORMAT(ptr)->addrl = (address << 5) | __osContAddressCrc(address); - __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_READ, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); ret = CHNL_ERR(*READ2FORMAT(ptr)); @@ -58,9 +58,9 @@ s32 __osVoiceContRead2(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { ret = __osVoiceGetStatus(mq, channel, &status); if (ret != 0) { break; + } else { + ret = CONT_ERR_CONTRFAIL; } - - ret = CONT_ERR_CONTRFAIL; } else { bcopy(&READ2FORMAT(ptr)->data, buffer, ARRLEN(READ2FORMAT(ptr)->data)); } diff --git a/src/voice/voicecontread36.c b/src/voice/voicecontread36.c index 503de36..c4d3b7a 100644 --- a/src/voice/voicecontread36.c +++ b/src/voice/voicecontread36.c @@ -7,7 +7,7 @@ #define READ36FORMAT(p) ((__OSVoiceRead36Format*)(ptr)) s32 __osVoiceContRead36(OSMesgQueue* mq, s32 channel, u16 address, u8* buffer) { - s32 ret; + s32 ret = 0; u8 status; s32 i; u8* ptr; @@ -37,15 +37,15 @@ s32 __osVoiceContRead36(OSMesgQueue* mq, s32 channel, u16 address, u8* buffer) { ptr[sizeof(__OSVoiceRead36Format)] = CONT_CMD_END; } else { - ptr = (u8*)&__osPfsPifRam + channel; + ptr += channel; } READ36FORMAT(ptr)->addrh = address >> 3; - READ36FORMAT(ptr)->addrl = __osContAddressCrc(address) | (address << 5); + READ36FORMAT(ptr)->addrl = (address << 5) | __osContAddressCrc(address); - __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_READ, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); ret = CHNL_ERR(*READ36FORMAT(ptr)); @@ -56,9 +56,9 @@ s32 __osVoiceContRead36(OSMesgQueue* mq, s32 channel, u16 address, u8* buffer) { ret = __osVoiceGetStatus(mq, channel, &status); if (ret != 0) { break; + } else { + ret = CONT_ERR_CONTRFAIL; } - - ret = CONT_ERR_CONTRFAIL; } else { bcopy(&READ36FORMAT(ptr)->data, buffer, ARRLEN(READ36FORMAT(ptr)->data)); } diff --git a/src/voice/voicecontrolgain.c b/src/voice/voicecontrolgain.c index 9515aa4..9c323f0 100644 --- a/src/voice/voicecontrolgain.c +++ b/src/voice/voicecontrolgain.c @@ -6,9 +6,16 @@ s32 __osVoiceSetADConverter(OSMesgQueue*, int ch, u8 cmd); s32 osVoiceControlGain(OSVoiceHandle* hd, s32 analog, s32 digital) { s32 ret; - u8 cmd = (u8)(analog == 0 ? 0x18 : 0x98); + u8 cmd; + static u8 digital_table[] = { 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0 }; + if (analog == 0) { + cmd = 0x18; + } else { + cmd = 0x98; + } + ERRCK(__osVoiceSetADConverter(hd->__mq, hd->__channel, cmd)); if ((digital < ARRLEN(digital_table)) && (digital >= 0)) { diff --git a/src/voice/voicecontwrite20.c b/src/voice/voicecontwrite20.c index 3842e3c..c94df0d 100644 --- a/src/voice/voicecontwrite20.c +++ b/src/voice/voicecontwrite20.c @@ -7,7 +7,7 @@ #define WRITE20FORMAT(p) ((__OSVoiceWrite20Format*)(ptr)) s32 __osVoiceContWrite20(OSMesgQueue* mq, int channel, u16 address, u8* buffer) { - s32 ret; + s32 ret = 0; u8 status; int i; u8* ptr; @@ -40,18 +40,18 @@ s32 __osVoiceContWrite20(OSMesgQueue* mq, int channel, u16 address, u8* buffer) ptr[sizeof(__OSVoiceWrite20Format)] = CONT_CMD_END; } else { - ptr = (u8*)&__osPfsPifRam.ramarray + channel; + ptr += channel; } WRITE20FORMAT(ptr)->addrh = address >> 3; - WRITE20FORMAT(ptr)->addrl = __osContAddressCrc(address) | (address << 5); + WRITE20FORMAT(ptr)->addrl = (address << 5) | __osContAddressCrc(address); bcopy(buffer, &WRITE20FORMAT(ptr)->data, 20); - __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); crc = __osVoiceContDataCrc(buffer, 20); osRecvMesg(mq, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_READ, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); ret = (WRITE20FORMAT(ptr)->rxsize & 0xC0) >> 4; @@ -61,9 +61,9 @@ s32 __osVoiceContWrite20(OSMesgQueue* mq, int channel, u16 address, u8* buffer) ret = __osVoiceGetStatus(mq, channel, &status); if (ret != 0) { break; + } else { + ret = CONT_ERR_CONTRFAIL; } - - ret = CONT_ERR_CONTRFAIL; } } else { ret = CONT_ERR_NO_CONTROLLER; diff --git a/src/voice/voicecontwrite4.c b/src/voice/voicecontwrite4.c index c2af86d..4bae207 100644 --- a/src/voice/voicecontwrite4.c +++ b/src/voice/voicecontwrite4.c @@ -7,7 +7,7 @@ #define WRITE4FORMAT(p) ((__OSVoiceWrite4Format*)(ptr)) s32 __osVoiceContWrite4(OSMesgQueue* mq, int channel, u16 address, u8 dst[4]) { - s32 ret; + s32 ret = 0; u8 status; int i; u8* ptr; @@ -38,18 +38,18 @@ s32 __osVoiceContWrite4(OSMesgQueue* mq, int channel, u16 address, u8 dst[4]) { ptr[sizeof(__OSVoiceWrite4Format)] = CONT_CMD_END; } else { - ptr = (u8*)&__osPfsPifRam + channel; + ptr += channel; } WRITE4FORMAT(ptr)->addrh = address >> 3; - WRITE4FORMAT(ptr)->addrl = __osContAddressCrc(address) | (address << 5); + WRITE4FORMAT(ptr)->addrl = (address << 5) | __osContAddressCrc(address); bcopy(dst, &WRITE4FORMAT(ptr)->data, 4); - __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); crc = __osVoiceContDataCrc(dst, 4); osRecvMesg(mq, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_READ, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); ret = (WRITE4FORMAT(ptr)->rxsize & 0xC0) >> 4; @@ -59,9 +59,9 @@ s32 __osVoiceContWrite4(OSMesgQueue* mq, int channel, u16 address, u8 dst[4]) { ret = __osVoiceGetStatus(mq, channel, &status); if (ret != 0) { break; + } else { + ret = CONT_ERR_CONTRFAIL; } - - ret = CONT_ERR_CONTRFAIL; } } else { ret = CONT_ERR_NO_CONTROLLER; diff --git a/src/voice/voicecountsyllables.c b/src/voice/voicecountsyllables.c index 998c1d0..b0112ef 100644 --- a/src/voice/voicecountsyllables.c +++ b/src/voice/voicecountsyllables.c @@ -14,7 +14,7 @@ void osVoiceCountSyllables(u8* data, u32* syllable) { old = 0; *syllable = 1; for (k = 0; data[k] != 0; k += 2) { - sjis = data[k + 1] + (data[k] << 8); + sjis = (data[k] << 8) + data[k + 1]; if ((sjis == 'あ') || (sjis == 'い') || (sjis == 'う') || (sjis == 'え') || (sjis == 'お') || (sjis == 'ア') || (sjis == 'イ') || (sjis == 'ウ') || (sjis == 'エ') || (sjis == 'オ')) { if (k == 0) { diff --git a/src/voice/voicecrc.c b/src/voice/voicecrc.c index 886c66d..911f44c 100644 --- a/src/voice/voicecrc.c +++ b/src/voice/voicecrc.c @@ -6,35 +6,34 @@ #define VOICE_CRC_GENERATOR 0x85 u8 __osVoiceContDataCrc(u8* data, u32 length) { - s32 ret = 0; + s32 temp = 0; u32 i; u32 j; - for (j = length; j != 0; j--, data++) { - // Loop over each i in the j starting with most significant - for (i = (1 << (VOICE_CRC_LENGTH - 1)); i != 0; i >>= 1) { - ret <<= 1; - if (*data & i) { - if (ret & (1 << VOICE_CRC_LENGTH)) { - // Same as ret++; ret ^= 0x85 since last i always 0 after the shift - ret ^= VOICE_CRC_GENERATOR - 1; + for (i = length; i != 0; data++, i--) { + // Loop over each j in the i starting with most significant + for (j = (1 << (VOICE_CRC_LENGTH - 1)); j != 0; j >>= 1) { + temp <<= 1; + if (*data & j) { + if (temp & (1 << VOICE_CRC_LENGTH)) { + // Same as temp++; temp ^= 0x85 since last j always 0 after the shift + temp ^= VOICE_CRC_GENERATOR - 1; } else { - ret++; + temp++; } - } else if (ret & (1 << VOICE_CRC_LENGTH)) { - ret ^= VOICE_CRC_GENERATOR; + } else if (temp & (1 << VOICE_CRC_LENGTH)) { + temp ^= VOICE_CRC_GENERATOR; } } } - // Act like a j of zeros is appended to data + // Act like a i of zeros is appended to data do { - ret <<= 1; - if (ret & (1 << VOICE_CRC_LENGTH)) { - ret ^= VOICE_CRC_GENERATOR; + temp <<= 1; + if (temp & (1 << VOICE_CRC_LENGTH)) { + temp ^= VOICE_CRC_GENERATOR; } - j++; - } while (j < VOICE_CRC_LENGTH); + } while (++i < VOICE_CRC_LENGTH); // Discarding the excess is done automatically by the return type - return ret; + return temp; } diff --git a/src/voice/voiceinit.c b/src/voice/voiceinit.c index 85f134c..adb39a4 100644 --- a/src/voice/voiceinit.c +++ b/src/voice/voiceinit.c @@ -15,7 +15,8 @@ s32 osVoiceInit(OSMesgQueue* mq, OSVoiceHandle* handle, int channel) { ERRCK(__osVoiceGetStatus(mq, channel, &stat)); - if (__osContChannelReset(mq, channel) != 0) { + ret = __osContChannelReset(mq, channel); + if (ret != 0) { return CONT_ERR_CONTRFAIL; } diff --git a/src/voice/voicemaskdictionary.c b/src/voice/voicemaskdictionary.c index a017e3d..913c4df 100644 --- a/src/voice/voicemaskdictionary.c +++ b/src/voice/voicemaskdictionary.c @@ -4,15 +4,16 @@ #include "voiceinternal.h" s32 osVoiceMaskDictionary(OSVoiceHandle* hd, u8* pattern, int size) { - s32 ret; + s32 ret = 0; s32 i; s32 j; u8 stat; u8 buf[20]; - ERRCK(__osVoiceGetStatus(hd->__mq, hd->__channel, &stat)); - - if (stat & 2) { + ret = __osVoiceGetStatus(hd->__mq, hd->__channel, &stat); + if (ret != 0) { + return ret; + } else if (stat & 2) { return CONT_ERR_VOICE_NO_RESPONSE; } diff --git a/src/voice/voicesetadconverter.c b/src/voice/voicesetadconverter.c index 2287c0d..45512af 100644 --- a/src/voice/voicesetadconverter.c +++ b/src/voice/voicesetadconverter.c @@ -7,7 +7,7 @@ #define SWRITEFORMAT(p) ((__OSVoiceSWriteFormat*)(p)) s32 __osVoiceSetADConverter(OSMesgQueue* mq, s32 channel, u8 data) { - s32 ret; + s32 ret = 0; int i; u8* ptr; u8 status; @@ -36,15 +36,15 @@ s32 __osVoiceSetADConverter(OSMesgQueue* mq, s32 channel, u8 data) { ptr[sizeof(__OSVoiceSWriteFormat)] = CONT_CMD_END; } else { - ptr = (u8*)&__osPfsPifRam + channel; + ptr += channel; } SWRITEFORMAT(ptr)->data = data; - SWRITEFORMAT(ptr)->scrc = __osContAddressCrc(data * 8); + SWRITEFORMAT(ptr)->scrc = __osContAddressCrc(data << 3); - __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_WRITE, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); - __osSiRawStartDma(OS_READ, &__osPfsPifRam); + ret = __osSiRawStartDma(OS_READ, &__osPfsPifRam); osRecvMesg(mq, NULL, OS_MESG_BLOCK); ret = CHNL_ERR(*SWRITEFORMAT(ptr)); @@ -54,9 +54,9 @@ s32 __osVoiceSetADConverter(OSMesgQueue* mq, s32 channel, u8 data) { ret = __osVoiceGetStatus(mq, channel, &status); if (ret != 0) { break; + } else { + ret = CONT_ERR_CONTRFAIL; } - - ret = CONT_ERR_CONTRFAIL; } } else { ret = CONT_ERR_NO_CONTROLLER; diff --git a/src/voice/voicesetword.c b/src/voice/voicesetword.c index 64bbe13..59effcb 100644 --- a/src/voice/voicesetword.c +++ b/src/voice/voicesetword.c @@ -9,14 +9,23 @@ s32 osVoiceSetWord(OSVoiceHandle* hd, u8* word) { u8 stat; u8 buf[40]; - ERRCK(__osVoiceGetStatus(hd->__mq, hd->__channel, &stat)); - if (stat & 2) { + ret = __osVoiceGetStatus(hd->__mq, hd->__channel, &stat); + if (ret != 0) { + return ret; + } else if (stat & 2) { return CONT_ERR_VOICE_NO_RESPONSE; } + for (k = 0; word[k] != 0; k += 2) { ; } +#ifndef NDEBUG + if (k >= 34) { + return CONT_ERR_VOICE_WORD; + } +#endif + bzero(buf, ARRLEN(buf)); for (j = 0; j < k; j += 2) { diff --git a/src/voice/voicestartreaddata.c b/src/voice/voicestartreaddata.c index 4e83ed1..ea83da0 100644 --- a/src/voice/voicestartreaddata.c +++ b/src/voice/voicestartreaddata.c @@ -8,8 +8,10 @@ s32 osVoiceStartReadData(OSVoiceHandle* hd) { u8 stat; u8 temp[4]; - ERRCK(__osVoiceGetStatus(hd->__mq, hd->__channel, &stat)); - if (stat & 2) { + ret = __osVoiceGetStatus(hd->__mq, hd->__channel, &stat); + if (ret != 0) { + return ret; + } else if (stat & 2) { return CONT_ERR_VOICE_NO_RESPONSE; } diff --git a/src/voice/voicestopreaddata.c b/src/voice/voicestopreaddata.c index d6380e6..b0f9cba 100644 --- a/src/voice/voicestopreaddata.c +++ b/src/voice/voicestopreaddata.c @@ -9,9 +9,10 @@ s32 osVoiceStopReadData(OSVoiceHandle* hd) { u8 stat; u8 temp[4]; - ERRCK(__osVoiceGetStatus(hd->__mq, hd->__channel, &stat)); - - if (stat & 2) { + ret = __osVoiceGetStatus(hd->__mq, hd->__channel, &stat); + if (ret != 0) { + return ret; + } else if (stat & 2) { return CONT_ERR_VOICE_NO_RESPONSE; } @@ -39,6 +40,9 @@ s32 osVoiceStopReadData(OSVoiceHandle* hd) { i++; } while ((ret == CONT_ERR_VOICE_NO_RESPONSE) && (i < 20)); } + if (i >= 20) { + ret == CONT_ERR_VOICE_NO_RESPONSE; + } return ret; } diff --git a/tools/Makefile b/tools/Makefile index f7bff84..8b5487e 100644 --- a/tools/Makefile +++ b/tools/Makefile @@ -1,11 +1,17 @@ .PHONY: all clean distclean + +# GCC GCC_DIR := gcc AR := $(GCC_DIR)/ar GCC-2.7.2 := $(GCC_DIR)/gcc STRIP-2.7 := $(GCC_DIR)/strip-2.7 -all: $(AR) $(GCC-2.7.2) $(STRIP-2.7) +# IDO +IDO_DIR := ido +IDO-5.3 := $(IDO_DIR)/cc + +all: $(AR) $(GCC-2.7.2) $(STRIP-2.7) $(IDO-5.3) $(AR): | $(GCC_DIR) wget https://github.com/decompals/mips-binutils-2.6/releases/download/main/binutils-2.6-linux.tar.gz @@ -25,6 +31,16 @@ $(STRIP-2.7): | $(GCC_DIR) $(GCC_DIR): mkdir -p $@ +$(IDO-5.3): | $(IDO_DIR) + wget https://github.com/decompals/ido-static-recomp/releases/latest/download/ido-5.3-recomp-ubuntu-20.04.tar.gz + tar xf ido-5.3-recomp-ubuntu-20.04.tar.gz -C $(IDO_DIR) + $(RM) ido-5.3-recomp-ubuntu-20.04.tar.gz + +$(IDO_DIR): + mkdir -p $@ + clean: -distclean: clean $(RM) -rf $(GCC_DIR) + $(RM) -rf $(IDO_DIR) + +distclean: clean diff --git a/tools/compile_sjis.py b/tools/compile_sjis.py index 1905745..136bdc7 100755 --- a/tools/compile_sjis.py +++ b/tools/compile_sjis.py @@ -9,6 +9,7 @@ WORKING_DIR = os.getcwd() fb = [] original_c_file = [i for i in sys.argv if ".c" in i][0] CC = [i for i in sys.argv if "-D__CC=" in i][0][7:] +build_dir = [i for i in sys.argv if "-D__BUILD_DIR" in i][0][14:] output_c_file = original_c_file @@ -19,7 +20,7 @@ original_c_file = "src/voice/" + original_c_file with open(original_c_file) as f: fb = f.read() -os.chdir("build/src/voice") +os.chdir(build_dir + "/src/voice") with open(output_c_file, "w+") as outf: sjis_process(fb, outf) diff --git a/tools/m2ctx.py b/tools/m2ctx.py new file mode 100755 index 0000000..39c5dc5 --- /dev/null +++ b/tools/m2ctx.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import argparse +import os +import sys +import subprocess +import tempfile + +script_dir = os.path.dirname(os.path.realpath(__file__)) +root_dir = os.path.abspath(os.path.join(script_dir, "..")) +src_dir = root_dir + "src/" + +# Project-specific +CPP_FLAGS = [ + "-Iinclude", + "-Iinclude/PR", + "-Iinclude/gcc", + "-Isrc", + "-Isrc/libc", + "-Iver/current/build/include", + "-D_LANGUAGE_C", + "-DF3DEX_GBI_2", + "-D_MIPS_SZLONG=32", + "-DSCRIPT(...)={}" + "-D__attribute__(...)=", + "-D__asm__(...)=", + "-ffreestanding", + "-DM2CTX", +] + +def import_c_file(in_file) -> str: + in_file = os.path.relpath(in_file, root_dir) + cpp_command = ["gcc", "-E", "-P", "-dM", *CPP_FLAGS, in_file] + cpp_command2 = ["gcc", "-E", "-P", *CPP_FLAGS, in_file] + + with tempfile.NamedTemporaryFile(suffix=".c") as tmp: + stock_macros = subprocess.check_output(["gcc", "-E", "-P", "-dM", tmp.name], cwd=root_dir, encoding="utf-8") + + out_text = "" + try: + out_text += subprocess.check_output(cpp_command, cwd=root_dir, encoding="utf-8") + out_text += subprocess.check_output(cpp_command2, cwd=root_dir, encoding="utf-8") + except subprocess.CalledProcessError: + print( + "Failed to preprocess input file, when running command:\n" + + cpp_command, + file=sys.stderr, + ) + sys.exit(1) + + if not out_text: + print("Output is empty - aborting") + sys.exit(1) + + for line in stock_macros.strip().splitlines(): + out_text = out_text.replace(line + "\n", "") + return out_text + +def main(): + parser = argparse.ArgumentParser( + description="""Create a context file which can be used for mips_to_c""" + ) + parser.add_argument( + "c_file", + help="""File from which to create context""", + ) + args = parser.parse_args() + + output = import_c_file(args.c_file) + + with open(os.path.join(root_dir, "ctx.c"), "w", encoding="UTF-8") as f: + f.write(output) + + +if __name__ == "__main__": + main() diff --git a/tools/print_mdebug.py b/tools/print_mdebug.py new file mode 100755 index 0000000..e0b295a --- /dev/null +++ b/tools/print_mdebug.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python3 +''' +Resources: +http://www.cs.unibo.it/~solmi/teaching/arch_2002-2003/AssemblyLanguageProgDoc.pdf +https://github.com/pathscale/binutils/blob/5c2c133020e41fc4aadd80a99156d2cea4754b96/include/coff/sym.h +https://github.com/pathscale/binutils/blob/5c2c133020e41fc4aadd80a99156d2cea4754b96/include/coff/symconst.h +https://github.com/pathscale/binutils/blob/5c2c133020e41fc4aadd80a99156d2cea4754b96/gas/ecoff.c +https://github.com/pathscale/binutils/blob/5c2c133020e41fc4aadd80a99156d2cea4754b96/bfd/ecoff.c +https://github.com/pathscale/absoft/blob/master/svn/trunk/ekopath-gcc/ekopath-gcc-4.2.0/gcc/mips-tdump.c +https://chromium.googlesource.com/native_client/nacl-toolchain/+/refs/tags/gcc-4.4.3/binutils/gas/ecoff.c +https://android.googlesource.com/toolchain/binutils/+/refs/heads/donut/binutils-2.17/bfd/ecofflink.c +https://kernel.googlesource.com/pub/scm/linux/kernel/git/hjl/binutils/+/hjl/secondary/include/coff/symconst.h +https://c0de.pw/bg/binutils-gdb/blob/cdbf20f73486c66e24f322400eba877eb534ae51/gdb/mdebugread.c +''' + +import os +import struct +import collections +import sys + +OFFSET = 0 # TODO why are the offsets in the symbolic header off by some amount? + +indent_level = 0 +is_comment = False + +symbol_type_list = [ + 'stNil', 'stGlobal', 'stStatic', 'stParam', 'stLocal', 'stLabel', 'stProc', 'stBlock', + 'stEnd', 'stMember', 'stTypedef', 'stFile', 'INVALID', 'INVALID', 'stStaticProc', 'stConstant', + 'stStaParam', 'INVALID', 'INVALID', 'INVALID', 'INVALID', 'INVALID', 'INVALID', 'INVALID', + 'INVALID', 'INVALID', 'stStruct', 'stUnion', 'stEnum', 'INVALID', 'INVALID', 'INVALID', + 'INVALID', 'INVALID', 'stIndirect'] +storage_class_list = ['scNil', 'scText', 'scData', 'scBss', 'scRegister', 'scAbs', 'scUndefined', 'reserved', + 'scBits', 'scDbx', 'scRegImage', 'scInfo', 'scUserStruct', 'scSData', 'scSBss', 'scRData', + 'scVar', 'scCommon', 'scSCommon', 'scVarRegister', 'scVariant', 'scUndefined', 'scInit'] +basic_type_c_list = ['nil', 'addr', 'signed char', 'unsigned char', 'short', 'unsigned short', 'int', 'unsigned int', + 'long', 'unsigned long', 'float', 'double', 'struct', 'union', 'enum', 'typedef', + 'range', 'set', 'complex', 'double complex', 'indirect', 'fixed decimal', 'float decimal', 'string', + 'bit', 'picture', 'void', 'long long', 'unsigned long long', 'INVALID', 'long', 'unsigned long', + 'long long', 'unsigned long long', 'addr', 'int64', 'unsigned int64'] + +def increase_indent(): + global indent_level + indent_level += 1 + +def decrease_indent(): + global indent_level + indent_level -= 1 + +def set_is_comment(set_to): + global is_comment + old = is_comment + is_comment = set_to + return old + +def get_indent(): + global indent_level + global is_comment + ret = '//' if is_comment else '' + for i in range(indent_level): + ret += ' ' + return ret + +def check_indent(): + global indent_level + assert indent_level == 0 + +def read_uint32_be(file_data, offset): + return struct.unpack('>I', file_data[offset:offset+4])[0] + +def read_uint16_be(file_data, offset): + return struct.unpack('>H', file_data[offset:offset+2])[0] + +def read_uint8_be(file_data, offset): + return struct.unpack('>B', file_data[offset:offset+1])[0] + +def read_elf_header(file_data, offset): + Header = collections.namedtuple('ElfHeader', + '''e_magic e_class e_data e_version e_osabi e_abiversion e_pad + e_type e_machine e_version2 e_entry e_phoff e_shoff e_flags + e_ehsize e_phentsize e_phnum e_shentsize e_shnum e_shstrndx''') + return Header._make(struct.unpack('>I5B7s2H5I6H', file_data[offset:offset+52])) + +def read_elf_section_header(file_data, offset): + Header = collections.namedtuple('SectionHeader', + '''sh_name sh_type sh_flags sh_addr sh_offset sh_size sh_link + sh_info sh_addralign sh_entsize''') + return Header._make(struct.unpack('>10I', file_data[offset:offset+40])) + +def read_symbolic_header(file_data, offset): + Header = collections.namedtuple('SymbolicHeader', + '''magic vstamp ilineMax cbLine cbLineOffset idnMax cbDnOffset + ipdMax cbPdOffset isymMax cbSymOffset ioptMax cbOptOffset + iauxMax cbAuxOffset issMax cbSsOffset issExtMax cbSsExtOffset + ifdMax cbFdOffset crfd cbRfdOffset iextMax cbExtOffset''') + return Header._make(struct.unpack('>2H23I', file_data[offset:offset+96])) + +# TODO find a better solution for the bitfield +def read_file_descriptor(file_data, offset): + if 'init' not in read_file_descriptor.__dict__: + read_file_descriptor.cache = {} + read_file_descriptor.header = collections.namedtuple('FileDescriptor', + '''adr rss issBase cbSs isymBase csym ilineBase cline ioptBase + copt ipdFirst cpd iauxBase caux rfdBase crfd XXX_bitfield + cbLineOffset cbLine''') + read_file_descriptor.init = True + if offset in read_file_descriptor.cache: + return read_file_descriptor.cache[offset] + read_file_descriptor.cache[offset] = read_file_descriptor.header._make( + struct.unpack('>I2iI6iHh4iI2I', file_data[offset:offset+72])) + return read_file_descriptor.cache[offset] + +def read_procedure_descriptor(file_data, offset): + Header = collections.namedtuple('ProcedureDescriptor', + '''adr isym iline regmask regoffset iopt fregmask fregoffset + frameoffset framereg pcreg lnLow lnHigh cbLineOffset''') + return Header._make(struct.unpack('>I8i2h2iI', file_data[offset:offset+52])) + +def read_symbol(file_data, offset): + if 'init' not in read_symbol.__dict__: + read_symbol.cache = {} + read_symbol.header = collections.namedtuple('Symbol', '''iss value st sc index''') + read_symbol.init = True + if offset in read_symbol.cache: + return read_symbol.cache[offset] + (word0, word1, word2) = struct.unpack('>iiI', file_data[offset:offset+12]) + read_symbol.cache[offset] = read_symbol.header._make(( + word0, word1, (word2 >> 26) & 0x3F, (word2 >> 21) & 0x1F, word2 & 0xFFFFF)) + return read_symbol.cache[offset] + +def read_auxiliary_symbol(file_data, offset): + if 'init' not in read_auxiliary_symbol.__dict__: + read_auxiliary_symbol.cache = {} + read_auxiliary_symbol.header = collections.namedtuple('AuxSymbol', + '''ti rndx dnLow dnHigh isym iss width count''') + read_auxiliary_symbol.type_info = collections.namedtuple('TypeInfo', + '''fBitfield continued bt tq4 tq5 tq0 tq1 tq2 tq3''') + read_auxiliary_symbol.rel_sym = collections.namedtuple('RelativeSymbol', '''rfd index''') + read_auxiliary_symbol.init = True + if offset in read_auxiliary_symbol.cache: + return read_auxiliary_symbol.cache[offset] + word0 = struct.unpack('>I', file_data[offset:offset+4])[0] + read_auxiliary_symbol.cache[offset] = read_auxiliary_symbol.header._make(( + read_auxiliary_symbol.type_info._make(((word0 >> 31) & 1, (word0 >> 30) & 1, (word0 >> 24) & 0x3F, (word0 >> 20) & 0xF, (word0 >> 16) & 0xF, (word0 >> 12) & 0xF, (word0 >> 8) & 0xF, (word0 >> 4) & 0xF, word0 & 0xF)), + read_auxiliary_symbol.rel_sym._make(((word0 >> 20) & 0xFFF, word0 & 0xFFFFF)), + word0, word0, word0, word0, word0, word0)) + return read_auxiliary_symbol.cache[offset] + +def read_string(file_data, offset): + current_offset = 0 + current_string = b'' + while True: + char = struct.unpack('c', file_data[offset+current_offset:offset+current_offset+1])[0] + if char == b'\0': + return current_string.decode('ascii') + else: + current_string += char + current_offset += 1 + +def map_relative_file_descriptor(file_data, fd, symbolic_header, rfd_num): + if fd.crfd == 0: + return rfd_num + + offset = symbolic_header.cbRfdOffset - OFFSET + (fd.rfdBase + rfd_num)*4 + return struct.unpack('>I', file_data[offset:offset+4])[0] + +def get_symbol_name_from_aux(file_data, fd, symbolic_header, aux_num, search_for_typedef): + aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + aux_num)*4) + fd_num = aux.rndx.rfd + next_aux = aux_num+1 + if fd_num == 4095: + aux2 = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + next_aux)*4) + fd_num = aux2.isym + next_aux = next_aux+1; + fd_num = map_relative_file_descriptor(file_data, fd, symbolic_header, fd_num) + fd2 = read_file_descriptor(file_data, symbolic_header.cbFdOffset - OFFSET + fd_num*72) + sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + (fd2.isymBase + aux.rndx.index)*12) + ret = '' + #print('%r' % (aux,)); + #print('%r' % (aux2,)); + #print('%r' % (sym,)); + if sym.st == 26 or sym.st == 27: #stStruct, stunion + ret = get_struct_or_union_string(file_data, fd2, symbolic_header, fd2.isymBase + aux.rndx.index, search_for_typedef) + elif sym.st == 28: #stEnum: + ret = get_enum_string(file_data, fd2, symbolic_header, fd2.isymBase + aux.rndx.index) + else: + ret = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd2.issBase + sym.iss) + return (ret, next_aux) + +def get_type_string(file_data, fd, symbolic_header, aux_num, name, search_for_typedef): + ret = '' + aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + aux_num)*4) + #print(''); + #print('%r' % (aux,)); + next_aux = aux_num+1 + has_bitfield = aux.ti.fBitfield == 1 + bitwidth = 0 + if has_bitfield: + bit_aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + next_aux)*4) + bitwidth = bit_aux.isym + next_aux = next_aux+1 + if aux.ti.bt == 12: # btStruct + (ret, next_aux) = get_symbol_name_from_aux(file_data, fd, symbolic_header, next_aux, search_for_typedef) + elif aux.ti.bt == 13: # btUnion + (ret, next_aux) = get_symbol_name_from_aux(file_data, fd, symbolic_header, next_aux, search_for_typedef) + elif aux.ti.bt == 15: # btTypedef + (ret, next_aux) = get_symbol_name_from_aux(file_data, fd, symbolic_header, next_aux, search_for_typedef) + elif aux.ti.bt == 14: # btEnum + (ret, next_aux) = get_symbol_name_from_aux(file_data, fd, symbolic_header, next_aux, search_for_typedef) + else: + if aux.ti.bt >= 36: + print('Error unknow bt: %d' % (aux.ti.bt)) + ret = basic_type_c_list[aux.ti.bt] + + tq_list = (aux.ti.tq0, aux.ti.tq1, aux.ti.tq2, aux.ti.tq3, aux.ti.tq4, aux.ti.tq5) + + # TODO this is very naive and probably does not work in a large amount of cases + last_was_proc = False # if we see a tqProc, assume the next will be a tqPtr + for tq in tq_list: + if tq == 0: # tqNil + break; + elif tq == 1: # tqPtr + if last_was_proc: + last_was_proc = False + continue + ret += '*' + elif tq == 2: # tqProc + last_was_proc = True + name = '(*%s)(/* ECOFF does not store param types */)' % name + elif tq == 3: # tqArray + next_aux += 2 # todo what does this skip over? (Apparantly the type of the index, so always int for C) + array_low_aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + next_aux)*4) + array_high_aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + next_aux+1)*4) + stride_aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + next_aux+2)*4) + next_aux += 3 + if array_high_aux.dnHigh == 0xFFFFFFFF: + name += '[]' + else: + name += '[%d]' % (array_high_aux.dnHigh + 1) + elif tq == 4: # tqFar + print('ERROR tqFar in get_type_name') + elif tq == 5: # tqVol + ret = 'volatile ' + ret + elif tq == 6: # tqConst + ret = 'const ' + ret + if has_bitfield: + name += ' : %d' % bitwidth + return ret + ' ' + name + +def get_enum_string(file_data, fd, symbolic_header, enum_sym_num): + ret = '' + start_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + enum_sym_num*12) + if start_sym.st != 28: + print('ERROR unknown type in get_enum_string start:%d' % start_sym.st) + return ret + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + start_sym.iss) + if name != '': + name += ' ' + ret += 'enum %s{\n' % name + increase_indent() + sym_num = enum_sym_num + 1 + while sym_num < fd.isymBase + start_sym.index: + sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + if sym.st == 8: # stEnd + decrease_indent() + ret += get_indent() + ret += '}' + elif sym.st == 9: # stMember + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + ret += get_indent() + ret += '%s = %d,\n' % (name, sym.value) + else: + print('ERROR unknown type in get_enum_string:%d' % sym.st) + break + sym_num += 1 + return ret + +def get_struct_or_union_string(file_data, fd, symbolic_header, union_sym_num, search_for_typedef): + ret = '' + start_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + union_sym_num*12) + if search_for_typedef: + typedef_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + (fd.isymBase + start_sym.index)*12) + if typedef_sym.st == 10: # stTypedef + return read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + typedef_sym.iss) + else: + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + start_sym.iss) + if name != '': + return name + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + start_sym.iss) + if name != '': + name += ' ' + if start_sym.st == 26: # stStruct + ret += 'struct %s{\n' % name + increase_indent() + elif start_sym.st == 27: # stUnion + ret += 'union %s{\n' % name + increase_indent() + else: + print('ERROR unknown type in get_struct_or_union_string start:%d' % start_sym.st) + return ret + sym_num = union_sym_num + 1 + while sym_num < fd.isymBase + start_sym.index: + sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + if sym.st == 8: # stEnd + decrease_indent() + ret += get_indent() + ret += '}' + elif sym.st == 9: # stMember + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + ret += get_indent() + ret += '/* 0x%X */ %s;\n' % (sym.value // 8, get_type_string(file_data, fd, symbolic_header, sym.index, name, True)) + elif sym.st == 26 or sym.st == 27: #stStruct, stUnion + sym_num = fd.isymBase + sym.index + continue + elif sym.st == 34: # stIndirect + # TODO what even is a stIndirect? + sym_num += 1 + else: + print('ERROR unknown type in get_struct_or_union_string:%d' % sym.st) + break + sym_num += 1 + return ret + +def print_typedef_symbols(file_data, fd, symbolic_header, typedef_sym_num): + typedef_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + typedef_sym_num*12) + if typedef_sym.st != 10: # stTypedef + print('ERROR expected stTypedef symbol in print_typedef_symbols, found:%d' % typedef_sym.st) + return + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + typedef_sym.iss) + print('typedef %s;' % get_type_string(file_data, fd, symbolic_header, typedef_sym.index, name, False)) + +def print_procedure(file_data, fd, symbolic_header, proc_sym_num): + proc_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + proc_sym_num*12) + proc_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + proc_sym.iss) + print('%s(' % get_type_string(file_data, fd, symbolic_header, proc_sym.index+1, proc_name, True), end='') + sym_num = proc_sym_num+1 + param_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + first = True + while param_sym.st == 3: # stParam + param_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + param_sym.iss) + print('%s%s' % ('' if first else ', ', + get_type_string(file_data, fd, symbolic_header, param_sym.index, param_name, True)), + end='') + sym_num += 1 + param_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + first = False + + print(');') + + check_indent(); + + comment_old = set_is_comment(True) + while sym_num < fd.isymBase + fd.csym: + sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + sym_num += 1 + if sym.st == 7: # stBlock + print('%s{' % get_indent()) + increase_indent() + elif sym.st == 8: # stEnd + end_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + if end_name == proc_name: + break + if end_name != '': + # this is a stEnd for something other than the function. Let's back out and return + sym_num -= 1 + break + decrease_indent() + print('%s}' % get_indent()) + elif sym.st == 4: # stLocal + local_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + is_reg = sym.sc == 4 # scRegister + print('%s%s%s;' % (get_indent(), + 'register ' if is_reg else '', + get_type_string(file_data, fd, symbolic_header, sym.index, local_name, True))) + elif sym.st == 2: # stStatic + static_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + if sym.index == 0xFFFFF: + print('%sstatic %s; // no type symbol' % (get_indent(),static_name)) + else: + print('%sstatic %s;' % (get_indent(),get_type_string(file_data, fd, symbolic_header, sym.index, static_name, True))) + elif sym.st == 5: # stLabel + label_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + print('%sLabel: %s @ %d;' % (get_indent(), label_name, sym.value)) + elif sym.st == 6: # stProc + # multiple name for function? + sym_num = print_procedure(file_data, fd, symbolic_header, sym_num-1) + elif sym.st == 26 or sym.st == 27: # stStruct, stUnion + print('%s%s;' % (get_indent(), get_struct_or_union_string(file_data, fd, symbolic_header, sym_num-1, False))) + sym_num = fd.isymBase + sym.index + elif sym.st == 28: # stEnum + print('%s%s;' % (get_indent(), get_enum_string(file_data, fd, symbolic_header, sym_num-1))) + sym_num = fd.isymBase + sym.index + elif sym.st == 34: # stIndirect + # TODO what even is a stIndirect? + indirect_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss) + print('%sTODO Indirect: %s;' % (get_indent(), indirect_name)) + else: + print('ERROR unknown st in print_procedure: %d' % sym.st) + set_is_comment(comment_old) + + check_indent(); + + return sym_num + +def print_symbols(file_data, fd, symbolic_header): + sym_num = fd.isymBase + indirects = [] + typedefs = [] + while sym_num < fd.isymBase + fd.csym: + root_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + if root_sym.st == 10: # stTypedef + aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + root_sym.index)*4) + offset = 0 + if aux.ti.fBitfield == 1: + offset = 1 + if aux.ti.bt == 12 or aux.ti.bt == 13 or aux.ti.bt == 14 or aux.ti.bt == 15: # btStruct, btUnion, btEnum, btTypedef + aux2 = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + root_sym.index + 1 + offset)*4) + fd_num = aux2.rndx.rfd + if fd_num == 4095: + fd_num = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + root_sym.index + 2 + offset)*4).isym + fd_num = map_relative_file_descriptor(file_data, fd, symbolic_header, fd_num) + fd2 = read_file_descriptor(file_data, symbolic_header.cbFdOffset - OFFSET + fd_num*72) + sym2 = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + (fd2.isymBase + aux2.rndx.index)*12) + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd2.issBase + sym2.iss) + if name != '': + typedefs.append(name) + elif root_sym.st == 34: # stIndirect + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + root_sym.iss) + indirects.append(name); + sym_num += 1 + sym_num = fd.isymBase + while sym_num < fd.isymBase + fd.csym: + root_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + if root_sym.st == 11: # stFile + file_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + root_sym.iss) + print('// begin file %s\n' % file_name) + sym_num += 1 + leaf_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + while leaf_sym.st != 8: # stEnd + if leaf_sym.st == 26 or leaf_sym.st == 27: # stStruct, stUnion + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + leaf_sym.iss) + if (name != '') and ((name in indirects) or (name not in typedefs)): # TODO + print('%s;\n' % get_struct_or_union_string(file_data, fd, symbolic_header, sym_num, False)) + sym_num = fd.isymBase + leaf_sym.index + elif leaf_sym.st == 28: # stEnum + name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + leaf_sym.iss) + if (name != '') and (name not in typedefs): # TODO + print('%s;\n' % get_enum_string(file_data, fd, symbolic_header, sym_num)) + sym_num = fd.isymBase + leaf_sym.index + elif leaf_sym.st == 10: # stTypedef + # TODO typedef for stIndirect shoulf print the keyword i.e. typdef >struct< THING thing + print_typedef_symbols(file_data, fd, symbolic_header, sym_num) + sym_num += 1 + print('') + elif leaf_sym.st == 6 or leaf_sym.st == 14: # stProc, stStaticProc + # TODO how do stProc and stStaticProc differ? stStaticProc isn't exported? + sym_num = print_procedure(file_data, fd, symbolic_header, sym_num) + print('') + elif leaf_sym.st == 2: # stStatic + static_name = read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + leaf_sym.iss) + if leaf_sym.sc == 2 or leaf_sym.sc == 3 or leaf_sym.sc == 5 or leaf_sym.sc == 15: # scData, scBss, scAbsolute, scRData + if leaf_sym.index != 0xFFFFF: # looks like it's an invalid value for .s files + print('static %s;\n' % get_type_string(file_data, fd, symbolic_header, leaf_sym.index, static_name, True)) + else: + print('static %s;\n' % static_name) + else: + print('ERROR unknown sc for stStatic in print_symbols: %d' % leaf_sym.sc) + sym_num += 1 + elif leaf_sym.st == 34: # stIndirect + # stIndirect is put out when the compiler sees a struct when it is not yet defined + # TODO more info + sym_num += 1 + elif leaf_sym.st == 5: # stLabel + print('// label: %s' % read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + leaf_sym.iss)) + sym_num += 1 + elif leaf_sym.st == 0: # stNil + print('// nil: %s' % read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + leaf_sym.iss)) + sym_num += 1 + else: + print('ERROR unknown st in leaf_sym in print_symbols: %d' % leaf_sym.st) + sym_num += 1 + leaf_sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + sym_num = fd.isymBase + root_sym.index + print('// end file %s' % file_name) + else: + print('ERROR expected st of stFile as only root type in print_symbols:%d' % root_sym.st) + return + +def main(): + global OFFSET + if len(sys.argv) < 2: + return # TODO print usage + + filename = sys.argv[1] + + try: + with open(filename, 'rb') as f: + file_data = f.read() + except IOError: + print('failed to read file ' + filename) + return + + elf_header = read_elf_header(file_data, 0) + section_headers = [] + debug_index = 0xFFFFFFFF + #print('%r' % (elf_header,)) + for i in range(elf_header.e_shnum): + section_headers.append(read_elf_section_header(file_data, elf_header.e_shoff + i*40)) + #print('%r' % (section_headers[i],)) + if section_headers[i].sh_type == 0x70000005: + debug_index = i + + if debug_index != 0xFFFFFFFF: + symbolic_header = read_symbolic_header(file_data, section_headers[debug_index].sh_offset) + file_descriptors = [] + print('%r' % (symbolic_header,)) + # Set offset by assuming that there are no optimization symbols so cbOptOffset points to the start of the symbolic header + #OFFSET = symbolic_header.cbOptOffset - section_headers[debug_index].sh_offset + #print('Using OFFSET of %d' % OFFSET) + #for sym_num in range(symbolic_header.isymMax): + #sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + #print('%d:%r' % (sym_num, (sym,))); + #for aux_num in range(symbolic_header.iauxMax): + #aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + aux_num*4) + #print('%d:%r' % (aux_num, (aux,))); + for file_num in range(symbolic_header.ifdMax): + fd = read_file_descriptor(file_data, symbolic_header.cbFdOffset - OFFSET + file_num*72) + file_descriptors.append(fd) + for file_num in range(symbolic_header.ifdMax): + fd = read_file_descriptor(file_data, symbolic_header.cbFdOffset - OFFSET + file_num*72) + print('%r' % (fd,)) + print(' name:%s' % read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + fd.rss)) + + ''' + print(' Relative File Descriptors:') + for rfd_num in range(fd.rfdBase, fd.rfdBase + fd.crfd): + offset = symbolic_header.cbRfdOffset - OFFSET + rfd_num*4 + rfd_index = struct.unpack('>I', file_data[offset:offset+4])[0] + rfd = read_file_descriptor(file_data, symbolic_header.cbFdOffset - OFFSET + rfd_index*72) + print(' %d:%r' % (rfd_index, (rfd,))) + ''' + + ''' + print(' procedures:') + for proc_num in range(fd.ipdFirst, fd.ipdFirst + fd.cpd): + pd = read_procedure_descriptor(file_data, symbolic_header.cbPdOffset - OFFSET + proc_num*52) + print(' %r' % ((pd,))) + ''' + + ''' + print(' symbols:') + for sym_num in range(fd.isymBase, fd.isymBase + fd.csym): + sym = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + sym_num*12) + print(' %r' % ((sym,))) + print(' name:%s' % read_string(file_data, symbolic_header.cbSsOffset - OFFSET + fd.issBase + sym.iss)) + print(' type:%s(%d)' % (symbol_type_list[sym.st], sym.st)) + print(' storage class:%s(%d)' % (storage_class_list[sym.sc], sym.sc)) + if sym.st == 3 or sym.st == 4 or sym.st == 9 or sym.st == 10 or sym.st == 28: # stParam, stLocal, stMember, stTypedef, stEnum + aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + sym.index)*4) + print(' %r' % ((aux,))) + offset = 0 + if aux.ti.fBitfield == 1: + bitfield_aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + sym.index + 1)*4) + print(' %r' % ((bitfield_aux,))) + offset = 1 + if aux.ti.bt == 12 or aux.ti.bt == 13 or aux.ti.bt == 14 or aux.ti.bt == 15: # btStruct, btUnion, btEnum, btTypedef + aux2 = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + sym.index + 1 + offset)*4) + print(' %r' % ((aux2,))) + fd_num = aux2.rndx.rfd + if fd_num == 4095: + aux3 = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + sym.index + 2 + offset)*4) + print(' %r' % ((aux3,))) + fd_num = aux3.isym + fd_num = map_relative_file_descriptor(file_data, fd, symbolic_header, fd_num) + sym2 = read_symbol(file_data, symbolic_header.cbSymOffset - OFFSET + (file_descriptors[fd_num].isymBase + aux2.rndx.index)*12) + print(' %r' % (sym2,)) + print(' name:%s' % read_string(file_data, symbolic_header.cbSsOffset - OFFSET + file_descriptors[aux3.isym].issBase + sym2.iss)) + if sym.st == 6 or sym.st == 14: # stProc, stStaticProc + # TODO what is the first aux symbol for? + aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + sym.index)*4) + type_aux = read_auxiliary_symbol(file_data, symbolic_header.cbAuxOffset - OFFSET + (fd.iauxBase + sym.index+1)*4) + print(' %r' % ((aux,))) + print(' %r' % ((type_aux,))) + ''' + + print(' pretty print:') + print_symbols(file_data, fd, symbolic_header) + + +main() \ No newline at end of file