Author: Armin Rigo <[email protected]>
Branch: 
Changeset: r2981:cace5cac5ccb
Date: 2017-06-16 20:45 +0200
http://bitbucket.org/cffi/cffi/changeset/cace5cac5ccb/

Log:    Issue #316

        Call MessageBox() more generally on most stderr outputs from cffi

diff --git a/c/_cffi_backend.c b/c/_cffi_backend.c
--- a/c/_cffi_backend.c
+++ b/c/_cffi_backend.c
@@ -288,6 +288,8 @@
 
 #include "wchar_helper.h"
 
+#include "../cffi/_cffi_errors.h"
+
 typedef struct _cffi_allocator_s {
     PyObject *ca_alloc, *ca_free;
     int ca_dont_clear;
@@ -1829,7 +1831,8 @@
 }
 
 /* forward */
-static void _my_PyErr_WriteUnraisable(char *objdescr, PyObject *obj,
+static void _my_PyErr_WriteUnraisable(PyObject *t, PyObject *v, PyObject *tb,
+                                      char *objdescr, PyObject *obj,
                                       char *extra_error_line);
 
 
@@ -1849,8 +1852,12 @@
             Py_DECREF(result);
         }
         else {
-            _my_PyErr_WriteUnraisable("From callback for ffi.gc ",
+            PyObject *ecap, *t, *v, *tb;
+            PyErr_Fetch(&t, &v, &tb);
+            ecap = _cffi_start_error_capture();
+            _my_PyErr_WriteUnraisable(t, v, tb, "From callback for ffi.gc ",
                                       origobj, NULL);
+            _cffi_stop_error_capture(ecap);
         }
         Py_DECREF(destructor);
 
@@ -5500,12 +5507,12 @@
     return convert_from_object(result, ctype, pyobj);
 }
 
