Beispiel #1
0
/* Try a 3-way comparison, returning an int.  Return:
   -2 for an exception;
   -1 if v <  w;
    0 if v == w;
    1 if v  > w;
    2 if this particular 3-way comparison is not implemented or undefined.
*/
static int
try_3way_compare(PyObject *v, PyObject *w)
{
	int c;
	cmpfunc f;

	/* Comparisons involving instances are given to instance_compare,
	   which has the same return conventions as this function. */

	f = v->ob_type->tp_compare;
	if (PyInstance_Check(v))
		return (*f)(v, w);
	if (PyInstance_Check(w))
		return (*w->ob_type->tp_compare)(v, w);

	/* If both have the same (non-NULL) tp_compare, use it. */
	if (f != NULL && f == w->ob_type->tp_compare) {
		c = (*f)(v, w);
		if (c < 0 && PyErr_Occurred())
			return -1;
		return c < 0 ? -1 : c > 0 ? 1 : 0;
	}

	/* If either tp_compare is _PyObject_SlotCompare, that's safe. */
	if (f == _PyObject_SlotCompare ||
	    w->ob_type->tp_compare == _PyObject_SlotCompare)
		return _PyObject_SlotCompare(v, w);

	/* Try coercion; if it fails, give up */
	c = PyNumber_CoerceEx(&v, &w);
	if (c < 0)
		return -2;
	if (c > 0)
		return 2;

	/* Try v's comparison, if defined */
	if ((f = v->ob_type->tp_compare) != NULL) {
		c = (*f)(v, w);
		Py_DECREF(v);
		Py_DECREF(w);
		if (c < 0 && PyErr_Occurred())
			return -2;
		return c < 0 ? -1 : c > 0 ? 1 : 0;
	}

	/* Try w's comparison, if defined */
	if ((f = w->ob_type->tp_compare) != NULL) {
		c = (*f)(w, v); /* swapped! */
		Py_DECREF(v);
		Py_DECREF(w);
		if (c < 0 && PyErr_Occurred())
			return -2;
		return c < 0 ? 1 : c > 0 ? -1 : 0; /* negated! */
	}

	/* No comparison defined */
	Py_DECREF(v);
	Py_DECREF(w);
	return 2;
}
Beispiel #2
0
PyObject *
PyNumber_Multiply(PyObject *v, PyObject *w)
{
	PyTypeObject *tp = v->ob_type;
	PySequenceMethods *m;

	BINOP(v, w, "__mul__", "__rmul__", PyNumber_Multiply);
	if (tp->tp_as_number != NULL &&
	    w->ob_type->tp_as_sequence != NULL &&
	    !PyInstance_Check(v)) {
		/* number*sequence -- swap v and w */
		PyObject *tmp = v;
		v = w;
		w = tmp;
		tp = v->ob_type;
	}
	if (tp->tp_as_number != NULL) {
		PyObject *x = NULL;
		PyObject * (*f)(PyObject *, PyObject *);
		if (PyInstance_Check(v)) {
			/* Instances of user-defined classes get their
			   other argument uncoerced, so they may
			   implement sequence*number as well as
			   number*number. */
			Py_INCREF(v);
			Py_INCREF(w);
		}
		else if (PyNumber_Coerce(&v, &w) != 0)
			return NULL;
		if ((f = v->ob_type->tp_as_number->nb_multiply) != NULL)
			x = (*f)(v, w);
		Py_DECREF(v);
		Py_DECREF(w);
		if (f != NULL)
			return x;
	}
	m = tp->tp_as_sequence;
	if (m && m->sq_repeat) {
		long mul_value;

		if (PyInt_Check(w)) {
			mul_value = PyInt_AsLong(w);
		}
		else if (PyLong_Check(w)) {
			mul_value = PyLong_AsLong(w);
			if (mul_value == -1 && PyErr_Occurred())
                                return NULL; 
		}
		else {
			return type_error(
				"can't multiply sequence with non-int");
		}
		return (*m->sq_repeat)(v, (int)mul_value);
	}
	return type_error("bad operand type(s) for *");
}
Beispiel #3
0
/* Try a 3-way comparison, returning an int.  Return:
   -2 for an exception;
   -1 if v <  w;
    0 if v == w;
    1 if v  > w;
    2 if this particular 3-way comparison is not implemented or undefined.
*/
static int
try_3way_compare(PyObject *v, PyObject *w)
{
	int c;
	cmpfunc f;

	/* Comparisons involving instances are given to instance_compare,
	   which has the same return conventions as this function. */

	f = v->ob_type->tp_compare;
	if (PyInstance_Check(v))
		return (*f)(v, w);
	if (PyInstance_Check(w))
		return (*w->ob_type->tp_compare)(v, w);

	/* If both have the same (non-NULL) tp_compare, use it. */
	if (f != NULL && f == w->ob_type->tp_compare) {
		c = (*f)(v, w);
		return adjust_tp_compare(c);
	}

	/* If either tp_compare is _PyObject_SlotCompare, that's safe. */
	if (f == _PyObject_SlotCompare ||
	    w->ob_type->tp_compare == _PyObject_SlotCompare)
		return _PyObject_SlotCompare(v, w);

	/* If we're here, v and w,
	    a) are not instances;
	    b) have different types or a type without tp_compare; and
	    c) don't have a user-defined tp_compare.
	   tp_compare implementations in C assume that both arguments
	   have their type, so we give up if the coercion fails or if
	   it yields types which are still incompatible (which can
	   happen with a user-defined nb_coerce).
	*/
	c = PyNumber_CoerceEx(&v, &w);
	if (c < 0)
		return -2;
	if (c > 0)
		return 2;
	f = v->ob_type->tp_compare;
	if (f != NULL && f == w->ob_type->tp_compare) {
		c = (*f)(v, w);
		Py_DECREF(v);
		Py_DECREF(w);
		return adjust_tp_compare(c);
	}

	/* No comparison defined */
	Py_DECREF(v);
	Py_DECREF(w);
	return 2;
}
Beispiel #4
0
/* Given a Python object, return a string to use in Jam
   code instead of said object.
   If the object is string, use the string value
   If the object implemenets __jam_repr__ method, use that.
   Otherwise return 0.

   The result value is newstr-ed.  */
