Matlab EVAL – limit access scope to a selected subset of built-in functions / variables?

Viewed 40

Dear Stackoverflow Community,

There's a non-trivial issue in Matlab I'm currently being puzzled with. Perhaps someone has faced similar question before.

Imagine, there's some user input imported previously from an external ini-file, consisting of a list of variable names, variable values and an equation to evalute, e.g.

names    = { 'var1', 'var2' };
values   = {   1.23,   4.56 };
equation = 'db( var1 / var2 )';

Is there a clean way to evaluate such input to a result, limiting the access scope during the evaluation to user variables and built-in mathematical functions only?

The user variables can be assigned to a cleared workspace of a dedicated function, and the evaluation can be performed there, so that no other variables except for user ones will be accessible for the evaluation, e.g.:

% evaluate user function in a workspace containing user parameters only
function out = cleanEval( equation, names, values )

   % descend into a subfunction to operate on this workspace 
   out = cleanEvalCore( equation, names, values );

function out = cleanEvalCore( equation, names, values )

   % clear all variables from the caller workspace (we have them here)
   evalin( 'caller', 'clear' );

   % assign user variables from names/values to the caller workspace
   for ii = 1 : numel( names )
       assignin( 'caller', names{ ii }, values{ ii } );
   end

   % evaluate user function in the caller workspace
   out = evalin( 'caller', equation );

However, as long as 'eval' is used for evaluation, there's a possible misuse case to enter a third code into the user function, e.g.

names    = { 'var1', 'var2' };
values   = {   1.23,   4.56 };
equation = 'myGUI.closeWindow()';

or e.g.

equation = '!format C:\'; 

... which might lead to interesting consequences if evaluated as is.

Converting the equation string to a 'function handle of user variables' does not solve the issue, since any third command inside the equation will still be evaluated.

Is there a typical way to limit the scope for a single evaluation statement, so that it only can access the standard math functions (e.g. min/max/sin/cos/exp/log/db) or functions of a given list, but nothing else?

Or is there a way to evaluate the equation with some built-in math. engine instead of EVAL?

1 Answers
Related