Exemple #1
0
static int
GAIRequest_tp_clear(GAIRequest *self)
{
    Py_CLEAR(self->callback);
    return RequestType.tp_clear((PyObject *)self);
}
Exemple #2
0
static int
psutil_bsd_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}
Exemple #3
0
/* Initialize the default adapters map
 *
 * Return 0 on success, else -1 and set an exception.
 */
static int
psyco_adapters_init(PyObject *mod)
{
    PyObject *call = NULL;
    int rv = -1;

    if (0 != microprotocols_add(&PyFloat_Type, NULL, (PyObject*)&pfloatType)) {
        goto exit;
    }
#if PY_MAJOR_VERSION < 3
    if (0 != microprotocols_add(&PyInt_Type, NULL, (PyObject*)&pintType)) {
        goto exit;
    }
#endif
    if (0 != microprotocols_add(&PyLong_Type, NULL, (PyObject*)&pintType)) {
        goto exit;
    }
    if (0 != microprotocols_add(&PyBool_Type, NULL, (PyObject*)&pbooleanType)) {
        goto exit;
    }

    /* strings */
#if PY_MAJOR_VERSION < 3
    if (0 != microprotocols_add(&PyString_Type, NULL, (PyObject*)&qstringType)) {
        goto exit;
    }
#endif
    if (0 != microprotocols_add(&PyUnicode_Type, NULL, (PyObject*)&qstringType)) {
        goto exit;
    }

    /* binary */
#if PY_MAJOR_VERSION < 3
    if (0 != microprotocols_add(&PyBuffer_Type, NULL, (PyObject*)&binaryType)) {
        goto exit;
    }
#else
    if (0 != microprotocols_add(&PyBytes_Type, NULL, (PyObject*)&binaryType)) {
        goto exit;
    }
#endif

#if PY_MAJOR_VERSION >= 3 || PY_MINOR_VERSION >= 6
    if (0 != microprotocols_add(&PyByteArray_Type, NULL, (PyObject*)&binaryType)) {
        goto exit;
    }
#endif
#if PY_MAJOR_VERSION >= 3 || PY_MINOR_VERSION >= 7
    if (0 != microprotocols_add(&PyMemoryView_Type, NULL, (PyObject*)&binaryType)) {
        goto exit;
    }
#endif

    if (0 != microprotocols_add(&PyList_Type, NULL, (PyObject*)&listType)) {
        goto exit;
    }

    /* the module has already been initialized, so we can obtain the callable
       objects directly from its dictionary :) */
    if (!(call = PyMapping_GetItemString(mod, "DateFromPy"))) { goto exit; }
    if (0 != microprotocols_add(PyDateTimeAPI->DateType, NULL, call)) { goto exit; }
    Py_CLEAR(call);

    if (!(call = PyMapping_GetItemString(mod, "TimeFromPy"))) { goto exit; }
    if (0 != microprotocols_add(PyDateTimeAPI->TimeType, NULL, call)) { goto exit; }
    Py_CLEAR(call);

    if (!(call = PyMapping_GetItemString(mod, "TimestampFromPy"))) { goto exit; }
    if (0 != microprotocols_add(PyDateTimeAPI->DateTimeType, NULL, call)) { goto exit; }
    Py_CLEAR(call);

    if (!(call = PyMapping_GetItemString(mod, "IntervalFromPy"))) { goto exit; }
    if (0 != microprotocols_add(PyDateTimeAPI->DeltaType, NULL, call)) { goto exit; }
    Py_CLEAR(call);

#ifdef HAVE_MXDATETIME
    /* as above, we use the callable objects from the psycopg module */
    if (NULL != (call = PyMapping_GetItemString(mod, "TimestampFromMx"))) {
        if (0 != microprotocols_add(mxDateTime.DateTime_Type, NULL, call)) { goto exit; }
        Py_CLEAR(call);

        /* if we found the above, we have this too. */
        if (!(call = PyMapping_GetItemString(mod, "TimeFromMx"))) { goto exit; }
        if (0 != microprotocols_add(mxDateTime.DateTimeDelta_Type, NULL, call)) { goto exit; }
        Py_CLEAR(call);
    }
    else {
        PyErr_Clear();
    }
#endif

    /* Success! */
    rv = 0;

exit:
    Py_XDECREF(call);

    return rv;
}
Exemple #4
0
static void
BlameIter_dealloc(BlameIter *self)
{
    Py_CLEAR(self->blame);
    PyObject_Del(self);
}
Exemple #5
0
void
PyThreadState_Clear(PyThreadState *tstate)
{
    if (Py_VerboseFlag && tstate->frame != NULL)
        fprintf(stderr,
          "PyThreadState_Clear: warning: thread still has a frame\n");

    Py_CLEAR(tstate->frame);

    Py_CLEAR(tstate->dict);
    Py_CLEAR(tstate->async_exc);

    Py_CLEAR(tstate->curexc_type);
    Py_CLEAR(tstate->curexc_value);
    Py_CLEAR(tstate->curexc_traceback);

    Py_CLEAR(tstate->exc_type);
    Py_CLEAR(tstate->exc_value);
    Py_CLEAR(tstate->exc_traceback);

    tstate->c_profilefunc = NULL;
    tstate->c_tracefunc = NULL;
    Py_CLEAR(tstate->c_profileobj);
    Py_CLEAR(tstate->c_traceobj);

    Py_CLEAR(tstate->coroutine_wrapper);
}
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;
            IFCLEARPGRES(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) == -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;
}
Exemple #7
0
bool QtApp::openWindow(const std::string& name) {
    assert(QThread::currentThread() == qApp->thread());

    PyScopedGIL gil;

    PyObject* rootObj = handleModuleCommand("gui", "RootObjs.__getitem__", "(s)", name.c_str());
    if(!rootObj) return false; // Python errs already handled in handleModuleCommand

    PyQtGuiObject* control = NULL;
    control = (PyQtGuiObject*) PyObject_GetAttrString(rootObj, "guiObj");
    if(!control) {
        if(PyErr_Occurred()) PyErr_Print();
        Py_DECREF(rootObj);
        return false;
    }

    if((PyObject*) control == Py_None) Py_CLEAR(control);
    if(control) {
        if(PyType_IsSubtype(Py_TYPE(control), &QtGuiObject_Type)) {
            QtBaseWidget::ScopedRef win(control->widget);
            if(win) {
                win->show();
                return true;
            }
            // continue with existing control but create new window
        }
        else {
            printf("Qt open window: existing rootObj.guiObj is of wrong type\n");
            // reset and continue with new control creation
            Py_CLEAR(control);
        }
    }

    if(!control) {
        control = (PyQtGuiObject*) PyObject_CallFunction((PyObject*) &QtGuiObject_Type, NULL);
        if(!control) {
            if(PyErr_Occurred()) PyErr_Print();
            Py_DECREF(rootObj);
            return false;
        }

        assert(control->root == NULL);
        control->root = control;
        Py_XINCREF(control->root);
        assert(control->subjectObject == NULL);
        control->subjectObject = PyObject_GetAttrString(rootObj, "obj");
        if(!control->subjectObject) {
            if(PyErr_Occurred()) PyErr_Print();
            Py_DECREF(rootObj);
            Py_DECREF(control);
            return false;
        }
    }

    if(PyObject_SetAttrString(rootObj, "guiObj", (PyObject*) control) < 0) {
        if(PyErr_Occurred()) PyErr_Print();
        Py_DECREF(rootObj);
        Py_DECREF(control);
        return false;
    }

    // check subjectObject
    {
        PyObject* subjectObject = PyObject_GetAttrString(rootObj, "obj");
        if(!subjectObject) {
            if(PyErr_Occurred()) PyErr_Print();
            // continue, maybe it doesn't matter
        }
        else {
            if(subjectObject != control->subjectObject) {
                printf("Qt open window: got new subject object\n");
                // strange, but just overtake and continue
                Py_CLEAR(control->subjectObject);
                control->subjectObject = subjectObject;
                subjectObject = NULL;
            }
        }
        Py_XDECREF(subjectObject);
    }

    QtBaseWidget* win = new QtBaseWidget(control);
    win->setAttribute(Qt::WA_DeleteOnClose);

    // set title
    {
        PyObject* title = PyObject_GetAttrString(rootObj, "title");
        std::string titleStr;
        if(!title || !pyStr(title, titleStr)) {
            if(PyErr_Occurred()) PyErr_Print();
            win->setWindowTitle(QString::fromStdString(name));
        }
        else {
            win->setWindowTitle(QString::fromStdString(titleStr));
        }
        Py_XDECREF(title);
    }

    Vec size = control->setupChilds();
    win->setMinimumSize(size.x, size.y);

    // ...

    win->show();
    control->layout();

    Py_DECREF(rootObj);
    Py_DECREF(control);
    return true;
}
Exemple #8
0
static void
tb_clear(PyTracebackObject *tb)
{
    Py_CLEAR(tb->tb_next);
    Py_CLEAR(tb->tb_frame);
}
Exemple #9
0
static void
show_warning(PyObject *filename, int lineno, PyObject *text, PyObject
                *category, PyObject *sourceline)
{
    PyObject *f_stderr;
    PyObject *name;
    char lineno_str[128];
    _Py_IDENTIFIER(__name__);

    PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);

    name = _PyObject_GetAttrId(category, &PyId___name__);
    if (name == NULL)  /* XXX Can an object lack a '__name__' attribute? */
        goto error;

    f_stderr = _PySys_GetObjectId(&PyId_stderr);
    if (f_stderr == NULL) {
        fprintf(stderr, "lost sys.stderr\n");
        goto error;
    }

    /* Print "filename:lineno: category: text\n" */
    if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
        goto error;
    if (PyFile_WriteString(lineno_str, f_stderr) < 0)
        goto error;
    if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
        goto error;
    if (PyFile_WriteString(": ", f_stderr) < 0)
        goto error;
    if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
        goto error;
    if (PyFile_WriteString("\n", f_stderr) < 0)
        goto error;
    Py_CLEAR(name);

    /* Print "  source_line\n" */
    if (sourceline) {
        int kind;
        void *data;
        Py_ssize_t i, len;
        Py_UCS4 ch;
        PyObject *truncated;

        if (PyUnicode_READY(sourceline) < 1)
            goto error;

        kind = PyUnicode_KIND(sourceline);
        data = PyUnicode_DATA(sourceline);
        len = PyUnicode_GET_LENGTH(sourceline);
        for (i=0; i<len; i++) {
            ch = PyUnicode_READ(kind, data, i);
            if (ch != ' ' && ch != '\t' && ch != '\014')
                break;
        }

        truncated = PyUnicode_Substring(sourceline, i, len);
        if (truncated == NULL)
            goto error;

        PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
        Py_DECREF(truncated);
        PyFile_WriteString("\n", f_stderr);
    }
    else {
        _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
    }

