This commit is contained in:
Maschell 2021-12-27 16:53:04 +01:00
parent db5adae785
commit 1223bbc29d
23 changed files with 2674 additions and 63 deletions

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule "homebrew_launcher_installer"]
path = homebrew_launcher_installer
url = https://github.com/wiiu-env/homebrew_launcher_installer

View File

@ -33,8 +33,8 @@ CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__
CXXFLAGS := $(CFLAGS) -std=c++20
ASFLAGS := -g $(ARCH)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map)
ASFLAGS := -g $(ARCH) -mregnames
LDFLAGS = -g $(ARCH) $(RPXSPECS) --entry=_start -Wl,-Map,$(notdir $*.map)
LIBS := -lwut -lz
@ -80,7 +80,7 @@ endif
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC) payload.elf.o
export OFILES := $(OFILES_BIN) $(OFILES_SRC) sd_loader.elf.o
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
@ -96,13 +96,13 @@ all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
make -C homebrew_launcher_installer
make -C sd_loader
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#-------------------------------------------------------------------------------
clean:
@echo clean ...
make clean -C homebrew_launcher_installer
make clean -C sd_loader
@rm -fr $(BUILD) $(TARGET).rpx $(TARGET).elf
#-------------------------------------------------------------------------------
@ -115,23 +115,23 @@ DEPENDS := $(OFILES:.o=.d)
# main targets
#-------------------------------------------------------------------------------
hbl_installer_payload := ../homebrew_launcher_installer/payload.elf
sd_loader := ../sd_loader/sd_loader.elf
all : $(OUTPUT).rpx
$(hbl_installer_payload):
make -C ../homebrew_launcher_installer
$(sd_loader):
make -C ../sd_loader
$(OUTPUT).rpx : $(OUTPUT).elf
$(OUTPUT).elf : $(OFILES)
$(OFILES) : hbl_installer_payload.h
$(OFILES) : sd_loader.h
$(OFILES_SRC) : $(HFILES_BIN)
#-------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#-------------------------------------------------------------------------------
hbl_installer_payload.h: $(hbl_installer_payload)
sd_loader.h: $(sd_loader)
@bin2s -a 32 -H `(echo $(<F) | tr . _)`.h $< | $(AS) -o $(<F).o
@echo '#pragma once' > $@
@printf '#include "' >> $@

@ -1 +0,0 @@
Subproject commit a3d477f1a3d1cc06d89574ee1cc047eb2c90ed7a

4
sd_loader/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
build/
*.elf
sd_loader.c
sd_loader.h

191
sd_loader/Makefile Normal file
View File

@ -0,0 +1,191 @@
#---------------------------------------------------------------------------------
# Clear the implicit built in rules
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPPC)),)
$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=<path to>devkitPPC")
endif
export PATH := $(DEVKITPPC)/bin:$(PORTLIBS)/bin:$(PATH)
export LIBOGC_INC := $(DEVKITPRO)/libogc/include
export LIBOGC_LIB := $(DEVKITPRO)/libogc/lib/wii
export PORTLIBS := $(DEVKITPRO)/portlibs/ppc
PREFIX := powerpc-eabi-
export AS := $(PREFIX)as
export CC := $(PREFIX)gcc
export CXX := $(PREFIX)g++
export AR := $(PREFIX)ar
export OBJCOPY := $(PREFIX)objcopy
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
#---------------------------------------------------------------------------------
TARGET := sd_loader
BUILD := build
BUILD_DBG := $(TARGET)_dbg
SOURCES := src
DATA :=
INCLUDES :=
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
CFLAGS := -std=gnu11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math -fno-builtin \
-Os -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing $(INCLUDE)
CXXFLAGS := -std=gnu++11 -mrvl -mcpu=750 -meabi -mhard-float -ffast-math \
-O3 -Wall -Wextra -Wno-unused-parameter -Wno-strict-aliasing $(INCLUDE)
ASFLAGS := -mregnames
LDFLAGS := -nostartfiles -Wl,--gc-sections
Q := @
MAKEFLAGS += --no-print-directory
#---------------------------------------------------------------------------------
# any extra libraries we wish to link with the project
#---------------------------------------------------------------------------------
LIBS :=
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(CURDIR) \
$(DEVKITPPC)/lib \
$(DEVKITPPC)/lib/gcc/powerpc-eabi/4.8.2
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export PROJECTDIR := $(CURDIR)
export OUTPUT := $(CURDIR)/$(TARGETDIR)/$(TARGET)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
#---------------------------------------------------------------------------------
# automatically build a list of object files for our project
#---------------------------------------------------------------------------------
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
TTFFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.ttf)))
PNGFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.png)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
export LD := $(CC)
else
export LD := $(CXX)
endif
export OFILES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \
$(sFILES:.s=.o) $(SFILES:.S=.o) \
$(PNGFILES:.png=.png.o) $(addsuffix .o,$(BINFILES))
#---------------------------------------------------------------------------------
# build a list of include paths
#---------------------------------------------------------------------------------
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD) -I$(LIBOGC_INC) \
-I$(PORTLIBS)/include -I$(PORTLIBS)/include/freetype2
#---------------------------------------------------------------------------------
# path to tools
#---------------------------------------------------------------------------------
DEVKITPATH=$(shell echo "$(DEVKITPRO)" | sed -e 's/^\([a-zA-Z]\):/\/\1/')
export PATH := $(DEVKITPATH)/tools/bin:$(DEVKITPATH)/devkitPPC/bin:$(PATH)
#---------------------------------------------------------------------------------
# build a list of library paths
#---------------------------------------------------------------------------------
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \
-L$(LIBOGC_LIB) -L$(PORTLIBS)/lib
export OUTPUT := $(CURDIR)/$(TARGET)
.PHONY: $(BUILD) clean install
#---------------------------------------------------------------------------------
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).bin $(BUILD_DBG).elf $(BUILD_DBG).c $(BUILD_DBG).h
#---------------------------------------------------------------------------------
else
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(OUTPUT).h: $(OFILES)
$(OUTPUT).c: $(OUTPUT).elf
@raw2c $<
@cp $(TARGET).c $@
$(OUTPUT).h: $(OUTPUT).c
@cp $(TARGET).h $@
#---------------------------------------------------------------------------------
# This rule links in binary data with the .jpg extension
#---------------------------------------------------------------------------------
%.elf: link.ld $(OFILES)
@echo "linking ... $(TARGET).elf"
$(Q)$(LD) -n -T $^ $(LDFLAGS) -o ../$(BUILD_DBG).elf $(LIBPATHS) $(LIBS)
$(Q)$(OBJCOPY) -S -R .comment -R .gnu.attributes ../$(BUILD_DBG).elf $@
#---------------------------------------------------------------------------------
%.a:
#---------------------------------------------------------------------------------
@echo $(notdir $@)
@rm -f $@
@$(AR) -rc $@ $^
#---------------------------------------------------------------------------------
%.o: %.cpp
@echo $(notdir $<)
@$(CXX) -MMD -MP -MF $(DEPSDIR)/$*.d $(CXXFLAGS) -c $< -o $@ $(ERROR_FILTER)
#---------------------------------------------------------------------------------
%.o: %.c
@echo $(notdir $<)
@$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d $(CFLAGS) -c $< -o $@ $(ERROR_FILTER)
#---------------------------------------------------------------------------------
%.o: %.S
@echo $(notdir $<)
@$(CC) -MMD -MP -MF $(DEPSDIR)/$*.d -x assembler-with-cpp $(ASFLAGS) -c $< -o $@ $(ERROR_FILTER)
#---------------------------------------------------------------------------------
%.png.o : %.png
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
#---------------------------------------------------------------------------------
%.ttf.o : %.ttf
@echo $(notdir $<)
@bin2s -a 32 $< | $(AS) -o $(@)
-include $(DEPENDS)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------

42
sd_loader/src/common.h Normal file
View File

@ -0,0 +1,42 @@
#ifndef COMMON_H
#define COMMON_H
#ifdef __cplusplus
extern "C" {
#endif
#include "os_defs.h"
#define HBL_VERSION "v1.4"
#define CAFE_OS_SD_PATH "/vol/external01"
#define SD_PATH "sd:"
#define WIIU_PATH "/wiiu"
#ifndef MEM_BASE
#define MEM_BASE (0x00800000)
#endif
#define ELF_DATA_ADDR (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x00))
#define ELF_DATA_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x04))
#define HBL_CHANNEL (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x08))
#define RPX_MAX_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x0C))
#define RPX_MAX_CODE_SIZE (*(volatile unsigned int*)(MEM_BASE + 0x1300 + 0x10))
#define MAIN_ENTRY_ADDR (*(volatile unsigned int*)(MEM_BASE + 0x1400 + 0x00))
#define OS_FIRMWARE (*(volatile unsigned int*)(MEM_BASE + 0x1400 + 0x04))
#define OS_SPECIFICS ((OsSpecifics*)(MEM_BASE + 0x1500))
#define MEM_AREA_TABLE ((s_mem_area*)(MEM_BASE + 0x1600))
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#define EXIT_RELAUNCH_ON_LOAD 0xFFFFFFFD
#ifdef __cplusplus
}
#endif
#endif /* COMMON_H */

591
sd_loader/src/elf_abi.h Normal file
View File

