Skip to content

Comments

[2.0.x] Fix crash upon repeated calls to process_subcommands_now_P#10509

Merged
thinkyhead merged 2 commits intoMarlinFirmware:bugfix-2.0.xfrom
marcio-ao:pr-fix-process-subcommands-now
Apr 24, 2018
Merged

[2.0.x] Fix crash upon repeated calls to process_subcommands_now_P#10509
thinkyhead merged 2 commits intoMarlinFirmware:bugfix-2.0.xfrom
marcio-ao:pr-fix-process-subcommands-now

Conversation

@marcio-ao
Copy link
Contributor

The first call to process_subcommands_now_P() would call parser.parse() on a buffer that was allocated on the stack. The parser would in turn store this pointer in parser.command_ptr, but this pointer would immediately become invalid when this call to process_subcommands_now_P() exited. A subsequent call to process_subcommands_now_P() would thus call strlen() on parser.command_ptr, now invalid, and thus crash Marlin.

This fix stores the value parser.command_ptr itself and restores it by value upon exit. This ensures that parser.command_ptr will not be left pointing to an invalid buffer.

This PR fixes a bug that was introduced in #10450, due to an attempt to make process_subcommands_now_P() safer (it did, but only once!)

 - The previous implementation would call parser.parse() on a
  buffer that was allocated on the stack. Parser.parse would
  in turn store this pointer in parser.command_ptr, but this
  pointer would become invalid upon the return of
  the first call to process_subcommands_now_P()
- A subsequent call to process_subcommands_now_P() would
  thus call strlen() on parser.command_ptr, now invalid,
  and thus crash Marlin.

This fix stores the value parser.command_ptr itself and
restores it upon exit, rather than replacing it to a pointer
to automatic data.
@marcio-ao marcio-ao force-pushed the pr-fix-process-subcommands-now branch from 4c75e7f to 0775ac9 Compare April 24, 2018 15:28
@thinkyhead
Copy link
Member

Hmm, yes, of course! This should work well. On invocation the command pointer points to a slot in the command queue which won't get overwritten until later on. (The queue slot is blocked from being re-used until the command exits.) If sub-commands call this function recursively then their strings will be on the stack. So, that's good. The stack will be smaller and this will run faster.

@marcio-ao
Copy link
Contributor Author

@thinkyhead : Yes, this was a counter-intuitive fix. Generally copying the data is a safe thing to do, but right here, the exact opposite was necessary.

@thinkyhead thinkyhead merged commit 02a711c into MarlinFirmware:bugfix-2.0.x Apr 24, 2018
@marcio-ao marcio-ao deleted the pr-fix-process-subcommands-now branch May 8, 2018 15:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants