-
Notifications
You must be signed in to change notification settings - Fork 0
/
gerador_elf.cpp
611 lines (531 loc) · 16.8 KB
/
gerador_elf.cpp
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#include <fstream>
#include <typeinfo>
#include <elfio/elfio.hpp>
#include "gerador_elf.hpp"
#include <sstream>
#include <string>
#include <algorithm>
#include <stdint.h>
#include <iomanip>
GeradorElf::GeradorElf(std::string namefile) {
this->file.open(namefile);
if (!this->file.is_open()) {
}
this->currentDataPosition = 0x08049098;
this->currentTextPosition = 0x08048080;
}
char GeradorElf::convertToHex(char c) {
switch(c) {
case '1' : return '\x1';
case '2' : return '\x2';
case '3' : return '\x3';
case '4' : return '\x4';
case '5' : return '\x5';
case '6' : return '\x6';
case '7' : return '\x7';
case '8' : return '\x8';
case '9' : return '\x9';
case 'a' : return '\xA';
case 'b' : return '\xB';
case 'c' : return '\xC';
case 'd' : return '\xD';
case 'e' : return '\xE';
case 'f' : return '\xF';
default : return 0;
}
}
std::string GeradorElf::undercase( std::string data ) {
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
return data;
}
bool GeradorElf::isRegister ( std::string name ) {
if (name == "eax" || name == "ebx" || name == "ecx" || name == "edx" ||
name == "esp" || name == "ebp" || name == "ebi" || name == "esi") {
return true;
} else {
return false;
}
}
bool GeradorElf::isMemory ( std::string name ) {
return (name.front() == '[' && name.back() == ']') ? true : false;
}
bool GeradorElf::isImmediate ( std::string name ) {
return (!this->isRegister(this->filterMemory(name))
&& !this->isMemory(name)) ? true : false;
}
std::string GeradorElf::filterMemory( std::string op ) {
std::string newOp = "";
for (unsigned int i = 0; i < op.length(); ++i) {
if (op[i] != '[' && op[i] != ']' && op[i] != ' ') {
newOp += op[i];
}
}
return newOp;
}
dataNode GeradorElf::findSymbol( std::string op ) {
dataNode node;
for (auto symbol : this->symbols) {
if (op == symbol.symbol) {
node = symbol;
break;
}
}
return node;
}
long long int GeradorElf::reverseNumber ( long long int number ) {
long long int reverse = 0;
long long int aux = 0;
int i = sizeof(number) / 2;
while(i != 0) {
aux = number % 0x100LL;
reverse = (reverse) | aux;
reverse = reverse << 2 * 4;
number /= 0x100LL;
i--;
}
reverse = reverse >> 2 * 4;
return reverse;
}
long long int GeradorElf::getRegistersNumber ( std::string reg ) {
reg = this->undercase(reg);
if( reg =="eax" ) return 0x0;
if( reg =="ecx" ) return 0x1;
if( reg =="edx" ) return 0x2;
if( reg =="ebx" ) return 0x3;
if( reg =="esi" ) return 0x6;
if( reg =="edi" ) return 0x7;
return 0x0;
}
long long int GeradorElf::hexParamater( std::string op ) {
long long int number;
op = this->undercase( op );
unsigned int length = op.length();
if (op[length - 1] == 'h') {
op.pop_back();
std::istringstream iss(op);
iss >> std::hex >> number;
}
if (op[0] == '0' && op[1] == 'x') {
std::string aux = op.substr(2, length);
std::istringstream iss(aux);
iss >> std::hex >> number;
}
return number;
}
int GeradorElf::numberOfDigits( long long int number, int base ) {
int number_of_digits = 0;
do {
++number_of_digits;
number /= base;;
} while (number);
return number_of_digits;
}
labelNode GeradorElf::findLabel( std::string op ) {
labelNode n;
bool founded = false;
for ( auto node : this->labels ) {
if ( node.label == op ) {
n = node;
founded = true;
}
}
if ( !founded ) {
this->storeLabel( op , -1LL );
n.address = -1;
n.label = op;
}
return n;
}
void GeradorElf::assemble(textNode& node) {
dataNode memoryAccess;
node.code = 0x0;
node.valid = false;
if (this->undercase(node.instruction) == "mov") {
if (isRegister(node.op1)
&& isMemory(this->removeMultipleSpaces(node.op2))) {
node.op2 = this->filterMemory( node.op2 );
if (!isRegister(node.op2)) {
memoryAccess = this->findSymbol( node.op2 );
if (node.op1 == "eax") {
int size = sizeof(memoryAccess.position);
node.code = (0xA1LL << size * 4) |
this->reverseNumber(memoryAccess.position);
}
}
} else if (isRegister(node.op1) && isImmediate(node.op2)) {
long long int immediate = 0x0;
node.code = 0xB8LL + this->getRegistersNumber(node.op1);
std::istringstream iss(node.op2);
iss >> std::hex >> immediate;
int size = sizeof(immediate);
node.code = (node.code << size * 4) | this->reverseNumber(immediate);
} else if (isRegister(node.op1) && isMemory(node.op2)) {
node.op2 = this->filterMemory( node.op2 );
if (!isRegister(node.op2)) {
node.code = 0xB8LL + this->getRegistersNumber(node.op1);
memoryAccess = this->findSymbol( node.op2 );
int size = sizeof(memoryAccess.position);
node.code = (node.code << size * 4) |
this->reverseNumber(memoryAccess.position);
}
}
node.valid = true;
}
if (this->undercase(node.instruction) == "add") {
if (isRegister(node.op1) &&
isMemory(this->removeMultipleSpaces(node.op2))) {
node.op2 = this->filterMemory( node.op2 );
if (!this->isRegister(node.op2))
memoryAccess = this->findSymbol( node.op2 );
if (node.op1 == "eax") {
int size = sizeof(memoryAccess.position);
node.code = (0x0305LL << size * 4)
| this->reverseNumber(memoryAccess.position);
}
}
node.valid = true;
}
if (this->undercase(node.instruction) == "int") {
long long int code = this->hexParamater( node.op1 );
int size = this->numberOfDigits(code, 16);
node.code = (0xCDLL << size * 4) | code;
node.valid = true;
}
if (this->undercase(node.instruction) == "push") {
if ( !this->isRegister(node.op1) ) {
memoryAccess = this->findSymbol( node.op1 );
int size = sizeof(memoryAccess.position);
node.code = (0x68LL << size * 4) |
this->reverseNumber(memoryAccess.position);
node.valid = true;
}
}
if (this->undercase(node.instruction) == "call") {
if ( !this->isRegister(node.op1) && !this->isMemory(node.op1)) {
labelNode label = this->findLabel( node.op1 );
if (label.address == -1) {
int size = sizeof(label.address);
node.label = this->currentLabel;
node.code = (0xE8LL << size * 4);
node.valid = false;
node.jump = label.label;
// avanca pc
long long int count = this->numberOfDigits(node.code, 16) / 2;
if (this->numberOfDigits(node.code, 16) % 2 != 0) count += 0x1;
this->currentTextPosition += count;
}
}
}
if (this->undercase(node.instruction) == "mul") {
if ( this->isMemory(node.op2) ) {
node.op2 = this->filterMemory(node.op2);
if ( !this->isRegister( node.op2 ) ) {
memoryAccess = this->findSymbol( node.op2 );
int size = sizeof(memoryAccess.position);
node.code = (0xF725LL << size * 4) |
this->reverseNumber(memoryAccess.position);
node.valid = true;
}
}
}
if (this->undercase(node.instruction) == "div") {
if ( this->isMemory(node.op2) ) {
node.op2 = this->filterMemory(node.op2);
if ( !this->isRegister( node.op2 ) ) {
memoryAccess = this->findSymbol( node.op2 );
int size = sizeof(memoryAccess.position);
node.code = (0xF735LL << size * 4) |
this->reverseNumber(memoryAccess.position);
node.valid = true;
}
}
}
if ( node.valid ) {
long long int count = this->numberOfDigits(node.code, 16) / 2;
if (this->numberOfDigits(node.code, 16) % 2 != 0) count += 0x1;
this->currentTextPosition += count;
node.label = this->currentLabel;
}
}
bool GeradorElf::isString( dataNode node ) {
return node.value[0] == '\'' ? true : false ;
}
dataNode GeradorElf::processDataNode( dataNode node ) {
std::string complementString = "";
int complement = 0;
int times = std::stoi(node.times);
if (node.type == "dd" && !this->isString(node) ) {
for (unsigned int i = 0; i < node.value.length(); ++i) {
node.value[i] = this->convertToHex(node.value[i]);
}
complement = (8 - node.value.length()) / 2;
while(complement != 0) {
complementString += '\x0';
complement--;
}
node.value = node.value + complementString;
node.position = this->currentDataPosition * times;
currentDataPosition += times * 8 / 2;
}
if (node.type == "dw" && !this->isString(node) ) {
for (unsigned int i = 0; i < node.value.length(); ++i) {
node.value[i] = this->convertToHex(node.value[i]);
}
complement = (4 - node.value.length()) / 2;
while(complement != 0) {
complementString += '\x0';
complement--;
}
node.value = node.value + complementString;
node.position = this->currentDataPosition * times;
currentDataPosition += times * 4 / 2;
}
if (node.type == "db" && !this->isString(node) ) {
for (unsigned int i = 0; i < node.value.length(); ++i) {
node.value[i] = this->convertToHex(node.value[i]);
}
complement = (2 - node.value.length()) / 2;
while(complement != 0) {
complementString += '\x0';
complement--;
}
node.value = node.value + complementString;
node.position = this->currentDataPosition * times;
currentDataPosition += times * 2 / 2;
}
return node;
}
std::string GeradorElf::getToken( std::string& line ) {
std::string token;
int found = line.find(" ");
int length = line.length();
token = line.substr(0, found);
line = line.substr(found + 1, length - 1);
return token;
}
dataNode GeradorElf::processDataLine(std::string line) {
dataNode node;
line = this->removeMultipleSpaces( line );
node.symbol = this->getToken( line );
if( !line.empty() ) node.type = this->getToken( line );
if( !line.empty() ) node.value = this->getToken( line );
if( !line.empty() && node.type == "times") {
node.times = node.value;
node.type = this->getToken( line );
node.value = this->getToken( line );
} else {
node.times = "1";
}
node = this->processDataNode( node );
return node;
}
bool Both_are_spaces(char lhs, char rhs) {
return (lhs == rhs) && (lhs == ' ');
}
// recebe uma linha e remove multiplos espaços consecutivos
std::string GeradorElf::removeMultipleSpaces(std::string line) {
std::string newline;
std::string::iterator new_end = std::unique(line.begin(), line.end(),
Both_are_spaces);
line.erase(new_end, line.end());
newline = line;
// caso a linha comece com um espaço, esse espaço é removido.
if (newline[0] == ' ') {
newline.erase(0, 1);
}
return newline;
}
std::string GeradorElf::getOp2( std::string& line ) {
std::string op = "";
op = line.substr( 0, line.length() );
line = "";
return op;
}
std::string GeradorElf::getOp1( std::string& line ) {
std::string op = "";
int foundComma = line.find( "," );
int foundSpace = line.find( " " );
int endLine = line.find( "\n" );
if (foundComma != -1) {
op = line.substr(0,foundComma);
line = line.substr(foundComma + 1, line.length());
} else if (foundSpace != -1 && foundComma == -1) {
op = line.substr(0,foundSpace);
line = line.substr(foundSpace + 1, line.length());
} else if ( op.empty() ) {
op = line.substr( 0, endLine );
line = "";
}
return op;
}
std::string GeradorElf::getInstruction( std::string& line ) {
std::string instruction = "";
int found = line.find( " " );
if (found != -1) {
instruction = line.substr(0,found);
line = line.substr(found + 1, line.length());
}
return instruction;
}
void GeradorElf::storeLabel( std::string line, long long int address ) {
labelNode node;
node.label = line;
node.address = address;
for (unsigned int i = 0; i < this->labels.size(); i++) {
if ( this->labels[i].label == node.label ) {
if ( this->labels[i].address == -1LL ) {
this->labels[i].address = address;
}
}
}
if (address != -1LL) {
this->labels.push_back( node );
this->currentLabel = line;
}
}
std::string GeradorElf::getLabel( std::string& line ) {
std::string label = "";
int found = line.find( ":" );
if (found != -1) {
label = line.substr(0,found);
line = line.substr(found + 1, line.length());
}
if (line.substr(0, 6) == "global") {
line = line.substr(7, line.length());
}
return label;
}
textNode GeradorElf::processTextLine(std::string line) {
textNode node;
std::string aux = "";
std::string label = "";
line = this->removeMultipleSpaces( line );
label = this->getLabel( line );
line = this->removeMultipleSpaces(line);
if ( label == "global" ) {
label = line.substr(7, line.length());
this->entryPoint.label = label;
this->entryPoint.address = this->currentTextPosition;
}
if ( !line.empty() ) {
node.instruction = this->getInstruction( line );
}
// labels comums
else if ( (!label.empty()) && label != "global") {
this->storeLabel( label, this->currentTextPosition );
}
if( !line.empty() ) node.op1 = this->getOp1( line );
if( !line.empty() ) node.op2 = this->getOp2( line );
this->assemble( node );
return node;
}
void GeradorElf::readFile() {
std::string line;
bool allowRead = false;
dataNode datanode;
textNode textnode;
// vamos focar em achar a section data
while ( getline( this->file, line ) ) {
if ( line == "section .data" ) {
allowRead = true;
continue;
}
if ( line.empty() ) allowRead = false;
if ( allowRead ) {
this->symbols.push_back(this->processDataLine( line ));
}
}
// resetamos o ponteiro do arquivo para o inicio
this->file.clear();
this->file.seekg(0, this->file.beg);
// agora podemos ler as instruções e ignorar a sessão data
while( getline(this->file, line) ) {
line = this->removeMultipleSpaces( line );
if ( line == "section .data" ) allowRead = false;
if ( line.empty() ) {
allowRead = true;
continue;
}
if ( line == "section .text" ) {
allowRead = true;
continue;
}
if ( allowRead )
this->instructions.push_back(this->processTextLine( line ));
}
}
std::string GeradorElf::convertInstructions( std::string text ) {
std::string newText = "";
for (unsigned int i = 0; i < text.length(); i+=2) {
std::string byte = text.substr(i,2);
char chr = (char) (int) strtol( byte.c_str(), NULL, 16 );
newText.push_back(chr);
}
return newText;
}
void GeradorElf::createFile() {
for (auto l : this->labels) {
for (unsigned int i = 0; i < this->instructions.size(); ++i) {
if ( !this->instructions[i].valid &&
this->instructions[i].jump == l.label ) {
labelNode ln = this->findLabel(this->instructions[i].jump);
this->instructions[i].code = this->instructions[i].code | ln.address;
this->instructions[i].valid = true;
}
}
}
std::string data = "";
for (auto dNode : this->symbols) {
int times = std::stoi( dNode.times );
for (int i = 0; i < times; i++ ) data += dNode.value;
};
ELFIO::elfio writer;
writer.create( ELFCLASS32, ELFDATA2LSB );
writer.set_os_abi( ELFOSABI_LINUX );
writer.set_type( ET_EXEC );
writer.set_machine( EM_386 );
ELFIO::section* data_sec = writer.sections.add( ".data" );
data_sec->set_type( SHT_PROGBITS );
data_sec->set_flags( SHF_ALLOC | SHF_WRITE );
data_sec->set_addr_align( 0x4 );
// data_sec->set_data( data, sizeof( data ) );
data_sec->set_data( data );
ELFIO::segment* data_seg = writer.segments.add();
data_seg->set_type( PT_LOAD );
data_seg->set_virtual_address( 0x08049098 );
data_seg->set_physical_address( 0x08049098 );
data_seg->set_flags( PF_W | PF_R );
data_seg->set_align( 0x10 );
data_seg->add_section_index( data_sec->get_index(),
data_sec->get_addr_align() );
for ( auto label : this->labels ) {
std::string text = "";
std::string textResult = "";
for ( auto i : this->instructions ) {
if ( i.valid && i.label == label.label) {
std::stringstream stream;
stream << std::hex << i.code;
std::string result( stream.str() );
if (result.length() % 2 != 0) result.insert(0, "0");
text += result;
}
};
textResult = this->convertInstructions( text );
ELFIO::section* text_sec = writer.sections.add(label.label);
text_sec->set_type(SHT_PROGBITS);
text_sec->set_flags( SHF_ALLOC | SHF_EXECINSTR );
text_sec->set_addr_align( 0x10 );
// text_sec->set_data( text, sizeof( text ) );
text_sec->set_data( textResult );
ELFIO::segment* text_seg = writer.segments.add();
text_seg->set_type( PT_LOAD );
text_seg->set_virtual_address( label.address );
text_seg->set_physical_address( label.address );
text_seg->set_flags( PF_X | PF_R );
text_seg->set_align( 0x1000 );
text_seg->add_section_index( text_sec->get_index(),
text_sec->get_addr_align() );
}
writer.set_entry( this->entryPoint.address );
writer.save( "output" );
}