-
Notifications
You must be signed in to change notification settings - Fork 113
/
sk3wldbg.cpp
2387 lines (2172 loc) · 75.6 KB
/
sk3wldbg.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
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
/*
Source for Sk3wlDbg IdaPro plugin
Copyright (c) 2016 Chris Eagle
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This program 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 General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* This is the Sk3wlDbg plugin module
*
* It is known to compile with
*
* - Visual Studio 2010, Linux g++, OS X - clang
*
*/
#define USE_DANGEROUS_FUNCTIONS
#ifdef __NT__
#ifdef _WIN32
#include <windows.h>
#ifndef _MSC_VER
//#include <windows.h>
#endif
//#include <winsock2.h>
#endif
#include <winnt.h>
#include <wincrypt.h>
#else
//#ifndef __NT__
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#endif
#ifdef PACKED
#undef PACKED
#endif
#define USE_STANDARD_FILE_FUNCTIONS
#include <unicorn/unicorn.h>
#include <pro.h>
#include <ida.hpp>
#include <idp.hpp>
#include <bytes.hpp>
#include <auto.hpp>
#include <loader.hpp>
#include <kernwin.hpp>
#include <typeinf.hpp>
#include <nalt.hpp>
#include <segment.hpp>
#include <segregs.hpp>
#include <typeinf.hpp>
#include <struct.hpp>
#include <entry.hpp>
#include <dbg.hpp>
#include <idd.hpp>
#include <ua.hpp>
#include "sk3wldbg.h"
#include "loader.h"
#ifdef DEBUG
#undef DEBUG
#else
#undef DEBUG
#endif
//#define DEBUG
static ssize_t idaapi idd_hook(void * /* ud */, int notification_code, va_list va);
struct safe_msg : public exec_request_t {
qstring the_msg;
safe_msg(qstring &msg) : the_msg(msg) {};
int idaapi execute(void);
};
int idaapi safe_msg::execute(void) {
msg("%s", the_msg.c_str());
return 0;
}
//Not certain this is necessary, but included to provide for message printing from
//the unicorn thread
void do_safe_msg(const char *msg) {
qstring m(msg);
safe_msg req(m);
execute_sync(req, MFF_FAST);
}
qstring *get_process_name(void) {
char buf[1024];
ssize_t sz = get_root_filename(buf, sizeof(buf));
return new qstring(buf);
}
static ssize_t idaapi idb_hook(void *user_data, int notification_code, va_list va) {
sk3wldbg *uc = (sk3wldbg*)user_data;
switch (notification_code) {
case idb_event::segm_added: {
segment_t *seg = va_arg(va, segment_t *);
uintptr_t start = seg->start_ea;
uintptr_t end = seg->end_ea;
//msg("idb_hook uc == %p\n", uc);
//msg("offset to uc->memmgr == 0x%x\n", ((char*)&uc->memmgr) - (char*)uc);
//msg("uc->memmgr == %p\n", uc->memmgr);
msg("segm_added mapping, %p:%p\n", (void*)start, (void*)end);
if (uc->memmgr->find_block(start) == NULL) {
msg("segm_added mapping, %p:%p\n", (void*)start, (void*)end);
uc->map_mem_zero(start, end, UC_PROT_READ | UC_PROT_WRITE | UC_PROT_EXEC, SDB_MAP_FIXED);
msg("segm_added mapped, %p:%p\n", (void*)start, (void*)end);
} else {
msg("segm_added already mapped\n");
}
return 1;
}
}
return 0;
}
/// Initialize debugger.
/// This function is called from the main thread.
/// \return success
bool idaapi uni_init_debugger(const char * /*hostname*/, int /*portnum*/, const char * /*password*/, qstring * /*errbuf*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_init_debugger called\n");
#endif
return true;
}
/// Terminate debugger.
/// This function is called from the main thread.
/// \return success
bool idaapi uni_term_debugger(void) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_term_debugger called\n");
#endif
// safe_msg req("uni_term_debugger called\n");
// execute_sync(req, MFF_FAST);
if (uc->uc) {
uc->emu_state = RS_TERM;
qsem_post(uc->run_sem);
//***synchronize here to make sure execution thread has stopped
qthread_join(uc->process_thread);
// msg("uni_term_debugger thread joined\n");
uc->close();
if (uc->registered_menu) {
detach_action_from_menu("Debugger/Take memory snapshot", "sk3wldbg:mem_map");
// unregister_action("sk3wldbg:mem_map");
uc->registered_menu = false;
}
// uc->uc = NULL;
}
unhook_from_notification_point(::HT_IDB, idb_hook);
// safe_msg req2("uni_term_debugger complete\n");
// execute_sync(req2, MFF_FAST);
return true;
}
bool sk3wldbg::queue_exception_event(uint32_t code, uint64_t mem_addr, const char *errmsg) {
debug_event_t exc;
exc.set_eid(::EXCEPTION);
exc.pid = the_process;
exc.tid = the_threads.front();
exc.ea = (ea_t)get_pc();
#ifdef DEBUG
qstring msgbuf;
msgbuf.sprnt("Exception occurred at: %p\n", (void*)exc.ea);
msg("%s", msgbuf.c_str());
#endif
exc.handled = true;
excinfo_t &xcpt = exc.exc();
xcpt.info = errmsg;
xcpt.code = code;
xcpt.can_cont = false;
xcpt.ea = (ea_t)mem_addr;
enqueue_debug_evt(exc);
return true;
}
void sk3wldbg::queue_step_event(uint64_t _pc) {
debug_event_t cont;
cont.set_eid(::STEP);
cont.pid = the_process;
cont.tid = the_threads.front();
cont.ea = (ea_t)_pc;
cont.handled = true;
enqueue_debug_evt(cont);
}
bool sk3wldbg::queue_bpt_event(bool is_hardware) {
debug_event_t brk;
brk.set_eid(::BREAKPOINT);
bptaddr_t &bpt = brk.bpt();
brk.pid = the_process;
brk.tid = the_threads.front();
brk.ea = (ea_t)get_pc();
#ifdef DEBUG
qstring msgbuf;
msgbuf.sprnt("Breakpoint hit at: %p\n", (void*)brk.ea);
msg("%s", msgbuf.c_str());
#endif
brk.handled = true;
bpt.hea = is_hardware ? brk.ea : BADADDR;
bpt.kea = BADADDR;
enqueue_debug_evt(brk);
return true;
}
struct print_pc : public exec_request_t {
uint64_t pc;
print_pc(uint64_t _pc) : pc(_pc) {};
int idaapi execute(void);
};
int idaapi print_pc::execute(void) {
#ifdef DEBUG
qstring msgbuf;
msgbuf.sprnt("processRunner running from %p\n", (void*)pc);
msg("%s", msgbuf.c_str());
#endif
return 0;
}
int idaapi processRunner(void *unicorn) {
sk3wldbg *uc = (sk3wldbg*)unicorn;
uint64_t pc = uc->get_pc();
if (pc == 0) {
msg("PC was not set previously, going with screen EA\n");
pc = get_screen_ea();
} else {
qstring msgbuf;
msgbuf.sprnt("PC was set previously to %p\n", (void*)pc);
msg("%s", msgbuf.c_str());
}
uc->start(pc);
//unicorn start has returned, process has ended, so tell IDA to detach
debug_event_t detach;
detach.set_eid(PROCESS_DETACHED);
detach.pid = uc->the_process;
detach.tid = uc->the_threads.front();
detach.ea = BADADDR;
detach.handled = true;
uc->enqueue_debug_evt(detach);
return 0;
}
/// Return information about the n-th "compatible" running process.
/// If n is 0, the processes list is reinitialized.
/// This function is called from the main thread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_get_processes(procinfo_vec_t *procs, qstring * /*errbuf*/) {
#ifdef DEBUG
msg("uni_get_processes called\n");
#endif
sk3wldbg *uc = (sk3wldbg*)dbg;
process_info_t info;
qstring *procname = get_process_name();
info.name = *procname;
delete procname;
info.pid = uc->the_process;
procs->push_back(info);
return 1;
}
#if IDA_SDK_VERSION < 700
//*** Learn proper way to do this in Ida 7.0
struct install_menu : public exec_request_t {
sk3wldbg *uc;
install_menu(sk3wldbg *_uc) : uc(_uc) {};
int idaapi execute(void);
};
int idaapi install_menu::execute(void) {
attach_action_to_menu("Debugger/Take memory snapshot", "sk3wldbg:mem_map", SETMENU_APP);
enable_menu_item("Debugger/Map memory...", false);
uc->registered_menu = true;
return 0;
}
#endif
/// Start an executable to debug.
/// This function is called from debthread.
/// \param path path to executable
/// \param args arguments to pass to executable
/// \param startdir current directory of new process
/// \param dbg_proc_flags \ref DBG_PROC_
/// \param input_path path to database input file.
/// (not always the same as 'path' - e.g. if you're analyzing
/// a dll and want to launch an executable that loads it)
/// \param input_file_crc32 CRC value for 'input_path'
/// \retval 1 ok
/// \retval 0 failed
/// \retval -2 file not found (ask for process options)
/// \retval 1 | #CRC32_MISMATCH ok, but the input file crc does not match
/// \retval -1 network error
int idaapi uni_start_process(const char * /*path*/,
const char *args,
const char * /*startdir*/,
int /*dbg_proc_flags*/,
const char *input_path,
uint32 /*input_file_crc32*/, qstring * /*errbuf*/) {
int choice = ask_buttons("Cursor", "Entry point", NULL, ASKBTN_YES, "Begin execution from:");
if (choice == ASKBTN_CANCEL) {
return 0;
}
#ifdef DEBUG
msg("uni_start_process called\n");
#endif
sk3wldbg *uc = (sk3wldbg*)dbg;
#if IDA_SDK_VERSION < 700
//*** Learn proper way to do this in Ida 7.0
install_menu req(uc);
execute_sync(req, MFF_FAST);
#endif
ea_t init_pc = BADADDR;
if (choice == ASKBTN_YES) {
init_pc = get_screen_ea();
uc->check_mode(init_pc);
}
if (!uc->open()) {
//failed to open unicorn instance
return 0;
}
qsem_free(uc->run_sem);
uc->run_sem = qsem_create(NULL, 0);
uc->pause_sem = qsem_create(NULL, 0);
qmutex_unlock(uc->evt_mutex);
uc->clear_memory();
uc->dbg_evt_list.clear();
uc->the_threads.clear();
uc->getRandomBytes(&uc->the_process, 2);
uc->the_process = (uc->the_process % 40000) + 1000;
thid_t a_thread = 0;
do {
uc->getRandomBytes(&a_thread, 2);
a_thread = (a_thread % 40000) + 1000;
} while (a_thread == (thid_t)uc->the_process);
uc->the_threads.push_back(a_thread);
FILE *bin = fopen(input_path, "rb");
bool loaded = false;
if (bin != NULL) {
msg("found input file %s\n", input_path);
if (fseek(bin, 0, SEEK_END) != 0) {
//HUH?
msg("SEEK_END fail\n");
} else {
long sz = ftell(bin);
void *img = malloc(sz);
if (img == NULL) {
//OOM
msg("image allocate fail\n");
} else {
msg("reading file of %u bytes\n", (uint32_t)sz);
fseek(bin, 0, SEEK_SET);
if (fread(img, sz, 1, bin) != 1) {
//fail
msg("fread fail\n");
} else {
loaded = loadImage(uc, img, sz, args, init_pc);
}
free(img);
}
}
fclose(bin);
}
void *buf16 = NULL; //memory pointer
if (uc->debug_mode == UC_MODE_16) {
//just map a megabyte
uc->init_memmgr(0, 0x100000);
buf16 = uc->map_mem_zero(0, 0x100000, UC_PROT_READ | UC_PROT_WRITE | UC_PROT_EXEC, SDB_MAP_FIXED);
} else if (uc->get_sp() == 0) {
//need a stack too, just sling it somewhere
//add it to uc->memory
unsigned int stack_top = 0xffffe000;
uc->init_memmgr(0, stack_top);
uc->map_mem_zero(stack_top - 0x100000, stack_top, UC_PROT_READ | UC_PROT_WRITE | UC_PROT_EXEC, SDB_MAP_FIXED);
stack_top -= 16;
uc->set_sp(stack_top);
}
if (!loaded) {
//didn't know format, let's try for what we need from IDA
//init memory, by copying from IDA
//May prefer instead to init from file, in which case we need loaders
//Also need to map in a stack and init stack pointer, this will be
//architecture dependent since each arch has its own SP register
//arch specific unicorns also need to set initial register state
segment_t *seg;
for (seg = get_first_seg(); seg != NULL; seg = get_next_seg(seg->start_ea)) {
void *buf;
ssize_t exact = (ssize_t)(seg->end_ea - seg->start_ea);
if (uc->debug_mode == UC_MODE_16) {
buf = seg->start_ea + (char*)buf16;
} else {
buf = uc->map_mem_zero(seg->start_ea, seg->end_ea, ida_to_uc_perms_map[seg->perm], SDB_MAP_FIXED);
}
get_bytes(buf, exact, seg->start_ea);
}
//need other ways to set PC, from start, user specified
uc->set_pc(init_pc);
} else { // we loaded it, but may need to load any additional segments that exist in IDA
segment_t *seg;
void *buf;
for (seg = get_first_seg(); seg != NULL; seg = get_next_seg(seg->start_ea)) {
if (seg->is_loader_segm()) {
//should have been handled by our loader
continue;
}
ssize_t exact = (ssize_t)(seg->end_ea - seg->start_ea);
buf = uc->map_mem_zero(seg->start_ea, seg->end_ea, ida_to_uc_perms_map[SEGPERM_EXEC | SEGPERM_WRITE | SEGPERM_READ], SDB_MAP_FIXED);
msg("trying to populate new segment\n");
get_bytes(buf, exact, seg->start_ea);
msg("populated new segment\n");
}
}
// need to respond to some idb events
hook_to_notification_point(::HT_IDB, idb_hook, uc);
//init registers
//TODO: each architecture subclass should have its own register state initialization
//register unicorn hooks
//start in break state, RS_RUN will be set in uni_continue_after_event
uc->emu_state = RS_BREAK;
uc->do_suspend = false;
uc->finished = false;
uc->single_step = false;
//this is going to have to run in a separate thread otherwise other
//debthread functions will never get called
uc->process_thread = qthread_create(processRunner, uc);
if (uc->process_thread == NULL) {
//error failed to create thread
msg(PLUGIN_NAME": Failed to start process.\n");
return 0;
}
debug_event_t start;
qstring *procname = get_process_name();
start.set_eid(PROCESS_STARTED);
modinfo_t &mod = start.modinfo();
mod.name = *procname;
delete procname;
start.pid = uc->the_process;
start.tid = uc->the_threads.front();
start.ea = BADADDR;
start.handled = true;
mod.base = inf_get_min_ea();
mod.size = inf_get_max_ea() - inf_get_min_ea();
mod.rebase_to = BADADDR;
uc->enqueue_debug_evt(start);
#ifdef DEBUG
msg("uni_start_process complete\n");
#endif
return 1;
}
/// Attach to an existing running process.
/// event_id should be equal to -1 if not attaching to a crashed process.
/// This function is called from debthread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_attach_process(pid_t /*pid*/, int /*event_id*/, int /*dbg_proc_flags*/, qstring * /*errbuf*/) {
//can't do this with unicorn
#ifdef DEBUG
msg("uni_attach_process called\n");
#endif
return 0;
}
/// Detach from the debugged process.
/// May be called while the process is running or suspended.
/// Must detach from the process in any case.
/// The kernel will repeatedly call get_debug_event() and until ::PROCESS_DETACHED.
/// In this mode, all other events will be automatically handled and process will be resumed.
/// This function is called from debthread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_detach_process(void) {
#ifdef DEBUG
msg("uni_detach_process called\n");
#endif
//for unicorn we will just terminate session if user wants to detach
sk3wldbg *uc = (sk3wldbg*)dbg;
uc->emu_state = RS_TERM;
qsem_post(uc->run_sem);
//***synchronize here to make sure execution thread has stopped
qthread_join(uc->process_thread);
#ifdef DEBUG
msg("uni_detach_process thread joined\n");
#endif
/*
debug_event_t detach;
detach.set_eid(PROCESS_DETACHED);
detach.pid = uc->the_process;
detach.tid = uc->the_threads.front();
detach.ea = BADADDR;
detach.handled = true;
uc->enqueue_debug_evt(detach);
*/
#ifdef DEBUG
msg("uni_detach_process complete\n");
#endif
return 1;
}
/// Rebase database if the debugged program has been rebased by the system.
/// This function is called from the main thread.
void idaapi uni_rebase_if_required_to(ea_t /*new_base*/) {
#ifdef DEBUG
msg("uni_rebase_if_required_to called: NOT IMPLEMENTED\n");
#endif
}
/// Prepare to pause the process.
/// Normally the next get_debug_event() will pause the process
/// If the process is sleeping then the pause will not occur
/// until the process wakes up. The interface should take care of
/// this situation.
/// If this function is absent, then it won't be possible to pause the program.
/// This function is called from debthread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_prepare_to_pause_process(qstring * /*errbuf*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_prepare_to_pause_process called\n");
#endif
uc->pause();
debug_event_t pause;
pause.set_eid(PROCESS_SUSPENDED);
pause.info()[0] = 0;
pause.pid = uc->the_process;
pause.tid = uc->the_threads.front();
#if IDA_SDK_VERSION < 730
pause.ea = inf.min_ea; //??? get pc from unicorn
#else
pause.ea = inf_get_min_ea();
#endif
uc->enqueue_debug_evt(pause);
#ifdef DEBUG
msg("uni_prepare_to_pause_process complete\n");
#endif
return 1;
}
/// Stop the process.
/// May be called while the process is running or suspended.
/// Must terminate the process in any case.
/// The kernel will repeatedly call get_debug_event() and until ::PROCESS_EXITED.
/// In this mode, all other events will be automatically handled and process will be resumed.
/// This function is called from debthread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_exit_process(qstring * /*errbuf*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_exit_process called\n");
#endif
uc->emu_state = RS_TERM;
qsem_post(uc->run_sem);
//***synchronize here to make sure execution thread has stopped
qthread_join(uc->process_thread);
#ifdef DEBUG
msg("uni_exit_process thread joined\n");
#endif
debug_event_t stop;
stop.set_exit_code(::PROCESS_EXITED, 0);
stop.pid = uc->the_process;
stop.tid = uc->the_threads.front();
#if IDA_SDK_VERSION < 730
stop.ea = inf.min_ea;
#else
stop.ea = inf_get_min_ea();
#endif
uc->enqueue_debug_evt(stop);
return 1;
}
/// Get a pending debug event and suspend the process.
/// This function will be called regularly by IDA.
/// This function is called from debthread.
/// IMPORTANT: commdbg does not expect immediately after a BPT-related event
/// any other event with the same thread/IP - this can cause erroneous
/// restoring of a breakpoint before resume
/// (the bug was encountered 24.02.2015 in pc_linux_upx.elf)
gdecode_t idaapi uni_get_debug_event(debug_event_t *event, int /*timeout_ms*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
if (uc->debug_queue_len() == 0) {
return GDE_NO_EVENT;
} else {
uc->dequeue_debug_evt(event);
// msg("uni_get_debug_event called returning: eid = 0x%08x\n", event->eid);
//should we ever act on event->eid here?
return uc->debug_queue_len() > 0 ? GDE_MANY_EVENTS : GDE_ONE_EVENT;
}
}
/// Continue after handling the event.
/// This function is called from debthread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_continue_after_event(const debug_event_t *event) {
sk3wldbg *uc = (sk3wldbg*)dbg;
event_id_t eid = event->eid();
#ifdef DEBUG
msg("uni_continue_after_event called: eid = 0x%08x\n", eid);
#endif
if (event == NULL || eid == 2) {// || uc->dbg_evt_list.size() == 0) {
return 1;
}
uc->emu_state = RS_RUN;
switch (eid) {
case PROCESS_STARTED:
#ifdef DEBUG
msg("uni_continue_after_event PROCESS_STARTED\n");
#endif
qsem_post(uc->run_sem);
break;
case PROCESS_EXITED:
#ifdef DEBUG
msg("uni_continue_after_event PROCESS_EXITED\n");
#endif
uc->emu_state = RS_TERM;
qsem_post(uc->run_sem);
break;
case THREAD_STARTED:
#ifdef DEBUG
msg("uni_continue_after_event THREAD_STARTED\n");
#endif
qsem_post(uc->run_sem);
break;
case THREAD_EXITED:
#ifdef DEBUG
msg("uni_continue_after_event THREAD_EXITED\n");
#endif
qsem_post(uc->run_sem);
break;
case BREAKPOINT:
#ifdef DEBUG
msg("uni_continue_after_event BREAKPOINT\n");
#endif
//resume from breakpoint, replace instruction in memory, single step resume again?
//need to honor resume_mode in this case
uc->emu_state = uc->resume_mode;
qsem_post(uc->run_sem);
break;
case STEP:
#ifdef DEBUG
msg("uni_continue_after_event trying to step\n");
#endif
//state should have been set in set_resume_mode
//need to honor resume_mode in this case
uc->emu_state = uc->resume_mode;
qsem_post(uc->run_sem);
break;
case EXCEPTION:
#ifdef DEBUG
msg("uni_continue_after_event EXCEPTION\n");
#endif
//give it a try
qsem_post(uc->run_sem);
break;
case LIB_LOADED:
#ifdef DEBUG
msg("uni_continue_after_event LIB_LOADED\n");
#endif
qsem_post(uc->run_sem);
break;
case LIB_UNLOADED:
#ifdef DEBUG
msg("uni_continue_after_event LIB_UNLOADED\n");
#endif
qsem_post(uc->run_sem);
break;
case INFORMATION:
#ifdef DEBUG
msg("uni_continue_after_event INFORMATION\n");
#endif
break;
case PROCESS_ATTACHED:
#ifdef DEBUG
msg("uni_continue_after_event PRICESS_ATTACH\n");
#endif
break;
case PROCESS_DETACHED:
#ifdef DEBUG
msg("uni_continue_after_event PROCESS_DETACHED\n");
#endif
break;
case PROCESS_SUSPENDED:
#ifdef DEBUG
msg("uni_continue_after_event PROCESS_SUSPENDED\n");
#endif
qsem_post(uc->run_sem);
break;
case TRACE_FULL:
#ifdef DEBUG
msg("uni_continue_after_event TRACE_FULL\n");
#endif
break;
case NO_EVENT:
break;
}
return 1;
}
/// Set exception handling.
/// This function is called from debthread or the main thread.
void idaapi uni_set_exception_info(const exception_info_t *info, int qty) {
#ifdef DEBUG
msg("uni_set_exception_info called\n");
#endif
for (int i = 0; i < qty; i++) {
msg("Exception #%d\n", i);
msg(" Code: 0x%x, flags: 0x%x\n", info[i].code, info[i].flags);
msg(" Name: %s, Desc: %s\n", info[i].name.c_str(), info[i].desc.c_str());
}
}
/// This function will be called by the kernel each time
/// it has stopped the debugger process and refreshed the database.
/// The debugger module may add information to the database if it wants.
///
/// The reason for introducing this function is that when an event line
/// LOAD_DLL happens, the database does not reflect the memory state yet
/// and therefore we can't add information about the dll into the database
/// in the get_debug_event() function.
/// Only when the kernel has adjusted the database we can do it.
/// Example: for imported PE DLLs we will add the exported function
/// names to the database.
///
/// This function pointer may be absent, i.e. NULL.
/// This function is called from the main thread.
void idaapi uni_stopped_at_debug_event(thread_name_vec_t * /*thr_names*/, bool /*dlls_added*/) {
#ifdef DEBUG
msg("uni_stopped_at_debug_event called\n");
#endif
}
/// \name Threads
/// The following functions manipulate threads.
/// These functions are called from debthread.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_thread_suspend(thid_t /*tid*/) { ///< Suspend a running thread
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_thread_suspend called\n");
#endif
uc->pause();
uc->do_suspend = true;
//is there an event we need to post to IDA?
return 1;
}
int idaapi uni_thread_continue(thid_t /*tid*/) { ///< Resume a suspended thread
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_thread_continue called\n");
#endif
//this is going to have to run in a separate thread otherwise other
//debthread functions will never get called
if (uc->do_suspend) {
uc->do_suspend = false;
}
uc->resume();
return 1;
}
int idaapi uni_set_resume_mode(thid_t /*tid*/, resume_mode_t resmod) { ///< Specify resume action
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
msg("uni_set_resume_mode called. resmod = %d\n", resmod);
#endif
//*** figure out how best to handle all resume modes
switch (resmod) {
case RESMOD_OVER:
uc->resume_mode = RS_STEP_OVER;
break;
case RESMOD_OUT:
uc->resume_mode = RS_STEP_OUT;
break;
case RESMOD_INTO:
uc->resume_mode = RS_STEP_INTO;
uc->set_stepping();
break;
case RESMOD_NONE:
uc->resume_mode = RS_RUN; //????
break;
default:
break;
}
return 1;
}
/// Read thread registers.
/// This function is called from debthread.
/// \param tid thread id
/// \param clsmask bitmask of register classes to read
/// \param regval pointer to vector of regvals for all registers.
/// regval is assumed to have debugger_t::nregs elements
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_read_registers(thid_t /*tid*/, int clsmask, regval_t *values, qstring * /*errbuf*/) {
#ifdef DEBUG
msg("uni_read_registers called\n");
#endif
sk3wldbg *uc = (sk3wldbg*)dbg;
uc_err err = UC_ERR_OK;
//need to figure out how to do this across all unicorn archs
for (int i = 0; i < uc->nregs; i++) {
if (uc->registers[i].register_class & clsmask) {
if (!uc->read_register(i, &values[i])) {
return 0;
}
}
}
return 1;
}
/// Write one thread register.
/// This function is called from debthread.
/// \param tid thread id
/// \param regidx register index
/// \param regval new value of the register
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_write_register(thid_t /*tid*/, int regidx, const regval_t *value, qstring * /*errbuf*/) {
#ifdef DEBUG
msg("uni_write_register called\n");
#endif
//need to figure out how to do this across all unicorn archs
sk3wldbg *uc = (sk3wldbg*)dbg;
uc_err err = uc_reg_write(uc->uc, uc->reg_map[regidx], &value->ival);
return err == UC_ERR_OK;
}
/// Get information about the base of a segment register.
/// Currently used by the IBM PC module to resolve references like fs:0.
/// This function is called from debthread.
/// \param tid thread id
/// \param sreg_value value of the segment register (returned by get_reg_val())
/// \param answer pointer to the answer. can't be NULL.
/// \retval 1 ok
/// \retval 0 failed
/// \retval -1 network error
int idaapi uni_thread_get_sreg_base(ea_t *answer, thid_t /*tid*/, int /*sreg_value*/, qstring * /*errbuf*/) {
#ifdef DEBUG
msg("uni_thread_get_sreg_base called\n");
#endif
//right now unicorn has no way to get this information since base is not a register
//would need to read decide whether seg is local or global, then UC_X86_REG_L/GDTR,
//the uc_read_mem to read correct descriptor, then parse out the base address
*answer = 0;
return 1;
}
/// \name Memory manipulation
/// The following functions manipulate bytes in the memory.
/// Get information on the memory areas.
/// The debugger module fills 'areas'. The returned vector MUST be sorted.
/// This function is called from debthread.
/// \retval -3 use idb segmentation
/// \retval -2 no changes
/// \retval -1 the process does not exist anymore
/// \retval 0 failed
/// \retval 1 new memory layout is returned
int idaapi uni_get_memory_info(meminfo_vec_t &areas, qstring * /*errbuf*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
qstring msgbuf;
msg("uni_get_memory_info called\n");
#endif
uc_mem_region *regions;
uint32_t count;
uc_err err = uc_mem_regions(uc->uc, ®ions, &count);
#ifdef DEBUG
msg("uc_mem_regions returned\n");
#endif
if (err == UC_ERR_OK) {
for (uint32_t i = 0; i < count; i++) {
memory_info_t mem;
mem.start_ea = (ea_t)regions[i].begin;
mem.end_ea = (ea_t)regions[i].end - 1; //-1 because uc_mem_region is inclusive
mem.perm = uc_to_ida_perms_map[regions[i].perms];
mem.bitness = 1; //default to 32
if (uc->debug_mode & UC_MODE_16) {
mem.bitness = 0;
} else if (uc->debug_mode & UC_MODE_64) {
mem.bitness = 2;
}
areas.push_back(mem);
#ifdef DEBUG
msgbuf.sprnt(" region %d: %p-%p (%d-%d:%d)\n", i,
(void*)mem.start_ea, (void*)mem.end_ea, mem.perm, regions[i].perms, mem.bitness);
msg("%s", msgbuf.c_str());
#endif
}
uc_free(regions);
#ifdef DEBUG
msg("uc_mem_regions returned %d regions\n", count);
#endif
} else {
msg("Failed on uc_mem_regions() with error returned %u: %s\n", err, uc_strerror(err));
}
return 1;
}
/// Read process memory.
/// Returns number of read bytes.
/// This function is called from debthread.
/// \retval 0 read error
/// \retval -1 process does not exist anymore
ssize_t idaapi uni_read_memory(ea_t ea, void *buffer, size_t size, qstring * /*errbuf*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
qstring msgbuf;
msgbuf.sprnt("uni_read_memory called for %p:%d\n", (void*)ea, size);
msg("%s", msgbuf.c_str());
#endif
uc_err err = uc_mem_read(uc->uc, ea, buffer, size);
if (err != UC_ERR_OK) {
msg("Failed on uc_mem_read() with error returned %u: %s\n", err, uc_strerror(err));
}
return size;
}
/// Write process memory.
/// This function is called from debthread.
/// \return number of written bytes, -1 if fatal error
ssize_t idaapi uni_write_memory(ea_t ea, const void *buffer, size_t size, qstring * /*errbuf*/) {
sk3wldbg *uc = (sk3wldbg*)dbg;
#ifdef DEBUG
qstring msgbuf;
msgbuf.sprnt("uni_write_memory called for %p:%u\n", (void*)ea, (uint32_t)size);
msg("%s", msgbuf.c_str());
#endif
uc_err err = uc_mem_write(uc->uc, ea, buffer, size);
if (err != UC_ERR_OK) {
msg("Failed on uc_mem_write() with error returned %u: %s\n", err, uc_strerror(err));
}
return size;
}
/// Is it possible to set breakpoint?.