char *python_to_string(PyObject* value)
{
    if (PyString_Check(value))
    {
        return newstr(PyString_AsString(value));
    }
    else
    {
        /* See if this is an instance that defines special __jam_repr__
           method. */
        if (PyInstance_Check(value)
            && PyObject_HasAttrString(value, "__jam_repr__"))
        {
            PyObject* repr = PyObject_GetAttrString(value, "__jam_repr__");
            if (repr)
            {
                PyObject* arguments2 = PyTuple_New(0);
                PyObject* value2 = PyObject_Call(repr, arguments2, 0);
                Py_DECREF(repr);
                Py_DECREF(arguments2);
                if (PyString_Check(value2))
                {
                    return newstr(PyString_AsString(value2));
                }
                Py_DECREF(value2);
            }
        }
        return 0;
    }
}
Beispiel #5
0
/* Do a 3-way comparison, by hook or by crook.  Return:
   -2 for an exception (but see below);
   -1 if v <  w;
    0 if v == w;
    1 if v >  w;
   BUT: if the object implements a tp_compare function, it returns
   whatever this function returns (whether with an exception or not).
*/
static int
do_cmp(PyObject *v, PyObject *w)
{
	int c;
	cmpfunc f;

	if (v->ob_type == w->ob_type
	    && (f = v->ob_type->tp_compare) != NULL) {
		c = (*f)(v, w);
		if (PyInstance_Check(v)) {
			/* Instance tp_compare has a different signature.
			   But if it returns undefined we fall through. */
			if (c != 2)
				return c;
			/* Else fall through to try_rich_to_3way_compare() */
		}
		else
			return adjust_tp_compare(c);
	}
	/* We only get here if one of the following is true:
	   a) v and w have different types
	   b) v and w have the same type, which doesn't have tp_compare
	   c) v and w are instances, and either __cmp__ is not defined or
	      __cmp__ returns NotImplemented
	*/
	c = try_rich_to_3way_compare(v, w);
	if (c < 2)
		return c;
	c = try_3way_compare(v, w);
	if (c < 2)
		return c;
	return default_3way_compare(v, w);
}
Beispiel #6
0
CallbackManager::~CallbackManager()
{
    // Decrement all of the callback function reference counts.
    for(SubjectCallbackDataMap::iterator it = callbacks.begin();
        it != callbacks.end(); ++it)
    {
        it->first->Detach(this);
        if(it->second.pycb != 0)
            Py_DECREF(it->second.pycb);
        if(it->second.pycb_data != 0)
        {
#ifdef Py_REFCNT
            // Hack! I found that decrementing the refcount of a class 
            //       instance from here causes a crash if it's the last
            //       reference and it will cause the object to be deleted.
            //       Decrementing the refcount on other object types is fine,
            //       even if it causes the object to get deleted. Other objects
            //       work okay so our reference counting seems good.
            bool lastInstance = Py_REFCNT(it->second.pycb_data) == 1 &&
                                PyInstance_Check(it->second.pycb_data);
            if(!lastInstance)
#endif
                Py_DECREF(it->second.pycb_data);
        }
    }
    delete threading;
}
static gboolean
init (NstPlugin *plugin)
{
	Py_Initialize();

	gobject = pygobject_init(2,1,0);

	module = PyImport_ImportModule("blueman.gui.NstBluetooth");
	if(!module) {
		PyErr_Print();
		return FALSE;
	}

	PyObject* class = PyObject_GetAttrString(module, "NstBluetooth");
	if(!class) {
		PyErr_Print();
		return FALSE;
	}

	Py_DECREF(class);

	self = PyInstance_New(class, NULL, NULL);
	if(!self) {
		PyErr_Print();
		return FALSE;
	}

	return PyInstance_Check(self);
}
Beispiel #8
0
PyObject *LOOKUP_SPECIAL(PyObject *source, PyObject *attr_name) {
#if PYTHON_VERSION < 300
    if (PyInstance_Check(source)) {
        return LOOKUP_INSTANCE(source, attr_name);
    }
#endif

    // TODO: There is heavy optimization in CPython to avoid it. Potentially
    // that's worth it to imitate that.

    PyObject *result = _PyType_Lookup(Py_TYPE(source), attr_name);

    if (likely(result)) {
        descrgetfunc func = Py_TYPE(result)->tp_descr_get;

        if (func == NULL) {
            Py_INCREF(result);
            return result;
        } else {
            PyObject *func_result = func(result, source, (PyObject *)(Py_TYPE(source)));

            if (unlikely(func_result == NULL)) {
                return NULL;
            }

            CHECK_OBJECT(func_result);
            return func_result;
        }
    }

    PyErr_SetObject(PyExc_AttributeError, attr_name);
    return NULL;
}
Beispiel #9
0
int
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
{
	if (err == NULL || exc == NULL) {
		/* maybe caused by "import exceptions" that failed early on */
		return 0;
	}
	if (PyTuple_Check(exc)) {
		int i, n;
		n = PyTuple_Size(exc);
		for (i = 0; i < n; i++) {
			/* Test recursively */
		     if (PyErr_GivenExceptionMatches(
			     err, PyTuple_GET_ITEM(exc, i)))
		     {
			     return 1;
		     }
		}
		return 0;
	}
	/* err might be an instance, so check its class. */
	if (PyInstance_Check(err))
		err = (PyObject*)((PyInstanceObject*)err)->in_class;

	if (PyClass_Check(err) && PyClass_Check(exc))
		return PyClass_IsSubclass(err, exc);

	return err == exc;
}
Beispiel #10
0
bool PyViewer::GetItem(int row_, int col_, c4_Bytes &buf_) {
  const c4_Property &prop = _template.NthProperty(col_);
  if (_byPos) {
    PWOSequence item(_data[row_]);
    PyRowRef::setFromPython(_tempRow, prop, item[col_]);
    return prop(_tempRow).GetData(buf_);
  }
  PyObject *item = _data[row_];
  if (PyInstance_Check(item)) {
    PyObject *attr = PyObject_GetAttrString(item, (char*)prop.Name());
    PyRowRef::setFromPython(_tempRow, prop, attr);
    return prop(_tempRow).GetData(buf_);
  }
  if (PyDict_Check(item)) {
    PyObject *attr = PyDict_GetItemString(item, (char*)prop.Name());
    PyRowRef::setFromPython(_tempRow, prop, attr);
    return prop(_tempRow).GetData(buf_);
  }
  if (_template.NumProperties() == 1) {
    PyRowRef::setFromPython(_tempRow, prop, _data[row_]);
    return prop(_tempRow).GetData(buf_);
  }
  Fail(PyExc_ValueError, "Object has no usable attributes");
  return false;
  // create a row with just this single property value
  // this detour handles dicts and objects, because makeRow does
  /*  c4_Row one;
  PyView v (prop); // nasty, stack-based temp to get at makeRow
  v.makeRow(one, _data[row_]);
  return prop (one).GetData(buf_); */
}
Beispiel #11
0
static PyObject *
try_complex_special_method(PyObject *op) {
    PyObject *f;
    static PyObject *complexstr;

    if (complexstr == NULL) {
        complexstr = PyString_InternFromString("__complex__");
        if (complexstr == NULL)
            return NULL;
    }
    if (PyInstance_Check(op)) {
        f = PyObject_GetAttr(op, complexstr);
        if (f == NULL) {
            if (PyErr_ExceptionMatches(PyExc_AttributeError))
                PyErr_Clear();
            else
                return NULL;
        }
    }
    else {
        f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);
        if (f == NULL && PyErr_Occurred())
            return NULL;
    }
    if (f != NULL) {
        PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
        Py_DECREF(f);
        return res;
    }
    return NULL;
}
Beispiel #12
0
static PyObject *
new_instancemethod(PyObject* unused, PyObject* args)
{
	PyObject* func;
	PyObject* self;
	PyObject* classObj;

	if (!PyArg_ParseTuple(args, "OOO!:instancemethod",
			      &func,
			      &self,
			      &PyClass_Type, &classObj))
		return NULL;
	if (!PyCallable_Check(func)) {
		PyErr_SetString(PyExc_TypeError,
				"first argument must be callable");
		return NULL;
	}
	if (self == Py_None)
		self = NULL;
	else if (!PyInstance_Check(self)) {
		PyErr_SetString(PyExc_TypeError,
				"second argument must be instance or None");
		return NULL;
	}
	return PyMethod_New(func, self, classObj);
}
Beispiel #13
0
// Returns a BORROWED reference
PyObject * getClassObject( PyObject * pyObject )
{
	bool isInstance = false;
	SIP_BLOCK_THREADS
	isInstance = PyInstance_Check( pyObject );
	SIP_UNBLOCK_THREADS
	if( isInstance )
		return (PyObject*)(((PyInstanceObject*)pyObject)->in_class);
	return 0;
}
Beispiel #14
0
static PyObject *LOOKUP_INSTANCE(PyObject *source, PyObject *attr_name) {
    CHECK_OBJECT(source);
    CHECK_OBJECT(attr_name);

    assert(PyInstance_Check(source));
    assert(PyString_CheckExact(attr_name));

    PyInstanceObject *source_instance = (PyInstanceObject *)source;

    // The special cases have their own variant on the code generation level
    // as we are called with constants only.
    assert(attr_name != const_str_plain___dict__);
    assert(attr_name != const_str_plain___class__);

    // Try the instance dict first.
    PyObject *result = GET_STRING_DICT_VALUE((PyDictObject *)source_instance->in_dict, (PyStringObject *)attr_name);

    if (result) {
        Py_INCREF(result);
        return result;
    }

    // Next see if a class has it
    result = FIND_ATTRIBUTE_IN_CLASS(source_instance->in_class, attr_name);

    if (result != NULL) {
        descrgetfunc func = Py_TYPE(result)->tp_descr_get;

        if (func) {
            result = func(result, source, (PyObject *)source_instance->in_class);

            if (unlikely(result == NULL)) {
                return NULL;
            }

            CHECK_OBJECT(result);

            return result;
        } else {
            Py_INCREF(result);
            return result;
        }
    }

    // Finally allow a __getattr__ to handle it or else it's an error.
    if (unlikely(source_instance->in_class->cl_getattr == NULL)) {
        PyErr_Format(PyExc_AttributeError, "%s instance has no attribute '%s'",
                     PyString_AS_STRING(source_instance->in_class->cl_name), PyString_AS_STRING(attr_name));

        return NULL;
    } else {
        PyObject *args[] = {source, attr_name};
        return CALL_FUNCTION_WITH_ARGS2(source_instance->in_class->cl_getattr, args);
    }
}
Beispiel #15
0
static PyObject *
reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    Py_ssize_t n;
    PyObject *seq, *reversed_meth;
    static PyObject *reversed_cache = NULL;
    reversedobject *ro;

    if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds))
        return NULL;

    if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) )
        return NULL;

    if (PyInstance_Check(seq)) {
        reversed_meth = PyObject_GetAttrString(seq, "__reversed__");
        if (reversed_meth == NULL) {
            if (PyErr_ExceptionMatches(PyExc_AttributeError))
                PyErr_Clear();
            else
                return NULL;
        }
    }
    else {
        reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__",
                                                &reversed_cache);
        if (reversed_meth == NULL && PyErr_Occurred())
            return NULL;
    }
    if (reversed_meth != NULL) {
        PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL);
        Py_DECREF(reversed_meth);
        return res;
    }

    if (!PySequence_Check(seq)) {
        PyErr_SetString(PyExc_TypeError,
                        "argument to reversed() must be a sequence");
        return NULL;
    }

    n = PySequence_Size(seq);
    if (n == -1)
        return NULL;

    ro = (reversedobject *)type->tp_alloc(type, 0);
    if (ro == NULL)
        return NULL;

    ro->index = n-1;
    Py_INCREF(seq);
    ro->seq = seq;
    return (PyObject *)ro;
}
PyObject* PyObject_AsPyString(PyObject* object) {
    if (object == NULL) {
        return NULL;
    }

    if (PyInstance_Check(object)) {
        return instance_repr((PyInstanceObject*) object);
    }

    return PyObject_CallAsPyString(Py_TYPE(object));
}
Beispiel #17
0
static void
debug_cycle(char *msg, PyObject *op)
{
	if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
		debug_instance(msg, (PyInstanceObject *)op);
	}
	else if (debug & DEBUG_OBJECTS) {
		PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
				  msg, op->ob_type->tp_name, op);
	}
}
//=============================================================================
// METHOD: SPELLvariableMonitor::retrieveLocalVariables()
//=============================================================================
void SPELLvariableMonitor::retrieveLocalVariables(std::vector<SPELLvarInfo>& vars)
{
	DEBUG("[VM] Retrieve Locals");

	/*
	 * Bottom stack frame is discarded,
	 * as globals and locals are the same dictionary
	 */
	if (m_frame->f_back == NULL) return;

	/*
	 * Get the names defined in the current code, including arguments
	 */
	std::vector<std::string> varNames = retrieveNames();

	/*
	 * Iterate over the locals dictionary, retrieving the names contained in
	 * varNames
	 */
	PyFrame_FastToLocals(m_frame);
	PyObject* dict = m_frame->f_locals;
	DEBUG("[VM] Frame: " + PYCREPR(m_frame));
	for( unsigned int index = 0; index< varNames.size(); index++)
	{
		std::string varName = varNames[index];
		PyObject* pyVarName = SSTRPY(varName);
		if (PyDict_Contains( dict, pyVarName ))
		{
			PyObject* object = PyDict_GetItem( dict, pyVarName );

			if (!SPELLpythonHelper::instance().isInstance(object, "Database", "spell.lib.adapter.databases.database"))
			{
				if (PyCallable_Check(object)) continue;
				if (PyClass_Check(object)) continue;
				if (PyModule_Check(object)) continue;
				if (PyInstance_Check(object)) continue;
			}
			DEBUG("[VM] Processing " + varName);
			std::string type = PYSSTR( PyObject_Type(object) );
			DEBUG("[VM] Type      : " + type);
			std::string value = PYREPR( object );
			DEBUG("[VM] Value     : " + value);
			DEBUG("[VM] Global    : " + BSTR(false));
			DEBUG("[VM] Registered: " + BSTR(isRegistered(varName)));

			// Mark empty values (empty strings) as "<empty>"
			if (value == "") value = EMPTY_STRING;

			vars.push_back( SPELLvarInfo(varName, type, value, false, isRegistered(varName)) );
		}
	}
	PyFrame_LocalsToFast(m_frame,0);
}
Beispiel #19
0
/* Return true if object has a finalization method.
 * CAUTION:  An instance of an old-style class has to be checked for a
 *__del__ method, and earlier versions of this used to call PyObject_HasAttr,
 * which in turn could call the class's __getattr__ hook (if any).  That
 * could invoke arbitrary Python code, mutating the object graph in arbitrary
 * ways, and that was the source of some excruciatingly subtle bugs.
 */
