1494 lines · cpp
1//===-- PythonDataObjects.cpp ---------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "lldb/Host/Config.h"10 11#if LLDB_ENABLE_PYTHON12 13#include "PythonDataObjects.h"14#include "ScriptInterpreterPython.h"15 16#include "lldb/Host/File.h"17#include "lldb/Host/FileSystem.h"18#include "lldb/Interpreter/ScriptInterpreter.h"19#include "lldb/Utility/LLDBLog.h"20#include "lldb/Utility/Log.h"21#include "lldb/Utility/Stream.h"22 23#include "llvm/ADT/ScopeExit.h"24#include "llvm/Support/Casting.h"25#include "llvm/Support/ConvertUTF.h"26#include "llvm/Support/Errno.h"27 28#include <cstdio>29#include <variant>30 31using namespace lldb_private;32using namespace lldb;33using namespace lldb_private::python;34using llvm::cantFail;35using llvm::Error;36using llvm::Expected;37using llvm::Twine;38 39template <> Expected<bool> python::As<bool>(Expected<PythonObject> &&obj) {40 if (!obj)41 return obj.takeError();42 return obj.get().IsTrue();43}44 45template <>46Expected<long long> python::As<long long>(Expected<PythonObject> &&obj) {47 if (!obj)48 return obj.takeError();49 return obj->AsLongLong();50}51 52template <>53Expected<unsigned long long>54python::As<unsigned long long>(Expected<PythonObject> &&obj) {55 if (!obj)56 return obj.takeError();57 return obj->AsUnsignedLongLong();58}59 60template <>61Expected<std::string> python::As<std::string>(Expected<PythonObject> &&obj) {62 if (!obj)63 return obj.takeError();64 PyObject *str_obj = PyObject_Str(obj.get().get());65 if (!str_obj)66 return llvm::make_error<PythonException>();67 auto str = Take<PythonString>(str_obj);68 auto utf8 = str.AsUTF8();69 if (!utf8)70 return utf8.takeError();71 return std::string(utf8.get());72}73 74void PythonObject::Reset() {75 if (m_py_obj && Py_IsInitialized()) {76 PyGILState_STATE state = PyGILState_Ensure();77 Py_DECREF(m_py_obj);78 PyGILState_Release(state);79 }80 m_py_obj = nullptr;81}82 83Expected<long long> PythonObject::AsLongLong() const {84 if (!m_py_obj)85 return nullDeref();86 assert(!PyErr_Occurred());87 long long r = PyLong_AsLongLong(m_py_obj);88 if (PyErr_Occurred())89 return exception();90 return r;91}92 93Expected<unsigned long long> PythonObject::AsUnsignedLongLong() const {94 if (!m_py_obj)95 return nullDeref();96 assert(!PyErr_Occurred());97 long long r = PyLong_AsUnsignedLongLong(m_py_obj);98 if (PyErr_Occurred())99 return exception();100 return r;101}102 103// wraps on overflow, instead of raising an error.104Expected<unsigned long long> PythonObject::AsModuloUnsignedLongLong() const {105 if (!m_py_obj)106 return nullDeref();107 assert(!PyErr_Occurred());108 unsigned long long r = PyLong_AsUnsignedLongLongMask(m_py_obj);109 // FIXME: We should fetch the exception message and hoist it.110 if (PyErr_Occurred())111 return exception();112 return r;113}114 115void StructuredPythonObject::Serialize(llvm::json::OStream &s) const {116 s.value(llvm::formatv("Python Obj: {0:X}", GetValue()).str());117}118 119// PythonObject120 121void PythonObject::Dump(Stream &strm) const {122 if (!m_py_obj) {123 strm << "NULL";124 return;125 }126 127 PyObject *py_str = PyObject_Repr(m_py_obj);128 if (!py_str)129 return;130 131 auto release_py_str = llvm::make_scope_exit([py_str] { Py_DECREF(py_str); });132 133 PyObject *py_bytes = PyUnicode_AsEncodedString(py_str, "utf-8", "replace");134 if (!py_bytes)135 return;136 137 auto release_py_bytes =138 llvm::make_scope_exit([py_bytes] { Py_DECREF(py_bytes); });139 140 char *buffer = nullptr;141 Py_ssize_t length = 0;142 if (PyBytes_AsStringAndSize(py_bytes, &buffer, &length) == -1)143 return;144 145 strm << llvm::StringRef(buffer, length);146}147 148PyObjectType PythonObject::GetObjectType() const {149 if (!IsAllocated())150 return PyObjectType::None;151 152 if (PythonModule::Check(m_py_obj))153 return PyObjectType::Module;154 if (PythonList::Check(m_py_obj))155 return PyObjectType::List;156 if (PythonTuple::Check(m_py_obj))157 return PyObjectType::Tuple;158 if (PythonDictionary::Check(m_py_obj))159 return PyObjectType::Dictionary;160 if (PythonString::Check(m_py_obj))161 return PyObjectType::String;162 if (PythonBytes::Check(m_py_obj))163 return PyObjectType::Bytes;164 if (PythonByteArray::Check(m_py_obj))165 return PyObjectType::ByteArray;166 if (PythonBoolean::Check(m_py_obj))167 return PyObjectType::Boolean;168 if (PythonInteger::Check(m_py_obj))169 return PyObjectType::Integer;170 if (PythonFile::Check(m_py_obj))171 return PyObjectType::File;172 if (PythonCallable::Check(m_py_obj))173 return PyObjectType::Callable;174 return PyObjectType::Unknown;175}176 177PythonString PythonObject::Repr() const {178 if (!m_py_obj)179 return PythonString();180 PyObject *repr = PyObject_Repr(m_py_obj);181 if (!repr)182 return PythonString();183 return PythonString(PyRefType::Owned, repr);184}185 186PythonString PythonObject::Str() const {187 if (!m_py_obj)188 return PythonString();189 PyObject *str = PyObject_Str(m_py_obj);190 if (!str)191 return PythonString();192 return PythonString(PyRefType::Owned, str);193}194 195PythonObject196PythonObject::ResolveNameWithDictionary(llvm::StringRef name,197 const PythonDictionary &dict) {198 size_t dot_pos = name.find('.');199 llvm::StringRef piece = name.substr(0, dot_pos);200 PythonObject result = dict.GetItemForKey(PythonString(piece));201 if (dot_pos == llvm::StringRef::npos) {202 // There was no dot, we're done.203 return result;204 }205 206 // There was a dot. The remaining portion of the name should be looked up in207 // the context of the object that was found in the dictionary.208 return result.ResolveName(name.substr(dot_pos + 1));209}210 211PythonObject PythonObject::ResolveName(llvm::StringRef name) const {212 // Resolve the name in the context of the specified object. If, for example,213 // `this` refers to a PyModule, then this will look for `name` in this214 // module. If `this` refers to a PyType, then it will resolve `name` as an215 // attribute of that type. If `this` refers to an instance of an object,216 // then it will resolve `name` as the value of the specified field.217 //218 // This function handles dotted names so that, for example, if `m_py_obj`219 // refers to the `sys` module, and `name` == "path.append", then it will find220 // the function `sys.path.append`.221 222 size_t dot_pos = name.find('.');223 if (dot_pos == llvm::StringRef::npos) {224 // No dots in the name, we should be able to find the value immediately as225 // an attribute of `m_py_obj`.226 return GetAttributeValue(name);227 }228 229 // Look up the first piece of the name, and resolve the rest as a child of230 // that.231 PythonObject parent = ResolveName(name.substr(0, dot_pos));232 if (!parent.IsAllocated())233 return PythonObject();234 235 // Tail recursion.. should be optimized by the compiler236 return parent.ResolveName(name.substr(dot_pos + 1));237}238 239bool PythonObject::HasAttribute(llvm::StringRef attr) const {240 if (!IsValid())241 return false;242 PythonString py_attr(attr);243 return !!PyObject_HasAttr(m_py_obj, py_attr.get());244}245 246PythonObject PythonObject::GetAttributeValue(llvm::StringRef attr) const {247 if (!IsValid())248 return PythonObject();249 250 PythonString py_attr(attr);251 if (!PyObject_HasAttr(m_py_obj, py_attr.get()))252 return PythonObject();253 254 return PythonObject(PyRefType::Owned,255 PyObject_GetAttr(m_py_obj, py_attr.get()));256}257 258StructuredData::ObjectSP PythonObject::CreateStructuredObject() const {259 switch (GetObjectType()) {260 case PyObjectType::Dictionary:261 return PythonDictionary(PyRefType::Borrowed, m_py_obj)262 .CreateStructuredDictionary();263 case PyObjectType::Boolean:264 return PythonBoolean(PyRefType::Borrowed, m_py_obj)265 .CreateStructuredBoolean();266 case PyObjectType::Integer: {267 StructuredData::IntegerSP int_sp =268 PythonInteger(PyRefType::Borrowed, m_py_obj).CreateStructuredInteger();269 if (std::holds_alternative<StructuredData::UnsignedIntegerSP>(int_sp))270 return std::get<StructuredData::UnsignedIntegerSP>(int_sp);271 if (std::holds_alternative<StructuredData::SignedIntegerSP>(int_sp))272 return std::get<StructuredData::SignedIntegerSP>(int_sp);273 return nullptr;274 };275 case PyObjectType::List:276 return PythonList(PyRefType::Borrowed, m_py_obj).CreateStructuredArray();277 case PyObjectType::String:278 return PythonString(PyRefType::Borrowed, m_py_obj).CreateStructuredString();279 case PyObjectType::Bytes:280 return PythonBytes(PyRefType::Borrowed, m_py_obj).CreateStructuredString();281 case PyObjectType::ByteArray:282 return PythonByteArray(PyRefType::Borrowed, m_py_obj)283 .CreateStructuredString();284 case PyObjectType::None:285 return StructuredData::ObjectSP();286 default:287 return StructuredData::ObjectSP(new StructuredPythonObject(288 PythonObject(PyRefType::Borrowed, m_py_obj)));289 }290}291 292// PythonString293 294PythonBytes::PythonBytes(llvm::ArrayRef<uint8_t> bytes) { SetBytes(bytes); }295 296PythonBytes::PythonBytes(const uint8_t *bytes, size_t length) {297 SetBytes(llvm::ArrayRef<uint8_t>(bytes, length));298}299 300bool PythonBytes::Check(PyObject *py_obj) {301 if (!py_obj)302 return false;303 return PyBytes_Check(py_obj);304}305 306llvm::ArrayRef<uint8_t> PythonBytes::GetBytes() const {307 if (!IsValid())308 return llvm::ArrayRef<uint8_t>();309 310 Py_ssize_t size;311 char *c;312 313 PyBytes_AsStringAndSize(m_py_obj, &c, &size);314 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);315}316 317size_t PythonBytes::GetSize() const {318 if (!IsValid())319 return 0;320 return PyBytes_Size(m_py_obj);321}322 323void PythonBytes::SetBytes(llvm::ArrayRef<uint8_t> bytes) {324 const char *data = reinterpret_cast<const char *>(bytes.data());325 *this = Take<PythonBytes>(PyBytes_FromStringAndSize(data, bytes.size()));326}327 328StructuredData::StringSP PythonBytes::CreateStructuredString() const {329 StructuredData::StringSP result(new StructuredData::String);330 Py_ssize_t size;331 char *c;332 PyBytes_AsStringAndSize(m_py_obj, &c, &size);333 result->SetValue(std::string(c, size));334 return result;335}336 337PythonByteArray::PythonByteArray(llvm::ArrayRef<uint8_t> bytes)338 : PythonByteArray(bytes.data(), bytes.size()) {}339 340PythonByteArray::PythonByteArray(const uint8_t *bytes, size_t length) {341 const char *str = reinterpret_cast<const char *>(bytes);342 *this = Take<PythonByteArray>(PyByteArray_FromStringAndSize(str, length));343}344 345bool PythonByteArray::Check(PyObject *py_obj) {346 if (!py_obj)347 return false;348 return PyByteArray_Check(py_obj);349}350 351llvm::ArrayRef<uint8_t> PythonByteArray::GetBytes() const {352 if (!IsValid())353 return llvm::ArrayRef<uint8_t>();354 355 char *c = PyByteArray_AsString(m_py_obj);356 size_t size = GetSize();357 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);358}359 360size_t PythonByteArray::GetSize() const {361 if (!IsValid())362 return 0;363 364 return PyByteArray_Size(m_py_obj);365}366 367StructuredData::StringSP PythonByteArray::CreateStructuredString() const {368 StructuredData::StringSP result(new StructuredData::String);369 llvm::ArrayRef<uint8_t> bytes = GetBytes();370 const char *str = reinterpret_cast<const char *>(bytes.data());371 result->SetValue(std::string(str, bytes.size()));372 return result;373}374 375// PythonString376 377Expected<PythonString> PythonString::FromUTF8(llvm::StringRef string) {378 PyObject *str = PyUnicode_FromStringAndSize(string.data(), string.size());379 if (!str)380 return llvm::make_error<PythonException>();381 return Take<PythonString>(str);382}383 384PythonString::PythonString(llvm::StringRef string) { SetString(string); }385 386bool PythonString::Check(PyObject *py_obj) {387 if (!py_obj)388 return false;389 390 if (PyUnicode_Check(py_obj))391 return true;392 return false;393}394 395llvm::StringRef PythonString::GetString() const {396 auto s = AsUTF8();397 if (!s) {398 llvm::consumeError(s.takeError());399 return llvm::StringRef("");400 }401 return s.get();402}403 404Expected<llvm::StringRef> PythonString::AsUTF8() const {405 if (!IsValid())406 return nullDeref();407 408 // PyUnicode_AsUTF8AndSize caches the UTF-8 representation of the string in409 // the Unicode object, which makes it more efficient and ties the lifetime of410 // the data to the Python string. However, it was only added to the Stable API411 // in Python 3.10. Older versions that want to use the Stable API must use412 // PyUnicode_AsUTF8String in combination with ConstString.413#if defined(Py_LIMITED_API) && (Py_LIMITED_API < 0x030a0000)414 PyObject *py_bytes = PyUnicode_AsUTF8String(m_py_obj);415 if (!py_bytes)416 return exception();417 auto release_py_str =418 llvm::make_scope_exit([py_bytes] { Py_DECREF(py_bytes); });419 Py_ssize_t size = PyBytes_Size(py_bytes);420 const char *str = PyBytes_AsString(py_bytes);421 422 if (!str)423 return exception();424 425 return ConstString(str, size).GetStringRef();426#else427 Py_ssize_t size;428 const char *str = PyUnicode_AsUTF8AndSize(m_py_obj, &size);429 430 if (!str)431 return exception();432 433 return llvm::StringRef(str, size);434#endif435}436 437size_t PythonString::GetSize() const {438 if (IsValid())439 return PyUnicode_GetLength(m_py_obj);440 return 0;441}442 443void PythonString::SetString(llvm::StringRef string) {444 auto s = FromUTF8(string);445 if (!s) {446 llvm::consumeError(s.takeError());447 Reset();448 } else {449 *this = std::move(s.get());450 }451}452 453StructuredData::StringSP PythonString::CreateStructuredString() const {454 StructuredData::StringSP result(new StructuredData::String);455 result->SetValue(GetString());456 return result;457}458 459// PythonInteger460 461PythonInteger::PythonInteger(int64_t value) { SetInteger(value); }462 463bool PythonInteger::Check(PyObject *py_obj) {464 if (!py_obj)465 return false;466 467 // Python 3 does not have PyInt_Check. There is only one type of integral468 // value, long.469 return PyLong_Check(py_obj);470}471 472void PythonInteger::SetInteger(int64_t value) {473 *this = Take<PythonInteger>(PyLong_FromLongLong(value));474}475 476StructuredData::IntegerSP PythonInteger::CreateStructuredInteger() const {477 StructuredData::UnsignedIntegerSP uint_sp = CreateStructuredUnsignedInteger();478 return uint_sp ? StructuredData::IntegerSP(uint_sp)479 : CreateStructuredSignedInteger();480}481 482StructuredData::UnsignedIntegerSP483PythonInteger::CreateStructuredUnsignedInteger() const {484 StructuredData::UnsignedIntegerSP result = nullptr;485 llvm::Expected<unsigned long long> value = AsUnsignedLongLong();486 if (!value)487 llvm::consumeError(value.takeError());488 else489 result = std::make_shared<StructuredData::UnsignedInteger>(value.get());490 491 return result;492}493 494StructuredData::SignedIntegerSP495PythonInteger::CreateStructuredSignedInteger() const {496 StructuredData::SignedIntegerSP result = nullptr;497 llvm::Expected<long long> value = AsLongLong();498 if (!value)499 llvm::consumeError(value.takeError());500 else501 result = std::make_shared<StructuredData::SignedInteger>(value.get());502 503 return result;504}505 506// PythonBoolean507 508PythonBoolean::PythonBoolean(bool value) { SetValue(value); }509 510bool PythonBoolean::Check(PyObject *py_obj) {511 return py_obj ? PyBool_Check(py_obj) : false;512}513 514bool PythonBoolean::GetValue() const {515 return m_py_obj ? PyObject_IsTrue(m_py_obj) : false;516}517 518void PythonBoolean::SetValue(bool value) {519 *this = Take<PythonBoolean>(PyBool_FromLong(value));520}521 522StructuredData::BooleanSP PythonBoolean::CreateStructuredBoolean() const {523 StructuredData::BooleanSP result(new StructuredData::Boolean);524 result->SetValue(GetValue());525 return result;526}527 528// PythonList529 530PythonList::PythonList(PyInitialValue value) {531 if (value == PyInitialValue::Empty)532 *this = Take<PythonList>(PyList_New(0));533}534 535PythonList::PythonList(int list_size) {536 *this = Take<PythonList>(PyList_New(list_size));537}538 539bool PythonList::Check(PyObject *py_obj) {540 if (!py_obj)541 return false;542 return PyList_Check(py_obj);543}544 545uint32_t PythonList::GetSize() const {546 if (IsValid())547 return PyList_Size(m_py_obj);548 return 0;549}550 551PythonObject PythonList::GetItemAtIndex(uint32_t index) const {552 if (IsValid())553 return PythonObject(PyRefType::Borrowed, PyList_GetItem(m_py_obj, index));554 return PythonObject();555}556 557void PythonList::SetItemAtIndex(uint32_t index, const PythonObject &object) {558 if (IsAllocated() && object.IsValid()) {559 // PyList_SetItem is documented to "steal" a reference, so we need to560 // convert it to an owned reference by incrementing it.561 Py_INCREF(object.get());562 PyList_SetItem(m_py_obj, index, object.get());563 }564}565 566void PythonList::AppendItem(const PythonObject &object) {567 if (IsAllocated() && object.IsValid()) {568 // `PyList_Append` does *not* steal a reference, so do not call `Py_INCREF`569 // here like we do with `PyList_SetItem`.570 PyList_Append(m_py_obj, object.get());571 }572}573 574StructuredData::ArraySP PythonList::CreateStructuredArray() const {575 StructuredData::ArraySP result(new StructuredData::Array);576 uint32_t count = GetSize();577 for (uint32_t i = 0; i < count; ++i) {578 PythonObject obj = GetItemAtIndex(i);579 result->AddItem(obj.CreateStructuredObject());580 }581 return result;582}583 584// PythonTuple585 586PythonTuple::PythonTuple(PyInitialValue value) {587 if (value == PyInitialValue::Empty)588 *this = Take<PythonTuple>(PyTuple_New(0));589}590 591PythonTuple::PythonTuple(int tuple_size) {592 *this = Take<PythonTuple>(PyTuple_New(tuple_size));593}594 595PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects) {596 m_py_obj = PyTuple_New(objects.size());597 598 uint32_t idx = 0;599 for (auto object : objects) {600 if (object.IsValid())601 SetItemAtIndex(idx, object);602 idx++;603 }604}605 606PythonTuple::PythonTuple(std::initializer_list<PyObject *> objects) {607 m_py_obj = PyTuple_New(objects.size());608 609 uint32_t idx = 0;610 for (auto py_object : objects) {611 PythonObject object(PyRefType::Borrowed, py_object);612 if (object.IsValid())613 SetItemAtIndex(idx, object);614 idx++;615 }616}617 618bool PythonTuple::Check(PyObject *py_obj) {619 if (!py_obj)620 return false;621 return PyTuple_Check(py_obj);622}623 624uint32_t PythonTuple::GetSize() const {625 if (IsValid())626 return PyTuple_Size(m_py_obj);627 return 0;628}629 630PythonObject PythonTuple::GetItemAtIndex(uint32_t index) const {631 if (IsValid())632 return PythonObject(PyRefType::Borrowed, PyTuple_GetItem(m_py_obj, index));633 return PythonObject();634}635 636void PythonTuple::SetItemAtIndex(uint32_t index, const PythonObject &object) {637 if (IsAllocated() && object.IsValid()) {638 // PyTuple_SetItem is documented to "steal" a reference, so we need to639 // convert it to an owned reference by incrementing it.640 Py_INCREF(object.get());641 PyTuple_SetItem(m_py_obj, index, object.get());642 }643}644 645StructuredData::ArraySP PythonTuple::CreateStructuredArray() const {646 StructuredData::ArraySP result(new StructuredData::Array);647 uint32_t count = GetSize();648 for (uint32_t i = 0; i < count; ++i) {649 PythonObject obj = GetItemAtIndex(i);650 result->AddItem(obj.CreateStructuredObject());651 }652 return result;653}654 655// PythonDictionary656 657PythonDictionary::PythonDictionary(PyInitialValue value) {658 if (value == PyInitialValue::Empty)659 *this = Take<PythonDictionary>(PyDict_New());660}661 662bool PythonDictionary::Check(PyObject *py_obj) {663 if (!py_obj)664 return false;665 666 return PyDict_Check(py_obj);667}668 669bool PythonDictionary::HasKey(const llvm::Twine &key) const {670 if (!IsValid())671 return false;672 673 PythonString key_object(key.isSingleStringRef() ? key.getSingleStringRef()674 : key.str());675 676 if (int res = PyDict_Contains(m_py_obj, key_object.get()) > 0)677 return res;678 679 PyErr_Print();680 return false;681}682 683uint32_t PythonDictionary::GetSize() const {684 if (IsValid())685 return PyDict_Size(m_py_obj);686 return 0;687}688 689PythonList PythonDictionary::GetKeys() const {690 if (IsValid())691 return PythonList(PyRefType::Owned, PyDict_Keys(m_py_obj));692 return PythonList(PyInitialValue::Invalid);693}694 695PythonObject PythonDictionary::GetItemForKey(const PythonObject &key) const {696 auto item = GetItem(key);697 if (!item) {698 llvm::consumeError(item.takeError());699 return PythonObject();700 }701 return std::move(item.get());702}703 704Expected<PythonObject>705PythonDictionary::GetItem(const PythonObject &key) const {706 if (!IsValid())707 return nullDeref();708 PyObject *o = PyDict_GetItemWithError(m_py_obj, key.get());709 if (PyErr_Occurred())710 return exception();711 if (!o)712 return keyError();713 return Retain<PythonObject>(o);714}715 716Expected<PythonObject> PythonDictionary::GetItem(const Twine &key) const {717 if (!IsValid())718 return nullDeref();719 PyObject *o = PyDict_GetItemString(m_py_obj, NullTerminated(key));720 if (PyErr_Occurred())721 return exception();722 if (!o)723 return keyError();724 return Retain<PythonObject>(o);725}726 727Error PythonDictionary::SetItem(const PythonObject &key,728 const PythonObject &value) const {729 if (!IsValid() || !value.IsValid())730 return nullDeref();731 int r = PyDict_SetItem(m_py_obj, key.get(), value.get());732 if (r < 0)733 return exception();734 return Error::success();735}736 737Error PythonDictionary::SetItem(const Twine &key,738 const PythonObject &value) const {739 if (!IsValid() || !value.IsValid())740 return nullDeref();741 int r = PyDict_SetItemString(m_py_obj, NullTerminated(key), value.get());742 if (r < 0)743 return exception();744 return Error::success();745}746 747void PythonDictionary::SetItemForKey(const PythonObject &key,748 const PythonObject &value) {749 Error error = SetItem(key, value);750 if (error)751 llvm::consumeError(std::move(error));752}753 754StructuredData::DictionarySP755PythonDictionary::CreateStructuredDictionary() const {756 StructuredData::DictionarySP result(new StructuredData::Dictionary);757 PythonList keys(GetKeys());758 uint32_t num_keys = keys.GetSize();759 for (uint32_t i = 0; i < num_keys; ++i) {760 PythonObject key = keys.GetItemAtIndex(i);761 PythonObject value = GetItemForKey(key);762 StructuredData::ObjectSP structured_value = value.CreateStructuredObject();763 result->AddItem(key.Str().GetString(), structured_value);764 }765 return result;766}767 768PythonModule PythonModule::BuiltinsModule() { return AddModule("builtins"); }769 770PythonModule PythonModule::MainModule() { return AddModule("__main__"); }771 772PythonModule PythonModule::AddModule(llvm::StringRef module) {773 std::string str = module.str();774 return PythonModule(PyRefType::Borrowed, PyImport_AddModule(str.c_str()));775}776 777Expected<PythonModule> PythonModule::Import(const Twine &name) {778 PyObject *mod = PyImport_ImportModule(NullTerminated(name));779 if (!mod)780 return exception();781 return Take<PythonModule>(mod);782}783 784Expected<PythonObject> PythonModule::Get(const Twine &name) {785 if (!IsValid())786 return nullDeref();787 PyObject *dict = PyModule_GetDict(m_py_obj);788 if (!dict)789 return exception();790 PyObject *item = PyDict_GetItemString(dict, NullTerminated(name));791 if (!item)792 return exception();793 return Retain<PythonObject>(item);794}795 796bool PythonModule::Check(PyObject *py_obj) {797 if (!py_obj)798 return false;799 800 return PyModule_Check(py_obj);801}802 803PythonDictionary PythonModule::GetDictionary() const {804 if (!IsValid())805 return PythonDictionary();806 return Retain<PythonDictionary>(PyModule_GetDict(m_py_obj));807}808 809bool PythonCallable::Check(PyObject *py_obj) {810 if (!py_obj)811 return false;812 813 PythonObject python_obj(PyRefType::Borrowed, py_obj);814 815 // Handle staticmethod/classmethod descriptors by extracting the816 // `__func__` attribute.817 if (python_obj.HasAttribute("__func__")) {818 PythonObject function_obj = python_obj.GetAttributeValue("__func__");819 if (!function_obj.IsAllocated())820 return false;821 return PyCallable_Check(function_obj.release());822 }823 824 return PyCallable_Check(py_obj);825}826 827static const char get_arg_info_script[] = R"(828from inspect import signature, Parameter, ismethod829from collections import namedtuple830ArgInfo = namedtuple('ArgInfo', ['count', 'has_varargs'])831def main(f):832 count = 0833 varargs = False834 for parameter in signature(f).parameters.values():835 kind = parameter.kind836 if kind in (Parameter.POSITIONAL_ONLY,837 Parameter.POSITIONAL_OR_KEYWORD):838 count += 1839 elif kind == Parameter.VAR_POSITIONAL:840 varargs = True841 elif kind in (Parameter.KEYWORD_ONLY,842 Parameter.VAR_KEYWORD):843 pass844 else:845 raise Exception(f'unknown parameter kind: {kind}')846 return ArgInfo(count, varargs)847)";848 849Expected<PythonCallable::ArgInfo> PythonCallable::GetArgInfo() const {850 ArgInfo result = {};851 if (!IsValid())852 return nullDeref();853 854 // no need to synchronize access to this global, we already have the GIL855 static PythonScript get_arg_info(get_arg_info_script);856 Expected<PythonObject> pyarginfo = get_arg_info(*this);857 if (!pyarginfo)858 return pyarginfo.takeError();859 long long count =860 cantFail(As<long long>(pyarginfo.get().GetAttribute("count")));861 bool has_varargs =862 cantFail(As<bool>(pyarginfo.get().GetAttribute("has_varargs")));863 result.max_positional_args = has_varargs ? ArgInfo::UNBOUNDED : count;864 865 return result;866}867 868constexpr unsigned869 PythonCallable::ArgInfo::UNBOUNDED; // FIXME delete after c++17870 871PythonObject PythonCallable::operator()() {872 return PythonObject(PyRefType::Owned, PyObject_CallObject(m_py_obj, nullptr));873}874 875PythonObject876PythonCallable::operator()(std::initializer_list<PyObject *> args) {877 PythonTuple arg_tuple(args);878 return PythonObject(PyRefType::Owned,879 PyObject_CallObject(m_py_obj, arg_tuple.get()));880}881 882PythonObject883PythonCallable::operator()(std::initializer_list<PythonObject> args) {884 PythonTuple arg_tuple(args);885 return PythonObject(PyRefType::Owned,886 PyObject_CallObject(m_py_obj, arg_tuple.get()));887}888 889bool PythonFile::Check(PyObject *py_obj) {890 if (!py_obj)891 return false;892 // In Python 3, there is no `PyFile_Check`, and in fact PyFile is not even a893 // first-class object type anymore. `PyFile_FromFd` is just a thin wrapper894 // over `io.open()`, which returns some object derived from `io.IOBase`. As a895 // result, the only way to detect a file in Python 3 is to check whether it896 // inherits from `io.IOBase`.897 auto io_module = PythonModule::Import("io");898 if (!io_module) {899 llvm::consumeError(io_module.takeError());900 return false;901 }902 auto iobase = io_module.get().Get("IOBase");903 if (!iobase) {904 llvm::consumeError(iobase.takeError());905 return false;906 }907 int r = PyObject_IsInstance(py_obj, iobase.get().get());908 if (r < 0) {909 llvm::consumeError(exception()); // clear the exception and log it.910 return false;911 }912 return !!r;913}914 915const char *PythonException::toCString() const {916 if (!m_repr_bytes)917 return "unknown exception";918 return PyBytes_AsString(m_repr_bytes);919}920 921PythonException::PythonException(const char *caller) {922 assert(PyErr_Occurred());923 m_exception_type = m_exception = m_traceback = m_repr_bytes = nullptr;924 PyErr_Fetch(&m_exception_type, &m_exception, &m_traceback);925 PyErr_NormalizeException(&m_exception_type, &m_exception, &m_traceback);926 PyErr_Clear();927 if (m_exception) {928 PyObject *repr = PyObject_Repr(m_exception);929 if (repr) {930 m_repr_bytes = PyUnicode_AsEncodedString(repr, "utf-8", nullptr);931 if (!m_repr_bytes) {932 PyErr_Clear();933 }934 Py_XDECREF(repr);935 } else {936 PyErr_Clear();937 }938 }939 Log *log = GetLog(LLDBLog::Script);940 if (caller)941 LLDB_LOGF(log, "%s failed with exception: %s", caller, toCString());942 else943 LLDB_LOGF(log, "python exception: %s", toCString());944}945void PythonException::Restore() {946 if (m_exception_type && m_exception) {947 PyErr_Restore(m_exception_type, m_exception, m_traceback);948 } else {949 PyErr_SetString(PyExc_Exception, toCString());950 }951 m_exception_type = m_exception = m_traceback = nullptr;952}953 954PythonException::~PythonException() {955 Py_XDECREF(m_exception_type);956 Py_XDECREF(m_exception);957 Py_XDECREF(m_traceback);958 Py_XDECREF(m_repr_bytes);959}960 961void PythonException::log(llvm::raw_ostream &OS) const { OS << toCString(); }962 963std::error_code PythonException::convertToErrorCode() const {964 return llvm::inconvertibleErrorCode();965}966 967bool PythonException::Matches(PyObject *exc) const {968 return PyErr_GivenExceptionMatches(m_exception_type, exc);969}970 971const char read_exception_script[] = R"(972import sys973from traceback import print_exception974if sys.version_info.major < 3:975 from StringIO import StringIO976else:977 from io import StringIO978def main(exc_type, exc_value, tb):979 f = StringIO()980 print_exception(exc_type, exc_value, tb, file=f)981 return f.getvalue()982)";983 984std::string PythonException::ReadBacktrace() const {985 986 if (!m_traceback)987 return toCString();988 989 // no need to synchronize access to this global, we already have the GIL990 static PythonScript read_exception(read_exception_script);991 992 Expected<std::string> backtrace = As<std::string>(993 read_exception(m_exception_type, m_exception, m_traceback));994 995 if (!backtrace) {996 std::string message =997 std::string(toCString()) + "\n" +998 "Traceback unavailable, an error occurred while reading it:\n";999 return (message + llvm::toString(backtrace.takeError()));1000 }1001 1002 return std::move(backtrace.get());1003}1004 1005char PythonException::ID = 0;1006 1007llvm::Expected<File::OpenOptions>1008GetOptionsForPyObject(const PythonObject &obj) {1009 auto options = File::OpenOptions(0);1010 auto readable = As<bool>(obj.CallMethod("readable"));1011 if (!readable)1012 return readable.takeError();1013 auto writable = As<bool>(obj.CallMethod("writable"));1014 if (!writable)1015 return writable.takeError();1016 if (readable.get() && writable.get())1017 options |= File::eOpenOptionReadWrite;1018 else if (writable.get())1019 options |= File::eOpenOptionWriteOnly;1020 else if (readable.get())1021 options |= File::eOpenOptionReadOnly;1022 return options;1023}1024 1025// Base class template for python files. All it knows how to do1026// is hold a reference to the python object and close or flush it1027// when the File is closed.1028namespace {1029template <typename Base> class OwnedPythonFile : public Base {1030public:1031 template <typename... Args>1032 OwnedPythonFile(const PythonFile &file, bool borrowed, Args... args)1033 : Base(args...), m_py_obj(file), m_borrowed(borrowed) {1034 assert(m_py_obj);1035 }1036 1037 ~OwnedPythonFile() override {1038 assert(m_py_obj);1039 GIL takeGIL;1040 Close();1041 // we need to ensure the python object is released while we still1042 // hold the GIL1043 m_py_obj.Reset();1044 }1045 1046 bool IsPythonSideValid() const {1047 GIL takeGIL;1048 auto closed = As<bool>(m_py_obj.GetAttribute("closed"));1049 if (!closed) {1050 llvm::consumeError(closed.takeError());1051 return false;1052 }1053 return !closed.get();1054 }1055 1056 bool IsValid() const override {1057 return IsPythonSideValid() && Base::IsValid();1058 }1059 1060 Status Close() override {1061 assert(m_py_obj);1062 Status py_error, base_error;1063 GIL takeGIL;1064 if (!m_borrowed) {1065 auto r = m_py_obj.CallMethod("close");1066 if (!r)1067 py_error = Status::FromError(r.takeError());1068 }1069 base_error = Base::Close();1070 // Cloning since the wrapped exception may still reference the PyThread.1071 if (py_error.Fail())1072 return py_error.Clone();1073 return base_error.Clone();1074 };1075 1076 PyObject *GetPythonObject() const {1077 assert(m_py_obj.IsValid());1078 return m_py_obj.get();1079 }1080 1081 static bool classof(const File *file) = delete;1082 1083protected:1084 PythonFile m_py_obj;1085 bool m_borrowed;1086};1087} // namespace1088 1089// A SimplePythonFile is a OwnedPythonFile that just does all I/O as1090// a NativeFile1091namespace {1092class SimplePythonFile : public OwnedPythonFile<NativeFile> {1093public:1094 SimplePythonFile(const PythonFile &file, bool borrowed, int fd,1095 File::OpenOptions options)1096 : OwnedPythonFile(file, borrowed, fd, options, false) {}1097 1098 static char ID;1099 bool isA(const void *classID) const override {1100 return classID == &ID || NativeFile::isA(classID);1101 }1102 static bool classof(const File *file) { return file->isA(&ID); }1103};1104char SimplePythonFile::ID = 0;1105} // namespace1106 1107// Shared methods between TextPythonFile and BinaryPythonFile1108namespace {1109class PythonIOFile : public OwnedPythonFile<File> {1110public:1111 PythonIOFile(const PythonFile &file, bool borrowed)1112 : OwnedPythonFile(file, borrowed) {}1113 1114 ~PythonIOFile() override { Close(); }1115 1116 bool IsValid() const override { return IsPythonSideValid(); }1117 1118 Status Close() override {1119 assert(m_py_obj);1120 GIL takeGIL;1121 if (m_borrowed)1122 return Flush();1123 auto r = m_py_obj.CallMethod("close");1124 if (!r)1125 // Cloning since the wrapped exception may still reference the PyThread.1126 return Status::FromError(r.takeError()).Clone();1127 return Status();1128 }1129 1130 Status Flush() override {1131 GIL takeGIL;1132 auto r = m_py_obj.CallMethod("flush");1133 if (!r)1134 // Cloning since the wrapped exception may still reference the PyThread.1135 return Status::FromError(r.takeError()).Clone();1136 return Status();1137 }1138 1139 Expected<File::OpenOptions> GetOptions() const override {1140 GIL takeGIL;1141 return GetOptionsForPyObject(m_py_obj);1142 }1143 1144 static char ID;1145 bool isA(const void *classID) const override {1146 return classID == &ID || File::isA(classID);1147 }1148 static bool classof(const File *file) { return file->isA(&ID); }1149};1150char PythonIOFile::ID = 0;1151} // namespace1152 1153namespace {1154class BinaryPythonFile : public PythonIOFile {1155protected:1156 int m_descriptor;1157 1158public:1159 BinaryPythonFile(int fd, const PythonFile &file, bool borrowed)1160 : PythonIOFile(file, borrowed),1161 m_descriptor(File::DescriptorIsValid(fd) ? fd1162 : File::kInvalidDescriptor) {}1163 1164 int GetDescriptor() const override { return m_descriptor; }1165 1166 Status Write(const void *buf, size_t &num_bytes) override {1167 GIL takeGIL;1168 PyObject *pybuffer_p = PyMemoryView_FromMemory(1169 const_cast<char *>((const char *)buf), num_bytes, PyBUF_READ);1170 if (!pybuffer_p)1171 // Cloning since the wrapped exception may still reference the PyThread.1172 return Status::FromError(llvm::make_error<PythonException>()).Clone();1173 auto pybuffer = Take<PythonObject>(pybuffer_p);1174 num_bytes = 0;1175 auto bytes_written = As<long long>(m_py_obj.CallMethod("write", pybuffer));1176 if (!bytes_written)1177 return Status::FromError(bytes_written.takeError());1178 if (bytes_written.get() < 0)1179 return Status::FromErrorString(1180 ".write() method returned a negative number!");1181 static_assert(sizeof(long long) >= sizeof(size_t), "overflow");1182 num_bytes = bytes_written.get();1183 return Status();1184 }1185 1186 Status Read(void *buf, size_t &num_bytes) override {1187 GIL takeGIL;1188 static_assert(sizeof(long long) >= sizeof(size_t), "overflow");1189 auto pybuffer_obj =1190 m_py_obj.CallMethod("read", (unsigned long long)num_bytes);1191 if (!pybuffer_obj)1192 // Cloning since the wrapped exception may still reference the PyThread.1193 return Status::FromError(pybuffer_obj.takeError()).Clone();1194 num_bytes = 0;1195 if (pybuffer_obj.get().IsNone()) {1196 // EOF1197 num_bytes = 0;1198 return Status();1199 }1200 PythonBytes pybytes(PyRefType::Borrowed, pybuffer_obj->get());1201 if (!pybytes)1202 return Status::FromError(llvm::make_error<PythonException>());1203 llvm::ArrayRef<uint8_t> bytes = pybytes.GetBytes();1204 memcpy(buf, bytes.begin(), bytes.size());1205 num_bytes = bytes.size();1206 return Status();1207 }1208};1209} // namespace1210 1211namespace {1212class TextPythonFile : public PythonIOFile {1213protected:1214 int m_descriptor;1215 1216public:1217 TextPythonFile(int fd, const PythonFile &file, bool borrowed)1218 : PythonIOFile(file, borrowed),1219 m_descriptor(File::DescriptorIsValid(fd) ? fd1220 : File::kInvalidDescriptor) {}1221 1222 int GetDescriptor() const override { return m_descriptor; }1223 1224 Status Write(const void *buf, size_t &num_bytes) override {1225 GIL takeGIL;1226 auto pystring =1227 PythonString::FromUTF8(llvm::StringRef((const char *)buf, num_bytes));1228 if (!pystring)1229 return Status::FromError(pystring.takeError());1230 num_bytes = 0;1231 auto bytes_written =1232 As<long long>(m_py_obj.CallMethod("write", pystring.get()));1233 if (!bytes_written)1234 // Cloning since the wrapped exception may still reference the PyThread.1235 return Status::FromError(bytes_written.takeError()).Clone();1236 if (bytes_written.get() < 0)1237 return Status::FromErrorString(1238 ".write() method returned a negative number!");1239 static_assert(sizeof(long long) >= sizeof(size_t), "overflow");1240 num_bytes = bytes_written.get();1241 return Status();1242 }1243 1244 Status Read(void *buf, size_t &num_bytes) override {1245 GIL takeGIL;1246 size_t num_chars = num_bytes / 6;1247 size_t orig_num_bytes = num_bytes;1248 num_bytes = 0;1249 if (orig_num_bytes < 6) {1250 return Status::FromErrorString(1251 "can't read less than 6 bytes from a utf8 text stream");1252 }1253 auto pystring = As<PythonString>(1254 m_py_obj.CallMethod("read", (unsigned long long)num_chars));1255 if (!pystring)1256 // Cloning since the wrapped exception may still reference the PyThread.1257 return Status::FromError(pystring.takeError()).Clone();1258 if (pystring.get().IsNone()) {1259 // EOF1260 return Status();1261 }1262 auto stringref = pystring.get().AsUTF8();1263 if (!stringref)1264 // Cloning since the wrapped exception may still reference the PyThread.1265 return Status::FromError(stringref.takeError()).Clone();1266 num_bytes = stringref.get().size();1267 memcpy(buf, stringref.get().begin(), num_bytes);1268 return Status();1269 }1270};1271} // namespace1272 1273llvm::Expected<FileSP> PythonFile::ConvertToFile(bool borrowed) {1274 if (!IsValid())1275 return llvm::createStringError(llvm::inconvertibleErrorCode(),1276 "invalid PythonFile");1277 1278 int fd = PyObject_AsFileDescriptor(m_py_obj);1279 if (fd < 0) {1280 PyErr_Clear();1281 return ConvertToFileForcingUseOfScriptingIOMethods(borrowed);1282 }1283 auto options = GetOptionsForPyObject(*this);1284 if (!options)1285 return options.takeError();1286 1287 File::OpenOptions rw =1288 options.get() & (File::eOpenOptionReadOnly | File::eOpenOptionWriteOnly |1289 File::eOpenOptionReadWrite);1290 if (rw == File::eOpenOptionWriteOnly || rw == File::eOpenOptionReadWrite) {1291 // LLDB and python will not share I/O buffers. We should probably1292 // flush the python buffers now.1293 auto r = CallMethod("flush");1294 if (!r)1295 return r.takeError();1296 }1297 1298 FileSP file_sp;1299 if (borrowed) {1300 // In this case we don't need to retain the python1301 // object at all.1302 file_sp = std::make_shared<NativeFile>(fd, options.get(), false);1303 } else {1304 file_sp = std::static_pointer_cast<File>(1305 std::make_shared<SimplePythonFile>(*this, borrowed, fd, options.get()));1306 }1307 if (!file_sp->IsValid())1308 return llvm::createStringError(llvm::inconvertibleErrorCode(),1309 "invalid File");1310 1311 return file_sp;1312}1313 1314llvm::Expected<FileSP>1315PythonFile::ConvertToFileForcingUseOfScriptingIOMethods(bool borrowed) {1316 1317 assert(!PyErr_Occurred());1318 1319 if (!IsValid())1320 return llvm::createStringError(llvm::inconvertibleErrorCode(),1321 "invalid PythonFile");1322 1323 int fd = PyObject_AsFileDescriptor(m_py_obj);1324 if (fd < 0) {1325 PyErr_Clear();1326 fd = File::kInvalidDescriptor;1327 }1328 1329 auto io_module = PythonModule::Import("io");1330 if (!io_module)1331 return io_module.takeError();1332 auto textIOBase = io_module.get().Get("TextIOBase");1333 if (!textIOBase)1334 return textIOBase.takeError();1335 auto rawIOBase = io_module.get().Get("RawIOBase");1336 if (!rawIOBase)1337 return rawIOBase.takeError();1338 auto bufferedIOBase = io_module.get().Get("BufferedIOBase");1339 if (!bufferedIOBase)1340 return bufferedIOBase.takeError();1341 1342 FileSP file_sp;1343 1344 auto isTextIO = IsInstance(textIOBase.get());1345 if (!isTextIO)1346 return isTextIO.takeError();1347 if (isTextIO.get())1348 file_sp = std::static_pointer_cast<File>(1349 std::make_shared<TextPythonFile>(fd, *this, borrowed));1350 1351 auto isRawIO = IsInstance(rawIOBase.get());1352 if (!isRawIO)1353 return isRawIO.takeError();1354 auto isBufferedIO = IsInstance(bufferedIOBase.get());1355 if (!isBufferedIO)1356 return isBufferedIO.takeError();1357 1358 if (isRawIO.get() || isBufferedIO.get()) {1359 file_sp = std::static_pointer_cast<File>(1360 std::make_shared<BinaryPythonFile>(fd, *this, borrowed));1361 }1362 1363 if (!file_sp)1364 return llvm::createStringError(llvm::inconvertibleErrorCode(),1365 "python file is neither text nor binary");1366 1367 if (!file_sp->IsValid())1368 return llvm::createStringError(llvm::inconvertibleErrorCode(),1369 "invalid File");1370 1371 return file_sp;1372}1373 1374Expected<PythonFile> PythonFile::FromFile(File &file, const char *mode) {1375 if (!file.IsValid())1376 return llvm::createStringError(llvm::inconvertibleErrorCode(),1377 "invalid file");1378 1379 if (auto *simple = llvm::dyn_cast<SimplePythonFile>(&file))1380 return Retain<PythonFile>(simple->GetPythonObject());1381 if (auto *pythonio = llvm::dyn_cast<PythonIOFile>(&file))1382 return Retain<PythonFile>(pythonio->GetPythonObject());1383 1384 if (!mode) {1385 auto m = file.GetOpenMode();1386 if (!m)1387 return m.takeError();1388 mode = m.get();1389 }1390 1391 PyObject *file_obj;1392 file_obj = PyFile_FromFd(file.GetDescriptor(), nullptr, mode, -1, nullptr,1393 "ignore", nullptr, /*closefd=*/0);1394 1395 if (!file_obj)1396 return exception();1397 1398 return Take<PythonFile>(file_obj);1399}1400 1401Error PythonScript::Init() {1402 if (function.IsValid())1403 return Error::success();1404 1405 PythonDictionary globals(PyInitialValue::Empty);1406 auto builtins = PythonModule::BuiltinsModule();1407 if (Error error = globals.SetItem("__builtins__", builtins))1408 return error;1409 PyObject *o = RunString(script, Py_file_input, globals.get(), globals.get());1410 if (!o)1411 return exception();1412 Take<PythonObject>(o);1413 auto f = As<PythonCallable>(globals.GetItem("main"));1414 if (!f)1415 return f.takeError();1416 function = std::move(f.get());1417 1418 return Error::success();1419}1420 1421llvm::Expected<PythonObject>1422python::runStringOneLine(const llvm::Twine &string,1423 const PythonDictionary &globals,1424 const PythonDictionary &locals) {1425 if (!globals.IsValid() || !locals.IsValid())1426 return nullDeref();1427 1428 PyObject *code =1429 Py_CompileString(NullTerminated(string), "<string>", Py_eval_input);1430 if (!code) {1431 PyErr_Clear();1432 code =1433 Py_CompileString(NullTerminated(string), "<string>", Py_single_input);1434 }1435 if (!code)1436 return exception();1437 auto code_ref = Take<PythonObject>(code);1438 1439 PyObject *result = PyEval_EvalCode(code, globals.get(), locals.get());1440 1441 if (!result)1442 return exception();1443 1444 return Take<PythonObject>(result);1445}1446 1447llvm::Expected<PythonObject>1448python::runStringMultiLine(const llvm::Twine &string,1449 const PythonDictionary &globals,1450 const PythonDictionary &locals) {1451 if (!globals.IsValid() || !locals.IsValid())1452 return nullDeref();1453 PyObject *result = RunString(NullTerminated(string), Py_file_input,1454 globals.get(), locals.get());1455 if (!result)1456 return exception();1457 return Take<PythonObject>(result);1458}1459 1460PyObject *lldb_private::python::RunString(const char *str, int start,1461 PyObject *globals, PyObject *locals) {1462 const char *filename = "<string>";1463 1464 // Compile the string into a code object.1465 PyObject *code = Py_CompileString(str, filename, start);1466 if (!code)1467 return nullptr;1468 1469 // Execute the code object.1470 PyObject *result = PyEval_EvalCode(code, globals, locals);1471 1472 // Clean up the code object.1473 Py_DECREF(code);1474 1475 return result;1476}1477 1478int lldb_private::python::RunSimpleString(const char *str) {1479 PyObject *main_module = PyImport_AddModule("__main__");1480 if (!main_module)1481 return -1;1482 1483 PyObject *globals = PyModule_GetDict(main_module);1484 if (!globals)1485 return -1;1486 1487 PyObject *result = RunString(str, Py_file_input, globals, globals);1488 if (!result)1489 return -1;1490 1491 return 0;1492}1493#endif1494