-
Notifications
You must be signed in to change notification settings - Fork 288
/
idapython.cpp
2272 lines (2059 loc) · 66.3 KB
/
idapython.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
//---------------------------------------------------------------------
// IDAPython - Python plugin for Interactive Disassembler
//
// Copyright (c) The IDAPython Team <[email protected]>
//
// All rights reserved.
//
// For detailed copyright information see the file COPYING in
// the root of the distribution archive.
//---------------------------------------------------------------------
// python.cpp - Main plugin code
//---------------------------------------------------------------------
#include <Python.h>
//-------------------------------------------------------------------------
// This define fixes the redefinition of ssize_t
#ifdef HAVE_SSIZE_T
#define _SSIZE_T_DEFINED 1
#endif
// Python defines snprintf macro so we need to allow it
#define USE_DANGEROUS_FUNCTIONS
#include <ida.hpp>
#include <idp.hpp>
#include <expr.hpp>
#include <diskio.hpp>
#include <loader.hpp>
#include <kernwin.hpp>
#include <ida_highlighter.hpp>
#include <signal.h>
#include "pywraps.hpp"
#include "extapi.hpp"
#include "extapi.cpp"
//-------------------------------------------------------------------------
idapython_plugin_t *idapython_plugin_t::instance = nullptr;
#include "pywraps.cpp"
//-------------------------------------------------------------------------
// Defines and constants
// Python-style version tuple comes from the makefile
// Only the serial and status is set here
#define VER_SERIAL 0
#define VER_STATUS "final"
#define IDAPYTHON_RUNSTATEMENT 0
#define IDAPYTHON_ENABLE_EXTLANG 3
#define IDAPYTHON_DISABLE_EXTLANG 4
#define PYTHON_DIR_NAME "python"
#define S_IDAPYTHON "IDAPython"
#define S_INIT_PY "init.py"
static const char S_IDC_ARGS_VARNAME[] = "ARGV";
static const char S_IDC_EXEC_PYTHON[] = "exec_python";
static const char S_IDC_EVAL_PYTHON[] = "eval_python";
static const char S_IDAPYTHON_DATA_NODE[] = "IDAPython_Data";
//lint -e818 could be pointer to const
//lint -e1762 member function '' could be made const
//-------------------------------------------------------------------------
idapython_plugin_t *ida_export get_plugin_instance()
{
return idapython_plugin_t::get_instance();
}
//-------------------------------------------------------------------------
// Allowing the user to interrupt a script is not entirely trivial.
// Imagine the following script, that is run in an IDB that uses
// an IDAPython processor module (important!) :
// ---
// while True:
// gen_disasm_text(dtext, ea, ea + 4, False)
// ---
// This script will call the processor module's out/outop functions in
// order to generate the text. If the processor module behaves
// correctly (i.e., doesn't take forever to generate said text), if the
// user presses 'Cancel' once the wait dialog box shows, what we want
// to cancel is _this_ script above: we don't want to interrupt the
// processor module while it's doing its thing!
// In order to do that, we will have to remember the time-of-entry of
// various entry points:
// - idapython_plugin_t::extlang_compile_file
// - IDAPython_RunStatement
// - ... and more importantly in this case:
// - idapython_plugin_t::extlang_call_method (called by the IDA kernel to generate text)
//
// Of course, in case the processor module's out/outop misbehaves, we still
// want the ability to cancel that operation. The following code allows for
// that, too.
//-------------------------------------------------------------------------
struct exec_entry_t
{
time_t etime;
exec_entry_t() { reset_start_time(); }
void reset_start_time() { etime = time(nullptr); }
};
DECLARE_TYPE_AS_MOVABLE(exec_entry_t);
typedef qvector<exec_entry_t> exec_entries_t;
//-------------------------------------------------------------------------
struct execution_t
{
exec_entries_t entries;
int timeout;
uint32 steps_before_action;
bool wait_box_shown;
bool interruptible_state;
execution_t()
: timeout(2),
steps_before_action(0),
wait_box_shown(false),
interruptible_state(true)
{
reset_steps();
}
void reset_steps();
void push();
void pop();
bool can_interrupt_current(time_t now) const;
void reset_current_start_time();
void stop_tracking();
void sync_to_present_time();
void maybe_hide_wait_box();
void set_interruptible(bool intr) { interruptible_state = intr; }
bool is_our_wait_box_in_charge() const;
static int on_trace(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg);
};
static execution_t execution;
//-------------------------------------------------------------------------
typedef qvector<bool> idapython_wait_box_requests_t;
static idapython_wait_box_requests_t idapython_wait_box_requests;
static inline bool idapython_is_user_waitbox_shown()
{
return idapython_wait_box_requests.has(false);
}
//-------------------------------------------------------------------------
//lint -esym(683,show_wait_box) function 'show_wait_box' #define'd, semantics may be lost
//lint -esym(750,show_wait_box) local macro '' not referenced
//lint -esym(750,hide_wait_box) local macro '' not referenced
void ida_export idapython_show_wait_box(
bool internal,
const char *message)
{
idapython_wait_box_requests.push_back(internal);
#undef show_wait_box
show_wait_box("%s", message);
#define show_wait_box USE_IDAPYTHON_SHOW_WAIT_BOX
}
//-------------------------------------------------------------------------
void ida_export idapython_hide_wait_box()
{
if ( !idapython_wait_box_requests.empty() )
{
idapython_wait_box_requests.pop_back();
execution.reset_current_start_time();
}
#undef hide_wait_box
hide_wait_box();
#define hide_wait_box USE_IDAPYTHON_HIDE_WAIT_BOX
}
// #define LOG_EXEC 1
#ifdef LOG_EXEC
#define LEXEC(...) msg("IDAPython exec: " __VA_ARGS__)
#else
#define LEXEC(...)
#endif
#define AVERAGE_STEPS_COUNT 10
#define MAX_STEPS_COUNT ((AVERAGE_STEPS_COUNT * 2) + 1)
//-------------------------------------------------------------------------
void execution_t::reset_steps()
{
// we want to trace/check the time about every 10 steps. But we don't
// want it to be exactly 10 steps, or we might never make important
// checks because the tracing happens always at the wrong point.
// E.g., imagine the following loop:
// ---
// while True:
// gen_disasm_text(dtext, ea, ea + 4, False)
// ---
// If we never hit the 'trace' callback while in the 'while True' loop
// but always when performing the call to the processor module's 'out/outop'
// then the loop will never stop. That was happening on windows (optimized.)
steps_before_action = 1 + rand() % (AVERAGE_STEPS_COUNT*2);
}
//-------------------------------------------------------------------------
void execution_t::push()
{
if ( entries.empty() )
extapi.PyEval_SetTrace_ptr((Py_tracefunc) execution_t::on_trace, nullptr); //lint !e611 cast between pointer to function type '' and pointer to object type 'void *'
entries.push_back();
LEXEC("push() (now: %d entries)\n", int(entries.size()));
}
//-------------------------------------------------------------------------
void execution_t::pop()
{
entries.pop_back();
if ( entries.empty() )
stop_tracking();
LEXEC("pop() (now: %d entries)\n", int(entries.size()));
}
//-------------------------------------------------------------------------
void execution_t::stop_tracking()
{
extapi.PyEval_SetTrace_ptr(nullptr, nullptr);
maybe_hide_wait_box();
}
//-------------------------------------------------------------------------
void execution_t::sync_to_present_time()
{
time_t now = time(nullptr);
LEXEC("execution_t (%p)::sync_to_present_time() now=%d\n", this, int(now));
for ( size_t i = 0, n = entries.size(); i < n; ++i )
entries[i].etime = now;
maybe_hide_wait_box();
}
//-------------------------------------------------------------------------
void execution_t::maybe_hide_wait_box()
{
if ( wait_box_shown )
{
LEXEC("execution_t (%p)::maybe_hide_wait_box() hiding dialog\n", this);
idapython_hide_wait_box();
wait_box_shown = false;
}
}
//-------------------------------------------------------------------------
bool execution_t::can_interrupt_current(time_t now) const
{
LEXEC("can_interrupt_current(): nentries: %d\n", int(entries.size()));
if ( entries.empty() || timeout <= 0 || !interruptible_state )
return false;
const exec_entry_t &last = entries.back();
bool can = (now - last.etime) > timeout;
LEXEC("can_interrupt_current(): last: %d, now: %d (-> %d)\n",
int(last.etime), int(now), can);
return can;
}
//-------------------------------------------------------------------------
void execution_t::reset_current_start_time()
{
if ( !entries.empty() )
{
LEXEC("reset_current_start_time()\n");
entries.back().reset_start_time();
}
}
//------------------------------------------------------------------------
int execution_t::on_trace(PyObject *, PyFrameObject *, int, PyObject *)
{
#ifdef TESTABLE_BUILD
// ensure there was no decrement overflow
QASSERT(30609, execution.steps_before_action <= MAX_STEPS_COUNT);
#endif
LEXEC("on_trace() (steps_before_action=%u, entries.size()=%d, timeout=%d)\n",
int(execution.steps_before_action),
int(execution.entries.size()),
execution.timeout);
if ( execution.timeout < 0 )
{
LEXEC("on_trace()::no timeout currently set (%d).\n", execution.timeout);
return 0;
}
// we don't want to query for time at every trace event
if ( execution.steps_before_action > 0 )
{
--execution.steps_before_action;
return 0;
}
if ( get_active_modal_widget() != nullptr )
{
LEXEC("on_trace()::a modal widget is active. Not showing our 'interrupt dialog'.\n");
// in addition, we want to sync the "start time" to now, so that
// the timeout will be relative to that (otherwise, calling
// ask_file() might end up showing the waitdialog for a fraction
// of a second after `_ida_kernwin.ask_file()` returns, but before
// the `ida_kernwin.ask_file()` one does.)
execution.sync_to_present_time();
return 0;
}
execution.reset_steps();
if ( idapython_is_user_waitbox_shown() )
{
LEXEC("on_trace()::a user wait dialog is currently shown. Not showing our 'interrupt dialog'.\n");
return 0;
}
time_t now = time(nullptr);
LEXEC("on_trace()::now: %d\n", int(now));
if ( execution.can_interrupt_current(now) )
{
const bool user_clicked_cancel = user_cancelled();
LEXEC("on_trace()::can_interrupt. 'Interrupt dialog' shown=%d, user cancelled=%d\n",
int(execution.wait_box_shown),
int(user_clicked_cancel));
if ( execution.wait_box_shown )
{
if ( user_clicked_cancel )
{
if ( PyErr_Occurred() == nullptr )
{
LEXEC("on_trace()::INTERRUPTING (setting 'User interrupted' exception)\n");
PyErr_SetString(PyExc_KeyboardInterrupt, "User interrupted");
}
return -1;
}
}
else
{
if ( !user_clicked_cancel )
{
LEXEC("on_trace()::showing wait dialog\n");
idapython_show_wait_box(/*internal=*/ true, "Running Python script");
execution.wait_box_shown = true;
}
else
{
LEXEC("on_trace()::not showing wait dialog; user_cancelled()\n");
}
}
}
return 0;
}
//-------------------------------------------------------------------------
//lint -esym(1788, new_execution_t) is referenced only by its constructor or destructor
void ida_export setup_new_execution(
new_execution_t *instance,
bool setup)
{
if ( setup )
{
instance->created = idapython_plugin_t::get_instance()->ui_ready
&& execution.timeout > 0;
if ( instance->created )
{
PYW_GIL_CHECK_LOCKED_SCOPE();
execution.push();
}
}
else
{
PYW_GIL_CHECK_LOCKED_SCOPE();
execution.pop();
}
}
//-------------------------------------------------------------------------
void ida_export set_interruptible_state(bool interruptible)
{
execution.set_interruptible(interruptible);
}
//-------------------------------------------------------------------------
void ida_export prepare_programmatic_plugin_load(const char *path)
{
idapython_plugin_t::get_instance()->requested_plugin_path = path;
}
//-------------------------------------------------------------------------
//lint -esym(714,disable_script_timeout) Symbol not referenced
idaman void ida_export disable_script_timeout()
{
// Clear timeout
execution.timeout = 0;
// Uninstall the trace function and hide the waitbox (if it was shown)
execution.stop_tracking();
}
//-------------------------------------------------------------------------
//lint -esym(714,set_script_timeout) Symbol not referenced
idaman int ida_export set_script_timeout(int timeout)
{
// Update the timeout
qswap(timeout, execution.timeout);
// Reset the execution time and hide the waitbox (so it is shown again after timeout elapses)
execution.sync_to_present_time();
return timeout;
}
//------------------------------------------------------------------------
// Return a formatted error or just print it to the console
static void handle_python_error(
qstring *errbuf,
bool clear_error = true)
{
if ( errbuf != nullptr )
errbuf->clear();
// No exception?
if ( !PyErr_Occurred() )
return;
PyW_GetError(errbuf, clear_error);
}
//-------------------------------------------------------------------------
#define ENCODING_COOKIE "# -*- coding: UTF-8 -*-\n"
#define ENCODING_COOKIE_LEN 24
static const char *insert_encoding_cookie(qstring *out)
{
// This is necessary for pre-3.9 parsers, to parse the
// input text as proper UTF-8. Python 3.9 switches to the PEG
// parser that, by default (and in particular since we don't
// pass PyCompilerFlags), will always assume UTF-8.
out->insert(0, ENCODING_COOKIE, ENCODING_COOKIE_LEN);
return out->c_str();
}
//------------------------------------------------------------------------
// Simple Python statement runner function for IDC
static error_t idaapi idc_runpythonstatement(
idc_value_t *argv,
idc_value_t *res)
{
qstring errbuf;
bool ok = idapython_plugin_t::extlang_eval_snippet(argv[0].c_str(), &errbuf);
if ( ok )
res->set_long(0);
else
res->set_string(errbuf);
return eOk;
}
static const char idc_runpythonstatement_args[] = { VT_STR, 0 };
static const ext_idcfunc_t idc_runpythonstatement_desc =
{
S_IDC_EXEC_PYTHON,
idc_runpythonstatement,
idc_runpythonstatement_args,
nullptr,
0,
0
};
//------------------------------------------------------------------------
// Simple Python expression evaluator for IDC
static error_t idaapi idc_eval_python(
idc_value_t *argv,
idc_value_t *res)
{
qstring errbuf;
const char *snippet = argv[0].c_str();
bool ok = idapython_plugin_t::extlang_eval_expr(res, BADADDR, snippet, &errbuf);
if ( !ok )
return throw_idc_exception(res, errbuf.c_str());
return eOk;
}
static const char idc_eval_python_args[] = { VT_STR, 0 };
static const ext_idcfunc_t idc_eval_python_desc =
{
S_IDC_EVAL_PYTHON,
idc_eval_python,
idc_eval_python_args,
nullptr,
0,
0
};
//--------------------------------------------------------------------------
static const cfgopt_t opts[] =
{
CFGOPT_R("SCRIPT_TIMEOUT", idapython_plugin_config_t, execution_timeout, 0, INT_MAX),
CFGOPT_B("ALERT_AUTO_SCRIPTS", idapython_plugin_config_t, alert_auto_scripts, true),
CFGOPT_B("REMOVE_CWD_SYS_PATH", idapython_plugin_config_t, remove_cwd_sys_path, true),
CFGOPT_B("AUTOIMPORT_COMPAT_IDAAPI", idapython_plugin_config_t, autoimport_compat_idaapi, true),
CFGOPT_B("IDAPYTHON_IDAUSR_SYSPATH", idapython_plugin_config_t, idausr_syspath, true),
CFGOPT_B("NAMESPACE_AWARE", idapython_plugin_config_t, namespace_aware, true),
CFGOPT_B("REPL_USE_SYS_DISPLAYHOOK", idapython_plugin_config_t, repl_use_sys_displayhook, true),
};
//-------------------------------------------------------------------------
// Convert return value from Python to IDC or report about an error.
// This function also decrements the reference "result" (python variable)
static bool return_python_result(
idc_value_t *idc_result,
const ref_t &py_result,
qstring *errbuf)
{
if ( errbuf != nullptr )
errbuf->clear();
if ( py_result == nullptr )
{
handle_python_error(errbuf);
return false;
}
int cvt = CIP_OK;
if ( idc_result != nullptr )
{
idc_result->clear();
cvt = pyvar_to_idcvar(py_result, idc_result);
if ( cvt < CIP_OK && errbuf != nullptr )
*errbuf = "ERROR: bad return value";
}
return cvt >= CIP_OK;
}
//-------------------------------------------------------------------------
// This function parses a name into two different components (if it applies).
// Example:
// parse_py_modname("modname.attrname", mod_buf, attr_buf)
// It splits the full name into two parts.
static bool parse_py_modname(
const char *full_name,
char *modname,
char *attrname,
size_t sz,
const char *defmod = S_IDA_IDAAPI_MODNAME)
{
const char *p = strrchr(full_name, '.');
if ( p == nullptr )
{
qstrncpy(modname, defmod, sz);
qstrncpy(attrname, full_name, sz);
}
else
{
qstrncpy(modname, full_name, p - full_name + 1);
qstrncpy(attrname, p + 1, sz);
}
return p != nullptr;
}
//-------------------------------------------------------------------------
static void wrap_in_function(qstring *out, const qstring &body, const char *name)
{
qstrvec_t lines;
lines.push_back().sprnt("def %s():\n", name);
qstring buf(body);
while ( !buf.empty() && qisspace(buf.last()) ) // dont copy trailing whitespace(s)
buf.remove_last();
char *ctx;
for ( char *p = qstrtok(buf.begin(), "\n", &ctx);
p != nullptr;
p = qstrtok(nullptr, "\n", &ctx) )
{
static const char FROM_FUTURE_IMPORT_STMT[] = "from __future__ import";
if ( strneq(p, FROM_FUTURE_IMPORT_STMT, sizeof(FROM_FUTURE_IMPORT_STMT)-1) )
{
lines.insert(lines.begin(), p);
}
else
{
qstring &s = lines.push_back();
s.append(" ", 4);
s.append(p);
}
}
out->qclear();
for ( size_t i = 0; i < lines.size(); ++i )
{
if ( i > 0 )
out->append('\n');
out->append(lines[i]);
}
}
//-------------------------------------------------------------------------
struct python_highlighter_t : public ida_syntax_highlighter_t
{
python_highlighter_t() : ida_syntax_highlighter_t()
{
open_strconst = '"';
close_strconst = '"';
open_chrconst = '\'';
close_chrconst = '\'';
escape_char = '\\';
preprocessor_char = char(1);
literal_closer = '\0';
text_color = HF_DEFAULT;
comment_color = HF_COMMENT;
string_color = HF_STRING;
preprocessor_color = HF_KEYWORD1;
style = HF_DEFAULT;
set_open_cmt("#");
add_multi_line_comment("\"\"\"", "\"\"\"");
add_multi_line_comment("'''", "'''");
add_keywords(
"and|as|assert|break|class|continue|def|"
"del|elif|else|except|exec|finally|"
"for|from|global|nonlocal|if|import|in|"
"is|lambda|not|or|pass|print|"
"raise|return|try|while|with|yield|"
"None|True|False",HF_KEYWORD1);
add_keywords("self", HF_KEYWORD2);
}
void add_new_keywords()
{
// Add new keywords (3.10+):
int py_major = 0, py_minor= 0;
qsscanf(Py_GetVersion(), "%d.%d", &py_major, &py_minor);
if ( py_major >= 3 && py_minor >= 5 )
add_keywords("async|await", HF_KEYWORD1);
if ( py_major >= 3 && py_minor >= 10 )
add_keywords("match|case", HF_KEYWORD1);
}
};
static python_highlighter_t python_highlighter;
extlang_t extlang_python =
{
sizeof(extlang_t),
0, // flags
0, // refcnt
"Python", // name
"py", // filext
&python_highlighter,
idapython_plugin_t::extlang_compile_expr,
idapython_plugin_t::extlang_compile_file,
idapython_plugin_t::extlang_call_func,
idapython_plugin_t::extlang_eval_expr,
idapython_plugin_t::extlang_eval_snippet,
idapython_plugin_t::extlang_create_object,
idapython_plugin_t::extlang_get_attr,
idapython_plugin_t::extlang_set_attr,
idapython_plugin_t::extlang_call_method,
idapython_plugin_t::extlang_load_procmod,
idapython_plugin_t::extlang_unload_procmod,
};
//-------------------------------------------------------------------------
idaman void ida_export enable_extlang_python(bool enable)
{
if ( enable )
select_extlang(&extlang_python);
else
select_extlang(nullptr);
}
//-------------------------------------------------------------------------
static const cli_t cli_python =
{
sizeof(cli_t),
0,
"Python",
"Python - IDAPython plugin",
"Enter any Python expression",
idapython_plugin_t::cli_execute_line,
nullptr,
nullptr,
idapython_plugin_t::cli_find_completions,
};
//-------------------------------------------------------------------------
// Control the Python CLI status
idaman void ida_export enable_python_cli(bool enable)
{
if ( enable )
install_command_interpreter(&cli_python);
else
remove_command_interpreter(&cli_python);
}
//------------------------------------------------------------------------
// Converts the global IDC variable "ARGV" into a Python variable.
// The arguments will then be accessible via 'idc' module / 'ARGV' variable.
void convert_idc_args()
{
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_args(PyList_New(0));
idc_value_t *idc_args = find_idc_gvar(S_IDC_ARGS_VARNAME);
if ( idc_args != nullptr )
{
idc_value_t attr;
char attr_name[20] = { "0" };
for ( int i=1; get_idcv_attr(&attr, idc_args, attr_name) == eOk; i++ )
{
PyList_Insert(py_args.o, i, PyUnicode_FromString(attr.c_str()));
qsnprintf(attr_name, sizeof(attr_name), "%d", i);
}
}
// Get reference to the IDC module (it is imported by init.py)
ref_t py_mod(PyW_TryImportModule(S_IDC_MODNAME));
if ( py_mod )
PyObject_SetAttrString(py_mod.o, S_IDC_ARGS_VARNAME, py_args.o);
}
//-------------------------------------------------------------------------
enum module_lifecycle_notification_t
{
mln_init = 0,
mln_term,
mln_closebase
};
static void send_modules_lifecycle_notification(module_lifecycle_notification_t what)
{
PYW_GIL_GET;
for ( size_t i = modules_callbacks.size(); i > 0; --i )
{
const module_callbacks_t &m = modules_callbacks[i-1];
switch ( what )
{
case mln_init: m.init(); break;
case mln_term: m.term(); break;
case mln_closebase: m.closebase(); break;
}
if ( PyErr_Occurred() )
{
msg("Error during module lifecycle notification:\n");
PyErr_Print();
}
}
}
//-------------------------------------------------------------------------
static wchar_t *utf8_wchar_t(qvector<wchar_t> *out, const char *in)
{
#ifdef __NT__
qwstring tmp;
utf8_utf16(&tmp, in);
out->qclear();
out->insert(out->begin(), tmp.begin(), tmp.end());
#else
const char *p = in;
while ( *p != '\0' )
{
wchar32_t cp = get_utf8_char(&p);
if ( cp == 0 || cp == BADCP )
break;
out->push_back(cp);
}
out->push_back(0); // we're not dealing with a qstring; have to do it ourselves
#endif
return out->begin();
}
//-------------------------------------------------------------------------
idapython_plugin_t::idapython_plugin_t()
: initialized(false),
ui_ready(false)
#ifdef TESTABLE_BUILD
, user_code_lenient(-1)
#endif
{
QASSERT(30615, instance == nullptr);
instance = this;
}
//-------------------------------------------------------------------------
// Cleaning up Python
idapython_plugin_t::~idapython_plugin_t()
{
QASSERT(30616, instance == this);
if ( !initialized || Py_IsInitialized() == 0 )
goto SKIP_CLEANUP;
if ( PyGILState_GetThisThreadState() )
{
// Note: No 'PYW_GIL_GET' here, as it would try to release
// the state after 'Py_Finalize()' has been called.
// ...nor is it a good idea to try to put it in its own scope,
// as it will PyGILState_Release() the current thread & GIL, and
// Py_Finalize() itself wouldn't be happy then.
PyGILState_Ensure();
}
// Let all modules perform possible de-initialization
send_modules_lifecycle_notification(mln_term);
unhook_from_notification_point(HT_IDB, on_idb_notification, this);
// Remove the CLI
enable_python_cli(false);
// Remove the extlang
remove_extlang(&extlang_python);
// De-init pywraps
deinit_pywraps();
// Uninstall IDC function
del_idc_func(idc_eval_python_desc.name);
del_idc_func(idc_runpythonstatement_desc.name);
// Shut the interpreter down
Py_Finalize();
initialized = false;
#ifdef TESTABLE_BUILD
if ( !is_user_code_lenient() ) // Check that all hooks were unhooked
QASSERT(30509, hook_data_vec.empty());
#endif
for ( size_t i = hook_data_vec.size(); i > 0; --i )
{
const hook_data_t &hd = hook_data_vec[i-1];
idapython_unhook_from_notification_point(hd.type, hd.cb, hd.ud);
}
SKIP_CLEANUP:
instance = nullptr;
}
#ifdef __NT__
// for MessageBox()
#pragma comment(lib, "user32")
#endif
//--------------------------------------------------------------------------
// show an error message, possibly during teardown of the process
AS_PRINTF(1, 2) static void lerror(const char *format, ...)
{
va_list va;
va_start(va, format);
#ifdef __NT__
char buf[MAXSTR];
qvsnprintf(buf, sizeof(buf), format, va);
// use MB_SERVICE_NOTIFICATION to prevent UI message loop from running since ida.exe is mostly shut down at this point
// and can crash if messages get processed
MessageBox(nullptr, buf, "IDA", MB_ICONERROR|MB_SERVICE_NOTIFICATION);
#else
qveprintf(format, va);
//qgetchar();
#endif
}
#define ERRMSG "Unexpected fatal error while initializing Python runtime. Please run idapyswitch to confirm or change the used Python runtime"
volatile sig_atomic_t initdone = 0;
//-------------------------------------------------------------------------
// some Python runtimes may call abort() or exit() if they don't like something
// catch this to avoid silent IDA exit
static void exithandler(void)
{
if ( !initdone )
{
initdone = 1;
lerror(ERRMSG);
// return to caller to continue exiting normally
}
}
//lint -e2761 call to non-async-signal-safe function '' within signal handler ''
//lint -e2762 call to signal registration function 'signal' within signal handler 'aborthandler'
//-------------------------------------------------------------------------
// catch unexpected abort() call
static void aborthandler(int sig)
{
lerror(ERRMSG);
initdone = 1; // avoid duplicate message on exit
// from https://www.gnu.org/software/libc/manual/html_node/Termination-in-Handler.html
/* Now reraise the signal. We reactivate the signal's
default handling, which is to terminate the process.
We could just call exit or abort,
but reraising the signal sets the return status
from the process correctly. */
signal(sig, SIG_DFL);
raise(sig);
}
//-------------------------------------------------------------------------
// Initialize the Python environment
bool idapython_plugin_t::init()
{
if ( Py_IsInitialized() != 0 )
return true;
// Read configuration
read_config_file2("idapython.cfg", opts, qnumber(opts),
/*defhdlr=*/ nullptr,
/*defines=*/ nullptr,
/*ndefines=*/ 0,
/*obj=*/ &this->config);
parse_plugin_options();
// Form the absolute path to IDA\python folder
{
char buf[QMAXPATH];
qmakepath(buf, sizeof(buf), idadir(PYTHON_DIR_NAME), QSTRINGIZE(PY_MAJOR_VERSION), nullptr);
idapython_dir = buf;
}
execution.timeout = config.execution_timeout;
// Check for the presence of essential files
if ( !_check_python_dir() )
return false;
char path[QMAXPATH];
qstring errbuf;
if ( !extapi.load(&errbuf) )
{
warning("Couldn't initialize IDAPython: %s", errbuf.c_str());
return false;
}
#ifdef __MAC__
if ( !extapi.lib_path.empty() )
{
// On OSX we should explicitly call Py_SetPythonHome().
// When using the system Python installation, sys.path will contain paths to other
// Python installations if they appear in $PATH. This can cause fatal errors during
// the system python's initialization.
//
// Note: The path will be something like:
// /System/Library/Frameworks/Python.framework/Versions/2.5/Python
// We need to strip the last part.
//
// Also, use a permanent buffer because Py_SetPythonHome() just stores a pointer
char utf8_pyhomepath[MAXSTR];
qstrncpy(utf8_pyhomepath, extapi.lib_path.c_str(), sizeof(utf8_pyhomepath));
char *lastslash = strrchr(utf8_pyhomepath, '/');
if ( lastslash != nullptr )
{
*lastslash = 0;
utf8_wchar_t(&pyhomepath, utf8_pyhomepath);
Py_SetPythonHome(pyhomepath.begin());
}
}
#endif
if ( config.alert_auto_scripts )
{
if ( pywraps_check_autoscripts(path, sizeof(path))
&& ask_yn(ASKBTN_NO,
"HIDECANCEL\n"
"TITLE IDAPython\n"
"The script '%s' was found in the current directory\n"
"and will be automatically executed by Python.\n"
"\n"
"Do you want to continue loading IDAPython?", path) <= 0 )
{
return false;
}
}
typedef void(*SignalHandlerPointer)(int);
// catch unexpected abort()
SignalHandlerPointer previousHandler = signal(SIGABRT, aborthandler);
// ... and exit()
atexit(exithandler);
// Start the interpreter
Py_InitializeEx(0 /* Don't catch SIGPIPE, SIGXFZ, SIGXFSZ & SIGINT signals */);
// disable handlers
initdone = 1;
signal(SIGABRT, previousHandler);
if ( !Py_IsInitialized() )
{
warning("IDAPython: Py_InitializeEx() failed");
return false;
}
// add new Python keywords as needed
python_highlighter.add_new_keywords();
// remove current directory
_prepare_sys_path();
if ( extapi.PyEval_ThreadsInitialized_ptr != nullptr
&& extapi.PyEval_InitThreads_ptr != nullptr )
{
// Enable multi-threading support (before 3.9
if ( !extapi.PyEval_ThreadsInitialized_ptr() )
extapi.PyEval_InitThreads_ptr();
}
#ifdef Py_DEBUG
msg("HexraysPython: Python compiled with DEBUG enabled.\n");
#endif
qstring dynload_base;