aboutsummaryrefslogtreecommitdiff
path: root/lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp
blob: 1340425aade4388d5d71e405f0c7e92f5512ef0b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
//===-- PythonDataObjects.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/Config.h"

#if LLDB_ENABLE_PYTHON

#include "PythonDataObjects.h"
#include "ScriptInterpreterPython.h"

#include "lldb/Host/File.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Interpreter/ScriptInterpreter.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"

#include "llvm/Support/Casting.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Errno.h"

#include <cstdio>
#include <variant>

using namespace lldb_private;
using namespace lldb;
using namespace lldb_private::python;
using llvm::cantFail;
using llvm::Error;
using llvm::Expected;
using llvm::Twine;

template <> Expected<bool> python::As<bool>(Expected<PythonObject> &&obj) {
  if (!obj)
    return obj.takeError();
  return obj.get().IsTrue();
}

template <>
Expected<long long> python::As<long long>(Expected<PythonObject> &&obj) {
  if (!obj)
    return obj.takeError();
  return obj->AsLongLong();
}

template <>
Expected<unsigned long long>
python::As<unsigned long long>(Expected<PythonObject> &&obj) {
  if (!obj)
    return obj.takeError();
  return obj->AsUnsignedLongLong();
}

template <>
Expected<std::string> python::As<std::string>(Expected<PythonObject> &&obj) {
  if (!obj)
    return obj.takeError();
  PyObject *str_obj = PyObject_Str(obj.get().get());
  if (!str_obj)
    return llvm::make_error<PythonException>();
  auto str = Take<PythonString>(str_obj);
  auto utf8 = str.AsUTF8();
  if (!utf8)
    return utf8.takeError();
  return std::string(utf8.get());
}

static bool python_is_finalizing() {
#if PY_VERSION_HEX >= 0x030d0000
  return Py_IsFinalizing();
#else
  return _Py_IsFinalizing();
#endif
}

void PythonObject::Reset() {
  if (m_py_obj && Py_IsInitialized()) {
    if (python_is_finalizing()) {
      // Leak m_py_obj rather than crashing the process.
      // https://docs.python.org/3/c-api/init.html#c.PyGILState_Ensure
    } else {
      PyGILState_STATE state = PyGILState_Ensure();
      Py_DECREF(m_py_obj);
      PyGILState_Release(state);
    }
  }
  m_py_obj = nullptr;
}

Expected<long long> PythonObject::AsLongLong() const {
  if (!m_py_obj)
    return nullDeref();
  assert(!PyErr_Occurred());
  long long r = PyLong_AsLongLong(m_py_obj);
  if (PyErr_Occurred())
    return exception();
  return r;
}

Expected<unsigned long long> PythonObject::AsUnsignedLongLong() const {
  if (!m_py_obj)
    return nullDeref();
  assert(!PyErr_Occurred());
  long long r = PyLong_AsUnsignedLongLong(m_py_obj);
  if (PyErr_Occurred())
    return exception();
  return r;
}

// wraps on overflow, instead of raising an error.
Expected<unsigned long long> PythonObject::AsModuloUnsignedLongLong() const {
  if (!m_py_obj)
    return nullDeref();
  assert(!PyErr_Occurred());
  unsigned long long r = PyLong_AsUnsignedLongLongMask(m_py_obj);
  // FIXME: We should fetch the exception message and hoist it.
  if (PyErr_Occurred())
    return exception();
  return r;
}

void StructuredPythonObject::Serialize(llvm::json::OStream &s) const {
  s.value(llvm::formatv("Python Obj: {0:X}", GetValue()).str());
}

// PythonObject

void PythonObject::Dump(Stream &strm) const {
  if (m_py_obj) {
    FILE *file = llvm::sys::RetryAfterSignal(nullptr, ::tmpfile);
    if (file) {
      ::PyObject_Print(m_py_obj, file, 0);
      const long length = ftell(file);
      if (length) {
        ::rewind(file);
        std::vector<char> file_contents(length, '\0');
        const size_t length_read =
            ::fread(file_contents.data(), 1, file_contents.size(), file);
        if (length_read > 0)
          strm.Write(file_contents.data(), length_read);
      }
      ::fclose(file);
    }
  } else
    strm.PutCString("NULL");
}

PyObjectType PythonObject::GetObjectType() const {
  if (!IsAllocated())
    return PyObjectType::None;

  if (PythonModule::Check(m_py_obj))
    return PyObjectType::Module;
  if (PythonList::Check(m_py_obj))
    return PyObjectType::List;
  if (PythonTuple::Check(m_py_obj))
    return PyObjectType::Tuple;
  if (PythonDictionary::Check(m_py_obj))
    return PyObjectType::Dictionary;
  if (PythonString::Check(m_py_obj))
    return PyObjectType::String;
  if (PythonBytes::Check(m_py_obj))
    return PyObjectType::Bytes;
  if (PythonByteArray::Check(m_py_obj))
    return PyObjectType::ByteArray;
  if (PythonBoolean::Check(m_py_obj))
    return PyObjectType::Boolean;
  if (PythonInteger::Check(m_py_obj))
    return PyObjectType::Integer;
  if (PythonFile::Check(m_py_obj))
    return PyObjectType::File;
  if (PythonCallable::Check(m_py_obj))
    return PyObjectType::Callable;
  return PyObjectType::Unknown;
}

PythonString PythonObject::Repr() const {
  if (!m_py_obj)
    return PythonString();
  PyObject *repr = PyObject_Repr(m_py_obj);
  if (!repr)
    return PythonString();
  return PythonString(PyRefType::Owned, repr);
}

PythonString PythonObject::Str() const {
  if (!m_py_obj)
    return PythonString();
  PyObject *str = PyObject_Str(m_py_obj);
  if (!str)
    return PythonString();
  return PythonString(PyRefType::Owned, str);
}

PythonObject
PythonObject::ResolveNameWithDictionary(llvm::StringRef name,
                                        const PythonDictionary &dict) {
  size_t dot_pos = name.find('.');
  llvm::StringRef piece = name.substr(0, dot_pos);
  PythonObject result = dict.GetItemForKey(PythonString(piece));
  if (dot_pos == llvm::StringRef::npos) {
    // There was no dot, we're done.
    return result;
  }

  // There was a dot.  The remaining portion of the name should be looked up in
  // the context of the object that was found in the dictionary.
  return result.ResolveName(name.substr(dot_pos + 1));
}

PythonObject PythonObject::ResolveName(llvm::StringRef name) const {
  // Resolve the name in the context of the specified object.  If, for example,
  // `this` refers to a PyModule, then this will look for `name` in this
  // module.  If `this` refers to a PyType, then it will resolve `name` as an
  // attribute of that type.  If `this` refers to an instance of an object,
  // then it will resolve `name` as the value of the specified field.
  //
  // This function handles dotted names so that, for example, if `m_py_obj`
  // refers to the `sys` module, and `name` == "path.append", then it will find
  // the function `sys.path.append`.

  size_t dot_pos = name.find('.');
  if (dot_pos == llvm::StringRef::npos) {
    // No dots in the name, we should be able to find the value immediately as
    // an attribute of `m_py_obj`.
    return GetAttributeValue(name);
  }

  // Look up the first piece of the name, and resolve the rest as a child of
  // that.
  PythonObject parent = ResolveName(name.substr(0, dot_pos));
  if (!parent.IsAllocated())
    return PythonObject();

  // Tail recursion.. should be optimized by the compiler
  return parent.ResolveName(name.substr(dot_pos + 1));
}

bool PythonObject::HasAttribute(llvm::StringRef attr) const {
  if (!IsValid())
    return false;
  PythonString py_attr(attr);
  return !!PyObject_HasAttr(m_py_obj, py_attr.get());
}

PythonObject PythonObject::GetAttributeValue(llvm::StringRef attr) const {
  if (!IsValid())
    return PythonObject();

  PythonString py_attr(attr);
  if (!PyObject_HasAttr(m_py_obj, py_attr.get()))
    return PythonObject();

  return PythonObject(PyRefType::Owned,
                      PyObject_GetAttr(m_py_obj, py_attr.get()));
}

StructuredData::ObjectSP PythonObject::CreateStructuredObject() const {
  assert(PyGILState_Check());
  switch (GetObjectType()) {
  case PyObjectType::Dictionary:
    return PythonDictionary(PyRefType::Borrowed, m_py_obj)
        .CreateStructuredDictionary();
  case PyObjectType::Boolean:
    return PythonBoolean(PyRefType::Borrowed, m_py_obj)
        .CreateStructuredBoolean();
  case PyObjectType::Integer: {
    StructuredData::IntegerSP int_sp =
        PythonInteger(PyRefType::Borrowed, m_py_obj).CreateStructuredInteger();
    if (std::holds_alternative<StructuredData::UnsignedIntegerSP>(int_sp))
      return std::get<StructuredData::UnsignedIntegerSP>(int_sp);
    if (std::holds_alternative<StructuredData::SignedIntegerSP>(int_sp))
      return std::get<StructuredData::SignedIntegerSP>(int_sp);
    return nullptr;
  };
  case PyObjectType::List:
    return PythonList(PyRefType::Borrowed, m_py_obj).CreateStructuredArray();
  case PyObjectType::String:
    return PythonString(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
  case PyObjectType::Bytes:
    return PythonBytes(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
  case PyObjectType::ByteArray:
    return PythonByteArray(PyRefType::Borrowed, m_py_obj)
        .CreateStructuredString();
  case PyObjectType::None:
    return StructuredData::ObjectSP();
  default:
    return StructuredData::ObjectSP(new StructuredPythonObject(
        PythonObject(PyRefType::Borrowed, m_py_obj)));
  }
}

// PythonString

PythonBytes::PythonBytes(llvm::ArrayRef<uint8_t> bytes) { SetBytes(bytes); }

PythonBytes::PythonBytes(const uint8_t *bytes, size_t length) {
  SetBytes(llvm::ArrayRef<uint8_t>(bytes, length));
}

bool PythonBytes::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;
  return PyBytes_Check(py_obj);
}

llvm::ArrayRef<uint8_t> PythonBytes::GetBytes() const {
  if (!IsValid())
    return llvm::ArrayRef<uint8_t>();

  Py_ssize_t size;
  char *c;

  PyBytes_AsStringAndSize(m_py_obj, &c, &size);
  return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
}

size_t PythonBytes::GetSize() const {
  if (!IsValid())
    return 0;
  return PyBytes_Size(m_py_obj);
}

void PythonBytes::SetBytes(llvm::ArrayRef<uint8_t> bytes) {
  const char *data = reinterpret_cast<const char *>(bytes.data());
  *this = Take<PythonBytes>(PyBytes_FromStringAndSize(data, bytes.size()));
}

StructuredData::StringSP PythonBytes::CreateStructuredString() const {
  StructuredData::StringSP result(new StructuredData::String);
  Py_ssize_t size;
  char *c;
  PyBytes_AsStringAndSize(m_py_obj, &c, &size);
  result->SetValue(std::string(c, size));
  return result;
}

PythonByteArray::PythonByteArray(llvm::ArrayRef<uint8_t> bytes)
    : PythonByteArray(bytes.data(), bytes.size()) {}

PythonByteArray::PythonByteArray(const uint8_t *bytes, size_t length) {
  const char *str = reinterpret_cast<const char *>(bytes);
  *this = Take<PythonByteArray>(PyByteArray_FromStringAndSize(str, length));
}

bool PythonByteArray::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;
  return PyByteArray_Check(py_obj);
}