-static void _my_PyErr_WriteUnraisable(char *objdescr, PyObject *obj,
+static void _my_PyErr_WriteUnraisable(PyObject *t, PyObject *v, PyObject *tb,
+                                      char *objdescr, PyObject *obj,
                                       char *extra_error_line)
 {
     /* like PyErr_WriteUnraisable(), but write a full traceback */
-    PyObject *f, *t, *v, *tb;
-    PyErr_Fetch(&t, &v, &tb);
+    PyObject *f;
 #if PY_MAJOR_VERSION >= 3
     /* jump through hoops to ensure the tb is attached to v, on Python 3 */
     PyErr_NormalizeException(&t, &v, &tb);
@@ -5595,8 +5602,12 @@
     }
     onerror_cb = PyTuple_GET_ITEM(cb_args, 3);
     if (onerror_cb == Py_None) {
-        _my_PyErr_WriteUnraisable("From cffi callback ", py_ob,
+        PyObject *ecap, *t, *v, *tb;
+        PyErr_Fetch(&t, &v, &tb);
+        ecap = _cffi_start_error_capture();
+        _my_PyErr_WriteUnraisable(t, v, tb, "From cffi callback ", py_ob,
                                   extra_error_line);
+        _cffi_stop_error_capture(ecap);
     }
     else {
         PyObject *exc1, *val1, *tb1, *res1, *exc2, *val2, *tb2;
@@ -5620,14 +5631,17 @@
         }
         else {
             /* double exception! print a double-traceback... */
+            PyObject *ecap;
             PyErr_Fetch(&exc2, &val2, &tb2);
-            PyErr_Restore(exc1, val1, tb1);
-            _my_PyErr_WriteUnraisable("From cffi callback ", py_ob,
+            ecap = _cffi_start_error_capture();
+            _my_PyErr_WriteUnraisable(exc1, val1, tb1,
+                                      "From cffi callback ", py_ob,
                                       extra_error_line);
-            PyErr_Restore(exc2, val2, tb2);
             extra_error_line = ("\nDuring the call to 'onerror', "
                                 "another exception occurred:\n\n");
-            _my_PyErr_WriteUnraisable(NULL, NULL, extra_error_line);
+            _my_PyErr_WriteUnraisable(exc2, val2, tb2,
+                                      NULL, NULL, extra_error_line);
+            _cffi_stop_error_capture(ecap);
         }
     }
     goto done;
diff --git a/cffi/_cffi_errors.h b/cffi/_cffi_errors.h
new file mode 100644
--- /dev/null
+++ b/cffi/_cffi_errors.h
@@ -0,0 +1,141 @@
+#ifndef CFFI_MESSAGEBOX
+# ifdef _MSC_VER
+#  define CFFI_MESSAGEBOX  1
+# else
+#  define CFFI_MESSAGEBOX  0
+# endif
+#endif
+
+
+#if CFFI_MESSAGEBOX
+/* Windows only: logic to take the Python-CFFI embedding logic
+   initialization errors and display them in a background thread
+   with MessageBox.  The idea is that if the whole program closes
+   as a result of this problem, then likely it is already a console
+   program and you can read the stderr output in the console too.
+   If it is not a console program, then it will likely show its own
+   dialog to complain, or generally not abruptly close, and for this
+   case the background thread should stay alive.
+*/
+static void *volatile _cffi_bootstrap_text;
+
+static PyObject *_cffi_start_error_capture(void)
+{
+    PyObject *result = NULL;
+    PyObject *x, *m, *bi;
+
+    if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text,
+            (void *)1, NULL) != NULL)
+        return (PyObject *)1;
+
+    m = PyImport_AddModule("_cffi_error_capture");
+    if (m == NULL)
+        goto error;
+
+    result = PyModule_GetDict(m);
+    if (result == NULL)
+        goto error;
+
+    bi = PyImport_ImportModule("__builtin__");
+    if (bi == NULL)
+        goto error;
+    PyDict_SetItemString(result, "__builtins__", bi);
+    Py_DECREF(bi);
+
+    x = PyRun_String(
+        "import sys\n"
+        "class FileLike:\n"
+        "  def write(self, x):\n"
+        "    of.write(x)\n"
+        "    self.buf += x\n"
+        "fl = FileLike()\n"
+        "fl.buf = ''\n"
+        "of = sys.stderr\n"
+        "sys.stderr = fl\n"
+        "def done():\n"
+        "  sys.stderr = of\n"
+        "  return fl.buf\n",   /* make sure the returned value stays alive */
+        Py_file_input,
+        result, result);
+    Py_XDECREF(x);
+
+ error:
+    if (PyErr_Occurred())
+    {
+        PyErr_WriteUnraisable(Py_None);
+        PyErr_Clear();
+    }
+    return result;
+}
+
+#pragma comment(lib, "user32.lib")
+
+static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
+{
+    Sleep(666);    /* may be interrupted if the whole process is closing */
+#if PY_MAJOR_VERSION >= 3
+    MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,
+                L"Python-CFFI error",
+                MB_OK | MB_ICONERROR);
+#else
+    MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
+                "Python-CFFI error",
+                MB_OK | MB_ICONERROR);
+#endif
+    _cffi_bootstrap_text = NULL;
+    return 0;
+}
+
+static void _cffi_stop_error_capture(PyObject *ecap)
+{
+    PyObject *s;
+    void *text;
+
+    if (ecap == (PyObject *)1)
+        return;
+
+    if (ecap == NULL)
+        goto error;
+
+    s = PyRun_String("done()", Py_eval_input, ecap, ecap);
+    if (s == NULL)
+        goto error;
+
+    /* Show a dialog box, but in a background thread, and
+       never show multiple dialog boxes at once. */
+#if PY_MAJOR_VERSION >= 3
+    text = PyUnicode_AsWideCharString(s, NULL);
+#else
+    text = PyString_AsString(s);
+#endif
+
+    _cffi_bootstrap_text = text;
+
+    if (text != NULL)
+    {
+        HANDLE h;
+        h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
+                         NULL, 0, NULL);
+        if (h != NULL)
+            CloseHandle(h);
+    }
+    /* decref the string, but it should stay alive as 'fl.buf'
+       in the small module above.  It will really be freed only if
+       we later get another similar error.  So it's a leak of at
+       most one copy of the small module.  That's fine for this
+       situation which is usually a "fatal error" anyway. */
+    Py_DECREF(s);
+    PyErr_Clear();
+    return;
+
+  error:
+    _cffi_bootstrap_text = NULL;
+    PyErr_Clear();
+}
+
+#else
+
+static PyObject *_cffi_start_error_capture(void) { return NULL; }
+static void _cffi_stop_error_capture(PyObject *ecap) { }
+
+#endif
diff --git a/cffi/_embedding.h b/cffi/_embedding.h
--- a/cffi/_embedding.h
+++ b/cffi/_embedding.h
@@ -109,132 +109,7 @@
 /**********  CPython-specific section  **********/
 #ifndef PYPY_VERSION
 
