Search code examples
matlabshared-librariesreverse-engineeringbuilt-infunction-definition

How to locate where a built-in function is defined?


In MATLAB, there are roughly 3 ways to define functions: non-comment-only .m files, .p files, and compiled code (e.g. DLL, MEX).

Knowing where a function is defined could be helpful in several cases, such as when a breaking change was introduced to some function outside our control, and we'd like to try to revert to an old version in the hopes of getting our code working again; or when trying to reverse-engineering some undisclosed algorithm.

The which function is usually very good at identifying function definitions and their locations (which works for .m, .p and MEX), but isn't very useful when it comes to shared library functions, where (at best) it points to a comment-only documentation file:

>> which _mcheck
built-in (undocumented)

>> which svd
built-in (D:\Program Files\MATLAB\R2019a\toolbox\matlab\matfun\svd)

If so, assuming a function found within a shared library is called during the execution of my code, how can I locate the specific file (DLL) that contains it?


Solution

  • It turns out that dbstop can be used for this. For example:

    >> which svd
    built-in (D:\Program Files\MATLAB\R2019a\toolbox\matlab\matfun\svd)
    
    >> dbstop svd
    Warning: Entering debug mode is only supported within running MATLAB code files. 
    Warning: MATLAB debugger can only stop in MATLAB code files, and "libmwmathlinalg>svd" is not a MATLAB code file.
             Instead, the debugger will stop at the point right before "libmwmathlinalg>svd" is called.
    

    From there's it's just a matter of finding a file called libmwmathlinalg (with the relevant extension) - which isn't a difficult task if your drive is indexed.