static int
has_finalizer(PyObject *op)
{
	if (PyInstance_Check(op)) {
		assert(delstr != NULL);
		return _PyInstance_Lookup(op, delstr) != NULL;
	}
	else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
		return op->ob_type->tp_del != NULL;
	else
		return 0;
}
Beispiel #20
0
//for now we don't know whether creating python class instance will do write to the class object, then no mutex used, we will check this in detail in the later time
//
int create_ins(void){
    int ret = -1;
    PyObject *pargs=NULL;

#if PY_DEBUG
    fprintf(stderr,"I am here %s\n",__FUNCTION__);
#endif

    if(!check_ready()){
        if(!check_and_set_ready()){
            goto create_ins_error;
        }
    }

	pargs = PyTuple_New(1);
    if(!pargs){
#if PY_DEBUG
		fprintf(stderr,"we cannot create the first tuple\n");  
#endif
        goto create_ins_error;
    }


	PyTuple_SetItem(pargs,0,Py_BuildValue("s",replica_group));

#if PY_DEBUG
	fprintf(stderr,"%p\n",pclass);  
#endif

	pins = PyInstance_New(pclass,pargs,NULL);

	if(!pins){
#if PY_DEBUG
		fprintf(stderr,"we cannot create the instance\n");  
#endif
        goto create_ins_error;
	}
	if(PyInstance_Check(pins)){
#if PY_DEBUG
		fprintf(stderr,"Sure, We have created an instance\n");  
#endif
	}else{
        goto create_ins_error;
    }
    ret = 0;
    goto create_ins_exit;
create_ins_error:
    if(NULL!=pins){Py_DECREF(pins);pins=NULL;};
create_ins_exit:
    if(NULL!=pargs){Py_DECREF(pargs);pargs=NULL;};
    return ret;
}
Beispiel #21
0
bool SET_ATTRIBUTE_DICT_SLOT(PyObject *target, PyObject *value) {
    CHECK_OBJECT(target);
    CHECK_OBJECT(value);

#if PYTHON_VERSION < 300
    if (likely(PyInstance_Check(target))) {
        PyInstanceObject *target_instance = (PyInstanceObject *)target;

        /* Note seems this doesn't have to be an exact dictionary. */
        if (unlikely(!PyDict_Check(value))) {
            PyErr_SetString(PyExc_TypeError, "__dict__ must be set to a dictionary");
            return false;
        }

        PyObject *old = target_instance->in_dict;

        Py_INCREF(value);
        target_instance->in_dict = value;

        Py_DECREF(old);
    } else
#endif
    {
        PyTypeObject *type = Py_TYPE(target);

        if (type->tp_setattro != NULL) {
            int status = (*type->tp_setattro)(target, const_str_plain___dict__, value);

            if (unlikely(status == -1)) {
                return false;
            }
        } else if (type->tp_setattr != NULL) {
            int status = (*type->tp_setattr)(target, (char *)"__dict__", value);

            if (unlikely(status == -1)) {
                return false;
            }
        } else if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
            PyErr_Format(PyExc_TypeError, "'%s' object has no attributes (assign to __dict__)", type->tp_name);

            return false;
        } else {
            PyErr_Format(PyExc_TypeError, "'%s' object has only read-only attributes (assign to __dict__)",
                         type->tp_name);

            return false;
        }
    }

    return true;
}
Beispiel #22
0
bool SET_ATTRIBUTE_CLASS_SLOT(PyObject *target, PyObject *value) {
    CHECK_OBJECT(target);
    CHECK_OBJECT(value);

#if PYTHON_VERSION < 300
    if (likely(PyInstance_Check(target))) {
        PyInstanceObject *target_instance = (PyInstanceObject *)target;

        if (unlikely(!PyClass_Check(value))) {
            PyErr_SetString(PyExc_TypeError, "__class__ must be set to a class");
            return false;
        }

        PyObject *old = (PyObject *)(target_instance->in_class);
        Py_INCREF(value);
        target_instance->in_class = (PyClassObject *)value;
        Py_DECREF(old);
    } else
#endif
    {
        PyTypeObject *type = Py_TYPE(target);

        if (type->tp_setattro != NULL) {
            int status = (*type->tp_setattro)(target, const_str_plain___class__, value);

            if (unlikely(status == -1)) {
                return false;
            }
        } else if (type->tp_setattr != NULL) {
            int status = (*type->tp_setattr)(target, (char *)"__class__", value);

            if (unlikely(status == -1)) {
                return false;
            }
        } else if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
            PyErr_Format(PyExc_TypeError, "'%s' object has no attributes (assign to __class__)", type->tp_name);

            return false;
        } else {
            PyErr_Format(PyExc_TypeError, "'%s' object has only read-only attributes (assign to __class__)",
                         type->tp_name);

            return false;
        }
    }

    return true;
}
Beispiel #23
0
// Call back into Python, passing a Python instance, and get back
// an interface object that wraps the instance.
/*static*/ PRBool 
PyG_Base::AutoWrapPythonInstance(PyObject *ob, const nsIID &iid, nsISupports **ppret)
{
	NS_PRECONDITION(ppret!=NULL, "null pointer when wrapping a Python instance!");
	NS_PRECONDITION(ob && PyInstance_Check(ob), "AutoWrapPythonInstance is expecting an non-NULL instance!");
	PRBool ok = PR_FALSE;
    // XXX - todo - this static object leaks! (but Python on Windows leaks 2000+ objects as it is ;-)
	static PyObject *func = NULL; // fetch this once and remember!
	PyObject *obIID = NULL;
	PyObject *wrap_ret = NULL;
	PyObject *args = NULL;
	if (func==NULL) { // not thread-safe, but nothing bad can happen, except an extra reference leak
		PyObject *mod = PyImport_ImportModule("xpcom.server");
		if (mod)
			func = PyObject_GetAttrString(mod, "WrapObject");
		Py_XDECREF(mod);
		if (func==NULL) goto done;
	}
	// See if the instance has previously been wrapped.
	if (CheckDefaultGateway(ob, iid, ppret)) {
		ok = PR_TRUE; // life is good!
	} else {
		PyErr_Clear();

		obIID = Py_nsIID::PyObjectFromIID(iid);
		if (obIID==NULL) goto done;
		args = Py_BuildValue("OOzi", ob, obIID, NULL, 0);
		if (args==NULL) goto done;
		wrap_ret = PyEval_CallObject(func, args);
		if (wrap_ret==NULL) goto done;
		ok = Py_nsISupports::InterfaceFromPyObject(wrap_ret, iid, ppret, PR_FALSE, PR_FALSE);
#ifdef DEBUG
		if (ok)
		// Check we _now_ have a default gateway
		{
			nsISupports *temp = NULL;
			NS_ABORT_IF_FALSE(CheckDefaultGateway(ob, iid, &temp), "Auto-wrapped object didnt get a default gateway!");
			if (temp) temp->Release();
		}
#endif
	}
done:
//	Py_XDECREF(func); -- func is static for performance reasons.
	Py_XDECREF(obIID);
	Py_XDECREF(wrap_ret);
	Py_XDECREF(args);
	return ok;
}
Beispiel #24
0
static PyObject *
csv_register_dialect(PyObject *module, PyObject *args)
{
        PyObject *name_obj, *dialect_obj;

	if (!PyArg_UnpackTuple(args, "", 2, 2, &name_obj, &dialect_obj))
                return NULL;
        if (!PyString_Check(name_obj)
#ifdef Py_USING_UNICODE
&& !PyUnicode_Check(name_obj)
#endif
) {
                PyErr_SetString(PyExc_TypeError, 
                                "dialect name must be a string or unicode");
                return NULL;
        }
        Py_INCREF(dialect_obj);
        /* A class rather than an instance? Instanciate */
        if (PyObject_TypeCheck(dialect_obj, &PyClass_Type)) {
                PyObject * new_dia;
                new_dia = PyObject_CallFunction(dialect_obj, "");
                Py_DECREF(dialect_obj);
                if (new_dia == NULL)
                        return NULL;
                dialect_obj = new_dia;
        }
        /* Make sure we finally have an instance */
        if (!PyInstance_Check(dialect_obj)) {
                PyErr_SetString(PyExc_TypeError, "dialect must be an instance");
                Py_DECREF(dialect_obj);
                return NULL;
        }
        if (PyObject_SetAttrString(dialect_obj, "_name", name_obj) < 0) {
                Py_DECREF(dialect_obj);
                return NULL;
        }
        if (PyDict_SetItem(dialects, name_obj, dialect_obj) < 0) {
                Py_DECREF(dialect_obj);
                return NULL;
        }
        Py_DECREF(dialect_obj);
        Py_INCREF(Py_None);
        return Py_None;
}
Beispiel #25
0
/* Return:
   NULL for exception;
   some object not equal to NotImplemented if it is implemented
     (this latter object may not be a Boolean).
*/
PyObject *
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
{
	PyObject *res;

	assert(Py_LT <= op && op <= Py_GE);
	if (Py_EnterRecursiveCall(" in cmp"))
		return NULL;

	/* If the types are equal, and not old-style instances, try to
	   get out cheap (don't bother with coercions etc.). */
	if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
		cmpfunc fcmp;
		richcmpfunc frich = RICHCOMPARE(v->ob_type);
		/* If the type has richcmp, try it first.  try_rich_compare
		   tries it two-sided, which is not needed since we've a
		   single type only. */
		if (frich != NULL) {
			res = (*frich)(v, w, op);
			if (res != Py_NotImplemented)
				goto Done;
			Py_DECREF(res);
		}
		/* No richcmp, or this particular richmp not implemented.
		   Try 3-way cmp. */
		fcmp = v->ob_type->tp_compare;
		if (fcmp != NULL) {
			int c = (*fcmp)(v, w);
			c = adjust_tp_compare(c);
			if (c == -2) {
				res = NULL;
				goto Done;
			}
			res = convert_3way_to_object(op, c);
			goto Done;
		}
	}

	/* Fast path not taken, or couldn't deliver a useful result. */
	res = do_richcmp(v, w, op);
