static void emit_all_code_objects(void) { PyObject *gc_module = NULL, *lst = NULL, *all_codes = NULL; Py_ssize_t i, size; gc_module = PyImport_ImportModuleNoBlock("gc"); if (gc_module == NULL) goto error; lst = PyObject_CallMethod(gc_module, "get_objects", ""); if (lst == NULL || !PyList_Check(lst)) goto error; all_codes = PySet_New(NULL); if (all_codes == NULL) goto error; size = PyList_GET_SIZE(lst); for (i = 0; i < size; i++) { PyObject *o = PyList_GET_ITEM(lst, i); if (o->ob_type->tp_traverse && o->ob_type->tp_traverse(o, _look_for_code_object, (void *)all_codes) < 0) goto error; } error: Py_XDECREF(all_codes); Py_XDECREF(lst); Py_XDECREF(gc_module); }
/* 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. Returns a *borrowed* reference. XXX This makes zlib.decompress immortal. */ static PyObject * get_decompress_func(void) { static PyObject *decompress = NULL; if (decompress == NULL) { PyObject *zlib; static int importing_zlib = 0; 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_GetAttrString(zlib, "decompress"); Py_DECREF(zlib); } else PyErr_Clear(); if (Py_VerboseFlag) PySys_WriteStderr("# zipimport: zlib %s\n", zlib != NULL ? "available": "UNAVAILABLE"); } return decompress; }
void * PyCapsule_Import(const char *name, int no_block) { PyObject *object = NULL; void *return_value = NULL; char *trace; size_t name_length = (strlen(name) + 1) * sizeof(char); char *name_dup = (char *)PyMem_MALLOC(name_length); if (!name_dup) { return NULL; } memcpy(name_dup, name, name_length); trace = name_dup; while (trace) { char *dot = strchr(trace, '.'); if (dot) { *dot++ = '\0'; } if (object == NULL) { if (no_block) { object = PyImport_ImportModuleNoBlock(trace); } else { object = PyImport_ImportModule(trace); if (!object) { PyErr_Format(PyExc_ImportError, "PyCapsule_Import could not import module \"%s\"", trace); } } } else { PyObject *object2 = PyObject_GetAttrString(object, trace); Py_DECREF(object); object = object2; } if (!object) { goto EXIT; } trace = dot; } /* compare attribute name to module.name by hand */ if (PyCapsule_IsValid(object, name)) { PyCapsule *capsule = (PyCapsule *)object; return_value = capsule->pointer; } else { PyErr_Format(PyExc_AttributeError, "PyCapsule_Import \"%s\" is not valid", name); } EXIT: Py_XDECREF(object); if (name_dup) { PyMem_FREE(name_dup); } return return_value; }
long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) { PyObject *mod, *func, *result; long retval; static PyObject *context; if (context == NULL) context = PyUnicode_InternFromString("_ctypes.DllGetClassObject"); mod = PyImport_ImportModuleNoBlock("ctypes"); if (!mod) { PyErr_WriteUnraisable(context ? context : Py_None); /* There has been a warning before about this already */ return E_FAIL; } func = PyObject_GetAttrString(mod, "DllGetClassObject"); Py_DECREF(mod); if (!func) { PyErr_WriteUnraisable(context ? context : Py_None); return E_FAIL; } { PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid); PyObject *py_riid = PyLong_FromVoidPtr((void *)riid); PyObject *py_ppv = PyLong_FromVoidPtr(ppv); if (!py_rclsid || !py_riid || !py_ppv) { Py_XDECREF(py_rclsid); Py_XDECREF(py_riid); Py_XDECREF(py_ppv); Py_DECREF(func); PyErr_WriteUnraisable(context ? context : Py_None); return E_FAIL; } result = PyObject_CallFunctionObjArgs(func, py_rclsid, py_riid, py_ppv, NULL); Py_DECREF(py_rclsid); Py_DECREF(py_riid); Py_DECREF(py_ppv); } Py_DECREF(func); if (!result) { PyErr_WriteUnraisable(context ? context : Py_None); return E_FAIL; } retval = PyLong_AsLong(result); if (PyErr_Occurred()) { PyErr_WriteUnraisable(context ? context : Py_None); retval = E_FAIL; } Py_DECREF(result); return retval; }
/* Header objects are in another module, some hoop jumping required... */ static PyObject *makeHeader(Header h) { PyObject *rpmmod = PyImport_ImportModuleNoBlock("rpm"); if (rpmmod == NULL) return NULL; PyObject *ptr = CAPSULE_BUILD(h, "rpm._C_Header"); PyObject *hdr = PyObject_CallMethod(rpmmod, "hdr", "(O)", ptr); Py_XDECREF(ptr); Py_XDECREF(rpmmod); return hdr; }
static PyObject * time_strptime(PyObject *self, PyObject *args) { PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); PyObject *strptime_result; if (!strptime_module) return NULL; strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args); Py_DECREF(strptime_module); return strptime_result; }
static PyObject * time_strptime(PyObject *self, PyObject *args) { PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime"); PyObject *strptime_result; _Py_IDENTIFIER(_strptime_time); if (!strptime_module) return NULL; strptime_result = _PyObject_CallMethodId(strptime_module, &PyId__strptime_time, "O", args); Py_DECREF(strptime_module); return strptime_result; }
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 void log_msg(int type, char *msg) { static PyObject *logging = NULL; static PyObject *logger = NULL; static PyObject *name = NULL; static PyObject *message = NULL; // import logging module on demand if (logging == NULL){ logging = PyImport_ImportModuleNoBlock("logging"); if (logging == NULL) PyErr_SetString(PyExc_ImportError, "Could not import module 'logging'"); } // build logger message name = Py_BuildValue("s", "pysendint"); // get the logger logger = PyObject_CallMethod(logging, "getLogger", "O", name); // build msg-message message = Py_BuildValue("s", msg); // call function depending on loglevel switch (type) { case info: PyObject_CallMethod(logger, "info", "O", message); break; case warning: PyObject_CallMethod(logger, "warn", "O", message); break; case error: PyObject_CallMethod(logger, "error", "O", message); break; case debug: PyObject_CallMethod(logger, "debug", "O", message); break; } Py_DECREF(message); Py_DECREF(name); }
PyMODINIT_FUNC initgc(void) { PyObject *m; m = Py_InitModule4("gc", GcMethods, gc__doc__, NULL, PYTHON_API_VERSION); if (m == NULL) return; if (garbage == NULL) { garbage = PyList_New(0); if (garbage == NULL) return; } Py_INCREF(garbage); if (PyModule_AddObject(m, "garbage", garbage) < 0) return; /* Importing can't be done in collect() because collect() * can be called via PyGC_Collect() in Py_Finalize(). * This wouldn't be a problem, except that <initialized> is * reset to 0 before calling collect which trips up * the import and triggers an assertion. */ if (tmod == NULL) { tmod = PyImport_ImportModuleNoBlock("time"); if (tmod == NULL) PyErr_Clear(); } #define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return ADD_INT(DEBUG_STATS); ADD_INT(DEBUG_COLLECTABLE); ADD_INT(DEBUG_UNCOLLECTABLE); ADD_INT(DEBUG_INSTANCES); ADD_INT(DEBUG_OBJECTS); ADD_INT(DEBUG_SAVEALL); ADD_INT(DEBUG_LEAK); #undef ADD_INT }
static PyObject *xml_write(PyObject *self, PyObject *args, PyObject *kw) { PyObject *writer_module, *new_args; PyObject *func, *result; int i; #if PY_MAJOR_VERSION <= 2 && PY_MINOR_VERSION <= 5 writer_module = PyImport_ImportModule("amara.writers"); #else writer_module = PyImport_ImportModuleNoBlock("amara.writers"); #endif writer_module = PyImport_ImportModule("amara.writers"); if (writer_module == NULL) { return NULL; } func = PyObject_GetAttrString(writer_module, "_xml_write"); if (func == NULL) { Py_DECREF(writer_module); return NULL; } new_args = PyTuple_New(1+PyTuple_Size(args)); if (new_args == NULL) { Py_DECREF(writer_module); Py_DECREF(func); return NULL; } Py_INCREF(self); PyTuple_SET_ITEM(new_args, 0, self); for(i=0; i<PyTuple_Size(args); i++) { PyObject *elem = PyTuple_GET_ITEM(args, i); Py_INCREF(elem); PyTuple_SET_ITEM(new_args, i+1, elem); } result = PyObject_Call(func, new_args, kw); Py_DECREF(writer_module); Py_DECREF(func); Py_DECREF(new_args); return result; }
static PyObject * time_tzset(PyObject *self, PyObject *unused) { PyObject* m; m = PyImport_ImportModuleNoBlock("time"); if (m == NULL) { return NULL; } tzset(); /* Reset timezone, altzone, daylight and tzname */ PyInit_timezone(m); Py_DECREF(m); Py_INCREF(Py_None); return Py_None; }
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 * time_tzset(PyObject *self, PyObject *unused) { PyObject* m; m = PyImport_ImportModuleNoBlock("time"); if (m == NULL) { return NULL; } tzset(); /* Reset timezone, altzone, daylight and tzname */ PyInit_timezone(m); Py_DECREF(m); if (PyErr_Occurred()) return NULL; Py_RETURN_NONE; }
long Call_CanUnloadNow(void) { PyObject *mod, *func, *result; long retval; static PyObject *context; if (context == NULL) context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow"); mod = PyImport_ImportModuleNoBlock("ctypes"); if (!mod) { /* OutputDebugString("Could not import ctypes"); */ /* We assume that this error can only occur when shutting down, so we silently ignore it */ PyErr_Clear(); return E_FAIL; } /* Other errors cannot be raised, but are printed to stderr */ func = PyObject_GetAttrString(mod, "DllCanUnloadNow"); Py_DECREF(mod); if (!func) { PyErr_WriteUnraisable(context ? context : Py_None); return E_FAIL; } result = PyObject_CallFunction(func, NULL); Py_DECREF(func); if (!result) { PyErr_WriteUnraisable(context ? context : Py_None); return E_FAIL; } retval = PyLong_AsLong(result); if (PyErr_Occurred()) { PyErr_WriteUnraisable(context ? context : Py_None); retval = E_FAIL; } Py_DECREF(result); return retval; }
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]; Py_UNICODE *u, *p; Py_ssize_t len; /* open the file */ if (filename == NULL) return 0; io = PyImport_ImportModuleNoBlock("io"); if (io == NULL) return -1; binary = PyObject_CallMethod(io, "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_FindEncoding(fd); encoding = (found_encoding != NULL) ? found_encoding : "utf-8"; lseek(fd, 0, 0); /* Reset position */ fob = PyObject_CallMethod(io, "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_CallMethod(fob, "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 */ u = PyUnicode_AS_UNICODE(lineobj); len = PyUnicode_GET_SIZE(lineobj); for (p=u; *p == ' ' || *p == '\t' || *p == '\014'; p++) len--; if (u != p) { PyObject *truncated; truncated = PyUnicode_FromUnicode(p, len); 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 _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; /* 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) { PyErr_Clear(); binary = _Py_FindSourceFile(filename, buf, sizeof(buf), io); if (binary == NULL) { Py_DECREF(io); return -1; } } /* use the right encoding to decode the file as unicode */ fd = PyObject_AsFileDescriptor(binary); if (fd < 0) { Py_DECREF(io); Py_DECREF(binary); return 0; } found_encoding = PyTokenizer_FindEncodingFilename(fd, filename); if (found_encoding == NULL) PyErr_Clear(); encoding = (found_encoding != NULL) ? found_encoding : "utf-8"; /* Reset position */ if (lseek(fd, 0, SEEK_SET) == (off_t)-1) { Py_DECREF(io); Py_DECREF(binary); PyMem_FREE(found_encoding); return 0; } 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; }
static PyObject * MacOS_GetErrorString(PyObject *self, PyObject *args) { int err; char buf[256]; Handle h; char *str; static int errors_loaded; if (!PyArg_ParseTuple(args, "i", &err)) return NULL; h = GetResource('Estr', err); if (!h && !errors_loaded) { /* ** Attempt to open the resource file containing the ** Estr resources. We ignore all errors. We also try ** this only once. */ PyObject *m, *rv; errors_loaded = 1; m = PyImport_ImportModuleNoBlock("macresource"); if (!m) { if (Py_VerboseFlag) PyErr_Print(); PyErr_Clear(); } else { rv = PyObject_CallMethod(m, "open_error_resource", ""); if (!rv) { if (Py_VerboseFlag) PyErr_Print(); PyErr_Clear(); } else { Py_DECREF(rv); /* And try again... */ h = GetResource('Estr', err); } Py_DECREF(m); } } /* ** Whether the code above succeeded or not, we won't try ** again. */ errors_loaded = 1; if (h) { HLock(h); str = (char *)*h; memcpy(buf, str+1, (unsigned char)str[0]); buf[(unsigned char)str[0]] = '\0'; HUnlock(h); ReleaseResource(h); } else { PyOS_snprintf(buf, sizeof(buf), "Mac OS error code %d", err); } return Py_BuildValue("s", buf); }