diff --git a/Makefile b/Makefile index 442c112..fa36586 100644 --- a/Makefile +++ b/Makefile @@ -100,7 +100,9 @@ export OUTPUT := $(CURDIR)/$(TARGET) #--------------------------------------------------------------------------------- $(BUILD): @[ -d $@ ] || mkdir -p $@ - @$(MAKE) --no-print-directory -s -C source/boot all + @$(MAKE) --no-print-directory -s -C source/boot + @mv -u $(CURDIR)/source/boot/appboot.bin \ + $(CURDIR)/data/appboot.bin @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile #--------------------------------------------------------------------------------- diff --git a/Test/menu.c b/Test/menu.c new file mode 100644 index 0000000..aa50a82 --- /dev/null +++ b/Test/menu.c @@ -0,0 +1,1416 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sys.h" +#include "fat.h" +#include "nand.h" +#include "restart.h" +#include "title.h" +#include "usbstorage.h" +#include "utils.h" +#include "video.h" +#include "wad.h" +#include "wpad.h" +#include +#include "globals.h" +#include "iospatch.h" +#include "appboot.h" + +/* FAT device list */ +//static fatDevice fdevList[] = { +fatDevice fdevList[] = { + { "sd", "Wii SD Slot", &__io_wiisd }, + { "usb", "USB Mass Storage Device", &__io_usbstorage }, + { "usb2", "USB 2.0 Mass Storage Device", &__io_wiiums }, + { "gcsda", "SD Gecko (Slot A)", &__io_gcsda }, + { "gcsdb", "SD Gecko (Slot B)", &__io_gcsdb }, + //{ "smb", "SMB share", NULL }, +}; + +/* NAND device list */ +//static nandDevice ndevList[] = { +nandDevice ndevList[] = { + { "Disable", 0, 0x00, 0x00 }, + { "SD/SDHC Card", 1, 0xF0, 0xF1 }, + { "USB 2.0 Mass Storage Device", 2, 0xF2, 0xF3 }, +}; + +/* FAT device */ +static fatDevice *fdev = NULL; +static nandDevice *ndev = NULL; + +// wiiNinja: Define a buffer holding the previous path names as user +// traverses the directory tree. Max of 10 levels is define at this point +static u8 gDirLevel = 0; +static char gDirList [MAX_DIR_LEVELS][MAX_FILE_PATH_LEN]; +static s32 gSeleted[MAX_DIR_LEVELS]; +static s32 gStart[MAX_DIR_LEVELS]; + +/* Macros */ +#define NB_FAT_DEVICES (sizeof(fdevList) / sizeof(fatDevice)) +#define NB_NAND_DEVICES (sizeof(ndevList) / sizeof(nandDevice)) + +// Local prototypes: wiiNinja +void WaitPrompt (char *prompt); +int PushCurrentDir(char *dirStr, int Selected, int Start); +char *PopCurrentDir(int *Selected, int *Start); +bool IsListFull (void); +char *PeekCurrentDir (void); +u32 WaitButtons(void); +u32 Pad_GetButtons(void); +void WiiLightControl (int state); + +int __Menu_IsGreater(const void *p1, const void *p2) +{ + u32 n1 = *(u32 *)p1; + u32 n2 = *(u32 *)p2; + + /* Equal */ + if (n1 == n2) + return 0; + + return (n1 > n2) ? 1 : -1; +} + + +int __Menu_EntryCmp(const void *p1, const void *p2) +{ + fatFile *f1 = (fatFile *)p1; + fatFile *f2 = (fatFile *)p2; + + /* Compare entries */ // wiiNinja: Include directory + if ((f1->isdir) && !(f2->isdir)) + return (-1); + else if (!(f1->isdir) && (f2->isdir)) + return (1); + else + return strcasecmp(f1->filename, f2->filename); +} + +static bool __FolderExists(const char *path) +{ + DIR *dir; + dir = opendir(path); + if(dir) + { + closedir(dir); + return true; + } + return false; +} + +static size_t __GetFileSizeBytes(const char *path) +{ + FILE *f; + size_t size = 0; + + f = fopen(path, "rb"); + if(!f) return 0; + + //Get file size + fseek(f, 0, SEEK_END); + size = ftell(f); + fclose(f); + + return size; +} + +char gFileName[MAX_FILE_PATH_LEN]; +s32 __Menu_RetrieveList(char *inPath, fatFile **outbuf, u32 *outlen) +{ + fatFile *buffer = NULL; + DIR *dir = NULL; + struct dirent *ent = NULL; + + //char dirpath[256], filename[768]; + u32 cnt; + + /* Generate dirpath */ + //sprintf(dirpath, "%s:" WAD_DIRECTORY, fdev->mount); + + /* Open directory */ + dir = opendir(inPath); + if (!dir) + return -1; + + /* Count entries */ + for (cnt = 0; ((ent = readdir(dir)) != NULL);) { + cnt++; + } + + if (cnt > 0) { + /* Allocate memory */ + buffer = malloc(sizeof(fatFile) * cnt); + if (!buffer) { + closedir(dir); + return -2; + } + + /* Reset directory */ + rewinddir(dir); + + /* Get entries */ + for (cnt = 0; ((ent = readdir(dir)) != NULL);) + { + bool addFlag = false; + bool isdir = false; + size_t fsize = 0; + + snprintf(gFileName, MAX_FILE_PATH_LEN, "%s/%s", inPath, ent->d_name); + if (__FolderExists(gFileName)) // wiiNinja + { + isdir = true; + // Add only the item ".." which is the previous directory + // AND if we're not at the root directory + if ((strcmp (ent->d_name, "..") == 0) && (gDirLevel > 1)) + addFlag = true; + else if (strcmp (ent->d_name, ".") != 0) + addFlag = true; + } + else + { + if(strlen(ent->d_name)>4) + { + if(!strcasecmp(ent->d_name+strlen(ent->d_name)-4, ".wad")) + { + fsize = __GetFileSizeBytes(gFileName); + addFlag = true; + } + } + } + + if (addFlag == true) + { + fatFile *file = &buffer[cnt++]; + + /* File name */ + strcpy(file->filename, ent->d_name); + + /* File stats */ + file->isdir = isdir; + file->fsize = fsize; + + } + } + + /* Sort list */ + qsort(buffer, cnt, sizeof(fatFile), __Menu_EntryCmp); + } + + /* Close directory */ + closedir(dir); + + /* Set values */ + *outbuf = buffer; + *outlen = cnt; + + return 0; +} + + +void Menu_SelectIOS(void) +{ + u8 *iosVersion = NULL; + u32 iosCnt; + u8 tmpVersion; + + u32 cnt; + s32 ret, selected = 0; + bool found = false; + + /* Get IOS versions */ + ret = Title_GetIOSVersions(&iosVersion, &iosCnt); + if (ret < 0) + return; + + /* Sort list */ + qsort(iosVersion, iosCnt, sizeof(u8), __Menu_IsGreater); + + if (gConfig.cIOSVersion < 0) + tmpVersion = CIOS_VERSION; + else + { + tmpVersion = (u8)gConfig.cIOSVersion; + // For debugging only + //printf ("User pre-selected cIOS: %i\n", tmpVersion); + //WaitButtons(); + } + + /* Set default version */ + for (cnt = 0; cnt < iosCnt; cnt++) { + u8 version = iosVersion[cnt]; + + /* Custom IOS available */ + //if (version == CIOS_VERSION) + if (version == tmpVersion) + { + selected = cnt; + found = true; + break; + } + + /* Current IOS */ + if (version == IOS_GetVersion()) + selected = cnt; + } + + /* Ask user for IOS version */ + if ((gConfig.cIOSVersion < 0) || (found == false)) + { + for (;;) + { + /* Clear console */ + Con_Clear(); + + printf("\t>> Select IOS version to use: < IOS%d >\n\n", iosVersion[selected]); + + printf("\t Press LEFT/RIGHT to change IOS version.\n\n"); + + printf("\t Press A button to continue.\n"); + printf("\t Press HOME button to restart.\n\n"); + + u32 buttons = WaitButtons(); + + /* LEFT/RIGHT buttons */ + if (buttons & WPAD_BUTTON_LEFT) { + if ((--selected) <= -1) + selected = (iosCnt - 1); + } + if (buttons & WPAD_BUTTON_RIGHT) { + if ((++selected) >= iosCnt) + selected = 0; + } + + /* HOME button */ + if (buttons & WPAD_BUTTON_HOME) + Restart(); + + /* A button */ + if (buttons & WPAD_BUTTON_A) + break; + } + } + + + u8 version = iosVersion[selected]; + + if (IOS_GetVersion() != version) { + /* Shutdown subsystems */ + Wpad_Disconnect(); + //mload_close(); + + /* Load IOS */ + + if(!loadIOS(version)) Wpad_Init(), Menu_SelectIOS(); + + /* Initialize subsystems */ + Wpad_Init(); + } +} + +void Menu_FatDevice(void) +{ + int ret, selected = 0; + + /* Unmount FAT device */ + //if (fdev) + //Fat_Unmount(fdev); + //if (((fdevList[selected].mount[0] == 's') && (ndev->name[0] == 'S'))) + //selected++; + static const u16 konamiCode[] = { + WPAD_BUTTON_UP, WPAD_BUTTON_UP, WPAD_BUTTON_DOWN, WPAD_BUTTON_DOWN, WPAD_BUTTON_LEFT, + WPAD_BUTTON_RIGHT, WPAD_BUTTON_LEFT, WPAD_BUTTON_RIGHT, WPAD_BUTTON_B, WPAD_BUTTON_A + }; + + int codePosition = 0; + + /* Select source device */ + if (gConfig.fatDeviceIndex < 0) + { + for (;;) { + /* Clear console */ + Con_Clear(); + + /* Selected device */ + fdev = &fdevList[selected]; + + printf("\t>> Select source device: < %s >\n\n", fdev->name); + + printf("\t Press LEFT/RIGHT to change the selected device.\n\n"); + + printf("\t Press A button to continue.\n"); + printf("\t Press HOME button to restart.\n\n"); + + u32 buttons = WaitButtons(); + + if (buttons & (WPAD_BUTTON_UP | WPAD_BUTTON_DOWN | WPAD_BUTTON_RIGHT | WPAD_BUTTON_LEFT | WPAD_BUTTON_A | WPAD_BUTTON_B)) { + if (buttons & konamiCode[codePosition]) + ++codePosition; + else + codePosition = 0; + } + + /* LEFT/RIGHT buttons */ + if (buttons & WPAD_BUTTON_LEFT) { + if ((--selected) <= -1) + selected = (NB_FAT_DEVICES - 1); + if ((fdevList[selected].mount[0] == 's') && (ndev->name[0] == 'S')) + selected--; + if ((fdevList[selected].mount[0] == 'u' && fdevList[selected].mount[3] == '2') && (ndev->name[0] == 'U')) + selected--; + if ((selected) <= -1) + selected = (NB_FAT_DEVICES - 1); + } + if (buttons & WPAD_BUTTON_RIGHT) { + if ((++selected) >= NB_FAT_DEVICES) + selected = 0; + if ((fdevList[selected].mount[0] == 's') && (ndev->name[0] == 'S')) + selected++; + if ((fdevList[selected].mount[0] == 'u' && fdevList[selected].mount[3] == '2') && (ndev->name[0] == 'U')) + selected++; + } + + /* HOME button */ + if (buttons & WPAD_BUTTON_HOME) + Restart(); + + /* A button */ + if (buttons & WPAD_BUTTON_A) { + if (codePosition == sizeof(konamiCode) / sizeof(konamiCode[0])) { + extern bool skipRegionSafetyCheck; + skipRegionSafetyCheck = true; + printf("[+] Disabled SM region checks\n"); + sleep(2); + } + break; + } + } + } + else + { + sleep(5); + fdev = &fdevList[gConfig.fatDeviceIndex]; + } + + printf("[+] Mounting %s, please wait...", fdev->name ); + fflush(stdout); + + /* Mount FAT device */ + + ret = Fat_Mount(fdev); + if (ret < 0) { + printf(" ERROR! (ret = %d)\n", ret); + goto err; + } else + printf(" OK!\n"); + + return; + +err: + + if(gConfig.fatDeviceIndex >= 0) gConfig.fatDeviceIndex = -1; + WiiLightControl (WII_LIGHT_OFF); + printf("\n"); + printf(" Press any button to continue...\n"); + + WaitButtons(); + + /* Prompt menu again */ + Menu_FatDevice(); +} + +void Menu_NandDevice(void) +{ + int ret, selected = 0; + + /* Disable NAND emulator */ + if (ndev) { + Nand_Unmount(ndev); + Nand_Disable(); + } + + /* Select source device */ + if (gConfig.nandDeviceIndex < 0) + { + for (;;) { + /* Clear console */ + Con_Clear(); + + /* Selected device */ + ndev = &ndevList[selected]; + + printf("\t>> Select NAND emulator device: < %s >\n\n", ndev->name); + + printf("\t Press LEFT/RIGHT to change the selected device.\n\n"); + + printf("\t Press A button to continue.\n"); + printf("\t Press HOME button to restart.\n\n"); + + u32 buttons = WaitButtons(); + + /* LEFT/RIGHT buttons */ + if (buttons & WPAD_BUTTON_LEFT) { + if ((--selected) <= -1) + selected = (NB_NAND_DEVICES - 1); + } + if (buttons & WPAD_BUTTON_RIGHT) { + if ((++selected) >= NB_NAND_DEVICES) + selected = 0; + } + + /* HOME button */ + if (buttons & WPAD_BUTTON_HOME) + Restart(); + + /* A button */ + if (buttons & WPAD_BUTTON_A) + break; + } + } + else + { + ndev = &ndevList[gConfig.nandDeviceIndex]; + } + + /* No NAND device */ + if (!ndev->mode) + return; + + printf("[+] Enabling NAND emulator..."); + fflush(stdout); + + /* Mount NAND device */ + ret = Nand_Mount(ndev); + if (ret < 0) { + printf(" ERROR! (ret = %d)\n", ret); + goto err; + } + + /* Enable NAND emulator */ + ret = Nand_Enable(ndev); + if (ret < 0) { + printf(" ERROR! (ret = %d)\n", ret); + goto err; + } else + printf(" OK!\n"); + + return; + +err: + printf("\n"); + printf(" Press any button to continue...\n"); + + WaitButtons(); + + /* Prompt menu again */ + Menu_NandDevice(); +} + +char gTmpFilePath[MAX_FILE_PATH_LEN]; +/* Install and/or Uninstall multiple WADs - Leathl */ +int Menu_BatchProcessWads(fatFile *files, int fileCount, char *inFilePath, int installCnt, int uninstallCnt) +{ + int count; + + for (;;) + { + Con_Clear(); + + if ((installCnt > 0) & (uninstallCnt == 0)) { + printf("[+] %d file%s marked for installation.\n", installCnt, (installCnt == 1) ? "" : "s"); + printf(" Do you want to proceed?\n"); + } + else if ((installCnt == 0) & (uninstallCnt > 0)) { + printf("[+] %d file%s marked for uninstallation.\n", uninstallCnt, (uninstallCnt == 1) ? "" : "s"); + printf(" Do you want to proceed?\n"); + } + else { + printf("[+] %d file%s marked for installation and %d file%s for uninstallation.\n", installCnt, (installCnt == 1) ? "" : "s", uninstallCnt, (uninstallCnt == 1) ? "" : "s"); + printf(" Do you want to proceed?\n"); + } + + printf("\n\n Press A to continue.\n"); + printf(" Press B to go back to the menu.\n\n"); + + u32 buttons = WaitButtons(); + + if (buttons & WPAD_BUTTON_A) + break; + + if (buttons & WPAD_BUTTON_B) + return 0; + } + + WiiLightControl (WII_LIGHT_ON); + int errors = 0; + int success = 0; + s32 ret; + + for (count = 0; count < fileCount; count++) + { + fatFile *thisFile = &files[count]; + + if ((thisFile->install == 1) | (thisFile->install == 2)) { + int mode = thisFile->install; + Con_Clear(); + printf("[+] Opening \"%s\", please wait...\n\n", thisFile->filename); + + sprintf(gTmpFilePath, "%s/%s", inFilePath, thisFile->filename); + + FILE *fp = fopen(gTmpFilePath, "rb"); + if (!fp) { + printf(" ERROR!\n"); + errors += 1; + continue; + } + + printf("[+] %s WAD, please wait...\n", (mode == 2) ? "Uninstalling" : "Installing"); + if (mode == 2) { + ret = Wad_Uninstall(fp); + } + else { + ret = Wad_Install(fp); + } + + if (ret < 0) errors += 1; + else success += 1; + + thisFile->installstate = ret; + + if (fp) + fclose(fp); + } + } + + WiiLightControl (WII_LIGHT_OFF); + + printf("\n"); + printf(" %d titles succeeded and %d failed...\n", success, errors); + + if (errors > 0) + { + printf("\n Some operations failed"); + printf("\n Press A to list.\n"); + printf(" Press B skip.\n"); + + u32 buttons = WaitButtons(); + + if ((buttons & WPAD_BUTTON_A)) + { + Con_Clear(); + + int i=0; + for (count = 0; count < fileCount; count++) + { + fatFile *thisFile = &files[count]; + + if (thisFile->installstate <0) + { + char str[41]; + strncpy(str, thisFile->filename, 40); //Only 40 chars to fit the screen + str[40]=0; + i++; + if(thisFile->installstate == -999) printf(" %s BRICK BLOCKED\n", str); + else if(thisFile->installstate == -998) printf(" %s Skipped\n", str); + else if(thisFile->installstate == -106) printf(" %s Not installed?\n", str); + else if(thisFile->installstate == -1036 ) printf(" %s Needed IOS missing\n", str); + else if(thisFile->installstate == -4100 ) printf(" %s No trucha bug?\n", str); + else printf(" %s error %d\n", str, thisFile->installstate); + if( i == 17 ) + { + printf("\n Press any button to continue\n"); + WaitButtons(); + i = 0; + } + } + } + } + } + printf("\n Press any button to continue...\n"); + WaitButtons(); + + return 1; +} + +/* File Operations - Leathl */ +int Menu_FileOperations(fatFile *file, char *inFilePath) +{ + f32 filesize = (file->fsize / MB_SIZE); + + for (;;) + { + Con_Clear(); + + printf("[+] WAD Filename : %s\n", file->filename); + printf(" WAD Filesize : %.2f MB\n\n\n", filesize); + + + printf("[+] Select action: < %s WAD >\n\n", "Delete"); //There's yet nothing else than delete + + printf(" Press LEFT/RIGHT to change selected action.\n\n"); + + printf(" Press A to continue.\n"); + printf(" Press B to go back to the menu.\n\n"); + + u32 buttons = WaitButtons(); + + /* A button */ + if (buttons & WPAD_BUTTON_A) + break; + + /* B button */ + if (buttons & WPAD_BUTTON_B) + return 0; + } + + Con_Clear(); + + printf("[+] Deleting \"%s\", please wait...\n", file->filename); + + sprintf(gTmpFilePath, "%s/%s", inFilePath, file->filename); + int error = remove(gTmpFilePath); + if (error != 0) + printf(" ERROR!"); + else + printf(" Successfully deleted!"); + + printf("\n"); + printf(" Press any button to continue...\n"); + + WaitButtons(); + + return !error; +} + +void Menu_WadManage(fatFile *file, char *inFilePath) +{ + FILE *fp = NULL; + + //char filepath[128]; + f32 filesize; + + u32 mode = 0; + + /* File size in megabytes */ + filesize = (file->fsize / MB_SIZE); + + for (;;) { + /* Clear console */ + Con_Clear(); + + printf("[+] WAD Filename : %s\n", file->filename); + printf(" WAD Filesize : %.2f MB\n\n\n", filesize); + + + printf("[+] Select action: < %s WAD >\n\n", (!mode) ? "Install" : "Uninstall"); + + printf(" Press LEFT/RIGHT to change selected action.\n\n"); + + printf(" Press A to continue.\n"); + printf(" Press B to go back to the menu.\n\n"); + + u32 buttons = WaitButtons(); + + /* LEFT/RIGHT buttons */ + if (buttons & (WPAD_BUTTON_LEFT | WPAD_BUTTON_RIGHT)) + mode ^= 1; + + /* A button */ + if (buttons & WPAD_BUTTON_A) + break; + + /* B button */ + if (buttons & WPAD_BUTTON_B) + return; + } + + /* Clear console */ + Con_Clear(); + + printf("[+] Opening \"%s\", please wait...", file->filename); + fflush(stdout); + + /* Generate filepath */ + // sprintf(filepath, "%s:" WAD_DIRECTORY "/%s", fdev->mount, file->filename); + sprintf(gTmpFilePath, "%s/%s", inFilePath, file->filename); // wiiNinja + + /* Open WAD */ + fp = fopen(gTmpFilePath, "rb"); + if (!fp) { + printf(" ERROR!\n"); + goto out; + } else + printf(" OK!\n\n"); + + printf("[+] %s WAD, please wait...\n", (!mode) ? "Installing" : "Uninstalling"); + + /* Do install/uninstall */ + WiiLightControl (WII_LIGHT_ON); + if (!mode) + Wad_Install(fp); + else + Wad_Uninstall(fp); + WiiLightControl (WII_LIGHT_OFF); + +out: + /* Close file */ + if (fp) + fclose(fp); + + printf("\n"); + printf(" Press any button to continue...\n"); + + /* Wait for button */ + WaitButtons(); +} + +void Menu_WadList(void) +{ + char str [100]; + fatFile *fileList = NULL; + u32 fileCnt; + int ret, selected = 0, start = 0; + char *tmpPath = malloc (MAX_FILE_PATH_LEN); + int installCnt = 0; + int uninstallCnt = 0; + + //fatFile *installFiles = malloc(sizeof(fatFile) * 50); + //int installCount = 0; + + // wiiNinja: check for malloc error + if (tmpPath == NULL) + { + ret = -997; // What am I gonna use here? + printf(" ERROR! Out of memory (ret = %d)\n", ret); + return; + } + + printf("[+] Retrieving file list..."); + fflush(stdout); + + gDirLevel = 0; + + // push root dir as base folder + sprintf(tmpPath, "%s:%s", fdev->mount, WAD_DIRECTORY); + PushCurrentDir(tmpPath,0,0); + // if user provides startup directory, try it out first + if (strcmp (WAD_DIRECTORY, gConfig.startupPath) != 0) + { + // replace root dir with provided startup directory + sprintf(tmpPath, "%s:%s", fdev->mount, gConfig.startupPath); + // If the directory can be successfully opened, it must exists + DIR *tmpDirPtr = opendir(tmpPath); + if (tmpDirPtr) + { + closedir (tmpDirPtr); + PushCurrentDir(tmpPath,0,0); + } + else // unable to open provided dir, stick with root dir + sprintf(tmpPath, "%s:%s", fdev->mount, WAD_DIRECTORY); + } + + /* Retrieve filelist */ +getList: + free (fileList); + fileList = NULL; + + ret = __Menu_RetrieveList(tmpPath, &fileList, &fileCnt); + if (ret < 0) { + printf(" ERROR! (ret = %d)\n", ret); + goto err; + } + + /* No files */ + if (!fileCnt) { + printf(" No files found!\n"); + goto err; + } + + /* Set install-values to 0 - Leathl */ + int counter; + for (counter = 0; counter < fileCnt; counter++) { + fatFile *file = &fileList[counter]; + file->install = 0; + } + + for (;;) + { + u32 cnt; + s32 index; + + /* Clear console */ + Con_Clear(); + + /** Print entries **/ + cnt = strlen(tmpPath); + if(cnt>30) + index = cnt-30; + else + index = 0; + + printf("[+] WAD files on [%s]:\n\n", tmpPath+index); + + /* Print entries */ + for (cnt = start; cnt < fileCnt; cnt++) + { + fatFile *file = &fileList[cnt]; + f32 filesize = file->fsize / MB_SIZE; + + /* Entries per page limit */ + if ((cnt - start) >= ENTRIES_PER_PAGE) + break; + + strncpy(str, file->filename, 40); //Only 40 chars to fit the screen + str[40]=0; + + /* Print filename */ + //printf("\t%2s %s (%.2f MB)\n", (cnt == selected) ? ">>" : " ", file->filename, filesize); + if (file->isdir) // wiiNinja + printf("\t%2s [%s]\n", (cnt == selected) ? ">>" : " ", str); + else + printf("\t%2s%s%s (%.2f MB)\n", (cnt == selected) ? ">>" : " ", (file->install == 1) ? "+" : ((file->install == 2) ? "-" : " "), str, filesize); + + } + + printf("\n"); + + printf("[+] Press A to (un)install."); + if(gDirLevel>1) + printf(" Press B to go up-level DIR.\n"); + else + printf(" Press B to select a device.\n"); + printf(" Use +/X and -/Y to (un)mark. Press 1/Z/ZR for delete menu.\n"); + + printf(" Press 2 to launch app.\n"); + + /** Controls **/ + u32 buttons = WaitButtons(); + + if (buttons & WPAD_BUTTON_2) + { + if (!LoadApp(tmpPath)) + { + printf(" Failed to load app.\n"); + goto err; + } + + Fat_Unmount(fdev); + //SetIos(36); + + LaunchApp(); + } + + /* DPAD buttons */ + if (buttons & WPAD_BUTTON_UP) { + selected--; + + if (selected <= -1) + selected = (fileCnt - 1); + } + if (buttons & WPAD_BUTTON_LEFT) { + selected = selected + ENTRIES_PER_PAGE; + + if (selected >= fileCnt) + selected = 0; + } + if (buttons & WPAD_BUTTON_DOWN) { + selected ++; + + if (selected >= fileCnt) + selected = 0; + } + if (buttons & WPAD_BUTTON_RIGHT) { + selected = selected - ENTRIES_PER_PAGE; + + if (selected <= -1) + selected = (fileCnt - 1); + } + + /* HOME button */ + if (buttons & WPAD_BUTTON_HOME) + Restart(); + + /* Plus Button - Leathl */ + if (buttons & WPAD_BUTTON_PLUS) + { + if(Wpad_TimeButton()) + { + installCnt = 0; + int i = 0; + while( i < fileCnt) + { + fatFile *file = &fileList[i]; + if (((file->isdir) == false) & (file->install == 0)) { + file->install = 1; + + installCnt += 1; + } + else if (((file->isdir) == false) & (file->install == 1)) { + file->install = 0; + + installCnt -= 1; + } + else if (((file->isdir) == false) & (file->install == 2)) { + file->install = 1; + + installCnt += 1; + uninstallCnt -= 1; + } + i++; + } + + } + else + { + fatFile *file = &fileList[selected]; + if (((file->isdir) == false) & (file->install == 0)) { + file->install = 1; + + installCnt += 1; + } + else if (((file->isdir) == false) & (file->install == 1)) { + file->install = 0; + + installCnt -= 1; + } + else if (((file->isdir) == false) & (file->install == 2)) { + file->install = 1; + + installCnt += 1; + uninstallCnt -= 1; + } + selected++; + + if (selected >= fileCnt) + selected = 0; + } + } + + /* Minus Button - Leathl */ + if (buttons & WPAD_BUTTON_MINUS) + { + if(Wpad_TimeButton()) + { + installCnt = 0; + int i = 0; + while( i < fileCnt) + { + fatFile *file = &fileList[i]; + if (((file->isdir) == false) & (file->install == 0)) { + file->install = 2; + + uninstallCnt += 1; + } + else if (((file->isdir) == false) & (file->install == 1)) { + file->install = 2; + + uninstallCnt += 1; + installCnt -= 1; + } + else if (((file->isdir) == false) & (file->install == 2)) { + file->install = 0; + + uninstallCnt -= 1; + } + i++; + } + + } + else + { + fatFile *file = &fileList[selected]; + if (((file->isdir) == false) & (file->install == 0)) { + file->install = 2; + + uninstallCnt += 1; + } + else if (((file->isdir) == false) & (file->install == 1)) { + file->install = 2; + + uninstallCnt += 1; + installCnt -= 1; + } + else if (((file->isdir) == false) & (file->install == 2)) { + file->install = 0; + + uninstallCnt -= 1; + } + selected++; + + if (selected >= fileCnt) + selected = 0; + } + } + + /* 1 Button - Leathl */ + if (buttons & WPAD_BUTTON_1) + { + fatFile *tmpFile = &fileList[selected]; + char *tmpCurPath = PeekCurrentDir (); + if (tmpCurPath != NULL) { + int res = Menu_FileOperations(tmpFile, tmpCurPath); + if (res != 0) + goto getList; + } + } + + + /* A button */ + if (buttons & WPAD_BUTTON_A) + { + fatFile *tmpFile = &fileList[selected]; + char *tmpCurPath; + if (tmpFile->isdir) // wiiNinja + { + if (strcmp (tmpFile->filename, "..") == 0) + { + selected = 0; + start = 0; + + // Previous dir + tmpCurPath = PopCurrentDir(&selected, &start); + if (tmpCurPath != NULL) + sprintf(tmpPath, "%s", tmpCurPath); + + installCnt = 0; + uninstallCnt = 0; + + goto getList; + } + else if (IsListFull () == true) + { + WaitPrompt ("Maximum number of directory levels is reached.\n"); + } + else + { + tmpCurPath = PeekCurrentDir (); + if (tmpCurPath != NULL) + { + if(gDirLevel>1) + sprintf(tmpPath, "%s/%s", tmpCurPath, tmpFile->filename); + else + sprintf(tmpPath, "%s%s", tmpCurPath, tmpFile->filename); + } + // wiiNinja: Need to PopCurrentDir + PushCurrentDir (tmpPath, selected, start); + selected = 0; + start = 0; + + installCnt = 0; + uninstallCnt = 0; + + goto getList; + } + } + else + { + //If at least one WAD is marked, goto batch screen - Leathl + if ((installCnt > 0) | (uninstallCnt > 0)) { + char *thisCurPath = PeekCurrentDir (); + if (thisCurPath != NULL) { + int res = Menu_BatchProcessWads(fileList, fileCnt, thisCurPath, installCnt, uninstallCnt); + + if (res == 1) { + int counter; + for (counter = 0; counter < fileCnt; counter++) { + fatFile *temp = &fileList[counter]; + temp->install = 0; + } + + installCnt = 0; + uninstallCnt = 0; + } + } + } + //else use standard wadmanage menu - Leathl + else { + tmpCurPath = PeekCurrentDir (); + if (tmpCurPath != NULL) + Menu_WadManage(tmpFile, tmpCurPath); + } + } + } + + /* B button */ + if (buttons & WPAD_BUTTON_B) + { + if(gDirLevel<=1) + { + return; + } + + char *tmpCurPath; + selected = 0; + start = 0; + // Previous dir + tmpCurPath = PopCurrentDir(&selected, &start); + if (tmpCurPath != NULL) + sprintf(tmpPath, "%s", tmpCurPath); + goto getList; + //return; + } + + /** Scrolling **/ + /* List scrolling */ + index = (selected - start); + + if (index >= ENTRIES_PER_PAGE) + start += index - (ENTRIES_PER_PAGE - 1); + if (index <= -1) + start += index; + } + +err: + printf("\n"); + printf(" Press any button to continue...\n"); + + free (tmpPath); + + /* Wait for button */ + WaitButtons(); +} + + +void Menu_Loop(void) +{ + u8 iosVersion; + if(AHBPROT_DISABLED) + IOSPATCH_Apply(); + else + { + /* Select IOS menu */ + Menu_SelectIOS(); + } + + /* Retrieve IOS version */ + iosVersion = IOS_GetVersion(); + + ndev = &ndevList[0]; + + /* NAND device menu */ + if ((iosVersion == CIOS_VERSION || iosVersion == 250) && IOS_GetRevision() >13) + { + Menu_NandDevice(); + } + for (;;) { + /* FAT device menu */ + Menu_FatDevice(); + + /* WAD list menu */ + Menu_WadList(); + } +} + +// Start of wiiNinja's added routines + +int PushCurrentDir (char *dirStr, int Selected, int Start) +{ + int retval = 0; + + // Store dirStr into the list and increment the gDirLevel + // WARNING: Make sure dirStr is no larger than MAX_FILE_PATH_LEN + if (gDirLevel < MAX_DIR_LEVELS) + { + strcpy (gDirList [gDirLevel], dirStr); + gSeleted[gDirLevel]=Selected; + gStart[gDirLevel]=Start; + gDirLevel++; + //if (gDirLevel >= MAX_DIR_LEVELS) + // gDirLevel = 0; + } + else + retval = -1; + + return (retval); +} + +char *PopCurrentDir(int *Selected, int *Start) +{ + if (gDirLevel > 1) + gDirLevel--; + else { + gDirLevel = 0; + } + *Selected = gSeleted[gDirLevel]; + *Start = gStart[gDirLevel]; + return PeekCurrentDir(); +} + +bool IsListFull (void) +{ + if (gDirLevel < MAX_DIR_LEVELS) + return (false); + else + return (true); +} + +char *PeekCurrentDir (void) +{ + // Return the current path + if (gDirLevel > 0) + return (gDirList [gDirLevel-1]); + else + return (NULL); +} + +void WaitPrompt (char *prompt) +{ + printf("\n%s", prompt); + printf(" Press any button to continue...\n"); + + /* Wait for button */ + WaitButtons(); +} + +u32 Pad_GetButtons(void) +{ + u32 buttons = 0, cnt; + + /* Scan pads */ + PAD_ScanPads(); + + /* Get pressed buttons */ + //for (cnt = 0; cnt < MAX_WIIMOTES; cnt++) + for (cnt = 0; cnt < 4; cnt++) + buttons |= PAD_ButtonsDown(cnt); + + return buttons; +} + +u32 WiiDRC_GetButtons(void) +{ + if(!WiiDRC_Inited() || !WiiDRC_Connected()) + return 0; + + /* Scan pads */ + WiiDRC_ScanPads(); + + /* Get pressed buttons */ + return WiiDRC_ButtonsDown(); +} + +// Routine to wait for a button from either the Wiimote or a gamecube +// controller. The return value will mimic the WPAD buttons to minimize +// the amount of changes to the original code, that is expecting only +// Wiimote button presses. Note that the "HOME" button on the Wiimote +// is mapped to the "SELECT" button on the Gamecube Ctrl. (wiiNinja 5/15/2009) +u32 WaitButtons(void) +{ + u32 buttons = 0; + u32 buttonsGC = 0; + u32 buttonsDRC = 0; + + /* Wait for button pressing */ + while (!buttons && !buttonsGC && !buttonsDRC) + { + // Wii buttons + buttons = Wpad_GetButtons(); + + // GC buttons + buttonsGC = Pad_GetButtons(); + + // DRC buttons + buttonsDRC = WiiDRC_GetButtons(); + + VIDEO_WaitVSync(); + } + + if(buttons & WPAD_CLASSIC_BUTTON_A) + buttons |= WPAD_BUTTON_A; + else if(buttons & WPAD_CLASSIC_BUTTON_B) + buttons |= WPAD_BUTTON_B; + else if(buttons & WPAD_CLASSIC_BUTTON_LEFT) + buttons |= WPAD_BUTTON_LEFT; + else if(buttons & WPAD_CLASSIC_BUTTON_RIGHT) + buttons |= WPAD_BUTTON_RIGHT; + else if(buttons & WPAD_CLASSIC_BUTTON_DOWN) + buttons |= WPAD_BUTTON_DOWN; + else if(buttons & WPAD_CLASSIC_BUTTON_UP) + buttons |= WPAD_BUTTON_UP; + else if(buttons & WPAD_CLASSIC_BUTTON_HOME) + buttons |= WPAD_BUTTON_HOME; + else if(buttons & (WPAD_CLASSIC_BUTTON_X | WPAD_CLASSIC_BUTTON_PLUS)) + buttons |= WPAD_BUTTON_PLUS; + else if(buttons & (WPAD_CLASSIC_BUTTON_Y | WPAD_CLASSIC_BUTTON_MINUS)) + buttons |= WPAD_BUTTON_MINUS; + else if(buttons & WPAD_CLASSIC_BUTTON_ZR) + buttons |= WPAD_BUTTON_1; + + if (buttonsGC) + { + if(buttonsGC & PAD_BUTTON_A) + buttons |= WPAD_BUTTON_A; + else if(buttonsGC & PAD_BUTTON_B) + buttons |= WPAD_BUTTON_B; + else if(buttonsGC & PAD_BUTTON_LEFT) + buttons |= WPAD_BUTTON_LEFT; + else if(buttonsGC & PAD_BUTTON_RIGHT) + buttons |= WPAD_BUTTON_RIGHT; + else if(buttonsGC & PAD_BUTTON_DOWN) + buttons |= WPAD_BUTTON_DOWN; + else if(buttonsGC & PAD_BUTTON_UP) + buttons |= WPAD_BUTTON_UP; + else if(buttonsGC & PAD_BUTTON_START) + buttons |= WPAD_BUTTON_HOME; + else if(buttonsGC & PAD_BUTTON_X) + buttons |= WPAD_BUTTON_PLUS; + else if(buttonsGC & PAD_BUTTON_Y) + buttons |= WPAD_BUTTON_MINUS; + else if(buttonsGC & PAD_TRIGGER_Z) + buttons |= WPAD_BUTTON_1; + } + + if (buttonsDRC) + { + if(buttonsDRC & WIIDRC_BUTTON_A) + buttons |= WPAD_BUTTON_A; + else if(buttonsDRC & WIIDRC_BUTTON_B) + buttons |= WPAD_BUTTON_B; + else if(buttonsDRC & WIIDRC_BUTTON_LEFT) + buttons |= WPAD_BUTTON_LEFT; + else if(buttonsDRC & WIIDRC_BUTTON_RIGHT) + buttons |= WPAD_BUTTON_RIGHT; + else if(buttonsDRC & WIIDRC_BUTTON_DOWN) + buttons |= WPAD_BUTTON_DOWN; + else if(buttonsDRC & WIIDRC_BUTTON_UP) + buttons |= WPAD_BUTTON_UP; + else if(buttonsDRC & WIIDRC_BUTTON_HOME) + buttons |= WPAD_BUTTON_HOME; + else if(buttonsDRC & (WIIDRC_BUTTON_X | WIIDRC_BUTTON_PLUS)) + buttons |= WPAD_BUTTON_PLUS; + else if(buttonsDRC & (WIIDRC_BUTTON_Y | WIIDRC_BUTTON_MINUS)) + buttons |= WPAD_BUTTON_MINUS; + else if(buttonsDRC & WIIDRC_BUTTON_ZR) + buttons |= WPAD_BUTTON_1; + } + + return buttons; +} // WaitButtons + + +void WiiLightControl (int state) +{ + switch (state) + { + case WII_LIGHT_ON: + /* Turn on Wii Light */ + WIILIGHT_SetLevel(255); + WIILIGHT_TurnOn(); + break; + + case WII_LIGHT_OFF: + default: + /* Turn off Wii Light */ + WIILIGHT_SetLevel(0); + WIILIGHT_TurnOn(); + WIILIGHT_Toggle(); + break; + } +} // WiiLightControl + diff --git a/data/appboot.bin b/data/appboot.bin index d8712d2..5adac45 100644 Binary files a/data/appboot.bin and b/data/appboot.bin differ diff --git a/source/appboot.c b/source/appboot.c index 25f5c0a..fac9f41 100644 --- a/source/appboot.c +++ b/source/appboot.c @@ -4,11 +4,15 @@ #include #include #include +#include #include +#include "appboot.h" #include "fat.h" #include "sys.h" #include "appmetadata.h" +#include "iospatch.h" +#include "video.h" extern void __exception_closeall(); @@ -20,35 +24,83 @@ u32 metaSize = 0; u8* appBuffer = NULL; u32 appSize = 0; - -typedef void (*entrypoint)(); u32 appEntry = 0; +u32 appIos = 0; + #include "appboot_bin.h" -static void Jump(entrypoint EntryPoint) -{ - appEntry = (u32)EntryPoint; +#define MEM2PROT 0x0D8B420A +#define ESMODULESTART (u16*)0x939F0000 - u32 level = IRQ_Disable(); - __IOS_ShutdownSubsystems(); - __exception_closeall(); - __lwp_thread_closeall(); - asm volatile ( - "lis %r3, appEntry@h\n" - "ori %r3, %r3, appEntry@l\n" - "lwz %r3, 0(%r3)\n" - "mtlr %r3\n" - "blr\n" - ); - IRQ_Restore(level); +static const u16 ticket[] = { + 0x685B, // ldr r3,[r3,#4] ; get TMD pointer + 0x22EC, 0x0052, // movls r2, 0x1D8 + 0x189B, // adds r3, r3, r2; add offset of access rights field in TMD + 0x681B, // ldr r3, [r3] ; load access rights (haxxme!) + 0x4698, // mov r8, r3 ; store it for the DVD video bitcheck later + 0x07DB // lsls r3, r3, #31; check AHBPROT bit +}; + +static bool patchahbprot(void) +{ + u16* patch; + + if ((read32(0x0D800064) == 0xFFFFFFFF) ? 1 : 0) + { + write16(MEM2PROT, 2); + for (patch = ESMODULESTART; patch < ESMODULESTART + 0x4000; ++patch) { + if (!memcmp(patch, ticket, sizeof(ticket))) + { + patch[4] = 0x23FF; + DCFlushRange(patch + 4, 2); + return 0; + } + } + return -1; + } + else { + return -2; + } } bool LoadApp(const char* path) { + Con_Clear(); + appBuffer = (u8*)0x92000000; char currentPath[256]; + snprintf(currentPath, sizeof(currentPath), "%s/meta.xml", path); + u16 argumentsSize = 0; + char* Arguments = LoadArguments(currentPath, &argumentsSize); + + if (Arguments) + { + *(vu32*)0x91000000 = argumentsSize; + memcpy((void*)0x91000020, Arguments, argumentsSize); + DCFlushRange((void*)0x91000020, argumentsSize); + ICInvalidateRange((void*)0x91000020, argumentsSize); + free(Arguments); + } + else + { + *(vu32*)0x91000000 = 0; + } + + struct MetaData* appData = LoadMetaData(currentPath); + + if (appData) + { + printf("-> App title: %s version %s\n", appData->name, appData->version); + printf("-> Coder(s): %s\n", appData->coder); + if (appData->releaseDate != NULL) + printf("-> Release date: %s\n", appData->releaseDate); + FreeMetaData(appData); + + printf("\n"); + } + snprintf(currentPath, sizeof(currentPath), "%s/boot.dol", path); FILE* f = fopen(currentPath, "rb"); @@ -62,6 +114,8 @@ bool LoadApp(const char* path) return false; } + printf("-> Load: %s\n", currentPath); + fseek(f, 0, SEEK_END); appSize = ftell(f); rewind(f); @@ -73,22 +127,21 @@ bool LoadApp(const char* path) } u32 ret = fread(appBuffer, 1, appSize, f); - DCFlushRange(appBuffer, (appSize + 31) & (~31)); - - fclose(f); - - snprintf(currentPath, sizeof(currentPath), "%s/meta.xml", path); - u16 argumentsSize = 0; - char* Arguments = LoadArguments(currentPath, &argumentsSize); - - if (Arguments) + if (ret != appSize) { - *(vu32*)0x91000000 = argumentsSize; - memcpy((void*)0x91000020, Arguments, argumentsSize); - DCFlushRange((u8*)0x91000020, argumentsSize); - free(Arguments); + printf("Failed to read file: %s (0x%X -> 0x%X)\n", currentPath, ret, appSize ); + fclose(f); + return false; + } + else + { + printf("-> App size: 0x%X\n\n", appSize); } + DCFlushRange(appBuffer, appSize); + ICInvalidateRange(appBuffer, appSize); + + fclose(f); return (ret == appSize); } @@ -99,13 +152,74 @@ u8* GetApp(u32* size) } void LaunchApp(void) -{ - entrypoint entry; +{ + entrypoint entry = NULL; + + LoadBooter(&entry); + + if (!appIos) + appIos = IOS_GetPreferredVersion(); + + if (AHBPROT_DISABLED) + { + if (appIos > 0 && appIos < 200) + { + printf("-> Patch IOS for AHB access\n"); + patchahbprot(); + } + } - memcpy((u8*)0x93000000, appboot_bin, appboot_bin_size); - DCFlushRange((u8*)0x93000000, appboot_bin_size); - entry = (entrypoint)0x93000000; + if (appIos > 0) + __IOS_LaunchNewIOS(appIos); - Jump(entry); + if (AHBPROT_DISABLED) + { + printf("-> Reenable DVD access\n"); + mask32(0x0D800180, 1 << 21, 0); + } + + printf("-> And we're outta here!\n"); + + *(vu32*)0x800000F8 = 0x0E7BE2C0; // Bus Speed + *(vu32*)0x800000FC = 0x2B73A840; // CPU Speed + + //SYS_ResetSystem(SYS_SHUTDOWN, 0, 0); + __exception_closeall(); + entry(); + + printf("--> Well.. this shouldn't happen\n"); Sys_LoadMenu(); -} \ No newline at end of file +} + +void SetIos(int ios) +{ + appIos = ios; +} + +bool LoadBooter(entrypoint* entry) +{ + dolhdr* dol = (dolhdr*)appboot_bin; + + u32 i; + for (i = 0; i < 7; i++) + { + if (dol->sizeText[i] == 0 || dol->addressText[i] < 0x100) + continue; + + memmove((void*)dol->addressText[i], appboot_bin + dol->offsetText[i], dol->sizeText[i]); + DCFlushRange((void*)dol->addressText[i], dol->sizeText[i]); + } + + for (i = 0; i < 11; i++) + { + if (dol->sizeData[i] == 0) + continue; + + memmove((void*)dol->addressData[i], appboot_bin + dol->offsetData[i], dol->sizeData[i]); + DCFlushRange((void*)dol->addressData[i], dol->sizeData[i]); + } + + *entry = (entrypoint)dol->entrypoint; + + return true; +} diff --git a/source/appboot.h b/source/appboot.h index b5808af..212bc26 100644 --- a/source/appboot.h +++ b/source/appboot.h @@ -1,8 +1,25 @@ #ifndef __APPBOOT_H__ #define __APPBOOT_H__ +typedef void (*entrypoint)(); + +typedef struct _dolhdr +{ + u32 offsetText[7]; + u32 offsetData[11]; + u32 addressText[7]; + u32 addressData[11]; + u32 sizeText[7]; + u32 sizeData[11]; + u32 addressBSS; + u32 sizeBSS; + u32 entrypoint; +} dolhdr; + bool LoadApp(const char* path); u8* GetApp(u32* size); void LaunchApp(void); +void SetIos(int ios); +bool LoadBooter(entrypoint* entry); #endif \ No newline at end of file diff --git a/source/appmetadata.c b/source/appmetadata.c index ad74a52..1d5e4a6 100644 --- a/source/appmetadata.c +++ b/source/appmetadata.c @@ -74,14 +74,21 @@ struct MetaData* LoadMetaData(const char* path) metaData->shortDescription = strdup(GetStringValue(app, "short_description")); metaData->longDescription = strdup(GetStringValue(app, "long_description")); - char release[40]; + char release[20]; memset(release, 0, sizeof(release)); snprintf(release, sizeof(release), "%s", GetStringValue(app, "release_date")); - + + metaData->releaseDate = NULL; if (strlen(release) == 14) + { snprintf(release, sizeof(release), "%c%c/%c%c/%c%c%c%c", release[4], release[5], release[6], release[7], release[0], release[1], release[2], release[3]); - else if (strlen(release) == 14) + metaData->releaseDate = strdup(release); + } + else if (strlen(release) == 12) + { snprintf(release, sizeof(release), "%c%c/%c%c%c%c", release[4], release[5], release[0], release[1], release[2], release[3]); + metaData->releaseDate = strdup(release); + } metaData->releaseDate = strdup(release); mxmlDelete(meta); @@ -122,9 +129,9 @@ char* LoadArguments(const char* path, u16* length) return NULL; } - app = mxmlFindElement(app, app, "arguments", NULL, NULL, MXML_DESCEND_FIRST); + mxml_node_t* arguments = mxmlFindElement(app, app, "arguments", NULL, NULL, MXML_DESCEND_FIRST); - if (!app) + if (!arguments) { mxmlDelete(meta); return NULL; @@ -133,7 +140,7 @@ char* LoadArguments(const char* path, u16* length) mxml_node_t* arg; u16 size = 0; - for (arg = mxmlFindElement(app, app, "arg", NULL, NULL, MXML_DESCEND_FIRST); arg != NULL; arg = mxmlFindElement(arg, app, "arg", NULL, NULL, MXML_NO_DESCEND)) + for (arg = mxmlFindElement(arguments, arguments, "arg", NULL, NULL, MXML_DESCEND_FIRST); arg != NULL; arg = mxmlFindElement(arg, arguments, "arg", NULL, NULL, MXML_NO_DESCEND)) { char* current = GetArgumentValue(arg); @@ -156,7 +163,7 @@ char* LoadArguments(const char* path, u16* length) char* argStr = malloc(size); size = 0; - for (arg = mxmlFindElement(app, app, "arg", NULL, NULL, MXML_DESCEND_FIRST); arg != NULL; arg = mxmlFindElement(arg, app, "arg", NULL, NULL, MXML_NO_DESCEND)) + for (arg = mxmlFindElement(arguments, arguments, "arg", NULL, NULL, MXML_DESCEND_FIRST); arg != NULL; arg = mxmlFindElement(arg, arguments, "arg", NULL, NULL, MXML_NO_DESCEND)) { char* current = GetArgumentValue(arg); @@ -172,6 +179,8 @@ char* LoadArguments(const char* path, u16* length) size += strlen(current); } } + + mxmlDelete(meta); argStr[size] = 0; *length = size; diff --git a/source/boot/Makefile b/source/boot/Makefile index 61bee48..954bd22 100644 --- a/source/boot/Makefile +++ b/source/boot/Makefile @@ -1,46 +1,152 @@ +#--------------------------------------------------------------------------------- +# Clear the implicit built in rules +#--------------------------------------------------------------------------------- -PREFIX = $(DEVKITPPC)/bin/powerpc-eabi- +.SUFFIXES: +#--------------------------------------------------------------------------------- +ifeq ($(strip $(DEVKITPPC)),) +$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=devkitPPC") +endif -AR = $(PREFIX)ar -AS = $(PREFIX)as -CC = $(PREFIX)gcc -CXX = $(PREFIX)g++ -LD = $(PREFIX)ld -OBJCOPY = $(PREFIX)objcopy -RANLIB = $(PREFIX)ranlib -STRIP = $(PREFIX)strip +include $(DEVKITPPC)/wii_rules -MACHDEP = -mcpu=750 -meabi -mhard-float -CFLAGS = $(MACHDEP) -O0 -s -Werror -Wall -fdata-sections -ffunction-sections -LDFLAGS = $(MACHDEP) -n -nostartfiles -nostdlib -Wl,--gc-sections,-T,openstub.ld -L. -ASFLAGS = -D_LANGUAGE_ASSEMBLY -DHW_RVL +#--------------------------------------------------------------------------------- +# 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 := appboot +BUILD := build +SOURCES := source +DATA := data +INCLUDES := -TARGET_LINKED = patcher.elf -TARGET = ../../data/appboot.bin +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- -CFILES = main.c utils.c loaddol.c loadelf.c -OBJS = main.o utils.o loaddol.o loadelf.o +CFLAGS = -g -O2 -Wall $(MACHDEP) $(INCLUDE) +CXXFLAGS = $(CFLAGS) -DEPDIR = .deps +LDFLAGS = -g $(MACHDEP) -Wl,-Map,$(notdir $@).map -Wl,--section-start,.init=0x81330000 -LIBS = +#--------------------------------------------------------------------------------- +# any extra libraries we wish to link with the project +#--------------------------------------------------------------------------------- +LIBS := -lwiiuse -lbte -lfat -logc -lm -all: $(TARGET) +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := + +#--------------------------------------------------------------------------------- +# 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 OUTPUT := $(CURDIR)/$(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))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) + export LD := $(CC) +else + export LD := $(CXX) +endif + +export OFILES := $(addsuffix .o,$(BINFILES)) \ + $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) \ + $(sFILES:.s=.o) $(SFILES:.S=.o) + +#--------------------------------------------------------------------------------- +# build a list of include paths +#--------------------------------------------------------------------------------- +export INCLUDE := $(foreach dir,$(INCLUDES), -iquote $(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) \ + -I$(LIBOGC_INC) + +#--------------------------------------------------------------------------------- +# build a list of library paths +#--------------------------------------------------------------------------------- +export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \ + -L$(LIBOGC_LIB) + +export OUTPUT := $(CURDIR)/$(TARGET) +.PHONY: $(BUILD) clean all + +#--------------------------------------------------------------------------------- +$(BUILD): + @[ -d $@ ] || mkdir -p $@ + @make --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + @mv $(OUTPUT).dol $(OUTPUT).bin + +#--------------------------------------------------------------------------------- +all: $(BUILD) + +#--------------------------------------------------------------------------------- +clean: + @rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).bin + +#--------------------------------------------------------------------------------- +run: + + +#--------------------------------------------------------------------------------- +else + +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- +$(OUTPUT).dol: $(OUTPUT).elf +$(OUTPUT).elf: $(OFILES) + +#--------------------------------------------------------------------------------- +# This rule links in binary data with the .jpg extension +#--------------------------------------------------------------------------------- +%.bin: %.elf + @echo "output ... $(TARGET).bin" + $(Q)$(OBJCOPY) -O binary $< $@ + +%.bin: %.dol + @echo "output ... $(TARGET).bin" + $(Q)$(OBJCOPY) -O binary $< $@ + +%.elf: link.ld $(OFILES) + @echo "linking ... $(TARGET).elf" + $(Q)$(CC) -n -T $^ $(LDFLAGS) -o $@ + +%.o: %.c + @echo "$@" + $(Q)$(CC) $(CFLAGS) -c $< -o $@ %.o: %.s - @$(CC) $(CFLAGS) $(DEFINES) $(ASFLAGS) -c $< -o $@ + @echo "$@" + $(Q)$(CC) $(CFLAGS) -c $< -o $@ -%.o: %.S - @$(CC) $(CFLAGS) $(DEFINES) $(ASFLAGS) -c $< -o $@ +-include $(DEPENDS) -%.o: %.c - @$(CC) $(CFLAGS) $(DEFINES) -c $< -o $@ - -$(TARGET_LINKED): $(OBJS) - @$(CC) -g -o $@ $(LDFLAGS) $(OBJS) $(LIBS) - -$(TARGET): $(TARGET_LINKED) - @$(OBJCOPY) -O binary -S $< $@ - -clean: - @-$(RM) -rf $(TARGET_LINKED) $(OBJS) $(DEPDIR) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- diff --git a/source/boot/loaddol.c b/source/boot/loaddol.c deleted file mode 100644 index 555621a..0000000 --- a/source/boot/loaddol.c +++ /dev/null @@ -1,32 +0,0 @@ - -#include "loaddol.h" - -static void memcopy(void* address, void* buffer, u32 size) -{ - _memcpy(address, buffer, size); - sync_after_write(address, (size + 31) & (~31)); -} - -u32 LoadDol(void* buffer) -{ - u32 i; - struct dolhdr* dol = (struct dolhdr*)buffer; - - for (i = 0; i < 7; i++) - { - if (dol->sizeText[i] == 0) - continue; - - memcopy((void*)dol->addressText[i], buffer + dol->offsetText[i], dol->sizeText[i]); - } - - for (i = 0; i < 11; i++) - { - if (dol->sizeData[i] == 0) - continue; - - memcopy((void*)dol->addressData[i], buffer + dol->offsetData[i], dol->sizeData[i]); - } - - return dol->entrypoint; -} \ No newline at end of file diff --git a/source/boot/loaddol.h b/source/boot/loaddol.h deleted file mode 100644 index 4a12007..0000000 --- a/source/boot/loaddol.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef __DOL_H__ -#define __DOL_H__ - -#include "utils.h" - -struct dolhdr -{ - u32 offsetText[7]; - u32 offsetData[11]; - u32 addressText[7]; - u32 addressData[11]; - u32 sizeText[7]; - u32 sizeData[11]; - u32 addressBSS; - u32 sizeBSS; - u32 entrypoint; -}; - - -u32 LoadDol(void* buffer); - -#endif \ No newline at end of file diff --git a/source/boot/loadelf.c b/source/boot/loadelf.c deleted file mode 100644 index d1ea085..0000000 --- a/source/boot/loadelf.c +++ /dev/null @@ -1,47 +0,0 @@ - -#include "loadelf.h" - -bool ExecIsElf(void* address) -{ - struct Elf32_Ehdr* ehdr = (struct Elf32_Ehdr*)address; - - if (*(u8*)address + 0 != 0x7F || *(u8*)address + 1 != 'E' || *(u8*)address + 2 != 'L' || *(u8*)address + 3 != 'F') - return false; - - if (ehdr->e_type != 2) // Executable - return false; - - if (ehdr->e_machine != 20) // PowerPC - return false; - - return true; -} - -u32 LoadElf(void* address) -{ - int i; - - struct Elf32_Ehdr* ehdr = (struct Elf32_Ehdr*)address; - struct Elf32_Shdr* shdr = (struct Elf32_Shdr*)(address + ehdr->e_shoff + (ehdr->e_shstrndx * sizeof(struct Elf32_Shdr))); - - for (i = 0; i < ehdr->e_shnum; i++) - { - shdr = (struct Elf32_Shdr*)(address + ehdr->e_shoff + (i * sizeof(struct Elf32_Shdr))); - - if (!(shdr->sh_flags & 0x02) || shdr->sh_addr == 0 || shdr->sh_size == 0) - continue; - - shdr->sh_addr &= 0x3FFFFFFF; - shdr->sh_addr |= 0x80000000; - - if (shdr->sh_type == 8) - _memset32((void*)shdr->sh_addr, 0, shdr->sh_size); - else - _memcpy((void*)shdr->sh_addr, (void*)(address + shdr->sh_offset), shdr->sh_size); - - sync_after_write((void*)shdr->sh_addr, (shdr->sh_size + 31) & (~31)); - - } - - return (ehdr->e_entry & 0x3FFFFFFF) | 0x80000000; -} \ No newline at end of file diff --git a/source/boot/loadelf.h b/source/boot/loadelf.h deleted file mode 100644 index 22e6ef1..0000000 --- a/source/boot/loadelf.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef __ELF_H__ -#define __ELF_H__ - -#include "utils.h" - -#define EI_NIDENT 16 - -struct Elf32_Ehdr -{ - u8 e_ident[EI_NIDENT]; - u16 e_type; - u16 e_machine; - u32 e_version; - u32 e_entry; - u32 e_phoff; - u32 e_shoff; - u32 e_flags; - u16 e_ehsize; - u16 e_phentsize; - u16 e_phnum; - u16 e_shentsize; - u16 e_shnum; - u16 e_shstrndx; -}; - -struct Elf32_Shdr -{ - u32 sh_name; - u32 sh_type; - u32 sh_flags; - u32 sh_addr; - u32 sh_offset; - u32 sh_size; - u32 sh_link; - u32 sh_info; - u32 sh_addralign; - u32 sh_entsize; -}; - -struct Elf32_Phdr -{ - u32 p_type; - u32 p_offset; - u32 p_vaddr; - u32 p_paddr; - u32 p_filesz; - u32 p_memsz; - u32 p_flags; - u32 p_align; -}; - -bool ExecIsElf(void* address); -u32 LoadElf(void* address); - -#endif \ No newline at end of file diff --git a/source/boot/main.c b/source/boot/main.c deleted file mode 100644 index 9fb1c9e..0000000 --- a/source/boot/main.c +++ /dev/null @@ -1,40 +0,0 @@ - -#include "loaddol.h" -#include "loadelf.h" -#include "utils.h" - -typedef void (*entrypoint)(); - -void _main(void) -{ - void* buffer = (void*)0x92000000; - entrypoint entry; - - u32 argumentsSize = *(vu32*)0x91000000; - - if (ExecIsElf(buffer)) - entry = (entrypoint)LoadElf(buffer); - else - entry = (entrypoint)LoadDol(buffer); - - if (!entry) - return; - - if (argumentsSize > 0) - { - u32* ptr = (u32*)entry; - - if (ptr[1] == 0x5F617267) - { - struct Arguments* argv = (struct Arguments*)&ptr[2]; - - argv->magic = 0x5F617267; - argv->cmdLine = (char*)0x91000020; - argv->length = argumentsSize; - - sync_after_write(&ptr[2], 4); - } - } - - entry(); -} \ No newline at end of file diff --git a/source/boot/openstub.ld b/source/boot/openstub.ld deleted file mode 100644 index 165168b..0000000 --- a/source/boot/openstub.ld +++ /dev/null @@ -1,15 +0,0 @@ -/* - TinyLoad - a simple region free (original) game launcher in 4k - -# This code is licensed to you under the terms of the GNU GPL, version 2; -# see file COPYING or http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt -*/ - -OUTPUT_FORMAT("elf32-powerpc") -OUTPUT_ARCH(powerpc:common) - -ENTRY(_main) - -SECTIONS { - . = 0x93000000; -} \ No newline at end of file diff --git a/source/boot/source/crt0.s b/source/boot/source/crt0.s new file mode 100644 index 0000000..7a68d74 --- /dev/null +++ b/source/boot/source/crt0.s @@ -0,0 +1,22 @@ +# Copyright 2008-2009 Segher Boessenkool +# This code is licensed to you under the terms of the GNU GPL, version 2; +# see file COPYING or http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt + +.extern _main + .globl _start +_start: + + # Disable interrupts, enable FP. + mfmsr 3 ; rlwinm 3,3,0,17,15 ; ori 3,3,0x2000 ; mtmsr 3 ; isync + + # Setup stack. + lis 1,_stack_top@ha ; addi 1,1,_stack_top@l ; li 0,0 ; stwu 0,-64(1) + + # Clear BSS. + lis 3,__bss_start@ha ; addi 3,3,__bss_start@l + li 4,0 + lis 5,__bss_end@ha ; addi 5,5,__bss_end@l ; sub 5,5,3 + bl _memset32 + + # Go! + bl _main diff --git a/source/boot/source/elf_abi.h b/source/boot/source/elf_abi.h new file mode 100644 index 0000000..4d763a1 --- /dev/null +++ b/source/boot/source/elf_abi.h @@ -0,0 +1,593 @@ +/* + * 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 + +#include + +/* + * This version doesn't work for 64-bit ABIs - Erik. + */ + +/* + * These typedefs need to be handled better. + */ +typedef u32 Elf32_Addr; /* Unsigned program address */ +typedef u32 Elf32_Off; /* Unsigned file offset */ +typedef s32 Elf32_Sword; /* Signed large integer */ +typedef u32 Elf32_Word; /* Unsigned large integer */ +typedef u16 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 ELFCLASS32 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 */ diff --git a/source/boot/source/link.ld b/source/boot/source/link.ld new file mode 100644 index 0000000..d144f55 --- /dev/null +++ b/source/boot/source/link.ld @@ -0,0 +1,27 @@ +/* Copyright 2008-2009 Segher Boessenkool + This code is licensed to you under the terms of the GNU GPL, version 2; + see file COPYING or http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt */ + +OUTPUT_FORMAT("elf32-powerpc") +OUTPUT_ARCH(powerpc:common) + +ENTRY(_start) + +SECTIONS { + . = 0x93300000; + + .start : { crt0.o(*) } + .text : { *(.text) } + .rodata : { *(.rodata .rodata.*)} + .data : { *(.data) } + + __bss_start = .; + .bss : { *(.bss) } + __bss_end = .; + + . = ALIGN(0x40); + .stack : { + . += 0x8000; + _stack_top = .; + } +} diff --git a/source/boot/source/loader.c b/source/boot/source/loader.c new file mode 100644 index 0000000..46e7700 --- /dev/null +++ b/source/boot/source/loader.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include + +#include "loader.h" +#include "elf_abi.h" + +bool ExecIsElf(const u8* buffer) +{ + Elf32_Ehdr* ehdr = (Elf32_Ehdr*)buffer; + + if (!IS_ELF(*ehdr)) + return false; + + if (ehdr->e_ident[EI_CLASS] != ELFCLASS32) + return false; + + if (ehdr->e_ident[EI_DATA] != ELFDATA2MSB) + return false; + + if (ehdr->e_ident[EI_VERSION] != EV_CURRENT) + return false; + + if (ehdr->e_type != ET_EXEC) + return false; + + if (ehdr->e_machine != EM_PPC) + return false; + + return true; +} + +bool LoadElf(entrypoint* entry, const u8* buffer) +{ + int i; + + Elf32_Ehdr* ehdr = (Elf32_Ehdr*)buffer; + + if (ehdr->e_phoff == 0 || ehdr->e_phnum == 0) + return false; + + if (ehdr->e_phentsize != (sizeof(Elf32_Phdr))) + return false; + + Elf32_Phdr* phdrs = (Elf32_Phdr*)(buffer + ehdr->e_phoff); + + for (i = 0; i < ehdr->e_phnum; i++) + { + if (phdrs[i].p_type == PT_LOAD) + { + phdrs[i].p_paddr &= 0x3FFFFFFF; + phdrs[i].p_paddr |= 0x80000000; + + if (phdrs[i].p_filesz > phdrs[i].p_memsz) + return false; + + if (phdrs[i].p_filesz) + { + memmove((void*)phdrs[i].p_paddr, (void*)(buffer + phdrs[i].p_offset), phdrs[i].p_filesz); + DCFlushRange((void*)phdrs[i].p_paddr, phdrs[i].p_memsz); + + if (phdrs[i].p_flags & PF_X) + ICInvalidateRange((void*)phdrs[i].p_paddr, phdrs[i].p_memsz); + } + } + } + + *entry = (entrypoint)((ehdr->e_entry & 0x3FFFFFFF) | 0x80000000); + return true; +} + +bool LoadDol(entrypoint* entry, const u8* buffer) +{ + u32 i; + dolhdr* dol = (dolhdr*)buffer; + + for (i = 0; i < 7; i++) + { + if (dol->sizeText[i] == 0 || dol->addressText[i] < 0x100) + continue; + + //printf(" Move text section %u @ 0x%08x -> 0x%08x (0x%0X bytes)\n", i, (u32)(buffer + dol->offsetText[i]), dol->addressText[i], dol->sizeText[i]); + memmove((void*)dol->addressText[i], buffer + dol->offsetText[i], dol->sizeText[i]); + DCFlushRange((void*)dol->addressText[i], dol->sizeText[i]); + ICInvalidateRange((void*)dol->addressText[i], dol->sizeText[i]); + + } + + for (i = 0; i < 11; i++) + { + if (dol->sizeData[i] == 0) + continue; + + //printf(" Move data section %u @ 0x%08x -> 0x%08x (0x%0X bytes)\n", i, (u32)(buffer + dol->offsetData[i]), dol->addressData[i], dol->sizeData[i]); + memmove((void*)dol->addressData[i], buffer + dol->offsetData[i], dol->sizeData[i]); + DCFlushRange((void*)dol->addressData[i], dol->sizeData[i]); + } + + *entry = (entrypoint)dol->entrypoint; + + return true; +} + diff --git a/source/boot/source/loader.h b/source/boot/source/loader.h new file mode 100644 index 0000000..88f75ab --- /dev/null +++ b/source/boot/source/loader.h @@ -0,0 +1,26 @@ +#ifndef _LOADER_H_ +#define _LOADER_H_ + +#include + +typedef void (*entrypoint) (void); + +typedef struct _dolhdr +{ + u32 offsetText[7]; + u32 offsetData[11]; + u32 addressText[7]; + u32 addressData[11]; + u32 sizeText[7]; + u32 sizeData[11]; + u32 addressBSS; + u32 sizeBSS; + u32 entrypoint; +} dolhdr; + +bool ExecIsElf(const u8* buffer); +bool LoadElf(entrypoint* entry, const u8* buffer); +bool LoadDol(entrypoint* entry, const u8* buffer); + + +#endif \ No newline at end of file diff --git a/source/boot/source/main.c b/source/boot/source/main.c new file mode 100644 index 0000000..43c02d4 --- /dev/null +++ b/source/boot/source/main.c @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "loader.h" + +extern void __exception_setreload(int t); +static void* xfb = NULL; +static GXRModeObj* rmode = NULL; + +struct Arguments +{ + int magic; + char* cmdLine; + int length; +}; + +void VideoInit(void) +{ + VIDEO_Init(); + rmode = VIDEO_GetPreferredMode(NULL); + xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode)); + console_init(xfb,20,20,rmode->fbWidth,rmode->xfbHeight,rmode->fbWidth*VI_DISPLAY_PIX_SZ); + VIDEO_Configure(rmode); + VIDEO_SetNextFramebuffer(xfb); + VIDEO_SetBlack(FALSE); + VIDEO_Flush(); + VIDEO_WaitVSync(); + if(rmode->viTVMode&VI_NON_INTERLACE) + VIDEO_WaitVSync(); + + printf("\x1b[2;0H"); +} + +int main(void) +{ + VideoInit(); + + u8* buffer = (u8*)0x92000000; + entrypoint entry; + bool execLoaded = false; + + if (ExecIsElf(buffer)) + { + //printf(" Loading ELF @ address 0x%08X:\n\n", (u32)buffer); + execLoaded = LoadElf(&entry, buffer); + } + else + { + //printf(" Loading DOL @ address 0x%08X::\n\n", (u32)buffer); + execLoaded = LoadDol(&entry, buffer); + } + + if (!execLoaded) + return -1; + + u8* execPtr = (u8*)entry; + + if (execPtr[0x20] == 0x41) + { + execPtr[0x21] = 0x40; + DCFlushRange(&execPtr[0x20], 1); + } + + u32 argumentsSize = *(vu32*)0x91000000; + if (argumentsSize > 0) + { + u32* ptr = (u32*)entry; + + if (ptr[1] == 0x5F617267) + { + struct Arguments* argv = (struct Arguments*)&ptr[2]; + + argv->magic = 0x5F617267; + argv->cmdLine = (char*)0x91000020; + argv->length = argumentsSize; + + DCFlushRange(&ptr[2], 4); + } + } + + entry(); + return 0; +} diff --git a/source/boot/utils.c b/source/boot/utils.c deleted file mode 100644 index 05d3540..0000000 --- a/source/boot/utils.c +++ /dev/null @@ -1,77 +0,0 @@ -#include "utils.h" - -void sync_before_read(void *ptr, u32 len) -{ - u32 a, b; - - a = (u32)ptr & ~0x1f; - b = ((u32)ptr + len + 0x1f) & ~0x1f; - - for ( ; a < b; a += 32) - asm("dcbi 0,%0" : : "b"(a) : "memory"); - - asm("sync ; isync"); -} - -void sync_after_write(const void *ptr, u32 len) -{ - u32 a, b; - - a = (u32)ptr & ~0x1f; - b = ((u32)ptr + len + 0x1f) & ~0x1f; - - for ( ; a < b; a += 32) - asm("dcbf 0,%0" : : "b"(a)); - - asm("sync ; isync"); -} - -void _memcpy(void *ptr, const void *src, u32 size) -{ - char *ptr2 = ptr; - u32 bsize = size; - const char* src2 = src; - while(size--) *ptr2++ = *src2++; - - sync_after_write(ptr, bsize); -} - -void _memset32(u32 *address, u32 data, u32 length) -{ - while(length--) - *address++ = data; -} - -int _memcmp(const void *s1, const void *s2, size_t n) -{ - unsigned char *us1 = (unsigned char *) s1; - unsigned char *us2 = (unsigned char *) s2; - while(n-- != 0) - { - if (*us1 != *us2) - return (*us1 < *us2) ? -1 : +1; - us1++; - us2++; - } - return 0; -} - -size_t strnlen(const char *s, size_t count) -{ - const char *sc; - - for(sc = s; count-- && *sc != '\0'; ++sc) - /* nothing */; - return sc - s; -} - -inline void write32(u32 dest, u32 value) -{ - *(u32*)dest = value; - sync_after_write((void*)dest, 0x20); -} - -inline u32 read32(u32 src) -{ - return *(u32*)src; -} \ No newline at end of file diff --git a/source/boot/utils.h b/source/boot/utils.h deleted file mode 100644 index bc6b61c..0000000 --- a/source/boot/utils.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef __UTILS_H__ -#define __UTILS_H__ - -typedef unsigned char u8; -typedef unsigned char uint8_t; -typedef unsigned short u16; -typedef unsigned short uint16_t; -typedef unsigned int u32; -typedef unsigned long long u64; - -typedef int bool; -typedef unsigned int sec_t; - -typedef signed char s8; -typedef signed short s16; -typedef signed int s32; -typedef signed long long s64; - -typedef volatile unsigned char vu8; -typedef volatile unsigned short vu16; -typedef volatile unsigned int vu32; -typedef volatile unsigned long long vu64; - -typedef volatile signed char vs8; -typedef volatile signed short vs16; -typedef volatile signed int vs32; -typedef volatile signed long long vs64; - -typedef s32 size_t; -typedef u32 u_int32_t; - - -struct Arguments -{ - int magic; - char* cmdLine; - int length; -}; - -#define NULL ((void*)0) -#define true 1 -#define false 0 -#define IsWiiU ((*(u32*)0xcd8005A0 >> 16 ) == 0xCAFE) - -void sync_before_read(void* ptr, u32 len); -void sync_after_write(const void* ptr, u32 len); -void _memcpy(void *ptr, const void *src, u32 size); -void _memset32(unsigned int *addr, unsigned int data, unsigned int count); -int _memcmp(const void *s1, const void *s2, size_t n); -size_t strnlen(const char *s, size_t count); -void write32(u32 value, u32 dest); -u32 read32(u32 src); - -#endif \ No newline at end of file