@ -0,0 +1,591 @@
/*
* Copyright (c) 1995, 1996, 2001, 2002
* Erik Theisen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This is the ELF ABI header file
* formerly known as "elf_abi.h".
*/
#ifndef _ELF_ABI_H
#define _ELF_ABI_H
/*
* This version doesn't work for 64-bit ABIs - Erik.
*/
/*
* These typedefs need to be handled better.
*/
typedef unsigned int Elf32_Addr; /* Unsigned program address */
typedef unsigned int Elf32_Off; /* Unsigned file offset */
typedef signed int Elf32_Sword; /* Signed large integer */
typedef unsigned int Elf32_Word; /* Unsigned large integer */
typedef unsigned short Elf32_Half; /* Unsigned medium integer */
/* e_ident[] identification indexes */
#define EI_MAG0 0 /* file ID */
#define EI_MAG1 1 /* file ID */
#define EI_MAG2 2 /* file ID */
#define EI_MAG3 3 /* file ID */
#define EI_CLASS 4 /* file class */
#define EI_DATA 5 /* data encoding */
#define EI_VERSION 6 /* ELF header version */
#define EI_OSABI 7 /* OS/ABI specific ELF extensions */
#define EI_ABIVERSION 8 /* ABI target version */
#define EI_PAD 9 /* start of pad bytes */
#define EI_NIDENT 16 /* Size of e_ident[] */
/* e_ident[] magic number */
#define ELFMAG0 0x7f /* e_ident[EI_MAG0] */
#define ELFMAG1 'E' /* e_ident[EI_MAG1] */
#define ELFMAG2 'L' /* e_ident[EI_MAG2] */
#define ELFMAG3 'F' /* e_ident[EI_MAG3] */
#define ELFMAG "\177ELF" /* magic */
#define SELFMAG 4 /* size of magic */
/* e_ident[] file class */
#define ELFCLASSNONE 0 /* invalid */
#define ELFCLASsigned int 1 /* 32-bit objs */
#define ELFCLASS64 2 /* 64-bit objs */
#define ELFCLASSNUM 3 /* number of classes */
/* e_ident[] data encoding */
#define ELFDATANONE 0 /* invalid */
#define ELFDATA2LSB 1 /* Little-Endian */
#define ELFDATA2MSB 2 /* Big-Endian */
#define ELFDATANUM 3 /* number of data encode defines */
/* e_ident[] OS/ABI specific ELF extensions */
#define ELFOSABI_NONE 0 /* No extension specified */
#define ELFOSABI_HPUX 1 /* Hewlett-Packard HP-UX */
#define ELFOSABI_NETBSD 2 /* NetBSD */
#define ELFOSABI_LINUX 3 /* Linux */
#define ELFOSABI_SOLARIS 6 /* Sun Solaris */
#define ELFOSABI_AIX 7 /* AIX */
#define ELFOSABI_IRIX 8 /* IRIX */
#define ELFOSABI_FREEBSD 9 /* FreeBSD */
#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX */
#define ELFOSABI_MODESTO 11 /* Novell Modesto */
#define ELFOSABI_OPENBSD 12 /* OpenBSD */
/* 64-255 Architecture-specific value range */
/* e_ident[] ABI Version */
#define ELFABIVERSION 0
/* e_ident */
#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \
(ehdr).e_ident[EI_MAG1] == ELFMAG1 && \
(ehdr).e_ident[EI_MAG2] == ELFMAG2 && \
(ehdr).e_ident[EI_MAG3] == ELFMAG3)
/* ELF Header */
typedef struct elfhdr{
unsigned char e_ident[EI_NIDENT]; /* ELF Identification */
Elf32_Half e_type; /* object file type */
Elf32_Half e_machine; /* machine */
Elf32_Word e_version; /* object file version */
Elf32_Addr e_entry; /* virtual entry point */
Elf32_Off e_phoff; /* program header table offset */
Elf32_Off e_shoff; /* section header table offset */
Elf32_Word e_flags; /* processor-specific flags */
Elf32_Half e_ehsize; /* ELF header size */
Elf32_Half e_phentsize; /* program header entry size */
Elf32_Half e_phnum; /* number of program header entries */
Elf32_Half e_shentsize; /* section header entry size */
Elf32_Half e_shnum; /* number of section header entries */
Elf32_Half e_shstrndx; /* section header table's "section
header string table" entry offset */
} Elf32_Ehdr;
/* e_type */
#define ET_NONE 0 /* No file type */
#define ET_REL 1 /* relocatable file */
#define ET_EXEC 2 /* executable file */
#define ET_DYN 3 /* shared object file */
#define ET_CORE 4 /* core file */
#define ET_NUM 5 /* number of types */
#define ET_LOOS 0xfe00 /* reserved range for operating */
#define ET_HIOS 0xfeff /* system specific e_type */
#define ET_LOPROC 0xff00 /* reserved range for processor */
#define ET_HIPROC 0xffff /* specific e_type */
/* e_machine */
#define EM_NONE 0 /* No Machine */
#define EM_M32 1 /* AT&T WE 32100 */
#define EM_SPARC 2 /* SPARC */
#define EM_386 3 /* Intel 80386 */
#define EM_68K 4 /* Motorola 68000 */
#define EM_88K 5 /* Motorola 88000 */
#if 0
#define EM_486 6 /* RESERVED - was Intel 80486 */
#endif
#define EM_860 7 /* Intel 80860 */
#define EM_MIPS 8 /* MIPS R3000 Big-Endian only */
#define EM_S370 9 /* IBM System/370 Processor */
#define EM_MIPS_RS4_BE 10 /* MIPS R4000 Big-Endian */
#if 0
#define EM_SPARC64 11 /* RESERVED - was SPARC v9
64-bit unoffical */
#endif
/* RESERVED 11-14 for future use */
#define EM_PARISC 15 /* HPPA */
/* RESERVED 16 for future use */
#define EM_VPP500 17 /* Fujitsu VPP500 */
#define EM_SPARC32PLUS 18 /* Enhanced instruction set SPARC */
#define EM_960 19 /* Intel 80960 */
#define EM_PPC 20 /* PowerPC */
#define EM_PPC64 21 /* 64-bit PowerPC */
#define EM_S390 22 /* IBM System/390 Processor */
/* RESERVED 23-35 for future use */
#define EM_V800 36 /* NEC V800 */
#define EM_FR20 37 /* Fujitsu FR20 */
#define EM_RH32 38 /* TRW RH-32 */
#define EM_RCE 39 /* Motorola RCE */
#define EM_ARM 40 /* Advanced Risc Machines ARM */
#define EM_ALPHA 41 /* Digital Alpha */
#define EM_SH 42 /* Hitachi SH */
#define EM_SPARCV9 43 /* SPARC Version 9 */
#define EM_TRICORE 44 /* Siemens TriCore embedded processor */
#define EM_ARC 45 /* Argonaut RISC Core */
#define EM_H8_300 46 /* Hitachi H8/300 */
#define EM_H8_300H 47 /* Hitachi H8/300H */
#define EM_H8S 48 /* Hitachi H8S */
#define EM_H8_500 49 /* Hitachi H8/500 */
#define EM_IA_64 50 /* Intel Merced */
#define EM_MIPS_X 51 /* Stanford MIPS-X */
#define EM_COLDFIRE 52 /* Motorola Coldfire */
#define EM_68HC12 53 /* Motorola M68HC12 */
#define EM_MMA 54 /* Fujitsu MMA Multimedia Accelerator*/
#define EM_PCP 55 /* Siemens PCP */
#define EM_NCPU 56 /* Sony nCPU embeeded RISC */
#define EM_NDR1 57 /* Denso NDR1 microprocessor */
#define EM_STARCORE 58 /* Motorola Start*Core processor */
#define EM_ME16 59 /* Toyota ME16 processor */
#define EM_ST100 60 /* STMicroelectronic ST100 processor */
#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam*/
#define EM_X86_64 62 /* AMD x86-64 */
#define EM_PDSP 63 /* Sony DSP Processor */
/* RESERVED 64,65 for future use */
#define EM_FX66 66 /* Siemens FX66 microcontroller */
#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */
#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */
#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller */
#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller */
#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller */
#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller */
#define EM_SVX 73 /* Silicon Graphics SVx */
#define EM_ST19 74 /* STMicroelectronics ST19 8 bit mc */
#define EM_VAX 75 /* Digital VAX */
#define EM_CHRIS 76 /* Axis Communications embedded proc. */
#define EM_JAVELIN 77 /* Infineon Technologies emb. proc. */
#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor */
#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor */
#define EM_MMIX 80 /* Donald Knuth's edu 64-bit proc. */
#define EM_HUANY 81 /* Harvard University mach-indep objs */
#define EM_PRISM 82 /* SiTera Prism */
#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller */
#define EM_FR30 84 /* Fujitsu FR30 */
#define EM_D10V 85 /* Mitsubishi DV10V */
#define EM_D30V 86 /* Mitsubishi DV30V */
#define EM_V850 87 /* NEC v850 */
#define EM_M32R 88 /* Mitsubishi M32R */
#define EM_MN10300 89 /* Matsushita MN10200 */
#define EM_MN10200 90 /* Matsushita MN10200 */
#define EM_PJ 91 /* picoJava */
#define EM_NUM 92 /* number of machine types */
/* Version */
#define EV_NONE 0 /* Invalid */
#define EV_CURRENT 1 /* Current */
#define EV_NUM 2 /* number of versions */
/* Section Header */
typedef struct {
Elf32_Word sh_name; /* name - index into section header
string table section */
Elf32_Word sh_type; /* type */
Elf32_Word sh_flags; /* flags */
Elf32_Addr sh_addr; /* address */
Elf32_Off sh_offset; /* file offset */
Elf32_Word sh_size; /* section size */
Elf32_Word sh_link; /* section header table index link */
Elf32_Word sh_info; /* extra information */
Elf32_Word sh_addralign; /* address alignment */
Elf32_Word sh_entsize; /* section entry size */
} Elf32_Shdr;
/* Special Section Indexes */
#define SHN_UNDEF 0 /* undefined */
#define SHN_LORESERVE 0xff00 /* lower bounds of reserved indexes */
#define SHN_LOPROC 0xff00 /* reserved range for processor */
#define SHN_HIPROC 0xff1f /* specific section indexes */
#define SHN_LOOS 0xff20 /* reserved range for operating */
#define SHN_HIOS 0xff3f /* specific semantics */
#define SHN_ABS 0xfff1 /* absolute value */
#define SHN_COMMON 0xfff2 /* common symbol */
#define SHN_XINDEX 0xffff /* Index is an extra table */
#define SHN_HIRESERVE 0xffff /* upper bounds of reserved indexes */
/* sh_type */
#define SHT_NULL 0 /* inactive */
#define SHT_PROGBITS 1 /* program defined information */
#define SHT_SYMTAB 2 /* symbol table section */
#define SHT_STRTAB 3 /* string table section */
#define SHT_RELA 4 /* relocation section with addends*/
#define SHT_HASH 5 /* symbol hash table section */
#define SHT_DYNAMIC 6 /* dynamic section */
#define SHT_NOTE 7 /* note section */
#define SHT_NOBITS 8 /* no space section */
#define SHT_REL 9 /* relation section without addends */
#define SHT_SHLIB 10 /* reserved - purpose unknown */
#define SHT_DYNSYM 11 /* dynamic symbol table section */
#define SHT_INIT_ARRAY 14 /* Array of constructors */
#define SHT_FINI_ARRAY 15 /* Array of destructors */
#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */
#define SHT_GROUP 17 /* Section group */
#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */
#define SHT_NUM 19 /* number of section types */
#define SHT_LOOS 0x60000000 /* Start OS-specific */
#define SHT_HIOS 0x6fffffff /* End OS-specific */
#define SHT_LOPROC 0x70000000 /* reserved range for processor */
#define SHT_HIPROC 0x7fffffff /* specific section header types */
#define SHT_LOUSER 0x80000000 /* reserved range for application */
#define SHT_HIUSER 0xffffffff /* specific indexes */
/* Section names */
#define ELF_BSS ".bss" /* uninitialized data */
#define ELF_COMMENT ".comment" /* version control information */
#define ELF_DATA ".data" /* initialized data */
#define ELF_DATA1 ".data1" /* initialized data */
#define ELF_DEBUG ".debug" /* debug */
#define ELF_DYNAMIC ".dynamic" /* dynamic linking information */
#define ELF_DYNSTR ".dynstr" /* dynamic string table */
#define ELF_DYNSYM ".dynsym" /* dynamic symbol table */
#define ELF_FINI ".fini" /* termination code */
#define ELF_FINI_ARRAY ".fini_array" /* Array of destructors */
#define ELF_GOT ".got" /* global offset table */
#define ELF_HASH ".hash" /* symbol hash table */
#define ELF_INIT ".init" /* initialization code */
#define ELF_INIT_ARRAY ".init_array" /* Array of constuctors */
#define ELF_INTERP ".interp" /* Pathname of program interpreter */
#define ELF_LINE ".line" /* Symbolic line numnber information */
#define ELF_NOTE ".note" /* Contains note section */
#define ELF_PLT ".plt" /* Procedure linkage table */
#define ELF_PREINIT_ARRAY ".preinit_array" /* Array of pre-constructors */
#define ELF_REL_DATA ".rel.data" /* relocation data */
#define ELF_REL_FINI ".rel.fini" /* relocation termination code */
#define ELF_REL_INIT ".rel.init" /* relocation initialization code */
#define ELF_REL_DYN ".rel.dyn" /* relocaltion dynamic link info */
#define ELF_REL_RODATA ".rel.rodata" /* relocation read-only data */
#define ELF_REL_TEXT ".rel.text" /* relocation code */
#define ELF_RODATA ".rodata" /* read-only data */
#define ELF_RODATA1 ".rodata1" /* read-only data */
#define ELF_SHSTRTAB ".shstrtab" /* section header string table */
#define ELF_STRTAB ".strtab" /* string table */
#define ELF_SYMTAB ".symtab" /* symbol table */
#define ELF_SYMTAB_SHNDX ".symtab_shndx"/* symbol table section index */
#define ELF_TBSS ".tbss" /* thread local uninit data */
#define ELF_TDATA ".tdata" /* thread local init data */
#define ELF_TDATA1 ".tdata1" /* thread local init data */
#define ELF_TEXT ".text" /* code */
/* Section Attribute Flags - sh_flags */
#define SHF_WRITE 0x1 /* Writable */
#define SHF_ALLOC 0x2 /* occupies memory */
#define SHF_EXECINSTR 0x4 /* executable */
#define SHF_MERGE 0x10 /* Might be merged */
#define SHF_STRINGS 0x20 /* Contains NULL terminated strings */
#define SHF_INFO_LINK 0x40 /* sh_info contains SHT index */
#define SHF_LINK_ORDER 0x80 /* Preserve order after combining*/
#define SHF_OS_NONCONFORMING 0x100 /* Non-standard OS specific handling */
#define SHF_GROUP 0x200 /* Member of section group */
#define SHF_TLS 0x400 /* Thread local storage */
#define SHF_MASKOS 0x0ff00000 /* OS specific */
#define SHF_MASKPROC 0xf0000000 /* reserved bits for processor */
/* specific section attributes */
/* Section Group Flags */
#define GRP_COMDAT 0x1 /* COMDAT group */
#define GRP_MASKOS 0x0ff00000 /* Mask OS specific flags */
#define GRP_MASKPROC 0xf0000000 /* Mask processor specific flags */
/* Symbol Table Entry */
typedef struct elf32_sym {
Elf32_Word st_name; /* name - index into string table */
Elf32_Addr st_value; /* symbol value */
Elf32_Word st_size; /* symbol size */
unsigned char st_info; /* type and binding */
unsigned char st_other; /* 0 - no defined meaning */
Elf32_Half st_shndx; /* section header index */
} Elf32_Sym;
/* Symbol table index */
#define STN_UNDEF 0 /* undefined */
/* Extract symbol info - st_info */
#define ELF32_ST_BIND(x) ((x) >> 4)
#define ELF32_ST_TYPE(x) (((unsigned int) x) & 0xf)
#define ELF32_ST_INFO(b,t) (((b) << 4) + ((t) & 0xf))
#define ELF32_ST_VISIBILITY(x) ((x) & 0x3)
/* Symbol Binding - ELF32_ST_BIND - st_info */
#define STB_LOCAL 0 /* Local symbol */
#define STB_GLOBAL 1 /* Global symbol */
#define STB_WEAK 2 /* like global - lower precedence */
#define STB_NUM 3 /* number of symbol bindings */
#define STB_LOOS 10 /* reserved range for operating */
#define STB_HIOS 12 /* system specific symbol bindings */
#define STB_LOPROC 13 /* reserved range for processor */
#define STB_HIPROC 15 /* specific symbol bindings */
/* Symbol type - ELF32_ST_TYPE - st_info */
#define STT_NOTYPE 0 /* not specified */
#define STT_OBJECT 1 /* data object */
#define STT_FUNC 2 /* function */
#define STT_SECTION 3 /* section */
#define STT_FILE 4 /* file */
#define STT_NUM 5 /* number of symbol types */
#define STT_TLS 6 /* Thread local storage symbol */
#define STT_LOOS 10 /* reserved range for operating */
#define STT_HIOS 12 /* system specific symbol types */
#define STT_LOPROC 13 /* reserved range for processor */
#define STT_HIPROC 15 /* specific symbol types */
/* Symbol visibility - ELF32_ST_VISIBILITY - st_other */
#define STV_DEFAULT 0 /* Normal visibility rules */
#define STV_INTERNAL 1 /* Processor specific hidden class */
#define STV_HIDDEN 2 /* Symbol unavailable in other mods */
#define STV_PROTECTED 3 /* Not preemptible, not exported */
/* Relocation entry with implicit addend */
typedef struct
{
Elf32_Addr r_offset; /* offset of relocation */
Elf32_Word r_info; /* symbol table index and type */
} Elf32_Rel;
/* Relocation entry with explicit addend */
typedef struct
{
Elf32_Addr r_offset; /* offset of relocation */
Elf32_Word r_info; /* symbol table index and type */
Elf32_Sword r_addend;
} Elf32_Rela;
/* Extract relocation info - r_info */
#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))
/* Program Header */
typedef struct {
Elf32_Word p_type; /* segment type */
Elf32_Off p_offset; /* segment offset */
Elf32_Addr p_vaddr; /* virtual address of segment */
Elf32_Addr p_paddr; /* physical address - ignored? */
Elf32_Word p_filesz; /* number of bytes in file for seg. */
Elf32_Word p_memsz; /* number of bytes in mem. for seg. */
Elf32_Word p_flags; /* flags */
Elf32_Word p_align; /* memory alignment */
} Elf32_Phdr;
/* Segment types - p_type */
#define PT_NULL 0 /* unused */
#define PT_LOAD 1 /* loadable segment */
#define PT_DYNAMIC 2 /* dynamic linking section */
#define PT_INTERP 3 /* the RTLD */
#define PT_NOTE 4 /* auxiliary information */
#define PT_SHLIB 5 /* reserved - purpose undefined */
#define PT_PHDR 6 /* program header */
#define PT_TLS 7 /* Thread local storage template */
#define PT_NUM 8 /* Number of segment types */
#define PT_LOOS 0x60000000 /* reserved range for operating */
#define PT_HIOS 0x6fffffff /* system specific segment types */
#define PT_LOPROC 0x70000000 /* reserved range for processor */
#define PT_HIPROC 0x7fffffff /* specific segment types */
/* Segment flags - p_flags */
#define PF_X 0x1 /* Executable */
#define PF_W 0x2 /* Writable */
#define PF_R 0x4 /* Readable */
#define PF_MASKOS 0x0ff00000 /* OS specific segment flags */
#define PF_MASKPROC 0xf0000000 /* reserved bits for processor */
/* specific segment flags */
/* Dynamic structure */
typedef struct
{
Elf32_Sword d_tag; /* controls meaning of d_val */
union
{
Elf32_Word d_val; /* Multiple meanings - see d_tag */
Elf32_Addr d_ptr; /* program virtual address */
} d_un;
} Elf32_Dyn;
extern Elf32_Dyn _DYNAMIC[];
/* Dynamic Array Tags - d_tag */
#define DT_NULL 0 /* marks end of _DYNAMIC array */
#define DT_NEEDED 1 /* string table offset of needed lib */
#define DT_PLTRELSZ 2 /* size of relocation entries in PLT */
#define DT_PLTGOT 3 /* address PLT/GOT */
#define DT_HASH 4 /* address of symbol hash table */
#define DT_STRTAB 5 /* address of string table */
#define DT_SYMTAB 6 /* address of symbol table */
#define DT_RELA 7 /* address of relocation table */
#define DT_RELASZ 8 /* size of relocation table */
#define DT_RELAENT 9 /* size of relocation entry */
#define DT_STRSZ 10 /* size of string table */
#define DT_SYMENT 11 /* size of symbol table entry */
#define DT_INIT 12 /* address of initialization func. */
#define DT_FINI 13 /* address of termination function */
#define DT_SONAME 14 /* string table offset of shared obj */
#define DT_RPATH 15 /* string table offset of library
search path */
#define DT_SYMBOLIC 16 /* start sym search in shared obj. */
#define DT_REL 17 /* address of rel. tbl. w addends */
#define DT_RELSZ 18 /* size of DT_REL relocation table */
#define DT_RELENT 19 /* size of DT_REL relocation entry */
#define DT_PLTREL 20 /* PLT referenced relocation entry */
#define DT_DEBUG 21 /* bugger */
#define DT_TEXTREL 22 /* Allow rel. mod. to unwritable seg */
#define DT_JMPREL 23 /* add. of PLT's relocation entries */
#define DT_BIND_NOW 24 /* Process relocations of object */
#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */
#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */
#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */
#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */
#define DT_RUNPATH 29 /* Library search path */
#define DT_FLAGS 30 /* Flags for the object being loaded */
#define DT_ENCODING 32 /* Start of encoded range */
#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/
#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */
#define DT_NUM 34 /* Number used. */
#define DT_LOOS 0x60000000 /* reserved range for OS */
#define DT_HIOS 0x6fffffff /* specific dynamic array tags */
#define DT_LOPROC 0x70000000 /* reserved range for processor */
#define DT_HIPROC 0x7fffffff /* specific dynamic array tags */
/* Dynamic Tag Flags - d_un.d_val */
#define DF_ORIGIN 0x01 /* Object may use DF_ORIGIN */
#define DF_SYMBOLIC 0x02 /* Symbol resolutions starts here */
#define DF_TEXTREL 0x04 /* Object contains text relocations */
#define DF_BIND_NOW 0x08 /* No lazy binding for this object */
#define DF_STATIC_TLS 0x10 /* Static thread local storage */
/* Standard ELF hashing function */
unsigned long elf_hash(const unsigned char *name);
#define ELF_TARG_VER 1 /* The ver for which this code is intended */
/*
* XXX - PowerPC defines really don't belong in here,
* but we'll put them in for simplicity.
*/
/* Values for Elf32/64_Ehdr.e_flags. */
#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */
/* Cygnus local bits below */
#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/
#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib
flag */
/* PowerPC relocations defined by the ABIs */
#define R_PPC_NONE 0
#define R_PPC_ADDR32 1 /* 32bit absolute address */
#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */
#define R_PPC_ADDR16 3 /* 16bit absolute address */
#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */
#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */
#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */
#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */
#define R_PPC_ADDR14_BRTAKEN 8
#define R_PPC_ADDR14_BRNTAKEN 9
#define R_PPC_REL24 10 /* PC relative 26 bit */
#define R_PPC_REL14 11 /* PC relative 16 bit */
#define R_PPC_REL14_BRTAKEN 12
#define R_PPC_REL14_BRNTAKEN 13
#define R_PPC_GOT16 14
#define R_PPC_GOT16_LO 15
#define R_PPC_GOT16_HI 16
#define R_PPC_GOT16_HA 17
#define R_PPC_PLTREL24 18
#define R_PPC_COPY 19
#define R_PPC_GLOB_DAT 20
#define R_PPC_JMP_SLOT 21
#define R_PPC_RELATIVE 22
#define R_PPC_LOCAL24PC 23
#define R_PPC_UADDR32 24
#define R_PPC_UADDR16 25
#define R_PPC_REL32 26
#define R_PPC_PLT32 27
#define R_PPC_PLTREL32 28
#define R_PPC_PLT16_LO 29
#define R_PPC_PLT16_HI 30
#define R_PPC_PLT16_HA 31
#define R_PPC_SDAREL16 32
#define R_PPC_SECTOFF 33
#define R_PPC_SECTOFF_LO 34
#define R_PPC_SECTOFF_HI 35
#define R_PPC_SECTOFF_HA 36
/* Keep this the last entry. */
#define R_PPC_NUM 37
/* The remaining relocs are from the Embedded ELF ABI, and are not
in the SVR4 ELF ABI. */
#define R_PPC_EMB_NADDR32 101
#define R_PPC_EMB_NADDR16 102
#define R_PPC_EMB_NADDR16_LO 103
#define R_PPC_EMB_NADDR16_HI 104
#define R_PPC_EMB_NADDR16_HA 105
#define R_PPC_EMB_SDAI16 106
#define R_PPC_EMB_SDA2I16 107
#define R_PPC_EMB_SDA2REL 108
#define R_PPC_EMB_SDA21 109 /* 16 bit offset in SDA */
#define R_PPC_EMB_MRKREF 110
#define R_PPC_EMB_RELSEC16 111
#define R_PPC_EMB_RELST_LO 112
#define R_PPC_EMB_RELST_HI 113
#define R_PPC_EMB_RELST_HA 114
#define R_PPC_EMB_BIT_FLD 115
#define R_PPC_EMB_RELSDA 116 /* 16 bit relative offset in SDA */
/* Diab tool relocations. */
#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */
#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */
#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */
#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */
#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */
#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */
/* This is a phony reloc to handle any old fashioned TOC16 references
that may still be in object files. */
#define R_PPC_TOC16 255
#endif /* _ELF_H */

