示例#1
0
文件: set.c 项目: H1d3r/binary_blobs
static PyObject *set_union(PyObject *module, PyObject *args)
{
  PyObject *a, *b, *item;

  if (!PyArg_ParseTuple(args, "OO:Union", &a, &b))
    return NULL;

  if (PyObject_IsTrue(a) == 0) {
    /* empty set a, reuse b */
    return PySequence_List(b);
  } else if (PyObject_IsTrue(b) == 0) {
    /* empty set b, reuse a */
    return PySequence_List(a);
  }
  /* create a new set containing the union of a and b */
  a = make_dict(a);
  if (a == NULL)
    return NULL;
  b = PyObject_GetIter(b);
  if (b == NULL) {
    Py_DECREF(a);
    return NULL;
  }
  while ((item = PyIter_Next(b)) != NULL) {
    if (PyDict_SetItem(a, item, Py_True) == -1) {
      Py_DECREF(item);
      Py_DECREF(b);
      Py_DECREF(a);
      return NULL;
    }
    Py_DECREF(item);
  }
  Py_DECREF(b);
  return make_ordered_set(a);
}
示例#2
0
/*
 * repr function
 * convert to a list and get its string value
 */
static PyObject *KX_PythonSeq_repr( KX_PythonSeq * self )
{
	PyObject *list = PySequence_List((PyObject *)self);
	PyObject *repr = PyObject_Repr(list);
	Py_DECREF(list);
	return repr;
}
示例#3
0
static PyObject *
hv_cli_dictof_get_static_types_list(NyHeapViewObject *hv) {
    if (PyObject_Length(hv->static_types) == 0) {
	PyObject *h = hv_heap(hv, Py_None, Py_None); /* It updates static_types */
	if (!h)
	  return 0;
	Py_DECREF(h);
    }
    return PySequence_List(hv->static_types);
}
示例#4
0
static PyObject *
hv_get_objects(NyHeapViewObject *hv) {
    PyObject *p = hv_heap(hv, Py_None, Py_None);
    PyObject *r;
    if (!p)
	goto err;
    r = PySequence_List(p);
    Py_DECREF(p);
    return r;
    err:
    return 0;
}
示例#5
0
PyObjectHandle LuaToPythonConverter::convertToList(lua_State* L, int index) {
  fixIndex(L, index);

  if (auto ref = getOpaqueRef(L, index)) {
    // Must convert to a Python list
    PyObjectHandle list(PySequence_List(ref->obj.get()));
    checkPythonError(list, L, "cannot convert to list");
    return list;
  }

  return convertListFromTable(L, index, false);
}
示例#6
0
文件: ptor.c 项目: hltbra/rubypython
VALUE ptorTuple(PyObject* pTuple)
{
	if(!PyTuple_Check(pTuple)) return Qnil;

	VALUE rArray;
	PyObject* pList;

	pList = PySequence_List(pTuple);
	rArray = ptorList(pList);
	Py_DECREF(pList);

	return rArray;
}
示例#7
0
文件: set.c 项目: H1d3r/binary_blobs
/* this function consumes a reference from 'set' */
static PyObject *make_ordered_set(PyObject *set)
{
  PyObject *result = PySequence_List(set);
  if (result == NULL) {
    Py_DECREF(set);
  } else {
    Py_DECREF(set);
    if (PyList_Sort(result) == -1) {
      Py_DECREF(result);
      return NULL;
    }
  }    
  return result;
}
static PyObject *
deque_extendleft(dequeobject *deque, PyObject *iterable)
{
    PyObject *it, *item;

    /* Handle case where id(deque) == id(iterable) */
    if ((PyObject *)deque == iterable) {
        PyObject *result;
        PyObject *s = PySequence_List(iterable);
        if (s == NULL)
            return NULL;
        result = deque_extendleft(deque, s);
        Py_DECREF(s);
        return result;
    }

    it = PyObject_GetIter(iterable);
    if (it == NULL)
        return NULL;

    if (deque->maxlen == 0)
        return consume_iterator(it);

    while ((item = PyIter_Next(it)) != NULL) {
        deque->state++;
        if (deque->leftindex == 0) {
            block *b = newblock(NULL, deque->leftblock,
                                deque->len);
            if (b == NULL) {
                Py_DECREF(item);
                Py_DECREF(it);
                return NULL;
            }
            assert(deque->leftblock->leftlink == NULL);
            deque->leftblock->leftlink = b;
            deque->leftblock = b;
            deque->leftindex = BLOCKLEN;
        }
        deque->len++;
        deque->leftindex--;
        deque->leftblock->data[deque->leftindex] = item;
        TRIM(deque, deque_pop);
    }
    Py_DECREF(it);
    if (PyErr_Occurred())
        return NULL;
    Py_RETURN_NONE;
}
示例#9
0
文件: py-event.c 项目: ChrisG0x20/gdb
int
evpy_emit_event (PyObject *event,
                 eventregistry_object *registry)
{
  PyObject *callback_list_copy = NULL;
  Py_ssize_t i;

  /* Create a copy of call back list and use that for
     notifying listeners to avoid skipping callbacks
     in the case of a callback being disconnected during
     a notification.  */
  callback_list_copy = PySequence_List (registry->callbacks);
  if (!callback_list_copy)
    goto fail;

  for (i = 0; i < PyList_Size (callback_list_copy); i++)
    {
      PyObject *func = PyList_GetItem (callback_list_copy, i);
      PyObject *func_result;

      if (func == NULL)
	goto fail;

      func_result = PyObject_CallFunctionObjArgs (func, event, NULL);

      if (func_result == NULL)
	{
	  /* Print the trace here, but keep going -- we want to try to
	     call all of the callbacks even if one is broken.  */
	  gdbpy_print_stack ();
	}
      else
	{
	  Py_DECREF (func_result);
	}
    }

  Py_XDECREF (callback_list_copy);
  Py_XDECREF (event);
  return 0;

 fail:
  gdbpy_print_stack ();
  Py_XDECREF (callback_list_copy);
  Py_XDECREF (event);
  return -1;
}
示例#10
0
文件: set.c 项目: H1d3r/binary_blobs
static PyObject *set_not(PyObject *module, PyObject *args)
{
  PyObject *a, *b, *item;

  if (!PyArg_ParseTuple(args, "OO:Not", &a, &b))
    return NULL;

  if (PyObject_IsTrue(a) == 0) {
    /* nothing to subtract from, return empty set */
    return PyList_New(0);
  } else if (PyObject_IsTrue(b) == 0) {
    /* nothing to subtract, use original set */
    return PySequence_List(a);
  }

  /* subtract set b from set a */
  a = make_dict(a);
  if (a == NULL)
    return NULL;
  b = PyObject_GetIter(b);
  if (b == NULL) {
    Py_DECREF(a);
    return NULL;
  }
  while ((item = PyIter_Next(b)) != NULL) {
    if (PyDict_DelItem(a, item) == -1) {
      if (PyErr_ExceptionMatches(PyExc_KeyError)) {
        PyErr_Clear();
      } else {
        Py_DECREF(item);
        Py_DECREF(b);
        Py_DECREF(a);
        return NULL;
      }
    }
    Py_DECREF(item);
  }
  Py_DECREF(b);
  return make_ordered_set(a);
}
示例#11
0
static PyObject* set_reduce(BoxedSet* so) noexcept {
    PyObject* keys = NULL, * args = NULL, * result = NULL, * dict = NULL;

    keys = PySequence_List((PyObject*)so);
    if (keys == NULL)
        goto done;
    args = PyTuple_Pack(1, keys);
    if (args == NULL)
        goto done;
    dict = PyObject_GetAttrString((PyObject*)so, "__dict__");
    if (dict == NULL) {
        PyErr_Clear();
        dict = Py_None;
        Py_INCREF(dict);
    }
    result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
done:
    Py_XDECREF(args);
    Py_XDECREF(keys);
    Py_XDECREF(dict);
    return result;
}
示例#12
0
static PyObject *
SpiDev_xfer2(SpiDevObject *self, PyObject *args)
{
	int status;
	uint16_t delay_usecs = 0;
	uint32_t speed_hz = 0;
	uint8_t bits_per_word = 0;
	uint16_t ii, len;
	PyObject *obj;
	PyObject *seq;
	struct spi_ioc_transfer xfer;
	Py_BEGIN_ALLOW_THREADS
	memset(&xfer, 0, sizeof(xfer));
	Py_END_ALLOW_THREADS
	uint8_t *txbuf, *rxbuf;
	char	wrmsg_text[4096];

	if (!PyArg_ParseTuple(args, "O|IHB:xfer2", &obj, &speed_hz, &delay_usecs, &bits_per_word))
		return NULL;

	seq = PySequence_Fast(obj, "expected a sequence");
	len = PySequence_Fast_GET_SIZE(seq);
	if (!seq || len <= 0) {
		PyErr_SetString(PyExc_TypeError, wrmsg_list0);
		return NULL;
	}

	if (len > SPIDEV_MAXPATH) {
		snprintf(wrmsg_text, sizeof(wrmsg_text) - 1, wrmsg_listmax, SPIDEV_MAXPATH);
		PyErr_SetString(PyExc_OverflowError, wrmsg_text);
		return NULL;
	}

	Py_BEGIN_ALLOW_THREADS
	txbuf = malloc(sizeof(__u8) * len);
	rxbuf = malloc(sizeof(__u8) * len);
	Py_END_ALLOW_THREADS

	for (ii = 0; ii < len; ii++) {
		PyObject *val = PySequence_Fast_GET_ITEM(seq, ii);
#if PY_MAJOR_VERSION < 3
		if (PyInt_Check(val)) {
			txbuf[ii] = (__u8)PyInt_AS_LONG(val);
		} else
#endif
		{
			if (PyLong_Check(val)) {
				txbuf[ii] = (__u8)PyLong_AS_LONG(val);
			} else {
				snprintf(wrmsg_text, sizeof (wrmsg_text) - 1, wrmsg_val, val);
				PyErr_SetString(PyExc_TypeError, wrmsg_text);
				free(txbuf);
				free(rxbuf);
				return NULL;
			}
		}
	}

	if (PyTuple_Check(obj)) {
		Py_DECREF(seq);
		seq = PySequence_List(obj);
	}

	Py_BEGIN_ALLOW_THREADS
	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);
	Py_END_ALLOW_THREADS
	if (status < 0) {
		PyErr_SetFromErrno(PyExc_IOError);
		free(txbuf);
		free(rxbuf);
		return NULL;
	}

	for (ii = 0; ii < len; ii++) {
		PyObject *val = Py_BuildValue("l", (long)rxbuf[ii]);
		PySequence_SetItem(seq, 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);

	Py_BEGIN_ALLOW_THREADS
	free(txbuf);
	free(rxbuf);
	Py_END_ALLOW_THREADS


	if (PyTuple_Check(obj)) {
		PyObject *old = seq;
		seq = PySequence_Tuple(seq);
		Py_DECREF(old);
	}

	return seq;
}
示例#13
0
static PyObject *
GMPy_Context_Fsum(PyObject *self, PyObject *other)
{
    MPFR_Object *temp, *result;
    mpfr_ptr *tab;
    int errcode;
    Py_ssize_t i, seq_length = 0;
    CTXT_Object *context = NULL;

    if (self && CTXT_Check(self)) {
        context = (CTXT_Object*)self;
    }
    else {
        CHECK_CONTEXT(context);
    }

    if (!(result = GMPy_MPFR_New(0, context))) {
        return NULL;
    }

    if (!(other = PySequence_List(other))) {
        Py_DECREF((PyObject*)result);
        TYPE_ERROR("argument must be an iterable");
        return NULL;
    }

    /* other contains a new list containing all the values from the
     * iterable. Now make sure each item in the list is an mpfr.
     */

    seq_length = PyList_GET_SIZE(other);
    for (i=0; i < seq_length; i++) {
        if (!(temp = GMPy_MPFR_From_Real(PyList_GET_ITEM(other, i), 1, context))) {
            Py_DECREF(other);
            Py_DECREF((PyObject*)result);
            TYPE_ERROR("all items in iterable must be real numbers");
            return NULL;
        }

        errcode = PyList_SetItem(other, i,(PyObject*)temp);
        if (errcode < 0) {
            Py_DECREF(other);
            Py_DECREF((PyObject*)result);
            TYPE_ERROR("all items in iterable must be real numbers");
            return NULL;
        }
    }

    /* create an array of pointers to the mpfr_t field of a Pympfr object */

    if (!(tab = (mpfr_ptr *)GMPY_MALLOC((sizeof(mpfr_srcptr) * seq_length)))) {
        Py_DECREF(other);
        Py_DECREF((PyObject*)result);
        return PyErr_NoMemory();
    }
    for (i=0; i < seq_length; i++) {
        temp = (MPFR_Object*)PyList_GET_ITEM(other, i);
        tab[i] = temp->f;
    }

    mpfr_clear_flags();
    result->rc = mpfr_sum(result->f, tab, seq_length, GET_MPFR_ROUND(context));
    Py_DECREF(other);
    GMPY_FREE(tab);

    _GMPy_MPFR_Cleanup(&result, context);
    return (PyObject*)result;
}
 List Sequence::asList() const
 {
     return List(NewReference(PySequence_List(mPtr)));
 }