llvm::ArrayRef<uint8_t> PythonByteArray::GetBytes() const {
  if (!IsValid())
    return llvm::ArrayRef<uint8_t>();

  char *c = PyByteArray_AsString(m_py_obj);
  size_t size = GetSize();
  return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
}

size_t PythonByteArray::GetSize() const {
  if (!IsValid())
    return 0;

  return PyByteArray_Size(m_py_obj);
}

StructuredData::StringSP PythonByteArray::CreateStructuredString() const {
  StructuredData::StringSP result(new StructuredData::String);
  llvm::ArrayRef<uint8_t> bytes = GetBytes();
  const char *str = reinterpret_cast<const char *>(bytes.data());
  result->SetValue(std::string(str, bytes.size()));
  return result;
}

// PythonString

Expected<PythonString> PythonString::FromUTF8(llvm::StringRef string) {
  PyObject *str = PyUnicode_FromStringAndSize(string.data(), string.size());
  if (!str)
    return llvm::make_error<PythonException>();
  return Take<PythonString>(str);
}

PythonString::PythonString(llvm::StringRef string) { SetString(string); }

bool PythonString::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;

  if (PyUnicode_Check(py_obj))
    return true;
  return false;
}

llvm::StringRef PythonString::GetString() const {
  auto s = AsUTF8();
  if (!s) {
    llvm::consumeError(s.takeError());
    return llvm::StringRef("");
  }
  return s.get();
}

Expected<llvm::StringRef> PythonString::AsUTF8() const {
  if (!IsValid())
    return nullDeref();

  Py_ssize_t size;
  const char *data;

  data = PyUnicode_AsUTF8AndSize(m_py_obj, &size);

  if (!data)
    return exception();

  return llvm::StringRef(data, size);
}

size_t PythonString::GetSize() const {
  if (IsValid()) {
#if PY_MINOR_VERSION >= 3
    return PyUnicode_GetLength(m_py_obj);
#else
    return PyUnicode_GetSize(m_py_obj);
#endif
  }
  return 0;
}

void PythonString::SetString(llvm::StringRef string) {
  auto s = FromUTF8(string);
  if (!s) {
    llvm::consumeError(s.takeError());
    Reset();
  } else {
    *this = std::move(s.get());
  }
}

StructuredData::StringSP PythonString::CreateStructuredString() const {
  StructuredData::StringSP result(new StructuredData::String);
  result->SetValue(GetString());
  return result;
}

// PythonInteger

PythonInteger::PythonInteger(int64_t value) { SetInteger(value); }

bool PythonInteger::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;

  // Python 3 does not have PyInt_Check.  There is only one type of integral
  // value, long.
  return PyLong_Check(py_obj);
}

void PythonInteger::SetInteger(int64_t value) {
  *this = Take<PythonInteger>(PyLong_FromLongLong(value));
}

StructuredData::IntegerSP PythonInteger::CreateStructuredInteger() const {
  StructuredData::UnsignedIntegerSP uint_sp = CreateStructuredUnsignedInteger();
  return uint_sp ? StructuredData::IntegerSP(uint_sp)
                 : CreateStructuredSignedInteger();
}

StructuredData::UnsignedIntegerSP
PythonInteger::CreateStructuredUnsignedInteger() const {
  StructuredData::UnsignedIntegerSP result = nullptr;
  llvm::Expected<unsigned long long> value = AsUnsignedLongLong();
  if (!value)
    llvm::consumeError(value.takeError());
  else
    result = std::make_shared<StructuredData::UnsignedInteger>(value.get());

  return result;
}

StructuredData::SignedIntegerSP
PythonInteger::CreateStructuredSignedInteger() const {
  StructuredData::SignedIntegerSP result = nullptr;
  llvm::Expected<long long> value = AsLongLong();
  if (!value)
    llvm::consumeError(value.takeError());
  else
    result = std::make_shared<StructuredData::SignedInteger>(value.get());

  return result;
}

// PythonBoolean

PythonBoolean::PythonBoolean(bool value) {
  SetValue(value);
}

bool PythonBoolean::Check(PyObject *py_obj) {
  return py_obj ? PyBool_Check(py_obj) : false;
}

bool PythonBoolean::GetValue() const {
  return m_py_obj ? PyObject_IsTrue(m_py_obj) : false;
}

void PythonBoolean::SetValue(bool value) {
  *this = Take<PythonBoolean>(PyBool_FromLong(value));
}

StructuredData::BooleanSP PythonBoolean::CreateStructuredBoolean() const {
  StructuredData::BooleanSP result(new StructuredData::Boolean);
  result->SetValue(GetValue());
  return result;
}

// PythonList

PythonList::PythonList(PyInitialValue value) {
  if (value == PyInitialValue::Empty)
    *this = Take<PythonList>(PyList_New(0));
}

PythonList::PythonList(int list_size) {
  *this = Take<PythonList>(PyList_New(list_size));
}

bool PythonList::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;
  return PyList_Check(py_obj);
}

uint32_t PythonList::GetSize() const {
  if (IsValid())
    return PyList_GET_SIZE(m_py_obj);
  return 0;
}

PythonObject PythonList::GetItemAtIndex(uint32_t index) const {
  if (IsValid())
    return PythonObject(PyRefType::Borrowed, PyList_GetItem(m_py_obj, index));
  return PythonObject();
}

void PythonList::SetItemAtIndex(uint32_t index, const PythonObject &object) {
  if (IsAllocated() && object.IsValid()) {
    // PyList_SetItem is documented to "steal" a reference, so we need to
    // convert it to an owned reference by incrementing it.
    Py_INCREF(object.get());
    PyList_SetItem(m_py_obj, index, object.get());
  }
}

void PythonList::AppendItem(const PythonObject &object) {
  if (IsAllocated() && object.IsValid()) {
    // `PyList_Append` does *not* steal a reference, so do not call `Py_INCREF`
    // here like we do with `PyList_SetItem`.
    PyList_Append(m_py_obj, object.get());
  }
}

StructuredData::ArraySP PythonList::CreateStructuredArray() const {
  StructuredData::ArraySP result(new StructuredData::Array);
  uint32_t count = GetSize();
  for (uint32_t i = 0; i < count; ++i) {
    PythonObject obj = GetItemAtIndex(i);
    result->AddItem(obj.CreateStructuredObject());
  }
  return result;
}

// PythonTuple

PythonTuple::PythonTuple(PyInitialValue value) {
  if (value == PyInitialValue::Empty)
    *this = Take<PythonTuple>(PyTuple_New(0));
}

PythonTuple::PythonTuple(int tuple_size) {
  *this = Take<PythonTuple>(PyTuple_New(tuple_size));
}

PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects) {
  m_py_obj = PyTuple_New(objects.size());

  uint32_t idx = 0;
  for (auto object : objects) {
    if (object.IsValid())
      SetItemAtIndex(idx, object);
    idx++;
  }
}

PythonTuple::PythonTuple(std::initializer_list<PyObject *> objects) {
  m_py_obj = PyTuple_New(objects.size());

  uint32_t idx = 0;
  for (auto py_object : objects) {
    PythonObject object(PyRefType::Borrowed, py_object);
    if (object.IsValid())
      SetItemAtIndex(idx, object);
    idx++;
  }
}

bool PythonTuple::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;
  return PyTuple_Check(py_obj);
}

uint32_t PythonTuple::GetSize() const {
  if (IsValid())
    return PyTuple_GET_SIZE(m_py_obj);
  return 0;
}

PythonObject PythonTuple::GetItemAtIndex(uint32_t index) const {
  if (IsValid())
    return PythonObject(PyRefType::Borrowed, PyTuple_GetItem(m_py_obj, index));
  return PythonObject();
}

void PythonTuple::SetItemAtIndex(uint32_t index, const PythonObject &object) {
  if (IsAllocated() && object.IsValid()) {
    // PyTuple_SetItem is documented to "steal" a reference, so we need to
    // convert it to an owned reference by incrementing it.
    Py_INCREF(object.get());
    PyTuple_SetItem(m_py_obj, index, object.get());
  }
}

StructuredData::ArraySP PythonTuple::CreateStructuredArray() const {
  StructuredData::ArraySP result(new StructuredData::Array);
  uint32_t count = GetSize();
  for (uint32_t i = 0; i < count; ++i) {
    PythonObject obj = GetItemAtIndex(i);
    result->AddItem(obj.CreateStructuredObject());
  }
  return result;
}

// PythonDictionary

PythonDictionary::PythonDictionary(PyInitialValue value) {
  if (value == PyInitialValue::Empty)
    *this = Take<PythonDictionary>(PyDict_New());
}

bool PythonDictionary::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;

  return PyDict_Check(py_obj);
}

bool PythonDictionary::HasKey(const llvm::Twine &key) const {
  if (!IsValid())
    return false;

  PythonString key_object(key.isSingleStringRef() ? key.getSingleStringRef()
                                                  : key.str());

  if (int res = PyDict_Contains(m_py_obj, key_object.get()) > 0)
    return res;

  PyErr_Print();
  return false;
}

uint32_t PythonDictionary::GetSize() const {
  if (IsValid())
    return PyDict_Size(m_py_obj);
  return 0;
}

PythonList PythonDictionary::GetKeys() const {
  if (IsValid())
    return PythonList(PyRefType::Owned, PyDict_Keys(m_py_obj));
  return PythonList(PyInitialValue::Invalid);
}

PythonObject PythonDictionary::GetItemForKey(const PythonObject &key) const {
  auto item = GetItem(key);
  if (!item) {
    llvm::consumeError(item.takeError());
    return PythonObject();
  }
  return std::move(item.get());
}

Expected<PythonObject>
PythonDictionary::GetItem(const PythonObject &key) const {
  if (!IsValid())
    return nullDeref();
  PyObject *o = PyDict_GetItemWithError(m_py_obj, key.get());
  if (PyErr_Occurred())
    return exception();
  if (!o)
    return keyError();
  return Retain<PythonObject>(o);
}

Expected<PythonObject> PythonDictionary::GetItem(const Twine &key) const {
  if (!IsValid())
    return nullDeref();
  PyObject *o = PyDict_GetItemString(m_py_obj, NullTerminated(key));
  if (PyErr_Occurred())
    return exception();
  if (!o)
    return keyError();
  return Retain<PythonObject>(o);
}

Error PythonDictionary::SetItem(const PythonObject &key,
                                const PythonObject &value) const {
  if (!IsValid() || !value.IsValid())
    return nullDeref();
  int r = PyDict_SetItem(m_py_obj, key.get(), value.get());
  if (r < 0)
    return exception();
  return Error::success();
}

Error PythonDictionary::SetItem(const Twine &key,
                                const PythonObject &value) const {
  if (!IsValid() || !value.IsValid())
    return nullDeref();
  int r = PyDict_SetItemString(m_py_obj, NullTerminated(key), value.get());
  if (r < 0)
    return exception();
  return Error::success();
}

void PythonDictionary::SetItemForKey(const PythonObject &key,
                                     const PythonObject &value) {
  Error error = SetItem(key, value);
  if (error)
    llvm::consumeError(std::move(error));
}

StructuredData::DictionarySP
PythonDictionary::CreateStructuredDictionary() const {
  StructuredData::DictionarySP result(new StructuredData::Dictionary);
  PythonList keys(GetKeys());
  uint32_t num_keys = keys.GetSize();
  for (uint32_t i = 0; i < num_keys; ++i) {
    PythonObject key = keys.GetItemAtIndex(i);
    PythonObject value = GetItemForKey(key);
    StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
    result->AddItem(key.Str().GetString(), structured_value);
  }
  return result;
}

PythonModule PythonModule::BuiltinsModule() { return AddModule("builtins"); }

PythonModule PythonModule::MainModule() { return AddModule("__main__"); }

PythonModule PythonModule::AddModule(llvm::StringRef module) {
  std::string str = module.str();
  return PythonModule(PyRefType::Borrowed, PyImport_AddModule(str.c_str()));
}

Expected<PythonModule> PythonModule::Import(const Twine &name) {
  PyObject *mod = PyImport_ImportModule(NullTerminated(name));
  if (!mod)
    return exception();
  return Take<PythonModule>(mod);
}

Expected<PythonObject> PythonModule::Get(const Twine &name) {
  if (!IsValid())
    return nullDeref();
  PyObject *dict = PyModule_GetDict(m_py_obj);
  if (!dict)
    return exception();
  PyObject *item = PyDict_GetItemString(dict, NullTerminated(name));
  if (!item)
    return exception();
  return Retain<PythonObject>(item);
}

bool PythonModule::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;

  return PyModule_Check(py_obj);
}

PythonDictionary PythonModule::GetDictionary() const {
  if (!IsValid())
    return PythonDictionary();
  return Retain<PythonDictionary>(PyModule_GetDict(m_py_obj));
}

bool PythonCallable::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;

  return PyCallable_Check(py_obj);
}

static const char get_arg_info_script[] = R"(
from inspect import signature, Parameter, ismethod
from collections import namedtuple
ArgInfo = namedtuple('ArgInfo', ['count', 'has_varargs'])
def main(f):
    count = 0
    varargs = False
    for parameter in signature(f).parameters.values():
        kind = parameter.kind
        if kind in (Parameter.POSITIONAL_ONLY,
                    Parameter.POSITIONAL_OR_KEYWORD):
            count += 1
        elif kind == Parameter.VAR_POSITIONAL:
            varargs = True
        elif kind in (Parameter.KEYWORD_ONLY,
                      Parameter.VAR_KEYWORD):
            pass
        else:
            raise Exception(f'unknown parameter kind: {kind}')
    return ArgInfo(count, varargs)
)";

Expected<PythonCallable::ArgInfo> PythonCallable::GetArgInfo() const {
  ArgInfo result = {};
  if (!IsValid())
    return nullDeref();

  // no need to synchronize access to this global, we already have the GIL
  static PythonScript get_arg_info(get_arg_info_script);
  Expected<PythonObject> pyarginfo = get_arg_info(*this);
  if (!pyarginfo)
    return pyarginfo.takeError();
  long long count =
      cantFail(As<long long>(pyarginfo.get().GetAttribute("count")));
  bool has_varargs =
      cantFail(As<bool>(pyarginfo.get().GetAttribute("has_varargs")));
  result.max_positional_args = has_varargs ? ArgInfo::UNBOUNDED : count;

  return result;
}

constexpr unsigned
    PythonCallable::ArgInfo::UNBOUNDED; // FIXME delete after c++17

PythonObject PythonCallable::operator()() {
  return PythonObject(PyRefType::Owned, PyObject_CallObject(m_py_obj, nullptr));
}

PythonObject PythonCallable::
operator()(std::initializer_list<PyObject *> args) {
  PythonTuple arg_tuple(args);
  return PythonObject(PyRefType::Owned,
                      PyObject_CallObject(m_py_obj, arg_tuple.get()));
}

PythonObject PythonCallable::
operator()(std::initializer_list<PythonObject> args) {
  PythonTuple arg_tuple(args);
  return PythonObject(PyRefType::Owned,
                      PyObject_CallObject(m_py_obj, arg_tuple.get()));
}

bool PythonFile::Check(PyObject *py_obj) {
  if (!py_obj)
    return false;
  // In Python 3, there is no `PyFile_Check`, and in fact PyFile is not even a
  // first-class object type anymore.  `PyFile_FromFd` is just a thin wrapper
  // over `io.open()`, which returns some object derived from `io.IOBase`. As a
  // result, the only way to detect a file in Python 3 is to check whether it
  // inherits from `io.IOBase`.
  auto io_module = PythonModule::Import("io");
  if (!io_module) {
    llvm::consumeError(io_module.takeError());
    return false;
  }
  auto iobase = io_module.get().Get("IOBase");
  if (!iobase) {
    llvm::consumeError(iobase.takeError());
    return false;
  }
  int r = PyObject_IsInstance(py_obj, iobase.get().get());
  if (r < 0) {
    llvm::consumeError(exception()); // clear the exception and log it.
    return false;
  }
  return !!r;
}

const char *PythonException::toCString() const {
  if (!m_repr_bytes)
    return "unknown exception";
  return PyBytes_AS_STRING(m_repr_bytes);
}

PythonException::PythonException(const char *caller) {
  assert(PyErr_Occurred());
  m_exception_type = m_exception = m_traceback = m_repr_bytes = nullptr;
  PyErr_Fetch(&m_exception_type, &m_exception, &m_traceback);
  PyErr_NormalizeException(&m_exception_type, &m_exception, &m_traceback);
  PyErr_Clear();
  if (m_exception) {
    PyObject *repr = PyObject_Repr(m_exception);
    if (repr) {
      m_repr_bytes = PyUnicode_AsEncodedString(repr, "utf-8", nullptr);
      if (!m_repr_bytes) {
        PyErr_Clear();
      }
      Py_XDECREF(repr);
    } else {
      PyErr_Clear();
    }
  }
  Log *log = GetLog(LLDBLog::Script);
  if (caller)
    LLDB_LOGF(log, "%s failed with exception: %s", caller, toCString());
  else
    LLDB_LOGF(log, "python exception: %s", toCString());
}
void PythonException::Restore() {
  if (m_exception_type && m_exception) {
    PyErr_Restore(m_exception_type, m_exception, m_traceback);
  } else {
    PyErr_SetString(PyExc_Exception, toCString());
  }
  m_exception_type = m_exception = m_traceback = nullptr;
}

PythonException::~PythonException() {
  Py_XDECREF(m_exception_type);
  Py_XDECREF(m_exception);
  Py_XDECREF(m_traceback);
  Py_XDECREF(m_repr_bytes);
}

void PythonException::log(llvm::raw_ostream &OS) const { OS << toCString(); }

std::error_code PythonException::convertToErrorCode() const {
  return llvm::inconvertibleErrorCode();
}

bool PythonException::Matches(PyObject *exc) const {
  return PyErr_GivenExceptionMatches(m_exception_type, exc);
}

const char read_exception_script[] = R"(
import sys
from traceback import print_exception
if sys.version_info.major < 3:
  from StringIO import StringIO
else:
  from io import StringIO
def main(exc_type, exc_value, tb):
  f = StringIO()
  print_exception(exc_type, exc_value, tb, file=f)
  return f.getvalue()
)";

std::string PythonException::ReadBacktrace() const {

  if (!m_traceback)
    return toCString();

  // no need to synchronize access to this global, we already have the GIL
  static PythonScript read_exception(read_exception_script);

  Expected<std::string> backtrace = As<std::string>(
      read_exception(m_exception_type, m_exception, m_traceback));

  if (!backtrace) {
    std::string message =
        std::string(toCString()) + "\n" +
        "Traceback unavailable, an error occurred while reading it:\n";
    return (message + llvm::toString(backtrace.takeError()));
  }

  return std::move(backtrace.get());
}

char PythonException::ID = 0;

llvm::Expected<File::OpenOptions>
GetOptionsForPyObject(const PythonObject &obj) {
  auto options = File::OpenOptions(0);
  auto readable = As<bool>(obj.CallMethod("readable"));
  if (!readable)
    return readable.takeError();
  auto writable = As<bool>(obj.CallMethod("writable"));
  if (!writable)
    return writable.takeError();
  if (readable.get() && writable.get())
    options |= File::eOpenOptionReadWrite;
  else if (writable.get())
    options |= File::eOpenOptionWriteOnly;
  else if (readable.get())
    options |= File::eOpenOptionReadOnly;
  return options;
}

// Base class template for python files.   All it knows how to do
// is hold a reference to the python object and close or flush it
// when the File is closed.
namespace {
template <typename Base> class OwnedPythonFile : public Base {
public:
  template <typename... Args>
  OwnedPythonFile(const PythonFile &file, bool borrowed, Args... args)
      : Base(args...), m_py_obj(file), m_borrowed(borrowed) {
    assert(m_py_obj);
  }

  ~OwnedPythonFile() override {
    assert(m_py_obj);
    GIL takeGIL;
    Close();
    // we need to ensure the python object is released while we still
    // hold the GIL
    m_py_obj.Reset();
  }

  bool IsPythonSideValid() const {
    GIL takeGIL;
    auto closed = As<bool>(m_py_obj.GetAttribute("closed"));
    if (!closed) {
      llvm::consumeError(closed.takeError());
      return false;
    }
    return !closed.get();
  }

  bool IsValid() const override {
    return IsPythonSideValid() && Base::IsValid();
  }

  Status Close() override {
    assert(m_py_obj);
    Status py_error, base_error;
    GIL takeGIL;
    if (!m_borrowed) {
      auto r = m_py_obj.CallMethod("close");
      if (!r)
        py_error = Status::FromError(r.takeError());
    }
    base_error = Base::Close();
    // Cloning since the wrapped exception may still reference the PyThread.
    if (py_error.Fail())
      return py_error.Clone();
    return base_error.Clone();
  };

  PyObject *GetPythonObject() const {
    assert(m_py_obj.IsValid());
    return m_py_obj.get();
  }

  static bool classof(const File *file) = delete;

protected:
  PythonFile m_py_obj;
  bool m_borrowed;
};
} // namespace

// A SimplePythonFile is a OwnedPythonFile that just does all I/O as
// a NativeFile
namespace {
class SimplePythonFile : public OwnedPythonFile<NativeFile> {
public:
  SimplePythonFile(const PythonFile &file, bool borrowed, int fd,
                   File::OpenOptions options)
      : OwnedPythonFile(file, borrowed, fd, options, false) {}

  static char ID;
  bool isA(const void *classID) const override {
    return classID == &ID || NativeFile::isA(classID);
  }
  static bool classof(const File *file) { return file->isA(&ID); }
};
char SimplePythonFile::ID = 0;
} // namespace

namespace {
class PythonBuffer {
public:
  PythonBuffer &operator=(const PythonBuffer &) = delete;
  PythonBuffer(const PythonBuffer &) = delete;

  static Expected<PythonBuffer> Create(PythonObject &obj,
                                       int flags = PyBUF_SIMPLE) {
    Py_buffer py_buffer = {};
    PyObject_GetBuffer(obj.get(), &py_buffer, flags);
    if (!py_buffer.obj)
      return llvm::make_error<PythonException>();
    return PythonBuffer(py_buffer);
  }

  PythonBuffer(PythonBuffer &&other) {
    m_buffer = other.m_buffer;
    other.m_buffer.obj = nullptr;
  }

  ~PythonBuffer() {
    if (m_buffer.obj)
      PyBuffer_Release(&m_buffer);
  }