620
sd_loader/src/entry.c Normal file
View File

@ -0,0 +1,620 @@
#include "os_types.h"
#include "elf_abi.h"
#include "common.h"
#include "os_defs.h"
#include "fs_defs.h"
#include "kernel_defs.h"
#include "loader_defs.h"
#define EXPORT_DECL(res, func, ...) res (* func)(__VA_ARGS__);
#define OS_FIND_EXPORT(handle, funcName, func) OSDynLoad_FindExport(handle, 0, funcName, &func)
typedef struct _private_data_t {
EXPORT_DECL(void *, MEMAllocFromDefaultHeapEx, int size, int align);
EXPORT_DECL(void, MEMFreeToDefaultHeap, void *ptr);
EXPORT_DECL(uint64_t, OSGetTitleID);
EXPORT_DECL(void*, memcpy, void *p1, const void *p2, unsigned int s);
EXPORT_DECL(void*, memset, void *p1, int val, unsigned int s);
EXPORT_DECL(void, OSFatal, const char *msg);
EXPORT_DECL(unsigned int, OSEffectiveToPhysical, const void*);
EXPORT_DECL(void, exit, int);
EXPORT_DECL(int, FSInit, void);
EXPORT_DECL(int, FSAddClientEx, void *pClient, int unk_zero_param, int errHandling);
EXPORT_DECL(int, FSDelClient, void *pClient);
EXPORT_DECL(void, FSInitCmdBlock, void *pCmd);
EXPORT_DECL(int, FSGetMountSource, void *pClient, void *pCmd, int type, void *source, int errHandling);
EXPORT_DECL(int, FSMount, void *pClient, void *pCmd, void *source, const char *target, uint32_t bytes, int errHandling);
EXPORT_DECL(int, FSUnmount, void *pClient, void *pCmd, const char *target, int errHandling);
EXPORT_DECL(int, FSOpenFile, void *pClient, void *pCmd, const char *path, const char *mode, int *fd, int errHandling);
EXPORT_DECL(int, FSGetStatFile, void *pClient, void *pCmd, int fd, void *buffer, int error);
EXPORT_DECL(int, FSReadFile, void *pClient, void *pCmd, void *buffer, int size, int count, int fd, int flag, int errHandling);
EXPORT_DECL(int, FSCloseFile, void *pClient, void *pCmd, int fd, int errHandling);
EXPORT_DECL(int, SYSRelaunchTitle, int argc, char **argv);
} private_data_t;
static void (*DCFlushRange)(void *addr, unsigned int size);
static void (*DCInvalidateRange)(void *addr, unsigned int size);
static void (*ICInvalidateRange)(void *addr, unsigned int size);
static unsigned int hook_LiWaitOneChunk;
static unsigned int addrphys_LiWaitOneChunk;
extern void SC0x25_KernelCopyData(unsigned int addr, unsigned int src, unsigned int len);
extern void my_PrepareTitle_hook(void);
/* Write a 32-bit word with kernel permissions */
static void __attribute__ ((noinline)) kern_write(void *addr, uint32_t value) {
asm volatile (
"li 3,1\n"
"li 4,0\n"
"mr 5,%1\n"
"li 6,0\n"
"li 7,0\n"
"lis 8,1\n"
"mr 9,%0\n"
"mr %1,1\n"
"li 0,0x3500\n"
"sc\n"
"nop\n"
"mr 1,%1\n"
:
: "r"(addr), "r"(value)
: "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12"
);
}
static void KernelCopyData(unsigned int addr, unsigned int src, unsigned int len) {
/*
* Setup a DBAT access with cache inhibited to write through and read directly from memory
*/
unsigned int dbatu0, dbatl0, dbatu1, dbatl1;
// save the original DBAT value
asm volatile("mfdbatu %0, 0" : "=r" (dbatu0));
asm volatile("mfdbatl %0, 0" : "=r" (dbatl0));
asm volatile("mfdbatu %0, 1" : "=r" (dbatu1));
asm volatile("mfdbatl %0, 1" : "=r" (dbatl1));
unsigned int target_dbatu0 = 0;
unsigned int target_dbatl0 = 0;
unsigned int target_dbatu1 = 0;
unsigned int target_dbatl1 = 0;
unsigned int *dst_p = (unsigned int*)addr;
unsigned int *src_p = (unsigned int*)src;
// we only need DBAT modification for addresses out of our own DBAT range
// as our own DBAT is available everywhere for user and supervisor
// since our own DBAT is on DBAT5 position we don't collide here
if(addr < 0x00800000 || addr >= 0x01000000) {
target_dbatu0 = (addr & 0x00F00000) | 0xC0000000 | 0x1F;
target_dbatl0 = (addr & 0xFFF00000) | 0x32;
asm volatile("mtdbatu 0, %0" : : "r" (target_dbatu0));
asm volatile("mtdbatl 0, %0" : : "r" (target_dbatl0));
dst_p = (unsigned int*)((addr & 0xFFFFFF) | 0xC0000000);
}
if(src < 0x00800000 || src >= 0x01000000) {
target_dbatu1 = (src & 0x00F00000) | 0xB0000000 | 0x1F;
target_dbatl1 = (src & 0xFFF00000) | 0x32;
asm volatile("mtdbatu 1, %0" : : "r" (target_dbatu1));
asm volatile("mtdbatl 1, %0" : : "r" (target_dbatl1));
src_p = (unsigned int*)((src & 0xFFFFFF) | 0xB0000000);
}
asm volatile("eieio; isync");
unsigned int i;
for(i = 0; i < len; i += 4) {
// if we are on the edge to next chunk
if((target_dbatu0 != 0) && (((unsigned int)dst_p & 0x00F00000) != (target_dbatu0 & 0x00F00000))) {
target_dbatu0 = ((addr + i) & 0x00F00000) | 0xC0000000 | 0x1F;
target_dbatl0 = ((addr + i) & 0xFFF00000) | 0x32;
dst_p = (unsigned int*)(((addr + i) & 0xFFFFFF) | 0xC0000000);
asm volatile("eieio; isync");
asm volatile("mtdbatu 0, %0" : : "r" (target_dbatu0));
asm volatile("mtdbatl 0, %0" : : "r" (target_dbatl0));
asm volatile("eieio; isync");
}
if((target_dbatu1 != 0) && (((unsigned int)src_p & 0x00F00000) != (target_dbatu1 & 0x00F00000))) {
target_dbatu1 = ((src + i) & 0x00F00000) | 0xB0000000 | 0x1F;
target_dbatl1 = ((src + i) & 0xFFF00000) | 0x32;
src_p = (unsigned int*)(((src + i) & 0xFFFFFF) | 0xB0000000);
asm volatile("eieio; isync");
asm volatile("mtdbatu 1, %0" : : "r" (target_dbatu1));
asm volatile("mtdbatl 1, %0" : : "r" (target_dbatl1));
asm volatile("eieio; isync");
}
*dst_p = *src_p;
++dst_p;
++src_p;
}
/*
* Restore original DBAT value
*/
asm volatile("eieio; isync");
asm volatile("mtdbatu 0, %0" : : "r" (dbatu0));
asm volatile("mtdbatl 0, %0" : : "r" (dbatl0));
asm volatile("mtdbatu 1, %0" : : "r" (dbatu1));
asm volatile("mtdbatl 1, %0" : : "r" (dbatl1));
asm volatile("eieio; isync");
}
// This function is called every time after LiBounceOneChunk.
// It waits for the asynchronous call of LiLoadAsync for the IOSU to fill data to the RPX/RPL address
// and return the still remaining bytes to load.
// We override it and replace the loaded date from LiLoadAsync with our data and our remaining bytes to load.
static int LiWaitOneChunk(unsigned int * iRemainingBytes, const char *filename, int fileType) {
unsigned int result;
register int core_id;
int remaining_bytes = 0;
int sgFileOffset;
int sgBufferNumber;
int *sgBounceError;
int *sgGotBytes;
int *sgTotalBytes;
int *sgIsLoadingBuffer;
int *sgFinishedLoadingBuffer;
// get the current core
asm volatile("mfspr %0, 0x3EF" : "=r" (core_id));
// get the offset of per core global variable for dynload initialized (just a simple address + (core_id * 4))
unsigned int gDynloadInitialized = *(volatile unsigned int*)(OS_SPECIFICS->addr_gDynloadInitialized + (core_id << 2));
// Comment (Dimok):
// time measurement at this position for logger -> we don't need it right now except maybe for debugging
//unsigned long long systemTime1 = Loader_GetSystemTime();
if(OS_FIRMWARE == 550) {
// pointer to global variables of the loader
loader_globals_550_t *loader_globals = (loader_globals_550_t*)(0xEFE19E80);
sgBufferNumber = loader_globals->sgBufferNumber;
sgFileOffset = loader_globals->sgFileOffset;
sgBounceError = &loader_globals->sgBounceError;
sgGotBytes = &loader_globals->sgGotBytes;
sgTotalBytes = &loader_globals->sgTotalBytes;
sgFinishedLoadingBuffer = &loader_globals->sgFinishedLoadingBuffer;
// not available on 5.5.x
sgIsLoadingBuffer = NULL;
} else {
// pointer to global variables of the loader
loader_globals_t *loader_globals = (loader_globals_t*)(OS_SPECIFICS->addr_sgIsLoadingBuffer);
sgBufferNumber = loader_globals->sgBufferNumber;
sgFileOffset = loader_globals->sgFileOffset;
sgBounceError = &loader_globals->sgBounceError;
sgGotBytes = &loader_globals->sgGotBytes;
sgIsLoadingBuffer = &loader_globals->sgIsLoadingBuffer;
// not available on < 5.5.x
sgTotalBytes = NULL;
sgFinishedLoadingBuffer = NULL;
}
// the data loading was started in LiBounceOneChunk() and here it waits for IOSU to finish copy the data
if(gDynloadInitialized != 0) {
result = OS_SPECIFICS->LiWaitIopCompleteWithInterrupts(0x2160EC0, &remaining_bytes);
} else {
result = OS_SPECIFICS->LiWaitIopComplete(0x2160EC0, &remaining_bytes);
}
// Comment (Dimok):
// time measurement at this position for logger -> we don't need it right now except maybe for debugging
//unsigned long long systemTime2 = Loader_GetSystemTime();
//------------------------------------------------------------------------------------------------------------------
// Start of our function intrusion:
// After IOSU is done writing the data into the 0xF6000000/0xF6400000 address,
// we overwrite it with our data before setting the global flag for IsLoadingBuffer to 0
// Do this only if we are in the game that was launched by our method
s_mem_area *mem_area = MEM_AREA_TABLE;
if((ELF_DATA_ADDR == mem_area->address) && (fileType == 0)) {
unsigned int load_address = (sgBufferNumber == 1) ? 0xF6000000 : (0xF6000000 + 0x00400000);
unsigned int load_addressPhys = (sgBufferNumber == 1) ? 0x1B000000 : (0x1B000000 + 0x00400000); // virtual 0xF6000000 and 0xF6400000
remaining_bytes = ELF_DATA_SIZE - sgFileOffset;
if (remaining_bytes > 0x400000)
// truncate size
remaining_bytes = 0x400000;
DCFlushRange((void*)load_address, remaining_bytes);
u32 rpxBlockPos = 0;
u32 done = 0;
u32 mapOffset = 0;
while((done < (u32)sgFileOffset) && mem_area) {
if((done + mem_area->size) > (u32)sgFileOffset) {
mapOffset = sgFileOffset - done;
done = sgFileOffset;
} else {
done += mem_area->size;
mem_area = mem_area->next;
}
}
while((done < ELF_DATA_SIZE) && (rpxBlockPos < 0x400000) && mem_area) {
u32 address = mem_area->address + mapOffset;
u32 blockSize = ELF_DATA_SIZE - done;
if(blockSize > (0x400000 - rpxBlockPos)) {
blockSize = 0x400000 - rpxBlockPos;
}
if((mapOffset + blockSize) >= mem_area->size) {
blockSize = mem_area->size - mapOffset;
//! this value is incremented later by blockSize, so set it to -blockSize for it to be 0 after copy
//! it makes smaller code then if(mapOffset == mem_area->size) after copy
mapOffset = -blockSize;
mem_area = mem_area->next;
}
SC0x25_KernelCopyData(load_addressPhys + rpxBlockPos, address, blockSize);
done += blockSize;
rpxBlockPos += blockSize;
mapOffset += blockSize;
}
DCInvalidateRange((void*)load_address, remaining_bytes);
if((u32)(sgFileOffset + remaining_bytes) == ELF_DATA_SIZE) {
ELF_DATA_ADDR = 0xDEADC0DE;
ELF_DATA_SIZE = 0;
MAIN_ENTRY_ADDR = 0xC001C0DE;
}
// set result to 0 -> "everything OK"
result = 0;
}
// end of our little intrusion into this function
//------------------------------------------------------------------------------------------------------------------
// set the result to the global bounce error variable
if(sgBounceError) {
*sgBounceError = result;
}
// disable global flag that buffer is still loaded by IOSU
if(sgFinishedLoadingBuffer) {
unsigned int zeroBitCount = 0;
asm volatile("cntlzw %0, %0" : "=r" (zeroBitCount) : "r"(*sgFinishedLoadingBuffer));
*sgFinishedLoadingBuffer = zeroBitCount >> 5;
} else if(sgIsLoadingBuffer) {
*sgIsLoadingBuffer = 0;
}
// check result for errors
if(result == 0) {
// the remaining size is set globally and in stack variable only
// if a pointer was passed to this function
if(iRemainingBytes) {
if(sgGotBytes) {
*sgGotBytes = remaining_bytes;
}
*iRemainingBytes = remaining_bytes;
// on 5.5.x a new variable for total loaded bytes was added
if(sgTotalBytes) {
*sgTotalBytes += remaining_bytes;
}
}
// Comment (Dimok):
// calculate time difference and print it on logging how long the wait for asynchronous data load took
// something like (systemTime2 - systemTime1) * constant / bus speed, did not look deeper into it as we don't need that crap
} else {
// Comment (Dimok):
// a lot of error handling here. depending on error code sometimes calls Loader_Panic() -> we don't make errors so we can skip that part ;-P
}
return result;
}
void my_PrepareTitle(CosAppXmlInfo *xmlKernelInfo) {
if(ELF_DATA_ADDR == MEM_AREA_TABLE->address) {
xmlKernelInfo->max_size = RPX_MAX_SIZE;
xmlKernelInfo->max_codesize = RPX_MAX_CODE_SIZE;
//! setup our hook to LiWaitOneChunk for RPX loading
hook_LiWaitOneChunk = ((u32)LiWaitOneChunk) | 0x48000002;
KernelCopyData(addrphys_LiWaitOneChunk, (u32) &hook_LiWaitOneChunk, 4);
asm volatile("icbi 0, %0" : : "r" (OS_SPECIFICS->addr_LiWaitOneChunk & ~31));
} else if((MAIN_ENTRY_ADDR == 0xC001C0DE) && (*(u32*)xmlKernelInfo->rpx_name == 0x66666c5f)) { // ffl_
//! restore original LiWaitOneChunk instruction as our RPX is done
MAIN_ENTRY_ADDR = 0xDEADC0DE;
KernelCopyData(addrphys_LiWaitOneChunk, (u32)&OS_SPECIFICS->orig_LiWaitOneChunkInstr, 4);
asm volatile("icbi 0, %0" : : "r" (OS_SPECIFICS->addr_LiWaitOneChunk & ~31));
}
}
static int LoadFileToMem(private_data_t *private_data, const char *filepath, unsigned char **fileOut, unsigned int * sizeOut) {
int iFd = -1;
void *pClient = private_data->MEMAllocFromDefaultHeapEx(FS_CLIENT_SIZE, 4);
if(!pClient)
return 0;
void *pCmd = private_data->MEMAllocFromDefaultHeapEx(FS_CMD_BLOCK_SIZE, 4);
if(!pCmd) {
private_data->MEMFreeToDefaultHeap(pClient);
return 0;
}
int success = 0;
private_data->FSInit();
private_data->FSInitCmdBlock(pCmd);
private_data->FSAddClientEx(pClient, 0, -1);
do {
char tempPath[FS_MOUNT_SOURCE_SIZE];
char mountPath[FS_MAX_MOUNTPATH_SIZE];
int status = private_data->FSGetMountSource(pClient, pCmd, 0, tempPath, -1);
if (status != 0) {
private_data->OSFatal("-13");
}
status = private_data->FSMount(pClient, pCmd, tempPath, mountPath, FS_MAX_MOUNTPATH_SIZE, -1);
if(status != 0) {
private_data->OSFatal("-12");
}
status = private_data->FSOpenFile(pClient, pCmd, filepath, "r", &iFd, -1);
if(status != 0) {
private_data->OSFatal("-11");
}
FSStat stat;
stat.size = 0;
void *pBuffer = NULL;
private_data->FSGetStatFile(pClient, pCmd, iFd, &stat, -1);
if (stat.size > 0) {
pBuffer = private_data->MEMAllocFromDefaultHeapEx((stat.size + 0x3F) & ~0x3F, 0x40);
} else {
private_data->OSFatal("-10");
}
unsigned int done = 0;
while(done < stat.size) {
int readBytes = private_data->FSReadFile(pClient, pCmd, pBuffer + done, 1, stat.size - done, iFd, 0, -1);
if(readBytes <= 0) {
break;
}
done += readBytes;
}
if(done != stat.size) {
private_data->MEMFreeToDefaultHeap(pBuffer);
} else {
*fileOut = (unsigned char*)pBuffer;
*sizeOut = stat.size;
success = 1;
}
private_data->FSCloseFile(pClient, pCmd, iFd, -1);
private_data->FSUnmount(pClient, pCmd, mountPath, -1);
} while(0);
private_data->FSDelClient(pClient);
private_data->MEMFreeToDefaultHeap(pClient);
private_data->MEMFreeToDefaultHeap(pCmd);
return success;
}
static void setup_patches(private_data_t *private_data) {
//! setup necessary syscalls and hooks for HBL
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl1 + (0x25 * 4)), (unsigned int)KernelCopyData);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl2 + (0x25 * 4)), (unsigned int)KernelCopyData);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl3 + (0x25 * 4)), (unsigned int)KernelCopyData);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl4 + (0x25 * 4)), (unsigned int)KernelCopyData);
kern_write((void*)(OS_SPECIFICS->addr_KernSyscallTbl5 + (0x25 * 4)), (unsigned int)KernelCopyData);
//! store physical address for later use
addrphys_LiWaitOneChunk = private_data->OSEffectiveToPhysical((void*)OS_SPECIFICS->addr_LiWaitOneChunk);
u32 addr_my_PrepareTitle_hook = ((u32)my_PrepareTitle_hook) | 0x48000003;
DCFlushRange(&addr_my_PrepareTitle_hook, 4);
//! create our copy syscall
SC0x25_KernelCopyData(OS_SPECIFICS->addr_PrepareTitle_hook, private_data->OSEffectiveToPhysical(&addr_my_PrepareTitle_hook), 4);
}
static unsigned int load_elf_image (private_data_t *private_data, unsigned char *elfstart) {
Elf32_Ehdr *ehdr;
Elf32_Phdr *phdrs;
unsigned char *image;
int i;
ehdr = (Elf32_Ehdr *) elfstart;
if(ehdr->e_phoff == 0 || ehdr->e_phnum == 0)
return 0;
if(ehdr->e_phentsize != sizeof(Elf32_Phdr))
return 0;
phdrs = (Elf32_Phdr*)(elfstart + ehdr->e_phoff);
for(i = 0; i < ehdr->e_phnum; i++) {
if(phdrs[i].p_type != PT_LOAD)
continue;
if(phdrs[i].p_filesz > phdrs[i].p_memsz)
continue;
if(!phdrs[i].p_filesz)
continue;
unsigned int p_paddr = phdrs[i].p_paddr;
image = (unsigned char *) (elfstart + phdrs[i].p_offset);
private_data->memcpy ((void *) p_paddr, image, phdrs[i].p_filesz);
DCFlushRange((void*)p_paddr, phdrs[i].p_filesz);
if(phdrs[i].p_flags & PF_X)
ICInvalidateRange ((void *) p_paddr, phdrs[i].p_memsz);
}
//! clear BSS
Elf32_Shdr *shdr = (Elf32_Shdr *) (elfstart + ehdr->e_shoff);
for(i = 0; i < ehdr->e_shnum; i++) {
const char *section_name = ((const char*)elfstart) + shdr[ehdr->e_shstrndx].sh_offset + shdr[i].sh_name;
if(section_name[0] == '.' && section_name[1] == 'b' && section_name[2] == 's' && section_name[3] == 's') {
private_data->memset((void*)shdr[i].sh_addr, 0, shdr[i].sh_size);
DCFlushRange((void*)shdr[i].sh_addr, shdr[i].sh_size);
} else if(section_name[0] == '.' && section_name[1] == 's' && section_name[2] == 'b' && section_name[3] == 's' && section_name[4] == 's') {
private_data->memset((void*)shdr[i].sh_addr, 0, shdr[i].sh_size);
DCFlushRange((void*)shdr[i].sh_addr, shdr[i].sh_size);
}
}
return ehdr->e_entry;
}
static void loadFunctionPointers(private_data_t * private_data) {
unsigned int coreinit_handle;
EXPORT_DECL(int, OSDynLoad_Acquire, const char* rpl, u32 *handle);
EXPORT_DECL(int, OSDynLoad_FindExport, u32 handle, int isdata, const char *symbol, void *address);
OSDynLoad_Acquire = (int (*)(const char*, u32 *))OS_SPECIFICS->addr_OSDynLoad_Acquire;
OSDynLoad_FindExport = (int (*)(u32, int, const char *, void *))OS_SPECIFICS->addr_OSDynLoad_FindExport;
OSDynLoad_Acquire("coreinit", &coreinit_handle);
unsigned int *functionPtr = 0;
OSDynLoad_FindExport(coreinit_handle, 1, "MEMAllocFromDefaultHeapEx", &functionPtr);
private_data->MEMAllocFromDefaultHeapEx = (void *(*)(int, int)) *functionPtr;
OSDynLoad_FindExport(coreinit_handle, 1, "MEMFreeToDefaultHeap", &functionPtr);
private_data->MEMFreeToDefaultHeap = (void (*)(void *)) *functionPtr;
OS_FIND_EXPORT(coreinit_handle, "OSGetTitleID", private_data->OSGetTitleID);
OS_FIND_EXPORT(coreinit_handle, "memcpy", private_data->memcpy);
OS_FIND_EXPORT(coreinit_handle, "memset", private_data->memset);
OS_FIND_EXPORT(coreinit_handle, "OSFatal", private_data->OSFatal);
OS_FIND_EXPORT(coreinit_handle, "DCFlushRange", DCFlushRange);
OS_FIND_EXPORT(coreinit_handle, "DCInvalidateRange", DCInvalidateRange);
OS_FIND_EXPORT(coreinit_handle, "ICInvalidateRange", ICInvalidateRange);
OS_FIND_EXPORT(coreinit_handle, "OSEffectiveToPhysical", private_data->OSEffectiveToPhysical);
OS_FIND_EXPORT(coreinit_handle, "exit", private_data->exit);
OS_FIND_EXPORT(coreinit_handle, "FSInit", private_data->FSInit);
OS_FIND_EXPORT(coreinit_handle, "FSAddClientEx", private_data->FSAddClientEx);
OS_FIND_EXPORT(coreinit_handle, "FSDelClient", private_data->FSDelClient);
OS_FIND_EXPORT(coreinit_handle, "FSInitCmdBlock", private_data->FSInitCmdBlock);
OS_FIND_EXPORT(coreinit_handle, "FSGetMountSource", private_data->FSGetMountSource);
OS_FIND_EXPORT(coreinit_handle, "FSMount", private_data->FSMount);
OS_FIND_EXPORT(coreinit_handle, "FSUnmount", private_data->FSUnmount);
OS_FIND_EXPORT(coreinit_handle, "FSOpenFile", private_data->FSOpenFile);
OS_FIND_EXPORT(coreinit_handle, "FSGetStatFile", private_data->FSGetStatFile);
OS_FIND_EXPORT(coreinit_handle, "FSReadFile", private_data->FSReadFile);
OS_FIND_EXPORT(coreinit_handle, "FSCloseFile", private_data->FSCloseFile);
unsigned int sysapp_handle;
OSDynLoad_Acquire("sysapp.rpl", &sysapp_handle);
OS_FIND_EXPORT(sysapp_handle, "SYSRelaunchTitle", private_data->SYSRelaunchTitle);
}
int _start(int argc, char **argv) {
private_data_t private_data;
if(MAIN_ENTRY_ADDR != 0xC001C0DE) {
loadFunctionPointers(&private_data);
while (1) {
if (ELF_DATA_ADDR != 0xDEADC0DE && ELF_DATA_SIZE > 0) {
//! copy data to safe area before processing it
unsigned char *pElfBuffer = (unsigned char *) private_data.MEMAllocFromDefaultHeapEx(ELF_DATA_SIZE, 4);
if (pElfBuffer) {
private_data.memcpy(pElfBuffer, (unsigned char *) ELF_DATA_ADDR, ELF_DATA_SIZE);
MAIN_ENTRY_ADDR = load_elf_image(&private_data, pElfBuffer);
private_data.MEMFreeToDefaultHeap(pElfBuffer);
}
ELF_DATA_ADDR = 0xDEADC0DE;
ELF_DATA_SIZE = 0;
}
if (MAIN_ENTRY_ADDR == 0xDEADC0DE || MAIN_ENTRY_ADDR == 0) {
//! setup necessary syscalls and hooks for HBL before launching it
setup_patches(&private_data);
if (HBL_CHANNEL) {
break;
} else {
unsigned char *pElfBuffer = NULL;
unsigned int uiElfSize = 0;
if (private_data.OSGetTitleID() == 0x000500101004A200L || // mii maker eur
private_data.OSGetTitleID() == 0x000500101004A100L || // mii maker usa
private_data.OSGetTitleID() == 0x000500101004A000L) { // mii maker jpn
LoadFileToMem(&private_data, CAFE_OS_SD_PATH WIIU_PATH "/apps/homebrew_launcher/homebrew_launcher.elf", &pElfBuffer, &uiElfSize);
}else{
break;
}
if (!pElfBuffer) {
private_data.OSFatal("Failed to load homebrew_launcher.elf");
} else {
MAIN_ENTRY_ADDR = load_elf_image(&private_data, pElfBuffer);
if (MAIN_ENTRY_ADDR == 0) {
private_data.OSFatal("Failed to load homebrew_launcher.elf");
} else {
private_data.MEMFreeToDefaultHeap(pElfBuffer);
}
}
}
} else {
int returnVal = ((int (*)(int, char **)) MAIN_ENTRY_ADDR)(argc, argv);
//! exit to miimaker and restart application on re-enter of another application
if (returnVal == (int) EXIT_RELAUNCH_ON_LOAD) {
break;
}
//! exit to homebrew launcher in all other cases
else {
MAIN_ENTRY_ADDR = 0xDEADC0DE;
private_data.SYSRelaunchTitle(0, 0);
private_data.exit(0);
break;
}
}
}
}
int ret = ( (int (*)(int, char **))(*(unsigned int*)OS_SPECIFICS->addr_OSTitle_main_entry) )(argc, argv);
//! if an application returns and was an RPX launch then launch HBL again
if(MAIN_ENTRY_ADDR == 0xC001C0DE) {
private_data.SYSRelaunchTitle(0, 0);
private_data.exit(0);
}
return ret;
}

