Beispiel #1
0
static void emit_all_code_objects(void)
{
    PyObject *gc_module = NULL, *lst = NULL, *all_codes = NULL;
    Py_ssize_t i, size;

    gc_module = PyImport_ImportModuleNoBlock("gc");
    if (gc_module == NULL)
        goto error;

    lst = PyObject_CallMethod(gc_module, "get_objects", "");
    if (lst == NULL || !PyList_Check(lst))
        goto error;

    all_codes = PySet_New(NULL);
    if (all_codes == NULL)
        goto error;

    size = PyList_GET_SIZE(lst);
    for (i = 0; i < size; i++) {
        PyObject *o = PyList_GET_ITEM(lst, i);
        if (o->ob_type->tp_traverse &&
                o->ob_type->tp_traverse(o, _look_for_code_object, (void *)all_codes)
                < 0)
            goto error;
    }

error:
    Py_XDECREF(all_codes);
    Py_XDECREF(lst);
    Py_XDECREF(gc_module);
}
Beispiel #2
0
void
PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
{
    PyObject *seen;
    PyObject *f = _PySys_GetObjectId(&PyId_stderr);
    if (PyExceptionInstance_Check(value)
        && tb != NULL && PyTraceBack_Check(tb)) {
        /* Put the traceback on the exception, otherwise it won't get
           displayed.  See issue #18776. */
        PyObject *cur_tb = PyException_GetTraceback(value);
        if (cur_tb == NULL)
            PyException_SetTraceback(value, tb);
        else
            Py_DECREF(cur_tb);
    }
    if (f == Py_None) {
        /* pass */
    }
    else if (f == NULL) {
        _PyObject_Dump(value);
        fprintf(stderr, "lost sys.stderr\n");
    }
    else {
        /* We choose to ignore seen being possibly NULL, and report
           at least the main exception (it could be a MemoryError).
        */
        seen = PySet_New(NULL);
        if (seen == NULL)
            PyErr_Clear();
        print_exception_recursive(f, value, seen);
        Py_XDECREF(seen);
    }
}
Beispiel #3
0
 /** ctor.
  */
 set(std::initializer_list<obj> l)
 {
     _p = PySet_New(NULL);
     for(auto &x: l){
         add(x);
     }
 }
Beispiel #4
0
static PyObject *pair_set_position(PyObject *self,
				   PyObject *args, PyObject *kwds) {

  // checked

  static char *keywords[] = { "postition", "follow", NULL };
  PyObject *position = NULL;
  int follow = 0;

  if (SibNil_Check(self))
    Py_RETURN_NONE;

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "O|p", keywords,
				    &position, &follow))
    return NULL;

  if (follow) {
    PyObject *seen = PySet_New(NULL);
    pwalk_setpos(self, seen, position);
    Py_DECREF(seen);

  } else {
    Py_ASSIGN(((SibPair *) self)->position, position);
  }

  Py_RETURN_NONE;
}
Beispiel #5
0
static PyObject *pair_fill_position(PyObject *self,
				    PyObject *args, PyObject *kwds) {

  // checked

  static char *keywords[] = { "position", "follow", NULL };
  PyObject *position = NULL;
  int follow = 0;

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "O|p", keywords,
				    &position, &follow))
    return NULL;

  if (follow) {
    PyObject *seen = PySet_New(NULL);
    pwalk_fillpos(self, seen, position);
    Py_DECREF(seen);

  } else {
    if (! ((SibPair *) self)->position) {
      Py_INCREF(position);
      ((SibPair *) self)->position = position;
    }
  }

  Py_RETURN_NONE;
}
Beispiel #6
0
 PyObject *to_python<types::set<T>>::convert(types::set<T> const &v)
 {
   PyObject *obj = PySet_New(nullptr);
   for (auto const &e : v)
     PySet_Add(obj, ::to_python(e));
   return obj;
 }
