-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIIPU.cpp
More file actions
238 lines (187 loc) · 16.4 KB
/
IIPU.cpp
File metadata and controls
238 lines (187 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#include "IIPU.h"
const char* action = NULL;
static std::vector<uint8_t> Unpack(
const std::string& sourceFileName,
uint32_t dataOffset,
uint32_t size
) {
std::ifstream sourceFile(sourceFileName, std::ios::binary);
if (!sourceFile.is_open()) {
std::cerr << "Error opening input file: " << sourceFileName << std::endl; exit(1);
}
sourceFile.seekg(dataOffset);
std::vector<uint8_t> sourceBuffer(size); // Это запакованные данные
sourceFile.read((char*)sourceBuffer.data(), size);
sourceFile.close();
std::vector<uint8_t> outputBuffer(size); // Это распакованные данные
uint32_t index = 0; // Текущее смещение в sourceFile
bool exceptionTrigger = false;
// Пропуск функции, если размер файла на входе равен 0
if (size == 0) {
std::cerr << "Input file is empty: " << sourceFileName << std::endl;
outputBuffer.clear();
return outputBuffer;
}
// Алгоритм распаковки
while (true) {
if (index >= size)
{
break;
}
if (sourceBuffer[index] == 0) {
if (exceptionTrigger == false) {
std::cerr << "INI_PACK is possibly corrupted, found null-byte at offset 0x" << std::hex << index << std::endl << "Continuing nevertheless..." << std::endl;
exceptionTrigger = true;
}
index++;
continue;
}
outputBuffer[index] = sourceBuffer[index] - sourceBuffer[index] / 2;
index++;
}
action = "Unpack";
return outputBuffer;
}
static std::vector<uint8_t> Compress(
const std::string& sourceFileName, //argv[4]
uint32_t unpackedSize,
uint32_t& packedSize
)
{
std::ifstream sourceFile(sourceFileName, std::ios::binary | std::ios::ate); // Модификатор ate is crucial
if (!sourceFile.is_open()) {
std::cerr << "Error opening source file on compression: " << sourceFileName << std::endl; exit(1);
}
std::vector<uint8_t> buffer;
std::streamsize fileSize = sourceFile.tellg();
// Если файл пустой, превышает исходный размер или ошибка чтения размера
if ((fileSize <= 0) || (fileSize > unpackedSize)) {
buffer.clear();
return buffer;
}
buffer.resize(static_cast<uint32_t>(unpackedSize)); // Выделение памяти для sourceBuffer равное fileSize
sourceFile.seekg(0, std::ios::beg);
sourceFile.read((char*)buffer.data(), unpackedSize); // Сохранение данных sourceFile в sourceBuffer
sourceFile.close(); // Buffer получен, можно закрывать файл
uint32_t index = 0; // Текущее смещение в sourceFile
// Алгоритм запаковки
while (true) {
if (index >= fileSize)
{
break;
}
if (buffer[index] > 0x80) {
std::cerr << "Invalid ini, found forbidden char at offset " << std::hex << index << std::endl;
buffer.clear();
return buffer;
}
buffer[index] = buffer[index] + buffer[index];
index++;
}
action = "Compress";
packedSize = fileSize; // Сжатие не применяется, поэтому размеры равны
return buffer;
}
int main(int argc, char* argv[])
{
system("cls");
// Обработка аргументов, получение имения файла в fileName
if (argc < 2 && 4 > argc) {
printf("\rUsage: xxx.efi [action] <INI file>\n\nActions:\n\t-r\t\tReplace INI_PACK contents\n\n");
return 1;
}
// Debug
//printf("Args count: %d\n", argc);
std::cout << "Loading..." << std::endl;
// Общие переменные
const std::string fileName = argv[1];
action = argv[2];
uint32_t align = NULL;
uint32_t rawSize = NULL;
std::vector<uint8_t> unpackedData;
std::vector<uint32_t> offsets = { 0 };
std::string signature = (std::string)"24494E495F5041434B"; // Сигнатура $INI_PACK
uint8_t sigCount = IFLASHcountHexPattern(fileName, signature, offsets);
// Переменные для Replace
uint32_t packedSize = NULL;
uint32_t packedDiff = NULL;
std::vector<uint8_t> efiFileData;
std::vector<uint8_t> packedData;
if (sigCount == 0) {
std::cerr << "There's something wrong with the input file... INI_PACK is missing" << std::endl;
return 1;
}
std::ifstream sourceFile(fileName, std::ios::binary);
if (!sourceFile.is_open()) {
std::cerr << "Error opening source file while getting INI_PACK size: " << fileName << std::endl;
return 1;
}
sourceFile.seekg(offsets[0] + 0xD); // 0xD - относительное смещение значения dataSize
sourceFile.read(reinterpret_cast<char*>(&rawSize), 0x4); // Получить rawSize
sourceFile.seekg(offsets[0] + 0x9); // 0x9 - относительное смещение значения align
sourceFile.read(reinterpret_cast<char*>(&align), 0x4); // Получить align
printf("\nSuccessfully found INI_PACK at offset: 0x%X\nData size: 0x%X\n", (int)offsets[0], rawSize);
// Проверка сколько сигнатур нашло
if (!(sigCount > 1)) {
switch (argc) {
case 2:
// Сохранить запакованные данные
saveDataByOffset(fileName, (std::string)"INI_PACK.bin", offsets[0] + align, rawSize);
// Создать распакованный файл
unpackedData = Unpack(fileName, offsets[0] + align, rawSize);
saveBufferToFile((std::string)"INI_PACK.txt", unpackedData, rawSize);
break;
case 4:
// Процедура запаковки и замены
if (action != (std::string)"-r") { action = NULL; break; }
packedData = Compress(argv[3], rawSize, packedSize);
if (packedData.size() <= 1) { printf("Failed to compress the file: empty data\n"); return 1; }
// Сохранение всего efi файла в буфер
saveFileToBuffer(fileName, efiFileData);
// Стереть старый модуль из буфера
for (uint32_t i = 0; i < rawSize; i++) {
efiFileData.erase(efiFileData.begin() + offsets[0] + align);
}
// Вставить запакованный файл
for (size_t i = packedData.size() - 1; i > 0; i--) {
efiFileData.insert(efiFileData.begin() + offsets[0] + align, packedData[i]);
}
efiFileData.insert(efiFileData.begin() + offsets[0] + align, packedData[0]);
// Простое выявление большего значения и присвоение разницы
packedDiff = rawSize >= packedData.size() ? (rawSize - packedData.size()) : NULL;
// Debug
//printf("packedDiff 0x%X - 0x%X\n", rawSize, packedData.size());
// Убрать разницу в размерах. "(fileSize - romBlockSize)" это вычисление смещения romBlock. 4 - отступ для chksum bytes
if (rawSize >= packedData.size()) {
//Увеличить Rom, т.к. размер ориг ini, был больше чем размер данных для вставки (packedData.size)
for (uint32_t i = 0; i < packedDiff; i++) {
efiFileData.insert(efiFileData.begin() + offsets[0] + align + packedData.size(), 0x0);
}
}
else
{
printf("\nUh-oh, the new INI is so big it overpals with other data! Offset: 0x%X.\nNot doing replacement\n", offsets[0] + align + packedSize + 1);
return 1;
}
std::cout << std::endl << "Saving re-packed INI to " << "new" << fileName << "..." << std::endl;
saveBufferToFile((std::string)"new" + fileName, efiFileData, efiFileData.size());
action = "Replace";
break;
default:
// Если кол-во аргументов ни одно из заявленных
std::cerr << std::endl << "Incorrect command!" << std::endl;
return 1;
}
if (action == NULL) {
std::cerr << std::endl << "Command failed!" << std::endl;
return 1;
}
}
else
{
std::cerr << "There's more than 1 INI_PACK in the source file" << std::endl << "Unable to pick one" << std::endl;
return 1;
}
std::cout << std::endl << action <<" performed successfully!" << std::endl; //Если дошло до конца, вывод текста
return 0;
}