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; }
/* 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; }
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(); }
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; }
int _Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent) { int err = 0; int fd; int i; char *found_encoding; char *encoding; PyObject *io; PyObject *binary; PyObject *fob = NULL; PyObject *lineobj = NULL; PyObject *res; char buf[MAXPATHLEN+1]; int kind; void *data; _Py_IDENTIFIER(close); _Py_IDENTIFIER(open); _Py_IDENTIFIER(TextIOWrapper); /* open the file */ if (filename == NULL) return 0; io = PyImport_ImportModuleNoBlock("io"); if (io == NULL) return -1; binary = _PyObject_CallMethodId(io, &PyId_open, "Os", filename, "rb"); if (binary == NULL) { binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io); if (binary == NULL) { Py_DECREF(io); return 0; } } /* use the right encoding to decode the file as unicode */ fd = PyObject_AsFileDescriptor(binary); found_encoding = PyTokenizer_FindEncodingFilename(fd, filename); encoding = (found_encoding != NULL) ? found_encoding : "utf-8"; lseek(fd, 0, 0); /* Reset position */ fob = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "Os", binary, encoding); Py_DECREF(io); Py_DECREF(binary); PyMem_FREE(found_encoding); if (fob == NULL) { PyErr_Clear(); return 0; } /* get the line number lineno */ for (i = 0; i < lineno; i++) { Py_XDECREF(lineobj); lineobj = PyFile_GetLine(fob, -1); if (!lineobj) { err = -1; break; } } res = _PyObject_CallMethodId(fob, &PyId_close, ""); if (res) Py_DECREF(res); else PyErr_Clear(); Py_DECREF(fob); if (!lineobj || !PyUnicode_Check(lineobj)) { Py_XDECREF(lineobj); return err; } /* remove the indentation of the line */ kind = PyUnicode_KIND(lineobj); data = PyUnicode_DATA(lineobj); for (i=0; i < PyUnicode_GET_LENGTH(lineobj); i++) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (ch != ' ' && ch != '\t' && ch != '\014') break; } if (i) { PyObject *truncated; truncated = PyUnicode_Substring(lineobj, i, PyUnicode_GET_LENGTH(lineobj)); if (truncated) { Py_DECREF(lineobj); lineobj = truncated; } else { PyErr_Clear(); } } /* Write some spaces before the line */ strcpy(buf, " "); assert (strlen(buf) == 10); while (indent > 0) { if(indent < 10) buf[indent] = '\0'; err = PyFile_WriteString(buf, f); if (err != 0) break; indent -= 10; } /* finally display the line */ if (err == 0) err = PyFile_WriteObject(lineobj, f, Py_PRINT_RAW); Py_DECREF(lineobj); if (err == 0) err = PyFile_WriteString("\n", f); return err; }
int path_converter(PyObject *o, void *p) { struct path_arg *path = p; int is_index, is_bytes, is_unicode; PyObject *bytes = NULL; Py_ssize_t length = 0; char *tmp; if (o == NULL) { path_cleanup(p); return 1; } path->object = path->cleanup = NULL; Py_INCREF(o); path->fd = -1; is_index = path->allow_fd && PyIndex_Check(o); is_bytes = PyBytes_Check(o); is_unicode = PyUnicode_Check(o); if (!is_index && !is_bytes && !is_unicode) { _Py_IDENTIFIER(__fspath__); PyObject *func; func = _PyObject_LookupSpecial(o, &PyId___fspath__); if (func == NULL) goto err_format; Py_DECREF(o); o = PyObject_CallFunctionObjArgs(func, NULL); Py_DECREF(func); if (o == NULL) return 0; is_bytes = PyBytes_Check(o); is_unicode = PyUnicode_Check(o); } if (is_unicode) { if (!PyUnicode_FSConverter(o, &bytes)) goto err; } else if (is_bytes) { bytes = o; Py_INCREF(bytes); } else if (is_index) { if (!fd_converter(o, &path->fd)) goto err; path->path = NULL; goto out; } else { err_format: PyErr_Format(PyExc_TypeError, "expected %s, not %s", path->allow_fd ? "string, bytes, os.PathLike, or integer" : "string, bytes, or os.PathLike", Py_TYPE(o)->tp_name); goto err; } length = PyBytes_GET_SIZE(bytes); tmp = PyBytes_AS_STRING(bytes); if ((size_t)length != strlen(tmp)) { PyErr_SetString(PyExc_TypeError, "path has embedded nul character"); goto err; } path->path = tmp; if (bytes == o) Py_DECREF(bytes); else path->cleanup = bytes; path->fd = -1; out: path->length = length; path->object = o; return Py_CLEANUP_SUPPORTED; err: Py_XDECREF(o); Py_XDECREF(bytes); return 0; }
/* zipimporter.__init__ Split the "subdirectory" from the Zip archive path, lookup a matching entry in sys.path_importer_cache, fetch the file directory from there if found, or else read it from the archive. */ static int zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds) { PyObject *path, *files, *tmp; PyObject *filename = NULL; Py_ssize_t len, flen; #ifdef ALTSEP _Py_IDENTIFIER(replace); #endif if (!_PyArg_NoKeywords("zipimporter()", kwds)) return -1; if (!PyArg_ParseTuple(args, "O&:zipimporter", PyUnicode_FSDecoder, &path)) return -1; if (PyUnicode_READY(path) == -1) return -1; len = PyUnicode_GET_LENGTH(path); if (len == 0) { PyErr_SetString(ZipImportError, "archive path is empty"); goto error; } #ifdef ALTSEP tmp = _PyObject_CallMethodId(path, &PyId_replace, "CC", ALTSEP, SEP); if (!tmp) goto error; Py_DECREF(path); path = tmp; #endif filename = path; Py_INCREF(filename); flen = len; for (;;) { struct stat statbuf; int rv; rv = _Py_stat(filename, &statbuf); if (rv == -2) goto error; if (rv == 0) { /* it exists */ if (!S_ISREG(statbuf.st_mode)) /* it's a not file */ Py_CLEAR(filename); break; } Py_CLEAR(filename); /* back up one path element */ flen = PyUnicode_FindChar(path, SEP, 0, flen, -1); if (flen == -1) break; filename = PyUnicode_Substring(path, 0, flen); } if (filename == NULL) { PyErr_SetString(ZipImportError, "not a Zip file"); goto error; } if (PyUnicode_READY(filename) < 0) goto error; files = PyDict_GetItem(zip_directory_cache, filename); if (files == NULL) { files = read_directory(filename); if (files == NULL) goto error; if (PyDict_SetItem(zip_directory_cache, filename, files) != 0) goto error; } else Py_INCREF(files); self->files = files; /* Transfer reference */ self->archive = filename; filename = NULL; /* Check if there is a prefix directory following the filename. */ if (flen != len) { tmp = PyUnicode_Substring(path, flen+1, PyUnicode_GET_LENGTH(path)); if (tmp == NULL) goto error; self->prefix = tmp; if (PyUnicode_READ_CHAR(path, len-1) != SEP) { /* add trailing SEP */ tmp = PyUnicode_FromFormat("%U%c", self->prefix, SEP); if (tmp == NULL) goto error; Py_DECREF(self->prefix); self->prefix = tmp; } } else self->prefix = PyUnicode_New(0, 0); Py_DECREF(path); return 0; error: Py_DECREF(path); Py_XDECREF(filename); return -1; }
/* 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; const 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) { const char *dot = strrchr(className, '.'); if (dot != NULL) className = dot+1; } moduleName = _PyObject_GetAttrId(t, &PyId___module__); if (moduleName == NULL || !PyUnicode_Check(moduleName)) { 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 */ }
static PyObject * iobase_readline(PyObject *self, PyObject *args) { /* For backwards compatibility, a (slowish) readline(). */ Py_ssize_t limit = -1; int has_peek = 0; PyObject *buffer, *result; Py_ssize_t old_size = -1; _Py_IDENTIFIER(read); _Py_IDENTIFIER(peek); if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) { return NULL; } if (_PyObject_HasAttrId(self, &PyId_peek)) has_peek = 1; buffer = PyByteArray_FromStringAndSize(NULL, 0); if (buffer == NULL) return NULL; while (limit < 0 || Py_SIZE(buffer) < limit) { Py_ssize_t nreadahead = 1; PyObject *b; if (has_peek) { PyObject *readahead = _PyObject_CallMethodId(self, &PyId_peek, "i", 1); if (readahead == NULL) { /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR occurs so we needn't do it ourselves. */ if (_PyIO_trap_eintr()) { continue; } goto fail; } if (!PyBytes_Check(readahead)) { PyErr_Format(PyExc_IOError, "peek() should have returned a bytes object, " "not '%.200s'", Py_TYPE(readahead)->tp_name); Py_DECREF(readahead); goto fail; } if (PyBytes_GET_SIZE(readahead) > 0) { Py_ssize_t n = 0; const char *buf = PyBytes_AS_STRING(readahead); if (limit >= 0) { do { if (n >= PyBytes_GET_SIZE(readahead) || n >= limit) break; if (buf[n++] == '\n') break; } while (1); } else { do { if (n >= PyBytes_GET_SIZE(readahead)) break; if (buf[n++] == '\n') break; } while (1); } nreadahead = n; } Py_DECREF(readahead); } b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead); if (b == NULL) { /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR occurs so we needn't do it ourselves. */ if (_PyIO_trap_eintr()) { continue; } goto fail; } if (!PyBytes_Check(b)) { PyErr_Format(PyExc_IOError, "read() should have returned a bytes object, " "not '%.200s'", Py_TYPE(b)->tp_name); Py_DECREF(b); goto fail; } if (PyBytes_GET_SIZE(b) == 0) { Py_DECREF(b); break; } old_size = PyByteArray_GET_SIZE(buffer); PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)); memcpy(PyByteArray_AS_STRING(buffer) + old_size, PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b)); Py_DECREF(b); if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n') break; } result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer), PyByteArray_GET_SIZE(buffer)); Py_DECREF(buffer); return result; fail: Py_DECREF(buffer); return NULL; }
static PyObject * warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwd_list[] = {"message", "category", "filename", "lineno", "module", "registry", "module_globals", "source", 0}; PyObject *message; PyObject *category; PyObject *filename; int lineno; PyObject *module = NULL; PyObject *registry = NULL; PyObject *module_globals = NULL; PyObject *sourceobj = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit", kwd_list, &message, &category, &filename, &lineno, &module, ®istry, &module_globals, &sourceobj)) return NULL; if (module_globals) { _Py_IDENTIFIER(get_source); _Py_IDENTIFIER(splitlines); PyObject *tmp; PyObject *loader; PyObject *module_name; PyObject *source; PyObject *source_list; PyObject *source_line; PyObject *returned; if ((tmp = _PyUnicode_FromId(&PyId_get_source)) == NULL) return NULL; if ((tmp = _PyUnicode_FromId(&PyId_splitlines)) == NULL) return NULL; /* Check/get the requisite pieces needed for the loader. */ loader = PyDict_GetItemString(module_globals, "__loader__"); module_name = PyDict_GetItemString(module_globals, "__name__"); if (loader == NULL || module_name == NULL) goto standard_call; /* Make sure the loader implements the optional get_source() method. */ if (!_PyObject_HasAttrId(loader, &PyId_get_source)) goto standard_call; /* Call get_source() to get the source code. */ source = PyObject_CallMethodObjArgs(loader, PyId_get_source.object, module_name, NULL); if (!source) return NULL; else if (source == Py_None) { Py_DECREF(Py_None); goto standard_call; } /* Split the source into lines. */ source_list = PyObject_CallMethodObjArgs(source, PyId_splitlines.object, NULL); Py_DECREF(source); if (!source_list) return NULL; /* Get the source line. */ source_line = PyList_GetItem(source_list, lineno-1); if (!source_line) { Py_DECREF(source_list); return NULL; } /* Handle the warning. */ returned = warn_explicit(category, message, filename, lineno, module, registry, source_line, sourceobj); Py_DECREF(source_list); return returned; } standard_call: return warn_explicit(category, message, filename, lineno, module, registry, NULL, sourceobj); }
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; char* className; _Py_IDENTIFIER(__module__); assert(PyExceptionClass_Check(type)); className = PyExceptionClass_Name(type); if (className != NULL) { 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_CompareWithId(moduleName, &PyId_builtins) != 0) { 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) err = -1; 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 */ 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(); }
int PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags) { PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name; mod_ty mod; PyArena *arena; 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) { PyErr_Print(); 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_AsString(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_AsString(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_AsString(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; } PyErr_Print(); 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) { PyErr_Print(); flush_io(); return -1; } Py_DECREF(v); flush_io(); 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 * subprocess_fork_exec(PyObject* self, PyObject *args) { PyObject *gc_module = NULL; PyObject *executable_list, *py_fds_to_keep; PyObject *env_list, *preexec_fn; PyObject *process_args, *converted_args = NULL, *fast_args = NULL; PyObject *preexec_fn_args_tuple = NULL; int p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite; int errpipe_read, errpipe_write, close_fds, restore_signals; int call_setsid; PyObject *cwd_obj, *cwd_obj2; const char *cwd; pid_t pid; int need_to_reenable_gc = 0; char *const *exec_array, *const *argv = NULL, *const *envp = NULL; Py_ssize_t arg_num; int import_lock_held = 0; if (!PyArg_ParseTuple( args, "OOpOOOiiiiiiiiiiO:fork_exec", &process_args, &executable_list, &close_fds, &py_fds_to_keep, &cwd_obj, &env_list, &p2cread, &p2cwrite, &c2pread, &c2pwrite, &errread, &errwrite, &errpipe_read, &errpipe_write, &restore_signals, &call_setsid, &preexec_fn)) return NULL; if (close_fds && errpipe_write < 3) { /* precondition */ PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3"); return NULL; } if (PySequence_Length(py_fds_to_keep) < 0) { PyErr_SetString(PyExc_ValueError, "cannot get length of fds_to_keep"); return NULL; } if (_sanity_check_python_fd_sequence(py_fds_to_keep)) { PyErr_SetString(PyExc_ValueError, "bad value(s) in fds_to_keep"); return NULL; } /* We need to call gc.disable() when we'll be calling preexec_fn */ if (preexec_fn != Py_None) { PyObject *result; _Py_IDENTIFIER(isenabled); _Py_IDENTIFIER(disable); gc_module = PyImport_ImportModule("gc"); if (gc_module == NULL) return NULL; result = _PyObject_CallMethodId(gc_module, &PyId_isenabled, NULL); if (result == NULL) { Py_DECREF(gc_module); return NULL; } need_to_reenable_gc = PyObject_IsTrue(result); Py_DECREF(result); if (need_to_reenable_gc == -1) { Py_DECREF(gc_module); return NULL; } result = _PyObject_CallMethodId(gc_module, &PyId_disable, NULL); if (result == NULL) { Py_DECREF(gc_module); return NULL; } Py_DECREF(result); } exec_array = _PySequence_BytesToCharpArray(executable_list); if (!exec_array) goto cleanup; /* Convert args and env into appropriate arguments for exec() */ /* These conversions are done in the parent process to avoid allocating or freeing memory in the child process. */ if (process_args != Py_None) { Py_ssize_t num_args; /* Equivalent to: */ /* tuple(PyUnicode_FSConverter(arg) for arg in process_args) */ fast_args = PySequence_Fast(process_args, "argv must be a tuple"); if (fast_args == NULL) goto cleanup; num_args = PySequence_Fast_GET_SIZE(fast_args); converted_args = PyTuple_New(num_args); if (converted_args == NULL) goto cleanup; for (arg_num = 0; arg_num < num_args; ++arg_num) { PyObject *borrowed_arg, *converted_arg; borrowed_arg = PySequence_Fast_GET_ITEM(fast_args, arg_num); if (PyUnicode_FSConverter(borrowed_arg, &converted_arg) == 0) goto cleanup; PyTuple_SET_ITEM(converted_args, arg_num, converted_arg); } argv = _PySequence_BytesToCharpArray(converted_args); Py_CLEAR(converted_args); Py_CLEAR(fast_args); if (!argv) goto cleanup; } if (env_list != Py_None) { envp = _PySequence_BytesToCharpArray(env_list); if (!envp) goto cleanup; } if (preexec_fn != Py_None) { preexec_fn_args_tuple = PyTuple_New(0); if (!preexec_fn_args_tuple) goto cleanup; _PyImport_AcquireLock(); import_lock_held = 1; } if (cwd_obj != Py_None) { if (PyUnicode_FSConverter(cwd_obj, &cwd_obj2) == 0) goto cleanup; cwd = PyBytes_AsString(cwd_obj2); } else { cwd = NULL; cwd_obj2 = NULL; } pid = fork(); if (pid == 0) { /* Child process */ /* * Code from here to _exit() must only use async-signal-safe functions, * listed at `man 7 signal` or * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html. */ if (preexec_fn != Py_None) { /* We'll be calling back into Python later so we need to do this. * This call may not be async-signal-safe but neither is calling * back into Python. The user asked us to use hope as a strategy * to avoid deadlock... */ PyOS_AfterFork(); } child_exec(exec_array, argv, envp, cwd, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, errpipe_read, errpipe_write, close_fds, restore_signals, call_setsid, py_fds_to_keep, preexec_fn, preexec_fn_args_tuple); _exit(255); return NULL; /* Dead code to avoid a potential compiler warning. */ } Py_XDECREF(cwd_obj2); if (pid == -1) { /* Capture the errno exception before errno can be clobbered. */ PyErr_SetFromErrno(PyExc_OSError); } if (preexec_fn != Py_None && _PyImport_ReleaseLock() < 0 && !PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "not holding the import lock"); } import_lock_held = 0; /* Parent process */ if (envp) _Py_FreeCharPArray(envp); if (argv) _Py_FreeCharPArray(argv); _Py_FreeCharPArray(exec_array); /* Reenable gc in the parent process (or if fork failed). */ if (need_to_reenable_gc && _enable_gc(gc_module)) { Py_XDECREF(gc_module); return NULL; } Py_XDECREF(preexec_fn_args_tuple); Py_XDECREF(gc_module); if (pid == -1) return NULL; /* fork() failed. Exception set earlier. */ return PyLong_FromPid(pid); cleanup: if (import_lock_held) _PyImport_ReleaseLock(); if (envp) _Py_FreeCharPArray(envp); if (argv) _Py_FreeCharPArray(argv); if (exec_array) _Py_FreeCharPArray(exec_array); Py_XDECREF(converted_args); Py_XDECREF(fast_args); Py_XDECREF(preexec_fn_args_tuple); /* Reenable gc if it was disabled. */ if (need_to_reenable_gc) { PyObject *exctype, *val, *tb; PyErr_Fetch(&exctype, &val, &tb); _enable_gc(gc_module); PyErr_Restore(exctype, val, tb); } Py_XDECREF(gc_module); return NULL; }
static PyObject * _io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint) /*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/ { Py_ssize_t length = 0; PyObject *result, *it = NULL; result = PyList_New(0); if (result == NULL) return NULL; if (hint <= 0) { /* XXX special-casing this made sense in the Python version in order to remove the bytecode interpretation overhead, but it could probably be removed here. */ _Py_IDENTIFIER(extend); PyObject *ret = _PyObject_CallMethodIdObjArgs(result, &PyId_extend, self, NULL); if (ret == NULL) { goto error; } Py_DECREF(ret); return result; } it = PyObject_GetIter(self); if (it == NULL) { goto error; } while (1) { Py_ssize_t line_length; PyObject *line = PyIter_Next(it); if (line == NULL) { if (PyErr_Occurred()) { goto error; } else break; /* StopIteration raised */ } if (PyList_Append(result, line) < 0) { Py_DECREF(line); goto error; } line_length = PyObject_Size(line); Py_DECREF(line); if (line_length < 0) { goto error; } if (line_length > hint - length) break; length += line_length; } Py_DECREF(it); return result; error: Py_XDECREF(it); Py_DECREF(result); return NULL; }
void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) { PyObject *exc, *v, *tb, *tmp; _Py_IDENTIFIER(filename); _Py_IDENTIFIER(lineno); _Py_IDENTIFIER(msg); _Py_IDENTIFIER(offset); _Py_IDENTIFIER(print_file_and_line); _Py_IDENTIFIER(text); /* add attributes for the line number and filename for the error */ PyErr_Fetch(&exc, &v, &tb); PyErr_NormalizeException(&exc, &v, &tb); /* XXX check that it is, indeed, a syntax error. It might not * be, though. */ tmp = PyLong_FromLong(lineno); if (tmp == NULL) PyErr_Clear(); else { if (_PyObject_SetAttrId(v, &PyId_lineno, tmp)) PyErr_Clear(); Py_DECREF(tmp); } tmp = NULL; if (col_offset >= 0) { tmp = PyLong_FromLong(col_offset); if (tmp == NULL) PyErr_Clear(); } if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None)) PyErr_Clear(); Py_XDECREF(tmp); if (filename != NULL) { if (_PyObject_SetAttrId(v, &PyId_filename, filename)) PyErr_Clear(); tmp = PyErr_ProgramTextObject(filename, lineno); if (tmp) { if (_PyObject_SetAttrId(v, &PyId_text, tmp)) PyErr_Clear(); Py_DECREF(tmp); } } if (exc != PyExc_SyntaxError) { if (!_PyObject_HasAttrId(v, &PyId_msg)) { tmp = PyObject_Str(v); if (tmp) { if (_PyObject_SetAttrId(v, &PyId_msg, tmp)) PyErr_Clear(); Py_DECREF(tmp); } else { PyErr_Clear(); } } if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) { if (_PyObject_SetAttrId(v, &PyId_print_file_and_line, Py_None)) PyErr_Clear(); } } PyErr_Restore(exc, v, tb); }
static int parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, int *lineno, int *offset, PyObject **text) { long hold; PyObject *v; _Py_IDENTIFIER(msg); _Py_IDENTIFIER(filename); _Py_IDENTIFIER(lineno); _Py_IDENTIFIER(offset); _Py_IDENTIFIER(text); *message = NULL; *filename = 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 = _PyUnicode_FromId(&PyId_string); if (*filename == NULL) { goto finally; } Py_INCREF(*filename); } else { *filename = v; } 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 = v; } return 1; finally: Py_XDECREF(*message); Py_XDECREF(*filename); return 0; }
static PyObject * _Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io) { Py_ssize_t i; PyObject *binary; PyObject *v; Py_ssize_t npath; size_t taillen; PyObject *syspath; PyObject *path; const char* tail; PyObject *filebytes; const char* filepath; Py_ssize_t len; PyObject* result; _Py_IDENTIFIER(open); filebytes = PyUnicode_EncodeFSDefault(filename); if (filebytes == NULL) { PyErr_Clear(); return NULL; } filepath = PyBytes_AS_STRING(filebytes); /* Search tail of filename in sys.path before giving up */ tail = strrchr(filepath, SEP); if (tail == NULL) tail = filepath; else tail++; taillen = strlen(tail); syspath = PySys_GetObject("path"); if (syspath == NULL || !PyList_Check(syspath)) goto error; npath = PyList_Size(syspath); for (i = 0; i < npath; i++) { v = PyList_GetItem(syspath, i); if (v == NULL) { PyErr_Clear(); break; } if (!PyUnicode_Check(v)) continue; path = PyUnicode_EncodeFSDefault(v); if (path == NULL) { PyErr_Clear(); continue; } len = PyBytes_GET_SIZE(path); if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) { Py_DECREF(path); continue; /* Too long */ } strcpy(namebuf, PyBytes_AS_STRING(path)); Py_DECREF(path); if (strlen(namebuf) != len) continue; /* v contains '\0' */ if (len > 0 && namebuf[len-1] != SEP) namebuf[len++] = SEP; strcpy(namebuf+len, tail); binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb"); if (binary != NULL) { result = binary; goto finally; } PyErr_Clear(); } goto error; error: result = NULL; finally: Py_DECREF(filebytes); return result; }
/* The item is a new reference. */ static PyObject* get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, PyObject *module, PyObject **item) { PyObject *action; Py_ssize_t i; PyObject *warnings_filters; _Py_IDENTIFIER(filters); warnings_filters = get_warnings_attr(&PyId_filters, 0); if (warnings_filters == NULL) { if (PyErr_Occurred()) return NULL; } else { Py_SETREF(_PyRuntime.warnings.filters, warnings_filters); } PyObject *filters = _PyRuntime.warnings.filters; if (filters == NULL || !PyList_Check(filters)) { PyErr_SetString(PyExc_ValueError, MODULE_NAME ".filters must be a list"); return NULL; } /* _PyRuntime.warnings.filters could change while we are iterating over it. */ for (i = 0; i < PyList_GET_SIZE(filters); i++) { PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj; Py_ssize_t ln; int is_subclass, good_msg, good_mod; tmp_item = PyList_GET_ITEM(filters, i); if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) { PyErr_Format(PyExc_ValueError, MODULE_NAME ".filters item %zd isn't a 5-tuple", i); return NULL; } /* Python code: action, msg, cat, mod, ln = item */ Py_INCREF(tmp_item); action = PyTuple_GET_ITEM(tmp_item, 0); msg = PyTuple_GET_ITEM(tmp_item, 1); cat = PyTuple_GET_ITEM(tmp_item, 2); mod = PyTuple_GET_ITEM(tmp_item, 3); ln_obj = PyTuple_GET_ITEM(tmp_item, 4); if (!PyUnicode_Check(action)) { PyErr_Format(PyExc_TypeError, "action must be a string, not '%.200s'", Py_TYPE(action)->tp_name); Py_DECREF(tmp_item); return NULL; } good_msg = check_matched(msg, text); if (good_msg == -1) { Py_DECREF(tmp_item); return NULL; } good_mod = check_matched(mod, module); if (good_mod == -1) { Py_DECREF(tmp_item); return NULL; } is_subclass = PyObject_IsSubclass(category, cat); if (is_subclass == -1) { Py_DECREF(tmp_item); return NULL; } ln = PyLong_AsSsize_t(ln_obj); if (ln == -1 && PyErr_Occurred()) { Py_DECREF(tmp_item); return NULL; } if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) { *item = tmp_item; return action; } Py_DECREF(tmp_item); } action = get_default_action(); if (action != NULL) { Py_INCREF(Py_None); *item = Py_None; return action; } return NULL; }
static PyObject * dbm__exit__(PyObject *self, PyObject *args) { _Py_IDENTIFIER(close); return _PyObject_CallMethodId(self, &PyId_close, NULL); }
PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { PyObject *d, *v, *n; PyMethodDef *ml; const char* name; PyModuleObject *m; PyInterpreterState *interp = PyThreadState_Get()->interp; if (interp->modules == NULL) Py_FatalError("Python import machinery not initialized"); if (PyType_Ready(&moduledef_type) < 0) return NULL; if (module->m_base.m_index == 0) { max_module_number++; Py_REFCNT(module) = 1; Py_TYPE(module) = &moduledef_type; module->m_base.m_index = max_module_number; } name = module->m_name; if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) { int err; err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "Python C API version mismatch for module %.100s: " "This Python has API version %d, module %.100s has version %d.", name, PYTHON_API_VERSION, name, module_api_version); if (err) return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } memset(m->md_state, 0, module->m_size); } d = PyModule_GetDict((PyObject*)m); if (module->m_methods != NULL) { n = PyUnicode_FromString(name); if (n == NULL) { Py_DECREF(m); return NULL; } for (ml = module->m_methods; ml->ml_name != NULL; ml++) { if ((ml->ml_flags & METH_CLASS) || (ml->ml_flags & METH_STATIC)) { PyErr_SetString(PyExc_ValueError, "module functions cannot set" " METH_CLASS or METH_STATIC"); Py_DECREF(n); Py_DECREF(m); return NULL; } v = PyCFunction_NewEx(ml, (PyObject*)m, n); if (v == NULL) { Py_DECREF(n); Py_DECREF(m); return NULL; } if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { Py_DECREF(v); Py_DECREF(n); Py_DECREF(m); return NULL; } Py_DECREF(v); } Py_DECREF(n); } if (module->m_doc != NULL) { _Py_IDENTIFIER(__doc__); v = PyUnicode_FromString(module->m_doc); if (v == NULL || _PyDict_SetItemId(d, &PyId___doc__, v) != 0) { Py_XDECREF(v); Py_DECREF(m); return NULL; } Py_DECREF(v); } m->md_def = module; return (PyObject*)m; }