error:
    Py_XDECREF(name);
    PyErr_Clear();
}
Exemple #10
0
static int normalize_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}
Exemple #11
0
void path_cleanup(struct path_arg *path)
{
	Py_CLEAR(path->object);
	Py_CLEAR(path->cleanup);
}
Exemple #12
0
static void
SignatureIter_tp_dealloc (SignatureIter *self)
{
    Py_CLEAR(self->bytes);
    PyObject_Del(self);
}
Exemple #13
0
static int
Snmp_updatereactor(void)
{
	int maxfd = 0, block = 0, fd, result, i;
	PyObject *keys, *key, *tmp;
	SnmpReaderObject *reader;
	fd_set fdset;
	struct timeval timeout;
	double to;

	FD_ZERO(&fdset);
	block = 1;		/* This means we don't have a timeout
				   planned. block will be reset to 0
				   if we need to setup a timeout. */
	snmp_select_info(&maxfd, &fdset, &timeout, &block);
	for (fd = 0; fd < maxfd; fd++) {
		if (FD_ISSET(fd, &fdset)) {
			result = PyDict_Contains(SnmpFds, PyInt_FromLong(fd));
			if (result == -1)
				return -1;
			if (!result) {
				/* Add this fd to the reactor */
				if ((reader = (SnmpReaderObject *)
					PyObject_CallObject((PyObject *)&SnmpReaderType,
					    NULL)) == NULL)
					return -1;
				reader->fd = fd;
				if ((key =
					PyInt_FromLong(fd)) == NULL) {
					Py_DECREF(reader);
					return -1;
				}
				if (PyDict_SetItem(SnmpFds, key, (PyObject*)reader) != 0) {
					Py_DECREF(reader);
					Py_DECREF(key);
					return -1;
				}
				Py_DECREF(key);
				if ((tmp = PyObject_CallMethod(reactor,
					    "addReader", "O", (PyObject*)reader)) ==
				    NULL) {
					Py_DECREF(reader);
					return -1;
				}
				Py_DECREF(tmp);
				Py_DECREF(reader);
			}
		}
	}
	if ((keys = PyDict_Keys(SnmpFds)) == NULL)
		return -1;
	for (i = 0; i < PyList_Size(keys); i++) {
		if ((key = PyList_GetItem(keys, i)) == NULL) {
			Py_DECREF(keys);
			return -1;
		}
		fd = PyInt_AsLong(key);
		if (PyErr_Occurred()) {
			Py_DECREF(keys);
			return -1;
		}
		if ((fd >= maxfd) || (!FD_ISSET(fd, &fdset))) {
			/* Delete this fd from the reactor */
			if ((reader = (SnmpReaderObject*)PyDict_GetItem(SnmpFds,
				    key)) == NULL) {
				Py_DECREF(keys);
				return -1;
			}
			if ((tmp = PyObject_CallMethod(reactor,
				    "removeReader", "O", (PyObject*)reader)) == NULL) {
				Py_DECREF(keys);
				return -1;
			}
			Py_DECREF(tmp);
			if (PyDict_DelItem(SnmpFds, key) == -1) {
				Py_DECREF(keys);
				return -1;
			}
		}
	}
	Py_DECREF(keys);
	/* Setup timeout */
	if (timeoutId) {
		if ((tmp = PyObject_CallMethod(timeoutId, "cancel", NULL)) == NULL) {
			/* Don't really know what to do. It seems better to
			 * raise an exception at this point. */
			Py_CLEAR(timeoutId);
			return -1;
		}
		Py_DECREF(tmp);
		Py_CLEAR(timeoutId);
	}
	if (!block) {
		to = (double)timeout.tv_sec +
		    (double)timeout.tv_usec/(double)1000000;
		if ((timeoutId = PyObject_CallMethod(reactor, "callLater", "dO",
			    to, timeoutFunction)) == NULL) {
			return -1;
		}
	}
	return 0;
}
Exemple #14
0
static int
Snmp_handle(int operation, netsnmp_session *session, int reqid,
    netsnmp_pdu *response, void *magic)
{
	PyObject *key, *defer, *results = NULL, *resultvalue = NULL,
	    *resultoid = NULL, *tmp;
	struct ErrorException *e;
	struct variable_list *vars;
	int i;
	long long counter64;
	SnmpObject *self;

	if ((key = PyInt_FromLong(reqid)) == NULL)
		/* Unknown session, don't know what to do... */
		return 1;
	self = (SnmpObject *)magic;
	if ((defer = PyDict_GetItem(self->defers, key)) == NULL)
		return 1;
	Py_INCREF(defer);
	PyDict_DelItem(self->defers, key);
	Py_DECREF(key);
	/* We have our deferred object. We will be able to trigger callbacks and
	 * errbacks */
	if (operation == NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE) {
		if (response->errstat != SNMP_ERR_NOERROR) {
			for (e = SnmpErrorToException; e->name; e++) {
				if (e->error == response->errstat) {
					PyErr_SetString(e->exception, snmp_errstring(e->error));
					goto fireexception;
				}
			}
			PyErr_Format(SnmpException, "unknown error %ld", response->errstat);
			goto fireexception;
		}
	} else {
		PyErr_SetString(SnmpException, "Timeout");
		goto fireexception;
	}
	if ((results = PyDict_New()) == NULL)
		goto fireexception;
	for (vars = response->variables; vars;
	     vars = vars->next_variable) {
	/* Let's handle the value */
		switch (vars->type) {
		case SNMP_NOSUCHOBJECT:
			PyErr_SetString(SnmpNoSuchObject, "No such object was found");
			goto fireexception;
		case SNMP_NOSUCHINSTANCE:
			PyErr_SetString(SnmpNoSuchInstance, "No such instance exists");
			goto fireexception;
		case SNMP_ENDOFMIBVIEW:
			if (PyDict_Size(results) == 0) {
				PyErr_SetString(SnmpEndOfMibView,
				    "End of MIB was reached");
				goto fireexception;
			} else
				continue;
		case ASN_INTEGER:
			resultvalue = PyLong_FromLong(*vars->val.integer);
			break;
		case ASN_UINTEGER:
		case ASN_TIMETICKS:
		case ASN_GAUGE:
		case ASN_COUNTER:
			resultvalue = PyLong_FromUnsignedLong(
				(unsigned long)*vars->val.integer);
			break;
		case ASN_OCTET_STR:
			resultvalue = PyString_FromStringAndSize(
				(char*)vars->val.string, vars->val_len);
			break;
		case ASN_BIT_STR:
			resultvalue = PyString_FromStringAndSize(
				(char*)vars->val.bitstring, vars->val_len);
			break;
		case ASN_OBJECT_ID:
			if ((resultvalue = PyTuple_New(
					vars->val_len/sizeof(oid))) == NULL)
				goto fireexception;
			for (i = 0; i < vars->val_len/sizeof(oid); i++) {
				if ((tmp = PyLong_FromLong(
						vars->val.objid[i])) == NULL)
					goto fireexception;
				PyTuple_SetItem(resultvalue, i, tmp);
			}
			if ((resultvalue = Snmp_oid2string(resultvalue)) == NULL)
				goto fireexception;
			break;
		case ASN_IPADDRESS:
			if (vars->val_len < 4) {
				PyErr_Format(SnmpException, "IP address is too short (%zd < 4)",
				    vars->val_len);
				goto fireexception;
			}
			resultvalue = PyString_FromFormat("%d.%d.%d.%d",
			    vars->val.string[0],
			    vars->val.string[1],
			    vars->val.string[2],
			    vars->val.string[3]);
			break;
		case ASN_COUNTER64:
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
		case ASN_OPAQUE_U64:
		case ASN_OPAQUE_I64:
		case ASN_OPAQUE_COUNTER64:
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
			counter64 = ((unsigned long long)(vars->val.counter64->high) << 32) +
			    (unsigned long long)(vars->val.counter64->low);
			resultvalue = PyLong_FromUnsignedLongLong(counter64);
			break;
#ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES
		case ASN_OPAQUE_FLOAT:
			resultvalue = PyFloat_FromDouble(*vars->val.floatVal);
			break;
		case ASN_OPAQUE_DOUBLE:
			resultvalue = PyFloat_FromDouble(*vars->val.doubleVal);
			break;
#endif                          /* NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */
		default:
			PyErr_Format(SnmpException, "unknown type returned (%d)",
			    vars->type);
			goto fireexception;
		}
		if (resultvalue == NULL) goto fireexception;

		/* And now, the OID */
		if ((resultoid = PyTuple_New(vars->name_length)) == NULL)
			goto fireexception;
		for (i = 0; i < vars->name_length; i++) {
			if ((tmp = PyLong_FromLong(vars->name[i])) == NULL)
				goto fireexception;
			PyTuple_SetItem(resultoid, i, tmp);
		}
		if ((resultoid = Snmp_oid2string(resultoid)) == NULL)
			goto fireexception;

		/* Put into dictionary */
		PyDict_SetItem(results, resultoid, resultvalue);
		Py_CLEAR(resultoid);
		Py_CLEAR(resultvalue);
	}
	if ((tmp = PyObject_GetAttrString(defer, "callback")) == NULL)
		goto fireexception;
	Py_DECREF(PyObject_CallMethod(reactor, "callLater", "iOO", 0, tmp, results));
	Py_DECREF(tmp);
	Py_DECREF(results);
	Py_DECREF(defer);
	Py_DECREF(self);
	return 1;

fireexception:
	Snmp_invokeerrback(defer);
	Py_XDECREF(results);
	Py_XDECREF(resultvalue);
	Py_XDECREF(resultoid);
	Py_DECREF(defer);
	Py_DECREF(self);
	return 1;
}
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;
}
Exemple #16
0
static int
PyCField_clear(CFieldObject *self)
{
    Py_CLEAR(self->proto);
    return 0;
}
PyObject *
_pygi_marshal_to_py_ghash (PyGIInvokeState   *state,
                           PyGICallableCache *callable_cache,
                           PyGIArgCache      *arg_cache,
                           GIArgument        *arg)
{
    GHashTable *hash_;
    GHashTableIter hash_table_iter;

    PyGIMarshalToPyFunc key_to_py_marshaller;
    PyGIMarshalToPyFunc value_to_py_marshaller;

    PyGIArgCache *key_arg_cache;
    PyGIArgCache *value_arg_cache;
    PyGIHashCache *hash_cache = (PyGIHashCache *)arg_cache;

    GIArgument key_arg;
    GIArgument value_arg;

    PyObject *py_obj = NULL;

    hash_ = arg->v_pointer;

    if (hash_ == NULL) {
        py_obj = Py_None;
        Py_INCREF (py_obj);
        return py_obj;
    }

    py_obj = PyDict_New ();
    if (py_obj == NULL)
        return NULL;

    key_arg_cache = hash_cache->key_cache;
    key_to_py_marshaller = key_arg_cache->to_py_marshaller;

    value_arg_cache = hash_cache->value_cache;
    value_to_py_marshaller = value_arg_cache->to_py_marshaller;

    g_hash_table_iter_init (&hash_table_iter, hash_);
    while (g_hash_table_iter_next (&hash_table_iter,
                                   &key_arg.v_pointer,
                                   &value_arg.v_pointer)) {
        PyObject *py_key;
        PyObject *py_value;
        int retval;


        _pygi_hash_pointer_to_arg (&key_arg, hash_cache->key_cache->type_tag);
        py_key = key_to_py_marshaller ( state,
                                      callable_cache,
                                      key_arg_cache,
                                     &key_arg);

        if (py_key == NULL) {
            Py_CLEAR (py_obj);
            return NULL;
        }

        _pygi_hash_pointer_to_arg (&value_arg, hash_cache->value_cache->type_tag);
        py_value = value_to_py_marshaller ( state,
                                          callable_cache,
                                          value_arg_cache,
                                         &value_arg);

        if (py_value == NULL) {
            Py_CLEAR (py_obj);
            Py_DECREF(py_key);
            return NULL;
        }

        retval = PyDict_SetItem (py_obj, py_key, py_value);

        Py_DECREF (py_key);
        Py_DECREF (py_value);

        if (retval < 0) {
            Py_CLEAR (py_obj);
            return NULL;
        }
    }

    return py_obj;
}
Exemple #18
0
static int
iobase_clear(iobase *self)
{
    Py_CLEAR(self->dict);
    return 0;
}
Exemple #19
0
static int myextension_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}
Exemple #20
0
int BaseMathObject_clear(BaseMathObject *self)
{
	Py_CLEAR(self->cb_user);
	return 0;
}
Exemple #21
0
static int
__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m)
{
    Py_CLEAR(m->func_closure);
    Py_CLEAR(m->func.m_module);
    Py_CLEAR(m->func_dict);
    Py_CLEAR(m->func_name);
    Py_CLEAR(m->func_qualname);
    Py_CLEAR(m->func_doc);
    Py_CLEAR(m->func_globals);
    Py_CLEAR(m->func_code);
    Py_CLEAR(m->func_classobj);
    Py_CLEAR(m->defaults_tuple);
    Py_CLEAR(m->defaults_kwdict);
    Py_CLEAR(m->func_annotations);

    if (m->defaults) {
        PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m);
        int i;

        for (i = 0; i < m->defaults_pyobjects; i++)
            Py_XDECREF(pydefaults[i]);

        PyObject_Free(m->defaults);
        m->defaults = NULL;
    }
