From 0c68e7336b9cfd03612f82369da30aa4ff1545d0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org>
Date: Mon, 3 Jan 2022 17:20:07 +0100
Subject: [PATCH] perfect_foresight_problem MEX: error out properly when called
 MATLAB function triggers an exception

Closes: #1832
---
 .../DynamicModelCaller.cc                       | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/mex/sources/perfect_foresight_problem/DynamicModelCaller.cc b/mex/sources/perfect_foresight_problem/DynamicModelCaller.cc
index 9349cfbcb4..69db88dfb9 100644
--- a/mex/sources/perfect_foresight_problem/DynamicModelCaller.cc
+++ b/mex/sources/perfect_foresight_problem/DynamicModelCaller.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2019 Dynare Team
+ * Copyright © 2019-2022 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -139,7 +139,10 @@ DynamicModelMatlabCaller::eval(int it, double *resid)
 
     mxArray *exception = mexCallMATLABWithTrap(1, plhs, 6, prhs, funcname.c_str());
     if (exception)
-      error_msg = std::string{"An error occurred when calling "} + funcname;
+      {
+        error_msg = std::string{"An error occurred when calling "} + funcname;
+        return; // Avoid manipulating null pointers in plhs, see #1832
+      }
 
     mxDestroyArray(T_mx);
     T_mx = plhs[0];
@@ -152,7 +155,10 @@ DynamicModelMatlabCaller::eval(int it, double *resid)
 
     mxArray *exception = mexCallMATLABWithTrap(1, plhs, 7, prhs, funcname.c_str());
     if (exception)
-      error_msg = std::string{"An error occurred when calling "} + funcname;
+      {
+        error_msg = std::string{"An error occurred when calling "} + funcname;
+        return; // Avoid manipulating null pointers in plhs, see #1832
+      }
 
     if (mxIsComplex(plhs[0]))
       plhs[0] = cmplxToReal(plhs[0]);
@@ -169,7 +175,10 @@ DynamicModelMatlabCaller::eval(int it, double *resid)
 
       mxArray *exception = mexCallMATLABWithTrap(1, plhs, 7, prhs, funcname.c_str());
       if (exception)
-        error_msg = std::string{"An error occurred when calling "} + funcname;
+        {
+          error_msg = std::string{"An error occurred when calling "} + funcname;
+          return; // Avoid manipulating null pointers in plhs, see #1832
+        }
 
       if (jacobian_mx)
         {
-- 
GitLab