60
sd_loader/src/fs_defs.h Normal file
View File

@ -0,0 +1,60 @@
#ifndef FS_DEFS_H
#define FS_DEFS_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* FS defines and types */
#define FS_MAX_LOCALPATH_SIZE 511
#define FS_MAX_MOUNTPATH_SIZE 128
#define FS_MAX_FULLPATH_SIZE (FS_MAX_LOCALPATH_SIZE + FS_MAX_MOUNTPATH_SIZE)
#define FS_MAX_ARGPATH_SIZE FS_MAX_FULLPATH_SIZE
#define FS_STATUS_OK 0
#define FS_RET_UNSUPPORTED_CMD 0x0400
#define FS_RET_NO_ERROR 0x0000
#define FS_RET_ALL_ERROR (unsigned int)(-1)
#define FS_STAT_FLAG_IS_DIRECTORY 0x80000000
/* max length of file/dir name */
#define FS_MAX_ENTNAME_SIZE 256
#define FS_SOURCETYPE_EXTERNAL 0
#define FS_SOURCETYPE_HFIO 1
#define FS_SOURCETYPE_HFIO 1
#define FS_MOUNT_SOURCE_SIZE 0x300
#define FS_CLIENT_SIZE 0x1700
#define FS_CMD_BLOCK_SIZE 0xA80
typedef struct {
uint32_t flag;
uint32_t permission;
uint32_t owner_id;
uint32_t group_id;
uint32_t size;
uint32_t alloc_size;
uint64_t quota_size;
uint32_t ent_id;
uint64_t ctime;
uint64_t mtime;
uint8_t attributes[48];
} __attribute__((packed)) FSStat;
typedef struct {
FSStat stat;
char name[FS_MAX_ENTNAME_SIZE];
} FSDirEntry;
#ifdef __cplusplus
}
#endif
#endif /* FS_DEFS_H */