-
-#ifdef _MSC_VER
-/* Windows only: logic to take the Python-CFFI embedding logic
-   initialization errors and display them in a background thread
-   with MessageBox.  The idea is that if the whole program closes
-   as a result of this problem, then likely it is already a console
-   program and you can read the stderr output in the console too.
-   If it is not a console program, then it will likely show its own
-   dialog to complain, or generally not abruptly close, and for this
-   case the background thread should stay alive.
-*/
-static PyObject *_cffi_bootstrap_string;
-static void *volatile _cffi_bootstrap_text;
-
-static PyObject *_cffi_start_error_capture(void)
-{
-    PyObject *result = NULL;
-    PyObject *x, *m, *bi;
-
-    if (!cffi_compare_and_swap(&_cffi_bootstrap_text, NULL, (void *)1))
-        return (PyObject *)1;
-
-    m = PyImport_AddModule("_cffi_error_capture");
-    if (m == NULL)
-        goto error;
-
-    result = PyModule_GetDict(m);
-    if (result == NULL)
-        goto error;
-
-    bi = PyImport_ImportModule("__builtin__");
-    if (bi == NULL)
-        goto error;
-    PyDict_SetItemString(result, "__builtins__", bi);
-    Py_DECREF(bi);
-
-    x = PyRun_String(
-        "import sys\n"
-        "class FileLike:\n"
-        "  def write(self, x):\n"
-        "    sys.__stderr__.write(x)\n"
-        "    self.buf += x\n"
-        "fl = FileLike()\n"
-        "fl.buf = ''\n"
-        "sys.stderr = fl\n"
-        "def done():\n"
-        "  sys.stderr = sys.__stderr__\n"
-        "  return fl.buf\n",   /* make sure the returned value stays alive */
-        Py_file_input,
-        result, result);
-    Py_XDECREF(x);
-
- error:
-    if (PyErr_Occurred())
-    {
-        PyErr_WriteUnraisable(Py_None);
-        PyErr_Clear();
-    }
-    return result;
-}
-
-#pragma comment(lib, "user32.lib")
-
-static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
-{
-    Sleep(666);    /* may be interrupted if the whole process is closing */
-#if PY_MAJOR_VERSION >= 3
-    MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,
-                L"Python-CFFI embedding error",
-                MB_OK | MB_ICONERROR);
-#else
-    MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
-                "Python-CFFI embedding error",
-                MB_OK | MB_ICONERROR);
-#endif
-    _cffi_bootstrap_text = NULL;
-    return 0;
-}
-
-static void _cffi_stop_error_capture(PyObject *ecap)
-{
-    PyObject *s;
-    void *text;
-
-    if (ecap == (PyObject *)1)
-        return;
-
-    if (ecap == NULL)
-        goto error;
-
-    s = PyRun_String("done()", Py_eval_input, ecap, ecap);
-    if (s == NULL)
-        goto error;
-
-    /* Show a dialog box, but in a background thread, and
-       never show multiple dialog boxes at once. */
-#if PY_MAJOR_VERSION >= 3
-    text = PyUnicode_AsWideCharString(s, NULL);
-#else
-    text = PyString_AsString(s);
-#endif
-
-    _cffi_bootstrap_text = text;
-
-    if (text != NULL)
-    {
-        HANDLE h;
-        h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
-                         NULL, 0, NULL);
-        if (h != NULL)
-            CloseHandle(h);
-    }
-    /* decref the string, but it should stay alive as 'fl.buf'
-       in the small module above.  It will really be freed only if
-       we later get another similar error.  So it's a leak of at
-       most one copy of the small module.  That's fine for this
-       situation which is usually a "fatal error" anyway. */
-    Py_DECREF(s);
-    PyErr_Clear();
-    return;
-
-  error:
-    _cffi_bootstrap_text = NULL;
-    PyErr_Clear();
-}
-#endif
+#include "_cffi_errors.h"
 
 
 #define _cffi_call_python_org  _cffi_exports[_CFFI_CPIDX]
@@ -347,14 +222,10 @@
         /* Print as much information as potentially useful.
            Debugging load-time failures with embedding is not fun
         */
-#ifdef _MSC_VER
         PyObject *ecap;
-#endif
         PyObject *exception, *v, *tb, *f, *modules, *mod;
         PyErr_Fetch(&exception, &v, &tb);
-#ifdef _MSC_VER
         ecap = _cffi_start_error_capture();
-#endif
         f = PySys_GetObject((char *)"stderr");
         if (f != NULL && f != Py_None) {
             PyFile_WriteString(
@@ -387,9 +258,7 @@
             PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
             PyFile_WriteString("\n\n", f);
         }
-#ifdef _MSC_VER
         _cffi_stop_error_capture(ecap);
-#endif
     }
     result = -1;
     goto done;
diff --git a/cffi/recompiler.py b/cffi/recompiler.py
--- a/cffi/recompiler.py
+++ b/cffi/recompiler.py
@@ -308,6 +308,8 @@
                 base_module_name,))
             prnt('#endif')
             lines = self._rel_readlines('_embedding.h')
+            i = lines.index('#include "_cffi_errors.h"\n')
+            lines[i:i+1] = self._rel_readlines('_cffi_errors.h')
             prnt(''.join(lines))
             self.needs_version(VERSION_EMBEDDED)
         #
diff --git a/doc/source/whatsnew.rst b/doc/source/whatsnew.rst
--- a/doc/source/whatsnew.rst
+++ b/doc/source/whatsnew.rst
@@ -26,6 +26,18 @@
   cffi.FFI()`` at module level just after ``import cffi``; and in
   out-of-line mode you don't instantiate ``FFI`` explicitly at all.)
 
+* Windows: using callbacks can be messy because the CFFI internal error
+  messages show up to stderr---but stderr goes nowhere in many
+  applications.  This makes it particularly hard to get started with the
+  embedding mode.  (Once you get started, you can at least use
+  ``@ffi.def_extern(onerror=...)`` and send the error logs where it
+  makes sense for your application, or record them in log files, and so
+  on.)  So what is new in CFFI is that now, on Windows CFFI will try to
+  open a non-modal MessageBox (in addition to sending raw messages to
+  stderr).  The MessageBox is only visible if the process stays alive:
+  typically, console applications that crash close immediately, but that
+  is also the situation where stderr should be visible anyway.
+
 
 v1.10.1
 =======
_______________________________________________
pypy-commit mailing list
[email protected]
https://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to