-
Notifications
You must be signed in to change notification settings - Fork 289
/
pywraps.cpp
2062 lines (1873 loc) · 62.3 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 <parsejson.hpp>
#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 )
PyList_SetItem(py_list.o, i, PyLong_FromSize_t(vec[i]));
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);
}
//-------------------------------------------------------------------------
ref_t ida_export PyW_StrVecToPyList(const qstrvec_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, PyUnicode_from_qstring(vec[i]));
return ref_t(py_list);
}
//-------------------------------------------------------------------------
static Py_ssize_t pyvar_walk_seq(
const ref_t &py_list,
int (idaapi *cb)(const ref_t &py_item, Py_ssize_t index, void *ud),
void *ud,
size_t maxsize)
{
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);
if ( maxsize < seqsz )
seqsz = maxsize;
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 && 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() == nullptr);
}
else
{
if ( PyErr_Occurred() == nullptr )
{
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_seq(
PyObject *py_list,
int (idaapi *cb)(const ref_t &py_item, Py_ssize_t index, void *ud),
void *ud,
size_t maxsize)
{
borref_t r(py_list);
return pyvar_walk_seq(r, cb, ud, maxsize);
}
//---------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PySeqToSizeVec(sizevec_t *out, PyObject *py_list, size_t maxsize)
{
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_seq(py_list, lambda_t::cvt, out, maxsize);
}
//---------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PySeqToEaVec(
eavec_t *out,
PyObject *py_list,
size_t maxsize)
{
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;
{
if ( PyLong_Check(py_item.o) )
{
unsigned long long ull = PyLong_AsUnsignedLongLong(py_item.o);
if ( ull == -1ULL && PyErr_Occurred() != nullptr )
return CIP_FAILED;
ea = ea_t(ull);
}
else
{
return CIP_FAILED;
}
}
eavec.push_back(ea);
return CIP_OK;
}
};
return pyvar_walk_seq(py_list, lambda_t::cvt, out, maxsize);
}
//-------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PySeqToTidVec(
qvector<tid_t> *out,
PyObject *py_list,
size_t maxsize)
{
return PyW_PySeqToEaVec((eavec_t *) out, py_list, maxsize);
}
//-------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PySeqToEa64Vec(ea64vec_t *out, PyObject *py_list, size_t maxsize)
{
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;
{
if ( PyLong_Check(py_item.o) )
{
unsigned long long ull = PyLong_AsUnsignedLongLong(py_item.o);
if ( ull == -1ULL && PyErr_Occurred() != nullptr )
return CIP_FAILED;
v = uint64(ull);
}
else
{
return CIP_FAILED;
}
}
ea64vec.push_back(v);
return CIP_OK;
}
};
return pyvar_walk_seq(py_list, lambda_t::cvt, out, maxsize);
}
//---------------------------------------------------------------------------
Py_ssize_t ida_export PyW_PySeqToStrVec(qstrvec_t *out, PyObject *py_list, size_t maxsize)
{
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 ( !PyUnicode_Check(py_item.o) )
return CIP_FAILED;
PyUnicode_as_qstring(&strvec.push_back(), py_item.o);
return CIP_OK;
}
};
return pyvar_walk_seq(py_list, lambda_t::cvt, out, maxsize);
}
//-------------------------------------------------------------------------
PyObject *ida_export PyW_from_jvalue_t(const jvalue_t &v)
{
do
{
if ( v.type() == JT_UNKNOWN )
break;
newref_t json_module(PyImport_ImportModule("json"));
if ( !json_module )
break;
borref_t json_globals(PyModule_GetDict(json_module.o));
if ( !json_globals )
break;
borref_t json_loads(PyDict_GetItemString(json_globals.o, "loads"));
if ( !json_loads )
break;
qstring clob;
if ( !serialize_json(&clob, v) )
break;
ref_t dict = newref_t(PyObject_CallFunction(json_loads.o, "s", clob.c_str()));
if ( !dict )
break;
dict.incref();
return dict.o;
} while ( false );
Py_RETURN_NONE;
}
//-------------------------------------------------------------------------
bool ida_export PyW_to_jvalue_t(jvalue_t *out, PyObject *py)
{
do
{
newref_t json_module(PyImport_ImportModule("json"));
if ( !json_module )
break;
borref_t json_globals(PyModule_GetDict(json_module.o));
if ( !json_globals )
break;
borref_t json_dumps(PyDict_GetItemString(json_globals.o, "dumps"));
if ( !json_dumps )
break;
newref_t str(PyObject_CallFunction(json_dumps.o, "O", py));
qstring buf;
if ( !PyUnicode_as_qstring(&buf, str.o) )
break;
if ( parse_json_string(out, buf.c_str()) != eOk )
break;
return true;
} while ( false );
return false;
}
//-------------------------------------------------------------------------
PyObject *ida_export PyW_from_jobj_t(const jobj_t &o)
{
jvalue_t v;
v.set_obj((jobj_t *) &o);
PyObject *rc = PyW_from_jvalue_t(v);
v.extract_obj();
return rc;
}
//-------------------------------------------------------------------------
bool ida_export PyW_to_jobj_t(jobj_t *out, PyObject *py)
{
if ( !PyDict_Check(py) )
return false;
jvalue_t v;
bool rc = PyW_to_jvalue_t(&v, py) && v.type() == JT_OBJ;
if ( rc )
out->swap(v.obj());
return rc;
}
//-------------------------------------------------------------------------
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)
{
int max_nloop = py_compiled_form_vec.size();
max_nloop *= 10; // i'm feeling generous today
int cnt = 0;
while ( !py_compiled_form_vec.empty() )
{
const ref_t &ref = py_compiled_form_vec.back();
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 result(PyObject_CallMethod(ref.o, (char *)"Free", "()"));
if ( !result && PyErr_Occurred() != nullptr )
{
msg("WARNING: Couldn't free form object at %p:\n", ref.o);
PyErr_Print();
py_compiled_form_vec.del(ref);
}
if ( ++cnt >= max_nloop )
{
#ifdef TESTABLE_BUILD
INTERR(30640); // too many iterations, probably we are looping endlessly
#endif
break;
}
}
}
//-------------------------------------------------------------------------
// 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 == nullptr || !PyLong_Check(attr.o) )
return -1;
return int(PyLong_AsLong(attr.o));
}
//-------------------------------------------------------------------------
static inline bool is_pyidc_cvt_type_int64(PyObject *py_var)
{
return get_pyidc_cvt_type(py_var) == PY_ICID_INT64;
}
//-------------------------------------------------------------------------
// 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,
nullptr,
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 / nullptr
if ( py_var == nullptr || py_var.o == Py_None )
{
idc_var->set_long(0);
}
// Numbers?
else if ( PyW_GetNumberAsIDC(py_var.o, idc_var) )
{
return CIP_OK;
}
// String
else if ( PyBytes_Check(py_var.o) )
{
idc_var->_set_string(PyBytes_AsString(py_var.o), PyBytes_Size(py_var.o));
}
// Unicode
else if ( PyUnicode_Check(py_var.o) )
{
qstring utf8;
PyUnicode_as_qstring(&utf8, py_var.o);
idc_var->_set_string(utf8.c_str(), utf8.length());
}
// 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
newref_t py_int(PyLong_FromSsize_t(i));
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 == nullptr )
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 == nullptr )
return CIP_FAILED;
// Get the value attribute
ref_t attr(PyW_TryGetAttrString(py_var.o, S_PY_IDCCVT_VALUE_ATTR));
if ( attr == nullptr )
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 || !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));
qstring field_name_buf;
PyUnicode_as_qstring(&field_name_buf, item.o);
const char *field_name = field_name_buf.begin();
if ( field_name == nullptr )
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 )
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);
}
//-------------------------------------------------------------------------
// helpers to use with idc_value_t::num (which can be 32-, or 64-bit.)
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 == nullptr )
{
newref_t nr(PyCapsule_New(idc_var.pvoid, VALID_CAPSULE_NAME, nullptr));
*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 == nullptr); // 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 )
{
// Recycling an int64 object?
if ( !is_pyidc_cvt_type_int64(py_var->o) )
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 == nullptr )
return CIP_FAILED;
*py_var = newref_t(PyObject_CallFunctionObjArgs(py_cls.o, PyLong_FromLongLong(idc_var.i64), nullptr));
if ( PyW_GetError() || !*py_var )
return CIP_FAILED;
}
break;
}
case VT_STR:
if ( *py_var == nullptr )
{
const qstring &s = idc_var.qstr();
if ( (flags & PYWCVTF_STR_AS_BYTES) != 0 )
*py_var = newref_t(PyBytes_FromStringAndSize(s.begin(), s.length()));
else
*py_var = newref_t(PyUnicode_FromStringAndSize(s.begin(), s.length()));
break;
}
else
return CIP_IMMUTABLE; // Cannot recycle immutable object
case VT_LONG:
// Cannot recycle immutable objects
if ( *py_var )
{
// Recycling an int64 object?
if ( !is_pyidc_cvt_type_int64(py_var->o) )
return CIP_IMMUTABLE;
// Update the attribute
PyObject_SetAttrString(py_var->o, S_PY_IDCCVT_VALUE_ATTR, cvt_to_pylong(idc_var.num));
return CIP_OK;
}
*py_var = newref_t(cvt_to_pylong(idc_var.num));
break;
case VT_FLOAT:
if ( !*py_var )
{
double x;
if ( processor_t::realcvt(&x, (fpvalue_t*)&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 )
{
ref_t py_cls(get_idaapi_attr_by_id(PY_CLSID_CVT_BYREF));
if ( py_cls == nullptr )
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, nullptr));
if ( PyW_GetError() || !*py_var )
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 == nullptr )
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 != nullptr )
{
// 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 == nullptr )
{
// Get skeleton class reference
ref_t py_cls(get_idaapi_attr_by_id(PY_CLSID_APPCALL_SKEL_OBJ));
if ( py_cls == nullptr )
return CIP_FAILED;
// Call constructor
obj = newref_t(PyObject_CallFunctionObjArgs(py_cls.o, nullptr));
if ( PyW_GetError() || !obj )
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