View File

@ -0,0 +1,74 @@
#ifndef __KERNEL_DEFS_H_
#define __KERNEL_DEFS_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// original structure in the kernel that is originally 0x1270 long
typedef struct {
uint32_t version_cos_xml; // version tag from cos.xml
uint64_t os_version; // os_version from app.xml
uint64_t title_id; // title_id tag from app.xml
uint32_t app_type; // app_type tag from app.xml
uint32_t cmdFlags; // unknown tag as it is always 0 (might be cmdFlags from cos.xml but i am not sure)
char rpx_name[0x1000]; // rpx name from cos.xml
uint32_t unknown2; // 0x050B8304 in mii maker and system menu (looks a bit like permissions complex that got masked!?)
uint32_t unknown3[63]; // those were all zeros, but its probably connected with unknown2
uint32_t max_size; // max_size in cos.xml which defines the maximum amount of memory reserved for the app
uint32_t avail_size; // avail_size or codegen_size in cos.xml (seems to mostly be 0?)
uint32_t codegen_size; // codegen_size or avail_size in cos.xml (seems to mostly be 0?)
uint32_t codegen_core; // codegen_core in cos.xml (seems to mostly be 1?)
uint32_t max_codesize; // max_codesize in cos.xml
uint32_t overlay_arena; // overlay_arena in cos.xml
uint32_t unknown4[59]; // all zeros it seems
uint32_t default_stack0_size; // not sure because always 0 but very likely
uint32_t default_stack1_size; // not sure because always 0 but very likely
uint32_t default_stack2_size; // not sure because always 0 but very likely
uint32_t default_redzone0_size; // not sure because always 0 but very likely
uint32_t default_redzone1_size; // not sure because always 0 but very likely
uint32_t default_redzone2_size; // not sure because always 0 but very likely
uint32_t exception_stack0_size; // from cos.xml, 0x1000 on mii maker
uint32_t exception_stack1_size; // from cos.xml, 0x1000 on mii maker
uint32_t exception_stack2_size; // from cos.xml, 0x1000 on mii maker
uint32_t sdk_version; // from app.xml, 20909 (0x51AD) on mii maker
uint32_t title_version; // from app.xml, 0x32 on mii maker
/*
// ---------------------------------------------------------------------------------------------------------------------------------------------
// the next part might be changing from title to title?! I don't think its important but nice to know maybe....
// ---------------------------------------------------------------------------------------------------------------------------------------------
char mlc[4]; // string "mlc" on mii maker and sysmenu
uint32_t unknown5[7]; // all zeros on mii maker and sysmenu
uint32_t unknown6_one; // 0x01 on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
char ACP[4]; // string "ACP" on mii maker and sysmenu
uint32_t unknown7[15]; // all zeros on mii maker and sysmenu
uint32_t unknown8_5; // 0x05 on mii maker and sysmenu
uint32_t unknown9_zero; // 0x00 on mii maker and sysmenu
uint32_t unknown10_ptr; // 0xFF23DD0C pointer on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
char UVD[4]; // string "UVD" on mii maker and sysmenu
uint32_t unknown11[15]; // all zeros on mii maker and sysmenu
uint32_t unknown12_5; // 0x05 on mii maker and sysmenu
uint32_t unknown13_zero; // 0x00 on mii maker and sysmenu
uint32_t unknown14_ptr; // 0xFF23EFC8 pointer on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
char SND[4]; // string "SND" on mii maker and sysmenu
uint32_t unknown15[15]; // all zeros on mii maker and sysmenu
uint32_t unknown16_5; // 0x05 on mii maker and sysmenu
uint32_t unknown17_zero; // 0x00 on mii maker and sysmenu
uint32_t unknown18_ptr; // 0xFF23F014 pointer on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
uint32_t unknown19; // 0x02 on miimaker, 0x0F on system menu
*/
// after that only zeros follow
} __attribute__((packed)) CosAppXmlInfo;
#ifdef __cplusplus
}
#endif
#endif // __KERNEL_DEFS_H_

View File

