Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: Fix segfault when an error occurs in np.fromfile #12354

Merged
merged 1 commit into from
Nov 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions numpy/core/include/numpy/npy_3kcompat.h
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,36 @@ npy_PyFile_CloseFile(PyObject *file)
}


/* This is a copy of _PyErr_ChainExceptions
*/
static NPY_INLINE void
npy_PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
{
if (exc == NULL)
return;

if (PyErr_Occurred()) {
/* only py3 supports this anyway */
#ifdef NPY_PY3K
PyObject *exc2, *val2, *tb2;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PyErr_Fetch(&exc2, &val2, &tb2);
PyErr_NormalizeException(&exc, &val, &tb);
if (tb != NULL) {
PyException_SetTraceback(val, tb);
Py_DECREF(tb);
}
Py_DECREF(exc);
PyErr_NormalizeException(&exc2, &val2, &tb2);
PyException_SetContext(val2, val);
PyErr_Restore(exc2, val2, tb2);
#endif
}
else {
PyErr_Restore(exc, val, tb);
}
}


/* This is a copy of _PyErr_ChainExceptions, with:
* - a minimal implementation for python 2
* - __cause__ used instead of __context__
Expand Down
11 changes: 10 additions & 1 deletion numpy/core/src/multiarray/multiarraymodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2044,6 +2044,7 @@ static PyObject *
array_fromfile(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds)
{
PyObject *file = NULL, *ret;
PyObject *err_type = NULL, *err_value = NULL, *err_traceback = NULL;
char *sep = "";
Py_ssize_t nin = -1;
static char *kwlist[] = {"file", "dtype", "count", "sep", NULL};
Expand Down Expand Up @@ -2079,18 +2080,26 @@ array_fromfile(PyObject *NPY_UNUSED(ignored), PyObject *args, PyObject *keywds)
}
ret = PyArray_FromFile(fp, type, (npy_intp) nin, sep);

/* If an exception is thrown in the call to PyArray_FromFile
* we need to clear it, and restore it later to ensure that
* we can cleanup the duplicated file descriptor properly.
*/
PyErr_Fetch(&err_type, &err_value, &err_traceback);
if (npy_PyFile_DupClose2(file, fp, orig_pos) < 0) {
npy_PyErr_ChainExceptions(err_type, err_value, err_traceback);
goto fail;
}
if (own && npy_PyFile_CloseFile(file) < 0) {
npy_PyErr_ChainExceptions(err_type, err_value, err_traceback);
goto fail;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be neat to call _PyErr_ChainExceptions here, although you'll need to add a backport of that in numpy\core\include\numpy\npy_3kcompat.h (almost identical to npy_PyErr_ChainExceptionsCause)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is part of the C-API that I'm not really familiar with - npy_PyErr_ChainExceptionsCause looks like it's almost identical to _PyErr_ChainExceptions.

What are the differences between them and why would I want to use one over the other?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_PyErr_ChainExceptions isn't available in python 2.7, which is why you can't use it directly.

_PyErr_ChainExceptions gives the behavior of

>>> try:
	raise ValueError
except:
	raise KeyError

Traceback (most recent call last):
  File "<pyshell#5>", line 2, in <module>
    raise ValueError
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#5>", line 4, in <module>
    raise KeyError
KeyError

While npy_PyErr_ChainExceptionsCause gives the behavior of:

>>> try:
	raise ValueError
except Exception as e:
	raise KeyError from e

Traceback (most recent call last):
  File "<pyshell#7>", line 2, in <module>
    raise ValueError
ValueError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<pyshell#7>", line 4, in <module>
    raise KeyError from e
KeyError

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the explanation, I've added the implementation of that and have used it.

}
PyErr_Restore(err_type, err_value, err_traceback);
Py_DECREF(file);
return ret;

fail:
Py_DECREF(file);
Py_DECREF(ret);
Py_XDECREF(ret);
return NULL;
}

Expand Down
13 changes: 13 additions & 0 deletions numpy/core/tests/test_multiarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -4541,6 +4541,19 @@ def test_file_position_after_tofile(self):
f.close()
assert_equal(pos, 10, err_msg=err_msg)

def test_load_object_array_fromfile(self):
# gh-12300
with open(self.filename, 'w') as f:
# Ensure we have a file with consistent contents
pass

with open(self.filename, 'rb') as f:
assert_raises_regex(ValueError, "Cannot read into object array",
np.fromfile, f, dtype=object)

assert_raises_regex(ValueError, "Cannot read into object array",
np.fromfile, self.filename, dtype=object)

def _check_from(self, s, value, **kw):
if 'sep' not in kw:
y = np.frombuffer(s, **kw)
Expand Down