/* action in (ACTION_RESET, ACTION_FINALIZE) */ void pysqlite_do_all_statements(pysqlite_Connection* self, int action) { int i; PyObject* weakref; PyObject* statement; pysqlite_Cursor* cursor; for (i = 0; i < PyList_Size(self->statements); i++) { weakref = PyList_GetItem(self->statements, i); statement = PyWeakref_GetObject(weakref); if (statement != Py_None) { if (action == ACTION_RESET) { (void)pysqlite_statement_reset((pysqlite_Statement*)statement); } else { (void)pysqlite_statement_finalize((pysqlite_Statement*)statement); } } } for (i = 0; i < PyList_Size(self->cursors); i++) { weakref = PyList_GetItem(self->cursors, i); cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref); if ((PyObject*)cursor != Py_None) { cursor->reset = 1; } } }
static int PySurface_UnlockBy (PyObject* surfobj, PyObject* lockobj) { PySurfaceObject* surf = (PySurfaceObject*) surfobj; int found = 0; int noerror = 1; if (surf->locklist) { PyObject *item, *ref; Py_ssize_t len = PyList_Size (surf->locklist); while (--len >= 0 && !found) { item = PyList_GetItem (surf->locklist, len); ref = PyWeakref_GetObject (item); if (ref == lockobj) { if (PySequence_DelItem (surf->locklist, len) == -1) return 0; else found = 1; } } /* Clear dead references */ len = PyList_Size (surf->locklist); while (--len >= 0) { item = PyList_GetItem (surf->locklist, len); ref = PyWeakref_GetObject (item); if (ref == Py_None) { if (PySequence_DelItem (surf->locklist, len) == -1) noerror = 0; else found++; } } } if (!found) return noerror; /* Release all found locks. */ while (found > 0) { if (surf->surf != NULL) SDL_UnlockSurface (surf->surf); if (surf->subsurface) PySurface_Unprep (surfobj); found--; } return noerror; }
static PyObject *PySSL_SSLshutdown(PySSLObject *self) { int err; PySocketSockObject *sock = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); /* Guard against closed socket */ if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) { _setSSLError("Underlying socket connection gone", PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); return NULL; } PySSL_BEGIN_ALLOW_THREADS err = SSL_shutdown(self->ssl); if (err == 0) { /* we need to call it again to finish the shutdown */ err = SSL_shutdown(self->ssl); } PySSL_END_ALLOW_THREADS if (err < 0) return PySSL_SetError(self, err, __FILE__, __LINE__); else { Py_INCREF(sock); return (PyObject *) sock; } }
static PyObject* sllist_insertbefore(SLListObject* self, PyObject* arg) { PyObject* value = NULL; PyObject* after = NULL; PyObject* list_ref; SLListNodeObject* new_node; SLListNodeObject* prev; if (!PyArg_UnpackTuple(arg, "insertbefore", 2, 2, &value, &after)) return NULL; if (!PyObject_TypeCheck(after, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "Argument is not an sllistnode"); return NULL; } if (PyObject_TypeCheck(value, &SLListNodeType)) value = ((SLListNodeObject*)value)->value; if (after == Py_None) { PyErr_SetString(PyExc_ValueError, "sllistnode does not belong to a list"); return NULL; } list_ref = PyWeakref_GetObject( ((SLListNodeObject*)after)->list_weakref); if (list_ref != (PyObject*)self) { PyErr_SetString(PyExc_ValueError, "sllistnode belongs to another list"); return NULL; } new_node = sllistnode_create(Py_None, value, (PyObject*)self); /* getting prev node for this from arg*/ prev = sllist_get_prev(self, (SLListNodeObject*)after); /* putting new node in created gap, not first and exists */ if((PyObject*)prev != Py_None && prev != NULL) { ((SLListNodeObject*)prev)->next = (PyObject*)new_node; new_node->next = after; } else { new_node->next = after; self->first = (PyObject*)new_node; } /* new_node->next = ((SLListNodeObject*)after)->next; */ /* ((SLListNodeObject*)before)->next = (PyObject*)new_node; */ ++self->size; Py_INCREF((PyObject*)new_node); return (PyObject*)new_node; }
/* Return a new reference to a Python Connection or subclass corresponding * to the DBusConnection conn. For use in callbacks. * * Raises AssertionError if the DBusConnection does not have a Connection. */ PyObject * DBusPyConnection_ExistingFromDBusConnection(DBusConnection *conn) { PyObject *self, *ref; Py_BEGIN_ALLOW_THREADS ref = (PyObject *)dbus_connection_get_data(conn, _connection_python_slot); Py_END_ALLOW_THREADS if (ref) { DBG("(DBusConnection *)%p has weak reference at %p", conn, ref); self = PyWeakref_GetObject(ref); /* still a borrowed ref */ if (self && self != Py_None && DBusPyConnection_Check(self)) { DBG("(DBusConnection *)%p has weak reference at %p pointing to %p", conn, ref, self); TRACE(self); Py_INCREF(self); TRACE(self); return self; } } PyErr_SetString(PyExc_AssertionError, "D-Bus connection does not have a Connection " "instance associated with it"); return NULL; }
// Get the instance object. PyObject *PyQtSlot::instance() const { // Use the weak reference if possible. if (mself_wr) return PyWeakref_GetObject(mself_wr); return mself; }
void pysqlite_reset_all_statements(pysqlite_Connection* self) { int i; PyObject* weakref; PyObject* statement; for (i = 0; i < PyList_Size(self->statements); i++) { weakref = PyList_GetItem(self->statements, i); statement = PyWeakref_GetObject(weakref); if (statement != Py_None) { (void)pysqlite_statement_reset((pysqlite_Statement*)statement); } } }
static PyObject* sllist_insertafter(SLListObject* self, PyObject* arg) { PyObject* value = NULL; PyObject* before = NULL; PyObject* list_ref; SLListNodeObject* new_node; if (!PyArg_UnpackTuple(arg, "insertafter", 2, 2, &value, &before)) return NULL; if (!PyObject_TypeCheck(before, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "Argument is not an sllistnode"); return NULL; } if (PyObject_TypeCheck(value, &SLListNodeType)) value = ((SLListNodeObject*)value)->value; if (((SLListNodeObject*)before)->list_weakref == Py_None) { PyErr_SetString(PyExc_ValueError, "sllistnode does not belong to a list"); return NULL; } list_ref = PyWeakref_GetObject( ((SLListNodeObject*)before)->list_weakref); if (list_ref != (PyObject*)self) { PyErr_SetString(PyExc_ValueError, "sllistnode belongs to another list"); return NULL; } new_node = sllistnode_create(Py_None, value, (PyObject*)self); /* putting new node in created gap */ new_node->next = ((SLListNodeObject*)before)->next; ((SLListNodeObject*)before)->next = (PyObject*)new_node; if (self->last == before) self->last = (PyObject*)new_node; ++self->size; Py_INCREF((PyObject*)new_node); return (PyObject*)new_node; }
static PyObject *PyUpb_ObjCacheGet(const void *obj, PyTypeObject *type) { PyObject *kv = PyUpb_StringForPointer(obj); PyObject *ref = PyDict_GetItem(obj_cache, kv); PyObject *ret; if (ref) { ret = PyWeakref_GetObject(ref); assert(ret != Py_None); Py_INCREF(ret); } else { PyUpb_ObjWrapper *wrapper = (PyUpb_ObjWrapper*)type->tp_alloc(type, 0); wrapper->obj = (void*)obj; wrapper->weakreflist = NULL; ret = (PyObject*)wrapper; ref = PyWeakref_NewRef(ret, weakref_callback); assert(PyWeakref_GetObject(ref) == ret); assert(ref); PyDict_SetItem(obj_cache, kv, ref); PyDict_SetItem(reverse_cache, ref, kv); } assert(ret); Py_DECREF(kv); return ret; }
// // CAssocManager::GetAssocObject // Returns an object *with a new reference*. NULL is not an error return - it just means "no object" ui_assoc_object *CAssocManager::GetAssocObject(void * handle) { if (handle==NULL) return NULL; // no possible association for NULL! ASSERT_GIL_HELD; // we rely on the GIL to serialize access to our map... PyObject *weakref; #ifdef _DEBUG cacheLookups++; #endif // implement a basic 1 item cache. if (lastLookup==handle) { weakref = lastObjectWeakRef; #ifdef _DEBUG ++cacheHits; #endif } else { if (!map.Lookup((void *)handle, (void *&)weakref)) weakref = NULL; lastLookup = handle; lastObjectWeakRef = weakref; } if (weakref==NULL) return NULL; // convert the weakref object into a real object. PyObject *ob = PyWeakref_GetObject(weakref); if (ob == NULL) { // an error - but a NULL return from us just means "no assoc" // so print the error and ignore it, treating it as if the // weak-ref target has died. gui_print_error(); ob = Py_None; } ui_assoc_object *ret; if (ob == Py_None) { // weak-ref target has died. Remove it from the map. Assoc(handle, NULL); ret = NULL; } else { ret = (ui_assoc_object *)ob; Py_INCREF(ret); } return ret; }
void CAssocManager::RemoveAssoc(void *handle) { // nuke any existing items. PyObject *weakref; if (map.Lookup(handle, (void *&)weakref)) { PyObject *ob = PyWeakref_GetObject(weakref); map.RemoveKey(handle); if (ob != Py_None) // The object isn't necessarily dead (ie, its refcount may // not be about to hit zero), but its 'dead' from our POV, so // let it free any MFC etc resources the object owns. // XXX - this kinda sucks - just relying on the object // destructor *should* be OK... ((ui_assoc_object *)ob)->cleanup(); Py_DECREF(weakref); } lastObjectWeakRef = 0; lastLookup = 0; // set cache invalid. }
static cursorObject * _conn_get_async_cursor(connectionObject *self) { PyObject *py_curs; if (!(py_curs = PyWeakref_GetObject(self->async_cursor))) { PyErr_SetString(PyExc_SystemError, "got null dereferencing cursor weakref"); goto error; } if (Py_None == py_curs) { PyErr_SetString(InterfaceError, "the asynchronous cursor has disappeared"); goto error; } Py_INCREF(py_curs); return (cursorObject *)py_curs; error: pq_clear_async(self); return NULL; }
/* Return a new reference to a Python Connection or subclass (given by cls) * corresponding to the DBusConnection conn, which must have been newly * created. For use by the Connection and Bus constructors. * * Raises AssertionError if the DBusConnection already has a Connection. */ static PyObject * DBusPyConnection_NewConsumingDBusConnection(PyTypeObject *cls, DBusConnection *conn, PyObject *mainloop) { Connection *self = NULL; PyObject *ref; dbus_bool_t ok; DBG("%s(cls=%p, conn=%p, mainloop=%p)", __func__, cls, conn, mainloop); DBUS_PY_RAISE_VIA_NULL_IF_FAIL(conn); Py_BEGIN_ALLOW_THREADS ref = (PyObject *)dbus_connection_get_data(conn, _connection_python_slot); Py_END_ALLOW_THREADS if (ref) { self = (Connection *)PyWeakref_GetObject(ref); ref = NULL; if (self && (PyObject *)self != Py_None) { self = NULL; PyErr_SetString(PyExc_AssertionError, "Newly created D-Bus connection already has a " "Connection instance associated with it"); DBG("%s() fail - assertion failed, DBusPyConn has a DBusConn already", __func__); DBG_WHEREAMI; return NULL; } } ref = NULL; /* Change mainloop from a borrowed reference to an owned reference */ if (!mainloop || mainloop == Py_None) { mainloop = dbus_py_get_default_main_loop(); if (!mainloop) goto err; } else { Py_INCREF(mainloop); } DBG("Constructing Connection from DBusConnection at %p", conn); self = (Connection *)(cls->tp_alloc(cls, 0)); if (!self) goto err; TRACE(self); DBG_WHEREAMI; self->has_mainloop = (mainloop != Py_None); self->conn = NULL; self->filters = PyList_New(0); if (!self->filters) goto err; self->object_paths = PyDict_New(); if (!self->object_paths) goto err; ref = PyWeakref_NewRef((PyObject *)self, NULL); if (!ref) goto err; DBG("Created weak ref %p to (Connection *)%p for (DBusConnection *)%p", ref, self, conn); Py_BEGIN_ALLOW_THREADS ok = dbus_connection_set_data(conn, _connection_python_slot, (void *)ref, (DBusFreeFunction)dbus_py_take_gil_and_xdecref); Py_END_ALLOW_THREADS if (ok) { DBG("Attached weak ref %p ((Connection *)%p) to (DBusConnection *)%p", ref, self, conn); ref = NULL; /* don't DECREF it - the DBusConnection owns it now */ } else { DBG("Failed to attached weak ref %p ((Connection *)%p) to " "(DBusConnection *)%p - will dispose of it", ref, self, conn); PyErr_NoMemory(); goto err; } DBUS_PY_RAISE_VIA_GOTO_IF_FAIL(conn, err); self->conn = conn; /* the DBusPyConnection will close it now */ conn = NULL; if (self->has_mainloop && !dbus_py_set_up_connection((PyObject *)self, mainloop)) { goto err; } Py_CLEAR(mainloop); DBG("%s() -> %p", __func__, self); TRACE(self); return (PyObject *)self; err: DBG("Failed to construct Connection from DBusConnection at %p", conn); Py_CLEAR(mainloop); Py_CLEAR(self); Py_CLEAR(ref); if (conn) { Py_BEGIN_ALLOW_THREADS dbus_connection_close(conn); dbus_connection_unref(conn); Py_END_ALLOW_THREADS } DBG("%s() fail", __func__); DBG_WHEREAMI; return NULL; }
static PyObject* sllist_insertnodebefore(SLListObject* self, PyObject* arg) { PyObject* inserted = NULL; PyObject* ref = NULL; if (!PyArg_UnpackTuple(arg, "insertnodebefore", 2, 2, &inserted, &ref)) return NULL; if (!PyObject_TypeCheck(inserted, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "Inserted object must be an sllistnode"); return NULL; } SLListNodeObject* inserted_node = (SLListNodeObject*)inserted; if (inserted_node->list_weakref != Py_None || inserted_node->next != Py_None) { PyErr_SetString(PyExc_ValueError, "Inserted node must not belong to a list"); return NULL; } if (!PyObject_TypeCheck(ref, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "ref_node argument must be an sllistnode"); return NULL; } SLListNodeObject* ref_node = (SLListNodeObject*)ref; if (ref_node->list_weakref == Py_None) { PyErr_SetString(PyExc_ValueError, "ref_node does not belong to a list"); return NULL; } PyObject* list_ref = PyWeakref_GetObject(ref_node->list_weakref); if (list_ref != (PyObject*)self) { PyErr_SetString(PyExc_ValueError, "ref_node belongs to another list"); return NULL; } sllistnode_link(ref, inserted_node, (PyObject*)self); /* getting prev node for this from arg*/ SLListNodeObject* prev_node = sllist_get_prev(self, ref_node); /* putting new node in created gap, not first and exists */ if ((PyObject*)prev_node != Py_None && prev_node != NULL) prev_node->next = inserted; else self->first = inserted; Py_INCREF(inserted); ++self->size; Py_INCREF(inserted); return inserted; }
int conn_poll(connectionObject *self) { int res = PSYCO_POLL_ERROR; Dprintf("conn_poll: status = %d", self->status); switch (self->status) { case CONN_STATUS_SETUP: Dprintf("conn_poll: status -> CONN_STATUS_CONNECTING"); self->status = CONN_STATUS_CONNECTING; res = PSYCO_POLL_WRITE; break; case CONN_STATUS_CONNECTING: res = _conn_poll_connecting(self); if (res == PSYCO_POLL_OK && self->async) { res = _conn_poll_setup_async(self); } break; case CONN_STATUS_DATESTYLE: res = _conn_poll_setup_async(self); break; case CONN_STATUS_READY: case CONN_STATUS_BEGIN: case CONN_STATUS_PREPARED: res = _conn_poll_query(self); if (res == PSYCO_POLL_OK && self->async && self->async_cursor) { /* An async query has just finished: parse the tuple in the * target cursor. */ cursorObject *curs; PyObject *py_curs = PyWeakref_GetObject(self->async_cursor); if (Py_None == py_curs) { pq_clear_async(self); PyErr_SetString(InterfaceError, "the asynchronous cursor has disappeared"); res = PSYCO_POLL_ERROR; break; } curs = (cursorObject *)py_curs; CLEARPGRES(curs->pgres); curs->pgres = pq_get_last_result(self); /* fetch the tuples (if there are any) and build the result. We * don't care if pq_fetch return 0 or 1, but if there was an error, * we want to signal it to the caller. */ if (pq_fetch(curs, 0) == -1) { res = PSYCO_POLL_ERROR; } /* We have finished with our async_cursor */ Py_CLEAR(self->async_cursor); } break; default: Dprintf("conn_poll: in unexpected state"); res = PSYCO_POLL_ERROR; } return res; }
static PyObject* sllist_remove(SLListObject* self, PyObject* arg) { SLListNodeObject* del_node; SLListNodeObject* prev; PyObject* list_ref; PyObject* value; if (!PyObject_TypeCheck(arg, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "Argument is not an sllistnode"); return NULL; } if (self->first == Py_None) { PyErr_SetString(PyExc_ValueError, "List is empty"); return NULL; } del_node = (SLListNodeObject*)arg; if (del_node->list_weakref == Py_None) { PyErr_SetString(PyExc_ValueError, "sllistnode does not belong to a list"); return NULL; } list_ref = PyWeakref_GetObject(del_node->list_weakref); if (list_ref != (PyObject*)self) { PyErr_SetString(PyExc_ValueError, "sllistnode belongs to another list"); return NULL; } /* remove first node case */ if(self->first == arg) { self->first = del_node->next; if (self->last == arg) self->last = Py_None; } /* we are sure that we have more than 1 node */ else { /* making gap */ prev = sllist_get_prev(self, del_node); prev->next = del_node->next; if (self->last == arg) self->last = (PyObject*)prev; } --self->size; value = del_node->value; Py_INCREF(value); sllistnode_delete(del_node); return value; }
static PyObject *PySSL_SSLdo_handshake(PySSLObject *self) { int ret; int err; int sockstate; /* Actually negotiate SSL connection */ /* XXX If SSL_do_handshake() returns 0, it's also a failure. */ sockstate = 0; do { PySocketSockObject *sock = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); if (((PyObject*)sock) == Py_None) { _setSSLError("Underlying socket connection gone", PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); return NULL; } PySSL_BEGIN_ALLOW_THREADS ret = SSL_do_handshake(self->ssl); err = SSL_get_error(self->ssl, ret); PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { return NULL; } if (err == SSL_ERROR_WANT_READ) { sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, ERRSTR("The handshake operation timed out")); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, ERRSTR("Underlying socket has been closed.")); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, ERRSTR("Underlying socket too large for select().")); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; } } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); if (ret < 1) return PySSL_SetError(self, ret, __FILE__, __LINE__); self->ssl->debug = 1; if (self->peer_cert) X509_free (self->peer_cert); PySSL_BEGIN_ALLOW_THREADS self->peer_cert = SSL_get_peer_certificate(self->ssl); PySSL_END_ALLOW_THREADS Py_INCREF(Py_None); return Py_None; }
static PyObject * PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno) { PyObject *v; char buf[2048]; char *errstr; int err; enum py_ssl_error p = PY_SSL_ERROR_NONE; assert(ret <= 0); if (obj->ssl != NULL) { err = SSL_get_error(obj->ssl, ret); switch (err) { case SSL_ERROR_ZERO_RETURN: errstr = "TLS/SSL connection has been closed"; p = PY_SSL_ERROR_ZERO_RETURN; break; case SSL_ERROR_WANT_READ: errstr = "The operation did not complete (read)"; p = PY_SSL_ERROR_WANT_READ; break; case SSL_ERROR_WANT_WRITE: p = PY_SSL_ERROR_WANT_WRITE; errstr = "The operation did not complete (write)"; break; case SSL_ERROR_WANT_X509_LOOKUP: p = PY_SSL_ERROR_WANT_X509_LOOKUP; errstr = "The operation did not complete (X509 lookup)"; break; case SSL_ERROR_WANT_CONNECT: p = PY_SSL_ERROR_WANT_CONNECT; errstr = "The operation did not complete (connect)"; break; case SSL_ERROR_SYSCALL: { unsigned long e = ERR_get_error(); if (e == 0) { PySocketSockObject *s = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket); if (ret == 0 || (((PyObject *)s) == Py_None)) { p = PY_SSL_ERROR_EOF; errstr = "EOF occurred in violation of protocol"; } else if (ret == -1) { /* underlying BIO reported an I/O error */ return s->errorhandler(); } else { /* possible? */ p = PY_SSL_ERROR_SYSCALL; errstr = "Some I/O error occurred"; } } else { p = PY_SSL_ERROR_SYSCALL; /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); } break; } case SSL_ERROR_SSL: { unsigned long e = ERR_get_error(); p = PY_SSL_ERROR_SSL; if (e != 0) /* XXX Protected by global interpreter lock */ errstr = ERR_error_string(e, NULL); else { /* possible? */ errstr = "A failure in the SSL library occurred"; } break; } default: p = PY_SSL_ERROR_INVALID_ERROR_CODE; errstr = "Invalid error code"; } } else { errstr = ERR_error_string(ERR_peek_last_error(), NULL); } PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); v = Py_BuildValue("(is)", p, buf); if (v != NULL) { PyErr_SetObject(PySSLErrorObject, v); Py_DECREF(v); } return NULL; }
static PyObject* sllist_insertnodeafter(SLListObject* self, PyObject* arg) { PyObject* inserted = NULL; PyObject* ref = NULL; if (!PyArg_UnpackTuple(arg, "insertnodeafter", 2, 2, &inserted, &ref)) return NULL; if (!PyObject_TypeCheck(inserted, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "Inserted object must be an sllistnode"); return NULL; } SLListNodeObject* inserted_node = (SLListNodeObject*)inserted; if (inserted_node->list_weakref != Py_None || inserted_node->next != Py_None) { PyErr_SetString(PyExc_ValueError, "Inserted node must not belong to a list"); return NULL; } if (!PyObject_TypeCheck(ref, &SLListNodeType)) { PyErr_SetString(PyExc_TypeError, "ref_node argument must be an sllistnode"); return NULL; } SLListNodeObject* ref_node = (SLListNodeObject*)ref; if (ref_node->list_weakref == Py_None) { PyErr_SetString(PyExc_ValueError, "ref_node does not belong to a list"); return NULL; } PyObject* list_ref = PyWeakref_GetObject(ref_node->list_weakref); if (list_ref != (PyObject*)self) { PyErr_SetString(PyExc_ValueError, "ref_node belongs to another list"); return NULL; } sllistnode_link(ref_node->next, inserted_node, (PyObject*)self); /* putting new node in created gap */ ref_node->next = inserted; if (self->last == ref) self->last = inserted; Py_INCREF(inserted); ++self->size; Py_INCREF(inserted); return inserted; }
/* * Invoke a single slot (Qt or Python) and return the result. */ PyObject *sip_api_invoke_slot(const sipSlot *slot, PyObject *sigargs) { PyObject *sa, *oxtype, *oxvalue, *oxtb, *sfunc, *sref; /* Keep some compilers quiet. */ oxtype = oxvalue = oxtb = NULL; /* Fan out Qt signals. (Only PyQt3 will do this.) */ if (slot->name != NULL && slot->name[0] != '\0') { assert(sipQtSupport->qt_emit_signal); if (sipQtSupport->qt_emit_signal(slot->pyobj, slot->name, sigargs) < 0) return NULL; Py_INCREF(Py_None); return Py_None; } /* Get the object to call, resolving any weak references. */ if (slot->weakSlot == Py_True) { /* * The slot is guaranteed to be Ok because it has an extra reference or * is None. */ sref = slot->pyobj; Py_INCREF(sref); } else if (slot -> weakSlot == NULL) sref = NULL; else if ((sref = PyWeakref_GetObject(slot -> weakSlot)) == NULL) return NULL; else Py_INCREF(sref); if (sref == Py_None) { /* * If the real object has gone then we pretend everything is Ok. This * mimics the Qt behaviour of not caring if a receiving object has been * deleted. */ Py_DECREF(sref); Py_INCREF(Py_None); return Py_None; } if (slot -> pyobj == NULL) { PyObject *self = (sref != NULL ? sref : slot->meth.mself); /* * If the receiver wraps a C++ object then ignore the call if it no * longer exists. */ if (PyObject_TypeCheck(self, (PyTypeObject *)&sipSimpleWrapper_Type) && sip_api_get_address((sipSimpleWrapper *)self) == NULL) { Py_XDECREF(sref); Py_INCREF(Py_None); return Py_None; } #if PY_MAJOR_VERSION >= 3 sfunc = PyMethod_New(slot->meth.mfunc, self); #else sfunc = PyMethod_New(slot->meth.mfunc, self, slot->meth.mclass); #endif if (sfunc == NULL) { Py_XDECREF(sref); return NULL; } } else if (slot -> name != NULL) { char *mname = slot -> name + 1; PyObject *self = (sref != NULL ? sref : slot->pyobj); if ((sfunc = PyObject_GetAttrString(self, mname)) == NULL || !PyCFunction_Check(sfunc)) { /* * Note that in earlier versions of SIP this error would be * detected when the slot was connected. */ PyErr_Format(PyExc_NameError,"Invalid slot %s",mname); Py_XDECREF(sfunc); Py_XDECREF(sref); return NULL; } } else { sfunc = slot->pyobj; Py_INCREF(sfunc); } /* * We make repeated attempts to call a slot. If we work out that it failed * because of an immediate type error we try again with one less argument. * We keep going until we run out of arguments to drop. This emulates the * Qt ability of the slot to accept fewer arguments than a signal provides. */ sa = sigargs; Py_INCREF(sa); for (;;) { PyObject *nsa, *xtype, *xvalue, *xtb, *resobj; if ((resobj = PyEval_CallObject(sfunc, sa)) != NULL) { Py_DECREF(sfunc); Py_XDECREF(sref); /* Remove any previous exception. */ if (sa != sigargs) { Py_XDECREF(oxtype); Py_XDECREF(oxvalue); Py_XDECREF(oxtb); PyErr_Clear(); } Py_DECREF(sa); return resobj; } /* Get the exception. */ PyErr_Fetch(&xtype,&xvalue,&xtb); /* * See if it is unacceptable. An acceptable failure is a type error * with no traceback - so long as we can still reduce the number of * arguments and try again. */ if (!PyErr_GivenExceptionMatches(xtype,PyExc_TypeError) || xtb != NULL || PyTuple_GET_SIZE(sa) == 0) { /* * If there is a traceback then we must have called the slot and * the exception was later on - so report the exception as is. */ if (xtb != NULL) { if (sa != sigargs) { Py_XDECREF(oxtype); Py_XDECREF(oxvalue); Py_XDECREF(oxtb); } PyErr_Restore(xtype,xvalue,xtb); } else if (sa == sigargs) PyErr_Restore(xtype,xvalue,xtb); else { /* * Discard the latest exception and restore the original one. */ Py_XDECREF(xtype); Py_XDECREF(xvalue); Py_XDECREF(xtb); PyErr_Restore(oxtype,oxvalue,oxtb); } break; } /* If this is the first attempt, save the exception. */ if (sa == sigargs) { oxtype = xtype; oxvalue = xvalue; oxtb = xtb; } else { Py_XDECREF(xtype); Py_XDECREF(xvalue); Py_XDECREF(xtb); } /* Create the new argument tuple. */ if ((nsa = PyTuple_GetSlice(sa,0,PyTuple_GET_SIZE(sa) - 1)) == NULL) { /* Tidy up. */ Py_XDECREF(oxtype); Py_XDECREF(oxvalue); Py_XDECREF(oxtb); break; } Py_DECREF(sa); sa = nsa; } Py_DECREF(sfunc); Py_XDECREF(sref); Py_DECREF(sa); return NULL; }
static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args) { char *data; int len; int count; int sockstate; int err; int nonblocking; PySocketSockObject *sock = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); if (((PyObject*)sock) == Py_None) { _setSSLError("Underlying socket connection gone", PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); return NULL; } if (!PyArg_ParseTuple(args, "y#:write", &data, &count)) return NULL; /* just in case the blocking state of the socket has been changed */ nonblocking = (sock->sock_timeout >= 0.0); BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); sockstate = check_socket_and_wait_for_timeout(sock, 1); if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, "The write operation timed out"); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, "Underlying socket has been closed."); return NULL; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, "Underlying socket too large for select()."); return NULL; } do { err = 0; PySSL_BEGIN_ALLOW_THREADS len = SSL_write(self->ssl, data, count); err = SSL_get_error(self->ssl, len); PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { return NULL; } if (err == SSL_ERROR_WANT_READ) { sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { sockstate = check_socket_and_wait_for_timeout(sock, 1); } else { sockstate = SOCKET_OPERATION_OK; } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, "The write operation timed out"); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { PyErr_SetString(PySSLErrorObject, "Underlying socket has been closed."); return NULL; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; } } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); if (len > 0) return PyLong_FromLong(len); else return PySSL_SetError(self, len, __FILE__, __LINE__); }
static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args) { PyObject *dest = NULL; Py_buffer buf; int buf_passed = 0; int count = -1; char *mem; /* XXX this should use Py_ssize_t */ int len = 1024; int sockstate; int err; int nonblocking; PySocketSockObject *sock = (PySocketSockObject *) PyWeakref_GetObject(self->Socket); if (((PyObject*)sock) == Py_None) { _setSSLError("Underlying socket connection gone", PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__); return NULL; } if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count)) return NULL; if ((dest == NULL) || (dest == Py_None)) { if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) return NULL; mem = PyByteArray_AS_STRING(dest); } else if (PyLong_Check(dest)) { len = PyLong_AS_LONG(dest); if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len))) return NULL; mem = PyByteArray_AS_STRING(dest); } else { if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0) return NULL; mem = buf.buf; len = buf.len; if ((count > 0) && (count <= len)) len = count; buf_passed = 1; } /* just in case the blocking state of the socket has been changed */ nonblocking = (sock->sock_timeout >= 0.0); BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking); BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking); /* first check if there are bytes ready to be read */ PySSL_BEGIN_ALLOW_THREADS count = SSL_pending(self->ssl); PySSL_END_ALLOW_THREADS if (!count) { sockstate = check_socket_and_wait_for_timeout(sock, 0); if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, "The read operation timed out"); goto error; } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) { PyErr_SetString(PySSLErrorObject, "Underlying socket too large for select()."); goto error; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { count = 0; goto done; } } do { err = 0; PySSL_BEGIN_ALLOW_THREADS count = SSL_read(self->ssl, mem, len); err = SSL_get_error(self->ssl, count); PySSL_END_ALLOW_THREADS if (PyErr_CheckSignals()) goto error; if (err == SSL_ERROR_WANT_READ) { sockstate = check_socket_and_wait_for_timeout(sock, 0); } else if (err == SSL_ERROR_WANT_WRITE) { sockstate = check_socket_and_wait_for_timeout(sock, 1); } else if ((err == SSL_ERROR_ZERO_RETURN) && (SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)) { count = 0; goto done; } else { sockstate = SOCKET_OPERATION_OK; } if (sockstate == SOCKET_HAS_TIMED_OUT) { PyErr_SetString(PySSLErrorObject, "The read operation timed out"); goto error; } else if (sockstate == SOCKET_IS_NONBLOCKING) { break; } } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE); if (count <= 0) { PySSL_SetError(self, count, __FILE__, __LINE__); goto error; } done: if (!buf_passed) { PyObject *res = PyBytes_FromStringAndSize(mem, count); Py_DECREF(dest); return res; } else { PyBuffer_Release(&buf); return PyLong_FromLong(count); } error: if (!buf_passed) { Py_DECREF(dest); } else { PyBuffer_Release(&buf); } return NULL; }
int ObjectRow_PyObject__init(ObjectRow_PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *pytmp, *pydesc, *cursor, *row, *o_type, *pickle_dict = 0; struct module_state *mstate; if (!PyArg_ParseTuple(args, "OO|O!", &cursor, &row, &PyDict_Type, &pickle_dict)) return -1; mstate = GETSTATE_FROMTYPE(self); if (pickle_dict) { /* If row or cursor weren't specified, then we require the third arg * (pickle_dict) be a dictionary, and we basically behave as this dict. * We do this for example from Database.add() */ self->pickle = pickle_dict; Py_INCREF(self->pickle); self->row = Py_None; Py_INCREF(self->row); self->desc = Py_None; Py_INCREF(self->desc); return 0; } /* First argument is the db cursor from which we fetch the row description * and object types. Or, it is a 2-tuple of same. */ if (PyTuple_Check(cursor)) { self->desc = PySequence_GetItem(cursor, 0); // new ref self->object_types = PySequence_GetItem(cursor, 1); // new ref } else if (!PyObject_HasAttrString(cursor, "_db")) { PyErr_Format(PyExc_ValueError, "First argument is not a Cursor or tuple object"); return -1; } else { PyObject *weak_db = PyObject_GetAttrString(cursor, "_db"); // new ref PyObject *db = PyWeakref_GetObject(weak_db); // borrowed ref self->object_types = PyObject_GetAttrString(db, "_object_types"); // new ref self->desc = PyObject_GetAttrString(cursor, "description"); // new ref Py_XDECREF(weak_db); } self->row = row; self->type_name = PySequence_GetItem(row, 0); // new ref if (!PyString_Check(self->type_name) && !PyUnicode_Check(self->type_name)) { Py_XDECREF(self->desc); Py_XDECREF(self->object_types); PyErr_Format(PyExc_ValueError, "First element of row must be object type"); return -1; } o_type = PyDict_GetItem(self->object_types, self->type_name); // borrowed ref self->attrs = PySequence_GetItem(o_type, 1); // new ref if (!self->attrs) { char *type_name; #if PY_MAJOR_VERSION >= 3 PyObject *bytes = PyUnicode_AsUTF8String(self->type_name); type_name = strdup(PyBytes_AS_STRING(bytes)); Py_DECREF(bytes); #else type_name = strdup(PyString_AsString(self->type_name)); #endif PyErr_Format(PyExc_ValueError, "Object type '%s' not defined.", type_name); free(type_name); Py_XDECREF(self->desc); Py_XDECREF(self->object_types); return -1; } /* For the queries dict key we use the address of the desc object rather * than the desc itself. desc is a tuple, and if we use it as a key it * will result in a hash() on the desc for each row which is much more * expensive. pysqlite passes us the same description tuple object for * each row in a query so it is safe to use the address. */ pydesc = PyLong_FromVoidPtr(self->desc); pytmp = PyDict_GetItem(mstate->queries, pydesc); self->query_info = pytmp ? (QueryInfo *)PyCObject_AsVoidPtr(pytmp) : NULL; if (!self->query_info) { /* This is a row for a query we haven't seen before, so we need to do * some initial setup. Most of what we do here is convert row and * attribute metadata into convenient data structures for later access. */ PyObject **desc_tuple = PySequence_Fast_ITEMS(self->desc); PyObject *key, *value; int i = 0; Py_ssize_t pos = 0; self->query_info = (QueryInfo *)malloc(sizeof(QueryInfo)); self->query_info->refcount = 0; self->query_info->pickle_idx = -1; self->query_info->idxmap = PyDict_New(); /* Iterate over the columns from the SQL query and keep track of * attribute names and their indexes within the row tuple. Start at * index 2 because index 0 and 1 are internal (the object type name * literal and type id). */ for (i = 2; i < PySequence_Length(self->desc); i++) { PyObject **desc_col = PySequence_Fast_ITEMS(desc_tuple[i]); ObjectAttribute *attr = (ObjectAttribute *)malloc(sizeof(ObjectAttribute)); attr->pickled = 0; attr->index = i; if (PyStr_Compare(desc_col[0], "pickle") == 0) self->query_info->pickle_idx = i; pytmp = PyCObject_FromVoidPtr(attr, free); PyDict_SetItem(self->query_info->idxmap, desc_col[0], pytmp); Py_DECREF(pytmp); } /* Now iterate over the kaa.db object attribute dict, storing the * type of each attribute, its flags, and figure out whether or not * we need to look in the pickle for that attribute. */ while (PyDict_Next(self->attrs, &pos, &key, &value)) { pytmp = PyDict_GetItem(self->query_info->idxmap, key); ObjectAttribute *attr = pytmp ? (ObjectAttribute *)PyCObject_AsVoidPtr(pytmp) : NULL; if (!attr) { attr = (ObjectAttribute *)malloc(sizeof(ObjectAttribute)); attr->index = -1; pytmp = PyCObject_FromVoidPtr(attr, free); PyDict_SetItem(self->query_info->idxmap, key, pytmp); Py_DECREF(pytmp); } attr->type = PySequence_Fast_GET_ITEM(value, 0); attr->flags = PyInt_AsLong(PySequence_Fast_GET_ITEM(value, 1)); attr->named_ivtidx = PyObject_RichCompareBool(PySequence_Fast_GET_ITEM(value, 2), key, Py_EQ) == 1; if (IS_ATTR_INDEXED_IGNORE_CASE(attr->flags) || attr->flags & ATTR_SIMPLE) // attribute is set to ignore case, or it's ATTR_SIMPLE, so we // need to look in the pickle for this attribute. attr->pickled = 1; else attr->pickled = 0; } /* Create a hash table that maps object type ids to type names. */ pos = 0; self->query_info->type_names = PyDict_New(); while (PyDict_Next(self->object_types, &pos, &key, &value)) { PyObject *type_id = PySequence_Fast_GET_ITEM(value, 0); PyDict_SetItem(self->query_info->type_names, type_id, key); } pytmp = PyCObject_FromVoidPtr(self->query_info, NULL); PyDict_SetItem(mstate->queries, pydesc, pytmp); Py_DECREF(pytmp); } Py_DECREF(pydesc); self->query_info->refcount++; if (self->query_info->pickle_idx >= 0) { // Pickle column included in row. Set _pickle member to True which // indicates the pickle data was fetched, but just hasn't yet been // unpickled. if (PySequence_Fast_GET_ITEM(self->row, self->query_info->pickle_idx) != Py_None) self->has_pickle = 1; self->pickle = Py_True; } else self->pickle = Py_False; Py_INCREF(self->pickle); Py_INCREF(self->row); if (pickle_dict && pickle_dict != Py_None) { Py_DECREF(self->pickle); self->pickle = pickle_dict; Py_INCREF(self->pickle); self->has_pickle = self->unpickled = 1; } return 0; }