PyObject* PyThread_GetInfo(void) { PyObject *threadinfo, *value; int pos = 0; #if (defined(_POSIX_THREADS) && defined(HAVE_CONFSTR) \ && defined(_CS_GNU_LIBPTHREAD_VERSION)) char buffer[255]; int len; #endif if (ThreadInfoType.tp_name == 0) { if (PyStructSequence_InitType2(&ThreadInfoType, &threadinfo_desc) < 0) return NULL; } threadinfo = PyStructSequence_New(&ThreadInfoType); if (threadinfo == NULL) return NULL; value = PyUnicode_FromString(PYTHREAD_NAME); if (value == NULL) { Py_DECREF(threadinfo); return NULL; } PyStructSequence_SET_ITEM(threadinfo, pos++, value); #ifdef _POSIX_THREADS #ifdef USE_SEMAPHORES value = PyUnicode_FromString("semaphore"); #else value = PyUnicode_FromString("mutex+cond"); #endif if (value == NULL) { Py_DECREF(threadinfo); return NULL; } #else Py_INCREF(Py_None); value = Py_None; #endif PyStructSequence_SET_ITEM(threadinfo, pos++, value); #if (defined(_POSIX_THREADS) && defined(HAVE_CONFSTR) \ && defined(_CS_GNU_LIBPTHREAD_VERSION)) value = NULL; len = confstr(_CS_GNU_LIBPTHREAD_VERSION, buffer, sizeof(buffer)); if (1 < len && len < sizeof(buffer)) { value = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1); if (value == NULL) PyErr_Clear(); } if (value == NULL) #endif { Py_INCREF(Py_None); value = Py_None; } PyStructSequence_SET_ITEM(threadinfo, pos++, value); return threadinfo; }
/* Writes a buffer to the file object * Make sure to hold the GIL state before calling this function * Returns the number of bytes written if successful, or -1 on error */ ssize_t pyfshfs_file_object_write_buffer( PyObject *file_object, const uint8_t *buffer, size_t size, libcerror_error_t **error ) { PyObject *argument_string = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; static char *function = "pyfshfs_file_object_write_buffer"; if( file_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file object.", function ); return( -1 ); } if( buffer == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid buffer.", function ); return( -1 ); } #if SIZEOF_SIZE_T > SIZEOF_INT if( size > (size_t) INT_MAX ) #else if( size > (size_t) SSIZE_MAX ) #endif { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid size value exceeds maximum.", function ); return( -1 ); } if( size > 0 ) { #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "write" ); #else method_name = PyString_FromString( "write" ); #endif #if PY_MAJOR_VERSION >= 3 argument_string = PyBytes_FromStringAndSize( (char *) buffer, size ); #else argument_string = PyString_FromStringAndSize( (char *) buffer, size ); #endif PyErr_Clear(); method_result = PyObject_CallMethodObjArgs( file_object, method_name, argument_string, NULL ); if( PyErr_Occurred() ) { pyfshfs_error_fetch( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_WRITE_FAILED, "%s: unable to write to file object.", function ); goto on_error; } if( method_result == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: missing method result.", function ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( argument_string ); Py_DecRef( method_name ); } return( (ssize_t) size ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( argument_string != NULL ) { Py_DecRef( argument_string ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); }
PyObject* BL_ShapeActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef) { BL_ShapeActionActuator* self= static_cast<BL_ShapeActionActuator*>(self_v); return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : ""); }
/* Retrieves the current offset within the file object * Make sure to hold the GIL state before calling this function * Returns 1 if successful or -1 on error */ int pyfshfs_file_object_get_offset( PyObject *file_object, off64_t *offset, libcerror_error_t **error ) { PyObject *method_name = NULL; PyObject *method_result = NULL; static char *function = "pyfshfs_file_object_get_offset"; int result = 0; if( file_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file object.", function ); return( -1 ); } if( offset == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid offset.", function ); return( -1 ); } #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "get_offset" ); #else method_name = PyString_FromString( "get_offset" ); #endif PyErr_Clear(); /* Determine if the file object has the get_offset method */ result = PyObject_HasAttr( file_object, method_name ); if( result == 0 ) { Py_DecRef( method_name ); /* Fall back to the tell method */ #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "tell" ); #else method_name = PyString_FromString( "tell" ); #endif } PyErr_Clear(); method_result = PyObject_CallMethodObjArgs( file_object, method_name, NULL ); if( PyErr_Occurred() ) { pyfshfs_error_fetch( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve current offset in file object.", function ); goto on_error; } if( method_result == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: missing method result.", function ); goto on_error; } if( pyfshfs_integer_signed_copy_to_64bit( method_result, offset, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to convert method result into current offset of file object.", function ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( method_name ); return( 1 ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); }
/* Retrieves the file size * Returns 1 if successful or -1 on error */ int pyfshfs_file_object_io_handle_get_size( pyfshfs_file_object_io_handle_t *file_object_io_handle, size64_t *size, libcerror_error_t **error ) { PyObject *method_name = NULL; static char *function = "pyfshfs_file_object_io_handle_get_size"; off64_t current_offset = 0; PyGILState_STATE gil_state = 0; int result = 0; if( file_object_io_handle == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file object IO handle.", function ); return( -1 ); } if( file_object_io_handle->file_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: invalid file object IO handle - missing file object.", function ); return( -1 ); } gil_state = PyGILState_Ensure(); #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "get_size" ); #else method_name = PyString_FromString( "get_size" ); #endif PyErr_Clear(); /* Determine if the file object has the get_size method */ result = PyObject_HasAttr( file_object_io_handle->file_object, method_name ); if( result != 0 ) { if( pyfshfs_file_object_get_size( file_object_io_handle->file_object, size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve size of file object.", function ); goto on_error; } } else { if( pyfshfs_file_object_get_offset( file_object_io_handle->file_object, ¤t_offset, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve current offset in file object.", function ); goto on_error; } if( pyfshfs_file_object_seek_offset( file_object_io_handle->file_object, 0, SEEK_END, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek end of file object.", function ); goto on_error; } if( pyfshfs_file_object_get_offset( file_object_io_handle->file_object, (off64_t *) size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve end offset in file object.", function ); pyfshfs_file_object_seek_offset( file_object_io_handle->file_object, current_offset, SEEK_SET, NULL ); goto on_error; } if( pyfshfs_file_object_seek_offset( file_object_io_handle->file_object, current_offset, SEEK_SET, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek current offset in file object.", function ); goto on_error; } } Py_DecRef( method_name ); PyGILState_Release( gil_state ); return( 1 ); on_error: if( method_name != NULL ) { Py_DecRef( method_name ); } PyGILState_Release( gil_state ); return( 1 ); }
static char *GetPythonImport (HINSTANCE hModule) { unsigned char *dllbase, *import_data, *import_name; DWORD pe_offset, opt_offset; WORD opt_magic; int num_dict_off, import_off; /* Safety check input */ if (hModule == NULL) { return NULL; } /* Module instance is also the base load address. First portion of memory is the MS-DOS loader, which holds the offset to the PE header (from the load base) at 0x3C */ dllbase = (unsigned char *)hModule; pe_offset = DWORD_AT(dllbase + 0x3C); /* The PE signature must be "PE\0\0" */ if (memcmp(dllbase+pe_offset,"PE\0\0",4)) { return NULL; } /* Following the PE signature is the standard COFF header (20 bytes) and then the optional header. The optional header starts with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+ uses 64-bits for some fields). It might also be 0x107 for a ROM image, but we don't process that here. The optional header ends with a data dictionary that directly points to certain types of data, among them the import entries (in the second table entry). Based on the header type, we determine offsets for the data dictionary count and the entry within the dictionary pointing to the imports. */ opt_offset = pe_offset + 4 + 20; opt_magic = WORD_AT(dllbase+opt_offset); if (opt_magic == 0x10B) { /* PE32 */ num_dict_off = 92; import_off = 104; } else if (opt_magic == 0x20B) { /* PE32+ */ num_dict_off = 108; import_off = 120; } else { /* Unsupported */ return NULL; } /* Now if an import table exists, offset to it and walk the list of imports. The import table is an array (ending when an entry has empty values) of structures (20 bytes each), which contains (at offset 12) a relative address (to the module base) at which a string constant holding the import name is located. */ if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) { /* We have at least 2 tables - the import table is the second one. But still it may be that the table size is zero */ if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD))) return NULL; import_data = dllbase + DWORD_AT(dllbase + opt_offset + import_off); while (DWORD_AT(import_data)) { import_name = dllbase + DWORD_AT(import_data+12); if (strlen(import_name) >= 6 && !strncmp(import_name,"python",6)) { char *pch; /* Ensure python prefix is followed only by numbers to the end of the basename */ pch = import_name + 6; #ifdef _DEBUG while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') { #else while (*pch && *pch != '.') { #endif if (*pch >= '0' && *pch <= '9') { pch++; } else { pch = NULL; break; } } if (pch) { /* Found it - return the name */ return import_name; } } import_data += 20; } } return NULL; } dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname, const char *pathname, FILE *fp) { dl_funcptr p; char funcname[258], *import_python; PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname); { HINSTANCE hDLL = NULL; char pathbuf[260]; LPTSTR dummy; unsigned int old_mode; /* We use LoadLibraryEx so Windows looks for dependent DLLs in directory of pathname first. However, Windows95 can sometimes not work correctly unless the absolute path is used. If GetFullPathName() fails, the LoadLibrary will certainly fail too, so use its error code */ /* Don't display a message box when Python can't load a DLL */ old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); if (GetFullPathName(pathname, sizeof(pathbuf), pathbuf, &dummy)) /* XXX This call doesn't exist in Windows CE */ hDLL = LoadLibraryEx(pathname, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); /* restore old error mode settings */ SetErrorMode(old_mode); if (hDLL==NULL){ PyObject *message; unsigned int errorCode; /* Get an error string from Win32 error code */ wchar_t theInfo[256]; /* Pointer to error text from system */ int theLength; /* Length of error text */ errorCode = GetLastError(); theLength = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */ NULL, /* message source */ errorCode, /* the message (error) ID */ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ theInfo, /* the buffer */ sizeof(theInfo), /* the buffer size */ NULL); /* no additional format args. */ /* Problem: could not get the error message. This should not happen if called correctly. */ if (theLength == 0) { message = PyUnicode_FromFormat( "DLL load failed with error code %d", errorCode); } else { /* For some reason a \r\n is appended to the text */ if (theLength >= 2 && theInfo[theLength-2] == '\r' && theInfo[theLength-1] == '\n') { theLength -= 2; theInfo[theLength] = '\0'; } message = PyUnicode_FromString( "DLL load failed: "); PyUnicode_AppendAndDel(&message, PyUnicode_FromUnicode( theInfo, theLength)); } PyErr_SetObject(PyExc_ImportError, message); Py_XDECREF(message); return NULL; } else { char buffer[256]; #ifdef _DEBUG PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll", #else PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll", #endif PY_MAJOR_VERSION,PY_MINOR_VERSION); import_python = GetPythonImport(hDLL); if (import_python && strcasecmp(buffer,import_python)) { PyOS_snprintf(buffer, sizeof(buffer), "Module use of %.150s conflicts " "with this version of Python.", import_python); PyErr_SetString(PyExc_ImportError,buffer); FreeLibrary(hDLL); return NULL; } } p = GetProcAddress(hDLL, funcname); } return p; }
bool PythonTransform::loadModuleAttributes() { if (pModule == NULL) { Q_EMIT error(tr("The module object is NULL for %1, could not (re)load the configuration").arg(moduleFileName),id); return false; } qDebug() << "Loading module attributes" << moduleName; bool ret = true; bool oldtwoWays = twoWays; twoWays = false; // setting default PyGILState_STATE lgstate; lgstate = PyGILState_Ensure(); // checking if the two ways attribute is there PyObject * twoWayAttr = PyUnicode_FromString(ISTWOWAY_ATTR_NAME); // New ref if (pythonmgm->checkPyError()) { if (PyObject_HasAttr(pModule,twoWayAttr) == 1) { // does the module has the attribute? PyObject * pyTwoWay = PyObject_GetAttr(pModule,twoWayAttr); // New ref if (pythonmgm->checkPyError()) { twoWays = pyTwoWay == Py_True; } else { logError(tr("T_T Error while getting attribute value ISTWOWAY_ATTR_NAME for %1:\n%2").arg(moduleFileName).arg(pythonmgm->getLastError()),id); } Py_XDECREF(pyTwoWay); } else { qDebug() << moduleFileName << "has no attribute" << ISTWOWAY_ATTR_NAME; } } else { logError(tr("T_T Error while converting to Unicode string:\n%1").arg(pythonmgm->getLastError()),id); } Py_XDECREF(twoWayAttr); bool parametersChanged = false; // checking if some default parameters names were defined PyObject * paramsNamesAttr = PyUnicode_FromString(PARAMS_NAMES_ATTR_NAME); // New ref if (pythonmgm->checkPyError()) { if (PyObject_HasAttr(pModule,paramsNamesAttr) == 1) { // does the module has the attribute? PyObject * pyNamesList = PyObject_GetAttr(pModule,paramsNamesAttr); // New ref if (pythonmgm->checkPyError()) { if (PyList_Check(pyNamesList)) { Py_ssize_t listSize = PyList_Size(pyNamesList); if (listSize > 0) { // if list size is null then nothing to do for (int i = 0; i < listSize; i++) { QByteArray val; PyObject *pyName = PyList_GetItem(pyNamesList, i); // borrowed ref if (pythonmgm->checkPyError()) { // error or invalid? #ifdef BUILD_PYTHON_3 if (PyUnicode_Check(pyName)) { // is this a unicode string? PyObject * nameutf8 = PyUnicode_AsUTF8String(pyName); // new ref if (pythonmgm->checkPyError() && nameutf8 != NULL) { val = QByteArray(PyBytes_AsString(nameutf8), PyBytes_Size(nameutf8)); } else { logError(tr("Error while encoding a parameter to UTF-8:%1").arg(pythonmgm->getLastError()),id); } Py_XDECREF(nameutf8); #else if (PyString_Check(pyName)) { // is this a string? val = QByteArray(PyString_AsString(pyName), PyString_Size(pyName)); #endif if (val.isEmpty()) { // if the parameter name is empty, we skip logWarning(tr("The Python object %1[%2] is an empty string, ignoring.").arg(PARAMS_NAMES_ATTR_NAME).arg(i),id); } else if (!parameters.contains(val)) { // we don't want to erase any pre-existing configuration parameters.insert(val, QByteArray()); parametersChanged = true; } } else { logWarning(tr("The Python object %1[%2] is not a string, ignoring.").arg(PARAMS_NAMES_ATTR_NAME).arg(i),id); } } else { logError(tr("T_T Error while getting the item from attribute list:\n%1").arg(pythonmgm->getLastError()),id); } } } else { logWarning(tr("The Python object for attribute names (%1) is empty, ignoring.").arg(PARAMS_NAMES_ATTR_NAME),id); } } else { logWarning(tr("The Python object for attribute names (%1) is not a list, ignoring.").arg(PARAMS_NAMES_ATTR_NAME),id); } } else {
static KMETHOD String_toPyObject(KonohaContext *kctx, KonohaStack *sfp) { KReturnPyObject(PyUnicode_FromString(kString_text(sfp[0].asString))); }
PyObject* PyCOMPSPack_strget_(PyCOMPS_Package *self, void *closure) { char *tmp = GET_FROM(self->package, (size_t)closure); return PyUnicode_FromString(tmp); }
static PyObject * get_mode(PyStdPrinter_Object *self, void *closure) { return PyUnicode_FromString("w"); }
/* Returns 0 on error (no new refs), 1 on success */ static int setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, PyObject **module, PyObject **registry) { PyObject *globals; /* Setup globals and lineno. */ PyFrameObject *f = PyThreadState_GET()->frame; while (--stack_level > 0 && f != NULL) f = f->f_back; if (f == NULL) { globals = PyThreadState_Get()->interp->sysdict; *lineno = 1; } else { globals = f->f_globals; *lineno = PyFrame_GetLineNumber(f); } *module = NULL; /* Setup registry. */ assert(globals != NULL); assert(PyDict_Check(globals)); *registry = PyDict_GetItemString(globals, "__warningregistry__"); if (*registry == NULL) { int rc; *registry = PyDict_New(); if (*registry == NULL) return 0; rc = PyDict_SetItemString(globals, "__warningregistry__", *registry); if (rc < 0) goto handle_error; } else Py_INCREF(*registry); /* Setup module. */ *module = PyDict_GetItemString(globals, "__name__"); if (*module == NULL) { *module = PyUnicode_FromString("<string>"); if (*module == NULL) goto handle_error; } else Py_INCREF(*module); /* Setup filename. */ *filename = PyDict_GetItemString(globals, "__file__"); if (*filename != NULL && PyUnicode_Check(*filename)) { Py_ssize_t len; int kind; void *data; if (PyUnicode_READY(*filename)) goto handle_error; len = PyUnicode_GetLength(*filename); kind = PyUnicode_KIND(*filename); data = PyUnicode_DATA(*filename); #define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0) /* if filename.lower().endswith((".pyc", ".pyo")): */ if (len >= 4 && PyUnicode_READ(kind, data, len-4) == '.' && ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' && ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' && (ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c' || ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'o')) { *filename = PyUnicode_Substring(*filename, 0, PyUnicode_GET_LENGTH(*filename)-1); if (*filename == NULL) goto handle_error; } else Py_INCREF(*filename); } else { *filename = NULL; if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) { PyObject *argv = _PySys_GetObjectId(&PyId_argv); /* PyList_Check() is needed because sys.argv is set to None during Python finalization */ if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) { int is_true; *filename = PyList_GetItem(argv, 0); Py_INCREF(*filename); /* If sys.argv[0] is false, then use '__main__'. */ is_true = PyObject_IsTrue(*filename); if (is_true < 0) { Py_DECREF(*filename); goto handle_error; } else if (!is_true) { Py_DECREF(*filename); *filename = PyUnicode_FromString("__main__"); if (*filename == NULL) goto handle_error; } } else { /* embedded interpreters don't have sys.argv, see bug #839151 */ *filename = PyUnicode_FromString("__main__"); if (*filename == NULL) goto handle_error; } } if (*filename == NULL) { *filename = *module; Py_INCREF(*filename); } } return 1; handle_error: /* filename not XDECREF'ed here as there is no way to jump here with a dangling reference. */ Py_XDECREF(*registry); Py_XDECREF(*module); return 0; }
PyInit__rpy_device(void) #endif { #if (PY_VERSION_HEX < 0x03010000) GrDev_close_name = PyString_FromString("close"); GrDev_activate_name = PyString_FromString("activate"); GrDev_deactivate_name = PyString_FromString("deactivate"); GrDev_size_name = PyString_FromString("size"); GrDev_newpage_name = PyString_FromString("newpage"); GrDev_clip_name = PyString_FromString("clip"); GrDev_strwidth_name = PyString_FromString("strwidth"); GrDev_text_name = PyString_FromString("text"); GrDev_rect_name = PyString_FromString("rect"); GrDev_circle_name = PyString_FromString("circle"); GrDev_line_name = PyString_FromString("line"); GrDev_polyline_name = PyString_FromString("polyline"); GrDev_polygon_name = PyString_FromString("polygon"); GrDev_locator_name = PyString_FromString("locator"); GrDev_mode_name = PyString_FromString("mode"); GrDev_metricinfo_name = PyString_FromString("metricinfo"); GrDev_getevent_name = PyString_FromString("getevent"); #else GrDev_close_name = PyUnicode_FromString("close"); GrDev_activate_name = PyUnicode_FromString("activate"); GrDev_deactivate_name = PyUnicode_FromString("deactivate"); GrDev_size_name = PyUnicode_FromString("size"); GrDev_newpage_name = PyUnicode_FromString("newpage"); GrDev_clip_name = PyUnicode_FromString("clip"); GrDev_strwidth_name = PyUnicode_FromString("strwidth"); GrDev_text_name = PyUnicode_FromString("text"); GrDev_rect_name = PyUnicode_FromString("rect"); GrDev_circle_name = PyUnicode_FromString("circle"); GrDev_line_name = PyUnicode_FromString("line"); GrDev_polyline_name = PyUnicode_FromString("polyline"); GrDev_polygon_name = PyUnicode_FromString("polygon"); GrDev_locator_name = PyUnicode_FromString("locator"); GrDev_mode_name = PyUnicode_FromString("mode"); GrDev_metricinfo_name = PyUnicode_FromString("metricinfo"); GrDev_getevent_name = PyUnicode_FromString("getevent"); #endif if (PyType_Ready(&GrDev_Type) < 0) { #if (PY_VERSION_HEX < 0x03010000) return; #else return NULL; #endif } PyObject *m, *d; #if (PY_VERSION_HEX < 0x03010000) m = Py_InitModule3("_rpy_device", rpydevice_methods, module_doc); #else m = PyModule_Create(&rpydevicemodule); #endif if (m == NULL) { #if (PY_VERSION_HEX < 0x03010000) return; #else return NULL; #endif } if (import_rinterface() < 0) #if (PY_VERSION_HEX < 0x03010000) return; #else return NULL; #endif d = PyModule_GetDict(m); PyModule_AddObject(m, "GraphicalDevice", (PyObject *)&GrDev_Type); #if (PY_VERSION_HEX < 0x03010000) #else return m; #endif }
static PyObject * get_line_buffer(PyObject *self, PyObject *noarg) { return PyUnicode_FromString(rl_line_buffer); }
static PyObject* ejdb_version(PyObject *module) { return PyUnicode_FromString(tcversion); }
bool EntityApp<E>::installPyModules() { Entities<E>::installScript(NULL); //Entity::installScript(g_script.getModule()); pEntities_ = new Entities<E>(); registerPyObjectToScript("entities", pEntities_); // 安装入口模块 PyObject *entryScriptFileName = NULL; if(componentType() == BASEAPP_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getBaseApp(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } else if(componentType() == CELLAPP_TYPE) { ENGINE_COMPONENT_INFO& info = g_kbeSrvConfig.getCellApp(); entryScriptFileName = PyUnicode_FromString(info.entryScriptFile); } if(entryScriptFileName != NULL) { entryScript_ = PyImport_Import(entryScriptFileName); SCRIPT_ERROR_CHECK(); S_RELEASE(entryScriptFileName); if(entryScript_.get() == NULL) { return false; } } // 添加pywatcher支持 if(!initializePyWatcher(&this->getScript())) return false; // 添加globalData, globalBases支持 pGlobalData_ = new GlobalDataClient(DBMGR_TYPE, GlobalDataServer::GLOBAL_DATA); registerPyObjectToScript("globalData", pGlobalData_); // 注册创建entity的方法到py // 向脚本注册app发布状态 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), publish, __py_getAppPublish, METH_VARARGS, 0); // 注册设置脚本输出类型 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), scriptLogType, __py_setScriptLogType, METH_VARARGS, 0); // 获得资源全路径 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), getResFullPath, __py_getResFullPath, METH_VARARGS, 0); // 文件操作 APPEND_SCRIPT_MODULE_METHOD(getScript().getModule(), open, __py_kbeOpen, METH_VARARGS, 0); if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_NORMAL", log4cxx::ScriptLevel::SCRIPT_INT)) { ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_NORMAL.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_INFO", log4cxx::ScriptLevel::SCRIPT_INFO)) { ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_INFO.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_ERR", log4cxx::ScriptLevel::SCRIPT_ERR)) { ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_ERR.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_DBG", log4cxx::ScriptLevel::SCRIPT_DBG)) { ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_DBG.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "LOG_TYPE_WAR", log4cxx::ScriptLevel::SCRIPT_WAR)) { ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.LOG_TYPE_WAR.\n"); } if(PyModule_AddIntConstant(this->getScript().getModule(), "NEXT_ONLY", KBE_NEXT_ONLY)) { ERROR_MSG( "EntityApp::installPyModules: Unable to set KBEngine.NEXT_ONLY.\n"); } onInstallPyModules(); return true; }
//------------------------------------------------------------------------------------- void Base::addPersistentsDataToStream(uint32 flags, MemoryStream* s) { std::vector<ENTITY_PROPERTY_UID> log; // 再将base中存储属性取出 PyObject* pydict = PyObject_GetAttrString(this, "__dict__"); // 先将celldata中的存储属性取出 ScriptDefModule::PROPERTYDESCRIPTION_MAP& propertyDescrs = scriptModule_->getPersistentPropertyDescriptions(); ScriptDefModule::PROPERTYDESCRIPTION_MAP::const_iterator iter = propertyDescrs.begin(); if(scriptModule_->hasCell()) { addPositionAndDirectionToStream(*s); } for(; iter != propertyDescrs.end(); iter++) { PropertyDescription* propertyDescription = iter->second; std::vector<ENTITY_PROPERTY_UID>::const_iterator finditer = std::find(log.begin(), log.end(), propertyDescription->getUType()); if(finditer != log.end()) continue; const char* attrname = propertyDescription->getName(); if(propertyDescription->isPersistent() && (flags & propertyDescription->getFlags()) > 0) { PyObject *key = PyUnicode_FromString(attrname); if(cellDataDict_ != NULL && PyDict_Contains(cellDataDict_, key) > 0) { PyObject* pyVal = PyDict_GetItemString(cellDataDict_, attrname); if(!propertyDescription->getDataType()->isSameType(pyVal)) { CRITICAL_MSG(fmt::format("{}::addPersistentsDataToStream: {} persistent[{}] type(curr_py: {} != {}) is error.\n", this->scriptName(), this->id(), attrname, (pyVal ? pyVal->ob_type->tp_name : "unknown"), propertyDescription->getDataType()->getName())); } else { (*s) << propertyDescription->getUType(); log.push_back(propertyDescription->getUType()); propertyDescription->addPersistentToStream(s, pyVal); DEBUG_PERSISTENT_PROPERTY("addCellPersistentsDataToStream", attrname); } } else if(PyDict_Contains(pydict, key) > 0) { PyObject* pyVal = PyDict_GetItem(pydict, key); if(!propertyDescription->getDataType()->isSameType(pyVal)) { CRITICAL_MSG(fmt::format("{}::addPersistentsDataToStream: {} persistent[{}] type(curr_py: {} != {}) is error.\n", this->scriptName(), this->id(), attrname, (pyVal ? pyVal->ob_type->tp_name : "unknown"), propertyDescription->getDataType()->getName())); } else { (*s) << propertyDescription->getUType(); log.push_back(propertyDescription->getUType()); propertyDescription->addPersistentToStream(s, pyVal); DEBUG_PERSISTENT_PROPERTY("addBasePersistentsDataToStream", attrname); } } else { CRITICAL_MSG(fmt::format("{}::addPersistentsDataToStream: {} not found Persistent[{}].\n", this->scriptName(), this->id(), attrname)); } Py_DECREF(key); } SCRIPT_ERROR_CHECK(); } Py_XDECREF(pydict); SCRIPT_ERROR_CHECK(); }
static PyObject *UnaryPredicate1D_name_get(BPy_UnaryPredicate1D *self, void *UNUSED(closure)) { return PyUnicode_FromString(Py_TYPE(self)->tp_name); }
static PyObject * record_repr(ApgRecordObject *v) { Py_ssize_t i, n; PyObject *keys_iter; _PyUnicodeWriter writer; n = Py_SIZE(v); assert(n > 0); keys_iter = PyObject_GetIter(v->mapping); if (keys_iter == NULL) { return NULL; } i = Py_ReprEnter((PyObject *)v); if (i != 0) { Py_DECREF(keys_iter); return i > 0 ? PyUnicode_FromString("<Record ...>") : NULL; } _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; writer.min_length = 12; /* <Record a=1> */ if (_PyUnicodeWriter_WriteASCIIString(&writer, "<Record ", 8) < 0) { goto error; } for (i = 0; i < n; ++i) { PyObject *key; PyObject *key_repr; PyObject *val_repr; if (i > 0) { if (_PyUnicodeWriter_WriteChar(&writer, ' ') < 0) { goto error; } } if (Py_EnterRecursiveCall(" while getting the repr of a record")) { goto error; } val_repr = PyObject_Repr(v->ob_item[i]); Py_LeaveRecursiveCall(); if (val_repr == NULL) { goto error; } key = PyIter_Next(keys_iter); if (key == NULL) { Py_DECREF(val_repr); PyErr_SetString(PyExc_RuntimeError, "invalid record mapping"); goto error; } key_repr = PyObject_Str(key); Py_DECREF(key); if (key_repr == NULL) { Py_DECREF(val_repr); goto error; } if (_PyUnicodeWriter_WriteStr(&writer, key_repr) < 0) { Py_DECREF(key_repr); Py_DECREF(val_repr); goto error; } Py_DECREF(key_repr); if (_PyUnicodeWriter_WriteChar(&writer, '=') < 0) { Py_DECREF(val_repr); goto error; } if (_PyUnicodeWriter_WriteStr(&writer, val_repr) < 0) { Py_DECREF(val_repr); goto error; } Py_DECREF(val_repr); } writer.overallocate = 0; if (_PyUnicodeWriter_WriteChar(&writer, '>') < 0) { goto error; } Py_DECREF(keys_iter); Py_ReprLeave((PyObject *)v); return _PyUnicodeWriter_Finish(&writer); error: Py_DECREF(keys_iter); _PyUnicodeWriter_Dealloc(&writer); Py_ReprLeave((PyObject *)v); return NULL; }
static PyObject * fortran_getattr(PyFortranObject *fp, char *name) { int i,j,k,flag; if (fp->dict != NULL) { PyObject *v = PyDict_GetItemString(fp->dict, name); if (v != NULL) { Py_INCREF(v); return v; } } for (i=0,j=1;i<fp->len && (j=strcmp(name,fp->defs[i].name));i++); if (j==0) if (fp->defs[i].rank!=-1) { /* F90 allocatable array */ if (fp->defs[i].func==NULL) return NULL; for(k=0;k<fp->defs[i].rank;++k) fp->defs[i].dims.d[k]=-1; save_def = &fp->defs[i]; (*(fp->defs[i].func))(&fp->defs[i].rank,fp->defs[i].dims.d,set_data,&flag); if (flag==2) k = fp->defs[i].rank + 1; else k = fp->defs[i].rank; if (fp->defs[i].data !=NULL) { /* array is allocated */ PyObject *v = PyArray_New(&PyArray_Type, k, fp->defs[i].dims.d, fp->defs[i].type, NULL, fp->defs[i].data, 0, NPY_ARRAY_FARRAY, NULL); if (v==NULL) return NULL; /* Py_INCREF(v); */ return v; } else { /* array is not allocated */ Py_RETURN_NONE; } } if (strcmp(name,"__dict__")==0) { Py_INCREF(fp->dict); return fp->dict; } if (strcmp(name,"__doc__")==0) { #if PY_VERSION_HEX >= 0x03000000 PyObject *s = PyUnicode_FromString(""), *s2, *s3; for (i=0;i<fp->len;i++) { s2 = fortran_doc(fp->defs[i]); s3 = PyUnicode_Concat(s, s2); Py_DECREF(s2); Py_DECREF(s); s = s3; } #else PyObject *s = PyString_FromString(""); for (i=0;i<fp->len;i++) PyString_ConcatAndDel(&s,fortran_doc(fp->defs[i])); #endif if (PyDict_SetItemString(fp->dict, name, s)) return NULL; return s; } if ((strcmp(name,"_cpointer")==0) && (fp->len==1)) { PyObject *cobj = F2PyCapsule_FromVoidPtr((void *)(fp->defs[0].data),NULL); if (PyDict_SetItemString(fp->dict, name, cobj)) return NULL; return cobj; } #if PY_VERSION_HEX >= 0x03000000 if (1) { PyObject *str, *ret; str = PyUnicode_FromString(name); ret = PyObject_GenericGetAttr((PyObject *)fp, str); Py_DECREF(str); return ret; } #else return Py_FindMethod(fortran_methods, (PyObject *)fp, name); #endif }
static void __Pyx_AddTraceback(const char *funcname, int __pyx_clineno, int __pyx_lineno, const char *__pyx_filename) { PyObject *py_srcfile = 0; PyObject *py_funcname = 0; PyObject *py_globals = 0; PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(__pyx_filename); #else py_srcfile = PyUnicode_FromString(__pyx_filename); #endif if (!py_srcfile) goto bad; if (__pyx_clineno) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, __pyx_clineno); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_globals = PyModule_GetDict(__pyx_m); if (!py_globals) goto bad; py_code = PyCode_New( 0, /*int argcount,*/ #if PY_MAJOR_VERSION >= 3 0, /*int kwonlyargcount,*/ #endif 0, /*int nlocals,*/ 0, /*int stacksize,*/ 0, /*int flags,*/ __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ __pyx_lineno, /*int firstlineno,*/ __pyx_empty_bytes /*PyObject *lnotab*/ ); if (!py_code) goto bad; py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ py_globals, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = __pyx_lineno; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); Py_XDECREF(py_code); Py_XDECREF(py_frame); }
/* 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); } #ifdef MS_WINDOWS /* Windows console IO is always UTF-8 encoded */ if (PyWindowsConsoleIO_Check(raw)) encoding = "utf-8"; #endif text = PyUnicode_FromString(name); if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0) goto error; res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL); 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 PyObject * io_open(PyObject *self, PyObject *args, PyObject *kwds) { char *kwlist[] = {"file", "mode", "buffering", "encoding", "errors", "newline", "closefd", NULL}; PyObject *file; char *mode = "r"; int buffering = -1, closefd = 1; char *encoding = NULL, *errors = NULL, *newline = NULL; unsigned i; int reading = 0, writing = 0, appending = 0, updating = 0; int text = 0, binary = 0, universal = 0; char rawmode[5], *m; int line_buffering, isatty; PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist, &file, &mode, &buffering, &encoding, &errors, &newline, &closefd)) { return NULL; } if (!PyUnicode_Check(file) && !PyBytes_Check(file) && !PyNumber_Check(file)) { PyObject *repr = PyObject_Repr(file); if (repr != NULL) { PyErr_Format(PyExc_TypeError, "invalid file: %s", PyString_AS_STRING(repr)); Py_DECREF(repr); } return NULL; } /* Decode mode */ for (i = 0; i < strlen(mode); i++) { char c = mode[i]; switch (c) { case 'r': reading = 1; break; case 'w': writing = 1; break; case 'a': appending = 1; break; case '+': updating = 1; break; case 't': text = 1; break; case 'b': binary = 1; break; case 'U': universal = 1; reading = 1; break; default: goto invalid_mode; } /* c must not be duplicated */ if (strchr(mode+i+1, c)) { invalid_mode: PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode); return NULL; } } m = rawmode; if (reading) *(m++) = 'r'; if (writing) *(m++) = 'w'; if (appending) *(m++) = 'a'; if (updating) *(m++) = '+'; *m = '\0'; /* Parameters validation */ if (universal) { if (writing || appending) { PyErr_SetString(PyExc_ValueError, "can't use U and writing mode at once"); return NULL; } reading = 1; } if (text && binary) { PyErr_SetString(PyExc_ValueError, "can't have text and binary mode at once"); return NULL; } if (reading + writing + appending > 1) { PyErr_SetString(PyExc_ValueError, "must have exactly one of read/write/append mode"); return NULL; } if (binary && encoding != NULL) { PyErr_SetString(PyExc_ValueError, "binary mode doesn't take an encoding argument"); return NULL; } if (binary && errors != NULL) { PyErr_SetString(PyExc_ValueError, "binary mode doesn't take an errors argument"); return NULL; } if (binary && newline != NULL) { PyErr_SetString(PyExc_ValueError, "binary mode doesn't take a newline argument"); return NULL; } /* Create the Raw file stream */ raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type, "Osi", file, rawmode, closefd); if (raw == NULL) return NULL; modeobj = PyUnicode_FromString(mode); if (modeobj == NULL) goto error; /* buffering */ { PyObject *res = PyObject_CallMethod(raw, "isatty", NULL); if (res == NULL) goto error; isatty = PyLong_AsLong(res); Py_DECREF(res); if (isatty == -1 && PyErr_Occurred()) goto error; } if (buffering == 1 || (buffering < 0 && isatty)) { buffering = -1; line_buffering = 1; } else line_buffering = 0; if (buffering < 0) { buffering = DEFAULT_BUFFER_SIZE; #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE { struct stat st; long fileno; PyObject *res = PyObject_CallMethod(raw, "fileno", NULL); if (res == NULL) goto error; fileno = PyInt_AsLong(res); Py_DECREF(res); if (fileno == -1 && PyErr_Occurred()) goto error; if (fstat(fileno, &st) >= 0 && st.st_blksize > 1) buffering = st.st_blksize; } #endif } if (buffering < 0) { PyErr_SetString(PyExc_ValueError, "invalid buffering size"); goto error; } /* if not buffering, returns the raw file object */ if (buffering == 0) { if (!binary) { PyErr_SetString(PyExc_ValueError, "can't have unbuffered text I/O"); goto error; } Py_DECREF(modeobj); return raw; } /* wraps into a buffered file */ { PyObject *Buffered_class; if (updating) Buffered_class = (PyObject *)&PyBufferedRandom_Type; else if (writing || appending) Buffered_class = (PyObject *)&PyBufferedWriter_Type; else if (reading) Buffered_class = (PyObject *)&PyBufferedReader_Type; else { PyErr_Format(PyExc_ValueError, "unknown mode: '%s'", mode); goto error; } buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering); } Py_CLEAR(raw); if (buffer == NULL) goto error; /* if binary, returns the buffered file */ if (binary) { Py_DECREF(modeobj); return buffer; } /* wraps into a TextIOWrapper */ wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type, "Osssi", buffer, encoding, errors, newline, line_buffering); Py_CLEAR(buffer); if (wrapper == NULL) goto error; if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0) goto error; Py_DECREF(modeobj); return wrapper; error: Py_XDECREF(raw); Py_XDECREF(modeobj); Py_XDECREF(buffer); Py_XDECREF(wrapper); return NULL; }
/* Retrieves the size of the file object * Make sure to hold the GIL state before calling this function * Returns 1 if successful or -1 on error */ int pyfshfs_file_object_get_size( PyObject *file_object, size64_t *size, libcerror_error_t **error ) { PyObject *method_name = NULL; PyObject *method_result = NULL; static char *function = "pyfshfs_file_object_get_size"; if( file_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file object.", function ); return( -1 ); } if( size == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid size.", function ); return( -1 ); } #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "get_size" ); #else method_name = PyString_FromString( "get_size" ); #endif PyErr_Clear(); method_result = PyObject_CallMethodObjArgs( file_object, method_name, NULL ); if( PyErr_Occurred() ) { pyfshfs_error_fetch( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to retrieve size of file object.", function ); goto on_error; } if( method_result == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: missing method result.", function ); goto on_error; } if( pyfshfs_integer_unsigned_copy_to_64bit( method_result, size, error ) != 1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to convert method result into size of file object.", function ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( method_name ); return( 1 ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); }
static PyObject * tuplerepr(PyTupleObject *v) { Py_ssize_t i, n; PyObject *s = NULL; _PyAccu acc; static PyObject *sep = NULL; n = Py_SIZE(v); if (n == 0) return PyUnicode_FromString("()"); if (sep == NULL) { sep = PyUnicode_FromString(", "); if (sep == NULL) return NULL; } /* While not mutable, it is still possible to end up with a cycle in a tuple through an object that stores itself within a tuple (and thus infinitely asks for the repr of itself). This should only be possible within a type. */ i = Py_ReprEnter((PyObject *)v); if (i != 0) { return i > 0 ? PyUnicode_FromString("(...)") : NULL; } if (_PyAccu_Init(&acc)) goto error; s = PyUnicode_FromString("("); if (s == NULL || _PyAccu_Accumulate(&acc, s)) goto error; Py_CLEAR(s); /* Do repr() on each element. */ for (i = 0; i < n; ++i) { if (Py_EnterRecursiveCall(" while getting the repr of a tuple")) goto error; s = PyObject_Repr(v->ob_item[i]); Py_LeaveRecursiveCall(); if (i > 0 && _PyAccu_Accumulate(&acc, sep)) goto error; if (s == NULL || _PyAccu_Accumulate(&acc, s)) goto error; Py_CLEAR(s); } if (n > 1) s = PyUnicode_FromString(")"); else s = PyUnicode_FromString(",)"); if (s == NULL || _PyAccu_Accumulate(&acc, s)) goto error; Py_CLEAR(s); Py_ReprLeave((PyObject *)v); return _PyAccu_Finish(&acc); error: _PyAccu_Destroy(&acc); Py_XDECREF(s); Py_ReprLeave((PyObject *)v); return NULL; }
/* Reads a buffer from the file object * Make sure to hold the GIL state before calling this function * Returns the number of bytes read if successful, or -1 on error */ ssize_t pyfshfs_file_object_read_buffer( PyObject *file_object, uint8_t *buffer, size_t size, libcerror_error_t **error ) { PyObject *argument_size = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; char *safe_buffer = NULL; static char *function = "pyfshfs_file_object_read_buffer"; Py_ssize_t safe_read_count = 0; ssize_t read_count = 0; int result = 0; if( file_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file object.", function ); return( -1 ); } if( buffer == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid buffer.", function ); return( -1 ); } if( size > (size_t) SSIZE_MAX ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid size value exceeds maximum.", function ); return( -1 ); } if( size > 0 ) { #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "read" ); #else method_name = PyString_FromString( "read" ); #endif argument_size = PyLong_FromSize_t( size ); PyErr_Clear(); method_result = PyObject_CallMethodObjArgs( file_object, method_name, argument_size, NULL ); if( PyErr_Occurred() ) { pyfshfs_error_fetch( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_READ_FAILED, "%s: unable to read from file object.", function ); goto on_error; } if( method_result == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: missing method result.", function ); goto on_error; } #if PY_MAJOR_VERSION >= 3 result = PyObject_IsInstance( method_result, (PyObject *) &PyBytes_Type ); #else result = PyObject_IsInstance( method_result, (PyObject *) &PyString_Type ); #endif if( result == -1 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_GET_FAILED, "%s: unable to determine if method result is a binary string object.", function ); goto on_error; } else if( result == 0 ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE, "%s: invalid method result value is not a binary string object.", function ); goto on_error; } #if PY_MAJOR_VERSION >= 3 result = PyBytes_AsStringAndSize( method_result, &safe_buffer, &safe_read_count ); #else result = PyString_AsStringAndSize( method_result, &safe_buffer, &safe_read_count ); #endif if( result == -1 ) { pyfshfs_error_fetch( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_READ_FAILED, "%s: unable to read from file object.", function ); goto on_error; } if( safe_read_count > (Py_ssize_t) SSIZE_MAX ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid read count value exceeds maximum.", function ); goto on_error; } read_count = (ssize_t) safe_read_count; if( memory_copy( buffer, safe_buffer, read_count ) == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_MEMORY, LIBCERROR_MEMORY_ERROR_COPY_FAILED, "%s: unable to data to buffer.", function ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( argument_size ); Py_DecRef( method_name ); } return( read_count ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( argument_size != NULL ) { Py_DecRef( argument_size ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); }
static PyObject* pyLoadObj(PyObject* self, PyObject* args) { PyObject *rtndict, *pyshapes, *pymaterials, *current, *meshobj; char const* filename; char *current_name; vectd vect; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if(!PyArg_ParseTuple(args, "s", &filename)) return NULL; tinyobj::LoadObj(shapes, materials, filename); pyshapes = PyDict_New(); pymaterials = PyDict_New(); rtndict = PyDict_New(); for (std::vector<tinyobj::shape_t>::iterator shape = shapes.begin() ; shape != shapes.end(); shape++) { meshobj = PyDict_New(); tinyobj::mesh_t cm = (*shape).mesh; for (int i = 0; i <= 4; i++ ) { current = PyList_New(0); switch(i) { case 0: current_name = "positions"; vect = vectd(cm.positions.begin(), cm.positions.end()); break; case 1: current_name = "normals"; vect = vectd(cm.normals.begin(), cm.normals.end()); break; case 2: current_name = "texcoords"; vect = vectd(cm.texcoords.begin(), cm.texcoords.end()); break; case 3: current_name = "indicies"; vect = vectd(cm.indices.begin(), cm.indices.end()); break; case 4: current_name = "material_ids"; vect = vectd(cm.material_ids.begin(), cm.material_ids.end()); break; } for (vectd::iterator it = vect.begin() ; it != vect.end(); it++) { PyList_Insert(current, it - vect.begin(), PyFloat_FromDouble(*it)); } PyDict_SetItemString(meshobj, current_name, current); } PyDict_SetItemString(pyshapes, (*shape).name.c_str(), meshobj); } for (std::vector<tinyobj::material_t>::iterator mat = materials.begin() ; mat != materials.end(); mat++) { PyObject *matobj = PyDict_New(); PyObject *unknown_parameter = PyDict_New(); for (std::map<std::string, std::string>::iterator p = (*mat).unknown_parameter.begin() ; p != (*mat).unknown_parameter.end(); ++p) { PyDict_SetItemString(unknown_parameter, p->first.c_str(), PyUnicode_FromString(p->second.c_str())); } PyDict_SetItemString(matobj, "shininess", PyFloat_FromDouble((*mat).shininess)); PyDict_SetItemString(matobj, "ior", PyFloat_FromDouble((*mat).ior)); PyDict_SetItemString(matobj, "dissolve", PyFloat_FromDouble((*mat).dissolve)); PyDict_SetItemString(matobj, "illum", PyLong_FromLong((*mat).illum)); PyDict_SetItemString(matobj, "ambient_texname", PyUnicode_FromString((*mat).ambient_texname.c_str())); PyDict_SetItemString(matobj, "diffuse_texname", PyUnicode_FromString((*mat).diffuse_texname.c_str())); PyDict_SetItemString(matobj, "specular_texname", PyUnicode_FromString((*mat).specular_texname.c_str())); PyDict_SetItemString(matobj, "specular_highlight_texname", PyUnicode_FromString((*mat).specular_highlight_texname.c_str())); PyDict_SetItemString(matobj, "bump_texname", PyUnicode_FromString((*mat).bump_texname.c_str())); PyDict_SetItemString(matobj, "displacement_texname", PyUnicode_FromString((*mat).displacement_texname.c_str())); PyDict_SetItemString(matobj, "alpha_texname", PyUnicode_FromString((*mat).alpha_texname.c_str())); PyDict_SetItemString(matobj, "ambient", pyTupleFromfloat3((*mat).ambient)); PyDict_SetItemString(matobj, "diffuse", pyTupleFromfloat3((*mat).diffuse)); PyDict_SetItemString(matobj, "specular", pyTupleFromfloat3((*mat).specular)); PyDict_SetItemString(matobj, "transmittance", pyTupleFromfloat3((*mat).transmittance)); PyDict_SetItemString(matobj, "emission", pyTupleFromfloat3((*mat).emission)); PyDict_SetItemString(matobj, "unknown_parameter", unknown_parameter); PyDict_SetItemString(pymaterials, (*mat).name.c_str(), matobj); } PyDict_SetItemString(rtndict, "shapes", pyshapes); PyDict_SetItemString(rtndict, "materials", pymaterials); return rtndict; }
/* Seeks a certain offset within the file object * Make sure to hold the GIL state before calling this function * Returns 1 if successful or -1 on error */ int pyfshfs_file_object_seek_offset( PyObject *file_object, off64_t offset, int whence, libcerror_error_t **error ) { PyObject *argument_offset = NULL; PyObject *argument_whence = NULL; PyObject *method_name = NULL; PyObject *method_result = NULL; static char *function = "pyfshfs_file_object_seek_offset"; if( file_object == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE, "%s: invalid file object.", function ); return( -1 ); } #if defined( HAVE_LONG_LONG ) if( offset > (off64_t) INT64_MAX ) #else if( offset > (off64_t) LONG_MAX ) #endif { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM, "%s: invalid offset value exceeds maximum.", function ); return( -1 ); } if( ( whence != SEEK_CUR ) && ( whence != SEEK_END ) && ( whence != SEEK_SET ) ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_ARGUMENTS, LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE, "%s: unsupported whence.", function ); return( -1 ); } #if PY_MAJOR_VERSION >= 3 method_name = PyUnicode_FromString( "seek" ); #else method_name = PyString_FromString( "seek" ); #endif #if defined( HAVE_LONG_LONG ) argument_offset = PyLong_FromLongLong( (PY_LONG_LONG) offset ); #else argument_offset = PyLong_FromLongLong( (long) offset ); #endif #if PY_MAJOR_VERSION >= 3 argument_whence = PyLong_FromLong( (long) whence ); #else argument_whence = PyInt_FromLong( (long) whence ); #endif PyErr_Clear(); method_result = PyObject_CallMethodObjArgs( file_object, method_name, argument_offset, argument_whence, NULL ); if( PyErr_Occurred() ) { pyfshfs_error_fetch( error, LIBCERROR_ERROR_DOMAIN_IO, LIBCERROR_IO_ERROR_SEEK_FAILED, "%s: unable to seek in file object.", function ); goto on_error; } if( method_result == NULL ) { libcerror_error_set( error, LIBCERROR_ERROR_DOMAIN_RUNTIME, LIBCERROR_RUNTIME_ERROR_VALUE_MISSING, "%s: missing method result.", function ); goto on_error; } Py_DecRef( method_result ); Py_DecRef( argument_whence ); Py_DecRef( argument_offset ); Py_DecRef( method_name ); return( 1 ); on_error: if( method_result != NULL ) { Py_DecRef( method_result ); } if( argument_whence != NULL ) { Py_DecRef( argument_whence ); } if( argument_offset != NULL ) { Py_DecRef( argument_offset ); } if( method_name != NULL ) { Py_DecRef( method_name ); } return( -1 ); }
static PyObject * normalizeUserObj(PyObject *obj) { PyCFunctionObject *fn; if (!PyCFunction_Check(obj)) { Py_INCREF(obj); return obj; } /* Replace built-in function objects with a descriptive string because of built-in methods -- keeping a reference to __self__ is probably not a good idea. */ fn = (PyCFunctionObject *)obj; if (fn->m_self == NULL) { /* built-in function: look up the module name */ PyObject *mod = fn->m_module; PyObject *modname = NULL; if (mod != NULL) { if (PyUnicode_Check(mod)) { modname = mod; Py_INCREF(modname); } else if (PyModule_Check(mod)) { modname = PyModule_GetNameObject(mod); if (modname == NULL) PyErr_Clear(); } } if (modname != NULL) { if (!_PyUnicode_EqualToASCIIString(modname, "builtins")) { PyObject *result; result = PyUnicode_FromFormat("<%U.%s>", modname, fn->m_ml->ml_name); Py_DECREF(modname); return result; } Py_DECREF(modname); } return PyUnicode_FromFormat("<%s>", fn->m_ml->ml_name); } else { /* built-in method: try to return repr(getattr(type(__self__), __name__)) */ PyObject *self = fn->m_self; PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name); PyObject *modname = fn->m_module; if (name != NULL) { PyObject *mo = _PyType_Lookup(Py_TYPE(self), name); Py_XINCREF(mo); Py_DECREF(name); if (mo != NULL) { PyObject *res = PyObject_Repr(mo); Py_DECREF(mo); if (res != NULL) return res; } } /* Otherwise, use __module__ */ PyErr_Clear(); if (modname != NULL && PyUnicode_Check(modname)) return PyUnicode_FromFormat("<built-in method %S.%s>", modname, fn->m_ml->ml_name); else return PyUnicode_FromFormat("<built-in method %s>", fn->m_ml->ml_name); } }
static void initerr(perrdetail *err_ret, const char *filename) { initerr_object(err_ret, PyUnicode_FromString(filename)); }
/** * Set one or more options in a decoder instance. * * Handled options are removed from the hash. * * @param di Decoder instance. * @param options A GHashTable of options to set. * * @return SRD_OK upon success, a (negative) error code otherwise. */ SRD_API int srd_inst_option_set(struct srd_decoder_inst *di, GHashTable *options) { PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval; PyObject *py_optlist, *py_classval; Py_UNICODE *py_ustr; unsigned long long int val_ull; int num_optkeys, ret, size, i; char *key, *value; if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) { /* Decoder has no options. */ if (g_hash_table_size(options) == 0) { /* No options provided. */ return SRD_OK; } else { srd_err("Protocol decoder has no options."); return SRD_ERR_ARG; } return SRD_OK; } ret = SRD_ERR_PYTHON; key = NULL; py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL; py_optlist = py_classval = NULL; py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options"); /* All of these are synthesized objects, so they're good. */ py_dec_optkeys = PyDict_Keys(py_dec_options); num_optkeys = PyList_Size(py_dec_optkeys); if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options"))) goto err_out; for (i = 0; i < num_optkeys; i++) { /* Get the default class value for this option. */ py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key); if (!(py_optlist = PyDict_GetItemString(py_dec_options, key))) goto err_out; if (!(py_classval = PyList_GetItem(py_optlist, 1))) goto err_out; if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) { srd_err("Options of type %s are not yet supported.", Py_TYPE(py_classval)->tp_name); goto err_out; } if ((value = g_hash_table_lookup(options, key))) { /* An override for this option was provided. */ if (PyUnicode_Check(py_classval)) { if (!(py_optval = PyUnicode_FromString(value))) { /* Some UTF-8 encoding error. */ PyErr_Clear(); goto err_out; } } else if (PyLong_Check(py_classval)) { if (!(py_optval = PyLong_FromString(value, NULL, 0))) { /* ValueError Exception */ PyErr_Clear(); srd_err("Option %s has invalid value " "%s: expected integer.", key, value); goto err_out; } } g_hash_table_remove(options, key); } else { /* Use the class default for this option. */ if (PyUnicode_Check(py_classval)) { /* Make a brand new copy of the string. */ py_ustr = PyUnicode_AS_UNICODE(py_classval); size = PyUnicode_GET_SIZE(py_classval); py_optval = PyUnicode_FromUnicode(py_ustr, size); } else if (PyLong_Check(py_classval)) { /* Make a brand new copy of the integer. */ val_ull = PyLong_AsUnsignedLongLong(py_classval); if (val_ull == (unsigned long long)-1) { /* OverFlowError exception */ PyErr_Clear(); srd_err("Invalid integer value for %s: " "expected integer.", key); goto err_out; } if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull))) goto err_out; } } /* * If we got here, py_optval holds a known good new reference * to the instance option to set. */ if (PyDict_SetItemString(py_di_options, key, py_optval) == -1) goto err_out; } ret = SRD_OK; err_out: Py_XDECREF(py_optlist); Py_XDECREF(py_di_options); Py_XDECREF(py_dec_optkeys); Py_XDECREF(py_dec_options); g_free(key); if (PyErr_Occurred()) srd_exception_catch("Stray exception in srd_inst_option_set()."); return ret; }