cinap_lenrekadd hg and python4bb9e2215 years agoHistory
2139 lines · 49.8 KB · C
RawDownload
 /* Generic object operations; and implementation of None (NoObject) */ #include "Python.h" #ifdef __cplusplusextern "C" {#endif #ifdef Py_REF_DEBUGPy_ssize_t _Py_RefTotal; Py_ssize_t_Py_GetRefTotal(void){	PyObject *o;	Py_ssize_t total = _Py_RefTotal;        /* ignore the references to the dummy object of the dicts and sets           because they are not reliable and not useful (now that the           hash table code is well-tested) */	o = _PyDict_Dummy();	if (o != NULL)		total -= o->ob_refcnt;	o = _PySet_Dummy();	if (o != NULL)		total -= o->ob_refcnt;	return total;}#endif /* Py_REF_DEBUG */ int Py_DivisionWarningFlag; /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.   These are used by the individual routines for object creation.   Do not call them otherwise, they do not initialize the object! */ #ifdef Py_TRACE_REFS/* Head of circular doubly-linked list of all objects.  These are linked * together via the _ob_prev and _ob_next members of a PyObject, which * exist only in a Py_TRACE_REFS build. */static PyObject refchain = {&refchain, &refchain}; /* Insert op at the front of the list of all objects.  If force is true, * op is added even if _ob_prev and _ob_next are non-NULL already.  If * force is false amd _ob_prev or _ob_next are non-NULL, do nothing. * force should be true if and only if op points to freshly allocated, * uninitialized memory, or you've unlinked op from the list and are * relinking it into the front. * Note that objects are normally added to the list via _Py_NewReference, * which is called by PyObject_Init.  Not all objects are initialized that * way, though; exceptions include statically allocated type objects, and * statically allocated singletons (like Py_True and Py_None). */void_Py_AddToAllObjects(PyObject *op, int force){#ifdef  Py_DEBUG	if (!force) {		/* If it's initialized memory, op must be in or out of		 * the list unambiguously.		 */		assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));	}#endif	if (force || op->_ob_prev == NULL) {		op->_ob_next = refchain._ob_next;		op->_ob_prev = &refchain;		refchain._ob_next->_ob_prev = op;		refchain._ob_next = op;	}}#endif	/* Py_TRACE_REFS */ #ifdef COUNT_ALLOCSstatic PyTypeObject *type_list;/* All types are added to type_list, at least when   they get one object created. That makes them   immortal, which unfortunately contributes to   garbage itself. If unlist_types_without_objects   is set, they will be removed from the type_list   once the last object is deallocated. */int unlist_types_without_objects;extern int tuple_zero_allocs, fast_tuple_allocs;extern int quick_int_allocs, quick_neg_int_allocs;extern int null_strings, one_strings;voiddump_counts(FILE* f){	PyTypeObject *tp; 	for (tp = type_list; tp; tp = tp->tp_next)		fprintf(f, "%s alloc'd: %d, freed: %d, max in use: %d\n",			tp->tp_name, tp->tp_allocs, tp->tp_frees,			tp->tp_maxalloc);	fprintf(f, "fast tuple allocs: %d, empty: %d\n",		fast_tuple_allocs, tuple_zero_allocs);	fprintf(f, "fast int allocs: pos: %d, neg: %d\n",		quick_int_allocs, quick_neg_int_allocs);	fprintf(f, "null strings: %d, 1-strings: %d\n",		null_strings, one_strings);} PyObject *get_counts(void){	PyTypeObject *tp;	PyObject *result;	PyObject *v; 	result = PyList_New(0);	if (result == NULL)		return NULL;	for (tp = type_list; tp; tp = tp->tp_next) {		v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,				  tp->tp_frees, tp->tp_maxalloc);		if (v == NULL) {			Py_DECREF(result);			return NULL;		}		if (PyList_Append(result, v) < 0) {			Py_DECREF(v);			Py_DECREF(result);			return NULL;		}		Py_DECREF(v);	}	return result;} voidinc_count(PyTypeObject *tp){	if (tp->tp_next == NULL && tp->tp_prev == NULL) {		/* first time; insert in linked list */		if (tp->tp_next != NULL) /* sanity check */			Py_FatalError("XXX inc_count sanity check");		if (type_list)			type_list->tp_prev = tp;		tp->tp_next = type_list;		/* Note that as of Python 2.2, heap-allocated type objects		 * can go away, but this code requires that they stay alive		 * until program exit.  That's why we're careful with		 * refcounts here.  type_list gets a new reference to tp,		 * while ownership of the reference type_list used to hold		 * (if any) was transferred to tp->tp_next in the line above.		 * tp is thus effectively immortal after this.		 */		Py_INCREF(tp);		type_list = tp;#ifdef Py_TRACE_REFS		/* Also insert in the doubly-linked list of all objects,		 * if not already there.		 */		_Py_AddToAllObjects((PyObject *)tp, 0);#endif	}	tp->tp_allocs++;	if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)		tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;} void dec_count(PyTypeObject *tp){	tp->tp_frees++;	if (unlist_types_without_objects &&	    tp->tp_allocs == tp->tp_frees) {		/* unlink the type from type_list */		if (tp->tp_prev)			tp->tp_prev->tp_next = tp->tp_next;		else			type_list = tp->tp_next;		if (tp->tp_next)			tp->tp_next->tp_prev = tp->tp_prev;		tp->tp_next = tp->tp_prev = NULL;		Py_DECREF(tp);	}} #endif #ifdef Py_REF_DEBUG/* Log a fatal error; doesn't return. */void_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op){	char buf[300]; 	PyOS_snprintf(buf, sizeof(buf),		      "%s:%i object at %p has negative ref count "		      "%" PY_FORMAT_SIZE_T "d",		      fname, lineno, op, op->ob_refcnt);	Py_FatalError(buf);} #endif /* Py_REF_DEBUG */ voidPy_IncRef(PyObject *o){    Py_XINCREF(o);} voidPy_DecRef(PyObject *o){    Py_XDECREF(o);} PyObject *PyObject_Init(PyObject *op, PyTypeObject *tp){	if (op == NULL)		return PyErr_NoMemory();	/* Any changes should be reflected in PyObject_INIT (objimpl.h) */	op->ob_type = tp;	_Py_NewReference(op);	return op;} PyVarObject *PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size){	if (op == NULL)		return (PyVarObject *) PyErr_NoMemory();	/* Any changes should be reflected in PyObject_INIT_VAR */	op->ob_size = size;	op->ob_type = tp;	_Py_NewReference((PyObject *)op);	return op;} PyObject *_PyObject_New(PyTypeObject *tp){	PyObject *op;	op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));	if (op == NULL)		return PyErr_NoMemory();	return PyObject_INIT(op, tp);} PyVarObject *_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems){	PyVarObject *op;	const size_t size = _PyObject_VAR_SIZE(tp, nitems);	op = (PyVarObject *) PyObject_MALLOC(size);	if (op == NULL)		return (PyVarObject *)PyErr_NoMemory();	return PyObject_INIT_VAR(op, tp, nitems);} /* for binary compatibility with 2.2 */#undef _PyObject_Delvoid_PyObject_Del(PyObject *op){	PyObject_FREE(op);} /* Implementation of PyObject_Print with recursion checking */static intinternal_print(PyObject *op, FILE *fp, int flags, int nesting){	int ret = 0;	if (nesting > 10) {		PyErr_SetString(PyExc_RuntimeError, "print recursion");		return -1;	}	if (PyErr_CheckSignals())		return -1;#ifdef USE_STACKCHECK	if (PyOS_CheckStack()) {		PyErr_SetString(PyExc_MemoryError, "stack overflow");		return -1;	}#endif	clearerr(fp); /* Clear any previous error condition */	if (op == NULL) {		fprintf(fp, "<nil>");	}	else {		if (op->ob_refcnt <= 0)			/* XXX(twouters) cast refcount to long until %zd is			   universally available */			fprintf(fp, "<refcnt %ld at %p>",				(long)op->ob_refcnt, op);		else if (op->ob_type->tp_print == NULL) {			PyObject *s;			if (flags & Py_PRINT_RAW)				s = PyObject_Str(op);			else				s = PyObject_Repr(op);			if (s == NULL)				ret = -1;			else {				ret = internal_print(s, fp, Py_PRINT_RAW,						     nesting+1);			}			Py_XDECREF(s);		}		else			ret = (*op->ob_type->tp_print)(op, fp, flags);	}	if (ret == 0) {		if (ferror(fp)) {			PyErr_SetFromErrno(PyExc_IOError);			clearerr(fp);			ret = -1;		}	}	return ret;} intPyObject_Print(PyObject *op, FILE *fp, int flags){	return internal_print(op, fp, flags, 0);}  /* For debugging convenience.  See Misc/gdbinit for some useful gdb hooks */void _PyObject_Dump(PyObject* op){	if (op == NULL)		fprintf(stderr, "NULL\n");	else {		fprintf(stderr, "object  : ");		(void)PyObject_Print(op, stderr, 0);		/* XXX(twouters) cast refcount to long until %zd is		   universally available */		fprintf(stderr, "\n"			"type    : %s\n"			"refcount: %ld\n"			"address : %p\n",			op->ob_type==NULL ? "NULL" : op->ob_type->tp_name,			(long)op->ob_refcnt,			op);	}} PyObject *PyObject_Repr(PyObject *v){	if (PyErr_CheckSignals())		return NULL;#ifdef USE_STACKCHECK	if (PyOS_CheckStack()) {		PyErr_SetString(PyExc_MemoryError, "stack overflow");		return NULL;	}#endif	if (v == NULL)		return PyString_FromString("<NULL>");	else if (v->ob_type->tp_repr == NULL)		return PyString_FromFormat("<%s object at %p>",					   v->ob_type->tp_name, v);	else {		PyObject *res;		res = (*v->ob_type->tp_repr)(v);		if (res == NULL)			return NULL;#ifdef Py_USING_UNICODE		if (PyUnicode_Check(res)) {			PyObject* str;			str = PyUnicode_AsEncodedString(res, NULL, NULL);			Py_DECREF(res);			if (str)				res = str;			else				return NULL;		}#endif		if (!PyString_Check(res)) {			PyErr_Format(PyExc_TypeError,				     "__repr__ returned non-string (type %.200s)",				     res->ob_type->tp_name);			Py_DECREF(res);			return NULL;		}		return res;	}} PyObject *_PyObject_Str(PyObject *v){	PyObject *res;	int type_ok;	if (v == NULL)		return PyString_FromString("<NULL>");	if (PyString_CheckExact(v)) {		Py_INCREF(v);		return v;	}#ifdef Py_USING_UNICODE	if (PyUnicode_CheckExact(v)) {		Py_INCREF(v);		return v;	}#endif	if (v->ob_type->tp_str == NULL)		return PyObject_Repr(v); 	res = (*v->ob_type->tp_str)(v);	if (res == NULL)		return NULL;	type_ok = PyString_Check(res);#ifdef Py_USING_UNICODE	type_ok = type_ok || PyUnicode_Check(res);#endif	if (!type_ok) {		PyErr_Format(PyExc_TypeError,			     "__str__ returned non-string (type %.200s)",			     res->ob_type->tp_name);		Py_DECREF(res);		return NULL;	}	return res;} PyObject *PyObject_Str(PyObject *v){	PyObject *res = _PyObject_Str(v);	if (res == NULL)		return NULL;#ifdef Py_USING_UNICODE	if (PyUnicode_Check(res)) {		PyObject* str;		str = PyUnicode_AsEncodedString(res, NULL, NULL);		Py_DECREF(res);		if (str)			res = str;		else		    	return NULL;	}#endif	assert(PyString_Check(res));	return res;} #ifdef Py_USING_UNICODEPyObject *PyObject_Unicode(PyObject *v){	PyObject *res;	PyObject *func;	PyObject *str;	static PyObject *unicodestr; 	if (v == NULL) {		res = PyString_FromString("<NULL>");		if (res == NULL)			return NULL;		str = PyUnicode_FromEncodedObject(res, NULL, "strict");		Py_DECREF(res);		return str;	} else if (PyUnicode_CheckExact(v)) {		Py_INCREF(v);		return v;	}	/* XXX As soon as we have a tp_unicode slot, we should	   check this before trying the __unicode__	   method. */	if (unicodestr == NULL) {		unicodestr= PyString_InternFromString("__unicode__");		if (unicodestr == NULL)			return NULL;	}	func = PyObject_GetAttr(v, unicodestr);	if (func != NULL) {		res = PyEval_CallObject(func, (PyObject *)NULL);		Py_DECREF(func);	}	else {		PyErr_Clear();		if (PyUnicode_Check(v)) {			/* For a Unicode subtype that's didn't overwrite __unicode__,			   return a true Unicode object with the same data. */			return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),			                             PyUnicode_GET_SIZE(v));		}		if (PyString_CheckExact(v)) {			Py_INCREF(v);			res = v;		}		else {			if (v->ob_type->tp_str != NULL)				res = (*v->ob_type->tp_str)(v);			else				res = PyObject_Repr(v);		}	}	if (res == NULL)		return NULL;	if (!PyUnicode_Check(res)) {		str = PyUnicode_FromEncodedObject(res, NULL, "strict");		Py_DECREF(res);

Lines 1–500 of 2139.