예제 #1
0
    inline bool matches( PyObject *exception ) const
    {
#if PYTHON_VERSION >= 300
        if ( PyTuple_Check( exception ))
        {
            Py_ssize_t length = PyTuple_Size( exception );

            for ( Py_ssize_t i = 0; i < length; i += 1 )
            {
                PyObject *element = PyTuple_GET_ITEM( exception, i );

                if (unlikely( !PyExceptionClass_Check( element ) ))
                {
                    PyErr_Format( PyExc_TypeError, "catching classes that do not inherit from BaseException is not allowed" );
                    throw PythonException();
                }
            }
        }
        else if (unlikely( !PyExceptionClass_Check( exception ) ))
        {
            PyErr_Format( PyExc_TypeError, "catching classes that do not inherit from BaseException is not allowed" );
            throw PythonException();
        }
#endif

        return
            PyErr_GivenExceptionMatches( this->exception_type, exception ) ||
            PyErr_GivenExceptionMatches( this->exception_value, exception );
    }
예제 #2
0
/**
 * @param code A lump of python code
 * @return True if the code forms a complete statment
 */
bool PythonScript::compilesToCompleteStatement(const QString & code) const
{
    bool result(false);
    GlobalInterpreterLock gil;
    PyObject *compiledCode = Py_CompileString(code.toAscii(), "", Py_file_input);
    if( PyObject *exception = PyErr_Occurred() )
    {
        // Certain exceptions still mean the code is complete
        if(PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_OverflowError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_ValueError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_TypeError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_MemoryError))
        {
            result = true;
        }
        else
        {
            result = false;
        }
        PyErr_Clear();
    }
    else
    {
        result = true;
    }
    Py_XDECREF(compiledCode);
    return result;
}
예제 #3
0
/*
 * PyArray_IntpFromIndexSequence
 * Returns the number of dimensions or -1 if an error occurred.
 * vals must be large enough to hold maxvals.
 * Opposed to PyArray_IntpFromSequence it uses and returns npy_intp
 * for the number of values.
 */
