Skip to content

Commit 8049216

Browse files
committed
Harden MATLAB matrix view unwrap
1 parent 43750f0 commit 8049216

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

matlab.h

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ extern "C" {
3737
#include <mex.h>
3838
}
3939

40+
#include <limits>
4041
#include <list>
4142
#include <set>
4243
#include <sstream>
@@ -432,11 +433,18 @@ gtsam::Matrix unwrap< gtsam::Matrix >(const mxArray* array) {
432433
// unwrap a MATLAB double matrix as a const Eigen matrix view without copying
433434
template <typename MatrixView>
434435
MatrixView unwrapMatrixView(const mxArray* array) {
435-
if (mxIsDouble(array)==false || mxIsComplex(array))
436-
error("unwrapMatrixView: not a real double matrix");
437-
int m = mxGetM(array), n = mxGetN(array);
436+
if (mxIsDouble(array)==false || mxIsComplex(array) || mxIsSparse(array))
437+
error("unwrapMatrixView: not a full real double matrix");
438+
const mwSize rows = mxGetM(array), cols = mxGetN(array);
439+
if (rows > static_cast<mwSize>(std::numeric_limits<Eigen::Index>::max()) ||
440+
cols > static_cast<mwSize>(std::numeric_limits<Eigen::Index>::max())) {
441+
error("unwrapMatrixView: matrix dimensions exceed Eigen::Index");
442+
}
443+
const Eigen::Index m = static_cast<Eigen::Index>(rows);
444+
const Eigen::Index n = static_cast<Eigen::Index>(cols);
438445
#ifdef DEBUG_WRAP
439-
mexPrintf("unwrapMatrixView called with %dx%d argument\n", m,n);
446+
mexPrintf("unwrapMatrixView called with %lldx%lld argument\n",
447+
static_cast<long long>(m), static_cast<long long>(n));
440448
#endif
441449
using Stride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
442450
using ConstMatrixMap = Eigen::Map<const gtsam::Matrix, 0, Stride>;

tests/test_matlab_wrapper.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ def test_matrix_view_arguments(self):
113113
header_content = f.read()
114114

115115
self.assertIn('unwrapMatrixView', header_content)
116+
self.assertIn('mxIsSparse(array)', header_content)
117+
self.assertIn('mwSize rows', header_content)
118+
self.assertIn('Eigen::Index m', header_content)
116119
self.assertIn('Stride(m, 1)', header_content)
117120

118121
def test_functions(self):

0 commit comments

Comments
 (0)