static PyObject * method_repr(PyMethodObject *a) { PyObject *self = a->im_self; PyObject *func = a->im_func; PyObject *funcname = NULL, *result = NULL; const char *defname = "?"; funcname = _PyObject_GetAttrId(func, &PyId___qualname__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } } if (funcname != NULL && !PyUnicode_Check(funcname)) { Py_DECREF(funcname); funcname = NULL; } /* XXX Shouldn't use repr()/%R here! */ result = PyUnicode_FromFormat("<bound method %V of %R>", funcname, defname, self); Py_XDECREF(funcname); return result; }
static PyObject * method_repr(PyMethodObject *a) { PyObject *self = a->im_self; PyObject *func = a->im_func; PyObject *klass; PyObject *funcname = NULL ,*klassname = NULL, *result = NULL; char *defname = "?"; if (self == NULL) { PyErr_BadInternalCall(); return NULL; } klass = (PyObject*)Py_TYPE(self); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } else if (!PyUnicode_Check(funcname)) { Py_DECREF(funcname); funcname = NULL; } if (klass == NULL) klassname = NULL; else { klassname = _PyObject_GetAttrId(klass, &PyId___name__); if (klassname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { Py_XDECREF(funcname); return NULL; } PyErr_Clear(); } else if (!PyUnicode_Check(klassname)) { Py_DECREF(klassname); klassname = NULL; } } /* XXX Shouldn't use repr()/%R here! */ result = PyUnicode_FromFormat("<bound method %V.%V of %R>", klassname, defname, funcname, defname, self); Py_XDECREF(funcname); Py_XDECREF(klassname); return result; }
static void wrong_exception_type(PyObject *exc) { _Py_IDENTIFIER(__class__); _Py_IDENTIFIER(__name__); PyObject *type = _PyObject_GetAttrId(exc, &PyId___class__); if (type != NULL) { PyObject *name = _PyObject_GetAttrId(type, &PyId___name__); Py_DECREF(type); if (name != NULL) { PyErr_Format(PyExc_TypeError, "don't know how to handle %S in error callback", name); Py_DECREF(name); } } }
static char* get_codec_name(const char *encoding) { char *name_utf8, *name_str; PyObject *codec, *name = NULL; codec = _PyCodec_Lookup(encoding); if (!codec) goto error; name = _PyObject_GetAttrId(codec, &PyId_name); Py_CLEAR(codec); if (!name) goto error; name_utf8 = _PyUnicode_AsString(name); if (name_utf8 == NULL) goto error; name_str = _PyMem_RawStrdup(name_utf8); Py_DECREF(name); if (name_str == NULL) { PyErr_NoMemory(); return NULL; } return name_str; error: Py_XDECREF(codec); Py_XDECREF(name); return NULL; }
static PyObject * weakref_repr(PyWeakReference *self) { PyObject *name, *repr; _Py_IDENTIFIER(__name__); if (PyWeakref_GET_OBJECT(self) == Py_None) return PyUnicode_FromFormat("<weakref at %p; dead>", self); name = _PyObject_GetAttrId(PyWeakref_GET_OBJECT(self), &PyId___name__); if (name == NULL || !PyUnicode_Check(name)) { if (name == NULL) PyErr_Clear(); repr = PyUnicode_FromFormat( "<weakref at %p; to '%s' at %p>", self, Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, PyWeakref_GET_OBJECT(self)); } else { repr = PyUnicode_FromFormat( "<weakref at %p; to '%s' at %p (%U)>", self, Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, PyWeakref_GET_OBJECT(self), name); } Py_XDECREF(name); return repr; }
int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { PyObject *writer, *value, *result; _Py_IDENTIFIER(write); if (f == NULL) { PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); return -1; } writer = _PyObject_GetAttrId(f, &PyId_write); if (writer == NULL) return -1; if (flags & Py_PRINT_RAW) { value = PyObject_Str(v); } else value = PyObject_Repr(v); if (value == NULL) { Py_DECREF(writer); return -1; } result = PyObject_CallFunctionObjArgs(writer, value, NULL); Py_DECREF(value); Py_DECREF(writer); if (result == NULL) return -1; Py_DECREF(result); return 0; }
static int gen_close_iter(PyObject *yf) { PyObject *retval = NULL; _Py_IDENTIFIER(close); if (PyGen_CheckExact(yf)) { retval = gen_close((PyGenObject *)yf, NULL); if (retval == NULL) return -1; } else { PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close); if (meth == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_WriteUnraisable(yf); PyErr_Clear(); } else { retval = PyObject_CallFunction(meth, ""); Py_DECREF(meth); if (retval == NULL) return -1; } } Py_XDECREF(retval); return 0; }
static PyObject * instancemethod_repr(PyObject *self) { PyObject *func = PyInstanceMethod_Function(self); PyObject *funcname = NULL , *result = NULL; char *defname = "?"; if (func == NULL) { PyErr_BadInternalCall(); return NULL; } funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } else if (!PyUnicode_Check(funcname)) { Py_DECREF(funcname); funcname = NULL; } result = PyUnicode_FromFormat("<instancemethod %V at %p>", funcname, defname, self); Py_XDECREF(funcname); return result; }
static PyObject * meth_get__qualname__(PyCFunctionObject *m, void *closure) { /* If __self__ is a module or NULL, return m.__name__ (e.g. len.__qualname__ == 'len') If __self__ is a type, return m.__self__.__qualname__ + '.' + m.__name__ (e.g. dict.fromkeys.__qualname__ == 'dict.fromkeys') Otherwise return type(m.__self__).__qualname__ + '.' + m.__name__ (e.g. [].append.__qualname__ == 'list.append') */ PyObject *type, *type_qualname, *res; _Py_IDENTIFIER(__qualname__); if (m->m_self == NULL || PyModule_Check(m->m_self)) return PyUnicode_FromString(m->m_ml->ml_name); type = PyType_Check(m->m_self) ? m->m_self : (PyObject*)Py_TYPE(m->m_self); type_qualname = _PyObject_GetAttrId(type, &PyId___qualname__); if (type_qualname == NULL) return NULL; if (!PyUnicode_Check(type_qualname)) { PyErr_SetString(PyExc_TypeError, "<method>.__class__." "__qualname__ is not a unicode object"); Py_XDECREF(type_qualname); return NULL; } res = PyUnicode_FromFormat("%S.%s", type_qualname, m->m_ml->ml_name); Py_DECREF(type_qualname); return res; }
/* Return the zlib.decompress function object, or NULL if zlib couldn't be imported. The function is cached when found, so subsequent calls don't import zlib again. */ static PyObject * get_decompress_func(void) { static int importing_zlib = 0; PyObject *zlib; PyObject *decompress; _Py_IDENTIFIER(decompress); if (importing_zlib != 0) /* Someone has a zlib.py[co] in their Zip file; let's avoid a stack overflow. */ return NULL; importing_zlib = 1; zlib = PyImport_ImportModuleNoBlock("zlib"); importing_zlib = 0; if (zlib != NULL) { decompress = _PyObject_GetAttrId(zlib, &PyId_decompress); Py_DECREF(zlib); } else { PyErr_Clear(); decompress = NULL; } if (Py_VerboseFlag) PySys_WriteStderr("# zipimport: zlib %s\n", zlib != NULL ? "available": "UNAVAILABLE"); return decompress; }
static void handle_system_exit(void) { PyObject *exception, *value, *tb; int exitcode = 0; if (Py_InspectFlag) /* Don't exit if -i flag was given. This flag is set to 0 * when entering interactive mode for inspecting. */ return; PyErr_Fetch(&exception, &value, &tb); fflush(stdout); if (value == NULL || value == Py_None) goto done; if (PyExceptionInstance_Check(value)) { /* The error code should be in the `code' attribute. */ _Py_IDENTIFIER(code); PyObject *code = _PyObject_GetAttrId(value, &PyId_code); if (code) { Py_DECREF(value); value = code; if (value == Py_None) goto done; } /* If we failed to dig out the 'code' attribute, just let the else clause below print the error. */ } if (PyLong_Check(value)) exitcode = (int)PyLong_AsLong(value); else { PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr); /* We clear the exception here to avoid triggering the assertion * in PyObject_Str that ensures it won't silently lose exception * details. */ PyErr_Clear(); if (sys_stderr != NULL && sys_stderr != Py_None) { PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW); } else { PyObject_Print(value, stderr, Py_PRINT_RAW); fflush(stderr); } PySys_WriteStderr("\n"); exitcode = 1; } done: /* Restore and clear the exception info, in order to properly decref * the exception, value, and traceback. If we just exit instead, * these leak, which confuses PYTHONDUMPREFS output, and may prevent * some finalizers from running. */ PyErr_Restore(exception, value, tb); PyErr_Clear(); Py_Exit(exitcode); /* NOTREACHED */ }
static PyObject * method_reduce(PyMethodObject *im) { PyObject *self = PyMethod_GET_SELF(im); PyObject *func = PyMethod_GET_FUNCTION(im); PyObject *funcname; _Py_IDENTIFIER(getattr); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { return NULL; } return Py_BuildValue("N(ON)", _PyEval_GetBuiltinId(&PyId_getattr), self, funcname); }
/* Text encoding/decoding API */ static PyObject *codec_getitem_checked(const char *encoding, const char *operation_name, int index) { _Py_IDENTIFIER(_is_text_encoding); PyObject *codec; PyObject *attr; PyObject *v; int is_text_codec; codec = _PyCodec_Lookup(encoding); if (codec == NULL) return NULL; /* Backwards compatibility: assume any raw tuple describes a text * encoding, and the same for anything lacking the private * attribute. */ if (!PyTuple_CheckExact(codec)) { attr = _PyObject_GetAttrId(codec, &PyId__is_text_encoding); if (attr == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { Py_DECREF(codec); return NULL; } } else { is_text_codec = PyObject_IsTrue(attr); Py_DECREF(attr); if (!is_text_codec) { Py_DECREF(codec); PyErr_Format(PyExc_LookupError, "'%.400s' is not a text encoding; " "use codecs.%s() to handle arbitrary codecs", encoding, operation_name); return NULL; } } } v = PyTuple_GET_ITEM(codec, index); Py_DECREF(codec); Py_INCREF(v); return v; }
static int fp_setreadl(struct tok_state *tok, const char* enc) { PyObject *readline = NULL, *stream = NULL, *io = NULL; _Py_IDENTIFIER(open); _Py_IDENTIFIER(readline); int fd; long pos; io = PyImport_ImportModuleNoBlock("io"); if (io == NULL) goto cleanup; fd = fileno(tok->fp); /* Due to buffering the file offset for fd can be different from the file * position of tok->fp. If tok->fp was opened in text mode on Windows, * its file position counts CRLF as one char and can't be directly mapped * to the file offset for fd. Instead we step back one byte and read to * the end of line.*/ pos = ftell(tok->fp); if (pos == -1 || lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL); goto cleanup; } stream = _PyObject_CallMethodId(io, &PyId_open, "isisOOO", fd, "r", -1, enc, Py_None, Py_None, Py_False); if (stream == NULL) goto cleanup; Py_XDECREF(tok->decoding_readline); readline = _PyObject_GetAttrId(stream, &PyId_readline); tok->decoding_readline = readline; if (pos > 0) { if (PyObject_CallObject(readline, NULL) == NULL) { readline = NULL; goto cleanup; } } cleanup: Py_XDECREF(stream); Py_XDECREF(io); return readline != NULL; }
static PyObject * method_reduce(PyMethodObject *im) { PyObject *self = PyMethod_GET_SELF(im); PyObject *func = PyMethod_GET_FUNCTION(im); PyObject *builtins; PyObject *getattr; PyObject *funcname; _Py_IDENTIFIER(getattr); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { return NULL; } builtins = PyEval_GetBuiltins(); getattr = _PyDict_GetItemId(builtins, &PyId_getattr); return Py_BuildValue("O(ON)", getattr, self, funcname); }
int PyObject_AsFileDescriptor(PyObject *o) { int fd; PyObject *meth; _Py_IDENTIFIER(fileno); if (PyLong_Check(o)) { fd = _PyLong_AsInt(o); } else if ((meth = _PyObject_GetAttrId(o, &PyId_fileno)) != NULL) { PyObject *fno = PyEval_CallObject(meth, NULL); Py_DECREF(meth); if (fno == NULL) return -1; if (PyLong_Check(fno)) { fd = _PyLong_AsInt(fno); Py_DECREF(fno); } else { PyErr_SetString(PyExc_TypeError, "fileno() returned a non-integer"); Py_DECREF(fno); return -1; } } else { PyErr_SetString(PyExc_TypeError, "argument must be an int, or have a fileno() method."); return -1; } if (fd == -1 && PyErr_Occurred()) return -1; if (fd < 0) { PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", fd); return -1; } return fd; }
/* Text encoding/decoding API */ PyObject * _PyCodec_LookupTextEncoding(const char *encoding, const char *alternate_command) { _Py_IDENTIFIER(_is_text_encoding); PyObject *codec; PyObject *attr; int is_text_codec; codec = _PyCodec_Lookup(encoding); if (codec == NULL) return NULL; /* Backwards compatibility: assume any raw tuple describes a text * encoding, and the same for anything lacking the private * attribute. */ if (!PyTuple_CheckExact(codec)) { attr = _PyObject_GetAttrId(codec, &PyId__is_text_encoding); if (attr == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { Py_DECREF(codec); return NULL; } } else { is_text_codec = PyObject_IsTrue(attr); Py_DECREF(attr); if (is_text_codec <= 0) { Py_DECREF(codec); if (!is_text_codec) PyErr_Format(PyExc_LookupError, "'%.400s' is not a text encoding; " "use %s to handle arbitrary codecs", encoding, alternate_command); return NULL; } } } /* This appears to be a valid text encoding */ return codec; }
static PyObject * time_strptime(PyObject *self, PyObject *args) { PyObject *module, *func, *result; _Py_IDENTIFIER(_strptime_time); module = PyImport_ImportModuleNoBlock("_strptime"); if (!module) return NULL; func = _PyObject_GetAttrId(module, &PyId__strptime_time); Py_DECREF(module); if (!func) { return NULL; } result = PyObject_Call(func, args, NULL); Py_DECREF(func); return result; }
static PyObject * module_dir(PyObject *self, PyObject *args) { _Py_IDENTIFIER(__dict__); PyObject *result = NULL; PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict != NULL) { if (PyDict_Check(dict)) result = PyDict_Keys(dict); else { const char *name = PyModule_GetName(self); if (name) PyErr_Format(PyExc_TypeError, "%.200s.__dict__ is not a dictionary", name); } } Py_XDECREF(dict); return result; }
/* Returns a new reference. A NULL return value can mean false or an error. */ static PyObject * get_warnings_attr(_Py_Identifier *attr_id, int try_import) { PyObject *warnings_str; PyObject *warnings_module, *obj; _Py_IDENTIFIER(warnings); warnings_str = _PyUnicode_FromId(&PyId_warnings); if (warnings_str == NULL) { return NULL; } /* don't try to import after the start of the Python finallization */ if (try_import && !_Py_IsFinalizing()) { warnings_module = PyImport_Import(warnings_str); if (warnings_module == NULL) { /* Fallback to the C implementation if we cannot get the Python implementation */ if (PyErr_ExceptionMatches(PyExc_ImportError)) { PyErr_Clear(); } return NULL; } } else { warnings_module = PyImport_GetModule(warnings_str); if (warnings_module == NULL) return NULL; } obj = _PyObject_GetAttrId(warnings_module, attr_id); Py_DECREF(warnings_module); if (obj == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return obj; }
static PyObject * csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args) { PyObject * output_file, * dialect = NULL; WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type); _Py_IDENTIFIER(write); if (!self) return NULL; self->dialect = NULL; self->writeline = NULL; self->rec = NULL; self->rec_size = 0; self->rec_len = 0; self->num_fields = 0; if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) { Py_DECREF(self); return NULL; } self->writeline = _PyObject_GetAttrId(output_file, &PyId_write); if (self->writeline == NULL || !PyCallable_Check(self->writeline)) { PyErr_SetString(PyExc_TypeError, "argument 1 must have a \"write\" method"); Py_DECREF(self); return NULL; } self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args); if (self->dialect == NULL) { Py_DECREF(self); return NULL; } PyObject_GC_Track(self); return (PyObject *)self; }
static PyObject * get_source_line(PyObject *module_globals, int lineno) { _Py_IDENTIFIER(get_source); _Py_IDENTIFIER(__loader__); _Py_IDENTIFIER(__name__); PyObject *loader; PyObject *module_name; PyObject *get_source; PyObject *source; PyObject *source_list; PyObject *source_line; /* Check/get the requisite pieces needed for the loader. */ loader = _PyDict_GetItemIdWithError(module_globals, &PyId___loader__); if (loader == NULL) { return NULL; } Py_INCREF(loader); module_name = _PyDict_GetItemIdWithError(module_globals, &PyId___name__); if (!module_name) { Py_DECREF(loader); return NULL; } Py_INCREF(module_name); /* Make sure the loader implements the optional get_source() method. */ get_source = _PyObject_GetAttrId(loader, &PyId_get_source); Py_DECREF(loader); if (!get_source) { Py_DECREF(module_name); if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } return NULL; } /* Call get_source() to get the source code. */ source = PyObject_CallFunctionObjArgs(get_source, module_name, NULL); Py_DECREF(get_source); Py_DECREF(module_name); if (!source) { return NULL; } if (source == Py_None) { Py_DECREF(source); return NULL; } /* Split the source into lines. */ source_list = PyUnicode_Splitlines(source, 0); Py_DECREF(source); if (!source_list) { return NULL; } /* Get the source line. */ source_line = PyList_GetItem(source_list, lineno-1); Py_XINCREF(source_line); Py_DECREF(source_list); return source_line; }
static void show_warning(PyObject *filename, int lineno, PyObject *text, PyObject *category, PyObject *sourceline) { PyObject *f_stderr; PyObject *name; char lineno_str[128]; _Py_IDENTIFIER(__name__); PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); name = _PyObject_GetAttrId(category, &PyId___name__); if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */ goto error; f_stderr = _PySys_GetObjectId(&PyId_stderr); if (f_stderr == NULL) { fprintf(stderr, "lost sys.stderr\n"); goto error; } /* Print "filename:lineno: category: text\n" */ if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0) goto error; if (PyFile_WriteString(lineno_str, f_stderr) < 0) goto error; if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0) goto error; if (PyFile_WriteString(": ", f_stderr) < 0) goto error; if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0) goto error; if (PyFile_WriteString("\n", f_stderr) < 0) goto error; Py_CLEAR(name); /* Print " source_line\n" */ if (sourceline) { int kind; void *data; Py_ssize_t i, len; Py_UCS4 ch; PyObject *truncated; if (PyUnicode_READY(sourceline) < 1) goto error; kind = PyUnicode_KIND(sourceline); data = PyUnicode_DATA(sourceline); len = PyUnicode_GET_LENGTH(sourceline); for (i=0; i<len; i++) { ch = PyUnicode_READ(kind, data, i); if (ch != ' ' && ch != '\t' && ch != '\014') break; } truncated = PyUnicode_Substring(sourceline, i, len); if (truncated == NULL) goto error; PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW); Py_DECREF(truncated); PyFile_WriteString("\n", f_stderr); } else { _Py_DisplaySourceLine(f_stderr, filename, lineno, 2); } error: Py_XDECREF(name); PyErr_Clear(); }
/* Call when an exception has occurred but there is no way for Python to handle it. Examples: exception in __del__ or during GC. */ void PyErr_WriteUnraisable(PyObject *obj) { _Py_IDENTIFIER(__module__); PyObject *f, *t, *v, *tb; PyObject *moduleName = NULL; char* className; PyErr_Fetch(&t, &v, &tb); f = _PySys_GetObjectId(&PyId_stderr); if (f == NULL || f == Py_None) goto done; if (obj) { if (PyFile_WriteString("Exception ignored in: ", f) < 0) goto done; if (PyFile_WriteObject(obj, f, 0) < 0) { PyErr_Clear(); if (PyFile_WriteString("<object repr() failed>", f) < 0) { goto done; } } if (PyFile_WriteString("\n", f) < 0) goto done; } if (PyTraceBack_Print(tb, f) < 0) goto done; if (!t) goto done; assert(PyExceptionClass_Check(t)); className = PyExceptionClass_Name(t); if (className != NULL) { char *dot = strrchr(className, '.'); if (dot != NULL) className = dot+1; } moduleName = _PyObject_GetAttrId(t, &PyId___module__); if (moduleName == NULL) { PyErr_Clear(); if (PyFile_WriteString("<unknown>", f) < 0) goto done; } else { if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) { if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0) goto done; if (PyFile_WriteString(".", f) < 0) goto done; } } if (className == NULL) { if (PyFile_WriteString("<unknown>", f) < 0) goto done; } else { if (PyFile_WriteString(className, f) < 0) goto done; } if (v && v != Py_None) { if (PyFile_WriteString(": ", f) < 0) goto done; if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) { PyErr_Clear(); if (PyFile_WriteString("<exception str() failed>", f) < 0) { goto done; } } } if (PyFile_WriteString("\n", f) < 0) goto done; done: Py_XDECREF(moduleName); Py_XDECREF(t); Py_XDECREF(v); Py_XDECREF(tb); PyErr_Clear(); /* Just in case */ }
/* copied from pythonrun.c, 3.3.0 */ static int parse_syntax_error(PyObject *err, PyObject **message, const char **filename, int *lineno, int *offset, const char **text) { long hold; PyObject *v; _Py_IDENTIFIER(msg); _Py_IDENTIFIER(filename); _Py_IDENTIFIER(lineno); _Py_IDENTIFIER(offset); _Py_IDENTIFIER(text); *message = NULL; /* new style errors. `err' is an instance */ *message = _PyObject_GetAttrId(err, &PyId_msg); if (!*message) goto finally; v = _PyObject_GetAttrId(err, &PyId_filename); if (!v) goto finally; if (v == Py_None) { Py_DECREF(v); *filename = NULL; } else { *filename = _PyUnicode_AsString(v); Py_DECREF(v); if (!*filename) goto finally; } v = _PyObject_GetAttrId(err, &PyId_lineno); if (!v) goto finally; hold = PyLong_AsLong(v); Py_DECREF(v); if (hold < 0 && PyErr_Occurred()) goto finally; *lineno = (int)hold; v = _PyObject_GetAttrId(err, &PyId_offset); if (!v) goto finally; if (v == Py_None) { *offset = -1; Py_DECREF(v); } else { hold = PyLong_AsLong(v); Py_DECREF(v); if (hold < 0 && PyErr_Occurred()) goto finally; *offset = (int)hold; } v = _PyObject_GetAttrId(err, &PyId_text); if (!v) goto finally; if (v == Py_None) { Py_DECREF(v); *text = NULL; } else { *text = _PyUnicode_AsString(v); Py_DECREF(v); if (!*text) goto finally; } return 1; finally: Py_XDECREF(*message); return 0; }
PyObject * PyFile_GetLine(PyObject *f, int n) { PyObject *result; if (f == NULL) { PyErr_BadInternalCall(); return NULL; } { PyObject *reader; PyObject *args; _Py_IDENTIFIER(readline); reader = _PyObject_GetAttrId(f, &PyId_readline); if (reader == NULL) return NULL; if (n <= 0) args = PyTuple_New(0); else args = Py_BuildValue("(i)", n); if (args == NULL) { Py_DECREF(reader); return NULL; } result = PyEval_CallObject(reader, args); Py_DECREF(reader); Py_DECREF(args); if (result != NULL && !PyBytes_Check(result) && !PyUnicode_Check(result)) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_TypeError, "object.readline() returned non-string"); } } if (n < 0 && result != NULL && PyBytes_Check(result)) { char *s = PyBytes_AS_STRING(result); Py_ssize_t len = PyBytes_GET_SIZE(result); if (len == 0) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_EOFError, "EOF when reading a line"); } else if (s[len-1] == '\n') { if (result->ob_refcnt == 1) _PyBytes_Resize(&result, len-1); else { PyObject *v; v = PyBytes_FromStringAndSize(s, len-1); Py_DECREF(result); result = v; } } } if (n < 0 && result != NULL && PyUnicode_Check(result)) { Py_ssize_t len = PyUnicode_GET_LENGTH(result); if (len == 0) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_EOFError, "EOF when reading a line"); } else if (PyUnicode_READ_CHAR(result, len-1) == '\n') { PyObject *v; v = PyUnicode_Substring(result, 0, len-1); Py_DECREF(result); result = v; } } return result; }
static PyObject * gen_throw(PyGenObject *gen, PyObject *args) { PyObject *typ; PyObject *tb = NULL; PyObject *val = NULL; PyObject *yf = _PyGen_yf(gen); _Py_IDENTIFIER(throw); if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) return NULL; if (yf) { PyObject *ret; int err; if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) { gen->gi_running = 1; err = gen_close_iter(yf); gen->gi_running = 0; Py_DECREF(yf); if (err < 0) return gen_send_ex(gen, Py_None, 1, 0); goto throw_here; } if (PyGen_CheckExact(yf)) { gen->gi_running = 1; ret = gen_throw((PyGenObject *)yf, args); gen->gi_running = 0; } else { PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw); if (meth == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { Py_DECREF(yf); return NULL; } PyErr_Clear(); Py_DECREF(yf); goto throw_here; } gen->gi_running = 1; ret = PyObject_CallObject(meth, args); gen->gi_running = 0; Py_DECREF(meth); } Py_DECREF(yf); if (!ret) { PyObject *val; /* Pop subiterator from stack */ ret = *(--gen->gi_frame->f_stacktop); assert(ret == yf); Py_DECREF(ret); /* Termination repetition of YIELD_FROM */ gen->gi_frame->f_lasti += 2; if (_PyGen_FetchStopIterationValue(&val) == 0) { ret = gen_send_ex(gen, val, 0, 0); Py_DECREF(val); } else { ret = gen_send_ex(gen, Py_None, 1, 0); } } return ret; } throw_here: /* First, check the traceback argument, replacing None with NULL. */ if (tb == Py_None) { tb = NULL; } else if (tb != NULL && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "throw() third argument must be a traceback object"); return NULL; } Py_INCREF(typ); Py_XINCREF(val); Py_XINCREF(tb); if (PyExceptionClass_Check(typ)) PyErr_NormalizeException(&typ, &val, &tb); else if (PyExceptionInstance_Check(typ)) { /* Raising an instance. The value should be a dummy. */ if (val && val != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto failed_throw; } else { /* Normalize to raise <class>, <instance> */ Py_XDECREF(val); val = typ; typ = PyExceptionInstance_Class(typ); Py_INCREF(typ); if (tb == NULL) /* Returns NULL if there's no traceback */ tb = PyException_GetTraceback(val); } } else { /* Not something you can raise. throw() fails. */ PyErr_Format(PyExc_TypeError, "exceptions must be classes or instances " "deriving from BaseException, not %s", Py_TYPE(typ)->tp_name); goto failed_throw; } PyErr_Restore(typ, val, tb); return gen_send_ex(gen, Py_None, 1, 0); failed_throw: /* Didn't use our arguments, so restore their original refcounts */ Py_DECREF(typ); Py_XDECREF(val); Py_XDECREF(tb); return NULL; }
static void print_exception(PyObject *f, PyObject *value) { int err = 0; PyObject *type, *tb; _Py_IDENTIFIER(print_file_and_line); if (!PyExceptionInstance_Check(value)) { err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); err += PyFile_WriteString(Py_TYPE(value)->tp_name, f); err += PyFile_WriteString(" found\n", f); if (err) PyErr_Clear(); return; } Py_INCREF(value); fflush(stdout); type = (PyObject *) Py_TYPE(value); tb = PyException_GetTraceback(value); if (tb && tb != Py_None) err = PyTraceBack_Print(tb, f); if (err == 0 && _PyObject_HasAttrId(value, &PyId_print_file_and_line)) { PyObject *message, *filename, *text; int lineno, offset; if (!parse_syntax_error(value, &message, &filename, &lineno, &offset, &text)) PyErr_Clear(); else { PyObject *line; Py_DECREF(value); value = message; line = PyUnicode_FromFormat(" File \"%U\", line %d\n", filename, lineno); Py_DECREF(filename); if (line != NULL) { PyFile_WriteObject(line, f, Py_PRINT_RAW); Py_DECREF(line); } if (text != NULL) { print_error_text(f, offset, text); Py_DECREF(text); } /* Can't be bothered to check all those PyFile_WriteString() calls */ if (PyErr_Occurred()) err = -1; } } if (err) { /* Don't do anything else */ } else { PyObject* moduleName; const char *className; _Py_IDENTIFIER(__module__); assert(PyExceptionClass_Check(type)); className = PyExceptionClass_Name(type); if (className != NULL) { const char *dot = strrchr(className, '.'); if (dot != NULL) className = dot+1; } moduleName = _PyObject_GetAttrId(type, &PyId___module__); if (moduleName == NULL || !PyUnicode_Check(moduleName)) { Py_XDECREF(moduleName); err = PyFile_WriteString("<unknown>", f); } else { if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) { err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW); err += PyFile_WriteString(".", f); } Py_DECREF(moduleName); } if (err == 0) { if (className == NULL) err = PyFile_WriteString("<unknown>", f); else err = PyFile_WriteString(className, f); } } if (err == 0 && (value != Py_None)) { PyObject *s = PyObject_Str(value); /* only print colon if the str() of the object is not the empty string */ if (s == NULL) { PyErr_Clear(); err = -1; PyFile_WriteString(": <exception str() failed>", f); } else if (!PyUnicode_Check(s) || PyUnicode_GetLength(s) != 0) err = PyFile_WriteString(": ", f); if (err == 0) err = PyFile_WriteObject(s, f, Py_PRINT_RAW); Py_XDECREF(s); } /* try to write a newline in any case */ if (err < 0) { PyErr_Clear(); } err += PyFile_WriteString("\n", f); Py_XDECREF(tb); Py_DECREF(value); /* If an error happened here, don't show it. XXX This is wrong, but too many callers rely on this behavior. */ if (err != 0) PyErr_Clear(); }
/* returns Py_None if the fd is not valid */ static PyObject* create_stdio(PyObject* io, int fd, int write_mode, const char* name, const char* encoding, const char* errors) { PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; const char* mode; const char* newline; PyObject *line_buffering; int buffering, isatty; _Py_IDENTIFIER(open); _Py_IDENTIFIER(isatty); _Py_IDENTIFIER(TextIOWrapper); _Py_IDENTIFIER(mode); if (!is_valid_fd(fd)) Py_RETURN_NONE; /* stdin is always opened in buffered mode, first because it shouldn't make a difference in common use cases, second because TextIOWrapper depends on the presence of a read1() method which only exists on buffered streams. */ if (Py_UnbufferedStdioFlag && write_mode) buffering = 0; else buffering = -1; if (write_mode) mode = "wb"; else mode = "rb"; buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi", fd, mode, buffering, Py_None, Py_None, /* encoding, errors */ Py_None, 0); /* newline, closefd */ if (buf == NULL) goto error; if (buffering) { _Py_IDENTIFIER(raw); raw = _PyObject_GetAttrId(buf, &PyId_raw); if (raw == NULL) goto error; } else { raw = buf; Py_INCREF(raw); } text = PyUnicode_FromString(name); if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0) goto error; res = _PyObject_CallMethodId(raw, &PyId_isatty, ""); if (res == NULL) goto error; isatty = PyObject_IsTrue(res); Py_DECREF(res); if (isatty == -1) goto error; if (isatty || Py_UnbufferedStdioFlag) line_buffering = Py_True; else line_buffering = Py_False; Py_CLEAR(raw); Py_CLEAR(text); #ifdef MS_WINDOWS /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r" newlines to "\n". sys.stdout and sys.stderr: translate "\n" to "\r\n". */ newline = NULL; #else /* sys.stdin: split lines at "\n". sys.stdout and sys.stderr: don't translate newlines (use "\n"). */ newline = "\n"; #endif stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO", buf, encoding, errors, newline, line_buffering); Py_CLEAR(buf); if (stream == NULL) goto error; if (write_mode) mode = "w"; else mode = "r"; text = PyUnicode_FromString(mode); if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0) goto error; Py_CLEAR(text); return stream; error: Py_XDECREF(buf); Py_XDECREF(stream); Py_XDECREF(text); Py_XDECREF(raw); if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) { /* Issue #24891: the file descriptor was closed after the first is_valid_fd() check was called. Ignore the OSError and set the stream to None. */ PyErr_Clear(); Py_RETURN_NONE; } return NULL; }
/* A PyRun_InteractiveOneObject() auxiliary function that does not print the * error on failure. */ static int PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, PyCompilerFlags *flags) { PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name; mod_ty mod; PyArena *arena; const char *ps1 = "", *ps2 = "", *enc = NULL; int errcode = 0; _Py_IDENTIFIER(encoding); _Py_IDENTIFIER(__main__); mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */ if (mod_name == NULL) { return -1; } if (fp == stdin) { /* Fetch encoding from sys.stdin if possible. */ v = _PySys_GetObjectId(&PyId_stdin); if (v && v != Py_None) { oenc = _PyObject_GetAttrId(v, &PyId_encoding); if (oenc) enc = PyUnicode_AsUTF8(oenc); if (!enc) PyErr_Clear(); } } v = _PySys_GetObjectId(&PyId_ps1); if (v != NULL) { v = PyObject_Str(v); if (v == NULL) PyErr_Clear(); else if (PyUnicode_Check(v)) { ps1 = PyUnicode_AsUTF8(v); if (ps1 == NULL) { PyErr_Clear(); ps1 = ""; } } } w = _PySys_GetObjectId(&PyId_ps2); if (w != NULL) { w = PyObject_Str(w); if (w == NULL) PyErr_Clear(); else if (PyUnicode_Check(w)) { ps2 = PyUnicode_AsUTF8(w); if (ps2 == NULL) { PyErr_Clear(); ps2 = ""; } } } arena = PyArena_New(); if (arena == NULL) { Py_XDECREF(v); Py_XDECREF(w); Py_XDECREF(oenc); return -1; } mod = PyParser_ASTFromFileObject(fp, filename, enc, Py_single_input, ps1, ps2, flags, &errcode, arena); Py_XDECREF(v); Py_XDECREF(w); Py_XDECREF(oenc); if (mod == NULL) { PyArena_Free(arena); if (errcode == E_EOF) { PyErr_Clear(); return E_EOF; } return -1; } m = PyImport_AddModuleObject(mod_name); if (m == NULL) { PyArena_Free(arena); return -1; } d = PyModule_GetDict(m); v = run_mod(mod, filename, d, d, flags, arena); PyArena_Free(arena); if (v == NULL) { return -1; } Py_DECREF(v); flush_io(); return 0; }