Done:
	Py_LeaveRecursiveCall();
	return res;
}
Beispiel #26
0
PyObject *
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
{
	PyObject *res;
	PyObject *v1, *z1, *w2, *z2;
	PyObject * (*f)(PyObject *, PyObject *, PyObject *);

	if (z == Py_None)
		return do_pow(v, w);
	/* XXX The ternary version doesn't do class instance coercions */
	if (PyInstance_Check(v))
		return v->ob_type->tp_as_number->nb_power(v, w, z);
	if (v->ob_type->tp_as_number == NULL ||
	    z->ob_type->tp_as_number == NULL ||
	    w->ob_type->tp_as_number == NULL) {
		return type_error("pow(x, y, z) requires numeric arguments");
	}
	if (PyNumber_Coerce(&v, &w) != 0)
		return NULL;
	res = NULL;
	v1 = v;
	z1 = z;
	if (PyNumber_Coerce(&v1, &z1) != 0)
		goto error2;
	w2 = w;
	z2 = z1;
 	if (PyNumber_Coerce(&w2, &z2) != 0)
		goto error1;
	if ((f = v1->ob_type->tp_as_number->nb_power) != NULL)
		res = (*f)(v1, w2, z2);
	else
		res = type_error(
			"pow(x, y, z) not defined for these operands");
	Py_DECREF(w2);
	Py_DECREF(z2);
  error1:
	Py_DECREF(v1);
	Py_DECREF(z1);
  error2:
	Py_DECREF(v);
	Py_DECREF(w);
	return res;
}
Beispiel #27
0
size_t _PySys_GetSizeOf(PyObject* o) {
    static PyObject* str__sizeof__ = NULL;
    PyObject* res = NULL;
    Py_ssize_t size;

    /* Make sure the type is initialized. float gets initialized late */
    if (PyType_Ready(Py_TYPE(o)) < 0)
        return (size_t)-1;

    /* Instance of old-style class */
    if (PyInstance_Check(o))
        size = PyInstance_Type.tp_basicsize;
    /* all other objects */
    else {
        PyObject* method = _PyObject_LookupSpecial(o, "__sizeof__", &str__sizeof__);
        if (method == NULL) {
            if (!PyErr_Occurred())
                PyErr_Format(PyExc_TypeError, "Type %.100s doesn't define __sizeof__", Py_TYPE(o)->tp_name);
        } else {
            res = PyObject_CallFunctionObjArgs(method, NULL);
            Py_DECREF(method);
        }

        if (res == NULL)
            return (size_t)-1;

        size = (size_t)PyInt_AsSsize_t(res);
        Py_DECREF(res);
        if (size == -1 && PyErr_Occurred())
            return (size_t)-1;
    }

    if (size < 0) {
        PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
        return (size_t)-1;
    }

    /* add gc_head size */
    if (PyObject_IS_GC(o))
        return ((size_t)size) + sizeof(PyGC_Head);
    return (size_t)size;
}
Beispiel #28
0
static int request_setattr(requestobject *self, char *name, PyObject *value)
{
    if (value == NULL) {
	PyErr_SetString(PyExc_AttributeError,
			"can't delete request attributes");
	return -1;
    }
    else if (strcmp(name, "content_type") == 0) {
	self->request_rec->content_type = 
	    ap_pstrdup(self->request_rec->pool, PyString_AsString(value));
	self->content_type_set = 1;
	return 0;
    }
    else if (strcmp(name, "filename") == 0) {
	self->request_rec->filename =
	    ap_pstrdup(self->request_rec->pool, PyString_AsString(value));
	return 0;
    }
    else if (strcmp(name, "hstack") == 0) {
	self->hstack = ap_pstrdup(self->request_rec->pool, PyString_AsString(value));
	return 0;
    }
    else if (strcmp(name, "_Request") == 0) {
	/* it's ok to assign None */
	if (value == Py_None) {
	    Py_XDECREF(self->Request);
	    self->Request = NULL;
	    return 0;
	}
	/* but anything else has to be an instance */
	if (! PyInstance_Check(value)) {
	    PyErr_SetString(PyExc_AttributeError,
			    "special attribute _Request must be an instance");
	    return -1;
	}
	Py_INCREF(value);
	self->Request = value;
	return 0;
    }
    else
	return PyMember_Set((char *)self->request_rec, request_memberlist, name, value);
}
Beispiel #29
0
int
PyCallable_Check(PyObject *x)
{
	if (x == NULL)
		return 0;
	if (PyInstance_Check(x)) {
		PyObject *call = PyObject_GetAttrString(x, "__call__");
		if (call == NULL) {
			PyErr_Clear();
			return 0;
		}
		/* Could test recursively but don't, for fear of endless
		   recursion if some joker sets self.__call__ = self */
		Py_DECREF(call);
		return 1;
	}
	else {
		return x->ob_type->tp_call != NULL;
	}
}
Beispiel #30
0
/* Do a 3-way comparison, by hook or by crook.  Return:
   -2 for an exception;
   -1 if v <  w;
    0 if v == w;
    1 if v >  w;
   If the object implements a tp_compare function, it returns
   whatever this function returns (whether with an exception or not).
*/
static int
do_cmp(PyObject *v, PyObject *w)
{
	int c;
	cmpfunc f;

	if (v->ob_type == w->ob_type
	    && (f = v->ob_type->tp_compare) != NULL) {
		c = (*f)(v, w);
		if (c != 2 || !PyInstance_Check(v))
			return c;
	}
	c = try_rich_to_3way_compare(v, w);
	if (c < 2)
		return c;
	c = try_3way_compare(v, w);
	if (c < 2)
		return c;
	return default_3way_compare(v, w);
}