示例#15
0
int local_scan(int fd, uschar **return_text)
    {
    PyObject *user_dict;
    PyObject *user_func;
    PyObject *result;
    PyObject *header_tuple;
    PyObject *original_recipients;
    PyObject *working_recipients;

    if (!expy_enabled)
        return LOCAL_SCAN_ACCEPT;

    if (!Py_IsInitialized())  /* local_scan() may have already been run */
        {
        Py_Initialize();
        ExPy_Header_Line.ob_type = &PyType_Type;
        }

    if (!expy_exim_dict)
        {
        PyObject *module = Py_InitModule(expy_exim_module, expy_exim_methods); /* Borrowed reference */
        Py_INCREF(module);                                 /* convert to New reference */
        expy_exim_dict = PyModule_GetDict(module);         /* Borrowed reference */
        Py_INCREF(expy_exim_dict);                         /* convert to New reference */
        }

    if (!expy_user_module)
        {
        if (expy_path_add)
            {
            PyObject *sys_module;
            PyObject *sys_dict;
            PyObject *sys_path;
            PyObject *add_value;

            sys_module = PyImport_ImportModule("sys");  /* New Reference */
            if (!sys_module)
                {
                PyErr_Clear();
                *return_text = "Internal error, can't import Python sys module";
                log_write(0, LOG_REJECT, "Couldn't import Python 'sys' module"); 
                /* FIXME: write out an exception traceback if possible to Exim log */
                return PYTHON_FAILURE_RETURN;
                }

            sys_dict = PyModule_GetDict(sys_module);               /* Borrowed Reference, never fails */
            sys_path = PyMapping_GetItemString(sys_dict, "path");  /* New reference */

            if (!sys_path || (!PyList_Check(sys_path)))
                {
                PyErr_Clear();  /* in case sys_path was NULL, harmless otherwise */
                *return_text = "Internal error, sys.path doesn't exist or isn't a list";
                log_write(0, LOG_REJECT, "expy: Python sys.path doesn't exist or isn't a list"); 
                /* FIXME: write out an exception traceback if possible to Exim log */
                return PYTHON_FAILURE_RETURN;
                }

            add_value = PyString_FromString(expy_path_add);  /* New reference */
            if (!add_value)
                {
                PyErr_Clear();
                log_write(0, LOG_PANIC, "expy: Failed to create Python string from [%s]", expy_path_add); 
                return PYTHON_FAILURE_RETURN;
                }

            if (PyList_Append(sys_path, add_value))
                {
                PyErr_Clear();
                log_write(0, LOG_PANIC, "expy: Failed to append [%s] to Python sys.path", expy_path_add);                
                }

            Py_DECREF(add_value);
            Py_DECREF(sys_path);
            Py_DECREF(sys_module);
            }

        expy_user_module = PyImport_ImportModule(expy_scan_module);  /* New Reference */

        if (!expy_user_module)
            {
            PyErr_Clear();
            *return_text = "Internal error, can't import Python local_scan module";
            log_write(0, LOG_REJECT, "Couldn't import Python '%s' module", expy_scan_module); 
            return PYTHON_FAILURE_RETURN;
            }
        }

    user_dict = PyModule_GetDict(expy_user_module);                      /* Borrowed Reference, never fails */
    user_func = PyMapping_GetItemString(user_dict, expy_scan_function);  /* New reference */

    if (!user_func)
        {
        PyErr_Clear();
        *return_text = "Internal error, module doesn't have local_scan function";
        log_write(0, LOG_REJECT, "Python %s module doesn't have a %s function", expy_scan_module, expy_scan_function); 
        return PYTHON_FAILURE_RETURN;
        }

    /* so far so good, prepare to run function */

    /* Copy exim variables */
    expy_dict_int("debug_selector", debug_selector);
    expy_dict_int("host_checking", host_checking);
    expy_dict_string("interface_address", interface_address);
    expy_dict_int("interface_port", interface_port);
    expy_dict_string("message_id", message_id);
    expy_dict_string("received_protocol", received_protocol);
    expy_dict_string("sender_address", sender_address);
    expy_dict_string("sender_host_address", sender_host_address);
    expy_dict_string("sender_host_authenticated", sender_host_authenticated);
    expy_dict_string("sender_host_name", sender_host_name);
    expy_dict_int("sender_host_port", sender_host_port);
    expy_dict_int("fd", fd);

    /* copy some constants */
    expy_dict_int("LOG_MAIN", LOG_MAIN);
    expy_dict_int("LOG_PANIC", LOG_PANIC);
    expy_dict_int("LOG_REJECT", LOG_REJECT);
    
    expy_dict_int("LOCAL_SCAN_ACCEPT", LOCAL_SCAN_ACCEPT);
    expy_dict_int("LOCAL_SCAN_ACCEPT_FREEZE", LOCAL_SCAN_ACCEPT_FREEZE);
    expy_dict_int("LOCAL_SCAN_ACCEPT_QUEUE", LOCAL_SCAN_ACCEPT_QUEUE);
    expy_dict_int("LOCAL_SCAN_REJECT", LOCAL_SCAN_REJECT);
    expy_dict_int("LOCAL_SCAN_REJECT_NOLOGHDR", LOCAL_SCAN_REJECT_NOLOGHDR);
    expy_dict_int("LOCAL_SCAN_TEMPREJECT", LOCAL_SCAN_TEMPREJECT);
    expy_dict_int("LOCAL_SCAN_TEMPREJECT_NOLOGHDR", LOCAL_SCAN_TEMPREJECT_NOLOGHDR);
    expy_dict_int("MESSAGE_ID_LENGTH", MESSAGE_ID_LENGTH);
    expy_dict_int("SPOOL_DATA_START_OFFSET", SPOOL_DATA_START_OFFSET);

    expy_dict_int("D_v", D_v);
    expy_dict_int("D_local_scan", D_local_scan);

    /* set the headers */
    header_tuple = get_headers();
    PyDict_SetItemString(expy_exim_dict, "headers", header_tuple);

    /* 
     * make list of recipients, give module a copy to work with in 
     * List format, but keep original tuple to compare against later
     */
    original_recipients = get_recipients();                     /* New reference */
    working_recipients = PySequence_List(original_recipients);  /* New reference */
    PyDict_SetItemString(expy_exim_dict, "recipients", working_recipients);
    Py_DECREF(working_recipients);    

    /* Try calling our function */
    result = PyObject_CallFunction(user_func, NULL);            /* New reference */

    Py_DECREF(user_func);  /* Don't need ref to function anymore */      

    /* Check for Python exception */
    if (!result)
        {
        PyErr_Clear();
        *return_text = "Internal error, local_scan function failed";
        Py_DECREF(original_recipients);
        clear_headers(header_tuple);
        Py_DECREF(header_tuple);
        return PYTHON_FAILURE_RETURN;

        // FIXME: should write exception to exim log somehow
        }

    /* User code may have replaced recipient list, so re-get ref */
    working_recipients = PyDict_GetItemString(expy_exim_dict, "recipients"); /* Borrowed reference */
    Py_XINCREF(working_recipients);                                           /* convert to New reference */

    /* 
     * reconcile original recipient list with what's present after 
     * Python code is done 
     */
    if ((!working_recipients) || (!PySequence_Check(working_recipients)) || (PySequence_Size(working_recipients) == 0))
        /* Python code either deleted exim.recipients alltogether, or replaced 
           it with a non-list, or emptied out the list */
        recipients_count = 0;
    else
        {        
        int i;

        /* remove original recipients not on the working list, reverse order important! */
        for (i = recipients_count - 1; i >= 0; i--)
            {
            PyObject *addr = PyTuple_GET_ITEM(original_recipients, i); /* borrowed ref */
            if (!PySequence_Contains(working_recipients, addr))
                expy_remove_recipient(i);
            }

        /* add new recipients not in the original list */
        for (i = PySequence_Size(working_recipients) - 1; i >= 0; i--)
            {
            PyObject *addr = PySequence_GetItem(working_recipients, i);
            if (!PySequence_Contains(original_recipients, addr))
                receive_add_recipient(PyString_AsString(addr), -1);
            Py_DECREF(addr);
            }
        }

    Py_XDECREF(working_recipients);   /* No longer needed */
    Py_DECREF(original_recipients);   /* No longer needed */

    clear_headers(header_tuple);
    Py_DECREF(header_tuple);          /* No longer needed */

    /* Deal with the return value, first see if python returned a non-empty sequence */
    if (PySequence_Check(result) && (PySequence_Size(result) > 0))
        {
        /* save first item */
        PyObject *rc = PySequence_GetItem(result, 0);

        /* if more than one item, convert 2nd item to string and use as return text */
        if (PySequence_Size(result) > 1)
            {
            PyObject *str;
            PyObject *obj = PySequence_GetItem(result, 1);   /* New reference */
            str = PyObject_Str(obj);                         /* New reference */

            *return_text = string_copy(PyString_AsString(str));

            Py_DECREF(obj);
            Py_DECREF(str);
            }

        /* drop the sequence, and focus on the first item we saved */
        Py_DECREF(result);
        result = rc;
        }

    /* If we have an integer, return that to Exim */
    if (PyInt_Check(result))
        {
        int rc = PyInt_AsLong(result);
        Py_DECREF(result);
        return rc;
        }

    /* didn't return anything usable */
    Py_DECREF(result);
    *return_text = "Internal error, bad return code";
    log_write(0, LOG_REJECT, "Python %s.%s function didn't return integer", expy_scan_module, expy_scan_function); 
    return PYTHON_FAILURE_RETURN;
    }