NPY_NO_EXPORT npy_intp
PyArray_IntpFromIndexSequence(PyObject *seq, npy_intp *vals, npy_intp maxvals)
{
    Py_ssize_t nd;
    npy_intp i;
    PyObject *op, *err;

    /*
     * Check to see if sequence is a single integer first.
     * or, can be made into one
     */
    nd = PySequence_Length(seq);
    if (nd == -1) {
        if (PyErr_Occurred()) {
            PyErr_Clear();
        }

        vals[0] = PyArray_PyIntAsIntp(seq);
        if(vals[0] == -1) {
            err = PyErr_Occurred();
            if (err &&
                    PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
                PyErr_SetString(PyExc_ValueError,
                        "Maximum allowed dimension exceeded");
            }
            if(err != NULL) {
                return -1;
            }
        }
        nd = 1;
    }
    else {
        for (i = 0; i < PyArray_MIN(nd,maxvals); i++) {
            op = PySequence_GetItem(seq, i);
            if (op == NULL) {
                return -1;
            }

            vals[i] = PyArray_PyIntAsIntp(op);
            Py_DECREF(op);
            if(vals[i] == -1) {
                err = PyErr_Occurred();
                if (err &&
                        PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) {
                    PyErr_SetString(PyExc_ValueError,
                            "Maximum allowed dimension exceeded");
                }
                if(err != NULL) {
                    return -1;
                }
            }
        }
    }
    return nd;
}
예제 #4
0
bool
rpcError_Extract(PyObject *error, int *errorCode, char **errorString)
{
	PyObject	*pyErrorCode,
			*pyErrorString;

	assert(PyErr_GivenExceptionMatches(error, rpcError));
	pyErrorCode = PyObject_GetAttrString(error, "errorCode");
	if (errorCode && PyInt_Check(pyErrorCode))
		*errorCode = (int)PyInt_AS_LONG(pyErrorCode);
	else {
		fprintf(rpcLogger, "invalid error code... deerror to -1\n");
		*errorCode = -1;
	}
	pyErrorString = PyObject_GetAttrString(error, "errorString");
	if (errorString && PyString_Check(pyErrorString)) {
		*errorString = alloc(PyString_GET_SIZE(pyErrorString) + 1);
		if (*errorString == NULL)
			return false;
		strcpy(*errorString, PyString_AS_STRING(pyErrorString));
	} else {
		fprintf(rpcLogger, "invalid error string... deerror to 'unknown error'\n");
		*errorString = alloc(strlen("unknown error") + 1);
		if (*errorString == NULL)
			return false;
		strcpy(*errorString, "unknown error");
	}
	return true;
}
예제 #5
0
파일: event.cpp 프로젝트: epaulson/htcondor
boost::python::object
EventIterator::next_nostop()
{
    boost::python::object stopIteration = py_import("exceptions").attr("StopIteration");
    boost::python::object result = boost::python::object();
    try
    {
        result = boost::python::object(next());
    }
    catch (const boost::python::error_already_set &)
    {
        PyObject *e, *v, *t;
        PyErr_Fetch(&e, &v, &t);
        if (!e) {throw;}
        if (PyErr_GivenExceptionMatches(stopIteration.ptr(), e))
        {
            boost::python::object pyE(boost::python::handle<>(boost::python::allow_null(e)));
            if (v) {boost::python::object pyV(boost::python::handle<>(boost::python::allow_null(v)));}
            if (t) {boost::python::object pyT(boost::python::handle<>(boost::python::allow_null(t)));}
        }
        else
        {
            PyErr_Restore(e, v, t);
            throw;
        }
    }
    return result;
}
예제 #6
0
PyObject *ERROR_GET_STOP_ITERATION_VALUE()
{
    assert ( PyErr_ExceptionMatches( PyExc_StopIteration ));

    PyObject *et, *ev, *tb;
    PyErr_Fetch( &et, &ev, &tb );

    Py_XDECREF(et);
    Py_XDECREF(tb);

    PyObject *value = NULL;

    if ( ev )
    {
        if ( PyErr_GivenExceptionMatches( ev, PyExc_StopIteration ) )
        {
            value = ((PyStopIterationObject *)ev)->value;
            Py_DECREF( ev );
        }
        else
        {
            value = ev;
        }
    }

    if ( value == NULL )
    {
        value = INCREASE_REFCOUNT( Py_None );
    }

    return value;
}
예제 #7
0
PyObject *ERROR_GET_STOP_ITERATION_VALUE()
{
    assert( PyErr_ExceptionMatches( PyExc_StopIteration ) );

    PyObject *exception_type, *exception_value, *exception_tb;
    PyErr_Fetch( &exception_type, &exception_value, &exception_tb );

    Py_DECREF( exception_type );
    Py_XDECREF( exception_tb );

    PyObject *value = NULL;

    if ( exception_value )
    {
        if ( PyErr_GivenExceptionMatches( exception_value, PyExc_StopIteration ) )
        {
            value = ((PyStopIterationObject *)exception_value)->value;
            Py_XINCREF( value );
            Py_DECREF( exception_value );
        }
        else
        {
            value = exception_value;
        }
    }

    if ( value == NULL )
    {
        value = INCREASE_REFCOUNT( Py_None );
    }

    return value;
}
예제 #8
0
/**
 * pygi_gerror_exception_check:
 * @error: a standard GLib GError ** output parameter
 *
 * Checks to see if a GError exception has been raised, and if so
 * translates the python exception to a standard GLib GError.  If the
 * raised exception is not a GError then PyErr_Print() is called.
 *
 * Returns: 0 if no exception has been raised, -1 if it is a
 * valid glib.GError, -2 otherwise.
 */
