Fix the module reading code

This commit is contained in:
Maschell 2022-02-13 14:47:47 +01:00
parent dcec3f7165
commit b247427427
3 changed files with 72 additions and 17 deletions

View File

@ -17,6 +17,7 @@
#include "ModuleDataFactory.h"
#include "ElfUtils.h"
#include "utils/FileUtils.h"
#include "utils/utils.h"
#include <coreinit/cache.h>
#include <map>
@ -31,29 +32,18 @@ ModuleDataFactory::load(const std::string &path, uint32_t *destination_address_p
elfio reader;
std::shared_ptr<ModuleData> moduleData = std::make_shared<ModuleData>();
FILE *f = fopen(path.c_str(), "rb");
fseek(f, 0, SEEK_END);
auto fsize = ftell(f);
fseek(f, 0, SEEK_SET);
auto *buffer = static_cast<char *>(memalign(0x40, ROUNDUP(fsize + 1, 0x40)));
if (!buffer) {
fclose(f);
DEBUG_FUNCTION_LINE("Failed to allocate buffer");
}
if ((long) fread(buffer, fsize, 1, f) != fsize) {
DEBUG_FUNCTION_LINE("Failed to load data into buffer");
free(buffer);
fclose(f);
uint8_t *buffer = nullptr;
uint32_t fsize = 0;
if (LoadFileToMem(path.c_str(), &buffer, &fsize) < 0) {
DEBUG_FUNCTION_LINE("Failed to load file");
return {};
}
fclose(f);
// Load ELF data
if (!reader.load(buffer, fsize)) {
if (!reader.load(reinterpret_cast<char *>(buffer), fsize)) {
DEBUG_FUNCTION_LINE("Can't find or process %s", path.c_str());
free(buffer);
return std::nullopt;
return {};
}
uint32_t sec_num = reader.sections.size();

View File

@ -0,0 +1,62 @@
#include <fcntl.h>
#include <malloc.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define ROUNDDOWN(val, align) ((val) & ~(align - 1))
#define ROUNDUP(val, align) ROUNDDOWN(((val) + (align - 1)), align)
int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size) {
//! always initialze input
*inbuffer = NULL;
if (size) {
*size = 0;
}
int32_t iFd = open(filepath, O_RDONLY);
if (iFd < 0) {
return -1;
}
uint32_t filesize = lseek(iFd, 0, SEEK_END);
lseek(iFd, 0, SEEK_SET);
auto *buffer = (uint8_t *) memalign(0x40, ROUNDUP(filesize, 0x40));
if (buffer == nullptr) {
close(iFd);
return -2;
}
uint32_t blocksize = 0x20000;
uint32_t done = 0;
int32_t readBytes = 0;
while (done < filesize) {
if (done + blocksize > filesize) {
blocksize = filesize - done;
}
readBytes = read(iFd, buffer + done, blocksize);
if (readBytes <= 0)
break;
done += readBytes;
}
::close(iFd);
if (done != filesize) {
free(buffer);
buffer = nullptr;
return -3;
}
*inbuffer = buffer;
//! sign is optional input
if (size) {
*size = filesize;
}
return filesize;
}

3
source/utils/FileUtils.h Normal file
View File

@ -0,0 +1,3 @@
#pragma once
int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size);