support icon indicating copy to clipboard operation
support copied to clipboard

[Bug] Hub crashes if exception is raised while handling unhandled exception.

Open dlech opened this issue 11 months ago • 0 comments

Describe the bug The unhandled exception handler does not handle exceptions. We call print_final_exception() but the print functions can also raise an exception. Since there is no nlr_push() to handle any exception, we end up crashing the hub and it reboots (or powers off on hubs that can't keep the power up long enough for a reset).

https://github.com/pybricks/pybricks-micropython/blob/master/bricks/_common/micropython.c#L108

To reproduce

The easiest way to reproduce this is to modify mp_hal_stdout_tx_strn() to not actually print and and just cause an infinite loop calling MICROPY_EVENT_POLL_HOOK.

        // pbio_error_t err = pbsys_bluetooth_tx((const uint8_t *)str, &size);
        pbio_error_t err = PBIO_ERROR_AGAIN;

Then download and run a program that prints something. (e.g. print("hi"))

The program will run forever because of the hacked print function. Press the stop button (hub button or Pybricks Code button) to stop the program. The firmware jumps to the function to print the unhandled SystemExit but gets stuck again in an infinite loop.

Press the stop button again. This time, there is nothing to catch the exception, so we end up in nlr_jump_fail().

Expected behavior This is how upstream MicroPython works, so maybe this is the expected behavior? But from a user point of view, having the hub go unresponsive and reset/power off isn't a great experience.

Solutions considered

  1. We should make sure print functions can't get stuck in an infinite loop like this. (This was a problem while testing the USB support pull request).
  2. We could disable the stop button from raising an exception for the duration of the unhandled exception handler.
  3. We could add a nlr_push() to catch exceptions and silently ignore them during the unhandled exception handler.

Note: these are not mutually exclusive options.

dlech avatar Feb 01 '25 16:02 dlech