Exemplo n.º 1
0
void
_PyModule_Clear(PyObject *m)
{
    /* To make the execution order of destructors for global
       objects a bit more predictable, we first zap all objects
       whose name starts with a single underscore, before we clear
       the entire dictionary.  We zap them by replacing them with
       None, rather than deleting them from the dictionary, to
       avoid rehashing the dictionary (to some extent). */

    Py_ssize_t pos;
    PyObject *key, *value;
    PyObject *d;

    d = ((PyModuleObject *)m)->md_dict;
    if (d == NULL)
        return;

    /* First, clear only names starting with a single underscore */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
            if (PyUnicode_READ_CHAR(key, 0) == '_' &&
                PyUnicode_READ_CHAR(key, 1) != '_') {
                if (Py_VerboseFlag > 1) {
                    const char *s = _PyUnicode_AsString(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[1] %s\n", s);
                    else
                        PyErr_Clear();
                }
                PyDict_SetItem(d, key, Py_None);
            }
        }
    }

    /* Next, clear all names except for __builtins__ */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
            if (PyUnicode_READ_CHAR(key, 0) != '_' ||
                PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
            {
                if (Py_VerboseFlag > 1) {
                    const char *s = _PyUnicode_AsString(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[2] %s\n", s);
                    else
                        PyErr_Clear();
                }
                PyDict_SetItem(d, key, Py_None);
            }
        }
    }

    /* Note: we leave __builtins__ in place, so that destructors
       of non-global objects defined in this module can still use
       builtins, in particularly 'None'. */

}
Exemplo n.º 2
0
hlVoid PrintValidation(HLValidation eValidation)
{
	switch(eValidation)
	{
	case HL_VALIDATES_ASSUMED_OK:
		PySys_WriteStdout("Assumed OK");
		break;
	case HL_VALIDATES_OK:
		PySys_WriteStdout("OK");
		break;
	case HL_VALIDATES_INCOMPLETE:
		PySys_WriteStderr("Incomplete");
		break;
	case HL_VALIDATES_CORRUPT:
		PySys_WriteStderr("Corrupt");
		break;
	case HL_VALIDATES_CANCELED:
		PySys_WriteStderr("Canceled");
		break;
	case HL_VALIDATES_ERROR:
		PySys_WriteStderr("Error");
		break;
	default:
		PySys_WriteStderr("Unknown");
		break;
	}
}
Exemplo n.º 3
0
QString PythonMapFormat::shortName() const
{
    QString ret;

    // find fun
    PyObject *pfun = PyObject_GetAttrString(mClass, "shortName");
    if (!pfun || !PyCallable_Check(pfun)) {
        PySys_WriteStderr("Plugin extension doesn't define \"shortName\". Falling back to \"nameFilter\"\n");
        return nameFilter();
    }

    // have fun
    PyObject *pinst = PyEval_CallFunction(pfun, "()");
    if (!pinst) {
        PySys_WriteStderr("** Uncaught exception in script **\n");
    } else {
        ret = PyString_AsString(pinst);
        Py_DECREF(pinst);
    }
    handleError();

    Py_DECREF(pfun);

    return ret;
}
Exemplo n.º 4
0
Arquivo: common.c Projeto: imclab/pyuv
/* handle uncausht exception in a callback */
static void
handle_uncaught_exception(Loop *loop)
{
    PyObject *excepthook, *exc, *value, *tb, *result;
    Bool exc_in_hook = False;

    ASSERT(loop);
    ASSERT(PyErr_Occurred());
    PyErr_Fetch(&exc, &value, &tb);

    excepthook = PyObject_GetAttrString((PyObject *)loop, "excepthook");
    if (excepthook == NULL) {
        if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
            PySys_WriteStderr("Exception while getting excepthook\n");
            PyErr_PrintEx(0);
            exc_in_hook = True;
        }
        PyErr_Restore(exc, value, tb);
    } else if (excepthook == Py_None) {
        PyErr_Restore(exc, value, tb);
    } else {
        PyErr_NormalizeException(&exc, &value, &tb);
        if (!value)
            PYUV_SET_NONE(value);
        if (!tb)
            PYUV_SET_NONE(tb);
        result = PyObject_CallFunctionObjArgs(excepthook, exc, value, tb, NULL);
        if (result == NULL) {
            PySys_WriteStderr("Unhandled exception in excepthook\n");
            PyErr_PrintEx(0);
            exc_in_hook = True;
            PyErr_Restore(exc, value, tb);
        } else {
            Py_DECREF(exc);
            Py_DECREF(value);
            Py_DECREF(tb);
        }
        Py_XDECREF(result);
    }
    Py_XDECREF(excepthook);

    /* Exception still pending, print it to stderr */
    if (PyErr_Occurred()) {
        if (exc_in_hook)
            PySys_WriteStderr("\n");
        PySys_WriteStderr("Unhandled exception in callback\n");
        PyErr_PrintEx(0);
    }
}
Exemplo n.º 5
0
int
Tcl_AppInit(Tcl_Interp *interp)
{
	Tk_Window main;

	main = Tk_MainWindow(interp);
	if (Tcl_Init(interp) == TCL_ERROR) {
		PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp));
		return TCL_ERROR;
	}
	if (Tk_Init(interp) == TCL_ERROR) {
		PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
		return TCL_ERROR;
	}
	return TCL_OK;
}
Exemplo n.º 6
0
static pascal OSErr
dragglue_SendData(FlavorType theType, void *dragSendRefCon,
                      ItemReference theItem, DragReference theDrag)
{
	DragObjObject *self = (DragObjObject *)dragSendRefCon;
	PyObject *args, *rv;
	int i;
	
	if ( self->sendproc == NULL )
		return -1;
	args = Py_BuildValue("O&l", PyMac_BuildOSType, theType, theItem);
	if ( args == NULL )
		return -1;
	rv = PyEval_CallObject(self->sendproc, args);
	Py_DECREF(args);
	if ( rv == NULL ) {
		PySys_WriteStderr("Drag: Exception in SendDataHandler\n");
		PyErr_Print();
		return -1;
	}
	i = -1;
	if ( rv == Py_None )
		i = 0;
	else
		PyArg_Parse(rv, "l", &i);
	Py_DECREF(rv);
	return i;
}
Exemplo n.º 7
0
static pascal OSErr
dragglue_ReceiveHandler(WindowPtr theWindow, void *handlerRefCon,
                        DragReference theDrag)
{
	PyObject *args, *rv;
	int i;
	
	args = Py_BuildValue("O&O&", DragObj_New, theDrag, WinObj_WhichWindow, theWindow);
	if ( args == NULL )
		return -1;
	rv = PyEval_CallObject((PyObject *)handlerRefCon, args);
	Py_DECREF(args);
	if ( rv == NULL ) {
		PySys_WriteStderr("Drag: Exception in ReceiveHandler\n");
		PyErr_Print();
		return -1;
	}
	i = -1;
	if ( rv == Py_None )
		i = 0;
	else
		PyArg_Parse(rv, "l", &i);
	Py_DECREF(rv);
	return i;
}
Exemplo n.º 8
0
int do_import(FARPROC init_func, char *modname)
{
	PyObject *m;
	char *oldcontext;

	if ((m = _PyImport_FindExtension(modname, modname)) != NULL) {
		return -1;
	}

	if (init_func == NULL) {
		PyErr_Format(PyExc_ImportError,
			     "dynamic module does not define init function (init%.200s)",
			     modname);
		return -1;
	}

	oldcontext = _Py_PackageContext;
	_Py_PackageContext = modname;
	(*init_func)();
	_Py_PackageContext = oldcontext;
	if (PyErr_Occurred()) {
		return -1;
	}

	if (_PyImport_FixupExtension(modname, modname) == NULL)
		return -1;
	if (Py_VerboseFlag)
		PySys_WriteStderr(
			"import %s # dynamically loaded from zipfile\n",
			modname);
	return 0;
}
Exemplo n.º 9
0
/* Function to issue a warning message; may raise an exception. */
int
PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)
{
    PyObject *dict, *func = NULL;
    PyObject *warnings_module = PyModule_GetWarningsModule();

    if (warnings_module != NULL) {
        dict = PyModule_GetDict(warnings_module);
        func = PyDict_GetItemString(dict, "warn");
    }
    if (func == NULL) {
        PySys_WriteStderr("warning: %s\n", message);
        return 0;
    }
    else {
        PyObject *res;

        if (category == NULL)
            category = PyExc_RuntimeWarning;
        res = PyObject_CallFunction(func, "sOn",
                                    message, category, stack_level);
        if (res == NULL)
            return -1;
        Py_DECREF(res);
        return 0;
    }
}
Exemplo n.º 10
0
bool PythonMapFormat::write(const Tiled::Map *map, const QString &fileName)
{
    mError = QString();

    mPlugin.log(tr("-- Using script %1 to write %2").arg(mScriptFile, fileName));

    PyObject *pmap = _wrap_convert_c2py__Tiled__Map_const(map);
    if (!pmap)
        return false;
    PyObject *pinst = PyObject_CallMethod(mClass,
                                          (char *)"write", (char *)"(Ns)",
                                          pmap,
                                          fileName.toUtf8().constData());

    if (!pinst) {
        PySys_WriteStderr("** Uncaught exception in script **\n");
        mError = tr("Uncaught exception in script. Please check console.");
    } else {
        bool ret = PyObject_IsTrue(pinst);
        Py_DECREF(pinst);
        if (!ret)
            mError = tr("Script returned false. Please check console.");
        return ret;
    }

    handleError();
    return false;
}
Exemplo n.º 11
0
Arquivo: gcmodule.c Projeto: d11/rts
void
_PyGC_Fini(void)
{
    if (!(debug & DEBUG_SAVEALL)
        && garbage != NULL && PyList_GET_SIZE(garbage) > 0) {
        char *message;
        if (debug & DEBUG_UNCOLLECTABLE)
            message = "gc: %zd uncollectable objects at " \
                "shutdown";
        else
            message = "gc: %zd uncollectable objects at " \
                "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
        if (PyErr_WarnFormat(PyExc_ResourceWarning, 0, message,
                             PyList_GET_SIZE(garbage)) < 0)
            PyErr_WriteUnraisable(NULL);
        if (debug & DEBUG_UNCOLLECTABLE) {
            PyObject *repr = NULL, *bytes = NULL;
            repr = PyObject_Repr(garbage);
            if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
                PyErr_WriteUnraisable(garbage);
            else {
                PySys_WriteStderr(
                    "    %s\n",
                    PyBytes_AS_STRING(bytes)
                    );
            }
            Py_XDECREF(repr);
            Py_XDECREF(bytes);
        }
    }
}
Exemplo n.º 12
0
static PyObject *
MatrixPointer_setY(MatrixPointer *self, PyObject *arg)
{
	PyObject *tmp, *streamtmp;
	
	if (arg == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
    
	int isNumber = PyNumber_Check(arg);
	if (isNumber == 1) {
		PySys_WriteStderr("MatrixPointer y attributes must be a PyoObject.\n");
        if (PyInt_AsLong(PyObject_CallMethod(self->server, "getIsBooted", NULL))) {
            PyObject_CallMethod(self->server, "shutdown", NULL);
        }
        Py_Exit(1);
	}
	
	tmp = arg;
	Py_INCREF(tmp);
	Py_XDECREF(self->y);
    
    self->y = tmp;
    streamtmp = PyObject_CallMethod((PyObject *)self->y, "_getStream", NULL);
    Py_INCREF(streamtmp);
    Py_XDECREF(self->y_stream);
    self->y_stream = (Stream *)streamtmp;
    
	Py_INCREF(Py_None);
	return Py_None;
}	
Exemplo n.º 13
0
/* Return the zlib.decompress function object, or NULL if zlib couldn't
   be imported. The function is cached when found, so subsequent calls
   don't import zlib again. Returns a *borrowed* reference.
   XXX This makes zlib.decompress immortal. */
static PyObject *
get_decompress_func(void)
{
    static PyObject *decompress = NULL;

    if (decompress == NULL) {
        PyObject *zlib;
        static int importing_zlib = 0;

        if (importing_zlib != 0)
            /* Someone has a zlib.py[co] in their Zip file;
               let's avoid a stack overflow. */
            return NULL;
        importing_zlib = 1;
        zlib = PyImport_ImportModuleNoBlock("zlib");
        importing_zlib = 0;
        if (zlib != NULL) {
            decompress = PyObject_GetAttrString(zlib,
                                                "decompress");
            Py_DECREF(zlib);
        }
        else
            PyErr_Clear();
        if (Py_VerboseFlag)
            PySys_WriteStderr("# zipimport: zlib %s\n",
                zlib != NULL ? "available": "UNAVAILABLE");
    }
    return decompress;
}
Exemplo n.º 14
0
static void
t_bootstrap(void *boot_raw)
{
	struct bootstate *boot = (struct bootstate *) boot_raw;
	PyThreadState *tstate;
	PyObject *res;

	tstate = PyThreadState_New(boot->interp);
	PyEval_AcquireThread(tstate);
	res = PyEval_CallObjectWithKeywords(
		boot->func, boot->args, boot->keyw);
	Py_DECREF(boot->func);
	Py_DECREF(boot->args);
	Py_XDECREF(boot->keyw);
	PyMem_DEL(boot_raw);
	if (res == NULL) {
		if (PyErr_ExceptionMatches(PyExc_SystemExit))
			PyErr_Clear();
		else {
			PySys_WriteStderr("Unhandled exception in thread:\n");
			PyErr_PrintEx(0);
		}
	}
	else
		Py_DECREF(res);
	PyThreadState_Clear(tstate);
	PyThreadState_DeleteCurrent();
	PyThread_exit_thread();
}
Exemplo n.º 15
0
/* Given the contents of a .py[co] file in a buffer, unmarshal the data
   and return the code object. Return None if it the magic word doesn't
   match (we do this instead of raising an exception as we fall back
   to .py if available and we don't want to mask other errors).
   Returns a new reference. */
static PyObject *
unmarshal_code(char *pathname, PyObject *data)
{
    PyObject *code;
    char *buf = PyBytes_AsString(data);
    Py_ssize_t size = PyBytes_Size(data);

    if (size <= 9) {
        PyErr_SetString(PyExc_TypeError,
                        "bad pyc data");
        return NULL;
    }

    if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
        if (Py_VerboseFlag)
            PySys_WriteStderr("# %s has bad magic\n",
                              pathname);
        Py_INCREF(Py_None);
        return NULL;
    }

    code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
    if (code == NULL)
        return NULL;
    if (!PyCode_Check(code)) {
        Py_DECREF(code);
        PyErr_Format(PyExc_TypeError,
                     "compiled module %.200s is not a code object",
                     pathname);
        return NULL;
    }
    return code;
}
Exemplo n.º 16
0
Tiled::Map *PythonMapFormat::read(const QString &fileName)
{
    mError = QString();

    mPlugin.log(tr("-- Using script %1 to read %2").arg(mScriptFile, fileName));

    if (!PyObject_HasAttrString(mClass, "read")) {
        mError = "Please define class that extends tiled.Plugin and "
                "has @classmethod read(cls, filename)";
        return nullptr;
    }
    PyObject *pinst = PyObject_CallMethod(mClass, (char *)"read",
                                          (char *)"(s)", fileName.toUtf8().constData());

    Tiled::Map *ret = nullptr;
    if (!pinst) {
        PySys_WriteStderr("** Uncaught exception in script **\n");
    } else {
        _wrap_convert_py2c__Tiled__Map___star__(pinst, &ret);
        Py_DECREF(pinst);
    }
    handleError();

    if (ret)
        ret->setProperty("__script__", mScriptFile);
    return ret;
}
Exemplo n.º 17
0
/* Warning with explicit origin */
int
PyErr_WarnExplicit(PyObject *category, const char *message,
                   const char *filename, int lineno,
                   const char *module, PyObject *registry)
{
    PyObject *mod, *dict, *func = NULL;

    mod = PyImport_ImportModule("warnings");
    if (mod != NULL) {
        dict = PyModule_GetDict(mod);
        func = PyDict_GetItemString(dict, "warn_explicit");
        Py_DECREF(mod);
    }
    if (func == NULL) {
        PySys_WriteStderr("warning: %s\n", message);
        return 0;
    }
    else {
        PyObject *res;

        if (category == NULL)
            category = PyExc_RuntimeWarning;
        if (registry == NULL)
            registry = Py_None;
        res = PyObject_CallFunction(func, "sOsizO", message, category,
                                    filename, lineno, module, registry);
        if (res == NULL)
            return -1;
        Py_DECREF(res);
        return 0;
    }
}
Exemplo n.º 18
0
/* Function to issue a warning message; may raise an exception. */
int
PyErr_Warn(PyObject *category, char *message)
{
	PyObject *dict, *func = NULL;
	PyObject *warnings_module = PyModule_GetWarningsModule();

	if (warnings_module != NULL) {
		dict = PyModule_GetDict(warnings_module);
		func = PyDict_GetItemString(dict, "warn");
	}
	if (func == NULL) {
		PySys_WriteStderr("warning: %s\n", message);
		return 0;
	}
	else {
		PyObject *args, *res;

		if (category == NULL)
			category = PyExc_RuntimeWarning;
		args = Py_BuildValue("(sO)", message, category);
		if (args == NULL)
			return -1;
		res = PyEval_CallObject(func, args);
		Py_DECREF(args);
		if (res == NULL)
			return -1;
		Py_DECREF(res);
		return 0;
	}
}
Exemplo n.º 19
0
static void
warn(const char *msg, const char *filename, int lineno)
{
    if (filename == NULL)
        filename = "<string>";
    PySys_WriteStderr(msg, filename, lineno);
}
Exemplo n.º 20
0
bool PythonPlugin::loadOrReloadModule(ScriptEntry &script)
{
    const QByteArray name = script.name.toUtf8();

    if (script.module) {
        PySys_WriteStdout("-- Reloading %s\n", name.constData());

        PyObject *module = PyImport_ReloadModule(script.module);
        Py_DECREF(script.module);
        script.module = module;
    } else {
        PySys_WriteStdout("-- Loading %s\n", name.constData());
        script.module = PyImport_ImportModule(name.constData());
    }

    if (!script.module)
        return false;

    PyObject *pluginClass = findPluginSubclass(script.module);

    if (!pluginClass) {
        PySys_WriteStderr("Extension of tiled.Plugin not defined in "
                          "script: %s\n", name.constData());
        return false;
    }

    if (script.mapFormat) {
        script.mapFormat->setPythonClass(pluginClass);
    } else {
        script.mapFormat = new PythonMapFormat(name, pluginClass, *this);
        addObject(script.mapFormat);
    }

    return true;
}
Exemplo n.º 21
0
static pascal OSErr
GenericCoercionHandler(const AEDesc *fromDesc, DescType toType, refcontype refcon, AEDesc *toDesc)
{	
	PyObject *handler = (PyObject *)refcon;
	AEDescObject *fromObject;
	PyObject *args, *res;
    PyGILState_STATE state;
	OSErr err = noErr;
	
	state = PyGILState_Ensure();
	if ((fromObject = (AEDescObject *)AEDesc_New((AEDesc *)fromDesc)) == NULL) {
		err = -1;
		goto cleanup;
	}
	if ((args = Py_BuildValue("OO&", fromObject, PyMac_BuildOSType, &toType)) == NULL) {
		Py_DECREF(fromObject);
		err = -1;
		goto cleanup;
	}
	res = PyEval_CallObject(handler, args);
	fromObject->ob_itself.descriptorType = 'null';
	fromObject->ob_itself.dataHandle = NULL;
	Py_DECREF(args);
	if (res == NULL) {
		PySys_WriteStderr("Exception in AE coercion handler function\n");
		PyErr_Print();
		err = errAECoercionFail;
		goto cleanup;
	}
	if (!AEDesc_Check(res)) {
		PySys_WriteStderr("AE coercion handler function did not return an AEDesc\n");
		Py_DECREF(res);
		err = errAECoercionFail;
		goto cleanup;
	}
	if (AEDuplicateDesc(&((AEDescObject *)res)->ob_itself, toDesc)) {
		Py_DECREF(res);
		err = -1;
		goto cleanup;
	}
	Py_DECREF(res);
cleanup:
	PyGILState_Release(state);
	return err;
}
Exemplo n.º 22
0
PyObject *
_PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp)
{
	PyObject *m, *d, *s;
	char *lastdot, *shortname, *packagecontext;
	dl_funcptr p;

	if ((m = _PyImport_FindExtension(name, pathname)) != NULL) {
		Py_INCREF(m);
		return m;
	}
	lastdot = strrchr(name, '.');
	if (lastdot == NULL) {
		packagecontext = NULL;
		shortname = name;
	}
	else {
		packagecontext = name;
		shortname = lastdot+1;
	}

	p = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp);
	if (PyErr_Occurred())
		return NULL;
	if (p == NULL) {
		PyErr_Format(PyExc_ImportError,
		   "dynamic module does not define init function (init%.200s)",
			     shortname);
		return NULL;
	}
	_Py_PackageContext = packagecontext;
	(*p)();
	_Py_PackageContext = NULL;
	if (PyErr_Occurred())
		return NULL;
	if (_PyImport_FixupExtension(name, pathname) == NULL)
		return NULL;

	m = PyDict_GetItemString(PyImport_GetModuleDict(), name);
	if (m == NULL) {
		PyErr_SetString(PyExc_SystemError,
				"dynamic module not initialized properly");
		return NULL;
	}
	/* Remember the filename as the __file__ attribute */
	d = PyModule_GetDict(m);
	s = PyString_FromString(pathname);
	if (s == NULL || PyDict_SetItemString(d, "__file__", s) != 0)
		PyErr_Clear(); /* Not important enough to report */
	Py_XDECREF(s);
	if (Py_VerboseFlag)
		PySys_WriteStderr(
			"import %s # dynamically loaded from %s\n",
			name, pathname);
	Py_INCREF(m);
	return m;
}
Exemplo n.º 23
0
static void
handle_system_exit(void)
{
    PyObject *exception, *value, *tb;
    int exitcode = 0;

    if (Py_InspectFlag)
        /* Don't exit if -i flag was given. This flag is set to 0
         * when entering interactive mode for inspecting. */
        return;

    PyErr_Fetch(&exception, &value, &tb);
    fflush(stdout);
    if (value == NULL || value == Py_None)
        goto done;
    if (PyExceptionInstance_Check(value)) {
        /* The error code should be in the `code' attribute. */
        _Py_IDENTIFIER(code);
        PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
        if (code) {
            Py_DECREF(value);
            value = code;
            if (value == Py_None)
                goto done;
        }
        /* If we failed to dig out the 'code' attribute,
           just let the else clause below print the error. */
    }
    if (PyLong_Check(value))
        exitcode = (int)PyLong_AsLong(value);
    else {
        PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
        /* We clear the exception here to avoid triggering the assertion
         * in PyObject_Str that ensures it won't silently lose exception
         * details.
         */
        PyErr_Clear();
        if (sys_stderr != NULL && sys_stderr != Py_None) {
            PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
        } else {
            PyObject_Print(value, stderr, Py_PRINT_RAW);
            fflush(stderr);
        }
        PySys_WriteStderr("\n");
        exitcode = 1;
    }
 done:
    /* Restore and clear the exception info, in order to properly decref
     * the exception, value, and traceback.      If we just exit instead,
     * these leak, which confuses PYTHONDUMPREFS output, and may prevent
     * some finalizers from running.
     */
    PyErr_Restore(exception, value, tb);
    PyErr_Clear();
    Py_Exit(exitcode);
    /* NOTREACHED */
}
Exemplo n.º 24
0
/* Given the contents of a .py[co] file in a buffer, unmarshal the data
   and return the code object. Return None if it the magic word doesn't
   match (we do this instead of raising an exception as we fall back
   to .py if available and we don't want to mask other errors).
   Returns a new reference. */