Beispiel #7
0
long SibPair_IsRecursive(PyObject *self) {

  // checked

  if (SibNil_Check(self))
    return 0;

  PyObject *seen = PySet_New(NULL);
  PyObject *pair_id;
  long result = 0;

  for ( ; SibPair_CheckExact(self); self = SibPair_CDR(self)) {
    pair_id = PyLong_FromVoidPtr(self);

    if (PySet_Contains(seen, pair_id)) {
      /* seen it, therefore recursive */
      Py_DECREF(pair_id);
      result = 1;
      break;

    } else {
      PySet_Add(seen, pair_id);
      Py_DECREF(pair_id);
    }
  }

  Py_DECREF(seen);
  return result;
}
Beispiel #8
0
long SibPair_IsProper(PyObject *self) {

  // checked

  if (SibNil_Check(self))
    return 1;

  PyObject *seen = PySet_New(NULL);
  PyObject *pair_id;
  long result = 0;

  for ( ; SibPair_CheckExact(self); self = SibPair_CDR(self)) {
    pair_id = PyLong_FromVoidPtr(self);

    if (PySet_Contains(seen, pair_id)) {
      /* seen it, therefore recursive */
      Py_DECREF(pair_id);
      result = 1;
      break;

    } else {
      PySet_Add(seen, pair_id);
      Py_DECREF(pair_id);
    }
  }

  /* it's either recursive and thus proper, or the last item needs to
     have been a nil, or it's improper */
  Py_DECREF(seen);
  return result || SibNil_Check(self);
}
static PyObject *convertFrom_QSet_0101QAbstractState(void *sipCppV, PyObject *sipTransferObj)
{
   QSet<QAbstractState*> *sipCpp = reinterpret_cast<QSet<QAbstractState*> *>(sipCppV);

#line 319 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/sip/QtCore/qset.sip"
    // Create the set.
    PyObject *s;

    if ((s = PySet_New(NULL)) == NULL)
        return NULL;

    // Set the set elements.
    QSet<QAbstractState *>::const_iterator it = sipCpp->constBegin();
    QSet<QAbstractState *>::const_iterator end = sipCpp->constEnd();

    while (it != end)
    {
        PyObject *tobj;

        // The explicit (void *) cast allows QAbstractState to be const.
        if ((tobj = sipConvertFromType((void *)*it, sipType_QAbstractState, sipTransferObj)) == NULL)
        {
            Py_DECREF(s);
            return NULL;
        }

        PySet_Add(s, tobj);

        ++it;
    }

    return s;
#line 165 "/home/vikky/Desktop/DVCS/stuff/scrapy/soft/PyQt-x11-gpl-4.11.4/QtCore/sipQtCoreQSet0101QAbstractState.cpp"
}
Beispiel #10
0
static PyObject *pair_length(PyObject *self, PyObject *_noargs) {
  PyObject *seen;
  PyObject *tmp;
  long length = 0;

  if (SibNil_Check(self)) {
    return PyLong_FromLong(length);
  }

  seen = PySet_New(NULL);

  for(; SibPair_CheckExact(self); self = SibPair_CDR(self)) {

    tmp = PyLong_FromVoidPtr(self);

    if (PySet_Contains(seen, tmp)) {
      Py_DECREF(tmp);
      self = NULL;
      break;

    } else {
      PySet_Add(seen, tmp);
      Py_DECREF(tmp);
      length++;
    }
  }

  if (self && ! SibNil_Check(self))
    length++;

  Py_DECREF(seen);
  return PyLong_FromLong(length);
}
Beispiel #11
0
 set& operator=(std::initializer_list<obj> l)
 {
     release();
     _p = PySet_New(NULL);
     for(auto &x: l){
         add(x);
     }
     return *this;
 }
Beispiel #12
0
static int foreach_libblock_id_user_map_callback(
        void *user_data, ID *self_id, ID **id_p, int UNUSED(cb_flag))
{
	IDUserMapData *data = user_data;

	if (*id_p) {

		if (data->types_bitmap) {
			if (!id_check_type(*id_p, data->types_bitmap)) {
				return IDWALK_RET_NOP;
			}
		}

		if ((GS(self_id->name) == ID_OB) && (id_p == (ID **)&((Object *)self_id)->proxy_from)) {
			/* We skip proxy_from here, since it some internal pointer which is not irrelevant info for py/API level. */
			return IDWALK_RET_NOP;
		}
		else if ((GS(self_id->name) == ID_KE) && (id_p == (ID **)&((Key *)self_id)->from)) {
			/* We skip from here, since it some internal pointer which is not irrelevant info for py/API level. */
			return IDWALK_RET_NOP;
		}

		/* pyrna_struct_hash() uses ptr.data only,
		 * but pyrna_struct_richcmp() uses also ptr.type,
		 * so we need to create a valid PointerRNA here...
		 */
		PyObject *key = data->py_id_key_lookup_only;
		RNA_id_pointer_create(*id_p, &((BPy_StructRNA *)key)->ptr);

		PyObject *set;
		if ((set = PyDict_GetItem(data->user_map, key)) == NULL) {

			/* limit to key's added already */
			if (data->is_subset) {
				return IDWALK_RET_NOP;
			}

			/* Cannot use our placeholder key here! */
			key = pyrna_id_CreatePyObject(*id_p);
			set = PySet_New(NULL);
			PyDict_SetItem(data->user_map, key, set);
			Py_DECREF(set);
			Py_DECREF(key);
		}

		if (data->py_id_curr == NULL) {
			data->py_id_curr = pyrna_id_CreatePyObject(data->id_curr);
		}

		PySet_Add(set, data->py_id_curr);
	}

	return IDWALK_RET_NOP;
}
Beispiel #13
0
static PyObject* Cache_cached_get(Cache* self) {
    PyObject* cached_set = PySet_New(NULL);
    for(int i=0; i<self->sets*self->ways; i++) {
        // For each cached cacheline expand to all cached addresses:
        for(int j=0; j<self->cl_size; j++) {
            // PySys_WriteStdout("%i %i %i %i\n", self->sets, self->ways, i, self->placement[i].cl_id);
            PyObject* addr = PyLong_FromUnsignedLong(self->placement[i].cl_id*self->cl_size+j);
            PySet_Add(cached_set, addr);
            Py_DECREF(addr);
        }
    }
    return cached_set;
}
Beispiel #14
0
/*
 * Convert a list of Value nodes containing the column name as a string to a
 * pyset of python unicode strings.
 */