  Py_buffer &get() { return m_buffer; }

private:
  // takes ownership of the buffer.
  PythonBuffer(const Py_buffer &py_buffer) : m_buffer(py_buffer) {}
  Py_buffer m_buffer;
};
} // namespace

// Shared methods between TextPythonFile and BinaryPythonFile
namespace {
class PythonIOFile : public OwnedPythonFile<File> {
public:
  PythonIOFile(const PythonFile &file, bool borrowed)
      : OwnedPythonFile(file, borrowed) {}

  ~PythonIOFile() override { Close(); }

  bool IsValid() const override { return IsPythonSideValid(); }

  Status Close() override {
    assert(m_py_obj);
    GIL takeGIL;
    if (m_borrowed)
      return Flush();
    auto r = m_py_obj.CallMethod("close");
    if (!r)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(r.takeError()).Clone();
    return Status();
  }

  Status Flush() override {
    GIL takeGIL;
    auto r = m_py_obj.CallMethod("flush");
    if (!r)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(r.takeError()).Clone();
    return Status();
  }

  Expected<File::OpenOptions> GetOptions() const override {
    GIL takeGIL;
    return GetOptionsForPyObject(m_py_obj);
  }

  static char ID;
  bool isA(const void *classID) const override {
    return classID == &ID || File::isA(classID);
  }
  static bool classof(const File *file) { return file->isA(&ID); }
};
char PythonIOFile::ID = 0;
} // namespace

namespace {
class BinaryPythonFile : public PythonIOFile {
protected:
  int m_descriptor;

public:
  BinaryPythonFile(int fd, const PythonFile &file, bool borrowed)
      : PythonIOFile(file, borrowed),
        m_descriptor(File::DescriptorIsValid(fd) ? fd
                                                 : File::kInvalidDescriptor) {}

  int GetDescriptor() const override { return m_descriptor; }

  Status Write(const void *buf, size_t &num_bytes) override {
    GIL takeGIL;
    PyObject *pybuffer_p = PyMemoryView_FromMemory(
        const_cast<char *>((const char *)buf), num_bytes, PyBUF_READ);
    if (!pybuffer_p)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(llvm::make_error<PythonException>()).Clone();
    auto pybuffer = Take<PythonObject>(pybuffer_p);
    num_bytes = 0;
    auto bytes_written = As<long long>(m_py_obj.CallMethod("write", pybuffer));
    if (!bytes_written)
      return Status::FromError(bytes_written.takeError());
    if (bytes_written.get() < 0)
      return Status::FromErrorString(
          ".write() method returned a negative number!");
    static_assert(sizeof(long long) >= sizeof(size_t), "overflow");
    num_bytes = bytes_written.get();
    return Status();
  }

  Status Read(void *buf, size_t &num_bytes) override {
    GIL takeGIL;
    static_assert(sizeof(long long) >= sizeof(size_t), "overflow");
    auto pybuffer_obj =
        m_py_obj.CallMethod("read", (unsigned long long)num_bytes);
    if (!pybuffer_obj)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(pybuffer_obj.takeError()).Clone();
    num_bytes = 0;
    if (pybuffer_obj.get().IsNone()) {
      // EOF
      num_bytes = 0;
      return Status();
    }
    auto pybuffer = PythonBuffer::Create(pybuffer_obj.get());
    if (!pybuffer)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(pybuffer.takeError()).Clone();
    memcpy(buf, pybuffer.get().get().buf, pybuffer.get().get().len);
    num_bytes = pybuffer.get().get().len;
    return Status();
  }
};
} // namespace

namespace {
class TextPythonFile : public PythonIOFile {
protected:
  int m_descriptor;

public:
  TextPythonFile(int fd, const PythonFile &file, bool borrowed)
      : PythonIOFile(file, borrowed),
        m_descriptor(File::DescriptorIsValid(fd) ? fd
                                                 : File::kInvalidDescriptor) {}

  int GetDescriptor() const override { return m_descriptor; }

  Status Write(const void *buf, size_t &num_bytes) override {
    GIL takeGIL;
    auto pystring =
        PythonString::FromUTF8(llvm::StringRef((const char *)buf, num_bytes));
    if (!pystring)
      return Status::FromError(pystring.takeError());
    num_bytes = 0;
    auto bytes_written =
        As<long long>(m_py_obj.CallMethod("write", pystring.get()));
    if (!bytes_written)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(bytes_written.takeError()).Clone();
    if (bytes_written.get() < 0)
      return Status::FromErrorString(
          ".write() method returned a negative number!");
    static_assert(sizeof(long long) >= sizeof(size_t), "overflow");
    num_bytes = bytes_written.get();
    return Status();
  }

  Status Read(void *buf, size_t &num_bytes) override {
    GIL takeGIL;
    size_t num_chars = num_bytes / 6;
    size_t orig_num_bytes = num_bytes;
    num_bytes = 0;
    if (orig_num_bytes < 6) {
      return Status::FromErrorString(
          "can't read less than 6 bytes from a utf8 text stream");
    }
    auto pystring = As<PythonString>(
        m_py_obj.CallMethod("read", (unsigned long long)num_chars));
    if (!pystring)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(pystring.takeError()).Clone();
    if (pystring.get().IsNone()) {
      // EOF
      return Status();
    }
    auto stringref = pystring.get().AsUTF8();
    if (!stringref)
      // Cloning since the wrapped exception may still reference the PyThread.
      return Status::FromError(stringref.takeError()).Clone();
    num_bytes = stringref.get().size();
    memcpy(buf, stringref.get().begin(), num_bytes);
    return Status();
  }
};
} // namespace

llvm::Expected<FileSP> PythonFile::ConvertToFile(bool borrowed) {
  if (!IsValid())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "invalid PythonFile");

  int fd = PyObject_AsFileDescriptor(m_py_obj);
  if (fd < 0) {
    PyErr_Clear();
    return ConvertToFileForcingUseOfScriptingIOMethods(borrowed);
  }
  auto options = GetOptionsForPyObject(*this);
  if (!options)
    return options.takeError();

  File::OpenOptions rw =
      options.get() & (File::eOpenOptionReadOnly | File::eOpenOptionWriteOnly |
                       File::eOpenOptionReadWrite);
  if (rw == File::eOpenOptionWriteOnly || rw == File::eOpenOptionReadWrite) {
    // LLDB and python will not share I/O buffers.  We should probably
    // flush the python buffers now.
    auto r = CallMethod("flush");
    if (!r)
      return r.takeError();
  }

  FileSP file_sp;
  if (borrowed) {
    // In this case we don't need to retain the python
    // object at all.
    file_sp = std::make_shared<NativeFile>(fd, options.get(), false);
  } else {
    file_sp = std::static_pointer_cast<File>(
        std::make_shared<SimplePythonFile>(*this, borrowed, fd, options.get()));
  }
  if (!file_sp->IsValid())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "invalid File");

  return file_sp;
}

llvm::Expected<FileSP>
PythonFile::ConvertToFileForcingUseOfScriptingIOMethods(bool borrowed) {

  assert(!PyErr_Occurred());

  if (!IsValid())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "invalid PythonFile");

  int fd = PyObject_AsFileDescriptor(m_py_obj);
  if (fd < 0) {
    PyErr_Clear();
    fd = File::kInvalidDescriptor;
  }

  auto io_module = PythonModule::Import("io");
  if (!io_module)
    return io_module.takeError();
  auto textIOBase = io_module.get().Get("TextIOBase");
  if (!textIOBase)
    return textIOBase.takeError();
  auto rawIOBase = io_module.get().Get("RawIOBase");
  if (!rawIOBase)
    return rawIOBase.takeError();
  auto bufferedIOBase = io_module.get().Get("BufferedIOBase");
  if (!bufferedIOBase)
    return bufferedIOBase.takeError();

  FileSP file_sp;

  auto isTextIO = IsInstance(textIOBase.get());
  if (!isTextIO)
    return isTextIO.takeError();
  if (isTextIO.get())
    file_sp = std::static_pointer_cast<File>(
        std::make_shared<TextPythonFile>(fd, *this, borrowed));

  auto isRawIO = IsInstance(rawIOBase.get());
  if (!isRawIO)
    return isRawIO.takeError();
  auto isBufferedIO = IsInstance(bufferedIOBase.get());
  if (!isBufferedIO)
    return isBufferedIO.takeError();

  if (isRawIO.get() || isBufferedIO.get()) {
    file_sp = std::static_pointer_cast<File>(
        std::make_shared<BinaryPythonFile>(fd, *this, borrowed));
  }

  if (!file_sp)
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "python file is neither text nor binary");

  if (!file_sp->IsValid())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "invalid File");

  return file_sp;
}

Expected<PythonFile> PythonFile::FromFile(File &file, const char *mode) {
  if (!file.IsValid())
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "invalid file");

  if (auto *simple = llvm::dyn_cast<SimplePythonFile>(&file))
    return Retain<PythonFile>(simple->GetPythonObject());
  if (auto *pythonio = llvm::dyn_cast<PythonIOFile>(&file))
    return Retain<PythonFile>(pythonio->GetPythonObject());

  if (!mode) {
    auto m = file.GetOpenMode();
    if (!m)
      return m.takeError();
    mode = m.get();
  }

  PyObject *file_obj;
  file_obj = PyFile_FromFd(file.GetDescriptor(), nullptr, mode, -1, nullptr,
                           "ignore", nullptr, /*closefd=*/0);

  if (!file_obj)
    return exception();

  return Take<PythonFile>(file_obj);
}

Error PythonScript::Init() {
  if (function.IsValid())
    return Error::success();

  PythonDictionary globals(PyInitialValue::Empty);
  auto builtins = PythonModule::BuiltinsModule();
  if (Error error = globals.SetItem("__builtins__", builtins))
    return error;
  PyObject *o =
      PyRun_String(script, Py_file_input, globals.get(), globals.get());
  if (!o)
    return exception();
  Take<PythonObject>(o);
  auto f = As<PythonCallable>(globals.GetItem("main"));
  if (!f)
    return f.takeError();
  function = std::move(f.get());

  return Error::success();
}

llvm::Expected<PythonObject>
python::runStringOneLine(const llvm::Twine &string,
                         const PythonDictionary &globals,
                         const PythonDictionary &locals) {
  if (!globals.IsValid() || !locals.IsValid())
    return nullDeref();

  PyObject *code =
      Py_CompileString(NullTerminated(string), "<string>", Py_eval_input);
  if (!code) {
    PyErr_Clear();
    code =
        Py_CompileString(NullTerminated(string), "<string>", Py_single_input);
  }
  if (!code)
    return exception();
  auto code_ref = Take<PythonObject>(code);

  PyObject *result = PyEval_EvalCode(code, globals.get(), locals.get());

  if (!result)
    return exception();

  return Take<PythonObject>(result);
}

llvm::Expected<PythonObject>
python::runStringMultiLine(const llvm::Twine &string,
                           const PythonDictionary &globals,
                           const PythonDictionary &locals) {
  if (!globals.IsValid() || !locals.IsValid())
    return nullDeref();
  PyObject *result = PyRun_String(NullTerminated(string), Py_file_input,
                                  globals.get(), locals.get());
  if (!result)
    return exception();
  return Take<PythonObject>(result);
}

