diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..3cd779d Binary files /dev/null and b/.DS_Store differ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..be8c706 --- /dev/null +++ b/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - build +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = build + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/add-ins/TwlSystem/NitroSystem_patch.zip b/add-ins/TwlSystem/NitroSystem_patch.zip new file mode 100644 index 0000000..4eb1525 Binary files /dev/null and b/add-ins/TwlSystem/NitroSystem_patch.zip differ diff --git a/add-ins/TwlSystem/使用方法.txt b/add-ins/TwlSystem/使用方法.txt new file mode 100644 index 0000000..2572dc4 --- /dev/null +++ b/add-ins/TwlSystem/使用方法.txt @@ -0,0 +1,25 @@ +--------------- +̃pb`͎bIȂ NitroSystem +TWL-SDK Ńrh/gpł悤ɂ̂łB +Yt zip t@CWJ NitroSystem ɏ㏑ĂB + + +ETWLSYSTEM_ROOT ‹ϐ NITROSYSTEM_ROOT ‹ϐ +@lݒ肷Kv܂B +ENitroSystem ̓rhȂKv܂B +Esnd, mcs Cu͎gpł܂B +Edemo ͂̂܂܂ł̓rhł܂B +@TWL-SDK ł nef tef ֕ύXꂽ +@TARGET_NEF ݒ肳Ă͍̂폜Kv܂B +---- + + +demõrhʂ@ + +LLIBRARY_DIRS = $(G2D_DEMOLIB)/lib/$(NITRO_BUILDTYPE) + +LLIBRARY_DIRS = $(G2D_DEMOLIB)/$(LIBDIR) + + +TARGET_NEF = main.nef@폜B + diff --git a/build/.DS_Store b/build/.DS_Store new file mode 100644 index 0000000..5acca63 Binary files /dev/null and b/build/.DS_Store differ diff --git a/build/Makefile b/build/Makefile new file mode 100644 index 0000000..a3f0a1e --- /dev/null +++ b/build/Makefile @@ -0,0 +1,37 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - build +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + tools \ + libraries \ + nandfirm \ + nand_formatter \ + libraries_sysmenu\ + systemmenu_RED + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/buildtools/commondefs b/build/buildtools/commondefs new file mode 100644 index 0000000..d091bed --- /dev/null +++ b/build/buildtools/commondefs @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - commondefs - common definitions for build system +# File: commondefs +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +ifndef TWL_IPL_COMMONDEFS_ +TWL_IPL_COMMONDEFS_ = TRUE + + +ifeq ($(TARGET_FIRM),SYSTEMMENU) +include $(TWLIPL_ROOT)/build/buildtools/commondefs.sysmenu +else +include $(TWLIPL_ROOT)/build/buildtools/commondefs.firm +endif + +#---------------------------------------------------------------------------- +endif # TWL_IPL_COMMONDEFS_ +#----- End of commondefs ----- diff --git a/build/buildtools/commondefs.firm b/build/buildtools/commondefs.firm new file mode 100644 index 0000000..d8a8d2b --- /dev/null +++ b/build/buildtools/commondefs.firm @@ -0,0 +1,260 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - commondefs - common definitions for build system +# File: commondefs +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +ifndef TWLFIRM_COMMONDEFS_ +TWLFIRM_COMMONDEFS_ = TRUE + +NITRO_NO_STD_PCHDR = TRUE # vRpCwb_}~ + +ifndef TWL_KEYSDIR +DUMMY_KEYS_SUFFIX = .dummykey +endif +TWL_KEYSDIR ?= $(FIRM_ROOT)/keys/dummy + + +ifneq ($(filter FIRM GCDFIRM,$(FIRM_TARGET)),) +TARGET_BIN ?= $(subst .,$(DUMMY_KEYS_SUFFIX).,$(TARGET_FIRM_BIN)) +endif + +EMPTY ?= +SPACE ?= $(EMPTY) $(EMPTY) + +# +# CodeGen Target +# +# FIRM_PLATFORM = [BB/EVA/TS] +# FIRM_MEMSIZE = [16M/32M] +# FIRM_CODEGEN = [ARM/THUMB] +# FIRM_PROC = [ARM9/ARM7] +# +# FIRM_TARGET = [FIRM/GCDFIRM/APP] +# + +FIRM_PLATFORM ?= TS +FIRM_MEMSIZE ?= 16M +FIRM_CODEGEN ?= ARM +FIRM_PROC ?= ARM9 +FIRM_TARGET ?= APP + +# replace TwlSDK +TWL_PLATFORM = $(FIRM_PLATFORM) +TWL_MEMSIZE = $(FIRM_MEMSIZE) +TWL_CODEGEN = $(FIRM_CODEGEN) +TWL_PROC = $(FIRM_PROC) + +# replace NitroSDK +ifndef CODEGEN_PROC +CODEGEN_PROC := $(FIRM_PROC) +endif + +ifeq ($(FIRM_CODEGEN),ALL) +FIRM_CODEGEN_ALL ?= TRUE +override FIRM_CODEGEN = ARM +endif + +ifeq ($(FIRM_CODEGEN),ARM) +FIRM_CODEGEN_ARCH = +else # ($(FIRM_CODEGEN),THUMB) +FIRM_CODEGEN_ARCH = .thumb +endif + +# +# SDK build type +# +# one of [FIRM_DEBUG/FIRM_RELEASE/FIRM_FINALROM] +# + +ifdef FIRM_DEBUG +FIRM_BUILD_TYPE ?= DEBUG +FIRM_BUILD_DIR ?= Debug + +else +ifdef FIRM_FINALROM +FIRM_BUILD_TYPE ?= FINALROM +FIRM_BUILD_DIR ?= Rom + +else # FIRM_RELEASE (default) +FIRM_BUILD_TYPE ?= RELEASE +FIRM_BUILD_DIR ?= Release + +endif +endif + +# replace TwlSDK +TWL_BUILD_TYPE ?= $(FIRM_BUILD_TYPE) +TWL_BUILD_DIR ?= $(FIRM_BUILD_DIR) + + + +#---------------------------------------------------------------------------- +# TWL-FIRM path settings +# + +FIRM_ROOT := $(subst $(SPACE),\ ,$(subst \,/,$(TWLIPL_ROOT))) +FIRM_BUILDTOOLSDIR := $(FIRM_ROOT)/build/buildtools +FIRM_BUILDSETUPDIR := $(FIRM_ROOT)/build/buildsetup +FIRM_INCDIR := $(FIRM_ROOT)/include +FIRM_TOOLSDIR := $(FIRM_ROOT)/tools +FIRM_COMPONENTSDIR := $(FIRM_ROOT)/components +FIRM_ADDINS ?= $(FIRM_ROOT)/add-ins + +FIRM_TWLSDK_ROOT ?=$(shell cygpath -w $(TWLSDK_ROOT)) +FIRM_NITROSDK_ROOT ?=$(shell cygpath -w $(NITROSDK_ROOT)) + +FIRM_BUILDARCH ?= $(CODEGEN_PROC)-$(FIRM_PLATFORM)$(FIRM_CODEGEN_ARCH) +FIRM_BUILDARCH_ARM9 := ARM9-$(FIRM_PLATFORM)$(FIRM_CODEGEN_ARCH) +FIRM_BUILDARCH_ARM7 := ARM7-$(FIRM_PLATFORM)$(FIRM_CODEGEN_ARCH) + +FIRM_BUILDTYPE ?= $(FIRM_BUILDARCH)/$(FIRM_BUILD_DIR) +FIRM_BUILDTYPE_ARM9 := $(FIRM_BUILDARCH_ARM9)/$(FIRM_BUILD_DIR) +FIRM_BUILDTYPE_ARM7 := $(FIRM_BUILDARCH_ARM7)/$(FIRM_BUILD_DIR) + +FIRM_LIBARCH := $(CODEGEN_PROC)-$(FIRM_PLATFORM) +FIRM_LIBTYPE := $(FIRM_LIBARCH)/$(FIRM_BUILD_DIR) +FIRM_LIBDIR := $(FIRM_ROOT)/lib/$(FIRM_LIBTYPE) +FIRM_LIBSYSCALLDIR := $(FIRM_ROOT)/lib/$(FIRM_LIBARCH)/etc +FIRM_LIBSUFFIX := .firm$(FIRM_CODEGEN_ARCH) + + +FIRM_SPECDIR := $(FIRM_INCDIR)/firm/specfiles +FIRM_LSFARCH := $(FIRM_LIBARCH) +ifneq ($(FIRM_TARGET),APP) +FIRM_LSFARCH := $(addsuffix -$(FIRM_TARGET),$(FIRM_LSFARCH)) +endif # FIRM_TARGET!=APP +FIRM_LCFARCH := $(FIRM_LSFARCH) +DEFAULT_FIRM_LCFILE := $(FIRM_SPECDIR)/$(FIRM_LCFARCH).lcf +DEFAULT_FIRM_LCFILE_TEMPLATE := $(FIRM_SPECDIR)/$(FIRM_LCFARCH)$(LCF_SUFFIX_).lcf.template +DEFAULT_FIRM_LCFILE_SPEC := $(FIRM_SPECDIR)/$(FIRM_LSFARCH).lsf +DEFAULT_FIRM_ROM_SPEC := $(FIRM_SPECDIR)/ROM-$(FIRM_PLATFORM).rsf + +# replace TwlSDK +TWL_BUILDARCH ?= $(FIRM_BUILDARCH) + + +### Compiler & Linker settings + +# replace NitroSDK +ifneq ($(FIRM_TARGET),APP) +LCFILE_TEMPLATE ?= $(DEFAULT_FIRM_LCFILE_TEMPLATE) +LCFILE_SPEC ?= $(DEFAULT_FIRM_LCFILE_SPEC) +ROM_SPEC ?= $(DEFAULT_FIRM_ROM_SPEC) +endif # FIRM_TARGET!=APP + +LDEPENDS_LCF += $(FIRM_BUILDTOOLSDIR)/commondefs +LDEPENDS_RES += $(FIRM_BUILDTOOLSDIR)/commondefs + + +### SDK Library settings + +ifeq ($(CODEGEN_PROC),ARM9) + +FIRM_LIBS_BASE ?= \ + libos \ + libmi \ + libpxi \ +# libgcd \ +# libacsign \ + +FIRM_TWL_LIBS_BASE ?= \ + +else # ($(CODEGEN_PROC),ARM7) + +FIRM_LIBS_BASE ?= \ + libos_sp \ + libfatfs_sp \ + libpxi_sp \ + libaes_sp \ + libpm_sp \ +# libnvram_sp \ +# libgcd_sp \ +# libacsign_sp \ +# libfirmsd_sp \ + +FIRM_TWL_LIBS_BASE ?= \ + +endif + +FIRM_LIBS ?= $(addsuffix $(FIRM_LIBSUFFIX).a,$(FIRM_LIBS_BASE)) +FIRM_LIBS += $(addsuffix $(TWL_LIBSUFFIX).a,$(FIRM_TWL_LIBS_BASE)) + +#---------------------------------------------------------------------------- +### TWL-commondefs +# +include $(TWLSDK_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- +# MY BUILD TOOLS +# +MAKENORFIRM := $(FIRM_TOOLSDIR)/bin/makenorfirm.exe +MAKENANDFIRM := $(FIRM_TOOLSDIR)/bin/makenandfirm.exe +MAKEGCDFIRM := $(FIRM_TOOLSDIR)/bin/makegcdfirm.exe +OPENSSL := $(FIRM_TOOLSDIR)/openssl/openssl.exe + +MAKEFIRM_RSA_PRVKEY ?= $(FIRM_TOOLSDIR)/openssl/rsa_private.der +MAKEFIRM_RSA_PUBKEY ?= $(FIRM_TOOLSDIR)/openssl/rsa_public.der + +MAKEFIRM_FLAGS ?= + +ifneq ($(filter FIRM GCDFIRM,$(FIRM_TARGET)),) +FIRM_STRIP_AXF := TRUE +endif + +#---------------------------------------------------------------------------- + +### Global Library resettings + +GINCLUDES := $(FIRM_INCDIR) $(GINCLUDES) +GLIBRARY_DIRS := $(FIRM_LIBDIR) $(GLIBRARY_DIRS) +GLIBRARIES := $(FIRM_LIBS) $(GLIBRARIES) + + +#---------------------------------------------------------------------------- +# TWLFIRM_INSTALL_ROOT +# + +ifdef TWLFIRM_INSTALL_ROOT +TWLFIRM_INSTALL_ROOT_ := $(TWLFIRM_INSTALL_ROOT) +else +TWLFIRM_INSTALL_ROOT_ := $(TWLIPL_ROOT) +endif + +FIRM_INSTALL_ROOT := $(subst $(SPACE),\ ,$(subst \,/,$(TWLFIRM_INSTALL_ROOT_))) +FIRM_INSTALL_INCDIR := $(FIRM_INSTALL_ROOT)/include +FIRM_INSTALL_TOOLSDIR := $(FIRM_INSTALL_ROOT)/tools +FIRM_INSTALL_LIBDIR := $(FIRM_INSTALL_ROOT)/lib/$(FIRM_LIBTYPE) +FIRM_INSTALL_PROMDIR := $(FIRM_INSTALL_TOOLSDIR)/prom +FIRM_INSTALL_COMPONENTSDIR := $(FIRM_INSTALL_ROOT)/components +FIRM_INSTALL_ADDINS := $(FIRM_INSTALL_ROOT)/add-ins + + +#---------------------------------------------------------------------------- +# Compiler flags +# +MACRO_FLAGS += -DFIRM_TARGET_$(FIRM_TARGET) + + +#---------------------------------------------------------------------------- +# Makelcf change for build firmware +# +ifneq ($(filter FIRM GCDFIRM,$(FIRM_TARGET)),) +MAKELCF := $(TWLSDK_ROOT)/tools/bin/makelcf.exe +endif + +#---------------------------------------------------------------------------- +endif # TWLFIRM_COMMONDEFS_ +#----- End of commondefs ----- diff --git a/build/buildtools/commondefs.sysmenu b/build/buildtools/commondefs.sysmenu new file mode 100644 index 0000000..64dd0dc --- /dev/null +++ b/build/buildtools/commondefs.sysmenu @@ -0,0 +1,97 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - commondefs - common definitions for build system +# File: commondefs +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +ifndef TWL_SYSMENU_COMMONDEFS_ +TWL_SYSMENU_COMMONDEFS_ = TRUE + +NITRO_NO_STD_PCHDR = TRUE # vRpCwb_}~ + +EMPTY ?= +SPACE ?= $(EMPTY) $(EMPTY) + +#---------------------------------------------------------------------------- +# TWL-SYSTEM-MENU path settings +# + +SYSMENU_ROOT := $(subst $(SPACE),\ ,$(subst \,/,$(TWLIPL_ROOT))) +SYSMENU_BUILDTOOLSDIR := $(SYSMENU_ROOT)/build/buildtools +SYSMENU_INCDIR := $(SYSMENU_ROOT)/include \ + $(TWLSDK_ROOT)/build/libraries/spi/arm9/include \ + $(TWLSDK_ROOT)/build/libraries/mb/common/include +SYSMENU_TOOLSDIR := $(SYSMENU_ROOT)/tools +SYSMENU_COMPONENTSDIR := $(SYSMENU_ROOT)/components + +LDEPENDS_LCF += $(SYSMENU_BUILDTOOLSDIR)/commondefs.sysmenu +LDEPENDS_RES += $(SYSMENU_BUILDTOOLSDIR)/commondefs.sysmenu + + +#---------------------------------------------------------------------------- +### TWL-commondefs +# +#include $(TWLSDK_ROOT)/build/buildtools/commondefs +include $(NITROSYSTEM_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- +### SYSTEM_MENU Library settings + +SYSMENU_LIBDIR := $(SYSMENU_ROOT)/lib/$(TWL_LIBTYPE) + +ifeq ($(CODEGEN_PROC),ARM9) + +SYSMENU_LIBS ?= \ + libsysmenu$(TWL_LIBSUFFIX).a \ + libmbloader$(TWL_LIBSUFFIX).a \ + libacsign$(TWL_LIBSUFFIX).a + +else # ($(CODEGEN_PROC),ARM7) + +SYSMENU_LIBS ?= \ + libmbloader_sp$(TWL_LIBSUFFIX).a + +endif + + +#---------------------------------------------------------------------------- +# MY BUILD TOOLS +# +OPENSSL := $(SYSMENU_TOOLSDIR)/openssl/openssl.exe + +MAKESYSMENU_RSA_PRVKEY ?= $(SYSMENU_TOOLSDIR)/openssl/rsa_private.der +MAKESYSMENU_RSA_PUBKEY ?= $(SYSMENU_TOOLSDIR)/openssl/rsa_public.der + +#---------------------------------------------------------------------------- + +### Global Library resettings + +GINCLUDES := $(SYSMENU_INCDIR) $(GINCLUDES) +GLIBRARY_DIRS := $(SYSMENU_LIBDIR) $(GLIBRARY_DIRS) +GLIBRARIES := $(SYSMENU_LIBS) $(GLIBRARIES) + + +#---------------------------------------------------------------------------- +# TWLSYSMENU_INSTALL_ROOT +# +SYSMENU_INSTALL_ROOT := $(SYSMENU_ROOT) +SYSMENU_INSTALL_INCDIR := $(SYSMENU_INSTALL_ROOT)/include +SYSMENU_INSTALL_TOOLSDIR := $(SYSMENU_INSTALL_ROOT)/tools +SYSMENU_INSTALL_LIBDIR := $(SYSMENU_INSTALL_ROOT)/lib/$(TWL_LIBTYPE) +SYSMENU_INSTALL_COMPONENTSDIR := $(SYSMENU_INSTALL_ROOT)/components + +#---------------------------------------------------------------------------- +endif # TWL_SYSMENU_COMMONDEFS_ +#----- End of commondefs ----- diff --git a/build/buildtools/modulerules b/build/buildtools/modulerules new file mode 100644 index 0000000..e6a5189 --- /dev/null +++ b/build/buildtools/modulerules @@ -0,0 +1,34 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - modulerules - common rules for build system +# File: modulerules +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +ifndef TWL_IPL_MODULERULES_ + +#---------------------------------------------------------------------------- +### TWL-modulerules +# + +ifeq ($(TARGET_FIRM),SYSTEMMENU) +include $(TWLIPL_ROOT)/build/buildtools/modulerules.sysmenu +else +include $(TWLIPL_ROOT)/build/buildtools/modulerules.firm +endif + + +#---------------------------------------------------------------------------- +TWL_IPL_MODULERULES_ = TRUE +endif # TWL_IPL_MODULERULES_ +#----- End of modulerules ----- diff --git a/build/buildtools/modulerules.firm b/build/buildtools/modulerules.firm new file mode 100644 index 0000000..4ea316f --- /dev/null +++ b/build/buildtools/modulerules.firm @@ -0,0 +1,92 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - modulerules - common rules for build system +# File: modulerules +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +ifndef TWLFIRM_MODULERULES_ + + +ifneq ($(MAKEFIRM_ARM9),) +MAKEROM_ARM9 = $(MAKEFIRM_ARM9) +endif +ifneq ($(MAKEFIRM_ARM7),) +MAKEROM_ARM7 = $(MAKEFIRM_ARM7) +endif + +#---------------------------------------------------------------------------- +### TWL-modulerules +# +include $(TWLSDK_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- + +# +# MAKENORFIRM / MAKENANDFIRM / MAKEGCDFIRM +# + +MAKEFIRM_ARM9 ?= $(MAKEROM_ARM9) +MAKEFIRM_ARM7 ?= $(MAKEROM_ARM7) + +MAKEFIRM_DEFS += -DFIRM_ROOT='$(FIRM_ROOT)' \ + -DMAKEFIRM_ARM9='$(basename $(MAKEFIRM_ARM9))' \ + -DMAKEFIRM_ARM7='$(basename $(MAKEFIRM_ARM7))' \ + -DMAKEFIRM_RSA_PRVKEY='$(MAKEFIRM_RSA_PRVKEY)' \ + +SDEPENDS_BIN += $(MAKEFIRM_RSA_PRVKEY) + + +.PHONY: firmtop firmlib + +firmtop: + @$(MAKE) -C $(TWLIPL_ROOT)/build + +firmlib: + @$(MAKE) -C $(TWLIPL_ROOT)/build/libraries + +# .nor +$(BINDIR)/%.nor: $(SDEPENDS_BIN) $(FIRM_SPEC) $(LDEPENDS_BIN) $(EDEPENDS_BIN) $(MAKEFILE) $(MAKENORFIRM) + $(MAKENORFIRM) $(MAKEFIRM_FLAGS) $(MAKEFIRM_DEFS) $(FIRM_SPEC) $@ + +# .nand +$(BINDIR)/%.nand: $(SDEPENDS_BIN) $(FIRM_SPEC) $(LDEPENDS_BIN) $(EDEPENDS_BIN) $(MAKEFILE) $(MAKENANDFIRM) + $(MAKENANDFIRM) $(MAKEFIRM_FLAGS) $(MAKEFIRM_DEFS) $(FIRM_SPEC) $@ + +# .gcd +$(BINDIR)/%.gcd: $(SDEPENDS_BIN) $(FIRM_SPEC) $(LDEPENDS_BIN) $(EDEPENDS_BIN) $(MAKEFILE) $(MAKEGCDFIRM) + $(MAKEGCDFIRM) $(MAKEFIRM_FLAGS) $(MAKEFIRM_DEFS) $(FIRM_SPEC) $@ + +# .rbin +$(BINDIR)/$(TARGET_BIN_BASENAME).rbin: $(OBJS) + objcopy -I elf32-little -O binary $< $@ + +# .axf +#$(BINDIR)/$(TARGET_BIN_BASENAME).axf: $(OBJS) $(LCFILE) $(MAKEFILE) $(LDEPENDS_NEF) $(EDEPENDS_NEF) $(ALIBRARIES) $(LDRES_FILE) $(CW_LIBCXX) +#ifeq ($(NITRO_CCTYPE),RVCT) +# $(LD) $(LDFLAGS) $(LIBRARY_DIRS) -o $@ $(GLIBRARIES) $(OBJS) +#else +# $(LD) $(LDFLAGS) $(LIBRARY_DIRS) @$(LDRES_FILE) $(LCFILE) -o $@ +#ifeq ($(TWL_PLATFORM),TS) +# cp $(BINDIR)/$(TARGET_BIN_BASENAME).axf $(BINDIR)/$(TARGET_BIN_BASENAME).tef +#else # ($(TWL_PLATFORM),BB) +#ifdef FIRM_STRIP_AXF +# $(OBJCOPY) $@ $(BINDIR)/$(TARGET_BIN_BASENAME).sbin +#endif +#endif +#endif + +#---------------------------------------------------------------------------- +TWLFIRM_MODULERULES_ = TRUE +endif # TWLFIRM_MODULERULES_ +#----- End of modulerules ----- diff --git a/build/buildtools/modulerules.sysmenu b/build/buildtools/modulerules.sysmenu new file mode 100644 index 0000000..ff50b1e --- /dev/null +++ b/build/buildtools/modulerules.sysmenu @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - modulerules - common rules for build system +# File: modulerules +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +ifndef TWL_SYSMENU_MODULERULES_ + +#---------------------------------------------------------------------------- +### TWL-modulerules +# +#include $(TWLSDK_ROOT)/build/buildtools/modulerules +include $(NITROSYSTEM_ROOT)/build/buildtools/modulerules + + +#---------------------------------------------------------------------------- +TWL_SYSMENU_MODULERULES_ = TRUE +endif # TWL_SYSMENU_MODULERULES_ +#----- End of modulerules ----- diff --git a/build/libraries/.DS_Store b/build/libraries/.DS_Store new file mode 100644 index 0000000..191272f Binary files /dev/null and b/build/libraries/.DS_Store differ diff --git a/build/libraries/Makefile b/build/libraries/Makefile new file mode 100644 index 0000000..43e0847 --- /dev/null +++ b/build/libraries/Makefile @@ -0,0 +1,44 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + os \ + gcd \ + mi \ + init \ + pxi \ + fatfs \ + aes \ + pm \ +# syscall \ +# nvram \ +# acsign \ +# acsign_ecc \ +# devices \ + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/aes/ARM7/Makefile b/build/libraries/aes/ARM7/Makefile new file mode 100644 index 0000000..a19bb1d --- /dev/null +++ b/build/libraries/aes/ARM7/Makefile @@ -0,0 +1,60 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - aes +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +SUBMAKES = + + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +# Codegen for sub processer +FIRM_PROC = ARM7 + +SRCDIR = . + +SRCS = \ + aes_init.c \ + aes_util.c \ + +TARGET_LIB = libaes_sp$(FIRM_LIBSUFFIX).a + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/aes/ARM7/aes_init.c b/build/libraries/aes/ARM7/aes_init.c new file mode 100644 index 0000000..9f37d4c --- /dev/null +++ b/build/libraries/aes/ARM7/aes_init.c @@ -0,0 +1,72 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - aes + File: aes_init.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +/*---------------------------------------------------------------------------* + Name: AESi_InitGameKeys + + Description: set IDs depending on the application. + you SHOULD NOT touch any ID registers after this call. + + Arguments: u8[4] game code + + Returns: None + *---------------------------------------------------------------------------*/ +void AESi_InitGameKeys( u8 game_code[4] ) +{ + while (reg_AES_AES_CNT & REG_AES_AES_CNT_E_MASK) + { + } + + reg_AES_AES_ID_B2 = AES_IDS_ID0_C(game_code); + reg_AES_AES_ID_B3 = AES_IDS_ID0_D(game_code); + + reg_AES_AES_ID_C0 = AES_IDS_ID1_A(game_code); + reg_AES_AES_ID_C1 = AES_IDS_ID1_B(game_code); + + // set dummy without seed[3] + reg_AES_AES_SEED_A0 = 1; + reg_AES_AES_SEED_A1 = 2; + reg_AES_AES_SEED_A2 = 3; + reg_AES_AES_SEED_B0 = 4; + reg_AES_AES_SEED_B1 = 5; + reg_AES_AES_SEED_B2 = 6; + reg_AES_AES_SEED_C0 = 7; + reg_AES_AES_SEED_C1 = 8; + reg_AES_AES_SEED_C2 = 9; + reg_AES_AES_SEED_D0 = 10; + reg_AES_AES_SEED_D1 = 11; + reg_AES_AES_SEED_D2 = 12; + + reg_AES_AES_KEY_A0 = 1; + reg_AES_AES_KEY_A1 = 2; + reg_AES_AES_KEY_A2 = 3; + reg_AES_AES_KEY_A3 = 3; + reg_AES_AES_KEY_B0 = 4; + reg_AES_AES_KEY_B1 = 5; + reg_AES_AES_KEY_B2 = 6; + reg_AES_AES_KEY_B3 = 6; + reg_AES_AES_KEY_C0 = 7; + reg_AES_AES_KEY_C1 = 8; + reg_AES_AES_KEY_C2 = 9; + reg_AES_AES_KEY_C3 = 9; + reg_AES_AES_KEY_D0 = 10; + reg_AES_AES_KEY_D1 = 11; + reg_AES_AES_KEY_D2 = 12; + reg_AES_AES_KEY_D3 = 12; +} diff --git a/build/libraries/aes/ARM7/aes_util.c b/build/libraries/aes/ARM7/aes_util.c new file mode 100644 index 0000000..47e8298 --- /dev/null +++ b/build/libraries/aes/ARM7/aes_util.c @@ -0,0 +1,46 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - aes + File: aes_util.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +/*---------------------------------------------------------------------------* + Name: AESi_AddCounter + + Description: calculate updated counter + + Arguments: pCounter pointer to the counter at offset 0 + nums offset in blocks (AES_BLOCK_SIZE) + + Returns: None + *---------------------------------------------------------------------------*/ +void AESi_AddCounter(AESCounter* pCounter, u32 nums) +{ + u32 data = 0; + int i; + for (i = 0; i < 16; i++) + { + data += pCounter->bytes[i] + (nums & 0xFF); + pCounter->bytes[i] = (u8)(data & 0xFF); + data >>= 8; + nums >>= 8; + if ( !data && !nums ) + { + break; + } + } +} + diff --git a/build/libraries/aes/Makefile b/build/libraries/aes/Makefile new file mode 100644 index 0000000..6f81501 --- /dev/null +++ b/build/libraries/aes/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - aes +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM7 + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/fatfs/ARM7/Makefile b/build/libraries/fatfs/ARM7/Makefile new file mode 100644 index 0000000..16ea02f --- /dev/null +++ b/build/libraries/fatfs/ARM7/Makefile @@ -0,0 +1,65 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - fatfs +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +SUBMAKES = + + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +# Codegen for sub processer +FIRM_PROC = ARM7 + +INCDIR = \ + $(TWLSDK_ROOT)/build/libraries/fatfs/ARM7.TWL/include \ + $(TWLSDK_ROOT)/build/libraries/fatfs/ARM7.TWL/include/twl/fatfs/ARM7 + +SRCDIR = src + +SRCS = \ + fatfs_loader.c \ + fatfs_firm.c \ + + +TARGET_LIB = libfatfs_sp$(FIRM_LIBSUFFIX).a + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/fatfs/ARM7/src/fatfs_firm.c b/build/libraries/fatfs/ARM7/src/fatfs_firm.c new file mode 100644 index 0000000..11fcbd1 --- /dev/null +++ b/build/libraries/fatfs/ARM7/src/fatfs_firm.c @@ -0,0 +1,506 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - fatfs + File: fatfs_firm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +#include +#include +#include +#include +#include +#include + +extern u32 NAND_FAT_PARTITION_COUNT; + +#define DMA_PIPE 2 +#define DMA_RECV 3 + +/* + pSD֐ +*/ +extern volatile SDMC_ERR_CODE SDCARD_ErrStatus; +extern s16 SDCARD_SDHCFlag; /* SDHCJ[htO */ +extern SDPortContext* SDNandContext; /* NANDp[^ */ + +/*---------------------------------------------------------------------------* + Name: WaitFifoFull + + Description: waiting to fill the SD FIFO + + SDJ[h̓ǂݍ݃f[^FIFOǂݍ߂ԂɂȂ܂ + Xg[܂B + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static inline void WaitFifoFull( void ) +{ + while( (*SDIF_CNT & SDIF_CNT_FULL) == 0 ) + { + if ( SDCARD_ErrStatus != SDMC_NORMAL ) // an error was occurred + { + break; + } + } +} + +/*---------------------------------------------------------------------------* + Name: StartToRead + + Description: start to read from SD I/F + + SDJ[h̓ǂݍ݂̊Jns܂B + + Arguments: block begining sector to transfer + count number of setctors to transfer + + Returns: None + *---------------------------------------------------------------------------*/ +static void StartToRead(u32 block, u32 count) +{ + *SDIF_FSC = count; + *SDIF_FDS = SECTOR_SIZE; + *SDIF_CNT = (*SDIF_CNT & ~(SDIF_CNT_FEIE | SDIF_CNT_FFIE)) | SDIF_CNT_FCLR | SDIF_CNT_USEFIFO; + CC_EXT_MODE = CC_EXT_MODE_DMA; + + SDCARD_ErrStatus = SDMC_NORMAL; + SD_EnableClock(); + SD_EnableSeccnt(count); + if ( SDCARD_SDHCFlag ) + { + SD_MultiReadBlock( block ); + } + else + { + SD_MultiReadBlock( block * SECTOR_SIZE ); + } +} + +/*---------------------------------------------------------------------------* + Name: StopToRead + + Description: stop to read from SD I/F + + SDJ[h̓ǂݍ݂̊s܂B + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void StopToRead( void ) +{ + if( !SD_CheckFPGAReg( SD_STOP,SD_STOP_SEC_ENABLE ) ){ + SD_StopTransmission(); /* J[h]IFPGAɒʒmiCMD12sj */ + } + SD_TransEndFPGA(); /* ]I(荞݃}XN֎~ɖ߂) */ + SD_DisableClock(); /* NbN~ */ + + *SDIF_CNT = (*SDIF_CNT & ~SDIF_CNT_USEFIFO) | SDIF_CNT_FCLR; /* FIFOgptOOFF */ + CC_EXT_MODE = CC_EXT_MODE_PIO; /* PIO[h(DMA[hOFF) */ +} + +/* + FATFS-SDMC̊ԂAESgݍ + ꕔ̐ݒ́AFATFSI񂵂Đݒ肷邱ƂɂȂB +*/ + +#define AES_GET_CNT_BITS(regValue, name) \ + ((regValue) & (REG_AES_AES_CNT_##name##_MASK)) + +static BOOL useAES = FALSE; +static AESCounter aesCounter; + +/*---------------------------------------------------------------------------* + Name: FATFS_EnableAES + + Description: enable AES data path + + ɓǂݍރf[^AESÍĂ邱ƂAO + IO֐ɒʒm邽߂APIłB + + APIĂяoɓǂݍރf[^AES̏lw + Ă΁AȌ̃V[PVȌĂяoł̏l͎ + vZ܂B + _ANZXsꍇ́ÂтɂAPIĂяo + Kv܂B + + Arguments: counter initial counter value + + Returns: None + *---------------------------------------------------------------------------*/ +void FATFS_EnableAES( const AESCounter* pCounter ) +{ + useAES = TRUE; + aesCounter = *pCounter; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_DisableAES + + Description: bypass AES + + ɓǂݍރf[^AESÍĂȂƂAO + IO֐ɒʒm邽߂APIłB + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void FATFS_DisableAES( void ) +{ + useAES = FALSE; +} + +/*---------------------------------------------------------------------------* + Name: ReadNormal + + Description: normal read + + ʂNAND/SDJ[hǂݍ݂܂B + + 荞݋֎~Ԃōɓ삷dlɂȂĂ܂B + + Arguments: block: source sector number in NAND + dest: dest address (4 bytes alignment) + count: sectors to transfer + + Returns: 0 if success + *---------------------------------------------------------------------------*/ +static u16 ReadNormal(u32 block, void *dest, u16 count) +{ + MINDmaConfig config = + { + MI_NDMA_NO_INTERVAL, + MI_NDMA_INTERVAL_PS_1, + MI_NDMA_BWORD_128, + SECTOR_SIZE/4 + }; +// OS_TPrintf("ReadNormal(0x%X, 0x%08X, 0x%X) is calling.\n", block, dest, count); + MI_NDmaRecvExAsync_Dev( DMA_PIPE, SDIF_FI, dest, (u32)(count * SECTOR_SIZE), NULL, NULL, &config, MI_NDMA_TIMING_SD_1 ); + StartToRead( block, count ); + MI_WaitNDma( DMA_PIPE ); + StopToRead(); + + return SDCARD_ErrStatus; +} + +/*---------------------------------------------------------------------------* + Name: ReadAES + + Description: AES read + + AESȂNAND/SDJ[hǂݍ݂܂B + AEŠ̐ݒ͂炩ߍsĂKv܂B + AES̏l̐ݒ́AFATFS_EnableAES̈vZ܂B + + 荞݋֎~Ԃōɓ삷dlɂȂĂ܂B + + Arguments: block: source sector number in NAND + dest: dest address (4 bytes alignment) + count: sectors to transfer + + Returns: 0 if success + *---------------------------------------------------------------------------*/ +#define PIPE_SIZE 64 +static u16 ReadAES(u32 block, void *dest, u16 count) +{ + u32 offset = 0; // in bytes + +// OS_TPrintf("ReadAES(0x%X, 0x%08X, 0x%X) is calling.\n", block, dest, count); + MI_NDmaPipeAsync_SetUp( DMA_PIPE, (void*)SDIF_FI, (void*)REG_AES_IFIFO_ADDR, PIPE_SIZE, NULL, NULL ); + +/* + AES̃ZbgAbvoDMAݒ +*/ + AESi_Reset(); + AESi_Reset(); + AESi_DmaRecv( DMA_RECV, dest, (u32)(count * SECTOR_SIZE), NULL, NULL ); + AESi_SetCounter( &aesCounter ); + AESi_Run( AES_MODE_CTR, 0, (u32)(count * SECTOR_SIZE / AES_BLOCK_SIZE), NULL, NULL ); + + // update for next read + AESi_AddCounter( &aesCounter, (u32)(count * SECTOR_SIZE / AES_BLOCK_SIZE) ); + + StartToRead( block, count ); + if ( SDCARD_ErrStatus != SDMC_NORMAL ) + { + goto err; + } + + while ( count * SECTOR_SIZE > offset ) + { + while ( AES_GET_CNT_BITS( reg_AES_AES_CNT, IFIFO_CNT ) ) + { + } + if ( (offset & (SECTOR_SIZE-1)) == 0 ) + { + WaitFifoFull(); + if ( SDCARD_ErrStatus != SDMC_NORMAL ) + { + goto err; + } + } + MI_NDmaRestart( DMA_PIPE ); + offset += PIPE_SIZE; + } + MI_WaitNDma( DMA_PIPE ); + StopToRead(); + MI_WaitNDma( DMA_RECV ); + return SDCARD_ErrStatus; + +err: + MI_StopNDma( DMA_RECV ); + MI_StopNDma( DMA_PIPE ); + StopToRead(); + AESi_Reset(); + return SDCARD_ErrStatus; +} + +/*---------------------------------------------------------------------------* + Name: nandRtfsIoFirm + + Description: ʑw̃ZN^[h^Cgv󂯂 + + Readɑ΂Ă̂݁AƎ̊֐gphCoIO֐łB + AES̗L̔͒fЉɖ؂łB + (Ԃɘ_̈̓ǂݍ݂܂”\邩) + + Arguments: driveno : hCuԍ + block : JnubNԍ + buffer : + count : ubN + reading : [hvTRUE + + Returns: TRUE/FALSE + *---------------------------------------------------------------------------*/ +static BOOL nandRtfsIoFirm( int driveno, u32 block, void* buffer, u16 count, BOOL reading ) +{ + u16 result; +#pragma unused( driveno) + + sdmcSelect( (u16)SDMC_PORT_NAND); + + if( reading ) + { + result = useAES ? + ReadAES( block, buffer, count ) : + ReadNormal( block, buffer, count ); + } + else + { + SdmcResultInfo SdResult; + result = sdmcWriteFifo( buffer, count, block, NULL, &SdResult ); + } + + return result ? FALSE : TRUE; +} + +/*---------------------------------------------------------------------------* + Name: sdmcRtfsIoFirm + + Description: ʑw̃ZN^[h^Cgv󂯂 + + Readɑ΂Ă̂݁AƎ̊֐gphCoIO֐łB + + Arguments: driveno : hCuԍ + block : JnubNԍ + buffer : + count : ubN + reading : [hvTRUE + + Returns: TRUE/FALSE + *---------------------------------------------------------------------------*/ +static BOOL sdmcRtfsIoFirm( int driveno, u32 block, void* buffer, u16 count, BOOL reading ) +{ + u16 result; +#pragma unused( driveno) + + sdmcSelect( (u16)SDMC_PORT_CARD ); + + if( reading ) + { + result = useAES ? + ReadAES( block, buffer, count ) : + ReadNormal( block, buffer, count ); + } + else + { + SdmcResultInfo SdResult; + result = sdmcWriteFifo( buffer, count, block, NULL, &SdResult ); + } + + return result ? FALSE : TRUE; +} + +/*---------------------------------------------------------------------------* + Name: nandRtfsAttachFirm + + Description: sdmchCohCuɊ蓖Ă + + ƎIO֐gp悤ɏ܂B + + Arguments: driveno : hCuԍ + + Returns: + *---------------------------------------------------------------------------*/ +#define nandRtfsCtrl FATFSi_nandRtfsCtrl +extern int nandRtfsCtrl( int driveno, int opcode, void* pargs); +static BOOL nandRtfsAttachFirm( int driveno, int partition_no) +{ + BOOLEAN result; + DDRIVE pdr; + + pdr.dev_table_drive_io = nandRtfsIoFirm; + pdr.dev_table_perform_device_ioctl = nandRtfsCtrl; + pdr.register_file_address = (dword) 0; /* Not used */ + pdr.interrupt_number = 0; /* Not used */ + pdr.drive_flags = (DRIVE_FLAGS_VALID | DRIVE_FLAGS_PARTITIONED);//DRIVE_FLAGS_FAILSAFE; + pdr.partition_number = partition_no; /* Not used */ + pdr.pcmcia_slot_number = 0; /* Not used */ + pdr.controller_number = 0; + pdr.logical_unit_number = 0; + + switch( partition_no ) + { + case 0: + result = rtfs_attach( driveno, &pdr, "SD1p0" ); //\̂FSCuɃRs[ + break; + case 1: + result = rtfs_attach( driveno, &pdr, "SD1p1" ); //\̂FSCuɃRs[ + break; + case 2: + result = rtfs_attach( driveno, &pdr, "SD1p2" ); //\̂FSCuɃRs[ + break; + case 3: + result = rtfs_attach( driveno, &pdr, "SD1p3" ); //\̂FSCuɃRs[ + break; + default: + result = FALSE; + break; + } + + return result; +} + +/*---------------------------------------------------------------------------* + Name: sdmcRtfsAttachFirm + + Description: sdmchCohCuɊ蓖Ă + + ƎIO֐gp悤ɏ܂B + + Arguments: driveno : hCuԍ + + Returns: + *---------------------------------------------------------------------------*/ +#define sdmcRtfsCtrl FATFSi_sdmcRtfsCtrl +extern int sdmcRtfsCtrl( int driveno, int opcode, void* pargs); +static BOOL sdmcRtfsAttachFirm( int driveno) +{ + BOOLEAN result; + DDRIVE pdr; + + pdr.dev_table_drive_io = sdmcRtfsIoFirm; + pdr.dev_table_perform_device_ioctl = sdmcRtfsCtrl; + pdr.register_file_address = (dword) 0; /* Not used */ + pdr.interrupt_number = 0; /* Not used */ + pdr.drive_flags = 0;//DRIVE_FLAGS_FAILSAFE; + pdr.partition_number = 0; /* Not used */ + pdr.pcmcia_slot_number = 0; /* Not used */ + pdr.controller_number = 0; + pdr.logical_unit_number = 0; + + result = rtfs_attach( driveno, &pdr, "SD0" ); //\̂FSCuɃRs[ + + return result; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_InitFIRM + + Description: init file system + + FATFS܂B + WFATFS_Init̎gpȂȗĂ邾łB + ȑONANDReLXgcĂȂAԂ𒘂 + Zkł܂B + FATFSp̃q[v(OS_ARENA_MAIN_SUBPRIV̊֘Aƃq[v) + 炩ߊmۂĂĂB + + Arguments: nandContext context of nand driver's previous life + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_InitFIRM( void* nandContext ) +{ + /* RTFSCu */ + if( !FATFSi_rtfs_init() ) + { + return FALSE; + } + + /* NANDp[^̐ݒ */ + SDNandContext = (SDPortContext*)nandContext; + + /* SDhCo */ + if ( FATFSi_sdmcInit( SDMC_NOUSE_DMA ) != SDMC_NORMAL ) + { + return FALSE; + } + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_MountDriveFIRM + + Description: mount specified partition + + w肵foCX̎w肵p[eBVw肵hCu + }Eg܂BNAND܂SDJ[ĥݑΉĂ܂B + APIŃ}EgꍇAƎIO֐gp悤ɂȂ܂B + + Arguments: driveno drive number "A:" is 0 + media media type + partition_no pertition number + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_MountDriveFIRM( int driveno, FATFSMediaType media, int partition_no ) +{ + if ( media == FATFS_MEDIA_TYPE_NAND ) + { + // CAUTION!: ֐2ĂяoRɂ‚ėvmFB + if ( !nandRtfsAttachFirm( driveno, partition_no ) || nandRtfsAttachFirm( driveno, partition_no ) ) + { + return FALSE; + } + } + else + { + if ( partition_no ) // support only 0 + { + return FALSE; + } + // CAUTION!: ֐2ĂяoRɂ‚ėvmFB + if ( !sdmcRtfsAttachFirm( driveno ) || sdmcRtfsAttachFirm( driveno ) ) + { + return FALSE; + } + } + return TRUE; +} diff --git a/build/libraries/fatfs/ARM7/src/fatfs_loader.c b/build/libraries/fatfs/ARM7/src/fatfs_loader.c new file mode 100644 index 0000000..03ee058 --- /dev/null +++ b/build/libraries/fatfs/ARM7/src/fatfs_loader.c @@ -0,0 +1,491 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - fatfs + File: fatfs_loader.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +#include +#include +#include +#include + +/* + PROFILE_ENABLE `Ƃx̃ptH[}X`FbNł܂B + p邽߂ɂ́Amain.cǂɁAu32 profile[256]; u32 pf_cnt; + `Kv܂B +*/ +//#define PROFILE_ENABLE + +#define MODULE_ALIGNMENT 0x10 // 16oCgPʂœǂݍ +//#define MODULE_ALIGNMENT 0x200 // 512oCgPʂœǂݍ +#define RoundUpModuleSize(value) (((value) + MODULE_ALIGNMENT - 1) & -MODULE_ALIGNMENT) + +#ifdef SDK_FINALROM // FINALROMŖ +#undef PROFILE_ENABLE +#endif + +#ifdef PROFILE_ENABLE +#define PROFILE_PXI_SEND 0x10000000 +#define PROFILE_PXI_RECV 0x20000000 +extern u32 profile[]; +extern u32 pf_cnt; +#endif + + +#define PXI_FIFO_TAG_DATA PXI_FIFO_TAG_USER_0 + +static ROM_Header* const rh= (ROM_Header*)HW_TWL_ROM_HEADER_BUF; +static int menu_fd = -1; + +/*---------------------------------------------------------------------------* + Name: FATFS_OpenRecentMenu + + Description: open recent menu file + VXej[̃t@C肵AI[vAt@CID + menu_fdɃZbg܂B + ŏIIɂ́AŒ̃^Cg^f[^ǂݍ݁AeTicket̏ + āAVXej[̃t@C肷邱ƂɂȂ\B + + Arguments: driveno drive number ('A' is 0) + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_OpenRecentMenu( int driveno ) +{ + char *menufile = (char*)L"A:\\ipl\\menu.srl"; + if (driveno < 0 || driveno >= 26) + { + return FALSE; + } + menufile[0] += (char)driveno; + menu_fd = po_open((u8*)menufile, PO_BINARY, 0); + if (menu_fd < 0) + { + return FALSE; + } + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_OpenSpecifiedSrl + + Description: open specified menu file + + Cӂ̃t@CI[vAt@CIDmenu_fdɃZbg܂B + + Arguments: menufile target filename + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_OpenSpecifiedSrl( const char* menufile ) +{ + menu_fd = po_open((u8*)menufile, PO_BINARY, 0); + if (menu_fd < 0) + { + return FALSE; + } + return TRUE; +} + +#define HEADER_SIZE 0x1000 +#define AUTH_SIZE ROM_HEADER_SIGN_TARGET_SIZE + +/*---------------------------------------------------------------------------* + Name: FATFS_LoadBuffer + + Description: load data and pass to ARM9 via WRAM[B] + + LoadBufferJjYŁAFAT̃t@C̓eARM9ɓ]܂B + + [LoadBufferJjY] + WRAM[B]𗘗pāAARM7,ARM9Ԃ̃f[^]s܂B + WRAM[B]̊eXbgoPc[œn܂B + 1Xbg̃f[^܂͑Sf[^i[łƂAARM9 + FIRM_PXI_ID_LOAD_PIRIOD𑗐M܂B + f[^cꍇ͎̃Xbg̏Ɉڂ܂B + 2ڈȍ~̌Ăяoł́AOŌ̃Xbg̑gp܂B + gpXbgARM9Ɋ蓖ĂĂƂ́AARM7 + Ȃ܂ŃXg[܂B + + [gp] + WRAM[B]bNAԂƂARM7ɓ|ĂƁB + + [ӓ_] + offsetsizeARM9ɒʒm܂Bʂ̌oHœĂB + SRLt@Cǂݍޏꍇ́A݂ROMwb_QƂłΏ\łB + (ROMwb_͌mĂ͂) + + ⑫: + ł́A郉CuARM7/ARM9ŕ킹邱Ƃ + OɂĂ邪AėpIɂɂ(ƗCuȂ)A + MŃXbg𔼕‚ƂAꂼɎMPXIR[obN + XbhpӂAMAPIf[^WRAMɊi[A + destsizeʒmƂ`OKł͂ȂH + (ŊԎԂ) + + Arguments: offset offset of the file to load (512 bytes alignment) + size size to load + + Returns: None + *---------------------------------------------------------------------------*/ +static BOOL FATFS_LoadBuffer(u32 offset, u32 size) +{ + u8* base = (u8*)HW_FIRM_LOAD_BUFFER_BASE; + static int count = 0; + + // seek first +// OS_TPrintf("po_lseek(offset=%X);\n", offset); + if (po_lseek(menu_fd, (s32)offset, PSEEK_SET) < 0) + { + return FALSE; + } +#ifdef PROFILE_ENABLE + // x2: after Seek + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + // loading loop + while (size > 0) + { + u8* dest = base + count * HW_FIRM_LOAD_BUFFER_UNIT_SIZE; // target buffer address + u32 unit = size < HW_FIRM_LOAD_BUFFER_UNIT_SIZE ? size : HW_FIRM_LOAD_BUFFER_UNIT_SIZE; // size + while (MI_GetWramBankMaster_B(count) != MI_WRAM_ARM7) // waiting to be master + { + } +#ifdef PROFILE_ENABLE + // x3...: after to wait ARM9 + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif +// OS_TPrintf("po_read(dest=%X, unit=%X);\n", dest, unit); + if (po_read(menu_fd, (u8*)dest, (int)unit) < 0) // reading + { + return FALSE; + } +#ifdef PROFILE_ENABLE + // x4...: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + profile[pf_cnt++] = (u32)PROFILE_PXI_SEND | FIRM_PXI_ID_LOAD_PIRIOD; // checkpoint +#endif + PXI_NotifyID( FIRM_PXI_ID_LOAD_PIRIOD ); + count = (count + 1) % HW_FIRM_LOAD_BUFFER_UNIT_NUMS; + size -= unit; + } + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_LoadHeader + + Description: load header + + SRLROMwb_ǂݍ݁AARM9ɓn܂B + MOɁAARM9 FIRM_PXI_ID_LOAD_HEADER 𑗐M܂B + MAARM9 FIRM_PXI_ID_AUTH_HEADER M܂B + ̎_ŁAC̏̈ʒuROMwb_i[ꂽ + z肵܂B + Ȃ΁Aseedf[^16oCgM܂B + 󂯎seedSeedAKeyCɐݒ肳܂B + makerom.TWL܂IPL̎dlɈˑ܂B + + Arguments: None + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL FATFS_LoadHeader( void ) +{ + // open the file in FATFS_InitFIRM() + if (menu_fd < 0) + { + return FALSE; + } + +#ifdef PROFILE_ENABLE + // 10: before PXI + pf_cnt = 0x10; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + profile[pf_cnt++] = (u32)PROFILE_PXI_SEND | FIRM_PXI_ID_LOAD_HEADER; // checkpoint +#endif + // load header without AES + PXI_NotifyID( FIRM_PXI_ID_LOAD_HEADER ); + FATFS_DisableAES(); + if (!FATFS_LoadBuffer(0, AUTH_SIZE) || +#ifdef PROFILE_ENABLE + // 12: after to load half + ((profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick())), FALSE) || +#endif + !FATFS_LoadBuffer(AUTH_SIZE, HEADER_SIZE - AUTH_SIZE) || +#ifdef PROFILE_ENABLE + // 1x: after to load remain + ((profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick())), FALSE) || +#endif + PXI_RecvID() != FIRM_PXI_ID_AUTH_HEADER ) + { + return FALSE; + } +#ifdef PROFILE_ENABLE + // 1x: after PXI + profile[pf_cnt++] = (u32)PROFILE_PXI_RECV | FIRM_PXI_ID_AUTH_HEADER; // checkpoint + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + // set id depends on game_code and seed to use (or all?) + { + AESKeySeed seed; + AESi_InitGameKeys((u8*)rh->s.game_code); + PXI_RecvDataByFifo( PXI_FIFO_TAG_DATA, &seed, AES_BLOCK_SIZE ); + AESi_WaitKey(); + AESi_SetKeySeedA(&seed); // APP + //AESi_WaitKey(); + //AESi_SetKeySeedB(&seed); // APP & HARD + //AESi_WaitKey(); + //AESi_SetKeySeedC(&seed); // + //AESi_WaitKey(); + //AESi_SetKeySeedD(&seed); // HARD + AESi_WaitKey(); + AESi_SetKeyC(&seed); // Direct + } + + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: FATFSi_GetCounter + + Description: get counter + + offsetɑΉAES̃JE^lvZ܂B + makerom.TWL̃R[hɈˑ܂B + + Arguments: offset offset from head of ROM_Header + + Returns: counter + *---------------------------------------------------------------------------*/ +static AESCounter* FATFSi_GetCounter( u32 offset ) +{ + static AESCounter counter; + + MI_CpuCopy8( rh->s.main_static_digest, &counter, 16 ); + AESi_AddCounter( &counter, offset - rh->s.aes_target_rom_offset ); + return &counter; +} + +/*---------------------------------------------------------------------------* + Name: FATFSi_SetupAES + + Description: setup whiere to use AES + + AESÍꂽf[^ǂݍނ߂̃ZbgAbvs܂B + fatfs_sdmc.c̃hCogpĂ邱ƂƂȂ܂B + (TwlSDKWōsꍇ́A̎dlɍ킹ďCKvI) + + APIĂяoOɁAC̏̈ʒuROMwb_ + i[ĂKv܂B + + ̑IsĂ܂A̐ݒ͕ʂ̏ꏊōsĂ + Kv܂B + + ]͈͂AES̈܂ꍇ́AE܂ł̃TCY ( + ȃTCY) Ԃ܂B + makerom.TWL܂IPL̎gpɈˑ܂B + + Arguments: offset offset of region from head of ROM_Header + size size of region + + Returns: size to transfer once + *---------------------------------------------------------------------------*/ +static u32 FATFSi_SetupAES( u32 offset, u32 size ) +{ + u32 aes_offset = rh->s.aes_target_rom_offset; + u32 aes_end = aes_offset + RoundUpModuleSize(rh->s.aes_target_size); + u32 end = offset + RoundUpModuleSize(size); + if ( rh->s.enable_aes ) + { + if ( offset >= aes_offset && offset < aes_end ) + { + if ( end > aes_end ) + { + size = aes_end - offset; + } + AESi_WaitKey(); + if (rh->s.developer_encrypt) + { + AESi_LoadKey( AES_KEY_SLOT_C ); + } + else + { + AESi_LoadKey( AES_KEY_SLOT_A ); + } + FATFS_EnableAES( FATFSi_GetCounter( offset ) ); + } + else + { + if ( offset < aes_offset && offset + size > aes_offset ) + { + size = aes_offset - offset; + } + FATFS_DisableAES(); + } + } + else + { + FATFS_DisableAES(); + } + return size; +} + +/*---------------------------------------------------------------------------* + Name: FATFSi_LoadModule + + Description: transfer module to ARM9 via WRAM[B] + + FATFSi_LoadBuffeȑAPIłB + + AESE܂Ƃ2ɕ邾łB + + Arguments: offset offset from head of ROM_Header + size size to load + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +static /*inline*/ BOOL FATFSi_LoadModule(u32 offset, u32 size) +{ + size = RoundUpModuleSize( size ); // ACg + while ( size > 0 ) + { + u32 unit = FATFSi_SetupAES( offset, size ); // x̓]TCY + if ( !FATFS_LoadBuffer( offset, unit ) ) + { + return FALSE; + } + offset += unit; + size -= unit; + } + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_LoadStatic + + Description: load static binary + + ARM9/ARM7StaticLTD Staticǂݍ݂܂B + MOɁAARM9FIRM_PXI_ID_LOAD_*_STATIC𑗐M܂B + ḾAARM9FIRM_PXI_ID_AUTH_*_STATICM܂B + TCY0̏ꍇ́Ãp[gPXIʐMs܂B + + APIĂяoOɁAC̏̈ʒuROMwb_ + i[ĂKv܂B + + ARM9ƈقȂAfoCXˑ̃ACgCsĂ܂B + (TCŶ) + + Arguments: None + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL FATFS_LoadStatic( void ) +{ +#ifdef PROFILE_ENABLE + // 30: LoadStatic + pf_cnt = 0x30; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + profile[pf_cnt++] = (u32)PROFILE_PXI_SEND | FIRM_PXI_ID_LOAD_STATIC; // checkpoint +#endif + PXI_NotifyID( FIRM_PXI_ID_LOAD_STATIC ); + + // load ARM9 static region without AES + if ( rh->s.main_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 31: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !FATFSi_LoadModule( rh->s.main_rom_offset, rh->s.main_size ) ) + { + return FALSE; + } + } + // load ARM7 static region without AES + if ( rh->s.sub_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 50: before PXI + pf_cnt = 0x50; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !FATFSi_LoadModule( rh->s.sub_rom_offset, rh->s.sub_size ) ) + { + return FALSE; + } + } + // load ARM9 extended static region with AES + if ( rh->s.main_ltd_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 70: before PXI + pf_cnt = 0x70; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !FATFSi_LoadModule( rh->s.main_ltd_rom_offset, rh->s.main_ltd_size ) ) + { + return FALSE; + } + } + // load ARM7 extended static region with AES + if ( rh->s.sub_ltd_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 90: before PXI + pf_cnt = 0x90; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !FATFSi_LoadModule( rh->s.sub_ltd_rom_offset, rh->s.sub_ltd_size ) ) + { + return FALSE; + } + } + + // waiting result + if ( PXI_RecvID() != FIRM_PXI_ID_AUTH_STATIC ) + { + return FALSE; + } +#ifdef PROFILE_ENABLE + // 9x: after PXI + profile[pf_cnt++] = (u32)PROFILE_PXI_RECV | FIRM_PXI_ID_AUTH_STATIC; // checkpoint + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: FATFS_Boot + + Description: boot + + ROMwb_̏ɁAOSi_BootĂяołB + + APIĂяoOɁAC̏̈ʒuROMwb_ + i[ĂKv܂B + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void FATFS_Boot( void ) +{ + OSi_Boot( rh->s.sub_entry_address, (MIHeader_WramRegs*)rh->s.main_wram_config_data ); +} diff --git a/build/libraries/fatfs/Makefile b/build/libraries/fatfs/Makefile new file mode 100644 index 0000000..a6aec45 --- /dev/null +++ b/build/libraries/fatfs/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - fatfs +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM7 + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/gcd/ARM7/Makefile b/build/libraries/gcd/ARM7/Makefile new file mode 100644 index 0000000..29f06b7 --- /dev/null +++ b/build/libraries/gcd/ARM7/Makefile @@ -0,0 +1,60 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= True + +FIRM_PROC = ARM7 + +SRCDIR = . ../common +SRCS = \ + gcd.c \ + gcd_init.c \ + blowfish.c \ + ds_blowfish.c \ + ds_blowfish_table.c \ + gcdfirm_blowfish_table.c \ + +TARGET_LIB = libgcd_sp$(FIRM_LIBSUFFIX).a +INCDIR = ../include + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/gcd/ARM9/Makefile b/build/libraries/gcd/ARM9/Makefile new file mode 100644 index 0000000..52cee61 --- /dev/null +++ b/build/libraries/gcd/ARM9/Makefile @@ -0,0 +1,65 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= True + + + +SRCDIR = . ../common +SRCS = \ + gcd.c \ + gcd_init.c \ + blowfish.c \ + ds_blowfish.c \ + ds_blowfish_table.c \ + gcdfirm_blowfish_table.c \ + +TARGET_LIB = libgcd$(FIRM_LIBSUFFIX).a +INCDIR = ../include + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +LDEPENDS_OBJ := $(MAKEFIRM_RSA_PUBKEY) \ + +gcd_acsign.c : $(LDEPENDS_OBJ) + touch gcd_acsign.c + +#===== End of Makefile ===== diff --git a/build/libraries/gcd/Makefile b/build/libraries/gcd/Makefile new file mode 100644 index 0000000..cd64988 --- /dev/null +++ b/build/libraries/gcd/Makefile @@ -0,0 +1,34 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - init +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Log: $ +# $NoKeywords: $ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 + +#ifdef TWL_WITH_ARM7 +SUBDIRS += ARM7 +#endif + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/gcd/common/blowfish.c b/build/libraries/gcd/common/blowfish.c new file mode 100644 index 0000000..60f8fb2 --- /dev/null +++ b/build/libraries/gcd/common/blowfish.c @@ -0,0 +1,149 @@ +/*---------------------------------------------------------------------------* + Project: TwlBrom - libraries - GCD + File: blowfish.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include + +#define MAXKEYBYTES 56 /* 448 bits */ +#define N 16 + + +static u32 F(const BLOWFISH_CTX *ctx, u32 x); + +void InitBlowfish(BLOWFISH_CTX *ctx, const unsigned char *key, int keyLen) +{ + int i, j, k; + u32 data, datal, datar; + + j = 0; + for (i = 0; i < N + 2; ++i) { + data = 0x00000000; + for (k = 0; k < 4; ++k) { + data = (data << 8) | key[j]; + j = j + 1; + if (j >= keyLen) + j = 0; + } + ctx->P[i] = ctx->P[i] ^ data; + } + + datal = 0x00000000; + datar = 0x00000000; + + for (i = 0; i < N + 2; i += 2) { + EncryptByBlowfish(ctx, &datal, &datar); + ctx->P[i] = datal; + ctx->P[i + 1] = datar; + } + + for (i = 0; i < 4; ++i) { + for (j = 0; j < 256; j += 2) { + EncryptByBlowfish(ctx, &datal, &datar); + ctx->S[i][j] = datal; + ctx->S[i][j + 1] = datar; + } + } + +} + + +void EncryptByBlowfish(const BLOWFISH_CTX *ctx, u32 *xl, u32 *xr) +{ + u32 Xl; + u32 Xr; + u32 temp; + int i; + + Xl = *xl; + Xr = *xr; + + for (i = 0; i < N; ++i) { + Xl = Xl ^ ctx->P[i]; + Xr = F(ctx, Xl) ^ Xr; + + temp = Xl; + + Xl = Xr; + Xr = temp; + } + + temp = Xl; + Xl = Xr; + Xr = temp; + + Xr = Xr ^ ctx->P[N]; + Xl = Xl ^ ctx->P[N + 1]; + + *xl = Xl; + *xr = Xr; +} + +void DecryptByBlowfish(const BLOWFISH_CTX *ctx, u32 *xl, u32 *xr) +{ + u32 Xl; + u32 Xr; + u32 temp; + int i; + + + Xl = *xl; + Xr = *xr; + + for (i = N + 1; i > 1; --i) { + Xl = Xl ^ ctx->P[i]; + Xr = F(ctx, Xl) ^ Xr; + + /* Exchange Xl and Xr */ + temp = Xl; + Xl = Xr; + Xr = temp; + } + + /* Exchange Xl and Xr */ + temp = Xl; + Xl = Xr; + Xr = temp; + + Xr = Xr ^ ctx->P[1]; + Xl = Xl ^ ctx->P[0]; + + *xl = Xl; + *xr = Xr; +} + + +static u32 F(const BLOWFISH_CTX *ctx, u32 x) { + u32 a, b, c, d; + u32 y; + + d = x & 0x00FF; + x >>= 8; + + c = x & 0x00FF; + x >>= 8; + + b = x & 0x00FF; + x >>= 8; + + a = x & 0x00FF; + + y = ctx->S[0][a] + ctx->S[1][b]; + + y = y ^ ctx->S[2][c]; + y = y + ctx->S[3][d]; + + return y; +} + + diff --git a/build/libraries/gcd/common/ds_blowfish.c b/build/libraries/gcd/common/ds_blowfish.c new file mode 100644 index 0000000..1a6b3bd --- /dev/null +++ b/build/libraries/gcd/common/ds_blowfish.c @@ -0,0 +1,186 @@ +/*---------------------------------------------------------------------------* + Project: TwlBrom - libraries - GCD + File: ds_blowfish.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include + + +#ifdef PRINT_DEBUG +#define DBG_PRINTF vlink_dos_printf +#define DBG_CHAR vlink_dos_put_console +#else +#define DBG_PRINTF( ... ) ((void)0) +#define DBG_CHAR( c ) ((void)0) +#endif + +static void my_memcopy(void *src, void *dst, int size); + + +// DS + +static char *normal_mode_key ATTRIBUTE_ALIGN(4) = "NmMdOnly"; +static char *png_off_key ATTRIBUTE_ALIGN(4) = "enPngOFF"; +static char *encrypt_object_key ATTRIBUTE_ALIGN(4) = "encryObj"; + +extern GCDSharedWork GCDi_SharedWork[2]; +extern GCDSecureWork GCDi_SecureWork[2]; + +static void GCDi_InitBlowfishKeyAndTableDS(BLOWFISH_CTX *ctx, u32 *keyBufp, s32 keyLen) +{ + EncryptByBlowfish(ctx, &(keyBufp)[2], &(keyBufp)[1]); + EncryptByBlowfish(ctx, &(keyBufp)[1], &(keyBufp)[0]); + InitBlowfish(ctx, (u8 *)keyBufp, keyLen); +} + +static void GCDi_MakeBlowfishTableDS(GCDSlot slot, BLOWFISH_CTX *tableBufp, const u32 *keyp, u32 *keyBufp, s32 keyLen) +{ + const BLOWFISH_CTX *blowfishInitTablep = &GCDi_BlowfishInitTableDS; + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + u32 *blowfishedKeyp; + + MI_CpuCopy32((void *)blowfishInitTablep, (void *)tableBufp, sizeof(BLOWFISH_CTX)); + + keyBufp[0] = *keyp; + keyBufp[1] = (*keyp >> 1); + keyBufp[2] = (*keyp << 1); + + GCDi_InitBlowfishKeyAndTableDS(tableBufp, keyBufp, keyLen); + + *(u64 *)sec->cardNormalModeKey = *(u64 *)rh->l.romNormalModeKey; + blowfishedKeyp = sec->cardNormalModeKey; + + DecryptByBlowfish(tableBufp, &(blowfishedKeyp)[1], &(blowfishedKeyp)[0]); + + if (keyLen > 8) { + sec->isGenUnScrambleKey = 1; + } + GCDi_InitBlowfishKeyAndTableDS(tableBufp, keyBufp, keyLen); +} + +void GCDi_InitCardOpBlowfishDS( GCDSlot slot ) +{ + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + GCDi_MakeBlowfishTableDS(slot, &sec->blowfishCardTable, &rh->l.initialCode, sec->cardKeyBuf, 8); +} + +static void GCDi_ChangeObjectTableDS(GCDSlot slot, s32 keyLen) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + BLOWFISH_CTX *tableBufp = &sec->blowfishCardTable; + u32 *keyBufp = sec->cardKeyBuf; + + keyBufp[1] = (keyBufp[1] << 1); + keyBufp[2] = (keyBufp[2] >> 1); + GCDi_InitBlowfishKeyAndTableDS(tableBufp, keyBufp, keyLen); +} + + +#define UNDEF_CODE 0xe7ffdeff +#define ENCRYPT_DEF_SIZE 0x800 +/* ƂŖOς */ +#define ENC_DESTINATION_BUF_SIZE 0x4000 +static u32 encDestBuf[ENC_DESTINATION_BUF_SIZE/sizeof(u32)]; + +void GCDi_DecryptObjectFileDS( GCDSlot slot ) +{ + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + GCDSharedWork* sh = &GCDi_SharedWork[slot]; + BLOWFISH_CTX *tableBufp = &sec->blowfishCardTable; + u32 *encBufp = (u32 *)&sec->blowfishFlashTable; + u32 *encDestp = (u32 *)rh->l.arm9.ramAddr; + s32 size = sec->secureSize; + s32 restSize; + BOOL exist = TRUE; + int i; + + sec->enableReadSecure = 1; // SECURË惊[hECl[u + + encDestp = GCDi_SecureAreaBuf[slot]; + encBufp = encDestBuf; + + if (size > ENCRYPT_DEF_SIZE) { + size = ENCRYPT_DEF_SIZE; + } + restSize = size; + + if (sec->enableReadSecure) { + MI_CpuCopy32(encDestp, encBufp, (u32)size); + DBG_PRINTF("%s %d\n",__FUNCTION__,__LINE__); + DecryptByBlowfish(tableBufp, &(encBufp)[1], &(encBufp)[0]); + } + + GCDi_ChangeObjectTableDS( slot, 8 ); + + if (sec->enableReadSecure) { + DecryptByBlowfish(tableBufp, &(encBufp)[1], &(encBufp)[0]); + DBG_PRINTF("%s %d\n",__FUNCTION__,__LINE__); + +#if 1 + for ( i=0; i<8; i++ ) + { + if ( encrypt_object_key[i] != ((char*)encBufp)[i] ) + { + exist = FALSE; + break; + } + } + + // ÍIuWFNgL + if ( exist ) + { +#else + if ((encBufp[0] == encrypt_object_key[0]) // ÍIuWFNgL + && (encBufp[1] == encrypt_object_key[1])) { +#endif + u32 *bufp = encBufp; + + bufp[0] = UNDEF_CODE; + bufp[1] = UNDEF_CODE; + while ((restSize -= 8) > 0) { + bufp += 2; // + DecryptByBlowfish(tableBufp, &(bufp)[1], &(bufp)[0]); + } + DBG_PRINTF("SUCCESS %s %d\n",__FUNCTION__,__LINE__); + } + else { + DBG_PRINTF("ERROR %s %d\n",__FUNCTION__,__LINE__); + // CpuClearFast32(UNDEF_CODE, encBufp, size); // `R[hŃNA + sh->disableEncryptedCardData = 1; // ÍIuWFNg ʒm + } + MI_CpuCopy32(encBufp, encDestp, (u32)size); + DBG_PRINTF("%s %d\n",__FUNCTION__,__LINE__); + } +} + + +/*************************************************** + + utility functions + + ***************************************************/ +static void my_memcopy(void *src, void *dst, int size) +{ + u8 *s,*d; + int i; + s = (u8 *)src; + d = (u8 *)dst; + for( i = 0 ; i < size ; i++ ) { + *d++ = *s++; + } +} + diff --git a/build/libraries/gcd/common/ds_blowfish_table.c b/build/libraries/gcd/common/ds_blowfish_table.c new file mode 100644 index 0000000..2ab70da --- /dev/null +++ b/build/libraries/gcd/common/ds_blowfish_table.c @@ -0,0 +1,286 @@ +/*---------------------------------------------------------------------------* + Project: TwlBrom - libraries - GCD + File: ds_blowfish_table.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include + + +const BLOWFISH_CTX GCDi_BlowfishInitTableDS = { + 0x5f20d599, 0xb9f54457, 0xd9a4196e, 0x945a6a9e, + 0xebf1aed8, 0x3ae27541, 0x32d08293, 0xd531ee33, + 0x9a6157cc, 0x1ba20637, 0xf5723979, 0xbef6ae55, + 0xfb691b5f, 0xe9f19de5, 0xa1d92cce, 0xe605325e, + 0xcffed3fe, 0x0d0462d4 , + + 0xb7ecf58b, 0xbb79602b, 0x0d319512, 0x2bda3f6e, + 0xf1f08488, 0x257e123d, 0xbbf12245, 0x061a0624, + 0x28dfad11, 0x3481648b, 0x2933eb2b, 0xbdf2aa99, + 0x9d95149c, 0x8cf5f79f, 0x29a19772, 0xcf5fd19d, + 0x1a074d66, 0x4b4ad3de, 0xa3a7c985, 0x3a059517, + 0xbf0a493d, 0xa28b890a, 0xdd49824a, 0x0bf19027, + 0x6a1cebe9, 0x05457683, 0x617081ba, 0xde4b3f17, + 0x39abcfae, 0x563af257, 0x8aad1148, 0x3f45e140, + 0x54029bfa, 0xfb93a6ca, 0x6ffe4def, 0x9c87d8a3, + 0x48d5ba08, 0xfd2d8d6a, 0x74f8156e, 0x8b52bebd, + 0x9e8a2218, 0x073774fb, 0x4a6c361b, 0x6242ba19, + 0x109179b9, 0x9665677b, 0xe82302fe, 0x778c99ee, + 0x64865c3e, 0x86786d4d, 0xe2654fa5, 0x5adfb21e, + 0x087ed00a, 0xac71b014, 0x1c83dbbd, 0x62a1d7b9, + 0x7c63c6cd, 0xe6c36952, 0x12ce75bf, 0x04215d44, + 0x3cd3fbfa, 0xd4631138, 0x49418595, 0x08f20946, + 0x1fdc1143, 0x6d15c076, 0x70633c1f, 0x6c8087ea, + 0x8b63bdc3, 0x372137c2, 0x2309eedc, 0x4d6a372e, + 0x50f79073, 0x921cac30, 0x91231004, 0xaa07d24f, + 0x9a4f3e68, 0x6a6064c9, 0xf32114c8, 0x124122d6, + 0xe6cf2444, 0x0ddd568a, 0x85e14d53, 0x5a528c1e, + 0xc284199c, 0x6ff15703, 0x58be00e3, 0xd5ed4cf6, + 0x1f9c6421, 0x3c0355be, 0xaaffdc4a, 0x5de0dac9, + 0xdee6bf5e, 0xf8b1d8f5, 0xb9b336ff, 0xdb956762, + 0xed375f31, 0x9967704c, 0x3118b590, 0x99993d6c, + 0xd3da42e4, 0xa0134225, 0x6c70d7ae, 0xc7cf55b1, + 0x43d546d7, 0x443d1761, 0x8533e928, 0x93a2d0d5, + 0x1f1225aa, 0x460bc5fb, 0x567697f5, 0x87bea645, + 0xe86b94b1, 0x9933feb1, 0x6c3e1fae, 0x091d7139, + 0xe4379000, 0x74753e10, 0x3b838cff, 0xf9b0f1b0, + 0x42470501, 0xacd6f195, 0x9ee6387e, 0x3f267495, + 0x185068b4, 0xb43043d0, 0x68e34b4c, 0xb64de5bf, + 0xa00a8b95, 0x77322574, 0x2cf7a1cf, 0x5a1371d8, + 0x51c9eaab, 0xefee0de8, 0x197e93e9, 0x38431ea7, + 0xa12c1681, 0xcc73e348, 0xd36c2129, 0xd9a0ce5d, + 0xa0437161, 0x64b51315, 0x192acf92, 0xa5b7addc, + 0xf865869f, 0xfbe79f1a, 0x13b8fdf7, 0x6fdb276c, + 0xf71c35df, 0x9b5b2c8d, 0x6438ab12, 0x31decc06, + 0x11754ee8, 0xeafae364, 0xc25434eb, 0xeb343fad, + 0x267d2c93, 0xf3569d36, 0xb3f6e15a, 0x9e4a6398, + 0x9ae48332, 0x907d6084, 0xee0e132e, 0xa2364b93, + 0x3816ec85, 0x020688e8, 0x3aa0f0bf, 0x9a6ad7ed, + 0xcf57e173, 0xdcb844f8, 0xd159232e, 0x715295df, + 0x4ba06199, 0x786e7fd5, 0x30c5a9ba, 0x328640d3, + 0x9c0c329d, 0x2f02b737, 0xa99854ba, 0xc90413c4, + 0xe7c8be8d, 0x2e50975d, 0x5922d693, 0x22bc270c, + 0x20a7e092, 0x7f6f930f, 0xb5d39f4c, 0x740b2aa6, + 0x107d4967, 0xc5d1cb26, 0x8ce77186, 0x5be99ca0, + 0x01f61ab2, 0x5e9e8cee, 0xdb1af283, 0x84eae5e6, + 0x7cd27659, 0x49a58df6, 0x16c24836, 0xa383bb52, + 0x0c07b974, 0x2861ff3b, 0xe4e961e1, 0xaa156eef, + 0x5de8ba4e, 0x32bb9605, 0x72fbb056, 0xc80e0f52, + 0x76652542, 0xdef2af89, 0x01f02710, 0x97a7744b, + 0x5426d507, 0x821f0954, 0x307d860a, 0x26b30e39, + 0xbb570b9b, 0xaf310636, 0xd9fc79fd, 0x0c2b1030, + 0xd79be1b3, 0xef5fdc7b, 0x4513f8d2, 0xbd75474d, + 0x7e3c9646, 0xb53ef375, 0x3b9ac567, 0x6b295bb0, + 0xc85b80de, 0x31b10515, 0xdd49ceb6, 0xaeb584ad, + 0x3167dc60, 0x4efe3034, 0xa62f80bd, 0x213963bf, + 0x7f35d986, 0x05226816, 0x2690e954, 0x516c078c, + 0xd75531a4, 0x3ea80709, 0xc166532e, 0xc47bf2f8, + 0xf1cf58f2, 0xe7a2c587, 0x87308f27, 0x6264a058, + 0x88b91823, 0xc4cefa7c, 0x17adae98, 0xf35b4acc, + 0x56d548e9, 0xc8f20dd3, 0xdb8c7392, 0xac562fd7, + + 0x6992f981, 0xf632c64d, 0x218dc0e6, 0x618076e2, + 0x6cdcbc11, 0x6919af93, 0xb9bfd09b, 0x67029f31, + 0x83ee51a3, 0x0c7b2206, 0x404249ab, 0x7d01d5b8, + 0x55f75ece, 0x99c53953, 0x9f87d846, 0xb464f7ba, + 0xa1fa9ae3, 0x1068906d, 0x548aca30, 0xc3609fa7, + 0x0d6bf519, 0xe698517a, 0xb4514398, 0x4fe935d6, + 0x7b0fdfc3, 0xbd5c2fd6, 0x1961153a, 0xaacb4bf1, + 0xc9646ddc, 0x561ec6d3, 0x504c38ef, 0xcc758671, + 0xe94e0d0d, 0x5d06f628, 0xd3aa1b70, 0x39a8cf45, + 0x2ea695ac, 0xd422e4b4, 0x5f37a874, 0xcc047a48, + 0xd8404ca5, 0x0828b428, 0x52721c0d, 0x477df041, + 0x4e533a19, 0x6b628458, 0x818ab593, 0xdc0d4e21, + 0xc6a23fb4, 0x402bc9fc, 0xe90438da, 0x6b865a5e, + 0x8525220c, 0x7c8d1168, 0x55951d92, 0xbb8eab4d, + 0xb7e6a6da, 0x5a32b651, 0x05dd4105, 0x50560a2a, + 0xcc471791, 0xb57ee6c9, 0x73db4a61, 0x33c85167, + 0x746edaf5, 0x37c3542e, 0x08af6d0d, 0x5f8a15e8, + 0xcd2159e2, 0x060cdea8, 0x5f6b775a, 0x3e6518db, + 0x78de50c8, 0xb382b8e0, 0x32724e5d, 0x34c14f07, + 0xb796ba23, 0x28a44e67, 0xeb62341e, 0xe9706a2d, + 0x70c4422f, 0x9c315a4e, 0x28475bf9, 0x6f71daaa, + 0x78b31f38, 0x1c6b92c4, 0x9a35f69e, 0xbf0e4db7, + 0x412918cc, 0x5d354803, 0xc62bd055, 0x605caf29, + 0x5e8e6974, 0xbdd47c9b, 0x7d64447b, 0x695d923f, + 0x4b001fb6, 0xcf3583d4, 0x174e647e, 0x2ed58dae, + 0x4e12289a, 0x08492b2e, 0x46c6ae5c, 0x6141ae85, + 0xd2826f1e, 0x1f163751, 0xa459f60b, 0xaf5aca9a, + 0x8b33d40d, 0x84f16320, 0xcfcb5c80, 0xd3b9b408, + 0x62bd0516, 0x569b3183, 0xba9f9851, 0xb2aa5bb2, + 0xb52c6b22, 0x63fa48d4, 0xfa585f2b, 0x0964fa61, + 0xb8e038bb, 0xa860929d, 0x0e6f670d, 0x010df537, + 0xd477c29f, 0x73f1ecfe, 0x7de03930, 0xe49861f5, + 0x0455282c, 0x2fdb5556, 0x58e5ec6b, 0x8064b606, + 0x4e1a2a6a, 0xc4d80f5b, 0x19522e0a, 0x30f562d9, + 0x7b8cbe48, 0xa29b384f, 0xd3c9afc3, 0x4162c1c7, + 0x2161b986, 0x4f996f57, 0x7bcebac1, 0x5e4d3bb5, + 0x57448b8a, 0x705f135f, 0x47295b6d, 0xece238dc, + 0x12655504, 0x4317e82a, 0x2add8ee1, 0xf794e2b3, + 0xe65c6e09, 0x6df88aeb, 0x48544989, 0xbfad2ff5, + 0xca4b94ea, 0x828739fc, 0xf2018a5f, 0x71e6f275, + 0xde42d8d6, 0x281d2df1, 0xa37e88a6, 0x301d47a0, + 0xdf71a3d9, 0x01cb1c49, 0xf2b136f8, 0x5d5822f0, + 0xa0bd6b45, 0x4288b2bb, 0xce288cc7, 0x6390e893, + 0x897c9008, 0xb77df53c, 0x554f2d04, 0x7efd1651, + 0xc1bee879, 0xf8d412f2, 0x230584b4, 0x2bd2cca0, + 0xadabe1fd, 0x6c55d10d, 0x4d944123, 0x054f3777, + 0x17bf0c28, 0x6c6712b3, 0xf75ac38c, 0x6d2a8441, + 0x271294d0, 0x9cedb42c, 0x8247ec4d, 0xb967d597, + 0x55c09d1b, 0x8ee57e07, 0x3ee7a8e2, 0x3a0ee412, + 0x3455452a, 0x5a2df9a2, 0x7c52ab1b, 0x555f1083, + 0x435af1d2, 0xa4a7c62b, 0xe8951589, 0xf89d4bb4, + 0x609fe375, 0xe6d65b78, 0x21e6440d, 0x2247bd06, + 0xad00a453, 0x8513438d, 0xfcaaf739, 0xed7baf38, + 0x542be4fc, 0xfc4c9850, 0xdff78085, 0xe122803c, + 0x24deda94, 0x397ab0c6, 0xa10fdc38, 0x6ff9f4a7, + 0x8b571863, 0x2e2a4184, 0xd9f253d4, 0xddd00f00, + 0xa6196e99, 0x5becd00a, 0xc0ab2458, 0xec6506cb, + 0x9438131a, 0x2f03670a, 0x77e3f73f, 0xc6337744, + 0xe3d03914, 0x7908a2c0, 0x579940bb, 0x90010b41, + 0x48cce1cd, 0xafb3db67, 0x4cf37488, 0xb1728f82, + 0xc42923b5, 0xfc196c12, 0x9ca4468e, 0x876525c4, + 0x8abe6dd3, 0x38031193, 0xf32b83ed, 0xea93a446, + 0x1d85533b, 0x08f1d4ce, 0xfced2783, 0xbc181a9b, + 0xdcae8bf9, 0x3850ab24, 0x104b72e9, 0x467b1722, + + 0x6459ab5d, 0xf8ae40f3, 0xf9c8e5bb, 0x554e0326, + 0xfeebeb7d, 0xe0e639f7, 0x2ebe110a, 0xed98ff28, + 0x5642c9c0, 0x00fdc342, 0xa287aff6, 0x323f015b, + 0x9a954792, 0x3d32a572, 0x9bd06bae, 0x9249d207, + 0xfa4a78e3, 0xf27d06a1, 0x7477cf41, 0x0cb21404, + 0x16648486, 0xa151bbd5, 0xd1f16fe5, 0x5ff7e2f2, + 0xb84d2058, 0xddcfc757, 0x76bed8c5, 0x7e5ff63d, + 0x888b2ae7, 0x3f381b24, 0x7723410e, 0xd44bf0f5, + 0xa4fa1f0c, 0xcf5f800b, 0xdae0f645, 0x5359342f, + 0x523c20fb, 0xb5355e62, 0x608bfe62, 0x5a86e363, + 0xd16e1a15, 0x32bc4547, 0x3867ebb4, 0x336ee4ab, + 0xa3edb53a, 0x4ee067ad, 0x62ee9541, 0x1d267162, + 0x3062ef31, 0xac82d7af, 0x0405dcc2, 0xbf0797f5, + 0x07235911, 0xe80264c0, 0xaf3ee597, 0xa659ac18, + 0x90334a8b, 0x9c7c6e1c, 0x3c4c7e20, 0xbb64613e, + 0x7e7c6bc5, 0x4cc59f3e, 0xf573ea9f, 0x4cc089d7, + 0x2df4fbf4, 0x511b14ec, 0xc812c1d5, 0x4a0bdf10, + 0x93bc9c8b, 0x3e3e6a45, 0xbaa9c17d, 0x07b4c1cd, + 0x8668e1e4, 0x386db243, 0x5c0cfbf3, 0xde713766, + 0xa06eef56, 0xa7654010, 0xbed0f798, 0x3637c80e, + 0x7cca10ec, 0x1e84ab9c, 0x02761705, 0xaa524f1c, + 0xa0c6c15f, 0x04d8b956, 0xa74d4484, 0x60ded859, + 0x050e38e6, 0x3be1038f, 0x3304816d, 0xce0b306f, + 0x33210569, 0x89bb26fb, 0x87aeb67d, 0xe007517e, + 0x0a96f7ac, 0x5cc4f96b, 0x4744e41d, 0xe3fa5eb8, + 0x42558478, 0xf75e484b, 0x8635477d, 0x05432b1d, + 0xb88aec03, 0x763c061e, 0x431a480c, 0xed8ab7a7, + 0x43c6131e, 0xdbef10ee, 0x833cfbec, 0xef4495b2, + 0x4e5154d8, 0x1d44112d, 0x1e5936fb, 0xc3c1347a, + 0x610057ca, 0x16a567ea, 0x55d0559b, 0x36d97fe1, + 0xae7640d2, 0xb0ce01dc, 0xcbd5837a, 0x6bec9820, + 0x349272c1, 0x375782f3, 0x36328a62, 0xae43900c, + 0x789b5cae, 0x0265138e, 0xc17168fd, 0xa031b0fe, + 0xc3b08224, 0xa76979b1, 0xd0ebd2f5, 0xdc32c082, + 0x3c26c79e, 0xc1988d6d, 0xd0d422bb, 0x3eec330f, + 0xdce1ccb9, 0x36774c6a, 0xbff91c14, 0x5f289f81, + 0x29328571, 0xc4487590, 0xd8ce4ab3, 0x2f148f44, + 0xef5740fd, 0xd97508aa, 0x6ed6d146, 0xc31f5532, + 0x1f84fe18, 0xffd584fc, 0x481b5e71, 0x0e9586c3, + 0xd3270828, 0x7b718338, 0x5463804c, 0xacb0569a, + 0x31ca80cf, 0xf3feef09, 0x7e24afbe, 0x3f53fea6, + 0x334a8dc2, 0xa622d168, 0xea7bad66, 0xb043b6de, + 0x009525a1, 0x46753fa3, 0xec441114, 0x92bc95d7, + 0x16a94ff0, 0x60976253, 0xf1410f2a, 0xeebe2471, + 0xcd087f94, 0x85b39360, 0x3f00075b, 0x83280fd8, + 0x9f69d19a, 0xc32edad1, 0xb9a20190, 0x662a4e6b, + 0xa6aeda9d, 0x68d32aea, 0x9c0c0c2f, 0xed4a8cd2, + 0x65579ee2, 0xa387099d, 0x5d32c4b4, 0x2b32d4c9, + 0x1e71e0b1, 0x90e64d64, 0x401ee371, 0x84f37ded, + 0x78c8ed0e, 0x71c0ae76, 0x05bb7227, 0xfb6402ea, + 0xb56b48f3, 0xed3f9342, 0xd253139f, 0xec2afef7, + 0xdb25471d, 0xc686913c, 0xfd11f08e, 0xf7367423, + 0x7a9ef5a4, 0x4450537e, 0xd3ca47d4, 0xe66d38eb, + 0x7f9471d9, 0x4b69c64a, 0xea52f411, 0xb08afe22, + 0x598b6736, 0x2a80e6e8, 0x130465eb, 0x9edcecee, + 0x05ecb15f, 0x9fe6596a, 0x896b595e, 0xca1af7bf, + 0x6a5bf944, 0xe4038571, 0x70e06229, 0xcfc4416f, + 0xe3ccb1b2, 0xa807a67e, 0x847fe787, 0x4b52db93, + 0xdd7eec6c, 0x104824d4, 0x60049f69, 0x1848e674, + 0xb92ce4f3, 0x7a502e4f, 0x6954d4df, 0xf3a78b2b, + 0xf31fffce, 0x3901263e, 0x89849517, 0x4b4cf0b0, + 0xc49f9182, 0xa59dac4b, 0x2517af74, 0xd332cac9, + 0x848a89bc, 0xae0dcc89, 0x9cdba27c, 0xee91786a, + 0x4e5d76ea, 0x69f56087, 0x02d46715, 0x3648afcf, + + 0x6fbfea07, 0x8f062d66, 0xf9fe9ac4, 0x758790f6, + 0x0fadf7b8, 0x3d5a1076, 0xb32eb059, 0xcc2c35c7, + 0xcb2b5670, 0xc59637e3, 0x8a1b462f, 0x88c74622, + 0x983226a7, 0x2286df61, 0x2f1cf48a, 0xaa09a187, + 0xd3aea9cc, 0x1c4500bd, 0x8687549a, 0xffef8752, + 0x8fa18f1e, 0x355c89c1, 0x3a2dda1b, 0xc2b2162c, + 0x78e256f1, 0x97636bc1, 0xc98f56c5, 0xaa2c7f32, + 0xaca8a6af, 0x88229120, 0x8b60e4de, 0x25424bf9, + 0x9c7fe31a, 0x3a89192c, 0x36d4057e, 0xc25869cc, + 0x2f8b32c1, 0x7aeb8590, 0xa1a55039, 0x66c59227, + 0x584f20b0, 0x4383557e, 0x9ce2452b, 0x9012d8e4, + 0x5683162c, 0xb3037916, 0x18612dad, 0x371f131a, + 0x739ce1e2, 0xfdd5807b, 0xfc87512d, 0x1fd7aa7b, + 0xaf8e7a2c, 0xcdbb8df4, 0x727c1195, 0xe26fee0b, + 0x37deafb9, 0x8d8cde83, 0xb7670562, 0x568dc696, + 0x62d70db6, 0x3646d6ba, 0xe6c88ebd, 0x106c2aea, + 0x5b6bff14, 0x463c82fa, 0x464330b1, 0x9b7d8a51, + 0x79833e92, 0xb25d555b, 0x90ce5e6c, 0x98538e62, + 0xe56d0dc9, 0xc5cd572d, 0xe1ba5781, 0x728fb8e8, + 0xdc134fe5, 0x15719dea, 0x8811b210, 0x7fd409d5, + 0x2c7f655b, 0x114c383b, 0xfb8d5068, 0xbf59b09e, + 0x4a898094, 0x12181ac5, 0x4ad15389, 0x8ce82910, + 0xeab6ec1c, 0x8b17c746, 0xa8311525, 0xb1436ba2, + 0x0bdbe29d, 0x11b09b87, 0xd2710e04, 0x82897729, + 0x7f41660a, 0xff480b1d, 0xfd24bb72, 0x9ba148c2, + 0xce7f7bfe, 0xd986db88, 0xb01c3b85, 0x0733a8dc, + 0xe32e51bf, 0x97009a0e, 0x97c0061e, 0xb6d89d43, + 0x6786c445, 0x88f8005f, 0x9e52a49a, 0x838aaac7, + 0x18c5ec75, 0x2fc3ceae, 0x18f92b1a, 0xf51aaeff, + 0x33b50b53, 0xe8fda751, 0x64a2e1a8, 0x431722b6, + 0xd80acc80, 0x40ba3bae, 0x4a92d9d7, 0x1004df89, + 0x2b189bee, 0x8a69776a, 0xb9f9f468, 0x6e1521a2, + 0x033b1ee6, 0x609b3062, 0x9b257e41, 0x52c58f9e, + 0xc2f80810, 0x1121a169, 0x795e3788, 0x10ff6635, + 0xed6e1842, 0x1c6bb697, 0x6de5364e, 0xbfe4b47d, + 0x05e0b920, 0xb8d5693a, 0xe0dcd5e3, 0x3e53acb9, + 0xad57a407, 0x1848ff77, 0x49ac2a76, 0x75478e2a, + 0x63679f6d, 0x398c3530, 0x6fd53905, 0xad5b3a64, + 0x82bb0bca, 0xb1459952, 0x99363693, 0x442013af, + 0x4402d836, 0x85923909, 0x974a4aff, 0xd763a687, + 0x24b5b5c7, 0x6fb40fed, 0x1452580c, 0xd37ba6d9, + 0x5838bc79, 0x843bbda1, 0x061ad806, 0xeaa86bfd, + 0x0428694b, 0x9982ad37, 0x851b0efb, 0x735da8bd, + 0x7558dccd, 0x6c63be0a, 0xe44ce748, 0x60042b30, + 0xdad815b9, 0x8f758186, 0x1c8dd496, 0x7c85705d, + 0xd57b671c, 0xcea66708, 0x70660a4b, 0xd463e5b7, + 0xea828a5b, 0xe2ca6710, 0x8517eff4, 0x8a5f2a2f, + 0x6af88297, 0xea1034d6, 0x3c5cc9eb, 0x46f849e1, + 0xf6bddeeb, 0xaaf192a9, 0xb018a0a6, 0x1f0fd33a, + 0x31ff6ff3, 0xd3444345, 0x88f79a50, 0xcec19609, + 0x2cf2cc76, 0x82adba2c, 0x84188f77, 0x9c07d2c0, + 0x4e839036, 0x434fa50b, 0x78ab043e, 0x09fbd64f, + 0xda902401, 0x613a3c6f, 0x4a697f0d, 0x02302beb, + 0x84e0dbb4, 0x35d7eca9, 0x857d37bf, 0x4ea9ce58, + 0xa8c780e4, 0x486730d3, 0x2faf29eb, 0xa7b46a74, + 0x923f0f3f, 0xaccaf3af, 0x94d94baf, 0x81ca43c0, + 0xa1482f0d, 0xd2d527b0, 0x85054bef, 0x934ddea3, + 0xbbf03c30, 0x27308f4a, 0x3ee3eb4c, 0x2f9aed64, + 0xf082f13b, 0x7fcff4ba, 0xe1b0cb40, 0x57aabc7f, + 0xf274c9d3, 0x220d43fa, 0x4e77f4d0, 0x7085d793, + 0xb6bf991f, 0x30f135de, 0xf0715ea7, 0x7b2d016b, + 0x5333f064, 0xf388390a, 0x6ba63a6b, 0x432fd235, + 0xb5fd02cd, 0xaa5bbce9, 0x7e19a4d8, 0x81945d0e, + 0xad776f9e, 0x93740ed6, 0x18c4e796, 0x19f5ad5f +}; + diff --git a/build/libraries/gcd/common/gcd.c b/build/libraries/gcd/common/gcd.c new file mode 100644 index 0000000..0f277b1 --- /dev/null +++ b/build/libraries/gcd/common/gcd.c @@ -0,0 +1,1215 @@ +/*---------------------------------------------------------------------------* + Project: TwlBrom - GCD - libraries + File: gcd.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ + +#include +#include + +// use this functions for DS mode only + +//#define PRINT_DEBUG + +#ifdef PRINT_DEBUG +#define DBG_PRINTF vlink_dos_printf +#define DBG_CHAR vlink_dos_put_console +#else +#define DBG_PRINTF( ... ) ((void)0) +#define DBG_CHAR( c ) ((void)0) +#endif + + +static BOOL GCDi_ReadRomPreCore( GCDSlot slot, u32 romp, void *ramp, s32 size ); +static void GCDi_ReadGameModeRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ); +static void GCDi_WriteGameModeRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ); + +static void GCD_DmaRecvRomAsync( GCDSlot slot, u32 dmaNo, void *dest ); +static void GCD_DmaSendRomAsync( GCDSlot slot, u32 dmaNo, void *src ); + + +u32 GCDi_HeaderBuf[2][ GCD_ROM_HEADER_SIZE/sizeof(u32) ]; +u32 GCDi_SecureAreaBuf[2][ GCD_SECURE_AREA_SIZE/sizeof(u32) ]; +u32 GCDi_Secure2AreaBuf[2][ GCD_SECURE_AREA_SIZE/sizeof(u32) ]; + +GCDSharedWork GCDi_SharedWork[2]; +GCDSecureWork GCDi_SecureWork[2]; + + +/*---------------------------------------------------------------------------* + Name: GCDi_Enable + + Description: enable game card master control + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Enable( GCDSlot slot ) +{ + REGType16v* cnt0 = GCDi_SelectRegAddr( slot, REG_MCCNT0_ADDR ); + + OSIntrMode enabled = OS_DisableInterrupts(); + + GCDi_WaitCtrl( slot ); + + *cnt0 |= REG_MI_MCCNT0_A_E_MASK | REG_MI_MCCNT0_A_I_MASK; + + (void)OS_RestoreInterrupts(enabled); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_Disable + + Description: disable game card master control + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Disable( GCDSlot slot ) +{ + REGType16v* cnt0 = GCDi_SelectRegAddr( slot, REG_MCCNT0_ADDR ); + + OSIntrMode enabled = OS_DisableInterrupts(); + + GCDi_WaitCtrl( slot ); + + *cnt0 &= ~(REG_MI_MCCNT0_A_E_MASK | REG_MI_MCCNT0_A_I_MASK); + + (void)OS_RestoreInterrupts(enabled); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_SelectRom + + Description: select game card rom + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SelectRom( GCDSlot slot ) +{ + REGType16v* cnt0 = GCDi_SelectRegAddr( slot, REG_MCCNT0_ADDR ); + + OSIntrMode enabled = OS_DisableInterrupts(); + + *cnt0 &= ~REG_MI_MCCNT0_A_SEL_MASK; + + (void)OS_RestoreInterrupts(enabled); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_SelectSpi + + Description: select game card spi + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SelectSpi( GCDSlot slot ) +{ + REGType16v* cnt0 = GCDi_SelectRegAddr( slot, REG_MCCNT0_ADDR ); + + OSIntrMode enabled = OS_DisableInterrupts(); + + *cnt0 |= REG_MI_MCCNT0_A_SEL_MASK; + + (void)OS_RestoreInterrupts(enabled); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_GenCtrl + + Description: generate game card control + + Arguments: op : command + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_GenCtrl( GCDCtrlRegs* regs, + GCDRw rw, + GCDPageCount pcount, + GCDClockType ckt, u32 lt1, u32 lt2, + BOOL cpn, BOOL dpn, BOOL csc, BOOL dsc ) +{ + regs->latency = ((lt1 << REG_MI_MCCNT1_A_L1_SHIFT) & REG_MI_MCCNT1_A_L1_MASK) + | ((lt2 << REG_MI_MCCNT1_A_L2_SHIFT) & REG_MI_MCCNT1_A_L2_MASK); + + regs->ctrl = REG_MI_MCCNT1_A_START_MASK | REG_MI_MCCNT1_A_RESB_MASK + | rw + | pcount + | ckt + | ((lt1 << REG_MI_MCCNT1_A_L1_SHIFT) & REG_MI_MCCNT1_A_L1_MASK) + | ((lt2 << REG_MI_MCCNT1_A_L2_SHIFT) & REG_MI_MCCNT1_A_L2_MASK) + | ((cpn || dpn) ? (u32)REG_MI_MCCNT1_A_SE_MASK : 0) + | (csc ? REG_MI_MCCNT1_A_CSC_MASK : 0) + | (dsc ? REG_MI_MCCNT1_A_DS_MASK : 0); + +#if 1 + regs->scramble = (cpn || dpn) ? (u32)REG_MI_MCCNT1_A_SE_MASK : 0 + | csc ? REG_MI_MCCNT1_A_CSC_MASK : 0 + | dsc ? REG_MI_MCCNT1_A_DS_MASK : 0; +#endif +} + +/*---------------------------------------------------------------------------* + Name: GCDi_SetCtrl + + Description: set game card control + + Arguments: op : command + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SetCtrl( GCDSlot slot, GCDCtrlRegs* regs ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + *cnt1 = regs->ctrl | regs->latency | regs->scramble; +} + +/*---------------------------------------------------------------------------* + Name: GCDi_SetOp + + Description: set game card command + + Arguments: op : command + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SetOp( GCDSlot slot, GCDCmd64* op ) +{ + GCDi_SelectRom( slot ); + + { + REGType8v* cmd = GCDi_SelectRegAddr( slot, REG_MCCMD0_ADDR ); + + cmd[0] = op->b[7]; + cmd[1] = op->b[6]; + cmd[2] = op->b[5]; + cmd[3] = op->b[4]; + cmd[4] = op->b[3]; + cmd[5] = op->b[2]; + cmd[6] = op->b[1]; + cmd[7] = op->b[0]; + } +} + +/*---------------------------------------------------------------------------* + Name: GCD_SendOnlyCardOpCore + + Description: send only rom command + sync version + + Arguments: ctrls : rom control + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_SendOnlyCardOpCore( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + GCDi_WaitCtrl( slot ); + + GCDi_SetOp( slot, &ctrls->gcdOp ); + + GCDi_SetCtrl( slot, ctrls->gcdRegs ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRomID + + Description: read rom ID + sync version + + Arguments: None + + Returns: rom ID + *---------------------------------------------------------------------------*/ +u32 GCD_ReadRomID( GCDSlot slot ) +{ + return GCD_ReadGameModeID( slot ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_ReadGameModeID + + Description: read rom ID on game mode + sync version + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +u32 GCD_ReadGameModeID( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + u32 romID = 0; + u16 id = (u16)OS_GetLockID(); + + if ( !GCD_IsExisting( slot ) ) + { + return romID; + } + + if ( slot == GCD_PRIMARY_SLOT ) + { + OS_LockCard( id ); + } + else + { + OS_LockExCard( id ); + } + + ctrls->gcdRegs = &ctrls->gIDRegs; + ctrls->gcdOp.dw = GCDOP_G_OP_RD_ROM_ID; + + romID = GCDi_ReadRomIDCore( slot, ctrls ); + + if ( slot == GCD_PRIMARY_SLOT ) + { + OS_UnlockCard( id ); + } + else + { + OS_UnlockExCard( id ); + } + OS_ReleaseLockID( id ); + + return romID; +} + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadRomIDCore + + Description: read rom ID + sync version + + Arguments: ctrls : rom control + + Returns: None + *---------------------------------------------------------------------------*/ +u32 GCDi_ReadRomIDCore( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + REGType32v* data1 = GCDi_SelectRegAddr( slot, REG_MCD1_ADDR ); + + GCDi_WaitCtrl( slot ); + + GCDi_SetOp( slot, &ctrls->gcdOp ); + + GCDi_SetCtrl( slot, ctrls->gcdRegs ); + GCDi_WaitData( slot ); + + return *data1; +} + + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRom + + Description: read rom data + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadRom( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDWork *gw = &GCDi_Work[slot]; + u16 id; + + if ( !GCD_IsExisting( slot ) ) + { + return; + } + + id = (u16)OS_GetLockID(); + if ( slot == GCD_PRIMARY_SLOT ) + { + OS_LockCard( id ); + } + else + { + OS_LockExCard( id ); + } + + if ( GCDi_ReadRomPreCore( slot, romp, ramp, size ) ) + { + GCD_ReadGameModeRom( slot, gw->romp, gw->ramp, gw->restSize ); + } + + if ( slot == GCD_PRIMARY_SLOT ) + { + OS_UnlockCard( id ); + } + else + { + OS_UnlockExCard( id ); + } + OS_ReleaseLockID( id ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRomAsync + + Description: read rom data + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDWork *gw = &GCDi_Work[slot]; + + if ( GCDi_ReadRomPreCore( slot, romp, ramp, size ) ) + { + GCD_ReadGameModeRomAsync( slot, gw->romp, gw->ramp, gw->restSize ); + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadRomPreCore + + Description: read rom data + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +static BOOL GCDi_ReadRomPreCore( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + BOOL game_area = GCDi_ReadRomCommonPreCore( slot, romp, ramp, size ); + { + GCDWork *gw = &GCDi_Work[slot]; + romp = gw->romp; + ramp = gw->ramp; + size = gw->restSize; + } + + return game_area; +} + +BOOL GCDi_ReadRomCommonPreCore( GCDSlot slot, u32 romp, void *ram, s32 size ) +{ + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + u32 romEndp = romp + size; + u32 secure2 = (u32)rh->l.twlAreaOffset * GCD_TWL_AREA_ALIGN + GCD_SECURE2_AREA_OFFSET; + u32 game2 = secure2 + GCD_SECURE2_AREA_SIZE; + u8 *ramp = ram; + + // header + if ( romp < GCD_ROM_HEADER_SIZE + && size > 0 ) + { + s32 otherSize = (s32)romEndp - GCD_ROM_HEADER_SIZE; + s32 hdrSize = size; + if ( otherSize > 0 ) + { + hdrSize -= otherSize; + } + MI_CpuCopyFast( &GCDi_HeaderBuf[slot][romp/4], ramp, (u32)hdrSize ); + romp += hdrSize; + ramp += hdrSize; + size -= hdrSize; + } + + // pad + if ( romp >= GCD_ROM_HEADER_SIZE && romp < GCD_SECURE_AREA_OFFSET + && size > 0 ) + { + s32 otherSize = (s32)romEndp - (GCD_SECURE_AREA_OFFSET - GCD_ROM_HEADER_SIZE); + s32 padSize = size; + if ( otherSize > 0 ) + { + padSize -= otherSize; + } + MI_CpuClearFast( ramp, (u32)padSize ); + romp += padSize; + ramp += padSize; + size -= padSize; + } + + //secure + if ( romp >= GCD_SECURE_AREA_OFFSET && romp < GCD_GAME_AREA_OFFSET + && size > 0 ) + { + s32 gameSize = (s32)romEndp - GCD_GAME_AREA_OFFSET; + s32 secureSize = size; + if ( gameSize > 0 ) + { + secureSize -= gameSize; + } + MI_CpuCopyFast( &GCDi_SecureAreaBuf[slot][(romp - GCD_SECURE_AREA_OFFSET)/4], ramp, (u32)secureSize ); + romp += secureSize; + ramp += secureSize; + size -= secureSize; + } + + //secure2 + if ( rh->l.twlAreaOffset + && romp >= secure2 && romp < game2 + && size > 0 ) + { + s32 game2Size = (s32)(romEndp - game2); + s32 secure2Size = size; + if ( game2Size > 0 ) + { + secure2Size -= game2Size; + } + MI_CpuCopyFast( &GCDi_Secure2AreaBuf[slot][(romp - secure2)/4], ramp, (u32)secure2Size ); + romp += secure2Size; + ramp += secure2Size; + size -= secure2Size; + } + + GCD_WaitRomAsync( slot ); + + { + GCDWork *gw = &GCDi_Work[slot]; + gw->romp = romp; + gw->ramp = ramp; + gw->restSize = size; + } + + // game + if ( romp >= GCD_GAME_AREA_OFFSET + && size > 0 ) + { + return TRUE; + } + + return FALSE; +} + +/*---------------------------------------------------------------------------* + Name: GCD_ReadNormalModeRom + + Description: read rom data on normal mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadNormalModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + s32 restSize = size; + s32 oneShotSize; + + ctrls->gcdRegs = &ctrls->nReadRomRegs; + oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + + if ( GCDi_SharedWork[slot].nCardID & GCD_ROMID_1TROM_MASK ) + { + // 3Dpݒ + { + ctrls->gcdRegs->ctrl &= ~REG_MI_MCCNT1_A_PC_MASK; + ctrls->gcdRegs->ctrl |= GCD_PAGE_1; + } + } + + while ( restSize > 0 ) // ubNǂݍ + { + GCDi_ReadNormalModeRomCore( slot, romp, ramp, oneShotSize, ctrls ); + + romp += oneShotSize; + *(u8 **)&ramp += oneShotSize; + restSize -= oneShotSize; + } + + GCDi_WaitDma( slot, ctrls->dmaNo ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadNormalModeRomCore + + Description: read rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadNormalModeRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ + ctrls->gcdOp.dw = GCDOP_N_OP_RD_PAGE + | ((u64 )(romp/GCD_ROM_PAGE_SIZE) << GCDOP_N_RD_PAGE_ADDR_SHIFT); + + GCDi_ReadRomCore( slot, ramp, size, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_ReadGameModeRom + + Description: read rom data on game mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadGameModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + s32 restSize = size; + s32 oneShotSize; + + ctrls->gcdRegs = &ctrls->gReadRomRegs; + oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + + while ( restSize > 0 ) // ubNǂݍ + { + GCDi_ReadGameModeRomCore( slot, romp, ramp, oneShotSize, ctrls ); + + romp += oneShotSize; + *(u8 **)&ramp += oneShotSize; + restSize -= oneShotSize; + } + + GCDi_WaitDma( slot, ctrls->dmaNo ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadGameModeRomCore + + Description: read rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_ReadGameModeRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ + ctrls->gcdOp.dw = GCDOP_G_OP_RD_PAGE + | ((u64 )(romp/GCD_ROM_PAGE_SIZE) << GCDOP_G_RD_PAGE_ADDR_SHIFT); + + GCDi_ReadRomCore( slot, ramp, size, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadRomCore + + Description: read rom data on game mode + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadRomCore( GCDSlot slot, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ + u32 dmaNo = ctrls->dmaNo; + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + REGType32v* data1 = GCDi_SelectRegAddr( slot, REG_MCD1_ADDR ); + + if ( !GCD_IsExisting( slot ) ) + { + return; + } + + GCDi_WaitDma( slot, dmaNo ); + + GCDi_SetOp( slot, &ctrls->gcdOp ); // R}hݒ + + if ( MI_EXDMA_CH_MIN <= dmaNo && dmaNo <= MI_EXDMA_CH_MAX ) + { + GCD_DmaRecvRomAsync( slot, dmaNo, ramp ); + GCDi_SetCtrl( slot, ctrls->gcdRegs ); // Rg[ݒ & DMAX^[g + } + else + { + void *ramEndp; + u32 ctrlTmp; + + GCDi_SetCtrl( slot, ctrls->gcdRegs ); // Rg[ݒ + + ramEndp = (u8 *)ramp + size; // i[IAhXZo + + do { // CPUǂݍ + ctrlTmp = *cnt1; + + if (ctrlTmp & REG_MI_MCCNT1_A_RDY_MASK) { + u32 dataTmp = *data1; + + if (ramp < ramEndp) + { + *((vu32 *)ramp) = dataTmp; // wTCY܂Ŋi[i㑱f[^͓ǂݎ̂āj + (*(vu32 **)&ramp)++; + } + } + } + while (ctrlTmp & REG_MI_MCCNT1_A_START_MASK); + } +} + + +/*---------------------------------------------------------------------------* + Name: GCD_WriteGameModeRom + + Description: write rom data on game mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_WriteGameModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + s32 restSize = size; + s32 oneShotSize; + + ctrls->gcdRegs = &ctrls->gWriteRomRegs; + + oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + + while ( restSize > 0 ) // ubNǂݍ + { + GCDi_WriteGameModeRomCore( slot, romp, ramp, oneShotSize, ctrls ); + + romp += oneShotSize; + *(u8 **)&ramp += oneShotSize; + restSize -= oneShotSize; + } + + GCDi_WaitDma( slot, ctrls->dmaNo ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_WriteGameModeRomCore + + Description: write rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_WriteGameModeRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ + ctrls->gcdOp.dw = GCDOP_G_OP_WR_PAGE + | ((u64 )(romp/GCD_ROM_PAGE_SIZE) << GCDOP_G_RD_PAGE_ADDR_SHIFT); + + GCDi_WriteRomCore( slot, ramp, size, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_WriteRomCore + + Description: write rom data on game mode + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WriteRomCore( GCDSlot slot, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ + u32 dmaNo = ctrls->dmaNo; + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + REGType32v* data1 = GCDi_SelectRegAddr( slot, REG_MCD1_ADDR ); + +// OS_TPrintf( "\nwrite size = %#x\n\n", size ); + + GCDi_WaitDma( slot, dmaNo ); + + GCDi_SetOp( slot, &ctrls->gcdOp ); // R}hݒ + + if ( MI_EXDMA_CH_MIN <= dmaNo && dmaNo <= MI_EXDMA_CH_MAX ) + { + GCD_DmaSendRomAsync( slot, dmaNo, ramp ); + GCDi_SetCtrl( slot, ctrls->gcdRegs ); // Rg[ݒ & DMAX^[g + } + else + { + void *ramEndp; + u32 ctrlTmp; + + GCDi_SetCtrl( slot, ctrls->gcdRegs ); // Rg[ݒ + + ramEndp = (u8 *)ramp + size; // i[IAhXZo + + do { // CPUǂݍ + ctrlTmp = *cnt1; + + if (ctrlTmp & REG_MI_MCCNT1_A_RDY_MASK) { + u32 dataTmp = 0; + + if (ramp < ramEndp) + { + dataTmp = *((vu32 *)ramp); + (*(vu32 **)&ramp)++; + } + *data1 = dataTmp; + } + } + while (ctrlTmp & REG_MI_MCCNT1_A_START_MASK); + } +} + +/*---------------------------------------------------------------------------* + Name: GCD_DmaRecvRomAsync + + Description: receive data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCD_DmaRecvRomAsync( GCDSlot slot, u32 dmaNo, void *dest ) +{ + const void* data1 = GCDi_SelectRegAddr( slot, REG_MCD1_ADDR ); + u32 timing = MI_NDMA_TIMING_CARD_A; + u32 blockSize = MI_NDMA_BWORD_1; + u32 interval = 1; + u32 prescale = MI_NDMA_INTERVAL_PS_1; + + if ( slot == GCD_SECONDARY_SLOT ) + { + timing = MI_NDMA_TIMING_CARD_B; + } + + MIi_ExDmaRecvAsyncCore(dmaNo, data1, dest, 4, 4, + blockSize, interval, prescale, + MI_NDMA_CONTINUOUS_ON, MI_NDMA_SRC_RELOAD_ENABLE, MI_NDMA_DEST_RELOAD_DISABLE, + timing); +} + +/*---------------------------------------------------------------------------* + Name: GCD_DmaSendRomAsync + + Description: receive data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCD_DmaSendRomAsync( GCDSlot slot, u32 dmaNo, void *src ) +{ + const void* data1 = GCDi_SelectRegAddr( slot, REG_MCD1_ADDR ); + u32 timing = MI_NDMA_TIMING_CARD_A; + u32 blockSize = MI_NDMA_BWORD_1; + u32 interval = 1; + u32 prescale = MI_NDMA_INTERVAL_PS_1; + + if ( slot == GCD_SECONDARY_SLOT ) + { + timing = MI_NDMA_TIMING_CARD_B; + } + + MIi_ExDmaSendAsyncCore(dmaNo, src, (void*)REG_MCD1_ADDR, 4, 4, + blockSize, interval, prescale, + MI_NDMA_CONTINUOUS_ON, MI_NDMA_SRC_RELOAD_DISABLE, MI_NDMA_DEST_RELOAD_ENABLE, + timing); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_GetOneShotSizeFromCtrl + + Description: get block size + + Arguments: ctrl : rom control + + Returns: None + *---------------------------------------------------------------------------*/ +s32 GCDi_GetOneShotSizeFromCtrl( u32 ctrl ) +{ + s32 oneShotSize = 0; + u32 pages = (ctrl & REG_MI_MCCNT1_A_PC_MASK) >> REG_MI_MCCNT1_A_PC_SHIFT; + s32 pageSize = 512; + + oneShotSize = pageSize << (pages - 1); + + return oneShotSize; +} + + +/*---------------------------------------------------------------------------* + Name: GCD_ReadNormalModeRomAsync + + Description: read rom data on normal mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadNormalModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + ctrls->gcdRegs = &ctrls->nReadRomRegs; + + gw->funcp = GCDi_ReadNormalModeRomCore; + + GCD_SetInterrupt( slot, romp, ramp, size, gw ); + + gw->funcp( slot, gw->romp, gw->ramp, gw->oneShotSize, ctrls ); +} + + +/*---------------------------------------------------------------------------* + Name: GCD_ReadGameModeRomAsync + + Description: read rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadGameModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + ctrls->gcdRegs = &ctrls->gReadRomRegs; + + gw->funcp = GCDi_ReadGameModeRomCore; + + GCD_SetInterrupt( slot, romp, ramp, size, gw ); + + gw->funcp( slot, gw->romp, gw->ramp, gw->oneShotSize, ctrls ); +} + + +/*---------------------------------------------------------------------------* + Name: GCD_WriteGameModeRomAsync + + Description: write rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_WriteGameModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + ctrls->gcdRegs = &ctrls->gWriteRomRegs; + + gw->funcp = GCDi_WriteGameModeRomCore; + + GCD_SetInterrupt( slot, romp, ramp, size, gw ); + + gw->funcp( slot, gw->romp, gw->ramp, gw->oneShotSize, ctrls ); +} + + +/*---------------------------------------------------------------------------* + Name: GCD_SetInterrupt + + Description: set interrupt + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_SetInterrupt( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDWork *gw ) +{ + GCDRomCtrls *ctrls = &gw->ctrls; + u32 dmaNo = ctrls->dmaNo; + u32 mask = GCDi_SelectIrqMask( slot, OS_IE_CARD_DATA ); + OSIrqFunction intr = GCDi_InterruptHandlerPRIME; + + gw->romp = romp; + gw->ramp = ramp; + gw->restSize = size; + gw->oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + + if ( dmaNo < MI_EXDMA_CH_MIN || MI_EXDMA_CH_MAX < dmaNo ) + { + ctrls->lastDmaNo = ctrls->dmaNo; + ctrls->dmaNo = GCD_DEFAULT_DMA_A_NO; + if ( slot == GCD_SECONDARY_SLOT ) + { + ctrls->dmaNo = GCD_DEFAULT_DMA_B_NO; + } + } + + GCDi_WaitDma( slot, dmaNo ); + + (void)OS_DisableInterrupts(); + + if ( slot ) + { + intr = GCDi_InterruptHandlerSECOND; + } + + OS_SetIrqFunction( mask, intr ); + + gw->isAsync = TRUE; + + gw->intrDone = FALSE; + + reg_OS_IF = mask; + reg_OS_IE |= mask; + + (void)OS_EnableInterrupts(); + (void)OS_EnableIrq(); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_InterruptHandler + + Description: interrupt handler + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_InterruptHandlerCommon( GCDSlot slot ) +{ + GCDWork *gw = &GCDi_Work[slot]; + s32 oneShotSize = gw->oneShotSize; + + // read block + + gw->romp += oneShotSize; + gw->ramp += oneShotSize; + gw->restSize -= oneShotSize; + + if (gw->restSize > 0) { + GCDRomCtrls *ctrls = &gw->ctrls; + gw->oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + gw->funcp( slot, gw->romp, gw->ramp, oneShotSize, &gw->ctrls ); + } else { + gw->intrDone = TRUE; // J[h̒ʒm + } +} + +void GCDi_InterruptHandlerPRIME( void ) +{ + GCDi_InterruptHandlerCommon( GCD_PRIMARY_SLOT ); +} + +void GCDi_InterruptHandlerSECOND( void ) +{ + GCDi_InterruptHandlerCommon( GCD_SECONDARY_SLOT ); +} + + +//================================================================================ +// WAIT/STOP +//================================================================================ +/*---------------------------------------------------------------------------* + Name: GCD_IsBusy + + Description: check whether game card is busy or not + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL GCD_IsBusy( GCDSlot slot ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + return (BOOL)((*cnt1 & REG_MI_MCCNT1_A_START_MASK) >> REG_MI_MCCNT1_A_START_SHIFT); +} + +/*---------------------------------------------------------------------------* + Name: GCD_IsDataReady + + Description: check whether data is ready or not + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL GCD_IsDataReady( GCDSlot slot ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + return (BOOL)((*cnt1 & REG_MI_MCCNT1_A_RDY_MASK) >> REG_MI_MCCNT1_A_RDY_SHIFT); +} + +/*---------------------------------------------------------------------------* + Name: GCD_Stop + + Description: stop game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_Stop( GCDSlot slot ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + OSIntrMode enabled = OS_DisableInterrupts(); + + *cnt1 &= ~REG_MI_MCCNT1_A_START_MASK; + + (void)OS_RestoreInterrupts(enabled); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitCtrl + + Description: wait while game card is busy + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitCtrl( GCDSlot slot ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + while (*cnt1 & REG_MI_MCCNT1_A_START_MASK) + { + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitData + + Description: wait until data is ready + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitData( GCDSlot slot ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + while ( !(*cnt1 & REG_MI_MCCNT1_A_RDY_MASK) ) + { + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitDma + + Description: wait for stopping game card DMA + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitDma( GCDSlot slot, u32 dmaNo ) +{ + GCDi_WaitCtrl( slot ); + + if ( MI_EXDMA_CH_MIN <= dmaNo && dmaNo <= MI_EXDMA_CH_MAX ) + { + MIi_StopExDma( dmaNo ); + } +} + + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitInterrupt + + Description: wait for game card interrupt + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitInterrupt( GCDSlot slot ) +{ + GCDWork *gw = &GCDi_Work[slot]; + + if ( gw->isAsync ) + { + while ( !gw->intrDone ) + { + } + } + gw->intrDone = FALSE; + gw->isAsync = FALSE; + + GCDi_WaitDma( slot, gw->ctrls.dmaNo ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_WaitRomAsync + + Description: wait for game card async access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_WaitRomAsync( GCDSlot slot ) +{ + GCDi_WaitInterrupt( slot ); + + { + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + u32 mask = GCDi_SelectIrqMask( slot, OS_IE_CARD_DATA ); + + OSIntrMode enabled = OS_DisableInterrupts(); + + ctrls->dmaNo = ctrls->lastDmaNo; + +#define IOP_DISABLE_OS_TIMER +#ifdef IOP_DISABLE_OS_TIMER + reg_OS_IE &= ~REG_OS_IE_T1_MASK; +#endif // IOP_DISABLE_OS_TIMER + + reg_OS_IE &= ~mask; // disable card interrupt + + (void)OS_RestoreInterrupts( enabled ); + } +} + + diff --git a/build/libraries/gcd/common/gcd_init.c b/build/libraries/gcd/common/gcd_init.c new file mode 100644 index 0000000..43d5c83 --- /dev/null +++ b/build/libraries/gcd/common/gcd_init.c @@ -0,0 +1,1696 @@ +/*---------------------------------------------------------------------------* + Project: TwlBrom - GCD - libraries + File: gcd_init.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ + +#include +#include +#include +#include + +//#define PRINT_DEBUG + +#ifdef PRINT_DEBUG +#define DBG_PRINTF vlink_dos_printf +#define DBG_CHAR vlink_dos_put_console +#else +#define DBG_PRINTF( ... ) ((void)0) +#define DBG_CHAR( c ) ((void)0) +#endif + + +//#define FIRM_FORCE_DEBUGGER +#define FIRM_FORCE_FIRMBLOWFISH + +#ifndef FIRM_FORCE_DEBUGGER +#define GCD_ENABLE_SCRAMBLE +#endif // FIRM_FORCE_DEBUGGER + +static void GCDi_GetExistingSlots( GCDSlot* start, GCDSlot* end ); +void GCDi_CallbackForReset(PXIFifoTag tag, u32 data, BOOL err); +void GCDi_CallbackForResetAll(PXIFifoTag tag, u32 data, BOOL err); + +static void GCDi_SetPngIntf( GCDSlot slot, u32 pnA_l, u8 pnA_h, u32 pnB_l, u8 pnB_h ); +static void GCDi_SendOnlyCardSecureOpCore( GCDSlot slot, GCDRomCtrls *ctrls ); +static void GCDi_ReadSecureModeRomCore( GCDSlot slot, void *ramp, s32 size, GCDRomCtrls *ctrls ); +static void Encrypt2SetTimer4Secure( GCDSlot slot, GCDRomCtrls *ctrls ); + +static BOOL IsCtrApp( GCDSlot slot ); +static BOOL IsDsApp( GCDSlot slot ); + +static BOOL GCDi_SecureInitialized[2]; + + +static void GCDi_LoadHeader( GCDSlot slot ); +static void GCDi_LoadHeaderAll( void ); +static void GCDi_LoadTable( GCDSlot slot ); +static void GCDi_LoadTableAsync( GCDSlot slot ); +static void GCDi_ReadShortHeader( GCDSlot slot, void *ramp ); +static void GCDi_ReadShortHeaderAsync( GCDSlot slot, void *ramp ); +static void GCDi_LoadSecure( GCDSlot slot ); +static void GCDi_LoadSecure2( GCDSlot slot ); +static void GCDi_LoadSecureAll( void ); +static void GCDi_LoadSecure2All( void ); + +static BOOL GCD_Initialized[2]; +extern GCDSharedWork GCDi_SharedWork[2]; +extern GCDSecureWork GCDi_SecureWork[2]; + +GCDWork GCDi_Work[2]; + + + +void* GCDi_GetRomHeaderAddr( GCDSlot slot ) +{ + return ((void*)GCDi_HeaderBuf[slot]); +} + + +// SDKSecondarySlot̃J[hvZbTݒ肪pӂĂȂ̂ŁAƂ肠[JŗpӁB +#ifdef SDK_ARM9 +static inline void MIi_SetExCardProcessor(MIProcessor proc) +{ + MI_PROCESSOR_ASSERT(proc); + reg_MI_EXMEMCNT = + (u16)((reg_MI_EXMEMCNT & ~REG_MI_EXMEMCNT_MPB_MASK) | (proc << REG_MI_EXMEMCNT_MPB_SHIFT)); +} +#endif +#ifdef SDK_ARM7 +#define REG_MI_EXMEMCNT_MPB_MASK 0x0400 +#define REG_MI_EXMEMCNT_MPB_SHIFT 10 +#endif +static inline MIProcessor MI_GetExCardProcessor(void) +{ + return (MIProcessor)((reg_MI_EXMEMCNT & REG_MI_EXMEMCNT_MPB_MASK) >> REG_MI_EXMEMCNT_MPB_SHIFT); +} + +// SDKSecondarySlot̃J[hbNpӂĂȂ̂ŁAƂ肠PrimarySlotƋpŁB +#ifdef SDK_ARM9 +#define OSi_ASSERT_ID( id ) SDK_ASSERTMSG( id >= OS_MAINP_LOCK_ID_START && id <= OS_MAINP_SYSTEM_LOCK_ID, \ + "lock ID %d is out of bounds", id ) +#else +#define OSi_ASSERT_ID( id ) SDK_ASSERTMSG( id >= OS_SUBP_LOCK_ID_START && id <= OS_SUBP_SYSTEM_LOCK_ID, \ + "lock ID %d is out of bounds", id ) +#endif + +static void OSi_AllocateExCardBus(void) +{ +#ifdef SDK_ARM9 + MIi_SetExCardProcessor(MI_PROCESSOR_ARM9); // Card for MAIN +#endif +} + +static void OSi_FreeExCardBus(void) +{ +#ifdef SDK_ARM9 + MIi_SetExCardProcessor(MI_PROCESSOR_ARM7); // Card for SUB +#endif +} + +#define HW_CARD_B_LOCK_BUF HW_CTRDG_LOCK_BUF + +s32 OS_LockExCard(u16 lockID) +{ + OSi_ASSERT_ID(lockID); + + return OS_LockByWord(lockID, (OSLockWord *)HW_CARD_B_LOCK_BUF, OSi_AllocateExCardBus); +} + +s32 OS_UnlockExCard(u16 lockID) +{ + OSi_ASSERT_ID(lockID); + + return OS_UnlockByWord(lockID, (OSLockWord *)HW_CARD_B_LOCK_BUF, OSi_FreeExCardBus); +} + + +/*---------------------------------------------------------------------------* + Name: GCD_Init + + Description: initialize for game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_Init( void ) +{ + GCDSlot slot; + MIProcessor lastProc = MI_GetCardProcessor(); + MIProcessor lastProcB = MI_GetExCardProcessor(); + u16 id = (u16)OS_GetLockID(); + + OS_LockCard( id ); + OS_LockExCard( id ); + +#ifdef SDK_ARM9 + MIi_SetCardProcessor( MI_PROCESSOR_ARM9 ); + MIi_SetExCardProcessor( MI_PROCESSOR_ARM9 ); +#else // SDK_ARM9 + while ( MI_GetCardProcessor() != MI_PROCESSOR_ARM7 ) + { + } + while ( MI_GetExCardProcessor() != MI_PROCESSOR_ARM7 ) + { + } +#endif // SDK_ARM7 + + if ( GCD_Initialized[GCD_PRIMARY_SLOT] == FALSE || + GCD_Initialized[GCD_SECONDARY_SLOT] == FALSE ) + { + GCDi_Init( TRUE ); + GCDi_LoadHeaderAll(); + GCDi_LoadSecureAll(); + } + + for (slot=GCD_PRIMARY_SLOT; slot<=GCD_SECONDARY_SLOT; slot++) + { + if ( GCD_Initialized[slot] == FALSE ) + { + if ( GCD_IsExisting( slot ) ) + { + if ( GCDi_IsDsApp( slot ) ) + { + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + + if ( rh->l.twlAreaOffset ) // && (sh->nCardID & GCD_ROMID_TWLROM_MASK) ) + { + u32 chat_cycles = OS_MSEC_TO_CPUCYC( 25 ) / GCD_CHATTERING_CYCLES; +#ifdef SDK_ARM9 + chat_cycles /= 2; +#endif // SDK_ARM9 + GCD_Reset( slot, chat_cycles ); + GCDi_LoadHeader( slot ); + GCDi_LoadSecure2( slot ); + } + + GCD_Initialized[slot] = TRUE; + } + } + } + } + +#ifdef SDK_ARM9 + MIi_SetCardProcessor( lastProc ); + MIi_SetExCardProcessor( lastProcB ); +#endif // SDK_ARM9 + + OS_UnlockExCard( id ); + OS_UnlockCard( id ); + + OS_ReleaseLockID( id ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_Init + + Description: initialize for game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Init( BOOL reset ) +{ + static BOOL initialized; + + if ( initialized == FALSE ) + { + GCDSlot slot; + + if ( reset ) + { +#ifdef SDK_ARM7 + + OSIntrMode enabled; + OSIrqMask lastIE; + BOOL lastIME; + + lastIE = OS_EnableIrqMask(OS_IE_SPFIFO_RECV); + lastIME = OS_EnableIrq(); + enabled = OS_EnableInterrupts(); + + //---- setting PXI + PXI_Init(); + PXI_SetFifoRecvCallback(PXI_FIFO_TAG_GCD, GCDi_CallbackForResetAll); + + while ( !( GCDi_Work[GCD_PRIMARY_SLOT].isPxiDone == TRUE && + GCDi_Work[GCD_SECONDARY_SLOT].isPxiDone == TRUE ) ) + { + } + + (void)OS_RestoreIrq(lastIME); + (void)OS_SetIrqMask(lastIE); + (void)OS_RestoreInterrupts(enabled); + +#else // SDK_ARM9 + + u32 chat_cycles = OS_MSEC_TO_CPUCYC( 25 ) / GCD_CHATTERING_CYCLES; + chat_cycles /= 2; + GCD_ResetAll( chat_cycles ); + +#endif // SDK_ARM9 + } + + for (slot=GCD_PRIMARY_SLOT; slot<=GCD_SECONDARY_SLOT; slot++) + { + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + GCDi_GenCtrl( &ctrls->nLoadTableRegs, GCD_RW_READ, + GCD_PAGE_16, + GCD_CKT_240NS, 0, 0x18, + FALSE, FALSE, FALSE, FALSE ); + + GCDi_GenCtrl( &ctrls->nSendOnlyOpRegs, GCD_RW_READ, + GCD_PAGE_0, + GCD_CKT_240NS, 0x18, 0, + FALSE, FALSE, FALSE, FALSE ); + + GCDi_GenCtrl( &ctrls->nIDRegs, GCD_RW_READ, + GCD_PAGE_STAT, + GCD_CKT_240NS, 0x18, 0, + FALSE, FALSE, FALSE, FALSE ); + + GCDi_GenCtrl( &ctrls->nReadShortHeaderRegs, GCD_RW_READ, + GCD_PAGE_1, + GCD_CKT_240NS, REG_MI_MCCNT1_L1_MASK, REG_MI_MCCNT1_L2_MASK >> REG_MI_MCCNT1_L2_SHIFT, + FALSE, FALSE, FALSE, FALSE ); + + GCDi_GenCtrl( &ctrls->nReadRomRegs, GCD_RW_READ, + GCD_PAGE_8, + GCD_CKT_240NS, 0x657, 0x1, + FALSE, FALSE, FALSE, FALSE ); + + GCDi_GenCtrl( &ctrls->sSendOnlyOpRegs, GCD_RW_READ, + GCD_PAGE_0, + GCD_CKT_240NS, 0x8f8+0x18, 0, + FALSE, FALSE, FALSE, FALSE ); // enable after PNG ON + + GCDi_GenCtrl( &ctrls->sIDRegs, GCD_RW_READ, + GCD_PAGE_STAT, + GCD_CKT_240NS, 0x8f8+0x18, 0, + FALSE, TRUE, FALSE, TRUE ); + + GCDi_GenCtrl( &ctrls->sReadRomRegs, GCD_RW_READ, + GCD_PAGE_8, + GCD_CKT_240NS, 0x8f8, 0x18, + FALSE, TRUE, FALSE, TRUE ); + + GCDi_GenCtrl( &ctrls->gIDRegs, GCD_RW_READ, + GCD_PAGE_STAT, + GCD_CKT_150NS, 0, 0x1, +#ifdef GCD_ENABLE_SCRAMBLE + TRUE, TRUE, TRUE, TRUE ); +#else // GCD_ENABLE_SCRAMBLE + FALSE, FALSE, FALSE, FALSE ); +#endif // GCD_ENABLE_SCRAMBLE + + GCDi_GenCtrl( &ctrls->gReadRomRegs, GCD_RW_READ, + GCD_PAGE_1, + GCD_CKT_150NS, 0x657, 0x1, +#ifdef GCD_ENABLE_SCRAMBLE + TRUE, TRUE, TRUE, TRUE ); +#else // GCD_ENABLE_SCRAMBLE + FALSE, FALSE, FALSE, FALSE ); +#endif // GCD_ENABLE_SCRAMBLE + + GCDi_GenCtrl( &ctrls->gWriteRomRegs, GCD_RW_WRITE, + GCD_PAGE_1, + GCD_CKT_150NS, 0x21, 0x1, +#ifdef GCD_ENABLE_SCRAMBLE + TRUE, TRUE, TRUE, TRUE ); +#else // GCD_ENABLE_SCRAMBLE + FALSE, FALSE, FALSE, FALSE ); +#endif // GCD_ENABLE_SCRAMBLE + } + + initialized = TRUE; + } +} + + +/*---------------------------------------------------------------------------* + Name: GCD_SetPrimarySlot + + Description: set primary game card slot + + Arguments: primary slot + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_SetPrimarySlot( u8 slot ) +{ + if ( slot <= 1 ) + { + reg_MI_MC_SWP = (u8)(slot * REG_MI_MC_SWP_E_MASK); + } +} + +/*---------------------------------------------------------------------------* + Name: GCD_GetPrimarySlot + + Description: get primary game card slot + + Arguments: None + + Returns: primary slot + *---------------------------------------------------------------------------*/ +u8 GCD_GetPrimarySlot( void ) +{ + return (u8)((reg_MI_MC_SWP & REG_MI_MC_SWP_E_MASK) >> REG_MI_MC_SWP_E_SHIFT); +} + + +/*---------------------------------------------------------------------------* + Name: GCDi_SendtoPxi + + Description: send data via PXI + + Arguments: data : data to send + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SendtoPxi(u32 data) +{ + while (PXI_SendWordByFifo(PXI_FIFO_TAG_GCD, data, FALSE) != PXI_FIFO_SUCCESS) + { + SVC_WaitByLoop(1); + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_CallbackForReset + + Description: callback to receive data from PXI + + Arguments: tag : tag from PXI (unused) + data : data from PXI + err : error bit (unused) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_CallbackForReset(PXIFifoTag tag, u32 data, BOOL err) +{ +#pragma unused( tag, err ) + GCDPxiCmd pxi; + pxi.raw = data; + + if (pxi.e.cmd == GCD_PXI_COMMAND_RESET) + { +#ifdef SDK_ARM7 + GCD_Reset( (GCDSlot)pxi.e.slot, pxi.e.param ); + //---- send message to ARM9 + GCDi_SendtoPxi( GCD_PXI_COMMAND_RESET ); +#endif // SDK_ARM7 + + GCDi_Work[pxi.e.slot].isPxiDone = TRUE; + } + else + { +#ifndef SDK_FINALROM + OS_Panic("illegal GCD pxi command."); +#else + OS_Panic(""); +#endif + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_CallbackForResetAll + + Description: callback to receive data from PXI + + Arguments: tag : tag from PXI (unused) + data : data from PXI + err : error bit (unused) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_CallbackForResetAll(PXIFifoTag tag, u32 data, BOOL err) +{ +#pragma unused( tag, err ) + GCDPxiCmd pxi; + pxi.raw = data; + + if (pxi.e.cmd == GCD_PXI_COMMAND_RESET) + { +#ifdef SDK_ARM7 + GCD_ResetAll( pxi.e.param ); + //---- send message to ARM9 + GCDi_SendtoPxi( GCD_PXI_COMMAND_RESET ); +#endif // SDK_ARM7 + + GCDi_Work[GCD_PRIMARY_SLOT].isPxiDone = TRUE; + GCDi_Work[GCD_SECONDARY_SLOT].isPxiDone = TRUE; + } + else + { +#ifndef SDK_FINALROM + OS_Panic("illegal GCD pxi command."); +#else + OS_Panic(""); +#endif + } +} + + +/*---------------------------------------------------------------------------* + Name: GCDi_GetExistingSlots + + Description: get enabled slots + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_GetExistingSlots( GCDSlot* start, GCDSlot* end ) +{ + if ( GCD_IsExisting( GCD_PRIMARY_SLOT ) ) + { + *start = GCD_PRIMARY_SLOT; + if ( GCD_IsExisting( GCD_SECONDARY_SLOT ) ) + { + *end = GCD_SECONDARY_SLOT; + } + else + { + *end = GCD_PRIMARY_SLOT; + } + } + else + { + *start = GCD_SECONDARY_SLOT; + if ( GCD_IsExisting( GCD_SECONDARY_SLOT ) ) + { + *end = GCD_SECONDARY_SLOT; + } + else + { + *end = GCD_NO_SLOT; + } + } +} + + +/*---------------------------------------------------------------------------* + Name: GCD_Reset + + Description: reset game card + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_Reset( GCDSlot slot, u32 chat_cycles ) +{ +#ifdef SDK_ARM9 +#pragma unused( chat_cycles, slot ) + + OSIntrMode enabled; + OSIrqMask lastIE; + BOOL lastIME; + + GCDPxiCmd pxi; + GCDi_Work[GCD_PRIMARY_SLOT].isPxiDone = FALSE; + GCDi_Work[GCD_SECONDARY_SLOT].isPxiDone = FALSE; + + lastIE = OS_EnableIrqMask(OS_IE_SPFIFO_RECV); + lastIME = OS_EnableIrq(); + enabled = OS_EnableInterrupts(); + + //---- setting PXI + PXI_Init(); + while (!PXI_IsCallbackReady(PXI_FIFO_TAG_GCD, PXI_PROC_ARM7)) + { + } + PXI_SetFifoRecvCallback(PXI_FIFO_TAG_GCD, GCDi_CallbackForReset); + + pxi.e.cmd = GCD_PXI_COMMAND_RESET; + pxi.e.param = chat_cycles; + pxi.e.slot = (u32)slot; + + //---- send message to ARM7 + GCDi_SendtoPxi( pxi.raw ); + + while ( !( GCDi_Work[GCD_PRIMARY_SLOT].isPxiDone == TRUE && + GCDi_Work[GCD_SECONDARY_SLOT].isPxiDone == TRUE ) ) + { + } + + (void)OS_RestoreIrq(lastIME); + (void)OS_SetIrqMask(lastIE); + (void)OS_RestoreInterrupts(enabled); + + PXI_SetFifoRecvCallback(PXI_FIFO_TAG_GCD, NULL); + + GCDi_Enable( slot ); + +#else // SDK_ARM7 + + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + + reg_MI_MCCHAT = (u16)chat_cycles; + + OS_SpinWait( chat_cycles * GCD_CHATTERING_CYCLES ); + + if ( !GCD_IsExisting( slot ) ) + { + return; + } + + GCDi_Enable( slot ); + + if ( GCD_GetDetectMode( slot ) != 0 ) + { + GCD_SetDetectMode( slot, 3 ); + + while ( GCD_GetDetectMode( slot ) != 0 ) + { + } + } + + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + + GCD_SetDetectMode( slot, 1 ); + + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + + GCD_SetDetectMode( slot, 2 ); + + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + + *cnt1 = REG_MI_MCCNT1_RESB_MASK; // preset + + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + +#endif // SDK_ARM7 +} + +/*---------------------------------------------------------------------------* + Name: GCD_ResetAll + + Description: reset game cards + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ResetAll( u32 chat_cycles ) +{ +#ifdef SDK_ARM9 +#pragma unused( chat_cycles ) + + GCDWork *gw = &GCDi_Work[GCD_PRIMARY_SLOT]; + OSIntrMode enabled; + OSIrqMask lastIE; + BOOL lastIME; + + GCDSlot slot; + GCDPxiCmd pxi; + gw->isPxiDone = FALSE; + + lastIE = OS_EnableIrqMask(OS_IE_SPFIFO_RECV); + lastIME = OS_EnableIrq(); + enabled = OS_EnableInterrupts(); + + //---- setting PXI + PXI_Init(); + while (!PXI_IsCallbackReady(PXI_FIFO_TAG_GCD, PXI_PROC_ARM7)) + { + } + PXI_SetFifoRecvCallback(PXI_FIFO_TAG_GCD, GCDi_CallbackForResetAll); + + pxi.e.cmd = GCD_PXI_COMMAND_RESET; + pxi.e.param = chat_cycles; + pxi.e.slot = (u32)NULL; + + //---- send message to ARM7 + GCDi_SendtoPxi( pxi.raw ); + + while (gw->isPxiDone == FALSE) + { + } + + (void)OS_RestoreIrq(lastIME); + (void)OS_SetIrqMask(lastIE); + (void)OS_RestoreInterrupts(enabled); + + PXI_SetFifoRecvCallback(PXI_FIFO_TAG_GCD, NULL); + + for (slot=GCD_PRIMARY_SLOT; slot<=GCD_SECONDARY_SLOT; slot++) + { + GCDi_Enable( slot ); + } + +#else // SDK_ARM7 + + GCDSlot slot, start, end; + + reg_MI_MCCHAT = (u16)chat_cycles; + + OS_SpinWait( chat_cycles * GCD_CHATTERING_CYCLES ); + + GCDi_GetExistingSlots( &start, &end ); + + for (slot=start; slot<=end; slot++) + { + GCDi_Enable( slot ); + + if ( GCD_GetDetectMode( slot ) != 0 ) + { + GCD_SetDetectMode( slot, 3 ); + + while ( GCD_GetDetectMode( slot ) != 0 ) + { + } + } + } + + if ( end != GCD_NO_SLOT ) + { + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + } + + for (slot=start; slot<=end; slot++) + { + GCD_SetDetectMode( slot, 1 ); + } + + if ( end != GCD_NO_SLOT ) + { + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + } + + for (slot=start; slot<=end; slot++) + { + GCD_SetDetectMode( slot, 2 ); + } + + if ( end != GCD_NO_SLOT ) + { + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + } + + for (slot=start; slot<=end; slot++) + { + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + *cnt1 = REG_MI_MCCNT1_RESB_MASK; // preset + } + + if ( end != GCD_NO_SLOT ) + { + OS_SpinWait( OS_MSEC_TO_CPUCYC( 50 ) ); + } + +#endif // SDK_ARM7 +} + +/*---------------------------------------------------------------------------* + Name: GCDi_LoadSecure + + Description: load secure area + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ + +static BOOL isCtrApp[2]; +static BOOL isDsApp[2]; + + +/*************************************************** + + ***************************************************/ + +BOOL GCDi_IsDsApp( GCDSlot slot ) +{ + return isDsApp[slot]; +} + +static const u8 dsNinLogo[] = { +0x24,0xff,0xae,0x51,0x69,0x9a,0xa2,0x21,0x3d,0x84,0x82,0x0a,0x84,0xe4,0x09,0xad, +0x11,0x24,0x8b,0x98,0xc0,0x81,0x7f,0x21,0xa3,0x52,0xbe,0x19,0x93,0x09,0xce,0x20, +0x10,0x46,0x4a,0x4a,0xf8,0x27,0x31,0xec,0x58,0xc7,0xe8,0x33,0x82,0xe3,0xce,0xbf, +0x85,0xf4,0xdf,0x94,0xce,0x4b,0x09,0xc1,0x94,0x56,0x8a,0xc0,0x13,0x72,0xa7,0xfc, +0x9f,0x84,0x4d,0x73,0xa3,0xca,0x9a,0x61,0x58,0x97,0xa3,0x27,0xfc,0x03,0x98,0x76, +0x23,0x1d,0xc7,0x61,0x03,0x04,0xae,0x56,0xbf,0x38,0x84,0x00,0x40,0xa7,0x0e,0xfd, +0xff,0x52,0xfe,0x03,0x6f,0x95,0x30,0xf1,0x97,0xfb,0xc0,0x85,0x60,0xd6,0x80,0x25, +0xa9,0x63,0xbe,0x03,0x01,0x4e,0x38,0xe2,0xf9,0xa2,0x34,0xff,0xbb,0x3e,0x03,0x44, +0x78,0x00,0x90,0xcb,0x88,0x11,0x3a,0x94,0x65,0xc0,0x7c,0x63,0x87,0xf0,0x3c,0xaf, +0xd6,0x25,0xe4,0x8b,0x38,0x0a,0xac,0x72,0x21,0xd4,0xf8,0x07,0x56,0xcf +}; + +static BOOL IsDsApp( GCDSlot slot ) +{ + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + BOOL isDsNinLogo = TRUE; + int i; + + isDsApp[slot] = FALSE; + + for ( i=0; il.nintendoLogo)[i] ) + { + isDsNinLogo = FALSE; + break; + } + } + if ( isDsNinLogo ) + { + isDsApp[slot] = TRUE; + } + + return isDsApp[slot]; +} + +/*************************************************** + + ***************************************************/ +static void SetVAE( GCDSlot slot, GCDCmd64* op ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + op->dw |= ((u64)(sec->va) << GCDOP_N_VAE_SHIFT) & GCDOP_N_VAE_MASK; +} + +static void SetVBI( GCDSlot slot, GCDCmd64* op ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + op->dw |= sec->vb; + sec->vb >>= GCDOP_N_VBI_SHIFT; +} + +static void SetVA( GCDSlot slot, GCDCmd64* op ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + op->dw |= ((u64)(sec->va) << GCDOP_S_VA_SHIFT) & GCDOP_S_VA_MASK; +} + +static void SetVB( GCDSlot slot, GCDCmd64* op ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + op->dw |= sec->vb & GCDOP_S_VB_MASK; + sec->vb++; +} + +static void SetDummyVC( GCDSlot slot, GCDCmd64* op ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + op->dw |= ((u64)(sec->vc_dummy) << GCDOP_S_VC_SHIFT) & GCDOP_S_VC_MASK; +} + +static void SetVD( GCDSlot slot, GCDCmd64* op ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + op->dw |= ((u64)(sec->vd) << GCDOP_S_VD_SHIFT) & GCDOP_S_VD_MASK; +} + +static void GCDi_GenVA_VB_VD( GCDSlot slot ) +{ + GCDHeader* fh = GCDi_GetRomHeaderAddr( slot ); + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + + sec->va = fh->sign.raw[0]; + sec->vb = fh->sign.raw[1]; + sec->vd = fh->sign.raw[2]; + sec->vc_dummy = fh->sign.raw[3]; + + EncryptByBlowfish(&sec->blowfishCardTable, &sec->va, &sec->vb); + EncryptByBlowfish(&sec->blowfishCardTable, &sec->vd, &sec->vc_dummy); +} + +// TWLFIRM_DSCARD_DEV + +#ifndef FIRM_FORCE_DEBUGGER + +void GCDi_InitCardOpBlowfish( GCDSlot slot ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + const BLOWFISH_CTX *blowfishInitTablep = &GCDi_BlowfishInitTableGCDFIRM; + BLOWFISH_CTX *tableBufp = &sec->blowfishCardTable; + + MI_CpuCopyFast( (void*)blowfishInitTablep, (void *)tableBufp, sizeof(BLOWFISH_CTX) ); + InitBlowfish( tableBufp, &((u8*)GCDi_HeaderBuf[slot])[0xc], 4 ); +} + +void GCDi_InitSecureParam( GCDSlot slot, BOOL twl_ex ) +{ + GCDRomHeaderDS *rh = GCDi_GetRomHeaderAddr( slot ); + u32 code = rh->initialCode; + + if ( twl_ex ) + { + rh->initialCode = 'ALWT'; + } + +#ifdef FIRM_FORCE_FIRMBLOWFISH + GCDi_InitCardOpBlowfish( slot ); +#else // FIRM_FORCE_FIRMBLOWFISH + GCDi_InitCardOpBlowfishDS( slot ); +#endif // FIRM_FORCE_FIRMBLOWFISH + + rh->initialCode = code; + + GCDi_GenVA_VB_VD( slot ); // VA & VB & VD +} + +void GCDi_InitPngIntf( GCDSlot slot ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + +#define PNA_INDEX (((u32)GCDi_GetRomHeaderAddr( slot )) + 0x12) // PNAe[uECfbNX +static u32 default_pnB_l = 0x879b9b05; +static u8 default_pnB_h = 0x5c; +static u8 default_pnA_l_1 = 0x60; +static u8 default_pnA_l_0_table[8] = { 0xe8, 0x4d, 0x5a, 0xb1, 0x17, 0x8f }; + + u32 pnA_l; + u8 pnA_h; + + pnA_l = sec->vd <<15 + | default_pnA_l_0_table[(*(vu16 *)PNA_INDEX & 0x0700) >>8] | default_pnA_l_1 <<8; + pnA_h = (u8)((sec->vd >>(32-15)) & 0x7f); + + GCDi_SetPngIntf( slot, pnA_l, pnA_h, default_pnB_l, default_pnB_h ); +} + +#endif // FIRM_FORCE_DEBUGGER + +/*************************************************** + + ***************************************************/ +static void GCDi_SetPngIntf( GCDSlot slot, u32 pnA_l, u8 pnA_h, u32 pnB_l, u8 pnB_h ) +{ + REGType32v* cnt1 = GCDi_SelectRegAddr( slot, REG_MCCNT1_ADDR ); + REGType32v* scra_l = GCDi_SelectRegAddr( slot, REG_MCSCRA_L_ADDR ); + REGType8v* scra_h = GCDi_SelectRegAddr( slot, REG_MCSCRA_H_ADDR ); + REGType32v* scrb_l = GCDi_SelectRegAddr( slot, REG_MCSCRB_L_ADDR ); + REGType8v* scrb_h = GCDi_SelectRegAddr( slot, REG_MCSCRB_H_ADDR ); + + // omlݒ + + GCDi_WaitCtrl( slot ); + + *scra_l = pnA_l; + *scra_h = pnA_h; + + *scrb_l = pnB_l; + *scrb_h = pnB_h; + + *cnt1 = REG_MI_MCCNT1_A_SCR_MASK | REG_MI_MCCNT1_A_SE_MASK | REG_MI_MCCNT1_A_DS_MASK | REG_MI_MCCNT1_A_RESB_MASK; + + GCDi_WaitCtrl( slot ); + + // f[^XNuݒ + GCDi_Work[slot].ctrls.sSendOnlyOpRegs.scramble |= REG_MI_MCCNT1_A_SE_MASK | REG_MI_MCCNT1_A_DS_MASK; +} + + +void GCDi_DecryptObjectFile( GCDSlot slot ) +{ + if ( GCDi_IsDsApp( slot ) ) + { + } +} + +/*************************************************** + + ***************************************************/ +static void ReadCardAsync4Secure_1( GCDSlot slot, void *romp ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + if ( GCDi_SharedWork[slot].nCardID & GCD_ROMID_1TROM_MASK ) + { + // 3Dpݒ + { + ctrls->gcdRegs->ctrl &= ~REG_MI_MCCNT1_PC_MASK; + ctrls->gcdRegs->ctrl |= GCD_PAGE_1; + } + } + ctrls->gcdOp.dw = GCDOP_S_OP_RD_SEGMENT // R}hݒ + | (((u64)romp/GCD_SECURE_SEGMENT_SIZE) << GCDOP_S_VC_SHIFT); + + gw->oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + SetVA( slot, &ctrls->gcdOp ); + Encrypt2SetTimer4Secure( slot, ctrls ); + + if ( (GCDi_SharedWork[slot].nCardID & GCD_ROMID_1TROM_MASK) == 0 ) + { + ctrls->ltckReq = TRUE; + } +} + +/*************************************************** + + ***************************************************/ +static void ReadCardAsync4Secure_2( GCDSlot slot ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + + /* CardTimerIntr4Secure(void)̂ */ + s32 oneShotSize; + s32 offset; + + // ZOgEɂ + // 3D1ZOg8y[Wɕēǂ + do { + oneShotSize = gw->oneShotSize; + offset = sec->segmentOffset + sec->blockOffset; + + GCDi_ReadSecureModeRomCore( slot, gw->ramp + offset, oneShotSize, ctrls ); + + gw->restSize -= oneShotSize; + sec->blockOffset += oneShotSize; + } + while( gw->restSize % GCD_SECURE_SEGMENT_SIZE ); +} + +/*************************************************** + + ***************************************************/ +u8 GCDi_SegmentIndexTable4Secure[] = +{ + (0<<6)|(1<<4)|(3<<2)|(2<<0), (0<<6)|(2<<4)|(1<<2)|(3<<0), (0<<6)|(2<<4)|(3<<2)|(1<<0), (0<<6)|(3<<4)|(1<<2)|(2<<0), + (1<<6)|(0<<4)|(2<<2)|(3<<0), (1<<6)|(2<<4)|(0<<2)|(3<<0), (1<<6)|(3<<4)|(0<<2)|(2<<0), (1<<6)|(3<<4)|(2<<2)|(0<<0), + (2<<6)|(1<<4)|(0<<2)|(3<<0), (2<<6)|(1<<4)|(3<<2)|(0<<0), (2<<6)|(3<<4)|(0<<2)|(1<<0), (2<<6)|(3<<4)|(1<<2)|(0<<0), + (3<<6)|(0<<4)|(1<<2)|(2<<0), (3<<6)|(0<<4)|(2<<2)|(1<<0), (3<<6)|(1<<4)|(2<<2)|(0<<0), (3<<6)|(2<<4)|(0<<2)|(1<<0), +}; + +/* + DCB 4_0132, 4_0213, 4_0231, 4_0312 ; - 4_0123, 4_0321 + DCB 4_1023, 4_1203, 4_1302, 4_1320 ; - 4_1032, 4_1230 + DCB 4_2103, 4_2130, 4_2301, 4_2310 ; - 4_2013, 4_2031 + DCB 4_3012, 4_3021, 4_3120, 4_3201 ; - 4_3102, 4_3210 +*/ + +void GCDi_ReadCardSegmentAsync4Secure( GCDSlot slot, BOOL twl_ex ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + s16 *blockOffsetp = &sec->blockOffset; + s16 *segmentOffsetp = &sec->segmentOffset; + s16 *tblShiftp = &sec->segmentTblShift; + s32 diffSegmentNo; + s32 offset; + + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + +// GCDi_WaitCtrl(); + + GCDi_SecureWork[slot].segmentTblp = &(((u8 *)GCDi_SegmentIndexTable4Secure)[GCDi_SecureWork[slot].vd >>28]); // ZOge[uݒ + GCDi_SecureWork[slot].numSecureSegment = GCD_SECURE_AREA_SIZE / GCD_SECURE_SEGMENT_SIZE; // SECUREZOg 1segment 4096 + + ctrls->gcdRegs = &ctrls->sReadRomRegs; + gw->romp = GCD_SECURE_AREA_OFFSET; + if ( !twl_ex ) + { + gw->ramp = (void*)GCDi_SecureAreaBuf[slot]; + } + else + { + gw->ramp = (void*)GCDi_Secure2AreaBuf[slot]; + } + gw->restSize = sizeof( GCDi_SecureAreaBuf[slot] ); + gw->oneShotSize = GCDi_GetOneShotSizeFromCtrl( ctrls->gcdRegs->ctrl ); + + sec->secureSize = gw->restSize; + + do { + // SECURË𒴂Ȃ悤ɒ + while ((diffSegmentNo = ((*sec->segmentTblp) >>*tblShiftp) & 0x3) >= sec->numSecureSegment) + *tblShiftp += 2; + + *segmentOffsetp = (s16)(GCD_SECURE_SEGMENT_SIZE * diffSegmentNo); // ZOgItZbg Zbg + *blockOffsetp = 0; // ubNItZbg NA + + offset = *segmentOffsetp + *blockOffsetp; + + ReadCardAsync4Secure_1( slot, (u8*)gw->romp + offset ); + ReadCardAsync4Secure_2( slot ); + + *tblShiftp += 2; + *tblShiftp &= 0x7; + } + while( gw->restSize > 0 ); +} + + +/*---------------------------------------------------------------------------* + Name: GCD_SendOnlyCardOpCore + + Description: send only rom command + sync version + + Arguments: ctrls : rom control + + Returns: None + *---------------------------------------------------------------------------*/ + +#define AddLatency2ToLatency1(param) \ + ( (((param) & CARD_LATENCY2_CYCLES_MASK) \ + >> CARD_LATENCY2_CYCLES_SHIFT) \ + + ((param) & ~CARD_LATENCY2_CYCLES_MASK) \ + ) + + +static void Encrypt2SetTimer4Secure( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + GCDSecureWork* sec = &GCDi_SecureWork[slot]; + GCDSharedWork* sh = &GCDi_SharedWork[slot]; + + SetVB( slot, &ctrls->gcdOp ); // VB Zbg + + //GCDi_SecureWork.paramBak = *paramp; // ÍÕobvAbv + // my_memcopy((void *)paramp, (void *)&(GCDi_SecureWork.paramBak),sizeof(CardCtrlParam)); // ÍÕobvAbv + + // R}hÍ + EncryptByBlowfish( &sec->blowfishCardTable, &((u32*)&ctrls->gcdOp)[1], (u32*)&ctrls->gcdOp ); + + // 3DpvR}hs + if ( sh->nCardID & GCD_ROMID_1TROM_MASK ) { + GCDCtrlRegs *preRegs = ctrls->gcdRegs; + ctrls->gcdRegs = &ctrls->sSendOnlyOpRegs; + GCD_SendOnlyCardOpCore( slot, ctrls ); + ctrls->gcdRegs = preRegs; + + OS_SpinWait( OS_MSEC_TO_CPUCYC(30) ); /* wait 27 milli sec. for 3D-MEMROY? */ + } +} + + +static void GCDi_SendOnlyCardSecureOpCore( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + GCDCtrlRegs *regs = ctrls->gcdRegs; + + // CeVQCeVP։Z +#if 0 + paramp->cardCnt = AddLatency2ToLatency1(GetCardCnt4Secure()) + | CARD_READ_MODE | CARD_0_PAGE + | CARD_START | CARD_RESET_HI; +#endif + + SetDummyVC( slot, &ctrls->gcdOp ); + Encrypt2SetTimer4Secure( slot, ctrls ); + + if ( (GCDi_SharedWork[slot].nCardID & GCD_ROMID_1TROM_MASK) == 0 ) { + ctrls->gcdRegs->ctrl |= GCD_LTCK_ENABLE; // }XNROMpݒF CeVԂɃNbN +// ctrls->ltckReq = TRUE; + } + GCD_SendOnlyCardOpCore( slot, ctrls ); +} + + +/*************************************************** + + ***************************************************/ +void GCDi_ChangeIntoSecureMode( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->nSendOnlyOpRegs; + ctrls->gcdOp.dw = GCDOP_N_OP_CHG_MODE; // R}hݒ + SetVAE( slot, &ctrls->gcdOp ); + SetVBI( slot, &ctrls->gcdOp ); + + GCD_SendOnlyCardOpCore( slot, ctrls ); +} + +void GCDi_ChangeIntoSecure2Mode( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->nSendOnlyOpRegs; + ctrls->gcdOp.dw = GCDOP_N_OP_CHG2_MODE; // R}hݒ + SetVAE( slot, &ctrls->gcdOp ); + SetVBI( slot, &ctrls->gcdOp ); + + GCD_SendOnlyCardOpCore( slot, ctrls ); +} + + +void GCDi_SendPngON( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->sSendOnlyOpRegs; + ctrls->gcdOp.dw = GCDOP_S_OP_PNG_ON; // R}hݒ + SetVD( slot, &ctrls->gcdOp ); + + GCDi_SendOnlyCardSecureOpCore( slot, ctrls ); +} + +void GCDi_SendPngOFF( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->sSendOnlyOpRegs; + ctrls->gcdOp.dw = GCDOP_S_OP_PNG_OFF; // R}hݒ + SetVA( slot, &ctrls->gcdOp ); + + GCDi_SendOnlyCardSecureOpCore( slot, ctrls ); +} + +void GCDi_ChangeIntoGameMode( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->sSendOnlyOpRegs; + ctrls->gcdOp.dw = GCDOP_S_OP_CHG_MODE; // R}hݒ + SetVA( slot, &ctrls->gcdOp ); + + GCDi_SendOnlyCardSecureOpCore( slot, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_SendOnlyCardNormalOpCore + + Description: send only rom command + sync version + + Arguments: ctrls : rom control + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCD_SendOnlyCardNormalOpCore( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + ctrls->gcdRegs = &ctrls->nSendOnlyOpRegs; + + GCD_SendOnlyCardOpCore( slot, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCD_SendOnlyCardSecureOpCore + + Description: send only rom command + sync version + + Arguments: ctrls : rom control + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCD_SendOnlyCardSecureOpCore( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + ctrls->gcdRegs = &ctrls->sSendOnlyOpRegs; + + if ( ctrls->ltckReq ) + { + ctrls->gcdRegs->ctrl |= GCD_LTCK_ENABLE; // }XNROMpݒF CeVԂɃNbN + ctrls->ltckReq = FALSE; + } + + GCD_SendOnlyCardOpCore( slot, ctrls ); +} + +/*************************************************** + + ***************************************************/ +static u32 GCDi_ReadSecureModeIDCore( GCDSlot slot, GCDRomCtrls *ctrls ) +{ + ctrls->gcdRegs = &ctrls->sIDRegs; + + if ( ctrls->ltckReq ) + { + ctrls->gcdRegs->ctrl |= GCD_LTCK_ENABLE; // }XNROMpݒF CeVԂɃNbN + ctrls->ltckReq = FALSE; + } + + return GCDi_ReadRomIDCore( slot, ctrls ); +} + +static void GCDi_ReadSecureModeRomCore( GCDSlot slot, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ + ctrls->gcdRegs = &ctrls->sReadRomRegs; + + if ( ctrls->ltckReq ) + { + ctrls->gcdRegs->ctrl |= GCD_LTCK_ENABLE; // }XNROMpݒF CeVԂɃNbN + ctrls->ltckReq = FALSE; + } + + GCDi_ReadRomCore( slot, ramp, size, ctrls ); +} + + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadSecureModeID + + Description: read rom ID on secure mode + sync version + + Arguments: None + + Returns: rom ID + *---------------------------------------------------------------------------*/ +u32 GCDi_ReadSecureModeID( GCDSlot slot ) +{ + GCDSharedWork* sh = &GCDi_SharedWork[slot]; + + if ( GCDi_IsSecureInitialized( slot ) == FALSE ) + { + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->sIDRegs; + ctrls->gcdOp.dw = GCDOP_S_OP_RD_ROM_ID; // R}hݒ + SetVA( slot, &ctrls->gcdOp ); + SetDummyVC( slot, &ctrls->gcdOp ); + Encrypt2SetTimer4Secure( slot, ctrls ); + + if ( (sh->nCardID & GCD_ROMID_1TROM_MASK) == 0 ) { + ctrls->ltckReq = TRUE; + } + sh->sCardID = GCDi_ReadSecureModeIDCore( slot, ctrls ); + DBG_PRINTF("%s %d CardID Secure 0x%08x\n",__FUNCTION__,__LINE__, sh->sCardID); + } + + return sh->sCardID; +} + +/*---------------------------------------------------------------------------* + Name: GCD_ReadNormalModeID + + Description: read rom ID on normal mode + sync version + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +u32 GCD_ReadNormalModeID( GCDSlot slot ) +{ + GCDSharedWork* sh = &GCDi_SharedWork[slot]; + + if ( GCDi_IsSecureInitialized( slot ) == FALSE ) + { + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->nIDRegs; + ctrls->gcdOp.dw = GCDOP_N_OP_RD_ROM_ID; // R}hݒ + + return GCDi_ReadRomIDCore( slot, ctrls ); + } else { + return sh->nCardID; + } +} + + +/*---------------------------------------------------------------------------* + Name: GCDi_LoadHeader + + Description: load header + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_LoadHeader( GCDSlot slot ) +{ + if ( GCDi_IsSecureInitialized( slot ) == FALSE ) + { + GCDSharedWork* sh = &GCDi_SharedWork[slot]; + + // load table from dev flash into ASIC + GCDi_LoadTable( slot ); + + // read ROM header + GCD_ReadNormalModeRom( slot, 0, GCDi_HeaderBuf[slot], sizeof( GCDi_HeaderBuf[slot] ) ); + + if ( ! IsDsApp( slot ) ) + { + MI_CpuFillFast( GCDi_HeaderBuf[slot], 0, sizeof( GCDi_HeaderBuf[slot] ) ); + } + + // read ROM-ID + sh->nCardID = GCD_ReadNormalModeID( slot ); + DBG_PRINTF("%s %d CardID Normal 0x%08x\n",__FUNCTION__,__LINE__, sh->nCardID); + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_LoadHeaderAll + + Description: load header + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_LoadHeaderAll( void ) +{ + GCDSlot slot, start, end; + + GCDi_GetExistingSlots( &start, &end ); + + if ( GCDi_IsSecureInitialized( GCD_PRIMARY_SLOT ) == FALSE ) + { + for (slot=start; slot<=end; slot++) + { + // load table from dev flash into ASIC + GCDi_LoadTableAsync( slot ); + } + + for (slot=start; slot<=end; slot++) + { + GCD_WaitRomAsync( slot ); + + // read short ROM header + GCDi_ReadShortHeaderAsync( slot, GCDi_HeaderBuf[slot] ); + } + + for (slot=start; slot<=end; slot++) + { + GCD_WaitRomAsync( slot ); + + if ( ! IsDsApp( slot ) ) + { + MI_CpuFillFast( GCDi_HeaderBuf[slot], 0, sizeof( GCDi_HeaderBuf[slot] ) ); + } + } + + for (slot=start; slot<=end; slot++) + { + // read ROM-ID + GCDSharedWork* sh = &GCDi_SharedWork[slot]; + sh->nCardID = GCD_ReadNormalModeID( slot ); + DBG_PRINTF("%s %d CardID Normal 0x%08x\n",__FUNCTION__,__LINE__, sh->nCardID); + + // read ROM header + GCD_ReadNormalModeRomAsync( slot, 0, GCDi_HeaderBuf[slot], sizeof( GCDi_HeaderBuf[slot] ) ); + } + + for (slot=start; slot<=end; slot++) + { + GCD_WaitRomAsync( slot ); + } + } +} + +/*---------------------------------------------------------------------------* + Name: GCDi_LoadTable + + Description: load table from dev flash into ASIC + sync version + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_LoadTable( GCDSlot slot ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->nLoadTableRegs; + ctrls->gcdOp.dw = GCDOP_N_OP_LD_TABLE; + + GCDi_ReadRomCore( slot, NULL, 0, ctrls ); +} + +static void GCDi_LoadTableCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ) +{ +#pragma unused( romp ) + + GCDi_ReadRomCore( slot, ramp, size, ctrls ); +} + +static void GCDi_LoadTableAsync( GCDSlot slot ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + ctrls->gcdRegs = &ctrls->nLoadTableRegs; + ctrls->gcdOp.dw = GCDOP_N_OP_LD_TABLE; + + gw->funcp = GCDi_LoadTableCore; + + GCD_SetInterrupt( slot, 0, GCDi_Secure2AreaBuf[slot], GCD_LOAD_TABLE_SIZE, gw ); + + gw->funcp( slot, gw->romp, gw->ramp, gw->oneShotSize, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadShortHeader + + Description: load table from dev flash into ASIC + sync version + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_ReadShortHeader( GCDSlot slot, void *ramp ) +{ + GCDRomCtrls *ctrls = &GCDi_Work[slot].ctrls; + + ctrls->gcdRegs = &ctrls->nReadShortHeaderRegs; + + GCDi_ReadNormalModeRomCore( slot, 0, ramp, GCD_ROM_PAGE_SIZE, ctrls ); +} + +static void GCDi_ReadShortHeaderAsync( GCDSlot slot, void *ramp ) +{ + GCDWork *gw = &GCDi_Work[slot]; + GCDRomCtrls *ctrls = &gw->ctrls; + + ctrls->gcdRegs = &ctrls->nReadShortHeaderRegs; + + gw->funcp = GCDi_ReadNormalModeRomCore; + + GCD_SetInterrupt( slot, 0, ramp, GCD_ROM_PAGE_SIZE, gw ); + + gw->funcp( slot, gw->romp, gw->ramp, gw->oneShotSize, ctrls ); +} + +/*---------------------------------------------------------------------------* + Name: GCDi_LoadSecure + + Description: load secure area + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void GCDi_LoadSecureCore( GCDSlot slot, BOOL twl_ex ) +{ + if ( GCDi_IsSecureInitialized( slot ) == FALSE ) + { + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + +#ifndef FIRM_FORCE_DEBUGGER + + GCDi_InitSecureParam( slot, twl_ex ); + +#endif // FIRM_FORCE_DEBUGGER + + if ( !twl_ex ) + { + GCDi_ChangeIntoSecureMode( slot ); + } + else + { + GCDi_ChangeIntoSecure2Mode( slot ); + } + +#ifdef FIRM_FORCE_DEBUGGER + + if ( !twl_ex ) + { + GCD_ReadNormalModeRom( slot, GCD_SECURE_AREA_OFFSET, GCDi_SecureAreaBuf[slot], sizeof( GCDi_SecureAreaBuf[slot] ) ); + } + else if ( rh->l.twlAreaOffset ) + { + GCD_ReadNormalModeRom( slot, (u32)rh->l.twlAreaOffset * GCD_TWL_AREA_ALIGN + GCD_SECURE2_AREA_OFFSET, + GCDi_Secure2AreaBuf[slot], sizeof( GCDi_Secure2AreaBuf[slot] ) ); + } + +#else // FIRM_FORCE_DEBUGGER + + GCDi_SendPngON( slot ); + GCDi_InitPngIntf( slot ); + + GCDi_ReadSecureModeID( slot ); + + GCDi_ReadCardSegmentAsync4Secure( slot, twl_ex ); + +#ifndef GCD_ENABLE_SCRAMBLE + GCDi_SendPngOFF( slot ); +#endif // GCD_ENABLE_SCRAMBLE + +#endif // FIRM_FORCE_DEBUGGER + + GCDi_ChangeIntoGameMode( slot ); + + // ÍIuWFNg̕ + if ( !twl_ex ) + { +#ifndef FIRM_FORCE_FIRMBLOWFISH + GCDi_DecryptObjectFileDS( slot ); +#endif // FIRM_FORCE_FIRMBLOWFISH + } + + if ( twl_ex || !rh->l.twlAreaOffset ) + { + GCDi_SecureInitialized[slot] = TRUE; + } + } +} + +static void GCDi_LoadSecure( GCDSlot slot ) +{ + GCDi_LoadSecureCore( slot, FALSE ); + +} + +static void GCDi_LoadSecure2( GCDSlot slot ) +{ + GCDi_LoadSecureCore( slot, TRUE ); + +} + +static void GCDi_LoadSecureAllCore( BOOL twl_ex ) +{ + GCDSlot slot, start, end; + + GCDi_GetExistingSlots( &start, &end ); + + if ( GCDi_IsSecureInitialized( GCD_PRIMARY_SLOT ) == FALSE ) + { + +#ifndef FIRM_FORCE_DEBUGGER + + for (slot=start; slot<=end; slot++) + { + GCDi_InitSecureParam( slot, twl_ex ); + } + +#endif // FIRM_FORCE_DEBUGGER + + if ( !twl_ex ) + { + for (slot=start; slot<=end; slot++) + { + GCDi_ChangeIntoSecureMode( slot ); + } + } + else + { + for (slot=start; slot<=end; slot++) + { + GCDi_ChangeIntoSecure2Mode( slot ); + } + } + +#ifdef FIRM_FORCE_DEBUGGER + + for (slot=start; slot<=end; slot++) + { + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + GCD_ReadNormalModeRomAsync( slot, GCD_SECURE_AREA_OFFSET, GCDi_SecureAreaBuf[slot], sizeof( GCDi_SecureAreaBuf[slot] ) ); + } + + for (slot=start; slot<=end; slot++) + { + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + GCD_WaitRomAsync( slot ); + + if ( rh->l.twlAreaOffset ) + { + GCD_ReadNormalModeRomAsync( slot, (u32)rh->l.twlAreaOffset * GCD_TWL_AREA_ALIGN + GCD_SECURE2_AREA_OFFSET, + GCDi_Secure2AreaBuf[slot], sizeof( GCDi_Secure2AreaBuf[slot] ) ); + } + } + + for (slot=start; slot<=end; slot++) + { + GCD_WaitRomAsync( slot ); + } + +#else // FIRM_FORCE_DEBUGGER + + for (slot=start; slot<=end; slot++) + { + GCDi_SendPngON( slot ); + } + + for (slot=start; slot<=end; slot++) + { + GCDi_InitPngIntf( slot ); + } + + for (slot=start; slot<=end; slot++) + { + GCDi_ReadSecureModeID( slot ); + } + + for (slot=start; slot<=end; slot++) + { + GCDi_ReadCardSegmentAsync4Secure( slot, twl_ex ); + } + +#ifndef GCD_ENABLE_SCRAMBLE + for (slot=start; slot<=end; slot++) + { + GCDi_SendPngOFF( slot ); + } +#endif // GCD_ENABLE_SCRAMBLE + +#endif // FIRM_FORCE_DEBUGGER + + for (slot=start; slot<=end; slot++) + { + GCDi_ChangeIntoGameMode( slot ); + } + + // ÍIuWFNg̕ + for (slot=start; slot<=end; slot++) + { + GCDRomHeader *rh = GCDi_GetRomHeaderAddr( slot ); + + if ( !twl_ex ) + { +#ifndef FIRM_FORCE_FIRMBLOWFISH + GCDi_DecryptObjectFileDS( slot ); +#endif // FIRM_FORCE_FIRMBLOWFISH + } + + if ( twl_ex || !rh->l.twlAreaOffset ) + { + GCDi_SecureInitialized[slot] = TRUE; + } + } + } +} + +static void GCDi_LoadSecureAll( void ) +{ + GCDi_LoadSecureAllCore( FALSE ); + +} + +static void GCDi_LoadSecure2All( void ) +{ + GCDi_LoadSecureAllCore( TRUE ); + +} + +// +BOOL GCDi_IsSecureInitialized( GCDSlot slot ) +{ + return GCDi_SecureInitialized[slot]; +} + diff --git a/build/libraries/gcd/common/gcdfirm_blowfish_table.c b/build/libraries/gcd/common/gcdfirm_blowfish_table.c new file mode 100644 index 0000000..ec61d6d --- /dev/null +++ b/build/libraries/gcd/common/gcdfirm_blowfish_table.c @@ -0,0 +1,288 @@ +/*---------------------------------------------------------------------------* + Project: TwlBrom - libraries - GCD + File: gcdfirm_blowfish_table.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include + + +const BLOWFISH_CTX GCDi_BlowfishInitTableGCDFIRM = { + + 0x7595a8ee, 0x84fff32d, 0x58f8aec6, 0x6f6444c2, + 0x10a6cfbc, 0xbee1b813, 0x88efabc3, 0xc72026cd, + 0xc00b913a, 0x9fb074c0, 0x56d4830f, 0x69abdee5, + 0xcf6e5ff2, 0xd7febe2f, 0x84f5d5e2, 0x73a1ccda, + 0x44205999, 0x74278f63, + + 0xf0907253, 0x1c95d48f, 0x7cdbce99, 0xa8b9508a, + 0x79379f9e, 0x129144fe, 0xd2b3554d, 0x72d702c6, + 0xce058143, 0x72b411b8, 0x9acf2ae7, 0x62c0d195, + 0x7d0861e5, 0x333ac8f6, 0xafc17b59, 0x7fabab12, + 0x5a20b8df, 0x43c908e1, 0xdf057b54, 0x65237d17, + 0x8988581c, 0x1d02cad9, 0xdde63c8a, 0x302fee12, + 0x0abedd9d, 0x586fb574, 0x10130aad, 0x0a1ead35, + 0xfe6f0870, 0x8cac4f02, 0x9c56ef2c, 0xc0ab9bcd, + 0x7faf9a52, 0xef822dcd, 0x2bc0fdc2, 0xde22a557, + 0xccf82867, 0x582a9d19, 0xd2790715, 0xdc8df689, + 0x250ca6e2, 0xfe35236d, 0x8648e2d6, 0xaa0bf6e7, + 0xd1240620, 0x413a5ea7, 0x4cf59143, 0x4f4f5472, + 0xa5f29a08, 0x1fff4e8f, 0x14f0ec2d, 0x47d6f42a, + 0x85b021f0, 0x7836f20a, 0xd908d0d7, 0xbdcc9dd5, + 0xa6ac0bfb, 0x96fb7daf, 0xb65476ff, 0xbde99b51, + 0xe8c84b8e, 0x72c88630, 0x3f8d0979, 0x5c1e45dc, + 0x7555b1db, 0x3edb5a90, 0xb07fac66, 0xf7316aba, + 0x84a088bd, 0xf0b2fb9d, 0x014b48e1, 0x6d0967e3, + 0xa38d60e4, 0x148eedf2, 0x81898864, 0xfe0d73aa, + 0x58c37bd5, 0x8ce2c345, 0x82951de7, 0x17be1aa6, + 0xbfe8ad1b, 0x4d6b4176, 0x3a0da43d, 0x50a4dcac, + 0x69f1282e, 0x16b49576, 0x6b521ffe, 0x67588174, + 0xb3de1d28, 0x06198cbd, 0xeea240ea, 0xd13e358e, + 0x3664b06c, 0x59f4e227, 0xb54122d3, 0x94bb71e3, + 0x0315fb94, 0x647301d6, 0x943f1f0d, 0x7a2aaec4, + 0x51bf88f7, 0x712c091a, 0x6d3b6e3e, 0x6eb24d52, + 0x9fc82ca4, 0x8ffc188e, 0xbe31140a, 0x1d3e5756, + 0xc574e16e, 0xb105a793, 0x94f658ec, 0x6ed4864c, + 0xb2bae3cf, 0xe342cf15, 0xf2bc4d27, 0x090334b1, + 0xc2632a42, 0x884f0092, 0xa59abd51, 0xe9d203f9, + 0x7d122257, 0x02a709aa, 0xac9fc39b, 0x4840beed, + 0x74be37a4, 0x24b9a4d3, 0x8178bca7, 0x606b85e5, + 0x1dcb46b2, 0xe6112060, 0xbd44008a, 0xd1be2964, + 0xcfcc5032, 0x74e10e43, 0x53fac5ab, 0x84a6e0a4, + 0x9080997a, 0xa31a0100, 0xcee21c1c, 0xebcee973, + 0x77e9a4c7, 0x3a261b9b, 0xce49ca16, 0xec3a432d, + 0x1410c1bf, 0x8d22c824, 0xb0018266, 0x7964e2e2, + 0xfcc6eb14, 0x12e6e035, 0xca689d0a, 0x5f9f39fc, + 0xbf14f7e9, 0x5d7813f2, 0x87347401, 0x1a107660, + 0xfeaa1bb7, 0x53ebb1a2, 0xfc47a457, 0xf71cde17, + 0x25379a36, 0xb2ed205d, 0x1225bf36, 0x14536bd4, + 0x31138cdf, 0xeeecb7f4, 0xbb6e5b19, 0x39877d0f, + 0x4366ac24, 0xfb13893c, 0x3a7039b2, 0x3a1b8037, + 0xfc668634, 0x0a3fb783, 0x50380526, 0x9c0e4b1a, + 0x462b9398, 0x0e6c7d2d, 0x689a929e, 0x715701e6, + 0x2e61d17d, 0x09da9145, 0xfb143ba1, 0x5b199259, + 0xc4e3a5ee, 0x0b4bda9a, 0xe18c526c, 0x73171c1a, + 0x1572a94b, 0x6d15b729, 0x71509e91, 0x571bc76e, + 0x8c721018, 0x1fcc1742, 0xa6602c75, 0x787f88a9, + 0x0598f9c4, 0x5addc61b, 0x8e9b7b41, 0x2f4daf72, + 0xd9f09e2a, 0xe76054ca, 0x28bc0b4e, 0x4a320c32, + 0xdf2b687e, 0x2cdffbcc, 0x77f16b69, 0x5d425665, + 0xcf207fd9, 0x2e4d166d, 0x46e57957, 0x37f50f39, + 0x6742b74a, 0xbb21df47, 0xe2df0964, 0x0dd6d989, + 0x6f635a6e, 0x8f05a457, 0x6e5dc010, 0xeae76f43, + 0x135c206a, 0x876bd938, 0x1ccbc607, 0xaf600e28, + 0x0daa4fe0, 0x95e0fe33, 0x093e44b1, 0x1d16b2ad, + 0x8d710ba2, 0x3ca3c1d9, 0x8f54a8e1, 0x7eb11ec8, + 0xcdb82a0e, 0xde1aff6d, 0x68ae2ce2, 0x80e1ca3e, + 0x67d60c2c, 0xac6ad1da, 0x5330c802, 0x5f67a04d, + 0x5d6f3c9d, 0x1f4725b0, 0x094a4c69, 0x4c1dea21, + 0xfd09ced5, 0x270fc341, 0xf16081f5, 0x54dcbdb4, + 0x72a36bf5, 0xbeabc16a, 0xdd82bb02, 0xf0e75d20, + 0xea6a64b0, 0x85cb5c2c, 0xd53a5aaa, 0x400f91d1, + + 0xc020695e, 0xa3d05c76, 0x8ac00446, 0xe0ebe1ce, + 0x7ed2ca13, 0x7f41bbca, 0x09daffc0, 0x16d39c09, + 0xd417fe9e, 0x11fc4b36, 0x87b92111, 0x581cea89, + 0x6a51516d, 0xa691f994, 0x06e5c6ab, 0x81200780, + 0xe6ea60b7, 0x8d0967af, 0x32f81d79, 0x1bf63b78, + 0xeefe70bb, 0x74123b42, 0xf7345b16, 0x7aaa1388, + 0x0152a394, 0xb5463ea1, 0xe7968633, 0xf6b00f17, + 0xfee65926, 0xfac95f88, 0xf7788838, 0x404d27c8, + 0x0a40725a, 0xac948618, 0xb2fb966f, 0x730b40c3, + 0x3fa5b3a0, 0x2a4a7b57, 0xe2ee0994, 0xe2662b03, + 0xa517c253, 0x5fcd9ac2, 0x7cf1861a, 0xfb9c6d92, + 0x726cfcf6, 0x6bc20855, 0xe03c7757, 0x15f7aefc, + 0x0490f4b2, 0xc5c49d9e, 0xd91bc403, 0x84799016, + 0x5e8b5d2f, 0xdd8aef68, 0x4225b87a, 0xd3912770, + 0x56f84df2, 0xe191d469, 0xb6306514, 0xf66b7461, + 0xaa528b42, 0xd7d8d211, 0x0409e809, 0x3e995489, + 0x984e2cd0, 0x21da8726, 0xa901dcce, 0xc59ed627, + 0xa508a395, 0xe67e1c10, 0x7786c594, 0x7db49c12, + 0xf3a048fa, 0x6c03c939, 0x5fe538b2, 0xe68d94f1, + 0x74116818, 0xbc041b38, 0x37e9f59f, 0xd5f0d6b4, + 0x3abedc09, 0xf2277fcf, 0xb1c090ca, 0x179fbeaf, + 0x6799f269, 0x4ef2e1ba, 0x9a8530fe, 0xe629bad3, + 0xef2d1806, 0xefe0d41a, 0x8fbd8038, 0xae93b3b8, + 0xb96af69a, 0xe976f30a, 0x3735edf2, 0xa10aab80, + 0x572bc346, 0xd9d352e5, 0xa88382fb, 0xc36d9a6a, + 0x622169f5, 0x2b668147, 0xc68d8e94, 0xd83725df, + 0x75ca8dc0, 0xe0fef07d, 0x3020348f, 0xd7e941c5, + 0x0f18da00, 0x9909caca, 0x1b5f4c03, 0x611ba66e, + 0xe3c25c8d, 0x87fe1654, 0x20ed099e, 0x2eef6251, + 0xf8b62747, 0xa8863716, 0x2e654e0a, 0x17985515, + 0xd121a7f0, 0xf0545a5b, 0xed9f9da3, 0xfe607b10, + 0x3afc599b, 0xa3c13305, 0x9667a20a, 0xbd639f0c, + 0xe647e3a0, 0x0e1304b2, 0x26a31cec, 0xd1435273, + 0x33845341, 0xbe3383f5, 0x22e5e07f, 0xb516aed2, + 0xe7dad3c1, 0x7e0b2eec, 0x7709d235, 0x48923397, + 0x086b62a6, 0x05270843, 0x48073d32, 0x3e22db8e, + 0x7b0fd2eb, 0x9199531d, 0xa47e9efc, 0x76b1bf31, + 0xee7b6f31, 0xdc6de2c0, 0x120d4d2c, 0x1c7d1a8b, + 0xd9192142, 0x5251ce66, 0x26dd0acf, 0x18073f04, + 0x5901f0a3, 0xfc24fea0, 0xe9d4474b, 0xbbda7bdd, + 0x66cb45f6, 0x66137a90, 0xa010a036, 0xa3fff96c, + 0x61c8194f, 0x553e0b2b, 0x72b54de2, 0x59aeefe9, + 0xda01dab4, 0xdac48b91, 0xbba66e7a, 0xa3819de2, + 0x1f950fce, 0xa3c4d697, 0xc4e28dce, 0x530179ee, + 0xaa7cc068, 0x1b44146a, 0xb267d209, 0x984ff1be, + 0x90fd796b, 0xe0e42a5f, 0x36d033fb, 0x13c2f482, + 0x3b19a86d, 0xff0ad256, 0xf06acb47, 0x0d4fbfa0, + 0x53246fd3, 0xf9296dd5, 0x42bb5d4a, 0xd4d86e75, + 0x96442650, 0x0bdebc51, 0xb3cee98d, 0x188c83e2, + 0xbe632850, 0x9a0ce659, 0xc51250cd, 0x141b9f77, + 0x292844d4, 0xa8ce50d4, 0xe6f471a3, 0xe51b7ef9, + 0xece33b79, 0x1ec17a6a, 0x01a0125e, 0x09071e04, + 0xbfe72df4, 0x170ed1cf, 0x2fa259ac, 0x4821704f, + 0x95b82704, 0xcd1e0c6a, 0xb57a33ce, 0x057204fe, + 0x7617de6b, 0xaa72f1d5, 0x4b46d61a, 0xac797378, + 0x4984d9cf, 0x40726022, 0x2b425b5c, 0x4ca25dab, + 0xa0e23aa3, 0x4fe1527a, 0x6fd3b7ac, 0xeb47ba60, + 0xcde7c8b7, 0x9aef5d0f, 0x821674cd, 0xc258ea7d, + 0xa6a813a5, 0x93e88a84, 0x8f32d2e3, 0x58ae440d, + 0xc5799715, 0x425284d0, 0x1b696e64, 0x7d3ce93a, + 0xdad0f25c, 0xc4b0dd14, 0x7079e2e5, 0xa9e8e61d, + 0xfaf686b7, 0x1cf1b87b, 0x31ab43c7, 0xdc45d1bb, + 0x386cb6ec, 0xcad283f2, 0x4dccbfaf, 0x4934f28b, + 0x2fbc3dd4, 0x789b64f7, 0xb2e8918f, 0x506acbf7, + + 0x50a13360, 0xd128d4d3, 0xba687526, 0xc5474940, + 0x6bb5dfc7, 0xef9bdf1f, 0x92cc643b, 0xfb2ad4f0, + 0x4ff9410b, 0xb013c81e, 0x9fe69574, 0x5fed0d88, + 0xcfe87720, 0x09cddf06, 0x9e57696f, 0xc429dfb9, + 0x460c5dd2, 0x9b9e505b, 0xc012bcf6, 0xd955bdda, + 0x7310ed31, 0xcdaaebe2, 0xc9761ff6, 0x5de00f45, + 0x66a5e949, 0x45c5df1d, 0x96a38fab, 0x18939d5b, + 0x94015083, 0xd27b1379, 0xe10107e7, 0xdaef6ef8, + 0xaf8f83b3, 0xafd37029, 0x7d6803e0, 0x3a545055, + 0xfd419925, 0xb49fa25f, 0x533ad3f4, 0xc49f3fe4, + 0x9b9eb196, 0x2015408e, 0xd6f46485, 0xa8e66479, + 0x5b8866e1, 0xc97d478d, 0xb7fcb30a, 0xddefdff0, + 0x34afb94c, 0xa155d92f, 0xf53979b1, 0xf0cdd075, + 0xf25accae, 0xe4208afd, 0x5b11bb77, 0x37b337e4, + 0xa69da8be, 0x28a9ee86, 0xb284b30e, 0xc3527598, + 0xf423936e, 0x7e2e1d51, 0xcaf2613d, 0x7505391e, + 0x252d3dd5, 0x00d18203, 0x7ef4577e, 0x244e98a9, + 0xb73b5840, 0xb0f9c9ed, 0xa8d4bc23, 0xb7228243, + 0x241418d3, 0x39fd4429, 0xe8ab9b37, 0x3a74ecdf, + 0xbf99499c, 0x70c3eb26, 0xc6ac5d10, 0x7085410a, + 0x9bc5ca24, 0x37cf4d32, 0x5a407af1, 0x7f38c2af, + 0x6cf95726, 0x2934cce9, 0x478e4a5e, 0x86bccd71, + 0x46673804, 0x5cd7e9da, 0x601c0e47, 0x32f3c95c, + 0x98f3b207, 0x2a9f09f2, 0xa68e3b9b, 0xe0a67f44, + 0x8d4801eb, 0x0d650900, 0x2dbd9d8f, 0x9113fe47, + 0x5a317b0e, 0x3d5a8d71, 0xfbd60e45, 0x86f6eedc, + 0x3f77fec6, 0xe56a0bb2, 0x32ab5ef7, 0x2262c429, + 0x7ed387c6, 0x0087c87e, 0x6570e4b7, 0x648d80e1, + 0xc3bd761a, 0x5c3c0c47, 0x9ac5b07c, 0x6ecb158f, + 0x73e2d323, 0x5095435e, 0x21a97ee4, 0x0c599519, + 0x1f6c6441, 0xee52efd7, 0xbd886ee2, 0x66ec3c66, + 0x0e42820c, 0xb4f244cb, 0xa56f2efc, 0xc0302f16, + 0xf9b795aa, 0x60a00f3f, 0xa83fb0a9, 0xe9b2f724, + 0xa3c3b44f, 0x8151cc80, 0x2ae0e99c, 0x0cb0ff00, + 0x2e9a646d, 0x991d2cd6, 0xef2bf16b, 0x0a610ad2, + 0x1674ea07, 0x567fcfe7, 0xf05ef5af, 0xdfdf47cb, + 0x6c3ebb59, 0x2f052cad, 0x4701ca04, 0x0c65164a, + 0xa285ecb3, 0x348fd20a, 0x7915f8ff, 0xdc269d33, + 0x74578f72, 0x763ced80, 0x53275951, 0x8c51eebd, + 0x6d8b4452, 0x5267c34e, 0xe9b7197b, 0x912800ab, + 0x10d207a4, 0x4238eaf7, 0x2171bd12, 0x9c7eff0b, + 0x251b79ff, 0x41bb7753, 0xecea6583, 0x031393e5, + 0x49a58fe9, 0x83bb7587, 0x4a2a3156, 0xa3ab8da7, + 0x38f774aa, 0xd3844d4e, 0x7cc81418, 0x894ca09d, + 0x341ade56, 0x9574d6a5, 0xd2299751, 0xdbd43293, + 0x253d53e8, 0x64005cc4, 0x813de56f, 0x631c3cda, + 0x931681bd, 0x77dd0ab8, 0x15d6b56f, 0x2a3106b1, + 0x603102bf, 0xfef29a3d, 0x648baa38, 0x470ae791, + 0x02e625ab, 0x04904d5d, 0x3b31cea4, 0xa9a2126d, + 0x76814575, 0x4c6a5511, 0xe2d7c619, 0x840d8ca5, + 0x4d15e8f8, 0x59256a95, 0xf1ed6a56, 0xb996efab, + 0x5da9c913, 0x7652bed8, 0xedbda0be, 0x59f81908, + 0xd1d45ed7, 0x00b5f876, 0x986b97e4, 0x0bf99862, + 0xf3a448c6, 0x05f92573, 0x9ab2c7c4, 0xbf92bbf2, + 0xa8e5e036, 0x3030a02b, 0xab1e833b, 0x5190d039, + 0x3d31eec2, 0x4eadf427, 0xea65d217, 0xafac4dd3, + 0xdf5ef6fe, 0xe88cdd6c, 0xab55d1df, 0x77689e8b, + 0x3ba6b081, 0x9ed37908, 0x42383678, 0xf9f221a6, + 0xb6cf355d, 0x1c10aa09, 0x38645486, 0xab46320e, + 0x6c01bdce, 0xaa9b77bf, 0xdc8a7085, 0x843c40c0, + 0x35218b12, 0x57c15a35, 0x37a879d4, 0x41fa8671, + 0xe9bae4f3, 0x9521c923, 0x2a32bab3, 0x5415b46b, + 0xcb7245dd, 0x6e6407bd, 0x88477782, 0x18424ea6, + 0x48214427, 0xd266b8b8, 0x70b796d4, 0xe4e48223, + + 0xf6a5bf45, 0xa34cc400, 0x0b62f21c, 0xf0eb6ca7, + 0x4f8566a3, 0xd23e5904, 0x86eac0fd, 0x95080a7d, + 0xe2926a24, 0x9983c4a1, 0x7e398b84, 0x9fccb2f1, + 0xff70696b, 0xccb47af7, 0x61d3bf96, 0xf4170385, + 0x0bc86fef, 0x06fb5c90, 0xce92d9fe, 0x120ca3cf, + 0xdcde2f59, 0xd6fd2b38, 0x4258d974, 0x4b2c0a3c, + 0x1f0967ec, 0x25987e51, 0x4e7acfc7, 0x1f7f9694, + 0x18de3230, 0x85d9095d, 0x54737616, 0x6ec26956, + 0x9eb3637b, 0x908a5192, 0x839fb43e, 0xefe70f2a, + 0x42e168a5, 0x776e5c22, 0x736be3a9, 0xb72d66ed, + 0xa4f94794, 0xb414bd55, 0x5de623d3, 0x9cd1e1a9, + 0x42957f7e, 0x381cf593, 0x678a7d07, 0x158bb604, + 0xe64926bd, 0x5a047438, 0x360d68cb, 0xab487a8e, + 0x0d769a0b, 0xde3fc939, 0xf33ea9c0, 0x28b87455, + 0xd5f6c00c, 0x853f8ffe, 0xc8d238c3, 0x3bb5473e, + 0xc9779097, 0xc4af3a0c, 0x899098c0, 0x3c51c0e4, + 0x7e02214e, 0xe65f85a4, 0xe7c4a857, 0x6096179e, + 0x9c9eb559, 0x709a5f7d, 0x548f6fd5, 0xf1ad58cb, + 0xe4bce783, 0x43ca2b6c, 0x6f43de8f, 0xa60a02f9, + 0xbcdd0f35, 0x58f582b3, 0x30633b0d, 0xf17c7d49, + 0x35f809f7, 0x9ee90417, 0x6360674f, 0x44375b7b, + 0x72949c97, 0xff78dcd2, 0x08bff59a, 0x00b14d4e, + 0xf37ef8c1, 0x6760a010, 0x87dd4dee, 0x31f5208a, + 0x721c3add, 0x6eb9ab46, 0x29250341, 0x2fdcc721, + 0x9d812ebb, 0x60a078a0, 0x20fcdc2d, 0xe8c594f9, + 0x4956e488, 0x81873803, 0xf51a953d, 0x9b43c7e1, + 0xdfd95440, 0x8dbdb07e, 0x1ecaf22f, 0xb14dceca, + 0xc4c8003d, 0xdc26051b, 0x8bdc1011, 0x6df204db, + 0xc72491cf, 0x9fd74623, 0xa663c57f, 0xd0f6f96d, + 0x60f5d249, 0x10b66b81, 0xeeb26437, 0xe739332c, + 0xeb94bdfd, 0xbfc4e0e3, 0x5d8ee7a8, 0xf676c5c3, + 0x38357061, 0x8d3e4d68, 0xd560280b, 0x7a85b438, + 0x00e7da19, 0x44e3021b, 0xb22bee73, 0x7af11114, + 0x9a4aacd3, 0xbb5ea97a, 0x7993ac0b, 0x3dc12ed7, + 0x7ac7eda8, 0x26528e57, 0xb15b78c9, 0xeae2b177, + 0xa9bd7a3c, 0x03812180, 0x0ed1451f, 0x9ab1c57d, + 0xa0acc3c5, 0xbf0b533d, 0x017f8413, 0x3228452a, + 0x86eb48e1, 0x379cbcff, 0x3b200f75, 0x0cbbb62b, + 0x7467627f, 0xc782b5e3, 0xd402c537, 0x026be842, + 0x41a32d7a, 0x5910b6ff, 0x909926b4, 0x05bd811e, + 0x92fd98c8, 0xcf66e980, 0x1f5eb79c, 0x4e2c31e4, + 0x5f9b7f0c, 0x91972e91, 0xf70f2e5a, 0xd5b6b627, + 0x3b1f243a, 0xf404cb7b, 0xe6232ec3, 0x22da8906, + 0x0cb348ff, 0x0da6349d, 0x7c858b98, 0xd9b258f1, + 0x623c9dd4, 0x8493c626, 0x91551f3b, 0x6ed97a53, + 0xb5a10c32, 0x23d39f3e, 0x57e7da04, 0x8f0b2689, + 0xebb54529, 0x0f015572, 0x2f4db833, 0x407e1d2b, + 0xfd815f1a, 0xdeacbb64, 0xe8c38859, 0xde04110b, + 0xb6c901ab, 0x153aee1a, 0x6b5af720, 0xc3bfe796, + 0x8b412bc7, 0xe8cbe167, 0x60d83df2, 0x35506981, + 0x2b8f1fc7, 0x311029cf, 0xf46fad6e, 0x7440056b, + 0x61df9779, 0x693d02da, 0xe7d93ccc, 0x861bd3d3, + 0xad0b85a0, 0x8bcd277a, 0xb72fceb7, 0x8ca5d84f, + 0xc0847150, 0x1bd88428, 0x4673ca0d, 0xb030dbe5, + 0xb51c06c1, 0x642baffb, 0xccb5043b, 0xb84aebcb, + 0xbcd80352, 0x385520d6, 0x3b4518aa, 0xfed91bbe, + 0x95f68932, 0x3a10ae0e, 0xd733aeaf, 0xf9f85ba7, + 0x978ac3d1, 0x6a64540c, 0xc5a1575c, 0xc2adcd2b, + 0xc3d45465, 0x47671f05, 0x8542fff3, 0x0f528f92, + 0x3da8b9cd, 0x13e96928, 0x0ae5cb86, 0x55602423, + 0x1acfb022, 0x68c9f16b, 0xbebc28a5, 0xb1d1d15e, + 0xa9f54130, 0x0ebb0b93, 0xaf3ffdb9, 0x52078aad, + 0xb3bf2160, 0xfb4d9d05, 0xe32785a3, 0xd05a87e5, + 0x688e68a5, 0x38840376, 0x9b46ac8d, 0x23f286fd, + +}; + diff --git a/build/libraries/init/ARM7/Makefile b/build/libraries/init/ARM7/Makefile new file mode 100644 index 0000000..ae15c2b --- /dev/null +++ b/build/libraries/init/ARM7/Makefile @@ -0,0 +1,58 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - init +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +#SUBMAKES = Makefile.CALLTRACE \ +# Makefile.FUNCTIONCOST + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +# Codegen for sub processer +FIRM_PROC = ARM7 + +SRCS = crt0_firm.c \ + +TARGET_OBJ = crt0_firm.o + + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/init/ARM7/crt0_firm.c b/build/libraries/init/ARM7/crt0_firm.c new file mode 100644 index 0000000..f4eea19 --- /dev/null +++ b/build/libraries/init/ARM7/crt0_firm.c @@ -0,0 +1,447 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - init + File: crt0.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +#define FIRM_ENABLE_JTAG + +void _start(void); +void _start_AutoloadDoneCallback(void *argv[]); + +#define SDK_NITROCODE_LE 0x2106c0de +#define SDK_NITROCODE_BE 0xdec00621 + +#define SDK_TWLCODE_LE 0x6314c0de +#define SDK_TWLCODE_BE 0xdec01463 + +// volatile parameters in IPL's work memory +#define IPL_PARAM_CARD_ROM_HEADER 0x023FE940 +#define IPL_PARAM_DOWNLOAD_PARAMETER 0x023FE904 + +extern void OS_IrqHandler(void); +extern void _fp_init(void); +extern void __call_static_initializers(void); +extern void TwlMain(void); + +static void INITi_DoAutoload(void); +static void INITi_ShelterLtdBinary(void); +static void detect_main_memory_size(void); + +// from LCF +extern unsigned long SDK_IRQ_STACKSIZE[]; + +extern void SDK_STATIC_BSS_START(void); // static bss start address +extern void SDK_STATIC_BSS_END(void); // static bss start address +extern void SDK_AUTOLOAD_LIST(void); // start pointer to autoload information +extern void SDK_AUTOLOAD_LIST_END(void); // end pointer to autoload information +extern void SDK_AUTOLOAD_START(void); // autoload data will start from here +extern void SDK_LTDAUTOLOAD_LIST(void); // start pointer to autoload information +extern void SDK_LTDAUTOLOAD_LIST_END(void); // end pointer to autoload information +extern void SDK_LTDAUTOLOAD_START(void); // autoload data will start from here + +//---- IRQ+SVC stack size in boot (this area is not cleared) +#define INITi_Initial_Stack 0x100 + +void *const _start_ModuleParams[] = +{ + (void *)SDK_AUTOLOAD_LIST, + (void *)SDK_AUTOLOAD_LIST_END, + (void *)SDK_AUTOLOAD_START, + (void *)SDK_STATIC_BSS_START, + (void *)SDK_STATIC_BSS_END, + (void*)0, // CompressedStaticEnd. This fixed number will be updated by compstatic tool. + (void*)0, // SDK_VERSION_ID // SDK version info /* [TODO] rhʂ */ + (void*)SDK_NITROCODE_BE, + (void*)SDK_NITROCODE_LE, +}; + +void* const _start_LtdModuleParams[] = +{ + (void*)SDK_LTDAUTOLOAD_LIST, + (void*)SDK_LTDAUTOLOAD_LIST_END, + (void*)SDK_LTDAUTOLOAD_START, + (void*)0, // CompressedLtdautoloadEnd. This fixed number will be updated by compstatic tool. + (void*)SDK_TWLCODE_BE, + (void*)SDK_TWLCODE_LE, +}; + +/*---------------------------------------------------------------------------* + Name: _start + + Description: Start up + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +SDK_WEAK_SYMBOL asm void _start( void ) +{ +#ifdef FIRM_ENABLE_JTAG + ldr r1, =REG_JTAG_ADDR + ldrh r2, [r1] + orr r2, r2, #REG_SCFG_JTAG_CPUJE_MASK | REG_SCFG_JTAG_ARM7SEL_MASK + strh r2, [r1] +#endif + + //---- set IME = 0 + // ( use that LSB of HW_REG_BASE equal to 0 ) + mov r12, #HW_REG_BASE + str r12, [r12, #REG_IME_OFFSET] + + //---- initialize stack pointer + // SVC mode + mov r0, #HW_PSR_SVC_MODE + msr cpsr_c, r0 + ldr sp, =HW_PRV_WRAM_SVC_STACK_END + + // IRQ mode + mov r0, #HW_PSR_IRQ_MODE + msr cpsr_c, r0 + ldr r0, =HW_PRV_WRAM_IRQ_STACK_END + mov sp, r0 + + // System mode + ldr r1, =SDK_IRQ_STACKSIZE + sub r1, r0, r1 + mov r0, #HW_PSR_SYS_MODE + msr cpsr_csfx, r0 + sub sp, r1, #4 // 4byte for stack check code + + //---- read reset flag from pmic +#ifdef TWL_PLATFORM_TS +#if 0 + mov r0, #REG_PMIC_SW_FLAGS_ADDR + bl PMi_GetRegister + ands r0, r0, #PMIC_SW_FLAGS_WARMBOOT +#else + mov r0, #I2C_SLAVE_MICRO_CONTROLLER + mov r1, #MCU_REG_TEMP_ADDR + bl I2Ci_ReadRegister + ands r0, r0, #0x01 // under construction +#endif + movne r0, #FIRM_PXI_ID_WARMBOOT + moveq r0, #FIRM_PXI_ID_COLDBOOT + bl PXI_SendByIntf + mov r0, #FIRM_PXI_ID_INIT_MMEM + bl PXI_WaitByIntf +#endif // TWL_PLATFORM_TS + + //---- wait for main memory mode into burst mode + ldr r3, =REG_EXMEMCNT_L_ADDR + mov r1, #REG_MI_EXMEMCNT_L_ECE2_MASK +@1: + ldrh r2, [r3] + tst r2, r1 + beq @1 + +#if 0 + // move parameters from IPL's work memory to shared area + ldr r0, =IPL_PARAM_CARD_ROM_HEADER + ldr r1, =HW_CARD_ROM_HEADER + add r2, r1, #HW_CARD_ROM_HEADER_SIZE +@1_1: + ldr r3, [r0], #4 + str r3, [r1], #4 + cmp r1, r2 + bmi @1_1 + ldr r0, =IPL_PARAM_DOWNLOAD_PARAMETER + add r2, r1, #HW_DOWNLOAD_PARAMETER_SIZE +@1_2: + ldr r3, [r0], #4 + str r3, [r1], #4 + cmp r1, r2 + bmi @1_2 +#endif + + //---- load autoload block and initialize bss + //bl INITi_DoAutoload +#ifndef SDK_FINALROM // for IS-TWL-DEBUGGER + bl _start_AutoloadDoneCallback +#endif + + //---- fill static static bss with 0 + ldr r0, =_start_ModuleParams + ldr r1, [r0, #12] // BSS segment start + ldr r2, [r0, #16] // BSS segment end + mov r0, #0 +@2: cmp r1, r2 + strcc r0, [r1], #4 + bcc @2 + + //---- detect main memory size + //bl detect_main_memory_size + + //---- set interrupt vector + ldr r1, =HW_INTR_VECTOR_BUF + ldr r0, =OS_IrqHandler + str r0, [r1, #0] + +#ifndef SDK_NOINIT + //---- for C++ + bl _fp_init + bl TwlSpStartUp + bl __call_static_initializers +#endif + + //---- start (to 16bit code) + ldr r1, =TwlSpMain + ldr lr, =HW_RESET_VECTOR + + bx r1 +} +/*---------------------------------------------------------------------------* + Name: INITi_DoAutoload + Description: NɉāAeI[g[hubŇŒf[^̓WJ + yѕϐ 0 NAsB + Arguments: ȂB + Returns: ȂB + *---------------------------------------------------------------------------*/ +/* + * < iKI[g[h > + * 0x02f88000 crt0 yшiڃ[hoCizuĂB + * NITRO ƋL”\ WRAM ɔzuׂoCif[^ 0x037c0000 Ƀ[hB + * TWL ł삵Ȃ WRAM ɔzuׂoCif[^𑱂̃AhXɃ[hB + * 0x02e80000 ɓiڃ[hoCizuĂB + * 0x04000 oCg̓J[h ROM ēǂݏos‚Ȃ̂ŁA0x02f84000 - 0x02f88000 ɑޔB + * NITRO ƋL”\ MAIN ɔzuׂoCif[^ 0x02f88000 + sizeof(crt0) Ƀ[hB + * TWL ł삵Ȃ MAIN ɔzuׂoCif[^𑱂̃AhXɃ[hB + */ +static asm void +INITi_DoAutoload(void) +{ +@000: + stmdb sp!, {lr} + /* WRAM pubNI[g[h */ + ldr r1, =_start_ModuleParams + ldr r12, [r1] // r12 = SDK_AUTOLOAD_LIST + ldr r0, [r1, #4] // r0 = SDK_AUTOLOAD_LIST_END + ldr r1, [r1, #8] // r1 = SDK_AUTOLOAD_START +@001: cmp r12, r0 + bge @010 + /* ŒZNV[h */ + stmdb sp!, {r0} + ldr r2, [r12], #4 // r2 = start address of destination range + ldr r3, [r12], #4 // r3 = size of fixed section + add r3, r3, r2 // r3 = end address of destination range of fixed section +@002: cmp r2, r3 + ldrlt r0, [r1], #4 + strlt r0, [r2], #4 + blt @002 + /* .bss ZNV 0 NA */ + mov r0, #0 + ldr r3, [r12], #4 // r3 = size of .bss section + add r3, r3, r2 // r3 = end address of destination range of .bss section +@003: cmp r2, r3 + strlt r0, [r2], #4 + blt @003 +@004: ldmia sp!, {r0} + b @001 + +@010: /* CpubN݂̑mF */ + ldr r1, =HW_TWL_ROM_HEADER_BUF + 0x1dc /* ARM7 pg풓W[ ROM TCY */ + ldr r0, [r1] + cmp r0, #0 + beq @020 + + /* ēǂݏos•ޔ */ + bl INITi_ShelterLtdBinary + + /* CpubNI[g[h */ + ldr r1, =_start_LtdModuleParams + ldr r12, [r1] // r12 = SDK_LTDAUTOLOAD_LIST + ldr r0, [r1, #4] // r0 = SDK_LTDAUTOLOAD_LIST_END + ldr r1, [r1, #8] // r1 = SDK_LTDAUTOLOAD_START +@011: cmp r12, r0 + bge @020 + /* ŒZNV[h */ + stmdb sp!, {r0} + ldr r2, [r12], #4 // r2 = start address of destination range + ldr r3, [r12], #4 // r3 = size of fixed section + add r3, r3, r2 // r3 = end address of destination range of fixed section +@012: cmp r2, r3 + ldrlt r0, [r1], #4 + strlt r0, [r2], #4 + blt @012 + /* .bss ZNV 0 NA */ + mov r0, #0 + ldr r3, [r12], #4 // r3 = size of .bss section + add r3, r3, r2 // r3 = end address of destination range of .bss section +@013: cmp r2, r3 + strlt r0, [r2], #4 + blt @013 +@014: ldmia sp!, {r0} + b @011 + +@020: /* I[g[hR[obN֐Ăяo */ + ldr r0, =_start_ModuleParams + ldr r1, =_start_LtdModuleParams + ldmia sp!, {lr} + b _start_AutoloadDoneCallback +} + +/*---------------------------------------------------------------------------* + Name: INITi_ShelterLtdBinary + Description: TWL p̃I[g[hoCif[^̓AJ[h ROM + ēǂݏołȂ̈̃f[^ޔGAɑޔB + ēǂݏołȂ̈̃f[^ ARM7 p ARM9 p̊g풓 + W[̂Q‚ɕÔ\̂ŁA璷ł͂邪 + ̐擪 0x4000 ꂼޔB + Arguments: ȂB + Returns: ȂB + *---------------------------------------------------------------------------*/ +static asm void +INITi_ShelterLtdBinary(void) +{ + /* ޔEAhX𒲍 */ + ldr r1, =HW_TWL_ROM_HEADER_BUF + 0x1d8 /* ARM7 pg풓W[ RAM AhX */ + ldr r1, [r1] + ldr r3, =HW_TWL_ROM_HEADER_BUF + 0x038 /* ARM7 p풓W[ RAM AhX */ + ldr r3, [r3] + sub r2, r3, #0x4000 /* ēǂݏos—̈TCY */ /* ARM7 pޔGA */ + + /* Rs[ */ +@loop: ldr r0, [r1], #4 + str r0, [r2], #4 + cmp r2, r3 + blt @loop + + bx lr +} + +/*---------------------------------------------------------------------------* + Name: _start_AutoloadDoneCallback + Description: I[g[hR[obNB + Arguments: argv - I[g[hp[^ێĂzB + argv[0] = SDK_AUTOLOAD_LIST + argv[1] = SDK_AUTOLOAD_LIST_END + argv[2] = SDK_AUTOLOAD_START + argv[3] = SDK_STATIC_BSS_START + argv[4] = SDK_STATIC_BSS_END + Returns: ȂB + *---------------------------------------------------------------------------*/ +SDK_WEAK_SYMBOL asm void +_start_AutoloadDoneCallback(void* argv[]) +{ + bx lr +} + +/*---------------------------------------------------------------------------* + Name: detect_main_memory_size + + Description: detect main memory size. + result is written into (u32*)HW_MMEMCHECKER_SUB. + value is [OS_CONSOLE_SIZE_4MB|OS_CONSOLE_SIZE_8MB| + OS_CONSOLE_SIZE_16MB|OS_CONSOLE_SIZE_32MB] + + + + + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +#define OSi_IMAGE_DIFFERENCE 0x400000 +#define OSi_IMAGE_DIFFERENCE2 0xb00000 + +static asm void detect_main_memory_size( void ) +{ +#if 0 // NITRO hardware is not supported + mov r0, #OS_CONSOLE_SIZE_4MB + mov r1, #0 + + ldr r2, =HW_MMEMCHECKER_SUB + sub r3, r2, #OSi_IMAGE_DIFFERENCE +@1: + strh r1, [r2] + ldrh r12, [r3] + cmp r1, r12 + + + bne @2 + + add r1, r1, #1 + cmp r1, #2 // check 2 loop + bne @1 + + //---- 4MB + b @4 + + //---- 8MB or 16MB or 32MB +@2: + // check if running on twl/nitro + ldr r1, =REG_CLK_ADDR + ldrh r12, [r1] + tst r12, #REG_SCFG_CLK_WRAMHCLK_MASK + moveq r0, #OS_CONSOLE_SIZE_8MB + beq @4 +#else + ldr r2, =HW_MMEMCHECKER_SUB +#endif + //---- 16MB or 32MB + mov r1, #0 + add r3, r2, #OSi_IMAGE_DIFFERENCE2 +@3: + strh r1, [r2] + ldrh r12, [r3] + cmp r1, r12 + + movne r0, #OS_CONSOLE_SIZE_32MB + bne @4 + + add r1, r1, #1 + cmp r1, #2 // check 2 loop + bne @3 + mov r0, #OS_CONSOLE_SIZE_16MB +@4: + strh r0, [r2] + + //---- detect chiptype + ldr r2, =REG_OP_ADDR + ldrh r0, [r2] + and r0, r0, #REG_SCFG_OP_OPT_MASK + + // check SMX_CNT + ldr r2, =REG_SMX_CNT_ADDR + ldrh r1, [r2] + tst r1, #0 + orrne r0, r0, #OS_CHIPTYPE_SMX_MASK + + //---- detect jtag + ldr r2, =REG_JTAG_ADDR + ldrh r1, [r2] + and r1, r1, #REG_SCFG_JTAG_CPUJE_MASK + orr r0, r0, r1, LSL #1 + + ldr r2, =HW_CHIPTYPE_FLAG + strb r0, [r2] + + bx lr +} + +/*---------------------------------------------------------------------------* + Name: TwlSpStartUp + + Description: hook for user start up + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +SDK_WEAK_SYMBOL void TwlSpStartUp(void) +{ +} diff --git a/build/libraries/init/ARM9/Makefile b/build/libraries/init/ARM9/Makefile new file mode 100644 index 0000000..7481707 --- /dev/null +++ b/build/libraries/init/ARM9/Makefile @@ -0,0 +1,54 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - init +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +#SUBMAKES = Makefile.CALLTRACE \ +# Makefile.FUNCTIONCOST + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +SRCS = crt0_firm.c \ + +TARGET_OBJ = crt0_firm.o + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/init/ARM9/crt0_firm.c b/build/libraries/init/ARM9/crt0_firm.c new file mode 100644 index 0000000..a0e20ce --- /dev/null +++ b/build/libraries/init/ARM9/crt0_firm.c @@ -0,0 +1,817 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - init + File: crt0.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +void _start(void); +void _start_AutoloadDoneCallback(void *argv[]); + +#define SDK_NITROCODE_LE 0x2106c0de +#define SDK_NITROCODE_BE 0xdec00621 + +#define SDK_TWLCODE_LE 0x6314c0de +#define SDK_TWLCODE_BE 0xdec01463 + +extern void OS_IrqHandler(void); +extern void _fp_init(void); +extern void __call_static_initializers(void); +extern void TwlMain(void); + +static void INITi_CpuClear32(register u32 data, register void *destp, register u32 size); +static void INITi_InitCoprocessor(void); +static void INITi_InitRegion(void); +static void INITi_DoAutoload(void); +static void INITi_ShelterLtdBinary(void); + +// from LCF +extern unsigned long SDK_IRQ_STACKSIZE[]; + +extern void SDK_AUTOLOAD_LIST(void); // start pointer to autoload information +extern void SDK_AUTOLOAD_LIST_END(void); // end pointer to autoload information +extern void SDK_AUTOLOAD_START(void); // autoload data will start from here +extern void SDK_STATIC_BSS_START(void); // static bss start address +extern void SDK_STATIC_BSS_END(void); // static bss end address +extern void SDK_LTDAUTOLOAD_LIST(void); // start pointer to autoload information +extern void SDK_LTDAUTOLOAD_LIST_END(void); // end pointer to autoload information +extern void SDK_LTDAUTOLOAD_START(void); // autoload data will start from here + +/*---------------------------------------------------------------------------* + Name: _start_ModuleParams + + Description: autoload/compress/arguments data block + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +//#include +#define SDK_VERSION_ID ((u32)SDK_VERSION_MAJOR<<24|\ + (u32)SDK_VERSION_MINOR<<16|\ + (u32)SDK_VERSION_RELSTEP) + +void *const _start_ModuleParams[] = +{ + (void *)SDK_AUTOLOAD_LIST, + (void *)SDK_AUTOLOAD_LIST_END, + (void *)SDK_AUTOLOAD_START, + (void *)SDK_STATIC_BSS_START, + (void *)SDK_STATIC_BSS_END, + (void *)0, // CompressedStaticEnd + (void *)SDK_VERSION_ID, // SDK version info + (void *)SDK_NITROCODE_BE, // Checker 1 + (void *)SDK_NITROCODE_LE, // Checker 2 +}; +void* const _start_LtdModuleParams[] = +{ + (void*)SDK_LTDAUTOLOAD_LIST, + (void*)SDK_LTDAUTOLOAD_LIST_END, + (void*)SDK_LTDAUTOLOAD_START, + (void*)0, // CompressedLtdautoloadEnd. This fixed number will be updated by compstatic tool. + (void*)SDK_TWLCODE_BE, + (void*)SDK_TWLCODE_LE, +}; + + +/*---------------------------------------------------------------------------* + Name: _start + + Description: Start up + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +#define INITi_HW_DTCM SDK_AUTOLOAD_DTCM_START + +SDK_WEAK_SYMBOL asm void _start( void ) +{ + //---- set IME = 0 + // ( use that LSB of HW_REG_BASE equal to 0 ) + mov r12, #HW_REG_BASE + str r12, [r12, #REG_IME_OFFSET] + + //---- initialize stack pointer + // SVC mode + mov r0, #HW_PSR_SVC_MODE + msr cpsr_c, r0 + ldr r0, =INITi_HW_DTCM + add r0, r0, #0x3fc0 + mov sp, r0 + + // IRQ mode + mov r0, #HW_PSR_IRQ_MODE + msr cpsr_c, r0 + ldr r0, =INITi_HW_DTCM + add r0, r0, #0x3fc0 + sub r0, r0, #HW_SVC_STACK_SIZE + sub sp, r0, #4 // 4byte for stack check code + tst sp, #4 + subeq sp, sp, #4 // for 8byte-alignment + + // System mode + ldr r1, =SDK_IRQ_STACKSIZE + sub r1, r0, r1 + mov r0, #HW_PSR_SYS_MODE + msr cpsr_csfx, r0 + sub sp, r1, #4 // 4byte for stack check code + + //---- read reset flag from pmic +#ifdef TWL_PLATFORM_TS +@0: bl PXI_RecvByIntf + cmp r0, #FIRM_PXI_ID_COLDBOOT + cmpne r0, #FIRM_PXI_ID_WARMBOOT + bne @0 + + //---- initialize Main Memory + cmp r0, #FIRM_PXI_ID_COLDBOOT + moveq r0, #TRUE + movne r0, #FALSE + bl MIi_InitMainMemCR + + mov r0, #FIRM_PXI_ID_INIT_MMEM + bl PXI_SendByIntf + +#else // TWL_PLATFORM_BB + //---- initialize Main Memory + bl MIi_InitMainMemCR + +#endif // TWL_PLATFORM_BB + + /* VXeRvZbT */ + bl INITi_InitCoprocessor + + /* [Wݒ */ + bl INITi_InitRegion + + //---- clear memory + // DTCM (16KB) + mov r0, #0 + ldr r1, =INITi_HW_DTCM + mov r2, #HW_DTCM_SIZE + bl INITi_CpuClear32 + + // BG/OBJ palette (1KB) + mov r0, #0 + ldr r1, =HW_PLTT + mov r2, #HW_PLTT_SIZE + bl INITi_CpuClear32 + + // OAM (1KB) + mov r0, #0x0200 + ldr r1, =HW_OAM + mov r2, #HW_OAM_SIZE + bl INITi_CpuClear32 + + //---- load autoload block and initialize bss +// bl INITi_DoAutoload +#ifndef SDK_FINALROM // for IS-TWL-DEBUGGER + bl _start_AutoloadDoneCallback +#endif + + //---- fill static static bss with 0 + mov r0, #0 + ldr r3, =_start_ModuleParams + ldr r1, [r3, #12] // SDK_STATIC_BSS_START + ldr r2, [r3, #16] // SDK_STATIC_BSS_END + sub r2, r2, r1 + bl INITi_CpuClear32 + + //---- flush static bss region + // (r0 == #0, r3 == _start_ModuleParams::BSS_segment_start) + bic r1, r3, #HW_CACHE_LINE_SIZE - 1 +@cacheflush: + mcr p15, 0, r0, c7, c10, 4 // wait writebuffer empty + mcr p15, 0, r1, c7, c5, 1 // ICache + mcr p15, 0, r1, c7, c14, 1 // DCache + add r1, r1, #HW_CACHE_LINE_SIZE + cmp r1, r2 + blt @cacheflush + + // print buffer (used for ARM7's printing) + ldr r1, =HW_COMPONENT_PARAM + str r0, [r1, #0] + + //---- set interrupt vector + ldr r1, =INITi_HW_DTCM + add r1, r1, #0x3fc0 + add r1, r1, #HW_DTCM_SYSRV_OFS_INTR_VECTOR + ldr r0, =OS_IrqHandler + str r0, [r1, #0] + +#ifndef SDK_NOINIT + //---- for C++ + bl _fp_init + bl TwlStartUp + bl __call_static_initializers +#endif + //---- start (to 16bit code) + ldr r1, =TwlMain + ldr lr, =HW_RESET_VECTOR + + tst sp, #4 + subne sp, sp, #4 // for 8byte-alignment + bx r1 +} + + +/*---------------------------------------------------------------------------* + Name: INITi_CpuClear32 + + Description: fill memory with specified data. + 32bit version + + Arguments: data : fill data + destp : destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +static asm void INITi_CpuClear32( register u32 data, register void *destp, register u32 size ) +{ + add r12, r1, r2 // r12: destEndp = destp + size +@20: + cmp r1, r12 // while (destp < destEndp) + stmltia r1!, {r0} // *((vu32 *)(destp++)) = data + blt @20 + bx lr +} + +/*---------------------------------------------------------------------------* + Name: INITi_DoAutoload + Description: NɉāAeI[g[hubŇŒf[^̓WJ + yѕϐ 0 NAsB4M bytes z PSRAM + ɔzuI[g[hubN̓WJ́An[hEFA TWL + ꍇɂsBI[g[hf[^ƃI[g[h悪ꕔ + dȂꍇ̂ŁAWJsB + Arguments: ȂB + Returns: ȂB + *---------------------------------------------------------------------------*/ +/* + * < iKI[g[h > + * 0x02000000 Static ZOgyшiڃ[hoCi(KvɉČ㔼k)zuĂB + * kĂꍇ́A܂ 0x02000000 Ɍ㏑‚‰𓀂B + * NITRO ƋL”\ ITCM ɔzuׂoCif[^ 0x01ff8000 Ƀ[hB + * NITRO ƋL”\ DTCM ɔzuׂoCif[^ 0x02fe0000 Ƀ[hB + * 0x02400000 ɓiڃ[hoCi(KvɉđSĈk)zuĂB + * 0x04000 oCg̓J[h ROM ēǂݏos‚Ȃ̂ŁA0x02f80000 - 0x02f84000 ɑޔB + * kĂꍇ́A܂ 0x02400000 Ɍ㏑‚‰𓀂B + * TWL ł삵Ȃ WRAM ɔzuׂoCif[^ꂼwAhXɃ[hB + * TWL ł삵ȂCɔzuׂoCif[^ORs[邱ƂŃ[hB + * ́ANITRO ƋL”\ȃCɔzuf[^ 0x02400000 zȂ͂ł邽߁A + * zuׂAhX 0x02400000 菬AhXɂȂ͂łׁB + * ܂AI[g[h񃊃Xg̎̂Cւ̃I[g[hubN .bss ZNṼNẢߒ + * j󂳂”\邪AÃI[g[h̍Ō̒iKȂ̂ŁAj󂳂ĂȂB + */ +static asm void +INITi_DoAutoload(void) +{ +@000: + stmdb sp!, {lr} + /* NITRO pubN̉ */ + ldr r1, =_start_ModuleParams + ldr r0, [r1, #20] // r0 = bottom of compressed data + bl MIi_UncompressBackward + +@010: + /* NITRO pubNI[g[h */ + ldr r1, =_start_ModuleParams + ldr r12, [r1] // r12 = SDK_AUTOLOAD_LIST + ldr r0, [r1, #4] // r0 = SDK_AUTOLOAD_LIST_END + ldr r1, [r1, #8] // r1 = SDK_AUTOLOAD_START +@011: cmp r12, r0 + bge @020 + /* ŒZNV[h */ + stmdb sp!, {r0} + ldr r2, [r12], #4 // r2 = start address of destination range + stmdb sp!, {r2} + ldr r3, [r12], #4 // r3 = size of fixed section + add r3, r3, r2 // r3 = end address of destination range of fixed section +@012: cmp r2, r3 + ldrlt r0, [r1], #4 + strlt r0, [r2], #4 + blt @012 + /* .bss ZNV 0 NA */ + mov r0, #0 // r0 = number to fill .bss section + ldr r3, [r12], #4 // r3 = size of .bss section + add r3, r3, r2 // r3 = end address of destination range of .bss section +@013: cmp r2, r3 + strlt r0, [r2], #4 + blt @013 + /* LbV𒲐 */ + ldmia sp!, {r2} // r2 = start address of destination range + mov r0, #HW_ITCM_IMAGE + cmp r2, r0 + addge r0, r0, #HW_ITCM_SIZE + cmpge r0, r2 + bgt @015 // If I-TCM autoload block, skip cache control logic. + ldr r0, =SDK_AUTOLOAD_DTCM_START + cmp r2, r0 + addge r0, r0, #HW_DTCM_SIZE + cmpge r0, r2 + bgt @015 // If D-TCM autoload block, skip cache control logic. + bic r2, r2, #HW_CACHE_LINE_SIZE - 1 // RoundDown32 +@014: cmp r2, r3 + bge @015 + mcr p15, 0, r2, c7, c14, 1 // Store and Invalidate D-Cache + mcr p15, 0, r2, c7, c5, 1 // Invalidate I-Cache + add r2, r2, #HW_CACHE_LINE_SIZE + b @014 +@015: ldmia sp!, {r0} + b @011 + +@020: + /* TWL n[hEFAœ삵Ă邩ǂ𒲍 */ + ldr r1, =REG_CLK_ADDR + ldrh r0, [r1] + tst r0, #REG_SCFG_CLK_WRAMHCLK_MASK + beq @030 + + /* TWL pubN݂̑mF */ + ldr r1, =HW_TWL_ROM_HEADER_BUF + 0x1cc /* ARM9 pg풓W[ ROM TCY */ + ldr r0, [r1] + cmp r0, #0 + beq @030 + + /* ēǂݏos•ޔ */ + bl INITi_ShelterLtdBinary + + /* TWL pubN̉ */ + ldr r1, =_start_LtdModuleParams + ldr r0, [r1, #12] + bl MIi_UncompressBackward + + /* TWL pubNI[g[h */ + ldr r1, =_start_LtdModuleParams + ldr r12, [r1] // r12 = SDK_LTDAUTOLOAD_LIST + ldr r0, [r1, #4] // r0 = SDK_LTDAUTOLOAD_LIST_END + ldr r1, [r1, #8] // r1 = SDK_LTDAUTOLOAD_START +@021: cmp r12, r0 + bge @030 + /* ŒZNV[h */ + stmdb sp!, {r0} + ldr r2, [r12], #4 // r2 = start address of destination range + stmdb sp!, {r2} + ldr r3, [r12], #4 // r3 = size of fixed section + add r3, r3, r2 // r3 = end address of destination range of fixed section +@022: cmp r2, r3 + ldrlt r0, [r1], #4 + strlt r0, [r2], #4 + blt @022 + /* .bss ZNV 0 NA */ + mov r0, #0 // r0 = number to fill .bss section + ldr r3, [r12], #4 // r3 = size of .bss section + add r3, r3, r2 // r3 = end address of destination range of .bss section +@023: cmp r2, r3 + strlt r0, [r2], #4 + blt @023 + /* LbV𒲐 */ + ldmia sp!, {r2} // r2 = start address of destination range + mov r0, #HW_ITCM_IMAGE + cmp r2, r0 + addge r0, r0, #HW_ITCM_SIZE + cmpge r0, r2 + bgt @025 // If I-TCM autoload block, skip cache control logic. + ldr r0, =SDK_AUTOLOAD_DTCM_START + cmp r2, r0 + addge r0, r0, #HW_DTCM_SIZE + cmpge r0, r2 + bgt @025 // If D-TCM autoload block, skip cache control logic. + bic r2, r2, #HW_CACHE_LINE_SIZE - 1 // RoundDown32 +@024: cmp r2, r3 + bge @025 + mcr p15, 0, r2, c7, c14, 1 // Store and Invalidate D-Cache + mcr p15, 0, r2, c7, c5, 1 // Invalidate I-Cache + add r2, r2, #HW_CACHE_LINE_SIZE + b @024 +@025: ldmia sp!, {r0} + b @021 + +@030: /* Cgobt@ɂȂ̂҂ */ + mov r0, #0 + mcr p15, 0, r0, c7, c10, 4 + + /* I[g[hR[obN֐Ăяo */ + ldr r0, =_start_ModuleParams + ldr r1, =_start_LtdModuleParams + ldmia sp!, {lr} + b _start_AutoloadDoneCallback +} + +/*---------------------------------------------------------------------------* + Name: INITi_ShelterLtdBinary + Description: TWL p̃I[g[hoCif[^̓AJ[h ROM + ēǂݏołȂ̈̃f[^ޔGAɑޔB + ēǂݏołȂ̈̃f[^ ARM7 p ARM9 p̊g풓 + W[̂Q‚ɕÔ\̂ŁA璷ł͂邪 + ̐擪 0x4000 ꂼޔB + Arguments: ȂB + Returns: ȂB + *---------------------------------------------------------------------------*/ +static asm void +INITi_ShelterLtdBinary(void) +{ + /* ARM7 pCԕی샊[WUANZX”\ɕύX */ + mrc p15, 0, r0, c5, c0, 3 + mrc p15, 0, r1, c5, c0, 2 + stmdb sp!, {r0, r1} + bic r0, r0, #(0xf << 8) + orr r0, r0, #(0x1 << 8) + bic r1, r1, #(0xf << 8) + orr r1, r1, #(0x1 << 8) + mcr p15, 0, r0, c5, c0, 3 + mcr p15, 0, r1, c5, c0, 2 + + /* ޔEAhX𒲍 */ + ldr r1, =HW_TWL_ROM_HEADER_BUF + 0x1c8 /* ARM9 pg풓W[ RAM AhX */ + ldr r1, [r1] + ldr r3, =HW_TWL_ROM_HEADER_BUF + 0x038 /* ARM7 p풓W[ RAM AhX */ + ldr r3, [r3] + sub r3, r3, #0x4000 /* ēǂݏos—̈TCY */ /* ARM7 pޔGA */ + sub r2, r3, #0x4000 /* ēǂݏos—̈TCY */ /* ARM9 pޔGA */ + + /* Rs[ */ +@loop: ldr r0, [r1], #4 + str r0, [r2], #4 + cmp r2, r3 + blt @loop + + /* ARM7 pCԕی샊[Wݒɖ߂ */ + ldmia sp!, {r0, r1} + mcr p15, 0, r0, c5, c0, 3 + mcr p15, 0, r1, c5, c0, 2 + bx lr +} + +/*---------------------------------------------------------------------------* + Name: MIi_UncompressBackward + Description: Uncompress special archive for module compression. + Arguments: bottom = Bottom adrs of packed archive + 1 + bottom[-8..-6] = offset for top of compressed data + inp_top = bottom - bottom[-8..-6] + bottom[-5] = offset for bottom of compressed data + inp = bottom - bottom[-5] + bottom[-4..-1] = offset for bottom of original data + outp = bottom + bottom[-4..-1] + typedef struct + { + u32 bufferTop:24; + u32 compressBottom:8; + u32 originalBottom; + } CompFooter; + Returns: None. + *---------------------------------------------------------------------------*/ +asm void +MIi_UncompressBackward(register void* bottom) +{ +#define data r0 +#define inp_top r1 +#define outp r2 +#define inp r3 +#define outp_save r4 +#define flag r5 +#define count8 r6 +#define index r7 +#define len r12 + + cmp bottom, #0 + beq @exit + stmfd sp!, {r4-r7} + ldmdb bottom, {r1-r2} + add outp, bottom, outp + sub inp, bottom, inp_top, LSR #24 + bic inp_top, inp_top, #0xff000000 + sub inp_top, bottom, inp_top + mov outp_save, outp +@loop: + cmp inp, inp_top // exit if inp==inp_top + ble @end_loop + ldrb flag, [inp, #-1]! // r4 = compress_flag = *--inp + mov count8, #8 +@loop8: + subs count8, count8, #1 + blt @loop + tst flag, #0x80 + bne @blockcopy +@bytecopy: + ldrb data, [inp, #-1]! + strb data, [outp, #-1]! // Copy 1 byte + b @joinhere +@blockcopy: + ldrb len, [inp, #-1]! + ldrb index, [inp, #-1]! + orr index, index, len, LSL #8 + bic index, index, #0xf000 + add index, index, #0x0002 + add len, len, #0x0020 +@patterncopy: + ldrb data, [outp, index] + strb data, [outp, #-1]! + subs len, len, #0x0010 + bge @patterncopy + +@joinhere: + cmp inp, inp_top + mov flag, flag, LSL #1 + bgt @loop8 +@end_loop: + + // DC_FlushRange & IC_InvalidateRange + mov r0, #0 + bic inp, inp_top, #HW_CACHE_LINE_SIZE - 1 +@cacheflush: + mcr p15, 0, r0, c7, c10, 4 // wait writebuffer empty + mcr p15, 0, inp, c7, c5, 1 // ICache + mcr p15, 0, inp, c7, c14, 1 // DCache + add inp, inp, #HW_CACHE_LINE_SIZE + cmp inp, outp_save + blt @cacheflush + + ldmfd sp!, {r4-r7} +@exit bx lr +} + +/*---------------------------------------------------------------------------* + Name: _start_AutoloadDoneCallback + Description: I[g[hR[obNB + Arguments: argv - I[g[hp[^ێĂzB + argv[0] = SDK_AUTOLOAD_LIST + argv[1] = SDK_AUTOLOAD_LIST_END + argv[2] = SDK_AUTOLOAD_START + argv[3] = SDK_STATIC_BSS_START + argv[4] = SDK_STATIC_BSS_END + Returns: ȂB + *---------------------------------------------------------------------------*/ +SDK_WEAK_SYMBOL asm void +_start_AutoloadDoneCallback(void* argv[]) +{ + bx lr +} + +/*---------------------------------------------------------------------------* + Name: INITi_InitCoprocessor + Description: VXeRvZbTB + ɁAI-TCM y D-TCM gp”\ȏԂɂB + Arguments: ȂB + Returns: ȂB + *---------------------------------------------------------------------------*/ +static asm void +INITi_InitCoprocessor(void) +{ + /* RvZbT̏Ԏ擾 */ + mrc p15, 0, r0, c1, c0, 0 + + tst r0, #HW_C1_PROTECT_UNIT_ENABLE + beq @010 + tst r0, #HW_C1_DCACHE_ENABLE + beq @003 + + /* D-Cache eɃCgobN */ + mov r1, #0 +@001: mov r2, #0 +@002: orr r3, r1, r2 + mcr p15, 0, r3, c7, c10, 2 + add r2, r2, #HW_CACHE_LINE_SIZE + cmp r2, #HW_DCACHE_SIZE / 4 + blt @002 + adds r1, r1, #1 << HW_C7_CACHE_SET_NO_SHIFT + bne @001 + +@003: /* Cgobt@ɂȂ̂҂ */ + mov r1, #0 + mcr p15, 0, r1, c7, c10, 4 + +@010: /* RvZbT̏Ԃ */ + ldr r1, = HW_C1_ITCM_LOAD_MODE \ + | HW_C1_DTCM_LOAD_MODE \ + | HW_C1_ITCM_ENABLE \ + | HW_C1_DTCM_ENABLE \ + | HW_C1_LD_INTERWORK_DISABLE \ + | HW_C1_ICACHE_ENABLE \ + | HW_C1_DCACHE_ENABLE \ + | HW_C1_PROTECT_UNIT_ENABLE + bic r0, r0, r1 + ldr r1, = HW_C1_SB1_BITSET \ + | HW_C1_EXCEPT_VEC_UPPER + orr r0, r0, r1 + mcr p15, 0, r0, c1, c0, 0 + + /* I-TCM ̃TCYݒ */ + mov r1, #HW_C9_TCMR_32MB + mcr p15, 0, r1, c9, c1, 1 + /* D-TCM ̃TCYyї̈x[XAhXݒ */ + ldr r1, =SDK_AUTOLOAD_DTCM_START + orr r1, r1, #HW_C9_TCMR_16KB + mcr p15, 0, r1, c9, c1, 0 + + /* I-TCM / D-TCM gpݒ */ + mov r1, #HW_C1_ITCM_ENABLE | HW_C1_DTCM_ENABLE + orr r0, r0, r1 + mcr p15, 0, r0, c1, c0, 0 + + bx lr +} + +/*---------------------------------------------------------------------------* + Name: INITi_InitRegion + Description: [WݒsB + Arguments: ȂB + Returns: ȂB + *---------------------------------------------------------------------------*/ +/* When hardware is TWL +; Region G: BACK_GROUND: Base = 0x0, Size = 4GB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 0: IO_VRAM: Base = 0x04000000, Size = 64MB, I:NC NB / D:NC NB, I:RW / D:RW +; Region 1: MAINMEM_WRAM: Base = 0x02000000, Size = 32MB, I:Cach Buf / D:Cach Buf, I:RW / D:RW +; Region 2: ARM7_RESERVE: Base = 0x02f80000, Size = 512KB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 3: EX_MAINMEM: Base = 0x0d000000, Size = 16MB, I:Cach Buf / D:Cach Buf, I:RW / D:RW +; Region 4: DTCM: Base = 0x02fe0000, Size = 16KB, I:NC NB / D:NC NB, I:NA / D:RW +; Region 5: ITCM: Base = 0x01000000, Size = 16MB, I:NC NB / D:NC NB, I:RW / D:RW +; Region 6: BIOS: Base = 0xffff0000, Size = 32KB, I:Cach NB / D:Cach NB, I:RO / D:RO +; Region 7: SHARED_WORK: Base = 0x02ffc000, Size = 16KB, I:NC NB / D:NC NB, I:NA / D:RW +*/ +/* When hardware is NITRO +; Region G: BACK_GROUND: Base = 0x0, Size = 4GB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 0: IO_VRAM: Base = 0x04000000, Size = 64MB, I:NC NB / D:NC NB, I:RW / D:RW +; Region 1: MAIN_MEM: Base = 0x02000000, Size = 8MB*, I:Cach Buf / D:Cach Buf, I:RW / D:RW +; (* When hardware is not debugger, size will be reduced to 4MB in OS_InitArena() ) +; Region 2: ARM7_RESERVE: Base = 0x027e0000, Size = 128KB, I:NC NB / D:NC NB, I:NA / D:NA +; (* When hardware is not debugger, base will be moved to 0x023e0000 in OS_InitArena() ) +; Region 3: CARTRIDGE: Base = 0x08000000, Size = 128MB, I:NC NB / D:NC NB, I:NA / D:RW +; Region 4: DTCM: Base = 0x02fe0000, Size = 16KB, I:NC NB / D:NC NB, I:NA / D:RW +; Region 5: ITCM: Base = 0x01000000, Size = 16MB, I:NC NB / D:NC NB, I:RW / D:RW +; Region 6: BIOS: Base = 0xffff0000, Size = 32KB, I:Cach NB / D:Cach NB, I:RO / D:RO +; Region 7: SHARED_WORK: Base = 0x02fff000, Size = 4KB, I:NC NB / D:NC NB, I:NA / D:RW +*/ + +static asm void +INITi_InitRegion(void) +{ +#define SET_PROTECTION_A(id, adr, siz) ldr r0, =(adr|HW_C6_PR_##siz|HW_C6_PR_ENABLE) +#define SET_PROTECTION_B(id, adr, siz) mcr p15, 0, r0, c6, id, 0 +#define REGION_BIT(a, b, c, d, e, f, g, h) (((a) << 0) | ((b) << 1) | ((c) << 2) | ((d) << 3) | ((e) << 4) | ((f) << 5) | ((g) << 6) | ((h) << 7)) +#define REGION_ACC(a, b, c, d, e, f, g, h) (((a) << 0) | ((b) << 4) | ((c) << 8) | ((d) << 12) | ((e) << 16) | ((f) << 20) | ((g) << 24) | ((h) << 28)) +#define NA 0 +#define RW 1 +#define RO 5 + + /* (0) I/O WX^y VRAM */ + SET_PROTECTION_A(c0, HW_IOREG, 64MB) + SET_PROTECTION_B(c0, HW_IOREG, 64MB) + + /* (4) D-TCM */ + ldr r0, =SDK_AUTOLOAD_DTCM_START + orr r0, r0, #HW_C6_PR_16KB | HW_C6_PR_ENABLE + SET_PROTECTION_B(c4, SDK_AUTOLOAD_DTCM_START, 16KB) + + /* (5) I-TCM */ + SET_PROTECTION_A(c5, HW_ITCM_IMAGE, 16MB) + SET_PROTECTION_B(c5, HW_ITCM_IMAGE, 16MB) + + /* (6) VXeR[ ROM */ + SET_PROTECTION_A(c6, HW_BIOS, 32KB) + SET_PROTECTION_B(c6, HW_BIOS, 32KB) + + /* TWL n[hEFAœ삵Ă邩ǂ𒲍 */ + ldr r1, =REG_CLK_ADDR + ldrh r0, [r1] + tst r0, #REG_SCFG_CLK_WRAMHCLK_MASK + beq @002 + +@001: /* n[hEFA TWL ̏ꍇ */ + /* (1) Cy WRAM */ + SET_PROTECTION_A(c1, HW_TWL_MAIN_MEM_MAIN, 32MB) + SET_PROTECTION_B(c1, HW_TWL_MAIN_MEM_MAIN, 32MB) + + /* (2) ARM7 pC */ + SET_PROTECTION_A(c2, HW_TWL_MAIN_MEM_SUB, 512KB) + SET_PROTECTION_B(c2, HW_TWL_MAIN_MEM_SUB, 512KB) + + /* (3) gC */ + SET_PROTECTION_A(c3, HW_TWL_MAIN_MEM_EX, 16MB) + SET_PROTECTION_B(c3, HW_TWL_MAIN_MEM_EX, 16MB) + + /* (7) ARM9/ARM7 LC */ + SET_PROTECTION_A(c7, HW_TWL_MAIN_MEM_SHARED, 16KB) + SET_PROTECTION_B(c7, HW_TWL_MAIN_MEM_SHARED, 16KB) + + /* ߃LbV */ + mov r0, #REGION_BIT(0, 1, 0, 1, 0, 0, 1, 0) + mcr p15, 0, r0, c2, c0, 1 + + /* f[^LbV */ +// mov r0, #REGION_BIT(0, 1, 0, 1, 0, 0, 1, 0) + mov r0, #REGION_BIT(0, 1, 1, 1, 0, 0, 1, 0) + mcr p15, 0, r0, c2, c0, 0 + + /* Cgobt@ */ +// mov r0, #REGION_BIT(0, 1, 0, 1, 0, 0, 0, 0) + mov r0, #REGION_BIT(0, 1, 1, 1, 0, 0, 0, 0) + mcr p15, 0, r0, c3, c0, 0 + + /* ߃ANZX */ + ldr r0, =REGION_ACC(RW, RW, NA, RW, NA, RW, RO, NA) + mcr p15, 0, r0, c5, c0, 3 + + /* f[^ANZX */ +// ldr r0, =REGION_ACC(RW, RW, NA, RW, RW, RW, RO, RW) + ldr r0, =REGION_ACC(RW, RW, RW, RW, RW, RW, RO, RW) + mcr p15, 0, r0, c5, c0, 2 +// b @003 + +@002: /* n[hEFA NITRO ̏ꍇ */ +#if 0 + /* (1) C */ + SET_PROTECTION_A(c1, HW_MAIN_MEM_MAIN, 8MB) + SET_PROTECTION_B(c1, HW_MAIN_MEM_MAIN, 8MB) + /* Size will be arranged in OS_InitArena(). */ + + /* (2) ARM7 pC */ + SET_PROTECTION_A(c2, (HW_MAIN_MEM_EX_END - HW_MAIN_MEM_SHARED_SIZE - HW_MAIN_MEM_SUB_SIZE), 128KB) + SET_PROTECTION_B(c2, (HW_MAIN_MEM_EX_END - HW_MAIN_MEM_SHARED_SIZE - HW_MAIN_MEM_SUB_SIZE), 128KB) + /* Base address will be moved in OS_InitArena(). */ + + /* (3) J[gbW */ + SET_PROTECTION_A(c3, HW_CTRDG_ROM, 128MB) + SET_PROTECTION_B(c3, HW_CTRDG_ROM, 128MB) + + /* (7) ARM9/ARM7 LC */ + SET_PROTECTION_A(c7, HW_MAIN_MEM_SHARED, 4KB) + SET_PROTECTION_B(c7, HW_MAIN_MEM_SHARED, 4KB) + + /* ߃LbV */ + mov r0, #REGION_BIT(0, 1, 0, 0, 0, 0, 1, 0) + mcr p15, 0, r0, c2, c0, 1 + + /* f[^LbV */ + mov r0, #REGION_BIT(0, 1, 0, 0, 0, 0, 1, 0) + mcr p15, 0, r0, c2, c0, 0 + + /* Cgobt@ */ + mov r0, #REGION_BIT(0, 1, 0, 0, 0, 0, 0, 0) + mcr p15, 0, r0, c3, c0, 0 + + /* ߃ANZX */ + ldr r0, =REGION_ACC(RW, RW, NA, NA, NA, RW, RO, NA) + mcr p15, 0, r0, c5, c0, 3 + + /* f[^ANZX */ + ldr r0, =REGION_ACC(RW, RW, NA, RW, RW, RW, RO, RW) + mcr p15, 0, r0, c5, c0, 2 +#endif +@003: /* veNVjbgyуLbVgpݒ */ + mrc p15, 0, r0, c1, c0, 0 + ldr r1, = HW_C1_ICACHE_ENABLE \ + | HW_C1_DCACHE_ENABLE \ + | HW_C1_CACHE_ROUND_ROBIN \ + | HW_C1_PROTECT_UNIT_ENABLE + orr r0, r0, r1 + mcr p15, 0, r0, c1, c0, 0 + + /* LbV̓ej */ + mov r1, #0 + mcr p15, 0, r1, c7, c6, 0 + mcr p15, 0, r1, c7, c5, 0 + + bx lr +} + + +/*---------------------------------------------------------------------------* + Name: TwlStartUp + + Description: hook for user start up + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +SDK_WEAK_SYMBOL void TwlStartUp(void) +{ +} + +/*---------------------------------------------------------------------------* + Name: OSi_ReferSymbol + + Description: used by SDK_REFER_SYMBOL macro to avoid dead-strip. + + Arguments: symbol unused + + Returns: None. + *---------------------------------------------------------------------------*/ +void OSi_ReferSymbol(void *symbol) +{ +#pragma unused(symbol) +} diff --git a/build/libraries/init/Makefile b/build/libraries/init/Makefile new file mode 100644 index 0000000..ce0d6f5 --- /dev/null +++ b/build/libraries/init/Makefile @@ -0,0 +1,32 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - init +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 \ + ARM7 \ + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/mi/ARM9/Makefile b/build/libraries/mi/ARM9/Makefile new file mode 100644 index 0000000..e8461f1 --- /dev/null +++ b/build/libraries/mi/ARM9/Makefile @@ -0,0 +1,60 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - mi +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +SUBMAKES = + + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +SRCDIR = . ../common + +SRCS = \ + mi_init_mainMemory.c \ + mi_loader.c \ + mi_exDma.c \ + +TARGET_LIB = libmi$(FIRM_LIBSUFFIX).a + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + +ifdef NITRO_CALLTRACE +CCFLAGS += -DOS_PROFILE_AVAILABLE -DOS_PROFILE_CALL_TRACE +endif + +ifdef NITRO_FUNCTIONCOST +CCFLAGS += -DOS_PROFILE_AVAILABLE -DOS_PROFILE_FUNCTION_COST +endif + +ifdef NITRO_TCM_APPLY +CCFLAGS += -DSDK_TCM_APPLY +endif + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/mi/ARM9/mi_init_mainMemory.c b/build/libraries/mi/ARM9/mi_init_mainMemory.c new file mode 100644 index 0000000..87e1d39 --- /dev/null +++ b/build/libraries/mi/ARM9/mi_init_mainMemory.c @@ -0,0 +1,160 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - mi + File: mi_init_mainMemory.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include + +void MIi_InitMainMemCRCore( void ); + +/*---------------------------------------------------------------------------* + Name: MIi_IsMainMemoryInitialized + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL MIi_IsMainMemoryInitialized( void ) +{ + return (BOOL)((reg_MI_EXMEMCNT & REG_MI_EXMEMCNT_CE2_MASK) >> REG_MI_EXMEMCNT_CE2_SHIFT); +} + +/*---------------------------------------------------------------------------* + Name: MIi_WaitMainMemoryInitialize + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_WaitMainMemoryInitialize( void ) +{ + while( MIi_IsMainMemoryInitialized() == FALSE ) + { + } +} + + +/*---------------------------------------------------------------------------* + Name: MIi_InitMainMemCR + + Description: change mainmem into the burst mode + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +#include + +asm void MIi_InitMainMemCR( BOOL setCR ) +{ + mov r12, lr + + mov r2, r0 + + mov r0, #0x8000 // low period 0.97ms + bl OS_SpinWaitCpuCycles + + ldr r3, =REG_EXMEMCNT_ADDR + mov r1, #REG_MI_EXMEMCNT_CE2_MASK + ldrh r0, [r3] + tst r0, r1 + bxne r12 + + strh r1, [r3] + + mov r0, #0x8000 // high period 0.97ms + bl OS_SpinWaitCpuCycles + + cmp r2, #FALSE + beq @10 + + // C[hin[hZbgj + // 񓯊[hiCLKŒjŃR}hsĂv + ldr r3, =HW_WRAM_AREA - 2 + bl MIi_InitMainMemCRCore +#ifdef TWL_PLATFORM_TS + ldr r3, =HW_MAIN_MEM_HI_EX_END - 2 + bl MIi_InitMainMemCRCore +#endif // TWL_PLATFORM_TS + +@10: + ldr r3, =REG_EXMEMCNT_ADDR + mov r1, #REG_MI_EXMEMCNT_IFM_MASK | REG_MI_EXMEMCNT_CE2_MASK + strh r1, [r3] + + bx r12 +} + +asm void MIi_InitMainMemCRCore( void ) +{ +// stmfd sp!, { lr } + +#ifdef TWL_PLATFORM_BB + mov r2, lr + ldr r0, =MMEM_DCR0_BURST_MODE | MMEM_DCR0_BURST_CONTINUOUS \ + | MMEM_DCR0_PARTIAL_REFRESH_NONE | MMEM_DCR0_SB1 + ldr r1, =MMEM_DCR1_1ST_R4_W3 | MMEM_DCR1_BURST_WRITE | MMEM_DCR1_BURST_LINER \ + | MMEM_DCR1_CLOCK_TRIGGER_UP | MMEM_DCR1_SB1 + ldrh lr, [r3] + strh lr, [r3] + strh lr, [r3] + mov lr, r2 + ldr r2, =HW_MAIN_MEM | MMEM_DCR2_CLOCK_TRIGGER_UP \ + | MMEM_DCR2_BURST_MODE | MMEM_DCR2_BURST_CONTINUOUS \ + | MMEM_DCR2_1ST_R4_W3 | MMEM_DCR2_BURST_WRITE | MMEM_DCR2_BURST_LINER \ + | MMEM_DCR2_PARTIAL_REFRESH_NONE | MMEM_DCR2_SB1 + strh r0, [r3] + strh r1, [r3] + ldrh r3, [r2] +#else // TWL_PLATFORM_TS + mov r2, lr + ldr r0, =MMEM_TCR0 + ldr r1, =MMEM_TCR1 + ldrh lr, [r3] + strh lr, [r3] + strh lr, [r3] + mov lr, r2 + ldr r2, =MMEM_TCR2 + strh r0, [r3] + strh r1, [r3] + strh r2, [r3] +#endif // TWL_PLATFORM_TS + +// ldmfd sp!, { lr } + bx lr +} + +asm void MIi_GetMainMemCR( MIMmemCR* dest ) +{ +#ifdef TWL_PLATFORM_TS + ldr r3, =HW_WRAM_AREA - 2 + ldr r1, =MMEM_TCR0_R + ldrh r2, [r3] + strh r2, [r3] + strh r2, [r3] + strh r1, [r3] + ldrh r1, [r3] + ldrh r2, [r3] + strh r2, [r0, #4] + strh r1, [r0, #2] + ldr r1, =MMEM_TCR0_R + strh r1, [r0, #0] +#endif // TWL_PLATFORM_TS + + bx lr +} \ No newline at end of file diff --git a/build/libraries/mi/ARM9/mi_loader.c b/build/libraries/mi/ARM9/mi_loader.c new file mode 100644 index 0000000..803976c --- /dev/null +++ b/build/libraries/mi/ARM9/mi_loader.c @@ -0,0 +1,509 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - mi + File: mi_loader.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include + +/* + PROFILE_ENABLE `Ƃx̃ptH[}X`FbNł܂B + p邽߂ɂ́Amain.cǂɁAu32 profile[256]; u32 pf_cnt; + `Kv܂B +*/ +//#define PROFILE_ENABLE + +#ifdef SDK_FINALROM // FINALROMŖ +#undef PROFILE_ENABLE +#endif + +#ifdef PROFILE_ENABLE +#define PROFILE_PXI_SEND 0x10000000 +#define PROFILE_PXI_RECV 0x20000000 +#define PROFILE_SHA1 0xa0000000 +#define PROFILE_RSA 0xb0000000 +extern u32 profile[]; +extern u32 pf_cnt; +#endif + + +#define PXI_FIFO_TAG_DATA PXI_FIFO_TAG_USER_0 + +static ROM_Header* const rh = (ROM_Header*)HW_TWL_ROM_HEADER_BUF; + +#define HEADER_SIZE 0x1000 +#define AUTH_SIZE 0xe00 +#define RSA_BLOCK_SIZE 128 + +#define HASH_UNIT 0x1000 // TODO: optimizing to maximize cache efficiency + +static const u8 s_digestDefaultKey[ SVC_SHA1_BLOCK_SIZE ] = { + 0x21, 0x06, 0xc0, 0xde, + 0xba, 0x98, 0xce, 0x3f, + 0xa6, 0x92, 0xe3, 0x9d, + 0x46, 0xf2, 0xed, 0x01, + + 0x76, 0xe3, 0xcc, 0x08, + 0x56, 0x23, 0x63, 0xfa, + 0xca, 0xd4, 0xec, 0xdf, + 0x9a, 0x62, 0x78, 0x34, + + 0x8f, 0x6d, 0x63, 0x3c, + 0xfe, 0x22, 0xca, 0x92, + 0x20, 0x88, 0x97, 0x23, + 0xd2, 0xcf, 0xae, 0xc2, + + 0x32, 0x67, 0x8d, 0xfe, + 0xca, 0x83, 0x64, 0x98, + 0xac, 0xfd, 0x3e, 0x37, + 0x87, 0x46, 0x58, 0x24, +}; + +/*---------------------------------------------------------------------------* + Name: CheckRomCertificate + + Description: check the certification in the ROM + + ROMwb_ɕtꂽؖ̃`FbNs܂B + makerom.TWL̃R[hɈˑ܂B + + Arguments: pool pointer to the SVCSignHeapContext + pCert pointer to the certification + pCAPubKey pointer to the public key for the certification + gameCode initial code + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +static BOOL CheckRomCertificate( SVCSignHeapContext* pool, const RomCertificate *pCert, const void* pCAPubKey, u32 gameCode ) +{ + u8 digest[DIGEST_SIZE_SHA1]; + u8 md[DIGEST_SIZE_SHA1]; + int i; + BOOL result = TRUE; + + // ؖwb_̃}WbNio[`FbN + if( pCert->header.magicNumber != TWL_ROM_CERT_MAGIC_NUMBER || + // ؖwb_ROMwb_̃Q[R[hv`FbN + pCert->header.gameCode != gameCode ) + { + result = FALSE; + } + // ؖ`FbN + SVC_DecryptSign( pool, &digest, pCert->sign, pCAPubKey ); + + // _CWFXǧvZ + SVC_CalcSHA1( md, pCert, ROM_CERT_SIGN_OFFSET ); + + // r + for (i = 0; i < DIGEST_SIZE_SHA1; i++) + { + if ( md[i] != digest[i] ) + { + result = FALSE; + } + } + + return result; +} + +/*---------------------------------------------------------------------------* + Name: MIi_LoadBuffer + + Description: receive data from ARM7 and store(move) via WRAM[B] + + LoadBufferJjYŁAt@C̓eARM7󂯎܂B + SVCSHA1Contextw肵ĂꍇARs[̂‚łSHA1 + vZs܂B + + [LoadBufferJjY] + WRAM[B]𗘗pāAARM7,ARM9Ԃ̃f[^]s܂B + WRAM[B]̊eXbgoPc[œn܂B + 1Xbg̃f[^܂͑Sf[^i[ꂽƂAARM7 + FIRM_PXI_ID_LOAD_PIRIODM܂B + ARM9͎Mɂ̃Xbg̎gpARM9ɕύXăf[^ + oAɃNA(ZLeB)Agp + ARM7ɖ߂܂B + + [gp] + WRAM[B]bNAԂƂARM7ɓ|ĂƁB + + [ӓ_] + offsetsizeARM7ʒm܂Bʂ̌oHœĂB + SRLt@Cǂݍޏꍇ́A݂ROMwb_QƂłΏ\łB + (ROMwb_͌mĂ͂) + + ⑫: + ł́A郉CuARM7/ARM9ŕ킹邱Ƃ + OɂĂ邪AėpIɂɂ(ƗCuȂ)A + MŃXbg𔼕‚ƂAꂼɎMPXIR[obN + XbhpӂAMAPIf[^WRAMɊi[A + destsizeʒmƂ`OKł͂ȂH + (ŊԎԂ) + + Arguments: dest destination address for received data + size size to load + ctx context for SHA1 if execute SVC_SHA1Update + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +static BOOL MIi_LoadBuffer(u8* dest, u32 size, SVCSHA1Context *ctx) +{ + u8* base = (u8*)HW_FIRM_LOAD_BUFFER_BASE; + static int count = 0; + + while (size > 0) + { + u8* src = base + count * HW_FIRM_LOAD_BUFFER_UNIT_SIZE; + u32 unit = size < HW_FIRM_LOAD_BUFFER_UNIT_SIZE ? size : HW_FIRM_LOAD_BUFFER_UNIT_SIZE; + //OS_TPrintf("%s: src=%X, unit=%X\n", __func__, src, unit); + if ( PXI_RecvID() != FIRM_PXI_ID_LOAD_PIRIOD ) + { + return FALSE; + } +#ifdef PROFILE_ENABLE + // x2...: after PXI + profile[pf_cnt++] = PROFILE_PXI_RECV | FIRM_PXI_ID_LOAD_PIRIOD; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + MIi_SetWramBankMaster_B(count, MI_WRAM_ARM9); + if (ctx) + { + int done; + for (done = 0; done < unit; done += HASH_UNIT) + { + u8* s = src + done; + u8* d = dest + done; + u32 u = unit < done + HASH_UNIT ? unit - done : HASH_UNIT; + MI_CpuCopyFast( s, d, u ); + SVC_SHA1Update( ctx, s, u ); + } + } + else + { + MI_CpuCopyFast( src, dest, unit ); + } + MI_CpuClearFast( src, unit ); + DC_FlushRange( src, unit ); +#ifdef PROFILE_ENABLE + // x2...: after copy & clear + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + MIi_SetWramBankMaster_B(count, MI_WRAM_ARM7); + count = (count + 1) % HW_FIRM_LOAD_BUFFER_UNIT_NUMS; + size -= unit; + dest += unit; + } + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: MI_LoadHeader + + Description: load header + + SRLROMwb_ARM7󂯎AF؂܂B + MOɁAARM7 FIRM_PXI_ID_LOAD_HEADER M܂B + MAF؂ʂȂARM7 FIRM_PXI_ID_AUTH_HEADER 𑗐M + ܂BȑOɁAC̏̈ʒuROMwb_i[ + ĂȂ΂Ȃ܂B + āAseedf[^16oCgM܂B + makerom.TWL܂IPL̎dlɈˑ܂B + + Arguments: pool pointer to the pool info for SVCSignHeapContext + rsa_key key address + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL MI_LoadHeader( SVCSignHeapContext* pool, const void* rsa_key ) +{ + SVCSHA1Context ctx; + u8 md[DIGEST_SIZE_SHA1]; + SignatureData sd; + int i; + BOOL result = TRUE; + + SVC_SHA1Init(&ctx); + +#ifdef PROFILE_ENABLE + pf_cnt = 0x10; +#endif + // load header (hash target) + if ( PXI_RecvID() != FIRM_PXI_ID_LOAD_HEADER || +#ifdef PROFILE_ENABLE + // 10: after PXI + ((profile[pf_cnt++] = PROFILE_PXI_RECV | FIRM_PXI_ID_LOAD_HEADER), FALSE) || + ((profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick())), FALSE) || +#endif + !MIi_LoadBuffer( (u8*)rh, AUTH_SIZE, &ctx ) ) + { + return FALSE; + } + SVC_SHA1GetHash(&ctx, md); +#ifdef PROFILE_ENABLE + // 1x: after HMAC + profile[pf_cnt++] = PROFILE_SHA1; // checkpoint + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + // load header (remain) + if ( !MIi_LoadBuffer( (u8*)rh + AUTH_SIZE, HEADER_SIZE - AUTH_SIZE, NULL ) ) + { + return FALSE; + } + + // Recؖ + if ( CheckRomCertificate( pool, &rh->certificate, rsa_key, *(u32*)rh->s.game_code ) ) + { + rsa_key = rh->certificate.pubKeyMod; // wb_p̌̎o + } + else + { + // Ƃ肠Recؖp̌̂܂܎gƉ + } + + // wb_`FbN + SVC_DecryptSign( pool, &sd, rh->signature, rsa_key ); + for (i = 0; i < DIGEST_SIZE_SHA1; i++) + { + if ( md[i] != sd.digest[i] ) + { + result = FALSE; + } + } +#ifdef PROFILE_ENABLE + // 1x: after RSA, before PXI + profile[pf_cnt++] = PROFILE_RSA; // checkpoint + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + profile[pf_cnt++] = (u32)PROFILE_PXI_SEND | FIRM_PXI_ID_AUTH_HEADER; // checkpoint +#endif + if ( result ) + { + PXI_NotifyID( FIRM_PXI_ID_AUTH_HEADER ); + PXI_SendDataByFifo( PXI_FIFO_TAG_DATA, sd.aes_key_seed, AES_BLOCK_SIZE ); + // DS݊wb_Rs[ + MI_CpuCopyFast( rh, (void*)HW_ROM_HEADER_BUF, HW_ROM_HEADER_BUF_END-HW_ROM_HEADER_BUF ); + } + MI_CpuClear8(&sd, sizeof(sd)); + MI_CpuClear8(&md, sizeof(md)); + + return result; +} + +/*---------------------------------------------------------------------------* + Name: MIi_GetTransferSize + + Description: get size to transfer once + + xɎMTCYԂ܂B + + ]͈͂AES̈܂ꍇ́AE܂ł̃TCY ( + ȃTCY) Ԃ܂B + makerom.TWL܂IPL̎gpɈˑ܂B + + Arguments: offset offset of region from head of ROM_Header + size size of region + + Returns: size to transfer once + *---------------------------------------------------------------------------*/ +static u32 MIi_GetTransferSize( u32 offset, u32 size ) +{ + u32 aes_offset = rh->s.aes_target_rom_offset; + u32 aes_end = aes_offset + rh->s.aes_target_size; + u32 end = offset + size; + if ( rh->s.enable_aes ) + { + if ( offset >= aes_offset && offset < aes_end ) + { + if ( end > aes_end ) + { + size = aes_end - offset; + } + } + else + { + if ( offset < aes_offset && offset + size > aes_offset ) + { + size = aes_offset - offset; + } + } + } + return size; +} + +/*---------------------------------------------------------------------------* + Name: MIi_LoadModule + + Description: receive module from ARM7 and store(move) via WRAM[B] + + MIi_LoadBuffeȑAPIłB + + AESE܂ꍇ́A2LoadBufferɕ܂B + + łɃnbVlĂāA傤SHA1̌vZ͈͑Ŝ + ǂݍޏꍇɕ֗łB + + Arguments: dest destination address for received data + offset offset from head of ROM_Header + size size to load + digest digest to compare + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +static /*inline*/ BOOL MIi_LoadModule(void* dest, u32 offset, u32 size, const u8 digest[DIGEST_SIZE_SHA1]) +{ + SVCHMACSHA1Context ctx; + u8 md[DIGEST_SIZE_SHA1]; + int i; + BOOL result = TRUE; + + SVC_HMACSHA1Init(&ctx, s_digestDefaultKey, SVC_SHA1_BLOCK_SIZE ); + while ( size > 0 ) + { + u32 unit = MIi_GetTransferSize( offset, size ); + if ( !MIi_LoadBuffer( dest, unit, &ctx.sha1_ctx ) ) // UpdateSHA1Ɠ + { + return FALSE; + } + dest = (u8*)dest + unit; + offset += unit; + size -= unit; + } + SVC_HMACSHA1GetHash(&ctx, md); +#ifdef PROFILE_ENABLE + // 3x: after SHA1 + profile[pf_cnt++] = PROFILE_SHA1; // checkpoint + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + for (i = 0; i < DIGEST_SIZE_SHA1; i++) + { + if (md[i] != digest[i]) + { + result = FALSE; + } + } + MI_CpuClear8(md, DIGEST_SIZE_SHA1); + return result; +} + +/*---------------------------------------------------------------------------* + Name: MI_LoadStatic + + Description: load static binary + + ARM9/ARM7StaticLTD StaticM܂B + MOɁAARM7FIRM_PXI_ID_LOAD_*_STATICM܂B + MAF؂ʂȂARM7FIRM_PXI_ID_AUTH_*_STATIC𑗐M + ܂BTCY0̏ꍇ́Ãp[gPXIʐMs܂B + + APIĂяoOɁAC̏̈ʒuROMwb_ + i[ĂKv܂B + + Arguments: None + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL MI_LoadStatic( void ) +{ + // load static + if ( PXI_RecvID() != FIRM_PXI_ID_LOAD_STATIC ) + { + return FALSE; + } +#ifdef PROFILE_ENABLE + // 30: after PXI + pf_cnt = 0x30; + profile[pf_cnt++] = PROFILE_PXI_RECV | FIRM_PXI_ID_LOAD_STATIC; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + // load ARM9 static region + if ( rh->s.main_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 31: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !MIi_LoadModule(rh->s.main_ram_address, rh->s.main_rom_offset, rh->s.main_size, rh->s.main_static_digest) ) + { + return FALSE; + } + } + + // load ARM7 static region + if ( rh->s.sub_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 50: before PXI + pf_cnt = 0x50; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !MIi_LoadModule( rh->s.sub_ram_address, rh->s.sub_rom_offset, rh->s.sub_size, rh->s.sub_static_digest ) ) + { + return FALSE; + } + } + + // load ARM9 extended static region + if ( rh->s.main_ltd_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 70: before PXI + pf_cnt = 0x70; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !MIi_LoadModule( rh->s.main_ltd_ram_address, rh->s.main_ltd_rom_offset, rh->s.main_ltd_size, rh->s.main_ltd_static_digest ) ) + { + return FALSE; + } + } + // load ARM7 extended static region + if ( rh->s.sub_ltd_size > 0 ) + { +#ifdef PROFILE_ENABLE + // 90: before PXI + pf_cnt = 0x90; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + if ( !MIi_LoadModule( rh->s.sub_ltd_ram_address, rh->s.sub_ltd_rom_offset, rh->s.sub_ltd_size, rh->s.sub_ltd_static_digest ) ) + { + return FALSE; + } + } +#ifdef PROFILE_ENABLE + // 9x: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + profile[pf_cnt++] = (u32)PROFILE_PXI_SEND | FIRM_PXI_ID_AUTH_STATIC; // checkpoint +#endif + PXI_NotifyID( FIRM_PXI_ID_AUTH_STATIC ); + return TRUE; +} + +/*---------------------------------------------------------------------------* + Name: MI_Boot + + Description: boot + + ROMwb_̏ɁAOSi_BootĂяołB + + APIĂяoOɁAC̏̈ʒuROMwb_ + i[ĂKv܂B + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void MI_Boot( void ) +{ + OSi_Boot( rh->s.main_entry_address, (MIHeader_WramRegs*)rh->s.main_wram_config_data ); +} diff --git a/build/libraries/mi/Makefile b/build/libraries/mi/Makefile new file mode 100644 index 0000000..54d99b0 --- /dev/null +++ b/build/libraries/mi/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - mi +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/mi/common/mi_exDma.c b/build/libraries/mi/common/mi_exDma.c new file mode 100644 index 0000000..5fab0b0 --- /dev/null +++ b/build/libraries/mi/common/mi_exDma.c @@ -0,0 +1,286 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - mi + File: mi_init_mainMemory.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +static u16 intervalTable[] = +{ + 1, 1, 1, 1, +}; + +static u32 prescaleTable[] = +{ + MI_NDMA_INTERVAL_PS_1, + MI_NDMA_INTERVAL_PS_1, + MI_NDMA_INTERVAL_PS_1, + MI_NDMA_INTERVAL_PS_1, +}; + +//================================================================================ +// memory oparation using DMA (sync) +//================================================================================ + +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaSendAsync + + Description: send data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaSendAsync( u32 dmaNo, const void *src, void *dest, u32 size ) +{ + u32 idx = dmaNo - MI_EXDMA_CH_MIN; + + { + u32 blockSize = MI_NDMA_BWORD_8; + u32 interval = intervalTable[idx]; + u32 prescale = prescaleTable[idx]; + + MIi_ExDmaSendAsyncCore( dmaNo, src, dest, size, size, + blockSize, interval, prescale, + MI_NDMA_CONTINUOUS_OFF, MI_NDMA_SRC_RELOAD_DISABLE, MI_NDMA_DEST_RELOAD_DISABLE, + MI_NDMA_IMM_MODE_ON ); + } +} + +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaRecvAsync + + Description: receive data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaRecvAsync( u32 dmaNo, const void *src, void *dest, u32 size ) +{ + u32 idx = dmaNo - MI_EXDMA_CH_MIN; + + { + u32 blockSize = MI_NDMA_BWORD_8; + u32 interval = intervalTable[idx]; + u32 prescale = prescaleTable[idx]; + + MIi_ExDmaRecvAsyncCore( dmaNo, src, dest, size, size, + blockSize, interval, prescale, + MI_NDMA_CONTINUOUS_OFF, MI_NDMA_SRC_RELOAD_DISABLE, MI_NDMA_DEST_RELOAD_DISABLE, + MI_NDMA_IMM_MODE_ON ); + } +} + +//----------------- internel functions ------------------- + +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaSendAsyncCore + + Description: send data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + blockSize : block size + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaSendAsyncCore( u32 dmaNo, const void *src, void *dest, u32 size, u32 oneShotSize, + u32 blockSize, u32 interval, u32 prescale, + u32 continuous, u32 srcRld, u32 destRld, + u32 timing ) +{ + MIi_WaitExDma( dmaNo ); + + MIi_SetExDmaParams( dmaNo, src, dest, size, oneShotSize, + blockSize, interval, prescale, + continuous, srcRld, destRld, + timing, + 0, MI_NDMA_SRC_INC, MI_NDMA_DEST_FIX ); +} + +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaRecvAsyncCore + + Description: receive data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + blockSize : block size + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaRecvAsyncCore( u32 dmaNo, const void *src, void *dest, u32 size, u32 oneShotSize, + u32 blockSize, u32 interval, u32 prescale, + u32 continuous, u32 srcRld, u32 destRld, + u32 timing ) +{ + MIi_WaitExDma( dmaNo ); + + MIi_SetExDmaParams( dmaNo, src, dest, size, oneShotSize, + blockSize, interval, prescale, + continuous, srcRld, destRld, + timing, + 0, MI_NDMA_SRC_FIX, MI_NDMA_DEST_INC ); +} + +/*---------------------------------------------------------------------------* + Name: MIi_SetExDmaParams + + Description: set DMA + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + blockSize : block size + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_SetExDmaParams( u32 dmaNo, const void *src, void *dest, u32 size, u32 oneShotSize, + u32 blockSize, u32 interval, u32 prescale, + u32 continuous, u32 srcRld, u32 destRld, + u32 timing, + u32 fillData, u32 srcDir, u32 destDir ) +{ + u32 idx = dmaNo - MI_EXDMA_CH_MIN; + + if ( idx < MI_EXDMA_CH_NUM ) + { + OSIntrMode enabled = OS_DisableInterrupts(); + + MIExDmaChanRegs *reg = &((MIExDmaChanRegs*)REG_NDMA0SAD_ADDR)[idx]; + + reg->src = src; + reg->dest = dest; + reg->fillData = fillData; + reg->totalCount = size / 4; + reg->wordCount = oneShotSize / 4; + reg->blockInterval = (interval << REG_MI_NDMA0BCNT_ICNT_SHIFT) | prescale; + reg->ctrl = blockSize + | srcDir | destDir + | srcRld | destRld + | continuous + | timing + | MI_NDMA_ENABLE | MI_NDMA_IF_ENABLE; + + (void)OS_RestoreInterrupts(enabled); + } +} + +//================================================================================ +// DMA WAIT/STOP +//================================================================================ +/*---------------------------------------------------------------------------* + Name: MIi_IsExDmaBusy + + Description: check whether extended DMA is busy or not + + Arguments: dmaNo : DMA channel No. + + Returns: TRUE if extended DMA is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL MIi_IsExDmaBusy( u32 dmaNo ) +{ + u32 idx = dmaNo - MI_EXDMA_CH_MIN; + + if ( idx < MI_EXDMA_CH_NUM ) + { + MIExDmaChanRegs *reg = &((MIExDmaChanRegs*)REG_NDMA0SAD_ADDR)[idx]; + + return (BOOL)((reg->ctrl & REG_MI_NDMA0CNT_E_MASK) >> REG_MI_NDMA0CNT_E_SHIFT); + } + + return FALSE; +} + +/*---------------------------------------------------------------------------* + Name: MIi_WaitExDma + + Description: wait while extended DMA is busy + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_WaitExDma( u32 dmaNo ) +{ + u32 idx = dmaNo - MI_EXDMA_CH_MIN; + + if ( idx < MI_EXDMA_CH_NUM ) + { + MIExDmaChanRegs *reg = &((MIExDmaChanRegs*)REG_NDMA0SAD_ADDR)[idx]; + + while (reg->ctrl & REG_MI_NDMA0CNT_E_MASK) + { + } + } +} + +/*---------------------------------------------------------------------------* + Name: MIi_StopDma + + Description: stop extended DMA + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_StopExDma( u32 dmaNo ) +{ + MIi_StopExDmaAsync( dmaNo ); + MIi_WaitExDma( dmaNo ); +} + +/*---------------------------------------------------------------------------* + Name: MIi_StopDmaAsync + + Description: stop extended DMA + async version + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_StopExDmaAsync( u32 dmaNo ) +{ + OSIntrMode enabled = OS_DisableInterrupts(); + + u32 idx = dmaNo - MI_EXDMA_CH_MIN; + + if ( idx < MI_EXDMA_CH_NUM ) + { + MIExDmaChanRegs *reg = &((MIExDmaChanRegs*)REG_NDMA0SAD_ADDR)[idx]; + + reg->ctrl &= ~MI_NDMA_ENABLE; + } + + (void)OS_RestoreInterrupts(enabled); +} + diff --git a/build/libraries/os/ARM7/Makefile b/build/libraries/os/ARM7/Makefile new file mode 100644 index 0000000..8ebb450 --- /dev/null +++ b/build/libraries/os/ARM7/Makefile @@ -0,0 +1,62 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries_sp - os +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +#SUBMAKES = Makefile.CALLTRACE \ +# Makefile.FUNCTIONCOST + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +# Codegen for sub processer +FIRM_PROC = ARM7 + +SRCDIR = ../common . + +SRCS = \ + os_init_firm.c \ + os_boot.c \ + +TARGET_LIB = libos_sp$(FIRM_LIBSUFFIX).a + + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/os/ARM9/Makefile b/build/libraries/os/ARM9/Makefile new file mode 100644 index 0000000..2e55190 --- /dev/null +++ b/build/libraries/os/ARM9/Makefile @@ -0,0 +1,60 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - os +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +SUBMAKES = + + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +SRCDIR = ../common . + +SRCS = \ + os_init_firm.c \ + os_boot.c \ + os_cache_tag.c \ + +TARGET_LIB = libos$(FIRM_LIBSUFFIX).a + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + +ifdef NITRO_CALLTRACE +CCFLAGS += -DOS_PROFILE_AVAILABLE -DOS_PROFILE_CALL_TRACE +endif + +ifdef NITRO_FUNCTIONCOST +CCFLAGS += -DOS_PROFILE_AVAILABLE -DOS_PROFILE_FUNCTION_COST +endif + +ifdef NITRO_TCM_APPLY +CCFLAGS += -DSDK_TCM_APPLY +endif + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/os/ARM9/os_cache_tag.c b/build/libraries/os/ARM9/os_cache_tag.c new file mode 100644 index 0000000..cb16308 --- /dev/null +++ b/build/libraries/os/ARM9/os_cache_tag.c @@ -0,0 +1,269 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS + File: os_cache_tag.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + + +//=========================================================================== +// DATA CACHE (for specified range) +//=========================================================================== +/*---------------------------------------------------------------------------* + Name: DC_ClearTagAll + + Description: clear tag in data cache + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +void DC_ClearTagAll( void ) +{ + DC_FillTagAll( 0 ); +} + +/*---------------------------------------------------------------------------* + Name: DC_FillTagAll + + Description: clear tag in data cache + + Arguments: data : fill data + + Returns: None. + *---------------------------------------------------------------------------*/ +asm void DC_FillTagAll( u32 data ) +{ + mov r12, #0 +@1: + mov r2, #0 +@2: + orr r3, r2, r12 + mcr p15, 3, r3, c15, c0, 0 // set index + mcr p15, 3, r0, c15, c2, 0 // clear tag + add r2, r2, #HW_CACHE_LINE_SIZE + cmp r2, #HW_DCACHE_SIZE/4 + blt @2 + + add r12, r12, #1< diff --git a/build/libraries/os/Makefile b/build/libraries/os/Makefile new file mode 100644 index 0000000..a61613f --- /dev/null +++ b/build/libraries/os/Makefile @@ -0,0 +1,32 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - os +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 \ + ARM7 \ + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/os/common/os_boot.c b/build/libraries/os/common/os_boot.c new file mode 100644 index 0000000..103efb1 --- /dev/null +++ b/build/libraries/os/common/os_boot.c @@ -0,0 +1,219 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS + File: os_boot.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include +#include +#ifdef SDK_ARM9 +#include +#else +#include +#endif + +#if 0 + ۑ: + OSi_BootCorẽRs[挈 + + 낢NA (ITCM,DTCM,STACK,TEXT,RODATA,DATAȂ (OSi_BootCore͎c)) + Ȃ̂ŁAOSi_BootCorẽ͎vOłɉ󂳂ꂻȂƂg +#endif + +void OSi_BootCore( OSEntryPoint p, MIHeader_WramRegs* w ); + +/*---------------------------------------------------------------------------* + Name: OSi_Boot + + Description: boot firm + + Arguments: entry : entry point + w : wram settings + + Returns: None + *---------------------------------------------------------------------------*/ +void OSi_Boot( void* entry, MIHeader_WramRegs* w ) +{ + OSEntryPoint p = (OSEntryPoint)entry; + void (*OSBootCore)( OSEntryPoint p, MIHeader_WramRegs* w ); + + (void)OS_DisableInterrupts(); + OSi_Finalize(); + +#ifdef SDK_ARM9 + OSBootCore = (void*)HW_ITCM; +#else // SDK_ARM7 + OSBootCore = (void*)(HW_PRV_WRAM_SVC_STACK - 0x200); +#endif // SDK_ARM7 + + MI_CpuCopyFast( OSi_BootCore, OSBootCore, 0x200 ); + + OSBootCore(p, w); +} + +/*---------------------------------------------------------------------------* + Name: OSi_Finalize + + Description: finalize + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void OSi_Finalize(void) +{ + (void)OS_DisableInterrupts(); + (void)OS_DisableIrq(); + reg_OS_IE = 0; + reg_OS_IF = 0xffffffff; +#ifdef SDK_ARM7 + reg_OS_IE2 = 0; + reg_OS_IF2 = 0xffff; + // set init check flag by bootrom + SVC_CpuClear( REG_OS_PAUSE_CHK_MASK, (void*)REG_PAUSE_ADDR, sizeof(u16), 16 ); +#else // SDK_ARM9 + // set init check flag + reg_OS_PAUSE = REG_OS_PAUSE_CHK_MASK; + *(u64*)HW_INIT_LOCK_BUF = 0; + + DC_Disable(); + DC_FlushAll(); + DC_WaitWriteBufferEmpty(); + IC_Disable(); + IC_InvalidateAll(); + + // clear cache + IC_ClearTagAll(); + IC_ClearInstructionAll(); + DC_ClearTagAll(); + DC_ClearDataAll(); + + OS_DisableProtectionUnit(); +#endif // SDK_ARM9 +} + +extern void SDK_STATIC_DATA_START(void); // static data start address +extern void SDK_STATIC_BSS_END(void); // static bss end address + +/*---------------------------------------------------------------------------* + Name: OSi_ClearWorkArea + + Description: clear work area + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +#include +asm void OSi_ClearWorkArea( void ) +{ + mov r11, lr + + // clear stack with r4-r9 + mov r0, #0 + ldr r1, =SDK_STATIC_DATA_START + ldr r2, =SDK_STATIC_BSS_END + sub r2, r2, r1 + bl MIi_CpuClearFast + + bx r11 +} + +asm void OSi_BootCore( OSEntryPoint p, MIHeader_WramRegs* w ) +{ + mov r11, r0 + mov r10, r1 + +#ifdef SDK_ARM9 + + // wait for request of wram map + ldr r3, =REG_SUBPINTF_ADDR + mov r2, #REG_PXI_SUBPINTF_A7STATUS_MASK +@0: + ldr r0, [r3] + and r0, r0, r2 + cmp r0, r2 + bne @0 + + // r10- => r9-r2 + ldr r9, =REG_MBK1_ADDR + add r2, r9, #32 +@1: + ldr r3, [r10], #4 + str r3, [r9], #4 + cmp r9, r2 + blt @1 + + // notify wram map + ldr r3, =REG_SUBPINTF_ADDR + mov r0, #REG_PXI_SUBPINTF_A9STATUS_MASK + str r0, [r3] + // wait for finalizing pxi + ldr r3, =REG_SUBPINTF_ADDR +@2: + ldr r0, [r3] + and r0, r0, #REG_PXI_SUBPINTF_A7STATUS_MASK + cmp r0, #0 + bne @2 + // finalize pxi + mov r0, #0 + str r0, [r3] + +#else // ARM7 + + // request wram map + ldr r3, =REG_MAINPINTF_ADDR + mov r0, #REG_PXI_MAINPINTF_A7STATUS_MASK + str r0, [r3] + // wait for wram map + mov r2, #REG_PXI_MAINPINTF_A9STATUS_MASK +@0: + ldr r0, [r3] + and r0, r0, r2 + cmp r0, r2 + bne @0 + // finalize pxi + mov r0, #0 + str r0, [r3] + + // r10- => r9-r2 + add r10, r10, #32 + ldr r9, =REG_MBK6_ADDR + add r2, r9, #15 +@1: + ldr r3, [r10], #4 + str r3, [r9], #4 + cmp r9, r2 + blt @1 + +#endif + + // clear stack with r4-r9 + mov r0, #0 +#if 0 + ldr r1, =HW_FIRM_STACK + ldr r2, =HW_FIRM_STACK_SIZE + bl MIi_CpuClearFast +#endif + + mov lr, r11 + + // clear registers +#if 0 + ldr sp, =HW_FIRM_STACK + ldmia sp, {r0-r12,sp} +#endif + + bx lr +} diff --git a/build/libraries/os/common/os_init_firm.c b/build/libraries/os/common/os_init_firm.c new file mode 100644 index 0000000..7359313 --- /dev/null +++ b/build/libraries/os/common/os_init_firm.c @@ -0,0 +1,148 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS + File: os_init_firm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include + +/*---------------------------------------------------------------------------* + Name: OS_InitNOR + + Description: initialize sdk os for firm + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +#pragma profile off +void OS_InitFIRM(void) +{ +#ifdef SDK_ARM9 + //---- system shared area check +// SDK_ASSERT((u32)&(OS_GetSystemWork()->command_area) == HW_CMD_AREA); + + //---------------------------------------------------------------- + // for ARM9 + +#ifdef SDK_ENABLE_ARM7_PRINT + // Init PrintServer for ARM7 (if specified) +// OS_InitPrintServer(); +#endif + + //---- Init interProcessor I/F + // Sync with ARM7 to enable OS_GetConsoleType() + // PXI_Init() must be called before OS_InitArenaEx() + //PXI_Init(); + PXI_InitFifoFIRM(); + + //---- Init Arena (arenas except SUBPRIV-WRAM) + OS_InitArena(); + + //---- Init Spinlock + OS_InitLock(); + + //---- Init Arena (extended main) + OS_InitArenaEx(); + + //---- Init IRQ Table + OS_InitIrqTable(); + + //---- Init IRQ Stack checker + OS_SetIrqStackChecker(); + + //---- Init Exception System +// OS_InitException(); + + //---- Init MI (Wram bank and DMA0 arranged) + MI_Init(); + + //---- Init VCountAlarm + OS_InitVAlarm(); + + //---- Init VRAM exclusive System + OSi_InitVramExclusive(); + + //---- Init Thread System +#ifndef SDK_NO_THREAD + OS_InitThread(); +#endif + //---- Init Reset System +#ifndef SDK_SMALL_BUILD +// OS_InitReset(); +#endif + + //---- Init Cartridge +#ifndef SDK_TEG +// CTRDG_Init(); +#endif + + //---- Init Card +#ifndef SDK_SMALL_BUILD +// CARD_Init(); +#endif + + //---- Init Power Manager +#ifndef SDK_TEG +// PM_Init(); +#endif + + //---- adjust VCOUNT +// OSi_WaitVCount0(); + +#else // SDK_ARM9 + //---------------------------------------------------------------- + // for ARM7 + + //---- Init interProcessor I/F + //PXI_Init(); + PXI_InitFifoFIRM(); + + //---- Init Arena (SUBPRIV-WRAM arena) + OS_InitArena(); + + //---- Init Spinlock + OS_InitLock(); + + //---- Init IRQ Table + OS_InitIrqTable(); + +#define SDK_EXCEPTION_BUG +#ifndef SDK_EXCEPTION_BUG + //---- Init Exception System + OS_InitException(); +#endif + + //---- Init Tick + OS_InitTick(); + + //---- Init Alarm System + OS_InitAlarm(); + + //---- Init Thread System + OS_InitThread(); + + //---- Init Reset System +#ifndef SDK_SMALL_BUILD +// OS_InitReset(); +#endif + + //---- Init Cartridge +#ifndef SDK_TEG +// CTRDG_Init(); +#endif + +#endif // SDK_ARM9 +} + +#pragma profile reset diff --git a/build/libraries/pm/ARM7/Makefile b/build/libraries/pm/ARM7/Makefile new file mode 100644 index 0000000..124e3af --- /dev/null +++ b/build/libraries/pm/ARM7/Makefile @@ -0,0 +1,62 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - pm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +SUBMAKES = + + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +# Codegen for sub processer +FIRM_PROC = ARM7 + +INCDIR = $(TWLSDK_ROOT)/build/libraries/spi/ARM7/pm/include \ + +SRCDIR = . + +SRCS = \ + pm_init.c \ + pm_pmic_ex.c \ + +TARGET_LIB = libpm_sp$(FIRM_LIBSUFFIX).a + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/pm/ARM7/pm_init.c b/build/libraries/pm/ARM7/pm_init.c new file mode 100644 index 0000000..00cb2f1 --- /dev/null +++ b/build/libraries/pm/ARM7/pm_init.c @@ -0,0 +1,88 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - pm + File: pm_init.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include + +static BOOL doneBackLight = FALSE; + +/*---------------------------------------------------------------------------* + Name: PM_InitFIRM + + Description: set default parameters + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void PM_InitFIRM( void ) +{ + // LED + PMi_ResetFlags( REG_PMIC_LED_CTL_ADDR, PMIC_LED_CTL_AUTO_BLINK | PMIC_LED_CTL_BLINK_BY_SLEEP ); + PMi_SetParams( REG_PMIC_LVL4_BRT_ADDR, + PMIC_LED_1_BRT_LEVEL_4_OFF | PMIC_LED_2_BRT_LEVEL_4_OFF, + PMIC_LVL4_BRT_LED_1_MASK | PMIC_LVL4_BRT_LED_2_MASK + ); + PMi_SetParams( REG_PMIC_LVL3_BRT_ADDR, + PMIC_LED_1_BRT_LEVEL_3_100 | PMIC_LED_2_BRT_LEVEL_3_OFF, + PMIC_LVL3_BRT_LED_1_MASK | PMIC_LVL3_BRT_LED_2_MASK + ); + PMi_SetParams( REG_PMIC_LVL2_BRT_ADDR, + PMIC_LED_1_BRT_LEVEL_2_OFF | PMIC_LED_1_BRT_LEVEL_2_100, + PMIC_LVL2_BRT_LED_1_MASK | PMIC_LVL2_BRT_LED_2_MASK + ); + PMi_SetParams( REG_PMIC_LVL1_BRT_ADDR, + PMIC_LED_1_BRT_LEVEL_1_100 | PMIC_LED_2_BRT_LEVEL_1_100, + PMIC_LVL1_BRT_LED_1_MASK | PMIC_LVL1_BRT_LED_2_MASK + ); + + // LCD ON + PMi_SetFlags( REG_PMIC_CTL2_ADDR, PMIC_CTL2_VDD50 ); + + // back light + PMi_SetParams( REG_PMIC_BL_BRT_A_ADDR, PMIC_BACKLIGHT_BRIGHT_MAX, PMIC_BL_BRT_A_MASK ); // TODO: less brightness + PMi_SetParams( REG_PMIC_BL_BRT_B_ADDR, PMIC_BACKLIGHT_BRIGHT_MAX, PMIC_BL_BRT_B_MASK ); // TODO: less brightness +} + +/*---------------------------------------------------------------------------* + Name: PM_BackLightOn + + Description: power B/L on if not set yet + + Arguments: force TRUE: wait until valid condition + FALSE not set unless valid condition + + Returns: None + *---------------------------------------------------------------------------*/ +void PM_BackLightOn( BOOL force ) +{ + if ( doneBackLight ) + { + return; // have already set + } + if ( force ) + { + while ( (reg_GX_DISPSTAT & REG_GX_DISPSTAT_INI_MASK) == FALSE ) + { + } + } + if ( reg_GX_DISPSTAT & REG_GX_DISPSTAT_INI_MASK ) + { + PMi_SetFlags( REG_PMIC_CTL2_ADDR, PMIC_CTL2_BACK_LIGHT_1 | PMIC_CTL2_BACK_LIGHT_2 ); + doneBackLight = TRUE; + } +} diff --git a/build/libraries/pm/ARM7/pm_pmic_ex.c b/build/libraries/pm/ARM7/pm_pmic_ex.c new file mode 100644 index 0000000..5932fa0 --- /dev/null +++ b/build/libraries/pm/ARM7/pm_pmic_ex.c @@ -0,0 +1,72 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - pm + File: pm_pmic_ex.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include + +//================================================================================ +// PMIC BIT CONTROL +//================================================================================ +/*---------------------------------------------------------------------------* + Name: PMi_SetParams + + Description: set control bit to device register + + Arguments: reg : device register + setBits : bits to set + maskBits : bits to mask + + Returns: None + *---------------------------------------------------------------------------*/ +void PMi_SetParams( u8 reg, u8 setBits, u8 maskBits ) +{ + u8 tmp; + tmp = PMi_GetRegister( reg ); + tmp &= ~maskBits; + setBits &= maskBits; + tmp |= setBits; + PMi_SetRegister( reg, tmp ); +} + +/*---------------------------------------------------------------------------* + Name: PMi_SetFlags + + Description: set control bit to device register + + Arguments: reg : device register + setBits : bits to set + + Returns: None + *---------------------------------------------------------------------------*/ +void PMi_SetFlags( u8 reg, u8 setBits ) +{ + PMi_SetParams( reg, setBits, setBits ); +} + +/*---------------------------------------------------------------------------* + Name: PMi_ResetFlags + + Description: clear control bit to device register + + Arguments: reg : device register + clrBits : bits to set + + Returns: None + *---------------------------------------------------------------------------*/ +void PMi_ResetFlags( u8 reg, u8 clrBits ) +{ + PMi_SetParams( reg, 0, clrBits ); +} + diff --git a/build/libraries/pm/Makefile b/build/libraries/pm/Makefile new file mode 100644 index 0000000..4d2df08 --- /dev/null +++ b/build/libraries/pm/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL - libraries - pm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM7 + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/pxi/ARM7/Makefile b/build/libraries/pxi/ARM7/Makefile new file mode 100644 index 0000000..72fd9f6 --- /dev/null +++ b/build/libraries/pxi/ARM7/Makefile @@ -0,0 +1,61 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries_sp - pxi +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +#SUBMAKES = Makefile.CALLTRACE \ +# Makefile.FUNCTIONCOST + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +# Codegen for sub processer +FIRM_PROC = ARM7 + +SRCDIR = ../common . + +SRCS = \ + pxi_misc.c \ + +TARGET_LIB = libpxi_sp$(FIRM_LIBSUFFIX).a + + +#---------------------------------------------------------------------------- + +# DEBUGŃrh̏ꍇARELEASEłŃrh +# DEBUGł̃Cu𑕂܂B + +ifdef NITRO_DEBUG +NITRO_BUILD_TYPE = RELEASE +endif + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/pxi/ARM9/Makefile b/build/libraries/pxi/ARM9/Makefile new file mode 100644 index 0000000..52fe444 --- /dev/null +++ b/build/libraries/pxi/ARM9/Makefile @@ -0,0 +1,58 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - pxi +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = +SUBMAKES = + + +#---------------------------------------------------------------------------- + +# build ARM & THUMB libraries +FIRM_CODEGEN_ALL ?= TRUE + +SRCDIR = ../common . + +SRCS = \ + pxi_misc.c \ + +TARGET_LIB = libpxi$(FIRM_LIBSUFFIX).a + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(FIRM_INSTALL_LIBDIR) + +ifdef NITRO_CALLTRACE +CCFLAGS += -DOS_PROFILE_AVAILABLE -DOS_PROFILE_CALL_TRACE +endif + +ifdef NITRO_FUNCTIONCOST +CCFLAGS += -DOS_PROFILE_AVAILABLE -DOS_PROFILE_FUNCTION_COST +endif + +ifdef NITRO_TCM_APPLY +CCFLAGS += -DSDK_TCM_APPLY +endif + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries/pxi/Makefile b/build/libraries/pxi/Makefile new file mode 100644 index 0000000..8410a70 --- /dev/null +++ b/build/libraries/pxi/Makefile @@ -0,0 +1,32 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - libraries - pxi +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 \ + ARM7 \ + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/libraries/pxi/common/pxi_misc.c b/build/libraries/pxi/common/pxi_misc.c new file mode 100644 index 0000000..7804e4b --- /dev/null +++ b/build/libraries/pxi/common/pxi_misc.c @@ -0,0 +1,352 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - library - pxi + File: pxi_misc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include +#include + +static u16 FifoCtrlInit = 0; + +/*********** function prototypes ******************/ +static inline PXIFifoStatus PXIi_GetFromFifo(u32 *data_buf); +static inline PXIFifoStatus PXIi_SetToFifo(u32 data); + + +/*---------------------------------------------------------------------------* + Name: PXI_InitFifoFIRM + + Description: initialize FIFO system for firm + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +void PXI_InitFifoFIRM(void) +{ + OSIntrMode enabled; + + enabled = OS_DisableInterrupts(); + + if (!FifoCtrlInit) + { + FifoCtrlInit = TRUE; + + reg_PXI_FIFO_CNT = + (REG_PXI_FIFO_CNT_SEND_CL_MASK | + REG_PXI_FIFO_CNT_E_MASK | REG_PXI_FIFO_CNT_ERR_MASK); + +#ifdef SDK_ARM9 + PXI_SendIDByIntf( FIRM_PXI_ID_INIT_ARM9 ); + PXI_WaitIDByIntf( FIRM_PXI_ID_INIT_ARM7 ); +#else // SDK_ARM7 + PXI_SendIDByIntf( FIRM_PXI_ID_INIT_ARM7 ); + PXI_WaitIDByIntf( FIRM_PXI_ID_INIT_ARM9 ); +#endif // SDK_ARM7 + } + (void)OS_RestoreInterrupts(enabled); +} + + +/*---------------------------------------------------------------------------* + Name: PXI_NotifyID + + Description: Send 4bit id to other processor + + Arguments: id notifying id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_NotifyID( u32 id ) +{ + PXI_SendIDByFifo( PXI_FIFO_TAG_SYSTEM, id ); +} + +/*---------------------------------------------------------------------------* + Name: PXI_WaitID + + Description: Wait 4bit id from the other processor + + Arguments: id waiting id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_WaitID( u32 id ) +{ + PXI_WaitIDByFifo( PXI_FIFO_TAG_SYSTEM, id ); +} + +/*---------------------------------------------------------------------------* + Name: PXI_RecvID + + Description: Receive 4bit id from the other processor + + Arguments: None + + Returns: id + *---------------------------------------------------------------------------*/ +u8 PXI_RecvID( void ) +{ + u8 id; + + while (PXI_RecvIDByFifo(PXI_FIFO_TAG_SYSTEM, &id) != PXI_FIFO_SUCCESS) + { + } + + return id; +} + +/*---------------------------------------------------------------------------* + Name: PXI_SendIDByIntf + + Description: Send 4bit id to the other processor + + Arguments: id sending id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_SendIDByIntf( u32 id ) +{ + reg_PXI_INTF = (u16)(id << REG_PXI_INTF_SEND_SHIFT); +} + +/*---------------------------------------------------------------------------* + Name: PXI_RecvIDByIntf + + Description: Receive 4bit id from the other processor + + Arguments: None + + Returns: received id + *---------------------------------------------------------------------------*/ +u32 PXI_RecvIDByIntf( void ) +{ + return (u32)((reg_PXI_INTF & REG_PXI_INTF_RECV_MASK) >> REG_PXI_INTF_RECV_SHIFT); +} + +/*---------------------------------------------------------------------------* + Name: PXI_WaitIDByIntf + + Description: Wait 4bit id from the other processor + + Arguments: id waiting id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_WaitIDByIntf( u32 id ) +{ + while (PXI_RecvIDByIntf() != id) + { + } +} + +/*---------------------------------------------------------------------------* + Name: PXI_SendIDByFifo + + Description: Send 32bit-word to another CPU via FIFO + + Arguments: + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_SendIDByFifo(PXIFifoTag tag, u32 id) +{ + static PXIFifoMessage fifomsg; + + fifomsg.e.tag = tag; + fifomsg.e.data = id; + + while ( PXIi_SetToFifo(fifomsg.raw) != PXI_FIFO_SUCCESS ) + { + } +} + +/*---------------------------------------------------------------------------* + Name: PXI_RecvIDByFifo + + Description: Recv 32bit-word from another CPU via FIFO + + Arguments: + + Returns: if error occured, returns minus value + *---------------------------------------------------------------------------*/ +PXIFifoStatus PXI_RecvIDByFifo(PXIFifoTag tag, void* buf) +{ + static PXIFifoMessage fifomsg; + u8* p = buf; + + while ( PXIi_GetFromFifo(&fifomsg.raw) != PXI_FIFO_SUCCESS ) + { + } + + if (fifomsg.e.tag != tag) + { + return PXI_FIFO_FAIL_RECV_ERR; + } + + *p = (u8)fifomsg.e.data; + + return PXI_FIFO_SUCCESS; +} + +/*---------------------------------------------------------------------------* + Name: PXI_WaitIDByFifo + + Description: Wait 32bit-word from another CPU via FIFO + + Arguments: id waiting id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_WaitIDByFifo(PXIFifoTag tag, u32 id) +{ + u8 buf = (u8)id; + + do + { + while (PXI_RecvIDByFifo(tag, &buf) != PXI_FIFO_SUCCESS) + { + } + } + while ( buf != id ); +} + +/*---------------------------------------------------------------------------* + Name: PXI_SendDataByFifo + + Description: Send data to another CPU via FIFO + + Arguments: + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_SendDataByFifo(PXIFifoTag tag, void* buf, int size) +{ + static PXIFifoMessage fifomsg; + u32* p = buf; + int len = size/4; + int i; + + fifomsg.e.tag = tag; + fifomsg.e.data = len; + + while ( PXIi_SetToFifo(fifomsg.raw) != PXI_FIFO_SUCCESS ) + { + } + + for ( i=0; i max_size/4) + { + return PXI_FIFO_FAIL_SEND_ERR; + } + + for ( i=0; iflags|=(n)) +#define BN_get_flags(b,n) ((b)->flags&(n)) +#define BN_CTX_set_flags(b,n) ((b)->flags|=(n)) +#define BN_CTX_get_flags(b,n) ((b)->flags&(n)) + +#ifndef HEADER_COMMON_BN_H_TYPEDEF_DEF +#define HEADER_COMMON_BN_H_TYPEDEF_DEF +typedef struct bignum_st BIGNUM; +typedef struct bignum_ctx BN_CTX; +typedef struct bn_mont_ctx_st BN_MONT_CTX; +typedef struct bn_recp_ctx_st BN_RECP_CTX; +typedef struct bn_prime_ctx_st BN_PRIME_CTX; +typedef struct bn_blind_ctx_st BN_BLIND_CTX; +typedef struct bn_blind_meth_st BN_BLIND_METH; +#endif + +typedef struct bn_mod_exp_meth_st BN_ME_METH; +typedef struct bn_mod_exp_ctx_st BN_ME_CTX; + + +/* The data array d must always have an extra 'valid' word in location + * bn->d[bn->max]. It must be ok for reading. This is needed if + * BN_MUL_LATENCY is defined. + */ +struct bignum_st + { + BN_ULONG *d; /* Pointer to an array of 'BN_BITS2' bit chunks. */ + int top; /* Index of last used d +1. */ + /* The next are internal book keeping for bn_expand. */ + int max; /* Size of the d array. */ + int neg; /* one if the number is negative */ + int flags; + }; + +/* Used for temp variables */ +#define BN_CTX_NUM 12 +struct bignum_ctx + { + int tos; + BIGNUM bn[BN_CTX_NUM+1]; + int flags; + R_SURRENDER *surrender; + }; + +#if defined(WIN64) || defined(__ia64__) || defined(CPU_IA64) +#define BN_USHORT unsigned int +#else +#define BN_USHORT unsigned short +#endif + +/* Used for prime number generation */ +struct bn_prime_ctx_st + { + BN_USHORT *primes; + BN_USHORT *mods; + int num_primes; + int prime_checks; + R_SURRENDER *surrender; + R_RANDOM *random; + int flags; + }; + +struct bn_blind_ctx_st + { + int init; + BN_BLIND_METH *meth; + BIGNUM B; + BIGNUM Bi; + BIGNUM mod; + }; + +struct bn_blind_meth_st + { + void (*init) (BN_BLIND_CTX *); + void (*ctx_free)(BN_BLIND_CTX *); + int (*set) (BN_BLIND_CTX *,R_RANDOM *,BIGNUM *,BIGNUM *, BN_ME_CTX *,BN_CTX *); + int (*convert) (BN_BLIND_CTX *,BIGNUM *,BN_CTX *); + int (*invert) (BN_BLIND_CTX *,BIGNUM *,BN_CTX *); + int (*update) (BN_BLIND_CTX *,BN_CTX *); + int (*copy) (BN_BLIND_CTX *,BN_BLIND_CTX *); + }; + +/* Used for montgomery multiplication */ +struct bn_mont_ctx_st + { + int use_word; /* 0 for word form, 1 for long form */ + int ri; /* number of bits in R */ + int riw; /* number of words in R */ + BIGNUM RR; /* used to convert to montgomery form */ + BIGNUM N; /* The modulus */ + BIGNUM Ni; /* The inverse of N */ + BN_ULONG n0; /* word form of inverse, normally only one of + * Ni or n0 is defined */ + int flags; + }; + +/* Used by the recursive exponentiation implementations */ +typedef struct bn_mod_exp_rec_meth_st + { +#ifndef NOPROTO + void (PRE_CCONV CCONV *mul)(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); + void (PRE_CCONV CCONV *sqr)(BN_ULONG *r, BN_ULONG *a); + void (PRE_CCONV CCONV *low_mul)(); +#else + void (PRE_CCONV CCONV *mul)(); + void (PRE_CCONV CCONV *sqr)(); + void (PRE_CCONV CCONV *low_mul)(); +#endif + } BN_MOD_EXP_REC_METH; + +/* If this flag is set, if there is a custom method for a modulus + * two times larger, use it. This is mostly mean for use on the + * itanium where a 512*512 routine is 10 times faster than the C + * code version, so we need to detect that we can turn of CRT + * for RSA if there is an native IA64 512*512 present. + */ +#define BN_ME_FLG_FAST_ASM 0x0001 + +struct bn_mod_exp_meth_st + { + int num; /* Word size we target */ + char *name; /* Identify the method */ +#ifndef NOPROTO + int (*useit)(const BN_ME_METH *meth); + /* If 'power' is null, reuse the old one */ + int (*mod_exp)(BN_ME_CTX *mctx,BIGNUM *r,BIGNUM *a,BIGNUM *p, + BN_CTX *ctx); + /* Create the BN_ME_CTX */ + int (*init_ctx)(const BN_ME_METH *meth,BN_ME_CTX **mctx); + /* Get rid of it */ + int (*free_ctx)(BN_ME_CTX *mctx); + /* Assign the modulus */ + int (*set)(BN_ME_CTX *mctx,BIGNUM *n,int cmd,int flags,BN_CTX *ctx); +#else + int (*useit)(); + int (*mod_exp)(); + int (*init_ctx)(); + int (*free_ctx)(); + int (*set)(); +#endif + int argi; + char *argp; /* 'Extra stuff' */ + }; + +#define BN_ME_METH_TABLE_MAX 32 +/* Used in BN_library_init */ +#define BN_INIT_LAST 0x00 +#define BN_INIT_BN_ME_METH 0x01 + +#define BN_BNME_F_DEFAULT 0x01 +/* Used only when loading, kept as bits internally, normally loaded as + * words */ +#define BN_BNME_F_BITS 0x02 +typedef struct bn_me_meth_info_st + { +#ifndef NOPROTO + const BN_ME_METH *(*meth)(void); +#else + const BN_ME_METH *(*meth)(); +#endif + int min; + int max; + int flags; + } BN_ME_METH_INFO; + +#define BN_ME_SET_MOD 0x01 +#define BN_ME_SET_BASE 0x02 +#define BN_ME_SET_EXP 0x03 +#define BN_ME_SET_FLG_NO_LOOKUP 0x01 /* Passed to BN_ME_CTX_set() */ + +#define BN_FLG_CACHE 0x10 /* Cache values */ +#define BN_ME_FLG_BASE 0x40 /* base has been cached */ +#define BN_ME_FLG_EXP 0x80 /* power has been cached */ +/* When one of these structures is setup, it is intended that the + * base or power, if not null, will be used for the current calculation. + * If the base and/or power are cached, they will only be used if the input + * value is null. + * For RSA, the power would normally be set. + * For DH, the base and power would be set. The initial value generated + * would be the public key, which is exchanged. The phase2 part would + * change the base but not the power. + * For DSA signing, a fixed base is used, but a random power. + * For DSA verification, there are two bases and two powers, + * a^p%m * b^q%m + * One way to implement this is to use a special function to + * generate a composite power value, and or a special base form. + * The other option is to have a special function to generate + * the 'base' array. The problem is that we are exponentiating with + * a 3 value power value, instead of the normal two. It should be possible + * to use the standard a^b%m function. + */ +struct bn_mod_exp_ctx_st + { + const BN_ME_METH *meth; + char *callback; + char *cb_arg; + int flags; + /* Evil hack for storage of data values, it should really be here + * other than the first value */ + char *modulus; /* eg BN_MONT_CTX */ + char *power; /* eg power representation */ + char *base; /* eg base representation */ + char *arg; + }; + +/* Used for reciprocal division/mod functions + * It cannot be shared between threads + */ +struct bn_recp_ctx_st + { + BIGNUM N; /* the divisor */ + BIGNUM Nr; /* the reciprocal */ + int num_bits; + int shift; + int flags; + }; + +typedef struct bn_rec_st + { + int depth; + int n; +#ifndef NOPROTO + void (PRE_CCONV CCONV *mul)(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); + void (PRE_CCONV CCONV *sqr)(BN_ULONG *r, BN_ULONG *a); + void (PRE_CCONV CCONV *low_mul)(); +#else + void (PRE_CCONV CCONV *mul)(); + void (PRE_CCONV CCONV *sqr)(); + void (PRE_CCONV CCONV *low_mul)(); +#endif + } BN_REC; + +#define BN_to_montgomery(r,a,mont,ctx) BN_mod_mul_montgomery(\ + r,a,&((mont)->RR),(mont),ctx) + +#define BN_prime_checks (5) + +#define BN_num_bytes(a) ((BN_num_bits(a)+7)/8) +#define BN_length(a) ((a)->top * BN_BYTES) +#define BN_is_word(a,w) (((a)->top == 1) && ((a)->d[0] == (BN_ULONG)(w))) +#define BN_is_zero(a) (((a)->top == 0) || BN_is_word(a,0)) +#define BN_is_one(a) (BN_is_word((a),1)) +#define BN_is_odd(a) (((a)->top > 0) && ((a)->d[0] & 1)) +#define BN_one(a) (BN_set_word((a),(BN_ULONG)1)) +#define BN_zero(a) (BN_set_word((a),(BN_ULONG)0)) + +/*#define BN_ascii2bn(a) BN_hex2bn(a) */ +/*#define BN_bn2ascii(a) BN_bn2hex(a) */ + +#define bn_expand(n,b) ((((((b+BN_BITS2-1))/BN_BITS2)) <= (n)->max)?\ + (n):bn_expand2((n),(b)/BN_BITS2+1)) +#define bn_wexpand(n,b) (((b) <= (n)->max)?(n):bn_expand2((n),(b))) + +#ifdef SMALL_CODE_SIZE +void bn_zexpand(BIGNUM *a,int n); +void bn_fix_top(BIGNUM *a); +#else +#define bn_zexpand(a,n) \ + if ((a)->top < n) \ + { \ + int i; \ + bn_wexpand((a),n); \ + if ((a)->d!=NULL) \ + { \ + for (i=(a)->top; id[i]=0; \ + } \ + } + +#define bn_fix_top(a) \ + { \ + BN_ULONG *ftl; \ + if ((a)->top > 0) \ + { \ + for (ftl= &((a)->d[(a)->top-1]); (a)->top > 0; (a)->top--) \ + if (*(ftl--)) break; \ + } \ + } +#endif + +#define BN_MONT_CTX_set(a,b,c) BN_MONT_CTX_set_word((a),(b),(c)) + +#ifndef NOPROTO + + +const BN_ME_METH *BN_ME_METH_word(void); +const BN_ME_METH *BN_ME_METH_full(void); + +#if (defined(BN_MUL_COMBA) || defined(BN_SQR_COMBA)) + +/* word4 - used for 64bit multiprime*/ +const BN_ME_METH *BN_ME_METH_word4(void); +const BN_ME_METH *BN_ME_METH_rec4_word8(void); +const BN_ME_METH *BN_ME_METH_rec4_word16(void); +const BN_ME_METH *BN_ME_METH_rec4_word32(void); +const BN_ME_METH *BN_ME_METH_rec4_word64(void); +const BN_ME_METH *BN_ME_METH_rec4_word128(void); + +/* word6 - used for 64bit multiprime*/ +const BN_ME_METH *BN_ME_METH_word6(void); +const BN_ME_METH *BN_ME_METH_rec6_word12(void); +const BN_ME_METH *BN_ME_METH_rec6_word24(void); +const BN_ME_METH *BN_ME_METH_rec6_word48(void); +const BN_ME_METH *BN_ME_METH_rec6_word96(void); + +const BN_ME_METH *BN_ME_METH_word8(void); +const BN_ME_METH *BN_ME_METH_rec8_word16(void); +const BN_ME_METH *BN_ME_METH_rec8_word32(void); +const BN_ME_METH *BN_ME_METH_rec8_word64(void); +const BN_ME_METH *BN_ME_METH_rec8_word128(void); +const BN_ME_METH *BN_ME_METH_rec8_word256(void); + +const BN_ME_METH *BN_ME_METH_word11(void); +const BN_ME_METH *BN_ME_METH_rec11_word22(void); +const BN_ME_METH *BN_ME_METH_rec11_word44(void); +const BN_ME_METH *BN_ME_METH_rec11_word88(void); + +const BN_ME_METH *BN_ME_METH_word16(void); +const BN_ME_METH *BN_ME_METH_rec16_word32(void); +const BN_ME_METH *BN_ME_METH_rec16_word64(void); +const BN_ME_METH *BN_ME_METH_rec16_word128(void); +const BN_ME_METH *BN_ME_METH_rec16_word256(void); + +#endif + +#ifdef CPU_IA64 +const BN_ME_METH *BN_ME_METH_ia64_384(void); +const BN_ME_METH *BN_ME_METH_ia64_512(void); +const BN_ME_METH *BN_ME_METH_ia64_1024(void); +#endif + +#if (defined(CPU_SPARC_V8PLUS) || defined (CPU_SPARC_V9)) +const BN_ME_METH *BN_ME_METH_usparc(void); +const BN_ME_METH *BN_ME_METH_usparc_352(void); +const BN_ME_METH *BN_ME_METH_usparc_512(void); +#endif + +#if 1 || defined(CPU_X86) +const BN_ME_METH *BN_ME_METH_pentium4_29(void); +const BN_ME_METH *BN_ME_METH_pentium4_28(void); +#endif + +/* NCipher Nfast hardware accelerator method prototype */ +const BN_ME_METH *BN_ME_METH_nfast(void); + + +BIGNUM *BN_value_one(void); +const char * BN_options(void); +BN_CTX *BN_CTX_new(void); +void BN_CTX_init(BN_CTX *c); +void BN_CTX_free(BN_CTX *c); +#ifndef NO_BN_RAND +int BN_rand(BIGNUM *rnd, R_RANDOM *rand, int bits, int top,int bottom); +#endif +int BN_num_bits(BIGNUM *a); +int BN_num_bits_word(BN_ILONG); +BIGNUM *BN_new(void); +void BN_init(BIGNUM *); +void BN_clear_free(BIGNUM *a); +BIGNUM *BN_copy(BIGNUM *a, BIGNUM *b); +BIGNUM *BN_bin2bn(unsigned char *s,int len,BIGNUM *ret); +int BN_bn2bin(BIGNUM *a, unsigned char *to); +BIGNUM *BN_mpi2bn(unsigned char *s,int len,BIGNUM *ret); +int BN_bn2mpi(BIGNUM *a, unsigned char *to); +int BN_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_usub(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_uadd(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_add(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx); +int BN_div(BIGNUM *dv, BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx); +int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b,BN_CTX *ctx); +int BN_sqr(BIGNUM *r, BIGNUM *a,BN_CTX *ctx); +BN_ULONG BN_mod_word(BIGNUM *a, BN_ULONG w); +BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w); +int BN_mul_word(BIGNUM *a, BN_ULONG w); +int BN_add_word(BIGNUM *a, BN_ULONG w); +int BN_sub_word(BIGNUM *a, BN_ULONG w); +int BN_set_word(BIGNUM *a, BN_ULONG w); +BN_ULONG BN_get_word(BIGNUM *a); +int BN_cmp(BIGNUM *a, BIGNUM *b); +void BN_free(BIGNUM *a); +int BN_is_bit_set(BIGNUM *a, int n); +int BN_lshift(BIGNUM *r, BIGNUM *a, int n); +int BN_lshift1(BIGNUM *r, BIGNUM *a); +int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p,BN_CTX *ctx); +int BN_mod_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx); +int BN_mod_exp_mont(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx, + BN_MONT_CTX *m_ctx); +int BN_mod_exp2_mont(BIGNUM *r, BIGNUM *a1, BIGNUM *p1,BIGNUM *a2, + BIGNUM *p2,BIGNUM *m,BN_CTX *ctx,BN_MONT_CTX *m_ctx); +int BN_mod_exp_simple(BIGNUM *r, BIGNUM *a, BIGNUM *p, + BIGNUM *m,BN_CTX *ctx); +int BN_mask_bits(BIGNUM *a,int n); +int BN_mod_mul(BIGNUM *ret, BIGNUM *a, BIGNUM *b, BIGNUM *m, + BN_CTX *ctx); +#if !defined(WIN16) && !defined(NO_FP_API) +int BN_print_fp(FILE *fp, BIGNUM *a); +#endif +#ifdef HEADER_COMMON_BIO_H +int BN_print(BIO *fp, BIGNUM *a); +#else +/* int BN_print(char *fp, BIGNUM *a); */ +#endif +int BN_reciprocal(BIGNUM *r, BIGNUM *m, int len, BN_CTX *ctx); +int BN_rshift(BIGNUM *r, BIGNUM *a, int n); +int BN_rshift1(BIGNUM *r, BIGNUM *a); +void BN_clear(BIGNUM *a); +BIGNUM *bn_expand2(BIGNUM *b, int bits); +BIGNUM *BN_dup(BIGNUM *a); +int BN_ucmp(BIGNUM *a, BIGNUM *b); +int BN_set_bit(BIGNUM *a, int n); +int BN_clear_bit(BIGNUM *a, int n); +char * BN_bn2hex(BIGNUM *a); +char * BN_bn2dec(BIGNUM *a); +int BN_hex2bn(BIGNUM **a,char *str); +int BN_dec2bn(BIGNUM **a,char *str); +int BN_gcd(BIGNUM *r,BIGNUM *in_a,BIGNUM *in_b,BN_CTX *ctx); +BIGNUM *BN_mod_inverse(BIGNUM *ret,BIGNUM *a, BIGNUM *n,BN_CTX *ctx); +/* Return R, where it is R*(1< +#include +#include "r_error.h" +#include "err.h" +#include +#else //NITRO +#include "r_error.h" +#ifndef NULL +#define NULL 0 +#endif +#endif + +#ifndef STANDALONE +#include "r_com.h" +#else +#if 0 //RSA +#define NO_STDLIB_MAPPING +#define Malloc(a) malloc(a) +#define Free(a) free(a) +#define Memset(a,b,c) memset(a,b,c) +#define Memcpy(a,b,c) memcpy(a,b,c) +#else // Nitro +#define NO_STDLIB_MAPPING +#include "acmemory.h" +#define Malloc(a) ACMemory_Alloc(a) +#define Free(a) ACMemory_Free(a) +#define Memset(a,b,c) ACMemory_Memset(a,b,c) +#define Memcpy(a,b,c) ACMemory_Memcpy(a,b,c) +#endif +#endif + +/* TEMP FIX */ +#undef BNerr +#define BNerr(a,b) +#include "bn.h" + +#define BN_EXP_TABLE_SIZE 16 + +/* see the bn_limit_ fields which are the start of a runtime + * tunable set of values to match these fixed compile-time constants + */ +/* Pentium pro 16,16,16,32,64 */ +/* Alpha 16,16,16,16.64 */ +/* StrongARM */ +#define BN_MULL_SIZE_NORMAL (16) /* 32 */ +#define BN_MUL_RECURSIVE_SIZE_NORMAL (16) /* 32 */ /* less than */ +#define BN_SQR_RECURSIVE_SIZE_NORMAL (16) /* 32 */ +#define BN_MUL_LOW_RECURSIVE_SIZE_NORMAL (32) /* 32 */ +#define BN_MONT_CTX_SET_SIZE_WORD (64) /* 32 */ + +/************************************************************* + * Using the long long type + */ +#define Lw(t) (((BN_ULONG)(t))&BN_MASK2) +#define Hw(t) (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2) + +/* These are used for internal error checking and are not normally used */ +#ifdef BN_DEBUG +#define bn_check_top(a) \ + { if ( ((a)->top < 0) || \ + ((a)->top > (a)->max) || \ + (((a)->top == 0) && (a)->neg) || \ + (((a)->top == 1) && (a->d[0] == 0))) \ + { char *nullp=NULL; *nullp='z'; } } +#define bn_check_num(a) if ((a) < 0) { char *nullp=NULL; *nullp='z'; } +#define bn_assert(a) if (!(a)) { char *nullp=NULL; *nullp='z'; } +#define bn_set_used_check(l,size,num) bn_su_check(l,size,num) +#ifdef BN_DEBUG2 +#define bn_do_used_check(fp,str,l,size,num) bn_du_check(fp,str,l,size,num) +#else +#define bn_do_used_check(fp,str,l,size,num) +#endif +#else +#define bn_assert(a) +#define bn_check_top(a) +#define bn_check_num(a) +#define bn_set_used_check(l,size,num) +#define bn_do_used_check(fp,str,l,size,num) +#endif + + +/*********************************************** +* IA64 32 bit build SWIZZLE code +* This essentially casts our points which are +* 32bits under abi32 to 64bit unsigned long +* longs and then grabs the top two bits of the +* pointer and places it in the 2nd and 3rd bits +* of the unsigned long long. +**********************************************/ +#ifdef HPUX_IA64_32 +#define SWIZLLE(VALUE) ((((unsigned long long)(VALUE) & 0xc0000000LL) <<31)\ +|((unsigned long long)(VALUE))) +#else +#define SWIZZLE(VALUE) (VALUE) +#endif + +#define bn_neg_words(a,n) \ + { \ + int iii; \ + \ + for (iii=0; iiimax=(r)->top,BN_set_flags((r),BN_FLG_STATIC_DATA)) +#else +#define bn_set_max(r) +#endif + +/* These macros are used to 'take' a section of a bignum for read only use */ +#define bn_set_low(r,a,n) \ + { \ + (r)->top=((a)->top > (n))?(n):(a)->top; \ + (r)->d=(a)->d; \ + (r)->neg=(a)->neg; \ + (r)->flags|=BN_FLG_STATIC_DATA; \ + bn_set_max(r); \ + } + +#define bn_set_high(r,a,n) \ + { \ + if ((a)->top > (n)) \ + { \ + (r)->top=(a)->top-n; \ + (r)->d= &((a)->d[n]); \ + } \ + else \ + (r)->top=0; \ + (r)->neg=(a)->neg; \ + (r)->flags|=BN_FLG_STATIC_DATA; \ + bn_set_max(r); \ + } + +/* #define bn_expand(n,b) ((((b)/BN_BITS2) <= (n)->max)?(n):bn_expand2((n),(b))) */ + +#ifdef BN_LLONG +#define mul_add(r,a,w,c) { \ + BN_ULLONG t; \ + t=(BN_ULLONG)w * (a) + (r) + (c); \ + (r)= Lw(t); \ + (c)= Hw(t); \ + } + +#define mul(r,a,w,c) { \ + BN_ULLONG t; \ + t=(BN_ULLONG)w * (a) + (c); \ + (r)= Lw(t); \ + (c)= Hw(t); \ + } + +#else +/************************************************************* + * No long long type + */ + +#define LBITS(a) ((a)&BN_MASK2l) +#define HBITS(a) (((a)>>BN_BITS4)&BN_MASK2lh) +#define L2HBITS(a) ((BN_ULONG)((a)&BN_MASK2lh)<>(BN_BITS4-1); \ + m =((m&BN_MASK2l)<<(BN_BITS4+1))&BN_MASK2; \ + l=(l+m)&BN_MASK2; if (l < m) h++; \ + (lo)=l; \ + (ho)=h; \ + } + +#if 0 +#define mul_add(r,a,bl,bh,b_hl,c) { \ + BN_ULONG l,h; \ + BN_ULONG lt,mt; \ + \ + h= (a); \ + l=LBITS(h); \ + h=HBITS(h); \ + mt=bl*l; \ + lt=mt+c+(r); \ + c=bh*h; \ + mt+=c+(l-h)*b_hl; \ + mt+=(lt>>BN_BITS4); \ + (r)=(lt&BN_MASK2l)|((mt&BN_MASK2l)<>BN_BITS4); \ + } +#else /* Normal version */ +#define mul_add(r,a,bl,bh,b_hl,c) { \ + BN_ULONG l,h; \ + \ + h= (a); \ + l=LBITS(h); \ + h=HBITS(h); \ + mul64(l,h,(bl),(bh)); \ + \ + /* non-multiply part */ \ + l=(l+(c))&BN_MASK2; if (l < (c)) h++; \ + (c)=(r); \ + l=(l+(c))&BN_MASK2; if (l < (c)) h++; \ + (c)=h&BN_MASK2; \ + (r)=l; \ + } +#endif + +#define mul(r,a,bl,bh,c) { \ + BN_ULONG l,h; \ + \ + h= (a); \ + l=LBITS(h); \ + h=HBITS(h); \ + mul64(l,h,(bl),(bh)); \ + \ + /* non-multiply part */ \ + l+=(c); if ((l&BN_MASK2) < (c)) h++; \ + (c)=h&BN_MASK2; \ + (r)=l&BN_MASK2; \ + } + +#endif + +#ifndef BN_MUL_COMBA +#define bn_mul_comba4(r,a,b) bn_mul_normal(r,a,4,b,4) +#define bn_mul_comba5(r,a,b) bn_mul_normal(r,a,5,b,5) +#define bn_mul_comba6(r,a,b) bn_mul_normal(r,a,6,b,6) +#define bn_mul_comba8(r,a,b) bn_mul_normal(r,a,8,b,8) +#define bn_mul_comba11(r,a,b) bn_mul_normal(r,a,11,b,11) +#define bn_mul_comba12(r,a,b) bn_mul_normal(r,a,12,b,12) +#define bn_mul_comba16(r,a,b) bn_mul_normal(r,a,16,b,16) +#endif +#if 1 +#ifndef BN_SQR_COMBA +#define bn_sqr_comba4(r,a) bn_mul_normal(r,a,4,a,4) +#define bn_sqr_comba5(r,a) bn_mul_normal(r,a,5,a,5) +#define bn_sqr_comba6(r,a) bn_mul_normal(r,a,6,a,6) +#define bn_sqr_comba8(r,a) bn_mul_normal(r,a,8,a,8) +#define bn_sqr_comba11(r,a) bn_mul_normal(r,a,11,a,11) +#define bn_sqr_comba12(r,a) bn_mul_normal(r,a,12,a,12) +#define bn_sqr_comba16(r,a) bn_mul_normal(r,a,16,a,16) +#endif +#else +#ifndef BN_SQR_COMBA +#define bn_sqr_comba4(r,a) bn_mul_comba4(r,a,a) +#define bn_sqr_comba5(r,a) bn_mul_comba5(r,a,a) +#define bn_sqr_comba6(r,a) bn_mul_comba6(r,a,a) +#define bn_sqr_comba8(r,a) bn_mul_comba8(r,a,a) +#define bn_sqr_comba11(r,a) bn_mul_comba11(r,a,a) +#define bn_sqr_comba12(r,a) bn_mul_comba12(r,a,a) +#define bn_sqr_comba16(r,a) bn_mul_comba16(r,a,a) +#endif +#endif +#ifndef BN_REDUCE_COMBA +#define r0_bn_mont_comba4(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba5(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba6(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba8(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba11(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba12(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba16(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#endif + +#ifndef NOPROTO + +BIGNUM *bn_expand2(BIGNUM *b, int bits); + +#ifdef X86_ASM +void bn_add_words(BN_ULONG *r,BN_ULONG *a,int num); +#endif + +#else + +BIGNUM *bn_expand2(); +#ifdef X86_ASM +BN_ULONG bn_add_words(); +#endif + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_BN_LCL_H */ + +void bn_mul_low_recursive(BN_ULONG *r,BN_ULONG *a,BN_ULONG *b,int n2,BN_ULONG *t); +void bn_mul_high(BN_ULONG *r,BN_ULONG *a,BN_ULONG *b,BN_ULONG *l,int n2, BN_ULONG *t); +int BN_gen_exp_string(unsigned char *str, BIGNUM *p, int bits); +void bn_from_montgomery_rec_full(BN_ULONG *rp, BN_ULONG *ap, + BN_ULONG *np, BN_ULONG *nip, BN_ULONG *tmp,BN_REC *rec); + +int bn_mont_ctx_new_word(const BN_ME_METH *meth, BN_ME_CTX **retp); + diff --git a/build/libraries_sysmenu/acsign/ARM9/include/bn_thx.h b/build/libraries_sysmenu/acsign/ARM9/include/bn_thx.h new file mode 100644 index 0000000..451b3e4 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/bn_thx.h @@ -0,0 +1,317 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/***************************************************************************** + * Copyright (c). 2001 RSA Security Inc. All rights reserved. + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + ****************************************************************************/ +/** + * @file bn_thx.h + * @brief header file created for used as interface defines for systems + * containing hetergeneous environments where some bn operations + * will be performed in isolation from the rest of the library + */ +#ifndef HEADER_COMMON_BN_THX_H +#define HEADER_COMMON_BN_THX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* These defines are required on systems so that the mod_exp code + * to be used in isolation from the bn operation with library will work, + * if these are not available, the header files with equivalent functionality + * should be added inside a CPU or Operating system define + */ +#ifndef NO_STDIO_H +#include +#endif + +#ifndef NO_STDLIB_H +#include +#endif + +#ifndef NO_STRING_H +#include +#endif + +/* Interface for ARM/DSP systems, this interface requires only + * the standard defines and includes at the moment + */ +#ifdef CPU_TMS320 +#define THX_RECIPIENT +#define CPU_DSP +#endif + +#ifdef THX_RECIPIENT + +#ifndef restrict +#define restrict +#endif + +#ifndef Malloc +#define Malloc malloc +#endif + +#ifndef Memcpy +#define Memcpy memcpy +#endif + +#ifndef Memmove +#define Memmove memmove +#endif + +#ifndef Memset +#define Memset memset +#endif + +#ifndef Free +#define Free free +#endif + +#endif /* THX_RECIPIENT */ + +#ifndef THX_RECIPIENT /* not the recipient, we must be the caller */ + +#include "bn_lcl.h" + +#endif /* ! THX_RECIPIENT */ + +/* The follow define protected inclusions are excerpts from the + * header file bn.h, this has been done, so that code written for the + * THX systems can be used in isolation from the library + * This code may need to be updated in line with changes to the bn.h + * header file. + */ +#ifndef HEADER_COMMON_BN_H +#define HEADER_COMMON_BN_H + +#if !defined(CCONV) +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +/* convert from the new to the old option names */ +#if defined(OPT_BN_LLONG) +#define BN_LLONG /* comment to make sure Configure leaves this alone */ +#endif + +#if defined(OPT_32_BIT_INT) || defined(OPT_32_BIT) +#define THIRTY_TWO_BIT +#endif + +#define BN_ILONG BN_ULONG + +#ifdef THIRTY_TWO_BIT +#define BN_ULLONG unsigned long long +#ifdef OPT_32_BIT_INT +#define BN_ULONG unsigned int +#define BN_LONG int +#else +#define BN_ULONG unsigned long +#define BN_LONG long +#endif +#define BN_BITS 64 +#define BN_BYTES 4 +#define BN_BITS2 32 +#define BN_BITS4 16 +/* This is needed because the Watcom compiler pre-processor + * under QNX is perverted and tries to parses the 'LL' + * part even though it is never used. + */ +#ifdef BN_LLONG +#define BN_MASK (0xffffffffffffffffL) +#endif +#define BN_MASK2 (0xffffffffL) +#define BN_MASK2l (0xffff) +#define BN_MASK2lh (0xffff) +#define BN_MASK2h1 (0xffff8000L) +#define BN_MASK2h (0xffff0000L) +#define BN_TBIT (0x80000000L) +#define BN_DEC_CONV (1000000000L) +#define BN_DEC_FMT1 "%lu" +#define BN_DEC_FMT2 "%09lu" +#define BN_DEC_NUM 9 +#define BN_HEX_FMT "%08lX" +#endif + +#define BN_EXP_TABLE_SIZE 16 + +typedef struct bignum_st BIGNUM; + +struct bignum_st + { + BN_ULONG *d; /* Pointer to an array of 'BN_BITS2' bit chunks. */ + int top; /* Index of last used d +1. */ + /* The next are internal book keeping for bn_expand. */ + int max; /* Size of the d array. */ + int neg; /* one if the number is negative */ + int flags; + }; + +PRE_CCONV BN_ULONG CCONV bn_mul_add_words(BN_ULONG *rp,BN_ULONG *ap, + int num, BN_ULONG w); +PRE_CCONV BN_ULONG CCONV bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, + int num, BN_ULONG w); +PRE_CCONV void CCONV bn_sqr_words(BN_ULONG *rp, BN_ULONG *ap, int num); +BN_ULONG CCONV bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d); +PRE_CCONV BN_ULONG CCONV bn_add_words(BN_ULONG *rp, BN_ULONG *ap, + BN_ULONG *bp,int num); +PRE_CCONV BN_ULONG CCONV bn_sub_words(BN_ULONG *rp, BN_ULONG *ap, + BN_ULONG *bp,int num); + +#ifndef BN_ME_METH +#define BN_ME_METH void +#endif + +#endif /* ! HEADER_COMMON_BN_H */ + +/* The follow define protected inclusions are excerpts from the + * header file r_error.h, this has been done, so that code written for the + * THX systems can be used in isolation from the library + * This code may need to be updated in line with changes to the r_error.h + * header file. + */ +#ifndef HEADER_COMMON_R_ERROR_H +#define HEADER_COMMON_R_ERROR_H + +/* The FATAL_INTERNAL_ERROR is a flag that is set with the following + * error codes: + * R_ERROR_INVALID_STATE + * R_ERROR_INIT_NOT_CALLED + * R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED + */ +#define R_ERROR_FATAL_INTERNAL_ERROR 64 + +/* The BAD_PARAMETER is a flag that is set with the following error + * codes: + * R_ERROR_NULL_ARG + * R_ERROR_BUFFER_TOO_SMALL + * R_ERROR_BAD_VALUE + * R_ERROR_BAD_RANGE + * R_ERROR_BAD_FORMAT + * R_ERROR_BAD_TYPE + * R_ERROR_BAD_DATA + * R_ERROR_BAD_LENGTH + */ +#define R_ERROR_BAD_PARAMETER 32 + +/* Base value for all general errors used through all products */ +#define R_ERROR_BASE 10000 + +#define R_ERROR_NONE 0 + +#define R_ERROR_FAILED (R_ERROR_BASE+1) +#define R_ERROR_IO (R_ERROR_BASE+2) +#define R_ERROR_PROTOCOL (R_ERROR_BASE+3) +#define R_ERROR_EOF (R_ERROR_BASE+4) +#define R_ERROR_ALLOC_FAILURE (R_ERROR_BASE+5) +#define R_ERROR_EVAL_RESTRICTION (R_ERROR_BASE+6) +#define R_ERROR_EVAL_EXPIRED (R_ERROR_BASE+7) +#define R_ERROR_NOT_FOUND (R_ERROR_BASE+8) +#define R_ERROR_NOT_AVAILABLE (R_ERROR_BASE+9) +#define R_ERROR_NOT_IMPLEMENTED (R_ERROR_BASE+10) +#define R_ERROR_NOT_SUPPORTED (R_ERROR_BASE+11) +#define R_ERROR_INVALID_STATE \ + ((R_ERROR_BASE+12) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_INIT_NOT_CALLED \ + ((R_ERROR_BASE+13) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED \ + ((R_ERROR_BASE+14) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_METHOD_UNDEFINED \ + ((R_ERROR_BASE+15) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_BUFFER_TOO_SMALL \ + ((R_ERROR_BASE+16) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_NULL_ARG ((R_ERROR_BASE+17) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_VALUE ((R_ERROR_BASE+18) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_RANGE ((R_ERROR_BASE+19) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_FORMAT ((R_ERROR_BASE+20) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_TYPE ((R_ERROR_BASE+21) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_DATA ((R_ERROR_BASE+22) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_LENGTH ((R_ERROR_BASE+23) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_RCOM_LIBRARY_NOT_SUPPORTED (R_ERROR_BASE+24) + +/* Resource Manager base for errors */ +#define R_COM_ERR_LIB_CTX_BASE 10100 + +#endif /* HEADER_COMMON_R_ERROR_H */ + + +const BN_ME_METH *BN_ME_METH_thxc(void); +/** + * @note THX code only needs to store rr, n0, str + * + */ +typedef struct thxc_mont_ctx_st + { + BIGNUM *rr; + unsigned char *str; + unsigned int str_len; + BN_ULONG n0; + } THXC_MONT_CTX; + + +int Rx_thxr_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG n0, int top, int tmp_len, unsigned char *str); + +int Ri_thxr_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG *dp, BN_ULONG *aap, BN_ULONG *rp, BN_ULONG *tmp, + BN_ULONG n0, int top, unsigned char *str); + +void Ri_thxr_mul_normal(BN_ULONG *r,BN_ULONG *a,int na,BN_ULONG *b,int nb); +void Ri_thxr_sqr_normal(BN_ULONG *r, BN_ULONG *a, int n, BN_ULONG *tmp); + +void Ri_thxr_from_montgomery_words(BN_ULONG *ret,BN_ULONG *ap,BN_ULONG *np, + int w, BN_ULONG n0); + +BN_ULONG Ri_thxr_from_mont_words(BN_ULONG *ap,BN_ULONG *wap, + BN_ULONG *np, int w, BN_ULONG n0); + +#ifdef CPU_TMS320 + +/* Method and functions required for the ARM/DSP interface */ + +const BN_ME_METH *BN_ME_METH_dspc(void); + +int Rx_dsp_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG n0, int top, int tmp_len, unsigned char *str); + +int Ri_dsp_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG *dp, BN_ULONG *aap, BN_ULONG *rp, BN_ULONG *tmp, + BN_ULONG n0, int top, unsigned char *str); + +#endif + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_COMMON_BN_THX_H */ diff --git a/build/libraries_sysmenu/acsign/ARM9/include/md5.h b/build/libraries_sysmenu/acsign/ARM9/include/md5.h new file mode 100644 index 0000000..7a5ca73 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/md5.h @@ -0,0 +1,73 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef _MD5_H_ +#define _MD5_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* MD5.H - header file for MD5C.C + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +rights reserved. + +License to copy and use this software is granted provided that it +is identified as the "RSA Data Security, Inc. MD5 Message-Digest +Algorithm" in all material mentioning or referencing this software +or this function. + +License is also granted to make and use derivative works provided +that such works are identified as "derived from the RSA Data +Security, Inc. MD5 Message-Digest Algorithm" in all material +mentioning or referencing the derived work. + +RSA Data Security, Inc. makes no representations concerning either +the merchantability of this software or the suitability of this +software for any particular purpose. It is provided "as is" +without express or implied warranty of any kind. + +These notices must be retained in any copies of any part of this +documentation and/or software. + */ + +typedef struct MD5_CTX MD5_CTX; +typedef struct MD5_CTX MD5Context; + +/* MD5 context. */ +struct MD5_CTX{ + unsigned long state[4]; /* state (ABCD) */ + unsigned long count[2]; /* number of bits, modulo 2^64 (lsb first) */ + unsigned char buffer[64]; /* input buffer */ +} ; + +void MD5Init(MD5_CTX *); +void MD5Update(MD5_CTX *, unsigned char *, unsigned int); +void MD5Final(unsigned char digest[16], MD5_CTX *); + + +#if defined( MD5_TEST ) +int MD5Test( ); +#endif // MD5_TEST + +#ifdef __cplusplus +} +#endif + +#endif // _MD5_H_ diff --git a/build/libraries_sysmenu/acsign/ARM9/include/r_error.h b/build/libraries_sysmenu/acsign/ARM9/include/r_error.h new file mode 100644 index 0000000..16ffb55 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/r_error.h @@ -0,0 +1,226 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file r_error.h + * This file contains the error definitions for the toolkit. + */ +#ifndef HEADER_COMMON_R_ERROR_H +#define HEADER_COMMON_R_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup R_ERROR_IDS Error Identifiers + * This section outlines the error codes returned, enabling identification of + * specific errors. For more information, see the + * Developer's Guide. + * + * @{ + */ +/** + * Indicates that a fatal error has occurred in the operation performed. + * This flag is set with the following error codes:
+ *
    + *
  • #R_ERROR_INVALID_STATE.
  • + *
  • #R_ERROR_INIT_NOT_CALLED.
  • + *
  • #R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED.
  • + *
+ */ +#define R_ERROR_FATAL_INTERNAL_ERROR 64 + +/** + * Indicates that the specified parameter is incorrect or contains invalid + * information. This flag is set with the following error codes:
+ *
    + *
  • #R_ERROR_NULL_ARG.
  • + *
  • #R_ERROR_BUFFER_TOO_SMALL.
  • + *
  • #R_ERROR_BAD_VALUE.
  • + *
  • #R_ERROR_BAD_RANGE.
  • + *
  • #R_ERROR_BAD_FORMAT.
  • + *
  • #R_ERROR_BAD_TYPE.
  • + *
  • #R_ERROR_BAD_DATA.
  • + *
  • #R_ERROR_BAD_LENGTH.
  • + *
+ */ +#define R_ERROR_BAD_PARAMETER 32 + +/* Indicates the base value for all general errors used through all products */ +#define R_ERROR_BASE 10000 + +/** + * Indicates that no errors were detected in the requested operation. + */ +#define R_ERROR_NONE 0 + +/** + * Indicates that the requested operation failed. + */ +#define R_ERROR_FAILED (R_ERROR_BASE+1) +/** + * Indicates that the requested operation detected an Input/Output error. + */ +#define R_ERROR_IO (R_ERROR_BASE+2) +/** + * Indicates that the requested operation detected a protocol error. + */ +#define R_ERROR_PROTOCOL (R_ERROR_BASE+3) +/** + * Indicates that the requested operation detected an End-of-File (EOF) error. + */ +#define R_ERROR_EOF (R_ERROR_BASE+4) +/** + * Indicates that the requested operation failed in a memory allocation + * operation. + */ +#define R_ERROR_ALLOC_FAILURE (R_ERROR_BASE+5) +/** + * Indicates that the requested operation is restricted in an evaluation + * version of the library. + */ +#define R_ERROR_EVAL_RESTRICTION (R_ERROR_BASE+6) +/** + * Indicates that the evaluation period of the library has expired. + */ +#define R_ERROR_EVAL_EXPIRED (R_ERROR_BASE+7) +/** + * Indicates that the requested operation detected that a pre-requirement was + * not found. + */ +#define R_ERROR_NOT_FOUND (R_ERROR_BASE+8) +/** + * Indicates that the requested operation detected that a pre-requirement was + * unavailable. + */ +#define R_ERROR_NOT_AVAILABLE (R_ERROR_BASE+9) +/** + * Indicates that the requested operation is not implemented in the current + * instantiation of the library. + */ +#define R_ERROR_NOT_IMPLEMENTED (R_ERROR_BASE+10) +/** + * Indicates that the requested operation is not supported in the current + * instantiation of the library. + */ +#define R_ERROR_NOT_SUPPORTED (R_ERROR_BASE+11) +/** + * Indicates that the requested operation entered an invalid state. + */ +#define R_ERROR_INVALID_STATE \ + ((R_ERROR_BASE+12) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested operation detected that an initialization + * operation has not been performed. + */ +#define R_ERROR_INIT_NOT_CALLED \ + ((R_ERROR_BASE+13) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested operation should not have been called. + */ +#define R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED \ + ((R_ERROR_BASE+14) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested method is not defined. + */ +#define R_ERROR_METHOD_UNDEFINED \ + ((R_ERROR_BASE+15) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested operation detected an inadequately sized + * buffer. + */ +#define R_ERROR_BUFFER_TOO_SMALL \ + ((R_ERROR_BASE+16) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * was passed as NULL. + */ +#define R_ERROR_NULL_ARG ((R_ERROR_BASE+17) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed contained a bad or incorrect value. + */ +#define R_ERROR_BAD_VALUE ((R_ERROR_BASE+18) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed was out of the allowed range. + */ +#define R_ERROR_BAD_RANGE ((R_ERROR_BASE+19) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed used a format that is not supported or incorrect. + */ +#define R_ERROR_BAD_FORMAT ((R_ERROR_BASE+20) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed used a type that is not supported or incorrect. + */ +#define R_ERROR_BAD_TYPE ((R_ERROR_BASE+21) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed contained incorrect or invalid data. + */ +#define R_ERROR_BAD_DATA ((R_ERROR_BASE+22) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed contained an incorrect length value. + */ +#define R_ERROR_BAD_LENGTH ((R_ERROR_BASE+23) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the library instantiation requested is not supported. + */ +#define R_ERROR_RCOM_LIBRARY_NOT_SUPPORTED (R_ERROR_BASE+24) +/** + * Indicates that the request operation was denied. + */ +#define R_ERROR_DENIED (R_ERROR_BASE+25) +/** + * Indicates that authentication is required before the operation + * can succeed. + */ +#define R_ERROR_AUTHENTICATION_REQUIRED (R_ERROR_BASE+26) + +/** + * Indicates that a required module was unable to be loaded. + */ +#define R_ERROR_MODULE_LOAD_FAILED \ + ((R_ERROR_BASE+27)|R_ERROR_FATAL_INTERNAL_ERROR) + +/* Resource Manager base for errors */ +#define R_COM_ERR_LIB_CTX_BASE 10100 + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_COMMON_R_ERROR_H */ + + + diff --git a/build/libraries_sysmenu/acsign/ARM9/include/r_stdiag.h b/build/libraries_sysmenu/acsign/ARM9/include/r_stdiag.h new file mode 100644 index 0000000..fbe3d3c --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/r_stdiag.h @@ -0,0 +1,98 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +/* + * *************************************************************************** + * + * Purpose: + * + * This file defines an API for performing stack diagnostics. + * + * It provides: + * Peek Stack Usage statistics + * To use it: + * 1. Build the library without "NO_R_DIAG" defined + * 2. Make a call to R_DIAG_set_stack_datum() prior to + * calling the first library function. + * 3. Add calls to the macro R_DIAG_CHECK_STACK where potential + * high stack usage points are. + * 4. Call R_DIAG_get_stack_low_water_mark() at then end of the + * library calls to return the maximum stack usage OR + * 5. Call R_DIAG_print_stack_depth() to display the peek stack + * usage + * + * + * + * History: + * 3-Aug-00 mjs development + * + * ************************************************************************** + */ + + +#ifndef HEADER_COMMON_R_STDIAG_H +#define HEADER_COMMON_R_STDIAG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef NO_R_DIAG + +#ifdef NOPROTO +int R_DIAG_set_stack_datum(char *ptr); +int R_DIAG_check_stack(char *ptr, char *file, int line, int hit); +int R_DIAG_get_stack_low_water_mark(int *depth, char **file, int *line, + int *hit); +int R_DIAG_print_stack_depth(BIO *bio); + +#else + +int R_DIAG_set_stack_datum(); +int R_DIAG_check_stack(); +int R_DIAG_get_stack_low_water_mark(); +int R_DIAG_print_stack_depth(); + +#endif + +#define R_DIAG_CHECK_STACK {\ + char r_diag_stack_check_var = 0;\ + static int r_diag_stack_check_cnt = 0;\ +\ + R_DIAG_check_stack(&r_diag_stack_check_var, __FILE__,\ + __LINE__,++r_diag_stack_check_cnt);\ + } +#else +#define R_DIAG_CHECK_STACK +#endif + + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_COMMON_R_STDIAG_H */ + diff --git a/build/libraries_sysmenu/acsign/ARM9/include/r_types.h b/build/libraries_sysmenu/acsign/ARM9/include/r_types.h new file mode 100644 index 0000000..f6514b1 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/r_types.h @@ -0,0 +1,257 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file r_types.h + * This file contains the library structure and type definitions. + */ +#ifndef HEADER_COMMON_R_TYPES_H +#define HEADER_COMMON_R_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup DATA_MNG_FLAGS Data Management Flags + * This section lists the data management flags. + * @{ + */ + +/** + * @} + */ + +/* This gets set if the flags field if the we need to 'free' the + * R_RANDOM when we call R_rand_free(). If it is not set, the + * rand_ctrl will only be called to clean things up. + */ +#define R_RANDOM_FLG_MALLOCED 0x01 + +/* portable form of a random callback function */ +/** + * @typedef R_RANDOM + * The random object type. + */ +typedef struct r_random_st R_RANDOM; +/** + * This structure is used by the random object type. + */ +struct r_random_st +{ + /** + * A method function for generation of random data. + * + * @see R_rand_bytes(). + */ + int (*rand_bytes)(R_RANDOM *ctx,unsigned char *bytes,int len); + /** + * A method function for seeding of the random generator. + * @see R_rand_seed(). + */ + int (*rand_seed)(R_RANDOM *ctx,unsigned char *bytes,int len); + /** + * A method function for control of the random generator used by + * other functions as a single interface. + * + * @see R_rand_entropy_count(), R_rand_set_entropy_func(), + * R_rand_get_entropy_func(), R_rand_load_file(), R_rand_write_file() + * and R_rand_file_name(). + */ + int (*rand_ctrl)(R_RANDOM *ctx,int op,char *arg); + /** + * The data used by the random implementation. + */ + char *arg; + /** + * A method flag for used for keeping the state of the #R_RANDOM. + */ + int flags; /* normally set to zero */ +}; +/** + * @typedef R_SURRENDER + * The surrender function and argument. + */ +typedef struct r_surrender_st R_SURRENDER; +/** + * This structure provides a status update of a time intensive operation. It + * also allows you to abort the operation if required. + */ +struct r_surrender_st +{ + /* Return 0 to continue, non-zero to 'cancel' function */ + /** + * The surrender function pointer used as a generic method of + * passing user-defined callback or information collection functions. + */ + int (*callback)(R_SURRENDER *ctx,int function,int num); + /** + * The argument data used by the callback operation. + */ + char *arg; +}; + +typedef struct r_fixed_point_number_st R_FIXED_POINT_NUMBER; +struct r_fixed_point_number_st +{ + unsigned long hi; + unsigned long lo; +}; + +/** + * @typedef R_INDEXED_INFO + * This structure details the index containing information for get and set + * functions. + */ +typedef struct r_indexed_info_st R_INDEXED_INFO; +/** This structure details the index containing information for get and set + * functions. + */ +struct r_indexed_info_st +{ + /** The index into the list of the item to work with. */ + int index; + /** The data of the item in the list. */ + void *data; + /** The length of the data. */ + unsigned int len; + /** The data value as an integer. */ + int value; +}; + +/** + * @typedef R_ID_INFO + * The information to work with requires a second identity value to find it. + */ +typedef struct r_id_info_st R_ID_INFO; +/** The information to get or set requires a second information identifier. + * This type is used when calling set_info and get_info to get a number of + * information items in one call. + */ +struct r_id_info_st +{ + /** The information identifier. */ + int info_id; + /** The information data associated with the identifier. */ + void *value; +}; + +/** @defgroup R_FLAG_COPY_IDS Copy Flag Identifiers + * + * This section provides information on the copy mode. When data is passed + * to/from the library you can specify whether or not the copy should be done + * by value, by reference or by direct assignment. + * @ingroup DATA_MNG_FLAGS + * @{ + */ + +/** + * The copy flag. When data is passed to/from the library you can specify + * whether or not the copy should be done by value, by reference or + * by direct assignment. + */ +typedef int R_FLAG_COPY; + +/* + * action flag app lib + * obj_get BY_VAL F X + * BY_REF X F [app will not free "obj" until it is + * BY_ASSIGN F X finished with the returned reference] + * obj_set BY_VAL F X + * BY_REF F X [app will not free passed reference + * BY_ASSIGN X F until after it has freed "obj"] + * + * BY_REF makes the lifetime of the two objects linked and it is up to + * the application to manage the objects in a manner that preserves this + * relationship. + */ + +/** + * Indicates to copy by value. A complete clone of the object is made. + * The lifecycles of the two objects are independent. + */ +#define R_FLAG_COPY_BY_VALUE 0x0000 + +/** + * Indicates to copy by reference. A reference to the object is made. + * The lifecycles of objects sharing references are linked. + */ +#define R_FLAG_COPY_BY_REFERENCE 0x0001 + +/** + * Indicates to copy by assignment. The object is assigned to the required + * party. The caller does not keep a reference to the passed object. + */ +#define R_FLAG_COPY_BY_ASSIGN 0x0002 + +/** + * Indicates to copy using the default flag settings. + */ +#define R_FLAG_COPY_DEFAULT R_FLAG_COPY_BY_VALUE + +/** + * @} + */ + +/** @defgroup R_FLAG_SHARE_IDS Shared Flag Identifiers + * + * This section provides information on the shared flags available. + * @ingroup DATA_MNG_FLAGS + * @{ + */ + +/** + * The constructor flag. Indicates whether or not it is permissible to share + * the internal state between objects. + */ +typedef int R_FLAG_SHARE; + +/** + * Indicates to share nothing. The states of the two objects are completely + * separate. + */ +#define R_FLAG_SHARE_NONE 0x0000 + +/** + * Indicates to share data. Constructed objects may reference the state of + * the object from which it was constructed. The lifecycles of the two objects + * are linked. + */ +#define R_FLAG_SHARE_DATA 0x0001 + +/** Indicates the share default in which nothing is shared. */ +#define R_FLAG_SHARE_DEFAULT R_FLAG_SHARE_NONE + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/build/libraries_sysmenu/acsign/ARM9/include/sha.h b/build/libraries_sysmenu/acsign/ARM9/include/sha.h new file mode 100644 index 0000000..e1543a7 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/sha.h @@ -0,0 +1,105 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef HEADER_COMMON_SHA_H +#define HEADER_COMMON_SHA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(CCONV) +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +#define SHA_CBLOCK 64 +#define SHA_LBLOCK 16 +#define SHA_BLOCK 16 +#define SHA_LAST_BLOCK 56 +#define SHA_LENGTH_BLOCK 8 +#define SHA_DIGEST_LENGTH 20 + +/* the default is to use unsigned long */ +#if !defined(OPT_SHA_INT) && !defined(OPT_SHA_LONG) +#define OPT_SHA_LONG +#endif + +#ifdef OPT_SHA_LONG +#define SHA_LONG unsigned long +#endif + +#ifdef OPT_SHA_INT +#define SHA_LONG unsigned int +#endif + +typedef struct sha_ctx_st SHA_CTX; + +struct sha_ctx_st + { + SHA_LONG h0,h1,h2,h3,h4; + SHA_LONG Nl,Nh; + SHA_LONG data[SHA_LBLOCK]; + int num; + void (PRE_CCONV CCONV *sha_block)(SHA_CTX *c, const unsigned char *W, + int num); + }; + +#ifndef NOPROTO +int SHA1_Setup(SHA_CTX *c, void (PRE_CCONV CCONV *sha_block)(SHA_CTX *c, + const unsigned char *W, int num)); +void SHA_Init(SHA_CTX *c); +void SHA_Update(SHA_CTX *c, const unsigned char *data, unsigned long len); +void SHA_Final(unsigned char *md, SHA_CTX *c); +unsigned char *SHA(const unsigned char *d, unsigned long n,unsigned char *md); +void SHA_Transform(SHA_CTX *c, const unsigned char *data); +void SHA1_Init(SHA_CTX *c); +void SHA1_Update(SHA_CTX *c, const unsigned char *data, unsigned long len); +void SHA1_Final(unsigned char *md, SHA_CTX *c); +unsigned char *SHA1(const unsigned char *d, unsigned long n,unsigned char *md); +void SHA1_Transform(SHA_CTX *c, const unsigned char *data); +#else +void SHA_Init(); +void SHA_Update(); +void SHA_Final(); +unsigned char *SHA(); +void SHA_Transform(); +void SHA1_Init(); +void SHA1_Update(); +void SHA1_Final(); +unsigned char *SHA1(); +void SHA1_Transform(); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_SHA_H */ diff --git a/build/libraries_sysmenu/acsign/ARM9/include/sha1.h b/build/libraries_sysmenu/acsign/ARM9/include/sha1.h new file mode 100644 index 0000000..692f2e9 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/sha1.h @@ -0,0 +1,90 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * sha1.h + * + * Description: + * This is the header file for code which implements the Secure + * Hashing Algorithm 1 as defined in FIPS PUB 180-1 published + * April 17, 1995. + * + * Many of the variable names in this code, especially the + * single character names, were used because those were the names + * used in the publication. + * + * Please read the file sha1.c for more information. + * + */ + +#ifndef _SHA1_H_ +#define _SHA1_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _SHA_enum_ +#define _SHA_enum_ +enum +{ + shaSuccess = 0, + shaNull, /* Null pointer parameter */ + shaInputTooLong, /* input data too long */ + shaStateError /* called Input after Result */ +}; +#endif + +/* + * This structure will hold context information for the SHA-1 + * hashing operation + */ +typedef struct SHA1Context +{ + unsigned long Intermediate_Hash[20/4]; /* Message Digest */ + + unsigned long Length_Low; /* Message length in bits */ + unsigned long Length_High; /* Message length in bits */ + + int Message_Block_Index; /* Index into message block array */ + unsigned char Message_Block[64]; /* 512-bit message blocks */ + + int Computed; /* Is the digest computed? */ + int Corrupted; /* Is the message digest corrupted? */ +} SHA1Context; + +/* + * Function Prototypes + */ + +int SHA1Reset( SHA1Context *); +int SHA1Input( SHA1Context *, + const unsigned char *, + unsigned int); +int SHA1Result( SHA1Context *, + unsigned char Message_Digest[20]); + +#if defined( SHA1_TEST ) +int SHA1Test( ); +#endif // SHA1_TEST + + +#ifdef __cplusplus +} +#endif + +#endif // _SHA1_H_ diff --git a/build/libraries_sysmenu/acsign/ARM9/include/sha_locl.h b/build/libraries_sysmenu/acsign/ARM9/include/sha_locl.h new file mode 100644 index 0000000..10553ab --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/include/sha_locl.h @@ -0,0 +1,290 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef HEADER_COMMON_SHA_LOCL_H +#define HEADER_COMMON_SHA_LOCL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STANDALONE +#include "r_com.h" +#else +#if 0 //RSA +#include +#include +#include +#define Memcpy memcpy +#define Memset memset +#define Strcpy strcpy +#else //NITRO +#include "acmemory.h" +#define Malloc(a) ACMemory_Alloc(a) +#define Free(a) ACMemory_Free(a) +#define Memset(a,b,c) ACMemory_Memset(a,b,c) +#define Memcpy(a,b,c) ACMemory_Memcpy(a,b,c) +#endif +#endif + +#ifdef undef +/* one or the other must be defined */ +#ifndef SHA_1 /* FIPE 180-1 */ +#define SHA_0 /* FIPS 180 */ +#endif +#endif + +#define ULONG unsigned long +#define UCHAR unsigned char +#define UINT unsigned int + +#ifdef NOCONST +#define const +#endif + +#undef c2nl +#define c2nl(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++))) )) + +#undef p_c2nl +#define p_c2nl(c,l,n) { \ + switch (n) { \ + case 0: l =((unsigned long)(*((c)++)))<<24; \ + case 1: l|=((unsigned long)(*((c)++)))<<16; \ + case 2: l|=((unsigned long)(*((c)++)))<< 8; \ + case 3: l|=((unsigned long)(*((c)++))); \ + } \ + } + +#undef c2nl_p +/* NOTE the pointer is not incremented at the end of this */ +#define c2nl_p(c,l,n) { \ + l=0; \ + (c)+=n; \ + switch (n) { \ + case 3: l =((unsigned long)(*(--(c))))<< 8; \ + case 2: l|=((unsigned long)(*(--(c))))<<16; \ + case 1: l|=((unsigned long)(*(--(c))))<<24; \ + } \ + } + +#undef p_c2nl_p +#define p_c2nl_p(c,l,sc,len) { \ + switch (sc) \ + { \ + case 0: l =((unsigned long)(*((c)++)))<<24; \ + if (--len == 0) break; \ + case 1: l|=((unsigned long)(*((c)++)))<<16; \ + if (--len == 0) break; \ + case 2: l|=((unsigned long)(*((c)++)))<< 8; \ + } \ + } + +#undef nl2c +#define nl2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff)) + +#undef c2l +#define c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<<24)) + +#undef p_c2l +#define p_c2l(c,l,n) { \ + switch (n) { \ + case 0: l =((unsigned long)(*((c)++))); \ + case 1: l|=((unsigned long)(*((c)++)))<< 8; \ + case 2: l|=((unsigned long)(*((c)++)))<<16; \ + case 3: l|=((unsigned long)(*((c)++)))<<24; \ + } \ + } + +#undef c2l_p +/* NOTE the pointer is not incremented at the end of this */ +#define c2l_p(c,l,n) { \ + l=0; \ + (c)+=n; \ + switch (n) { \ + case 3: l =((unsigned long)(*(--(c))))<<16; \ + case 2: l|=((unsigned long)(*(--(c))))<< 8; \ + case 1: l|=((unsigned long)(*(--(c)))); \ + } \ + } + +#undef p_c2l_p +#define p_c2l_p(c,l,sc,len) { \ + switch (sc) \ + { \ + case 0: l =((unsigned long)(*((c)++))); \ + if (--len == 0) break; \ + case 1: l|=((unsigned long)(*((c)++)))<< 8; \ + if (--len == 0) break; \ + case 2: l|=((unsigned long)(*((c)++)))<<16; \ + } \ + } + +#undef l2c +#define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24)&0xff)) + +#ifdef OPT_SHA_B_ENDIAN +#define B_ENDIAN +#endif +#ifdef OPT_SHA_L_ENDIAN +#define L_ENDIAN +#endif + +#undef ROTATE +#if defined(WIN32) +#define ROTATE(a,n) _lrotl(a,n) +#else +#define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n)))) +#endif + +/* byte order reversal */ +#if defined(WIN32) +/* 5 instructions with rotate instruction, else 9 */ +#define Endian_Reverse32(a) \ + { \ + unsigned long l=(a); \ + (a)=((ROTATE(l,8)&0x00FF00FF)|(ROTATE(l,24)&0xFF00FF00)); \ + } +#else +/* 6 instructions with rotate instruction, else 8 */ +#define Endian_Reverse32(a) \ + { \ + unsigned long l=(a); \ + l=(((l&0xFF00FF00)>>8L)|((l&0x00FF00FF)<<8L)); \ + (a)=ROTATE(l,16L); \ + } +#endif + +/* F() below can be + * simplified to the code in F_00_19. + * #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) + * another tweak to be made + * in F_40_59, (x&a)|(y&a) -> (x|y)&a + */ +#define F_00_19(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) +#define F_20_39(b,c,d) ((b) ^ (c) ^ (d)) +#define F_40_59(b,c,d) (((b) & (c)) | (((b)|(c)) & (d))) +#define F_60_79(b,c,d) F_20_39(b,c,d) + +#ifdef SHA_0 +#undef Xupdate +#define Xupdate(a,i,ia,ib,ic,id) X[(i)&0x0f]=(a)=\ + (ia[(i)&0x0f]^ib[((i)+2)&0x0f]^ic[((i)+8)&0x0f]^id[((i)+13)&0x0f]); +#endif +#ifdef SHA_1 +#undef Xupdate +#define Xupdate(a,i,ia,ib,ic,id) (a)=\ + (ia[(i)&0x0f]^ib[((i)+2)&0x0f]^ic[((i)+8)&0x0f]^id[((i)+13)&0x0f]);\ + X[(i)&0x0f]=(a)=ROTATE((a),1); +#endif + +#define BODY_00_15(i,a,b,c,d,e,f,xa) \ + (f)=xa[i]+(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_60_79(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)=X[(i)&0x0f]+(e)+K_60_79+ROTATE((a),5)+F_60_79((b),(c),(d)); \ + (b)=ROTATE((b),30); + +/* + * The CodeWarrior compiler has a problem correctly expanding things like + * + * (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); + * + * so we separate this to 3 explicit adds, just for PalmOS. + */ +#ifndef UNDER_PALMOS + +#define BODY_16_19(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_20_31(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_32_39(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_40_59(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e)+K_40_59+ROTATE((a),5)+F_40_59((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#else /* UNDER_PALMOS */ + +#define BODY_16_19(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e); \ + (f)+=K_00_19; \ + (f)+=ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_20_31(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e); \ + (f)+=K_20_39; \ + (f)+=ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_32_39(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e); \ + (f)+=K_20_39; \ + (f)+=ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_40_59(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e); \ + (f)+=K_40_59; \ + (f)+=ROTATE((a),5)+F_40_59((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#endif /* UNDER_PALMOS */ + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_SHA_LOCL_H */ diff --git a/build/libraries_sysmenu/acsign/ARM9/src/acmemory.c b/build/libraries_sysmenu/acsign/ARM9/src/acmemory.c new file mode 100644 index 0000000..a6785f0 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/acmemory.c @@ -0,0 +1,306 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +// +// BNn֐p̃֘Au +// +#include +#include "acmemory.h" + +/* + head tail + | | | | + +--------+---------+----....----+---------+--------+ + |block |check |buffer |check |block | + +--------+---------+----....----+---------+--------+ + |4byte |4byte |Upper4(size)|4byte |4byte | + <------------------ 4 * n -------------------> + + block = n = (4 * 4 + Upper4(size)) / 4 + check = 0x0F5555F0Fgp^0x0FAAAAF0Fgp +*/ + +unsigned long aACMemoryPoolA[ 16 ]; +unsigned long aACMemoryPool[ 1024 * 32 / sizeof (unsigned long) ]; // 32K +unsigned long aACMemoryPoolB[ 16 ]; + +#define ACMEMORYPOOL_HEAD (aACMemoryPool) +#define ACMEMORYPOOL_TAIL (aACMemoryPool + sizeof aACMemoryPool / sizeof (unsigned long)) +#define ACMEMORYPOOL_SIZE ((unsigned long)ACMEMORYPOOL_TAIL - (unsigned long)ACMEMORYPOOL_HEAD) + +#define ACMEMORY_CHECK_BASE 0xF000000F +#define ACMEMORY_CHECK_FREE (0x00555500 | ACMEMORY_CHECK_BASE) +#define ACMEMORY_CHECK_USED (0x00AAAA00 | ACMEMORY_CHECK_BASE) + +#define ACMemory_Lower4( _size ) (((_size) ) & 0xFFFFFFFC) +#define ACMemory_Upper4( _size ) (((_size) + 3) & 0xFFFFFFFC) + +#define pACMemory_FromHeadToBody( _head ) ((unsigned long*)(((volatile unsigned long*)(_head)) + 2)) +#define pACMemory_FromBodyToHead( _body ) ((unsigned long*)(((volatile unsigned long*)(_body)) - 2)) +#define pACMemory_FromHeadToTail( _head ) ((unsigned long*)(((volatile unsigned long*)(_head)) + nACMemory_HeadBlock( _head ))) +#define pACMemory_FromTailToHead( _tail ) ((unsigned long*)(((volatile unsigned long*)(_tail)) - nACMemory_TailBlock( _tail ))) +#define nACMemory_HeadBlock( _head ) (((volatile unsigned long*)(_head))[+0]) +#define nACMemory_HeadCheck( _head ) (((volatile unsigned long*)(_head))[+1]) +#define nACMemory_TailBlock( _tail ) (((volatile unsigned long*)(_tail))[-1]) +#define nACMemory_TailCheck( _tail ) (((volatile unsigned long*)(_tail))[-2]) + +//#define USE_OSALLOC +//#define USE_ACMEMORY_DEBUGDUMP +//#define USE_ACMEMORY_DEBUGFILL + +// +#if defined( USE_ACMEMORY_DEBUGDUMP ) +static +void acMemory_DebugDump( ) +{ + unsigned long* ptr = ACMEMORYPOOL_HEAD; + + // + OS_Printf( "----ACMemory_Dump [0x%.8x - 0x%.8x : 0x%.8x ]----\n", ACMEMORYPOOL_HEAD, ACMEMORYPOOL_TAIL, ACMEMORYPOOL_SIZE ); + + for ( ; (unsigned long)ptr < (unsigned long)ACMEMORYPOOL_TAIL; ) + { + OS_Printf( " [0x%.8x - 0x%.8x] (0x%.8x) <%c> ", + ptr, + pACMemory_FromHeadToTail( ptr ), + nACMemory_HeadBlock( ptr ), + nACMemory_HeadCheck( ptr ) == ACMEMORY_CHECK_USED ? '*' : '-' ); + + //OS_Printf( "0x%.8x 0x%.8x", nACMemory_HeadBlock( ptr ), nACMemory_HeadCheck( ptr ) ); + + //OS_Printf( " .... " ); + + ptr += nACMemory_HeadBlock( ptr ); + + //OS_Printf( "0x%.8x 0x%.8x", nACMemory_TailCheck( ptr ), nACMemory_TailBlock( ptr ) ); + + OS_Printf( "\n" ); + OS_PrintServer(); + } + ptr = 0; +} + +#define ACMemory_DebugDump( ) acMemory_DebugDump( ) + +#else + +#define ACMemory_DebugDump( ) + +#endif //USE_ACMEMORY_DEBUGDUMP + +// +#if defined( USE_ACMEMORY_DEBUGFILL ) +static +void acMemory_DebugFill( void* ptr, int cnt, int val ) +{ + (void)ACMemory_Memset( ptr, val, cnt ); +} + +#define ACMemory_DebugFill( _ptr, _cnt, _val ) acMemory_DebugFill( _ptr, _cnt, _val ) + +#else + +#define ACMemory_DebugFill( _ptr, _cnt, _val ) + +#endif //USE_ACMEMORY_DEBUGFILL + +// +void ACMemory_Clear( ) +{ + unsigned long* head = ACMEMORYPOOL_HEAD; + unsigned long* tail = ACMEMORYPOOL_TAIL; + unsigned long block; + unsigned long check; + + + block = ACMEMORYPOOL_SIZE / 4; + check = ACMEMORY_CHECK_FREE; + + nACMemory_HeadBlock( head ) = block; + nACMemory_HeadCheck( head ) = check; + nACMemory_TailBlock( tail ) = block; + nACMemory_TailCheck( tail ) = check; + + ACMemory_DebugFill( pACMemory_FromHeadToBody( head ), (block - 4) * 4, 0xFF ); + ACMemory_DebugDump( ); +} + +// +void* ACMemory_Alloc( u32 size ) +{ + #if defined( USE_OSALLOC ) + OSIntrMode nOSIntrMode; + void* alloc = NULL; + + nOSIntrMode = OS_DisableInterrupts( ); + alloc = OS_Alloc( size ); + (void)OS_RestoreInterrupts( nOSIntrMode ); + return alloc; + + #else + + unsigned long* head = ACMEMORYPOOL_HEAD; + unsigned long* tail = ACMEMORYPOOL_TAIL; + unsigned long block, oldblock, newblock; + unsigned long check, oldcheck, newcheck; + + if ( !size ) return 0; + + // + if ( size < 16 ) size = 16; + block = 4 + ACMemory_Upper4( size ) / 4; + check = ACMEMORY_CHECK_USED; + + // + for ( ; ; ) + { + if ( (unsigned long)head >= (unsigned long)tail ) + { + head = 0; + break; + } + + newblock = nACMemory_HeadBlock( head ); + newcheck = nACMemory_HeadCheck( head ); + if ( newcheck == check ) + { + head += newblock; + continue ; + } + if ( newblock < block + 4 + 4 ) + { + head += newblock; + continue ; + } + + break; + } + + if ( !head ) return 0; + + // + oldblock = nACMemory_HeadBlock( head ); + oldcheck = nACMemory_HeadCheck( head ); + + nACMemory_HeadBlock( head ) = block; + nACMemory_HeadCheck( head ) = check; + + tail = pACMemory_FromHeadToTail( head ); + nACMemory_TailBlock( tail ) = block; + nACMemory_TailCheck( tail ) = check; + + if ( (unsigned long)tail < (unsigned long)ACMEMORYPOOL_TAIL ) + { + nACMemory_HeadBlock( tail ) = oldblock - block; + nACMemory_HeadCheck( tail ) = oldcheck; + tail = pACMemory_FromHeadToTail( tail ); + nACMemory_TailBlock( tail ) = oldblock - block; + nACMemory_TailCheck( tail ) = oldcheck; + } + + // + (void)ACMemory_Memset( pACMemory_FromHeadToBody( head ), 0x00, (block - 4) * 4 ); + + ACMemory_DebugFill( pACMemory_FromHeadToBody( head ), (block - 4) * 4, 0x00 ); + ACMemory_DebugDump( ); + + return (void*)pACMemory_FromHeadToBody( head ); + #endif +} + +// +void ACMemory_Free( void* adrs ) +{ + #if defined( USE_OSALLOC ) + OSIntrMode nOSIntrMode; + + nOSIntrMode = OS_DisableInterrupts( ); + OS_Free( adrs ); + (void)OS_RestoreInterrupts( nOSIntrMode ); + #else + + unsigned long* work; + unsigned long* head; + unsigned long* tail; + unsigned long block; + unsigned long check; + + + if ( !adrs ) return ; + + // + head = pACMemory_FromBodyToHead( adrs ); + tail = pACMemory_FromHeadToTail( head ); + block = nACMemory_HeadBlock( head ); + check = ACMEMORY_CHECK_FREE; + + // + if ( nACMemory_HeadBlock( head ) != nACMemory_TailBlock( tail ) ) + return ; + if ( nACMemory_HeadCheck( head ) != nACMemory_TailCheck( tail ) ) + return ; + + + // + if ( (unsigned long)head != (unsigned long)ACMEMORYPOOL_HEAD ) + { + work = pACMemory_FromTailToHead( head ); + if ( nACMemory_HeadCheck( work ) == check ) + { + block += nACMemory_HeadBlock( work ); + head = work; + } + } + // + if ( (unsigned long)tail != (unsigned long)ACMEMORYPOOL_TAIL ) + { + work = pACMemory_FromHeadToTail( tail ); + if ( nACMemory_TailCheck( work ) == check ) + { + block += nACMemory_TailBlock( work ); + tail = work; + } + } + + // + nACMemory_HeadBlock( head ) = nACMemory_TailBlock( tail ) = block; + nACMemory_HeadCheck( head ) = nACMemory_TailCheck( tail ) = check; + + ACMemory_DebugFill( pACMemory_FromHeadToBody( head ), (block - 4) * 4, 0xFF ); + ACMemory_DebugDump( ); + + #endif +} + + +// +void* ACMemory_Memset( void* adrs, u32 val, u32 cnt ) +{ + if ( !adrs ) return 0; + MI_CpuFill8( (void*)adrs, (u8)val, (u32)cnt ); + return adrs; +} + +// +void* ACMemory_Memcpy( void* dst, void* src, u32 cnt ) +{ + if ( !dst || !src ) return 0; + MI_CpuCopy8( (const void*)src, (void*)dst, (u32)cnt ); + return dst; +} + + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/acsign.c b/build/libraries_sysmenu/acsign/ARM9/src/acsign.c new file mode 100644 index 0000000..f5dc67d --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/acsign.c @@ -0,0 +1,453 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "acmemory.h" + +// SHA1 +#include "sha.h" +#include "sha1dgst.c" + +#define _DLENGTH_ (160/8) +#define _BLENGTH_ (512/8) + +#define HASHContext SHA_CTX + +#define HASHReset( _context ) (void)SHA1_Init( _context ) +#define HASHSetSource( _context, _ptr, _len ) (void)SHA1_Update( _context, _ptr, _len ) +#define HASHGetDigest( _context, _ptr ) (void)SHA1_Final( _ptr, _context ) + +// BN +#include "bn.h" + +#include "bn_lib.c" +#include "bn_asm.c" +#include "bn_comba.c" +#include "bn_lsh.c" +#include "bn_rsh.c" +#include "bn_word.c" +#include "bn_add.c" +#include "bn_mul.c" +#include "bn_div.c" +#include "bn_exp.c" +#include "bn_sqr.c" +#include "bn_fm_w.c" +#include "bn_gcd.c" +#include "bn_ex_str.c" +#include "bn_ms_w.c" +//#include "bn_me.c" +#include "bn_rec.c" +#include "bn_mont.c" +#include "bn_recp.c" +#include "bn_wdiv.c" +#include "bn_r_exp.c" +#include "bn_m_exp.c" + + +#if !defined( RSA_ENC_DEC ) + +#define BER_NULL 5 +#define BER_OBJECT 6 +#define BER_SEQUENCE 16 +#define BER_OCTET_STRING 4 +#define BER_CONSTRUCTED 0x20 + + +// +// rsa_padding_check_pkcs1_type_1֐ +// +static +int decode_padding( unsigned char* pdst_adrs, unsigned int* pdst_size, + unsigned char* psrc_adrs, unsigned int nsrc_size, + int length ) +{ + unsigned char* p; + unsigned char* q; + unsigned char* pe; + int i; + + if (nsrc_size >= length ) + return 0; + + /* The leading 0 was removed by the bignum->bin conversion */ + if (nsrc_size < 10) + return 0; + + p = psrc_adrs; + pe = &(psrc_adrs[nsrc_size]); + /* if (p[0] != 0) goto err; */ + if ( p[0] != 1 ) + return 0; + p++; + + for ( i = 0; i < 8; i++ ) + { + if ( *(p++) != 0xFF ) + return 0; + } + for ( ; p != pe; p++ ) + { + if ( *p != 0xFF ) + break; + } + if ( p == pe ) + return 0; + + if ( *(p++) != 0 ) + return 0; + + *pdst_size = (unsigned int)((int)pe - (int)p); + q = pdst_adrs; + while ( p != pe ) + *(q++)= *(p++); + + return 1; +} + +// +// +// +static +int pk_skip( unsigned char **datap, unsigned int *dlenp, + unsigned char type, unsigned int *lenp) +{ + unsigned char *data = *datap; + unsigned int dlen = *dlenp; + unsigned int len = 0; + unsigned char l; + + if (*(data++) != type) + return 0; + + if (dlen < 1) + return 0; + dlen--; + + if ( (*data & 0x80) != 0 ) + { + l = (unsigned char)( *data & 0x7F ); + if (dlen < (unsigned int)l + 1) + return 0; + dlen -= l; + if (lenp != NULL) + { + data++; + do + { + len <<= 7; + len += (*data & 0x7f); + l--; + } + while (l > 0); + } + else + { + data += l; + } + } + else + { + len = *data; + data++; + if (dlen < 1) + return 0; + dlen--; + } + + *datap = data; + *dlenp = dlen; + if (lenp != NULL) + { + *lenp = len; + } + + return 1; +} + +// +// PK_decode_sighash֐ +// +static +int decode_sighash( unsigned char* data, unsigned int dlen, + unsigned char** ppdgst_adrs, unsigned int* pdgst_size, + unsigned char** pphash_adrs, unsigned int* phash_size ) +{ + #if 0 + /* 01 */ OB_cmpu(BER_SEQUENCE, 0, 0), + /* 02 */ OB_down(0, 1), + /* 03 */ OB_cmpu(BER_SEQUENCE, 0, 0), + /* 04 */ OB_down(0, 1), + /* 05 */ OB_cmpu(BER_OBJECT, 0, 0), + /* 06 */ OB_call(OB_F_SET, PK_TYPE_SIG, PK_SIG_DIGEST_OID), + + /* go up a level - we got all we need out of the + * sequence that contains the parameters + * - we could OB_next(0,1) and check that we have BER_NULL + * as then next item but there is no real need to do that + */ + + /* 07 */ OB_up(0, 1), + /* 08 */ OB_next(0, 1), + /* 09 */ OB_cmpu(BER_OCTET_STRING, 0, 0), + /* 10 */ OB_call(OB_F_SET, PK_TYPE_SIG, PK_SIG_HASH), + + /* 11 */ OB_exit(0), + /* 12 */ OB_FINISH, + #endif + + unsigned int len; + + if ( !pk_skip(&data, &dlen, (BER_SEQUENCE|BER_CONSTRUCTED), NULL) ) + return 0; + + if ( !pk_skip(&data, &dlen, (BER_SEQUENCE|BER_CONSTRUCTED), NULL) ) + return 0; + + if ( !pk_skip(&data, &dlen, (BER_OBJECT), &len) ) + return 0; + + /* + if (digest != NULL) + { + digest->adrs = data; + digest->size = len; + } + */ + if ( ppdgst_adrs ) *ppdgst_adrs = data; + if ( pdgst_size ) *pdgst_size = len; + + data += len; + if (dlen < len) + return 0; + dlen -= len; + + if ( !pk_skip(&data, &dlen, BER_NULL, &len) ) + return 0; + data += len; + if (dlen < len) + return 0; + dlen -= len; + + if ( !pk_skip(&data, &dlen, (BER_OCTET_STRING), &len) ) + return 0; + + /* + if (hash != NULL) + { + hash->adrs = data; + hash->size = len; + } + */ + if ( pphash_adrs ) *pphash_adrs = data; + if ( phash_size ) *phash_size = len; + + return 1; +} + +#endif + + + + +// +#define SGN_LEN 128 +#define MOD_LEN 128 +#define EXP_LEN 3 + +int ACSign_Decrypto( + void* buffer, // o͗̈ + void* sgn_ptr, // f[^ւ̃|C^ + void* key_ptr // L[ւ̃|C^ + ) +{ + BN_CTX* ctx; + BIGNUM src, dst, exp, mod; + void* exp_ptr; + void* mod_ptr; + int nTmp, nWrk; + unsigned char* pAdrs = 0; + unsigned int nSize = 0; + unsigned long nDummyExp = 0x00010001; // 65537Œ + unsigned long aBufferA[ 256 / sizeof (unsigned long) ]; + unsigned long aBufferB[ 256 / sizeof (unsigned long) ]; + + + if ( !buffer ) return 0; + if ( !sgn_ptr ) return 0; + if ( !key_ptr ) return 0; + + // + ACMemory_Clear( ); + + // + exp_ptr = &nDummyExp; + mod_ptr = key_ptr; + + (void)ACMemory_Memset( aBufferA, 0, sizeof aBufferA ); + (void)ACMemory_Memset( aBufferB, 0, sizeof aBufferB ); + + ctx=BN_CTX_new(); + + BN_init( &src ); + BN_init( &dst ); + BN_init( &exp ); + BN_init( &mod ); + + (void)BN_bin2bn( sgn_ptr, SGN_LEN, &src ); + (void)BN_bin2bn( exp_ptr, EXP_LEN, &exp ); + (void)BN_bin2bn( mod_ptr, MOD_LEN, &mod ); + + nTmp = BN_mod_exp( &dst, &src, &exp, &mod, ctx ); + + nTmp = BN_bn2bin( &dst, (unsigned char*)aBufferA ); + + BN_free( &src ); + BN_free( &dst ); + BN_free( &exp ); + BN_free( &mod ); + + if (ctx != NULL) + BN_CTX_free(ctx); + + #if defined( RSA_ENC_DEC ) + + pAdrs = (unsigned char*)aBufferA + 4; //_~[SoCg͓ǂݔ΂ + nSize = nTmp; + + (void)ACMemory_Memcpy( buffer, pAdrs, _DLENGTH_ * 4 ); + + #else + + if ( !decode_padding( (unsigned char*)aBufferB, (unsigned int*)&nWrk, (unsigned char*)aBufferA, (unsigned int )nTmp, SGN_LEN ) ) + return 0; + if ( !decode_sighash( (unsigned char*)aBufferB, (unsigned int)nWrk, NULL, NULL, (unsigned char**)&pAdrs, (unsigned int*)&nSize ) ) + return 0; + if ( nSize != _DLENGTH_ ) + return 0; + + (void)ACMemory_Memcpy( buffer, pAdrs, _DLENGTH_ * 1 ); + + #endif + + return 1; +} + + +// +#define ROMH_SIZE 0x0160 +int ACSign_Digest( + void* buffer, // o͗̈ + void* romh_ptr, // f[^ւ̃|C^ + void* mbin_ptr, // f[^ւ̃|C^ + int mbin_len, // f[^̒ + void* sbin_ptr, // f[^ւ̃|C^ + int sbin_len, // f[^̒ + u32 serial_num // VAio[ + ) +{ + #if defined( RSA_ENC_DEC ) + HASHContext context; + + + if ( !buffer ) return 0; + if ( !romh_ptr ) return 0; + if ( !mbin_ptr || !mbin_len ) return 0; + if ( !sbin_ptr || !sbin_len ) return 0; + + + HASHReset( &context ); + HASHSetSource( &context, romh_ptr, ROMH_SIZE ); + HASHGetDigest( &context, (unsigned char*)buffer + _DLENGTH_ * 0 ); + + HASHReset( &context ); + HASHSetSource( &context, mbin_ptr, mbin_len ); + HASHGetDigest( &context, (unsigned char*)buffer + _DLENGTH_ * 1 ); + + HASHReset( &context ); + HASHSetSource( &context, sbin_ptr, sbin_len ); + HASHGetDigest( &context, (unsigned char*)buffer + _DLENGTH_ * 2 ); + + HASHReset( &context ); + HASHSetSource( &context, buffer, _DLENGTH_ * 3 ); + HASHGetDigest( &context, (unsigned char*)buffer + _DLENGTH_ * 3 ); + + #else + + HASHContext context; + unsigned char aBuffer[ (_DLENGTH_ * 3 + sizeof (unsigned long)) ]; + + if ( !buffer ) return 0; + if ( !romh_ptr ) return 0; + if ( !mbin_ptr || !mbin_len ) return 0; + if ( !sbin_ptr || !sbin_len ) return 0; + + HASHReset( &context ); + HASHSetSource( &context, romh_ptr, ROMH_SIZE ); + HASHGetDigest( &context, (unsigned char*)aBuffer + _DLENGTH_ * 0 ); + + HASHReset( &context ); + HASHSetSource( &context, mbin_ptr, mbin_len ); + HASHGetDigest( &context, (unsigned char*)aBuffer + _DLENGTH_ * 1 ); + + HASHReset( &context ); + HASHSetSource( &context, sbin_ptr, sbin_len ); + HASHGetDigest( &context, (unsigned char*)aBuffer + _DLENGTH_ * 2 ); + + // VAԍ ͂OŒ + aBuffer[ (_DLENGTH_ * 3) + 0 ] = (unsigned char)((serial_num >> 0) & 0xFF); + aBuffer[ (_DLENGTH_ * 3) + 1 ] = (unsigned char)((serial_num >> 8) & 0xFF); + aBuffer[ (_DLENGTH_ * 3) + 2 ] = (unsigned char)((serial_num >> 16) & 0xFF); + aBuffer[ (_DLENGTH_ * 3) + 3 ] = (unsigned char)((serial_num >> 24) & 0xFF); + + HASHReset( &context ); + HASHSetSource( &context, (unsigned char*)aBuffer, _DLENGTH_ * 3 + sizeof (unsigned long) ); + HASHGetDigest( &context, (unsigned char*)buffer ); + #endif + return 1; +} + + +// +int ACSign_Compare( + void* decrypto, // ACSign_Decryptȍo + void* digest // ACSign_Digest̏o + ) +{ + unsigned char* ptrA = (unsigned char*)decrypto; + unsigned char* ptrB = (unsigned char*)digest; + int loop; + int test = 1; + + if ( !decrypto ) return 0; + if ( !digest ) return 0; + + #if defined( RSA_ENC_DEC ) + for ( loop = 0; loop < _DLENGTH_ * 4; loop++ ) + #else + for ( loop = 0; loop < _DLENGTH_ * 1; loop++ ) + #endif + { + if ( *ptrA++ != *ptrB++ ) + { + test = 0; + break; + } + } + return test; +} + + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/acsign_util.c b/build/libraries_sysmenu/acsign/ARM9/src/acsign_util.c new file mode 100644 index 0000000..ccda052 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/acsign_util.c @@ -0,0 +1,111 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include + +#define AUTH_KEY_BUFFER_LEN 128 +#define MB_AUTH_SIGN_SIZE (128) /* digital sign size */ + + +typedef struct MbAuthCode +{ + char magic_code[2]; // }WbNio[ + u16 version; // o[W + u8 sign[MB_AUTH_SIGN_SIZE]; // + u32 serial_number; // VAԍ +} MbAuthCode; // 16byte + + + +static u8 key_buffer[AUTH_KEY_BUFFER_LEN] = { + 0x9E,0xC1,0xCC,0xC0,0x4A,0x6B,0xD0,0xA0,0x6D,0x62,0xED,0x5F,0x15,0x67,0x87,0x12, + 0xE6,0xF4,0x77,0x1F,0xD8,0x5C,0x81,0xCE,0x0C,0xD0,0x22,0x31,0xF5,0x89,0x08,0xF5, + 0xBE,0x04,0xCB,0xC1,0x4F,0x63,0xD9,0x5A,0x98,0xFF,0xEB,0x36,0x0F,0x9C,0x5D,0xAD, + 0x15,0xB9,0x99,0xFB,0xC6,0x86,0x2C,0x0A,0x0C,0xFC,0xE6,0x86,0x03,0x60,0xD4,0x87, + 0x28,0xD5,0x66,0x42,0x9C,0xF7,0x04,0x14,0x4E,0x6F,0x73,0x20,0xC3,0x3E,0x3F,0xF5, + 0x82,0x2E,0x78,0x18,0xD6,0xCD,0xD5,0xC2,0xDC,0xAA,0x1D,0x34,0x91,0xEC,0x99,0xC9, + 0xF7,0xBF,0xBF,0xA0,0x0E,0x1E,0xF0,0x25,0xF8,0x66,0x17,0x54,0x34,0x28,0x2D,0x28, + 0xA3,0xAE,0xF0,0xA9,0xFA,0x3A,0x70,0x56,0xD2,0x34,0xA9,0xC5,0x9E,0x5D,0xF5,0xE1 +}; + + +int ACSignDecrpto(void *output_buffer, MBDownloadFileInfo *download_file_info_buf) +{ + return ACSign_Decrypto(output_buffer, + ((MbAuthCode *)(download_file_info_buf->auth_code))->sign, + key_buffer); +} + + +int ACSignDigest(void *input_buffer, MBDownloadFileInfo *download_file_info_buf) +{ + int ret_code; + u8 digest_output_buffer[AUTH_BUFFER_LEN]; + + ret_code = ACSign_Digest((void *)digest_output_buffer, // o͗̈ 20 Bytes + (void *)(download_file_info_buf->seg[0].recv_addr), + (void *)(download_file_info_buf->seg[1].recv_addr), + (int)(download_file_info_buf->seg[1].size), + (void *)(download_file_info_buf->seg[2].recv_addr), + (int)(download_file_info_buf->seg[2].size), + ((MbAuthCode *)(download_file_info_buf)->auth_code)->serial_number // serial_number + ); + if( ret_code == 0 ) + { + return ret_code; // failure + } + + return ACSign_Compare( + input_buffer, // ACSign_Decryptȍo + (void*)digest_output_buffer // ACSign_Digest̏o + ); +} + +#if 0 +void* doAlloc( int size ) +{ + OSIntrMode nOSIntrMode; + void* alloc = NULL; + + nOSIntrMode = OS_DisableInterrupts( ); + alloc = OS_Alloc( size ); + (void)OS_RestoreInterrupts( nOSIntrMode ); + return alloc; +} + +void doFree( void* adrs ) +{ + OSIntrMode nOSIntrMode; + + nOSIntrMode = OS_DisableInterrupts( ); + OS_Free( adrs ); + (void)OS_RestoreInterrupts( nOSIntrMode ); +} + +void* doMemset( void* adrs, int val, int cnt ) +{ + return memset( adrs, val, cnt ); +} + +void* doMemcpy( void* dst, void* src, int cnt ) +{ + return memcpy( dst, src, cnt ); +} + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_add.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_add.c new file mode 100644 index 0000000..7b36c8b --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_add.c @@ -0,0 +1,320 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +/** + * @file bn_add.c + * @brief BIGNUM addition and subtraction functions + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_ADD +#define SPLIT_BN_UADD +#define SPLIT_BN_USUB +#define SPLIT_BN_SUB +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_ADD +/* r can == a or b */ +int BN_add(r, a, b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + BIGNUM *tmp; + + bn_check_top(a); + bn_check_top(b); + + /* a + b a+b + * a + -b a-b + * -a + b b-a + * -a + -b -(a+b) + */ + if (a->neg ^ b->neg) + { + /* only one is negative */ + if (a->neg) + { tmp=a; a=b; b=tmp; } + + /* we are now a - b */ + + if (BN_ucmp(a,b) < 0) + { + if (!BN_usub(r,b,a)) return(0); + r->neg=1; + } + else + { + if (!BN_usub(r,a,b)) return(0); + r->neg=0; + } + return(1); + } + + if (a->neg) /* both are neg */ + r->neg=1; + else + r->neg=0; + + if (!BN_uadd(r,a,b)) return(0); + return(1); + } +#endif + +#ifdef SPLIT_BN_UADD +/* unsigned add of b to a, r must be large enough */ +int BN_uadd(r,a,b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + register int i; + int max,min; + BN_ULONG *ap,*bp,*rp,carry,t1; + BIGNUM *tmp; + + bn_check_top(a); + bn_check_top(b); + + if (a->top < b->top) + { tmp=a; a=b; b=tmp; } + max=a->top; + min=b->top; + + if (bn_wexpand(r,max+1) == NULL) + return(0); + + r->top=max; + + + ap=a->d; + bp=b->d; + rp=r->d; + carry=0; + + carry=bn_add_words(rp,ap,bp,min); + rp+=min; + ap+=min; + bp+=min; + i=min; + + if (carry) + { + while (i < max) + { + i++; + t1= *(ap++); + if ((*(rp++)=(t1+1)&BN_MASK2) >= t1) + { + carry=0; + break; + } + } + if ((i >= max) && carry) + { + *(rp++)=1; + r->top++; + } + } + if (rp != ap) + { + for (; ib from a + * @param r result of subtraction + * @param a pointer to a BIGNUM + * @param b pointer to a BIGNUM + * @pre a must be larger than b + * @return 1 on success, 0 on failure + * @todo On next IRIX port check the validity of IRIX_CC_BUG. + */ +#ifdef SPLIT_BN_USUB +int BN_usub(r, a, b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + int max,min; + register BN_ULONG t1,t2,*ap,*bp,*rp; + int i,carry; +#if defined(IRIX_CC_BUG) && !defined(LINT) + int dummy; +#endif + + bn_check_top(a); + bn_check_top(b); + + /* + * check for pre-condition violation + */ + if (a->top < b->top) + { +#ifndef NO_ERR + BNerr(BN_F_BN_USUB,BN_R_ARG2_LT_ARG3); +#endif + return(0); + } + + max=a->top; + min=b->top; + if (bn_wexpand(r,max) == NULL) return(0); + + ap=a->d; + bp=b->d; + rp=r->d; + + /* + * perform the subtraction and see if we + * have a (final) carry + */ + carry=0; + for (i=0; i t2) break; + } + } + + if (rp != ap) + { +#ifdef BN_LIBRARY_SMALL + Memcpy(rp,ap,sizeof(*rp)*(max-i)); +#else /* BN_LIBRARY_SMALL */ + for (;;) + { + if (i++ >= max) break; + rp[0]=ap[0]; + if (i++ >= max) break; + rp[1]=ap[1]; + if (i++ >= max) break; + rp[2]=ap[2]; + if (i++ >= max) break; + rp[3]=ap[3]; + rp+=4; + ap+=4; + } +#endif /* BN_LIBRARY_SMALL */ + } + + r->top=max; + bn_fix_top(r); + return(1); + } +#endif + +#ifdef SPLIT_BN_SUB +int BN_sub(r, a, b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + int max; + int add=0,neg=0; + BIGNUM *tmp; + + bn_check_top(a); + bn_check_top(b); + + /* a - b a-b + * a - -b a+b + * -a - b -(a+b) + * -a - -b b-a + */ + if (a->neg) + { + if (b->neg) + { tmp=a; a=b; b=tmp; } + else + { add=1; neg=1; } + } + else + { + if (b->neg) { add=1; neg=0; } + } + + if (add) + { + if (!BN_uadd(r,a,b)) return(0); + r->neg=neg; + return(1); + } + + /* We are actually doing a - b */ + + max=(a->top > b->top)?a->top:b->top; + if (bn_wexpand(r,max) == NULL) return(0); + if (BN_ucmp(a,b) < 0) + { + if (!BN_usub(r,b,a)) return(0); + r->neg=1; + } + else + { + if (!BN_usub(r,a,b)) return(0); + r->neg=0; + } + return(1); + } +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_asm.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_asm.c new file mode 100644 index 0000000..64efa61 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_asm.c @@ -0,0 +1,525 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef OPT_BN_ASM + +#define BN_MUL_ADD_WORDS + +#ifndef BN_MUL_WORDS +#define BN_MUL_WORDS +#endif + +#ifndef BN_SQR_WORDS +#define BN_SQR_WORDS +#endif + +#ifndef BN_ADD_WORDS +#define BN_ADD_WORDS +#endif + +#ifndef BN_SUB_WORDS +#define BN_SUB_WORDS +#endif + +#endif + + +#include "bn_lcl.h" + +#ifdef BN_LLONG + +/* + * bn_mul_add_words + * + * for(i=0;i=0; i--) + fprintf(stderr,BN_HEX_FMT,ap[i]); + fprintf(stderr,"*"); + fprintf(stderr,BN_HEX_FMT,w); + fprintf(stderr,"+"); + for (i=num-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,rp[i]); +#endif + + for (;;) + { + mul_add(rp[0],ap[0],w,c1); + if (--num == 0) break; + mul_add(rp[1],ap[1],w,c1); + if (--num == 0) break; + mul_add(rp[2],ap[2],w,c1); + if (--num == 0) break; + mul_add(rp[3],ap[3],w,c1); + if (--num == 0) break; + ap+=4; + rp+=4; + } + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"-"); + fprintf(stderr,BN_HEX_FMT,c1); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,rp[i]); + fprintf(stderr,"\n"); + } +#endif + return(c1); + } +#endif + +#ifdef BN_MUL_WORDS +BN_ULONG bn_mul_words(rp,ap,num,w) +BN_ULONG *rp,*ap; +int num; +BN_ULONG w; + { + BN_ULONG c1=0; + + bn_check_num(num); + if (num <= 0) return(c1); + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=num; + + for (i=num-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,ap[i]); + fprintf(stderr,"*"); + fprintf(stderr,BN_HEX_FMT,w); +#endif + + for (;;) + { + mul(rp[0],ap[0],w,c1); + if (--num == 0) break; + mul(rp[1],ap[1],w,c1); + if (--num == 0) break; + mul(rp[2],ap[2],w,c1); + if (--num == 0) break; + mul(rp[3],ap[3],w,c1); + if (--num == 0) break; + ap+=4; + rp+=4; + } + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"-"); + fprintf(stderr,BN_HEX_FMT,c1); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,rp[i]); + fprintf(stderr,"\n"); + } +#endif + return(c1); + } +#endif + +#ifdef BN_SQR_WORDS +void bn_sqr_words(r,a,n) +BN_ULONG *r,*a; +int n; + { + bn_check_num(n); + if (n <= 0) return; + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=n; + + for (i=n-1; i>=0; i--) + { + fprintf(stderr,BN_HEX_FMT,a[i]); + if (i != 0) + fprintf(stderr,"^2*2^%X+",i*2*BN_BITS2); + else + fprintf(stderr,"^2"); + } +#endif + + for (;;) + { + BN_ULLONG t; + + t=(BN_ULLONG)(a[0])*(a[0]); + r[0]=Lw(t); r[1]=Hw(t); + if (--n == 0) break; + + t=(BN_ULLONG)(a[1])*(a[1]); + r[2]=Lw(t); r[3]=Hw(t); + if (--n == 0) break; + + t=(BN_ULLONG)(a[2])*(a[2]); + r[4]=Lw(t); r[5]=Hw(t); + if (--n == 0) break; + + t=(BN_ULLONG)(a[3])*(a[3]); + r[6]=Lw(t); r[7]=Hw(t); + if (--n == 0) break; + + a+=4; + r+=8; + } +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + + fprintf(stderr,"-"); + for (i=nn+nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,r[i]); + fprintf(stderr,"\n"); + } +#endif + } +#endif + +#else + +#ifdef BN_MUL_ADD_WORDS + +BN_ULONG bn_mul_add_words(rp,ap,num,w) +BN_ULONG *rp,*ap; +int num; +BN_ULONG w; + { + BN_ULONG c=0; + BN_ULONG bl,bh,b_hl; + + bn_check_num(num); + if (num <= 0) return((BN_ULONG)0); + + bl=LBITS(w); + bh=HBITS(w); + b_hl=bh-bl; +/* +{ int i,nnum=num; +BN_ULONG *rrp=rp; +for (i=num-1; i>=0; i--) printf("%02X",rp[i]); +printf("+"); +for (i=num-1; i>=0; i--) printf("%02X",ap[i]); +printf("*%02X - ",w); +*/ + for (;;) + { + mul_add(rp[0],ap[0],bl,bh,b_hl,c); + if (--num == 0) break; + mul_add(rp[1],ap[1],bl,bh,b_hl,c); + if (--num == 0) break; + mul_add(rp[2],ap[2],bl,bh,b_hl,c); + if (--num == 0) break; + mul_add(rp[3],ap[3],bl,bh,b_hl,c); + if (--num == 0) break; + ap+=4; + rp+=4; + } + +/* +printf("%02X",c); +for (i=nnum-1; i>=0; i--) printf("%02X",rrp[i]); +printf("\n"); +} +*/ + return(c); + } + +#endif + +#ifdef BN_MUL_WORDS +BN_ULONG bn_mul_words(rp,ap,num,w) +BN_ULONG *rp,*ap; +int num; +BN_ULONG w; + { + BN_ULONG carry=0; + BN_ULONG bl,bh; + + bn_check_num(num); + if (num <= 0) return((BN_ULONG)0); + + bl=LBITS(w); + bh=HBITS(w); + + for (;;) + { + mul(rp[0],ap[0],bl,bh,carry); + if (--num == 0) break; + mul(rp[1],ap[1],bl,bh,carry); + if (--num == 0) break; + mul(rp[2],ap[2],bl,bh,carry); + if (--num == 0) break; + mul(rp[3],ap[3],bl,bh,carry); + if (--num == 0) break; + ap+=4; + rp+=4; + } + return(carry); + } +#endif + +#ifdef BN_SQR_WORDS +void bn_sqr_words(r,a,n) +BN_ULONG *r,*a; +int n; + { + bn_check_num(n); + if (n <= 0) return; + for (;;) + { + sqr64(r[0],r[1],a[0]); + if (--n == 0) break; + + sqr64(r[2],r[3],a[1]); + if (--n == 0) break; + + sqr64(r[4],r[5],a[2]); + if (--n == 0) break; + + sqr64(r[6],r[7],a[3]); + if (--n == 0) break; + + a+=4; + r+=8; + } + } +#endif + +#endif + +#ifdef BN_ADD_WORDS +#ifdef BN_LLONG +BN_ULONG bn_add_words(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { + BN_ULLONG ll=0; + + bn_check_num(n); + if (n <= 0) return((BN_ULONG)0); + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=n; + + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,a[i]); + fprintf(stderr,"+"); + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,b[i]); +#endif + + for (;;) + { + ll+=(BN_ULLONG)a[0]+b[0]; + r[0]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + ll+=(BN_ULLONG)a[1]+b[1]; + r[1]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + ll+=(BN_ULLONG)a[2]+b[2]; + r[2]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + ll+=(BN_ULLONG)a[3]+b[3]; + r[3]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + a+=4; + b+=4; + r+=4; + } +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"-"); + fprintf(stderr,BN_HEX_FMT,(BN_ULONG)ll); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,r[i]); + fprintf(stderr,"\n"); + } +#endif + return((BN_ULONG)ll); + } +#else +BN_ULONG bn_add_words(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { + BN_ULONG c,l,t; + + bn_check_num(n); + if (n <= 0) return((BN_ULONG)0); + + c=0; + for (;;) + { + t=a[0]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[0])&BN_MASK2; + c+=(l < t); + r[0]=l; + if (--n <= 0) break; + + t=a[1]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[1])&BN_MASK2; + c+=(l < t); + r[1]=l; + if (--n <= 0) break; + + t=a[2]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[2])&BN_MASK2; + c+=(l < t); + r[2]=l; + if (--n <= 0) break; + + t=a[3]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[3])&BN_MASK2; + c+=(l < t); + r[3]=l; + if (--n <= 0) break; + + a+=4; + b+=4; + r+=4; + } + + return((BN_ULONG)c); + } +#endif +#endif + +#ifdef BN_SUB_WORDS +BN_ULONG bn_sub_words(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { + BN_ULONG c,t1,t2; + + bn_check_num(n); + if (n <= 0) return((BN_ULONG)0); + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=n; + + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,a[i]); + fprintf(stderr,"-"); + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,b[i]); +#endif + + c=0; + for (;;) + { + t1=a[0]; t2=b[0]; + r[0]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + t1=a[1]; t2=b[1]; + r[1]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + t1=a[2]; t2=b[2]; + r[2]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + t1=a[3]; t2=b[3]; + r[3]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + a+=4; + b+=4; + r+=4; + } + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"- "); + if (c) fprintf(stderr,"-"); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,r[i]); + fprintf(stderr,"\n"); + } +#endif + return(c); + } +#endif + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_comba.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_comba.c new file mode 100644 index 0000000..462c8f4 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_comba.c @@ -0,0 +1,450 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MUL_COMBA8 +#define SPLIT_BN_MUL_COMBA4 +#define SPLIT_BN_SQR_COMBA8 +#define SPLIT_BN_SQR_COMBA4 +#endif /* NO_SPLIT */ + +#ifndef OPT_BN_ASM +/* #if 1 */ + +#ifdef BN_LLONG +#define mul_add_c(a,b,c0,c1,c2) \ + t=(BN_ULLONG)a*b; \ + t1=(BN_ULONG)Lw(t); \ + t2=(BN_ULONG)Hw(t); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define mul_add_c2(a,b,c0,c1,c2) \ + t=(BN_ULLONG)a*b; \ + tt=(t+t)&BN_MASK; \ + if (tt < t) c2++; \ + t1=(BN_ULONG)Lw(tt); \ + t2=(BN_ULONG)Hw(tt); \ + c0=(c0+t1)&BN_MASK2; \ + if ((c0 < t1) && (((++t2)&BN_MASK2) == 0)) c2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c(a,i,c0,c1,c2) \ + t=(BN_ULLONG)a[i]*a[i]; \ + t1=(BN_ULONG)Lw(t); \ + t2=(BN_ULONG)Hw(t); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c2(a,i,j,c0,c1,c2) \ + mul_add_c2((a)[i],(a)[j],c0,c1,c2) +#else +#define mul_add_c(a,b,c0,c1,c2) \ + t1=LBITS(a); t2=HBITS(a); \ + bl=LBITS(b); bh=HBITS(b); \ + mul64(t1,t2,bl,bh); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define mul_add_c2(a,b,c0,c1,c2) \ + t1=LBITS(a); t2=HBITS(a); \ + bl=LBITS(b); bh=HBITS(b); \ + mul64(t1,t2,bl,bh); \ + if (t2 & BN_TBIT) c2++; \ + t2=(t2+t2)&BN_MASK2; \ + if (t1 & BN_TBIT) t2++; \ + t1=(t1+t1)&BN_MASK2; \ + c0=(c0+t1)&BN_MASK2; \ + if ((c0 < t1) && (((++t2)&BN_MASK2) == 0)) c2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c(a,i,c0,c1,c2) \ + sqr64(t1,t2,(a)[i]); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c2(a,i,j,c0,c1,c2) \ + mul_add_c2((a)[i],(a)[j],c0,c1,c2) +#endif + +#if defined(BN_MUL_COMBA) + +#ifdef SPLIT_BN_MUL_COMBA8 +#undef bn_mul_comba8 +void bn_mul_comba8(r,a,b) +BN_ULONG *r,*a,*b; + { +#ifdef BN_LLONG + BN_ULLONG t; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + mul_add_c(a[0],b[0],c1,c2,c3); + r[0]=c1; + c1=0; + mul_add_c(a[0],b[1],c2,c3,c1); + mul_add_c(a[1],b[0],c2,c3,c1); + r[1]=c2; + c2=0; + mul_add_c(a[2],b[0],c3,c1,c2); + mul_add_c(a[1],b[1],c3,c1,c2); + mul_add_c(a[0],b[2],c3,c1,c2); + r[2]=c3; + c3=0; + mul_add_c(a[0],b[3],c1,c2,c3); + mul_add_c(a[1],b[2],c1,c2,c3); + mul_add_c(a[2],b[1],c1,c2,c3); + mul_add_c(a[3],b[0],c1,c2,c3); + r[3]=c1; + c1=0; + mul_add_c(a[4],b[0],c2,c3,c1); + mul_add_c(a[3],b[1],c2,c3,c1); + mul_add_c(a[2],b[2],c2,c3,c1); + mul_add_c(a[1],b[3],c2,c3,c1); + mul_add_c(a[0],b[4],c2,c3,c1); + r[4]=c2; + c2=0; + mul_add_c(a[0],b[5],c3,c1,c2); + mul_add_c(a[1],b[4],c3,c1,c2); + mul_add_c(a[2],b[3],c3,c1,c2); + mul_add_c(a[3],b[2],c3,c1,c2); + mul_add_c(a[4],b[1],c3,c1,c2); + mul_add_c(a[5],b[0],c3,c1,c2); + r[5]=c3; + c3=0; + mul_add_c(a[6],b[0],c1,c2,c3); + mul_add_c(a[5],b[1],c1,c2,c3); + mul_add_c(a[4],b[2],c1,c2,c3); + mul_add_c(a[3],b[3],c1,c2,c3); + mul_add_c(a[2],b[4],c1,c2,c3); + mul_add_c(a[1],b[5],c1,c2,c3); + mul_add_c(a[0],b[6],c1,c2,c3); + r[6]=c1; + c1=0; + mul_add_c(a[0],b[7],c2,c3,c1); + mul_add_c(a[1],b[6],c2,c3,c1); + mul_add_c(a[2],b[5],c2,c3,c1); + mul_add_c(a[3],b[4],c2,c3,c1); + mul_add_c(a[4],b[3],c2,c3,c1); + mul_add_c(a[5],b[2],c2,c3,c1); + mul_add_c(a[6],b[1],c2,c3,c1); + mul_add_c(a[7],b[0],c2,c3,c1); + r[7]=c2; + c2=0; + mul_add_c(a[7],b[1],c3,c1,c2); + mul_add_c(a[6],b[2],c3,c1,c2); + mul_add_c(a[5],b[3],c3,c1,c2); + mul_add_c(a[4],b[4],c3,c1,c2); + mul_add_c(a[3],b[5],c3,c1,c2); + mul_add_c(a[2],b[6],c3,c1,c2); + mul_add_c(a[1],b[7],c3,c1,c2); + r[8]=c3; + c3=0; + mul_add_c(a[2],b[7],c1,c2,c3); + mul_add_c(a[3],b[6],c1,c2,c3); + mul_add_c(a[4],b[5],c1,c2,c3); + mul_add_c(a[5],b[4],c1,c2,c3); + mul_add_c(a[6],b[3],c1,c2,c3); + mul_add_c(a[7],b[2],c1,c2,c3); + r[9]=c1; + c1=0; + mul_add_c(a[7],b[3],c2,c3,c1); + mul_add_c(a[6],b[4],c2,c3,c1); + mul_add_c(a[5],b[5],c2,c3,c1); + mul_add_c(a[4],b[6],c2,c3,c1); + mul_add_c(a[3],b[7],c2,c3,c1); + r[10]=c2; + c2=0; + mul_add_c(a[4],b[7],c3,c1,c2); + mul_add_c(a[5],b[6],c3,c1,c2); + mul_add_c(a[6],b[5],c3,c1,c2); + mul_add_c(a[7],b[4],c3,c1,c2); + r[11]=c3; + c3=0; + mul_add_c(a[7],b[5],c1,c2,c3); + mul_add_c(a[6],b[6],c1,c2,c3); + mul_add_c(a[5],b[7],c1,c2,c3); + r[12]=c1; + c1=0; + mul_add_c(a[6],b[7],c2,c3,c1); + mul_add_c(a[7],b[6],c2,c3,c1); + r[13]=c2; + c2=0; + mul_add_c(a[7],b[7],c3,c1,c2); + r[14]=c3; + r[15]=c1; + } +#endif + +#ifdef SPLIT_BN_MUL_COMBA4 +#undef bn_mul_comba4 +void bn_mul_comba4(r,a,b) +BN_ULONG *r,*a,*b; + { +#ifdef BN_LLONG + BN_ULLONG t; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + mul_add_c(a[0],b[0],c1,c2,c3); + r[0]=c1; + c1=0; + mul_add_c(a[0],b[1],c2,c3,c1); + mul_add_c(a[1],b[0],c2,c3,c1); + r[1]=c2; + c2=0; + mul_add_c(a[2],b[0],c3,c1,c2); + mul_add_c(a[1],b[1],c3,c1,c2); + mul_add_c(a[0],b[2],c3,c1,c2); + r[2]=c3; + c3=0; + mul_add_c(a[0],b[3],c1,c2,c3); + mul_add_c(a[1],b[2],c1,c2,c3); + mul_add_c(a[2],b[1],c1,c2,c3); + mul_add_c(a[3],b[0],c1,c2,c3); + r[3]=c1; + c1=0; + mul_add_c(a[3],b[1],c2,c3,c1); + mul_add_c(a[2],b[2],c2,c3,c1); + mul_add_c(a[1],b[3],c2,c3,c1); + r[4]=c2; + c2=0; + mul_add_c(a[2],b[3],c3,c1,c2); + mul_add_c(a[3],b[2],c3,c1,c2); + r[5]=c3; + c3=0; + mul_add_c(a[3],b[3],c1,c2,c3); + r[6]=c1; + r[7]=c2; + } +#endif + +#else + +#ifdef SPLIT_BN_MUL_COMBA4 +#undef bn_mul_comba4 +void bn_mul_comba4(r,a,b) +BN_ULONG *r,*a,*b; + { + r[4]=bn_mul_words( &(r[0]),a,4,b[0]); + r[5]=bn_mul_add_words(&(r[1]),a,4,b[1]); + r[6]=bn_mul_add_words(&(r[2]),a,4,b[2]); + r[7]=bn_mul_add_words(&(r[3]),a,4,b[3]); + } +#endif + +#ifdef SPLIT_BN_MUL_COMBA8 +#undef bn_mul_comba8 +void bn_mul_comba8(r,a,b) +BN_ULONG *r,*a,*b; + { + r[ 8]=bn_mul_words( &(r[0]),a,8,b[0]); + r[ 9]=bn_mul_add_words(&(r[1]),a,8,b[1]); + r[10]=bn_mul_add_words(&(r[2]),a,8,b[2]); + r[11]=bn_mul_add_words(&(r[3]),a,8,b[3]); + r[12]=bn_mul_add_words(&(r[4]),a,8,b[4]); + r[13]=bn_mul_add_words(&(r[5]),a,8,b[5]); + r[14]=bn_mul_add_words(&(r[6]),a,8,b[6]); + r[15]=bn_mul_add_words(&(r[7]),a,8,b[7]); + } +#endif + +#endif /* BN_MUL_COMBA */ + +#ifdef BN_SQR_COMBA + +#ifdef SPLIT_BN_SQR_COMBA8 +#undef bn_sqr_comba8 +void bn_sqr_comba8(r,a) +BN_ULONG *r,*a; + { +#ifdef BN_LLONG + BN_ULLONG t,tt; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + sqr_add_c(a,0,c1,c2,c3); + r[0]=c1; + c1=0; + sqr_add_c2(a,1,0,c2,c3,c1); + r[1]=c2; + c2=0; + sqr_add_c(a,1,c3,c1,c2); + sqr_add_c2(a,2,0,c3,c1,c2); + r[2]=c3; + c3=0; + sqr_add_c2(a,3,0,c1,c2,c3); + sqr_add_c2(a,2,1,c1,c2,c3); + r[3]=c1; + c1=0; + sqr_add_c(a,2,c2,c3,c1); + sqr_add_c2(a,3,1,c2,c3,c1); + sqr_add_c2(a,4,0,c2,c3,c1); + r[4]=c2; + c2=0; + sqr_add_c2(a,5,0,c3,c1,c2); + sqr_add_c2(a,4,1,c3,c1,c2); + sqr_add_c2(a,3,2,c3,c1,c2); + r[5]=c3; + c3=0; + sqr_add_c(a,3,c1,c2,c3); + sqr_add_c2(a,4,2,c1,c2,c3); + sqr_add_c2(a,5,1,c1,c2,c3); + sqr_add_c2(a,6,0,c1,c2,c3); + r[6]=c1; + c1=0; + sqr_add_c2(a,7,0,c2,c3,c1); + sqr_add_c2(a,6,1,c2,c3,c1); + sqr_add_c2(a,5,2,c2,c3,c1); + sqr_add_c2(a,4,3,c2,c3,c1); + r[7]=c2; + c2=0; + sqr_add_c(a,4,c3,c1,c2); + sqr_add_c2(a,5,3,c3,c1,c2); + sqr_add_c2(a,6,2,c3,c1,c2); + sqr_add_c2(a,7,1,c3,c1,c2); + r[8]=c3; + c3=0; + sqr_add_c2(a,7,2,c1,c2,c3); + sqr_add_c2(a,6,3,c1,c2,c3); + sqr_add_c2(a,5,4,c1,c2,c3); + r[9]=c1; + c1=0; + sqr_add_c(a,5,c2,c3,c1); + sqr_add_c2(a,6,4,c2,c3,c1); + sqr_add_c2(a,7,3,c2,c3,c1); + r[10]=c2; + c2=0; + sqr_add_c2(a,7,4,c3,c1,c2); + sqr_add_c2(a,6,5,c3,c1,c2); + r[11]=c3; + c3=0; + sqr_add_c(a,6,c1,c2,c3); + sqr_add_c2(a,7,5,c1,c2,c3); + r[12]=c1; + c1=0; + sqr_add_c2(a,7,6,c2,c3,c1); + r[13]=c2; + c2=0; + sqr_add_c(a,7,c3,c1,c2); + r[14]=c3; + r[15]=c1; + } +#endif + +#ifdef SPLIT_BN_SQR_COMBA4 +#undef bn_sqr_comba4 +void bn_sqr_comba4(r,a) +BN_ULONG *r,*a; + { +#ifdef BN_LLONG + BN_ULLONG t,tt; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + sqr_add_c(a,0,c1,c2,c3); + r[0]=c1; + c1=0; + sqr_add_c2(a,1,0,c2,c3,c1); + r[1]=c2; + c2=0; + sqr_add_c(a,1,c3,c1,c2); + sqr_add_c2(a,2,0,c3,c1,c2); + r[2]=c3; + c3=0; + sqr_add_c2(a,3,0,c1,c2,c3); + sqr_add_c2(a,2,1,c1,c2,c3); + r[3]=c1; + c1=0; + sqr_add_c(a,2,c2,c3,c1); + sqr_add_c2(a,3,1,c2,c3,c1); + r[4]=c2; + c2=0; + sqr_add_c2(a,3,2,c3,c1,c2); + r[5]=c3; + c3=0; + sqr_add_c(a,3,c1,c2,c3); + r[6]=c1; + r[7]=c2; + } +#endif +#else + +#ifdef SPLIT_BN_SQR_COMBA4 +/* hmm... is it faster just to do a multiply? */ +#undef bn_sqr_comba4 +void bn_sqr_comba4(r,a) +BN_ULONG *r,*a; + { + BN_ULONG t[8]; + bn_sqr_normal(r,a,4,t); + } +#endif + +#ifdef SPLIT_BN_SQR_COMBA8 +#undef bn_sqr_comba8 +void bn_sqr_comba8(r,a) +BN_ULONG *r,*a; + { + BN_ULONG t[16]; + bn_sqr_normal(r,a,8,t); + } +#endif + +#endif + +#endif /* OPT_BN_ASM */ + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_div.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_div.c new file mode 100644 index 0000000..7036d19 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_div.c @@ -0,0 +1,381 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file bn_div.c + * @brief Division and modulus functions + */ +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_DIV +#define SPLIT_BN_MOD +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_DIV +/* The old slow way */ +#ifdef OLD_BN_DIVISION +int BN_div(dv, rem, m, d,ctx) +BIGNUM *dv; +BIGNUM *rem; +BIGNUM *m; +BIGNUM *d; +BN_CTX *ctx; + { + int i,nm,nd; + BIGNUM *D; + + bn_check_top(m); + bn_check_top(d); + if (BN_is_zero(d)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_DIV,BN_R_DIV_BY_ZERO); +#endif + return(0); + } + + if (BN_ucmp(m,d) < 0) + { + if (rem != NULL) + { if (BN_copy(rem,m) == NULL) return(0); } + if (dv != NULL) BN_zero(dv); + return(1); + } + + D= &(ctx->bn[ctx->tos]); + if (dv == NULL) dv= &(ctx->bn[ctx->tos+1]); + if (rem == NULL) rem= &(ctx->bn[ctx->tos+2]); + + nd=BN_num_bits(d); + nm=BN_num_bits(m); + if (BN_copy(D,d) == NULL) return(0); + if (BN_copy(rem,m) == NULL) return(0); + + /* The next 2 are needed so we can do a dv->d[0]|=1 later + * since BN_lshift1 will only work once there is a value + */ + BN_zero(dv); + bn_wexpand(dv,1); + dv->top=1; + + if (!BN_lshift(D,D,nm-nd)) return(0); + for (i=nm-nd; i>=0; i--) + { + if (!BN_lshift1(dv,dv)) return(0); + if (BN_ucmp(rem,D) >= 0) + { + dv->d[0]|=1; + if (!BN_usub(rem,rem,D)) return(0); + } +/* CAN IMPROVE (and have now :=) */ + if (!BN_rshift1(D,D)) return(0); + } + rem->neg=BN_is_zero(rem)?0:m->neg; + dv->neg=m->neg^d->neg; + return(1); + } + +#else +/** + * Performs Big number division + * + * @param dv [In] division + * @param rm [Out] remainder + * @param num [In] number + * @param divisor [In] divisor + * @param ctx [In] Temporary data storage + * + * @todo add more comments to this function + */ +int BN_div(BIGNUM *dv, BIGNUM *rm, BIGNUM *num, BIGNUM *divisor, BN_CTX *ctx) + { + int norm_shift,i,j,loop; + BIGNUM *tmp,wnum,*snum,*sdiv,*res; + BN_ULONG *resp,*wnump; + BN_ULONG d0,d1; + int num_n,div_n; + + bn_check_top(num); + bn_check_top(divisor); + + if (BN_is_zero(divisor)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_DIV,BN_R_DIV_BY_ZERO); +#endif + return(0); + } + + if (BN_ucmp(num,divisor) < 0) + { + if (rm != NULL) + { if (BN_copy(rm,num) == NULL) return(0); } + if (dv != NULL) (void)BN_zero(dv); + return(1); + } + + tmp= &(ctx->bn[ctx->tos]); + tmp->neg=0; + snum= &(ctx->bn[ctx->tos+1]); + sdiv= &(ctx->bn[ctx->tos+2]); + if (dv == NULL) + res= &(ctx->bn[ctx->tos+3]); + else res=dv; + + /* First we normalise the numbers */ + norm_shift=BN_BITS2-((BN_num_bits(divisor))%BN_BITS2); + if (!BN_lshift(sdiv,divisor,norm_shift)) return(0); + sdiv->neg=0; + norm_shift+=BN_BITS2; + if (!BN_lshift(snum,num,norm_shift)) return(0); + snum->neg=0; + div_n=sdiv->top; + num_n=snum->top; + loop=num_n-div_n; + + /* Lets setup a 'window' into snum + * This is the part that corresponds to the current + * 'area' being divided */ + BN_init(&wnum); + wnum.d= &(snum->d[loop]); + wnum.top= div_n; + wnum.max= snum->max+1; /* a bit of a lie */ + + /* Get the top 2 words of sdiv */ + /* i=sdiv->top; */ + d0=sdiv->d[div_n-1]; + d1=(div_n == 1)?0:sdiv->d[div_n-2]; + + /* pointer to the 'top' of snum */ + wnump= &(snum->d[num_n-1]); + + /* Setup to 'res' */ + if (!bn_wexpand(res,(loop+1))) goto err; + res->neg= (num->neg^divisor->neg); + res->top=loop; + resp= &(res->d[loop-1]); + + /* space for temp */ + if (!bn_wexpand(tmp,(div_n+1))) goto err; + + if (BN_ucmp(&wnum,sdiv) >= 0) + { + if (!BN_usub(&wnum,&wnum,sdiv)) goto err; + *resp=1; + res->d[res->top-1]=1; + } + else + res->top--; + resp--; + + for (i=0; i>BN_BITS2) || + (t2 <= ((BN_ULLONG)(rem< t1l) t3h++; + t3h=(t1h-t3h)&BN_MASK2; + + /*if ((t3>>BN_BITS2) || + (t2 <= ((t3<d,sdiv->d,div_n,q); + tmp->d[div_n]=l0; + for (j=div_n+1; j>0; j--) + if (tmp->d[j-1]) break; + tmp->top=j; + + j=wnum.top; +#ifdef BN_DEBUG + /* Sometimes this is 0 now (wnum.top is not). + * We need to look at this some time, I am quite + * sure it has no affect. + */ + bn_fix_top(&wnum); +#endif + (void)BN_sub(&wnum,&wnum,tmp); + + snum->top=snum->top+wnum.top-j; + + if (wnum.neg) + { + q--; + j=wnum.top; + (void)BN_add(&wnum,&wnum,sdiv); + snum->top+=wnum.top-j; + } + *(resp--)=q; + wnump--; + } + bn_fix_top(snum); + if (rm != NULL) + { + i=num->neg; /* just in case num == rm */ + if (BN_rshift(rm,snum,norm_shift) == 0) + return(0); + rm->neg=i; + } + return(1); +err: + return(0); + } +#endif +#endif + +#ifdef SPLIT_BN_MOD +/** + * Calculate the remainder where rem = m mod d + * + * @param rem [Out] Modulus result + * @param m [In] Base value + * @param d [In] Divisor + * @param ctx [In] BN_CTX for data space + * + * @pre variables are initialised and valid + * @post rem contained modulus + * + * @retval 1 success + * @retval 0 failure + * + * @note when BN_LIBRARY_SMALL define uses following algorithm + * otherwise calls through to BN_div + * + * @note m < d rem = m + * (length m = length of d) and (m > d) , rem = m - d + * alg otherwise + * let rem = m + * loop while rem > d + * let dv = shift left d, n bits to = length rem + * if dv > rem + * let dv = shift left d, n - 1 bits ( = length rem - 1) + * end if + * let rem = rem - dv; + * end loop + * + * @relates BN_div + */ +int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx) +{ +#ifdef BN_LIBRARY_SMALL + int nm,nd; + BIGNUM *dv, *dv2; + + /* if m < d , mod = m */ + if (BN_ucmp(m,d) < 0) + return((BN_copy(rem,m) == NULL)?0:1); + + dv= &(ctx->bn[ctx->tos]); + dv2 = &(ctx->bn[ctx->tos+1]); + + nm=BN_num_bits(m); + nd=BN_num_bits(d); + + /* if bits m = bits d and m >= d (from above) + * rem = m - d + */ + if(nm == nd) + { + BN_usub(rem, m, d); + goto end; + } + + if (BN_copy(rem, m) == NULL) + { + return 0; + } + + /* while the rem > d */ + while(BN_ucmp(rem,d) > 0) + { + nm=BN_num_bits(rem); + if(!BN_lshift(dv2,d,nm-nd)) + { + return(0); + } + + if(BN_ucmp(dv2, rem) >0) + { + if(!BN_lshift(dv2,d,nm-nd-1)) + { + return(0); + } + } + + BN_usub(rem,rem,dv2); + } +end: + return(1); +#else + return(BN_div(NULL,rem,m,d,ctx)); +#endif +} +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_ex_str.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_ex_str.c new file mode 100644 index 0000000..02e31d1 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_ex_str.c @@ -0,0 +1,453 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +#include "bn_lcl.h" + +const static unsigned char p2 []={0,8,1,1,1,1,1,0,0,0}; +const static unsigned char p4 []={0,8,1,1,1,4,1,0,0,0}; +const static unsigned char p16[]={0,8,1,1,1,16,1,0,0,0}; + +/* The following defines allow for redefinition of the window size + * of the exponent string at compile time, this affects the size + * of temporary data required in montgomery operations. + * Larger window sizes have more memory and are slightly faster + */ +#ifndef MAX_WIN_SIZE +#define MAX_WIN_SIZE 5 +#endif + +#if (MAX_WIN_SIZE == 6) +#define MAX_NUM_SIZE 16 +#endif + +#if (MAX_WIN_SIZE == 5) +#define MAX_NUM_SIZE 16 +#endif + +#if (MAX_WIN_SIZE == 4) +#define MAX_NUM_SIZE 8 +#endif + +#if (MAX_WIN_SIZE == 3) +#define MAX_NUM_SIZE 4 +#endif + +#ifndef MAX_NUM_SIZE +#define MAX_NUM_SIZE 16 +#endif + +/* This table is used to calculate how far to shift a window to find + * the next 1 bit within the window, for a given window size + * Comment next to each value represents window size, value of the window + * and the number of shifts to find the next 1 bit. + * where the value of the window is 0, the shift is the size of the window + * and thus may not necessary yield a 1 bit, but refreshes the window + */ +const static unsigned char shift[64]= + {6, /* window 6, bits 000000, shift 6 */ + 0, /* 6, bits 000001, shift 0 */ + 1, /* 6, bits 000010, shift 1 */ + 0, /* 6, bits 000011, shift 0 */ + 2, /* 6, bits 000100, shift 2 */ + 0, /* 6, bits 000101, shift 0 */ + 1, /* 6, bits 000110, shift 1 */ + 0, /* 6, bits 000111, shift 0 */ + 3, /* 6, bits 001000, shift 3 */ + 0, /* 6, bits 001001, shift 0 */ + 1, /* 6, bits 001010, shift 1 */ + 0, /* 6, bits 001011, shift 0 */ + 2, /* 6, bits 001100, shift 2 */ + 0, /* 6, bits 001101, shift 0 */ + 1, /* 6, bits 001110, shift 1 */ + 0, /* 6, bits 001111, shift 0 */ + 4, /* 6, bits 010000, shift 4 */ + 0, /* 6, bits 010001, shift 0 */ + 1, /* 6, bits 010010, shift 1 */ + 0, /* 6, bits 010011, shift 0 */ + 2, /* 6, bits 010100, shift 2 */ + 0, /* 6, bits 010101, shift 0 */ + 1, /* 6, bits 010110, shift 1 */ + 0, /* 6, bits 010111, shift 0 */ + 3, /* 6, bits 011000, shift 3 */ + 0, /* 6, bits 011001, shift 0 */ + 1, /* 6, bits 011010, shift 1 */ + 0, /* 6, bits 011011, shift 0 */ + 2, /* 6, bits 011100, shift 2 */ + 0, /* 6, bits 011101, shift 0 */ + 1, /* 6, bits 011110, shift 1 */ + 0, /* 6, bits 011111, shift 0 */ + 5, /* 6, bits 100000, shift 5 */ + /* also window 5, bits 00000, shift 5 */ + 0, /* 5 ,bits 00001, shift 0 */ + 1, /* 5 ,bits 00010, shift 1 */ + 0, /* 5 ,bits 00011, shift 0 */ + 2, /* 5 ,bits 00100, shift 2 */ + 0, /* 5 ,bits 00101, shift 0 */ + 1, /* 5 ,bits 00110, shift 1 */ + 0, /* 5 ,bits 00111, shift 0 */ + 3, /* 5 ,bits 01000, shift 3 */ + 0, /* 5 ,bits 01001, shift 0 */ + 1, /* 5 ,bits 01010, shift 1 */ + 0, /* 5 ,bits 01011, shift 0 */ + 2, /* 5 ,bits 01100, shift 2 */ + 0, /* 5 ,bits 01101, shift 0 */ + 1, /* 5 ,bits 01110, shift 1 */ + 0, /* 5 ,bits 01111, shift 0 */ + 4, /* 5 ,bits 10000, shift 1 */ + /* also window 4, bits 0000, shift 4 */ + 0, /* 4 ,bits 0001, shift 0 */ + 1, /* 4 ,bits 0010, shift 1 */ + 0, /* 4 ,bits 0011, shift 0 */ + 2, /* 4 ,bits 0100, shift 2 */ + 0, /* 4 ,bits 0101, shift 0 */ + 1, /* 4 ,bits 0110, shift 1 */ + 0, /* 4 ,bits 0111, shift 0 */ + 3, /* 4 ,bits 1000, shift 3 */ + /* also window 3, bits 000, shift 3 */ + 0, /* 3 ,bits 001, shift 0 */ + 1, /* 3 ,bits 010, shift 1 */ + 0, /* 3 ,bits 011, shift 0 */ + 2, /* 3 ,bits 100, shift 2 */ + 0, /* 3 ,bits 101, shift 0 */ + 1, /* 3 ,bits 110, shift 1 */ + 0 /* 3 ,bits 111, shift 0 */ + }; + +/* This table defines the starting point in the shift table for + * a particular window size + */ +const static unsigned char *shift_val[7]= + { + &(shift[63]), /* window 0 - unused */ + &(shift[62]), /* window 1 */ + &(shift[60]), /* window 2 - unused */ + &(shift[56]), /* window 3 */ + &(shift[48]), /* window 4 */ + &(shift[32]), /* window 5 */ + &(shift[ 0]), /* window 6 - unused */ + }; + +/** + * Calculates a Montgomery exponent string. + * + * For a supplied exponent p, generate an exponent string strp, which + * defines in pairs the number of multiplies and square operations + * required by a particular bit pattern, commonly used exponents + * 3, 11 and F4 have predefined constant string values, the rest + * are calculated into a cast unsigned char * array via the data + * pointer of a BIGNUM taken from the BN_CTX stack of BIGNUMs + * + * @param p [In] Exponent + * @param strp [Out] Exponent string result + * @param flags [In] Unused + * @param ctx [In] Temporary data storage + * + * @pre p, and ctx are initialised and valid + * @post strp points to required exponent string + * + * @notes String length value in strp[2] is invalid for strings + * greater than length 255 + * string terminates with pattern, 0, 0 this should be + * used in accurately determining the length of a returned + * string strp. + * + * @note strings with value sqr = 255, mul = 0, sqr value should be + * treated as value 256, and added to the next sqr value, this + * is used by exponent strings where more then 256 contiguous + * zero bits are in the exponent bit representation. + * + * @note code contains conditional compilation of code dependent on + * the OS int/long sizes + */ +int BN_gen_exp_bits(p,strp,flags,ctx) +BIGNUM *p; +unsigned char **strp; +int flags; +BN_CTX *ctx; + { + int bits,i,j,window,num; + unsigned char *str=NULL; + BIGNUM *tmp; + + flags=flags; + bits=p->top*BN_BITS2; + tmp=&(ctx->bn[ctx->tos]); + if (p->top == 0) + return(0); + +#if (BN_BITS2 > 17) + if (p->top == 1) +#else + if (bits <= 32) +#endif + { +#if (BN_BITS2 > 17) + if ((p->top == 1) && (p->d[0] == 0x10001)) + str=(unsigned char *)p16; +#endif +#if (16 >= BN_BITS2) && (BN_BITS > 8) + if ( (p->top == 2) && + (p->d[0] == 0x0001) && + (p->d[1] == 0x0001)) + str=(unsigned char *)p16; +#endif +#if (8 >= BN_BITS) + if ( (p->top == 3) && + (p->d[0] == 0x01) && + (p->d[1] == 0x00) && + (p->d[2] == 0x01)) + str=(unsigned char *)p16; +#endif + else if ((p->d[0] == 0x11) && (p->top == 1)) + str=(unsigned char *)p4; + else if ((p->d[0] == 0x3) && (p->top == 1)) + str=(unsigned char *)p2; + window=1; + num=1; + i=BN_BITS2; + } + else if (bits >= 256) + { + window=MAX_WIN_SIZE; /* max size of window */ + num=MAX_NUM_SIZE; + i=(BN_BITS2+(MAX_WIN_SIZE -1))/MAX_WIN_SIZE; + } + else if (bits >= 128) + { + window=4; + num=8; + i=(BN_BITS2+3)/4; + } + else /* 128 to 33 */ + { + window=3; + num=4; + i=(BN_BITS2+2)/3; + } + + /* Number of tmp words */ + j=(p->top*i*2+BN_BYTES-1+4)/BN_BYTES; + + if (str == NULL) + { + if (!bn_wexpand(tmp,j)) + return(0); + str=(unsigned char *)tmp->d; + i=BN_gen_exp_string(&(str[4]),p,window); + i+=2; + str[0]=(unsigned char)((i>>8)&0xff); + str[1]=(unsigned char)((i )&0xff); + str[2]=(unsigned char)window; + str[3]=(unsigned char)num; + } + else + { + i=8; + } + *strp=str; + return(i+2); + } + + +/** + * Generates the Montgomery exponent string. + * + * This function is used to generate an 'exponent string' + * which is an array of bytes that encode how to perform the steps in + * the a^p%m operation. + * + * @param str [Out] Containing the generated string + * @param p [In] Exponent to generate the string for + * @param bits [In] Size of the window for shifting the values of the BIGNUM + * + * @pre p is initialised and value BIGNUM, bits is not 0 + * @post str points to generated exponent string + * + * @note str is cast assigned the data of a BIGNUM allocated and + * expanded from the BN_CTX of the calling function BN_gen_exp_bits + * it does not need to be de-allocated + * + * @note string consisted of unsigned char pairs and 4 byte init + * pairs are sqr count and multiply, where strings are greater + * than 256 bit, length in position str[2] is invalid + * + * @note strings with value sqr = 255, mul = 0, sqr value should be + * treated as value 256, and added to the next sqr value, this + * is used by exponent strings where more then 256 contiguous + * zero bits are in the exponent bit representation. + * + */ +int BN_gen_exp_string(str,p,bits) +unsigned char *str; +BIGNUM *p; +int bits; + { + unsigned char *sp; + unsigned int mask; + const unsigned char *shift; + BN_ULONG w,wh,wl,*d; + unsigned int i,mul,sqr,t,s,ss; + int top; + + if (bits > 6) bits=6; + shift= shift_val[bits]; + + /* This is the mask for the bits we wish to operate on */ + mask=(unsigned int)( (1<top*BN_BITS2+bits-1)/bits)*2+2]); + *sp-- = 0; + *sp-- = 0; + top=p->top; /* Total words we will shift in */ + d=p->d; + w=wl= *d++; + if (top <= 1) + wh=0; + else + wh= *d++; + sqr=0; + i=0; + + for (;;) + { + /* t will contain how far we need to shift to set a 1 + * in the bottom bit. */ + for (;;) + { + t=w&mask; /* retrieve our window */ + s=shift[t]; /* get the shift value for the window */ + if (s == 0) break; /* no shift write out the vals */ + sqr+=s; /* add the shifted zero count to sqr */ + ss+=s; /* ss is total shift for wl */ + if (ss >= BN_BITS2) /* we have shifted > word len */ + { + if (top <= 1) break; /* no more to do */ + top--; /* dec the count */ + + wl=wh; /* copy the next word */ + /* load the word after or 0 if no more */ + wh=(top <= 1)?0:(*d++); + /* adjust our shift by len of word */ + ss-=BN_BITS2; + } + /* reset our window word w */ + if (ss == 0) + w=wl; + else + w=(wl>>ss)|(wh<<(BN_BITS2-ss)); + } + + /* At this point we have the 0th bit set */ + mul=t; + if (t == 0) break; /* we have reached the end of p */ + /* write out sqr/mul pair */ + *sp-- = (unsigned char)(sqr & 0xff); + *sp-- = (unsigned char)(mul & 0xff); + if(sqr >= 256) /* check whether sqr exceeds max uchar */ + { + /* output the expanded list of to allow for this + * and numbers will require to be added together + * at interpret time + */ + while(sqr >= 256) + { + *sp-- = 255; + *sp-- = 0; /* mul is never zero normally */ + sqr-= 256; + } + } + sqr=(unsigned int)bits; /* set sqr to be the window size */ + + ss+=bits; /* ss is total shift for wl */ + if (ss >= BN_BITS2) /* adjust window words w,wl, wh again */ + { + if (top <= 1) break; + top--; + + wl=wh; + wh=(top <= 1)?0:(*(d++)); + ss-=BN_BITS2; + } + + if (ss == 0) + w=wl; + else + w=(wl>>ss)|(wh<<(BN_BITS2-ss)); + } + sp++; + i=2; + /* reverse the string from the top of the exponent string + * and copy to the bottom, allocated exponent string is 2 * max length + * expected for exponent string + */ + while (sp[0] != 0 || sp[1] != 0) + { + str[0]=sp[0]; + str[1]=sp[1]; + str+=2; + sp+=2; + i+=2; + } + str[0]=0; + str[1]=0; + + return( (int)i ); + } + +#ifdef MAIN +main() + { + BIGNUM p; + unsigned char buf[512],*pp; + int i; + + BN_init(&p); + BN_rand(&p,33,1,0); +#ifndef NO_FP_API + BN_print_fp(stdout,&p); fprintf(stdout,"\n"); +#endif + + BN_rand(&p,512,1,1); +#ifndef NO_FP_API + BN_print_fp(stdout,&p); fprintf(stdout,"\n"); +#endif + for (i=0; i<10000; i++) + BN_gen_exp_string(buf,&p,5); + +#if 0 + BN_gen_exp_string(buf,&p,3); + + pp=buf; + for (;;) + { + printf("mul %d sqr %d\n",pp[0],pp[1]); + if (pp[1] == 0) break; + pp+=2; + } +#endif + } +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_exp.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_exp.c new file mode 100644 index 0000000..723b62f --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_exp.c @@ -0,0 +1,172 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MOD_EXP_ORIG +#define SPLIT_BN_MOD_EXP +#endif /* NO_SPLIT */ + +#define TABLE_SIZE 16 + +#ifdef SPLIT_BN_MOD_EXP_ORIG +#if 0 +/* this one works - simple but works */ +int BN_mod_exp_orig(r,a,p,m,ctx) +BIGNUM *r,*a,*p,*m; +BN_CTX *ctx; + { + int i,bits,ret=0; + BIGNUM *v,*tmp; + + v= &(ctx->bn[ctx->tos++]); + tmp= &(ctx->bn[ctx->tos++]); + + if (BN_copy(v,a) == NULL) goto err; + bits=BN_num_bits(p); + + if (BN_is_odd(p)) + { if (BN_copy(r,a) == NULL) goto err; } + else { if (!BN_one(r)) goto err; } + + for (i=1; itos-=2; + return(ret); + } + +#endif + +/* this one works - simple but works */ +int BN_exp(r,a,p,ctx) +BIGNUM *r,*a,*p; +BN_CTX *ctx; + { + int i,bits,ret=0,tos; + BIGNUM *v,*rr; + + bn_check_top(a); + bn_check_top(p); + + tos=ctx->tos; + v= &(ctx->bn[ctx->tos++]); + if ((r == a) || (r == p)) + rr= &(ctx->bn[ctx->tos++]); + else + rr=r; + + if (BN_copy(v,a) == NULL) goto err; + bits=BN_num_bits(p); + + if (BN_is_odd(p)) + { if (BN_copy(rr,a) == NULL) goto err; } + else { if (!BN_one(rr)) goto err; } + + for (i=1; itos=tos; + if (r != rr) (void)BN_copy(r,rr); + return(ret); + } +#endif + +#ifdef SPLIT_BN_MOD_EXP +/** + * Perform mod exp on BIGNUM + * @param r Pointer to return value BIGNUM + * @param a Pointer to data value BIGNUM + * @param p Pointer to Public exponent BIGNUM + * @param m Pointer to modulus BIGNUM + * @param ctx Pointer to BN_CTX + * @return 0 success + * @pre BIGNUMs a, p, m and BN_CTX ctx exist and are valid + * @post BIGNUM r points to evaluated mod_exp + * @note BN_mod_exp_mont is only available if library compiled + * with define BN_MONT_MUL, and will only be used to compute + * mod_exp operation where the modulus m is odd. + * BN_mod_exp_recp is only available if library is compiled + * with define RECP_MUL_MOD. + * BN_mod_exp_simple is the default method, not available if + * library is compiled with define RECP_MUL_MOD. + * if BN_mod_exp_mont is available, which ever of BN_mod_exp_simple + * or BN_mod_exp_recp is available will only be used for even + * modulus m values. + * @relates BN_mod_exp_mont + * @relates BN_mod_exp_recp + * @relates BN_mod_exp_simple + */ +int BN_mod_exp(r,a,p,m,ctx) +BIGNUM *r; +BIGNUM *a; +BIGNUM *p; +BIGNUM *m; +BN_CTX *ctx; + { + int ret; + + bn_check_top(a); + bn_check_top(p); + bn_check_top(m); + +#ifdef MONT_MUL_MOD + + if (BN_is_odd(m)) + { ret=BN_mod_exp_mont(r,a,p,m,ctx,NULL); } + else +#endif +#ifdef RECP_MUL_MOD + { ret=BN_mod_exp_recp(r,a,p,m,ctx); } +#else + { ret=BN_mod_exp_simple(r,a,p,m,ctx); } +#endif + + return(ret); + } +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_fm_w.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_fm_w.c new file mode 100644 index 0000000..54c67ab --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_fm_w.c @@ -0,0 +1,79 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +#include "bn_lcl.h" + +/* rp has w words, the top w words are 0 */ +void bn_from_montgomery_words(ret,a,np,w,n0) +BN_ULONG *ret; +BN_ULONG *a; +BN_ULONG *np; +int w; +BN_ULONG n0; + { + BN_ULONG v0,v1,*ap,*wap; + int i; + + v1=0; + + ap=a; + wap= &(a[w]); + /* Consider putting this loop in ASM */ + for (i=0; i0; i--) + if (ap[i] != np[i]) break; + } + v1=(ap[i] >= np[i]); + } + if (v1) + (void)bn_sub_words(ret,ap,np,w); + else + { +#if 0 /* Alpha does not like Memcpy */ + Memcpy(ret,ap,sizeof(BN_ULONG)*w); +#else + for (i=0; ibn[ctx->tos]); + b= &(ctx->bn[ctx->tos+1]); + + if (BN_copy(a,in_a) == NULL) goto err; + if (BN_copy(b,in_b) == NULL) goto err; + + if (BN_cmp(a,b) < 0) { t=a; a=b; b=t; } + t=bn_euclid(a,b); + if (t == NULL) goto err; + + if (BN_copy(r,t) == NULL) goto err; + ret=1; +err: + return(ret); + } + +BIGNUM *bn_euclid(a,b) +BIGNUM *a,*b; + { + BIGNUM *t; + int shifts=0; + + bn_check_top(a); + bn_check_top(b); + + for (;;) + { + if (BN_is_zero(b)) + break; + + if (BN_is_odd(a)) + { + if (BN_is_odd(b)) + { + if (!BN_sub(a,a,b)) goto err; + if (!BN_rshift1(a,a)) goto err; + if (BN_cmp(a,b) < 0) + { t=a; a=b; b=t; } + } + else /* a odd - b even */ + { + if (!BN_rshift1(b,b)) goto err; + if (BN_cmp(a,b) < 0) + { t=a; a=b; b=t; } + } + } + else /* a is even */ + { + if (BN_is_odd(b)) + { + if (!BN_rshift1(a,a)) goto err; + if (BN_cmp(a,b) < 0) + { t=a; a=b; b=t; } + } + else /* a even - b even */ + { + if (!BN_rshift1(a,a)) goto err; + if (!BN_rshift1(b,b)) goto err; + shifts++; + } + } + } + if (shifts) + { + if (!BN_lshift(a,a,shifts)) goto err; + } + return(a); +err: + return(NULL); + } +#endif + +#ifdef SPLIT_BN_MOD_INVERSE +/* solves ax == 1 (mod n) */ +BIGNUM *BN_mod_inverse(in, a, n, ctx) +BIGNUM *in; +BIGNUM *a; +BIGNUM *n; +BN_CTX *ctx; + { + BIGNUM *A,*B,*X,*Y,*M,*D,*R; + BIGNUM *T,*ret=NULL; + int sign; + + bn_check_top(a); + bn_check_top(n); + + A= &(ctx->bn[ctx->tos]); + B= &(ctx->bn[ctx->tos+1]); + X= &(ctx->bn[ctx->tos+2]); + D= &(ctx->bn[ctx->tos+3]); + M= &(ctx->bn[ctx->tos+4]); + Y= &(ctx->bn[ctx->tos+5]); + ctx->tos+=6; + if (in == NULL) + R=BN_new(); + else + R=in; + if (R == NULL) goto err; + + (void)BN_zero(X); + (void)BN_one(Y); + if (BN_copy(A,a) == NULL) goto err; + if (BN_copy(B,n) == NULL) goto err; + sign=1; + + while (!BN_is_zero(B)) + { + if (!BN_div(D,M,A,B,ctx)) goto err; + T=A; + A=B; + B=M; + /* T has a struct, M does not */ + + if (!BN_mul(T,D,X,ctx)) goto err; + if (!BN_add(T,T,Y)) goto err; + M=Y; + Y=X; + X=T; + sign= -sign; + } + if (sign < 0) + { + if (!BN_sub(Y,n,Y)) goto err; + } + + if (BN_is_one(A)) + { if (!BN_mod(R,Y,n,ctx)) goto err; } + else + { +#ifndef NO_ERR + BNerr(BN_F_BN_MOD_INVERSE,BN_R_NO_INVERSE); +#endif + goto err; + } + ret=R; +err: + if ((ret == NULL) && (in == NULL)) BN_free(R); + ctx->tos-=6; + return(ret); + } +#endif + +#ifdef SPLIT_BN_MOD_INVERSE_WORD +/* solves 1 == (ret*(1<l + * @param l [In] a word (size of word depends on machine) + * @returns number of bits in parameter l + */ +#ifdef SPLIT_BN_NUM_BITS_WORD +int BN_num_bits_word(l) +BN_ILONG l; + { + int i; + + /* + * This table represents the number of bits required to + * represent a "number", where "number" is indexed from + * 0 into the table. So: + * number 0 = # bits req'd to represent 0 = bits[0] = 0 + * number 1 = # bits req'd to represent 1 = bits[1] = 1 + * number 2 = # bits req'd to represent 2 = bits[2] = 2 + * number 3 = # bits req'd to represent 3 = bits[3] = 2 + * number 4 = # bits req'd to represent 4 = bits[4] = 3 + * etc. + * + * The small code size table exists to save some space, + * but requires (at most) an extra shift, an extra AND, + * and an extra add. + */ +#ifdef SMALL_CODE_SIZE + const static char bits[16]={ + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 + }; +#else + const static char bits[256]={ + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + }; +#endif + +#if defined(SIXTY_FOUR_BIT_LONG) + if (l & 0xffffffff00000000L) + { + if (l & 0xffff000000000000L) + { + if (l & 0xff00000000000000L) + i=56; + else i=48; + } + else + { + if (l & 0x0000ff0000000000L) + i=40; + else i=32; + } + } + else +#else +#ifdef SIXTY_FOUR_BIT + if (l & 0xffffffff00000000LL) + { + if (l & 0xffff000000000000LL) + { + if (l & 0xff00000000000000LL) + i=56; + else i=48; + } + else + { + if (l & 0x0000ff0000000000LL) + i=40; + else i=32; + } + } + else +#endif +#endif + { +#if defined(THIRTY_BIT) || defined(THIRTY_ONE_BIT) || defined(THIRTY_TWO_BIT) || defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) + if (l & 0xffff0000L) + { + if (l & 0xff000000L) + i=24; + else i=16; + } + else +#endif + { + if (l & 0xff00L) + i=8; + else + i=0; + } + } +#ifndef SMALL_CODE_SIZE + return(i+bits[l>>i]); +#else + l>>=i; + if (l & 0xf0) + return(bits[l>>4]+i+4); + else + return(bits[l]+i); +#endif + } +#endif + +#ifdef SPLIT_BN_NUM_BITS +int BN_num_bits(a) +BIGNUM *a; + { + BN_ULONG l; + int i; + + bn_check_top(a); + + if (a->top == 0) return(0); + l=a->d[a->top-1]; + i=(a->top-1)*BN_BITS2; +#ifdef BN_DEBUG + if (l == 0) + { +#if !defined(NO_FP_API) && !defined(WIN16) + fprintf(stderr,"BAD TOP VALUE\n"); +#endif + abort(); /* BN_DEBUG */ + /* TODO: need to understand what sort of error can + * be reported for this error + */ + return(0); + } +#endif + return(i+BN_num_bits_word(l)); + } +#endif + +/** + * Clears and free a BIGNUM + * + * @param a [In] BIGNUM to clear then free + */ +#ifdef SPLIT_BN_CLEAR_FREE +void BN_clear_free(BIGNUM *a) +{ + if (a == NULL) + { + return; + } + + BN_clear(a); + BN_free(a); +} +#endif + +#ifdef SPLIT_BN_FREE +/** + * Frees a BIGNUM + * + * @param a [In] BIGNUM to free + */ +void BN_free(a) +BIGNUM *a; + { + if (a == NULL) return; + if ((a->d != NULL) && !(BN_get_flags(a,BN_FLG_STATIC_DATA))) + Free(a->d); + a->flags|=BN_FLG_FREE; /* REMOVE? */ + if (a->flags & BN_FLG_MALLOCED) + Free(a); + } +#endif + +#ifdef SPLIT_BN_INIT + +#ifdef SMALL_CODE_SIZE +/** + * Zero expands a bignum + * + * @param a [In] BIGNUM to expand + * @param n [In] number of bits to expand to + * + * @pre a is a valid BIGNUM. + */ +void bn_zexpand(a,n) +BIGNUM *a; +int n; + { + if ((a)->top < n) + { + int i; + bn_wexpand((a),n); + if (a->d!=NULL) + { + for (i=(a)->top; id[i]=0; + } + } + } + +/** + * Fixes the top value in the BIGNUM to be the count of BN_ULONGs with data. + * + * @param a [In] BIGNUM to free + * + * @pre a is a valid BIGNUM. + */ +void bn_fix_top(a) +BIGNUM *a; + { + BN_ULONG *ftl; + if ((a)->top > 0) + { + for (ftl= &((a)->d[(a)->top-1]); (a)->top > 0; (a)->top--) + if (*(ftl--)) break; + } + } +#endif + +/** + * Initializes a BIGNUM + * + * @param a [In] BIGNUM reference + * + * @pre a is a valid BIGNUM. + */ +void BN_init(a) +BIGNUM *a; + { + (void)Memset(a,0,sizeof(BIGNUM)); + } +#endif + +#ifdef SPLIT_BN_NEW +/** + * Allocates a BIGNUM + * + * @return pointer to allocated BIGNUM + */ +BIGNUM *BN_new() + { + BIGNUM *ret; + + if ((ret=(BIGNUM *)Malloc(sizeof(BIGNUM))) == NULL) + { +#ifndef NO_ERR + BNerr(BN_F_BN_NEW,ERR_R_MALLOC_FAILURE); +#endif + return(NULL); + } + ret->flags=BN_FLG_MALLOCED; + ret->top=0; + ret->neg=0; + ret->max=0; + ret->d=NULL; + return(ret); + } +#endif + +#ifdef SPLIT_BN_CTX_NEW +/** + * Allocates a BIGNUM context + * + * @return pointer to allocated BIGNUM context + */ +BN_CTX *BN_CTX_new() + { + BN_CTX *ret; + + ret=(BN_CTX *)Malloc(sizeof(BN_CTX)); + if (ret == NULL) + { +#ifndef NO_ERR + BNerr(BN_F_BN_CTX_NEW,ERR_R_MALLOC_FAILURE); +#endif + return(NULL); + } + + BN_CTX_init(ret); + ret->flags=BN_FLG_MALLOCED; + return(ret); + } +#endif + +#ifdef SPLIT_CTX_INIT +/** + * Initializes a BIGNUM context + * + * @param a [In] BIGNUM context reference + * + * @pre a is a valid BIGNUM context. + */ +void BN_CTX_init(ctx) +BN_CTX *ctx; + { + (void)Memset(ctx,0,sizeof(BN_CTX)); + ctx->tos=0; + ctx->flags=0; + } +#endif + +#ifdef SPLIT_BN_CTX_FREE +/** + * Frees a BIGNUM context + * + * @param a [In] BIGNUM context reference + * + * @pre a is a valid BIGNUM context. + */ +void BN_CTX_free(c) +BN_CTX *c; + { + int i; + + for (i=0; ibn[i])); + if (c->flags & BN_FLG_MALLOCED) + Free(c); + } +#endif + +#ifdef SPLIT_BN_EXPAND2 +BIGNUM *bn_expand2(b, words) +BIGNUM *b; +int words; + { + BN_ULONG *A,*B,*a; + + R_DIAG_CHECK_STACK; + + bn_check_top(b); + + if (words > b->max) + { + bn_check_top(b); + if (BN_get_flags(b,BN_FLG_STATIC_DATA)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_EXPAND2,BN_R_EXPAND_ON_STATIC_BIGNUM_DATA); +#endif + return(NULL); + } + a=A=(BN_ULONG *)Malloc(sizeof(BN_ULONG)*(words+1)); + if (A == NULL) + { +#ifndef NO_ERR + BNerr(BN_F_BN_EXPAND2,ERR_R_MALLOC_FAILURE); +#endif + return(NULL); + } + /* during development this is a nice way of making sure + * that we are not relying on the top byte being 0 or + * other such things + */ +#ifdef BN_DEBUG + (void)Memset(A,0x5c,sizeof(BN_ULONG)*(words+1)); +#endif + + B=b->d; + if (B != NULL) + { +#ifndef SMALL_CODE_SIZE + int i; + + /* for (i=b->top&(~7); i>0; i-=8) */ + /* The above line can induce a SunC compiler bug */ + for (i=(b->top>>3); i>0; i--) + { + BN_ULONG T0,T1,T2,T3; + + T0=B[0]; + T1=B[1]; + T2=B[2]; + T3=B[3]; + A[0]=T0; + A[1]=T1; + A[2]=T2; + A[3]=T3; + T0=B[4]; + T1=B[5]; + T2=B[6]; + T3=B[7]; + A[4]=T0; + A[5]=T1; + A[6]=T2; + A[7]=T3; + A+=8; + B+=8; + } + switch (b->top&7) + { + case 7: + A[6]=B[6]; + case 6: + A[5]=B[5]; + case 5: + A[4]=B[4]; + case 4: + A[3]=B[3]; + case 3: + A[2]=B[2]; + case 2: + A[1]=B[1]; + case 1: + A[0]=B[0]; + case 0: + /* I need the 'case 0' entry for utrix cc. + * If the optimiser is turned on, it does the + * switch table by doing + * a=top&7 + * a--; + * goto jump_table[a]; + * If top is 0, this makes us jump to 0xffffffc + * which is rather bad. + * eric 23-Apr-1998 + */ + ; + } +#if 0 /* Not needed */ + B= &(b->d[b->top]); + j=b->max-8; + for (i=b->top; itop); +#endif + Free(b->d); + } + + b->d=a; + b->max=words; + } + return(b); + } +#endif + +#ifdef SPLIT_BN_DUP +/** + * Duplicates a BIGNUM + * + * @param a [In] BIGNUM reference + * + * @returns pointer to duplicate BIGNUM of a + */ +BIGNUM *BN_dup(a) +BIGNUM *a; + { + BIGNUM *r; + BIGNUM *ret; + + bn_check_top(a); + + r=BN_new(); + if (r == NULL) return(NULL); + ret = (BIGNUM *)BN_copy(r,a); + if (ret == NULL) + { + BN_free(r); + } + return(ret); + } +#endif + +#ifdef SPLIT_BN_COPY +/** + * Copies a BIGNUM to an existing BIGNUM + * + * @param a [In] To BIGNUM reference + * @param b [Out] From BIGNUM reference + * + * @pre Both a and b are valid BIGNUMs + * + * @returns pointer to duplicate BIGNUM of a + */ +BIGNUM *BN_copy(a, b) +BIGNUM *a; +BIGNUM *b; + { +#ifndef SMALL_CODE_SIZE + int i; + BN_ULONG *A,*B; +#endif + + bn_check_top(b); + + if (a == b) return(a); + if (bn_wexpand(a,b->top) == NULL) return(NULL); +#ifndef SMALL_CODE_SIZE + A=a->d; + B=b->d; + +/* for (i=b->top&~0x07; i>0; i-=8) */ +/* The above version of this loop has been removed. It appeared + to generate a compiler bug in SunC 4.x and 5.x. I do not believe + that the code was to blame. Compiling with -fast was the problem + since this would loop unroll the loop below another 3 times. + The compiler would generate generate + andcc %o0,-8,%o1 # load ~0x07 + ld [%i2],%o3 # load *B + ble .L77000125 # exit loop unless 8 or more + ld [%i1],%o2 # load *A + sub %o1,-7,%o0 # + sdivcc %o0,8,%o0 # when do we clear %y? + bvs,a .L900001510 + sethi %hi(0x80000000),%o0 +.L900001510: + cmp %o0,3 + bl .L77000114 # one loop + ld [%o2],%o0 + # three loop code + + The loop would then be unrolled 3 times. The problem I believe + I was seeing was that the sdivcc operates is %y:%o0 / 8. + %y is not being cleared, and so occasionally this would + cause problems. The replacement code sequence stops + the compiler generating the sdiv instruction. + */ + for (i=(b->top>>3); i>0; i--) + { + BN_ULONG T0,T1,T2,T3; + T0=B[0]; + T1=B[1]; + T2=B[2]; + T3=B[3]; + A[0]=T0; + A[1]=T1; + A[2]=T2; + A[3]=T3; + T0=B[4]; + T1=B[5]; + T2=B[6]; + T3=B[7]; + A[4]=T0; + A[5]=T1; + A[6]=T2; + A[7]=T3; + A+=8; + B+=8; + } + switch (b->top&0x07) + { + case 7: + A[6]=B[6]; + case 6: + A[5]=B[5]; + case 5: + A[4]=B[4]; + case 4: + A[3]=B[3]; + case 3: + A[2]=B[2]; + case 2: + A[1]=B[1]; + case 1: + A[0]=B[0]; + case 0: + /* I need the 'case 0' entry for utrix cc. + * If the optimiser is turned on, it does the + * switch table by doing + * a=top&7 + * a--; + * goto jump_table[a]; + * If top is 0, this makes us jump to 0xffffffc which is + * rather bad. + * eric 23-Apr-1998 + */ + ; + } +#else + (void)Memcpy(a->d,b->d,sizeof(b->d[0])*b->top); +#endif + +/* (void)Memset(&(a->d[b->top]),0,sizeof(a->d[0])*(a->max-b->top));*/ + a->top=b->top; + if ((a->top == 0) && (a->d != NULL)) + a->d[0]=0; + a->neg=b->neg; + return(a); + } +#endif + +#ifdef SPLIT_BN_CLEAR +/** + * Clears a BIGNUM + * + * @param a [In] BIGNUM to clear + * + * @pre a is valid + */ +void BN_clear(a) +BIGNUM *a; + { + if (a->d != NULL) + (void)Memset(a->d,0,a->max*sizeof(a->d[0])); + a->top=0; + a->neg=0; + } +#endif + +#ifdef SPLIT_BN_GET_WORD +BN_ULONG BN_get_word(a) +BIGNUM *a; + { + int i,n; + BN_ULONG ret=0; + + n=BN_num_bytes(a); + if (n > ((int) sizeof(BN_ULONG))) + return(BN_MASK2); + for (i=a->top-1; i>=0; i--) + { +#ifndef SIXTY_FOUR_BIT /* the data item > unsigned long */ + ret<<=BN_BITS4; /* stops the compiler complaining */ + ret<<=BN_BITS4; +#else + ret=0; +#endif + ret|=a->d[i]; + } + return(ret); + } +#endif + +#ifdef SPLIT_BN_SET_WORD +/** + * Set the BIGNUM to the supplied BN_ULONG value. + * + * @param a [In/Out] BIGNUM to be updated + * @param w [In] Value to be set in a + * + * @notes Function will expand a to be an + * array of 8 BN_ULONGs in size. + * @todo Review behaviour of expansion without checking + * of size first. + */ +int BN_set_word(a,w) +BIGNUM *a; +BN_ULONG w; + { + int i,n; + + if (bn_expand(a,(int)(sizeof(BN_ULONG)*8)) == NULL) return(0); + +#ifdef BN_BYTES + /* This is used when a BN_ULONG is greater in size + * than the BN_BYTES of the array, eg BN_ULONG 64 bits + * and actual a->d array of 32 bits. + */ + n=sizeof(BN_ULONG)/BN_BYTES; +#else + n=1; +#endif + a->neg=0; + a->top=0; + a->d[0]=(BN_ULONG)w&BN_MASK2; + if (a->d[0] != 0) a->top=1; + for (i=1; i>=BN_BITS2 so compilers don't complain + * on builds where sizeof(long) == BN_TYPES */ +#ifndef SIXTY_FOUR_BIT /* the data item > unsigned long */ + w>>=BN_BITS4; + w>>=BN_BITS4; +#else + w=0; +#endif + a->d[i]=(BN_ULONG)w&BN_MASK2; + if (a->d[i] != 0) a->top=i+1; + } + return(1); + } +#endif + +#ifdef BN_BYTES +#ifdef SPLIT_BN_BIN2BN +/* ignore negative */ +BIGNUM *BN_bin2bn(s, len, ret) +unsigned char *s; +int len; +BIGNUM *ret; + { + int i,m; + int n; + BN_ULONG l; + + if (ret == NULL) ret=BN_new(); + if (ret == NULL) return(NULL); + l=0; + n=len; + if (n == 0) + { + ret->top=0; + return(ret); + } + if (bn_expand(ret,(int)(n+2)*8) == NULL) + return(NULL); + i=((n-1)/BN_BYTES)+1; + m=((n-1)%(BN_BYTES)); + ret->top=i; + while (n-- > 0) + { + l=(l<<8L)| *(s++); + if (m-- == 0) + { + ret->d[--i]=l; + l=0; + m=BN_BYTES-1; + } + } + /* need to call this due to clear byte at top if avoiding + * having the top bit set (-ve number) */ + bn_fix_top(ret); + return(ret); + } +#endif + +#ifdef SPLIT_BN_BN2BIN +/* ignore negative */ +int BN_bn2bin(a, to) +BIGNUM *a; +unsigned char *to; + { + int n,i; + BN_ULONG l; + + bn_check_top(a); + + n=i=BN_num_bytes(a); + while (i-- > 0) + { + l=a->d[i/BN_BYTES]; + *(to++)=(unsigned char)((l>>(8*(i%BN_BYTES)))&0xff); + } + return(n); + } +#endif +#else +#ifdef SPLIT_BN_BIN2BN +/* ignore negative */ +BIGNUM *BN_bin2bn(s, len, ret) +unsigned char *s; +int len; +BIGNUM *ret; + { + int i,w,r,b,j,v; + int n; + BN_ULONG l; + + if (ret == NULL) ret=BN_new(); + if (ret == NULL) return(NULL); + while (len > 0) + { + if (*s != 0) break; + s++; + len--; + } + n=len*8; + if (bn_expand(ret,n) == NULL) + return(NULL); + for (i=0; imax; i++) + ret->d[i]=0; + j=0; + for (i=len-1; i>=0; i--) + { + v=((int)s[i])&0xff; + w=j/BN_BITS2; + b=j%BN_BITS2; + r=BN_BITS2-b; + j+=8; + if (r >= 8) + { + ret->d[w]|=(((BN_ULONG)v)<d[w] =(ret->d[w]|(((BN_ULONG)v)<d[w+1]=(ret->d[w+1]|(((BN_ULONG)v)>>r)); + } + } + + ret->top=((n-1)/BN_BITS2)+1; + bn_fix_top(ret); + return(ret); + } +#endif + +#ifdef SPLIT_BN_BN2BIN +int BN_bn2bin(a, to) +BIGNUM *a; +unsigned char *to; + { + int num,i,bi,w,b,r,max; + BN_ULONG l,*lp; + + bn_check_top(a); + + num=bi=BN_num_bytes(a); + lp=a->d; + for (i=0; i= 8) + to[bi]=(lp[w]>>b)&0xff; + else + { + to[bi]=(lp[w]>>b); + if (w+1 < a->top) + to[bi]|=lp[w+1]<top-b->top; + if (i != 0) return(i); + ap=a->d; + bp=b->d; + for (i=a->top-1; i>=0; i--) + { + t1= ap[i]; + t2= bp[i]; + if (t1 != t2) + return(t1 > t2?1:-1); + } + return(0); + } +#endif + +#ifdef SPLIT_BN_CMP +int BN_cmp(a, b) +BIGNUM *a; +BIGNUM *b; + { + int i; + int gt,lt; + BN_ULONG t1,t2; + + if ((a == NULL) || (b == NULL)) + { + if (a != NULL) + return(-1); + else if (b != NULL) + return(1); + else + return(0); + } + + bn_check_top(a); + bn_check_top(b); + + if (a->neg != b->neg) + { + if (a->neg) + return(-1); + else return(1); + } + if (a->neg == 0) + { gt=1; lt= -1; } + else { gt= -1; lt=1; } + + if (a->top > b->top) return(gt); + if (a->top < b->top) return(lt); + for (i=a->top-1; i>=0; i--) + { + t1=a->d[i]; + t2=b->d[i]; + if (t1 > t2) return(gt); + if (t1 < t2) return(lt); + } + return(0); + } +#endif + +#ifdef SPLIT_BN_SET_BIT +int BN_set_bit(a, n) +BIGNUM *a; +int n; + { + int i,j,k; + + bn_check_top(a); + + i=n/BN_BITS2; + j=n%BN_BITS2; + if (a->top <= i) + { + if (bn_wexpand(a,i+1) == NULL) return(0); + for(k=a->top; kd[k]=0; + a->top=i+1; + } + + a->d[i]|=(((BN_ULONG)1)<top <= i) return(0); + + a->d[i]&=(~(((BN_ULONG)1)<top <= i) return(0); + return((a->d[i]&(((BN_ULONG)1)<= a->top) return(0); + if (b == 0) + a->top=w; + else + { + a->top=w+1; + a->d[w]&= ~(((BN_ULONG)BN_MASK2)< bb)?1:-1); + for (i=n-2; i>=0; i--) + { + aa=a[i]; + bb=b[i]; + if (aa != bb) return((aa > bb)?1:-1); + } + return(0); + } +#endif +#endif + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_lsh.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_lsh.c new file mode 100644 index 0000000..21508b1 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_lsh.c @@ -0,0 +1,128 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_LSHIFT1 +#define SPLIT_BN_LSHIFT +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_LSHIFT1 +#ifdef SMALL_CODE_SIZE + +int BN_lshift1(r, a) +BIGNUM *r,*a; + { + return(BN_lshift(r, a, 1)); + } + +#else + +int BN_lshift1(r, a) +BIGNUM *r; +BIGNUM *a; + { + register BN_ULONG *ap,*rp,t,c; + int i; + + bn_check_top(a); + + if (r != a) + { + if (bn_wexpand(r,a->top+1) == NULL) return(0); + r->neg=a->neg; + r->top=a->top; + } + else + { + if (bn_wexpand(r,a->top+1) == NULL) return(0); + } + ap=a->d; + rp=r->d; + c=0; + for (i=0; itop; i++) + { + t= *(ap++); + *(rp++)=((t<<1L)|c)&BN_MASK2; + c=(t & BN_TBIT)?1:0; + } + if (c) + { + *rp=1; + r->top++; + } + return(1); + } +#endif +#endif + +#ifdef SPLIT_BN_LSHIFT +int BN_lshift(r, a, n) +BIGNUM *r; +BIGNUM *a; +int n; + { + int i,nw,lb,rb; + BN_ULONG *t,*f; + BN_ULONG l; + + bn_check_top(a); + +#ifndef SMALL_CODE_SIZE + if (n == 1) return(BN_lshift1(r,a)); +#endif + if (bn_wexpand(r,a->top+(n/BN_BITS2)+1) == NULL) return(0); + r->neg=a->neg; + nw=n/BN_BITS2; + lb=n%BN_BITS2; + rb=BN_BITS2-lb; + f=a->d; + t=r->d; + t[a->top+nw]=0; + if (lb == 0) + for (i=a->top-1; i>=0; i--) + t[nw+i]=f[i]; + else + for (i=a->top-1; i>=0; i--) + { + l=f[i]; + t[nw+i+1]|=(l>>rb)&BN_MASK2; + t[nw+i]=(l<top=a->top+nw+1; + bn_fix_top(r); + return(1); + } +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_m_exp.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_m_exp.c new file mode 100644 index 0000000..480bb59 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_m_exp.c @@ -0,0 +1,299 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#if 0 //RSA +#include +#endif +#include "bn_lcl.h" + +/* #ifdef MONT_MUL_MOD */ +/** + * Generic form of Montgomery Exponentiation, can be called directly + * out side of a BN_ME_METH + * + * @param rr_in BIGNUM pointer for result + * @param a_in BIGNUM pointer for base + * @param p BIGNUM pointer to the exponent + * @param m BIGNUM pointer to the modulus + * @param ctx BN_CTX pointer for temp values are argument storage + * @param in_mont BN_MONT_CTX pointer to structure of montgomery values + * + * @pre arguments are all initialised and not NULL or zero + * @post rr_in contains evaluated result + * + * @note + */ +int BN_mod_exp_mont(rr_in,a_in,p,m,ctx,in_mont) +BIGNUM *rr_in; +BIGNUM *a_in; +BIGNUM *p; +BIGNUM *m; +BN_CTX *ctx; +BN_MONT_CTX *in_mont; + { + int i,j,k,ret=0,tos,top; + int mul,sqr,num; + BIGNUM *d,*aa,*r,*a,*t; + BN_ULONG *vall[BN_EXP_TABLE_SIZE],*dp,*rp,n0,*rr,*tmp,*np; + BN_MONT_CTX *mont=NULL; + unsigned char *str=NULL; +#ifdef BN_SURRENDER + R_SURRENDER *surrender=NULL; + int count=0; +#endif + + bn_check_top(a_in); + bn_check_top(p); + bn_check_top(m); + + if (!(m->d[0] & 1)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_MOD_EXP_MONT,BN_R_CALLED_WITH_EVEN_MODULUS); +#endif + return(0); + } + + tos=ctx->tos; + + if (BN_is_zero(a_in)) + { (void)BN_zero(rr_in); return(1); } + if (BN_is_zero(p)) + { (void)BN_one(rr_in); return(1); } + if (BN_is_one(p)) + { (void)BN_copy(rr_in,a_in); return(1); } + + /* If this is not done, things will break in the montgomery + * part */ + +#if 1 + if (in_mont != NULL) + mont=in_mont; + else +#endif + { + if ((mont=BN_MONT_CTX_new()) == NULL) goto err; + if (!BN_MONT_CTX_set(mont,m,ctx)) goto err; + } + +#ifdef BN_SURRENDER + surrender=ctx->surrender; +#endif + + if (!BN_gen_exp_bits(p,&str,0,ctx)) goto err; + /* Remember this function uses another element from the passed ctx */ + ctx->tos++; + num=str[3]; + i=(BN_BITS+str[2]-1)/str[2]; + str+=4; + + + top=mont->N.top; + if ((a_in->top == top) && (a_in->d[top-1] < m->d[top-1])) + { + a=a_in; + } + else if (a_in->top < top) + { + a= &(ctx->bn[ctx->tos++]); + a->top=a_in->top; + bn_zexpand(a,top); + for (j=0; jtop; j++) + a->d[j]=a_in->d[j]; + } + else /* if (a_in->top > i) */ + { + a= &(ctx->bn[ctx->tos++]); + if (!BN_mod(a,a_in,m,ctx)) goto err; + bn_zexpand(a,top); + } + + /* At this point a is the size of the modulus and is 0 padded + * out to its size if needed. + */ + + /* Number of tmp words */ + k=num*top; + j=k+(p->top*i*2+BN_BYTES-1+4)/BN_BYTES; + + aa=&(ctx->bn[ctx->tos++]); + d= &(ctx->bn[ctx->tos++]); + r= &(ctx->bn[ctx->tos++]); + t= &(ctx->bn[ctx->tos++]); + + if (bn_wexpand(rr_in,top) == NULL) goto err; + if (bn_wexpand(d,top*4) == NULL) goto err; /* *2? */ + if (bn_wexpand(r,top*2) == NULL) goto err; + if (bn_wexpand(aa,j) == NULL) goto err; + if (bn_wexpand(t,top*2) == NULL) goto err; + dp=d->d; + rp=r->d; + tmp=t->d; + rr=mont->RR.d; + + n0=mont->n0; + np=mont->N.d; + + vall[0]=aa->d; + + bn_mul_normal(tmp,a->d,top,rr,top); + bn_from_montgomery_words(vall[0],tmp,np,top,n0); + + if (num > 1) + { + bn_sqr_normal(tmp,vall[0],top,dp); + bn_from_montgomery_words(dp,tmp,np,top,n0); + + for (i=1; i>1],sizeof(BN_ULONG)*top); + while (sqr != 0) + { +#ifdef BN_SURRENDER + /* + * Check this at the start of the loop rather than the + * end so we avoid as many of the bn operations as possible + */ + if (surrender != NULL) + { + if (surrender->callback(surrender,0xff, count++) != 0) + { + goto err; + } + } +#endif /* BN_SURRENDER */ + + /* + * check the abort flag at the start of the loop so we avoid + * as many of the bn operations as possible + */ + if (BN_CTX_get_flags(ctx, BN_CTX_FLG_ABORT)) + { + goto err; + } + + for (i=0; i>1],top); + bn_from_montgomery_words(rp,tmp,np,top,n0); + } + else + { + bn_mul_normal(tmp,rp,top,a->d,top); + bn_from_montgomery_words(rr_in->d,tmp,np,top,n0); + goto end; + } + } + + /* if (mul != 1) */ + { + for (i=top; id,rp,np,top,n0); + } +end: /* Use this to avoid an if */ + + /* + * Even if the operation has completed successfully, if the + * abort flag is set we want to abort so that anything + * calling this function will know not to continue. + */ + if (BN_CTX_get_flags(ctx, BN_CTX_FLG_ABORT)) + { + goto err; + } + + rr_in->top=top; + bn_fix_top(rr_in); + ret=1; +err: +#ifdef BN_SURRENDER + /* + * Even if the operation completed successfully we want to abort + * if the abort flag has been is set, so that subsequent operations + * do not continue. Allow the caller change to return value and + * cause the function to fail. + */ + if (surrender != NULL) + { + if (surrender->callback(surrender, 0xff, -1) != 0) + { + ret = 0; + } + } +#endif + if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); + ctx->tos=tos; + return(ret); + } +/* #endif */ + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_me.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_me.c new file mode 100644 index 0000000..fae0749 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_me.c @@ -0,0 +1,267 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file bn_me.c + * @brief BN method functions and utilities + */ +#include "bn_lcl.h" +#include "bn_thx.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MOD_EXP_METH_DEFAULT +#define SPLIT_BN_MONT_CTX_USEIT +#define SPLIT_BN_ME_CTX_NAME +#define SPLIT_BN_ME_CTX_NEW +#define SPLIT_BN_ME_CTX_FREE +#define SPLIT_BN_ME_CTX_SET +#define SPLIT_BN_ME_CTX_MOD_EXP +#endif /* NO_SPLIT */ + +#ifndef NOPROTO +BN_ME_METH *bn_mod_exp_meth_default(int fallback); +#else +BN_ME_METH *bn_mod_exp_meth_default(); +#endif + +#ifdef SPLIT_BN_MOD_EXP_METH_DEFAULT + +/** + * Returns the default mod_exp method, choose first available in the + * method table or a hardwired default + * + * @param fallback [In] Flag for choice of method + * - 0 use the first value in the method table + * - 1 use the all encompassing default method + * + * @pre BN_default_init() has been run setting up library + * + * @post + * + * @internal uses global table bnme[] and counter me_num + * + * @internal only read the BN_ME_METH_INFO table no need for locking + * + * @relates BN_library_init + * @relates BN_default_init + * @relates BN_ME_CTX_new + * @relates BN_ME_CTX_free + * + */ +BN_ME_METH *bn_mod_exp_meth_default(int fallback) +{ + const BN_ME_METH *tmp; + +#ifndef BN_LIBRARY_SMALL + BN_ME_METH_INFO *meth_info; + + if(!fallback && ((meth_info = BN_bnme_get_info(0)) != NULL)) + { + tmp = meth_info->meth(); + } + else +#endif + { + /* set in bn.h or override bn_thx.h */ + tmp = BN_ME_METH_DEFAULT(); + } + return((BN_ME_METH *)tmp); +} +#endif + +#ifdef SPLIT_BN_MONT_CTX_USEIT + +#ifndef NOPROTO +int bn_mont_ctx_useit(int argi); +#else +int bn_mont_ctx_useit(); +#endif + +/** + * Montgomery method default useit function + * + * @param argi [In] reserved for future use + * + * @return 0 success + */ +int bn_mont_ctx_useit(int argi) + { + return(0); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_NAME +/** + * Retrieve the BN method name string + * + * @param ctx [In] Method + * + * @pre ctx is valid and not NULL + * + * @return string pointer + */ +char *BN_ME_CTX_name(BN_ME_CTX *ctx) + { + return(ctx->meth->name); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_NEW +/** + * Allocate a new BN_ME_CTX structure and assign method + * + * @param meth [In] Method to assign + * @param in [Out] Result BN_ME_CTX + * + * @note if meth is NULL system method default is used + * + * @retval pointer to BN_ME_CTX success + * @retval NULL failure + */ +BN_ME_CTX *BN_ME_CTX_new(BN_ME_METH *meth, BN_ME_CTX **in) + { + int i; + BN_ME_CTX *ret; + + if (in == NULL) + in= &ret; + + if (meth == NULL) + meth=bn_mod_exp_meth_default(0); + i=meth->init_ctx(meth,in); + if (i) + return(NULL); + else + return(*in); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_FREE +/** + * Free context method + * + * @param mctx [In] Context object to be deallocated + * + * @note it is the callers responsibility to set mctx to NULL after free + * + * @pre mctx is not NULL and is valide BN_ME_CTX + */ +void BN_ME_CTX_free(BN_ME_CTX *mctx) + { + mctx->meth->free_ctx(mctx); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_SET +/** + * Set value to BN_ME_CTX by identifier + * + * @param mctx [In] Method context object + * @param b [In] Big number + * @param cmd [In] Command identifier + * @param flags [In] Mask operation directives + * @param ctx [In] BN data store + * + * @note cmd values: + * @li BN_ME_SET_MOD will cause a method lookup is method not set + * + * @note passes control to set method in mctx + * + * @return result of mctx method set operation + */ +int BN_ME_CTX_set(BN_ME_CTX *mctx, BIGNUM *b, int cmd, int flags, BN_CTX *ctx) + { +#ifndef BN_LIBRARY_SMALL +#ifndef NOPROTO + const BN_ME_METH *(*meth)(void); +#else + const BN_ME_METH *(*meth)(); +#endif +#endif /* BN_LIBRARY_SMALL */ + + /* If we are loading the modulus, and we do not have the + * no_lookup flag (without a null method) + */ + if ((cmd == BN_ME_SET_MOD) && + ((mctx->meth != NULL) && !(flags & BN_ME_SET_FLG_NO_LOOKUP))) + { +#ifndef BN_LIBRARY_SMALL + meth=(const BN_ME_METH*(*)(void)) + BN_bnme_get(BN_num_bits(b),BN_BNME_F_BITS); + if (meth != NULL) + mctx->meth=meth(); + else +#endif + mctx->meth=bn_mod_exp_meth_default(1); + } + return(mctx->meth->set(mctx,b,cmd,flags,ctx)); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_MOD_EXP +/** + * Call method mod_exp operation + * + * @param mctx [In] Method context object + * @param ret [Out] Result + * @param a [In] Base value + * @param p [In] Exponent + * @param m [In] Modulus + * @param ctx [In] Data storage + * + * @pre a must be expandable + * + * @return 0 success + */ +int BN_ME_CTX_mod_exp(BN_ME_CTX *mctx, BIGNUM *ret, BIGNUM *a, BIGNUM *p, + BIGNUM *m, BN_CTX *ctx) + { + int wtop; + + /* Before we call the method, make sure we are not doing 0^p, + * and p is not 0 or 1 */ + if (BN_is_zero(a)) + { BN_zero(ret); return(0); } + if (p != NULL) + { + if (BN_is_zero(p)) + { BN_one(ret); return(0); } + else if (BN_is_one(p)) + { BN_copy(ret,a); return(0); } + } + + /* wtop is the size 'a' needs to be for the method */ + wtop=mctx->meth->num; + bn_zexpand(a,wtop); + + return(mctx->meth->mod_exp(mctx,ret,a,p,ctx)); + } +#endif + +#endif + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_mont.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_mont.c new file mode 100644 index 0000000..d6a45de --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_mont.c @@ -0,0 +1,247 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#undef BN_DEBUG +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MOD_MUL_MONTGOMERY +#define SPLIT_BN_FROM_MONTGOMERY +#define SPLIT_BN_MONT_CTX_NEW +#define SPLIT_BN_MONT_CTX_INIT +#define SPLIT_BN_MONT_CTX_FREE +#define SPLIT_BN_MONT_CTX_COPY +#endif /* NO_SPLIT */ + +/* #define DEBUG */ + +#ifdef SPLIT_BN_MOD_MUL_MONTGOMERY +/* We multiply a by b, generating a number 2n words long. + * This is then reduced by the montogmery number, which is + * n words. */ +int BN_mod_mul_montgomery(r,a,b,mont,ctx) +BIGNUM *r,*a,*b; +BN_MONT_CTX *mont; +BN_CTX *ctx; + { + BIGNUM *tmp,*tmp2; + int ret=0,w; + int i; + + bn_check_top(a); + bn_check_top(b); + + w=mont->riw; + + tmp= &(ctx->bn[ctx->tos++]); + tmp2= &(ctx->bn[ctx->tos++]); + bn_check_top(tmp); + bn_check_top(tmp2); + if (bn_wexpand(tmp,w+w) == NULL) goto err; + if (bn_wexpand(r,w+w) == NULL) goto err; + + if (a == b) + { + if (bn_wexpand(tmp2,w+w) == NULL) goto err; +#ifdef BN_SQR_COMBA + if ((a->top == 8) && (a->top == b->top)) + bn_sqr_comba8(tmp->d,a->d); + else +#endif + { + bn_sqr_normal(tmp->d,a->d,a->top,tmp2->d); + } + } + else + { +#ifdef BN_MUL_COMBA + if (a->top == 8) + bn_mul_comba8(tmp->d,a->d,b->d); + else +#endif + { + bn_mul_normal(tmp->d,a->d,a->top,b->d,b->top); + } + } + + i=a->top+b->top; + while (i<(w+w)) + { + tmp->d[i]=0; + i++; + } + tmp->top=w+w; + tmp->neg=0; + + /* reduce from aRR to aR */ + /* tmp->d is 2w words */ +#if 0 + bn_fix_top(tmp); + BN_from_montgomery_words(r,tmp,mont,ctx); +#else + bn_from_montgomery_words(r->d,tmp->d,mont->N.d,w,mont->n0); +#endif + r->top=w; + r->neg=0; + bn_fix_top(r); + + ret=1; +err: + ctx->tos-=2; + return(ret); + } +#endif + +#ifdef SPLIT_BN_FROM_MONTGOMERY +int BN_from_montgomery(ret,a,mont,ctx) +BIGNUM *ret; +BIGNUM *a; +BN_MONT_CTX *mont; +BN_CTX *ctx; + { + BIGNUM *n,*r; + BN_ULONG *np,*rp,n0,v0,v1,*nrp; + int al,nl,max,i; + int retn=0; + + bn_check_top(a); + + r= &(ctx->bn[ctx->tos]); + + if (!BN_copy(r,a)) goto err1; + n= &(mont->N); + + /* mont->riw is the size of mont->N in bits/words */ + al=mont->riw; + + nl=n->top; + if ((al == 0) || (nl == 0)) { r->top=0; return(1); } + + max=(nl+al+1); /* allow for overflow (no?) XXX */ + if (bn_wexpand(r,max) == NULL) goto err1; + if (bn_wexpand(ret,max) == NULL) goto err1; + + r->neg=a->neg^n->neg; + np=n->d; + rp=r->d; + nrp= &(r->d[nl]); + + /* clear the top words of T */ + for (i=r->top; id[i]=0; + + r->top=max; + n0=mont->n0; + + v1=0; + for (i=0; iriw will be a multiple of the word size */ + (void)BN_rshift(ret,r,mont->riw*BN_BITS2); + + if (BN_ucmp(ret, &(mont->N)) >= 0) + { + (void)BN_usub(ret,ret,&(mont->N)); /* XXX */ + } + retn=1; + +err1: + return(retn); + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_NEW +BN_MONT_CTX *BN_MONT_CTX_new() + { + BN_MONT_CTX *ret; + + if ((ret=(BN_MONT_CTX *)Malloc(sizeof(BN_MONT_CTX))) == NULL) + return(NULL); + + BN_MONT_CTX_init(ret); + ret->flags=BN_FLG_MALLOCED; + return(ret); + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_INIT +void BN_MONT_CTX_init(ctx) +BN_MONT_CTX *ctx; + { + ctx->use_word=0; + ctx->riw=0; + BN_init(&(ctx->RR)); + BN_init(&(ctx->N)); + BN_init(&(ctx->Ni)); + ctx->flags=0; + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_FREE +void BN_MONT_CTX_free(mont) +BN_MONT_CTX *mont; + { + BN_free(&(mont->RR)); + BN_free(&(mont->N)); + BN_free(&(mont->Ni)); + if (mont->flags & BN_FLG_MALLOCED) + Free(mont); + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_COPY +BN_MONT_CTX *BN_MONT_CTX_copy(to, from) +BN_MONT_CTX *to, *from; + { + if (to == from) return(to); + + (void)BN_copy(&(to->RR),&(from->RR)); + (void)BN_copy(&(to->N),&(from->N)); + (void)BN_copy(&(to->Ni),&(from->Ni)); + bn_zexpand(&(to->RR),from->riw); + bn_zexpand(&(to->Ni),from->riw); + to->use_word=from->use_word; + to->riw=from->riw; + to->n0=from->n0; + return(to); + } +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_ms_w.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_ms_w.c new file mode 100644 index 0000000..86a6510 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_ms_w.c @@ -0,0 +1,137 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +int BN_MONT_CTX_set_word(mont,mod,ctx) +BN_MONT_CTX *mont; +BIGNUM *mod; +BN_CTX *ctx; + { + BIGNUM Ri,*R; +#if 1 + BN_ULONG tmod,rr; +#else + BN_ULONG buf[2]; + BIGNUM tmod; +#endif + + + bn_check_top(mod); + if (mod->top == 0) return(0); + + R= &(mont->RR); /* grab RR as a temp */ + if (BN_copy(&(mont->N),mod) == NULL) /* Set N */ + return(0); + + BN_init(&Ri); + + mont->use_word=1; + +/* EAY is this number of words to shift, or the number to shift to end up + * with a '1' in the next word? + * for 8 bit words, is 0x01ab == 1 or 2 + */ + mont->riw=(BN_num_bits(mod)+(BN_BITS2-1))/BN_BITS2; + if (!BN_zero(R)) return(0); + + /* We are now setting a number which is larger than our current + * one after we do the shift + */ + if (!BN_set_bit(R,BN_BITS2)) + goto err; + +#if 0 + tmod.d=buf; + tmod.top=1; + tmod.max=mod->max; + tmod.neg=mod->neg; + buf[0]=mod->d[0]&BN_MASK2; + buf[1]=0; + + if ((BN_mod_inverse(&Ri,R,&tmod,ctx)) == NULL) + goto err; +#else + tmod=mod->d[0]; + rr=BN_mod_inverse_word(tmod); + if (!BN_set_word(&Ri,rr)) + goto err; +#endif + + /* R*Ri */ + if (!BN_lshift(&Ri,&Ri,BN_BITS2)) + goto err; + + if (!BN_is_zero(&Ri)) + (void)BN_sub_word(&Ri,1); + else + { + /* This is not common..., 1 in BN_MASK2, + * It happens when buf[0] was == 1. So for 8 bit, + * this is 1/256, 16bit, 1 in 2^16 etc. + */ + if (!BN_set_word(&Ri,BN_MASK2)) + goto err; + } +#if 0 + BN_div(&Ri,NULL,&Ri,&tmod,ctx); + //BN_div_word(&Ri,tmod); + mont->n0=Ri.d[0]; +#else +#if 0 + { + BN_ULONG h,l; + + h=l=0; + if (Ri.top >= 2) h=Ri.d[1]; + if (Ri.top >= 1) l=Ri.d[0]; + mont->n0=bn_div_words(h,l,tmod); + } +#endif + mont->n0=bn_div_words( + (Ri.top >= 2)?Ri.d[1]:0, + (Ri.top >= 1)?Ri.d[0]:0, + tmod); +#endif + /* mod->top=z; */ + + /* setup RR for conversions */ + (void)BN_zero(&(mont->RR)); + if (!BN_set_bit(&(mont->RR),mont->riw*2*BN_BITS2)) + goto err; + (void)BN_mod(&(mont->RR),&(mont->RR),&(mont->N),ctx); + bn_zexpand(&(mont->RR),mont->riw); +#if 0 + bn_zexpand(&(mont->Ni),mont->riw); /*This is not used? */ +#endif + +err: + BN_free(&Ri); + return(1); + } + + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_mul.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_mul.c new file mode 100644 index 0000000..76e83e7 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_mul.c @@ -0,0 +1,795 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MUL_RECURSIVE +#define SPLIT_BN_MUL_PART_RECURSIVE +#define SPLIT_BN_MUL_LOW_RECURSIVE +#define SPLIT_BN_MUL_HIGH +#define SPLIT_BN_MUL +#define SPLIT_BN_MUL_NORMAL +#define SPLIT_BN_MUL_LOW_NORMAL +#endif /* NO_SPLIT */ + +#ifdef SMALL_CODE_SIZE +#undef BN_RECURSION_MUL +#endif + +#ifdef BN_RECURSION_MUL +#if 0 /* Replaced by bn_mul_rec_words() */ +/* r is 2*n2 words in size, + * a and b are both n2 words in size. + * n2 must be a power of 2. + * We multiply and return the result. + * t must be 2*n2 words in size + * We calulate + * a[0]*b[0] + * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) + * a[1]*b[1] + */ +#ifdef SPLIT_BN_MUL_RECURSIVE +void bn_mul_recursive(r,a,b,n2,t) +BN_ULONG *r,*a,*b; +int n2; +BN_ULONG *t; + { + int n=n2/2,c1,c2; + unsigned int neg,zero; + BN_ULONG ln,lo,*p; + +#ifdef BN_COUNT +printf(" bn_mul_recursive %d * %d\n",n2,n2); +#endif +#ifdef BN_MUL_COMBA +/* if (n2 == 4) + { + bn_mul_comba4(r,a,b); + return; + } + else */ if (n2 == 8) + { + bn_mul_comba8(r,a,b); + return; + } +#endif + if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) + { + /* This should not happen */ + bn_mul_normal(r,a,n2,b,n2); + return; + } + /* r=(a[0]-a[1])*(b[1]-b[0]) */ + c1=bn_cmp_words(a,&(a[n]),n); + c2=bn_cmp_words(&(b[n]),b,n); + zero=neg=0; + switch (c1*3+c2) + { + case -4: + bn_sub_words(t, &(a[n]),a, n); /* - */ + bn_sub_words(&(t[n]),b, &(b[n]),n); /* - */ + break; + case -3: + zero=1; + break; + case -2: + bn_sub_words(t, &(a[n]),a, n); /* - */ + bn_sub_words(&(t[n]),&(b[n]),b, n); /* + */ + neg=1; + break; + case -1: + case 0: + case 1: + zero=1; + break; + case 2: + bn_sub_words(t, a, &(a[n]),n); /* + */ + bn_sub_words(&(t[n]),b, &(b[n]),n); /* - */ + neg=1; + break; + case 3: + zero=1; + break; + case 4: + bn_sub_words(t, a, &(a[n]),n); + bn_sub_words(&(t[n]),&(b[n]),b, n); + break; + } + +#ifdef BN_MUL_COMBA + if (n == 4) + { + if (!zero) + bn_mul_comba4(&(t[n2]),t,&(t[n])); + else + Memset(&(t[n2]),0,8*sizeof(BN_ULONG)); + + bn_mul_comba4(r,a,b); + bn_mul_comba4(&(r[n2]),&(a[n]),&(b[n])); + } + else if (n == 8) + { + if (!zero) + bn_mul_comba8(&(t[n2]),t,&(t[n])); + else + Memset(&(t[n2]),0,16*sizeof(BN_ULONG)); + + bn_mul_comba8(r,a,b); + bn_mul_comba8(&(r[n2]),&(a[n]),&(b[n])); + } + else +#endif + { + p= &(t[n2*2]); + if (!zero) + bn_mul_recursive(&(t[n2]),t,&(t[n]),n,p); + else + Memset(&(t[n2]),0,n2*sizeof(BN_ULONG)); + bn_mul_recursive(r,a,b,n,p); + bn_mul_recursive(&(r[n2]),&(a[n]),&(b[n]),n,p); + } + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1=(int)bn_add_words(t,r,&(r[n2]),n2); + + if (neg) /* if t[32] is negative */ + { + c1-=(int)bn_sub_words(&(t[n2]),t,&(t[n2]),n2); + } + else + { + /* Might have a carry */ + c1+=(int)bn_add_words(&(t[n2]),&(t[n2]),t,n2); + } + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + * c1 holds the carry bits + */ + c1+=(int)bn_add_words(&(r[n]),&(r[n]),&(t[n2]),n2); + if (c1) + { + p= &(r[n+n2]); + lo= *p; + ln=(lo+c1)&BN_MASK2; + *p=ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if (ln < (BN_ULONG)c1) + { + do { + p++; + lo= *p; + ln=(lo+1)&BN_MASK2; + *p=ln; + } while (ln == 0); + } + } + } +#endif +#endif + +#if 0 +#ifdef SPLIT_BN_MUL_PART_RECURSIVE +/* n+tn is the word length + * t must be n*4 is size, as does r */ +void bn_mul_part_recursive(r,a,b,tn,n,t) +BN_ULONG *r,*a,*b; +int tn,n; +BN_ULONG *t; + { + int i,j,n2=n*2; + int c1; + BN_ULONG ln,lo,*p; + +#ifdef BN_COUNT +printf(" bn_mul_part_recursive %d * %d\n",tn+n,tn+n); +#endif + if (n < 8) + { + i=tn+n; + bn_mul_normal(r,a,i,b,i); + return; + } + + /* r=(a[0]-a[1])*(b[1]-b[0]) */ + bn_sub_words(t, a, &(a[n]),n); /* + */ + bn_sub_words(&(t[n]),b, &(b[n]),n); /* - */ + +#ifdef BN_MUL_COMBA +/* if (n == 4) + { + bn_mul_comba4(&(t[n2]),t,&(t[n])); + bn_mul_comba4(r,a,b); + bn_mul_normal(&(r[n2]),&(a[n]),tn,&(b[n]),tn); + Memset(&(r[n2+tn*2]),0,sizeof(BN_ULONG)*(n2-tn*2)); + } + else */ if (n == 8) + { + bn_mul_comba8(&(t[n2]),t,&(t[n])); + bn_mul_comba8(r,a,b); + bn_mul_normal(&(r[n2]),&(a[n]),tn,&(b[n]),tn); + Memset(&(r[n2+tn*2]),0,sizeof(BN_ULONG)*(n2-tn*2)); + } + else +#endif + { + p= &(t[n2*2]); + bn_mul_recursive(&(t[n2]),t,&(t[n]),n,p); + bn_mul_recursive(r,a,b,n,p); + i=n/2; + /* If there is only a bottom half to the number, + * just do it */ + j=tn-i; + if (j == 0) + { + bn_mul_recursive(&(r[n2]),&(a[n]),&(b[n]),i,p); + Memset(&(r[n2+i*2]),0,sizeof(BN_ULONG)*(n2-i*2)); + } + else if (j > 0) /* eg, n == 16, i == 8 and tn == 11 */ + { + bn_mul_part_recursive(&(r[n2]),&(a[n]),&(b[n]), + j,i,p); + Memset(&(r[n2+tn*2]),0, + sizeof(BN_ULONG)*(n2-tn*2)); + } + else /* (j < 0) eg, n == 16, i == 8 and tn == 5 */ + { + Memset(&(r[n2]),0,sizeof(BN_ULONG)*n2); + if (tn < BN_MUL_RECURSIVE_SIZE_NORMAL) + { + bn_mul_normal(&(r[n2]),&(a[n]),tn,&(b[n]),tn); + } + else + { + for (;;) + { + i/=2; + if (i < tn) + { + bn_mul_part_recursive(&(r[n2]), + &(a[n]),&(b[n]), + tn-i,i,p); + break; + } + else if (i == tn) + { + bn_mul_recursive(&(r[n2]), + &(a[n]),&(b[n]), + i,p); + break; + } + } + } + } + } + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1=(int)bn_add_words(t,r,&(r[n2]),n2); + c1-=(int)bn_sub_words(&(t[n2]),t,&(t[n2]),n2); + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + * c1 holds the carry bits + */ + c1+=(int)bn_add_words(&(r[n]),&(r[n]),&(t[n2]),n2); + if (c1) + { + p= &(r[n+n2]); + lo= *p; + ln=(lo+c1)&BN_MASK2; + *p=ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if (ln < (BN_ULONG)c1) + { + do { + p++; + lo= *p; + ln=(lo+1)&BN_MASK2; + *p=ln; + } while (ln == 0); + } + } + } +#endif +#endif + +#if 0 +#ifdef SPLIT_BN_MUL_LOW_RECURSIVE +/* a and b must be the same size, which is n2. + * r must be n2 words and t must be n2*2 + */ +void bn_mul_low_recursive(r,a,b,n2,t) +BN_ULONG *r,*a,*b; +int n2; +BN_ULONG *t; + { + int n=n2/2; + +#ifdef BN_COUNT +printf(" bn_mul_low_recursive %d * %d\n",n2,n2); +#endif + + bn_mul_recursive(r,a,b,n,&(t[0])); + if (n >= BN_MUL_LOW_RECURSIVE_SIZE_NORMAL) + { + bn_mul_low_recursive(&(t[0]),&(a[0]),&(b[n]),n,&(t[n2])); + bn_add_words(&(r[n]),&(r[n]),&(t[0]),n); + bn_mul_low_recursive(&(t[0]),&(a[n]),&(b[0]),n,&(t[n2])); + bn_add_words(&(r[n]),&(r[n]),&(t[0]),n); + } + else + { + bn_mul_low_normal(&(t[0]),&(a[0]),&(b[n]),n); + bn_mul_low_normal(&(t[n]),&(a[n]),&(b[0]),n); + bn_add_words(&(r[n]),&(r[n]),&(t[0]),n); + bn_add_words(&(r[n]),&(r[n]),&(t[n]),n); + } + } +#endif +#endif + +#ifdef SPLIT_BN_MUL_HIGH +#if 0 +/* a and b must be the same size, which is n2. + * r must be n2 words and t must be n2*2 + * l is the low words of the output. + * t must be n2*3 + */ +void bn_mul_high(r,a,b,l,n2,t) +BN_ULONG *r,*a,*b,*l; +int n2; +BN_ULONG *t; + { + int i,n; + int c1,c2; + int neg,oneg,zero; + BN_ULONG ll,lc,*lp,*mp; + +#ifdef BN_COUNT +printf(" bn_mul_high %d * %d\n",n2,n2); +#endif + n=n2/2; + + /* Calculate (al-ah)*(bh-bl) */ + neg=zero=0; + c1=bn_cmp_words(&(a[0]),&(a[n]),n); + c2=bn_cmp_words(&(b[n]),&(b[0]),n); + switch (c1*3+c2) + { + case -4: + bn_sub_words(&(r[0]),&(a[n]),&(a[0]),n); + bn_sub_words(&(r[n]),&(b[0]),&(b[n]),n); + break; + case -3: + zero=1; + break; + case -2: + bn_sub_words(&(r[0]),&(a[n]),&(a[0]),n); + bn_sub_words(&(r[n]),&(b[n]),&(b[0]),n); + neg=1; + break; + case -1: + case 0: + case 1: + zero=1; + break; + case 2: + bn_sub_words(&(r[0]),&(a[0]),&(a[n]),n); + bn_sub_words(&(r[n]),&(b[0]),&(b[n]),n); + neg=1; + break; + case 3: + zero=1; + break; + case 4: + bn_sub_words(&(r[0]),&(a[0]),&(a[n]),n); + bn_sub_words(&(r[n]),&(b[n]),&(b[0]),n); + break; + } + + oneg=neg; + /* t[10] = (a[0]-a[1])*(b[1]-b[0]) */ + /* r[10] = (a[1]*b[1]) */ +#ifdef BN_MUL_COMBA + if (n == 8) + { + bn_mul_comba8(&(t[0]),&(r[0]),&(r[n])); + bn_mul_comba8(r,&(a[n]),&(b[n])); + } + else +#endif + { +#ifdef BN_MUL_RECURSION + bn_mul_recursive(&(t[0]),&(r[0]),&(r[n]),n,&(t[n2])); + bn_mul_recursive(r,&(a[n]),&(b[n]),n,&(t[n2])); +#else + bn_mul_normal(&(t[0]),&(r[0]),n,&(r[n]),n); + bn_mul_normal(r,&(a[n]),n,&(b[n]),n); +#endif + } + + /* s0 == low(al*bl) + * s1 == low(ah*bh)+low((al-ah)*(bh-bl))+low(al*bl)+high(al*bl) + * We know s0 and s1 so the only unknown is high(al*bl) + * high(al*bl) == s1 - low(ah*bh+s0+(al-ah)*(bh-bl)) + * high(al*bl) == s1 - (r[0]+l[0]+t[0]) + */ + if (l != NULL) + { + lp= &(t[n2+n]); + c1=(int)bn_add_words(lp,&(r[0]),&(l[0]),n); + } + else + { + c1=0; + lp= &(r[0]); + } + + if (neg) + neg=(int)bn_sub_words(&(t[n2]),lp,&(t[0]),n); + else + { + bn_add_words(&(t[n2]),lp,&(t[0]),n); + neg=0; + } + + if (l != NULL) + { + bn_sub_words(&(t[n2+n]),&(l[n]),&(t[n2]),n); + } + else + { + lp= &(t[n2+n]); + mp= &(t[n2]); + for (i=0; i 0) + { + lc=c1; + do { + ll=(r[i]+lc)&BN_MASK2; + r[i++]=ll; + lc=(lc > ll); + } while (lc); + } + else + { + lc= -c1; + do { + ll=r[i]; + r[i++]=(ll-lc)&BN_MASK2; + lc=(lc > ll); + } while (lc); + } + } + if (c2 != 0) /* Add starting at r[1] */ + { + i=n; + if (c2 > 0) + { + lc=c2; + do { + ll=(r[i]+lc)&BN_MASK2; + r[i++]=ll; + lc=(lc > ll); + } while (lc); + } + else + { + lc= -c2; + do { + ll=r[i]; + r[i++]=(ll-lc)&BN_MASK2; + lc=(lc > ll); + } while (lc); + } + } + } +#endif +#endif +#endif + +#ifdef SPLIT_BN_MUL +int BN_mul(r,a,b,ctx) +BIGNUM *r,*a,*b; +BN_CTX *ctx; + { + int top,al,bl,neg; + BIGNUM *rr; +#ifdef BN_RECURSION_MUL + BIGNUM *t; + int i,j,k,l; +#endif + +#ifdef BN_COUNT +printf("BN_mul %d * %d\n",a->top,b->top); +#endif + + bn_check_top(a); + bn_check_top(b); + bn_check_top(r); + + al=a->top; + bl=b->top; + + if ((al == 0) || (bl == 0)) + { + (void)BN_zero(r); + return(1); + } + top=al+bl; + neg=a->neg^b->neg; + + if ((r == a) || (r == b)) + rr= &(ctx->bn[ctx->tos+1]); + else + rr=r; + + if (bn_wexpand(rr,top) == NULL) return(0); + rr->top=top; + +#if defined(BN_MUL_COMBA) || defined(BN_RECURSION_MUL) + if (al == bl) + { +# ifdef BN_MUL_COMBA +/* if (al == 4) + { + bn_mul_comba4(rr->d,a->d,b->d); + goto end; + } + else */ if (al == 8) + { + bn_mul_comba8(rr->d,a->d,b->d); + goto end; + } + else +# endif +#ifdef BN_RECURSION_MUL + if (al < BN_MULL_SIZE_NORMAL) +#endif + { + bn_mul_normal(rr->d,a->d,al,b->d,bl); + goto end; + } +# ifdef BN_RECURSION_MUL + goto symetric; +# endif + } +#endif +#ifdef BN_RECURSION_MUL + else if ((al < BN_MULL_SIZE_NORMAL) || (bl < BN_MULL_SIZE_NORMAL)) + { + bn_mul_normal(rr->d,a->d,al,b->d,bl); + goto end; + } + else + { + i=(al-bl); + if ((i == 1) && !BN_get_flags(b,BN_FLG_STATIC_DATA)) + { + bn_wexpand(b,al); + b->d[bl]=0; + bl++; + goto symetric; + } + else if ((i == -1) && !BN_get_flags(a,BN_FLG_STATIC_DATA)) + { + bn_wexpand(a,bl); + a->d[al]=0; + al++; + goto symetric; + } + } +#endif + +#ifdef BN_RECURSION_MUL +normal_mul: +#endif + bn_mul_normal(rr->d,a->d,al,b->d,bl); + +#ifdef BN_RECURSION_MUL + if (0) + { +symetric: + /* symetric and > 4 */ + /* 16 or larger */ + l=BN_num_bits_word((BN_ULONG)al); + j=1<<(l-1); + k=j+j; + t= &(ctx->bn[ctx->tos]); + if (al == j) /* exact multiple */ + { + BN_REC rec; + rec.depth=l-5; + rec.n=j; + rec.mul=bn_mul_comba8; + rec.sqr=bn_sqr_comba8; + if (bn_wexpand(t,k+k) == NULL) + return(0); + if (bn_wexpand(rr,k) == NULL) + return(0); + bn_mul_rec_words(rr->d,a->d,b->d,t->d,&rec); + } + else + goto normal_mul; +#if 0 + { + bn_zexpand(a,k); + bn_zexpand(b,k); + bn_wexpand(t,k); + bn_wexpand(rr,k); + bn_mul_part_recursive(rr->d,a->d,b->d,al-j,j,t->d); + } +#endif + } +#endif +#if defined(BN_MUL_COMBA) || defined(BN_RECURSION_MUL) +end: +#endif + + r->neg=neg; + bn_fix_top(rr); + if (r != rr) (void)BN_copy(r,rr); + return(1); + } +#endif + + +#ifdef SPLIT_BN_MUL_NORMAL +void bn_mul_normal(r,a,na,b,nb) +BN_ULONG *r,*a; +int na; +BN_ULONG *b; +int nb; + { + BN_ULONG *rr; + +#ifdef BN_COUNT +printf(" bn_mul_normal %d * %d\n",na,nb); +#endif + /* asymetric and >= 4 */ +#if 0 + if ((na == nb) && (na == 8)) + { + bn_mul_normal(r,a,na,b,nb); + return; + } +#endif + + if (na < nb) + { + int itmp; + BN_ULONG *ltmp; + + itmp=na; na=nb; nb=itmp; + ltmp=a; a=b; b=ltmp; + + } + rr= &(r[na]); + rr[0]=bn_mul_words(r,a,na,b[0]); + + for (;;) + { + if (--nb <= 0) return; + rr[1]=bn_mul_add_words(&(r[1]),a,na,b[1]); + if (--nb <= 0) return; + rr[2]=bn_mul_add_words(&(r[2]),a,na,b[2]); + if (--nb <= 0) return; + rr[3]=bn_mul_add_words(&(r[3]),a,na,b[3]); + if (--nb <= 0) return; + rr[4]=bn_mul_add_words(&(r[4]),a,na,b[4]); + rr+=4; + r+=4; + b+=4; + } + } +#endif + +#ifdef SPLIT_BN_MUL_LOW_NORMAL +void bn_mul_low_normal(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { +#ifdef BN_COUNT +printf(" bn_mul_low_normal %d * %d\n",n,n); +#endif + (void)bn_mul_words(r,a,n,b[0]); + + for (;;) + { + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[1]),a,n,b[1]); + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[2]),a,n,b[2]); + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[3]),a,n,b[3]); + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[4]),a,n,b[4]); + r+=4; + b+=4; + } + } +#endif +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_r_exp.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_r_exp.c new file mode 100644 index 0000000..ef056ef --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_r_exp.c @@ -0,0 +1,150 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +/* #ifdef RECP_MUL_MOD */ +int BN_mod_exp_recp(r,a,p,m,ctx) +BIGNUM *r; +BIGNUM *a; +BIGNUM *p; +BIGNUM *m; +BN_CTX *ctx; + { + int i,j,bits,ret=0,wstart,wend,window,wvalue; + int start=1,ts=0; + BIGNUM *aa; + BIGNUM val[BN_EXP_TABLE_SIZE]; + BN_RECP_CTX recp; + + bits=BN_num_bits(p); + + if (BN_is_zero(a)) + { (void)BN_zero(r); return(1); } + if (BN_is_zero(p)) + { (void)BN_one(r); return(1); } + if (BN_is_one(p)) + { (void)BN_copy(r,a); return(1); } + + BN_RECP_CTX_init(&recp); + if (BN_RECP_CTX_set(&recp,m,ctx) <= 0) goto err; + + BN_init(&(val[0])); + ts=1; + + aa= &(ctx->bn[ctx->tos++]); + + if (!BN_mod(&(val[0]),a,m,ctx)) goto err; /* 1 */ + if (!BN_mod_mul_reciprocal(aa,&(val[0]),&(val[0]),&recp,ctx)) + goto err; /* 2 */ + + if (bits <= 17) /* This is probably 3 or 0x10001, so just do singles */ + window=1; + else if (bits >= 256) + window=5; /* max size of window */ + else if (bits >= 128) + window=4; + else + window=3; + + j=1<<(window-1); + for (i=1; i>1]),&recp,ctx)) + goto err; + + /* move the 'window' down further */ + wstart-=wend+1; + wvalue=0; + start=0; + if (wstart < 0) break; + } + ret=1; +err: + ctx->tos--; + for (i=0; in; + int n2=n/2; + int neg=0; + BN_ULONG c1; + + + if (rec->depth == 0) + { + /* t needs to have space for 4*n words + * The multiply needs to be a n2*n2 -> n + */ +#ifndef NOPROTO + void (PRE_CCONV CCONV *rmul)(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); +#else + void (PRE_CCONV CCONV *rmul)(); +#endif + rmul=rec->mul; + +#ifdef _EXTRA_ARG_ + /* THIS IS WRONG - there is no extra int arg on the end */ + rmul(&(r[0]),&(a[0]),&(b[0]),n2); + rmul(&(r[n]),&(a[n2]),&(b[n2]),n2); +#else + rmul(&(r[0]),&(a[0]),&(b[0])); + rmul(&(r[n]),&(a[n2]),&(b[n2])); +#endif + + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + { + bn_2s_comp(&(tt[n+ 0]),&(tt[n+ 0]),n2); + neg=1; + } + else + neg=0; + if (bn_sub_words(&(tt[n+n2]),&(b[n2]),&(b[0]),n2)) + { + neg^=1; + bn_2s_comp(&(tt[n+n2]),&(tt[n+n2]),n2); + } + +#ifdef _EXTRA_ARG_ + rmul(&(tt[0]),&(tt[n+0]),&(tt[n+n2]),n2); +#else + rmul(&(tt[0]),&(tt[n+0]),&(tt[n+n2])); +#endif + } + else /* Leaf node */ + { + /* t has 4*n words taken per call. + * Since n is half the size per call, we need + * 6*n words for our current level and all sub levels + * The multiply needs to be a n2*n2 -> n + */ + rec->depth--; + rec->n=n2; + bn_mul_rec_words(&(r[0]), &(a[0]), &(b[0]), &(tt[n+n]),rec); + bn_mul_rec_words(&(r[n]), &(a[n2]),&(b[n2]), &(tt[n+n]),rec); + + neg=0; + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + { + bn_2s_comp(&(tt[n+ 0]),&(tt[n+ 0]),n2); + neg=1; + } + else + neg=0; + if (bn_sub_words(&(tt[n+n2]),&(b[n2]),&(b[0]),n2)) + { + neg^=1; + bn_2s_comp(&(tt[n+n2]),&(tt[n+n2]),n2); + } + + bn_mul_rec_words(&(tt[0]),&(tt[n]),&(tt[n+n2]),&(tt[n+n]),rec); + rec->n=n; + rec->depth++; + } + + c1=bn_add_words(&(tt[n]),&(r[0]),&(r[n]),n); + + if (neg) + c1-=bn_sub_words(&(tt[0]),&(tt[n]),&(tt[0]),n); + else + c1+=bn_add_words(&(tt[0]),&(tt[n]),&(tt[0]),n); + tt[n]=c1; + c1=bn_add_words(&(r[n2]),&(r[n2]),&(tt[0]),n+1); + if (c1) + { + tt= &(r[n+n2+1]); + do { + } while (++(*(tt++)) == 0); + } + } +#endif + +#ifdef SPLIT_BN_SQR_REC_WORDS +/* tt needs to be 3*n words */ +void bn_sqr_rec_words(r,a,tt,rec) +BN_ULONG *r,*a,*tt; +BN_REC *rec; + { + int n=rec->n; + int n2=n/2; + BN_ULONG c1; + + if (rec->depth == 0) + { + /* t needs to have space for 4*n words + * The multiply needs to be a n2*n2 -> n + */ +#ifndef NOPROTO + void (PRE_CCONV CCONV *rsqr)(BN_ULONG *r, BN_ULONG *a); +#else + void (PRE_CCONV CCONV *rsqr)(); +#endif + + rsqr=rec->sqr; + +#ifdef _EXTRA_ARG_ + /* THIS IS WRONG - there is no extra int arg on the end */ + rsqr(&(r[0]), &(a[0]), n2); + rsqr(&(r[n]), &(a[n2]),n2); +#else + rsqr(&(r[0]), &(a[0])); + rsqr(&(r[n]), &(a[n2])); +#endif + + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + bn_2s_comp(&(tt[n+0]),&tt[n+0], n2); + +#ifdef _EXTRA_ARG_ + rsqr(&(tt[0]),&(tt[n]), n2); +#else + rsqr(&(tt[0]),&(tt[n])); +#endif + + } + else /* Leaf node */ + { + /* t has 4*n words taken per call. + * Since n is half the size per call, we need + * 6*n words for our current level and all sub levels + * The multiply needs to be a n2*n2 -> n + */ + rec->depth--; + rec->n=n2; + bn_sqr_rec_words(&(r[0]), &(a[0]), &(tt[n+n]),rec); + bn_sqr_rec_words(&(r[n]), &(a[n2]),&(tt[n+n]),rec); + + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + bn_2s_comp(&(tt[n+0]),&tt[n+0], n2); + bn_sqr_rec_words(&(tt[0]),&(tt[n]),&(tt[n+n]),rec); + + rec->n=n; + rec->depth++; + } + + c1=bn_add_words(&(tt[n]),&(r[0]),&(r[n]),n); + c1-=bn_sub_words(&(tt[0]),&(tt[n]),&(tt[0]),n); + + tt[n]=c1; + c1=bn_add_words(&(r[n2]),&(r[n2]),&(tt[0]),n+1); + if (c1) + { + tt= &(r[n+n2+1]); + do { + } while (++(*(tt++)) == 0); + } + } +#endif + +#endif /* !NO_SPLIT || !SPLIT_FILE */ diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_recp.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_recp.c new file mode 100644 index 0000000..6830f59 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_recp.c @@ -0,0 +1,218 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +void BN_RECP_CTX_init(recp) +BN_RECP_CTX *recp; + { + BN_init(&(recp->N)); + BN_init(&(recp->Nr)); + recp->num_bits=0; + recp->flags=0; + } + +BN_RECP_CTX *BN_RECP_CTX_new() + { + BN_RECP_CTX *ret; + + if ((ret=(BN_RECP_CTX *)Malloc(sizeof(BN_RECP_CTX))) == NULL) + return(NULL); + + BN_RECP_CTX_init(ret); + ret->flags=BN_FLG_MALLOCED; + return(ret); + } + +void BN_RECP_CTX_free(recp) +BN_RECP_CTX *recp; + { + BN_free(&(recp->N)); + BN_free(&(recp->Nr)); + if (recp->flags & BN_FLG_MALLOCED) + Free(recp); + } + +int BN_RECP_CTX_set(recp,d,ctx) +BN_RECP_CTX *recp; +BIGNUM *d; +BN_CTX *ctx; + { + (void)BN_copy(&(recp->N),d); + (void)BN_zero(&(recp->Nr)); + recp->num_bits=BN_num_bits(d); + recp->shift=0; + ctx=ctx; /* Stop warning */ + return(1); + } + +int BN_mod_mul_reciprocal(r, x, y, recp, ctx) +BIGNUM *r; +BIGNUM *x; +BIGNUM *y; +BN_RECP_CTX *recp; +BN_CTX *ctx; + { + int ret=0; + BIGNUM *a; + + bn_check_top(x); + bn_check_top(y); + + a= &(ctx->bn[ctx->tos++]); + if (y != NULL) + { + if (x == y) + { if (!BN_sqr(a,x,ctx)) goto err; } + else + { if (!BN_mul(a,x,y,ctx)) goto err; } + } + else + a=x; /* Just do the mod */ + + (void)BN_div_recp(NULL,r,a,recp,ctx); + ret=1; +err: + ctx->tos--; + return(ret); + } + +int BN_div_recp(dv,rem,m,recp,ctx) +BIGNUM *dv; +BIGNUM *rem; +BIGNUM *m; +BN_RECP_CTX *recp; +BN_CTX *ctx; + { + int i,j,tos,ret=0,ex; + BIGNUM *a,*b,*d,*r; + + bn_check_top(m); + + tos=ctx->tos; + a= &(ctx->bn[ctx->tos++]); + b= &(ctx->bn[ctx->tos++]); + if (dv != NULL) + d=dv; + else + d= &(ctx->bn[ctx->tos++]); + if (rem != NULL) + r=rem; + else + r= &(ctx->bn[ctx->tos++]); + + if (BN_ucmp(m,&(recp->N)) < 0) + { + (void)BN_zero(d); + (void)BN_copy(r,m); + ctx->tos=tos; + return(1); + } + + /* We want the remainder + * Given input of ABCDEF / ab + * we need multiply ABCDEF by 3 digests of the reciprocal of ab + * + */ + i=BN_num_bits(m); + + j=recp->num_bits*2; + if (j > i) + { + i=j; + ex=0; + } + else + { + ex=(i-j)/2; + } + + j=i/2; + + if (i != recp->shift) + recp->shift=BN_reciprocal(&(recp->Nr),&(recp->N), + i,ctx); + + if (!BN_rshift(a,m,j-ex)) goto err; + if (!BN_mul(b,a,&(recp->Nr),ctx)) goto err; + if (!BN_rshift(d,b,j+ex)) goto err; + d->neg=0; + if (!BN_mul(b,&(recp->N),d,ctx)) goto err; + if (!BN_usub(r,m,b)) goto err; + r->neg=0; + + j=0; +#if 1 + while (BN_ucmp(r,&(recp->N)) >= 0) + { + if (j++ > 2) + { +#ifndef NO_ERR + BNerr(BN_F_BN_DIV_RECP,BN_R_BAD_RECIPROCAL); +#endif + goto err; + } + if (!BN_usub(r,r,&(recp->N))) goto err; + if (!BN_add_word(d,1)) goto err; + } +#endif + + r->neg=BN_is_zero(r)?0:m->neg; + d->neg=m->neg^recp->N.neg; + ret=1; +err: + ctx->tos=tos; + return(ret); + } + +/* len is the expected size of the result + * We actually calculate with an extra word of precision, so + * we can do faster division if the remainder is not required. + */ +int BN_reciprocal(r,m,len,ctx) +BIGNUM *r; +BIGNUM *m; +int len; +BN_CTX *ctx; + { + int ret= -1; + BIGNUM t; + + bn_check_top(m); + + BN_init(&t); + + (void)BN_zero(&t); + if (!BN_set_bit(&t,len)) goto err; + + if (!BN_div(r,NULL,&t,m,ctx)) goto err; + ret=len; +err: + BN_free(&t); + return(ret); + } + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_rsh.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_rsh.c new file mode 100644 index 0000000..0f0d5c6 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_rsh.c @@ -0,0 +1,139 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_RSHIFT1 +#define SPLIT_BN_RSHIFT +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_RSHIFT1 +#ifdef SMALL_CODE_SIZE +int BN_rshift1(r, a) +BIGNUM *r; +BIGNUM *a; + { + return(BN_rshift(r,a,1)); + } + +#else + +int BN_rshift1(r, a) +BIGNUM *r; +BIGNUM *a; + { + BN_ULONG *ap,*rp,t,c; + int i; + + bn_check_top(a); + + if (BN_is_zero(a)) + { + BN_zero(r); + return(1); + } + if (a != r) + { + if (bn_wexpand(r,a->top) == NULL) return(0); + r->top=a->top; + r->neg=a->neg; + } + ap=a->d; + rp=r->d; + c=0; + for (i=a->top-1; i>=0; i--) + { + t=ap[i]; + rp[i]=((t>>1)&BN_MASK2)|c; + c=(t&1)?BN_TBIT:0; + } + bn_fix_top(r); + return(1); + } +#endif +#endif + +#ifdef SPLIT_BN_RSHIFT +int BN_rshift(r, a, n) +BIGNUM *r; +BIGNUM *a; +int n; + { + int i,j,nw,lb,rb; + BN_ULONG *t,*f; + BN_ULONG l,tmp; + + bn_check_top(a); + +#ifndef SMALL_CODE_SIZE + if (n == 1) return(BN_rshift1(r,a)); +#endif + nw=n/BN_BITS2; + rb=n%BN_BITS2; + lb=BN_BITS2-rb; + if (nw > a->top) + { + (void)BN_zero(r); + return(1); + } + if (r != a) + { + if (bn_wexpand(r,a->top-nw+1+1/*???*/) == NULL) return(0); + r->neg=a->neg; + } + + f= &(a->d[nw]); + t=r->d; + j=a->top-nw; + r->top=j; + + if (rb == 0) + { + for (i=j+1; i > 0; i--) + *(t++)= *(f++); + } + else + { + l= *(f++); + for (i=1; i>rb)&BN_MASK2; + l= *(f++); + *(t++) =(tmp|(l<>rb)&BN_MASK2; + *t=0; + } + bn_fix_top(r); + return(1); + } +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_sqr.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_sqr.c new file mode 100644 index 0000000..24b5c4c --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_sqr.c @@ -0,0 +1,289 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#ifdef SMALL_CODE_SIZE +#undef BN_RECURSION_SQR +#endif + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_SQR +#define SPLIT_BN_SQR_NORMAL +#define SPLIT_BN_RECURSION_SQR +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_SQR +/* r must not be a */ +int BN_sqr(r, a, ctx) +BIGNUM *r; +BIGNUM *a; +BN_CTX *ctx; + { + int max,al; + BIGNUM *tmp,*rr; + +#ifdef BN_COUNT +printf("BN_sqr %d * %d\n",a->top,a->top); +#endif + bn_check_top(a); + tmp= &(ctx->bn[ctx->tos]); + rr=(a != r)?r: (&ctx->bn[ctx->tos+1]); + + al=a->top; + if (al <= 0) + { + r->top=0; + return(1); + } + + max=(al+al); + if (bn_wexpand(rr,max) == NULL) return(0); + + rr->top=max; + rr->neg=0; + + if (al == 4) + { +#ifndef BN_SQR_COMBA + BN_ULONG t[8]; + bn_sqr_normal(rr->d,a->d,4,t); +#else + bn_sqr_comba4(rr->d,a->d); +#endif + } + else if (al == 8) + { +#ifndef BN_SQR_COMBA + BN_ULONG t[16]; + bn_sqr_normal(rr->d,a->d,8,t); +#else + bn_sqr_comba8(rr->d,a->d); +#endif + } + else + { +#if 1 && defined(BN_RECURSION_SQR) + if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) + { + BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL*2]; + bn_sqr_normal(rr->d,a->d,al,t); + } + else + { + int j,l,k; + + l=BN_num_bits_word((BN_ULONG)al); + j=1<<(l-1); + k=j+j; + if ((al == j) && !BN_get_flags(a,BN_FLG_STATIC_DATA)) + { + BN_REC rec; + if (bn_wexpand(tmp,k*2) == NULL) return(0); + rec.depth=l-5; + rec.n=j; + rec.mul=bn_mul_comba8; + rec.sqr=bn_sqr_comba8; + + bn_sqr_rec_words(rr->d,a->d,tmp->d,&rec); + } + else + { + if (bn_wexpand(tmp,max) == NULL) return(0); + bn_assert(al*2 <= max); + bn_sqr_normal(rr->d,a->d,al,tmp->d); + } + } +#else + if (bn_wexpand(tmp,max) == NULL) return(0); + bn_assert(al*2 <= max); + bn_sqr_normal(rr->d,a->d,al,tmp->d); +#endif +#ifdef BN_DEBUG + tmp->top=0; +#endif + } + + if ((max > 0) && (rr->d[max-1] == 0)) rr->top--; + if (rr != r) (void)BN_copy(r,rr); + return(1); + } +#endif + +#ifdef SPLIT_BN_SQR_NORMAL +/* tmp must have 2*n words */ +void bn_sqr_normal(r, a, n, tmp) +BN_ULONG *r; +BN_ULONG *a; +int n; +BN_ULONG *tmp; + { + int i,j,max; + BN_ULONG *ap,*rp,m; + + max=n*2; + ap=a; + rp=r; + rp[0]=rp[max-1]=0; + rp++; + j=n; + + if (--j > 0) + { + m= (*ap++); + rp[j]=bn_mul_words(rp,ap,j,m); + rp+=2; + } + + for (i=n-2; i>0; i--) + { + j--; + m= *(ap++); + rp[j]=bn_mul_add_words(rp,ap,j,m); + rp+=2; + } + + (void)bn_add_words(r,r,r,max); + + /* There will not be a carry */ + + bn_sqr_words(tmp,a,n); + + (void)bn_add_words(r,r,tmp,max); + } +#endif + +#if 0 /* replaced by bn_sqr_rec_words() AND this has bugs */ +#ifdef SPLIT_BN_RECURSION_SQR +#ifdef BN_RECURSION_SQR +/* r is 2*n words in size, + * a and b are both n words in size. + * n must be a power of 2. + * We multiply and return the result. + * t must be 2*n words in size + * We calulate + * a[0]*b[0] + * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) + * a[1]*b[1] + */ +void bn_sqr_recursive(r,a,n2,t) +BN_ULONG *r,*a; +int n2; +BN_ULONG *t; + { + int n=n2/2; + int zero,c1; + BN_ULONG ln,lo,*p; + +#ifdef BN_COUNT +printf(" bn_sqr_recursive %d * %d\n",n2,n2); +#endif + if (n2 == 4) + { +#ifndef BN_SQR_COMBA + bn_sqr_normal(r,a,4,t); +#else + bn_sqr_comba4(r,a); +#endif + return; + } + else if (n2 == 8) + { +#ifndef BN_SQR_COMBA + bn_sqr_normal(r,a,8,t); +#else + bn_sqr_comba8(r,a); +#endif + return; + } + if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) + { + bn_sqr_normal(r,a,n2,t); + return; + } + /* r=(a[0]-a[1])*(a[1]-a[0]) */ + c1=bn_cmp_words(a,&(a[n]),n); + zero=0; + if (c1 > 0) + bn_sub_words(t,a,&(a[n]),n); + else if (c1 < 0) + bn_sub_words(t,&(a[n]),a,n); + else + zero=1; + + /* The result will always be negative unless it is zero */ + p= &(t[n2*2]); + + if (!zero) + bn_sqr_recursive(&(t[n2]),t,n,p); + else + Memset(&(t[n2]),0,n*sizeof(BN_ULONG)); + bn_sqr_recursive(r,a,n,p); + bn_sqr_recursive(&(r[n2]),&(a[n]),n,p); + + /* t[32] holds (a[0]-a[1])*(a[1]-a[0]), it is negative or zero + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1=(int)(bn_add_words(t,r,&(r[n2]),n2)); + + /* t[32] is negative */ + c1-=(int)(bn_sub_words(&(t[n2]),t,&(t[n2]),n2)); + + /* t[32] holds (a[0]-a[1])*(a[1]-a[0])+(a[0]*a[0])+(a[1]*a[1]) + * r[10] holds (a[0]*a[0]) + * r[32] holds (a[1]*a[1]) + * c1 holds the carry bits + */ + c1+=(int)(bn_add_words(&(r[n]),&(r[n]),&(t[n2]),n2)); + if (c1) + { + p= &(r[n+n2]); + lo= *p; + ln=(lo+c1)&BN_MASK2; + *p=ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if (ln < (BN_ULONG)c1) + { + do { + p++; + lo= *p; + ln=(lo+1)&BN_MASK2; + *p=ln; + } while (ln == 0); + } + } + } +#endif +#endif +#endif +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/bn_wdiv.c b/build/libraries_sysmenu/acsign/ARM9/src/bn_wdiv.c new file mode 100644 index 0000000..97c2186 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/bn_wdiv.c @@ -0,0 +1,116 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#ifndef OPT_BN_ASM + +#ifndef BN_DIV_WORDS +#define BN_DIV_WORDS +#endif + +#endif + +#ifdef BN_DIV_WORDS +#if defined(BN_LLONG) +BN_ULONG bn_div_words(h,l,d) +BN_ULONG h,l,d; + { + return((BN_ULONG)(((((BN_ULLONG)h)< ((BN_ULONG)1)<= d) h-=d; + + if (i) + { + d=(d<>(BN_BITS2-i)))&BN_MASK2; + l=(l<>BN_BITS4)&BN_MASK2lh; + dl=(d&BN_MASK2l); + for (;;) + { + if ((h>>BN_BITS4) == dh) + q=BN_MASK2l; + else + q=h/dh; + + for (;;) + { + t=(h-q*dh)&BN_MASK2; + if ((t&BN_MASK2h) || + (((dl*q)&BN_MASK2) <= (( + (t<>BN_BITS4)&BN_MASK2lh))&BN_MASK2))) + break; + q--; + } + th=(q*dh)&BN_MASK2; + tl=(q*dl)&BN_MASK2; + t=(tl>>BN_BITS4); + tl=(tl&BN_MASK2lh)<>BN_BITS4))&BN_MASK2; + l=(l&BN_MASK2l)<top-1; i>=0; i--) + { +#ifndef BN_LLONG + ret=((ret<d[i]>>BN_BITS4)&BN_MASK2l))%w; + ret=((ret<d[i]&BN_MASK2l))%w; +#else + ret=(BN_ULLONG)(((ret<<(BN_ULLONG)BN_BITS2)|a->d[i])% + (BN_ULLONG)w); +#endif + } + return((BN_ULONG)ret); + } +#endif + +#ifdef SPLIT_BN_DIV_WORD +BN_ULONG BN_div_word(a, w) +BIGNUM *a; +BN_ULONG w; + { + BN_ULONG ret; + int i; + + if (a->top == 0) return(0); + ret=0; + w=w&BN_MASK2;//w&=BN_MASK2; + for (i=a->top-1; i>=0; i--) + { + BN_ULONG l,d; + + l=a->d[i]; + d=bn_div_words(ret,l,w); + ret=(l-((d*w)&BN_MASK2))&BN_MASK2; + a->d[i]=d; + } + if ((a->top > 0) && (a->d[a->top-1] == 0)) + a->top--; + return(ret); + } +#endif + +#ifdef SPLIT_BN_ADD_WORD +int BN_add_word(a, w) +BIGNUM *a; +BN_ULONG w; + { + BN_ULONG l; + int i; + + if (w == 0) return(1); + bn_check_top(a); + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->neg) + { + if(a->top > 1) + { + a->neg=0; + i=BN_sub_word(a,w); + a->neg=1; + return(i); + } + else + { /* a->top == 1, it cannot be 0 */ + l=a->d[0]; + if (l > w) + a->d[0]=l-w; + else if (l < w) + { + a->neg=0; + a->d[0]=w-l; + } + else + { + a->neg=0; + a->top=0; + } + return(1); + } + } + w=w&BN_MASK2;//w&=BN_MASK2; + if (bn_wexpand(a,a->top+1) == NULL) return(0); + a->d[a->top]=0; + i=0; + for (;;) + { + l=(a->d[i]+(BN_ULONG)w)&BN_MASK2; + a->d[i]=l; + if (w > l) + w=1; + else + break; + i++; + } + if (i >= a->top) + a->top++; + return(1); + } +#endif + +#ifdef SPLIT_BN_SUB_WORD +int BN_sub_word(a, w) +BIGNUM *a; +BN_ULONG w; + { + int i; + + bn_check_top(a); + if (w == 0) return(1); + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->neg) + { + a->neg=0; + i=BN_add_word(a,w); + a->neg=1; + return(i); + } + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->top <= 1) + { + BN_ULONG l; + + if (a->top == 0) + { + if (bn_wexpand(a,1) == NULL) return(0); + a->d[0]=w; + a->neg = 1; + a->top = 1; + return(1); + } + l=a->d[0]; + if (l == w) + a->top=0; + else if (l > w) + a->d[0]=l-w; + else + { + a->neg=1; + a->d[0]=w-l; + } + return(1); + } + i=0; + for (;;) + { + if (a->d[i] >= w) + { + a->d[i]-=w; + break; + } + else + { + a->d[i]=(a->d[i]-w)&BN_MASK2; + i++; + w=1; + } + } + if ((a->d[i] == 0) && (i == (a->top-1))) + a->top--; + return(1); + } +#endif + +#ifdef SPLIT_BN_MUL_WORD +int BN_mul_word(a,w) +BIGNUM *a; +BN_ULONG w; + { + BN_ULONG ll; + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->top) + { + ll=bn_mul_words(a->d,a->d,a->top,w); + if (ll) + { + if (bn_wexpand(a,a->top+1) == NULL) return(0); + a->d[a->top++]=ll; + } + } + return(1); + } +#endif + +#endif diff --git a/build/libraries_sysmenu/acsign/ARM9/src/main.c b/build/libraries_sysmenu/acsign/ARM9/src/main.c new file mode 100644 index 0000000..d0d591b --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/main.c @@ -0,0 +1,320 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*/ +#include +#include + +#include "acsign.h" +#include "acmemory.h" + +/*---------------------------------------------------------------------------*/ +unsigned long binarray[ 1024 * 1024 * 2 / sizeof (unsigned long) ]; +unsigned long keyarray[ 1024 / sizeof (unsigned long) ]; +unsigned long sgnarray[ 1024 / sizeof (unsigned long) ]; +unsigned long bufferA[ ACSIGN_BUFFER / sizeof (unsigned long) ]; +unsigned long bufferB[ ACSIGN_BUFFER / sizeof (unsigned long) ]; + + + +/*--------------------------------------------------------------------------*/ +// ROMwb_ +//---------------------------------------------------------------------- +typedef struct { + // + // 0x000 System Reserved + // + char title_name[12]; // Soft title name + u32 game_code; // Game code + + u16 maker_code; // Maker code + u8 machine_code; // Machine code + u8 rom_type; // Rom type + u8 rom_size; // Rom size + + u8 reserved_A[9]; // System Reserved A ( Set ALL 0 ) + u8 soft_version; // Soft version + + u8 comp_arm9_boot_area:1; // Compress arm9 boot area + u8 comp_arm7_boot_area:1; // Compress arm7 boot area + u8 inspectCard:1; // J[htO + u8 disableClearMemoryPad:1; // IPL2pbhNAEfBZ[utO + u8 :0; + + + // + // 0x020 for Static modules (Section:B) + // + // ARM9 + u32 main_rom_offset; // ROM offset + void* main_entry_address; // Entry point + void* main_ram_address; // RAM address + u32 main_size; // Module size + + // ARM7 + u32 sub_rom_offset; // ROM offset + void* sub_entry_address; // Entry point + void* sub_ram_address; // RAM address + u32 sub_size; // Module size + + // + // 0x040 for File Name Table[FNT] (Section:C) + // + u32 fnt_offset; // ROM offset + u32 fnt_size; // Table size + + // + // 0x048 for File Allocation Table[FAT] (Section:E) + // + u32 fat_offset; // ROM offset + u32 fat_size; // Table size + + // + // 0x050 for Overlay Tables[OVT] (Section:D) + // + // ARM9 + u32 main_ovt_offset; // ROM offset + u32 main_ovt_size; // Table size + + // ARM7 + u32 sub_ovt_offset; // ROM offset + u32 sub_ovt_size; // Table size + + // 0x060 for ROM control parameter + u8 reserved_A2[32]; + + // 0x080 - 0x0C0 System Reserved + u8 reserved_B[64]; // System Reserved B (Set 0) + + // 0x0C0 for NINTENDO logo data + u8 nintendo_logo[0x9c]; // NINTENDO logo data + u16 nintendo_logo_crc16; // CRC-16 + + // 0x15E ROM header CRC-16 + u16 header_crc16; // ROM header CRC-16 +} RomHeader; + + +/* V-blank callback */ +static void VBlankIntr(void) +{ + OS_SetIrqCheckFlag(OS_IE_V_BLANK); +} + + + + + +/*---------------------------------------------------------------------------* + Name: InitializeAllocateSystem + + Description: C̃A[iɂăăVXeB + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +static void InitializeAllocateSystem(void) +{ + void* tempLo; + OSHeapHandle hh; + + // OS_Init͌Ă΂ĂƂO + tempLo = OS_InitAlloc( + OS_ARENA_MAIN , + OS_GetMainArenaLo() , + OS_GetMainArenaHi() , + 1 + ); + OS_SetArenaLo( + OS_ARENA_MAIN , + tempLo + ); + hh = OS_CreateHeap( + OS_ARENA_MAIN , + OS_GetMainArenaLo() , + OS_GetMainArenaHi() + ); + if( hh < 0 ) + { + OS_Panic("ARM9: Fail to create heap...\n"); + } + hh = OS_SetCurrentHeap( + OS_ARENA_MAIN , + hh + ); +} + + +// +static +void TestAC(char* iplfile, char* srlfile, char* sgnfile, FSFile* pfile ) +{ + RomHeader* pHeader; + const char* path; + BOOL fresult; + void* srl_ptr = 0; + long srl_len = 0; + void* key_ptr = 0; + long key_len = 0; + void* sgn_ptr = 0; + long sgn_len = 0; + + + if ( !pfile ) return ; + if ( !iplfile ) return ; + if ( !srlfile ) return ; + if ( !sgnfile ) return ; + + path = iplfile; + if ( (fresult = FS_OpenFile(pfile, path)) ) + { + key_len = FS_ReadFile( pfile, keyarray, sizeof keyarray ); + key_ptr = keyarray; + fresult = FS_CloseFile( pfile ); + } + if ( !fresult ) + OS_Printf("file read error! %s\n", path ); + + path = srlfile; + if ( (fresult = FS_OpenFile(pfile, path)) ) + { + srl_len = FS_ReadFile( pfile, binarray, sizeof binarray ); + srl_ptr = binarray; + fresult = FS_CloseFile( pfile ); + } + if ( !fresult ) + OS_Printf("file read error! %s\n", path ); + + path = sgnfile; //"/data/sgn0.bin"; // sgn + if ( (fresult = FS_OpenFile(pfile, path)) ) + { + sgn_len = FS_ReadFile( pfile, sgnarray, sizeof sgnarray ); + sgn_ptr = sgnarray; + fresult = FS_CloseFile( pfile ); + } + if ( !fresult ) + OS_Printf("file read error! %s\n", path ); + + // F + if ( srl_ptr && srl_len && key_ptr && key_len && sgn_ptr && sgn_len ) + { + long nSerial = 0; + pHeader = (RomHeader*)binarray; + + MI_CpuFill8( bufferA, 0, sizeof bufferA ); + MI_CpuFill8( bufferB, 0, sizeof bufferB ); + #if 0 + HMAC/Digtal Signature + >char seg_id[2]; //->"ac"ɌŒ + >u16 version; //-> 1ɌŒ + >u8 auth_code[20]/digital_sign[128] + >long serial_number + >char title_name[12]; // RomHeader.title_name + >u32 game_code; // RomHeader.game_code + >u16 maker_code; // RomHeader.make_code + >u8 machine_code; // RomHeader.machine_code + #endif + ((unsigned char*)&nSerial)[0] = ((unsigned char*)sgn_ptr + 4 + 128)[0]; + ((unsigned char*)&nSerial)[1] = ((unsigned char*)sgn_ptr + 4 + 128)[1]; + ((unsigned char*)&nSerial)[2] = ((unsigned char*)sgn_ptr + 4 + 128)[2]; + ((unsigned char*)&nSerial)[3] = ((unsigned char*)sgn_ptr + 4 + 128)[3]; + + (void)ACSign_Decrypto( bufferA, + (char*)sgn_ptr + 4, // t@C̈Í͂ւ̃ItZbgvX + (char*)key_ptr + 16 ); // PCMOD݂̂̃t@CɑΉ+16sv + + (void)ACSign_Digest( bufferB, + srl_ptr, + (char*)srl_ptr + pHeader->main_rom_offset, + pHeader->main_size, + (char*)srl_ptr + pHeader->sub_rom_offset, + pHeader->sub_size, + nSerial ); + + if ( ACSign_Compare( bufferA, bufferB ) ) + { + OS_Printf( "Authentication_Code test : success! [%12s %12s] \n", srlfile, sgnfile ); + } + else + { + OS_Printf( "Authentication_Code test : failure! [%12s %12s]\n", srlfile, sgnfile ); + } + + } + else + { + OS_Printf( "no test\n" ); + } + + OS_PrintServer(); +} + + +void NitroMain(void) +{ + FSFile file; + + + OS_InitPrintServer(); + OS_Init(); + OS_InitThread(); + InitializeAllocateSystem(); + + OS_SetIrqFunction(OS_IE_V_BLANK, VBlankIntr); + (void)OS_EnableIrqMask(OS_IE_V_BLANK); + (void)OS_EnableIrqMask(OS_IE_FIFO_RECV); + (void)OS_EnableIrq(); + + if ( sizeof (int ) < sizeof ( long ) ) + OS_Printf( "sizeof (int ) != sizeof ( long )\n" ); + if ( sizeof ( RomHeader ) != 0x0160 ) + OS_Printf( "sizeof ( RomHeader ) != 0x0160\n" ); + + /* initialize file-system */ + FS_Init( (u32)MI_DMA_MAX_NUM ); /* use DMA-3 for FS */ + + /* always preload FS table for faster directory access. */ + { + u32 need_size = FS_GetTableSize(); + void *p_table = OS_Alloc(need_size); + SDK_ASSERT(p_table != NULL); + (void)FS_LoadTable(p_table, need_size); + } + + // t@Cǂݍ + FS_InitFile(&file); + //TestAC( "/data/iplpub.bin", "/data/main.srl", "/data/sgn.bin", &file ); + + TestAC( "/data/iplpub.bin", "/data/main0.srl", "/data/sgn0.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main1.srl", "/data/sgn1.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main2.srl", "/data/sgn2.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main3.srl", "/data/sgn3.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main4.srl", "/data/sgn4.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main5.srl", "/data/sgn5.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main6.srl", "/data/sgn6.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main7.srl", "/data/sgn7.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main0.srl", "/data/sgn7.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main3.srl", "/data/sgn1.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main5.srl", "/data/sgn5.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main1.srl", "/data/sgn0.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main0.srl", "/data/sgn1.bin", &file ); + TestAC( "/data/iplpub.bin", "/data/main0.srl", "/data/sgn0.bin", &file ); + + OS_Terminate(); +} + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/md5.c b/build/libraries_sysmenu/acsign/ARM9/src/md5.c new file mode 100644 index 0000000..9b89e56 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/md5.c @@ -0,0 +1,412 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* MD5C.C - RSA Data Security, Inc., MD5 message-digest algorithm + */ + +/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All +rights reserved. + +License to copy and use this software is granted provided that it +is identified as the "RSA Data Security, Inc. MD5 Message-Digest +Algorithm" in all material mentioning or referencing this software +or this function. + +License is also granted to make and use derivative works provided +that such works are identified as "derived from the RSA Data +Security, Inc. MD5 Message-Digest Algorithm" in all material +mentioning or referencing the derived work. + +RSA Data Security, Inc. makes no representations concerning either +the merchantability of this software or the suitability of this +software for any particular purpose. It is provided "as is" +without express or implied warranty of any kind. + +These notices must be retained in any copies of any part of this +documentation and/or software. + */ + +#include "md5.h" + +/* Constants for MD5Transform routine. */ + +#define S11 7 +#define S12 12 +#define S13 17 +#define S14 22 +#define S21 5 +#define S22 9 +#define S23 14 +#define S24 20 +#define S31 4 +#define S32 11 +#define S33 16 +#define S34 23 +#define S41 6 +#define S42 10 +#define S43 15 +#define S44 21 + +static void MD5Transform(unsigned long [4], unsigned char [64]); +static void Encode(unsigned char *, unsigned long *, unsigned int); +static void Decode(unsigned long *, unsigned char *, unsigned int); +static void MD5_memcpy(unsigned char*, unsigned char*, unsigned int); +static void MD5_memset(unsigned char*, int, unsigned int); + +static unsigned char PADDING[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +/* F, G, H and I are basic MD5 functions. + */ +#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) +#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | (~z))) + +/* ROTATE_LEFT rotates x left n bits. + */ +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) + +/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. + Rotation is separate from addition to prevent recomputation. + */ +#define FF(a, b, c, d, x, s, ac) { \ + (a) += F ((b), (c), (d)) + (x) + (unsigned long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define GG(a, b, c, d, x, s, ac) { \ + (a) += G ((b), (c), (d)) + (x) + (unsigned long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define HH(a, b, c, d, x, s, ac) { \ + (a) += H ((b), (c), (d)) + (x) + (unsigned long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } +#define II(a, b, c, d, x, s, ac) { \ + (a) += I ((b), (c), (d)) + (x) + (unsigned long)(ac); \ + (a) = ROTATE_LEFT ((a), (s)); \ + (a) += (b); \ + } + +/* MD5 initialization. Begins an MD5 operation, writing a new context. + */ +void MD5Init(context) +MD5_CTX *context; /* context */ +{ + context->count[0] = context->count[1] = 0; + /* Load magic initialization constants. */ + context->state[0] = 0x67452301; + context->state[1] = 0xefcdab89; + context->state[2] = 0x98badcfe; + context->state[3] = 0x10325476; +} + +/* MD5 block update operation. Continues an MD5 message-digest + operation, processing another message block, and updating the + context. + */ +void MD5Update(context, input, inputLen) +MD5_CTX *context; /* context */ +unsigned char *input; /* input block */ +unsigned int inputLen; /* length of input block */ +{ + unsigned int i, index, partLen; + + /* Compute number of bytes mod 64 */ + index = (unsigned int)((context->count[0] >> 3) & 0x3F); + + /* Update number of bits */ + if ((context->count[0] += ((unsigned long)inputLen << 3)) < ((unsigned long)inputLen << 3)) + context->count[1]++; + context->count[1] += ((unsigned long)inputLen >> 29); + + partLen = 64 - index; + + /* Transform as many times as possible. */ + if (inputLen >= partLen) { + MD5_memcpy((unsigned char*)&context->buffer[index], (unsigned char*)input, partLen); + MD5Transform (context->state, context->buffer); + + for (i = partLen; i + 63 < inputLen; i += 64) + MD5Transform (context->state, &input[i]); + + index = 0; + } + else + i = 0; + + /* Buffer remaining input */ + MD5_memcpy((unsigned char*)&context->buffer[index], (unsigned char*)&input[i], inputLen-i); +} + +/* MD5 finalization. Ends an MD5 message-digest operation, writing the + the message digest and zeroizing the context. + */ +void MD5Final(digest, context) +unsigned char digest[16]; /* message digest */ +MD5_CTX *context; /* context */ +{ + unsigned char bits[8]; + unsigned int index, padLen; + + /* Save number of bits */ + Encode (bits, context->count, 8); + + /* Pad out to 56 mod 64. */ + index = (unsigned int)((context->count[0] >> 3) & 0x3f); + padLen = (index < 56) ? (56 - index) : (120 - index); + MD5Update (context, PADDING, padLen); + + /* Append length (before padding) */ + MD5Update (context, bits, 8); + + /* Store state in digest */ + Encode (digest, context->state, 16); + + /* Zeroize sensitive information. */ + MD5_memset ((unsigned char*)context, 0, sizeof (*context)); +} + +/* MD5 basic transformation. Transforms state based on block. + */ +static void MD5Transform (state, block) +unsigned long state[4]; +unsigned char block[64]; +{ + unsigned long a = state[0], b = state[1], c = state[2], d = state[3], x[16]; + + Decode (x, block, 64); + + /* Round 1 */ + FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ + FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ + FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ + FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ + FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ + FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ + FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ + FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ + FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ + FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ + FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + + /* Round 2 */ + GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ + GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ + GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ + GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ + GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ + GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ + GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ + GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ + GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ + GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ + GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + + /* Round 3 */ + HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ + HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ + HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ + HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ + HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ + HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ + HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ + HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ + HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ + HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + + /* Round 4 */ + II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ + II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ + II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ + II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ + II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ + II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ + II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ + II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ + II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ + II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + + /* Zeroize sensitive information. */ + MD5_memset ((unsigned char*)x, 0, sizeof (x)); +} + +/* Encodes input (unsigned long) into output (unsigned char). Assumes len is + a multiple of 4. + */ +static void Encode(output, input, len) +unsigned char *output; +unsigned long *input; +unsigned int len; +{ + unsigned int i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) { + output[j ] = (unsigned char)( input[i] & 0xff); + output[j+1] = (unsigned char)((input[i] >> 8) & 0xff); + output[j+2] = (unsigned char)((input[i] >> 16) & 0xff); + output[j+3] = (unsigned char)((input[i] >> 24) & 0xff); + } +} + +/* Decodes input (unsigned char) into output (unsigned long). Assumes len is + a multiple of 4. + */ +static void Decode(output, input, len) +unsigned long *output; +unsigned char *input; +unsigned int len; +{ + unsigned int i, j; + + for (i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((unsigned long)input[j]) | (((unsigned long)input[j+1]) << 8) | + (((unsigned long)input[j+2]) << 16) | (((unsigned long)input[j+3]) << 24); +} + +/* Note: Replace "for loop" with standard memcpy if possible. + */ + +static void MD5_memcpy(output, input, len) +unsigned char* output; +unsigned char* input; +unsigned int len; +{ + unsigned int i; + + for (i = 0; i < len; i++) + output[i] = input[i]; +} + +/* Note: Replace "for loop" with standard memset if possible. + */ +static void MD5_memset(output, value, len) +unsigned char* output; +int value; +unsigned int len; +{ + unsigned int i; + + for (i = 0; i < len; i++) + ((char *)output)[i] = (char)value; +} + + + + +////////////////////////////////////////////////////////////////////////////// +#if defined( MD5_TEST ) + +#include + +char* samplearray[ 7 ] = +{ + "", + "a", + "abc", + "message digest", + "abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "1234567890" // x8 +}; + +char* resultarray[ 7 ] = +{ + "\xD4\x1D\x8C\xD9\x8F\x00\xB2\x04\xE9\x80\x09\x98\xEC\xF8\x42\x7E", + "\x0C\xC1\x75\xB9\xC0\xF1\xB6\xA8\x31\xC3\x99\xE2\x69\x77\x26\x61", + "\x90\x01\x50\x98\x3C\xD2\x4F\xB0\xD6\x96\x3F\x7D\x28\xE1\x7F\x72", + "\xF9\x6B\x69\x7D\x7C\xB7\x93\x8D\x52\x5A\x2F\x31\xAA\xF1\x61\xD0", + "\xC3\xFC\xD3\xD7\x61\x92\xE4\x00\x7D\xFB\x49\x6C\xCA\x67\xE1\x3B", + "\xD1\x74\xAB\x98\xD2\x77\xD9\xF5\xA5\x61\x1C\x2C\x9F\x41\x9D\x9F", + "\x57\xED\xF4\xA2\x2B\xE3\xC9\x55\xAC\x49\xDA\x2E\x21\x07\xB6\x7A" +}; + +int repeatarray[ 7 ] = +{ + 1, + 1, + 1, + 1, + 1, + 1, + 8 +}; + +int MD5Test( ) +{ + MD5_CTX context; + unsigned char digest[16]; + int i, j, error; + + error = 0; + for ( j = 0; j < 7; j++ ) + { + MD5Init(&context); + + for ( i = 0; i < repeatarray[j]; i++ ) + { + MD5Update (&context, + (unsigned char*)samplearray[j], + (unsigned int)strlen( samplearray[j]) ); + } + + MD5Final(digest, &context); + + error = memcmp( digest, resultarray[j], 16 ); + + if ( error ) + break; + } + + return error ? 0 : 1; +} + +#endif // MD5_TEST +////////////////////////////////////////////////////////////////////////////// diff --git a/build/libraries_sysmenu/acsign/ARM9/src/sha1.c b/build/libraries_sysmenu/acsign/ARM9/src/sha1.c new file mode 100644 index 0000000..e7f2a65 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/sha1.c @@ -0,0 +1,470 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * sha1.c + * + * Description: + * This file implements the Secure Hashing Algorithm 1 as + * defined in FIPS PUB 180-1 published April 17, 1995. + * + * The SHA-1, produces a 160-bit message digest for a given + * data stream. It should take about 2**n steps to find a + * message with the same digest as a given message and + * 2**(n/2) to find any two messages with the same digest, + * when n is the digest size in bits. Therefore, this + * algorithm can serve as a means of providing a + * "fingerprint" for a message. + * + * Portability Issues: + * SHA-1 is defined in terms of 32-bit "words". This code + * uses (included via "sha1.h" to define 32 and 8 + * bit unsigned integer types. If your C compiler does not + * support 32 bit unsigned integers, this code is not + * appropriate. + * + * Caveats: + * SHA-1 is designed to work with messages less than 2^64 bits + * long. Although SHA-1 allows a message digest to be generated + * for messages of any number of bits less than 2^64, this + * implementation only works with messages with a length that is + * a multiple of the size of an 8-bit character. + * + */ + +#include "sha1.h" + +/* + * Define the SHA1 circular left shift macro + */ +#define SHA1CircularShift(bits,word) \ + (((word) << (bits)) | ((word) >> (32-(bits)))) + +/* Local Function Prototyptes */ +void SHA1PadMessage(SHA1Context *); +void SHA1ProcessMessageBlock(SHA1Context *); + +/* + * SHA1Reset + * + * Description: + * This function will initialize the SHA1Context in preparation + * for computing a new SHA1 message digest. + * + * Parameters: + * context: [in/out] + * The context to reset. + * + * Returns: + * sha Error Code. + * + */ +int SHA1Reset(SHA1Context *context) +{ + if (!context) + { + return shaNull; + } + + context->Length_Low = 0; + context->Length_High = 0; + context->Message_Block_Index = 0; + + context->Intermediate_Hash[0] = 0x67452301; + context->Intermediate_Hash[1] = 0xEFCDAB89; + context->Intermediate_Hash[2] = 0x98BADCFE; + context->Intermediate_Hash[3] = 0x10325476; + context->Intermediate_Hash[4] = 0xC3D2E1F0; + + context->Computed = 0; + context->Corrupted = 0; + + return shaSuccess; +} + +/* + * SHA1Result + * + * Description: + * This function will return the 160-bit message digest into the + * Message_Digest array provided by the caller. + * NOTE: The first octet of hash is stored in the 0th element, + * the last octet of hash in the 19th element. + * + * Parameters: + * context: [in/out] + * The context to use to calculate the SHA-1 hash. + * Message_Digest: [out] + * Where the digest is returned. + * + * Returns: + * sha Error Code. + * + */ +int SHA1Result( SHA1Context *context, + unsigned char Message_Digest[20]) +{ + int i; + + if (!context || !Message_Digest) + { + return shaNull; + } + + if (context->Corrupted) + { + return context->Corrupted; + } + + if (!context->Computed) + { + SHA1PadMessage(context); + for(i=0; i<64; ++i) + { + /* message may be sensitive, clear it out */ + context->Message_Block[i] = 0; + } + context->Length_Low = 0; /* and clear length */ + context->Length_High = 0; + context->Computed = 1; + + } + + for(i = 0; i < 20; ++i) + { + Message_Digest[i] = (unsigned char) + (context->Intermediate_Hash[i>>2] + >> 8 * ( 3 - ( i & 0x03 ) )); + } + + return shaSuccess; +} + +/* + * SHA1Input + * + * Description: + * This function accepts an array of octets as the next portion + * of the message. + * + * Parameters: + * context: [in/out] + * The SHA context to update + * message_array: [in] + * An array of characters representing the next portion of + * the message. + * length: [in] + * The length of the message in message_array + * + * Returns: + * sha Error Code. + * + */ +int SHA1Input( SHA1Context *context, + const unsigned char *message_array, + unsigned int length) +{ + if (!length) + { + return shaSuccess; + } + + if (!context || !message_array) + { + return shaNull; + } + + if (context->Computed) + { + context->Corrupted = shaStateError; + + return shaStateError; + } + + if (context->Corrupted) + { + return context->Corrupted; + } + while(length-- && !context->Corrupted) + { + context->Message_Block[context->Message_Block_Index++] = + (unsigned char)(*message_array & 0xFF); + + context->Length_Low += 8; + if (context->Length_Low == 0) + { + context->Length_High++; + if (context->Length_High == 0) + { + /* Message is too long */ + context->Corrupted = 1; + } + } + + if (context->Message_Block_Index == 64) + { + SHA1ProcessMessageBlock(context); + } + + message_array++; + } + + return shaSuccess; +} + +/* + * SHA1ProcessMessageBlock + * + * Description: + * This function will process the next 512 bits of the message + * stored in the Message_Block array. + * + * Parameters: + * None. + * + * Returns: + * Nothing. + * + * Comments: + * + * Many of the variable names in this code, especially the + * single character names, were used because those were the + * names used in the publication. + * + * + */ +void SHA1ProcessMessageBlock(SHA1Context *context) +{ + const unsigned long K[] = { /* Constants defined in SHA-1 */ + 0x5A827999, + 0x6ED9EBA1, + 0x8F1BBCDC, + 0xCA62C1D6 + }; + int t; /* Loop counter */ + unsigned long temp; /* Temporary word value */ + unsigned long W[80]; /* Word sequence */ + unsigned long A, B, C, D, E; /* Word buffers */ + + /* + * Initialize the first 16 words in the array W + */ + for(t = 0; t < 16; t++) + { + W[t] = context->Message_Block[t * 4 ] << 24; + W[t] |= context->Message_Block[t * 4 + 1] << 16; + W[t] |= context->Message_Block[t * 4 + 2] << 8; + W[t] |= context->Message_Block[t * 4 + 3]; + } + + for(t = 16; t < 80; t++) + { + W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); + } + + A = context->Intermediate_Hash[0]; + B = context->Intermediate_Hash[1]; + C = context->Intermediate_Hash[2]; + D = context->Intermediate_Hash[3]; + E = context->Intermediate_Hash[4]; + + for(t = 0; t < 20; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + + B = A; + A = temp; + } + + for(t = 20; t < 40; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for(t = 40; t < 60; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for(t = 60; t < 80; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + context->Intermediate_Hash[0] += A; + context->Intermediate_Hash[1] += B; + context->Intermediate_Hash[2] += C; + context->Intermediate_Hash[3] += D; + context->Intermediate_Hash[4] += E; + + context->Message_Block_Index = 0; +} + +/* + * SHA1PadMessage + * + + * Description: + * According to the standard, the message must be padded to an even + * 512 bits. The first padding bit must be a '1'. The last 64 + * bits represent the length of the original message. All bits in + * between should be 0. This function will pad the message + * according to those rules by filling the Message_Block array + * accordingly. It will also call the ProcessMessageBlock function + * provided appropriately. When it returns, it can be assumed that + * the message digest has been computed. + * + * Parameters: + * context: [in/out] + * The context to pad + * ProcessMessageBlock: [in] + * The appropriate SHA*ProcessMessageBlock function + * Returns: + * Nothing. + * + */ + +void SHA1PadMessage(SHA1Context *context) +{ + /* + * Check to see if the current message block is too small to hold + * the initial padding bits and length. If so, we will pad the + * block, process it, and then continue padding into a second + * block. + */ + if (context->Message_Block_Index > 55) + { + context->Message_Block[context->Message_Block_Index++] = 0x80; + while(context->Message_Block_Index < 64) + { + context->Message_Block[context->Message_Block_Index++] = 0; + } + + SHA1ProcessMessageBlock(context); + + while(context->Message_Block_Index < 56) + { + context->Message_Block[context->Message_Block_Index++] = 0; + } + } + else + { + context->Message_Block[context->Message_Block_Index++] = 0x80; + while(context->Message_Block_Index < 56) + { + + context->Message_Block[context->Message_Block_Index++] = 0; + } + } + + /* + * Store the message length as the last 8 octets + */ + context->Message_Block[56] = (unsigned char)(context->Length_High >> 24); + context->Message_Block[57] = (unsigned char)(context->Length_High >> 16); + context->Message_Block[58] = (unsigned char)(context->Length_High >> 8); + context->Message_Block[59] = (unsigned char)(context->Length_High ); + context->Message_Block[60] = (unsigned char)(context->Length_Low >> 24); + context->Message_Block[61] = (unsigned char)(context->Length_Low >> 16); + context->Message_Block[62] = (unsigned char)(context->Length_Low >> 8); + context->Message_Block[63] = (unsigned char)(context->Length_Low ); + + SHA1ProcessMessageBlock(context); +} + + + + +////////////////////////////////////////////////////////////////////////////// +#if defined( SHA1_TEST ) + +#include "string.h" + +char* samplearray[4] = +{ + "abc", + "abcdbcdecdefdefgefghfghighijhi" "jkijkljklmklmnlmnomnopnopq", + "a", + "01234567012345670123456701234567" "01234567012345670123456701234567" +}; + +char* resultarray[ 4 ] = +{ + "\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E\x25\x71\x78\x50\xC2\x6C\x9C\xD0\xD8\x9D", + "\x84\x98\x3E\x44\x1C\x3B\xD2\x6E\xBA\xAE\x4A\xA1\xF9\x51\x29\xE5\xE5\x46\x70\xF1", + "\x34\xAA\x97\x3C\xD4\xC4\xDA\xA4\xF6\x1E\xEB\x2B\xDB\xAD\x27\x31\x65\x34\x01\x6F", + "\xDE\xA3\x56\xA2\xCD\xDD\x90\xC7\xA7\xEC\xED\xC5\xEB\xB5\x63\x93\x4F\x46\x04\x52" +}; + +long int repeatcount[4] = { 1, 1, 1000000, 10 }; + +int SHA1Test( ) +{ + SHA1Context sha; + unsigned char digest[20]; + int i, j, error; + + error = 0; + for ( j = 0; j < 4; ++j ) + { + if ( !error ) + error = SHA1Reset(&sha); + + for(i = 0; i < repeatcount[j]; ++i) + { + if ( !error ) + error = SHA1Input(&sha, + (const unsigned char *)samplearray[j], + (unsigned int)strlen(samplearray[j])); + } + + if ( !error ) + error = SHA1Result(&sha, digest); + + if ( !error ) + error = memcmp( digest, resultarray[j], 20 ); + + if (error) + break; + } + + return error ? 0 : 1; +} + +#endif // SHA1_TEST +////////////////////////////////////////////////////////////////////////////// + diff --git a/build/libraries_sysmenu/acsign/ARM9/src/sha1dgst.c b/build/libraries_sysmenu/acsign/ARM9/src/sha1dgst.c new file mode 100644 index 0000000..4742b60 --- /dev/null +++ b/build/libraries_sysmenu/acsign/ARM9/src/sha1dgst.c @@ -0,0 +1,786 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +////!!!!#include "r_com.h" + +#ifndef NO_SHA1 +#undef SHA_0 +#define SHA_1 +#include "sha.h" +#include "sha_locl.h" +#ifdef CPU_X86 +#include "r_cpuid.h" +#endif /* NO_SHA1 */ + +const char *SHA1_version="SHA1 part of RCOM 2.3.0 11-Jun-2002"; + +/* Implemented from SHA-1 document - The Secure Hash Algorithm + */ + +#define INIT_DATA_h0 (SHA_LONG)0x67452301L +#define INIT_DATA_h1 (SHA_LONG)0xefcdab89L +#define INIT_DATA_h2 (SHA_LONG)0x98badcfeL +#define INIT_DATA_h3 (SHA_LONG)0x10325476L +#define INIT_DATA_h4 (SHA_LONG)0xc3d2e1f0L + +#define K_00_19 (SHA_LONG)0x5a827999L +#define K_20_39 (SHA_LONG)0x6ed9eba1L +#define K_40_59 (SHA_LONG)0x8f1bbcdcL +#define K_60_79 (SHA_LONG)0xca62c1d6L + +#ifndef CCONV +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +/* Endian flags are only used for the assembler code */ +#ifndef OPT_SHA1_ASM +#undef L_ENDIAN +#undef B_ENDIAN +#endif + + +#ifdef OPT_SHA1_ASM + +#ifdef CPU_X86 +void CCONV sha1_block_586(SHA_CTX *c,const unsigned char *p, int num); +void CCONV sha1_block_686(SHA_CTX *c,const unsigned char *p, int num); +void CCONV sha1_block_786(SHA_CTX *c,const unsigned char *p, int num); +unsigned long r_cpuid(unsigned long *,char **name); + +#elif OPT_SHA1_ARM +PRE_CCONV void CCONV sha1_arm4_fast(SHA_CTX *c, const unsigned char *p, + int num); +PRE_CCONV void CCONV sha1_arm4_small(SHA_CTX *c, const unsigned char *p, + int num); +#else +void CCONV sha1_block_asm(SHA_CTX *c, const unsigned char *p, int num); +#endif /* CPU_X86 */ + +#else /* OPT_SHA1_ASM */ + +void sha1_block(SHA_CTX *c, SHA_LONG *p, int num); + +#endif /* OPT_SHA1_ASM */ + +#undef M_c2nl +#undef M_p_c2nl +#undef M_c2nl_p +#undef M_p_c2nl_p +#undef M_nl2c + +#if defined(L_ENDIAN) && !defined(OPT_SHA1_ASM) +# define M_c2nl c2l +# define M_p_c2nl p_c2l +# define M_c2nl_p c2l_p +# define M_p_c2nl_p p_c2l_p +# define M_nl2c l2c +#else +# define M_c2nl c2nl +# define M_p_c2nl p_c2nl +# define M_c2nl_p c2nl_p +# define M_p_c2nl_p p_c2nl_p +# define M_nl2c nl2c +#endif /* defined(L_ENDIAN) && !defined(OPT_SHA1_ASM) */ + +int SHA1_Setup(c,sha_block) +SHA_CTX *c; +void (PRE_CCONV CCONV *sha_block)(SHA_CTX *c, const unsigned char *W, int num); + { + c->sha_block=sha_block; + return(0); + } + +void SHA1_Init(c) +SHA_CTX *c; + { + c->h0=INIT_DATA_h0; + c->h1=INIT_DATA_h1; + c->h2=INIT_DATA_h2; + c->h3=INIT_DATA_h3; + c->h4=INIT_DATA_h4; + c->Nl=0; + c->Nh=0; + c->num=0; + +#ifdef OPT_SHA1_ASM +#ifdef CPU_X86 + if (c->sha_block == NULL) + { + unsigned long cpu,attrib; + + /* We should make the methods loadable */ + cpu=r_cpuid(&attrib,NULL); + if (attrib & R_CPU_X86_HAS_PENTIUM_IV) + c->sha_block=sha1_block_786; + else if (attrib & R_CPU_X86_HAS_PENTIUM_PRO) + c->sha_block=sha1_block_686; + else + c->sha_block=sha1_block_586; + } +#else /* CPU_X86 */ + +#ifndef OPT_SHA1_ARM + c->sha_block=sha1_block_asm; +#else /* OPT_SHA1_ARM */ + if (c->sha_block == NULL) + { +#ifdef SMALL_CODE_SIZE + c->sha_block = sha1_arm4_small; +#else /* SMALL_CODE_SIZE */ + c->sha_block = sha1_arm4_fast; +#endif /* SMALL_CODE_SIZE */ + } +#endif /* OPT_SHA1_ARM */ +#endif /* CPU_X86 */ + +#else /* OPT_SHA1_ASM */ + c->sha_block=(void (PRE_CCONV CCONV *)(SHA_CTX *, const unsigned char *, int))sha1_block; +#endif /* OPT_SHA1_ASM */ + } + +#ifdef OPT_SHA1_ASM + +void SHA1_Update(c, data, len) +SHA_CTX *c; +const register unsigned char *data; +unsigned long len; + { + int i; + unsigned int alignment; + unsigned long l; + unsigned char *cp=(unsigned char *)c->data; + + if (len == 0) return; + + l=(c->Nl+(len<<3))&0xffffffffL; + if (l < c->Nl) /* overflow */ + c->Nh++; + c->Nh+=(len>>29); + c->Nl=l; + + if (c->num != 0) + { + if (c->num+len >= SHA_CBLOCK) + { + i=SHA_CBLOCK-c->num; + Memcpy(&(cp[c->num]),data,i); + len-=i; + data+=i; + + c->sha_block(c,cp,64); + c->num=0; + /* drop through and do the rest */ + } + else + { + Memcpy(&(cp[c->num]),data,len); + c->num+=(int)len; + return; + } + } + /* we now can process the input data in blocks of SHA_CBLOCK + * chars and save the leftovers to c->data. */ + if (len >= SHA_CBLOCK) + { + i=(int)(len& ~63); + len-=i; + + /* + * Check to see if the input data lies on a word boundary. + * Do this as the ASM relies on input data being word aligned. + */ + alignment = (((unsigned int)data) & (sizeof(unsigned int)-1)) + & 0x03; + if (alignment == 0) + { + c->sha_block(c,data,i); + data+=i; + } + else + { + do { + Memcpy(cp, data, SHA_CBLOCK); + data += SHA_CBLOCK; + c->sha_block(c, cp, SHA_CBLOCK); + i -= SHA_CBLOCK; + } while (i > 0); + } + } + c->num=len; + if (len) + { + Memcpy(cp,data,(int)len); + } + } + +void SHA1_Transform(c,b) +SHA_CTX *c; +const unsigned char *b; + { + c->sha_block(c,b,64); + } + +void SHA1_Final(md, c) +unsigned char *md; +SHA_CTX *c; + { + register int i,j; + register SHA_LONG l; + register SHA_LONG *p; + const static unsigned char end[4]={0x80,0x00,0x00,0x00}; + unsigned char *cp= (unsigned char *)end; + unsigned char *pc; + + /* c->num should definitly have room for at least one more byte. */ + p=c->data; + j=c->num; + i=j>>2; + +#ifdef PURIFY + /* PURIFY */ + /* we reference uninitialised data but don't keep the result + * which purify complains about ... and we don't want to have + * to come back here to find a non-existant problem later + */ + + /* purify often complains about the following line as an + * Uninitialized Memory Read. While this can be true, the + * following p_c2l macro will reset l when that case is true. + * This is because j&0x03 contains the number of 'valid' bytes + * already in p[i]. If and only if j&0x03 == 0, the UMR will + * occur but this is also the only time p_c2l will do + * l= *(cp++) instead of l|= *(cp++) + */ + if ((j&0x03) == 0) p[i]=0; +#endif + + pc=(unsigned char *)c->data; + pc[j]=0x80; + for (j++; j & 0x03; j++) + pc[j]=0; + i++; + /* i is the next 'undefined word' */ + if (c->num >= SHA_LAST_BLOCK) + { + for (; isha_block(c,(unsigned char *)p,64); + i=0; + } + for (; i<(SHA_LBLOCK-2); i++) + p[i]=0; + + l=c->Nl; + pc[63]=(unsigned char)((l )&0xff); + pc[62]=(unsigned char)((l>> 8)&0xff); + pc[61]=(unsigned char)((l>>16)&0xff); + pc[60]=(unsigned char)((l>>24)&0xff); + l=c->Nh; + pc[59]=(unsigned char)((l )&0xff); + pc[58]=(unsigned char)((l>> 8)&0xff); + pc[57]=(unsigned char)((l>>16)&0xff); + pc[56]=(unsigned char)((l>>24)&0xff); + + c->sha_block(c,(unsigned char *)p,64); + cp=md; + l=c->h0; nl2c(l,cp); + l=c->h1; nl2c(l,cp); + l=c->h2; nl2c(l,cp); + l=c->h3; nl2c(l,cp); + l=c->h4; nl2c(l,cp); + + /* clear stuff, sha1_block_asm may be leaving some stuff on the stack + * but I'm not worried :-) */ + c->num=0; +/* Memset((char *)&c,0,sizeof(c));*/ + } + +#else /* !OPT_SHA1_ASM */ + +void SHA1_Update(c, data, len) +SHA_CTX *c; +const register unsigned char *data; +unsigned long len; + { + register SHA_LONG *p; + int ew,ec,sw,sc; + SHA_LONG l; + + if (len == 0) return; + + l=(c->Nl+(len<<3))&0xffffffffL; + if (l < c->Nl) /* overflow */ + c->Nh++; + c->Nh+=(len>>29); + c->Nl=l; + + if (c->num != 0) + { + p=c->data; + sw=c->num>>2; + sc=c->num&0x03; + + if ((c->num+len) >= SHA_CBLOCK) + { + l= p[sw]; + M_p_c2nl(data,l,sc); + p[sw++]=l; + for (; swnum); + + c->sha_block(c,(unsigned char *)p,64); + c->num=0; + /* drop through and do the rest */ + } + else + { + c->num+=(int)len; + if ((sc+len) < 4) /* ugly, add char's to a word */ + { + l= p[sw]; + M_p_c2nl_p(data,l,sc,len); + p[sw]=l; + } + else + { + ew=(c->num>>2); + ec=(c->num&0x03); + l= p[sw]; + M_p_c2nl(data,l,sc); + p[sw++]=l; + for (; sw < ew; sw++) + { M_c2nl(data,l); p[sw]=l; } + if (ec) + { + M_c2nl_p(data,l,ec); + p[sw]=l; + } + } + return; + } + } + /* We can only do the following code for assember, the reason + * being that the sha1_block 'C' version changes the values + * in the 'data' array. The assember code avoids this and + * copies it to a local array. I should be able to do this for + * the C version as well.... + */ +#if defined(B_ENDIAN) || defined(OPT_SHA1_ASM) + if ((((unsigned long)data)%sizeof(SHA_LONG)) == 0) + { + sw=len/SHA_CBLOCK; + if (sw) + { + sw*=SHA_CBLOCK; + c->sha_block(c,(SHA_LONG *)data,sw); + data+=sw; + len-=sw; + } + } +#endif + /* we now can process the input data in blocks of SHA_CBLOCK + * chars and save the leftovers to c->data. */ + p=c->data; + while (len >= SHA_CBLOCK) + { +#if defined(B_ENDIAN) || defined(L_ENDIAN) + if (p != (SHA_LONG *)data) + Memcpy(p,data,SHA_CBLOCK); + data+=SHA_CBLOCK; +# ifdef L_ENDIAN +# ifndef OPT_SHA1_ASM /* Will not happen */ + for (sw=(SHA_LBLOCK/4); sw; sw--) + { + Endian_Reverse32(p[0]); + Endian_Reverse32(p[1]); + Endian_Reverse32(p[2]); + Endian_Reverse32(p[3]); + p+=4; + } + p=c->data; +# endif +# endif +#else + for (sw=(SHA_BLOCK/4); sw; sw--) + { + M_c2nl(data,l); *(p++)=l; + M_c2nl(data,l); *(p++)=l; + M_c2nl(data,l); *(p++)=l; + M_c2nl(data,l); *(p++)=l; + } + p=c->data; +#endif + c->sha_block(c,(unsigned char *)p,64); + len-=SHA_CBLOCK; + } + ec=(int)len; + c->num=ec; + ew=(ec>>2); + ec&=0x03; + + for (sw=0; sw < ew; sw++) + { M_c2nl(data,l); p[sw]=l; } + M_c2nl_p(data,l,ec); + p[sw]=l; + } + +void SHA1_Transform(c,b) +SHA_CTX *c; +const unsigned char *b; + { + SHA_LONG p[16]; +#ifndef B_ENDIAN + SHA_LONG *q; + int i; +#endif + +#if defined(B_ENDIAN) || defined(L_ENDIAN) + Memcpy(p,b,64); +#ifdef L_ENDIAN + q=p; + for (i=(SHA_LBLOCK/4); i; i--) + { + Endian_Reverse32(q[0]); + Endian_Reverse32(q[1]); + Endian_Reverse32(q[2]); + Endian_Reverse32(q[3]); + q+=4; + } +#endif +#else + q=p; + for (i=(SHA_LBLOCK/4); i; i--) + { + SHA_LONG l; + c2nl(b,l); *(q++)=l; + c2nl(b,l); *(q++)=l; + c2nl(b,l); *(q++)=l; + c2nl(b,l); *(q++)=l; + } +#endif + c->sha_block(c,(unsigned char *)p,64); + } + + +void sha1_block(c, W, num) +SHA_CTX *c; +SHA_LONG *W; +int num; + { +#ifndef SMALL_CODE_SIZE + register SHA_LONG A,B,C,D,E,T; + SHA_LONG X[16]; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + for (;;) + { + BODY_00_15( 0,A,B,C,D,E,T,W); + BODY_00_15( 1,T,A,B,C,D,E,W); + BODY_00_15( 2,E,T,A,B,C,D,W); + BODY_00_15( 3,D,E,T,A,B,C,W); + BODY_00_15( 4,C,D,E,T,A,B,W); + BODY_00_15( 5,B,C,D,E,T,A,W); + BODY_00_15( 6,A,B,C,D,E,T,W); + BODY_00_15( 7,T,A,B,C,D,E,W); + BODY_00_15( 8,E,T,A,B,C,D,W); + BODY_00_15( 9,D,E,T,A,B,C,W); + BODY_00_15(10,C,D,E,T,A,B,W); + BODY_00_15(11,B,C,D,E,T,A,W); + BODY_00_15(12,A,B,C,D,E,T,W); + BODY_00_15(13,T,A,B,C,D,E,W); + BODY_00_15(14,E,T,A,B,C,D,W); + BODY_00_15(15,D,E,T,A,B,C,W); + BODY_16_19(16,C,D,E,T,A,B,W,W,W,W); + BODY_16_19(17,B,C,D,E,T,A,W,W,W,W); + BODY_16_19(18,A,B,C,D,E,T,W,W,W,W); + BODY_16_19(19,T,A,B,C,D,E,W,W,W,X); + + BODY_20_31(20,E,T,A,B,C,D,W,W,W,X); + BODY_20_31(21,D,E,T,A,B,C,W,W,W,X); + BODY_20_31(22,C,D,E,T,A,B,W,W,W,X); + BODY_20_31(23,B,C,D,E,T,A,W,W,W,X); + BODY_20_31(24,A,B,C,D,E,T,W,W,X,X); + BODY_20_31(25,T,A,B,C,D,E,W,W,X,X); + BODY_20_31(26,E,T,A,B,C,D,W,W,X,X); + BODY_20_31(27,D,E,T,A,B,C,W,W,X,X); + BODY_20_31(28,C,D,E,T,A,B,W,W,X,X); + BODY_20_31(29,B,C,D,E,T,A,W,W,X,X); + BODY_20_31(30,A,B,C,D,E,T,W,X,X,X); + BODY_20_31(31,T,A,B,C,D,E,W,X,X,X); + BODY_32_39(32,E,T,A,B,C,D,X); + BODY_32_39(33,D,E,T,A,B,C,X); + BODY_32_39(34,C,D,E,T,A,B,X); + BODY_32_39(35,B,C,D,E,T,A,X); + BODY_32_39(36,A,B,C,D,E,T,X); + BODY_32_39(37,T,A,B,C,D,E,X); + BODY_32_39(38,E,T,A,B,C,D,X); + BODY_32_39(39,D,E,T,A,B,C,X); + + BODY_40_59(40,C,D,E,T,A,B,X); + BODY_40_59(41,B,C,D,E,T,A,X); + BODY_40_59(42,A,B,C,D,E,T,X); + BODY_40_59(43,T,A,B,C,D,E,X); + BODY_40_59(44,E,T,A,B,C,D,X); + BODY_40_59(45,D,E,T,A,B,C,X); + BODY_40_59(46,C,D,E,T,A,B,X); + BODY_40_59(47,B,C,D,E,T,A,X); + BODY_40_59(48,A,B,C,D,E,T,X); + BODY_40_59(49,T,A,B,C,D,E,X); + BODY_40_59(50,E,T,A,B,C,D,X); + BODY_40_59(51,D,E,T,A,B,C,X); + BODY_40_59(52,C,D,E,T,A,B,X); + BODY_40_59(53,B,C,D,E,T,A,X); + BODY_40_59(54,A,B,C,D,E,T,X); + BODY_40_59(55,T,A,B,C,D,E,X); + BODY_40_59(56,E,T,A,B,C,D,X); + BODY_40_59(57,D,E,T,A,B,C,X); + BODY_40_59(58,C,D,E,T,A,B,X); + BODY_40_59(59,B,C,D,E,T,A,X); + + BODY_60_79(60,A,B,C,D,E,T,X); + BODY_60_79(61,T,A,B,C,D,E,X); + BODY_60_79(62,E,T,A,B,C,D,X); + BODY_60_79(63,D,E,T,A,B,C,X); + BODY_60_79(64,C,D,E,T,A,B,X); + BODY_60_79(65,B,C,D,E,T,A,X); + BODY_60_79(66,A,B,C,D,E,T,X); + BODY_60_79(67,T,A,B,C,D,E,X); + BODY_60_79(68,E,T,A,B,C,D,X); + BODY_60_79(69,D,E,T,A,B,C,X); + BODY_60_79(70,C,D,E,T,A,B,X); + BODY_60_79(71,B,C,D,E,T,A,X); + BODY_60_79(72,A,B,C,D,E,T,X); + BODY_60_79(73,T,A,B,C,D,E,X); + BODY_60_79(74,E,T,A,B,C,D,X); + BODY_60_79(75,D,E,T,A,B,C,X); + BODY_60_79(76,C,D,E,T,A,B,X); + BODY_60_79(77,B,C,D,E,T,A,X); + BODY_60_79(78,A,B,C,D,E,T,X); + BODY_60_79(79,T,A,B,C,D,E,X); + + c->h0=(c->h0+E)&0xffffffffL; + c->h1=(c->h1+T)&0xffffffffL; + c->h2=(c->h2+A)&0xffffffffL; + c->h3=(c->h3+B)&0xffffffffL; + c->h4=(c->h4+C)&0xffffffffL; + + num-=64; + if (num <= 0) break; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + W+=16; + } +#else /* SMALL_CODE_SIZE */ + SHA_LONG A,B,C,D,E,T; + SHA_LONG X[16]; + SHA_LONG *a1,*a2,*a3; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + for (;;) + { + int i; + + for (i=0; i<16; i++) + { + BODY_00_15(i,A,B,C,D,E,T,W); + E=D; D=C; C=B; B=A; A=T; + } + + a1=W; + for (i=16; i<20; i++) + { + if (i == 19) a1=X; + BODY_16_19(i,A,B,C,D,E,T,W,W,W,a1); + E=D; D=C; C=B; B=A; A=T; + } + + a1=a2=a3=W; + for (i=20; i<40; i++) + { + if (i == 24) a3=X; + if (i == 30) a2=X; + if (i == 32) a1=X; + BODY_20_31(i,A,B,C,D,E,T,a1,a2,a3,X); + E=D; D=C; C=B; B=A; A=T; + } + + for (i=40; i<60; i++) + { + BODY_40_59(i,A,B,C,D,E,T,X); + E=D; D=C; C=B; B=A; A=T; + } + + for (i=60; i<80; i++) + { + BODY_60_79(i,A,B,C,D,E,T,X); + E=D; D=C; C=B; B=A; A=T; + } + + c->h0=(c->h0+A)&0xffffffffL; + c->h1=(c->h1+B)&0xffffffffL; + c->h2=(c->h2+C)&0xffffffffL; + c->h3=(c->h3+D)&0xffffffffL; + c->h4=(c->h4+E)&0xffffffffL; + + num-=64; + if (num <= 0) break; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + W+=16; + } +#endif /* SMALL_CODE_SIZE */ + } + +void SHA1_Final(md, c) +unsigned char *md; +SHA_CTX *c; + { + register int i,j; + register SHA_LONG l; + register SHA_LONG *p; + const static unsigned char end[4]={0x80,0x00,0x00,0x00}; + unsigned char *cp= (unsigned char *)end; + + /* c->num should definitly have room for at least one more byte. */ + p=c->data; + j=c->num; + i=j>>2; + +#ifdef PURIFY + /* PURIFY */ + /* we reference uninitialised data but don't keep the result + * which purify complains about ... and we don't want to have + * to come back here to find a non-existant problem later + */ + + /* purify often complains about the following line as an + * Uninitialized Memory Read. While this can be true, the + * following p_c2l macro will reset l when that case is true. + * This is because j&0x03 contains the number of 'valid' bytes + * already in p[i]. If and only if j&0x03 == 0, the UMR will + * occur but this is also the only time p_c2l will do + * l= *(cp++) instead of l|= *(cp++) + */ + if ((j&0x03) == 0) p[i]=0; +#endif + + l=p[i]; + M_p_c2nl(cp,l,j&0x03); + p[i]=l; + i++; + /* i is the next 'undefined word' */ + if (c->num >= SHA_LAST_BLOCK) + { + for (; isha_block(c,(unsigned char *)p,64); + i=0; + } + for (; i<(SHA_LBLOCK-2); i++) + p[i]=0; + p[SHA_LBLOCK-2]=c->Nh; + p[SHA_LBLOCK-1]=c->Nl; +#if defined(L_ENDIAN) + Endian_Reverse32(p[SHA_LBLOCK-2]); + Endian_Reverse32(p[SHA_LBLOCK-1]); +#endif + c->sha_block(c,(unsigned char *)p,64); + cp=md; + l=c->h0; nl2c(l,cp); + l=c->h1; nl2c(l,cp); + l=c->h2; nl2c(l,cp); + l=c->h3; nl2c(l,cp); + l=c->h4; nl2c(l,cp); + + /* clear stuff, sha1_block may be leaving some stuff on the stack + * but I'm not worried :-) */ + c->num=0; +/* Memset((char *)&c,0,sizeof(c));*/ + } +#endif + +#if 0 +int pr(ctx) +SHA_CTX *ctx; + { + int i,j; + unsigned char *p=(unsigned char *)(ctx->data); + + fprintf(stderr,"num = %08X%08X\n",ctx->Nh,ctx->Nl); + fprintf(stderr," %08X %08X %08X %08X %08X\n", + ctx->h0,ctx->h1,ctx->h2,ctx->h3,ctx->h4); + fprintf(stderr,"bufnum = %d\n",ctx->num); + fprintf(stderr," "); + for (j=0; j<64; j+=16) + { + for (i=0; i<16; i++) + { +/* + if ((i+j) >= ctx->num) + fprintf(stderr,"--"); + else +*/ + fprintf(stderr,"%02X",p[i+j]); + } + if ((j+16) >=64) + fprintf(stderr,"\n"); + else + fprintf(stderr,"\n "); + } + } + +#endif + +#endif /* NO_SHA1 */ diff --git a/build/libraries_sysmenu/acsign/Makefile b/build/libraries_sysmenu/acsign/Makefile new file mode 100644 index 0000000..665c3ec --- /dev/null +++ b/build/libraries_sysmenu/acsign/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-27#$ +# $Rev: 1203 $ +# $Author: yada $ +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 + +TARGET_FIRM = SYSTEMMENU + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries_sysmenu/mb_loader/ARM7/Makefile b/build/libraries_sysmenu/mb_loader/ARM7/Makefile new file mode 100644 index 0000000..c678ae7 --- /dev/null +++ b/build/libraries_sysmenu/mb_loader/ARM7/Makefile @@ -0,0 +1,53 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-27#$ +# $Rev: 1203 $ +# $Author: yada $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED +TWL_PROC = ARM7 + +#---------------------------------------------------------------------------- + +SRCDIR = ../common/src + +INCDIR = ../common/include \ + $(TWLSDK_ROOT)/build/libraries/mb/common/include + + +SRCS = mb_loader.c + +TARGET_LIB = libmbloader_sp$(TWL_LIBSUFFIX).a + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(SYSMENU_INSTALL_LIBDIR) + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== + diff --git a/build/libraries_sysmenu/mb_loader/ARM9/Makefile b/build/libraries_sysmenu/mb_loader/ARM9/Makefile new file mode 100644 index 0000000..257cddc --- /dev/null +++ b/build/libraries_sysmenu/mb_loader/ARM9/Makefile @@ -0,0 +1,52 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-27#$ +# $Rev: 1203 $ +# $Author: yada $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED +TWL_PROC = ARM9 + +#---------------------------------------------------------------------------- + +SRCDIR = ../common/src + +INCDIR = ../common/include \ + $(TWLSDK_ROOT)/build/libraries/mb/common/include + +SRCS = mb_loader.c + +TARGET_LIB = libmbloader$(TWL_LIBSUFFIX).a + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(SYSMENU_INSTALL_LIBDIR) + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== + diff --git a/build/libraries_sysmenu/mb_loader/Makefile b/build/libraries_sysmenu/mb_loader/Makefile new file mode 100644 index 0000000..6024cf8 --- /dev/null +++ b/build/libraries_sysmenu/mb_loader/Makefile @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-27#$ +# $Rev: 1203 $ +# $Author: yada $ +#---------------------------------------------------------------------------- + +TARGET_FIRM = SYSTEMMENU +SUBDIRS = ARM7 ARM9 + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/libraries_sysmenu/mb_loader/common/src/mb_loader.c b/build/libraries_sysmenu/mb_loader/common/src/mb_loader.c new file mode 100644 index 0000000..5289b5c --- /dev/null +++ b/build/libraries_sysmenu/mb_loader/common/src/mb_loader.c @@ -0,0 +1,312 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: mb_loader.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +#if defined(SDK_ARM7) +#include +#else +#ifdef SDK_SMALL_BUILD +#include "SYSM_work.h" +#endif +#endif + + +#include // twl/mb.hȂB +#include +#include + +// -------------------------------------------------------------------------- + +// Download̃TCY + +#define MB_OVT_MAX_SIZE MB_COMM_BLOCK_SIZE // OVT̍őTCYiBlockTCYőTCYƂj + +/*----------------------------------------------------------------------------*/ +#define MB_TRIGGER_SIGNAL_TO_ARM7 (0x00000001) + +/*----------------------------------------------------------------------------*/ +static void MIm_CpuClear32( register u32 data, register void *destp, register u32 size ); +static void MIm_CpuClear32( register u32 data, register void *destp, register u32 size ); +static void LOADERi_LocateAllSegments( MBDownloadFileInfo *mdfi ); +static void MBi_SearchAndLocateSegmentInfo( MBDownloadFileInfo *mdfi, u16 processor ); +static void LOADERi_Jump(void); +static void MBi_fifo_callback_arm7(PXIFifoTag tag, u32 msg_adr, BOOL err); + +/*----------------------------------------------------------------------------*/ +static MB_LoaderCallback loader_precallback = NULL; + +/*----------------------------------------------------------------------------*/ + + +#if defined(SDK_ARM7) + +/*---------------------------------------------------------------------------* + Name: MIm_CpuCopy32 + + Description: [_[pCpuCopy + + Arguments: srcp, destp, size + + Returns: void + *---------------------------------------------------------------------------*/ + +#include + +asm void MIm_CpuCopy32( register const void *srcp, register void *destp, register u32 size ) +{ + add r12, r1, r2 // r12: destEndp = destp + size + +@30: + cmp r1, r12 // while (destp < destEndp) + ldmltia r0!, {r2} // *((vu32 *)(destp)++) = *((vu32 *)(srcp)++) + stmltia r1!, {r2} + blt @30 + + bx lr +} + +#ifndef SDK_SMALL_BUILD +static asm void MIm_CpuClear32( register u32 data, register void *destp, register u32 size ) +{ + add r12, r1, r2 // r12: destEndp = destp + size + +@20: + cmp r1, r12 // while (destp < destEndp) + stmltia r1!, {r0} // *((vu32 *)(destp++)) = data + blt @20 + + bx lr +} +#endif + +#include + + +/*---------------------------------------------------------------------------* + Name: LOADERi_LocateAllSegments + + Description: ARM9,ARM7̊eZOgKvɉčĔzuB + + Arguments: mdfi + + Returns: void + *---------------------------------------------------------------------------*/ + +static void LOADERi_LocateAllSegments( MBDownloadFileInfo *mdfi ) +{ + MBi_SearchAndLocateSegmentInfo(mdfi, MI_PROCESSOR_ARM9); // ARM9ZOgɂ‚Ă̔zu + MBi_SearchAndLocateSegmentInfo(mdfi, MI_PROCESSOR_ARM7); // ARM7ZOgɂ‚Ă̔zu +} + + +/* w̃ZOg, Ĕzu */ +static void MBi_SearchAndLocateSegmentInfo( MBDownloadFileInfo *mdfi, u16 processor ) +{ + int i; + MbSegmentInfo *seg_info; + + if( mdfi ) { + for( i = 0 ; i < MB_DL_SEGMENT_NUM ; ++i ) { + seg_info = &mdfi->seg[i]; + if ( seg_info->target == processor ) { + if ( seg_info->recv_addr != seg_info->load_addr ) { + MIm_CpuCopy32( (void*)seg_info->recv_addr, (void*)seg_info->load_addr, seg_info->size ); +#ifndef SDK_SMALL_BUILD // IPL2̏ꍇ́ÃNAIPL2ōsB + MIm_CpuClear32( 0, (void*)seg_info->recv_addr, seg_info->size ); +#endif + } + } + } + } +} + + +/*---------------------------------------------------------------------------* + Name: LOADERi_Jump + + Description: [_[N (ARM7/9 ) + + Arguments: + + Returns: void + *---------------------------------------------------------------------------*/ + +static void LOADERi_Jump(void) +{ +#if defined(SDK_ARM7) + + MBDownloadFileInfo *mdfi = (MBDownloadFileInfo*)MB_DOWNLOAD_FILEINFO_ADDRESS; + MBParam *p_param = (MBParam*)HW_WM_BOOT_BUF; + + if( p_param->boot_type != MB_TYPE_MULTIBOOT ) { // u[g^Cv}`u[głȂꍇ́ATRUE^[B + return; + } + + LOADERi_LocateAllSegments( mdfi ); // u[gvO̍ĔzusB + +#endif +} + + +/*---------------------------------------------------------------------------* + Name: MBi_fifo_callback_arm7 + + Description: p PXI ^OoRŃ[_[N + + Arguments: + + Returns: None. + *---------------------------------------------------------------------------*/ + +static void MBi_fifo_callback_arm7(PXIFifoTag tag, u32 msg_adr, BOOL err) +{ +#pragma unused( err ) + + if (tag == PXI_FIFO_TAG_MB && msg_adr == (u32)MB_TRIGGER_SIGNAL_TO_ARM7) + { + if ( loader_precallback ) { + (*loader_precallback)(); + } + } +} + +#endif /* defined(SDK_ARM7) */ + + +/*---------------------------------------------------------------------------* + Name: LOADER_Start + + Description: [_[̃X^[g + + Arguments: None. + + Returns: TRUE - success FALSE - failed + *---------------------------------------------------------------------------*/ + + +void LOADER_Start(void) +{ + +#if defined(SDK_ARM9) + int result; + MBDownloadFileInfo *mdfi = (MBDownloadFileInfo*)MB_DOWNLOAD_FILEINFO_ADDRESS; + MBParam *p_param = (MBParam*)HW_WM_BOOT_BUF; + + // }`u[g̎̓fobKGgɔ΂Ȃ悤NAB +#ifdef SDK_SMALL_BUILD + GetMovedInfoFromIPL1Addr()->isOnDebugger = 0; // USG-WW-3rd & USG-China-2ndł́AGetSharedWorkAddr()->isOnDebugger̓pb`̈ƃobeBOĂ邪Ã[`ARM9̃}`u[g[`ŌĂ΂ꂽŁAARM7Ńpb`}[`Ă΂̂ŁAvB + // AfobKŃrhɂ́AQƂ鑤isOnDebuggertONAĂȂ̂ŁACB +#endif // SDK_SMALL_BUILD + + // VXëփ}`u[gtO + p_param->boot_type = MB_TYPE_MULTIBOOT; + // e@VXë֏ + MI_CpuCopy8((void*)MB_BSSDESC_ADDRESS, &p_param->parent_bss_desc, MB_BSSDESC_SIZE); + + // ARM7փ[_[Nʒm + result = PXI_SendWordByFifo( PXI_FIFO_TAG_MB, (u32)MB_TRIGGER_SIGNAL_TO_ARM7, FALSE ); + SDK_ASSERTMSG((result >= 0), "ARM9:FIFO SEND ERROR!\n"); + + return; + +#else /* defined(SDK_ARM9) */ + + // [_[R[ + LOADERi_Jump(); + +#endif +} + + +/*---------------------------------------------------------------------------* + Name: LOADER_Init + + Description: [_[̏ + + Arguments: callback - u[g̏oƂɕԂR[obN + + Returns: None. + *---------------------------------------------------------------------------*/ + +void LOADER_Init(MB_LoaderCallback callback) +{ + MBParam *p_param = (MBParam*)HW_WM_BOOT_BUF; + + PXI_Init(); // ĂȂAs + +#if defined(SDK_ARM7) + + loader_precallback = callback; + + /* u[gtO̕␳(}`u[gtOw肳ĂȂꍇROMƂ݂ȂB) */ + if (p_param->boot_type != MB_TYPE_MULTIBOOT) { + p_param->boot_type = MB_TYPE_NORMAL; + } + /* ̏, K MB_TYPE_MULTIBOOT MB_TYPE_NORMAL ɂȂ */ + + // }`u[gĎFIFOR[obNZbg + PXI_SetFifoRecvCallback( PXI_FIFO_TAG_MB, MBi_fifo_callback_arm7 ); + +#else /* defined(SDK_ARM7) */ + + #pragma unused(callback) + +#endif +} + + + +/*----------------------------------------------------------------------------* +/* sgp + *----------------------------------------------------------------------------*/ + +#if defined(LOADER_USE_OVT_BUF) + +//---------------------------------------------------------------------- +// I[o[Ce[u +//---------------------------------------------------------------------- +typedef struct { + u32 id; // I[o[C ID + void *ram_address; // [h擪ʒu + u32 ram_size; // [hTCY + u32 bss_size; // bss ̈TCY + void *sinit_init; // static initializer 擪AhX + void *sinit_init_end; // static initializer ŏIAhX + u32 file_id; // I[o[Ct@CID + u32 rsv; // \B +} ROM_OVT; + + +// OVT̍őTCYiɂ‚Ă͍čl̗]nj +#define MB_OVT_MAX_SIZE MB_COMM_BLOCKSIZE + +// Overlay Table Buffer +// }`u[gvOŁAX^eBbNCjVCUN̂ɕKv +// I[o[Ce[uŗeʂςĂB +// IPL2ɂdlł܂܂ŁAɒuĂ +static u32 mb_ovt_buf[MB_OVT_MAX_SIZE/sizeof(u32)]; + +static void MB_SetOverlayTable(ROM_OVT *srcp, u16 sec_num) +{ + if (srcp && sec_num) + { + MI_CpuCopy8((void*)srcp, (void*)mb_ovt_buf, sec_num*sizeof(ROM_OVT)); + } +} + +#endif diff --git a/build/libraries_sysmenu/sysmenu/ARM9/MakeCrt0 b/build/libraries_sysmenu/sysmenu/ARM9/MakeCrt0 new file mode 100644 index 0000000..95df676 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/MakeCrt0 @@ -0,0 +1,46 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + + +SUBDIRS = + + +#---------------------------------------------------------------------------- +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED +TWL_PROC = ARM9 + +SRCS = crt1.c + +TARGET_OBJ = crt1.o + +LINCLUDES = $(COMMON_DIR) + +include $(TWLIPL_ROOT)/build/buildtools/commondefs.sysmenu + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(SYSMENU_INSTALL_LIBDIR) + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules.sysmenu + + +#===== End of Makefile ===== diff --git a/build/libraries_sysmenu/sysmenu/ARM9/Makefile b/build/libraries_sysmenu/sysmenu/ARM9/Makefile new file mode 100644 index 0000000..41d3503 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/Makefile @@ -0,0 +1,53 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +MYSUBDIRS = ./ + +#---------------------------------------------------------------------------- +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED +TWL_PROC = ARM9 + +SRCS = sysmenu_lib.c sysmenu_card.c sysmenu_util.c gameBoot.c ninLogoFunc.c cmn.c \ + nitroSettingsEx.c + +TARGET_LIB = libsysmenu$(TWL_LIBSUFFIX).a + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = $(SYSMENU_INSTALL_LIBDIR) + +LINCLUDES = $(TWLSDK_ROOT)/build/libraries/mb/common/include \ + $(TWLSDK_ROOT)/build/libraries/spi/ARM9/include \ + +#---------------------------------------------------------------------------- + +do-build: $(MYSUBDIRS) $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +$(MYSUBDIRS):: +# $(MAKE) -C $@ -f MakeCrt0 + +#===== End of Makefile ===== diff --git a/build/libraries_sysmenu/sysmenu/ARM9/include/sysmenu_card.h b/build/libraries_sysmenu/sysmenu/ARM9/include/sysmenu_card.h new file mode 100644 index 0000000..eeee6e8 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/include/sysmenu_card.h @@ -0,0 +1,248 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SYSM_card.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef SYSM_CARD_H_ +#define SYSM_CARD_H_ + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +//---------------------------------------------------------------------- +// J[ho +// +//EARM7 J[h̃_E[h܂ł͌oJn܂B +//Eo̓J[hoXւ̃ANZXbN܂B +//EAvP[VNO SYSM_FinalizeCardPulledOut() +// ĂяoĊmɌo悤ɂĉB +//---------------------------------------------------------------------- + +BOOL SYSM_IsCardPulledOut(void); + + +//---------------------------------------------------------------------- +// J[hoI +//---------------------------------------------------------------------- + +void SYSM_FinalizeCardPulledOut(void); + + +//---------------------------------------------------------------------- +// J[ho +//---------------------------------------------------------------------- + +BOOL SYSM_IsDetectingCardPulledOut(void); + + +//---------------------------------------------------------------------- +// J[ho +//---------------------------------------------------------------------- + +void SYSMi_InitCardPulledOut(void); + + +//---------------------------------------------------------------------- +// J[hIDǂݍ +//---------------------------------------------------------------------- + +u32 SYSMi_ReadCardID(void); + + +//---------------------------------------------------------------------- +// J[hf[^ǂݍ +//---------------------------------------------------------------------- + +void SYSM_ReadCard(void *romp, void *ramp, s32 size); + + +//---------------------------------------------------------------------- +// J[h̃f[^]̓fBH +//---------------------------------------------------------------------- + +#define SYSMi_IsCardDataReady() \ + \ + (*(vu32 *)REG_CARDCNT & CARD_DATA_READY) + +//EJ[h̃f[^]̓fBǂԂ܂B + +//---------------------------------------------------------------------- +// J[hf[^҂ +//---------------------------------------------------------------------- + +#define SYSMi_WaitCardData() \ +{ \ + while (!SYSMi_IsCardDataReady()) ; \ +} + +//EJ[hf[^]̏I҂܂B + + +//---------------------------------------------------------------------- +// J[h̓rW[H +//---------------------------------------------------------------------- + +#define SYSMi_IsCardBusy() \ + \ + (*(vu32 *)REG_CARDCNT & CARD_START) + +//EJ[hrW[ǂԂ܂B + +//---------------------------------------------------------------------- +// J[h҂ +//---------------------------------------------------------------------- + +#define SYSMi_WaitCard() \ +{ \ + while (SYSMi_IsCardBusy()) ; \ +} + +//EJ[h̏I҂܂B + + +//---------------------------------------------------------------------- +// Rg[p[^liGAME[hj +//---------------------------------------------------------------------- + +#define SYSMi_GetCardCnt4Game() \ + \ + (*(vu32 *)MROMCNT_GAME_BUF) + +//EGAME[h̃Rg[p[^l܂B + + + +//---------------------------------------------------------------------- +// qnlGAE}bv +//---------------------------------------------------------------------- + +#define MROM_SECURE_AREA 0x4000 // SECUREGA +#define MROM_GAME_AREA 0x8000 // GAMEGA + +//---------------------------------------------------------------------- +// qnlGAETCY +//---------------------------------------------------------------------- + +#define MROM_SEGMENT_SIZE 0x1000 // ZOgTCY +#define MROM_SECURE_SIZE 0x4000 // SECUREGATCY + +#ifndef MROM_PAGE_SIZE +#define MROM_PAGE_SIZE 512 // }XNqnlEy[W +#endif + +//---------------------------------------------------------------------- +// E}bv +//---------------------------------------------------------------------- + +#define MROMCNT_GAME_BUF (HW_ROM_HEADER_BUF + 0x60) // GAME[hERg[f[^ +#define MROMCNT_SECURE_BUF (HW_ROM_HEADER_BUF + 0x64) // SECURE[hERg[f[^ + + +//---------------------------------------------------------------------- +// WX^EAhX +//---------------------------------------------------------------------- + +#ifndef REG_BASE +#define REG_BASE 0x04000000 // WX^Q +#endif +#ifndef REG_IME +#define REG_IME (REG_BASE + 0x208) // 荞݃}X^Cl[u +#endif + +#define REG_CARDMST_SPI_CNT (REG_BASE + 0x1a0) // J[h}X^[rohRg[ + +#define REG_CARD_MASTER_CNT (REG_BASE + 0x1a1) // J[h}X^[Rg[ + +#define REG_CARD_SPI_CNT (REG_BASE + 0x1a0) // J[hrohRg[ +#define REG_CARD_SPI_DATA (REG_BASE + 0x1a2) // f[^ + +#define REG_CARDCNT (REG_BASE + 0x1a4) // J[hRg[ +#define REG_CARD_CMD (REG_BASE + 0x1a8) // R}hݒ +#define REG_CARD_DATA (REG_BASE + 0x100010) // f[^ + + +//---------------------------------------------------------------------- +// J[h }X^[Rg[ +//---------------------------------------------------------------------- + +#define CARDMST_SEL_DEVICE 0x20 // foCXI +#define CARDMST_SEL_ROM 0x00 // }XNqnl^RcI +#define CARDMST_SEL_SPI 0x20 // rohI + +#define CARDMST_IF_ENABLE 0x40 // 荞ݗv +#define CARDMST_ENABLE 0x80 // J[hCl[u + + +//---------------------------------------------------------------------- +// J[hANZX Rg[ +//---------------------------------------------------------------------- + +#define CARD_LATENCY1_CYCLES_MASK 0x00001fff // CeVP̃TCN +#define CARD_LATENCY2_CYCLES_MASK 0x003f0000 // CeVQ̃TCN +#define CARD_LATENCY_MASK 0x003f1fff // L킹}XN + +#define CARD_LATENCY1_CYCLES_SHIFT 0 +#define CARD_LATENCY2_CYCLES_SHIFT 16 + +#define CARD_DATA_SCRAMBLE_ON 0x00002000 // f[^XNu nm +#define CARD_SCRAMBLE_UNIT_ON 0x00004000 // XNuH nm +#define CARD_CMD_SCRAMBLE_ON 0x00400000 // R}hXNu nm + // XNutOQ̃Zbg +#define CARD_SCRAMBLE_SET_MASK ( CARD_SCRAMBLE_UNIT_ON | CARD_DATA_SCRAMBLE_ON \ + | CARD_CMD_SCRAMBLE_ON) + +#define CARD_DATA_READY 0x00800000 // f[^ fB + +#define CARD_1_PAGE 0x01000000 // Py[W +#define CARD_STATUS 0x07000000 // Xe[^X[h + +#define CARD_RESET_LO 0x00000000 // ZbgMx k +#define CARD_RESET_HI 0x20000000 // g +#define CARD_ACCESS_MODE 0x40000000 // ANZX [h +#define CARD_READ_MODE 0x00000000 // [h[h +#define CARD_WRITE_MODE 0x40000000 // Cg[h +#define CARD_START 0x80000000 // X^[g + +// \̃op萔 + +#define ST_CARD_1_PAGE 1 // Py[W +#define ST_CARD_STATUS 7 // Xe[^X[h + +#define ST_CARD_READ_MODE 0 // [h[h +#define ST_CARD_WRITE_MODE 1 // Cg[h + + +//---------------------------------------------------------------------- +// }XNqnlR}h +//---------------------------------------------------------------------- + +// GAME[h + +#define MROMOP_G_OP_MASK 0xff000000 // R}h}XN + +#define MROMOP_G_READ_ID 0xb8000000 // hcǂݍ +#define MROMOP_G_READ_PAGE 0xb7000000 // y[Wǂݍ + + + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // SYSM_CARD_H_ diff --git a/build/libraries_sysmenu/sysmenu/ARM9/include/sysmenu_define.h b/build/libraries_sysmenu/sysmenu/ARM9/include/sysmenu_define.h new file mode 100644 index 0000000..05e8886 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/include/sysmenu_define.h @@ -0,0 +1,50 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SYSM_define.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __SYSM_DEFINE_H__ +#define __SYSM_DEFINE_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// define data------------------------------------------- + + // 萔 +#define POW_LCDC_SW_TOP 0x0000 // LCDɉʕ\ +#define POW_LCDC_SW_BOTTOM 0x8000 // LCDɉʕ\ +#define POW_E2D2 0x0200 // 2DH2 ̓dON +#define POW_E2D1 0x0002 // 2DH1 ̓dON +#define POW_ELC 0x0001 // LCDCH̓dON + +#define SUBP_RECV_IF_ENABLE 0x4000 // 荞ݗvM + + // rpbNID +#define BOOTFLAG_LOCK_ID (OS_MAINP_LOCK_ID_END-1) +#define CARTRIDGE_LOCK_ID (OS_MAINP_LOCK_ID_END-2) + + // SetBootFlag֐̈int set_clear_flagŎw肷萔 +#define SBF_CLEAR 0 +#define SBF_SET 1 + +#ifdef __cplusplus +} +#endif + +#endif // __SYSM_DEFINE_H__ diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/cmn.c b/build/libraries_sysmenu/sysmenu/ARM9/src/cmn.c new file mode 100644 index 0000000..055928d --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/cmn.c @@ -0,0 +1,250 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: mainFunc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include + +#include + + +/*---------------------------------------------------------------------------* + Name: CMN_InitFileSystem + + Description: t@CVXeLɂ܂B + ܂At@Ce[uɓǂݍ݂܂B + + Arguments: pAllocator: LȃAP[^ւ̃|C^B + + Returns: ȂB + *---------------------------------------------------------------------------*/ +// t@CVXe +void CMN_InitFileSystem( NNSFndAllocator* pAllocator ) +{ + SDK_NULL_ASSERT( pAllocator ); + + // ARM7Ƃ̒ʐMFIFO荞݋ + (void)OS_EnableIrqMask(OS_IE_SPFIFO_RECV); + + // t@CVXe + FS_Init( FS_DMA_NOT_USE ); + + // t@Ce[uLbV + if( pAllocator != NULL ) + { + const u32 need_size = FS_GetTableSize(); + void *p_table = NNS_FndAllocFromAllocator( pAllocator, need_size ); + SDK_ASSERT(p_table != NULL); + (void)FS_LoadTable(p_table, need_size); + } +} + + + +/*---------------------------------------------------------------------------* + Name: CMN_ClearVram + + Description: VRAM NA܂B + VRAM SĖ蓖ĂłȂ΂Ȃ܂B + + Arguments: ȂB + + Returns: ȂB + *---------------------------------------------------------------------------*/ +// VRAMNA +void CMN_ClearVram( void ) +{ + //--------------------------------------------------------------------------- + // All VRAM banks to LCDC + //--------------------------------------------------------------------------- + GX_SetBankForLCDC(GX_VRAM_LCDC_ALL); + + //--------------------------------------------------------------------------- + // Clear all LCDC space + //--------------------------------------------------------------------------- + MI_CpuClearFast((void *)HW_LCDC_VRAM, HW_LCDC_VRAM_SIZE); + + //--------------------------------------------------------------------------- + // Disable the banks on LCDC + //--------------------------------------------------------------------------- + (void)GX_DisableBankForLCDC(); + + MI_CpuFillFast((void *)HW_OAM, 192, HW_OAM_SIZE); // clear OAM + MI_CpuClearFast((void *)HW_PLTT, HW_PLTT_SIZE); // clear the standard palette + + MI_CpuFillFast((void*)HW_DB_OAM, 192, HW_DB_OAM_SIZE); // clear OAM + MI_CpuClearFast((void *)HW_DB_PLTT, HW_DB_PLTT_SIZE); // clear the standard palette +} + + + +/*---------------------------------------------------------------------------* + Name: CMN_LoadFile + + Description: t@CɃ[h܂B + t@Cf[^svɂȂꍇ + CMN_UnloadFile( *ppFile, pAlloc ) Ńt@Cf[^ + ܂B + + Arguments: ppFile: t@C[hAhX󂯎 + obt@ւ̃|C^B + fpath: [ht@C̃pX + pAlloc: AP[^ւ̃|C^ + + Returns: [ht@C̃t@CTCYԂ܂B + 0 ̏ꍇ̓t@C[hɎs\܂B + ̏ꍇ *ppFile ̒l͖łB + *---------------------------------------------------------------------------*/ +u32 CMN_LoadFile(void** ppFile, const char* fpath, NNSFndAllocator* pAlloc) +{ + BOOL bSuccess; + FSFile f; + u32 length; + u32 read; + + SDK_NULL_ASSERT( ppFile ); + SDK_NULL_ASSERT( fpath ); + SDK_NULL_ASSERT( pAlloc ); + + FS_InitFile(&f); + + bSuccess = FS_OpenFile(&f, fpath); + if( ! bSuccess ) + { + OS_Warning("file (%s) not found", fpath); + return 0; + } + + length = FS_GetLength(&f); + *ppFile = NNS_FndAllocFromAllocator(pAlloc, length); + if( *ppFile == NULL ) + { + OS_Warning("cant allocate memory for file: %s", fpath); + return 0; + } + + read = (u32)FS_ReadFile(&f, *ppFile, (s32)length); + if( read != length ) + { + OS_Warning("fail to load file: %s", fpath); + NNS_FndFreeToAllocator(pAlloc, *ppFile); + return 0; + } + + bSuccess = FS_CloseFile(&f); + if( ! bSuccess ) + { + OS_Warning("fail to close file: %s", fpath); + } + + return length; +} + + + +/*---------------------------------------------------------------------------* + Name: CMN_UnloadFile + + Description: t@Cf[^܂B + + Arguments: pFile: t@Cf[^ւ̃|C^ + pAlloc: t@C[hɗpAP[^ւ̃|C^ + + Returns: ȂB + *---------------------------------------------------------------------------*/ +void CMN_UnloadFile(void* pFile, NNSFndAllocator* pAlloc) +{ + NNS_FndFreeToAllocator(pAlloc, pFile); +} + + + +/*---------------------------------------------------------------------------* + Name: CMN_LoadArchive + + Description: pXŎw肳ꂽA[JCuɓǂݍ݁At@CVX + eɃ}Eg܂B + A[JCusvɂȂꍇ + CMN_RemoveArchive( Ԃl, pAllocator ) ŃA[JCu + ܂B + + Arguments: name: A[JCut@CVXeŎʂׂ̖OB + path: A[JCũpXB + pAllocator: AP[^ւ̃|C^ + + Returns: A[JCũ[hɐ΁ANNSFndArchive \̂ւ̃|C + ^Ԃ܂Bsꍇɂ́ANULLԂ܂B + *---------------------------------------------------------------------------*/ +NNSFndArchive* +CMN_LoadArchive(const char* name, const char* path, NNSFndAllocator* pAllocator) +{ + FSFile file; + NNSFndArchive* archive = NULL; + + SDK_NULL_ASSERT(name); + SDK_NULL_ASSERT(path); + SDK_NULL_ASSERT(pAllocator); + + FS_InitFile(&file); + if (FS_OpenFile(&file, path)) + { + u32 binarySize = FS_GetLength(&file); + u32 memorySize = MATH_ROUNDUP(sizeof(NNSFndArchive), 16) + MATH_ROUNDUP(binarySize, 16); + + u8* memory = (u8*)NNS_FndAllocFromAllocator(pAllocator, memorySize); + + if (memory != NULL) + { + u8* binary = memory + MATH_ROUNDUP(sizeof(NNSFndArchive), 16); + + if ((u32)FS_ReadFile(&file, binary, (s32)binarySize) == binarySize) + { + if (NNS_FndMountArchive((NNSFndArchive*)memory, name, binary)) + { + archive = (NNSFndArchive*)memory; + } + } + } + (void)FS_CloseFile(&file); + } + return archive; +} + + + +/*---------------------------------------------------------------------------* + Name: CMN_RemoveArchive + + Description: w肳ꂽA[JCu폜܂B + + w肳ꂽA[JCut@CVXeA}EgAA + [JCuǂݍ܂Ă܂B + + Arguments: archive: NNSA[JCu\̂ւ̃|C^B + pAllocator: A[JCu[hɗpAP[^ւ̃|C^B + + Returns: ȂB + *---------------------------------------------------------------------------*/ +void +CMN_RemoveArchive(NNSFndArchive* archive, NNSFndAllocator* pAllocator) +{ + SDK_NULL_ASSERT(archive); + SDK_NULL_ASSERT(pAllocator); + + (void)NNS_FndUnmountArchive(archive); + NNS_FndFreeToAllocator(pAllocator, archive); +} + diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/crt1.c b/build/libraries_sysmenu/sysmenu/ARM9/src/crt1.c new file mode 100644 index 0000000..c5d8408 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/crt1.c @@ -0,0 +1,559 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: crt1.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include // SYSM changed. + +#define SDK_NOCOMPRESS // SYSM changed. + + +extern void NitroMain( void ); +extern void OS_IrqHandler( void ); +static void do_autoload( void ); +static void init_cp15( void ); +void _start( void ); +extern void* const _start_ModuleParams[]; +void _start_AutoloadDoneCallback( void* argv[] ); + +extern void __call_static_initializers( void ); +extern void _fp_init( void ); + +// from LCF +extern u32 SDK_IRQ_STACKSIZE[]; +extern void SDK_AUTOLOAD_START( void ); // autoload data will start from here +extern void SDK_AUTOLOAD_LIST( void ); // start pointer to autoload information +extern void SDK_AUTOLOAD_LIST_END( void ); // end pointer to autoload information +extern void SDK_STATIC_BSS_START( void ); // static bss start address +extern void SDK_STATIC_BSS_END( void ); // static bss end address + + +/*---------------------------------------------------------------------------* + Name: _start + + Description: Start up + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +#define INITi_HW_DTCM SDK_AUTOLOAD_DTCM_START + +__declspec ( weak ) asm void _start( void ) +{ + //---- set IME = 0 + // ( use that LSB of HW_REG_BASE equal to 0 ) + mov r12, #HW_REG_BASE + str r12, [r12, #REG_IME_OFFSET] + + //---- initialize cp15 + bl init_cp15 + + //---- initialize stack pointer + // SVC mode + mov r0, #HW_PSR_SVC_MODE + msr cpsr_c, r0 + ldr r0, =INITi_HW_DTCM + add r0, r0, #0x3fc0 + mov sp, r0 + + // IRQ mode + mov r0, #HW_PSR_IRQ_MODE + msr cpsr_c, r0 + ldr r0, =INITi_HW_DTCM + add r0, r0, #0x3fc0 + sub r0, r0, #HW_SVC_STACK_SIZE + mov sp, r0 + + // System mode + ldr r1, =SDK_IRQ_STACKSIZE + sub r1, r0, r1 + mov r0, #HW_PSR_SYS_MODE + msr cpsr_csfx, r0 + sub sp, r1, #4 // 4byte for stack check code + + //---- load autoload block and initialize bss +#ifndef SDK_NOCOMPRESS + ldr r1, =_start_ModuleParams + ldr r0, [r1, #20] // r0 = bottom of compressed data + bl MIi_UncompressBackward +#endif + bl do_autoload + + //---- clear memory + // DTCM (16KB) + mov r0, #0 + ldr r1, =INITi_HW_DTCM + mov r2, #HW_DTCM_SIZE + bl MIi_CpuClear32 + +/* // BG/OBJ palette (1KB) // SYSM changed. + mov r0, #0 + ldr r1, =HW_PLTT + mov r2, #HW_PLTT_SIZE + bl MIi_CpuClear32 + + // OAM (1KB) + mov r0, #0x0200 + ldr r1, =HW_OAM + mov r2, #HW_OAM_SIZE + bl MIi_CpuClear32 +*/ + //---- set interrupt vector + ldr r1, =INITi_HW_DTCM + add r1, r1, #0x3fc0 + add r1, r1, #HW_DTCM_SYSRV_OFS_INTR_VECTOR + ldr r0, =OS_IrqHandler + str r0, [r1, #0] + +#ifndef SDK_NOINIT + //---- for C++ + bl _fp_init + bl NitroStartUp + bl __call_static_initializers +#endif + //---- start (to 16bit code) + ldr r1, =NitroMain +// ldr lr, =HW_RESET_VECTOR + ldr lr, =RETURN_FROM_MAIN_ARM9_FUNCP // SYSM changed. + + bx r1 +} + +/*---------------------------------------------------------------------------* + Name: _start_ModuleParams + + Description: autoload/compress/arguments data block + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +void* const _start_ModuleParams[] = +{ + (void*)SDK_AUTOLOAD_LIST, + (void*)SDK_AUTOLOAD_LIST_END, + (void*)SDK_AUTOLOAD_START, + (void*)SDK_STATIC_BSS_START, + (void*)SDK_STATIC_BSS_END, +#ifndef SDK_NOCOMPRESS + (void*)0, // CompressedStaticEnd +#endif +}; + +/*---------------------------------------------------------------------------* + Name: MIi_UncompressBackward + + Description: Uncompress special archive for module compression + + Arguments: bottom = Bottom adrs of packed archive + 1 + bottom[-12] = offset for top of compressed data + inp_top = bottom + bottom[-12] + bottom[ -8] = offset for bottom of compressed data + inp = bottom + bottom[ -8] + bottom[ -4] = offset for bottom of original data + outp = bottom + bottom[ -4] + + typedef struct + { + int bufferTop; + int compressBottom; + int originalBottom; + } CompFooter; + + Returns: None. + *---------------------------------------------------------------------------*/ +asm void MIi_UncompressBackward( register void* bottom ) +{ +#define data r0 +#define inp_top r1 +#define outp r2 +#define inp r3 +#define outp_save r4 +#define flag r5 +#define count8 r6 +#define index r7 +#define len r12 + cmp bottom, #0 + beq @exit + stmfd sp!, {r4-r7} + ldmdb bottom, {r1-r2} + add outp, bottom, outp + sub inp, bottom, inp_top, LSR #24 + bic inp_top, inp_top, #0xff000000 + sub inp_top, bottom, inp_top + mov outp_save, outp +@loop: + cmp inp, inp_top // exit if inp==inp_top + ble @end_loop + ldrb flag, [inp, #-1]! // r4 = compress_flag = *--inp + mov count8, #8 +@loop8: + subs count8, count8, #1 + blt @loop + tst flag, #0x80 + bne @blockcopy +@bytecopy: + ldrb data, [inp, #-1]! +#ifdef SDK_TEG + sub outp, outp, #1 + swpb data, data, [outp] +#else + strb data, [outp, #-1]! // Copy 1 byte +#endif + b @joinhere +@blockcopy: + ldrb len, [inp, #-1]! + ldrb index, [inp, #-1]! + orr index, index, len, LSL #8 + bic index, index, #0xf000 + add index, index, #0x0002 + add len, len, #0x0020 +@patterncopy: + ldrb data, [outp, index] +#ifdef SDK_TEG + sub outp, outp, #1 + swpb data, data, [outp] +#else + strb data, [outp, #-1]! +#endif + subs len, len, #0x0010 + bge @patterncopy + +@joinhere: + cmp inp, inp_top + mov flag, flag, LSL #1 + bgt @loop8 +@end_loop: + + // DC_FlushRange & IC_InvalidateRange + bic inp, inp_top, #HW_CACHE_LINE_SIZE - 1 +@cacheflush: + mcr p15, 0, inp, c7, c5, 1 // ICache + mcr p15, 0, inp, c7, c14, 1 // DCache + add inp, inp, #HW_CACHE_LINE_SIZE + cmp inp, outp_save + blt @cacheflush + + ldmfd sp!, {r4-r7} +@exit bx lr +} + + +/*---------------------------------------------------------------------------* + Name: do_autoload + + Description: put autoload data block according to autoload information, + and clear static bss by filling with 0. + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +static asm void do_autoload( void ) +{ +#define ptable r0 +#define infop r1 +#define infop_end r2 +#define src r3 +#define dest r4 +#define dest_size r5 +#define dest_end r6 +#define tmp r7 + + ldr ptable, =_start_ModuleParams + ldr infop, [ptable, #0] // r1 = start pointer to autoload_info + ldr infop_end, [ptable, #4] // r2 = end pointer to autoload_info + ldr src, [ptable, #8] // r3 = autoload block + +@2: + cmp infop, infop_end // reach to end? + beq @fill_bss + + ldr dest, [infop], #4 // dest + ldr dest_size, [infop], #4 // size + add dest_end, dest, dest_size // dest_end +@1: + cmp dest, dest_end + ldrmi tmp, [src], #4 // [dest++] <- [src++] + strmi tmp, [dest], #4 + bmi @1 + + //---- fill bss with 0 + ldr dest_size, [infop], #4 // size + add dest_end, dest, dest_size // bss end + mov tmp, #0 +@4: + cmp dest, dest_end + strcc tmp, [dest], #4 + bcc @4 + + beq @2 + + //---- fill static static bss with 0 +@fill_bss: + ldr dest, [ptable, #12] // BSS segment start + ldr dest_end, [ptable, #16] // BSS segment end + mov tmp, #0 +@3: + cmp dest, dest_end + strcc tmp, [dest], #4 + bcc @3 + + // r0 = _start_ModuleParams + b _start_AutoloadDoneCallback // Jump into the callback +} + +/*---------------------------------------------------------------------------* + Name: _start_AutoloadDoneCallback + + Description: hook for end of autoload (This is dummy target for DEBUGGER) + + Arguments: argv: pointer for autoload parameters + argv[0] = SDK_AUTOLOAD_LIST + argv[1] = SDK_AUTOLOAD_LIST_END + argv[2] = SDK_AUTOLOAD_START + argv[3] = SDK_STATIC_BSS_START + argv[4] = SDK_STATIC_BSS_END + + Returns: None. + *---------------------------------------------------------------------------*/ +__declspec ( weak ) asm void _start_AutoloadDoneCallback( void* argv[] ) +{ + bx lr +} + +//----------------------------------------------------------------------- +// VXeRvZbT +//----------------------------------------------------------------------- +static asm void init_cp15(void) +{ + // veNVjbg/LbV/TCM fBZ[u + + mrc p15, 0, r0, c1, c0, 0 + ldr r1, =HW_C1_ICACHE_ENABLE | HW_C1_DCACHE_ENABLE \ + | HW_C1_ITCM_ENABLE | HW_C1_DTCM_ENABLE \ + | HW_C1_ITCM_LOAD_MODE | HW_C1_DTCM_LOAD_MODE \ + | HW_C1_LD_INTERWORK_DISABLE \ + | HW_C1_PROTECT_UNIT_ENABLE + bic r0, r0, r1 + mcr p15, 0, r0, c1, c0, 0 + + // LbV + mov r0, #0 + mcr p15, 0, r0, c7, c5, 0 // ߃LbV + mcr p15, 0, r0, c7, c6, 0 // f[^LbV + + // Cgobt@ GveB҂ + mcr p15, 0, r0, c7, c10, 4 + +/* +; Region G: BACK_GROUND: Base = 0x0, Size = 4GB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 0: IO_VRAM: Base = 0x04000000, Size = 64MB, I:NC NB / D:NC NB, I:RW / D:RW +; Region 1Rel: MAIN_MEM: Base = 0x02000000, Size = 4MB, I:Cach Buf / D:Cach Buf, I:RW / D:RW +; Region 1Dbg: MAIN_MEM: Base = 0x02000000, Size = 8MB, I:Cach Buf / D:Cach Buf, I:RW / D:RW +; Region 2Rel: SOUND_DATA: Base = 0x02380000, Size = 512KB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 2D4M: SOUND_DATA: Base = 0x02300000, Size = 1MB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 2D8M: SOUND_DATA: Base = 0x02600000, Size = 2MB, I:NC NB / D:NC NB, I:NA / D:NA +; Region 3: CARTRIDGE: Base = 0x08000000, Size = 128MB, I:NC NB / D:NC NB, I:NA / D:RW +; Region 4: DTCM: Base = SOUND_DATA, Size = 16KB, I:NC NB / D:NC NB, I:NA / D:RW +; Region 5: ITCM: Base = 0x01000000, Size = 16MB, I:NC NB / D:NC NB, I:RW / D:RW + +; Region 6: BIOS: Base = 0xffff0000, Size = 32KB, I:Cach NB / D:Cach NB, I:RO / D:RO +; Region 7: SHARE_WORK: Base = 0x027ff000, Size = 4KB, I:NC NB / D:NC NB, I:NA / D:RW +;(Region 7: DBG_RESERVE: Base = 0x02700000, Size = 1MB, I:NC NB / D:NC NB, I:RW / D:RW) +*/ +#define SET_PROTECTION_A( id, adr, siz ) ldr r0, =(adr|HW_C6_PR_##siz|HW_C6_PR_ENABLE) +#define SET_PROTECTION_B( id, adr, siz ) mcr p15, 0, r0, c6, id, 0 +#define REGION_BIT(a,b,c,d,e,f,g,h) (((a)<<0)|((b)<<1)|((c)<<2)|((d)<<3)|((e)<<4)|((f)<<5)|((g)<<6)|((h)<<7)) +#define REGION_ACC(a,b,c,d,e,f,g,h) (((a)<<0)|((b)<<4)|((c)<<8)|((d)<<12)|((e)<<16)|((f)<<20)|((g)<<24)|((h)<<28)) +#define NA 0 +#define RW 1 +#define RO 5 + + + // + // [W + // + //---- I/O WX^ & VRAM + SET_PROTECTION_A( c0, HW_IOREG, 64MB ) + SET_PROTECTION_B( c0, HW_IOREG, 64MB ) + + //---- C + SET_PROTECTION_A( c1, HW_MAIN_MEM_MAIN, 4MB ) + SET_PROTECTION_B( c1, HW_MAIN_MEM_MAIN, 4MB ) + +/* //---- TEhf[^̈ // SYSM changed. +#if HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x1000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 4KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 4KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x2000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 8KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 8KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x4000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 16KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 16KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x8000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 32KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 32KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x10000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 64KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 64KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x20000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 128KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 128KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x40000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 256KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 256KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x80000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 512KB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 512KB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x100000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 1MB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 1MB ) +#elif HW_MAIN_MEM_SUB_SIZE+HW_MAIN_MEM_SHARED_SIZE == 0x200000 + SET_PROTECTION_A( c2, HW_MAIN_MEM_SUB, 2MB ) + SET_PROTECTION_B( c2, HW_MAIN_MEM_SUB, 2MB ) +#else +#pragma message(ERROR: Size unmatch HW_MAIN_MEM_SUB_SIZE) +#endif +*/ + //---- J[gbW̗͑pr + // CPU [N RAM + SET_PROTECTION_A( c3, HW_CTRDG_ROM, 128MB ) + SET_PROTECTION_B( c3, HW_CTRDG_ROM, 128MB ) + + //---- f[^ TCM + // + CPU [N RAM ̏ꍇ +//#if (HW_DTCM & 0x3FFF) != 0 +//#pragma message(ERROR: HW_DTCM need to be aligned 16KB!) +//#endif + +// SET_PROTECTION_A( c4, HW_DTCM, 16KB ) + ldr r0, =SDK_AUTOLOAD_DTCM_START + orr r0, r0, #HW_C6_PR_16KB + orr r0, r0, #HW_C6_PR_ENABLE + SET_PROTECTION_B( c4, HW_DTCM, 16KB ) + + //---- TCM + // f[^ TCM D悪AC̈܂ł̃C[W + SET_PROTECTION_A( c5, HW_ITCM_IMAGE, 16MB ) + SET_PROTECTION_B( c5, HW_ITCM_IMAGE, 16MB ) + + //---- BIOS + SET_PROTECTION_A( c6, HW_BIOS, 32KB ) + SET_PROTECTION_B( c6, HW_BIOS, 32KB ) + + //---- SHARED CPU ԒʐM[N̈ + SET_PROTECTION_A( c7, HW_MAIN_MEM_SHARED, 4KB ) + SET_PROTECTION_B( c7, HW_MAIN_MEM_SHARED, 4KB ) + +#if HW_MAIN_MEM_SHARED_SIZE != 0x1000 +#pragma message(ERROR: Size unmatch HW_MAIN_MEM_SHARED_SIZE) +#endif + + // + // ߂sbl ݒ + // + mov r0, #HW_C9_TCMR_32MB + mcr p15, 0, r0, c9, c1, 1 + + // + // f[^sbl ݒ + // + ldr r0, =INITi_HW_DTCM + orr r0, r0, #HW_C9_TCMR_16KB + mcr p15, 0, r0, c9, c1, 0 + + // + // ߃LbV Cl[u ([Wݒ) + // 1: MAIN_MEM + // 6: BIOS + // + mov r0, #REGION_BIT(0,1,0,0,0,0,1,0) + mcr p15, 0, r0, c2, c0, 1 + + // + // f[^LbV Cl[u ([Wݒ) + // 1: MAIN_MEM + // 6: BIOS + // + mov r0, #REGION_BIT(0,1,0,0,0,0,1,0) + mcr p15, 0, r0, c2, c0, 0 + + // + // Cgobt@ Cl[u([Wݒ) + // 1: MAIN_MEM + // + mov r0, #REGION_BIT(0,1,0,0,0,0,0,0) + mcr p15, 0, r0, c3, c0, 0 + + // + // ߃ANZX ([Wݒ) + // IO_VRAM : RW + // MAIN_MEM_MAIN : RW + // MAIN_MEM_SUB : NA + // CTRDG : NA + // DTCM : NA + // ITCM : RW + // BIOS : RO + // SHARED : NA + // + ldr r0, =REGION_ACC(RW,RW,NA,NA,NA,RW,RO,NA) + mcr p15, 0, r0, c5, c0, 3 + + // + // f[^ANZXi[Wݒj + // IO_VRAM : RW + // MAIN_MEM_MAIN : RW + // MAIN_MEM_SUB : NA + // CTRDG : RW + // DTCM : RW + // ITCM : RW + // BIOS : RO + // SHARED : RW + // + ldr r0, =REGION_ACC(RW,RW,NA,RW,RW,RW,RO,RW) + mcr p15, 0, r0, c5, c0, 2 + + // + // VXeRvZbT }X^[ݒ + // + mrc p15, 0, r0, c1, c0, 0 + ldr r1,=HW_C1_ICACHE_ENABLE | HW_C1_DCACHE_ENABLE | HW_C1_CACHE_ROUND_ROBIN \ + | HW_C1_ITCM_ENABLE | HW_C1_DTCM_ENABLE \ + | HW_C1_SB1_BITSET | HW_C1_EXCEPT_VEC_UPPER \ + | HW_C1_PROTECT_UNIT_ENABLE + orr r0, r0, r1 + mcr p15, 0, r0, c1, c0, 0 + + bx lr +} + + +/*---------------------------------------------------------------------------* + Name: NitroStartUp + + Description: hook for user start up + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +__declspec ( weak ) void NitroStartUp( void ) +{ +} diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/gameBoot.c b/build/libraries_sysmenu/sysmenu/ARM9/src/gameBoot.c new file mode 100644 index 0000000..558b328 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/gameBoot.c @@ -0,0 +1,247 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: gameBoot.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include + +// define data------------------------------------------------------- +#define C1_DTCM_ENABLE 0x00010000 // f[^sbl Cl[u +#define C1_EXCEPT_VEC_UPPER 0x00002000 // OxN^ ʃAhXiɐݒ肵ĉj +#define C1_SB1_BITSET 0x00000078 // WX^PpPŒrbgiA{[gfADATA32\VOiAPROG32\VOiACgobt@Cl[uj + +#define INITi_HW_DTCM SDK_AUTOLOAD_DTCM_START + +// extern data------------------------------------------------------- + +// from LCF +extern u32 SDK_IRQ_STACKSIZE[]; + +// function's prototype---------------------------------------------- +void ReturnFromMain(void); +void ResetCP15(void); +void ClearBankregAndStack(void); +void CpuClear32Byte(void); +void BootFuncEnd(void); + +// global variables-------------------------------------------------- + +// static variables-------------------------------------------------- + +// const data-------------------------------------------------------- + + +#include // ̃\[X̓ftHgłARMŃRpCB + +//----------------------------------------------------------------------- +// C[`̃^[ +//----------------------------------------------------------------------- + +/* + ReturnFromMainRam̌ɃRs[@AReturnFromMainAhXA +@@@(BootFuncEnd - ReturnFromMain)TCYRs[ƂĂ邪A +@@@̕@ƁARpC̍œKdlŊ֐тςĂ܂ɂȂB +@@@ɂ@͂ȂH +*/ + + +asm void ReturnFromMain(void) +{ + //--------------------------------------- + // f[^LbVSĖɁBiDC_InvalidateAll𔲂oĎj + //--------------------------------------- + mov r0, #0 + mcr p15, 0, r0, c7, c6, 0 + + //--------------------------------------- + // ARM7Ƃ̓Ƃisubp_state2ɂȂ̂҂āAmainp_state2ɂBj + //--------------------------------------- + ldr r1, =REG_SUBPINTF_ADDR +@0 ldrh r0, [r1] + and r0, r0, #0x000f + cmp r0, #0x0002 + bne @0 + mov r0, #0x0200 + strh r0, [r1] + + //--------------------------------------- + // ISfobKtO̊i[ + //--------------------------------------- +#ifdef __IS_DEBUGGER_BUILD + ldr r3, =HW_MAIN_MEM_EX_END + sub r0, r3, #0x400 + ldrh r11, [r0, #0x14] // r11 = GetMovedInfoFromIPL1Addr()->isOnDebugger +#endif + //--------------------------------------- + // ARM7Ƃ̓Ƃisubp_state1ɂȂ̂҂āAmainp_state1ɂBj + //--------------------------------------- + ldr r1, =REG_SUBPINTF_ADDR +@1 ldrh r0, [r1] + and r0, r0, #0x000f + cmp r0, #0x0001 + bne @1 + mov r0, #0x0100 + strh r0, [r1] + + //--------------------------------------- + // oNWX^X^bNNA + //--------------------------------------- + bl ClearBankregAndStack + + //--------------------------------------- + // veNVjbg̉ + //--------------------------------------- + bl ResetCP15 + + //--------------------------------------- + // ARM7Ƃ̍ŏIƂ(subp_state0ɂȂ̂҂āAmainp_state0ɂj + //--------------------------------------- + ldr r1, =REG_SUBPINTF_ADDR +@2 ldrh r0, [r1] + and r0, r0, #0x000f + cmp r0, #0x0001 + beq @2 + ldr r3, =REG_VCOUNT_ADDR // VJE^SIPL2o[Wœl(=0)ŃAvɈn悤ɂB +@3 ldrh r0, [r3] + cmp r0, #0 + bne @3 +// mov r0, #0 // R0ɓǂVJEgl"0"Ȃ̂ŁA͂Ȃ + strh r0, [r1] + + //--------------------------------------- + // R11̒lƂɃu[gAhX擾 + //--------------------------------------- + ldr r3, =HW_MAIN_MEM_EX_END // Q[EGg|Cg l + ldr r12, [r3, #-(0x200 - 0x24)] // rmhp->arm9->entryAddr + mov lr, r12 + +#ifdef __IS_DEBUGGER_BUILD + cmp r11, #1 // if (!GetMovedInfoFromIPL1Addr()->isOnDebugger) + ldreq r12, [r3, #-(0x200 - 0x168)] // fobKEGg|Cg l +#endif + + //--------------------------------------- + // ėpWX^NA + //--------------------------------------- + ldr r11, =INITi_HW_DTCM // NADTCMf[^ǂݏoāAėpWX^NAB + ldmia r11, {r0-r10} + mov r11, #0 + + //--------------------------------------- + // Q[u[g + //--------------------------------------- + bx r12 +} + + +//----------------------------------------------------------------------- +// VXeRvZbT Zbg +//----------------------------------------------------------------------- +asm void ResetCP15(void) +{ + // veNVjbgLbVITCMBDTCM͗LiX^bNNA邽߁j + ldr r0, = C1_DTCM_ENABLE | C1_EXCEPT_VEC_UPPER | C1_SB1_BITSET + mcr p15, 0, r0, c1, c0, 0 + + // ITCM̊蓖Ă + mov r0, #0 + mcr p15, 0, r0, c6, c5, 0 + + // DTCM̊蓖Ă +// mov r0,#0 +// mcr p15, 0, r0, c9, c1, 0 + + // LbV + mov r0, #0 + mcr p15, 0, r0, c7, c5, 0 // ߃LbV + mcr p15, 0, r0, c7, c6, 0 // f[^LbV + + // Cgobt@ GveB҂ + mcr p15, 0, r0, c7, c10, 4 + + bx lr +} + + +//----------------------------------------------------------------------- +// oNWX^ Zbg X^bN̈ NA +//----------------------------------------------------------------------- +asm void ClearBankregAndStack(void) +{ + mov r12, lr + +#ifndef IPL2_ONLYMULTIBOOT + mov r0, #0xc0 | HW_PSR_SVC_MODE // SVC[h֐؂芷 & IRQ/FIQs + msr cpsr_cxsf, r0 + ldr r0, =INITi_HW_DTCM + add r0, r0, #0x3fc0 + mov sp, r0 // SP ̃Zbg + mov lr, #0 + msr spsr_csxf, lr + + mov r0, #0xc0 | HW_PSR_IRQ_MODE // IRQ[h֐؂芷 & IRQ/FIQs + msr cpsr_cxsf, r0 + ldr r0, =INITi_HW_DTCM + add r0, r0, #0x3fc0 + sub r0, r0, #HW_SVC_STACK_SIZE + mov sp, r0 // SP ̃Zbg + mov lr, #0 + msr spsr_cxsf, lr + + ldr r1, =SDK_IRQ_STACKSIZE + sub r1, r0, r1 + mov r0, #0xc0 | HW_PSR_SYS_MODE // VXe[h֐؂芷 & IRQ/FIQs + msr cpsr_cxsf, r0 + sub sp, r1, #4 // SP ̃Zbg & 4byte for stack check code +#endif // IPL2_ONLYMULTIBOOT + + ldr r0, =HW_ITCM // ITCM̃NA + mov r1, #HW_ITCM_SIZE + bl CpuClear32Byte + + ldr r0, =INITi_HW_DTCM // X^bN܂߂DTCM̃NA + mov r1, #HW_DTCM_SIZE + bl CpuClear32Byte + + bx r12 +} + + +// 32bytePʂ̃NA r0 dstp,r1 byteSize +asm void CpuClear32Byte(void) +{ + add r2, r0, r1 // IAhX̎Zo + mov r1, r1, lsr #5 // TCY32byteP + mov r3, #0 + mov r4, r3 + mov r5, r3 + mov r6, r3 + mov r7, r3 + mov r8, r3 + mov r9, r3 + mov r10, r3 +@0 cmp r0, r2 // NAIH + stmltia r0!, {r3-r10} + blt @0 + bx lr +} + + +void BootFuncEnd(void) +{ +} +#include // ܂ŁB + diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/ninLogoFunc.c b/build/libraries_sysmenu/sysmenu/ARM9/src/ninLogoFunc.c new file mode 100644 index 0000000..cb4387a --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/ninLogoFunc.c @@ -0,0 +1,168 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: ninLogoFunc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include + +// define data----------------------------------------------------------- + +// extern data----------------------------------------------------------- + +// function's prototype-------------------------------------------------- +static void UnCompNintendoLogo2(u16 *NintendoLogoDatap, u16 *dstp, u32 *temp); +static void SVC_DiffUnFilter16_16_2(u16 *srcp,u16 *dstp); +static s32 MEMBm_InitFunc(const u8 *devicep, void *ramp, const void *paramp); +static s32 MEMBm_TerminateFunc(const u8 *devicep); +static u8 MEMBm_ByteStreamFunc(const u8 *devicep); +static u32 MEMBm_WordStreamFunc(const u8 *devicep); + + +// global variable------------------------------------------------------- + +// static variable------------------------------------------------------- +static MIUnpackBitsParam Nin_UnPackBitsParam2 = { (8 * 8 / 2) * ( 7 * 2 ), 1, 4, 0, 0 }; + +// const data------------------------------------------------------------ +static const u8 Nin_Char_Diff_Huff_Table2[]={ + 0x24,0xd4,0x00,0x00, + 0x0f,0x40,0x00,0x00,0x00,0x01,0x81,0x82,0x82,0x83,0x0f,0x83,0x0c,0xc3,0x03,0x83, + 0x01,0x83,0x04,0xc3,0x08,0x0e,0x02,0xc2,0x0d,0xc2,0x07,0x0b,0x06,0x0a,0x05,0x09, +}; + + +const MIReadStreamCallbacks memb_ifp2={ + MEMBm_InitFunc, + MEMBm_TerminateFunc, + MEMBm_ByteStreamFunc, + NULL, + MEMBm_WordStreamFunc, +}; + + +// function's description-------------------------------------------- + +// NintendoSf[^̓WJ[`iOBJ2D}bv[hœWJj +// tempBuffpɂ́A0x700byteKvłB +void SYSM_LoadNintendoLogo2D( u16 *ninLogoDatap, u16 *dstp, u16 color, u32 *tempBuffp ) +{ + u32 work[ 0x100 / sizeof(u32) ]; + + Nin_UnPackBitsParam2.destOffset = color - 1; + UnCompNintendoLogo2( ninLogoDatap, (u16 *)tempBuffp, work ); + MI_CpuCopyFast( (u16 *)( (u32)tempBuffp + 0 ), dstp + 0x0000 / sizeof(u16), 0x1a0 ); + MI_CpuCopyFast( (u16 *)( (u32)tempBuffp + 0x1a0), dstp + 0x0400 / sizeof(u16), 0x1a0 ); +} + + +void SYSM_LoadNintendoLogo1D( u16 *ninLogoDatap, u16 *dstp, u16 color, u32 *tempBuffp ) +{ + u32 work[ 0x100 / sizeof(u32) ]; + + Nin_UnPackBitsParam2.destOffset = color - 1; + UnCompNintendoLogo2( ninLogoDatap, (u16 *)tempBuffp, work ); + MI_CpuCopyFast( (u16 *)tempBuffp, dstp, 0x340 ); +} + +/* UnCompNintendoLogo2[N + + zu恄 dstp(0x700) temp(0x100) + + NintendoS{wb_ 0x0c0 + nt}WJobt@ 0x200 + nt}WJ̃obt@ 0x0d0 + diff̃f[^ 0x0d0 + UnpackBits̃f[^ 0x700 + +*/ + +//@NintendoSWJ[`@(r0=Skf[^ r1=WJAhX) +#include +static asm void UnCompNintendoLogo2(u16 *NintendoLogoDatap, u16 *dstp, u32 *temp) +{ + push {r0-r2,r4, lr} + + ldr r0, =Nin_Char_Diff_Huff_Table2 + mov r1, r2 // r1 <- temp + mov r4, r1 // r4 <- temp + mov r2, #36 + bl MIi_CpuCopy16 // NintendoS̈ke[û݂Rs[Ă + + ldr r0, [sp, #0] // r0 <- NintendoLogoDatap + mov r2, #36 + add r1, r4, r2 // r1 <- temp + 36 + mov r2, #NINTENDO_LOGO_LENGTH + bl MIi_CpuCopy16 // NintendoLogoDatapNintendoSf[^{̂Rs[Ă + + mov r0, r4 // r0 <- temp + ldr r1, [sp, #4] // r1 <- dstp + mov r2, #1 + lsl r2, r2, #8 + add r2, r2, r1 // r2 <- dstp + 0x100 + ldr r3, =memb_ifp2 // r3 <- memb_ifp2 + bl SVC_UncompressHuffmanFromDevice // nt}WJ + + ldr r0, [sp, #4] + ldr r2, =0x0000d082 + str r2, [r0,#0] + + mov r1, r4 // temp + bl SVC_DiffUnFilter16_16_2 // DiffWJ + + mov r0, r4 // temp + ldr r1, [sp, #4] // dstp + ldr r2, =Nin_UnPackBitsParam2 + bl SVC_UnpackBits // rbgWJ + + pop {r0-r2,r4, pc} +} + + +// tB^WJVXeR[i16Bit16Bitj (r0=Srcp, r1=Destp) +static asm void SVC_DiffUnFilter16_16_2(u16 *srcp,u16 *dstp) +{ + swi 24 + bx lr +} +#include + + +// ============================================================================ +// oCgANZX”\pANZX[`Q +// ============================================================================ +static s32 MEMBm_InitFunc(const u8 *devicep, void *ramp, const void *paramp) +{ + #pragma unused(ramp) + if(paramp) return (s32)MEMBm_WordStreamFunc(devicep); + else return 0; +} + +static s32 MEMBm_TerminateFunc(const u8 *devicep) +{ + #pragma unused(devicep) + return 0; +} + +static u8 MEMBm_ByteStreamFunc(const u8 *devicep) +{ + return *devicep; +} + +static u32 MEMBm_WordStreamFunc(const u8 *devicep) +{ + return *(u32 *)devicep; +} diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/nitroSettingsEx.c b/build/libraries_sysmenu/sysmenu/ARM9/src/nitroSettingsEx.c new file mode 100644 index 0000000..6cfbd2b --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/nitroSettingsEx.c @@ -0,0 +1,505 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: nitroSettingsEx.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include "spi.h" + +// define data---------------------------------------------------------- + +#define NCD_EX_FORCE_ENABLE // ̃XCb``ƁASYSMo[WɊւ炸INitroConfigDataExLɂȂB + // @ł́ÃtOON,OFFɊ֌WȂ퓮삷邪AAvrhfobK⑼@œ삳ۂɁAONłȂƃ_B + // ǂݍ܂ĂȂNCDEX[hĎSĂ܂̂ŒӁB + +#define SAVE_COUNT_MAX 0x0080 // NitroConfigData.saveCount̍ől +#define SAVE_COUNT_MASK 0x007f // NitroConfigData.saveCount̒l͈̔͂}XNB(0x00-0x7fj +#define NCD_NOT_CORRECT 0x00ff // NITROݒf[^ǂݏoĂȂ or LȂ̂ȂƂB +#define NVRAM_RETRY_NUM 8 // NVRAMgC + +// NVRAMXe[^XWX^l +#define SR_WIP 0x01 // 0:READY 1:CgAC[X +#define SR_WEN 0x02 // 0:Cg֎~ 1:Cg +#define SR_EER 0x20 // 1:C[XG[iSANYOFLASĤ݁j + +#define READ_IPL2_HEADER_ADDR 0x18 // IPL2wb_̂Aǂݍ݂Kvȕ̐擪AhX +#define READ_IPL2_HEADER_SIZE 0x0a // IPL2wb_̂Aǂݍ݂KvȃTCY +#define NCD_ROM_ADDR_SHIFT 3 + +// NVRAM֘AMR}hXe[g +static enum NvramCommState{ + COMM_READY = 0, + COMM_RD, + COMM_WE, + COMM_WR, + COMM_RDSR_WE, + COMM_RDSR_WR, + COMM_SRST +}NvramCommState; + + +// IPL2wb_̈ꕔi0x18̃f[^) +typedef struct IPL2HeaderPart { + struct { + u8 timestamp[5]; // IPL2^CX^v [0]:,[1]:,[2]:,[3]:,[4]:N + u8 ipl2_type; // IPL2^Cv(nitroConfigData.hŒ`IPL2_TYPE...j + u8 rsv[2]; + } version; + + u16 ncd_rom_addr; + + u8 pad[ 0x16 ]; // LbVCɍ킹邽߂̃pfBOB{͕KvȂB +} IPL2HeaderPart; // 0x20bytes + + +// function's prototype------------------------------------------------- +static void NCD_ReadIPL2Header( void ); +static int NVRAMm_checkCorrectNCD(NCDStoreEx *ncdsp); +static BOOL NCD_CheckDataValue( NCDStoreEx *ncdsp ); +static BOOL NVRAMm_ExecuteCommand( int nv_state, u32 addr, u16 size, u8 *srcp ); +static void Callback_NVRAM(PXIFifoTag tag, u32 data, BOOL err); + +// const data----------------------------------------------------------- + +// global variables----------------------------------------------------- +NitroConfigDataEx ncdEx; + +// static variables----------------------------------------------------- +static volatile BOOL nv_cb_occurred; +static volatile u16 nv_result; +static u16 ena_ncd_num = NCD_NOT_CORRECT; +static u16 next_saveCount; +static NCDStoreEx ncds[2] ATTRIBUTE_ALIGN(32); + +static IPL2HeaderPart ipl2Header ATTRIBUTE_ALIGN(32); +static BOOL read_ipl2h = FALSE; + +// function's description----------------------------------------------- + +//---------------------------------------------------------------------- +// IPL2wb_̓ǂݏo +//---------------------------------------------------------------------- +// R|[lgł̎gp + +// IPL2wb_̓ǂݏo +static void NCD_ReadIPL2Header( void ) +{ + if( !read_ipl2h ) { + OS_TPrintf( "IPL2Header:%x\n", sizeof(IPL2HeaderPart) ); + DC_InvalidateRange( &ipl2Header, sizeof(IPL2HeaderPart) ); + while( !NVRAMm_ExecuteCommand( COMM_RD, READ_IPL2_HEADER_ADDR, READ_IPL2_HEADER_SIZE, (u8 *)&ipl2Header ) ) {} + read_ipl2h = TRUE; + } +} + +// IPL2^Cv̎擾 +u8 NCD_GetIPL2Type( void ) +{ + NCD_ReadIPL2Header(); + return ipl2Header.version.ipl2_type; +} + +// IPL2o[W̎擾 +u8 *NCD_GetIPL2Version( void ) +{ + NCD_ReadIPL2Header(); + return ipl2Header.version.timestamp; +} + +// NCDi[ROMAhX̎擾 +u32 NCD_GetNCDRomAddr( void ) +{ + NCD_ReadIPL2Header(); + return (u32)( ipl2Header.ncd_rom_addr << NCD_ROM_ADDR_SHIFT ); +} + +//---------------------------------------------------------------------- +// NITROݒf[^̃[h +//---------------------------------------------------------------------- +int NVRAMm_ReadNitroConfigData(NitroConfigData *dstp) +{ + int result = 0; + NCDStoreEx *ncdsp = &ncds[ 0 ]; + + DC_InvalidateRange( ncdsp, sizeof(NCDStoreEx) * 2 ); + + // tbVjdĂNITROݒf[^ǂݏoB + while( !NVRAMm_ExecuteCommand( COMM_RD, NCD_GetNCDRomAddr(), sizeof(NCDStoreEx), (u8 *)&ncdsp[0]) ) {} + while( !NVRAMm_ExecuteCommand( COMM_RD, NCD_GetNCDRomAddr() + SPI_NVRAM_PAGE_SIZE, sizeof(NCDStoreEx), (u8 *)&ncdsp[1]) ) {} + OS_TPrintf("NCD read addr=%08x\n", NCD_GetNCDRomAddr() ); + + // ǂݏof[^̂ǂ炪L𔻒肷B + if(NVRAMm_checkCorrectNCD(ncdsp)) { + next_saveCount = 1; + result = 1; + goto END; // Lȃf[^Ȃ΃G[IB + } + next_saveCount = (u8)((ncdsp[ena_ncd_num].saveCount + 1) & SAVE_COUNT_MASK); + + // LNITROݒf[^obt@ɓ] + if( dstp != NULL ) { + SVC_CpuCopy( (void *)&ncdsp[ ena_ncd_num ].ncd, (void *)dstp, sizeof(NitroConfigData), 16); + SVC_CpuCopy( (void *)&ncdsp[ ena_ncd_num ].ncd_ex, (void *)&ncdEx, sizeof(NitroConfigDataEx), 16); + } + +END: + return result; +} + + +//---------------------------------------------------------------------- +// NITROݒf[^̃Cg +//---------------------------------------------------------------------- +void NVRAMm_WriteNitroConfigData( NitroConfigData *srcp ) +{ + NCDStoreEx *ncdsp = &ncds[ 0 ]; + u16 size = sizeof(NCDStore); + u32 flash_addr; + int retry; + + // ܂NITROݒf[^[hĂȂ΁A[hsĕKvȏ擾B + if( ena_ncd_num == NCD_NOT_CORRECT ) { + if( NVRAMm_ReadNitroConfigData( NULL ) ) { + ena_ncd_num = 0; // Lȃf[^Ȃ"0"ɃCgB + } + } + + // NCD CRCAZ[uJEglACgAhX̎ZoB + ncdsp->ncd = *srcp; // *GetNCDWork();@łꏏB + ncdsp->ncd.version = NITRO_CONFIG_DATA_VERSION; // o[Ŵ݂̂ɐݒB + ncdsp->crc16 = SVC_GetCRC16( 0xffff, (const void *)&ncdsp->ncd, sizeof(NitroConfigData) ); + ncdsp->saveCount = next_saveCount; + next_saveCount = (u8)( ( next_saveCount + 1 ) & SAVE_COUNT_MASK ); + + // NCD_EXCRCZoB +#ifndef NCD_EX_FORCE_ENABLE + if( ( NCD_GetIPL2Type() != IPL2_TYPE_NTR_WW ) && ( NCD_GetIPL2Type() & IPL2_TYPE_NCD_EX_FLAG ) ) +#endif + { + ncdsp->ncd_ex = *GetNCDExWork(); + ncdsp->ncd_ex.version = NITRO_CONFIG_DATA_EX_VERSION; // o[Ŵ݂̂ɐݒB + ncdsp->ncd_ex.valid_language_bitmap = VALID_LANG_BITMAP; + ncdsp->crc16_ex = SVC_GetCRC16( 0xffff, (const void *)&ncdsp->ncd_ex, sizeof(NitroConfigDataEx) ); + size = sizeof(NCDStoreEx); // ݃TCYNCDStoreExɊgB + } + + // NITROݒf[^̃Cg + DC_FlushRange(ncdsp, sizeof(NCDStoreEx)); + retry = NVRAM_RETRY_NUM; + while( retry-- ) { + ena_ncd_num ^= 0x01; // gC̓xɏ݃AhX؂ւB + flash_addr = NCD_GetNCDRomAddr() + ena_ncd_num * SPI_NVRAM_PAGE_SIZE; + OS_TPrintf("NCD write addr=%08x\n", flash_addr ); + + if( NVRAMm_ExecuteCommand( COMM_WE, flash_addr, size, (u8 *)ncdsp) ) { + OS_TPrintf("NVRAM Write succeeded.\n"); + break; + } + SVC_WaitByLoop( 0x4000 ); + OS_TPrintf("NVRAM Write retry = %d.\n", NVRAM_RETRY_NUM - retry ); + } +} + + +//---------------------------------------------------------------------- +// ~[OĂNITROݒf[^̂ǂ炪L𔻒 +//---------------------------------------------------------------------- + +static int NVRAMm_checkCorrectNCD(NCDStoreEx *ncdsp) +{ + u16 i; + u16 ncd_valid = 0; + + // e~[f[^CRC & saveCount`FbN + for(i = 0; i < 2; i++) { + u16 crc; + BOOL invalid = FALSE; + + crc = SVC_GetCRC16( 0xffff, (const void *)&ncdsp[i].ncd, sizeof(NitroConfigData) ); + + if( ( ncdsp[ i ].crc16 != crc ) // CRCAsaveCountl0x80ȉŁAƒo[Wvf[^𐳓ƔfB + || ( ncdsp[ i ].ncd.version != NITRO_CONFIG_DATA_VERSION ) + || ( ncdsp[ i ].saveCount >= SAVE_COUNT_MAX ) ) { + OS_TPrintf("NCD crc error.\n"); + invalid = TRUE; + } + + // NCDExLIPL2TypeȂ΁ANCDExCRC`FbNsB +#ifndef NCD_EX_FORCE_ENABLE + if( ( NCD_GetIPL2Type() != IPL2_TYPE_NTR_WW ) && ( NCD_GetIPL2Type() & IPL2_TYPE_NCD_EX_FLAG ) ) +#endif + { + crc = SVC_GetCRC16( 0xffff, (const void *)&ncdsp[i].ncd_ex, sizeof(NitroConfigDataEx) ); + + if( ( ncdsp[ i ].crc16_ex != crc ) + || ( ncdsp[ i ].ncd_ex.version != NITRO_CONFIG_DATA_EX_VERSION ) ) { + OS_TPrintf("NCDEx crc error.\n"); + invalid = TRUE; + } + } + // NCD, NCDExCRCȂAf[^̒g`FbNB + if( !invalid ) { + if( NCD_CheckDataValue( &ncdsp[ i ] ) ) { + ncd_valid |= 0x01 << i; // f[^lłȂ`FbNB + ena_ncd_num = i; // LNCD̃CfbNX؂ւB + }else { + invalid = TRUE; + } + } + + if( ncd_valid & ( 0x01 << i ) ) { + OS_TPrintf("NCD mirror%d is valid.:saveCount = %d\n", i, ncdsp[i].saveCount); + }else { + OS_TPrintf("NCD mirror%d is invalid.\n", i); + } + } + + + if( ncd_valid == 0 ) { + return 1; + }else if( ncd_valid == 0x03 ) { + // ~[OꂽNCDƂɐȏꍇAZ[uJEgl傫LƂB + u16 saveCount = (u8)( ( ncdsp[ 0 ].saveCount + 1 ) & SAVE_COUNT_MASK ); + if( saveCount != ncdsp[ 1 ].saveCount ) { + ena_ncd_num = 0; + } + } + + OS_TPrintf("use NCD mirror%d.:saveCount = %d\n", ena_ncd_num, ncdsp[ena_ncd_num].saveCount); + + return 0; +} + + +// NITROݒf[^̒ll`FbNB // FALSE:ȂBTRUEFB +static BOOL NCD_CheckDataValue( NCDStoreEx *ncdsp ) +{ + NitroConfigData *ncdp = &ncdsp->ncd; + NitroConfigDataEx *ncdexp = &ncdsp->ncd_ex; + + //ncdp->option; + // NCDlanguage`FbN + if( ~( LANG_BITMAP_WW & VALID_LANG_BITMAP ) & ( 0x0001 << ncdp->option.language ) ) { + OS_TPrintf("NCD: invalid language : org:%02d ex:%02d bitmap:%04x\n", + ncdp->option.language, ncdexp->language, ncdexp->valid_language_bitmap ); + return FALSE; + } + // NCDExlanguage`FbNiNCDExLȂ̂́ALIPL2^Cv̂́j +#ifndef NCD_EX_FORCE_ENABLE + if( ( NCD_GetIPL2Type() != IPL2_TYPE_NTR_WW ) && ( NCD_GetIPL2Type() & IPL2_TYPE_NCD_EX_FLAG ) ) +#endif + { + if( ( ~VALID_LANG_BITMAP & ( 0x0001 << ncdexp->language ) ) + || ( ncdexp->valid_language_bitmap != VALID_LANG_BITMAP ) ) { + + OS_TPrintf("NCDEx: invalid language : org:%02d ex:%02d bitmap:%04x\n", + ncdp->option.language, ncdexp->language, ncdexp->valid_language_bitmap ); + return FALSE; + } + } + + //ncdp->owner; + // favoriteColor4bitȂ̂Ŕ͈͊O͂ȂB + // birthday + if( ncdp->option.input_birthday ) { + if( ( ncdp->owner.birthday.month > 12 ) || ( ncdp->owner.birthday.day > 31 ) ) { + OS_TPrintf("NCD: invalid birthday : %02d/%02d\n", ncdp->owner.birthday.month, ncdp->owner.birthday.day ); + return FALSE; + } + } + + // nickname + if( ncdp->option.input_nickname ) { + if( ncdp->owner.nickname.length > NCD_NICKNAME_LENGTH ) { + OS_TPrintf("NCD: invalid nickname length : %02d\n", ncdp->owner.nickname.length ); + return FALSE; + } + } + + // comment + if( ncdp->owner.comment.length > NCD_COMMENT_LENGTH ) { + OS_TPrintf("NCD: invalid comment length : %02d\n", ncdp->owner.comment.length ); + return FALSE; + } + + //ncdp->alarm; + if( ( ncdp->alarm.hour > 23 ) || ( ncdp->alarm.minute > 59 ) ) { + OS_TPrintf("NCD: invalid alarm time : %02d:%02d\n", ncdp->alarm.hour, ncdp->alarm.minute ); + return FALSE; + } + + //ncdp->tp; + // TPLu[VĺATP_CalcCalibrateParamŒl̃`FbNĂ̂ŁA`FbNȂB + + OS_TPrintf( "NCD: correct data.\n" ); + return TRUE; +} + + +//---------------------------------------------------------------------- +// NVRAMւ̃ANZX[`{ ( nv_state <- COMM_RD or COMM_WE ) +//---------------------------------------------------------------------- +static BOOL NVRAMm_ExecuteCommand( int nv_state, u32 addr, u16 size, u8 *srcp ) +{ + OSTick start; + BOOL nv_sending = FALSE; + u8 *nvram_srp = (u8 *)&ncds[1]; + + PXI_SetFifoRecvCallback( PXI_FIFO_TAG_NVRAM , Callback_NVRAM ); + + while( 1 ) { + //--------------------------------------- + // NVRAMR}h𔭍s + //--------------------------------------- + if( !nv_sending ) { + + nv_cb_occurred = FALSE; + + switch( nv_state ) { + case COMM_RD: + nv_sending = SPI_NvramReadDataBytes( addr, size, srcp ); + break; + + case COMM_WE: + nv_sending = SPI_NvramWriteEnable(); + break; + + case COMM_WR: + nv_sending = SPI_NvramPageWrite( addr, size , srcp ); + start = OS_GetTick(); + break; + + case COMM_RDSR_WE: + case COMM_RDSR_WR: + nv_sending = SPI_NvramReadStatusRegister( nvram_srp ); + break; + + case COMM_SRST: + nv_sending = SPI_NvramSoftwareReset(); + break; + } + //--------------------------------------- + // R}hsʁiR[obNj҂Čʂ + //--------------------------------------- + }else { // nv_sending == TRUE + if( nv_cb_occurred == TRUE ) { // R[obN҂B + + nv_sending = FALSE; + + if( nv_result == SPI_PXI_RESULT_SUCCESS ) { + switch( nv_state ) { + case COMM_RD: + return TRUE; + + case COMM_WE: + nv_state = COMM_RDSR_WE; + break; + + case COMM_WR: + nv_state = COMM_RDSR_WR; + break; + + case COMM_RDSR_WE: + case COMM_RDSR_WR: + + DC_InvalidateRange( nvram_srp, 1 ); + + if( nv_state == COMM_RDSR_WE ) { // CgCl[umFXe[gȂ + if( ( *nvram_srp & SR_WEN ) ) { + nv_state = COMM_WR; + }else { + OS_TPrintf("NVRAM ERR: Write Enable Invalid.\n"); + return FALSE; + } + }else { + if( ( *nvram_srp & SR_WIP ) == 0 ) { // Cg^C[XI + return TRUE; + }else { + if( ( *nvram_srp & SR_EER ) // SR_EERĂG[ + || ( OS_TicksToMilliSeconds( OS_GetTick() - start ) > 4000 ) ) { + // R}hs4bo߂G[iیj + OS_TPrintf( "NVRAM SR : %02x\n", *nvram_srp ); + nv_state = COMM_SRST; + }else { + SVC_WaitByLoop( 0x4000 ); + } + } + } + break; + + case COMM_SRST: + OS_TPrintf("NVRAM ERR: PageErase Timeout and SoftReset.\n"); + return FALSE; + } + }else { // nv_result != SPI_PXI_RESULT_SUCCESS + OS_TPrintf("NVRAM ERR: NVRAM PXI command failed.\n"); + return FALSE; + } + } + } + } +} + + +//---------------------------------------------------------------------- +// R[obN +//---------------------------------------------------------------------- +static void Callback_NVRAM( PXIFifoTag tag, u32 data, BOOL err ) +{ + #pragma unused(tag) + + u16 command = (u16)( ( ( data & SPI_PXI_DATA_MASK ) & 0x7f00 ) >> 8 ); + + nv_result = (u16)( data & 0x00ff ); + nv_cb_occurred = TRUE; // R[obNtOTRUE + + if( err ) { + OS_TPrintf("NVRAM-ARM9: Received PXI data is error.\n"); + nv_result = 0x00ff; + } + + switch(command){ // R}h\ + case SPI_PXI_COMMAND_NVRAM_READ: + OS_TPrintf("NVRAM-ARM9:ReadDataBytes"); + break; + case SPI_PXI_COMMAND_NVRAM_WREN: + OS_TPrintf("NVRAM-ARM9:WriteEnable"); + break; + case SPI_PXI_COMMAND_NVRAM_PW: + OS_TPrintf("NVRAM-ARM9:PageWrite"); + break; + case SPI_PXI_COMMAND_NVRAM_RDSR: + OS_TPrintf("NVRAM-ARM9:ReadStatusRegister"); + break; + case SPI_PXI_COMMAND_NVRAM_WRDI: + OS_TPrintf("NVRAM-ARM9:WriteDisable"); + break; + case SPI_PXI_COMMAND_NVRAM_PE: + OS_TPrintf("NVRAM-ARM9:PageErase"); + break; + case SPI_PXI_COMMAND_NVRAM_SR: + OS_TPrintf("NVRAM-ARM9:SoftwareReset"); + break; + default: + OS_TPrintf("NVRAM-ARM9:?????"); + break; + } + if( nv_result != SPI_PXI_RESULT_SUCCESS ) { + OS_TPrintf(" Error! ->%x", nv_result ); + } + OS_TPrintf("\n"); +} + diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_card.c b/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_card.c new file mode 100644 index 0000000..1bc09cd --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_card.c @@ -0,0 +1,253 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SYSM_card.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "sysmenu_card.h" + + +typedef enum { + CARD_NOT_DETECTING = 0, + CARD_DETECTING +} CARDPullStatus; + + +typedef struct SYSMCardPullWork +{ + CARDPullStatus pullStatus; + u32 cardCnt; + u16 lockID; + u16 detectPullOut; + +} SYSMCardPullWork; + + +static SYSMCardPullWork cpw; + + +// ֐ +void SYSMi_InitCardPulledOut(void); +BOOL SYSMi_IsDetectableCardPulledOut(void); +void SYSMi_StartReadCardID(void); +void SYSMi_ReadCardPage(void *romp, void *ramp, s32 size); +static void SYSMi_SetCardOp(const u32 *op); + + +//---------------------------------------------------------------------- +// J[ho +//---------------------------------------------------------------------- + +void SYSMi_InitCardPulledOut(void) +{ + cpw.lockID = (u16 )OS_GetLockID(); + cpw.cardCnt = *(vu32 *)MROMCNT_GAME_BUF; +} + + +//---------------------------------------------------------------------- +// J[ho +//---------------------------------------------------------------------- + +BOOL SYSM_IsCardPulledOut(void) +{ + if (SYSMi_IsDetectableCardPulledOut() == FALSE) return FALSE; + + switch (cpw.pullStatus) { + case CARD_NOT_DETECTING: + if (OS_TryLockCard( cpw.lockID ) == OS_LOCK_SUCCESS ) + { + SYSMi_StartReadCardID(); + cpw.pullStatus = CARD_DETECTING; + } + break; + + case CARD_DETECTING: + if (SYSMi_IsCardDataReady()) { + u32 cardID = *(vu32 *)REG_CARD_DATA; + if (cardID != GetSYSMWork()->nCardID + && SYSM_IsNITROCard()) + { + cpw.detectPullOut = TRUE; + } + + (void)OS_UnlockCard( cpw.lockID ); + cpw.pullStatus = CARD_NOT_DETECTING; + } + break; + } + + return cpw.detectPullOut; +} + + +//---------------------------------------------------------------------- +// J[hoI +//---------------------------------------------------------------------- + +void SYSM_FinalizeCardPulledOut(void) +{ + while (SYSM_IsDetectingCardPulledOut()) { + (void)SYSM_IsCardPulledOut(); + } +} + + +//---------------------------------------------------------------------- +// J[ho +//---------------------------------------------------------------------- + +BOOL SYSM_IsDetectingCardPulledOut(void) +{ + return (cpw.pullStatus == CARD_DETECTING); +} + + +//---------------------------------------------------------------------- +// J[hȍłĂ邩 +//---------------------------------------------------------------------- + +BOOL SYSMi_IsDetectableCardPulledOut(void) +{ + return (SYSM_GetBootFlag() & BFLG_LOAD_CARD_COMPLETED ) ? TRUE : FALSE; +} + + +//---------------------------------------------------------------------- +// J[hIDǂݍ݊Jn +//---------------------------------------------------------------------- + +void SYSMi_StartReadCardID(void) +{ + u32 op[2]; + + op[0] = 0; // R}hݒ + op[1] = MROMOP_G_READ_ID; + + SYSMi_SetCardOp( op ); + // Rg[ݒ + *(vu32 *)REG_CARDCNT = cpw.cardCnt + | CARD_READ_MODE | CARD_STATUS + | CARD_START | CARD_RESET_HI; +} + + +//---------------------------------------------------------------------- +// J[hIDǂݍ +//---------------------------------------------------------------------- + +u32 SYSMi_ReadCardID(void) +{ + u32 op[2]; + + op[0] = 0; // R}hݒ + op[1] = MROMOP_G_READ_ID; + + SYSMi_SetCardOp( op ); + // Rg[ݒ + *(vu32 *)REG_CARDCNT = *(vu32 *)MROMCNT_GAME_BUF + | CARD_READ_MODE | CARD_STATUS + | CARD_START | CARD_RESET_HI; + + SYSMi_WaitCardData(); + + return *(vu32 *)REG_CARD_DATA; +} + + +//---------------------------------------------------------------------- +// J[hf[^ǂݍ +//---------------------------------------------------------------------- + +void SYSM_ReadCard(void *romp, void *ramp, s32 size) +{ + s32 restSize = size; + s32 blockSize = MROM_PAGE_SIZE; + + while (restSize > 0) { // ubNǂݍ + if (restSize >= MROM_PAGE_SIZE) { size = MROM_PAGE_SIZE; + } else { size = restSize; + } + + SYSMi_ReadCardPage(romp, ramp, size); + + (u8 *)romp += size; + (u8 *)ramp += size; + restSize -= size; + } +} + + +//---------------------------------------------------------------------- +// y[Wǂݍ +//---------------------------------------------------------------------- + +void SYSMi_ReadCardPage(void *romp, void *ramp, s32 size) +{ + { u32 op[2]; + + op[0] = (u32 )romp <<24; // R}hݒ + op[1] = MROMOP_G_READ_PAGE | (u32 )romp >>8; + + SYSMi_SetCardOp( op ); + } + + // y[W[h + { void *ramEndp; + u32 cardCntTmp; + + *(vu32 *)REG_CARDCNT = *(vu32 *)MROMCNT_GAME_BUF // Rg[ݒ + | CARD_READ_MODE | CARD_1_PAGE + | CARD_START | CARD_RESET_HI; + + ramEndp = (u8 *)ramp + size; // i[IAhXZo + + do { // CPUǂݍ + cardCntTmp = *(vu32 *)REG_CARDCNT; + + if (cardCntTmp & CARD_DATA_READY) { + u32 dataTmp = *(vu32 *)REG_CARD_DATA; + + if (ramp < ramEndp) + *((vu32 *)ramp) = dataTmp; // wTCY܂Ŋi[i㑱f[^͓ǂݎ̂āj + ((vu32 *)ramp)++; + } + } while (cardCntTmp & CARD_START); + } +} + + +//---------------------------------------------------------------------- +// R}hݒ +//---------------------------------------------------------------------- + +static void SYSMi_SetCardOp(const u32 *op) +{ + int i; + + *(vu8 *)REG_CARD_MASTER_CNT = CARDMST_SEL_ROM // }X^[Cl[u + | CARDMST_ENABLE; + + for (i=0; i<2; i++) { // R}hݒ + u32 opTmp = op[1 - i]; + vu8 *opDestBasep = (vu8 *)(REG_CARD_CMD + i*4); + + opDestBasep[0] = (u8 )(opTmp >>24); + opDestBasep[1] = (u8 )(opTmp >>16); + opDestBasep[2] = (u8 )(opTmp >>8); + opDestBasep[3] = (u8 )(opTmp >>0); + } +} + diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_lib.c b/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_lib.c new file mode 100644 index 0000000..8b40ee0 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_lib.c @@ -0,0 +1,743 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SYSM_lib.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include "sysmenu_define.h" +#include "sysmenu_card.h" +#include "spi.h" +#include "mb_child.h" + +// define data----------------------------------------------------------------- + +#define SCREEN_RED 0 +#define SCREEN_YELLOW 1 + +typedef struct BannerCheckParam { + u8 *srcp; + u32 size; +}BannerCheckParam; + +// extern data----------------------------------------------------------------- +extern void ReturnFromMain( void ); +extern void BootFuncEnd( void ); + +FS_EXTERN_OVERLAY( ipl2_data ); +FS_EXTERN_OVERLAY( bm_mainp ); + +// function's prototype------------------------------------------------------- +static void SYSMi_WaitInitARM7( void ); +static BOOL SYSMi_IsDebuggerBannerViewMode( void ); + +static BOOL SYSMi_CheckTitlePointer( TitleProperty *pBootTitle ); +void SYSM_Finalize( void ); +void SYSM_RebootLauncher( void ); +void SYSM_RebootTitle( u64 titleID ); + + + +static void INTR_SubpIRQ( void ); + +static void SYSMi_CheckCardLoadAddressAndSize( void ); +static void LoadRomRegSizeAdjust( CARDRomRegion *romRegp, u32 load_limit_lo, u32 load_limit_hi ); +static void SYSMi_ReadyBootNitroGame( void ); +static BOOL SYSMi_CheckARM7LoadNITROCard( void ); +static void SYSMi_MainpRegisterAndRamClear( BOOL isPlatformTWL ); +static void ClearMemory( int addr1, int addr2 ); + +static void SYSMi_CopyInfoFromIPL1( void ); + +static void SYSMi_ReadNTRSetting( void ); +static void SYSMi_ReadTWLSetting( void ); +static void SYSMi_VerifyNTRSetting( void ); +static BOOL SYSMi_CheckEntryAddress( void ); +static void SYSMi_WriteAdjustRTC( void ); +static BOOL SYSMi_SendMessageToARM7( u32 msg ); +static BOOL SYSMi_CheckNitroCardRightly( void ); +static int SYSMi_ExistCard( void ); +static u32 SYSMi_SelectBootType( void ); +static void SYSMi_DispInitialDebugData( void ); +static void SYSMi_DispDebugData( void ); + +static void DispSingleColorScreen( int mode ); + +static void SYSMi_ReadCardBannerFile( void ); +static void SYSMi_CheckCardCloneBoot( void ); + + +// global variable------------------------------------------------------------- +#ifdef __SYSM_DEBUG +SharedWork *swp; // fobKłIPL1SharedWork̃EHb`p +SYSM_work *pSysm; // fobKłSYSM[ÑEHb`p +NitroConfigData *ncdp; // fobKłNCf[^@̃EHb`p +#endif + +// static variable------------------------------------------------------------- +static BOOL s_isBanner = FALSE; +static BannerFile s_bannerBuf; + +// const data------------------------------------------------------------------ + +static BannerCheckParam s_bannerCheckList[ BNR_VER_MAX ] = { + { (u8 *)&s_bannerBuf.v1, sizeof( BannerFileV1 ) }, + { (u8 *)&s_bannerBuf.v2, sizeof( BannerFileV2 ) }, + { (u8 *)&s_bannerBuf.v3, sizeof( BannerFileV3 ) }, +}; + +#ifdef __DEBUG_SECURITY_CODE +static GXRgb security_detection_color[] = { GX_RGB( 31, 0, 0 ), + GX_RGB( 31, 31, 0 ), }; +#endif + +// inline functions------------------------------------------------------------ + +static inline void DBG_SetRed(u32 y_pos) +{ + *(u16 *)(HW_DB_BG_VRAM + 0xf000 + 0x20*2*y_pos) = (1<<12) | 0x100; + MI_CpuFill16(((u8 *)HW_DB_BG_VRAM + 0x20*0x100), 0x1111, 0x20); +} + +// ============================================================================ +// function's description +// ============================================================================ + +// SystemMenȕ +void SYSM_Init( void ) +{ +#ifdef __SYSM_DEBUG + pSysm = GetSYSMWork(); + ncdp = GetNCDWork(); +// SYSMi_DispInitialDebugData(); // fobO\ +#endif /* __SYSM_DEBUG */ + + TP_Init(); + RTC_Init(); + + // WRAMݒ͂H +// MI_SetMainMemoryPriority(MI_PROCESSOR_ARM7); +// MI_SetWramBank(MI_WRAM_ARM7_ALL); + + SVC_CpuClearFast(0x0000, (u16 *)GetSYSMWork(), sizeof(SYSM_work)); // SYSM[ÑNA + + // ISfobKǂ̔B@BootROM̃p[^nH + SYSMi_WaitInitARM7(); +} + + +// ARM7̏҂ +static void SYSMi_WaitInitARM7( void ) +{ +/* while( !( SYSM_GetBootFlag() & BFLG_ARM7_INIT_COMPLETED ) ) { + SVC_WaitByLoop(0x1000); // ARM7̏Î҂B + } +*/ + reg_OS_PAUSE |= REG_OS_PAUSE_CHK_MASK; // PAUSEWX^̃`FbNtÕZbg + + SYSMi_ReadTWLSetting(); // NANDTWL{̐ݒf[^[h + PMm_SetBackLightBrightness(); + + SYSMi_ReadNTRSetting(); // NOR NTR{̐ݒf[^[h + SYSMi_VerifyNTRSetting(); // NVRAMNTR{̐ݒf[^[hAsvӏNTRJoB + + SYSM_CaribrateTP(); // ǂݏoTWL{̐ݒf[^ƂTPLu[VB + SYSMi_WriteAdjustRTC(); // ǂݏoTWL{̐ݒf[^ƂRTCNbN␳lZbgB + + SYSMi_CheckCardCloneBoot(); // J[hN[u[g`FbN + SYSMi_ReadCardBannerFile(); // J[hoi[t@C̓ǂݏoB + + // ============================================================== + // fobKΉR[h +#ifdef __IS_DEBUGGER_BUILD + if( GetSYSMWork()->isOnDebugger ) { + if( SYSMi_ExistCard() && + !SYSMi_IsDebuggerBannerViewMode() ){ // fobK㓮̏ꍇ́A̒ŃJ[hu[g܂łĂ܂B + SYSM_GetResetParam()->isLogoSkip = TRUE; + SYSM_GetResetParam()->bootTitleID = SYSM_GetCardTitleID(); + } + }else { + while( 1 ) {} // ISfobKrhISfobKołȂ~B + } +#endif // __IS_DEBUGGER_BUILD + // ============================================================== +} + + +int SYSM_GetCardTitleList( TitleProperty *pTitleList_Card ) +{ +#pragma unused( pTitleList_Card ) + return 0; +} + + +int SYSM_GetNandTitleList( TitleProperty *pTitleList_Nand ) +{ +#pragma unused( pTitleList_Nand ) + // filter_flag : ALL, ALL_APP, SYS_APP, USER_APP, Data only, ̏w肵ă^CgXg擾B + // return : *TitleProperty Array + return 0; +} + + +// w^Cgu[g”\ȃ|C^`FbN +static BOOL SYSMi_CheckTitlePointer( TitleProperty *pBootTitle ) +{ +#pragma unused( pBootTitle ) + + return TRUE; +} + + +// w^Cg̔F؁[h@Pt[IB +AuthResult SYSM_LoadAndAuthenticateTitle( TitleProperty *pBootTitle ) +{ + // C̃NA + // DS_E[hvC̎́AROMwb_ޔ + // Av[h + // AvF + + // p[^`FbN + if( !SYSMi_CheckTitlePointer( pBootTitle ) ) { + return AUTH_RESULT_TITLE_POINTER_ERROR; + } + // GgAhX̐`FbN + if( !SYSMi_CheckEntryAddress() ) { + return AUTH_RESULT_ENTRY_ADDRESS_ERROR; + } + + return AUTH_RESULT_SUCCEEDED; +} + + +// u[ĝ߂̏I +void SYSM_Finalize( void ) +{ + // ARM7ւ̃u[gʒm + // WX^ERAMNA + + // u[gɃveNVjbgOFFɂȂ΁AsȃAhXł̋Nĥł́H + + u32 i; + + // u[g̑O + MI_CpuCopyFast( (void *)ReturnFromMain, (void *)RETURN_FROM_MAIN_ARM9_FUNCP, (u32)( (u32)BootFuncEnd - (u32)ReturnFromMain ) ); + DC_StoreRange ( (void *)ReturnFromMain, 0x200 ); // Q[u[g̍ŏIČ̕ɃRs[iSYSMs̃X^bN㏸Ŕj󂳂Ȃ悤ɁÃ^C~OŃRs[Bj + + for( i = 0; i <= MI_DMA_MAX_NUM; i++ ) { // DMA̒~ + MI_StopDma( i ); + } + SYSM_FinalizeCardPulledOut(); // J[hoI + SYSMi_MainpRegisterAndRamClear( TRUE ); // WX^RAMNA + ( void )GX_VBlankIntr(FALSE); + ( void )OS_SetIrqFunction(OS_IE_SUBP, INTR_SubpIRQ); + ( void )OS_SetIrqMask(OS_IE_SUBP); // TuvZbT荞݂݂̂B + reg_PXI_SUBPINTF = SUBP_RECV_IF_ENABLE | 0x0f00; // ARM9Xe[g "0x0f" + GetSYSMWork()->mainp_state = MAINP_STATE_WAIT_BOOT_REQ; + // FIFO̓NAς݂Ȃ̂ŁAgȂB + // ARM7̒ʒm҂ + OS_WaitIrq(1, OS_IE_SUBP); // SVC_WaitIntr(0,OS_IE_SUBP);ύXB + + // 荞݂NAčŏIu[gV[PXցB + reg_PXI_SUBPINTF &= 0x0f00; // TuvZbT荞݋ƒtONA + ( void )OS_DisableIrq(); + ( void )OS_SetIrqMask(0); + ( void )OS_ResetRequestIrqMask( (u32)~0 ); +} + + +// `[u[g +void SYSM_RebootLauncher( void ) +{ +} + + +// ċN^Cgw肵Ẵu[g +void SYSM_RebootTitle( u64 titleID ) +{ +#pragma unused( titleID ) + +} + + +#if 0 +// NITRONARM7ɒʒm +BOOL SYSM_BootCard( void ) +{ // NintendoS`FbŃÃ^C~OōsB + + ( void )SYSMi_SendMessageToARM7(MSG_BOOT_TYPE_CARD); // ARM7ɃJ[hNʒmB + + if( SYSM_CheckNinLogo( (u16 *)GetRomHeaderAddr()->nintendo_logo ) == FALSE + || GetSYSMWork()->enableCardNormalOnly == TRUE ) { // NORMALJ[hΉ + SYSM_SetBootFlag( BFLG_ILLEGAL_NITRO_CARD ); + return FALSE; + }else { + SYSM_SetBootFlag( BFLG_BOOT_DECIDED | BFLG_BOOT_NITRO ); + return TRUE; + } +} +#endif + +#if 0 +// TP[h”\ǂ𒲂ׂB +BOOL SYSM_IsTPReadable( void ) +{ + if( SYSM_GetBootFlag() & BFLG_BOOT_DECIDED ) return FALSE; + else return TRUE; +} +#endif + + +// ARM7-ARM9L\[XbootFlagւ̒l̃Zbg +void SYSM_SetBootFlag( u32 value ) +{ + BOOL preIrq = OS_DisableIrq(); + LockVariable *lockp = &GetSYSMWork()->boot_flag; + ( void )OS_LockByWord( BOOTFLAG_LOCK_ID, &(lockp->lock), (void (*)( void ))0x00000000); + lockp->value |= value; + ( void )OS_UnLockByWord(BOOTFLAG_LOCK_ID, &(lockp->lock), (void (*)( void ))0x00000000); + ( void )OS_RestoreIrq( preIrq ); +} + + +void SYSM_ClearBootFlag( u32 value ) +{ + BOOL preIrq = OS_DisableIrq(); + LockVariable *lockp = &GetSYSMWork()->boot_flag; + ( void )OS_LockByWord( BOOTFLAG_LOCK_ID, &(lockp->lock), (void (*)( void ))0x00000000); + lockp->value &= ~value; + ( void )OS_UnLockByWord(BOOTFLAG_LOCK_ID, &(lockp->lock), (void (*)( void ))0x00000000); + ( void )OS_RestoreIrq( preIrq ); +} + + +// ============================================================================ +// 荞ݏ +// ============================================================================ + +// TuvZbT荞 +static void INTR_SubpIRQ( void ) +{ + OS_SetIrqCheckFlag( OS_IE_SUBP ); +} + + +// ============================================================================ +// AvN +// ============================================================================ + +// GgAhX̐`FbN +static BOOL SYSMi_CheckEntryAddress( void ) +{ + // GgAhXROMo^GAAGBJ[gbWGAȂA[vɓB + if( !( ( (u32)GetRomHeaderAddr()->main_entry_address >= HW_MAIN_MEM ) + && ( (u32)GetRomHeaderAddr()->main_entry_address < SYSM_ARM9_MMEM_ENTRY_ADDR_LIMIT ) ) + || !( ( ( (u32)GetRomHeaderAddr()->sub_entry_address >= HW_MAIN_MEM ) + && ( (u32)GetRomHeaderAddr()->sub_entry_address < SYSM_ARM7_LOAD_MMEM_LAST_ADDR ) ) + || ( ( (u32)GetRomHeaderAddr()->sub_entry_address >= HW_WRAM ) + && ( (u32)GetRomHeaderAddr()->sub_entry_address < SYSM_ARM7_LOAD_WRAM_LAST_ADDR ) ) ) ) + { + OS_TPrintf("entry address invalid.\n"); +#ifdef __DEBUG_SECURITY_CODE + DispSingleColorScreen( SCREEN_YELLOW ); +#endif + return FALSE; + } + OS_TPrintf("entry address valid.\n"); + return TRUE; +} + + +// ARM7ɂNITROQ[̃[hmFB +static BOOL SYSMi_CheckARM7LoadNITROCard( void ) +{ + if( SYSMi_ExistCard() +// && !( SYSM_GetBootFlag() & BFLG_LOAD_CARD_COMPLETED ) + ) { + return FALSE; + } + return TRUE; +} + + + +// SystemMenuŎgpWX^̃NA +static void SYSMi_MainpRegisterAndRamClear( BOOL isPlatformTWL ) +{ + // ŌオTuvZbT荞ݑ҂Ȃ̂ŁAIME̓NAȂB + ( void )OS_SetIrqMask(0); + ( void )OS_ResetRequestIrqMask( (u32)~0 ); + + // NA + GX_SetBankForLCDC(GX_VRAM_LCDC_ALL); // VRAM NA + MI_CpuClearFast((void*)HW_LCDC_VRAM, HW_LCDC_VRAM_SIZE); + ( void )GX_DisableBankForLCDC(); +// MI_CpuClearFast((void *)HW_ITCM, HW_ITCM_SIZE); // ITCM NA ITCMɂSDK̃R[hĂ̂ŁAgameBoot.cŃNAB +// MI_CpuClearFast((void *)HW_DTCM, HW_DTCM_SIZE-0x800); // DTCM NA DTCM̓X^bN&SDKϐȂ̂ŁAŌgameBoot.cŃNAĂB + MI_CpuClearFast((void *)HW_OAM, HW_OAM_SIZE); // OAM NA + MI_CpuClearFast((void *)HW_PLTT, HW_PLTT_SIZE); // pbg NA + MI_CpuClearFast((void *)HW_DB_OAM, HW_DB_OAM_SIZE); // OAM NA + MI_CpuClearFast((void *)HW_DB_PLTT, HW_DB_PLTT_SIZE); // pbg NA + + // WX^NA + MI_CpuClearFast((void*)(HW_REG_BASE + 0x8), 0x12c); // BG0CNT ` KEYCNT + MI_CpuClearFast((void*)(HW_REG_BASE + 0x280), 0x40); // DIVCNT ` SQRTD3 + MI_CpuClearFast((void*)(HW_REG_BASE + 0x1000), 0x6e); // DISP1CNT1 ` DISPBRTCNT1 + CP_SetDiv32_32( 0, 1 ); + reg_PXI_SUBP_FIFO_CNT = 0x4008; + reg_GX_DISPCNT = 0; + reg_GX_DISPSTAT = 0; // reg_GX_VCOUNT̓x^NAłȂ̂ŁA̐擪̃NA𕪗B + + + // NTR̎ɂ́Aoi[鎞́AMCCNT̃J[hCl[urbg"1"ŁAƂɂ"0"ɂȂĂA + // NTRN̎ɂ́Ał𓥏PȂƃ_BBB + + // NAĂȂWX^́AVCOUNT, PIFCNT, MC-, EXMEMCNT, IME, RBKCNT1, PAUSE, POWLCDCNT, S3DnłB + if( isPlatformTWL ) { + // TWLpWX^̃NA + } +} + + +// ============================================================================ +// Tu[` +// ============================================================================ + +// SfXLbvH +BOOL SYSM_IsLogoDemoSkip( void ) +{ + // VXeAṽn[hZbgɂ郍Sf΂ɓB + + return SYSMi_IsDebuggerBannerViewMode(); +} + +// ISfobK̃oi[r[[hNǂH +static BOOL SYSMi_IsDebuggerBannerViewMode( void ) +{ +#ifdef __IS_DEBUGGER_BUILD + return ( GetSYSMWork()->isOnDebugger && + SYSMi_ExistCard() && + GetRomHeaderAddr()->dbgRomSize == 0 ) ? TRUE : FALSE; +#else + return FALSE; +#endif // __IS_DEBUGGER_BUILD +} + + +// NITROݒf[^̓ǂݏoB +static void SYSMi_ReadNTRSetting( void ) +{ + RTCDate date; + RTCTime time; + + GetSYSMWork()->ncd_invalid = NVRAMm_ReadNitroConfigData( GetNCDWork() ); + // NVRAMNITROݒf[^[hB + if( GetSYSMWork()->ncd_invalid ) { // [hNITROݒf[^A0NÂgpB + OS_TPrintf(" NCD destroyed.\n" ); + SVC_CpuClearFast( 0x0000, GetNCDExWork(), sizeof(NitroConfigDataEx) ); + GetNCDExWork()->version = NITRO_CONFIG_DATA_EX_VERSION; + GetNCDWork()->option.backLightBrightness= 2; // o׎ƓlɁB + GetNCDWork()->option.language = LANG_ENGLISH; // vZbgKvȃf[^̓vZbgĂ + GetNCDWork()->option.destroyFlashFlag = 1; + GetNCDWork()->owner.birthday.month = 1; + GetNCDWork()->owner.birthday.day = 1; + GetNCDExWork()->valid_language_bitmap = VALID_LANG_BITMAP; + } + + // RTC̃Zbg or loꍇ͏NV[PXցB + ( void )RTC_GetDateTime( &date, &time ); + if( !SYSM_CheckRTCDate( &date ) || + !SYSM_CheckRTCTime( &time ) +#ifndef __IS_DEBUGGER_BUILD // ƒfobKłRTC̓drȂ̂ŁA񂱂ɂЂĐݒf[^ЕNAĂ܂BhXCb`B + || ( GetSYSMWork()->rtcStatus & 0x01 ) +#endif + ) { // RTCُ̈oArtc̓tOrtcOffset0ɂNVRAMɏ݁B + OS_TPrintf("\"RTC reset\" or \"Illegal RTC data\" detect!\n"); + GetNCDWork()->option.input_rtc = 0; + GetNCDWork()->option.rtcOffset = 0; + GetNCDWork()->option.rtcLastSetYear = 0; + ( void )NVRAMm_WriteNitroConfigData( GetNCDWork() ); + } +} + + +// TWLݒf[^̓ǂݏo +static void SYSMi_ReadTWLSetting( void ) +{ + +} + + +// NTRݒTWLݒxt@CāAsv΁ANTRݒXV +static void SYSMi_VerifyNTRSetting( void ) +{ +} + + +// RTC̓t`FbN +BOOL SYSM_CheckRTCDate( RTCDate *datep ) +{ + if( ( datep->year >= 100 ) + || ( datep->month < 1 ) || ( datep->month > 12 ) + || ( datep->day < 1 ) || ( datep->day > 31 ) + || ( datep->week >= RTC_WEEK_MAX ) ) { + return FALSE; + } + return TRUE; +} + + +// RTC̎`FbN +BOOL SYSM_CheckRTCTime( RTCTime *timep ) +{ + if( ( timep->hour > 23 ) + || ( timep->minute > 59 ) + || ( timep->second > 59 ) ) { + return FALSE; + } + return TRUE; +} + + +// oi[t@C̓ǂݍ݂̎ +static void SYSMi_ReadCardBannerFile( void ) +{ + s32 lockCardID; + BannerFile *pBanner = &s_bannerBuf; + + if( ( !SYSMi_ExistCard() ) || ( *(void** )BANNER_ROM_OFFSET == NULL ) ) { + s_isBanner = FALSE; + return; + } + + // ROMJ[h̃oi[f[^̃[h + if ( ( lockCardID = OS_GetLockID() ) > 0 ) { + ( void )OS_LockCard( (u16 )lockCardID ); + DC_FlushRange( pBanner, sizeof(BannerFile) ); + SYSM_ReadCard(*(void** )BANNER_ROM_OFFSET, pBanner, sizeof(BannerFile) ); + ( void )OS_UnLockCard( (u16 )lockCardID ); + OS_ReleaseLockID( (u16 )lockCardID ); + } + + // oi[f[^̐`FbN + { + int i; + u16 calc_crc = 0xffff; + u16 *hd_crcp = (u16 *)&pBanner->h.crc16_v1; + BannerCheckParam *chkp = &s_bannerCheckList[ 0 ]; + + s_isBanner = TRUE; + + for( i = 0; i < BNR_VER_MAX; i++ ) { + if( i < pBanner->h.version ) { + calc_crc = SVC_GetCRC16( calc_crc, chkp->srcp, chkp->size ); + if( calc_crc != *hd_crcp++ ) { + s_isBanner = FALSE; + break; + } + }else { + MI_CpuClear16( chkp->srcp, chkp->size ); + } + chkp++; + } + if( !s_isBanner ) { + MI_CpuClear16( &s_bannerBuf, sizeof(BannerFile) ); + } + } +} + + +// N[u[g +static void SYSMi_CheckCardCloneBoot( void ) +{ + s32 lockCardID; + u8 *buffp = (u8 *)&s_bannerBuf; // oi[pobt@e|ƂĎgp + u32 total_rom_size = GetRomHeaderAddr()->total_rom_size ? GetRomHeaderAddr()->total_rom_size : 0x01000000; + u32 file_offset = total_rom_size & 0xFFFFFE00; + + if( !SYSMi_ExistCard() ) { + return; + } + + if ( ( lockCardID = OS_GetLockID() ) > 0 ) { + ( void )OS_LockCard( (u16 )lockCardID ); + DC_FlushRange( buffp, BNR_IMAGE_SIZE ); + SYSM_ReadCard( (void *)file_offset, buffp, BNR_IMAGE_SIZE ); + ( void )OS_UnLockCard( (u16 )lockCardID ); + OS_ReleaseLockID( (u16 )lockCardID ); + } + + buffp += total_rom_size & 0x000001FF; + if( *buffp++ == 'a' && *buffp == 'c' ) { + GetSYSMWork()->clone_boot_mode = CLONE_BOOT_MODE; + }else { + GetSYSMWork()->clone_boot_mode = OTHER_BOOT_MODE; + } +} + + +// ^b`plLu[V +void SYSM_CaribrateTP( void ) +{ +#ifndef __TP_OFF + TPCalibrateParam calibrate; + + ( void )TP_CalcCalibrateParam( &calibrate, // ^b`pl + GetNCDWork()->tp.raw_x1, GetNCDWork()->tp.raw_y1, (u16)GetNCDWork()->tp.dx1, (u16)GetNCDWork()->tp.dy1, + GetNCDWork()->tp.raw_x2, GetNCDWork()->tp.raw_y2, (u16)GetNCDWork()->tp.dx2, (u16)GetNCDWork()->tp.dy2 ); + TP_SetCalibrateParam( &calibrate ); + OS_Printf("TP_calib: %4d %4d %4d %4d %4d %4d\n", + GetNCDWork()->tp.raw_x1, GetNCDWork()->tp.raw_y1, (u16)GetNCDWork()->tp.dx1, (u16)GetNCDWork()->tp.dy1, + GetNCDWork()->tp.raw_x2, GetNCDWork()->tp.raw_y2, (u16)GetNCDWork()->tp.dx2, (u16)GetNCDWork()->tp.dy2 ); +#endif +} + + +// RTCNbN␳lZbg +static void SYSMi_WriteAdjustRTC( void ) +{ +#ifndef __IS_DEBUGGER_BUILD // fobKprh͕␳ȂB + RTCRawAdjust raw; + + raw.adjust = GetNCDWork()->option.rtcClockAdjust; // ncd_invalidɂrtcClockAdjust + // 0NAĂ邽ߕ␳@\͎gpȂ + ( void )RTCi_SetRegAdjust( &raw ); +#endif /* __IS_DEBUGGER_BUILD */ +} + + +// FIFOoRARM7ɃbZ[WʒmBPXI_FIFO_TAG_USER_1gpB +static BOOL SYSMi_SendMessageToARM7(u32 msg) +{ +#pragma unused(msg) + return TRUE; +} + + +// NTR,TWLJ[h݃`FbN u^[@1FJ[hF@0FJ[hȂv +static int SYSMi_ExistCard( void ) +{ + if( ( GetRomHeaderAddr()->nintendo_logo_crc16 == 0xcf56 ) && + ( GetRomHeaderAddr()->header_crc16 == GetSYSMWork()->cardHeaderCrc16) ) { + return TRUE; // NTR,TWLJ[hiNintendoSCRCAJ[hwb_CRCꍇj + // NintendoSf[^̃`FbŃA̓sAS\[`Nɍs܂B + }else { + return FALSE; // NTR,TWLJ[hȂ + } +} + + +// NintendoS`FbN u^[@1:NintendoSF@0Fsv +BOOL SYSM_CheckNinLogo(u16 *logo_cardp) +{ + u16 *logo_orgp = (u16 *)SYSROM9_NINLOGO_ADR; // ARM9̃VXeROM̃Sf[^ƃJ[gbŴ̂r + u16 length = NINTENDO_LOGO_LENGTH >> 1; + + while(length--) { + if(*logo_orgp++ != *logo_cardp++) return FALSE; + } + return TRUE; +} + + +// X[v[hւ̑J +void SYSM_GoSleepMode( void ) +{ +#ifndef __IS_DEBUGGER_BUILD // fobKprh̓X[vȂB + PM_GoSleepMode( (PMWakeUpTrigger)( (PAD_DetectFold() ? PM_TRIGGER_COVER_OPEN : 0) | PM_TRIGGER_RTC_ALARM ), + 0, + 0 ); +#endif /* __IS_DEBUGGER_BUILD */ +} + + +// obNCgPx +void PMm_SetBackLightBrightness( void ) +{ + ( void )PMi_WriteRegister( 4, (u16)NCD_GetBackLightBrightness() ); + ( void )PM_SetBackLight( PM_LCD_ALL, PM_BACKLIGHT_ON ); +} + + +//====================================================================== +// fobO֐ +//====================================================================== + +// f[^̃fobO\ +#ifdef __SYSM_DEBUG +static void SYSMi_DispInitialDebugData( void ) +{ + OS_Printf("SYSM version :20%x\n", SYSMENU_VER); + if( GetMovedInfoFromIPL1Addr()->isOnDebugger ) OS_Printf("Run On IS-DEBUGGER\n"); + else OS_Printf("Run On IS-EMULATOR\n"); + if(GetMovedInfoFromIPL1Addr()->rtcStatus & 0x01) OS_Printf("RTC reset is detected!\n"); + if(GetMovedInfoFromIPL1Addr()->rtcError) OS_Printf("RTC error is detected!\n"); +#if 0 + OS_Printf("NvDate :%4d\n",sizeof(NvDate)); + OS_Printf("NvNickname :%4d\n",sizeof(NvNickname)); + OS_Printf("NvComment :%4d\n",sizeof(NvComment)); + OS_Printf("NvOwnerInfo :%4d\n",sizeof(NvOwnerInfo)); + OS_Printf("NvAlarm :%4d\n",sizeof(NvAlarm)); + OS_Printf("NvTpCalibData:%4d\n",sizeof(NvTpCalibData)); + OS_Printf("NvOption :%4d\n",sizeof(NvOption)); + OS_Printf("NCD :%4d\n",sizeof(NitroConfigData)); + OS_Printf("NCDStore :%4d\n",sizeof(NCDStore)); +#endif +#if 0 + { // ROM_HEADER_BUFF̓eo + int i,j; + u32 *romhp = (u32 *)GetRomHeaderAddr(); + OS_Printf("ROM Header Buff\n "); + for(i = 0; i < 6; i++) { + for(j = 0; j < 4; j++) OS_Printf(" 0x%8x", *romhp++); + OS_Printf("\n "); + } + OS_Printf("\n"); + } + { // ROM_HEADER_BUFF̓eo + int i,j; + u32 *romhp = (u32 *)MB_CARD_ROM_HEADER_ADDRESS; + OS_Printf("MB Card ROM Header Buff\n "); + for(i = 0; i < 6; i++) { + for(j = 0; j < 4; j++) OS_Printf(" 0x%8x", *romhp++); + OS_Printf("\n "); + } + OS_Printf("\n"); + } +#endif /* 0 */ +} +#endif /* __SYSM_DEBUG */ + + + +#ifdef __DEBUG_SECURITY_CODE +// ZLeBƓĂ邩mFfobOR[h +static void DispSingleColorScreen( int mode ) +{ + ( void )OS_DisableIrq(); + GX_LoadBGPltt ( &security_detection_color[ mode ], 0, sizeof(GXRgb) ); + GXS_LoadBGPltt ( &security_detection_color[ mode ], 0, sizeof(GXRgb) ); + GX_DispOn(); + GXS_DispOn(); + GX_SetGraphicsMode ( GX_DISPMODE_GRAPHICS, GX_BGMODE_0, GX_BG0_AS_2D ); + GXS_SetGraphicsMode( GX_BGMODE_0 ); + GX_SetMasterBrightness( 0 ); + GXS_SetMasterBrightness( 0 ); + GX_SetVisiblePlane ( GX_PLANEMASK_NONE ); + GXS_SetVisiblePlane( GX_PLANEMASK_NONE ); +} +#endif + + diff --git a/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_util.c b/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_util.c new file mode 100644 index 0000000..76c45b1 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/ARM9/src/sysmenu_util.c @@ -0,0 +1,172 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SYSM_util.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include + +// define data------------------------------------------ + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- +static s64 SYSMi_CalcRtcSecOffset( RTCDate *datep, RTCTime *timep ); + +// global variable ------------------------------------- + +// static variable ------------------------------------- + +// const data ----------------------------------------- + +// function's description------------------------------- + +//====================================================================== +// NITROݒf[^@[N +//====================================================================== + +// NITROݒf[^̃jbNl[EFEȁB +void NCD_ClearOwnerInfo( void ) +{ + NitroConfigData *ncdp = GetNCDWork(); + + MI_CpuClear16( &ncdp->owner, sizeof(NvOwnerInfo) ); + ncdp->owner.birthday.month = 1; + ncdp->owner.birthday.day = 1; + ncdp->option.input_birthday = 0; + ncdp->option.input_favoriteColor = 0; + ncdp->option.input_nickname = 0; +} + + +//====================================================================== +// RTCItZbg +//====================================================================== + +// RTCɐVݒlZbgāA̒lƂrtcOffsetlZoB +s64 SYSM_CalcRtcOffsetAndSetDateTime( RTCDate *newDatep, RTCTime *newTimep ) +{ + RTCDate oldDate; + RTCTime oldTime; + s64 offset0; + s64 offset1; + s64 offset; + + // RTCւ̐Vl̐ݒ + (void)RTC_GetDateTime( &oldDate, &oldTime ); // CgOɌ݂RTCl擾B + (void)RTC_SetDateTime( newDatep, newTimep ); // VRTCݒl̃ZbgB + oldTime.second = 0; + + // RTCݒ莞́A̐ݒłǂꂾRTClωibItZbgPʁjZoB + if( ( oldDate.year < NCD_GetRtcLastSetYear() ) && ( NCD_GetInputRTC() ) ) { + oldDate.year += 100; // O̐ݒ`̐ݒ̊ԂRTCĂ܂Ayear100ZoffsetvZB + } + NCD_SetRtcLastSetYear( (u8)newDatep->year ); + + offset0 = SYSMi_CalcRtcSecOffset( &oldDate, &oldTime ); // ݒ蒼ORTCl̃ItZbgZo + offset1 = SYSMi_CalcRtcSecOffset( newDatep, newTimep ); // VZbgꂽRTCl̃ItZbgZo + offset = NCD_GetRtcOffset() + offset1 - offset0; // VRTC_ofs ݂RTC_ofs ̍̒lZă^[B + + OS_Printf ("Now Date = year:%3d month:%3d date:%3d hour:%3d minute:%3d second:%3d\n", + oldDate.year, oldDate.month, oldDate.day, + oldTime.hour, oldTime.minute, oldTime.second); + OS_Printf ("Set Date = year:%3d month:%3d date:%3d hour:%3d minute:%3d second:%3d\n", + newDatep->year, newDatep->month, newDatep->day, + newTimep->hour, newTimep->minute, newTimep->second); + OS_Printf ("offset[0] = %x\n", offset0 ); + OS_Printf ("offset[1] = %x\n", offset1 ); + OS_Printf ("rtcOffset = %x\n", offset ); + + return offset; +} + + +// RTCItZbgl̎Zo +#define SECOND_OFFSET +static s64 SYSMi_CalcRtcSecOffset( RTCDate *datep, RTCTime *timep ) +{ + u32 i; + int uruu = 0; + int dayNum = 0; + s64 offset; + + // AAb@b or ItZbg +#ifdef SECOND_OFFSET + offset = ( timep->hour * 60 + timep->minute ) * 60 + timep->second; +#else + offset = timep->hour * 60 + timep->minute; +#endif + + // A@ɊZĂA@b or ItZbg + dayNum = (int)datep->day - 1; + for( i = 1; i < datep->month; i++ ) { + dayNum += SYSM_GetDayNum( datep->year, i ); + } + + // N@ɊZ + if( datep->year > 0 ) { + uruu = ( ( (int)datep->year - 1 ) >> 2 ) + 1; // wN-1܂ł̂邤ҐZoāA̓ZB + } + dayNum += uruu + (u32)( datep->year * 365 ); + + // NEEɊZl@b or ItZbg +#ifdef SECOND_OFFSET + offset += (s64)( dayNum * 24 * 3600 ); +#else + offset += (s64)( dayNum * 24 * 60 ); +#endif + + return offset; +} + + +// w肳ꂽNE̓ԂB +u32 SYSM_GetDayNum( u32 year, u32 month ) +{ + u32 dayNum = 31; + if( month == 2 ) { + if( SYSM_IsLeapYear100( year ) ) { + dayNum -= 2; + }else { + dayNum -= 3; + } + }else if( ( month == 4 ) || ( month == 6 ) || ( month == 9 ) || ( month == 11 ) ) { + dayNum--; + } + return dayNum; +} + +/* +u32 SYSM_GetDayNum( u32 year, u32 month ) +{ + u8 date_tbl[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + if( ( month == 2 ) && SYSM_IsLeapYear100( year ) ) { + return 29; + } + return date_tbl[ month - 1 ]; // PPQP +} +*/ + +// ȈՂ邤N̔ (邤NF1Aʏ̔NF0jRTĈƂ肤2000`2100NɌ肷B +BOOL SYSM_IsLeapYear100( u32 year ) +{ + if( ( year & 0x03 ) || ( year == 100 ) ) { // 邤ŃAu4Ŋ؂@@100Ŋ؂ȂNv܂́u400Ŋ؂Nv + return FALSE; + }else { + return TRUE; + } +} + diff --git a/build/libraries_sysmenu/sysmenu/Makefile b/build/libraries_sysmenu/sysmenu/Makefile new file mode 100644 index 0000000..52c5a13 --- /dev/null +++ b/build/libraries_sysmenu/sysmenu/Makefile @@ -0,0 +1,33 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +TARGET_FIRM = SYSTEMMENU + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nand_formatter/.DS_Store b/build/nand_formatter/.DS_Store new file mode 100644 index 0000000..c865c9d Binary files /dev/null and b/build/nand_formatter/.DS_Store differ diff --git a/build/nand_formatter/ARM7/Makefile b/build/nand_formatter/ARM7/Makefile new file mode 100644 index 0000000..3a6a2fe --- /dev/null +++ b/build/nand_formatter/ARM7/Makefile @@ -0,0 +1,53 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-09#$ +# $Rev: 1486 $ +# $Author: terui $ +#---------------------------------------------------------------------------- + +TARGET_PLATFORM = TWL +#TWL_ARCHGEN = LIMITED +TWL_PROC = ARM7 +TWL_NO_STD_PCHDR = TRUE + +#---------------------------------------------------------------------------- + +SRCS = main.c \ + dummy.FLXMAIN.c \ + dummy.FLXWRAM.c \ + dummy.LTDMAIN.c \ + dummy.LTDWRAM.c + +TARGET_NAME = formatter_sub + +TARGET_NEF = $(TARGET_NAME).tef +LCFILE_SPEC = $(TARGET_NAME).lsf +LCFILE_TEMPLATE = $(TARGET_NAME).lcf.template +LDRES_TEMPLATE = $(TARGET_NAME).response.template + +CRT0_O = crt0.LTD.TWL.o + +#---------------------------------------------------------------------------- +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +MACRO_FLAGS += -DSDK_ARM7COMP_LTD + +MAKELCF_FLAGS += -DISTD_LIBS='$(ISTD_LIBS)' + +do-build: $(TARGETS) + +#---------------------------------------------------------------------------- +include $(TWLSDK_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/nand_formatter/ARM7/formatter_sub.lcf.template b/build/nand_formatter/ARM7/formatter_sub.lcf.template new file mode 100644 index 0000000..87fabc1 --- /dev/null +++ b/build/nand_formatter/ARM7/formatter_sub.lcf.template @@ -0,0 +1,897 @@ +#--------------------------------------------------------------------------- +# Project: TwlSDK - demos - FATFS - formatter - formatter_sub.TWL +# File: mongoose.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 > + + + (RWX) : ORIGIN = , LENGTH = 0x0 >> + + binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + check.WORKRAM (RWX) : ORIGIN = 0x037f8000, LENGTH = 0x18000 > workram.check + check.MAINMEM (RWX) : ORIGIN = 0x02fe0000, LENGTH = 0x1c000 > mainmem.check + + binary.LTDAUTOLOAD_TOP (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWX) : ORIGIN = , LENGTH = 0x0 >> + + binary.LTDAUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + check.LTDWRAM (RWX) : ORIGIN = 0x03000000, LENGTH = 0x40000 > ltdwram.check + check.LTDMAIN (RWX) : ORIGIN = 0x02f88000, LENGTH = 0x58000 > ltdmain.check +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + #:::::::::: text/rodata + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_STATIC_DATA_END =.; + . = ALIGN(4); + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_STATIC_BSS_END = .; + + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.MAIN.START = 0x02fe0000; + SDK_AUTOLOAD.MAIN.END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.BSS_END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.SIZE = 0; + SDK_AUTOLOAD.MAIN.BSS_SIZE = 0; + SDK_AUTOLOAD.WRAM.START = 0x037f8000; + SDK_AUTOLOAD.WRAM.END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.BSS_END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.SIZE = 0; + SDK_AUTOLOAD.WRAM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + __exception_table_start__ =.; + EXCEPTION + __exception_table_end__ =.; + SDK_STATIC_ETABLE_END =.; + + + + + + + + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(4); + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + . = ALIGN(4); + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_MAIN_START = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD_MAIN_END = SDK_AUTOLOAD.MAIN.END; + SDK_AUTOLOAD_MAIN_BSS_END = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_AUTOLOAD_MAIN_SIZE = SDK_AUTOLOAD.MAIN.SIZE; + SDK_AUTOLOAD_MAIN_BSS_SIZE = SDK_AUTOLOAD.MAIN.BSS_SIZE; + SDK_AUTOLOAD_WRAM_START = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD_WRAM_END = SDK_AUTOLOAD.WRAM.END; + SDK_AUTOLOAD_WRAM_BSS_END = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_AUTOLOAD_WRAM_SIZE = SDK_AUTOLOAD.WRAM.SIZE; + SDK_AUTOLOAD_WRAM_BSS_SIZE = SDK_AUTOLOAD.WRAM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + + } > binary.AUTOLOAD_INFO + + SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; + SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_OVERLAY..DATA_END =.; + . = ALIGN(4); + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(4); + SDK_SECTION_ARENA_START =.; + + } > arena.MAIN + + ############################ OVERLAYDEFS ############################ + .F: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > F + + ############################ OVERLAYTABLE ########################### + .F: + { + + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + } > F + + ############################ OTHERS ################################# + SDK_WRAM_ARENA_LO = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_SUBPRIV_ARENA_LO = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_IRQ_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + + .check.WORKRAM: + { + . = . + SDK_AUTOLOAD.WRAM.BSS_END - SDK_AUTOLOAD.WRAM.START + 0x080 + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + + } > check.WORKRAM + + .check.MAINMEM: + { + . = SDK_SUBPRIV_ARENA_LO; + + } > check.MAINMEM + + ########################### LTDAUTOLOADS ############################ + SDK_LTDAUTOLOAD.LTDMAIN.START = SDK_STATIC_BSS_END; + SDK_LTDAUTOLOAD.LTDMAIN.END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.SIZE = 0; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE = 0; + SDK_LTDAUTOLOAD.LTDWRAM.START = 0x03000000; + SDK_LTDAUTOLOAD.LTDWRAM.END = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD.LTDWRAM.BSS_END = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD.LTDWRAM.SIZE = 0; + SDK_LTDAUTOLOAD.LTDWRAM.BSS_SIZE = 0; + SDK_LTDAUTOLOAD_TOP_START = 0x02e80000; + SDK_LTDAUTOLOAD_TOP_SIZE = 4; # STATIC ̈悪 4 bytes ̃_~[oCit@C̐擪ɓ # + SDK_LTDAUTOLOAD_START = SDK_LTDAUTOLOAD_TOP_START + SDK_LTDAUTOLOAD_TOP_SIZE; + SDK_LTDAUTOLOAD_SIZE = 0; + SDK_LTDAUTOLOAD_NUMBER = ; + + .binary.LTDAUTOLOAD_TOP: + { + WRITEW 0xdeadbeef; + + } > binary.LTDAUTOLOAD_TOP + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDAUTOLOAD__ID =; + SDK_LTDAUTOLOAD..ID =; + SDK_LTDAUTOLOAD..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDAUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + #:::::::::: text/rodata + SDK_LTDAUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(4); + SDK_LTDAUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_LTDAUTOLOAD..DATA_END =.; + . = ALIGN(4); + SDK_LTDAUTOLOAD..END =.; + + SDK_LTDAUTOLOAD..TEXT_SIZE = SDK_LTDAUTOLOAD..TEXT_END - SDK_LTDAUTOLOAD..TEXT_START; + SDK_LTDAUTOLOAD..DATA_SIZE = SDK_LTDAUTOLOAD..DATA_END - SDK_LTDAUTOLOAD..DATA_START; + SDK_LTDAUTOLOAD..SIZE = SDK_LTDAUTOLOAD..END - SDK_LTDAUTOLOAD..START; + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDAUTOLOAD..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_LTDAUTOLOAD..BSS_END =.; + + SDK_LTDAUTOLOAD..BSS_SIZE = SDK_LTDAUTOLOAD..BSS_END - SDK_LTDAUTOLOAD..BSS_START; + + } >> + + + + SDK_LTDAUTOLOAD_LTDMAIN_START = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD_LTDMAIN_END = SDK_LTDAUTOLOAD.LTDMAIN.END; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + SDK_LTDAUTOLOAD_LTDMAIN_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.SIZE; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE; + SDK_LTDAUTOLOAD_LTDWRAM_START = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD_LTDWRAM_END = SDK_LTDAUTOLOAD.LTDWRAM.END; + SDK_LTDAUTOLOAD_LTDWRAM_BSS_END = SDK_LTDAUTOLOAD.LTDWRAM.BSS_END; + SDK_LTDAUTOLOAD_LTDWRAM_SIZE = SDK_LTDAUTOLOAD.LTDWRAM.SIZE; + SDK_LTDAUTOLOAD_LTDWRAM_BSS_SIZE = SDK_LTDAUTOLOAD.LTDWRAM.BSS_SIZE; + + ######################### LTDAUTOLOAD_INFO ########################## + .binary.LTDAUTOLOAD_INFO: + { + + WRITEW ADDR(.); + WRITEW SDK_LTDAUTOLOAD..SIZE; + WRITEW SDK_LTDAUTOLOAD..BSS_SIZE; + + + } > binary.LTDAUTOLOAD_INFO + + SDK_LTDAUTOLOAD_LIST = SDK_LTDAUTOLOAD_START + SDK_LTDAUTOLOAD_SIZE; + SDK_LTDAUTOLOAD_LIST_END = SDK_LTDAUTOLOAD_LIST + SIZEOF(.binary.LTDAUTOLOAD_INFO); + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SIZEOF(.binary.LTDAUTOLOAD_INFO); + + ########################### LTDOVERLAYS ############################# + SDK_LTDOVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDOVERLAY__ID =; + SDK_LTDOVERLAY..ID =; + SDK_LTDOVERLAY..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDOVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_LTDOVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_LTDOVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_LTDOVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_LTDOVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_LTDOVERLAY..DATA_END =.; + . = ALIGN(4); + SDK_LTDOVERLAY..END =.; + + SDK_LTDOVERLAY..TEXT_SIZE = SDK_LTDOVERLAY..TEXT_END - SDK_LTDOVERLAY..TEXT_START; + SDK_LTDOVERLAY..DATA_SIZE = SDK_LTDOVERLAY..DATA_END - SDK_LTDOVERLAY..DATA_START; + SDK_LTDOVERLAY..SIZE = SDK_LTDOVERLAY..END - SDK_LTDOVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDOVERLAY..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_LTDOVERLAY..BSS_END =.; + + SDK_LTDOVERLAY..BSS_SIZE = SDK_LTDOVERLAY..BSS_END - SDK_LTDOVERLAY..BSS_START; + + } >> + + + + ########################## LTDOVERLAYDEFS ########################### + .L: + { + ### TWL limited extended static module information + WRITEW SDK_LTDAUTOLOAD_TOP_START; # load address + WRITEW 0; # padding + WRITEW SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD_TOP_SIZE; # size of module + WRITEW 0; # padding + + ### TWL limited overlay filename + + WRITES (""); + + + } > L + + ######################### LTDOVERLAYTABLE ########################### + .L: + { + + WRITES # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_LTDOVERLAY..SIZE; # size of module + WRITEW SDK_LTDOVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_LTDOVERLAY..SINIT_START; # start address of static init + WRITEW SDK_LTDOVERLAY..SINIT_END; # end address of static init + WRITEW # ROM file ID + WRITEW 0; # Reserved + + + } > L + + ############################ OTHERS ################################# + .check.LTDWRAM: + { + . = SDK_LTDAUTOLOAD.LTDWRAM.BSS_END; + + } > check.LTDWRAM + + .check.LTDMAIN: + { + . = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + + } > check.LTDMAIN + +} diff --git a/build/nand_formatter/ARM7/formatter_sub.lsf b/build/nand_formatter/ARM7/formatter_sub.lsf new file mode 100644 index 0000000..390cb60 --- /dev/null +++ b/build/nand_formatter/ARM7/formatter_sub.lsf @@ -0,0 +1,79 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - demos - FATFS - formatter - formatter_sub +# File: mongoose.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# Nitro LCF SPEC FILE +# +#-------- +Static $(TARGET_NAME) +{ + Address 0x02f88000 + Library crt0.HYB.TWL.o + StackSize 1024 1024 +} + +#-------- +Autoload WRAM +{ + Address 0x037f8000 + + Library libsubpsyscall.a \ + $(CW_LIBS) \ + libos_sp.TWL$(CODEGEN).a \ + libmi_sp.TWL$(CODEGEN).a \ + libpad_sp.TWL$(CODEGEN).a \ + libpxi_sp.TWL$(CODEGEN).a \ + libstd_sp.TWL$(CODEGEN).a \ + libexi_sp.TWL$(CODEGEN).a \ + libsnd_sp.TWL$(CODEGEN).a \ + libspi_sp.TWL$(CODEGEN).a \ + libpm_sp.TWL$(CODEGEN).a \ + libcdc_sp.TWL$(CODEGEN).a \ + libtp_sp.TWL$(CODEGEN).a \ + libtpex_sp.TWL$(CODEGEN).a \ + libnvram_sp.TWL$(CODEGEN).a \ + $(ISTD_LIBS) + + Object * (.etable) + Object * (.wram) + Object $(OBJDIR)/main.o + Object $(OBJDIR)/dummy.FLXWRAM.o +} + +#-------- +Autoload MAIN +{ + Address 0x02fe0000 + Object $(OBJDIR)/dummy.FLXMAIN.o +} + +#-------- +Ltdautoload LTDWRAM +{ + Address 0x03000000 + Object * (.ltdwram) + Object $(OBJDIR)/dummy.LTDWRAM.o +} + +#-------- +Ltdautoload LTDMAIN +{ + After $(TARGET_NAME) + Object * (.ltdmain) + Object $(OBJDIR)/dummy.LTDMAIN.o + Library libfatfs_sp.TWL$(CODEGEN).a +} + diff --git a/build/nand_formatter/ARM7/formatter_sub.response.template b/build/nand_formatter/ARM7/formatter_sub.response.template new file mode 100644 index 0000000..88b1808 --- /dev/null +++ b/build/nand_formatter/ARM7/formatter_sub.response.template @@ -0,0 +1,40 @@ + + + + + -l + + + + + + + -l + + + + -og ,0 -ol + + + + + -l + + + + + + + + -l + + + + -og ,0 -ol + + + + + -l + + diff --git a/build/nand_formatter/ARM7/src/dummy.EXTWRAM.c b/build/nand_formatter/ARM7/src/dummy.EXTWRAM.c new file mode 100644 index 0000000..0f2e61f --- /dev/null +++ b/build/nand_formatter/ARM7/src/dummy.EXTWRAM.c @@ -0,0 +1,27 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +extern void Dummy_EXTWRAM(void); + +void +Dummy_EXTWRAM(void) +{ + OS_Printf("Printed from extra wram area. [%p]\n", Dummy_EXTWRAM); +} + diff --git a/build/nand_formatter/ARM7/src/dummy.FLXMAIN.c b/build/nand_formatter/ARM7/src/dummy.FLXMAIN.c new file mode 100644 index 0000000..3001470 --- /dev/null +++ b/build/nand_formatter/ARM7/src/dummy.FLXMAIN.c @@ -0,0 +1,27 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +extern void Dummy_FLXMAIN(void); + +void +Dummy_FLXMAIN(void) +{ + OS_Printf("Printed from flexible main memory area. [%p]\n", Dummy_FLXMAIN); +} + diff --git a/build/nand_formatter/ARM7/src/dummy.FLXWRAM.c b/build/nand_formatter/ARM7/src/dummy.FLXWRAM.c new file mode 100644 index 0000000..75e7057 --- /dev/null +++ b/build/nand_formatter/ARM7/src/dummy.FLXWRAM.c @@ -0,0 +1,27 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +extern void Dummy_FLXWRAM(void); + +void +Dummy_FLXWRAM(void) +{ + OS_Printf("Printed from flexible wram area. [%p]\n", Dummy_FLXWRAM); +} + diff --git a/build/nand_formatter/ARM7/src/dummy.LTDMAIN.c b/build/nand_formatter/ARM7/src/dummy.LTDMAIN.c new file mode 100644 index 0000000..48d46a1 --- /dev/null +++ b/build/nand_formatter/ARM7/src/dummy.LTDMAIN.c @@ -0,0 +1,27 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +extern void Dummy_LTDMAIN(void); + +void +Dummy_LTDMAIN(void) +{ + OS_Printf("Printed from limited main memory area. [%p]\n", Dummy_LTDMAIN); +} + diff --git a/build/nand_formatter/ARM7/src/dummy.LTDWRAM.c b/build/nand_formatter/ARM7/src/dummy.LTDWRAM.c new file mode 100644 index 0000000..aec15de --- /dev/null +++ b/build/nand_formatter/ARM7/src/dummy.LTDWRAM.c @@ -0,0 +1,27 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include + +extern void Dummy_LTDWRAM(void); + +void +Dummy_LTDWRAM(void) +{ + OS_Printf("Printed from limited wram area. [%p]\n", Dummy_LTDWRAM); +} + diff --git a/build/nand_formatter/ARM7/src/main.c b/build/nand_formatter/ARM7/src/main.c new file mode 100644 index 0000000..436aa1b --- /dev/null +++ b/build/nand_formatter/ARM7/src/main.c @@ -0,0 +1,393 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +typedef struct FileProperty { + u32 size; + const char *path; +}FileProperty; + +extern void Dummy_FLXWRAM(void); +extern void Dummy_FLXMAIN(void); +#ifdef SDK_WIRELESS_IN_VRAM +extern void Dummy_EXTWRAM(void); +#endif +extern void Dummy_LTDWRAM(void); +extern void Dummy_LTDMAIN(void); + +static void Pragma_LTDWRAM(void); +static void Pragma_LTDMAIN(void); + +static void CreateDirectory( const char *pDrive, const char **ppDirList ); +static void CheckDirectory ( const char *pDrive, const char **ppDirList ); +static void CreateFile( const FileProperty *pFileList ); +static void CheckFile ( const FileProperty *pFileList ); + +// const data-------------------------------------------------------- + +// FATFS̃NX^TCY16KB +static const FileProperty s_fileList[] = { + { 128, "F:/sys/ID.sgn" }, // ASTCY͓KBgB + { 4096, "F:/sys/HWINFO.dat" }, + { 4096, "F:/shared1/TWLCFG0.dat" }, + { 4096, "F:/shared1/TWLCFG1.dat" }, // ~[ + { 4096, "F:/shared1/WIFICFG0.dat" }, + { 4096, "F:/shared1/WIFICFG1.dat" }, // ~[ + { 0, NULL }, +}; + +static const char *s_pDirList0[] = { + (const char *)"sys", + (const char *)"title", + (const char *)"ticket", + (const char *)"shared1", + (const char *)"import", + (const char *)"tmp", + NULL, + }; + +static const char *s_pDirList1[] = { + (const char *)"photo", + (const char *)"shared2", + NULL, + }; + + + +/*---------------------------------------------------------------------------*/ +#include +static void +Pragma_LTDWRAM(void) +{ + OS_Printf("Printed from limited wram area by pragma. [%p]\n", Pragma_LTDWRAM); +} +#include + +/*---------------------------------------------------------------------------*/ +#include +static void +Pragma_LTDMAIN(void) +{ + OS_Printf("Printed from limited main memory area by pragma. [%p]\n", Pragma_LTDMAIN); +} +#include + + +/*---------------------------------------------------------------------------* + Name: InitializeAllocateSystem + + Description: ăVXeB + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +static void InitializeAllocateSystem(void) +{ + void *tempLo; + OSHeapHandle hh; + + OS_TPrintf("OS_GetWramSubPrivArenaLo() = %p\n", OS_GetWramSubPrivArenaLo()); + OS_TPrintf("OS_GetWramSubPrivArenaHi() = %p\n", OS_GetWramSubPrivArenaHi()); + OS_TPrintf("OS_GetWramSubArenaLo() = %p\n", OS_GetWramSubArenaLo()); + OS_TPrintf("OS_GetWramSubArenaHi() = %p\n", OS_GetWramSubArenaHi()); + OS_TPrintf("OS_GetSubPrivArenaLo() = %p\n", OS_GetSubPrivArenaLo()); + OS_TPrintf("OS_GetSubPrivArenaHi() = %p\n", OS_GetSubPrivArenaHi()); + + OS_TPrintf("call OS_SetWramSubPrivArenaHi(0x0380f980); to fix arena.\n"); + OS_SetWramSubPrivArenaHi((void*)0x0380f980); + + // ď + tempLo = OS_InitAlloc(OS_ARENA_WRAM_SUBPRIV, + OS_GetWramSubPrivArenaLo(), OS_GetWramSubPrivArenaHi(), 1); + + // A[i0NA + MI_CpuClear8(tempLo, (u32)OS_GetWramSubPrivArenaHi() - (u32)tempLo); + + // A[iʃAhXݒ + OS_SetArenaLo(OS_ARENA_WRAM_SUBPRIV, tempLo); + // q[v쐬 + hh = OS_CreateHeap(OS_ARENA_WRAM_SUBPRIV, + OS_GetWramSubPrivArenaLo(), OS_GetWramSubPrivArenaHi()); + + if (hh < 0) + { + OS_Panic("ARM7: Fail to create heap.\n"); + } + + // Jgq[vɐݒ + (void)OS_SetCurrentHeap(OS_ARENA_WRAM_SUBPRIV, hh); +} + +/*---------------------------------------------------------------------------* + Name: TwlSpMain + Description: NxN^B + Arguments: None. + Returns: None. + *---------------------------------------------------------------------------*/ +void +TwlSpMain(void) +{ + int nand_fat_partition_num; + + OS_Init(); + SPI_Init(2); + OS_InitTick(); + OS_InitAlarm(); + OS_InitThread(); + (void)PAD_InitXYButton(); + InitializeAllocateSystem(); + + // 荞݂̗L + (void)OS_EnableIrq(); + (void)OS_EnableInterrupts(); + + // FATFSCupq[v𐶐 (}IARM9̋󔒕Ԏ؂) + { + OSHeapHandle hh; + u8 *lo = (u8*)0x02A00000; // OS_GetSubPrivArenaLo() + u8 *hi = (u8*)0x02B00000; // OS_GetSubPrivArenaHi() + OS_SetSubPrivArenaLo(OS_InitAlloc(OS_ARENA_MAIN_SUBPRIV, lo, hi, 1)); + hh = OS_CreateHeap(OS_ARENA_MAIN_SUBPRIV, lo + 32, hi - 32); + OS_SetCurrentHeap(OS_ARENA_MAIN_SUBPRIV, hh); + } + + // FATFSCuSDIOFATp[T + if(!FATFS_Init(FATFS_DMA_NOT_USE, 8)) + { + OS_TPanic("FATFS_Init() failed.\n"); + } + + // NANDtH[}bg + { +#define FATAL_ERROR() do {} while (TRUE) + // ҏWASDKFATFS_Init̓p[^CKvB +#define NAND_SIZE 245 // 256MB mobiNANDł̎gp”\TCYiiNANDł͈ႤlɂȂBBj +#define PARTITION_RAW_SIZE 4 +#define PARTITION_0_SIZE 213 +#define PARTITION_1_SIZE ( NAND_SIZE - PARTITION_RAW_SIZE - PARTITION_0_SIZE ) +#define NAND_FAT_PARTITION_NUM 2 // FATp[eBViRAWp[eBVj + + int i; + + /* p[eBVTCYvvgݒ */ + u32 partition_MB_size[5]; + partition_MB_size[0] = PARTITION_RAW_SIZE; // RAẄ + partition_MB_size[1] = PARTITION_0_SIZE; // FAT0̈ + partition_MB_size[2] = PARTITION_1_SIZE; // FAT1̈ + nand_fat_partition_num = NAND_FAT_PARTITION_NUM; + + for( i=0; imain_ram_address = 0x00000000; + } + + while (TRUE) + { + OS_Halt(); + } +} + + +// fBNg쐬 +static void CreateDirectory( const char *pDrive, const char **ppDirList ) +{ + // ftHghCu̎w + OS_TPrintf( "\nCreate directory : %s\n", pDrive ); + if( !FATFS_SetDefaultDrive( pDrive ) ) { + FATAL_ERROR(); + } + // w肳ꂽfBNg[gɍ쐬 + while( *ppDirList ) { + OS_TPrintf( " %s...", *ppDirList ); + if( !FATFS_CreateDirectory( *ppDirList, "rwxrwxrwx") ) { + OS_TPrintf( "ng.\n" ); + FATAL_ERROR(); + } + OS_TPrintf( "ok.\n" ); + ppDirList++; + } +} + + +// fBNg݃`FbN +static void CheckDirectory( const char *pDrive, const char **ppDirList ) +{ + // ftHghCu̎w + OS_TPrintf( "\nCheck directory : %s\n", pDrive ); + if( !FATFS_SetDefaultDrive( pDrive ) ) { + FATAL_ERROR(); + } + + // w肳ꂽfBNg`FbN + while( *ppDirList ) { + FATFSDirectoryHandle dir = FATFS_OpenDirectory( *ppDirList, "rw"); + OS_TPrintf( " %s...", *ppDirList ); + if (dir != NULL) + { + OS_TPrintf( "ok.\n" ); + (void)FATFS_CloseDirectory( dir ); + }else { + OS_TPrintf( "ng.\n" ); + FATAL_ERROR(); + } + ppDirList++; + } +} + + +// t@C쐬 +static void CreateFile( const FileProperty *pFileList ) +{ + // ftHghCu̎w + OS_TPrintf( "\nCreate File :\n" ); + + // w肳ꂽfBNg[gɍ쐬 + while( pFileList->path ) { + FATFSFileHandle file; + + OS_TPrintf( " %s, %dbytes...", pFileList->path, pFileList->size ); + if( !FATFS_CreateFile( pFileList->path, TRUE, "rwxrwxrwx" ) ) { + OS_TPrintf( "ng.\n" ); + FATAL_ERROR(); + } + file = FATFS_OpenFile( pFileList->path, "w" ); + if( !file ) { + OS_TPrintf( "ng.\n" ); + FATAL_ERROR(); + } + if( !FATFS_SetFileLength( file, (int)pFileList->size ) ) { + OS_TPrintf( "ng.\n" ); + FATAL_ERROR(); + } + (void)FATFS_CloseFile( file ); + OS_TPrintf( "ok.\n" ); + pFileList++; + } +} + + +// t@C`FbN +static void CheckFile( const FileProperty *pFileList ) +{ + // ftHghCu̎w + OS_TPrintf( "\nCheck File :\n" ); + + // w肳ꂽfBNg[gɍ쐬 + while( pFileList->path ) { + FATFSFileHandle file; + + OS_TPrintf( " %s, %dbytes...", pFileList->path, pFileList->size ); + file = FATFS_OpenFile( pFileList->path, "r" ); + if( !file ) { + OS_TPrintf( "ng.\n" ); + FATAL_ERROR(); + } + if( FATFS_GetFileLength( file ) != pFileList->size ) { + OS_TPrintf( "ng. size = %d\n", FATFS_GetFileLength( file ) ); + FATAL_ERROR(); + } + (void)FATFS_CloseFile( file ); + OS_TPrintf( "ok.\n" ); + pFileList++; + } +} + diff --git a/build/nand_formatter/ARM9/Makefile b/build/nand_formatter/ARM9/Makefile new file mode 100644 index 0000000..780ac45 --- /dev/null +++ b/build/nand_formatter/ARM9/Makefile @@ -0,0 +1,42 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-18 #$ +# $Rev: 972 $ +# $Author: hatamoto_minoru $ +#---------------------------------------------------------------------------- + +TARGET_PLATFORM = TWL + +TWL_PROC = ARM9 +#TWL_ARCHGEN = LIMITED +TARGET_BIN = formatter.srl + +MAKEROM_ARM7_BASE = ../ARM7/bin/$(TWL_BUILDTYPE_ARM7)/formatter_sub +MAKEROM_ARM7 = $(MAKEROM_ARM7_BASE).tef + +SRCS = main.c + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +SUBDIRS = ../ARM7 + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/nand_formatter/ARM9/src/main.c b/build/nand_formatter/ARM9/src/main.c new file mode 100644 index 0000000..6446b4d --- /dev/null +++ b/build/nand_formatter/ARM9/src/main.c @@ -0,0 +1,89 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + + +#include +#include +#include + + +//================================================================================ + + +/*---------------------------------------------------------------------------* + Name: VBlankIntr + + Description: VBlank interrupt handler + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static void VBlankIntr(void) +{ + //---- check interrupt flag + OS_SetIrqCheckFlag(OS_IE_V_BLANK); +} + +/*---------------------------------------------------------------------------* + Name: NitroMain + + Description: main + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void NitroMain(void) +{ + OS_InitArena(); + PXI_Init(); + OS_InitLock(); + OS_InitArenaEx(); + OS_InitIrqTable(); + OS_SetIrqStackChecker(); + MI_Init(); + OS_InitVAlarm(); + OSi_InitVramExclusive(); + OS_InitThread(); + OS_InitReset(); + OS_Init(); + GX_Init(); + + (void)OS_SetIrqFunction(OS_IE_V_BLANK, VBlankIntr); + (void)OS_EnableIrqMask(OS_IE_V_BLANK); + (void)OS_EnableIrq(); + (void)GX_VBlankIntr(TRUE); + + FATFS_Init(); + + // ARM7̃tH[}bgʒm҂ (ĂƂ΂₭ȕ@ŒʒmĂ) + OS_TPrintf("now formatting NAND partitions...\n"); + { + const CARDRomHeader *header = CARD_GetOwnRomHeader(); + while (*(u32 *)header->main_ram_address != 0x00000000) + { + OS_WaitVBlankIntr(); + } + } + + OS_TPrintf("format has completed!\n"); + OS_Terminate(); +} + + +/*====== End of main.c ======*/ diff --git a/build/nand_formatter/Makefile b/build/nand_formatter/Makefile new file mode 100644 index 0000000..aa8f3c0 --- /dev/null +++ b/build/nand_formatter/Makefile @@ -0,0 +1,34 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - firmware +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + ARM7 \ + ARM9 \ + + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/.DS_Store b/build/nandfirm/.DS_Store new file mode 100644 index 0000000..728f19e Binary files /dev/null and b/build/nandfirm/.DS_Store differ diff --git a/build/nandfirm/Makefile b/build/nandfirm/Makefile new file mode 100644 index 0000000..c74b708 --- /dev/null +++ b/build/nandfirm/Makefile @@ -0,0 +1,35 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - firmware +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + nandfirm-print \ + sdmc-launcher \ + menu-launcher \ + + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/menu-launcher/ARM7/Makefile b/build/nandfirm/menu-launcher/ARM7/Makefile new file mode 100644 index 0000000..2513f59 --- /dev/null +++ b/build/nandfirm/menu-launcher/ARM7/Makefile @@ -0,0 +1,51 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - menu-launcher +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +FIRM_PROC = ARM7 +FIRM_TARGET = FIRM + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = menu_launcher7.tef + +SRCS = main.c + +CRT0_O = crt0_firm.o + +#LCFILE_TEMPLATE = $(FIRM_SPECDIR)/$(FIRM_PROC)-$(FIRM_PLATFORM)-PARTNER.lcf.template + +#SRCDIR = # using default +#LCFILE = # using default + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +LLIBRARIES = libaes_sp$(TWL_LIBSUFFIX).a + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/menu-launcher/ARM7/main.c b/build/nandfirm/menu-launcher/ARM7/main.c new file mode 100644 index 0000000..a84cee9 --- /dev/null +++ b/build/nandfirm/menu-launcher/ARM7/main.c @@ -0,0 +1,182 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - nandfirm - menu-launcher + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +#define FATFS_HEAP_SIZE (64*1024) // FATFSpq[v (TCYKv) + +#define BOOT_DEVICE FATFS_MEDIA_TYPE_NAND +#define PARTITION_NO 0 // Ώۃp[eBV + +#define DRIVE_LETTER 'A' // }EghCu +#define DRIVE_NO (DRIVE_LETTER - 'A') // }EghCuԍ + +static u8 fatfsHeap[FATFS_HEAP_SIZE] __attribute__ ((aligned (32))); + +static SDPortContextData nandContext; // ꎞҔp (ɓnȂSHARED̂ǂ̃AhXɂ) + +#ifndef SDK_FINALROM +static u8 step = 0x80; +#endif + +/* + Profile +*/ +#ifndef SDK_FINALROM +#define PRFILE_MAX 128 +u32 profile[PRFILE_MAX]; +u32 pf_cnt = 0; +#endif + +/*************************************************************** + PreInit + + FromBoot̑Ή܂Ƃ߂違C̏ + OS_InitOȂ̂Œ (ARM9ɂ郁CŏȂ悤ɒ) +***************************************************************/ +static void PreInit(void) +{ + + /* + FromBrom֘A + */ + + /* ͂ǂցH */ + + // NANDp[^̑Ҕ + nandContext = OSi_GetFromBromAddr()->SDNandContext; + + MIi_CpuClearFast( 0, (void*)OSi_GetFromBromAddr(), sizeof(OSFromBromBuf) ); +} + +/*************************************************************** + EraseAll + + sI܂ + 낢Ă + DS[hɂďÎ悢H +***************************************************************/ +static void EraseAll(void) +{ +#ifdef SDK_FINALROM + // TODO +#endif +} + +void TwlSpMain( void ) +{ + // OS_InitDebugLED and OS_SetDebugLED are able to call after OS_Init +#ifndef SDK_FINALROM + I2Ci_WriteRegister(I2C_SLAVE_DEBUG_LED, 0x03, 0x00); + I2Ci_WriteRegister(I2C_SLAVE_DEBUG_LED, 0x01, ++step); +#endif + + PreInit(); + +#ifndef SDK_FINALROM + I2Ci_WriteRegister(I2C_SLAVE_DEBUG_LED, 0x01, ++step); + + // 0: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + OS_InitFIRM(); + +#ifndef SDK_FINALROM + // 1: after PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + OS_SetDebugLED(++step); + + PM_InitFIRM(); + +#ifndef SDK_FINALROM + // 2: after PM + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + OS_SetDebugLED(++step); + + /* FATFSCupɃJgq[vɐݒ */ + { + { + OSHeapHandle hh; + u8 *lo = (u8*)fatfsHeap; + u8 *hi = (u8*)fatfsHeap + FATFS_HEAP_SIZE; + lo = OS_InitAlloc(OS_ARENA_MAIN_SUBPRIV, lo, hi, 1); + OS_SetArenaLo(OS_ARENA_MAIN_SUBPRIV, lo); + hh = OS_CreateHeap(OS_ARENA_MAIN_SUBPRIV, OS_GetSubPrivArenaLo(), hi); + OS_SetCurrentHeap(OS_ARENA_MAIN_SUBPRIV, hh); + } + } + + OS_SetDebugLED(++step); + + if ( FATFS_InitFIRM( &nandContext ) ) + { +#ifndef SDK_FINALROM + // 3: after FATFS + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + + if ( FATFS_MountDriveFIRM( DRIVE_NO, BOOT_DEVICE, PARTITION_NO ) ) + { + BOOL result; +#ifndef SDK_FINALROM + // 4: after Mount + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + + result = FATFS_OpenRecentMenu( DRIVE_NO ); + + if ( result ) + { +#ifndef SDK_FINALROM + // 5: after Open + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + + if ( FATFS_LoadHeader() && FATFS_LoadStatic() ) + { +#ifndef SDK_FINALROM + // 127: before Boot + pf_cnt = PRFILE_MAX-1; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + + FATFS_Boot(); + } + } + } + } + + OS_SetDebugLED( (u8)(0xF0 | step)); + + EraseAll(); + + // failed + while (1) + { + PXI_NotifyID( FIRM_PXI_ID_NULL ); + } +} + diff --git a/build/nandfirm/menu-launcher/ARM9/Makefile b/build/nandfirm/menu-launcher/ARM9/Makefile new file mode 100644 index 0000000..c426b86 --- /dev/null +++ b/build/nandfirm/menu-launcher/ARM9/Makefile @@ -0,0 +1,50 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - nandfirm - menu-launcher +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +FIRM_TARGET = FIRM + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = menu_launcher9.tef + +SRCS = main.c + +CRT0_O = crt0_firm.o + +#LCFILE_TEMPLATE = $(FIRM_SPECDIR)/$(FIRM_PROC)-$(FIRM_PLATFORM)-PARTNER.lcf.template + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/menu-launcher/ARM9/main.c b/build/nandfirm/menu-launcher/ARM9/main.c new file mode 100644 index 0000000..a208eab --- /dev/null +++ b/build/nandfirm/menu-launcher/ARM9/main.c @@ -0,0 +1,134 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - nandfirm - menu-launcher + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include + +/* ͂ǂցH */ +#define RSA_KEY_ADDR OSi_GetFromBromAddr()->rsa_pubkey[7] + +#define RSA_HEAP_SIZE (4*1024) // RSApq[vTCY (TCYKv) + +static u8 acHeap[RSA_HEAP_SIZE] __attribute__ ((aligned (32))); +static SVCSignHeapContext acPool; + +/* + PROFILE_ENABLE `Ƃx̃ptH[}X`FbNł܂B + p邽߂ɂ́Amain.cǂɁAu32 profile[256]; u32 pf_cnt = 0; + `Kv܂B +*/ +#define PROFILE_ENABLE + +#ifdef SDK_FINALROM // FINALROMŖ +#undef PROFILE_ENABLE +#endif + +#ifdef PROFILE_ENABLE +#define PRFILE_MAX 128 +u32 profile[PRFILE_MAX]; +u32 pf_cnt = 0; +#endif + +/*************************************************************** + PreInit + + FromBoot̑Ή܂Ƃ߂違C̏ + OS_InitOȂ̂Œ +***************************************************************/ +static void PreInit(void) +{ + /* + C֘A + */ + + // SHARED̈NA (IS-TWL-DEBUGGER̍XV҂) +#ifdef SDK_FINALROM + MIi_CpuClearFast( 0, (void*)HW_MAIN_MEM_SHARED, HW_MAIN_MEM_SHARED_END-HW_MAIN_MEM_SHARED ); +#endif + + /* + FromBrom֘A + */ + + /* ͂ǂցH */ + + MIi_CpuClearFast( 0, (void*)OSi_GetFromBromAddr(), sizeof(OSFromBromBuf) ); +} + +/*************************************************************** + CheckHeader + + wb_VXej[ƂĖȂ`FbN + 擪32B͌ŒlƎv (}X^[o[W͈Ⴄ) +***************************************************************/ +static BOOL CheckHeader(void) +{ + // TODO + return TRUE; +} + +/*************************************************************** + EraseAll + + sI܂ + 낢Ă + DS[hɂďÎ悢H +***************************************************************/ +static void EraseAll(void) +{ +#ifdef SDK_FINALROM + // TODO +#endif +} + +void TwlMain( void ) +{ + PreInit(); + +#ifdef PROFILE_ENABLE + // 0: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + OS_InitFIRM(); +#ifdef PROFILE_ENABLE + OS_InitTick(); + // 1: after PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + SVC_InitSignHeap( &acPool, acHeap, sizeof(acHeap) ); + + // load menu + if ( MI_LoadHeader( &acPool, RSA_KEY_ADDR ) && CheckHeader() && MI_LoadStatic() ) + { +#ifdef PROFILE_ENABLE + // 127: before Boot + pf_cnt = PRFILE_MAX-1; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + MI_Boot(); + } + + EraseAll(); + + // failed + while (1) + { + PXI_NotifyID( FIRM_PXI_ID_NULL ); + } +} + diff --git a/build/nandfirm/menu-launcher/Makefile b/build/nandfirm/menu-launcher/Makefile new file mode 100644 index 0000000..b4674eb --- /dev/null +++ b/build/nandfirm/menu-launcher/Makefile @@ -0,0 +1,59 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - nandfirm - menu-launcher +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + + +FIRM_TARGET = FIRM + +# if you have valid keys, set environment value like below +#export TWL_KEYSDIR='$(FIRM_ROOT)/../twl_firmware/bootrom/build/keys' + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + ARM7 \ + ARM9 \ + wram_regs \ + +TARGET_FIRM_BIN = menu_launcher.nand menu_launcher.srl +BINDIR = . +MAKEFIRM_ARM9 = ARM9/bin/ARM9-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/menu_launcher9.tef +MAKEFIRM_ARM7 = ARM7/bin/ARM7-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/menu_launcher7.tef +MAKEFIRM_RSA_PRVKEY = $(TWL_KEYSDIR)/rsa/private_nand.der +LDEPENDS_BIN += wram_regs/wram_regs.rbin + +MAKEROM_ARM7_BASE = $(basename $(MAKEFIRM_ARM7)) +MAKEROM_FLAGS += -F + +NITRO_MAKEROM = TRUE +MAKEFIRM_FLAGS += -p +FIRM_SPEC = nandfirm.nandsf + +LDIRT_CLEAN += $(TARGETS) \ + $(basename $(firstword $(TARGETS))).tlf \ + rsa_public.sbin \ + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGET_BIN) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/nandfirm/menu-launcher/nandfirm.nandsf b/build/nandfirm/menu-launcher/nandfirm.nandsf new file mode 100644 index 0000000..84c9ff2 --- /dev/null +++ b/build/nandfirm/menu-launcher/nandfirm.nandsf @@ -0,0 +1,24 @@ +#NANDSF --- Nandfirm Spec File + +VERSION : GENERATE + +RSA_KEY : $(MAKEFIRM_RSA_PRVKEY) +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ./wram_regs/wram_regs.rbin + +MIRROR_OFS: 0x100000 + +DECOMP_PROC : ARM9 # ARM9 or ARM7 + +ARM9_COMP : FALSE # TRUE or FALSE, should be before ARM9_SBIN +ARM9_SBIN : $(MAKEFIRM_ARM9).FLX.TWL.sbin +ARM9_ELF : $(MAKEFIRM_ARM9).tef + +ARM7_COMP : FALSE # TRUE or FALSE, should be before ARM7_SBIN +ARM7_SBIN : $(MAKEFIRM_ARM7).FLX.TWL.sbin +ARM7_ELF : $(MAKEFIRM_ARM7).tef + +ARM9_X2 : TRUE # TRUE or FALSE + +NCD_ROMOFS : 0x07fe00 diff --git a/build/nandfirm/menu-launcher/wram_regs/Makefile b/build/nandfirm/menu-launcher/wram_regs/Makefile new file mode 100644 index 0000000..cb6c305 --- /dev/null +++ b/build/nandfirm/menu-launcher/wram_regs/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - norfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = wram_regs.rbin + +SRCS = \ + wram_regs.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_DIR = . +INSTALL_TARGETS = $(BINDIR)/$(TARGET_BIN) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/menu-launcher/wram_regs/wram_regs.c b/build/nandfirm/menu-launcher/wram_regs/wram_regs.c new file mode 100644 index 0000000..bafe67b --- /dev/null +++ b/build/nandfirm/menu-launcher/wram_regs/wram_regs.c @@ -0,0 +1,91 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - nandfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +MIHeader_WramRegs wram_regs_init = +{ + // ARM9 + { + REG_MI_MBK_A0_FIELD( 1, MI_WRAM_A_OFFSET_0KB , MI_WRAM_ARM9 ), + REG_MI_MBK_A1_FIELD( 1, MI_WRAM_A_OFFSET_64KB , MI_WRAM_ARM9 ), + REG_MI_MBK_A2_FIELD( 1, MI_WRAM_A_OFFSET_128KB, MI_WRAM_ARM9 ), + REG_MI_MBK_A3_FIELD( 1, MI_WRAM_A_OFFSET_192KB, MI_WRAM_ARM9 ), + }, + { + REG_MI_MBK_B0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_C0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_C5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_C6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_C7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, HW_WRAM_AREA_HALF ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00080000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00040000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, MI_WRAM_MAP_NULL ) + ), + + // ARM7 + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00080000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00040000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, HW_WRAM_AREA_HALF ) + ), + + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + 3, + + // VRAM-C + 7, + // VRAM-D + 7, +}; + diff --git a/build/nandfirm/nandfirm-print/Makefile b/build/nandfirm/nandfirm-print/Makefile new file mode 100644 index 0000000..b92d2c1 --- /dev/null +++ b/build/nandfirm/nandfirm-print/Makefile @@ -0,0 +1,50 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - build +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + + +FIRM_TARGET = FIRM + + +#---------------------------------------------------------------------------- + +SUBDIRS = ../../norfirm/norfirm-print + +TARGET_FIRM_BIN = nandfirm_print.nand +BINDIR = . +MAKEFIRM_ARM9 = ../../norfirm/norfirm-print/ARM9/bin/ARM9-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/twl_norfirm9_print.tef +MAKEFIRM_ARM7 = ../../norfirm/norfirm-print/ARM7/bin/ARM7-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/twl_norfirm7_print.tef +MAKEFIRM_RSA_PRVKEY = $(TWL_KEYSDIR)/rsa/private_nand.der +LDEPENDS_BIN += ../../norfirm/norfirm-print/wram_regs/wram_regs.rbin + +NITRO_MAKEROM = TRUE +MAKEFIRM_FLAGS += -p +FIRM_SPEC = nandfirm-BB.nandsf + +LDIRT_CLEAN += $(BINDIR)/$(TARGET_BIN) \ + rsa_public.sbin \ + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGET_BIN) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/nandfirm-print/nandfirm-BB.nandsf b/build/nandfirm/nandfirm-print/nandfirm-BB.nandsf new file mode 100644 index 0000000..71e6491 --- /dev/null +++ b/build/nandfirm/nandfirm-print/nandfirm-BB.nandsf @@ -0,0 +1,24 @@ +#NANDSF --- Nandfirm Spec File + +VERSION : GENERATE + +RSA_KEY : $(MAKEFIRM_RSA_PRVKEY) +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ../../norfirm/norfirm-print/wram_regs/wram_regs.rbin + +MIRROR_OFS: 0x100000 + +DECOMP_PROC : ARM9 # ARM9 or ARM7 + +ARM9_COMP : FALSE # TRUE or FALSE, should be before ARM9_SBIN +ARM9_SBIN : $(MAKEFIRM_ARM9).FLX.TWL.sbin +ARM9_ELF : $(MAKEFIRM_ARM9).tef + +ARM7_COMP : FALSE # TRUE or FALSE, should be before ARM7_SBIN +ARM7_SBIN : $(MAKEFIRM_ARM7).FLX.TWL.sbin +ARM7_ELF : $(MAKEFIRM_ARM7).tef + +ARM9_X2 : TRUE # TRUE or FALSE + +NCD_ROMOFS : 0x07fe00 diff --git a/build/nandfirm/sdmc-launcher/ARM7/Makefile b/build/nandfirm/sdmc-launcher/ARM7/Makefile new file mode 100644 index 0000000..8a02e2d --- /dev/null +++ b/build/nandfirm/sdmc-launcher/ARM7/Makefile @@ -0,0 +1,51 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - nandfirm - sdmc-launcher +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +FIRM_PROC = ARM7 +FIRM_TARGET = FIRM + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = sdmc_launcher7.tef + +SRCS = main.c + +CRT0_O = crt0_firm.o + +#LCFILE_TEMPLATE = $(FIRM_SPECDIR)/$(FIRM_PROC)-$(FIRM_PLATFORM)-PARTNER.lcf.template + +#SRCDIR = # using default +#LCFILE = # using default + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +LLIBRARIES = libaes_sp$(TWL_LIBSUFFIX).a + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/sdmc-launcher/ARM7/main.c b/build/nandfirm/sdmc-launcher/ARM7/main.c new file mode 100644 index 0000000..110f81a --- /dev/null +++ b/build/nandfirm/sdmc-launcher/ARM7/main.c @@ -0,0 +1,222 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - nandfirm - sdmc-launcher + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +#define FATFS_HEAP_SIZE (64*1024) // FATFSpq[v (TCYKv) + +#define BOOT_DEVICE FATFS_MEDIA_TYPE_SD +#define PARTITION_NO 0 // 0Œ +#define MENU_FILE (char*)L"A:\\menu.srl" // Ώۃt@C(DRIVE_LETTERƍ킹邱) +#define MENU_FILE_A (char*)L"A:\\menu_a.srl" // Ώۃt@C(DRIVE_LETTERƍ킹邱) +#define MENU_FILE_B (char*)L"A:\\menu_b.srl" // Ώۃt@C(DRIVE_LETTERƍ킹邱) +#define MENU_FILE_L (char*)L"A:\\menu_l.srl" // Ώۃt@C(DRIVE_LETTERƍ킹邱) +#define MENU_FILE_R (char*)L"A:\\menu_r.srl" // Ώۃt@C(DRIVE_LETTERƍ킹邱) + +#define DRIVE_LETTER 'A' // }EghCu +#define DRIVE_NO (DRIVE_LETTER - 'A') // }EghCuԍ + +static u8 fatfsHeap[FATFS_HEAP_SIZE] __attribute__ ((aligned (32))); + +static SDPortContextData nandContext; // ꎞҔp (ɓnȂSHARED̂ǂ̃AhXɂ) + +#ifndef SDK_FINALROM +static u8 step = 0x80; +#endif + +/* + Profile +*/ +#ifndef SDK_FINALROM +#define PROFILE_MAX 0x100 +u32 profile[PROFILE_MAX]; +u32 pf_cnt = 0; +#endif + +/*************************************************************** + PreInit + + FromBoot̑Ή܂Ƃ߂違C̏ + OS_InitOȂ̂Œ (ARM9ɂ郁CŏȂ悤ɒ) +***************************************************************/ +static void PreInit(void) +{ + + /* + FromBrom֘A + */ + + // NANDp[^̑Ҕ + nandContext = OSi_GetFromBromAddr()->SDNandContext; + + MIi_CpuClearFast( 0, (void*)OSi_GetFromBromAddr(), sizeof(OSFromBromBuf) ); +} + +/*************************************************************** + EraseAll + + sI܂ + 낢Ă + DS[hɂďÎ悢H +***************************************************************/ +static void EraseAll(void) +{ +#ifdef SDK_FINALROM + // TODO +#endif +} + +void TwlSpMain( void ) +{ + // OS_InitDebugLED and OS_SetDebugLED are able to call after OS_Init +#ifndef SDK_FINALROM + I2Ci_WriteRegister(I2C_SLAVE_DEBUG_LED, 0x03, 0x00); + I2Ci_WriteRegister(I2C_SLAVE_DEBUG_LED, 0x01, ++step); +#endif + + PreInit(); + +#ifndef SDK_FINALROM + I2Ci_WriteRegister(I2C_SLAVE_DEBUG_LED, 0x01, ++step); + + // 0: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSecondsBROM(OS_GetTick()); +#endif + + OS_InitFIRM(); + OS_EnableIrq(); // PMOS_InitTick()gĂ̂ (łgĂH) + +#ifndef SDK_FINALROM + //OS_EnableIrq(); + // 1: after PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + OS_SetDebugLED(++step); + + PM_InitFIRM(); + PM_BackLightOn( FALSE ); + +#ifndef SDK_FINALROM + // 2: after PM + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + OS_SetDebugLED(++step); + + /* FATFSCupɃJgq[vݒ */ + /* WRAMfatfsHeapCq[vƂēo^Ă */ + { + OSHeapHandle hh; + u8 *lo = (u8*)fatfsHeap; + u8 *hi = (u8*)fatfsHeap + FATFS_HEAP_SIZE; + lo = OS_InitAlloc(OS_ARENA_MAIN_SUBPRIV, lo, hi, 1); + OS_SetArenaLo(OS_ARENA_MAIN_SUBPRIV, lo); + hh = OS_CreateHeap(OS_ARENA_MAIN_SUBPRIV, OS_GetSubPrivArenaLo(), hi); + OS_SetCurrentHeap(OS_ARENA_MAIN_SUBPRIV, hh); + } + + OS_SetDebugLED(++step); + + if ( FATFS_InitFIRM( &nandContext ) ) + { +#ifndef SDK_FINALROM + // 3: after FATFS + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + PM_BackLightOn( FALSE ); + + if ( FATFS_MountDriveFIRM( DRIVE_NO, BOOT_DEVICE, PARTITION_NO ) ) + { + BOOL result; +#ifndef SDK_FINALROM + // 4: after Mount + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + PM_BackLightOn( FALSE ); + + switch ( PAD_Read() & PAD_KEYPORT_MASK ) + { + case 0: + result = FATFS_OpenSpecifiedSrl( MENU_FILE ); + break; + case PAD_BUTTON_A: + result = FATFS_OpenSpecifiedSrl( MENU_FILE_A ); + break; + case PAD_BUTTON_B: + result = FATFS_OpenSpecifiedSrl( MENU_FILE_B ); + break; + case PAD_BUTTON_L: + result = FATFS_OpenSpecifiedSrl( MENU_FILE_L ); + break; + case PAD_BUTTON_R: + result = FATFS_OpenSpecifiedSrl( MENU_FILE_R ); + break; + default: + OS_SetDebugLED( (u8)(PAD_Read() & PAD_KEYPORT_MASK) ); + OS_Terminate(); + break; + } + + if ( result ) + { +#ifndef SDK_FINALROM + // 5: after Open + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + OS_SetDebugLED(++step); + PM_BackLightOn( FALSE ); + + if ( FATFS_LoadHeader() && FATFS_LoadStatic() ) + { +#ifndef SDK_FINALROM + // 127: before Boot + pf_cnt = PROFILE_MAX-1; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + { + int i; + PXI_RecvID(); + OS_TPrintf("\n[ARM7] Begin\n"); + for (i = 0; i < PROFILE_MAX; i++) + { + OS_TPrintf("0x%08X\n", profile[i]); + } + OS_TPrintf("\n[ARM7] End\n"); + } +#endif + OS_SetDebugLED(++step); + PM_BackLightOn( TRUE ); // last chance + + FATFS_Boot(); + } + } + } + } + + OS_SetDebugLED( (u8)(0xF0 | step)); + + EraseAll(); + + // failed + while (1) + { + PXI_NotifyID( FIRM_PXI_ID_NULL ); + } +} + diff --git a/build/nandfirm/sdmc-launcher/ARM9/Makefile b/build/nandfirm/sdmc-launcher/ARM9/Makefile new file mode 100644 index 0000000..8e9e540 --- /dev/null +++ b/build/nandfirm/sdmc-launcher/ARM9/Makefile @@ -0,0 +1,50 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - nandfirm - sdmc-launcher +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +FIRM_TARGET = FIRM + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = sdmc_launcher9.tef + +SRCS = main.c + +CRT0_O = crt0_firm.o + +#LCFILE_TEMPLATE = $(FIRM_SPECDIR)/$(FIRM_PROC)-$(FIRM_PLATFORM)-PARTNER.lcf.template + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/sdmc-launcher/ARM9/main.c b/build/nandfirm/sdmc-launcher/ARM9/main.c new file mode 100644 index 0000000..a6d3631 --- /dev/null +++ b/build/nandfirm/sdmc-launcher/ARM9/main.c @@ -0,0 +1,173 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - nandfirm - sdmc-launcher + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include + +#define RSA_KEY_ADDR rsa_key +static const u8 rsa_key[128] = +{ + 0xdf, 0x56, 0x30, + 0xc9, 0xae, 0x05, 0x55, 0xe8, 0xdf, 0xbe, 0xe6, 0xb9, 0x30, 0xb9, 0x76, 0x93, 0xb4, 0xc2, 0x20, + 0xe7, 0xae, 0x4c, 0x3e, 0xc3, 0xed, 0x27, 0xcf, 0x5d, 0x4f, 0xb5, 0x7d, 0xde, 0x38, 0xbc, 0xfe, + 0x25, 0x32, 0xd8, 0x23, 0x98, 0x52, 0xb5, 0xda, 0xf7, 0x39, 0xdc, 0xb3, 0x0a, 0x94, 0x7a, 0x2b, + 0x79, 0xe6, 0xe0, 0x4c, 0xbc, 0x21, 0xbd, 0x59, 0xb2, 0xc7, 0xf1, 0xc0, 0xf1, 0xfb, 0x29, 0x75, + 0xa1, 0x21, 0x93, 0x01, 0x29, 0x1c, 0x9a, 0xe1, 0x2d, 0x55, 0xfc, 0x7b, 0xb8, 0xcb, 0x07, 0x33, + 0xc5, 0x91, 0x0d, 0xc8, 0x45, 0x59, 0xef, 0xbe, 0x58, 0xc7, 0xc1, 0x1d, 0xd5, 0xf2, 0xcf, 0x1f, + 0xe0, 0x6d, 0x21, 0x00, 0xcd, 0x42, 0xd8, 0x84, 0x85, 0xe3, 0xb2, 0x02, 0x1a, 0xa5, 0x89, 0x02, + 0xa1, 0x96, 0xc6, 0xf7, 0x61, 0x68, 0x66, 0xe6, 0x65, 0x12, 0xb7, 0xf1, 0x49 +}; + +#define RSA_HEAP_SIZE (4*1024) // RSApq[vTCY (TCYKv) + +static u8 acHeap[RSA_HEAP_SIZE] __attribute__ ((aligned (32))); +static SVCSignHeapContext acPool; + +/* + Profile +*/ +#ifndef SDK_FINALROM +#define PROFILE_MAX 0x100 +u32 profile[PROFILE_MAX]; +u32 pf_cnt = 0; +#endif + +/*************************************************************** + PreInit + + FromBoot̑Ή܂Ƃ߂違C̏ + OS_InitOȂ̂Œ + MI_LoadHeaderOɂȂ(100msec)Ԃ̂ŁA”\Ȃ + OS_Initɂ낢돈I +***************************************************************/ +static void PreInit(void) +{ + /* + C֘A + */ + + // SHARED̈NA (IS-TWL-DEBUGGER̍XV҂) +#ifdef SDK_FINALROM + //MIi_CpuClearFast( 0, (void*)HW_MAIN_MEM_SHARED, HW_MAIN_MEM_SHARED_END-HW_MAIN_MEM_SHARED ); +#endif + // SHARED̈NA (OK?) + MIi_CpuClearFast( 0, (void*)HW_PXI_SIGNAL_PARAM_ARM9, HW_MAIN_MEM_SHARED_END-HW_PXI_SIGNAL_PARAM_ARM9); + + /* + FromBrom֘A + */ + + MIi_CpuClearFast( 0, (void*)OSi_GetFromBromAddr(), sizeof(OSFromBromBuf) ); +} + +/*************************************************************** + PostInit + + MI_LoadHeaderOɂȂ(100msec)Ԃ̂ŁA”\Ȃ + OS_Initɂ낢돈I + C̏ +***************************************************************/ +static void PostInit(void) +{ + /* + C֘A (ARM9p̗̈SNA) + */ + + MIi_CpuClearFast( 0, (void*)HW_DELIVER_ARG_BUF_END, HW_TWL_MAIN_MEM_MAIN_SIZE-HW_DELIVER_ARG_BUF_SIZE ); + DC_FlushAll(); +} + +/*************************************************************** + CheckHeader + + wb_VXej[ƂĖȂ`FbN + 擪32B͌ŒlƎv (}X^[o[W͈Ⴄ) +***************************************************************/ +static BOOL CheckHeader(void) +{ + return TRUE; +} + +/*************************************************************** + EraseAll + + sI܂ + 낢Ă + DS[hɂďÎ悢H +***************************************************************/ +static void EraseAll(void) +{ +#ifdef SDK_FINALROM + // TODO +#endif +} + +void TwlMain( void ) +{ + PreInit(); + +#ifndef SDK_FINALROM + // 0: before PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSecondsBROM(OS_GetTick()); +#endif + + OS_InitFIRM(); +#ifndef SDK_FINALROM + OS_EnableIrq(); + OS_InitTick(); + // 1: after PXI + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + SVC_InitSignHeap( &acPool, acHeap, sizeof(acHeap) ); + + PostInit(); + +#ifndef SDK_FINALROM + // 2: after PostInit + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); +#endif + + // load menu + if ( MI_LoadHeader( &acPool, RSA_KEY_ADDR ) && CheckHeader() && MI_LoadStatic() ) + { +#ifndef SDK_FINALROM + // 127: before Boot + pf_cnt = PROFILE_MAX-1; + profile[pf_cnt++] = (u32)OS_TicksToMicroSeconds(OS_GetTick()); + { + int i; + OS_TPrintf("\n[ARM9] Begin\n"); + for (i = 0; i < PROFILE_MAX; i++) + { + OS_TPrintf("0x%08X\n", profile[i]); + } + OS_TPrintf("\n[ARM9] End\n"); + PXI_NotifyID( FIRM_PXI_ID_NULL ); + } +#endif + + MI_Boot(); + } + + EraseAll(); + + // failed + while (1) + { + PXI_NotifyID( FIRM_PXI_ID_NULL ); + } +} + diff --git a/build/nandfirm/sdmc-launcher/Makefile b/build/nandfirm/sdmc-launcher/Makefile new file mode 100644 index 0000000..565f8a1 --- /dev/null +++ b/build/nandfirm/sdmc-launcher/Makefile @@ -0,0 +1,59 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - nandfirm - sdmc-launcher +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + + +FIRM_TARGET = FIRM + +# if you have valid keys, set environment value like below +#export TWL_KEYSDIR='$(FIRM_ROOT)/../twl_firmware/bootrom/build/keys' + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + ARM7 \ + ARM9 \ + wram_regs \ + +TARGET_FIRM_BIN = sdmc_launcher.nand sdmc_launcher.srl +BINDIR = . +MAKEFIRM_ARM9 = ARM9/bin/ARM9-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/sdmc_launcher9.tef +MAKEFIRM_ARM7 = ARM7/bin/ARM7-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/sdmc_launcher7.tef +MAKEFIRM_RSA_PRVKEY = $(TWL_KEYSDIR)/rsa/private_nand.der +LDEPENDS_BIN += wram_regs/wram_regs.rbin + +MAKEROM_ARM7_BASE = $(basename $(MAKEFIRM_ARM7)) +MAKEROM_FLAGS += -F + +NITRO_MAKEROM = TRUE +MAKEFIRM_FLAGS += -p +FIRM_SPEC = nandfirm.nandsf + +LDIRT_CLEAN += $(TARGETS) \ + $(basename $(firstword $(TARGETS))).tlf \ + rsa_public.sbin \ + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGET_BIN) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/nandfirm/sdmc-launcher/nandfirm.nandsf b/build/nandfirm/sdmc-launcher/nandfirm.nandsf new file mode 100644 index 0000000..84c9ff2 --- /dev/null +++ b/build/nandfirm/sdmc-launcher/nandfirm.nandsf @@ -0,0 +1,24 @@ +#NANDSF --- Nandfirm Spec File + +VERSION : GENERATE + +RSA_KEY : $(MAKEFIRM_RSA_PRVKEY) +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ./wram_regs/wram_regs.rbin + +MIRROR_OFS: 0x100000 + +DECOMP_PROC : ARM9 # ARM9 or ARM7 + +ARM9_COMP : FALSE # TRUE or FALSE, should be before ARM9_SBIN +ARM9_SBIN : $(MAKEFIRM_ARM9).FLX.TWL.sbin +ARM9_ELF : $(MAKEFIRM_ARM9).tef + +ARM7_COMP : FALSE # TRUE or FALSE, should be before ARM7_SBIN +ARM7_SBIN : $(MAKEFIRM_ARM7).FLX.TWL.sbin +ARM7_ELF : $(MAKEFIRM_ARM7).tef + +ARM9_X2 : TRUE # TRUE or FALSE + +NCD_ROMOFS : 0x07fe00 diff --git a/build/nandfirm/sdmc-launcher/wram_regs/Makefile b/build/nandfirm/sdmc-launcher/wram_regs/Makefile new file mode 100644 index 0000000..cb6c305 --- /dev/null +++ b/build/nandfirm/sdmc-launcher/wram_regs/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - norfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = wram_regs.rbin + +SRCS = \ + wram_regs.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_DIR = . +INSTALL_TARGETS = $(BINDIR)/$(TARGET_BIN) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/nandfirm/sdmc-launcher/wram_regs/wram_regs.c b/build/nandfirm/sdmc-launcher/wram_regs/wram_regs.c new file mode 100644 index 0000000..bafe67b --- /dev/null +++ b/build/nandfirm/sdmc-launcher/wram_regs/wram_regs.c @@ -0,0 +1,91 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - nandfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +MIHeader_WramRegs wram_regs_init = +{ + // ARM9 + { + REG_MI_MBK_A0_FIELD( 1, MI_WRAM_A_OFFSET_0KB , MI_WRAM_ARM9 ), + REG_MI_MBK_A1_FIELD( 1, MI_WRAM_A_OFFSET_64KB , MI_WRAM_ARM9 ), + REG_MI_MBK_A2_FIELD( 1, MI_WRAM_A_OFFSET_128KB, MI_WRAM_ARM9 ), + REG_MI_MBK_A3_FIELD( 1, MI_WRAM_A_OFFSET_192KB, MI_WRAM_ARM9 ), + }, + { + REG_MI_MBK_B0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_C0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_C4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_C5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_C6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_C7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, HW_WRAM_AREA_HALF ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00080000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00040000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, MI_WRAM_MAP_NULL ) + ), + + // ARM7 + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00080000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00040000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_256KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, HW_WRAM_AREA_HALF ) + ), + + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + 3, + + // VRAM-C + 7, + // VRAM-D + 7, +}; + diff --git a/build/norfirm/.DS_Store b/build/norfirm/.DS_Store new file mode 100644 index 0000000..599a467 Binary files /dev/null and b/build/norfirm/.DS_Store differ diff --git a/build/norfirm/Makefile b/build/norfirm/Makefile new file mode 100644 index 0000000..1501817 --- /dev/null +++ b/build/norfirm/Makefile @@ -0,0 +1,34 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - firmware +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + norfirm-print \ + norfirm-empty \ + + +#---------------------------------------------------------------------------- + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/norfirm/norfirm-empty/Makefile b/build/norfirm/norfirm-empty/Makefile new file mode 100644 index 0000000..32cfdec --- /dev/null +++ b/build/norfirm/norfirm-empty/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - build +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + + +FIRM_TARGET = FIRM + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + +TARGET_FIRM_BIN = norfirm_empty.nor +BINDIR = . +MAKEFIRM_RSA_PRVKEY = $(TWL_KEYSDIR)/rsa/private_nor.der + +MAKEFIRM_ARM9 = +MAKEFIRM_ARM7 = + +NITRO_MAKEROM = TRUE +MAKEFIRM_FLAGS += -p +FIRM_SPEC = norfirm-BB.norsf + +LDIRT_CLEAN += $(BINDIR)/$(TARGET_BIN) \ + rsa_public.sbin \ + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGET_BIN) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#===== End of Makefile ===== diff --git a/build/norfirm/norfirm-empty/norfirm-BB.norsf b/build/norfirm/norfirm-empty/norfirm-BB.norsf new file mode 100644 index 0000000..319e685 --- /dev/null +++ b/build/norfirm/norfirm-empty/norfirm-BB.norsf @@ -0,0 +1,8 @@ +#NORSF --- Norfirm Spec File + +VERSION : GENERATE + +BOOT_NAND : TRUE # TRUE or FALSE + +NCD_ROMOFS : 0x07fe00 + diff --git a/build/norfirm/norfirm-print/ARM7/Makefile b/build/norfirm/norfirm-print/ARM7/Makefile new file mode 100644 index 0000000..d00372e --- /dev/null +++ b/build/norfirm/norfirm-print/ARM7/Makefile @@ -0,0 +1,50 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - norfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +FIRM_PROC = ARM7 +FIRM_TARGET = FIRM + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = twl_norfirm7_print.tef + +CRT0_O = crt0_firm.o + +SRCS = \ + main.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/norfirm/norfirm-print/ARM7/main.c b/build/norfirm/norfirm-print/ARM7/main.c new file mode 100644 index 0000000..13134a0 --- /dev/null +++ b/build/norfirm/norfirm-print/ARM7/main.c @@ -0,0 +1,31 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - norfirm-print + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include + + +void TwlSpMain( void ) +{ + OS_TPrintf( "\nNOR Boot time is %d msec.\n", OS_TicksToMilliSecondsBROM32(OS_GetTick())); + + OS_InitFIRM(); + + OS_TPrintf( "\nARM7 starts.\n" ); + OS_TPrintf( "\nARM7 ends.\n" ); + + OS_Terminate(); +} + diff --git a/build/norfirm/norfirm-print/ARM9/Makefile b/build/norfirm/norfirm-print/ARM9/Makefile new file mode 100644 index 0000000..503c9c1 --- /dev/null +++ b/build/norfirm/norfirm-print/ARM9/Makefile @@ -0,0 +1,49 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - norfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +FIRM_TARGET = FIRM + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = twl_norfirm9_print.tef + +CRT0_O = crt0_firm.o + +SRCS = \ + main.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/norfirm/norfirm-print/ARM9/main.c b/build/norfirm/norfirm-print/ARM9/main.c new file mode 100644 index 0000000..08f1fdb --- /dev/null +++ b/build/norfirm/norfirm-print/ARM9/main.c @@ -0,0 +1,31 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - norfirm-print + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include + + +void TwlMain( void ) +{ + OS_TPrintf( "\nNOR Boot time is %d msec.\n", OS_TicksToMilliSecondsBROM32(OS_GetTick())); + + OS_InitFIRM(); + + OS_TPrintf( "\nARM9 starts.\n" ); + OS_TPrintf( "\nARM9 ends.\n" ); + + OS_Terminate(); +} + diff --git a/build/norfirm/norfirm-print/Makefile b/build/norfirm/norfirm-print/Makefile new file mode 100644 index 0000000..0b6a16a --- /dev/null +++ b/build/norfirm/norfirm-print/Makefile @@ -0,0 +1,60 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - build +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + + +FIRM_TARGET = FIRM + +# if you have no valid key, comment out next line +#TWL_KEYSDIR = $(FIRM_ROOT)/../twl_firmware/bootrom/build/keys + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + ARM7 \ + ARM9 \ + wram_regs \ + +TARGET_FIRM_BIN = norfirm_print.nor norfirm_print.srl +BINDIR = . +MAKEFIRM_ARM9 = ARM9/bin/ARM9-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/twl_norfirm9_print.tef +MAKEFIRM_ARM7 = ARM7/bin/ARM7-$(FIRM_PLATFORM)$(CODEGEN_ARCH)/$(FIRM_BUILD_DIR)/twl_norfirm7_print.tef +MAKEFIRM_RSA_PRVKEY = $(TWL_KEYSDIR)/rsa/private_nor.der +LDEPENDS_BIN += wram_regs/wram_regs.rbin + +MAKEROM_ARM7_BASE = $(basename $(MAKEFIRM_ARM7)) +MAKEROM_FLAGS += -F + +NITRO_MAKEROM = TRUE +MAKEFIRM_FLAGS += -p +FIRM_SPEC = norfirm-BB.norsf + +LDIRT_CLEAN += $(TARGETS) \ + $(basename $(firstword $(TARGETS))).tlf \ + rsa_public.sbin \ + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build: $(TARGET_BIN) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/norfirm/norfirm-print/norfirm-BB.norsf b/build/norfirm/norfirm-print/norfirm-BB.norsf new file mode 100644 index 0000000..a472dc2 --- /dev/null +++ b/build/norfirm/norfirm-print/norfirm-BB.norsf @@ -0,0 +1,25 @@ +#NORSF --- Norfirm Spec File + +VERSION : GENERATE + +BOOT_NAND : TRUE # TRUE or FALSE + +RSA_KEY : $(MAKEFIRM_RSA_PRVKEY) +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ./wram_regs/wram_regs.rbin + +DECOMP_PROC : ARM9 # ARM9 or ARM7 + +ARM9_COMP : TRUE # TRUE or FALSE, should be before ARM9_SBIN +ARM9_SBIN : $(MAKEFIRM_ARM9).FLX.TWL.sbin +ARM9_ELF : $(MAKEFIRM_ARM9).tef + +ARM7_COMP : TRUE # TRUE or FALSE, should be before ARM7_SBIN +ARM7_SBIN : $(MAKEFIRM_ARM7).FLX.TWL.sbin +ARM7_ELF : $(MAKEFIRM_ARM7).tef + +NCD_ROMOFS : 0x07fe00 + +BAUDRATE : 8M # 4M or 8M +ARM9_X2 : TRUE # TRUE or FALSE diff --git a/build/norfirm/norfirm-print/wram_regs/Makefile b/build/norfirm/norfirm-print/wram_regs/Makefile new file mode 100644 index 0000000..f0ecbed --- /dev/null +++ b/build/norfirm/norfirm-print/wram_regs/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - norfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = wram_regs.rbin + +SRCS = \ + wram_regs.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_DIR = . +INSTALL_TARGETS = $(BINDIR)/$(TARGET_BIN) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/norfirm/norfirm-print/wram_regs/wram_regs.c b/build/norfirm/norfirm-print/wram_regs/wram_regs.c new file mode 100644 index 0000000..ea59c65 --- /dev/null +++ b/build/norfirm/norfirm-print/wram_regs/wram_regs.c @@ -0,0 +1,91 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev:$ + $Author:$ + *---------------------------------------------------------------------------*/ +#include +#include + +MIHeader_WramRegs wram_regs_init = +{ + // ARM9 + { + REG_MI_MBK_A0_FIELD( 1, MI_WRAM_A_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A1_FIELD( 1, MI_WRAM_A_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A2_FIELD( 1, MI_WRAM_A_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_A3_FIELD( 1, MI_WRAM_A_OFFSET_192KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_B0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_C0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM9 ), + }, + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, HW_WRAM_AREA_HALF ) + ), + + // ARM7 + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, HW_WRAM_AREA_HALF ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00020000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, MI_WRAM_MAP_NULL ) + ), + + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + 3, + + // VRAM-C + 7, + // VRAM-D + 7, +}; + diff --git a/build/systemMenu_RED/.DS_Store b/build/systemMenu_RED/.DS_Store new file mode 100644 index 0000000..7a69c3a Binary files /dev/null and b/build/systemMenu_RED/.DS_Store differ diff --git a/build/systemMenu_RED/DS_DownloadPlay/ARM9/ARM9-TS.lsf b/build/systemMenu_RED/DS_DownloadPlay/ARM9/ARM9-TS.lsf new file mode 100644 index 0000000..1b0a503 --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/ARM9/ARM9-TS.lsf @@ -0,0 +1,70 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ARM9-BB.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x02800000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) +} + +Overlay bm_mainp +{ + After $(TARGET_NAME) + Object $(OBJDIR)/DS_Setting.o $(OBJDIR)/settingMenu.o $(OBJDIR)/rtcSet.o $(OBJDIR)/langSelect.o \ + $(OBJDIR)/tpCalib.o $(OBJDIR)/ownerInfo.o $(OBJDIR)/AgbLcdSel.o $(OBJDIR)/autoBoot.o \ + $(OBJDIR)/unicode.o $(OBJDIR)/misc.o \ + $(OBJDIR)/DS_DownloadPlay.o \ + $(OBJDIR)/DS_Chat.o +} + +Overlay ipl2_data +{ + After bm_mainp + Object ./font/f12han.o +} + + +Autoload ITCM +{ + Address 0x01ff8000 + Object * (.itcm) + Object $(OBJS_AUTOLOAD) (.text) + Object $(OBJS_AUTOLOAD) (.rodata) +} + +Autoload DTCM +{ + Address $(ADDRESS_DTCM) + Object * (.dtcm) + Object $(OBJS_AUTOLOAD) (.data) + Object $(OBJS_AUTOLOAD) (.sdata) + Object $(OBJS_AUTOLOAD) (.bss) + Object $(OBJS_AUTOLOAD) (.sbss) +} + +Ltdautoload LTDMAIN +{ + # NITRO/TWL L̃I[o[C݂ꍇ́Aɂ̌ɔzuKv܂B + After ipl2_data + Object * (.ltdmain) + Object $(OBJS_LTDAUTOLOAD) + Library $(LLIBS_EX) $(GLIBS_EX) +} diff --git a/build/systemMenu_RED/DS_DownloadPlay/ARM9/Makefile b/build/systemMenu_RED/DS_DownloadPlay/ARM9/Makefile new file mode 100644 index 0000000..bd252c8 --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/ARM9/Makefile @@ -0,0 +1,52 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlSDK - demos - simpleShoot-1 +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev: $ +# $Author: $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- + +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED + +TARGET_BIN = dlplay.srl + +LCFILE_SPEC = ARM9-TS.lsf +ROM_SPEC = main.rsf + +SRCS = main.c mainFunc.c DS_DownloadPlay.c + +LINCLUDES = $(TWLSDK_ROOT)/build/libraries/spi/arm9/include \ + $(TWLSDK_ROOT)/build/libraries/mb/common/include \ + +LLIBRARY_DIRS = +LLIBRARIES = +LDEPENDS_NEF = + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build : $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/DS_DownloadPlay/ARM9/main.rsf b/build/systemMenu_RED/DS_DownloadPlay/ARM9/main.rsf new file mode 100644 index 0000000..511b587 --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/ARM9/main.rsf @@ -0,0 +1,146 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ROM-BB.rsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL ROM SPEC FILE +# + +Arm9 +{ + Static "$(MAKEROM_ARM9:r).FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.FLX.TWL.sbin$(COMPSUFFIX9)" + Elf "$(MAKEROM_ARM9:r).tef" +} + +Arm7 +{ + Static "$(MAKEROM_ARM7_BASE:r).FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.FLX.TWL.sbin$(COMPSUFFIX7)" + Elf "$(MAKEROM_ARM7_BASE:r).tef" +} + +Arm9.Ltd +{ + Static "$(MAKEROM_ARM9:r).LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.LTD.TWL.sbin$(COMPSUFFIX9)" +} + +Arm7.Ltd +{ + Static "$(MAKEROM_ARM7_BASE:r).LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.LTD.TWL.sbin$(COMPSUFFIX7)" +} + +Property +{ + ### + ### Settings for FinalROM + ### + #### BEGIN + # + # TITLE NAME: Your product name within 12bytes + # + #TitleName "YourAppName" + + # + # MAKER CODE: Your company ID# in 2 ascii words + # issued by NINTENDO + # + #MakerCode "00" + + # + # REMASTER VERSION: Mastering version + # + #RomVersion 0 + + # + # ROM SPEED TYPE: [MROM/1TROM/UNDEFINED] + # + RomSpeedType $(MAKEROM_ROMSPEED) + + # + # ROM SIZE: in bit [64M/128M/256M/512M/1G/2G] + # + #RomSize 128M + #RomSize 256M + + # + # ROM PADDING: TRUE if finalrom + # + #RomFootPadding TRUE + + # + # ROM HEADER TEMPLATE: Provided to every product by NINTENDO + # + #RomHeaderTemplate ./etc/rom_header.template.sbin + + # + # BANNER FILE: generated from Banner Spec File + # + BannerFile ../banner/banner.bnr + + ### + ### Setting for TWL + ### + # + # BANNER FILE: + # + BannerTWLFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + # + # Boot allowed Media: [GameCard/NAND/SDCard/DownloadPlay] + # possible to choose one or more. + # + BootMedia GameCard NAND SDCard DownloadPlay + + # + # Certification FILE: + # + Certificate $(TWLSDK_ROOT)/include/twl/specfiles/default_sgn.sbin + + # + # Digest parameters: + # + DigestParam 1024 32 + + # + # WRAM mapping: [MAP_BB_HYB/MAP_BB_LTD/MAP_TS_HYB/MAP_TS_LTD] + # don't have to edit + # + WramMapping $(MAKEROM_WRAM_MAPPING) + + # + # Codec mode: + # don't have to edit + # + CodecMode $(MAKEROM_CODEC_MODE) + + ### + #### END +} + +RomSpec +{ + Offset 0x00000000 + Segment ALL + HostRoot data + Root /data + File NTR_IPL_font_m.NFTR +} diff --git a/build/systemMenu_RED/DS_DownloadPlay/ARM9/src/DS_DownloadPlay.c b/build/systemMenu_RED/DS_DownloadPlay/ARM9/src/DS_DownloadPlay.c new file mode 100644 index 0000000..13d9abb --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/ARM9/src/DS_DownloadPlay.c @@ -0,0 +1,1618 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: DS_DownloadPlay.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +// mb_private.hPRINT_DEBUG"1"ɂĂƁA_E[hɐɃu[głȂȂĂ̂ŁAӁB + +#include +#include // Ƃ̂OK? +#include +#include "mb_child.h" +#include "mb_private.h" + + +#include "misc.h" +#include "DS_Setting.h" +#include "DS_DownloadPlay.h" + +// define data------------------------------------------ +#define PARENT_VIEW_NUM 4 // e@񃊃Xg̈ʕ\ +#define PLIST_X 1 // e@񃊃Xg̕\Xʒu +#define PLIST_Y 4 // e@񃊃Xg̕\Yʒu +#define MB_DMA_NO 2 // }`u[gpDMAԍ +#define PRG_NEXT_SEQ_QUE_NUM 4 // ̃vOV[PXi[L[̐ +#define MY_GGID 0x00000000 // }`u[gpGGID +#define G_INTRO_X 1 // Q[e\Xʒu +#define G_INTRO_Y 4 // Q[e\Yʒu +#define G_MEMBER_X 1 // ʐMo[\Xʒu +#define G_MEMBER_Y 10 // ʐMo[\Yʒu +#define MSG_VIEW_COUNT 75 // bZ[W\VJEg +#define MSG_BLINK_COUNT 12 // bZ[W_ŃJEg + +#define NINLOGO_LOAD_1D_CHAR // NintendoSf[^1D}bsOLN^Ń[hB + + // vOV[PX +typedef enum PrgSeq { + PSEQ_READY = 0, + PSEQ_INIT, + PSEQ_INITIALIZING, + PSEQ_ENDING, + PSEQ_END, + PSEQ_CANCELLED, + PSEQ_DISCONNECTED_BY_PARENT, + PSEQ_SCANNING, + PSEQ_CONNECTING, + PSEQ_CONNECT_SUCCEEDED, + PSEQ_CONNECT_FAILED, + PSEQ_REQ_REFUSED, + PSEQ_MEMBER_FULL, + PSEQ_DOWNLOAD_READY, + PSEQ_DOWNLOADING, + PSEQ_DOWNLOAD_COMPLETED, + PSEQ_DOWNLOAD_FAILED, + PSEQ_BOOT_REQ_WAIT, + PSEQ_BOOT_READY, + PSEQ_BOOT_START, + PSEQ_BOOT_FAILED +}PrgSeq; + +static char *str_prgSeq[] = { + "PSEQ_READY", + "PSEQ_INIT", + "PSEQ_INITIALIZING", + "PSEQ_ENDING", + "PSEQ_END", + "PSEQ_CANCELLED", + "PSEQ_DISCONNECTED_BY_PARENT", + "PSEQ_SCANNING", + "PSEQ_CONNECTING", + "PSEQ_CONNECT_SUCCEEDED", + "PSEQ_CONNECT_FAILED", + "PSEQ_REQ_REFUSED", + "PSEQ_MEMBER_FULL", + "PSEQ_DOWNLOAD_READY", + "PSEQ_DOWNLOADING", + "PSEQ_DOWNLOAD_COMPLETED", + "PSEQ_DOWNLOAD_FAILED", + "PSEQ_BOOT_REQ_WAIT", + "PSEQ_BOOT_READY", + "PSEQ_BOOT_START", + "PSEQ_BOOT_FAILED", +}; + + + // e@񔭌ԃf[^ +typedef struct FindTime { + BOOL find; // ǂ + int vcount; // +}FindTime; + + // bZ[W\Xe[^X +typedef struct MsgViewStatus { + u16 handle; + u16 vcount; + u16 flag; + u16 color; + const u8 *str; + int (*nextProcessp)(void); +}MsgViewStatus; + + // vOV[PXi[pL[ +typedef struct PrgNextSeqQue { + BOOL lock; + u8 pad; + u8 num; + u8 top; + u8 bottom; + PrgSeq seq[ PRG_NEXT_SEQ_QUE_NUM ]; +}PrgNextSeqQue; + + +// extern data------------------------------------------ +extern void MBw_SetMaxScanTime( u16 time ); +extern int MBw_GetScanChannel( void ); +extern void UnCompNintendoLogo( u16 *NintendoLogoDatap, u16 *dstp, u32 *temp ); + +// function's prototype declaration--------------------- + // CV[PX +static void SEQ_DSDL_init( void ); +static int SEQ_DSDL_Connect( void ); +static int SEQ_DSDL_Download( void ); +static BOOL CheckNextSeq_Connect( void ); +static BOOL CheckNextSeq_Download( void ); + // R[obN +static void CallbackChild_MB( u32 status, void *arg ); // }`u[gpR[obN֐ + // \n +static void DispTopScreen( void ); +static void DispScanStatus( void ); +static void DispParentNum( void ); +static void DispParentList( void ); +static void DispGameIntroduction( void ); +static void DispPlayMember( void ); +static void DispParentGameInfo( u32 view_no, u32 listNo, BOOL drawFixedDataFlag ); +static void ClearDispParentGameInfo( u32 view_no, u32 listNo ); +static void DispGameIntroduction_Core( u32 listNo ); +static void DispPlayMember_Core( u32 listNo ); +static void ClearDispGameIntroduction( void ); +static void ClearDispPlayMember( void ); +static void DecimalToString( u8 *dstp, const void *valuep, u8 drawLength, u8 size ); +static void InitParentFindTime( void ); +static void CountParentFindTime( void ); +static BOOL CheckParentFindTime( u32 index ); +static void CountAndDispTotalTime( void ); +static void SetIconOBJ( u32 index ); +static void ClearIconOBJ( u32 index ); +static void SetDispMessage( u16 color, const u8 *str ); +static BOOL DispMessage( void ); +static void SetBlinkMessage( u16 color, const u8 *str ); +static void DispBlinkMessage( void ); + // NintendoS\ +static void InitDispNintendoLogo( void ); +static BOOL DispNintendoLogo( void ); + // ̑ +static void SetMyUserInfo( MBUserInfo *my ); +static BOOL IsScanLock( void ); + // 荞 +static void VBlankIntr_WDL( void ); + // V[PXL[ +static void InitPrgNextSeqQue( void ); +static BOOL SetPrgNextSeqQue( PrgSeq seq ); +static BOOL GetPrgNextSeqQue( PrgSeq *seqp ); +static void LockPrgNextSeqQue( void ); +static void UnlockPrgNextSeqQue( void ); +static BOOL IsEmptyPrgNextSeqQue( void ); + +void SearchPatchAddress( void ); + +// global variable ------------------------------------- + +// static variable ------------------------------------- +static int (*wdProcess)( void ); // ݎs̃vZXւ̃|C^ +static int csrC; // j[̃J[\ʒu +static int csrC_old; // j[̑OJ[\ʒu +static PrgSeq prgSeq; // vOV[PX +static PrgNextSeqQue nextSeq; // ̃vOV[PXi[L[ +static BOOL end_flag; // ItO +static MsgViewStatus msgStat; // bZ[W\Xe[^X +static MBUserInfo myUser; // ̃[U[ +static u16 tgid = 0; +static u16 tp_touch_count = 0; +static u32 gameInfoLostCount = 0; +// e@Xg̕\Ɏgp +static int unrenewalFlag; +static int total_vcount; +static int time_ms; // e@ms +static int time_sec; // e@sec +static u16 msgHandle; // bZ[W\nh +static u16 dispGameInfoFlag; // ɕ\Q[rbgŎB +static u16 dispIntroFlag; // Q[̏ڍ׃f[^`tO +static u16 dispMemberFlag; // Q[̏ڍ׃f[^`tO +static u16 gameName[ MB_GAME_NAME_LENGTH + 1 ]; // e@Q[l[ +static u16 userName[ MB_USER_NAME_LENGTH + 1 ]; // e@[U[l[ +static u16 gameIntroduction[2][ MB_GAME_INTRO_LENGTH / 2 + 1 ]; + // e@Q[e +static u16 playMember[ MB_MEMBER_MAX_NUM ][ MB_USER_NAME_LENGTH + 1]; + // ʐMo[Xg +static u8 parentListNo[ PARENT_VIEW_NUM ][ 4 ] ATTRIBUTE_ALIGN(2); + // e@Xgԍ +static u32 objVramBuff[ (MB_ICON_DATA_SIZE * PARENT_VIEW_NUM + 0x20) / sizeof(u32) ] ATTRIBUTE_ALIGN(32); +static FindTime findTime[ MB_GAME_INFO_RECV_LIST_NUM ]; // e@ԃf[^ +static GXOamAttr oamBakM[ 128 ] ATTRIBUTE_ALIGN(32); // OAM obNAbv + +static const MbBeaconRecvStatus *mbrsp; + +// MBCup[N +static u32 mbwork[ MB_CHILD_SYSTEM_BUF_SIZE / sizeof(u32) ]; + +// NintendoS\ +static int loop_count; +static u32 ninLogoBuff[ 0x700 / sizeof(u32) ]; + +static MBDownloadFileInfo dlfileinfo; +static u8 output_buffer[ AUTH_BUFFER_LEN ]; + +// const data ----------------------------------------- + // \p +static const u8 str_sura[] ATTRIBUTE_ALIGN(2) = "/"; +static const u8 str_period[] ATTRIBUTE_ALIGN(2) = "."; +static const u8 str_sec[] ATTRIBUTE_ALIGN(2) = "sec"; +static const u8 str_disconnected[] ATTRIBUTE_ALIGN(2) = "disconnected by parent."; +static const u8 str_connect_succeeded[] ATTRIBUTE_ALIGN(2) = "connect succeeded."; +static const u8 str_connect_failed[] ATTRIBUTE_ALIGN(2) = "connect failed."; +static const u8 str_req_refused[] ATTRIBUTE_ALIGN(2) = "req refused."; +static const u8 str_member_full[] ATTRIBUTE_ALIGN(2) = "member full."; +static const u8 str_downloading[] ATTRIBUTE_ALIGN(2) = "DOWNLOADING...."; +static const u8 str_download_completed[] ATTRIBUTE_ALIGN(2) = "download completed."; +static const u8 str_download_cancelled[] ATTRIBUTE_ALIGN(2) = "download cancelled."; + + // j[֐p@e@Xg񃊃Xg +static u8 *str_parentListNo[] ATTRIBUTE_ALIGN(2) = { + parentListNo[0], + parentListNo[1], + parentListNo[2], + parentListNo[3], +}; + + // j[֐p@j[\f[^ +static const MenuComponent childModeSel = { + PARENT_VIEW_NUM, // ڐ + PLIST_X, // XʒuiLj + PLIST_Y, // Yʒui@V@@j + 0, // ̍ڂւXʒuL + 4, // ̍ڂւYʒuL + 3, + WHITE, // IF + HIGHLIGHT_Y, // IF + (const u8 **)&str_parentListNo, // j[ڕ񃊃Xg +}; + + +//====================================================== +// C[v +//====================================================== + +// }`u[g̃C[v +int DS_DownloadPlayMain(void) +{ + SEQ_DSDL_init(); + + wdProcess = SEQ_DSDL_Connect; + + OS_TPrintf("MbBeaconRecvStatus:%d\n", sizeof(MbBeaconRecvStatus) ); + + while(1) { + OS_WaitIrq(1, OS_IE_V_BLANK); + ReadKeyPad(); + mf_KEYPAD_rapid(); + + mbrsp = MB_GetBeaconRecvStatus(); + + if( wdProcess != NULL ) { + if(wdProcess()) { + return 0; + } + } + + //// //// + { + static int touch = 0; + TPData tmp1 ATTRIBUTE_ALIGN(32); + TPData tmp2 ATTRIBUTE_ALIGN(32); + + while (TP_RequestRawSampling(&tmp1) != 0) {} + TP_GetCalibratedPoint(&tmp2, &tmp1); + + if (tmp2.touch != touch) + { + tp_touch_count++; + (void)DrawDecimalSJIS( 16, 0, RED, &tp_touch_count, 4, 2 ); + OS_Printf("touch change %d validity = %d\n", tmp2.touch, tmp2.validity); + touch = tmp2.touch; + } + } + //// ܂ //// + +// if (SYSM_IsCardPulledOut()) { // J[ho + if ( 0 ) { + OS_Printf("Card is pulled out.\n"); +#ifdef __DEBUG + OS_Terminate(); +#endif + } + + if (PAD_DetectFold() == TRUE) { // X[v[hւ̑J + SYSM_GoSleepMode(); + } + + OS_PrintServer(); // ARM7̃vgfobO + } + return 0; +} + + +//====================================================== +// }`u[gij +//====================================================== + +// }`u[g̏ +static void SEQ_DSDL_init(void) +{ + GXS_SetVisiblePlane( GX_PLANEMASK_NONE ); + GX_SetVisiblePlane ( GX_PLANEMASK_NONE ); + + (void)OS_SetIrqFunction(OS_IE_V_BLANK, VBlankIntr_WDL); + GXS_SetOBJVRamModeChar(GX_OBJVRAMMODE_CHAR_1D_32K); + + // NITROJ[hROMo^f[^̃NA + MI_CpuClearFast( (void *)HW_ROM_HEADER_BUF, 0x160 ); + + // TuXN[̃NA + MI_CpuClearFast( bgBakS, sizeof(bgBakS) ); + MI_CpuFillFast ( (void *)HW_OAM, 192 , HW_OAM_SIZE ); + MI_CpuFillFast ( (void *)oamBakS, 192 , sizeof(oamBakS) ); // 192ŃtBȂƁAgpOBJ(0, 0)ɃLNo.0őS\Ă܂B + + // CXN[̃NA + MI_CpuClearFast( (void *)HW_BG_VRAM, 0x10000 ); + MI_CpuClearFast( (void *)HW_OBJ_VRAM, 0x8000 ); + MI_CpuClearFast( bgBakM, sizeof(bgBakM) ); + MI_CpuFillFast ( (void *)oamBakM, 192 , sizeof(oamBakM) ); // 192ŃtBȂƁAgpOBJ(0, 0)ɃLNo.0őS\Ă܂B + MI_CpuFillFast ( (void *)HW_OAM, 192 , HW_OAM_SIZE ); + MI_CpuCopyFast ( myPlttData, (void *)HW_BG_PLTT, sizeof(myPlttData) ); // BGpbg Zbg + + ClearAllStringSJIS(); + + (void)DrawStringSJIS ( 1, 0, WHITE, (const u8 *)"NICKNAME="); + (void)DrawStringSJIS ( 1, 2, LIGHTGREEN, (const u8 *)"PARENT NUM ="); +// (void)DrawStringSJIS ( 1, 22, LIGHTGREEN, (const u8 *)"GINFO LOST COUNT ="); + (void)DrawStringSJISEx( 26, 2, CYAN, str_period, PARENT_VIEW_NUM); + (void)DrawStringSJISEx( 29, 2, CYAN, str_sec, PARENT_VIEW_NUM); + + InitPrgNextSeqQue(); + unrenewalFlag = 0; + end_flag = FALSE; + prgSeq = PSEQ_INIT; + msgHandle = 0x8000; + dispGameInfoFlag = 0; + dispIntroFlag = 0; + dispMemberFlag = 0; + csrC_old = 2; // ŏ͂킴ƈႤlɂĂ + csrC = 0; + { + int i; + for( i = 0; i < PARENT_VIEW_NUM; i++ ) { + parentListNo[i][2] = '.'; + parentListNo[i][3] = 0x00; + } + } + SetMyUserInfo( &myUser ); // MBUserInfoNITROݒf[^ǂݏoăZbg + { + // jbNl[\ + u16 nickname[ MB_USER_NAME_LENGTH + 1 ]; + ExUTF16_LEtoSJIS_BE( (u8 *)nickname, (u16 *)myUser.name, myUser.nameLength ); + nickname[ myUser.nameLength ] = 0; + (void)DrawStringSJIS( 8, 0, WHITE, (const u8 *)nickname ); + } + + InitParentFindTime(); // e@ԕϐ̃NA + + while( (SYSM_GetBootFlag() & BFLG_WM_INITIALIZED) == 0 ) {} + + LOADER_Init( NULL ); + + GXS_SetVisiblePlane( GX_PLANEMASK_OBJ | GX_PLANEMASK_BG1 ); + GX_SetVisiblePlane ( GX_PLANEMASK_OBJ | GX_PLANEMASK_BG1 ); +} + + +// TOPXN[ւ̕\ +static void DispTopScreen( void ) +{ + SetTargetScreenSJIS( TOP_SCREEN ); + ClearAllStringSJIS(); + (void)DrawStringSJIS( 1, 0, YELLOW, (const u8 *)"WIRELESS DOWNLOAD"); + (void)DrawStringSJIS( G_INTRO_X, G_INTRO_Y, LIGHTGREEN, (const u8 *)"GAME INTRODUCTION"); + (void)DrawStringSJIS( G_MEMBER_X, G_MEMBER_Y, LIGHTGREEN, (const u8 *)"MEMBER LIST"); + SetTargetScreenSJIS( BOTTOM_SCREEN ); +} + + +//====================================================== +// }`u[gie@T[` ` ڑj +//====================================================== + +// }`u[g̐ڑV[PX +static int SEQ_DSDL_Connect(void) +{ + // ݂prgSeqɉ + BOOL getSeqFlag = CheckNextSeq_Connect(); + + switch ( prgSeq ) { + case PSEQ_INIT: // q@[h̊JniCȕ`StartScan܂ł̗sj + if ( MB_Init( mbwork, &myUser, MY_GGID, tgid, MB_DMA_NO ) != WM_ERRCODE_SUCCESS ) { + OS_Printf("MB init failed.\n"); + break; + } + MB_CommSetChildStateCallback( CallbackChild_MB ); + if ( MB_StartChild() != WM_ERRCODE_SUCCESS ) { + OS_Printf("MB start failed.\n"); + break; + } + tgid++; + DispTopScreen(); + prgSeq = PSEQ_INITIALIZING; + break; + + case PSEQ_INITIALIZING: + break; + + case PSEQ_SCANNING: // XL͐AV[PX`FbNsB + case PSEQ_ENDING: + if( !getSeqFlag ) { + return 0; + } + break; + + case PSEQ_CONNECTING: // ڑ̓L[͂󂯕tɃ^[BiV[PX`FbN͍sj + return 0; + + case PSEQ_CONNECT_SUCCEEDED: // bZ[W\A_E[hV[PXɈڍsB + if( DispMessage() ) { + UnlockPrgNextSeqQue(); // V[PXbN + wdProcess = SEQ_DSDL_Download; + } + return 0; + + case PSEQ_CONNECT_FAILED: // bZ[W\AXLĊJBiXLĊĴ̂́ACuōsBj + if( DispMessage() ) { + UnlockPrgNextSeqQue(); // V[PXbN + prgSeq = PSEQ_SCANNING; + } + break; + + case PSEQ_DISCONNECTED_BY_PARENT: // ؒfobZ[W\ݒB + if( DispMessage() ) { + UnlockPrgNextSeqQue(); // V[PXbN + prgSeq = PSEQ_INIT; + } + break; + + case PSEQ_CANCELLED: // I + return 0; + + default: + break; + } + + + // J[\ړ + if(pad.trg & PAD_KEY_DOWN){ // J[\̈ړ + if( ++csrC == MB_GAME_INFO_RECV_LIST_NUM ){ + csrC = 0; + } + } + if(pad.trg & PAD_KEY_UP){ + if( --csrC & 0x80 ){ + csrC = MB_GAME_INFO_RECV_LIST_NUM - 1; + } + } + DrawMenu((u16)(csrC & (PARENT_VIEW_NUM - 1)), &childModeSel); // XgԍiJ[\j̕\ + DispParentNum(); // e@̕\ + DispParentList(); // e@Xg̕\ + DispScanStatus(); // WMXLԂ̕\ + CountAndDispTotalTime(); // g[^Ԃ̃JEg\ + CountParentFindTime(); // e@Ԃ̃JEg + + + // e@ւ̐ڑ + if(pad.trg & PAD_BUTTON_A) { + if( mbrsp->usefulGameInfoFlag & (0x0001 << csrC) ) { + if( MB_CommDownloadRequest( csrC ) == WM_ERRCODE_SUCCESS ) { // ڑJn + OS_Printf("start conntct to parent.\n"); + prgSeq = PSEQ_CONNECTING; + }else { + OS_Printf("this parent info is invalid.\n"); + } + } + }else if(pad.trg & PAD_BUTTON_B) { // IJn + if( prgSeq == PSEQ_SCANNING ) { + OS_Printf("MB End start\n"); + prgSeq = PSEQ_ENDING; +// end_flag = TRUE; + MB_End(); + } + }else if( pad.trg & PAD_BUTTON_R ) { + unrenewalFlag ^= 0x01; +// MB_SetUnrenewalGameInfoFlag( (BOOL)unrenewalFlag ); + } + + csrC_old = csrC; // J[\ʒȗޔ + return 0; +} + + +// V[PX̃`FbNiR[obNŃC[vƂ͔񓯊ɕԂ鎟V[PXւ̈ڍsC[ṽvOisɍ킹Bj +static BOOL CheckNextSeq_Connect(void) +{ + PrgSeq seq; + // MBR[obNɂāAV[PXڍsĂꍇ̏ + if( GetPrgNextSeqQue( &seq) ) { // MBR[obNɂāAV[PXڍsĂꍇ̏ + prgSeq = seq; + OS_Printf("prgSeq = %s\n", str_prgSeq[ prgSeq ]); + + switch( seq ) { + case PSEQ_SCANNING: + { +/* + u8 *ver = MBw_GetWLVersion(); + (void)DrawStringSJIS( 21, 0, WHITE, (const u8 *)"WL ver=" ); + (void)DrawStringSJIS( 26, 0, WHITE, (const u8 *)ver ); +*/ + } + break; + + case PSEQ_CONNECT_SUCCEEDED: // ڑbZ[W\ݒB + SetDispMessage( YELLOW, str_connect_succeeded ); + LockPrgNextSeqQue(); // prgSeqbNB + return FALSE; + + case PSEQ_CONNECT_FAILED: // ڑsbZ[W\ݒB + SetDispMessage( RED, str_connect_failed); + LockPrgNextSeqQue(); // prgSeqbNB + return FALSE; + + case PSEQ_DISCONNECTED_BY_PARENT: // ؒfobZ[W\ݒB + SetDispMessage( RED, str_disconnected); + LockPrgNextSeqQue(); // prgSeqbNB + return FALSE; + + case PSEQ_CANCELLED: // I + { + u32 i; + for( i = 0; i < PARENT_VIEW_NUM; i++ ) { + ClearIconOBJ( i ); // SACȐ + } +// if( end_flag ) { +// ClearAllStringSJIS(); +// SetTargetScreenSJIS( TOP_SCREEN ); +// ClearAllStringSJIS(); +// SetTargetScreenSJIS( BOTTOM_SCREEN ); +// (void)DrawStringSJIS( 11, 11, WHITE, (const u8 *)"イ傤܂B"); +// }else { + prgSeq = PSEQ_INIT; +// } + } + return FALSE; + } + } + return TRUE; // V[PXڍsȂꍇFALSE^[̃V[PXłȂꍇTRUE^[B +} + + +//====================================================== +// }`u[gi_E[hj +//====================================================== + +// }`u[g̃t@C_E[hV[PX +static int SEQ_DSDL_Download(void) +{ + static int count_old = 0; + // ݂prgSeqɉ + BOOL getSeqFlag = CheckNextSeq_Download(); + + switch(prgSeq) { + + case PSEQ_REQ_REFUSED: + case PSEQ_MEMBER_FULL: // bZ[W\AUIď蒼B + if( DispMessage() ) { + UnlockPrgNextSeqQue(); // V[PXbN + prgSeq = PSEQ_ENDING; + wdProcess = SEQ_DSDL_Connect; + MB_End(); + } + break; + + // _E[ht@CMA_E[hł + case PSEQ_DOWNLOAD_READY: +// if (pad.trg & PAD_BUTTON_A) { // _E[hJn + OS_Printf("Start download.\n"); + ClearStringSJIS_handle(msgHandle); + (void)MB_CommStartDownload(); + SetBlinkMessage( YELLOW, str_downloading ); +// } + break; + + // _E[h + case PSEQ_DOWNLOADING: + if( getSeqFlag ) { + DispBlinkMessage(); + msgHandle = msgStat.handle; + + if( 1 ) { + u16 percent = MB_GetChildProgressPercentage(); + msgHandle = DrawDecimalSJIS( 16, 21, WHITE, &percent ,3, 2 ); + } + } + break; + + // _E[h + case PSEQ_DOWNLOAD_COMPLETED: + if( DispMessage() ) { + { + msgHandle = DrawStringSJIS( 4, 21, LIGHTGREEN, "Sign Digest...."); + if ( ACSignDigest ( output_buffer, &dlfileinfo ) ) { + ClearStringSJIS_handle( msgHandle ); + msgHandle = DrawStringSJIS( 4, 21, LIGHTGREEN, "Digest SUCCEEDED."); + }else { + ClearStringSJIS_handle( msgHandle ); + msgHandle = DrawStringSJIS( 4, 21, RED, "Digest FAILED."); + } + { + int i; + for ( i = 0; i < 120; i++ ) { + SVC_WaitVBlankIntr(); + } + } + ClearStringSJIS_handle( msgHandle ); + } + UnlockPrgNextSeqQue(); // V[PXbN + prgSeq = PSEQ_BOOT_REQ_WAIT; + msgHandle = DrawStringSJIS( 4, 21, WHITE, "Waiting BOOT-REQ from parent."); + } + break; + + // e@̃u[g‘҂ + case PSEQ_BOOT_REQ_WAIT: + break; + + // _E[hAu[gł +// case PSEQ_BOOT_READY: +// (void)LOADER_Start(); // ARM7ɂāA_E[hvO̍ĔzusB +// return 1; // "1"Ń^[邱ƂŁA}`u[g̃C[v甲IPL2ɏ߂B + + // e@̃u[gvMɂAN”ۃ`FbNsBiNintendoS\`FbNj + case PSEQ_BOOT_READY: + if( DispNintendoLogo() ) { + if( SYSM_CheckNinLogo( (u16 *)GetRomHeaderAddr()->nintendo_logo ) ) { + prgSeq = PSEQ_BOOT_START; + }else { + SetDispMessage( RED, (const u8 *)"Illegal game data."); + prgSeq = PSEQ_BOOT_FAILED; + } + } + break; + + // u[gJn + case PSEQ_BOOT_START: + ClearStringSJIS_handle(msgHandle); + + SearchPatchAddress(); + + (void)LOADER_Start(); // ARM7ɂāA_E[hvO̍ĔzusB + return 1; // "1"Ń^[邱ƂŁA}`u[g̃C[v甲IPL2ɏ߂B + + // u[gs + // e@ɂāAڑؒfꂽ + // LZꍇ + case PSEQ_BOOT_FAILED: + case PSEQ_DISCONNECTED_BY_PARENT: + case PSEQ_CANCELLED: + if( DispMessage() ) { // w胁bZ[Wԕ\ + UnlockPrgNextSeqQue(); // V[PXbN + ClearStringSJIS_handle( msgHandle ); + prgSeq = PSEQ_INIT; + wdProcess = SEQ_DSDL_Connect; + } + break; + + default: + break; + } + + // B{^ŏIs + if( pad.trg & PAD_BUTTON_B ) { + MB_End(); // LŹAe@T[`Ԃ蒼B + } + + DrawMenu((u16)(csrC & (PARENT_VIEW_NUM - 1)), &childModeSel); // XgԍiJ[\j̕\ + DispParentNum(); // e@̕\ + DispParentList(); // e@Xg̕\ + DispScanStatus(); // WMXLԂ̕\ + CountAndDispTotalTime(); // g[^Ԃ̃JEg\ + CountParentFindTime(); // e@Ԃ̃JEg + return 0; +} + + +// V[PX̃`FbNiR[obNŃC[vƂ͔񓯊ɕԂ鎟V[PXւ̈ڍsC[ṽvOisɍ킹Bj +static BOOL CheckNextSeq_Download(void) +{ + PrgSeq seq; + + // MBR[obNɂāAV[PXڍsĂꍇ̏ + if( GetPrgNextSeqQue( &seq) ) { + prgSeq = seq; + OS_Printf("prgSeq = %s\n", str_prgSeq[ prgSeq ]); + + switch( seq ) { + + case PSEQ_REQ_REFUSED: // ڑۃbZ[W\ݒ + SetDispMessage( RED, str_req_refused); + LockPrgNextSeqQue(); // prgSeqbNB + return FALSE; + + case PSEQ_MEMBER_FULL: // o[FULLbZ[W\ݒB + SetDispMessage( RED, str_member_full); + LockPrgNextSeqQue(); // prgSeqbNB + return FALSE; + + case PSEQ_DOWNLOAD_READY: // _E[h + ClearStringSJIS_handle( msgHandle ); + { + msgHandle = DrawStringSJIS( 4, 21, WHITE, "Sign Decript...."); + if ( ACSignDecrpto( output_buffer, &dlfileinfo ) ) { + ClearStringSJIS_handle( msgHandle ); + msgHandle = DrawStringSJIS( 4, 21, LIGHTGREEN, "Decript SUCCEEDED."); + }else { + ClearStringSJIS_handle( msgHandle ); + msgHandle = DrawStringSJIS( 4, 21, RED, "Decript FAILED."); + } + { + int i; + for ( i = 0; i < 120; i++ ) { + SVC_WaitVBlankIntr(); + } + } + ClearStringSJIS_handle( msgHandle ); + } + + msgHandle = DrawStringSJIS( 4, 21, WHITE, "PUSH [A] TO DOWNLOAD."); + break; + + case PSEQ_DOWNLOAD_COMPLETED: // _E[h + ClearStringSJIS_handle( msgHandle ); + SetDispMessage( YELLOW, str_download_completed ); + LockPrgNextSeqQue(); // V[PXbN + return FALSE; + +// case PSEQ_BOOT_READY: // u[g +// ClearStringSJIS_handle( msgHandle ); +// break; + + case PSEQ_BOOT_READY: // u[g + ClearStringSJIS_handle( msgHandle ); + InitDispNintendoLogo(); + break; + + case PSEQ_CANCELLED: + ClearStringSJIS_handle( msgHandle ); + SetDispMessage( RED, str_download_cancelled ); + LockPrgNextSeqQue(); // V[PXbN + return FALSE; + + case PSEQ_DISCONNECTED_BY_PARENT: // ؒfobZ[W\ݒB + ClearStringSJIS_handle( msgHandle ); + SetDispMessage( RED, str_disconnected ); + LockPrgNextSeqQue(); // prgSeqbNB + return FALSE; + + default: + break; + } + } + return TRUE; +} + + +//====================================================== +// R[obN +//====================================================== + +// q@[hł̃R[obN +static void CallbackChild_MB( u32 status, void *arg ) +{ + switch (status) + { + case MB_COMM_CSTATE_INIT_COMPLETE: // + OS_Printf("CB: init completed.\n"); + (void)SetPrgNextSeqQue( PSEQ_SCANNING ); + break; + +// case MB_COMM_CSTATE_END_COMPLETE: // }`u[gI +// OS_Printf("CB: end completed.\n"); +// (void)SetPrgNextSeqQue( PSEQ_END ); +// break; + + case MB_COMM_CSTATE_REQ_REFUSED: // e@̃Gg[ + OS_Printf("CB: request refused.\n"); + (void)SetPrgNextSeqQue( PSEQ_REQ_REFUSED ); + break; + + case MB_COMM_CSTATE_MEMBER_FULL: // Q[ɒB + OS_Printf("CB: member full.\n"); + (void)SetPrgNextSeqQue( PSEQ_MEMBER_FULL ); + break; + + case MB_COMM_CSTATE_CONNECT: // e@ւ̐ڑ + OS_Printf("CB: connected.\n"); + (void)SetPrgNextSeqQue( PSEQ_CONNECT_SUCCEEDED ); + break; + + case MB_COMM_CSTATE_CONNECT_FAILED: // e@ւ̐ڑs + OS_Printf("CB: connect failed!\n"); + (void)SetPrgNextSeqQue( PSEQ_CONNECT_FAILED ); + break; + + case MB_COMM_CSTATE_DLINFO_ACCEPTED: // e@_E[hM + OS_Printf("CB: dlinfo accepted.\n"); + (void)SetPrgNextSeqQue( PSEQ_DOWNLOAD_READY ); + MI_CpuCopy16( (void *)arg, (void *)&dlfileinfo, sizeof( MBDownloadFileInfo ) ) ; + break; + + case MB_COMM_CSTATE_RECV_PROCEED: // MJn + OS_Printf("CB: recv proceed.\n"); + (void)SetPrgNextSeqQue( PSEQ_DOWNLOADING ); + break; + + case MB_COMM_CSTATE_RECV_COMPLETE: // M + OS_Printf("CB: recv completed.\n"); + (void)SetPrgNextSeqQue( PSEQ_DOWNLOAD_COMPLETED ); + break; + + case MB_COMM_CSTATE_BOOT_READY: // u[g + OS_Printf("CB: boot ready.\n"); +// GetSYSMWork()->mb_flag = 1; +// GetSYSMWork()->mb_ggid = *(u32 *)( MB_GetBeaconRecvStatus()->list[ pCwork->connectTargetNo ].bssDesc.gameInfo.ggid ); +// GetSYSMWork()->mb_ggid = MB_GetBeaconRecvStatus()->list[ pCwork->connectTargetNo ].gameInfo.ggid; + (void)SetPrgNextSeqQue( PSEQ_BOOT_READY ); + break; + + case MB_COMM_CSTATE_CANCELLED: // _E[hLZ + OS_Printf("CB: download cancel.\n"); + (void)SetPrgNextSeqQue( PSEQ_CANCELLED ); + break; + + case MB_COMM_CSTATE_DISCONNECTED_BY_PARENT: // e@̐ؒfʒm + OS_Printf("CB: disconnected by parent!\n"); + (void)SetPrgNextSeqQue( PSEQ_DISCONNECTED_BY_PARENT ); + break; + + case MB_COMM_CSTATE_GAMEINFO_LOST: + gameInfoLostCount++; + break; + } +} + + +//====================================================== +// \nTu[` +//====================================================== + +// XLԂ̕\ +static void DispScanStatus(void) +{ +#if 0 + int channel = MBw_GetScanChannel(); + + (void)DrawHexSJIS( 13, 2, WHITE, &channel, 2); + if( IsScanLock() ) { // XLbNȂA̎Ԃ\ + (void)DrawStringSJIS( 15, 2, RED, (const u8 *)"LOCK"); + (void)DrawHexSJIS ( 19, 2, WHITE, &mbrsp->nowLockTimeCount, 4); + }else { + (void)DrawStringSJIS( 15, 2, RED, (const u8 *)" "); + } +#endif +} + + +// e@̕\ +static void DispParentNum(void) +{ + int i; + int num = 0; + + for (i = 0; i < MB_GAME_INFO_RECV_LIST_NUM; i++) { // e@̃JEg + if( mbrsp->usefulGameInfoFlag & (0x0001 << i) ) num++; + } + (void)DrawDecimalSJIS( 10, 2, LIGHTGREEN, &num, 2, 4); +} + + +// e@񃊃Xg̕\ +static void DispParentList(void) +{ + u32 i; + u32 listNo = (u32)( csrC & ~(PARENT_VIEW_NUM - 1) ); // ݕ\̃Xg̐擪Zoi~\Ń}XNj + u32 listNo_old = (u32)( csrC_old & ~(PARENT_VIEW_NUM - 1) ); // O\Xg̐擪Zo + +// (void)DrawDecimalSJISEx( 15, 22, WHITE, &gameInfoLostCount, 8, 4, 0); + + // Q[e̕\ + DispGameIntroduction(); + + // ʐMo[̕\ + DispPlayMember(); + + // e@Xg̕\ + for( i = 0; i < PARENT_VIEW_NUM; i++ ) { + if( (listNo != listNo_old) || !(mbrsp->usefulGameInfoFlag & (0x0001 << listNo)) ){ + if( dispGameInfoFlag & (0x0001 << listNo_old) ) { // \XgʒuύX or Ye@LłȂȂꍇAO\f[^ɕ\ς݂ȂNAB + ClearDispParentGameInfo( i, listNo_old); + dispGameInfoFlag ^= 0x0001 << listNo_old; + } + } + + if( mbrsp->usefulGameInfoFlag & (0x0001 << listNo) ) { // YXg̃f[^LŁA–\Ȃ\B + DispParentGameInfo( i, listNo , !(dispGameInfoFlag & (0x0001 << listNo)) ); + dispGameInfoFlag |= 0x0001 << listNo; + } + if( csrC != csrC_old ) { + DecimalToString( parentListNo[i], &listNo, 2, 2); // r[ʂ̐擪Xgio[𕶎obt@ɓB + } + listNo++; + listNo_old++; + } +} + + +// Q[e̕\ +static void DispGameIntroduction( void ) +{ + BOOL clear = FALSE; + + if( ( ( csrC != csrC_old ) && ( dispIntroFlag & (0x0001 << csrC_old) ) ) + || ( !(mbrsp->usefulGameInfoFlag & (0x0001 << csrC)) && ( dispIntroFlag & (0x0001 << csrC) ) ) ) { + ClearDispGameIntroduction(); // J[\āAOJ[\ʒȕڍו\sĂA + dispIntroFlag = 0; + clear = TRUE; + } + + if( (mbrsp->usefulGameInfoFlag & (0x0001 << csrC)) && !( dispIntroFlag & (0x0001 << csrC) ) ) { + if ( !clear ){ // ݃J[\ʒũQ[񂪗LŁA܂ڍו\sĂȂ\B + ClearDispGameIntroduction(); + } + DispGameIntroduction_Core( (u32)csrC ); + dispIntroFlag = (u16)( 0x0001 << csrC ); // J[\ړꂽA݈ʒũQ[񂪖\̎ɂ̂ݕ\ or NAsB + } +} + + +// ʐMo[̃NA\ +static void DispPlayMember( void ) +{ + BOOL clear = FALSE; + + if( ( ( csrC != csrC_old ) && ( dispMemberFlag & (0x0001 << csrC_old) ) ) + || ( !(mbrsp->validGameInfoFlag & (0x0001 << csrC)) && ( dispMemberFlag & (0x0001 << csrC) ) ) ) { + ClearDispPlayMember(); // J[\ʒũQ[ڍ׏\ĂāÃQ[񂪖ɂȂNAB + dispMemberFlag = 0; + clear = TRUE; + } + + if( (mbrsp->validGameInfoFlag & (0x0001 << csrC)) && !( dispMemberFlag & (0x0001 << csrC) ) ) { + if ( !clear ){ // ݃J[\ʒũQ[񂪗LŁA܂ڍו\sĂȂ\B + ClearDispPlayMember(); + } + DispPlayMember_Core( (u32)csrC ); + dispMemberFlag = (u16)( 0x0001 << csrC ); // J[\ړꂽA݈ʒũQ[񂪖\̎ɂ̂ݕ\ or NAsB + } +} + + +// w肳ꂽe@̕\ +static void DispParentGameInfo( u32 view_no, u32 listNo, BOOL drawFixedDataFlag) +{ + if(drawFixedDataFlag) { // ωȂ̕\ + + MI_CpuClear16( gameName, MB_GAME_NAME_LENGTH * 2 ); + MI_CpuClear16( userName, MB_USER_NAME_LENGTH * 2 ); + ExUTF16_LEtoSJIS_BE( (u8 *)gameName, (u16 *)mbrsp->list[ listNo ].gameInfo.fixed.gameName, MB_GAME_NAME_LENGTH * 2 ); + ExUTF16_LEtoSJIS_BE( (u8 *)userName, (u16 *)mbrsp->list[ listNo ].gameInfo.fixed.parent.name, (u16)( mbrsp->list[ listNo ].gameInfo.fixed.parent.nameLength * 2)); +// MI_CpuCopy16( mbrsp->list[ listNo ].gameInfo.fixed.gameName, gameName, MB_GAME_NAME_LENGTH * 2); +// MI_CpuCopy16( mbrsp->list[ listNo ].gameInfo.fixed.parent.name, userName, mbrsp->list[ listNo ].gameInfo.fixed.parent.nameLength * 2); + gameName[ MB_GAME_NAME_LENGTH ] = 0; + userName[ mbrsp->list[ listNo ].gameInfo.fixed.parent.nameLength ] = 0; + + (void)ClearStringSJISEx( gameName, view_no); + (void)ClearStringSJISEx( userName, view_no); + (void)DrawStringSJISEx( 9, (PLIST_Y + (int)view_no*4), WHITE, gameName, view_no); + (void)DrawStringSJISEx( 9, (PLIST_Y + (int)view_no*4 + 2), WHITE, userName, view_no); + + (void)DrawStringSJISEx( 26, (PLIST_Y + (int)view_no*4), YELLOW, str_sura, view_no); + (void)DrawDecimalSJIS ( 27, (PLIST_Y + (int)view_no*4), YELLOW, &mbrsp->list[ listNo ].gameInfo.fixed.maxPlayerNum, 2, 1); + + // e@Ԃ̕\ + (void)CheckParentFindTime( listNo ); // Őe@𔭌Ă邩ĊmFĂB + time_ms = (int)findTime[listNo].vcount * 17; + time_sec = time_ms / 1000; + time_ms = (time_ms % 1000) / 10; + (void)DrawDecimalSJISEx( 23, (PLIST_Y + (int)view_no*4 + 2), CYAN, &time_sec, 4, 4, view_no); + (void)DrawDecimalSJISEx( 27, (PLIST_Y + (int)view_no*4 + 2), CYAN, &time_ms, 2, 4, view_no); + (void)DrawStringSJISEx ( 26, (PLIST_Y + (int)view_no*4 + 2), CYAN, str_period, view_no); + (void)DrawStringSJISEx ( 29, (PLIST_Y + (int)view_no*4 + 2), CYAN, str_sec, view_no); + + SetIconOBJ( listNo ); // ACR̕\ + } + { // ωio[Ee@JEg̕\j + (void)DrawDecimalSJIS( 24, (PLIST_Y + (int)view_no*4), YELLOW, &mbrsp->list[ listNo ].gameInfo.volat.nowPlayerNum, 2, 1); + (void)DrawHexSJIS ( 19, (PLIST_Y + (int)view_no*4 + 2), CYAN, &mbrsp->list[ listNo ].lifetimeCount, 4); + { + u16 color = RED; + if ( mbrsp->validGameInfoFlag & ( 0x0001 << listNo ) ) { + color = CYAN; + } + (void)DrawHexSJIS ( 19, (PLIST_Y + (int)view_no*4), color, &mbrsp->list[ listNo ].gameInfo.seqNoVolat, 2); + } + } +} + + +// w肳ꂽe@̕\NA +static void ClearDispParentGameInfo( u32 view_no, u32 listNo) +{ + // ̕ϐ̃AhX́ADispParentGameInfô̂ƈvĂȂƁA\NA邱ƂłȂ̂ŒӁBiϐŕ\Ƃ̓AhXςĂ܂j + // iDrawStringSJIS֐̎dlj + ClearStringSJISEx( gameName, view_no ); // Q[ + ClearStringSJISEx( userName, view_no ); // [U[ + ClearStringSJISEx( &time_sec, view_no ); // e@sec + ClearStringSJISEx( &time_ms, view_no ); // e@ms + ClearStringSJISEx( (void *)str_sura, view_no ); // "/" + ClearStringSJISEx( (void *)str_period, view_no ); // "." + ClearStringSJISEx( (void *)str_sec, view_no ); // "sec" + ClearStringSJIS ( (void *)&mbrsp->list[ listNo ].lifetimeCount ); // e@JEg + ClearStringSJIS ( (void *)&mbrsp->list[ listNo ].gameInfo.volat.nowPlayerNum ); // vCl + ClearStringSJIS ( (void *)&mbrsp->list[ listNo ].gameInfo.fixed.maxPlayerNum ); // ővCl + ClearStringSJIS ( (void *)&mbrsp->list[ listNo ].gameInfo.seqNoVolat ); // ővCl + + ClearIconOBJ( listNo ); // ACȐ +} + + +// Q[e̕\i) +static void DispGameIntroduction_Core( u32 listNo ) +{ + int i; + const u16 *strp = mbrsp->list[ listNo ].gameInfo.fixed.gameIntroduction; + u16 *dstp; + u16 gameIntroTmp[ MB_GAME_INTRO_LENGTH / 2 + 1 ]; + + MI_CpuClear16( gameIntroduction[0], (MB_GAME_INTRO_LENGTH / 2 + 1) * sizeof(u16) ); + MI_CpuClear16( gameIntroduction[1], (MB_GAME_INTRO_LENGTH / 2 + 1) * sizeof(u16) ); + + dstp = gameIntroTmp; + for ( i = 0; i < MB_GAME_INTRO_LENGTH / 2; i++ ) { // oCgPʂł̃Rs[Ȃ̂ŁA1śAMB_GAME_INTRO_LENGTH/2*2B + if( ( *strp == NULL) || ( *strp == 0x000a ) ) { + *dstp++ = 0x0000; + }else { + *dstp++ = *strp++; + } + } + ExUTF16_LEtoSJIS_BE( (u8 *)gameIntroduction[ 0 ], gameIntroTmp, MB_GAME_INTRO_LENGTH / 2 ); + + if( *strp == 0x000a ) { + strp++; + } + + dstp = gameIntroTmp; + for ( i = 0; i < MB_GAME_INTRO_LENGTH / 2; i++ ) { + if( ( *strp == NULL) || ( *strp == 0x000a ) ) { + *dstp++ = 0x00; + }else { + *dstp++ = *strp++; + } + } + ExUTF16_LEtoSJIS_BE( (u8 *)gameIntroduction[ 1 ], gameIntroTmp, MB_GAME_INTRO_LENGTH / 2 + 1 ); + + ClearDispGameIntroduction(); + + SetTargetScreenSJIS( TOP_SCREEN ); + (void)DrawStringSJIS( ( G_INTRO_X + 1 ), ( G_INTRO_Y + 2 ), WHITE, (const u8 *)gameIntroduction[0] ); + (void)DrawStringSJIS( ( G_INTRO_X + 1 ), ( G_INTRO_Y + 4 ), WHITE, (const u8 *)gameIntroduction[1] ); + SetTargetScreenSJIS( BOTTOM_SCREEN ); +} + + +// Q[e\̃NA +static void ClearDispGameIntroduction( void ) +{ + SetTargetScreenSJIS( TOP_SCREEN ); + ClearStringSJIS( (void *)gameIntroduction[0] ); + ClearStringSJIS( (void *)gameIntroduction[1] ); + SetTargetScreenSJIS( BOTTOM_SCREEN ); +} + + +// ʐMo[̕\ij +static void DispPlayMember_Core( u32 listNo ) +{ + int n, count_x; + u16 nameLength; + int pos_x, pos_y; + const MBUserInfo *memberp = &mbrsp->list[ listNo ].gameInfo.volat.member[ 0 ]; + u16 *dstp; + + SetTargetScreenSJIS( TOP_SCREEN ); + + MI_CpuClear16( playMember, sizeof(playMember) ); + count_x = 0; + pos_x = G_MEMBER_X + 1; + pos_y = G_MEMBER_Y + 2; + for ( n = 0; n < MB_MEMBER_MAX_NUM; n++ ) { + + if( memberp->nameLength > MB_USER_NAME_LENGTH ) { // Õ`FbN + nameLength = MB_USER_NAME_LENGTH; + }else { + nameLength = memberp->nameLength; + } + dstp = playMember[ n ]; + if( mbrsp->list[ listNo ].gameInfo.volat.nowPlayerFlag & (0x0002 << n ) ) { + + ExUTF16_LEtoSJIS_BE( (u8 *)dstp, (u16 *)memberp->name, nameLength ); + playMember[ n ][ nameLength ] = 0; + (void)DrawStringSJIS( pos_x, pos_y, WHITE, (const u8 *)playMember[ n ] ); + }else { + MI_CpuCopy16( (void *)"----------", (void *)playMember[ n ], MB_USER_NAME_LENGTH + 1); + (void)DrawStringSJIS( pos_x, pos_y, WHITE, playMember[ n ] ); + } + memberp++; + + if( ++count_x == 3 ) { // \ʒu̎Zo + pos_x -= 20; + pos_y += 2; + count_x = 0; + }else { + pos_x += 10; + } + } + + SetTargetScreenSJIS( BOTTOM_SCREEN ); +} + + +// ʐMo[\̃NA +static void ClearDispPlayMember( void ) +{ + int i; + + SetTargetScreenSJIS( TOP_SCREEN ); + for( i = 0; i < MB_MEMBER_MAX_NUM + 1; i++ ) { + ClearStringSJIS( (void *)playMember[ i ] ); + } + SetTargetScreenSJIS( BOTTOM_SCREEN ); +} + + +// 10if[^𕶎ɕϊ +static void DecimalToString(u8 *dstp, const void *valuep, u8 drawLength, u8 size) +{ + u16 count; + u32 mask, divisor, target; + + mask = 0xff; + while(--size > 0) { + mask = (mask << 8) | 0xff; + } + target=(*(u32 *)valuep) & mask; + count=10; + divisor=1000000000; + while(count) { + CP_SetDiv32_32(target, divisor); + if (count <= drawLength) { + *dstp++ = (u8)(CP_GetDivResult32()+0x0030); + } + target=(u32)CP_GetDivRemainder32(); + CP_SetDiv32_32(divisor, 10); + divisor=(u32)CP_GetDivResult32(); + count--; + } +} + + +// e@ԕϐ̃NA +static void InitParentFindTime( void ) +{ + int i; + for( i = 0; i < MB_GAME_INFO_RECV_LIST_NUM; i++) { + findTime[i].find = FALSE; + findTime[i].vcount = 0; + } + total_vcount = 0; +} + + +// e@Ԃ̃JEg +static void CountParentFindTime( void ) +{ + u32 i; + + for( i = 0; i < MB_GAME_INFO_RECV_LIST_NUM; i++ ) { + if( !CheckParentFindTime( i ) ) { + findTime[i].vcount = total_vcount; // e@񂪌‚܂ŃJEg + } + } +} + + +// e@񂪑ǂ`FbNāAԃJEg~B +static BOOL CheckParentFindTime( u32 index ) +{ + if( mbrsp->validGameInfoFlag & (0x01 << index) ) { // e@񂪔ꂽȂAJEg~B + findTime[ index ].find = TRUE; + } + return findTime[ index ].find; +} + + +// g[^Ԃ̃JEg\ +static void CountAndDispTotalTime( void ) +{ + total_vcount++; + time_ms = total_vcount * 17; + time_sec = time_ms / 1000; + time_ms = (time_ms % 1000) / 10; + (void)DrawDecimalSJISEx( 23, 2, CYAN, &time_sec, 4, 4, PARENT_VIEW_NUM); + (void)DrawDecimalSJISEx( 27, 2, CYAN, &time_ms, 2, 4, PARENT_VIEW_NUM); +} + + +// ACROBJ̃[h +static void SetIconOBJ( u32 index ) +{ + u16 view_no = (u16)( index & 0x03 ); + const MBIconInfo *iconp = &mbrsp->list[ index ].gameInfo.fixed.icon; + + GXS_LoadOBJPltt( iconp->palette, (u32)( MB_ICON_PALETTE_SIZE * view_no ), MB_ICON_PALETTE_SIZE ); + MI_CpuCopyFast( iconp->data, (void *)((u32)objVramBuff + 0x20 + MB_ICON_DATA_SIZE * view_no), MB_ICON_DATA_SIZE ); + G2_SetOBJAttr( (GXOamAttr*)&oamBakS[ view_no ], // OAM pointer + 8 * (PLIST_X + 3), // X position + 8 * PLIST_Y + (view_no * 32), // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_32x32, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 1 + view_no * 16, // charactor + view_no, // palette + 0); // affine +} + +// ACROBJ̃NA +static void ClearIconOBJ( u32 index ) +{ + u16 view_no = (u16)( index & 0x03 ); + u16 *oamp = (u16 *)&oamBakS[ view_no ]; + + *oamp++ = 192; // YWʊOɁBiI[0NAł̓_j + *oamp++ = 0; + *oamp++ = 0; + *oamp = 0; +} + + +// bZ[W\̃Zbg +static void SetDispMessage( u16 color, const u8 *str ) +{ + msgStat.vcount = MSG_VIEW_COUNT; + msgStat.color = color; + msgStat.str = str; +} + + +// bZ[W\ +static BOOL DispMessage(void) +{ + if( msgStat.vcount == MSG_VIEW_COUNT ) { + msgStat.handle = DrawStringSJIS( 4, 21, msgStat.color, msgStat.str ); + } + + if ( --msgStat.vcount == 0 ) { + ClearStringSJIS_handle( msgStat.handle ); + return TRUE; + } + return FALSE; +} + + +// bZ[W\̃Zbgi_ŕ\j +static void SetBlinkMessage( u16 color, const u8 *str ) +{ + msgStat.vcount = MSG_BLINK_COUNT; + msgStat.flag = 1; + msgStat.color = color; + msgStat.str = str; +} + + +// bZ[W\ +static void DispBlinkMessage( void ) +{ + if( ( msgStat.vcount == MSG_BLINK_COUNT ) && msgStat.flag ) { + msgStat.handle = DrawStringSJIS( 4, 21, msgStat.color, msgStat.str ); + } + + if ( --msgStat.vcount == 0 ) { + ClearStringSJIS_handle( msgStat.handle ); + msgStat.flag ^= 0x01; + msgStat.vcount = MSG_BLINK_COUNT; + } +} + + +//============================================================================= +// NintendoS\ +//============================================================================= + +// NintendoS\̏ +static void InitDispNintendoLogo( void ) +{ + int i; + u16 *palettep = (u16 *)(HW_OBJ_PLTT + 0x20 * 15 ) + 1; // pbg15̃J[1ɁB + *palettep++ = 0x7fff; + *palettep = 0x1111; + + // TOPʂ̑S\NA + SetTargetScreenSJIS( TOP_SCREEN ); + ClearAllStringSJIS(); + SetTargetScreenSJIS( BOTTOM_SCREEN ); + + // ʏɎMQ[NintendoS\B +#ifdef NINLOGO_LOAD_1D_CHAR + // 1D}bsOł̃[h\ + GX_SetOBJVRamModeChar( GX_OBJVRAMMODE_CHAR_1D_32K ); + SYSM_LoadNintendoLogo1D( (u16 *)GetRomHeaderAddr()->nintendo_logo, (u16 *)( HW_OBJ_VRAM + 0x40 ), 1, ninLogoBuff ); +// SYSM_LoadNintendoLogo1D( (u16 *)SYSROM9_NINLOGO_ADR, (u16 *)( HW_OBJ_VRAM + 0x40 ), 1, ninLogoBuff ); + + for ( i = 0; i < 3; i++ ) { + G2_SetOBJAttr( &oamBakM[ 10 + i ], // OAM pointer + 72 + 32 * i, // X position + 88, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_32x8, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 0x2 + i * 4, // charactor + 15, // palette + 0); // affine + } + { + G2_SetOBJAttr( &oamBakM[ 13 ], // OAM pointer + 72 + 32 * 3, // X position + 88, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_8x8, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 0x2 + 3 * 4, // charactor + 15, // palette + 0); // affine + } + for ( i = 0; i < 3; i++ ) { + G2_SetOBJAttr( &oamBakM[ 14 + i ], // OAM pointer + 72 + 32 * i, // X position + 96, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_32x8, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 0x0f + i * 4, // charactor + 15, // palette + 0); // affine + } + { + G2_SetOBJAttr( &oamBakM[ 17 ], // OAM pointer + 72 + 32 * 3, // X position + 96, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_8x8, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 0xf + 3 * 4, // charactor + 15, // palette + 0); // affine + } +#else + // 2D}bsOł̃[h\ + GX_SetOBJVRamModeChar( GX_OBJVRAMMODE_CHAR_2D ); + SYSM_LoadNintendoLogo2D( (u16 *)GetRomHeaderAddr()->nintendo_logo, (u16 *)( HW_OBJ_VRAM + 0x40 ), 1, ninLogoBuff ); +// SYSM_LoadNintendoLogo2D( (u16 *)SYSROM9_NINLOGO_ADR, (u16 *)( HW_OBJ_VRAM + 0x40 ), 1, ninLogoBuff ); + + for ( i = 0; i < 4; i++ ) { + G2_SetOBJAttr( &oamBakM[11 + i], // OAM pointer + 72 + 32 * i, // X position + 88, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_32x16, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 0x2 + i * 4, // charactor + 15, // palette + 0); // affine + } +#endif + + loop_count = 120; +} + + +// NintendoS\ +static BOOL DispNintendoLogo( void ) +{ + if( --loop_count == 0 ) { + { + int i; + for ( i = 0; i < 4; i++ ) { + G2_SetOBJPosition( &oamBakM[ 11 + i ], 0, 192 ); + } + } + return TRUE; + } + return FALSE; +} + + +//============================================================================= +// ̑Tu[` +//============================================================================= + +// ̃[U[NITROݒf[^ǂݏoăZbg +static void SetMyUserInfo( MBUserInfo *my ) +{ + NvNickname *nickname = NCD_GetNickname(); + + MI_CpuCopy16( nickname->str, my->name, (u32)( nickname->length * 2 ) ); + my->nameLength = nickname->length; + my->playerNo = 0; // Ƃ肠OɂB + my->favoriteColor = NCD_GetFavoriteColor(); +} + + +// ݃XLbNǂ擾B +static BOOL IsScanLock(void) +{ + return mbrsp->nowScanTargetFlag ? TRUE : FALSE; +} + + +//============================================================================= +// 荞݃[` +//============================================================================= + +// VuN荞 +static void VBlankIntr_WDL(void) +{ + // OAM, BG-VRAM̍XV + DC_FlushRange (oamBakM, sizeof(oamBakM)); + DC_FlushRange (oamBakS, sizeof(oamBakS)); + DC_FlushRange (bgBakM, sizeof(bgBakM)); + DC_FlushRange (bgBakS, sizeof(bgBakS)); + DC_FlushRange (objVramBuff, sizeof(objVramBuff)); + MI_CpuCopyFast(oamBakM, (void*)HW_OAM, sizeof(oamBakM)); + MI_CpuCopyFast(oamBakS, (void*)HW_DB_OAM, sizeof(oamBakS)); + MI_CpuCopyFast(bgBakM, (void*)(HW_BG_VRAM + 0xf000), sizeof(bgBakM)); + MI_CpuCopyFast(bgBakS, (void*)(HW_DB_BG_VRAM + 0xf000), sizeof(bgBakS)); + MI_CpuCopyFast(objVramBuff, (void*)HW_DB_OBJ_VRAM, sizeof(objVramBuff)); + //---- 荞݃`FbNtO + OS_SetIrqCheckFlag(OS_IE_V_BLANK); +} + + +//============================================================================= +// vOV[PXL[ +//============================================================================= + +// L[ +static void InitPrgNextSeqQue( void ) +{ + MI_CpuClear16( &nextSeq, sizeof(nextSeq) ); +} + + +// PrgSeqL[ɃZbgB +static BOOL SetPrgNextSeqQue( PrgSeq seq ) +{ + BOOL preIRQ = OS_DisableIrq(); + BOOL retval = FALSE; + + if( nextSeq.num != PRG_NEXT_SEQ_QUE_NUM ) { + nextSeq.seq[ nextSeq.bottom ] =seq; + nextSeq.num++; + nextSeq.bottom++; + if( nextSeq.bottom == PRG_NEXT_SEQ_QUE_NUM ) { + nextSeq.bottom = 0; + } + retval = TRUE; + } + (void)OS_RestoreIrq( preIRQ ); + return retval; +} + + +// PrgSeqL[o +static BOOL GetPrgNextSeqQue( PrgSeq *seqp ) +{ + BOOL preIRQ = OS_DisableIrq(); + BOOL retval = FALSE; + + if( ( !nextSeq.lock ) && ( nextSeq.num != 0 ) ) { // L[bNĂ炸AŽSeq݂ȂAL[oB + *seqp = nextSeq.seq[ nextSeq.top ]; + nextSeq.num--; + nextSeq.top++; + if( nextSeq.top == PRG_NEXT_SEQ_QUE_NUM ) { + nextSeq.top = 0; + } + retval = TRUE; + } + (void)OS_RestoreIrq( preIRQ ); + return retval; +} + + +// L[bNBibNGetPrgNextSeqQueŎSeqoȂȂ܂Bj +static void LockPrgNextSeqQue(void) +{ + nextSeq.lock = TRUE; +} + + +// L[̃bNB +static void UnlockPrgNextSeqQue(void) +{ + nextSeq.lock = FALSE; +} + +// L[󂩁H +static BOOL IsEmptyPrgNextSeqQue(void) +{ + return nextSeq.num ? FALSE : TRUE; +} + + + +static const u32 searchCode[] = { + 0xe59f1028, + 0xe59f2028, + 0xe1d200b0, + 0xe2100001, + 0x1afffffc, + 0xe1d100b0, + 0xe3500006, + 0x0afffff9, + 0xe1d100b0, + 0xe3500005, + 0x0afffff6, + 0xe12fff1e, + 0x04808214, + 0x0480819c, +}; + + +void SearchPatchAddress( void ) +{ + MBDownloadFileInfo *dlfinfo = (MBDownloadFileInfo *)MB_DOWNLOAD_FILEINFO_ADDRESS; + BOOL find = FALSE; + u32 *tgtp = (u32 *)MB_ARM7_STATIC_RECV_BUFFER; + u32 size = dlfinfo->seg[ 2 ].size >> 2; + + while( size-- ) { + if( *tgtp++ == searchCode[0] ) { + u32 *srcp = (u32 *)&searchCode[ 1 ]; + u32 *checkp = tgtp ; + int i = sizeof( searchCode ) / sizeof(u32) - 1; + while( i-- ) { + if( *srcp++ != *checkp++ ) break; + } + if( i < 0 ) { + u32 addr = (u32)tgtp - 0x04 + 0x18; + OS_TPrintf("Found! -> 0x%08x\n", addr ); + find = TRUE; + } + } + } + if( !find ) { + OS_TPrintf("Not found.\n"); + } +} + diff --git a/build/systemMenu_RED/DS_DownloadPlay/ARM9/src/DS_DownloadPlay.h b/build/systemMenu_RED/DS_DownloadPlay/ARM9/src/DS_DownloadPlay.h new file mode 100644 index 0000000..1c9a8f8 --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/ARM9/src/DS_DownloadPlay.h @@ -0,0 +1,37 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: DS_DownloadPlay.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __DS_DOWNLOAD_PLAY_H__ +#define __DS_DOWNLOAD_PLAY_H__ + +#ifdef __cplusplus +extern "C" { +#endif + + +#include + +// define data---------------------------------------------------------- + +int DS_DownloadPlayMain( void ); + + +#ifdef __cplusplus +} +#endif + +#endif // __DS_DOWNLOAD_PLAY_H__ diff --git a/build/systemMenu_RED/DS_DownloadPlay/Makefile b/build/systemMenu_RED/DS_DownloadPlay/Makefile new file mode 100644 index 0000000..9cf34e1 --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/Makefile @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +SUBDIRS = banner ARM9 + +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/DS_DownloadPlay/banner/Makefile b/build/systemMenu_RED/DS_DownloadPlay/banner/Makefile new file mode 100644 index 0000000..efdcadf --- /dev/null +++ b/build/systemMenu_RED/DS_DownloadPlay/banner/Makefile @@ -0,0 +1,52 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +ICON_DIR = ./icon +TOOLS_DIR = $(TWLIPL_ROOT)/tools/bin +NTEXCONV = $(TOOLS_DIR)/ntexconv.exe +MAKEBANNER = $(TOOLS_DIR)/makebanner.exe + +BANNER_ICON = $(ICON_DIR)/gameIcon.bmp +BANNER_SPEC = banner_v3.bsf + +TARGETS = banner.bnr +INSTALL_DIR = ./ +INSTALL_TARGETS = $(TARGETS) + +BANNER_ICON_NAME = $(basename $(BANNER_ICON)) + +LDIRT_CLEAN = $(TARGETS) \ + $(BANNER_ICON_NAME).nbfs \ + $(BANNER_ICON_NAME).nbfc \ + $(BANNER_ICON_NAME).nbfp \ + $(TARGETS:.bnr=.srl) + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- +# build +#---------------------------------------------------------------------------- +do-build: $(TARGETS) + +$(TARGETS): $(BANNER_SPEC) $(BANNER_ICON) + $(NTEXCONV) -no -bg -bgb -bgnc $(BANNER_ICON) >/dev/null && \ + $(MAKEBANNER) -d -N $(BANNER_ICON_NAME) $(BANNER_SPEC) $(TARGETS) + +# diff --git a/build/systemMenu_RED/DS_DownloadPlay/banner/banner_v3.bsf b/build/systemMenu_RED/DS_DownloadPlay/banner/banner_v3.bsf new file mode 100644 index 0000000..8209887 Binary files /dev/null and b/build/systemMenu_RED/DS_DownloadPlay/banner/banner_v3.bsf differ diff --git a/build/systemMenu_RED/DS_DownloadPlay/banner/icon/gameIcon.bmp b/build/systemMenu_RED/DS_DownloadPlay/banner/icon/gameIcon.bmp new file mode 100644 index 0000000..9c18b2e Binary files /dev/null and b/build/systemMenu_RED/DS_DownloadPlay/banner/icon/gameIcon.bmp differ diff --git a/build/systemMenu_RED/Launcher/ARM9/ARM9-TS.lsf b/build/systemMenu_RED/Launcher/ARM9/ARM9-TS.lsf new file mode 100644 index 0000000..199d6f8 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/ARM9-TS.lsf @@ -0,0 +1,54 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ARM9-BB.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x02800000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) +} + + +Autoload ITCM +{ + Address 0x01ff8000 + Object * (.itcm) + Object $(OBJS_AUTOLOAD) (.text) + Object $(OBJS_AUTOLOAD) (.rodata) +} + +Autoload DTCM +{ + Address $(ADDRESS_DTCM) + Object * (.dtcm) + Object $(OBJS_AUTOLOAD) (.data) + Object $(OBJS_AUTOLOAD) (.sdata) + Object $(OBJS_AUTOLOAD) (.bss) + Object $(OBJS_AUTOLOAD) (.sbss) +} + +Ltdautoload LTDMAIN +{ + # NITRO/TWL L̃I[o[C݂ꍇ́Aɂ̌ɔzuKv܂B + After $(TARGET_NAME) + Object * (.ltdmain) + Object $(OBJS_LTDAUTOLOAD) + Library $(LLIBS_EX) $(GLIBS_EX) +} diff --git a/build/systemMenu_RED/Launcher/ARM9/Makefile b/build/systemMenu_RED/Launcher/ARM9/Makefile new file mode 100644 index 0000000..bab2460 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/Makefile @@ -0,0 +1,54 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlSDK - demos - simpleShoot-1 +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev: $ +# $Author: $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- + +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED + +TARGET_BIN = main.srl + +LCFILE_SPEC = ARM9-TS.lsf +ROM_SPEC = main.rsf + +LOGO_DIR = Logo + +SRCS_LOGO = logoDemo.c logoData.c +SRCS = main.c launcher.c misc.c $(addprefix $(LOGO_DIR)/, $(SRCS_LOGO)) +#SRCS_OVERLAY = + +LINCLUDES = $(SRCDIR)/$(LOGO_DIR) +#LLIBRARY_DIRS = +#LLIBRARIES = +#LDEPENDS_NEF = + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build : $(FONT_OBJS) $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/Launcher/ARM9/main.rsf b/build/systemMenu_RED/Launcher/ARM9/main.rsf new file mode 100644 index 0000000..ca53113 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/main.rsf @@ -0,0 +1,147 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ROM-BB.rsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL ROM SPEC FILE +# + +Arm9 +{ + Static "$(MAKEROM_ARM9:r).FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.FLX.TWL.sbin$(COMPSUFFIX9)" + Elf "$(MAKEROM_ARM9:r).tef" +} + +Arm7 +{ + Static "$(MAKEROM_ARM7_BASE:r).FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.FLX.TWL.sbin$(COMPSUFFIX7)" + Elf "$(MAKEROM_ARM7_BASE:r).tef" +} + +Arm9.Ltd +{ + Static "$(MAKEROM_ARM9:r).LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.LTD.TWL.sbin$(COMPSUFFIX9)" +} + +Arm7.Ltd +{ + Static "$(MAKEROM_ARM7_BASE:r).LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.LTD.TWL.sbin$(COMPSUFFIX7)" +} + +Property +{ + ### + ### Settings for FinalROM + ### + #### BEGIN + # + # TITLE NAME: Your product name within 12bytes + # + #TitleName "YourAppName" + + # + # MAKER CODE: Your company ID# in 2 ascii words + # issued by NINTENDO + # + #MakerCode "00" + + # + # REMASTER VERSION: Mastering version + # + #RomVersion 0 + + # + # ROM SPEED TYPE: [MROM/1TROM/UNDEFINED] + # + RomSpeedType $(MAKEROM_ROMSPEED) + + # + # ROM SIZE: in bit [64M/128M/256M/512M/1G/2G] + # + #RomSize 128M + #RomSize 256M + + # + # ROM PADDING: TRUE if finalrom + # + #RomFootPadding TRUE + + # + # ROM HEADER TEMPLATE: Provided to every product by NINTENDO + # + #RomHeaderTemplate ./etc/rom_header.template.sbin + + # + # BANNER FILE: generated from Banner Spec File + # + #BannerFile ./etc/myGameBanner.bnr + BannerFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + ### + ### Setting for TWL + ### + # + # BANNER FILE: + # + BannerTWLFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + # + # Boot allowed Media: [GameCard/NAND/SDCard/DownloadPlay] + # possible to choose one or more. + # + BootMedia GameCard NAND SDCard DownloadPlay + + # + # Certification FILE: + # + Certificate $(TWLSDK_ROOT)/include/twl/specfiles/default_sgn.sbin + + # + # Digest parameters: + # + DigestParam 1024 32 + + # + # WRAM mapping: [MAP_BB_HYB/MAP_BB_LTD/MAP_TS_HYB/MAP_TS_LTD] + # don't have to edit + # + WramMapping $(MAKEROM_WRAM_MAPPING) + + # + # Codec mode: + # don't have to edit + # + CodecMode $(MAKEROM_CODEC_MODE) + + ### + #### END +} + +RomSpec +{ + Offset 0x00000000 + Segment ALL + HostRoot ../../data + Root /data + File NTR_IPL_font_m.NFTR CardBanner.bnr DownloadBanner.bnr EmptyBanner.bnr PictoChatBanner.bnr SettingBanner.bnr +} \ No newline at end of file diff --git a/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoData.c b/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoData.c new file mode 100644 index 0000000..03fa5f1 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoData.c @@ -0,0 +1,204 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: logoData.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" + +// define data----------------------------------------------------------- +#define NIN_LOGO_LENGTH 0x9c // NintendoSf[^TCY + +#define OAM_OBJ_BLEND 0x00000400 // nai[h +#define OAM_SIZE_64x32 0xc0004000 // nai USRQhbg +#define OAM_COLOR_256 0x00002000 // QTUF I +#define OAM_AFFINE_NONE 0x00000000 // AtB[h +#define OAM_V_POS_SHIFT 0 +#define OAM_H_POS_SHIFT 16 +#define OAM_AFFINE_NO_SHIFT 25 +#define OAM_PRIORITY_SHIFT 10 +#define OAM_PLTT_SHIFT 12 + + +// extern data----------------------------------------------------------- + +// function's prototype-------------------------------------------------- +void LoadLogoData( void ); +static void UnCompNintendoLogo( u16 *NintendoLogoDatap, u16 *dstp, u32 *temp ); +static void SVC_DiffUnFilter16_16( u16 *srcp,u16 *dstp ); +static s32 MEMB_InitFunc( const u8 *devicep, void *ramp, const void *paramp ); +static s32 MEMB_TerminateFunc( const u8 *devicep ); +static u8 MEMB_ByteStreamFunc( const u8 *devicep ); +static u32 MEMB_WordStreamFunc( const u8 *devicep ); + +// global variable------------------------------------------------------- + +// static variable------------------------------------------------------- + +// const data------------------------------------------------------------ +const u32 OamLogoData[ 2 ][ 2 ] = { + { + OAM_OBJ_BLEND | OAM_SIZE_64x32 | OAM_AFFINE_NONE | OAM_COLOR_256 | + 71 << OAM_H_POS_SHIFT | + 88 << OAM_V_POS_SHIFT | + 0 << OAM_AFFINE_NO_SHIFT, + 0 << 1 | 5 << OAM_PLTT_SHIFT | 2 << OAM_PRIORITY_SHIFT + }, + + { + OAM_OBJ_BLEND | OAM_SIZE_64x32 | OAM_AFFINE_NONE | OAM_COLOR_256 | + 71 + 64 << OAM_H_POS_SHIFT | + 88 << OAM_V_POS_SHIFT | + 0 << OAM_AFFINE_NO_SHIFT, + 8 << 1 | 5 << OAM_PLTT_SHIFT | 2 << OAM_PRIORITY_SHIFT + }, +}; + +static const MIReadStreamCallbacks memb_ifp={ + MEMB_InitFunc, + MEMB_TerminateFunc, + MEMB_ByteStreamFunc, + NULL, + MEMB_WordStreamFunc, +}; + +static const MIUnpackBitsParam Nin_UnPackBitsParam={ + (8*8/2)*( 7*2), 1, 8, 0x1e, 0 +}; + +static const u8 Nin_Char_Diff_Huff_Table[] = { + 0x24,0xd4,0x00,0x00, + 0x0f,0x40,0x00,0x00,0x00,0x01,0x81,0x82,0x82,0x83,0x0f,0x83,0x0c,0xc3,0x03,0x83, + 0x01,0x83,0x04,0xc3,0x08,0x0e,0x02,0xc2,0x0d,0xc2,0x07,0x0b,0x06,0x0a,0x05,0x09, +}; + +static const u8 Nin_Char_Diff_Huff[] ATTRIBUTE_ALIGN( 2 ) = { + 0x24, 0xff, 0xae, 0x51, 0x69, 0x9a, 0xa2, 0x21, 0x3d, 0x84, 0x82, 0x0a, 0x84, 0xe4, 0x09, 0xad, + 0x11, 0x24, 0x8b, 0x98, 0xc0, 0x81, 0x7f, 0x21, 0xa3, 0x52, 0xbe, 0x19, 0x93, 0x09, 0xce, 0x20, + 0x10, 0x46, 0x4a, 0x4a, 0xf8, 0x27, 0x31, 0xec, 0x58, 0xc7, 0xe8, 0x33, 0x82, 0xe3, 0xce, 0xbf, + 0x85, 0xf4, 0xdf, 0x94, 0xce, 0x4b, 0x09, 0xc1, 0x94, 0x56, 0x8a, 0xc0, 0x13, 0x72, 0xa7, 0xfc, + 0x9f, 0x84, 0x4d, 0x73, 0xa3, 0xca, 0x9a, 0x61, 0x58, 0x97, 0xa3, 0x27, 0xfc, 0x03, 0x98, 0x76, + 0x23, 0x1d, 0xc7, 0x61, 0x03, 0x04, 0xae, 0x56, 0xbf, 0x38, 0x84, 0x00, 0x40, 0xa7, 0x0e, 0xfd, + 0xff, 0x52, 0xfe, 0x03, 0x6f, 0x95, 0x30, 0xf1, 0x97, 0xfb, 0xc0, 0x85, 0x60, 0xd6, 0x80, 0x25, + 0xa9, 0x63, 0xbe, 0x03, 0x01, 0x4e, 0x38, 0xe2, 0xf9, 0xa2, 0x34, 0xff, 0xbb, 0x3e, 0x03, 0x44, + 0x78, 0x00, 0x90, 0xcb, 0x88, 0x11, 0x3a, 0x94, 0x65, 0xc0, 0x7c, 0x63, 0x87, 0xf0, 0x3c, 0xaf, + 0xd6, 0x25, 0xe4, 0x8b, 0x38, 0x0a, 0xac, 0x72, 0x21, 0xd4, 0xf8, 0x07, 0x56, 0xcf, 0x00, 0x00, +}; + + +// ============================================================================ +// Sf[^[h +// ============================================================================ +void LoadLogoData(void) +{ + u32 temp[ 0x500 / sizeof(u32) ]; + u16 *pBuff = NNS_FndAllocFromAllocator( &g_allocator, 0x1000 ); + MI_CpuClear32( pBuff, 0x1000 ); + + if( pBuff == NULL ) { + OS_TPrintf( " %s : memory allocate error.\n", __FUNCTION__ ); + return; + } + + UnCompNintendoLogo( (u16 *)Nin_Char_Diff_Huff, pBuff, temp ); // NintendoSpBuffɓWJ + MI_CpuCopy32( pBuff, (u32 *)HW_OBJ_VRAM, 0x340 ); // OBJ-VRAMɃ[h + MI_CpuCopy32( (void *)( (u32)pBuff + 0x340 ), (u32 *)( HW_OBJ_VRAM + 0x400 ), 8*8*13 ); + + *(vu16 *)( HW_OBJ_PLTT + 0x3e ) = 0x0000; // OBJpbgZbg + *(vu16 *)HW_BG_PLTT = 0xffff; // obNhbvuvɂB + + MI_CpuCopy32( OamLogoData, (u32 *)HW_OAM, sizeof(OamLogoData) ); // NintendoSpOAMf[^Zbg + NNS_FndFreeToAllocator( &g_allocator, pBuff ); +} + + +//@NintendoSWJ[`@(r0=Skf[^ r1=WJAhX) +#include + +asm void UnCompNintendoLogo(u16 *NintendoLogoDatap, u16 *dstp, u32 *temp) +{ + push {r0-r2,r4, lr} + + ldr r0, =Nin_Char_Diff_Huff_Table + mov r2, #0x0e + lsl r2, r2, #8 + add r1, r1, r2 // P+0xe00 + mov r4, r1 + mov r2, #36 + bl MIi_CpuCopy16 // NintendoS̈ke[û݂Rs[Ă + + ldr r0, [sp, #0] // OiNinLogoBak[36]) + mov r2, #36 + add r1, r4, r2 // P+0xe00+36 + mov r2, #NIN_LOGO_LENGTH + bl MIi_CpuCopy16 // ONintendoSf[^{̂Rs[Ă + + mov r0, r4 // P+0xe00 + ldr r1, [sp, #4] // P + ldr r2, [sp, #8] // Q + ldr r3, =memb_ifp + bl SVC_UncompressHuffmanFromDevice // nt}WJ + + ldr r0, [sp, #4] + ldr r2, =0x0000d082 + str r2, [r0,#0] + + mov r1, r4 // P+0xe00 + bl SVC_DiffUnFilter16_16 // DiffWJ + + mov r0, r4 // P+0xe00 + ldr r1, [sp, #4] // P + ldr r2, =Nin_UnPackBitsParam + bl SVC_UnpackBits // rbgWJ + + pop {r0-r2,r4, pc} +} + + +// tB^WJVXeR[i16Bit16Bitj (r0=Srcp, r1=Destp) +static asm void SVC_DiffUnFilter16_16(u16 *srcp,u16 *dstp) +{ + swi 24 + bx lr +} +#include + + +// ============================================================================ +// oCgANZX”\pANZX[`Q +// ============================================================================ +static s32 MEMB_InitFunc(const u8 *devicep, void *ramp, const void *paramp) +{ +#pragma unused(ramp) + if(paramp) return (s32)MEMB_WordStreamFunc(devicep); + else return 0; +} + +static s32 MEMB_TerminateFunc(const u8 *devicep) +{ +#pragma unused(devicep) + return 0; +} + +static u8 MEMB_ByteStreamFunc(const u8 *devicep) +{ + return *devicep; +} + +static u32 MEMB_WordStreamFunc(const u8 *devicep) +{ + return *(u32 *)devicep; +} + diff --git a/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoDemo.c b/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoDemo.c new file mode 100644 index 0000000..91467d7 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoDemo.c @@ -0,0 +1,131 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: logoDemo.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include "logoDemo.h" + +// define data-------------------------------------------------------- + +#define LOGO_DISP_FRAME 60 // S\t[ + +// S\Xe[^X\ +typedef struct LogoStatus { + s32 state; + BOOL enable; + s32 value_A; + s32 value_B; + s32 mainCounter; +}LogoStatus; + +// extern data-------------------------------------------------------- +extern void LoadLogoData( void ); + +// function's prototype----------------------------------------------- + +// static variables--------------------------------------------------- +static LogoStatus s_logo = { 0, TRUE, 0, 0, 0 }; + +// const data--------------------------------------------------------- + +static void LogoInit( void ) +{ + // OFF + GX_DispOff(); + GXS_DispOff(); + + // VRAM蓖āNA + GX_SetBankForOBJ( GX_VRAM_OBJ_128_A ); // @V@@@@@OBJp + GX_SetGraphicsMode( GX_DISPMODE_GRAPHICS, GX_BGMODE_0, GX_BG0_AS_2D ); + MI_CpuClearFast( (void *)HW_OBJ_VRAM, 0x1000 ); // OBJ-VRAM NA + MI_DmaFill32( 3, (void *)HW_OAM, 192, HW_OAM_SIZE ); // OAM NA + + // ʐݒ + GX_SetGraphicsMode( GX_DISPMODE_GRAPHICS, GX_BGMODE_2, GX_BG0_AS_2D ); + GX_SetOBJVRamModeChar( GX_OBJVRAMMODE_CHAR_2D ); + G2_SetBlendAlpha( GX_BLEND_PLANEMASK_OBJ, GX_BLEND_PLANEMASK_BD, s_logo.value_A, s_logo.value_B ); + GX_SetVisiblePlane( GX_PLANEMASK_OBJ ); + + // Sf[^[h + LoadLogoData(); + + s_logo.value_A = 0; + s_logo.value_B = 16; + G2_ChangeBlendAlpha( s_logo.value_A, s_logo.value_B ); + + // Cʂ̂ON + GX_DispOn(); +} + + +// SC +int LogoMain() +{ + if( !IsLogoEnable() ) { + return 1; + } + + switch( s_logo.state ) { + case 0: // ݒ + LogoInit(); + + s_logo.mainCounter = 0; + s_logo.state++; + break; + + case 1: // NintendoStF[hC + if( s_logo.mainCounter++ < 16 ){ // Nintendoۺ \ + G2_ChangeBlendAlpha( ++s_logo.value_A, --s_logo.value_B ); + }else { + s_logo.mainCounter = 0; + s_logo.state++; + } + break; + + + case 2: // NintendoS\ + if( s_logo.mainCounter++ == LOGO_DISP_FRAME ) { + s_logo.mainCounter = 0; + s_logo.state++; + } + break; + + case 3: // NintendoStF[hAEg + if( s_logo.mainCounter++ < 16 ) { + G2_ChangeBlendAlpha( --s_logo.value_A, ++s_logo.value_B ); + }else { + return 1; + } + break; + + default: + break; + } + + return 0; +} + + +// S\OFFɂB +void SetLogoEnable( BOOL enable ) +{ + s_logo.enable = enable; +} + +// S\Ԏ擾 +BOOL IsLogoEnable(void) +{ + return s_logo.enable; +} diff --git a/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoDemo.h b/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoDemo.h new file mode 100644 index 0000000..3923a33 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/Logo/logoDemo.h @@ -0,0 +1,35 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: logoDemo.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef _LOGO_DEMO_H +#define _LOGO_DEMO_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern int LogoMain( void ); +extern void SetLogoEnable( BOOL enable ); +extern BOOL IsLogoEnable( void ); + +#ifdef __cplusplus +} +#endif + +#endif /* _LOGO_DEMO_H */ diff --git a/build/systemMenu_RED/Launcher/ARM9/src/launcher.c b/build/systemMenu_RED/Launcher/ARM9/src/launcher.c new file mode 100644 index 0000000..5581150 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/launcher.c @@ -0,0 +1,388 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: launcher.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "launcher.h" + + +// define data------------------------------------------ +#define LAUNCHER_ELEMENT_NUM 4 // Sj[̍ڐ + +#define B_LIGHT_BUTTON_TOP_X 24 +#define B_LIGHT_BUTTON_TOP_Y 21 +#define B_LIGHT_BUTTON_BOTTOM_X ( B_LIGHT_BUTTON_TOP_X + 7 ) +#define B_LIGHT_BUTTON_BOTTOM_Y ( B_LIGHT_BUTTON_TOP_Y + 2 ) + + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- +static void DrawBackLightSwitch(void); +static void DrawLauncher(u16 nowCsr, const MenuParam *pMenu); + +// global variable ------------------------------------- + +// static variable ------------------------------------- +static int s_csr = 0; // j[̃J[\ʒu +static const u16 *s_pStrLauncher[ LAUNCHER_ELEMENT_NUM ]; // Sj[pe[uւ̃|C^Xg + +// const data ----------------------------------------- +//=============================================== +// Launcher.c +//=============================================== +static const u16 *const s_pStrLauncherElemTbl[ LAUNCHER_ELEMENT_NUM ][ LANG_CODE_MAX ] = { + { + (const u16 *)L"DSJ[h", + (const u16 *)L"DS Card", + (const u16 *)L"DS Card(F)", + (const u16 *)L"DS Card(G)", + (const u16 *)L"DS Card(I)", + (const u16 *)L"DS Card(S)", + }, + { + (const u16 *)L"sNg`bg", + (const u16 *)L"PictoChat", + (const u16 *)L"PictoChat(F)", + (const u16 *)L"PictoChat(G)", + (const u16 *)L"PictoChat(I)", + (const u16 *)L"PictoChat(S)", + }, + { + (const u16 *)L"DS_E[hvC", + (const u16 *)L"DS Download Play", + (const u16 *)L"DS Download Play(F)", + (const u16 *)L"DS Download Play(G)", + (const u16 *)L"DS Download Play(I)", + (const u16 *)L"DS Download Play(S)", + }, + { + (const u16 *)L"{̐ݒ", + (const u16 *)L"Machine Settings", + (const u16 *)L"Machine Settings(F)", + (const u16 *)L"Machine Settings(G)", + (const u16 *)L"Machine Settings(I)", + (const u16 *)L"Machine Settings(S)", + }, +}; + +static MenuPos s_launcherPos[] = { + { TRUE, 4 * 8, 8 * 8 }, + { TRUE, 4 * 8, 10 * 8 }, + { TRUE, 4 * 8, 12 * 8 }, + { TRUE, 4 * 8, 14 * 8 }, + { TRUE, 4 * 8, 16 * 8 }, +}; + +static const MenuParam s_launcherParam = { + LAUNCHER_ELEMENT_NUM, + TXT_COLOR_BLACK, + TXT_COLOR_GREEN, + TXT_COLOR_RED, + &s_launcherPos[0], + (const u16 **)&s_pStrLauncher, +}; + +static const u16 *const str_backlight[] = { + (const u16 *)L"BLT:ON ", + (const u16 *)L"BLT:OFF", +}; + +//====================================================== +// `[ +//====================================================== + +// oi[\֌Wibj +#define DBGBNR +#ifdef DBGBNR + +static const u8 TITLE_PROPERTY_NUM = 40; +static BannerFile *empty_banner; +static BannerFile *card_banner; +static BannerFile *pictochat_banner; +static BannerFile *download_banner; +static BannerFile *setting_banner; +static TitleProperty tp[TITLE_PROPERTY_NUM]; +static u8 image_index_list[TITLE_PROPERTY_NUM]; +static const int MAX_SHOW_BANNER = 6; +static GXOamAttr banner_oam_attr[MAX_SHOW_BANNER]; +static u8 *pbanner_image_list[TITLE_PROPERTY_NUM*2]; +static int banner_count = 0; + +static void LoadBannerFiles() +{ + // t@CǂݍݕBemptyoi[ǂݍގɂȂB{AAvn͊O擾 + // ŌɉȂƑʖځBAǂʼn΂̂cc + u32 size = CMN_LoadFile( (void **)&empty_banner, "data/EmptyBanner.bnr", &g_allocator); + NNS_G2D_ASSERT( size > 0 ); + size = CMN_LoadFile( (void **)&card_banner, "data/CardBanner.bnr", &g_allocator); + NNS_G2D_ASSERT( size > 0 ); + size = CMN_LoadFile( (void **)&pictochat_banner, "data/PictochatBanner.bnr", &g_allocator); + NNS_G2D_ASSERT( size > 0 ); + size = CMN_LoadFile( (void **)&download_banner, "data/DownloadBanner.bnr", &g_allocator); + NNS_G2D_ASSERT( size > 0 ); + size = CMN_LoadFile( (void **)&setting_banner, "data/SettingBanner.bnr", &g_allocator); + NNS_G2D_ASSERT( size > 0 ); +} + +// pbg̓ǂݍ݂OBJ֌W̏ +static void BannerInit() +{ + int l; + LoadBannerFiles(); + + // łׂȂCBGOBJ̐ݒ + GX_SetVisiblePlane(GX_PLANEMASK_OBJ | GX_PLANEMASK_BG0); // display only OBJ&BG0 + GX_SetOBJVRamModeChar(GX_OBJVRAMMODE_CHAR_1D_128K); // 2D mapping mode + + // pbgǂݍ + GX_LoadOBJPltt( empty_banner->v1.pltt, 0, BNR_PLTT_SIZE ); + + //OBJATTȐccŒlMďꏊLN^[ς肷 + for(l=0;lv1.image; + for(m=0;mv1.gameName[GetNCDWork()->option.language]; + int width = NNS_G2dTextCanvasGetStringWidth(&gTextCanvas, str, NULL); + PutStringUTF16( (256-width)/2, 48, TXT_COLOR_BLACK, str ); + } +} + +#endif //DBGBNR + + +// `[̏ +void LauncherInit( TitleProperty *pTitleList ) +{ +#pragma unused( pTitleList ) + + int i; + GX_DispOff(); + GXS_DispOff(); + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + + DrawBackLightSwitch(); + + PrintfSJIS( 0, 0, TXT_COLOR_BLUE, "TWL-SYSTEM MENU ver.%06x", SYSMENU_VER ); + + // NITROݒf[^languageɉCj[\̐؂ւ + for( i = 0; i < LAUNCHER_ELEMENT_NUM; i++ ) { + s_pStrLauncher[ i ] = s_pStrLauncherElemTbl[ i ][ GetNCDWork()->option.language ]; + } + + if( !SYSM_IsNITROCard() ) { + s_launcherPos[ 0 ].enable = FALSE; // DSJ[h́A擪vf𖳌ɂB + } + + //DrawMenu( s_csr, &s_launcherParam ); + + SVC_CpuClear( 0x0000, &tpd, sizeof(TpWork), 16 ); + + InitGetAndDrawRtcData( RTC_DATE_TOP_X, RTC_DATE_TOP_Y, RTC_TIME_TOP_X, RTC_TIME_TOP_Y ); + + GX_SetVisiblePlane( GX_PLANEMASK_BG0 ); + GX_DispOn(); + GXS_DispOn(); + + #ifdef DBGBNR + BannerInit(); + #endif +} + + +// `[C +TitleProperty *LauncherMain( TitleProperty *pTitleList ) +{ +#pragma unused( pTitleList ) + + static BOOL touch_bl = FALSE; + BOOL tp_bl_on_off = FALSE; + BOOL tp_select = FALSE; + static int csr_v = 0; + static int selected = 0; + + // `NA + NNS_G2dCharCanvasClear(&gCanvas,TXT_COLOR_WHITE); + + PrintfSJIS( 0, 0, TXT_COLOR_BLUE, "TWL-SYSTEM MENU ver.%06x", SYSMENU_VER ); + DrawBackLightSwitch(); + + // RTC̎擾\ + GetAndDrawRtcData(); + + //-------------------------------------- + // obNCgON,OFF + //-------------------------------------- + if(tpd.disp.touch) { + BOOL range = InRangeTp( B_LIGHT_BUTTON_TOP_X*8, B_LIGHT_BUTTON_TOP_Y*8-4, + B_LIGHT_BUTTON_BOTTOM_X*8, B_LIGHT_BUTTON_BOTTOM_Y*8-4, &tpd.disp ); + if( range && !touch_bl ) { + touch_bl = TRUE; + tp_bl_on_off = TRUE; + } + }else { + touch_bl = FALSE; + } + + if( (pad.trg & PAD_BUTTON_R) || (tp_bl_on_off) ) { + GetNCDWork()->option.backLightOffFlag ^= 0x01; + DrawBackLightSwitch(); + } + + //-------------------------------------- + // L[͏ + //-------------------------------------- + if(pad.cont & PAD_KEY_RIGHT){ // oi[I + if(csr_v == 0) csr_v = 1; + } + if( pad.cont & PAD_KEY_LEFT ){ + if(csr_v == 0) csr_v = -1; + } + s_csr += csr_v; + if((TITLE_PROPERTY_NUM-1)*12 < s_csr) s_csr = (TITLE_PROPERTY_NUM-1)*12; + if( s_csr < 0 ) s_csr = 0; + if(s_csr%12 == 0){ + csr_v = 0; + selected = s_csr/12; + } + // tp_select = SelectMenuByTP( &s_csr, &s_launcherParam ); + + // DrawMenu( s_csr, &s_launcherParam ); + + #ifdef DBGBNR + BannerDraw( s_csr, selected, NULL ); + #endif + + if( ( pad.trg & PAD_BUTTON_A ) || ( tp_select ) ) { // j[ڂւ̕ + if( s_launcherPos[ 0 ].enable ) { + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + return NULL; + } + } + + return NULL; +} + +#if 0 +// `[` +static void DrawLauncher(u16 nowCsr, const MenuParam *pMenu) +{ + int i; + int color; + + for( i = 0; i < pMenu->num; i++ ) { + if(i == nowCsr) { + if( !pMenu->pos[ i ].enable ) { + color = pMenu->disable_color; + }else { + color = pMenu->select_color; + } + }else { + color = pMenu->normal_color; + } + PutStringUTF16( pMenu->pos[ i ].x, pMenu->pos[ i ].y, color, (pMenu->str_elem)[ i ] ); + } +} +#endif + +// obNCgXCb`̕\ +static void DrawBackLightSwitch(void) +{ + u16 color; + + if( GetNCDWork()->option.backLightOffFlag ) { + color = TXT_COLOR_BLACK; + }else { + color = TXT_COLOR_RED; + } + + PutStringUTF16( B_LIGHT_BUTTON_TOP_X, B_LIGHT_BUTTON_TOP_Y, color, + str_backlight[ GetNCDWork()->option.backLightOffFlag ] ); +} + diff --git a/build/systemMenu_RED/Launcher/ARM9/src/launcher.h b/build/systemMenu_RED/Launcher/ARM9/src/launcher.h new file mode 100644 index 0000000..fd63c32 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/launcher.h @@ -0,0 +1,41 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: launcher.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __LAUNCHER_H__ +#define __LAUNCHER_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// define data---------------------------------------------------------- + +// global variables-------------------------------------------------- + +// function------------------------------------------------------------- +void LauncherInit( TitleProperty *pTitleList ); +TitleProperty *LauncherMain( TitleProperty *pTitleList ); + + +#ifdef __cplusplus +} +#endif + +#endif // __LAUNCHER_H__ diff --git a/build/systemMenu_RED/Launcher/ARM9/src/main.c b/build/systemMenu_RED/Launcher/ARM9/src/main.c new file mode 100644 index 0000000..6d7dc10 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/main.c @@ -0,0 +1,434 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "launcher.h" +#include "misc.h" +#include "logoDemo.h" + +// extern data----------------------------------------------------------------- + +// define data----------------------------------------------------------------- + +// function's prototype------------------------------------------------------- +static void InitAllocator( NNSFndAllocator* pAllocator ); +static void InitAllocSystem( void ); +static BOOL CheckBootStatus( void ); +static void INTR_VBlank( void ); + +// global variable------------------------------------------------------------- +NNSFndAllocator g_allocator; + +// static variable------------------------------------------------------------- +static BannerFile banner; // oi[f[^ + +// const data------------------------------------------------------------------ + +#if 1 + +typedef struct CardStatus { + u16 primarySlot; // PULLOUT, DETECT, VALID, INVALID + u16 secondarySlot; // B +}CardStatus; + + +void TwlMain( void ) +{ + enum { + START = 0, + LOGODEMO = 1, + LAUNCHER_INIT = 2, + LAUNCHER = 3, + AUTHENTICATE = 4, + BOOT = 5, + STOP = 6 + }; + u32 state = START; + TitleProperty *pBootTitle = NULL; + TitleProperty *pTitleList = NULL; + + OS_Init(); + + (void)OS_EnableIrq(); + (void)OS_EnableInterrupts(); + + FS_Init( FS_DMA_NOT_USE ); + GX_Init(); + + // 荞݋-------------------- + (void)OS_SetIrqFunction(OS_IE_V_BLANK, INTR_VBlank); + (void)OS_EnableIrqMask(OS_IE_V_BLANK); + (void)GX_VBlankIntr(TRUE); + + // VXej[---------- + SYSM_Init(); // OS_IniťŃR[B + + // VXȅ---------------- + InitAllocator( &g_allocator ); + CMN_InitFileSystem( &g_allocator ); + + // Zbgp[^̎擾-------- + if( SYSM_GetResetParam()->isLogoSkip ) { + if( SYSM_GetResetParam()->bootTitleID ) { // AvڋN̎w肪烍Sf΂ĎwAvN + pBootTitle = (TitleProperty *)SYSM_GetResetParam(); + state = AUTHENTICATE; + }else { // ȊȌꍇ́ASf΂ă`[N + state = LAUNCHER_INIT; + } + } + + // Regi\[Xjt@C̃[h +// FS_ReadContentFile( ContentID ); + + // LRegt@C̃[h +// FS_ReadSharedContentFile( ContentID ); + + // NANDAvXg̎擾---------- + (void)SYSM_GetNandTitleList( pTitleList ); + + while( 1 ) { + OS_WaitIrq(1, OS_IE_V_BLANK); // VuN荞ݑ҂ + + ReadKeyPad(); // L[͂̎擾 + ReadTpData(); // TP͂̎擾 + + (void)SYSM_GetCardTitleList( pTitleList ); // J[hAvXg̎擾iXbhŐJ[h}ʒm̂C[vŎ擾j + + switch( state ) { + case START: + state = LOGODEMO; + break; + case LOGODEMO: + if( LogoMain() ) { + state = LAUNCHER_INIT; + } + break; + case LAUNCHER_INIT: + InitBG(); // BG + LauncherInit( pTitleList ); + state = LAUNCHER; + break; + case LAUNCHER: + pBootTitle = LauncherMain( pTitleList ); + if( pBootTitle ) { + state = AUTHENTICATE; + } + break; + case AUTHENTICATE: + switch ( SYSM_LoadAndAuthenticateTitle( pBootTitle ) ) { // Av[hF + case AUTH_PROCESSING: + break; + case AUTH_RESULT_SUCCEEDED: + state = BOOT; + break; + case AUTH_RESULT_TITLE_POINTER_ERROR: + case AUTH_RESULT_AUTHENTICATE_FAILED: + case AUTH_RESULT_ENTRY_ADDRESS_ERROR: + state = STOP; + break; + } + break; + case BOOT: + SYSM_Finalize(); // I + return; + case STOP: // ~ + break; + } + } +} +#endif + + +// ============================================================================ +// function's description +// ============================================================================ +/* +void TwlMain(void) +{ + typedef enum PrgState { + STATE_START = 1, + STATE_LOGO_DISP, + STATE_LOGO_MENU, + STATE_WAIT_BOOT + }PrgState; + + PrgState prg_state = STATE_START; + BOOL boot_decision = FALSE; + + // ---------------------------------- + SYSM_Init(); // VXej[֘Af[^̏iTwlMain̐擪ŃR[ĉBj + + OS_Init(); + + (void)OS_EnableIrq(); + (void)OS_EnableInterrupts(); + + FS_Init( FS_DMA_NOT_USE ); + GX_Init(); + GX_SetPower(GX_POWER_ALL); // eWbN p[ON + + // 荞݋---------------------------- + (void)OS_SetIrqFunction(OS_IE_V_BLANK, INTR_VBlank); + (void)OS_EnableIrqMask(OS_IE_V_BLANK); + (void)GX_VBlankIntr(TRUE); + + // foCX------------------------------- +#ifndef __TP_OFF + TP_Init(); +#endif + (void)RTC_Init(); + + // VXȅ------------------ + InitAllocator( &g_allocator ); + CMN_InitFileSystem( &g_allocator ); + +// InitAllocSystem(); + + // ARM7҂-------------------------- +// if( SYSM_WaitARM7Init() ) { // ARM7̏Î҂Ă烁C[vJn +// return; // TRUEԂꂽAfobKu[gȂ̂Ń^[ +// } + + // C[v---------------------------- + while(1){ + OS_WaitIrq(1, OS_IE_V_BLANK); // VuN荞ݑ҂ + ReadKeyPad(); // L[͂̎擾 + + if(SYSM_IsTPReadable()) { + ReadTpData(); // TP͂̎擾 + } + +// if(SYSM_Main()) { // IPL2VXẽC +// return; // TRUEAĂ烁C[v烊^[iNITROQ[Nj +// } + + switch(prg_state) { + case STATE_START: + boot_decision = CheckBootStatus(); // u[gԂ`FbNBiV[gJbgNRpCXCb`ɂ鋭Nj +// if( !SYSM_GetBannerFile( &banner ) ) { // oi[f[^̃[h +// OS_Printf("ROM banner data read failed.\n"); +// } + prg_state = STATE_LOGO_DISP; + break; + + //----------------------------------- + // NITROS\ + //----------------------------------- + case STATE_LOGO_DISP: + if( LogoMain() ) { // S\[`iBFLG_GAMEBOY_LOGO_OFF̎͑Ij + InitBG(); // BG + LauncherInit(); // u[g莞̂݃Sj[B + + prg_state = STATE_LOGO_MENU; + } + break; // NITROJ[hłȂꍇ́Â܂ܖ[vB + + //----------------------------------- + // Sj[ŋN[hI + //----------------------------------- + case STATE_LOGO_MENU: + { + IPL2BootType command = LauncherMain( boot_decision ); + + switch(command) { + case BOOT_TYPE_UNSOLVED: + break; + + case BOOT_TYPE_NITRO: +// if( !SYSM_BootNITRO() ) { +// (void)DrawStringSJIS( 4, 20, RED, (const u8 *)"This NITRO card is invalid!!"); +// } + break; + + case BOOT_TYPE_PICT_CHAT: +// (void)SYSM_BootPictChat(); + break; + + case BOOT_TYPE_WIRELESS_BOOT: +// (void)SYSM_BootDSDownloadPlay(); + break; + + case BOOT_TYPE_BMENU: +// (void)SYSM_BootMachineSetting(); + break; + + default: + OS_Panic( "ERROR: boot code failed : %d\n", command ); + } + if(command) { + prg_state = STATE_WAIT_BOOT; + } + } + break; + case STATE_WAIT_BOOT: +// SYSM_PermitToBootSelectedTarget(); + break; + } + + if ( PAD_DetectFold() == TRUE ) { // X[v[hւ̑J +// SYSM_FinalizeCardPulledOut(); + SYSM_GoSleepMode(); +// (void)SYSM_IsCardPulledOut(); // J[hoR}hs +// SYSM_FinalizeCardPulledOut(); + // J[ho +// if ( SYSM_IsCardPulledOut() ) { + if ( 0 ) { + (void)PM_ForceToPowerOff(); + } + } + +// if (SYSM_IsCardPulledOut()) { // J[ho + if ( 0 ) { + OS_Printf("Card is pulled out.\n"); + OS_Terminate(); + } + + OS_PrintServer(); // ARM7̃vgfobO + + //---- BG-VRAM̍XV +// DC_FlushRange ( bgBakS, sizeof(bgBakS) ); +// MI_CpuCopyFast( bgBakS, (void*)(HW_DB_BG_VRAM+0xf000), sizeof(bgBakS) ); + } +} +*/ + + +// AP[^̏ +static void InitAllocator( NNSFndAllocator* pAllocator ) +{ + u32 arenaLow = MATH_ROUNDUP ((u32)OS_GetMainArenaLo(), 16); + u32 arenaHigh = MATH_ROUNDDOWN((u32)OS_GetMainArenaHi(), 16); + u32 heapSize = arenaHigh - arenaLow; + void* heapMemory = OS_AllocFromMainArenaLo(heapSize, 16); + NNSFndHeapHandle heapHandle; + SDK_NULL_ASSERT( pAllocator ); + + heapHandle = NNS_FndCreateExpHeap(heapMemory, heapSize); + SDK_ASSERT( heapHandle != NNS_FND_HEAP_INVALID_HANDLE ); + + NNS_FndInitAllocatorForExpHeap(pAllocator, heapHandle, 4); +} + +#if 0 +// mallocVXȅ +static void InitAllocSystem(void) +{ + void* tempLo; + OSHeapHandle hh; + + tempLo = OS_InitAlloc(OS_ARENA_MAIN, OS_GetMainArenaLo(), OS_GetMainArenaHi(), 16); + OS_SetArenaLo(OS_ARENA_MAIN, tempLo); + OS_TPrintf( "ArenaLo : %08x ArenaHi : %08x\n", OS_GetMainArenaLo(), OS_GetMainArenaHi() ); + + hh = OS_CreateHeap(OS_ARENA_MAIN, OS_GetMainArenaLo(), OS_GetMainArenaHi()); + if(hh < 0) { + OS_Panic("ARM9: Fail to create heap...\n"); + } + hh = OS_SetCurrentHeap(OS_ARENA_MAIN, hh); +} +#endif + +// u[gԂmFAS\L𔻒f------- +static BOOL CheckBootStatus(void) +{ + BOOL boot_decision = FALSE; // uu[gev + BOOL other_shortcut_off = FALSE; + + //----------------------------------------------------- + // fobOpRpCXCb`ɂ鋓 + //----------------------------------------------------- + { +#ifdef __FORCE_BOOT_BMENU // u[gj[NXCb`ONH + SYSM_SetBootFlag( BFLG_BOOT_BMENU ); + return TRUE; // uu[gevŃ^[ +#endif /* __FORCE_BOOT_BMENU */ + +#ifdef __LOGO_SKIP // fobOpSXLbv + SetLogoEnable( FALSE ); // S\XLbv +#endif /* __LOGO_SKIP */ + } + + + //----------------------------------------------------- + // NITROݒf[^͎̐ݒ胁j[V[gJbgN + //----------------------------------------------------- +#ifdef __DIRECT_BOOT_BMENU_ENABLE // NITROݒf[^͎̃u[gj[ڋNXCb`ONH + if( ( (GetNCDWork()->option.input_tp == 0) + ||(GetNCDWork()->option.input_language == 0) + ||(GetNCDWork()->option.input_rtc == 0) + ||(GetNCDWork()->option.input_favoriteColor == 0) + ||(GetNCDWork()->option.input_nickname == 0) ) ) { // TP,,RTC,jbNl[ZbgĂȂ΁AS\Q[[hs킸Au[gj[V[gJbgNB + + if( ( pad.cont & PAD_PRODUCTION_NITRO_SHORTCUT ) == PAD_PRODUCTION_NITRO_SHORTCUT ) { + other_shortcut_off = TRUE; // ʎYHp̃L[V[gJbgĂAݒ胁j[N͂ȂB + }else if( !SYSM_IsInspectNITROCard() ) { // AAʎYp̃L[V[gJbgĂ鎞ANITROJ[hĂ鎞́Au[gj[ւ̃V[gJbgN͍sȂB + SYSM_SetBootFlag( BFLG_BOOT_BMENU ); + SetLogoEnable( FALSE ); + return TRUE; // uu[gevŃ^[ + } + } +#endif /* __DIRECT_BOOT_BMENU_ENABLE */ + + + //----------------------------------------------------- + // L[V[gJbgN + //----------------------------------------------------- + if( !other_shortcut_off && !GetNCDWork()->option.autoBootFlag ) { + // V[gJbgONƒI[gNOFF̎ + u32 nowBootFlag = 0; + + if(pad.cont & PAD_BUTTON_R){ // R{^NȂAS\ȂAGBQ[ + SetLogoEnable( FALSE ); + nowBootFlag = BFLG_BOOT_AGB; + }else if(pad.cont & PAD_BUTTON_L){ // L{^NȂAS\NITROQ[ + nowBootFlag = BFLG_BOOT_NITRO; + }else if(pad.cont & PAD_BUTTON_B){ // B{^NȂAS\Ƀu[gj[ + nowBootFlag = BFLG_BOOT_BMENU; + } + if( nowBootFlag ) { + SYSM_SetBootFlag( nowBootFlag ); + return TRUE; // uu[gevŃ^[ + } + } + + + //----------------------------------------------------- + // NIvVL̋ + //----------------------------------------------------- +#ifndef __SYSM_DEBUG + if( GetNCDWork()->option.autoBootFlag ) { + if ( SYSM_IsNITROCard() ) { // NITROJ[ĥ݂̎NITRON + SYSM_SetBootFlag( BFLG_BOOT_NITRO ); + return TRUE; // uu[gevŃ^[ + } + } +#endif /* __SYSM_DEBUG */ + + return FALSE; // uu[gevŃ^[ +} + + +// ============================================================================ +// 荞ݏ +// ============================================================================ + +// VuN荞 +static void INTR_VBlank(void) +{ + OS_SetIrqCheckFlag(OS_IE_V_BLANK); // VuN`FbÑZbg +} + diff --git a/build/systemMenu_RED/Launcher/ARM9/src/misc.c b/build/systemMenu_RED/Launcher/ARM9/src/misc.c new file mode 100644 index 0000000..f92abe4 --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/misc.c @@ -0,0 +1,588 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: misc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" + +// define data----------------------------------------------------------------- +#define NTR_IPL_FONT_DATA "data/NTR_IPL_font_m.NFTR" + +#define STRING_LENGTH_MAX 256 + +#define GRAY(x) GX_RGB(x, x, x) + +enum +{ + TXT_CPALETTE_MAIN, + TXT_CPALETTE_USERCOLOR, + TXT_CPALETTE_4BPP, + TXT_NUM_CPALEETE +}; + +// fʂ̃J[pbg +GXRgb TXTColorPalette[TXT_NUM_CPALEETE * 16] = +{ + GX_RGB(31, 31, 31), GX_RGB(31, 31, 31), GX_RGB( 0, 0, 0), GX_RGB(31, 0, 0), + GX_RGB( 0, 31, 0), GX_RGB( 0, 0, 31), GX_RGB( 0, 31, 31), GX_RGB(31, 0, 31), + GX_RGB(31, 31, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), + GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), + + GX_RGB( 0, 0, 0), GX_RGB(12, 16, 19), GX_RGB(23, 9, 0), GX_RGB(31, 0, 3), + GX_RGB(31, 17, 31), GX_RGB(31, 18, 0), GX_RGB(30, 28, 0), GX_RGB(21, 31, 0), + GX_RGB( 0, 20, 7), GX_RGB( 9, 27, 17), GX_RGB( 6, 23, 30), GX_RGB( 0, 11, 30), + GX_RGB( 0, 0, 18), GX_RGB(17, 0, 26), GX_RGB(26, 0, 29), GX_RGB(31, 0, 18), + + GRAY(31), GRAY(29), GRAY(27), GRAY(25), + GRAY(23), GRAY(21), GRAY(19), GRAY(17), + GRAY(15), GRAY(14), GRAY(12), GRAY(10), + GRAY( 8), GRAY( 6), GRAY( 3), GRAY( 0), +}; + +// extern data----------------------------------------------------------------- + +// define data----------------------------------------------------------------- +#define CANVAS_WIDTH 32 // `̕ (LN^P) +#define CANVAS_HEIGHT 24 // `̍ (LN^P) +#define CANVAS_LEFT 0 // `̈ʒuX (LN^P) +#define CANVAS_TOP 0 // `̈ʒuY (LN^P) + +#define TEXT_HSPACE 1 // `掞̕ (sNZP) +#define TEXT_VSPACE 1 // `掞̍s (sNZP) + +#define CHARACTER_OFFSET 0 // gpLN^̊Jnԍ + +// RTCf[^\ʒu[N +typedef struct RtcDrawPos{ + int date_x; + int date_y; + int time_x; + int time_y; +}RtcDrawPos; + +// function's prototype------------------------------------------------------- +static void InitScreen( void ); +static void InitCanvas( void ); +static void GetAndDrawRtcDataCore( BOOL forceGetFlag ); + +// global variable------------------------------------------------------------- +KeyWork pad; // L[pbh̓f[^ +TpWork tpd; // ^b`pl̓f[^ + +NNSG2dFont gFont; // tHg +NNSG2dCharCanvas gCanvas; // CharCanvas +NNSG2dTextCanvas gTextCanvas; // TextCanvas +NNSG2dCharCanvas gCanvasSub; // CharCanvas +NNSG2dTextCanvas gTextCanvasSub; // TextCanvas + +// static variable------------------------------------------------------------- +static int s_detach_count; +static RtcDrawPos s_rtcPos; +static RTCDate s_rtcDate; +static RTCTime s_rtcTime; +static u16 s_vcount; + +static char s_strBuffer[ STRING_LENGTH_MAX * 2 ] ATTRIBUTE_ALIGN(2); +static u16 s_strBufferUTF16[ STRING_LENGTH_MAX ]; + +// const data------------------------------------------------------------------ + +// jf[^\pR[h +const u8 *const g_strWeek[] ATTRIBUTE_ALIGN(2) = { + (const u8 *)"SUN", + (const u8 *)"MON", + (const u8 *)"TUE", + (const u8 *)"WED", + (const u8 *)"THU", + (const u8 *)"FRI", + (const u8 *)"SAT", +}; + +// ============================================================================ +// function's description +// ============================================================================ + +// BG +void InitBG(void) +{ + // OFF + GX_DispOff(); + GXS_DispOff(); + + // VRAM̊蓖ĂSĉ + GX_DisableBankForBG(); + GX_DisableBankForOBJ(); + GX_DisableBankForSubBG(); + GX_DisableBankForSubOBJ(); + + // C2DGW̏o͂ʂ + GX_SetDispSelect( GX_DISP_SELECT_SUB_MAIN ); + + // CLCD + { + // VRAM蓖 + GX_SetBankForBG ( GX_VRAM_BG_128_A ); + GX_SetBankForOBJ( GX_VRAM_OBJ_128_B ); + + MI_CpuClearFast( (void *)HW_BG_VRAM, 0x20000 ); // BG -VRAM NA + MI_CpuClearFast( (void *)HW_OBJ_VRAM, 0x20000 ); // OBJ-VRAM NA + + // J[pbgݒ + GX_LoadBGPltt( TXTColorPalette, 0, sizeof(TXTColorPalette) ); + + // BG[hݒ + GX_SetGraphicsMode( GX_DISPMODE_GRAPHICS, GX_BGMODE_0, GX_BG0_AS_2D ); + + GX_SetBGScrOffset ( GX_BGSCROFFSET_0x10000 ); + GX_SetBGCharOffset( GX_BGCHAROFFSET_0x00000 ); + } + // TuLCD + { + // VRAM蓖 + GX_SetBankForSubBG ( GX_VRAM_SUB_BG_128_C ); // VRAM-C for BGs + GX_SetBankForSubOBJ( GX_VRAM_SUB_OBJ_128_D ); // VRAM-D for BGs + + MI_CpuClearFast( (void *)HW_DB_BG_VRAM, 0x20000 ); // BG -VRAM NA + MI_CpuClearFast( (void *)HW_DB_OBJ_VRAM, 0x20000 ); // OBJ -VRAM NA + + // J[pbgݒ + GXS_LoadBGPltt( TXTColorPalette, 0, sizeof(TXTColorPalette) ); + + // BG[hݒ + GXS_SetGraphicsMode( GX_BGMODE_0 ); // BGMODE is 0 + } + InitScreen(); + InitCanvas(); +} + + +// XN[ +static void InitScreen( void ) +{ + // C BG 0 ݒ + G2_SetBG0Control( + GX_BG_SCRSIZE_TEXT_256x256, // XN[TCY 256x256 + GX_BG_COLORMODE_16, // J[[h 16F + GX_BG_SCRBASE_0xf800, // XN[x[X + GX_BG_CHARBASE_0x00000, // LN^x[X + GX_BG_EXTPLTT_01 // gpbgXbg + ); + GX_SetVisiblePlane( GX_PLANEMASK_BG0 ); + + // Tu BG 0 ݒ + G2S_SetBG0Control( + GX_BG_SCRSIZE_TEXT_256x256, // 256pix x 256pix text + GX_BG_COLORMODE_16, // use 256 colors mode + GX_BG_SCRBASE_0xf800, // screen base offset + 0x0000 is the address for BG #0 screen + GX_BG_CHARBASE_0x00000, // character base offset + 0x04000 is the address for BG #0 characters + GX_BG_EXTPLTT_01 // use BGExtPltt slot #0 if BGExtPltt is enabled + ); + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); // display only BG #0 +} + + +// `̏ +static void InitCanvas( void ) +{ + // tHgǂݍ݂܂ + { + void* pFontFile; + u32 size = CMN_LoadFile( &pFontFile, NTR_IPL_FONT_DATA, &g_allocator); + NNS_G2D_ASSERT( size > 0 ); + NNS_G2dFontInitUTF16(&gFont, pFontFile); +// NNS_G2dPrintFont(&gFont); + } + + { + // CharCanvas ̏ + NNS_G2dCharCanvasInitForBG( + &gCanvas, + (GXCharFmt16*)G2_GetBG0CharPtr() + CHARACTER_OFFSET, + CANVAS_WIDTH, + CANVAS_HEIGHT, + NNS_G2D_CHARA_COLORMODE_16 + ); + + // TextCanvas̏ + NNS_G2dTextCanvasInit( + &gTextCanvas, + &gCanvas, + &gFont, + TEXT_HSPACE, + TEXT_VSPACE + ); + + // XN[ݒ + NNS_G2dMapScrToCharText( + G2_GetBG0ScrPtr(), + CANVAS_WIDTH, + CANVAS_HEIGHT, + CANVAS_LEFT, + CANVAS_TOP, + NNS_G2D_TEXT_BG_WIDTH_256, + CHARACTER_OFFSET, + TXT_CPALETTE_MAIN + ); + } + { + // CharCanvas ̏ + NNS_G2dCharCanvasInitForBG( + &gCanvasSub, + (GXCharFmt16*)G2S_GetBG0CharPtr() + CHARACTER_OFFSET, + CANVAS_WIDTH, + CANVAS_HEIGHT, + NNS_G2D_CHARA_COLORMODE_16 + ); + + // TextCanvas̏ + NNS_G2dTextCanvasInit( + &gTextCanvasSub, + &gCanvasSub, + &gFont, + TEXT_HSPACE, + TEXT_VSPACE + ); + + // XN[ݒ + NNS_G2dMapScrToCharText( + G2S_GetBG0ScrPtr(), + CANVAS_WIDTH, + CANVAS_HEIGHT, + CANVAS_LEFT, + CANVAS_TOP, + NNS_G2D_TEXT_BG_WIDTH_256, + CHARACTER_OFFSET, + TXT_CPALETTE_MAIN + ); + } +} + + +// UTF16ł̒ڕ\ +void PutStringUTF16( int x, int y, int color, const u16 *strUTF16 ) +{ + NNS_G2dTextCanvasDrawText( &gTextCanvas, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + strUTF16 ); +} + +void PutStringUTF16Sub( int x, int y, int color, const u16 *strUTF16 ) +{ + NNS_G2dTextCanvasDrawText( &gTextCanvasSub, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + strUTF16 ); +} + + +// SJISPrintf`ŕ\iUTF16ɕϊ) +void PrintfSJIS( int x, int y, int color, const char *fmt, ... ) +{ + int srcLen; + int dstLen = sizeof(s_strBufferUTF16); + va_list vlist; + va_start(vlist, fmt); + srcLen = STD_TVSNPrintf( s_strBuffer, sizeof(s_strBuffer), fmt, vlist); + va_end(vlist); + s_strBuffer[ srcLen ] = 0; + + (void)STD_ConvertStringSjisToUnicode( s_strBufferUTF16, &dstLen, s_strBuffer, &srcLen, NULL ); + s_strBufferUTF16[ dstLen ] = 0; + + NNS_G2dTextCanvasDrawText(&gTextCanvas, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + s_strBufferUTF16 ); +} + +void PrintfSJISSub( int x, int y, int color, const char *fmt, ... ) +{ + int srcLen; + int dstLen = sizeof(s_strBufferUTF16); + va_list vlist; + va_start(vlist, fmt); + srcLen = STD_TVSNPrintf( s_strBuffer, sizeof(s_strBuffer), fmt, vlist); + va_end(vlist); + s_strBuffer[ srcLen ] = 0; + + (void)STD_ConvertStringSjisToUnicode( s_strBufferUTF16, &dstLen, s_strBuffer, &srcLen, NULL ); + s_strBufferUTF16[ dstLen ] = 0; + + NNS_G2dTextCanvasDrawText(&gTextCanvasSub, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + s_strBufferUTF16 ); +} + + +// L[͓ǂݏo-------------------------------- +void ReadKeyPad(void) +{ + u16 readData = PAD_Read(); + pad.trg = (u16)(readData & (readData ^ pad.cont)); // gK + pad.cont = readData; // x^ +} + + +// ^b`plf[^̎擾----------------------- +void ReadTpData(void) +{ + TP_GetCalibratedPoint( &tpd.last, &tpd.raw ); // OTPf[^ޔ + + if( TP_RequestRawSampling(&tpd.raw) ) { // ^b`pl̃TvO + SVC_CpuClear(0x0000, &tpd.raw, sizeof(tpd.raw), 16); // SPI-busyŃf[^擾Ɏśhf[^ȂhŃ^[B + return; + } + TP_GetCalibratedPoint( &tpd.disp, &tpd.raw ); // TPWLCDWɕϊB + + if( !WaitDetachTP() ) { // TPf^b`҂sB + SVC_CpuClear(0x0000, &tpd.disp, sizeof(tpd.disp), 16); // SPI-busyŃf[^擾Ɏśhf[^ȂhŃ^[B + return; + } +#if 1 + if(tpd.disp.touch) { // ݂TPf[^\ + switch ( tpd.disp.validity ) { + case TP_VALIDITY_VALID: + OS_Printf("( %3d, %3d ) -> ( %3d, %3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + case TP_VALIDITY_INVALID_X: + OS_Printf("( *%3d, %3d ) -> ( *%3d, %3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + case TP_VALIDITY_INVALID_Y: + OS_Printf("( %3d, *%3d ) -> ( %3d, *%3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + case TP_VALIDITY_INVALID_XY: + OS_Printf("( *%3d, *%3d ) -> ( *%3d, *%3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + } + } +#endif +} + + +// TPf^b`҂ +BOOL WaitDetachTP( void ) +{ + // s_detach_countnĂAJEgB + if(s_detach_count > 0) { + if(tpd.disp.touch == 0) { // TPĂȂ΁AJEgisKlōē͂󂯕tB + s_detach_count--; + }else { + s_detach_count = TP_CSR_DETACH_COUNT; + } + return FALSE; + } + return TRUE; +} + + +// TPf^b`҂̊Jn +void StartDetachTP( void ) +{ + s_detach_count = TP_CSR_DETACH_COUNT; +} + + +//====================================================== +// j[ +//====================================================== + +// j[` +void DrawMenu( u16 nowCsr, const MenuParam *pMenu ) +{ + int i; + int color; + + for( i = 0; i < pMenu->num; i++ ) { + if(i == nowCsr) { + if( !pMenu->pos[ i ].enable ) { + color = pMenu->disable_color; + }else { + color = pMenu->select_color; + } + }else { + color = pMenu->normal_color; + } + PutStringUTF16( pMenu->pos[ i ].x, pMenu->pos[ i ].y, color, (pMenu->str_elem)[ i ] ); + } +} + + +// ^b`plɂ郁j[I +BOOL SelectMenuByTP( u16 *nowCsr, const MenuParam *pMenu ) +{ + u16 i; + TPData *target; + static u16 detach_count = 0; + static u16 csr_old = 0xff; + static u16 same_csr_count = 0; + + // detach_countnĂAJEgB + if( detach_count > 0 ) { + if( tpd.disp.touch == 0 ) { // TPĂȂ΁AJEgisAPOJEgŃj[I + if( ++detach_count == TP_CSR_DETACH_COUNT ) { + detach_count = 0; + return TRUE; + }else { + return FALSE; + } + } + } + detach_count=0; // detachJEgl̃NA + + // ʏ́ATPf[^j[ɂ邩ǂ𔻒B + if( tpd.disp.touch ) target = &tpd.disp; + else target = &tpd.last; + + for( i = 0; i < pMenu->num; i++ ) { + if( tpd.disp.touch ) { // ^b`plj[̗vfŃ^b`ĂȂA + NNSG2dTextRect rect = NNS_G2dTextCanvasGetTextRect( &gTextCanvas, (pMenu->str_elem)[ i ] ); + u16 top_x = (u16)( pMenu->pos[ i ].x ); // j[vfLCDWZo + u16 top_y = (u16)( pMenu->pos[ i ].y - 4 ); + u16 bottom_x = (u16)( top_x + rect.width ); + u16 bottom_y = (u16)( top_y + rect.height + 4 ); // YẂ}4̃}[W + + OS_TPrintf( "MENU[ %d ] : top_x = %02d top_y = %02d bot_x = %02d bot_y = %02d : ", + i, top_x, top_y, bottom_x, bottom_y ); + + if( InRangeTp( top_x, top_y, bottom_x, bottom_y, target ) ) { + OS_TPrintf( "InRange\n" ); + if( tpd.disp.validity == TP_VALIDITY_VALID ) { // J[\̗vfɈړ + if( csr_old == i ) { + if( same_csr_count < TP_CSR_TOUCH_COUNT ) { + same_csr_count++; + }else { + *nowCsr = i; + } + return FALSE; + }else { + csr_old = i; + } + break; + } + }else { + OS_TPrintf( "OutRange\n" ); + } + }else { // touch==0 + if( same_csr_count == TP_CSR_TOUCH_COUNT ) { + detach_count = 1; + break; + } + } + } + same_csr_count = 0; + return FALSE; +} + + +// ݂̃^b`plWẅɂ邩ǂԂB +BOOL InRangeTp( int top_x, int top_y, int bottom_x, int bottom_y, TPData *tgt ) +{ + if( ( tgt->x >= top_x ) && + ( tgt->x <= bottom_x ) && + ( tgt->y >= top_y ) && + ( tgt->y <= bottom_y ) ) { + return TRUE; + }else { + return FALSE; + } +} + + +//=============================================== +// RTCANZX[` +//=============================================== + +// RTCf[^擾\̏ +void InitGetAndDrawRtcData( int drawDatePos_x, int drawDatePos_y, int drawTimePos_x, int drawTimePos_y) +{ + s_vcount = 0; + s_rtcPos.date_x = drawDatePos_x; + s_rtcPos.date_y = drawDatePos_y; + s_rtcPos.time_x = drawTimePos_x; + s_rtcPos.time_y = drawTimePos_y; + + (void)RTC_GetDateTime( &s_rtcDate, &s_rtcTime); + GetAndDrawRtcDataCore( TRUE ); +} + + +void GetAndDrawRtcData( void ) +{ + GetAndDrawRtcDataCore( FALSE ); +} + + +// RTC̎擾\ +static void GetAndDrawRtcDataCore( BOOL forceGetFlag ) +{ + u32 year; + RTCDate date_old; + RTCTime time_old; + + // RTC̎擾 + if( forceGetFlag || ( s_vcount++ == 60 ) ) { + s_vcount = 0; + MI_CpuCopy16( &s_rtcDate, &date_old, sizeof(RTCDate) ); + MI_CpuCopy16( &s_rtcTime, &time_old, sizeof(RTCTime) ); + + (void)RTC_GetDateTime( &s_rtcDate, &s_rtcTime ); + + // ORTC̏ + { + year = s_rtcDate.year + 2000; + PrintfSJISSub( s_rtcPos.date_x, s_rtcPos.date_y, TXT_COLOR_WHITE, "%d/%02d/%02d[%3s]", + year, + date_old.month, + date_old.day, + g_strWeek[ date_old.week ] + ); + PrintfSJISSub( s_rtcPos.time_x, s_rtcPos.time_y, TXT_COLOR_WHITE, "%02d:%02d:%02d", + time_old.hour, + time_old.minute, + time_old.second + ); + } + // RTC̕\ + { + year = s_rtcDate.year + 2000; + PrintfSJISSub( s_rtcPos.date_x, s_rtcPos.date_y, TXT_COLOR_BLACK, "%d/%02d/%02d[%3s]", + year, + s_rtcDate.month, + s_rtcDate.day, + g_strWeek[ s_rtcDate.week ] + ); + PrintfSJISSub( s_rtcPos.time_x, s_rtcPos.time_y, TXT_COLOR_BLACK, "%02d:%02d:%02d", + s_rtcTime.hour, + s_rtcTime.minute, + s_rtcTime.second + ); + } + } +} + + +// oi[ACROBJ̃[h +void SetBannerIconOBJ( GXOamAttr *pDstOAM, BannerFileV1 *bannerp ) +{ + GXS_LoadOBJPltt( bannerp->pltt, 15, BNR_PLTT_SIZE ); + MI_CpuCopyFast( bannerp->image, (void *)(HW_DB_OBJ_VRAM + 0x20), BNR_IMAGE_SIZE ); + G2_SetOBJAttr( pDstOAM, // OAM pointer + 32, // X position + 32, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_32x32, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 1, // charactor + 15, // palette + 0); // affine +} diff --git a/build/systemMenu_RED/Launcher/ARM9/src/misc.h b/build/systemMenu_RED/Launcher/ARM9/src/misc.h new file mode 100644 index 0000000..67b32bd --- /dev/null +++ b/build/systemMenu_RED/Launcher/ARM9/src/misc.h @@ -0,0 +1,153 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: misc.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __MISC_H__ +#define __MISC_H__ + +#include +#include + +#define NNS_G2D_UNICODE +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// define data---------------------------------------------------------- +#define TP_CSR_TOUCH_COUNT 2 // TPJ[\̃`^Oẑ߂̃JEgl +#define TP_CSR_DETACH_COUNT 2 // TPJ[\uIvƔ肷TPf^b`̃JEgl + +// DrawText ł̍ +#define TXT_DRAWTEXT_FLAG_DEFAULT (NNS_G2D_VERTICALORIGIN_TOP | NNS_G2D_HORIZONTALORIGIN_LEFT | NNS_G2D_HORIZONTALALIGN_LEFT) + +// TXTColorPalette ̐F 16Fpbgւ̃[hz +enum +{ + // pbg0 TXT_CPALETTE_MAIN + TXT_COLOR_NULL=0, + TXT_COLOR_WHITE, + TXT_COLOR_BLACK, + TXT_COLOR_RED, + TXT_COLOR_GREEN, + TXT_COLOR_BLUE, + TXT_COLOR_CYAN, + TXT_COLOR_MAGENTA, + TXT_COLOR_YELLOW, + + // pbg1 TXT_CPALETTE_USERCOLOR + TXT_UCOLOR_NULL=0, + TXT_UCOLOR_GRAY, + TXT_UCOLOR_BROWN, + TXT_UCOLOR_RED, + TXT_UCOLOR_PINK, + TXT_UCOLOR_ORANGE, + TXT_UCOLOR_YELLOW, + TXT_UCOLOR_LIMEGREEN, + TXT_UCOLOR_DARKGREEN, + TXT_UCOLOR_SEAGREEN, + TXT_UCOLOR_TURQUOISE, + TXT_UCOLOR_BLUE, + TXT_UCOLOR_DARKBLUE, + TXT_UCOLOR_PURPLE, + TXT_UCOLOR_VIOLET, + TXT_UCOLOR_MAGENTA, + + // pbg TXT_CPALETTE_4BPP + TXT_COLOR_4BPP_NULL=0, + TXT_COLOR_4BPP_BG=1, + TXT_COLOR_4BPP_TEXT=1 +}; + + +// v\ꏊ +#define RTC_DATE_TOP_X ( 9 * 8 ) +#define RTC_DATE_TOP_Y ( 10 * 8 ) +#define RTC_TIME_TOP_X ( 12 * 8 ) +#define RTC_TIME_TOP_Y ( 12 * 8 ) + + +// L[f[^[N +typedef struct { + u16 trg; // gK + u16 cont; // x^ +}KeyWork; + + +// ^b`pl[N +typedef struct { + int detached; // ̃f[^͂Ń^b`ꂽƂB + TPData disp; // ̓͒liLCDWj + TPData raw; // ̓͒liTP Wj + TPData last; // O̓͒liLCDWj +}TpWork; + + +// j[vfW +typedef struct MenuPos { + BOOL enable; + int x; + int y; +}MenuPos; + + +// j[\p[^\ +typedef struct MenuParam { + int num; + int normal_color; + int select_color; + int disable_color; + MenuPos *pos; + const u16 **str_elem; +}MenuParam; + + +// global variables-------------------------------------------------- +extern TpWork tpd; // ^b`plf[^ +extern KeyWork pad; // L[pbh̓f[^ +extern const u8 *const g_strWeek[ 7 ]; // j + +extern NNSFndAllocator g_allocator; // AP[^ +extern NNSG2dFont gFont; // tHg +extern NNSG2dCharCanvas gCanvas; // CharCanvas +extern NNSG2dTextCanvas gTextCanvas; // TextCanvas + +// function------------------------------------------------------------- +void InitBG( void ); +void PutStringUTF16 ( int x, int y, int color, const u16 *strUTF16 ); +void PutStringUTF16Sub( int x, int y, int color, const u16 *strUTF16 ); +void PrintfSJIS ( int x, int y, int color, const char *fmt, ... ); +void PrintfSJISSub( int x, int y, int color, const char *fmt, ... ); +void ReadKeyPad( void ); +void ReadTpData( void ); +BOOL WaitDetachTP( void ); +void StartDetachTP( void ); +void DrawMenu( u16 nowCsr, const MenuParam *pMenu ); +BOOL SelectMenuByTP( u16 *nowCsr, const MenuParam *pMenu ); +BOOL InRangeTp( int top_x, int top_y, int bottom_x, int bottom_y, TPData *tgt ); +void InitGetAndDrawRtcData( int drawDatePos_x, int drawDatePos_y, int drawTimePos_x, int drawTimePos_y ); +void GetAndDrawRtcData( void ); +void SetBannerIconOBJ( GXOamAttr *pDstOAM, BannerFileV1 *bannerp ); + +#ifdef __cplusplus +} +#endif + +#endif // __MISC_H__ diff --git a/build/systemMenu_RED/Launcher/Makefile b/build/systemMenu_RED/Launcher/Makefile new file mode 100644 index 0000000..02cacbf --- /dev/null +++ b/build/systemMenu_RED/Launcher/Makefile @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +SUBDIRS = ARM9 + +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/MachineSettings/ARM9/Makefile b/build/systemMenu_RED/MachineSettings/ARM9/Makefile new file mode 100644 index 0000000..6454a1f --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/Makefile @@ -0,0 +1,54 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlSDK - demos - simpleShoot-1 +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev: $ +# $Author: $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- + +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED + +TARGET_BIN = main.srl + +#LCFILE_SPEC = +ROM_SPEC = main.rsf + +SRCS = main.c misc.c \ + MachineSetting.c setRTC.c selectLanguage.c calibrationTP.c + #setOwnerInfo.c + +#SRCS_OVERLAY = + +#LINCLUDES = +#LLIBRARY_DIRS = +#LLIBRARIES = +#LDEPENDS_NEF = + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build : $(FONT_OBJS) $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/MachineSettings/ARM9/main.rsf b/build/systemMenu_RED/MachineSettings/ARM9/main.rsf new file mode 100644 index 0000000..f7b7ea4 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/main.rsf @@ -0,0 +1,146 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ROM-BB.rsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL ROM SPEC FILE +# + +Arm9 +{ + Static "$(MAKEROM_ARM9:r).FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.FLX.TWL.sbin$(COMPSUFFIX9)" + Elf "$(MAKEROM_ARM9:r).tef" +} + +Arm7 +{ + Static "$(MAKEROM_ARM7_BASE:r).FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.FLX.TWL.sbin$(COMPSUFFIX7)" + Elf "$(MAKEROM_ARM7_BASE:r).tef" +} + +Arm9.Ltd +{ + Static "$(MAKEROM_ARM9:r).LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.LTD.TWL.sbin$(COMPSUFFIX9)" +} + +Arm7.Ltd +{ + Static "$(MAKEROM_ARM7_BASE:r).LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.LTD.TWL.sbin$(COMPSUFFIX7)" +} + +Property +{ + ### + ### Settings for FinalROM + ### + #### BEGIN + # + # TITLE NAME: Your product name within 12bytes + # + #TitleName "YourAppName" + + # + # MAKER CODE: Your company ID# in 2 ascii words + # issued by NINTENDO + # + #MakerCode "00" + + # + # REMASTER VERSION: Mastering version + # + #RomVersion 0 + + # + # ROM SPEED TYPE: [MROM/1TROM/UNDEFINED] + # + RomSpeedType $(MAKEROM_ROMSPEED) + + # + # ROM SIZE: in bit [64M/128M/256M/512M/1G/2G] + # + #RomSize 128M + #RomSize 256M + + # + # ROM PADDING: TRUE if finalrom + # + #RomFootPadding TRUE + + # + # ROM HEADER TEMPLATE: Provided to every product by NINTENDO + # + #RomHeaderTemplate ./etc/rom_header.template.sbin + + # + # BANNER FILE: generated from Banner Spec File + # + BannerFile ../banner/banner.bnr + + ### + ### Setting for TWL + ### + # + # BANNER FILE: + # + BannerTWLFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + # + # Boot allowed Media: [GameCard/NAND/SDCard/DownloadPlay] + # possible to choose one or more. + # + BootMedia GameCard NAND SDCard DownloadPlay + + # + # Certification FILE: + # + Certificate $(TWLSDK_ROOT)/include/twl/specfiles/default_sgn.sbin + + # + # Digest parameters: + # + DigestParam 1024 32 + + # + # WRAM mapping: [MAP_BB_HYB/MAP_BB_LTD/MAP_TS_HYB/MAP_TS_LTD] + # don't have to edit + # + WramMapping $(MAKEROM_WRAM_MAPPING) + + # + # Codec mode: + # don't have to edit + # + CodecMode $(MAKEROM_CODEC_MODE) + + ### + #### END +} + +RomSpec +{ + Offset 0x00000000 + Segment ALL + HostRoot ../../data + Root /data + File NTR_IPL_font_m.NFTR +} diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/MachineSetting.c b/build/systemMenu_RED/MachineSettings/ARM9/src/MachineSetting.c new file mode 100644 index 0000000..9105a7d --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/MachineSetting.c @@ -0,0 +1,295 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: mainMenu.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "MachineSetting.h" +#include "spi.h" + +// define data------------------------------------------ + // LZ{^LCD̈ +#define CANCEL_BUTTON_TOP_X ( 12 * 8 ) +#define CANCEL_BUTTON_TOP_Y ( 21 * 8 ) +#define CANCEL_BUTTON_BOTTOM_X ( CANCEL_BUTTON_TOP_X + 5 * 8 ) +#define CANCEL_BUTTON_BOTTOM_Y ( CANCEL_BUTTON_TOP_Y + 2 * 8 ) + // OK{^LCD̈ +#define OK_BUTTON_TOP_X ( 22 * 8 ) +#define OK_BUTTON_TOP_Y ( 21 * 8 ) +#define OK_BUTTON_BOTTOM_X ( OK_BUTTON_TOP_X + 2 * 8 ) +#define OK_BUTTON_BOTTOM_Y ( OK_BUTTON_TOP_Y + 2 * 8 ) + + +#define SETTING_MENU_ELEMENT_NUM 4 // Cj[̍ڐ + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- +static BOOL InitialSetting( void ); +static void InitialSettingFinalizeInit( void ); +static int InitialSettingFinalizeMain( void ); + +// global variable ------------------------------------- +BOOL g_initialSet = FALSE; + +// static variable ------------------------------------- +static u16 s_csr = 0; +static const u16 *s_pStrSetting[ SETTING_MENU_ELEMENT_NUM ]; // Cj[pe[uւ̃|C^Xg + +// const data ----------------------------------------- + + +//=============================================== +// mainMenu.c +//=============================================== +static const u16 *const s_pStrSettingElemTbl[ SETTING_MENU_ELEMENT_NUM ][ LANG_CODE_MAX ] = { + { + (const u16 *)L"", + (const u16 *)L"LANGUAGE", + (const u16 *)L"LANGUAGE(F)", + (const u16 *)L"LANGUAGE(G)", + (const u16 *)L"LANGUAGE(I)", + (const u16 *)L"LANGUAGE(S)", + }, + { + (const u16 *)L"t & ", + (const u16 *)L"DATE & TIME", + (const u16 *)L"DATE & TIME(F)", + (const u16 *)L"DATE & TIME(G)", + (const u16 *)L"DATE & TIME(I)", + (const u16 *)L"DATE & TIME(S)", + }, + { + (const u16 *)L"[U[", + (const u16 *)L"USER INFORMATION", + (const u16 *)L"USER INFORMATION(F)", + (const u16 *)L"USER INFORMATION(G)", + (const u16 *)L"USER INFORMATION(I)", + (const u16 *)L"USER INFORMATION(S)", + }, + { + (const u16 *)L"^b`pl␳", + (const u16 *)L"TOUCH PANEL", + (const u16 *)L"TOUCH PANEL(F)", + (const u16 *)L"TOUCH PANEL(G)", + (const u16 *)L"TOUCH PANEL(I)", + (const u16 *)L"TOUCH PANEL(S)", + }, +}; + +static MenuPos s_settingPos[] = { + { TRUE, 4 * 8, 8 * 8 }, + { TRUE, 4 * 8, 10 * 8 }, + { FALSE, 4 * 8, 12 * 8 }, + { TRUE, 4 * 8, 14 * 8 }, +}; + + +static const MenuParam s_settingParam = { + SETTING_MENU_ELEMENT_NUM, + TXT_COLOR_BLACK, + TXT_COLOR_GREEN, + TXT_COLOR_RED, + &s_settingPos[ 0 ], + (const u16 **)&s_pStrSetting, +}; + +//====================================================== +// Cj[ +//====================================================== + +// Cj[̏ +void MachineSettingInit( void ) +{ + int i; + + // NV[PX + if( InitialSetting() ) { + return; + } + + GX_DispOff(); + GXS_DispOff(); + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + + PutStringUTF16( 0, 0, TXT_COLOR_BLUE, (const u16 *)L"MACHINE SETTINGS" ); +#ifdef __NCD_CLEAR_ENABLE + (void)PutStringUTF16( 18 * 8, 21 * 8, TXT_COLOR_BLACK, (const u16 *)L"[START]:NCD clear."); +#endif /* __NCD_CLEAR_ENABLE */ + + // NITROݒf[^languageɉCj[\̐؂ւ + for( i = 0; i < SETTING_MENU_ELEMENT_NUM; i++ ) { + s_pStrSetting[ i ] = s_pStrSettingElemTbl[ i ][ GetNCDWork()->option.language ]; + } + + DrawMenu( s_csr, &s_settingParam ); + + SVC_CpuClear( 0x0000, &tpd, sizeof(TpWork), 16 ); + + GX_SetVisiblePlane ( GX_PLANEMASK_BG0 ); + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); + GX_DispOn(); + GXS_DispOn(); + + g_pNowProcess = MachineSettingMain; +} + + +// Cj[ +int MachineSettingMain( void ) +{ + BOOL tp_select; + + ReadTP(); + + //-------------------------------------- + // L[͏ + //-------------------------------------- + if( pad.trg & PAD_KEY_DOWN ){ // J[\̈ړ + if( ++s_csr == SETTING_MENU_ELEMENT_NUM ) { + s_csr=0; + } + } + if( pad.trg & PAD_KEY_UP ){ + if( --s_csr & 0x80 ) { + s_csr=SETTING_MENU_ELEMENT_NUM - 1; + } + } + tp_select = SelectMenuByTP( &s_csr, &s_settingParam ); + DrawMenu( s_csr, &s_settingParam ); + + if( ( pad.trg & PAD_BUTTON_A ) || ( tp_select ) ) { // j[ڂւ̕ + if( s_settingPos[ s_csr ].enable ) { + switch( s_csr ) { + case 0: + SelectLanguageInit(); + g_pNowProcess = SelectLanguageMain; + break; + case 1: + SetRTCInit(); + g_pNowProcess = SetRTCMain; + break; + case 2: +// SetOwnerInfoInit(); +// g_pNowProcess = SetOwnerInfoMain; + break; + case 3: + TP_CalibrationInit(); + g_pNowProcess = TP_CalibrationMain; + break; + } + } + } + +#ifdef __NCD_CLEAR_ENABLE + if( pad.trg & PAD_BUTTON_START ) { + SVC_CpuClearFast( 0x0000, GetNCDWork(), sizeof(NitroConfigData) ); + (void)SPI_NvramWriteEnable(); + SVC_WaitVBlankIntr(); + (void)SPI_NvramPageErase( 0x3fe00 ); + SVC_WaitVBlankIntr(); + (void)SPI_NvramWriteEnable(); + SVC_WaitVBlankIntr(); + (void)SPI_NvramPageErase( 0x3ff00 ); + SVC_WaitVBlankIntr(); + (void)SPI_NvramWriteDisable(); + OS_TPrintf("NitroConfigData zero clear!!\n"); + } +#endif /* __NCD_CLEAR_ENABLE */ + + return 0; +} + + +// OK / CANCEL{^̕` +void DrawOKCancelButton(void) +{ + (void)PutStringUTF16( CANCEL_BUTTON_TOP_X, CANCEL_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L"CANCEL"); + (void)PutStringUTF16( OK_BUTTON_TOP_X, OK_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L"OK"); +} + + +// OK or CANCEL{^`FbN +void CheckOKCancelButton(BOOL *tp_ok, BOOL *tp_cancel) +{ + *tp_cancel = WithinRangeTP( CANCEL_BUTTON_TOP_X, CANCEL_BUTTON_TOP_Y, + CANCEL_BUTTON_BOTTOM_X, CANCEL_BUTTON_BOTTOM_Y, &tpd.disp ); + *tp_ok = WithinRangeTP( OK_BUTTON_TOP_X, OK_BUTTON_TOP_Y, + OK_BUTTON_BOTTOM_X, OK_BUTTON_BOTTOM_Y, &tpd.disp ); +} + + +//--------------------------------------------------------- +// +// ݒI +// +//--------------------------------------------------------- + +// NV[PX +static BOOL InitialSetting( void ) +{ +#if 0 + if(GetNCDWork()->option.input_language == 0) { // ݒ肪܂B + g_initialSet = TRUE; + s_csr = 2; + SelectLangageInit(); + g_pNowProcess = SelectLanguageMain; + return TRUE; + }else if(GetNCDWork()->option.input_tp == 0) { // TPLu[V܂B + g_initialSet = TRUE; + s_csr = 3; + TP_CalibrationInit(); + g_pNowProcess = TP_CalibrationMain; + return TRUE; + }else if(GetNCDWork()->option.input_rtc == 0) { // RTCݒ肪܂B + ClearRTC(); + g_initialSet = TRUE; + s_csr = 1; + SetRTCInit(); + g_pNowProcess = SetRTCMain; + return TRUE; + }else if( (GetNCDWork()->option.input_nickname == 0) // jbNl[܂͍DȐF͂܂B + || (GetNCDWork()->option.input_favoriteColor == 0) ) { +/* g_initialSet = TRUE; + s_csr = 0; + SetOwnerInfoInit(); + g_pNowProcess = SetOwnerInfoMain; + return TRUE; +*/ } + + if( g_initialSet ) { + InitialSettingFinalizeInit(); + g_pNowProcess = InitialSettingFinalizeMain(); + return TRUE; + } +#endif + return FALSE; +} + + +static void InitialSettingFinalizeInit( void ) +{ + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + (void)PutStringUTF16( 6 * 8, 10 * 8, TXT_COLOR_BLACK, (const u16 *)L" Initial setting completed."); + (void)PutStringUTF16( 6 * 8, 12 * 8, TXT_COLOR_BLACK, (const u16 *)L" Please reboot."); +} + + +static int InitialSettingFinalizeMain( void ) +{ + return 0; +} + diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/MachineSetting.h b/build/systemMenu_RED/MachineSettings/ARM9/src/MachineSetting.h new file mode 100644 index 0000000..da904fc --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/MachineSetting.h @@ -0,0 +1,77 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: MachineSetting.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __MACHINE_SETTING_H__ +#define __MACHINE_SETTING_H__ + +#ifdef __cplusplus +extern "C" { +#endif + + +#include + + +// define data---------------------------------------------------------- +#define TP_CSR_TOUCH_COUNT 2 // TPJ[\̃`^Oẑ߂̃JEgl +#define TP_CSR_DETACH_COUNT 2 // TPJ[\uIvƔ肷TPf^b`̃JEgl + +#define HANDLE_MENU 48 +#define HANDLE_RTC_VIEW 240 +#define HANDLE_OK_BUTTON 255 +#define HANDLE_CANCEL_BUTTON 256 + +// l̓C^[tF[Xp[Nivoid InputDecimal()Ŏgpj +typedef struct InputNumParam { + u16 pos_x; // ͒l̕\Xʒu + u16 pos_y; // V@@@@ Yʒu + int up_count; + int down_count; + int keta_max; // ő包 + int value_min; // ͒l̍ŏ + int value_max; // ͒l̍ő + int y_offset; // ^b`pl͂̊ʒuYItZbg +}InputNumParam; + +// global variable------------------------------------------------------ +extern NNSFndAllocator g_allocator; +extern BOOL g_initialSet; +extern int (*g_pNowProcess)( void ); + +// function------------------------------------------------------------- +extern void MachineSettingInit( void ); +extern int MachineSettingMain( void ); +extern void SetOwnerInfoInit( void ); +extern int SetOwnerInfoMain( void ); +extern void SetRTCInit( void ); +extern int SetRTCMain( void ); +extern void SelectLanguageInit( void ); +extern int SelectLanguageMain( void ); +extern void TP_CalibrationInit( void ); +extern int TP_CalibrationMain( void ); + +extern void DrawOKCancelButton( void ); +extern void CheckOKCancelButton(BOOL *tp_ok, BOOL *tp_cancel); +extern void InputDecimal(int *tgtp, InputNumParam *inpp); + +extern void ClearRTC( void ); + +#ifdef __cplusplus +} +#endif + +#endif // __MACHINE_SETTING_H__ diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/calibrationTP.c b/build/systemMenu_RED/MachineSettings/ARM9/src/calibrationTP.c new file mode 100644 index 0000000..8cd7d8b --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/calibrationTP.c @@ -0,0 +1,524 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: calibrationTP.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "MachineSetting.h" + +// define data------------------------------------------ + // OK{^LCD̈ +#define OK_BUTTON_TOP_X ( 2 * 8 ) +#define OK_BUTTON_TOP_Y ( 20 * 8 ) +#define OK_BUTTON_BOTTOM_X ( OK_BUTTON_TOP_X + 8 * 8 ) +#define OK_BUTTON_BOTTOM_Y ( OK_BUTTON_TOP_Y + 4 * 8 ) + + // LZ{^LCD̈ +#define CANCEL_BUTTON_TOP_X ( 11 * 8 ) +#define CANCEL_BUTTON_TOP_Y ( 20 * 8 ) +#define CANCEL_BUTTON_BOTTOM_X ( CANCEL_BUTTON_TOP_X + 8 * 8 ) +#define CANCEL_BUTTON_BOTTOM_Y ( CANCEL_BUTTON_TOP_Y + 4 * 8 ) + + // gC{^LCD̈ +#define RETRY_BUTTON_TOP_X ( 20 * 8 ) +#define RETRY_BUTTON_TOP_Y ( 20 * 8 ) +#define RETRY_BUTTON_BOTTOM_X ( RETRY_BUTTON_TOP_X + 8 * 8 ) +#define RETRY_BUTTON_BOTTOM_Y ( RETRY_BUTTON_TOP_Y + 4 * 8 ) + + // Lu[VpOBJf[^ +const u16 bitmapOBJPoint[8 * 8 * 5]; + + // eLN^f[^TCY +#define IMAGE_DATA (bitmapOBJPoint) +#define IMAGE_DATA_SIZE (sizeof(bitmapOBJPoint)) +#define MY_CHAR_SIZE (sizeof(myChar)) + + // NITRO-LCDTCY +#define DISP_X_SIZE 256 +#define DISP_Y_SIZE 192 + +enum { + INIT=0, + INTERVAL_0, + CALIBRATE_1, + INTERVAL_1, + CALIBRATE_2, + INTERVAL_2, + CHECK_PARAM, + INTERVAL_3, + GET_POINT +}; + + // Lu[Vݒ胏[N +typedef struct CalibWork { + u32 seq; + u16 release_count; + u16 touch_count; + u16 last_x; + u16 last_y; + TPData sample[2]; + TPCalibrateParam calibrate; +}CalibWork; + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- +static void DisplayInit(); +static BOOL GetSamplePointNow(TPData *data); +static BOOL WaitPanelReleaseNow( void ); +static void ReturnMenu(void); + +// global variable ------------------------------------- + +// static variable ------------------------------------- +static CalibWork *s_pCw; +static GXOamAttr s_oamBak[ 128 ] ATTRIBUTE_ALIGN(32); // OAM obNAbv + +// const data ----------------------------------------- + +//====================================================== +// function's description +//====================================================== + +/*---------------------------------------------------------------------------* + Name: SetPoint8x8 + + Description: Display a 8x8 OBJ on indicated point. + + Arguments: x - position X. + y - position Y. + + Returns: None. + *---------------------------------------------------------------------------*/ +static inline void SetPoint8x8(u16 pos_x, u16 pos_y) +{ + G2_SetOBJAttr( &s_oamBak[0], // OAM number + pos_x - 4, // X position + pos_y - 4, // Y position + 0, // Priority + GX_OAM_MODE_BITMAPOBJ, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_8x8, // 8x8 size + GX_OAM_COLOR_16, // 16 color + 0x60, // charactor + 15, // alpha + 0); +} + + +/*---------------------------------------------------------------------------* + Name: SetPoint16x16 + + Description: Display a 16x16 OBJ on indicated point. + + Arguments: x - position X. + y - position Y. + + Returns: None. + *---------------------------------------------------------------------------*/ +static inline void SetPoint16x16(u16 pos_x, u16 pos_y) +{ + G2_SetOBJAttr( &s_oamBak[0], // OAM number + pos_x - 8, // X position + pos_y - 8, // Y position + 0, // Priority + GX_OAM_MODE_BITMAPOBJ, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_16x16, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 0x61, // charactor + 15, // alpha + 0); +} + + +/*---------------------------------------------------------------------------* + Name: DisplayInit + + Description: Graphics Initialization + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +static void DisplayInit() +{ + MI_CpuClearFast( (void *)HW_OAM, 0x20 ); + MI_CpuClearFast( s_oamBak, sizeof(s_oamBak) ); + GX_SetOBJVRamModeBmp( GX_OBJVRAMMODE_BMP_1D_128K ); // 2D mapping OBJ + /* Load charactor bitmap data */ + GX_LoadOBJ( (const void *)IMAGE_DATA, 0x3000 /* 0 */, IMAGE_DATA_SIZE ); // Transfer OBJ bitmap data to VRAM +} + + +/*---------------------------------------------------------------------------* + Name: GetSamplePointNow + + Description: Get touched point by OneTime Sampling. + This function use TP_RequestSampling() and TP_WaitRawResult() + + Arguments: None. + + Returns: data - getton TouchPanel data. + BOOL - if touched and got point this function returns TRUE. + else FALSE. + *---------------------------------------------------------------------------*/ +static BOOL GetSamplePointNow(TPData *data) +{ + TPData temp; + + enum { + OK_COUNT = 4, OK_RANGE = 50 + }; + + // Detect a point pushed during definite time. + while (TP_RequestRawSampling( &temp )) { }; + + if (! temp.touch ) { + s_pCw->touch_count = 0; + return FALSE; + } + + if ( temp.validity != TP_VALIDITY_VALID ) { + s_pCw->touch_count = 0; + return FALSE; + } + + OS_Printf("( %d, %d )\n", temp.x, temp.y); + + s_pCw->touch_count++; + if ( s_pCw->touch_count == 1 ) { + s_pCw->last_x = temp.x; + s_pCw->last_y = temp.y; + return FALSE; + } + + // if jump point from last frame, reset count. + if ( (s32)(s_pCw->last_x - temp.x) < - OK_RANGE || + (s32)(s_pCw->last_x - temp.x) > OK_RANGE ) + { + s_pCw->touch_count = 1; + s_pCw->last_x = temp.x; + s_pCw->last_y = temp.y; + return FALSE; + } + + if ( (s32)(s_pCw->last_y - temp.y) < - OK_RANGE || + (s32)(s_pCw->last_y - temp.y) > OK_RANGE ) + { + s_pCw->touch_count = 1; + s_pCw->last_x = temp.x; + s_pCw->last_y = temp.y; + return FALSE; + } + + // if the point pressed during OK_COUNT, detect finish. + if ( s_pCw->touch_count == OK_COUNT ) { + data->x = (u16) ( (temp.x + s_pCw->last_x) / 2 ); + data->y = (u16) ( (temp.y + s_pCw->last_y) / 2 ); + data->touch = TP_TOUCH_ON; + data->validity = TP_VALIDITY_VALID; + s_pCw->touch_count=0; + return TRUE; + } + + s_pCw->last_x = temp.x; + s_pCw->last_y = temp.y; + return FALSE; +} + + +/*---------------------------------------------------------------------------* + Name: WaitPanelReleaseNow + + Description: Wait to released TouchPanel, using OneTime Sampling. + This function is using TP_RequestSampling() and TP_WaitRawResult(). + + Arguments: None. + + Returns: BOOL - if TouchPanel is released , this returns TRUE. + else FALSE. + + *---------------------------------------------------------------------------*/ +static BOOL WaitPanelReleaseNow( void ) +{ + TPData temp; + + enum { + INTERVAL_CNT = 10 + }; + + while (TP_RequestRawSampling( &temp )) { + SVC_WaitByLoop(0x400); + }; + + if ( temp.touch ) { + s_pCw->release_count = 0; + return FALSE; + } + + s_pCw->release_count++; + if ( s_pCw->release_count >= INTERVAL_CNT ) { + s_pCw->release_count = 0; + return TRUE; + } else { + return FALSE; + } +} + + +/*---------------------------------------------------------------------------* + Name: TP_Calibration + + Description: Initialization and main loop + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +int TP_CalibrationMain( void ) +{ + BOOL tp_ok = FALSE; + BOOL tp_cancel = FALSE; + BOOL tp_retry = FALSE; + + switch (s_pCw->seq) { + case INIT: + NNS_G2dCharCanvasClearArea( &gCanvas, TXT_COLOR_WHITE, + 0 * 8 , 20 * 8, 32 * 8, 4 * 8 ); + s_pCw->seq = INTERVAL_0; + PutStringUTF16( 2 * 8, 21 * 8, TXT_COLOR_CYAN, (const u16 *)L"[B]:CANCEL" ); + break; + + case INTERVAL_0: + // wait release TouchPanel + if ( WaitPanelReleaseNow() ) { + s_pCw->seq = CALIBRATE_1; + } + break; + + case CALIBRATE_1: + // detect first point. + SetPoint8x8( 32, 32 ); + if ( GetSamplePointNow( &s_pCw->sample[ 0 ] ) ) { + OS_Printf( "OK! ( %d, %d )\n", s_pCw->sample[0].x, s_pCw->sample[0].y ); + s_pCw->seq = INTERVAL_1; + } + break; + + case INTERVAL_1: + // wait release TouchPanel + if ( WaitPanelReleaseNow() ) { + s_pCw->seq = CALIBRATE_2; + } + break; + + case CALIBRATE_2: + // detect second point. + SetPoint8x8( DISP_X_SIZE - 32, DISP_Y_SIZE - 32 ); + if ( GetSamplePointNow( &s_pCw->sample[ 1 ] ) ) { + OS_Printf( "OK! ( %d, %d )\n", s_pCw->sample[1].x, s_pCw->sample[1].y ); + // Calculate and set calibration parameter from two detected point. + (void)TP_CalcCalibrateParam( + &s_pCw->calibrate, + s_pCw->sample[0].x, s_pCw->sample[0].y, 32, 32, + s_pCw->sample[1].x, s_pCw->sample[1].y, DISP_X_SIZE - 32, DISP_Y_SIZE - 32 ); + TP_SetCalibrateParam( &s_pCw->calibrate ); + + OS_Printf( "Calibrate param: \n" ); + OS_Printf( "\tx = %d, xDotSize = %d\n", s_pCw->calibrate.x0, s_pCw->calibrate.xDotSize / 0x100 ); + OS_Printf( "\ty = %d, yDotSize = %d\n", s_pCw->calibrate.y0, s_pCw->calibrate.yDotSize / 0x100 ); + OS_Printf( "Check calibrate param\n" ); + + s_pCw->seq = INTERVAL_2; + } + break; + + case INTERVAL_2: + // Wait release TouchPanel + if ( WaitPanelReleaseNow() ) { + s_pCw->seq = CHECK_PARAM; + } + break; + + case CHECK_PARAM: + // Verify Calibrattion Parameter. + SetPoint8x8( DISP_X_SIZE / 2, DISP_Y_SIZE / 2 ); + if ( GetSamplePointNow( &tpd.raw ) ) { + TP_GetUnCalibratedPoint( &tpd.disp.x, &tpd.disp.y, DISP_X_SIZE / 2, DISP_Y_SIZE / 2 ); + s_pCw->seq = GET_POINT; + + NNS_G2dCharCanvasClearArea( &gCanvas, TXT_COLOR_WHITE, + 2 * 8 , 21 * 8, 10 * 8, 2 * 8 ); + PutStringUTF16( OK_BUTTON_TOP_X, OK_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L" OK "); + PutStringUTF16( CANCEL_BUTTON_TOP_X, CANCEL_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L" CANCEL "); + PutStringUTF16( RETRY_BUTTON_TOP_X, RETRY_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L" RETRY "); + PutStringUTF16( OK_BUTTON_TOP_X + 2 * 8, OK_BUTTON_TOP_Y + 2 * 8, TXT_COLOR_CYAN, (const u16 *)L"[A]"); + PutStringUTF16( CANCEL_BUTTON_TOP_X + 2 * 8, CANCEL_BUTTON_TOP_Y + 2 * 8, TXT_COLOR_CYAN, (const u16 *)L"[B]"); + PutStringUTF16( RETRY_BUTTON_TOP_X, RETRY_BUTTON_TOP_Y + 2 * 8, TXT_COLOR_CYAN, (const u16 *)L"[START]"); + { + s32 xRange, yRange; + xRange = tpd.raw.x - tpd.disp.x; + yRange = tpd.raw.y - tpd.disp.y; + OS_TPrintf( "OK! ( %d, %d )\n", tpd.raw.x, tpd.raw.y ); + OS_TPrintf( "Raw ( %d, %d )\n", tpd.disp.x, tpd.disp.y ); + OS_TPrintf( "\txRange = %d, yRange = %d\n", xRange, yRange ); + } + } + break; + + case GET_POINT: + // Draw Marker by calibrated point. + while ( TP_RequestRawSampling( &tpd.raw ) ) { + SVC_WaitByLoop( 0x400 ); + } + TP_GetCalibratedPoint( &tpd.disp, &tpd.raw ); + + if ( tpd.raw.touch ) { + SetPoint16x16( tpd.disp.x, tpd.disp.y ); + + // [OK] [CANCEL] [RETRY]{^`FbN + tp_ok = WithinRangeTP( OK_BUTTON_TOP_X, OK_BUTTON_TOP_Y, + OK_BUTTON_BOTTOM_X, OK_BUTTON_BOTTOM_Y, &tpd.disp ); + tp_cancel = WithinRangeTP( CANCEL_BUTTON_TOP_X, CANCEL_BUTTON_TOP_Y, + CANCEL_BUTTON_BOTTOM_X, CANCEL_BUTTON_BOTTOM_Y, &tpd.disp ); + tp_retry = WithinRangeTP( RETRY_BUTTON_TOP_X, RETRY_BUTTON_TOP_Y, + RETRY_BUTTON_BOTTOM_X, RETRY_BUTTON_BOTTOM_Y, &tpd.disp ); + + if( tpd.raw.validity==TP_VALIDITY_VALID ) { + OS_TPrintf( "( %3d, %3d ) -> ( %4d, %4d )\n", tpd.disp.x, tpd.disp.y, tpd.raw.x, tpd.raw.y ); + } + } + + if( ( pad.trg & PAD_BUTTON_A ) || tp_ok ) { + GetSYSMWork()->ncd_invalid = 0; + GetNCDWork()->option.input_tp = 1; // ^b`pl̓tO𗧂ĂB + GetNCDWork()->tp.raw_x1 = s_pCw->sample[0].x; + GetNCDWork()->tp.raw_y1 = s_pCw->sample[0].y; + GetNCDWork()->tp.dx1 = 32; + GetNCDWork()->tp.dy1 = 32; + GetNCDWork()->tp.raw_x2 = s_pCw->sample[1].x; + GetNCDWork()->tp.raw_y2 = s_pCw->sample[1].y; + GetNCDWork()->tp.dx2 = DISP_X_SIZE - 32; + GetNCDWork()->tp.dy2 = DISP_Y_SIZE - 32; + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData( GetNCDWork() ); + + ReturnMenu(); + return 0; + }else if( ( pad.trg & PAD_BUTTON_START ) || tp_retry ) { + s_pCw->seq = INIT; + } + break; + } + + /* flush cache of OAM buffers to main memory */ + DC_FlushRange( s_oamBak, sizeof(s_oamBak) ); + GX_LoadOAM( s_oamBak, 0, sizeof(s_oamBak) ); + MI_DmaFill32( 3, s_oamBak, 192, sizeof(s_oamBak) ); // Clear OAM buffer + + // B{^LZ + if( ( pad.trg & PAD_BUTTON_B ) || tp_cancel ){ + (void)TP_CalcCalibrateParam( + &s_pCw->calibrate, + GetNCDWork()->tp.raw_x1, GetNCDWork()->tp.raw_y1, (u16)GetNCDWork()->tp.dx1, (u16)GetNCDWork()->tp.dy1, + GetNCDWork()->tp.raw_x2, GetNCDWork()->tp.raw_y2, (u16)GetNCDWork()->tp.dx2, (u16)GetNCDWork()->tp.dy2 ); + TP_SetCalibrateParam( &s_pCw->calibrate ); + ReturnMenu(); + return 0; + } + + return 0; +} + + +// j[ɖ߂ +static void ReturnMenu( void ) +{ + NNS_FndFreeToAllocator( &g_allocator, s_pCw ); // Lu[Vpϐ̊J + s_pCw = NULL; + OS_Printf("Free :CalibWork\n"); + MachineSettingInit(); +} + + +// Lu[Vݒ̏ +void TP_CalibrationInit( void ) +{ + GX_DispOff(); + GXS_DispOff(); + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + + PutStringUTF16( 0, 0, TXT_COLOR_BLUE, (const u16 *)L"TOUCH PANEL CALIBRATION" ); + + if( g_initialSet ) { + PutStringUTF16( 8 * 8, 18 * 8, TXT_COLOR_RED, (const u16 *)L"Calibrate touch panel." ); + } + + DisplayInit(); + + s_pCw = NNS_FndAllocFromAllocator( &g_allocator, sizeof(CalibWork) ); // Lu[Vpϐ̊m + if( s_pCw == NULL ) { + OS_Panic("ARM9- Fail to allocate memory...\n"); + } + SVC_CpuClear( 0x0000, s_pCw, sizeof(CalibWork), 16 ); + SVC_CpuClear( 0x0000, &tpd, sizeof(TpWork), 16 ); + + GX_SetVisiblePlane ( GX_PLANEMASK_BG0 | GX_PLANEMASK_OBJ ); + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); + GX_DispOn(); + GXS_DispOn(); + + s_pCw->seq = INIT; +} + + +// ^b`plݒ|Cg@Lf[^ +const u16 bitmapOBJPoint[8 * 8 * 5] = { + 0x0000, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x0000, // 0 char + 0xFC00, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0xFC00, // 0 char + 0xFC00, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0xFC00, // 0 char + 0xFC00, 0xFC00, 0xFC00, 0x801F, 0x801F, 0xFC00, 0xFC00, 0xFC00, // 0 char + 0xFC00, 0xFC00, 0xFC00, 0x801F, 0x801F, 0xFC00, 0xFC00, 0xFC00, // 0 char + 0xFC00, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0xFC00, // 0 char + 0xFC00, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0xFC00, // 0 char + 0x0000, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x0000, // 0 char + + 0x0000, 0x0000, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x0000, 0x0000, // 1 char + 0x0000, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x0000, // 1 char + 0xFC00, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0xFC00, // 1 char + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 1 char + + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 2 char + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 2 char + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 2 char + 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x801F, 0x801F, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, // 2 char + + 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x801F, 0x801F, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, // 3 char + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 3 char + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 3 char + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 3 char + + 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, // 4 char + 0xFC00, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0x0000, 0x0000, 0x0000, 0x0000, 0xFC00, 0xFC00, 0xFC00, // 4 char + 0x0000, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x0000, // 4 char + 0x0000, 0x0000, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0xFC00, 0x0000, 0x0000, // 4 char +}; + diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/main.c b/build/systemMenu_RED/MachineSettings/ARM9/src/main.c new file mode 100644 index 0000000..a0e8631 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/main.c @@ -0,0 +1,117 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "MachineSetting.h" + +// extern data----------------------------------------------------------------- + +// define data----------------------------------------------------------------- + +// function's prototype------------------------------------------------------- +static void InitAllocator( NNSFndAllocator* pAllocator ); +static void InitAllocSystem( void ); +static void INTR_VBlank( void ); + +// global variable------------------------------------------------------------- +NNSFndAllocator g_allocator; +int (*g_pNowProcess)( void ); +RTCDrawProperty g_rtcDraw = { + TRUE, RTC_DATE_TOP_X, RTC_DATE_TOP_Y, RTC_TIME_TOP_X, RTC_TIME_TOP_Y +}; + +// static variable------------------------------------------------------------- + +// const data------------------------------------------------------------------ + + +// ============================================================================ +// function's description +// ============================================================================ +void TwlMain(void) +{ + + // ---------------------------------- + OS_Init(); + + (void)OS_EnableIrq(); + (void)OS_EnableInterrupts(); + + GX_Init(); + GX_SetPower(GX_POWER_ALL); // eWbN p[ON + + // 荞݋---------------------------- + (void)OS_SetIrqFunction(OS_IE_V_BLANK, INTR_VBlank); + (void)OS_EnableIrqMask(OS_IE_V_BLANK); + (void)GX_VBlankIntr(TRUE); + + // foCX------------------------------- + TP_Init(); + (void)RTC_Init(); + + // VXȅ------------------ + InitAllocator( &g_allocator ); + CMN_InitFileSystem( &g_allocator ); + + // NitroConfigDatã[h + (void)NVRAMm_ReadNitroConfigData( GetNCDWork() ); + SYSM_CaribrateTP(); + + InitBG(); + GetAndDrawRTCData( &g_rtcDraw, TRUE ); + MachineSettingInit(); + // C[v---------------------------- + while ( 1 ) { + OS_WaitIrq( 1, OS_IE_V_BLANK ); // VuN荞ݑ҂ + + ReadKeyPad(); // L[͂̎擾 + + (void)g_pNowProcess(); + + GetAndDrawRTCData( &g_rtcDraw, FALSE ); + } +} + + +// AP[^̏ +static void InitAllocator( NNSFndAllocator* pAllocator ) +{ + u32 arenaLow = MATH_ROUNDUP ( (u32)OS_GetMainArenaLo(), 16 ); + u32 arenaHigh = MATH_ROUNDDOWN( (u32)OS_GetMainArenaHi(), 16 ); + u32 heapSize = arenaHigh - arenaLow; + void* heapMemory = OS_AllocFromMainArenaLo( heapSize, 16 ); + NNSFndHeapHandle heapHandle; + SDK_NULL_ASSERT( pAllocator ); + + heapHandle = NNS_FndCreateExpHeap( heapMemory, heapSize ); + SDK_ASSERT( heapHandle != NNS_FND_HEAP_INVALID_HANDLE ); + + NNS_FndInitAllocatorForExpHeap( pAllocator, heapHandle, 4 ); +} + + +// ============================================================================ +// 荞ݏ +// ============================================================================ + +// VuN荞 +static void INTR_VBlank(void) +{ + OS_SetIrqCheckFlag(OS_IE_V_BLANK); // VuN`FbÑZbg +} + diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/misc.c b/build/systemMenu_RED/MachineSettings/ARM9/src/misc.c new file mode 100644 index 0000000..03f8c50 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/misc.c @@ -0,0 +1,601 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: misc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" + +// define data----------------------------------------------------------------- +#define NTR_IPL_FONT_DATA "data/NTR_IPL_font_m.NFTR" + +#define STRING_LENGTH_MAX 256 + +#define GRAY(x) GX_RGB(x, x, x) + +enum +{ + TXT_CPALETTE_MAIN, + TXT_CPALETTE_USERCOLOR, + TXT_CPALETTE_4BPP, + TXT_NUM_CPALEETE +}; + +// fʂ̃J[pbg +GXRgb TXTColorPalette[TXT_NUM_CPALEETE * 16] = +{ + GX_RGB(31, 31, 31), GX_RGB(31, 31, 31), GX_RGB( 0, 0, 0), GX_RGB(31, 0, 0), + GX_RGB( 0, 31, 0), GX_RGB( 0, 0, 31), GX_RGB( 0, 31, 31), GX_RGB(31, 0, 31), + GX_RGB(31, 31, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), + GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), GX_RGB( 0, 0, 0), + + GX_RGB( 0, 0, 0), GX_RGB(12, 16, 19), GX_RGB(23, 9, 0), GX_RGB(31, 0, 3), + GX_RGB(31, 17, 31), GX_RGB(31, 18, 0), GX_RGB(30, 28, 0), GX_RGB(21, 31, 0), + GX_RGB( 0, 20, 7), GX_RGB( 9, 27, 17), GX_RGB( 6, 23, 30), GX_RGB( 0, 11, 30), + GX_RGB( 0, 0, 18), GX_RGB(17, 0, 26), GX_RGB(26, 0, 29), GX_RGB(31, 0, 18), + + GRAY(31), GRAY(29), GRAY(27), GRAY(25), + GRAY(23), GRAY(21), GRAY(19), GRAY(17), + GRAY(15), GRAY(14), GRAY(12), GRAY(10), + GRAY( 8), GRAY( 6), GRAY( 3), GRAY( 0), +}; + +// extern data----------------------------------------------------------------- + +// define data----------------------------------------------------------------- +#define CANVAS_WIDTH 32 // `̕ (LN^P) +#define CANVAS_HEIGHT 24 // `̍ (LN^P) +#define CANVAS_LEFT 0 // `̈ʒuX (LN^P) +#define CANVAS_TOP 0 // `̈ʒuY (LN^P) + +#define TEXT_HSPACE 1 // `掞̕ (sNZP) +#define TEXT_VSPACE 1 // `掞̍s (sNZP) + +#define CHARACTER_OFFSET 0 // gpLN^̊Jnԍ + +// RTCf[^\ʒu[N +typedef struct RtcDrawPos{ + int date_x; + int date_y; + int time_x; + int time_y; +}RtcDrawPos; + +// function's prototype------------------------------------------------------- +static BOOL WaitDetachTP( void ); +static void StartDetachTP( void ); +static void InitScreen( void ); +static void InitCanvas( void ); + +// global variable------------------------------------------------------------- +KeyWork pad; // L[pbh̓f[^ +TpWork tpd; // ^b`pl̓f[^ + +NNSG2dFont gFont; // tHg +NNSG2dCharCanvas gCanvas; // CharCanvas +NNSG2dTextCanvas gTextCanvas; // TextCanvas +NNSG2dCharCanvas gCanvasSub; // CharCanvas +NNSG2dTextCanvas gTextCanvasSub; // TextCanvas + +// static variable------------------------------------------------------------- +static int s_detach_count; +static RtcDrawPos s_rtcPos; +static RTCDate s_rtcDate; +static RTCTime s_rtcTime; +static u16 s_vcount; + +static char s_strBuffer[ STRING_LENGTH_MAX * 2 ] ATTRIBUTE_ALIGN(2); +static u16 s_strBufferUTF16[ STRING_LENGTH_MAX ]; + +// const data------------------------------------------------------------------ + +// jf[^\pR[h +const u8 *const g_strWeek[] ATTRIBUTE_ALIGN(2) = { + (const u8 *)"SUN", + (const u8 *)"MON", + (const u8 *)"TUE", + (const u8 *)"WED", + (const u8 *)"THU", + (const u8 *)"FRI", + (const u8 *)"SAT", +}; + +// ============================================================================ +// function's description +// ============================================================================ + +// BG +void InitBG(void) +{ + // OFF + GX_DispOff(); + GXS_DispOff(); + + // VRAM̊蓖ĂSĉ + GX_DisableBankForBG(); + GX_DisableBankForOBJ(); + GX_DisableBankForSubBG(); + GX_DisableBankForSubOBJ(); + + // C2DGW̏o͂ʂ + GX_SetDispSelect( GX_DISP_SELECT_SUB_MAIN ); + + // CLCD + { + // VRAM蓖 + GX_SetBankForBG ( GX_VRAM_BG_128_A ); + GX_SetBankForOBJ( GX_VRAM_OBJ_128_B ); + + MI_CpuClearFast( (void *)HW_BG_VRAM, 0x20000 ); // BG -VRAM NA + MI_CpuClearFast( (void *)HW_OBJ_VRAM, 0x20000 ); // OBJ-VRAM NA + + // J[pbgݒ + GX_LoadBGPltt( TXTColorPalette, 0, sizeof(TXTColorPalette) ); + + // BG[hݒ + GX_SetGraphicsMode( GX_DISPMODE_GRAPHICS, GX_BGMODE_0, GX_BG0_AS_2D ); + + GX_SetBGScrOffset ( GX_BGSCROFFSET_0x10000 ); + GX_SetBGCharOffset( GX_BGCHAROFFSET_0x00000 ); + } + // TuLCD + { + // VRAM蓖 + GX_SetBankForSubBG ( GX_VRAM_SUB_BG_128_C ); // VRAM-C for BGs + GX_SetBankForSubOBJ( GX_VRAM_SUB_OBJ_128_D ); // VRAM-D for BGs + + MI_CpuClearFast( (void *)HW_DB_BG_VRAM, 0x20000 ); // BG -VRAM NA + MI_CpuClearFast( (void *)HW_DB_OBJ_VRAM, 0x20000 ); // OBJ -VRAM NA + + // J[pbgݒ + GXS_LoadBGPltt( TXTColorPalette, 0, sizeof(TXTColorPalette) ); + + // BG[hݒ + GXS_SetGraphicsMode( GX_BGMODE_0 ); // BGMODE is 0 + } + InitScreen(); + InitCanvas(); +} + + +// XN[ +static void InitScreen( void ) +{ + // C BG 0 ݒ + G2_SetBG0Control( + GX_BG_SCRSIZE_TEXT_256x256, // XN[TCY 256x256 + GX_BG_COLORMODE_16, // J[[h 16F + GX_BG_SCRBASE_0xf800, // XN[x[X + GX_BG_CHARBASE_0x00000, // LN^x[X + GX_BG_EXTPLTT_01 // gpbgXbg + ); + GX_SetVisiblePlane( GX_PLANEMASK_BG0 ); + + // Tu BG 0 ݒ + G2S_SetBG0Control( + GX_BG_SCRSIZE_TEXT_256x256, // 256pix x 256pix text + GX_BG_COLORMODE_16, // use 256 colors mode + GX_BG_SCRBASE_0xf800, // screen base offset + 0x0000 is the address for BG #0 screen + GX_BG_CHARBASE_0x00000, // character base offset + 0x04000 is the address for BG #0 characters + GX_BG_EXTPLTT_01 // use BGExtPltt slot #0 if BGExtPltt is enabled + ); + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); // display only BG #0 +} + + +// `̏ +static void InitCanvas( void ) +{ + // tHgǂݍ݂܂ + { + void* pFontFile; + u32 size = CMN_LoadFile( &pFontFile, NTR_IPL_FONT_DATA, &g_allocator); + NNS_G2D_ASSERT( size > 0 ); + NNS_G2dFontInitUTF16(&gFont, pFontFile); +// NNS_G2dPrintFont(&gFont); + } + + { + // CharCanvas ̏ + NNS_G2dCharCanvasInitForBG( + &gCanvas, + (GXCharFmt16*)G2_GetBG0CharPtr() + CHARACTER_OFFSET, + CANVAS_WIDTH, + CANVAS_HEIGHT, + NNS_G2D_CHARA_COLORMODE_16 + ); + + // TextCanvas̏ + NNS_G2dTextCanvasInit( + &gTextCanvas, + &gCanvas, + &gFont, + TEXT_HSPACE, + TEXT_VSPACE + ); + + // XN[ݒ + NNS_G2dMapScrToCharText( + G2_GetBG0ScrPtr(), + CANVAS_WIDTH, + CANVAS_HEIGHT, + CANVAS_LEFT, + CANVAS_TOP, + NNS_G2D_TEXT_BG_WIDTH_256, + CHARACTER_OFFSET, + TXT_CPALETTE_MAIN + ); + } + { + // CharCanvas ̏ + NNS_G2dCharCanvasInitForBG( + &gCanvasSub, + (GXCharFmt16*)G2S_GetBG0CharPtr() + CHARACTER_OFFSET, + CANVAS_WIDTH, + CANVAS_HEIGHT, + NNS_G2D_CHARA_COLORMODE_16 + ); + + // TextCanvas̏ + NNS_G2dTextCanvasInit( + &gTextCanvasSub, + &gCanvasSub, + &gFont, + TEXT_HSPACE, + TEXT_VSPACE + ); + + // XN[ݒ + NNS_G2dMapScrToCharText( + G2S_GetBG0ScrPtr(), + CANVAS_WIDTH, + CANVAS_HEIGHT, + CANVAS_LEFT, + CANVAS_TOP, + NNS_G2D_TEXT_BG_WIDTH_256, + CHARACTER_OFFSET, + TXT_CPALETTE_MAIN + ); + } +} + + +// UTF16ł̒ڕ\ +void PutStringUTF16( int x, int y, int color, const u16 *strUTF16 ) +{ + NNS_G2dTextCanvasDrawText( &gTextCanvas, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + strUTF16 ); +} + +void PutStringUTF16Sub( int x, int y, int color, const u16 *strUTF16 ) +{ + NNS_G2dTextCanvasDrawText( &gTextCanvasSub, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + strUTF16 ); +} + + +// tō쐬\ꍇ̕擾 +int GetPrintfWidth( const NNSG2dTextCanvas *pCanvas, const char *fmt, ... ) +{ + int srcLen; + int dstLen = sizeof(s_strBufferUTF16); + va_list vlist; + va_start(vlist, fmt); + srcLen = STD_TVSNPrintf( s_strBuffer, sizeof(s_strBuffer), fmt, vlist); + va_end(vlist); + s_strBuffer[ srcLen ] = 0; + + (void)STD_ConvertStringSjisToUnicode( s_strBufferUTF16, &dstLen, s_strBuffer, &srcLen, NULL ); + s_strBufferUTF16[ dstLen ] = 0; + + return NNS_G2dTextCanvasGetTextWidth( pCanvas, s_strBufferUTF16 ); +} + + +// SJISPrintf`ŕ\iUTF16ɕϊ) +void PrintfSJIS( int x, int y, int color, const char *fmt, ... ) +{ + int srcLen; + int dstLen = sizeof(s_strBufferUTF16); + va_list vlist; + va_start(vlist, fmt); + srcLen = STD_TVSNPrintf( s_strBuffer, sizeof(s_strBuffer), fmt, vlist); + va_end(vlist); + s_strBuffer[ srcLen ] = 0; + + (void)STD_ConvertStringSjisToUnicode( s_strBufferUTF16, &dstLen, s_strBuffer, &srcLen, NULL ); + s_strBufferUTF16[ dstLen ] = 0; + + NNS_G2dTextCanvasDrawText(&gTextCanvas, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + s_strBufferUTF16 ); +} + +void PrintfSJISSub( int x, int y, int color, const char *fmt, ... ) +{ + int srcLen; + int dstLen = sizeof(s_strBufferUTF16); + va_list vlist; + va_start(vlist, fmt); + srcLen = STD_TVSNPrintf( s_strBuffer, sizeof(s_strBuffer), fmt, vlist); + va_end(vlist); + s_strBuffer[ srcLen ] = 0; + + (void)STD_ConvertStringSjisToUnicode( s_strBufferUTF16, &dstLen, s_strBuffer, &srcLen, NULL ); + s_strBufferUTF16[ dstLen ] = 0; + + NNS_G2dTextCanvasDrawText(&gTextCanvasSub, x, y, color, TXT_DRAWTEXT_FLAG_DEFAULT, + s_strBufferUTF16 ); +} + + +// L[͓ǂݏo-------------------------------- +void ReadKeyPad(void) +{ + u16 readData = PAD_Read(); + pad.trg = (u16)(readData & (readData ^ pad.cont)); // gK + pad.cont = readData; // x^ +} + + +// ^b`plf[^̎擾----------------------- +void ReadTP(void) +{ + TP_GetCalibratedPoint( &tpd.last, &tpd.raw ); // OTPf[^ޔ + + if( TP_RequestRawSampling(&tpd.raw) ) { // ^b`pl̃TvO + SVC_CpuClear(0x0000, &tpd.raw, sizeof(tpd.raw), 16); // SPI-busyŃf[^擾Ɏśhf[^ȂhŃ^[B + return; + } + TP_GetCalibratedPoint( &tpd.disp, &tpd.raw ); // TPWLCDWɕϊB + + if( !WaitDetachTP() ) { // TPf^b`҂sB + SVC_CpuClear(0x0000, &tpd.disp, sizeof(tpd.disp), 16); // SPI-busyŃf[^擾Ɏśhf[^ȂhŃ^[B + return; + } +#if 1 + if(tpd.disp.touch) { // ݂TPf[^\ + switch ( tpd.disp.validity ) { + case TP_VALIDITY_VALID: + OS_Printf("( %3d, %3d ) -> ( %3d, %3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + case TP_VALIDITY_INVALID_X: + OS_Printf("( *%3d, %3d ) -> ( *%3d, %3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + case TP_VALIDITY_INVALID_Y: + OS_Printf("( %3d, *%3d ) -> ( %3d, *%3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + case TP_VALIDITY_INVALID_XY: + OS_Printf("( *%3d, *%3d ) -> ( *%3d, *%3d )\n", tpd.raw.x, tpd.raw.y, tpd.disp.x, tpd.disp.y); + break; + } + } +#endif +} + + +// TPf^b`҂ +static BOOL WaitDetachTP( void ) +{ + // s_detach_countnĂAJEgB + if(s_detach_count > 0) { + if(tpd.disp.touch == 0) { // TPĂȂ΁AJEgisKlōē͂󂯕tB + s_detach_count--; + }else { + s_detach_count = TP_CSR_DETACH_COUNT; + } + return FALSE; + } + return TRUE; +} + + +// TPf^b`҂̊Jn +static void StartDetachTP( void ) +{ + s_detach_count = TP_CSR_DETACH_COUNT; +} + + +//====================================================== +// j[ +//====================================================== + +// j[` +void DrawMenu( u16 nowCsr, const MenuParam *pMenu ) +{ + int i; + int color; + + for( i = 0; i < pMenu->num; i++ ) { + if(i == nowCsr) { + if( !pMenu->pos[ i ].enable ) { + color = pMenu->disable_color; + }else { + color = pMenu->select_color; + } + }else { + color = pMenu->normal_color; + } + PutStringUTF16( pMenu->pos[ i ].x, pMenu->pos[ i ].y, color, (pMenu->str_elem)[ i ] ); + } +} + + +// ^b`plɂ郁j[I +BOOL SelectMenuByTP( u16 *nowCsr, const MenuParam *pMenu ) +{ + u16 i; + TPData *target; + static u16 detach_count = 0; + static u16 csr_old = 0xff; + static u16 same_csr_count = 0; + + // detach_countnĂAJEgB + if( detach_count > 0 ) { + if( tpd.disp.touch == 0 ) { // TPĂȂ΁AJEgisAPOJEgŃj[I + if( ++detach_count == TP_CSR_DETACH_COUNT ) { + detach_count = 0; + return TRUE; + }else { + return FALSE; + } + } + } + detach_count=0; // detachJEgl̃NA + + // ʏ́ATPf[^j[ɂ邩ǂ𔻒B + if( tpd.disp.touch ) target = &tpd.disp; + else target = &tpd.last; + + for( i = 0; i < pMenu->num; i++ ) { + if( tpd.disp.touch ) { // ^b`plj[̗vfŃ^b`ĂȂA + NNSG2dTextRect rect = NNS_G2dTextCanvasGetTextRect( &gTextCanvas, (pMenu->str_elem)[ i ] ); + u16 top_x = (u16)( pMenu->pos[ i ].x ); // j[vfLCDWZo + u16 top_y = (u16)( pMenu->pos[ i ].y ); + u16 bottom_x = (u16)( top_x + rect.width ); + u16 bottom_y = (u16)( top_y + rect.height ); + + OS_TPrintf( "MENU[ %d ] : top_x = %02d top_y = %02d bot_x = %02d bot_y = %02d : ", + i, top_x, top_y, bottom_x, bottom_y ); + + if( WithinRangeTP( top_x, top_y, bottom_x, bottom_y, target ) ) { + OS_TPrintf( "InRange\n" ); + if( tpd.disp.validity == TP_VALIDITY_VALID ) { // J[\̗vfɈړ + if( csr_old == i ) { + if( same_csr_count < TP_CSR_TOUCH_COUNT ) { + same_csr_count++; + }else { + *nowCsr = i; + } + return FALSE; + }else { + csr_old = i; + } + break; + } + }else { + OS_TPrintf( "OutRange\n" ); + } + }else { // touch==0 + if( same_csr_count == TP_CSR_TOUCH_COUNT ) { + detach_count = 1; + break; + } + } + } + same_csr_count = 0; + return FALSE; +} + + +// ݂̃^b`plWẅɂ邩ǂԂB +BOOL WithinRangeTP( int top_x, int top_y, int bottom_x, int bottom_y, TPData *tgt ) +{ + if( ( tgt->x >= top_x ) && + ( tgt->x <= bottom_x ) && + ( tgt->y >= top_y ) && + ( tgt->y <= bottom_y ) ) { + OS_TPrintf( "\nRANGE : tx=%3d ty=%3d bx=%3d by=%3d : x=%3d y=%3d\n", + top_x, top_y, bottom_x, bottom_y, tgt->x, tgt->y ); + return TRUE; + }else { + return FALSE; + } +} + + +// oi[ACROBJ̃[h +void SetBannerIconOBJ( GXOamAttr *pDstOAM, BannerFileV1 *bannerp ) +{ + GXS_LoadOBJPltt( bannerp->pltt, 15, BNR_PLTT_SIZE ); + MI_CpuCopyFast( bannerp->image, (void *)(HW_DB_OBJ_VRAM + 0x20), BNR_IMAGE_SIZE ); + G2_SetOBJAttr( pDstOAM, // OAM pointer + 32, // X position + 32, // Y position + 0, // Priority + GX_OAM_MODE_NORMAL, // Bitmap mode + FALSE, // mosaic off + GX_OAM_EFFECT_NONE, // affine off + GX_OAM_SHAPE_32x32, // 16x16 size + GX_OAM_COLOR_16, // 16 color + 1, // charactor + 15, // palette + 0); // affine +} + + +//=============================================== +// RTCANZX[` +//=============================================== + +// RTCf[^̎擾 +BOOL GetRTCData( RTCDrawProperty *pRTCDraw, BOOL forceGetFlag ) +{ + if( forceGetFlag || ( pRTCDraw->vcount++ == 59 ) ) { + pRTCDraw->vcount = 0; + MI_CpuCopy16( &pRTCDraw->date, &pRTCDraw->date_old, sizeof(RTCDate) ); + MI_CpuCopy16( &pRTCDraw->time, &pRTCDraw->time_old, sizeof(RTCTime) ); + (void)RTC_GetDateTime( &pRTCDraw->date, &pRTCDraw->time ); + return TRUE; + } + return FALSE; +} + + +// RTCf[^̕\ +void DrawRTCData( RTCDrawProperty *pRTCDraw ) +{ + void (*pPrintFunc)( int x, int y, int color, const char *fmt, ... ) = + ( pRTCDraw->isTopLCD ) ? PrintfSJISSub : PrintfSJIS; + + // ORTC̏ + { + u32 year = pRTCDraw->date_old.year + 2000; + pPrintFunc( pRTCDraw->date_x, pRTCDraw->date_y, TXT_COLOR_WHITE, "%04d/%02d/%02d[%3s]", + year, + pRTCDraw->date_old.month, + pRTCDraw->date_old.day, + g_strWeek[ pRTCDraw->date_old.week ] + ); + pPrintFunc( pRTCDraw->time_x, pRTCDraw->time_y, TXT_COLOR_WHITE, "%02d:%02d:%02d", + pRTCDraw->time_old.hour, + pRTCDraw->time_old.minute, + pRTCDraw->time_old.second + ); + } + // RTC̕\ + { + u32 year = pRTCDraw->date.year + 2000; + pPrintFunc( pRTCDraw->date_x, pRTCDraw->date_y, TXT_COLOR_BLACK, "%d/%02d/%02d[%3s]", + year, + pRTCDraw->date.month, + pRTCDraw->date.day, + g_strWeek[ pRTCDraw->date.week ] + ); + pPrintFunc( pRTCDraw->time_x, pRTCDraw->time_y, TXT_COLOR_BLACK, "%02d:%02d:%02d", + pRTCDraw->time.hour, + pRTCDraw->time.minute, + pRTCDraw->time.second + ); + } +} + +// RTCf[^̎擾&\ +void GetAndDrawRTCData( RTCDrawProperty *pRTCDraw, BOOL forceGetFlag ) +{ + if( GetRTCData( pRTCDraw, forceGetFlag ) ) { + DrawRTCData( pRTCDraw ); + } +} diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/misc.h b/build/systemMenu_RED/MachineSettings/ARM9/src/misc.h new file mode 100644 index 0000000..e0f0a40 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/misc.h @@ -0,0 +1,168 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: misc.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __MISC_H__ +#define __MISC_H__ + +#include +#include + +#define NNS_G2D_UNICODE +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// define data---------------------------------------------------------- +#define TP_CSR_TOUCH_COUNT 2 // TPJ[\̃`^Oẑ߂̃JEgl +#define TP_CSR_DETACH_COUNT 2 // TPJ[\uIvƔ肷TPf^b`̃JEgl + +// DrawText ł̍ +#define TXT_DRAWTEXT_FLAG_DEFAULT (NNS_G2D_VERTICALORIGIN_TOP | NNS_G2D_HORIZONTALORIGIN_LEFT | NNS_G2D_HORIZONTALALIGN_LEFT) + +// TXTColorPalette ̐F 16Fpbgւ̃[hz +enum +{ + // pbg0 TXT_CPALETTE_MAIN + TXT_COLOR_NULL=0, + TXT_COLOR_WHITE, + TXT_COLOR_BLACK, + TXT_COLOR_RED, + TXT_COLOR_GREEN, + TXT_COLOR_BLUE, + TXT_COLOR_CYAN, + TXT_COLOR_MAGENTA, + TXT_COLOR_YELLOW, + + // pbg1 TXT_CPALETTE_USERCOLOR + TXT_UCOLOR_NULL=0, + TXT_UCOLOR_GRAY, + TXT_UCOLOR_BROWN, + TXT_UCOLOR_RED, + TXT_UCOLOR_PINK, + TXT_UCOLOR_ORANGE, + TXT_UCOLOR_YELLOW, + TXT_UCOLOR_LIMEGREEN, + TXT_UCOLOR_DARKGREEN, + TXT_UCOLOR_SEAGREEN, + TXT_UCOLOR_TURQUOISE, + TXT_UCOLOR_BLUE, + TXT_UCOLOR_DARKBLUE, + TXT_UCOLOR_PURPLE, + TXT_UCOLOR_VIOLET, + TXT_UCOLOR_MAGENTA, + + // pbg TXT_CPALETTE_4BPP + TXT_COLOR_4BPP_NULL=0, + TXT_COLOR_4BPP_BG=1, + TXT_COLOR_4BPP_TEXT=1 +}; + + +// v\ꏊ +#define RTC_DATE_TOP_X ( 9 * 8 ) +#define RTC_DATE_TOP_Y ( 10 * 8 ) +#define RTC_TIME_TOP_X ( 12 * 8 ) +#define RTC_TIME_TOP_Y ( 12 * 8 ) + + +// L[f[^[N +typedef struct { + u16 trg; // gK + u16 cont; // x^ +}KeyWork; + + +// ^b`pl[N +typedef struct { + int detached; // ̃f[^͂Ń^b`ꂽƂB + TPData disp; // ̓͒liLCDWj + TPData raw; // ̓͒liTP Wj + TPData last; // O̓͒liLCDWj +}TpWork; + + +// j[vfW +typedef struct MenuPos { + BOOL enable; + int x; + int y; +}MenuPos; + + +// j[\p[^\ +typedef struct MenuParam { + int num; + int normal_color; + int select_color; + int disable_color; + MenuPos *pos; + const u16 **str_elem; +}MenuParam; + + +// RTCf[^\ʒu[N +typedef struct RTCDrawProperty { + BOOL isTopLCD; + int date_x; + int date_y; + int time_x; + int time_y; + int vcount; + RTCDate date; + RTCTime time; + RTCDate date_old; + RTCTime time_old; +}RTCDrawProperty; + +// global variables-------------------------------------------------- +extern TpWork tpd; // ^b`plf[^ +extern KeyWork pad; // L[pbh̓f[^ +extern const u8 *const g_strWeek[ 7 ]; // j +extern RTCDrawProperty g_rtcDraw; + +extern NNSFndAllocator g_allocator; // AP[^ +extern NNSG2dFont gFont; // tHg +extern NNSG2dCharCanvas gCanvas; // CharCanvas +extern NNSG2dTextCanvas gTextCanvas; // TextCanvas + +// function------------------------------------------------------------- +void InitBG( void ); +int GetPrintfWidth( const NNSG2dTextCanvas *pCanvas, const char *fmt, ... ); +void PutStringUTF16 ( int x, int y, int color, const u16 *strUTF16 ); +void PutStringUTF16Sub( int x, int y, int color, const u16 *strUTF16 ); +void PrintfSJIS ( int x, int y, int color, const char *fmt, ... ); +void PrintfSJISSub( int x, int y, int color, const char *fmt, ... ); +void ReadKeyPad( void ); +void ReadTP( void ); +void DrawMenu( u16 nowCsr, const MenuParam *pMenu ); +BOOL SelectMenuByTP( u16 *nowCsr, const MenuParam *pMenu ); +BOOL WithinRangeTP( int top_x, int top_y, int bottom_x, int bottom_y, TPData *tgt ); +void SetBannerIconOBJ( GXOamAttr *pDstOAM, BannerFileV1 *bannerp ); +BOOL GetRTCData( RTCDrawProperty *pRTCDraw, BOOL forceGetFlag ); +void DrawRTCData( RTCDrawProperty *pRTCDraw ); +void GetAndDrawRTCData( RTCDrawProperty *pRTCDraw, BOOL forceGetFlag ); + +#ifdef __cplusplus +} +#endif + +#endif // __MISC_H__ diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/selectLanguage.c b/build/systemMenu_RED/MachineSettings/ARM9/src/selectLanguage.c new file mode 100644 index 0000000..49b3f64 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/selectLanguage.c @@ -0,0 +1,148 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SelectLanguage.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "MachineSetting.h" + +// define data------------------------------------------ +#define CANCEL_BUTTON_TOP_X ( 2 * 8 ) +#define CANCEL_BUTTON_TOP_Y ( 21 * 8 ) +#define CANCEL_BUTTON_BOTTOM_X ( (CANCEL_BUTTON_TOP_X + 8 ) * 8 ) +#define CANCEL_BUTTON_BOTTOM_Y ( (CANCEL_BUTTON_TOP_Y + 2 ) * 8 ) + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- + +// global variable ------------------------------------- + +// static variable ------------------------------------- +static NvLangCode s_langCode; // R[h + +// const data ----------------------------------------- +static const u16 *const s_pStrLanguage[] = { + (const u16 *)L"{", + (const u16 *)L"English ", + (const u16 *)L"Francais", + (const u16 *)L"Deutsch ", + (const u16 *)L"Italiano", + (const u16 *)L"Espanol ", +}; + +static MenuPos s_languagePos[] = { + { TRUE, 4 * 8, 6 * 8 }, + { TRUE, 4 * 8, 8 * 8 }, + { TRUE, 4 * 8, 10 * 8 }, + { TRUE, 4 * 8, 12 * 8 }, + { TRUE, 4 * 8, 14 * 8 }, + { TRUE, 4 * 8, 16 * 8 }, +}; + +static const MenuParam langSel = { + 6, + TXT_COLOR_BLACK, + TXT_COLOR_GREEN, + TXT_COLOR_RED, + &s_languagePos[ 0 ], + (const u16 **)&s_pStrLanguage, +}; + + +//====================================================== +// function's description +//====================================================== + +// ݒ̏ +void SelectLanguageInit( void ) +{ + GX_DispOff(); + GXS_DispOff(); + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + + PutStringUTF16( 0, 0, TXT_COLOR_BLUE, (const u16 *)L"LANGUAGE SELECT" ); + PutStringUTF16( CANCEL_BUTTON_TOP_X, CANCEL_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L"CANCEL" ); + if( g_initialSet ) { + PutStringUTF16( 8 * 8, 18 * 8, TXT_COLOR_RED, (const u16 *)L"Select language." ); + } + + if( ( GetSYSMWork()->ncd_invalid ) || + ( GetNCDWork()->option.language >= LANG_CODE_MAX ) ) { + s_langCode = LANG_ENGLISH; + }else { + s_langCode = (NvLangCode)GetNCDWork()->option.language; + } + + DrawMenu( (u16)s_langCode, &langSel ); + + SVC_CpuClear( 0x0000, &tpd, sizeof(TpWork), 16 ); + + GX_SetVisiblePlane ( GX_PLANEMASK_BG0 ); + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); + GX_DispOn(); + GXS_DispOn(); +} + + +// I +int SelectLanguageMain( void ) +{ + BOOL tp_select,tp_cancel = FALSE; + + ReadTP(); // TP͂̎擾 + + //-------------------------------------- + // L[͏ + //-------------------------------------- + if( pad.trg & PAD_KEY_DOWN ) { // J[\̈ړ + if( ++s_langCode == LANG_CODE_MAX ) { + s_langCode = (NvLangCode)0; + } + } + if( pad.trg & PAD_KEY_UP ) { + if( --s_langCode < 0 ) { + s_langCode = (NvLangCode)( LANG_CODE_MAX - 1 ); + } + } + tp_select = SelectMenuByTP( (u16 *)&s_langCode, &langSel ); + DrawMenu( (u16)s_langCode, &langSel ); + + // [CANCEL]{^`FbN + if( tpd.disp.touch ) { + tp_cancel = WithinRangeTP( CANCEL_BUTTON_TOP_X, CANCEL_BUTTON_TOP_Y, + CANCEL_BUTTON_BOTTOM_X, CANCEL_BUTTON_BOTTOM_Y, &tpd.disp ); + } + + if( ( pad.trg & PAD_BUTTON_A ) || tp_select ) { // j[ڂւ̕ + GetSYSMWork()->ncd_invalid = 0; + GetNCDWork()->option.input_language = 1; // ̓tO𗧂Ă + GetNCDWork()->option.language = s_langCode; + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData( GetNCDWork() ); + MachineSettingInit(); + return 0; + }else if( ( pad.trg & PAD_BUTTON_B ) || tp_cancel ) { + MachineSettingInit(); + return 0; + } + + return 0; +} + + diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/setOwnerInfo.c b/build/systemMenu_RED/MachineSettings/ARM9/src/setOwnerInfo.c new file mode 100644 index 0000000..20f9457 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/setOwnerInfo.c @@ -0,0 +1,1077 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: ownerInfo.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include "misc.h" +#include "DS_Setting.h" +#include "myFontequ.h" + +/* + + jbNl[́ASJISŕۑĂ܂ANVRAMɂ͊eR[hHi/Lot]`Ŋi[Ă܂B + +*/ + +// define data---------------------------------- + +#define OWNER_INFO_ELEM_NUM 3 + + // RETURN{^LCD̈ +#define RETURN_BUTTON_LT_X 2 +#define RETURN_BUTTON_LT_Y 21 +#define RETURN_BUTTON_RB_X (RETURN_BUTTON_LT_X + 8) +#define RETURN_BUTTON_RB_Y (RETURN_BUTTON_LT_Y + 2) + + // I[i[J[\LCD̈ +#define OWNER_INFO_CSR_LT_X 2 +#define OWNER_INFO_CSR_LT_Y 5 +#define OWNER_INFO_CSR_NEXT_Y_NUM 3 + + // NJ[\LCD̈ +#define DAY_LT_X (OWNER_INFO_CSR_LT_X + 13) +#define DAY_LT_Y (OWNER_INFO_CSR_LT_Y + OWNER_INFO_CSR_NEXT_Y_NUM * 1) + + // DȐFJ[\LCD̈ +#define FCOLOR_LT_X (OWNER_INFO_CSR_LT_X + 13) +#define FCOLOR_LT_Y (OWNER_INFO_CSR_LT_Y + OWNER_INFO_CSR_NEXT_Y_NUM * 2) + + // \tgEFAL[{[hLCD̈ +#define CLIST_LT_X 4 +#define CLIST_LT_Y 7 +#define CLIST_RB_X (CLIST_LT_X + 24) +#define CLIST_RB_Y (CLIST_LT_Y + 12) + // {^擪LCD̈ +#define BUTTON_TOP_LT_X (CLIST_LT_X + 18) +#define BUTTON_TOP_LT_Y (CLIST_LT_Y + 2) +#define BUTTON_TOP_RB_X (BUTTON_TOP_LT_X + 8) +#define BUTTON_TOP_RB_Y (BUTTON_TOP_LT_Y + 2) + // ̓l[LCD̈ +#define INPUT_NAME_LT_X 11 +#define INPUT_NAME_LT_Y 3 + // LN^R[h +#define CHAR_MODE_HKANA 0 +#define CHAR_MODE_KKANA 1 +#define CHAR_MODE_EISUU 2 +#define CHAR_MODE_MAX CHAR_MODE_EISUU + + // jbNl[̓L +#define CHAR_USCORE 0x5181 // 'Q' (0x8151)t]́B + +#define CHAR_LIST_CHAR_NUM 120 + + // jbNl[͍\ +typedef struct Nickname { + u8 input_flag; // ̓tO + u8 change_flag; // ύXtO + u8 length; // + u8 pad; + u16 str[NCD_NICKNAME_LENGTH + 1]; // jbNl[R[h +}Nickname; + + // J[\X,YʒuiLPʁj +typedef struct CsrPos { + u16 x; // x + u16 y; // y +}CsrPos; + + // a +typedef struct Birthday { + int year; // N(1900-2099) + int month; // (1-12) + int day; // (1-31) +}Birthday; + + // vtB[ҏW[N +typedef struct OwnerWork { + u16 sel; + Nickname nickname; // jbNl[ + Birthday birthday; // N + int favoriteColor; // DȐF + + // [U[J[N̓[N + int seq; // V[PXԍ + int *tgtp; // ̓^[Qbgւ̃|C^ + InputNumParam inp; // l͊֐InputDecimalpp[^ + + // jbNl[̓[N + u16 char_mode; // ̓LN^[hiȁAJiApj + u16 rsv; // \CsrPos̃ACĝ߂̃pfBO + CsrPos tpcsr; // TPɂĎZoJ[\ʒu + CsrPos csr_now; // ݂̃J[\ʒuiL[TP̗ZoLȒlj + CsrPos csr_old; // Ot[̃J[\ʒu + u16 detach_count; // TPLȃJ[\ʒu痣ẴJEgl + u16 touch_count; // TPLȃJ[\ʒuŃ^b`ĂԂ̃JEgl + u16 handleTbl[CHAR_LIST_CHAR_NUM]; // LN^Xgpnhi[z +}OwnerWork; + +// extern data---------------------------------- + + +// function's prototype------------------------- +void SEQ_OwnerInfo_init(void); +int SEQ_OwnerInfo(void); + +static void SEQ_InputBirthday_init(void); +static int SEQ_InputBirthday(void); +static void SEQ_InputFavoriteColor_init(void); +static int SEQ_InputFavoriteColor(void); +static void DrawBirthday(u16 x, u16 y, u16 color, NvDate *birthp); +static void SEQ_InputNickname_init(void); +static int SEQ_InputNickname(void); +static void ReturnMenu(int save_flag); +static u16 CalcTblIndex(CsrPos *csrp); +static void DeleteName1Char(void); +static void MoveCharCursor(int force_flag); +static BOOL MoveCharCursorTp(CsrPos *csrp); +static void DrawTargetCsrChar(CsrPos *csrp, u16 color); +static void DrawCharacterList(void); +static void SetSoftKeyboardButton(u16 char_mode); +static void SJISCodeExchangeCopy(u16 *srcp, u16 *dstp, u16 length); + +// static variable------------------------------ +static OwnerWork *ow; + +// const data----------------------------------- +static const u16 char_tbl[3][CHAR_LIST_CHAR_NUM]; + +static const u8 *const str_ownerInfoSel[] ATTRIBUTE_ALIGN(2) = { + (const u8 *)"NICKNAME ", + (const u8 *)"BIRTHDAY ", + (const u8 *)"USER COLOR", +}; + +const MenuComponent ownerInfoSel={ + OWNER_INFO_ELEM_NUM, + OWNER_INFO_CSR_LT_X, + OWNER_INFO_CSR_LT_Y, + 0, + OWNER_INFO_CSR_NEXT_Y_NUM, + 23, + WHITE, + HIGHLIGHT_Y, + (const u8 **)&str_ownerInfoSel, +}; + +static const u8 str_button_hkana[] ATTRIBUTE_ALIGN(2) = " "; +static const u8 str_button_kkana[] ATTRIBUTE_ALIGN(2) = " Ji "; +static const u8 str_button_eisuu[] ATTRIBUTE_ALIGN(2) = " ABC "; +static const u8 str_button_del[] ATTRIBUTE_ALIGN(2) = " DEL "; +static const u8 str_button_cancel[] ATTRIBUTE_ALIGN(2) = "CANCEL"; +static const u8 str_button_ok[] ATTRIBUTE_ALIGN(2) = " OK "; +static const u16 *str_button[] = { NULL, + NULL, + (const u16 *)str_button_del, + (const u16 *)str_button_cancel, + (const u16 *)str_button_ok, + }; +//static const u16 str_uscore[] = { uscore_, uscore_, uscore_, uscore_, uscore_, uscore_, uscore_, uscore_, EOM_}; + +//====================================================== +// I[i[ҏW +//====================================================== + +// I[i[ҏW̏ +void SEQ_OwnerInfo_init(void) +{ + u16 x,y; + u16 temp[NCD_NICKNAME_LENGTH + 1]; + + GXS_SetVisiblePlane(GX_PLANEMASK_NONE); + + MI_CpuClearFast(bgBakS,sizeof(bgBakS)); + SVC_CpuClearFast(0xc0, oamBakS, sizeof(oamBakS)); + + ClearAllStringSJIS(); + + (void)DrawStringSJIS( 1, 0, YELLOW, (const u8 *)"USER INFO SET"); + (void)DrawStringSJIS( RETURN_BUTTON_LT_X, RETURN_BUTTON_LT_Y,HIGHLIGHT_C, (const u8 *)" RETURN "); + + if(ow == NULL) { + ow = NNS_FndAllocFromAllocator( &g_allocator, sizeof(OwnerWork) ); // I[i[ҏWp[N̊m +#ifdef __SYSM_DEBUG + if(ow == NULL) OS_Panic("ARM9- Fail to allocate memory...\n"); +#endif /* __SYSM_DEBUG */ + OS_Printf("Alloc :OwnerWork\n"); + SVC_CpuClear(0x0000, ow, sizeof(OwnerWork), 16); + } + + // I[i[̃`FbN + { + u32 dayNum; + + if(GetNCDWork()->owner.nickname.length > NCD_NICKNAME_LENGTH) { + GetNCDWork()->owner.nickname.length = 0; + SVC_CpuClear(0x0000, GetNCDWork()->owner.nickname.str, NCD_NICKNAME_LENGTH * 2, 16); + } + if((GetNCDWork()->owner.birthday.month == 0) || (GetNCDWork()->owner.birthday.month > 12)) { + GetNCDWork()->owner.birthday.month = 1; + } + dayNum = SYSM_GetDayNum( 0, (u32)GetNCDWork()->owner.birthday.month ); + if((GetNCDWork()->owner.birthday.day == 0) || (GetNCDWork()->owner.birthday.day > dayNum)) { + GetNCDWork()->owner.birthday.day = 1; + } + if( GetNCDWork()->owner.favoriteColor >= NCD_FAVORITE_COLOR_MAX_NUM ) { + GetNCDWork()->owner.favoriteColor = 0; + } + } + + // I[i[̕\ + x = (u16)(ownerInfoSel.pos_x+13); + y = (u16)ownerInfoSel.pos_y; + SVC_CpuClear(0x0000, temp, sizeof(temp), 16); + ExUTF16_LEtoSJIS_BE( (u8 *)temp, GetNCDWork()->owner.nickname.str, GetNCDWork()->owner.nickname.length); + (void)DrawStringSJIS ( x, y, LIGHTGREEN, temp); + DrawBirthday ( x, (u16)(y + OWNER_INFO_CSR_NEXT_Y_NUM * 1), LIGHTGREEN, &GetNCDWork()->owner.birthday); + ow->favoriteColor = GetNCDWork()->owner.favoriteColor; + (void)DrawDecimalSJIS( x, (u16)(y + OWNER_INFO_CSR_NEXT_Y_NUM * 2), LIGHTGREEN, &ow->favoriteColor, 2, 1); + + DrawMenu(ow->sel, &ownerInfoSel); + SVC_CpuClear(0x0000, &tpd, sizeof(TpWork), 16); + + GXS_SetVisiblePlane(GX_PLANEMASK_OBJ | GX_PLANEMASK_BG1); +} + + +// I[i[ҏW +int SEQ_OwnerInfo(void) +{ + BOOL tp_select; + BOOL tp_return = FALSE; + + ReadTP(); // ^b`pl͂̎擾 + + if(tpd.disp.touch) { // [RETURN]{^`FbN + tp_return = WithinRangeTP(RETURN_BUTTON_LT_X*8, RETURN_BUTTON_LT_Y*8-4, + RETURN_BUTTON_RB_X*8, RETURN_BUTTON_RB_Y*8-4, &tpd.disp); + } + + // I[i[̏NV[PX + if(g_initialSet) { + + pad.trg = 0; + + if(GetNCDWork()->option.input_nickname == 0) { + ow->sel = 0; + pad.trg |= PAD_BUTTON_A; + }else if(GetNCDWork()->option.input_favoriteColor == 0) { + ow->sel = 2; + pad.trg |= PAD_BUTTON_A; + }else if(GetNCDWork()->option.input_birthday == 0) { + ow->sel = 1; + pad.trg |= PAD_BUTTON_A; + }else if ( GetNCDWork()->option.input_nickname + || GetNCDWork()->option.input_favoriteColor + || GetNCDWork()->option.input_birthday ) { + pad.trg |= PAD_BUTTON_B; // j[ɖ߂炷 + } + } + + //-------------------------------------- + // L[͏ + //-------------------------------------- + if(pad.trg & PAD_KEY_DOWN){ // J[\̈ړ + if(++ow->sel == OWNER_INFO_ELEM_NUM) ow->sel= 0; + } + if(pad.trg & PAD_KEY_UP){ + if(--ow->sel & 0x80) ow->sel = OWNER_INFO_ELEM_NUM - 1; + } + tp_select=SelectMenuByTp(&ow->sel, &ownerInfoSel); + DrawMenu(ow->sel, &ownerInfoSel); + + if((pad.trg & PAD_BUTTON_A) || (tp_select)) { // j[ڂւ̕ + + mf_clearRect( RETURN_BUTTON_LT_X, RETURN_BUTTON_LT_Y, 2, 8); + DrawOKCancelButton(); + + switch(ow->sel) { + case 0: + SEQ_InputNickname_init(); + g_pNowProcess = SEQ_InputNickname; + break; + case 1: + SEQ_InputBirthday_init(); + g_pNowProcess = SEQ_InputBirthday; + break; + case 2: + SEQ_InputFavoriteColor_init(); + g_pNowProcess = SEQ_InputFavoriteColor; + break; + } + }else if((pad.trg & PAD_BUTTON_B) || (tp_return)) { // j[ɖ߂ + NNS_FndFreeToAllocator( &g_allocator, ow ); // [N̉ + ow = NULL; + OS_Printf("Free :OwnerWork\n"); + SEQ_MainMenu_init(); + } + + return 0; +} + + +//====================================================== +// N +//====================================================== + +// N͂̏ +static void SEQ_InputBirthday_init(void) +{ + // N̕\ + DrawBirthday((u16)(ownerInfoSel.pos_x + 13), (u16)(ownerInfoSel.pos_y + OWNER_INFO_CSR_NEXT_Y_NUM * 1), WHITE, &GetNCDWork()->owner.birthday); + // Ñ[h + ow->birthday.month = (int)GetNCDWork()->owner.birthday.month; + ow->birthday.day = (int)GetNCDWork()->owner.birthday.day; + SVC_CpuClear(0x0000, &tpd, sizeof(TpWork), 16); + ow->seq = 0; +} + + +// N +static int SEQ_InputBirthday(void) +{ + BOOL tp_ok = FALSE; + BOOL tp_cancel = FALSE; + int x_base, y_base, abs_y_offset, new_seq; + + enum { // t̓V[PXԍ + SEQ_INIT = 0, + SEQ_MONTH_INIT = 2, SEQ_MONTH_SET, + SEQ_DAY_INIT, SEQ_DAY_SET, + SEQ_END, + SEQ_RETURN=64 + }; + + + ReadTP(); // ^b`pl͂̎擾 + + ow->inp.y_offset = 0; + + CheckOKCancelButton(&tp_ok, &tp_cancel); + + if(tpd.disp.touch) { // [CANCEL]{^`FbN + if((ow->seq & 0x01) && (ow->seq < SEQ_END)) { // SEQ_**_SET̎̂ݗL + new_seq = ow->seq; + x_base = (ownerInfoSel.pos_x + 13) * 8; + y_base = (ownerInfoSel.pos_y + OWNER_INFO_CSR_NEXT_Y_NUM * 1) * 8 + 6; + // ͍ڈړ̃`FbN + if( WithinRangeTP( x_base, (y_base - 6), (x_base + 80), (y_base + 6), &tpd.disp) ) { + if(tpd.disp.x < x_base + 2 * 8) { + new_seq = SEQ_MONTH_SET; + }else if((tpd.disp.x >= x_base + 3 * 8) && (tpd.disp.x < x_base + 5 * 8)) { + new_seq = SEQ_DAY_SET; + }else if(tpd.disp.x >= x_base + 7 * 8) { + } + } + if(ow->seq != new_seq) { + ow->seq = new_seq - 1; + }else { + // ͒l̑ + if(WithinRangeTP( ow->inp.pos_x * 8, (y_base - 30), (ow->inp.pos_x + ow->inp.keta_max) * 8, (y_base + 30), &tpd.disp)) { + ow->inp.y_offset = tpd.disp.y - y_base; + abs_y_offset = (ow->inp.y_offset >= 0) ? ow->inp.y_offset : -ow->inp.y_offset; + if(abs_y_offset <= 6) { + ow->inp.y_offset = 0; + }else if(abs_y_offset <= 14){ + ow->inp.y_offset >>= 2; + }else if(abs_y_offset <= 22){ + ow->inp.y_offset >>= 1; + } + } + } + } + } + + // ^b`pl or L[͂ɂāAJ[\ʒuɁÄʒũJ[\B + if((ow->seq > 0) && ((ow->seq & 0x01) == 0)) { // SEQ_INIT͎̎sȂ + (void)DrawDecimalSJIS( ow->inp.pos_x, ow->inp.pos_y, WHITE, ow->tgtp, (u8)ow->inp.keta_max, 4); + } + + // eV[PXɂ鏈 + switch(ow->seq){ + case SEQ_INIT: + ow->seq = SEQ_MONTH_INIT; + // ̂܂SEQ_MONTH_INIT + + case SEQ_MONTH_INIT: + ow->inp.pos_x = DAY_LT_X; + ow->inp.pos_y = DAY_LT_Y; + ow->inp.keta_max = 2; + ow->inp.value_max = 12; + ow->inp.value_min = 1; + ow->inp.y_offset = 0; + ow->tgtp = (int *)&ow->birthday.month; + break; + + case SEQ_DAY_INIT: + ow->inp.pos_x = DAY_LT_X + 3; + ow->inp.keta_max = 2; + ow->inp.value_min = 1; + ow->inp.value_max = (int)SYSM_GetDayNum( 0, (u32)ow->birthday.month ); + // NEƂɂ̌̓ZoB + if(ow->birthday.day > ow->inp.value_max) { + ow->birthday.day = ow->inp.value_max; + } + ow->inp.y_offset = 0; + ow->tgtp = (int *)&ow->birthday.day; + break; + + case SEQ_MONTH_SET: + case SEQ_DAY_SET: + InputDecimal(ow->tgtp, &ow->inp); + + // ͂Ȃ΁AZoāA݂͓̓𒴂ĂCB + if(ow->seq == SEQ_MONTH_SET) { + u32 dayNum = SYSM_GetDayNum( 0, (u32)ow->birthday.month ); + if( dayNum < ow->birthday.day) { + ow->birthday.day = (u8)dayNum; + (void)DrawDecimalSJIS( DAY_LT_X + 3, DAY_LT_Y, WHITE, &ow->birthday.day, 2, 4); + } + } + break; + + case SEQ_END: + GetNCDWork()->owner.birthday.month = (u8 )ow->birthday.month; + GetNCDWork()->owner.birthday.day = (u8 )ow->birthday.day; + GetNCDWork()->option.input_birthday = 1; + GetSYSMWork()->ncd_invalid = 0; + + if ( GetNCDWork()->option.destroyFlashFlag ) { + GetNCDWork()->option.destroyFlashFlag = 0; + } + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData (GetNCDWork()); + + // SEQ_END̎͂̂܂܃^[B + + case SEQ_RETURN: + SEQ_OwnerInfo_init(); + g_pNowProcess = SEQ_OwnerInfo; + return 0; + } + + if(ow->seq & 0x01) { // SEQ_**_SET̎̂ݗL + if((pad.trg & PAD_BUTTON_A) || (tp_ok)) { + ow->seq = SEQ_END; // A{^Ō + }else if((pad.trg & PAD_BUTTON_B) || (tp_cancel)) { // B{^ŃLZ + ow->seq = SEQ_RETURN; + }else if(pad.trg & PAD_KEY_LEFT) { + if(ow->seq == SEQ_MONTH_SET) ow->seq = SEQ_DAY_INIT; + else ow->seq -= 3; + }else if(pad.trg & PAD_KEY_RIGHT) { + if(ow->seq == SEQ_DAY_SET) ow->seq = SEQ_MONTH_INIT; + else ow->seq++; + } + }else { // SEQ_**_INIT̎̂ݗL + ow->seq++; + } + return 0; +} + + +// N̕` +static void DrawBirthday(u16 x, u16 y, u16 color, NvDate *birthp) +{ + (void)DrawStringSJIS ( (u16)(x + 2), y, color, (const u8 *)"/"); + (void)DrawDecimalSJIS( x, y, color, &birthp->month, 2, 1); + (void)DrawDecimalSJIS( (u16)(x + 3), y, color, &birthp->day, 2, 1); +} + + +//====================================================== +// DȐF +//====================================================== + +// DȐF͂̏ +static void SEQ_InputFavoriteColor_init(void) +{ + // DȐF̃[h + ow->favoriteColor = (int)GetNCDWork()->owner.favoriteColor; + // DȐF̕\ + SVC_CpuClear(0x0000, &tpd, sizeof(TpWork), 16); + ow->seq = 0; + + if( g_initialSet ) { + (void)DrawStringSJIS( 8, 18, RED, (const u8 *)"Select user color."); + } +} + + +// DȐF +static int SEQ_InputFavoriteColor(void) +{ + BOOL tp_ok = FALSE; + BOOL tp_cancel = FALSE; + int x_base, y_base, abs_y_offset, new_seq; + + enum { // t̓V[PXԍ + SEQ_INIT = 0, SEQ_SET, + SEQ_END, + SEQ_RETURN=64 + }; + + + ReadTP(); // ^b`pl͂̎擾 + + ow->inp.y_offset = 0; + + CheckOKCancelButton(&tp_ok, &tp_cancel); + + if(tpd.disp.touch) { // [CANCEL]{^`FbN + if((ow->seq & 0x01) && (ow->seq < SEQ_END)) { // SEQ_**_SET̎̂ݗL + new_seq = ow->seq; + x_base = FCOLOR_LT_X * 8; + y_base = FCOLOR_LT_Y * 8 + 6; + // ͒l̑ + if(WithinRangeTP( ow->inp.pos_x * 8, (y_base - 30), (ow->inp.pos_x + ow->inp.keta_max) * 8, (y_base + 30), &tpd.disp)) { + ow->inp.y_offset = tpd.disp.y - y_base; + abs_y_offset = (ow->inp.y_offset >= 0) ? ow->inp.y_offset : -ow->inp.y_offset; + if(abs_y_offset <= 6) { + ow->inp.y_offset = 0; + }else if(abs_y_offset <= 14){ + ow->inp.y_offset >>= 2; + }else if(abs_y_offset <= 22){ + ow->inp.y_offset >>= 1; + } + } + } + } + + // eV[PXɂ鏈 + switch(ow->seq){ + case SEQ_INIT: + ow->inp.pos_x = FCOLOR_LT_X; + ow->inp.pos_y = FCOLOR_LT_Y; + ow->inp.keta_max = 2; + ow->inp.value_max = NCD_FAVORITE_COLOR_MAX_NUM - 1; + ow->inp.value_min = 0; + ow->inp.y_offset = 0; + ow->tgtp = (int *)&ow->favoriteColor; + break; + + case SEQ_SET: + InputDecimal(ow->tgtp, &ow->inp); + break; + + case SEQ_END: + GetNCDWork()->option.input_favoriteColor = 1; + GetNCDWork()->owner.favoriteColor = (u8 )ow->favoriteColor; + GetSYSMWork()->ncd_invalid = 0; + + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData (GetNCDWork()); + + // SEQ_END̎͂̂܂܃^[B + + case SEQ_RETURN: + SEQ_OwnerInfo_init(); + g_pNowProcess = SEQ_OwnerInfo; + return 0; + } + + if(ow->seq & 0x01) { // SEQ_**_SET̎̂ݗL + if((pad.trg & PAD_BUTTON_A) || (tp_ok)) { + ow->seq = SEQ_END; // A{^Ō + }else if((pad.trg & PAD_BUTTON_B) || (tp_cancel)) { // B{^ŃLZ + ow->seq = SEQ_RETURN; + } + }else { // SEQ_**_INIT̎̂ݗL + ow->seq++; + } + return 0; +} + + +//====================================================== +// jbNl[̓ +//====================================================== + +// jbNl[͂̏ +static void SEQ_InputNickname_init(void) +{ + GXS_SetVisiblePlane(GX_PLANEMASK_NONE); + + MI_CpuClearFast(bgBakS, sizeof(bgBakS)); + + ClearAllStringSJIS(); + + (void)DrawStringSJIS( 1, 0, YELLOW, (const u8 *)"INPUT NICKNAME"); +// (void)DrawStringSJIS( INPUT_NAME_LT_Y, WHITE, (const u16 *)str_uscore); + if( g_initialSet ) { + (void)DrawStringSJIS( 8, 20, RED, (const u8 *)"Input nickname."); + } + + // jbNl[UTF16SJISɕϊăRs[ + SVC_CpuClear(CHAR_USCORE, ow->nickname.str, NCD_NICKNAME_LENGTH * 2, 16); + if(GetSYSMWork()->ncd_invalid == 0) { + ExUTF16_LEtoSJIS_BE( (u8 *)ow->nickname.str, GetNCDWork()->owner.nickname.str, GetNCDWork()->owner.nickname.length); + ow->nickname.length = GetNCDWork()->owner.nickname.length; + ow->nickname.input_flag = 1; + } + ow->nickname.change_flag = 0; + (void)DrawStringSJIS( INPUT_NAME_LT_X, INPUT_NAME_LT_Y, WHITE, (const u16 *)ow->nickname.str); + + ow->char_mode = CHAR_MODE_HKANA; // uЂ炪ȁv͂Zbg + SetSoftKeyboardButton(ow->char_mode); // {^̃Zbg + ow->detach_count = 0; + ow->touch_count = 0; + ow->tpcsr.x = 0; + ow->tpcsr.y = 0; + ow->csr_now.x = 0; + ow->csr_now.y = 0; + ow->csr_now.x = 15; + ow->csr_now.y = 5; + DrawCharacterList(); // ̓Lꗗ̕` + MoveCharCursor(1); // J[\\ + + SVC_CpuClear(0x0000, &tpd, sizeof(TpWork), 16); + + GXS_SetVisiblePlane(GX_PLANEMASK_BG1); +} + + +// jbNl[̓ +static int SEQ_InputNickname(void) +{ + BOOL tp_input = FALSE; + u16 tbl_index, charCode; + const u16 *char_listp; + + ow->csr_old = ow->csr_now; // Ot[̃J[\ʒuۑ + + ReadTP(); // ^b`pl͂̎擾 + + tp_input = MoveCharCursorTp(&ow->csr_now); // TP͂ɂJ[\ړ + + // J[\ړ + char_listp = char_tbl[ow->char_mode]; + if(pad.trg & PAD_KEY_UP) { + while(1) { + if(--ow->csr_now.y & 0x8000) ow->csr_now.y = 5; + tbl_index = CalcTblIndex(&ow->csr_now); + if(char_listp[tbl_index]) { + break; + }else if(ow->csr_now.x > 15) { + ow->csr_now.x = 15; + ow->csr_now.y = 6; // ̃[v-15ɂȂB + } + } + }else if(pad.trg & PAD_KEY_DOWN) { + while(1) { + if(++ow->csr_now.y > 5) ow->csr_now.y = 0; + tbl_index = CalcTblIndex(&ow->csr_now); + if(char_listp[tbl_index]) { + break; + }else if(ow->csr_now.x > 15) { + ow->csr_now.x--; + ow->csr_now.y--; + } + } + } + + if(pad.trg & PAD_KEY_LEFT) { + while(1) { + if(--ow->csr_now.x & 0x8000) ow->csr_now.x = 18; + tbl_index = CalcTblIndex(&ow->csr_now); + if(char_listp[tbl_index]) { + break; + } + } + }else if(pad.trg & PAD_KEY_RIGHT) { + while(1) { + if(++ow->csr_now.x > 18) ow->csr_now.x = 0; + tbl_index = CalcTblIndex(&ow->csr_now); + if(char_listp[tbl_index]) { + break; + } + } + } + + if(pad.trg & PAD_BUTTON_START) { + ow->csr_now.x = 15; + ow->csr_now.y = 5; + } + + // ͕؂ւ + if(pad.trg & (PAD_BUTTON_R | PAD_BUTTON_L)) { + if(pad.trg & PAD_BUTTON_R) { + if(++ow->char_mode > CHAR_MODE_MAX) ow->char_mode = 0; + }else { + if(--ow->char_mode & 0x8000) ow->char_mode = CHAR_MODE_MAX; + } + SetSoftKeyboardButton(ow->char_mode); + while(1) { + tbl_index = CalcTblIndex(&ow->csr_now); + if(char_tbl[ow->char_mode][tbl_index]) { + break; + } + ow->csr_now.x--; + } + DrawCharacterList(); + } + + charCode = (u16)char_listp[CalcTblIndex(&ow->csr_now)]; + MoveCharCursor(0); + + if((pad.trg & PAD_BUTTON_A)||(tp_input)) { + // E[R}h + if((charCode == VAR_BUTTON1_)||(charCode == VAR_BUTTON2_)) {// ͕؂ւ + ow->char_mode = (u16)(ow->char_mode + 1 + charCode - CODE_BUTTON_TOP_); + if(ow->char_mode > CHAR_MODE_MAX) ow->char_mode -= CHAR_MODE_MAX+1; + SetSoftKeyboardButton(ow->char_mode); + DrawCharacterList(); + }else if(charCode == OK_BUTTON_) { // + ReturnMenu(1); + }else if(charCode == CANCEL_BUTTON_){ // LZ + ReturnMenu(0); + }else if(charCode == DEL_BUTTON_) { // P폜 + DeleteName1Char(); + }else { + if(ow->nickname.length < NCD_NICKNAME_LENGTH) { // ꕶ + ow->nickname.str[ow->nickname.length] = (u16)((charCode >> 8) | (charCode << 8)); + // SJISASCIIڕ̍ۂɂ𔻕ʂł悤ASJISHi,LȍŊi[B + ow->nickname.length++; + ow->nickname.change_flag = 1; + (void)DrawStringSJIS( INPUT_NAME_LT_X, INPUT_NAME_LT_Y, WHITE, ow->nickname.str); + } + } + }else if(pad.trg & PAD_BUTTON_B) { + if(!( (charCode >= CODE_BUTTON_TOP_)&&(charCode < CODE_BUTTON_BOTTOM_) )) { + DeleteName1Char(); // P폜 + }else if(charCode == OK_BUTTON_) { + ReturnMenu(0); // [OK]{^B{^Ȃ烊^[ + } + } + + return 0; +} + + +// Cj[ɖ߂ +static void ReturnMenu(int save_flag) +{ + int i; + + if((save_flag)&&(ow->nickname.change_flag)) { + GetSYSMWork()->ncd_invalid = 0; + GetNCDWork()->option.input_nickname = 1; // jbNl[̓tO𗧂ĂB + + ExSJIS_BEtoUTF16_LE( (u8 *)ow->nickname.str, GetNCDWork()->owner.nickname.str, ow->nickname.length); + // ͂ꂽl[SJISUTF16֕ϊB + GetNCDWork()->owner.nickname.length = ow->nickname.length; + for(i = ow->nickname.length; i < NCD_NICKNAME_LENGTH; i++) {// ͂ꂽOȍ~0x0000Ŗ߂B + GetNCDWork()->owner.nickname.str[i] = 0x0000; + } + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData(GetNCDWork()); + } + SEQ_OwnerInfo_init(); + g_pNowProcess = SEQ_OwnerInfo; // I[i[ҏWɖ߂ +} + +// P폜 +static void DeleteName1Char(void) +{ + if(ow->nickname.length == 0) return; + + ow->nickname.change_flag = 1; + ow->nickname.length--; + ow->nickname.str[ow->nickname.length] = CHAR_USCORE; + (void)DrawStringSJIS( INPUT_NAME_LT_X, INPUT_NAME_LT_Y, WHITE, ow->nickname.str); +} + + +// J[\ʒuΉLԍ擾 +static u16 CalcTblIndex(CsrPos *csrp) +{ + u16 tbl_index = 0; + u16 x_bak = csrp->x; + + while(x_bak >= 5) { + x_bak -= 5; + tbl_index += 30; + } + tbl_index += x_bak + (csrp->y * 5); + + return tbl_index; +} + + +// J[\ړ +static void MoveCharCursor(int force_flag) +{ + if((*(u32 *)&ow->csr_now != *(u32 *)&ow->csr_old) || (force_flag)) { + DrawTargetCsrChar(&ow->csr_old, WHITE); + DrawTargetCsrChar(&ow->csr_now, HIGHLIGHT_Y); + } +} + + +// J[\ʒũLN^` +static void DrawTargetCsrChar(CsrPos *csrp, u16 color) +{ + u16 index = CalcTblIndex(csrp); + u16 charCode = (u16)char_tbl[ ow->char_mode ][ index ]; + + if( (charCode >= CODE_BUTTON_TOP_) && (charCode < CODE_BUTTON_BOTTOM_) ) { + if(color == WHITE) { + color = HIGHLIGHT_C; + } + } + + if(ChangeColorSJIS(ow->handleTbl[ index ], color) == 0) { + OS_Printf("this handle is not found. %x\n", ow->handleTbl[ index ]); + } +} + + +// TPɂJ[\ړ +static BOOL MoveCharCursorTp(CsrPos *csrp) +{ + int x_bak; + BOOL active = FALSE; + CsrPos temp; + + if(ow->detach_count) { + if(tpd.disp.touch == 0) { + if(++ow->detach_count == TP_CSR_DETACH_COUNT) { + ow->detach_count = 0; + return TRUE; + }else { + return FALSE; + } + } + } + ow->detach_count = 0; + + if(tpd.disp.touch) { + if(WithinRangeTP(CLIST_LT_X*8, CLIST_LT_Y*8-4, CLIST_RB_X*8-1, CLIST_RB_Y*8-4, &tpd.disp)) { + // }[WB + temp.x = (u16)((tpd.disp.x - CLIST_LT_X * 8) / 8); + temp.y = (u16)((tpd.disp.y - (CLIST_LT_Y * 8)) / 16); + x_bak = temp.x; // TƂɂ󔒗̕␳ + while(x_bak >= 5) { + x_bak -= 6; + temp.x--; + } + + if(temp.y == 0) { // E[]̕␳ + if(temp.x > 18) temp.x = 18; + }else if(temp.x > 15) { + temp.x = 15; + } + if(*(u32 *)&temp == *(u32 *)&ow->tpcsr) { // TPJ[\ʒuOƓȂAJEgi߂āA + if(ow->touch_count < TP_CSR_TOUCH_COUNT) { // KlɒBLȈʒuƂB + ow->touch_count++; + }else { + csrp->x = temp.x; + csrp->y = temp.y; + } + return FALSE; + } + } + }else { // touch == 0 + if(ow->touch_count == TP_CSR_TOUCH_COUNT) { + ow->detach_count = 1; + } + } + ow->tpcsr.x = temp.x; + ow->tpcsr.y = temp.y; + ow->touch_count = 0; + return FALSE; +} + + +// ݂charmodẽLN^ꗗ` +static void DrawCharacterList(void) +{ + u16 i, j, k, x, y, index, button; + const u16 *code; + u16 str[2]; + + // LXg̍폜 + for( i = 0; i < CHAR_LIST_CHAR_NUM; i++ ) { + if( ow->handleTbl[ i ] ) { + ClearStringSJIS_handle( ow->handleTbl[ i ] ); + } + } + + // LN^Xg̕` + code = char_tbl[ow->char_mode]; + str[1] = 0x0000; + index = 0; + button = 0; + for(i = 0; i < 4; i++) { +// buffp = bgBakS + CLIST_LT_X + (CLIST_LT_Y << 5) + (6 * i); + for(j = 0; j < 6; j++) { + x = (u16)(CLIST_LT_X + (i * 6)); + y = (u16)(CLIST_LT_Y + (j * 2)); + for(k = 0; k < 5; k++) { + if(*code != EOM_) { + if( (*code >= CODE_BUTTON_TOP_) && (*code < CODE_BUTTON_BOTTOM_) ) { // {^ + ow->handleTbl[ index ] = DrawStringSJIS( x, y, HIGHLIGHT_C, str_button[ button++ ]); + }else { // LN^ + str[0] = (u16)( (*code >> 8) | ( *code << 8) ); + ow->handleTbl[ index ] = DrawStringSJISEx( x, y, WHITE, str, index ); + } + } + index++; + code++; + x++; + } + } + } + MoveCharCursor(1); +} + + +// \tgL[{[h̃{^ݒ +static void SetSoftKeyboardButton(u16 char_mode) +{ + if(char_mode == 0) { + str_button[0] = (const u16 *)str_button_kkana; // 1 + str_button[1] = (const u16 *)str_button_eisuu; // 2 + }else if(char_mode == 1) { + str_button[0] = (const u16 *)str_button_eisuu; // 2 + str_button[1] = (const u16 *)str_button_hkana; // 0 + }else { + str_button[0] = (const u16 *)str_button_hkana; // 0 + str_button[1] = (const u16 *)str_button_kkana; // 1 + } +} + + +// SJISR[hR[hHi/Lot]ȂRs[ +static void SJISCodeExchangeCopy(u16 *srcp, u16 *dstp, u16 length) +{ + while(length--) { + *dstp++ = (u16)( (*srcp >> 8) | (*srcp << 8) ); + srcp++; + } +} + + +//====================================================== +// jbNl[͗pLe[u +//====================================================== + +/* + SJIS𕶎萔ƂċLqꍇAȉ̂QʂŏʁEʃR[h̊i[ +@@@tɂȂĂ܂̂ŁAӂ邱ƁB + + u8 str[] = ""; 0x82,0xa0,0x82,0xa2...ƏʃR[hʃoCgɊi[B + u16 code = ''; 0xa0,0x82 ƏʁEʃR[ĥ܂܊i[B + +*/ + +static const u16 char_tbl[3][CHAR_LIST_CHAR_NUM] = { + { // Ђ炪 + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + + '', '', '', '', '', + '', '@', '', '@', '', + '', '', '', '', '', + '', '@', '', '@', '', + '', '', '', '', '', + '', '@', '', '@', '', + + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', 'A', 'B', 'I', '[', + + 'u', 'v', '`', 'E', '@', + VAR_BUTTON1_, EOM_, EOM_, EOM_, EOM_, + VAR_BUTTON2_, EOM_, EOM_, EOM_, EOM_, + DEL_BUTTON_, EOM_, EOM_, EOM_, EOM_, + CANCEL_BUTTON_, EOM_, EOM_, EOM_, EOM_, + OK_BUTTON_, EOM_, EOM_, EOM_, EOM_, + }, + + { // J^Ji + 'A', 'C', 'E', 'G', 'I', + 'J', 'L', 'N', 'P', 'R', + 'T', 'V', 'X', 'Z', '\', + '^', '`', 'c', 'e', 'g', + 'i', 'j', 'k', 'l', 'm', + 'n', 'q', 't', 'w', 'z', + + '}', '~', '', '', '', + '', '@', '', '@', '', + '', '', '', '', '', + '', '@', '', '@', '', + '@', 'B', 'D', 'F', 'H', + '', '@', '', '@', '', + + 'K', 'M', 'O', 'Q', 'S', + 'U', 'W', 'Y', '[', ']', + '_', 'a', 'd', 'f', 'h', + 'o', 'r', 'u', 'x', '{', + 'p', 's', 'v', 'y', '|', + 'b', 'A', 'B', 'I', '[', + + 'u', 'v', '`', 'E', '@', + VAR_BUTTON1_, EOM_, EOM_, EOM_, EOM_, + VAR_BUTTON2_, EOM_, EOM_, EOM_, EOM_, + DEL_BUTTON_, EOM_, EOM_, EOM_, EOM_, + CANCEL_BUTTON_, EOM_, EOM_, EOM_, EOM_, + OK_BUTTON_, EOM_, EOM_, EOM_, EOM_, + }, + + { // p + '`', 'a', 'b', 'c', 'd', + 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', + 't', 'u', 'v', 'w', 'x', + 'y', '@', '@', '@', '@', + + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '', '', '', '', + '', '@', '@', '@', '@', + + 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', + 'I', '@', '', '@', '^', + 'C', '@', 'D', '@', '|', + 'f', '@', 'h', '@', '@', + '', '@', 'i', '@', 'j', + + EOM_, EOM_, EOM_, EOM_, EOM_, + VAR_BUTTON1_, EOM_, EOM_, EOM_, EOM_, + VAR_BUTTON2_, EOM_, EOM_, EOM_, EOM_, + DEL_BUTTON_, EOM_, EOM_, EOM_, EOM_, + CANCEL_BUTTON_, EOM_, EOM_, EOM_, EOM_, + OK_BUTTON_, EOM_, EOM_, EOM_, EOM_, + }, +}; + diff --git a/build/systemMenu_RED/MachineSettings/ARM9/src/setRTC.c b/build/systemMenu_RED/MachineSettings/ARM9/src/setRTC.c new file mode 100644 index 0000000..3c6ffe3 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/ARM9/src/setRTC.c @@ -0,0 +1,557 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: setRTC.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "MachineSetting.h" + +// define data------------------------------------------ + +//#define __RTC_MINUTE_OFFSET // ̒`LȏꍇrtcOffset͕ItZbgŎZo܂B܂Aȏꍇ͕bItZbgƂȂ܂B + + // RETURN{^LCD̈ +#define RETURN_BUTTON_TOP_X ( 2 * 8 ) +#define RETURN_BUTTON_TOP_Y ( 21 * 8 ) +#define RETURN_BUTTON_BOTTOM_X ( RETURN_BUTTON_TOP_X + 6 * 8 ) +#define RETURN_BUTTON_BOTTOM_Y ( RETURN_BUTTON_TOP_Y + 2 * 8 ) + + // tf[^LCD̈ +#define DATE_TOP_Y ( 10 * 8 ) +#define YEAR_TOP_X ( 5 * 8 ) +#define MONTH_TOP_X ( YEAR_TOP_X + 5 * 8 ) +#define DAY_TOP_X ( MONTH_TOP_X + 3 * 8 ) + + // f[^LCD̈ +#define TIME_TOP_Y ( DATE_TOP_Y ) +#define HOUR_TOP_X ( DAY_TOP_X + 5 * 8 ) +#define MINUTE_TOP_X ( HOUR_TOP_X + 3 * 8 ) +#define SECOND_TOP_X ( MINUTE_TOP_X + 3 * 8 ) + + // ̓^b`plpJE^ +#define S_UPDOWN_COUNT_MAX 16 + // l̓^b`plpJE^ +#define D_DOWN_COUNT_MAX -50 +#define D_UP_COUNT_MAX 50 + + + // t̓V[PXp[N +typedef struct DateTimeParam { + int seq; // V[PXԍ + int *pTgt; // ͑Ώۂ̕ϐւ̃|C^ + RTCDate Date; + RTCTime Time; + RTCDate Date_old; + RTCTime Time_old; +}DateTimeParam; + + + // RTCݒV[PXp[N +typedef struct SetRtcWork { + int csr; // J[\ʒu + s64 rtcOffset[ 2 ]; // RTCItZbgli[0]:ݒύXO̒lA[1]:ύX̒lj + DateTimeParam dtp; // t̓V[PXp[N + InputNumParam inp; // l̓C^[tF[Xp[N +}SetRtcWork; + + +typedef struct DateTimeWidth { + int year; + int month; + int day; + int hour; + int minute; + int second; +}DateTimeWidth; + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- +RTCWeek CalcWeekFromDate( u32 year, u32 month, u32 day ); +void InputDecimal(int *pTgt, InputNumParam *inpp); + +static void InputRtcDateTimeInit( int start ); +static int InputRtcDateTimeMain( void ); + +static void TransmitRtcData(DateTimeParam *dtpp, RtcDateTime *rtcp); +static void SelectString( int *pTgt, const u8 **const pStrp, InputNumParam *inpp); +static void BcdToHex(int *bcdp); +static void HexToBcd(int *hexp); +static BOOL CheckLeapYear( u32 year ); +static void DrawDateTime( RTCDate *pDate, RTCTime *pTime, int color ); + +// global variable ------------------------------------- + +// static variable ------------------------------------- +static SetRtcWork *s_pWork; // RTCݒp[N +// const data ----------------------------------------- + +//====================================================== +// tݒ +//====================================================== + +// RTCݒV[PX̏ +void SetRTCInit( void ) +{ + GX_DispOff(); + GXS_DispOff(); + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + + PutStringUTF16( 0, 0, TXT_COLOR_BLUE, (const u16 *)L"DATE & TIME SET" ); + PutStringUTF16( RETURN_BUTTON_TOP_X, RETURN_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L" RETURN " ); + + if( g_initialSet ) { + if( GetSYSMWork()->rtcStatus & 0x01) { + PutStringUTF16( 8 * 8, 18 * 8, TXT_COLOR_RED, (const u16 *)L"RTC reset is detected!" ); + }else { + PutStringUTF16( 8 * 8, 18 * 8, TXT_COLOR_RED, (const u16 *)L"Set RTC." ); + } + } + + s_pWork = NNS_FndAllocFromAllocator( &g_allocator, sizeof(SetRtcWork) ); // RTCݒp[N̊m + if( s_pWork == NULL ) { + OS_Panic( "ARM9- Fail to allocate memory...\n" ); + } + + SVC_CpuClear( 0x0000, s_pWork, sizeof(SetRtcWork), 16 ); + SVC_CpuClear( 0x0000, &tpd, sizeof(TpWork), 16 ); + + RTC_GetDateTime( &s_pWork->dtp.Date, &s_pWork->dtp.Time ); + s_pWork->dtp.Date.year += 2000; + + PrintfSJIS ( YEAR_TOP_X, DATE_TOP_Y, TXT_COLOR_BLACK, "%04d", s_pWork->dtp.Date.year ); + PrintfSJIS ( MONTH_TOP_X, DATE_TOP_Y, TXT_COLOR_BLACK, "%02d", s_pWork->dtp.Date.month ); + PrintfSJIS ( DAY_TOP_X, DATE_TOP_Y, TXT_COLOR_BLACK, "%02d", s_pWork->dtp.Date.day ); + PrintfSJIS ( HOUR_TOP_X, TIME_TOP_Y, TXT_COLOR_BLACK, "%02d", s_pWork->dtp.Time.hour ); + PrintfSJIS ( MINUTE_TOP_X, TIME_TOP_Y, TXT_COLOR_BLACK, "%02d", s_pWork->dtp.Time.minute ); + + DrawDateTime( &s_pWork->dtp.Date, &s_pWork->dtp.Time, TXT_COLOR_BLACK ); + + GX_SetVisiblePlane ( GX_PLANEMASK_BG0 ); + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); + GX_DispOn(); + GXS_DispOn(); +} + + +// w肵tE̕\ +static void DrawDateTime( RTCDate *pDate, RTCTime *pTime, int color ) +{ + PrintfSJIS( YEAR_TOP_X, DATE_TOP_Y, color, "%04d", pDate->year ); + PrintfSJIS( MONTH_TOP_X, DATE_TOP_Y, color, "%02d", pDate->month ); + PrintfSJIS( DAY_TOP_X, DATE_TOP_Y, color, "%02d", pDate->day ); + PrintfSJIS( HOUR_TOP_X, TIME_TOP_Y, color, "%02d", pTime->hour ); + PrintfSJIS( MINUTE_TOP_X, TIME_TOP_Y, color, "%02d", pTime->minute ); + PutStringUTF16( YEAR_TOP_X + 4 * 8, DATE_TOP_Y, color, L"/" ); + PutStringUTF16( MONTH_TOP_X + 2 * 8, DATE_TOP_Y, color, L"/" ); + PutStringUTF16( HOUR_TOP_X + 2 * 8, TIME_TOP_Y, color, L":" ); +} + + +// RTCݒV[PX +int SetRTCMain( void ) +{ + BOOL tp_set = FALSE; + BOOL tp_return = FALSE; + + ReadTP(); // TP͂̎擾 + + if(tpd.disp.touch) { + tp_set = WithinRangeTP( YEAR_TOP_X, DATE_TOP_Y, // [RTCݒ]̈扟`FbN + SECOND_TOP_X, DATE_TOP_Y + 16, &tpd.disp ); + // [RETURN]{^`FbN + tp_return = WithinRangeTP( RETURN_BUTTON_TOP_X, RETURN_BUTTON_TOP_Y, + RETURN_BUTTON_BOTTOM_X, RETURN_BUTTON_BOTTOM_Y, &tpd.disp ); + } + if( g_initialSet && !GetNCDWork()->option.input_rtc ) { + tp_set = TRUE; + } + //-------------------------------------- + // L[͏ + //-------------------------------------- + if( ( pad.trg & PAD_BUTTON_A ) || tp_set ) { // RTCݒJn + InputRtcDateTimeInit( 1 ); + g_pNowProcess = InputRtcDateTimeMain; + }else if( ( pad.trg & PAD_BUTTON_B ) || tp_return ) { // j[ɖ߂ + NNS_FndFreeToAllocator( &g_allocator, s_pWork ); // RTCݒp[N̉ + s_pWork = NULL; + MachineSettingInit(); + } +#ifdef __SYSM_DEBUG + else if( pad.trg & PAD_BUTTON_START ) { + ClearRTC(); + OS_Printf( "RTC offset in NVRAM is ZERO clear!\n" ); + } +#endif /* __SYSM_DEBUG */ + + return 0; +} + + +//====================================================== +// t͏ +//====================================================== + +// t͏ +static void InputRtcDateTimeInit( int start ) +{ + NNS_G2dCharCanvasClearArea( &gCanvas, TXT_COLOR_WHITE, + RETURN_BUTTON_TOP_X, RETURN_BUTTON_TOP_Y, 256 - RETURN_BUTTON_TOP_X, 2 * 8 ); + if( start ) { + DrawOKCancelButton(); + s_pWork->dtp.seq = 0; + }else { + PutStringUTF16( RETURN_BUTTON_TOP_X, RETURN_BUTTON_TOP_Y, TXT_COLOR_CYAN, (const u16 *)L"RETURN" ); + } + SVC_CpuClear( 0x0000, &tpd, sizeof(TpWork), 16 ); +} + + +// t +static int InputRtcDateTimeMain( void ) +{ + BOOL tp_ok = FALSE; + BOOL tp_cancel = FALSE; + int new_seq, y_base, abs_y_offset; + + enum { // t̓V[PXԍ + SEQ_INIT=0, + SEQ_YEAR_INIT=2, SEQ_YEAR_SET, + SEQ_MONTH_INIT, SEQ_MONTH_SET, + SEQ_DAY_INIT, SEQ_DAY_SET, + SEQ_HOUR_INIT, SEQ_HOUR_SET, + SEQ_MINUTE_INIT, SEQ_MINUTE_SET, + SEQ_END, + SEQ_CANCEL=64 + }; + + ReadTP(); // ^b`pl͂̎擾 + CheckOKCancelButton( &tp_ok, &tp_cancel ); // [OK],[CANCEL]{^`FbN + + s_pWork->inp.y_offset = 0; + + if( tpd.disp.touch ) { // [CANCEL]{^`FbN + if( ( s_pWork->dtp.seq & 0x01 ) && ( s_pWork->dtp.seq < SEQ_END ) ) { // SEQ_**_SET̎̂ݗL + new_seq = s_pWork->dtp.seq; + y_base = DATE_TOP_Y + 6; + + // ͍ڈړ̃`FbN + if( WithinRangeTP( YEAR_TOP_X, DATE_TOP_Y, SECOND_TOP_X, DATE_TOP_Y + 12, &tpd.disp ) ) { + if( tpd.disp.x < YEAR_TOP_X + 32 ) { + new_seq = SEQ_YEAR_SET; + }else if( ( tpd.disp.x >= MONTH_TOP_X ) && ( tpd.disp.x < MONTH_TOP_X + 16 ) ) { + new_seq = SEQ_MONTH_SET; + }else if( ( tpd.disp.x >= DAY_TOP_X ) && ( tpd.disp.x < DAY_TOP_X + 16 ) ) { + new_seq = SEQ_DAY_SET; + }else if( ( tpd.disp.x >= HOUR_TOP_X ) && ( tpd.disp.x < HOUR_TOP_X + 16 ) ) { + new_seq = SEQ_HOUR_SET; + }else if( ( tpd.disp.x >= MINUTE_TOP_X ) && ( tpd.disp.x < MINUTE_TOP_X + 16 ) ) { + new_seq = SEQ_MINUTE_SET; + } + } + if( s_pWork->dtp.seq != new_seq ) { + s_pWork->dtp.seq = new_seq - 1; + }else if( WithinRangeTP( s_pWork->inp.pos_x, y_base - 40, + s_pWork->inp.pos_x + s_pWork->inp.keta_max * 8, y_base + 60, &tpd.disp ) ) { + // ͒l̑ + s_pWork->inp.y_offset = tpd.disp.y - y_base; + abs_y_offset = ( s_pWork->inp.y_offset >= 0 ) ? s_pWork->inp.y_offset : -s_pWork->inp.y_offset; + if( abs_y_offset <= 6 ) { + s_pWork->inp.y_offset = 0; + }else if( abs_y_offset <= 20 ){ + s_pWork->inp.y_offset >>= 2; + }else if( abs_y_offset <= 40 ){ + s_pWork->inp.y_offset >>= 1; + } + } + } + } + + // ^b`pl or L[͂ɂāAJ[\ʒuɁÄʒũJ[\B + if( ( s_pWork->dtp.seq > 0 ) && ( ( s_pWork->dtp.seq & 0x01 ) == 0 ) ) { // SEQ_INIT͎̎sȂ + PrintfSJIS( s_pWork->inp.pos_x, s_pWork->inp.pos_y, TXT_COLOR_BLACK, "%02d", *s_pWork->dtp.pTgt ); + } + + // eV[PX̏ + switch(s_pWork->dtp.seq){ + + case SEQ_INIT: + MI_CpuCopy32( &s_pWork->dtp.Date, &s_pWork->dtp.Date_old, sizeof(RTCDate) ); + MI_CpuCopy32( &s_pWork->dtp.Time, &s_pWork->dtp.Time_old, sizeof(RTCTime) ); + + s_pWork->dtp.seq = SEQ_YEAR_INIT; + // SEQ_INIT͒ʂSEQ_YEAR_INIT + + case SEQ_YEAR_INIT: + s_pWork->inp.pos_x = YEAR_TOP_X; + s_pWork->inp.pos_y = DATE_TOP_Y; + s_pWork->inp.keta_max = 4; + s_pWork->inp.value_max = 2099; + s_pWork->inp.value_min = 2000; +// s_pWork->inp.value_min = 2004; +// if(s_pWork->dtp.Date.year < 2004) { +// s_pWork->dtp.Date.year = 2004; +// } + s_pWork->dtp.pTgt = (int *)&s_pWork->dtp.Date.year; + break; + + case SEQ_MONTH_INIT: + s_pWork->inp.pos_x = MONTH_TOP_X; + s_pWork->inp.keta_max = 2; + s_pWork->inp.value_max = 12; + s_pWork->inp.value_min = 1; + s_pWork->dtp.pTgt = (int *)&s_pWork->dtp.Date.month; + break; + + case SEQ_DAY_INIT: + s_pWork->inp.pos_x = DAY_TOP_X; + s_pWork->inp.keta_max = 2; + s_pWork->inp.value_max = (int)SYSM_GetDayNum( s_pWork->dtp.Date.year, s_pWork->dtp.Date.month ); + // NEƂɂ̌̓ZoB + s_pWork->inp.value_min = 1; + if(s_pWork->dtp.Date.day > s_pWork->inp.value_max) { + s_pWork->dtp.Date.day = (u32)s_pWork->inp.value_max; + } + s_pWork->dtp.pTgt = (int *)&s_pWork->dtp.Date.day; + break; + + case SEQ_HOUR_INIT: + s_pWork->inp.pos_x = HOUR_TOP_X; + s_pWork->inp.keta_max = 2; + s_pWork->inp.value_max = 23; + s_pWork->inp.value_min = 0; + s_pWork->dtp.pTgt = (int *)&s_pWork->dtp.Time.hour; + break; + + case SEQ_MINUTE_INIT: + s_pWork->inp.pos_x = MINUTE_TOP_X; + s_pWork->inp.keta_max = 2; + s_pWork->inp.value_max = 59; + s_pWork->inp.value_min = 0; + s_pWork->dtp.pTgt = (int *)&s_pWork->dtp.Time.minute; + break; + + case SEQ_YEAR_SET: + case SEQ_MONTH_SET: + case SEQ_DAY_SET: + case SEQ_HOUR_SET: + case SEQ_MINUTE_SET: + InputDecimal( s_pWork->dtp.pTgt, &s_pWork->inp ); + + // N͂Ȃ΁AjČvZ + if( ( s_pWork->dtp.seq == SEQ_YEAR_SET ) || + ( s_pWork->dtp.seq == SEQ_MONTH_SET ) || + ( s_pWork->dtp.seq == SEQ_DAY_SET ) ) { + s_pWork->dtp.Date.week = CalcWeekFromDate( s_pWork->dtp.Date.year, s_pWork->dtp.Date.month, s_pWork->dtp.Date.day ); + } + + // NE͂Ȃ΁AZoāA݂͓̓𒴂ĂCB + if( ( s_pWork->dtp.seq == SEQ_YEAR_SET ) || + ( s_pWork->dtp.seq == SEQ_MONTH_SET ) ) { + u32 dayNum = SYSM_GetDayNum( s_pWork->dtp.Date.year, s_pWork->dtp.Date.month ); + if( dayNum < s_pWork->dtp.Date.day ) { + PrintfSJIS( DAY_TOP_X, DATE_TOP_Y, TXT_COLOR_WHITE, "%02d", s_pWork->dtp.Date.day ); + PrintfSJIS( DAY_TOP_X, DATE_TOP_Y, TXT_COLOR_BLACK, "%02d", dayNum ); + s_pWork->dtp.Date.day = dayNum; + } + } + break; + + case SEQ_END: + s_pWork->dtp.Time.second = 0; + { + RTCDate date; // +-2000̂ʓ|Ȃ̂ŁAʃobt@ɃRs[ď + MI_CpuCopy32( &s_pWork->dtp.Date, &date, sizeof(RTCDate) ); + date.year -= 2000; + (void)RTC_SetDateTime( &date, &s_pWork->dtp.Time ); + NCD_SetRtcOffset( SYSM_CalcRtcOffsetAndSetDateTime( &date, &s_pWork->dtp.Time ) ); + } + + GetSYSMWork()->ncd_invalid = 0; + GetNCDWork()->option.input_rtc = 1; // RTC̓tO𗧂ĂB + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData( GetNCDWork() ); + + // ʂ̕\XV + GetAndDrawRTCData( &g_rtcDraw, TRUE ); + + g_pNowProcess = SetRTCMain; + InputRtcDateTimeInit( 0 ); // t͉ʂ̃NA + return 0; + + case SEQ_CANCEL: + // tE\̒lɖ߂ĕ\XV + DrawDateTime( &s_pWork->dtp.Date, &s_pWork->dtp.Time, TXT_COLOR_WHITE ); + DrawDateTime( &s_pWork->dtp.Date_old, &s_pWork->dtp.Time_old, TXT_COLOR_BLACK ); + MI_CpuCopy32( &s_pWork->dtp.Date_old, &s_pWork->dtp.Date, sizeof(RTCDate) ); + MI_CpuCopy32( &s_pWork->dtp.Time_old, &s_pWork->dtp.Time, sizeof(RTCTime) ); + g_pNowProcess = SetRTCMain; + InputRtcDateTimeInit( 0 ); // t͉ʂ̃NA + return 0; + } + + if( s_pWork->dtp.seq & 0x01 ) { // SEQ_**_SET̎̂ݗL + if( ( pad.trg & PAD_BUTTON_A ) || tp_ok ) { + s_pWork->dtp.seq = SEQ_END; // A{^Ō + }else if( ( pad.trg & PAD_BUTTON_B ) || tp_cancel ) { // B{^ŃLZ + s_pWork->dtp.seq = SEQ_CANCEL; + }else if( pad.trg & PAD_KEY_LEFT ) { + if( s_pWork->dtp.seq == SEQ_YEAR_SET ) { + s_pWork->dtp.seq = SEQ_MINUTE_INIT; + }else { + s_pWork->dtp.seq -= 3; + } + }else if( pad.trg & PAD_KEY_RIGHT ) { + if( s_pWork->dtp.seq == SEQ_MINUTE_SET ) { + s_pWork->dtp.seq = SEQ_YEAR_INIT; + }else { + s_pWork->dtp.seq++; + } + } + }else { // SEQ_**_INIT̎̂ݗL + s_pWork->dtp.seq++; + } + return 0; +} + + +/* +// 邤N̔ (邤NFPAʏ̔NFO^[j +BOOL CheckLeapYear( u32 year) +{ + if((year & 0x03) == 0) { // 邤ŃAu4Ŋ؂@@100Ŋ؂ȂNv + CP_SetDiv32_32(year, 100); // u400Ŋ؂Nv + if(CP_GetDivRemainder32() != 0) { + return TRUE; + }else { + CP_SetDiv32_32(year, 400); + if(CP_GetDivRemainder32() == 0) { + return TRUE; + } + } + } + return FALSE; +} +*/ + +// tj߂B +RTCWeek CalcWeekFromDate( u32 year, u32 month, u32 day ) +{ + if( month == 1 || month == 2 ){ + year--; + month += 12; + } + return (RTCWeek)( ( year + year/4 - year/100 + year/400 + (13*month + 8)/5 + day) % 7 ); +} + + +/* +// ɂp[^I +static void SelectString(int *pTgt, const u8 **const ppStr, InputNumParam *pInp ) +{ + BOOL value_up = FALSE; + BOOL value_down = FALSE; + const u8 *pStr_old = *pTgt; + + if( pInp->y_offset == 0 ) { + pInp->up_count = S_UPDOWN_COUNT_MAX; + }else { + pInp->up_count ++; + if( pInp->up_count > S_UPDOWN_COUNT_MAX ) { + pInp->up_count = 0; + if( pInp->y_offset < 0 ) value_up = TRUE; + else value_down = TRUE; + } + } + + if( ( pad.trg & PAD_KEY_DOWN ) || value_down ) { // \؂ւ + if( ++ *pTgt > pInp->value_max ) { + *pTgt = 0; + } + }else if( ( pad.trg & PAD_KEY_UP ) || value_up ) { + if( -- *pTgt & 0x8000 ) { + *pTgt = pInp->value_max; + } + } + + PutStringUTF16( pInp->pos_x, pInp->pos_y, TXT_COLOR_WHITE, pStr_old ); // + PutStringUTF16( pInp->pos_x, pInp->pos_y, TXT_COLOR_BLACK, ppStr[ *pTgt ] ); // ݑIĂ镶\ +} +*/ + +// POil +void InputDecimal( int *pTgt, InputNumParam *pInp ) +{ + BOOL value_up = FALSE; + BOOL value_down = FALSE; + int old = *pTgt; + + if( pInp->y_offset == 0 ) { + pInp->up_count = D_UP_COUNT_MAX; + pInp->down_count = D_DOWN_COUNT_MAX; + }else if( pInp->y_offset < 0 ) { + pInp->down_count += pInp->y_offset; + if( pInp->down_count < D_DOWN_COUNT_MAX ) { + pInp->down_count = 0; + value_down = TRUE; + } + }else { // y_offset > 0 + pInp->up_count += pInp->y_offset; + if( pInp->up_count > D_UP_COUNT_MAX ) { + pInp->up_count = 0; + value_up = TRUE; + } + } + + // L[͂ɉđΏےl𑝌 + if( value_down || + ( pad.trg & PAD_KEY_UP ) || + ( ( pad.cont & PAD_KEY_UP ) && ( pad.cont & PAD_BUTTON_R ) ) ) { + if( --*pTgt < pInp->value_min ) { + *pTgt = pInp->value_max; + } + }else if( value_up || + ( pad.trg & PAD_KEY_DOWN ) || + ( ( pad.cont & PAD_KEY_DOWN ) && ( pad.cont & PAD_BUTTON_R ) ) ) { + if( ++*pTgt > pInp->value_max ) { + *pTgt = pInp->value_min; + } + } + + PrintfSJIS( pInp->pos_x, pInp->pos_y, TXT_COLOR_WHITE, "%02d", old ); + PrintfSJIS( pInp->pos_x, pInp->pos_y, TXT_COLOR_GREEN, "%02d", *pTgt ); + // ΏےlnCCg\ +} + + +// RTCݒ̃NA +void ClearRTC( void ) +{ + SVC_CpuClear( 0x0000, &GetSYSMWork()->rtc[0].Time, sizeof(RTCTime), 16 ); + GetSYSMWork()->rtc[0].Date.year = 0; + GetSYSMWork()->rtc[0].Date.month = 1; + GetSYSMWork()->rtc[0].Date.day = 1; + (void)RTC_SetDateTime( &GetSYSMWork()->rtc[0].Date, &GetSYSMWork()->rtc[0].Time ); + GetNCDWork()->option.input_rtc = 0; + GetNCDWork()->option.rtcOffset = 0; + NCD_SetRtcLastSetYear( 0 ); + // :::::::::::::::::::::::::::::::::::::::::::::: + // NVRAMւ̏ + // :::::::::::::::::::::::::::::::::::::::::::::: + (void)NVRAMm_WriteNitroConfigData( GetNCDWork() ); +} diff --git a/build/systemMenu_RED/MachineSettings/Makefile b/build/systemMenu_RED/MachineSettings/Makefile new file mode 100644 index 0000000..9cf34e1 --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/Makefile @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +SUBDIRS = banner ARM9 + +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/MachineSettings/banner/Makefile b/build/systemMenu_RED/MachineSettings/banner/Makefile new file mode 100644 index 0000000..efdcadf --- /dev/null +++ b/build/systemMenu_RED/MachineSettings/banner/Makefile @@ -0,0 +1,52 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +ICON_DIR = ./icon +TOOLS_DIR = $(TWLIPL_ROOT)/tools/bin +NTEXCONV = $(TOOLS_DIR)/ntexconv.exe +MAKEBANNER = $(TOOLS_DIR)/makebanner.exe + +BANNER_ICON = $(ICON_DIR)/gameIcon.bmp +BANNER_SPEC = banner_v3.bsf + +TARGETS = banner.bnr +INSTALL_DIR = ./ +INSTALL_TARGETS = $(TARGETS) + +BANNER_ICON_NAME = $(basename $(BANNER_ICON)) + +LDIRT_CLEAN = $(TARGETS) \ + $(BANNER_ICON_NAME).nbfs \ + $(BANNER_ICON_NAME).nbfc \ + $(BANNER_ICON_NAME).nbfp \ + $(TARGETS:.bnr=.srl) + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- +# build +#---------------------------------------------------------------------------- +do-build: $(TARGETS) + +$(TARGETS): $(BANNER_SPEC) $(BANNER_ICON) + $(NTEXCONV) -no -bg -bgb -bgnc $(BANNER_ICON) >/dev/null && \ + $(MAKEBANNER) -d -N $(BANNER_ICON_NAME) $(BANNER_SPEC) $(TARGETS) + +# diff --git a/build/systemMenu_RED/MachineSettings/banner/banner_v3.bsf b/build/systemMenu_RED/MachineSettings/banner/banner_v3.bsf new file mode 100644 index 0000000..c5a4f1d Binary files /dev/null and b/build/systemMenu_RED/MachineSettings/banner/banner_v3.bsf differ diff --git a/build/systemMenu_RED/MachineSettings/banner/icon/gameIcon.bmp b/build/systemMenu_RED/MachineSettings/banner/icon/gameIcon.bmp new file mode 100644 index 0000000..1a7a401 Binary files /dev/null and b/build/systemMenu_RED/MachineSettings/banner/icon/gameIcon.bmp differ diff --git a/build/systemMenu_RED/Makefile b/build/systemMenu_RED/Makefile new file mode 100644 index 0000000..bcccad8 --- /dev/null +++ b/build/systemMenu_RED/Makefile @@ -0,0 +1,31 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +SUBDIRS = launcher MachineSettings PictoChat \ + #DS_DownloadPlay + +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/PictoChat/ARM9/Makefile b/build/systemMenu_RED/PictoChat/ARM9/Makefile new file mode 100644 index 0000000..af75337 --- /dev/null +++ b/build/systemMenu_RED/PictoChat/ARM9/Makefile @@ -0,0 +1,53 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlSDK - demos - simpleShoot-1 +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev: $ +# $Author: $ +#---------------------------------------------------------------------------- + +SUBDIRS = + +#---------------------------------------------------------------------------- + +TARGET_FIRM = SYSTEMMENU +TARGET_PLATFORM = TWL +TWL_ARCHGEN = LIMITED + +TARGET_BIN = main.srl + +#LCFILE_SPEC = +ROM_SPEC = main.rsf + +MISC_DIR = ../../MachineSettings/ARM9/src + +SRCS = main.c PictoChat.c $(MISC_DIR)/misc.c +#SRCS_OVERLAY = + +LINCLUDES = $(MISC_DIR) +#LLIBRARY_DIRS = +#LLIBRARIES = +#LDEPENDS_NEF = + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +do-build : $(FONT_OBJS) $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/PictoChat/ARM9/main.rsf b/build/systemMenu_RED/PictoChat/ARM9/main.rsf new file mode 100644 index 0000000..f7b7ea4 --- /dev/null +++ b/build/systemMenu_RED/PictoChat/ARM9/main.rsf @@ -0,0 +1,146 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ROM-BB.rsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL ROM SPEC FILE +# + +Arm9 +{ + Static "$(MAKEROM_ARM9:r).FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.FLX.TWL.sbin$(COMPSUFFIX9)" + Elf "$(MAKEROM_ARM9:r).tef" +} + +Arm7 +{ + Static "$(MAKEROM_ARM7_BASE:r).FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.FLX.TWL.sbin$(COMPSUFFIX7)" + Elf "$(MAKEROM_ARM7_BASE:r).tef" +} + +Arm9.Ltd +{ + Static "$(MAKEROM_ARM9:r).LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.LTD.TWL.sbin$(COMPSUFFIX9)" +} + +Arm7.Ltd +{ + Static "$(MAKEROM_ARM7_BASE:r).LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.LTD.TWL.sbin$(COMPSUFFIX7)" +} + +Property +{ + ### + ### Settings for FinalROM + ### + #### BEGIN + # + # TITLE NAME: Your product name within 12bytes + # + #TitleName "YourAppName" + + # + # MAKER CODE: Your company ID# in 2 ascii words + # issued by NINTENDO + # + #MakerCode "00" + + # + # REMASTER VERSION: Mastering version + # + #RomVersion 0 + + # + # ROM SPEED TYPE: [MROM/1TROM/UNDEFINED] + # + RomSpeedType $(MAKEROM_ROMSPEED) + + # + # ROM SIZE: in bit [64M/128M/256M/512M/1G/2G] + # + #RomSize 128M + #RomSize 256M + + # + # ROM PADDING: TRUE if finalrom + # + #RomFootPadding TRUE + + # + # ROM HEADER TEMPLATE: Provided to every product by NINTENDO + # + #RomHeaderTemplate ./etc/rom_header.template.sbin + + # + # BANNER FILE: generated from Banner Spec File + # + BannerFile ../banner/banner.bnr + + ### + ### Setting for TWL + ### + # + # BANNER FILE: + # + BannerTWLFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + # + # Boot allowed Media: [GameCard/NAND/SDCard/DownloadPlay] + # possible to choose one or more. + # + BootMedia GameCard NAND SDCard DownloadPlay + + # + # Certification FILE: + # + Certificate $(TWLSDK_ROOT)/include/twl/specfiles/default_sgn.sbin + + # + # Digest parameters: + # + DigestParam 1024 32 + + # + # WRAM mapping: [MAP_BB_HYB/MAP_BB_LTD/MAP_TS_HYB/MAP_TS_LTD] + # don't have to edit + # + WramMapping $(MAKEROM_WRAM_MAPPING) + + # + # Codec mode: + # don't have to edit + # + CodecMode $(MAKEROM_CODEC_MODE) + + ### + #### END +} + +RomSpec +{ + Offset 0x00000000 + Segment ALL + HostRoot ../../data + Root /data + File NTR_IPL_font_m.NFTR +} diff --git a/build/systemMenu_RED/PictoChat/ARM9/src/PictoChat.c b/build/systemMenu_RED/PictoChat/ARM9/src/PictoChat.c new file mode 100644 index 0000000..e2c466e --- /dev/null +++ b/build/systemMenu_RED/PictoChat/ARM9/src/PictoChat.c @@ -0,0 +1,83 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: DS_Chat.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include +#include "misc.h" +#include "PictoChat.h" + +// define data------------------------------------------ +#define RETURN_BUTTON_TOP_X 2 +#define RETURN_BUTTON_TOP_Y 21 +#define RETURN_BUTTON_BOTTOM_X ( RETURN_BUTTON_TOP_X + 8 ) +#define RETURN_BUTTON_BOTTOM_Y ( RETURN_BUTTON_TOP_Y + 2 ) + +// extern data------------------------------------------ + +// function's prototype declaration--------------------- + +// global variable ------------------------------------- +RTCDrawProperty g_rtcDraw = { + TRUE, RTC_DATE_TOP_X, RTC_DATE_TOP_Y, RTC_TIME_TOP_X, RTC_TIME_TOP_Y +}; + +// static variable ------------------------------------- + +// const data ----------------------------------------- + +//====================================================== +// sNg`bg +//====================================================== + +// sNg`bg̏ +void PictoChatInit( void ) +{ + GX_DispOff(); + GXS_DispOff(); + NNS_G2dCharCanvasClear( &gCanvas, TXT_COLOR_WHITE ); + + PutStringUTF16( 1 * 8, 0 * 8, TXT_COLOR_BLUE, (const u16 *)L"PictoChat"); + PutStringUTF16( 4 * 8, 8 * 8, TXT_COLOR_BLACK, (const u16 *)L"Under Construction..."); + GetAndDrawRTCData( &g_rtcDraw, TRUE ); + + GXS_SetVisiblePlane( GX_PLANEMASK_BG0 ); + GX_DispOn(); + GXS_DispOn(); +} + + +// sNg`bg̃C[v +void PictoChatMain(void) +{ + BOOL tp_cancel = FALSE; + + ReadTP(); // ^b`pl͂̎擾 + + // [RETURN]{^`FbN + if(tpd.disp.touch) { + tp_cancel = WithinRangeTP( RETURN_BUTTON_TOP_X * 8, RETURN_BUTTON_TOP_Y * 8 - 4, + RETURN_BUTTON_BOTTOM_X * 8, RETURN_BUTTON_BOTTOM_Y * 8 - 4, &tpd.disp ); + } + + if( ( pad.trg & PAD_BUTTON_B ) || tp_cancel ) { +// SYSM_RebootLauncher(); + } + + GetAndDrawRTCData( &g_rtcDraw, FALSE ); +} + + diff --git a/build/systemMenu_RED/PictoChat/ARM9/src/PictoChat.h b/build/systemMenu_RED/PictoChat/ARM9/src/PictoChat.h new file mode 100644 index 0000000..eaea919 --- /dev/null +++ b/build/systemMenu_RED/PictoChat/ARM9/src/PictoChat.h @@ -0,0 +1,37 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: DS_Chat.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __DS_CHAT_H__ +#define __DS_CHAT_H__ + +#ifdef __cplusplus +extern "C" { +#endif + + +#include + +// define data---------------------------------------------------------- + +void PictoChatInit( void ); +void PictoChatMain( void ); + +#ifdef __cplusplus +} +#endif + +#endif // __DS_CHAT_H__ diff --git a/build/systemMenu_RED/PictoChat/ARM9/src/main.c b/build/systemMenu_RED/PictoChat/ARM9/src/main.c new file mode 100644 index 0000000..c432558 --- /dev/null +++ b/build/systemMenu_RED/PictoChat/ARM9/src/main.c @@ -0,0 +1,107 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: main.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#include +#include "misc.h" +#include "PictoChat.h" + +// extern data----------------------------------------------------------------- + +// define data----------------------------------------------------------------- + +// function's prototype------------------------------------------------------- +static void InitAllocator( NNSFndAllocator* pAllocator ); +static void InitAllocSystem( void ); +static void INTR_VBlank( void ); + +// global variable------------------------------------------------------------- +NNSFndAllocator g_allocator; + +// static variable------------------------------------------------------------- + +// const data------------------------------------------------------------------ + + +// ============================================================================ +// function's description +// ============================================================================ +void TwlMain(void) +{ + + // ---------------------------------- + OS_Init(); + + (void)OS_EnableIrq(); + (void)OS_EnableInterrupts(); + + GX_Init(); + GX_SetPower(GX_POWER_ALL); // eWbN p[ON + + // 荞݋---------------------------- + (void)OS_SetIrqFunction(OS_IE_V_BLANK, INTR_VBlank); + (void)OS_EnableIrqMask(OS_IE_V_BLANK); + (void)GX_VBlankIntr(TRUE); + + // foCX------------------------------- + TP_Init(); + (void)RTC_Init(); + + // VXȅ------------------ + InitAllocator( &g_allocator ); + CMN_InitFileSystem( &g_allocator ); + + InitBG(); + PictoChatInit(); + // C[v---------------------------- + while(1){ + OS_WaitIrq(1, OS_IE_V_BLANK); // VuN荞ݑ҂ + + ReadKeyPad(); // L[͂̎擾 + ReadTP(); // TP͂̎擾 + + PictoChatMain(); + } +} + + +// AP[^̏ +static void InitAllocator( NNSFndAllocator* pAllocator ) +{ + u32 arenaLow = MATH_ROUNDUP ((u32)OS_GetMainArenaLo(), 16); + u32 arenaHigh = MATH_ROUNDDOWN((u32)OS_GetMainArenaHi(), 16); + u32 heapSize = arenaHigh - arenaLow; + void* heapMemory = OS_AllocFromMainArenaLo(heapSize, 16); + NNSFndHeapHandle heapHandle; + SDK_NULL_ASSERT( pAllocator ); + + heapHandle = NNS_FndCreateExpHeap(heapMemory, heapSize); + SDK_ASSERT( heapHandle != NNS_FND_HEAP_INVALID_HANDLE ); + + NNS_FndInitAllocatorForExpHeap(pAllocator, heapHandle, 4); +} + + +// ============================================================================ +// 荞ݏ +// ============================================================================ + +// VuN荞 +static void INTR_VBlank(void) +{ + OS_SetIrqCheckFlag(OS_IE_V_BLANK); // VuN`FbÑZbg +} + diff --git a/build/systemMenu_RED/PictoChat/Makefile b/build/systemMenu_RED/PictoChat/Makefile new file mode 100644 index 0000000..9cf34e1 --- /dev/null +++ b/build/systemMenu_RED/PictoChat/Makefile @@ -0,0 +1,30 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +#---------------------------------------------------------------------------- + +SUBDIRS = banner ARM9 + +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/systemMenu_RED/PictoChat/banner/Makefile b/build/systemMenu_RED/PictoChat/banner/Makefile new file mode 100644 index 0000000..efdcadf --- /dev/null +++ b/build/systemMenu_RED/PictoChat/banner/Makefile @@ -0,0 +1,52 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlIPL +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-10-03#$ +# $Rev: 1319 $ +# $Author: kitase_hirotake $ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +ICON_DIR = ./icon +TOOLS_DIR = $(TWLIPL_ROOT)/tools/bin +NTEXCONV = $(TOOLS_DIR)/ntexconv.exe +MAKEBANNER = $(TOOLS_DIR)/makebanner.exe + +BANNER_ICON = $(ICON_DIR)/gameIcon.bmp +BANNER_SPEC = banner_v3.bsf + +TARGETS = banner.bnr +INSTALL_DIR = ./ +INSTALL_TARGETS = $(TARGETS) + +BANNER_ICON_NAME = $(basename $(BANNER_ICON)) + +LDIRT_CLEAN = $(TARGETS) \ + $(BANNER_ICON_NAME).nbfs \ + $(BANNER_ICON_NAME).nbfc \ + $(BANNER_ICON_NAME).nbfp \ + $(TARGETS:.bnr=.srl) + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + +#---------------------------------------------------------------------------- +# build +#---------------------------------------------------------------------------- +do-build: $(TARGETS) + +$(TARGETS): $(BANNER_SPEC) $(BANNER_ICON) + $(NTEXCONV) -no -bg -bgb -bgnc $(BANNER_ICON) >/dev/null && \ + $(MAKEBANNER) -d -N $(BANNER_ICON_NAME) $(BANNER_SPEC) $(TARGETS) + +# diff --git a/build/systemMenu_RED/PictoChat/banner/banner_v3.bsf b/build/systemMenu_RED/PictoChat/banner/banner_v3.bsf new file mode 100644 index 0000000..d595b6d Binary files /dev/null and b/build/systemMenu_RED/PictoChat/banner/banner_v3.bsf differ diff --git a/build/systemMenu_RED/PictoChat/banner/icon/gameIcon.bmp b/build/systemMenu_RED/PictoChat/banner/icon/gameIcon.bmp new file mode 100644 index 0000000..5fe5ee2 Binary files /dev/null and b/build/systemMenu_RED/PictoChat/banner/icon/gameIcon.bmp differ diff --git a/build/systemMenu_RED/data/CardBanner.bnr b/build/systemMenu_RED/data/CardBanner.bnr new file mode 100644 index 0000000..3e87abc Binary files /dev/null and b/build/systemMenu_RED/data/CardBanner.bnr differ diff --git a/build/systemMenu_RED/data/DownloadBanner.bnr b/build/systemMenu_RED/data/DownloadBanner.bnr new file mode 100644 index 0000000..f14caef Binary files /dev/null and b/build/systemMenu_RED/data/DownloadBanner.bnr differ diff --git a/build/systemMenu_RED/data/EmptyBanner.bnr b/build/systemMenu_RED/data/EmptyBanner.bnr new file mode 100644 index 0000000..35bb2e4 Binary files /dev/null and b/build/systemMenu_RED/data/EmptyBanner.bnr differ diff --git a/build/systemMenu_RED/data/NTR_IPL_font_l.NFTR b/build/systemMenu_RED/data/NTR_IPL_font_l.NFTR new file mode 100644 index 0000000..b6fe11e Binary files /dev/null and b/build/systemMenu_RED/data/NTR_IPL_font_l.NFTR differ diff --git a/build/systemMenu_RED/data/NTR_IPL_font_m.NFTR b/build/systemMenu_RED/data/NTR_IPL_font_m.NFTR new file mode 100644 index 0000000..03ba3a4 Binary files /dev/null and b/build/systemMenu_RED/data/NTR_IPL_font_m.NFTR differ diff --git a/build/systemMenu_RED/data/NTR_IPL_font_s.NFTR b/build/systemMenu_RED/data/NTR_IPL_font_s.NFTR new file mode 100644 index 0000000..59591f8 Binary files /dev/null and b/build/systemMenu_RED/data/NTR_IPL_font_s.NFTR differ diff --git a/build/systemMenu_RED/data/PictoChatBanner.bnr b/build/systemMenu_RED/data/PictoChatBanner.bnr new file mode 100644 index 0000000..87072f9 Binary files /dev/null and b/build/systemMenu_RED/data/PictoChatBanner.bnr differ diff --git a/build/systemMenu_RED/data/SettingBanner.bnr b/build/systemMenu_RED/data/SettingBanner.bnr new file mode 100644 index 0000000..e1f6218 Binary files /dev/null and b/build/systemMenu_RED/data/SettingBanner.bnr differ diff --git a/build/tools/.DS_Store b/build/tools/.DS_Store new file mode 100644 index 0000000..4a816c3 Binary files /dev/null and b/build/tools/.DS_Store differ diff --git a/build/tools/Makefile b/build/tools/Makefile new file mode 100644 index 0000000..9246e82 --- /dev/null +++ b/build/tools/Makefile @@ -0,0 +1,35 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - firmware +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + + +#---------------------------------------------------------------------------- + +SUBDIRS = \ + makenorfirm \ + makegcdfirm \ + makenandfirm \ + + +#---------------------------------------------------------------------------- + +include $(TWLSDK_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/tools/acsign/Makefile b/build/tools/acsign/Makefile new file mode 100644 index 0000000..bba2b4a --- /dev/null +++ b/build/tools/acsign/Makefile @@ -0,0 +1,61 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: NitroSDK - libraries - acsign +# File: Makefile +# +# Copyright 2003,2004 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $NoKeywords: $ +#---------------------------------------------------------------------------- + +#---------------------------------------------------------------------------- +# Codegen for sub processer +NITRO_PROC = ARM9 + +# build ARM & THUMB libraries +NITRO_CODEGEN_ALL = True + +#---------------------------------------------------------------------------- + +SUBDIRS = + + +#---------------------------------------------------------------------------- + +SRCDIR = ./src +INCDIR = ./include $(TWLSDK_ROOT)/build/libraries/mb/include + + +SRCS = acsign.c acmemory.c acsign_util.c + +TARGET_LIB = libacsign_x86.a + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +# CCFLAGS += -DOPT_32_BIT -DSTANDALONE -DNO_SPLIT -DNO_FP_API -DNO_R_DIAG -DNO_STDIO_H -DNO_STDLIB_H +CCFLAGS += -DSMALL_CODE_SIZE \ + -DSTANDALONE \ + -DOPT_32_BIT \ + -DNO_SPLIT \ + -DNO_FP_API \ + -DNO_R_DIAG \ + -DNO_STDIO_H \ + -DNO_STDLIB_H + +INSTALL_TARGETS = $(TARGETS) +INSTALL_DIR = . + + +do-build: $(TARGETS) + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/tools/acsign/acsign.c b/build/tools/acsign/acsign.c new file mode 100644 index 0000000..7b63142 --- /dev/null +++ b/build/tools/acsign/acsign.c @@ -0,0 +1,334 @@ +#include +#include "format_sign.h" +#include "acsign.h" + +// SHA1 +#include "sha1dgst.c" + +// RSA + +// BN +#include "bn.h" + +#include "bn_lib.c" +#include "bn_asm.c" +#include "bn_comba.c" +#include "bn_lsh.c" +#include "bn_rsh.c" +#include "bn_word.c" +#include "bn_add.c" +#include "bn_mul.c" +#include "bn_div.c" +#include "bn_exp.c" +#include "bn_sqr.c" +#include "bn_fm_w.c" +#include "bn_gcd.c" +#include "bn_ex_str.c" +#include "bn_ms_w.c" +//#include "bn_me.c" +#include "bn_rec.c" +#include "bn_mont.c" +#include "bn_recp.c" +#include "bn_wdiv.c" +#include "bn_r_exp.c" +#include "bn_m_exp.c" + + + +#define BER_NULL 5 +#define BER_OBJECT 6 +#define BER_SEQUENCE 16 +#define BER_OCTET_STRING 4 +#define BER_CONSTRUCTED 0x20 + + +/** + * Perform the EMSA-PKCS1_v1_5 padding + * + * @param random random context for seed data generation + * @param out destination buffer + * @param out_len length written to out + * @param in data to be padded + * @param in_len length of in + * @param flags mask of operation directives + * + * @pre out_len must contain length of data allocated to out + * @pre out must be the allocated the total length to be padded + * + * @note Method from PKCS#1 v2.1 standard 9.2.1 EMSA-PKCS1-v1_5 + * @li In: Hash is hash funtion, hLen denotes length of octets of hash output + * @li In: M is message to be encoded + * @li In: emLen is intended length of octets + * @li Out: EM encoded message of length emLen + * + * @li Apply the hash function to message M to produce a hash value H + * If hash output is message to long the output message too long and + * stop + * @li Encode the algorithm ID for the hash in function into an ASN1 value + * @li if emLen < 10 + BER encoded message T output message length too short + * and stop + * @li generate octet string PS consisting of emLen - Length(T) - 2 octets + * with value FF + * @li Concatenate PS, DER encoding T and other padding such that EM is: + * 01 || PS || 00 || T + * + * @note it is the out layers responsibility to DER encode the + * data prior to padding as described in the first 2 steps in method + */ +// +// rsa_padding_add_pkcs1_type_1֐ +// +static int add_padding(unsigned char *out, + int out_len, const unsigned char *in, int in_len) +{ + unsigned char *p; + int j,i; + + if ((in_len+11) > out_len) + return(1); + + /* First we copy data bytes to the output buffer, this + * way the input and output buffers can be the same + * and things will still work */ + p=out+out_len-in_len; + for (i=in_len-1; i>=0; i--) + p[i]=in[i]; + p=out; + *(p++)=0; + *(p++)=1; /* Private Key BT (Block Type) */ + + /* pad with 0xff data */ + j=out_len-3-in_len; + Memset(p,0xff,j); + p[j]='\0'; + return(0); +} + +static void debug_dump(const void* buf, int len, const char* str, int line_elms) +{ + const u8* bufp = (u8*)buf; + int i,ii; + + if (str) + { + debug_printf("%s :\n", str); + } + for (i=0; i<=len/line_elms; i++) + { + if (i*line_elms >= len) + { + break; + } + for (ii=0; ii= len) + { + break; + } + debug_printf("%02x ", bufp[i*line_elms+ii]); + } + debug_printf("\n"); + } +} + +// +// RSA +// +BOOL ACSign_Encrypto(void *sign, const void *key, const void *data, int length) +{ + BN_CTX *ctx; + BIGNUM src, dst, exp, mod; + u8* key_exp = &((u8*)key)[ACS_RSA_PRVEXP_OFFSET]; + u8* key_mod = &((u8*)key)[ACS_RSA_PRVMOD_OFFSET]; + u8 buf[ACS_ENCRYPTED_HASH_LEN]; + u32 len = length; + BOOL result = TRUE; + + if (NULL == sign || NULL == key || NULL == data || 0 > length) { + return FALSE; + } + + if ( add_padding( buf, ACS_ENCRYPTED_HASH_LEN, data, length ) ) { + debug_printf2("encode_padding was failed.\n"); + result = FALSE; + goto end; + } + + { + debug_dump(buf, ACS_ENCRYPTED_HASH_LEN, "padded hash", 16); + debug_dump(key_mod, ACS_RSA_PRVMOD_LEN, "key mod", 16); + debug_dump(key_exp, ACS_RSA_PRVEXP_LEN, "key exp", 16); + } + + ctx = BN_CTX_new(); + + BN_init(&src); + BN_init(&dst); + BN_init(&exp); + BN_init(&mod); + + BN_bin2bn((u8*)buf, ACS_ENCRYPTED_HASH_LEN, &src); + BN_bin2bn(key_exp, ACS_RSA_PRVEXP_LEN, &exp); + BN_bin2bn(key_mod, ACS_RSA_PRVMOD_LEN, &mod); + + BN_mod_exp( &dst, &src, &exp, &mod, ctx ); + + len = BN_bn2bin( &dst, sign ); + + BN_free(&src); + BN_free(&dst); + BN_free(&exp); + BN_free(&mod); + + if (ctx) { + BN_CTX_free(ctx); + } + + if ( len != ACS_DECRYPTED_HASH_LEN ) { + result = FALSE; + goto end; + } +end: + return result; +} + +BOOL ACSign_Decrypto(void *buf, const void *key, const void *sign, int length) +{ + BN_CTX *ctx; + BIGNUM src, dst, exp, mod; + u32 key_exp = ACS_RSA_EXP; + u8* key_mod = &((u8*)key)[ACS_RSA_PRVMOD_OFFSET]; + u8* bufp = (u8*)buf; + u32 len = length; + BOOL result = TRUE; + + if (NULL == buf || NULL == key || NULL == sign || 0 > length) { + return FALSE; + } + + ctx = BN_CTX_new(); + + BN_init(&src); + BN_init(&dst); + BN_init(&exp); + BN_init(&mod); + + BN_bin2bn((u8*)sign, ACS_ENCRYPTED_HASH_LEN, &src); + BN_bin2bn((u8*)&key_exp, ACS_RSA_PUBEXP_LEN, &exp); + BN_bin2bn(key_mod, ACS_RSA_PRVMOD_LEN, &mod); + + BN_mod_exp( &dst, &src, &exp, &mod, ctx ); + + len = BN_bn2bin( &dst, bufp ); + + BN_free(&src); + BN_free(&dst); + BN_free(&exp); + BN_free(&mod); + + if (ctx) { + BN_CTX_free(ctx); + } + + if ( len != ACS_DECRYPTED_HASH_LEN ) { + result = FALSE; + goto end; + } +end: + return result; +} + +// +int ACSign_DigestUnit( + void* buffer, // o͗̈ + const void* buf, // f[^ւ̃|C^ + unsigned int len // f[^̒ + ) +{ + HASHContext context; + unsigned char *bufferp = buffer; + + HASHReset( &context ); + HASHUpdate( &context, buf, len ); + HASHGetDigest( &context, bufferp ); + + return TRUE; +} + +// +int ACSign_CompareUnit( + const void* decedHash, // ACSign_Decryptȍo + const void* digest // ACSign_DigestUnit̏o + ) +{ + const unsigned char* dgt = digest; + const unsigned char* dgtCmp = decedHash; + int i; + int test = TRUE; + + if ( !decedHash ) return FALSE; + if ( !digest ) return FALSE; + + for ( i = 0; i < ACS_HASH_LEN; i++ ) + { + if ( *dgt++ != *dgtCmp++ ) + { + test = FALSE; + break; + } + } + return test; +} + +/* + CӃoCg̓̓f[^ + CӃoCg̏o̓f[^𓾂܂B + ΂Ă邩Ȃ͒llȒlɃ}bv邾łB + o̓ԂĂĂȂ +*/ +int ACSign_GetKey( + void* dest_ptr, // o̓f[^ւ̃|C^ + unsigned int dest_len, // o̓f[^̒ + const void* src_ptr, // ̓f[^ւ̃|C^ + unsigned int src_len // ̓f[^̒ + ) +{ + HASHContext ctx; + unsigned char *ptr; + unsigned char state[ACS_HASH_LEN]; + unsigned char output[ACS_HASH_LEN]; + int i; + + if (dest_ptr == NULL) + return 1; + if (src_ptr == NULL && src_len > 0) + return 0; + + HASHReset(&ctx); + + HASHUpdate(&ctx, src_ptr, src_len); + HASHGetDigest(&ctx, state); + + ptr = dest_ptr; + while (dest_len > 0) + { + unsigned int len = dest_len < ACS_HASH_LEN ? dest_len : ACS_HASH_LEN; + + // plus one + for (i = 0; i < ACS_HASH_LEN; i++) + { + if (state[ACS_HASH_LEN-1-i]++) + break; + } + + HASHUpdate(&ctx, state, ACS_HASH_LEN); + HASHGetDigest(&ctx, output); + memcpy(ptr, output, len); + ptr += len; + dest_len -= len; + } + memset(state, 0, ACS_HASH_LEN); + memset(output, 0, ACS_HASH_LEN); + return 1; +} + diff --git a/build/tools/acsign/acsign_gcd.c b/build/tools/acsign/acsign_gcd.c new file mode 100644 index 0000000..e8b4567 --- /dev/null +++ b/build/tools/acsign/acsign_gcd.c @@ -0,0 +1,74 @@ +#include +#include "acsign_gcd.h" + +static void debug_dump(void* buf, int len, char* str, int line_elms) +{ + u8* bufp = (u8*)buf; + int i,ii; + + if (str) + { + debug_printf("%s :\n", str); + } + for (i=0; i<=len/line_elms; i++) + { + if (i*line_elms >= len) + { + break; + } + for (ii=0; ii= len) + { + break; + } + debug_printf("%02x ", bufp[i*line_elms+ii]); + } + debug_printf("\n"); + } +} + +// +int ACSign_DigestHeader( + void* buffer, // o͗̈ + GCDHeader* header // wb_ւ̃|C^ + ) +{ + HASHContext context; + GCDHeader* nh = header; + unsigned char *bufferp = buffer; + + HASHReset( &context ); + HASHUpdate( &context, (void*)&nh->l, sizeof(GCDHeaderLow) ); + HASHUpdate( &context, (void*)&nh->h, sizeof(GCDHeaderHigh) ); + HASHGetDigest( &context, bufferp ); + + return TRUE; +} + +// +int ACSign_Final( + GCDHeader* header, // wb_ւ̃|C^ + void* buffer, // ͗̈ + const void* key + ) +{ + GCDHeader* nh = header; + FIRMSignedContext* sc = buffer; + + if (key) + { + unsigned char decSign[ACS_ENCRYPTED_HASH_LEN]; + + debug_dump(sc->hash, sizeof(sc->hash), "5 hashs of header, norfirms and total", 20); + + ACSign_Encrypto(&nh->sign, key, buffer, sizeof(FIRMSignedContext)); + ACSign_Decrypto(decSign, key, (void*)&nh->sign, ACS_ENCRYPTED_HASH_LEN); + + debug_dump(&nh->sign, ACS_ENCRYPTED_HASH_LEN, "encrypted sign", 16); + debug_dump(decSign, ACS_ENCRYPTED_HASH_LEN, "decrypted sign", 16); + } + + return TRUE; +} + diff --git a/build/tools/acsign/acsign_nand.c b/build/tools/acsign/acsign_nand.c new file mode 100644 index 0000000..8b0b719 --- /dev/null +++ b/build/tools/acsign/acsign_nand.c @@ -0,0 +1,75 @@ +#include +#include "acsign_nand.h" + +static void debug_dump(void* buf, int len, char* str, int line_elms) +{ + u8* bufp = (u8*)buf; + int i,ii; + + if (str) + { + debug_printf("%s :\n", str); + } + for (i=0; i<=len/line_elms; i++) + { + if (i*line_elms >= len) + { + break; + } + for (ii=0; ii= len) + { + break; + } + debug_printf("%02x ", bufp[i*line_elms+ii]); + } + debug_printf("\n"); + } +} + +// +int ACSign_DigestHeader( + void* buffer, // o͗̈ + NANDHeader* header // wb_ւ̃|C^ + ) +{ + HASHContext context; + NANDHeader* nh = header; + unsigned char *bufferp = buffer; + + HASHReset( &context ); + HASHUpdate( &context, (void*)&nh->d, sizeof(NORHeaderDS) ); + HASHUpdate( &context, (void*)&nh->l, sizeof(NANDHeaderLow) ); + HASHUpdate( &context, (void*)&nh->h, sizeof(NANDHeaderHigh) ); + HASHGetDigest( &context, bufferp ); + + return TRUE; +} + +// +int ACSign_Final( + NANDHeader* header, // wb_ւ̃|C^ + void* buffer, // ͗̈ + const void* key + ) +{ + NANDHeader* nh = header; + FIRMSignedContext* sc = buffer; + + if (key) + { + unsigned char decSign[ACS_ENCRYPTED_HASH_LEN]; + + debug_dump(sc->hash, sizeof(sc->hash), "5 hashs of header, nandfirms and total", 20); + + ACSign_Encrypto(&nh->sign, key, buffer, sizeof(FIRMSignedContext)); + ACSign_Decrypto(decSign, key, (void*)&nh->sign, ACS_ENCRYPTED_HASH_LEN); + + debug_dump(&nh->sign, ACS_ENCRYPTED_HASH_LEN, "encrypted sign", 16); + debug_dump(decSign, ACS_ENCRYPTED_HASH_LEN, "decrypted sign", 16); + } + + return TRUE; +} + diff --git a/build/tools/acsign/acsign_nor.c b/build/tools/acsign/acsign_nor.c new file mode 100644 index 0000000..0bb690c --- /dev/null +++ b/build/tools/acsign/acsign_nor.c @@ -0,0 +1,75 @@ +#include +#include "acsign_nor.h" + +static void debug_dump(void* buf, int len, char* str, int line_elms) +{ + u8* bufp = (u8*)buf; + int i,ii; + + if (str) + { + debug_printf("%s :\n", str); + } + for (i=0; i<=len/line_elms; i++) + { + if (i*line_elms >= len) + { + break; + } + for (ii=0; ii= len) + { + break; + } + debug_printf("%02x ", bufp[i*line_elms+ii]); + } + debug_printf("\n"); + } +} + +// +int ACSign_DigestHeader( + void* buffer, // o͗̈ + NORHeader* header // wb_ւ̃|C^ + ) +{ + HASHContext context; + NORHeader* nh = header; + unsigned char *bufferp = buffer; + + HASHReset( &context ); + HASHUpdate( &context, (void*)&nh->d, sizeof(NORHeaderDS) ); + HASHUpdate( &context, (void*)&nh->l, sizeof(NORHeaderLow) ); + HASHUpdate( &context, (void*)&nh->h, sizeof(NORHeaderHigh) ); + HASHGetDigest( &context, bufferp ); + + return TRUE; +} + +// +int ACSign_Final( + NORHeader* header, // wb_ւ̃|C^ + void* buffer, // ͗̈ + const void* key + ) +{ + NORHeader* nh = header; + FIRMSignedContext* sc = buffer; + + if (key) + { + unsigned char decSign[ACS_ENCRYPTED_HASH_LEN]; + + debug_dump(sc->hash, sizeof(sc->hash), "5 hashs of header, norfirms and total", 20); + + ACSign_Encrypto(&nh->sign, key, buffer, sizeof(FIRMSignedContext)); + ACSign_Decrypto(decSign, key, (void*)&nh->sign, ACS_ENCRYPTED_HASH_LEN); + + debug_dump(&nh->sign, ACS_ENCRYPTED_HASH_LEN, "encrypted sign", 16); + debug_dump(decSign, ACS_ENCRYPTED_HASH_LEN, "decrypted sign", 16); + } + + return TRUE; +} + diff --git a/build/tools/acsign/aes.h b/build/tools/acsign/aes.h new file mode 100644 index 0000000..a7a75d8 --- /dev/null +++ b/build/tools/acsign/aes.h @@ -0,0 +1,139 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2003 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + */ + +#ifndef HEADER_COMMON_AES_H +#define HEADER_COMMON_AES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define AES_ecb_encrypt(key, out, in) \ + AES_ecb_encrypt_com((key), (out), (in), AES_encrypt) +#define AES_ecb_encrypt_m(key, out, in) \ + AES_ecb_encrypt_com((key), (out), (in), AES_encrypt_m) +#define AES_ecb_encrypt_s(key, out, in) \ + AES_ecb_encrypt_com((key), (out), (in), AES_encrypt_s) + +#define AES_ecb_decrypt(key, out, in) \ + AES_ecb_decrypt_com((key), (out), (in), AES_decrypt) +#define AES_ecb_decrypt_m(key, out, in) \ + AES_ecb_decrypt_com((key), (out), (in), AES_decrypt_m) +#define AES_ecb_decrypt_s(key, out, in) \ + AES_ecb_decrypt_com((key), (out), (in), AES_decrypt_s) + +#define AES_cbc_encrypt(ctx, out, in, len, iv) \ + AES_cbc_encrypt_com((ctx), (out), (in), (len), (iv), AES_encrypt) +#define AES_cbc_encrypt_m(ctx, out, in, len, iv) \ + AES_cbc_encrypt_com((ctx), (out), (in), (len), (iv), AES_encrypt_m) +#define AES_cbc_encrypt_s(ctx, out, in, len, iv) \ + AES_cbc_encrypt_com((ctx), (out), (in), (len), (iv), AES_encrypt_s) + +#define AES_cbc_decrypt(ctx, out, in, len, iv) \ + AES_cbc_decrypt_com((ctx), (out), (in), (len), (iv), AES_decrypt) +#define AES_cbc_decrypt_m(ctx, out, in, len, iv) \ + AES_cbc_decrypt_com((ctx), (out), (in), (len), (iv), AES_decrypt_m) +#define AES_cbc_decrypt_s(ctx, out, in, len, iv) \ + AES_cbc_decrypt_com((ctx), (out), (in), (len), (iv), AES_decrypt_s) + +#define AES_cfb128_encrypt(ks, out, in, len, iv, num) \ + AES_cfb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt) +#define AES_cfb128_encrypt_m(ks, out, in, len, iv, num) \ + AES_cfb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt_m) +#define AES_cfb128_encrypt_s(ks, out, in, len, iv, num) \ + AES_cfb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt_s) + +#define AES_cfb128_decrypt(ks, out, in, len, iv, num) \ + AES_cfb128_decrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_decrypt) +#define AES_cfb128_decrypt_m(ks, out, in, len, iv, num) \ + AES_cfb128_decrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_decrypt_m) +#define AES_cfb128_decrypt_s(ks, out, in, len, iv, num) \ + AES_cfb128_decrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_decrypt_s) + +/** Note. OFB encryption is also used for decryption */ +#define AES_ofb128_encrypt(ks, out, in, len, iv, num) \ + AES_ofb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt) +#define AES_ofb128_encrypt_m(ks, out, in, len, iv, num) \ + AES_ofb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt_m) +#define AES_ofb128_encrypt_s(ks, out, in, len, iv, num) \ + AES_ofb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt_s) + +#define AES_ofb128_decrypt(ks, out, in, len, iv, num) \ + AES_ofb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt) +#define AES_ofb128_decrypt_m(ks, out, in, len, iv, num) \ + AES_ofb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt_m) +#define AES_ofb128_decrypt_s(ks, out, in, len, iv, num) \ + AES_ofb128_encrypt_com((ks), (out), (in), (len), (iv), (num), \ + AES_encrypt_s) + + +#define AES_MAXROUNDS 14 + +#define AES_ENCRYPT 1 +#define AES_DECRYPT 0 + +typedef unsigned int AES_INT4; + +typedef struct aes_key_st { + unsigned int rounds; + unsigned int key_size; + AES_INT4 ks[(AES_MAXROUNDS+1)*8]; + } AES_KEY; + +typedef void (* AES_ENC_DEC_FN)(AES_KEY *, AES_INT4 *); + +void AES_encrypt(AES_KEY *ctx,AES_INT4 *data); +void AES_encrypt_m(AES_KEY *ctx,AES_INT4 *data); +void AES_encrypt_s(AES_KEY *ctx,AES_INT4 *data); +void AES_decrypt(AES_KEY *ctx,AES_INT4 *data); +void AES_decrypt_m(AES_KEY *ctx,AES_INT4 *data); +void AES_decrypt_s(AES_KEY *ctx,AES_INT4 *data); + +void AES_ecb_encrypt_com(AES_KEY *key, unsigned char *out, + const unsigned char *in, AES_ENC_DEC_FN enc_fn); +void AES_ecb_decrypt_com(AES_KEY *key, unsigned char *out, + const unsigned char *in, AES_ENC_DEC_FN dec_fn); +void AES_cbc_encrypt_com(AES_KEY *ctx, unsigned char *out, + const unsigned char *in, long length, unsigned char *iv, + AES_ENC_DEC_FN enc_fn); +void AES_cbc_decrypt_com(AES_KEY *ctx, unsigned char *out, + const unsigned char *in, long length, unsigned char *iv, + AES_ENC_DEC_FN dec_fn); +void AES_ofb128_encrypt_com(AES_KEY *ks,const unsigned char *in, + unsigned char *out, long length, unsigned char *ivec, int *num, + AES_ENC_DEC_FN enc_fn); +void AES_cfb128_encrypt_com(AES_KEY *ks, const unsigned char *in, + unsigned char *out, long length, unsigned char *ivec, int *num, + AES_ENC_DEC_FN enc_fn); +void AES_cfb128_decrypt_com(AES_KEY *ks, const unsigned char *in, + unsigned char *out, long length, unsigned char *ivec, int *num, + AES_ENC_DEC_FN dec_fn); + +int AES_set_key(AES_KEY *ctx, const unsigned char *key, int len); +void AES_convert_key(AES_KEY *ctx); +AES_INT4 AES_rotate(AES_INT4 u); +unsigned char AES_xtime(AES_INT4 x); + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_AES_H */ diff --git a/build/tools/acsign/aes2.c b/build/tools/acsign/aes2.c new file mode 100644 index 0000000..778dc53 --- /dev/null +++ b/build/tools/acsign/aes2.c @@ -0,0 +1,133 @@ +#include +#include + +#include "aes2.h" + +#include "aes_e.c" +#include "aes_e_ecb.c" +#include "aes_skey.c" + +// +// swap with memory allocation +// +static unsigned char* AES_Swap(const unsigned char *src, int len, int unit) +{ + int i; + int j; + unsigned char *dest = malloc(len); + for (i = 0; i < len; i+=unit) + for (j = 0; j < unit; j++) + dest[i + j] = src[i + unit - j - 1]; + return dest; +} + +// +// set keys +// +void AES_SetKey(AES_KEY *key, const unsigned char seed[AES_BLOCK_SIZE], const unsigned char id[AES_BLOCK_SIZE]) +{ + static const unsigned char f[AES_BLOCK_SIZE] = {0xff, 0xfe, 0xfb, 0x4e, 0x29, 0x59, 0x02, 0x58, 0x2a, 0x68, 0x0f, 0x5f, 0x1a, 0x4f, 0x3e, 0x79}; + static const unsigned char s = 0x2a; + + unsigned char key1[AES_BLOCK_SIZE]; + unsigned char key2[AES_BLOCK_SIZE]; + int i; + int o = 0; + + for (i = 0; i < AES_BLOCK_SIZE; i++) { + key1[i] = seed[AES_BLOCK_SIZE-i-1] ^ id[AES_BLOCK_SIZE-i-1]; + } + for (i = AES_BLOCK_SIZE - 1; i >= 0; i--) { + int t = key1[i] + f[i] + o; + o = (t > 0xFF ? 1 : 0); + key1[i] = t & 0xFF; + } + for (i = 0; i < AES_BLOCK_SIZE; i++) { + int j1 = (i + s / 8) % AES_BLOCK_SIZE; + int j2 = (j1 + 1) % AES_BLOCK_SIZE; + int k = s % 8; + key2[i] = ((key1[j1] << k) & 0xFF) | ((key1[j2] >> (8 - k)) & 0xFF); + } + AES_set_key(key, key2, 16); + memset(key2, 0, 16); + memset(key1, 0, 16); +} + +// +// ctr mode +// +#define GETU32(pt) (((unsigned long)(pt)[0] << 24) ^ ((unsigned long)(pt)[1] << 16) ^ ((unsigned long)(pt)[2] << 8) ^ ((unsigned long)(pt)[3])) +#define PUTU32(ct, st) { (ct)[0] = (unsigned char)((st) >> 24); (ct)[1] = (unsigned char)((st) >> 16); (ct)[2] = (unsigned char)((st) >> 8); (ct)[3] = (unsigned char)(st); } + +/* increment counter as u128 */ +static void AES_ctr128_increment(unsigned char *counter) { + unsigned long c; + + c = GETU32(counter + 12); + c++; c &= 0xFFFFFFFF; + PUTU32(counter + 12, c); + if (c) return; // return unless overflow + + c = GETU32(counter + 8); + c++; c &= 0xFFFFFFFF; + PUTU32(counter + 8, c); + if (c) return; // return unless overflow + + c = GETU32(counter + 4); + c++; c &= 0xFFFFFFFF; + PUTU32(counter + 4, c); + if (c) return; // return unless overflow + + c = GETU32(counter + 0); + c++; c &= 0xFFFFFFFF; + PUTU32(counter + 0, c); +} +static void AES_ctr128(const unsigned char *in, unsigned char *out, const unsigned long length, AES_KEY *key, + unsigned char ivec[AES_BLOCK_SIZE], unsigned char ebuf[AES_BLOCK_SIZE], unsigned int *num) { + + unsigned int n; + unsigned long l=length; + + n = *num; + + while (l--) { // loop each byte + if (n == 0) { + AES_ecb_encrypt(key, ebuf, ivec); // encrypt counter + AES_ctr128_increment(ivec); // increment counter + } + *(out++) = *(in++) ^ ebuf[n]; + n = (n+1) % AES_BLOCK_SIZE; + } + + *num=n; +} + +void AES_Ctr(AES_KEY *key, unsigned char *outdata, const unsigned char *indata, int len, unsigned char iv[AES_BLOCK_SIZE]) +{ + unsigned char ebuf[AES_BLOCK_SIZE]; + unsigned char *tmp; + unsigned int nums; + + if (len <= 0 || len > 0xFFFF00 || (len % AES_BLOCK_SIZE) != 0 || indata == NULL || outdata == NULL) + { + return; + } + + // CTR + memset(ebuf, 0, AES_BLOCK_SIZE); + nums = 0; + + tmp = AES_Swap(iv, AES_BLOCK_SIZE, AES_BLOCK_SIZE); + memcpy(iv, tmp, AES_BLOCK_SIZE); + free(tmp); + + tmp = AES_Swap(indata, len, AES_BLOCK_SIZE); + AES_ctr128(tmp, outdata, len, key, iv, ebuf, &nums); + free(tmp); + + tmp = AES_Swap(outdata, len, AES_BLOCK_SIZE); + memcpy(outdata, tmp, len); + free(tmp); + return; +} + diff --git a/build/tools/acsign/aes2.h b/build/tools/acsign/aes2.h new file mode 100644 index 0000000..3e80799 --- /dev/null +++ b/build/tools/acsign/aes2.h @@ -0,0 +1,21 @@ +#ifndef __AES_2_H__ +#define __AES_2_H__ + +#include "aes.h" + +#define AES_BLOCK_SIZE 16 +#define AES_NONCE_SIZE 12 +#define AES_QUANTITY (AES_BLOCK_SIZE - AES_NONCE_SIZE - 1) + +#ifdef __cplusplus +extern "C" { +#endif + +void AES_SetKey(AES_KEY *key, const unsigned char seed[AES_BLOCK_SIZE], const unsigned char id[AES_BLOCK_SIZE]); +void AES_Ctr(AES_KEY *key, unsigned char *outdata, const unsigned char *indata, int len, unsigned char iv[AES_BLOCK_SIZE]); + +#ifdef __cplusplus +} +#endif + +#endif // __AES_2_H__ diff --git a/build/tools/acsign/aes_e.c b/build/tools/acsign/aes_e.c new file mode 100644 index 0000000..fab235c --- /dev/null +++ b/build/tools/acsign/aes_e.c @@ -0,0 +1,115 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2003 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + */ + +/** + * @file aes_e.c + * \brief Large code size (thus fast) AES Encryption + */ + +#ifndef NO_AES + +#include "aes.h" + +/* Include the Large aes_submix tables */ +#include "aes_e.h" + +/* AES ECB Encryption of 1 x 128 bit Block */ +void AES_encrypt(AES_KEY *ctx, AES_INT4 *data) +{ + int r; + int rounds; + AES_INT4 *k; + AES_INT4 o0,o1,o2,o3; + AES_INT4 tmp0,tmp1,tmp2,tmp3; + + rounds=ctx->rounds; + k= (AES_INT4 *)ctx->ks; + + /* Encrypt one block. + */ + tmp0=data[0]; + tmp1=data[1]; + tmp2=data[2]; + tmp3=data[3]; +/*printf("K %08X %08X %08X %08X\n",tmp0,tmp1,tmp2,tmp3); +printf("KS %08X %08X %08X %08X\n",k[0],k[1],k[2],k[3]); */ + tmp0^=k[0]; + tmp1^=k[1]; + tmp2^=k[2]; + tmp3^=k[3]; + k+=4; + + for(r = 1; r < rounds; r++) + { +/*printf("%2d %08X %08X %08X %08X\n",r,tmp0,tmp1,tmp2,tmp3); */ + o0 = aes_submix[3][(tmp3 )&0xff]^ + aes_submix[2][(tmp2>> 8)&0xff]^ + aes_submix[1][(tmp1>>16)&0xff]^ + aes_submix[0][(tmp0>>24)&0xff]; + + o1 = aes_submix[3][(tmp0 )&0xff]^ + aes_submix[2][(tmp3>> 8)&0xff]^ + aes_submix[1][(tmp2>>16)&0xff]^ + aes_submix[0][(tmp1>>24)&0xff]; + + o2 = + aes_submix[3][(tmp1 )&0xff]^ + aes_submix[2][(tmp0>> 8)&0xff]^ + aes_submix[1][(tmp3>>16)&0xff]^ + aes_submix[0][(tmp2>>24)&0xff]; + + o3 = + aes_submix[3][(tmp2 )&0xff]^ + aes_submix[2][(tmp1>> 8)&0xff]^ + aes_submix[1][(tmp0>>16)&0xff]^ + aes_submix[0][(tmp3>>24)&0xff]; + +/* +printf(" %08X %08X %08X %08X\n",o0,o1,o2,o3); +printf("KS %08X %08X %08X %08X\n",k[0],k[1],k[2],k[3]); */ + tmp0=o0^k[0]; + tmp1=o1^k[1]; + tmp2=o2^k[2]; + tmp3=o3^k[3]; + k+=4; + } +/*printf("O %08X %08X %08X %08X\n",o0,o1,o2,o3); */ + o0 = (aes_submix[0][(tmp3 )&0xff]>> 8)&0xFF; + o1 = (aes_submix[0][(tmp0 )&0xff]>> 8)&0xFF; + o2 = (aes_submix[0][(tmp1 )&0xff]>> 8)&0xFF; + o3 = (aes_submix[0][(tmp2 )&0xff]>> 8)&0xFF; + + o0|= (aes_submix[0][(tmp2>> 8)&0xff] )&0xFF00; + o1|= (aes_submix[0][(tmp3>> 8)&0xff] )&0xFF00; + o2|= (aes_submix[0][(tmp0>> 8)&0xff] )&0xFF00; + o3|= (aes_submix[0][(tmp1>> 8)&0xff] )&0xFF00; + + o0|= (aes_submix[0][(tmp1>>16)&0xff]<< 8)&0xFF0000; + o1|= (aes_submix[0][(tmp2>>16)&0xff]<< 8)&0xFF0000; + o2|= (aes_submix[0][(tmp3>>16)&0xff]<< 8)&0xFF0000; + o3|= (aes_submix[0][(tmp0>>16)&0xff]<< 8)&0xFF0000; + + o0|= (aes_submix[0][(tmp0>>24) ]<<16)&0xFF000000; + o1|= (aes_submix[0][(tmp1>>24) ]<<16)&0xFF000000; + o2|= (aes_submix[0][(tmp2>>24) ]<<16)&0xFF000000; + o3|= (aes_submix[0][(tmp3>>24) ]<<16)&0xFF000000; +/*printf("P %08X %08X %08X %08X\n",o0,o1,o2,o3); */ + o0^=k[0]; + o1^=k[1]; + o2^=k[2]; + o3^=k[3]; +/*printf("Q %08X %08X %08X %08X\n",o0,o1,o2,o3); */ + data[0]= o0; + data[1]= o1; + data[2]= o2; + data[3]= o3; + } + +#endif /* NO_AES */ diff --git a/build/tools/acsign/aes_e.h b/build/tools/acsign/aes_e.h new file mode 100644 index 0000000..74f6db7 --- /dev/null +++ b/build/tools/acsign/aes_e.h @@ -0,0 +1,284 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2003 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + */ + +#ifndef HEADER_COMMON_AES_E_H +#define HEADER_COMMON_AES_E_H + +#ifdef __cplusplus +extern "C" { +#endif + +const AES_INT4 aes_submix[4][256]={{ + 0xC66363A5,0xF87C7C84,0xEE777799,0xF67B7B8D, + 0xFFF2F20D,0xD66B6BBD,0xDE6F6FB1,0x91C5C554, + 0x60303050,0x02010103,0xCE6767A9,0x562B2B7D, + 0xE7FEFE19,0xB5D7D762,0x4DABABE6,0xEC76769A, + 0x8FCACA45,0x1F82829D,0x89C9C940,0xFA7D7D87, + 0xEFFAFA15,0xB25959EB,0x8E4747C9,0xFBF0F00B, + 0x41ADADEC,0xB3D4D467,0x5FA2A2FD,0x45AFAFEA, + 0x239C9CBF,0x53A4A4F7,0xE4727296,0x9BC0C05B, + 0x75B7B7C2,0xE1FDFD1C,0x3D9393AE,0x4C26266A, + 0x6C36365A,0x7E3F3F41,0xF5F7F702,0x83CCCC4F, + 0x6834345C,0x51A5A5F4,0xD1E5E534,0xF9F1F108, + 0xE2717193,0xABD8D873,0x62313153,0x2A15153F, + 0x0804040C,0x95C7C752,0x46232365,0x9DC3C35E, + 0x30181828,0x379696A1,0x0A05050F,0x2F9A9AB5, + 0x0E070709,0x24121236,0x1B80809B,0xDFE2E23D, + 0xCDEBEB26,0x4E272769,0x7FB2B2CD,0xEA75759F, + 0x1209091B,0x1D83839E,0x582C2C74,0x341A1A2E, + 0x361B1B2D,0xDC6E6EB2,0xB45A5AEE,0x5BA0A0FB, + 0xA45252F6,0x763B3B4D,0xB7D6D661,0x7DB3B3CE, + 0x5229297B,0xDDE3E33E,0x5E2F2F71,0x13848497, + 0xA65353F5,0xB9D1D168,0x00000000,0xC1EDED2C, + 0x40202060,0xE3FCFC1F,0x79B1B1C8,0xB65B5BED, + 0xD46A6ABE,0x8DCBCB46,0x67BEBED9,0x7239394B, + 0x944A4ADE,0x984C4CD4,0xB05858E8,0x85CFCF4A, + 0xBBD0D06B,0xC5EFEF2A,0x4FAAAAE5,0xEDFBFB16, + 0x864343C5,0x9A4D4DD7,0x66333355,0x11858594, + 0x8A4545CF,0xE9F9F910,0x04020206,0xFE7F7F81, + 0xA05050F0,0x783C3C44,0x259F9FBA,0x4BA8A8E3, + 0xA25151F3,0x5DA3A3FE,0x804040C0,0x058F8F8A, + 0x3F9292AD,0x219D9DBC,0x70383848,0xF1F5F504, + 0x63BCBCDF,0x77B6B6C1,0xAFDADA75,0x42212163, + 0x20101030,0xE5FFFF1A,0xFDF3F30E,0xBFD2D26D, + 0x81CDCD4C,0x180C0C14,0x26131335,0xC3ECEC2F, + 0xBE5F5FE1,0x359797A2,0x884444CC,0x2E171739, + 0x93C4C457,0x55A7A7F2,0xFC7E7E82,0x7A3D3D47, + 0xC86464AC,0xBA5D5DE7,0x3219192B,0xE6737395, + 0xC06060A0,0x19818198,0x9E4F4FD1,0xA3DCDC7F, + 0x44222266,0x542A2A7E,0x3B9090AB,0x0B888883, + 0x8C4646CA,0xC7EEEE29,0x6BB8B8D3,0x2814143C, + 0xA7DEDE79,0xBC5E5EE2,0x160B0B1D,0xADDBDB76, + 0xDBE0E03B,0x64323256,0x743A3A4E,0x140A0A1E, + 0x924949DB,0x0C06060A,0x4824246C,0xB85C5CE4, + 0x9FC2C25D,0xBDD3D36E,0x43ACACEF,0xC46262A6, + 0x399191A8,0x319595A4,0xD3E4E437,0xF279798B, + 0xD5E7E732,0x8BC8C843,0x6E373759,0xDA6D6DB7, + 0x018D8D8C,0xB1D5D564,0x9C4E4ED2,0x49A9A9E0, + 0xD86C6CB4,0xAC5656FA,0xF3F4F407,0xCFEAEA25, + 0xCA6565AF,0xF47A7A8E,0x47AEAEE9,0x10080818, + 0x6FBABAD5,0xF0787888,0x4A25256F,0x5C2E2E72, + 0x381C1C24,0x57A6A6F1,0x73B4B4C7,0x97C6C651, + 0xCBE8E823,0xA1DDDD7C,0xE874749C,0x3E1F1F21, + 0x964B4BDD,0x61BDBDDC,0x0D8B8B86,0x0F8A8A85, + 0xE0707090,0x7C3E3E42,0x71B5B5C4,0xCC6666AA, + 0x904848D8,0x06030305,0xF7F6F601,0x1C0E0E12, + 0xC26161A3,0x6A35355F,0xAE5757F9,0x69B9B9D0, + 0x17868691,0x99C1C158,0x3A1D1D27,0x279E9EB9, + 0xD9E1E138,0xEBF8F813,0x2B9898B3,0x22111133, + 0xD26969BB,0xA9D9D970,0x078E8E89,0x339494A7, + 0x2D9B9BB6,0x3C1E1E22,0x15878792,0xC9E9E920, + 0x87CECE49,0xAA5555FF,0x50282878,0xA5DFDF7A, + 0x038C8C8F,0x59A1A1F8,0x09898980,0x1A0D0D17, + 0x65BFBFDA,0xD7E6E631,0x844242C6,0xD06868B8, + 0x824141C3,0x299999B0,0x5A2D2D77,0x1E0F0F11, + 0x7BB0B0CB,0xA85454FC,0x6DBBBBD6,0x2C16163A, + },{ + 0xA5C66363,0x84F87C7C,0x99EE7777,0x8DF67B7B, + 0x0DFFF2F2,0xBDD66B6B,0xB1DE6F6F,0x5491C5C5, + 0x50603030,0x03020101,0xA9CE6767,0x7D562B2B, + 0x19E7FEFE,0x62B5D7D7,0xE64DABAB,0x9AEC7676, + 0x458FCACA,0x9D1F8282,0x4089C9C9,0x87FA7D7D, + 0x15EFFAFA,0xEBB25959,0xC98E4747,0x0BFBF0F0, + 0xEC41ADAD,0x67B3D4D4,0xFD5FA2A2,0xEA45AFAF, + 0xBF239C9C,0xF753A4A4,0x96E47272,0x5B9BC0C0, + 0xC275B7B7,0x1CE1FDFD,0xAE3D9393,0x6A4C2626, + 0x5A6C3636,0x417E3F3F,0x02F5F7F7,0x4F83CCCC, + 0x5C683434,0xF451A5A5,0x34D1E5E5,0x08F9F1F1, + 0x93E27171,0x73ABD8D8,0x53623131,0x3F2A1515, + 0x0C080404,0x5295C7C7,0x65462323,0x5E9DC3C3, + 0x28301818,0xA1379696,0x0F0A0505,0xB52F9A9A, + 0x090E0707,0x36241212,0x9B1B8080,0x3DDFE2E2, + 0x26CDEBEB,0x694E2727,0xCD7FB2B2,0x9FEA7575, + 0x1B120909,0x9E1D8383,0x74582C2C,0x2E341A1A, + 0x2D361B1B,0xB2DC6E6E,0xEEB45A5A,0xFB5BA0A0, + 0xF6A45252,0x4D763B3B,0x61B7D6D6,0xCE7DB3B3, + 0x7B522929,0x3EDDE3E3,0x715E2F2F,0x97138484, + 0xF5A65353,0x68B9D1D1,0x00000000,0x2CC1EDED, + 0x60402020,0x1FE3FCFC,0xC879B1B1,0xEDB65B5B, + 0xBED46A6A,0x468DCBCB,0xD967BEBE,0x4B723939, + 0xDE944A4A,0xD4984C4C,0xE8B05858,0x4A85CFCF, + 0x6BBBD0D0,0x2AC5EFEF,0xE54FAAAA,0x16EDFBFB, + 0xC5864343,0xD79A4D4D,0x55663333,0x94118585, + 0xCF8A4545,0x10E9F9F9,0x06040202,0x81FE7F7F, + 0xF0A05050,0x44783C3C,0xBA259F9F,0xE34BA8A8, + 0xF3A25151,0xFE5DA3A3,0xC0804040,0x8A058F8F, + 0xAD3F9292,0xBC219D9D,0x48703838,0x04F1F5F5, + 0xDF63BCBC,0xC177B6B6,0x75AFDADA,0x63422121, + 0x30201010,0x1AE5FFFF,0x0EFDF3F3,0x6DBFD2D2, + 0x4C81CDCD,0x14180C0C,0x35261313,0x2FC3ECEC, + 0xE1BE5F5F,0xA2359797,0xCC884444,0x392E1717, + 0x5793C4C4,0xF255A7A7,0x82FC7E7E,0x477A3D3D, + 0xACC86464,0xE7BA5D5D,0x2B321919,0x95E67373, + 0xA0C06060,0x98198181,0xD19E4F4F,0x7FA3DCDC, + 0x66442222,0x7E542A2A,0xAB3B9090,0x830B8888, + 0xCA8C4646,0x29C7EEEE,0xD36BB8B8,0x3C281414, + 0x79A7DEDE,0xE2BC5E5E,0x1D160B0B,0x76ADDBDB, + 0x3BDBE0E0,0x56643232,0x4E743A3A,0x1E140A0A, + 0xDB924949,0x0A0C0606,0x6C482424,0xE4B85C5C, + 0x5D9FC2C2,0x6EBDD3D3,0xEF43ACAC,0xA6C46262, + 0xA8399191,0xA4319595,0x37D3E4E4,0x8BF27979, + 0x32D5E7E7,0x438BC8C8,0x596E3737,0xB7DA6D6D, + 0x8C018D8D,0x64B1D5D5,0xD29C4E4E,0xE049A9A9, + 0xB4D86C6C,0xFAAC5656,0x07F3F4F4,0x25CFEAEA, + 0xAFCA6565,0x8EF47A7A,0xE947AEAE,0x18100808, + 0xD56FBABA,0x88F07878,0x6F4A2525,0x725C2E2E, + 0x24381C1C,0xF157A6A6,0xC773B4B4,0x5197C6C6, + 0x23CBE8E8,0x7CA1DDDD,0x9CE87474,0x213E1F1F, + 0xDD964B4B,0xDC61BDBD,0x860D8B8B,0x850F8A8A, + 0x90E07070,0x427C3E3E,0xC471B5B5,0xAACC6666, + 0xD8904848,0x05060303,0x01F7F6F6,0x121C0E0E, + 0xA3C26161,0x5F6A3535,0xF9AE5757,0xD069B9B9, + 0x91178686,0x5899C1C1,0x273A1D1D,0xB9279E9E, + 0x38D9E1E1,0x13EBF8F8,0xB32B9898,0x33221111, + 0xBBD26969,0x70A9D9D9,0x89078E8E,0xA7339494, + 0xB62D9B9B,0x223C1E1E,0x92158787,0x20C9E9E9, + 0x4987CECE,0xFFAA5555,0x78502828,0x7AA5DFDF, + 0x8F038C8C,0xF859A1A1,0x80098989,0x171A0D0D, + 0xDA65BFBF,0x31D7E6E6,0xC6844242,0xB8D06868, + 0xC3824141,0xB0299999,0x775A2D2D,0x111E0F0F, + 0xCB7BB0B0,0xFCA85454,0xD66DBBBB,0x3A2C1616, + },{ + 0x63A5C663,0x7C84F87C,0x7799EE77,0x7B8DF67B, + 0xF20DFFF2,0x6BBDD66B,0x6FB1DE6F,0xC55491C5, + 0x30506030,0x01030201,0x67A9CE67,0x2B7D562B, + 0xFE19E7FE,0xD762B5D7,0xABE64DAB,0x769AEC76, + 0xCA458FCA,0x829D1F82,0xC94089C9,0x7D87FA7D, + 0xFA15EFFA,0x59EBB259,0x47C98E47,0xF00BFBF0, + 0xADEC41AD,0xD467B3D4,0xA2FD5FA2,0xAFEA45AF, + 0x9CBF239C,0xA4F753A4,0x7296E472,0xC05B9BC0, + 0xB7C275B7,0xFD1CE1FD,0x93AE3D93,0x266A4C26, + 0x365A6C36,0x3F417E3F,0xF702F5F7,0xCC4F83CC, + 0x345C6834,0xA5F451A5,0xE534D1E5,0xF108F9F1, + 0x7193E271,0xD873ABD8,0x31536231,0x153F2A15, + 0x040C0804,0xC75295C7,0x23654623,0xC35E9DC3, + 0x18283018,0x96A13796,0x050F0A05,0x9AB52F9A, + 0x07090E07,0x12362412,0x809B1B80,0xE23DDFE2, + 0xEB26CDEB,0x27694E27,0xB2CD7FB2,0x759FEA75, + 0x091B1209,0x839E1D83,0x2C74582C,0x1A2E341A, + 0x1B2D361B,0x6EB2DC6E,0x5AEEB45A,0xA0FB5BA0, + 0x52F6A452,0x3B4D763B,0xD661B7D6,0xB3CE7DB3, + 0x297B5229,0xE33EDDE3,0x2F715E2F,0x84971384, + 0x53F5A653,0xD168B9D1,0x00000000,0xED2CC1ED, + 0x20604020,0xFC1FE3FC,0xB1C879B1,0x5BEDB65B, + 0x6ABED46A,0xCB468DCB,0xBED967BE,0x394B7239, + 0x4ADE944A,0x4CD4984C,0x58E8B058,0xCF4A85CF, + 0xD06BBBD0,0xEF2AC5EF,0xAAE54FAA,0xFB16EDFB, + 0x43C58643,0x4DD79A4D,0x33556633,0x85941185, + 0x45CF8A45,0xF910E9F9,0x02060402,0x7F81FE7F, + 0x50F0A050,0x3C44783C,0x9FBA259F,0xA8E34BA8, + 0x51F3A251,0xA3FE5DA3,0x40C08040,0x8F8A058F, + 0x92AD3F92,0x9DBC219D,0x38487038,0xF504F1F5, + 0xBCDF63BC,0xB6C177B6,0xDA75AFDA,0x21634221, + 0x10302010,0xFF1AE5FF,0xF30EFDF3,0xD26DBFD2, + 0xCD4C81CD,0x0C14180C,0x13352613,0xEC2FC3EC, + 0x5FE1BE5F,0x97A23597,0x44CC8844,0x17392E17, + 0xC45793C4,0xA7F255A7,0x7E82FC7E,0x3D477A3D, + 0x64ACC864,0x5DE7BA5D,0x192B3219,0x7395E673, + 0x60A0C060,0x81981981,0x4FD19E4F,0xDC7FA3DC, + 0x22664422,0x2A7E542A,0x90AB3B90,0x88830B88, + 0x46CA8C46,0xEE29C7EE,0xB8D36BB8,0x143C2814, + 0xDE79A7DE,0x5EE2BC5E,0x0B1D160B,0xDB76ADDB, + 0xE03BDBE0,0x32566432,0x3A4E743A,0x0A1E140A, + 0x49DB9249,0x060A0C06,0x246C4824,0x5CE4B85C, + 0xC25D9FC2,0xD36EBDD3,0xACEF43AC,0x62A6C462, + 0x91A83991,0x95A43195,0xE437D3E4,0x798BF279, + 0xE732D5E7,0xC8438BC8,0x37596E37,0x6DB7DA6D, + 0x8D8C018D,0xD564B1D5,0x4ED29C4E,0xA9E049A9, + 0x6CB4D86C,0x56FAAC56,0xF407F3F4,0xEA25CFEA, + 0x65AFCA65,0x7A8EF47A,0xAEE947AE,0x08181008, + 0xBAD56FBA,0x7888F078,0x256F4A25,0x2E725C2E, + 0x1C24381C,0xA6F157A6,0xB4C773B4,0xC65197C6, + 0xE823CBE8,0xDD7CA1DD,0x749CE874,0x1F213E1F, + 0x4BDD964B,0xBDDC61BD,0x8B860D8B,0x8A850F8A, + 0x7090E070,0x3E427C3E,0xB5C471B5,0x66AACC66, + 0x48D89048,0x03050603,0xF601F7F6,0x0E121C0E, + 0x61A3C261,0x355F6A35,0x57F9AE57,0xB9D069B9, + 0x86911786,0xC15899C1,0x1D273A1D,0x9EB9279E, + 0xE138D9E1,0xF813EBF8,0x98B32B98,0x11332211, + 0x69BBD269,0xD970A9D9,0x8E89078E,0x94A73394, + 0x9BB62D9B,0x1E223C1E,0x87921587,0xE920C9E9, + 0xCE4987CE,0x55FFAA55,0x28785028,0xDF7AA5DF, + 0x8C8F038C,0xA1F859A1,0x89800989,0x0D171A0D, + 0xBFDA65BF,0xE631D7E6,0x42C68442,0x68B8D068, + 0x41C38241,0x99B02999,0x2D775A2D,0x0F111E0F, + 0xB0CB7BB0,0x54FCA854,0xBBD66DBB,0x163A2C16, + },{ + 0x6363A5C6,0x7C7C84F8,0x777799EE,0x7B7B8DF6, + 0xF2F20DFF,0x6B6BBDD6,0x6F6FB1DE,0xC5C55491, + 0x30305060,0x01010302,0x6767A9CE,0x2B2B7D56, + 0xFEFE19E7,0xD7D762B5,0xABABE64D,0x76769AEC, + 0xCACA458F,0x82829D1F,0xC9C94089,0x7D7D87FA, + 0xFAFA15EF,0x5959EBB2,0x4747C98E,0xF0F00BFB, + 0xADADEC41,0xD4D467B3,0xA2A2FD5F,0xAFAFEA45, + 0x9C9CBF23,0xA4A4F753,0x727296E4,0xC0C05B9B, + 0xB7B7C275,0xFDFD1CE1,0x9393AE3D,0x26266A4C, + 0x36365A6C,0x3F3F417E,0xF7F702F5,0xCCCC4F83, + 0x34345C68,0xA5A5F451,0xE5E534D1,0xF1F108F9, + 0x717193E2,0xD8D873AB,0x31315362,0x15153F2A, + 0x04040C08,0xC7C75295,0x23236546,0xC3C35E9D, + 0x18182830,0x9696A137,0x05050F0A,0x9A9AB52F, + 0x0707090E,0x12123624,0x80809B1B,0xE2E23DDF, + 0xEBEB26CD,0x2727694E,0xB2B2CD7F,0x75759FEA, + 0x09091B12,0x83839E1D,0x2C2C7458,0x1A1A2E34, + 0x1B1B2D36,0x6E6EB2DC,0x5A5AEEB4,0xA0A0FB5B, + 0x5252F6A4,0x3B3B4D76,0xD6D661B7,0xB3B3CE7D, + 0x29297B52,0xE3E33EDD,0x2F2F715E,0x84849713, + 0x5353F5A6,0xD1D168B9,0x00000000,0xEDED2CC1, + 0x20206040,0xFCFC1FE3,0xB1B1C879,0x5B5BEDB6, + 0x6A6ABED4,0xCBCB468D,0xBEBED967,0x39394B72, + 0x4A4ADE94,0x4C4CD498,0x5858E8B0,0xCFCF4A85, + 0xD0D06BBB,0xEFEF2AC5,0xAAAAE54F,0xFBFB16ED, + 0x4343C586,0x4D4DD79A,0x33335566,0x85859411, + 0x4545CF8A,0xF9F910E9,0x02020604,0x7F7F81FE, + 0x5050F0A0,0x3C3C4478,0x9F9FBA25,0xA8A8E34B, + 0x5151F3A2,0xA3A3FE5D,0x4040C080,0x8F8F8A05, + 0x9292AD3F,0x9D9DBC21,0x38384870,0xF5F504F1, + 0xBCBCDF63,0xB6B6C177,0xDADA75AF,0x21216342, + 0x10103020,0xFFFF1AE5,0xF3F30EFD,0xD2D26DBF, + 0xCDCD4C81,0x0C0C1418,0x13133526,0xECEC2FC3, + 0x5F5FE1BE,0x9797A235,0x4444CC88,0x1717392E, + 0xC4C45793,0xA7A7F255,0x7E7E82FC,0x3D3D477A, + 0x6464ACC8,0x5D5DE7BA,0x19192B32,0x737395E6, + 0x6060A0C0,0x81819819,0x4F4FD19E,0xDCDC7FA3, + 0x22226644,0x2A2A7E54,0x9090AB3B,0x8888830B, + 0x4646CA8C,0xEEEE29C7,0xB8B8D36B,0x14143C28, + 0xDEDE79A7,0x5E5EE2BC,0x0B0B1D16,0xDBDB76AD, + 0xE0E03BDB,0x32325664,0x3A3A4E74,0x0A0A1E14, + 0x4949DB92,0x06060A0C,0x24246C48,0x5C5CE4B8, + 0xC2C25D9F,0xD3D36EBD,0xACACEF43,0x6262A6C4, + 0x9191A839,0x9595A431,0xE4E437D3,0x79798BF2, + 0xE7E732D5,0xC8C8438B,0x3737596E,0x6D6DB7DA, + 0x8D8D8C01,0xD5D564B1,0x4E4ED29C,0xA9A9E049, + 0x6C6CB4D8,0x5656FAAC,0xF4F407F3,0xEAEA25CF, + 0x6565AFCA,0x7A7A8EF4,0xAEAEE947,0x08081810, + 0xBABAD56F,0x787888F0,0x25256F4A,0x2E2E725C, + 0x1C1C2438,0xA6A6F157,0xB4B4C773,0xC6C65197, + 0xE8E823CB,0xDDDD7CA1,0x74749CE8,0x1F1F213E, + 0x4B4BDD96,0xBDBDDC61,0x8B8B860D,0x8A8A850F, + 0x707090E0,0x3E3E427C,0xB5B5C471,0x6666AACC, + 0x4848D890,0x03030506,0xF6F601F7,0x0E0E121C, + 0x6161A3C2,0x35355F6A,0x5757F9AE,0xB9B9D069, + 0x86869117,0xC1C15899,0x1D1D273A,0x9E9EB927, + 0xE1E138D9,0xF8F813EB,0x9898B32B,0x11113322, + 0x6969BBD2,0xD9D970A9,0x8E8E8907,0x9494A733, + 0x9B9BB62D,0x1E1E223C,0x87879215,0xE9E920C9, + 0xCECE4987,0x5555FFAA,0x28287850,0xDFDF7AA5, + 0x8C8C8F03,0xA1A1F859,0x89898009,0x0D0D171A, + 0xBFBFDA65,0xE6E631D7,0x4242C684,0x6868B8D0, + 0x4141C382,0x9999B029,0x2D2D775A,0x0F0F111E, + 0xB0B0CB7B,0x5454FCA8,0xBBBBD66D,0x16163A2C, + }}; + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_AES_E_H */ diff --git a/build/tools/acsign/aes_e_ecb.c b/build/tools/acsign/aes_e_ecb.c new file mode 100644 index 0000000..55867bd --- /dev/null +++ b/build/tools/acsign/aes_e_ecb.c @@ -0,0 +1,48 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2003 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + */ + +#ifndef NO_AES + +#include "aes.h" + + +void AES_ecb_encrypt_com(AES_KEY *key, unsigned char *out, + const unsigned char *in, AES_ENC_DEC_FN enc_fn) + { + AES_INT4 data[4],w; + + data[0]=((in[ 0]<<24)|(in[ 1]<<16)|(in[ 2]<<8)|(in[ 3])); + data[1]=((in[ 4]<<24)|(in[ 5]<<16)|(in[ 6]<<8)|(in[ 7])); + data[2]=((in[ 8]<<24)|(in[ 9]<<16)|(in[10]<<8)|(in[11])); + data[3]=((in[12]<<24)|(in[13]<<16)|(in[14]<<8)|(in[15])); + enc_fn(key,&(data[0])); + w=data[0]; + out[ 0]=(w>>24)&0xff; + out[ 1]=(w>>16)&0xff; + out[ 2]=(w>> 8)&0xff; + out[ 3]=(w )&0xff; + w=data[1]; + out[ 4]=(w>>24)&0xff; + out[ 5]=(w>>16)&0xff; + out[ 6]=(w>> 8)&0xff; + out[ 7]=(w )&0xff; + w=data[2]; + out[ 8]=(w>>24)&0xff; + out[ 9]=(w>>16)&0xff; + out[10]=(w>> 8)&0xff; + out[11]=(w )&0xff; + w=data[3]; + out[12]=(w>>24)&0xff; + out[13]=(w>>16)&0xff; + out[14]=(w>> 8)&0xff; + out[15]=(w )&0xff; + } + +#endif /* NO_AES */ diff --git a/build/tools/acsign/aes_sbox.h b/build/tools/acsign/aes_sbox.h new file mode 100644 index 0000000..6a584f4 --- /dev/null +++ b/build/tools/acsign/aes_sbox.h @@ -0,0 +1,59 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2003 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + */ + +#ifndef HEADER_COMMON_AES_SBOX_H +#define HEADER_COMMON_AES_SBOX_H + +#ifdef __cplusplus +extern "C" { +#endif + +extern const unsigned char aes_sbox[256]; + +const unsigned char aes_sbox[256]={ + 0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5, + 0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76, + 0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0, + 0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0, + 0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC, + 0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15, + 0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A, + 0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75, + 0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0, + 0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84, + 0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B, + 0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF, + 0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85, + 0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8, + 0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5, + 0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2, + 0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17, + 0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73, + 0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88, + 0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB, + 0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C, + 0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79, + 0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9, + 0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08, + 0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6, + 0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A, + 0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E, + 0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E, + 0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94, + 0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF, + 0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68, + 0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16, + }; + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_AES_SBOX_H */ diff --git a/build/tools/acsign/aes_skey.c b/build/tools/acsign/aes_skey.c new file mode 100644 index 0000000..682766e --- /dev/null +++ b/build/tools/acsign/aes_skey.c @@ -0,0 +1,143 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2003 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + */ + +#ifndef NO_AES + +#include "aes.h" +#include "aes_sbox.h" + +static const unsigned char Rcon[30]={ + 0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80, + 0x1b,0x36,0x6c,0xd8,0xab,0x4d,0x9a,0x2f, + 0x5e,0xbc,0x63,0xc6,0x97,0x35,0x6a,0xd4, + 0xb3,0x7d,0xfa,0xef,0xc5,0x91, + }; + +int AES_set_key(AES_KEY *ctx, const unsigned char *key, int len) + { + int i,ii; + AES_INT4 *W,tmp,tmp2; + const unsigned char *ip; + int words; + + if (len == 16) + { + i=10; + words=4; + } + else if (len == 24) + { + i=12; + words=6; + } + else if (len == 32) + { + i=14; + words=8; + } + else + return(1); + + ctx->rounds=i; + ctx->key_size=words; + W=(unsigned int *)ctx->ks; + for (i=0; irounds+1); + for (i=words; i> 8)&0xff]<<16; + tmp2|=(AES_INT4)aes_sbox[(tmp>>16)&0xff]<<24; + tmp2|=(AES_INT4)aes_sbox[(tmp>>24) ]; + tmp=tmp2^(((unsigned int)*ip)<<24); + ip++; + } + if ((words == 8) && ((i % words) == 4)) + { + tmp2 =(AES_INT4)aes_sbox[(tmp )&0xff] ; + tmp2|=(AES_INT4)aes_sbox[(tmp>> 8)&0xff]<< 8; + tmp2|=(AES_INT4)aes_sbox[(tmp>>16)&0xff]<<16; + tmp2|=(AES_INT4)aes_sbox[(tmp>>24) ]<<24; + tmp=tmp2; + } + W[i]=W[i-words]^tmp; + } + return(0); + } + +#define rot1(x) (((x) << 24) | ((x) >> 8)) +#define rot2(x) (((x) << 16) | ((x) >> 16)) +#define rot3(x) (((x) << 8) | ((x) >> 24)) + +/* This cute trick does 4 'mul by two' at once. Stolen from + * Dr B. R. Gladman but I'm sure the u-(u>>7) is + * a standard graphics trick + * The key to this is that we need to xor with 0x1b if the top bit is set. + * a 1xxx xxxx 0xxx 0xxx First we mask the 7bit, + * b 1000 0000 0000 0000 then we shift right by 7 puting the 7bit in 0bit, + * c 0000 0001 0000 0000 we then subtract (c) from (b) + * d 0111 1111 0000 0000 and now we and with our mask + * e 0001 1011 0000 0000 + */ +#define mt 0x80808080 +#define ml 0x7f7f7f7f +#define mh 0xfefefefe +#define mm 0x1b1b1b1b +#define mul2(x,t) ((t)=((x)&mt), \ + ((((x)+(x))&mh)^(((t)-((t)>>7))&mm))) + +#define mix_col(x,f2,f3) (\ + (f2)=mul2(x,f3), \ + (f3)=(x)^(f2), \ + (rot3(f3) ^ rot2(x) ^ rot1(x)^(f2))) + +#define inv_mix_col(x,f2,f4,f8,f9) (\ + (f2)=mul2(x,f2), \ + (f4)=mul2(f2,f4), \ + (f8)=mul2(f4,f8), \ + (f9)=(x)^(f8), \ + (f8)=((f2)^(f4)^(f8)), \ + (f2)^=(f9), \ + (f4)^=(f9), \ + (f8)^=rot3(f2), \ + (f8)^=rot2(f4), \ + (f8)^rot1(f9)) + +void AES_convert_key(AES_KEY *ctx) + { + int i; + AES_INT4 *k,w,t1,t2,t3,t4; + + k= ctx->ks; + k+=4; + for (i=ctx->rounds*4; i>4; i--) + { + w= *k; + w = inv_mix_col(w,t1,t2,t3,t4); + *k++ =w; + } + } +#endif /* NO_AES */ diff --git a/build/tools/acsign/bn_add.c b/build/tools/acsign/bn_add.c new file mode 100644 index 0000000..75820c6 --- /dev/null +++ b/build/tools/acsign/bn_add.c @@ -0,0 +1,304 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +/** + * @file bn_add.c + * @brief BIGNUM addition and subtraction functions + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_ADD +#define SPLIT_BN_UADD +#define SPLIT_BN_USUB +#define SPLIT_BN_SUB +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_ADD +/* r can == a or b */ +int BN_add(r, a, b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + BIGNUM *tmp; + + bn_check_top(a); + bn_check_top(b); + + /* a + b a+b + * a + -b a-b + * -a + b b-a + * -a + -b -(a+b) + */ + if (a->neg ^ b->neg) + { + /* only one is negative */ + if (a->neg) + { tmp=a; a=b; b=tmp; } + + /* we are now a - b */ + + if (BN_ucmp(a,b) < 0) + { + if (!BN_usub(r,b,a)) return(0); + r->neg=1; + } + else + { + if (!BN_usub(r,a,b)) return(0); + r->neg=0; + } + return(1); + } + + if (a->neg) /* both are neg */ + r->neg=1; + else + r->neg=0; + + if (!BN_uadd(r,a,b)) return(0); + return(1); + } +#endif + +#ifdef SPLIT_BN_UADD +/* unsigned add of b to a, r must be large enough */ +int BN_uadd(r,a,b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + register int i; + int max,min; + BN_ULONG *ap,*bp,*rp,carry,t1; + BIGNUM *tmp; + + bn_check_top(a); + bn_check_top(b); + + if (a->top < b->top) + { tmp=a; a=b; b=tmp; } + max=a->top; + min=b->top; + + if (bn_wexpand(r,max+1) == NULL) + return(0); + + r->top=max; + + + ap=a->d; + bp=b->d; + rp=r->d; + carry=0; + + carry=bn_add_words(rp,ap,bp,min); + rp+=min; + ap+=min; + bp+=min; + i=min; + + if (carry) + { + while (i < max) + { + i++; + t1= *(ap++); + if ((*(rp++)=(t1+1)&BN_MASK2) >= t1) + { + carry=0; + break; + } + } + if ((i >= max) && carry) + { + *(rp++)=1; + r->top++; + } + } + if (rp != ap) + { + for (; ib from a + * @param r result of subtraction + * @param a pointer to a BIGNUM + * @param b pointer to a BIGNUM + * @pre a must be larger than b + * @return 1 on success, 0 on failure + * @todo On next IRIX port check the validity of IRIX_CC_BUG. + */ +#ifdef SPLIT_BN_USUB +int BN_usub(r, a, b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + int max,min; + register BN_ULONG t1,t2,*ap,*bp,*rp; + int i,carry; +#if defined(IRIX_CC_BUG) && !defined(LINT) + int dummy; +#endif + + bn_check_top(a); + bn_check_top(b); + + /* + * check for pre-condition violation + */ + if (a->top < b->top) + { +#ifndef NO_ERR + BNerr(BN_F_BN_USUB,BN_R_ARG2_LT_ARG3); +#endif + return(0); + } + + max=a->top; + min=b->top; + if (bn_wexpand(r,max) == NULL) return(0); + + ap=a->d; + bp=b->d; + rp=r->d; + + /* + * perform the subtraction and see if we + * have a (final) carry + */ + carry=0; + for (i=0; i t2) break; + } + } + + if (rp != ap) + { +#ifdef BN_LIBRARY_SMALL + Memcpy(rp,ap,sizeof(*rp)*(max-i)); +#else /* BN_LIBRARY_SMALL */ + for (;;) + { + if (i++ >= max) break; + rp[0]=ap[0]; + if (i++ >= max) break; + rp[1]=ap[1]; + if (i++ >= max) break; + rp[2]=ap[2]; + if (i++ >= max) break; + rp[3]=ap[3]; + rp+=4; + ap+=4; + } +#endif /* BN_LIBRARY_SMALL */ + } + + r->top=max; + bn_fix_top(r); + return(1); + } +#endif + +#ifdef SPLIT_BN_SUB +int BN_sub(r, a, b) +BIGNUM *r; +BIGNUM *a; +BIGNUM *b; + { + int max; + int add=0,neg=0; + BIGNUM *tmp; + + bn_check_top(a); + bn_check_top(b); + + /* a - b a-b + * a - -b a+b + * -a - b -(a+b) + * -a - -b b-a + */ + if (a->neg) + { + if (b->neg) + { tmp=a; a=b; b=tmp; } + else + { add=1; neg=1; } + } + else + { + if (b->neg) { add=1; neg=0; } + } + + if (add) + { + if (!BN_uadd(r,a,b)) return(0); + r->neg=neg; + return(1); + } + + /* We are actually doing a - b */ + + max=(a->top > b->top)?a->top:b->top; + if (bn_wexpand(r,max) == NULL) return(0); + if (BN_ucmp(a,b) < 0) + { + if (!BN_usub(r,b,a)) return(0); + r->neg=1; + } + else + { + if (!BN_usub(r,a,b)) return(0); + r->neg=0; + } + return(1); + } +#endif + +#endif diff --git a/build/tools/acsign/bn_asm.c b/build/tools/acsign/bn_asm.c new file mode 100644 index 0000000..59326c1 --- /dev/null +++ b/build/tools/acsign/bn_asm.c @@ -0,0 +1,509 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef OPT_BN_ASM + +#define BN_MUL_ADD_WORDS + +#ifndef BN_MUL_WORDS +#define BN_MUL_WORDS +#endif + +#ifndef BN_SQR_WORDS +#define BN_SQR_WORDS +#endif + +#ifndef BN_ADD_WORDS +#define BN_ADD_WORDS +#endif + +#ifndef BN_SUB_WORDS +#define BN_SUB_WORDS +#endif + +#endif + + +#include "bn_lcl.h" + +#ifdef BN_LLONG + +/* + * bn_mul_add_words + * + * for(i=0;i=0; i--) + fprintf(stderr,BN_HEX_FMT,ap[i]); + fprintf(stderr,"*"); + fprintf(stderr,BN_HEX_FMT,w); + fprintf(stderr,"+"); + for (i=num-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,rp[i]); +#endif + + for (;;) + { + mul_add(rp[0],ap[0],w,c1); + if (--num == 0) break; + mul_add(rp[1],ap[1],w,c1); + if (--num == 0) break; + mul_add(rp[2],ap[2],w,c1); + if (--num == 0) break; + mul_add(rp[3],ap[3],w,c1); + if (--num == 0) break; + ap+=4; + rp+=4; + } + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"-"); + fprintf(stderr,BN_HEX_FMT,c1); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,rp[i]); + fprintf(stderr,"\n"); + } +#endif + return(c1); + } +#endif + +#ifdef BN_MUL_WORDS +BN_ULONG bn_mul_words(rp,ap,num,w) +BN_ULONG *rp,*ap; +int num; +BN_ULONG w; + { + BN_ULONG c1=0; + + bn_check_num(num); + if (num <= 0) return(c1); + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=num; + + for (i=num-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,ap[i]); + fprintf(stderr,"*"); + fprintf(stderr,BN_HEX_FMT,w); +#endif + + for (;;) + { + mul(rp[0],ap[0],w,c1); + if (--num == 0) break; + mul(rp[1],ap[1],w,c1); + if (--num == 0) break; + mul(rp[2],ap[2],w,c1); + if (--num == 0) break; + mul(rp[3],ap[3],w,c1); + if (--num == 0) break; + ap+=4; + rp+=4; + } + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"-"); + fprintf(stderr,BN_HEX_FMT,c1); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,rp[i]); + fprintf(stderr,"\n"); + } +#endif + return(c1); + } +#endif + +#ifdef BN_SQR_WORDS +void bn_sqr_words(r,a,n) +BN_ULONG *r,*a; +int n; + { + bn_check_num(n); + if (n <= 0) return; + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=n; + + for (i=n-1; i>=0; i--) + { + fprintf(stderr,BN_HEX_FMT,a[i]); + if (i != 0) + fprintf(stderr,"^2*2^%X+",i*2*BN_BITS2); + else + fprintf(stderr,"^2"); + } +#endif + + for (;;) + { + BN_ULLONG t; + + t=(BN_ULLONG)(a[0])*(a[0]); + r[0]=Lw(t); r[1]=Hw(t); + if (--n == 0) break; + + t=(BN_ULLONG)(a[1])*(a[1]); + r[2]=Lw(t); r[3]=Hw(t); + if (--n == 0) break; + + t=(BN_ULLONG)(a[2])*(a[2]); + r[4]=Lw(t); r[5]=Hw(t); + if (--n == 0) break; + + t=(BN_ULLONG)(a[3])*(a[3]); + r[6]=Lw(t); r[7]=Hw(t); + if (--n == 0) break; + + a+=4; + r+=8; + } +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + + fprintf(stderr,"-"); + for (i=nn+nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,r[i]); + fprintf(stderr,"\n"); + } +#endif + } +#endif + +#else + +#ifdef BN_MUL_ADD_WORDS + +BN_ULONG bn_mul_add_words(rp,ap,num,w) +BN_ULONG *rp,*ap; +int num; +BN_ULONG w; + { + BN_ULONG c=0; + BN_ULONG bl,bh,b_hl; + + bn_check_num(num); + if (num <= 0) return((BN_ULONG)0); + + bl=LBITS(w); + bh=HBITS(w); + b_hl=bh-bl; +/* +{ int i,nnum=num; +BN_ULONG *rrp=rp; +for (i=num-1; i>=0; i--) printf("%02X",rp[i]); +printf("+"); +for (i=num-1; i>=0; i--) printf("%02X",ap[i]); +printf("*%02X - ",w); +*/ + for (;;) + { + mul_add(rp[0],ap[0],bl,bh,b_hl,c); + if (--num == 0) break; + mul_add(rp[1],ap[1],bl,bh,b_hl,c); + if (--num == 0) break; + mul_add(rp[2],ap[2],bl,bh,b_hl,c); + if (--num == 0) break; + mul_add(rp[3],ap[3],bl,bh,b_hl,c); + if (--num == 0) break; + ap+=4; + rp+=4; + } + +/* +printf("%02X",c); +for (i=nnum-1; i>=0; i--) printf("%02X",rrp[i]); +printf("\n"); +} +*/ + return(c); + } + +#endif + +#ifdef BN_MUL_WORDS +BN_ULONG bn_mul_words(rp,ap,num,w) +BN_ULONG *rp,*ap; +int num; +BN_ULONG w; + { + BN_ULONG carry=0; + BN_ULONG bl,bh; + + bn_check_num(num); + if (num <= 0) return((BN_ULONG)0); + + bl=LBITS(w); + bh=HBITS(w); + + for (;;) + { + mul(rp[0],ap[0],bl,bh,carry); + if (--num == 0) break; + mul(rp[1],ap[1],bl,bh,carry); + if (--num == 0) break; + mul(rp[2],ap[2],bl,bh,carry); + if (--num == 0) break; + mul(rp[3],ap[3],bl,bh,carry); + if (--num == 0) break; + ap+=4; + rp+=4; + } + return(carry); + } +#endif + +#ifdef BN_SQR_WORDS +void bn_sqr_words(r,a,n) +BN_ULONG *r,*a; +int n; + { + bn_check_num(n); + if (n <= 0) return; + for (;;) + { + sqr64(r[0],r[1],a[0]); + if (--n == 0) break; + + sqr64(r[2],r[3],a[1]); + if (--n == 0) break; + + sqr64(r[4],r[5],a[2]); + if (--n == 0) break; + + sqr64(r[6],r[7],a[3]); + if (--n == 0) break; + + a+=4; + r+=8; + } + } +#endif + +#endif + +#ifdef BN_ADD_WORDS +#ifdef BN_LLONG +BN_ULONG bn_add_words(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { + BN_ULLONG ll=0; + + bn_check_num(n); + if (n <= 0) return((BN_ULONG)0); + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=n; + + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,a[i]); + fprintf(stderr,"+"); + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,b[i]); +#endif + + for (;;) + { + ll+=(BN_ULLONG)a[0]+b[0]; + r[0]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + ll+=(BN_ULLONG)a[1]+b[1]; + r[1]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + ll+=(BN_ULLONG)a[2]+b[2]; + r[2]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + ll+=(BN_ULLONG)a[3]+b[3]; + r[3]=(BN_ULONG)ll&BN_MASK2; + ll>>=BN_BITS2; + if (--n <= 0) break; + + a+=4; + b+=4; + r+=4; + } +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"-"); + fprintf(stderr,BN_HEX_FMT,(BN_ULONG)ll); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,r[i]); + fprintf(stderr,"\n"); + } +#endif + return((BN_ULONG)ll); + } +#else +BN_ULONG bn_add_words(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { + BN_ULONG c,l,t; + + bn_check_num(n); + if (n <= 0) return((BN_ULONG)0); + + c=0; + for (;;) + { + t=a[0]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[0])&BN_MASK2; + c+=(l < t); + r[0]=l; + if (--n <= 0) break; + + t=a[1]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[1])&BN_MASK2; + c+=(l < t); + r[1]=l; + if (--n <= 0) break; + + t=a[2]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[2])&BN_MASK2; + c+=(l < t); + r[2]=l; + if (--n <= 0) break; + + t=a[3]; + t=(t+c)&BN_MASK2; + c=(t < c); + l=(t+b[3])&BN_MASK2; + c+=(l < t); + r[3]=l; + if (--n <= 0) break; + + a+=4; + b+=4; + r+=4; + } + + return((BN_ULONG)c); + } +#endif +#endif + +#ifdef BN_SUB_WORDS +BN_ULONG bn_sub_words(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { + BN_ULONG c,t1,t2; + + bn_check_num(n); + if (n <= 0) return((BN_ULONG)0); + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + { + int i,nn=n; + + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,a[i]); + fprintf(stderr,"-"); + for (i=n-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,b[i]); +#endif + + c=0; + for (;;) + { + t1=a[0]; t2=b[0]; + r[0]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + t1=a[1]; t2=b[1]; + r[1]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + t1=a[2]; t2=b[2]; + r[2]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + t1=a[3]; t2=b[3]; + r[3]=(t1-t2-c)&BN_MASK2; + if (t1 != t2) c=(t1 < t2); + if (--n <= 0) break; + + a+=4; + b+=4; + r+=4; + } + +#if defined(BN_ASM_DEBUG) && !defined(NO_FP_API) + fprintf(stderr,"- "); + if (c) fprintf(stderr,"-"); + for (i=nn-1; i>=0; i--) + fprintf(stderr,BN_HEX_FMT,r[i]); + fprintf(stderr,"\n"); + } +#endif + return(c); + } +#endif + diff --git a/build/tools/acsign/bn_comba.c b/build/tools/acsign/bn_comba.c new file mode 100644 index 0000000..61dbc93 --- /dev/null +++ b/build/tools/acsign/bn_comba.c @@ -0,0 +1,434 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MUL_COMBA8 +#define SPLIT_BN_MUL_COMBA4 +#define SPLIT_BN_SQR_COMBA8 +#define SPLIT_BN_SQR_COMBA4 +#endif /* NO_SPLIT */ + +#ifndef OPT_BN_ASM +/* #if 1 */ + +#ifdef BN_LLONG +#define mul_add_c(a,b,c0,c1,c2) \ + t=(BN_ULLONG)a*b; \ + t1=(BN_ULONG)Lw(t); \ + t2=(BN_ULONG)Hw(t); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define mul_add_c2(a,b,c0,c1,c2) \ + t=(BN_ULLONG)a*b; \ + tt=(t+t)&BN_MASK; \ + if (tt < t) c2++; \ + t1=(BN_ULONG)Lw(tt); \ + t2=(BN_ULONG)Hw(tt); \ + c0=(c0+t1)&BN_MASK2; \ + if ((c0 < t1) && (((++t2)&BN_MASK2) == 0)) c2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c(a,i,c0,c1,c2) \ + t=(BN_ULLONG)a[i]*a[i]; \ + t1=(BN_ULONG)Lw(t); \ + t2=(BN_ULONG)Hw(t); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c2(a,i,j,c0,c1,c2) \ + mul_add_c2((a)[i],(a)[j],c0,c1,c2) +#else +#define mul_add_c(a,b,c0,c1,c2) \ + t1=LBITS(a); t2=HBITS(a); \ + bl=LBITS(b); bh=HBITS(b); \ + mul64(t1,t2,bl,bh); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define mul_add_c2(a,b,c0,c1,c2) \ + t1=LBITS(a); t2=HBITS(a); \ + bl=LBITS(b); bh=HBITS(b); \ + mul64(t1,t2,bl,bh); \ + if (t2 & BN_TBIT) c2++; \ + t2=(t2+t2)&BN_MASK2; \ + if (t1 & BN_TBIT) t2++; \ + t1=(t1+t1)&BN_MASK2; \ + c0=(c0+t1)&BN_MASK2; \ + if ((c0 < t1) && (((++t2)&BN_MASK2) == 0)) c2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c(a,i,c0,c1,c2) \ + sqr64(t1,t2,(a)[i]); \ + c0=(c0+t1)&BN_MASK2; if ((c0) < t1) t2++; \ + c1=(c1+t2)&BN_MASK2; if ((c1) < t2) c2++; + +#define sqr_add_c2(a,i,j,c0,c1,c2) \ + mul_add_c2((a)[i],(a)[j],c0,c1,c2) +#endif + +#if defined(BN_MUL_COMBA) + +#ifdef SPLIT_BN_MUL_COMBA8 +#undef bn_mul_comba8 +void bn_mul_comba8(r,a,b) +BN_ULONG *r,*a,*b; + { +#ifdef BN_LLONG + BN_ULLONG t; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + mul_add_c(a[0],b[0],c1,c2,c3); + r[0]=c1; + c1=0; + mul_add_c(a[0],b[1],c2,c3,c1); + mul_add_c(a[1],b[0],c2,c3,c1); + r[1]=c2; + c2=0; + mul_add_c(a[2],b[0],c3,c1,c2); + mul_add_c(a[1],b[1],c3,c1,c2); + mul_add_c(a[0],b[2],c3,c1,c2); + r[2]=c3; + c3=0; + mul_add_c(a[0],b[3],c1,c2,c3); + mul_add_c(a[1],b[2],c1,c2,c3); + mul_add_c(a[2],b[1],c1,c2,c3); + mul_add_c(a[3],b[0],c1,c2,c3); + r[3]=c1; + c1=0; + mul_add_c(a[4],b[0],c2,c3,c1); + mul_add_c(a[3],b[1],c2,c3,c1); + mul_add_c(a[2],b[2],c2,c3,c1); + mul_add_c(a[1],b[3],c2,c3,c1); + mul_add_c(a[0],b[4],c2,c3,c1); + r[4]=c2; + c2=0; + mul_add_c(a[0],b[5],c3,c1,c2); + mul_add_c(a[1],b[4],c3,c1,c2); + mul_add_c(a[2],b[3],c3,c1,c2); + mul_add_c(a[3],b[2],c3,c1,c2); + mul_add_c(a[4],b[1],c3,c1,c2); + mul_add_c(a[5],b[0],c3,c1,c2); + r[5]=c3; + c3=0; + mul_add_c(a[6],b[0],c1,c2,c3); + mul_add_c(a[5],b[1],c1,c2,c3); + mul_add_c(a[4],b[2],c1,c2,c3); + mul_add_c(a[3],b[3],c1,c2,c3); + mul_add_c(a[2],b[4],c1,c2,c3); + mul_add_c(a[1],b[5],c1,c2,c3); + mul_add_c(a[0],b[6],c1,c2,c3); + r[6]=c1; + c1=0; + mul_add_c(a[0],b[7],c2,c3,c1); + mul_add_c(a[1],b[6],c2,c3,c1); + mul_add_c(a[2],b[5],c2,c3,c1); + mul_add_c(a[3],b[4],c2,c3,c1); + mul_add_c(a[4],b[3],c2,c3,c1); + mul_add_c(a[5],b[2],c2,c3,c1); + mul_add_c(a[6],b[1],c2,c3,c1); + mul_add_c(a[7],b[0],c2,c3,c1); + r[7]=c2; + c2=0; + mul_add_c(a[7],b[1],c3,c1,c2); + mul_add_c(a[6],b[2],c3,c1,c2); + mul_add_c(a[5],b[3],c3,c1,c2); + mul_add_c(a[4],b[4],c3,c1,c2); + mul_add_c(a[3],b[5],c3,c1,c2); + mul_add_c(a[2],b[6],c3,c1,c2); + mul_add_c(a[1],b[7],c3,c1,c2); + r[8]=c3; + c3=0; + mul_add_c(a[2],b[7],c1,c2,c3); + mul_add_c(a[3],b[6],c1,c2,c3); + mul_add_c(a[4],b[5],c1,c2,c3); + mul_add_c(a[5],b[4],c1,c2,c3); + mul_add_c(a[6],b[3],c1,c2,c3); + mul_add_c(a[7],b[2],c1,c2,c3); + r[9]=c1; + c1=0; + mul_add_c(a[7],b[3],c2,c3,c1); + mul_add_c(a[6],b[4],c2,c3,c1); + mul_add_c(a[5],b[5],c2,c3,c1); + mul_add_c(a[4],b[6],c2,c3,c1); + mul_add_c(a[3],b[7],c2,c3,c1); + r[10]=c2; + c2=0; + mul_add_c(a[4],b[7],c3,c1,c2); + mul_add_c(a[5],b[6],c3,c1,c2); + mul_add_c(a[6],b[5],c3,c1,c2); + mul_add_c(a[7],b[4],c3,c1,c2); + r[11]=c3; + c3=0; + mul_add_c(a[7],b[5],c1,c2,c3); + mul_add_c(a[6],b[6],c1,c2,c3); + mul_add_c(a[5],b[7],c1,c2,c3); + r[12]=c1; + c1=0; + mul_add_c(a[6],b[7],c2,c3,c1); + mul_add_c(a[7],b[6],c2,c3,c1); + r[13]=c2; + c2=0; + mul_add_c(a[7],b[7],c3,c1,c2); + r[14]=c3; + r[15]=c1; + } +#endif + +#ifdef SPLIT_BN_MUL_COMBA4 +#undef bn_mul_comba4 +void bn_mul_comba4(r,a,b) +BN_ULONG *r,*a,*b; + { +#ifdef BN_LLONG + BN_ULLONG t; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + mul_add_c(a[0],b[0],c1,c2,c3); + r[0]=c1; + c1=0; + mul_add_c(a[0],b[1],c2,c3,c1); + mul_add_c(a[1],b[0],c2,c3,c1); + r[1]=c2; + c2=0; + mul_add_c(a[2],b[0],c3,c1,c2); + mul_add_c(a[1],b[1],c3,c1,c2); + mul_add_c(a[0],b[2],c3,c1,c2); + r[2]=c3; + c3=0; + mul_add_c(a[0],b[3],c1,c2,c3); + mul_add_c(a[1],b[2],c1,c2,c3); + mul_add_c(a[2],b[1],c1,c2,c3); + mul_add_c(a[3],b[0],c1,c2,c3); + r[3]=c1; + c1=0; + mul_add_c(a[3],b[1],c2,c3,c1); + mul_add_c(a[2],b[2],c2,c3,c1); + mul_add_c(a[1],b[3],c2,c3,c1); + r[4]=c2; + c2=0; + mul_add_c(a[2],b[3],c3,c1,c2); + mul_add_c(a[3],b[2],c3,c1,c2); + r[5]=c3; + c3=0; + mul_add_c(a[3],b[3],c1,c2,c3); + r[6]=c1; + r[7]=c2; + } +#endif + +#else + +#ifdef SPLIT_BN_MUL_COMBA4 +#undef bn_mul_comba4 +void bn_mul_comba4(r,a,b) +BN_ULONG *r,*a,*b; + { + r[4]=bn_mul_words( &(r[0]),a,4,b[0]); + r[5]=bn_mul_add_words(&(r[1]),a,4,b[1]); + r[6]=bn_mul_add_words(&(r[2]),a,4,b[2]); + r[7]=bn_mul_add_words(&(r[3]),a,4,b[3]); + } +#endif + +#ifdef SPLIT_BN_MUL_COMBA8 +#undef bn_mul_comba8 +void bn_mul_comba8(r,a,b) +BN_ULONG *r,*a,*b; + { + r[ 8]=bn_mul_words( &(r[0]),a,8,b[0]); + r[ 9]=bn_mul_add_words(&(r[1]),a,8,b[1]); + r[10]=bn_mul_add_words(&(r[2]),a,8,b[2]); + r[11]=bn_mul_add_words(&(r[3]),a,8,b[3]); + r[12]=bn_mul_add_words(&(r[4]),a,8,b[4]); + r[13]=bn_mul_add_words(&(r[5]),a,8,b[5]); + r[14]=bn_mul_add_words(&(r[6]),a,8,b[6]); + r[15]=bn_mul_add_words(&(r[7]),a,8,b[7]); + } +#endif + +#endif /* BN_MUL_COMBA */ + +#ifdef BN_SQR_COMBA + +#ifdef SPLIT_BN_SQR_COMBA8 +#undef bn_sqr_comba8 +void bn_sqr_comba8(r,a) +BN_ULONG *r,*a; + { +#ifdef BN_LLONG + BN_ULLONG t,tt; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + sqr_add_c(a,0,c1,c2,c3); + r[0]=c1; + c1=0; + sqr_add_c2(a,1,0,c2,c3,c1); + r[1]=c2; + c2=0; + sqr_add_c(a,1,c3,c1,c2); + sqr_add_c2(a,2,0,c3,c1,c2); + r[2]=c3; + c3=0; + sqr_add_c2(a,3,0,c1,c2,c3); + sqr_add_c2(a,2,1,c1,c2,c3); + r[3]=c1; + c1=0; + sqr_add_c(a,2,c2,c3,c1); + sqr_add_c2(a,3,1,c2,c3,c1); + sqr_add_c2(a,4,0,c2,c3,c1); + r[4]=c2; + c2=0; + sqr_add_c2(a,5,0,c3,c1,c2); + sqr_add_c2(a,4,1,c3,c1,c2); + sqr_add_c2(a,3,2,c3,c1,c2); + r[5]=c3; + c3=0; + sqr_add_c(a,3,c1,c2,c3); + sqr_add_c2(a,4,2,c1,c2,c3); + sqr_add_c2(a,5,1,c1,c2,c3); + sqr_add_c2(a,6,0,c1,c2,c3); + r[6]=c1; + c1=0; + sqr_add_c2(a,7,0,c2,c3,c1); + sqr_add_c2(a,6,1,c2,c3,c1); + sqr_add_c2(a,5,2,c2,c3,c1); + sqr_add_c2(a,4,3,c2,c3,c1); + r[7]=c2; + c2=0; + sqr_add_c(a,4,c3,c1,c2); + sqr_add_c2(a,5,3,c3,c1,c2); + sqr_add_c2(a,6,2,c3,c1,c2); + sqr_add_c2(a,7,1,c3,c1,c2); + r[8]=c3; + c3=0; + sqr_add_c2(a,7,2,c1,c2,c3); + sqr_add_c2(a,6,3,c1,c2,c3); + sqr_add_c2(a,5,4,c1,c2,c3); + r[9]=c1; + c1=0; + sqr_add_c(a,5,c2,c3,c1); + sqr_add_c2(a,6,4,c2,c3,c1); + sqr_add_c2(a,7,3,c2,c3,c1); + r[10]=c2; + c2=0; + sqr_add_c2(a,7,4,c3,c1,c2); + sqr_add_c2(a,6,5,c3,c1,c2); + r[11]=c3; + c3=0; + sqr_add_c(a,6,c1,c2,c3); + sqr_add_c2(a,7,5,c1,c2,c3); + r[12]=c1; + c1=0; + sqr_add_c2(a,7,6,c2,c3,c1); + r[13]=c2; + c2=0; + sqr_add_c(a,7,c3,c1,c2); + r[14]=c3; + r[15]=c1; + } +#endif + +#ifdef SPLIT_BN_SQR_COMBA4 +#undef bn_sqr_comba4 +void bn_sqr_comba4(r,a) +BN_ULONG *r,*a; + { +#ifdef BN_LLONG + BN_ULLONG t,tt; +#else + BN_ULONG bl,bh; +#endif + BN_ULONG t1,t2; + BN_ULONG c1,c2,c3; + + c1=0; + c2=0; + c3=0; + sqr_add_c(a,0,c1,c2,c3); + r[0]=c1; + c1=0; + sqr_add_c2(a,1,0,c2,c3,c1); + r[1]=c2; + c2=0; + sqr_add_c(a,1,c3,c1,c2); + sqr_add_c2(a,2,0,c3,c1,c2); + r[2]=c3; + c3=0; + sqr_add_c2(a,3,0,c1,c2,c3); + sqr_add_c2(a,2,1,c1,c2,c3); + r[3]=c1; + c1=0; + sqr_add_c(a,2,c2,c3,c1); + sqr_add_c2(a,3,1,c2,c3,c1); + r[4]=c2; + c2=0; + sqr_add_c2(a,3,2,c3,c1,c2); + r[5]=c3; + c3=0; + sqr_add_c(a,3,c1,c2,c3); + r[6]=c1; + r[7]=c2; + } +#endif +#else + +#ifdef SPLIT_BN_SQR_COMBA4 +/* hmm... is it faster just to do a multiply? */ +#undef bn_sqr_comba4 +void bn_sqr_comba4(r,a) +BN_ULONG *r,*a; + { + BN_ULONG t[8]; + bn_sqr_normal(r,a,4,t); + } +#endif + +#ifdef SPLIT_BN_SQR_COMBA8 +#undef bn_sqr_comba8 +void bn_sqr_comba8(r,a) +BN_ULONG *r,*a; + { + BN_ULONG t[16]; + bn_sqr_normal(r,a,8,t); + } +#endif + +#endif + +#endif /* OPT_BN_ASM */ + +#endif diff --git a/build/tools/acsign/bn_div.c b/build/tools/acsign/bn_div.c new file mode 100644 index 0000000..d2c1257 --- /dev/null +++ b/build/tools/acsign/bn_div.c @@ -0,0 +1,365 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file bn_div.c + * @brief Division and modulus functions + */ +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_DIV +#define SPLIT_BN_MOD +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_DIV +/* The old slow way */ +#ifdef OLD_BN_DIVISION +int BN_div(dv, rem, m, d,ctx) +BIGNUM *dv; +BIGNUM *rem; +BIGNUM *m; +BIGNUM *d; +BN_CTX *ctx; + { + int i,nm,nd; + BIGNUM *D; + + bn_check_top(m); + bn_check_top(d); + if (BN_is_zero(d)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_DIV,BN_R_DIV_BY_ZERO); +#endif + return(0); + } + + if (BN_ucmp(m,d) < 0) + { + if (rem != NULL) + { if (BN_copy(rem,m) == NULL) return(0); } + if (dv != NULL) BN_zero(dv); + return(1); + } + + D= &(ctx->bn[ctx->tos]); + if (dv == NULL) dv= &(ctx->bn[ctx->tos+1]); + if (rem == NULL) rem= &(ctx->bn[ctx->tos+2]); + + nd=BN_num_bits(d); + nm=BN_num_bits(m); + if (BN_copy(D,d) == NULL) return(0); + if (BN_copy(rem,m) == NULL) return(0); + + /* The next 2 are needed so we can do a dv->d[0]|=1 later + * since BN_lshift1 will only work once there is a value + */ + BN_zero(dv); + bn_wexpand(dv,1); + dv->top=1; + + if (!BN_lshift(D,D,nm-nd)) return(0); + for (i=nm-nd; i>=0; i--) + { + if (!BN_lshift1(dv,dv)) return(0); + if (BN_ucmp(rem,D) >= 0) + { + dv->d[0]|=1; + if (!BN_usub(rem,rem,D)) return(0); + } +/* CAN IMPROVE (and have now :=) */ + if (!BN_rshift1(D,D)) return(0); + } + rem->neg=BN_is_zero(rem)?0:m->neg; + dv->neg=m->neg^d->neg; + return(1); + } + +#else +/** + * Performs Big number division + * + * @param dv [In] division + * @param rm [Out] remainder + * @param num [In] number + * @param divisor [In] divisor + * @param ctx [In] Temporary data storage + * + * @todo add more comments to this function + */ +int BN_div(BIGNUM *dv, BIGNUM *rm, BIGNUM *num, BIGNUM *divisor, BN_CTX *ctx) + { + int norm_shift,i,j,loop; + BIGNUM *tmp,wnum,*snum,*sdiv,*res; + BN_ULONG *resp,*wnump; + BN_ULONG d0,d1; + int num_n,div_n; + + bn_check_top(num); + bn_check_top(divisor); + + if (BN_is_zero(divisor)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_DIV,BN_R_DIV_BY_ZERO); +#endif + return(0); + } + + if (BN_ucmp(num,divisor) < 0) + { + if (rm != NULL) + { if (BN_copy(rm,num) == NULL) return(0); } + if (dv != NULL) (void)BN_zero(dv); + return(1); + } + + tmp= &(ctx->bn[ctx->tos]); + tmp->neg=0; + snum= &(ctx->bn[ctx->tos+1]); + sdiv= &(ctx->bn[ctx->tos+2]); + if (dv == NULL) + res= &(ctx->bn[ctx->tos+3]); + else res=dv; + + /* First we normalise the numbers */ + norm_shift=BN_BITS2-((BN_num_bits(divisor))%BN_BITS2); + if (!BN_lshift(sdiv,divisor,norm_shift)) return(0); + sdiv->neg=0; + norm_shift+=BN_BITS2; + if (!BN_lshift(snum,num,norm_shift)) return(0); + snum->neg=0; + div_n=sdiv->top; + num_n=snum->top; + loop=num_n-div_n; + + /* Lets setup a 'window' into snum + * This is the part that corresponds to the current + * 'area' being divided */ + BN_init(&wnum); + wnum.d= &(snum->d[loop]); + wnum.top= div_n; + wnum.max= snum->max+1; /* a bit of a lie */ + + /* Get the top 2 words of sdiv */ + /* i=sdiv->top; */ + d0=sdiv->d[div_n-1]; + d1=(div_n == 1)?0:sdiv->d[div_n-2]; + + /* pointer to the 'top' of snum */ + wnump= &(snum->d[num_n-1]); + + /* Setup to 'res' */ + if (!bn_wexpand(res,(loop+1))) goto err; + res->neg= (num->neg^divisor->neg); + res->top=loop; + resp= &(res->d[loop-1]); + + /* space for temp */ + if (!bn_wexpand(tmp,(div_n+1))) goto err; + + if (BN_ucmp(&wnum,sdiv) >= 0) + { + if (!BN_usub(&wnum,&wnum,sdiv)) goto err; + *resp=1; + res->d[res->top-1]=1; + } + else + res->top--; + resp--; + + for (i=0; i>BN_BITS2) || + (t2 <= ((BN_ULLONG)(rem< t1l) t3h++; + t3h=(t1h-t3h)&BN_MASK2; + + /*if ((t3>>BN_BITS2) || + (t2 <= ((t3<d,sdiv->d,div_n,q); + tmp->d[div_n]=l0; + for (j=div_n+1; j>0; j--) + if (tmp->d[j-1]) break; + tmp->top=j; + + j=wnum.top; +#ifdef BN_DEBUG + /* Sometimes this is 0 now (wnum.top is not). + * We need to look at this some time, I am quite + * sure it has no affect. + */ + bn_fix_top(&wnum); +#endif + (void)BN_sub(&wnum,&wnum,tmp); + + snum->top=snum->top+wnum.top-j; + + if (wnum.neg) + { + q--; + j=wnum.top; + (void)BN_add(&wnum,&wnum,sdiv); + snum->top+=wnum.top-j; + } + *(resp--)=q; + wnump--; + } + bn_fix_top(snum); + if (rm != NULL) + { + i=num->neg; /* just in case num == rm */ + if (BN_rshift(rm,snum,norm_shift) == 0) + return(0); + rm->neg=i; + } + return(1); +err: + return(0); + } +#endif +#endif + +#ifdef SPLIT_BN_MOD +/** + * Calculate the remainder where rem = m mod d + * + * @param rem [Out] Modulus result + * @param m [In] Base value + * @param d [In] Divisor + * @param ctx [In] BN_CTX for data space + * + * @pre variables are initialised and valid + * @post rem contained modulus + * + * @retval 1 success + * @retval 0 failure + * + * @note when BN_LIBRARY_SMALL define uses following algorithm + * otherwise calls through to BN_div + * + * @note m < d rem = m + * (length m = length of d) and (m > d) , rem = m - d + * alg otherwise + * let rem = m + * loop while rem > d + * let dv = shift left d, n bits to = length rem + * if dv > rem + * let dv = shift left d, n - 1 bits ( = length rem - 1) + * end if + * let rem = rem - dv; + * end loop + * + * @relates BN_div + */ +int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx) +{ +#ifdef BN_LIBRARY_SMALL + int nm,nd; + BIGNUM *dv, *dv2; + + /* if m < d , mod = m */ + if (BN_ucmp(m,d) < 0) + return((BN_copy(rem,m) == NULL)?0:1); + + dv= &(ctx->bn[ctx->tos]); + dv2 = &(ctx->bn[ctx->tos+1]); + + nm=BN_num_bits(m); + nd=BN_num_bits(d); + + /* if bits m = bits d and m >= d (from above) + * rem = m - d + */ + if(nm == nd) + { + BN_usub(rem, m, d); + goto end; + } + + if (BN_copy(rem, m) == NULL) + { + return 0; + } + + /* while the rem > d */ + while(BN_ucmp(rem,d) > 0) + { + nm=BN_num_bits(rem); + if(!BN_lshift(dv2,d,nm-nd)) + { + return(0); + } + + if(BN_ucmp(dv2, rem) >0) + { + if(!BN_lshift(dv2,d,nm-nd-1)) + { + return(0); + } + } + + BN_usub(rem,rem,dv2); + } +end: + return(1); +#else + return(BN_div(NULL,rem,m,d,ctx)); +#endif +} +#endif + +#endif diff --git a/build/tools/acsign/bn_ex_str.c b/build/tools/acsign/bn_ex_str.c new file mode 100644 index 0000000..dc40f5c --- /dev/null +++ b/build/tools/acsign/bn_ex_str.c @@ -0,0 +1,437 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +#include "bn_lcl.h" + +const static unsigned char p2 []={0,8,1,1,1,1,1,0,0,0}; +const static unsigned char p4 []={0,8,1,1,1,4,1,0,0,0}; +const static unsigned char p16[]={0,8,1,1,1,16,1,0,0,0}; + +/* The following defines allow for redefinition of the window size + * of the exponent string at compile time, this affects the size + * of temporary data required in montgomery operations. + * Larger window sizes have more memory and are slightly faster + */ +#ifndef MAX_WIN_SIZE +#define MAX_WIN_SIZE 5 +#endif + +#if (MAX_WIN_SIZE == 6) +#define MAX_NUM_SIZE 16 +#endif + +#if (MAX_WIN_SIZE == 5) +#define MAX_NUM_SIZE 16 +#endif + +#if (MAX_WIN_SIZE == 4) +#define MAX_NUM_SIZE 8 +#endif + +#if (MAX_WIN_SIZE == 3) +#define MAX_NUM_SIZE 4 +#endif + +#ifndef MAX_NUM_SIZE +#define MAX_NUM_SIZE 16 +#endif + +/* This table is used to calculate how far to shift a window to find + * the next 1 bit within the window, for a given window size + * Comment next to each value represents window size, value of the window + * and the number of shifts to find the next 1 bit. + * where the value of the window is 0, the shift is the size of the window + * and thus may not necessary yield a 1 bit, but refreshes the window + */ +const static unsigned char shift[64]= + {6, /* window 6, bits 000000, shift 6 */ + 0, /* 6, bits 000001, shift 0 */ + 1, /* 6, bits 000010, shift 1 */ + 0, /* 6, bits 000011, shift 0 */ + 2, /* 6, bits 000100, shift 2 */ + 0, /* 6, bits 000101, shift 0 */ + 1, /* 6, bits 000110, shift 1 */ + 0, /* 6, bits 000111, shift 0 */ + 3, /* 6, bits 001000, shift 3 */ + 0, /* 6, bits 001001, shift 0 */ + 1, /* 6, bits 001010, shift 1 */ + 0, /* 6, bits 001011, shift 0 */ + 2, /* 6, bits 001100, shift 2 */ + 0, /* 6, bits 001101, shift 0 */ + 1, /* 6, bits 001110, shift 1 */ + 0, /* 6, bits 001111, shift 0 */ + 4, /* 6, bits 010000, shift 4 */ + 0, /* 6, bits 010001, shift 0 */ + 1, /* 6, bits 010010, shift 1 */ + 0, /* 6, bits 010011, shift 0 */ + 2, /* 6, bits 010100, shift 2 */ + 0, /* 6, bits 010101, shift 0 */ + 1, /* 6, bits 010110, shift 1 */ + 0, /* 6, bits 010111, shift 0 */ + 3, /* 6, bits 011000, shift 3 */ + 0, /* 6, bits 011001, shift 0 */ + 1, /* 6, bits 011010, shift 1 */ + 0, /* 6, bits 011011, shift 0 */ + 2, /* 6, bits 011100, shift 2 */ + 0, /* 6, bits 011101, shift 0 */ + 1, /* 6, bits 011110, shift 1 */ + 0, /* 6, bits 011111, shift 0 */ + 5, /* 6, bits 100000, shift 5 */ + /* also window 5, bits 00000, shift 5 */ + 0, /* 5 ,bits 00001, shift 0 */ + 1, /* 5 ,bits 00010, shift 1 */ + 0, /* 5 ,bits 00011, shift 0 */ + 2, /* 5 ,bits 00100, shift 2 */ + 0, /* 5 ,bits 00101, shift 0 */ + 1, /* 5 ,bits 00110, shift 1 */ + 0, /* 5 ,bits 00111, shift 0 */ + 3, /* 5 ,bits 01000, shift 3 */ + 0, /* 5 ,bits 01001, shift 0 */ + 1, /* 5 ,bits 01010, shift 1 */ + 0, /* 5 ,bits 01011, shift 0 */ + 2, /* 5 ,bits 01100, shift 2 */ + 0, /* 5 ,bits 01101, shift 0 */ + 1, /* 5 ,bits 01110, shift 1 */ + 0, /* 5 ,bits 01111, shift 0 */ + 4, /* 5 ,bits 10000, shift 1 */ + /* also window 4, bits 0000, shift 4 */ + 0, /* 4 ,bits 0001, shift 0 */ + 1, /* 4 ,bits 0010, shift 1 */ + 0, /* 4 ,bits 0011, shift 0 */ + 2, /* 4 ,bits 0100, shift 2 */ + 0, /* 4 ,bits 0101, shift 0 */ + 1, /* 4 ,bits 0110, shift 1 */ + 0, /* 4 ,bits 0111, shift 0 */ + 3, /* 4 ,bits 1000, shift 3 */ + /* also window 3, bits 000, shift 3 */ + 0, /* 3 ,bits 001, shift 0 */ + 1, /* 3 ,bits 010, shift 1 */ + 0, /* 3 ,bits 011, shift 0 */ + 2, /* 3 ,bits 100, shift 2 */ + 0, /* 3 ,bits 101, shift 0 */ + 1, /* 3 ,bits 110, shift 1 */ + 0 /* 3 ,bits 111, shift 0 */ + }; + +/* This table defines the starting point in the shift table for + * a particular window size + */ +const static unsigned char *shift_val[7]= + { + &(shift[63]), /* window 0 - unused */ + &(shift[62]), /* window 1 */ + &(shift[60]), /* window 2 - unused */ + &(shift[56]), /* window 3 */ + &(shift[48]), /* window 4 */ + &(shift[32]), /* window 5 */ + &(shift[ 0]), /* window 6 - unused */ + }; + +/** + * Calculates a Montgomery exponent string. + * + * For a supplied exponent p, generate an exponent string strp, which + * defines in pairs the number of multiplies and square operations + * required by a particular bit pattern, commonly used exponents + * 3, 11 and F4 have predefined constant string values, the rest + * are calculated into a cast unsigned char * array via the data + * pointer of a BIGNUM taken from the BN_CTX stack of BIGNUMs + * + * @param p [In] Exponent + * @param strp [Out] Exponent string result + * @param flags [In] Unused + * @param ctx [In] Temporary data storage + * + * @pre p, and ctx are initialised and valid + * @post strp points to required exponent string + * + * @notes String length value in strp[2] is invalid for strings + * greater than length 255 + * string terminates with pattern, 0, 0 this should be + * used in accurately determining the length of a returned + * string strp. + * + * @note strings with value sqr = 255, mul = 0, sqr value should be + * treated as value 256, and added to the next sqr value, this + * is used by exponent strings where more then 256 contiguous + * zero bits are in the exponent bit representation. + * + * @note code contains conditional compilation of code dependent on + * the OS int/long sizes + */ +int BN_gen_exp_bits(p,strp,flags,ctx) +BIGNUM *p; +unsigned char **strp; +int flags; +BN_CTX *ctx; + { + int bits,i,j,window,num; + unsigned char *str=NULL; + BIGNUM *tmp; + + flags=flags; + bits=p->top*BN_BITS2; + tmp=&(ctx->bn[ctx->tos]); + if (p->top == 0) + return(0); + +#if (BN_BITS2 > 17) + if (p->top == 1) +#else + if (bits <= 32) +#endif + { +#if (BN_BITS2 > 17) + if ((p->top == 1) && (p->d[0] == 0x10001)) + str=(unsigned char *)p16; +#endif +#if (16 >= BN_BITS2) && (BN_BITS > 8) + if ( (p->top == 2) && + (p->d[0] == 0x0001) && + (p->d[1] == 0x0001)) + str=(unsigned char *)p16; +#endif +#if (8 >= BN_BITS) + if ( (p->top == 3) && + (p->d[0] == 0x01) && + (p->d[1] == 0x00) && + (p->d[2] == 0x01)) + str=(unsigned char *)p16; +#endif + else if ((p->d[0] == 0x11) && (p->top == 1)) + str=(unsigned char *)p4; + else if ((p->d[0] == 0x3) && (p->top == 1)) + str=(unsigned char *)p2; + window=1; + num=1; + i=BN_BITS2; + } + else if (bits >= 256) + { + window=MAX_WIN_SIZE; /* max size of window */ + num=MAX_NUM_SIZE; + i=(BN_BITS2+(MAX_WIN_SIZE -1))/MAX_WIN_SIZE; + } + else if (bits >= 128) + { + window=4; + num=8; + i=(BN_BITS2+3)/4; + } + else /* 128 to 33 */ + { + window=3; + num=4; + i=(BN_BITS2+2)/3; + } + + /* Number of tmp words */ + j=(p->top*i*2+BN_BYTES-1+4)/BN_BYTES; + + if (str == NULL) + { + if (!bn_wexpand(tmp,j)) + return(0); + str=(unsigned char *)tmp->d; + i=BN_gen_exp_string(&(str[4]),p,window); + i+=2; + str[0]=(unsigned char)((i>>8)&0xff); + str[1]=(unsigned char)((i )&0xff); + str[2]=(unsigned char)window; + str[3]=(unsigned char)num; + } + else + { + i=8; + } + *strp=str; + return(i+2); + } + + +/** + * Generates the Montgomery exponent string. + * + * This function is used to generate an 'exponent string' + * which is an array of bytes that encode how to perform the steps in + * the a^p%m operation. + * + * @param str [Out] Containing the generated string + * @param p [In] Exponent to generate the string for + * @param bits [In] Size of the window for shifting the values of the BIGNUM + * + * @pre p is initialised and value BIGNUM, bits is not 0 + * @post str points to generated exponent string + * + * @note str is cast assigned the data of a BIGNUM allocated and + * expanded from the BN_CTX of the calling function BN_gen_exp_bits + * it does not need to be de-allocated + * + * @note string consisted of unsigned char pairs and 4 byte init + * pairs are sqr count and multiply, where strings are greater + * than 256 bit, length in position str[2] is invalid + * + * @note strings with value sqr = 255, mul = 0, sqr value should be + * treated as value 256, and added to the next sqr value, this + * is used by exponent strings where more then 256 contiguous + * zero bits are in the exponent bit representation. + * + */ +int BN_gen_exp_string(str,p,bits) +unsigned char *str; +BIGNUM *p; +int bits; + { + unsigned char *sp; + unsigned int mask; + const unsigned char *shift; + BN_ULONG w,wh,wl,*d; + unsigned int i,mul,sqr,t,s,ss; + int top; + + if (bits > 6) bits=6; + shift= shift_val[bits]; + + /* This is the mask for the bits we wish to operate on */ + mask=(1<top*BN_BITS2+bits-1)/bits)*2+2]); + *sp-- = 0; + *sp-- = 0; + top=p->top; /* Total words we will shift in */ + d=p->d; + w=wl= *d++; + if (top <= 1) + wh=0; + else + wh= *d++; + sqr=0; + i=0; + + for (;;) + { + /* t will contain how far we need to shift to set a 1 + * in the bottom bit. */ + for (;;) + { + t=w&mask; /* retrieve our window */ + s=shift[t]; /* get the shift value for the window */ + if (s == 0) break; /* no shift write out the vals */ + sqr+=s; /* add the shifted zero count to sqr */ + ss+=s; /* ss is total shift for wl */ + if (ss >= BN_BITS2) /* we have shifted > word len */ + { + if (top <= 1) break; /* no more to do */ + top--; /* dec the count */ + + wl=wh; /* copy the next word */ + /* load the word after or 0 if no more */ + wh=(top <= 1)?0:(*d++); + /* adjust our shift by len of word */ + ss-=BN_BITS2; + } + /* reset our window word w */ + if (ss == 0) + w=wl; + else + w=(wl>>ss)|(wh<<(BN_BITS2-ss)); + } + + /* At this point we have the 0th bit set */ + mul=t; + if (t == 0) break; /* we have reached the end of p */ + /* write out sqr/mul pair */ + *sp-- = (unsigned char)(sqr & 0xff); + *sp-- = (unsigned char)(mul & 0xff); + if(sqr >= 256) /* check whether sqr exceeds max uchar */ + { + /* output the expanded list of to allow for this + * and numbers will require to be added together + * at interpret time + */ + while(sqr >= 256) + { + *sp-- = 255; + *sp-- = 0; /* mul is never zero normally */ + sqr-= 256; + } + } + sqr=bits; /* set sqr to be the window size */ + + ss+=bits; /* ss is total shift for wl */ + if (ss >= BN_BITS2) /* adjust window words w,wl, wh again */ + { + if (top <= 1) break; + top--; + + wl=wh; + wh=(top <= 1)?0:(*(d++)); + ss-=BN_BITS2; + } + + if (ss == 0) + w=wl; + else + w=(wl>>ss)|(wh<<(BN_BITS2-ss)); + } + sp++; + i=2; + /* reverse the string from the top of the exponent string + * and copy to the bottom, allocated exponent string is 2 * max length + * expected for exponent string + */ + while (sp[0] != 0 || sp[1] != 0) + { + str[0]=sp[0]; + str[1]=sp[1]; + str+=2; + sp+=2; + i+=2; + } + str[0]=0; + str[1]=0; + + return(i); + } + +#ifdef MAIN +main() + { + BIGNUM p; + unsigned char buf[512],*pp; + int i; + + BN_init(&p); + BN_rand(&p,33,1,0); +#ifndef NO_FP_API + BN_print_fp(stdout,&p); fprintf(stdout,"\n"); +#endif + + BN_rand(&p,512,1,1); +#ifndef NO_FP_API + BN_print_fp(stdout,&p); fprintf(stdout,"\n"); +#endif + for (i=0; i<10000; i++) + BN_gen_exp_string(buf,&p,5); + +#if 0 + BN_gen_exp_string(buf,&p,3); + + pp=buf; + for (;;) + { + printf("mul %d sqr %d\n",pp[0],pp[1]); + if (pp[1] == 0) break; + pp+=2; + } +#endif + } +#endif diff --git a/build/tools/acsign/bn_exp.c b/build/tools/acsign/bn_exp.c new file mode 100644 index 0000000..08634e7 --- /dev/null +++ b/build/tools/acsign/bn_exp.c @@ -0,0 +1,156 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MOD_EXP_ORIG +#define SPLIT_BN_MOD_EXP +#endif /* NO_SPLIT */ + +#define TABLE_SIZE 16 + +#ifdef SPLIT_BN_MOD_EXP_ORIG +#if 0 +/* this one works - simple but works */ +int BN_mod_exp_orig(r,a,p,m,ctx) +BIGNUM *r,*a,*p,*m; +BN_CTX *ctx; + { + int i,bits,ret=0; + BIGNUM *v,*tmp; + + v= &(ctx->bn[ctx->tos++]); + tmp= &(ctx->bn[ctx->tos++]); + + if (BN_copy(v,a) == NULL) goto err; + bits=BN_num_bits(p); + + if (BN_is_odd(p)) + { if (BN_copy(r,a) == NULL) goto err; } + else { if (!BN_one(r)) goto err; } + + for (i=1; itos-=2; + return(ret); + } + +#endif + +/* this one works - simple but works */ +int BN_exp(r,a,p,ctx) +BIGNUM *r,*a,*p; +BN_CTX *ctx; + { + int i,bits,ret=0,tos; + BIGNUM *v,*rr; + + bn_check_top(a); + bn_check_top(p); + + tos=ctx->tos; + v= &(ctx->bn[ctx->tos++]); + if ((r == a) || (r == p)) + rr= &(ctx->bn[ctx->tos++]); + else + rr=r; + + if (BN_copy(v,a) == NULL) goto err; + bits=BN_num_bits(p); + + if (BN_is_odd(p)) + { if (BN_copy(rr,a) == NULL) goto err; } + else { if (!BN_one(rr)) goto err; } + + for (i=1; itos=tos; + if (r != rr) (void)BN_copy(r,rr); + return(ret); + } +#endif + +#ifdef SPLIT_BN_MOD_EXP +/** + * Perform mod exp on BIGNUM + * @param r Pointer to return value BIGNUM + * @param a Pointer to data value BIGNUM + * @param p Pointer to Public exponent BIGNUM + * @param m Pointer to modulus BIGNUM + * @param ctx Pointer to BN_CTX + * @return 0 success + * @pre BIGNUMs a, p, m and BN_CTX ctx exist and are valid + * @post BIGNUM r points to evaluated mod_exp + * @note BN_mod_exp_mont is only available if library compiled + * with define BN_MONT_MUL, and will only be used to compute + * mod_exp operation where the modulus m is odd. + * BN_mod_exp_recp is only available if library is compiled + * with define RECP_MUL_MOD. + * BN_mod_exp_simple is the default method, not available if + * library is compiled with define RECP_MUL_MOD. + * if BN_mod_exp_mont is available, which ever of BN_mod_exp_simple + * or BN_mod_exp_recp is available will only be used for even + * modulus m values. + * @relates BN_mod_exp_mont + * @relates BN_mod_exp_recp + * @relates BN_mod_exp_simple + */ +int BN_mod_exp(r,a,p,m,ctx) +BIGNUM *r; +BIGNUM *a; +BIGNUM *p; +BIGNUM *m; +BN_CTX *ctx; + { + int ret; + + bn_check_top(a); + bn_check_top(p); + bn_check_top(m); + +#ifdef MONT_MUL_MOD + + if (BN_is_odd(m)) + { ret=BN_mod_exp_mont(r,a,p,m,ctx,NULL); } + else +#endif +#ifdef RECP_MUL_MOD + { ret=BN_mod_exp_recp(r,a,p,m,ctx); } +#else + { ret=BN_mod_exp_simple(r,a,p,m,ctx); } +#endif + + return(ret); + } +#endif + +#endif diff --git a/build/tools/acsign/bn_fm_w.c b/build/tools/acsign/bn_fm_w.c new file mode 100644 index 0000000..999ed55 --- /dev/null +++ b/build/tools/acsign/bn_fm_w.c @@ -0,0 +1,63 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +#include "bn_lcl.h" + +/* rp has w words, the top w words are 0 */ +void bn_from_montgomery_words(ret,a,np,w,n0) +BN_ULONG *ret; +BN_ULONG *a; +BN_ULONG *np; +int w; +BN_ULONG n0; + { + BN_ULONG v0,v1,*ap,*wap; + int i; + + v1=0; + + ap=a; + wap= &(a[w]); + /* Consider putting this loop in ASM */ + for (i=0; i0; i--) + if (ap[i] != np[i]) break; + } + v1=(ap[i] >= np[i]); + } + if (v1) + (void)bn_sub_words(ret,ap,np,w); + else + { +#if 0 /* Alpha does not like Memcpy */ + Memcpy(ret,ap,sizeof(BN_ULONG)*w); +#else + for (i=0; ibn[ctx->tos]); + b= &(ctx->bn[ctx->tos+1]); + + if (BN_copy(a,in_a) == NULL) goto err; + if (BN_copy(b,in_b) == NULL) goto err; + + if (BN_cmp(a,b) < 0) { t=a; a=b; b=t; } + t=bn_euclid(a,b); + if (t == NULL) goto err; + + if (BN_copy(r,t) == NULL) goto err; + ret=1; +err: + return(ret); + } + +BIGNUM *bn_euclid(a,b) +BIGNUM *a,*b; + { + BIGNUM *t; + int shifts=0; + + bn_check_top(a); + bn_check_top(b); + + for (;;) + { + if (BN_is_zero(b)) + break; + + if (BN_is_odd(a)) + { + if (BN_is_odd(b)) + { + if (!BN_sub(a,a,b)) goto err; + if (!BN_rshift1(a,a)) goto err; + if (BN_cmp(a,b) < 0) + { t=a; a=b; b=t; } + } + else /* a odd - b even */ + { + if (!BN_rshift1(b,b)) goto err; + if (BN_cmp(a,b) < 0) + { t=a; a=b; b=t; } + } + } + else /* a is even */ + { + if (BN_is_odd(b)) + { + if (!BN_rshift1(a,a)) goto err; + if (BN_cmp(a,b) < 0) + { t=a; a=b; b=t; } + } + else /* a even - b even */ + { + if (!BN_rshift1(a,a)) goto err; + if (!BN_rshift1(b,b)) goto err; + shifts++; + } + } + } + if (shifts) + { + if (!BN_lshift(a,a,shifts)) goto err; + } + return(a); +err: + return(NULL); + } +#endif + +#ifdef SPLIT_BN_MOD_INVERSE +/* solves ax == 1 (mod n) */ +BIGNUM *BN_mod_inverse(in, a, n, ctx) +BIGNUM *in; +BIGNUM *a; +BIGNUM *n; +BN_CTX *ctx; + { + BIGNUM *A,*B,*X,*Y,*M,*D,*R; + BIGNUM *T,*ret=NULL; + int sign; + + bn_check_top(a); + bn_check_top(n); + + A= &(ctx->bn[ctx->tos]); + B= &(ctx->bn[ctx->tos+1]); + X= &(ctx->bn[ctx->tos+2]); + D= &(ctx->bn[ctx->tos+3]); + M= &(ctx->bn[ctx->tos+4]); + Y= &(ctx->bn[ctx->tos+5]); + ctx->tos+=6; + if (in == NULL) + R=BN_new(); + else + R=in; + if (R == NULL) goto err; + + (void)BN_zero(X); + (void)BN_one(Y); + if (BN_copy(A,a) == NULL) goto err; + if (BN_copy(B,n) == NULL) goto err; + sign=1; + + while (!BN_is_zero(B)) + { + if (!BN_div(D,M,A,B,ctx)) goto err; + T=A; + A=B; + B=M; + /* T has a struct, M does not */ + + if (!BN_mul(T,D,X,ctx)) goto err; + if (!BN_add(T,T,Y)) goto err; + M=Y; + Y=X; + X=T; + sign= -sign; + } + if (sign < 0) + { + if (!BN_sub(Y,n,Y)) goto err; + } + + if (BN_is_one(A)) + { if (!BN_mod(R,Y,n,ctx)) goto err; } + else + { +#ifndef NO_ERR + BNerr(BN_F_BN_MOD_INVERSE,BN_R_NO_INVERSE); +#endif + goto err; + } + ret=R; +err: + if ((ret == NULL) && (in == NULL)) BN_free(R); + ctx->tos-=6; + return(ret); + } +#endif + +#ifdef SPLIT_BN_MOD_INVERSE_WORD +/* solves 1 == (ret*(1<l + * @param l [In] a word (size of word depends on machine) + * @returns number of bits in parameter l + */ +#ifdef SPLIT_BN_NUM_BITS_WORD +int BN_num_bits_word(l) +BN_ILONG l; + { + int i; + + /* + * This table represents the number of bits required to + * represent a "number", where "number" is indexed from + * 0 into the table. So: + * number 0 = # bits req'd to represent 0 = bits[0] = 0 + * number 1 = # bits req'd to represent 1 = bits[1] = 1 + * number 2 = # bits req'd to represent 2 = bits[2] = 2 + * number 3 = # bits req'd to represent 3 = bits[3] = 2 + * number 4 = # bits req'd to represent 4 = bits[4] = 3 + * etc. + * + * The small code size table exists to save some space, + * but requires (at most) an extra shift, an extra AND, + * and an extra add. + */ +#ifdef SMALL_CODE_SIZE + const static char bits[16]={ + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 + }; +#else + const static char bits[256]={ + 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + }; +#endif + +#if defined(SIXTY_FOUR_BIT_LONG) + if (l & 0xffffffff00000000L) + { + if (l & 0xffff000000000000L) + { + if (l & 0xff00000000000000L) + i=56; + else i=48; + } + else + { + if (l & 0x0000ff0000000000L) + i=40; + else i=32; + } + } + else +#else +#ifdef SIXTY_FOUR_BIT + if (l & 0xffffffff00000000LL) + { + if (l & 0xffff000000000000LL) + { + if (l & 0xff00000000000000LL) + i=56; + else i=48; + } + else + { + if (l & 0x0000ff0000000000LL) + i=40; + else i=32; + } + } + else +#endif +#endif + { +#if defined(THIRTY_BIT) || defined(THIRTY_ONE_BIT) || defined(THIRTY_TWO_BIT) || defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) + if (l & 0xffff0000L) + { + if (l & 0xff000000L) + i=24; + else i=16; + } + else +#endif + { + if (l & 0xff00L) + i=8; + else + i=0; + } + } +#ifndef SMALL_CODE_SIZE + return(i+bits[l>>i]); +#else + l>>=i; + if (l & 0xf0) + return(bits[l>>4]+i+4); + else + return(bits[l]+i); +#endif + } +#endif + +#ifdef SPLIT_BN_NUM_BITS +int BN_num_bits(a) +BIGNUM *a; + { + BN_ULONG l; + int i; + + bn_check_top(a); + + if (a->top == 0) return(0); + l=a->d[a->top-1]; + i=(a->top-1)*BN_BITS2; +#ifdef BN_DEBUG + if (l == 0) + { +#if !defined(NO_FP_API) && !defined(WIN16) + fprintf(stderr,"BAD TOP VALUE\n"); +#endif + abort(); /* BN_DEBUG */ + /* TODO: need to understand what sort of error can + * be reported for this error + */ + return(0); + } +#endif + return(i+BN_num_bits_word(l)); + } +#endif + +/** + * Clears and free a BIGNUM + * + * @param a [In] BIGNUM to clear then free + */ +#ifdef SPLIT_BN_CLEAR_FREE +void BN_clear_free(BIGNUM *a) +{ + if (a == NULL) + { + return; + } + + BN_clear(a); + BN_free(a); +} +#endif + +#ifdef SPLIT_BN_FREE +/** + * Frees a BIGNUM + * + * @param a [In] BIGNUM to free + */ +void BN_free(a) +BIGNUM *a; + { + if (a == NULL) return; + if ((a->d != NULL) && !(BN_get_flags(a,BN_FLG_STATIC_DATA))) + Free(a->d); + a->flags|=BN_FLG_FREE; /* REMOVE? */ + if (a->flags & BN_FLG_MALLOCED) + Free(a); + } +#endif + +#ifdef SPLIT_BN_INIT + +#ifdef SMALL_CODE_SIZE +/** + * Zero expands a bignum + * + * @param a [In] BIGNUM to expand + * @param n [In] number of bits to expand to + * + * @pre a is a valid BIGNUM. + */ +void bn_zexpand(a,n) +BIGNUM *a; +int n; + { + if ((a)->top < n) + { + int i; + bn_wexpand((a),n); + if (a->d!=NULL) + { + for (i=(a)->top; id[i]=0; + } + } + } + +/** + * Fixes the top value in the BIGNUM to be the count of BN_ULONGs with data. + * + * @param a [In] BIGNUM to free + * + * @pre a is a valid BIGNUM. + */ +void bn_fix_top(a) +BIGNUM *a; + { + BN_ULONG *ftl; + if ((a)->top > 0) + { + for (ftl= &((a)->d[(a)->top-1]); (a)->top > 0; (a)->top--) + if (*(ftl--)) break; + } + } +#endif + +/** + * Initializes a BIGNUM + * + * @param a [In] BIGNUM reference + * + * @pre a is a valid BIGNUM. + */ +void BN_init(a) +BIGNUM *a; + { + (void)Memset(a,0,sizeof(BIGNUM)); + } +#endif + +#ifdef SPLIT_BN_NEW +/** + * Allocates a BIGNUM + * + * @return pointer to allocated BIGNUM + */ +BIGNUM *BN_new() + { + BIGNUM *ret; + + if ((ret=(BIGNUM *)Malloc(sizeof(BIGNUM))) == NULL) + { +#ifndef NO_ERR + BNerr(BN_F_BN_NEW,ERR_R_MALLOC_FAILURE); +#endif + return(NULL); + } + ret->flags=BN_FLG_MALLOCED; + ret->top=0; + ret->neg=0; + ret->max=0; + ret->d=NULL; + return(ret); + } +#endif + +#ifdef SPLIT_BN_CTX_NEW +/** + * Allocates a BIGNUM context + * + * @return pointer to allocated BIGNUM context + */ +BN_CTX *BN_CTX_new() + { + BN_CTX *ret; + + ret=(BN_CTX *)Malloc(sizeof(BN_CTX)); + if (ret == NULL) + { +#ifndef NO_ERR + BNerr(BN_F_BN_CTX_NEW,ERR_R_MALLOC_FAILURE); +#endif + return(NULL); + } + + BN_CTX_init(ret); + ret->flags=BN_FLG_MALLOCED; + return(ret); + } +#endif + +#ifdef SPLIT_CTX_INIT +/** + * Initializes a BIGNUM context + * + * @param a [In] BIGNUM context reference + * + * @pre a is a valid BIGNUM context. + */ +void BN_CTX_init(ctx) +BN_CTX *ctx; + { + (void)Memset(ctx,0,sizeof(BN_CTX)); + ctx->tos=0; + ctx->flags=0; + } +#endif + +#ifdef SPLIT_BN_CTX_FREE +/** + * Frees a BIGNUM context + * + * @param a [In] BIGNUM context reference + * + * @pre a is a valid BIGNUM context. + */ +void BN_CTX_free(c) +BN_CTX *c; + { + int i; + + for (i=0; ibn[i])); + if (c->flags & BN_FLG_MALLOCED) + Free(c); + } +#endif + +#ifdef SPLIT_BN_EXPAND2 +BIGNUM *bn_expand2(b, words) +BIGNUM *b; +int words; + { + BN_ULONG *A,*B,*a; + + R_DIAG_CHECK_STACK; + + bn_check_top(b); + + if (words > b->max) + { + bn_check_top(b); + if (BN_get_flags(b,BN_FLG_STATIC_DATA)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_EXPAND2,BN_R_EXPAND_ON_STATIC_BIGNUM_DATA); +#endif + return(NULL); + } + a=A=(BN_ULONG *)Malloc(sizeof(BN_ULONG)*(words+1)); + if (A == NULL) + { +#ifndef NO_ERR + BNerr(BN_F_BN_EXPAND2,ERR_R_MALLOC_FAILURE); +#endif + return(NULL); + } + /* during development this is a nice way of making sure + * that we are not relying on the top byte being 0 or + * other such things + */ +#ifdef BN_DEBUG + (void)Memset(A,0x5c,sizeof(BN_ULONG)*(words+1)); +#endif + + B=b->d; + if (B != NULL) + { +#ifndef SMALL_CODE_SIZE + int i; + + /* for (i=b->top&(~7); i>0; i-=8) */ + /* The above line can induce a SunC compiler bug */ + for (i=(b->top>>3); i>0; i--) + { + BN_ULONG T0,T1,T2,T3; + + T0=B[0]; + T1=B[1]; + T2=B[2]; + T3=B[3]; + A[0]=T0; + A[1]=T1; + A[2]=T2; + A[3]=T3; + T0=B[4]; + T1=B[5]; + T2=B[6]; + T3=B[7]; + A[4]=T0; + A[5]=T1; + A[6]=T2; + A[7]=T3; + A+=8; + B+=8; + } + switch (b->top&7) + { + case 7: + A[6]=B[6]; + case 6: + A[5]=B[5]; + case 5: + A[4]=B[4]; + case 4: + A[3]=B[3]; + case 3: + A[2]=B[2]; + case 2: + A[1]=B[1]; + case 1: + A[0]=B[0]; + case 0: + /* I need the 'case 0' entry for utrix cc. + * If the optimiser is turned on, it does the + * switch table by doing + * a=top&7 + * a--; + * goto jump_table[a]; + * If top is 0, this makes us jump to 0xffffffc + * which is rather bad. + * eric 23-Apr-1998 + */ + ; + } +#if 0 /* Not needed */ + B= &(b->d[b->top]); + j=b->max-8; + for (i=b->top; itop); +#endif + Free(b->d); + } + + b->d=a; + b->max=words; + } + return(b); + } +#endif + +#ifdef SPLIT_BN_DUP +/** + * Duplicates a BIGNUM + * + * @param a [In] BIGNUM reference + * + * @returns pointer to duplicate BIGNUM of a + */ +BIGNUM *BN_dup(a) +BIGNUM *a; + { + BIGNUM *r; + BIGNUM *ret; + + bn_check_top(a); + + r=BN_new(); + if (r == NULL) return(NULL); + ret = (BIGNUM *)BN_copy(r,a); + if (ret == NULL) + { + BN_free(r); + } + return(ret); + } +#endif + +#ifdef SPLIT_BN_COPY +/** + * Copies a BIGNUM to an existing BIGNUM + * + * @param a [In] To BIGNUM reference + * @param b [Out] From BIGNUM reference + * + * @pre Both a and b are valid BIGNUMs + * + * @returns pointer to duplicate BIGNUM of a + */ +BIGNUM *BN_copy(a, b) +BIGNUM *a; +BIGNUM *b; + { +#ifndef SMALL_CODE_SIZE + int i; + BN_ULONG *A,*B; +#endif + + bn_check_top(b); + + if (a == b) return(a); + if (bn_wexpand(a,b->top) == NULL) return(NULL); +#ifndef SMALL_CODE_SIZE + A=a->d; + B=b->d; + +/* for (i=b->top&~0x07; i>0; i-=8) */ +/* The above version of this loop has been removed. It appeared + to generate a compiler bug in SunC 4.x and 5.x. I do not believe + that the code was to blame. Compiling with -fast was the problem + since this would loop unroll the loop below another 3 times. + The compiler would generate generate + andcc %o0,-8,%o1 # load ~0x07 + ld [%i2],%o3 # load *B + ble .L77000125 # exit loop unless 8 or more + ld [%i1],%o2 # load *A + sub %o1,-7,%o0 # + sdivcc %o0,8,%o0 # when do we clear %y? + bvs,a .L900001510 + sethi %hi(0x80000000),%o0 +.L900001510: + cmp %o0,3 + bl .L77000114 # one loop + ld [%o2],%o0 + # three loop code + + The loop would then be unrolled 3 times. The problem I believe + I was seeing was that the sdivcc operates is %y:%o0 / 8. + %y is not being cleared, and so occasionally this would + cause problems. The replacement code sequence stops + the compiler generating the sdiv instruction. + */ + for (i=(b->top>>3); i>0; i--) + { + BN_ULONG T0,T1,T2,T3; + T0=B[0]; + T1=B[1]; + T2=B[2]; + T3=B[3]; + A[0]=T0; + A[1]=T1; + A[2]=T2; + A[3]=T3; + T0=B[4]; + T1=B[5]; + T2=B[6]; + T3=B[7]; + A[4]=T0; + A[5]=T1; + A[6]=T2; + A[7]=T3; + A+=8; + B+=8; + } + switch (b->top&0x07) + { + case 7: + A[6]=B[6]; + case 6: + A[5]=B[5]; + case 5: + A[4]=B[4]; + case 4: + A[3]=B[3]; + case 3: + A[2]=B[2]; + case 2: + A[1]=B[1]; + case 1: + A[0]=B[0]; + case 0: + /* I need the 'case 0' entry for utrix cc. + * If the optimiser is turned on, it does the + * switch table by doing + * a=top&7 + * a--; + * goto jump_table[a]; + * If top is 0, this makes us jump to 0xffffffc which is + * rather bad. + * eric 23-Apr-1998 + */ + ; + } +#else + (void)Memcpy(a->d,b->d,sizeof(b->d[0])*b->top); +#endif + +/* (void)Memset(&(a->d[b->top]),0,sizeof(a->d[0])*(a->max-b->top));*/ + a->top=b->top; + if ((a->top == 0) && (a->d != NULL)) + a->d[0]=0; + a->neg=b->neg; + return(a); + } +#endif + +#ifdef SPLIT_BN_CLEAR +/** + * Clears a BIGNUM + * + * @param a [In] BIGNUM to clear + * + * @pre a is valid + */ +void BN_clear(a) +BIGNUM *a; + { + if (a->d != NULL) + (void)Memset(a->d,0,a->max*sizeof(a->d[0])); + a->top=0; + a->neg=0; + } +#endif + +#ifdef SPLIT_BN_GET_WORD +BN_ULONG BN_get_word(a) +BIGNUM *a; + { + int i,n; + BN_ULONG ret=0; + + n=BN_num_bytes(a); + if (n > ((int) sizeof(BN_ULONG))) + return(BN_MASK2); + for (i=a->top-1; i>=0; i--) + { +#ifndef SIXTY_FOUR_BIT /* the data item > unsigned long */ + ret<<=BN_BITS4; /* stops the compiler complaining */ + ret<<=BN_BITS4; +#else + ret=0; +#endif + ret|=a->d[i]; + } + return(ret); + } +#endif + +#ifdef SPLIT_BN_SET_WORD +/** + * Set the BIGNUM to the supplied BN_ULONG value. + * + * @param a [In/Out] BIGNUM to be updated + * @param w [In] Value to be set in a + * + * @notes Function will expand a to be an + * array of 8 BN_ULONGs in size. + * @todo Review behaviour of expansion without checking + * of size first. + */ +int BN_set_word(a,w) +BIGNUM *a; +BN_ULONG w; + { + int i,n; + + if (bn_expand(a,(int)(sizeof(BN_ULONG)*8)) == NULL) return(0); + +#ifdef BN_BYTES + /* This is used when a BN_ULONG is greater in size + * than the BN_BYTES of the array, eg BN_ULONG 64 bits + * and actual a->d array of 32 bits. + */ + n=sizeof(BN_ULONG)/BN_BYTES; +#else + n=1; +#endif + a->neg=0; + a->top=0; + a->d[0]=(BN_ULONG)w&BN_MASK2; + if (a->d[0] != 0) a->top=1; + for (i=1; i>=BN_BITS2 so compilers don't complain + * on builds where sizeof(long) == BN_TYPES */ +#ifndef SIXTY_FOUR_BIT /* the data item > unsigned long */ + w>>=BN_BITS4; + w>>=BN_BITS4; +#else + w=0; +#endif + a->d[i]=(BN_ULONG)w&BN_MASK2; + if (a->d[i] != 0) a->top=i+1; + } + return(1); + } +#endif + +#ifdef BN_BYTES +#ifdef SPLIT_BN_BIN2BN +/* ignore negative */ +BIGNUM *BN_bin2bn(s, len, ret) +unsigned char *s; +int len; +BIGNUM *ret; + { + unsigned int i,m; + unsigned int n; + BN_ULONG l; + + if (ret == NULL) ret=BN_new(); + if (ret == NULL) return(NULL); + l=0; + n=len; + if (n == 0) + { + ret->top=0; + return(ret); + } + if (bn_expand(ret,(int)(n+2)*8) == NULL) + return(NULL); + i=((n-1)/BN_BYTES)+1; + m=((n-1)%(BN_BYTES)); + ret->top=i; + while (n-- > 0) + { + l=(l<<8L)| *(s++); + if (m-- == 0) + { + ret->d[--i]=l; + l=0; + m=BN_BYTES-1; + } + } + /* need to call this due to clear byte at top if avoiding + * having the top bit set (-ve number) */ + bn_fix_top(ret); + return(ret); + } +#endif + +#ifdef SPLIT_BN_BN2BIN +/* ignore negative */ +int BN_bn2bin(a, to) +BIGNUM *a; +unsigned char *to; + { + int n,i; + BN_ULONG l; + + bn_check_top(a); + + n=i=BN_num_bytes(a); + while (i-- > 0) + { + l=a->d[i/BN_BYTES]; + *(to++)=(unsigned char)((l>>(8*(i%BN_BYTES)))&0xff); + } + return(n); + } +#endif +#else +#ifdef SPLIT_BN_BIN2BN +/* ignore negative */ +BIGNUM *BN_bin2bn(s, len, ret) +unsigned char *s; +int len; +BIGNUM *ret; + { + int i,w,r,b,j,v; + int n; + BN_ULONG l; + + if (ret == NULL) ret=BN_new(); + if (ret == NULL) return(NULL); + while (len > 0) + { + if (*s != 0) break; + s++; + len--; + } + n=len*8; + if (bn_expand(ret,n) == NULL) + return(NULL); + for (i=0; imax; i++) + ret->d[i]=0; + j=0; + for (i=len-1; i>=0; i--) + { + v=((int)s[i])&0xff; + w=j/BN_BITS2; + b=j%BN_BITS2; + r=BN_BITS2-b; + j+=8; + if (r >= 8) + { + ret->d[w]|=(((BN_ULONG)v)<d[w] =(ret->d[w]|(((BN_ULONG)v)<d[w+1]=(ret->d[w+1]|(((BN_ULONG)v)>>r)); + } + } + + ret->top=((n-1)/BN_BITS2)+1; + bn_fix_top(ret); + return(ret); + } +#endif + +#ifdef SPLIT_BN_BN2BIN +int BN_bn2bin(a, to) +BIGNUM *a; +unsigned char *to; + { + int num,i,bi,w,b,r,max; + BN_ULONG l,*lp; + + bn_check_top(a); + + num=bi=BN_num_bytes(a); + lp=a->d; + for (i=0; i= 8) + to[bi]=(lp[w]>>b)&0xff; + else + { + to[bi]=(lp[w]>>b); + if (w+1 < a->top) + to[bi]|=lp[w+1]<top-b->top; + if (i != 0) return(i); + ap=a->d; + bp=b->d; + for (i=a->top-1; i>=0; i--) + { + t1= ap[i]; + t2= bp[i]; + if (t1 != t2) + return(t1 > t2?1:-1); + } + return(0); + } +#endif + +#ifdef SPLIT_BN_CMP +int BN_cmp(a, b) +BIGNUM *a; +BIGNUM *b; + { + int i; + int gt,lt; + BN_ULONG t1,t2; + + if ((a == NULL) || (b == NULL)) + { + if (a != NULL) + return(-1); + else if (b != NULL) + return(1); + else + return(0); + } + + bn_check_top(a); + bn_check_top(b); + + if (a->neg != b->neg) + { + if (a->neg) + return(-1); + else return(1); + } + if (a->neg == 0) + { gt=1; lt= -1; } + else { gt= -1; lt=1; } + + if (a->top > b->top) return(gt); + if (a->top < b->top) return(lt); + for (i=a->top-1; i>=0; i--) + { + t1=a->d[i]; + t2=b->d[i]; + if (t1 > t2) return(gt); + if (t1 < t2) return(lt); + } + return(0); + } +#endif + +#ifdef SPLIT_BN_SET_BIT +int BN_set_bit(a, n) +BIGNUM *a; +int n; + { + int i,j,k; + + bn_check_top(a); + + i=n/BN_BITS2; + j=n%BN_BITS2; + if (a->top <= i) + { + if (bn_wexpand(a,i+1) == NULL) return(0); + for(k=a->top; kd[k]=0; + a->top=i+1; + } + + a->d[i]|=(((BN_ULONG)1)<top <= i) return(0); + + a->d[i]&=(~(((BN_ULONG)1)<top <= i) return(0); + return((a->d[i]&(((BN_ULONG)1)<= a->top) return(0); + if (b == 0) + a->top=w; + else + { + a->top=w+1; + a->d[w]&= ~(((BN_ULONG)BN_MASK2)< bb)?1:-1); + for (i=n-2; i>=0; i--) + { + aa=a[i]; + bb=b[i]; + if (aa != bb) return((aa > bb)?1:-1); + } + return(0); + } +#endif +#endif + diff --git a/build/tools/acsign/bn_lsh.c b/build/tools/acsign/bn_lsh.c new file mode 100644 index 0000000..133b33e --- /dev/null +++ b/build/tools/acsign/bn_lsh.c @@ -0,0 +1,112 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_LSHIFT1 +#define SPLIT_BN_LSHIFT +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_LSHIFT1 +#ifdef SMALL_CODE_SIZE + +int BN_lshift1(r, a) +BIGNUM *r,*a; + { + return(BN_lshift(r, a, 1)); + } + +#else + +int BN_lshift1(r, a) +BIGNUM *r; +BIGNUM *a; + { + register BN_ULONG *ap,*rp,t,c; + int i; + + bn_check_top(a); + + if (r != a) + { + if (bn_wexpand(r,a->top+1) == NULL) return(0); + r->neg=a->neg; + r->top=a->top; + } + else + { + if (bn_wexpand(r,a->top+1) == NULL) return(0); + } + ap=a->d; + rp=r->d; + c=0; + for (i=0; itop; i++) + { + t= *(ap++); + *(rp++)=((t<<1L)|c)&BN_MASK2; + c=(t & BN_TBIT)?1:0; + } + if (c) + { + *rp=1; + r->top++; + } + return(1); + } +#endif +#endif + +#ifdef SPLIT_BN_LSHIFT +int BN_lshift(r, a, n) +BIGNUM *r; +BIGNUM *a; +int n; + { + int i,nw,lb,rb; + BN_ULONG *t,*f; + BN_ULONG l; + + bn_check_top(a); + +#ifndef SMALL_CODE_SIZE + if (n == 1) return(BN_lshift1(r,a)); +#endif + if (bn_wexpand(r,a->top+(n/BN_BITS2)+1) == NULL) return(0); + r->neg=a->neg; + nw=n/BN_BITS2; + lb=n%BN_BITS2; + rb=BN_BITS2-lb; + f=a->d; + t=r->d; + t[a->top+nw]=0; + if (lb == 0) + for (i=a->top-1; i>=0; i--) + t[nw+i]=f[i]; + else + for (i=a->top-1; i>=0; i--) + { + l=f[i]; + t[nw+i+1]|=(l>>rb)&BN_MASK2; + t[nw+i]=(l<top=a->top+nw+1; + bn_fix_top(r); + return(1); + } +#endif + +#endif diff --git a/build/tools/acsign/bn_m_exp.c b/build/tools/acsign/bn_m_exp.c new file mode 100644 index 0000000..8d8afe9 --- /dev/null +++ b/build/tools/acsign/bn_m_exp.c @@ -0,0 +1,283 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#if 0 //RSA +#include +#endif +#include "bn_lcl.h" + +/* #ifdef MONT_MUL_MOD */ +/** + * Generic form of Montgomery Exponentiation, can be called directly + * out side of a BN_ME_METH + * + * @param rr_in BIGNUM pointer for result + * @param a_in BIGNUM pointer for base + * @param p BIGNUM pointer to the exponent + * @param m BIGNUM pointer to the modulus + * @param ctx BN_CTX pointer for temp values are argument storage + * @param in_mont BN_MONT_CTX pointer to structure of montgomery values + * + * @pre arguments are all initialised and not NULL or zero + * @post rr_in contains evaluated result + * + * @note + */ +int BN_mod_exp_mont(rr_in,a_in,p,m,ctx,in_mont) +BIGNUM *rr_in; +BIGNUM *a_in; +BIGNUM *p; +BIGNUM *m; +BN_CTX *ctx; +BN_MONT_CTX *in_mont; + { + int i,j,k,ret=0,tos,top; + int mul,sqr,num; + BIGNUM *d,*aa,*r,*a,*t; + BN_ULONG *vall[BN_EXP_TABLE_SIZE],*dp,*rp,n0,*rr,*tmp,*np; + BN_MONT_CTX *mont=NULL; + unsigned char *str=NULL; +#ifdef BN_SURRENDER + R_SURRENDER *surrender=NULL; + int count=0; +#endif + + bn_check_top(a_in); + bn_check_top(p); + bn_check_top(m); + + if (!(m->d[0] & 1)) + { +#ifndef NO_ERR + BNerr(BN_F_BN_MOD_EXP_MONT,BN_R_CALLED_WITH_EVEN_MODULUS); +#endif + return(0); + } + + tos=ctx->tos; + + if (BN_is_zero(a_in)) + { (void)BN_zero(rr_in); return(1); } + if (BN_is_zero(p)) + { (void)BN_one(rr_in); return(1); } + if (BN_is_one(p)) + { (void)BN_copy(rr_in,a_in); return(1); } + + /* If this is not done, things will break in the montgomery + * part */ + +#if 1 + if (in_mont != NULL) + mont=in_mont; + else +#endif + { + if ((mont=BN_MONT_CTX_new()) == NULL) goto err; + if (!BN_MONT_CTX_set(mont,m,ctx)) goto err; + } + +#ifdef BN_SURRENDER + surrender=ctx->surrender; +#endif + + if (!BN_gen_exp_bits(p,&str,0,ctx)) goto err; + /* Remember this function uses another element from the passed ctx */ + ctx->tos++; + num=str[3]; + i=(BN_BITS+str[2]-1)/str[2]; + str+=4; + + + top=mont->N.top; + if ((a_in->top == top) && (a_in->d[top-1] < m->d[top-1])) + { + a=a_in; + } + else if (a_in->top < top) + { + a= &(ctx->bn[ctx->tos++]); + a->top=a_in->top; + bn_zexpand(a,top); + for (j=0; jtop; j++) + a->d[j]=a_in->d[j]; + } + else /* if (a_in->top > i) */ + { + a= &(ctx->bn[ctx->tos++]); + if (!BN_mod(a,a_in,m,ctx)) goto err; + bn_zexpand(a,top); + } + + /* At this point a is the size of the modulus and is 0 padded + * out to its size if needed. + */ + + /* Number of tmp words */ + k=num*top; + j=k+(p->top*i*2+BN_BYTES-1+4)/BN_BYTES; + + aa=&(ctx->bn[ctx->tos++]); + d= &(ctx->bn[ctx->tos++]); + r= &(ctx->bn[ctx->tos++]); + t= &(ctx->bn[ctx->tos++]); + + if (bn_wexpand(rr_in,top) == NULL) goto err; + if (bn_wexpand(d,top*4) == NULL) goto err; /* *2? */ + if (bn_wexpand(r,top*2) == NULL) goto err; + if (bn_wexpand(aa,j) == NULL) goto err; + if (bn_wexpand(t,top*2) == NULL) goto err; + dp=d->d; + rp=r->d; + tmp=t->d; + rr=mont->RR.d; + + n0=mont->n0; + np=mont->N.d; + + vall[0]=aa->d; + + bn_mul_normal(tmp,a->d,top,rr,top); + bn_from_montgomery_words(vall[0],tmp,np,top,n0); + + if (num > 1) + { + bn_sqr_normal(tmp,vall[0],top,dp); + bn_from_montgomery_words(dp,tmp,np,top,n0); + + for (i=1; i>1],sizeof(BN_ULONG)*top); + while (sqr != 0) + { +#ifdef BN_SURRENDER + /* + * Check this at the start of the loop rather than the + * end so we avoid as many of the bn operations as possible + */ + if (surrender != NULL) + { + if (surrender->callback(surrender,0xff, count++) != 0) + { + goto err; + } + } +#endif /* BN_SURRENDER */ + + /* + * check the abort flag at the start of the loop so we avoid + * as many of the bn operations as possible + */ + if (BN_CTX_get_flags(ctx, BN_CTX_FLG_ABORT)) + { + goto err; + } + + for (i=0; i>1],top); + bn_from_montgomery_words(rp,tmp,np,top,n0); + } + else + { + bn_mul_normal(tmp,rp,top,a->d,top); + bn_from_montgomery_words(rr_in->d,tmp,np,top,n0); + goto end; + } + } + + /* if (mul != 1) */ + { + for (i=top; id,rp,np,top,n0); + } +end: /* Use this to avoid an if */ + + /* + * Even if the operation has completed successfully, if the + * abort flag is set we want to abort so that anything + * calling this function will know not to continue. + */ + if (BN_CTX_get_flags(ctx, BN_CTX_FLG_ABORT)) + { + goto err; + } + + rr_in->top=top; + bn_fix_top(rr_in); + ret=1; +err: +#ifdef BN_SURRENDER + /* + * Even if the operation completed successfully we want to abort + * if the abort flag has been is set, so that subsequent operations + * do not continue. Allow the caller change to return value and + * cause the function to fail. + */ + if (surrender != NULL) + { + if (surrender->callback(surrender, 0xff, -1) != 0) + { + ret = 0; + } + } +#endif + if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); + ctx->tos=tos; + return(ret); + } +/* #endif */ + diff --git a/build/tools/acsign/bn_me.c b/build/tools/acsign/bn_me.c new file mode 100644 index 0000000..250967c --- /dev/null +++ b/build/tools/acsign/bn_me.c @@ -0,0 +1,251 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file bn_me.c + * @brief BN method functions and utilities + */ +#include "bn_lcl.h" +#include "bn_thx.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MOD_EXP_METH_DEFAULT +#define SPLIT_BN_MONT_CTX_USEIT +#define SPLIT_BN_ME_CTX_NAME +#define SPLIT_BN_ME_CTX_NEW +#define SPLIT_BN_ME_CTX_FREE +#define SPLIT_BN_ME_CTX_SET +#define SPLIT_BN_ME_CTX_MOD_EXP +#endif /* NO_SPLIT */ + +#ifndef NOPROTO +BN_ME_METH *bn_mod_exp_meth_default(int fallback); +#else +BN_ME_METH *bn_mod_exp_meth_default(); +#endif + +#ifdef SPLIT_BN_MOD_EXP_METH_DEFAULT + +/** + * Returns the default mod_exp method, choose first available in the + * method table or a hardwired default + * + * @param fallback [In] Flag for choice of method + * - 0 use the first value in the method table + * - 1 use the all encompassing default method + * + * @pre BN_default_init() has been run setting up library + * + * @post + * + * @internal uses global table bnme[] and counter me_num + * + * @internal only read the BN_ME_METH_INFO table no need for locking + * + * @relates BN_library_init + * @relates BN_default_init + * @relates BN_ME_CTX_new + * @relates BN_ME_CTX_free + * + */ +BN_ME_METH *bn_mod_exp_meth_default(int fallback) +{ + const BN_ME_METH *tmp; + +#ifndef BN_LIBRARY_SMALL + BN_ME_METH_INFO *meth_info; + + if(!fallback && ((meth_info = BN_bnme_get_info(0)) != NULL)) + { + tmp = meth_info->meth(); + } + else +#endif + { + /* set in bn.h or override bn_thx.h */ + tmp = BN_ME_METH_DEFAULT(); + } + return((BN_ME_METH *)tmp); +} +#endif + +#ifdef SPLIT_BN_MONT_CTX_USEIT + +#ifndef NOPROTO +int bn_mont_ctx_useit(int argi); +#else +int bn_mont_ctx_useit(); +#endif + +/** + * Montgomery method default useit function + * + * @param argi [In] reserved for future use + * + * @return 0 success + */ +int bn_mont_ctx_useit(int argi) + { + return(0); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_NAME +/** + * Retrieve the BN method name string + * + * @param ctx [In] Method + * + * @pre ctx is valid and not NULL + * + * @return string pointer + */ +char *BN_ME_CTX_name(BN_ME_CTX *ctx) + { + return(ctx->meth->name); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_NEW +/** + * Allocate a new BN_ME_CTX structure and assign method + * + * @param meth [In] Method to assign + * @param in [Out] Result BN_ME_CTX + * + * @note if meth is NULL system method default is used + * + * @retval pointer to BN_ME_CTX success + * @retval NULL failure + */ +BN_ME_CTX *BN_ME_CTX_new(BN_ME_METH *meth, BN_ME_CTX **in) + { + int i; + BN_ME_CTX *ret; + + if (in == NULL) + in= &ret; + + if (meth == NULL) + meth=bn_mod_exp_meth_default(0); + i=meth->init_ctx(meth,in); + if (i) + return(NULL); + else + return(*in); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_FREE +/** + * Free context method + * + * @param mctx [In] Context object to be deallocated + * + * @note it is the callers responsibility to set mctx to NULL after free + * + * @pre mctx is not NULL and is valide BN_ME_CTX + */ +void BN_ME_CTX_free(BN_ME_CTX *mctx) + { + mctx->meth->free_ctx(mctx); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_SET +/** + * Set value to BN_ME_CTX by identifier + * + * @param mctx [In] Method context object + * @param b [In] Big number + * @param cmd [In] Command identifier + * @param flags [In] Mask operation directives + * @param ctx [In] BN data store + * + * @note cmd values: + * @li BN_ME_SET_MOD will cause a method lookup is method not set + * + * @note passes control to set method in mctx + * + * @return result of mctx method set operation + */ +int BN_ME_CTX_set(BN_ME_CTX *mctx, BIGNUM *b, int cmd, int flags, BN_CTX *ctx) + { +#ifndef BN_LIBRARY_SMALL +#ifndef NOPROTO + const BN_ME_METH *(*meth)(void); +#else + const BN_ME_METH *(*meth)(); +#endif +#endif /* BN_LIBRARY_SMALL */ + + /* If we are loading the modulus, and we do not have the + * no_lookup flag (without a null method) + */ + if ((cmd == BN_ME_SET_MOD) && + ((mctx->meth != NULL) && !(flags & BN_ME_SET_FLG_NO_LOOKUP))) + { +#ifndef BN_LIBRARY_SMALL + meth=(const BN_ME_METH*(*)(void)) + BN_bnme_get(BN_num_bits(b),BN_BNME_F_BITS); + if (meth != NULL) + mctx->meth=meth(); + else +#endif + mctx->meth=bn_mod_exp_meth_default(1); + } + return(mctx->meth->set(mctx,b,cmd,flags,ctx)); + } +#endif + +#ifdef SPLIT_BN_ME_CTX_MOD_EXP +/** + * Call method mod_exp operation + * + * @param mctx [In] Method context object + * @param ret [Out] Result + * @param a [In] Base value + * @param p [In] Exponent + * @param m [In] Modulus + * @param ctx [In] Data storage + * + * @pre a must be expandable + * + * @return 0 success + */ +int BN_ME_CTX_mod_exp(BN_ME_CTX *mctx, BIGNUM *ret, BIGNUM *a, BIGNUM *p, + BIGNUM *m, BN_CTX *ctx) + { + int wtop; + + /* Before we call the method, make sure we are not doing 0^p, + * and p is not 0 or 1 */ + if (BN_is_zero(a)) + { BN_zero(ret); return(0); } + if (p != NULL) + { + if (BN_is_zero(p)) + { BN_one(ret); return(0); } + else if (BN_is_one(p)) + { BN_copy(ret,a); return(0); } + } + + /* wtop is the size 'a' needs to be for the method */ + wtop=mctx->meth->num; + bn_zexpand(a,wtop); + + return(mctx->meth->mod_exp(mctx,ret,a,p,ctx)); + } +#endif + +#endif + diff --git a/build/tools/acsign/bn_mont.c b/build/tools/acsign/bn_mont.c new file mode 100644 index 0000000..6fc5fea --- /dev/null +++ b/build/tools/acsign/bn_mont.c @@ -0,0 +1,231 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#undef BN_DEBUG +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MOD_MUL_MONTGOMERY +#define SPLIT_BN_FROM_MONTGOMERY +#define SPLIT_BN_MONT_CTX_NEW +#define SPLIT_BN_MONT_CTX_INIT +#define SPLIT_BN_MONT_CTX_FREE +#define SPLIT_BN_MONT_CTX_COPY +#endif /* NO_SPLIT */ + +/* #define DEBUG */ + +#ifdef SPLIT_BN_MOD_MUL_MONTGOMERY +/* We multiply a by b, generating a number 2n words long. + * This is then reduced by the montogmery number, which is + * n words. */ +int BN_mod_mul_montgomery(r,a,b,mont,ctx) +BIGNUM *r,*a,*b; +BN_MONT_CTX *mont; +BN_CTX *ctx; + { + BIGNUM *tmp,*tmp2; + int ret=0,w; + int i; + + bn_check_top(a); + bn_check_top(b); + + w=mont->riw; + + tmp= &(ctx->bn[ctx->tos++]); + tmp2= &(ctx->bn[ctx->tos++]); + bn_check_top(tmp); + bn_check_top(tmp2); + if (bn_wexpand(tmp,w+w) == NULL) goto err; + if (bn_wexpand(r,w+w) == NULL) goto err; + + if (a == b) + { + if (bn_wexpand(tmp2,w+w) == NULL) goto err; +#ifdef BN_SQR_COMBA + if ((a->top == 8) && (a->top == b->top)) + bn_sqr_comba8(tmp->d,a->d); + else +#endif + { + bn_sqr_normal(tmp->d,a->d,a->top,tmp2->d); + } + } + else + { +#ifdef BN_MUL_COMBA + if (a->top == 8) + bn_mul_comba8(tmp->d,a->d,b->d); + else +#endif + { + bn_mul_normal(tmp->d,a->d,a->top,b->d,b->top); + } + } + + i=a->top+b->top; + while (i<(w+w)) + { + tmp->d[i]=0; + i++; + } + tmp->top=w+w; + tmp->neg=0; + + /* reduce from aRR to aR */ + /* tmp->d is 2w words */ +#if 0 + bn_fix_top(tmp); + BN_from_montgomery_words(r,tmp,mont,ctx); +#else + bn_from_montgomery_words(r->d,tmp->d,mont->N.d,w,mont->n0); +#endif + r->top=w; + r->neg=0; + bn_fix_top(r); + + ret=1; +err: + ctx->tos-=2; + return(ret); + } +#endif + +#ifdef SPLIT_BN_FROM_MONTGOMERY +int BN_from_montgomery(ret,a,mont,ctx) +BIGNUM *ret; +BIGNUM *a; +BN_MONT_CTX *mont; +BN_CTX *ctx; + { + BIGNUM *n,*r; + BN_ULONG *np,*rp,n0,v0,v1,*nrp; + int al,nl,max,i; + int retn=0; + + bn_check_top(a); + + r= &(ctx->bn[ctx->tos]); + + if (!BN_copy(r,a)) goto err1; + n= &(mont->N); + + /* mont->riw is the size of mont->N in bits/words */ + al=mont->riw; + + nl=n->top; + if ((al == 0) || (nl == 0)) { r->top=0; return(1); } + + max=(nl+al+1); /* allow for overflow (no?) XXX */ + if (bn_wexpand(r,max) == NULL) goto err1; + if (bn_wexpand(ret,max) == NULL) goto err1; + + r->neg=a->neg^n->neg; + np=n->d; + rp=r->d; + nrp= &(r->d[nl]); + + /* clear the top words of T */ + for (i=r->top; id[i]=0; + + r->top=max; + n0=mont->n0; + + v1=0; + for (i=0; iriw will be a multiple of the word size */ + (void)BN_rshift(ret,r,mont->riw*BN_BITS2); + + if (BN_ucmp(ret, &(mont->N)) >= 0) + { + (void)BN_usub(ret,ret,&(mont->N)); /* XXX */ + } + retn=1; + +err1: + return(retn); + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_NEW +BN_MONT_CTX *BN_MONT_CTX_new() + { + BN_MONT_CTX *ret; + + if ((ret=(BN_MONT_CTX *)Malloc(sizeof(BN_MONT_CTX))) == NULL) + return(NULL); + + BN_MONT_CTX_init(ret); + ret->flags=BN_FLG_MALLOCED; + return(ret); + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_INIT +void BN_MONT_CTX_init(ctx) +BN_MONT_CTX *ctx; + { + ctx->use_word=0; + ctx->riw=0; + BN_init(&(ctx->RR)); + BN_init(&(ctx->N)); + BN_init(&(ctx->Ni)); + ctx->flags=0; + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_FREE +void BN_MONT_CTX_free(mont) +BN_MONT_CTX *mont; + { + BN_free(&(mont->RR)); + BN_free(&(mont->N)); + BN_free(&(mont->Ni)); + if (mont->flags & BN_FLG_MALLOCED) + Free(mont); + } +#endif + +#ifdef SPLIT_BN_MONT_CTX_COPY +BN_MONT_CTX *BN_MONT_CTX_copy(to, from) +BN_MONT_CTX *to, *from; + { + if (to == from) return(to); + + (void)BN_copy(&(to->RR),&(from->RR)); + (void)BN_copy(&(to->N),&(from->N)); + (void)BN_copy(&(to->Ni),&(from->Ni)); + bn_zexpand(&(to->RR),from->riw); + bn_zexpand(&(to->Ni),from->riw); + to->use_word=from->use_word; + to->riw=from->riw; + to->n0=from->n0; + return(to); + } +#endif + +#endif diff --git a/build/tools/acsign/bn_ms_w.c b/build/tools/acsign/bn_ms_w.c new file mode 100644 index 0000000..1ddd40e --- /dev/null +++ b/build/tools/acsign/bn_ms_w.c @@ -0,0 +1,121 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +int BN_MONT_CTX_set_word(mont,mod,ctx) +BN_MONT_CTX *mont; +BIGNUM *mod; +BN_CTX *ctx; + { + BIGNUM Ri,*R; +#if 1 + BN_ULONG tmod,rr; +#else + BN_ULONG buf[2]; + BIGNUM tmod; +#endif + + + bn_check_top(mod); + if (mod->top == 0) return(0); + + R= &(mont->RR); /* grab RR as a temp */ + if (BN_copy(&(mont->N),mod) == NULL) /* Set N */ + return(0); + + BN_init(&Ri); + + mont->use_word=1; + +/* EAY is this number of words to shift, or the number to shift to end up + * with a '1' in the next word? + * for 8 bit words, is 0x01ab == 1 or 2 + */ + mont->riw=(BN_num_bits(mod)+(BN_BITS2-1))/BN_BITS2; + if (!BN_zero(R)) return(0); + + /* We are now setting a number which is larger than our current + * one after we do the shift + */ + if (!BN_set_bit(R,BN_BITS2)) + goto err; + +#if 0 + tmod.d=buf; + tmod.top=1; + tmod.max=mod->max; + tmod.neg=mod->neg; + buf[0]=mod->d[0]&BN_MASK2; + buf[1]=0; + + if ((BN_mod_inverse(&Ri,R,&tmod,ctx)) == NULL) + goto err; +#else + tmod=mod->d[0]; + rr=BN_mod_inverse_word(tmod); + if (!BN_set_word(&Ri,rr)) + goto err; +#endif + + /* R*Ri */ + if (!BN_lshift(&Ri,&Ri,BN_BITS2)) + goto err; + + if (!BN_is_zero(&Ri)) + (void)BN_sub_word(&Ri,1); + else + { + /* This is not common..., 1 in BN_MASK2, + * It happens when buf[0] was == 1. So for 8 bit, + * this is 1/256, 16bit, 1 in 2^16 etc. + */ + if (!BN_set_word(&Ri,BN_MASK2)) + goto err; + } +#if 0 + BN_div(&Ri,NULL,&Ri,&tmod,ctx); + //BN_div_word(&Ri,tmod); + mont->n0=Ri.d[0]; +#else +#if 0 + { + BN_ULONG h,l; + + h=l=0; + if (Ri.top >= 2) h=Ri.d[1]; + if (Ri.top >= 1) l=Ri.d[0]; + mont->n0=bn_div_words(h,l,tmod); + } +#endif + mont->n0=bn_div_words( + (Ri.top >= 2)?Ri.d[1]:0, + (Ri.top >= 1)?Ri.d[0]:0, + tmod); +#endif + /* mod->top=z; */ + + /* setup RR for conversions */ + (void)BN_zero(&(mont->RR)); + if (!BN_set_bit(&(mont->RR),mont->riw*2*BN_BITS2)) + goto err; + (void)BN_mod(&(mont->RR),&(mont->RR),&(mont->N),ctx); + bn_zexpand(&(mont->RR),mont->riw); +#if 0 + bn_zexpand(&(mont->Ni),mont->riw); /*This is not used? */ +#endif + +err: + BN_free(&Ri); + return(1); + } + + diff --git a/build/tools/acsign/bn_mul.c b/build/tools/acsign/bn_mul.c new file mode 100644 index 0000000..4dd0e23 --- /dev/null +++ b/build/tools/acsign/bn_mul.c @@ -0,0 +1,779 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_MUL_RECURSIVE +#define SPLIT_BN_MUL_PART_RECURSIVE +#define SPLIT_BN_MUL_LOW_RECURSIVE +#define SPLIT_BN_MUL_HIGH +#define SPLIT_BN_MUL +#define SPLIT_BN_MUL_NORMAL +#define SPLIT_BN_MUL_LOW_NORMAL +#endif /* NO_SPLIT */ + +#ifdef SMALL_CODE_SIZE +#undef BN_RECURSION_MUL +#endif + +#ifdef BN_RECURSION_MUL +#if 0 /* Replaced by bn_mul_rec_words() */ +/* r is 2*n2 words in size, + * a and b are both n2 words in size. + * n2 must be a power of 2. + * We multiply and return the result. + * t must be 2*n2 words in size + * We calulate + * a[0]*b[0] + * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) + * a[1]*b[1] + */ +#ifdef SPLIT_BN_MUL_RECURSIVE +void bn_mul_recursive(r,a,b,n2,t) +BN_ULONG *r,*a,*b; +int n2; +BN_ULONG *t; + { + int n=n2/2,c1,c2; + unsigned int neg,zero; + BN_ULONG ln,lo,*p; + +#ifdef BN_COUNT +printf(" bn_mul_recursive %d * %d\n",n2,n2); +#endif +#ifdef BN_MUL_COMBA +/* if (n2 == 4) + { + bn_mul_comba4(r,a,b); + return; + } + else */ if (n2 == 8) + { + bn_mul_comba8(r,a,b); + return; + } +#endif + if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) + { + /* This should not happen */ + bn_mul_normal(r,a,n2,b,n2); + return; + } + /* r=(a[0]-a[1])*(b[1]-b[0]) */ + c1=bn_cmp_words(a,&(a[n]),n); + c2=bn_cmp_words(&(b[n]),b,n); + zero=neg=0; + switch (c1*3+c2) + { + case -4: + bn_sub_words(t, &(a[n]),a, n); /* - */ + bn_sub_words(&(t[n]),b, &(b[n]),n); /* - */ + break; + case -3: + zero=1; + break; + case -2: + bn_sub_words(t, &(a[n]),a, n); /* - */ + bn_sub_words(&(t[n]),&(b[n]),b, n); /* + */ + neg=1; + break; + case -1: + case 0: + case 1: + zero=1; + break; + case 2: + bn_sub_words(t, a, &(a[n]),n); /* + */ + bn_sub_words(&(t[n]),b, &(b[n]),n); /* - */ + neg=1; + break; + case 3: + zero=1; + break; + case 4: + bn_sub_words(t, a, &(a[n]),n); + bn_sub_words(&(t[n]),&(b[n]),b, n); + break; + } + +#ifdef BN_MUL_COMBA + if (n == 4) + { + if (!zero) + bn_mul_comba4(&(t[n2]),t,&(t[n])); + else + Memset(&(t[n2]),0,8*sizeof(BN_ULONG)); + + bn_mul_comba4(r,a,b); + bn_mul_comba4(&(r[n2]),&(a[n]),&(b[n])); + } + else if (n == 8) + { + if (!zero) + bn_mul_comba8(&(t[n2]),t,&(t[n])); + else + Memset(&(t[n2]),0,16*sizeof(BN_ULONG)); + + bn_mul_comba8(r,a,b); + bn_mul_comba8(&(r[n2]),&(a[n]),&(b[n])); + } + else +#endif + { + p= &(t[n2*2]); + if (!zero) + bn_mul_recursive(&(t[n2]),t,&(t[n]),n,p); + else + Memset(&(t[n2]),0,n2*sizeof(BN_ULONG)); + bn_mul_recursive(r,a,b,n,p); + bn_mul_recursive(&(r[n2]),&(a[n]),&(b[n]),n,p); + } + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1=(int)bn_add_words(t,r,&(r[n2]),n2); + + if (neg) /* if t[32] is negative */ + { + c1-=(int)bn_sub_words(&(t[n2]),t,&(t[n2]),n2); + } + else + { + /* Might have a carry */ + c1+=(int)bn_add_words(&(t[n2]),&(t[n2]),t,n2); + } + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + * c1 holds the carry bits + */ + c1+=(int)bn_add_words(&(r[n]),&(r[n]),&(t[n2]),n2); + if (c1) + { + p= &(r[n+n2]); + lo= *p; + ln=(lo+c1)&BN_MASK2; + *p=ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if (ln < (BN_ULONG)c1) + { + do { + p++; + lo= *p; + ln=(lo+1)&BN_MASK2; + *p=ln; + } while (ln == 0); + } + } + } +#endif +#endif + +#if 0 +#ifdef SPLIT_BN_MUL_PART_RECURSIVE +/* n+tn is the word length + * t must be n*4 is size, as does r */ +void bn_mul_part_recursive(r,a,b,tn,n,t) +BN_ULONG *r,*a,*b; +int tn,n; +BN_ULONG *t; + { + int i,j,n2=n*2; + int c1; + BN_ULONG ln,lo,*p; + +#ifdef BN_COUNT +printf(" bn_mul_part_recursive %d * %d\n",tn+n,tn+n); +#endif + if (n < 8) + { + i=tn+n; + bn_mul_normal(r,a,i,b,i); + return; + } + + /* r=(a[0]-a[1])*(b[1]-b[0]) */ + bn_sub_words(t, a, &(a[n]),n); /* + */ + bn_sub_words(&(t[n]),b, &(b[n]),n); /* - */ + +#ifdef BN_MUL_COMBA +/* if (n == 4) + { + bn_mul_comba4(&(t[n2]),t,&(t[n])); + bn_mul_comba4(r,a,b); + bn_mul_normal(&(r[n2]),&(a[n]),tn,&(b[n]),tn); + Memset(&(r[n2+tn*2]),0,sizeof(BN_ULONG)*(n2-tn*2)); + } + else */ if (n == 8) + { + bn_mul_comba8(&(t[n2]),t,&(t[n])); + bn_mul_comba8(r,a,b); + bn_mul_normal(&(r[n2]),&(a[n]),tn,&(b[n]),tn); + Memset(&(r[n2+tn*2]),0,sizeof(BN_ULONG)*(n2-tn*2)); + } + else +#endif + { + p= &(t[n2*2]); + bn_mul_recursive(&(t[n2]),t,&(t[n]),n,p); + bn_mul_recursive(r,a,b,n,p); + i=n/2; + /* If there is only a bottom half to the number, + * just do it */ + j=tn-i; + if (j == 0) + { + bn_mul_recursive(&(r[n2]),&(a[n]),&(b[n]),i,p); + Memset(&(r[n2+i*2]),0,sizeof(BN_ULONG)*(n2-i*2)); + } + else if (j > 0) /* eg, n == 16, i == 8 and tn == 11 */ + { + bn_mul_part_recursive(&(r[n2]),&(a[n]),&(b[n]), + j,i,p); + Memset(&(r[n2+tn*2]),0, + sizeof(BN_ULONG)*(n2-tn*2)); + } + else /* (j < 0) eg, n == 16, i == 8 and tn == 5 */ + { + Memset(&(r[n2]),0,sizeof(BN_ULONG)*n2); + if (tn < BN_MUL_RECURSIVE_SIZE_NORMAL) + { + bn_mul_normal(&(r[n2]),&(a[n]),tn,&(b[n]),tn); + } + else + { + for (;;) + { + i/=2; + if (i < tn) + { + bn_mul_part_recursive(&(r[n2]), + &(a[n]),&(b[n]), + tn-i,i,p); + break; + } + else if (i == tn) + { + bn_mul_recursive(&(r[n2]), + &(a[n]),&(b[n]), + i,p); + break; + } + } + } + } + } + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1=(int)bn_add_words(t,r,&(r[n2]),n2); + c1-=(int)bn_sub_words(&(t[n2]),t,&(t[n2]),n2); + + /* t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + * c1 holds the carry bits + */ + c1+=(int)bn_add_words(&(r[n]),&(r[n]),&(t[n2]),n2); + if (c1) + { + p= &(r[n+n2]); + lo= *p; + ln=(lo+c1)&BN_MASK2; + *p=ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if (ln < (BN_ULONG)c1) + { + do { + p++; + lo= *p; + ln=(lo+1)&BN_MASK2; + *p=ln; + } while (ln == 0); + } + } + } +#endif +#endif + +#if 0 +#ifdef SPLIT_BN_MUL_LOW_RECURSIVE +/* a and b must be the same size, which is n2. + * r must be n2 words and t must be n2*2 + */ +void bn_mul_low_recursive(r,a,b,n2,t) +BN_ULONG *r,*a,*b; +int n2; +BN_ULONG *t; + { + int n=n2/2; + +#ifdef BN_COUNT +printf(" bn_mul_low_recursive %d * %d\n",n2,n2); +#endif + + bn_mul_recursive(r,a,b,n,&(t[0])); + if (n >= BN_MUL_LOW_RECURSIVE_SIZE_NORMAL) + { + bn_mul_low_recursive(&(t[0]),&(a[0]),&(b[n]),n,&(t[n2])); + bn_add_words(&(r[n]),&(r[n]),&(t[0]),n); + bn_mul_low_recursive(&(t[0]),&(a[n]),&(b[0]),n,&(t[n2])); + bn_add_words(&(r[n]),&(r[n]),&(t[0]),n); + } + else + { + bn_mul_low_normal(&(t[0]),&(a[0]),&(b[n]),n); + bn_mul_low_normal(&(t[n]),&(a[n]),&(b[0]),n); + bn_add_words(&(r[n]),&(r[n]),&(t[0]),n); + bn_add_words(&(r[n]),&(r[n]),&(t[n]),n); + } + } +#endif +#endif + +#ifdef SPLIT_BN_MUL_HIGH +#if 0 +/* a and b must be the same size, which is n2. + * r must be n2 words and t must be n2*2 + * l is the low words of the output. + * t must be n2*3 + */ +void bn_mul_high(r,a,b,l,n2,t) +BN_ULONG *r,*a,*b,*l; +int n2; +BN_ULONG *t; + { + int i,n; + int c1,c2; + int neg,oneg,zero; + BN_ULONG ll,lc,*lp,*mp; + +#ifdef BN_COUNT +printf(" bn_mul_high %d * %d\n",n2,n2); +#endif + n=n2/2; + + /* Calculate (al-ah)*(bh-bl) */ + neg=zero=0; + c1=bn_cmp_words(&(a[0]),&(a[n]),n); + c2=bn_cmp_words(&(b[n]),&(b[0]),n); + switch (c1*3+c2) + { + case -4: + bn_sub_words(&(r[0]),&(a[n]),&(a[0]),n); + bn_sub_words(&(r[n]),&(b[0]),&(b[n]),n); + break; + case -3: + zero=1; + break; + case -2: + bn_sub_words(&(r[0]),&(a[n]),&(a[0]),n); + bn_sub_words(&(r[n]),&(b[n]),&(b[0]),n); + neg=1; + break; + case -1: + case 0: + case 1: + zero=1; + break; + case 2: + bn_sub_words(&(r[0]),&(a[0]),&(a[n]),n); + bn_sub_words(&(r[n]),&(b[0]),&(b[n]),n); + neg=1; + break; + case 3: + zero=1; + break; + case 4: + bn_sub_words(&(r[0]),&(a[0]),&(a[n]),n); + bn_sub_words(&(r[n]),&(b[n]),&(b[0]),n); + break; + } + + oneg=neg; + /* t[10] = (a[0]-a[1])*(b[1]-b[0]) */ + /* r[10] = (a[1]*b[1]) */ +#ifdef BN_MUL_COMBA + if (n == 8) + { + bn_mul_comba8(&(t[0]),&(r[0]),&(r[n])); + bn_mul_comba8(r,&(a[n]),&(b[n])); + } + else +#endif + { +#ifdef BN_MUL_RECURSION + bn_mul_recursive(&(t[0]),&(r[0]),&(r[n]),n,&(t[n2])); + bn_mul_recursive(r,&(a[n]),&(b[n]),n,&(t[n2])); +#else + bn_mul_normal(&(t[0]),&(r[0]),n,&(r[n]),n); + bn_mul_normal(r,&(a[n]),n,&(b[n]),n); +#endif + } + + /* s0 == low(al*bl) + * s1 == low(ah*bh)+low((al-ah)*(bh-bl))+low(al*bl)+high(al*bl) + * We know s0 and s1 so the only unknown is high(al*bl) + * high(al*bl) == s1 - low(ah*bh+s0+(al-ah)*(bh-bl)) + * high(al*bl) == s1 - (r[0]+l[0]+t[0]) + */ + if (l != NULL) + { + lp= &(t[n2+n]); + c1=(int)bn_add_words(lp,&(r[0]),&(l[0]),n); + } + else + { + c1=0; + lp= &(r[0]); + } + + if (neg) + neg=(int)bn_sub_words(&(t[n2]),lp,&(t[0]),n); + else + { + bn_add_words(&(t[n2]),lp,&(t[0]),n); + neg=0; + } + + if (l != NULL) + { + bn_sub_words(&(t[n2+n]),&(l[n]),&(t[n2]),n); + } + else + { + lp= &(t[n2+n]); + mp= &(t[n2]); + for (i=0; i 0) + { + lc=c1; + do { + ll=(r[i]+lc)&BN_MASK2; + r[i++]=ll; + lc=(lc > ll); + } while (lc); + } + else + { + lc= -c1; + do { + ll=r[i]; + r[i++]=(ll-lc)&BN_MASK2; + lc=(lc > ll); + } while (lc); + } + } + if (c2 != 0) /* Add starting at r[1] */ + { + i=n; + if (c2 > 0) + { + lc=c2; + do { + ll=(r[i]+lc)&BN_MASK2; + r[i++]=ll; + lc=(lc > ll); + } while (lc); + } + else + { + lc= -c2; + do { + ll=r[i]; + r[i++]=(ll-lc)&BN_MASK2; + lc=(lc > ll); + } while (lc); + } + } + } +#endif +#endif +#endif + +#ifdef SPLIT_BN_MUL +int BN_mul(r,a,b,ctx) +BIGNUM *r,*a,*b; +BN_CTX *ctx; + { + int top,al,bl,neg; + BIGNUM *rr; +#ifdef BN_RECURSION_MUL + BIGNUM *t; + int i,j,k,l; +#endif + +#ifdef BN_COUNT +printf("BN_mul %d * %d\n",a->top,b->top); +#endif + + bn_check_top(a); + bn_check_top(b); + bn_check_top(r); + + al=a->top; + bl=b->top; + + if ((al == 0) || (bl == 0)) + { + (void)BN_zero(r); + return(1); + } + top=al+bl; + neg=a->neg^b->neg; + + if ((r == a) || (r == b)) + rr= &(ctx->bn[ctx->tos+1]); + else + rr=r; + + if (bn_wexpand(rr,top) == NULL) return(0); + rr->top=top; + +#if defined(BN_MUL_COMBA) || defined(BN_RECURSION_MUL) + if (al == bl) + { +# ifdef BN_MUL_COMBA +/* if (al == 4) + { + bn_mul_comba4(rr->d,a->d,b->d); + goto end; + } + else */ if (al == 8) + { + bn_mul_comba8(rr->d,a->d,b->d); + goto end; + } + else +# endif +#ifdef BN_RECURSION_MUL + if (al < BN_MULL_SIZE_NORMAL) +#endif + { + bn_mul_normal(rr->d,a->d,al,b->d,bl); + goto end; + } +# ifdef BN_RECURSION_MUL + goto symetric; +# endif + } +#endif +#ifdef BN_RECURSION_MUL + else if ((al < BN_MULL_SIZE_NORMAL) || (bl < BN_MULL_SIZE_NORMAL)) + { + bn_mul_normal(rr->d,a->d,al,b->d,bl); + goto end; + } + else + { + i=(al-bl); + if ((i == 1) && !BN_get_flags(b,BN_FLG_STATIC_DATA)) + { + bn_wexpand(b,al); + b->d[bl]=0; + bl++; + goto symetric; + } + else if ((i == -1) && !BN_get_flags(a,BN_FLG_STATIC_DATA)) + { + bn_wexpand(a,bl); + a->d[al]=0; + al++; + goto symetric; + } + } +#endif + +#ifdef BN_RECURSION_MUL +normal_mul: +#endif + bn_mul_normal(rr->d,a->d,al,b->d,bl); + +#ifdef BN_RECURSION_MUL + if (0) + { +symetric: + /* symetric and > 4 */ + /* 16 or larger */ + l=BN_num_bits_word((BN_ULONG)al); + j=1<<(l-1); + k=j+j; + t= &(ctx->bn[ctx->tos]); + if (al == j) /* exact multiple */ + { + BN_REC rec; + rec.depth=l-5; + rec.n=j; + rec.mul=bn_mul_comba8; + rec.sqr=bn_sqr_comba8; + if (bn_wexpand(t,k+k) == NULL) + return(0); + if (bn_wexpand(rr,k) == NULL) + return(0); + bn_mul_rec_words(rr->d,a->d,b->d,t->d,&rec); + } + else + goto normal_mul; +#if 0 + { + bn_zexpand(a,k); + bn_zexpand(b,k); + bn_wexpand(t,k); + bn_wexpand(rr,k); + bn_mul_part_recursive(rr->d,a->d,b->d,al-j,j,t->d); + } +#endif + } +#endif +#if defined(BN_MUL_COMBA) || defined(BN_RECURSION_MUL) +end: +#endif + + r->neg=neg; + bn_fix_top(rr); + if (r != rr) (void)BN_copy(r,rr); + return(1); + } +#endif + + +#ifdef SPLIT_BN_MUL_NORMAL +void bn_mul_normal(r,a,na,b,nb) +BN_ULONG *r,*a; +int na; +BN_ULONG *b; +int nb; + { + BN_ULONG *rr; + +#ifdef BN_COUNT +printf(" bn_mul_normal %d * %d\n",na,nb); +#endif + /* asymetric and >= 4 */ +#if 0 + if ((na == nb) && (na == 8)) + { + bn_mul_normal(r,a,na,b,nb); + return; + } +#endif + + if (na < nb) + { + int itmp; + BN_ULONG *ltmp; + + itmp=na; na=nb; nb=itmp; + ltmp=a; a=b; b=ltmp; + + } + rr= &(r[na]); + rr[0]=bn_mul_words(r,a,na,b[0]); + + for (;;) + { + if (--nb <= 0) return; + rr[1]=bn_mul_add_words(&(r[1]),a,na,b[1]); + if (--nb <= 0) return; + rr[2]=bn_mul_add_words(&(r[2]),a,na,b[2]); + if (--nb <= 0) return; + rr[3]=bn_mul_add_words(&(r[3]),a,na,b[3]); + if (--nb <= 0) return; + rr[4]=bn_mul_add_words(&(r[4]),a,na,b[4]); + rr+=4; + r+=4; + b+=4; + } + } +#endif + +#ifdef SPLIT_BN_MUL_LOW_NORMAL +void bn_mul_low_normal(r,a,b,n) +BN_ULONG *r,*a,*b; +int n; + { +#ifdef BN_COUNT +printf(" bn_mul_low_normal %d * %d\n",n,n); +#endif + (void)bn_mul_words(r,a,n,b[0]); + + for (;;) + { + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[1]),a,n,b[1]); + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[2]),a,n,b[2]); + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[3]),a,n,b[3]); + if (--n <= 0) return; + (void)bn_mul_add_words(&(r[4]),a,n,b[4]); + r+=4; + b+=4; + } + } +#endif +#endif diff --git a/build/tools/acsign/bn_r_exp.c b/build/tools/acsign/bn_r_exp.c new file mode 100644 index 0000000..9465e40 --- /dev/null +++ b/build/tools/acsign/bn_r_exp.c @@ -0,0 +1,134 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +/* #ifdef RECP_MUL_MOD */ +int BN_mod_exp_recp(r,a,p,m,ctx) +BIGNUM *r; +BIGNUM *a; +BIGNUM *p; +BIGNUM *m; +BN_CTX *ctx; + { + int i,j,bits,ret=0,wstart,wend,window,wvalue; + int start=1,ts=0; + BIGNUM *aa; + BIGNUM val[BN_EXP_TABLE_SIZE]; + BN_RECP_CTX recp; + + bits=BN_num_bits(p); + + if (BN_is_zero(a)) + { (void)BN_zero(r); return(1); } + if (BN_is_zero(p)) + { (void)BN_one(r); return(1); } + if (BN_is_one(p)) + { (void)BN_copy(r,a); return(1); } + + BN_RECP_CTX_init(&recp); + if (BN_RECP_CTX_set(&recp,m,ctx) <= 0) goto err; + + BN_init(&(val[0])); + ts=1; + + aa= &(ctx->bn[ctx->tos++]); + + if (!BN_mod(&(val[0]),a,m,ctx)) goto err; /* 1 */ + if (!BN_mod_mul_reciprocal(aa,&(val[0]),&(val[0]),&recp,ctx)) + goto err; /* 2 */ + + if (bits <= 17) /* This is probably 3 or 0x10001, so just do singles */ + window=1; + else if (bits >= 256) + window=5; /* max size of window */ + else if (bits >= 128) + window=4; + else + window=3; + + j=1<<(window-1); + for (i=1; i>1]),&recp,ctx)) + goto err; + + /* move the 'window' down further */ + wstart-=wend+1; + wvalue=0; + start=0; + if (wstart < 0) break; + } + ret=1; +err: + ctx->tos--; + for (i=0; in; + int n2=n/2; + int c1,neg=0; + + + if (rec->depth == 0) + { + /* t needs to have space for 4*n words + * The multiply needs to be a n2*n2 -> n + */ +#ifndef NOPROTO + void (PRE_CCONV CCONV *rmul)(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); +#else + void (PRE_CCONV CCONV *rmul)(); +#endif + rmul=rec->mul; + +#ifdef _EXTRA_ARG_ + /* THIS IS WRONG - there is no extra int arg on the end */ + rmul(&(r[0]),&(a[0]),&(b[0]),n2); + rmul(&(r[n]),&(a[n2]),&(b[n2]),n2); +#else + rmul(&(r[0]),&(a[0]),&(b[0])); + rmul(&(r[n]),&(a[n2]),&(b[n2])); +#endif + + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + { + bn_2s_comp(&(tt[n+ 0]),&(tt[n+ 0]),n2); + neg=1; + } + else + neg=0; + if (bn_sub_words(&(tt[n+n2]),&(b[n2]),&(b[0]),n2)) + { + neg^=1; + bn_2s_comp(&(tt[n+n2]),&(tt[n+n2]),n2); + } + +#ifdef _EXTRA_ARG_ + rmul(&(tt[0]),&(tt[n+0]),&(tt[n+n2]),n2); +#else + rmul(&(tt[0]),&(tt[n+0]),&(tt[n+n2])); +#endif + } + else /* Leaf node */ + { + /* t has 4*n words taken per call. + * Since n is half the size per call, we need + * 6*n words for our current level and all sub levels + * The multiply needs to be a n2*n2 -> n + */ + rec->depth--; + rec->n=n2; + bn_mul_rec_words(&(r[0]), &(a[0]), &(b[0]), &(tt[n+n]),rec); + bn_mul_rec_words(&(r[n]), &(a[n2]),&(b[n2]), &(tt[n+n]),rec); + + neg=0; + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + { + bn_2s_comp(&(tt[n+ 0]),&(tt[n+ 0]),n2); + neg=1; + } + else + neg=0; + if (bn_sub_words(&(tt[n+n2]),&(b[n2]),&(b[0]),n2)) + { + neg^=1; + bn_2s_comp(&(tt[n+n2]),&(tt[n+n2]),n2); + } + + bn_mul_rec_words(&(tt[0]),&(tt[n]),&(tt[n+n2]),&(tt[n+n]),rec); + rec->n=n; + rec->depth++; + } + + c1=bn_add_words(&(tt[n]),&(r[0]),&(r[n]),n); + + if (neg) + c1-=bn_sub_words(&(tt[0]),&(tt[n]),&(tt[0]),n); + else + c1+=bn_add_words(&(tt[0]),&(tt[n]),&(tt[0]),n); + tt[n]=c1; + c1=bn_add_words(&(r[n2]),&(r[n2]),&(tt[0]),n+1); + if (c1) + { + tt= &(r[n+n2+1]); + do { + } while (++(*(tt++)) == 0); + } + } +#endif + +#ifdef SPLIT_BN_SQR_REC_WORDS +/* tt needs to be 3*n words */ +void bn_sqr_rec_words(r,a,tt,rec) +BN_ULONG *r,*a,*tt; +BN_REC *rec; + { + int n=rec->n; + int n2=n/2; + int c1; + + if (rec->depth == 0) + { + /* t needs to have space for 4*n words + * The multiply needs to be a n2*n2 -> n + */ +#ifndef NOPROTO + void (PRE_CCONV CCONV *rsqr)(BN_ULONG *r, BN_ULONG *a); +#else + void (PRE_CCONV CCONV *rsqr)(); +#endif + + rsqr=rec->sqr; + +#ifdef _EXTRA_ARG_ + /* THIS IS WRONG - there is no extra int arg on the end */ + rsqr(&(r[0]), &(a[0]), n2); + rsqr(&(r[n]), &(a[n2]),n2); +#else + rsqr(&(r[0]), &(a[0])); + rsqr(&(r[n]), &(a[n2])); +#endif + + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + bn_2s_comp(&(tt[n+0]),&tt[n+0], n2); + +#ifdef _EXTRA_ARG_ + rsqr(&(tt[0]),&(tt[n]), n2); +#else + rsqr(&(tt[0]),&(tt[n])); +#endif + + } + else /* Leaf node */ + { + /* t has 4*n words taken per call. + * Since n is half the size per call, we need + * 6*n words for our current level and all sub levels + * The multiply needs to be a n2*n2 -> n + */ + rec->depth--; + rec->n=n2; + bn_sqr_rec_words(&(r[0]), &(a[0]), &(tt[n+n]),rec); + bn_sqr_rec_words(&(r[n]), &(a[n2]),&(tt[n+n]),rec); + + if (bn_sub_words(&(tt[n+0]), &(a[0]),&(a[n2]),n2)) + bn_2s_comp(&(tt[n+0]),&tt[n+0], n2); + bn_sqr_rec_words(&(tt[0]),&(tt[n]),&(tt[n+n]),rec); + + rec->n=n; + rec->depth++; + } + + c1=bn_add_words(&(tt[n]),&(r[0]),&(r[n]),n); + c1-=bn_sub_words(&(tt[0]),&(tt[n]),&(tt[0]),n); + + tt[n]=c1; + c1=bn_add_words(&(r[n2]),&(r[n2]),&(tt[0]),n+1); + if (c1) + { + tt= &(r[n+n2+1]); + do { + } while (++(*(tt++)) == 0); + } + } +#endif + +#endif /* !NO_SPLIT || !SPLIT_FILE */ diff --git a/build/tools/acsign/bn_recp.c b/build/tools/acsign/bn_recp.c new file mode 100644 index 0000000..e762a81 --- /dev/null +++ b/build/tools/acsign/bn_recp.c @@ -0,0 +1,202 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +void BN_RECP_CTX_init(recp) +BN_RECP_CTX *recp; + { + BN_init(&(recp->N)); + BN_init(&(recp->Nr)); + recp->num_bits=0; + recp->flags=0; + } + +BN_RECP_CTX *BN_RECP_CTX_new() + { + BN_RECP_CTX *ret; + + if ((ret=(BN_RECP_CTX *)Malloc(sizeof(BN_RECP_CTX))) == NULL) + return(NULL); + + BN_RECP_CTX_init(ret); + ret->flags=BN_FLG_MALLOCED; + return(ret); + } + +void BN_RECP_CTX_free(recp) +BN_RECP_CTX *recp; + { + BN_free(&(recp->N)); + BN_free(&(recp->Nr)); + if (recp->flags & BN_FLG_MALLOCED) + Free(recp); + } + +int BN_RECP_CTX_set(recp,d,ctx) +BN_RECP_CTX *recp; +BIGNUM *d; +BN_CTX *ctx; + { + (void)BN_copy(&(recp->N),d); + (void)BN_zero(&(recp->Nr)); + recp->num_bits=BN_num_bits(d); + recp->shift=0; + ctx=ctx; /* Stop warning */ + return(1); + } + +int BN_mod_mul_reciprocal(r, x, y, recp, ctx) +BIGNUM *r; +BIGNUM *x; +BIGNUM *y; +BN_RECP_CTX *recp; +BN_CTX *ctx; + { + int ret=0; + BIGNUM *a; + + bn_check_top(x); + bn_check_top(y); + + a= &(ctx->bn[ctx->tos++]); + if (y != NULL) + { + if (x == y) + { if (!BN_sqr(a,x,ctx)) goto err; } + else + { if (!BN_mul(a,x,y,ctx)) goto err; } + } + else + a=x; /* Just do the mod */ + + (void)BN_div_recp(NULL,r,a,recp,ctx); + ret=1; +err: + ctx->tos--; + return(ret); + } + +int BN_div_recp(dv,rem,m,recp,ctx) +BIGNUM *dv; +BIGNUM *rem; +BIGNUM *m; +BN_RECP_CTX *recp; +BN_CTX *ctx; + { + int i,j,tos,ret=0,ex; + BIGNUM *a,*b,*d,*r; + + bn_check_top(m); + + tos=ctx->tos; + a= &(ctx->bn[ctx->tos++]); + b= &(ctx->bn[ctx->tos++]); + if (dv != NULL) + d=dv; + else + d= &(ctx->bn[ctx->tos++]); + if (rem != NULL) + r=rem; + else + r= &(ctx->bn[ctx->tos++]); + + if (BN_ucmp(m,&(recp->N)) < 0) + { + (void)BN_zero(d); + (void)BN_copy(r,m); + ctx->tos=tos; + return(1); + } + + /* We want the remainder + * Given input of ABCDEF / ab + * we need multiply ABCDEF by 3 digests of the reciprocal of ab + * + */ + i=BN_num_bits(m); + + j=recp->num_bits*2; + if (j > i) + { + i=j; + ex=0; + } + else + { + ex=(i-j)/2; + } + + j=i/2; + + if (i != recp->shift) + recp->shift=BN_reciprocal(&(recp->Nr),&(recp->N), + i,ctx); + + if (!BN_rshift(a,m,j-ex)) goto err; + if (!BN_mul(b,a,&(recp->Nr),ctx)) goto err; + if (!BN_rshift(d,b,j+ex)) goto err; + d->neg=0; + if (!BN_mul(b,&(recp->N),d,ctx)) goto err; + if (!BN_usub(r,m,b)) goto err; + r->neg=0; + + j=0; +#if 1 + while (BN_ucmp(r,&(recp->N)) >= 0) + { + if (j++ > 2) + { +#ifndef NO_ERR + BNerr(BN_F_BN_DIV_RECP,BN_R_BAD_RECIPROCAL); +#endif + goto err; + } + if (!BN_usub(r,r,&(recp->N))) goto err; + if (!BN_add_word(d,1)) goto err; + } +#endif + + r->neg=BN_is_zero(r)?0:m->neg; + d->neg=m->neg^recp->N.neg; + ret=1; +err: + ctx->tos=tos; + return(ret); + } + +/* len is the expected size of the result + * We actually calculate with an extra word of precision, so + * we can do faster division if the remainder is not required. + */ +int BN_reciprocal(r,m,len,ctx) +BIGNUM *r; +BIGNUM *m; +int len; +BN_CTX *ctx; + { + int ret= -1; + BIGNUM t; + + bn_check_top(m); + + BN_init(&t); + + (void)BN_zero(&t); + if (!BN_set_bit(&t,len)) goto err; + + if (!BN_div(r,NULL,&t,m,ctx)) goto err; + ret=len; +err: + BN_free(&t); + return(ret); + } + diff --git a/build/tools/acsign/bn_rsh.c b/build/tools/acsign/bn_rsh.c new file mode 100644 index 0000000..909cd9a --- /dev/null +++ b/build/tools/acsign/bn_rsh.c @@ -0,0 +1,123 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_RSHIFT1 +#define SPLIT_BN_RSHIFT +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_RSHIFT1 +#ifdef SMALL_CODE_SIZE +int BN_rshift1(r, a) +BIGNUM *r; +BIGNUM *a; + { + return(BN_rshift(r,a,1)); + } + +#else + +int BN_rshift1(r, a) +BIGNUM *r; +BIGNUM *a; + { + BN_ULONG *ap,*rp,t,c; + int i; + + bn_check_top(a); + + if (BN_is_zero(a)) + { + BN_zero(r); + return(1); + } + if (a != r) + { + if (bn_wexpand(r,a->top) == NULL) return(0); + r->top=a->top; + r->neg=a->neg; + } + ap=a->d; + rp=r->d; + c=0; + for (i=a->top-1; i>=0; i--) + { + t=ap[i]; + rp[i]=((t>>1)&BN_MASK2)|c; + c=(t&1)?BN_TBIT:0; + } + bn_fix_top(r); + return(1); + } +#endif +#endif + +#ifdef SPLIT_BN_RSHIFT +int BN_rshift(r, a, n) +BIGNUM *r; +BIGNUM *a; +int n; + { + int i,j,nw,lb,rb; + BN_ULONG *t,*f; + BN_ULONG l,tmp; + + bn_check_top(a); + +#ifndef SMALL_CODE_SIZE + if (n == 1) return(BN_rshift1(r,a)); +#endif + nw=n/BN_BITS2; + rb=n%BN_BITS2; + lb=BN_BITS2-rb; + if (nw > a->top) + { + (void)BN_zero(r); + return(1); + } + if (r != a) + { + if (bn_wexpand(r,a->top-nw+1+1/*???*/) == NULL) return(0); + r->neg=a->neg; + } + + f= &(a->d[nw]); + t=r->d; + j=a->top-nw; + r->top=j; + + if (rb == 0) + { + for (i=j+1; i > 0; i--) + *(t++)= *(f++); + } + else + { + l= *(f++); + for (i=1; i>rb)&BN_MASK2; + l= *(f++); + *(t++) =(tmp|(l<>rb)&BN_MASK2; + *t=0; + } + bn_fix_top(r); + return(1); + } +#endif + +#endif diff --git a/build/tools/acsign/bn_sqr.c b/build/tools/acsign/bn_sqr.c new file mode 100644 index 0000000..4762cd9 --- /dev/null +++ b/build/tools/acsign/bn_sqr.c @@ -0,0 +1,273 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#ifdef SMALL_CODE_SIZE +#undef BN_RECURSION_SQR +#endif + +#if !(defined(NO_SPLIT) && defined(SPLIT_FILE)) + +#ifdef NO_SPLIT +#define SPLIT_BN_SQR +#define SPLIT_BN_SQR_NORMAL +#define SPLIT_BN_RECURSION_SQR +#endif /* NO_SPLIT */ + +#ifdef SPLIT_BN_SQR +/* r must not be a */ +int BN_sqr(r, a, ctx) +BIGNUM *r; +BIGNUM *a; +BN_CTX *ctx; + { + int max,al; + BIGNUM *tmp,*rr; + +#ifdef BN_COUNT +printf("BN_sqr %d * %d\n",a->top,a->top); +#endif + bn_check_top(a); + tmp= &(ctx->bn[ctx->tos]); + rr=(a != r)?r: (&ctx->bn[ctx->tos+1]); + + al=a->top; + if (al <= 0) + { + r->top=0; + return(1); + } + + max=(al+al); + if (bn_wexpand(rr,max) == NULL) return(0); + + rr->top=max; + rr->neg=0; + + if (al == 4) + { +#ifndef BN_SQR_COMBA + BN_ULONG t[8]; + bn_sqr_normal(rr->d,a->d,4,t); +#else + bn_sqr_comba4(rr->d,a->d); +#endif + } + else if (al == 8) + { +#ifndef BN_SQR_COMBA + BN_ULONG t[16]; + bn_sqr_normal(rr->d,a->d,8,t); +#else + bn_sqr_comba8(rr->d,a->d); +#endif + } + else + { +#if 1 && defined(BN_RECURSION_SQR) + if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) + { + BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL*2]; + bn_sqr_normal(rr->d,a->d,al,t); + } + else + { + int j,l,k; + + l=BN_num_bits_word((BN_ULONG)al); + j=1<<(l-1); + k=j+j; + if ((al == j) && !BN_get_flags(a,BN_FLG_STATIC_DATA)) + { + BN_REC rec; + if (bn_wexpand(tmp,k*2) == NULL) return(0); + rec.depth=l-5; + rec.n=j; + rec.mul=bn_mul_comba8; + rec.sqr=bn_sqr_comba8; + + bn_sqr_rec_words(rr->d,a->d,tmp->d,&rec); + } + else + { + if (bn_wexpand(tmp,max) == NULL) return(0); + bn_assert(al*2 <= max); + bn_sqr_normal(rr->d,a->d,al,tmp->d); + } + } +#else + if (bn_wexpand(tmp,max) == NULL) return(0); + bn_assert(al*2 <= max); + bn_sqr_normal(rr->d,a->d,al,tmp->d); +#endif +#ifdef BN_DEBUG + tmp->top=0; +#endif + } + + if ((max > 0) && (rr->d[max-1] == 0)) rr->top--; + if (rr != r) (void)BN_copy(r,rr); + return(1); + } +#endif + +#ifdef SPLIT_BN_SQR_NORMAL +/* tmp must have 2*n words */ +void bn_sqr_normal(r, a, n, tmp) +BN_ULONG *r; +BN_ULONG *a; +int n; +BN_ULONG *tmp; + { + int i,j,max; + BN_ULONG *ap,*rp,m; + + max=n*2; + ap=a; + rp=r; + rp[0]=rp[max-1]=0; + rp++; + j=n; + + if (--j > 0) + { + m= (*ap++); + rp[j]=bn_mul_words(rp,ap,j,m); + rp+=2; + } + + for (i=n-2; i>0; i--) + { + j--; + m= *(ap++); + rp[j]=bn_mul_add_words(rp,ap,j,m); + rp+=2; + } + + (void)bn_add_words(r,r,r,max); + + /* There will not be a carry */ + + bn_sqr_words(tmp,a,n); + + (void)bn_add_words(r,r,tmp,max); + } +#endif + +#if 0 /* replaced by bn_sqr_rec_words() AND this has bugs */ +#ifdef SPLIT_BN_RECURSION_SQR +#ifdef BN_RECURSION_SQR +/* r is 2*n words in size, + * a and b are both n words in size. + * n must be a power of 2. + * We multiply and return the result. + * t must be 2*n words in size + * We calulate + * a[0]*b[0] + * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) + * a[1]*b[1] + */ +void bn_sqr_recursive(r,a,n2,t) +BN_ULONG *r,*a; +int n2; +BN_ULONG *t; + { + int n=n2/2; + int zero,c1; + BN_ULONG ln,lo,*p; + +#ifdef BN_COUNT +printf(" bn_sqr_recursive %d * %d\n",n2,n2); +#endif + if (n2 == 4) + { +#ifndef BN_SQR_COMBA + bn_sqr_normal(r,a,4,t); +#else + bn_sqr_comba4(r,a); +#endif + return; + } + else if (n2 == 8) + { +#ifndef BN_SQR_COMBA + bn_sqr_normal(r,a,8,t); +#else + bn_sqr_comba8(r,a); +#endif + return; + } + if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) + { + bn_sqr_normal(r,a,n2,t); + return; + } + /* r=(a[0]-a[1])*(a[1]-a[0]) */ + c1=bn_cmp_words(a,&(a[n]),n); + zero=0; + if (c1 > 0) + bn_sub_words(t,a,&(a[n]),n); + else if (c1 < 0) + bn_sub_words(t,&(a[n]),a,n); + else + zero=1; + + /* The result will always be negative unless it is zero */ + p= &(t[n2*2]); + + if (!zero) + bn_sqr_recursive(&(t[n2]),t,n,p); + else + Memset(&(t[n2]),0,n*sizeof(BN_ULONG)); + bn_sqr_recursive(r,a,n,p); + bn_sqr_recursive(&(r[n2]),&(a[n]),n,p); + + /* t[32] holds (a[0]-a[1])*(a[1]-a[0]), it is negative or zero + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1=(int)(bn_add_words(t,r,&(r[n2]),n2)); + + /* t[32] is negative */ + c1-=(int)(bn_sub_words(&(t[n2]),t,&(t[n2]),n2)); + + /* t[32] holds (a[0]-a[1])*(a[1]-a[0])+(a[0]*a[0])+(a[1]*a[1]) + * r[10] holds (a[0]*a[0]) + * r[32] holds (a[1]*a[1]) + * c1 holds the carry bits + */ + c1+=(int)(bn_add_words(&(r[n]),&(r[n]),&(t[n2]),n2)); + if (c1) + { + p= &(r[n+n2]); + lo= *p; + ln=(lo+c1)&BN_MASK2; + *p=ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if (ln < (BN_ULONG)c1) + { + do { + p++; + lo= *p; + ln=(lo+1)&BN_MASK2; + *p=ln; + } while (ln == 0); + } + } + } +#endif +#endif +#endif +#endif diff --git a/build/tools/acsign/bn_wdiv.c b/build/tools/acsign/bn_wdiv.c new file mode 100644 index 0000000..d76752a --- /dev/null +++ b/build/tools/acsign/bn_wdiv.c @@ -0,0 +1,100 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#include "bn_lcl.h" + +#ifndef OPT_BN_ASM + +#ifndef BN_DIV_WORDS +#define BN_DIV_WORDS +#endif + +#endif + +#ifdef BN_DIV_WORDS +#if defined(BN_LLONG) +BN_ULONG bn_div_words(h,l,d) +BN_ULONG h,l,d; + { + return((BN_ULONG)(((((BN_ULLONG)h)< ((BN_ULONG)1)<= d) h-=d; + + if (i) + { + d=(d<>(BN_BITS2-i)))&BN_MASK2; + l=(l<>BN_BITS4)&BN_MASK2lh; + dl=(d&BN_MASK2l); + for (;;) + { + if ((h>>BN_BITS4) == dh) + q=BN_MASK2l; + else + q=h/dh; + + for (;;) + { + t=(h-q*dh)&BN_MASK2; + if ((t&BN_MASK2h) || + (((dl*q)&BN_MASK2) <= (( + (t<>BN_BITS4)&BN_MASK2lh))&BN_MASK2))) + break; + q--; + } + th=(q*dh)&BN_MASK2; + tl=(q*dl)&BN_MASK2; + t=(tl>>BN_BITS4); + tl=(tl&BN_MASK2lh)<>BN_BITS4))&BN_MASK2; + l=(l&BN_MASK2l)<top-1; i>=0; i--) + { +#ifndef BN_LLONG + ret=((ret<d[i]>>BN_BITS4)&BN_MASK2l))%w; + ret=((ret<d[i]&BN_MASK2l))%w; +#else + ret=(BN_ULLONG)(((ret<<(BN_ULLONG)BN_BITS2)|a->d[i])% + (BN_ULLONG)w); +#endif + } + return((BN_ULONG)ret); + } +#endif + +#ifdef SPLIT_BN_DIV_WORD +BN_ULONG BN_div_word(a, w) +BIGNUM *a; +BN_ULONG w; + { + BN_ULONG ret; + int i; + + if (a->top == 0) return(0); + ret=0; + w=w&BN_MASK2;//w&=BN_MASK2; + for (i=a->top-1; i>=0; i--) + { + BN_ULONG l,d; + + l=a->d[i]; + d=bn_div_words(ret,l,w); + ret=(l-((d*w)&BN_MASK2))&BN_MASK2; + a->d[i]=d; + } + if ((a->top > 0) && (a->d[a->top-1] == 0)) + a->top--; + return(ret); + } +#endif + +#ifdef SPLIT_BN_ADD_WORD +int BN_add_word(a, w) +BIGNUM *a; +BN_ULONG w; + { + BN_ULONG l; + int i; + + if (w == 0) return(1); + bn_check_top(a); + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->neg) + { + if(a->top > 1) + { + a->neg=0; + i=BN_sub_word(a,w); + a->neg=1; + return(i); + } + else + { /* a->top == 1, it cannot be 0 */ + l=a->d[0]; + if (l > w) + a->d[0]=l-w; + else if (l < w) + { + a->neg=0; + a->d[0]=w-l; + } + else + { + a->neg=0; + a->top=0; + } + return(1); + } + } + w=w&BN_MASK2;//w&=BN_MASK2; + if (bn_wexpand(a,a->top+1) == NULL) return(0); + a->d[a->top]=0; + i=0; + for (;;) + { + l=(a->d[i]+(BN_ULONG)w)&BN_MASK2; + a->d[i]=l; + if (w > l) + w=1; + else + break; + i++; + } + if (i >= a->top) + a->top++; + return(1); + } +#endif + +#ifdef SPLIT_BN_SUB_WORD +int BN_sub_word(a, w) +BIGNUM *a; +BN_ULONG w; + { + int i; + + bn_check_top(a); + if (w == 0) return(1); + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->neg) + { + a->neg=0; + i=BN_add_word(a,w); + a->neg=1; + return(i); + } + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->top <= 1) + { + BN_ULONG l; + + if (a->top == 0) + { + if (bn_wexpand(a,1) == NULL) return(0); + a->d[0]=w; + a->neg = 1; + a->top = 1; + return(1); + } + l=a->d[0]; + if (l == w) + a->top=0; + else if (l > w) + a->d[0]=l-w; + else + { + a->neg=1; + a->d[0]=w-l; + } + return(1); + } + i=0; + for (;;) + { + if (a->d[i] >= w) + { + a->d[i]-=w; + break; + } + else + { + a->d[i]=(a->d[i]-w)&BN_MASK2; + i++; + w=1; + } + } + if ((a->d[i] == 0) && (i == (a->top-1))) + a->top--; + return(1); + } +#endif + +#ifdef SPLIT_BN_MUL_WORD +int BN_mul_word(a,w) +BIGNUM *a; +BN_ULONG w; + { + BN_ULONG ll; + + w=w&BN_MASK2;//w&=BN_MASK2; + if (a->top) + { + ll=bn_mul_words(a->d,a->d,a->top,w); + if (ll) + { + if (bn_wexpand(a,a->top+1) == NULL) return(0); + a->d[a->top++]=ll; + } + } + return(1); + } +#endif + +#endif diff --git a/build/tools/acsign/include/acsign.h b/build/tools/acsign/include/acsign.h new file mode 100644 index 0000000..6e11663 --- /dev/null +++ b/build/tools/acsign/include/acsign.h @@ -0,0 +1,49 @@ +#ifndef _ACSIGN_H_ +#define _ACSIGN_H_ + +#include "sha.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define HASHContext SHA_CTX + +#define HASHReset( _context ) \ +do{ \ + (_context)->sha_block = NULL; \ + (void)SHA1_Init( _context ); \ +} while(0) +#define HASHUpdate( _context, _ptr, _len ) (void)SHA1_Update( _context, _ptr, _len ) +#define HASHGetDigest( _context, _ptr ) (void)SHA1_Final( _ptr, _context ) + +// +BOOL ACSign_Encrypto(void *sign, const void *key, const void *data, int length); +BOOL ACSign_Decrypto(void *buf, const void *key, const void *sign, int length); + +// +int ACSign_DigestUnit( + void* buffer, // o͗̈ + const void* buf, // f[^ւ̃|C^ + unsigned int len // f[^̒ + ); + +// +int ACSign_CompareUnit( + const void* decedHash, // ACSign_Decryptȍo + const void* digest // ACSign_DigestUnit̏o + ); + +// +int ACSign_GetKey( + void* dest_ptr, // o̓f[^ւ̃|C^ + unsigned int dest_len, // o̓f[^̒ + const void* src_ptr, // ̓f[^ւ̃|C^ + unsigned int src_len // ̓f[^̒ + ); + +#ifdef __cplusplus +} +#endif + +#endif //_ACSIGN_H_ diff --git a/build/tools/acsign/include/acsign_gcd.h b/build/tools/acsign/include/acsign_gcd.h new file mode 100644 index 0000000..2c9853e --- /dev/null +++ b/build/tools/acsign/include/acsign_gcd.h @@ -0,0 +1,30 @@ +#ifndef _ACSIGN_GCD_H_ +#define _ACSIGN_GCD_H_ + +#include "sha.h" +#include "format_sign.h" +#include "format_rom.h" +#include "acsign.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// +int ACSign_Final( + GCDHeader* header, // wb_ւ̃|C^ + void* buffer, // o͗̈ + const void* key + ); + +// +int ACSign_DigestHeader( + void* buffer, // o͗̈ + GCDHeader* header // f[^ւ̃|C^ + ); + +#ifdef __cplusplus +} +#endif + +#endif //_ACSIGN_GCD_H_ diff --git a/build/tools/acsign/include/acsign_nand.h b/build/tools/acsign/include/acsign_nand.h new file mode 100644 index 0000000..97afa98 --- /dev/null +++ b/build/tools/acsign/include/acsign_nand.h @@ -0,0 +1,30 @@ +#ifndef _ACSIGN_NAND_H_ +#define _ACSIGN_NAND_H_ + +#include "sha.h" +#include "format_sign.h" +#include "format_rom.h" +#include "acsign.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// +int ACSign_Final( + NANDHeader* header, // wb_ւ̃|C^ + void* buffer, // o͗̈ + const void* key + ); + +// +int ACSign_DigestHeader( + void* buffer, // o͗̈ + NANDHeader* header // f[^ւ̃|C^ + ); + +#ifdef __cplusplus +} +#endif + +#endif //_ACSIGN_NAND_H_ diff --git a/build/tools/acsign/include/acsign_nor.h b/build/tools/acsign/include/acsign_nor.h new file mode 100644 index 0000000..eb097b5 --- /dev/null +++ b/build/tools/acsign/include/acsign_nor.h @@ -0,0 +1,30 @@ +#ifndef _ACSIGN_NOR_H_ +#define _ACSIGN_NOR_H_ + +#include "sha.h" +#include "format_sign.h" +#include "format_rom.h" +#include "acsign.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// +int ACSign_Final( + NORHeader* header, // wb_ւ̃|C^ + void* buffer, // o͗̈ + const void* key + ); + +// +int ACSign_DigestHeader( + void* buffer, // o͗̈ + NORHeader* header // f[^ւ̃|C^ + ); + +#ifdef __cplusplus +} +#endif + +#endif //_ACSIGN_NOR_H_ diff --git a/build/tools/acsign/include/bn.h b/build/tools/acsign/include/bn.h new file mode 100644 index 0000000..f68b3d2 --- /dev/null +++ b/build/tools/acsign/include/bn.h @@ -0,0 +1,1120 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef HEADER_COMMON_BN_H +#define HEADER_COMMON_BN_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef FLAT_INC +#include "r_types.h" +#else +#include "../include/r_types.h" +#endif + +#if !defined(CCONV) +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +/* convert from the new to the old option names */ +#if defined(OPT_BN_LLONG) +#define BN_LLONG /* comment to make sure Configure leaves this alone */ +#endif + +#if defined(OPT_BN_MUL_LATENCY) +#define BN_MUL_LATENCY +#endif + +/* by default we have the following switched on - unless we have an option + * that switched them off for a specific platform + */ +#ifdef OPT_NO_COMBA +#define OPT_NO_BN_MUL_COMBA +#define OPT_NO_BN_SQR_COMBA +#endif + +#ifdef OPT_NO_REC +#define OPT_NO_BN_RECURSION_MUL +#define OPT_NO_BN_RECURSION_SQR +#endif + +#ifndef OPT_NO_BN_MUL_COMBA +#define BN_MUL_COMBA +#endif +#ifndef OPT_NO_BN_SQR_COMBA +#define BN_SQR_COMBA +#endif +#ifndef OPT_NO_BN_RECURSION_MUL +#define BN_RECURSION_MUL +#endif +#ifndef OPT_NO_BN_RECURSION_SQR +#define BN_RECURSION_SQR +#endif +#ifndef OPT_NO_BN_RECURSION_MONT +#undef BN_RECURSION_MONT /* DO NOT TURN THIS ON, IT IS BROKEN */ +#endif + +#if (!defined(OPT_NO_BN_MUL_COMBA) && !defined(OPT_NO_BN_SQR_COMBA)) +#if OPT_MONT_REDUCE_COMBA /* TEMP UNTIL C IS IMPLEMENTED-DEF'd ON PLATFORMS W/ ASM */ +#define BN_REDUCE_COMBA +#endif +#endif + +#define RECP_MUL_MOD +#define MONT_MUL_MOD + +#ifndef OPT_NO_BN_SURRENDER +#define BN_SURRENDER +#else +#undef BN_SURRENDER +#endif + +#ifdef SMALL_CODE_SIZE +#undef BN_MUL_COMBA /* stop modification */ +#undef BN_SQR_COMBA /* stop modification */ +#undef BN_REDUCE_COMBA /* stop modification */ +#undef BN_RECURSION_MUL /* stop modification */ +#undef BN_RECURSION_SQR /* stop modification */ +#undef BN_RECURSION_MONT /* stop modification */ +#endif + + + +/* This next option uses the C libraries (2 word)/(1 word) function. + * If it is not defined, I use my C version (which is slower). + * The reason for this flag is that when the particular C compiler + * library routine is used, and the library is linked with a different + * compiler, the library is missing. This mostly happens when the + * library is built with gcc and then linked using nornal cc. This would + * be a common occurance because gcc normally produces code that is + * 2 times faster than system compilers for the big number stuff. + * For machines with only one compiler (or shared libraries), this should + * be on. Again this in only really a problem on machines + * using "long long's", are 32bit, and are not using my assember code. */ +#if defined(MSDOS) || defined(WINDOWS) || defined(linux) +#define BN_DIV2W +#endif + +/* Only one for the following should be defined */ +/* The prime number generation stuff may not work when + * EIGHT_BIT but I don't care since I've only used this mode + * for debuging the bignum libraries */ +#undef SIXTY_FOUR_BIT_LONG +#undef SIXTY_FOUR_BIT +#undef SIXTY_BIT +#undef THIRTY_TWO_BIT +#undef THIRTY_BIT +#undef SIXTEEN_BIT +#undef EIGHT_BIT +#undef TEST_EIGHT_BIT + +#if defined(OPT_64_BIT_LONG) +#define SIXTY_FOUR_BIT_LONG +#endif +#if defined(OPT_64_BIT) +#define SIXTY_FOUR_BIT +#endif +#if defined(OPT_60_BIT) +#define SIXTY_BIT +#endif +#if defined(OPT_32_BIT) +#define THIRTY_TWO_BIT +#endif +#if defined(OPT_32_BIT_INT) +#define THIRTY_TWO_BIT +#endif +#if defined(OPT_30_BIT) +#define THIRTY_BIT +#endif +#if defined(OPT_16_BIT) +#define SIXTEEN_BIT +#endif +#if defined(OPT_8_BIT) +#define EIGHT_BIT +#endif +#if defined(OPT_8_BIT_TEST) +#define TEST_EIGHT_BIT +#endif + +/* This define is used for those few functions that 'break' when + * things are compiled for 8 bit words. Basically the size of an + * integer. + */ +#define BN_ILONG BN_ULONG + +/* assuming long is 64bit - this is the DEC Alpha + * unsigned long long is only 64 bits, don't define + * BN_LLONG for the DEC Alpha */ +#ifdef SIXTY_FOUR_BIT_LONG +#undef BN_LLONG +#define BN_ULLONG unsigned long long +#define BN_ULONG unsigned long +#define BN_LONG long +#define BN_BITS 128 +#define BN_BYTES 8 +#define BN_BITS2 64 +#define BN_BITS4 32 +#define BN_MASK (0xffffffffffffffffffffffffffffffffLL) +#define BN_MASK2 (0xffffffffffffffffL) +#define BN_MASK2l (0xffffffffL) +#define BN_MASK2lh (0xffffffffL) +#define BN_MASK2h (0xffffffff00000000L) +#define BN_MASK2h1 (0xffffffff80000000L) +#define BN_TBIT (0x8000000000000000L) +#define BN_DEC_CONV (10000000000000000000UL) +#define BN_DEC_FMT1 "%lu" +#define BN_DEC_FMT2 "%019lu" +#define BN_DEC_NUM 19 +#define BN_HEX_FMT "%016lX" +#endif + +/* This is where the long long data type is 64 bits, but long is 32. + * For machines where there are 64bit registers, this is the mode to use. + * IRIX, on R4000 and above should use this mode, along with the relevent + * assember code. Do NOT define BN_LLONG. + */ +#ifdef SIXTY_FOUR_BIT +#undef BN_LLONG /* Protect against config */ +/* #define BN_ULLONG unsigned long long */ +#ifdef WIN64 +#define BN_ULONG unsigned _int64 +#define BN_LONG _int64 +#else +#define BN_ULONG unsigned long long +#define BN_LONG long long +#endif +#define BN_BITS 128 +#define BN_BYTES 8 +#define BN_BITS2 64 +#define BN_BITS4 32 +#define BN_MASK2 (0xffffffffffffffffLL) +#define BN_MASK2l (0xffffffffL) +#define BN_MASK2lh (0xffffffffL) +#define BN_MASK2h (0xffffffff00000000LL) +#define BN_MASK2h1 (0xffffffff80000000LL) +#define BN_TBIT (0x8000000000000000LL) +#define BN_DEC_CONV (10000000000000000000ULL) +#ifdef WIN64 +#define BN_DEC_FMT1 "%I64u" +#define BN_DEC_FMT2 "%019I64u" +#define BN_DEC_NUM 19 +#define BN_HEX_FMT "%016I64X" +#else +#define BN_DEC_FMT1 "%llu" +#define BN_DEC_FMT2 "%019llu" +#define BN_DEC_NUM 19 +#define BN_HEX_FMT "%016llX" +#endif +#endif + +#ifdef SIXTY_BIT +#undef SIXTY_FOUR_BIT +#undef BN_LLONG /* Protect against config */ +/* #define BN_ULLONG unsigned long long */ +#define BN_ULONG unsigned long long +#define BN_LONG long long +#define BN_BITS 120 +#define BN_BITS2 60 +#define BN_BITS4 30 +#define BN_MASK2 (0x0fffffffffffffffLL) +#define BN_MASK2l ( 0x3fffffffL) +#define BN_MASK2lh ( 0x3fffffffL) +#define BN_MASK2h (0x0fffffffc0000000LL) +#define BN_MASK2h1 (0x0fffffffe0000000LL) +#define BN_TBIT (0x0800000000000000LL) +#define BN_DEC_CONV (100000000000000000LL) +#define BN_DEC_FMT1 "%9u" +#define BN_DEC_FMT2 "%017llu" +#define BN_DEC_NUM 17 +#define BN_HEX_FMT "%016llX" +#endif + +#ifdef THIRTY_TWO_BIT +#ifdef WIN32 +#if defined(__BORLANDC__) +#define BN_ULLONG unsigned __int64 +#else /* !__BORLANDC__ */ +#if defined(__MINGW32__) || defined(__DJGPP__) +#define BN_ULLONG unsigned long long +#else +#define BN_ULLONG unsigned _int64 +#endif /* __MINGW32__ || __DJGPP__ */ +#endif /* __BORLANDC__ */ +#else /* !WIN32 */ +#define BN_ULLONG unsigned long long +#endif /* WIN32 */ +#ifdef OPT_32_BIT_INT +#define BN_ULONG unsigned int +#define BN_LONG int +#else +#define BN_ULONG unsigned long +#define BN_LONG long +#endif +#define BN_BITS 64 +#define BN_BYTES 4 +#define BN_BITS2 32 +#define BN_BITS4 16 +/* This is needed because the Watcom compiler pre-processor + * under QNX tries to parses the 'LL' part even though it is + * never used. + */ +#ifdef BN_LLONG +#ifndef WIN32 +#define BN_MASK (0xffffffffffffffffLL) +#else +#define BN_MASK (0xffffffffffffffffL) +#endif +#endif +#define BN_MASK2 (0xffffffffL) +#define BN_MASK2l (0xffff) +#define BN_MASK2lh (0xffff) +#define BN_MASK2h1 (0xffff8000L) +#define BN_MASK2h (0xffff0000L) +#define BN_TBIT (0x80000000L) +#define BN_DEC_CONV (1000000000L) +#define BN_DEC_FMT1 "%lu" +#define BN_DEC_FMT2 "%09lu" +#define BN_DEC_NUM 9 +#define BN_HEX_FMT "%08lX" +#endif + +#ifdef THIRTY_BIT +#ifdef WIN32 +#if defined(__MINGW32__) || defined(__DJGPP__) +#define BN_ULLONG unsigned long long +#else /* ! (__MINGW32__ || __DJGPP__) */ +#define BN_ULLONG unsigned _int64 +#endif /* __MINGW32__ || __DJGPP__ */ +#else /* !WIN32 */ +#define BN_ULLONG unsigned long long +#endif /* WIN32 */ +#define BN_ULONG unsigned long +#define BN_LONG long +#define BN_BITS 60 +#define BN_BITS2 30 +#define BN_BITS4 15 +/* This is needed because the Watcom compiler pre-processor + * under QNX tries to parses the 'LL' part even though it is + * never used. + */ +#ifdef BN_LLONG +#ifndef WIN32 +#define BN_MASK (0x0fffffffffffffffLL) +#else +#define BN_MASK (0x0fffffffffffffffL) +#endif +#endif +#define BN_MASK2 (0x3fffffffL) +#define BN_MASK2l (0x7fff) +#define BN_MASK2lh (0x7fff) +#define BN_MASK2h1 (0x3fffc000L) +#define BN_MASK2h (0x3fff8000L) +#define BN_TBIT (0x20000000L) +#define BN_DEC_CONV (1000000000L) +#define BN_DEC_FMT1 "%lu" +#define BN_DEC_FMT2 "%09lu" +#define BN_DEC_NUM 9 +#define BN_HEX_FMT "%08lX" +#endif + +#ifdef SIXTEEN_BIT +#ifndef BN_DIV2W +#define BN_DIV2W +#endif +#define BN_ULLONG unsigned long +#define BN_ULONG unsigned short +#define BN_LONG short +#define BN_BITS 32 +#define BN_BYTES 2 +#define BN_BITS2 16 +#define BN_BITS4 8 +#define BN_MASK (0xffffffff) +#define BN_MASK2 (0xffff) +#define BN_MASK2l (0xff) +#define BN_MASK2lh (0xff) +#define BN_MASK2h1 (0xff80) +#define BN_MASK2h (0xff00) +#define BN_TBIT (0x8000) +#define BN_DEC_CONV (10000) +#define BN_DEC_FMT1 "%u" +#define BN_DEC_FMT2 "%04u" +#define BN_DEC_NUM 4 +#define BN_HEX_FMT "%04X" +#endif + +#ifdef TEST_EIGHT_BIT +#define EIGHT_BIT /* comment to stop editing */ +#endif + +#ifdef EIGHT_BIT +#undef BN_ILONG +#define BN_ILONG unsigned int +#ifndef BN_DIV2W +#define BN_DIV2W +#endif +#ifdef TEST_EIGHT_BIT +#define BN_ULLONG unsigned int +#define BN_ULONG unsigned int +#define BN_LONG int +#else +#define BN_ULLONG unsigned short +#define BN_ULONG unsigned char +#define BN_LONG char +#endif +#define BN_BITS 16 +#define BN_BYTES 1 +#define BN_BITS2 8 +#define BN_BITS4 4 +#define BN_MASK (0xffff) +#define BN_MASK2 (0xff) +#define BN_MASK2lh (0xf) +#define BN_MASK2l (0xf) +#define BN_MASK2h1 (0xf8) +#define BN_MASK2h (0xf0) +#define BN_TBIT (0x80) +#define BN_DEC_CONV (100) +#define BN_DEC_FMT1 "%u" +#define BN_DEC_FMT2 "%02u" +#define BN_DEC_NUM 2 +#define BN_HEX_FMT "%02X" +#endif + +#ifdef BIGNUM +#undef BIGNUM +#endif + +#define BN_FLG_MALLOCED 0x01 +#define BN_FLG_STATIC_DATA 0x02 +#define BN_FLG_FREE 0x8000 /* used for debuging */ +#define BN_CTX_FLG_ABORT 0x4000 /* used for aborting RSA operations*/ +#define BN_set_flags(b,n) ((b)->flags|=(n)) +#define BN_get_flags(b,n) ((b)->flags&(n)) +#define BN_CTX_set_flags(b,n) ((b)->flags|=(n)) +#define BN_CTX_get_flags(b,n) ((b)->flags&(n)) + +#ifndef HEADER_COMMON_BN_H_TYPEDEF_DEF +#define HEADER_COMMON_BN_H_TYPEDEF_DEF +typedef struct bignum_st BIGNUM; +typedef struct bignum_ctx BN_CTX; +typedef struct bn_mont_ctx_st BN_MONT_CTX; +typedef struct bn_recp_ctx_st BN_RECP_CTX; +typedef struct bn_prime_ctx_st BN_PRIME_CTX; +typedef struct bn_blind_ctx_st BN_BLIND_CTX; +typedef struct bn_blind_meth_st BN_BLIND_METH; +#endif + +typedef struct bn_mod_exp_meth_st BN_ME_METH; +typedef struct bn_mod_exp_ctx_st BN_ME_CTX; + + +/* The data array d must always have an extra 'valid' word in location + * bn->d[bn->max]. It must be ok for reading. This is needed if + * BN_MUL_LATENCY is defined. + */ +struct bignum_st + { + BN_ULONG *d; /* Pointer to an array of 'BN_BITS2' bit chunks. */ + int top; /* Index of last used d +1. */ + /* The next are internal book keeping for bn_expand. */ + int max; /* Size of the d array. */ + int neg; /* one if the number is negative */ + int flags; + }; + +/* Used for temp variables */ +#define BN_CTX_NUM 12 +struct bignum_ctx + { + int tos; + BIGNUM bn[BN_CTX_NUM+1]; + int flags; + R_SURRENDER *surrender; + }; + +#if defined(WIN64) || defined(__ia64__) || defined(CPU_IA64) +#define BN_USHORT unsigned int +#else +#define BN_USHORT unsigned short +#endif + +/* Used for prime number generation */ +struct bn_prime_ctx_st + { + BN_USHORT *primes; + BN_USHORT *mods; + int num_primes; + int prime_checks; + R_SURRENDER *surrender; + R_RANDOM *random; + int flags; + }; + +struct bn_blind_ctx_st + { + int init; + BN_BLIND_METH *meth; + BIGNUM B; + BIGNUM Bi; + BIGNUM mod; + }; + +struct bn_blind_meth_st + { + void (*init) (BN_BLIND_CTX *); + void (*ctx_free)(BN_BLIND_CTX *); + int (*set) (BN_BLIND_CTX *,R_RANDOM *,BIGNUM *,BIGNUM *, BN_ME_CTX *,BN_CTX *); + int (*convert) (BN_BLIND_CTX *,BIGNUM *,BN_CTX *); + int (*invert) (BN_BLIND_CTX *,BIGNUM *,BN_CTX *); + int (*update) (BN_BLIND_CTX *,BN_CTX *); + int (*copy) (BN_BLIND_CTX *,BN_BLIND_CTX *); + }; + +/* Used for montgomery multiplication */ +struct bn_mont_ctx_st + { + int use_word; /* 0 for word form, 1 for long form */ + int ri; /* number of bits in R */ + int riw; /* number of words in R */ + BIGNUM RR; /* used to convert to montgomery form */ + BIGNUM N; /* The modulus */ + BIGNUM Ni; /* The inverse of N */ + BN_ULONG n0; /* word form of inverse, normally only one of + * Ni or n0 is defined */ + int flags; + }; + +/* Used by the recursive exponentiation implementations */ +typedef struct bn_mod_exp_rec_meth_st + { +#ifndef NOPROTO + void (PRE_CCONV CCONV *mul)(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); + void (PRE_CCONV CCONV *sqr)(BN_ULONG *r, BN_ULONG *a); + void (PRE_CCONV CCONV *low_mul)(); +#else + void (PRE_CCONV CCONV *mul)(); + void (PRE_CCONV CCONV *sqr)(); + void (PRE_CCONV CCONV *low_mul)(); +#endif + } BN_MOD_EXP_REC_METH; + +/* If this flag is set, if there is a custom method for a modulus + * two times larger, use it. This is mostly mean for use on the + * itanium where a 512*512 routine is 10 times faster than the C + * code version, so we need to detect that we can turn of CRT + * for RSA if there is an native IA64 512*512 present. + */ +#define BN_ME_FLG_FAST_ASM 0x0001 + +struct bn_mod_exp_meth_st + { + int num; /* Word size we target */ + char *name; /* Identify the method */ +#ifndef NOPROTO + int (*useit)(const BN_ME_METH *meth); + /* If 'power' is null, reuse the old one */ + int (*mod_exp)(BN_ME_CTX *mctx,BIGNUM *r,BIGNUM *a,BIGNUM *p, + BN_CTX *ctx); + /* Create the BN_ME_CTX */ + int (*init_ctx)(const BN_ME_METH *meth,BN_ME_CTX **mctx); + /* Get rid of it */ + int (*free_ctx)(BN_ME_CTX *mctx); + /* Assign the modulus */ + int (*set)(BN_ME_CTX *mctx,BIGNUM *n,int cmd,int flags,BN_CTX *ctx); +#else + int (*useit)(); + int (*mod_exp)(); + int (*init_ctx)(); + int (*free_ctx)(); + int (*set)(); +#endif + int argi; + char *argp; /* 'Extra stuff' */ + }; + +#define BN_ME_METH_TABLE_MAX 32 +/* Used in BN_library_init */ +#define BN_INIT_LAST 0x00 +#define BN_INIT_BN_ME_METH 0x01 + +#define BN_BNME_F_DEFAULT 0x01 +/* Used only when loading, kept as bits internally, normally loaded as + * words */ +#define BN_BNME_F_BITS 0x02 +typedef struct bn_me_meth_info_st + { +#ifndef NOPROTO + const BN_ME_METH *(*meth)(void); +#else + const BN_ME_METH *(*meth)(); +#endif + int min; + int max; + int flags; + } BN_ME_METH_INFO; + +#define BN_ME_SET_MOD 0x01 +#define BN_ME_SET_BASE 0x02 +#define BN_ME_SET_EXP 0x03 +#define BN_ME_SET_FLG_NO_LOOKUP 0x01 /* Passed to BN_ME_CTX_set() */ + +#define BN_FLG_CACHE 0x10 /* Cache values */ +#define BN_ME_FLG_BASE 0x40 /* base has been cached */ +#define BN_ME_FLG_EXP 0x80 /* power has been cached */ +/* When one of these structures is setup, it is intended that the + * base or power, if not null, will be used for the current calculation. + * If the base and/or power are cached, they will only be used if the input + * value is null. + * For RSA, the power would normally be set. + * For DH, the base and power would be set. The initial value generated + * would be the public key, which is exchanged. The phase2 part would + * change the base but not the power. + * For DSA signing, a fixed base is used, but a random power. + * For DSA verification, there are two bases and two powers, + * a^p%m * b^q%m + * One way to implement this is to use a special function to + * generate a composite power value, and or a special base form. + * The other option is to have a special function to generate + * the 'base' array. The problem is that we are exponentiating with + * a 3 value power value, instead of the normal two. It should be possible + * to use the standard a^b%m function. + */ +struct bn_mod_exp_ctx_st + { + const BN_ME_METH *meth; + char *callback; + char *cb_arg; + int flags; + /* Evil hack for storage of data values, it should really be here + * other than the first value */ + char *modulus; /* eg BN_MONT_CTX */ + char *power; /* eg power representation */ + char *base; /* eg base representation */ + char *arg; + }; + +/* Used for reciprocal division/mod functions + * It cannot be shared between threads + */ +struct bn_recp_ctx_st + { + BIGNUM N; /* the divisor */ + BIGNUM Nr; /* the reciprocal */ + int num_bits; + int shift; + int flags; + }; + +typedef struct bn_rec_st + { + int depth; + int n; +#ifndef NOPROTO + void (PRE_CCONV CCONV *mul)(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b); + void (PRE_CCONV CCONV *sqr)(BN_ULONG *r, BN_ULONG *a); + void (PRE_CCONV CCONV *low_mul)(); +#else + void (PRE_CCONV CCONV *mul)(); + void (PRE_CCONV CCONV *sqr)(); + void (PRE_CCONV CCONV *low_mul)(); +#endif + } BN_REC; + +#define BN_to_montgomery(r,a,mont,ctx) BN_mod_mul_montgomery(\ + r,a,&((mont)->RR),(mont),ctx) + +#define BN_prime_checks (5) + +#define BN_num_bytes(a) ((BN_num_bits(a)+7)/8) +#define BN_length(a) ((a)->top * BN_BYTES) +#define BN_is_word(a,w) (((a)->top == 1) && ((a)->d[0] == (BN_ULONG)(w))) +#define BN_is_zero(a) (((a)->top == 0) || BN_is_word(a,0)) +#define BN_is_one(a) (BN_is_word((a),1)) +#define BN_is_odd(a) (((a)->top > 0) && ((a)->d[0] & 1)) +#define BN_one(a) (BN_set_word((a),(BN_ULONG)1)) +#define BN_zero(a) (BN_set_word((a),(BN_ULONG)0)) + +/*#define BN_ascii2bn(a) BN_hex2bn(a) */ +/*#define BN_bn2ascii(a) BN_bn2hex(a) */ + +#define bn_expand(n,b) ((((((b+BN_BITS2-1))/BN_BITS2)) <= (n)->max)?\ + (n):bn_expand2((n),(b)/BN_BITS2+1)) +#define bn_wexpand(n,b) (((b) <= (n)->max)?(n):bn_expand2((n),(b))) + +#ifdef SMALL_CODE_SIZE +void bn_zexpand(BIGNUM *a,int n); +void bn_fix_top(BIGNUM *a); +#else +#define bn_zexpand(a,n) \ + if ((a)->top < n) \ + { \ + int i; \ + bn_wexpand((a),n); \ + if ((a)->d!=NULL) \ + { \ + for (i=(a)->top; id[i]=0; \ + } \ + } + +#define bn_fix_top(a) \ + { \ + BN_ULONG *ftl; \ + if ((a)->top > 0) \ + { \ + for (ftl= &((a)->d[(a)->top-1]); (a)->top > 0; (a)->top--) \ + if (*(ftl--)) break; \ + } \ + } +#endif + +#define BN_MONT_CTX_set(a,b,c) BN_MONT_CTX_set_word((a),(b),(c)) + +#ifndef NOPROTO + + +const BN_ME_METH *BN_ME_METH_word(void); +const BN_ME_METH *BN_ME_METH_full(void); + +#if (defined(BN_MUL_COMBA) || defined(BN_SQR_COMBA)) + +/* word4 - used for 64bit multiprime*/ +const BN_ME_METH *BN_ME_METH_word4(void); +const BN_ME_METH *BN_ME_METH_rec4_word8(void); +const BN_ME_METH *BN_ME_METH_rec4_word16(void); +const BN_ME_METH *BN_ME_METH_rec4_word32(void); +const BN_ME_METH *BN_ME_METH_rec4_word64(void); +const BN_ME_METH *BN_ME_METH_rec4_word128(void); + +/* word6 - used for 64bit multiprime*/ +const BN_ME_METH *BN_ME_METH_word6(void); +const BN_ME_METH *BN_ME_METH_rec6_word12(void); +const BN_ME_METH *BN_ME_METH_rec6_word24(void); +const BN_ME_METH *BN_ME_METH_rec6_word48(void); +const BN_ME_METH *BN_ME_METH_rec6_word96(void); + +const BN_ME_METH *BN_ME_METH_word8(void); +const BN_ME_METH *BN_ME_METH_rec8_word16(void); +const BN_ME_METH *BN_ME_METH_rec8_word32(void); +const BN_ME_METH *BN_ME_METH_rec8_word64(void); +const BN_ME_METH *BN_ME_METH_rec8_word128(void); +const BN_ME_METH *BN_ME_METH_rec8_word256(void); + +const BN_ME_METH *BN_ME_METH_word11(void); +const BN_ME_METH *BN_ME_METH_rec11_word22(void); +const BN_ME_METH *BN_ME_METH_rec11_word44(void); +const BN_ME_METH *BN_ME_METH_rec11_word88(void); + +const BN_ME_METH *BN_ME_METH_word16(void); +const BN_ME_METH *BN_ME_METH_rec16_word32(void); +const BN_ME_METH *BN_ME_METH_rec16_word64(void); +const BN_ME_METH *BN_ME_METH_rec16_word128(void); +const BN_ME_METH *BN_ME_METH_rec16_word256(void); + +#endif + +#ifdef CPU_IA64 +const BN_ME_METH *BN_ME_METH_ia64_384(void); +const BN_ME_METH *BN_ME_METH_ia64_512(void); +const BN_ME_METH *BN_ME_METH_ia64_1024(void); +#endif + +#if (defined(CPU_SPARC_V8PLUS) || defined (CPU_SPARC_V9)) +const BN_ME_METH *BN_ME_METH_usparc(void); +const BN_ME_METH *BN_ME_METH_usparc_352(void); +const BN_ME_METH *BN_ME_METH_usparc_512(void); +#endif + +#if 1 || defined(CPU_X86) +const BN_ME_METH *BN_ME_METH_pentium4_29(void); +const BN_ME_METH *BN_ME_METH_pentium4_28(void); +#endif + +/* NCipher Nfast hardware accelerator method prototype */ +const BN_ME_METH *BN_ME_METH_nfast(void); + + +BIGNUM *BN_value_one(void); +const char * BN_options(void); +BN_CTX *BN_CTX_new(void); +void BN_CTX_init(BN_CTX *c); +void BN_CTX_free(BN_CTX *c); +#ifndef NO_BN_RAND +int BN_rand(BIGNUM *rnd, R_RANDOM *rand, int bits, int top,int bottom); +#endif +int BN_num_bits(BIGNUM *a); +int BN_num_bits_word(BN_ILONG); +BIGNUM *BN_new(void); +void BN_init(BIGNUM *); +void BN_clear_free(BIGNUM *a); +BIGNUM *BN_copy(BIGNUM *a, BIGNUM *b); +BIGNUM *BN_bin2bn(unsigned char *s,int len,BIGNUM *ret); +int BN_bn2bin(BIGNUM *a, unsigned char *to); +BIGNUM *BN_mpi2bn(unsigned char *s,int len,BIGNUM *ret); +int BN_bn2mpi(BIGNUM *a, unsigned char *to); +int BN_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_usub(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_uadd(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_add(BIGNUM *r, BIGNUM *a, BIGNUM *b); +int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx); +int BN_div(BIGNUM *dv, BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx); +int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b,BN_CTX *ctx); +int BN_sqr(BIGNUM *r, BIGNUM *a,BN_CTX *ctx); +BN_ULONG BN_mod_word(BIGNUM *a, BN_ULONG w); +BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w); +int BN_mul_word(BIGNUM *a, BN_ULONG w); +int BN_add_word(BIGNUM *a, BN_ULONG w); +int BN_sub_word(BIGNUM *a, BN_ULONG w); +int BN_set_word(BIGNUM *a, BN_ULONG w); +BN_ULONG BN_get_word(BIGNUM *a); +int BN_cmp(BIGNUM *a, BIGNUM *b); +void BN_free(BIGNUM *a); +int BN_is_bit_set(BIGNUM *a, int n); +int BN_lshift(BIGNUM *r, BIGNUM *a, int n); +int BN_lshift1(BIGNUM *r, BIGNUM *a); +int BN_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p,BN_CTX *ctx); +int BN_mod_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx); +int BN_mod_exp_mont(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx, + BN_MONT_CTX *m_ctx); +int BN_mod_exp2_mont(BIGNUM *r, BIGNUM *a1, BIGNUM *p1,BIGNUM *a2, + BIGNUM *p2,BIGNUM *m,BN_CTX *ctx,BN_MONT_CTX *m_ctx); +int BN_mod_exp_simple(BIGNUM *r, BIGNUM *a, BIGNUM *p, + BIGNUM *m,BN_CTX *ctx); +int BN_mask_bits(BIGNUM *a,int n); +int BN_mod_mul(BIGNUM *ret, BIGNUM *a, BIGNUM *b, BIGNUM *m, + BN_CTX *ctx); +#if !defined(WIN16) && !defined(NO_FP_API) +int BN_print_fp(FILE *fp, BIGNUM *a); +#endif +#ifdef HEADER_COMMON_BIO_H +int BN_print(BIO *fp, BIGNUM *a); +#else +/* int BN_print(char *fp, BIGNUM *a); */ +#endif +int BN_reciprocal(BIGNUM *r, BIGNUM *m, int len, BN_CTX *ctx); +int BN_rshift(BIGNUM *r, BIGNUM *a, int n); +int BN_rshift1(BIGNUM *r, BIGNUM *a); +void BN_clear(BIGNUM *a); +BIGNUM *bn_expand2(BIGNUM *b, int bits); +BIGNUM *BN_dup(BIGNUM *a); +int BN_ucmp(BIGNUM *a, BIGNUM *b); +int BN_set_bit(BIGNUM *a, int n); +int BN_clear_bit(BIGNUM *a, int n); +char * BN_bn2hex(BIGNUM *a); +char * BN_bn2dec(BIGNUM *a); +int BN_hex2bn(BIGNUM **a,char *str); +int BN_dec2bn(BIGNUM **a,char *str); +int BN_gcd(BIGNUM *r,BIGNUM *in_a,BIGNUM *in_b,BN_CTX *ctx); +BIGNUM *BN_mod_inverse(BIGNUM *ret,BIGNUM *a, BIGNUM *n,BN_CTX *ctx); +/* Return R, where it is R*(1< +#include +//#include "r_error.h" +//#include "err.h" +#include + +#ifndef STANDALONE +#include "r_com.h" +#else +#define NO_STDLIB_MAPPING +#define Malloc(a) malloc(a) +#define Free(a) free(a) +#define Memset(a,b,c) memset(a,b,c) +#define Memcpy(a,b,c) memcpy(a,b,c) +#endif + +/* TEMP FIX */ +#undef BNerr +#define BNerr(a,b) +#include "bn.h" + +#define BN_EXP_TABLE_SIZE 16 + +/* see the bn_limit_ fields which are the start of a runtime + * tunable set of values to match these fixed compile-time constants + */ +/* Pentium pro 16,16,16,32,64 */ +/* Alpha 16,16,16,16.64 */ +/* StrongARM */ +#define BN_MULL_SIZE_NORMAL (16) /* 32 */ +#define BN_MUL_RECURSIVE_SIZE_NORMAL (16) /* 32 */ /* less than */ +#define BN_SQR_RECURSIVE_SIZE_NORMAL (16) /* 32 */ +#define BN_MUL_LOW_RECURSIVE_SIZE_NORMAL (32) /* 32 */ +#define BN_MONT_CTX_SET_SIZE_WORD (64) /* 32 */ + +/************************************************************* + * Using the long long type + */ +#define Lw(t) (((BN_ULONG)(t))&BN_MASK2) +#define Hw(t) (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2) + +/* These are used for internal error checking and are not normally used */ +#ifdef BN_DEBUG +#define bn_check_top(a) \ + { if ( ((a)->top < 0) || \ + ((a)->top > (a)->max) || \ + (((a)->top == 0) && (a)->neg) || \ + (((a)->top == 1) && (a->d[0] == 0))) \ + { char *nullp=NULL; *nullp='z'; } } +#define bn_check_num(a) if ((a) < 0) { char *nullp=NULL; *nullp='z'; } +#define bn_assert(a) if (!(a)) { char *nullp=NULL; *nullp='z'; } +#define bn_set_used_check(l,size,num) bn_su_check(l,size,num) +#ifdef BN_DEBUG2 +#define bn_do_used_check(fp,str,l,size,num) bn_du_check(fp,str,l,size,num) +#else +#define bn_do_used_check(fp,str,l,size,num) +#endif +#else +#define bn_assert(a) +#define bn_check_top(a) +#define bn_check_num(a) +#define bn_set_used_check(l,size,num) +#define bn_do_used_check(fp,str,l,size,num) +#endif + + +/*********************************************** +* IA64 32 bit build SWIZZLE code +* This essentially casts our points which are +* 32bits under abi32 to 64bit unsigned long +* longs and then grabs the top two bits of the +* pointer and places it in the 2nd and 3rd bits +* of the unsigned long long. +**********************************************/ +#ifdef HPUX_IA64_32 +#define SWIZLLE(VALUE) ((((unsigned long long)(VALUE) & 0xc0000000LL) <<31)\ +|((unsigned long long)(VALUE))) +#else +#define SWIZZLE(VALUE) (VALUE) +#endif + +#define bn_neg_words(a,n) \ + { \ + int iii; \ + \ + for (iii=0; iiimax=(r)->top,BN_set_flags((r),BN_FLG_STATIC_DATA)) +#else +#define bn_set_max(r) +#endif + +/* These macros are used to 'take' a section of a bignum for read only use */ +#define bn_set_low(r,a,n) \ + { \ + (r)->top=((a)->top > (n))?(n):(a)->top; \ + (r)->d=(a)->d; \ + (r)->neg=(a)->neg; \ + (r)->flags|=BN_FLG_STATIC_DATA; \ + bn_set_max(r); \ + } + +#define bn_set_high(r,a,n) \ + { \ + if ((a)->top > (n)) \ + { \ + (r)->top=(a)->top-n; \ + (r)->d= &((a)->d[n]); \ + } \ + else \ + (r)->top=0; \ + (r)->neg=(a)->neg; \ + (r)->flags|=BN_FLG_STATIC_DATA; \ + bn_set_max(r); \ + } + +/* #define bn_expand(n,b) ((((b)/BN_BITS2) <= (n)->max)?(n):bn_expand2((n),(b))) */ + +#ifdef BN_LLONG +#define mul_add(r,a,w,c) { \ + BN_ULLONG t; \ + t=(BN_ULLONG)w * (a) + (r) + (c); \ + (r)= Lw(t); \ + (c)= Hw(t); \ + } + +#define mul(r,a,w,c) { \ + BN_ULLONG t; \ + t=(BN_ULLONG)w * (a) + (c); \ + (r)= Lw(t); \ + (c)= Hw(t); \ + } + +#else +/************************************************************* + * No long long type + */ + +#define LBITS(a) ((a)&BN_MASK2l) +#define HBITS(a) (((a)>>BN_BITS4)&BN_MASK2lh) +#define L2HBITS(a) ((BN_ULONG)((a)&BN_MASK2lh)<>(BN_BITS4-1); \ + m =((m&BN_MASK2l)<<(BN_BITS4+1))&BN_MASK2; \ + l=(l+m)&BN_MASK2; if (l < m) h++; \ + (lo)=l; \ + (ho)=h; \ + } + +#if 0 +#define mul_add(r,a,bl,bh,b_hl,c) { \ + BN_ULONG l,h; \ + BN_ULONG lt,mt; \ + \ + h= (a); \ + l=LBITS(h); \ + h=HBITS(h); \ + mt=bl*l; \ + lt=mt+c+(r); \ + c=bh*h; \ + mt+=c+(l-h)*b_hl; \ + mt+=(lt>>BN_BITS4); \ + (r)=(lt&BN_MASK2l)|((mt&BN_MASK2l)<>BN_BITS4); \ + } +#else /* Normal version */ +#define mul_add(r,a,bl,bh,b_hl,c) { \ + BN_ULONG l,h; \ + \ + h= (a); \ + l=LBITS(h); \ + h=HBITS(h); \ + mul64(l,h,(bl),(bh)); \ + \ + /* non-multiply part */ \ + l=(l+(c))&BN_MASK2; if (l < (c)) h++; \ + (c)=(r); \ + l=(l+(c))&BN_MASK2; if (l < (c)) h++; \ + (c)=h&BN_MASK2; \ + (r)=l; \ + } +#endif + +#define mul(r,a,bl,bh,c) { \ + BN_ULONG l,h; \ + \ + h= (a); \ + l=LBITS(h); \ + h=HBITS(h); \ + mul64(l,h,(bl),(bh)); \ + \ + /* non-multiply part */ \ + l+=(c); if ((l&BN_MASK2) < (c)) h++; \ + (c)=h&BN_MASK2; \ + (r)=l&BN_MASK2; \ + } + +#endif + +#ifndef BN_MUL_COMBA +#define bn_mul_comba4(r,a,b) bn_mul_normal(r,a,4,b,4) +#define bn_mul_comba5(r,a,b) bn_mul_normal(r,a,5,b,5) +#define bn_mul_comba6(r,a,b) bn_mul_normal(r,a,6,b,6) +#define bn_mul_comba8(r,a,b) bn_mul_normal(r,a,8,b,8) +#define bn_mul_comba11(r,a,b) bn_mul_normal(r,a,11,b,11) +#define bn_mul_comba12(r,a,b) bn_mul_normal(r,a,12,b,12) +#define bn_mul_comba16(r,a,b) bn_mul_normal(r,a,16,b,16) +#endif +#if 1 +#ifndef BN_SQR_COMBA +#define bn_sqr_comba4(r,a) bn_mul_normal(r,a,4,a,4) +#define bn_sqr_comba5(r,a) bn_mul_normal(r,a,5,a,5) +#define bn_sqr_comba6(r,a) bn_mul_normal(r,a,6,a,6) +#define bn_sqr_comba8(r,a) bn_mul_normal(r,a,8,a,8) +#define bn_sqr_comba11(r,a) bn_mul_normal(r,a,11,a,11) +#define bn_sqr_comba12(r,a) bn_mul_normal(r,a,12,a,12) +#define bn_sqr_comba16(r,a) bn_mul_normal(r,a,16,a,16) +#endif +#else +#ifndef BN_SQR_COMBA +#define bn_sqr_comba4(r,a) bn_mul_comba4(r,a,a) +#define bn_sqr_comba5(r,a) bn_mul_comba5(r,a,a) +#define bn_sqr_comba6(r,a) bn_mul_comba6(r,a,a) +#define bn_sqr_comba8(r,a) bn_mul_comba8(r,a,a) +#define bn_sqr_comba11(r,a) bn_mul_comba11(r,a,a) +#define bn_sqr_comba12(r,a) bn_mul_comba12(r,a,a) +#define bn_sqr_comba16(r,a) bn_mul_comba16(r,a,a) +#endif +#endif +#ifndef BN_REDUCE_COMBA +#define r0_bn_mont_comba4(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba5(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba6(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba8(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba11(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba12(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#define r0_bn_mont_comba16(r,a,n,num,n0) bn_from_montgomery_words(r,a,n,num,n0) +#endif + +#ifndef NOPROTO + +BIGNUM *bn_expand2(BIGNUM *b, int bits); + +#ifdef X86_ASM +void bn_add_words(BN_ULONG *r,BN_ULONG *a,int num); +#endif + +#else + +BIGNUM *bn_expand2(); +#ifdef X86_ASM +BN_ULONG bn_add_words(); +#endif + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_BN_LCL_H */ + +void bn_mul_low_recursive(BN_ULONG *r,BN_ULONG *a,BN_ULONG *b,int n2,BN_ULONG *t); +void bn_mul_high(BN_ULONG *r,BN_ULONG *a,BN_ULONG *b,BN_ULONG *l,int n2, BN_ULONG *t); +int BN_gen_exp_string(unsigned char *str, BIGNUM *p, int bits); +void bn_from_montgomery_rec_full(BN_ULONG *rp, BN_ULONG *ap, + BN_ULONG *np, BN_ULONG *nip, BN_ULONG *tmp,BN_REC *rec); + +int bn_mont_ctx_new_word(const BN_ME_METH *meth, BN_ME_CTX **retp); + diff --git a/build/tools/acsign/include/bn_thx.h b/build/tools/acsign/include/bn_thx.h new file mode 100644 index 0000000..13e157b --- /dev/null +++ b/build/tools/acsign/include/bn_thx.h @@ -0,0 +1,301 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/***************************************************************************** + * Copyright (c). 2001 RSA Security Inc. All rights reserved. + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + ****************************************************************************/ +/** + * @file bn_thx.h + * @brief header file created for used as interface defines for systems + * containing hetergeneous environments where some bn operations + * will be performed in isolation from the rest of the library + */ +#ifndef HEADER_COMMON_BN_THX_H +#define HEADER_COMMON_BN_THX_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* These defines are required on systems so that the mod_exp code + * to be used in isolation from the bn operation with library will work, + * if these are not available, the header files with equivalent functionality + * should be added inside a CPU or Operating system define + */ +#ifndef NO_STDIO_H +#include +#endif + +#ifndef NO_STDLIB_H +#include +#endif + +#ifndef NO_STRING_H +#include +#endif + +/* Interface for ARM/DSP systems, this interface requires only + * the standard defines and includes at the moment + */ +#ifdef CPU_TMS320 +#define THX_RECIPIENT +#define CPU_DSP +#endif + +#ifdef THX_RECIPIENT + +#ifndef restrict +#define restrict +#endif + +#ifndef Malloc +#define Malloc malloc +#endif + +#ifndef Memcpy +#define Memcpy memcpy +#endif + +#ifndef Memmove +#define Memmove memmove +#endif + +#ifndef Memset +#define Memset memset +#endif + +#ifndef Free +#define Free free +#endif + +#endif /* THX_RECIPIENT */ + +#ifndef THX_RECIPIENT /* not the recipient, we must be the caller */ + +#include "bn_lcl.h" + +#endif /* ! THX_RECIPIENT */ + +/* The follow define protected inclusions are excerpts from the + * header file bn.h, this has been done, so that code written for the + * THX systems can be used in isolation from the library + * This code may need to be updated in line with changes to the bn.h + * header file. + */ +#ifndef HEADER_COMMON_BN_H +#define HEADER_COMMON_BN_H + +#if !defined(CCONV) +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +/* convert from the new to the old option names */ +#if defined(OPT_BN_LLONG) +#define BN_LLONG /* comment to make sure Configure leaves this alone */ +#endif + +#if defined(OPT_32_BIT_INT) || defined(OPT_32_BIT) +#define THIRTY_TWO_BIT +#endif + +#define BN_ILONG BN_ULONG + +#ifdef THIRTY_TWO_BIT +#define BN_ULLONG unsigned long long +#ifdef OPT_32_BIT_INT +#define BN_ULONG unsigned int +#define BN_LONG int +#else +#define BN_ULONG unsigned long +#define BN_LONG long +#endif +#define BN_BITS 64 +#define BN_BYTES 4 +#define BN_BITS2 32 +#define BN_BITS4 16 +/* This is needed because the Watcom compiler pre-processor + * under QNX is perverted and tries to parses the 'LL' + * part even though it is never used. + */ +#ifdef BN_LLONG +#define BN_MASK (0xffffffffffffffffL) +#endif +#define BN_MASK2 (0xffffffffL) +#define BN_MASK2l (0xffff) +#define BN_MASK2lh (0xffff) +#define BN_MASK2h1 (0xffff8000L) +#define BN_MASK2h (0xffff0000L) +#define BN_TBIT (0x80000000L) +#define BN_DEC_CONV (1000000000L) +#define BN_DEC_FMT1 "%lu" +#define BN_DEC_FMT2 "%09lu" +#define BN_DEC_NUM 9 +#define BN_HEX_FMT "%08lX" +#endif + +#define BN_EXP_TABLE_SIZE 16 + +typedef struct bignum_st BIGNUM; + +struct bignum_st + { + BN_ULONG *d; /* Pointer to an array of 'BN_BITS2' bit chunks. */ + int top; /* Index of last used d +1. */ + /* The next are internal book keeping for bn_expand. */ + int max; /* Size of the d array. */ + int neg; /* one if the number is negative */ + int flags; + }; + +PRE_CCONV BN_ULONG CCONV bn_mul_add_words(BN_ULONG *rp,BN_ULONG *ap, + int num, BN_ULONG w); +PRE_CCONV BN_ULONG CCONV bn_mul_words(BN_ULONG *rp, BN_ULONG *ap, + int num, BN_ULONG w); +PRE_CCONV void CCONV bn_sqr_words(BN_ULONG *rp, BN_ULONG *ap, int num); +BN_ULONG CCONV bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d); +PRE_CCONV BN_ULONG CCONV bn_add_words(BN_ULONG *rp, BN_ULONG *ap, + BN_ULONG *bp,int num); +PRE_CCONV BN_ULONG CCONV bn_sub_words(BN_ULONG *rp, BN_ULONG *ap, + BN_ULONG *bp,int num); + +#ifndef BN_ME_METH +#define BN_ME_METH void +#endif + +#endif /* ! HEADER_COMMON_BN_H */ + +/* The follow define protected inclusions are excerpts from the + * header file r_error.h, this has been done, so that code written for the + * THX systems can be used in isolation from the library + * This code may need to be updated in line with changes to the r_error.h + * header file. + */ +#ifndef HEADER_COMMON_R_ERROR_H +#define HEADER_COMMON_R_ERROR_H + +/* The FATAL_INTERNAL_ERROR is a flag that is set with the following + * error codes: + * R_ERROR_INVALID_STATE + * R_ERROR_INIT_NOT_CALLED + * R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED + */ +#define R_ERROR_FATAL_INTERNAL_ERROR 64 + +/* The BAD_PARAMETER is a flag that is set with the following error + * codes: + * R_ERROR_NULL_ARG + * R_ERROR_BUFFER_TOO_SMALL + * R_ERROR_BAD_VALUE + * R_ERROR_BAD_RANGE + * R_ERROR_BAD_FORMAT + * R_ERROR_BAD_TYPE + * R_ERROR_BAD_DATA + * R_ERROR_BAD_LENGTH + */ +#define R_ERROR_BAD_PARAMETER 32 + +/* Base value for all general errors used through all products */ +#define R_ERROR_BASE 10000 + +#define R_ERROR_NONE 0 + +#define R_ERROR_FAILED (R_ERROR_BASE+1) +#define R_ERROR_IO (R_ERROR_BASE+2) +#define R_ERROR_PROTOCOL (R_ERROR_BASE+3) +#define R_ERROR_EOF (R_ERROR_BASE+4) +#define R_ERROR_ALLOC_FAILURE (R_ERROR_BASE+5) +#define R_ERROR_EVAL_RESTRICTION (R_ERROR_BASE+6) +#define R_ERROR_EVAL_EXPIRED (R_ERROR_BASE+7) +#define R_ERROR_NOT_FOUND (R_ERROR_BASE+8) +#define R_ERROR_NOT_AVAILABLE (R_ERROR_BASE+9) +#define R_ERROR_NOT_IMPLEMENTED (R_ERROR_BASE+10) +#define R_ERROR_NOT_SUPPORTED (R_ERROR_BASE+11) +#define R_ERROR_INVALID_STATE \ + ((R_ERROR_BASE+12) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_INIT_NOT_CALLED \ + ((R_ERROR_BASE+13) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED \ + ((R_ERROR_BASE+14) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_METHOD_UNDEFINED \ + ((R_ERROR_BASE+15) | R_ERROR_FATAL_INTERNAL_ERROR) +#define R_ERROR_BUFFER_TOO_SMALL \ + ((R_ERROR_BASE+16) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_NULL_ARG ((R_ERROR_BASE+17) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_VALUE ((R_ERROR_BASE+18) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_RANGE ((R_ERROR_BASE+19) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_FORMAT ((R_ERROR_BASE+20) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_TYPE ((R_ERROR_BASE+21) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_DATA ((R_ERROR_BASE+22) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_BAD_LENGTH ((R_ERROR_BASE+23) | R_ERROR_BAD_PARAMETER) +#define R_ERROR_RCOM_LIBRARY_NOT_SUPPORTED (R_ERROR_BASE+24) + +/* Resource Manager base for errors */ +#define R_COM_ERR_LIB_CTX_BASE 10100 + +#endif /* HEADER_COMMON_R_ERROR_H */ + + +const BN_ME_METH *BN_ME_METH_thxc(void); +/** + * @note THX code only needs to store rr, n0, str + * + */ +typedef struct thxc_mont_ctx_st + { + BIGNUM *rr; + unsigned char *str; + unsigned int str_len; + BN_ULONG n0; + } THXC_MONT_CTX; + + +int Rx_thxr_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG n0, int top, int tmp_len, unsigned char *str); + +int Ri_thxr_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG *dp, BN_ULONG *aap, BN_ULONG *rp, BN_ULONG *tmp, + BN_ULONG n0, int top, unsigned char *str); + +void Ri_thxr_mul_normal(BN_ULONG *r,BN_ULONG *a,int na,BN_ULONG *b,int nb); +void Ri_thxr_sqr_normal(BN_ULONG *r, BN_ULONG *a, int n, BN_ULONG *tmp); + +void Ri_thxr_from_montgomery_words(BN_ULONG *ret,BN_ULONG *ap,BN_ULONG *np, + int w, BN_ULONG n0); + +BN_ULONG Ri_thxr_from_mont_words(BN_ULONG *ap,BN_ULONG *wap, + BN_ULONG *np, int w, BN_ULONG n0); + +#ifdef CPU_TMS320 + +/* Method and functions required for the ARM/DSP interface */ + +const BN_ME_METH *BN_ME_METH_dspc(void); + +int Rx_dsp_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG n0, int top, int tmp_len, unsigned char *str); + +int Ri_dsp_mod_exp_mont( BN_ULONG *result, BN_ULONG *ap, BN_ULONG *np, + BN_ULONG *rrp, BN_ULONG *dp, BN_ULONG *aap, BN_ULONG *rp, BN_ULONG *tmp, + BN_ULONG n0, int top, unsigned char *str); + +#endif + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_COMMON_BN_THX_H */ diff --git a/build/tools/acsign/include/r_error.h b/build/tools/acsign/include/r_error.h new file mode 100644 index 0000000..8e269f3 --- /dev/null +++ b/build/tools/acsign/include/r_error.h @@ -0,0 +1,210 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file r_error.h + * This file contains the error definitions for the toolkit. + */ +#ifndef HEADER_COMMON_R_ERROR_H +#define HEADER_COMMON_R_ERROR_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup R_ERROR_IDS Error Identifiers + * This section outlines the error codes returned, enabling identification of + * specific errors. For more information, see the + * Developer's Guide. + * + * @{ + */ +/** + * Indicates that a fatal error has occurred in the operation performed. + * This flag is set with the following error codes:
+ *
    + *
  • #R_ERROR_INVALID_STATE.
  • + *
  • #R_ERROR_INIT_NOT_CALLED.
  • + *
  • #R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED.
  • + *
+ */ +#define R_ERROR_FATAL_INTERNAL_ERROR 64 + +/** + * Indicates that the specified parameter is incorrect or contains invalid + * information. This flag is set with the following error codes:
+ *
    + *
  • #R_ERROR_NULL_ARG.
  • + *
  • #R_ERROR_BUFFER_TOO_SMALL.
  • + *
  • #R_ERROR_BAD_VALUE.
  • + *
  • #R_ERROR_BAD_RANGE.
  • + *
  • #R_ERROR_BAD_FORMAT.
  • + *
  • #R_ERROR_BAD_TYPE.
  • + *
  • #R_ERROR_BAD_DATA.
  • + *
  • #R_ERROR_BAD_LENGTH.
  • + *
+ */ +#define R_ERROR_BAD_PARAMETER 32 + +/* Indicates the base value for all general errors used through all products */ +#define R_ERROR_BASE 10000 + +/** + * Indicates that no errors were detected in the requested operation. + */ +#define R_ERROR_NONE 0 + +/** + * Indicates that the requested operation failed. + */ +#define R_ERROR_FAILED (R_ERROR_BASE+1) +/** + * Indicates that the requested operation detected an Input/Output error. + */ +#define R_ERROR_IO (R_ERROR_BASE+2) +/** + * Indicates that the requested operation detected a protocol error. + */ +#define R_ERROR_PROTOCOL (R_ERROR_BASE+3) +/** + * Indicates that the requested operation detected an End-of-File (EOF) error. + */ +#define R_ERROR_EOF (R_ERROR_BASE+4) +/** + * Indicates that the requested operation failed in a memory allocation + * operation. + */ +#define R_ERROR_ALLOC_FAILURE (R_ERROR_BASE+5) +/** + * Indicates that the requested operation is restricted in an evaluation + * version of the library. + */ +#define R_ERROR_EVAL_RESTRICTION (R_ERROR_BASE+6) +/** + * Indicates that the evaluation period of the library has expired. + */ +#define R_ERROR_EVAL_EXPIRED (R_ERROR_BASE+7) +/** + * Indicates that the requested operation detected that a pre-requirement was + * not found. + */ +#define R_ERROR_NOT_FOUND (R_ERROR_BASE+8) +/** + * Indicates that the requested operation detected that a pre-requirement was + * unavailable. + */ +#define R_ERROR_NOT_AVAILABLE (R_ERROR_BASE+9) +/** + * Indicates that the requested operation is not implemented in the current + * instantiation of the library. + */ +#define R_ERROR_NOT_IMPLEMENTED (R_ERROR_BASE+10) +/** + * Indicates that the requested operation is not supported in the current + * instantiation of the library. + */ +#define R_ERROR_NOT_SUPPORTED (R_ERROR_BASE+11) +/** + * Indicates that the requested operation entered an invalid state. + */ +#define R_ERROR_INVALID_STATE \ + ((R_ERROR_BASE+12) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested operation detected that an initialization + * operation has not been performed. + */ +#define R_ERROR_INIT_NOT_CALLED \ + ((R_ERROR_BASE+13) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested operation should not have been called. + */ +#define R_ERROR_SHOULD_NOT_HAVE_BEEN_CALLED \ + ((R_ERROR_BASE+14) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested method is not defined. + */ +#define R_ERROR_METHOD_UNDEFINED \ + ((R_ERROR_BASE+15) | R_ERROR_FATAL_INTERNAL_ERROR) +/** + * Indicates that the requested operation detected an inadequately sized + * buffer. + */ +#define R_ERROR_BUFFER_TOO_SMALL \ + ((R_ERROR_BASE+16) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * was passed as NULL. + */ +#define R_ERROR_NULL_ARG ((R_ERROR_BASE+17) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed contained a bad or incorrect value. + */ +#define R_ERROR_BAD_VALUE ((R_ERROR_BASE+18) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed was out of the allowed range. + */ +#define R_ERROR_BAD_RANGE ((R_ERROR_BASE+19) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed used a format that is not supported or incorrect. + */ +#define R_ERROR_BAD_FORMAT ((R_ERROR_BASE+20) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed used a type that is not supported or incorrect. + */ +#define R_ERROR_BAD_TYPE ((R_ERROR_BASE+21) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed contained incorrect or invalid data. + */ +#define R_ERROR_BAD_DATA ((R_ERROR_BASE+22) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the requested operation detected that a required argument + * passed contained an incorrect length value. + */ +#define R_ERROR_BAD_LENGTH ((R_ERROR_BASE+23) | R_ERROR_BAD_PARAMETER) +/** + * Indicates that the library instantiation requested is not supported. + */ +#define R_ERROR_RCOM_LIBRARY_NOT_SUPPORTED (R_ERROR_BASE+24) +/** + * Indicates that the request operation was denied. + */ +#define R_ERROR_DENIED (R_ERROR_BASE+25) +/** + * Indicates that authentication is required before the operation + * can succeed. + */ +#define R_ERROR_AUTHENTICATION_REQUIRED (R_ERROR_BASE+26) + +/** + * Indicates that a required module was unable to be loaded. + */ +#define R_ERROR_MODULE_LOAD_FAILED \ + ((R_ERROR_BASE+27)|R_ERROR_FATAL_INTERNAL_ERROR) + +/* Resource Manager base for errors */ +#define R_COM_ERR_LIB_CTX_BASE 10100 + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_COMMON_R_ERROR_H */ + + + diff --git a/build/tools/acsign/include/r_stdiag.h b/build/tools/acsign/include/r_stdiag.h new file mode 100644 index 0000000..566de6f --- /dev/null +++ b/build/tools/acsign/include/r_stdiag.h @@ -0,0 +1,82 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +/* + * *************************************************************************** + * + * Purpose: + * + * This file defines an API for performing stack diagnostics. + * + * It provides: + * Peek Stack Usage statistics + * To use it: + * 1. Build the library without "NO_R_DIAG" defined + * 2. Make a call to R_DIAG_set_stack_datum() prior to + * calling the first library function. + * 3. Add calls to the macro R_DIAG_CHECK_STACK where potential + * high stack usage points are. + * 4. Call R_DIAG_get_stack_low_water_mark() at then end of the + * library calls to return the maximum stack usage OR + * 5. Call R_DIAG_print_stack_depth() to display the peek stack + * usage + * + * + * + * History: + * 3-Aug-00 mjs development + * + * ************************************************************************** + */ + + +#ifndef HEADER_COMMON_R_STDIAG_H +#define HEADER_COMMON_R_STDIAG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef NO_R_DIAG + +#ifdef NOPROTO +int R_DIAG_set_stack_datum(char *ptr); +int R_DIAG_check_stack(char *ptr, char *file, int line, int hit); +int R_DIAG_get_stack_low_water_mark(int *depth, char **file, int *line, + int *hit); +int R_DIAG_print_stack_depth(BIO *bio); + +#else + +int R_DIAG_set_stack_datum(); +int R_DIAG_check_stack(); +int R_DIAG_get_stack_low_water_mark(); +int R_DIAG_print_stack_depth(); + +#endif + +#define R_DIAG_CHECK_STACK {\ + char r_diag_stack_check_var = 0;\ + static int r_diag_stack_check_cnt = 0;\ +\ + R_DIAG_check_stack(&r_diag_stack_check_var, __FILE__,\ + __LINE__,++r_diag_stack_check_cnt);\ + } +#else +#define R_DIAG_CHECK_STACK +#endif + + +#ifdef __cplusplus +} +#endif +#endif /* HEADER_COMMON_R_STDIAG_H */ + diff --git a/build/tools/acsign/include/r_types.h b/build/tools/acsign/include/r_types.h new file mode 100644 index 0000000..d35556a --- /dev/null +++ b/build/tools/acsign/include/r_types.h @@ -0,0 +1,241 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ +/** + * @file r_types.h + * This file contains the library structure and type definitions. + */ +#ifndef HEADER_COMMON_R_TYPES_H +#define HEADER_COMMON_R_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup DATA_MNG_FLAGS Data Management Flags + * This section lists the data management flags. + * @{ + */ + +/** + * @} + */ + +/* This gets set if the flags field if the we need to 'free' the + * R_RANDOM when we call R_rand_free(). If it is not set, the + * rand_ctrl will only be called to clean things up. + */ +#define R_RANDOM_FLG_MALLOCED 0x01 + +/* portable form of a random callback function */ +/** + * @typedef R_RANDOM + * The random object type. + */ +typedef struct r_random_st R_RANDOM; +/** + * This structure is used by the random object type. + */ +struct r_random_st +{ + /** + * A method function for generation of random data. + * + * @see R_rand_bytes(). + */ + int (*rand_bytes)(R_RANDOM *ctx,unsigned char *bytes,int len); + /** + * A method function for seeding of the random generator. + * @see R_rand_seed(). + */ + int (*rand_seed)(R_RANDOM *ctx,unsigned char *bytes,int len); + /** + * A method function for control of the random generator used by + * other functions as a single interface. + * + * @see R_rand_entropy_count(), R_rand_set_entropy_func(), + * R_rand_get_entropy_func(), R_rand_load_file(), R_rand_write_file() + * and R_rand_file_name(). + */ + int (*rand_ctrl)(R_RANDOM *ctx,int op,char *arg); + /** + * The data used by the random implementation. + */ + char *arg; + /** + * A method flag for used for keeping the state of the #R_RANDOM. + */ + int flags; /* normally set to zero */ +}; +/** + * @typedef R_SURRENDER + * The surrender function and argument. + */ +typedef struct r_surrender_st R_SURRENDER; +/** + * This structure provides a status update of a time intensive operation. It + * also allows you to abort the operation if required. + */ +struct r_surrender_st +{ + /* Return 0 to continue, non-zero to 'cancel' function */ + /** + * The surrender function pointer used as a generic method of + * passing user-defined callback or information collection functions. + */ + int (*callback)(R_SURRENDER *ctx,int function,int num); + /** + * The argument data used by the callback operation. + */ + char *arg; +}; + +typedef struct r_fixed_point_number_st R_FIXED_POINT_NUMBER; +struct r_fixed_point_number_st +{ + unsigned long hi; + unsigned long lo; +}; + +/** + * @typedef R_INDEXED_INFO + * This structure details the index containing information for get and set + * functions. + */ +typedef struct r_indexed_info_st R_INDEXED_INFO; +/** This structure details the index containing information for get and set + * functions. + */ +struct r_indexed_info_st +{ + /** The index into the list of the item to work with. */ + int index; + /** The data of the item in the list. */ + void *data; + /** The length of the data. */ + unsigned int len; + /** The data value as an integer. */ + int value; +}; + +/** + * @typedef R_ID_INFO + * The information to work with requires a second identity value to find it. + */ +typedef struct r_id_info_st R_ID_INFO; +/** The information to get or set requires a second information identifier. + * This type is used when calling set_info and get_info to get a number of + * information items in one call. + */ +struct r_id_info_st +{ + /** The information identifier. */ + int info_id; + /** The information data associated with the identifier. */ + void *value; +}; + +/** @defgroup R_FLAG_COPY_IDS Copy Flag Identifiers + * + * This section provides information on the copy mode. When data is passed + * to/from the library you can specify whether or not the copy should be done + * by value, by reference or by direct assignment. + * @ingroup DATA_MNG_FLAGS + * @{ + */ + +/** + * The copy flag. When data is passed to/from the library you can specify + * whether or not the copy should be done by value, by reference or + * by direct assignment. + */ +typedef int R_FLAG_COPY; + +/* + * action flag app lib + * obj_get BY_VAL F X + * BY_REF X F [app will not free "obj" until it is + * BY_ASSIGN F X finished with the returned reference] + * obj_set BY_VAL F X + * BY_REF F X [app will not free passed reference + * BY_ASSIGN X F until after it has freed "obj"] + * + * BY_REF makes the lifetime of the two objects linked and it is up to + * the application to manage the objects in a manner that preserves this + * relationship. + */ + +/** + * Indicates to copy by value. A complete clone of the object is made. + * The lifecycles of the two objects are independent. + */ +#define R_FLAG_COPY_BY_VALUE 0x0000 + +/** + * Indicates to copy by reference. A reference to the object is made. + * The lifecycles of objects sharing references are linked. + */ +#define R_FLAG_COPY_BY_REFERENCE 0x0001 + +/** + * Indicates to copy by assignment. The object is assigned to the required + * party. The caller does not keep a reference to the passed object. + */ +#define R_FLAG_COPY_BY_ASSIGN 0x0002 + +/** + * Indicates to copy using the default flag settings. + */ +#define R_FLAG_COPY_DEFAULT R_FLAG_COPY_BY_VALUE + +/** + * @} + */ + +/** @defgroup R_FLAG_SHARE_IDS Shared Flag Identifiers + * + * This section provides information on the shared flags available. + * @ingroup DATA_MNG_FLAGS + * @{ + */ + +/** + * The constructor flag. Indicates whether or not it is permissible to share + * the internal state between objects. + */ +typedef int R_FLAG_SHARE; + +/** + * Indicates to share nothing. The states of the two objects are completely + * separate. + */ +#define R_FLAG_SHARE_NONE 0x0000 + +/** + * Indicates to share data. Constructed objects may reference the state of + * the object from which it was constructed. The lifecycles of the two objects + * are linked. + */ +#define R_FLAG_SHARE_DATA 0x0001 + +/** Indicates the share default in which nothing is shared. */ +#define R_FLAG_SHARE_DEFAULT R_FLAG_SHARE_NONE + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/build/tools/acsign/include/sha.h b/build/tools/acsign/include/sha.h new file mode 100644 index 0000000..d6eeed2 --- /dev/null +++ b/build/tools/acsign/include/sha.h @@ -0,0 +1,89 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef HEADER_COMMON_SHA_H +#define HEADER_COMMON_SHA_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(CCONV) +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +#define SHA_CBLOCK 64 +#define SHA_LBLOCK 16 +#define SHA_BLOCK 16 +#define SHA_LAST_BLOCK 56 +#define SHA_LENGTH_BLOCK 8 +#define SHA_DIGEST_LENGTH 20 + +/* the default is to use unsigned long */ +#if !defined(OPT_SHA_INT) && !defined(OPT_SHA_LONG) +#define OPT_SHA_LONG +#endif + +#ifdef OPT_SHA_LONG +#define SHA_LONG unsigned long +#endif + +#ifdef OPT_SHA_INT +#define SHA_LONG unsigned int +#endif + +typedef struct sha_ctx_st SHA_CTX; + +struct sha_ctx_st + { + SHA_LONG h0,h1,h2,h3,h4; + SHA_LONG Nl,Nh; + SHA_LONG data[SHA_LBLOCK]; + int num; + void (PRE_CCONV CCONV *sha_block)(SHA_CTX *c, const unsigned char *W, + int num); + }; + +#ifndef NOPROTO +int SHA1_Setup(SHA_CTX *c, void (PRE_CCONV CCONV *sha_block)(SHA_CTX *c, + const unsigned char *W, int num)); +void SHA_Init(SHA_CTX *c); +void SHA_Update(SHA_CTX *c, const unsigned char *data, unsigned long len); +void SHA_Final(unsigned char *md, SHA_CTX *c); +unsigned char *SHA(const unsigned char *d, unsigned long n,unsigned char *md); +void SHA_Transform(SHA_CTX *c, const unsigned char *data); +void SHA1_Init(SHA_CTX *c); +void SHA1_Update(SHA_CTX *c, const unsigned char *data, unsigned long len); +void SHA1_Final(unsigned char *md, SHA_CTX *c); +unsigned char *SHA1(const unsigned char *d, unsigned long n,unsigned char *md); +void SHA1_Transform(SHA_CTX *c, const unsigned char *data); +#else +void SHA_Init(); +void SHA_Update(); +void SHA_Final(); +unsigned char *SHA(); +void SHA_Transform(); +void SHA1_Init(); +void SHA1_Update(); +void SHA1_Final(); +unsigned char *SHA1(); +void SHA1_Transform(); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_SHA_H */ diff --git a/build/tools/acsign/include/sha1.h b/build/tools/acsign/include/sha1.h new file mode 100644 index 0000000..ed4a672 --- /dev/null +++ b/build/tools/acsign/include/sha1.h @@ -0,0 +1,73 @@ +/* + * sha1.h + * + * Description: + * This is the header file for code which implements the Secure + * Hashing Algorithm 1 as defined in FIPS PUB 180-1 published + * April 17, 1995. + * + * Many of the variable names in this code, especially the + * single character names, were used because those were the names + * used in the publication. + * + * Please read the file sha1.c for more information. + * + */ + +#ifndef _SHA1_H_ +#define _SHA1_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef _SHA_enum_ +#define _SHA_enum_ +enum +{ + shaSuccess = 0, + shaNull, /* Null pointer parameter */ + shaInputTooLong, /* input data too long */ + shaStateError /* called Input after Result */ +}; +#endif + +/* + * This structure will hold context information for the SHA-1 + * hashing operation + */ +typedef struct SHA1Context +{ + unsigned long Intermediate_Hash[20/4]; /* Message Digest */ + + unsigned long Length_Low; /* Message length in bits */ + unsigned long Length_High; /* Message length in bits */ + + int Message_Block_Index; /* Index into message block array */ + unsigned char Message_Block[64]; /* 512-bit message blocks */ + + int Computed; /* Is the digest computed? */ + int Corrupted; /* Is the message digest corrupted? */ +} SHA1Context; + +/* + * Function Prototypes + */ + +int SHA1Reset( SHA1Context *); +int SHA1Input( SHA1Context *, + const unsigned char *, + unsigned int); +int SHA1Result( SHA1Context *, + unsigned char Message_Digest[20]); + +#if defined( SHA1_TEST ) +int SHA1Test( ); +#endif // SHA1_TEST + + +#ifdef __cplusplus +} +#endif + +#endif // _SHA1_H_ diff --git a/build/tools/acsign/include/sha_locl.h b/build/tools/acsign/include/sha_locl.h new file mode 100644 index 0000000..2361282 --- /dev/null +++ b/build/tools/acsign/include/sha_locl.h @@ -0,0 +1,274 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +#ifndef HEADER_COMMON_SHA_LOCL_H +#define HEADER_COMMON_SHA_LOCL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STANDALONE +//#include "r_com.h" +#else +#if 1 //RSA +#include +#include +#include +//#define Memcpy memcpy +//#define Memset memset +#define Strcpy strcpy +#else //NITRO +#include "acmemory.h" +#define Malloc(a) ACMemory_Alloc(a) +#define Free(a) ACMemory_Free(a) +#define Memset(a,b,c) ACMemory_Memset(a,b,c) +#define Memcpy(a,b,c) ACMemory_Memcpy(a,b,c) +#endif +#endif + +#ifdef undef +/* one or the other must be defined */ +#ifndef SHA_1 /* FIPE 180-1 */ +#define SHA_0 /* FIPS 180 */ +#endif +#endif + +#define ULONG unsigned long +#define UCHAR unsigned char +#define UINT unsigned int + +#ifdef NOCONST +#define const +#endif + +#undef c2nl +#define c2nl(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++))) )) + +#undef p_c2nl +#define p_c2nl(c,l,n) { \ + switch (n) { \ + case 0: l =((unsigned long)(*((c)++)))<<24; \ + case 1: l|=((unsigned long)(*((c)++)))<<16; \ + case 2: l|=((unsigned long)(*((c)++)))<< 8; \ + case 3: l|=((unsigned long)(*((c)++))); \ + } \ + } + +#undef c2nl_p +/* NOTE the pointer is not incremented at the end of this */ +#define c2nl_p(c,l,n) { \ + l=0; \ + (c)+=n; \ + switch (n) { \ + case 3: l =((unsigned long)(*(--(c))))<< 8; \ + case 2: l|=((unsigned long)(*(--(c))))<<16; \ + case 1: l|=((unsigned long)(*(--(c))))<<24; \ + } \ + } + +#undef p_c2nl_p +#define p_c2nl_p(c,l,sc,len) { \ + switch (sc) \ + { \ + case 0: l =((unsigned long)(*((c)++)))<<24; \ + if (--len == 0) break; \ + case 1: l|=((unsigned long)(*((c)++)))<<16; \ + if (--len == 0) break; \ + case 2: l|=((unsigned long)(*((c)++)))<< 8; \ + } \ + } + +#undef nl2c +#define nl2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff)) + +#undef c2l +#define c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ + l|=(((unsigned long)(*((c)++)))<< 8), \ + l|=(((unsigned long)(*((c)++)))<<16), \ + l|=(((unsigned long)(*((c)++)))<<24)) + +#undef p_c2l +#define p_c2l(c,l,n) { \ + switch (n) { \ + case 0: l =((unsigned long)(*((c)++))); \ + case 1: l|=((unsigned long)(*((c)++)))<< 8; \ + case 2: l|=((unsigned long)(*((c)++)))<<16; \ + case 3: l|=((unsigned long)(*((c)++)))<<24; \ + } \ + } + +#undef c2l_p +/* NOTE the pointer is not incremented at the end of this */ +#define c2l_p(c,l,n) { \ + l=0; \ + (c)+=n; \ + switch (n) { \ + case 3: l =((unsigned long)(*(--(c))))<<16; \ + case 2: l|=((unsigned long)(*(--(c))))<< 8; \ + case 1: l|=((unsigned long)(*(--(c)))); \ + } \ + } + +#undef p_c2l_p +#define p_c2l_p(c,l,sc,len) { \ + switch (sc) \ + { \ + case 0: l =((unsigned long)(*((c)++))); \ + if (--len == 0) break; \ + case 1: l|=((unsigned long)(*((c)++)))<< 8; \ + if (--len == 0) break; \ + case 2: l|=((unsigned long)(*((c)++)))<<16; \ + } \ + } + +#undef l2c +#define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16)&0xff), \ + *((c)++)=(unsigned char)(((l)>>24)&0xff)) + +#ifdef OPT_SHA_B_ENDIAN +#define B_ENDIAN +#endif +#ifdef OPT_SHA_L_ENDIAN +#define L_ENDIAN +#endif + +#undef ROTATE +#if defined(WIN32) +#define ROTATE(a,n) _lrotl(a,n) +#else +#define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n)))) +#endif + +/* byte order reversal */ +#if defined(WIN32) +/* 5 instructions with rotate instruction, else 9 */ +#define Endian_Reverse32(a) \ + { \ + unsigned long l=(a); \ + (a)=((ROTATE(l,8)&0x00FF00FF)|(ROTATE(l,24)&0xFF00FF00)); \ + } +#else +/* 6 instructions with rotate instruction, else 8 */ +#define Endian_Reverse32(a) \ + { \ + unsigned long l=(a); \ + l=(((l&0xFF00FF00)>>8L)|((l&0x00FF00FF)<<8L)); \ + (a)=ROTATE(l,16L); \ + } +#endif + +/* F() below can be + * simplified to the code in F_00_19. + * #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) + * another tweak to be made + * in F_40_59, (x&a)|(y&a) -> (x|y)&a + */ +#define F_00_19(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) +#define F_20_39(b,c,d) ((b) ^ (c) ^ (d)) +#define F_40_59(b,c,d) (((b) & (c)) | (((b)|(c)) & (d))) +#define F_60_79(b,c,d) F_20_39(b,c,d) + +#ifdef SHA_0 +#undef Xupdate +#define Xupdate(a,i,ia,ib,ic,id) X[(i)&0x0f]=(a)=\ + (ia[(i)&0x0f]^ib[((i)+2)&0x0f]^ic[((i)+8)&0x0f]^id[((i)+13)&0x0f]); +#endif +#ifdef SHA_1 +#undef Xupdate +#define Xupdate(a,i,ia,ib,ic,id) (a)=\ + (ia[(i)&0x0f]^ib[((i)+2)&0x0f]^ic[((i)+8)&0x0f]^id[((i)+13)&0x0f]);\ + X[(i)&0x0f]=(a)=ROTATE((a),1); +#endif + +#define BODY_00_15(i,a,b,c,d,e,f,xa) \ + (f)=xa[i]+(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_60_79(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)=X[(i)&0x0f]+(e)+K_60_79+ROTATE((a),5)+F_60_79((b),(c),(d)); \ + (b)=ROTATE((b),30); + +/* + * The CodeWarrior compiler has a problem correctly expanding things like + * + * (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); + * + * so we separate this to 3 explicit adds, just for PalmOS. + */ +#ifndef UNDER_PALMOS + +#define BODY_16_19(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_20_31(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_32_39(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_40_59(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e)+K_40_59+ROTATE((a),5)+F_40_59((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#else /* UNDER_PALMOS */ + +#define BODY_16_19(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e); \ + (f)+=K_00_19; \ + (f)+=ROTATE((a),5)+F_00_19((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_20_31(i,a,b,c,d,e,f,xa,xb,xc,xd) \ + Xupdate(f,i,xa,xb,xc,xd); \ + (f)+=(e); \ + (f)+=K_20_39; \ + (f)+=ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_32_39(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e); \ + (f)+=K_20_39; \ + (f)+=ROTATE((a),5)+F_20_39((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#define BODY_40_59(i,a,b,c,d,e,f,xa) \ + Xupdate(f,i,xa,xa,xa,xa); \ + (f)+=(e); \ + (f)+=K_40_59; \ + (f)+=ROTATE((a),5)+F_40_59((b),(c),(d)); \ + (b)=ROTATE((b),30); + +#endif /* UNDER_PALMOS */ + +#ifdef __cplusplus +} +#endif + +#endif /* HEADER_COMMON_SHA_LOCL_H */ diff --git a/build/tools/acsign/sha1.c b/build/tools/acsign/sha1.c new file mode 100644 index 0000000..6bebd12 --- /dev/null +++ b/build/tools/acsign/sha1.c @@ -0,0 +1,453 @@ +/* + * sha1.c + * + * Description: + * This file implements the Secure Hashing Algorithm 1 as + * defined in FIPS PUB 180-1 published April 17, 1995. + * + * The SHA-1, produces a 160-bit message digest for a given + * data stream. It should take about 2**n steps to find a + * message with the same digest as a given message and + * 2**(n/2) to find any two messages with the same digest, + * when n is the digest size in bits. Therefore, this + * algorithm can serve as a means of providing a + * "fingerprint" for a message. + * + * Portability Issues: + * SHA-1 is defined in terms of 32-bit "words". This code + * uses (included via "sha1.h" to define 32 and 8 + * bit unsigned integer types. If your C compiler does not + * support 32 bit unsigned integers, this code is not + * appropriate. + * + * Caveats: + * SHA-1 is designed to work with messages less than 2^64 bits + * long. Although SHA-1 allows a message digest to be generated + * for messages of any number of bits less than 2^64, this + * implementation only works with messages with a length that is + * a multiple of the size of an 8-bit character. + * + */ + +#include "sha1.h" + +/* + * Define the SHA1 circular left shift macro + */ +#define SHA1CircularShift(bits,word) \ + (((word) << (bits)) | ((word) >> (32-(bits)))) + +/* Local Function Prototyptes */ +void SHA1PadMessage(SHA1Context *); +void SHA1ProcessMessageBlock(SHA1Context *); + +/* + * SHA1Reset + * + * Description: + * This function will initialize the SHA1Context in preparation + * for computing a new SHA1 message digest. + * + * Parameters: + * context: [in/out] + * The context to reset. + * + * Returns: + * sha Error Code. + * + */ +int SHA1Reset(SHA1Context *context) +{ + if (!context) + { + return shaNull; + } + + context->Length_Low = 0; + context->Length_High = 0; + context->Message_Block_Index = 0; + + context->Intermediate_Hash[0] = 0x67452301; + context->Intermediate_Hash[1] = 0xEFCDAB89; + context->Intermediate_Hash[2] = 0x98BADCFE; + context->Intermediate_Hash[3] = 0x10325476; + context->Intermediate_Hash[4] = 0xC3D2E1F0; + + context->Computed = 0; + context->Corrupted = 0; + + return shaSuccess; +} + +/* + * SHA1Result + * + * Description: + * This function will return the 160-bit message digest into the + * Message_Digest array provided by the caller. + * NOTE: The first octet of hash is stored in the 0th element, + * the last octet of hash in the 19th element. + * + * Parameters: + * context: [in/out] + * The context to use to calculate the SHA-1 hash. + * Message_Digest: [out] + * Where the digest is returned. + * + * Returns: + * sha Error Code. + * + */ +int SHA1Result( SHA1Context *context, + unsigned char Message_Digest[20]) +{ + int i; + + if (!context || !Message_Digest) + { + return shaNull; + } + + if (context->Corrupted) + { + return context->Corrupted; + } + + if (!context->Computed) + { + SHA1PadMessage(context); + for(i=0; i<64; ++i) + { + /* message may be sensitive, clear it out */ + context->Message_Block[i] = 0; + } + context->Length_Low = 0; /* and clear length */ + context->Length_High = 0; + context->Computed = 1; + + } + + for(i = 0; i < 20; ++i) + { + Message_Digest[i] = (unsigned char) + (context->Intermediate_Hash[i>>2] + >> 8 * ( 3 - ( i & 0x03 ) )); + } + + return shaSuccess; +} + +/* + * SHA1Input + * + * Description: + * This function accepts an array of octets as the next portion + * of the message. + * + * Parameters: + * context: [in/out] + * The SHA context to update + * message_array: [in] + * An array of characters representing the next portion of + * the message. + * length: [in] + * The length of the message in message_array + * + * Returns: + * sha Error Code. + * + */ +int SHA1Input( SHA1Context *context, + const unsigned char *message_array, + unsigned int length) +{ + if (!length) + { + return shaSuccess; + } + + if (!context || !message_array) + { + return shaNull; + } + + if (context->Computed) + { + context->Corrupted = shaStateError; + + return shaStateError; + } + + if (context->Corrupted) + { + return context->Corrupted; + } + while(length-- && !context->Corrupted) + { + context->Message_Block[context->Message_Block_Index++] = + (unsigned char)(*message_array & 0xFF); + + context->Length_Low += 8; + if (context->Length_Low == 0) + { + context->Length_High++; + if (context->Length_High == 0) + { + /* Message is too long */ + context->Corrupted = 1; + } + } + + if (context->Message_Block_Index == 64) + { + SHA1ProcessMessageBlock(context); + } + + message_array++; + } + + return shaSuccess; +} + +/* + * SHA1ProcessMessageBlock + * + * Description: + * This function will process the next 512 bits of the message + * stored in the Message_Block array. + * + * Parameters: + * None. + * + * Returns: + * Nothing. + * + * Comments: + * + * Many of the variable names in this code, especially the + * single character names, were used because those were the + * names used in the publication. + * + * + */ +void SHA1ProcessMessageBlock(SHA1Context *context) +{ + const unsigned long K[] = { /* Constants defined in SHA-1 */ + 0x5A827999, + 0x6ED9EBA1, + 0x8F1BBCDC, + 0xCA62C1D6 + }; + int t; /* Loop counter */ + unsigned long temp; /* Temporary word value */ + unsigned long W[80]; /* Word sequence */ + unsigned long A, B, C, D, E; /* Word buffers */ + + /* + * Initialize the first 16 words in the array W + */ + for(t = 0; t < 16; t++) + { + W[t] = context->Message_Block[t * 4 ] << 24; + W[t] |= context->Message_Block[t * 4 + 1] << 16; + W[t] |= context->Message_Block[t * 4 + 2] << 8; + W[t] |= context->Message_Block[t * 4 + 3]; + } + + for(t = 16; t < 80; t++) + { + W[t] = SHA1CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); + } + + A = context->Intermediate_Hash[0]; + B = context->Intermediate_Hash[1]; + C = context->Intermediate_Hash[2]; + D = context->Intermediate_Hash[3]; + E = context->Intermediate_Hash[4]; + + for(t = 0; t < 20; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + + B = A; + A = temp; + } + + for(t = 20; t < 40; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for(t = 40; t < 60; t++) + { + temp = SHA1CircularShift(5,A) + + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + for(t = 60; t < 80; t++) + { + temp = SHA1CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; + E = D; + D = C; + C = SHA1CircularShift(30,B); + B = A; + A = temp; + } + + context->Intermediate_Hash[0] += A; + context->Intermediate_Hash[1] += B; + context->Intermediate_Hash[2] += C; + context->Intermediate_Hash[3] += D; + context->Intermediate_Hash[4] += E; + + context->Message_Block_Index = 0; +} + +/* + * SHA1PadMessage + * + + * Description: + * According to the standard, the message must be padded to an even + * 512 bits. The first padding bit must be a '1'. The last 64 + * bits represent the length of the original message. All bits in + * between should be 0. This function will pad the message + * according to those rules by filling the Message_Block array + * accordingly. It will also call the ProcessMessageBlock function + * provided appropriately. When it returns, it can be assumed that + * the message digest has been computed. + * + * Parameters: + * context: [in/out] + * The context to pad + * ProcessMessageBlock: [in] + * The appropriate SHA*ProcessMessageBlock function + * Returns: + * Nothing. + * + */ + +void SHA1PadMessage(SHA1Context *context) +{ + /* + * Check to see if the current message block is too small to hold + * the initial padding bits and length. If so, we will pad the + * block, process it, and then continue padding into a second + * block. + */ + if (context->Message_Block_Index > 55) + { + context->Message_Block[context->Message_Block_Index++] = 0x80; + while(context->Message_Block_Index < 64) + { + context->Message_Block[context->Message_Block_Index++] = 0; + } + + SHA1ProcessMessageBlock(context); + + while(context->Message_Block_Index < 56) + { + context->Message_Block[context->Message_Block_Index++] = 0; + } + } + else + { + context->Message_Block[context->Message_Block_Index++] = 0x80; + while(context->Message_Block_Index < 56) + { + + context->Message_Block[context->Message_Block_Index++] = 0; + } + } + + /* + * Store the message length as the last 8 octets + */ + context->Message_Block[56] = (unsigned char)(context->Length_High >> 24); + context->Message_Block[57] = (unsigned char)(context->Length_High >> 16); + context->Message_Block[58] = (unsigned char)(context->Length_High >> 8); + context->Message_Block[59] = (unsigned char)(context->Length_High ); + context->Message_Block[60] = (unsigned char)(context->Length_Low >> 24); + context->Message_Block[61] = (unsigned char)(context->Length_Low >> 16); + context->Message_Block[62] = (unsigned char)(context->Length_Low >> 8); + context->Message_Block[63] = (unsigned char)(context->Length_Low ); + + SHA1ProcessMessageBlock(context); +} + + + + +////////////////////////////////////////////////////////////////////////////// +#if defined( SHA1_TEST ) + +#include "string.h" + +char* samplearray[4] = +{ + "abc", + "abcdbcdecdefdefgefghfghighijhi" "jkijkljklmklmnlmnomnopnopq", + "a", + "01234567012345670123456701234567" "01234567012345670123456701234567" +}; + +char* resultarray[ 4 ] = +{ + "\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E\x25\x71\x78\x50\xC2\x6C\x9C\xD0\xD8\x9D", + "\x84\x98\x3E\x44\x1C\x3B\xD2\x6E\xBA\xAE\x4A\xA1\xF9\x51\x29\xE5\xE5\x46\x70\xF1", + "\x34\xAA\x97\x3C\xD4\xC4\xDA\xA4\xF6\x1E\xEB\x2B\xDB\xAD\x27\x31\x65\x34\x01\x6F", + "\xDE\xA3\x56\xA2\xCD\xDD\x90\xC7\xA7\xEC\xED\xC5\xEB\xB5\x63\x93\x4F\x46\x04\x52" +}; + +long int repeatcount[4] = { 1, 1, 1000000, 10 }; + +int SHA1Test( ) +{ + SHA1Context sha; + unsigned char digest[20]; + int i, j, error; + + error = 0; + for ( j = 0; j < 4; ++j ) + { + if ( !error ) + error = SHA1Reset(&sha); + + for(i = 0; i < repeatcount[j]; ++i) + { + if ( !error ) + error = SHA1Input(&sha, + (const unsigned char *)samplearray[j], + (unsigned int)strlen(samplearray[j])); + } + + if ( !error ) + error = SHA1Result(&sha, digest); + + if ( !error ) + error = memcmp( digest, resultarray[j], 20 ); + + if (error) + break; + } + + return error ? 0 : 1; +} + +#endif // SHA1_TEST +////////////////////////////////////////////////////////////////////////////// + diff --git a/build/tools/acsign/sha1dgst.c b/build/tools/acsign/sha1dgst.c new file mode 100644 index 0000000..f975915 --- /dev/null +++ b/build/tools/acsign/sha1dgst.c @@ -0,0 +1,770 @@ +/* $Id$ */ +/* + * Copyright (C) 1998-2002 RSA Security Inc. All rights reserved. + * + * This work contains proprietary information of RSA Security. + * Distribution is limited to authorized licensees of RSA + * Security. Any unauthorized reproduction, distribution or + * modification of this work is strictly prohibited. + * + */ + +////!!!!#include "r_com.h" + +#ifndef NO_SHA1 +#undef SHA_0 +#define SHA_1 +#include "sha.h" +#include "sha_locl.h" +#ifdef CPU_X86 +#include "r_cpuid.h" +#endif /* NO_SHA1 */ + +const char *SHA1_version="SHA1 part of RCOM 2.3.0 11-Jun-2002"; + +/* Implemented from SHA-1 document - The Secure Hash Algorithm + */ + +#define INIT_DATA_h0 (SHA_LONG)0x67452301L +#define INIT_DATA_h1 (SHA_LONG)0xefcdab89L +#define INIT_DATA_h2 (SHA_LONG)0x98badcfeL +#define INIT_DATA_h3 (SHA_LONG)0x10325476L +#define INIT_DATA_h4 (SHA_LONG)0xc3d2e1f0L + +#define K_00_19 (SHA_LONG)0x5a827999L +#define K_20_39 (SHA_LONG)0x6ed9eba1L +#define K_40_59 (SHA_LONG)0x8f1bbcdcL +#define K_60_79 (SHA_LONG)0xca62c1d6L + +#ifndef CCONV +#define CCONV +#endif + +#ifndef PRE_CCONV +#define PRE_CCONV +#endif + +/* Endian flags are only used for the assembler code */ +#ifndef OPT_SHA1_ASM +#undef L_ENDIAN +#undef B_ENDIAN +#endif + + +#ifdef OPT_SHA1_ASM + +#ifdef CPU_X86 +void CCONV sha1_block_586(SHA_CTX *c,const unsigned char *p, int num); +void CCONV sha1_block_686(SHA_CTX *c,const unsigned char *p, int num); +void CCONV sha1_block_786(SHA_CTX *c,const unsigned char *p, int num); +unsigned long r_cpuid(unsigned long *,char **name); + +#elif OPT_SHA1_ARM +PRE_CCONV void CCONV sha1_arm4_fast(SHA_CTX *c, const unsigned char *p, + int num); +PRE_CCONV void CCONV sha1_arm4_small(SHA_CTX *c, const unsigned char *p, + int num); +#else +void CCONV sha1_block_asm(SHA_CTX *c, const unsigned char *p, int num); +#endif /* CPU_X86 */ + +#else /* OPT_SHA1_ASM */ + +void sha1_block(SHA_CTX *c, SHA_LONG *p, int num); + +#endif /* OPT_SHA1_ASM */ + +#undef M_c2nl +#undef M_p_c2nl +#undef M_c2nl_p +#undef M_p_c2nl_p +#undef M_nl2c + +#if defined(L_ENDIAN) && !defined(OPT_SHA1_ASM) +# define M_c2nl c2l +# define M_p_c2nl p_c2l +# define M_c2nl_p c2l_p +# define M_p_c2nl_p p_c2l_p +# define M_nl2c l2c +#else +# define M_c2nl c2nl +# define M_p_c2nl p_c2nl +# define M_c2nl_p c2nl_p +# define M_p_c2nl_p p_c2nl_p +# define M_nl2c nl2c +#endif /* defined(L_ENDIAN) && !defined(OPT_SHA1_ASM) */ + +int SHA1_Setup(c,sha_block) +SHA_CTX *c; +void (PRE_CCONV CCONV *sha_block)(SHA_CTX *c, const unsigned char *W, int num); + { + c->sha_block=sha_block; + return(0); + } + +void SHA1_Init(c) +SHA_CTX *c; + { + c->h0=INIT_DATA_h0; + c->h1=INIT_DATA_h1; + c->h2=INIT_DATA_h2; + c->h3=INIT_DATA_h3; + c->h4=INIT_DATA_h4; + c->Nl=0; + c->Nh=0; + c->num=0; + +#ifdef OPT_SHA1_ASM +#ifdef CPU_X86 + if (c->sha_block == NULL) + { + unsigned long cpu,attrib; + + /* We should make the methods loadable */ + cpu=r_cpuid(&attrib,NULL); + if (attrib & R_CPU_X86_HAS_PENTIUM_IV) + c->sha_block=sha1_block_786; + else if (attrib & R_CPU_X86_HAS_PENTIUM_PRO) + c->sha_block=sha1_block_686; + else + c->sha_block=sha1_block_586; + } +#else /* CPU_X86 */ + +#ifndef OPT_SHA1_ARM + c->sha_block=sha1_block_asm; +#else /* OPT_SHA1_ARM */ + if (c->sha_block == NULL) + { +#ifdef SMALL_CODE_SIZE + c->sha_block = sha1_arm4_small; +#else /* SMALL_CODE_SIZE */ + c->sha_block = sha1_arm4_fast; +#endif /* SMALL_CODE_SIZE */ + } +#endif /* OPT_SHA1_ARM */ +#endif /* CPU_X86 */ + +#else /* OPT_SHA1_ASM */ + c->sha_block=(void (PRE_CCONV CCONV *)(SHA_CTX *, const unsigned char *, int))sha1_block; +#endif /* OPT_SHA1_ASM */ + } + +#ifdef OPT_SHA1_ASM + +void SHA1_Update(c, data, len) +SHA_CTX *c; +const register unsigned char *data; +unsigned long len; + { + int i; + unsigned int alignment; + unsigned long l; + unsigned char *cp=(unsigned char *)c->data; + + if (len == 0) return; + + l=(c->Nl+(len<<3))&0xffffffffL; + if (l < c->Nl) /* overflow */ + c->Nh++; + c->Nh+=(len>>29); + c->Nl=l; + + if (c->num != 0) + { + if (c->num+len >= SHA_CBLOCK) + { + i=SHA_CBLOCK-c->num; + Memcpy(&(cp[c->num]),data,i); + len-=i; + data+=i; + + c->sha_block(c,cp,64); + c->num=0; + /* drop through and do the rest */ + } + else + { + Memcpy(&(cp[c->num]),data,len); + c->num+=(int)len; + return; + } + } + /* we now can process the input data in blocks of SHA_CBLOCK + * chars and save the leftovers to c->data. */ + if (len >= SHA_CBLOCK) + { + i=(int)(len& ~63); + len-=i; + + /* + * Check to see if the input data lies on a word boundary. + * Do this as the ASM relies on input data being word aligned. + */ + alignment = (((unsigned int)data) & (sizeof(unsigned int)-1)) + & 0x03; + if (alignment == 0) + { + c->sha_block(c,data,i); + data+=i; + } + else + { + do { + Memcpy(cp, data, SHA_CBLOCK); + data += SHA_CBLOCK; + c->sha_block(c, cp, SHA_CBLOCK); + i -= SHA_CBLOCK; + } while (i > 0); + } + } + c->num=len; + if (len) + { + Memcpy(cp,data,(int)len); + } + } + +void SHA1_Transform(c,b) +SHA_CTX *c; +const unsigned char *b; + { + c->sha_block(c,b,64); + } + +void SHA1_Final(md, c) +unsigned char *md; +SHA_CTX *c; + { + register int i,j; + register SHA_LONG l; + register SHA_LONG *p; + const static unsigned char end[4]={0x80,0x00,0x00,0x00}; + unsigned char *cp= (unsigned char *)end; + unsigned char *pc; + + /* c->num should definitly have room for at least one more byte. */ + p=c->data; + j=c->num; + i=j>>2; + +#ifdef PURIFY + /* PURIFY */ + /* we reference uninitialised data but don't keep the result + * which purify complains about ... and we don't want to have + * to come back here to find a non-existant problem later + */ + + /* purify often complains about the following line as an + * Uninitialized Memory Read. While this can be true, the + * following p_c2l macro will reset l when that case is true. + * This is because j&0x03 contains the number of 'valid' bytes + * already in p[i]. If and only if j&0x03 == 0, the UMR will + * occur but this is also the only time p_c2l will do + * l= *(cp++) instead of l|= *(cp++) + */ + if ((j&0x03) == 0) p[i]=0; +#endif + + pc=(unsigned char *)c->data; + pc[j]=0x80; + for (j++; j & 0x03; j++) + pc[j]=0; + i++; + /* i is the next 'undefined word' */ + if (c->num >= SHA_LAST_BLOCK) + { + for (; isha_block(c,(unsigned char *)p,64); + i=0; + } + for (; i<(SHA_LBLOCK-2); i++) + p[i]=0; + + l=c->Nl; + pc[63]=(unsigned char)((l )&0xff); + pc[62]=(unsigned char)((l>> 8)&0xff); + pc[61]=(unsigned char)((l>>16)&0xff); + pc[60]=(unsigned char)((l>>24)&0xff); + l=c->Nh; + pc[59]=(unsigned char)((l )&0xff); + pc[58]=(unsigned char)((l>> 8)&0xff); + pc[57]=(unsigned char)((l>>16)&0xff); + pc[56]=(unsigned char)((l>>24)&0xff); + + c->sha_block(c,(unsigned char *)p,64); + cp=md; + l=c->h0; nl2c(l,cp); + l=c->h1; nl2c(l,cp); + l=c->h2; nl2c(l,cp); + l=c->h3; nl2c(l,cp); + l=c->h4; nl2c(l,cp); + + /* clear stuff, sha1_block_asm may be leaving some stuff on the stack + * but I'm not worried :-) */ + c->num=0; +/* Memset((char *)&c,0,sizeof(c));*/ + } + +#else /* !OPT_SHA1_ASM */ + +void SHA1_Update(c, data, len) +SHA_CTX *c; +const register unsigned char *data; +unsigned long len; + { + register SHA_LONG *p; + int ew,ec,sw,sc; + SHA_LONG l; + + if (len == 0) return; + + l=(c->Nl+(len<<3))&0xffffffffL; + if (l < c->Nl) /* overflow */ + c->Nh++; + c->Nh+=(len>>29); + c->Nl=l; + + if (c->num != 0) + { + p=c->data; + sw=c->num>>2; + sc=c->num&0x03; + + if ((c->num+len) >= SHA_CBLOCK) + { + l= p[sw]; + M_p_c2nl(data,l,sc); + p[sw++]=l; + for (; swnum); + + c->sha_block(c,(unsigned char *)p,64); + c->num=0; + /* drop through and do the rest */ + } + else + { + c->num+=(int)len; + if ((sc+len) < 4) /* ugly, add char's to a word */ + { + l= p[sw]; + M_p_c2nl_p(data,l,sc,len); + p[sw]=l; + } + else + { + ew=(c->num>>2); + ec=(c->num&0x03); + l= p[sw]; + M_p_c2nl(data,l,sc); + p[sw++]=l; + for (; sw < ew; sw++) + { M_c2nl(data,l); p[sw]=l; } + if (ec) + { + M_c2nl_p(data,l,ec); + p[sw]=l; + } + } + return; + } + } + /* We can only do the following code for assember, the reason + * being that the sha1_block 'C' version changes the values + * in the 'data' array. The assember code avoids this and + * copies it to a local array. I should be able to do this for + * the C version as well.... + */ +#if defined(B_ENDIAN) || defined(OPT_SHA1_ASM) + if ((((unsigned long)data)%sizeof(SHA_LONG)) == 0) + { + sw=len/SHA_CBLOCK; + if (sw) + { + sw*=SHA_CBLOCK; + c->sha_block(c,(SHA_LONG *)data,sw); + data+=sw; + len-=sw; + } + } +#endif + /* we now can process the input data in blocks of SHA_CBLOCK + * chars and save the leftovers to c->data. */ + p=c->data; + while (len >= SHA_CBLOCK) + { +#if defined(B_ENDIAN) || defined(L_ENDIAN) + if (p != (SHA_LONG *)data) + Memcpy(p,data,SHA_CBLOCK); + data+=SHA_CBLOCK; +# ifdef L_ENDIAN +# ifndef OPT_SHA1_ASM /* Will not happen */ + for (sw=(SHA_LBLOCK/4); sw; sw--) + { + Endian_Reverse32(p[0]); + Endian_Reverse32(p[1]); + Endian_Reverse32(p[2]); + Endian_Reverse32(p[3]); + p+=4; + } + p=c->data; +# endif +# endif +#else + for (sw=(SHA_BLOCK/4); sw; sw--) + { + M_c2nl(data,l); *(p++)=l; + M_c2nl(data,l); *(p++)=l; + M_c2nl(data,l); *(p++)=l; + M_c2nl(data,l); *(p++)=l; + } + p=c->data; +#endif + c->sha_block(c,(unsigned char *)p,64); + len-=SHA_CBLOCK; + } + ec=(int)len; + c->num=ec; + ew=(ec>>2); + ec&=0x03; + + for (sw=0; sw < ew; sw++) + { M_c2nl(data,l); p[sw]=l; } + M_c2nl_p(data,l,ec); + p[sw]=l; + } + +void SHA1_Transform(c,b) +SHA_CTX *c; +const unsigned char *b; + { + SHA_LONG p[16]; +#ifndef B_ENDIAN + SHA_LONG *q; + int i; +#endif + +#if defined(B_ENDIAN) || defined(L_ENDIAN) + Memcpy(p,b,64); +#ifdef L_ENDIAN + q=p; + for (i=(SHA_LBLOCK/4); i; i--) + { + Endian_Reverse32(q[0]); + Endian_Reverse32(q[1]); + Endian_Reverse32(q[2]); + Endian_Reverse32(q[3]); + q+=4; + } +#endif +#else + q=p; + for (i=(SHA_LBLOCK/4); i; i--) + { + SHA_LONG l; + c2nl(b,l); *(q++)=l; + c2nl(b,l); *(q++)=l; + c2nl(b,l); *(q++)=l; + c2nl(b,l); *(q++)=l; + } +#endif + c->sha_block(c,(unsigned char *)p,64); + } + + +void sha1_block(c, W, num) +SHA_CTX *c; +SHA_LONG *W; +int num; + { +#ifndef SMALL_CODE_SIZE + register SHA_LONG A,B,C,D,E,T; + SHA_LONG X[16]; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + for (;;) + { + BODY_00_15( 0,A,B,C,D,E,T,W); + BODY_00_15( 1,T,A,B,C,D,E,W); + BODY_00_15( 2,E,T,A,B,C,D,W); + BODY_00_15( 3,D,E,T,A,B,C,W); + BODY_00_15( 4,C,D,E,T,A,B,W); + BODY_00_15( 5,B,C,D,E,T,A,W); + BODY_00_15( 6,A,B,C,D,E,T,W); + BODY_00_15( 7,T,A,B,C,D,E,W); + BODY_00_15( 8,E,T,A,B,C,D,W); + BODY_00_15( 9,D,E,T,A,B,C,W); + BODY_00_15(10,C,D,E,T,A,B,W); + BODY_00_15(11,B,C,D,E,T,A,W); + BODY_00_15(12,A,B,C,D,E,T,W); + BODY_00_15(13,T,A,B,C,D,E,W); + BODY_00_15(14,E,T,A,B,C,D,W); + BODY_00_15(15,D,E,T,A,B,C,W); + BODY_16_19(16,C,D,E,T,A,B,W,W,W,W); + BODY_16_19(17,B,C,D,E,T,A,W,W,W,W); + BODY_16_19(18,A,B,C,D,E,T,W,W,W,W); + BODY_16_19(19,T,A,B,C,D,E,W,W,W,X); + + BODY_20_31(20,E,T,A,B,C,D,W,W,W,X); + BODY_20_31(21,D,E,T,A,B,C,W,W,W,X); + BODY_20_31(22,C,D,E,T,A,B,W,W,W,X); + BODY_20_31(23,B,C,D,E,T,A,W,W,W,X); + BODY_20_31(24,A,B,C,D,E,T,W,W,X,X); + BODY_20_31(25,T,A,B,C,D,E,W,W,X,X); + BODY_20_31(26,E,T,A,B,C,D,W,W,X,X); + BODY_20_31(27,D,E,T,A,B,C,W,W,X,X); + BODY_20_31(28,C,D,E,T,A,B,W,W,X,X); + BODY_20_31(29,B,C,D,E,T,A,W,W,X,X); + BODY_20_31(30,A,B,C,D,E,T,W,X,X,X); + BODY_20_31(31,T,A,B,C,D,E,W,X,X,X); + BODY_32_39(32,E,T,A,B,C,D,X); + BODY_32_39(33,D,E,T,A,B,C,X); + BODY_32_39(34,C,D,E,T,A,B,X); + BODY_32_39(35,B,C,D,E,T,A,X); + BODY_32_39(36,A,B,C,D,E,T,X); + BODY_32_39(37,T,A,B,C,D,E,X); + BODY_32_39(38,E,T,A,B,C,D,X); + BODY_32_39(39,D,E,T,A,B,C,X); + + BODY_40_59(40,C,D,E,T,A,B,X); + BODY_40_59(41,B,C,D,E,T,A,X); + BODY_40_59(42,A,B,C,D,E,T,X); + BODY_40_59(43,T,A,B,C,D,E,X); + BODY_40_59(44,E,T,A,B,C,D,X); + BODY_40_59(45,D,E,T,A,B,C,X); + BODY_40_59(46,C,D,E,T,A,B,X); + BODY_40_59(47,B,C,D,E,T,A,X); + BODY_40_59(48,A,B,C,D,E,T,X); + BODY_40_59(49,T,A,B,C,D,E,X); + BODY_40_59(50,E,T,A,B,C,D,X); + BODY_40_59(51,D,E,T,A,B,C,X); + BODY_40_59(52,C,D,E,T,A,B,X); + BODY_40_59(53,B,C,D,E,T,A,X); + BODY_40_59(54,A,B,C,D,E,T,X); + BODY_40_59(55,T,A,B,C,D,E,X); + BODY_40_59(56,E,T,A,B,C,D,X); + BODY_40_59(57,D,E,T,A,B,C,X); + BODY_40_59(58,C,D,E,T,A,B,X); + BODY_40_59(59,B,C,D,E,T,A,X); + + BODY_60_79(60,A,B,C,D,E,T,X); + BODY_60_79(61,T,A,B,C,D,E,X); + BODY_60_79(62,E,T,A,B,C,D,X); + BODY_60_79(63,D,E,T,A,B,C,X); + BODY_60_79(64,C,D,E,T,A,B,X); + BODY_60_79(65,B,C,D,E,T,A,X); + BODY_60_79(66,A,B,C,D,E,T,X); + BODY_60_79(67,T,A,B,C,D,E,X); + BODY_60_79(68,E,T,A,B,C,D,X); + BODY_60_79(69,D,E,T,A,B,C,X); + BODY_60_79(70,C,D,E,T,A,B,X); + BODY_60_79(71,B,C,D,E,T,A,X); + BODY_60_79(72,A,B,C,D,E,T,X); + BODY_60_79(73,T,A,B,C,D,E,X); + BODY_60_79(74,E,T,A,B,C,D,X); + BODY_60_79(75,D,E,T,A,B,C,X); + BODY_60_79(76,C,D,E,T,A,B,X); + BODY_60_79(77,B,C,D,E,T,A,X); + BODY_60_79(78,A,B,C,D,E,T,X); + BODY_60_79(79,T,A,B,C,D,E,X); + + c->h0=(c->h0+E)&0xffffffffL; + c->h1=(c->h1+T)&0xffffffffL; + c->h2=(c->h2+A)&0xffffffffL; + c->h3=(c->h3+B)&0xffffffffL; + c->h4=(c->h4+C)&0xffffffffL; + + num-=64; + if (num <= 0) break; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + W+=16; + } +#else /* SMALL_CODE_SIZE */ + SHA_LONG A,B,C,D,E,T; + SHA_LONG X[16]; + SHA_LONG *a1,*a2,*a3; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + for (;;) + { + int i; + + for (i=0; i<16; i++) + { + BODY_00_15(i,A,B,C,D,E,T,W); + E=D; D=C; C=B; B=A; A=T; + } + + a1=W; + for (i=16; i<20; i++) + { + if (i == 19) a1=X; + BODY_16_19(i,A,B,C,D,E,T,W,W,W,a1); + E=D; D=C; C=B; B=A; A=T; + } + + a1=a2=a3=W; + for (i=20; i<40; i++) + { + if (i == 24) a3=X; + if (i == 30) a2=X; + if (i == 32) a1=X; + BODY_20_31(i,A,B,C,D,E,T,a1,a2,a3,X); + E=D; D=C; C=B; B=A; A=T; + } + + for (i=40; i<60; i++) + { + BODY_40_59(i,A,B,C,D,E,T,X); + E=D; D=C; C=B; B=A; A=T; + } + + for (i=60; i<80; i++) + { + BODY_60_79(i,A,B,C,D,E,T,X); + E=D; D=C; C=B; B=A; A=T; + } + + c->h0=(c->h0+A)&0xffffffffL; + c->h1=(c->h1+B)&0xffffffffL; + c->h2=(c->h2+C)&0xffffffffL; + c->h3=(c->h3+D)&0xffffffffL; + c->h4=(c->h4+E)&0xffffffffL; + + num-=64; + if (num <= 0) break; + + A=c->h0; + B=c->h1; + C=c->h2; + D=c->h3; + E=c->h4; + + W+=16; + } +#endif /* SMALL_CODE_SIZE */ + } + +void SHA1_Final(md, c) +unsigned char *md; +SHA_CTX *c; + { + register int i,j; + register SHA_LONG l; + register SHA_LONG *p; + const static unsigned char end[4]={0x80,0x00,0x00,0x00}; + unsigned char *cp= (unsigned char *)end; + + /* c->num should definitly have room for at least one more byte. */ + p=c->data; + j=c->num; + i=j>>2; + +#ifdef PURIFY + /* PURIFY */ + /* we reference uninitialised data but don't keep the result + * which purify complains about ... and we don't want to have + * to come back here to find a non-existant problem later + */ + + /* purify often complains about the following line as an + * Uninitialized Memory Read. While this can be true, the + * following p_c2l macro will reset l when that case is true. + * This is because j&0x03 contains the number of 'valid' bytes + * already in p[i]. If and only if j&0x03 == 0, the UMR will + * occur but this is also the only time p_c2l will do + * l= *(cp++) instead of l|= *(cp++) + */ + if ((j&0x03) == 0) p[i]=0; +#endif + + l=p[i]; + M_p_c2nl(cp,l,j&0x03); + p[i]=l; + i++; + /* i is the next 'undefined word' */ + if (c->num >= SHA_LAST_BLOCK) + { + for (; isha_block(c,(unsigned char *)p,64); + i=0; + } + for (; i<(SHA_LBLOCK-2); i++) + p[i]=0; + p[SHA_LBLOCK-2]=c->Nh; + p[SHA_LBLOCK-1]=c->Nl; +#if defined(L_ENDIAN) + Endian_Reverse32(p[SHA_LBLOCK-2]); + Endian_Reverse32(p[SHA_LBLOCK-1]); +#endif + c->sha_block(c,(unsigned char *)p,64); + cp=md; + l=c->h0; nl2c(l,cp); + l=c->h1; nl2c(l,cp); + l=c->h2; nl2c(l,cp); + l=c->h3; nl2c(l,cp); + l=c->h4; nl2c(l,cp); + + /* clear stuff, sha1_block may be leaving some stuff on the stack + * but I'm not worried :-) */ + c->num=0; +/* Memset((char *)&c,0,sizeof(c));*/ + } +#endif + +#if 0 +int pr(ctx) +SHA_CTX *ctx; + { + int i,j; + unsigned char *p=(unsigned char *)(ctx->data); + + fprintf(stderr,"num = %08X%08X\n",ctx->Nh,ctx->Nl); + fprintf(stderr," %08X %08X %08X %08X %08X\n", + ctx->h0,ctx->h1,ctx->h2,ctx->h3,ctx->h4); + fprintf(stderr,"bufnum = %d\n",ctx->num); + fprintf(stderr," "); + for (j=0; j<64; j+=16) + { + for (i=0; i<16; i++) + { +/* + if ((i+j) >= ctx->num) + fprintf(stderr,"--"); + else +*/ + fprintf(stderr,"%02X",p[i+j]); + } + if ((j+16) >=64) + fprintf(stderr,"\n"); + else + fprintf(stderr,"\n "); + } + } + +#endif + +#endif /* NO_SHA1 */ diff --git a/build/tools/makegcdfirm/Makefile b/build/tools/makegcdfirm/Makefile new file mode 100644 index 0000000..7158170 --- /dev/null +++ b/build/tools/makegcdfirm/Makefile @@ -0,0 +1,151 @@ +#! make -f +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makegcdfirm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- + +TARGET_PLATFORM = TWL + +SUPPORT_ECC = 0 + +ifeq ($(SUPPORT_ECC),1) +ECC_SRCDIR = ../../libraries/acsign_ecc/common \ + ../../libraries/acsign_ecc/common/algae/common/ecc \ + ../../libraries/acsign_ecc/common/algae/cmp \ + ../../libraries/acsign_ecc/common/algae/ecsource \ + +ECC_INCDIR = ../../libraries/acsign_ecc/include \ + ../../libraries/acsign_ecc/common/algae/include \ + ../../libraries/acsign_ecc/common/algae/common/include \ + +ECC_SRCS = acsign_ecc.c acsign_cryptoc.c \ + \ + cmparith.c cmpbits.c cmpcnv.c cmpdiv.c cmpmem.c \ + cmpmod.c cmpmuldv.c cmpspprt.c cmpsqr.c cmpvectr.c \ + computem.c ecfpatbl.c ecfpsmul.c \ + spcprime.c secfpcom.c \ + \ + p224v1.c p224v1a.c \ + +ECC_DEFS = -DRSA_PROTOTYPES=RSA_ENABLED \ + -DRCOM_BUILD=RSA_ENABLED -DRSA_FAST_INVERSE=RSA_ENABLED \ + -DRSA_STD_MEM_FUNCS=RSA_ENABLED -DRSA_STD_ALLOC_FUNCS=RSA_ENABLED \ +else +ECC_SRCDIR = +ECC_INCDIR = +ECC_SRCS = +ECC_DEFS = +endif + +SRCDIR += ../acsign $(ECC_SRCDIR) +INCDIR += ../acsign/include $(ECC_INCDIR) $(ECC_SRCDIR) + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +TARGETS = makegcdfirm.exe + +SOURCES_C = makegcdfirm.c \ + out_gcdfirm.c \ + misc.c \ + path.c \ + defval.c \ + compress.c \ + wram_regs.c \ + acsign.c \ + acsign_gcd.c \ + aes2.c \ + $(ECC_SRCS) + +SOURCES = $(SORUCES_C) + +OBJECTS = $(SOURCES_C:.c=.o) + +HEADERS = format_nlist.h \ + makegcdfirm.h \ + path.h \ + format_rom.h \ + misc.h \ + defval.h \ + compress.h \ + +MACROS += -DSMALL_CODE_SIZE \ + -DSTANDALONE \ + -DOPT_32_BIT \ + -DNO_SPLIT \ + -DNO_FP_API \ + -DNO_R_DIAG \ + $(ECC_DEFS) + +INSTALL_DIR = $(FIRM_INSTALL_TOOLSDIR)/bin +INSTALL_TARGETS = $(TARGETS) + +LDIRT_CLEAN = $(OBJECTS) $(TARGETS) version.h + + +VPATH = $(SRCDIR) +TWL_INCDIR := $(TWL_INCDIR) $(addprefix -I,$(INCDIR)) $(addprefix -I,$(FIRM_INCDIR)) + +include $(TWLSDK_ROOT)/build/buildtools/twl/modulerules.x86 + +#---------------------------------------------------------------------------- +# build +#---------------------------------------------------------------------------- +do-build: $(TARGETS) + +$(TARGETS): $(OBJECTS) + $(CC_X86) $+ -o $@ + +makegcdfirm.o: makegcdfirm.c makegcdfirm.h format_rom.h path.h version.h +out_gcdfirm.o: out_gcdfirm.c misc.h format_rom.h format_nlist.h format_sign.h elf.h compress.h \ + $(FIRM_INCDIR)/firm/format/sign.h \ + $(FIRM_INCDIR)/firm/format/wram_regs.h \ + $(FIRM_INCDIR)/firm/format/gcdfirm.h \ + +misc.o: misc.c misc.h +path.o: path.c path.h +compress.o: compress.c compress.h +wram_regs.o: wram_regs.c +acsign.o: acsign.c ../acsign/include/acsign.h +acsign_gcd.o: acsign_gcd.c format_sign.h \ + $(FIRM_INCDIR)/firm/format/sign.h \ + $(FIRM_INCDIR)/firm/format/wram_regs.h \ + $(FIRM_INCDIR)/firm/format/gcdfirm.h \ + +aes2.o: aes2.c aes2.h + +$(FIRM_INCDIR)/firm/format/sign.h: +$(FIRM_INCDIR)/firm/format/wram_regs.h: +$(FIRM_INCDIR)/firm/format/gcdfirm.h: +format_nlist.h: +format_rom.h: +makegcdfirm.h: +acsign.h: +acsign_gcd.h: +path.h: + +# avoid to warning message +misc.o:WARNING += -Wno-format-y2k + +# + +version.h: $(SOURCES) $(HEADERS) + @for i in $^ ; \ + do \ + date -r $$i +'#define SDK_DATE_OF_LATEST_FILE %Y%m%dUL'; \ + done | sort | tail -1 > $@ + +test: path.c misc.c + $(CC_X86) -DTEST $+ -o $@ diff --git a/build/tools/makegcdfirm/compress.c b/build/tools/makegcdfirm/compress.c new file mode 100644 index 0000000..6a8c403 --- /dev/null +++ b/build/tools/makegcdfirm/compress.c @@ -0,0 +1,293 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: compress.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // atoi() +#include // strcmp() +#include // isprint() +#include // chdir() +#include +#include // UCHAR_MAX +#include +#include // stat() +#include "elf.h" +#include "misc.h" +#include "defval.h" +#include "format_rom.h" +#include "format_nlist.h" +#include "makegcdfirm.h" + +//#define ADD_HEADER + +#define DIFF_CODE_HEADER (0x80) +#define RL_CODE_HEADER (0x30) +#define LZ_CODE_HEADER (0x10) +#define HUFF_CODE_HEADER (0x20) +#define CODE_HEADER_MASK (0xF0) + +//=========================================================================== +// LZ77k +//=========================================================================== +static u8 SearchLZ(const u8 *nextp, u32 remainSize, u16 *offset); + +static u16 windowPos; +static u16 windowLen; + +static s16 LZOffsetTable[4096]; +static s16 LZByteTable[256]; +static s16 LZEndTable[256]; + + +static void LZInitTable(void) +{ + u16 i; + + for (i = 0; i < 256; i++) + { + LZByteTable[i] = -1; + LZEndTable[i] = -1; + } + windowPos = 0; + windowLen = 0; +} + +static void SlideByte(const u8 *srcp) +{ + s16 offset; + u8 in_data = *srcp; + u16 insert_offset; + + if (windowLen == 4096) + { + u8 out_data = *(srcp - 4096); + if ((LZByteTable[out_data] = LZOffsetTable[LZByteTable[out_data]]) == -1) + { + LZEndTable[out_data] = -1; + } + insert_offset = windowPos; + } + else + { + insert_offset = windowLen; + } + + offset = LZEndTable[in_data]; + if (offset == -1) + { + LZByteTable[in_data] = insert_offset; + } + else + { + LZOffsetTable[offset] = insert_offset; + } + LZEndTable[in_data] = insert_offset; + LZOffsetTable[insert_offset] = -1; + + if (windowLen == 4096) + { + windowPos = (u16)((windowPos + 1) % 0x1000); + } + else + { + windowLen++; + } +} + +static void LZSlide(const u8 *srcp, u32 n) +{ + u32 i; + + for (i = 0; i < n; i++) + { + SlideByte(srcp++); + } +} + +/*---------------------------------------------------------------------------* + Name: MI_CompressLZ + + Description: LZ77ksȂ֐ + + Arguments: srcp kf[^ւ̃|C^ + size kf[^TCY + dstp kf[^ւ̃|C^ + kf[^傫TCỸobt@KvłB + + Returns: k̃f[^TCYB + k̃f[^kO傫Ȃꍇɂ͈k𒆒f0Ԃ܂B + *---------------------------------------------------------------------------*/ +u32 LZCompWrite(u8 *srcp, u32 size, u8 *dstp, int boundary) +{ + u32 LZDstCount; // kf[^̃oCg + u8 LZCompFlags; // k̗LtOn + u8 *LZCompFlagsp; // LZCompFlags i[郁̈|Cg + u16 lastOffset; // vf[^܂ł̃ItZbg (̎_ł̍Œvf[^) + u8 lastLength; // vf[^ (̎_ł̍Œvf[^) + u8 i; + u32 dstMax; + +#ifdef ADD_HEADER + *(u32 *)dstp = size << 8 | LZ_CODE_HEADER; // f[^Ewb_ + dstp += 4; +#endif + LZDstCount = 4; + dstMax = size; + LZInitTable(); + + while (size > 0) + { + LZCompFlags = 0; + LZCompFlagsp = dstp++; // tOn̊i[ + LZDstCount++; + + // tOn8rbgf[^ƂĊi[邽߁A8񃋁[v + for (i = 0; i < 8; i++) + { + LZCompFlags <<= 1; // (i=0) ͓ɈӖ͂Ȃ + if (size <= 0) + { + // I[ɗꍇ̓tOŌ܂ŃVtgĂI + continue; + } + + if ((lastLength = SearchLZ(srcp, size, &lastOffset))) + { + // k”\ȏꍇ̓tO𗧂Ă + LZCompFlags |= 0x1; + + // ItZbg͏4rbgƉ8rbgɕĊi[ + *dstp++ = (u8)((lastLength - 3) << 4 | (lastOffset - 1) >> 8); + *dstp++ = (u8)((lastOffset - 1) & 0xff); + LZDstCount += 2; + LZSlide(srcp, lastLength); + srcp += lastLength; + size -= lastLength; + } + else + { + // kȂ + LZSlide(srcp, 1); + *dstp++ = *srcp++; + size--; + LZDstCount++; + } + } // 8񃋁[vI + *LZCompFlagsp = LZCompFlags; // tOni[ + } + + // 16oCgEACg + // ACgpf[^0 ̓f[^TCYɊ܂߂ + i = 0; + while (LZDstCount & (boundary - 1)) +// while ((LZDstCount + i) & 0x3) + { + *dstp++ = 0; + LZDstCount++; + i++; + } + + return LZDstCount; +} + +//-------------------------------------------------------- +// LZ77kŃXCh̒Œv܂B +// Arguments: startp f[^̊Jnʒu|C^ +// nextp Jnf[^̃|C^ +// remainSize cf[^TCY +// offset vItZbgi[̈ւ̃|C^ +// Return : v񂪌‚ꍇ TRUE +// ‚Ȃꍇ FALSE +//-------------------------------------------------------- +static u8 SearchLZ(const u8 *nextp, u32 remainSize, u16 *offset) +{ + const u8 *searchp; + const u8 *headp, *searchHeadp; + u16 maxOffset; + u8 maxLength = 2; + u8 tmpLength; + s32 w_offset; + + if (remainSize < 3) + { + return 0; + } + + w_offset = LZByteTable[*nextp]; + + while (w_offset != -1) + { + if (w_offset < windowPos) + { + searchp = nextp - windowPos + w_offset; + } + else + { + searchp = nextp - windowLen - windowPos + w_offset; + } + + /* ĂǂA͂ɍ */ + if (*(searchp + 1) != *(nextp + 1) || *(searchp + 2) != *(nextp + 2)) + { + w_offset = LZOffsetTable[w_offset]; + continue; + } + + if (nextp - searchp < 2) + { + // VRAM2oCgANZXȂ̂ (VRAMf[^ǂݏoꍇ邽)A + // Ώۃf[^2oCgÕf[^ɂȂ΂ȂȂB + // + // ItZbg12rbgŊi[邽߁A4096ȉ + break; + } + tmpLength = 3; + searchHeadp = searchp + 3; + headp = nextp + 3; + + while (((u32)(headp - nextp) < remainSize) && (*headp == *searchHeadp)) + { + headp++; + searchHeadp++; + tmpLength++; + + // f[^4rbgŊi[邽߁A18ȉ (3̉ʂ͂) + if (tmpLength == (0xF + 3)) + { + break; + } + } + if (tmpLength > maxLength) + { + // ő咷ItZbgXV + maxLength = tmpLength; + maxOffset = (u16)(nextp - searchp); + if (maxLength == (0xF + 3)) + { + // vőȂ̂ŁAIB + break; + } + } + w_offset = LZOffsetTable[w_offset]; + } + + if (maxLength < 3) + { + return 0; + } + *offset = maxOffset; + return maxLength; +} + diff --git a/build/tools/makegcdfirm/compress.h b/build/tools/makegcdfirm/compress.h new file mode 100644 index 0000000..e3dc58f --- /dev/null +++ b/build/tools/makegcdfirm/compress.h @@ -0,0 +1,38 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: compress.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef COMPRESS_H_ +#define COMPRESS_H_ + +#include "misc.h" + + +/*---------------------------------------------------------------------------* + Name: MI_CompressLZ + + Description: LZ77ksȂ֐ + + Arguments: srcp kf[^ւ̃|C^ + size kf[^TCY + dstp kf[^ւ̃|C^ + kf[^傫TCỸobt@KvłB + + Returns: k̃f[^TCYB + *---------------------------------------------------------------------------*/ +u32 LZCompWrite(u8 *srcp, u32 size, u8 *dstp, int boundary); + + +#endif //COMPRESS_H_ diff --git a/build/tools/makegcdfirm/defval.c b/build/tools/makegcdfirm/defval.c new file mode 100644 index 0000000..679fb0e --- /dev/null +++ b/build/tools/makegcdfirm/defval.c @@ -0,0 +1,315 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makerom + File: defval.c + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: defval.c,v $ + Revision 1.10 2006/01/18 02:11:19 kitase_hirotake + do-indent + + Revision 1.9 2005/02/28 05:26:03 yosizaki + do-indent. + + Revision 1.8 2004/08/05 13:50:13 yasu + Support -M option + + Revision 1.7 2004/06/29 04:55:40 yasu + Use VBuffer to resolve variables + + Revision 1.6 2004/06/23 07:51:02 yasu + fix a bug as illegal memory freeing at ResolveDefVal() + + Revision 1.5 2004/05/27 00:40:49 yasu + care also about current directory (dot ".") + + Revision 1.4 2004/05/27 00:25:46 yasu + care about double-dots ".." for defvalue option :r, :e + + Revision 1.3 2004/05/27 00:11:19 yasu + fix a error when searching a "dot" of file extension + + Revision 1.2 2004/05/26 12:02:47 yasu + support :h, :t, :r, :e option for variable name + + Revision 1.1 2004/03/26 05:06:45 yasu + support variables like as -DNAME=VALUE + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include // getenv() +#include // strcasecmp() +#include // getopt() +#include "misc.h" +#include "defval.h" + +typedef struct tValdef +{ + struct tValdef *next; + char *name; + char *value; +} +tValdef; + +tValdef *valdef_top = NULL; + + +// +// Add new define value via file +// +// opt : "DEFINE=VALUE" +// +BOOL AddDefValFromFile(char *filename) +{ + char *buffer; + int buffer_size; + int read_size; + FILE *fp; + + if (filename[0] == '-' && filename[1] == '\0') + { + fp = stdin; + } + else if (NULL == (fp = fopen(filename, "rb"))) + { + fprintf(stderr, "Cannot open file \"%s\".\n", filename); + return FALSE; + } + + buffer_size = DEFVAL_DEFAULT_BUFFER_SIZE; + + if (NULL == (buffer = malloc(buffer_size))) + { + fprintf(stderr, "Cannot allocate memory.\n"); + return FALSE; + } + + read_size = 0; + + while (NULL != fgets(buffer + read_size, buffer_size - read_size, fp)) + { + read_size = strlen(buffer); + + if (read_size == buffer_size - 1 && buffer[read_size - 1] != '\n') + { + buffer_size *= 2; + + if (NULL == (buffer = realloc(buffer, buffer_size))) + { + fprintf(stderr, "Cannot allocate memory.\n"); + return FALSE; + } + continue; + } + + AddDefVal(buffer); + read_size = 0; + } + + if (fp != stdin) + { + fclose(fp); + } + free(buffer); + + return TRUE; +} + + +// +// Add new define value +// +// opt : "DEFINE=VALUE" +// +void AddDefVal(char *opt) +{ + int i; + tValdef *t; + + for (i = 0;; i++) + { + if ('=' == opt[i] || '\0' == opt[i]) + { + break; + } + } + + if (i > 0) + { + t = Alloc(sizeof(tValdef)); + t->name = strncpy(Alloc(i + 1), opt, i); + t->name[i] = '\0'; + + if (opt[i] == '=') + { + i++; + } + t->value = strdup(opt + i); + + t->next = valdef_top; + valdef_top = t; + + debug_printf("DEFINE:$(%s)=\"%s\"\n", t->name, t->value); + } + return; +} + +// +// Search define value +// +// Return: value of specified name +// +char *SearchDefVal(char *name) +{ + tValdef *t; + + for (t = valdef_top; t; t = t->next) + { + if (!strcmp(t->name, name)) + { + return t->value; + } + } + + return getenv(name); +} + + +// +// Search define value and Modify it by : option +// +// Return: duplicated value of specified name modified by :x option +// +char *SearchDefValWithOption(char *name) +{ + int len_name = strlen(name); + char *value; + char option = '\0'; + + if (len_name > 2 && name[len_name - 2] == ':') + { + name[len_name - 2] = '\0'; + option = name[len_name - 1]; + } + + value = SearchDefVal(name); + + if (value) + { + int value_len = strlen(value); + int col_dot = value_len; + int col_filename = 0; + int i; + + for (i = 0; i < value_len; i++) + { + switch (value[i]) + { + case '.': + if (col_filename == i && + (value[i + 1] == '\0' || (value[i + 1] == '.' && value[i + 2] == '\0'))) + { + i = value_len; // exit loop if last entry is . or .. + } + else + { + col_dot = i; // Save the last dot column + } + break; + + case '/': + case '\\': + case ':': + col_filename = i + 1; // Save the last filename + col_dot = value_len; // Reset dot position + break; + + default: + ; + } + } + + switch (option) + { + case 'h': // Dirname with the last slash + value = strdup(value); + value[col_filename] = '\0'; + break; + + case 't': // Filename + value = strdup(value + col_filename); + break; + + case 'r': // All without . file extension + value = strdup(value); + value[col_dot] = '\0'; + break; + + case 'e': // File extension + value = strdup(value + col_dot + 1); + break; + + default: + value = strdup(value); + } + } + return value; +} + + +// +// Resolve define value +// +// Return: new string +// +char *ResolveDefVal(char *str) +{ + int i, j; + char *val; + VBuffer buf; + + InitVBuffer(&buf); + + for (i = 0; '\0' != str[i]; i++) + { + // search $(XXX) + if ('$' == str[i] && '(' == str[i + 1]) + { + for (j = i + 2; '\0' != str[j]; j++) + { + if (')' == str[j]) + { + str[j] = '\0'; + + // get value of XXX + val = SearchDefValWithOption(&str[i + 2]); + + // copy value of XXX + if (val) + { + char *s = val; + + while (*s) + { + PutVBuffer(&buf, *s); + s++; + } + free(val); + } + i = j; + goto next; + } + } + } + PutVBuffer(&buf, str[i]); + next:; + } + return GetVBuffer(&buf); // pass allocated buffer, should be freed by caller +} diff --git a/build/tools/makegcdfirm/defval.h b/build/tools/makegcdfirm/defval.h new file mode 100644 index 0000000..7135510 --- /dev/null +++ b/build/tools/makegcdfirm/defval.h @@ -0,0 +1,38 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makerom + File: defval.h + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: defval.h,v $ + Revision 1.4 2006/01/18 02:11:19 kitase_hirotake + do-indent + + Revision 1.3 2005/02/28 05:26:03 yosizaki + do-indent. + + Revision 1.2 2004/08/05 13:50:13 yasu + Support -M option + + Revision 1.1 2004/03/26 05:06:45 yasu + support variables like as -DNAME=VALUE + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef DEFVAL_H_ +#define DEFVAL_H_ + +#define DEFVAL_DEFAULT_BUFFER_SIZE (1024) + +BOOL AddDefValFromFile(char *filename); +void AddDefVal(char *opt); +char *SearchDefVal(char *name); +char *ResolveDefVal(char *str); + +#endif //DEFVAL_H_ diff --git a/build/tools/makegcdfirm/elf.h b/build/tools/makegcdfirm/elf.h new file mode 100644 index 0000000..c360cd3 --- /dev/null +++ b/build/tools/makegcdfirm/elf.h @@ -0,0 +1,431 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - ELF + File: elf.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + *---------------------------------------------------------------------------*/ + +#ifndef ELF_H_ +#define ELF_H_ + +#include "misc.h" + +/*--------------------------------------------------------- + ^` + --------------------------------------------------------*/ +typedef u32 Elf32_Addr; /* size:4, align:4 Unsigned program address */ +typedef u16 Elf32_Half; /* size:2, align:2 Unsigned medium int */ +typedef u32 Elf32_Off; /* size:4, align:4 Unsigned file offset */ +typedef s32 Elf32_Sword; /* size:4, align:4 Signed large int */ +typedef u32 Elf32_Word; /* size:4, align:4 Unsigned large int */ + +/*--------------------------------------------------------- + ELF Header + --------------------------------------------------------*/ +/* e_ident̃CfbNX */ +#define EI_MAG0 0 /* File identification */ +#define EI_MAG1 1 /* File identification */ +#define EI_MAG2 2 /* File identification */ +#define EI_MAG3 3 /* File identification */ +#define EI_CLASS 4 /* File class 0=invalid, 1=32bit, 2=64bit */ +#define EI_DATA 5 /* Data encoding 0=invalid, 1=LSB, 2=MSB */ +#define EI_VERSION 6 /* File version ݂1 */ +#define EI_PAD 7 /* Start of padding bytes */ +#define EI_NIDENT 16 /* Size of e_ident[] */ + +typedef struct { + unsigned char e_ident[EI_NIDENT]; + Elf32_Half e_type; /* ELF̌`(Ĕzu”\, s”\Ȃ) */ + Elf32_Half e_machine; /* t@CŗvA[LeN` */ + Elf32_Word e_version; /* ELFtH[}bg̃o[Wi݂1j */ + Elf32_Addr e_entry; /* vÕGg|CgBw薳Ȃ0B */ + Elf32_Off e_phoff; /* vOwb_e[ũt@C擪̃ItZbg */ + Elf32_Off e_shoff; /* ZNVwb_e[ũt@C擪̃ItZbg */ + Elf32_Word e_flags; /* vZbTŗL̃tO */ + Elf32_Half e_ehsize; /* ELFwb_̃TCY */ + Elf32_Half e_phentsize; /* 1vOwb_̃TCY */ + Elf32_Half e_phnum; /* vOwb_̐ */ + Elf32_Half e_shentsize; /* 1ZNVwb_̃TCY */ + Elf32_Half e_shnum; /* ZNVwb_̐ */ + Elf32_Half e_shstrndx; /* ZNVe[uZNVւ̃CfbNX */ +} Elf32_Ehdr; + +/* e_ident[EI_*]̒g` */ +#define ELFMAG0 0x7f +#define ELFMAG1 'E' +#define ELFMAG2 'L' +#define ELFMAG3 'F' +#define ELFCLASSNONE 0 /* invalid */ +#define ELFCLASS32 1 /* ARM and Thumb processors use 32-bit ELF. */ +#define ELFCLASS64 2 +#define ELFDATANONE 0 /* invalid */ +#define ELFDATA2LSB 1 /* little-endian */ +#define ELFDATA2MSB 2 /* big-endian */ + + +/* [e_type] */ +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* Re-locatable file */ +#define ET_EXEC 2 /* Executable file */ +#define ET_DYN 3 /* Shared object file */ +#define ET_CORE 4 /* Core file */ +#define ET_LOPROC 0xff00 /* Processor-specific */ +#define ET_HIPROC 0xffff /* Processor-specific */ + +/* [e_machine] */ +#define EM_NONE 0 /* No machine */ +#define EM_M32 1 +#define EM_SPARC 2 +#define EM_386 3 +#define EM_68K 4 +#define EM_88K 5 +#define EM_860 7 +#define EM_MIPS 8 +#define EM_MIPS_RS4_BE 10 +#define EM_ARM 40 /* ARM/Thumb Architecture */ + + +/* [e_version] This member identifies the object file version.*/ +#define EV_NONE 0 /* Invalid version */ +#define EV_CURRENT 1 /* Current version */ + + +/* + ARM-specific e_flags + e_flags Field Value Meaning + EF_ARM_HASENTRY (0x02) e_entry contains a program-loader entry point + (see section 4.1.1, Entry points, below). + EF_ARM_SYMSARESORTED (0x04) Each subsection of the symbol table is sorted by symbol value + (see section 4.4.8, Symbol table order, below) + EF_ARM_DYNSYMSUSESEGIDX (0x8) Symbols in dynamic symbol tables that are defined in sections + included in program segment n have st_shndx = n + 1. + (see section 4.4.9, Dynamic symbol table entries, below). + EF_ARM_MAPSYMSFIRST (0x10) Mapping symbols precede other local symbols in the symbol table + (see section 4.4.8, Symbol table order, below). + + EF_ARM_EABIMASK (0xFF000000)(current version is 0x02000000) + This masks an 8-bit version number, the version of the ARM + EABI to which this ELF file conforms. This EABI is version 2. A + value of 0 denotes unknown conformance. +*/ +#define EF_ARM_HASENTRY 0x02 +#define EF_ARM_SYMSARESORTED 0x04 +#define EF_ARM_DYNSYMSUSESEGIDX 0x8 +#define EF_ARM_MAPSYMSFIRST 0x10 +#define EF_ARM_EABIMASK 0xFF000000 + + +/*--------------------------------------------------------- + Program headers + --------------------------------------------------------*/ +typedef struct { + Elf32_Word p_type; + Elf32_Off p_offset; + Elf32_Addr p_vaddr; + Elf32_Addr p_paddr; + Elf32_Word p_filesz; + Elf32_Word p_memsz; + Elf32_Word p_flags; + Elf32_Word p_align; +} Elf32_Phdr; + +/* [p_type] */ +#define PT_NULL 0 /* gȂGgŁÃo̒l̈Ӗ͖` */ +#define PT_LOAD 1 /* sɃ[hZOg */ +#define PT_DYNAMIC 2 /* I\̔zێZOg */ +#define PT_INTERP 3 /* t@C̉߂ɎgC^v^̃pXێZOg */ +#define PT_NOTE 4 /* t@C̉߂ɂ͎gȂێZOg */ +#define PT_SHLIB 5 /* \ */ +#define PT_PHDR 6 /* vOwb_e[uivÕC[Ẅꕔłꍇ̂ݑ݁j */ +//#define PT_TLS ? /* XbhǏL̈̃ev[g */ + +#define PT_LOOS 0x60000000 /* OSŗLɗ\񂳂ꂽ̈ */ +#define PT_HIOS 0x6fffffff + +#define PT_LOPROC 0x70000000 /* vZbTŗLɗ\񂳂ꂽ̈ */ +#define PT_HIPROC 0x7fffffff + +/* [p_flags]*/ +#define PF_X 1 /*s”\*/ +#define PF_W 2 /*݉”\*/ +#define PF_R 4 /*ǂݏo”\*/ +#define PF_ARM_SB 0x10000000 /*The segment contains the location addressed by the static base*/ +#define PF_ARM_PI 0x20000000 /*The segment is position-independent*/ +#define PF_ARM_ENTRY 0x80000000 /*The segment contains the entry point*/ +#define PF_MASKPROC 0xf0000000 + + +/*--------------------------------------------------------- + Section headers + --------------------------------------------------------*/ +typedef struct { + Elf32_Word sh_name; /*ZNVwb_e[uZNṼCfbNX*/ + Elf32_Word sh_type; /* ^CviL`QƁj */ + Elf32_Word sh_flags; + Elf32_Addr sh_addr; /* */ + Elf32_Off sh_offset; /* t@C̐擪̃ItZbg */ + Elf32_Word sh_size; /* oCgPʂ̃TCY */ + Elf32_Word sh_link; /* sh_typeɂĒl̈Ӗς */ + Elf32_Word sh_info; /* sh_typeɂĒl̈Ӗς */ + Elf32_Word sh_addralign; /* ACg(0or1ŐȂ,44ByteAlign) */ + Elf32_Word sh_entsize; /* ŒTCỸGge[uꍇA1vf̃TCY */ +} Elf32_Shdr; + +/* sh_addr mod sh_addralign = 0 łȂ΂ȂȂ */ + +/* Section Types, [sh_type] */ +#define SHT_NULL 0 +#define SHT_PROGBITS 1 +#define SHT_SYMTAB 2 +#define SHT_STRTAB 3 +#define SHT_RELA 4 +#define SHT_HASH 5 +#define SHT_DYNAMIC 6 +#define SHT_NOTE 7 +#define SHT_NOBITS 8 +#define SHT_REL 9 +#define SHT_SHLIB 10 +#define SHT_DYNSYM 11 +#define SHT_LOPROC 0x70000000 +#define SHT_HIPROC 0x7fffffff +#define SHT_LOUSER 0x80000000 +#define SHT_HIUSER 0xffffffff + + +/* [sh_flags] */ +#define SHF_WRITE 0x1 +#define SHF_ALLOC 0x2 +#define SHF_EXECINSTR 0x4 +#define SHF_MASKPROC 0xf0000000 +/* ARM-EABI-specific */ +#define SHF_ENTRYSECT 0x10000000 /* The section contains an entry point. */ +#define SHF_COMDEF 0x80000000 /* The section may be multiply defined in the input to a link step. */ +/* others */ +#define SHF_LINK_ORDER 0x80 + +/*ZNVCfbNX*/ +//Sym->st_shndxȂ +#define SHN_UNDEF 0 +#define SHN_LORESERVE 0xff00 +#define SHN_LOPROC 0xff00 +#define SHN_HIPROC 0xff1f +#define SHN_ABS 0xfff1 +#define SHN_COMMON 0xfff2 +#define SHN_HIRESERVE 0xffff + + +//̓wb_łȂ̃f[^\ + +/*--------------------------------------------------------- + Symbol Table Entry + --------------------------------------------------------*/ +typedef struct { + Elf32_Word st_name; /* V{e[ũCfbNX */ + Elf32_Addr st_value; /* 炭֘AZNVł̃ItZbgl */ + Elf32_Word st_size; /* TCYȂAsȏꍇ 0 */ + unsigned char st_info; /* oCh ^Cv */ + unsigned char st_other; /* ݂ 0 */ + Elf32_Half st_shndx; /* ֘AZNVwb_e[ũCfbNX */ +} Elf32_Sym; + + +/* st_info */ +#define ELF32_ST_BIND(i) ((i)>>4) +#define ELF32_ST_TYPE(i) ((i)&0xf) +#define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) + +/* st_info BIND */ +#define STB_LOCAL 0 +#define STB_GLOBAL 1 +#define STB_WEAK 2 +#define STB_LOPROC 13 +#define STB_HIPROC 15 + +/* st_info TYPE */ +#define STT_NOTYPE 0 /*`*/ +#define STT_OBJECT 1 /*f[^IuWFNg*/ +#define STT_FUNC 2 +#define STT_SECTION 3 +#define STT_FILE 4 +#define STT_LOPROC 13 +#define STT_HIPROC 15 + + +/*--------------------------------------------------------- + Relocation Entry + --------------------------------------------------------*/ +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; +} Elf32_Rel; + +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; + Elf32_Sword r_addend; +} Elf32_Rela; + +#define ELF32_R_SYM(i) ((i)>>8) +#define ELF32_R_TYPE(i) ((unsigned char)(i)) +#define ELF32_R_INFO(s,t) (((s)<<8)+(unsigned char)(t)) + + +/* r_info TYPE */ +#define R_ARM_NONE 0 /* Any No relocation. Encodes dependencies between sections. */ +#define R_ARM_PC24 1 /* ARM B/BL S . P + A */ +#define R_ARM_ABS32 2 /* 32-bit word S + A */ +#define R_ARM_REL32 3 /* 32-bit word S . P + A */ +#define R_ARM_PC13 4 /* ARM LDR r, [pc,c] S . P + A */ +#define R_ARM_ABS16 5 /* 16-bit half-word S + A */ +#define R_ARM_ABS12 6 /* ARM LDR/STR S + A */ +#define R_ARM_THM_ABS5 7 /* Thumb LDR/STR S + A */ +#define R_ARM_ABS8 8 /* 8-bit byte S + A */ +#define R_ARM_SBREL32 9 /* 32-bit word S . B + A */ +#define R_ARM_THM_PC22 10 /* Thumb BL pair S . P+ A */ +#define R_ARM_THM_PC8 11 /* Thumb LDR r, [pc,c] S . P + A */ +#define R_ARM_AMP_VCALL9 12 /* AMP VCALL Obsolete.SA-1500 only. */ +#define R_ARM_SWI24 13 /* ARM SWI S + A */ +#define R_ARM_THM_SWI8 14 /* Thumb SWI S + A */ +#define R_ARM_XPC25 15 /* ARM BLX S . P+ A */ +#define R_ARM_THM_XPC22 16 /* Thumb BLX pair S . P+ A */ + +/* 17-31, reserved to ARM Linux */ +//17-19 Reserved to ARM LINUX +#define R_ARM_COPY 20 /* 32 bit word Copy symbol at dynamic link time. */ +#define R_ARM_GLOB_DAT 21 /* 32 bit word Create GOT entry. */ +#define R_ARM_JUMP_SLOT 22 /* 32 bit word Create PLT entry. */ +#define R_ARM_RELATIVE 23 /* 32 bit word Adjust by program base. */ +#define R_ARM_GOTOFF 24 /* 32 bit word Offset relative to start of GOT. */ +#define R_ARM_GOTPC 25 /* 32 bit word Insert address of GOT. */ +#define R_ARM_GOT32 26 /* 32 bit word Entry in GOT. */ +#define R_ARM_PLT32 27 /* ARM BL Entry in PLT. */ + +/* 28-31 Reserved to ARM LINUX */ +#define R_ARM_ALU_PCREL_7_0 32 /* ARM ADD/SUB (S . P + A) & 0x000000FF */ +#define R_ARM_ALU_PCREL_15_8 33 /* ARM ADD/SUB (S . P + A) & 0x0000FF00 */ +#define R_ARM_ALU_PCREL_23_15 34 /* ARM ADD/SUB (S . P + A) & 0x00FF0000 */ +#define R_ARM_LDR_SBREL_11_0 35 /* ARM LDR/STR (S . B + A) & 0x00000FFF */ +#define R_ARM_ALU_SBREL_19_12 36 /* ARM ADD/SUB (S . B + A) & 0x000FF000 */ +#define R_ARM_ALU_SBREL_27_20 37 /* ARM ADD/SUB (S . B + A) & 0x0FF00000 */ + +#define R_ARM_TARGET1 38 +#define R_ARM_ROSEGREL32 39 +#define R_ARM_V4BX 40 +#define R_ARM_TARGET2 41 +#define R_ARM_PREL31 42 + +/* 96-111, reserved to ARM g++ */ +#define R_ARM_GNU_VTENTRY 100 /* 32 bit word Record C++ vtable entry. */ +#define R_ARM_GNU_VTINHERIT 101 /* 32 bit word Record C++ member usage. */ +#define R_ARM_THM_PC11 102 /* Thumb B S . P + A */ +#define R_ARM_THM_PC9 103 /* Thumb B S . P + A */ + +/* 112-127, reserved for private experiments */ + +/* 128-248, reserved to ARM */ +#define R_ARM_RXPC25 249 /* ARM BLX (S . P) + A #define For calls between program segments. */ +#define R_ARM_RSBREL32 250 /* Word (S . SB) + A For an offset from SB, the static base. */ +#define R_ARM_THM_RPC22 251 /* Thumb BL/BLX pair (S . P) + A For calls between program segments. */ +#define R_ARM_RREL32 252 /* Word (S . P) + A For on offset between two segments. */ +#define R_ARM_RABS32 253 /* Word S + A For the address of a location in the target segment. */ +#define R_ARM_RPC24 254 /* ARM B/BL (S . P) + A For calls between program segments. */ +#define R_ARM_RBASE 255 /* None None.Identifies the segment being relocated by the following + relocation directives. The ARM EABI poses two problems for relocating + executables and shared objects encoded in */ + + +// shirait +#define R_ARM_LDR_PC_G0 4 //LDR + +#define R_ARM_ABS12 6 //LDR, STR + +#define R_ARM_THM_CALL 10 //R_ARM_THM_PC22Ɠ + +#define R_ARM_CALL 28 //BL/BLX +#define R_ARM_JUMP24 29 //B/BL +#define R_ARM_THM_JUMP24 30 + +#define R_ARM_MOVW_ABS_NC 43 //MOVW +#define R_ARM_MOVT_ABS 44 //MOVT +#define R_ARM_MOVW_PREL_NC 45 //MOVW +#define R_ARM_MOVT_PREL 46 //MOVT + +#define R_ARM_ALU_PC_G0_NC 57 //ADD, SUB +#define R_ARM_ALU_PC_G0 58 //ADD, SUB +#define R_ARM_ALU_PC_G1_NC 59 //ADD, SUB +#define R_ARM_ALU_PC_G1 60 //ADD, SUB +#define R_ARM_ALU_PC_G2 61 //ADD, SUB +#define R_ARM_LDR_PC_G1 62 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_PC_G2 63 //LDR, STR, LDRB, STRB +#define R_ARM_LDRS_PC_G0 64 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_PC_G1 65 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_PC_G2 66 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDC_PC_G0 67 //LDC, STC +#define R_ARM_LDC_PC_G1 68 //LDC, STC +#define R_ARM_LDC_PC_G2 69 //LDC, STC +#define R_ARM_ALU_SB_G0_NC 70 //ADD, SUB +#define R_ARM_ALU_SB_G0 71 //ADD, SUB +#define R_ARM_ALU_SB_G1_NC 72 //ADD, SUB +#define R_ARM_ALU_SB_G1 73 //ADD, SUB +#define R_ARM_ALU_SB_G2 74 //ADD, SUB +#define R_ARM_LDR_SB_G0 75 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_SB_G1 76 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_SB_G2 77 //LDR, STR, LDRB, STRB +#define R_ARM_LDRS_SB_G0 78 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_SB_G1 79 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_SB_G2 80 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDC_SB_G0 81 //LDC, STC +#define R_ARM_LDC_SB_G1 82 //LDC, STC +#define R_ARM_LDC_SB_G2 83 //LDC, STC +#define R_ARM_MOVW_BREL_NC 84 //MOVW +#define R_ARM_MOVT_BREL 85 //MOVT +#define R_ARM_MOVW_BREL 86 //MOVW + +#define R_ARM_GOT_BREL12 97 //LDR +#define R_ARM_GOTOFF12 98 //LDR, STR + +#define R_ARM_TLS_LDO12 109 //LDR, STR +#define R_ARM_TLS_LE12 110 //LDR, STR +#define R_ARM_TLS_TE12GP 111 //LDR + + + +/*--------------------------------------------------------- + Dynamic Section elf_v1.2 + --------------------------------------------------------*/ +typedef struct { + Elf32_Sword d_tag; + union { + Elf32_Word d_val; + Elf32_Addr d_ptr; + } d_un; +} Elf32_Dyn; + + +/* Additional symbol types for Thumb. */ +#define STT_ARM_TFUNC STT_LOPROC /* A Thumb function. */ +#define STT_ARM_16BIT STT_HIPROC /* A Thumb label. */ + + + + + + + + + +/*--------------------------------------------------------- + ELFwb_ǂݏo + --------------------------------------------------------*/ +void *ELF_LoadELFHeader(const void *buf, Elf32_Ehdr *ehdr); + + + +#endif /* ELF_H_ */ + diff --git a/build/tools/makegcdfirm/format_nlist.h b/build/tools/makegcdfirm/format_nlist.h new file mode 100644 index 0000000..e3bee64 --- /dev/null +++ b/build/tools/makegcdfirm/format_nlist.h @@ -0,0 +1,54 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: format_nlist.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_NLIST_H_ +#define FORMAT_NLIST_H_ + +#include +#include "misc.h" +#include "path.h" + +#define SPECFILE_MAGIC_ID "#NORSF" + +#define CRC16_INIT_VALUE 0xffff + +//--------------------------------------------------------------------------- +// Banner Spec File +//--------------------------------------------------------------------------- + +// Command List +typedef struct +{ + char *string; + BOOL (*funcp) (char *, int num); + +} +tCommandDesc; + + +// F Command +typedef struct +{ + u32 offsetStart; + u32 offsetEnd; + u32 padding; + char fullPathSrc[FILENAME_MAX]; + +} +tFileDesc; + + +#endif // FORMAT_NLIST_H_ diff --git a/build/tools/makegcdfirm/format_rom.h b/build/tools/makegcdfirm/format_rom.h new file mode 100644 index 0000000..c1c6d89 --- /dev/null +++ b/build/tools/makegcdfirm/format_rom.h @@ -0,0 +1,59 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: format_rom.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_ROM_H_ +#define FORMAT_ROM_H_ + +#include "misc.h" +#include + + +#define DEFAULT_ALIGN 0x200 +#define FIRM_ALIGN DEFAULT_ALIGN +#define FIRM_ALIGN_MASK (FIRM_ALIGN - 1) + +#define NML_AREA_ALIGN 0x80000 // 512KB +#define TWL_AREA_ALIGN 0x80000 // 512KB +#define SEC2_AREA_OFFSET 0x3000 // 12KB +#define GAME2_AREA_OFFSET 0x7000 // 28KB + +#define DEFAULT_HOSTROOT "." +#define DEFAULT_ROOT "/" + +#define DEFAULT_REJECT_1 "CVS" +#define DEFAULT_REJECT_2 "vssver.scc" + +#define FORMAT_VERSION "1.0" + +#define ENTRYNAME_MAX 127 + +#define ROM_SIZE_MIN 0x20000 + +#define DEFAULT_ROMHEADER_TEMPLATE "gcdfirm_header_twlj.template.sbin" +#define DEFAULT_LISTFILE "default.nlf" + +#define DEFAULT_NORFIRM_SUFFIX ".gcd" +#define DEFAULT_SPECFILE_SUFFIX ".gcdsf" + +/*===========================================================================* + * ROM FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// ROM HEADER +//--------------------------------------------------------------------------- + +#endif //FORMAT_ROM_H_ diff --git a/build/tools/makegcdfirm/format_sign.h b/build/tools/makegcdfirm/format_sign.h new file mode 100644 index 0000000..782a5d2 --- /dev/null +++ b/build/tools/makegcdfirm/format_sign.h @@ -0,0 +1,32 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - SS + File: format_sign.h + + Copyright 2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_MAKENORFIRM_ACSIGN_FORMAT_H_ +#define FIRM_MAKENORFIRM_ACSIGN_FORMAT_H_ + +#include "format_rom.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_MAKENORFIRM_ACSIGN_FORMAT_H_ */ +#endif diff --git a/build/tools/makegcdfirm/gcdfirm_header_twlj.template.sbin b/build/tools/makegcdfirm/gcdfirm_header_twlj.template.sbin new file mode 100644 index 0000000..60ed6b7 Binary files /dev/null and b/build/tools/makegcdfirm/gcdfirm_header_twlj.template.sbin differ diff --git a/build/tools/makegcdfirm/makegcdfirm.c b/build/tools/makegcdfirm/makegcdfirm.c new file mode 100644 index 0000000..9afa68a --- /dev/null +++ b/build/tools/makegcdfirm/makegcdfirm.c @@ -0,0 +1,106 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: makegcdfirm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include +#include // strcasecmp() +#include // getopt() +#include "makegcdfirm.h" +#include "format_rom.h" +#include "path.h" +#include "defval.h" +#include "version.h" + +static int makegcdfirm(const char *specFile, const char *norFile); + +//--------------------------------------------------------------------------- +// Main +//--------------------------------------------------------------------------- + +int main(int argc, char *argv[]) +{ + int n; + int narg; + char *gcdfirmFile; + + InitAppName(argv[0]); + + while ((n = getopt(argc, argv, "D:hvpd")) != -1) + { + switch (n) + { + case 'h': + case 'v': + goto usage; + + case 'D': + AddDefVal(optarg); + break; + + case 'p': + PrintMode = TRUE; + break; + + case 'd': + DebugMode = TRUE; + break; + + default: + break; + } + } + + narg = argc - optind; + if (narg > 0) + { + // Make SpecFile->GcdfirmFile + gcdfirmFile = + strdup(narg > + 1 ? argv[optind + 1] : ChangeSuffix(argv[optind], DEFAULT_NORFIRM_SUFFIX)); + return makegcdfirm(argv[optind], gcdfirmFile); + } + + usage: + { + char *makegcdfirm = GetAppName(); + + fprintf(stderr, + "NITRO-SDK Development Tool - %s - Make gcdfirm file \n" + "Build %lu\n\n" + "Usage: %s [-phv] [-DNAME=VALUE ...] SPECFILE [NORFIRMFILE]\n\n", + makegcdfirm, SDK_DATE_OF_LATEST_FILE, makegcdfirm); + } + return 1; +} + + +//--------------------------------------------------------------------------- +// makegcdfirm +//--------------------------------------------------------------------------- + +static int makegcdfirm(const char *specFile, const char *norFile) +{ + debug_printf("makegcdfirm(): '%s' -> '%s'\n", specFile, norFile); + + // Check identical + if (specFile && norFile && !strcasecmp(specFile, norFile)) + { + error("gcdfirm spec file is identical '%s'", norFile); + return 1; + } + + return OutputGcdfirmFile(specFile, norFile) ? 0 : 1; +} diff --git a/build/tools/makegcdfirm/makegcdfirm.h b/build/tools/makegcdfirm/makegcdfirm.h new file mode 100644 index 0000000..c38c14a --- /dev/null +++ b/build/tools/makegcdfirm/makegcdfirm.h @@ -0,0 +1,24 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: makegcdfirm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef MAKEGCDFIRM_H_ +#define MAKEGCDFIRM_H_ + +#include "misc.h" + +BOOL OutputGcdfirmFile(const char *specFile, const char *gcdFile); + +#endif //MAKEGCDFIRM_H_ diff --git a/build/tools/makegcdfirm/misc.c b/build/tools/makegcdfirm/misc.c new file mode 100644 index 0000000..7706d6b --- /dev/null +++ b/build/tools/makegcdfirm/misc.c @@ -0,0 +1,628 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: misc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // calloc() +#include // free(), exit() +#include // setmode() +#include // stat() +#include // setmode() +#include // strlen() +#include // va_start(),va_end() +#include // localtime() + +#include +#include "misc.h" + +BOOL DebugMode = FALSE; +BOOL PrintMode = FALSE; +char *PubkeyFileName = NULL; + +/*---------------------------------------------------------------------------* + * File Output Utilities + * + * BOOL OpenFile( const char* filename ) + * void CloseFile( void ) + * BOOL CheckResult( void ) + * void PutBuffer( const void* ptr, int len ) + * void PutByte( u8 c ) + * void PutWord( u16 c ) + * void PutWord( u32 c ) + * void PutString( const char *str ) + *---------------------------------------------------------------------------*/ + +static FILE *OutFile = NULL; +static const char *FileName = NULL; +static BOOL Status = FALSE; + + +// +// File Open +// + +BOOL OpenFile(const char *filename) +{ + if (OutFile) + CloseFile(); + + if (filename) + { + if (NULL == (OutFile = fopen(filename, "wb+"))) + { + error("Can't write '%s'", filename); + Status = FALSE; + return FALSE; + } + } + else + { + setmode(1, O_BINARY); + OutFile = stdout; // out to console if filename == NULL + } + FileName = filename; + Status = TRUE; + + return TRUE; +} + + +// +// File Close +// + +BOOL CloseFile(void) +{ + if (OutFile) + { + if (FileName) + { + if (fclose(OutFile) == -1) + { + error("Can't close '%s'", FileName); + Status = FALSE; + } + } + else + { + setmode(1, O_TEXT); + } + } + OutFile = NULL; + + return Status; +} + + +// +// File Seek +// + +void SeekFile(long pos) +{ + if (OutFile && fseek(OutFile, pos, SEEK_SET)) + { + error("Can't seek '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + + +// +// Error Check +// + +BOOL CheckResult(void) +{ + return Status; +} + + +// +// Delete outfile +// + +void DeleteOutFile(void) +{ + // Delete outfile + if (FileName) + { + debug_printf("Delete '%s'\n", FileName); + (void)unlink(FileName); + FileName = NULL; + } + return; +} + + +// +// Buffer Output +// + +void PutBuffer(const void *ptr, int len) /* If error, close file */ +{ + if (OutFile && len != fwrite(ptr, 1, len, OutFile)) + { + error("Can't write buffer to '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + +// +// Buffer Input +// + +void GetBuffer(void *ptr, int len) /* If error, close file */ +{ + if (OutFile && len != fread(ptr, 1, len, OutFile)) + { + error("Can't read '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + +// +// Byte/Half/Word Output +// + +void PutByte(u8 c) +{ + PutBuffer(&c, 1); +} +void PutHalf(u16 c) +{ + PutBuffer(&c, 2); +} +void PutWord(u32 c) +{ + PutBuffer(&c, 4); +} +void PutString(const char *str) +{ + PutBuffer(str, strlen(str)); +} + + +// +// Printf +// + +void PrintString(const char *fmt, ...) +{ + char *buffer; + va_list va; + int nchars; + int bufsize = FILENAME_MAX; + + while (1) + { + buffer = Alloc(bufsize); + va_start(va, fmt); + nchars = vsnprintf(buffer, bufsize, fmt, va); + va_end(va); + + if (0 <= nchars && nchars < bufsize) + { + break; + } + + Free(&buffer); + bufsize *= 2; + } + + if (nchars > 0) + { + PutBuffer(buffer, nchars); + } + Free(&buffer); +} + + +/*---------------------------------------------------------------------------* + * File Read/Write Utilities + * + * int ReadFile( const char* filename, void** buffer ) + * + * Read a file to buffer allocated internally + * Return read size + * Add '\0' at tail of file for help to handle text file + * + * BOOL WriteFile( const char* filename, void** buffer, int size ) + *---------------------------------------------------------------------------*/ + +int ReadFile(const char *filename, void *filebuffer, int size) +{ + FILE *fp; + struct stat fileStat; + int fileSize, readSize; + void **buffer = (void **)filebuffer; + + /* Check file */ + if (stat(filename, &fileStat) || !S_ISREG(fileStat.st_mode)) + { + goto error; + } + fileSize = fileStat.st_size; + if (fileSize < 0) + { + goto error; + } + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) + { + goto error; + } + + if (size && (size < fileSize)) + { + readSize = size; + } + else + { + readSize = fileSize; + } + + /* Read file */ + *buffer = Alloc(readSize + 1); /* error handle is done in Alloc() */ + /* size+1 for '\0' to handle text file */ + if (readSize != fread(*buffer, sizeof(char), readSize, fp)) + { + goto error_free_close; + } + + (*(char **)buffer)[readSize] = '\0'; /* Works as terminater if file is text file */ + + /* Close file */ + fclose(fp); + return readSize; + + error_free_close: + Free(buffer); + fclose(fp); + error: + error("Can't read '%s'", filename); + return -1; +} + + +int ReadFileWithPadding(const char *filename, void *filebuffer, int size, int boundary) +{ + FILE *fp; + struct stat fileStat; + int fileSize, readSize, padSize; + void **buffer = (void **)filebuffer; + + if (!boundary) + { + return ReadFile(filename, buffer, size); + } + + /* Check file */ + if (stat(filename, &fileStat) || !S_ISREG(fileStat.st_mode)) + { + goto error; + } + fileSize = fileStat.st_size; + if (fileSize < 0) + { + goto error; + } + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) + { + goto error; + } + + if (size && (size < fileSize)) + { + readSize = size; + } + else + { + readSize = fileSize; + } + + padSize = (boundary - (readSize & (boundary-1))) & (boundary-1); + + /* Read file */ + *buffer = Alloc(readSize + padSize); /* error handle is done in Alloc() */ + /* size+1 for '\0' to handle text file */ + if (readSize != fread(*buffer, sizeof(char), readSize, fp)) + { + goto error_free_close; + } + + memset((char*)*buffer + readSize, 0, padSize); + + /* Close file */ + fclose(fp); + return readSize + padSize; + + error_free_close: + Free(buffer); + fclose(fp); + error: + error("Can't read '%s'", filename); + return -1; +} + + +BOOL WriteFile(const char *filename, void *buffer, int size) +{ + debug_printf("WriteFile %s\n", filename); + + (void)OpenFile(filename); + PutBuffer(buffer, size); + CloseFile(); + Free(&buffer); + return CheckResult(); +} + + +/*---------------------------------------------------------------------------* + * Time Format Utilities + * + * char* GetGMTime( const time_t time ) Show GMT + * char* GetTime( const time_t time ) Show local Time + *---------------------------------------------------------------------------*/ + +char *GetGMTime(const time_t time) +{ + static char timebuffer[32]; + strftime(timebuffer, sizeof(timebuffer), "%y/%m/%d-%H:%M:%S", gmtime(&time)); + return timebuffer; +} + + +char *GetTime(const time_t time) +{ + static char timebuffer[32]; + strftime(timebuffer, sizeof(timebuffer), "%y/%m/%d-%H:%M:%S", localtime(&time)); + return timebuffer; +} + + +/*---------------------------------------------------------------------------* + * Memory Allocation Utilities + * + * void* Alloc( size_t size ) + *---------------------------------------------------------------------------*/ + +void *Alloc(size_t size) +{ + void *t = calloc(1, size); + + if (t == NULL) + { + error("Can't allocate memory."); + exit(10); + } + return t; +} + + +void Free(void *p) +{ + void **ptr = (void **)p; + + if (*ptr) + { + free(*ptr); + (*ptr) = NULL; + } +} + + +/*---------------------------------------------------------------------------* + * VBuffer + * + * void PutVBuffer( VBuffer* vbuf, char c ) + *---------------------------------------------------------------------------*/ + +void PutVBuffer(VBuffer * vbuf, char c) +{ + int size; + char *tmp_buffer; + + if (vbuf->buffer == 0) + { + vbuf->size = VBUFFER_INITIAL_SIZE; + vbuf->buffer = Alloc(vbuf->size); // buffer is CALLOCed + } + size = strlen(vbuf->buffer); + + if (size >= vbuf->size - 1) + { + // Need buffer expansion + vbuf->size *= 2; + tmp_buffer = Alloc(vbuf->size); // buffer is CALLOCed + strcpy(tmp_buffer, vbuf->buffer); + Free(&vbuf->buffer); + vbuf->buffer = tmp_buffer; + } + vbuf->buffer[size] = c; + return; +} + +char *GetVBuffer(VBuffer * vbuf) +{ + return vbuf->buffer; +} + +void InitVBuffer(VBuffer * vbuf) +{ + vbuf->buffer = 0; + vbuf->size = 0; +} + +void FreeVBuffer(VBuffer * vbuf) +{ + Free(&vbuf->buffer); +} + + +/*---------------------------------------------------------------------------* + * File Path Utilities + * + * char* ChangeBackSlash( char* path ) + *---------------------------------------------------------------------------*/ + +char *ChangeBackSlash(char *path) +{ + char *p = path; + + while (*p) + { + if (*p == '\\') + { + *p = '/'; + } + p++; + } + return path; +} + + +/*---------------------------------------------------------------------------* + * Math + * + * u16 CalcCRC16( u16 start, u8 *data, int size ) + *---------------------------------------------------------------------------*/ + +static u16 crc16_table[16] = { + 0x0000, 0xCC01, 0xD801, 0x1400, + 0xF001, 0x3C00, 0x2800, 0xE401, + 0xA001, 0x6C00, 0x7800, 0xB401, + 0x5000, 0x9C01, 0x8801, 0x4400 +}; + +u16 CalcCRC16(u16 start, u8 *data, int size) +{ + u16 r1; + u16 total = start; + + while (size-- > 0) + { + // 4bit + r1 = crc16_table[total & 0xf]; + total = (total >> 4) & 0x0fff; + total = total ^ r1 ^ crc16_table[*data & 0xf]; + + // 4bit + r1 = crc16_table[total & 0xf]; + total = (total >> 4) & 0x0fff; + total = total ^ r1 ^ crc16_table[(*data >> 4) & 0xf]; + + data++; + } + return total; +} + + +/*---------------------------------------------------------------------------* + * for firm header + * + *---------------------------------------------------------------------------*/ + +static u8 ConvertAlign( u32 ofs ) +{ + u8 i; + + ofs /= 4; + for (i=0; i<7; i++) + { + if ( ofs & 1 ) + { + break; + } + ofs >>= 1; + } + + return i; +} + +tROMAddrConvType ConvertHeaderRamAddr( s32 p ) +{ + tROMAddrConvType retval; + + retval.align = ConvertAlign( p ); + retval.address = (u16)((p - HW_WRAM)/(4< + +typedef enum +{ + FALSE = 0, + TRUE = 1 +} +BOOL; + +typedef unsigned char u8; +typedef unsigned short int u16; +typedef unsigned long int u32; +typedef unsigned long long u64; +typedef signed char s8; +typedef signed short int s16; +typedef signed long int s32; +typedef signed long long s64; +typedef volatile u8 vu8; +typedef volatile u32 vu32; +typedef vu32 REGType32v; + +#define error(...) do { fprintf(stderr, "Error: "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); } while(0) + +#define warning(...) do { fprintf(stderr, "Warning: "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); } while(0) + +BOOL OpenFile(const char *filename); +BOOL CloseFile(void); +void SeekFile(long pos); +BOOL CheckResult(void); +void DeleteOutFile(void); +void PutBuffer(const void *ptr, int len); +void GetBuffer(void *ptr, int len); +void PutByte(u8 c); +void PutHalf(u16 c); +void PutWord(u32 c); +void PutString(const char *str); +void PrintString(const char *fmt, ...); + +#define READ_ALL 0 +int ReadFile(const char *filename, void *filebuffer, int size); +int ReadFileWithPadding(const char *filename, void *filebuffer, int size, int boundary); +BOOL WriteFile(const char *filename, void *buffer, int size); + +char *GetGMTime(const time_t time); +char *GetTime(const time_t time); + +void *Alloc(size_t size); +void Free(void *p); + +typedef struct +{ + char *buffer; + int size; +} +VBuffer; + +#define VBUFFER_INITIAL_SIZE 1024 +void InitVBuffer(VBuffer * vbuf); +void FreeVBuffer(VBuffer * vbuf); +void PutVBuffer(VBuffer * vbuf, char c); +char *GetVBuffer(VBuffer * vbuf); + +char *ChangeBackSlash(char *path); + +u16 CalcCRC16(u16 start, u8 *data, int size); +const char *WrapNull(const char *str); + +typedef struct +{ + u16 address; + u8 align; +} +tROMAddrConvType; + +tROMAddrConvType ConvertHeaderRamAddr( s32 p ); +tROMAddrConvType ConvertHeaderRomOffset( s32 p ); +u16 ConvertHeaderRomOffsetAlign( s32 p, u32 align ); + +typedef union +{ + struct + { + u32 sign:1; + u32 header_hash:1; + u32 arm9_hash:1; + u32 arm7_hash:1; + u32 hash_table_hash:1; + u32 final_hash:1; + u32 header_footer:1; + } + e; + u32 raw; +} +tErrorFlags; + +extern BOOL DebugMode; +extern BOOL PrintMode; +extern char *PubkeyFileName; +void debug_printf(const char *str, ...); +void debug_printf2(const char *str, ...); + +#endif //MISC_H_ diff --git a/build/tools/makegcdfirm/out_gcdfirm.c b/build/tools/makegcdfirm/out_gcdfirm.c new file mode 100644 index 0000000..44ee62a --- /dev/null +++ b/build/tools/makegcdfirm/out_gcdfirm.c @@ -0,0 +1,994 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: out_gcdfirm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // atoi() +#include // strcmp() +#include // isprint() +#include // chdir() +#include +#include // UCHAR_MAX +#include +#include // stat() +#include "elf.h" +#include "misc.h" +#include "defval.h" +#include "format_rom.h" +#include "format_nlist.h" +#include "makegcdfirm.h" +#include "format_sign.h" +#include "acsign_gcd.h" +#include "compress.h" + +#define SDK_ASM + +#include +#include "../acsign/aes2.h" + +#define ROMHDRCMD "ROM_HDR" +#define SBIN9CMD "ARM9_SBIN" +#define SBIN7CMD "ARM7_SBIN" +#define ELF9CMD "ARM9_ELF" +#define ELF7CMD "ARM7_ELF" +#define GAMECODECMD "GAMECODE" +#define ARM9X2CMD "ARM9_X2" +#define NMLOFSCMD "NML_OFS" +#define TWLOFSCMD "TWL_OFS" +#define VERCMD "VERSION" +#define RSAKEYCMD "RSA_KEY" +#define OUTKEYCMD "OUT_KEY" +#define WREGCMD "WRAM_RBIN" +#define NANDFMCMD "NANDFIRM" +#define NORFMCMD "NORFIRM" +#define ERRCMD "ERROR" + +static BOOL ConstructGcdfirmFile(char * specFile); +static BOOL ReadRomHeaderFile(const char *fileName); +static BOOL ReadSbinFile(const char *fileName, void* minfo, void* hash, BOOL comp); +static size_t ReadFirmFile(const char *fileName); +static BOOL ReadKeyFile(const char *fileName); +static BOOL ReadWramRegFile(const char *fileName); +static s32 GetRamAddr(const char *fileName); + +static BOOL EncryptBuffer(char *buffer, int length); + +static BOOL RomHeader_Command(char * line, int num); +static BOOL Sbin9_Command(char * line, int num); +static BOOL Sbin7_Command(char * line, int num); +static BOOL Elf9_Command(char * line, int num); +static BOOL Elf7_Command(char * line, int num); +static BOOL GAMECODE_Command(char * line, int num); +static BOOL ARM9X2_Command(char * line, int num); +static BOOL NMLOFS_Command(char * line, int num); +static BOOL TWLOFS_Command(char * line, int num); +static BOOL VERSION_Command(char * line, int num); +static BOOL RSAKEY_Command(char * line, int num); +static BOOL OUTKEY_Command(char * line, int num); +static BOOL WramRegs_Command(char * line, int num); +static BOOL NorFirm_Command(char * line, int num); +static BOOL NandFirm_Command(char * line, int num); +static BOOL ERROR_Command(char * line, int num); + +static BOOL InitializeAesKey(void); +static BOOL InitializeGcdfirmFile(void); +static BOOL FinalizeGcdfirmFile(const char *gcdFile); + +static s32 Offset; // Current offset +static int LineNum; // Line number for error message +static const char *specFileName; // specFile name for error message + +GCDHeader gcdHeader; // Gcdfirm Header Shadow +FIRMSignedContext signedContext; +u8 *keyFileBuf; +BOOL compArm9 = FALSE; +BOOL compArm7 = FALSE; +tErrorFlags errFlags; + +//--------------------------------------------------------------------------- +// Output - gcdfirm File +//--------------------------------------------------------------------------- + +BOOL OutputGcdfirmFile(const char *specFile, const char *gcdFile) +{ + char *buffer; + BOOL state; + + if (ReadFile(specFile, &buffer, READ_ALL) <= 0) + { + return FALSE; + } + + if (!OpenFile(gcdFile)) + { + return FALSE; + } + + specFileName = specFile; + + state = InitializeGcdfirmFile() && ConstructGcdfirmFile(buffer) && + FinalizeGcdfirmFile(gcdFile) && CloseFile(); + + if (!state) + { + DeleteOutFile(); + } + + return state; +} + + +//--------------------------------------------------------------------------- +// Output - Gcdfirm File +//--------------------------------------------------------------------------- + +static const tCommandDesc command[] = { + {ROMHDRCMD, RomHeader_Command}, + {SBIN9CMD, Sbin9_Command}, {SBIN7CMD, Sbin7_Command}, + {ELF9CMD, Elf9_Command},{ELF7CMD, Elf7_Command}, + {VERCMD, VERSION_Command}, + {GAMECODECMD, GAMECODE_Command}, + {ARM9X2CMD, ARM9X2_Command}, + {NMLOFSCMD, NMLOFS_Command}, + {TWLOFSCMD, TWLOFS_Command}, + {RSAKEYCMD, RSAKEY_Command}, + {OUTKEYCMD, OUTKEY_Command}, + {WREGCMD, WramRegs_Command}, + {NANDFMCMD, NandFirm_Command}, + {NORFMCMD, NorFirm_Command}, + {ERRCMD, ERROR_Command}, +}; + +BOOL ConstructGcdfirmFile(char * specFile) +{ + char *line; + char *line_top; + char *p; + int i; + + LineNum = 0; + Offset = 0x4000; + SeekFile(Offset); + + line = specFile++; + + while (*line != '\0') + { + LineNum++; + + // Get command line + line_top = line; + while (*line != '\0') + { + if (*line++ == '\n') + { + break; + } + } + + // Print for debug + debug_printf("GCDSF Line%4d [", LineNum, line); + for (p = line_top; p != line; p++) + { + if (isprint(*p)) + { + debug_printf("%c", *p); + } + } + debug_printf("]\n"); + + if (*line_top == '#') + { + } + else + { + for (i = 0; i < (sizeof(command) / sizeof(command[0])); i++) + { + if (!strncmp(line_top, command[i].string, strlen(command[i].string))) + { + if (command[i].funcp != NULL) + { + char line_cmd[FILENAME_MAX]; + char line_scan[FILENAME_MAX]; + char* line_conv; + int num; + + num = sscanf( line_top, + "%1024[^ :] : %1024[^ \x0d:#\n]", + line_cmd, line_scan + ); + line_conv = ResolveDefVal(line_scan); + + debug_printf("line_cmd = %s, line_conv = %s\n", line_cmd, line_conv); + + if (!command[i].funcp(line_conv, num - 1)) + return FALSE; + } + } + } + } + + } + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - 'RomHeader' Command +//--------------------------------------------------------------------------- + +static BOOL RomHeader_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("hom header file = %s\n", line); + + return ReadRomHeaderFile(line); +} + + +static BOOL ReadRomHeaderFile(const char *fileName) +{ + char *file; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &file, READ_ALL)) < 0) + return FALSE; + + gcdHeader = *(GCDHeader*)file; + + // Output file image with fitting region + SeekFile(0L); + PutBuffer(file, file_size); + + Free(&file); + + return CheckResult(); +} + +//--------------------------------------------------------------------------- +// Output - 'WramRegs' Command +//--------------------------------------------------------------------------- + +extern MIHeader_WramRegs wram_regs_init; +MIHeader_WramRegs* wram_regs; + +static BOOL WramRegs_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("wram regs file = %s\n", line); + + return ReadWramRegFile(line); +} + +static BOOL ReadWramRegFile(const char *fileName) +{ + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &wram_regs, READ_ALL)) < 0) + return FALSE; + + gcdHeader.h.w = *wram_regs; + + return CheckResult(); +} + +//--------------------------------------------------------------------------- +// Output - 'RSAKEY' Command +//--------------------------------------------------------------------------- + +static BOOL RSAKEY_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("rsa key = %s\n", line); + + return ReadKeyFile(line); +} + +static BOOL ReadKeyFile(const char *fileName) +{ + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &keyFileBuf, READ_ALL)) < 0) + return FALSE; + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'OUTKEY' Command +//--------------------------------------------------------------------------- + +static BOOL OUTKEY_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("out key = %s\n", line); + + PubkeyFileName = line; + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'VERSION' Command +//--------------------------------------------------------------------------- + +static u8 ConvToBCD8(int x) +{ + u8 bcd = 0; + + x %= 100; + bcd |= (x / 10)<<4; + bcd |= (x % 10); + + return bcd; +} + +static BOOL VERSION_Command(char * line, int num) +{ + char scan[FILENAME_MAX]; + u64 version = -1; + + // rescan + num = sscanf( line, + "0x%1024[^\x0d\n]", + scan + ); + + if (num == 1) + { + // convert version info + version = strtoull(scan, NULL, 16); + } + else if (num == 0) + { + // generate version info + u8* ver8 = (u8*)&version; + time_t timer; + struct tm *t_st; + + time(&timer); + t_st = localtime(&timer); + + ver8[0] = ConvToBCD8(t_st->tm_min); + ver8[1] = ConvToBCD8(t_st->tm_hour); + ver8[2] = ConvToBCD8(t_st->tm_mday); + ver8[3] = ConvToBCD8(t_st->tm_mon+1); + ver8[4] = ConvToBCD8(t_st->tm_year); + ver8[5] = 0xff; + ver8[6] = 0xff; + ver8[7] = 0xff; + } + + debug_printf2("version = %08llx\n", version); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'NMLOFS' Command +//--------------------------------------------------------------------------- + +static BOOL NMLOFS_Command(char * line, int num) +{ + u32 offset = 0; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + offset = strtoul(line, NULL, 0); + + gcdHeader.l.normal_area_offset = offset / NML_AREA_ALIGN; + + debug_printf2("normal area offset = %#x\n", offset); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'TWLOFS' Command +//--------------------------------------------------------------------------- + +static BOOL TWLOFS_Command(char * line, int num) +{ + u32 offset = 0; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + offset = strtoul(line, NULL, 0); + + gcdHeader.l.twl_area_offset = offset / TWL_AREA_ALIGN; + + debug_printf2("twl area offset = %#x\n", offset); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'ARM9_X2' Command +//--------------------------------------------------------------------------- + +static BOOL ARM9X2_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "TRUE")) + { + gcdHeader.l.arm9_x2 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm9 x2 = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'GAMECODE' Command +//--------------------------------------------------------------------------- + +static BOOL GAMECODE_Command(char * line, int num) +{ + u32 key; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + key = strtoul(line, NULL, 0); + + debug_printf2("keyinfo = %#x\n", key); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Elf9' Command +//--------------------------------------------------------------------------- + +static BOOL Elf9_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm9 elf = %s\n", line); + + { + s32 ramAddr = GetRamAddr(line); + gcdHeader.l.main_ram_address = (void*)ramAddr; + } + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Elf7' Command +//--------------------------------------------------------------------------- + +static BOOL Elf7_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm7 elf = %s\n", line); + + { + s32 ramAddr = GetRamAddr(line); + gcdHeader.l.sub_ram_address = (void*)ramAddr; + } + + return CheckResult(); +} + + +static s32 GetRamAddr(const char *fileName) +{ + Elf32_Ehdr *ehdr; + s32 ramAddr; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &ehdr, sizeof(Elf32_Ehdr))) < 0) + return FALSE; + + ramAddr = ehdr->e_entry; + + Free(&ehdr); + + debug_printf2("ramaddr = 0x%08x\n", ramAddr); + + return ramAddr; +} + + +//--------------------------------------------------------------------------- +// Output - 'NANDFIRM' Command +//--------------------------------------------------------------------------- + +static BOOL NandFirm_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("nandfirm = %s\n", line); + + // Set NANDFIRM ROM Offset + if (!Offset) + { + Offset = sizeof(GCDHeader); + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + gcdHeader.l.nandfirm_offset = Offset; + gcdHeader.l.nandfirm_size = ReadFirmFile(line); + } + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'NORFIRM' Command +//--------------------------------------------------------------------------- + +static BOOL NorFirm_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("norfirm = %s\n", line); + + // Set NORFIRM ROM Offset + if (!Offset) + { + Offset = sizeof(GCDHeader); + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + gcdHeader.l.norfirm_offset = Offset; + gcdHeader.l.norfirm_size = ReadFirmFile(line); + } + + return CheckResult(); +} + + +static size_t ReadFirmFile(const char *fileName) +{ + char *file; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFileWithPadding(fileName, &file, READ_ALL, FIRM_ALIGN)) < 0) + return FALSE; + + Offset += file_size; + + // Output file image with fitting region + PutBuffer(file, file_size); + + Free(&file); + + return file_size; +} + + +//--------------------------------------------------------------------------- +// Output - 'Sbin9' Command +//--------------------------------------------------------------------------- + +static BOOL Sbin9_Command(char * line, int num) +{ + FIRMSignedContext* sc = &signedContext; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm9 sbin = %s\n", line); + + // Set ARM9 ROM Offset + if (!Offset) + + { + Offset = sizeof(GCDHeader); + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + gcdHeader.l.main_rom_offset = Offset; + } + + return ReadSbinFile(line, &gcdHeader.l.main_rom_offset, &sc->hash[FIRM_SIGNED_HASH_IDX_ARM9], compArm9); +} + +//--------------------------------------------------------------------------- +// Output - 'Sbin7' Command +//--------------------------------------------------------------------------- + +static BOOL Sbin7_Command(char * line, int num) +{ + FIRMSignedContext* sc = &signedContext; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm7 sbin = %s\n", line); + + // Set ARM7 ROM Offset + if (!Offset) + { + Offset = sizeof(GCDHeader); + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + gcdHeader.l.sub_rom_offset = Offset; + } + + return ReadSbinFile(line, &gcdHeader.l.sub_rom_offset, &sc->hash[FIRM_SIGNED_HASH_IDX_ARM7], compArm7); +} + + +static BOOL ReadSbinFile(const char *fileName, void* minfo, void* hash, BOOL comp) +{ + const GCDHeader_ModuleInfo *m = minfo; + u32 *size = (void*)&m->size; + u32 *orig_size = (void*)&m->decomp_size; + char *buffer; + char *file; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &file, READ_ALL)) < 0) + return FALSE; + + *orig_size = file_size; + + // Digest file image + if (hash) + { + ACSign_DigestUnit(hash, file, file_size); + } + + // Compress file image with fitting region + buffer = Alloc(file_size * 2); + if ( comp ) + { + file_size = LZCompWrite(file, file_size, buffer, FIRM_ALIGN); + } + else + { + memcpy(&buffer[0], file, file_size); + { + u32 pad_size = (DEFAULT_ALIGN - (file_size % FIRM_ALIGN)) % FIRM_ALIGN; + if (pad_size) + memset(&buffer[file_size], 0, pad_size); + file_size += pad_size; + } + } + Free(&file); + file = buffer; + + if (size) + { + *size = file_size; + } + Offset += file_size; + + // Encrypt file image + EncryptBuffer(file, file_size); + + // Output file image with fitting region + PutBuffer(file, file_size); + + Free(&file); + + return CheckResult(); +} + +typedef struct +{ + unsigned long e[4]; +} u128; + +static BOOL EncryptBuffer(char *buffer, int length) +{ + const u128 id = {{ AES_IDS_ID2_A, AES_IDS_ID2_B, AES_IDS_ID2_C, AES_IDS_ID2_D }}; + u128 iv = {{ length, -length, ~length, 0 }}; + FIRMSignedContext* sc = &signedContext; + char *buffer2 = Alloc(length); + AES_KEY key; + if (!buffer2) + return FALSE; + AES_SetKey(&key, sc->aes_key, (unsigned char*)&id); + AES_Ctr(&key, buffer2, buffer, length, (unsigned char*)&iv); + memcpy(buffer, buffer2, length); + memset(buffer2, 0, length); + Free(buffer2); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - 'ERROR' Command +//--------------------------------------------------------------------------- +static char* error_type[] = +{ + "SIGN", + "HEADER_HASH", + "ARM9_HASH", + "ARM7_HASH", + "HASH_TABLE_HASH", + "FINAL_HASH", + "HEADER_FOOTER", +}; + +static BOOL ERROR_Command(char * line, int num) +{ + char* dbg_str = "UNKNOWN"; + int i; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + for (i=0; ihash[FIRM_SIGNED_HASH_IDX_HEADER][0] ^= 1; + } + if ( errFlags.e.arm9_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_ARM9][0] ^= 1; + } + if ( errFlags.e.arm7_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_ARM7][0] ^= 1; + } + if ( errFlags.e.hash_table_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_HASH_TABLE][0] ^= 1; + } +} + +static void SetFinalHashError(FIRMSignedContext* sc) +{ + if ( errFlags.e.final_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_FINAL][0] ^= 1; + } +} + +static void SetSignError(GCDHeader* nh) +{ + if ( errFlags.e.sign ) + { + nh->sign.raw[0] ^= 1; + } + +} + +static void SetFooterError(GCDHeader* nh) +{ + if ( errFlags.e.header_footer ) + { + nh->h.reserved_footer[sizeof(nh->h.reserved_footer)-1] ^= 1; + } + +} + +//--------------------------------------------------------------------------- +// Output - Initialize AES Key +//--------------------------------------------------------------------------- +static BOOL InitializeAesKey(void) +{ + FIRMSignedContext* sc = &signedContext; + struct stat specstat; + time_t spectime; + if (stat(specFileName, &specstat) != 0) + return FALSE; + time(&spectime); + memcpy(&sc->aes_key[0], &specstat.st_atime, 4); + memcpy(&sc->aes_key[4], &specstat.st_mtime, 4); + memcpy(&sc->aes_key[8], &specstat.st_ctime, 4); + memcpy(&sc->aes_key[12], &spectime, 4); + ACSign_GetKey(sc->aes_key, sizeof(sc->aes_key), sc->aes_key, sizeof(sc->aes_key)); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - Initialize Gcdfirm File +//--------------------------------------------------------------------------- + +static BOOL InitializeGcdfirmFile(void) +{ + ReadRomHeaderFile( GetSrcPath(GetAppBaseName(), DEFAULT_ROMHEADER_TEMPLATE) ); + + memset(&signedContext.hash[FIRM_SIGNED_HASH_IDX_HASH_TABLE], 0xff, sizeof(signedContext.hash[0])); + gcdHeader.h.w = wram_regs_init; + InitializeAesKey(); + return TRUE; +} + +//--------------------------------------------------------------------------- +// Output - Finalize Gcdfirm File +//--------------------------------------------------------------------------- + +static BOOL FinalizeGcdfirmFile(const char *gcdFile) +{ + GCDHeader* nh = &gcdHeader; + FIRMSignedContext* sc = &signedContext; + u8* key = keyFileBuf; + int size; + + // set rom size + size = ROM_SIZE_MIN; + nh->l.rom_size = 0; + while (size < Offset) + { + size <<= 1; + nh->l.rom_size++; + } + + ACSign_DigestHeader(&sc->hash[FIRM_SIGNED_HASH_IDX_HEADER], nh); + + SetUnitHashErrors(sc); + + ACSign_DigestUnit(&sc->hash[FIRM_SIGNED_HASH_IDX_FINAL], sc, FIRM_HEADER_2ND_HASH_AREA_LEN); + + SetFinalHashError(sc); + + if (key) + { + ACSign_Final(nh, sc, key); + } + + SetFooterError(nh); + + SetSignError(nh); + + // Output file image + SeekFile(0L); + PutBuffer(&gcdHeader, sizeof(gcdHeader)); + + // Output public key (modulus) + if (PubkeyFileName) + { + WriteFile(PubkeyFileName, &keyFileBuf[ACS_RSA_PRVMOD_OFFSET], ACS_RSA_PRVMOD_LEN); + } + + return TRUE; +} diff --git a/build/tools/makegcdfirm/path.c b/build/tools/makegcdfirm/path.c new file mode 100644 index 0000000..eeeb989 --- /dev/null +++ b/build/tools/makegcdfirm/path.c @@ -0,0 +1,931 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makebanner + File: path.c + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: path.c,v $ + Revision 1.3 2006/01/18 02:11:20 kitase_hirotake + do-indent + + Revision 1.2 2005/02/28 05:26:13 yosizaki + do-indent. + + Revision 1.1 2004/08/30 08:41:14 yasu + makebanner moves into CVS tree + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include // free() +#include // strcasecmp() +#include // stat() +#include // opendir()/readdir()/closedir() +#include // getcwd() +#ifdef __CYGWIN__ +#include // cygwin_conv_to_win32_path() +#endif +#include "path.h" + +//--------------------------------------------------------------------------- +// Get File Statue +//--------------------------------------------------------------------------- + +tFileStatus GetFileStatus(struct stat *s, const char *filename) +{ + // Get file status + if (stat(filename, s)) + { + error("Can't get status %s", filename); + return FILESTATUS_ERROR; + } + + if (S_ISREG(s->st_mode)) + { + return FILESTATUS_FILE; + } + else if (S_ISDIR(s->st_mode)) + { + return FILESTATUS_DIR; + } + + error("Unknown file type %s", filename); + return FILESTATUS_ERROR; +} + + +//--------------------------------------------------------------------------- +// File Globbing & Dir Listing +//--------------------------------------------------------------------------- + +typedef struct +{ + tCallBack callBack; + void *param; + tWildCard *accept; + tWildCard *reject; + +} +tForeachEntryParam; + + +static BOOL isAcceptEntryName(char *pathName, tWildCard * accept, tWildCard * reject) +{ + char *p = pathName; + + while (*p) + { + if (*p == '/') + pathName = p + 1; + p++; + } + + if (accept) + { + while (accept) + { + if (WildCardCmp(accept->name, pathName)) + { + goto accepted; + } + accept = accept->next; + } + return FALSE; + } + accepted: + + while (reject) + { + if (WildCardCmp(reject->name, pathName)) + { + return FALSE; + } + reject = reject->next; + } + return TRUE; +} + + +static BOOL ForeachEntry_CallBack(char *pathName, void *param) +{ + tForeachEntryParam *t = (tForeachEntryParam *) param; + struct stat fstat; + + if (!isAcceptEntryName(pathName, t->accept, t->reject)) + { + // Reject!!! ignored + return TRUE; + } + + switch (GetFileStatus(&fstat, pathName)) + { + case FILESTATUS_FILE: + return t->callBack(pathName, t->param); + + case FILESTATUS_DIR: + return ForeachDirList(pathName, ForeachEntry_CallBack, param); + + default: + break; + } + return FALSE; +} + + +BOOL ForeachEntry(const char *pathName, tWildCard * reject, tCallBack callBack, void *param) +{ + tForeachEntryParam t; + + t.callBack = callBack; + t.param = param; + t.accept = NULL; + t.reject = reject; + + return ForeachPathGlobbing(pathName, ForeachEntry_CallBack, &t); +} + + +typedef struct +{ + tCallBack callBack; + void *param; + char *baseName; + +} +tForeachFileParam; + + +static BOOL ForeachFile_CallBack(char *pathName, void *param) +{ + tForeachFileParam *t = (tForeachFileParam *) param; + + int len = strlen(t->baseName); + + debug_printf(" ForeachFile_CallBack path[%s] base[%s]\n", pathName, t->baseName); + + if (strncmp(pathName, t->baseName, len)) + { + error("Wildcard in Root is not supported"); + return FALSE; + } + + return t->callBack(pathName + len, t->param); +} + + +BOOL ForeachFile(const char *baseName, const char *fileName, tWildCard * reject, tCallBack callBack, + void *param) +{ + char *cBaseName; + char *cPathName; + BOOL state; + tForeachFileParam t; + + debug_printf("ForeachFile : baseName[%s] fileName[%s]\n", baseName, fileName); + + cBaseName = GetSrcPath(baseName, ""); + cPathName = GetSrcPath(baseName, fileName); + + debug_printf("ForeachFile : cBaseName[%s] cPathName[%s]\n", cBaseName, cPathName); + + t.callBack = callBack; + t.param = param; + t.baseName = cBaseName; + + state = ForeachEntry(cPathName, reject, ForeachFile_CallBack, &t); + + free(cBaseName); + free(cPathName); + + return state; +} + + +//--------------------------------------------------------------------------- +// FilePath Globbing +//--------------------------------------------------------------------------- + +typedef struct +{ + char *baseName; + char *pathName; + tCallBack callBack; + void *param; + +} +tGlobParam; + + +static int CountFile; +static BOOL ForeachPathGlobbing_Entry(tGlobParam * pg); +static BOOL ForeachPathGlobbing_WildCard(char *pathName, void *param); + +BOOL ForeachPathGlobbing(const char *pathName, tCallBack callBack, void *param) +{ + tGlobParam g; + BOOL ret; + + g.baseName = NULL; + g.pathName = PathNormalize(pathName, TRUE); + g.callBack = callBack; + g.param = param; + CountFile = 0; + + debug_printf("PathGlobbing : Name [%s]->[%s]\n", pathName, g.pathName); + + ret = ForeachPathGlobbing_Entry(&g); + + free(g.pathName); + + if (ret && CountFile == 0) + { + error("No file or directory matched %s", pathName); + return FALSE; + } + return ret; +} + + +static BOOL ForeachPathGlobbing_Entry(tGlobParam * pg) +{ + tGlobParam g; + char *entryName; + struct stat s; + BOOL state; + + if (pg->pathName) + { + entryName = PathDup(pg->pathName); + + g = *pg; + g.pathName = PathGetDirLevelDown(pg->pathName); + + if (pg->baseName) + { + g.baseName = Alloc(strlen(pg->baseName) + strlen(entryName) + 2); + sprintf(g.baseName, "%s/%s", pg->baseName, entryName); + } + else + { + g.baseName = strdup(entryName); + } + + // Check if wildcard ? + if (isPathWildCard(entryName)) + { + state = ForeachDirList(pg->baseName, ForeachPathGlobbing_WildCard, &g); + } + else + { + state = ForeachPathGlobbing_Entry(&g); + } + + Free(&entryName); + Free(&g.baseName); + } + else + { + // Check if file exists + if (!stat(pg->baseName, &s)) + { + debug_printf(" File Found [%s]\n", pg->baseName); + + // Globbing done, exec callback + + state = pg->callBack(pg->baseName, pg->param); + CountFile++; + } + else + { + debug_printf(" File Not Found [%s]\n", pg->baseName); + state = TRUE; // Ignored + } + } + return state; +} + + +static BOOL ForeachPathGlobbing_WildCard(char *pathName, void *param) +{ + tGlobParam g; + tGlobParam *pg = (tGlobParam *) param; + + debug_printf(" WildCardCmp: [%s] [%s]\n", pg->baseName, pathName); + + if (WildCardCmp(pg->baseName, pathName)) + { + g = *pg; + g.baseName = pathName; + return ForeachPathGlobbing_Entry(&g); + } + + return TRUE; // Ignored +} + + +//--------------------------------------------------------------------------- +// Directory Listing +// Listing directory & Exec CallBack +//--------------------------------------------------------------------------- + +BOOL ForeachDirList(const char *dirName, tCallBack callBack, void *param) +{ + DIR *dir; + struct dirent *entry; + char *pathName; + BOOL state = TRUE; + + if (!dirName) + { + dirName = "."; + } + + debug_printf("DirectoryList: Name [%s]\n", dirName); + + // Open directory + if (NULL == (dir = opendir(dirName))) + { + error("Can't read directory %s", dirName); + return FALSE; + } + + // Store new files + while (NULL != (entry = readdir(dir))) + { + pathName = entry->d_name; + + if (!strcmp(pathName, ".") || !strcmp(pathName, "..")) + { + continue; + } + + debug_printf(" :%s\n", pathName); + pathName = GetSrcPath(dirName, pathName); + state = callBack(pathName, param); + free(pathName); + + if (!state) + break; + } + + closedir(dir); + return state; +} + + +//--------------------------------------------------------------------------- +// +// PathName Utilities +// +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// StrCmp/StrCpy entry name terminated / or \0 +//--------------------------------------------------------------------------- + +int PathCmp(const char *path, const char *cmp) +{ + char c; + + do + { + c = *path; + if (c == '/') + c = '\0'; // end of string if '/' + if (c != *cmp) + return 1; + path++; + cmp++; + } + while (c); + + return 0; +} + + +char *PathCpy(char *dest, const char *src) +{ + while (*src != '\0' && *src != '/') + { + *dest++ = *src++; + } + return dest; // Don't set '\0' +} + + +int PathLen(const char *path) +{ + int n = 0; + + while (*path != '\0' && *path != '/') + { + n++; + path++; + } + return n; +} + + +char *PathDup(const char *src) +{ + int n = PathLen(src); + char *dest = Alloc(n + 2); + + PathCpy(dest, src); + dest[n] = '\0'; + + return dest; +} + + +BOOL WildCardCmp(const char *wildcard, const char *path) +{ + if (*wildcard == '*') + { + if (*path != '\0' && WildCardCmp(wildcard, path + 1)) + return TRUE; + if (WildCardCmp(wildcard + 1, path)) + return TRUE; + } + + else if (*wildcard == '?') + { + return *path != '\0' && WildCardCmp(wildcard + 1, path + 1); + } + + else if (*wildcard == *path) + { + return *path == '\0' || WildCardCmp(wildcard + 1, path + 1); + } + + return FALSE; +} + + +BOOL isPathWildCard(const char *path) +{ + while (*path != '\0' && *path != '/') + { + if (*path == '*' || *path == '?') + { + return TRUE; + } + path++; + } + return FALSE; +} + + +//--------------------------------------------------------------------------- +// Go up/down directory level +//--------------------------------------------------------------------------- + +char *PathGetDirLevelDown(const char *path) +{ + while (*path) + { + if (*path == '/') + return (char *)path + 1; + path++; + } + return NULL; +} + + +//--------------------------------------------------------------------------- +// Get Basename +//--------------------------------------------------------------------------- + +char *GetBaseName(const char *path) +{ + int i; + char *new_path; + + for (i = strlen(path) - 1; i >= 0; i--) + { + if (path[i] == '/') + { + new_path = strdup(path); + new_path[i] = '\0'; + return new_path; + } + if (path[i] == ':') + { + new_path = Alloc(i + 3); + strncpy(new_path, path, i); + strcpy(new_path + i, ":."); + return new_path; + } + } + + new_path = strdup("."); + return new_path; +} + + +//--------------------------------------------------------------------------- +// Get Filename +//--------------------------------------------------------------------------- + +char *GetFileName(const char *path) +{ + int i; + char *new_file; + + for (i = strlen(path) - 1; i >= 0; i--) + { + if (path[i] == '/' || path[i] == ':') + { + new_file = strdup(path + i + 1); + return new_file; + } + } + new_file = strdup(path); + return new_file; +} + + +//--------------------------------------------------------------------------- +// Reconstruct path name +// +// - Resolve '.' or '..' in path name +// - Work around . and / to translate regular form +// +// Regular form of path: +// Absolute Path [Drive:]/.[/Entry...] +// Relative Path [Drive:].[/Entry]... +// +// ex) +// abc/def -> ./abc/def +// /aaa -> /./aaa +// D:/aaa -> D:/./aaa +// / -> /. +// . -> . +// ../aa -> ./../aa +//--------------------------------------------------------------------------- + +char *PathNormalize(const char *pathName, BOOL isTreatDotDot) +{ + int i, level, level_root, n; + BOOL isAbsolute; + const char *entry[DIRLEVEL_MAX]; + + char *pathNormal = Alloc(strlen(pathName) + 4); + const char *p_org; + char *p_new; + + // + // Check if drive letter C: D: E: + // Check if absolute path + // + p_new = pathNormal; + p_org = SkipDriveName(pathName); + n = (int)p_org - (int)pathName; + + if (n > 0) + { + strncpy(p_new, pathName, n); + p_new += n; + } + isAbsolute = isAbsolutePath(p_org); + + // + // Resolve '.' and '..' + // + // Slice the path at point of / , put them into entry[] + // + + level = level_root = 0; + + for (; p_org; p_org = PathGetDirLevelDown(p_org)) + { + if (!PathCmp(p_org, "") || !PathCmp(p_org, ".")) + { + // skip it + continue; + } + else if (!PathCmp(p_org, "..") && isTreatDotDot) + { + if (level > level_root) + { + // Back to parent dir + level--; + continue; + } + + // if pathname starts with '/', no directory to go up + if (isAbsolute) + { + error("Can't go up directory, '..' Ignored. %s", pathName); + continue; + } + + // keep '..' + level_root = level + 1; + } + + // name entry + entry[level] = p_org; + level++; + } + + // Reconstruct pathname + if (isAbsolute) + { + *p_new++ = '/'; + } + *p_new++ = '.'; + + for (i = 0; i < level; i++) + { + *p_new++ = '/'; + p_new = PathCpy(p_new, entry[i]); + } + *p_new = '\0'; + +#if 0 + if (strcmp(pathNormal, pathName)) + { + debug_printf(" PathNormal: [%s] -> [%s]\n", pathName, pathNormal); + } +#endif + return pathNormal; +} + + +//--------------------------------------------------------------------------- +// Get Src Path +// Normalize BASENAME +// Normalize FILENAME +// Concat both +//--------------------------------------------------------------------------- + +char *GetSrcPath(const char *baseName, const char *fileName) +{ + char *base; + char *file; + char *t; + char *path; + + base = PathNormalize(baseName, TRUE); + file = PathNormalize(fileName, TRUE); + t = Alloc(strlen(base) + strlen(file) + 2); + + // Concat base + '/' + file + sprintf(t, "%s/%s", base, file); + path = PathNormalize(t, FALSE); + + free(base); + free(file); + free(t); + + debug_printf(" GetSrcPath: [%s]\n", path); + return path; +} + + +//--------------------------------------------------------------------------- +// Get Dest Path +// Concat BASENAME + FILENAME +// Normalize it +//--------------------------------------------------------------------------- + +char *GetDestPath(const char *baseName, const char *fileName) +{ + char *t; + char *path; + + t = Alloc(strlen(baseName) + strlen(fileName) + 2); + + // Concat base + '/' + file + sprintf(t, "%s/%s", baseName, fileName); + path = PathNormalize(t, TRUE); + + free(t); + + debug_printf(" GetDestPath: [%s]\n", path); + return path; +} + + +//--------------------------------------------------------------------------- +// Remake the path into familier shape +// Delete ./ +//--------------------------------------------------------------------------- + +char *PathDenormalize(char *path) +{ + char *p; + + p = (char *)SkipDriveName(path); + if (*p == '/') + { + p++; + } + + // Cut './' + if (*p == '.' && *(p + 1) == '/') + { + while ('\0' != (*p = *(p + 2))) + { + p++; + } + + if (p == path) + { + + } + } + + + + return path; +} + + +//--------------------------------------------------------------------------- +// Get PC Path +//--------------------------------------------------------------------------- + +char *GetWin32Path(char *cygpath) +{ + static char buffer[FILENAME_MAX]; + +#ifdef __CYGWIN__ + if (*cygpath == '/') + { + cygwin_conv_to_win32_path(cygpath, buffer); + } + else +#endif + { + strcpy(buffer, cygpath); + } + + return ChangeBackSlash(buffer); +} + +char *ChangeWin32Path(char *cygpath) +{ + char *win32path = strdup(GetWin32Path(cygpath)); + + free(cygpath); + return win32path; +} + +//--------------------------------------------------------------------------- +// Change suffix +//--------------------------------------------------------------------------- +char *ChangeSuffix(const char *file, const char *suffix) +{ + int i, n; + char *path; + + n = strlen(file); + + for (i = n; file[i] != '.'; i--) + { + if (file[i] == '/' || i == 0) + { + i = n; + break; + } + } + + path = Alloc(i + strlen(suffix) + 1); + strncpy(path, file, i); + strcpy(path + i, suffix); + + return path; +} + + +//--------------------------------------------------------------------------- +// Get Current Dir +//--------------------------------------------------------------------------- + +char *GetCurrentDirectory(void) +{ + static char buffer[FILENAME_MAX]; + char *cwd; + + cwd = getcwd(buffer, FILENAME_MAX); + if (!cwd) + { + error("Can't access current directory"); + exit(10); + } + return cwd; +} + + +//--------------------------------------------------------------------------- +// Check if absolute path +// +// Return True in case of ... +// +// /dirA/dirB/fileC +// D:/dirA/dirB/fileC +// +// Return False in case of ... +// +// dirX/dirY/fileZ +// D:dirX/dirY/fileZ +//--------------------------------------------------------------------------- + +BOOL isAbsolutePath(const char *path) +{ + const char *p = path; + + while (*p != '\0') + { + if (*p == '/' || *p == '\\') + { + if (p == path || p[-1] == ':') + { + return TRUE; + } + } + p++; + } + return FALSE; +} + +//--------------------------------------------------------------------------- +// Check if drive name +// +// Return next character of ':' if drive name +// Return head of path if no drive name +//--------------------------------------------------------------------------- + +const char *SkipDriveName(const char *path) +{ + const char *p = path; + + while (*p != '\0' && *p != '/' && *p != '\\') + { + if (*p == ':') + { + return p + 1; + } + p++; + } + return path; +} + + +//--------------------------------------------------------------------------- +// App Name Utilities +//--------------------------------------------------------------------------- +static char *appName; +static char *appBaseName; +static char *appFileName; + +void InitAppName(const char *path) +{ + char *slash_path = ChangeBackSlash(strdup(path)); + + appBaseName = GetBaseName(slash_path); + appFileName = GetFileName(slash_path); + appName = ChangeSuffix(appFileName, ""); + + free(slash_path); +} + +char *GetAppName(void) +{ + return appName; +} + +char *GetAppBaseName(void) +{ + return appBaseName; +} + +char *GetAppFileName(void) +{ + return appFileName; +} + + +#ifdef TEST +int main(int argc, char *argv[]) +{ + int i; + char *s; + + for (i = 1; i < argc; i++) + { + s = PathNormalize(argv[i], TRUE); + printf("[%s] -> [%s]\n", argv[i], s); + free(s); + } + return 0; +} +#endif diff --git a/build/tools/makegcdfirm/path.h b/build/tools/makegcdfirm/path.h new file mode 100644 index 0000000..e9956dc --- /dev/null +++ b/build/tools/makegcdfirm/path.h @@ -0,0 +1,93 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makebanner + File: path.h + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: path.h,v $ + Revision 1.3 2006/01/18 02:11:20 kitase_hirotake + do-indent + + Revision 1.2 2005/02/28 05:26:13 yosizaki + do-indent. + + Revision 1.1 2004/08/30 08:41:14 yasu + makebanner moves into CVS tree + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef PATH_H_ +#define PATH_H_ + +#include // struct tat +#include "misc.h" + +#define DIRLEVEL_MAX 256 +#ifndef FILENAME_MAX +#define FILENAME_MAX 1024 +#endif + +typedef enum +{ + FILESTATUS_ERROR = -1, + FILESTATUS_FILE = 0, + FILESTATUS_DIR = 1 +} +tFileStatus; + + +// Item Reject Control + +typedef struct tWildCard +{ + struct tWildCard *next; + char *name; + +} +tWildCard; + + +// CallBacks + +typedef BOOL (*tCallBack) (char *, void *); + + +// Prototypes + +tFileStatus GetFileStatus(struct stat *s, const char *filename); +BOOL ForeachEntry(const char *pathName, tWildCard * reject, tCallBack callBack, void *param); +BOOL ForeachFile(const char *baseName, const char *fileName, tWildCard * reject, + tCallBack callBack, void *param); +BOOL ForeachPathGlobbing(const char *pathName, tCallBack callBack, void *param); +BOOL ForeachDirList(const char *dirName, tCallBack callBack, void *param); +int PathCmp(const char *path, const char *cmp); +char *PathCpy(char *dest, const char *src); +int PathLen(const char *path); +char *PathDup(const char *src); +char *PathGetDirLevelDown(const char *path); +char *GetBaseName(const char *path); +char *GetFileName(const char *path); +BOOL WildCardCmp(const char *wildcard, const char *path); +BOOL isPathWildCard(const char *path); +char *PathNormalize(const char *pathName, BOOL isTreatDotDot); +char *PathDenormalize(char *path); +char *GetSrcPath(const char *base, const char *file); +char *GetDestPath(const char *base, const char *file); +char *GetWin32Path(char *cygpath); +char *ChangeWin32Path(char *cygpath); +char *ChangeSuffix(const char *file, const char *suffix); +char *GetCurrentDirectory(void); +BOOL isAbsolutePath(const char *path); +const char *SkipDriveName(const char *path); +void InitAppName(const char *path); +char *GetAppName(void); +char *GetAppBaseName(void); +char *GetAppFileName(void); + +#endif //PATH_H_ diff --git a/build/tools/makegcdfirm/test/Makefile b/build/tools/makegcdfirm/test/Makefile new file mode 100644 index 0000000..1f985ca --- /dev/null +++ b/build/tools/makegcdfirm/test/Makefile @@ -0,0 +1,56 @@ +#! make -f +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makenorfirm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- + +SUBDIRS = wram_rbin \ + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +MAKEGCDFIRM = ../makegcdfirm.exe + +MAKEFIRM_ARM9 = ./twl_gcdfirm9_print.axf +MAKEFIRM_ARM7 = ./twl_gcdfirm7_print.axf +SDEPENDS_BIN += $(MAKEFIRM_ARM9) $(MAKEFIRM_ARM7) +MAKEFIRM_FLAGS += -d +MAKEFIRM_DEFS += -DFIRM_ROOT='$(FIRM_ROOT)' \ + -DMAKEFIRM_ARM9='$(basename $(MAKEFIRM_ARM9))' \ + -DMAKEFIRM_ARM7='$(basename $(MAKEFIRM_ARM7))' \ + -DMAKEFIRM_RSA_PRVKEY='$(MAKEFIRM_RSA_PRVKEY)' \ + +TARGET = test.srl + +%.srl: %.gcdsf $(MAKEGCDFIRM) + $(MAKEGCDFIRM) $(MAKEFIRM_FLAGS) $(MAKEFIRM_DEFS) $< $@ + +.PHONY: build install do-autotest clean clobber + +define ECHO_CURDIR + echo "==== $(CURDIR)"; +endef + +build: + @$(ECHO_CURDIR) + @$(MAKE) $(TARGET) + +install do-autotest: + @$(ECHO_CURDIR) + +clean clobber super-clobber: + @$(ECHO_CURDIR) + -rm -f $(TARGET) *~ + +test-utf16.bsf: icon.nbfc icon.nbfp diff --git a/build/tools/makegcdfirm/test/nandfirm_print.nand b/build/tools/makegcdfirm/test/nandfirm_print.nand new file mode 100644 index 0000000..999ce18 Binary files /dev/null and b/build/tools/makegcdfirm/test/nandfirm_print.nand differ diff --git a/build/tools/makegcdfirm/test/norfirm_print.nor b/build/tools/makegcdfirm/test/norfirm_print.nor new file mode 100644 index 0000000..2a6baec Binary files /dev/null and b/build/tools/makegcdfirm/test/norfirm_print.nor differ diff --git a/build/tools/makegcdfirm/test/rsa_private.der b/build/tools/makegcdfirm/test/rsa_private.der new file mode 100644 index 0000000..06f5f4c Binary files /dev/null and b/build/tools/makegcdfirm/test/rsa_private.der differ diff --git a/build/tools/makegcdfirm/test/test.gcdsf b/build/tools/makegcdfirm/test/test.gcdsf new file mode 100644 index 0000000..88d5067 --- /dev/null +++ b/build/tools/makegcdfirm/test/test.gcdsf @@ -0,0 +1,22 @@ +#GCDSF --- Gcdfirm Spec File + +VERSION : GENERATE + +RSA_KEY : rsa_private.der +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ./wram_rbin/wram_regs.rbin + +ARM9_SBIN : $(MAKEFIRM_ARM9).sbin +ARM9_ELF : $(MAKEFIRM_ARM9).axf + +ARM7_SBIN : $(MAKEFIRM_ARM7).sbin +ARM7_ELF : $(MAKEFIRM_ARM7).axf + +ARM9_X2 : TRUE # TRUE or FALSE + +NML_OFS : 0x80000 +TWL_OFS : 0x100000 + +ERROR : ARM7_HASH # SIGN, HEADER_HASH, ARM9_HASH, ARM7_HASH, HASH_TABLE_HASH or FINAL_HASH +ERROR : HEADER_FOOTER # for debug diff --git a/build/tools/makegcdfirm/test/twl_gcdfirm7_print.axf b/build/tools/makegcdfirm/test/twl_gcdfirm7_print.axf new file mode 100644 index 0000000..b255bd2 Binary files /dev/null and b/build/tools/makegcdfirm/test/twl_gcdfirm7_print.axf differ diff --git a/build/tools/makegcdfirm/test/twl_gcdfirm7_print.sbin b/build/tools/makegcdfirm/test/twl_gcdfirm7_print.sbin new file mode 100644 index 0000000..a4eeebc Binary files /dev/null and b/build/tools/makegcdfirm/test/twl_gcdfirm7_print.sbin differ diff --git a/build/tools/makegcdfirm/test/twl_gcdfirm9_print.axf b/build/tools/makegcdfirm/test/twl_gcdfirm9_print.axf new file mode 100644 index 0000000..3d064b3 Binary files /dev/null and b/build/tools/makegcdfirm/test/twl_gcdfirm9_print.axf differ diff --git a/build/tools/makegcdfirm/test/twl_gcdfirm9_print.sbin b/build/tools/makegcdfirm/test/twl_gcdfirm9_print.sbin new file mode 100644 index 0000000..cd305be Binary files /dev/null and b/build/tools/makegcdfirm/test/twl_gcdfirm9_print.sbin differ diff --git a/build/tools/makegcdfirm/test/wram_rbin/Makefile b/build/tools/makegcdfirm/test/wram_rbin/Makefile new file mode 100644 index 0000000..c9cd7eb --- /dev/null +++ b/build/tools/makegcdfirm/test/wram_rbin/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - gcdfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = wram_regs.rbin + +SRCS = \ + wram_regs.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_DIR = . +INSTALL_TARGETS = $(BINDIR)/$(TARGET_BIN) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/tools/makegcdfirm/test/wram_rbin/wram_regs.c b/build/tools/makegcdfirm/test/wram_rbin/wram_regs.c new file mode 100644 index 0000000..ee7d112 --- /dev/null +++ b/build/tools/makegcdfirm/test/wram_rbin/wram_regs.c @@ -0,0 +1,89 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +MIHeader_WramRegs wram_regs = +{ + // ARM9 + { + REG_WRAM_A_BNK_PACK(0, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_0KB, TRUE), + REG_WRAM_A_BNK_PACK(1, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_64KB, TRUE), + REG_WRAM_A_BNK_PACK(2, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_128KB, TRUE), + REG_WRAM_A_BNK_PACK(3, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_192KB, TRUE), + }, + { + REG_WRAM_B_BNK_PACK(0, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_0KB, TRUE), + REG_WRAM_B_BNK_PACK(1, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_32KB, TRUE), + REG_WRAM_B_BNK_PACK(2, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_64KB, TRUE), + REG_WRAM_B_BNK_PACK(3, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_96KB, TRUE), + REG_WRAM_B_BNK_PACK(4, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_128KB, TRUE), + REG_WRAM_B_BNK_PACK(5, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_160KB, TRUE), + REG_WRAM_B_BNK_PACK(6, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_192KB, TRUE), + REG_WRAM_B_BNK_PACK(7, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_224KB, TRUE), + }, + { + REG_WRAM_C_BNK_PACK(0, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_0KB, TRUE), + REG_WRAM_C_BNK_PACK(1, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_32KB, TRUE), + REG_WRAM_C_BNK_PACK(2, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_64KB, TRUE), + REG_WRAM_C_BNK_PACK(3, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_96KB, TRUE), + REG_WRAM_C_BNK_PACK(4, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_128KB, TRUE), + REG_WRAM_C_BNK_PACK(5, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_160KB, TRUE), + REG_WRAM_C_BNK_PACK(6, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_192KB, TRUE), + REG_WRAM_C_BNK_PACK(7, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_224KB, TRUE), + }, + REG_WRAM_A_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_A_IMG_128KB + ), + REG_WRAM_B_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_B_IMG_128KB + ), + REG_WRAM_C_MAP_PACK(HW_WRAM_AREA_HALF, + HW_WRAM_AREA_HALF + 0x00020000, + MI_WRAM_C_IMG_128KB + ), + + // ARM7 + REG_WRAM_A_MAP_PACK(HW_WRAM_AREA_HALF, + HW_WRAM_AREA_HALF + 0x00020000, + MI_WRAM_A_IMG_128KB + ), + REG_WRAM_B_MAP_PACK(HW_WRAM_AREA_HALF + 0x00020000, + HW_WRAM_AREA_HALF + 0x00040000, + MI_WRAM_B_IMG_128KB + ), + REG_WRAM_C_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_C_IMG_128KB + ), + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + MI_WRAM_ARM7_ALL, + + // VRAM-C + 7, + // VRAM-D + 7, +}; diff --git a/build/tools/makegcdfirm/wram_regs.c b/build/tools/makegcdfirm/wram_regs.c new file mode 100644 index 0000000..fba20ce --- /dev/null +++ b/build/tools/makegcdfirm/wram_regs.c @@ -0,0 +1,96 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makegcdfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include "format_rom.h" +//#define SDK_ASM +#define NITRO_TYPES_H_ +#include +#include +#include + + +MIHeader_WramRegs wram_regs_init = +{ + // ARM9 + { + REG_MI_MBK_A0_FIELD( 1, MI_WRAM_A_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A1_FIELD( 1, MI_WRAM_A_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A2_FIELD( 1, MI_WRAM_A_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_A3_FIELD( 1, MI_WRAM_A_OFFSET_192KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_B0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_C0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM9 ), + }, + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, HW_WRAM_AREA_HALF ) + ), + + // ARM7 + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, HW_WRAM_AREA_HALF ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00020000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, MI_WRAM_MAP_NULL ) + ), + + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + 3, + + // VRAM-C + 7, + // VRAM-D + 7, +}; + diff --git a/build/tools/makenandfirm/Makefile b/build/tools/makenandfirm/Makefile new file mode 100644 index 0000000..11436d9 --- /dev/null +++ b/build/tools/makenandfirm/Makefile @@ -0,0 +1,151 @@ +#! make -f +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makenandfirm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- + +TARGET_PLATFORM = TWL + +SUPPORT_ECC = 0 + +ifeq ($(SUPPORT_ECC),1) +ECC_SRCDIR = ../../libraries/acsign_ecc/common \ + ../../libraries/acsign_ecc/common/algae/common/ecc \ + ../../libraries/acsign_ecc/common/algae/cmp \ + ../../libraries/acsign_ecc/common/algae/ecsource \ + +ECC_INCDIR = ../../libraries/acsign_ecc/include \ + ../../libraries/acsign_ecc/common/algae/include \ + ../../libraries/acsign_ecc/common/algae/common/include \ + +ECC_SRCS = acsign_ecc.c acsign_cryptoc.c \ + \ + cmparith.c cmpbits.c cmpcnv.c cmpdiv.c cmpmem.c \ + cmpmod.c cmpmuldv.c cmpspprt.c cmpsqr.c cmpvectr.c \ + computem.c ecfpatbl.c ecfpsmul.c \ + spcprime.c secfpcom.c \ + \ + p224v1.c p224v1a.c \ + +ECC_DEFS = -DRSA_PROTOTYPES=RSA_ENABLED \ + -DRCOM_BUILD=RSA_ENABLED -DRSA_FAST_INVERSE=RSA_ENABLED \ + -DRSA_STD_MEM_FUNCS=RSA_ENABLED -DRSA_STD_ALLOC_FUNCS=RSA_ENABLED \ +else +ECC_SRCDIR = +ECC_INCDIR = +ECC_SRCS = +ECC_DEFS = +endif + +SRCDIR += ../acsign $(ECC_SRCDIR) +INCDIR += ../acsign/include $(ECC_INCDIR) $(ECC_SRCDIR) + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +TARGETS = makenandfirm.exe + +SOURCES_C = makenandfirm.c \ + out_nandfirm.c \ + misc.c \ + path.c \ + defval.c \ + compress.c \ + wram_regs.c \ + acsign.c \ + acsign_nand.c \ + aes2.c \ + $(ECC_SRCS) + +SOURCES = $(SORUCES_C) + +OBJECTS = $(SOURCES_C:.c=.o) + +HEADERS = format_nlist.h \ + makenandfirm.h \ + path.h \ + format_rom.h \ + misc.h \ + defval.h \ + compress.h \ + +MACROS += -DSMALL_CODE_SIZE \ + -DSTANDALONE \ + -DOPT_32_BIT \ + -DNO_SPLIT \ + -DNO_FP_API \ + -DNO_R_DIAG \ + $(ECC_DEFS) + +INSTALL_DIR = $(FIRM_INSTALL_TOOLSDIR)/bin +INSTALL_TARGETS = $(TARGETS) + +LDIRT_CLEAN = $(OBJECTS) $(TARGETS) version.h + + +VPATH = $(SRCDIR) +TWL_INCDIR := $(TWL_INCDIR) $(addprefix -I,$(INCDIR)) $(addprefix -I,$(FIRM_INCDIR)) + +include $(TWLSDK_ROOT)/build/buildtools/twl/modulerules.x86 + +#---------------------------------------------------------------------------- +# build +#---------------------------------------------------------------------------- +do-build: $(TARGETS) + +$(TARGETS): $(OBJECTS) + $(CC_X86) $+ -o $@ + +makenandfirm.o: makenandfirm.c makenandfirm.h format_rom.h path.h version.h +out_nandfirm.o: out_nandfirm.c misc.h format_rom.h format_nlist.h format_sign.h elf.h compress.h \ + $(FIRM_INCDIR)/firm/format/sign.h \ + $(FIRM_INCDIR)/firm/format/wram_regs.h \ + $(FIRM_INCDIR)/firm/format/nandfirm.h \ + +misc.o: misc.c misc.h +path.o: path.c path.h +compress.o: compress.c compress.h +wram_regs.o: wram_regs.c +acsign.o: acsign.c ../acsign/include/acsign.h +acsign_nand.o: acsign_nand.c format_sign.h \ + $(FIRM_INCDIR)/firm/format/sign.h \ + $(FIRM_INCDIR)/firm/format/wram_regs.h \ + $(FIRM_INCDIR)/firm/format/nandfirm.h \ + +aes2.o: aes2.c aes2.h + +$(FIRM_INCDIR)/firm/format/sign.h: +$(FIRM_INCDIR)/firm/format/wram_regs.h: +$(FIRM_INCDIR)/firm/format/nandfirm.h: +format_nlist.h: +format_rom.h: +makenandfirm.h: +acsign.h: +acsign_nand.h: +path.h: + +# avoid to warning message +misc.o:WARNING += -Wno-format-y2k + +# + +version.h: $(SOURCES) $(HEADERS) + @for i in $^ ; \ + do \ + date -r $$i +'#define SDK_DATE_OF_LATEST_FILE %Y%m%dUL'; \ + done | sort | tail -1 > $@ + +test: path.c misc.c + $(CC_X86) -DTEST $+ -o $@ diff --git a/build/tools/makenandfirm/compress.c b/build/tools/makenandfirm/compress.c new file mode 100644 index 0000000..71e468c --- /dev/null +++ b/build/tools/makenandfirm/compress.c @@ -0,0 +1,293 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: compress.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // atoi() +#include // strcmp() +#include // isprint() +#include // chdir() +#include +#include // UCHAR_MAX +#include +#include // stat() +#include "elf.h" +#include "misc.h" +#include "defval.h" +#include "format_rom.h" +#include "format_nlist.h" +#include "makenandfirm.h" + +//#define ADD_HEADER + +#define DIFF_CODE_HEADER (0x80) +#define RL_CODE_HEADER (0x30) +#define LZ_CODE_HEADER (0x10) +#define HUFF_CODE_HEADER (0x20) +#define CODE_HEADER_MASK (0xF0) + +//=========================================================================== +// LZ77k +//=========================================================================== +static u8 SearchLZ(const u8 *nextp, u32 remainSize, u16 *offset); + +static u16 windowPos; +static u16 windowLen; + +static s16 LZOffsetTable[4096]; +static s16 LZByteTable[256]; +static s16 LZEndTable[256]; + + +static void LZInitTable(void) +{ + u16 i; + + for (i = 0; i < 256; i++) + { + LZByteTable[i] = -1; + LZEndTable[i] = -1; + } + windowPos = 0; + windowLen = 0; +} + +static void SlideByte(const u8 *srcp) +{ + s16 offset; + u8 in_data = *srcp; + u16 insert_offset; + + if (windowLen == 4096) + { + u8 out_data = *(srcp - 4096); + if ((LZByteTable[out_data] = LZOffsetTable[LZByteTable[out_data]]) == -1) + { + LZEndTable[out_data] = -1; + } + insert_offset = windowPos; + } + else + { + insert_offset = windowLen; + } + + offset = LZEndTable[in_data]; + if (offset == -1) + { + LZByteTable[in_data] = insert_offset; + } + else + { + LZOffsetTable[offset] = insert_offset; + } + LZEndTable[in_data] = insert_offset; + LZOffsetTable[insert_offset] = -1; + + if (windowLen == 4096) + { + windowPos = (u16)((windowPos + 1) % 0x1000); + } + else + { + windowLen++; + } +} + +static void LZSlide(const u8 *srcp, u32 n) +{ + u32 i; + + for (i = 0; i < n; i++) + { + SlideByte(srcp++); + } +} + +/*---------------------------------------------------------------------------* + Name: MI_CompressLZ + + Description: LZ77ksȂ֐ + + Arguments: srcp kf[^ւ̃|C^ + size kf[^TCY + dstp kf[^ւ̃|C^ + kf[^傫TCỸobt@KvłB + + Returns: k̃f[^TCYB + k̃f[^kO傫Ȃꍇɂ͈k𒆒f0Ԃ܂B + *---------------------------------------------------------------------------*/ +u32 LZCompWrite(u8 *srcp, u32 size, u8 *dstp, int boundary) +{ + u32 LZDstCount; // kf[^̃oCg + u8 LZCompFlags; // k̗LtOn + u8 *LZCompFlagsp; // LZCompFlags i[郁̈|Cg + u16 lastOffset; // vf[^܂ł̃ItZbg (̎_ł̍Œvf[^) + u8 lastLength; // vf[^ (̎_ł̍Œvf[^) + u8 i; + u32 dstMax; + +#ifdef ADD_HEADER + *(u32 *)dstp = size << 8 | LZ_CODE_HEADER; // f[^Ewb_ + dstp += 4; +#endif + LZDstCount = 4; + dstMax = size; + LZInitTable(); + + while (size > 0) + { + LZCompFlags = 0; + LZCompFlagsp = dstp++; // tOn̊i[ + LZDstCount++; + + // tOn8rbgf[^ƂĊi[邽߁A8񃋁[v + for (i = 0; i < 8; i++) + { + LZCompFlags <<= 1; // (i=0) ͓ɈӖ͂Ȃ + if (size <= 0) + { + // I[ɗꍇ̓tOŌ܂ŃVtgĂI + continue; + } + + if ((lastLength = SearchLZ(srcp, size, &lastOffset))) + { + // k”\ȏꍇ̓tO𗧂Ă + LZCompFlags |= 0x1; + + // ItZbg͏4rbgƉ8rbgɕĊi[ + *dstp++ = (u8)((lastLength - 3) << 4 | (lastOffset - 1) >> 8); + *dstp++ = (u8)((lastOffset - 1) & 0xff); + LZDstCount += 2; + LZSlide(srcp, lastLength); + srcp += lastLength; + size -= lastLength; + } + else + { + // kȂ + LZSlide(srcp, 1); + *dstp++ = *srcp++; + size--; + LZDstCount++; + } + } // 8񃋁[vI + *LZCompFlagsp = LZCompFlags; // tOni[ + } + + // 16oCgEACg + // ACgpf[^0 ̓f[^TCYɊ܂߂ + i = 0; + while (LZDstCount & (boundary - 1)) +// while ((LZDstCount + i) & 0x3) + { + *dstp++ = 0; + LZDstCount++; + i++; + } + + return LZDstCount; +} + +//-------------------------------------------------------- +// LZ77kŃXCh̒Œv܂B +// Arguments: startp f[^̊Jnʒu|C^ +// nextp Jnf[^̃|C^ +// remainSize cf[^TCY +// offset vItZbgi[̈ւ̃|C^ +// Return : v񂪌‚ꍇ TRUE +// ‚Ȃꍇ FALSE +//-------------------------------------------------------- +static u8 SearchLZ(const u8 *nextp, u32 remainSize, u16 *offset) +{ + const u8 *searchp; + const u8 *headp, *searchHeadp; + u16 maxOffset; + u8 maxLength = 2; + u8 tmpLength; + s32 w_offset; + + if (remainSize < 3) + { + return 0; + } + + w_offset = LZByteTable[*nextp]; + + while (w_offset != -1) + { + if (w_offset < windowPos) + { + searchp = nextp - windowPos + w_offset; + } + else + { + searchp = nextp - windowLen - windowPos + w_offset; + } + + /* ĂǂA͂ɍ */ + if (*(searchp + 1) != *(nextp + 1) || *(searchp + 2) != *(nextp + 2)) + { + w_offset = LZOffsetTable[w_offset]; + continue; + } + + if (nextp - searchp < 2) + { + // VRAM2oCgANZXȂ̂ (VRAMf[^ǂݏoꍇ邽)A + // Ώۃf[^2oCgÕf[^ɂȂ΂ȂȂB + // + // ItZbg12rbgŊi[邽߁A4096ȉ + break; + } + tmpLength = 3; + searchHeadp = searchp + 3; + headp = nextp + 3; + + while (((u32)(headp - nextp) < remainSize) && (*headp == *searchHeadp)) + { + headp++; + searchHeadp++; + tmpLength++; + + // f[^4rbgŊi[邽߁A18ȉ (3̉ʂ͂) + if (tmpLength == (0xF + 3)) + { + break; + } + } + if (tmpLength > maxLength) + { + // ő咷ItZbgXV + maxLength = tmpLength; + maxOffset = (u16)(nextp - searchp); + if (maxLength == (0xF + 3)) + { + // vőȂ̂ŁAIB + break; + } + } + w_offset = LZOffsetTable[w_offset]; + } + + if (maxLength < 3) + { + return 0; + } + *offset = maxOffset; + return maxLength; +} + diff --git a/build/tools/makenandfirm/compress.h b/build/tools/makenandfirm/compress.h new file mode 100644 index 0000000..f8fd899 --- /dev/null +++ b/build/tools/makenandfirm/compress.h @@ -0,0 +1,38 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: compress.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef COMPRESS_H_ +#define COMPRESS_H_ + +#include "misc.h" + + +/*---------------------------------------------------------------------------* + Name: MI_CompressLZ + + Description: LZ77ksȂ֐ + + Arguments: srcp kf[^ւ̃|C^ + size kf[^TCY + dstp kf[^ւ̃|C^ + kf[^傫TCỸobt@KvłB + + Returns: k̃f[^TCYB + *---------------------------------------------------------------------------*/ +u32 LZCompWrite(u8 *srcp, u32 size, u8 *dstp, int boundary); + + +#endif //COMPRESS_H_ diff --git a/build/tools/makenandfirm/defval.c b/build/tools/makenandfirm/defval.c new file mode 100644 index 0000000..679fb0e --- /dev/null +++ b/build/tools/makenandfirm/defval.c @@ -0,0 +1,315 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makerom + File: defval.c + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: defval.c,v $ + Revision 1.10 2006/01/18 02:11:19 kitase_hirotake + do-indent + + Revision 1.9 2005/02/28 05:26:03 yosizaki + do-indent. + + Revision 1.8 2004/08/05 13:50:13 yasu + Support -M option + + Revision 1.7 2004/06/29 04:55:40 yasu + Use VBuffer to resolve variables + + Revision 1.6 2004/06/23 07:51:02 yasu + fix a bug as illegal memory freeing at ResolveDefVal() + + Revision 1.5 2004/05/27 00:40:49 yasu + care also about current directory (dot ".") + + Revision 1.4 2004/05/27 00:25:46 yasu + care about double-dots ".." for defvalue option :r, :e + + Revision 1.3 2004/05/27 00:11:19 yasu + fix a error when searching a "dot" of file extension + + Revision 1.2 2004/05/26 12:02:47 yasu + support :h, :t, :r, :e option for variable name + + Revision 1.1 2004/03/26 05:06:45 yasu + support variables like as -DNAME=VALUE + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include // getenv() +#include // strcasecmp() +#include // getopt() +#include "misc.h" +#include "defval.h" + +typedef struct tValdef +{ + struct tValdef *next; + char *name; + char *value; +} +tValdef; + +tValdef *valdef_top = NULL; + + +// +// Add new define value via file +// +// opt : "DEFINE=VALUE" +// +BOOL AddDefValFromFile(char *filename) +{ + char *buffer; + int buffer_size; + int read_size; + FILE *fp; + + if (filename[0] == '-' && filename[1] == '\0') + { + fp = stdin; + } + else if (NULL == (fp = fopen(filename, "rb"))) + { + fprintf(stderr, "Cannot open file \"%s\".\n", filename); + return FALSE; + } + + buffer_size = DEFVAL_DEFAULT_BUFFER_SIZE; + + if (NULL == (buffer = malloc(buffer_size))) + { + fprintf(stderr, "Cannot allocate memory.\n"); + return FALSE; + } + + read_size = 0; + + while (NULL != fgets(buffer + read_size, buffer_size - read_size, fp)) + { + read_size = strlen(buffer); + + if (read_size == buffer_size - 1 && buffer[read_size - 1] != '\n') + { + buffer_size *= 2; + + if (NULL == (buffer = realloc(buffer, buffer_size))) + { + fprintf(stderr, "Cannot allocate memory.\n"); + return FALSE; + } + continue; + } + + AddDefVal(buffer); + read_size = 0; + } + + if (fp != stdin) + { + fclose(fp); + } + free(buffer); + + return TRUE; +} + + +// +// Add new define value +// +// opt : "DEFINE=VALUE" +// +void AddDefVal(char *opt) +{ + int i; + tValdef *t; + + for (i = 0;; i++) + { + if ('=' == opt[i] || '\0' == opt[i]) + { + break; + } + } + + if (i > 0) + { + t = Alloc(sizeof(tValdef)); + t->name = strncpy(Alloc(i + 1), opt, i); + t->name[i] = '\0'; + + if (opt[i] == '=') + { + i++; + } + t->value = strdup(opt + i); + + t->next = valdef_top; + valdef_top = t; + + debug_printf("DEFINE:$(%s)=\"%s\"\n", t->name, t->value); + } + return; +} + +// +// Search define value +// +// Return: value of specified name +// +char *SearchDefVal(char *name) +{ + tValdef *t; + + for (t = valdef_top; t; t = t->next) + { + if (!strcmp(t->name, name)) + { + return t->value; + } + } + + return getenv(name); +} + + +// +// Search define value and Modify it by : option +// +// Return: duplicated value of specified name modified by :x option +// +char *SearchDefValWithOption(char *name) +{ + int len_name = strlen(name); + char *value; + char option = '\0'; + + if (len_name > 2 && name[len_name - 2] == ':') + { + name[len_name - 2] = '\0'; + option = name[len_name - 1]; + } + + value = SearchDefVal(name); + + if (value) + { + int value_len = strlen(value); + int col_dot = value_len; + int col_filename = 0; + int i; + + for (i = 0; i < value_len; i++) + { + switch (value[i]) + { + case '.': + if (col_filename == i && + (value[i + 1] == '\0' || (value[i + 1] == '.' && value[i + 2] == '\0'))) + { + i = value_len; // exit loop if last entry is . or .. + } + else + { + col_dot = i; // Save the last dot column + } + break; + + case '/': + case '\\': + case ':': + col_filename = i + 1; // Save the last filename + col_dot = value_len; // Reset dot position + break; + + default: + ; + } + } + + switch (option) + { + case 'h': // Dirname with the last slash + value = strdup(value); + value[col_filename] = '\0'; + break; + + case 't': // Filename + value = strdup(value + col_filename); + break; + + case 'r': // All without . file extension + value = strdup(value); + value[col_dot] = '\0'; + break; + + case 'e': // File extension + value = strdup(value + col_dot + 1); + break; + + default: + value = strdup(value); + } + } + return value; +} + + +// +// Resolve define value +// +// Return: new string +// +char *ResolveDefVal(char *str) +{ + int i, j; + char *val; + VBuffer buf; + + InitVBuffer(&buf); + + for (i = 0; '\0' != str[i]; i++) + { + // search $(XXX) + if ('$' == str[i] && '(' == str[i + 1]) + { + for (j = i + 2; '\0' != str[j]; j++) + { + if (')' == str[j]) + { + str[j] = '\0'; + + // get value of XXX + val = SearchDefValWithOption(&str[i + 2]); + + // copy value of XXX + if (val) + { + char *s = val; + + while (*s) + { + PutVBuffer(&buf, *s); + s++; + } + free(val); + } + i = j; + goto next; + } + } + } + PutVBuffer(&buf, str[i]); + next:; + } + return GetVBuffer(&buf); // pass allocated buffer, should be freed by caller +} diff --git a/build/tools/makenandfirm/defval.h b/build/tools/makenandfirm/defval.h new file mode 100644 index 0000000..7135510 --- /dev/null +++ b/build/tools/makenandfirm/defval.h @@ -0,0 +1,38 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makerom + File: defval.h + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: defval.h,v $ + Revision 1.4 2006/01/18 02:11:19 kitase_hirotake + do-indent + + Revision 1.3 2005/02/28 05:26:03 yosizaki + do-indent. + + Revision 1.2 2004/08/05 13:50:13 yasu + Support -M option + + Revision 1.1 2004/03/26 05:06:45 yasu + support variables like as -DNAME=VALUE + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef DEFVAL_H_ +#define DEFVAL_H_ + +#define DEFVAL_DEFAULT_BUFFER_SIZE (1024) + +BOOL AddDefValFromFile(char *filename); +void AddDefVal(char *opt); +char *SearchDefVal(char *name); +char *ResolveDefVal(char *str); + +#endif //DEFVAL_H_ diff --git a/build/tools/makenandfirm/elf.h b/build/tools/makenandfirm/elf.h new file mode 100644 index 0000000..c360cd3 --- /dev/null +++ b/build/tools/makenandfirm/elf.h @@ -0,0 +1,431 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - ELF + File: elf.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + *---------------------------------------------------------------------------*/ + +#ifndef ELF_H_ +#define ELF_H_ + +#include "misc.h" + +/*--------------------------------------------------------- + ^` + --------------------------------------------------------*/ +typedef u32 Elf32_Addr; /* size:4, align:4 Unsigned program address */ +typedef u16 Elf32_Half; /* size:2, align:2 Unsigned medium int */ +typedef u32 Elf32_Off; /* size:4, align:4 Unsigned file offset */ +typedef s32 Elf32_Sword; /* size:4, align:4 Signed large int */ +typedef u32 Elf32_Word; /* size:4, align:4 Unsigned large int */ + +/*--------------------------------------------------------- + ELF Header + --------------------------------------------------------*/ +/* e_ident̃CfbNX */ +#define EI_MAG0 0 /* File identification */ +#define EI_MAG1 1 /* File identification */ +#define EI_MAG2 2 /* File identification */ +#define EI_MAG3 3 /* File identification */ +#define EI_CLASS 4 /* File class 0=invalid, 1=32bit, 2=64bit */ +#define EI_DATA 5 /* Data encoding 0=invalid, 1=LSB, 2=MSB */ +#define EI_VERSION 6 /* File version ݂1 */ +#define EI_PAD 7 /* Start of padding bytes */ +#define EI_NIDENT 16 /* Size of e_ident[] */ + +typedef struct { + unsigned char e_ident[EI_NIDENT]; + Elf32_Half e_type; /* ELF̌`(Ĕzu”\, s”\Ȃ) */ + Elf32_Half e_machine; /* t@CŗvA[LeN` */ + Elf32_Word e_version; /* ELFtH[}bg̃o[Wi݂1j */ + Elf32_Addr e_entry; /* vÕGg|CgBw薳Ȃ0B */ + Elf32_Off e_phoff; /* vOwb_e[ũt@C擪̃ItZbg */ + Elf32_Off e_shoff; /* ZNVwb_e[ũt@C擪̃ItZbg */ + Elf32_Word e_flags; /* vZbTŗL̃tO */ + Elf32_Half e_ehsize; /* ELFwb_̃TCY */ + Elf32_Half e_phentsize; /* 1vOwb_̃TCY */ + Elf32_Half e_phnum; /* vOwb_̐ */ + Elf32_Half e_shentsize; /* 1ZNVwb_̃TCY */ + Elf32_Half e_shnum; /* ZNVwb_̐ */ + Elf32_Half e_shstrndx; /* ZNVe[uZNVւ̃CfbNX */ +} Elf32_Ehdr; + +/* e_ident[EI_*]̒g` */ +#define ELFMAG0 0x7f +#define ELFMAG1 'E' +#define ELFMAG2 'L' +#define ELFMAG3 'F' +#define ELFCLASSNONE 0 /* invalid */ +#define ELFCLASS32 1 /* ARM and Thumb processors use 32-bit ELF. */ +#define ELFCLASS64 2 +#define ELFDATANONE 0 /* invalid */ +#define ELFDATA2LSB 1 /* little-endian */ +#define ELFDATA2MSB 2 /* big-endian */ + + +/* [e_type] */ +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* Re-locatable file */ +#define ET_EXEC 2 /* Executable file */ +#define ET_DYN 3 /* Shared object file */ +#define ET_CORE 4 /* Core file */ +#define ET_LOPROC 0xff00 /* Processor-specific */ +#define ET_HIPROC 0xffff /* Processor-specific */ + +/* [e_machine] */ +#define EM_NONE 0 /* No machine */ +#define EM_M32 1 +#define EM_SPARC 2 +#define EM_386 3 +#define EM_68K 4 +#define EM_88K 5 +#define EM_860 7 +#define EM_MIPS 8 +#define EM_MIPS_RS4_BE 10 +#define EM_ARM 40 /* ARM/Thumb Architecture */ + + +/* [e_version] This member identifies the object file version.*/ +#define EV_NONE 0 /* Invalid version */ +#define EV_CURRENT 1 /* Current version */ + + +/* + ARM-specific e_flags + e_flags Field Value Meaning + EF_ARM_HASENTRY (0x02) e_entry contains a program-loader entry point + (see section 4.1.1, Entry points, below). + EF_ARM_SYMSARESORTED (0x04) Each subsection of the symbol table is sorted by symbol value + (see section 4.4.8, Symbol table order, below) + EF_ARM_DYNSYMSUSESEGIDX (0x8) Symbols in dynamic symbol tables that are defined in sections + included in program segment n have st_shndx = n + 1. + (see section 4.4.9, Dynamic symbol table entries, below). + EF_ARM_MAPSYMSFIRST (0x10) Mapping symbols precede other local symbols in the symbol table + (see section 4.4.8, Symbol table order, below). + + EF_ARM_EABIMASK (0xFF000000)(current version is 0x02000000) + This masks an 8-bit version number, the version of the ARM + EABI to which this ELF file conforms. This EABI is version 2. A + value of 0 denotes unknown conformance. +*/ +#define EF_ARM_HASENTRY 0x02 +#define EF_ARM_SYMSARESORTED 0x04 +#define EF_ARM_DYNSYMSUSESEGIDX 0x8 +#define EF_ARM_MAPSYMSFIRST 0x10 +#define EF_ARM_EABIMASK 0xFF000000 + + +/*--------------------------------------------------------- + Program headers + --------------------------------------------------------*/ +typedef struct { + Elf32_Word p_type; + Elf32_Off p_offset; + Elf32_Addr p_vaddr; + Elf32_Addr p_paddr; + Elf32_Word p_filesz; + Elf32_Word p_memsz; + Elf32_Word p_flags; + Elf32_Word p_align; +} Elf32_Phdr; + +/* [p_type] */ +#define PT_NULL 0 /* gȂGgŁÃo̒l̈Ӗ͖` */ +#define PT_LOAD 1 /* sɃ[hZOg */ +#define PT_DYNAMIC 2 /* I\̔zێZOg */ +#define PT_INTERP 3 /* t@C̉߂ɎgC^v^̃pXێZOg */ +#define PT_NOTE 4 /* t@C̉߂ɂ͎gȂێZOg */ +#define PT_SHLIB 5 /* \ */ +#define PT_PHDR 6 /* vOwb_e[uivÕC[Ẅꕔłꍇ̂ݑ݁j */ +//#define PT_TLS ? /* XbhǏL̈̃ev[g */ + +#define PT_LOOS 0x60000000 /* OSŗLɗ\񂳂ꂽ̈ */ +#define PT_HIOS 0x6fffffff + +#define PT_LOPROC 0x70000000 /* vZbTŗLɗ\񂳂ꂽ̈ */ +#define PT_HIPROC 0x7fffffff + +/* [p_flags]*/ +#define PF_X 1 /*s”\*/ +#define PF_W 2 /*݉”\*/ +#define PF_R 4 /*ǂݏo”\*/ +#define PF_ARM_SB 0x10000000 /*The segment contains the location addressed by the static base*/ +#define PF_ARM_PI 0x20000000 /*The segment is position-independent*/ +#define PF_ARM_ENTRY 0x80000000 /*The segment contains the entry point*/ +#define PF_MASKPROC 0xf0000000 + + +/*--------------------------------------------------------- + Section headers + --------------------------------------------------------*/ +typedef struct { + Elf32_Word sh_name; /*ZNVwb_e[uZNṼCfbNX*/ + Elf32_Word sh_type; /* ^CviL`QƁj */ + Elf32_Word sh_flags; + Elf32_Addr sh_addr; /* */ + Elf32_Off sh_offset; /* t@C̐擪̃ItZbg */ + Elf32_Word sh_size; /* oCgPʂ̃TCY */ + Elf32_Word sh_link; /* sh_typeɂĒl̈Ӗς */ + Elf32_Word sh_info; /* sh_typeɂĒl̈Ӗς */ + Elf32_Word sh_addralign; /* ACg(0or1ŐȂ,44ByteAlign) */ + Elf32_Word sh_entsize; /* ŒTCỸGge[uꍇA1vf̃TCY */ +} Elf32_Shdr; + +/* sh_addr mod sh_addralign = 0 łȂ΂ȂȂ */ + +/* Section Types, [sh_type] */ +#define SHT_NULL 0 +#define SHT_PROGBITS 1 +#define SHT_SYMTAB 2 +#define SHT_STRTAB 3 +#define SHT_RELA 4 +#define SHT_HASH 5 +#define SHT_DYNAMIC 6 +#define SHT_NOTE 7 +#define SHT_NOBITS 8 +#define SHT_REL 9 +#define SHT_SHLIB 10 +#define SHT_DYNSYM 11 +#define SHT_LOPROC 0x70000000 +#define SHT_HIPROC 0x7fffffff +#define SHT_LOUSER 0x80000000 +#define SHT_HIUSER 0xffffffff + + +/* [sh_flags] */ +#define SHF_WRITE 0x1 +#define SHF_ALLOC 0x2 +#define SHF_EXECINSTR 0x4 +#define SHF_MASKPROC 0xf0000000 +/* ARM-EABI-specific */ +#define SHF_ENTRYSECT 0x10000000 /* The section contains an entry point. */ +#define SHF_COMDEF 0x80000000 /* The section may be multiply defined in the input to a link step. */ +/* others */ +#define SHF_LINK_ORDER 0x80 + +/*ZNVCfbNX*/ +//Sym->st_shndxȂ +#define SHN_UNDEF 0 +#define SHN_LORESERVE 0xff00 +#define SHN_LOPROC 0xff00 +#define SHN_HIPROC 0xff1f +#define SHN_ABS 0xfff1 +#define SHN_COMMON 0xfff2 +#define SHN_HIRESERVE 0xffff + + +//̓wb_łȂ̃f[^\ + +/*--------------------------------------------------------- + Symbol Table Entry + --------------------------------------------------------*/ +typedef struct { + Elf32_Word st_name; /* V{e[ũCfbNX */ + Elf32_Addr st_value; /* 炭֘AZNVł̃ItZbgl */ + Elf32_Word st_size; /* TCYȂAsȏꍇ 0 */ + unsigned char st_info; /* oCh ^Cv */ + unsigned char st_other; /* ݂ 0 */ + Elf32_Half st_shndx; /* ֘AZNVwb_e[ũCfbNX */ +} Elf32_Sym; + + +/* st_info */ +#define ELF32_ST_BIND(i) ((i)>>4) +#define ELF32_ST_TYPE(i) ((i)&0xf) +#define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) + +/* st_info BIND */ +#define STB_LOCAL 0 +#define STB_GLOBAL 1 +#define STB_WEAK 2 +#define STB_LOPROC 13 +#define STB_HIPROC 15 + +/* st_info TYPE */ +#define STT_NOTYPE 0 /*`*/ +#define STT_OBJECT 1 /*f[^IuWFNg*/ +#define STT_FUNC 2 +#define STT_SECTION 3 +#define STT_FILE 4 +#define STT_LOPROC 13 +#define STT_HIPROC 15 + + +/*--------------------------------------------------------- + Relocation Entry + --------------------------------------------------------*/ +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; +} Elf32_Rel; + +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; + Elf32_Sword r_addend; +} Elf32_Rela; + +#define ELF32_R_SYM(i) ((i)>>8) +#define ELF32_R_TYPE(i) ((unsigned char)(i)) +#define ELF32_R_INFO(s,t) (((s)<<8)+(unsigned char)(t)) + + +/* r_info TYPE */ +#define R_ARM_NONE 0 /* Any No relocation. Encodes dependencies between sections. */ +#define R_ARM_PC24 1 /* ARM B/BL S . P + A */ +#define R_ARM_ABS32 2 /* 32-bit word S + A */ +#define R_ARM_REL32 3 /* 32-bit word S . P + A */ +#define R_ARM_PC13 4 /* ARM LDR r, [pc,c] S . P + A */ +#define R_ARM_ABS16 5 /* 16-bit half-word S + A */ +#define R_ARM_ABS12 6 /* ARM LDR/STR S + A */ +#define R_ARM_THM_ABS5 7 /* Thumb LDR/STR S + A */ +#define R_ARM_ABS8 8 /* 8-bit byte S + A */ +#define R_ARM_SBREL32 9 /* 32-bit word S . B + A */ +#define R_ARM_THM_PC22 10 /* Thumb BL pair S . P+ A */ +#define R_ARM_THM_PC8 11 /* Thumb LDR r, [pc,c] S . P + A */ +#define R_ARM_AMP_VCALL9 12 /* AMP VCALL Obsolete.SA-1500 only. */ +#define R_ARM_SWI24 13 /* ARM SWI S + A */ +#define R_ARM_THM_SWI8 14 /* Thumb SWI S + A */ +#define R_ARM_XPC25 15 /* ARM BLX S . P+ A */ +#define R_ARM_THM_XPC22 16 /* Thumb BLX pair S . P+ A */ + +/* 17-31, reserved to ARM Linux */ +//17-19 Reserved to ARM LINUX +#define R_ARM_COPY 20 /* 32 bit word Copy symbol at dynamic link time. */ +#define R_ARM_GLOB_DAT 21 /* 32 bit word Create GOT entry. */ +#define R_ARM_JUMP_SLOT 22 /* 32 bit word Create PLT entry. */ +#define R_ARM_RELATIVE 23 /* 32 bit word Adjust by program base. */ +#define R_ARM_GOTOFF 24 /* 32 bit word Offset relative to start of GOT. */ +#define R_ARM_GOTPC 25 /* 32 bit word Insert address of GOT. */ +#define R_ARM_GOT32 26 /* 32 bit word Entry in GOT. */ +#define R_ARM_PLT32 27 /* ARM BL Entry in PLT. */ + +/* 28-31 Reserved to ARM LINUX */ +#define R_ARM_ALU_PCREL_7_0 32 /* ARM ADD/SUB (S . P + A) & 0x000000FF */ +#define R_ARM_ALU_PCREL_15_8 33 /* ARM ADD/SUB (S . P + A) & 0x0000FF00 */ +#define R_ARM_ALU_PCREL_23_15 34 /* ARM ADD/SUB (S . P + A) & 0x00FF0000 */ +#define R_ARM_LDR_SBREL_11_0 35 /* ARM LDR/STR (S . B + A) & 0x00000FFF */ +#define R_ARM_ALU_SBREL_19_12 36 /* ARM ADD/SUB (S . B + A) & 0x000FF000 */ +#define R_ARM_ALU_SBREL_27_20 37 /* ARM ADD/SUB (S . B + A) & 0x0FF00000 */ + +#define R_ARM_TARGET1 38 +#define R_ARM_ROSEGREL32 39 +#define R_ARM_V4BX 40 +#define R_ARM_TARGET2 41 +#define R_ARM_PREL31 42 + +/* 96-111, reserved to ARM g++ */ +#define R_ARM_GNU_VTENTRY 100 /* 32 bit word Record C++ vtable entry. */ +#define R_ARM_GNU_VTINHERIT 101 /* 32 bit word Record C++ member usage. */ +#define R_ARM_THM_PC11 102 /* Thumb B S . P + A */ +#define R_ARM_THM_PC9 103 /* Thumb B S . P + A */ + +/* 112-127, reserved for private experiments */ + +/* 128-248, reserved to ARM */ +#define R_ARM_RXPC25 249 /* ARM BLX (S . P) + A #define For calls between program segments. */ +#define R_ARM_RSBREL32 250 /* Word (S . SB) + A For an offset from SB, the static base. */ +#define R_ARM_THM_RPC22 251 /* Thumb BL/BLX pair (S . P) + A For calls between program segments. */ +#define R_ARM_RREL32 252 /* Word (S . P) + A For on offset between two segments. */ +#define R_ARM_RABS32 253 /* Word S + A For the address of a location in the target segment. */ +#define R_ARM_RPC24 254 /* ARM B/BL (S . P) + A For calls between program segments. */ +#define R_ARM_RBASE 255 /* None None.Identifies the segment being relocated by the following + relocation directives. The ARM EABI poses two problems for relocating + executables and shared objects encoded in */ + + +// shirait +#define R_ARM_LDR_PC_G0 4 //LDR + +#define R_ARM_ABS12 6 //LDR, STR + +#define R_ARM_THM_CALL 10 //R_ARM_THM_PC22Ɠ + +#define R_ARM_CALL 28 //BL/BLX +#define R_ARM_JUMP24 29 //B/BL +#define R_ARM_THM_JUMP24 30 + +#define R_ARM_MOVW_ABS_NC 43 //MOVW +#define R_ARM_MOVT_ABS 44 //MOVT +#define R_ARM_MOVW_PREL_NC 45 //MOVW +#define R_ARM_MOVT_PREL 46 //MOVT + +#define R_ARM_ALU_PC_G0_NC 57 //ADD, SUB +#define R_ARM_ALU_PC_G0 58 //ADD, SUB +#define R_ARM_ALU_PC_G1_NC 59 //ADD, SUB +#define R_ARM_ALU_PC_G1 60 //ADD, SUB +#define R_ARM_ALU_PC_G2 61 //ADD, SUB +#define R_ARM_LDR_PC_G1 62 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_PC_G2 63 //LDR, STR, LDRB, STRB +#define R_ARM_LDRS_PC_G0 64 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_PC_G1 65 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_PC_G2 66 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDC_PC_G0 67 //LDC, STC +#define R_ARM_LDC_PC_G1 68 //LDC, STC +#define R_ARM_LDC_PC_G2 69 //LDC, STC +#define R_ARM_ALU_SB_G0_NC 70 //ADD, SUB +#define R_ARM_ALU_SB_G0 71 //ADD, SUB +#define R_ARM_ALU_SB_G1_NC 72 //ADD, SUB +#define R_ARM_ALU_SB_G1 73 //ADD, SUB +#define R_ARM_ALU_SB_G2 74 //ADD, SUB +#define R_ARM_LDR_SB_G0 75 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_SB_G1 76 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_SB_G2 77 //LDR, STR, LDRB, STRB +#define R_ARM_LDRS_SB_G0 78 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_SB_G1 79 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_SB_G2 80 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDC_SB_G0 81 //LDC, STC +#define R_ARM_LDC_SB_G1 82 //LDC, STC +#define R_ARM_LDC_SB_G2 83 //LDC, STC +#define R_ARM_MOVW_BREL_NC 84 //MOVW +#define R_ARM_MOVT_BREL 85 //MOVT +#define R_ARM_MOVW_BREL 86 //MOVW + +#define R_ARM_GOT_BREL12 97 //LDR +#define R_ARM_GOTOFF12 98 //LDR, STR + +#define R_ARM_TLS_LDO12 109 //LDR, STR +#define R_ARM_TLS_LE12 110 //LDR, STR +#define R_ARM_TLS_TE12GP 111 //LDR + + + +/*--------------------------------------------------------- + Dynamic Section elf_v1.2 + --------------------------------------------------------*/ +typedef struct { + Elf32_Sword d_tag; + union { + Elf32_Word d_val; + Elf32_Addr d_ptr; + } d_un; +} Elf32_Dyn; + + +/* Additional symbol types for Thumb. */ +#define STT_ARM_TFUNC STT_LOPROC /* A Thumb function. */ +#define STT_ARM_16BIT STT_HIPROC /* A Thumb label. */ + + + + + + + + + +/*--------------------------------------------------------- + ELFwb_ǂݏo + --------------------------------------------------------*/ +void *ELF_LoadELFHeader(const void *buf, Elf32_Ehdr *ehdr); + + + +#endif /* ELF_H_ */ + diff --git a/build/tools/makenandfirm/format_nlist.h b/build/tools/makenandfirm/format_nlist.h new file mode 100644 index 0000000..a1ac95f --- /dev/null +++ b/build/tools/makenandfirm/format_nlist.h @@ -0,0 +1,54 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: format_nlist.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_NLIST_H_ +#define FORMAT_NLIST_H_ + +#include +#include "misc.h" +#include "path.h" + +#define SPECFILE_MAGIC_ID "#NANDSF" + +#define CRC16_INIT_VALUE 0xffff + +//--------------------------------------------------------------------------- +// Banner Spec File +//--------------------------------------------------------------------------- + +// Command List +typedef struct +{ + char *string; + BOOL (*funcp) (char *, int num); + +} +tCommandDesc; + + +// F Command +typedef struct +{ + u32 offsetStart; + u32 offsetEnd; + u32 padding; + char fullPathSrc[FILENAME_MAX]; + +} +tFileDesc; + + +#endif // FORMAT_NLIST_H_ diff --git a/build/tools/makenandfirm/format_rom.h b/build/tools/makenandfirm/format_rom.h new file mode 100644 index 0000000..e7195c1 --- /dev/null +++ b/build/tools/makenandfirm/format_rom.h @@ -0,0 +1,51 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: format_rom.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_ROM_H_ +#define FORMAT_ROM_H_ + +#include "misc.h" +#include + + +#define DEFAULT_ALIGN 0x200 +#define FIRM_ALIGN DEFAULT_ALIGN +#define FIRM_ALIGN_MASK (FIRM_ALIGN - 1) + +#define DEFAULT_HOSTROOT "." +#define DEFAULT_ROOT "/" + +#define DEFAULT_REJECT_1 "CVS" +#define DEFAULT_REJECT_2 "vssver.scc" + +#define FORMAT_VERSION "1.0" + +#define ENTRYNAME_MAX 127 + +#define DEFAULT_LISTFILE "default.nlf" + +#define DEFAULT_NANDFIRM_SUFFIX ".nand" +#define DEFAULT_SPECFILE_SUFFIX ".nandsf" + +/*===========================================================================* + * ROM FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// ROM HEADER +//--------------------------------------------------------------------------- + +#endif //FORMAT_ROM_H_ diff --git a/build/tools/makenandfirm/format_sign.h b/build/tools/makenandfirm/format_sign.h new file mode 100644 index 0000000..6d3d277 --- /dev/null +++ b/build/tools/makenandfirm/format_sign.h @@ -0,0 +1,32 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - SS + File: format_sign.h + + Copyright 2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_MAKENANDFIRM_ACSIGN_FORMAT_H_ +#define FIRM_MAKENANDFIRM_ACSIGN_FORMAT_H_ + +#include "format_rom.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_MAKENANDFIRM_ACSIGN_FORMAT_H_ */ +#endif diff --git a/build/tools/makenandfirm/makenandfirm.c b/build/tools/makenandfirm/makenandfirm.c new file mode 100644 index 0000000..abdb1c5 --- /dev/null +++ b/build/tools/makenandfirm/makenandfirm.c @@ -0,0 +1,106 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: makenandfirm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include +#include // strcasecmp() +#include // getopt() +#include "makenandfirm.h" +#include "format_rom.h" +#include "path.h" +#include "defval.h" +#include "version.h" + +static int makenandfirm(const char *specFile, const char *nandFile); + +//--------------------------------------------------------------------------- +// Main +//--------------------------------------------------------------------------- + +int main(int argc, char *argv[]) +{ + int n; + int narg; + char *nandfirmFile; + + InitAppName(argv[0]); + + while ((n = getopt(argc, argv, "D:hvpd")) != -1) + { + switch (n) + { + case 'h': + case 'v': + goto usage; + + case 'D': + AddDefVal(optarg); + break; + + case 'p': + PrintMode = TRUE; + break; + + case 'd': + DebugMode = TRUE; + break; + + default: + break; + } + } + + narg = argc - optind; + if (narg > 0) + { + // Make SpecFile->NandfirmFile + nandfirmFile = + strdup(narg > + 1 ? argv[optind + 1] : ChangeSuffix(argv[optind], DEFAULT_NANDFIRM_SUFFIX)); + return makenandfirm(argv[optind], nandfirmFile); + } + + usage: + { + char *makenandfirm = GetAppName(); + + fprintf(stderr, + "NITRO-SDK Development Tool - %s - Make nandfirm file \n" + "Build %lu\n\n" + "Usage: %s [-phv] [-DNAME=VALUE ...] SPECFILE [NANDFIRMFILE]\n\n", + makenandfirm, SDK_DATE_OF_LATEST_FILE, makenandfirm); + } + return 1; +} + + +//--------------------------------------------------------------------------- +// makenandfirm +//--------------------------------------------------------------------------- + +static int makenandfirm(const char *specFile, const char *nandFile) +{ + debug_printf("makenandfirm(): '%s' -> '%s'\n", specFile, nandFile); + + // Check identical + if (specFile && nandFile && !strcasecmp(specFile, nandFile)) + { + error("nandfirm spec file is identical '%s'", nandFile); + return 1; + } + + return OutputNandfirmFile(specFile, nandFile) ? 0 : 1; +} diff --git a/build/tools/makenandfirm/makenandfirm.h b/build/tools/makenandfirm/makenandfirm.h new file mode 100644 index 0000000..21ac7e0 --- /dev/null +++ b/build/tools/makenandfirm/makenandfirm.h @@ -0,0 +1,24 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: makenandfirm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef MAKENANDFIRM_H_ +#define MAKENANDFIRM_H_ + +#include "misc.h" + +BOOL OutputNandfirmFile(const char *specFile, const char *nandFile); + +#endif //MAKENANDFIRM_H_ diff --git a/build/tools/makenandfirm/misc.c b/build/tools/makenandfirm/misc.c new file mode 100644 index 0000000..7326f41 --- /dev/null +++ b/build/tools/makenandfirm/misc.c @@ -0,0 +1,628 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: misc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // calloc() +#include // free(), exit() +#include // setmode() +#include // stat() +#include // setmode() +#include // strlen() +#include // va_start(),va_end() +#include // localtime() + +#include +#include "misc.h" + +BOOL DebugMode = FALSE; +BOOL PrintMode = FALSE; +char *PubkeyFileName = NULL; + +/*---------------------------------------------------------------------------* + * File Output Utilities + * + * BOOL OpenFile( const char* filename ) + * void CloseFile( void ) + * BOOL CheckResult( void ) + * void PutBuffer( const void* ptr, int len ) + * void PutByte( u8 c ) + * void PutWord( u16 c ) + * void PutWord( u32 c ) + * void PutString( const char *str ) + *---------------------------------------------------------------------------*/ + +static FILE *OutFile = NULL; +static const char *FileName = NULL; +static BOOL Status = FALSE; + + +// +// File Open +// + +BOOL OpenFile(const char *filename) +{ + if (OutFile) + CloseFile(); + + if (filename) + { + if (NULL == (OutFile = fopen(filename, "wb+"))) + { + error("Can't write '%s'", filename); + Status = FALSE; + return FALSE; + } + } + else + { + setmode(1, O_BINARY); + OutFile = stdout; // out to console if filename == NULL + } + FileName = filename; + Status = TRUE; + + return TRUE; +} + + +// +// File Close +// + +BOOL CloseFile(void) +{ + if (OutFile) + { + if (FileName) + { + if (fclose(OutFile) == -1) + { + error("Can't close '%s'", FileName); + Status = FALSE; + } + } + else + { + setmode(1, O_TEXT); + } + } + OutFile = NULL; + + return Status; +} + + +// +// File Seek +// + +void SeekFile(long pos) +{ + if (OutFile && fseek(OutFile, pos, SEEK_SET)) + { + error("Can't seek '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + + +// +// Error Check +// + +BOOL CheckResult(void) +{ + return Status; +} + + +// +// Delete outfile +// + +void DeleteOutFile(void) +{ + // Delete outfile + if (FileName) + { + debug_printf("Delete '%s'\n", FileName); + (void)unlink(FileName); + FileName = NULL; + } + return; +} + + +// +// Buffer Output +// + +void PutBuffer(const void *ptr, int len) /* If error, close file */ +{ + if (OutFile && len != fwrite(ptr, 1, len, OutFile)) + { + error("Can't write buffer to '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + +// +// Buffer Input +// + +void GetBuffer(void *ptr, int len) /* If error, close file */ +{ + if (OutFile && len != fread(ptr, 1, len, OutFile)) + { + error("Can't read '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + +// +// Byte/Half/Word Output +// + +void PutByte(u8 c) +{ + PutBuffer(&c, 1); +} +void PutHalf(u16 c) +{ + PutBuffer(&c, 2); +} +void PutWord(u32 c) +{ + PutBuffer(&c, 4); +} +void PutString(const char *str) +{ + PutBuffer(str, strlen(str)); +} + + +// +// Printf +// + +void PrintString(const char *fmt, ...) +{ + char *buffer; + va_list va; + int nchars; + int bufsize = FILENAME_MAX; + + while (1) + { + buffer = Alloc(bufsize); + va_start(va, fmt); + nchars = vsnprintf(buffer, bufsize, fmt, va); + va_end(va); + + if (0 <= nchars && nchars < bufsize) + { + break; + } + + Free(&buffer); + bufsize *= 2; + } + + if (nchars > 0) + { + PutBuffer(buffer, nchars); + } + Free(&buffer); +} + + +/*---------------------------------------------------------------------------* + * File Read/Write Utilities + * + * int ReadFile( const char* filename, void** buffer ) + * + * Read a file to buffer allocated internally + * Return read size + * Add '\0' at tail of file for help to handle text file + * + * BOOL WriteFile( const char* filename, void** buffer, int size ) + *---------------------------------------------------------------------------*/ + +int ReadFile(const char *filename, void *filebuffer, int size) +{ + FILE *fp; + struct stat fileStat; + int fileSize, readSize; + void **buffer = (void **)filebuffer; + + /* Check file */ + if (stat(filename, &fileStat) || !S_ISREG(fileStat.st_mode)) + { + goto error; + } + fileSize = fileStat.st_size; + if (fileSize < 0) + { + goto error; + } + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) + { + goto error; + } + + if (size && (size < fileSize)) + { + readSize = size; + } + else + { + readSize = fileSize; + } + + /* Read file */ + *buffer = Alloc(readSize + 1); /* error handle is done in Alloc() */ + /* size+1 for '\0' to handle text file */ + if (readSize != fread(*buffer, sizeof(char), readSize, fp)) + { + goto error_free_close; + } + + (*(char **)buffer)[readSize] = '\0'; /* Works as terminater if file is text file */ + + /* Close file */ + fclose(fp); + return readSize; + + error_free_close: + Free(buffer); + fclose(fp); + error: + error("Can't read '%s'", filename); + return -1; +} + + +int ReadFileWithPadding(const char *filename, void *filebuffer, int size, int boundary) +{ + FILE *fp; + struct stat fileStat; + int fileSize, readSize, padSize; + void **buffer = (void **)filebuffer; + + if (!boundary) + { + return ReadFile(filename, buffer, size); + } + + /* Check file */ + if (stat(filename, &fileStat) || !S_ISREG(fileStat.st_mode)) + { + goto error; + } + fileSize = fileStat.st_size; + if (fileSize < 0) + { + goto error; + } + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) + { + goto error; + } + + if (size && (size < fileSize)) + { + readSize = size; + } + else + { + readSize = fileSize; + } + + padSize = (boundary - (readSize & (boundary-1))) & (boundary-1); + + /* Read file */ + *buffer = Alloc(readSize + padSize); /* error handle is done in Alloc() */ + /* size+1 for '\0' to handle text file */ + if (readSize != fread(*buffer, sizeof(char), readSize, fp)) + { + goto error_free_close; + } + + memset((char*)*buffer + readSize, 0, padSize); + + /* Close file */ + fclose(fp); + return readSize + padSize; + + error_free_close: + Free(buffer); + fclose(fp); + error: + error("Can't read '%s'", filename); + return -1; +} + + +BOOL WriteFile(const char *filename, void *buffer, int size) +{ + debug_printf("WriteFile %s\n", filename); + + (void)OpenFile(filename); + PutBuffer(buffer, size); + CloseFile(); + Free(&buffer); + return CheckResult(); +} + + +/*---------------------------------------------------------------------------* + * Time Format Utilities + * + * char* GetGMTime( const time_t time ) Show GMT + * char* GetTime( const time_t time ) Show local Time + *---------------------------------------------------------------------------*/ + +char *GetGMTime(const time_t time) +{ + static char timebuffer[32]; + strftime(timebuffer, sizeof(timebuffer), "%y/%m/%d-%H:%M:%S", gmtime(&time)); + return timebuffer; +} + + +char *GetTime(const time_t time) +{ + static char timebuffer[32]; + strftime(timebuffer, sizeof(timebuffer), "%y/%m/%d-%H:%M:%S", localtime(&time)); + return timebuffer; +} + + +/*---------------------------------------------------------------------------* + * Memory Allocation Utilities + * + * void* Alloc( size_t size ) + *---------------------------------------------------------------------------*/ + +void *Alloc(size_t size) +{ + void *t = calloc(1, size); + + if (t == NULL) + { + error("Can't allocate memory."); + exit(10); + } + return t; +} + + +void Free(void *p) +{ + void **ptr = (void **)p; + + if (*ptr) + { + free(*ptr); + (*ptr) = NULL; + } +} + + +/*---------------------------------------------------------------------------* + * VBuffer + * + * void PutVBuffer( VBuffer* vbuf, char c ) + *---------------------------------------------------------------------------*/ + +void PutVBuffer(VBuffer * vbuf, char c) +{ + int size; + char *tmp_buffer; + + if (vbuf->buffer == 0) + { + vbuf->size = VBUFFER_INITIAL_SIZE; + vbuf->buffer = Alloc(vbuf->size); // buffer is CALLOCed + } + size = strlen(vbuf->buffer); + + if (size >= vbuf->size - 1) + { + // Need buffer expansion + vbuf->size *= 2; + tmp_buffer = Alloc(vbuf->size); // buffer is CALLOCed + strcpy(tmp_buffer, vbuf->buffer); + Free(&vbuf->buffer); + vbuf->buffer = tmp_buffer; + } + vbuf->buffer[size] = c; + return; +} + +char *GetVBuffer(VBuffer * vbuf) +{ + return vbuf->buffer; +} + +void InitVBuffer(VBuffer * vbuf) +{ + vbuf->buffer = 0; + vbuf->size = 0; +} + +void FreeVBuffer(VBuffer * vbuf) +{ + Free(&vbuf->buffer); +} + + +/*---------------------------------------------------------------------------* + * File Path Utilities + * + * char* ChangeBackSlash( char* path ) + *---------------------------------------------------------------------------*/ + +char *ChangeBackSlash(char *path) +{ + char *p = path; + + while (*p) + { + if (*p == '\\') + { + *p = '/'; + } + p++; + } + return path; +} + + +/*---------------------------------------------------------------------------* + * Math + * + * u16 CalcCRC16( u16 start, u8 *data, int size ) + *---------------------------------------------------------------------------*/ + +static u16 crc16_table[16] = { + 0x0000, 0xCC01, 0xD801, 0x1400, + 0xF001, 0x3C00, 0x2800, 0xE401, + 0xA001, 0x6C00, 0x7800, 0xB401, + 0x5000, 0x9C01, 0x8801, 0x4400 +}; + +u16 CalcCRC16(u16 start, u8 *data, int size) +{ + u16 r1; + u16 total = start; + + while (size-- > 0) + { + // 4bit + r1 = crc16_table[total & 0xf]; + total = (total >> 4) & 0x0fff; + total = total ^ r1 ^ crc16_table[*data & 0xf]; + + // 4bit + r1 = crc16_table[total & 0xf]; + total = (total >> 4) & 0x0fff; + total = total ^ r1 ^ crc16_table[(*data >> 4) & 0xf]; + + data++; + } + return total; +} + + +/*---------------------------------------------------------------------------* + * for firm header + * + *---------------------------------------------------------------------------*/ + +static u8 ConvertAlign( u32 ofs ) +{ + u8 i; + + ofs /= 4; + for (i=0; i<7; i++) + { + if ( ofs & 1 ) + { + break; + } + ofs >>= 1; + } + + return i; +} + +tROMAddrConvType ConvertHeaderRamAddr( s32 p ) +{ + tROMAddrConvType retval; + + retval.align = ConvertAlign( p ); + retval.address = (u16)((p - HW_WRAM)/(4< + +typedef enum +{ + FALSE = 0, + TRUE = 1 +} +BOOL; + +typedef unsigned char u8; +typedef unsigned short int u16; +typedef unsigned long int u32; +typedef unsigned long long u64; +typedef signed char s8; +typedef signed short int s16; +typedef signed long int s32; +typedef signed long long s64; +typedef volatile u8 vu8; +typedef volatile u32 vu32; +typedef vu32 REGType32v; + +#define error(...) do { fprintf(stderr, "Error: "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); } while(0) + +#define warning(...) do { fprintf(stderr, "Warning: "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); } while(0) + +BOOL OpenFile(const char *filename); +BOOL CloseFile(void); +void SeekFile(long pos); +BOOL CheckResult(void); +void DeleteOutFile(void); +void PutBuffer(const void *ptr, int len); +void GetBuffer(void *ptr, int len); +void PutByte(u8 c); +void PutHalf(u16 c); +void PutWord(u32 c); +void PutString(const char *str); +void PrintString(const char *fmt, ...); + +#define READ_ALL 0 +int ReadFile(const char *filename, void *filebuffer, int size); +int ReadFileWithPadding(const char *filename, void *filebuffer, int size, int boundary); +BOOL WriteFile(const char *filename, void *buffer, int size); + +char *GetGMTime(const time_t time); +char *GetTime(const time_t time); + +void *Alloc(size_t size); +void Free(void *p); + +typedef struct +{ + char *buffer; + int size; +} +VBuffer; + +#define VBUFFER_INITIAL_SIZE 1024 +void InitVBuffer(VBuffer * vbuf); +void FreeVBuffer(VBuffer * vbuf); +void PutVBuffer(VBuffer * vbuf, char c); +char *GetVBuffer(VBuffer * vbuf); + +char *ChangeBackSlash(char *path); + +u16 CalcCRC16(u16 start, u8 *data, int size); +const char *WrapNull(const char *str); + +typedef struct +{ + u16 address; + u8 align; +} +tROMAddrConvType; + +tROMAddrConvType ConvertHeaderRamAddr( s32 p ); +tROMAddrConvType ConvertHeaderRomOffset( s32 p ); +u16 ConvertHeaderRomOffsetAlign( s32 p, u32 align ); + +typedef union +{ + struct + { + u32 sign:1; + u32 header_hash:1; + u32 arm9_hash:1; + u32 arm7_hash:1; + u32 hash_table_hash:1; + u32 final_hash:1; + u32 header_footer:1; + } + e; + u32 raw; +} +tErrorFlags; + +extern BOOL DebugMode; +extern BOOL PrintMode; +extern char *PubkeyFileName; +void debug_printf(const char *str, ...); +void debug_printf2(const char *str, ...); + +#endif //MISC_H_ diff --git a/build/tools/makenandfirm/out_nandfirm.c b/build/tools/makenandfirm/out_nandfirm.c new file mode 100644 index 0000000..ad1e69a --- /dev/null +++ b/build/tools/makenandfirm/out_nandfirm.c @@ -0,0 +1,979 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: out_nandfirm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // atoi() +#include // strcmp() +#include // isprint() +#include // chdir() +#include +#include // UCHAR_MAX +#include +#include // stat() +#include "elf.h" +#include "misc.h" +#include "defval.h" +#include "format_rom.h" +#include "format_nlist.h" +#include "makenandfirm.h" +#include "format_sign.h" +#include "acsign_nand.h" +#include "compress.h" + +#define SDK_ASM + +#include +#include "../acsign/aes2.h" + +#define SBIN9CMD "ARM9_SBIN" +#define SBIN7CMD "ARM7_SBIN" +#define ELF9CMD "ARM9_ELF" +#define ELF7CMD "ARM7_ELF" +#define COMP9CMD "ARM9_COMP" +#define COMP7CMD "ARM7_COMP" +#define DECOMPCMD "DECOMP_PROC" +#define ARM9X2CMD "ARM9_X2" +#define VERCMD "VERSION" +#define RSAKEYCMD "RSA_KEY" +#define OUTKEYCMD "OUT_KEY" +#define WREGCMD "WRAM_RBIN" +#define ENDKEYCMD "ENC_KEYINFO" +#define NCDCMD "NCD_ROMOFS" +#define MIRRORCMD "MIRROR_OFS" +#define ERRCMD "ERROR" + +static BOOL ConstructNandfirmFile(char * specFile); +static BOOL ReadSbinFile(const char *fileName, void* minfo, void* minfo2, void* hash, BOOL comp); +static BOOL ReadKeyFile(const char *fileName); +static BOOL ReadWramRegFile(const char *fileName); +static s32 GetRamAddr(const char *fileName); + +static BOOL EncryptBuffer(char *buffer, int length); + +static BOOL Sbin9_Command(char * line, int num); +static BOOL Sbin7_Command(char * line, int num); +static BOOL Elf9_Command(char * line, int num); +static BOOL Elf7_Command(char * line, int num); +static BOOL Comp9_Command(char * line, int num); +static BOOL Comp7_Command(char * line, int num); +static BOOL Decomp_Command(char * line, int num); +static BOOL ARM9X2_Command(char * line, int num); +static BOOL VERSION_Command(char * line, int num); +static BOOL RSAKEY_Command(char * line, int num); +static BOOL OUTKEY_Command(char * line, int num); +static BOOL WramRegs_Command(char * line, int num); +static BOOL ENCKEY_Command(char * line, int num); +static BOOL NcdOffset_Command(char * line, int num); +static BOOL MirrorOffset_Command(char * line, int num); +static BOOL ERROR_Command(char * line, int num); + +static BOOL InitializeAesKey(void); +static BOOL InitializeNandfirmFile(void); +static BOOL FinalizeNandfirmFile(const char *nandFile); + +static s32 Offset; // Current offset +static int LineNum; // Line number for error message +static const char *specFileName; // specFile name for error message + +NANDHeaderEx nandHeader; // Nandfirm Header Shadow +FIRMSignedContext signedContext; +u8 *keyFileBuf; +BOOL compArm9 = TRUE; +BOOL compArm7 = TRUE; +u32 mirrorOfs = 0; +tErrorFlags errFlags; + +//--------------------------------------------------------------------------- +// Output - nandfirm File +//--------------------------------------------------------------------------- + +BOOL OutputNandfirmFile(const char *specFile, const char *nandFile) +{ + char *buffer; + BOOL state; + + if (ReadFile(specFile, &buffer, READ_ALL) <= 0) + { + return FALSE; + } + + if (!OpenFile(nandFile)) + { + return FALSE; + } + + specFileName = specFile; + + state = InitializeNandfirmFile() && ConstructNandfirmFile(buffer) && + FinalizeNandfirmFile(nandFile) && CloseFile(); + + if (!state) + { + DeleteOutFile(); + } + + return state; +} + + +//--------------------------------------------------------------------------- +// Output - Nandfirm File +//--------------------------------------------------------------------------- + +static const tCommandDesc command[] = { + {SBIN9CMD, Sbin9_Command}, {SBIN7CMD, Sbin7_Command}, + {ELF9CMD, Elf9_Command},{ELF7CMD, Elf7_Command}, + {COMP9CMD, Comp9_Command},{COMP7CMD, Comp7_Command}, + {DECOMPCMD, Decomp_Command}, + {VERCMD, VERSION_Command}, + {ARM9X2CMD, ARM9X2_Command}, + {RSAKEYCMD, RSAKEY_Command}, + {OUTKEYCMD, OUTKEY_Command}, + {WREGCMD, WramRegs_Command}, + {ENDKEYCMD, ENCKEY_Command}, + {NCDCMD, NcdOffset_Command}, + {MIRRORCMD, MirrorOffset_Command}, + {ERRCMD, ERROR_Command}, +}; + +BOOL ConstructNandfirmFile(char * specFile) +{ + char *line; + char *line_top; + char *p; + int i; + + LineNum = 0; + Offset = 0x00000000; + + line = specFile++; + + while (*line != '\0') + { + LineNum++; + + // Get command line + line_top = line; + while (*line != '\0') + { + if (*line++ == '\n') + { + break; + } + } + + // Print for debug + debug_printf("NANDSF Line%4d [", LineNum, line); + for (p = line_top; p != line; p++) + { + if (isprint(*p)) + { + debug_printf("%c", *p); + } + } + debug_printf("]\n"); + + if (*line_top == '#') + { + } + else + { + for (i = 0; i < (sizeof(command) / sizeof(command[0])); i++) + { + if (!strncmp(line_top, command[i].string, strlen(command[i].string))) + { + if (command[i].funcp != NULL) + { + char line_cmd[FILENAME_MAX]; + char line_scan[FILENAME_MAX]; + char* line_conv; + int num; + + num = sscanf( line_top, + "%1024[^ :] : %1024[^ \x0d:#\n]", + line_cmd, line_scan + ); + line_conv = ResolveDefVal(line_scan); + + debug_printf("line_cmd = %s, line_conv = %s\n", line_cmd, line_conv); + + if (!command[i].funcp(line_conv, num - 1)) + return FALSE; + } + } + } + } + + } + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - 'WramRegs' Command +//--------------------------------------------------------------------------- + +extern MIHeader_WramRegs wram_regs_init; +MIHeader_WramRegs* wram_regs; + +static BOOL WramRegs_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("wram regs file = %s\n", line); + + return ReadWramRegFile(line); +} + +static BOOL ReadWramRegFile(const char *fileName) +{ + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &wram_regs, READ_ALL)) < 0) + return FALSE; + + nandHeader.o.h.w = *wram_regs; + nandHeader.m.h.w = *wram_regs; + + return CheckResult(); +} + +//--------------------------------------------------------------------------- +// Output - 'RSAKEY' Command +//--------------------------------------------------------------------------- + +static BOOL RSAKEY_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("rsa key = %s\n", line); + + return ReadKeyFile(line); +} + +static BOOL ReadKeyFile(const char *fileName) +{ + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &keyFileBuf, READ_ALL)) < 0) + return FALSE; + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'OUTKEY' Command +//--------------------------------------------------------------------------- + +static BOOL OUTKEY_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("out key = %s\n", line); + + PubkeyFileName = line; + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'VERSION' Command +//--------------------------------------------------------------------------- + +static u8 ConvToBCD8(int x) +{ + u8 bcd = 0; + + x %= 100; + bcd |= (x / 10)<<4; + bcd |= (x % 10); + + return bcd; +} + +static BOOL VERSION_Command(char * line, int num) +{ + char scan[FILENAME_MAX]; + u64 version = -1; + + // rescan + num = sscanf( line, + "0x%1024[^\x0d\n]", + scan + ); + + if (num == 1) + { + // convert version info + version = strtoull(scan, NULL, 16); + } + else if (num == 0) + { + // generate version info + u8* ver8 = (u8*)&version; + time_t timer; + struct tm *t_st; + + time(&timer); + t_st = localtime(&timer); + + ver8[0] = ConvToBCD8(t_st->tm_min); + ver8[1] = ConvToBCD8(t_st->tm_hour); + ver8[2] = ConvToBCD8(t_st->tm_mday); + ver8[3] = ConvToBCD8(t_st->tm_mon+1); + ver8[4] = ConvToBCD8(t_st->tm_year); + ver8[5] = 0xff; + ver8[6] = 0xff; + ver8[7] = 0xff; + } + + debug_printf2("version = %08llx\n", version); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Decomp' Command +//--------------------------------------------------------------------------- + +static BOOL Decomp_Command(char * line, int num) +{ + char* dbg_str = "ARM7"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "ARM9")) + { + nandHeader.o.l.arm9_decomp = TRUE; + nandHeader.m.l.arm9_decomp = TRUE; + dbg_str = "ARM9"; + } + + debug_printf2("decompress processor = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'ARM9_X2' Command +//--------------------------------------------------------------------------- + +static BOOL ARM9X2_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "TRUE")) + { + nandHeader.o.l.arm9_x2 = TRUE; + nandHeader.m.l.arm9_x2 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm9 x2 = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Comp9' Command +//--------------------------------------------------------------------------- + +static BOOL Comp9_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + compArm9 = FALSE; + + if (!strcmp(line, "TRUE")) + { + nandHeader.o.l.comp_arm9_boot_area = TRUE; + nandHeader.m.l.comp_arm9_boot_area = TRUE; + compArm9 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm9 compress = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Comp7' Command +//--------------------------------------------------------------------------- + +static BOOL Comp7_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + compArm7 = FALSE; + + if (!strcmp(line, "TRUE")) + { + nandHeader.o.l.comp_arm7_boot_area = TRUE; + nandHeader.m.l.comp_arm7_boot_area = TRUE; + compArm7 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm7 compress = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Elf9' Command +//--------------------------------------------------------------------------- + +static BOOL Elf9_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm9 elf = %s\n", line); + + { + s32 ramAddr = GetRamAddr(line); + nandHeader.o.l.main_ram_address = (void*)ramAddr; + nandHeader.m.l.main_ram_address = (void*)ramAddr; + } + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Elf7' Command +//--------------------------------------------------------------------------- + +static BOOL Elf7_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm7 elf = %s\n", line); + + { + s32 ramAddr = GetRamAddr(line); + nandHeader.o.l.sub_ram_address = (void*)ramAddr; + nandHeader.m.l.sub_ram_address = (void*)ramAddr; + } + + return CheckResult(); +} + + +static s32 GetRamAddr(const char *fileName) +{ + Elf32_Ehdr *ehdr; + s32 ramAddr; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &ehdr, sizeof(Elf32_Ehdr))) < 0) + return FALSE; + + ramAddr = ehdr->e_entry; + + Free(&ehdr); + + debug_printf2("ramaddr = 0x%08x\n", ramAddr); + + return ramAddr; +} + + +//--------------------------------------------------------------------------- +// Output - 'Sbin9' Command +//--------------------------------------------------------------------------- + +static BOOL Sbin9_Command(char * line, int num) +{ + FIRMSignedContext* sc = &signedContext; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm9 sbin = %s\n", line); + + // Set ARM9 ROM Offset + if (!Offset) + { + Offset = (sizeof(NANDHeader) + FIRM_ALIGN_MASK) & ~FIRM_ALIGN_MASK; + if (mirrorOfs) + { + Offset += sizeof(NANDHeaderCore) * 2; + } + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + nandHeader.o.l.main_rom_offset = Offset; + nandHeader.m.l.main_rom_offset = Offset + mirrorOfs - sizeof(NANDHeaderCore) * 2; + } + + return ReadSbinFile(line, &nandHeader.o.l.main_rom_offset, &nandHeader.m.l.main_rom_offset, &sc->hash[FIRM_SIGNED_HASH_IDX_ARM9], compArm9); +} + +//--------------------------------------------------------------------------- +// Output - 'Sbin7' Command +//--------------------------------------------------------------------------- + +static BOOL Sbin7_Command(char * line, int num) +{ + FIRMSignedContext* sc = &signedContext; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm7 sbin = %s\n", line); + + // Set ARM7 ROM Offset + if (!Offset) + { + Offset = (sizeof(NANDHeader) + FIRM_ALIGN_MASK) & ~FIRM_ALIGN_MASK; + if (mirrorOfs) + { + Offset += sizeof(NANDHeaderCore) * 2; + } + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + nandHeader.o.l.sub_rom_offset = Offset; + nandHeader.m.l.sub_rom_offset = Offset + mirrorOfs - sizeof(NANDHeaderCore) * 2; + } + + return ReadSbinFile(line, &nandHeader.o.l.sub_rom_offset, &nandHeader.m.l.sub_rom_offset, &sc->hash[FIRM_SIGNED_HASH_IDX_ARM7], compArm7); +} + + +static BOOL ReadSbinFile(const char *fileName, void* minfo, void* minfo2, void* hash, BOOL comp) +{ + const NANDHeader_ModuleInfo *m = minfo; + u32 *size = (void*)&m->size; + u32 *orig_size = (void*)&m->decomp_size; + const NANDHeader_ModuleInfo *m2 = minfo2; + u32 *size2 = (void*)&m2->size; + u32 *orig_size2 = (void*)&m2->decomp_size; + char *buffer; + char *file; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &file, READ_ALL)) < 0) + return FALSE; + + *orig_size = *orig_size2 = file_size; + + // Digest file image + if (hash) + { + ACSign_DigestUnit(hash, file, file_size); + } + + // Compress file image with fitting region + buffer = Alloc(file_size * 2); + if ( comp ) + { + file_size = LZCompWrite(file, file_size, buffer, FIRM_ALIGN); + } + else + { + memcpy(&buffer[0], file, file_size); + { + u32 pad_size = (FIRM_ALIGN - (file_size % FIRM_ALIGN)) % FIRM_ALIGN; + if (pad_size) + memset(&buffer[file_size], 0, pad_size); + file_size += pad_size; + } + } + Free(&file); + file = buffer; + + if (size) + { + *size = *size2 = file_size; + } + Offset += file_size; + + // Encrypt file image + EncryptBuffer(file, file_size); + + // Output file image with fitting region + PutBuffer(file, file_size); + + Free(&file); + + if (mirrorOfs && mirrorOfs < Offset + sizeof(NANDHeaderCore) * 2) + { + error("mirrorOfs is too small (%ld < %ld).\n", mirrorOfs, Offset + sizeof(NANDHeaderCore) * 2); + return FALSE; + } + + return CheckResult(); +} + +typedef struct +{ + unsigned long e[4]; +} u128; + +static BOOL EncryptBuffer(char *buffer, int length) +{ + const u128 id = {{ AES_IDS_ID2_A, AES_IDS_ID2_B, AES_IDS_ID2_C, AES_IDS_ID2_D }}; + u128 iv = {{ length, -length, ~length, 0 }}; + FIRMSignedContext* sc = &signedContext; + char *buffer2 = Alloc(length); + AES_KEY key; + if (!buffer2) + return FALSE; + AES_SetKey(&key, sc->aes_key, (unsigned char*)&id); + AES_Ctr(&key, buffer2, buffer, length, (unsigned char*)&iv); + memcpy(buffer, buffer2, length); + memset(buffer2, 0, length); + Free(buffer2); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - 'ENC_KEYINFO' Command +//--------------------------------------------------------------------------- + +static BOOL ENCKEY_Command(char * line, int num) +{ + u32 key; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + key = strtoul(line, NULL, 0); + nandHeader.g.d.ds_key = key; + + debug_printf2("keyinfo = %#x\n", key); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'NcdOffset' Command +//--------------------------------------------------------------------------- + +static BOOL NcdOffset_Command(char * line, int num) +{ + u32 ofs; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + ofs = strtoul(line, NULL, 0); + { + nandHeader.g.d.ncd_romAdr = ConvertHeaderRomOffsetAlign(ofs, 8); + } + + debug_printf2("ncd romoffset = %#x\n", ofs); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'MirrorOffset' Command +//--------------------------------------------------------------------------- + +static BOOL MirrorOffset_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + mirrorOfs = strtoul(line, NULL, 0); + + debug_printf2("mirrored image offset = %#x\n", mirrorOfs); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'ERROR' Command +//--------------------------------------------------------------------------- +static char* error_type[] = +{ + "SIGN", + "HEADER_HASH", + "ARM9_HASH", + "ARM7_HASH", + "HASH_TABLE_HASH", + "FINAL_HASH", + "HEADER_FOOTER", +}; + +static BOOL ERROR_Command(char * line, int num) +{ + char* dbg_str = "UNKNOWN"; + int i; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + for (i=0; ihash[FIRM_SIGNED_HASH_IDX_HEADER][0] ^= 1; + } + if ( errFlags.e.arm9_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_ARM9][0] ^= 1; + } + if ( errFlags.e.arm7_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_ARM7][0] ^= 1; + } + if ( errFlags.e.hash_table_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_HASH_TABLE][0] ^= 1; + } +} + +static void SetFinalHashError(FIRMSignedContext* sc) +{ + if ( errFlags.e.final_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_FINAL][0] ^= 1; + } +} + +static void SetSignError(NANDHeader* nh) +{ + if ( errFlags.e.sign ) + { + nh->sign.raw[0] ^= 1; + } + +} + +static void SetFooterError(NANDHeader* nh) +{ + if ( errFlags.e.header_footer ) + { + nh->h.reserved_footer[sizeof(nh->h.reserved_footer)-1] ^= 1; + } + +} + +//--------------------------------------------------------------------------- +// Output - Initialize AES Key +//--------------------------------------------------------------------------- +static BOOL InitializeAesKey(void) +{ + FIRMSignedContext* sc = &signedContext; + struct stat specstat; + time_t spectime; + if (stat(specFileName, &specstat) != 0) + return FALSE; + time(&spectime); + memcpy(&sc->aes_key[0], &specstat.st_atime, 4); + memcpy(&sc->aes_key[4], &specstat.st_mtime, 4); + memcpy(&sc->aes_key[8], &specstat.st_ctime, 4); + memcpy(&sc->aes_key[12], &spectime, 4); + ACSign_GetKey(sc->aes_key, sizeof(sc->aes_key), sc->aes_key, sizeof(sc->aes_key)); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - Initialize Nandfirm File +//--------------------------------------------------------------------------- + +static BOOL InitializeNandfirmFile(void) +{ + memset(&signedContext.hash[FIRM_SIGNED_HASH_IDX_HASH_TABLE], 0xff, sizeof(signedContext.hash[0])); + nandHeader.o.h.w = wram_regs_init; + nandHeader.m.h.w = wram_regs_init; + InitializeAesKey(); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - Finalize Nandfirm File +//--------------------------------------------------------------------------- + +static void FinalizeNandfirmFileCore(NANDHeaderCore* master) +{ + NANDHeader *nh = &nandHeader.g; + FIRMSignedContext* sc = &signedContext; + u8* key = keyFileBuf; + + memcpy(&nh->l, &master->l, sizeof(NANDHeaderLow)); + memcpy(&nh->h, &master->h, sizeof(NANDHeaderHigh)); + + ACSign_DigestHeader(&sc->hash[FIRM_SIGNED_HASH_IDX_HEADER], nh); + + SetUnitHashErrors(sc); + + ACSign_DigestUnit(&sc->hash[FIRM_SIGNED_HASH_IDX_FINAL], sc, FIRM_HEADER_2ND_HASH_AREA_LEN); + + SetFinalHashError(sc); + + if (key) + { + ACSign_Final(nh, sc, key); + } + + SetFooterError(nh); + + SetSignError(nh); + + memcpy(&master->sign, &nh->sign, sizeof(FIRMPaddedSign)); +} + +static BOOL FinalizeNandfirmFile(const char *nandFile) +{ + // for m header (copy to g) + FinalizeNandfirmFileCore(&nandHeader.m); + + // for o header (copy to g) + FinalizeNandfirmFileCore(&nandHeader.o); + + // Output file image + SeekFile(0L); + if (mirrorOfs) + { + PutBuffer(&nandHeader, sizeof(nandHeader)); + } + else + { + PutBuffer(&nandHeader.g, sizeof(nandHeader.g)); + } + + // Output public key (modulus) + if (PubkeyFileName) + { + WriteFile(PubkeyFileName, &keyFileBuf[ACS_RSA_PRVMOD_OFFSET], ACS_RSA_PRVMOD_LEN); + } + + return TRUE; +} diff --git a/build/tools/makenandfirm/path.c b/build/tools/makenandfirm/path.c new file mode 100644 index 0000000..eeeb989 --- /dev/null +++ b/build/tools/makenandfirm/path.c @@ -0,0 +1,931 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makebanner + File: path.c + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: path.c,v $ + Revision 1.3 2006/01/18 02:11:20 kitase_hirotake + do-indent + + Revision 1.2 2005/02/28 05:26:13 yosizaki + do-indent. + + Revision 1.1 2004/08/30 08:41:14 yasu + makebanner moves into CVS tree + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include // free() +#include // strcasecmp() +#include // stat() +#include // opendir()/readdir()/closedir() +#include // getcwd() +#ifdef __CYGWIN__ +#include // cygwin_conv_to_win32_path() +#endif +#include "path.h" + +//--------------------------------------------------------------------------- +// Get File Statue +//--------------------------------------------------------------------------- + +tFileStatus GetFileStatus(struct stat *s, const char *filename) +{ + // Get file status + if (stat(filename, s)) + { + error("Can't get status %s", filename); + return FILESTATUS_ERROR; + } + + if (S_ISREG(s->st_mode)) + { + return FILESTATUS_FILE; + } + else if (S_ISDIR(s->st_mode)) + { + return FILESTATUS_DIR; + } + + error("Unknown file type %s", filename); + return FILESTATUS_ERROR; +} + + +//--------------------------------------------------------------------------- +// File Globbing & Dir Listing +//--------------------------------------------------------------------------- + +typedef struct +{ + tCallBack callBack; + void *param; + tWildCard *accept; + tWildCard *reject; + +} +tForeachEntryParam; + + +static BOOL isAcceptEntryName(char *pathName, tWildCard * accept, tWildCard * reject) +{ + char *p = pathName; + + while (*p) + { + if (*p == '/') + pathName = p + 1; + p++; + } + + if (accept) + { + while (accept) + { + if (WildCardCmp(accept->name, pathName)) + { + goto accepted; + } + accept = accept->next; + } + return FALSE; + } + accepted: + + while (reject) + { + if (WildCardCmp(reject->name, pathName)) + { + return FALSE; + } + reject = reject->next; + } + return TRUE; +} + + +static BOOL ForeachEntry_CallBack(char *pathName, void *param) +{ + tForeachEntryParam *t = (tForeachEntryParam *) param; + struct stat fstat; + + if (!isAcceptEntryName(pathName, t->accept, t->reject)) + { + // Reject!!! ignored + return TRUE; + } + + switch (GetFileStatus(&fstat, pathName)) + { + case FILESTATUS_FILE: + return t->callBack(pathName, t->param); + + case FILESTATUS_DIR: + return ForeachDirList(pathName, ForeachEntry_CallBack, param); + + default: + break; + } + return FALSE; +} + + +BOOL ForeachEntry(const char *pathName, tWildCard * reject, tCallBack callBack, void *param) +{ + tForeachEntryParam t; + + t.callBack = callBack; + t.param = param; + t.accept = NULL; + t.reject = reject; + + return ForeachPathGlobbing(pathName, ForeachEntry_CallBack, &t); +} + + +typedef struct +{ + tCallBack callBack; + void *param; + char *baseName; + +} +tForeachFileParam; + + +static BOOL ForeachFile_CallBack(char *pathName, void *param) +{ + tForeachFileParam *t = (tForeachFileParam *) param; + + int len = strlen(t->baseName); + + debug_printf(" ForeachFile_CallBack path[%s] base[%s]\n", pathName, t->baseName); + + if (strncmp(pathName, t->baseName, len)) + { + error("Wildcard in Root is not supported"); + return FALSE; + } + + return t->callBack(pathName + len, t->param); +} + + +BOOL ForeachFile(const char *baseName, const char *fileName, tWildCard * reject, tCallBack callBack, + void *param) +{ + char *cBaseName; + char *cPathName; + BOOL state; + tForeachFileParam t; + + debug_printf("ForeachFile : baseName[%s] fileName[%s]\n", baseName, fileName); + + cBaseName = GetSrcPath(baseName, ""); + cPathName = GetSrcPath(baseName, fileName); + + debug_printf("ForeachFile : cBaseName[%s] cPathName[%s]\n", cBaseName, cPathName); + + t.callBack = callBack; + t.param = param; + t.baseName = cBaseName; + + state = ForeachEntry(cPathName, reject, ForeachFile_CallBack, &t); + + free(cBaseName); + free(cPathName); + + return state; +} + + +//--------------------------------------------------------------------------- +// FilePath Globbing +//--------------------------------------------------------------------------- + +typedef struct +{ + char *baseName; + char *pathName; + tCallBack callBack; + void *param; + +} +tGlobParam; + + +static int CountFile; +static BOOL ForeachPathGlobbing_Entry(tGlobParam * pg); +static BOOL ForeachPathGlobbing_WildCard(char *pathName, void *param); + +BOOL ForeachPathGlobbing(const char *pathName, tCallBack callBack, void *param) +{ + tGlobParam g; + BOOL ret; + + g.baseName = NULL; + g.pathName = PathNormalize(pathName, TRUE); + g.callBack = callBack; + g.param = param; + CountFile = 0; + + debug_printf("PathGlobbing : Name [%s]->[%s]\n", pathName, g.pathName); + + ret = ForeachPathGlobbing_Entry(&g); + + free(g.pathName); + + if (ret && CountFile == 0) + { + error("No file or directory matched %s", pathName); + return FALSE; + } + return ret; +} + + +static BOOL ForeachPathGlobbing_Entry(tGlobParam * pg) +{ + tGlobParam g; + char *entryName; + struct stat s; + BOOL state; + + if (pg->pathName) + { + entryName = PathDup(pg->pathName); + + g = *pg; + g.pathName = PathGetDirLevelDown(pg->pathName); + + if (pg->baseName) + { + g.baseName = Alloc(strlen(pg->baseName) + strlen(entryName) + 2); + sprintf(g.baseName, "%s/%s", pg->baseName, entryName); + } + else + { + g.baseName = strdup(entryName); + } + + // Check if wildcard ? + if (isPathWildCard(entryName)) + { + state = ForeachDirList(pg->baseName, ForeachPathGlobbing_WildCard, &g); + } + else + { + state = ForeachPathGlobbing_Entry(&g); + } + + Free(&entryName); + Free(&g.baseName); + } + else + { + // Check if file exists + if (!stat(pg->baseName, &s)) + { + debug_printf(" File Found [%s]\n", pg->baseName); + + // Globbing done, exec callback + + state = pg->callBack(pg->baseName, pg->param); + CountFile++; + } + else + { + debug_printf(" File Not Found [%s]\n", pg->baseName); + state = TRUE; // Ignored + } + } + return state; +} + + +static BOOL ForeachPathGlobbing_WildCard(char *pathName, void *param) +{ + tGlobParam g; + tGlobParam *pg = (tGlobParam *) param; + + debug_printf(" WildCardCmp: [%s] [%s]\n", pg->baseName, pathName); + + if (WildCardCmp(pg->baseName, pathName)) + { + g = *pg; + g.baseName = pathName; + return ForeachPathGlobbing_Entry(&g); + } + + return TRUE; // Ignored +} + + +//--------------------------------------------------------------------------- +// Directory Listing +// Listing directory & Exec CallBack +//--------------------------------------------------------------------------- + +BOOL ForeachDirList(const char *dirName, tCallBack callBack, void *param) +{ + DIR *dir; + struct dirent *entry; + char *pathName; + BOOL state = TRUE; + + if (!dirName) + { + dirName = "."; + } + + debug_printf("DirectoryList: Name [%s]\n", dirName); + + // Open directory + if (NULL == (dir = opendir(dirName))) + { + error("Can't read directory %s", dirName); + return FALSE; + } + + // Store new files + while (NULL != (entry = readdir(dir))) + { + pathName = entry->d_name; + + if (!strcmp(pathName, ".") || !strcmp(pathName, "..")) + { + continue; + } + + debug_printf(" :%s\n", pathName); + pathName = GetSrcPath(dirName, pathName); + state = callBack(pathName, param); + free(pathName); + + if (!state) + break; + } + + closedir(dir); + return state; +} + + +//--------------------------------------------------------------------------- +// +// PathName Utilities +// +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// StrCmp/StrCpy entry name terminated / or \0 +//--------------------------------------------------------------------------- + +int PathCmp(const char *path, const char *cmp) +{ + char c; + + do + { + c = *path; + if (c == '/') + c = '\0'; // end of string if '/' + if (c != *cmp) + return 1; + path++; + cmp++; + } + while (c); + + return 0; +} + + +char *PathCpy(char *dest, const char *src) +{ + while (*src != '\0' && *src != '/') + { + *dest++ = *src++; + } + return dest; // Don't set '\0' +} + + +int PathLen(const char *path) +{ + int n = 0; + + while (*path != '\0' && *path != '/') + { + n++; + path++; + } + return n; +} + + +char *PathDup(const char *src) +{ + int n = PathLen(src); + char *dest = Alloc(n + 2); + + PathCpy(dest, src); + dest[n] = '\0'; + + return dest; +} + + +BOOL WildCardCmp(const char *wildcard, const char *path) +{ + if (*wildcard == '*') + { + if (*path != '\0' && WildCardCmp(wildcard, path + 1)) + return TRUE; + if (WildCardCmp(wildcard + 1, path)) + return TRUE; + } + + else if (*wildcard == '?') + { + return *path != '\0' && WildCardCmp(wildcard + 1, path + 1); + } + + else if (*wildcard == *path) + { + return *path == '\0' || WildCardCmp(wildcard + 1, path + 1); + } + + return FALSE; +} + + +BOOL isPathWildCard(const char *path) +{ + while (*path != '\0' && *path != '/') + { + if (*path == '*' || *path == '?') + { + return TRUE; + } + path++; + } + return FALSE; +} + + +//--------------------------------------------------------------------------- +// Go up/down directory level +//--------------------------------------------------------------------------- + +char *PathGetDirLevelDown(const char *path) +{ + while (*path) + { + if (*path == '/') + return (char *)path + 1; + path++; + } + return NULL; +} + + +//--------------------------------------------------------------------------- +// Get Basename +//--------------------------------------------------------------------------- + +char *GetBaseName(const char *path) +{ + int i; + char *new_path; + + for (i = strlen(path) - 1; i >= 0; i--) + { + if (path[i] == '/') + { + new_path = strdup(path); + new_path[i] = '\0'; + return new_path; + } + if (path[i] == ':') + { + new_path = Alloc(i + 3); + strncpy(new_path, path, i); + strcpy(new_path + i, ":."); + return new_path; + } + } + + new_path = strdup("."); + return new_path; +} + + +//--------------------------------------------------------------------------- +// Get Filename +//--------------------------------------------------------------------------- + +char *GetFileName(const char *path) +{ + int i; + char *new_file; + + for (i = strlen(path) - 1; i >= 0; i--) + { + if (path[i] == '/' || path[i] == ':') + { + new_file = strdup(path + i + 1); + return new_file; + } + } + new_file = strdup(path); + return new_file; +} + + +//--------------------------------------------------------------------------- +// Reconstruct path name +// +// - Resolve '.' or '..' in path name +// - Work around . and / to translate regular form +// +// Regular form of path: +// Absolute Path [Drive:]/.[/Entry...] +// Relative Path [Drive:].[/Entry]... +// +// ex) +// abc/def -> ./abc/def +// /aaa -> /./aaa +// D:/aaa -> D:/./aaa +// / -> /. +// . -> . +// ../aa -> ./../aa +//--------------------------------------------------------------------------- + +char *PathNormalize(const char *pathName, BOOL isTreatDotDot) +{ + int i, level, level_root, n; + BOOL isAbsolute; + const char *entry[DIRLEVEL_MAX]; + + char *pathNormal = Alloc(strlen(pathName) + 4); + const char *p_org; + char *p_new; + + // + // Check if drive letter C: D: E: + // Check if absolute path + // + p_new = pathNormal; + p_org = SkipDriveName(pathName); + n = (int)p_org - (int)pathName; + + if (n > 0) + { + strncpy(p_new, pathName, n); + p_new += n; + } + isAbsolute = isAbsolutePath(p_org); + + // + // Resolve '.' and '..' + // + // Slice the path at point of / , put them into entry[] + // + + level = level_root = 0; + + for (; p_org; p_org = PathGetDirLevelDown(p_org)) + { + if (!PathCmp(p_org, "") || !PathCmp(p_org, ".")) + { + // skip it + continue; + } + else if (!PathCmp(p_org, "..") && isTreatDotDot) + { + if (level > level_root) + { + // Back to parent dir + level--; + continue; + } + + // if pathname starts with '/', no directory to go up + if (isAbsolute) + { + error("Can't go up directory, '..' Ignored. %s", pathName); + continue; + } + + // keep '..' + level_root = level + 1; + } + + // name entry + entry[level] = p_org; + level++; + } + + // Reconstruct pathname + if (isAbsolute) + { + *p_new++ = '/'; + } + *p_new++ = '.'; + + for (i = 0; i < level; i++) + { + *p_new++ = '/'; + p_new = PathCpy(p_new, entry[i]); + } + *p_new = '\0'; + +#if 0 + if (strcmp(pathNormal, pathName)) + { + debug_printf(" PathNormal: [%s] -> [%s]\n", pathName, pathNormal); + } +#endif + return pathNormal; +} + + +//--------------------------------------------------------------------------- +// Get Src Path +// Normalize BASENAME +// Normalize FILENAME +// Concat both +//--------------------------------------------------------------------------- + +char *GetSrcPath(const char *baseName, const char *fileName) +{ + char *base; + char *file; + char *t; + char *path; + + base = PathNormalize(baseName, TRUE); + file = PathNormalize(fileName, TRUE); + t = Alloc(strlen(base) + strlen(file) + 2); + + // Concat base + '/' + file + sprintf(t, "%s/%s", base, file); + path = PathNormalize(t, FALSE); + + free(base); + free(file); + free(t); + + debug_printf(" GetSrcPath: [%s]\n", path); + return path; +} + + +//--------------------------------------------------------------------------- +// Get Dest Path +// Concat BASENAME + FILENAME +// Normalize it +//--------------------------------------------------------------------------- + +char *GetDestPath(const char *baseName, const char *fileName) +{ + char *t; + char *path; + + t = Alloc(strlen(baseName) + strlen(fileName) + 2); + + // Concat base + '/' + file + sprintf(t, "%s/%s", baseName, fileName); + path = PathNormalize(t, TRUE); + + free(t); + + debug_printf(" GetDestPath: [%s]\n", path); + return path; +} + + +//--------------------------------------------------------------------------- +// Remake the path into familier shape +// Delete ./ +//--------------------------------------------------------------------------- + +char *PathDenormalize(char *path) +{ + char *p; + + p = (char *)SkipDriveName(path); + if (*p == '/') + { + p++; + } + + // Cut './' + if (*p == '.' && *(p + 1) == '/') + { + while ('\0' != (*p = *(p + 2))) + { + p++; + } + + if (p == path) + { + + } + } + + + + return path; +} + + +//--------------------------------------------------------------------------- +// Get PC Path +//--------------------------------------------------------------------------- + +char *GetWin32Path(char *cygpath) +{ + static char buffer[FILENAME_MAX]; + +#ifdef __CYGWIN__ + if (*cygpath == '/') + { + cygwin_conv_to_win32_path(cygpath, buffer); + } + else +#endif + { + strcpy(buffer, cygpath); + } + + return ChangeBackSlash(buffer); +} + +char *ChangeWin32Path(char *cygpath) +{ + char *win32path = strdup(GetWin32Path(cygpath)); + + free(cygpath); + return win32path; +} + +//--------------------------------------------------------------------------- +// Change suffix +//--------------------------------------------------------------------------- +char *ChangeSuffix(const char *file, const char *suffix) +{ + int i, n; + char *path; + + n = strlen(file); + + for (i = n; file[i] != '.'; i--) + { + if (file[i] == '/' || i == 0) + { + i = n; + break; + } + } + + path = Alloc(i + strlen(suffix) + 1); + strncpy(path, file, i); + strcpy(path + i, suffix); + + return path; +} + + +//--------------------------------------------------------------------------- +// Get Current Dir +//--------------------------------------------------------------------------- + +char *GetCurrentDirectory(void) +{ + static char buffer[FILENAME_MAX]; + char *cwd; + + cwd = getcwd(buffer, FILENAME_MAX); + if (!cwd) + { + error("Can't access current directory"); + exit(10); + } + return cwd; +} + + +//--------------------------------------------------------------------------- +// Check if absolute path +// +// Return True in case of ... +// +// /dirA/dirB/fileC +// D:/dirA/dirB/fileC +// +// Return False in case of ... +// +// dirX/dirY/fileZ +// D:dirX/dirY/fileZ +//--------------------------------------------------------------------------- + +BOOL isAbsolutePath(const char *path) +{ + const char *p = path; + + while (*p != '\0') + { + if (*p == '/' || *p == '\\') + { + if (p == path || p[-1] == ':') + { + return TRUE; + } + } + p++; + } + return FALSE; +} + +//--------------------------------------------------------------------------- +// Check if drive name +// +// Return next character of ':' if drive name +// Return head of path if no drive name +//--------------------------------------------------------------------------- + +const char *SkipDriveName(const char *path) +{ + const char *p = path; + + while (*p != '\0' && *p != '/' && *p != '\\') + { + if (*p == ':') + { + return p + 1; + } + p++; + } + return path; +} + + +//--------------------------------------------------------------------------- +// App Name Utilities +//--------------------------------------------------------------------------- +static char *appName; +static char *appBaseName; +static char *appFileName; + +void InitAppName(const char *path) +{ + char *slash_path = ChangeBackSlash(strdup(path)); + + appBaseName = GetBaseName(slash_path); + appFileName = GetFileName(slash_path); + appName = ChangeSuffix(appFileName, ""); + + free(slash_path); +} + +char *GetAppName(void) +{ + return appName; +} + +char *GetAppBaseName(void) +{ + return appBaseName; +} + +char *GetAppFileName(void) +{ + return appFileName; +} + + +#ifdef TEST +int main(int argc, char *argv[]) +{ + int i; + char *s; + + for (i = 1; i < argc; i++) + { + s = PathNormalize(argv[i], TRUE); + printf("[%s] -> [%s]\n", argv[i], s); + free(s); + } + return 0; +} +#endif diff --git a/build/tools/makenandfirm/path.h b/build/tools/makenandfirm/path.h new file mode 100644 index 0000000..e9956dc --- /dev/null +++ b/build/tools/makenandfirm/path.h @@ -0,0 +1,93 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makebanner + File: path.h + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: path.h,v $ + Revision 1.3 2006/01/18 02:11:20 kitase_hirotake + do-indent + + Revision 1.2 2005/02/28 05:26:13 yosizaki + do-indent. + + Revision 1.1 2004/08/30 08:41:14 yasu + makebanner moves into CVS tree + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef PATH_H_ +#define PATH_H_ + +#include // struct tat +#include "misc.h" + +#define DIRLEVEL_MAX 256 +#ifndef FILENAME_MAX +#define FILENAME_MAX 1024 +#endif + +typedef enum +{ + FILESTATUS_ERROR = -1, + FILESTATUS_FILE = 0, + FILESTATUS_DIR = 1 +} +tFileStatus; + + +// Item Reject Control + +typedef struct tWildCard +{ + struct tWildCard *next; + char *name; + +} +tWildCard; + + +// CallBacks + +typedef BOOL (*tCallBack) (char *, void *); + + +// Prototypes + +tFileStatus GetFileStatus(struct stat *s, const char *filename); +BOOL ForeachEntry(const char *pathName, tWildCard * reject, tCallBack callBack, void *param); +BOOL ForeachFile(const char *baseName, const char *fileName, tWildCard * reject, + tCallBack callBack, void *param); +BOOL ForeachPathGlobbing(const char *pathName, tCallBack callBack, void *param); +BOOL ForeachDirList(const char *dirName, tCallBack callBack, void *param); +int PathCmp(const char *path, const char *cmp); +char *PathCpy(char *dest, const char *src); +int PathLen(const char *path); +char *PathDup(const char *src); +char *PathGetDirLevelDown(const char *path); +char *GetBaseName(const char *path); +char *GetFileName(const char *path); +BOOL WildCardCmp(const char *wildcard, const char *path); +BOOL isPathWildCard(const char *path); +char *PathNormalize(const char *pathName, BOOL isTreatDotDot); +char *PathDenormalize(char *path); +char *GetSrcPath(const char *base, const char *file); +char *GetDestPath(const char *base, const char *file); +char *GetWin32Path(char *cygpath); +char *ChangeWin32Path(char *cygpath); +char *ChangeSuffix(const char *file, const char *suffix); +char *GetCurrentDirectory(void); +BOOL isAbsolutePath(const char *path); +const char *SkipDriveName(const char *path); +void InitAppName(const char *path); +char *GetAppName(void); +char *GetAppBaseName(void); +char *GetAppFileName(void); + +#endif //PATH_H_ diff --git a/build/tools/makenandfirm/test/Makefile b/build/tools/makenandfirm/test/Makefile new file mode 100644 index 0000000..7ed8894 --- /dev/null +++ b/build/tools/makenandfirm/test/Makefile @@ -0,0 +1,56 @@ +#! make -f +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makenandfirm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- + +SUBDIRS = wram_rbin \ + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +MAKENANDFIRM = ../makenandfirm.exe + +MAKEFIRM_ARM9 = ./twl_nandfirm9_print.axf +MAKEFIRM_ARM7 = ./twl_nandfirm7_print.axf +SDEPENDS_BIN += $(MAKEFIRM_ARM9) $(MAKEFIRM_ARM7) +MAKEFIRM_FLAGS += -d +MAKEFIRM_DEFS += -DFIRM_ROOT='$(FIRM_ROOT)' \ + -DMAKEFIRM_ARM9='$(basename $(MAKEFIRM_ARM9))' \ + -DMAKEFIRM_ARM7='$(basename $(MAKEFIRM_ARM7))' \ + -DMAKEFIRM_RSA_PRVKEY='$(MAKEFIRM_RSA_PRVKEY)' \ + +TARGET = test.srl + +%.srl: %.nandsf $(MAKENANDFIRM) + $(MAKENANDFIRM) $(MAKEFIRM_FLAGS) $(MAKEFIRM_DEFS) $< $@ + +.PHONY: build install do-autotest clean clobber + +define ECHO_CURDIR + echo "==== $(CURDIR)"; +endef + +build: + @$(ECHO_CURDIR) + @$(MAKE) $(TARGET) + +install do-autotest: + @$(ECHO_CURDIR) + +clean clobber super-clobber: + @$(ECHO_CURDIR) + -rm -f $(TARGET) *~ + +test-utf16.bsf: icon.nbfc icon.nbfp diff --git a/build/tools/makenandfirm/test/rsa_private.der b/build/tools/makenandfirm/test/rsa_private.der new file mode 100644 index 0000000..06f5f4c Binary files /dev/null and b/build/tools/makenandfirm/test/rsa_private.der differ diff --git a/build/tools/makenandfirm/test/test.nandsf b/build/tools/makenandfirm/test/test.nandsf new file mode 100644 index 0000000..545d66c --- /dev/null +++ b/build/tools/makenandfirm/test/test.nandsf @@ -0,0 +1,28 @@ +#NANDSF --- Nandfirm Spec File + +VERSION : 0x0 # GENERATE + +RSA_KEY : rsa_private.der +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ./wram_rbin/wram_regs.rbin + +DECOMP_PROC : ARM9 # ARM9 or ARM7 + +MIRROR_OFS : 0xc000 # 0x8000 is too small + +ARM9_COMP : TRUE # TRUE or FALSE, should be before ARM9_SBIN +ARM9_SBIN : $(MAKEFIRM_ARM9).sbin +ARM9_ELF : $(MAKEFIRM_ARM9).axf + +ARM7_COMP : FALSE # TRUE or FALSE, should be before ARM7_SBIN +ARM7_SBIN : $(MAKEFIRM_ARM7).sbin +ARM7_ELF : $(MAKEFIRM_ARM7).axf + +ARM9_X2 : TRUE # TRUE or FALSE + +ENC_KEYINFO : 0x5043414d # 'MACP' +NCD_ROMOFS : 0x07fe00 + +ERROR : ARM7_HASH # SIGN, HEADER_HASH, ARM9_HASH, ARM7_HASH, HASH_TABLE_HASH or FINAL_HASH +ERROR : HEADER_FOOTER # for debug diff --git a/build/tools/makenandfirm/test/twl_nandfirm7_print.axf b/build/tools/makenandfirm/test/twl_nandfirm7_print.axf new file mode 100644 index 0000000..b255bd2 Binary files /dev/null and b/build/tools/makenandfirm/test/twl_nandfirm7_print.axf differ diff --git a/build/tools/makenandfirm/test/twl_nandfirm7_print.sbin b/build/tools/makenandfirm/test/twl_nandfirm7_print.sbin new file mode 100644 index 0000000..a4eeebc Binary files /dev/null and b/build/tools/makenandfirm/test/twl_nandfirm7_print.sbin differ diff --git a/build/tools/makenandfirm/test/twl_nandfirm9_print.axf b/build/tools/makenandfirm/test/twl_nandfirm9_print.axf new file mode 100644 index 0000000..3d064b3 Binary files /dev/null and b/build/tools/makenandfirm/test/twl_nandfirm9_print.axf differ diff --git a/build/tools/makenandfirm/test/twl_nandfirm9_print.sbin b/build/tools/makenandfirm/test/twl_nandfirm9_print.sbin new file mode 100644 index 0000000..cd305be Binary files /dev/null and b/build/tools/makenandfirm/test/twl_nandfirm9_print.sbin differ diff --git a/build/tools/makenandfirm/test/wram_rbin/Makefile b/build/tools/makenandfirm/test/wram_rbin/Makefile new file mode 100644 index 0000000..217e8b4 --- /dev/null +++ b/build/tools/makenandfirm/test/wram_rbin/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - nandfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = wram_regs.rbin + +SRCS = \ + wram_regs.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_DIR = . +INSTALL_TARGETS = $(BINDIR)/$(TARGET_BIN) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/tools/makenandfirm/test/wram_rbin/wram_regs.c b/build/tools/makenandfirm/test/wram_rbin/wram_regs.c new file mode 100644 index 0000000..88332ab --- /dev/null +++ b/build/tools/makenandfirm/test/wram_rbin/wram_regs.c @@ -0,0 +1,89 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +MIHeader_WramRegs wram_regs = +{ + // ARM9 + { + REG_WRAM_A_BNK_PACK(0, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_0KB, TRUE), + REG_WRAM_A_BNK_PACK(1, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_64KB, TRUE), + REG_WRAM_A_BNK_PACK(2, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_128KB, TRUE), + REG_WRAM_A_BNK_PACK(3, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_192KB, TRUE), + }, + { + REG_WRAM_B_BNK_PACK(0, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_0KB, TRUE), + REG_WRAM_B_BNK_PACK(1, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_32KB, TRUE), + REG_WRAM_B_BNK_PACK(2, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_64KB, TRUE), + REG_WRAM_B_BNK_PACK(3, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_96KB, TRUE), + REG_WRAM_B_BNK_PACK(4, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_128KB, TRUE), + REG_WRAM_B_BNK_PACK(5, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_160KB, TRUE), + REG_WRAM_B_BNK_PACK(6, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_192KB, TRUE), + REG_WRAM_B_BNK_PACK(7, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_224KB, TRUE), + }, + { + REG_WRAM_C_BNK_PACK(0, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_0KB, TRUE), + REG_WRAM_C_BNK_PACK(1, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_32KB, TRUE), + REG_WRAM_C_BNK_PACK(2, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_64KB, TRUE), + REG_WRAM_C_BNK_PACK(3, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_96KB, TRUE), + REG_WRAM_C_BNK_PACK(4, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_128KB, TRUE), + REG_WRAM_C_BNK_PACK(5, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_160KB, TRUE), + REG_WRAM_C_BNK_PACK(6, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_192KB, TRUE), + REG_WRAM_C_BNK_PACK(7, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_224KB, TRUE), + }, + REG_WRAM_A_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_A_IMG_128KB + ), + REG_WRAM_B_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_B_IMG_128KB + ), + REG_WRAM_C_MAP_PACK(HW_WRAM_AREA_HALF, + HW_WRAM_AREA_HALF + 0x00020000, + MI_WRAM_C_IMG_128KB + ), + + // ARM7 + REG_WRAM_A_MAP_PACK(HW_WRAM_AREA_HALF, + HW_WRAM_AREA_HALF + 0x00020000, + MI_WRAM_A_IMG_128KB + ), + REG_WRAM_B_MAP_PACK(HW_WRAM_AREA_HALF + 0x00020000, + HW_WRAM_AREA_HALF + 0x00040000, + MI_WRAM_B_IMG_128KB + ), + REG_WRAM_C_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_C_IMG_128KB + ), + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + MI_WRAM_ARM7_ALL, + + // VRAM-C + 7, + // VRAM-D + 7, +}; diff --git a/build/tools/makenandfirm/wram_regs.c b/build/tools/makenandfirm/wram_regs.c new file mode 100644 index 0000000..5f09a86 --- /dev/null +++ b/build/tools/makenandfirm/wram_regs.c @@ -0,0 +1,96 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenandfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include "format_rom.h" +//#define SDK_ASM +#define NITRO_TYPES_H_ +#include +#include +#include + + +MIHeader_WramRegs wram_regs_init = +{ + // ARM9 + { + REG_MI_MBK_A0_FIELD( 1, MI_WRAM_A_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A1_FIELD( 1, MI_WRAM_A_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A2_FIELD( 1, MI_WRAM_A_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_A3_FIELD( 1, MI_WRAM_A_OFFSET_192KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_B0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_C0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM9 ), + }, + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, HW_WRAM_AREA_HALF ) + ), + + // ARM7 + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, HW_WRAM_AREA_HALF ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00020000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, MI_WRAM_MAP_NULL ) + ), + + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + 3, + + // VRAM-C + 7, + // VRAM-D + 7, +}; + diff --git a/build/tools/makenorfirm/Makefile b/build/tools/makenorfirm/Makefile new file mode 100644 index 0000000..60b4ecd --- /dev/null +++ b/build/tools/makenorfirm/Makefile @@ -0,0 +1,151 @@ +#! make -f +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makenorfirm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- + +TARGET_PLATFORM = TWL + +SUPPORT_ECC = 0 + +ifeq ($(SUPPORT_ECC),1) +ECC_SRCDIR = ../../libraries/acsign_ecc/common \ + ../../libraries/acsign_ecc/common/algae/common/ecc \ + ../../libraries/acsign_ecc/common/algae/cmp \ + ../../libraries/acsign_ecc/common/algae/ecsource \ + +ECC_INCDIR = ../../libraries/acsign_ecc/include \ + ../../libraries/acsign_ecc/common/algae/include \ + ../../libraries/acsign_ecc/common/algae/common/include \ + +ECC_SRCS = acsign_ecc.c acsign_cryptoc.c \ + \ + cmparith.c cmpbits.c cmpcnv.c cmpdiv.c cmpmem.c \ + cmpmod.c cmpmuldv.c cmpspprt.c cmpsqr.c cmpvectr.c \ + computem.c ecfpatbl.c ecfpsmul.c \ + spcprime.c secfpcom.c \ + \ + p224v1.c p224v1a.c \ + +ECC_DEFS = -DRSA_PROTOTYPES=RSA_ENABLED \ + -DRCOM_BUILD=RSA_ENABLED -DRSA_FAST_INVERSE=RSA_ENABLED \ + -DRSA_STD_MEM_FUNCS=RSA_ENABLED -DRSA_STD_ALLOC_FUNCS=RSA_ENABLED \ +else +ECC_SRCDIR = +ECC_INCDIR = +ECC_SRCS = +ECC_DEFS = +endif + +SRCDIR += ../acsign $(ECC_SRCDIR) +INCDIR += ../acsign/include $(ECC_INCDIR) $(ECC_SRCDIR) + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +TARGETS = makenorfirm.exe + +SOURCES_C = makenorfirm.c \ + out_norfirm.c \ + misc.c \ + path.c \ + defval.c \ + compress.c \ + wram_regs.c \ + acsign.c \ + acsign_nor.c \ + aes2.c \ + $(ECC_SRCS) + +SOURCES = $(SORUCES_C) + +OBJECTS = $(SOURCES_C:.c=.o) + +HEADERS = format_nlist.h \ + makenorfirm.h \ + path.h \ + format_rom.h \ + misc.h \ + defval.h \ + compress.h \ + +MACROS += -DSMALL_CODE_SIZE \ + -DSTANDALONE \ + -DOPT_32_BIT \ + -DNO_SPLIT \ + -DNO_FP_API \ + -DNO_R_DIAG \ + $(ECC_DEFS) + +INSTALL_DIR = $(FIRM_INSTALL_TOOLSDIR)/bin +INSTALL_TARGETS = $(TARGETS) + +LDIRT_CLEAN = $(OBJECTS) $(TARGETS) version.h + + +VPATH = $(SRCDIR) +TWL_INCDIR := $(TWL_INCDIR) $(addprefix -I,$(INCDIR)) $(addprefix -I,$(FIRM_INCDIR)) + +include $(TWLSDK_ROOT)/build/buildtools/twl/modulerules.x86 + +#---------------------------------------------------------------------------- +# build +#---------------------------------------------------------------------------- +do-build: $(TARGETS) + +$(TARGETS): $(OBJECTS) + $(CC_X86) $+ -o $@ + +makenorfirm.o: makenorfirm.c makenorfirm.h format_rom.h path.h version.h +out_norfirm.o: out_norfirm.c misc.h format_rom.h format_nlist.h format_sign.h elf.h compress.h \ + $(FIRM_INCDIR)/firm/format/sign.h \ + $(FIRM_INCDIR)/firm/format/wram_regs.h \ + $(FIRM_INCDIR)/firm/format/norfirm.h \ + +misc.o: misc.c misc.h +path.o: path.c path.h +compress.o: compress.c compress.h +wram_regs.o: wram_regs.c +acsign.o: acsign.c ../acsign/include/acsign.h +acsign_nor.o: acsign_nor.c format_sign.h \ + $(FIRM_INCDIR)/firm/format/sign.h \ + $(FIRM_INCDIR)/firm/format/wram_regs.h \ + $(FIRM_INCDIR)/firm/format/norfirm.h \ + +aes2.o: aes2.c aes2.h + +$(FIRM_INCDIR)/firm/format/sign.h: +$(FIRM_INCDIR)/firm/format/wram_regs.h: +$(FIRM_INCDIR)/firm/format/norfirm.h: +format_nlist.h: +format_rom.h: +makenorfirm.h: +acsign.h: +acsign_nor.h: +path.h: + +# avoid to warning message +misc.o:WARNING += -Wno-format-y2k + +# + +version.h: $(SOURCES) $(HEADERS) + @for i in $^ ; \ + do \ + date -r $$i +'#define SDK_DATE_OF_LATEST_FILE %Y%m%dUL'; \ + done | sort | tail -1 > $@ + +test: path.c misc.c + $(CC_X86) -DTEST $+ -o $@ diff --git a/build/tools/makenorfirm/compress.c b/build/tools/makenorfirm/compress.c new file mode 100644 index 0000000..0d7a555 --- /dev/null +++ b/build/tools/makenorfirm/compress.c @@ -0,0 +1,293 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: compress.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // atoi() +#include // strcmp() +#include // isprint() +#include // chdir() +#include +#include // UCHAR_MAX +#include +#include // stat() +#include "elf.h" +#include "misc.h" +#include "defval.h" +#include "format_rom.h" +#include "format_nlist.h" +#include "makenorfirm.h" + +//#define ADD_HEADER + +#define DIFF_CODE_HEADER (0x80) +#define RL_CODE_HEADER (0x30) +#define LZ_CODE_HEADER (0x10) +#define HUFF_CODE_HEADER (0x20) +#define CODE_HEADER_MASK (0xF0) + +//=========================================================================== +// LZ77k +//=========================================================================== +static u8 SearchLZ(const u8 *nextp, u32 remainSize, u16 *offset); + +static u16 windowPos; +static u16 windowLen; + +static s16 LZOffsetTable[4096]; +static s16 LZByteTable[256]; +static s16 LZEndTable[256]; + + +static void LZInitTable(void) +{ + u16 i; + + for (i = 0; i < 256; i++) + { + LZByteTable[i] = -1; + LZEndTable[i] = -1; + } + windowPos = 0; + windowLen = 0; +} + +static void SlideByte(const u8 *srcp) +{ + s16 offset; + u8 in_data = *srcp; + u16 insert_offset; + + if (windowLen == 4096) + { + u8 out_data = *(srcp - 4096); + if ((LZByteTable[out_data] = LZOffsetTable[LZByteTable[out_data]]) == -1) + { + LZEndTable[out_data] = -1; + } + insert_offset = windowPos; + } + else + { + insert_offset = windowLen; + } + + offset = LZEndTable[in_data]; + if (offset == -1) + { + LZByteTable[in_data] = insert_offset; + } + else + { + LZOffsetTable[offset] = insert_offset; + } + LZEndTable[in_data] = insert_offset; + LZOffsetTable[insert_offset] = -1; + + if (windowLen == 4096) + { + windowPos = (u16)((windowPos + 1) % 0x1000); + } + else + { + windowLen++; + } +} + +static void LZSlide(const u8 *srcp, u32 n) +{ + u32 i; + + for (i = 0; i < n; i++) + { + SlideByte(srcp++); + } +} + +/*---------------------------------------------------------------------------* + Name: MI_CompressLZ + + Description: LZ77ksȂ֐ + + Arguments: srcp kf[^ւ̃|C^ + size kf[^TCY + dstp kf[^ւ̃|C^ + kf[^傫TCỸobt@KvłB + + Returns: k̃f[^TCYB + k̃f[^kO傫Ȃꍇɂ͈k𒆒f0Ԃ܂B + *---------------------------------------------------------------------------*/ +u32 LZCompWrite(u8 *srcp, u32 size, u8 *dstp, int boundary) +{ + u32 LZDstCount; // kf[^̃oCg + u8 LZCompFlags; // k̗LtOn + u8 *LZCompFlagsp; // LZCompFlags i[郁̈|Cg + u16 lastOffset; // vf[^܂ł̃ItZbg (̎_ł̍Œvf[^) + u8 lastLength; // vf[^ (̎_ł̍Œvf[^) + u8 i; + u32 dstMax; + +#ifdef ADD_HEADER + *(u32 *)dstp = size << 8 | LZ_CODE_HEADER; // f[^Ewb_ + dstp += 4; +#endif + LZDstCount = 4; + dstMax = size; + LZInitTable(); + + while (size > 0) + { + LZCompFlags = 0; + LZCompFlagsp = dstp++; // tOn̊i[ + LZDstCount++; + + // tOn8rbgf[^ƂĊi[邽߁A8񃋁[v + for (i = 0; i < 8; i++) + { + LZCompFlags <<= 1; // (i=0) ͓ɈӖ͂Ȃ + if (size <= 0) + { + // I[ɗꍇ̓tOŌ܂ŃVtgĂI + continue; + } + + if ((lastLength = SearchLZ(srcp, size, &lastOffset))) + { + // k”\ȏꍇ̓tO𗧂Ă + LZCompFlags |= 0x1; + + // ItZbg͏4rbgƉ8rbgɕĊi[ + *dstp++ = (u8)((lastLength - 3) << 4 | (lastOffset - 1) >> 8); + *dstp++ = (u8)((lastOffset - 1) & 0xff); + LZDstCount += 2; + LZSlide(srcp, lastLength); + srcp += lastLength; + size -= lastLength; + } + else + { + // kȂ + LZSlide(srcp, 1); + *dstp++ = *srcp++; + size--; + LZDstCount++; + } + } // 8񃋁[vI + *LZCompFlagsp = LZCompFlags; // tOni[ + } + + // 16oCgEACg + // ACgpf[^0 ̓f[^TCYɊ܂߂ + i = 0; + while (LZDstCount & (boundary - 1)) +// while ((LZDstCount + i) & 0x3) + { + *dstp++ = 0; + LZDstCount++; + i++; + } + + return LZDstCount; +} + +//-------------------------------------------------------- +// LZ77kŃXCh̒Œv܂B +// Arguments: startp f[^̊Jnʒu|C^ +// nextp Jnf[^̃|C^ +// remainSize cf[^TCY +// offset vItZbgi[̈ւ̃|C^ +// Return : v񂪌‚ꍇ TRUE +// ‚Ȃꍇ FALSE +//-------------------------------------------------------- +static u8 SearchLZ(const u8 *nextp, u32 remainSize, u16 *offset) +{ + const u8 *searchp; + const u8 *headp, *searchHeadp; + u16 maxOffset; + u8 maxLength = 2; + u8 tmpLength; + s32 w_offset; + + if (remainSize < 3) + { + return 0; + } + + w_offset = LZByteTable[*nextp]; + + while (w_offset != -1) + { + if (w_offset < windowPos) + { + searchp = nextp - windowPos + w_offset; + } + else + { + searchp = nextp - windowLen - windowPos + w_offset; + } + + /* ĂǂA͂ɍ */ + if (*(searchp + 1) != *(nextp + 1) || *(searchp + 2) != *(nextp + 2)) + { + w_offset = LZOffsetTable[w_offset]; + continue; + } + + if (nextp - searchp < 2) + { + // VRAM2oCgANZXȂ̂ (VRAMf[^ǂݏoꍇ邽)A + // Ώۃf[^2oCgÕf[^ɂȂ΂ȂȂB + // + // ItZbg12rbgŊi[邽߁A4096ȉ + break; + } + tmpLength = 3; + searchHeadp = searchp + 3; + headp = nextp + 3; + + while (((u32)(headp - nextp) < remainSize) && (*headp == *searchHeadp)) + { + headp++; + searchHeadp++; + tmpLength++; + + // f[^4rbgŊi[邽߁A18ȉ (3̉ʂ͂) + if (tmpLength == (0xF + 3)) + { + break; + } + } + if (tmpLength > maxLength) + { + // ő咷ItZbgXV + maxLength = tmpLength; + maxOffset = (u16)(nextp - searchp); + if (maxLength == (0xF + 3)) + { + // vőȂ̂ŁAIB + break; + } + } + w_offset = LZOffsetTable[w_offset]; + } + + if (maxLength < 3) + { + return 0; + } + *offset = maxOffset; + return maxLength; +} + diff --git a/build/tools/makenorfirm/compress.h b/build/tools/makenorfirm/compress.h new file mode 100644 index 0000000..e3dc58f --- /dev/null +++ b/build/tools/makenorfirm/compress.h @@ -0,0 +1,38 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: compress.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef COMPRESS_H_ +#define COMPRESS_H_ + +#include "misc.h" + + +/*---------------------------------------------------------------------------* + Name: MI_CompressLZ + + Description: LZ77ksȂ֐ + + Arguments: srcp kf[^ւ̃|C^ + size kf[^TCY + dstp kf[^ւ̃|C^ + kf[^傫TCỸobt@KvłB + + Returns: k̃f[^TCYB + *---------------------------------------------------------------------------*/ +u32 LZCompWrite(u8 *srcp, u32 size, u8 *dstp, int boundary); + + +#endif //COMPRESS_H_ diff --git a/build/tools/makenorfirm/defval.c b/build/tools/makenorfirm/defval.c new file mode 100644 index 0000000..679fb0e --- /dev/null +++ b/build/tools/makenorfirm/defval.c @@ -0,0 +1,315 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makerom + File: defval.c + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: defval.c,v $ + Revision 1.10 2006/01/18 02:11:19 kitase_hirotake + do-indent + + Revision 1.9 2005/02/28 05:26:03 yosizaki + do-indent. + + Revision 1.8 2004/08/05 13:50:13 yasu + Support -M option + + Revision 1.7 2004/06/29 04:55:40 yasu + Use VBuffer to resolve variables + + Revision 1.6 2004/06/23 07:51:02 yasu + fix a bug as illegal memory freeing at ResolveDefVal() + + Revision 1.5 2004/05/27 00:40:49 yasu + care also about current directory (dot ".") + + Revision 1.4 2004/05/27 00:25:46 yasu + care about double-dots ".." for defvalue option :r, :e + + Revision 1.3 2004/05/27 00:11:19 yasu + fix a error when searching a "dot" of file extension + + Revision 1.2 2004/05/26 12:02:47 yasu + support :h, :t, :r, :e option for variable name + + Revision 1.1 2004/03/26 05:06:45 yasu + support variables like as -DNAME=VALUE + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include // getenv() +#include // strcasecmp() +#include // getopt() +#include "misc.h" +#include "defval.h" + +typedef struct tValdef +{ + struct tValdef *next; + char *name; + char *value; +} +tValdef; + +tValdef *valdef_top = NULL; + + +// +// Add new define value via file +// +// opt : "DEFINE=VALUE" +// +BOOL AddDefValFromFile(char *filename) +{ + char *buffer; + int buffer_size; + int read_size; + FILE *fp; + + if (filename[0] == '-' && filename[1] == '\0') + { + fp = stdin; + } + else if (NULL == (fp = fopen(filename, "rb"))) + { + fprintf(stderr, "Cannot open file \"%s\".\n", filename); + return FALSE; + } + + buffer_size = DEFVAL_DEFAULT_BUFFER_SIZE; + + if (NULL == (buffer = malloc(buffer_size))) + { + fprintf(stderr, "Cannot allocate memory.\n"); + return FALSE; + } + + read_size = 0; + + while (NULL != fgets(buffer + read_size, buffer_size - read_size, fp)) + { + read_size = strlen(buffer); + + if (read_size == buffer_size - 1 && buffer[read_size - 1] != '\n') + { + buffer_size *= 2; + + if (NULL == (buffer = realloc(buffer, buffer_size))) + { + fprintf(stderr, "Cannot allocate memory.\n"); + return FALSE; + } + continue; + } + + AddDefVal(buffer); + read_size = 0; + } + + if (fp != stdin) + { + fclose(fp); + } + free(buffer); + + return TRUE; +} + + +// +// Add new define value +// +// opt : "DEFINE=VALUE" +// +void AddDefVal(char *opt) +{ + int i; + tValdef *t; + + for (i = 0;; i++) + { + if ('=' == opt[i] || '\0' == opt[i]) + { + break; + } + } + + if (i > 0) + { + t = Alloc(sizeof(tValdef)); + t->name = strncpy(Alloc(i + 1), opt, i); + t->name[i] = '\0'; + + if (opt[i] == '=') + { + i++; + } + t->value = strdup(opt + i); + + t->next = valdef_top; + valdef_top = t; + + debug_printf("DEFINE:$(%s)=\"%s\"\n", t->name, t->value); + } + return; +} + +// +// Search define value +// +// Return: value of specified name +// +char *SearchDefVal(char *name) +{ + tValdef *t; + + for (t = valdef_top; t; t = t->next) + { + if (!strcmp(t->name, name)) + { + return t->value; + } + } + + return getenv(name); +} + + +// +// Search define value and Modify it by : option +// +// Return: duplicated value of specified name modified by :x option +// +char *SearchDefValWithOption(char *name) +{ + int len_name = strlen(name); + char *value; + char option = '\0'; + + if (len_name > 2 && name[len_name - 2] == ':') + { + name[len_name - 2] = '\0'; + option = name[len_name - 1]; + } + + value = SearchDefVal(name); + + if (value) + { + int value_len = strlen(value); + int col_dot = value_len; + int col_filename = 0; + int i; + + for (i = 0; i < value_len; i++) + { + switch (value[i]) + { + case '.': + if (col_filename == i && + (value[i + 1] == '\0' || (value[i + 1] == '.' && value[i + 2] == '\0'))) + { + i = value_len; // exit loop if last entry is . or .. + } + else + { + col_dot = i; // Save the last dot column + } + break; + + case '/': + case '\\': + case ':': + col_filename = i + 1; // Save the last filename + col_dot = value_len; // Reset dot position + break; + + default: + ; + } + } + + switch (option) + { + case 'h': // Dirname with the last slash + value = strdup(value); + value[col_filename] = '\0'; + break; + + case 't': // Filename + value = strdup(value + col_filename); + break; + + case 'r': // All without . file extension + value = strdup(value); + value[col_dot] = '\0'; + break; + + case 'e': // File extension + value = strdup(value + col_dot + 1); + break; + + default: + value = strdup(value); + } + } + return value; +} + + +// +// Resolve define value +// +// Return: new string +// +char *ResolveDefVal(char *str) +{ + int i, j; + char *val; + VBuffer buf; + + InitVBuffer(&buf); + + for (i = 0; '\0' != str[i]; i++) + { + // search $(XXX) + if ('$' == str[i] && '(' == str[i + 1]) + { + for (j = i + 2; '\0' != str[j]; j++) + { + if (')' == str[j]) + { + str[j] = '\0'; + + // get value of XXX + val = SearchDefValWithOption(&str[i + 2]); + + // copy value of XXX + if (val) + { + char *s = val; + + while (*s) + { + PutVBuffer(&buf, *s); + s++; + } + free(val); + } + i = j; + goto next; + } + } + } + PutVBuffer(&buf, str[i]); + next:; + } + return GetVBuffer(&buf); // pass allocated buffer, should be freed by caller +} diff --git a/build/tools/makenorfirm/defval.h b/build/tools/makenorfirm/defval.h new file mode 100644 index 0000000..7135510 --- /dev/null +++ b/build/tools/makenorfirm/defval.h @@ -0,0 +1,38 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makerom + File: defval.h + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: defval.h,v $ + Revision 1.4 2006/01/18 02:11:19 kitase_hirotake + do-indent + + Revision 1.3 2005/02/28 05:26:03 yosizaki + do-indent. + + Revision 1.2 2004/08/05 13:50:13 yasu + Support -M option + + Revision 1.1 2004/03/26 05:06:45 yasu + support variables like as -DNAME=VALUE + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef DEFVAL_H_ +#define DEFVAL_H_ + +#define DEFVAL_DEFAULT_BUFFER_SIZE (1024) + +BOOL AddDefValFromFile(char *filename); +void AddDefVal(char *opt); +char *SearchDefVal(char *name); +char *ResolveDefVal(char *str); + +#endif //DEFVAL_H_ diff --git a/build/tools/makenorfirm/elf.h b/build/tools/makenorfirm/elf.h new file mode 100644 index 0000000..c360cd3 --- /dev/null +++ b/build/tools/makenorfirm/elf.h @@ -0,0 +1,431 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - ELF + File: elf.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + *---------------------------------------------------------------------------*/ + +#ifndef ELF_H_ +#define ELF_H_ + +#include "misc.h" + +/*--------------------------------------------------------- + ^` + --------------------------------------------------------*/ +typedef u32 Elf32_Addr; /* size:4, align:4 Unsigned program address */ +typedef u16 Elf32_Half; /* size:2, align:2 Unsigned medium int */ +typedef u32 Elf32_Off; /* size:4, align:4 Unsigned file offset */ +typedef s32 Elf32_Sword; /* size:4, align:4 Signed large int */ +typedef u32 Elf32_Word; /* size:4, align:4 Unsigned large int */ + +/*--------------------------------------------------------- + ELF Header + --------------------------------------------------------*/ +/* e_ident̃CfbNX */ +#define EI_MAG0 0 /* File identification */ +#define EI_MAG1 1 /* File identification */ +#define EI_MAG2 2 /* File identification */ +#define EI_MAG3 3 /* File identification */ +#define EI_CLASS 4 /* File class 0=invalid, 1=32bit, 2=64bit */ +#define EI_DATA 5 /* Data encoding 0=invalid, 1=LSB, 2=MSB */ +#define EI_VERSION 6 /* File version ݂1 */ +#define EI_PAD 7 /* Start of padding bytes */ +#define EI_NIDENT 16 /* Size of e_ident[] */ + +typedef struct { + unsigned char e_ident[EI_NIDENT]; + Elf32_Half e_type; /* ELF̌`(Ĕzu”\, s”\Ȃ) */ + Elf32_Half e_machine; /* t@CŗvA[LeN` */ + Elf32_Word e_version; /* ELFtH[}bg̃o[Wi݂1j */ + Elf32_Addr e_entry; /* vÕGg|CgBw薳Ȃ0B */ + Elf32_Off e_phoff; /* vOwb_e[ũt@C擪̃ItZbg */ + Elf32_Off e_shoff; /* ZNVwb_e[ũt@C擪̃ItZbg */ + Elf32_Word e_flags; /* vZbTŗL̃tO */ + Elf32_Half e_ehsize; /* ELFwb_̃TCY */ + Elf32_Half e_phentsize; /* 1vOwb_̃TCY */ + Elf32_Half e_phnum; /* vOwb_̐ */ + Elf32_Half e_shentsize; /* 1ZNVwb_̃TCY */ + Elf32_Half e_shnum; /* ZNVwb_̐ */ + Elf32_Half e_shstrndx; /* ZNVe[uZNVւ̃CfbNX */ +} Elf32_Ehdr; + +/* e_ident[EI_*]̒g` */ +#define ELFMAG0 0x7f +#define ELFMAG1 'E' +#define ELFMAG2 'L' +#define ELFMAG3 'F' +#define ELFCLASSNONE 0 /* invalid */ +#define ELFCLASS32 1 /* ARM and Thumb processors use 32-bit ELF. */ +#define ELFCLASS64 2 +#define ELFDATANONE 0 /* invalid */ +#define ELFDATA2LSB 1 /* little-endian */ +#define ELFDATA2MSB 2 /* big-endian */ + + +/* [e_type] */ +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* Re-locatable file */ +#define ET_EXEC 2 /* Executable file */ +#define ET_DYN 3 /* Shared object file */ +#define ET_CORE 4 /* Core file */ +#define ET_LOPROC 0xff00 /* Processor-specific */ +#define ET_HIPROC 0xffff /* Processor-specific */ + +/* [e_machine] */ +#define EM_NONE 0 /* No machine */ +#define EM_M32 1 +#define EM_SPARC 2 +#define EM_386 3 +#define EM_68K 4 +#define EM_88K 5 +#define EM_860 7 +#define EM_MIPS 8 +#define EM_MIPS_RS4_BE 10 +#define EM_ARM 40 /* ARM/Thumb Architecture */ + + +/* [e_version] This member identifies the object file version.*/ +#define EV_NONE 0 /* Invalid version */ +#define EV_CURRENT 1 /* Current version */ + + +/* + ARM-specific e_flags + e_flags Field Value Meaning + EF_ARM_HASENTRY (0x02) e_entry contains a program-loader entry point + (see section 4.1.1, Entry points, below). + EF_ARM_SYMSARESORTED (0x04) Each subsection of the symbol table is sorted by symbol value + (see section 4.4.8, Symbol table order, below) + EF_ARM_DYNSYMSUSESEGIDX (0x8) Symbols in dynamic symbol tables that are defined in sections + included in program segment n have st_shndx = n + 1. + (see section 4.4.9, Dynamic symbol table entries, below). + EF_ARM_MAPSYMSFIRST (0x10) Mapping symbols precede other local symbols in the symbol table + (see section 4.4.8, Symbol table order, below). + + EF_ARM_EABIMASK (0xFF000000)(current version is 0x02000000) + This masks an 8-bit version number, the version of the ARM + EABI to which this ELF file conforms. This EABI is version 2. A + value of 0 denotes unknown conformance. +*/ +#define EF_ARM_HASENTRY 0x02 +#define EF_ARM_SYMSARESORTED 0x04 +#define EF_ARM_DYNSYMSUSESEGIDX 0x8 +#define EF_ARM_MAPSYMSFIRST 0x10 +#define EF_ARM_EABIMASK 0xFF000000 + + +/*--------------------------------------------------------- + Program headers + --------------------------------------------------------*/ +typedef struct { + Elf32_Word p_type; + Elf32_Off p_offset; + Elf32_Addr p_vaddr; + Elf32_Addr p_paddr; + Elf32_Word p_filesz; + Elf32_Word p_memsz; + Elf32_Word p_flags; + Elf32_Word p_align; +} Elf32_Phdr; + +/* [p_type] */ +#define PT_NULL 0 /* gȂGgŁÃo̒l̈Ӗ͖` */ +#define PT_LOAD 1 /* sɃ[hZOg */ +#define PT_DYNAMIC 2 /* I\̔zێZOg */ +#define PT_INTERP 3 /* t@C̉߂ɎgC^v^̃pXێZOg */ +#define PT_NOTE 4 /* t@C̉߂ɂ͎gȂێZOg */ +#define PT_SHLIB 5 /* \ */ +#define PT_PHDR 6 /* vOwb_e[uivÕC[Ẅꕔłꍇ̂ݑ݁j */ +//#define PT_TLS ? /* XbhǏL̈̃ev[g */ + +#define PT_LOOS 0x60000000 /* OSŗLɗ\񂳂ꂽ̈ */ +#define PT_HIOS 0x6fffffff + +#define PT_LOPROC 0x70000000 /* vZbTŗLɗ\񂳂ꂽ̈ */ +#define PT_HIPROC 0x7fffffff + +/* [p_flags]*/ +#define PF_X 1 /*s”\*/ +#define PF_W 2 /*݉”\*/ +#define PF_R 4 /*ǂݏo”\*/ +#define PF_ARM_SB 0x10000000 /*The segment contains the location addressed by the static base*/ +#define PF_ARM_PI 0x20000000 /*The segment is position-independent*/ +#define PF_ARM_ENTRY 0x80000000 /*The segment contains the entry point*/ +#define PF_MASKPROC 0xf0000000 + + +/*--------------------------------------------------------- + Section headers + --------------------------------------------------------*/ +typedef struct { + Elf32_Word sh_name; /*ZNVwb_e[uZNṼCfbNX*/ + Elf32_Word sh_type; /* ^CviL`QƁj */ + Elf32_Word sh_flags; + Elf32_Addr sh_addr; /* */ + Elf32_Off sh_offset; /* t@C̐擪̃ItZbg */ + Elf32_Word sh_size; /* oCgPʂ̃TCY */ + Elf32_Word sh_link; /* sh_typeɂĒl̈Ӗς */ + Elf32_Word sh_info; /* sh_typeɂĒl̈Ӗς */ + Elf32_Word sh_addralign; /* ACg(0or1ŐȂ,44ByteAlign) */ + Elf32_Word sh_entsize; /* ŒTCỸGge[uꍇA1vf̃TCY */ +} Elf32_Shdr; + +/* sh_addr mod sh_addralign = 0 łȂ΂ȂȂ */ + +/* Section Types, [sh_type] */ +#define SHT_NULL 0 +#define SHT_PROGBITS 1 +#define SHT_SYMTAB 2 +#define SHT_STRTAB 3 +#define SHT_RELA 4 +#define SHT_HASH 5 +#define SHT_DYNAMIC 6 +#define SHT_NOTE 7 +#define SHT_NOBITS 8 +#define SHT_REL 9 +#define SHT_SHLIB 10 +#define SHT_DYNSYM 11 +#define SHT_LOPROC 0x70000000 +#define SHT_HIPROC 0x7fffffff +#define SHT_LOUSER 0x80000000 +#define SHT_HIUSER 0xffffffff + + +/* [sh_flags] */ +#define SHF_WRITE 0x1 +#define SHF_ALLOC 0x2 +#define SHF_EXECINSTR 0x4 +#define SHF_MASKPROC 0xf0000000 +/* ARM-EABI-specific */ +#define SHF_ENTRYSECT 0x10000000 /* The section contains an entry point. */ +#define SHF_COMDEF 0x80000000 /* The section may be multiply defined in the input to a link step. */ +/* others */ +#define SHF_LINK_ORDER 0x80 + +/*ZNVCfbNX*/ +//Sym->st_shndxȂ +#define SHN_UNDEF 0 +#define SHN_LORESERVE 0xff00 +#define SHN_LOPROC 0xff00 +#define SHN_HIPROC 0xff1f +#define SHN_ABS 0xfff1 +#define SHN_COMMON 0xfff2 +#define SHN_HIRESERVE 0xffff + + +//̓wb_łȂ̃f[^\ + +/*--------------------------------------------------------- + Symbol Table Entry + --------------------------------------------------------*/ +typedef struct { + Elf32_Word st_name; /* V{e[ũCfbNX */ + Elf32_Addr st_value; /* 炭֘AZNVł̃ItZbgl */ + Elf32_Word st_size; /* TCYȂAsȏꍇ 0 */ + unsigned char st_info; /* oCh ^Cv */ + unsigned char st_other; /* ݂ 0 */ + Elf32_Half st_shndx; /* ֘AZNVwb_e[ũCfbNX */ +} Elf32_Sym; + + +/* st_info */ +#define ELF32_ST_BIND(i) ((i)>>4) +#define ELF32_ST_TYPE(i) ((i)&0xf) +#define ELF32_ST_INFO(b,t) (((b)<<4)+((t)&0xf)) + +/* st_info BIND */ +#define STB_LOCAL 0 +#define STB_GLOBAL 1 +#define STB_WEAK 2 +#define STB_LOPROC 13 +#define STB_HIPROC 15 + +/* st_info TYPE */ +#define STT_NOTYPE 0 /*`*/ +#define STT_OBJECT 1 /*f[^IuWFNg*/ +#define STT_FUNC 2 +#define STT_SECTION 3 +#define STT_FILE 4 +#define STT_LOPROC 13 +#define STT_HIPROC 15 + + +/*--------------------------------------------------------- + Relocation Entry + --------------------------------------------------------*/ +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; +} Elf32_Rel; + +typedef struct { + Elf32_Addr r_offset; + Elf32_Word r_info; + Elf32_Sword r_addend; +} Elf32_Rela; + +#define ELF32_R_SYM(i) ((i)>>8) +#define ELF32_R_TYPE(i) ((unsigned char)(i)) +#define ELF32_R_INFO(s,t) (((s)<<8)+(unsigned char)(t)) + + +/* r_info TYPE */ +#define R_ARM_NONE 0 /* Any No relocation. Encodes dependencies between sections. */ +#define R_ARM_PC24 1 /* ARM B/BL S . P + A */ +#define R_ARM_ABS32 2 /* 32-bit word S + A */ +#define R_ARM_REL32 3 /* 32-bit word S . P + A */ +#define R_ARM_PC13 4 /* ARM LDR r, [pc,c] S . P + A */ +#define R_ARM_ABS16 5 /* 16-bit half-word S + A */ +#define R_ARM_ABS12 6 /* ARM LDR/STR S + A */ +#define R_ARM_THM_ABS5 7 /* Thumb LDR/STR S + A */ +#define R_ARM_ABS8 8 /* 8-bit byte S + A */ +#define R_ARM_SBREL32 9 /* 32-bit word S . B + A */ +#define R_ARM_THM_PC22 10 /* Thumb BL pair S . P+ A */ +#define R_ARM_THM_PC8 11 /* Thumb LDR r, [pc,c] S . P + A */ +#define R_ARM_AMP_VCALL9 12 /* AMP VCALL Obsolete.SA-1500 only. */ +#define R_ARM_SWI24 13 /* ARM SWI S + A */ +#define R_ARM_THM_SWI8 14 /* Thumb SWI S + A */ +#define R_ARM_XPC25 15 /* ARM BLX S . P+ A */ +#define R_ARM_THM_XPC22 16 /* Thumb BLX pair S . P+ A */ + +/* 17-31, reserved to ARM Linux */ +//17-19 Reserved to ARM LINUX +#define R_ARM_COPY 20 /* 32 bit word Copy symbol at dynamic link time. */ +#define R_ARM_GLOB_DAT 21 /* 32 bit word Create GOT entry. */ +#define R_ARM_JUMP_SLOT 22 /* 32 bit word Create PLT entry. */ +#define R_ARM_RELATIVE 23 /* 32 bit word Adjust by program base. */ +#define R_ARM_GOTOFF 24 /* 32 bit word Offset relative to start of GOT. */ +#define R_ARM_GOTPC 25 /* 32 bit word Insert address of GOT. */ +#define R_ARM_GOT32 26 /* 32 bit word Entry in GOT. */ +#define R_ARM_PLT32 27 /* ARM BL Entry in PLT. */ + +/* 28-31 Reserved to ARM LINUX */ +#define R_ARM_ALU_PCREL_7_0 32 /* ARM ADD/SUB (S . P + A) & 0x000000FF */ +#define R_ARM_ALU_PCREL_15_8 33 /* ARM ADD/SUB (S . P + A) & 0x0000FF00 */ +#define R_ARM_ALU_PCREL_23_15 34 /* ARM ADD/SUB (S . P + A) & 0x00FF0000 */ +#define R_ARM_LDR_SBREL_11_0 35 /* ARM LDR/STR (S . B + A) & 0x00000FFF */ +#define R_ARM_ALU_SBREL_19_12 36 /* ARM ADD/SUB (S . B + A) & 0x000FF000 */ +#define R_ARM_ALU_SBREL_27_20 37 /* ARM ADD/SUB (S . B + A) & 0x0FF00000 */ + +#define R_ARM_TARGET1 38 +#define R_ARM_ROSEGREL32 39 +#define R_ARM_V4BX 40 +#define R_ARM_TARGET2 41 +#define R_ARM_PREL31 42 + +/* 96-111, reserved to ARM g++ */ +#define R_ARM_GNU_VTENTRY 100 /* 32 bit word Record C++ vtable entry. */ +#define R_ARM_GNU_VTINHERIT 101 /* 32 bit word Record C++ member usage. */ +#define R_ARM_THM_PC11 102 /* Thumb B S . P + A */ +#define R_ARM_THM_PC9 103 /* Thumb B S . P + A */ + +/* 112-127, reserved for private experiments */ + +/* 128-248, reserved to ARM */ +#define R_ARM_RXPC25 249 /* ARM BLX (S . P) + A #define For calls between program segments. */ +#define R_ARM_RSBREL32 250 /* Word (S . SB) + A For an offset from SB, the static base. */ +#define R_ARM_THM_RPC22 251 /* Thumb BL/BLX pair (S . P) + A For calls between program segments. */ +#define R_ARM_RREL32 252 /* Word (S . P) + A For on offset between two segments. */ +#define R_ARM_RABS32 253 /* Word S + A For the address of a location in the target segment. */ +#define R_ARM_RPC24 254 /* ARM B/BL (S . P) + A For calls between program segments. */ +#define R_ARM_RBASE 255 /* None None.Identifies the segment being relocated by the following + relocation directives. The ARM EABI poses two problems for relocating + executables and shared objects encoded in */ + + +// shirait +#define R_ARM_LDR_PC_G0 4 //LDR + +#define R_ARM_ABS12 6 //LDR, STR + +#define R_ARM_THM_CALL 10 //R_ARM_THM_PC22Ɠ + +#define R_ARM_CALL 28 //BL/BLX +#define R_ARM_JUMP24 29 //B/BL +#define R_ARM_THM_JUMP24 30 + +#define R_ARM_MOVW_ABS_NC 43 //MOVW +#define R_ARM_MOVT_ABS 44 //MOVT +#define R_ARM_MOVW_PREL_NC 45 //MOVW +#define R_ARM_MOVT_PREL 46 //MOVT + +#define R_ARM_ALU_PC_G0_NC 57 //ADD, SUB +#define R_ARM_ALU_PC_G0 58 //ADD, SUB +#define R_ARM_ALU_PC_G1_NC 59 //ADD, SUB +#define R_ARM_ALU_PC_G1 60 //ADD, SUB +#define R_ARM_ALU_PC_G2 61 //ADD, SUB +#define R_ARM_LDR_PC_G1 62 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_PC_G2 63 //LDR, STR, LDRB, STRB +#define R_ARM_LDRS_PC_G0 64 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_PC_G1 65 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_PC_G2 66 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDC_PC_G0 67 //LDC, STC +#define R_ARM_LDC_PC_G1 68 //LDC, STC +#define R_ARM_LDC_PC_G2 69 //LDC, STC +#define R_ARM_ALU_SB_G0_NC 70 //ADD, SUB +#define R_ARM_ALU_SB_G0 71 //ADD, SUB +#define R_ARM_ALU_SB_G1_NC 72 //ADD, SUB +#define R_ARM_ALU_SB_G1 73 //ADD, SUB +#define R_ARM_ALU_SB_G2 74 //ADD, SUB +#define R_ARM_LDR_SB_G0 75 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_SB_G1 76 //LDR, STR, LDRB, STRB +#define R_ARM_LDR_SB_G2 77 //LDR, STR, LDRB, STRB +#define R_ARM_LDRS_SB_G0 78 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_SB_G1 79 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDRS_SB_G2 80 //LDRD, STRD, LDRH, STRH, LDRSH, LDRSB +#define R_ARM_LDC_SB_G0 81 //LDC, STC +#define R_ARM_LDC_SB_G1 82 //LDC, STC +#define R_ARM_LDC_SB_G2 83 //LDC, STC +#define R_ARM_MOVW_BREL_NC 84 //MOVW +#define R_ARM_MOVT_BREL 85 //MOVT +#define R_ARM_MOVW_BREL 86 //MOVW + +#define R_ARM_GOT_BREL12 97 //LDR +#define R_ARM_GOTOFF12 98 //LDR, STR + +#define R_ARM_TLS_LDO12 109 //LDR, STR +#define R_ARM_TLS_LE12 110 //LDR, STR +#define R_ARM_TLS_TE12GP 111 //LDR + + + +/*--------------------------------------------------------- + Dynamic Section elf_v1.2 + --------------------------------------------------------*/ +typedef struct { + Elf32_Sword d_tag; + union { + Elf32_Word d_val; + Elf32_Addr d_ptr; + } d_un; +} Elf32_Dyn; + + +/* Additional symbol types for Thumb. */ +#define STT_ARM_TFUNC STT_LOPROC /* A Thumb function. */ +#define STT_ARM_16BIT STT_HIPROC /* A Thumb label. */ + + + + + + + + + +/*--------------------------------------------------------- + ELFwb_ǂݏo + --------------------------------------------------------*/ +void *ELF_LoadELFHeader(const void *buf, Elf32_Ehdr *ehdr); + + + +#endif /* ELF_H_ */ + diff --git a/build/tools/makenorfirm/format_nlist.h b/build/tools/makenorfirm/format_nlist.h new file mode 100644 index 0000000..6e5ba82 --- /dev/null +++ b/build/tools/makenorfirm/format_nlist.h @@ -0,0 +1,54 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: format_nlist.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_NLIST_H_ +#define FORMAT_NLIST_H_ + +#include +#include "misc.h" +#include "path.h" + +#define SPECFILE_MAGIC_ID "#NORSF" + +#define CRC16_INIT_VALUE 0xffff + +//--------------------------------------------------------------------------- +// Banner Spec File +//--------------------------------------------------------------------------- + +// Command List +typedef struct +{ + char *string; + BOOL (*funcp) (char *, int num); + +} +tCommandDesc; + + +// F Command +typedef struct +{ + u32 offsetStart; + u32 offsetEnd; + u32 padding; + char fullPathSrc[FILENAME_MAX]; + +} +tFileDesc; + + +#endif // FORMAT_NLIST_H_ diff --git a/build/tools/makenorfirm/format_rom.h b/build/tools/makenorfirm/format_rom.h new file mode 100644 index 0000000..3cb717f --- /dev/null +++ b/build/tools/makenorfirm/format_rom.h @@ -0,0 +1,51 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: format_rom.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_ROM_H_ +#define FORMAT_ROM_H_ + +#include "misc.h" +#include + + +#define DEFAULT_ALIGN 16 +#define FIRM_ALIGN DEFAULT_ALIGN +#define FIRM_ALIGN_MASK (FIRM_ALIGN - 1) + +#define DEFAULT_HOSTROOT "." +#define DEFAULT_ROOT "/" + +#define DEFAULT_REJECT_1 "CVS" +#define DEFAULT_REJECT_2 "vssver.scc" + +#define FORMAT_VERSION "1.0" + +#define ENTRYNAME_MAX 127 + +#define DEFAULT_LISTFILE "default.nlf" + +#define DEFAULT_NORFIRM_SUFFIX ".nor" +#define DEFAULT_SPECFILE_SUFFIX ".norsf" + +/*===========================================================================* + * ROM FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// ROM HEADER +//--------------------------------------------------------------------------- + +#endif //FORMAT_ROM_H_ diff --git a/build/tools/makenorfirm/format_sign.h b/build/tools/makenorfirm/format_sign.h new file mode 100644 index 0000000..782a5d2 --- /dev/null +++ b/build/tools/makenorfirm/format_sign.h @@ -0,0 +1,32 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - SS + File: format_sign.h + + Copyright 2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_MAKENORFIRM_ACSIGN_FORMAT_H_ +#define FIRM_MAKENORFIRM_ACSIGN_FORMAT_H_ + +#include "format_rom.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_MAKENORFIRM_ACSIGN_FORMAT_H_ */ +#endif diff --git a/build/tools/makenorfirm/makenorfirm.c b/build/tools/makenorfirm/makenorfirm.c new file mode 100644 index 0000000..613efa7 --- /dev/null +++ b/build/tools/makenorfirm/makenorfirm.c @@ -0,0 +1,106 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: makenorfirm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include +#include // strcasecmp() +#include // getopt() +#include "makenorfirm.h" +#include "format_rom.h" +#include "path.h" +#include "defval.h" +#include "version.h" + +static int makenorfirm(const char *specFile, const char *norFile); + +//--------------------------------------------------------------------------- +// Main +//--------------------------------------------------------------------------- + +int main(int argc, char *argv[]) +{ + int n; + int narg; + char *norfirmFile; + + InitAppName(argv[0]); + + while ((n = getopt(argc, argv, "D:hvpd")) != -1) + { + switch (n) + { + case 'h': + case 'v': + goto usage; + + case 'D': + AddDefVal(optarg); + break; + + case 'p': + PrintMode = TRUE; + break; + + case 'd': + DebugMode = TRUE; + break; + + default: + break; + } + } + + narg = argc - optind; + if (narg > 0) + { + // Make SpecFile->NorfirmFile + norfirmFile = + strdup(narg > + 1 ? argv[optind + 1] : ChangeSuffix(argv[optind], DEFAULT_NORFIRM_SUFFIX)); + return makenorfirm(argv[optind], norfirmFile); + } + + usage: + { + char *makenorfirm = GetAppName(); + + fprintf(stderr, + "NITRO-SDK Development Tool - %s - Make norfirm file \n" + "Build %lu\n\n" + "Usage: %s [-phv] [-DNAME=VALUE ...] SPECFILE [NORFIRMFILE]\n\n", + makenorfirm, SDK_DATE_OF_LATEST_FILE, makenorfirm); + } + return 1; +} + + +//--------------------------------------------------------------------------- +// makenorfirm +//--------------------------------------------------------------------------- + +static int makenorfirm(const char *specFile, const char *norFile) +{ + debug_printf("makenorfirm(): '%s' -> '%s'\n", specFile, norFile); + + // Check identical + if (specFile && norFile && !strcasecmp(specFile, norFile)) + { + error("norfirm spec file is identical '%s'", norFile); + return 1; + } + + return OutputNorfirmFile(specFile, norFile) ? 0 : 1; +} diff --git a/build/tools/makenorfirm/makenorfirm.h b/build/tools/makenorfirm/makenorfirm.h new file mode 100644 index 0000000..bb8eed6 --- /dev/null +++ b/build/tools/makenorfirm/makenorfirm.h @@ -0,0 +1,24 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: makenorfirm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef MAKENORFIRM_H_ +#define MAKENORFIRM_H_ + +#include "misc.h" + +BOOL OutputNorfirmFile(const char *specFile, const char *norFile); + +#endif //MAKENORFIRM_H_ diff --git a/build/tools/makenorfirm/misc.c b/build/tools/makenorfirm/misc.c new file mode 100644 index 0000000..7706d6b --- /dev/null +++ b/build/tools/makenorfirm/misc.c @@ -0,0 +1,628 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: misc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // calloc() +#include // free(), exit() +#include // setmode() +#include // stat() +#include // setmode() +#include // strlen() +#include // va_start(),va_end() +#include // localtime() + +#include +#include "misc.h" + +BOOL DebugMode = FALSE; +BOOL PrintMode = FALSE; +char *PubkeyFileName = NULL; + +/*---------------------------------------------------------------------------* + * File Output Utilities + * + * BOOL OpenFile( const char* filename ) + * void CloseFile( void ) + * BOOL CheckResult( void ) + * void PutBuffer( const void* ptr, int len ) + * void PutByte( u8 c ) + * void PutWord( u16 c ) + * void PutWord( u32 c ) + * void PutString( const char *str ) + *---------------------------------------------------------------------------*/ + +static FILE *OutFile = NULL; +static const char *FileName = NULL; +static BOOL Status = FALSE; + + +// +// File Open +// + +BOOL OpenFile(const char *filename) +{ + if (OutFile) + CloseFile(); + + if (filename) + { + if (NULL == (OutFile = fopen(filename, "wb+"))) + { + error("Can't write '%s'", filename); + Status = FALSE; + return FALSE; + } + } + else + { + setmode(1, O_BINARY); + OutFile = stdout; // out to console if filename == NULL + } + FileName = filename; + Status = TRUE; + + return TRUE; +} + + +// +// File Close +// + +BOOL CloseFile(void) +{ + if (OutFile) + { + if (FileName) + { + if (fclose(OutFile) == -1) + { + error("Can't close '%s'", FileName); + Status = FALSE; + } + } + else + { + setmode(1, O_TEXT); + } + } + OutFile = NULL; + + return Status; +} + + +// +// File Seek +// + +void SeekFile(long pos) +{ + if (OutFile && fseek(OutFile, pos, SEEK_SET)) + { + error("Can't seek '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + + +// +// Error Check +// + +BOOL CheckResult(void) +{ + return Status; +} + + +// +// Delete outfile +// + +void DeleteOutFile(void) +{ + // Delete outfile + if (FileName) + { + debug_printf("Delete '%s'\n", FileName); + (void)unlink(FileName); + FileName = NULL; + } + return; +} + + +// +// Buffer Output +// + +void PutBuffer(const void *ptr, int len) /* If error, close file */ +{ + if (OutFile && len != fwrite(ptr, 1, len, OutFile)) + { + error("Can't write buffer to '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + +// +// Buffer Input +// + +void GetBuffer(void *ptr, int len) /* If error, close file */ +{ + if (OutFile && len != fread(ptr, 1, len, OutFile)) + { + error("Can't read '%s'", FileName ? FileName : ""); + CloseFile(); + Status = FALSE; + } +} + +// +// Byte/Half/Word Output +// + +void PutByte(u8 c) +{ + PutBuffer(&c, 1); +} +void PutHalf(u16 c) +{ + PutBuffer(&c, 2); +} +void PutWord(u32 c) +{ + PutBuffer(&c, 4); +} +void PutString(const char *str) +{ + PutBuffer(str, strlen(str)); +} + + +// +// Printf +// + +void PrintString(const char *fmt, ...) +{ + char *buffer; + va_list va; + int nchars; + int bufsize = FILENAME_MAX; + + while (1) + { + buffer = Alloc(bufsize); + va_start(va, fmt); + nchars = vsnprintf(buffer, bufsize, fmt, va); + va_end(va); + + if (0 <= nchars && nchars < bufsize) + { + break; + } + + Free(&buffer); + bufsize *= 2; + } + + if (nchars > 0) + { + PutBuffer(buffer, nchars); + } + Free(&buffer); +} + + +/*---------------------------------------------------------------------------* + * File Read/Write Utilities + * + * int ReadFile( const char* filename, void** buffer ) + * + * Read a file to buffer allocated internally + * Return read size + * Add '\0' at tail of file for help to handle text file + * + * BOOL WriteFile( const char* filename, void** buffer, int size ) + *---------------------------------------------------------------------------*/ + +int ReadFile(const char *filename, void *filebuffer, int size) +{ + FILE *fp; + struct stat fileStat; + int fileSize, readSize; + void **buffer = (void **)filebuffer; + + /* Check file */ + if (stat(filename, &fileStat) || !S_ISREG(fileStat.st_mode)) + { + goto error; + } + fileSize = fileStat.st_size; + if (fileSize < 0) + { + goto error; + } + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) + { + goto error; + } + + if (size && (size < fileSize)) + { + readSize = size; + } + else + { + readSize = fileSize; + } + + /* Read file */ + *buffer = Alloc(readSize + 1); /* error handle is done in Alloc() */ + /* size+1 for '\0' to handle text file */ + if (readSize != fread(*buffer, sizeof(char), readSize, fp)) + { + goto error_free_close; + } + + (*(char **)buffer)[readSize] = '\0'; /* Works as terminater if file is text file */ + + /* Close file */ + fclose(fp); + return readSize; + + error_free_close: + Free(buffer); + fclose(fp); + error: + error("Can't read '%s'", filename); + return -1; +} + + +int ReadFileWithPadding(const char *filename, void *filebuffer, int size, int boundary) +{ + FILE *fp; + struct stat fileStat; + int fileSize, readSize, padSize; + void **buffer = (void **)filebuffer; + + if (!boundary) + { + return ReadFile(filename, buffer, size); + } + + /* Check file */ + if (stat(filename, &fileStat) || !S_ISREG(fileStat.st_mode)) + { + goto error; + } + fileSize = fileStat.st_size; + if (fileSize < 0) + { + goto error; + } + + /* Open file */ + fp = fopen(filename, "rb"); + if (!fp) + { + goto error; + } + + if (size && (size < fileSize)) + { + readSize = size; + } + else + { + readSize = fileSize; + } + + padSize = (boundary - (readSize & (boundary-1))) & (boundary-1); + + /* Read file */ + *buffer = Alloc(readSize + padSize); /* error handle is done in Alloc() */ + /* size+1 for '\0' to handle text file */ + if (readSize != fread(*buffer, sizeof(char), readSize, fp)) + { + goto error_free_close; + } + + memset((char*)*buffer + readSize, 0, padSize); + + /* Close file */ + fclose(fp); + return readSize + padSize; + + error_free_close: + Free(buffer); + fclose(fp); + error: + error("Can't read '%s'", filename); + return -1; +} + + +BOOL WriteFile(const char *filename, void *buffer, int size) +{ + debug_printf("WriteFile %s\n", filename); + + (void)OpenFile(filename); + PutBuffer(buffer, size); + CloseFile(); + Free(&buffer); + return CheckResult(); +} + + +/*---------------------------------------------------------------------------* + * Time Format Utilities + * + * char* GetGMTime( const time_t time ) Show GMT + * char* GetTime( const time_t time ) Show local Time + *---------------------------------------------------------------------------*/ + +char *GetGMTime(const time_t time) +{ + static char timebuffer[32]; + strftime(timebuffer, sizeof(timebuffer), "%y/%m/%d-%H:%M:%S", gmtime(&time)); + return timebuffer; +} + + +char *GetTime(const time_t time) +{ + static char timebuffer[32]; + strftime(timebuffer, sizeof(timebuffer), "%y/%m/%d-%H:%M:%S", localtime(&time)); + return timebuffer; +} + + +/*---------------------------------------------------------------------------* + * Memory Allocation Utilities + * + * void* Alloc( size_t size ) + *---------------------------------------------------------------------------*/ + +void *Alloc(size_t size) +{ + void *t = calloc(1, size); + + if (t == NULL) + { + error("Can't allocate memory."); + exit(10); + } + return t; +} + + +void Free(void *p) +{ + void **ptr = (void **)p; + + if (*ptr) + { + free(*ptr); + (*ptr) = NULL; + } +} + + +/*---------------------------------------------------------------------------* + * VBuffer + * + * void PutVBuffer( VBuffer* vbuf, char c ) + *---------------------------------------------------------------------------*/ + +void PutVBuffer(VBuffer * vbuf, char c) +{ + int size; + char *tmp_buffer; + + if (vbuf->buffer == 0) + { + vbuf->size = VBUFFER_INITIAL_SIZE; + vbuf->buffer = Alloc(vbuf->size); // buffer is CALLOCed + } + size = strlen(vbuf->buffer); + + if (size >= vbuf->size - 1) + { + // Need buffer expansion + vbuf->size *= 2; + tmp_buffer = Alloc(vbuf->size); // buffer is CALLOCed + strcpy(tmp_buffer, vbuf->buffer); + Free(&vbuf->buffer); + vbuf->buffer = tmp_buffer; + } + vbuf->buffer[size] = c; + return; +} + +char *GetVBuffer(VBuffer * vbuf) +{ + return vbuf->buffer; +} + +void InitVBuffer(VBuffer * vbuf) +{ + vbuf->buffer = 0; + vbuf->size = 0; +} + +void FreeVBuffer(VBuffer * vbuf) +{ + Free(&vbuf->buffer); +} + + +/*---------------------------------------------------------------------------* + * File Path Utilities + * + * char* ChangeBackSlash( char* path ) + *---------------------------------------------------------------------------*/ + +char *ChangeBackSlash(char *path) +{ + char *p = path; + + while (*p) + { + if (*p == '\\') + { + *p = '/'; + } + p++; + } + return path; +} + + +/*---------------------------------------------------------------------------* + * Math + * + * u16 CalcCRC16( u16 start, u8 *data, int size ) + *---------------------------------------------------------------------------*/ + +static u16 crc16_table[16] = { + 0x0000, 0xCC01, 0xD801, 0x1400, + 0xF001, 0x3C00, 0x2800, 0xE401, + 0xA001, 0x6C00, 0x7800, 0xB401, + 0x5000, 0x9C01, 0x8801, 0x4400 +}; + +u16 CalcCRC16(u16 start, u8 *data, int size) +{ + u16 r1; + u16 total = start; + + while (size-- > 0) + { + // 4bit + r1 = crc16_table[total & 0xf]; + total = (total >> 4) & 0x0fff; + total = total ^ r1 ^ crc16_table[*data & 0xf]; + + // 4bit + r1 = crc16_table[total & 0xf]; + total = (total >> 4) & 0x0fff; + total = total ^ r1 ^ crc16_table[(*data >> 4) & 0xf]; + + data++; + } + return total; +} + + +/*---------------------------------------------------------------------------* + * for firm header + * + *---------------------------------------------------------------------------*/ + +static u8 ConvertAlign( u32 ofs ) +{ + u8 i; + + ofs /= 4; + for (i=0; i<7; i++) + { + if ( ofs & 1 ) + { + break; + } + ofs >>= 1; + } + + return i; +} + +tROMAddrConvType ConvertHeaderRamAddr( s32 p ) +{ + tROMAddrConvType retval; + + retval.align = ConvertAlign( p ); + retval.address = (u16)((p - HW_WRAM)/(4< + +typedef enum +{ + FALSE = 0, + TRUE = 1 +} +BOOL; + +typedef unsigned char u8; +typedef unsigned short int u16; +typedef unsigned long int u32; +typedef unsigned long long u64; +typedef signed char s8; +typedef signed short int s16; +typedef signed long int s32; +typedef signed long long s64; +typedef volatile u8 vu8; +typedef volatile u32 vu32; +typedef vu32 REGType32v; + + + + +#define error(...) do { fprintf(stderr, "Error: "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); } while(0) + +#define warning(...) do { fprintf(stderr, "Warning: "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); } while(0) + +BOOL OpenFile(const char *filename); +BOOL CloseFile(void); +void SeekFile(long pos); +BOOL CheckResult(void); +void DeleteOutFile(void); +void PutBuffer(const void *ptr, int len); +void GetBuffer(void *ptr, int len); +void PutByte(u8 c); +void PutHalf(u16 c); +void PutWord(u32 c); +void PutString(const char *str); +void PrintString(const char *fmt, ...); + +#define READ_ALL 0 +int ReadFile(const char *filename, void *filebuffer, int size); +int ReadFileWithPadding(const char *filename, void *filebuffer, int size, int boundary); +BOOL WriteFile(const char *filename, void *buffer, int size); + +char *GetGMTime(const time_t time); +char *GetTime(const time_t time); + +void *Alloc(size_t size); +void Free(void *p); + +typedef struct +{ + char *buffer; + int size; +} +VBuffer; + +#define VBUFFER_INITIAL_SIZE 1024 +void InitVBuffer(VBuffer * vbuf); +void FreeVBuffer(VBuffer * vbuf); +void PutVBuffer(VBuffer * vbuf, char c); +char *GetVBuffer(VBuffer * vbuf); + +char *ChangeBackSlash(char *path); + +u16 CalcCRC16(u16 start, u8 *data, int size); +const char *WrapNull(const char *str); + +typedef struct +{ + u16 address; + u8 align; +} +tROMAddrConvType; + +tROMAddrConvType ConvertHeaderRamAddr( s32 p ); +tROMAddrConvType ConvertHeaderRomOffset( s32 p ); +u16 ConvertHeaderRomOffsetAlign( s32 p, u32 align ); + +typedef union +{ + struct + { + u32 sign:1; + u32 header_hash:1; + u32 arm9_hash:1; + u32 arm7_hash:1; + u32 hash_table_hash:1; + u32 final_hash:1; + u32 header_footer:1; + u32 wl_check:1; + } + e; + u32 raw; +} +tErrorFlags; + +extern BOOL DebugMode; +extern BOOL PrintMode; +extern char *PubkeyFileName; +void debug_printf(const char *str, ...); +void debug_printf2(const char *str, ...); + +#endif //MISC_H_ diff --git a/build/tools/makenorfirm/out_norfirm.c b/build/tools/makenorfirm/out_norfirm.c new file mode 100644 index 0000000..d2416e0 --- /dev/null +++ b/build/tools/makenorfirm/out_norfirm.c @@ -0,0 +1,984 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: out_norfirm.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include // atoi() +#include // strcmp() +#include // isprint() +#include // chdir() +#include +#include // UCHAR_MAX +#include +#include // stat() +#include "elf.h" +#include "misc.h" +#include "defval.h" +#include "format_rom.h" +#include "format_nlist.h" +#include "makenorfirm.h" +#include "format_sign.h" +#include "acsign_nor.h" +#include "compress.h" + +#define SDK_ASM + +#include +#include "../acsign/aes2.h" + +#define NANDCMD "BOOT_NAND" +#define SBIN9CMD "ARM9_SBIN" +#define SBIN7CMD "ARM7_SBIN" +#define ELF9CMD "ARM9_ELF" +#define ELF7CMD "ARM7_ELF" +#define COMP9CMD "ARM9_COMP" +#define COMP7CMD "ARM7_COMP" +#define DECOMPCMD "DECOMP_PROC" +#define BAUDCMD "BAUDRATE" +#define ARM9X2CMD "ARM9_X2" +#define VERCMD "VERSION" +#define RSAKEYCMD "RSA_KEY" +#define OUTKEYCMD "OUT_KEY" +#define WREGCMD "WRAM_RBIN" +#define ENDKEYCMD "ENC_KEYINFO" +#define NCDCMD "NCD_ROMOFS" +#define ERRCMD "ERROR" + +static BOOL ConstructNorfirmFile(char * specFile); +static BOOL ReadSbinFile(const char *fileName, void* minfo, void* hash, BOOL comp); +static BOOL ReadKeyFile(const char *fileName); +static BOOL ReadWramRegFile(const char *fileName); +static s32 GetRamAddr(const char *fileName); + +static BOOL EncryptBuffer(char *buffer, int length); + +static BOOL BTNAND_Command(char * line, int num); +static BOOL Sbin9_Command(char * line, int num); +static BOOL Sbin7_Command(char * line, int num); +static BOOL Elf9_Command(char * line, int num); +static BOOL Elf7_Command(char * line, int num); +static BOOL Comp9_Command(char * line, int num); +static BOOL Comp7_Command(char * line, int num); +static BOOL Decomp_Command(char * line, int num); +static BOOL BAUDRATE_Command(char * line, int num); +static BOOL ARM9X2_Command(char * line, int num); +static BOOL VERSION_Command(char * line, int num); +static BOOL RSAKEY_Command(char * line, int num); +static BOOL OUTKEY_Command(char * line, int num); +static BOOL WramRegs_Command(char * line, int num); +static BOOL ENCKEY_Command(char * line, int num); +static BOOL NcdOffset_Command(char * line, int num); +static BOOL ERROR_Command(char * line, int num); + +static BOOL InitializeAesKey(void); +static BOOL InitializeNorfirmFile(void); +static BOOL FinalizeNorfirmFile(const char *norFile); + +static s32 Offset; // Current offset +static int LineNum; // Line number for error message +static const char *specFileName; // specFile name for error message + +NORHeader norHeader; // Norfirm Header Shadow +FIRMSignedContext signedContext; +u8 *keyFileBuf; +BOOL compArm9 = TRUE; +BOOL compArm7 = TRUE; +tErrorFlags errFlags; + +//--------------------------------------------------------------------------- +// Output - norfirm File +//--------------------------------------------------------------------------- + +BOOL OutputNorfirmFile(const char *specFile, const char *norFile) +{ + char *buffer; + BOOL state; + + if (ReadFile(specFile, &buffer, READ_ALL) <= 0) + { + return FALSE; + } + + if (!OpenFile(norFile)) + { + return FALSE; + } + + specFileName = specFile; + + state = InitializeNorfirmFile() && ConstructNorfirmFile(buffer) && + FinalizeNorfirmFile(norFile) && CloseFile(); + + if (!state) + { + DeleteOutFile(); + } + + return state; +} + + +//--------------------------------------------------------------------------- +// Output - Norfirm File +//--------------------------------------------------------------------------- + +static const tCommandDesc command[] = { + {SBIN9CMD, Sbin9_Command}, {SBIN7CMD, Sbin7_Command}, + {ELF9CMD, Elf9_Command},{ELF7CMD, Elf7_Command}, + {COMP9CMD, Comp9_Command},{COMP7CMD, Comp7_Command}, + {DECOMPCMD, Decomp_Command}, + {NANDCMD, BTNAND_Command}, + {VERCMD, VERSION_Command}, + {BAUDCMD, BAUDRATE_Command}, + {ARM9X2CMD, ARM9X2_Command}, + {RSAKEYCMD, RSAKEY_Command}, + {OUTKEYCMD, OUTKEY_Command}, + {WREGCMD, WramRegs_Command}, + {ENDKEYCMD, ENCKEY_Command}, + {NCDCMD, NcdOffset_Command}, + {ERRCMD, ERROR_Command}, +}; + +BOOL ConstructNorfirmFile(char * specFile) +{ + char *line; + char *line_top; + char *p; + int i; + + LineNum = 0; + Offset = 0x00000000; + + line = specFile++; + + while (*line != '\0') + { + LineNum++; + + // Get command line + line_top = line; + while (*line != '\0') + { + if (*line++ == '\n') + { + break; + } + } + + // Print for debug + debug_printf("NORSF Line%4d [", LineNum, line); + for (p = line_top; p != line; p++) + { + if (isprint(*p)) + { + debug_printf("%c", *p); + } + } + debug_printf("]\n"); + + if (*line_top == '#') + { + } + else + { + for (i = 0; i < (sizeof(command) / sizeof(command[0])); i++) + { + if (!strncmp(line_top, command[i].string, strlen(command[i].string))) + { + if (command[i].funcp != NULL) + { + char line_cmd[FILENAME_MAX]; + char line_scan[FILENAME_MAX]; + char* line_conv; + int num; + + num = sscanf( line_top, + "%1024[^ :] : %1024[^ \x0d:#\n]", + line_cmd, line_scan + ); + line_conv = ResolveDefVal(line_scan); + + debug_printf("line_cmd = %s, line_conv = %s\n", line_cmd, line_conv); + + if (!command[i].funcp(line_conv, num - 1)) + return FALSE; + } + } + } + } + + } + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - 'WramRegs' Command +//--------------------------------------------------------------------------- + +extern MIHeader_WramRegs wram_regs_init; +MIHeader_WramRegs* wram_regs; + +static BOOL WramRegs_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("wram regs file = %s\n", line); + + return ReadWramRegFile(line); +} + +static BOOL ReadWramRegFile(const char *fileName) +{ + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &wram_regs, READ_ALL)) < 0) + return FALSE; + + norHeader.h.w = *wram_regs; + + return CheckResult(); +} + +//--------------------------------------------------------------------------- +// Output - 'RSAKEY' Command +//--------------------------------------------------------------------------- + +static BOOL RSAKEY_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("rsa key = %s\n", line); + + return ReadKeyFile(line); +} + +static BOOL ReadKeyFile(const char *fileName) +{ + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &keyFileBuf, READ_ALL)) < 0) + return FALSE; + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'OUTKEY' Command +//--------------------------------------------------------------------------- + +static BOOL OUTKEY_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("out key = %s\n", line); + + PubkeyFileName = line; + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'VERSION' Command +//--------------------------------------------------------------------------- + +static u8 ConvToBCD8(int x) +{ + u8 bcd = 0; + + x %= 100; + bcd |= (x / 10)<<4; + bcd |= (x % 10); + + return bcd; +} + +static BOOL VERSION_Command(char * line, int num) +{ + char scan[FILENAME_MAX]; + u64 version = -1; + + // rescan + num = sscanf( line, + "0x%1024[^\x0d\n]", + scan + ); + + if (num == 1) + { + // convert version info + version = strtoull(scan, NULL, 16); + } + else if (num == 0) + { + // generate version info + u8* ver8 = (u8*)&version; + time_t timer; + struct tm *t_st; + + time(&timer); + t_st = localtime(&timer); + + ver8[0] = ConvToBCD8(t_st->tm_min); + ver8[1] = ConvToBCD8(t_st->tm_hour); + ver8[2] = ConvToBCD8(t_st->tm_mday); + ver8[3] = ConvToBCD8(t_st->tm_mon+1); + ver8[4] = ConvToBCD8(t_st->tm_year); + ver8[5] = 0xff; + ver8[6] = 0xff; + ver8[7] = 0xff; + } + + norHeader.d.card_key = version; + + debug_printf2("version = %08llx\n", version); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'BOOT_NAND' Command +//--------------------------------------------------------------------------- + +static BOOL BTNAND_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + norHeader.l.boot_nandfirm = FALSE; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "TRUE")) + { + norHeader.l.boot_nandfirm = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("boot nandfirm = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Decomp' Command +//--------------------------------------------------------------------------- + +static BOOL Decomp_Command(char * line, int num) +{ + char* dbg_str = "ARM7"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "ARM9")) + { + norHeader.l.arm9_decomp = TRUE; + dbg_str = "ARM9"; + } + + debug_printf2("decompress processor = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'ARM9_X2' Command +//--------------------------------------------------------------------------- + +static BOOL ARM9X2_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "TRUE")) + { + norHeader.l.arm9_x2 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm9 x2 = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'BAUDRATE' Command +//--------------------------------------------------------------------------- + +static BOOL BAUDRATE_Command(char * line, int num) +{ + char* dbg_str = "4M"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + if (!strcmp(line, "8M")) + { + norHeader.l.baudrate = TRUE; + dbg_str = "8M"; + } + + debug_printf2("spi speed = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Comp9' Command +//--------------------------------------------------------------------------- + +static BOOL Comp9_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + compArm9 = FALSE; + + if (!strcmp(line, "TRUE")) + { + norHeader.l.comp_arm9_boot_area = TRUE; + compArm9 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm9 compress = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Comp7' Command +//--------------------------------------------------------------------------- + +static BOOL Comp7_Command(char * line, int num) +{ + char* dbg_str = "FALSE"; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + compArm7 = FALSE; + + if (!strcmp(line, "TRUE")) + { + norHeader.l.comp_arm7_boot_area = TRUE; + compArm7 = TRUE; + dbg_str = "TRUE"; + } + + debug_printf2("arm7 compress = %s\n", dbg_str); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Elf9' Command +//--------------------------------------------------------------------------- + +static BOOL Elf9_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm9 elf = %s\n", line); + + { + s32 ramAddr = GetRamAddr(line); + norHeader.l.main_ram_address = (void*)ramAddr; + } + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'Elf7' Command +//--------------------------------------------------------------------------- + +static BOOL Elf7_Command(char * line, int num) +{ + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm7 elf = %s\n", line); + + { + s32 ramAddr = GetRamAddr(line); + norHeader.l.sub_ram_address = (void*)ramAddr; + } + + return CheckResult(); +} + + +static s32 GetRamAddr(const char *fileName) +{ + Elf32_Ehdr *ehdr; + s32 ramAddr; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &ehdr, sizeof(Elf32_Ehdr))) < 0) + return FALSE; + + ramAddr = ehdr->e_entry; + + Free(&ehdr); + + debug_printf2("ramaddr = 0x%08x\n", ramAddr); + + return ramAddr; +} + + +//--------------------------------------------------------------------------- +// Output - 'Sbin9' Command +//--------------------------------------------------------------------------- + +static BOOL Sbin9_Command(char * line, int num) +{ + FIRMSignedContext* sc = &signedContext; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm9 sbin = %s\n", line); + + // Set ARM9 ROM Offset + if (!Offset) + { + Offset = (sizeof(NORHeader) + FIRM_ALIGN_MASK) & ~FIRM_ALIGN_MASK; + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + norHeader.l.main_rom_offset = Offset; + } + + return ReadSbinFile(line, &norHeader.l.main_rom_offset, &sc->hash[FIRM_SIGNED_HASH_IDX_ARM9], compArm9); +} + +//--------------------------------------------------------------------------- +// Output - 'Sbin7' Command +//--------------------------------------------------------------------------- + +static BOOL Sbin7_Command(char * line, int num) +{ + FIRMSignedContext* sc = &signedContext; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + debug_printf2("arm7 sbin = %s\n", line); + + // Set ARM7 ROM Offset + if (!Offset) + { + Offset = (sizeof(NORHeader) + FIRM_ALIGN_MASK) & ~FIRM_ALIGN_MASK; + SeekFile(Offset); + } + debug_printf2("romoffset = %#x\n", Offset); + { + norHeader.l.sub_rom_offset = Offset; + } + + return ReadSbinFile(line, &norHeader.l.sub_rom_offset, &sc->hash[FIRM_SIGNED_HASH_IDX_ARM7], compArm7); +} + + +static BOOL ReadSbinFile(const char *fileName, void* minfo, void* hash, BOOL comp) +{ + const NORHeader_ModuleInfo *m = minfo; + u32 *size = (void*)&m->size; + u32 *orig_size = (void*)&m->decomp_size; + char *buffer; + char *file; + int file_size; + struct stat st; + + if (FILESTATUS_FILE != GetFileStatus(&st, fileName)) + { + error("'%s' is not regular file.", fileName); + return FALSE; + } + + if ((file_size = ReadFile(fileName, &file, READ_ALL)) < 0) + return FALSE; + + *orig_size = file_size; + + // Digest file image + if (hash) + { + ACSign_DigestUnit(hash, file, file_size); + } + + // Compress file image with fitting region + buffer = Alloc(file_size * 2); + if ( comp ) + { + file_size = LZCompWrite(file, file_size, buffer, FIRM_ALIGN); + } + else + { + memcpy(&buffer[0], file, file_size); + { + u32 pad_size = (FIRM_ALIGN - (file_size % FIRM_ALIGN)) % FIRM_ALIGN; + if (pad_size) + memset(&buffer[file_size], 0, pad_size); + file_size += pad_size; + } + } + Free(&file); + file = buffer; + + if (size) + { + *size = file_size; + } + Offset += file_size; + + // Encrypt file image + EncryptBuffer(file, file_size); + + // Output file image with fitting region + PutBuffer(file, file_size); + + Free(&file); + + return CheckResult(); +} + +typedef struct +{ + unsigned long e[4]; +} u128; + +static BOOL EncryptBuffer(char *buffer, int length) +{ + const u128 id = {{ AES_IDS_ID2_A, AES_IDS_ID2_B, AES_IDS_ID2_C, AES_IDS_ID2_D }}; + u128 iv = {{ length, -length, ~length, 0 }}; + FIRMSignedContext* sc = &signedContext; + char *buffer2 = Alloc(length); + AES_KEY key; + if (!buffer2) + return FALSE; + AES_SetKey(&key, sc->aes_key, (unsigned char*)&id); + AES_Ctr(&key, buffer2, buffer, length, (unsigned char*)&iv); + memcpy(buffer, buffer2, length); + memset(buffer2, 0, length); + Free(buffer2); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - 'ENC_KEYINFO' Command +//--------------------------------------------------------------------------- + +static BOOL ENCKEY_Command(char * line, int num) +{ + u32 key; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + key = strtoul(line, NULL, 0); + norHeader.d.ds_key = key; + + debug_printf2("keyinfo = %#x\n", key); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'NcdOffset' Command +//--------------------------------------------------------------------------- + +static BOOL NcdOffset_Command(char * line, int num) +{ + u32 ofs; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + ofs = strtoul(line, NULL, 0); + { + norHeader.d.ncd_romAdr = ConvertHeaderRomOffsetAlign(ofs, 8); + } + + debug_printf2("ncd romoffset = %#x\n", ofs); + + return CheckResult(); +} + + +//--------------------------------------------------------------------------- +// Output - 'ERROR' Command +//--------------------------------------------------------------------------- +static char* error_type[] = +{ + "SIGN", + "HEADER_HASH", + "ARM9_HASH", + "ARM7_HASH", + "HASH_TABLE_HASH", + "FINAL_HASH", + "HEADER_FOOTER", + "WL_CHECK", +}; + +static BOOL ERROR_Command(char * line, int num) +{ + char* dbg_str = "UNKNOWN"; + int i; + + if (num != 1) + { + error("Wrong format spec file '%s' line:%d", specFileName, LineNum); + return FALSE; + } + + for (i=0; ihash[FIRM_SIGNED_HASH_IDX_HEADER][0] ^= 1; + } + if ( errFlags.e.arm9_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_ARM9][0] ^= 1; + } + if ( errFlags.e.arm7_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_ARM7][0] ^= 1; + } + if ( errFlags.e.hash_table_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_HASH_TABLE][0] ^= 1; + } +} + +static void SetFinalHashError(FIRMSignedContext* sc) +{ + if ( errFlags.e.final_hash ) + { + sc->hash[FIRM_SIGNED_HASH_IDX_FINAL][0] ^= 1; + } +} + +static void SetSignError(NORHeader* nh) +{ + if ( errFlags.e.sign ) + { + nh->sign.raw[0] ^= 1; + } + +} + +static void SetFooterError(NORHeader* nh) +{ + if ( errFlags.e.header_footer ) + { + nh->h.reserved_footer[sizeof(nh->h.reserved_footer)-1] ^= 1; + } + +} + +static void SetWirelessCheck(NORHeader* nh) +{ + if ( errFlags.e.wl_check ) + { + nh->wl_params[0] ^= 0x80; + nh->wl_params[sizeof(nh->wl_params)-1] ^= 0x80; + } + +} + + +//--------------------------------------------------------------------------- +// Output - Initialize AES Key +//--------------------------------------------------------------------------- +static BOOL InitializeAesKey(void) +{ + FIRMSignedContext* sc = &signedContext; + struct stat specstat; + time_t spectime; + if (stat(specFileName, &specstat) != 0) + return FALSE; + time(&spectime); + memcpy(&sc->aes_key[0], &specstat.st_atime, 4); + memcpy(&sc->aes_key[4], &specstat.st_mtime, 4); + memcpy(&sc->aes_key[8], &specstat.st_ctime, 4); + memcpy(&sc->aes_key[12], &spectime, 4); + ACSign_GetKey(sc->aes_key, sizeof(sc->aes_key), sc->aes_key, sizeof(sc->aes_key)); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - Initialize Norfirm File +//--------------------------------------------------------------------------- + +static BOOL InitializeNorfirmFile(void) +{ + memset(norHeader.wl_params, 0xff, sizeof(norHeader.wl_params)); + memset(&signedContext.hash[FIRM_SIGNED_HASH_IDX_HASH_TABLE], 0xff, sizeof(signedContext.hash[0])); + norHeader.l.boot_nandfirm = TRUE; + InitializeAesKey(); + return TRUE; +} + + +//--------------------------------------------------------------------------- +// Output - Finalize Norfirm File +//--------------------------------------------------------------------------- + +static BOOL FinalizeNorfirmFile(const char *norFile) +{ + NORHeader* nh = &norHeader; + FIRMSignedContext* sc = &signedContext; + u8* key = keyFileBuf; + + ACSign_DigestHeader(&sc->hash[FIRM_SIGNED_HASH_IDX_HEADER], nh); + + SetUnitHashErrors(sc); + + ACSign_DigestUnit(&sc->hash[FIRM_SIGNED_HASH_IDX_FINAL], sc, FIRM_HEADER_2ND_HASH_AREA_LEN); + + SetFinalHashError(sc); + + if (key) + { + ACSign_Final(nh, sc, key); + } + + SetFooterError(nh); + + SetSignError(nh); + + SetWirelessCheck(nh); + + // Output file image + SeekFile(0L); + PutBuffer(&norHeader, sizeof(norHeader)); + + // Output public key (modulus) + if (PubkeyFileName) + { + WriteFile(PubkeyFileName, &keyFileBuf[ACS_RSA_PRVMOD_OFFSET], ACS_RSA_PRVMOD_LEN); + } + + return TRUE; +} diff --git a/build/tools/makenorfirm/path.c b/build/tools/makenorfirm/path.c new file mode 100644 index 0000000..eeeb989 --- /dev/null +++ b/build/tools/makenorfirm/path.c @@ -0,0 +1,931 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makebanner + File: path.c + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: path.c,v $ + Revision 1.3 2006/01/18 02:11:20 kitase_hirotake + do-indent + + Revision 1.2 2005/02/28 05:26:13 yosizaki + do-indent. + + Revision 1.1 2004/08/30 08:41:14 yasu + makebanner moves into CVS tree + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#include +#include // free() +#include // strcasecmp() +#include // stat() +#include // opendir()/readdir()/closedir() +#include // getcwd() +#ifdef __CYGWIN__ +#include // cygwin_conv_to_win32_path() +#endif +#include "path.h" + +//--------------------------------------------------------------------------- +// Get File Statue +//--------------------------------------------------------------------------- + +tFileStatus GetFileStatus(struct stat *s, const char *filename) +{ + // Get file status + if (stat(filename, s)) + { + error("Can't get status %s", filename); + return FILESTATUS_ERROR; + } + + if (S_ISREG(s->st_mode)) + { + return FILESTATUS_FILE; + } + else if (S_ISDIR(s->st_mode)) + { + return FILESTATUS_DIR; + } + + error("Unknown file type %s", filename); + return FILESTATUS_ERROR; +} + + +//--------------------------------------------------------------------------- +// File Globbing & Dir Listing +//--------------------------------------------------------------------------- + +typedef struct +{ + tCallBack callBack; + void *param; + tWildCard *accept; + tWildCard *reject; + +} +tForeachEntryParam; + + +static BOOL isAcceptEntryName(char *pathName, tWildCard * accept, tWildCard * reject) +{ + char *p = pathName; + + while (*p) + { + if (*p == '/') + pathName = p + 1; + p++; + } + + if (accept) + { + while (accept) + { + if (WildCardCmp(accept->name, pathName)) + { + goto accepted; + } + accept = accept->next; + } + return FALSE; + } + accepted: + + while (reject) + { + if (WildCardCmp(reject->name, pathName)) + { + return FALSE; + } + reject = reject->next; + } + return TRUE; +} + + +static BOOL ForeachEntry_CallBack(char *pathName, void *param) +{ + tForeachEntryParam *t = (tForeachEntryParam *) param; + struct stat fstat; + + if (!isAcceptEntryName(pathName, t->accept, t->reject)) + { + // Reject!!! ignored + return TRUE; + } + + switch (GetFileStatus(&fstat, pathName)) + { + case FILESTATUS_FILE: + return t->callBack(pathName, t->param); + + case FILESTATUS_DIR: + return ForeachDirList(pathName, ForeachEntry_CallBack, param); + + default: + break; + } + return FALSE; +} + + +BOOL ForeachEntry(const char *pathName, tWildCard * reject, tCallBack callBack, void *param) +{ + tForeachEntryParam t; + + t.callBack = callBack; + t.param = param; + t.accept = NULL; + t.reject = reject; + + return ForeachPathGlobbing(pathName, ForeachEntry_CallBack, &t); +} + + +typedef struct +{ + tCallBack callBack; + void *param; + char *baseName; + +} +tForeachFileParam; + + +static BOOL ForeachFile_CallBack(char *pathName, void *param) +{ + tForeachFileParam *t = (tForeachFileParam *) param; + + int len = strlen(t->baseName); + + debug_printf(" ForeachFile_CallBack path[%s] base[%s]\n", pathName, t->baseName); + + if (strncmp(pathName, t->baseName, len)) + { + error("Wildcard in Root is not supported"); + return FALSE; + } + + return t->callBack(pathName + len, t->param); +} + + +BOOL ForeachFile(const char *baseName, const char *fileName, tWildCard * reject, tCallBack callBack, + void *param) +{ + char *cBaseName; + char *cPathName; + BOOL state; + tForeachFileParam t; + + debug_printf("ForeachFile : baseName[%s] fileName[%s]\n", baseName, fileName); + + cBaseName = GetSrcPath(baseName, ""); + cPathName = GetSrcPath(baseName, fileName); + + debug_printf("ForeachFile : cBaseName[%s] cPathName[%s]\n", cBaseName, cPathName); + + t.callBack = callBack; + t.param = param; + t.baseName = cBaseName; + + state = ForeachEntry(cPathName, reject, ForeachFile_CallBack, &t); + + free(cBaseName); + free(cPathName); + + return state; +} + + +//--------------------------------------------------------------------------- +// FilePath Globbing +//--------------------------------------------------------------------------- + +typedef struct +{ + char *baseName; + char *pathName; + tCallBack callBack; + void *param; + +} +tGlobParam; + + +static int CountFile; +static BOOL ForeachPathGlobbing_Entry(tGlobParam * pg); +static BOOL ForeachPathGlobbing_WildCard(char *pathName, void *param); + +BOOL ForeachPathGlobbing(const char *pathName, tCallBack callBack, void *param) +{ + tGlobParam g; + BOOL ret; + + g.baseName = NULL; + g.pathName = PathNormalize(pathName, TRUE); + g.callBack = callBack; + g.param = param; + CountFile = 0; + + debug_printf("PathGlobbing : Name [%s]->[%s]\n", pathName, g.pathName); + + ret = ForeachPathGlobbing_Entry(&g); + + free(g.pathName); + + if (ret && CountFile == 0) + { + error("No file or directory matched %s", pathName); + return FALSE; + } + return ret; +} + + +static BOOL ForeachPathGlobbing_Entry(tGlobParam * pg) +{ + tGlobParam g; + char *entryName; + struct stat s; + BOOL state; + + if (pg->pathName) + { + entryName = PathDup(pg->pathName); + + g = *pg; + g.pathName = PathGetDirLevelDown(pg->pathName); + + if (pg->baseName) + { + g.baseName = Alloc(strlen(pg->baseName) + strlen(entryName) + 2); + sprintf(g.baseName, "%s/%s", pg->baseName, entryName); + } + else + { + g.baseName = strdup(entryName); + } + + // Check if wildcard ? + if (isPathWildCard(entryName)) + { + state = ForeachDirList(pg->baseName, ForeachPathGlobbing_WildCard, &g); + } + else + { + state = ForeachPathGlobbing_Entry(&g); + } + + Free(&entryName); + Free(&g.baseName); + } + else + { + // Check if file exists + if (!stat(pg->baseName, &s)) + { + debug_printf(" File Found [%s]\n", pg->baseName); + + // Globbing done, exec callback + + state = pg->callBack(pg->baseName, pg->param); + CountFile++; + } + else + { + debug_printf(" File Not Found [%s]\n", pg->baseName); + state = TRUE; // Ignored + } + } + return state; +} + + +static BOOL ForeachPathGlobbing_WildCard(char *pathName, void *param) +{ + tGlobParam g; + tGlobParam *pg = (tGlobParam *) param; + + debug_printf(" WildCardCmp: [%s] [%s]\n", pg->baseName, pathName); + + if (WildCardCmp(pg->baseName, pathName)) + { + g = *pg; + g.baseName = pathName; + return ForeachPathGlobbing_Entry(&g); + } + + return TRUE; // Ignored +} + + +//--------------------------------------------------------------------------- +// Directory Listing +// Listing directory & Exec CallBack +//--------------------------------------------------------------------------- + +BOOL ForeachDirList(const char *dirName, tCallBack callBack, void *param) +{ + DIR *dir; + struct dirent *entry; + char *pathName; + BOOL state = TRUE; + + if (!dirName) + { + dirName = "."; + } + + debug_printf("DirectoryList: Name [%s]\n", dirName); + + // Open directory + if (NULL == (dir = opendir(dirName))) + { + error("Can't read directory %s", dirName); + return FALSE; + } + + // Store new files + while (NULL != (entry = readdir(dir))) + { + pathName = entry->d_name; + + if (!strcmp(pathName, ".") || !strcmp(pathName, "..")) + { + continue; + } + + debug_printf(" :%s\n", pathName); + pathName = GetSrcPath(dirName, pathName); + state = callBack(pathName, param); + free(pathName); + + if (!state) + break; + } + + closedir(dir); + return state; +} + + +//--------------------------------------------------------------------------- +// +// PathName Utilities +// +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// StrCmp/StrCpy entry name terminated / or \0 +//--------------------------------------------------------------------------- + +int PathCmp(const char *path, const char *cmp) +{ + char c; + + do + { + c = *path; + if (c == '/') + c = '\0'; // end of string if '/' + if (c != *cmp) + return 1; + path++; + cmp++; + } + while (c); + + return 0; +} + + +char *PathCpy(char *dest, const char *src) +{ + while (*src != '\0' && *src != '/') + { + *dest++ = *src++; + } + return dest; // Don't set '\0' +} + + +int PathLen(const char *path) +{ + int n = 0; + + while (*path != '\0' && *path != '/') + { + n++; + path++; + } + return n; +} + + +char *PathDup(const char *src) +{ + int n = PathLen(src); + char *dest = Alloc(n + 2); + + PathCpy(dest, src); + dest[n] = '\0'; + + return dest; +} + + +BOOL WildCardCmp(const char *wildcard, const char *path) +{ + if (*wildcard == '*') + { + if (*path != '\0' && WildCardCmp(wildcard, path + 1)) + return TRUE; + if (WildCardCmp(wildcard + 1, path)) + return TRUE; + } + + else if (*wildcard == '?') + { + return *path != '\0' && WildCardCmp(wildcard + 1, path + 1); + } + + else if (*wildcard == *path) + { + return *path == '\0' || WildCardCmp(wildcard + 1, path + 1); + } + + return FALSE; +} + + +BOOL isPathWildCard(const char *path) +{ + while (*path != '\0' && *path != '/') + { + if (*path == '*' || *path == '?') + { + return TRUE; + } + path++; + } + return FALSE; +} + + +//--------------------------------------------------------------------------- +// Go up/down directory level +//--------------------------------------------------------------------------- + +char *PathGetDirLevelDown(const char *path) +{ + while (*path) + { + if (*path == '/') + return (char *)path + 1; + path++; + } + return NULL; +} + + +//--------------------------------------------------------------------------- +// Get Basename +//--------------------------------------------------------------------------- + +char *GetBaseName(const char *path) +{ + int i; + char *new_path; + + for (i = strlen(path) - 1; i >= 0; i--) + { + if (path[i] == '/') + { + new_path = strdup(path); + new_path[i] = '\0'; + return new_path; + } + if (path[i] == ':') + { + new_path = Alloc(i + 3); + strncpy(new_path, path, i); + strcpy(new_path + i, ":."); + return new_path; + } + } + + new_path = strdup("."); + return new_path; +} + + +//--------------------------------------------------------------------------- +// Get Filename +//--------------------------------------------------------------------------- + +char *GetFileName(const char *path) +{ + int i; + char *new_file; + + for (i = strlen(path) - 1; i >= 0; i--) + { + if (path[i] == '/' || path[i] == ':') + { + new_file = strdup(path + i + 1); + return new_file; + } + } + new_file = strdup(path); + return new_file; +} + + +//--------------------------------------------------------------------------- +// Reconstruct path name +// +// - Resolve '.' or '..' in path name +// - Work around . and / to translate regular form +// +// Regular form of path: +// Absolute Path [Drive:]/.[/Entry...] +// Relative Path [Drive:].[/Entry]... +// +// ex) +// abc/def -> ./abc/def +// /aaa -> /./aaa +// D:/aaa -> D:/./aaa +// / -> /. +// . -> . +// ../aa -> ./../aa +//--------------------------------------------------------------------------- + +char *PathNormalize(const char *pathName, BOOL isTreatDotDot) +{ + int i, level, level_root, n; + BOOL isAbsolute; + const char *entry[DIRLEVEL_MAX]; + + char *pathNormal = Alloc(strlen(pathName) + 4); + const char *p_org; + char *p_new; + + // + // Check if drive letter C: D: E: + // Check if absolute path + // + p_new = pathNormal; + p_org = SkipDriveName(pathName); + n = (int)p_org - (int)pathName; + + if (n > 0) + { + strncpy(p_new, pathName, n); + p_new += n; + } + isAbsolute = isAbsolutePath(p_org); + + // + // Resolve '.' and '..' + // + // Slice the path at point of / , put them into entry[] + // + + level = level_root = 0; + + for (; p_org; p_org = PathGetDirLevelDown(p_org)) + { + if (!PathCmp(p_org, "") || !PathCmp(p_org, ".")) + { + // skip it + continue; + } + else if (!PathCmp(p_org, "..") && isTreatDotDot) + { + if (level > level_root) + { + // Back to parent dir + level--; + continue; + } + + // if pathname starts with '/', no directory to go up + if (isAbsolute) + { + error("Can't go up directory, '..' Ignored. %s", pathName); + continue; + } + + // keep '..' + level_root = level + 1; + } + + // name entry + entry[level] = p_org; + level++; + } + + // Reconstruct pathname + if (isAbsolute) + { + *p_new++ = '/'; + } + *p_new++ = '.'; + + for (i = 0; i < level; i++) + { + *p_new++ = '/'; + p_new = PathCpy(p_new, entry[i]); + } + *p_new = '\0'; + +#if 0 + if (strcmp(pathNormal, pathName)) + { + debug_printf(" PathNormal: [%s] -> [%s]\n", pathName, pathNormal); + } +#endif + return pathNormal; +} + + +//--------------------------------------------------------------------------- +// Get Src Path +// Normalize BASENAME +// Normalize FILENAME +// Concat both +//--------------------------------------------------------------------------- + +char *GetSrcPath(const char *baseName, const char *fileName) +{ + char *base; + char *file; + char *t; + char *path; + + base = PathNormalize(baseName, TRUE); + file = PathNormalize(fileName, TRUE); + t = Alloc(strlen(base) + strlen(file) + 2); + + // Concat base + '/' + file + sprintf(t, "%s/%s", base, file); + path = PathNormalize(t, FALSE); + + free(base); + free(file); + free(t); + + debug_printf(" GetSrcPath: [%s]\n", path); + return path; +} + + +//--------------------------------------------------------------------------- +// Get Dest Path +// Concat BASENAME + FILENAME +// Normalize it +//--------------------------------------------------------------------------- + +char *GetDestPath(const char *baseName, const char *fileName) +{ + char *t; + char *path; + + t = Alloc(strlen(baseName) + strlen(fileName) + 2); + + // Concat base + '/' + file + sprintf(t, "%s/%s", baseName, fileName); + path = PathNormalize(t, TRUE); + + free(t); + + debug_printf(" GetDestPath: [%s]\n", path); + return path; +} + + +//--------------------------------------------------------------------------- +// Remake the path into familier shape +// Delete ./ +//--------------------------------------------------------------------------- + +char *PathDenormalize(char *path) +{ + char *p; + + p = (char *)SkipDriveName(path); + if (*p == '/') + { + p++; + } + + // Cut './' + if (*p == '.' && *(p + 1) == '/') + { + while ('\0' != (*p = *(p + 2))) + { + p++; + } + + if (p == path) + { + + } + } + + + + return path; +} + + +//--------------------------------------------------------------------------- +// Get PC Path +//--------------------------------------------------------------------------- + +char *GetWin32Path(char *cygpath) +{ + static char buffer[FILENAME_MAX]; + +#ifdef __CYGWIN__ + if (*cygpath == '/') + { + cygwin_conv_to_win32_path(cygpath, buffer); + } + else +#endif + { + strcpy(buffer, cygpath); + } + + return ChangeBackSlash(buffer); +} + +char *ChangeWin32Path(char *cygpath) +{ + char *win32path = strdup(GetWin32Path(cygpath)); + + free(cygpath); + return win32path; +} + +//--------------------------------------------------------------------------- +// Change suffix +//--------------------------------------------------------------------------- +char *ChangeSuffix(const char *file, const char *suffix) +{ + int i, n; + char *path; + + n = strlen(file); + + for (i = n; file[i] != '.'; i--) + { + if (file[i] == '/' || i == 0) + { + i = n; + break; + } + } + + path = Alloc(i + strlen(suffix) + 1); + strncpy(path, file, i); + strcpy(path + i, suffix); + + return path; +} + + +//--------------------------------------------------------------------------- +// Get Current Dir +//--------------------------------------------------------------------------- + +char *GetCurrentDirectory(void) +{ + static char buffer[FILENAME_MAX]; + char *cwd; + + cwd = getcwd(buffer, FILENAME_MAX); + if (!cwd) + { + error("Can't access current directory"); + exit(10); + } + return cwd; +} + + +//--------------------------------------------------------------------------- +// Check if absolute path +// +// Return True in case of ... +// +// /dirA/dirB/fileC +// D:/dirA/dirB/fileC +// +// Return False in case of ... +// +// dirX/dirY/fileZ +// D:dirX/dirY/fileZ +//--------------------------------------------------------------------------- + +BOOL isAbsolutePath(const char *path) +{ + const char *p = path; + + while (*p != '\0') + { + if (*p == '/' || *p == '\\') + { + if (p == path || p[-1] == ':') + { + return TRUE; + } + } + p++; + } + return FALSE; +} + +//--------------------------------------------------------------------------- +// Check if drive name +// +// Return next character of ':' if drive name +// Return head of path if no drive name +//--------------------------------------------------------------------------- + +const char *SkipDriveName(const char *path) +{ + const char *p = path; + + while (*p != '\0' && *p != '/' && *p != '\\') + { + if (*p == ':') + { + return p + 1; + } + p++; + } + return path; +} + + +//--------------------------------------------------------------------------- +// App Name Utilities +//--------------------------------------------------------------------------- +static char *appName; +static char *appBaseName; +static char *appFileName; + +void InitAppName(const char *path) +{ + char *slash_path = ChangeBackSlash(strdup(path)); + + appBaseName = GetBaseName(slash_path); + appFileName = GetFileName(slash_path); + appName = ChangeSuffix(appFileName, ""); + + free(slash_path); +} + +char *GetAppName(void) +{ + return appName; +} + +char *GetAppBaseName(void) +{ + return appBaseName; +} + +char *GetAppFileName(void) +{ + return appFileName; +} + + +#ifdef TEST +int main(int argc, char *argv[]) +{ + int i; + char *s; + + for (i = 1; i < argc; i++) + { + s = PathNormalize(argv[i], TRUE); + printf("[%s] -> [%s]\n", argv[i], s); + free(s); + } + return 0; +} +#endif diff --git a/build/tools/makenorfirm/path.h b/build/tools/makenorfirm/path.h new file mode 100644 index 0000000..e9956dc --- /dev/null +++ b/build/tools/makenorfirm/path.h @@ -0,0 +1,93 @@ +/*---------------------------------------------------------------------------* + Project: NitroSDK - tools - makebanner + File: path.h + + Copyright 2003-2006 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: path.h,v $ + Revision 1.3 2006/01/18 02:11:20 kitase_hirotake + do-indent + + Revision 1.2 2005/02/28 05:26:13 yosizaki + do-indent. + + Revision 1.1 2004/08/30 08:41:14 yasu + makebanner moves into CVS tree + + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef PATH_H_ +#define PATH_H_ + +#include // struct tat +#include "misc.h" + +#define DIRLEVEL_MAX 256 +#ifndef FILENAME_MAX +#define FILENAME_MAX 1024 +#endif + +typedef enum +{ + FILESTATUS_ERROR = -1, + FILESTATUS_FILE = 0, + FILESTATUS_DIR = 1 +} +tFileStatus; + + +// Item Reject Control + +typedef struct tWildCard +{ + struct tWildCard *next; + char *name; + +} +tWildCard; + + +// CallBacks + +typedef BOOL (*tCallBack) (char *, void *); + + +// Prototypes + +tFileStatus GetFileStatus(struct stat *s, const char *filename); +BOOL ForeachEntry(const char *pathName, tWildCard * reject, tCallBack callBack, void *param); +BOOL ForeachFile(const char *baseName, const char *fileName, tWildCard * reject, + tCallBack callBack, void *param); +BOOL ForeachPathGlobbing(const char *pathName, tCallBack callBack, void *param); +BOOL ForeachDirList(const char *dirName, tCallBack callBack, void *param); +int PathCmp(const char *path, const char *cmp); +char *PathCpy(char *dest, const char *src); +int PathLen(const char *path); +char *PathDup(const char *src); +char *PathGetDirLevelDown(const char *path); +char *GetBaseName(const char *path); +char *GetFileName(const char *path); +BOOL WildCardCmp(const char *wildcard, const char *path); +BOOL isPathWildCard(const char *path); +char *PathNormalize(const char *pathName, BOOL isTreatDotDot); +char *PathDenormalize(char *path); +char *GetSrcPath(const char *base, const char *file); +char *GetDestPath(const char *base, const char *file); +char *GetWin32Path(char *cygpath); +char *ChangeWin32Path(char *cygpath); +char *ChangeSuffix(const char *file, const char *suffix); +char *GetCurrentDirectory(void); +BOOL isAbsolutePath(const char *path); +const char *SkipDriveName(const char *path); +void InitAppName(const char *path); +char *GetAppName(void); +char *GetAppBaseName(void); +char *GetAppFileName(void); + +#endif //PATH_H_ diff --git a/build/tools/makenorfirm/test/Makefile b/build/tools/makenorfirm/test/Makefile new file mode 100644 index 0000000..992184a --- /dev/null +++ b/build/tools/makenorfirm/test/Makefile @@ -0,0 +1,58 @@ +#! make -f +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makenorfirm +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- + +SUBDIRS = wram_rbin \ + +include $(TWLSDK_ROOT)/build/buildtools/commondefs + +MAKENORFIRM = ../makenorfirm.exe + +MAKEFIRM_RSA_PRVKEY = ./rsa_private.der + +MAKEFIRM_ARM9 = ./twl_norfirm9_print.axf +MAKEFIRM_ARM7 = ./twl_norfirm7_print.axf +SDEPENDS_BIN += $(MAKEFIRM_ARM9) $(MAKEFIRM_ARM7) +MAKEFIRM_FLAGS += -d +MAKEFIRM_DEFS += -DFIRM_ROOT='$(FIRM_ROOT)' \ + -DMAKEFIRM_ARM9='$(basename $(MAKEFIRM_ARM9))' \ + -DMAKEFIRM_ARM7='$(basename $(MAKEFIRM_ARM7))' \ + -DMAKEFIRM_RSA_PRVKEY='$(MAKEFIRM_RSA_PRVKEY)' \ + +TARGET = test.srl + +%.srl: %.norsf $(MAKENORFIRM) $(MAKEFIRM_RSA_PRVKEY) + $(MAKENORFIRM) $(MAKEFIRM_FLAGS) $(MAKEFIRM_DEFS) $< $@ + +.PHONY: build install do-autotest clean clobber + +define ECHO_CURDIR + echo "==== $(CURDIR)"; +endef + +build: + @$(ECHO_CURDIR) + @$(MAKE) $(TARGET) + +install do-autotest: + @$(ECHO_CURDIR) + +clean clobber super-clobber: + @$(ECHO_CURDIR) + -rm -f $(TARGET) *~ + +test-utf16.bsf: icon.nbfc icon.nbfp diff --git a/build/tools/makenorfirm/test/rsa_private.der b/build/tools/makenorfirm/test/rsa_private.der new file mode 100644 index 0000000..ccf67c1 Binary files /dev/null and b/build/tools/makenorfirm/test/rsa_private.der differ diff --git a/build/tools/makenorfirm/test/test.norsf b/build/tools/makenorfirm/test/test.norsf new file mode 100644 index 0000000..7c3093a --- /dev/null +++ b/build/tools/makenorfirm/test/test.norsf @@ -0,0 +1,30 @@ +#NORSF --- Norfirm Spec File + +VERSION : 0x0 # GENERATE + +BOOT_NAND : TRUE # TRUE or FALSE + +RSA_KEY : rsa_private.der +OUT_KEY : rsa_public.sbin + +WRAM_RBIN: ./wram_rbin/wram_regs.rbin + +DECOMP_PROC : ARM9 # ARM9 or ARM7 + +ARM9_COMP : TRUE # TRUE or FALSE, should be before ARM9_SBIN +ARM9_SBIN : $(MAKEFIRM_ARM9).sbin +ARM9_ELF : $(MAKEFIRM_ARM9).axf + +ARM7_COMP : FALSE # TRUE or FALSE, should be before ARM7_SBIN +ARM7_SBIN : $(MAKEFIRM_ARM7).sbin +ARM7_ELF : $(MAKEFIRM_ARM7).axf + +BAUDRATE : 8M # 4M or 8M +ARM9_X2 : TRUE # TRUE or FALSE + +ENC_KEYINFO : 0x5043414d # 'MACP' +NCD_ROMOFS : 0x07fe00 + +ERROR : ARM7_HASH # SIGN, HEADER_HASH, ARM9_HASH, ARM7_HASH, HASH_TABLE_HASH or FINAL_HASH +ERROR : HEADER_FOOTER # for debug +ERROR : WL_CHECK # for debug diff --git a/build/tools/makenorfirm/test/twl_norfirm7_print.axf b/build/tools/makenorfirm/test/twl_norfirm7_print.axf new file mode 100644 index 0000000..b255bd2 Binary files /dev/null and b/build/tools/makenorfirm/test/twl_norfirm7_print.axf differ diff --git a/build/tools/makenorfirm/test/twl_norfirm7_print.sbin b/build/tools/makenorfirm/test/twl_norfirm7_print.sbin new file mode 100644 index 0000000..a4eeebc Binary files /dev/null and b/build/tools/makenorfirm/test/twl_norfirm7_print.sbin differ diff --git a/build/tools/makenorfirm/test/twl_norfirm9_print.axf b/build/tools/makenorfirm/test/twl_norfirm9_print.axf new file mode 100644 index 0000000..3d064b3 Binary files /dev/null and b/build/tools/makenorfirm/test/twl_norfirm9_print.axf differ diff --git a/build/tools/makenorfirm/test/twl_norfirm9_print.sbin b/build/tools/makenorfirm/test/twl_norfirm9_print.sbin new file mode 100644 index 0000000..cd305be Binary files /dev/null and b/build/tools/makenorfirm/test/twl_norfirm9_print.sbin differ diff --git a/build/tools/makenorfirm/test/wram_rbin/Makefile b/build/tools/makenorfirm/test/wram_rbin/Makefile new file mode 100644 index 0000000..f0ecbed --- /dev/null +++ b/build/tools/makenorfirm/test/wram_rbin/Makefile @@ -0,0 +1,48 @@ +#! make -f +#---------------------------------------------------------------------------- +# Project: TwlFirm - tools - norfirm-print +# File: Makefile +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#---------------------------------------------------------------------------- + +SUBDIRS = + +LINCLUDES = ../include + +#---------------------------------------------------------------------------- + +TARGET_BIN = wram_regs.rbin + +SRCS = \ + wram_regs.c \ + +#SRCDIR = # using default +#LCFILE = # using default + + +include $(TWLIPL_ROOT)/build/buildtools/commondefs + +INSTALL_DIR = . +INSTALL_TARGETS = $(BINDIR)/$(TARGET_BIN) + + +#---------------------------------------------------------------------------- + +do-build: $(TARGETS) + + +include $(TWLIPL_ROOT)/build/buildtools/modulerules + + +#===== End of Makefile ===== diff --git a/build/tools/makenorfirm/test/wram_rbin/wram_regs.c b/build/tools/makenorfirm/test/wram_rbin/wram_regs.c new file mode 100644 index 0000000..d2cdda9 --- /dev/null +++ b/build/tools/makenorfirm/test/wram_rbin/wram_regs.c @@ -0,0 +1,89 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include +#include + +MIHeader_WramRegs wram_regs = +{ + // ARM9 + { + REG_WRAM_A_BNK_PACK(0, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_0KB, TRUE), + REG_WRAM_A_BNK_PACK(1, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_64KB, TRUE), + REG_WRAM_A_BNK_PACK(2, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_128KB, TRUE), + REG_WRAM_A_BNK_PACK(3, MI_WRAM_A_ARM7, MI_WRAM_A_OFS_192KB, TRUE), + }, + { + REG_WRAM_B_BNK_PACK(0, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_0KB, TRUE), + REG_WRAM_B_BNK_PACK(1, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_32KB, TRUE), + REG_WRAM_B_BNK_PACK(2, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_64KB, TRUE), + REG_WRAM_B_BNK_PACK(3, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_96KB, TRUE), + REG_WRAM_B_BNK_PACK(4, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_128KB, TRUE), + REG_WRAM_B_BNK_PACK(5, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_160KB, TRUE), + REG_WRAM_B_BNK_PACK(6, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_192KB, TRUE), + REG_WRAM_B_BNK_PACK(7, MI_WRAM_B_ARM7, MI_WRAM_B_OFS_224KB, TRUE), + }, + { + REG_WRAM_C_BNK_PACK(0, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_0KB, TRUE), + REG_WRAM_C_BNK_PACK(1, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_32KB, TRUE), + REG_WRAM_C_BNK_PACK(2, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_64KB, TRUE), + REG_WRAM_C_BNK_PACK(3, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_96KB, TRUE), + REG_WRAM_C_BNK_PACK(4, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_128KB, TRUE), + REG_WRAM_C_BNK_PACK(5, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_160KB, TRUE), + REG_WRAM_C_BNK_PACK(6, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_192KB, TRUE), + REG_WRAM_C_BNK_PACK(7, MI_WRAM_C_ARM9, MI_WRAM_C_OFS_224KB, TRUE), + }, + REG_WRAM_A_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_A_IMG_128KB + ), + REG_WRAM_B_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_B_IMG_128KB + ), + REG_WRAM_C_MAP_PACK(HW_WRAM_AREA_HALF, + HW_WRAM_AREA_HALF + 0x00020000, + MI_WRAM_C_IMG_128KB + ), + + // ARM7 + REG_WRAM_A_MAP_PACK(HW_WRAM_AREA_HALF, + HW_WRAM_AREA_HALF + 0x00020000, + MI_WRAM_A_IMG_128KB + ), + REG_WRAM_B_MAP_PACK(HW_WRAM_AREA_HALF + 0x00020000, + HW_WRAM_AREA_HALF + 0x00040000, + MI_WRAM_B_IMG_128KB + ), + REG_WRAM_C_MAP_PACK(MI_WRAM_MAP_NULL, + MI_WRAM_MAP_NULL, + MI_WRAM_C_IMG_128KB + ), + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + MI_WRAM_ARM7_ALL, + + // VRAM-C + 7, + // VRAM-D + 7, +}; diff --git a/build/tools/makenorfirm/wram_regs.c b/build/tools/makenorfirm/wram_regs.c new file mode 100644 index 0000000..68ed468 --- /dev/null +++ b/build/tools/makenorfirm/wram_regs.c @@ -0,0 +1,96 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - tools - makenorfirm + File: wram_regs.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#include "format_rom.h" +//#define SDK_ASM +#define NITRO_TYPES_H_ +#include +#include +#include + + +MIHeader_WramRegs wram_regs_init = +{ + // ARM9 + { + REG_MI_MBK_A0_FIELD( 1, MI_WRAM_A_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A1_FIELD( 1, MI_WRAM_A_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_A2_FIELD( 1, MI_WRAM_A_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_A3_FIELD( 1, MI_WRAM_A_OFFSET_192KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_B0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM7 ), + REG_MI_MBK_B4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM7 ), + REG_MI_MBK_B7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM7 ), + }, + { + REG_MI_MBK_C0_FIELD( 1, MI_WRAM_BC_OFFSET_0KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C1_FIELD( 1, MI_WRAM_BC_OFFSET_32KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C2_FIELD( 1, MI_WRAM_BC_OFFSET_64KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C3_FIELD( 1, MI_WRAM_BC_OFFSET_96KB , MI_WRAM_ARM9 ), + REG_MI_MBK_C4_FIELD( 1, MI_WRAM_BC_OFFSET_128KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C5_FIELD( 1, MI_WRAM_BC_OFFSET_160KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C6_FIELD( 1, MI_WRAM_BC_OFFSET_192KB, MI_WRAM_ARM9 ), + REG_MI_MBK_C7_FIELD( 1, MI_WRAM_BC_OFFSET_224KB, MI_WRAM_ARM9 ), + }, + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, MI_WRAM_MAP_NULL ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, HW_WRAM_AREA_HALF ) + ), + + // ARM7 + REG_MI_MBK6_FIELD( REG_WRAM_MAP_CONV_ADDR( 6, A, EADDR, HW_WRAM_AREA_HALF + 0x00020000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 6, A, SADDR, HW_WRAM_AREA_HALF ) + ), + REG_MI_MBK7_FIELD( REG_WRAM_MAP_CONV_ADDR( 7, B, EADDR, HW_WRAM_AREA_HALF + 0x00040000 ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 7, B, SADDR, HW_WRAM_AREA_HALF + 0x00020000 ) + ), + REG_MI_MBK8_FIELD( REG_WRAM_MAP_CONV_ADDR( 8, C, EADDR, MI_WRAM_MAP_NULL ), + MI_WRAM_IMAGE_128KB, + REG_WRAM_MAP_CONV_ADDR( 8, C, SADDR, MI_WRAM_MAP_NULL ) + ), + + // WRAM Lock + { + 0, + 0, + 0, + }, + + // WRAM-0/1 + 3, + + // VRAM-C + 7, + // VRAM-D + 7, +}; + diff --git a/doc/NORフラッシュマップ.xls b/doc/NORフラッシュマップ.xls new file mode 100644 index 0000000..4efbd6b Binary files /dev/null and b/doc/NORフラッシュマップ.xls differ diff --git a/doc/SystemMenu_REDリリース.txt b/doc/SystemMenu_REDリリース.txt new file mode 100644 index 0000000..dbb4b2c --- /dev/null +++ b/doc/SystemMenu_REDリリース.txt @@ -0,0 +1,55 @@ +SystemMenu_RED + + +11/16() 1st.[X\ + +E`[ + EJ[hAv擾 ~ + ENANDAvXg擾 + ETWLJ[hN ~ + ENTRJ[hiNTR[hjN ~ + ENANDAvN ij + EJ[h} ~ + EISfobKΉ ~ + Et@[EFAƂĐK ~ + EAvNWRAM-MAPݒ ~ + EEÍ ~ + EǗ ~ + E}bvFIX ~ + ENTRR|[lgpb` ~ +E{̐ݒ + EI + ETP␳ + EtEݒ + E[U[ ~ + Ȇݒ ~ + ENANDւ̕ۑ + ENTR(NVRAM)ւ̕ۑ + Eݒf[^tH[}bgFIX ~ +EWiFiݒ ~ +EDS_E[hvC ~ +Elbg[NAbvf[g ~ +EAvǗ ~ + ESDɃRs[ۂ̃t@CtH[}bg~ + +ENANDt@[`[p[^n ~ + EAhXFIX ~ +E`[NANDAvԃp[^n ~ + E{̐ݒf[^Ȃǂ̏ ~ + ENAND,SD}EgiANZXj ~ + EAvHWZbgp[^ ~ + EDS_E[hvC̏ ~ +ENANDI[o[CFS ~ +EL\[XANZX ~ +E^CgO\[XANZX ~ +ENANDAvfobOΉ ~@iJ[hAvƂăfobOj + +ENANDAvCXg[ @iTwlSDKNMenugpj +ENANDtH[}bg iTwlSDKdemos.TWL/fatfs/formattergpj + +Emakerom.TWLΉ + Ewb_TwlSDK̋L + ETitleIDH + Et@[prhiPKIsgpAAESÍ͈͕ύXjɑΉ + ETWLJ[h̃m[}̈}jAݒł悤ɁB + diff --git a/doc/TWL-NANDファーム二重化.vsd b/doc/TWL-NANDファーム二重化.vsd new file mode 100644 index 0000000..7cb4d95 Binary files /dev/null and b/doc/TWL-NANDファーム二重化.vsd differ diff --git a/doc/TWL_SystemMenuメモリマップ.vsd b/doc/TWL_SystemMenuメモリマップ.vsd new file mode 100644 index 0000000..db99946 Binary files /dev/null and b/doc/TWL_SystemMenuメモリマップ.vsd differ diff --git a/doc/TWL_staticModule.xls b/doc/TWL_staticModule.xls new file mode 100644 index 0000000..2921a9b Binary files /dev/null and b/doc/TWL_staticModule.xls differ diff --git a/doc/TWLフォルダツリー&NUP.vsd b/doc/TWLフォルダツリー&NUP.vsd new file mode 100644 index 0000000..b59bf8d Binary files /dev/null and b/doc/TWLフォルダツリー&NUP.vsd differ diff --git a/doc/rom_header_format.xls b/doc/rom_header_format.xls new file mode 100644 index 0000000..1e68fb5 Binary files /dev/null and b/doc/rom_header_format.xls differ diff --git a/include/.DS_Store b/include/.DS_Store new file mode 100644 index 0000000..804f2d4 Binary files /dev/null and b/include/.DS_Store differ diff --git a/include/firm.h b/include/firm.h new file mode 100644 index 0000000..37ccbca --- /dev/null +++ b/include/firm.h @@ -0,0 +1,35 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm + File: firm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_H_ +#define FIRM_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include +/* +#include +#include +*/ + +/* FIRM_H_ */ +#endif diff --git a/include/firm/.DS_Store b/include/firm/.DS_Store new file mode 100644 index 0000000..40cfa8d Binary files /dev/null and b/include/firm/.DS_Store differ diff --git a/include/firm/acsign.h b/include/firm/acsign.h new file mode 100644 index 0000000..f275754 --- /dev/null +++ b/include/firm/acsign.h @@ -0,0 +1,33 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - ACSIGN + File: acsign.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_ACSIGN_H_ +#define FIRM_ACSIGN_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_ACSIGN_H_ */ +#endif diff --git a/include/firm/aes.h b/include/firm/aes.h new file mode 100644 index 0000000..0f479d2 --- /dev/null +++ b/include/firm/aes.h @@ -0,0 +1,28 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - include - AES + File: aes.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_AES_H_ +#define FIRM_AES_H_ + +#ifdef SDK_ARM7 +#include +#include +#include +#include +#endif // SDK_ARM7 + +/* FIRM_AES_H_ */ +#endif diff --git a/include/firm/aes/ARM7/aes_ids.h b/include/firm/aes/ARM7/aes_ids.h new file mode 100644 index 0000000..3969442 --- /dev/null +++ b/include/firm/aes/ARM7/aes_ids.h @@ -0,0 +1,42 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirmSDK - AES - include + File: aes_ids.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef TWL_AES_AES_IDS_H_ +#define TWL_AES_AES_IDS_H_ + +#define AES_IDS_ID0_A (('N' << 0) | ('i' << 8) | ('n' << 16) | ('t' << 24)) +#define AES_IDS_ID0_B (('e' << 0) | ('n' << 8) | ('d' << 16) | ('o' << 24)) +#define AES_IDS_ID0_C(c) (((unsigned long)c[0] << 0) | ((unsigned long)c[1] << 8) | ((unsigned long)c[2] << 16) | ((unsigned long)c[3] << 24)) +#define AES_IDS_ID0_D(c) (((unsigned long)c[3] << 0) | ((unsigned long)c[2] << 8) | ((unsigned long)c[1] << 16) | ((unsigned long)c[0] << 24)) + +#define AES_IDS_ID1_A(c) (((unsigned long)c[3] << 0) | ((unsigned long)c[1] << 8) | ((unsigned long)c[2] << 16) | ((unsigned long)c[0] << 24)) +#define AES_IDS_ID1_B(c) (((unsigned long)c[0] << 0) | ((unsigned long)c[2] << 8) | ((unsigned long)c[1] << 16) | ((unsigned long)c[3] << 24)) +#define AES_IDS_ID1_C (*(unsigned long*)0x04004d04) +#define AES_IDS_ID1_D (*(unsigned long*)0x04004d00) + +#define AES_IDS_ID2_A (('N' << 0) | ('i' << 8) | ('n' << 16) | ('t' << 24)) +#define AES_IDS_ID2_B (('e' << 0) | ('n' << 8) | ('d' << 16) | ('o' << 24)) +#define AES_IDS_ID2_C ((' ' << 0) | ('D' << 8) | ('S' << 16) | ('\0' << 24)) +#define AES_IDS_ID2_D ((0x01 << 0) | (0x23 << 8) | (0x21 << 16) | (0x00 << 24)) + +#define AES_IDS_ID3_A (*(unsigned long*)0x04004d00) +#define AES_IDS_ID3_B (('N' << 0) | ('I' << 8) | ('N' << 16) | ('T' << 24)) +#define AES_IDS_ID3_C (('E' << 0) | ('N' << 8) | ('D' << 16) | ('O' << 24)) +#define AES_IDS_ID3_D (*(unsigned long*)0x04004d04) + +/* TWL_AES_AES_IDS_H_ */ +#endif diff --git a/include/firm/aes/ARM7/aes_init.h b/include/firm/aes/ARM7/aes_init.h new file mode 100644 index 0000000..00150c7 --- /dev/null +++ b/include/firm/aes/ARM7/aes_init.h @@ -0,0 +1,35 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - AES - include + File: aes_init.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef TWL_AES_AES_INIT_H_ +#define TWL_AES_AES_INIT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + ֐` + *---------------------------------------------------------------------------*/ +void AESi_InitGameKeys( u8 game_code[4] ); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* TWL_AES_AES_INIT_H_ */ +#endif diff --git a/include/firm/aes/ARM7/aes_util.h b/include/firm/aes/ARM7/aes_util.h new file mode 100644 index 0000000..3f36a08 --- /dev/null +++ b/include/firm/aes/ARM7/aes_util.h @@ -0,0 +1,35 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - AES - include + File: aes_util.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef TWL_AES_AES_UTIL_H_ +#define TWL_AES_AES_UTIL_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + ֐` + *---------------------------------------------------------------------------*/ +void AESi_AddCounter(AESCounter* pCounter, u32 nums); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* TWL_AES_AES_UTIL_H_ */ +#endif diff --git a/include/firm/fatfs.h b/include/firm/fatfs.h new file mode 100644 index 0000000..2d6cc20 --- /dev/null +++ b/include/firm/fatfs.h @@ -0,0 +1,28 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - fatfs + File: fatfs.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_FATFS_H_ +#define FIRM_FATFS_H_ + +#ifdef SDK_ARM7 +#include +#include +#endif // SDK_ARM7 + + +/* FIRM_FATFS_H_ */ +#endif diff --git a/include/firm/fatfs/ARM7/fatfs_firm.h b/include/firm/fatfs/ARM7/fatfs_firm.h new file mode 100644 index 0000000..23badb9 --- /dev/null +++ b/include/firm/fatfs/ARM7/fatfs_firm.h @@ -0,0 +1,79 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - fatfs + File: fatfs.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_FATFS_FATFS_FIRM_H_ +#define FIRM_FATFS_FATFS_FIRM_H_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + Name: FATFS_EnableAES + + Description: enable AES data path + + Arguments: counter initial counter value + + Returns: None + *---------------------------------------------------------------------------*/ +void FATFS_EnableAES( const AESCounter* pCounter ); + +/*---------------------------------------------------------------------------* + Name: FATFS_DisableAES + + Description: bypass AES + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void FATFS_DisableAES( void ); + +/*---------------------------------------------------------------------------* + Name: FATFS_InitFIRM + + Description: init file system + + Arguments: nandContext : nand context to omit initialization (if any) + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_InitFIRM( void* nandContext ); + +/*---------------------------------------------------------------------------* + Name: FATFS_MountDriveFIRM + + Description: mount nand partition + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_MountDriveFIRM( int driveno, FATFSMediaType media, int partition_no ); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +/* FIRM_FATFS_FATFS_FIRM_H_ */ +#endif diff --git a/include/firm/fatfs/ARM7/fatfs_loader.h b/include/firm/fatfs/ARM7/fatfs_loader.h new file mode 100644 index 0000000..74b80d8 --- /dev/null +++ b/include/firm/fatfs/ARM7/fatfs_loader.h @@ -0,0 +1,89 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - fatfs + File: fatfs_loader.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_FATFS_FATFS_LOADER_H_ +#define FIRM_FATFS_FATFS_LOADER_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + Name: FATFS_OpenRecentMenu + + Description: open recent menu file + + Arguments: driveno drive number ('A' is 0) + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_OpenRecentMenu( int driveno ); + +/*---------------------------------------------------------------------------* + Name: FATFS_OpenSpecifiedSrl + + Description: open specified menu file + + Arguments: menufile target filename + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL FATFS_OpenSpecifiedSrl( const char* menufile ); + +/*---------------------------------------------------------------------------* + Name: FATFS_LoadHeader + + Description: load menu header + + Arguments: None + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL FATFS_LoadHeader( void ); + +/*---------------------------------------------------------------------------* + Name: FATFS_LoadStatic + + Description: load static binary + + Arguments: None + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL FATFS_LoadStatic( void ); + +/*---------------------------------------------------------------------------* + Name: FATFS_Boot + + Description: boot + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void FATFS_Boot( void ); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +/* FIRM_FATFS_FATFS_LOADER_H_ */ +#endif diff --git a/include/firm/format/firm_common.h b/include/firm/format/firm_common.h new file mode 100644 index 0000000..404ec28 --- /dev/null +++ b/include/firm/format/firm_common.h @@ -0,0 +1,67 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - format - firm + File: firm_common.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_FORMAT_FIRM_COMMON_H_ +#define FIRM_FORMAT_FIRM_COMMON_H_ + +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +// 풓W[ +typedef struct +{ + u32 rom_offset; /* ] ROM ItZbg */ + u32 decomp_size; /* WJTCY */ + void *ram_address; /* ] RAM ItZbg */ + u32 size; /* ]TCY */ +} +FIRMHeader_ModuleInfo; + +// DS-IPL2wb_ +typedef struct +{ + u16 reserved_0h[4]; + u32 ds_key; + u16 ds_arm9_romAdr; + u16 ds_arm9_ramAdr; + u16 ds_arm7_romAdr; + u16 ds_arm7_ramAdr; + u16 ds_arm9_romOffsetUnit:3; + u16 ds_arm9_ramOffsetUnit:3; + u16 ds_arm7_romOffsetUnit:3; + u16 ds_arm7_ramOffsetUnit:3; + u16 :2; + u16 ds_header_ver:2; + u16 ds_data_romAdr; + u64 card_key; + u16 ncd_romAdr; + u16 reserved_24h[2]; + u16 ds_data_crc16; +} +NORHeaderDS; + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif // FIRM_FORMAT_FIRM_COMMON_H_ diff --git a/include/firm/format/format_rom.h b/include/firm/format/format_rom.h new file mode 100644 index 0000000..33309be --- /dev/null +++ b/include/firm/format/format_rom.h @@ -0,0 +1,532 @@ +/*---------------------------------------------------------------------------* + Project: TwlSDK - tools - makerom.TWL + File: format_rom.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FORMAT_ROM_H_ +#define FORMAT_ROM_H_ + +//#include "misc.h" +//#include "format_rom_certificate.h" +//#include "acsign/include/acsign.h" +//#include "aes/include/aes2.h" +#include +#include + + +//#define ENABLE_OVERLAY_DIGEST_ANNEX // ̒`LȂAOverlaỹ_CWFXgcompstaticMBp̂̂Ƃ͕ʓr‚悤ɂȂB + +#define ROM_KEYTABLE2_SIZE 0x3000 // TWL-ROMTWLp̈擪ɂL[e[uQTCYBTWLp̈̃ZLÄ́Ǎ납JnB +#define ROM_TWL_LTD_ALIGN 0x80000 // TWL-ROMTWLp̈̐ݒPʁ@dl512KB +#define ROM_TWL_LTD_ALIGN_SHIFT 19 // L̒PʂrbgVtgɊZ +#define ROM_TWL_ALL_NORMAL_AREA_FLAG 0x8000 + +#define DS_DLPLAY_SIGNATURE_PADDING_SIZE 512 // DS_E[hvCi[GATCY + +#define DIGEST_SIZE_SHA1 20 + +#define DEFAULT_ALIGN 512 +#define DEFAULT_HOSTROOT "." +#define DEFAULT_ROOT "/" +#define DEFAULT_ROMHEADER_TEMPLATE "rom_header.template.sbin" +#define DEFAULT_ROMHEADER_SURFFIX "_header.sbin" +#define DEFAULT_FILENAME_SURFFIX "_files.sbin" + +#define DEFAULT_REJECT { "CVS", "vssver.scc", ".?*", 0/*Terminater*/ } +#define DEFAULT_REJECT_CONSERVATIVE { "CVS", "vssver.scc", 0/*Terminater*/ } + +#define FORMAT_VERSION "1.1" + +#define ENTRYNAME_MAX 127 + +#define FILE_ID_START 0x0000 +#define FILE_ID_END 0xefff +#define DIR_ID_START 0xf000 +#define DIR_ID_END 0xffff + +#define DEFAULT_LISTFILE "default.nlf" + +#define DEFAULT_ROMFILE_SUFFIX ".srl" +#define DEFAULT_LISTFILE_SUFFIX ".nlf" +#define DEFAULT_LISTFILE_SUFFIX_TWL ".tlf" + +#define ROM_SIZE_MIN 0x20000 + +#define CRC16_INIT_VALUE 0xffff +#define CALC_CRC16_SIZE 0x15e + +#define SECURE_AREA_START 0x00004000 +#define SECURE_AREA_END 0x00008000 +#define SECURE_AREA_SIZE (SECURE_AREA_END - SECURE_AREA_START) + +#define CARD_LATENCY_MASK 0x083f1fff +#define CARD_MROM_GAME_LATENCY 0x00010017 +#define CARD_MROM_SECURE_HW_LATENCY 0x001808f8 +#define CARD_MROM_SECURE_SW_LATENCY 0x051e +#define CARD_1TROM_GAME_LATENCY 0x00010657 +#define CARD_1TROM_SECURE_HW_LATENCY 0x081808f8 +#define CARD_1TROM_SECURE_SW_LATENCY 0x0d7e + +// for out_romheader.c size check +#define BOOTABLE_SIZE_ARM9 0x00280000 // 2.5M +#define BOOTABLE_SIZE_ARM7 0x00040000 // 256K + +/*===========================================================================* + * ROM FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// Section A ROM HEADER +//--------------------------------------------------------------------------- + +#define ROMHEADER_CORP_ID "NINTENDO " +#define TITLE_NAME_MAX 12 +#define GAME_CODE_MAX 4 +#define MAKER_CODE_MAX 2 + +typedef struct ROM_Header_Short +{ + //========================================================== + // + // NTR/TWL common + // + //========================================================== + + // + // 0x000 System Reserved + // + char title_name[TITLE_NAME_MAX]; // Soft title name + char game_code[GAME_CODE_MAX]; // Game code + char maker_code[MAKER_CODE_MAX]; // Maker code + char platform_code; // Platform code bit0: not support NTR, bit1: support TWL ( NTR_only=0x00, NTR/TWL=0x03, TWL_only=0x02 ) + u8 rom_type; // Rom type + u8 rom_size; // Rom size (2rom_size Mbit: ex. 128Mbit̂Ƃrom_size = 7) + + u8 reserved_A[7]; // System Reserved A ( Set ALL 0 ) + + u8 enable_signature:1; // enable ROM Header signature + u8 enable_aes:1; // enable AES encryption + u8 developer_encrypt:1; // JpZLeBĂꍇ"1"Biłł"0" + u8: 5; + + u8: 6; + u8 for_korea:1; // For Korea + u8 for_china:1; // For China + + u8 rom_version; // Rom version + + u8 comp_arm9_boot_area:1; // Compress arm9 boot area + u8 comp_arm7_boot_area:1; // Compress arm7 boot area + u8 inspect_card:1; // Show inspect card + u8 disable_clear_memory_pad:1; // for Debugger + u8 enable_twl_rom_cache_read:1; // Enable TWL ROM cacheRead command + u8: 1; + u8 warning_no_spec_rom_speed:1;// Warning not to specify rom speed + u8 disable_detect_pull_out:1; // + + // + // 0x020 for Static modules (Section:B) + // + // ARM9 + u32 main_rom_offset; // ROM offset + void *main_entry_address; // Entry point + void *main_ram_address; // RAM address + u32 main_size; // Module size + + // ARM7 + u32 sub_rom_offset; // ROM offset + void *sub_entry_address; // Entry point + void *sub_ram_address; // RAM address + u32 sub_size; // Module size + + // + // 0x040 for File Name Table[FNT] (Section:C) + // + struct ROM_FNT *fnt_offset; // ROM offset + u32 fnt_size; // Table size + + // + // 0x048 for File Allocation Table[FAT] (Section:E) + // + struct ROM_FAT *fat_offset; // ROM offset + u32 fat_size; // Table size + + // + // 0x050 for Overlay Tables[OVT] (Section:D) + // + // ARM9 + struct ROM_OVT *main_ovt_offset; // ROM offset + u32 main_ovt_size; // Table size + + // ARM7 + struct ROM_OVT *sub_ovt_offset; // ROM offset + u32 sub_ovt_size; // Table size + + // 0x060 for ROM control parameter (Section:F) + u32 game_cmd_param; // Game command parameter + u32 secure_cmd_param; // Secure command parameter + + u32 banner_offset; // Banner ROM offset + + u16 secure_area_crc16; // Secure area CRC-16 + u16 secure_cmd_latency; // Secure command latency ((param+2)*256 system cycles) + + // since NITRO-SDK 2.0PR4 + void *main_autoload_done; // ARM9 autoload done callback address (debug purpose) + void *sub_autoload_done; // ARM7 autoload done callback address (debug purpose) + + u8 ctrl_reserved_B[8]; // Ctrl Reserved B (Set 0) + + // since NITRO-SDK 2.0PR6 + u32 rom_valid_size; // ROM Original Size + u32 rom_header_size; // ROM Header size + u32 main_module_param_offset; // Offset for table of ARM9 module parameters + u32 sub_module_param_offset; // Offset for table of ARM7 module parameters + + // 0x090 - 0x0C0 System Reserved + u16 twl_card_normal_area_rom_offset; // undeveloped + u16 twl_card_keytable_area_rom_offset; // undeveloped + u16 nand_card_dl_area_rom_offset; // undeveloped + u16 nand_card_bk_area_rom_offset; // undeveloped + u8 nand_card_flag; // undeveloped + u8 reserved_B[39]; + + // 0x0C0 for NINTENDO logo data + u8 nintendo_logo[0x9c]; // NINTENDO logo data + u16 nintendo_logo_crc16; // CRC-16 + + // 0x15E ROM header CRC-16 + u16 header_crc16; // ROM header CRC-16 + + // 0x160 - 0x180 Debugger Reserved + u8 reserved_C[32]; // Debugger Reserved (Set ALL 0) + + //========================================================== + // + // TWL only + // + //========================================================== + + // 0x180 - 0x190 TWL-WRAM A/B/C ARM9 configuration data + u32 main_wram_config_data[8]; // developing... + + // 0x1A0 - 0x1B0 TWL-WRAM A/B/C ARM7 configuration data + u32 sub_wram_config_data[4]; // developing... + + // 0x1B0 - reserved. + u8 reserved_ltd_A[ 15 ]; + + // 0x1BF - TWL expansion flags + u8 codec_mode:1; // 0:NTR mode, 1:TWL mode // undeveloped + u8: 3; + u8 enable_boot_nand:1; // undeveloped + u8 enable_boot_sd_card:1; // undeveloped + u8 enable_boot_game_card:1; // undeveloped + u8 enable_boot_download_play:1; // undeveloped + + // 0x1C0 for EX Static modules + // + // ARM9 + u32 main_ltd_rom_offset; // ROM offset // undeveloped + u8 reserved_ltd_B[ 4 ]; + void *main_ltd_ram_address; // RAM address // undeveloped + u32 main_ltd_size; // Module size // undeveloped + + // ARM7 + u32 sub_ltd_rom_offset; // ROM offset // undeveloped + u8 reserved_ltd_C[ 4 ]; + void *sub_ltd_ram_address; // RAM address // undeveloped + u32 sub_ltd_size; // Module size // undeveloped + + // 0x01E0 - 0x01E8 for NITRO digest area offset & size + u32 nitro_digest_area_rom_offset; + u32 nitro_digest_area_size; + + // 0x01E8 - 0x01F0 for TWL digest area offset & size + u32 twl_digest_area_rom_offset; + u32 twl_digest_area_size; + + // 0x01F0 - 0x01F8 for FS digest table1 offset & size + u32 digest1_table_offset; + u32 digest1_table_size; + + // 0x01F8 - 0x0200 for FS digest table1 offset + u32 digest2_table_offset; + u32 digest2_table_size; + + // 0x0200 - 0x0208 for FS digest config parameters + u32 digest1_block_size; + u32 digest2_covered_digest1_num; + + // 0x0208 - 0x0210 for Banner for TWL + u32 banner_twl_offset; + u32 banner_twl_size; + + // 0x0210 - 0x0218 for TWL rom valid size + u32 twl_rom_valid_size; // ROM Original Size + u8 reserved_ltd_D[ 4 ]; + + // 0x0218 - 0x0220 for TWL ltd module param offset + u32 main_ltd_module_param_offset; // Offset for table of ARM9 ltd module parameters + u32 sub_ltd_module_param_offset; // Offset for table of ARM7 ltd module parameters + + // 0x0220 - 0x0230 for AES target offset & size + u32 aes_target_rom_offset; + u32 aes_target_size; + u8 reserved_ltd_E[ 8 ]; + + // 0x230 - 0x300 reserved. + u8 reserved_ltd_F[ 0x300 - 0x230 ]; + + // 0x300 - 0x378 Rom Segment Digest + u8 main_static_digest[ DIGEST_SIZE_SHA1 ]; + u8 sub_static_digest[ DIGEST_SIZE_SHA1 ]; + u8 digest2_table_digest[ DIGEST_SIZE_SHA1 ]; + u8 banner_twl_digest[ DIGEST_SIZE_SHA1 ]; + u8 main_ltd_static_digest[ DIGEST_SIZE_SHA1 ]; + u8 sub_ltd_static_digest[ DIGEST_SIZE_SHA1 ]; + + +#ifdef ENABLE_OVERLAY_DIGEST_ANNEX + // ͖B + // overlaỹ_CWFXǵAcompstaticstaticW[ɕtA + // DS_E[hvCp̃I[o[C_CWFXggp̂ŁAȂB + // ܂Aoverlay_ex́AoverlayƋʉ\Ȃ̂ŁAOVT_CWFXge[uȂB + u32 main_overlay_digest_table_offset; + u32 sub_overlay_digest_table_offset; + u8 main_overlay_digesttable_digest[ DIGEST_SIZE_SHA1 ]; + u8 sub_overlay_digesttable_digest[ DIGEST_SIZE_SHA1 ]; + +#endif // ENABLE_OVERLAY_DIGEST_ANNEX +} +ROM_Header_Short; + +typedef struct +{ + struct ROM_Header_Short s; + + //// + //// EXTRA SYSTEM REGION + //// + + // + // 0x02f0 - 0x0e00 System Reserved + // + u8 reserved_D[4 * 1024 - sizeof(ROM_Header_Short) - sizeof(RomCertificate) - RSA_KEY_LENGTH ]; // Reserved D + + // + // 0x0e00 - 0x0f80 ROM Certificate + // + RomCertificate certificate; + + // + // 0x0f80 - 0x1000 ROM Header Signature + // + u8 signature[ RSA_KEY_LENGTH ]; // PKCS#1_v1.5̌`ŃtH[}bgꂽSignatureDataARSAÍꂽ + + // + // 0x01000 - 0x04000 System Reserved + // + u8 reserved_E[12 * 1024]; // Reserved E + +} +ROM_Header; // 16KB + + + +// (ROM_Header.signature)̃f[^ +typedef struct SignatureData +{ + u8 aes_key_seed[ AES_BLOCK_SIZE ]; + u8 digest[ DIGEST_SIZE_SHA1 ]; +}SignatureData; + + + +//--------------------------------------------------------------------------- +// Section C FNT: FILE NAME TABLE +// - DIRECTORY TABLE +// - ENTRY TABLE +//--------------------------------------------------------------------------- + +typedef struct ROM_FNTDir +{ + u32 entry_start; // offset for entry + u16 entry_file_id; // file id for 1st file + u16 parent_id; // parent directory id + +} +ROM_FNTDir; + + +/* P-SEUDO CODE for YOUR INFO. +typedef struct ROM_FNTStrFile +{ + u8 entry_type :1; // 0 if file entry + u8 entry_name_length:7; // length of filename (0-127) + char entry_name[length]; // file name (surpress '\0') + +} ROM_FNTStrFile; + + +typedef struct ROM_FNTStrDir +{ + u8 entry_type :1; // 1 if directory entry + u8 entry_name_length:7; // length of directory name (0-127) + char entry_name[length]; // directory name (surpress '\0') + u8 dir_id_L; // low byte of directory id + u8 dir_id_H; // high byte of directory id +} ROM_FNTStrDir; +*/ + +//--------------------------------------------------------------------------- +// Section D OVT: OVERLAY TABLE +//--------------------------------------------------------------------------- + +typedef struct ROM_OVT +{ + void *id; // Overlay ID + void *ram_address; // ram address + u32 ram_size; // ram size + u32 bss_size; // bss size + void *sinit_init; // static initializer start + void *sinit_init_end; // static initializer end + u32 file_id; // file id in FAT + u32 compressed:24; // I[o[Ck̃TCY + u32 flag:8; // I[o[CtO + +} +ROM_OVT; + + +//--------------------------------------------------------------------------- +// Section E FAT: FILE ALLOCATION TABLE +//--------------------------------------------------------------------------- + +typedef struct ROM_FilePtr +{ + u32 offset; // offset + +} +ROM_FilePtr; + + +typedef struct ROM_FAT +{ + ROM_FilePtr top; // file region start + ROM_FilePtr bottom; // end + +} +ROM_FAT; + + +//--------------------------------------------------------------------------- +// Section F LT: ROM LATENCY +//--------------------------------------------------------------------------- + +typedef enum +{ + ONETROM = 0, + MROM +} +tRomSpeedType; + +typedef struct ROM_LT +{ + u32 game_latency; + u32 secure_hw_latency; + u16 secure_sw_latency; + +} +ROM_LT; + + +//--------------------------------------------------------------------------- +// Section X ONT: OVERLAY NAME TABLE (not include in ROM) generated by LD +// - OverlayDefs +//--------------------------------------------------------------------------- + +typedef struct ROM_ONTHeader +{ + void *static_ram_address; // static module ram_address + void *static_entry_address; // entry address + u32 static_size; // size + void *static_autoload_done; // autoload done callback address + +} +ROM_ONTHeader; + +typedef struct ROM_ONT +{ + ROM_ONTHeader header; + char file_list[1]; + +} +ROM_ONT; + +#define SIZE_OF_SIGN 136 +#define NITROCODE_LE 0x2106c0de +#define NITROCODE_BE 0xdec00621 +#define TWLCODE_LE 0x6314c0de +#define TWLCODE_BE 0xdec01463 + +//--------------------------------------------------------------------------- +// Section Y MDP: Module params +//--------------------------------------------------------------------------- +typedef struct tModuleParam +{ + void *autoload_list; + void *autoload_list_end; + void *autoload_start; + void *static_bss_start; + void *static_bss_end; + void *compressed_static_end; // tCompFooter 1vfw + u32 version; + u32 nitro_magic_be; + u32 nitro_magic_le; + +} +tModuleParam; + +typedef struct tLtdModuleParam +{ + void *autoload_list; + void *autoload_list_end; + void *autoload_start; + void *compressed_static_end; // tCompFooter 1vfw + u32 twl_magic_be; + u32 twl_magic_le; +} +tLtdModuleParam; + + +typedef struct +{ + u32 bufferTop:24; + u32 compressBottom:8; + u32 originalBottom; +} +tCompFooter; + +typedef struct // compstatic/component.h蔲 +{ + u32 magicNumber; // Fq ==MAGICNUMBER_FOOTER + int staticParamsOffset; // StaticParams ւ̃ItZbg + int digestParamsOffset; // SDK_DIGEST_TABLE ւ̃ItZbg + int ltdStaticParamsOffset; // LtdStaticParams ւ̃ItZbg +} +StaticFooter; + +#endif //FORMAT_ROM_H_ diff --git a/include/firm/format/format_rom_certificate.h b/include/firm/format/format_rom_certificate.h new file mode 100644 index 0000000..859d40a --- /dev/null +++ b/include/firm/format/format_rom_certificate.h @@ -0,0 +1,50 @@ +/*---------------------------------------------------------------------------* + Project: TwlSDK - tools - makerom.TWL + File: format_rom_certificate.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FORMAT_ROM_CERTIFICATE_H_ +#define FORMAT_ROM_CERTIFICATE_H_ + +//#include "misc.h" + +/*===========================================================================* + * ROM CERTIFICATE FORMAT + *===========================================================================*/ + +#define TWL_ROM_CERT_MAGIC_NUMBER 0x54524543 // "CERT"̕ + +#define RSA_KEY_LENGTH ( 1024 / 8 ) +#define ROM_CERT_SIGN_OFFSET 256 + +#define ROM_HEADER_SIGN_TARGET_SIZE 0xe00 + +// ROMؖwb_ +typedef struct RomCertificateHeader { + u32 magicNumber; + u32 version; + u32 serialNo; + u32 gameCode; +}RomCertificateHeader; + +// ROMؖ +typedef struct RomCertificate { + RomCertificateHeader header; + u8 reserved[ ROM_CERT_SIGN_OFFSET - sizeof(RomCertificateHeader) - RSA_KEY_LENGTH ]; + u8 pubKeyMod[ RSA_KEY_LENGTH ]; + u8 sign[ RSA_KEY_LENGTH ]; +}RomCertificate; + +#endif //FORMAT_ROM_CERTIFICATE_H_ diff --git a/include/firm/format/from_brom.h b/include/firm/format/from_brom.h new file mode 100644 index 0000000..cad8390 --- /dev/null +++ b/include/firm/format/from_brom.h @@ -0,0 +1,100 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - format - from_brom + File: from_brom.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_FORMAT_FROM_BROM_H_ +#define FIRM_FORMAT_FROM_BROM_H_ + +#include +#include +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SDK_ARM9 +#define RSA_PUBKEY_NUM_FROM_BROM 8 +#define AESKEY_NUM_FROM_BROM 8 +#else // SDK_ARM7 +#define RSA_PUBKEY_NUM_FROM_BROM 4 +#define AESKEY_NUM_FROM_BROM 4 +#endif // SDK_ARM7 + + +// sizeof(SDPortContext) +typedef struct SDportContextData +{ + u32 data[17]; +} +SDPortContextData; + + +typedef struct +{ + union + { + NANDHeader nand; + NORHeader nor; + GCDHeader gcd; + u8 max[0x400]; + } + header; // 1KB + + u8 rsa_pubkey[RSA_PUBKEY_NUM_FROM_BROM][ACS_PUBKEY_LEN]; // 1KB + u8 aes_key[AESKEY_NUM_FROM_BROM][ACS_AES_LEN]; // 128B + u8 hash_table_hash[ACS_HASH_LEN]; // 20B + + BLOWFISH_CTX ds_blowfish; // 4KB + + BLOWFISH_CTX twl_blowfish; // 4KB + +} +OSFromBrom9Buf; + +typedef struct +{ + union + { + NANDHeader nand; + NORHeader nor; + GCDHeader gcd; + u8 max[0x400]; + } + header; // 1KB + + u8 rsa_pubkey[RSA_PUBKEY_NUM_FROM_BROM][ACS_PUBKEY_LEN]; // 512B + u8 aes_key[AESKEY_NUM_FROM_BROM][ACS_AES_LEN]; // 64B + u8 hash_table_hash[ACS_HASH_LEN]; // 20B + + BLOWFISH_CTX twl_blowfish[2]; // (4KB + ) * 2 + + SDPortContextData SDNandContext; +} +OSFromBrom7Buf; + +#ifdef SDK_ARM9 +typedef OSFromBrom9Buf OSFromBromBuf; +#else // SDK_ARM7 +typedef OSFromBrom7Buf OSFromBromBuf; +#endif // SDK_ARM7 + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif // FIRM_FORMAT_FROM_BROM_H_ diff --git a/include/firm/format/gcdfirm.h b/include/firm/format/gcdfirm.h new file mode 100644 index 0000000..3e489a1 --- /dev/null +++ b/include/firm/format/gcdfirm.h @@ -0,0 +1,114 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - format - gcdfirm + File: gcdfirm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_FORMAT_GCDFIRM_H_ +#define FIRM_FORMAT_GCDFIRM_H_ + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*===========================================================================* + * NOR FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// Section A NOR HEADER +//--------------------------------------------------------------------------- + +// 풓W[ +typedef FIRMHeader_ModuleInfo GCDHeader_ModuleInfo; + +// TWL-GCDt@[wb_ +typedef struct +{ + /* 0x000-0x020 [VXe\̈] */ + u8 reserved_0h[0x14]; + u8 rom_size; // Rom size (2rom_size Mbit: ex. 128Mbit̂Ƃrom_size = 7) + u8 reserved_16h[0xb]; + + /* 0x020-0x040 [풓W[pp[^] */ + u32 main_rom_offset; /* ARM9 ] ROM ItZbg */ + u32 main_decomp_size; /* ARM9 WJTCY */ + void *main_ram_address; /* ARM9 ] RAM ItZbg */ + u32 main_size; /* ARM9 ]TCY */ + u32 sub_rom_offset; /* ARM7 ] ROM ItZbg */ + u32 sub_decomp_size; /* ARM9 WJTCY */ + void *sub_ram_address; /* ARM7 ] RAM ItZbg */ + u32 sub_size; /* ARM7 ]TCY */ + + /* 0x040-0x080 [VXe\̈] */ + u8 reserved_40h[0x40]; + + /* 0x080-0x090 [t@[oCi] */ + u32 nandfirm_offset; // address of rom_valid_size + u32 nandfirm_size; // address of rom_header_size + u32 norfirm_offset; // address of main_module_param + u32 norfirm_size; // address of sub_module_param + + /* 0x090-0x094 [TWL-ROMRg[] */ + u16 normal_area_offset; + u16 twl_area_offset; + + /* 0x094-0x0c0 [VXe\̈] */ + u8 reserved_98h[0x2c]; + + /* 0x0c0-0x100 [DSJ[hNINTENDOSd̈] */ + u8 reserved_C0h[0x3f]; + + u8 comp_arm9_boot_area:1; // Compress arm9 boot area + u8 comp_arm7_boot_area:1; // Compress arm7 boot area + u8 arm9_x2:1; + u8 :0; +} +GCDHeaderLow; + +typedef struct +{ + /* 0x180-0x1b0 [WRAMWX^p[^] */ + MIHeader_WramRegs w; + + /* 0x1b0-0x200 [VXe\̈] */ + u8 reserved_footer[0x50]; +} +GCDHeaderHigh; + +// GCDwb_ +typedef struct +{ + /* 0x000-0x100 */ + GCDHeaderLow l; + + /* 0x100-0x180 */ + FIRMPaddedSign sign; + + /* 0x180-0x200 */ + GCDHeaderHigh h; +} +GCDHeader; + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //FIRM_FORMAT_GCDFIRM_H_ diff --git a/include/firm/format/nandfirm.h b/include/firm/format/nandfirm.h new file mode 100644 index 0000000..68b9ad6 --- /dev/null +++ b/include/firm/format/nandfirm.h @@ -0,0 +1,131 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - format - nandfirm + File: nandfirm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_FORMAT_NAND_H_ +#define FIRM_FORMAT_NAND_H_ + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*===========================================================================* + * NAND FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// Section A NAND HEADER +//--------------------------------------------------------------------------- + +// 풓W[ +typedef FIRMHeader_ModuleInfo NANDHeader_ModuleInfo; + +// TWL-NANDt@[wb_ +typedef struct +{ + /* 0x000-0x020 [VXe\̈] */ + u8 reserved_0h[0x20]; /* VXe\ A */ + + /* 0x020-0x040 [풓W[pp[^] */ + u32 main_rom_offset; /* ARM9 ] ROM ItZbg */ + u32 main_decomp_size; /* ARM9 WJTCY */ + void *main_ram_address; /* ARM9 ] RAM ItZbg */ + u32 main_size; /* ARM9 ]TCY */ + u32 sub_rom_offset; /* ARM7 ] ROM ItZbg */ + u32 sub_decomp_size; /* ARM9 WJTCY */ + void *sub_ram_address; /* ARM7 ] RAM ItZbg */ + u32 sub_size; /* ARM7 ]TCY */ + + /* 0x040-0x0c0 [VXe\̈] */ + u8 reserved_40h[0x80]; + + /* 0x0c0-0x100 [DSJ[hNINTENDOSd̈] */ + u8 reserved_C0h[0x3f]; + + u8 comp_arm9_boot_area:1; // Compress arm9 boot area + u8 comp_arm7_boot_area:1; // Compress arm7 boot area + u8 arm9_x2:1; + u8 arm9_decomp:1; + u8 :0; +} +NANDHeaderLow; + +typedef struct +{ + /* 0x180-0x1b0 [WRAMWX^p[^] */ + MIHeader_WramRegs w; + + /* 0x1b0-0x200 [VXe\̈] */ + u8 reserved_footer[0x50]; +} +NANDHeaderHigh; + +// NANDwb_ +typedef struct +{ + /* 0x000-0x028 [DS-NORwb_] */ + NORHeaderDS d; + + /* 0x028-0x200 [VXe\̈(O)] */ + u8 reserved_mbr[512 - sizeof(NORHeaderDS)]; + + /* 0x200-0x300 */ + NANDHeaderLow l; + + /* 0x300-0x380 */ + FIRMPaddedSign sign; + + /* 0x380-0x400 */ + NANDHeaderHigh h; +} +NANDHeader; + +// 璷wb_ (璷) +typedef struct +{ + /* 0x400-0x500 *//* 0x600-0x700 */ + NANDHeaderLow l; + + /* 0x500-0x580 *//* 0x700-0x780 */ + FIRMPaddedSign sign; + + /* 0x580-0x600 *//* 0x780-0x800 */ + NANDHeaderHigh h; +} +NANDHeaderCore; + +// 璷wb_ (S) +typedef struct +{ + /* 0x000-0x400 [ۂɎgpwb_] */ + NANDHeader g; + /* 0x400-0x600 [ftHgʒuC[Wɑ΂wb_] */ + NANDHeaderCore o; + /* 0x600-0x800 [ꎞҔʒuC[Wɑ΂wb_] */ + NANDHeaderCore m; +} +NANDHeaderEx; + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //FIRM_FORMAT_NAND_H_ diff --git a/include/firm/format/norfirm.h b/include/firm/format/norfirm.h new file mode 100644 index 0000000..27587fa --- /dev/null +++ b/include/firm/format/norfirm.h @@ -0,0 +1,108 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - format - norfirm + File: norfirm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_FORMAT_NOR_H_ +#define FIRM_FORMAT_NOR_H_ + +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/*===========================================================================* + * NOR FORMAT + *===========================================================================*/ + +//--------------------------------------------------------------------------- +// Section A NOR HEADER +//--------------------------------------------------------------------------- + +// 풓W[ +typedef FIRMHeader_ModuleInfo NORHeader_ModuleInfo; + +// TWL-NORt@[wb_ +typedef struct +{ + /* 0x000-0x020 [VXe\̈] */ + u8 reserved_0h[0x20]; /* VXe\ A */ + + /* 0x020-0x040 [풓W[pp[^] */ + u32 main_rom_offset; /* ARM9 ] ROM ItZbg */ + u32 main_decomp_size; /* ARM9 WJTCY */ + void *main_ram_address; /* ARM9 ] RAM ItZbg */ + u32 main_size; /* ARM9 ]TCY */ + u32 sub_rom_offset; /* ARM7 ] ROM ItZbg */ + u32 sub_decomp_size; /* ARM9 WJTCY */ + void *sub_ram_address; /* ARM7 ] RAM ItZbg */ + u32 sub_size; /* ARM7 ]TCY */ + + /* 0x040-0x0c0 [VXe\̈] */ + u8 reserved_40h[0x80]; + + /* 0x0c0-0x100 [DSJ[hNINTENDOSd̈] */ + u8 reserved_C0h[0x3f]; + + u8 comp_arm9_boot_area:1; // Compress arm9 boot area + u8 comp_arm7_boot_area:1; // Compress arm7 boot area + u8 arm9_x2:1; + u8 arm9_decomp:1; + u8 :2; + u8 baudrate:1; + u8 boot_nandfirm:1; +} +NORHeaderLow; + +typedef struct +{ + /* 0x180-0x1b0 [WRAMWX^p[^] */ + MIHeader_WramRegs w; + + /* 0x1b0-0x200 [VXe\̈] */ + u8 reserved_footer[0x50]; +} +NORHeaderHigh; + +// NORwb_ +typedef struct +{ + /* 0x000-0x028 */ + NORHeaderDS d; + + /* 0x028-0x200 */ + u8 wl_params[472]; + + /* 0x200-0x300 */ + NORHeaderLow l; + + /* 0x300-0x380 */ + FIRMPaddedSign sign; + + /* 0x380-0x400 */ + NORHeaderHigh h; +} +NORHeader; + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //FIRM_FORMAT_NOR_H_ diff --git a/include/firm/format/sign.h b/include/firm/format/sign.h new file mode 100644 index 0000000..25887d7 --- /dev/null +++ b/include/firm/format/sign.h @@ -0,0 +1,95 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - format - sign + File: sign.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FORMAT_SIGN_H_ +#define FORMAT_SIGN_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + +// signed hash index +typedef enum +{ + FIRM_SIGNED_HASH_IDX_HEADER = 0, + FIRM_SIGNED_HASH_IDX_ARM9 = 1, + FIRM_SIGNED_HASH_IDX_ARM7 = 2, + FIRM_SIGNED_HASH_IDX_HASH_TABLE = 3, + FIRM_SIGNED_HASH_IDX_FINAL = 4, + + FIRM_SIGNED_HASH_NUM = 5 +} +FIRMSignedHashIndex; + + +#define ACS_BASE_BLOCK_SIZE 4096 // should be the multiple of 16 +#define ACS_META_BLOCK_SIZE 5120 // should be the multiple of 16 and the multiple of 20 + // would be the multiple of 512, then the mutilple of 2560 + +#define ACS_PUBKEY_LEN 128 +#define ACS_HASH_LEN 20 +#define ACS_AES_LEN 16 + +#define ACS_ENCRYPTED_HASH_LEN ACS_PUBKEY_LEN +#define ACS_DECRYPTED_HASH_LEN ACS_HASH_LEN + +#define ACS_RSA_EXP 0x00010001 +#define ACS_RSA_EXP_LEN 3 + +// DER format of RSA keys + +#define ACS_RSA_PRVMOD_OFFSET 0x0B +#define ACS_RSA_PRVEXP_OFFSET 0x93 +#define ACS_RSA_PRVMOD_LEN 128 +#define ACS_RSA_PRVEXP_LEN 128 + +#define ACS_RSA_PUBMOD_OFFSET 0x1D +#define ACS_RSA_PUBEXP_OFFSET 0x93 +#define ACS_RSA_PUBMOD_LEN 128 +#define ACS_RSA_PUBEXP_LEN ACS_RSA_EXP_LEN + +#define FIRM_HEADER_2ND_HASH_AREA_LEN (sizeof(FIRMSignedContext) - ACS_HASH_LEN) + + +// ReLXg +typedef struct +{ + unsigned char aes_key[ACS_AES_LEN]; + unsigned char hash[FIRM_SIGNED_HASH_NUM][ACS_HASH_LEN]; +} +FIRMSignedContext; + +// +typedef union +{ + struct + { + unsigned char prePad[(ACS_ENCRYPTED_HASH_LEN - sizeof(FIRMSignedContext))-1]; + FIRMSignedContext c; + unsigned char postPad[1]; + } + e; + unsigned int raw[ACS_ENCRYPTED_HASH_LEN/4]; +} +FIRMPaddedSign; + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //FORMAT_SIGN_H_ diff --git a/include/firm/format/wram_regs.h b/include/firm/format/wram_regs.h new file mode 100644 index 0000000..08c8d19 --- /dev/null +++ b/include/firm/format/wram_regs.h @@ -0,0 +1,85 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - MI - include + File: wram_regs.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_FORMAT_WRAM_REGS_H_ +#define FIRM_FORMAT_WRAM_REGS_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef enum +{ + MI_WRAM_A_OFFSET_0KB = 0, + MI_WRAM_A_OFFSET_64KB = 1, + MI_WRAM_A_OFFSET_128KB = 2, + MI_WRAM_A_OFFSET_192KB = 3 +} MIWramAOffset; + +typedef enum +{ + MI_WRAM_BC_OFFSET_0KB = 0, + MI_WRAM_BC_OFFSET_32KB = 1, + MI_WRAM_BC_OFFSET_64KB = 2, + MI_WRAM_BC_OFFSET_96KB = 3, + MI_WRAM_BC_OFFSET_128KB = 4, + MI_WRAM_BC_OFFSET_160KB = 5, + MI_WRAM_BC_OFFSET_192KB = 6, + MI_WRAM_BC_OFFSET_224KB = 7 +} MIWramBCOffset; + + +#define MI_WRAM_MAP_NULL HW_WRAM_AREA + +#define REG_WRAM_MAP_CONV_ADDR( regno, abc, border, addr ) \ +( \ + ((((addr) - HW_WRAM_AREA) / MI_WRAM_##abc##_SLOT_SIZE) & \ + (REG_MI_MBK##regno##_W##abc##_##border##_MASK >> \ + REG_MI_MBK##regno##_W##abc##_##border##_SHIFT)) \ +) + + +// WRAM}bsOWX^ +typedef struct +{ + u8 main_wrambnk_a[4]; // ARM9 SCFG_MBK1 + u8 main_wrambnk_b[8]; // ARM9 SCFG_MBK2-3 + u8 main_wrambnk_c[8]; // ARM9 SCFG_MBK4-5 + + u32 main_wrammap_a; // ARM9 SCFG_MBK6 + u32 main_wrammap_b; // ARM9 SCFG_MBK7 + u32 main_wrammap_c; // ARM9 SCFG_MBK8 + + u32 sub_wrammap_a; // ARM7 SCFG_MBK6 + u32 sub_wrammap_b; // ARM7 SCFG_MBK7 + u32 sub_wrammap_c; // ARM7 SCFG_MBK8 + + u8 sub_wramlock[3]; // ARM7 SCFG_MBK9 + + u8 main_wrambnk_01:2; // ARM9 RBKCNT1_H + u8 main_vrambnk_c:3; // ARM9 RBKCNT0_H + u8 main_vrambnk_d:3; // ARM9 RBKCNT0_H +} +MIHeader_WramRegs; + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_FORMAT_WRAM_REGS_H_ */ +#endif diff --git a/include/firm/gcd.h b/include/firm/gcd.h new file mode 100644 index 0000000..26593c55 --- /dev/null +++ b/include/firm/gcd.h @@ -0,0 +1,26 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - GCD + File: gcd.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_GCD_H_ +#define FIRM_GCD_H_ + +//#include +#include +#include + +/* FIRM_GCD_H_ */ +#endif diff --git a/include/firm/gcd/blowfish.h b/include/firm/gcd/blowfish.h new file mode 100644 index 0000000..bba522a --- /dev/null +++ b/include/firm/gcd/blowfish.h @@ -0,0 +1,42 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - GCD - include + File: blowfish.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_GCD_BLOWFISH_H +#define FIRM_GCD_BLOWFISH_H + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + u32 P[16 + 2]; + u32 S[4][256]; +} BLOWFISH_CTX; + + +void InitBlowfish(BLOWFISH_CTX *ctx, const unsigned char *key, int keyLen); +void EncryptByBlowfish(const BLOWFISH_CTX *ctx, u32 *xl, u32 *xr); +void DecryptByBlowfish(const BLOWFISH_CTX *ctx, u32 *xl, u32 *xr); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif // FIRM_GCD_BLOWFISH_H diff --git a/include/firm/gcd/gcd.h b/include/firm/gcd/gcd.h new file mode 100644 index 0000000..c910675 --- /dev/null +++ b/include/firm/gcd/gcd.h @@ -0,0 +1,779 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - GCD - include + File: gcd.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_GCD_GCD_H_ +#define FIRM_GCD_GCD_H_ + +#include +#include +#include +#include +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + GCD_PRIMARY_SLOT = 0, + GCD_SECONDARY_SLOT = 1, + + GCD_NO_SLOT = -1 +} +GCDSlot; + + +/*****************/ + +/* ROMwb_Eu[gp[^\ */ +typedef struct { + u8 *romAddr; // ROMAhX + u8 *entryAddr; // GgAhX + u8 *ramAddr; // RAMAhX + s32 romSize; // ROMTCY +} GCDBootUsrParam; + +// J[hANZXERg[WX^\ +typedef struct { + u16 latency1:13; // CeVP̃TCN + u16 dataScramble_on:1; // f[^XNu nm + u16 scrambleUnit_on:1; // XNuH nm + u16 initScramblePN:1; // XNuomf[^ + u16 latency2:6; // CeVQ̃TCN + u16 cmdScramble_on:1; // R}hXNu nm + u16 dataReady:1; // f[^ fB + u16 pages:3; // y[W + u16 clockType:1; // NbN^CviPTO^QSOj + u16 clockInLatency:1; // CeVԂɃNbN + u16 reset:1; // ZbgM + u16 accessMode:1; // ANZX[h + u16 start:1; // X^[g +} GCDCardCnt; + +// J[hRg[Ep[^\ +typedef struct { + // u32 dmaNo; // DMAԍ + u32 cardCnt; // J[hRg[ + u32 op[2]; // R}h +} GCDCardCtrlParam; + + +/* ROMwb_\ */ +typedef struct { + s8 titleName[12]; // \tg^Cg + u32 initialCode; // CjVR[h + + u16 makerCode; // [J[R[h + u8 machineCode; // {̃R[h + u8 deviceType; // foCX^Cv + + u8 nonVerReserved[4]; // \i4oCgj + u8 verDepReserved[4]; // \io[WˑA4oCgj + u16 wirelessSerialNo; + u16 softVersion:8; // \tgo[W + u16 compArm9BootArea:1; // ARM9u[gGAktO + u16 compArm7BootArea:1; // ARM7u[gGAktO + u16 :0; + + GCDBootUsrParam arm9; // ARM9u[g̈p[^ + GCDBootUsrParam arm7; // ARM7u[g̈p[^ + + u32 fileSysReserved[8]; // t@CVXe\i32oCgj + + GCDCardCnt romCtrl4Game; // ROMRg[iNORMAL & GAME[hj + GCDCardCnt romCtrl4Secure; // iSECURE[hj + u8 romCtrlReserved_l[4]; // \ + u16 secureCRC16; // ZLÄCRC16bit + u16 romTimerLatency; // ^C}[CeVi(TCN/256) - 2A3Dpj + u8 romReserved_h[8]; // \ + u32 romNormalModeKey[2]; // NORMAL[hL[ + + u8 reserved_80h[0x10]; // \̈i16oCgj + + u16 normalAreaOffset; // NORMAL̈ + u16 twlAreaOffset; // TWLp̈ + + u8 reserved_94h[0x2c]; // \̈i44oCgj + + u16 nintendoLogo[0x9c/2]; // NINTENDOSi156oCgj + u16 ninLogoCRC16; // NINTENDOSCRC16 + u16 headerCRC16; // wb_CRC16 + + u8 *dbgRomAddr; // fobKj^ROMAhX + s32 dbgRomSize; // fobKj^ROMTCY + u8 *dbgArm9RamAddr; // fobKj^ARM9-RAMAhX + u8 *dbgArm7RamAddr; // fobKj^ARM7-RAMAhX + + u8 reserved_170h[0x10]; // \̈i16oCgj +} +GCDRomHeaderDS; + +typedef struct { + // DS݊ + GCDRomHeaderDS l; + + // TWLg + MIHeader_WramRegs w; + + u8 reserved_1b0h[0x10]; // \̈i16oCgj + + GCDBootUsrParam arm9ex; // ARM9gu[g̈p[^ + GCDBootUsrParam arm7ex; // ARM7gu[g̈p[^ + + u8 reserved_1e0h[0x1000 - 0x1e0 - 0x200]; // \̈ + + u8 acsign_contents[0x180]; // Recؖ + + u8 acsign_header[0x80]; // ROMwb_dq +} +GCDRomHeader; + + +/* ZLA[N\ */ +typedef struct { + u8 recvRtcBuf[8]; // RTCf[^Mobt@iv4oCgEj +#if 0 + u16 flashCrc16; // tbVCRC16 + u16 flashCount; // tbV 8oCgJEg + u32 flashBuf[2]; // tbVMobt@iv4oCgEj + u32 flashKeyBuf[3]; // tbVL[Ee|obt@ +#endif + u32 unScrambleKey[2]; // XNuL[i8oCgAMakeBlowfishTable() ŎZoj + s16 isGenUnScrambleKey; // XNuL[iMakeBlowfishTable() Őݒj + + u32 va; // 24biti24bitMj + u32 vb; // 20biti+`4bitAVBI: 32bitMj + u32 vc_dummy; // 16biti16bitMj + u32 vd; // 24biti24bitMj + + GCDCardCnt cardCntBak4Secure; // SECURER}hp[^EobNAbv + s16 enableReadSecure; // SECURË惊[hECl[uiLoadSecure4Card() Őݒj + u32 cardNormalModeKey[2]; // NORMAL[hL[iMakeBlowfishTable() ŎZoj + u32 cardKeyBuf[3]; // J[hL[Ee|obt@ + s32 secureSize; // SECURËTCY + s16 sequenceNo4Secure; // V[PXԍiSECUREpj + s16 segmentTblShift; // ZOgԍe[uVtgliSECUREpj + u8 *segmentTblp; // ZOge[u|C^iSECUREpj + s16 numSecureSegment; // SECUREZOgiSECUREpj + s16 segmentOffset; // ZOgItZbgiSECUREpj + s16 blockOffset; // ubNItZbgiSECUREpj + + // CardCtrlParam paramBak; // J[hp[^ ÍOobNAbviSECUREpj + + BLOWFISH_CTX blowfishCardTable; // J[hpBlowfishe[u + BLOWFISH_CTX blowfishFlashTable; + + u8 bufEnd[4]; // ZLA[NŏIf[^ +} GCDSecureWork; + + +/* L[N\ */ +typedef struct { + u32 nCardID; // NORMALJ[hIDiLoadCardHeader() Ŏ擾j + u32 sCardID; // SECUREJ[hIDiCardTimerIntr4Secure() Ŏ擾j + u16 cardHeaderCrc16; // J[hwb_CRC16iLoadCardHeader() ŎZoj + u16 cardSecureCrc16; // J[hSECURËCRC16iLoadSecure4Card() ŎZoj + s16 cardHeaderError; // J[hwb_G[iCheckCardHeader() Őݒj + s16 disableEncryptedCardData;// J[hSECURËÍf[^iDecryptObjectFile() Őݒj + s16 cardSequenceNo; // J[hǂݍ݃V[PXԍ + s16 enableCardNormalOnly; // J[hNORMAL[ĥݗLiLoadFlashDemo() Őݒj + + // s16 isOnDebugger; // fobKœ쒆 + // s16 rtcError; // RTCG[ + + u32 recvRtc[2]; // RTCXe[^X1^C}[f[^iv4oCgEj + +} GCDSharedWork; + + +typedef union +{ + u64 dw; + u8 b[8]; +} +GCDCmd64; + +typedef struct +{ + u32 ctrl; + s32 cmdcount; + u32 latency; + u32 scramble; + u8 master; + u8 spi; + GCDSlot slot; +} +GCDCtrlRegs; + +typedef struct +{ + GCDCmd64 gcdOp; + u32 dmaNo; + u32 lastDmaNo; + BOOL ltckReq; + GCDCtrlRegs *gcdRegs; + GCDCtrlRegs nLoadTableRegs; + GCDCtrlRegs nSendOnlyOpRegs; + GCDCtrlRegs sSendOnlyOpRegs; + GCDCtrlRegs nIDRegs; + GCDCtrlRegs sIDRegs; + GCDCtrlRegs gIDRegs; + GCDCtrlRegs nReadShortHeaderRegs; + GCDCtrlRegs nReadRomRegs; + GCDCtrlRegs sReadRomRegs; + GCDCtrlRegs gReadRomRegs; + GCDCtrlRegs gWriteRomRegs; +} +GCDRomCtrls; + +typedef void (* GCDRomFuncp)( u32 romp, void *ramp, s32 size ); +typedef void (* GCDAsyncCoreFuncp)( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ); + + +typedef struct +{ + u32 romp; // ROM offset + u8 *ramp; // RAM address + s32 restSize; // rest size + s32 oneShotSize; // one shot size + vs8 intrDone; + s8 isAsync; + volatile BOOL isPxiDone; + GCDRomCtrls ctrls; + GCDAsyncCoreFuncp funcp; +} +GCDWork; + + +#define GCD_DEFAULT_DMA_A_NO 7 +#define GCD_DEFAULT_DMA_B_NO 6 + +#define GCD_CHATTERING_CYCLES 0x200U + +#define GCD_ROM_PAGE_SIZE 0x200 // 512B +#define GCD_SECURE_SEGMENT_SIZE 0x1000 // 4KB +#define GCD_LOAD_TABLE_SIZE 0x2000 // 8KB + +#define GCD_NML_AREA_ALIGN 0x80000 // 512KB +#define GCD_TWL_AREA_ALIGN 0x80000 // 512KB +#define GCD_SECURE2_AREA_SIZE 0x4000 // 16KB +#define GCD_SECURE2_AREA_OFFSET 0x3000 // 12KB +#define GCD_GAME2_AREA_OFFSET 0x7000 // 28KB + + +// ROM area + +#define GCD_LOAD_TABLE_SIZE 0x2000 // 8KB +#define GCD_DS_ROM_HEADER_SIZE 0x200 // 512B +#define GCD_ROM_HEADER_SIZE 0x1000 // 4KB +#define GCD_SECURE_AREA_SIZE 0x4000 // 16KB + +#define GCD_SECURE_AREA_OFFSET 0x4000 +#define GCD_GAME_AREA_OFFSET 0x8000 + + +// ROM command + +#define GCDOP_BIT_NUM 64 + +// NORMAL mode + +#define GCDOP_N_OP_MASK 0xff00000000000000ULL +#define GCDOP_N_OP_SIZE 8 + +#define GCDOP_N_OP_RD_ROM_ID 0x9000000000000000ULL +#define GCDOP_N_OP_RD_PAGE 0x0000000000000000ULL +#define GCDOP_N_OP_WR_PAGE 0x8000000000000000ULL +#define GCDOP_N_OP_LD_TABLE 0x9f00000000000000ULL +#define GCDOP_N_OP_CHG_MODE 0x3c00000000000000ULL +#define GCDOP_N_OP_CHG2_MODE 0x3d00000000000000ULL + +#define GCDOP_N_RD_ROM_ID_PAD 0x00ffffffffffffffULL +#define GCDOP_N_RD_PAGE_PAD 0x00fffffeff00ffffULL +#define GCDOP_N_CHG_MODE_PAD 0x00000000f00000ffULL +#define GCDOP_N_CHG2_MODE_PAD GCDOP_N_CHG_MODE_PAD + +#define GCDOP_N_RD_PAGE_ADDR_SHIFT 33 +#define GCDOP_N_RD_PAGE_ADDR_SIZE 23 +#define GCDOP_N_RD_PAGE_ADDR_MASK 0x00fffffe00000000ULL + +#define GCDOP_N_VAE_SHIFT 32 +#define GCDOP_N_VAE_SIZE 24 +#define GCDOP_N_VAE_MASK 0x00ffffff00000000ULL + +#define GCDOP_N_VBI_SHIFT 8 +#define GCDOP_N_VBI_SIZE 20 +#define GCDOP_N_VBI_MASK 0x000000000fffff00ULL + + +// SECURE mode + +#define GCDOP_S_OP_MASK 0xf000000000000000ULL +#define GCDOP_S_OP_SIZE 4 + +#define GCDOP_S_OP_RD_ROM_ID 0x1000000000000000ULL +#define GCDOP_S_OP_RD_SEGMENT 0x2000000000000000ULL +#define GCDOP_S_OP_PNG_ON 0x4000000000000000ULL +#define GCDOP_S_OP_PNG_OFF 0x6000000000000000ULL +#define GCDOP_S_OP_CHG_MODE 0xa000000000000000ULL + +#define GCDOP_S_VA_SHIFT GCDOP_S_VB_SIZE +#define GCDOP_S_VA_SIZE 24 +#define GCDOP_S_VA_MASK 0x00000ffffff00000ULL + +#define GCDOP_S_VB_SHIFT 0 +#define GCDOP_S_VB_SIZE 20 +#define GCDOP_S_VB_MASK 0x00000000000fffffULL + +#define GCDOP_S_VC_SHIFT (GCDOP_S_VA_SIZE + GCDOP_S_VB_SIZE) +#define GCDOP_S_VC_SIZE 16 +#define GCDOP_S_VC_MASK 0x0ffff00000000000ULL + +#define GCDOP_S_VD_SHIFT GCDOP_S_VA_SHIFT +#define GCDOP_S_VD_SIZE GCDOP_S_VA_SIZE +#define GCDOP_S_VD_MASK GCDOP_S_VA_MASK + + +// GAME mode + +#define GCDOP_G_OP_MASK 0xff00000000000000ULL +#define GCDOP_G_OP_SIZE 8 + +#define GCDOP_G_OP_RD_ROM_ID 0xb800000000000000ULL +#define GCDOP_G_OP_RD_ROM_UID 0xb900000000000000ULL +#define GCDOP_G_OP_RD_PAGE 0xb700000000000000ULL +#define GCDOP_G_OP_RD_CACHE_START 0x5800000000000000ULL +#define GCDOP_G_OP_RD_CACHE 0x6000000000000000ULL +#define GCDOP_G_OP_RD_CACHE_LAST 0x6800000000000000ULL +#define GCDOP_G_OP_WR_PAGE 0x8000000000000000ULL + +#define GCDOP_G_RD_ROM_ID_PAD 0x00ffffffffffffffULL +#define GCDOP_G_RD_ROM_UID_PAD 0x00ffffffffffffffULL +#define GCDOP_G_RD_PAGE_PAD 0x00f0000000ffffffULL + +#define GCDOP_G_RD_PAGE_ADDR_SHIFT 33 +#define GCDOP_G_RD_PAGE_ADDR_SIZE 23 +#define GCDOP_G_RD_PAGE_ADDR_MASK 0x000ffffe00000000ULL + + +// ROM ID + +#define GCD_ROMID_1TROM_MASK 0x80000000UL +#define GCD_ROMID_TWLROM_MASK 0x40000000UL +#define GCD_ROMID_BADBLK_MASK 0x20000000UL +#define GCD_ROMID_SIZE_MASK 0x0000ff00UL + + + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadRomID + + Description: read rom ID + sync version + + Arguments: None + + Returns: rom ID + *---------------------------------------------------------------------------*/ +u32 GCDi_ReadRomID( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadRom + + Description: read rom data + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadRomAsync + + Description: read rom data + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadNormalModeRom + + Description: read rom data on normal mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadNormalModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadNormalModeRomAsync + + Description: read rom data on normal mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadNormalModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadGameModeRom + + Description: read rom data on game mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadGameModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_ReadGameModeRomAsync + + Description: read rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_ReadGameModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_WriteGameModeRom + + Description: write rom data on game mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WriteGameModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_WriteGameModeRomAsync + + Description: write rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WriteGameModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_Enable + + Description: Enable game card master control + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Enable( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_Disable + + Description: disable game card master control + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Disable( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCD_SetPrimarySlot + + Description: set primary game card slot + + Arguments: primary slot + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_SetPrimarySlot( u8 slot ); + +/*---------------------------------------------------------------------------* + Name: GCD_GetPrimarySlot + + Description: get primary game card slot + + Arguments: None + + Returns: primary slot + *---------------------------------------------------------------------------*/ +u8 GCD_GetPrimarySlot(void ); + +/*---------------------------------------------------------------------------* + Name: GCD_Reset + + Description: reset game card + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_Reset( GCDSlot slot, u32 chat_cycles ); + +/*---------------------------------------------------------------------------* + Name: GCD_Reset + + Description: reset game card + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ResetAll( u32 chat_cycles ); + +/*---------------------------------------------------------------------------* + Name: GCDi_SelectRom + + Description: select game card spi + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SelectRom( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_SelectSpi + + Description: select game card spi + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SelectSpi( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_SetDmaNo + + Description: set card dma number + + Arguments: dmaNo : dma channel number + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_SetDmaNo( GCDSlot slot, u32 dmaNo ); + +/*---------------------------------------------------------------------------* + Name: GCDi_GetDmaNo + + Description: get card dma number + + Arguments: None + + Returns: dmaNo : dma channel number + *---------------------------------------------------------------------------*/ +u32 GCDi_GetDmaNo( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_InterruptHandler + + Description: interrupt handler + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_InterruptHandlerPRIME( void ); +void GCDi_InterruptHandlerSECOND( void ); +void GCDi_InterruptHandlerCommon( GCDSlot slot ); + +//================================================================================ +// WAIT/STOP +//================================================================================ +/*---------------------------------------------------------------------------* + Name: GCDi_IsBusy + + Description: check whether game card is busy or not + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL GCDi_IsBusy( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_IsDataReady + + Description: check whether data is ready or not + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL GCDi_IsDataReady( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_Stop + + Description: stop game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Stop( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitCtrl + + Description: wait while game card is busy + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitCtrl( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitData + + Description: wait until data is ready + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitData( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitDma + + Description: wait for stopping game card DMA + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitDma( GCDSlot slot, u32 dmaNo ); + +/*---------------------------------------------------------------------------* + Name: GCDi_WaitInterrupt + + Description: wait for game card interrupt + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_WaitInterrupt( GCDSlot slot ); + + +// internal + +BOOL GCDi_IsSecureInitialized( GCDSlot slot ); +BOOL GCDi_IsCtrApp( GCDSlot slot ); +BOOL GCDi_IsDsApp( GCDSlot slot ); + +u32 GCDi_ReadNormalModeID( GCDSlot slot ); +u32 GCDi_ReadSecureModeID( GCDSlot slot ); +u32 GCDi_ReadGameModeID( GCDSlot slot ); + +u32 GCDi_ReadRomIDCore( GCDSlot slot, GCDRomCtrls *ctrls ); +void GCDi_ReadRomCore( GCDSlot slot, void *ramp, s32 size, GCDRomCtrls *ctrls ); +BOOL GCDi_ReadRomCommonPreCore( GCDSlot slot, u32 romp, void *ram, s32 size ); +void GCDi_WriteRomCore( GCDSlot slot, void *ramp, s32 size, GCDRomCtrls *ctrls ); + +void GCDi_ReadNormalModeRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ); + +void GCDi_InitSecureParam( GCDSlot slot, BOOL twl_ex ); +void GCDi_InitPngIntf( GCDSlot slot ); +void GCDi_SetInitCardOpBlowfish( void (*p)( void ) ); +void GCDi_SetDecryptObjectFilep( void (*p)( void ) ); +void GCDi_SetSetPngIntf( void (*p)( u32 pnA_l, u8 pnA_h, u32 pnB_l, u8 pnB_h ) ); +void GCDi_SetReadSecureModeIDCorep( u32 (p)( GCDRomCtrls *ctrls ) ); +void GCDi_SetReadSecureModeRomCorep( void (p)( u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ) ); +void GCDi_SetGetOneShotSizeFromCtrlp( s32 (p)( u32 ctrl ) ); + +void GCDi_SetSendOnlyCardOpCorep( void (*p)( GCDRomCtrls *ctrls ) ); +void GCDi_ChangeIntoSecureMode( GCDSlot slot ); +void GCDi_ChangeIntoSecure2Mode( GCDSlot slot ); +void GCDi_SendPngON( GCDSlot slot ); +void GCDi_SendPngOFF( GCDSlot slot ); +void GCDi_ChangeIntoGameMode( GCDSlot slot ); +void GCDi_ReadCardSegmentAsync4Secure( GCDSlot slot, BOOL twl_ex ); + +void GCDi_InitCardOpBlowfish( GCDSlot slot ); +void GCDi_InitCardOpBlowfishDS( GCDSlot slot ); +void GCDi_DecryptObjectFile( GCDSlot slot ); +void GCDi_DecryptObjectFileDS( GCDSlot slot ); + +void GCD_SetInterrupt( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDWork *wp ); + +void* GCDi_GetRomHeaderAddr( GCDSlot slot ); + + +extern u32 GCDi_HeaderBuf[2][ GCD_ROM_HEADER_SIZE/sizeof(u32) ]; +extern u32 GCDi_SecureAreaBuf[2][ GCD_SECURE_AREA_SIZE/sizeof(u32) ]; +extern u32 GCDi_Secure2AreaBuf[2][ GCD_SECURE_AREA_SIZE/sizeof(u32) ]; + +extern GCDSharedWork GCDi_SharedWork[2]; +extern GCDWork GCDi_Work[2]; + +// e[u +extern const BLOWFISH_CTX GCDi_BlowfishInitTableDS; +extern const BLOWFISH_CTX GCDi_BlowfishInitTableGCDFIRM; + + +// SecondarySlot̃J[hbNpӂĂȂ̂ŁAƂ肠PrimarySlotƋpŁB +s32 OS_LockExCard( u16 lockID ); +s32 OS_UnlockExCard( u16 lockID ); + +#ifdef __cplusplus +} /* extern "C" */ + +#endif + +/* FIRM_GCD_GCD_H_ */ +#endif diff --git a/include/firm/gcd/gcd_misc.h b/include/firm/gcd/gcd_misc.h new file mode 100644 index 0000000..4b3da84 --- /dev/null +++ b/include/firm/gcd/gcd_misc.h @@ -0,0 +1,516 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - GCD - include + File: ngcd.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_GCD_GCD_MISC_H_ +#define FIRM_GCD_GCD_MISC_H_ + +#include +#include "./gcd.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +#define PXI_FIFO_TAG_GCD PXI_FIFO_TAG_USER_1 + +#define reg_MI_MC_DET (*(REGType8v *) REG_MC_OFFSET) +#define reg_MI_MC_SWP (*(REGType8v *) ( REG_MC_OFFSET + 1 ) ) + +#define REG_MCCHAT_OFFSET 0x4012 +#define REG_MCCHAT_ADDR (HW_REG_BASE + REG_MCCHAT_OFFSET) +#define reg_MI_MCCHAT (*( REGType16v *) REG_MCCHAT_ADDR) + +/* MCSCRA_L */ + +#define REG_MCSCRA_L_OFFSET 0x1b0 +#define REG_MCSCRA_L_ADDR (HW_REG_BASE + REG_MCSCRA_L_OFFSET) +#define reg_MI_MCSCRA_L (*( REGType32v *) REG_MCSCRA_L_ADDR) + +/* MCSCRB_L */ + +#define REG_MCSCRB_L_OFFSET 0x1b4 +#define REG_MCSCRB_L_ADDR (HW_REG_BASE + REG_MCSCRB_L_OFFSET) +#define reg_MI_MCSCRB_L (*( REGType32v *) REG_MCSCRB_L_ADDR) + +/* MCSCRA_H */ + +#define REG_MCSCRA_H_OFFSET 0x1b8 +#define REG_MCSCRA_H_ADDR (HW_REG_BASE + REG_MCSCRA_H_OFFSET) +#define reg_MI_MCSCRA_H (*( REGType8v *) REG_MCSCRA_H_ADDR) + +/* MCSCRB_H */ + +#define REG_MCSCRB_H_OFFSET 0x1ba +#define REG_MCSCRB_H_ADDR (HW_REG_BASE + REG_MCSCRB_H_OFFSET) +#define reg_MI_MCSCRB_H (*( REGType8v *) REG_MCSCRB_H_ADDR) + + +#define REG_MI_MCCNT1_A_CSC_SHIFT 22 +#define REG_MI_MCCNT1_A_CSC_SIZE 1 +#define REG_MI_MCCNT1_A_CSC_MASK 0x00400000 + +#define REG_MI_MC_SWP_E_SHIFT 7 +#define REG_MI_MC_SWP_E_SIZE 1 +#define REG_MI_MC_SWP_E_MASK 0x80 + + + +typedef enum +{ + GCD_PAGE_0 = 0x0UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_1 = 0x1UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_2 = 0x2UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_4 = 0x3UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_8 = 0x4UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_16 = 0x5UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_32 = 0x6UL << REG_MI_MCCNT1_A_PC_SHIFT, + GCD_PAGE_STAT = 0x7UL << REG_MI_MCCNT1_A_PC_SHIFT +} +GCDPageCount; + +typedef enum +{ + GCD_CKT_150NS = 0x0UL << REG_MI_MCCNT1_A_CT_SHIFT, + GCD_CKT_240NS = 0x1UL << REG_MI_MCCNT1_A_CT_SHIFT +} +GCDClockType; + +typedef enum +{ + GCD_RW_READ = 0x0UL << REG_MI_MCCNT1_WR_SHIFT, + GCD_RW_WRITE = 0x1UL << REG_MI_MCCNT1_WR_SHIFT +} +GCDRw; + +typedef enum +{ + GCD_RESET_LO = 0x0UL << REG_MI_MCCNT1_A_RESB_SHIFT, + GCD_RESET_HI = 0x1UL << REG_MI_MCCNT1_A_RESB_SHIFT +} +GCDReset; + +typedef enum +{ +#ifdef SDK_ARM9 + GCD_LTCK_DISABLE = 0x0UL << REG_MI_MCCNT1_A_TRM_SHIFT, + GCD_LTCK_ENABLE = 0x1UL << REG_MI_MCCNT1_A_TRM_SHIFT +#else + GCD_LTCK_DISABLE = 0x0UL << REG_MI_MCCNT1_A_RTM_SHIFT, + GCD_LTCK_ENABLE = 0x1UL << REG_MI_MCCNT1_A_RTM_SHIFT +#endif +} +GCDLtClkEnable; + +typedef struct +{ + u32 ctrl; + u8 master; + u8 spi; +} +NGCDCtrlRegs; + +// PXIł̒ʐMvgR֘A` +#define GCD_PXI_COMMAND_MASK 0x0000003f // Jn[h̃R}h +#define GCD_PXI_COMMAND_SHIFT 0 +#define GCD_PXI_COMMAND_SIZE 6 +#define GCD_PXI_COMMAND_PARAM_MASK 0x03ffffc0 // Jn[h̃p[^ +#define GCD_PXI_COMMAND_PARAM_SHIFT 6 +#define GCD_PXI_COMMAND_PARAM_SIZE 20 + +typedef union +{ + struct + { + u32 cmd:GCD_PXI_COMMAND_SIZE; + u32 param:GCD_PXI_COMMAND_PARAM_SIZE-1; + u32 slot:1; + } + e; + u32 raw; +} +GCDPxiCmd; + +// PXIoRŔs閽 +#define GCD_PXI_COMMAND_RESET 0x01 +#define GCD_PXI_COMMAND_LOADED 0x02 + + +/*---------------------------------------------------------------------------* + Name: GCD_Init + + Description: initialize for game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_Init( void ); + +/*---------------------------------------------------------------------------* + Name: GCDi_Init + + Description: initialize for game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Init( BOOL reset ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRomID + + Description: read rom ID + sync version + + Arguments: None + + Returns: rom ID + *---------------------------------------------------------------------------*/ +u32 GCD_ReadRomID( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRom + + Description: read rom data + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRomAsync + + Description: read rom data + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadNormalModeRom + + Description: read rom data on normal mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadNormalModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadGameModeRom + + Description: read rom data on game mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadGameModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadRomPreCore + + Description: read rom data + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL GCD_ReadRomPreCore( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_ReadGameModeRomAsync + + Description: read rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_ReadGameModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_WriteGameModeRom + + Description: write rom data on game mode + sync version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_WriteGameModeRom( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCD_WriteGameModeRomAsync + + Description: write rom data on game mode + async version + + Arguments: romp : rom offset + ramp : ram destination address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_WriteGameModeRomAsync( GCDSlot slot, u32 romp, void *ramp, s32 size ); + +/*---------------------------------------------------------------------------* + Name: GCDi_Enable + + Description: Enable game card master control + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Enable( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_Disable + + Description: disable game card master control + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCDi_Disable( GCDSlot slot ); + +//================================================================================ +// WAIT/STOP +//================================================================================ +/*---------------------------------------------------------------------------* + Name: GCD_IsExisting + + Description: get whether cartridge exists + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +static inline BOOL GCD_IsExisting( GCDSlot slot ) +{ + s32 ofs = (GCD_GetPrimarySlot() ^ slot) * 4; + s32 r = ~reg_MI_MC_DET & (REG_MI_MC_SL1_CDET_MASK << ofs); + return r >> (REG_MI_MC_SL1_CDET_SHIFT + ofs); +} + +/*---------------------------------------------------------------------------* + Name: GCD_SetDetectMode + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static inline void GCD_SetDetectMode( GCDSlot slot, u32 mode ) +{ + s32 ofs = (GCD_GetPrimarySlot() ^ slot) * 4; + s32 others = reg_MI_MC_DET & ~(REG_MI_MC_SL1_MODE_MASK << ofs); + reg_MI_MC_DET = (u8)((mode << (REG_MI_MC_SL1_MODE_SHIFT + ofs)) | others); +} + +/*---------------------------------------------------------------------------* + Name: GCD_GetDetectMode + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static inline u8 GCD_GetDetectMode( GCDSlot slot ) +{ + s32 ofs = (GCD_GetPrimarySlot() ^ slot) * 4; + return (u8)((reg_MI_MC_DET & (REG_MI_MC_SL1_MODE_MASK << ofs)) + >> (REG_MI_MC_SL1_MODE_SHIFT + ofs)); +} + +/*---------------------------------------------------------------------------* + Name: GCD_SetChatCounter + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static inline void GCD_SetChatCounter( u16 value ) +{ + reg_MI_MCCHAT = value; +} + +/*---------------------------------------------------------------------------* + Name: GCD_IsBusy + + Description: check whether game card is busy or not + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL GCD_IsBusy( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCD_IsDataReady + + Description: check whether data is ready or not + + Arguments: None + + Returns: TRUE if game card is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL GCD_IsDataReady( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCD_Stop + + Description: stop game card access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_Stop( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCD_WaitRomAsync + + Description: wait for game card async access + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void GCD_WaitRomAsync( GCDSlot slot ); + +/*---------------------------------------------------------------------------* + Name: GCDi_SelectRegAddr + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static inline void* GCDi_SelectRegAddr( GCDSlot slot, u32 base ) +{ + u32 addr = base; + + if ( slot == GCD_SECONDARY_SLOT ) + { + addr += REG_MCCNT0_B_ADDR - REG_MCCNT0_ADDR; + } + + return (void*)addr; +} + +/*---------------------------------------------------------------------------* + Name: GCDi_SelectIrqMask + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +static inline u32 GCDi_SelectIrqMask( GCDSlot slot, u32 base_mask ) +{ + u32 mask = base_mask; + + if ( slot == GCD_SECONDARY_SLOT ) + { + switch ( mask ) + { + case OS_IE_CARD_DATA: + mask = OS_IE_CARD_B_DATA; + break; + case OS_IE_CARD_IREQ: + mask = OS_IE_CARD_B_IREQ; + break; + case OS_IE_CARD_A_DET: + mask = OS_IE_CARD_B_DET; + break; + } + } + + return mask; +} + + +// internal + +u32 GCD_ReadNormalModeID( GCDSlot slot ); +u32 GCD_ReadSecureModeID( GCDSlot slot ); +u32 GCD_ReadGameModeID( GCDSlot slot ); + +void GCDi_SetOp( GCDSlot slot, GCDCmd64* op ); +void GCDi_SetCtrl( GCDSlot slot, GCDCtrlRegs* regs ); +void GCDi_GenCtrl( GCDCtrlRegs* regs, + GCDRw rw, + GCDPageCount pcount, + GCDClockType ckt, u32 lt1, u32 lt2, + BOOL cpn, BOOL dpn, BOOL csc, BOOL dsc ); +s32 GCDi_GetOneShotSizeFromCtrl( u32 ctrl ); +void GCD_SendOnlyCardOpCore( GCDSlot slot, GCDRomCtrls *ctrls ); +u32 GCDi_ReadRomIDCore( GCDSlot slot, GCDRomCtrls *ctrls ); +void GCD_ReadRomCore( GCDSlot slot, u32 romp, void *ramp, s32 size, GCDRomCtrls *ctrls ); +void GCD_WaitRomAsyncCore( GCDSlot slot ); + +void GCDi_WaitCtrl( GCDSlot slot ); +void GCDi_WaitData( GCDSlot slot ); +void GCDi_WaitDma( GCDSlot slot, u32 dmaNo ); +void GCDi_WaitInterrupt( GCDSlot slot ); + +void GCDi_SendtoPxi(u32 data); + +#ifdef __cplusplus +} /* extern "C" */ + +#endif + +/* FIRM_GCD_GCD_MISC_H_ */ +#endif diff --git a/include/firm/hw/ARM7/mmap_firm.h b/include/firm/hw/ARM7/mmap_firm.h new file mode 100644 index 0000000..d93fe22 --- /dev/null +++ b/include/firm/hw/ARM7/mmap_firm.h @@ -0,0 +1,55 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - HW - include + File: mmap_firm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_HW_MMAP_FIRM_H_ +#define FIRM_HW_MMAP_FIRM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------- FIRM +#define HW_FIRM HW_WRAM +#define HW_FIRM_END (HW_FIRM + HW_FIRM_SIZE) +#define HW_FIRM_SIZE (HW_WRAM_0_SIZE + HW_WRAM_1_SIZE + HW_WRAM_A_SIZE_MAX + HW_WRAM_B_SIZE_MAX) + +//------------------------------------- FIRM_WRAM_ABC +#define HW_FIRM_WRAM_A_MAP_END (HW_WRAM_AREA_END - HW_PRV_WRAM_SIZE) +#define HW_FIRM_WRAM_B_MAP_END HW_FIRM_WRAM_A_MAP_END +#define HW_FIRM_WRAM_C_MAP_END HW_FIRM_WRAM_A_MAP_END + +//------------------------------------- HW_FIRM_FROM_BROM_BUF +#define HW_FIRM_FROM_BROM_BUF (HW_FIRM_FROM_BROM_BUF_END - HW_FIRM_FROM_BROM_BUF_SIZE) +#define HW_FIRM_FROM_BROM_BUF_END (HW_WRAM_AREA_END - 0x1000) // END - 4KB +#define HW_FIRM_FROM_BROM_BUF_SIZE 0x3000 // 12KB + +//------------------------------------- HW_FIRM_APP_BUF +#define HW_FIRM_APP_BUF (HW_MAIN_MEM_HI_EX_END - HW_FIRM_APP_BUF_SIZE) +#define HW_FIRM_APP_BUF_END (HW_FIRM_APP_BUF + HW_FIRM_APP_BUF_SIZE) +#define HW_FIRM_APP_BUF_SIZE 0x00800000 // 8MB + +//------------------------------------- HW_FIRM_BOOT_CORE +#define HW_FIRM_BOOT_CORE HW_EXT_WRAM +#define HW_FIRM_BOOT_CORE_END (HW_FIRM_BOOT_CORE + HW_FIRM_BOOT_CORE_SIZE) +#define HW_FIRM_BOOT_CORE_SIZE 0x200 // 512B + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_HW_MMAP_FIRM_H_ */ +#endif diff --git a/include/firm/hw/ARM9/mmap_firm.h b/include/firm/hw/ARM9/mmap_firm.h new file mode 100644 index 0000000..6a96de0 --- /dev/null +++ b/include/firm/hw/ARM9/mmap_firm.h @@ -0,0 +1,54 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - HW - include + File: mmap_firm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_HW_MMAP_FIRM_H_ +#define FIRM_HW_MMAP_FIRM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------- FIRM +#define HW_FIRM HW_WRAM_EX +#define HW_FIRM_END (HW_FIRM + HW_FIRM_SIZE) +#define HW_FIRM_SIZE HW_WRAM_C_SIZE_MAX + +//------------------------------------- FIRM_WRAM_ABC +#define HW_FIRM_WRAM_A_MAP_END HW_WRAM_AREA_END +#define HW_FIRM_WRAM_B_MAP_END HW_FIRM_WRAM_A_MAP_END +#define HW_FIRM_WRAM_C_MAP_END HW_FIRM_WRAM_A_MAP_END + +//------------------------------------- HW_FIRM_FROM_BROM_BUF +#define HW_FIRM_FROM_BROM_BUF (HW_FIRM_FROM_BROM_BUF_END - HW_FIRM_FROM_BROM_BUF_SIZE) +#define HW_FIRM_FROM_BROM_BUF_END (HW_ITCM_END - 0x1000) // END - 4KB +#define HW_FIRM_FROM_BROM_BUF_SIZE 0x3000 // 12KB + +//------------------------------------- HW_FIRM_APP_BUF +#define HW_FIRM_APP_BUF (HW_MAIN_MEM_HI_EX_END - HW_FIRM_APP_BUF_SIZE) +#define HW_FIRM_APP_BUF_END (HW_FIRM_APP_BUF + HW_FIRM_APP_BUF_SIZE) +#define HW_FIRM_APP_BUF_SIZE 0x00800000 // 8MB + +//------------------------------------- HW_FIRM_BOOT_CORE +#define HW_FIRM_BOOT_CORE HW_FIRM_FROM_BROM_BUF_END +#define HW_FIRM_BOOT_CORE_END (HW_FIRM_BOOT_CORE + HW_FIRM_BOOT_CORE_SIZE) +#define HW_FIRM_BOOT_CORE_SIZE 0x200 // 512B + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_HW_MMAP_FIRM_H_ */ +#endif diff --git a/include/firm/hw/common/mmap_firm.h b/include/firm/hw/common/mmap_firm.h new file mode 100644 index 0000000..6b86cd3 --- /dev/null +++ b/include/firm/hw/common/mmap_firm.h @@ -0,0 +1,37 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - HW - include + File: mmap_firm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_HW_COMMON_MMAP_FIRM_H_ +#define FIRM_HW_COMMON_MMAP_FIRM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +//------------------------------------- *_LoadBuffer +#define HW_FIRM_LOAD_BUFFER_BASE MI_GetWramMapStart_B() +#define HW_FIRM_LOAD_BUFFER_UNIT_SIZE 0x8000 +#define HW_FIRM_LOAD_BUFFER_UNIT_NUMS 8 +#define HW_FIRM_LOAD_BUFFER_SIZE (HW_FIRM_LOAD_BUFFER_UNIT_SIZE * HW_FIRM_LOAD_BUFFER_UNIT_NUMS) +#define HW_FIRM_LOAD_BUFFER_END (HW_FIRM_LOAD_BUFFER_BASE + HW_FIRM_LOAD_BUFFER_SIZE) + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_HW_COMMON_MMAP_FIRM_H_ */ +#endif diff --git a/include/firm/memorymap.h b/include/firm/memorymap.h new file mode 100644 index 0000000..fa95b48 --- /dev/null +++ b/include/firm/memorymap.h @@ -0,0 +1,30 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - include - HW + File: memorymap.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_MEMORYMAP_H_ +#define FIRM_MEMORYMAP_H_ + +#include +#include + +#ifdef SDK_ARM9 +#include +#else //SDK_ARM7 +#include +#endif + +/* FIRM_MEMORYMAP_H_ */ +#endif diff --git a/include/firm/mi.h b/include/firm/mi.h new file mode 100644 index 0000000..475c4c1 --- /dev/null +++ b/include/firm/mi.h @@ -0,0 +1,30 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - include - MI + File: mi.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_MI_H_ +#define FIRM_MI_H_ + +#include + +#include +#include +#ifdef SDK_ARM9 +#include +#endif + +/* FIRM_MI_H_ */ +#endif diff --git a/include/firm/mi/ARM9/mi_loader.h b/include/firm/mi/ARM9/mi_loader.h new file mode 100644 index 0000000..0fa3274 --- /dev/null +++ b/include/firm/mi/ARM9/mi_loader.h @@ -0,0 +1,67 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - mi + File: mi_loader.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_MI_LOADER_H_ +#define FIRM_MI_LOADER_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + Name: MI_LoadHeader + + Description: load header + + Arguments: pool pointer to the pool info for SVCSignHeapContext + rsa_key key address + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL MI_LoadHeader( SVCSignHeapContext* pool, const void* rsa_key ); + +/*---------------------------------------------------------------------------* + Name: MI_LoadStatic + + Description: load static binary + + Arguments: None + + Returns: TRUE if success + *---------------------------------------------------------------------------*/ +BOOL MI_LoadStatic( void ); + +/*---------------------------------------------------------------------------* + Name: MI_Boot + + Description: boot + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void MI_Boot( void ); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +/* FIRM_MI_LOADER_H_ */ +#endif diff --git a/include/firm/mi/exDma.h b/include/firm/mi/exDma.h new file mode 100644 index 0000000..38d8ec1 --- /dev/null +++ b/include/firm/mi/exDma.h @@ -0,0 +1,203 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - libraries - mi + File: exDma.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef TWL_MI_EXDMA_H_ +#define TWL_MI_EXDMA_H_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//---------------------------------------------------------------------- + +//---- registers +typedef struct +{ + const void * src; + void * dest; + u32 totalCount; + u32 wordCount; + u32 blockInterval; + u32 fillData; + u32 ctrl; +} +t_MIExDmaChanRegs; + +typedef volatile t_MIExDmaChanRegs MIExDmaChanRegs; + + +//================================================================================ +// DMA control definition +//================================================================================ +//---- DMA channel No. +#define MI_EXDMA_CH_MIN 4 +#define MI_EXDMA_CH_MAX 7 + +#define MI_EXDMA_CH_NUM 4 + + +//================================================================================ +// DMA WAIT +//================================================================================ +/*---------------------------------------------------------------------------* + Name: MIi_IsExDmaBusy + + Description: check whether extended DMA is busy or not + + Arguments: dmaNo : DMA channel No. + + Returns: TRUE if extended DMA is busy, FALSE if not + *---------------------------------------------------------------------------*/ +BOOL MIi_IsExDmaBusy( u32 dmaNo ); + +/*---------------------------------------------------------------------------* + Name: MIi_WaitExDma + + Description: wait while extended DMA is busy + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_WaitExDma( u32 dmaNo ); + +/*---------------------------------------------------------------------------* + Name: MIi_StopExDma + + Description: stop extended DMA + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_StopExDma( u32 dmaNo ); + +/*---------------------------------------------------------------------------* + Name: MIi_StopDmaAsync + + Description: stop extended DMA + async version + + Arguments: dmaNo : DMA channel No. + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_StopExDmaAsync( u32 dmaNo ); + +//================================================================================ +// memory operation using DMA +//================================================================================ +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaSendAsync + + Description: send data with DMA + sync version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaSendAsync( u32 dmaNo, const void *src, void *dest, u32 size ); + +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaRecvAsync + + Description: receive data with DMA + sync version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaRecvAsync( u32 dmaNo, const void *src, void *dest, u32 size ); + +//----------------- internel functions ------------------- +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaSendAsyncCore + + Description: send data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + blockSize : block size + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaSendAsyncCore( u32 dmaNo, const void *src, void *dest, u32 size, u32 oneShotSize, + u32 blockSize, u32 interval, u32 prescale, + u32 continuous, u32 srcRld, u32 destRld, + u32 timing ); + +/*---------------------------------------------------------------------------* + Name: MIi_ExDmaRecvAsyncCore + + Description: receive data with DMA + async version + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + blockSize : block size + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_ExDmaRecvAsyncCore( u32 dmaNo, const void *src, void *dest, u32 size, u32 oneShotSize, + u32 blockSize, u32 interval, u32 prescale, + u32 continuous, u32 srcRld, u32 destRld, + u32 timing ); + +/*---------------------------------------------------------------------------* + Name: MIi_SetExDmaParams + + Description: set DMA + + Arguments: dmaNo : DMA channel No. + dest : destination address + src : source address + size : size (byte) + blockSize : block size + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_SetExDmaParams( u32 dmaNo, const void *src, void *dest, u32 size, u32 oneShotSize, + u32 blockSize, u32 interval, u32 prescale, + u32 continuous, u32 srcRld, u32 destRld, + u32 timing, + u32 fillData, u32 srcDir, u32 destDir); + + +#ifdef __cplusplus +} /* extern "C" */ + +#endif + +/* TWL_MI_EXDMA_H_ */ +#endif diff --git a/include/firm/mi/mainMemory.h b/include/firm/mi/mainMemory.h new file mode 100644 index 0000000..424a2bf --- /dev/null +++ b/include/firm/mi/mainMemory.h @@ -0,0 +1,111 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - include - MI + File: mainMemory.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_MI_MAINMEMORY_H_ +#define FIRM_MI_MAINMEMORY_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct +{ + u16 cr0; + u16 cr1; + u16 cr2; +} +MIMmemCR; + +//---------------------------------------------------------------------- +// C CRR}h +//---------------------------------------------------------------------- + +// for DS-PSRAM + +// CR0 +#define MMEM_DCR0_PARTIAL_REFRESH_NONE 0x0003 // p[VtbV +#define MMEM_DCR0_BURST_CONTINUOUS 0x001c // Ao[XgiQQSoCgj +#define MMEM_DCR0_BURST_MODE 0x0000 // o[Xg[h +#define MMEM_DCR0_PAGE_MODE 0x0020 // y[W[h +#define MMEM_DCR0_SB1 0xffc0 // PŒ + +// CR1 +#define MMEM_DCR1_1ST_R4_W3 0x0002 // Pq^v S^R +#define MMEM_DCR1_BURST_WRITE 0x0000 // o[XgCg +#define MMEM_DCR1_CLOCK_TRIGGER_UP 0x0100 // NbN +#define MMEM_DCR1_BURST_LINER 0x0200 // o[XgjAEV[PX +#define MMEM_DCR1_SB1 0xe430 // PŒ + +// CR2 +#define MMEM_DCR2_SB1 0x004003fe // PŒ +#define MMEM_DCR2_CLOCK_TRIGGER_UP 0x00000400 // NbN +#define MMEM_DCR2_BURST_WRITE 0x00000000 // o[XgCg +#define MMEM_DCR2_BURST_LINER 0x00001000 // o[XgjAEV[PX +#define MMEM_DCR2_1ST_R4_W3 0x00004000 // Pq^v S^R +#define MMEM_DCR2_BURST_MODE 0x00000000 // o[Xg[h +#define MMEM_DCR2_PAGE_MODE 0x00010000 // y[W[h +#define MMEM_DCR2_BURST_CONTINUOUS 0x000e0000 // Ao[XgiQQSoCgj +#define MMEM_DCR2_PARTIAL_REFRESH_NONE 0x00300000 // p[VtbV + +// for TWL-PSRAM + +#define MMEM_TCR0 0xFFFF +#define MMEM_TCR1 0xFFDF +#define MMEM_TCR2 0xFFEA + + +/*---------------------------------------------------------------------------* + Name: MIi_InitMainMemCR + + Description: change main memory into the burst mode + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_InitMainMemCR( BOOL setCR ); + +void MIi_GetMainMemCR( MIMmemCR* dest ); + +/*---------------------------------------------------------------------------* + Name: MIi_IsMainMemoryInitialized + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +BOOL MIi_IsMainMemoryInitialized( void ); + +/*---------------------------------------------------------------------------* + Name: MIi_WaitMainMemoryInitialize + + Description: + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void MIi_WaitMainMemoryInitialize( void ); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_MI_MAINMEMORY_H_ */ +#endif diff --git a/include/firm/misc.h b/include/firm/misc.h new file mode 100644 index 0000000..36d3cfc --- /dev/null +++ b/include/firm/misc.h @@ -0,0 +1,33 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - include - + File: misc.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_MISC_H_ +#define FIRM_MISC_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define offsetof(t, memb) ((size_t)(&(((t *)0)->memb))) + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_MISC_H_ */ +#endif diff --git a/include/firm/nvram.h b/include/firm/nvram.h new file mode 100644 index 0000000..ea9e4c8 --- /dev/null +++ b/include/firm/nvram.h @@ -0,0 +1,43 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - NVRAM + File: nvram.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_NVRAM_H_ +#define FIRM_NVRAM_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SDK_ARM9 +#else // SDK_ARM7 + +/*---------------------------------------------------------------------------* + ֐` + *---------------------------------------------------------------------------*/ +void NVRAMi_Read(u32 address, void *buf, u32 size); +void NVRAMi_Write(u32 address, void *buf, u32 size); + +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_NVRAM_H_ */ +#endif diff --git a/include/firm/os.h b/include/firm/os.h new file mode 100644 index 0000000..f91cfcf --- /dev/null +++ b/include/firm/os.h @@ -0,0 +1,36 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS + File: os.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_OS_H_ +#define FIRM_OS_H_ + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_OS_H_ */ +#endif diff --git a/include/firm/os/ARM9/os_cache_tag.h b/include/firm/os/ARM9/os_cache_tag.h new file mode 100644 index 0000000..7116eaf --- /dev/null +++ b/include/firm/os/ARM9/os_cache_tag.h @@ -0,0 +1,151 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS - include + File: os_cache_tag.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef TWL_OS_CACHE_TAG_H_ +#define TWL_OS_CACHE_TAG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +//=========================================================================== +// DATA CACHE (for specified range) +//=========================================================================== +/*---------------------------------------------------------------------------* + Name: DC_ClearTagAll + + Description: clear tag in data cache + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +void DC_ClearTagAll( void ); + +/*---------------------------------------------------------------------------* + Name: DC_ClearDataAll + + Description: clear data in data cache + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +void DC_ClearDataAll( void ); + +/*---------------------------------------------------------------------------* + Name: DC_FillTagAll + + Description: clear tag in data cache + + Arguments: data : fill data + + Returns: None. + *---------------------------------------------------------------------------*/ +void DC_FillTagAll( u32 data ); + +/*---------------------------------------------------------------------------* + Name: DC_FillDataAll + + Description: fill data in data cache + + Arguments: data : fill data + + Returns: None. + *---------------------------------------------------------------------------*/ +void DC_FillDataAll( u32 data ); + +/*---------------------------------------------------------------------------* + Name: DC_GetTagAndDataAll + + Description: get tag and data in data cache + + Arguments: tag tag address + data data address + + Returns: None. + *---------------------------------------------------------------------------*/ +void DC_GetTagAndDataAll( void* tag, void* data ); + +//=========================================================================== +// INSTRUCTION CACHE +//=========================================================================== +/*---------------------------------------------------------------------------* + Name: IC_ClearTagAll + + Description: clear tag in instruction cache + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +void IC_ClearTagAll( void ); + +/*---------------------------------------------------------------------------* + Name: IC_ClearInstructionAll + + Description: clear instruction in instruction cache + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +void IC_ClearInstructionAll( void ); + +/*---------------------------------------------------------------------------* + Name: IC_FillTagAll + + Description: fill tag in instruction cache + + Arguments: None + + Returns: None. + *---------------------------------------------------------------------------*/ +void IC_FillTagAll( u32 data ); + +/*---------------------------------------------------------------------------* + Name: IC_FillInstructionAll + + Description: fill instruction in instruction cache + + Arguments: data : fill data + + Returns: None. + *---------------------------------------------------------------------------*/ +void IC_FillInstructionAll( u32 data ); + +/*---------------------------------------------------------------------------* + Name: IC_GetTagAndInstructionAll + + Description: get tag and instruction in instruction cache + + Arguments: tag tag address + inst instruction address + + Returns: None. + *---------------------------------------------------------------------------*/ +void IC_GetTagAndInstructionAll( void* tag, void* inst ); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* TWL_OS_CACHE_TAG_H_ */ +#endif diff --git a/include/firm/os/common/boot.h b/include/firm/os/common/boot.h new file mode 100644 index 0000000..2c78f4a --- /dev/null +++ b/include/firm/os/common/boot.h @@ -0,0 +1,86 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS - include + File: boot.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_OS_BOOT_H_ +#define FIRM_OS_BOOT_H_ + +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//---- entry point type +typedef void (*OSEntryPoint) (void); + +/*---------------------------------------------------------------------------* + Name: OSi_Boot + + Description: boot firm + + Arguments: entry : entry point + w : wram settings + + Returns: None + *---------------------------------------------------------------------------*/ +void OSi_Boot( void* entry, MIHeader_WramRegs* w ); + +/*---------------------------------------------------------------------------* + Name: OSi_Finalize + + Description: finalize + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void OSi_Finalize(void); + +/*---------------------------------------------------------------------------* + Name: OSi_ClearWorkArea + + Description: clear work area + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void OSi_ClearWorkArea( void ); + +/*---------------------------------------------------------------------------* + Name: OSi_GetFromBromAddr + + Description: data address from bootrom to firm + + Arguments: None + + Returns: address + *---------------------------------------------------------------------------*/ +static inline OSFromBromBuf* OSi_GetFromBromAddr( void ) +{ + return (OSFromBromBuf*)HW_FIRM_FROM_BROM_BUF; +} + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_OS_BOOT_H_ */ +#endif diff --git a/include/firm/os/common/init.h b/include/firm/os/common/init.h new file mode 100644 index 0000000..45e596c --- /dev/null +++ b/include/firm/os/common/init.h @@ -0,0 +1,43 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - OS - include + File: init.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_OS_INIT_H_ +#define FIRM_OS_INIT_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + Name: OS_InitFIRM + + Description: initialize sdk os for firm + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void OS_InitFIRM(void); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_OS_INIT_H_ */ +#endif diff --git a/include/firm/os/common/system.h b/include/firm/os/common/system.h new file mode 100644 index 0000000..2cdd5f8 --- /dev/null +++ b/include/firm/os/common/system.h @@ -0,0 +1,53 @@ +/*---------------------------------------------------------------------------* + Project: TwlSDK - OS - include + File: system.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ +#ifndef TWL_FIRM_OS_SYSTEM_H_ +#define TWL_FIRM_OS_SYSTEM_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//---------------------------------------------------------------------------- + +typedef u32 OSCpuCycle; + +#define OS_CPU_CLOCK HW_CPU_CLOCK + +//---- sec to cpu cycle +// 150nsec - 30sec +#define OS_SEC_TO_CPUCYC( sec ) ((OSCpuCycle)( ( OS_CPU_CLOCK * (u32)(sec)) )) +#define OS_MSEC_TO_CPUCYC( msec ) ((OSCpuCycle)( ((OS_CPU_CLOCK/1000) * (u32)(msec)) )) +#define OS_USEC_TO_CPUCYC( usec ) ((OSCpuCycle)( ((OS_CPU_CLOCK/1000) * (u32)(usec)) / 1000 )) +#define OS_NSEC_TO_CPUCYC( nsec ) ((OSCpuCycle)( ((OS_CPU_CLOCK/1000) * (u32)(nsec)) / (1000 * 1000) )) + +//---- cpu cycle to sec +// 150nsec - 30sec +#define OS_CPUCYC_TO_SEC( cyc ) ( ((u32)(cyc) ) / OS_CPU_CLOCK ) +#define OS_CPUCYC_TO_MSEC( cyc ) ( ((u32)(cyc) ) / (OS_CPU_CLOCK/1000) ) +#define OS_CPUCYC_TO_USEC( cyc ) ( ((u32)(cyc) * 1000) / (OS_CPU_CLOCK/1000) ) +#define OS_CPUCYC_TO_NSEC( cyc ) ( ((u32)(cyc) * 1000 * 1000) / (OS_CPU_CLOCK/1000) ) + + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* TWL_FIRM_OS_SYSTEM_H_ */ +#endif diff --git a/include/firm/os/common/tick_brom.h b/include/firm/os/common/tick_brom.h new file mode 100644 index 0000000..c0471bf --- /dev/null +++ b/include/firm/os/common/tick_brom.h @@ -0,0 +1,51 @@ +/*---------------------------------------------------------------------------* + Project: TwlBromSDK - OS - include + File: tick_addin.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FRIM_OS_TICK_BROM_H_ +#define FRIM_OS_TICK_BROM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +//---- sec to tick +#define OS_MicroSecondsToTicksBROM( usec ) ((OSTick)( ((OS_SYSTEM_CLOCK/1000) * (u64)(usec)) / 1024 / 1000 )) +#define OS_MicroSecondsToTicksBROM32( usec ) ((OSTick)( ((OS_SYSTEM_CLOCK/1000) * (u32)(usec)) / 1024 / 1000 )) + +#define OS_MilliSecondsToTicksBROM( msec ) ((OSTick)( ((OS_SYSTEM_CLOCK/1000) * (u64)(msec)) / 1024 )) +#define OS_MilliSecondsToTicksBROM32( msec ) ((OSTick)( ((OS_SYSTEM_CLOCK/1000) * (u32)(msec)) / 1024 )) + +#define OS_SecondsToTicksBROM( sec ) ((OSTick)( (OS_SYSTEM_CLOCK * (u64)(sec)) / 1024 )) +#define OS_SecondsToTicksBROM32( sec ) ((OSTick)( (OS_SYSTEM_CLOCK * (u32)(sec)) / 1024 )) + +//---- tick to sec +#define OS_TicksToMicroSecondsBROM( tick ) ( ((u64)(tick) * 1024 * 1000) / (OS_SYSTEM_CLOCK/1000) ) +#define OS_TicksToMicroSecondsBROM32( tick ) ( ((u32)(tick) * 1024 * 1000) / (OS_SYSTEM_CLOCK/1000) ) + +#define OS_TicksToMilliSecondsBROM( tick ) ( ((u64)(tick) * 1024) / (OS_SYSTEM_CLOCK/1000) ) +#define OS_TicksToMilliSecondsBROM32( tick ) ( ((u32)(tick) * 1024) / (OS_SYSTEM_CLOCK/1000) ) + +#define OS_TicksToSecondsBROM( tick ) ( ((u64)(tick) * 1024) / OS_SYSTEM_CLOCK ) +#define OS_TicksToSecondsBROM32( tick ) ( ((u32)(tick) * 1024) / OS_SYSTEM_CLOCK ) + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FRIM_OS_TICK_BROM_H_ */ +#endif diff --git a/include/firm/pm.h b/include/firm/pm.h new file mode 100644 index 0000000..dfb8919 --- /dev/null +++ b/include/firm/pm.h @@ -0,0 +1,27 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - pm + File: pm.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_PM_H_ +#define FIRM_PM_H_ + +#ifdef SDK_ARM7 +#include +#include +#endif // SDK_ARM7 + +/* FIRM_PM_H_ */ +#endif diff --git a/include/firm/pm/ARM7/pm_init.h b/include/firm/pm/ARM7/pm_init.h new file mode 100644 index 0000000..055c8d9 --- /dev/null +++ b/include/firm/pm/ARM7/pm_init.h @@ -0,0 +1,64 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - pm + File: pm_init.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_PM_ARM7_PM_INIT_H_ +#define FIRM_PM_ARM7_PM_INIT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/*---------------------------------------------------------------------------* + Name: PM_InitFIRM + + Description: power B/L on + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void PM_InitFIRM( void ); + +/*---------------------------------------------------------------------------* + Name: PM_CheckINIFlag + + Description: Check INI in GX_DISPSTAT (able to call before PM_InitFIRM) + + Arguments: None + + Returns: None + *---------------------------------------------------------------------------*/ +void PM_CheckINIFlag(void); + +/*---------------------------------------------------------------------------* + Name: PM_BackLightOn + + Description: power B/L on if not set yet + + Arguments: force TRUE: wait until valid condition + FALSE not set unless valid condition + + Returns: None + *---------------------------------------------------------------------------*/ +void PM_BackLightOn( BOOL force ); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_PM_ARM7_PM_INIT_H_ */ +#endif diff --git a/include/firm/pm/ARM7/pm_pmic_ex.h b/include/firm/pm/ARM7/pm_pmic_ex.h new file mode 100644 index 0000000..3651590 --- /dev/null +++ b/include/firm/pm/ARM7/pm_pmic_ex.h @@ -0,0 +1,73 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - pm + File: pm_pmic_ex.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef FIRM_PM_PMIC_EX_H_ +#define FIRM_PM_PMIC_EX_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//================================================================================ +// PMIC ACCESS +//================================================================================ +/*---------------------------------------------------------------------------* + Name: PMi_SetParams + + Description: set control bit to device register + + Arguments: reg : device register + setBits : bits to set + maskBits : bits to mask + + Returns: None + *---------------------------------------------------------------------------*/ +void PMi_SetParams( u8 reg, u8 setBits, u8 maskBits ); + +/*---------------------------------------------------------------------------* + Name: PMi_SetFlags + + Description: set control bit to device register + + Arguments: reg : device register + setBits : bits to set + + Returns: None + *---------------------------------------------------------------------------*/ +void PMi_SetFlags( u8 reg, u8 setBits ); + +/*---------------------------------------------------------------------------* + Name: PMi_ResetFlags + + Description: clear control bit to device register + + Arguments: reg : device register + clrBits : bits to set + + Returns: None + *---------------------------------------------------------------------------*/ +void PMi_ResetFlags( u8 reg, u8 clrBits ); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* FIRM_PM_PMIC_EX_H_ */ +#endif diff --git a/include/firm/pxi.h b/include/firm/pxi.h new file mode 100644 index 0000000..b257e65 --- /dev/null +++ b/include/firm/pxi.h @@ -0,0 +1,28 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - include - PXI + File: pxi.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_PXI_H_ +#define FIRM_PXI_H_ + +#include + +#include +#include + + +/* FIRM_PXI_H_ */ +#endif diff --git a/include/firm/pxi/common/misc.h b/include/firm/pxi/common/misc.h new file mode 100644 index 0000000..36c740b --- /dev/null +++ b/include/firm/pxi/common/misc.h @@ -0,0 +1,217 @@ +/*---------------------------------------------------------------------------* + Project: TwlFirm - -include - PXI + File: misc.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_PXI_COMMON_MISC_H_ +#define FIRM_PXI_COMMON_MISC_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// PXI sync ID for bootrom +typedef enum +{ + // from ARM7 + FIRM_PXI_ID_COLDBOOT = 1, + FIRM_PXI_ID_WARMBOOT = 2, + + FIRM_PXI_ID_INIT_ARM7 = 7, + FIRM_PXI_ID_LOAD_HEADER = 6, + FIRM_PXI_ID_LOAD_STATIC = 5, + + // *_Loaderp (ARM7ARM9) + FIRM_PXI_ID_LOAD_PIRIOD = 1, + + // from ARM9 + FIRM_PXI_ID_INIT_ARM9 = 9, + FIRM_PXI_ID_AUTH_HEADER = 10, + FIRM_PXI_ID_AUTH_STATIC = 11, + + // from both of ARM9 and ARM7 + FIRM_PXI_ID_NULL = 0, + FIRM_PXI_ID_ERR = 0xF +} +FIRMPxiID; + + +/*---------------------------------------------------------------------------* + Name: PXI_InitFifoFIRM + + Description: initialize FIFO system for bootrom + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ +void PXI_InitFifoFIRM(void); + +/*---------------------------------------------------------------------------* + Name: PXI_NotifyID + + Description: send 4bit id to other processor + + Arguments: id notifying id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_NotifyID( u32 id ); + +/*---------------------------------------------------------------------------* + Name: PXI_WaitID + + Description: Wait 4bit id from the other processor + + Arguments: id waiting id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_WaitID( u32 id ); + +/*---------------------------------------------------------------------------* + Name: PXI_RecvID + + Description: Receive 4bit id from the other processor + + Arguments: None + + Returns: id + *---------------------------------------------------------------------------*/ +u8 PXI_RecvID( void ); + +/*---------------------------------------------------------------------------* + Name: PXI_SendIDByIntf + + Description: send 4bit id to other processor + + Arguments: id notifying id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_SendIDByIntf( u32 id ); + +/*---------------------------------------------------------------------------* + Name: PXI_RecvIDByIntf + + Description: receive 4bit id from the other processor + + Arguments: None + + Returns: received id + *---------------------------------------------------------------------------*/ +u32 PXI_RecvIDByIntf( void ); + +/*---------------------------------------------------------------------------* + Name: PXI_WaitIDByIntf + + Description: Wait 4bit id from the other processor + + Arguments: id waiting id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_WaitIDByIntf( u32 id ); + +/*---------------------------------------------------------------------------* + Name: PXI_SendIDByFifo + + Description: Send 32bit-word to another CPU via FIFO + + Arguments: + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_SendIDByFifo(PXIFifoTag tag, u32 id); + +/*---------------------------------------------------------------------------* + Name: PXI_RecvIDByFifo + + Description: Recv 32bit-word from another CPU via FIFO + + Arguments: + + Returns: if error occured, returns minus value + *---------------------------------------------------------------------------*/ +PXIFifoStatus PXI_RecvIDByFifo(PXIFifoTag tag, void* buf); + +/*---------------------------------------------------------------------------* + Name: PXI_WaitIDByFifo + + Description: Wait 32bit-word from another CPU via FIFO + + Arguments: id waiting id + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_WaitIDByFifo(PXIFifoTag tag, u32 id); + +/*---------------------------------------------------------------------------* + Name: PXI_SendDataByFifo + + Description: Send 32bit-word to another CPU via FIFO + + Arguments: + + Returns: None + *---------------------------------------------------------------------------*/ +void PXI_SendDataByFifo(PXIFifoTag tag, void* buf, int size); + +/*---------------------------------------------------------------------------* + Name: PXI_RecvDataByFifo + + Description: Recv 32bit-word to another CPU via FIFO + + Arguments: + + Returns: if error occured, returns minus value + *---------------------------------------------------------------------------*/ +PXIFifoStatus PXI_RecvDataByFifo(PXIFifoTag tag, void* buf, int max_size); + +/*---------------------------------------------------------------------------* + Name: PXI_IsSendFifoFull + + Description: Check if send fifo is full? + + Arguments: None. + + Returns: if send fifo is full + *---------------------------------------------------------------------------*/ +static inline BOOL PXI_IsSendFifoFull(void) +{ + return (reg_PXI_FIFO_CNT & REG_PXI_FIFO_CNT_SEND_FULL_MASK) >> REG_PXI_FIFO_CNT_SEND_FULL_SHIFT; +} + +/*---------------------------------------------------------------------------* + Name: PXI_IsRecvFifoEmpty + + Description: Check if receive fifo is empty? + + Arguments: None. + + Returns: if receive fifo is empty + *---------------------------------------------------------------------------*/ +static inline BOOL PXI_IsRecvFifoEmpty(void) +{ + return (reg_PXI_FIFO_CNT & REG_PXI_FIFO_CNT_RECV_EMP_MASK) >> REG_PXI_FIFO_CNT_RECV_EMP_SHIFT; +} + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* FIRM_PXI_COMMON_MISC_H_ */ diff --git a/include/firm/pxi/common/regname_ex.h b/include/firm/pxi/common/regname_ex.h new file mode 100644 index 0000000..5883d6c --- /dev/null +++ b/include/firm/pxi/common/regname_ex.h @@ -0,0 +1,42 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - include - PXI + File: regname.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Log: $ + $NoKeywords: $ + *---------------------------------------------------------------------------*/ + +#ifndef FIRM_PXI_COMMON_REGNAME_EX_H_ +#define FIRM_PXI_COMMON_REGNAME_EX_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef SDK_ARM9 + +#define REG_PXI_FIFO_CNT_SEND_FULL_SHIFT REG_PXI_SUBP_FIFO_CNT_SEND_FULL_SHIFT +#define REG_PXI_FIFO_CNT_RECV_EMP_SHIFT REG_PXI_SUBP_FIFO_CNT_RECV_EMP_SHIFT + +#else // SDK_ARM7 + +#define REG_PXI_FIFO_CNT_SEND_FULL_SHIFT REG_PXI_MAINP_FIFO_CNT_SEND_FULL_SHIFT +#define REG_PXI_FIFO_CNT_RECV_EMP_SHIFT REG_PXI_MAINP_FIFO_CNT_RECV_EMP_SHIFT + +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif +/* FIRM_PXI_COMMON_REGNAME_EX_H_ */ +#endif diff --git a/include/firm/specfiles/ARM7-BB-FIRM.lcf.template b/include/firm/specfiles/ARM7-BB-FIRM.lcf.template new file mode 100644 index 0000000..a0176d4 --- /dev/null +++ b/include/firm/specfiles/ARM7-BB-FIRM.lcf.template @@ -0,0 +1,507 @@ +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makelcf +# File: ARM7-BB-FIRM.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 # > + + (RWX) : ORIGIN = , LENGTH = 0x0 > + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 > + + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + check.WORKRAM (RWX) : ORIGIN = , LENGTH = 0x48000 > workram.check +} + +KEEP_SECTION +{ + .ctor +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); . = ALIGN(4); # Fit to cache line + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + crt0_firm.o (.text) + + + + + + + . = ALIGN(4); + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + EXCEPTION + SDK_STATIC_ETABLE_END =.; + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(4); + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(4); + SDK_STATIC_DATA_END =.; + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + __exception_table_start__ = SDK_STATIC_ETABLE_START; # for exception table + __exception_table_end__ = SDK_STATIC_ETABLE_END; # for exception table + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_STATIC_BSS_END = .; + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.MAIN.START = 0x02380000; + SDK_AUTOLOAD.MAIN.END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.BSS_END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.SIZE = 0; + SDK_AUTOLOAD.MAIN.BSS_SIZE = 0; + SDK_AUTOLOAD.WRAM.START = 0x037f8000; + SDK_AUTOLOAD.WRAM.END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.BSS_END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.SIZE = 0; + SDK_AUTOLOAD.WRAM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_MAIN_START = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD_MAIN_END = SDK_AUTOLOAD.MAIN.END; + SDK_AUTOLOAD_MAIN_BSS_END = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_AUTOLOAD_MAIN_SIZE = SDK_AUTOLOAD.MAIN.SIZE; + SDK_AUTOLOAD_MAIN_BSS_SIZE = SDK_AUTOLOAD.MAIN.BSS_SIZE; + SDK_AUTOLOAD_WRAM_START = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD_WRAM_END = SDK_AUTOLOAD.WRAM.END; + SDK_AUTOLOAD_WRAM_BSS_END = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_AUTOLOAD_WRAM_SIZE = SDK_AUTOLOAD.WRAM.SIZE; + SDK_AUTOLOAD_WRAM_BSS_SIZE = SDK_AUTOLOAD.WRAM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> # > binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(4); + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(4); + SDK_OVERLAY..DATA_END =.; + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(4); + SDK_SECTION_ARENA_START =.; + } > arena.MAIN + + + ############################ OVERLAYDEFS ############################ + .: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > + + + ############################ OVERLAYTABLE ########################### + .: + { + + # Overlay + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + + } > + + + ############################ OTHERS ################################# + SDK_SUBPRIV_ARENA_LO = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_WRAM_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE = ; # allocated in WRAM + + # work ram size checker + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + .check.WORKRAM: + { + . = . + SDK_SECTION_ARENA_START - + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.WORKRAM +} diff --git a/include/firm/specfiles/ARM7-BB-FIRM.lsf b/include/firm/specfiles/ARM7-BB-FIRM.lsf new file mode 100644 index 0000000..4217650 --- /dev/null +++ b/include/firm/specfiles/ARM7-BB-FIRM.lsf @@ -0,0 +1,28 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM7-BB-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x037f8000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) + Object * (.wram) + StackSize 1024 512 +} diff --git a/include/firm/specfiles/ARM7-BB-GCDFIRM.lcf.template b/include/firm/specfiles/ARM7-BB-GCDFIRM.lcf.template new file mode 100644 index 0000000..ebabab9 --- /dev/null +++ b/include/firm/specfiles/ARM7-BB-GCDFIRM.lcf.template @@ -0,0 +1,507 @@ +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makelcf +# File: ARM7-BB-NORFIRM.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 # > + + (RWX) : ORIGIN = , LENGTH = 0x0 > + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 > + + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + check.WORKRAM (RWX) : ORIGIN = , LENGTH = 0x48000 > workram.check +} + +KEEP_SECTION +{ + .ctor +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); . = ALIGN(4); # Fit to cache line + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + crt0.o (.text) + + + + + + + . = ALIGN(4); + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + EXCEPTION + SDK_STATIC_ETABLE_END =.; + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(4); + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(4); + SDK_STATIC_DATA_END =.; + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + __exception_table_start__ = SDK_STATIC_ETABLE_START; # for exception table + __exception_table_end__ = SDK_STATIC_ETABLE_END; # for exception table + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_STATIC_BSS_END = .; + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.MAIN.START = 0x02380000; + SDK_AUTOLOAD.MAIN.END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.BSS_END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.SIZE = 0; + SDK_AUTOLOAD.MAIN.BSS_SIZE = 0; + SDK_AUTOLOAD.WRAM.START = 0x037f8000; + SDK_AUTOLOAD.WRAM.END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.BSS_END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.SIZE = 0; + SDK_AUTOLOAD.WRAM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_MAIN_START = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD_MAIN_END = SDK_AUTOLOAD.MAIN.END; + SDK_AUTOLOAD_MAIN_BSS_END = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_AUTOLOAD_MAIN_SIZE = SDK_AUTOLOAD.MAIN.SIZE; + SDK_AUTOLOAD_MAIN_BSS_SIZE = SDK_AUTOLOAD.MAIN.BSS_SIZE; + SDK_AUTOLOAD_WRAM_START = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD_WRAM_END = SDK_AUTOLOAD.WRAM.END; + SDK_AUTOLOAD_WRAM_BSS_END = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_AUTOLOAD_WRAM_SIZE = SDK_AUTOLOAD.WRAM.SIZE; + SDK_AUTOLOAD_WRAM_BSS_SIZE = SDK_AUTOLOAD.WRAM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> # > binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(4); + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(4); + SDK_OVERLAY..DATA_END =.; + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(4); + SDK_SECTION_ARENA_START =.; + } > arena.MAIN + + + ############################ OVERLAYDEFS ############################ + .: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > + + + ############################ OVERLAYTABLE ########################### + .: + { + + # Overlay + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + + } > + + + ############################ OTHERS ################################# + SDK_SUBPRIV_ARENA_LO = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_WRAM_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE = ; # allocated in WRAM + + # work ram size checker + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + .check.WORKRAM: + { + . = . + SDK_SECTION_ARENA_START - + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.WORKRAM +} diff --git a/include/firm/specfiles/ARM7-BB-GCDFIRM.lsf b/include/firm/specfiles/ARM7-BB-GCDFIRM.lsf new file mode 100644 index 0000000..4217650 --- /dev/null +++ b/include/firm/specfiles/ARM7-BB-GCDFIRM.lsf @@ -0,0 +1,28 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM7-BB-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x037f8000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) + Object * (.wram) + StackSize 1024 512 +} diff --git a/include/firm/specfiles/ARM7-TS-FIRM.lcf.template b/include/firm/specfiles/ARM7-TS-FIRM.lcf.template new file mode 100644 index 0000000..8f7597a --- /dev/null +++ b/include/firm/specfiles/ARM7-TS-FIRM.lcf.template @@ -0,0 +1,929 @@ +#--------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ARM7-BB.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 > + + + (RWX) : ORIGIN = , LENGTH = 0x0 >> + + binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + binary.STATIC_FOOTER (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + check.WORKRAM (RWX) : ORIGIN = 0x037f8000, LENGTH = 0x18000 > workram.check + check.MAINMEM (RWX) : ORIGIN = 0x02fe0000, LENGTH = 0x1c000 > mainmem.check + + binary.LTDAUTOLOAD_TOP (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWX) : ORIGIN = , LENGTH = 0x0 >> + + binary.LTDAUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + check.LTDWRAM (RWX) : ORIGIN = 0x03000000, LENGTH = 0x40000 > ltdwram.check + check.LTDMAIN (RWX) : ORIGIN = 0x02f88000, LENGTH = 0x58000 > ltdmain.check +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + #:::::::::: text/rodata + SDK_STATIC_TEXT_END =.; + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + __exception_table_start__ =.; + EXCEPTION + __exception_table_end__ =.; + SDK_STATIC_ETABLE_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_STATIC_DATA_END =.; + . = ALIGN(4); + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_STATIC_BSS_END = .; + + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.MAIN.START = 0x02fe0000; + SDK_AUTOLOAD.MAIN.END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.BSS_END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.SIZE = 0; + SDK_AUTOLOAD.MAIN.BSS_SIZE = 0; + SDK_AUTOLOAD.WRAM.START = 0x037f8000; + SDK_AUTOLOAD.WRAM.END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.BSS_END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.SIZE = 0; + SDK_AUTOLOAD.WRAM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(4); + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + . = ALIGN(4); + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_MAIN_START = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD_MAIN_END = SDK_AUTOLOAD.MAIN.END; + SDK_AUTOLOAD_MAIN_BSS_END = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_AUTOLOAD_MAIN_SIZE = SDK_AUTOLOAD.MAIN.SIZE; + SDK_AUTOLOAD_MAIN_BSS_SIZE = SDK_AUTOLOAD.MAIN.BSS_SIZE; + SDK_AUTOLOAD_WRAM_START = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD_WRAM_END = SDK_AUTOLOAD.WRAM.END; + SDK_AUTOLOAD_WRAM_BSS_END = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_AUTOLOAD_WRAM_SIZE = SDK_AUTOLOAD.WRAM.SIZE; + SDK_AUTOLOAD_WRAM_BSS_SIZE = SDK_AUTOLOAD.WRAM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + } > binary.AUTOLOAD_INFO + + SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; + SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ STATIC_FOOTER ########################## + .binary.STATIC_FOOTER: + { + WRITEW 0xdec00621; # LE(0x2106C0DE) = NITRO CODE + WRITEW _start_ModuleParams - ADDR(.); + WRITEW 0; # NO DIGEST + WRITEW _start_LtdModuleParams - ADDR(.); + } > binary.STATIC_FOOTER + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_OVERLAY..DATA_END =.; + . = ALIGN(4); + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(4); + SDK_SECTION_ARENA_START =.; + + } > arena.MAIN + + ############################ OVERLAYDEFS ############################ + .F: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > F + + ############################ OVERLAYTABLE ########################### + .F: + { + + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + } > F + + ############################ OTHERS ################################# + SDK_WRAM_ARENA_LO = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_SUBPRIV_ARENA_LO = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_IRQ_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + + .check.WORKRAM: + { + . = . + SDK_AUTOLOAD.WRAM.BSS_END - SDK_AUTOLOAD.WRAM.START + 0x080 + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + + } > check.WORKRAM + + .check.MAINMEM: + { + . = SDK_SUBPRIV_ARENA_LO; + + } > check.MAINMEM + + ########################### LTDAUTOLOADS ############################ + SDK_LTDAUTOLOAD.LTDMAIN.START = SDK_STATIC_BSS_END; + SDK_LTDAUTOLOAD.LTDMAIN.END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.SIZE = 0; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE = 0; + SDK_LTDAUTOLOAD.LTDWRAM.START = 0x03000000; + SDK_LTDAUTOLOAD.LTDWRAM.END = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD.LTDWRAM.BSS_END = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD.LTDWRAM.SIZE = 0; + SDK_LTDAUTOLOAD.LTDWRAM.BSS_SIZE = 0; + SDK_LTDAUTOLOAD_TOP_START = 0x02e80000; + SDK_LTDAUTOLOAD_TOP_SIZE = 4; # STATIC ̈悪 4 bytes ̃_~[oCit@C̐擪ɓ # + SDK_LTDAUTOLOAD_START = SDK_LTDAUTOLOAD_TOP_START + SDK_LTDAUTOLOAD_TOP_SIZE; + SDK_LTDAUTOLOAD_SIZE = 0; + SDK_LTDAUTOLOAD_NUMBER = ; + + .binary.LTDAUTOLOAD_TOP: + { + WRITEW 0xdeadbeef; + + } > binary.LTDAUTOLOAD_TOP + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDAUTOLOAD__ID =; + SDK_LTDAUTOLOAD..ID =; + SDK_LTDAUTOLOAD..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDAUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + #:::::::::: text/rodata + SDK_LTDAUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(4); + SDK_LTDAUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_LTDAUTOLOAD..DATA_END =.; + . = ALIGN(4); + SDK_LTDAUTOLOAD..END =.; + + SDK_LTDAUTOLOAD..TEXT_SIZE = SDK_LTDAUTOLOAD..TEXT_END - SDK_LTDAUTOLOAD..TEXT_START; + SDK_LTDAUTOLOAD..DATA_SIZE = SDK_LTDAUTOLOAD..DATA_END - SDK_LTDAUTOLOAD..DATA_START; + SDK_LTDAUTOLOAD..SIZE = SDK_LTDAUTOLOAD..END - SDK_LTDAUTOLOAD..START; + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDAUTOLOAD..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_LTDAUTOLOAD..BSS_END =.; + + SDK_LTDAUTOLOAD..BSS_SIZE = SDK_LTDAUTOLOAD..BSS_END - SDK_LTDAUTOLOAD..BSS_START; + + } >> + + + + SDK_LTDAUTOLOAD_LTDMAIN_START = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD_LTDMAIN_END = SDK_LTDAUTOLOAD.LTDMAIN.END; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + SDK_LTDAUTOLOAD_LTDMAIN_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.SIZE; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE; + SDK_LTDAUTOLOAD_LTDWRAM_START = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD_LTDWRAM_END = SDK_LTDAUTOLOAD.LTDWRAM.END; + SDK_LTDAUTOLOAD_LTDWRAM_BSS_END = SDK_LTDAUTOLOAD.LTDWRAM.BSS_END; + SDK_LTDAUTOLOAD_LTDWRAM_SIZE = SDK_LTDAUTOLOAD.LTDWRAM.SIZE; + SDK_LTDAUTOLOAD_LTDWRAM_BSS_SIZE = SDK_LTDAUTOLOAD.LTDWRAM.BSS_SIZE; + + ######################### LTDAUTOLOAD_INFO ########################## + .binary.LTDAUTOLOAD_INFO: + { + + WRITEW ADDR(.); + WRITEW SDK_LTDAUTOLOAD..SIZE; + WRITEW SDK_LTDAUTOLOAD..BSS_SIZE; + + } > binary.LTDAUTOLOAD_INFO + + SDK_LTDAUTOLOAD_LIST = SDK_LTDAUTOLOAD_START + SDK_LTDAUTOLOAD_SIZE; + SDK_LTDAUTOLOAD_LIST_END = SDK_LTDAUTOLOAD_LIST + SIZEOF(.binary.LTDAUTOLOAD_INFO); + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SIZEOF(.binary.LTDAUTOLOAD_INFO); + + ########################### LTDOVERLAYS ############################# + SDK_LTDOVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDOVERLAY__ID =; + SDK_LTDOVERLAY..ID =; + SDK_LTDOVERLAY..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDOVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_LTDOVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_LTDOVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_LTDOVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_LTDOVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_LTDOVERLAY..DATA_END =.; + . = ALIGN(4); + SDK_LTDOVERLAY..END =.; + + SDK_LTDOVERLAY..TEXT_SIZE = SDK_LTDOVERLAY..TEXT_END - SDK_LTDOVERLAY..TEXT_START; + SDK_LTDOVERLAY..DATA_SIZE = SDK_LTDOVERLAY..DATA_END - SDK_LTDOVERLAY..DATA_START; + SDK_LTDOVERLAY..SIZE = SDK_LTDOVERLAY..END - SDK_LTDOVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDOVERLAY..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_LTDOVERLAY..BSS_END =.; + + SDK_LTDOVERLAY..BSS_SIZE = SDK_LTDOVERLAY..BSS_END - SDK_LTDOVERLAY..BSS_START; + + } >> + + + + ########################## LTDOVERLAYDEFS ########################### + .L: + { + ### TWL limited extended static module information + WRITEW SDK_LTDAUTOLOAD_TOP_START; # load address + WRITEW 0; # padding + WRITEW SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD_TOP_SIZE; # size of module + WRITEW 0; # padding + + ### TWL limited overlay filename + + WRITES (""); + + + } > L + + ######################### LTDOVERLAYTABLE ########################### + .L: + { + + WRITES # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_LTDOVERLAY..SIZE; # size of module + WRITEW SDK_LTDOVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_LTDOVERLAY..SINIT_START; # start address of static init + WRITEW SDK_LTDOVERLAY..SINIT_END; # end address of static init + WRITEW # ROM file ID + WRITEW 0; # Reserved + + + } > L + + ############################ OTHERS ################################# + .check.LTDWRAM: + { + . = SDK_LTDAUTOLOAD.LTDWRAM.BSS_END; + + } > check.LTDWRAM + + .check.LTDMAIN: + { +# . = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + + } > check.LTDMAIN + +} diff --git a/include/firm/specfiles/ARM7-TS-FIRM.lsf b/include/firm/specfiles/ARM7-TS-FIRM.lsf new file mode 100644 index 0000000..10fc59e --- /dev/null +++ b/include/firm/specfiles/ARM7-TS-FIRM.lsf @@ -0,0 +1,31 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM7-TS-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x037f8000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) + Object * (.etable) + Object * (.wram) + Object * (.ltdwram) + Object * (.ltdmain) + StackSize 1024 1024 +} diff --git a/include/firm/specfiles/ARM7-TS-GCDFIRM.lcf.template b/include/firm/specfiles/ARM7-TS-GCDFIRM.lcf.template new file mode 100644 index 0000000..c3244f8 --- /dev/null +++ b/include/firm/specfiles/ARM7-TS-GCDFIRM.lcf.template @@ -0,0 +1,507 @@ +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makelcf +# File: ARM7-TS-NORFIRM.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 # > + + (RWX) : ORIGIN = , LENGTH = 0x0 > + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 > + + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + check.WORKRAM (RWX) : ORIGIN = , LENGTH = 0x48000 > workram.check +} + +KEEP_SECTION +{ + .ctor +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); . = ALIGN(4); # Fit to cache line + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + crt0.o (.text) + + + + + + + . = ALIGN(4); + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + EXCEPTION + SDK_STATIC_ETABLE_END =.; + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(4); + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(4); + SDK_STATIC_DATA_END =.; + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + __exception_table_start__ = SDK_STATIC_ETABLE_START; # for exception table + __exception_table_end__ = SDK_STATIC_ETABLE_END; # for exception table + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_STATIC_BSS_END = .; + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.MAIN.START = 0x02380000; + SDK_AUTOLOAD.MAIN.END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.BSS_END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.SIZE = 0; + SDK_AUTOLOAD.MAIN.BSS_SIZE = 0; + SDK_AUTOLOAD.WRAM.START = 0x037f8000; + SDK_AUTOLOAD.WRAM.END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.BSS_END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.SIZE = 0; + SDK_AUTOLOAD.WRAM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_MAIN_START = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD_MAIN_END = SDK_AUTOLOAD.MAIN.END; + SDK_AUTOLOAD_MAIN_BSS_END = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_AUTOLOAD_MAIN_SIZE = SDK_AUTOLOAD.MAIN.SIZE; + SDK_AUTOLOAD_MAIN_BSS_SIZE = SDK_AUTOLOAD.MAIN.BSS_SIZE; + SDK_AUTOLOAD_WRAM_START = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD_WRAM_END = SDK_AUTOLOAD.WRAM.END; + SDK_AUTOLOAD_WRAM_BSS_END = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_AUTOLOAD_WRAM_SIZE = SDK_AUTOLOAD.WRAM.SIZE; + SDK_AUTOLOAD_WRAM_BSS_SIZE = SDK_AUTOLOAD.WRAM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> # > binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(4); + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(4); + SDK_OVERLAY..DATA_END =.; + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(4); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(4); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(4); + SDK_SECTION_ARENA_START =.; + } > arena.MAIN + + + ############################ OVERLAYDEFS ############################ + .: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > + + + ############################ OVERLAYTABLE ########################### + .: + { + + # Overlay + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + + } > + + + ############################ OTHERS ################################# + SDK_SUBPRIV_ARENA_LO = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_WRAM_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE = ; # allocated in WRAM + + # work ram size checker + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + .check.WORKRAM: + { + . = . + SDK_SECTION_ARENA_START - + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.WORKRAM +} diff --git a/include/firm/specfiles/ARM7-TS-GCDFIRM.lsf b/include/firm/specfiles/ARM7-TS-GCDFIRM.lsf new file mode 100644 index 0000000..d4f5d88 --- /dev/null +++ b/include/firm/specfiles/ARM7-TS-GCDFIRM.lsf @@ -0,0 +1,28 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM7-TS-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x037f8000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) + Object * (.wram) + StackSize 1024 512 +} diff --git a/include/firm/specfiles/ARM7-TS-PARTNER.lcf.template b/include/firm/specfiles/ARM7-TS-PARTNER.lcf.template new file mode 100644 index 0000000..5e9c415 --- /dev/null +++ b/include/firm/specfiles/ARM7-TS-PARTNER.lcf.template @@ -0,0 +1,899 @@ +#--------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ARM7-BB.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 #> + + + (RWX) : ORIGIN = , LENGTH = 0x0 #>> + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + check.WORKRAM (RWX) : ORIGIN = 0x037f8000, LENGTH = 0x18000 > workram.check + check.MAINMEM (RWX) : ORIGIN = 0x02fe0000, LENGTH = 0x1c000 > mainmem.check + +# binary.LTDAUTOLOAD_TOP (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWX) : ORIGIN = , LENGTH = 0x0 #>> + +# binary.LTDAUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + check.LTDWRAM (RWX) : ORIGIN = 0x03000000, LENGTH = 0x40000 > ltdwram.check + check.LTDMAIN (RWX) : ORIGIN = 0x02f88000, LENGTH = 0x58000 > ltdmain.check +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + #:::::::::: text/rodata + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_STATIC_DATA_END =.; + . = ALIGN(4); + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_STATIC_BSS_END = .; + + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.MAIN.START = 0x02fe0000; + SDK_AUTOLOAD.MAIN.END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.BSS_END = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD.MAIN.SIZE = 0; + SDK_AUTOLOAD.MAIN.BSS_SIZE = 0; + SDK_AUTOLOAD.WRAM.START = 0x037f8000; + SDK_AUTOLOAD.WRAM.END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.BSS_END = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD.WRAM.SIZE = 0; + SDK_AUTOLOAD.WRAM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + __exception_table_start__ =.; + EXCEPTION + __exception_table_end__ =.; + SDK_STATIC_ETABLE_END =.; + + + + + + + + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(4); + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + . = ALIGN(4); + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_MAIN_START = SDK_AUTOLOAD.MAIN.START; + SDK_AUTOLOAD_MAIN_END = SDK_AUTOLOAD.MAIN.END; + SDK_AUTOLOAD_MAIN_BSS_END = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_AUTOLOAD_MAIN_SIZE = SDK_AUTOLOAD.MAIN.SIZE; + SDK_AUTOLOAD_MAIN_BSS_SIZE = SDK_AUTOLOAD.MAIN.BSS_SIZE; + SDK_AUTOLOAD_WRAM_START = SDK_AUTOLOAD.WRAM.START; + SDK_AUTOLOAD_WRAM_END = SDK_AUTOLOAD.WRAM.END; + SDK_AUTOLOAD_WRAM_BSS_END = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_AUTOLOAD_WRAM_SIZE = SDK_AUTOLOAD.WRAM.SIZE; + SDK_AUTOLOAD_WRAM_BSS_SIZE = SDK_AUTOLOAD.WRAM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> #> binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_OVERLAY..DATA_END =.; + . = ALIGN(4); + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(4); + SDK_SECTION_ARENA_START =.; + + } > arena.MAIN + + ############################ OVERLAYDEFS ############################ + .F: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > F + + ############################ OVERLAYTABLE ########################### + .F: + { + + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + } > F + + ############################ OTHERS ################################# + SDK_WRAM_ARENA_LO = SDK_AUTOLOAD.WRAM.BSS_END; + SDK_SUBPRIV_ARENA_LO = SDK_AUTOLOAD.MAIN.BSS_END; + SDK_IRQ_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE = ; # allocated in WRAM + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + + .check.WORKRAM: + { + . = . + SDK_AUTOLOAD.WRAM.BSS_END - SDK_AUTOLOAD.WRAM.START + 0x080 + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + + } > check.WORKRAM + + .check.MAINMEM: + { + . = SDK_SUBPRIV_ARENA_LO; + + } > check.MAINMEM + + ########################### LTDAUTOLOADS ############################ + SDK_LTDAUTOLOAD.LTDMAIN.START = SDK_STATIC_BSS_END; + SDK_LTDAUTOLOAD.LTDMAIN.END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.SIZE = 0; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE = 0; + SDK_LTDAUTOLOAD.LTDWRAM.START = 0x03000000; + SDK_LTDAUTOLOAD.LTDWRAM.END = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD.LTDWRAM.BSS_END = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD.LTDWRAM.SIZE = 0; + SDK_LTDAUTOLOAD.LTDWRAM.BSS_SIZE = 0; + SDK_LTDAUTOLOAD_TOP_START = 0x02e80000; + SDK_LTDAUTOLOAD_TOP_SIZE = 4; # STATIC ̈悪 4 bytes ̃_~[oCit@C̐擪ɓ # + SDK_LTDAUTOLOAD_START = SDK_LTDAUTOLOAD_TOP_START + SDK_LTDAUTOLOAD_TOP_SIZE; + SDK_LTDAUTOLOAD_SIZE = 0; + SDK_LTDAUTOLOAD_NUMBER = ; + + .binary.LTDAUTOLOAD_TOP: + { + WRITEW 0xdeadbeef; + + } >> #> binary.LTDAUTOLOAD_TOP + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDAUTOLOAD__ID =; + SDK_LTDAUTOLOAD..ID =; + SDK_LTDAUTOLOAD..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDAUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + #:::::::::: text/rodata + SDK_LTDAUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(4); + SDK_LTDAUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_LTDAUTOLOAD..DATA_END =.; + . = ALIGN(4); + SDK_LTDAUTOLOAD..END =.; + + SDK_LTDAUTOLOAD..TEXT_SIZE = SDK_LTDAUTOLOAD..TEXT_END - SDK_LTDAUTOLOAD..TEXT_START; + SDK_LTDAUTOLOAD..DATA_SIZE = SDK_LTDAUTOLOAD..DATA_END - SDK_LTDAUTOLOAD..DATA_START; + SDK_LTDAUTOLOAD..SIZE = SDK_LTDAUTOLOAD..END - SDK_LTDAUTOLOAD..START; + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDAUTOLOAD..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_LTDAUTOLOAD..BSS_END =.; + + SDK_LTDAUTOLOAD..BSS_SIZE = SDK_LTDAUTOLOAD..BSS_END - SDK_LTDAUTOLOAD..BSS_START; + + } >> + + + + SDK_LTDAUTOLOAD_LTDMAIN_START = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD_LTDMAIN_END = SDK_LTDAUTOLOAD.LTDMAIN.END; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + SDK_LTDAUTOLOAD_LTDMAIN_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.SIZE; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE; + SDK_LTDAUTOLOAD_LTDWRAM_START = SDK_LTDAUTOLOAD.LTDWRAM.START; + SDK_LTDAUTOLOAD_LTDWRAM_END = SDK_LTDAUTOLOAD.LTDWRAM.END; + SDK_LTDAUTOLOAD_LTDWRAM_BSS_END = SDK_LTDAUTOLOAD.LTDWRAM.BSS_END; + SDK_LTDAUTOLOAD_LTDWRAM_SIZE = SDK_LTDAUTOLOAD.LTDWRAM.SIZE; + SDK_LTDAUTOLOAD_LTDWRAM_BSS_SIZE = SDK_LTDAUTOLOAD.LTDWRAM.BSS_SIZE; + + ######################### LTDAUTOLOAD_INFO ########################## + .binary.LTDAUTOLOAD_INFO: + { + SDK_LTDAUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_LTDAUTOLOAD..SIZE; + WRITEW SDK_LTDAUTOLOAD..BSS_SIZE; + + SDK_LTDAUTOLOAD_LIST_END = .; + } >> #> binary.LTDAUTOLOAD_INFO + +# SDK_LTDAUTOLOAD_LIST = SDK_LTDAUTOLOAD_START + SDK_LTDAUTOLOAD_SIZE; +# SDK_LTDAUTOLOAD_LIST_END = SDK_LTDAUTOLOAD_LIST + SIZEOF(.binary.LTDAUTOLOAD_INFO); + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SIZEOF(.binary.LTDAUTOLOAD_INFO); + + ########################### LTDOVERLAYS ############################# + SDK_LTDOVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDOVERLAY__ID =; + SDK_LTDOVERLAY..ID =; + SDK_LTDOVERLAY..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDOVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_LTDOVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_LTDOVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_LTDOVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(4); + SDK_LTDOVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_LTDOVERLAY..DATA_END =.; + . = ALIGN(4); + SDK_LTDOVERLAY..END =.; + + SDK_LTDOVERLAY..TEXT_SIZE = SDK_LTDOVERLAY..TEXT_END - SDK_LTDOVERLAY..TEXT_START; + SDK_LTDOVERLAY..DATA_SIZE = SDK_LTDOVERLAY..DATA_END - SDK_LTDOVERLAY..DATA_START; + SDK_LTDOVERLAY..SIZE = SDK_LTDOVERLAY..END - SDK_LTDOVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(4); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDOVERLAY..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(4); + SDK_LTDOVERLAY..BSS_END =.; + + SDK_LTDOVERLAY..BSS_SIZE = SDK_LTDOVERLAY..BSS_END - SDK_LTDOVERLAY..BSS_START; + + } >> + + + + ########################## LTDOVERLAYDEFS ########################### + .L: + { + ### TWL limited extended static module information + WRITEW SDK_LTDAUTOLOAD_TOP_START; # load address + WRITEW 0; # padding + WRITEW SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD_TOP_SIZE; # size of module + WRITEW 0; # padding + + ### TWL limited overlay filename + + WRITES (""); + + + } > L + + ######################### LTDOVERLAYTABLE ########################### + .L: + { + + WRITES # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_LTDOVERLAY..SIZE; # size of module + WRITEW SDK_LTDOVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_LTDOVERLAY..SINIT_START; # start address of static init + WRITEW SDK_LTDOVERLAY..SINIT_END; # end address of static init + WRITEW # ROM file ID + WRITEW 0; # Reserved + + + } > L + + ############################ OTHERS ################################# + .check.LTDWRAM: + { + . = SDK_LTDAUTOLOAD.LTDWRAM.BSS_END; + + } > check.LTDWRAM + + .check.LTDMAIN: + { +# . = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + + } > check.LTDMAIN + +} diff --git a/include/firm/specfiles/ARM9-BB-FIRM.lcf.template b/include/firm/specfiles/ARM9-BB-FIRM.lcf.template new file mode 100644 index 0000000..da10b75 --- /dev/null +++ b/include/firm/specfiles/ARM9-BB-FIRM.lcf.template @@ -0,0 +1,602 @@ +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makelcf +# File: ARM9-BB-FIRM.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 # > + + (RWX) : ORIGIN = , LENGTH = 0x0 # > + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 > +# binary.STATIC_FOOTER (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + dummy.MAIN_EX (RW) : ORIGIN = 0x023e0000, LENGTH = 0x0 + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + arena.MAIN_EX (RW) : ORIGIN = AFTER(dummy.MAIN_EX,), LENGTH = 0x0 + arena.ITCM (RW) : ORIGIN = AFTER(ITCM,), LENGTH = 0x0 + arena.DTCM (RW) : ORIGIN = AFTER(DTCM,), LENGTH = 0x0 + binary.MODULE_FILES (RW) : ORIGIN = 0x0, LENGTH = 0x0 > component.files + check.ITCM (RWX) : ORIGIN = 0x0, LENGTH = 0x08000 > itcm.check + check.DTCM (RW) : ORIGIN = 0x0, LENGTH = 0x04000 > dtcm.check +} + +FORCE_ACTIVE +{ + SVC_SoftReset +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); . = ALIGN(32); # Fit to cache line + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + crt0_firm.o (.text) + libsyscall.a (.text) + crt0_firm.o (.rodata) + # + # .version ZNVljĂ܂B + # ̃ZNVɊ܂܂̓bg`FbN̍ۂ + # KvƂȂ܂̂ŁAK̈ʒuɎc悤ɂĉB + # + * (.version) + OBJECT(TwlMain,*) + + + + + + + . = ALIGN(4); + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + EXCEPTION + SDK_STATIC_ETABLE_END =.; + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(32); + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY_DIGEST =.; + # NO DIGEST + SDK_OVERLAY_DIGEST_END =.; + #:::::::::: data + . = ALIGN(32); + SDK_STATIC_DATA_END =.; + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + __exception_table_start__ = SDK_STATIC_ETABLE_START; # for exception table + __exception_table_end__ = SDK_STATIC_ETABLE_END; # for exception table + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_STATIC_BSS_END = .; + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.ITCM.START = 0x01ff8000; + SDK_AUTOLOAD.ITCM.END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.BSS_END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.SIZE = 0; + SDK_AUTOLOAD.ITCM.BSS_SIZE = 0; + SDK_AUTOLOAD.DTCM.START = 0x027e0000; + SDK_AUTOLOAD.DTCM.END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.BSS_END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.SIZE = 0; + SDK_AUTOLOAD.DTCM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(32); + SDK_AUTOLOAD..DATA_END =.; + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_ITCM_START = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD_ITCM_END = SDK_AUTOLOAD.ITCM.END; + SDK_AUTOLOAD_ITCM_BSS_END = SDK_AUTOLOAD.ITCM.BSS_END; + SDK_AUTOLOAD_ITCM_SIZE = SDK_AUTOLOAD.ITCM.SIZE; + SDK_AUTOLOAD_ITCM_BSS_SIZE = SDK_AUTOLOAD.ITCM.BSS_SIZE; + SDK_AUTOLOAD_DTCM_START = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD_DTCM_END = SDK_AUTOLOAD.DTCM.END; + SDK_AUTOLOAD_DTCM_BSS_END = SDK_AUTOLOAD.DTCM.BSS_END; + SDK_AUTOLOAD_DTCM_SIZE = SDK_AUTOLOAD.DTCM.SIZE; + SDK_AUTOLOAD_DTCM_BSS_SIZE = SDK_AUTOLOAD.DTCM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> # > binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ STATIC_FOOTER ########################## + .binary.STATIC_FOOTER: + { + WRITEW 0xdec00621; # LE(0x2106C0DE) = NITRO CODE + WRITEW _start_ModuleParams - ADDR(.); + WRITEW 0; # NO DIGEST + } >> # > binary.STATIC_FOOTER + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(32); + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(32); + SDK_OVERLAY..DATA_END =.; + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ MAIN EX ################################## + # MAIN EX Area + .dummy.MAIN_EX: + { + . = ALIGN(32); + } > dummy.MAIN_EX + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(32); + SDK_SECTION_ARENA_START =.; + } > arena.MAIN + + .arena.MAIN_EX: + { + . = ALIGN(32); + SDK_SECTION_ARENA_EX_START =.; + } > arena.MAIN_EX + + .arena.ITCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_ITCM_START =.; + } > arena.ITCM + + .arena.DTCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_DTCM_START =.; + } > arena.DTCM + + ############################ OVERLAYDEFS ############################ + .: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > + + + ############################ OVERLAYTABLE ########################### + .: + { + + # Overlay + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + + } > + + + ############################ OTHERS ################################# + SDK_MAIN_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in DTCM + SDK_SYS_STACKSIZE = ; # when 0 means all remains of DTCM + + # Module filelist + .binary.MODULE_FILES: + { + WRITES (""); + WRITES (""); + WRITES (""); + } > binary.MODULE_FILES + + # ITCM/DTCM size checker => check AUTOLOAD_ITCM/DTCM + .check.ITCM: + { + . = . + SDK_AUTOLOAD_ITCM_SIZE + SDK_AUTOLOAD_ITCM_BSS_SIZE; + } > check.ITCM + + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + .check.DTCM: + { + . = . + SDK_AUTOLOAD_DTCM_SIZE + SDK_AUTOLOAD_DTCM_BSS_SIZE; + . = . + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.DTCM + +} diff --git a/include/firm/specfiles/ARM9-BB-FIRM.lsf b/include/firm/specfiles/ARM9-BB-FIRM.lsf new file mode 100644 index 0000000..c7676d2 --- /dev/null +++ b/include/firm/specfiles/ARM9-BB-FIRM.lsf @@ -0,0 +1,42 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM9-BB-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x03800000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) +} + +Autoload ITCM +{ + Address 0x01ff8000 + Object * (.itcm) + Object $(OBJS_AUTOLOAD) (.text) +} + +Autoload DTCM +{ + Address 0x027e0000 + Object * (.dtcm) + Object $(OBJS_AUTOLOAD) (.data) + Object $(OBJS_AUTOLOAD) (.bss) +} + diff --git a/include/firm/specfiles/ARM9-BB-GCDFIRM.lcf.template b/include/firm/specfiles/ARM9-BB-GCDFIRM.lcf.template new file mode 100644 index 0000000..4cace18 --- /dev/null +++ b/include/firm/specfiles/ARM9-BB-GCDFIRM.lcf.template @@ -0,0 +1,602 @@ +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makelcf +# File: ARM9-BB-NORFIRM.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 # > + + (RWX) : ORIGIN = , LENGTH = 0x0 # > + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 > +# binary.STATIC_FOOTER (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + dummy.MAIN_EX (RW) : ORIGIN = 0x023e0000, LENGTH = 0x0 + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + arena.MAIN_EX (RW) : ORIGIN = AFTER(dummy.MAIN_EX,), LENGTH = 0x0 + arena.ITCM (RW) : ORIGIN = AFTER(ITCM,), LENGTH = 0x0 + arena.DTCM (RW) : ORIGIN = AFTER(DTCM,), LENGTH = 0x0 + binary.MODULE_FILES (RW) : ORIGIN = 0x0, LENGTH = 0x0 > component.files + check.ITCM (RWX) : ORIGIN = 0x0, LENGTH = 0x08000 > itcm.check + check.DTCM (RW) : ORIGIN = 0x0, LENGTH = 0x04000 > dtcm.check +} + +FORCE_ACTIVE +{ + SVC_SoftReset +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); . = ALIGN(32); # Fit to cache line + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + crt0.o (.text) + libsyscall.a (.text) + crt0.o (.rodata) + # + # .version ZNVljĂ܂B + # ̃ZNVɊ܂܂̓bg`FbN̍ۂ + # KvƂȂ܂̂ŁAK̈ʒuɎc悤ɂĉB + # + * (.version) + OBJECT(TwlMain,*) + + + + + + + . = ALIGN(4); + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + EXCEPTION + SDK_STATIC_ETABLE_END =.; + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(32); + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY_DIGEST =.; + # NO DIGEST + SDK_OVERLAY_DIGEST_END =.; + #:::::::::: data + . = ALIGN(32); + SDK_STATIC_DATA_END =.; + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + __exception_table_start__ = SDK_STATIC_ETABLE_START; # for exception table + __exception_table_end__ = SDK_STATIC_ETABLE_END; # for exception table + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_STATIC_BSS_END = .; + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.ITCM.START = 0x01ff8000; + SDK_AUTOLOAD.ITCM.END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.BSS_END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.SIZE = 0; + SDK_AUTOLOAD.ITCM.BSS_SIZE = 0; + SDK_AUTOLOAD.DTCM.START = 0x027e0000; + SDK_AUTOLOAD.DTCM.END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.BSS_END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.SIZE = 0; + SDK_AUTOLOAD.DTCM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(32); + SDK_AUTOLOAD..DATA_END =.; + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_ITCM_START = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD_ITCM_END = SDK_AUTOLOAD.ITCM.END; + SDK_AUTOLOAD_ITCM_BSS_END = SDK_AUTOLOAD.ITCM.BSS_END; + SDK_AUTOLOAD_ITCM_SIZE = SDK_AUTOLOAD.ITCM.SIZE; + SDK_AUTOLOAD_ITCM_BSS_SIZE = SDK_AUTOLOAD.ITCM.BSS_SIZE; + SDK_AUTOLOAD_DTCM_START = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD_DTCM_END = SDK_AUTOLOAD.DTCM.END; + SDK_AUTOLOAD_DTCM_BSS_END = SDK_AUTOLOAD.DTCM.BSS_END; + SDK_AUTOLOAD_DTCM_SIZE = SDK_AUTOLOAD.DTCM.SIZE; + SDK_AUTOLOAD_DTCM_BSS_SIZE = SDK_AUTOLOAD.DTCM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> # > binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ STATIC_FOOTER ########################## + .binary.STATIC_FOOTER: + { + WRITEW 0xdec00621; # LE(0x2106C0DE) = NITRO CODE + WRITEW _start_ModuleParams - ADDR(.); + WRITEW 0; # NO DIGEST + } >> # > binary.STATIC_FOOTER + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(32); + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(32); + SDK_OVERLAY..DATA_END =.; + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ MAIN EX ################################## + # MAIN EX Area + .dummy.MAIN_EX: + { + . = ALIGN(32); + } > dummy.MAIN_EX + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(32); + SDK_SECTION_ARENA_START =.; + } > arena.MAIN + + .arena.MAIN_EX: + { + . = ALIGN(32); + SDK_SECTION_ARENA_EX_START =.; + } > arena.MAIN_EX + + .arena.ITCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_ITCM_START =.; + } > arena.ITCM + + .arena.DTCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_DTCM_START =.; + } > arena.DTCM + + ############################ OVERLAYDEFS ############################ + .: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > + + + ############################ OVERLAYTABLE ########################### + .: + { + + # Overlay + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + + } > + + + ############################ OTHERS ################################# + SDK_MAIN_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in DTCM + SDK_SYS_STACKSIZE = ; # when 0 means all remains of DTCM + + # Module filelist + .binary.MODULE_FILES: + { + WRITES (""); + WRITES (""); + WRITES (""); + } > binary.MODULE_FILES + + # ITCM/DTCM size checker => check AUTOLOAD_ITCM/DTCM + .check.ITCM: + { + . = . + SDK_AUTOLOAD_ITCM_SIZE + SDK_AUTOLOAD_ITCM_BSS_SIZE; + } > check.ITCM + + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + .check.DTCM: + { + . = . + SDK_AUTOLOAD_DTCM_SIZE + SDK_AUTOLOAD_DTCM_BSS_SIZE; + . = . + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.DTCM + +} diff --git a/include/firm/specfiles/ARM9-BB-GCDFIRM.lsf b/include/firm/specfiles/ARM9-BB-GCDFIRM.lsf new file mode 100644 index 0000000..c7676d2 --- /dev/null +++ b/include/firm/specfiles/ARM9-BB-GCDFIRM.lsf @@ -0,0 +1,42 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM9-BB-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x03800000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) +} + +Autoload ITCM +{ + Address 0x01ff8000 + Object * (.itcm) + Object $(OBJS_AUTOLOAD) (.text) +} + +Autoload DTCM +{ + Address 0x027e0000 + Object * (.dtcm) + Object $(OBJS_AUTOLOAD) (.data) + Object $(OBJS_AUTOLOAD) (.bss) +} + diff --git a/include/firm/specfiles/ARM9-TS-FIRM.lcf.template b/include/firm/specfiles/ARM9-TS-FIRM.lcf.template new file mode 100644 index 0000000..fd41209 --- /dev/null +++ b/include/firm/specfiles/ARM9-TS-FIRM.lcf.template @@ -0,0 +1,1033 @@ +#--------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ARM9-BB.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 > + + + (RWX) : ORIGIN = , LENGTH = 0x0 >> + + binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + binary.STATIC_FOOTER (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + dummy.MAIN_EX.NITRO (RW) : ORIGIN = 0x023e0000, LENGTH = 0x0 + arena.MAIN.NITRO (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + arena.MAIN_EX.NITRO (RW) : ORIGIN = AFTER(dummy.MAIN_EX.NITRO,), LENGTH = 0x0 + arena.ITCM (RW) : ORIGIN = AFTER(ITCM,), LENGTH = 0x0 + arena.DTCM (RW) : ORIGIN = AFTER(DTCM,), LENGTH = 0x0 + + check.ITCM (RW) : ORIGIN = 0x0, LENGTH = 0x08000 > itcm.check + check.DTCM (RW) : ORIGIN = 0x0, LENGTH = 0x04000 > dtcm.check + + binary.LTDAUTOLOAD_TOP (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWX) : ORIGIN = , LENGTH = 0x0 >> + + binary.LTDAUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + dummy.MAIN_EX.TWL (RW) : ORIGIN = 0x0d000000, LENGTH = 0x0 + arena.MAIN.TWL (RW) : ORIGIN = AFTER(,,LTDMAIN,), LENGTH = 0x0 + arena.MAIN_EX.TWL (RW) : ORIGIN = AFTER(dummy.MAIN_EX.TWL,,,LTDMAIN,), LENGTH = 0x0 + + binary.MODULE_FILES (RW) : ORIGIN = 0, LENGTH = 0x0 > component.files +} + +FORCE_ACTIVE +{ + SVC_SoftReset +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + OBJECT(_start,*) + crt0_firm.o (.text) + crt0_firm.o (.rodata) + libsyscall.a (.text) + # + # .version ZNVljĂ܂B + # ̃ZNVɊ܂܂̓bg`FbN̍ۂ + # KvƂȂ܂̂ŁAK̈ʒuɎc悤ɂĉB + # + * (.version) + OBJECT(TwlMain,*) + + + + + + + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + __exception_table_start__ =.; + EXCEPTION + __exception_table_end__ =.; + SDK_STATIC_ETABLE_END =.; + + + + + + + + + + + + + . = ALIGN(4); + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + #:::::::::: text/rodata + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); # Fit to cache line + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY_DIGEST =.; + # NO DIGEST + SDK_OVERLAY_DIGEST_END =.; + #:::::::::: data + SDK_STATIC_DATA_END =.; + . = ALIGN(32); + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_STATIC_BSS_END = .; + + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.ITCM.START = 0x01ff8000; + SDK_AUTOLOAD.ITCM.END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.BSS_END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.SIZE = 0; + SDK_AUTOLOAD.ITCM.BSS_SIZE = 0; + SDK_AUTOLOAD.DTCM.START = 0x02fe0000; + SDK_AUTOLOAD.DTCM.END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.BSS_END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.SIZE = 0; + SDK_AUTOLOAD.DTCM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_AUTOLOAD..SINIT_START = .; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_AUTOLOAD..SINIT_END = .; + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(32); + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + . = ALIGN(32); + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_ITCM_START = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD_ITCM_END = SDK_AUTOLOAD.ITCM.END; + SDK_AUTOLOAD_ITCM_BSS_END = SDK_AUTOLOAD.ITCM.BSS_END; + SDK_AUTOLOAD_ITCM_SIZE = SDK_AUTOLOAD.ITCM.SIZE; + SDK_AUTOLOAD_ITCM_BSS_SIZE = SDK_AUTOLOAD.ITCM.BSS_SIZE; + SDK_AUTOLOAD_DTCM_START = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD_DTCM_END = SDK_AUTOLOAD.DTCM.END; + SDK_AUTOLOAD_DTCM_BSS_END = SDK_AUTOLOAD.DTCM.BSS_END; + SDK_AUTOLOAD_DTCM_SIZE = SDK_AUTOLOAD.DTCM.SIZE; + SDK_AUTOLOAD_DTCM_BSS_SIZE = SDK_AUTOLOAD.DTCM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..SINIT_START; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + } > binary.AUTOLOAD_INFO + + SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; + SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ STATIC_FOOTER ########################## + .binary.STATIC_FOOTER: + { + WRITEW 0xdec00621; # LE(0x2106C0DE) = NITRO CODE + WRITEW _start_ModuleParams - ADDR(.); + WRITEW 0; # NO DIGEST + WRITEW _start_LtdModuleParams - ADDR(.); + } > binary.STATIC_FOOTER + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_OVERLAY..DATA_END =.; + . = ALIGN(32); + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ OVERLAYDEFS ############################ + .F: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > F + + ############################ OVERLAYTABLE ########################### + .F: + { + + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + } > F + + ############################ ARENA ################################## + .dummy.MAIN_EX.NITRO: + { + . = ALIGN(32); + + } > dummy.MAIN_EX.NITRO + + .arena.MAIN.NITRO: + { + . = ALIGN(32); + SDK_SECTION_ARENA_START =.; + + } > arena.MAIN.NITRO + + .arena.MAIN_EX.NITRO: + { + . = ALIGN(32); + SDK_SECTION_ARENA_EX_START =.; + + } > arena.MAIN_EX.NITRO + + .arena.ITCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_ITCM_START =.; + + } > arena.ITCM + + .arena.DTCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_DTCM_START =.; + + } > arena.DTCM + + ############################ OTHERS ################################# + SDK_MAIN_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in DTCM + SDK_SYS_STACKSIZE = ; # when 0 means all remains of DTCM + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + + .check.ITCM: + { + . = . + SDK_AUTOLOAD_ITCM_SIZE + SDK_AUTOLOAD_ITCM_BSS_SIZE; + + . = . + SDK_OVERLAY..SIZE + SDK_OVERLAY..BSS_SIZE; + + + } > check.ITCM + + .check.DTCM: + { + . = . + SDK_AUTOLOAD_DTCM_SIZE + SDK_AUTOLOAD_DTCM_BSS_SIZE; + + . = . + SDK_OVERLAY..SIZE + SDK_OVERLAY..BSS_SIZE; + + . = . + 0x080 + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.DTCM + + ########################### LTDAUTOLOADS ############################ + SDK_LTDAUTOLOAD.LTDMAIN.START = SDK_STATIC_BSS_END; + SDK_LTDAUTOLOAD.LTDMAIN.END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_EDN = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.SIZE = 0; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE = 0; + SDK_LTDAUTOLOAD_TOP_START = 0x02400000; + SDK_LTDAUTOLOAD_TOP_SIZE = 4; # STATIC ̈悪 4 bytes ̃_~[oCit@C̐擪ɓ # + SDK_LTDAUTOLOAD_START = SDK_LTDAUTOLOAD_TOP_START + SDK_LTDAUTOLOAD_TOP_SIZE; + SDK_LTDAUTOLOAD_SIZE = 0; + SDK_LTDAUTOLOAD_NUMBER = ; + + .binary.LTDAUTOLOAD_TOP: + { + WRITEW 0; + + } > binary.LTDAUTOLOAD_TOP + + + .: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDAUTOLOAD__ID =; + SDK_LTDAUTOLOAD..ID =; + SDK_LTDAUTOLOAD..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDAUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_LTDAUTOLOAD..SINIT_START = .; + #:::::::::: ctor + + + + + + + + + + + + + #:::::::::: ctor + SDK_LTDAUTOLOAD..SINIT_END = .; + #:::::::::: text/rodata + SDK_LTDAUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); + SDK_LTDAUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_LTDAUTOLOAD..DATA_END =.; + . = ALIGN(32); + SDK_LTDAUTOLOAD..END =.; + + SDK_LTDAUTOLOAD..TEXT_SIZE = SDK_LTDAUTOLOAD..TEXT_END - SDK_LTDAUTOLOAD..TEXT_START; + SDK_LTDAUTOLOAD..DATA_SIZE = SDK_LTDAUTOLOAD..DATA_END - SDK_LTDAUTOLOAD..DATA_START; + SDK_LTDAUTOLOAD..SIZE = SDK_LTDAUTOLOAD..END - SDK_LTDAUTOLOAD..START; + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDAUTOLOAD..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_LTDAUTOLOAD..BSS_END =.; + + SDK_LTDAUTOLOAD..BSS_SIZE = SDK_LTDAUTOLOAD..BSS_END - SDK_LTDAUTOLOAD..BSS_START; + + } >> + + + + SDK_LTDAUTOLOAD_LTDMAIN_START = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD_LTDMAIN_END = SDK_LTDAUTOLOAD.LTDMAIN.END; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + SDK_LTDAUTOLOAD_LTDMAIN_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.SIZE; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE; + + ######################### LTDAUTOLOAD_INFO ########################## + .binary.LTDAUTOLOAD_INFO: + { + + WRITEW ADDR(.); + WRITEW SDK_LTDAUTOLOAD..SIZE; + WRITEW SDK_LTDAUTOLOAD..BSS_SIZE; + + } > binary.LTDAUTOLOAD_INFO + + SDK_LTDAUTOLOAD_LIST = SDK_LTDAUTOLOAD_START + SDK_LTDAUTOLOAD_SIZE; + SDK_LTDAUTOLOAD_LIST_END = SDK_LTDAUTOLOAD_LIST + SIZEOF(.binary.LTDAUTOLOAD_INFO); + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SIZEOF(.binary.LTDAUTOLOAD_INFO); + + ########################### LTDOVERLAYS ############################# + SDK_LTDOVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDOVERLAY__ID =; + SDK_LTDOVERLAY..ID =; + SDK_LTDOVERLAY..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDOVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_LTDOVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_LTDOVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_LTDOVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); + SDK_LTDOVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_LTDOVERLAY..DATA_END =.; + . = ALIGN(32); + SDK_LTDOVERLAY..END =.; + + SDK_LTDOVERLAY..TEXT_SIZE = SDK_LTDOVERLAY..TEXT_END - SDK_LTDOVERLAY..TEXT_START; + SDK_LTDOVERLAY..DATA_SIZE = SDK_LTDOVERLAY..DATA_END - SDK_LTDOVERLAY..DATA_START; + SDK_LTDOVERLAY..SIZE = SDK_LTDOVERLAY..END - SDK_LTDOVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDOVERLAY..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_LTDOVERLAY..BSS_END =.; + + SDK_LTDOVERLAY..BSS_SIZE = SDK_LTDOVERLAY..BSS_END - SDK_LTDOVERLAY..BSS_START; + + } >> + + + + ########################## LTDOVERLAYDEFS ########################### + .L: + { + ### TWL limited extended static module information + WRITEW SDK_LTDAUTOLOAD_TOP_START; # load address + WRITEW 0; # padding + WRITEW SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD_TOP_SIZE; # size of module + WRITEW 0; # padding + + ### TWL limited overlay filename + + WRITES (""); + + + } > L + + ######################### LTDOVERLAYTABLE ########################### + .L: + { + + WRITES # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_LTDOVERLAY..SIZE; # size of module + WRITEW SDK_LTDOVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_LTDOVERLAY..SINIT_START; # start address of static init + WRITEW SDK_LTDOVERLAY..SINIT_END; # end address of static init + WRITEW # ROM file ID + WRITEW 0; # Reserved + + + } > L + + ############################ ARENA ################################## + .dummy.MAIN_EX.TWL: + { + . = ALIGN(32); + + } > dummy.MAIN_EX.TWL + + .arena.MAIN.TWL: + { + . = ALIGN(32); + SDK_LTDMAIN_ARENA_LO =.; + + } > arena.MAIN.TWL + + .arena.MAIN_EX.TWL: + { + . = ALIGN(32); + SDK_LTDMAIN_EX_ARENA_LO =.; + + } > arena.MAIN_EX.TWL + + ############################ OTHERS ################################# + # Module filelist + .binary.MODULE_FILES: + { + WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + + } > binary.MODULE_FILES + +} diff --git a/include/firm/specfiles/ARM9-TS-FIRM.lsf b/include/firm/specfiles/ARM9-TS-FIRM.lsf new file mode 100644 index 0000000..272005c --- /dev/null +++ b/include/firm/specfiles/ARM9-TS-FIRM.lsf @@ -0,0 +1,56 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM9-TS-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x03800000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) + Object * (.itcm) + Object $(OBJS_AUTOLOAD) (.text) + Object $(OBJS_AUTOLOAD) (.rodata) + Object $(OBJS_AUTOLOAD) (.init) + Object $(OBJS_AUTOLOAD) (.ctor) + Object $(OBJS_AUTOLOAD) (.sinit) + Object * (.ltdmain) + Object $(OBJS_LTDAUTOLOAD) + Library $(LLIBS_EX) $(GLIBS_EX) + Object * (.dtcm) + Object $(OBJS_AUTOLOAD) (.data) + Object $(OBJS_AUTOLOAD) (.sdata) + Object $(OBJS_AUTOLOAD) (.bss) + Object $(OBJS_AUTOLOAD) (.sbss) +} + +Autoload ITCM +{ + Address 0x01ff8000 +} + +Autoload DTCM +{ + Address $(ADDRESS_DTCM) +} + +Ltdautoload LTDMAIN +{ + # NITRO/TWL L̃I[o[C݂ꍇ́Aɂ̌ɔzuKv܂B + After $(TARGET_NAME) +} diff --git a/include/firm/specfiles/ARM9-TS-GCDFIRM.lcf.template b/include/firm/specfiles/ARM9-TS-GCDFIRM.lcf.template new file mode 100644 index 0000000..a5236b6 --- /dev/null +++ b/include/firm/specfiles/ARM9-TS-GCDFIRM.lcf.template @@ -0,0 +1,602 @@ +#--------------------------------------------------------------------------- +# Project: TwlFirm - tools - makelcf +# File: ARM9-TS-NORFIRM.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev:$ +# $Author:$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 # > + + (RWX) : ORIGIN = , LENGTH = 0x0 # > + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 > +# binary.STATIC_FOOTER (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + (RW) : ORIGIN = AFTER(), LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + dummy.MAIN_EX (RW) : ORIGIN = 0x023e0000, LENGTH = 0x0 + arena.MAIN (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + arena.MAIN_EX (RW) : ORIGIN = AFTER(dummy.MAIN_EX,), LENGTH = 0x0 + arena.ITCM (RW) : ORIGIN = AFTER(ITCM,), LENGTH = 0x0 + arena.DTCM (RW) : ORIGIN = AFTER(DTCM,), LENGTH = 0x0 + binary.MODULE_FILES (RW) : ORIGIN = 0x0, LENGTH = 0x0 > component.files + check.ITCM (RWX) : ORIGIN = 0x0, LENGTH = 0x08000 > itcm.check + check.DTCM (RW) : ORIGIN = 0x0, LENGTH = 0x04000 > dtcm.check +} + +FORCE_ACTIVE +{ + SVC_SoftReset +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); . = ALIGN(32); # Fit to cache line + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + crt0.o (.text) + libsyscall.a (.text) + crt0.o (.rodata) + # + # .version ZNVljĂ܂B + # ̃ZNVɊ܂܂̓bg`FbN̍ۂ + # KvƂȂ܂̂ŁAK̈ʒuɎc悤ɂĉB + # + * (.version) + OBJECT(TwlMain,*) + + + + + + + . = ALIGN(4); + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + EXCEPTION + SDK_STATIC_ETABLE_END =.; + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(32); + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY_DIGEST =.; + # NO DIGEST + SDK_OVERLAY_DIGEST_END =.; + #:::::::::: data + . = ALIGN(32); + SDK_STATIC_DATA_END =.; + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + __exception_table_start__ = SDK_STATIC_ETABLE_START; # for exception table + __exception_table_end__ = SDK_STATIC_ETABLE_END; # for exception table + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_STATIC_BSS_END = .; + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.ITCM.START = 0x01ff8000; + SDK_AUTOLOAD.ITCM.END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.BSS_END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.SIZE = 0; + SDK_AUTOLOAD.ITCM.BSS_SIZE = 0; + SDK_AUTOLOAD.DTCM.START = 0x027e0000; + SDK_AUTOLOAD.DTCM.END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.BSS_END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.SIZE = 0; + SDK_AUTOLOAD.DTCM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(32); + SDK_AUTOLOAD..DATA_END =.; + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_ITCM_START = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD_ITCM_END = SDK_AUTOLOAD.ITCM.END; + SDK_AUTOLOAD_ITCM_BSS_END = SDK_AUTOLOAD.ITCM.BSS_END; + SDK_AUTOLOAD_ITCM_SIZE = SDK_AUTOLOAD.ITCM.SIZE; + SDK_AUTOLOAD_ITCM_BSS_SIZE = SDK_AUTOLOAD.ITCM.BSS_SIZE; + SDK_AUTOLOAD_DTCM_START = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD_DTCM_END = SDK_AUTOLOAD.DTCM.END; + SDK_AUTOLOAD_DTCM_BSS_END = SDK_AUTOLOAD.DTCM.BSS_END; + SDK_AUTOLOAD_DTCM_SIZE = SDK_AUTOLOAD.DTCM.SIZE; + SDK_AUTOLOAD_DTCM_BSS_SIZE = SDK_AUTOLOAD.DTCM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> # > binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + + ############################ STATIC_FOOTER ########################## + .binary.STATIC_FOOTER: + { + WRITEW 0xdec00621; # LE(0x2106C0DE) = NITRO CODE + WRITEW _start_ModuleParams - ADDR(.); + WRITEW 0; # NO DIGEST + } >> # > binary.STATIC_FOOTER + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + + #:::::::::: text/rodata + . = ALIGN(32); + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: data + . = ALIGN(32); + SDK_OVERLAY..DATA_END =.; + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); . = ALIGN(32); + + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + . = ALIGN(4); + + + + + + + . = ALIGN(4); + #:::::::::: bss + . = ALIGN(32); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ MAIN EX ################################## + # MAIN EX Area + .dummy.MAIN_EX: + { + . = ALIGN(32); + } > dummy.MAIN_EX + + ############################ ARENA ################################## + .arena.MAIN: + { + . = ALIGN(32); + SDK_SECTION_ARENA_START =.; + } > arena.MAIN + + .arena.MAIN_EX: + { + . = ALIGN(32); + SDK_SECTION_ARENA_EX_START =.; + } > arena.MAIN_EX + + .arena.ITCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_ITCM_START =.; + } > arena.ITCM + + .arena.DTCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_DTCM_START =.; + } > arena.DTCM + + ############################ OVERLAYDEFS ############################ + .: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > + + + ############################ OVERLAYTABLE ########################### + .: + { + + # Overlay + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + + } > + + + ############################ OTHERS ################################# + SDK_MAIN_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in DTCM + SDK_SYS_STACKSIZE = ; # when 0 means all remains of DTCM + + # Module filelist + .binary.MODULE_FILES: + { + WRITES (""); + WRITES (""); + WRITES (""); + } > binary.MODULE_FILES + + # ITCM/DTCM size checker => check AUTOLOAD_ITCM/DTCM + .check.ITCM: + { + . = . + SDK_AUTOLOAD_ITCM_SIZE + SDK_AUTOLOAD_ITCM_BSS_SIZE; + } > check.ITCM + + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + .check.DTCM: + { + . = . + SDK_AUTOLOAD_DTCM_SIZE + SDK_AUTOLOAD_DTCM_BSS_SIZE; + . = . + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.DTCM + +} diff --git a/include/firm/specfiles/ARM9-TS-GCDFIRM.lsf b/include/firm/specfiles/ARM9-TS-GCDFIRM.lsf new file mode 100644 index 0000000..2678095 --- /dev/null +++ b/include/firm/specfiles/ARM9-TS-GCDFIRM.lsf @@ -0,0 +1,42 @@ +#---------------------------------------------------------------------------- +# Project: TwlFirm - include +# File: ARM9-TS-NORFIRM.lsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: 2007-09-06$ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TwlFirm LCF SPEC FILE +# + +Static $(TARGET_NAME) +{ + Address 0x03800000 + Object $(OBJS_STATIC) + Library $(LLIBS) $(GLIBS) $(CW_LIBS) +} + +Autoload ITCM +{ + Address 0x01ff8000 + Object * (.itcm) + Object $(OBJS_AUTOLOAD) (.text) +} + +Autoload DTCM +{ + Address 0x027e0000 + Object * (.dtcm) + Object $(OBJS_AUTOLOAD) (.data) + Object $(OBJS_AUTOLOAD) (.bss) +} + diff --git a/include/firm/specfiles/ARM9-TS-PARTNER.lcf.template b/include/firm/specfiles/ARM9-TS-PARTNER.lcf.template new file mode 100644 index 0000000..d4582b7 --- /dev/null +++ b/include/firm/specfiles/ARM9-TS-PARTNER.lcf.template @@ -0,0 +1,983 @@ +#--------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ARM9-BB.lcf.template +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded instructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#--------------------------------------------------------------------------- +MEMORY +{ + (RWX) : ORIGIN = , LENGTH = 0x0 #> + + + (RWX) : ORIGIN = , LENGTH = 0x0 #>> + +# binary.AUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> +# binary.STATIC_FOOTER (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + F (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + dummy.MAIN_EX.NITRO (RW) : ORIGIN = 0x023e0000, LENGTH = 0x0 + arena.MAIN.NITRO (RW) : ORIGIN = AFTER(,), LENGTH = 0x0 + arena.MAIN_EX.NITRO (RW) : ORIGIN = AFTER(dummy.MAIN_EX.NITRO,), LENGTH = 0x0 + arena.ITCM (RW) : ORIGIN = AFTER(ITCM,), LENGTH = 0x0 + arena.DTCM (RW) : ORIGIN = AFTER(DTCM,), LENGTH = 0x0 + + check.ITCM (RW) : ORIGIN = 0x0, LENGTH = 0x08000 > itcm.check + check.DTCM (RW) : ORIGIN = 0x0, LENGTH = 0x04000 > dtcm.check + +# binary.LTDAUTOLOAD_TOP (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWX) : ORIGIN = , LENGTH = 0x0 #>> + +# binary.LTDAUTOLOAD_INFO (RWX) : ORIGIN = 0, LENGTH = 0x0 >> + + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + L (RW) : ORIGIN = 0, LENGTH = 0x0 > + + (RWXO): ORIGIN = , LENGTH = 0x0 > + + + dummy.MAIN_EX.TWL (RW) : ORIGIN = 0x0d000000, LENGTH = 0x0 + arena.MAIN.TWL (RW) : ORIGIN = AFTER(,,LTDMAIN,), LENGTH = 0x0 + arena.MAIN_EX.TWL (RW) : ORIGIN = AFTER(dummy.MAIN_EX.TWL,,,LTDMAIN,), LENGTH = 0x0 + + binary.MODULE_FILES (RW) : ORIGIN = 0, LENGTH = 0x0 > component.files +} + +FORCE_ACTIVE +{ + SVC_SoftReset +} + +KEEP_SECTION +{ + .sinit +} + +SECTIONS +{ + ############################ STATIC ################################# + .: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_STATIC_START =.; + SDK_STATIC_TEXT_START =.; + #:::::::::: text/rodata + libsyscall.a (.text) + OBJECT(_start,*) + crt0_firm.o (.text) + crt0_firm.o (.rodata) + # + # .version ZNVljĂ܂B + # ̃ZNVɊ܂܂̓bg`FbN̍ۂ + # KvƂȂ܂̂ŁAK̈ʒuɎc悤ɂĉB + # + * (.version) + OBJECT(TwlMain,*) + + + + + + + * (.exception) + . = ALIGN(4); + SDK_STATIC_ETABLE_START =.; + __exception_table_start__ =.; + EXCEPTION + __exception_table_end__ =.; + SDK_STATIC_ETABLE_END =.; + + + + + + + + + + + + + . = ALIGN(4); + SDK_STATIC_SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_STATIC_SINIT_END =.; + #:::::::::: text/rodata + SDK_STATIC_TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); # Fit to cache line + SDK_STATIC_DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY_DIGEST =.; + # NO DIGEST + SDK_OVERLAY_DIGEST_END =.; + #:::::::::: data + SDK_STATIC_DATA_END =.; + . = ALIGN(32); + SDK_STATIC_END =.; + + SDK_STATIC_TEXT_SIZE = SDK_STATIC_TEXT_END - SDK_STATIC_TEXT_START; + SDK_STATIC_DATA_SIZE = SDK_STATIC_DATA_END - SDK_STATIC_DATA_START; + SDK_STATIC_SIZE = SDK_STATIC_END - SDK_STATIC_START; + __sinit__ = SDK_STATIC_SINIT_START; # for static initializer + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_STATIC_BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_STATIC_BSS_END = .; + + SDK_STATIC_BSS_SIZE = SDK_STATIC_BSS_END - SDK_STATIC_BSS_START; + + } >> + + + ############################ AUTOLOADS ############################## + SDK_AUTOLOAD.ITCM.START = 0x01ff8000; + SDK_AUTOLOAD.ITCM.END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.BSS_END = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD.ITCM.SIZE = 0; + SDK_AUTOLOAD.ITCM.BSS_SIZE = 0; + SDK_AUTOLOAD.DTCM.START = 0x02fe0000; + SDK_AUTOLOAD.DTCM.END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.BSS_END = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD.DTCM.SIZE = 0; + SDK_AUTOLOAD.DTCM.BSS_SIZE = 0; + SDK_AUTOLOAD_START = SDK_STATIC_END; + SDK_AUTOLOAD_SIZE = 0; + SDK_AUTOLOAD_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_AUTOLOAD__ID =; + SDK_AUTOLOAD..ID =; + SDK_AUTOLOAD..START =.; + SDK_AUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + #:::::::::: text/rodata + SDK_AUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE BLOCK + # + . = ALIGN(32); + SDK_AUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_AUTOLOAD..DATA_END =.; + . = ALIGN(32); + SDK_AUTOLOAD..END =.; + + SDK_AUTOLOAD..TEXT_SIZE = SDK_AUTOLOAD..TEXT_END - SDK_AUTOLOAD..TEXT_START; + SDK_AUTOLOAD..DATA_SIZE = SDK_AUTOLOAD..DATA_END - SDK_AUTOLOAD..DATA_START; + SDK_AUTOLOAD..SIZE = SDK_AUTOLOAD..END - SDK_AUTOLOAD..START; + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SDK_AUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL + + + # + # BSS BLOCK + # + SDK_AUTOLOAD..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_AUTOLOAD..BSS_END = .; + + SDK_AUTOLOAD..BSS_SIZE = SDK_AUTOLOAD..BSS_END - SDK_AUTOLOAD..BSS_START; + + } >> + + + + SDK_AUTOLOAD_ITCM_START = SDK_AUTOLOAD.ITCM.START; + SDK_AUTOLOAD_ITCM_END = SDK_AUTOLOAD.ITCM.END; + SDK_AUTOLOAD_ITCM_BSS_END = SDK_AUTOLOAD.ITCM.BSS_END; + SDK_AUTOLOAD_ITCM_SIZE = SDK_AUTOLOAD.ITCM.SIZE; + SDK_AUTOLOAD_ITCM_BSS_SIZE = SDK_AUTOLOAD.ITCM.BSS_SIZE; + SDK_AUTOLOAD_DTCM_START = SDK_AUTOLOAD.DTCM.START; + SDK_AUTOLOAD_DTCM_END = SDK_AUTOLOAD.DTCM.END; + SDK_AUTOLOAD_DTCM_BSS_END = SDK_AUTOLOAD.DTCM.BSS_END; + SDK_AUTOLOAD_DTCM_SIZE = SDK_AUTOLOAD.DTCM.SIZE; + SDK_AUTOLOAD_DTCM_BSS_SIZE = SDK_AUTOLOAD.DTCM.BSS_SIZE; + + ############################ AUTOLOAD_INFO ########################## + .binary.AUTOLOAD_INFO: + { + SDK_AUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_AUTOLOAD..SIZE; + WRITEW SDK_AUTOLOAD..BSS_SIZE; + + SDK_AUTOLOAD_LIST_END = .; + } >> #> binary.AUTOLOAD_INFO + +# SDK_AUTOLOAD_LIST = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE; +# SDK_AUTOLOAD_LIST_END = SDK_AUTOLOAD_START + SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + SDK_AUTOLOAD_SIZE = SDK_AUTOLOAD_SIZE + SIZEOF(.binary.AUTOLOAD_INFO); + +# ############################ STATIC_FOOTER ########################## +# .binary.STATIC_FOOTER: +# { +# WRITEW 0xdec00621; # LE(0x2106C0DE) = NITRO CODE +# WRITEW _start_ModuleParams - ADDR(.); +# WRITEW 0; # NO DIGEST +# } > binary.STATIC_FOOTER + + ############################ OVERLAYS ############################### + SDK_OVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # TEXT BLOCK: READ ONLY + # + SDK_OVERLAY__ID =; ### SEGMENT OVERLAY ID + SDK_OVERLAY..ID =; + SDK_OVERLAY..START =.; + SDK_OVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_OVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_OVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_OVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); + SDK_OVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_OVERLAY..DATA_END =.; + . = ALIGN(32); + SDK_OVERLAY..END =.; + + SDK_OVERLAY..TEXT_SIZE = SDK_OVERLAY..TEXT_END - SDK_OVERLAY..TEXT_START; + SDK_OVERLAY..DATA_SIZE = SDK_OVERLAY..DATA_END - SDK_OVERLAY..DATA_START; + SDK_OVERLAY..SIZE = SDK_OVERLAY..END - SDK_OVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_OVERLAY..BSS_START = .; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_OVERLAY..BSS_END = .; + + SDK_OVERLAY..BSS_SIZE = SDK_OVERLAY..BSS_END - SDK_OVERLAY..BSS_START; + + } >> + + + + ############################ OVERLAYDEFS ############################ + .F: + { + ### module information + WRITEW ADDR(.); # load address + WRITEW _start; # entry address + WRITEW SDK_STATIC_SIZE + SDK_AUTOLOAD_SIZE; # size of module + WRITEW _start_AutoloadDoneCallback; # callback autoload done + + ### overlay filename + + WRITES (""); # Overlay + + + } > F + + ############################ OVERLAYTABLE ########################### + .F: + { + + WRITEW ; # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_OVERLAY..SIZE; # size of module + WRITEW SDK_OVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_OVERLAY..SINIT_START; # start address of static init + WRITEW SDK_OVERLAY..SINIT_END; # end address of static init + WRITEW ; # ROM file ID + WRITEW 0; # Reserved + + + } > F + + ############################ ARENA ################################## + .dummy.MAIN_EX.NITRO: + { + . = ALIGN(32); + + } > dummy.MAIN_EX.NITRO + + .arena.MAIN.NITRO: + { + . = ALIGN(32); + SDK_SECTION_ARENA_START =.; + + } > arena.MAIN.NITRO + + .arena.MAIN_EX.NITRO: + { + . = ALIGN(32); + SDK_SECTION_ARENA_EX_START =.; + + } > arena.MAIN_EX.NITRO + + .arena.ITCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_ITCM_START =.; + + } > arena.ITCM + + .arena.DTCM: + { + . = ALIGN(32); + SDK_SECTION_ARENA_DTCM_START =.; + + } > arena.DTCM + + ############################ OTHERS ################################# + SDK_MAIN_ARENA_LO = SDK_SECTION_ARENA_START; + SDK_IRQ_STACKSIZE = ; # allocated in DTCM + SDK_SYS_STACKSIZE = ; # when 0 means all remains of DTCM + SDK_SYS_STACKSIZE_SIGN = (SDK_SYS_STACKSIZE < 0x80000000) * 2 - 1; + + .check.ITCM: + { + . = . + SDK_AUTOLOAD_ITCM_SIZE + SDK_AUTOLOAD_ITCM_BSS_SIZE; + + . = . + SDK_OVERLAY..SIZE + SDK_OVERLAY..BSS_SIZE; + + + } > check.ITCM + + .check.DTCM: + { + . = . + SDK_AUTOLOAD_DTCM_SIZE + SDK_AUTOLOAD_DTCM_BSS_SIZE; + + . = . + SDK_OVERLAY..SIZE + SDK_OVERLAY..BSS_SIZE; + + . = . + 0x080 + SDK_IRQ_STACKSIZE + SDK_SYS_STACKSIZE * SDK_SYS_STACKSIZE_SIGN; + } > check.DTCM + + ########################### LTDAUTOLOADS ############################ + SDK_LTDAUTOLOAD.LTDMAIN.START = SDK_STATIC_BSS_END; + SDK_LTDAUTOLOAD.LTDMAIN.END = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_EDN = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD.LTDMAIN.SIZE = 0; + SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE = 0; + SDK_LTDAUTOLOAD_TOP_START = 0x02400000; + SDK_LTDAUTOLOAD_TOP_SIZE = 4; # STATIC ̈悪 4 bytes ̃_~[oCit@C̐擪ɓ # + SDK_LTDAUTOLOAD_START = SDK_LTDAUTOLOAD_TOP_START + SDK_LTDAUTOLOAD_TOP_SIZE; + SDK_LTDAUTOLOAD_SIZE = 0; + SDK_LTDAUTOLOAD_NUMBER = ; + + .binary.LTDAUTOLOAD_TOP: + { + WRITEW 0; + + } >> #> binary.LTDAUTOLOAD_TOP + + + .: + { + ALIGNALL(4); + . = ALIGN(32); # Fit to cache line + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDAUTOLOAD__ID =; + SDK_LTDAUTOLOAD..ID =; + SDK_LTDAUTOLOAD..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDAUTOLOAD..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + #:::::::::: text/rodata + SDK_LTDAUTOLOAD..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); + SDK_LTDAUTOLOAD..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + + + + + + + #:::::::::: data + SDK_LTDAUTOLOAD..DATA_END =.; + . = ALIGN(32); + SDK_LTDAUTOLOAD..END =.; + + SDK_LTDAUTOLOAD..TEXT_SIZE = SDK_LTDAUTOLOAD..TEXT_END - SDK_LTDAUTOLOAD..TEXT_START; + SDK_LTDAUTOLOAD..DATA_SIZE = SDK_LTDAUTOLOAD..DATA_END - SDK_LTDAUTOLOAD..DATA_START; + SDK_LTDAUTOLOAD..SIZE = SDK_LTDAUTOLOAD..END - SDK_LTDAUTOLOAD..START; + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD..SIZE; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDAUTOLOAD..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_LTDAUTOLOAD..BSS_END =.; + + SDK_LTDAUTOLOAD..BSS_SIZE = SDK_LTDAUTOLOAD..BSS_END - SDK_LTDAUTOLOAD..BSS_START; + + } >> + + + + SDK_LTDAUTOLOAD_LTDMAIN_START = SDK_LTDAUTOLOAD.LTDMAIN.START; + SDK_LTDAUTOLOAD_LTDMAIN_END = SDK_LTDAUTOLOAD.LTDMAIN.END; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_END = SDK_LTDAUTOLOAD.LTDMAIN.BSS_END; + SDK_LTDAUTOLOAD_LTDMAIN_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.SIZE; + SDK_LTDAUTOLOAD_LTDMAIN_BSS_SIZE = SDK_LTDAUTOLOAD.LTDMAIN.BSS_SIZE; + + ######################### LTDAUTOLOAD_INFO ########################## + .binary.LTDAUTOLOAD_INFO: + { + SDK_LTDAUTOLOAD_LIST = .; + + WRITEW ADDR(.); + WRITEW SDK_LTDAUTOLOAD..SIZE; + WRITEW SDK_LTDAUTOLOAD..BSS_SIZE; + + SDK_LTDAUTOLOAD_LIST_END = .; + } >> #> binary.LTDAUTOLOAD_INFO + +# SDK_LTDAUTOLOAD_LIST = SDK_LTDAUTOLOAD_START + SDK_LTDAUTOLOAD_SIZE; +# SDK_LTDAUTOLOAD_LIST_END = SDK_LTDAUTOLOAD_LIST + SIZEOF(.binary.LTDAUTOLOAD_INFO); + SDK_LTDAUTOLOAD_SIZE = SDK_LTDAUTOLOAD_SIZE + SIZEOF(.binary.LTDAUTOLOAD_INFO); + + ########################### LTDOVERLAYS ############################# + SDK_LTDOVERLAY_NUMBER = ; + + + .: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + SDK_LTDOVERLAY__ID =; + SDK_LTDOVERLAY..ID =; + SDK_LTDOVERLAY..START =.; + # + # TEXT BLOCK: READ ONLY + # + SDK_LTDOVERLAY..TEXT_START =.; + #:::::::::: text/rodata + + + + + + + + + + + + + + + + + + + . = ALIGN(4); + SDK_LTDOVERLAY..SINIT_START =.; + #:::::::::: ctor + + + + + + + + + + + + + WRITEW 0; + #:::::::::: ctor + SDK_LTDOVERLAY..SINIT_END =.; + #:::::::::: text/rodata + SDK_LTDOVERLAY..TEXT_END =.; + + # + # DATA BLOCK: READ WRITE + # + . = ALIGN(32); + SDK_LTDOVERLAY..DATA_START =.; + #:::::::::: data + + + + + + + + + + + + + #:::::::::: data + SDK_LTDOVERLAY..DATA_END =.; + . = ALIGN(32); + SDK_LTDOVERLAY..END =.; + + SDK_LTDOVERLAY..TEXT_SIZE = SDK_LTDOVERLAY..TEXT_END - SDK_LTDOVERLAY..TEXT_START; + SDK_LTDOVERLAY..DATA_SIZE = SDK_LTDOVERLAY..DATA_END - SDK_LTDOVERLAY..DATA_START; + SDK_LTDOVERLAY..SIZE = SDK_LTDOVERLAY..END - SDK_LTDOVERLAY..START; + + } > + + ..bss: + { + ALIGNALL(4); + . = ALIGN(32); + + # + # Definition to refer overlay segment, when same name symbols exist in multiple overlays. + # + + SEARCH_SYMBOL ; + + + # + # BSS BLOCK + # + SDK_LTDOVERLAY..BSS_START =.; + #:::::::::: bss + + + + + + + + + + + + + #:::::::::: bss + . = ALIGN(32); + SDK_LTDOVERLAY..BSS_END =.; + + SDK_LTDOVERLAY..BSS_SIZE = SDK_LTDOVERLAY..BSS_END - SDK_LTDOVERLAY..BSS_START; + + } >> + + + + ########################## LTDOVERLAYDEFS ########################### + .L: + { + ### TWL limited extended static module information + WRITEW SDK_LTDAUTOLOAD_TOP_START; # load address + WRITEW 0; # padding + WRITEW SDK_LTDAUTOLOAD_SIZE + SDK_LTDAUTOLOAD_TOP_SIZE; # size of module + WRITEW 0; # padding + + ### TWL limited overlay filename + + WRITES (""); + + + } > L + + ######################### LTDOVERLAYTABLE ########################### + .L: + { + + WRITES # overlay ID + WRITEW ADDR(.); # load address + WRITEW SDK_LTDOVERLAY..SIZE; # size of module + WRITEW SDK_LTDOVERLAY..BSS_SIZE; # size of bss + WRITEW SDK_LTDOVERLAY..SINIT_START; # start address of static init + WRITEW SDK_LTDOVERLAY..SINIT_END; # end address of static init + WRITEW # ROM file ID + WRITEW 0; # Reserved + + + } > L + + ############################ ARENA ################################## + .dummy.MAIN_EX.TWL: + { + . = ALIGN(32); + + } > dummy.MAIN_EX.TWL + + .arena.MAIN.TWL: + { + . = ALIGN(32); + SDK_LTDMAIN_ARENA_LO =.; + + } > arena.MAIN.TWL + + .arena.MAIN_EX.TWL: + { + . = ALIGN(32); + SDK_LTDMAIN_EX_ARENA_LO =.; + + } > arena.MAIN_EX.TWL + + ############################ OTHERS ################################# + # Module filelist + .binary.MODULE_FILES: + { +# WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + WRITES (""); + + } > binary.MODULE_FILES + +} diff --git a/include/firm/specfiles/ROM-TS.rsf b/include/firm/specfiles/ROM-TS.rsf new file mode 100644 index 0000000..6d3681c --- /dev/null +++ b/include/firm/specfiles/ROM-TS.rsf @@ -0,0 +1,148 @@ +#---------------------------------------------------------------------------- +# Project: TwlSDK - include +# File: ROM-BB.rsf +# +# Copyright 2007 Nintendo. All rights reserved. +# +# These coded insructions, statements, and computer programs contain +# proprietary information of Nintendo of America Inc. and/or Nintendo +# Company Ltd., and are protected by Federal copyright law. They may +# not be disclosed to third parties or copied or duplicated in any form, +# in whole or in part, without the prior written consent of Nintendo. +# +# $Date:: $ +# $Rev$ +# $Author$ +#---------------------------------------------------------------------------- +# +# TWL ROM SPEC FILE +# + +Arm9 +{ + Static "$(MAKEROM_ARM9:r).FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.FLX.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.FLX.TWL.sbin$(COMPSUFFIX9)" + Elf "$(MAKEROM_ARM9:r).tef" +} + +Arm7 +{ + Static "$(MAKEROM_ARM7_BASE:r).FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.FLX.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.FLX.TWL.sbin$(COMPSUFFIX7)" + Elf "$(MAKEROM_ARM7_BASE:r).tef" +} + +Arm9.Ltd +{ + Static "$(MAKEROM_ARM9:r).LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayDefs "$(MAKEROM_ARM9:r)_defs.LTD.TWL.sbin$(COMPSUFFIX9)" + OverlayTable "$(MAKEROM_ARM9:r)_table.LTD.TWL.sbin$(COMPSUFFIX9)" +} + +Arm7.Ltd +{ + Static "$(MAKEROM_ARM7_BASE:r).LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayDefs "$(MAKEROM_ARM7_BASE:r)_defs.LTD.TWL.sbin$(COMPSUFFIX7)" + OverlayTable "$(MAKEROM_ARM7_BASE:r)_table.LTD.TWL.sbin$(COMPSUFFIX7)" +} + +Property +{ + ### + ### Settings for FinalROM + ### + #### BEGIN + # + # TITLE NAME: Your product name within 12bytes + # + TitleName "FIRM" + + # + # MAKER CODE: Your company ID# in 2 ascii words + # issued by NINTENDO + # + MakerCode "01" + + # + # REMASTER VERSION: Mastering version + # + #RomVersion 0 + + # + # ROM SPEED TYPE: [MROM/1TROM/UNDEFINED] + # + RomSpeedType $(MAKEROM_ROMSPEED) + + # + # ROM SIZE: in bit [64M/128M/256M/512M/1G/2G] + # + #RomSize 128M + #RomSize 256M + + # + # ROM PADDING: TRUE if finalrom + # + #RomFootPadding TRUE + + # + # ROM HEADER TEMPLATE: Provided to every product by NINTENDO + # + #RomHeaderTemplate ./etc/rom_header.template.sbin + + # + # BANNER FILE: generated from Banner Spec File + # + #BannerFile ./etc/myGameBanner.bnr + BannerFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + ### + ### Setting for TWL + ### + # + # BANNER FILE: + # + BannerTWLFile $(TWLSDK_ROOT)/include/twl/specfiles/default.bnr + + # + # Boot allowed Media: [GameCard/NAND/SDCard/DownloadPlay] + # possible to choose one or more. + # + BootMedia GameCard NAND SDCard DownloadPlay + + # + # Certification FILE: + # + Certificate $(TWLSDK_ROOT)/include/twl/specfiles/default_sgn.sbin + + # + # Digest parameters: + # + DigestParam 1024 32 + + # + # WRAM mapping: [MAP_BB_HYB/MAP_BB_LTD/MAP_TS_HYB/MAP_TS_LTD] + # don't have to edit + # + #WramMapping $(MAKEROM_WRAM_MAPPING) + WramMappingDirect wram_regs/wram_regs.rbin + + # + # Codec mode: + # don't have to edit + # + CodecMode $(MAKEROM_CODEC_MODE) + + ### + #### END +} + +RomSpec +{ + Offset 0x00000000 + Segment ALL + HostRoot $(MAKEROM_ROMROOT) + Root / + File $(MAKEROM_ROMFILES) +} diff --git a/include/sysmenu.h b/include/sysmenu.h new file mode 100644 index 0000000..80dbc8f --- /dev/null +++ b/include/sysmenu.h @@ -0,0 +1,33 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: sysmenu.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ +#ifndef SYSMENU_H_ +#define SYSMENU_H_ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +/* SYSMENU_H_ */ +#endif diff --git a/include/sysmenu/.DS_Store b/include/sysmenu/.DS_Store new file mode 100644 index 0000000..cf1554c Binary files /dev/null and b/include/sysmenu/.DS_Store differ diff --git a/include/sysmenu/acsign.h b/include/sysmenu/acsign.h new file mode 100644 index 0000000..f334333 --- /dev/null +++ b/include/sysmenu/acsign.h @@ -0,0 +1,35 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - ACSIGN + File: acsign.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef SYSM_ACSIGN_H_ +#define SYSM_ACSIGN_H_ + +#ifdef SDK_ARM9 +#include +#include +#endif // SDK_ARM9 + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* SYSM_ACSIGN_H_ */ +#endif diff --git a/include/sysmenu/acsign/ARM9/acsign.h b/include/sysmenu/acsign/ARM9/acsign.h new file mode 100644 index 0000000..eff3b53 --- /dev/null +++ b/include/sysmenu/acsign/ARM9/acsign.h @@ -0,0 +1,59 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: acsign.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef _ACSIGN_H_ +#define _ACSIGN_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined( RSA_ENC_DEC ) +#define ACSIGN_BUFFER ((160/8)*4) // o̓obt@ +#else +#define ACSIGN_BUFFER ((160/8)*1) // o̓obt@ +#endif + +// +int ACSign_Decrypto( + void* buffer, // o͗̈ + void* sgn_ptr, // f[^ւ̃|C^ + void* key_ptr // L[ւ̃|C^ + ); + +// +int ACSign_Digest( + void* buffer, // o͗̈ + void* romh_ptr, // f[^ւ̃|C^ + void* mbin_ptr, // f[^ւ̃|C^ + int mbin_len, // f[^̒ + void* sbin_ptr, // f[^ւ̃|C^ + int sbin_len, // f[^̒ + u32 serial_num // VAio[ + ); + +// +int ACSign_Compare( + void* dercypto, // ACSign_Decryptȍo + void* digest // ACSign_Digest̏o + ); + +#ifdef __cplusplus +} +#endif + +#endif //_ACSIGN_H_ diff --git a/include/sysmenu/acsign/ARM9/acsign_util.h b/include/sysmenu/acsign/ARM9/acsign_util.h new file mode 100644 index 0000000..dd09d6b --- /dev/null +++ b/include/sysmenu/acsign/ARM9/acsign_util.h @@ -0,0 +1,37 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: acsign_util.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef _ACSIGN_UTIL_H_ +#define _ACSIGN_UTIL_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AUTH_BUFFER_LEN 20 + +extern int ACSignDecrpto(void *output_buffer, MBDownloadFileInfo *download_file_info_buf); +extern int ACSignDigest(void *input_buffer, MBDownloadFileInfo *download_file_info_buf); + + +#ifdef __cplusplus +} +#endif + +#endif //_ACSIGN_UTIL_H_ diff --git a/include/sysmenu/banner.h b/include/sysmenu/banner.h new file mode 100644 index 0000000..3479150 --- /dev/null +++ b/include/sysmenu/banner.h @@ -0,0 +1,111 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: banner.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef BANNER_H_ +#define BANNER_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifndef BANNER_ROM_OFFSET +#define BANNER_ROM_OFFSET (HW_ROM_HEADER_BUF + 0x68) +#endif + +#define BNR_VER_MIN 1 +#define BNR_VER_MAX 3 +#define BNR_HEADER_RSV_SIZE 24 + +#define BNR_CHINESE_SUPPORT_VER 2 +#define BNR_HANGUL_SUPPORT_VER 3 + +typedef enum +{ + BNR_JAPANESE = 0, + BNR_ENGLISH = 1, + BNR_FRENCH = 2, + BNR_GERMAN = 3, + BNR_ITALIAN = 4, + BNR_SPANISH = 5, + BNR_CHINESE = 6, + BNR_HANGUL = 7, + BNR_LANG_NUM +} BannerFileLangIdx; + +#define BNR_LANG_NUM_V1 6 +#define BNR_LANG_NUM_V2 1 +#define BNR_LANG_NUM_V3 1 + + +#define BNR_HEADER_SIZE 32 +#define BNR_VER_OFFSET 0 +#define BNR_V1_CRC16_OFFSET 2 +#define BNR_IMAGE_OFFSET BNR_HEADER_SIZE +#define BNR_IMAGE_SIZE (32 * 32 / (8/4)) +#define BNR_PLTT_OFFSET (BNR_IMAGE_OFFSET + BANNER_IMAGE_SIZE) +#define BNR_PLTT_NUM 16 +#define BNR_PLTT_SIZE (BNR_PLTT_NUM * 2) +#define BNR_LANG_OFFSET (BNR_PLTT_OFFSET + BANNER_PLTT_SIZE) +#define BNR_LANG_LENGTH 128 +#define BNR_LANG_SIZE (BNR_LANG_LENGTH * 2) + +typedef struct +{ + u8 version; + u8 reserved_A; + u16 crc16_v1; + u16 crc16_v2; + u16 crc16_v3; + u8 reserved_B[BNR_HEADER_RSV_SIZE]; +} BannerHeader; + +typedef struct +{ + u8 image[BNR_IMAGE_SIZE]; + GXRgba pltt[BNR_PLTT_NUM]; + + u16 gameName[BNR_LANG_NUM_V1][BNR_LANG_LENGTH]; +} BannerFileV1; + +typedef struct +{ + u16 gameName[BNR_LANG_NUM_V2][BNR_LANG_LENGTH]; +} BannerFileV2; + +typedef struct +{ + u16 gameName[BNR_LANG_NUM_V3][BNR_LANG_LENGTH]; +} BannerFileV3; + +typedef struct +{ + BannerHeader h; + BannerFileV1 v1; + BannerFileV2 v2; + BannerFileV3 v3; +} BannerFile; + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* BANNER_H_ */ +#endif diff --git a/include/sysmenu/machineSettings.h b/include/sysmenu/machineSettings.h new file mode 100644 index 0000000..be955cd --- /dev/null +++ b/include/sysmenu/machineSettings.h @@ -0,0 +1,32 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: machineSettings.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef SYSM_MACHINE_SETTINGS_H_ +#define SYSM_MACHINE_SETTINGS_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* SYSM_MACHINE_SETTINGs_H_ */ +#endif diff --git a/include/sysmenu/machineSettings/common/nitroSettings.h b/include/sysmenu/machineSettings/common/nitroSettings.h new file mode 100644 index 0000000..9dca4b7 --- /dev/null +++ b/include/sysmenu/machineSettings/common/nitroSettings.h @@ -0,0 +1,483 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: NitroSettings.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + + +#ifndef NITRO_SETTINGS_H_ +#define NITRO_SETTINGS_H_ +#if defined(SDK_CW) // NitroConfigDataɃrbgtB[hgĂ̂ŁARpCˑŕs”\B + // āACWȊÕRpC̏ꍇ́Ãwb_𖳌ɂăG[o悤ɂčĊmFB + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +// define data ------------------------------------ +#define NITRO_CONFIG_DATA_VERSION 5 // NITROݒf[^tH[}bgo[W +#define NITRO_CONFIG_DATA_EX_VERSION 1 // gNITROݒf[^tH[}bgo[W +#define NCD_NICKNAME_LENGTH 10 // jbNl[ +#define NCD_COMMENT_LENGTH 26 // Rg +#define NCD_FAVORITE_COLOR_MAX_NUM 16 // DȐF̍ő吔 + +// ݒR[h +typedef enum NvLangCode{ + LANG_JAPANESE =0, // { + LANG_ENGLISH =1, // p + LANG_FRENCH =2, // tX + LANG_GERMAN =3, // hCc + LANG_ITALIAN =4, // C^A + LANG_SPANISH =5, // XyC + LANG_CHINESE =6, // + LANG_HANGUL =7, // ؍ + LANG_CODE_MAX +}NvLangCode; + +#define LANG_CODE_MAX_WW ( LANG_SPANISH + 1 ) +#define LANG_BITMAP_WW ( ( 0x0001 << LANG_JAPANESE ) \ + | ( 0x0001 << LANG_ENGLISH ) \ + | ( 0x0001 << LANG_FRENCH ) \ + | ( 0x0001 << LANG_GERMAN ) \ + | ( 0x0001 << LANG_ITALIAN ) \ + | ( 0x0001 << LANG_SPANISH ) ) // ʏłł̑Ήrbg}bv + +#define VALID_LANG_BITMAP LANG_BITMAP_WW // {IPL2̑Ήrbg}bv + + +// tf[^ +typedef struct NvDate{ + u8 month; // :01`12 + u8 day; // :01`31 +}NvDate; // 2byte + +// jbNl[ +typedef struct NvNickname{ + u16 str[NCD_NICKNAME_LENGTH]; // jbNl[iUnicode(UTF16)ōő10AI[R[hȂj + u8 length; // + u8 rsv; +}NvNickname; // 22byte + +// Rg +typedef struct NvComment{ + u16 str[NCD_COMMENT_LENGTH]; //RgiUnicode(UTF16)ōő26AI[R[hȂj + u8 length; // + u8 rsv; +}NvComment; // 54byte + +// I[i[ +typedef struct NvOwnerInfo{ + u8 favoriteColor : 4; // DȐF + u8 rsv : 4; // \B + NvDate birthday; // N + u8 pad; + NvNickname nickname; // jbNl[ + NvComment comment; // Rg +}NvOwnerInfo; // 80byte + +// IPLpڊo܂vf[^ +typedef struct NvAlarm{ + u8 hour; // A[:00`23 + u8 minute; // A[:00`59 + u8 rsv1; // \ + u8 pad; + u16 alarmOn : 1; // A[ON,OFFi0:OFF, 1:ONj + u16 rsv2 : 15; // \ +}NvAlarm; // 6byte + +// ^b`plLu[Vf[^ +typedef struct NvTpCalibData{ + u16 raw_x1; // PLu[V_TP擾lX + u16 raw_y1; // @@@@V@@@@@@@@TP擾lY + u8 dx1; // @@@@V@@@@@@@@LCDW X + u8 dy1; // @@@@V@@@@@@@@LCDW Y + u16 raw_x2; // QLu[V_TP擾lX + u16 raw_y2; // @@@@V@@@@@@@@TP擾lY + u8 dx2; // @@@@V@@@@@@@@LCDW X + u8 dy2; // @@@@V@@@@@@@@LCDW Y +}NvTpCalibData; // 12byte + +// IvV +typedef struct NvOption{ + u16 language : 3; // R[hiLANG_SPANISH܂ł̕WR[hj + u16 agbLcd : 1; // AGB[hŋN鎞ɂǂLCDŋN邩Hi0:TOP,1:BOTTOMj + u16 backLightBrightness : 2; // obNCgPxf[^ + u16 autoBootFlag : 1; // NV[PXŁAj[~ȂŎN邩ǂH(0:OFF, 1:ON) + u16 backLightOffFlag : 1; // obNCgON,OFFtOi0:ON, 1:OFFj + u16 rsv2 : 1; // \ + u16 destroyFlashFlag : 1; // tbVV[PXtO + u16 input_birthday : 1; // a͂ꂽH + u16 input_favoriteColor : 1; // DȐF͂ꂽH + u16 input_tp : 1; // ^b`plLu[VꂽHi V ) + u16 input_language : 1; // ͂ꂽH@ (0:ݒ, 1:ݒς) + u16 input_rtc : 1; // RTCݒ肪ꂽH ( V@@@@@ ) + u16 input_nickname : 1; // jbNl[͂ꂽH ( V@@@@@ ) + u8 rtcLastSetYear; // RTC̑OݒN + u8 rtcClockAdjust; // RTCNbNl + s64 rtcOffset; // RTCݒ莞̃ItZbgli[U[RTCݒύXxɂ̒lɉđ܂Bj +}NvOption; // 12byte + +// NITROeݒf[^ +typedef struct NitroConfigData{ + u8 version; // tbVi[f[^tH[}bg̃o[W + u8 pad; + NvOwnerInfo owner; // I[i[ + NvAlarm alarm; // IPLpڊo܂vf[^ + NvTpCalibData tp; // ^b`plLu[Vf[^ + NvOption option; // IvV +}NitroConfigData; // 112byte + +// NITROeݒf[^NVRAMۑtH[}bg +typedef struct NCDStore{ + NitroConfigData ncd; // NITROeݒf[^ + u16 saveCount; // 0x00-0x7f[văJEgAJEglVf[^LB + u16 crc16; // NITROeݒf[^16bitCRC + u8 pad[ 128 - sizeof(NitroConfigData) - 4]; +}NCDStore; // 128byte // {ȂAsaveCountcrc16256byte̍ŌɕtāAԂɃpfBO𖄂߂B + + +//---------------------------------------------- +// IPL2E؍łł̊gtH[}bg +//---------------------------------------------- +// gNITROݒf[^ +typedef struct NitroConfigDataEx{ + u8 version; // o[W + u8 language; // R[hiLANG_CHINESEȍ~ɊgꂽlBj + u16 valid_language_bitmap; // {IPL2ŗLȌR[hrbg}bv + u8 pad[ 256 - sizeof(NitroConfigData) - 4 - 4 - 2 ]; // 4:saveCount+crc16, 2:NCDEx.version+NCDEx.language, 2:crc16_ex +}NitroConfigDataEx; // 138bytes + +// NITROeݒf[^NVRAMۑtH[}bg +typedef struct NCDStoreEx{ + NitroConfigData ncd; // NITROeݒf[^ + u16 saveCount; // 0x00-0x7f[văJEgAJEglVf[^LB + u16 crc16; // NITROeݒf[^16bitCRC + NitroConfigDataEx ncd_ex; + u16 crc16_ex; +}NCDStoreEx; // 256byte // {ȂAsaveCountcrc16256byte̍ŌɕtāAԂɃpfBO𖄂߂B + + +//========================================================= +// NVRAMւ̃[hCg֐ +//========================================================= +#ifdef SDK_ARM9 +extern int NVRAMm_ReadNitroConfigData (NitroConfigData *dstp); +extern void NVRAMm_WriteNitroConfigData(NitroConfigData *dstp); +#endif + + +//========================================================= +// NITROݒf[^ւ̃ANZX֐ +//========================================================= +extern NitroConfigDataEx ncdEx; + +#define GetNCDWork() ( (NitroConfigData *)( HW_NVRAM_USER_INFO ) ) +#define GetNCDExWork() ( &ncdEx ) + // NITROݒf[^̈̃AhXl + +extern void NCD_ClearOwnerInfo( void ); // jbNl[EaEDȐF̃NA +extern u8 NCD_GetIPL2Type( void ); +extern u8 *NCD_GetIPL2Version( void ); +extern u32 NCD_GetNCDRomAddr( void ); + +//========================================================= +// f[^擾 +//========================================================= + +//----------------------------------- +// I[i[Ŝ̎擾B +static inline NvOwnerInfo *NCD_GetOwnerInfo(void) +{ + return &GetNCDWork()->owner; +} + +// DȐF̎擾B +static inline u8 NCD_GetFavoriteColor(void) +{ + return (u8)GetNCDWork()->owner.favoriteColor; +} + +// a̎擾B +static inline NvDate *NCD_GetBirthday(void) +{ + return &GetNCDWork()->owner.birthday; +} + +// jbNl[̎擾B +static inline NvNickname *NCD_GetNickname(void) +{ + return &GetNCDWork()->owner.nickname; +} + +// Rg̎擾B +static inline NvComment *NCD_GetComment(void) +{ + return &GetNCDWork()->owner.comment; +} + + +//----------------------------------- +// A[̎擾B +static inline NvAlarm *NCD_GetAlarmData(void) +{ + return &GetNCDWork()->alarm; +} + + +//----------------------------------- +// ^b`plLu[Vf[^̎擾B +static inline NvTpCalibData *NCD_GetTPCalibration(void) +{ + return &GetNCDWork()->tp; +} + + +//----------------------------------- +// IvV̎擾B + +// R[h̎擾 +static inline NvLangCode NCD_GetLanguage(void) +{ + return (NvLangCode)GetNCDExWork()->language; +} + +static inline NvLangCode NCD_GetLanguageOrg(void) +{ + return (NvLangCode)GetNCDWork()->option.language; +} + +// RTCItZbgl̎擾 +static inline s64 NCD_GetRtcOffset(void) +{ + return GetNCDWork()->option.rtcOffset; +} + +// RTCNbNl̎擾 +static inline u8 NCD_GetRtcClockAdjust(void) +{ + return GetNCDWork()->option.rtcClockAdjust; +} + +// RTC̑OZbgN̎擾 +static inline u8 NCD_GetRtcLastSetYear(void) +{ + return GetNCDWork()->option.rtcLastSetYear; +} + +// NV[PX̎NONHi0:OFF, 1:ONj +static inline int NCD_GetAutoBootFlag(void) +{ + return (int)GetNCDWork()->option.autoBootFlag; +} + +// obNCgPx擾i0-3j +static inline int NCD_GetBackLightBrightness(void) +{ + return (int)GetNCDWork()->option.backLightBrightness; +} + +// tbVV[PXǂH +static inline int NCD_GetDestroyFlash(void) +{ + return (int)GetNCDWork()->option.destroyFlashFlag; +} + +// af[^ZbgĂ邩H +static inline int NCD_GetInputBirthday(void) +{ + return (int)GetNCDWork()->option.input_birthday; +} + +// DȐFf[^ZbgĂ邩H +static inline int NCD_GetInputFavoriteColor(void) +{ + return (int)GetNCDWork()->option.input_favoriteColor; +} + +// TPLu[Vf[^ZbgĂ邩H +static inline int NCD_GetInputTP(void) +{ + return (int)GetNCDWork()->option.input_tp; +} + +// R[hZbgĂ邩H +static inline int NCD_GetInputLanguage(void) +{ + return (int)GetNCDWork()->option.input_language; +} + +// RTCf[^ZbgĂ邩H +static inline int NCD_GetInputRTC(void) +{ + return (int)GetNCDWork()->option.input_rtc; +} + +// I[i[̃jbNl[ZbgĂ邩H +static inline int NCD_GetInputNickname(void) +{ + return (int)GetNCDWork()->option.input_nickname; +} + +//========================================================= +// f[^Zbg +//========================================================= +//----------------------------------- +// I[i[Ŝ̃ZbgB +static inline void NCD_SetOwnerInfo(NvOwnerInfo *owinfop) +{ + SVC_CpuCopy( owinfop, &GetNCDWork()->owner, sizeof(NvOwnerInfo), 16); +} + +// DȐF̃ZbgB +static inline void NCD_SetFavoriteColor(u8 favoriteColor) +{ + GetNCDWork()->owner.favoriteColor = favoriteColor; +} + +// ãZbgB +static inline void NCD_SetBirthday(NvDate *birthp) +{ + GetNCDWork()->owner.birthday.month = birthp->month; + GetNCDWork()->owner.birthday.day = birthp->day; +} + +// jbNl[̃ZbgB +static inline void NCD_SetNickname(NvNickname *namep) +{ + SVC_CpuCopy( namep, &GetNCDWork()->owner.nickname, sizeof(NvNickname), 16); +} + +// Rg̃ZbgB +static inline void NCD_SetComment(NvComment *commentp) +{ + SVC_CpuCopy( commentp, &GetNCDWork()->owner.comment, sizeof(NvComment), 16); +} + + +//----------------------------------- +// A[̃ZbgB +static inline void NCD_SetAlarmData(NvAlarm *alarmp) +{ + SVC_CpuCopy( alarmp, &GetNCDWork()->alarm, sizeof(NvAlarm), 16); +} + + +//----------------------------------- +// ^b`plLu[Vf[^̃ZbgB +static inline void NCD_SetTPCalibration(NvTpCalibData *tp_calibp) +{ + SVC_CpuCopy( tp_calibp, &GetNCDWork()->tp, sizeof(NvTpCalibData), 16); +} + + +//----------------------------------- +// IvṼZbgB + +// R[h̃Zbg +static inline void NCD_SetLanguage(NvLangCode language) +{ + GetNCDExWork()->language = language; + + if( language >= LANG_CODE_MAX_WW ) { + GetNCDWork()->option.language = LANG_ENGLISH; + }else { + GetNCDWork()->option.language = language; + } +} + +// RTCItZbgl̃Zbg +static inline void NCD_SetRtcOffset(s64 rtcOffset) +{ + GetNCDWork()->option.rtcOffset = rtcOffset; +} + +// RTCNbNl̃Zbg +static inline void NCD_SetRtcClockAdjust(u8 rtcClockAdjust) +{ + GetNCDWork()->option.rtcClockAdjust = rtcClockAdjust; +} + + +// RTCLastSetYearւ̃Zbg +static inline void NCD_SetRtcLastSetYear(u8 rtcLastSetYear) +{ + GetNCDWork()->option.rtcLastSetYear = rtcLastSetYear; +} + + +// NV[PX̎NON,OFFtOZbgB +static inline void NCD_SetAutoBootFlag(BOOL autoBootFlag) +{ + GetNCDWork()->option.autoBootFlag = (u16)autoBootFlag; +} + +// obNCgPxZbgB +static inline void NCD_SetBackLightBrightness(BOOL backLightBrightness ) +{ + GetNCDWork()->option.backLightBrightness = (u16)backLightBrightness; +} + +// tbVV[PXǂ̃tOZbgB +static inline void NCD_SetDestroyFlash(BOOL destroy) +{ + GetNCDWork()->option.destroyFlashFlag = (u16)destroy; +} + +// af[^͍̓ς݃tOZbgB +static inline void NCD_SetInputBirthday(BOOL input) +{ + GetNCDWork()->option.input_birthday = (u16)input; +} + +// DȐFf[^͍̓ς݃tOZbgB +static inline void NCD_SetInputFavoriteColor(BOOL input) +{ + GetNCDWork()->option.input_favoriteColor = (u16)input; +} + +// TPLu[Vf[^͍̓ς݃tOZbgB +static inline void NCD_SetInputTP(BOOL input) +{ + GetNCDWork()->option.input_tp = (u16)input; +} + +// R[h͍̓ς݃tOZbgB +static inline void NCD_SetInputLanguage(BOOL input) +{ + GetNCDWork()->option.input_language = (u16)input; +} + +// RTCf[^͍̓ς݃tOZbgB +static inline void NCD_SetInputRTC(BOOL input) +{ + GetNCDWork()->option.input_rtc = (u16)input; +} + +// I[i[̃jbNl[͍̓ς݃tOZbgB +static inline void NCD_SetInputNickname(BOOL input) +{ + GetNCDWork()->option.input_nickname = (u16)input; +} + + + +#ifdef __cplusplus +} +#endif + +#endif // SDK_CW +#endif // NITRO_SETTINGS_H_ diff --git a/include/sysmenu/mb_loader.h b/include/sysmenu/mb_loader.h new file mode 100644 index 0000000..d5a1933 --- /dev/null +++ b/include/sysmenu/mb_loader.h @@ -0,0 +1,32 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - MB_LOADER + File: mb_loader.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef SYSM_MB_LOADER_H_ +#define SYSM_MB_LOADER_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* SYSM_MB_LOADER_H_ */ +#endif diff --git a/include/sysmenu/mb_loader/common/mb_loader.h b/include/sysmenu/mb_loader/common/mb_loader.h new file mode 100644 index 0000000..9b853e6 --- /dev/null +++ b/include/sysmenu/mb_loader/common/mb_loader.h @@ -0,0 +1,86 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: mb_loader.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#if !defined(_LOADER_H_) +#define _LOADER_H_ + +#include +#include // twl/mb.hȂB + +#ifdef __cplusplus +extern "C" { +#endif + +#define PXI_FIFO_TAG_MB PXI_FIFO_TAG_USER_0 +/* + ̍ہAFIFO_TAGƂȂTAGԍɎw肵ĂB +*/ + +/*---------------------------------------------------------------------------* + Type definition + *---------------------------------------------------------------------------*/ + +typedef void (*MB_LoaderCallback)(void); + +/*---------------------------------------------------------------------------* + functions + *---------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------* + Name: LOADER_Init + + Description: [_[̏ + + Arguments: callback - u[g̏oƂɕԂR[obN + + Returns: None. + *---------------------------------------------------------------------------*/ + +void LOADER_Init(MB_LoaderCallback callback); + + +/*---------------------------------------------------------------------------* + Name: LOADER_Start + + Description: [_[̃X^[g + + Arguments: None. + + Returns: None. + *---------------------------------------------------------------------------*/ + +void LOADER_Start( void ); + + +/*---------------------------------------------------------------------------* + Name: MIm_CpuCopy32 + + Description: [_[pCpuCopy32֐ + + Arguments: + + Returns: TRUE - success FALSE - failed + *---------------------------------------------------------------------------*/ + +void MIm_CpuCopy32( register const void *srcp, register void *destp, register u32 size ); + + +#ifdef __cplusplus +} +#endif + +#endif /* _LOADER_H_ */ diff --git a/include/sysmenu/memorymap.h b/include/sysmenu/memorymap.h new file mode 100644 index 0000000..cfa4bf0 --- /dev/null +++ b/include/sysmenu/memorymap.h @@ -0,0 +1,34 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - memorymap + File: memorymap.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef SYSM_MEMORYMAP_H_ +#define SYSM_MEMORYMAP_H_ + + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* SYSM_MEMORYMAP_H_ */ +#endif diff --git a/include/sysmenu/mmap.h b/include/sysmenu/mmap.h new file mode 100644 index 0000000..9aab156 --- /dev/null +++ b/include/sysmenu/mmap.h @@ -0,0 +1,57 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: mmap.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __MMAP_H__ +#define __MMAP_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// define data ------------------------------------ + +#define RETURN_FROM_MAIN_ARM9_FUNCP 0x023fee00 // NITROQ[u[gARM9ŏI̓AhX +#define RETURN_FROM_MAIN_ARM7_FUNCP 0x0380f600 // NITROQ[u[gARM7ŏI̓AhX + +#define SYSM_ADDR_TOP 0x02300000 // SYSMzu擪AhX +#define SYSM_ADDR_BOTTOM 0x023fe000 // SYSMzuŏIAhX + +#define SYSM_ARM9_MMEM_ENTRY_ADDR_LIMIT ( SYSM_ADDR_TOP - 0x80000 ) // 0x02800000 + +#define SYSM_ARM9_LOAD_MMEM_LAST_ADDR ( SYSM_ADDR_TOP - 0x80000 ) // SYSM[h”\NITROJ[hu[gR[h̃CŏIAhX +#define SYSM_ARM7_LOAD_MMEM_LAST_ADDR ( SYSM_ADDR_BOTTOM ) // SYSM[h”\NITROJ[hu[gR[h̃CŏIAhX +#define SYSM_ARM7_LOAD_WRAM_LAST_ADDR ( RETURN_FROM_MAIN_ARM7_FUNCP & ~0x0fff ) // SYSM[h”\NITROJ[hu[gR[h̃CŏIAhX +#define SYSM_ARM7_LOAD_BUF_ADDR ( SYSM_ADDR_TOP - 0x40000 ) // SYSMNITROJ[hARM7u[gR[h̃[hsۂ̃[hobt@AhX +#define SYSM_ARM7_LOAD_BUF_SIZE ( SYSM_ADDR_TOP - SYSM_ARM7_LOAD_BUF_ADDR ) // SYSMNITROJ[hARM7R[h[hobt@TCY + +#define UNCOMP_TEMP_BUF ( SYSM_ARM7_LOAD_BUF_ADDR ) // kWJpf[^ꎞi[obt@AhX +#define UNCOMP_TEMP_BUF_SIZE ( SYSM_ARM7_LOAD_BUF_SIZE ) // kWJpf[^ꎞi[obt@TCY + +#define NITRO_CARD_SECURE_SIZE 0x4000 // NITROJ[h̃ZLÄTCY(16Kbytes) + +#define SYSROM9_NINLOGO_ADR 0xffff0020 // ARM9VXeROM̔CVSi[AhX +#define AGB_CARTRIDGE_NIN_LOGO_DATA (HW_CTRDG_ROM + 4) // AGBJ[gbWNintendoSf[^i[AhX + + +#ifdef __cplusplus +} +#endif + +#endif // __MMAP_H__ + diff --git a/include/sysmenu/rom_header.h b/include/sysmenu/rom_header.h new file mode 100644 index 0000000..b09e1f2 --- /dev/null +++ b/include/sysmenu/rom_header.h @@ -0,0 +1,175 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: rom_header.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef _ROM_HEADER_H_ +#define _ROM_HEADER_H_ + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +#define NINTENDO_LOGO_LENGTH 0x9c // NintendoSf[^TCY + +//---------------------------------------------------------------------- +// t@Cl[e[u +//---------------------------------------------------------------------- + +typedef struct ROM_FNT{ + char entry_name[FS_FILE_NAME_MAX]; // t@C (I[ \0 ͏Ȃ) +} ROM_FNT; + +//---------------------------------------------------------------------- +// t@CAP[Ve[u +//---------------------------------------------------------------------- +typedef struct { + void *top; // t@C̐擪 ROM AhX + void *bottom; // t@C̍ŏI ROM AhX +} ROM_FAT; + +//---------------------------------------------------------------------- +// I[o[Ce[u +//---------------------------------------------------------------------- +typedef struct { + u32 id; // I[o[C ID + void *ram_address; // [h擪ʒu + u32 ram_size; // [hTCY + u32 bss_size; // bss ̈TCY + void *sinit_init; // static initializer 擪AhX + void *sinit_init_end; // static initializer ŏIAhX + u32 file_id; // I[o[Ct@CID + u32 rsv; // \B +} ROM_OVT; + +//---------------------------------------------------------------------- +// ROMwb_ +//---------------------------------------------------------------------- +typedef struct { + // + // 0x000 System Reserved + // + char title_name[12]; // Soft title name + u32 game_code; // Game code + + u16 maker_code; // Maker code + u8 machine_code; // Machine code + u8 rom_type; // Rom type + u8 rom_size; // Rom size + + u8 agbRomCycle1st; // 1ZOAGBRomANZXTCN1st. + u8 agbRomCycle2nd; // 1ZOAGBRomANZXTCN2nd. + u8 reserved_A[7]; // System Reserved A ( Set ALL 0 ) + + u8 soft_version; // Soft version + u8 comp_arm9_boot_area:1; // Compress arm9 boot area + u8 comp_arm7_boot_area:1; // Compress arm7 boot area + u8 inspectCard:1; // J[htO + u8 disableClearMemoryPad:1; // IPL2pbhNAEfBZ[utO + u8 enableAgbRomCycle:1; + u8 :2; + u8 disableDetectPullOut:1; // J[hofBZ[utO + + // + // 0x020 for Static modules (Section:B) + // + // ARM9 + u32 main_rom_offset; // ROM offset + void* main_entry_address; // Entry point + void* main_ram_address; // RAM address + u32 main_size; // Module size + + // ARM7 + u32 sub_rom_offset; // ROM offset + void* sub_entry_address; // Entry point + void* sub_ram_address; // RAM address + u32 sub_size; // Module size + + // + // 0x040 for File Name Table[FNT] (Section:C) + // + ROM_FNT* fnt_offset; // ROM offset + u32 fnt_size; // Table size + + // + // 0x048 for File Allocation Table[FAT] (Section:E) + // + ROM_FAT* fat_offset; // ROM offset + u32 fat_size; // Table size + + // + // 0x050 for Overlay Tables[OVT] (Section:D) + // + // ARM9 + ROM_OVT* main_ovt_offset; // ROM offset + u32 main_ovt_size; // Table size + + // ARM7 + ROM_OVT* sub_ovt_offset; // ROM offset + u32 sub_ovt_size; // Table size + + // 0x060 for ROM control parameter + u32 game_cmd_param; // Game command parameter + u32 secure_cmd_param; // Secure command parameter + + u32 banner_offset; // Banner ROM offset + + u16 secure_area_crc16; // Secure area CRC-16 + u16 secure_cmd_latency; // Secure command latency ((param+2)*256 system cycles) + u8 ctrl_reserved_B[16]; // Ctrl Reserved B (Set 0) + + // 0x080 - 0x0C0 System Reserved + u32 total_rom_size; + u8 reserved_B[60]; // System Reserved B (Set 0) + + // 0x0C0 for NINTENDO logo data + u8 nintendo_logo[ NINTENDO_LOGO_LENGTH ]; // NINTENDO logo data + u16 nintendo_logo_crc16; // CRC-16 + + // 0x15E ROM header CRC-16 + u16 header_crc16; // ROM header CRC-16 + + // + // 0x0160 - 0x0180 System Reserved + // + u32 dbgRomAddr; // fobKj^ROMAhX + s32 dbgRomSize; // fobKj^ROMTCY + u32 dbgArm9RamAddr; // fobKj^ARM9-RAMAhX + u32 dbgArm7RamAddr; // fobKj^ARM7-RAMAhX + u8 reserved_C[16]; // Debugger Reserved (Set ALL 0) + +} RomHeader; + + +//---------------------------------------------------------------------- +// ROMwb_AhXl +//---------------------------------------------------------------------- + +#define GetRomHeaderAddr() ((RomHeader *)HW_ROM_HEADER_BUF) + +//EROMwb_AhXl܂B + + +#ifdef __cplusplus + +#endif + +#endif // _ROM_HEADER_H_ + + + diff --git a/include/sysmenu/sysmenu_lib.h b/include/sysmenu/sysmenu_lib.h new file mode 100644 index 0000000..d0565c0 --- /dev/null +++ b/include/sysmenu/sysmenu_lib.h @@ -0,0 +1,35 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL - SYSMENU_LIB + File: sysmenu_lib.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: 2007-09-06$ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef SYSM_SYSMENU_LIB_H_ +#define SYSM_SYSMENU_LIB_H_ + +#ifdef SDK_ARM9 +#include +#include +#endif // SDK_ARM9 + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/* SYSM_SYSMENU_LIB_H_ */ +#endif diff --git a/include/sysmenu/sysmenu_lib/ARM9/cmn.h b/include/sysmenu/sysmenu_lib/ARM9/cmn.h new file mode 100644 index 0000000..9640c41 --- /dev/null +++ b/include/sysmenu/sysmenu_lib/ARM9/cmn.h @@ -0,0 +1,54 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: mainFunc.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef CMN_H_ +#define CMN_H_ + + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +// define data--------------------------------------------- +#define ARY_SIZEOF(ary) ( sizeof(ary) / sizeof( (ary)[0] ) ) +#define ROUNDUP_DIV(a, b) (( (a) + ((b) - 1) ) / (b)) + + +// function------------------------------------------------ +void CMN_InitAllocator( NNSFndAllocator* pAllocator ); +void CMN_InitFileSystem( NNSFndAllocator* pAllocator ); +void CMN_ClearVram( void ); +u32 CMN_LoadFile(void** ppFile, const char* fpath, NNSFndAllocator* pAlloc); +void CMN_UnloadFile(void* pFile, NNSFndAllocator* pAlloc); +NNSFndArchive* CMN_LoadArchive(const char* name, const char* path, NNSFndAllocator* pAllocator); +void CMN_RemoveArchive(NNSFndArchive* archive, NNSFndAllocator* pAllocator); + + +#ifdef __cplusplus +}/* extern "C" */ +#endif + +#endif // CMN_H_ + diff --git a/include/sysmenu/sysmenu_lib/ARM9/sysmenu_api.h b/include/sysmenu/sysmenu_lib/ARM9/sysmenu_api.h new file mode 100644 index 0000000..db5e09b --- /dev/null +++ b/include/sysmenu/sysmenu_lib/ARM9/sysmenu_api.h @@ -0,0 +1,117 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: SYSM_lib.h + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __SYSM_LIB_H__ +#define __SYSM_LIB_H__ + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// define data---------------------------------------------------------- + +// ^Cg +typedef struct TitleProperty { // ̏́A`[ɂ͔FؒʂĂȂǁANɂ͔Fؒʂ̂őv낤B + u64 titleID; // ^CgID + void *pBanner; // oi[ւ̃|C^iŒ蒷tH[}bgȂUĂv낤B) + u32 rsv; +}TitleProperty; + + +// Zbgp[^ +typedef struct ResetParam { + u64 bootTitleID; // N^Cg邩HȂ炻̃^CgID + u32 rsv; + BOOL isLogoSkip; // SfXLbv邩H +}ResetParam; + + +// AvF، +typedef enum AuthResult { + AUTH_PROCESSING = 0, + AUTH_RESULT_SUCCEEDED = 1, + AUTH_RESULT_TITLE_POINTER_ERROR = 2, + AUTH_RESULT_AUTHENTICATE_FAILED = 3, + AUTH_RESULT_ENTRY_ADDRESS_ERROR = 4 +}AuthResult; + + +// global variable------------------------------------------------------ + +// function------------------------------------------------------------- +extern void SYSM_Init( void ); +extern BOOL SYSM_IsLogoDemoSkip( void ); +extern void SYSM_CaribrateTP( void ); +extern int SYSM_GetCardTitleList( TitleProperty *pTitleList_Card ); +extern int SYSM_GetNandTitleList( TitleProperty *pTitleList_Nand ); +extern AuthResult SYSM_LoadAndAuthenticateTitle( TitleProperty *pBootTitle ); +extern void SYSM_Finalize( void ); + +extern void SYSM_PermitToBootSelectedTarget( void ); +extern void SYSM_LoadSYSMData( void ); +extern BOOL SYSM_BootNITRO( void ); +extern void SYSM_BootPictChat( void ); +extern void SYSM_BootDSDownloadPlay( void ); +extern void SYSM_BootMachineSetting( void ); + +extern BOOL SYSM_ReadBannerFile( BannerFile *banner ); +extern BOOL SYSM_IsTPReadable( void ); + +extern BOOL SYSM_CheckNinLogo( u16 *logo_cardp ); +extern void SYSM_LoadNintendoLogo2D( u16 *ninLogoDatap, u16 *dstp, u16 color, u32 *tempBuffp ); // tempBuffpɂ0x700byteKvłB +extern void SYSM_LoadNintendoLogo1D( u16 *ninLogoDatap, u16 *dstp, u16 color, u32 *tempBuffp ); // B + +extern void SYSM_SetBootFlag( u32 value ); +extern void SYSM_ClearBootFlag( u32 value ); + + +extern void SYSM_GoSleepMode( void ); +extern void PMm_SetBackLightBrightness( void ); + + +extern void NCD_ClearOwnerInfo( void ); // jbNl[EaEDȐF̃NA +extern BOOL SYSM_CheckRTCDate( RTCDate *datep ); +extern BOOL SYSM_CheckRTCTime( RTCTime *timep ); +extern s64 SYSM_CalcRtcOffsetAndSetDateTime( RTCDate *newDate, RTCTime *newTime ); +extern u32 SYSM_GetDayNum( u32 year, u32 month ); +extern BOOL SYSM_IsLeapYear100( u32 year ); + +// ȉ̊֐́ASYSM_MainR[ꂽɐl擾ł悤ɂȂ܂B + +// NITROJ[hĂ邩H +static inline BOOL SYSM_IsNITROCard( void ) +{ + return (SYSM_GetBootFlag() & BFLG_EXIST_NITRO_CARD) ? TRUE : FALSE; +} + +// pNITROJ[hĂ邩H +static inline BOOL SYSM_IsInspectNITROCard( void ) +{ + return ( (SYSM_IsNITROCard()) && (GetRomHeaderAddr()->inspectCard) ); +} + + +#ifdef __cplusplus +} +#endif + +#endif // __SYSM_LIB_H__ diff --git a/include/sysmenu/sysmenu_work.h b/include/sysmenu/sysmenu_work.h new file mode 100644 index 0000000..593f66a --- /dev/null +++ b/include/sysmenu/sysmenu_work.h @@ -0,0 +1,202 @@ +/*---------------------------------------------------------------------------* + Project: TwlIPL + File: sysmenu_work.c + + Copyright 2007 Nintendo. All rights reserved. + + These coded instructions, statements, and computer programs contain + proprietary information of Nintendo of America Inc. and/or Nintendo + Company Ltd., and are protected by Federal copyright law. They may + not be disclosed to third parties or copied or duplicated in any form, + in whole or in part, without the prior written consent of Nintendo. + + $Date:: $ + $Rev$ + $Author$ + *---------------------------------------------------------------------------*/ + +#ifndef __SYSMENU_WORK_H__ +#define __SYSMENU_WORK_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// compile switch --------------------------------- +#ifndef SDK_FINALROM + +//#define __SYSM_DEBUG + +#endif // SDK_FINALROM + +//#define __DEBUG_SECURITY_CODE // PassMẽZLeBR[hmFpXCb` + + +// define data ------------------------------------ +#define SYSMENU_VER 0x071029 // SystemMenuo[W + +#define PXI_FIFO_TAG_SYSM PXI_FIFO_TAG_USER_1 // SystemMenupFIFO^O + +#define PAD_PRODUCTION_NITRO_SHORTCUT ( PAD_BUTTON_A | PAD_BUTTON_B \ + | PAD_BUTTON_X | PAD_BUTTON_Y | PAD_BUTTON_R ) +#define PAD_PRODUCTION_AGB_SHORTCUT ( PAD_BUTTON_A | PAD_BUTTON_B \ + | PAD_BUTTON_X | PAD_BUTTON_Y | PAD_BUTTON_L ) + // ʎYHŎgpNITRONݒLZV[gJbgL[ + + + // bootFlag̒l +#define BFLG_EXIST_AGB_CARTRIDGE 0x00000001 +#define BFLG_EXIST_NITRO_CARD 0x00000002 +#define BFLG_ILLEGAL_NITRO_CARD 0x00000004 +#define BFLG_ILLEGAL_BMENU 0x00000008 +#define BFLG_BOOT_AGB 0x00000010 +#define BFLG_BOOT_NITRO 0x00000020 +#define BFLG_BOOT_BMENU 0x00000040 +#define BFLG_BOOT_PICT_CHAT 0x00000080 +#define BFLG_BOOT_WIRELESS_BOOT 0x00000100 +#define BFLG_LOAD_CARD_COMPLETED 0x00000200 +#define BFLG_LOAD_BMENU_COMPLETED 0x00000400 +#define BFLG_LOAD_SYSM_DATA_COMPLETED 0x00000800 +#define BFLG_REQ_UNCOMP_BMENU 0x00001000 +#define BFLG_REQ_UNCOMP_SYSM_DATA 0x00002000 +#define BFLG_ARM7_INIT_COMPLETED 0x00004000 +#define BFLG_READ_NCD_COMPLETED 0x00008000 +#define BFLG_SHORTCUT_CHECK_COMPLETED 0x00010000 +#define BFLG_HOT_START 0x00020000 +#define BFLG_BOOT_1SEG 0x00040000 +#define BFLG_PERMIT_TO_BOOT 0x08000000 +#define BFLG_SYSM_DATA_ENABLE 0x10000000 +#define BFLG_CARD_CHECKED 0x20000000 +#define BFLG_WM_INITIALIZED 0x40000000 +#define BFLG_BOOT_DECIDED 0x80000000 + +#define CLONE_BOOT_MODE 1 +#define OTHER_BOOT_MODE 2 + + // mainp_state̒l +typedef enum MainpState { + MAINP_STATE_INIT = 1, + MAINP_STATE_START, + MAINP_STATE_WAIT_BOOT_DECISION, + MAINP_STATE_WAIT_NITRO_GAME_LOAD, + MAINP_STATE_WAIT_READY_CHANGE_AGB, + MAINP_STATE_WAIT_BMENU_LOAD, + MAINP_STATE_WAIT_BOOT_REQ, + MAINP_STATE_WAIT_START_NITRO_GAME_REQ, + MAINP_STATE_BOOT_SELECTED_TARGET, + MAINP_STATE_BOOT_AGB_REQ +}MainpState; + + + // subp_state̒l +typedef enum SubpState { + SUBP_STATE_INIT = 1, + SUBP_STATE_STAY, + SUBP_STATE_CLEAR_MAIN_MEMORY, + SUBP_STATE_BOOT_NITRO_GAME_INIT, + SUBP_STATE_LOAD_NITRO_GAME, + SUBP_STATE_LOAD_BMENU, + SUBP_STATE_BOOT_NITRO_GAME, + SUBP_STATE_WAIT_START_BMENU_REQ, + SUBP_STATE_START_BMENU, + SUBP_STATE_BOOT_AGB, + SUBP_STATE_BOOT_AGB_ACK, + SUBP_STATE_BOOT_FAILED, + SUBP_STATE_MB_BOOT, + SUBP_STATE_TERMINATE_WM +}SubpState; + + + // SYSMi_SendMessageToARM7(int msg)ARM9ARM7ɒʒm郁bZ[W + // ARM7̃bZ[W܂ +typedef enum SYSMMsg { + MSG_INVALID = 0, // f[^B + + MSG_UNCOMP_SYSM_DATA, // ARM9SYSM_datakWJ悤vB + MSG_UNCOMP_BMENU, // ARM9bmenukWJ悤vB + + MSG_BOOT_TYPE_NITRO, // ARM7ɁuNITROQ[NvʒmB + MSG_BOOT_TYPE_AGB, // ARM7ɁuAGBNvʒmB +#ifndef __DS_CHAT_OFF + MSG_BOOT_TYPE_PICT_CHAT, // ARM7ɁuG`bgNvʒmB +#endif + MSG_BOOT_TYPE_WIRELESS_BOOT, // ARM7Ɂu}`u[gNvʒmB + MSG_BOOT_TYPE_BMENU, // ARM7Ɂuu[gj[NvʒmB + MSG_START_BMENU, // ARM7Ɂuu[gj[JnvʒmB + MSG_TERMINATE_WM // ARM7ɁuWMIvʒmB +}SYSMMsg; + + +//---------------------------------------------------------------------- +//@f[^^` +//---------------------------------------------------------------------- + +// bN +typedef struct LockVariable{ + OSLockWord lock; + vu32 value; +}LockVariable; + +// RTCt\ +typedef struct RtcDateTime { + RTCDate Date; + RTCTime Time; +}RtcDateTime; + +// SYSML[N\ +typedef struct SYSM_work{ + u32 card_arm7_ram_adr; // NITROJ[hARM7u[gR[hRAM[hAhX + int ncd_invalid; // NITROݒf[^tO + u32 ncd_rom_adr; // NITROݒf[^ROMAhX + u32 bm_arm7_ram_adr; // u[gj[ARM9RAMAhX + u32 bm_arm7_comp_adr; // u[gj[ARM7̈koCiRAMAhX + u16 sysm_data_crc16; + u16 bm_crc16; + u8 sysm_type; + u8 pmic_type; // fobK݂̂ŎgpB + u8 clone_boot_mode; + + + u8 rtcStatus; + u16 cardHeaderCrc16; + u16 rsv; + BOOL isOnDebugger; + BOOL enableCardNormalOnly; + u32 nCardID; // NORMALJ[hIDiLoadCardHeader() Ŏ擾j + + volatile MainpState mainp_state; // ARM9vOXe[g + volatile SubpState subp_state; // ARM7vOXe[g + LockVariable boot_flag; // u[gԃtOiSYSM_GetBootFlag(),SetBootFlag()ŃANZXs܂Bj + RtcDateTime rtc[2]; // RTCԃf[^([0]:N̒lA[1]:Q[u[gO̒lj +// u32 mb_flag; +// u32 mb_ggid; +}SYSM_work; + + +//---------------------------------------------------------------------- +//@SYSML[N̈̃AhXl +//---------------------------------------------------------------------- + +#define SYSM_GetResetParam() ( (ResetParam *)HW_RED_RESERVED ) + +#define GetSYSMWork() ( (SYSM_work *)( HW_RED_RESERVED + sizeof(ResetParam) ) ) + +//ESYSML[N̈̃AhXl܂B + +//---------------------------------------------------------------------- +//@bootFlag̃[h +//---------------------------------------------------------------------- +#define SYSM_GetBootFlag() ( *(vu32 *)&GetSYSMWork()->boot_flag.value ) + +//EbootFlagll܂B + + +#ifdef __cplusplus +} +#endif + +#endif // __SYSMENU_WORK_H__ + diff --git a/keys/dummy/rsa/private_gcd.der b/keys/dummy/rsa/private_gcd.der new file mode 100644 index 0000000..91e7fe4 Binary files /dev/null and b/keys/dummy/rsa/private_gcd.der differ diff --git a/keys/dummy/rsa/private_nand.der b/keys/dummy/rsa/private_nand.der new file mode 100644 index 0000000..771e3bf Binary files /dev/null and b/keys/dummy/rsa/private_nand.der differ diff --git a/keys/dummy/rsa/private_nor.der b/keys/dummy/rsa/private_nor.der new file mode 100644 index 0000000..2f3aba7 Binary files /dev/null and b/keys/dummy/rsa/private_nor.der differ diff --git a/keys/dummy/rsa/pubkey_gcd.der b/keys/dummy/rsa/pubkey_gcd.der new file mode 100644 index 0000000..b9cc07d Binary files /dev/null and b/keys/dummy/rsa/pubkey_gcd.der differ diff --git a/keys/dummy/rsa/pubkey_nand.der b/keys/dummy/rsa/pubkey_nand.der new file mode 100644 index 0000000..cbd2740 Binary files /dev/null and b/keys/dummy/rsa/pubkey_nand.der differ diff --git a/keys/dummy/rsa/pubkey_nor.der b/keys/dummy/rsa/pubkey_nor.der new file mode 100644 index 0000000..3c3999e Binary files /dev/null and b/keys/dummy/rsa/pubkey_nor.der differ diff --git a/readme.txt b/readme.txt new file mode 100644 index 0000000..79bb150 --- /dev/null +++ b/readme.txt @@ -0,0 +1,13 @@ +1.rhɕKvȂ +@NORt@[ANANDt@[ + ENitroSDK4.0ȍ~ + ETwlSDK +@VXej[ +@@ETwlSDK +@@ENitroSystem 070314({c[add-insTwlSDKΉpb`𓖂Ắj + + +2.‹ϐ̐ݒ +@TWLIPL_ROOT + ex.) TWLIPL_ROOT=c:/TwlIPL + diff --git a/setup b/setup new file mode 100644 index 0000000..55e7ae2 --- /dev/null +++ b/setup @@ -0,0 +1,8 @@ +#!/usr/bin/bash + +#---------------------------------------------------------------- +# This script is not for execute directly. +# Please use 'source ./setup'. +#---------------------------------------------------------------- + +export TWLIPL_ROOT=`cygpath -m $PWD` diff --git a/tools/.DS_Store b/tools/.DS_Store new file mode 100644 index 0000000..ddddbda Binary files /dev/null and b/tools/.DS_Store differ diff --git a/tools/bin/TXLib.dll b/tools/bin/TXLib.dll new file mode 100644 index 0000000..7e1dc0b Binary files /dev/null and b/tools/bin/TXLib.dll differ diff --git a/tools/bin/makebanner.exe b/tools/bin/makebanner.exe new file mode 100644 index 0000000..fd580a2 Binary files /dev/null and b/tools/bin/makebanner.exe differ diff --git a/tools/bin/ntexconv.exe b/tools/bin/ntexconv.exe new file mode 100644 index 0000000..d29e2ed Binary files /dev/null and b/tools/bin/ntexconv.exe differ diff --git a/tools/openssl/openssl.exe b/tools/openssl/openssl.exe new file mode 100644 index 0000000..8967c31 Binary files /dev/null and b/tools/openssl/openssl.exe differ