static PyObject *
unmarshal_code(const char *pathname, PyObject *data, time_t mtime)
{
    PyObject *code;
    unsigned char *buf = (unsigned char *)PyString_AsString(data);
    Py_ssize_t size = PyString_Size(data);

    if (size < 8) {
        PyErr_SetString(ZipImportError,
                        "bad pyc data");
        return NULL;
    }

    if (get_uint32(buf) != (unsigned int)PyImport_GetMagicNumber()) {
        if (Py_VerboseFlag) {
            PySys_WriteStderr("# %s has bad magic\n",
                              pathname);
        }
        Py_INCREF(Py_None);
        return Py_None;  /* signal caller to try alternative */
    }

    if (mtime != 0 && !eq_mtime(get_uint32(buf + 4), mtime)) {
        if (Py_VerboseFlag) {
            PySys_WriteStderr("# %s has bad mtime\n",
                              pathname);
        }
        Py_INCREF(Py_None);
        return Py_None;  /* signal caller to try alternative */
    }

    code = PyMarshal_ReadObjectFromString((char *)buf + 8, size - 8);
    if (code == NULL) {
        return NULL;
    }
    if (!PyCode_Check(code)) {
        Py_DECREF(code);
        PyErr_Format(PyExc_TypeError,
             "compiled module %.200s is not a code object",
             pathname);
        return NULL;
    }
    return code;
}
Exemplo n.º 25
0
static void
scss_Scanner_dealloc(scss_Scanner *self)
{
	if (self->scanner != NULL) Scanner_del(self->scanner);

	self->ob_type->tp_free((PyObject*)self);

	#ifdef DEBUG
		PySys_WriteStderr("Scss Scanner object destroyed!\n");
	#endif
}
Exemplo n.º 26
0
static void
scss_BlockLocator_dealloc(scss_BlockLocator *self)
{
	if (self->locator != NULL) BlockLocator_del(self->locator);

	self->ob_type->tp_free((PyObject*)self);

	#ifdef DEBUG
		PySys_WriteStderr("Scss BlockLocator object destroyed!\n");
	#endif
}
Exemplo n.º 27
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);
	}
}
Exemplo n.º 28
0
static PyObject*
load_module(char *name, char *pathname, FILE *fp) {
	PyCodeObject* co = parse_source_module(pathname, fp);
	if (co == NULL)
		return NULL;
	if (Py_VerboseFlag)
		PySys_WriteStderr("import %s # from %s\n",
						  name, pathname);
	PyObject* m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
	Py_DECREF(co);
	return m;
}
Exemplo n.º 29
0
void ExtensionError(CControlBlock *pcb, const char *errmsg)
{
	char *windows_error = ::GetLastError() ?
	                          ::FormatSysError(::GetLastError()) : NULL;
	{ // temp scope to release python lock
	CEnterLeavePython celp;
	PySys_WriteStderr("Internal Extension Error: %s\n", errmsg);
	if (windows_error)
		PySys_WriteStderr("Last Windows error: %s\n", windows_error);
	if (PyErr_Occurred()) {
		PyErr_Print();
		PyErr_Clear();
	}
	} // end temp scope
	if (pcb) {
		char *htmlStream = HTMLErrorResp(errmsg);
	
		pcb->SetStatus(HSE_STATUS_ERROR);
		pcb->SetLogMessage(errmsg);
		HSE_SEND_HEADER_EX_INFO SendHeaderExInfo;
		SendHeaderExInfo.pszStatus = "200 OK";
		SendHeaderExInfo.cchStatus = strlen(SendHeaderExInfo.pszStatus);
		SendHeaderExInfo.pszHeader = "Content-type: text/html\r\n\r\n";
		SendHeaderExInfo.cchHeader = strlen(SendHeaderExInfo.pszHeader);
		SendHeaderExInfo.fKeepConn = FALSE;
		EXTENSION_CONTROL_BLOCK * ecb = pcb->GetECB();
		ecb->ServerSupportFunction(ecb->ConnID, HSE_REQ_SEND_RESPONSE_HEADER_EX, &SendHeaderExInfo, NULL,NULL);
		pcb->WriteStream(htmlStream, strlen(htmlStream));
		if (windows_error) {
			static char *chunk = "<br>Last Windows error:";
			pcb->WriteStream(chunk, strlen(chunk));
			pcb->WriteStream(windows_error, strlen(windows_error));
		}
	}
	const char *inserts[] = {errmsg, windows_error ? windows_error : "n/a"};
	WriteEventLogMessage(EVENTLOG_ERROR_TYPE, E_PYISAPI_EXTENSION_FAILED,
			     2, inserts);
	if (windows_error)
		free(windows_error);
}
static void
t_bootstrap(void *boot_raw)
{
	struct bootstate *boot = (struct bootstate *) boot_raw;
	PyThreadState *tstate;
	PyObject *res;

	tstate = boot->tstate;
	tstate->thread_id = PyThread_get_thread_ident();
	_PyThreadState_Init(tstate);
	PyEval_AcquireThread(tstate);
	res = PyEval_CallObjectWithKeywords(
		boot->func, boot->args, boot->keyw);
	if (res == NULL) {
		if (PyErr_ExceptionMatches(PyExc_SystemExit))
			PyErr_Clear();
		else {
			PyObject *file;
			PySys_WriteStderr(
				"Unhandled exception in thread started by ");
			file = PySys_GetObject("stderr");
			if (file != NULL && file != Py_None)
				PyFile_WriteObject(boot->func, file, 0);
			else
				PyObject_Print(boot->func, stderr, 0);
			PySys_WriteStderr("\n");
			PyErr_PrintEx(0);
		}
	}
	else
		Py_DECREF(res);
	Py_DECREF(boot->func);
	Py_DECREF(boot->args);
	Py_XDECREF(boot->keyw);
	PyMem_DEL(boot_raw);
	PyThreadState_Clear(tstate);
	PyThreadState_DeleteCurrent();
	PyThread_exit_thread();
}