forked from EiNSTeiN-/idapython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
python.cpp
1661 lines (1482 loc) · 45.6 KB
/
python.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
#ifdef __LINUX__
#include <dlfcn.h>
#endif
#ifdef __MAC__
#include <mach-o/dyld.h>
#endif
#include <ida.hpp>
#include <idp.hpp>
#include <expr.hpp>
#include <diskio.hpp>
#include <loader.hpp>
#include <kernwin.hpp>
#ifdef WITH_HEXRAYS
#include <hexrays.hpp>
hexdsp_t *hexdsp = NULL;
#endif
#include "pywraps.hpp"
//-------------------------------------------------------------------------
// 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_MAIN[] = "__main__";
static const char S_IDC_RUNPYTHON_STATEMENT[] = "RunPythonStatement";
static const char S_IDAPYTHON_DATA_NODE[] = "IDAPython_Data";
//-------------------------------------------------------------------------
// Types
//
enum script_run_when
{
run_on_db_open = 0, // run script after opening database (default)
run_on_ui_ready = 1, // run script when UI is ready
run_on_init = 2, // run script immediately on plugin load (shortly after IDA starts)
};
//-------------------------------------------------------------------------
// Global variables
static bool g_initialized = false;
static int g_run_when = -1;
static char g_run_script[QMAXPATH];
static char g_idapython_dir[QMAXPATH];
//-------------------------------------------------------------------------
// Prototypes and forward declarations
// Alias to SWIG_Init
//lint -esym(526,init_idaapi) not defined
extern "C" void init_idaapi(void);
// Plugin run() callback
void idaapi run(int arg);
//-------------------------------------------------------------------------
// This is a simple tracing code for debugging purposes.
// It might evolve into a tracing facility for user scripts.
//#define ENABLE_PYTHON_PROFILING
#ifdef ENABLE_PYTHON_PROFILING
#include "compile.h"
#include "frameobject.h"
int tracefunc(PyObject *obj, _frame *frame, int what, PyObject *arg)
{
PyObject *str;
/* Catch line change events. */
/* Print the filename and line number */
if ( what == PyTrace_LINE )
{
str = PyObject_Str(frame->f_code->co_filename);
if ( str )
{
msg("PROFILING: %s:%d\n", PyString_AsString(str), frame->f_lineno);
Py_DECREF(str);
}
}
return 0;
}
#endif
//-------------------------------------------------------------------------
// Helper routines to make Python script execution breakable from IDA
static int ninsns = 0; // number of times trace function was called
static bool box_displayed; // has the wait box been displayed?
static time_t start_time; // the start time of the execution
static int script_timeout = 2;
static bool g_ui_ready = false;
static bool g_alert_auto_scripts = true;
static bool g_remove_cwd_sys_path = false;
static bool g_use_local_python = false;
static void end_execution(void);
static void begin_execution(void);
//------------------------------------------------------------------------
// This callback is called on various interpreter events
static int break_check(PyObject *obj, _frame *frame, int what, PyObject *arg)
{
if ( wasBreak() )
{
// User pressed Cancel in the waitbox; send KeyboardInterrupt exception
PyErr_SetInterrupt();
}
else if ( !box_displayed && ++ninsns > 10 )
{
// We check the timer once every 10 calls
ninsns = 0;
// Timeout disabled or elapsed?
if ( script_timeout != 0 && (time(NULL) - start_time > script_timeout) )
{
box_displayed = true;
show_wait_box("Running Python script");
}
}
#ifdef ENABLE_PYTHON_PROFILING
return tracefunc(obj, frame, what, arg);
#else
qnotused(obj);
qnotused(frame);
qnotused(what);
qnotused(arg);
return 0;
#endif
}
//------------------------------------------------------------------------
static void reset_execution_time()
{
start_time = time(NULL);
ninsns = 0;
}
//------------------------------------------------------------------------
// Prepare for Python execution
static void begin_execution()
{
if ( !g_ui_ready || script_timeout == 0 )
return;
PYW_GIL_CHECK_LOCKED_SCOPE();
end_execution();
reset_execution_time();
PyEval_SetTrace(break_check, NULL);
}
//---------------------------------------------------------------------------
static void hide_script_waitbox()
{
if ( box_displayed )
{
hide_wait_box();
box_displayed = false;
}
}
//------------------------------------------------------------------------
// Called after Python execution finishes
static void end_execution()
{
hide_script_waitbox();
PYW_GIL_CHECK_LOCKED_SCOPE();
#ifdef ENABLE_PYTHON_PROFILING
PyEval_SetTrace(tracefunc, NULL);
#else
PyEval_SetTrace(NULL, NULL);
#endif
}
//-------------------------------------------------------------------------
//lint -esym(714,disable_script_timeout) Symbol not referenced
void disable_script_timeout()
{
// Clear timeout
script_timeout = 0;
// Uninstall the trace function and hide the waitbox (if it was shown)
end_execution();
}
//-------------------------------------------------------------------------
//lint -esym(714,set_script_timeout) Symbol not referenced
int set_script_timeout(int timeout)
{
// Update the timeout
qswap(timeout, script_timeout);
// Reset the execution time and hide the waitbox (so it is shown again after timeout elapses)
reset_execution_time();
hide_script_waitbox();
return timeout;
}
//------------------------------------------------------------------------
// Return a formatted error or just print it to the console
static void handle_python_error(
char *errbuf,
size_t errbufsize,
bool clear_error = true)
{
if ( errbufsize > 0 )
errbuf[0] = '\0';
// No exception?
if ( !PyErr_Occurred() )
return;
qstring s;
if ( PyW_GetError(&s, clear_error) )
qstrncpy(errbuf, s.c_str(), errbufsize);
}
//------------------------------------------------------------------------
// Helper function to get globals for the __main__ module
// Note: The references are borrowed. No need to free them.
static PyObject *GetMainGlobals()
{
PyObject *module = PyImport_AddModule(S_MAIN);
return module == NULL ? NULL : PyModule_GetDict(module);
}
//------------------------------------------------------------------------
static void PythonEvalOrExec(
const char *str,
const char *filename = "<string>")
{
// Compile as an expression
PYW_GIL_CHECK_LOCKED_SCOPE();
PyCompilerFlags cf = {0};
newref_t py_code(Py_CompileStringFlags(str, filename, Py_eval_input, &cf));
if ( py_code == NULL || PyErr_Occurred() )
{
// Not an expression?
PyErr_Clear();
// Run as a string
PyRun_SimpleString(str);
}
else
{
PyObject *py_globals = GetMainGlobals();
newref_t py_result(
PyEval_EvalCode(
(PyCodeObject *) py_code.o,
py_globals,
py_globals));
if ( py_result == NULL || PyErr_Occurred() )
{
PyErr_Print();
}
else
{
qstring result_str;
if ( py_result.o != Py_None && PyW_ObjectToString(py_result.o, &result_str) )
msg("%s\n", result_str.c_str());
}
}
}
//------------------------------------------------------------------------
// Executes a simple string
static bool idaapi IDAPython_extlang_run_statements(
const char *str,
char *errbuf,
size_t errbufsize)
{
PYW_GIL_GET;
PyObject *globals = GetMainGlobals();
bool ok;
if ( globals == NULL )
{
ok = false;
}
else
{
errbuf[0] = '\0';
PyErr_Clear();
begin_execution();
newref_t result(PyRun_String(
str,
Py_file_input,
globals,
globals));
end_execution();
ok = result != NULL && !PyErr_Occurred();
if ( !ok )
handle_python_error(errbuf, errbufsize);
}
if ( !ok && errbuf[0] == '\0' )
qstrncpy(errbuf, "internal error", errbufsize);
return ok;
}
//------------------------------------------------------------------------
// Simple Python statement runner function for IDC
static const char idc_runpythonstatement_args[] = { VT_STR2, 0 };
static error_t idaapi idc_runpythonstatement(
idc_value_t *argv,
idc_value_t *res)
{
char errbuf[MAXSTR];
bool ok = IDAPython_extlang_run_statements(argv[0].c_str(), errbuf, sizeof(errbuf));
if ( ok )
res->set_long(0);
else
res->set_string(errbuf);
return eOk;
}
//--------------------------------------------------------------------------
const char *idaapi set_python_options(
const char *keyword,
int value_type,
const void *value)
{
do
{
if ( value_type == IDPOPT_NUM )
{
if ( qstrcmp(keyword, "SCRIPT_TIMEOUT") == 0 )
{
script_timeout = int(*(uval_t *)value);
break;
}
else if ( qstrcmp(keyword, "ALERT_AUTO_SCRIPTS") == 0 )
{
g_alert_auto_scripts = *(uval_t *)value != 0;
break;
}
else if ( qstrcmp(keyword, "REMOVE_CWD_SYS_PATH") == 0 )
{
g_remove_cwd_sys_path = *(uval_t *)value != 0;
break;
}
else if ( qstrcmp(keyword, "USE_LOCAL_PYTHON") == 0 )
{
g_use_local_python = *(uval_t *)value != 0;
break;
}
}
return IDPOPT_BADKEY;
} while (false);
return IDPOPT_OK;
}
//-------------------------------------------------------------------------
// Check for the presence of a file in IDADIR/python and complain on error
bool CheckScriptFiles()
{
static const char *const script_files[] =
{
S_IDC_MODNAME ".py",
S_INIT_PY,
"idaapi.py",
"idautils.py"
};
for ( size_t i=0; i<qnumber(script_files); i++ )
{
char filepath[QMAXPATH];
qmakepath(filepath, sizeof(filepath), g_idapython_dir, script_files[i], NULL);
if ( !qfileexist(filepath) )
{
warning("IDAPython: Missing required file: '%s'", script_files[i]);
return false;
}
}
return true;
}
//-------------------------------------------------------------------------
// This function will execute a script in the main module context
// It does not use 'import', thus the executed script will not yield a new module name
// Caller of this function should call handle_python_error() to clear the exception and print the error
static int PyRunFile(const char *FileName)
{
#ifdef __NT__
// if the current disk has no space (sic, the current directory, not the one
// with the input file), PyRun_File() will die with a cryptic message that
// C runtime library could not be loaded. So we check the disk space before
// calling it.
char curdir[QMAXPATH];
if ( _getcwd(curdir, sizeof(curdir)) == NULL
|| getdspace(curdir) == 0 )
{
warning("No free disk space on %s, python will not be available", curdir);
return 0;
}
#endif
PYW_GIL_CHECK_LOCKED_SCOPE();
PyObject *file_obj = PyFile_FromString((char*)FileName, "r"); //lint !e1776
PyObject *globals = GetMainGlobals();
if ( globals == NULL || file_obj == NULL )
{
Py_XDECREF(file_obj);
return 0;
}
PyErr_Clear();
PyObject *result = PyRun_File(
PyFile_AsFile(file_obj),
FileName,
Py_file_input,
globals,
globals);
Py_XDECREF(file_obj);
int rc = result != NULL && !PyErr_Occurred();
Py_XDECREF(result);
return rc;
}
//-------------------------------------------------------------------------
// Execute Python statement(s) from an editor window
void IDAPython_RunStatement(void)
{
char statement[16 * MAXSTR];
netnode history;
// Get the existing or create a new netnode in the database
history.create(S_IDAPYTHON_DATA_NODE);
// Fetch the previous statement
size_t statement_size = sizeof(statement);
if ( history.getblob(statement, &statement_size, 0, 'A') == NULL )
statement[0] = '\0';
if ( asktext(sizeof(statement), statement, statement, "ACCEPT TABS\nEnter Python expressions") != NULL )
{
begin_execution();
PyRun_SimpleString(statement);
end_execution();
// Store the statement to the database
history.setblob(statement, strlen(statement) + 1, 0, 'A');
}
}
//-------------------------------------------------------------------------
// 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,
char *errbuf,
size_t errbufsize)
{
if ( errbufsize > 0 )
errbuf[0] = '\0';
if ( py_result == NULL )
{
handle_python_error(errbuf, errbufsize);
return false;
}
int cvt = CIP_OK;
if ( idc_result != NULL )
{
idc_result->clear();
cvt = pyvar_to_idcvar(py_result, idc_result);
if ( cvt < CIP_OK )
qsnprintf(errbuf, errbufsize, "ERROR: bad return value");
}
return cvt >= CIP_OK;
}
//-------------------------------------------------------------------------
// This function will call the Python function 'idaapi.IDAPython_ExecFile'
// It does not use 'import', thus the executed script will not yield a new module name
// It returns the exception and traceback information.
// We use the Python function to execute the script because it knows how to deal with
// module reloading.
static bool IDAPython_ExecFile(
const char *FileName,
char *errbuf,
size_t errbufsz,
const char *idaapi_script = S_IDAAPI_EXECSCRIPT,
idc_value_t *second_res = NULL,
bool want_tuple = false)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
ref_t py_execscript(get_idaapi_attr(idaapi_script));
if ( py_execscript == NULL )
{
qsnprintf(errbuf, errbufsz, "Could not find idaapi.%s ?!", idaapi_script);
return false;
}
char script[MAXSTR];
qstrncpy(script, FileName, sizeof(script));
strrpl(script, '\\', '/');
newref_t py_script(PyString_FromString(script));
newref_t py_ret(PyObject_CallFunctionObjArgs(
py_execscript.o,
py_script.o,
GetMainGlobals(),
NULL));
// Failure at this point means the script was interrupted
bool interrupted = false;
qstring err;
if ( PyW_GetError(&err) || py_ret == NULL )
{
PyErr_Clear();
if ( err.empty() )
qstrncpy(errbuf, "Script interrupted", errbufsz);
else
qstrncpy(errbuf, err.c_str(), errbufsz);
interrupted = true;
}
bool ok = false;
if ( !interrupted )
{
PyObject *ret_o;
if ( want_tuple )
{
if ( second_res != NULL
&& PyTuple_Check(py_ret.o)
&& PyTuple_Size(py_ret.o) == 2 )
{
ret_o = PyTuple_GetItem(py_ret.o, 0); // Borrowed reference
}
else
{
INTERR(30444);
}
}
else
{
ret_o = py_ret.o;
}
if ( ret_o == Py_None )
{
if ( want_tuple )
{
borref_t ret2_o(PyTuple_GetItem(py_ret.o, 1));
ok = return_python_result(second_res, ret2_o, errbuf, errbufsz);
}
else
{
ok = true;
}
}
else if ( PyString_Check(ret_o) )
{
qstrncpy(errbuf, PyString_AsString(ret_o), errbufsz);
}
else
{
INTERR(30154);
}
}
return ok;
}
//-------------------------------------------------------------------------
// Execute the Python script from the plugin
static bool RunScript(const char *script)
{
begin_execution();
char errbuf[MAXSTR];
bool ok = IDAPython_ExecFile(script, errbuf, sizeof(errbuf));
if ( !ok )
warning("IDAPython: error executing '%s':\n%s", script, errbuf);
end_execution();
return 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_IDAAPI_MODNAME)
{
const char *p = strchr(full_name, '.');
if ( p == NULL )
{
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 != NULL;
}
//-------------------------------------------------------------------------
// Compile callback for Python external language evaluator
bool idaapi IDAPython_extlang_compile(
const char *name,
ea_t /*current_ea*/,
const char *expr,
char *errbuf,
size_t errbufsize)
{
PYW_GIL_GET;
PyObject *globals = GetMainGlobals();
PyCodeObject *code = (PyCodeObject *)Py_CompileString(expr, "<string>", Py_eval_input);
if ( code == NULL )
{
handle_python_error(errbuf, errbufsize);
return false;
}
// Set the desired function name
Py_XDECREF(code->co_name);
code->co_name = PyString_FromString(name);
// Create a function out of code
PyObject *func = PyFunction_New((PyObject *)code, globals);
if ( func == NULL )
{
ERR:
handle_python_error(errbuf, errbufsize);
Py_XDECREF(code);
return false;
}
int err = PyDict_SetItemString(globals, name, func);
Py_XDECREF(func);
if ( err )
goto ERR;
return true;
}
//-------------------------------------------------------------------------
// Run callback for Python external language evaluator
bool idaapi IDAPython_extlang_run(
const char *name,
int nargs,
const idc_value_t args[],
idc_value_t *result,
char *errbuf,
size_t errbufsize)
{
PYW_GIL_GET;
// Try to extract module name (if any) from the funcname
char modname[MAXSTR] = {0};
char funcname[MAXSTR] = {0};
bool imported_module = parse_py_modname(name, modname, funcname, MAXSTR);
bool ok = true;
PyObject *module = NULL;
ref_vec_t pargs;
do
{
// Convert arguments to python
ok = pyw_convert_idc_args(args, nargs, pargs, false, errbuf, errbufsize);
if ( !ok )
break;
if ( imported_module )
{
module = PyImport_ImportModule(modname);
}
else
{
module = PyImport_AddModule(S_MAIN);
QASSERT(30156, module != NULL);
}
PyObject *globals = PyModule_GetDict(module);
QASSERT(30157, globals != NULL);
PyObject *func = PyDict_GetItemString(globals, funcname);
if ( func == NULL )
{
qsnprintf(errbuf, errbufsize, "undefined function %s", name);
ok = false;
break;
}
borref_t code(PyFunction_GetCode(func));
qvector<PyObject*> pargs_ptrs;
pargs.to_pyobject_pointers(&pargs_ptrs);
newref_t py_res(PyEval_EvalCodeEx(
(PyCodeObject*) code.o,
globals, NULL,
pargs_ptrs.begin(),
nargs,
NULL, 0, NULL, 0, NULL));
ok = return_python_result(result, py_res, errbuf, errbufsize);
} while ( false );
if ( imported_module )
Py_XDECREF(module);
return ok;
}
//-------------------------------------------------------------------------
// Compile callback for Python external language evaluator
bool idaapi IDAPython_extlang_compile_file(
const char *filename,
char *errbuf,
size_t errbufsize)
{
PYW_GIL_GET;
begin_execution();
bool ok = IDAPython_ExecFile(filename, errbuf, errbufsize);
end_execution();
return ok;
}
//-------------------------------------------------------------------------
// Load processor module callback for Python external language evaluator
static bool idaapi IDAPython_extlang_loadprocmod(
const char *filename,
idc_value_t *procobj,
char *errbuf,
size_t errbufsize)
{
PYW_GIL_GET;
begin_execution();
bool ok = IDAPython_ExecFile(filename, errbuf, errbufsize, S_IDAAPI_LOADPROCMOD, procobj, true);
if ( ok && procobj->is_zero() )
{
errbuf[0] = '\0';
ok = false;
}
end_execution();
return ok;
}
//-------------------------------------------------------------------------
// Unload processor module callback for Python external language evaluator
static bool idaapi IDAPython_extlang_unloadprocmod(
const char *filename,
char *errbuf,
size_t errbufsize)
{
PYW_GIL_GET;
begin_execution();
bool ok = IDAPython_ExecFile(filename, errbuf, errbufsize, S_IDAAPI_UNLOADPROCMOD);
end_execution();
return ok;
}
//-------------------------------------------------------------------------
// Create an object instance
bool idaapi IDAPython_extlang_create_object(
const char *name, // in: object class name
int nargs, // in: number of input arguments
const idc_value_t args[], // in: input arguments
idc_value_t *result, // out: created object or exception
char *errbuf, // out: error message if evaluation fails
size_t errbufsize) // in: size of the error buffer
{
PYW_GIL_GET;
bool ok = false;
ref_vec_t pargs;
do
{
// Parse the object name (to get the module and class name)
char modname[MAXSTR] = {0};
char clsname[MAXSTR] = {0};
parse_py_modname(name, modname, clsname, MAXSTR);
// Get a reference to the module
ref_t py_mod(PyW_TryImportModule(modname));
if ( py_mod == NULL )
{
qsnprintf(errbuf, errbufsize, "Could not import module '%s'!", modname);
break;
}
// Get the class reference
ref_t py_cls(PyW_TryGetAttrString(py_mod.o, clsname));
if ( py_cls == NULL )
{
qsnprintf(errbuf, errbufsize, "Could not find class type '%s'!", clsname);
break;
}
// Error during conversion?
ok = pyw_convert_idc_args(args, nargs, pargs, true, errbuf, errbufsize);
if ( !ok )
break;
// Call the constructor
newref_t py_res(PyObject_CallObject(py_cls.o, pargs.empty() ? NULL : pargs[0].o));
ok = return_python_result(result, py_res, errbuf, errbufsize);
} while ( false );
return ok;
}
//-------------------------------------------------------------------------
// Returns the attribute value of a given object from the global scope
bool idaapi IDAPython_extlang_get_attr(
const idc_value_t *obj, // in: object (may be NULL)
const char *attr, // in: attribute name
idc_value_t *result)
{
PYW_GIL_GET;
int cvt = CIP_FAILED;
do
{
// Get a reference to the module
ref_t py_mod(PyW_TryImportModule(S_MAIN));
if ( py_mod == NULL )
break;
// Object specified:
// - (1) string contain attribute name in the main module
// - (2) opaque object (we use it as is)
ref_t py_obj;
if ( obj != NULL )
{
// (1) Get attribute from main module
if ( obj->vtype == VT_STR2 )
{
py_obj = PyW_TryGetAttrString(py_mod.o, obj->c_str());
}
// (2) see if opaque object
else
{
// Convert object (expecting opaque object)
cvt = idcvar_to_pyvar(*obj, &py_obj);
if ( cvt != CIP_OK_OPAQUE ) // Only opaque objects are accepted
{
py_obj = ref_t();
cvt = CIP_FAILED;
break;
}
}
// Get the attribute reference
if ( py_obj == NULL )
break;
}
// No object specified:
else
{
// ...then work with main module
py_obj = py_mod;
}
// Special case: if attribute not passed then retrieve the class
// name associated associated with the passed object
if ( attr == NULL || attr[0] == '\0' )
{
cvt = CIP_FAILED;
// Get the class
newref_t cls(PyObject_GetAttrString(py_obj.o, "__class__"));
if ( cls == NULL )
break;
// Get its name
newref_t name(PyObject_GetAttrString(cls.o, "__name__"));
if ( name == NULL )
break;
// Convert name object to string object
newref_t string(PyObject_Str(name.o));
if ( string == NULL )
break;
// Convert name python string to a C string
const char *clsname = PyString_AsString(string.o);
if ( clsname == NULL )
break;
result->set_string(clsname);
cvt = CIP_OK; //lint !e838
break;
}
ref_t py_attr(PyW_TryGetAttrString(py_obj.o, attr));
// No attribute?
if ( py_attr == NULL )
{
cvt = CIP_FAILED;
break;
}
// Don't store result
if ( result == NULL )
{
cvt = CIP_OK;
// Decrement attribute (because of GetAttrString)
}
else
{
cvt = pyvar_to_idcvar(py_attr, result);
// // Conversion succeeded and opaque object was passed:
// // Since the object will be passed to IDC, it is likely that IDC value will be
// // destroyed and also destroying the opaque object with it. That is an undesired effect.
// // We increment the reference of the object so that even if the IDC value dies
// // the opaque object remains. So by not decrement reference after GetAttrString() call
// // we are indirectly increasing the reference. If it was not opaque then we decrement the reference.
// if ( cvt >= CIP_OK && cvt != CIP_OK_NODECREF )
// {
// // Decrement the reference (that was incremented by GetAttrString())
// py_attr.decref();
// }
}
} while ( false );
return cvt >= CIP_OK;
}
//-------------------------------------------------------------------------
// Returns the attribute value of a given object from the global scope
//lint -e{818}
bool idaapi IDAPython_extlang_set_attr(
idc_value_t *obj, // in: object name (may be NULL)
const char *attr, // in: attribute name
idc_value_t *value)
{
PYW_GIL_GET;
bool ok = false;
do
{
// Get a reference to the module
ref_t py_mod(PyW_TryImportModule(S_MAIN));
if ( py_mod == NULL )
break;
ref_t py_obj;
if ( obj != NULL )
{
// Get the attribute reference (from just a name)
if ( obj->vtype == VT_STR2 )
{
py_obj = PyW_TryGetAttrString(py_mod.o, obj->c_str());
}
else
{
int cvt = idcvar_to_pyvar(*obj, &py_obj);
if ( cvt != CIP_OK_OPAQUE ) // Only opaque objects are accepted
py_obj = ref_t();
}
// No object to set_attr on?
if ( py_obj == NULL )
break;
}
else
{
// set_attr on the main module
py_obj = py_mod;
}
// Convert the value
ref_t py_var;
int cvt = idcvar_to_pyvar(*value, &py_var);
if ( cvt >= CIP_OK )
{
ok = PyObject_SetAttrString(py_obj.o, attr, py_var.o) != -1;
// if ( cvt != CIP_OK_NODECREF )
// Py_XDECREF(py_var);