modbus_check_response() crashes on an invalid exception code

Bug #241006 reported by Nicodemmus
4
Affects Status Importance Assigned to Milestone
libmodbus
Fix Released
Medium
Stéphane Raimbault

Bug Description

Hi,

I am using version 2.0 of the libmodbus library.

When an exception error is received, the application crashes. I found that the problem is in the following function:

static int modbus_check_response(modbus_param_t *mb_param,
                                 uint8_t *query,
                                 uint8_t *response)

the code that handles the invalid exception code starts at line 664 of the file modbus.c as is as follows (line numbers are in brackets):

[664] /* The chances are low to hit this
[665] case but can avoid a vicious
[666] segfault */
[667] char s_error[64];
[668] sprintf(s_error,
[669] "Invalid exception code %d",
[670] response[offset + 2]);
[671] error_treat(mb_param, INVALID_EXCEPTION_CODE,
[672] s_error);

[673] free(s_error);

[674] return INVALID_EXCEPTION_CODE;

As you can see in line 673, free() is used to deallocate the memory assigned to s_error. However s_error was not dynamically created (with malloc) and that is where the seg fault occurs.

Conclusion: free(s_error) in line 673 should be removed.

As the comment says, it is unlikely that this section of the code is ever executed, however, it happened to me and that's how I found the problem.

Regards,

P.S. Can someone please explain to me how to make a patch so I can attach code changes into to future bug reports? Maybe that way is easier to submit a fix for this kind of easy problems.

Related branches

Revision history for this message
Stéphane Raimbault (sra) wrote :

Thank you for your bug report.
The string was no more a dynamic allocation in libmodbus 2.0, I chose to not remove the free and to add a malloc!
Can you test this change from the trunk, please?

PS: you've a button to attach file on your bug report.

Changed in libmodbus:
assignee: nobody → sra
importance: Undecided → Medium
milestone: none → 2.0.1
Revision history for this message
Stéphane Raimbault (sra) wrote :

I've some problems to push my changes on Launchpad. I will try again in 24 hours...

Revision history for this message
Nicodemmus (jesusht) wrote :

I will be happy to try the fix as soon as it is in the trunk.

Please let me know when it is ready

Revision history for this message
Stéphane Raimbault (sra) wrote :

Pushed up!

Revision history for this message
Nicodemmus (jesusht) wrote :

Hi Stéphane,

I tried the fix and it works perfect.

Thanks for the quick response.

Changed in libmodbus:
status: New → Fix Released
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.