gboolean
pygi_gerror_exception_check (GError **error)
{
    int res = -1;
    PyObject *type, *value, *traceback;
    PyErr_Fetch(&type, &value, &traceback);
    if (type == NULL)
        return 0;
    PyErr_NormalizeException(&type, &value, &traceback);
    if (value == NULL) {
        PyErr_Restore(type, value, traceback);
        PyErr_Print();
        return -2;
    }
    if (!value ||
        !PyErr_GivenExceptionMatches(type,
                                     (PyObject *) PyGError)) {
        PyErr_Restore(type, value, traceback);
        PyErr_Print();
        return -2;
    }
    Py_DECREF(type);
    Py_XDECREF(traceback);

    if (!pygi_error_marshal_from_py (value, error)) {
        PyErr_Print();
        res = -2;
    }

    Py_DECREF(value);
    return res;

}
예제 #9
0
파일: errors.c 프로젝트: DinoV/cpython
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)) {
        Py_ssize_t 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 (PyExceptionInstance_Check(err))
        err = PyExceptionInstance_Class(err);

    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
        return PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
    }

    return err == exc;
}
예제 #10
0
// This is for the actual comparison operation that is being done in the
// node tree, no other code should use it. TODO: Then it's probably not
// properly located here, and it could still in-line the code of
// "PyErr_GivenExceptionMatches" to save on Python3 doing two tuple checks
// and iterations.
NUITKA_MAY_BE_UNUSED static inline int EXCEPTION_MATCH_BOOL( PyObject *exception_value, PyObject *exception_checked )
{
    CHECK_OBJECT( exception_value );
    CHECK_OBJECT( exception_checked );

#if PYTHON_VERSION >= 300
    if ( PyTuple_Check( exception_checked ))
    {
        Py_ssize_t length = PyTuple_Size( exception_checked );

        for ( Py_ssize_t i = 0; i < length; i += 1 )
        {
            PyObject *element = PyTuple_GET_ITEM( exception_checked, i );

            if (unlikely( !PyExceptionClass_Check( element ) ))
            {
                PyErr_Format( PyExc_TypeError, "catching classes that do not inherit from BaseException is not allowed" );
                return -1;
            }
        }
    }
    else if (unlikely( !PyExceptionClass_Check( exception_checked ) ))
    {
        PyErr_Format( PyExc_TypeError, "catching classes that do not inherit from BaseException is not allowed" );
        return -1;
    }
#endif

    return PyErr_GivenExceptionMatches( exception_value, exception_checked );
}
예제 #11
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)) {
        Py_ssize_t 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 (PyExceptionInstance_Check(err))
        err = PyExceptionInstance_Class(err);

    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
        /* problems here!?  not sure PyObject_IsSubclass expects to
           be called with an exception pending... */
        return PyObject_IsSubclass(err, exc);
    }

    return err == exc;
}
예제 #12
0
void python_script_error_jump(const char *filepath, int *lineno, int *offset)
{
  PyObject *exception, *value;
  PyTracebackObject *tb;

  *lineno = -1;
  *offset = 0;

  PyErr_Fetch(&exception, &value, (PyObject **)&tb);

  if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
    /* no traceback available when SyntaxError.
     * python has no api's to this. reference parse_syntax_error() from pythonrun.c */
    PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
    PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */

    if (value) { /* should always be true */
      PyObject *message;
      PyObject *filename_py, *text_py;

      if (parse_syntax_error(value, &message, &filename_py, lineno, offset, &text_py)) {
        const char *filename = _PyUnicode_AsString(filename_py);
        /* python adds a '/', prefix, so check for both */
        if ((BLI_path_cmp(filename, filepath) == 0) ||
            ((filename[0] == '\\' || filename[0] == '/') &&
             BLI_path_cmp(filename + 1, filepath) == 0)) {
          /* good */
        }
        else {
          *lineno = -1;
        }
      }
      else {
        *lineno = -1;
      }
    }
  }
  else {
    PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
    PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */
    PyErr_Print();

    for (tb = (PyTracebackObject *)PySys_GetObject("last_traceback");
         tb && (PyObject *)tb != Py_None;
         tb = tb->tb_next) {
      PyObject *coerce;
      const char *tb_filepath = traceback_filepath(tb, &coerce);
      const int match = ((BLI_path_cmp(tb_filepath, filepath) == 0) ||
                         ((tb_filepath[0] == '\\' || tb_filepath[0] == '/') &&
                          BLI_path_cmp(tb_filepath + 1, filepath) == 0));
      Py_DECREF(coerce);

      if (match) {
        *lineno = tb->tb_lineno;
        /* used to break here, but better find the inner most line */
      }
    }
  }
}
예제 #13
0
std::string formatPythonException( bool withStacktrace, int *lineNumber )
{
	PyObject *exceptionPyObject, *valuePyObject, *tracebackPyObject;
	PyErr_Fetch( &exceptionPyObject, &valuePyObject, &tracebackPyObject );

	if( !exceptionPyObject )
	{
		throw IECore::Exception( "No Python exception set" );
	}

	PyErr_NormalizeException( &exceptionPyObject, &valuePyObject, &tracebackPyObject );

	object exception( ( handle<>( exceptionPyObject ) ) );

	// valuePyObject and tracebackPyObject may be NULL.
	object value;
	if( valuePyObject )
	{
		value = object( handle<>( valuePyObject ) );
	}

	object traceback;
	if( tracebackPyObject )
	{
		traceback = object( handle<>( tracebackPyObject ) );
	}

	if( lineNumber )
	{
		if( PyErr_GivenExceptionMatches( value.ptr(), PyExc_SyntaxError ) )
		{
			*lineNumber = extract<int>( value.attr( "lineno" ) );
		}
		else if( traceback )
		{
			*lineNumber = extract<int>( traceback.attr( "tb_lineno" ) );
		}
	}

	object tracebackModule( import( "traceback" ) );

	object formattedList;
	if( withStacktrace )
	{
		formattedList = tracebackModule.attr( "format_exception" )( exception, value, traceback );
	}
	else
	{
		formattedList = tracebackModule.attr( "format_exception_only" )( exception, value );
	}

	object formatted = str( "" ).join( formattedList );
	std::string s = extract<std::string>( formatted );

	return s;
}
예제 #14
0
static PyObject *__Pyx_Generator_Throw(PyObject *self, PyObject *args) {
    __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self;
    PyObject *typ;
    PyObject *tb = NULL;
    PyObject *val = NULL;
    PyObject *yf = gen->yieldfrom;

    if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb))
        return NULL;

    if (unlikely(__Pyx_Generator_CheckRunning(gen)))
        return NULL;

    if (yf) {
        PyObject *ret;
        Py_INCREF(yf);
#if PY_VERSION_HEX >= 0x02050000
        if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit)) {
            int err = __Pyx_Generator_CloseIter(gen, yf);
            Py_DECREF(yf);
            __Pyx_Generator_Undelegate(gen);
            if (err < 0)
                return __Pyx_Generator_SendEx(gen, NULL);
            goto throw_here;
        }