Exemple #22
0
void
clear_start_response(void)
{
    Py_CLEAR(start_response);
}
Exemple #23
0
static int mmh3_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}
Exemple #24
0
/* Implement tpc_commit/tpc_rollback.
 *
 * This is a common framework performing the chechs and state manipulation
 * common to the two functions.
 *
 * Parameters are:
 * - self, args: passed by Python
 * - opc_f: the function to call in case of one-phase commit/rollback
 *          one of conn_commit/conn_rollback
 * - tpc_cmd: the command to execute for a two-phase commit/rollback
 *
 * The function can be called in three cases:
 * - If xid is specified, the status must be "ready";
 *   issue the commit/rollback prepared.
 * - if xid is not specified and status is "begin" with a xid,
 *   issue a normal commit/rollback.
 * - if xid is not specified and status is "prepared",
 *   issue the commit/rollback prepared.
 */
static PyObject *
_psyco_conn_tpc_finish(connectionObject *self, PyObject *args,
    _finish_f opc_f, char *tpc_cmd)
{
    PyObject *oxid = NULL;
    XidObject *xid = NULL;
    PyObject *rv = NULL;

    if (!PyArg_ParseTuple(args, "|O", &oxid)) { goto exit; }

    if (oxid) {
        if (!(xid = xid_ensure(oxid))) { goto exit; }
    }

    if (xid) {
        /* committing/aborting a recovered transaction. */
        if (self->status != CONN_STATUS_READY) {
            PyErr_SetString(ProgrammingError,
                "tpc_commit/tpc_rollback with a xid "
                "must be called outside a transaction");
            goto exit;
        }
        if (0 > conn_tpc_command(self, tpc_cmd, xid)) {
            goto exit;
        }
    } else {
        /* committing/aborting our own transaction. */
        if (!self->tpc_xid) {
            PyErr_SetString(ProgrammingError,
                "tpc_commit/tpc_rollback with no parameter "
                "must be called in a two-phase transaction");
            goto exit;
        }

        switch (self->status) {
          case CONN_STATUS_BEGIN:
            if (0 > opc_f(self)) { goto exit; }
            break;

          case CONN_STATUS_PREPARED:
            if (0 > conn_tpc_command(self, tpc_cmd, self->tpc_xid)) {
                goto exit;
            }
            break;

          default:
            PyErr_SetString(InterfaceError,
                "unexpected state in tpc_commit/tpc_rollback");
            goto exit;
        }

        Py_CLEAR(self->tpc_xid);

        /* connection goes ready */
        self->status = CONN_STATUS_READY;
    }

    Py_INCREF(Py_None);
    rv = Py_None;

exit:
    Py_XDECREF(xid);
    return rv;
}
static PyObject*
faulthandler_dump_traceback_later(PyObject *self,
                                   PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
    double timeout;
    PY_TIMEOUT_T timeout_us;
    int repeat = 0;
    PyObject *file = NULL;
    int fd;
    int exit = 0;
    PyThreadState *tstate;
    char *header;
    size_t header_len;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs,
        "d|iOi:dump_traceback_later", kwlist,
        &timeout, &repeat, &file, &exit))
        return NULL;
    if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
        PyErr_SetString(PyExc_OverflowError,  "timeout value is too large");
        return NULL;
    }
    timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
    if (timeout_us <= 0) {
        PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
        return NULL;
    }

    tstate = get_thread_state();
    if (tstate == NULL)
        return NULL;

    file = faulthandler_get_fileno(file, &fd);
    if (file == NULL)
        return NULL;

    /* format the timeout */
    header = format_timeout(timeout);
    if (header == NULL)
        return PyErr_NoMemory();
    header_len = strlen(header);

    /* Cancel previous thread, if running */
    cancel_dump_traceback_later();

    Py_XDECREF(thread.file);
    Py_INCREF(file);
    thread.file = file;
    thread.fd = fd;
    thread.timeout_us = timeout_us;
    thread.repeat = repeat;
    thread.interp = tstate->interp;
    thread.exit = exit;
    thread.header = header;
    thread.header_len = header_len;

    /* Arm these locks to serve as events when released */
    PyThread_acquire_lock(thread.running, 1);

    if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
        PyThread_release_lock(thread.running);
        Py_CLEAR(thread.file);
        free(header);
        thread.header = NULL;
        PyErr_SetString(PyExc_RuntimeError,
                        "unable to start watchdog thread");
        return NULL;
    }

    Py_RETURN_NONE;
}
Exemple #26
0
static int Reference_clear(Reference * self) {
	Reference *s;
	s = (Reference *)self;
	Py_CLEAR(s->value);
	return 0;
}
Exemple #27
0
static int
cell_clear(PyCellObject *op)
{
	Py_CLEAR(op->ob_ref);
	return 0;
}
static PyObject *
tuplerepr(PyTupleObject *v)
{
    Py_ssize_t i, n;
    PyObject *s = NULL;
    _PyAccu acc;
    static PyObject *sep = NULL;

    n = Py_SIZE(v);
    if (n == 0)
        return PyUnicode_FromString("()");

    if (sep == NULL) {
        sep = PyUnicode_FromString(", ");
        if (sep == NULL)
            return NULL;
    }

    /* While not mutable, it is still possible to end up with a cycle in a
       tuple through an object that stores itself within a tuple (and thus
       infinitely asks for the repr of itself). This should only be
       possible within a type. */
    i = Py_ReprEnter((PyObject *)v);
    if (i != 0) {
        return i > 0 ? PyUnicode_FromString("(...)") : NULL;
    }

    if (_PyAccu_Init(&acc))
        goto error;

    s = PyUnicode_FromString("(");
    if (s == NULL || _PyAccu_Accumulate(&acc, s))
        goto error;
    Py_CLEAR(s);

    /* Do repr() on each element. */
    for (i = 0; i < n; ++i) {
        if (Py_EnterRecursiveCall(" while getting the repr of a tuple"))
            goto error;
        s = PyObject_Repr(v->ob_item[i]);
        Py_LeaveRecursiveCall();
        if (i > 0 && _PyAccu_Accumulate(&acc, sep))
            goto error;
        if (s == NULL || _PyAccu_Accumulate(&acc, s))
            goto error;
        Py_CLEAR(s);
    }
    if (n > 1)
        s = PyUnicode_FromString(")");
    else
        s = PyUnicode_FromString(",)");
    if (s == NULL || _PyAccu_Accumulate(&acc, s))
        goto error;
    Py_CLEAR(s);

    Py_ReprLeave((PyObject *)v);
    return _PyAccu_Finish(&acc);

error:
    _PyAccu_Destroy(&acc);
    Py_XDECREF(s);
    Py_ReprLeave((PyObject *)v);
    return NULL;
}
Exemple #29
0
void
IndexIter_dealloc(IndexIter *self)
{
    Py_CLEAR(self->owner);
    PyObject_Del(self);
}
Exemple #30
0
PyObject *
column_setstate(columnObject *self, PyObject *state)
{
    Py_ssize_t size;
    PyObject *rv = NULL;

    if (state == Py_None) {
        goto exit;
    }
    if (!PyTuple_Check(state)) {
        PyErr_SetString(PyExc_TypeError, "state is not a tuple");
        goto error;
    }

    size = PyTuple_GET_SIZE(state);

    if (size > 0) {
        Py_CLEAR(self->name);
        self->name = PyTuple_GET_ITEM(state, 0);
        Py_INCREF(self->name);
    }
    if (size > 1) {
        Py_CLEAR(self->type_code);
        self->type_code = PyTuple_GET_ITEM(state, 1);
        Py_INCREF(self->type_code);
    }
    if (size > 2) {
        Py_CLEAR(self->display_size);
        self->display_size = PyTuple_GET_ITEM(state, 2);
        Py_INCREF(self->display_size);
    }
    if (size > 3) {
        Py_CLEAR(self->internal_size);
        self->internal_size = PyTuple_GET_ITEM(state, 3);
        Py_INCREF(self->internal_size);
    }
    if (size > 4) {
        Py_CLEAR(self->precision);
        self->precision = PyTuple_GET_ITEM(state, 4);
        Py_INCREF(self->precision);
    }
    if (size > 5) {
        Py_CLEAR(self->scale);
        self->scale = PyTuple_GET_ITEM(state, 5);
        Py_INCREF(self->scale);
    }
    if (size > 6) {
        Py_CLEAR(self->null_ok);
        self->null_ok = PyTuple_GET_ITEM(state, 6);
        Py_INCREF(self->null_ok);
    }
    if (size > 7) {
        Py_CLEAR(self->table_oid);
        self->table_oid = PyTuple_GET_ITEM(state, 7);
        Py_INCREF(self->table_oid);
    }
    if (size > 8) {
        Py_CLEAR(self->table_column);
        self->table_column = PyTuple_GET_ITEM(state, 8);
        Py_INCREF(self->table_column);
    }

exit:
    rv = Py_None;
    Py_INCREF(rv);

error:
    return rv;
}