@ -0,0 +1,69 @@
# This stuff may need a change in different kernel versions
# This is only needed when launched directly through browser and not SD card.
.section ".kernel_code"
.globl SaveAndResetDataBATs_And_SRs_hook
SaveAndResetDataBATs_And_SRs_hook:
# setup CTR to the position we need to return to
mflr r5
mtctr r5
# set link register to its original value
mtlr r7
# setup us a nice DBAT for our code data with same region as our code
mfspr r5, 560
mtspr 570, r5
mfspr r5, 561
mtspr 571, r5
# restore the original kernel instructions that we replaced
lwz r5, 0x34(r3)
lwz r6, 0x38(r3)
lwz r7, 0x3C(r3)
lwz r8, 0x40(r3)
lwz r9, 0x44(r3)
lwz r10, 0x48(r3)
lwz r11, 0x4C(r3)
lwz r3, 0x50(r3)
isync
mtsr 7, r5
# jump back to the position in kernel after our patch (from LR)
bctr
.extern my_PrepareTitle
.globl my_PrepareTitle_hook
my_PrepareTitle_hook:
# store all registers on stack to avoid issues with the call to C functions
stwu r1, -0x90(r1)
# registers for our own usage
# just store everything
stmw r3, 0x10(r1)
# save the LR from where we came
mflr r31
# the cos.xml/app.xml structure is at the location 0x68 of r11
# there are actually many places that can be hooked for it
# e.g. 0xFFF16130 and r27 points to this structure
addi r3, r11, 0x68
bl my_PrepareTitle
# setup LR to jump back to kernel code
mtlr r31
# restore all original values of registers from stack
lmw r3, 0x10(r1)
# restore the stack
addi r1, r1, 0x90
# restore original instruction that we replaced in the kernel
clrlwi r7, r12, 0
# jump back
blr
.globl SC0x25_KernelCopyData
SC0x25_KernelCopyData:
li r0, 0x2500
sc
blr

23
sd_loader/src/link.ld Normal file
View File

@ -0,0 +1,23 @@
OUTPUT(sd_loader.elf);
ENTRY(_start);
SECTIONS {
. = 0x00800000;
.text : {
*(.kernel_code*);
*(.text*);
/* Tell linker to not garbage collect this section as it is not referenced anywhere */
KEEP(*(.kernel_code*));
}
.data : {
*(.rodata*);
*(.data*);
*(.bss*);
}
/DISCARD/ : {
*(*);
}
}
ASSERT((SIZEOF(.text) + SIZEOF(.data)) < 0x1300, "Memory overlapping with main elf.");

View File

@ -0,0 +1,36 @@
#ifndef __LOADER_DEFS_H_
#define __LOADER_DEFS_H_
#ifdef __cplusplus
extern "C" {
#endif
// struct holding the globals of the loader (there are actually more but we don't need others)
typedef struct _loader_globals_t {
int sgIsLoadingBuffer;
int sgFileType;
int sgProcId;
int sgGotBytes;
int sgFileOffset;
int sgBufferNumber;
int sgBounceError;
char sgLoadName[0x1000];
} __attribute__((packed)) loader_globals_t;
typedef struct _loader_globals_550_t {
int sgFinishedLoadingBuffer;
int sgFileType;
int sgProcId;
int sgGotBytes;
int sgTotalBytes;
int sgFileOffset;
int sgBufferNumber;
int sgBounceError;
char sgLoadName[0x1000];
} __attribute__((packed)) loader_globals_550_t;
#ifdef __cplusplus
}
#endif
#endif // __LOADER_DEFS_H_

38
sd_loader/src/os_defs.h Normal file
View File

@ -0,0 +1,38 @@
#ifndef __OS_DEFS_H_
#define __OS_DEFS_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _OsSpecifics {
unsigned int addr_OSDynLoad_Acquire;
unsigned int addr_OSDynLoad_FindExport;
unsigned int addr_OSTitle_main_entry;
unsigned int addr_KernSyscallTbl1;
unsigned int addr_KernSyscallTbl2;
unsigned int addr_KernSyscallTbl3;
unsigned int addr_KernSyscallTbl4;
unsigned int addr_KernSyscallTbl5;
int (*LiWaitIopComplete)(int, int *);
int (*LiWaitIopCompleteWithInterrupts)(int, int *);
unsigned int addr_LiWaitOneChunk;
unsigned int addr_PrepareTitle_hook;
unsigned int addr_sgIsLoadingBuffer;
unsigned int addr_gDynloadInitialized;
unsigned int orig_LiWaitOneChunkInstr;
} OsSpecifics;
typedef struct _s_mem_area {
unsigned int address;
unsigned int size;
struct _s_mem_area* next;
} s_mem_area;
#ifdef __cplusplus
}
#endif
#endif // __OS_DEFS_H_

215
sd_loader/src/os_types.h Normal file
View File

@ -0,0 +1,215 @@
#ifndef _OS_TYPES_H_
#define _OS_TYPES_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
/*+----------------------------------------------------------------------------------------------+*/
typedef uint8_t u8; ///< 8bit unsigned integer
typedef uint16_t u16; ///< 16bit unsigned integer
typedef uint32_t u32; ///< 32bit unsigned integer
typedef uint64_t u64; ///< 64bit unsigned integer
/*+----------------------------------------------------------------------------------------------+*/
typedef int8_t s8; ///< 8bit signed integer
typedef int16_t s16; ///< 16bit signed integer
typedef int32_t s32; ///< 32bit signed integer
typedef int64_t s64; ///< 64bit signed integer
/*+----------------------------------------------------------------------------------------------+*/
typedef volatile u8 vu8; ///< 8bit unsigned volatile integer
typedef volatile u16 vu16; ///< 16bit unsigned volatile integer
typedef volatile u32 vu32; ///< 32bit unsigned volatile integer
typedef volatile u64 vu64; ///< 64bit unsigned volatile integer
/*+----------------------------------------------------------------------------------------------+*/
typedef volatile s8 vs8; ///< 8bit signed volatile integer
typedef volatile s16 vs16; ///< 16bit signed volatile integer
typedef volatile s32 vs32; ///< 32bit signed volatile integer
typedef volatile s64 vs64; ///< 64bit signed volatile integer
/*+----------------------------------------------------------------------------------------------+*/
// fixed point math typedefs
typedef s16 sfp16; ///< signed 8:8 fixed point
typedef s32 sfp32; ///< signed 20:8 fixed point
typedef u16 ufp16; ///< unsigned 8:8 fixed point
typedef u32 ufp32; ///< unsigned 24:8 fixed point
/*+----------------------------------------------------------------------------------------------+*/
typedef float f32;
typedef double f64;
/*+----------------------------------------------------------------------------------------------+*/
typedef volatile float vf32;
typedef volatile double vf64;
/*+----------------------------------------------------------------------------------------------+*/
#define OS_MESSAGE_NOBLOCK 0
#define OS_MESSAGE_BLOCK 1
#define OS_EXCEPTION_DSI 2
#define OS_EXCEPTION_ISI 3
#define OS_EXCEPTION_PROGRAM 6
#define OS_EXCEPTION_MODE_THREAD 1
#define OS_EXCEPTION_MODE_GLOBAL_ALL_CORES 4
#define OS_THREAD_ATTR_AFFINITY_NONE 0x0007u // affinity to run on every core
#define OS_THREAD_ATTR_AFFINITY_CORE0 0x0001u // run only on core0
#define OS_THREAD_ATTR_AFFINITY_CORE1 0x0002u // run only on core1
#define OS_THREAD_ATTR_AFFINITY_CORE2 0x0004u // run only on core2
#define OS_THREAD_ATTR_DETACH 0x0008u // detached
#define OS_THREAD_ATTR_PINNED_AFFINITY 0x0010u // pinned (affinitized) to a single core
#define OS_THREAD_ATTR_CHECK_STACK_USE 0x0040u // check for stack usage
#define OS_THREAD_ATTR_NAME_SENT 0x0080u // debugger has seen the name
#define OS_THREAD_ATTR_LAST (OS_THREAD_ATTR_DETACH | OS_THREAD_ATTR_PINNED_AFFINITY | OS_THREAD_ATTR_AFFINITY_NONE)
typedef struct OSThread_ OSThread;
typedef struct OSThreadLink_ {
OSThread *next;
OSThread *prev;
} OSThreadLink;
typedef struct OSThreadQueue_ {
OSThread *head;
OSThread *tail;
void *parentStruct;
u32 reserved;
} OSThreadQueue;
typedef struct OSMessage_ {
u32 message;
u32 data0;
u32 data1;
u32 data2;
} OSMessage;
typedef struct OSMessageQueue_ {
u32 tag;
char *name;
u32 reserved;
OSThreadQueue sendQueue;
OSThreadQueue recvQueue;
OSMessage *messages;
int msgCount;
int firstIndex;
int usedCount;
} OSMessageQueue;
typedef struct OSContext_ {
char tag[8];
u32 gpr[32];
u32 cr;
u32 lr;
u32 ctr;
u32 xer;
u32 srr0;
u32 srr1;
u32 ex0;
u32 ex1;
u32 exception_type;
u32 reserved;
double fpscr;
double fpr[32];
u16 spinLockCount;
u16 state;
u32 gqr[8];
u32 pir;
double psf[32];
u64 coretime[3];
u64 starttime;
u32 error;
u32 attributes;
u32 pmc1;
u32 pmc2;
u32 pmc3;
u32 pmc4;
u32 mmcr0;
u32 mmcr1;
} OSContext;
typedef enum OSExceptionType {
OS_EXCEPTION_TYPE_SYSTEM_RESET = 0,
OS_EXCEPTION_TYPE_MACHINE_CHECK = 1,
OS_EXCEPTION_TYPE_DSI = 2,
OS_EXCEPTION_TYPE_ISI = 3,
OS_EXCEPTION_TYPE_EXTERNAL_INTERRUPT = 4,
OS_EXCEPTION_TYPE_ALIGNMENT = 5,
OS_EXCEPTION_TYPE_PROGRAM = 6,
OS_EXCEPTION_TYPE_FLOATING_POINT = 7,
OS_EXCEPTION_TYPE_DECREMENTER = 8,
OS_EXCEPTION_TYPE_SYSTEM_CALL = 9,
OS_EXCEPTION_TYPE_TRACE = 10,
OS_EXCEPTION_TYPE_PERFORMANCE_MONITOR = 11,
OS_EXCEPTION_TYPE_BREAKPOINT = 12,
OS_EXCEPTION_TYPE_SYSTEM_INTERRUPT = 13,
OS_EXCEPTION_TYPE_ICI = 14,
} OSExceptionType;
typedef int (*ThreadFunc)(int argc, void *argv);
struct OSThread_ {
OSContext context;
u32 txtTag;
u8 state;
u8 attr;
short threadId;
int suspend;
int priority;
char _[0x394 - 0x330 - sizeof(OSThreadLink)];
OSThreadLink linkActive;
void *stackBase;
void *stackEnd;
ThreadFunc entryPoint;
char _3A0[0x6A0 - 0x3A0];
};
typedef struct _OSCalendarTime {
int sec;
int min;
int hour;
int mday;
int mon;
int year;
int wday;
int yday;
int msec;
int usec;
} OSCalendarTime;
typedef struct MCPTitleListType {
u64 titleId;
u8 unknwn[4];
s8 path[56];
u32 appType;
u8 unknwn1[0x54 - 0x48];
u8 device;
u8 unknwn2;
s8 indexedDevice[10];
u8 unk0x60;
} MCPTitleListType;
#ifdef __cplusplus
}
#endif
#endif

198
source/hbl_install.cpp Normal file
View File

