loudmummer
loudmummer

Reputation: 554

Is there a way to safely modify mex files in MATLAB?

I am using someone else's code for my purpose. This code uses a .mex64 file generated from C code. There is a print statement in this file - it displays something onto the command window. I need to modify the text of this statement. I could recompile, but I do not have the complete source code.

When I open the mex64 file in a text editor, I can see the text to be printed in plain text. However, if I try to modify it and run it, matlab crashes with a System Error -

Abnormal termination:
Access violation

Here is how I attempted to recreate the problem. I wrote the following code -

#include <stdio.h>
#include "C:\Program Files\MATLAB\R2017b\extern\include\mex.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  main();
  return;
}

int main(){
    printf("Hello\n");
}

The mex64 file generated runs normally - prints the text "Hello". But when I located the word "Hello" in the mex64 file and modified it to "Hell", it crashed as described above. Looks like there is some sort of integrity check within MATLAB that fails.

Can someone explain what is happening?

Is there a way to somehow modify the mex64 file and successfully run it?

Upvotes: 4

Views: 437

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60680

If you change the text length, other stuff moves around in the file, making internal pointers wrong.

But this is probably not the only thing that is happening. Your text editor is likely changing the value of a lot of other bytes as well (e.g. values in the range 0-31 are meaningless in text, and often text editors will ignore them or change them).

You should do this in a binary file editor, these are often referred to as hex editor.

It is perfectly fine to change the value of bytes within a string in conpiled code. But only change their values, don’t remove or add any bytes.

You will notice that all strings end with a 0 byte. That is the end-of-string marker. Don’t overwrite it. But you can (usually) add one earlier to make the string shorter. That is, you add a zero byte at the end of your string, and don’t remove any of the bytes that come after.

Upvotes: 3

Related Questions