-
Notifications
You must be signed in to change notification settings - Fork 150
/
image.C
2141 lines (1823 loc) · 66.6 KB
/
image.C
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* See the dyninst/COPYRIGHT file for copyright information.
*
* We provide the Paradyn Tools (below described as "Paradyn")
* on an AS IS basis, and do not warrant its validity or performance.
* We reserve the right to update, modify, or discontinue this
* software at any time. We shall have no obligation to supply such
* updates or modifications or any other form of support to you.
*
* By your use of Paradyn, you understand and agree that we (or any
* other person or entity with proprietary rights in Paradyn) are
* under no obligation to provide either maintenance services,
* update services, notices of latent defects, or correction of
* defects for Paradyn.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <string>
#include <fstream>
#include "image.h"
#include "common/src/arch.h"
#include "parRegion.h"
#include "util.h"
#include "inst.h"
#include "debug.h"
#include "function.h"
#include "Parsing.h"
#include "common/src/Timer.h"
#include "common/src/debugOstream.h"
#include "common/src/pathName.h"
#include "common/src/MappedFile.h"
#include "dyninstAPI/h/BPatch_flowGraph.h"
#include "common/h/util.h"
#include "symtabAPI/h/Function.h"
#include "parseAPI/h/InstructionSource.h"
#include "parseAPI/h/CodeObject.h"
#include "parseAPI/h/CFG.h"
#include "dataflowAPI/h/AbslocInterface.h"
#include "dataflowAPI/h/SymEval.h"
#if defined(TIMED_PARSE)
#include <sys/time.h>
#endif
#if defined( cap_dwarf )
#include "dwarf.h"
#include "libdwarf.h"
#endif
#if defined(_MSC_VER)
#include <dbghelp.h>
#endif
#if defined(os_vxworks)
#include "dyninstAPI/src/vxworks.h"
#endif
// For callbacks
#include "dyninstAPI/src/mapped_object.h"
AnnotationClass<image_variable> ImageVariableUpPtrAnno("ImageVariableUpPtrAnno", NULL);
AnnotationClass<parse_func> ImageFuncUpPtrAnno("ImageFuncUpPtrAnno", NULL);
pdvector<image*> allImages;
using namespace std;
using namespace Dyninst;
using namespace Dyninst::ParseAPI;
using Dyninst::SymtabAPI::Symtab;
using Dyninst::SymtabAPI::Symbol;
using Dyninst::SymtabAPI::Region;
using Dyninst::SymtabAPI::Variable;
using Dyninst::SymtabAPI::Module;
char main_function_names[NUMBER_OF_MAIN_POSSIBILITIES][20] = {
"main",
"DYNINST_pltMain",
"_main",
"WinMain",
"_WinMain",
"wWinMain",
"_wWinMain",
"tls_cb_0"};
string fileDescriptor::emptyString(string(""));
fileDescriptor::fileDescriptor():
code_(0), data_(0), dynamic_(0), shared_(false),
pid_(0), length_(0), rawPtr_(NULL)
{
// This shouldn't be called... must be public for pdvector, though
}
bool fileDescriptor::IsEqual(const fileDescriptor &fd) const {
// Don't test isShared, only file name and addresses
bool file_match_ = false;
// Annoying... we often get "foo vs ./foo" or such. So consider it a match
// if either file name is prefixed by the other; we don't get trailing crud.
string::size_type len1 = file_.length();
string::size_type len2 = fd.file_.length();
if(((len1>=len2) && (file_.substr(len1-len2,len2) == fd.file_))
|| ((len2>len1) && (fd.file_.substr(len2-len1,len1) == file_)))
file_match_ = true;
#if defined(os_linux)
struct stat buf1;
struct stat buf2;
if (!stat(file_.c_str(),&buf1)
&& !stat(fd.file_.c_str(),&buf2)
&& buf1.st_ino == buf2.st_ino) {
file_match_ = true;
}
#endif
#if defined(os_windows)
if(extract_pathname_tail(file_) == extract_pathname_tail(fd.file_)) file_match_ = true;
#endif
#if 0
cerr << hex << "Addr comparison: " << code_ << " ? " << fd.code_
<< ", " << data_ << " ? " << fd.data_
<< ", " << dynamic_ << " ? " << fd.dynamic_ << dec << endl;
#endif
bool addr_match = ((code_ == fd.code_ && data_ == fd.data_) ||
(dynamic_ && dynamic_ == fd.dynamic_));
#if 0
cerr << "file " << file_match_
<< ", addr " << addr_match
<< ", member_ " << (member_ == fd.member_)
<< ", pid_ " << (pid_ == fd.pid_) << endl;
#endif
if (file_match_ &&
(addr_match) &&
(member_ == fd.member_) &&
(pid_ == fd.pid_))
return true;
else
return false;
}
// only for non-files
void* fileDescriptor::rawPtr()
{
#if defined(os_windows)
return rawPtr_;
#else
return NULL;
#endif
}
// All debug_ostream vrbles are defined in process.C (for no particular reason)
extern unsigned enable_pd_sharedobj_debug;
int codeBytesSeen = 0;
#if defined(ppc32_linux) || defined(ppc32_bgp) || defined(ppc64_linux) || defined(ppc64_bgq)
#include <dataflowAPI/h/slicing.h>
#include <dataflowAPI/h/SymEval.h>
#include <dataflowAPI/h/AbslocInterface.h>
#include <dataflowAPI/h/Absloc.h>
#include <common/h/DynAST.h>
namespace {
/* On PPC GLIBC (32 & 64 bit) the address of main is in a structure
located in either .data or .rodata, depending on whether the
binary is PIC. The structure has the following format:
struct
{
void * // "small data area base"
main // pointer to main
init // pointer to init
fini // pointer to fini
}
This structure is passed in GR8 as an argument to libc_start_main.
Annoyingly, the value in GR8 is computed in several different ways,
depending on how GLIBC was compiled.
This code follows the i386 linux version closely otherwise.
*/
class Default_Predicates : public Slicer::Predicates {};
/* This visitor is capable of simplifying constant value computations
that involve additions and concatenations (lis instruction). This
is sufficient to handle the startup struct address calculation in
GLIBC that we have seen; if additional variants are introduced
(refer to start.S in glibc or equivalently to the compiled library)
this visitor should be expanded to handle any new operations */
class SimpleArithVisitor : public ASTVisitor {
using ASTVisitor::visit;
virtual ASTPtr visit(AST * a) {return a->ptr();};
virtual ASTPtr visit(DataflowAPI::BottomAST *a) {return a->ptr(); };
virtual ASTPtr visit(DataflowAPI::ConstantAST *c) {return c->ptr();};
virtual ASTPtr visit(DataflowAPI::VariableAST *v) {return v->ptr();};
virtual ASTPtr visit(DataflowAPI::RoseAST * r) {
using namespace DataflowAPI;
AST::Children newKids;
for(unsigned i=0;i<r->numChildren();++i) {
newKids.push_back(r->child(i)->accept(this));
}
switch(r->val().op) {
case ROSEOperation::addOp:
assert(newKids.size() == 2);
if(newKids[0]->getID() == AST::V_ConstantAST &&
newKids[1]->getID() == AST::V_ConstantAST)
{
ConstantAST::Ptr c1 = ConstantAST::convert(newKids[0]);
ConstantAST::Ptr c2 = ConstantAST::convert(newKids[1]);
return ConstantAST::create(
Constant(c1->val().val+c2->val().val));
}
break;
case ROSEOperation::concatOp:
assert(newKids.size() == 2);
if(newKids[0]->getID() == AST::V_ConstantAST &&
newKids[1]->getID() == AST::V_ConstantAST)
{
ConstantAST::Ptr c1 = ConstantAST::convert(newKids[0]);
ConstantAST::Ptr c2 = ConstantAST::convert(newKids[1]);
unsigned long result = c1->val().val;
result |= (c2->val().val << c2->val().size);
return ConstantAST::create(result);
}
break;
default:
startup_printf("%s[%d] unhandled operation in simplification\n",FILE__,__LINE__);
}
return RoseAST::create(r->val(), newKids);
}
};
struct libc_startup_info {
void * sda;
void * main_addr;
void * init_addr;
void * fini_addr;
};
void *get_raw_symtab_ptr(Symtab *linkedFile, Address addr)
{
Region *reg = linkedFile->findEnclosingRegion(addr);
if (reg != NULL) {
char *data = (char*)reg->getPtrToRawData();
data += addr - reg->getMemOffset();
return data;
}
return NULL;
}
Address deref_opd(Symtab *linkedFile, Address addr)
{
Region *reg = linkedFile->findEnclosingRegion(addr);
if (reg && reg->getRegionName() == ".opd") {
// opd symbol needing dereference
void *data = get_raw_symtab_ptr(linkedFile, addr);
if (data)
return *(Address*)data;
}
return addr;
}
/*
* b ends with a call to libc_start_main. We are looking for the
* value in GR8, which is the address of a structure that contains
* the address to main
*/
Address evaluate_main_address(Symtab * linkedFile, Function * f, Block *b)
{
using namespace DataflowAPI;
using namespace InstructionAPI;
// looking for the *last* instruction in the block
// that defines GR8
Instruction::Ptr r8_def;
Address r8_def_addr;
InstructionDecoder dec(
b->region()->getPtrToInstruction(b->start()),
b->end()-b->start(),
b->region()->getArch());
RegisterAST::Ptr r2( new RegisterAST(ppc32::r2) );
RegisterAST::Ptr r8( new RegisterAST(ppc32::r8) );
Address cur_addr = b->start();
while(Instruction::Ptr cur = dec.decode()) {
if(cur->isWritten(r8)) {
r8_def = cur;
r8_def_addr = cur_addr;
}
cur_addr += cur->size();
}
if(!r8_def)
return 0;
Address ss_addr = 0;
// Try a TOC-based lookup first
if (r8_def->isRead(r2)) {
set<Expression::Ptr> memReads;
r8_def->getMemoryReadOperands(memReads);
Address TOC = f->obj()->cs()->getTOC(r8_def_addr);
if (TOC != 0 && memReads.size() == 1) {
Expression::Ptr expr = *memReads.begin();
expr->bind(r2.get(), Result(u64, TOC));
const Result &res = expr->eval();
if (res.defined) {
void *res_addr =
get_raw_symtab_ptr(linkedFile, res.convert<Address>());
if (res_addr)
ss_addr = *(Address*)res_addr;
}
}
}
if (ss_addr == 0) {
// Get all of the assignments that happen in this instruction
AssignmentConverter conv(true);
vector<Assignment::Ptr> assigns;
conv.convert(r8_def,r8_def_addr,f,b,assigns);
// find the one we care about (r8)
vector<Assignment::Ptr>::iterator ait = assigns.begin();
for( ; ait != assigns.end(); ++ait) {
AbsRegion & outReg = (*ait)->out();
Absloc const& loc = outReg.absloc();
if(loc.reg() == r8->getID())
break;
}
if(ait == assigns.end()) {
return 0;
}
// Slice back to the definition of R8, and, if possible, simplify
// to a constant
Slicer slc(*ait,b,f);
Default_Predicates preds;
Graph::Ptr slg = slc.backwardSlice(preds);
DataflowAPI::Result_t sl_res;
DataflowAPI::SymEval::expand(slg,sl_res);
AST::Ptr calculation = sl_res[*ait];
SimpleArithVisitor visit;
AST::Ptr simplified = calculation->accept(&visit);
//printf("after simplification:\n%s\n",simplified->format().c_str());
if(simplified->getID() == AST::V_ConstantAST) {
ConstantAST::Ptr cp = ConstantAST::convert(simplified);
ss_addr = cp->val().val;
}
}
// need a pointer to the image data
auto si = (struct libc_startup_info *)
get_raw_symtab_ptr(linkedFile, ss_addr);
if (si)
return (Address)si->main_addr;
return 0;
}
}
#endif
#include <Graph.h>
#include <Node.h>
#include <DynAST.h>
#include <dyntypes.h>
#include <SymEval.h>
#include <slicing.h>
class FindMainVisitor : public ASTVisitor
{
using ASTVisitor::visit;
public:
bool resolved;
bool hardFault;
Address target;
FindMainVisitor() : resolved(false), hardFault(false), target(0) {}
virtual AST::Ptr visit(DataflowAPI::RoseAST * r)
{
using namespace DataflowAPI;
AST::Children newKids;
for(unsigned i = 0; i < r->numChildren(); i++)
newKids.push_back(r->child(i)->accept(this));
switch(r->val().op)
{
case ROSEOperation::addOp:
assert(newKids.size() == 2);
if(newKids[0]->getID() == AST::V_ConstantAST &&
newKids[1]->getID() == AST::V_ConstantAST)
{
ConstantAST::Ptr c1 = ConstantAST::convert(newKids[0]);
ConstantAST::Ptr c2 = ConstantAST::convert(newKids[1]);
if(!hardFault)
{
target = c1->val().val + c2->val().val;
resolved = true;
}
return ConstantAST::create(
Constant(c1->val().val + c2->val().val));
}
break;
default:
startup_printf("%s[%d] unhandled FindMainVisitor operation\n",
FILE__,__LINE__);
}
return RoseAST::create(r->val(), newKids);
}
virtual ASTPtr visit(DataflowAPI::ConstantAST * c)
{
/* We can only handle constant values */
if(!target && !hardFault)
{
resolved = true;
target = c->val().val;
}
return c->ptr();
};
virtual ASTPtr visit(DataflowAPI::VariableAST* v)
{
/* If we visit a variable node, we can't do any analysis */
hardFault = true;
resolved = false;
target = 0;
return v->ptr();
}
};
/**
* Search for the Main Symbols in the list of symbols, Only in case
* if the file is a shared object. If not present add them to the
* list. Returns zero on success, nonzero otherwise.
*/
int image::findMain()
{
#if defined(ppc32_linux) || defined(ppc32_bgp) || defined(ppc64_linux)
using namespace Dyninst::InstructionAPI;
// Only look for main in executables, but do allow position-independent
// executables (PIE) which look like shared objects with an INTERP.
// (Some strange DSOs also have INTERP, but this is rare.)
if(!desc_.isSharedObject() || linkedFile->getInterpreterName() != NULL)
{
bool foundMain = false;
bool foundStart = false;
bool foundFini = false;
// check if 'main' is in allsymbols
vector <SymtabAPI::Function *> funcs;
if (linkedFile->findFunctionsByName(funcs, "main") ||
linkedFile->findFunctionsByName(funcs, "_main"))
foundMain = true;
else if (linkedFile->findFunctionsByName(funcs, "_start"))
foundStart = true;
else if (linkedFile->findFunctionsByName(funcs, "_fini"))
foundFini = true;
Region *eReg = NULL;
bool foundText = linkedFile->findRegion(eReg, ".text");
if (!foundText)
return -1;
if(!foundMain)
{
logLine("No main symbol found: attempting to create symbol for main\n");
Address eAddr = linkedFile->getEntryOffset();
eAddr = deref_opd(linkedFile, eAddr);
bool parseInAllLoadableRegions = (BPatch_normalMode != mode_);
SymtabCodeSource scs(linkedFile, filt, parseInAllLoadableRegions);
CodeObject tco(&scs,NULL,NULL,false);
tco.parse(eAddr,false);
set<CodeRegion *> regions;
scs.findRegions(eAddr,regions);
if(regions.empty()) {
// express puzzlement
return -1;
}
SymtabCodeRegion * reg =
static_cast<SymtabCodeRegion*>(*regions.begin());
Function * func =
tco.findFuncByEntry(reg,eAddr);
if(!func) {
// again, puzzlement
return -1;
}
Block * b = NULL;
const Function::edgelist & calls = func->callEdges();
if (calls.empty()) {
// when there are no calls, let's hope the entry block is it
b = tco.findBlockByEntry(reg,eAddr);
} else if(calls.size() == 1) {
Function::edgelist::iterator cit = calls.begin();
b = (*cit)->src();
} else {
startup_printf("%s[%d] _start has unexpected number (%d) of"
" call edges, bailing on findMain()\n",
FILE__,__LINE__,calls.size());
return -1;
}
if (!b) return -1;
Address mainAddress = evaluate_main_address(linkedFile,func,b);
mainAddress = deref_opd(linkedFile, mainAddress);
if(0 == mainAddress || !scs.isValidAddress(mainAddress)) {
startup_printf("%s[%d] failed to find main\n",FILE__,__LINE__);
return -1;
} else {
startup_printf("%s[%d] found main at %lx\n",
FILE__,__LINE__,mainAddress);
}
Symbol *newSym= new Symbol( "main",
Symbol::ST_FUNCTION,
Symbol::SL_LOCAL,
Symbol::SV_INTERNAL,
mainAddress,
linkedFile->getDefaultModule(),
eReg,
0 );
linkedFile->addSymbol(newSym);
}
}
#elif defined(i386_unknown_linux2_0) \
|| defined(x86_64_unknown_linux2_4) /* Blind duplication - Ray */ \
|| (defined(os_freebsd) \
&& (defined(arch_x86) || defined(arch_x86_64)))
// Only look for main in executables, but do allow position-independent
// executables (PIE) which look like shared objects with an INTERP.
// (Some strange DSOs also have INTERP, but this is rare.)
if(!desc_.isSharedObject() || linkedFile->getInterpreterName() != NULL)
{
bool foundMain = false;
bool foundStart = false;
bool foundFini = false;
//check if 'main' is in allsymbols
vector <SymtabAPI::Function *> funcs;
if (linkedFile->findFunctionsByName(funcs, "main") ||
linkedFile->findFunctionsByName(funcs, "_main")) {
foundMain = true;
}
if (linkedFile->findFunctionsByName(funcs, "_start")) {
foundStart = true;
}
if (linkedFile->findFunctionsByName(funcs, "_fini")) {
foundFini = true;
}
Address eAddr = linkedFile->getEntryOffset();
Region *eReg = linkedFile->findEnclosingRegion(eAddr);
if (!eReg)
return -1;
// Address eStart = eReg->getMemOffset();
if(!foundMain)
{
logLine( "No main symbol found: creating symbol for main\n" );
//find and add main to allsymbols
// const unsigned char* p;
// p = (( const unsigned char * ) eReg->getPtrToRawData());
// if (eAddr > eStart) {
// p += (eAddr - eStart);
// }
switch(linkedFile->getAddressWidth()) {
case 4:
// 32-bit...
startup_printf("%s[%u]: setting 32-bit mode\n",
FILE__,__LINE__);
ia32_set_mode_64(false);
break;
case 8:
startup_printf("%s[%u]: setting 64-bit mode\n",
FILE__,__LINE__);
ia32_set_mode_64(true);
break;
default:
assert(0 && "Illegal address width");
break;
}
Address mainAddress = 0;
// Create a temporary SymtabCodeSource that we can use for parsing.
// We're going to throw it away when we're done so that we can re-sync
// with the new symbols we're going to add shortly.
bool parseInAllLoadableRegions = (BPatch_normalMode != mode_);
SymtabCodeSource scs(linkedFile, filt, parseInAllLoadableRegions);
CodeObject co(&scs);
#if !defined(os_freebsd)
/* Find the entry point, where we start our analysis */
Address entry_point = (Address)linkedFile->getEntryOffset();
/* Get the code regions we are looking at */
std::set<CodeRegion*> regions;
scs.findRegions(entry_point, regions);
/* We should only get one region */
if(regions.size() != 1)
{
startup_printf("%s[%u]: Overlapping or non existant regions!\n",
FILE__, __LINE__);
return -1;
}
CodeRegion* region = *regions.begin();
assert(region);
/* Parse the function we're looking at */
co.parse(region, entry_point, true);
/* Get the parsed Function */
vector<ParseAPI::Function*> funcs;
Function* func = co.findFuncByEntry(region, entry_point);
if(!func)
{
startup_printf("%s[%u]: No functions found in our region.\n",
FILE__, __LINE__);
return -1;
}
/* Get the call edges for this function */
Function::edgelist list = func->callEdges();
/* There should be at least one edge */
ParseAPI::Edge* e = *list.begin();
if(!e)
{
startup_printf("%s[%u]: Error: no call edges found for this function.\n",
FILE__, __LINE__);
return -1;
}
/* get the block for this call edge (source) */
Block* b = e->src();
assert(b);
Block::Insns insns;
b->getInsns(insns);
if (insns.size() < 2) {
startup_printf("%s[%u]: should have at least two instructions\n", FILE__, __LINE__);
return -1;
}
// To get the secont to last instruction, which loads the address of main
auto iit = insns.end();
--iit;
--iit;
/* Let's get the assignment for this instruction. */
std::vector<Assignment::Ptr> assignments;
Dyninst::AssignmentConverter assign_convert(true, false);
assign_convert.convert(iit->second, iit->first, func, b, assignments);
if(assignments.size() >= 1)
{
Assignment::Ptr assignment = assignments[0];
std::pair<AST::Ptr, bool> res = DataflowAPI::SymEval::expand(assignment, false);
AST::Ptr ast = res.first;
if(!ast)
{
/* expand failed */
mainAddress = 0x0;
startup_printf("%s[%u]: cannot expand %s from instruction %s\n", FILE__, __LINE__, assignment->format().c_str(), assignment->insn()->format().c_str());
} else {
startup_printf("%s[%u]: try to visit %s\n", FILE__, __LINE__, ast->format().c_str());
FindMainVisitor fmv;
ast->accept(&fmv);
if(fmv.resolved)
{
mainAddress = fmv.target;
} else {
mainAddress = 0x0;
startup_printf("%s[%u]: FindMainVisitor cannot find main address in %s\n", FILE__, __LINE__, ast->format().c_str());
}
}
}
#else
// Heuristic: main is the target of the 4th call in the text section
using namespace Dyninst::InstructionAPI;
unsigned bytesSeen = 0, numCalls = 0;
InstructionDecoder decoder(p, eReg->getMemSize(), scs.getArch());
Instruction::Ptr curInsn = decoder.decode();
while( numCalls < 4 && curInsn && curInsn->isValid() &&
bytesSeen < eReg->getMemSize())
{
InsnCategory category = curInsn->getCategory();
if( category == c_CallInsn ) {
numCalls++;
}
if( numCalls < 4 ) {
bytesSeen += curInsn->size();
curInsn = decoder.decode();
}
}
if( numCalls != 4 ) {
logLine("heuristic for finding global constructor function failed\n");
}else{
Address callAddress = eReg->getMemOffset() + bytesSeen;
RegisterAST thePC = RegisterAST(Dyninst::MachRegister::getPC(scs.getArch()));
Expression::Ptr callTarget = curInsn->getControlFlowTarget();
if( callTarget.get() ) {
callTarget->bind(&thePC, Result(s64, callAddress));
Result actualTarget = callTarget->eval();
if( actualTarget.defined ) {
mainAddress = actualTarget.convert<Address>();
}
}
}
#endif
if(!mainAddress || !scs.isValidAddress(mainAddress)) {
startup_printf("%s[%u]: invalid main address 0x%lx\n",
FILE__, __LINE__, mainAddress);
} else {
startup_printf("%s[%u]: set main address to 0x%lx\n",
FILE__,__LINE__,mainAddress);
}
/* Note: creating a symbol for main at the invalid address
anyway, because there is guard code for this later in the
process and otherwise we end up in a weird "this is not an
a.out" path.
findMain, like all important utility functions, should have
a way of gracefully indicating that it has failed. It should
not return void. NR
*/
Region *pltsec;
if((linkedFile->findRegion(pltsec, ".plt")) && pltsec->isOffsetInRegion(mainAddress))
{
//logLine( "No static symbol for function main\n" );
Symbol *newSym = new Symbol("DYNINST_pltMain",
Symbol::ST_FUNCTION,
Symbol::SL_LOCAL,
Symbol::SV_INTERNAL,
mainAddress,
linkedFile->getDefaultModule(),
eReg,
0 );
linkedFile->addSymbol( newSym );
}
else
{
Symbol *newSym= new Symbol( "main",
Symbol::ST_FUNCTION,
Symbol::SL_LOCAL,
Symbol::SV_INTERNAL,
mainAddress,
linkedFile->getDefaultModule(),
eReg,
0 );
linkedFile->addSymbol(newSym);
}
}
if( !foundStart )
{
Symbol *startSym = new Symbol( "_start",
Symbol::ST_FUNCTION,
Symbol::SL_LOCAL,
Symbol::SV_INTERNAL,
eReg->getMemOffset(),
linkedFile->getDefaultModule(),
eReg,
0 );
//cout << "sim for start!" << endl;
linkedFile->addSymbol(startSym);
}
if( !foundFini )
{
Region *finisec = NULL;
if (linkedFile->findRegion(finisec,".fini")) {
Symbol *finiSym = new Symbol( "_fini",
Symbol::ST_FUNCTION,
Symbol::SL_LOCAL,
Symbol::SV_INTERNAL,
finisec->getMemOffset(),
linkedFile->getDefaultModule(),
finisec,
0 );
linkedFile->addSymbol(finiSym);
}
}
}
Region *dynamicsec;
vector < Symbol *>syms;
if(linkedFile->findRegion(dynamicsec, ".dynamic")==true)
{
if(linkedFile->findSymbol(syms,
"_DYNAMIC",
Symbol::ST_UNKNOWN,
SymtabAPI::mangledName)==false)
{
Symbol *newSym = new Symbol( "_DYNAMIC",
Symbol::ST_OBJECT,
Symbol::SL_LOCAL,
Symbol::SV_INTERNAL,
dynamicsec->getMemOffset(),
linkedFile->getDefaultModule(),
dynamicsec,
0 );
linkedFile->addSymbol(newSym);
}
}
#elif defined(i386_unknown_nt4_0)
if(linkedFile->isExec()) {
vector <Symbol *>syms;
vector<SymtabAPI::Function *> funcs;
Address eAddr = linkedFile->getEntryOffset();
Region *eReg = linkedFile->findEnclosingRegion(eAddr);
bool found_main = false;
for (unsigned i=0; i<NUMBER_OF_MAIN_POSSIBILITIES; i++) {
if(linkedFile->findFunctionsByName(funcs, main_function_names[i])) {
found_main = true;
break;
}
}
if (found_main) {
if(!linkedFile->findSymbol(syms,"start",Symbol::ST_UNKNOWN, SymtabAPI::mangledName)) {
//use 'start' for mainCRTStartup.
Symbol *startSym = new Symbol( "start",
Symbol::ST_FUNCTION,
Symbol::SL_GLOBAL,
Symbol::SV_DEFAULT,
eAddr ,
linkedFile->getDefaultModule(),
eReg,
UINT_MAX );
linkedFile->addSymbol(startSym);
}
syms.clear();
}
else {
// add entry point as main given that nothing else was found
startup_printf("[%s:%u] - findmain could not find symbol "
"for main, using binary entry point %x\n",
__FILE__, __LINE__, eAddr);
linkedFile->addSymbol(new Symbol("main",
Symbol::ST_FUNCTION,
Symbol::SL_GLOBAL,
Symbol::SV_DEFAULT,
eAddr,
linkedFile->getDefaultModule(),
eReg));
}
}
#endif
return 0; /* Success */
}
/*
* We do a search for a "main" symbol (a couple of variants), and
* if found we flag this image as the executable (a.out).
*/
bool image::determineImageType()
{
#if defined(TIMED_PARSE)
struct timeval starttime;
gettimeofday(&starttime, NULL);
#endif
//Checking "main" function names in same order as in the inst-*.C files
vector <SymtabAPI::Function *>funcs;
if (linkedFile->findFunctionsByName(funcs,"main") ||
linkedFile->findFunctionsByName(funcs,"_main")
#if defined(os_windows)
|| linkedFile->findFunctionsByName(funcs,"WinMain") ||
linkedFile->findFunctionsByName(funcs,"_WinMain") ||
linkedFile->findFunctionsByName(funcs,"wWinMain") ||
linkedFile->findFunctionsByName(funcs,"_wWinMain")
#endif
) {
is_a_out = true;
}
else
is_a_out = false;
// Checking for libdyninstRT (DYNINSTinit())
if (linkedFile->findFunctionsByName(funcs, "DYNINSTinit") ||
linkedFile->findFunctionsByName(funcs, "_DYNINSTinit"))
is_libdyninstRT = true;
else
is_libdyninstRT = false;
#if defined(TIMED_PARSE)
struct timeval endtime;
gettimeofday(&endtime, NULL);
unsigned long lstarttime = starttime.tv_sec * 1000 * 1000 + starttime.tv_usec;
unsigned long lendtime = endtime.tv_sec * 1000 * 1000 + endtime.tv_usec;
unsigned long difftime = lendtime - lstarttime;
double dursecs = difftime/(1000 );
cout << __FILE__ << ":" << __LINE__ <<": determineImageType took "<<dursecs <<" msecs" << endl;
#endif
return true;
}
bool image::getInferiorHeaps(vector<pair<string,Address> > &codeHeaps,
vector<pair<string,Address> > &dataHeaps) {
if ((codeHeaps_.size() == 0) &&
(dataHeaps_.size() == 0)) return false;
for (unsigned i = 0; i < codeHeaps_.size(); i++) {
codeHeaps.push_back(codeHeaps_[i]);
}
for (unsigned i = 0; i < dataHeaps_.size(); i++) {
dataHeaps.push_back(dataHeaps_[i]);
}
return true;
}
bool image::addSymtabVariables()
{
/* Eventually we'll have to do this on all platforms (because we'll retrieve
* the type information here).
*/
#if defined(TIMED_PARSE)
struct timeval starttime;
gettimeofday(&starttime, NULL);
#endif
std::string mangledName;