@ -0,0 +1,198 @@
#include <stdint.h>
#include <string.h>
#include <malloc.h>
#include <coreinit/dynload.h>
#include <coreinit/debug.h>
#include <coreinit/memorymap.h>
#include <coreinit/cache.h>
#include "../sd_loader/src/common.h"
#include "../sd_loader/src/elf_abi.h"
#include "sd_loader_elf.h"
#define KERN_SYSCALL_TBL_1 0xFFE84C70 // unknown
#define KERN_SYSCALL_TBL_2 0xFFE85070 // works with games
#define KERN_SYSCALL_TBL_3 0xFFE85470 // works with loader
#define KERN_SYSCALL_TBL_4 0xFFEAAA60 // works with home menu
#define KERN_SYSCALL_TBL_5 0xFFEAAE60 // works with browser (previously KERN_SYSCALL_TBL)
#define address_LiWaitIopComplete 0x01010180
#define address_LiWaitIopCompleteWithInterrupts 0x0101006C
#define address_LiWaitOneChunk 0x0100080C
#define address_PrepareTitle_hook 0xFFF184E4
#define address_sgIsLoadingBuffer 0xEFE19E80
#define address_gDynloadInitialized 0xEFE13DBC
#define ADDRESS_OSTitle_main_entry_ptr 0x1005E040
#define ADDRESS_main_entry_hook 0x0101c56c
/* assembly functions */
extern "C" void Syscall_0x36(void);
extern "C" void KernelPatches(void);
extern "C" void SCKernelCopyData(unsigned int addr, unsigned int src, unsigned int len);
extern "C" void SC_0x25_KernelCopyData(unsigned int addr, unsigned int src, unsigned int len);
void __attribute__ ((noinline)) kern_write(void *addr, uint32_t value);
static void InstallPatches();
static unsigned int load_elf_image(const uint8_t *elfstart) {
Elf32_Ehdr *ehdr;
Elf32_Phdr *phdrs;
unsigned char *image;
int i;
ehdr = (Elf32_Ehdr *) elfstart;
if (ehdr->e_phoff == 0 || ehdr->e_phnum == 0)
return 0;
if (ehdr->e_phentsize != sizeof(Elf32_Phdr))
return 0;
phdrs = (Elf32_Phdr *) (elfstart + ehdr->e_phoff);
for (i = 0; i < ehdr->e_phnum; i++) {
if (phdrs[i].p_type != PT_LOAD)
continue;
if (phdrs[i].p_filesz > phdrs[i].p_memsz)
continue;
if (!phdrs[i].p_filesz)
continue;
unsigned int p_paddr = phdrs[i].p_paddr;
image = (unsigned char *) (elfstart + phdrs[i].p_offset);
memcpy((void *) p_paddr, image, phdrs[i].p_filesz);
DCFlushRange((void *) p_paddr, phdrs[i].p_filesz);
if (phdrs[i].p_flags & PF_X)
ICInvalidateRange((void *) p_paddr, phdrs[i].p_memsz);
}
//! clear BSS
Elf32_Shdr *shdr = (Elf32_Shdr *) (elfstart + ehdr->e_shoff);
for (i = 0; i < ehdr->e_shnum; i++) {
const char *section_name = ((const char *) elfstart) + shdr[ehdr->e_shstrndx].sh_offset + shdr[i].sh_name;
if (section_name[0] == '.' && section_name[1] == 'b' && section_name[2] == 's' && section_name[3] == 's') {
memset((void *) shdr[i].sh_addr, 0, shdr[i].sh_size);
DCFlushRange((void *) shdr[i].sh_addr, shdr[i].sh_size);
} else if (section_name[0] == '.' && section_name[1] == 's' && section_name[2] == 'b' && section_name[3] == 's' && section_name[4] == 's') {
memset((void *) shdr[i].sh_addr, 0, shdr[i].sh_size);
DCFlushRange((void *) shdr[i].sh_addr, shdr[i].sh_size);
}
}
return ehdr->e_entry;
}
void KernelWriteU32(uint32_t addr, uint32_t value) {
ICInvalidateRange(&value, 4);
DCFlushRange(&value, 4);
uint32_t dst = (uint32_t) OSEffectiveToPhysical((uint32_t) addr);
uint32_t src = (uint32_t) OSEffectiveToPhysical((uint32_t) &value);
SC_0x25_KernelCopyData(dst, src, 4);
DCFlushRange((void *) addr, 4);
ICInvalidateRange((void *) addr, 4);
}
void InstallHBL() {
kern_write((void *) (KERN_SYSCALL_TBL_1 + (0x25 * 4)), (unsigned int) SCKernelCopyData);
kern_write((void *) (KERN_SYSCALL_TBL_2 + (0x25 * 4)), (unsigned int) SCKernelCopyData);
kern_write((void *) (KERN_SYSCALL_TBL_3 + (0x25 * 4)), (unsigned int) SCKernelCopyData);
kern_write((void *) (KERN_SYSCALL_TBL_4 + (0x25 * 4)), (unsigned int) SCKernelCopyData);
kern_write((void *) (KERN_SYSCALL_TBL_5 + (0x25 * 4)), (unsigned int) SCKernelCopyData);
kern_write((void *) (KERN_SYSCALL_TBL_1 + (0x36 * 4)), (unsigned int) KernelPatches);
kern_write((void *) (KERN_SYSCALL_TBL_2 + (0x36 * 4)), (unsigned int) KernelPatches);
kern_write((void *) (KERN_SYSCALL_TBL_3 + (0x36 * 4)), (unsigned int) KernelPatches);
kern_write((void *) (KERN_SYSCALL_TBL_4 + (0x36 * 4)), (unsigned int) KernelPatches);
kern_write((void *) (KERN_SYSCALL_TBL_5 + (0x36 * 4)), (unsigned int) KernelPatches);
Syscall_0x36();
InstallPatches();
unsigned char *pElfBuffer = (unsigned char *) sd_loader_elf; // use this address as temporary to load the elf
unsigned int mainEntryPoint = load_elf_image(pElfBuffer);
if (mainEntryPoint == 0) {
OSFatal("failed to load elf");
}
//! Install our entry point hook
unsigned int repl_addr = ADDRESS_main_entry_hook;
unsigned int jump_addr = mainEntryPoint & 0x03fffffc;
unsigned int bufferU32 = 0x48000003 | jump_addr;
KernelWriteU32(repl_addr, bufferU32);
}
/* ****************************************************************** */
/* INSTALL PATCHES */
/* All OS specific stuff is done here */
/* ****************************************************************** */
static void InstallPatches() {
OsSpecifics osSpecificFunctions;
memset(&osSpecificFunctions, 0, sizeof(OsSpecifics));
unsigned int bufferU32;
/* Pre-setup a few options to defined values */
bufferU32 = 550;
memcpy((void*)&OS_FIRMWARE, &bufferU32, sizeof(bufferU32));
bufferU32 = 0xDEADC0DE;
memcpy((void*)&MAIN_ENTRY_ADDR, &bufferU32, sizeof(bufferU32));
memcpy((void*)&ELF_DATA_ADDR, &bufferU32, sizeof(bufferU32));
bufferU32 = 0;
memcpy((void*)&ELF_DATA_SIZE, &bufferU32, sizeof(bufferU32));
memcpy((void*)&HBL_CHANNEL, &bufferU32, sizeof(bufferU32));
osSpecificFunctions.addr_OSDynLoad_Acquire = (unsigned int)OSDynLoad_Acquire;
osSpecificFunctions.addr_OSDynLoad_FindExport = (unsigned int)OSDynLoad_FindExport;
osSpecificFunctions.addr_KernSyscallTbl1 = KERN_SYSCALL_TBL_1;
osSpecificFunctions.addr_KernSyscallTbl2 = KERN_SYSCALL_TBL_2;
osSpecificFunctions.addr_KernSyscallTbl3 = KERN_SYSCALL_TBL_3;
osSpecificFunctions.addr_KernSyscallTbl4 = KERN_SYSCALL_TBL_4;
osSpecificFunctions.addr_KernSyscallTbl5 = KERN_SYSCALL_TBL_5;
osSpecificFunctions.LiWaitIopComplete = (int (*)(int, int *)) address_LiWaitIopComplete;
osSpecificFunctions.LiWaitIopCompleteWithInterrupts = (int (*)(int, int *)) address_LiWaitIopCompleteWithInterrupts;
osSpecificFunctions.addr_LiWaitOneChunk = address_LiWaitOneChunk;
osSpecificFunctions.addr_PrepareTitle_hook = address_PrepareTitle_hook;
osSpecificFunctions.addr_sgIsLoadingBuffer = address_sgIsLoadingBuffer;
osSpecificFunctions.addr_gDynloadInitialized = address_gDynloadInitialized;
osSpecificFunctions.orig_LiWaitOneChunkInstr = *(unsigned int*)address_LiWaitOneChunk;
//! pointer to main entry point of a title
osSpecificFunctions.addr_OSTitle_main_entry = ADDRESS_OSTitle_main_entry_ptr;
memcpy((void*)OS_SPECIFICS, &osSpecificFunctions, sizeof(OsSpecifics));
}
/* Write a 32-bit word with kernel permissions */
void __attribute__ ((noinline)) kern_write(void *addr, uint32_t value) {
asm volatile (
"li 3,1\n"
"li 4,0\n"
"mr 5,%1\n"
"li 6,0\n"
"li 7,0\n"
"lis 8,1\n"
"mr 9,%0\n"
"mr %1,1\n"
"li 0,0x3500\n"
"sc\n"
"nop\n"
"mr 1,%1\n"
:
: "r"(addr), "r"(value)
: "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12"
);
}

3
source/hbl_install.h Normal file
View File

@ -0,0 +1,3 @@
#pragma once
void InstallHBL();

74
source/kernel_defs.h Normal file
View File

@ -0,0 +1,74 @@
#ifndef __KERNEL_DEFS_H_
#define __KERNEL_DEFS_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// original structure in the kernel that is originally 0x1270 long
typedef struct {
uint32_t version_cos_xml; // version tag from cos.xml
uint64_t os_version; // os_version from app.xml
uint64_t title_id; // title_id tag from app.xml
uint32_t app_type; // app_type tag from app.xml
uint32_t cmdFlags; // unknown tag as it is always 0 (might be cmdFlags from cos.xml but i am not sure)
char rpx_name[0x1000]; // rpx name from cos.xml
uint32_t unknown2; // 0x050B8304 in mii maker and system menu (looks a bit like permissions complex that got masked!?)
uint32_t unknown3[63]; // those were all zeros, but its probably connected with unknown2
uint32_t max_size; // max_size in cos.xml which defines the maximum amount of memory reserved for the app
uint32_t avail_size; // avail_size or codegen_size in cos.xml (seems to mostly be 0?)
uint32_t codegen_size; // codegen_size or avail_size in cos.xml (seems to mostly be 0?)
uint32_t codegen_core; // codegen_core in cos.xml (seems to mostly be 1?)
uint32_t max_codesize; // max_codesize in cos.xml
uint32_t overlay_arena; // overlay_arena in cos.xml
uint32_t unknown4[59]; // all zeros it seems
uint32_t default_stack0_size; // not sure because always 0 but very likely
uint32_t default_stack1_size; // not sure because always 0 but very likely
uint32_t default_stack2_size; // not sure because always 0 but very likely
uint32_t default_redzone0_size; // not sure because always 0 but very likely
uint32_t default_redzone1_size; // not sure because always 0 but very likely
uint32_t default_redzone2_size; // not sure because always 0 but very likely
uint32_t exception_stack0_size; // from cos.xml, 0x1000 on mii maker
uint32_t exception_stack1_size; // from cos.xml, 0x1000 on mii maker
uint32_t exception_stack2_size; // from cos.xml, 0x1000 on mii maker
uint32_t sdk_version; // from app.xml, 20909 (0x51AD) on mii maker
uint32_t title_version; // from app.xml, 0x32 on mii maker
/*
// ---------------------------------------------------------------------------------------------------------------------------------------------
// the next part might be changing from title to title?! I don't think its important but nice to know maybe....
// ---------------------------------------------------------------------------------------------------------------------------------------------
char mlc[4]; // string "mlc" on mii maker and sysmenu
uint32_t unknown5[7]; // all zeros on mii maker and sysmenu
uint32_t unknown6_one; // 0x01 on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
char ACP[4]; // string "ACP" on mii maker and sysmenu
uint32_t unknown7[15]; // all zeros on mii maker and sysmenu
uint32_t unknown8_5; // 0x05 on mii maker and sysmenu
uint32_t unknown9_zero; // 0x00 on mii maker and sysmenu
uint32_t unknown10_ptr; // 0xFF23DD0C pointer on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
char UVD[4]; // string "UVD" on mii maker and sysmenu
uint32_t unknown11[15]; // all zeros on mii maker and sysmenu
uint32_t unknown12_5; // 0x05 on mii maker and sysmenu
uint32_t unknown13_zero; // 0x00 on mii maker and sysmenu
uint32_t unknown14_ptr; // 0xFF23EFC8 pointer on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
char SND[4]; // string "SND" on mii maker and sysmenu
uint32_t unknown15[15]; // all zeros on mii maker and sysmenu
uint32_t unknown16_5; // 0x05 on mii maker and sysmenu
uint32_t unknown17_zero; // 0x00 on mii maker and sysmenu
uint32_t unknown18_ptr; // 0xFF23F014 pointer on mii maker and sysmenu
// ---------------------------------------------------------------------------------------------------------------------------------------------
uint32_t unknown19; // 0x02 on miimaker, 0x0F on system menu
*/
// after that only zeros follow
} __attribute__((packed)) CosAppXmlInfo;
#ifdef __cplusplus
}
#endif
#endif // __KERNEL_DEFS_H_

211
source/kernel_patches.s Normal file
View File