PyObject *
valuesToPySet(List *targetlist)
{
	PyObject   *result = PySet_New(0);
	ListCell   *lc;

	foreach(lc, targetlist)
	{
		Value	   *value = (Value *) lfirst(lc);
		PyObject   *pyString = PyString_FromString(strVal(value));

		PySet_Add(result, pyString);
		Py_DECREF(pyString);
	}
Beispiel #15
0
static PyObject *pair_unpack(PyObject *self, PyObject *_noargs) {

  // checked

  SibPairFollower *i = PyObject_New(SibPairFollower, &SibPairFollowerType);
  if(! i)
    return NULL;

  Py_INCREF(self);
  i->current = self;
  i->seen = PySet_New(NULL);
  i->just_items = 1;

  return (PyObject *) i;
}
Beispiel #16
0
static int
LockObject_init(LockObject *self, PyObject *args, PyObject *kwargs)
{

    GDEBUG("self:%p", self);

    self->counter = 1;

    Py_CLEAR(self->waiters);

    self->waiters = PySet_New(NULL);
    if (self->waiters == NULL) {
        return -1;
    }
    DEBUG("self:%p counter:%d waiters:%p", self, self->counter, self->waiters);
    return 1;
}
Beispiel #17
0
PyObject *WeakSet_New(void){
    WeakSet *self;
    self = (WeakSet *)WeakSetType.tp_alloc(&WeakSetType, 0);
    self->set = self->selfref = NULL;

    self->set = PySet_New(NULL);
    if (!self->set) goto bail;

    self->selfref = PyWeakref_NewRef((PyObject *)self->set,NULL);
    if (!self->selfref) goto bail;

    return (PyObject *)self;
bail:
    Py_XDECREF(self->set);
    Py_XDECREF(self->selfref);
    Py_DECREF(self);
    return NULL;
}
static PyObject *Video_device_get_info(Video_device *self)
{
  ASSERT_OPEN;
  struct v4l2_capability caps;

  if(my_ioctl(self->fd, VIDIOC_QUERYCAP, &caps))
    {
      return NULL;
    }

  PyObject *set = PySet_New(NULL);

  if(!set)
    {
      return NULL;
    }

  struct capability *capability = capabilities;

  while((void *)capability < (void *)capabilities + sizeof(capabilities))
    {
      if(caps.capabilities & capability->id)
	{
	  PyObject *s = PyString_FromString(capability->name);

	  if(!s)
	    {
              Py_DECREF(set);
	      return NULL;
	    }

	  PySet_Add(set, s);
	}

      capability++;
    }

  return Py_BuildValue("sssO", caps.driver, caps.card, caps.bus_info, set);
}
Beispiel #19
0
static int
SemaphoreObject_init(SemaphoreObject *self, PyObject *args, PyObject *kwargs)
{

    int value = 1; 
    GDEBUG("self:%p", self);
    static char *keywords[] = {"value", NULL};
    
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:__init__", keywords, &value)) {
        return -1;
    }
    self->counter = value;

    Py_CLEAR(self->waiters);

    self->waiters = PySet_New(NULL);
    if (self->waiters == NULL) {
        return -1;
    }
    DEBUG("self:%p counter:%d waiters:%p", self, self->counter, self->waiters);
    return 1;
}
Beispiel #20
0
static PyObject *pair_clear_position(PyObject *self,
				     PyObject *args, PyObject *kwds) {

  static char *keywords[] = { "follow", NULL };
  int follow = 0;

  if (SibNil_Check(self))
    Py_RETURN_NONE;

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "|p", keywords, &follow))
    return NULL;

  if (follow) {
    PyObject *seen = PySet_New(NULL);
    pwalk_setpos(self, seen, NULL);
    Py_DECREF(seen);

  } else {
    Py_CLEAR(((SibPair *) self)->position);
  }

  Py_RETURN_NONE;
}
Beispiel #21
0
void
TestPyOtherSide::testSetToList()
{
    // Test if a Python set is converted to a list
    PyObject *set = PySet_New(NULL);
    QVERIFY(set != NULL);
    PyObject *o = NULL;

    o = PyLong_FromLong(123);
    QVERIFY(o != NULL);
    QVERIFY(PySet_Add(set, o) == 0);

    o = PyLong_FromLong(321);
    QVERIFY(o != NULL);
    QVERIFY(PySet_Add(set, o) == 0);

    o = PyLong_FromLong(444);
    QVERIFY(o != NULL);
    QVERIFY(PySet_Add(set, o) == 0);

    // This will not be added (no duplicates in a set)
    o = PyLong_FromLong(123);
    QVERIFY(o != NULL);
    QVERIFY(PySet_Add(set, o) == 0);

    // At this point, we should have 3 items (123, 321 and 444)
    QVERIFY(PySet_Size(set) == 3);

    QVariant v = convertPyObjectToQVariant(set);
    QVERIFY(v.canConvert(QMetaType::QVariantList));

    QList<QVariant> l = v.toList();
    QVERIFY(l.size() == 3);
    QVERIFY(l.contains(123));
    QVERIFY(l.contains(321));
    QVERIFY(l.contains(444));
}
Beispiel #22
0
static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
{
#if 0  /* If someone knows how to get a proper 'self' in that case... */
	BPy_StructRNA *pyrna = (BPy_StructRNA *)self;
	Main *bmain = pyrna->ptr.data;
#else
	Main *bmain = G.main;  /* XXX Ugly, but should work! */
#endif

	static const char *kwlist[] = {"subset", "key_types", "value_types", NULL};
	PyObject *subset = NULL;

	PyObject *key_types = NULL;
	PyObject *val_types = NULL;
	BLI_bitmap *key_types_bitmap = NULL;
	BLI_bitmap *val_types_bitmap = NULL;

	PyObject *ret = NULL;


	if (!PyArg_ParseTupleAndKeywords(
	        args, kwds, "|O$O!O!:user_map", (char **)kwlist,
	        &subset,
	        &PySet_Type, &key_types,
	        &PySet_Type, &val_types))
	{
		return NULL;
	}

	if (key_types) {
		key_types_bitmap = pyrna_set_to_enum_bitmap(
		        rna_enum_id_type_items, key_types, sizeof(short), true, USHRT_MAX, "key types");
		if (key_types_bitmap == NULL) {
			goto error;
		}
	}

	if (val_types) {
		val_types_bitmap = pyrna_set_to_enum_bitmap(
		        rna_enum_id_type_items, val_types, sizeof(short), true, USHRT_MAX, "value types");
		if (val_types_bitmap == NULL) {
			goto error;
		}
	}

	IDUserMapData data_cb = {NULL};

	if (subset) {
		PyObject *subset_fast = PySequence_Fast(subset, "user_map");
		if (subset_fast == NULL) {
			goto error;
		}

		PyObject **subset_array = PySequence_Fast_ITEMS(subset_fast);
		Py_ssize_t subset_len = PySequence_Fast_GET_SIZE(subset_fast);

		data_cb.user_map = _PyDict_NewPresized(subset_len);
		data_cb.is_subset = true;
		for (; subset_len; subset_array++, subset_len--) {
			PyObject *set = PySet_New(NULL);
			PyDict_SetItem(data_cb.user_map, *subset_array, set);
			Py_DECREF(set);
		}
		Py_DECREF(subset_fast);
	}
	else {
		data_cb.user_map = PyDict_New();
	}

	data_cb.types_bitmap = key_types_bitmap;

	ListBase *lb_array[MAX_LIBARRAY];
	int lb_index;
	lb_index = set_listbasepointers(bmain, lb_array);

	while (lb_index--) {

		if (val_types_bitmap && lb_array[lb_index]->first) {
			if (!id_check_type(lb_array[lb_index]->first, val_types_bitmap)) {
				continue;
			}
		}

		for (ID *id = lb_array[lb_index]->first; id; id = id->next) {
			/* One-time init, ID is just used as placeholder here, we abuse this in iterator callback
			 * to avoid having to rebuild a complete bpyrna object each time for the key searching
			 * (where only ID pointer value is used). */
			if (data_cb.py_id_key_lookup_only == NULL) {
				data_cb.py_id_key_lookup_only = pyrna_id_CreatePyObject(id);
			}

			if (!data_cb.is_subset) {
				PyObject *key = data_cb.py_id_key_lookup_only;
				PyObject *set;

				RNA_id_pointer_create(id, &((BPy_StructRNA *)key)->ptr);

				/* We have to insert the key now, otherwise ID unused would be missing from final dict... */
				if ((set = PyDict_GetItem(data_cb.user_map, key)) == NULL) {
					/* Cannot use our placeholder key here! */
					key = pyrna_id_CreatePyObject(id);
					set = PySet_New(NULL);
					PyDict_SetItem(data_cb.user_map, key, set);
					Py_DECREF(set);
					Py_DECREF(key);
				}
			}

			data_cb.id_curr = id;
			BKE_library_foreach_ID_link(id, foreach_libblock_id_user_map_callback, &data_cb, IDWALK_NOP);

			if (data_cb.py_id_curr) {
				Py_DECREF(data_cb.py_id_curr);
				data_cb.py_id_curr = NULL;
			}
		}
	}

	ret = data_cb.user_map;


error:

	Py_XDECREF(data_cb.py_id_key_lookup_only);

	if (key_types_bitmap) {
		MEM_freeN(key_types_bitmap);
	}

	if (val_types_bitmap) {
		MEM_freeN(val_types_bitmap);
	}

	return ret;

}
// Returns a new reference.
static PyObject*
decode_val(DecodeBuffer* input, TType type, PyObject* typeargs) {
  switch (type) {

  case T_BOOL: {
    int8_t v = readByte(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }

    switch (v) {
    case 0: Py_RETURN_FALSE;
    case 1: Py_RETURN_TRUE;
    // Don't laugh.  This is a potentially serious issue.
    default: PyErr_SetString(PyExc_TypeError, "boolean out of range"); return NULL;
    }
    break;
  }
  case T_I08: {
    int8_t v = readByte(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }

    return PyInt_FromLong(v);
  }
  case T_I16: {
    int16_t v = readI16(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    return PyInt_FromLong(v);
  }
  case T_I32: {
    int32_t v = readI32(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    return PyInt_FromLong(v);
  }

  case T_I64: {
    int64_t v = readI64(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    // TODO(dreiss): Find out if we can take this fastpath always when
    //               sizeof(long) == sizeof(long long).
    if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
      return PyInt_FromLong((long) v);
    }

    return PyLong_FromLongLong(v);
  }

  case T_DOUBLE: {
    double v = readDouble(input);
    if (v == -1.0 && PyErr_Occurred()) {
      return false;
    }
    return PyFloat_FromDouble(v);
  }

  case T_STRING: {
    Py_ssize_t len = readI32(input);
    char* buf;
    if (!readBytes(input, &buf, len)) {
      return NULL;
    }

    return PyString_FromStringAndSize(buf, len);
  }

  case T_LIST:
  case T_SET: {
    SetListTypeArgs parsedargs;
    int32_t len;
    PyObject* ret = NULL;
    int i;

    if (!parse_set_list_args(&parsedargs, typeargs)) {
      return NULL;
    }

    if (!checkTypeByte(input, parsedargs.element_type)) {
      return NULL;
    }

    len = readI32(input);
    if (!check_ssize_t_32(len)) {
      return NULL;
    }

    ret = PyList_New(len);
    if (!ret) {
      return NULL;
    }

    for (i = 0; i < len; i++) {
      PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs);
      if (!item) {
        Py_DECREF(ret);
        return NULL;
      }
      PyList_SET_ITEM(ret, i, item);
    }

    // TODO(dreiss): Consider biting the bullet and making two separate cases
    //               for list and set, avoiding this post facto conversion.
    if (type == T_SET) {
      PyObject* setret;
#if (PY_VERSION_HEX < 0x02050000)
      // hack needed for older versions
      setret = PyObject_CallFunctionObjArgs((PyObject*)&PySet_Type, ret, NULL);
#else
      // official version
      setret = PySet_New(ret);
#endif
      Py_DECREF(ret);
      return setret;
    }
    return ret;
  }

  case T_MAP: {
    int32_t len;
    int i;
    MapTypeArgs parsedargs;
    PyObject* ret = NULL;

    if (!parse_map_args(&parsedargs, typeargs)) {
      return NULL;
    }

    if (!checkTypeByte(input, parsedargs.ktag)) {
      return NULL;
    }
    if (!checkTypeByte(input, parsedargs.vtag)) {
      return NULL;
    }

    len = readI32(input);
    if (!check_ssize_t_32(len)) {
      return false;
    }

    ret = PyDict_New();
    if (!ret) {
      goto error;
    }

    for (i = 0; i < len; i++) {
      PyObject* k = NULL;
      PyObject* v = NULL;
      k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs);
      if (k == NULL) {
        goto loop_error;
      }
      v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs);
      if (v == NULL) {
        goto loop_error;
      }
      if (PyDict_SetItem(ret, k, v) == -1) {
        goto loop_error;
      }

      Py_DECREF(k);
      Py_DECREF(v);
      continue;

      // Yuck!  Destructors, anyone?
      loop_error:
      Py_XDECREF(k);
      Py_XDECREF(v);
      goto error;
    }

    return ret;

    error:
    Py_XDECREF(ret);
    return NULL;
  }

  case T_STRUCT: {
    StructTypeArgs parsedargs;
    if (!parse_struct_args(&parsedargs, typeargs)) {
      return NULL;
    }

    PyObject* ret = PyObject_CallObject(parsedargs.klass, NULL);
    if (!ret) {
      return NULL;
    }

    if (!decode_struct(input, ret, parsedargs.spec)) {
      Py_DECREF(ret);
      return NULL;
    }

    return ret;
  }

  case T_STOP:
  case T_VOID:
  case T_UTF16:
  case T_UTF8:
  case T_U64:
  default:
    PyErr_SetString(PyExc_TypeError, "Unexpected TType");
    return NULL;
  }
}
Beispiel #24
0
PyObject *WeakSet_test(PyObject *ignored){
    int r;
    WeakSet *set = NULL;
    PyObject *obj = NULL;
    PyObject *setref = NULL;
    PyObject *setbackup = NULL;

    // It'd be nice if this had line numbers.
#define T(x) if (!(x)) {PyErr_SetString(PyExc_AssertionError,"FIXME"); goto bail;}

    obj = WeakSet_New(); 
    if (!obj) goto bail;

    set = (WeakSet *)WeakSet_New();
    if (!set) goto bail;
    setref = set->selfref;
    Py_INCREF(setref);
    T(setref->ob_refcnt == 2);
    T(PyObject_Length(set->set) == 0);
    T(WeakSet_Contains((PyObject *)set,obj) == 0);

    r = WeakSet_Add((PyObject *)set,obj);
    if (r) goto bail;
    T(setref->ob_refcnt == 3);
    T(PyObject_Length(set->set) == 1);
    T(WeakSet_Contains((PyObject *)set,obj) == 1);

    // Simple case, object is deleted while set is still alive.
    Py_CLEAR(obj);
    T(setref->ob_refcnt == 2);
    T(PyObject_Length(set->set) == 0);

    // Complex, set is deleted, while object is still alive.
    obj = WeakSet_New(); 
    if (!obj) goto bail;
    r = WeakSet_Add((PyObject *)set,obj);
    if (r) goto bail;
    T(PyObject_Length(set->set) == 1);
    T(WeakSet_Contains((PyObject *)set,obj) == 1);
    T(setref->ob_refcnt == 3);


    // If we simply delete set, the reference created for obj, and hence
    // setref, will have nothing pointing to it and be garbage collected before
    // set is actually deleted. So create a backup of the set, forcing the
    // reference created for obj to persist.
    setbackup = PySet_New(set->set);
    if (!setbackup) goto bail;

    Py_CLEAR(set);
    // The reference for obj is still holding a reference to setref
    T(setref->ob_refcnt == 2);

    Py_CLEAR(obj);
    // Now only we are holding a reference to setref
    T(setref->ob_refcnt == 1);


    Py_XDECREF(set);
    Py_XDECREF(setbackup);
    Py_XDECREF(setref);
    Py_XDECREF(obj);
    Py_RETURN_TRUE;
bail:
    Py_XDECREF(set);
    Py_XDECREF(setbackup);
    Py_XDECREF(setref);
    Py_XDECREF(obj);
    return NULL;
}
Beispiel #25
0
 PyObject *to_python<types::empty_set>::convert(types::empty_set)
 {
   return PySet_New(nullptr);
 }