#endif
        gen->is_running = 1;
        if (__Pyx_Generator_CheckExact(yf)) {
            ret = __Pyx_Generator_Throw(yf, args);
        } else {
            PyObject *meth = PyObject_GetAttrString(yf, "throw");
            if (unlikely(!meth)) {
                Py_DECREF(yf);
                if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
                    gen->is_running = 0;
                    return NULL;
                }
                PyErr_Clear();
                __Pyx_Generator_Undelegate(gen);
                gen->is_running = 0;
                goto throw_here;
            }
            ret = PyObject_CallObject(meth, args);
            Py_DECREF(meth);
        }
        gen->is_running = 0;
        Py_DECREF(yf);
        if (!ret) {
            ret = __Pyx_Generator_FinishDelegation(gen);
        }
        return ret;
    }
throw_here:
    __Pyx_Raise(typ, val, tb, NULL);
    return __Pyx_Generator_SendEx(gen, NULL);
}
예제 #15
0
static PyObject *__Pyx_Generator_Close(PyObject *self) {
    __pyx_GeneratorObject *gen = (__pyx_GeneratorObject *) self;
    PyObject *retval, *raised_exception;
    PyObject *yf = gen->yieldfrom;
    int err = 0;

    if (unlikely(__Pyx_Generator_CheckRunning(gen)))
        return NULL;

    if (yf) {
        Py_INCREF(yf);
        err = __Pyx_Generator_CloseIter(gen, yf);
        __Pyx_Generator_Undelegate(gen);
        Py_DECREF(yf);
    }
    if (err == 0)
#if PY_VERSION_HEX < 0x02050000
        PyErr_SetNone(PyExc_StopIteration);
#else
        PyErr_SetNone(PyExc_GeneratorExit);
#endif
    retval = __Pyx_Generator_SendEx(gen, NULL);
    if (retval) {
        Py_DECREF(retval);
        PyErr_SetString(PyExc_RuntimeError,
                        "generator ignored GeneratorExit");
        return NULL;
    }
    raised_exception = PyErr_Occurred();
    if (!raised_exception
        || raised_exception == PyExc_StopIteration
#if PY_VERSION_HEX >= 0x02050000
        || raised_exception == PyExc_GeneratorExit
        || PyErr_GivenExceptionMatches(raised_exception, PyExc_GeneratorExit)
#endif
        || PyErr_GivenExceptionMatches(raised_exception, PyExc_StopIteration))
    {
        if (raised_exception) PyErr_Clear();      /* ignore these errors */
        Py_INCREF(Py_None);
        return Py_None;
    }
    return NULL;
}
예제 #16
0
// Is the current exception a "server" exception? - ie, one explicitly
// thrown by Python code to indicate an error.  This is defined as
// any exception whose type is a subclass of com_error (a plain
// com_error probably means an unhandled exception from someone
// calling an interface)
BOOL IsServerErrorCurrent() {
	BOOL rc = FALSE;
	PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
	PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);
	assert(exc_typ); // we should only be called with an exception current.
	if (exc_typ) {
		PyErr_NormalizeException( &exc_typ, &exc_val, &exc_tb);
		// so it must "match" a com_error, but not be *exactly* a COM error.
		rc = PyErr_GivenExceptionMatches(exc_val, PyWinExc_COMError) && exc_typ != PyWinExc_COMError;
	}
	PyErr_Restore(exc_typ, exc_val, exc_tb);
	return rc;
}
QString PythonScripting::errorMsg()
{
  PyObject *exception=0, *value=0, *traceback=0;
  PyTracebackObject *excit=0;
  PyFrameObject *frame;
  char *fname;
  QString msg;
  if (!PyErr_Occurred()) return "";

  PyErr_Fetch(&exception, &value, &traceback);
  PyErr_NormalizeException(&exception, &value, &traceback);
  if(PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
  {
    msg.append(toString(PyObject_GetAttrString(value, "text"), true) + "\n");
    PyObject *offset = PyObject_GetAttrString(value, "offset");
    for (int i=1; i<PyInt_AsLong(offset); i++)
      msg.append(" ");
    msg.append("^\n");
    Py_DECREF(offset);
    msg.append("SyntaxError: ");
    msg.append(toString(PyObject_GetAttrString(value, "msg"), true) + "\n");
    msg.append("at ").append(toString(PyObject_GetAttrString(value, "filename"), true));
    msg.append(":").append(toString(PyObject_GetAttrString(value, "lineno"), true));
    msg.append("\n");
    Py_DECREF(exception);
    Py_DECREF(value);
  } else {
    msg.append(toString(exception,true)).remove("exceptions.").append(": ");
    msg.append(toString(value,true));
    msg.append("\n");
  }

  if (traceback) {
    excit = (PyTracebackObject*)traceback;
    while (excit && (PyObject*)excit != Py_None)
    {
      frame = excit->tb_frame;
      msg.append("at ").append(PyString_AsString(frame->f_code->co_filename));
      msg.append(":").append(QString::number(excit->tb_lineno));
      if (frame->f_code->co_name && *(fname = PyString_AsString(frame->f_code->co_name)) != '?')
	msg.append(" in ").append(fname);
      msg.append("\n");
      excit = excit->tb_next;
    }
    Py_DECREF(traceback);
  }

  return msg;
}
예제 #18
0
void python_script_error_jump(const char *filepath, int *lineno, int *offset)
{
	PyObject *exception, *value;
	PyTracebackObject *tb;

	*lineno= -1;
	*offset= 0;

	PyErr_Fetch(&exception, &value, (PyObject **)&tb);

	if(exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
		/* no traceback available when SyntaxError.
		 * python has no api's to this. reference parse_syntax_error() from pythonrun.c */
		PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
		PyErr_Restore(exception, value, (PyObject *)tb);	/* takes away reference! */

		if(value) { /* should always be true */
			PyObject *message;
			const char *filename, *text;

			if(parse_syntax_error(value, &message, &filename, lineno, offset, &text)) {
				/* python adds a '/', prefix, so check for both */
				if(	(strcmp(filename, filepath) == 0) || 
					((filename[0] == '\\' || filename[0] == '/') && strcmp(filename + 1, filepath) == 0)
				) {
					/* good */
				}
				else {
					*lineno= -1;
				}
			}
			else {
				*lineno= -1;
			}
		}
	}
	else {
		PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
		PyErr_Restore(exception, value, (PyObject *)tb);	/* takes away reference! */
		PyErr_Print();

		for(tb= (PyTracebackObject *)PySys_GetObject("last_traceback"); tb && (PyObject *)tb != Py_None; tb= tb->tb_next) {
			if(strcmp(traceback_filepath(tb), filepath) != 0) {
				*lineno= tb->tb_lineno;
				break;
			}
		}
	}
}
예제 #19
0
파일: _iomodule.c 프로젝트: RDWang/python
Py_off_t
PyNumber_AsOff_t(PyObject *item, PyObject *err)
{
    Py_off_t result;
    PyObject *runerr;
    PyObject *value = PyNumber_Index(item);
    if (value == NULL)
        return -1;

    if (PyInt_Check(value)) {
        /* We assume a long always fits in a Py_off_t... */
        result = (Py_off_t) PyInt_AS_LONG(value);
        goto finish;
    }

    /* We're done if PyLong_AsSsize_t() returns without error. */
    result = PyLong_AsOff_t(value);
    if (result != -1 || !(runerr = PyErr_Occurred()))
        goto finish;

    /* Error handling code -- only manage OverflowError differently */
    if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
        goto finish;

    PyErr_Clear();
    /* If no error-handling desired then the default clipping
       is sufficient.
     */
    if (!err) {
        assert(PyLong_Check(value));
        /* Whether or not it is less than or equal to
           zero is determined by the sign of ob_size
        */
        if (_PyLong_Sign(value) < 0)
            result = PY_OFF_T_MIN;
        else
            result = PY_OFF_T_MAX;
    }
    else {
        /* Otherwise replace the error with caller's error object. */
        PyErr_Format(err,
                     "cannot fit '%.200s' into an offset-sized integer",
                     item->ob_type->tp_name);
    }

 finish:
    Py_DECREF(value);
    return result;
}
예제 #20
0
파일: errors.c 프로젝트: irov/Mengine
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)) {
        Py_ssize_t 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 (PyExceptionInstance_Check(err))
        err = PyExceptionInstance_Class(err);

    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
        int res = 0, reclimit;
        PyObject *exception, *value, *tb;
        PyErr_Fetch(&exception, &value, &tb);
        /* Temporarily bump the recursion limit, so that in the most
           common case PyObject_IsSubclass will not raise a recursion
           error we have to ignore anyway.  Don't do it when the limit
           is already insanely high, to avoid overflow */
        reclimit = Py_GetRecursionLimit();
        if (reclimit < (1 << 30))
            Py_SetRecursionLimit(reclimit + 5);
        res = PyObject_IsSubclass(err, exc);
        Py_SetRecursionLimit(reclimit);
        /* This function must not fail, so print the error here */
        if (res == -1) {
            PyErr_WriteUnraisable(err);
            res = 0;
        }
        PyErr_Restore(exception, value, tb);
        return res;
    }

    return err == exc;
}
예제 #21
0
static PyObject *
pygpgme_context_genkey(PyGpgmeContext *self, PyObject *args)
{
    PyObject *py_pubkey = Py_None, *py_seckey = Py_None;
    const char *parms;
    gpgme_data_t pubkey = NULL, seckey = NULL;
    PyObject *result;
    gpgme_error_t err;

    if (!PyArg_ParseTuple(args, "z|OO", &parms, &py_pubkey, &py_seckey))
        return NULL;

    if (pygpgme_data_new(&pubkey, py_pubkey))
        return NULL;

    if (pygpgme_data_new(&seckey, py_seckey)) {
        gpgme_data_release(pubkey);
        return NULL;
    }

    Py_BEGIN_ALLOW_THREADS;
    err = gpgme_op_genkey(self->ctx, parms, pubkey, seckey);
    Py_END_ALLOW_THREADS;

    gpgme_data_release(seckey);
    gpgme_data_release(pubkey);
    result = pygpgme_genkey_result(self->ctx);

    if (pygpgme_check_error(err)) {
        PyObject *err_type, *err_value, *err_traceback;

        PyErr_Fetch(&err_type, &err_value, &err_traceback);
        PyErr_NormalizeException(&err_type, &err_value, &err_traceback);

        if (!PyErr_GivenExceptionMatches(err_type, pygpgme_error))
            goto end;

        if (result != NULL) {
            PyObject_SetAttrString(err_value, "result", result);
            Py_DECREF(result);
        }
    end:
        PyErr_Restore(err_type, err_value, err_traceback);
        return NULL;
    }

    return (PyObject *) result;
}
예제 #22
0
파일: context.c 프로젝트: Jonnyliu/phoneyc
JSBool
get_prop(JSContext* jscx, JSObject* jsobj, jsval key, jsval* rval)
{
    Context* pycx = NULL;
    PyObject* pykey = NULL;
    PyObject* pyval = NULL;
    JSBool ret = JS_FALSE;

    pycx = (Context*) JS_GetContextPrivate(jscx);
    if(pycx == NULL)
    {
        JS_ReportError(jscx, "Failed to get Python context.");
        goto done;
    }

    // Bail if there's no registered global handler.
    if(pycx->global == NULL)
    {
        ret = JS_TRUE;
        goto done;
    }

    pykey = js2py(pycx, key);
    if(pykey == NULL) goto done;

    if(Context_has_access(pycx, jscx, pycx->global, pykey) <= 0) goto done;

    pyval = PyObject_GetItem(pycx->global, pykey);
    if(pyval == NULL)
    {
        if(PyErr_GivenExceptionMatches(PyErr_Occurred(), PyExc_KeyError))
        {
            PyErr_Clear();
            ret = JS_TRUE;
        }
        goto done;
    }

    *rval = py2js(pycx, pyval);
    if(*rval == JSVAL_VOID) goto done;
    ret = JS_TRUE;

done:
    Py_XDECREF(pykey);
    Py_XDECREF(pyval);
    return ret;
}
예제 #23
0
// Generically fills an EXCEP_INFO.  The scode in the EXCEPINFO
// is the HRESULT as nominated by the user.
void PyCom_ExcepInfoFromPyException(EXCEPINFO *pExcepInfo)
{
	// If the caller did not provide a valid exception info, get out now!
	if (pExcepInfo==NULL) {
		PyErr_Clear(); // must leave Python in a clean state.
		return;
	}
	PyObject *exception, *v, *tb;
	PyErr_Fetch(&exception, &v, &tb);
	if (PyCom_ExcepInfoFromPyObject(v, pExcepInfo, NULL))
	{
		// done.
	}
	else
	{
		memset(pExcepInfo, 0, sizeof(EXCEPINFO));
		// Clear the exception raised by PyCom_ExcepInfoFromPyObject,
		// not the one we are interested in!
		PyErr_Clear();
		// Not a special exception object - do the best we can.
		char *szBaseMessage = "Unexpected Python Error: ";
		char *szException = GetPythonTraceback(exception, v, tb);
		size_t len = strlen(szBaseMessage) + strlen(szException) + 1;
		char *tempBuf = new char[len];
		if (tempBuf) {
			snprintf(tempBuf, len, "%s%s", szBaseMessage, szException);
			pExcepInfo->bstrDescription = PyWin_String_AsBstr(tempBuf);
			delete [] tempBuf;
		} else
			pExcepInfo->bstrDescription = SysAllocString(L"memory error allocating exception buffer!");
		pExcepInfo->bstrSource = SysAllocString(L"Python COM Server Internal Error");

		// Map some well known exceptions to specific HRESULTs
		// Note: v can be NULL. This can happen via PyErr_SetNone().
		//       e.g.: KeyboardInterrupt
		if (PyErr_GivenExceptionMatches(exception, PyExc_MemoryError))
			pExcepInfo->scode = E_OUTOFMEMORY;
		else
			// Any other common Python exceptions we should map?
			pExcepInfo->scode = E_FAIL;
	}
	Py_XDECREF(exception);
	Py_XDECREF(v);
	Py_XDECREF(tb);
	PyErr_Clear();
}
예제 #24
0
파일: atexitmodule.c 프로젝트: 1st1/cpython
static void
atexit_callfuncs(PyObject *module)
{
    PyObject *exc_type = NULL, *exc_value, *exc_tb, *r;
    atexit_callback *cb;
    atexitmodule_state *modstate;
    int i;

    if (module == NULL)
        return;
    modstate = GET_ATEXIT_STATE(module);

    if (modstate->ncallbacks == 0)
        return;


    for (i = modstate->ncallbacks - 1; i >= 0; i--)
    {
        cb = modstate->atexit_callbacks[i];
        if (cb == NULL)
            continue;

        r = PyObject_Call(cb->func, cb->args, cb->kwargs);
        Py_XDECREF(r);
        if (r == NULL) {
            /* Maintain the last exception, but don't leak if there are
               multiple exceptions. */
            if (exc_type) {
                Py_DECREF(exc_type);
                Py_XDECREF(exc_value);
                Py_XDECREF(exc_tb);
            }
            PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
            if (!PyErr_GivenExceptionMatches(exc_type, PyExc_SystemExit)) {
                PySys_WriteStderr("Error in atexit._run_exitfuncs:\n");
                PyErr_NormalizeException(&exc_type, &exc_value, &exc_tb);
                PyErr_Display(exc_type, exc_value, exc_tb);
            }
        }
    }

    atexit_cleanup(modstate);

    if (exc_type)
        PyErr_Restore(exc_type, exc_value, exc_tb);
}
예제 #25
0
파일: errors.c 프로젝트: cpcloud/cpython
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)) {
        Py_ssize_t 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 (PyExceptionInstance_Check(err))
        err = PyExceptionInstance_Class(err);

    if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
        int res = 0;
        PyObject *exception, *value, *tb;
        PyErr_Fetch(&exception, &value, &tb);
        /* PyObject_IsSubclass() can recurse and therefore is
           not safe (see test_bad_getattr in test.pickletester). */
        res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc);
        /* This function must not fail, so print the error here */
        if (res == -1) {
            PyErr_WriteUnraisable(err);
            res = 0;
        }
        PyErr_Restore(exception, value, tb);
        return res;
    }

    return err == exc;
}
예제 #26
0
/* annotate exception with encrypt_result data */
static void
decode_encrypt_result(PyGpgmeContext *self)
{
    PyObject *err_type, *err_value, *err_traceback;
    gpgme_encrypt_result_t res;
    gpgme_invalid_key_t key;
    PyObject *list;

    PyErr_Fetch(&err_type, &err_value, &err_traceback);
    PyErr_NormalizeException(&err_type, &err_value, &err_traceback);

    if (!PyErr_GivenExceptionMatches(err_type, pygpgme_error))
        goto end;

    res = gpgme_op_encrypt_result(self->ctx);
    if (res == NULL)
        goto end;

    list = PyList_New(0);
    for (key = res->invalid_recipients; key != NULL; key = key->next) {
        PyObject *item, *py_fpr, *err;

        if (key->fpr)
            py_fpr = PyUnicode_DecodeASCII(key->fpr, strlen(key->fpr),
                                           "replace");
        else {
            py_fpr = Py_None;
            Py_INCREF(py_fpr);
        }
        err = pygpgme_error_object(key->reason);
        item = Py_BuildValue("(NN)", py_fpr, err);
        PyList_Append(list, item);
        Py_DECREF(item);
    }

    PyObject_SetAttrString(err_value, "invalid_recipients", list);
    Py_DECREF(list);

 end:
    PyErr_Restore(err_type, err_value, err_traceback);
}
예제 #27
0
static void
decode_decrypt_result(PyGpgmeContext *self)
{
    PyObject *err_type, *err_value, *err_traceback;
    PyObject *value;
    gpgme_decrypt_result_t res;

    PyErr_Fetch(&err_type, &err_value, &err_traceback);
    PyErr_NormalizeException(&err_type, &err_value, &err_traceback);

    if (!PyErr_GivenExceptionMatches(err_type, pygpgme_error))
        goto end;

    res = gpgme_op_decrypt_result(self->ctx);
    if (res == NULL)
        goto end;

    if (res->unsupported_algorithm) {
        value = PyUnicode_DecodeUTF8(res->unsupported_algorithm,
                                     strlen(res->unsupported_algorithm),
                                     "replace");
    } else {
        Py_INCREF(Py_None);
        value = Py_None;
    }
    if (value) {
        PyObject_SetAttrString(err_value, "unsupported_algorithm", value);
        Py_DECREF(value);
    }

    value = PyBool_FromLong(res->wrong_key_usage);
    if (value) {
        PyObject_SetAttrString(err_value, "wrong_key_usage", value);
        Py_DECREF(value);
    }

 end:
    PyErr_Restore(err_type, err_value, err_traceback);
}
예제 #28
0
static PyObject *
pygpgme_context_import(PyGpgmeContext *self, PyObject *args)
{
    PyObject *py_keydata, *result;
    gpgme_data_t keydata;
    gpgme_error_t err;

    if (!PyArg_ParseTuple(args, "O", &py_keydata))
        return NULL;

    if (pygpgme_data_new(&keydata, py_keydata))
        return NULL;

    Py_BEGIN_ALLOW_THREADS;
    err = gpgme_op_import(self->ctx, keydata);
    Py_END_ALLOW_THREADS;

    gpgme_data_release(keydata);
    result = pygpgme_import_result(self->ctx);
    if (pygpgme_check_error(err)) {
        PyObject *err_type, *err_value, *err_traceback;

        PyErr_Fetch(&err_type, &err_value, &err_traceback);
        PyErr_NormalizeException(&err_type, &err_value, &err_traceback);

        if (!PyErr_GivenExceptionMatches(err_type, pygpgme_error))
            goto end;

        if (result != NULL) {
            PyObject_SetAttrString(err_value, "result", result);
            Py_DECREF(result);
        }
    end:
        PyErr_Restore(err_type, err_value, err_traceback);
        return NULL;
    }
    return result;
}
예제 #29
0
// originally copied from Py3's builtin_next()
static CYTHON_INLINE PyObject *__Pyx_PyIter_Next2(PyObject* iterator, PyObject* defval) {
    PyObject* next;
    iternextfunc iternext = Py_TYPE(iterator)->tp_iternext;
#if CYTHON_COMPILING_IN_CPYTHON
    if (unlikely(!iternext)) {
#else
    if (unlikely(!iternext) || unlikely(!PyIter_Check(iterator))) {
#endif
        PyErr_Format(PyExc_TypeError,
            "%.200s object is not an iterator", Py_TYPE(iterator)->tp_name);
        return NULL;
    }
    next = iternext(iterator);
    if (likely(next))
        return next;
#if CYTHON_COMPILING_IN_CPYTHON
#if PY_VERSION_HEX >= 0x03010000 || (PY_MAJOR_VERSION < 3 && PY_VERSION_HEX >= 0x02070000)
    if (unlikely(iternext == &_PyObject_NextNotImplemented))
        return NULL;
#endif
#endif
    if (defval) {
        PyObject* exc_type = PyErr_Occurred();
        if (exc_type) {
            if (unlikely(exc_type != PyExc_StopIteration) &&
                    !PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))
                return NULL;
            PyErr_Clear();
        }
        Py_INCREF(defval);
        return defval;
    }
    if (!PyErr_Occurred())
        PyErr_SetNone(PyExc_StopIteration);
    return NULL;
}

