forked from idapython/src
-
Notifications
You must be signed in to change notification settings - Fork 5
/
pywraps.cpp
2002 lines (1824 loc) · 60 KB
/
pywraps.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
#include <pro.h>
#include <ieee.h>
#include <Python.h>
#include "pywraps.hpp"
#include "extapi.hpp"
#undef hook_to_notification_point
#undef unhook_from_notification_point
#undef show_wait_box
#undef hide_wait_box
//lint -esym(843,pywraps_initialized) could be declared const
//lint -esym(843,g_nw) could be declared const
//lint -esym(844,g_nw) could be declared const
//lint -esym(843,g_use_local_python) could be declared const
//------------------------------------------------------------------------
// String constants used
static const char S_PY_IDCCVT_VALUE_ATTR[] = "__idc_cvt_value__";
static const char S_PY_IDCCVT_ID_ATTR[] = "__idc_cvt_id__";
static const char S_PY_IDC_GLOBAL_VAR_FMT[] = "__py_cvt_gvar_%d";
#define S_PY_IDC_OPAQUE_T "py_idc_cvt_helper_t"
// Constants used by get_idaapi_class_reference()
#define PY_CLSID_CVT_INT64 0
#define PY_CLSID_APPCALL_SKEL_OBJ 1
#define PY_CLSID_CVT_BYREF 2
#define PY_CLSID_LAST 3
//---------------------------------------------------------------------------
// Use these macros to define script<->C fields
#define DEFINE_SCFIELDX(name, type, is_opt) { #name, type, qoffsetof(CUR_STRUC, name), is_opt }
#define DEFINE_SCFIELD(name, type) DEFINE_SCFIELDX(name, type, 0)
#define DEFINE_SCFIELD_OPT(name, type) DEFINE_SCFIELDX(name, type, 1)
//---------------------------------------------------------------------------
enum scfield_types_t
{
// Numeric fields
FT_FIRST_NUM,
FT_INT,
FT_SIZET,
FT_SSIZET,
FT_NUM16,
FT_NUM32,
FT_LAST_NUM,
// String field
FT_STR,
FT_CHAR,
// Object fields
FT_ARR,
// Allocated array of strings
FT_STRARR,
// Allocated array of 16bit numbers
FT_NUM16ARR,
// Fixed size character array. The size must be passed in the definition
FT_CHRARR_STATIC,
};
//---------------------------------------------------------------------------
struct scfld_t
{
const char *field_name;
uint32 field_type;
size_t field_offs;
bool is_optional;
};
#define FT_VALUE_MASK 0xFFFF0000
// Possible return values of conversion functions
#define FT_NOT_FOUND -1
#define FT_BAD_TYPE -2
#define FT_OK 1
static ref_t get_idaapi_attr_by_id(const int class_id);
static ref_t get_idaapi_attr(const char *attr);
//---------------------------------------------------------------------------
ref_t ida_export PyW_SizeVecToPyList(const sizevec_t &vec)
{
size_t n = vec.size();
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_list(PyList_New(n));
for ( size_t i = 0; i < n; ++i )
{
#ifdef PY3
PyList_SetItem(py_list.o, i, PyLong_FromSize_t(vec[i]));
#else
PyList_SetItem(py_list.o, i, PyInt_FromSize_t(vec[i]));
#endif
}
return ref_t(py_list);
}
//---------------------------------------------------------------------------
ref_t ida_export PyW_UvalVecToPyList(const uvalvec_t &vec)
{
size_t n = vec.size();
PYW_GIL_CHECK_LOCKED_SCOPE();
newref_t py_list(PyList_New(n));
for ( size_t i = 0; i < n; ++i )
PyList_SetItem(py_list.o, i, Py_BuildValue(PY_BV_UVAL, bvuval_t(vec[i])));
return ref_t(py_list);
}
//-------------------------------------------------------------------------
static Py_ssize_t pyvar_walk_list(
const ref_t &py_list,
int (idaapi *cb)(const ref_t &py_item, Py_ssize_t index, void *ud),
void *ud)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
PyObject *o = py_list.o;
if ( !PyList_CheckExact(o) && !PyW_IsSequenceType(o) )
{
PyErr_SetString(PyExc_ValueError, "Object is not a sequence");
return CIP_FAILED;
}
bool is_seq = !PyList_CheckExact(o);
Py_ssize_t seqsz = is_seq ? PySequence_Size(o) : PyList_Size(o);
for ( Py_ssize_t i = 0; i < seqsz; ++i )
{
// Get the item
ref_t py_item;
if ( is_seq )
py_item = newref_t(PySequence_GetItem(o, i));
else
py_item = borref_t(PyList_GetItem(o, i));
bool ok = py_item != NULL && cb(py_item, i, ud) == CIP_OK;
if ( ok )
{
// We cannot have, at the same time, a 'successful conversion', and
// the Python runtime raising an exception. It's up to the callback
// implementation to ensure that whatever it did, didn't cause an
// error to be set.
QASSERT(30604, PyErr_Occurred() == NULL);
}
else
{
if ( PyErr_Occurred() == NULL )
{
qstring m;
m.sprnt("Sequence item #%d cannot be converted", int(i));
PyErr_SetString(PyExc_ValueError, m.c_str());
}
return CIP_FAILED;
}
}
return seqsz;
}
//-------------------------------------------------------------------------
Py_ssize_t ida_export pyvar_walk_list(
PyObject *py_list,
int (idaapi *cb)(const ref_t &py_item, Py_ssize_t index, void *ud),
void *ud)
{
borref_t r(py_list);
return pyvar_walk_list(r, cb, ud);
}
//---------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PyListToSizeVec(sizevec_t *out, PyObject *py_list)
{
out->clear();
struct ida_local lambda_t
{
static int idaapi cvt(const ref_t &py_item, Py_ssize_t /*i*/, void *ud)
{
sizevec_t &vec = *static_cast<sizevec_t *>(ud);
uint64 num;
if ( !PyW_GetNumber(py_item.o, &num) )
return CIP_FAILED;
vec.push_back(size_t(num));
return CIP_OK;
}
};
return pyvar_walk_list(py_list, lambda_t::cvt, out);
}
//---------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PyListToEaVec(eavec_t *out, PyObject *py_list)
{
out->clear();
struct ida_local lambda_t
{
static int idaapi cvt(const ref_t &py_item, Py_ssize_t /*i*/, void *ud)
{
eavec_t &eavec = *(eavec_t *) ud;
ea_t ea = BADADDR;
{
#ifdef PY3
if ( PyLong_Check(py_item.o) )
{
unsigned long long ull = PyLong_AsUnsignedLongLong(py_item.o);
if ( ull == -1ULL && PyErr_Occurred() != NULL )
return CIP_FAILED;
ea = ea_t(ull);
}
else
{
return CIP_FAILED;
}
#else
if ( PyInt_Check(py_item.o) )
ea = PyInt_AsUnsignedLongMask(py_item.o);
else if ( PyLong_Check(py_item.o) )
ea = ea_t(PyLong_AsUnsignedLongLong(py_item.o));
else
return CIP_FAILED;
if ( PyErr_Occurred() != NULL )
return CIP_FAILED;
#endif
}
eavec.push_back(ea);
return CIP_OK;
}
};
return pyvar_walk_list(py_list, lambda_t::cvt, out);
}
//-------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PyListToEa64Vec(ea64vec_t *out, PyObject *py_list)
{
out->clear();
struct ida_local lambda_t
{
static int idaapi cvt(const ref_t &py_item, Py_ssize_t /*i*/, void *ud)
{
ea64vec_t &ea64vec = *(ea64vec_t *) ud;
ea64_t v = 0;
{
#ifdef PY3
if ( PyLong_Check(py_item.o) )
{
unsigned long long ull = PyLong_AsUnsignedLongLong(py_item.o);
if ( ull == -1ULL && PyErr_Occurred() != NULL )
return CIP_FAILED;
v = uint64(ull);
}
else
{
return CIP_FAILED;
}
#else
if ( PyInt_Check(py_item.o) )
v = PyInt_AsUnsignedLongMask(py_item.o);
else if ( PyLong_Check(py_item.o) )
v = uint64(PyLong_AsUnsignedLongLong(py_item.o));
else
return CIP_FAILED;
if ( PyErr_Occurred() != NULL )
return CIP_FAILED;
#endif
}
ea64vec.push_back(v);
return CIP_OK;
}
};
return pyvar_walk_list(py_list, lambda_t::cvt, out);
}
//---------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PyListToStrVec(qstrvec_t *out, PyObject *py_list)
{
out->clear();
struct ida_local lambda_t
{
static int idaapi cvt(const ref_t &py_item, Py_ssize_t /*i*/, void *ud)
{
qstrvec_t &strvec = *(qstrvec_t *)ud;
if ( !IDAPyStr_Check(py_item.o) )
return CIP_FAILED;
IDAPyStr_AsUTF8(&strvec.push_back(), py_item.o);
return CIP_OK;
}
};
return pyvar_walk_list(py_list, lambda_t::cvt, out);
}
//-------------------------------------------------------------------------
PyObject *ida_export meminfo_vec_t_to_py(meminfo_vec_t &ranges)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
PyObject *py_list = PyList_New(ranges.size());
meminfo_vec_t::const_iterator it, it_end(ranges.end());
Py_ssize_t i = 0;
for ( it=ranges.begin(); it != it_end; ++it, ++i )
{
const memory_info_t &mi = *it;
// start_ea end_ea name sclass sbase bitness perm
PyList_SetItem(py_list, i,
Py_BuildValue("(" PY_BV_EA PY_BV_EA "ss" PY_BV_EA "II)",
bvea_t(mi.start_ea),
bvea_t(mi.end_ea),
mi.name.c_str(),
mi.sclass.c_str(),
bvea_t(mi.sbase),
(unsigned int)(mi.bitness),
(unsigned int)mi.perm));
}
return py_list;
}
//-------------------------------------------------------------------------
static qvector<ref_t> py_compiled_form_vec;
//-------------------------------------------------------------------------
void ida_export PyW_register_compiled_form(PyObject *py_form)
{
ref_t ref = borref_t(py_form);
if ( !py_compiled_form_vec.has(ref) )
py_compiled_form_vec.push_back(ref);
}
//-------------------------------------------------------------------------
void ida_export PyW_unregister_compiled_form(PyObject *py_form)
{
ref_t ref = borref_t(py_form);
if ( py_compiled_form_vec.has(ref) )
py_compiled_form_vec.del(ref);
}
//-------------------------------------------------------------------------
static void free_compiled_form_instances(void)
{
while ( !py_compiled_form_vec.empty() )
{
const ref_t &ref = py_compiled_form_vec[0];
qstring title;
if ( !PyW_GetStringAttr(ref.o, "title", &title) )
title = "<unknown title>";
msg("WARNING: Form \"%s\" was not Free()d. Force-freeing.\n", title.c_str());
// Will call 'py_unregister_compiled_form()', and thus trim the vector down.
newref_t unused(PyObject_CallMethod(ref.o, (char *)"Free", "()"));
}
}
//-------------------------------------------------------------------------
// Checks if the given py_var is a special PyIdc_cvt_helper object.
// It does that by examining the magic attribute and returns its numeric value.
// It returns -1 if the object is not a recognized helper object.
// Any Python object can be treated as an cvt object if this attribute is created.
static int get_pyidc_cvt_type(PyObject *py_var)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
// Check if this our special by reference object
ref_t attr(PyW_TryGetAttrString(py_var, S_PY_IDCCVT_ID_ATTR));
if ( attr == NULL || !IDAPyIntOrLong_Check(attr.o) )
return -1;
return int(IDAPyIntOrLong_AsLong(attr.o));
}
//-------------------------------------------------------------------------
// Utility function to convert a python object to an IDC object
// and sets a python exception on failure.
bool ida_export pyvar_to_idcvar_or_error(const ref_t &py_obj, idc_value_t *idc_obj)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
int sn = 0;
bool ok = pyvar_to_idcvar(py_obj, idc_obj, &sn) >= CIP_OK;
if ( !ok )
PyErr_SetString(PyExc_ValueError, "Could not convert Python object to IDC object!");
return ok;
}
//------------------------------------------------------------------------
static idc_class_t *get_py_idc_cvt_opaque()
{
return find_idc_class(S_PY_IDC_OPAQUE_T);
}
//-------------------------------------------------------------------------
// Utility function to create opaque / convertible Python <-> IDC variables
// The referred Python variable will have its reference increased
static bool wrap_PyObject_ptr(const ref_t &py_var, idc_value_t *idc_var)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
// Create an IDC object of this special helper class
if ( idcv_object(idc_var, get_py_idc_cvt_opaque()) != eOk )
return false;
// Store the CVT id
idc_value_t idc_val;
idc_val.set_long(PY_ICID_OPAQUE);
set_idcv_attr(idc_var, S_PY_IDCCVT_ID_ATTR, idc_val);
// Store the value as a PVOID referencing the given Python object
py_var.incref();
idc_val.set_pvoid(py_var.o);
set_idcv_attr(idc_var, S_PY_IDCCVT_VALUE_ATTR, idc_val);
return true;
}
//------------------------------------------------------------------------
// IDC Opaque object destructor: when the IDC object dies we kill the
// opaque Python object along with it
static error_t idaapi py_idc_opaque_dtor(
idc_value_t *argv,
idc_value_t * /*res*/)
{
// This can be called at plugin registration time, when a
// 'script_plugin_t' instance is ::free()'d. It is
// not guaranteed that we have the GIL at that point.
PYW_GIL_GET;
// Get the value from the object
idc_value_t idc_val;
get_idcv_attr(&idc_val, &argv[0], S_PY_IDCCVT_VALUE_ATTR);
// Extract the Python object reference
PyObject *py_obj = (PyObject *)idc_val.pvoid;
// Decrease its reference (and eventually destroy it)
{
uninterruptible_op_t op;
Py_DECREF(py_obj);
}
return eOk;
}
static const char py_idc_cvt_helper_dtor_args[] = { VT_OBJ, 0 };
static const ext_idcfunc_t opaque_dtor_desc =
{
S_PY_IDC_OPAQUE_T ".dtor_name",
py_idc_opaque_dtor,
py_idc_cvt_helper_dtor_args,
NULL,
0,
0
};
//-------------------------------------------------------------------------
// Converts a Python variable into an IDC variable
// This function returns on one CIP_XXXX
static int pyvar_to_idcvar1(
const ref_t &py_var,
idc_value_t *idc_var,
int *gvar_sn,
qvector<const PyObject *> &_visited);
static int pyvar_to_idcvar2(
const ref_t &py_var,
idc_value_t *idc_var,
int *gvar_sn,
qvector<const PyObject *> &visited)
{
if ( !visited.add_unique(py_var.o) )
{
qstring buf;
buf.sprnt("<PyObject-%p-snipped-to-prevent-infinite-recursion>", py_var.o);
idc_var->_set_string(buf.c_str());
return CIP_OK;
}
// None / NULL
if ( py_var == NULL || py_var.o == Py_None )
{
idc_var->set_long(0);
}
// Numbers?
else if ( PyW_GetNumberAsIDC(py_var.o, idc_var) )
{
return CIP_OK;
}
// String
#ifdef PY3
else if ( PyBytes_Check(py_var.o) )
{
idc_var->_set_string(PyBytes_AsString(py_var.o), PyBytes_Size(py_var.o));
}
#else
else if ( PyString_Check(py_var.o) )
{
idc_var->_set_string(PyString_AsString(py_var.o), PyString_Size(py_var.o));
}
#endif
// Unicode
else if ( PyUnicode_Check(py_var.o) )
{
#ifdef PY3
qstring utf8;
IDAPyStr_AsUTF8(&utf8, py_var.o);
idc_var->_set_string(utf8.c_str(), utf8.length());
#else
newref_t utf8(PyUnicode_AsEncodedString(py_var.o, ENC_UTF8, "strict"));
return pyvar_to_idcvar1(utf8, idc_var, gvar_sn, visited);
#endif
}
// Boolean
else if ( PyBool_Check(py_var.o) )
{
idc_var->set_long(py_var.o == Py_True ? 1 : 0);
}
// Float
else if ( PyFloat_Check(py_var.o) )
{
double dresult = PyFloat_AsDouble(py_var.o);
ieee_realcvt((void *)&dresult, idc_var->e, 3);
idc_var->vtype = VT_FLOAT;
}
// void*
else if ( PyCapsule_IsValid(py_var.o, VALID_CAPSULE_NAME) )
{
idc_var->set_pvoid(PyCapsule_GetPointer(py_var.o, VALID_CAPSULE_NAME));
}
// Python list?
else if ( PyList_CheckExact(py_var.o) || PyW_IsSequenceType(py_var.o) )
{
// Create the object
idcv_object(idc_var);
// Determine list size and type
bool is_seq = !PyList_CheckExact(py_var.o);
Py_ssize_t size = is_seq ? PySequence_Size(py_var.o) : PyList_Size(py_var.o);
bool ok = true;
qstring attr_name;
// Convert each item
for ( Py_ssize_t i=0; i < size; i++ )
{
// Get the item
ref_t py_item;
if ( is_seq )
py_item = newref_t(PySequence_GetItem(py_var.o, i));
else
py_item = borref_t(PyList_GetItem(py_var.o, i));
// Convert the item into an IDC variable
idc_value_t v;
ok = pyvar_to_idcvar1(py_item, &v, gvar_sn, visited) >= CIP_OK;
if ( ok )
{
// Form the attribute name
#ifdef PY3
newref_t py_int(PyLong_FromSsize_t(i));
#else
newref_t py_int(PyInt_FromSsize_t(i));
#endif
ok = PyW_ObjectToString(py_int.o, &attr_name);
if ( !ok )
break;
// Store the attribute
set_idcv_attr(idc_var, attr_name.c_str(), v);
}
if ( !ok )
break;
}
return ok ? CIP_OK : CIP_FAILED;
}
// Dictionary: we convert to an IDC object
else if ( PyDict_Check(py_var.o) )
{
// Create an empty IDC object
idcv_object(idc_var);
// Get the dict.items() list
newref_t py_items(PyDict_Items(py_var.o));
// Get the size of the list
qstring key_name;
bool ok = true;
Py_ssize_t size = PySequence_Size(py_items.o);
for ( Py_ssize_t i=0; i < size; i++ )
{
// Get item[i] -> (key, value)
PyObject *py_item = PyList_GetItem(py_items.o, i);
// Extract key/value
newref_t key(PySequence_GetItem(py_item, 0));
newref_t val(PySequence_GetItem(py_item, 1));
// Get key's string representation
PyW_ObjectToString(key.o, &key_name);
// Convert the attribute into an IDC value
idc_value_t v;
ok = pyvar_to_idcvar1(val, &v, gvar_sn, visited) >= CIP_OK;
if ( ok )
{
// Store the attribute
set_idcv_attr(idc_var, key_name.c_str(), v);
}
if ( !ok )
break;
}
return ok ? CIP_OK : CIP_FAILED;
}
// Possible function?
else if ( PyCallable_Check(py_var.o) )
{
idc_var->clear();
idc_var->vtype = VT_FUNC;
idc_var->funcidx = -1; // Does not apply
return CIP_OK;
}
// Objects:
// - pyidc_cvt objects: int64, byref, opaque
// - other python objects
else
{
// Get the type
int cvt_id = get_pyidc_cvt_type(py_var.o);
switch ( cvt_id )
{
//
// INT64
//
case PY_ICID_INT64:
{
// Get the value attribute
ref_t attr(PyW_TryGetAttrString(py_var.o, S_PY_IDCCVT_VALUE_ATTR));
if ( attr == NULL )
return false;
idc_var->set_int64(PyLong_AsLongLong(attr.o));
return CIP_OK;
}
//
// BYREF
//
case PY_ICID_BYREF:
{
// BYREF always require this parameter
if ( gvar_sn == NULL )
return CIP_FAILED;
// Get the value attribute
ref_t attr(PyW_TryGetAttrString(py_var.o, S_PY_IDCCVT_VALUE_ATTR));
if ( attr == NULL )
return CIP_FAILED;
// Create a global variable
char buf[MAXSTR];
qsnprintf(buf, sizeof(buf), S_PY_IDC_GLOBAL_VAR_FMT, *gvar_sn);
idc_value_t *gvar = add_idc_gvar(buf);
// Convert the python value into the IDC global variable
bool ok = pyvar_to_idcvar1(attr, gvar, gvar_sn, visited) >= CIP_OK;
if ( ok )
{
(*gvar_sn)++;
// Create a reference to this global variable
create_idcv_ref(idc_var, gvar);
}
return ok ? CIP_OK : CIP_FAILED;
}
//
// OPAQUE
//
case PY_ICID_OPAQUE:
if ( !wrap_PyObject_ptr(py_var, idc_var) )
return CIP_FAILED;
return CIP_OK_OPAQUE;
//
// Other objects
//
default:
// A normal object?
{
newref_t py_dir(PyObject_Dir(py_var.o));
Py_ssize_t size = PyList_Size(py_dir.o);
if ( py_dir == NULL || !PyList_Check(py_dir.o) || size == 0 )
return CIP_FAILED;
// Create the IDC object
idcv_object(idc_var);
for ( Py_ssize_t i=0; i < size; i++ )
{
borref_t item(PyList_GetItem(py_dir.o, i));
#ifdef PY3
qstring field_name_buf;
IDAPyStr_AsUTF8(&field_name_buf, item.o);
const char *field_name = field_name_buf.begin();
#else
const char *field_name = PyString_AsString(item.o);
#endif
if ( field_name == NULL )
continue;
size_t len = strlen(field_name);
// Skip private attributes
if ( (len > 2 )
&& (strncmp(field_name, "__", 2) == 0 )
&& (strncmp(field_name+len-2, "__", 2) == 0) )
{
continue;
}
idc_value_t v;
newref_t attr(PyObject_GetAttrString(py_var.o, field_name));
if ( attr == NULL )
return CIP_FAILED;
else if ( pyvar_to_idcvar1(attr, &v, gvar_sn, visited) < CIP_OK )
return CIP_FAILED;
// Store the attribute
set_idcv_attr(idc_var, field_name, v);
}
}
break;
}
}
return CIP_OK;
}
//-------------------------------------------------------------------------
// Converts a Python variable into an IDC variable
// This function returns on one CIP_XXXX
static int pyvar_to_idcvar1(
const ref_t &py_var,
idc_value_t *idc_var,
int *gvar_sn,
qvector<const PyObject *> &_visited)
{
qvector<const PyObject *> visited = _visited;
return pyvar_to_idcvar2(py_var, idc_var, gvar_sn, visited);
}
//-------------------------------------------------------------------------
// Converts a Python variable into an IDC variable
// This function returns on one CIP_XXXX
int ida_export pyvar_to_idcvar(
const ref_t &py_var,
idc_value_t *idc_var,
int *gvar_sn)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
qvector<const PyObject *> visited;
return pyvar_to_idcvar1(py_var, idc_var, gvar_sn, visited);
}
//-------------------------------------------------------------------------
inline PyObject *cvt_to_pylong(int32 v)
{
return PyLong_FromLong(v);
}
inline PyObject *cvt_to_pylong(int64 v)
{
return PyLong_FromLongLong(v);
}
//-------------------------------------------------------------------------
// Converts an IDC variable to a Python variable
// If py_var points to an existing object then the object will be updated
// If py_var points to an existing immutable object then ZERO is returned
// Returns one of CIP_xxxx. Check pywraps.hpp
int ida_export idcvar_to_pyvar(
const idc_value_t &idc_var,
ref_t *py_var,
uint32 flags)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
switch ( idc_var.vtype )
{
case VT_PVOID:
if ( *py_var == NULL )
{
newref_t nr(PyCapsule_New(idc_var.pvoid, VALID_CAPSULE_NAME, NULL));
*py_var = nr;
}
else
{
return CIP_IMMUTABLE;
}
break;
case VT_INT64:
{
bool as_pylong = (flags & PYWCVTF_INT64_AS_UNSIGNED_PYLONG) != 0;
if ( as_pylong )
{
QASSERT(30513, *py_var == NULL); // recycling not supported in this case
*py_var = newref_t(PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) idc_var.i64));
return CIP_OK;
}
else
{
// Recycle?
if ( *py_var != NULL )
{
// Recycling an int64 object?
int t = get_pyidc_cvt_type(py_var->o);
if ( t != PY_ICID_INT64 )
return CIP_IMMUTABLE; // Cannot recycle immutable object
// Update the attribute
PyObject_SetAttrString(py_var->o, S_PY_IDCCVT_VALUE_ATTR, PyLong_FromLongLong(idc_var.i64));
return CIP_OK;
}
ref_t py_cls(get_idaapi_attr_by_id(PY_CLSID_CVT_INT64));
if ( py_cls == NULL )
return CIP_FAILED;
*py_var = newref_t(PyObject_CallFunctionObjArgs(py_cls.o, PyLong_FromLongLong(idc_var.i64), NULL));
if ( PyW_GetError() || *py_var == NULL )
return CIP_FAILED;
}
break;
}
case VT_STR:
if ( *py_var == NULL )
{
const qstring &s = idc_var.qstr();
if ( (flags & PYWCVTF_STR_AS_BYTES) != 0 )
*py_var = newref_t(IDAPyBytes_FromMemAndSize(s.begin(), s.length()));
else
*py_var = newref_t(IDAPyStr_FromUTF8AndSize(s.begin(), s.length()));
break;
}
else
return CIP_IMMUTABLE; // Cannot recycle immutable object
case VT_LONG:
// Cannot recycle immutable objects
if ( *py_var != NULL )
return CIP_IMMUTABLE;
*py_var = newref_t(cvt_to_pylong(idc_var.num));
break;
case VT_FLOAT:
if ( *py_var == NULL )
{
double x;
if ( ph.realcvt(&x, (uint16 *)idc_var.e, (sizeof(x)/2-1)|010) != 1 )
INTERR(30160);
*py_var = newref_t(PyFloat_FromDouble(x));
break;
}
else
return CIP_IMMUTABLE;
case VT_REF:
{
if ( *py_var == NULL )
{
ref_t py_cls(get_idaapi_attr_by_id(PY_CLSID_CVT_BYREF));
if ( py_cls == NULL )
return CIP_FAILED;
// Create a byref object with None value. We populate it later
*py_var = newref_t(PyObject_CallFunctionObjArgs(py_cls.o, Py_None, NULL));
if ( PyW_GetError() || *py_var == NULL )
return CIP_FAILED;
}
int t = get_pyidc_cvt_type(py_var->o);
if ( t != PY_ICID_BYREF )
return CIP_FAILED;
// Dereference
// (Since we are not using VREF_COPY flag, we can safely const_cast)
idc_value_t *dref_v = deref_idcv(const_cast<idc_value_t *>(&idc_var), VREF_LOOP);
if ( dref_v == NULL )
return CIP_FAILED;
// Can we recycle the object?
ref_t new_py_val(PyW_TryGetAttrString(py_var->o, S_PY_IDCCVT_VALUE_ATTR));
if ( new_py_val != NULL )
{
// Recycle
t = idcvar_to_pyvar(*dref_v, &new_py_val);
// Success? Nothing more to be done
if ( t == CIP_OK )
return CIP_OK;
// Clear it so we don't recycle it
new_py_val = ref_t();
}
// Try to convert (not recycle)
if ( idcvar_to_pyvar(*dref_v, &new_py_val) != CIP_OK )
return CIP_FAILED;
// Update the attribute
PyObject_SetAttrString(py_var->o, S_PY_IDCCVT_VALUE_ATTR, new_py_val.o);
break;
}
// Can convert back into a Python object or Python dictionary
// (Depending if py_var will be recycled and it was a dictionary)
case VT_OBJ:
{
// Check if this IDC object has __cvt_id__ and the __idc_cvt_value__ fields
idc_value_t idc_val;
if ( get_idcv_attr(&idc_val, &idc_var, S_PY_IDCCVT_ID_ATTR) == eOk
&& get_idcv_attr(&idc_val, &idc_var, S_PY_IDCCVT_VALUE_ATTR) == eOk )
{
// Extract the object
*py_var = borref_t((PyObject *) idc_val.pvoid);
return CIP_OK_OPAQUE;
}
ref_t obj;
bool is_dict = false;
// Need to create a new object?
if ( *py_var == NULL )
{
// Get skeleton class reference
ref_t py_cls(get_idaapi_attr_by_id(PY_CLSID_APPCALL_SKEL_OBJ));
if ( py_cls == NULL )
return CIP_FAILED;
// Call constructor
obj = newref_t(PyObject_CallFunctionObjArgs(py_cls.o, NULL));
if ( PyW_GetError() || obj == NULL )
return CIP_FAILED;
}
else
{
// Recycle existing variable
obj = *py_var;
if ( PyDict_Check(obj.o) )
is_dict = true;
}
// Walk the IDC attributes and store into python
for ( const char *attr_name = first_idcv_attr(&idc_var);
attr_name != NULL;
attr_name = next_idcv_attr(&idc_var, attr_name) )
{
// Get the attribute
idc_value_t v;
get_idcv_attr(&v, &idc_var, attr_name, true);
// Convert attribute to a python value (recursively)
ref_t py_attr;
int cvt = idcvar_to_pyvar(v, &py_attr);
if ( cvt <= CIP_IMMUTABLE )
return CIP_FAILED;
if ( is_dict )
PyDict_SetItemString(obj.o, attr_name, py_attr.o);
else
PyObject_SetAttrString(obj.o, attr_name, py_attr.o);
}
*py_var = obj;
break;
}
// Unhandled type
default:
*py_var = ref_t();
return CIP_FAILED;
}
return CIP_OK;
}
//-------------------------------------------------------------------------
// Converts IDC arguments to Python argument list or just one tuple
// If 'decref' is NULL then 'pargs' will contain one element which is the tuple
bool ida_export pyw_convert_idc_args(
const idc_value_t args[],
int nargs,
ref_vec_t &pargs,
uint32 flags,
qstring *errbuf)
{
PYW_GIL_CHECK_LOCKED_SCOPE();
ref_t py_tuple;
pargs.qclear();
bool as_tuple = (flags & PYWCVTF_AS_TUPLE) != 0;
if ( as_tuple )
{
py_tuple = newref_t(PyTuple_New(nargs));
if ( py_tuple == NULL )
{
if ( errbuf != NULL )
*errbuf = "Failed to create a new tuple to store arguments!";
return false;
}
}
for ( int i=0; i < nargs; i++ )
{
ref_t py_obj;
int cvt = idcvar_to_pyvar(args[i], &py_obj, flags);
if ( cvt < CIP_OK )
{
if ( errbuf != NULL )
errbuf->sprnt("arg#%d has wrong type %d", i, args[i].vtype);
return false;
}
if ( as_tuple )
{
// PyTuple_SetItem() steals the reference.
py_obj.incref();
QASSERT(30412, PyTuple_SetItem(py_tuple.o, i, py_obj.o) == 0);
}
else
{
pargs.push_back(py_obj);
}
}