@ -0,0 +1,211 @@
#define BAT_SETUP_HOOK_ADDR 0xFFF1D624
# not all of those NOP address are required for every firmware
# mainly these should stop the kernel from removing our IBAT4 and DBAT5
#define BAT_SET_NOP_ADDR_1 0xFFF06B6C
#define BAT_SET_NOP_ADDR_2 0xFFF06BF8
#define BAT_SET_NOP_ADDR_3 0xFFF003C8
#define BAT_SET_NOP_ADDR_4 0xFFF003CC
#define BAT_SET_NOP_ADDR_5 0xFFF1D70C
#define BAT_SET_NOP_ADDR_6 0xFFF1D728
#define BAT_SET_NOP_ADDR_7 0xFFF1D82C
#define BAT_SET_NOP_ADDR_8 0xFFEE11C4
#define BAT_SET_NOP_ADDR_9 0xFFEE11C8
#define BAT_SETUP_HOOK_ENTRY 0x00800000
#define BAT4U_VAL 0x008000FF
#define BAT4L_VAL 0x30800012
#define SET_R4_TO_ADDR(addr) \
lis r3, addr@h ; \
ori r3, r3, addr@l ; \
stw r4, 0(r3) ; \
dcbf 0, r3 ; \
icbi 0, r3 ;
.globl Syscall_0x36
Syscall_0x36:
li r0, 0x3600
sc
blr
.global SCKernelCopyData
SCKernelCopyData:
// Disable data address translation
mfmsr %r6
li %r7, 0x10
andc %r6, %r6, %r7
mtmsr %r6
// Copy data
addi %r3, %r3, -1
addi %r4, %r4, -1
mtctr %r5
SCKernelCopyData_loop:
lbzu %r5, 1(%r4)
stbu %r5, 1(%r3)
bdnz SCKernelCopyData_loop
// Enable data address translation
ori %r6, %r6, 0x10
mtmsr %r6
blr
.global SC_0x25_KernelCopyData
SC_0x25_KernelCopyData:
li %r0, 0x2500
sc
blr
.globl KernelPatches
KernelPatches:
# store the old DBAT0
mfdbatu r5, 0
mfdbatl r6, 0
# memory barrier
eieio
isync
# setup DBAT0 for access to kernel code memory
lis r3, 0xFFF0
ori r3, r3, 0x0002
mtdbatu 0, r3
lis r3, 0xFFF0
ori r3, r3, 0x0032
mtdbatl 0, r3
# memory barrier
eieio
isync
# SaveAndResetDataBATs_And_SRs hook setup, but could be any BAT function though
# just chosen because its simple
lis r3, BAT_SETUP_HOOK_ADDR@h
ori r3, r3, BAT_SETUP_HOOK_ADDR@l
# make the kernel setup our section in IBAT4 and
# jump to our function to restore the replaced instructions
lis r4, 0x3ce0 # lis r7, BAT4L_VAL@h
ori r4, r4, BAT4L_VAL@h
stw r4, 0x00(r3)
lis r4, 0x60e7 # ori r7, r7, BAT4L_VAL@l
ori r4, r4, BAT4L_VAL@l
stw r4, 0x04(r3)
lis r4, 0x7cf1 # mtspr 561, r7
ori r4, r4, 0x8ba6
stw r4, 0x08(r3)
lis r4, 0x3ce0 # lis r7, BAT4U_VAL@h
ori r4, r4, BAT4U_VAL@h
stw r4, 0x0C(r3)
lis r4, 0x60e7 # ori r7, r7, BAT4U_VAL@l
ori r4, r4, BAT4U_VAL@l
stw r4, 0x10(r3)
lis r4, 0x7cf0 # mtspr 560, r7
ori r4, r4, 0x8ba6
stw r4, 0x14(r3)
lis r4, 0x7c00 # eieio
ori r4, r4, 0x06ac
stw r4, 0x18(r3)
lis r4, 0x4c00 # isync
ori r4, r4, 0x012c
stw r4, 0x1C(r3)
lis r4, 0x7ce8 # mflr r7
ori r4, r4, 0x02a6
stw r4, 0x20(r3)
lis r4, (BAT_SETUP_HOOK_ENTRY | 0x48000003)@h # bla BAT_SETUP_HOOK_ENTRY
ori r4, r4, (BAT_SETUP_HOOK_ENTRY | 0x48000003)@l
stw r4, 0x24(r3)
# flush and invalidate the replaced instructions
lis r3, (BAT_SETUP_HOOK_ADDR & ~31)@h
ori r3, r3, (BAT_SETUP_HOOK_ADDR & ~31)@l
dcbf 0, r3
icbi 0, r3
lis r3, ((BAT_SETUP_HOOK_ADDR + 0x20) & ~31)@h
ori r3, r3, ((BAT_SETUP_HOOK_ADDR + 0x20) & ~31)@l
dcbf 0, r3
icbi 0, r3
sync
# setup IBAT4 for core 1 at this position (not really required but wont hurt)
# IBATL 4
lis r3, BAT4L_VAL@h
ori r3, r3, BAT4L_VAL@l
mtspr 561, r3
# IBATU 4
lis r3, BAT4U_VAL@h
ori r3, r3, BAT4U_VAL@l
mtspr 560, r3
# memory barrier
eieio
isync
# write "nop" to some positions
lis r4, 0x6000
# nop on IBATU 4 and DBAT 5 set/reset
#ifdef BAT_SET_NOP_ADDR_1
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_1)
#endif
#ifdef BAT_SET_NOP_ADDR_2
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_2)
#endif
#ifdef BAT_SET_NOP_ADDR_3
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_3)
#endif
#ifdef BAT_SET_NOP_ADDR_4
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_4)
#endif
#ifdef BAT_SET_NOP_ADDR_5
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_5)
#endif
#ifdef BAT_SET_NOP_ADDR_6
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_6)
#endif
#ifdef BAT_SET_NOP_ADDR_7
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_7)
#endif
#if (defined(BAT_SET_NOP_ADDR_8) && defined(BAT_SET_NOP_ADDR_9))
# memory barrier
eieio
isync
# setup DBAT0 for access to kernel code memory
lis r3, 0xFFEE
ori r3, r3, 0x0002
mtdbatu 0, r3
lis r3, 0xFFEE
ori r3, r3, 0x0032
mtdbatl 0, r3
# memory barrier
eieio
isync
# write "nop" to some positions
lis r4, 0x6000
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_8)
SET_R4_TO_ADDR(BAT_SET_NOP_ADDR_9)
#endif
# memory barrier
eieio
isync
# restore DBAT 0 and return from interrupt
mtdbatu 0, r5
mtdbatl 0, r6
# memory barrier
eieio
isync
blr

23
source/logger.h Normal file
View File

@ -0,0 +1,23 @@
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <cstring>
#include <whb/log.h>
#define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__)
#define DEBUG_FUNCTION_LINE(FMT, ARGS...)do { \
WHBLogPrintf("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0);
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...)do { \
WHBLogWritef("[%23s]%30s@L%04d: " FMT "",__FILENAME__,__FUNCTION__, __LINE__, ## ARGS); \
} while (0);
#ifdef __cplusplus
}
#endif

View File

@ -1,69 +1,128 @@
#include <string.h>
#include <coreinit/title.h>
#include <sysapp/title.h>
#include <stdint.h>
#include <malloc.h>
#include <cstring>
#include <proc_ui/procui.h>
#include <sysapp/launch.h>
#include <coreinit/ios.h>
#include <coreinit/cache.h>
#include "../homebrew_launcher_installer/src/elf_abi.h"
#include "payload_elf.h"
#include <sysapp/title.h>
#include <coreinit/mcp.h>
#include <coreinit/debug.h>
#include <nn/acp/title.h>
#include <nn/sl/common.h>
#include <nn/sl/FileStream.h>
#include <nn/sl/LaunchInfoDatabase.h>
#include <nn/ccr/sys_caffeine.h>
static unsigned int load_elf_image (const uint8_t* elfstart) {
Elf32_Ehdr *ehdr;
Elf32_Phdr *phdrs;
unsigned char *image;
int i;
#include <nn/act/client_cpp.h>
#include "hbl_install.h"
#include "utils.h"
#include "logger.h"
ehdr = (Elf32_Ehdr *) elfstart;
#include <whb/log_module.h>
#include <whb/log_udp.h>
#include <whb/log_cafe.h>
if(ehdr->e_phoff == 0 || ehdr->e_phnum == 0)
return 0;
extern "C" void Initialize__Q2_2nn3spmFv();
extern "C" void SetAutoFatal__Q2_2nn3spmFb(bool);
extern "C" void SetExtendedStorage__Q2_2nn3spmFQ3_2nn3spm12StorageIndex(int*);
extern "C" void SetDefaultExtendedStorageVolumeId__Q2_2nn3spmFRCQ3_2nn3spm8VolumeId(int*);
if(ehdr->e_phentsize != sizeof(Elf32_Phdr))
return 0;
bool getQuickBoot() {
auto bootCheck = CCRSysCaffeineBootCheck();
if (bootCheck == 0) {
nn::sl::Initialize(MEMAllocFromDefaultHeapEx, MEMFreeToDefaultHeap);
char path[0x80];
nn::sl::GetDefaultDatabasePath(path, 0x80, 0x00050010, 0x10066000);
FSCmdBlock cmdBlock;
FSInitCmdBlock(&cmdBlock);
phdrs = (Elf32_Phdr*)(elfstart + ehdr->e_phoff);
auto fileStream = new nn::sl::FileStream;
auto *fsClient = (FSClient *) memalign(0x40, sizeof(FSClient));
memset(fsClient, 0, sizeof(*fsClient));
FSAddClient(fsClient, FS_ERROR_FLAG_NONE);
for(i = 0; i < ehdr->e_phnum; i++) {
if(phdrs[i].p_type != PT_LOAD)
continue;
fileStream->Initialize(fsClient, &cmdBlock, path, "r");
if(phdrs[i].p_filesz > phdrs[i].p_memsz)
continue;
auto database = new nn::sl::LaunchInfoDatabase;
database->Load(fileStream, nn::sl::REGION_EUR);
CCRAppLaunchParam data; // load sys caffeine data
// load app launch param
CCRSysCaffeineGetAppLaunchParam(&data);
nn::act::Initialize();
for(int i = 0; i < 13; i++){
char uuid[16];
auto result = nn::act::GetUuidEx(uuid, i);
if(result.IsSuccess()){
if( memcmp(uuid, data.uuid, 8) == 0) {
DEBUG_FUNCTION_LINE("Load Console account %d", i);
nn::act::LoadConsoleAccount(i, 0, 0, 0);
break;
}
}
}
nn::act::Finalize();
if(!phdrs[i].p_filesz)
continue;
// get launch info for id
nn::sl::LaunchInfo info;
database->GetLaunchInfoById(&info, data.titleId);
unsigned int p_paddr = phdrs[i].p_paddr;
image = (unsigned char *) (elfstart + phdrs[i].p_offset);
// info.titleId
OSReport("Quick boot into: %016llX\n", info.titleId);
memcpy ((void *) p_paddr, image, phdrs[i].p_filesz);
DCFlushRange((void*)p_paddr, phdrs[i].p_filesz);
delete database;
delete fileStream;
if(phdrs[i].p_flags & PF_X)
ICInvalidateRange ((void *) p_paddr, phdrs[i].p_memsz);
FSDelClient(fsClient, FS_ERROR_FLAG_NONE);
nn::sl::Finalize();
MCPTitleListType titleInfo;
int32_t handle = MCP_Open();
MCP_GetTitleInfo(handle, info.titleId, &titleInfo);
MCP_Close(handle);
ACPAssignTitlePatch(&titleInfo);
_SYSLaunchTitleWithStdArgsInNoSplash(info.titleId, nullptr);
return true;
} else {
OSReport("No quick boot\n");
}
//! clear BSS
Elf32_Shdr *shdr = (Elf32_Shdr *) (elfstart + ehdr->e_shoff);
for(i = 0; i < ehdr->e_shnum; i++) {
const char *section_name = ((const char*)elfstart) + shdr[ehdr->e_shstrndx].sh_offset + shdr[i].sh_name;
if(section_name[0] == '.' && section_name[1] == 'b' && section_name[2] == 's' && section_name[3] == 's') {
memset((void*)shdr[i].sh_addr, 0, shdr[i].sh_size);
DCFlushRange((void*)shdr[i].sh_addr, shdr[i].sh_size);
} else if(section_name[0] == '.' && section_name[1] == 's' && section_name[2] == 'b' && section_name[3] == 's' && section_name[4] == 's') {
memset((void*)shdr[i].sh_addr, 0, shdr[i].sh_size);
DCFlushRange((void*)shdr[i].sh_addr, shdr[i].sh_size);
}
}
return ehdr->e_entry;
return false;
}
static void initExternalStorage(void) {
Initialize__Q2_2nn3spmFv();
SetAutoFatal__Q2_2nn3spmFb(false);
int storageIndex[2]{};
SetExtendedStorage__Q2_2nn3spmFQ3_2nn3spm12StorageIndex(storageIndex);
int volumeId[4]{};
SetDefaultExtendedStorageVolumeId__Q2_2nn3spmFRCQ3_2nn3spm8VolumeId(volumeId);
}
void bootHomebrewLauncher(void) {
uint64_t titleId = _SYSGetSystemApplicationTitleId(SYSTEM_APP_ID_MII_MAKER);
_SYSLaunchTitleWithStdArgsInNoSplash(titleId, nullptr);
}
extern "C" void _SYSLaunchMenuWithCheckingAccount(nn::act::SlotNo slot);
int main(int argc, char **argv) {
uint32_t res = load_elf_image(payload_elf);
if(res != 0) {
((int (*)(int, char **)) res)(0, nullptr);
if(!WHBLogModuleInit()){
WHBLogCafeInit();
WHBLogUdpInit();
}
initExternalStorage();
InstallHBL();
if(!getQuickBoot()) {
bootHomebrewLauncher();
}
return 0;
}

39
source/utils.cpp Normal file
View File

@ -0,0 +1,39 @@
#include <string.h>
#include <stddef.h>
#include <whb/log.h>
#include "logger.h"
#include "utils.h"
// https://gist.github.com/ccbrown/9722406
void Utils::dumpHex(const void *data, size_t size) {
char ascii[17];
size_t i, j;
ascii[16] = '\0';
WHBLogWritef("0x%08X (0x0000): ", data);
for (i = 0; i < size; ++i) {
WHBLogWritef("%02X ", ((unsigned char *) data)[i]);
if (((unsigned char *) data)[i] >= ' ' && ((unsigned char *) data)[i] <= '~') {
ascii[i % 16] = ((unsigned char *) data)[i];
} else {
ascii[i % 16] = '.';
}
if ((i + 1) % 8 == 0 || i + 1 == size) {
WHBLogWritef(" ");
if ((i + 1) % 16 == 0) {
WHBLogPrintf("| %s ", ascii);
if (i + 1 < size) {
WHBLogWritef("0x%08X (0x%04X); ", ((uint32_t) data) + i + 1, i + 1);
}
} else if (i + 1 == size) {
ascii[(i + 1) % 16] = '\0';
if ((i + 1) % 16 <= 8) {
WHBLogWritef(" ");
}
for (j = (i + 1) % 16; j < 16; ++j) {
WHBLogWritef(" ");
}
WHBLogPrintf("| %s \n", ascii);
}
}
}
}

45
source/utils.h Normal file
View File

@ -0,0 +1,45 @@
#pragma once
#include <malloc.h>
#include <string>
#ifdef __cplusplus
extern "C" {
#endif
#define LIMIT(x, min, max) \
({ \
typeof( x ) _x = x; \
typeof( min ) _min = min; \
typeof( max ) _max = max; \
( ( ( _x ) < ( _min ) ) ? ( _min ) : ( ( _x ) > ( _max ) ) ? ( _max) : ( _x ) ); \
})
#define DegToRad(a) ( (a) * 0.01745329252f )
#define RadToDeg(a) ( (a) * 57.29577951f )
#define ALIGN4(x) (((x) + 3) & ~3)
#define ALIGN32(x) (((x) + 31) & ~31)
// those work only in powers of 2
#define ROUNDDOWN(val, align) ((val) & ~(align-1))
#define ROUNDUP(val, align) ROUNDDOWN(((val) + (align-1)), align)
#define le16(i) ((((uint16_t) ((i) & 0xFF)) << 8) | ((uint16_t) (((i) & 0xFF00) >> 8)))
#define le32(i) ((((uint32_t)le16((i) & 0xFFFF)) << 16) | ((uint32_t)le16(((i) & 0xFFFF0000) >> 16)))
#define le64(i) ((((uint64_t)le32((i) & 0xFFFFFFFFLL)) << 32) | ((uint64_t)le32(((i) & 0xFFFFFFFF00000000LL) >> 32)))
#ifdef __cplusplus
}
#endif
class Utils {
public:
static void dumpHex(const void *data, size_t size);
static std::string calculateSHA1(const char *buffer, size_t size);
static std::string hashFile(const std::string &path);
};