/////////////// IterFinish.proto ///////////////

static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/

/////////////// IterFinish ///////////////

// When PyIter_Next(iter) has returned NULL in order to signal termination,
// this function does the right cleanup and returns 0 on success.  If it
// detects an error that occurred in the iterator, it returns -1.

static CYTHON_INLINE int __Pyx_IterFinish(void) {
#if CYTHON_COMPILING_IN_CPYTHON
    PyThreadState *tstate = PyThreadState_GET();
    PyObject* exc_type = tstate->curexc_type;
    if (unlikely(exc_type)) {
        if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) {
            PyObject *exc_value, *exc_tb;
            exc_value = tstate->curexc_value;
            exc_tb = tstate->curexc_traceback;
            tstate->curexc_type = 0;
            tstate->curexc_value = 0;
            tstate->curexc_traceback = 0;
            Py_DECREF(exc_type);
            Py_XDECREF(exc_value);
            Py_XDECREF(exc_tb);
            return 0;
        } else {
            return -1;
        }
    }
    return 0;
#else
    if (unlikely(PyErr_Occurred())) {
        if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) {
            PyErr_Clear();
            return 0;
        } else {
            return -1;
        }
    }
    return 0;
#endif
}
예제 #30
0
파일: errors.c 프로젝트: cpcloud/cpython
int
PyErr_ExceptionMatches(PyObject *exc)
{
    return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
}