#endif
eErrorCode(), E.ReadBacktrace()); if (!options.GetMaskoutErrors()) E.Restore(); return error; }); return Status::FromError(std::move(error)); } return Status(); } void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback( std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec, CommandReturnObject &result) { m_active_io_handler = eIOHandlerBreakpoint; m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( " ", *this, &bp_options_vec); } void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback( WatchpointOptions *wp_options, CommandReturnObject &result) { m_active_io_handler = eIOHandlerWatchpoint; m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler( " ", *this, wp_options); } Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction( BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) { Status error; // For now just cons up a oneliner that calls the provided function. std::string function_signature = function_name; llvm::Expected<unsigned> maybe_args = GetMaxPositionalArgumentsForCallable(function_name); if (!maybe_args) { error = Status::FromErrorStringWithFormat( "could not get num args: %s", llvm::toString(maybe_args.takeError()).c_str()); return error; } size_t max_args = *maybe_args; bool uses_extra_args = false; if (max_args >= 4) { uses_extra_args = true; function_signature += "(frame, bp_loc, extra_args, internal_dict)"; } else if (max_args >= 3) { if (extra_args_sp) { error = Status::FromErrorStringWithFormat( "cannot pass extra_args to a three argument callback"); return error; } uses_extra_args = false; function_signature += "(frame, bp_loc, internal_dict)"; } else { error = Status::FromErrorStringWithFormat("expected 3 or 4 argument " "function, %s can only take %zu", function_name, max_args); return error; } SetBreakpointCommandCallback(bp_options, function_signature.c_str(), extra_args_sp, uses_extra_args, /*is_callback=*/true); return error; } Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( BreakpointOptions &bp_options, std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) { Status error; error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source, cmd_data_up->script_source, /*has_extra_args=*/false, /*is_callback=*/false); if (error.Fail()) { return error; } auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up)); bp_options.SetCallback( ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); return error; } Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( BreakpointOptions &bp_options, const char *command_body_text, bool is_callback) { return SetBreakpointCommandCallback(bp_options, command_body_text, {}, /*uses_extra_args=*/false, is_callback); } // Set a Python one-liner as the callback for the breakpoint. Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback( BreakpointOptions &bp_options, const char *command_body_text, StructuredData::ObjectSP extra_args_sp, bool uses_extra_args, bool is_callback) { auto data_up = std::make_unique<CommandDataPython>(extra_args_sp); // Split the command_body_text into lines, and pass that to // GenerateBreakpointCommandCallbackData. That will wrap the body in an // auto-generated function, and return the function name in script_source. // That is what the callback will actually invoke. data_up->user_source.SplitIntoLines(command_body_text); Status error = GenerateBreakpointCommandCallbackData( data_up->user_source, data_up->script_source, uses_extra_args, is_callback); if (error.Success()) { auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up)); bp_options.SetCallback( ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp); return error; } return error; } // Set a Python one-liner as the callback for the watchpoint. void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback( WatchpointOptions *wp_options, const char *user_input, bool is_callback) { auto data_up = std::make_unique<WatchpointOptions::CommandData>(); // It's necessary to set both user_source and script_source to the oneliner. // The former is used to generate callback description (as in watchpoint // command list) while the latter is used for Python to interpret during the // actual callback. data_up->user_source.AppendString(user_input); data_up->script_source.assign(user_input); if (GenerateWatchpointCommandCallbackData( data_up->user_source, data_up->script_source, is_callback)) { auto baton_sp = std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up)); wp_options->SetCallback( ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp); } } Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter( StringList &function_def) { // Convert StringList to one long, newline delimited, const char *. std::string function_def_string(function_def.CopyList()); LLDB_LOG(GetLog(LLDBLog::Script), "Added Function:\n%s\n", function_def_string.c_str()); Status error = ExecuteMultipleLines( function_def_string.c_str(), ExecuteScriptOptions().SetEnableIO(false)); return error; } Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature, const StringList &input, bool is_callback) { Status error; int num_lines = input.GetSize(); if (num_lines == 0) { error = Status::FromErrorString("No input data."); return error; } if (!signature || *signature == 0) { error = Status::FromErrorString("No output function name."); return error; } StreamString sstr; StringList auto_generated_function; auto_generated_function.AppendString(signature); auto_generated_function.AppendString( " global_dict = globals()"); // Grab the global dictionary auto_generated_function.AppendString( " new_keys = internal_dict.keys()"); // Make a list of keys in the // session dict auto_generated_function.AppendString( " old_keys = global_dict.keys()"); // Save list of keys in global dict auto_generated_function.AppendString( " global_dict.update(internal_dict)"); // Add the session dictionary // to the global dictionary. if (is_callback) { // If the user input is a callback to a python function, make sure the input // is only 1 line, otherwise appending the user input would break the // generated wrapped function if (num_lines == 1) { sstr.Clear(); sstr.Printf(" __return_val = %s", input.GetStringAtIndex(0)); auto_generated_function.AppendString(sstr.GetData()); } else { return Status::FromErrorString( "ScriptInterpreterPythonImpl::GenerateFunction(is_callback=" "true) = ERROR: python function is multiline."); } } else { auto_generated_function.AppendString( " __return_val = None"); // Initialize user callback return value. auto_generated_function.AppendString( " def __user_code():"); // Create a nested function that will wrap // the user input. This is necessary to // capture the return value of the user input // and prevent early returns. for (int i = 0; i < num_lines; ++i) { sstr.Clear(); sstr.Printf(" %s", input.GetStringAtIndex(i)); auto_generated_function.AppendString(sstr.GetData()); } auto_generated_function.AppendString( " __return_val = __user_code()"); // Call user code and capture // return value } auto_generated_function.AppendString( " for key in new_keys:"); // Iterate over all the keys from session // dict auto_generated_function.AppendString( " if key in old_keys:"); // If key was originally in // global dict auto_generated_function.AppendString( " internal_dict[key] = global_dict[key]"); // Update it auto_generated_function.AppendString( " elif key in global_dict:"); // Then if it is still in the // global dict auto_generated_function.AppendString( " del global_dict[key]"); // remove key/value from the // global dict auto_generated_function.AppendString( " return __return_val"); // Return the user callback return value. // Verify that the results are valid Python. error = ExportFunctionDefinitionToInterpreter(auto_generated_function); return error; } bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( StringList &user_input, std::string &output, const void *name_token) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); StreamString sstr; // Check to see if we have any data; if not, just return. if (user_input.GetSize() == 0) return false; // Take what the user wrote, wrap it all up inside one big auto-generated // Python function, passing in the ValueObject as parameter to the function. std::string auto_generated_function_name( GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token)); sstr.Printf("def %s (valobj, internal_dict):", auto_generated_function_name.c_str()); if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false) .Success()) return false; // Store the name of the auto-generated function to be called. output.assign(auto_generated_function_name); return true; } bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction( StringList &user_input, std::string &output) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); StreamString sstr; // Check to see if we have any data; if not, just return. if (user_input.GetSize() == 0) return false; std::string auto_generated_function_name(GenerateUniqueName( "lldb_autogen_python_cmd_alias_func", num_created_functions)); sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):", auto_generated_function_name.c_str()); if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false) .Success()) return false; // Store the name of the auto-generated function to be called. output.assign(auto_generated_function_name); return true; } bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( StringList &user_input, std::string &output, const void *name_token) { static uint32_t num_created_classes = 0; user_input.RemoveBlankLines(); int num_lines = user_input.GetSize(); StreamString sstr; // Check to see if we have any data; if not, just return. if (user_input.GetSize() == 0) return false; // Wrap all user input into a Python class std::string auto_generated_class_name(GenerateUniqueName( "lldb_autogen_python_type_synth_class", num_created_classes, name_token)); StringList auto_generated_class; // Create the function name & definition string. sstr.Printf("class %s:", auto_generated_class_name.c_str()); auto_generated_class.AppendString(sstr.GetString()); // Wrap everything up inside the class, increasing the indentation. we don't // need to play any fancy indentation tricks here because there is no // surrounding code whose indentation we need to honor for (int i = 0; i < num_lines; ++i) { sstr.Clear(); sstr.Printf(" %s", user_input.GetStringAtIndex(i)); auto_generated_class.AppendString(sstr.GetString()); } // Verify that the results are valid Python. (even though the method is // ExportFunctionDefinitionToInterpreter, a class will actually be exported) // (TODO: rename that method to ExportDefinitionToInterpreter) if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success()) return false; // Store the name of the auto-generated class output.assign(auto_generated_class_name); return true; } StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) { if (class_name == nullptr || class_name[0] == '\0') return StructuredData::GenericSP(); Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); PythonObject ret_val = SWIGBridge::LLDBSWIGPython_CreateFrameRecognizer( class_name, m_dictionary_name.c_str()); return StructuredData::GenericSP( new StructuredPythonObject(std::move(ret_val))); } lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments( const StructuredData::ObjectSP &os_plugin_object_sp, lldb::StackFrameSP frame_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); if (!os_plugin_object_sp) return ValueObjectListSP(); StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); if (!generic) return nullptr; PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); if (!implementor.IsAllocated()) return ValueObjectListSP(); PythonObject py_return(PyRefType::Owned, SWIGBridge::LLDBSwigPython_GetRecognizedArguments( implementor.get(), frame_sp)); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); } if (py_return.get()) { PythonList result_list(PyRefType::Borrowed, py_return.get()); ValueObjectListSP result = std::make_shared<ValueObjectList>(); for (size_t i = 0; i < result_list.GetSize(); i++) { PyObject *item = result_list.GetItemAtIndex(i).get(); lldb::SBValue *sb_value_ptr = (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item); auto valobj_sp = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr); if (valobj_sp) result->Append(valobj_sp); } return result; } return ValueObjectListSP(); } bool ScriptInterpreterPythonImpl::ShouldHide( const StructuredData::ObjectSP &os_plugin_object_sp, lldb::StackFrameSP frame_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); if (!os_plugin_object_sp) return false; StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric(); if (!generic) return false; PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); if (!implementor.IsAllocated()) return false; bool result = SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); } return result; } ScriptedProcessInterfaceUP ScriptInterpreterPythonImpl::CreateScriptedProcessInterface() { return std::make_unique<ScriptedProcessPythonInterface>(*this); } ScriptedStopHookInterfaceSP ScriptInterpreterPythonImpl::CreateScriptedStopHookInterface() { return std::make_shared<ScriptedStopHookPythonInterface>(*this); } ScriptedBreakpointInterfaceSP ScriptInterpreterPythonImpl::CreateScriptedBreakpointInterface() { return std::make_shared<ScriptedBreakpointPythonInterface>(*this); } ScriptedThreadInterfaceSP ScriptInterpreterPythonImpl::CreateScriptedThreadInterface() { return std::make_shared<ScriptedThreadPythonInterface>(*this); } ScriptedThreadPlanInterfaceSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlanInterface() { return std::make_shared<ScriptedThreadPlanPythonInterface>(*this); } OperatingSystemInterfaceSP ScriptInterpreterPythonImpl::CreateOperatingSystemInterface() { return std::make_shared<OperatingSystemPythonInterface>(*this); } StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateStructuredDataFromScriptObject( ScriptObject obj) { void *ptr = const_cast<void *>(obj.GetPointer()); Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr)); if (!py_obj.IsValid() || py_obj.IsNone()) return {}; return py_obj.CreateStructuredObject(); } StructuredData::ObjectSP ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error) { if (!FileSystem::Instance().Exists(file_spec)) { error = Status::FromErrorString("no such file"); return StructuredData::ObjectSP(); } StructuredData::ObjectSP module_sp; LoadScriptOptions load_script_options = LoadScriptOptions().SetInitSession(true).SetSilent(false); if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options, error, &module_sp)) return module_sp; return StructuredData::ObjectSP(); } StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings( StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error) { if (!plugin_module_sp || !target || !setting_name || !setting_name[0]) return StructuredData::DictionarySP(); StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric(); if (!generic) return StructuredData::DictionarySP(); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); TargetSP target_sp(target->shared_from_this()); auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting( generic->GetValue(), setting_name, target_sp); if (!setting) return StructuredData::DictionarySP(); PythonDictionary py_dict = unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting))); if (!py_dict) return StructuredData::DictionarySP(); return py_dict.CreateStructuredDictionary(); } StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider( const char *class_name, lldb::ValueObjectSP valobj) { if (class_name == nullptr || class_name[0] == '\0') return StructuredData::ObjectSP(); if (!valobj.get()) return StructuredData::ObjectSP(); ExecutionContext exe_ctx(valobj->GetExecutionContextRef()); Target *target = exe_ctx.GetTargetPtr(); if (!target) return StructuredData::ObjectSP(); Debugger &debugger = target->GetDebugger(); ScriptInterpreterPythonImpl *python_interpreter = GetPythonInterpreter(debugger); if (!python_interpreter) return StructuredData::ObjectSP(); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateSyntheticProvider( class_name, python_interpreter->m_dictionary_name.c_str(), valobj); return StructuredData::ObjectSP( new StructuredPythonObject(std::move(ret_val))); } StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) { DebuggerSP debugger_sp(m_debugger.shared_from_this()); if (class_name == nullptr || class_name[0] == '\0') return StructuredData::GenericSP(); if (!debugger_sp.get()) return StructuredData::GenericSP(); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); PythonObject ret_val = SWIGBridge::LLDBSwigPythonCreateCommandObject( class_name, m_dictionary_name.c_str(), debugger_sp); if (ret_val.IsValid()) return StructuredData::GenericSP( new StructuredPythonObject(std::move(ret_val))); else return {}; } bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction( const char *oneliner, std::string &output, const void *name_token) { StringList input; input.SplitIntoLines(oneliner, strlen(oneliner)); return GenerateTypeScriptFunction(input, output, name_token); } bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass( const char *oneliner, std::string &output, const void *name_token) { StringList input; input.SplitIntoLines(oneliner, strlen(oneliner)); return GenerateTypeSynthClass(input, output, name_token); } Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData( StringList &user_input, std::string &output, bool has_extra_args, bool is_callback) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); StreamString sstr; Status error; if (user_input.GetSize() == 0) { error = Status::FromErrorString("No input data."); return error; } std::string auto_generated_function_name(GenerateUniqueName( "lldb_autogen_python_bp_callback_func_", num_created_functions)); if (has_extra_args) sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):", auto_generated_function_name.c_str()); else sstr.Printf("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str()); error = GenerateFunction(sstr.GetData(), user_input, is_callback); if (!error.Success()) return error; // Store the name of the auto-generated function to be called. output.assign(auto_generated_function_name); return error; } bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData( StringList &user_input, std::string &output, bool is_callback) { static uint32_t num_created_functions = 0; user_input.RemoveBlankLines(); StreamString sstr; if (user_input.GetSize() == 0) return false; std::string auto_generated_function_name(GenerateUniqueName( "lldb_autogen_python_wp_callback_func_", num_created_functions)); sstr.Printf("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str()); if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success()) return false; // Store the name of the auto-generated function to be called. output.assign(auto_generated_function_name); return true; } bool ScriptInterpreterPythonImpl::GetScriptedSummary( const char *python_function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) { LLDB_SCOPED_TIMER(); if (!valobj.get()) { retval.assign("<no object>"); return false; } void *old_callee = nullptr; StructuredData::Generic *generic = nullptr; if (callee_wrapper_sp) { generic = callee_wrapper_sp->GetAsGeneric(); if (generic) old_callee = generic->GetValue(); } void *new_callee = old_callee; bool ret_val; if (python_function_name && *python_function_name) { { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); { TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options)); static Timer::Category func_cat("LLDBSwigPythonCallTypeScript"); Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript"); ret_val = SWIGBridge::LLDBSwigPythonCallTypeScript( python_function_name, GetSessionDictionary().get(), valobj, &new_callee, options_sp, retval); } } } else { retval.assign("<no function name>"); return false; } if (new_callee && old_callee != new_callee) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); callee_wrapper_sp = std::make_shared<StructuredPythonObject>( PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee))); } return ret_val; } bool ScriptInterpreterPythonImpl::FormatterCallbackFunction( const char *python_function_name, TypeImplSP type_impl_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); return SWIGBridge::LLDBSwigPythonFormatterCallbackFunction( python_function_name, m_dictionary_name.c_str(), type_impl_sp); } bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction( void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { CommandDataPython *bp_option_data = (CommandDataPython *)baton; const char *python_function_name = bp_option_data->script_source.c_str(); if (!context) return true; ExecutionContext exe_ctx(context->exe_ctx_ref); Target *target = exe_ctx.GetTargetPtr(); if (!target) return true; Debugger &debugger = target->GetDebugger(); ScriptInterpreterPythonImpl *python_interpreter = GetPythonInterpreter(debugger); if (!python_interpreter) return true; if (python_function_name && python_function_name[0]) { const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id); if (breakpoint_sp) { const BreakpointLocationSP bp_loc_sp( breakpoint_sp->FindLocationByID(break_loc_id)); if (stop_frame_sp && bp_loc_sp) { bool ret_val = true; { Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); Expected<bool> maybe_ret_val = SWIGBridge::LLDBSwigPythonBreakpointCallbackFunction( python_function_name, python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, bp_loc_sp, bp_option_data->m_extra_args); if (!maybe_ret_val) { llvm::handleAllErrors( maybe_ret_val.takeError(), [&](PythonException &E) { *debugger.GetAsyncErrorStream() << E.ReadBacktrace(); }, [&](const llvm::ErrorInfoBase &E) { *debugger.GetAsyncErrorStream() << E.message(); }); } else { ret_val = maybe_ret_val.get(); } } return ret_val; } } } // We currently always true so we stop in case anything goes wrong when // trying to call the script function return true; } bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction( void *baton, StoppointCallbackContext *context, user_id_t watch_id) { WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *)baton; const char *python_function_name = wp_option_data->script_source.c_str(); if (!context) return true; ExecutionContext exe_ctx(context->exe_ctx_ref); Target *target = exe_ctx.GetTargetPtr(); if (!target) return true; Debugger &debugger = target->GetDebugger(); ScriptInterpreterPythonImpl *python_interpreter = GetPythonInterpreter(debugger); if (!python_interpreter) return true; if (python_function_name && python_function_name[0]) { const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP()); WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id); if (wp_sp) { if (stop_frame_sp && wp_sp) { bool ret_val = true; { Locker py_lock(python_interpreter, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSwigPythonWatchpointCallbackFunction( python_function_name, python_interpreter->m_dictionary_name.c_str(), stop_frame_sp, wp_sp); } return ret_val; } } } // We currently always true so we stop in case anything goes wrong when // trying to call the script function return true; } size_t ScriptInterpreterPythonImpl::CalculateNumChildren( const StructuredData::ObjectSP &implementor_sp, uint32_t max) { if (!implementor_sp) return 0; StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return 0; auto *implementor = static_cast<PyObject *>(generic->GetValue()); if (!implementor) return 0; size_t ret_val = 0; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max); } return ret_val; } lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex( const StructuredData::ObjectSP &implementor_sp, uint32_t idx) { if (!implementor_sp) return lldb::ValueObjectSP(); StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return lldb::ValueObjectSP(); auto *implementor = static_cast<PyObject *>(generic->GetValue()); if (!implementor) return lldb::ValueObjectSP(); lldb::ValueObjectSP ret_val; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); PyObject *child_ptr = SWIGBridge::LLDBSwigPython_GetChildAtIndex(implementor, idx); if (child_ptr != nullptr && child_ptr != Py_None) { lldb::SBValue *sb_value_ptr = (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); if (sb_value_ptr == nullptr) Py_XDECREF(child_ptr); else ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue( sb_value_ptr); } else { Py_XDECREF(child_ptr); } } return ret_val; } llvm::Expected<int> ScriptInterpreterPythonImpl::GetIndexOfChildWithName( const StructuredData::ObjectSP &implementor_sp, const char *child_name) { if (!implementor_sp) return llvm::createStringError("Type has no child named '%s'", child_name); StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return llvm::createStringError("Type has no child named '%s'", child_name); auto *implementor = static_cast<PyObject *>(generic->GetValue()); if (!implementor) return llvm::createStringError("Type has no child named '%s'", child_name); int ret_val = INT32_MAX; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name); } if (ret_val == INT32_MAX) return llvm::createStringError("Type has no child named '%s'", child_name); return ret_val; } bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance( const StructuredData::ObjectSP &implementor_sp) { bool ret_val = false; if (!implementor_sp) return ret_val; StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return ret_val; auto *implementor = static_cast<PyObject *>(generic->GetValue()); if (!implementor) return ret_val; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSwigPython_UpdateSynthProviderInstance(implementor); } return ret_val; } bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance( const StructuredData::ObjectSP &implementor_sp) { bool ret_val = false; if (!implementor_sp) return ret_val; StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return ret_val; auto *implementor = static_cast<PyObject *>(generic->GetValue()); if (!implementor) return ret_val; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSwigPython_MightHaveChildrenSynthProviderInstance( implementor); } return ret_val; } lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue( const StructuredData::ObjectSP &implementor_sp) { lldb::ValueObjectSP ret_val(nullptr); if (!implementor_sp) return ret_val; StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return ret_val; auto *implementor = static_cast<PyObject *>(generic->GetValue()); if (!implementor) return ret_val; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); PyObject *child_ptr = SWIGBridge::LLDBSwigPython_GetValueSynthProviderInstance(implementor); if (child_ptr != nullptr && child_ptr != Py_None) { lldb::SBValue *sb_value_ptr = (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr); if (sb_value_ptr == nullptr) Py_XDECREF(child_ptr); else ret_val = SWIGBridge::LLDBSWIGPython_GetValueObjectSPFromSBValue( sb_value_ptr); } else { Py_XDECREF(child_ptr); } } return ret_val; } ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName( const StructuredData::ObjectSP &implementor_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); if (!implementor_sp) return {}; StructuredData::Generic *generic = implementor_sp->GetAsGeneric(); if (!generic) return {}; PythonObject implementor(PyRefType::Borrowed, (PyObject *)generic->GetValue()); if (!implementor.IsAllocated()) return {}; llvm::Expected<PythonObject> expected_py_return = implementor.CallMethod("get_type_name"); if (!expected_py_return) { llvm::consumeError(expected_py_return.takeError()); return {}; } PythonObject py_return = std::move(expected_py_return.get()); if (!py_return.IsAllocated() || !PythonString::Check(py_return.get())) return {}; PythonString type_name(PyRefType::Borrowed, py_return.get()); return ConstString(type_name.GetString()); } bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( const char *impl_function, Process *process, std::string &output, Status &error) { bool ret_val; if (!process) { error = Status::FromErrorString("no process"); return false; } if (!impl_function || !impl_function[0]) { error = Status::FromErrorString("no function to execute"); return false; } { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordProcess( impl_function, m_dictionary_name.c_str(), process->shared_from_this(), output); if (!ret_val) error = Status::FromErrorString("python script evaluation failed"); } return ret_val; } bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( const char *impl_function, Thread *thread, std::string &output, Status &error) { if (!thread) { error = Status::FromErrorString("no thread"); return false; } if (!impl_function || !impl_function[0]) { error = Status::FromErrorString("no function to execute"); return false; } Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); if (std::optional<std::string> result = SWIGBridge::LLDBSWIGPythonRunScriptKeywordThread( impl_function, m_dictionary_name.c_str(), thread->shared_from_this())) { output = std::move(*result); return true; } error = Status::FromErrorString("python script evaluation failed"); return false; } bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( const char *impl_function, Target *target, std::string &output, Status &error) { bool ret_val; if (!target) { error = Status::FromErrorString("no thread"); return false; } if (!impl_function || !impl_function[0]) { error = Status::FromErrorString("no function to execute"); return false; } { TargetSP target_sp(target->shared_from_this()); Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordTarget( impl_function, m_dictionary_name.c_str(), target_sp, output); if (!ret_val) error = Status::FromErrorString("python script evaluation failed"); } return ret_val; } bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( const char *impl_function, StackFrame *frame, std::string &output, Status &error) { if (!frame) { error = Status::FromErrorString("no frame"); return false; } if (!impl_function || !impl_function[0]) { error = Status::FromErrorString("no function to execute"); return false; } Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); if (std::optional<std::string> result = SWIGBridge::LLDBSWIGPythonRunScriptKeywordFrame( impl_function, m_dictionary_name.c_str(), frame->shared_from_this())) { output = std::move(*result); return true; } error = Status::FromErrorString("python script evaluation failed"); return false; } bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword( const char *impl_function, ValueObject *value, std::string &output, Status &error) { bool ret_val; if (!value) { error = Status::FromErrorString("no value"); return false; } if (!impl_function || !impl_function[0]) { error = Status::FromErrorString("no function to execute"); return false; } { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN); ret_val = SWIGBridge::LLDBSWIGPythonRunScriptKeywordValue( impl_function, m_dictionary_name.c_str(), value->GetSP(), output); if (!ret_val) error = Status::FromErrorString("python script evaluation failed"); } return ret_val; } uint64_t replace_all(std::string &str, const std::string &oldStr, const std::string &newStr) { size_t pos = 0; uint64_t matches = 0; while ((pos = str.find(oldStr, pos)) != std::string::npos) { matches++; str.replace(pos, oldStr.length(), newStr); pos += newStr.length(); } return matches; } bool ScriptInterpreterPythonImpl::LoadScriptingModule( const char *pathname, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir, lldb::TargetSP target_sp) { namespace fs = llvm::sys::fs; namespace path = llvm::sys::path; ExecuteScriptOptions exc_options = ExecuteScriptOptions() .SetEnableIO(!options.GetSilent()) .SetSetLLDBGlobals(false); if (!pathname || !pathname[0]) { error = Status::FromErrorString("empty path"); return false; } llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>> io_redirect_or_error = ScriptInterpreterIORedirect::Create( exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr); if (!io_redirect_or_error) { error = Status::FromError(io_redirect_or_error.takeError()); return false; } ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error; // Before executing Python code, lock the GIL. Locker py_lock(this, Locker::AcquireLock | (options.GetInitSession() ? Locker::InitSession : 0) | Locker::NoSTDIN, Locker::FreeAcquiredLock | (options.GetInitSession() ? Locker::TearDownSession : 0), io_redirect.GetInputFile(), io_redirect.GetOutputFile(), io_redirect.GetErrorFile()); auto ExtendSysPath = [&](std::string directory) -> llvm::Error { if (directory.empty()) { return llvm::createStringError("invalid directory name"); } replace_all(directory, "\\", "\\\\"); replace_all(directory, "'", "\\'"); // Make sure that Python has "directory" in the search path. StreamString command_stream; command_stream.Printf("if not (sys.path.__contains__('%s')):\n " "sys.path.insert(1,'%s');\n\n", directory.c_str(), directory.c_str()); bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), exc_options).Success(); if (!syspath_retval) return llvm::createStringError("Python sys.path handling failed"); return llvm::Error::success(); }; std::string module_name(pathname); bool possible_package = false; if (extra_search_dir) { if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) { error = Status::FromError(std::move(e)); return false; } } else { FileSpec module_file(pathname); FileSystem::Instance().Resolve(module_file); fs::file_status st; std::error_code ec = status(module_file.GetPath(), st); if (ec || st.type() == fs::file_type::status_error || st.type() == fs::file_type::type_unknown || st.type() == fs::file_type::file_not_found) { // if not a valid file of any sort, check if it might be a filename still // dot can't be used but / and \ can, and if either is found, reject if (strchr(pathname, '\\') || strchr(pathname, '/')) { error = Status::FromErrorStringWithFormatv("invalid pathname '{0}'", pathname); return false; } // Not a filename, probably a package of some sort, let it go through. possible_package = true; } else if (is_directory(st) || is_regular_file(st)) { if (module_file.GetDirectory().IsEmpty()) { error = Status::FromErrorStringWithFormatv( "invalid directory name '{0}'", pathname); return false; } if (llvm::Error e = ExtendSysPath(module_file.GetDirectory().GetCString())) { error = Status::FromError(std::move(e)); return false; } module_name = module_file.GetFilename().GetCString(); } else { error = Status::FromErrorString( "no known way to import this module specification"); return false; } } // Strip .py or .pyc extension llvm::StringRef extension = llvm::sys::path::extension(module_name); if (!extension.empty()) { if (extension == ".py") module_name.resize(module_name.length() - 3); else if (extension == ".pyc") module_name.resize(module_name.length() - 4); } if (!possible_package && module_name.find('.') != llvm::StringRef::npos) { error = Status::FromErrorStringWithFormat( "Python does not allow dots in module names: %s", module_name.c_str()); return false; } if (module_name.find('-') != llvm::StringRef::npos) { error = Status::FromErrorStringWithFormat( "Python discourages dashes in module names: %s", module_name.c_str()); return false; } // Check if the module is already imported. StreamString command_stream; command_stream.Clear(); command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str()); bool does_contain = false; // This call will succeed if the module was ever imported in any Debugger in // the lifetime of the process in which this LLDB framework is living. const bool does_contain_executed = ExecuteOneLineWithReturn( command_stream.GetData(), ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options); const bool was_imported_globally = does_contain_executed && does_contain; const bool was_imported_locally = GetSessionDictionary() .GetItemForKey(PythonString(module_name)) .IsAllocated(); // now actually do the import command_stream.Clear(); if (was_imported_globally || was_imported_locally) { if (!was_imported_locally) command_stream.Printf("import %s ; reload_module(%s)", module_name.c_str(), module_name.c_str()); else command_stream.Printf("reload_module(%s)", module_name.c_str()); } else command_stream.Printf("import %s", module_name.c_str()); error = ExecuteMultipleLines(command_stream.GetData(), exc_options); if (error.Fail()) return false; // if we are here, everything worked // call __lldb_init_module(debugger,dict) if (!SWIGBridge::LLDBSwigPythonCallModuleInit( module_name.c_str(), m_dictionary_name.c_str(), m_debugger.shared_from_this())) { error = Status::FromErrorString("calling __lldb_init_module failed"); return false; } if (module_sp) { // everything went just great, now set the module object command_stream.Clear(); command_stream.Printf("%s", module_name.c_str()); void *module_pyobj = nullptr; if (ExecuteOneLineWithReturn( command_stream.GetData(), ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj, exc_options) && module_pyobj) *module_sp = std::make_shared<StructuredPythonObject>(PythonObject( PyRefType::Owned, static_cast<PyObject *>(module_pyobj))); } // Finally, if we got a target passed in, then we should tell the new module // about this target: if (target_sp) return SWIGBridge::LLDBSwigPythonCallModuleNewTarget( module_name.c_str(), m_dictionary_name.c_str(), target_sp); return true; } bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) { if (!word || !word[0]) return false; llvm::StringRef word_sr(word); // filter out a few characters that would just confuse us and that are // clearly not keyword material anyway if (word_sr.find('"') != llvm::StringRef::npos || word_sr.find('\'') != llvm::StringRef::npos) return false; StreamString command_stream; command_stream.Printf("keyword.iskeyword('%s')", word); bool result; ExecuteScriptOptions options; options.SetEnableIO(false); options.SetMaskoutErrors(true); options.SetSetLLDBGlobals(false); if (ExecuteOneLineWithReturn(command_stream.GetData(), ScriptInterpreter::eScriptReturnTypeBool, &result, options)) return result; return false; } ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler( lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro) : m_debugger_sp(debugger_sp), m_synch_wanted(synchro), m_old_asynch(debugger_sp->GetAsyncExecution()) { if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous) m_debugger_sp->SetAsyncExecution(false); else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous) m_debugger_sp->SetAsyncExecution(true); } ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() { if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue) m_debugger_sp->SetAsyncExecution(m_old_asynch); } bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( const char *impl_function, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) { if (!impl_function) { error = Status::FromErrorString("no function to execute"); return false; } lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); if (!debugger_sp.get()) { error = Status::FromErrorString("invalid Debugger pointer"); return false; } bool ret_val = false; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), Locker::FreeLock | Locker::TearDownSession); SynchronicityHandler synch_handler(debugger_sp, synchronicity); std::string args_str = args.str(); ret_val = SWIGBridge::LLDBSwigPythonCallCommand( impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(), cmd_retobj, exe_ctx_ref_sp); } if (!ret_val) error = Status::FromErrorString("unable to execute script function"); else if (cmd_retobj.GetStatus() == eReturnStatusFailed) return false; error.Clear(); return ret_val; } bool ScriptInterpreterPythonImpl::RunScriptBasedCommand( StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) { if (!impl_obj_sp || !impl_obj_sp->IsValid()) { error = Status::FromErrorString("no function to execute"); return false; } lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); if (!debugger_sp.get()) { error = Status::FromErrorString("invalid Debugger pointer"); return false; } bool ret_val = false; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), Locker::FreeLock | Locker::TearDownSession); SynchronicityHandler synch_handler(debugger_sp, synchronicity); std::string args_str = args.str(); ret_val = SWIGBridge::LLDBSwigPythonCallCommandObject( static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp, args_str.c_str(), cmd_retobj, exe_ctx_ref_sp); } if (!ret_val) error = Status::FromErrorString("unable to execute script function"); else if (cmd_retobj.GetStatus() == eReturnStatusFailed) return false; error.Clear(); return ret_val; } bool ScriptInterpreterPythonImpl::RunScriptBasedParsedCommand( StructuredData::GenericSP impl_obj_sp, Args &args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) { if (!impl_obj_sp || !impl_obj_sp->IsValid()) { error = Status::FromErrorString("no function to execute"); return false; } lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx)); if (!debugger_sp.get()) { error = Status::FromErrorString("invalid Debugger pointer"); return false; } bool ret_val = false; { Locker py_lock(this, Locker::AcquireLock | Locker::InitSession | (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN), Locker::FreeLock | Locker::TearDownSession); SynchronicityHandler synch_handler(debugger_sp, synchronicity); StructuredData::ArraySP args_arr_sp(new StructuredData::Array()); for (const Args::ArgEntry &entry : args) { args_arr_sp->AddStringItem(entry.ref()); } StructuredDataImpl args_impl(args_arr_sp); ret_val = SWIGBridge::LLDBSwigPythonCallParsedCommandObject( static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp, args_impl, cmd_retobj, exe_ctx_ref_sp); } if (!ret_val) error = Status::FromErrorString("unable to execute script function"); else if (cmd_retobj.GetStatus() == eReturnStatusFailed) return false; error.Clear(); return ret_val; } std::optional<std::string> ScriptInterpreterPythonImpl::GetRepeatCommandForScriptedCommand( StructuredData::GenericSP impl_obj_sp, Args &args) { if (!impl_obj_sp || !impl_obj_sp->IsValid()) return std::nullopt; lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this(); if (!debugger_sp.get()) return std::nullopt; std::optional<std::string> ret_val; { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); StructuredData::ArraySP args_arr_sp(new StructuredData::Array()); // For scripting commands, we send the command string: std::string command; args.GetQuotedCommandString(command); ret_val = SWIGBridge::LLDBSwigPythonGetRepeatCommandForScriptedCommand( static_cast<PyObject *>(impl_obj_sp->GetValue()), command); } return ret_val; } StructuredData::DictionarySP ScriptInterpreterPythonImpl::HandleArgumentCompletionForScriptedCommand( StructuredData::GenericSP impl_obj_sp, std::vector<llvm::StringRef> &args, size_t args_pos, size_t char_in_arg) { StructuredData::DictionarySP completion_dict_sp; if (!impl_obj_sp || !impl_obj_sp->IsValid()) return completion_dict_sp; { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); completion_dict_sp = SWIGBridge::LLDBSwigPythonHandleArgumentCompletionForScriptedCommand( static_cast<PyObject *>(impl_obj_sp->GetValue()), args, args_pos, char_in_arg); } return completion_dict_sp; } StructuredData::DictionarySP ScriptInterpreterPythonImpl::HandleOptionArgumentCompletionForScriptedCommand( StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_option, size_t char_in_arg) { StructuredData::DictionarySP completion_dict_sp; if (!impl_obj_sp || !impl_obj_sp->IsValid()) return completion_dict_sp; { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); completion_dict_sp = SWIGBridge:: LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand( static_cast<PyObject *>(impl_obj_sp->GetValue()), long_option, char_in_arg); } return completion_dict_sp; } /// In Python, a special attribute __doc__ contains the docstring for an object /// (function, method, class, ...) if any is defined Otherwise, the attribute's /// value is None. bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item, std::string &dest) { dest.clear(); if (!item || !*item) return false; std::string command(item); command += ".__doc__"; // Python is going to point this to valid data if ExecuteOneLineWithReturn // returns successfully. char *result_ptr = nullptr; if (ExecuteOneLineWithReturn( command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone, &result_ptr, ExecuteScriptOptions().SetEnableIO(false))) { if (result_ptr) dest.assign(result_ptr); return true; } StreamString str_stream; str_stream << "Function " << item << " was not found. Containing module might be missing."; dest = std::string(str_stream.GetString()); return false; } bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject( StructuredData::GenericSP cmd_obj_sp, std::string &dest) { dest.clear(); Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); if (!cmd_obj_sp) return false; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return false; llvm::Expected<PythonObject> expected_py_return = implementor.CallMethod("get_short_help"); if (!expected_py_return) { llvm::consumeError(expected_py_return.takeError()); return false; } PythonObject py_return = std::move(expected_py_return.get()); if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { PythonString py_string(PyRefType::Borrowed, py_return.get()); llvm::StringRef return_data(py_string.GetString()); dest.assign(return_data.data(), return_data.size()); return true; } return false; } uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject( StructuredData::GenericSP cmd_obj_sp) { uint32_t result = 0; Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); static char callee_name[] = "get_flags"; if (!cmd_obj_sp) return result; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return result; PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); if (PyErr_Occurred()) PyErr_Clear(); if (!pmeth.IsAllocated()) return result; if (PyCallable_Check(pmeth.get()) == 0) { if (PyErr_Occurred()) PyErr_Clear(); return result; } if (PyErr_Occurred()) PyErr_Clear(); long long py_return = unwrapOrSetPythonException( As<long long>(implementor.CallMethod(callee_name))); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); } else { result = py_return; } return result; } StructuredData::ObjectSP ScriptInterpreterPythonImpl::GetOptionsForCommandObject( StructuredData::GenericSP cmd_obj_sp) { StructuredData::ObjectSP result = {}; Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); static char callee_name[] = "get_options_definition"; if (!cmd_obj_sp) return result; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return result; PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); if (PyErr_Occurred()) PyErr_Clear(); if (!pmeth.IsAllocated()) return result; if (PyCallable_Check(pmeth.get()) == 0) { if (PyErr_Occurred()) PyErr_Clear(); return result; } if (PyErr_Occurred()) PyErr_Clear(); PythonDictionary py_return = unwrapOrSetPythonException( As<PythonDictionary>(implementor.CallMethod(callee_name))); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); return {}; } return py_return.CreateStructuredObject(); } StructuredData::ObjectSP ScriptInterpreterPythonImpl::GetArgumentsForCommandObject( StructuredData::GenericSP cmd_obj_sp) { StructuredData::ObjectSP result = {}; Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); static char callee_name[] = "get_args_definition"; if (!cmd_obj_sp) return result; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return result; PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); if (PyErr_Occurred()) PyErr_Clear(); if (!pmeth.IsAllocated()) return result; if (PyCallable_Check(pmeth.get()) == 0) { if (PyErr_Occurred()) PyErr_Clear(); return result; } if (PyErr_Occurred()) PyErr_Clear(); PythonList py_return = unwrapOrSetPythonException( As<PythonList>(implementor.CallMethod(callee_name))); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); return {}; } return py_return.CreateStructuredObject(); } void ScriptInterpreterPythonImpl::OptionParsingStartedForCommandObject( StructuredData::GenericSP cmd_obj_sp) { Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); static char callee_name[] = "option_parsing_started"; if (!cmd_obj_sp) return; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return; PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); if (PyErr_Occurred()) PyErr_Clear(); if (!pmeth.IsAllocated()) return; if (PyCallable_Check(pmeth.get()) == 0) { if (PyErr_Occurred()) PyErr_Clear(); return; } if (PyErr_Occurred()) PyErr_Clear(); // option_parsing_starting doesn't return anything, ignore anything but // python errors. unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name))); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); return; } } bool ScriptInterpreterPythonImpl::SetOptionValueForCommandObject( StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx, llvm::StringRef long_option, llvm::StringRef value) { StructuredData::ObjectSP result = {}; Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); static char callee_name[] = "set_option_value"; if (!cmd_obj_sp) return false; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return false; PythonObject pmeth(PyRefType::Owned, PyObject_GetAttrString(implementor.get(), callee_name)); if (PyErr_Occurred()) PyErr_Clear(); if (!pmeth.IsAllocated()) return false; if (PyCallable_Check(pmeth.get()) == 0) { if (PyErr_Occurred()) PyErr_Clear(); return false; } if (PyErr_Occurred()) PyErr_Clear(); lldb::ExecutionContextRefSP exe_ctx_ref_sp; if (exe_ctx) exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx); PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp); bool py_return = unwrapOrSetPythonException(As<bool>( implementor.CallMethod(callee_name, ctx_ref_obj, long_option.str().c_str(), value.str().c_str()))); // if it fails, print the error but otherwise go on if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); return false; } return py_return; } bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject( StructuredData::GenericSP cmd_obj_sp, std::string &dest) { dest.clear(); Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock); if (!cmd_obj_sp) return false; PythonObject implementor(PyRefType::Borrowed, (PyObject *)cmd_obj_sp->GetValue()); if (!implementor.IsAllocated()) return false; llvm::Expected<PythonObject> expected_py_return = implementor.CallMethod("get_long_help"); if (!expected_py_return) { llvm::consumeError(expected_py_return.takeError()); return false; } PythonObject py_return = std::move(expected_py_return.get()); bool got_string = false; if (py_return.IsAllocated() && PythonString::Check(py_return.get())) { PythonString str(PyRefType::Borrowed, py_return.get()); llvm::StringRef str_data(str.GetString()); dest.assign(str_data.data(), str_data.size()); got_string = true; } return got_string; } std::unique_ptr<ScriptInterpreterLocker> ScriptInterpreterPythonImpl::AcquireInterpreterLock() { std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker( this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN, Locker::FreeLock | Locker::TearDownSession)); return py_lock; } void ScriptInterpreterPythonImpl::Initialize() { LLDB_SCOPED_TIMER(); // RAII-based initialization which correctly handles multiple-initialization, // version- specific differences among Python 2 and Python 3, and saving and // restoring various other pieces of state that can get mucked with during // initialization. InitializePythonRAII initialize_guard; LLDBSwigPyInit(); // Update the path python uses to search for modules to include the current // directory. RunSimpleString("import sys"); AddToSysPath(AddLocation::End, "."); // Don't denormalize paths when calling file_spec.GetPath(). On platforms // that use a backslash as the path separator, this will result in executing // python code containing paths with unescaped backslashes. But Python also // accepts forward slashes, so to make life easier we just use that. if (FileSpec file_spec = GetPythonDir()) AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); if (FileSpec file_spec = HostInfo::GetShlibDir()) AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false)); RunSimpleString("sys.dont_write_bytecode = 1; import " "lldb.embedded_interpreter; from " "lldb.embedded_interpreter import run_python_interpreter; " "from lldb.embedded_interpreter import run_one_line"); #if LLDB_USE_PYTHON_SET_INTERRUPT // Python will not just overwrite its internal SIGINT handler but also the // one from the process. Backup the current SIGINT handler to prevent that // Python deletes it. RestoreSignalHandlerScope save_sigint(SIGINT); // Setup a default SIGINT signal handler that works the same way as the // normal Python REPL signal handler which raises a KeyboardInterrupt. // Also make sure to not pollute the user's REPL with the signal module nor // our utility function. RunSimpleString("def lldb_setup_sigint_handler():\n" " import signal;\n" " def signal_handler(sig, frame):\n" " raise KeyboardInterrupt()\n" " signal.signal(signal.SIGINT, signal_handler);\n" "lldb_setup_sigint_handler();\n" "del lldb_setup_sigint_handler\n"); #endif } void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location, std::string path) { std::string statement; if (location == AddLocation::Beginning) { statement.assign("sys.path.insert(0,\""); statement.append(path); statement.append("\")"); } else { statement.assign("sys.path.append(\""); statement.append(path); statement.append("\")"); } RunSimpleString(statement.c_str()); } // We are intentionally NOT calling Py_Finalize here (this would be the logical // place to call it). Calling Py_Finalize here causes test suite runs to seg // fault: The test suite runs in Python. It registers SBDebugger::Terminate to // be called 'at_exit'. When the test suite Python harness finishes up, it // calls Py_Finalize, which calls all the 'at_exit' registered functions. // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate, // which calls ScriptInterpreter::Terminate, which calls // ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we // end up with Py_Finalize being called from within Py_Finalize, which results // in a seg fault. Since this function only gets called when lldb is shutting // down and going away anyway, the fact that we don't actually call Py_Finalize // should not cause any problems (everything should shut down/go away anyway // when the process exits). // // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); } #endif