Beispiel #26
0
PyObject*
Context_new(PyTypeObject* type, PyObject* args, PyObject* kwargs)
{
    Context* self = NULL;
    Runtime* runtime = NULL;
    PyObject* global = NULL;
    PyObject* access = NULL;
    PyObject* alertlist = NULL;
    
    char* keywords[] = {"runtime", "glbl", "access", "alertlist", NULL};

    if(!PyArg_ParseTupleAndKeywords(
        args, kwargs,
        "O!|OOO",
        keywords,
        RuntimeType, &runtime,
        &global,
        &access,
        &alertlist
    )) goto error;

    if(global == Py_None) global = NULL;
    if(access == Py_None) access = NULL;
    if(alertlist == Py_None) alertlist = NULL;

    if(global != NULL && !PyMapping_Check(global))
    {
        PyErr_SetString(PyExc_TypeError,
                            "Global handler must provide item access.");
        goto error;
    }

    if(access != NULL && !PyCallable_Check(access))
    {
        PyErr_SetString(PyExc_TypeError,
                            "Access handler must be callable.");
        goto error;
    }

    if(alertlist != NULL && !PyList_Check(alertlist))
    {
        PyErr_SetString(PyExc_TypeError,
                        "Alert list must be a list object.");
        goto error;
    }
            
    self = (Context*) type->tp_alloc(type, 0);
    if(self == NULL) goto error;

    // Tracking what classes we've installed in
    // the context.
    self->classes = (PyDictObject*) PyDict_New();
    if(self->classes == NULL) goto error;

    self->objects = (PySetObject*) PySet_New(NULL);
    if(self->objects == NULL) goto error;

    self->cx = JS_NewContext(runtime->rt, 8192);
    if(self->cx == NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Failed to create JSContext.");
        goto error;
    }

    JS_BeginRequest(self->cx);

    /*
     *  Notice that we don't add a ref to the Python context for
     *  the copy stored on the JSContext*. I'm pretty sure this
     *  would cause a cyclic dependancy that would prevent
     *  garbage collection from happening on either side of the
     *  bridge.
     *
     */
    JS_SetContextPrivate(self->cx, self);

    // Setup the root of the property lookup doodad.
    self->root = JS_NewObject(self->cx, &js_global_class, NULL, NULL);
    if(self->root == NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Error creating root object.");
        goto error;
    }

    if(!JS_InitStandardClasses(self->cx, self->root))
    {
        PyErr_SetString(PyExc_RuntimeError, "Error initializing JS VM.");
        goto error;
    }

    // Don't setup the global handler until after the standard classes
    // have been initialized.
    // XXX: Does anyone know if finalize is called if new fails?
    if(global != NULL) Py_INCREF(global);
    self->global = global;

    if(access != NULL) Py_INCREF(access);
    self->access = access;

    if(alertlist != NULL) Py_INCREF(alertlist);
    self->alertlist = alertlist;

    // Setup counters for resource limits
    self->branch_count = 0;
    self->max_time = 0;
    self->start_time = 0;
    self->max_heap = 0;

    JS_SetBranchCallback(self->cx, branch_cb);
    JS_SetErrorReporter(self->cx, report_error_cb);
    
    Py_INCREF(runtime);
    self->rt = runtime;

    goto success;

error:
    if(self != NULL && self->cx != NULL) JS_EndRequest(self->cx);
    Py_XDECREF(self);
    self = NULL;

success:
    if(self != NULL && self->cx != NULL) JS_EndRequest(self->cx);
    return (PyObject*) self;
}
Beispiel #27
0
// Returns a new reference.
static PyObject*
decode_val(DecodeBuffer* input, TType type, PyObject* typeargs, long string_limit, long container_limit) {
    switch (type) {

    case T_BOOL: {
        int8_t v = readByte(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }

        switch (v) {
        case 0:
            Py_RETURN_FALSE;
        case 1:
            Py_RETURN_TRUE;
        // Don't laugh.  This is a potentially serious issue.
        default:
            PyErr_SetString(PyExc_TypeError, "boolean out of range");
            return NULL;
        }
        break;
    }
    case T_I08: {
        int8_t v = readByte(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }

        return PyInt_FromLong(v);
    }
    case T_I16: {
        int16_t v = readI16(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        return PyInt_FromLong(v);
    }
    case T_I32: {
        int32_t v = readI32(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        return PyInt_FromLong(v);
    }

    case T_I64: {
        int64_t v = readI64(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        // TODO(dreiss): Find out if we can take this fastpath always when
        //               sizeof(long) == sizeof(long long).
        if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
            return PyInt_FromLong((long) v);
        }

        return PyLong_FromLongLong(v);
    }

    case T_DOUBLE: {
        double v = readDouble(input);
        if (v == -1.0 && PyErr_Occurred()) {
            return false;
        }
        return PyFloat_FromDouble(v);
    }

    case T_STRING: {
        Py_ssize_t len = readI32(input);
        char* buf;
        if (!readBytes(input, &buf, len)) {
            return NULL;
        }
        if (!check_length_limit(len, string_limit)) {
            return NULL;
        }

        if (is_utf8(typeargs))
            return PyUnicode_DecodeUTF8(buf, len, 0);
        else
            return PyString_FromStringAndSize(buf, len);
    }

    case T_LIST:
    case T_SET: {
        SetListTypeArgs parsedargs;
        int32_t len;
        PyObject* ret = NULL;
        int i;
        bool use_tuple = false;

        if (!parse_set_list_args(&parsedargs, typeargs)) {
            return NULL;
        }

        if (!checkTypeByte(input, parsedargs.element_type)) {
            return NULL;
        }

        len = readI32(input);
        if (!check_length_limit(len, container_limit)) {
            return NULL;
        }

        use_tuple = type == T_LIST && parsedargs.immutable;
        ret = use_tuple ? PyTuple_New(len) : PyList_New(len);
        if (!ret) {
            return NULL;
        }

        for (i = 0; i < len; i++) {
            PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs, string_limit, container_limit);
            if (!item) {
                Py_DECREF(ret);
                return NULL;
            }
            if (use_tuple) {
                PyTuple_SET_ITEM(ret, i, item);
            } else  {
                PyList_SET_ITEM(ret, i, item);
            }
        }

        // TODO(dreiss): Consider biting the bullet and making two separate cases
        //               for list and set, avoiding this post facto conversion.
        if (type == T_SET) {
            PyObject* setret;
            setret = parsedargs.immutable ? PyFrozenSet_New(ret) : PySet_New(ret);
            Py_DECREF(ret);
            return setret;
        }
        return ret;
    }

    case T_MAP: {
        int32_t len;
        int i;
        MapTypeArgs parsedargs;
        PyObject* ret = NULL;

        if (!parse_map_args(&parsedargs, typeargs)) {
            return NULL;
        }

        if (!checkTypeByte(input, parsedargs.ktag)) {
            return NULL;
        }
        if (!checkTypeByte(input, parsedargs.vtag)) {
            return NULL;
        }

        len = readI32(input);
        if (!check_length_limit(len, container_limit)) {
            return NULL;
        }

        ret = PyDict_New();
        if (!ret) {
            goto error;
        }

        for (i = 0; i < len; i++) {
            PyObject* k = NULL;
            PyObject* v = NULL;
            k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs, string_limit, container_limit);
            if (k == NULL) {
                goto loop_error;
            }
            v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs, string_limit, container_limit);
            if (v == NULL) {
                goto loop_error;
            }
            if (PyDict_SetItem(ret, k, v) == -1) {
                goto loop_error;
            }

            Py_DECREF(k);
            Py_DECREF(v);
            continue;

            // Yuck!  Destructors, anyone?
loop_error:
            Py_XDECREF(k);
            Py_XDECREF(v);
            goto error;
        }

        if (parsedargs.immutable) {
            PyObject* thrift = PyImport_ImportModule("thrift.Thrift");
            PyObject* cls = NULL;
            PyObject* arg = NULL;
            if (!thrift) {
                goto error;
            }
            cls = PyObject_GetAttrString(thrift, "TFrozenDict");
            if (!cls) {
                goto error;
            }
            arg = PyTuple_New(1);
            PyTuple_SET_ITEM(arg, 0, ret);
            return PyObject_CallObject(cls, arg);
        }

        return ret;

error:
        Py_XDECREF(ret);
        return NULL;
    }

    case T_STRUCT: {
        StructTypeArgs parsedargs;
        if (!parse_struct_args(&parsedargs, typeargs)) {
            return NULL;
        }

        return decode_struct(input, Py_None, parsedargs.klass, parsedargs.spec, string_limit, container_limit);
    }

    case T_STOP:
    case T_VOID:
    case T_UTF16:
    case T_UTF8:
    case T_U64:
    default:
        PyErr_SetString(PyExc_TypeError, "Unexpected TType");
        return NULL;
    }
}
Beispiel #28
0
static PyObject *
plist_fullset (PyObject *self) {

	return PySet_New(plist_fulllist(self));

}
Beispiel #29
0
//=============================================================================
// STATIC : SPELLwsWarmStartImpl::setGlobalsFilter()
//=============================================================================
void SPELLwsWarmStartImpl::setGlobalsFilter( PyObject* filterKeys )
{
	s_filterKeys = PySet_New( filterKeys );
}