static PyObject * get_dataset(PyObject *self, PyObject *args) { int i, j, k, num_atom; double symprec; SpglibDataset *dataset; PyArrayObject* lattice_vectors; PyArrayObject* atomic_positions; PyArrayObject* atom_types; PyObject* array, *vec, *mat, *rot, *trans, *wyckoffs, *equiv_atoms; double *p_lattice; double *p_positions; double lattice[3][3]; double (*positions)[3]; int *types_int; int *types; if (!PyArg_ParseTuple(args, "OOOd", &lattice_vectors, &atomic_positions, &atom_types, &symprec)) { return NULL; } p_lattice = (double(*))lattice_vectors->data; p_positions = (double(*))atomic_positions->data; num_atom = atom_types->dimensions[0]; positions = (double(*)[3]) malloc(sizeof(double[3]) * num_atom); types_int = (int*)atom_types->data; types = (int*) malloc(sizeof(int) * num_atom); set_spglib_cell(lattice, positions, types, num_atom, p_lattice, p_positions, types_int); dataset = spg_get_dataset(lattice, positions, types, num_atom, symprec); free(types); free(positions); array = PyList_New(10); /* Space group number, international symbol, hall symbol */ PyList_SetItem(array, 0, PyInt_FromLong((long) dataset->spacegroup_number)); PyList_SetItem(array, 1, PyString_FromString(dataset->international_symbol)); PyList_SetItem(array, 2, PyInt_FromLong((long) dataset->hall_number)); PyList_SetItem(array, 3, PyString_FromString(dataset->hall_symbol)); /* Transformation matrix */ mat = PyList_New(3); for (i = 0; i < 3; i++) { vec = PyList_New(3); for (j = 0; j < 3; j++) { PyList_SetItem(vec, j, PyFloat_FromDouble(dataset->transformation_matrix[i][j])); } PyList_SetItem(mat, i, vec); } PyList_SetItem(array, 4, mat); /* Origin shift */ vec = PyList_New(3); for (i = 0; i < 3; i++) { PyList_SetItem(vec, i, PyFloat_FromDouble(dataset->origin_shift[i])); } PyList_SetItem(array, 5, vec); /* Rotation matrices */ rot = PyList_New(dataset->n_operations); for (i = 0; i < dataset->n_operations; i++) { mat = PyList_New(3); for (j = 0; j < 3; j++) { vec = PyList_New(3); for (k = 0; k < 3; k++) { PyList_SetItem(vec, k, PyInt_FromLong((long) dataset->rotations[i][j][k])); } PyList_SetItem(mat, j, vec); } PyList_SetItem(rot, i, mat); } PyList_SetItem(array, 6, rot); /* Translation vectors */ trans = PyList_New(dataset->n_operations); for (i = 0; i < dataset->n_operations; i++) { vec = PyList_New(3); for (j = 0; j < 3; j++) { PyList_SetItem(vec, j, PyFloat_FromDouble(dataset->translations[i][j])); } PyList_SetItem(trans, i, vec); } PyList_SetItem(array, 7, trans); /* Wyckoff letters, Equivalent atoms */ wyckoffs = PyList_New(dataset->n_atoms); equiv_atoms = PyList_New(dataset->n_atoms); for (i = 0; i < dataset->n_atoms; i++) { PyList_SetItem(wyckoffs, i, PyInt_FromLong((long) dataset->wyckoffs[i])); PyList_SetItem(equiv_atoms, i, PyInt_FromLong((long) dataset->equivalent_atoms[i])); } PyList_SetItem(array, 8, wyckoffs); PyList_SetItem(array, 9, equiv_atoms); spg_free_dataset(dataset); return array; }
void *uwsgi_request_subhandler_pump(struct wsgi_request *wsgi_req, struct uwsgi_app *wi) { PyObject *zero; int i; PyObject *pydictkey, *pydictvalue; char *port = memchr(wsgi_req->host, ':', wsgi_req->host_len); if (port) { zero = PyString_FromStringAndSize(wsgi_req->host, (port-wsgi_req->host)); PyDict_SetItemString(wsgi_req->async_environ, "server_name", zero); Py_DECREF(zero); zero = PyString_FromStringAndSize(port, wsgi_req->host_len-((port+1)-wsgi_req->host)); PyDict_SetItemString(wsgi_req->async_environ, "server_port", zero); Py_DECREF(zero); } else { zero = PyString_FromStringAndSize(wsgi_req->host, wsgi_req->host_len); PyDict_SetItemString(wsgi_req->async_environ, "server_name", zero); Py_DECREF(zero); zero = PyString_FromStringAndSize("80", 2); PyDict_SetItemString(wsgi_req->async_environ, "server_port", zero); Py_DECREF(zero); } zero = PyString_FromStringAndSize(wsgi_req->remote_addr, wsgi_req->remote_addr_len); PyDict_SetItemString(wsgi_req->async_environ, "remote_addr", zero); Py_DECREF(zero); zero = PyString_FromStringAndSize(wsgi_req->path_info, wsgi_req->path_info_len); PyDict_SetItemString(wsgi_req->async_environ, "uri", zero); Py_DECREF(zero); if (wsgi_req->query_string_len > 0) { zero = PyString_FromStringAndSize(wsgi_req->query_string, wsgi_req->query_string_len); PyDict_SetItemString(wsgi_req->async_environ, "query_string", zero); Py_DECREF(zero); } zero = PyString_FromStringAndSize(uwsgi_lower(wsgi_req->method, wsgi_req->method_len), wsgi_req->method_len); PyDict_SetItemString(wsgi_req->async_environ, "method", zero); Py_DECREF(zero); if (wsgi_req->post_cl > 0) { PyDict_SetItemString(wsgi_req->async_environ, "content_length", PyInt_FromLong(wsgi_req->post_cl)); if (wsgi_req->content_type_len > 0) { zero = PyString_FromStringAndSize(wsgi_req->content_type, wsgi_req->content_type_len); PyDict_SetItemString(wsgi_req->async_environ, "content_type", zero); Py_DECREF(zero); } } PyObject *headers = PyDict_New(); for (i = 0; i < wsgi_req->var_cnt; i += 2) { #ifdef UWSGI_DEBUG uwsgi_debug("%.*s: %.*s\n", wsgi_req->hvec[i].iov_len, wsgi_req->hvec[i].iov_base, wsgi_req->hvec[i+1].iov_len, wsgi_req->hvec[i+1].iov_base); #endif if (wsgi_req->hvec[i].iov_len < 6) continue; if (!uwsgi_startswith(wsgi_req->hvec[i].iov_base, "HTTP_", 5)) { (void) uwsgi_lower(wsgi_req->hvec[i].iov_base+5, wsgi_req->hvec[i].iov_len-5); #ifdef PYTHREE pydictkey = PyUnicode_DecodeLatin1(wsgi_req->hvec[i].iov_base+5, wsgi_req->hvec[i].iov_len-5, NULL); pydictvalue = PyUnicode_DecodeLatin1(wsgi_req->hvec[i + 1].iov_base, wsgi_req->hvec[i + 1].iov_len, NULL); #else pydictkey = PyString_FromStringAndSize(wsgi_req->hvec[i].iov_base+5, wsgi_req->hvec[i].iov_len-5); pydictvalue = PyString_FromStringAndSize(wsgi_req->hvec[i + 1].iov_base, wsgi_req->hvec[i + 1].iov_len); #endif PyObject *old_value = PyDict_GetItem(headers, pydictkey); if (old_value) { if (PyString_Check(old_value)) { PyObject *new_value = PyList_New(0); PyList_Append(new_value, old_value); old_value = new_value; PyDict_SetItem(headers, pydictkey, old_value); Py_DECREF(old_value); } PyList_Append(old_value, pydictvalue); } else { PyDict_SetItem(headers, pydictkey, pydictvalue); } Py_DECREF(pydictkey); Py_DECREF(pydictvalue); } } PyDict_SetItemString(wsgi_req->async_environ, "headers", headers); Py_DECREF(headers); // create wsgi.input custom object wsgi_req->async_input = (PyObject *) PyObject_New(uwsgi_Input, &uwsgi_InputType); ((uwsgi_Input*)wsgi_req->async_input)->wsgi_req = wsgi_req; PyDict_SetItemString(wsgi_req->async_environ, "body", wsgi_req->async_input); if (wsgi_req->scheme_len > 0) { zero = PyString_FromStringAndSize(wsgi_req->scheme, wsgi_req->scheme_len); } else if (wsgi_req->https_len > 0) { if (!strncasecmp(wsgi_req->https, "on", 2) || wsgi_req->https[0] == '1') { zero = PyString_FromString("https"); } else { zero = PyString_FromString("http"); } } else { zero = PyString_FromString("http"); } PyDict_SetItemString(wsgi_req->async_environ, "scheme", zero); Py_DECREF(zero); wsgi_req->async_app = wi->callable; // export .env only in non-threaded mode if (uwsgi.threads < 2) { PyDict_SetItemString(up.embedded_dict, "env", wsgi_req->async_environ); } PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.version", wi->uwsgi_version); if (uwsgi.cores > 1) { PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.core", PyInt_FromLong(wsgi_req->async_id)); } PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.node", wi->uwsgi_node); // call PyTuple_SetItem(wsgi_req->async_args, 0, wsgi_req->async_environ); return python_call(wsgi_req->async_app, wsgi_req->async_args, uwsgi.catch_exceptions, wsgi_req); }
static PyObject *Py_FindObjects(PyObject *obj, PyObject *args) { PyArrayObject *input = NULL; PyObject *result = NULL, *tuple = NULL, *start = NULL, *end = NULL; PyObject *slc = NULL; int jj; long max_label; maybelong ii, *regions = NULL; if (!PyArg_ParseTuple(args, "O&l", NI_ObjectToInputArray, &input, &max_label)) goto exit; if (max_label < 0) max_label = 0; if (max_label > 0) { if (input->nd > 0) { regions = (maybelong*)malloc(2 * max_label * input->nd * sizeof(maybelong)); } else { regions = (maybelong*)malloc(max_label * sizeof(maybelong)); } if (!regions) { PyErr_NoMemory(); goto exit; } } if (!NI_FindObjects(input, max_label, regions)) goto exit; result = PyList_New(max_label); if (!result) { PyErr_NoMemory(); goto exit; } for(ii = 0; ii < max_label; ii++) { maybelong idx = input->nd > 0 ? 2 * input->nd * ii : ii; if (regions[idx] >= 0) { PyObject *tuple = PyTuple_New(input->nd); if (!tuple) { PyErr_NoMemory(); goto exit; } for(jj = 0; jj < input->nd; jj++) { start = PyLong_FromLong(regions[idx + jj]); end = PyLong_FromLong(regions[idx + jj + input->nd]); if (!start || !end) { PyErr_NoMemory(); goto exit; } slc = PySlice_New(start, end, NULL); if (!slc) { PyErr_NoMemory(); goto exit; } Py_XDECREF(start); Py_XDECREF(end); start = end = NULL; PyTuple_SetItem(tuple, jj, slc); slc = NULL; } PyList_SetItem(result, ii, tuple); tuple = NULL; } else { Py_INCREF(Py_None); PyList_SetItem(result, ii, Py_None); } } Py_INCREF(result); exit: Py_XDECREF(input); Py_XDECREF(result); Py_XDECREF(tuple); Py_XDECREF(start); Py_XDECREF(end); Py_XDECREF(slc); if (regions) free(regions); if (PyErr_Occurred()) { Py_XDECREF(result); return NULL; } else { return result; } }
PyObject *pygrpc_consume_ops(grpc_op *op, size_t nops) { static const int TYPE_INDEX = 0; static const int INITIAL_METADATA_INDEX = 1; static const int TRAILING_METADATA_INDEX = 2; static const int MESSAGE_INDEX = 3; static const int STATUS_INDEX = 4; static const int CANCELLED_INDEX = 5; static const int OPRESULT_LENGTH = 6; PyObject *list; size_t i; size_t j; char *bytes; size_t bytes_size; PyObject *results = PyList_New(nops); if (!results) { return NULL; } for (i = 0; i < nops; ++i) { PyObject *result = PyTuple_Pack(OPRESULT_LENGTH, Py_None, Py_None, Py_None, Py_None, Py_None, Py_None); PyTuple_SetItem(result, TYPE_INDEX, PyInt_FromLong(op[i].op)); switch(op[i].op) { case GRPC_OP_RECV_INITIAL_METADATA: PyTuple_SetItem(result, INITIAL_METADATA_INDEX, list=PyList_New(op[i].data.recv_initial_metadata->count)); for (j = 0; j < op[i].data.recv_initial_metadata->count; ++j) { grpc_metadata md = op[i].data.recv_initial_metadata->metadata[j]; PyList_SetItem(list, j, Py_BuildValue("ss#", md.key, md.value, (Py_ssize_t)md.value_length)); } break; case GRPC_OP_RECV_MESSAGE: if (*op[i].data.recv_message) { pygrpc_byte_buffer_to_bytes( *op[i].data.recv_message, &bytes, &bytes_size); PyTuple_SetItem(result, MESSAGE_INDEX, PyString_FromStringAndSize(bytes, bytes_size)); gpr_free(bytes); } else { PyTuple_SetItem(result, MESSAGE_INDEX, Py_BuildValue("")); } break; case GRPC_OP_RECV_STATUS_ON_CLIENT: PyTuple_SetItem( result, TRAILING_METADATA_INDEX, list = PyList_New(op[i].data.recv_status_on_client.trailing_metadata->count)); for (j = 0; j < op[i].data.recv_status_on_client.trailing_metadata->count; ++j) { grpc_metadata md = op[i].data.recv_status_on_client.trailing_metadata->metadata[j]; PyList_SetItem(list, j, Py_BuildValue("ss#", md.key, md.value, (Py_ssize_t)md.value_length)); } PyTuple_SetItem( result, STATUS_INDEX, Py_BuildValue( "is", *op[i].data.recv_status_on_client.status, *op[i].data.recv_status_on_client.status_details)); break; case GRPC_OP_RECV_CLOSE_ON_SERVER: PyTuple_SetItem( result, CANCELLED_INDEX, PyBool_FromLong(*op[i].data.recv_close_on_server.cancelled)); break; default: break; } pygrpc_discard_op(op[i]); PyList_SetItem(results, i, result); } return results; }
/** * Decode barcode from an image buffer. The supported data structure is DIB. * It is necessary to re-construct input data for barcode detection. */ static PyObject * decodeBuffer(PyObject *self, PyObject *args) { PyObject *o; if (!PyArg_ParseTuple(args, "O", &o)) return NULL; PyObject *ao = PyObject_GetAttrString(o, "__array_struct__"); PyObject *retval; if ((ao == NULL) || !PyCObject_Check(ao)) { PyErr_SetString(PyExc_TypeError, "object does not have array interface"); return NULL; } PyArrayInterface *pai = (PyArrayInterface*)PyCObject_AsVoidPtr(ao); if (pai->two != 2) { PyErr_SetString(PyExc_TypeError, "object does not have array interface"); Py_DECREF(ao); return NULL; } // Construct data with header info and image data char *buffer = (char*)pai->data; // The address of image data int width = pai->shape[1]; // image width int height = pai->shape[0]; // image height int size = pai->strides[0] * pai->shape[0]; // image size = stride * height char *total = (char *)malloc(size + 40); // buffer size = image size + header size memset(total, 0, size + 40); BITMAPINFOHEADER bitmap_info = {40, width, height, 0, 24, 0, size, 0, 0, 0, 0}; memcpy(total, &bitmap_info, 40); // Copy image data to buffer from bottom to top char *data = total + 40; int stride = pai->strides[0]; int i = 1; for (; i <= height; i++) { memcpy(data, buffer + stride * (height - i), stride); data += stride; } // Dynamsoft Barcode Reader initialization __int64 llFormat = (OneD | QR_CODE | PDF417 | DATAMATRIX); int iMaxCount = 0x7FFFFFFF; ReaderOptions ro = {0}; pBarcodeResultArray pResults = NULL; ro.llBarcodeFormat = llFormat; ro.iMaxBarcodesNumPerPage = iMaxCount; printf("width: %d, height: %d, size:%d\n", width, height, size); int iRet = DBR_DecodeBuffer((unsigned char *)total, size + 40, &ro, &pResults); printf("DBR_DecodeBuffer ret: %d\n", iRet); free(total); // Do not forget to release the constructed buffer // Get results int count = pResults->iBarcodeCount; pBarcodeResult* ppBarcodes = pResults->ppBarcodes; pBarcodeResult tmp = NULL; retval = PyList_New(count); // The returned Python object PyObject* result = NULL; i = 0; for (; i < count; i++) { tmp = ppBarcodes[i]; result = PyString_FromString(tmp->pBarcodeData); printf("result: %s\n", tmp->pBarcodeData); PyList_SetItem(retval, i, Py_BuildValue("iN", (int)tmp->llFormat, result)); // Add results to list } // release memory DBR_FreeBarcodeResults(&pResults); Py_DECREF(ao); return retval; }
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs) { static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL}; PyObject* database; int detect_types = 0; PyObject* isolation_level = NULL; PyObject* factory = NULL; int check_same_thread = 1; int cached_statements = 100; double timeout = 5.0; int rc; PyObject* class_attr = NULL; PyObject* class_attr_str = NULL; int is_apsw_connection = 0; PyObject* database_utf8; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|diOiOi", kwlist, &database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements)) { return -1; } self->initialized = 1; spatialite_init(0); self->begin_statement = NULL; self->statement_cache = NULL; self->statements = NULL; self->cursors = NULL; Py_INCREF(Py_None); self->row_factory = Py_None; Py_INCREF(&PyUnicode_Type); self->text_factory = (PyObject*)&PyUnicode_Type; if (PyString_Check(database) || PyUnicode_Check(database)) { if (PyString_Check(database)) { database_utf8 = database; Py_INCREF(database_utf8); } else { database_utf8 = PyUnicode_AsUTF8String(database); if (!database_utf8) { return -1; } } Py_BEGIN_ALLOW_THREADS rc = sqlite3_open(PyString_AsString(database_utf8), &self->db); Py_END_ALLOW_THREADS Py_DECREF(database_utf8); if (rc != SQLITE_OK) { _pysqlite_seterror(self->db, NULL); return -1; } } else { /* Create a pysqlite connection from a APSW connection */ class_attr = PyObject_GetAttrString(database, "__class__"); if (class_attr) { class_attr_str = PyObject_Str(class_attr); if (class_attr_str) { if (strcmp(PyString_AsString(class_attr_str), "<type 'apsw.Connection'>") == 0) { /* In the APSW Connection object, the first entry after * PyObject_HEAD is the sqlite3* we want to get hold of. * Luckily, this is the same layout as we have in our * pysqlite_Connection */ self->db = ((pysqlite_Connection*)database)->db; Py_INCREF(database); self->apsw_connection = database; is_apsw_connection = 1; } } } Py_XDECREF(class_attr_str); Py_XDECREF(class_attr); if (!is_apsw_connection) { PyErr_SetString(PyExc_ValueError, "database parameter must be string or APSW Connection object"); return -1; } } if (!isolation_level) { isolation_level = PyString_FromString(""); if (!isolation_level) { return -1; } } else { Py_INCREF(isolation_level); } self->isolation_level = NULL; pysqlite_connection_set_isolation_level(self, isolation_level); Py_DECREF(isolation_level); self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements); if (PyErr_Occurred()) { return -1; } self->created_statements = 0; self->created_cursors = 0; /* Create lists of weak references to statements/cursors */ self->statements = PyList_New(0); self->cursors = PyList_New(0); if (!self->statements || !self->cursors) { return -1; } /* By default, the Cache class INCREFs the factory in its initializer, and * decrefs it in its deallocator method. Since this would create a circular * reference here, we're breaking it by decrementing self, and telling the * cache class to not decref the factory (self) in its deallocator. */ self->statement_cache->decref_factory = 0; Py_DECREF(self); self->inTransaction = 0; self->detect_types = detect_types; self->timeout = timeout; (void)sqlite3_busy_timeout(self->db, (int)(timeout*1000)); #ifdef WITH_THREAD self->thread_ident = PyThread_get_thread_ident(); #endif self->check_same_thread = check_same_thread; self->function_pinboard = PyDict_New(); if (!self->function_pinboard) { return -1; } self->collations = PyDict_New(); if (!self->collations) { return -1; } self->Warning = pysqlite_Warning; self->Error = pysqlite_Error; self->InterfaceError = pysqlite_InterfaceError; self->DatabaseError = pysqlite_DatabaseError; self->DataError = pysqlite_DataError; self->OperationalError = pysqlite_OperationalError; self->IntegrityError = pysqlite_IntegrityError; self->InternalError = pysqlite_InternalError; self->ProgrammingError = pysqlite_ProgrammingError; self->NotSupportedError = pysqlite_NotSupportedError; return 0; }
/** ******************************************************************************************************* * This function will get a batch of records from the Aeropike DB. * * @param err as_error object * @param self AerospikeClient object * @param py_keys The list of keys * @param batch_policy_p as_policy_batch object * * Returns the record if key exists otherwise NULL. ******************************************************************************************************* */ static PyObject * batch_select_aerospike_batch_get(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char **filter_bins, Py_ssize_t bins_size) { PyObject * py_recs = NULL; as_batch batch; bool batch_initialised = false; // Convert python keys list to as_key ** and add it to as_batch.keys // keys can be specified in PyList or PyTuple if ( py_keys != NULL && PyList_Check(py_keys) ) { Py_ssize_t size = PyList_Size(py_keys); py_recs = PyList_New(size); as_batch_init(&batch, size); // Batch object initialised batch_initialised = true; for ( int i = 0; i < size; i++ ) { PyObject * py_key = PyList_GetItem(py_keys, i); if ( !PyTuple_Check(py_key) ) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple."); goto CLEANUP; } pyobject_to_key(err, py_key, as_batch_keyat(&batch, i)); if ( err->code != AEROSPIKE_OK ) { goto CLEANUP; } } } else if ( py_keys != NULL && PyTuple_Check(py_keys) ) { Py_ssize_t size = PyTuple_Size(py_keys); py_recs = PyList_New(size); as_batch_init(&batch, size); // Batch object initialised batch_initialised = true; for ( int i = 0; i < size; i++ ) { PyObject * py_key = PyTuple_GetItem(py_keys, i); if ( !PyTuple_Check(py_key) ) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple."); goto CLEANUP; } pyobject_to_key(err, py_key, as_batch_keyat(&batch, i)); if ( err->code != AEROSPIKE_OK ) { goto CLEANUP; } } } else { as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple."); goto CLEANUP; } // Invoke C-client API aerospike_batch_get_bins(self->as, err, batch_policy_p, &batch, (const char **) filter_bins, bins_size, (aerospike_batch_read_callback) batch_select_cb, py_recs); CLEANUP: if (batch_initialised == true) { // We should destroy batch object as we are using 'as_batch_init' for initialisation // Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction // is necessary. as_batch_destroy(&batch); } return py_recs; }
static PyObject * PDFfile_new(PyTypeObject *type, PyObject * /*args*/, PyObject * /*kwds*/) { // do not create new object if there is no opened document if (!ScCore->primaryMainWindow()->HaveDoc) { PyErr_SetString(PyExc_SystemError, "Need to open document first"); return NULL; } PDFfile *self; self = (PDFfile *)type->tp_alloc(type, 0); if (self) { // set file attribute self->file = PyString_FromString(""); if (!self->file){ Py_DECREF(self); return NULL; } // set fonts attribute self->fonts = PyList_New(0); if (!self->fonts){ Py_DECREF(self); return NULL; } // set pages attribute self->pages = PyList_New(0); if (self->pages == NULL){ Py_DECREF(self); return NULL; } // set thumbnails attribute self->thumbnails = 0; // set compress attribute self->compress = 0; // set compressmtd attribute self->compressmtd = 0; // set quality attribute self->quality = 0; // set resolution attribute self->resolution = PyInt_FromLong(300); if (!self->resolution){ Py_DECREF(self); return NULL; } // set downsample attribute self->downsample = PyInt_FromLong(0); if (!self->downsample){ Py_DECREF(self); return NULL; } // set bookmarks attribute self->bookmarks = 0; // set binding attribute self->binding = 0; // set presentation attribute self->presentation = 0; // set effval attribute self->effval = PyList_New(0); if (!self->effval){ Py_DECREF(self); return NULL; } // set article attribute self->article = 0; // set encrypt attribute self->encrypt = 0; // set uselpi attribute self->uselpi = 0; self->usespot = 1; self->domulti = 0; // set lpival attribute self->lpival = PyList_New(0); if (!self->lpival){ Py_DECREF(self); return NULL; } // set owner attribute self->owner = PyString_FromString(""); if (!self->owner){ Py_DECREF(self); return NULL; } // set user attribute self->user = PyString_FromString(""); if (!self->user){ Py_DECREF(self); return NULL; } // set aprint attribute self->aprint = 1; // set achange attribute self->achange = 1; // set acopy attribute self->acopy = 1; // set aanot attribute self->aanot = 1; // set version attribute self->version = 14; // set output attribute self->outdst = 0; self->profiles = 0; // bool self->profilei = 0; // bool self->intents = 0; // int - 0 - ? self->intenti = 0; // int - 0 - ? self->noembicc = 0; // bool self->solidpr = PyString_FromString(""); if (!self->solidpr){ Py_DECREF(self); return NULL; } self->imagepr = PyString_FromString(""); if (!self->imagepr){ Py_DECREF(self); return NULL; } self->printprofc = PyString_FromString(""); if (!self->printprofc){ Py_DECREF(self); return NULL; } self->info = PyString_FromString(""); if (!self->info){ Py_DECREF(self); return NULL; } self->bleedt = 0; // double - self->bleedl = 0; // double - self->bleedr = 0; // double - self->bleedb = 0; // double - } return (PyObject *) self; }
static int PDFfile_init(PDFfile *self, PyObject * /*args*/, PyObject * /*kwds*/) { int i; if (!ScCore->primaryMainWindow()->HaveDoc) { PyErr_SetString(PyExc_SystemError, "Must open doc first"); return -1; } // defaut save into file QString tf = ScCore->primaryMainWindow()->doc->PDF_Options.fileName; if (tf.isEmpty()) { QFileInfo fi = QFileInfo(ScCore->primaryMainWindow()->doc->DocName); tf = fi.path()+"/"+fi.baseName()+".pdf"; } PyObject *file = NULL; file = PyString_FromString(tf.toAscii()); if (file){ Py_DECREF(self->file); self->file = file; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'file' attribute"); return -1; } // embed all used fonts PyObject *fonts = NULL; fonts = PyList_New(0); if (fonts){ Py_DECREF(self->fonts); self->fonts = fonts; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'fonts' attribute"); return -1; } // get all used fonts QMap<QString,int> ReallyUsed = ScCore->primaryMainWindow()->doc->UsedFonts; // create list of all used fonts QList<QString> tmpEm; tmpEm = ReallyUsed.keys(); QList<QString>::Iterator itef; for (itef = tmpEm.begin(); itef != tmpEm.end(); ++itef) { // AV: dunno what this is for, but it looks as if it's the only place where HasMetrics is used... // if (PrefsManager::instance()->appPrefs.AvailFonts[(*itef).toAscii()]->HasMetrics) { PyObject *tmp= NULL; tmp = PyString_FromString((*itef).toAscii()); if (tmp) { PyList_Append(self->fonts, tmp); // do i need Py_DECREF(tmp) here? // Does PyList_Append increase reference or 'steal' one from provided argument // If it 'steal' reference comment next line Py_DECREF(tmp); } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'fonts' attribute"); return -1; } // } } // set to print all pages PyObject *pages = NULL; int num = 0; // which one should I use ??? // new = ScCore->primaryMainWindow()->view->Pages.count() num = ScCore->primaryMainWindow()->doc->Pages->count(); pages = PyList_New(num); if (!pages){ PyErr_SetString(PyExc_SystemError, "Can not initialize 'pages' attribute"); return -1; } for (i = 0; i<num; ++i) { PyObject *tmp; tmp = PyInt_FromLong((long)i+1L); if (tmp) PyList_SetItem(pages, i, tmp); else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'pages' attribute"); return -1; } } Py_DECREF(self->pages); self->pages = pages; // do not print thumbnails self->thumbnails = ScCore->primaryMainWindow()->doc->PDF_Options.Thumbnails; // set automatic compression self->compress = ScCore->primaryMainWindow()->doc->PDF_Options.Compress; self->compressmtd = ScCore->primaryMainWindow()->doc->PDF_Options.CompressMethod; // use maximum image quality self->quality = ScCore->primaryMainWindow()->doc->PDF_Options.Quality; // default resolution PyObject *resolution = NULL; resolution = PyInt_FromLong(300); if (resolution){ Py_DECREF(self->resolution); self->resolution = resolution; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'resolutin' attribute"); return -1; } // do not downsample images int down = ScCore->primaryMainWindow()->doc->PDF_Options.RecalcPic ? ScCore->primaryMainWindow()->doc->PDF_Options.PicRes : 0; PyObject *downsample = NULL; downsample = PyInt_FromLong(down); if (downsample){ Py_DECREF(self->downsample); self->downsample = downsample; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'downsamle' attribute"); return -1; } // no bookmarks self->bookmarks = ScCore->primaryMainWindow()->doc->PDF_Options.Bookmarks; // left margin binding self->binding = ScCore->primaryMainWindow()->doc->PDF_Options.Binding; // do not enable presentation effects self->presentation = ScCore->primaryMainWindow()->doc->PDF_Options.PresentMode; // set effects values for all pages PyObject *effval = NULL; num = 0; // which one should I use ??? // new = ScCore->primaryMainWindow()->view->Pages.count(); num = ScCore->primaryMainWindow()->doc->Pages->count(); effval = PyList_New(num); if (!effval){ PyErr_SetString(PyExc_SystemError, "Can not initialize 'effval' attribute"); return -1; } int num2 = ScCore->primaryMainWindow()->doc->PDF_Options.PresentVals.count(); for (i = 0; i<num2; ++i) { PyObject *tmp; PDFPresentationData t = ScCore->primaryMainWindow()->doc->PDF_Options.PresentVals[i]; tmp = Py_BuildValue(const_cast<char*>("[iiiiii]"), t.pageEffectDuration, t.pageViewDuration, t.effectType, t.Dm, t.M, t.Di ); if (tmp) PyList_SetItem(effval, i, tmp); else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'effval' attribute"); return -1; } for (; i<num; ++i) { PyObject *tmp; tmp = Py_BuildValue(const_cast<char*>("[iiiiii]"), 1, 1, 0, 0, 0, 0); if (tmp) PyList_SetItem(effval, i, tmp); else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'effval' attribute"); return -1; } } } Py_DECREF(self->effval); self->effval = effval; // do not save linked text frames as PDF article self->article = ScCore->primaryMainWindow()->doc->PDF_Options.Articles; // do not encrypt file self->encrypt = ScCore->primaryMainWindow()->doc->PDF_Options.Encrypt; // do not Use Custom Rendering Settings self->uselpi = ScCore->primaryMainWindow()->doc->PDF_Options.UseLPI; self->usespot = ScCore->primaryMainWindow()->doc->PDF_Options.UseSpotColors; self->domulti = ScCore->primaryMainWindow()->doc->PDF_Options.doMultiFile; // get default values for lpival int n = ScCore->primaryMainWindow()->doc->PDF_Options.LPISettings.size(); PyObject *lpival=PyList_New(n); if (!lpival){ PyErr_SetString(PyExc_SystemError, "Can not initialize 'lpival' attribute"); return -1; } QMap<QString,LPIData>::Iterator it = ScCore->primaryMainWindow()->doc->PDF_Options.LPISettings.begin(); while (it != ScCore->primaryMainWindow()->doc->PDF_Options.LPISettings.end()) { PyObject *tmp; tmp = Py_BuildValue(const_cast<char*>("[siii]"), it.key().toAscii().constData(), it.value().Frequency, it.value().Angle, it.value().SpotFunc); if (!tmp) { PyErr_SetString(PyExc_SystemError, "Can not initialize 'lpival' attribute"); return -1; } PyList_SetItem(lpival, --n, tmp); ++it; } PyList_Reverse(lpival); Py_DECREF(self->lpival); self->lpival = lpival; // set owner's password PyObject *owner = NULL; owner = PyString_FromString(ScCore->primaryMainWindow()->doc->PDF_Options.PassOwner.toAscii()); if (owner){ Py_DECREF(self->owner); self->owner = owner; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'owner' attribute"); return -1; } // set user'a password PyObject *user = NULL; user = PyString_FromString(ScCore->primaryMainWindow()->doc->PDF_Options.PassUser.toAscii()); if (user){ Py_DECREF(self->user); self->user = user; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'user' attribute"); return -1; } // allow printing document self->aprint = ScCore->primaryMainWindow()->doc->PDF_Options.Permissions & 4; // allow changing document self->achange = ScCore->primaryMainWindow()->doc->PDF_Options.Permissions & 8; // allow copying document self->acopy = ScCore->primaryMainWindow()->doc->PDF_Options.Permissions & 16; // allow adding annotation and fields self->aanot = ScCore->primaryMainWindow()->doc->PDF_Options.Permissions & 32; // use 1.4 pdf version *aka. Acrobat 5) self->version = ScCore->primaryMainWindow()->doc->PDF_Options.Version; // output destination is screen self->outdst = ScCore->primaryMainWindow()->doc->PDF_Options.UseRGB ? 0 : 1; self->profiles = ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles; // bool self->profilei = ScCore->primaryMainWindow()->doc->PDF_Options.UseProfiles2; // bool self->noembicc = ScCore->primaryMainWindow()->doc->PDF_Options.EmbeddedI; // bool self->intents = ScCore->primaryMainWindow()->doc->PDF_Options.Intent; // int - 0 - 3 self->intenti = ScCore->primaryMainWindow()->doc->PDF_Options.Intent2; // int - 0 - 3 QString tp = ScCore->primaryMainWindow()->doc->PDF_Options.SolidProf; if (!ScCore->InputProfiles.contains(tp)) tp = ScCore->primaryMainWindow()->view->Doc->CMSSettings.DefaultSolidColorRGBProfile; PyObject *solidpr = NULL; solidpr = PyString_FromString(tp.toAscii()); if (solidpr){ Py_DECREF(self->solidpr); self->solidpr = solidpr; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'solidpr' attribute"); return -1; } QString tp2 = ScCore->primaryMainWindow()->doc->PDF_Options.ImageProf; if (!ScCore->InputProfiles.contains(tp2)) tp2 = ScCore->primaryMainWindow()->view->Doc->CMSSettings.DefaultSolidColorRGBProfile; PyObject *imagepr = NULL; imagepr = PyString_FromString(tp2.toAscii()); if (imagepr){ Py_DECREF(self->imagepr); self->imagepr = imagepr; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'imagepr' attribute"); return -1; } QString tp3 = ScCore->primaryMainWindow()->doc->PDF_Options.PrintProf; if (!ScCore->PDFXProfiles.contains(tp3)) tp3 = ScCore->primaryMainWindow()->view->Doc->CMSSettings.DefaultPrinterProfile; PyObject *printprofc = NULL; printprofc = PyString_FromString(tp3.toAscii()); if (printprofc){ Py_DECREF(self->printprofc); self->printprofc = printprofc; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'printprofc' attribute"); return -1; } QString tinfo = ScCore->primaryMainWindow()->doc->PDF_Options.Info; PyObject *info = NULL; info = PyString_FromString(tinfo.toAscii()); if (info){ Py_DECREF(self->info); self->info = info; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'info' attribute"); return -1; } self->bleedt = ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Top*ScCore->primaryMainWindow()->doc->unitRatio(); // double - self->bleedl = ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Left*ScCore->primaryMainWindow()->doc->unitRatio(); // double - self->bleedr = ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Right*ScCore->primaryMainWindow()->doc->unitRatio(); // double - self->bleedb = ScCore->primaryMainWindow()->doc->PDF_Options.bleeds.Bottom*ScCore->primaryMainWindow()->doc->unitRatio(); // double - return 0; }
/* call BPY_context_set first */ void BPY_python_start(int argc, const char **argv) { #ifndef WITH_PYTHON_MODULE PyThreadState *py_tstate = NULL; const char *py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL); /* not essential but nice to set our name */ static wchar_t program_path_wchar[FILE_MAX]; /* python holds a reference */ BLI_strncpy_wchar_from_utf8(program_path_wchar, BKE_appdir_program_path(), ARRAY_SIZE(program_path_wchar)); Py_SetProgramName(program_path_wchar); /* must run before python initializes */ PyImport_ExtendInittab(bpy_internal_modules); /* allow to use our own included python */ PyC_SetHomePath(py_path_bundle); /* without this the sys.stdout may be set to 'ascii' * (it is on my system at least), where printing unicode values will raise * an error, this is highly annoying, another stumbling block for devs, * so use a more relaxed error handler and enforce utf-8 since the rest of * blender is utf-8 too - campbell */ Py_SetStandardStreamEncoding("utf-8", "surrogateescape"); /* Update, Py3.3 resolves attempting to parse non-existing header */ #if 0 /* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to * parse from the 'sysconfig' module which is used by 'site', * so for now disable site. alternatively we could copy the file. */ if (py_path_bundle) { Py_NoSiteFlag = 1; } #endif Py_FrozenFlag = 1; Py_Initialize(); // PySys_SetArgv(argc, argv); /* broken in py3, not a huge deal */ /* sigh, why do python guys not have a (char **) version anymore? */ { int i; PyObject *py_argv = PyList_New(argc); for (i = 0; i < argc; i++) { /* should fix bug #20021 - utf path name problems, by replacing * PyUnicode_FromString, with this one */ PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i])); } PySys_SetObject("argv", py_argv); Py_DECREF(py_argv); } /* Initialize thread support (also acquires lock) */ PyEval_InitThreads(); #else (void)argc; (void)argv; /* must run before python initializes */ /* broken in py3.3, load explicitly below */ // PyImport_ExtendInittab(bpy_internal_modules); #endif bpy_intern_string_init(); #ifdef WITH_PYTHON_MODULE { /* Manually load all modules */ struct _inittab *inittab_item; PyObject *sys_modules = PyImport_GetModuleDict(); for (inittab_item = bpy_internal_modules; inittab_item->name; inittab_item++) { PyObject *mod = inittab_item->initfunc(); if (mod) { PyDict_SetItemString(sys_modules, inittab_item->name, mod); } else { PyErr_Print(); PyErr_Clear(); } // Py_DECREF(mod); /* ideally would decref, but in this case we never want to free */ } } #endif /* bpy.* and lets us import it */ BPy_init_modules(); bpy_import_init(PyEval_GetBuiltins()); pyrna_alloc_types(); #ifndef WITH_PYTHON_MODULE /* py module runs atexit when bpy is freed */ BPY_atexit_register(); /* this can init any time */ py_tstate = PyGILState_GetThisThreadState(); PyEval_ReleaseThread(py_tstate); #endif }
/* Get buffer info from the global dictionary */ static _buffer_info_t* _buffer_get_info(PyObject *arr) { PyObject *key = NULL, *item_list = NULL, *item = NULL; _buffer_info_t *info = NULL, *old_info = NULL; if (_buffer_info_cache == NULL) { _buffer_info_cache = PyDict_New(); if (_buffer_info_cache == NULL) { return NULL; } } /* Compute information */ info = _buffer_info_new((PyArrayObject*)arr); if (info == NULL) { return NULL; } /* Check if it is identical with an old one; reuse old one, if yes */ key = PyLong_FromVoidPtr((void*)arr); if (key == NULL) { goto fail; } item_list = PyDict_GetItem(_buffer_info_cache, key); if (item_list != NULL) { Py_INCREF(item_list); if (PyList_GET_SIZE(item_list) > 0) { item = PyList_GetItem(item_list, PyList_GET_SIZE(item_list) - 1); old_info = (_buffer_info_t*)PyLong_AsVoidPtr(item); if (_buffer_info_cmp(info, old_info) == 0) { _buffer_info_free(info); info = old_info; } } } else { item_list = PyList_New(0); if (item_list == NULL) { goto fail; } if (PyDict_SetItem(_buffer_info_cache, key, item_list) != 0) { goto fail; } } if (info != old_info) { /* Needs insertion */ item = PyLong_FromVoidPtr((void*)info); if (item == NULL) { goto fail; } PyList_Append(item_list, item); Py_DECREF(item); } Py_DECREF(item_list); Py_DECREF(key); return info; fail: if (info != NULL && info != old_info) { _buffer_info_free(info); } Py_XDECREF(item_list); Py_XDECREF(key); return NULL; }
static PyObject * PLy_spi_execute_fetch_result(SPITupleTable *tuptable, int rows, int status) { PLyResultObject *result; volatile MemoryContext oldcontext; result = (PLyResultObject *) PLy_result_new(); Py_DECREF(result->status); result->status = PyInt_FromLong(status); if (status > 0 && tuptable == NULL) { Py_DECREF(result->nrows); result->nrows = PyInt_FromLong(rows); } else if (status > 0 && tuptable != NULL) { PLyTypeInfo args; int i; Py_DECREF(result->nrows); result->nrows = PyInt_FromLong(rows); PLy_typeinfo_init(&args); oldcontext = CurrentMemoryContext; PG_TRY(); { MemoryContext oldcontext2; if (rows) { Py_DECREF(result->rows); result->rows = PyList_New(rows); PLy_input_tuple_funcs(&args, tuptable->tupdesc); for (i = 0; i < rows; i++) { PyObject *row = PLyDict_FromTuple(&args, tuptable->vals[i], tuptable->tupdesc); PyList_SetItem(result->rows, i, row); } } /* * Save tuple descriptor for later use by result set metadata * functions. Save it in TopMemoryContext so that it survives * outside of an SPI context. We trust that PLy_result_dealloc() * will clean it up when the time is right. (Do this as late as * possible, to minimize the number of ways the tupdesc could get * leaked due to errors.) */ oldcontext2 = MemoryContextSwitchTo(TopMemoryContext); result->tupdesc = CreateTupleDescCopy(tuptable->tupdesc); MemoryContextSwitchTo(oldcontext2); } PG_CATCH(); { MemoryContextSwitchTo(oldcontext); PLy_typeinfo_dealloc(&args); SPI_freetuptable(tuptable); Py_DECREF(result); PG_RE_THROW(); } PG_END_TRY(); PLy_typeinfo_dealloc(&args); SPI_freetuptable(tuptable); } return (PyObject *) result; }
PyObject *PyObject_FromPROPVARIANT( PROPVARIANT *pVar ) { switch (pVar->vt) { case VT_EMPTY: case VT_NULL: case VT_ILLEGAL: Py_INCREF(Py_None); return Py_None; case VT_I1: return PyInt_FromLong(pVar->cVal); case VT_I1|VT_VECTOR: return VectorToSeq(pVar->cac.pElems, pVar->cac.cElems, PyWinObject_FromCHAR); case VT_UI1: return PyInt_FromLong(pVar->bVal); case VT_UI1|VT_VECTOR: return VectorToSeq(pVar->caub.pElems, pVar->caub.cElems, PyWinObject_FromUCHAR); case VT_I2: return PyInt_FromLong(pVar->iVal); case VT_I2|VT_VECTOR: return VectorToSeq(pVar->cai.pElems, pVar->cai.cElems, PyWinObject_FromSHORT); case VT_UI2: return PyInt_FromLong(pVar->uiVal); case VT_UI2|VT_VECTOR: return VectorToSeq(pVar->caui.pElems, pVar->caui.cElems, PyWinObject_FromUSHORT); case VT_I4: return PyInt_FromLong(pVar->lVal); case VT_I4|VT_VECTOR: return VectorToSeq(pVar->cal.pElems, pVar->cal.cElems, PyInt_FromLong); case VT_INT: return PyInt_FromLong(pVar->intVal); case VT_UI4: return PyLong_FromUnsignedLong(pVar->ulVal); case VT_UI4|VT_VECTOR: return VectorToSeq(pVar->caul.pElems, pVar->caul.cElems, PyLong_FromUnsignedLong); case VT_UINT: return PyLong_FromUnsignedLong(pVar->uintVal); case VT_I8: return PyWinObject_FromLARGE_INTEGER(pVar->hVal); case VT_I8|VT_VECTOR: return VectorToSeq<LARGE_INTEGER>(pVar->cah.pElems, pVar->cah.cElems, PyWinObject_FromLARGE_INTEGER); case VT_UI8: return PyWinObject_FromULARGE_INTEGER(pVar->uhVal); case VT_UI8|VT_VECTOR: return VectorToSeq<ULARGE_INTEGER>(pVar->cauh.pElems, pVar->cauh.cElems, PyWinObject_FromULARGE_INTEGER); case VT_R4: return PyFloat_FromDouble(pVar->fltVal); case VT_R4|VT_VECTOR: return VectorToSeq(pVar->caflt.pElems, pVar->caflt.cElems, PyWinObject_FromFLOAT); case VT_R8: return PyFloat_FromDouble(pVar->dblVal); case VT_R8|VT_VECTOR: return VectorToSeq(pVar->cadbl.pElems, pVar->cadbl.cElems, PyFloat_FromDouble); case VT_CY: return PyObject_FromCurrency(pVar->cyVal); case VT_CY|VT_VECTOR: return VectorToSeq<CY>(pVar->cacy.pElems, pVar->cacy.cElems, PyObject_FromCurrency); case VT_DATE: return PyWinObject_FromDATE(pVar->date); case VT_DATE|VT_VECTOR: return VectorToSeq(pVar->cadate.pElems, pVar->cadate.cElems, PyWinObject_FromDATE); case VT_BSTR: return PyWinObject_FromBstr(pVar->bstrVal); case VT_BSTR|VT_VECTOR: return VectorToSeq(pVar->cabstr.pElems, pVar->cabstr.cElems, PyWinObject_FromVT_BSTR); case VT_BOOL: return PyWinObject_FromVARIANT_BOOL(pVar->boolVal); case VT_BOOL|VT_VECTOR: return VectorToSeq(pVar->cabool.pElems, pVar->cabool.cElems, PyWinObject_FromVARIANT_BOOL); case VT_ERROR: return PyInt_FromLong(pVar->scode); case VT_ERROR|VT_VECTOR: return VectorToSeq(pVar->cascode.pElems, pVar->cascode.cElems, PyInt_FromLong); case VT_FILETIME: return PyWinObject_FromFILETIME(pVar->filetime); case VT_FILETIME|VT_VECTOR: return VectorToSeq<FILETIME>(pVar->cafiletime.pElems, pVar->cafiletime.cElems, PyWinObject_FromFILETIME); case VT_LPSTR: if (pVar->pszVal == NULL) { Py_INCREF(Py_None); return Py_None; } return PyWinCoreString_FromString(pVar->pszVal); case VT_LPSTR|VT_VECTOR: { PyObject *ret = PyList_New(pVar->calpstr.cElems); if (ret==NULL) return NULL; for (ULONG i=0; i<pVar->calpstr.cElems;i++){ PyObject *elem=PyWinCoreString_FromString(pVar->calpstr.pElems[i]); if (elem==NULL){ Py_DECREF(ret); return NULL; } PyList_SET_ITEM(ret, i, elem); } return ret; } case VT_LPWSTR: return PyWinObject_FromOLECHAR(pVar->pwszVal); case VT_LPWSTR|VT_VECTOR: { PyObject *ret = PyList_New(pVar->calpwstr.cElems); if (ret==NULL) return NULL; for (ULONG i=0; i<pVar->calpwstr.cElems;i++){ PyObject *elem=PyWinObject_FromWCHAR(pVar->calpwstr.pElems[i]); if (elem==NULL){ Py_DECREF(ret); return NULL; } PyList_SET_ITEM(ret, i, elem); } return ret; } case VT_CLSID: return PyWinObject_FromIID(*pVar->puuid); case VT_CLSID|VT_VECTOR: return VectorToSeq<CLSID>(pVar->cauuid.pElems, pVar->cauuid.cElems, PyWinObject_FromIID); case VT_STREAM: case VT_STREAMED_OBJECT: return PyCom_PyObjectFromIUnknown(pVar->pStream, IID_IStream, TRUE); case VT_STORAGE: case VT_STORED_OBJECT: return PyCom_PyObjectFromIUnknown(pVar->pStorage, IID_IStorage, TRUE); case VT_VECTOR | VT_VARIANT: return PyObject_FromPROPVARIANTs(pVar->capropvar.pElems, pVar->capropvar.cElems); case VT_BLOB: case VT_BLOB_OBJECT: return PyString_FromStringAndSize((const char *)pVar->blob.pBlobData, pVar->blob.cbSize); // case VT_UNKNOWN: // return PyCom_PyObjectFromIUnknown(pVar->punkVal, IID_IUnknown, TRUE); // case VT_DISPATCH: // return PyCom_PyObjectFromIUnknown(pVar->pdispVal, IID_IDispatch, TRUE); /* // Want to get VT_CF and VT_BLOB working with a test case first! case VT_CF: { // special "clipboard format" // cbSize is the size of the buffer pointed to // by pClipData, plus sizeof(ulClipFmt) // XXX - in that case, shouldn't we pass // pClipData + sizeof(DWORD) to Py_BuildValue?? ULONG cb = CBPCLIPDATA(*pVar->pclipdata); return Py_BuildValue("is#", pVar->pclipdata->ulClipFmt, pVar->pclipdata->pClipData, (int)cb); } */ default: PyErr_Format(PyExc_TypeError, "Unsupported property type 0x%x", pVar->vt); return NULL; } }
/** * This is the callback passed to the FSEvents API, which calls * the Python callback function, in turn, by passing in event data * as Python objects. * * :param stream_ref: * A pointer to an ``FSEventStream`` instance. * :param stream_callback_info_ref: * Callback context information passed by the FSEvents API. * This contains a reference to the Python callback that this * function calls in turn with information about the events. * :param num_events: * An unsigned integer representing the number of events * captured by the FSEvents API. * :param event_paths: * An array of NUL-terminated C strings representing event paths. * :param event_flags: * An array of ``FSEventStreamEventFlags`` unsigned integral * mask values. * :param event_ids: * An array of 64-bit unsigned integers representing event * identifiers. */ static void watchdog_FSEventStreamCallback(ConstFSEventStreamRef stream_ref, StreamCallbackInfo *stream_callback_info_ref, size_t num_events, const char *event_paths[], const FSEventStreamEventFlags event_flags[], const FSEventStreamEventId event_ids[]) { UNUSED(stream_ref); UNUSED(event_ids); size_t i = 0; PyObject *callback_result = NULL; PyObject *path = NULL; PyObject *flags = NULL; PyObject *py_event_flags = NULL; PyObject *py_event_paths = NULL; PyThreadState *saved_thread_state = NULL; /* Acquire interpreter lock and save original thread state. */ PyGILState_STATE gil_state = PyGILState_Ensure(); saved_thread_state = PyThreadState_Swap(stream_callback_info_ref->thread_state); /* Convert event flags and paths to Python ints and strings. */ py_event_paths = PyList_New(num_events); py_event_flags = PyList_New(num_events); if (G_NOT(py_event_paths && py_event_flags)) { Py_DECREF(py_event_paths); Py_DECREF(py_event_flags); return /*NULL*/; } for (i = 0; i < num_events; ++i) { #if PY_MAJOR_VERSION >= 3 path = PyUnicode_FromString(event_paths[i]); flags = PyLong_FromLong(event_flags[i]); #else path = PyString_FromString(event_paths[i]); flags = PyInt_FromLong(event_flags[i]); #endif if (G_NOT(path && flags)) { Py_DECREF(py_event_paths); Py_DECREF(py_event_flags); return /*NULL*/; } PyList_SET_ITEM(py_event_paths, i, path); PyList_SET_ITEM(py_event_flags, i, flags); } /* Call the Python callback function supplied by the stream information * struct. The Python callback function should accept two arguments, * both being Python lists: * * def python_callback(event_paths, event_flags): * pass */ callback_result = \ PyObject_CallFunction(stream_callback_info_ref->python_callback, "OO", py_event_paths, py_event_flags); if (G_IS_NULL(callback_result)) { if (G_NOT(PyErr_Occurred())) { PyErr_SetString(PyExc_ValueError, ERROR_CANNOT_CALL_CALLBACK); } CFRunLoopStop(stream_callback_info_ref->run_loop_ref); } /* Release the lock and restore thread state. */ PyThreadState_Swap(saved_thread_state); PyGILState_Release(gil_state); }
PyObject *PyRecord::getattro(PyObject *self, PyObject *obname) { PyObject *res; PyRecord *pyrec = (PyRecord *)self; char *name=PYWIN_ATTR_CONVERT(obname); if (name==NULL) return NULL; if (strcmp(name, "__members__")==0) { ULONG cnames = 0; HRESULT hr = pyrec->pri->GetFieldNames(&cnames, NULL); if (FAILED(hr)) return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo); BSTR *strs = (BSTR *)malloc(sizeof(BSTR) * cnames); if (strs==NULL) return PyErr_NoMemory(); hr = pyrec->pri->GetFieldNames(&cnames, strs); if (FAILED(hr)) { free(strs); return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo); } res = PyList_New(cnames); for (ULONG i=0;i<cnames && res != NULL;i++) { PyObject *item = PyWinCoreString_FromString(strs[i]); SysFreeString(strs[i]); if (item==NULL) { Py_DECREF(res); res = NULL; } else PyList_SET_ITEM(res, i, item); // ref count swallowed. } free(strs); return res; } res = PyObject_GenericGetAttr(self, obname); if (res != NULL) return res; PyErr_Clear(); WCHAR *wname; if (!PyWinObject_AsWCHAR(obname, &wname)) return NULL; VARIANT vret; VariantInit(&vret); void *sub_data = NULL; PY_INTERFACE_PRECALL; HRESULT hr = pyrec->pri->GetFieldNoCopy(pyrec->pdata, wname, &vret, &sub_data); PyWinObject_FreeWCHAR(wname); PY_INTERFACE_POSTCALL; if (FAILED(hr)) { if (hr == TYPE_E_FIELDNOTFOUND){ // This is slightly suspect - throwing a unicode // object for an AttributeError in py2k - but this // is the value we asked COM for, so it makes sense... // (and PyErr_Format doesn't handle unicode in py2x) PyErr_SetObject(PyExc_AttributeError, obname); return NULL; } return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo); } // Short-circuit sub-structs and arrays here, so we dont allocate a new chunk // of memory and copy it - we need sub-structs to persist. if (V_VT(&vret)==(VT_BYREF | VT_RECORD)) return new PyRecord(V_RECORDINFO(&vret), V_RECORD(&vret), pyrec->owner); else if (V_VT(&vret)==(VT_BYREF | VT_ARRAY | VT_RECORD)) { SAFEARRAY *psa = *V_ARRAYREF(&vret); int d = SafeArrayGetDim(psa); if (sub_data==NULL) return PyErr_Format(PyExc_RuntimeError, "Did not get a buffer for the array!"); if (SafeArrayGetDim(psa) != 1) return PyErr_Format(PyExc_TypeError, "Only support single dimensional arrays of records"); IRecordInfo *sub = NULL; long ubound, lbound, nelems; int i; BYTE *this_data; PyObject *ret_tuple = NULL; ULONG element_size = 0; hr = SafeArrayGetUBound(psa, 1, &ubound); if (FAILED(hr)) goto array_end; hr = SafeArrayGetLBound(psa, 1, &lbound); if (FAILED(hr)) goto array_end; hr = SafeArrayGetRecordInfo(psa, &sub); if (FAILED(hr)) goto array_end; hr = sub->GetSize(&element_size); if (FAILED(hr)) goto array_end; nelems = ubound-lbound; ret_tuple = PyTuple_New(nelems); if (ret_tuple==NULL) goto array_end; this_data = (BYTE *)sub_data; for (i=0;i<nelems;i++) { PyTuple_SET_ITEM(ret_tuple, i, new PyRecord(sub, this_data, pyrec->owner)); this_data += element_size; } array_end: if (sub) sub->Release(); if (FAILED(hr)) return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo); return ret_tuple; } // This default conversion we use is a little slow (but it will do!) // For arrays, the pparray->pvData member is *not* set, since the actual data // pointer from the record is returned in sub_data, so set it here. if (V_ISARRAY(&vret) && V_ISBYREF(&vret)) (*V_ARRAYREF(&vret))->pvData = sub_data; PyObject *ret = PyCom_PyObjectFromVariant(&vret); // VariantClear(&vret); return ret; }
static PyObject * SpiDev_xfer(SpiDevObject *self, PyObject *args) { uint16_t ii, len; int status; uint16_t delay_usecs = 0; uint32_t speed_hz = 0; uint8_t bits_per_word = 0; PyObject *list; #ifdef SPIDEV_SINGLE struct spi_ioc_transfer *xferptr; memset(&xferptr, 0, sizeof(xferptr)); #else struct spi_ioc_transfer xfer; memset(&xfer, 0, sizeof(xfer)); #endif uint8_t *txbuf, *rxbuf; if (!PyArg_ParseTuple(args, "O|IHB:xfer", &list, &speed_hz, &delay_usecs, &bits_per_word)) return NULL; if (!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, wrmsg); return NULL; } if ((len = PyList_GET_SIZE(list)) > SPIDEV_MAXPATH) { PyErr_SetString(PyExc_OverflowError, wrmsg); return NULL; } txbuf = malloc(sizeof(__u8) * len); rxbuf = malloc(sizeof(__u8) * len); #ifdef SPIDEV_SINGLE xferptr = (struct spi_ioc_transfer*) malloc(sizeof(struct spi_ioc_transfer) * len); for (ii = 0; ii < len; ii++) { PyObject *val = PyList_GET_ITEM(list, ii); if (!PyLong_Check(val)) { PyErr_SetString(PyExc_TypeError, wrmsg); free(xferptr); free(txbuf); free(rxbuf); return NULL; } txbuf[ii] = (__u8)PyLong_AS_LONG(val); xferptr[ii].tx_buf = (unsigned long)&txbuf[ii]; xferptr[ii].rx_buf = (unsigned long)&rxbuf[ii]; xferptr[ii].len = 1; xferptr[ii].delay_usecs = delay; xferptr[ii].speed_hz = speed_hz ? speed_hz : self->max_speed_hz; xferptr[ii].bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word; #ifdef SPI_IOC_WR_MODE32 xferptr[ii].tx_nbits = 0; #endif #ifdef SPI_IOC_RD_MODE32 xferptr[ii].rx_nbits = 0; #endif } status = ioctl(self->fd, SPI_IOC_MESSAGE(len), xferptr); if (status < 0) { PyErr_SetFromErrno(PyExc_IOError); free(xferptr); free(txbuf); free(rxbuf); return NULL; } #else for (ii = 0; ii < len; ii++) { PyObject *val = PyList_GET_ITEM(list, ii); if (!PyLong_Check(val)) { PyErr_SetString(PyExc_TypeError, wrmsg); free(txbuf); free(rxbuf); return NULL; } txbuf[ii] = (__u8)PyLong_AS_LONG(val); } xfer.tx_buf = (unsigned long)txbuf; xfer.rx_buf = (unsigned long)rxbuf; xfer.len = len; xfer.delay_usecs = delay_usecs; xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz; xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word; #ifdef SPI_IOC_WR_MODE32 xfer.tx_nbits = 0; #endif #ifdef SPI_IOC_RD_MODE32 xfer.rx_nbits = 0; #endif status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer); if (status < 0) { PyErr_SetFromErrno(PyExc_IOError); free(txbuf); free(rxbuf); return NULL; } #endif list = PyList_New(len); for (ii = 0; ii < len; ii++) { PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]); PyList_SET_ITEM(list, ii, val); } // WA: // in CS_HIGH mode CS isn't pulled to low after transfer, but after read // reading 0 bytes doesnt matter but brings cs down // tomdean: // Stop generating an extra CS except in mode CS_HOGH if (self->mode & SPI_CS_HIGH) status = read(self->fd, &rxbuf[0], 0); free(txbuf); free(rxbuf); return list; }
PyObject *wsgi_convert_headers_to_bytes(PyObject *headers) { PyObject *result = NULL; int i; long size; if (!PyList_Check(headers)) { PyErr_Format(PyExc_TypeError, "expected list object for headers, " "value of type %.200s found", headers->ob_type->tp_name); return 0; } size = PyList_Size(headers); result = PyList_New(size); for (i = 0; i < size; i++) { PyObject *header = NULL; PyObject *header_name = NULL; PyObject *header_value = NULL; PyObject *header_name_as_bytes = NULL; PyObject *header_value_as_bytes = NULL; PyObject *result_tuple = NULL; header = PyList_GetItem(headers, i); if (!PyTuple_Check(header)) { PyErr_Format(PyExc_TypeError, "list of tuple values " "expected for headers, value of type %.200s found", header->ob_type->tp_name); Py_DECREF(result); return 0; } if (PyTuple_Size(header) != 2) { PyErr_Format(PyExc_ValueError, "tuple of length 2 " "expected for header, length is %d", (int)PyTuple_Size(header)); Py_DECREF(result); return 0; } result_tuple = PyTuple_New(2); PyList_SET_ITEM(result, i, result_tuple); header_name = PyTuple_GetItem(header, 0); header_value = PyTuple_GetItem(header, 1); header_name_as_bytes = wsgi_convert_string_to_bytes(header_name); if (!header_name_as_bytes) goto failure; PyTuple_SET_ITEM(result_tuple, 0, header_name_as_bytes); if (!wsgi_validate_header_name(header_name_as_bytes)) goto failure; header_value_as_bytes = wsgi_convert_string_to_bytes(header_value); if (!header_value_as_bytes) goto failure; PyTuple_SET_ITEM(result_tuple, 1, header_value_as_bytes); if (!wsgi_validate_header_value(header_value_as_bytes)) goto failure; } return result; failure: Py_DECREF(result); return NULL; }
static PyObject * SpiDev_xfer2(SpiDevObject *self, PyObject *args) { static char *msg = "Argument must be a list of at least one, " "but not more than 4096 integers"; int status; uint16_t delay_usecs = 0; uint32_t speed_hz = 0; uint8_t bits_per_word = 0; uint16_t ii, len; PyObject *list; struct spi_ioc_transfer xfer; memset(&xfer, 0, sizeof(xfer)); uint8_t *txbuf, *rxbuf; if (!PyArg_ParseTuple(args, "O|IHB:xfer2", &list, &speed_hz, &delay_usecs, &bits_per_word)) return NULL; if (!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, wrmsg); return NULL; } if ((len = PyList_GET_SIZE(list)) > SPIDEV_MAXPATH) { PyErr_SetString(PyExc_OverflowError, wrmsg); return NULL; } txbuf = malloc(sizeof(__u8) * len); rxbuf = malloc(sizeof(__u8) * len); for (ii = 0; ii < len; ii++) { PyObject *val = PyList_GET_ITEM(list, ii); if (!PyLong_Check(val)) { PyErr_SetString(PyExc_TypeError, msg); free(txbuf); free(rxbuf); return NULL; } txbuf[ii] = (__u8)PyLong_AS_LONG(val); } xfer.tx_buf = (unsigned long)txbuf; xfer.rx_buf = (unsigned long)rxbuf; xfer.len = len; xfer.delay_usecs = delay_usecs; xfer.speed_hz = speed_hz ? speed_hz : self->max_speed_hz; xfer.bits_per_word = bits_per_word ? bits_per_word : self->bits_per_word; status = ioctl(self->fd, SPI_IOC_MESSAGE(1), &xfer); if (status < 0) { PyErr_SetFromErrno(PyExc_IOError); free(txbuf); free(rxbuf); return NULL; } list = PyList_New(len); for (ii = 0; ii < len; ii++) { PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]); PyList_SET_ITEM(list, ii, val); } // WA: // in CS_HIGH mode CS isnt pulled to low after transfer // reading 0 bytes doesn't really matter but brings CS down // tomdean: // Stop generating an extra CS except in mode CS_HOGH if (self->mode & SPI_CS_HIGH) status = read(self->fd, &rxbuf[0], 0); free(txbuf); free(rxbuf); return list; }
/** ******************************************************************************************************* * This function will get a batch of records from the Aeropike DB. * * @param err as_error object * @param self AerospikeClient object * @param py_keys The list of keys * @param batch_policy_p as_policy_batch object * * Returns the record if key exists otherwise NULL. ******************************************************************************************************* */ static PyObject * batch_select_aerospike_batch_read(as_error *err, AerospikeClient * self, PyObject *py_keys, as_policy_batch * batch_policy_p, char** filter_bins, Py_ssize_t bins_size) { PyObject * py_recs = NULL; as_batch_read_records records; as_batch_read_record* record = NULL; bool batch_initialised = false; // Convert python keys list to as_key ** and add it to as_batch.keys // keys can be specified in PyList or PyTuple if ( py_keys != NULL && PyList_Check(py_keys) ) { Py_ssize_t size = PyList_Size(py_keys); py_recs = PyList_New(size); as_batch_read_inita(&records, size); // Batch object initialised batch_initialised = true; for ( int i = 0; i < size; i++ ) { PyObject * py_key = PyList_GetItem(py_keys, i); if ( !PyTuple_Check(py_key) ) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple."); goto CLEANUP; } record = as_batch_read_reserve(&records); pyobject_to_key(err, py_key, &record->key); if (bins_size) { record->bin_names = filter_bins; record->n_bin_names = bins_size; } else { record->read_all_bins = true; } if ( err->code != AEROSPIKE_OK ) { goto CLEANUP; } } } else if ( py_keys != NULL && PyTuple_Check(py_keys) ) { Py_ssize_t size = PyTuple_Size(py_keys); py_recs = PyList_New(size); as_batch_read_inita(&records, size); // Batch object initialised batch_initialised = true; for ( int i = 0; i < size; i++ ) { PyObject * py_key = PyTuple_GetItem(py_keys, i); if ( !PyTuple_Check(py_key) ) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Key should be a tuple."); goto CLEANUP; } record = as_batch_read_reserve(&records); pyobject_to_key(err, py_key, &record->key); if (bins_size) { record->bin_names = filter_bins; record->n_bin_names = bins_size; } else { record->read_all_bins = true; } if ( err->code != AEROSPIKE_OK ) { goto CLEANUP; } } } else { as_error_update(err, AEROSPIKE_ERR_PARAM, "Keys should be specified as a list or tuple."); goto CLEANUP; } // Invoke C-client API if (aerospike_batch_read(self->as, err, batch_policy_p, &records) != AEROSPIKE_OK) { goto CLEANUP; } batch_select_recs(err, &records, &py_recs); CLEANUP: if (batch_initialised == true) { // We should destroy batch object as we are using 'as_batch_init' for initialisation // Also, pyobject_to_key is soing strdup() in case of Unicode. So, object destruction // is necessary. as_batch_read_destroy(&records); } return py_recs; }
/* * Return process memory mappings. */ static PyObject * psutil_proc_memory_maps(PyObject *self, PyObject *args) { int pid; int fd = -1; char path[100]; char perms[10]; char *name; struct stat st; pstatus_t status; prxmap_t *xmap = NULL, *p; off_t size; size_t nread; int nmap; uintptr_t pr_addr_sz; uintptr_t stk_base_sz, brk_base_sz; PyObject *pytuple = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) { return NULL; } if (! PyArg_ParseTuple(args, "i", &pid)) { goto error; } sprintf(path, "/proc/%i/status", pid); if (! psutil_file_to_struct(path, (void *)&status, sizeof(status))) { goto error; } sprintf(path, "/proc/%i/xmap", pid); if (stat(path, &st) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } size = st.st_size; fd = open(path, O_RDONLY); if (fd == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } xmap = (prxmap_t *)malloc(size); if (xmap == NULL) { PyErr_NoMemory(); goto error; } nread = pread(fd, xmap, size, 0); nmap = nread / sizeof(prxmap_t); p = xmap; while (nmap) { nmap -= 1; if (p == NULL) { p += 1; continue; } perms[0] = '\0'; pr_addr_sz = p->pr_vaddr + p->pr_size; // perms sprintf(perms, "%c%c%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-', p->pr_mflags & MA_WRITE ? 'w' : '-', p->pr_mflags & MA_EXEC ? 'x' : '-', p->pr_mflags & MA_SHARED ? 's' : '-', p->pr_mflags & MA_NORESERVE ? 'R' : '-', p->pr_mflags & MA_RESERVED1 ? '*' : ' '); // name if (strlen(p->pr_mapname) > 0) { name = p->pr_mapname; } else { if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) { name = "[shmid]"; } else { stk_base_sz = status.pr_stkbase + status.pr_stksize; brk_base_sz = status.pr_brkbase + status.pr_brksize; if ((pr_addr_sz > status.pr_stkbase) && (p->pr_vaddr < stk_base_sz)) { name = "[stack]"; } else if ((p->pr_mflags & MA_ANON) && \ (pr_addr_sz > status.pr_brkbase) && \ (p->pr_vaddr < brk_base_sz)) { name = "[heap]"; } else { name = "[anon]"; } } } pytuple = Py_BuildValue("iisslll", p->pr_vaddr, pr_addr_sz, perms, name, (long)p->pr_rss * p->pr_pagesize, (long)p->pr_anon * p->pr_pagesize, (long)p->pr_locked * p->pr_pagesize); if (!pytuple) goto error; if (PyList_Append(py_retlist, pytuple)) goto error; Py_DECREF(pytuple); // increment pointer p += 1; } close(fd); free(xmap); return py_retlist; error: if (fd != -1) close(fd); Py_XDECREF(pytuple); Py_DECREF(py_retlist); if (xmap != NULL) free(xmap); return NULL; }
PyObject * xid_recover(PyObject *conn) { PyObject *rv = NULL; PyObject *curs = NULL; PyObject *xids = NULL; XidObject *xid = NULL; PyObject *recs = NULL; PyObject *rec = NULL; PyObject *item = NULL; PyObject *tmp; Py_ssize_t len, i; /* curs = conn.cursor() */ if (!(curs = PyObject_CallMethod(conn, "cursor", NULL))) { goto exit; } /* curs.execute(...) */ if (!(tmp = PyObject_CallMethod(curs, "execute", "s", "SELECT gid, prepared, owner, database FROM pg_prepared_xacts"))) { goto exit; } Py_DECREF(tmp); /* recs = curs.fetchall() */ if (!(recs = PyObject_CallMethod(curs, "fetchall", NULL))) { goto exit; } /* curs.close() */ if (!(tmp = PyObject_CallMethod(curs, "close", NULL))) { goto exit; } Py_DECREF(tmp); /* Build the list with return values. */ if (0 > (len = PySequence_Size(recs))) { goto exit; } if (!(xids = PyList_New(len))) { goto exit; } /* populate the xids list */ for (i = 0; i < len; ++i) { if (!(rec = PySequence_GetItem(recs, i))) { goto exit; } /* Get the xid with the XA triple set */ if (!(item = PySequence_GetItem(rec, 0))) { goto exit; } if (!(xid = xid_from_string(item))) { goto exit; } Py_DECREF(item); item = NULL; /* set xid.prepared */ if (!(item = PySequence_GetItem(rec, 1))) { goto exit; } tmp = xid->prepared; xid->prepared = item; Py_DECREF(tmp); item = NULL; /* set xid.owner */ if (!(item = PySequence_GetItem(rec, 2))) { goto exit; } tmp = xid->owner; xid->owner = item; Py_DECREF(tmp); item = NULL; /* set xid.database */ if (!(item = PySequence_GetItem(rec, 3))) { goto exit; } tmp = xid->database; xid->database = item; Py_DECREF(tmp); item = NULL; /* xid finished: add it to the returned list */ PyList_SET_ITEM(xids, i, (PyObject *)xid); xid = NULL; /* ref stolen */ Py_DECREF(rec); rec = NULL; } /* set the return value. */ rv = xids; xids = NULL; exit: Py_XDECREF(xids); Py_XDECREF(xid); Py_XDECREF(curs); Py_XDECREF(recs); Py_XDECREF(rec); Py_XDECREF(item); return rv; }
/* * Return TCP and UDP connections opened by process. * UNIX sockets are excluded. * * Thanks to: * https://github.com/DavidGriffith/finx/blob/master/ * nxsensor-3.5.0-1/src/sysdeps/solaris.c * ...and: * https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/ * cmd-inet/usr.bin/netstat/netstat.c */ static PyObject * psutil_net_connections(PyObject *self, PyObject *args) { long pid; int sd = NULL; mib2_tcpConnEntry_t *tp = NULL; mib2_udpEntry_t *ude; #if defined(AF_INET6) mib2_tcp6ConnEntry_t *tp6; mib2_udp6Entry_t *ude6; #endif char buf[512]; int i, flags, getcode, num_ent, state; char lip[200], rip[200]; int lport, rport; int processed_pid; struct strbuf ctlbuf, databuf; struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf; struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf; struct T_error_ack *tea = (struct T_error_ack *)buf; struct opthdr *mibhdr; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_laddr = NULL; PyObject *py_raddr = NULL; PyObject *af_filter = NULL; PyObject *type_filter = NULL; if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter)) goto error; if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) { PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence"); goto error; } sd = open("/dev/arp", O_RDWR); if (sd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp"); goto error; } /* XXX - These 2 are used in ifconfig.c but they seem unnecessary ret = ioctl(sd, I_PUSH, "tcp"); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } ret = ioctl(sd, I_PUSH, "udp"); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } */ // OK, this mess is basically copied and pasted from nxsensor project // which copied and pasted it from netstat source code, mibget() // function. Also see: // http://stackoverflow.com/questions/8723598/ tor->PRIM_type = T_SVR4_OPTMGMT_REQ; tor->OPT_offset = sizeof (struct T_optmgmt_req); tor->OPT_length = sizeof (struct opthdr); tor->MGMT_flags = T_CURRENT; mibhdr = (struct opthdr *)&tor[1]; mibhdr->level = EXPER_IP_AND_ALL_IRES; mibhdr->name = 0; mibhdr->len = 0; ctlbuf.buf = buf; ctlbuf.len = tor->OPT_offset + tor->OPT_length; flags = 0; // request to be sent in non-priority if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } mibhdr = (struct opthdr *)&toa[1]; ctlbuf.maxlen = sizeof (buf); for (;;) { flags = 0; getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags); if (getcode != MOREDATA || ctlbuf.len < sizeof (struct T_optmgmt_ack) || toa->PRIM_type != T_OPTMGMT_ACK || toa->MGMT_flags != T_SUCCESS) { break; } if (ctlbuf.len >= sizeof (struct T_error_ack) && tea->PRIM_type == T_ERROR_ACK) { PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK"); goto error; } if (getcode == 0 && ctlbuf.len >= sizeof (struct T_optmgmt_ack) && toa->PRIM_type == T_OPTMGMT_ACK && toa->MGMT_flags == T_SUCCESS) { PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK"); goto error; } databuf.maxlen = mibhdr->len; databuf.len = 0; databuf.buf = (char *)malloc((int)mibhdr->len); if (!databuf.buf) { PyErr_NoMemory(); goto error; } flags = 0; getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags); if (getcode < 0) { PyErr_SetFromErrno(PyExc_OSError); goto error; } // TCPv4 if (mibhdr->level == MIB2_TCP && mibhdr->name == MIB2_TCP_13) { tp = (mib2_tcpConnEntry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_tcpConnEntry_t); for (i = 0; i < num_ent; i++, tp++) { processed_pid = tp->tcpConnCreationProcess; if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses inet_ntop(AF_INET, &tp->tcpConnLocalAddress, lip, sizeof(lip)); inet_ntop(AF_INET, &tp->tcpConnRemAddress, rip, sizeof(rip)); lport = tp->tcpConnLocalPort; rport = tp->tcpConnRemPort; // contruct python tuple/list py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; if (rport != 0) { py_raddr = Py_BuildValue("(si)", rip, rport); } else { py_raddr = Py_BuildValue("()"); } if (!py_raddr) goto error; state = tp->tcpConnEntryInfo.ce_state; // add item py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM, py_laddr, py_raddr, state, processed_pid); if (!py_tuple) { goto error; } if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #if defined(AF_INET6) // TCPv6 else if (mibhdr->level == MIB2_TCP6 && mibhdr->name == MIB2_TCP6_CONN) { tp6 = (mib2_tcp6ConnEntry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_tcp6ConnEntry_t); for (i = 0; i < num_ent; i++, tp6++) { processed_pid = tp6->tcp6ConnCreationProcess; if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses inet_ntop(AF_INET6, &tp6->tcp6ConnLocalAddress, lip, sizeof(lip)); inet_ntop(AF_INET6, &tp6->tcp6ConnRemAddress, rip, sizeof(rip)); lport = tp6->tcp6ConnLocalPort; rport = tp6->tcp6ConnRemPort; // contruct python tuple/list py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; if (rport != 0) { py_raddr = Py_BuildValue("(si)", rip, rport); } else { py_raddr = Py_BuildValue("()"); } if (!py_raddr) goto error; state = tp6->tcp6ConnEntryInfo.ce_state; // add item py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM, py_laddr, py_raddr, state, processed_pid); if (!py_tuple) { goto error; } if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #endif // UDPv4 else if (mibhdr->level == MIB2_UDP || mibhdr->level == MIB2_UDP_ENTRY) { ude = (mib2_udpEntry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_udpEntry_t); for (i = 0; i < num_ent; i++, ude++) { processed_pid = ude->udpCreationProcess; if (pid != -1 && processed_pid != pid) continue; // XXX Very ugly hack! It seems we get here only the first // time we bump into a UDPv4 socket. PID is a very high // number (clearly impossible) and the address does not // belong to any valid interface. Not sure what else // to do other than skipping. if (processed_pid > 131072) continue; inet_ntop(AF_INET, &ude->udpLocalAddress, lip, sizeof(lip)); lport = ude->udpLocalPort; py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM, py_laddr, py_raddr, PSUTIL_CONN_NONE, processed_pid); if (!py_tuple) { goto error; } if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #if defined(AF_INET6) // UDPv6 else if (mibhdr->level == MIB2_UDP6 || mibhdr->level == MIB2_UDP6_ENTRY) { ude6 = (mib2_udp6Entry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_udp6Entry_t); for (i = 0; i < num_ent; i++, ude6++) { processed_pid = ude6->udp6CreationProcess; if (pid != -1 && processed_pid != pid) continue; inet_ntop(AF_INET6, &ude6->udp6LocalAddress, lip, sizeof(lip)); lport = ude6->udp6LocalPort; py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM, py_laddr, py_raddr, PSUTIL_CONN_NONE, processed_pid); if (!py_tuple) { goto error; } if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #endif free(databuf.buf); } close(sd); return py_retlist; error: Py_XDECREF(py_tuple); Py_XDECREF(py_laddr); Py_XDECREF(py_raddr); Py_DECREF(py_retlist); // TODO : free databuf if (sd != NULL) close(sd); return NULL; }
//! Loads model to database void db_load_model(iks *xml, PyObject **py_models) { /*! * Loads models to database * * @xml Iksemel document * @py_models Pointer to models dictionary * */ iks *iface, *met, *arg; for (iface = iks_first_tag(xml); iface; iface = iks_next_tag(iface)) { PyObject *py_methods = PyDict_New(); char *iface_name = iks_find_attrib(iface, "name"); for (met = iks_first_tag(iface); met; met = iks_next_tag(met)) { PyObject *py_tuple = PyTuple_New(4); // First argument is type. 0 for methods, 1 for signals if (iks_strcmp(iks_name(met), "method") == 0) { PyTuple_SetItem(py_tuple, 0, PyInt_FromLong((long) 0)); } else { PyTuple_SetItem(py_tuple, 0, PyInt_FromLong((long) 1)); } // Second argument is PolicyKit action ID char *action_id = db_action_id(iface_name, met); PyTuple_SetItem(py_tuple, 1, PyString_FromString(action_id)); // Build argument lists PyObject *py_args_in = PyList_New(0); PyObject *py_args_out = PyList_New(0); int noreply = 0; for (arg = iks_first_tag(met); arg; arg = iks_next_tag(arg)) { if (iks_strcmp(iks_name(arg), "attribute") == 0) { if (iks_strcmp(iks_find_attrib(arg, "name"), "org.freedesktop.DBus.Method.NoReply") == 0) { if (iks_strcmp(iks_find_attrib(arg, "value"), "true") == 0) { noreply = 1; } } } else if (iks_strcmp(iks_name(arg), "arg") == 0) { if (iks_strcmp(iks_name(met), "method") == 0) { if (iks_strcmp(iks_find_attrib(arg, "direction"), "out") == 0) { PyList_Append(py_args_out, PyString_FromString(iks_find_attrib(arg, "type"))); } else { PyList_Append(py_args_in, PyString_FromString(iks_find_attrib(arg, "type"))); } } else if (iks_strcmp(iks_name(met), "signal") == 0) { PyList_Append(py_args_out, PyString_FromString(iks_find_attrib(arg, "type"))); } } } if (noreply) { py_args_out = PyList_New(0); } // Third argument is input arguments PyTuple_SetItem(py_tuple, 2, py_args_in); // Fourth argument is output arguments PyTuple_SetItem(py_tuple, 3, py_args_out); PyDict_SetItemString(py_methods, iks_find_attrib(met, "name"), py_tuple); } PyDict_SetItemString(*py_models, iface_name, py_methods); } }
static PyObject *sendmsg_recvmsg(PyObject *self, PyObject *args, PyObject *keywds) { int fd = -1; int flags = 0; int maxsize = 8192; int cmsg_size = 4096; size_t cmsg_space; size_t cmsg_overhead; Py_ssize_t recvmsg_result; struct msghdr message_header; struct cmsghdr *control_message; struct iovec iov[1]; char *cmsgbuf; PyObject *ancillary; PyObject *final_result = NULL; static char *kwlist[] = {"fd", "flags", "maxsize", "cmsg_size", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|iii:recvmsg", kwlist, &fd, &flags, &maxsize, &cmsg_size)) { return NULL; } cmsg_space = CMSG_SPACE(cmsg_size); /* overflow check */ if (cmsg_space > SOCKLEN_MAX) { PyErr_Format(PyExc_OverflowError, "CMSG_SPACE(cmsg_size) greater than SOCKLEN_MAX: %d", cmsg_size); return NULL; } message_header.msg_name = NULL; message_header.msg_namelen = 0; iov[0].iov_len = maxsize; iov[0].iov_base = PyMem_Malloc(maxsize); if (!iov[0].iov_base) { PyErr_NoMemory(); return NULL; } message_header.msg_iov = iov; message_header.msg_iovlen = 1; cmsgbuf = PyMem_Malloc(cmsg_space); if (!cmsgbuf) { PyMem_Free(iov[0].iov_base); PyErr_NoMemory(); return NULL; } memset(cmsgbuf, 0, cmsg_space); message_header.msg_control = cmsgbuf; /* see above for overflow check */ message_header.msg_controllen = (socklen_t) cmsg_space; recvmsg_result = recvmsg(fd, &message_header, flags); if (recvmsg_result < 0) { PyErr_SetFromErrno(sendmsg_socket_error); goto finished; } ancillary = PyList_New(0); if (!ancillary) { goto finished; } for (control_message = CMSG_FIRSTHDR(&message_header); control_message; control_message = CMSG_NXTHDR(&message_header, control_message)) { PyObject *entry; /* Some platforms apparently always fill out the ancillary data structure with a single bogus value if none is provided; ignore it, if that is the case. */ if ((!(control_message->cmsg_level)) && (!(control_message->cmsg_type))) { continue; } /* * Figure out how much of the cmsg size is cmsg structure overhead - in * other words, how much is not part of the application data. This lets * us compute the right application data size below. There should * really be a CMSG_ macro for this. */ cmsg_overhead = (char*)CMSG_DATA(control_message) - (char*)control_message; entry = Py_BuildValue( "(iis#)", control_message->cmsg_level, control_message->cmsg_type, CMSG_DATA(control_message), (Py_ssize_t) (control_message->cmsg_len - cmsg_overhead)); if (!entry) { Py_DECREF(ancillary); goto finished; } if (PyList_Append(ancillary, entry) < 0) { Py_DECREF(ancillary); Py_DECREF(entry); goto finished; } else { Py_DECREF(entry); } } final_result = Py_BuildValue( "s#iO", iov[0].iov_base, recvmsg_result, message_header.msg_flags, ancillary); Py_DECREF(ancillary); finished: PyMem_Free(iov[0].iov_base); PyMem_Free(cmsgbuf); return final_result; }
PyObject * _pygi_marshal_to_py_array (PyGIInvokeState *state, PyGICallableCache *callable_cache, PyGIArgCache *arg_cache, GIArgument *arg) { GArray *array_; PyObject *py_obj = NULL; PyGISequenceCache *seq_cache = (PyGISequenceCache *)arg_cache; gsize processed_items = 0; /* GArrays make it easier to iterate over arrays * with different element sizes but requires that * we allocate a GArray if the argument was a C array */ if (seq_cache->array_type == GI_ARRAY_TYPE_C) { gsize len; if (seq_cache->fixed_size >= 0) { g_assert(arg->v_pointer != NULL); len = seq_cache->fixed_size; } else if (seq_cache->is_zero_terminated) { if (arg->v_pointer == NULL) { len = 0; } else if (seq_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8) { len = strlen (arg->v_pointer); } else { len = g_strv_length ((gchar **)arg->v_pointer); } } else { GIArgument *len_arg = state->args[seq_cache->len_arg_index]; len = len_arg->v_long; } array_ = g_array_new (FALSE, FALSE, seq_cache->item_size); if (array_ == NULL) { PyErr_NoMemory (); if (arg_cache->transfer == GI_TRANSFER_EVERYTHING && arg->v_pointer != NULL) g_free (arg->v_pointer); return NULL; } if (array_->data != NULL) g_free (array_->data); array_->data = arg->v_pointer; array_->len = len; } else { array_ = arg->v_pointer; } if (seq_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8) { if (arg->v_pointer == NULL) { py_obj = PYGLIB_PyBytes_FromString (""); } else { py_obj = PYGLIB_PyBytes_FromStringAndSize (array_->data, array_->len); } } else { if (arg->v_pointer == NULL) { py_obj = PyList_New (0); } else { int i; gsize item_size; PyGIMarshalToPyFunc item_to_py_marshaller; PyGIArgCache *item_arg_cache; py_obj = PyList_New (array_->len); if (py_obj == NULL) goto err; item_arg_cache = seq_cache->item_cache; item_to_py_marshaller = item_arg_cache->to_py_marshaller; item_size = g_array_get_element_size (array_); for (i = 0; i < array_->len; i++) { GIArgument item_arg; PyObject *py_item; if (seq_cache->array_type == GI_ARRAY_TYPE_PTR_ARRAY) { item_arg.v_pointer = g_ptr_array_index ( ( GPtrArray *)array_, i); } else if (item_arg_cache->type_tag == GI_TYPE_TAG_INTERFACE) { PyGIInterfaceCache *iface_cache = (PyGIInterfaceCache *) item_arg_cache; gboolean is_gvariant = iface_cache->g_type == G_TYPE_VARIANT; // FIXME: This probably doesn't work with boxed types or gvalues. See fx. _pygi_marshal_from_py_array() switch (g_base_info_get_type (iface_cache->interface_info)) { case GI_INFO_TYPE_STRUCT: if (is_gvariant) { g_assert (item_size == sizeof (gpointer)); if (arg_cache->transfer == GI_TRANSFER_EVERYTHING) item_arg.v_pointer = g_variant_ref_sink (g_array_index (array_, gpointer, i)); else item_arg.v_pointer = g_array_index (array_, gpointer, i); } else if (arg_cache->transfer == GI_TRANSFER_EVERYTHING) { gpointer *_struct = g_malloc (item_size); memcpy (_struct, array_->data + i * item_size, item_size); item_arg.v_pointer = _struct; } else item_arg.v_pointer = array_->data + i * item_size; break; default: item_arg.v_pointer = g_array_index (array_, gpointer, i); break; } } else { memcpy (&item_arg, array_->data + i * item_size, item_size); } py_item = item_to_py_marshaller ( state, callable_cache, item_arg_cache, &item_arg); if (py_item == NULL) { Py_CLEAR (py_obj); if (seq_cache->array_type == GI_ARRAY_TYPE_C) g_array_unref (array_); goto err; } PyList_SET_ITEM (py_obj, i, py_item); processed_items++; } } } if (seq_cache->array_type == GI_ARRAY_TYPE_C) g_array_free (array_, FALSE); return py_obj; err: if (seq_cache->array_type == GI_ARRAY_TYPE_C) { g_array_free (array_, arg_cache->transfer == GI_TRANSFER_EVERYTHING); } else { /* clean up unprocessed items */ if (seq_cache->item_cache->to_py_cleanup != NULL) { int j; PyGIMarshalCleanupFunc cleanup_func = seq_cache->item_cache->to_py_cleanup; for (j = processed_items; j < array_->len; j++) { cleanup_func (state, seq_cache->item_cache, g_array_index (array_, gpointer, j), FALSE); } } if (arg_cache->transfer == GI_TRANSFER_EVERYTHING) g_array_free (array_, TRUE); } return NULL; }
static response_status write_headers(client_t *client, char *data, size_t datalen, char is_file) { write_bucket *bucket; uint32_t hlen = 0; PyObject *headers = NULL, *templist = NULL; response_status ret; DEBUG("header write? %d", client->header_done); if(client->header_done){ return STATUS_OK; } //TODO ERROR CHECK headers = PySequence_Fast(client->headers, "header must be list"); hlen = PySequence_Fast_GET_SIZE(headers); bucket = new_write_bucket(client->fd, (hlen * 4) + 42 ); if(bucket == NULL){ goto error; } templist = PyList_New(hlen * 4); bucket->temp1 = templist; if(add_status_line(bucket, client) == -1){ goto error; } //write header if(add_all_headers(bucket, headers, hlen, client) == -1){ //Error goto error; } // check content_length_set if(data && !client->content_length_set && client->http_parser->http_minor == 1){ //Transfer-Encoding chunked add_header(bucket, "Transfer-Encoding", 17, "chunked", 7); client->chunked_response = 1; } if (is_file && !client->content_length_set){ if (set_file_content_length(client, bucket) == -1) { goto error; } } if(client->keep_alive == 1){ //Keep-Alive add_header(bucket, "Connection", 10, "Keep-Alive", 10); }else{ add_header(bucket, "Connection", 10, "close", 5); } set2bucket(bucket, CRLF, 2); //write body client->bucket = bucket; set_first_body_data(client, data, datalen); ret = writev_bucket(bucket); if(ret != STATUS_SUSPEND){ client->header_done = 1; if(ret == STATUS_OK && data){ client->write_bytes += datalen; } // clear free_write_bucket(bucket); client->bucket = NULL; } Py_DECREF(headers); return ret; error: if (PyErr_Occurred()){ /* write_error_log(__FILE__, __LINE__); */ call_error_logger(); } Py_XDECREF(headers); if(bucket){ free_write_bucket(bucket); client->bucket = NULL; } return STATUS_ERROR; }
static PyObject *SPIDev_transfer(SPIDev *self, PyObject *args, PyObject *kwds) { uint8_t cs; uint32_t n_bytes, n_words, i, word; PyObject *txdata, *rxdata, *word_obj; void *txbuf, *rxbuf; if (self->mode_3wire) { PyErr_SetString(PyExc_IOError, "SPIDev.transfer not supported in 3 wire mode"); return NULL; } cs = 0; if(!PyArg_ParseTuple(args, "bO!", &cs, &PyList_Type, &txdata)) { return NULL; } if (SPIDev_activateCS(self, cs) < 0) return NULL; n_words = PyList_Size(txdata); n_bytes = (uint32_t) (((float) (self->bits_per_word * n_words)) / 8.0 + 0.5); txbuf = malloc(n_bytes); rxbuf = malloc(n_bytes); for (i=0; i<n_words; i++) { word_obj = PyList_GetItem(txdata, i); if (!PyInt_Check(word_obj)) { PyErr_SetString(PyExc_ValueError, "data list to transmit can only contain integers"); free(txbuf); return NULL; } word = PyInt_AsLong(word_obj); if (word < 0) { if (PyErr_Occurred() != NULL) return NULL; word = 0; } switch(self->bytes_per_word) { case 1: ((uint8_t*)txbuf)[i] = (uint8_t) word; break; case 2: ((uint16_t*)txbuf)[i] = (uint16_t) word; break; case 4: ((uint32_t*)txbuf)[i] = (uint32_t) word; break; default: break; } } n_words = SPI_transfer(self->spidev_fd[cs], txbuf, rxbuf, n_words); rxdata = PyList_New(0); for (i=0; i<n_words; i++) { switch(self->bytes_per_word) { case 1: word = ((uint8_t*)rxbuf)[i]; break; case 2: word = ((uint16_t*)rxbuf)[i]; break; case 4: word = ((uint32_t*)rxbuf)[i]; break; default: word = 0; break; } word_obj = PyInt_FromLong(word); PyList_Append(rxdata, word_obj); Py_DECREF(word_obj); } free(txbuf); free(rxbuf); return rxdata; }
PyObject* xcsoar_Airspaces_findIntrusions(Pyxcsoar_Airspaces *self, PyObject *args) { PyObject *py_flight = nullptr; if (!PyArg_ParseTuple(args, "O", &py_flight)) { return nullptr; } DebugReplay *replay = ((Pyxcsoar_Flight*)py_flight)->flight->Replay(); if (replay == nullptr) { PyErr_SetString(PyExc_IOError, "Can't start replay - file not found."); return nullptr; } PyObject *py_result = PyDict_New(); Airspaces::AirspaceVector last_airspaces; while (replay->Next()) { const MoreData &basic = replay->Basic(); if (!basic.time_available || !basic.location_available || !basic.NavAltitudeAvailable()) continue; const auto range = self->airspace_database->QueryInside(ToAircraftState(basic, replay->Calculated())); Airspaces::AirspaceVector airspaces(range.begin(), range.end()); for (auto it = airspaces.begin(); it != airspaces.end(); it++) { PyObject *py_name = PyUnicode_FromString((*it).GetAirspace().GetName()); PyObject *py_airspace = nullptr, *py_period = nullptr; if (PyDict_Contains(py_result, py_name) == 0) { // this is the first fix inside this airspace py_airspace = PyList_New(0); PyDict_SetItem(py_result, py_name, py_airspace); py_period = PyList_New(0); PyList_Append(py_airspace, py_period); Py_DECREF(py_period); } else { // this airspace was hit some time before... py_airspace = PyDict_GetItem(py_result, py_name); // check if the last fix was already inside this airspace auto in_last = std::find(last_airspaces.begin(), last_airspaces.end(), *it); if (in_last == last_airspaces.end()) { // create a new period py_period = PyList_New(0); PyList_Append(py_airspace, py_period); Py_DECREF(py_period); } else { py_period = PyList_GET_ITEM(py_airspace, PyList_GET_SIZE(py_airspace) - 1); } } PyList_Append(py_period, Py_BuildValue("{s:N,s:N}", "time", Python::BrokenDateTimeToPy(basic.date_time_utc), "location", Python::WriteLonLat(basic.location))); } last_airspaces = std::move(airspaces); } delete replay; return py_result; }
static PyObject * describe_plugin(PyObject * mod, PyObject * args) { char * libname = NULL; int plug_id; int port_num; void * dlfile; LADSPA_Descriptor * (* descrip_func)(unsigned long); LADSPA_Descriptor * descrip; PyObject * dict = NULL; PyObject * ports = NULL; PyObject * portinfo = NULL; PyArg_ParseTuple(args, "si", &libname, &plug_id); if (libname == NULL) { Py_INCREF(Py_None); return Py_None; } dlfile = dlopen(libname, RTLD_NOW); if (dlfile == NULL) { Py_INCREF(Py_None); return Py_None; } descrip_func = dlsym(dlfile, "ladspa_descriptor"); descrip = descrip_func(plug_id); if (descrip == NULL) { Py_INCREF(Py_None); return Py_None; } dict = PyDict_New(); PyDict_SetItemString(dict, "lib_name", PyString_FromString(libname)); PyDict_SetItemString(dict, "lib_type", PyString_FromString("ladspa")); PyDict_SetItemString(dict, "lib_index", PyInt_FromLong(plug_id)); PyDict_SetItemString(dict, "unique_id", PyInt_FromLong(descrip->UniqueID)); PyDict_SetItemString(dict, "properties", PyInt_FromLong(descrip->Properties)); PyDict_SetItemString(dict, "label", PyString_FromString(descrip->Label)); PyDict_SetItemString(dict, "name", PyString_FromString(descrip->Name)); PyDict_SetItemString(dict, "maker", PyString_FromString(descrip->Maker)); PyDict_SetItemString(dict, "copyright", PyString_FromString(descrip->Copyright)); ports = PyList_New(descrip->PortCount); for(port_num=0; port_num < descrip->PortCount; port_num++) { portinfo = PyDict_New(); PyDict_SetItemString(portinfo, "descriptor", PyInt_FromLong(descrip->PortDescriptors[port_num])); PyDict_SetItemString(portinfo, "name", PyString_FromString(descrip->PortNames[port_num])); PyDict_SetItemString(portinfo, "hint_type", PyInt_FromLong(descrip->PortRangeHints[port_num].HintDescriptor)); PyDict_SetItemString(portinfo, "hint_lower", PyFloat_FromDouble(descrip->PortRangeHints[port_num].LowerBound)); PyDict_SetItemString(portinfo, "hint_upper", PyFloat_FromDouble(descrip->PortRangeHints[port_num].UpperBound)); PyList_SetItem(ports, port_num, portinfo); } PyDict_SetItemString(dict, "ports", ports); dlclose(dlfile); Py_INCREF(dict); return dict; }
static PyObject * archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw) { static char *keywords[] = { "start_pc", "end_pc", "count", NULL }; CORE_ADDR start, end = 0; CORE_ADDR pc; gdb_py_ulongest start_temp; long count = 0, i; PyObject *result_list, *end_obj = NULL, *count_obj = NULL; struct gdbarch *gdbarch = NULL; ARCHPY_REQUIRE_VALID (self, gdbarch); if (!PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO", keywords, &start_temp, &end_obj, &count_obj)) return NULL; start = start_temp; if (end_obj) { /* Make a long logic check first. In Python 3.x, internally, all integers are represented as longs. In Python 2.x, there is still a differentiation internally between a PyInt and a PyLong. Explicitly do this long check conversion first. In GDB, for Python 3.x, we #ifdef PyInt = PyLong. This check has to be done first to ensure we do not lose information in the conversion process. */ if (PyLong_Check (end_obj)) end = PyLong_AsUnsignedLongLong (end_obj); else if (PyInt_Check (end_obj)) /* If the end_pc value is specified without a trailing 'L', end_obj will be an integer and not a long integer. */ end = PyInt_AsLong (end_obj); else { Py_DECREF (end_obj); Py_XDECREF (count_obj); PyErr_SetString (PyExc_TypeError, _("Argument 'end_pc' should be a (long) integer.")); return NULL; } if (end < start) { Py_DECREF (end_obj); Py_XDECREF (count_obj); PyErr_SetString (PyExc_ValueError, _("Argument 'end_pc' should be greater than or " "equal to the argument 'start_pc'.")); return NULL; } } if (count_obj) { count = PyInt_AsLong (count_obj); if (PyErr_Occurred () || count < 0) { Py_DECREF (count_obj); Py_XDECREF (end_obj); PyErr_SetString (PyExc_TypeError, _("Argument 'count' should be an non-negative " "integer.")); return NULL; } } result_list = PyList_New (0); if (result_list == NULL) return NULL; for (pc = start, i = 0; /* All args are specified. */ (end_obj && count_obj && pc <= end && i < count) /* end_pc is specified, but no count. */ || (end_obj && count_obj == NULL && pc <= end) /* end_pc is not specified, but a count is. */ || (end_obj == NULL && count_obj && i < count) /* Both end_pc and count are not specified. */ || (end_obj == NULL && count_obj == NULL && pc == start);) { int insn_len = 0; char *as = NULL; struct ui_file *memfile = mem_fileopen (); PyObject *insn_dict = PyDict_New (); volatile struct gdb_exception except; if (insn_dict == NULL) { Py_DECREF (result_list); ui_file_delete (memfile); return NULL; } if (PyList_Append (result_list, insn_dict)) { Py_DECREF (result_list); Py_DECREF (insn_dict); ui_file_delete (memfile); return NULL; /* PyList_Append Sets the exception. */ } TRY_CATCH (except, RETURN_MASK_ALL) { insn_len = gdb_print_insn (gdbarch, pc, memfile, NULL); } if (except.reason < 0) { Py_DECREF (result_list); ui_file_delete (memfile); gdbpy_convert_exception (except); return NULL; } as = ui_file_xstrdup (memfile, NULL); if (PyDict_SetItemString (insn_dict, "addr", gdb_py_long_from_ulongest (pc)) || PyDict_SetItemString (insn_dict, "asm", PyString_FromString (*as ? as : "<unknown>")) || PyDict_SetItemString (insn_dict, "length", PyInt_FromLong (insn_len))) { Py_DECREF (result_list); ui_file_delete (memfile); xfree (as); return NULL; } pc += insn_len; i++; ui_file_delete (memfile); xfree (as); }