vshymanskyy / TinyGSM

A small Arduino library for GSM modules, that just works
GNU Lesser General Public License v3.0
1.96k stars 728 forks source link

Crash when calling TinyGsmClient::connected on ESP32 #385

Closed xvinny-zz closed 4 years ago

xvinny-zz commented 4 years ago

I already found the bug, but I'm posting this anyway to the knowledge of the developer.

What type of issues is this?

[ ] Request to support a new module

[ ] Bug or problem compiling the library [X] Bug or issue with library functionality (ie, sending data over TCP/IP)

What are you working with?

Main processor board: Doit ESP32 (ESP-WROOM-32) Modem: SIM800L TinyGSM version: 0.10.5 Code:

TinyGsmClient client(modem);
if (client.connected())
...

Scenario, steps to reproduce

  1. Create TinyGsm instance
  2. Create TinyGsmClient instance
  3. Call TinyGsmClient::connected function

Expected result

The library should return 0.

Actual result

Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x400f4581  PS      : 0x00060b30  A0      : 0x800d3d2d  A1      : 0x3ffb1b20  
A2      : 0x00008f10  A3      : 0x3ffb1b4c  A4      : 0x3ffb8efc  A5      : 0x00000000  
A6      : 0x3ffc09a4  A7      : 0xffffffc1  A8      : 0x00000001  A9      : 0x3ffb1b00  
A10     : 0x00000000  A11     : 0x3ffb8f30  A12     : 0x80088400  A13     : 0x3ffb1a20  
A14     : 0x00000000  A15     : 0x3ffb0060  SAR     : 0x00000010  EXCCAUSE: 0x0000001c  
EXCVADDR: 0x00008f2c  LBEG    : 0x4000132c  LEND    : 0x40001346  LCOUNT  : 0x800da7ab  

Backtrace: 0x400f4581:0x3ffb1b20 0x400d3d2a:0x3ffb1b40 0x400d7e79:0x3ffb1b70 0x400db641:0x3ffb1fb0 0x40088215:0x3ffb1fd0

How did I solve?

The problem is at TinyGsmTCP.tpp, specifically on int GsmClient::available(). The function returns rx.size() + sock_available. As rx.size() returns a size_t type, which is an unsigned int and sock_available which is an uint16_t, there is some incompatibility on ESP which doesn't allow the sum of both types even that their value was 0 (what is the case).

It is crazy, but if you use the following code, the bug doesn't occur:

      ESP_LOGD("", "[available] Getting rx size...");
      int rxSize = rx.size();
      int socketAvailable = sock_available;
      ESP_LOGD("", "[available] Returning rxSize %d + sock_available: %d", rxSize, socketAvailable);
      return rxSize + socketAvailable;

If you comment this line -> ESP_LOGD("", "[available] Returning rxSize %d + sock_available: %d", rxSize, socketAvailable); the bug comes back!! It seems to be a compiler (xtensa) bug, or how the ESP32 deals with different integer types under a combination of a thousand factors (what happened in this case). Crazy!!

SRGDamia1 commented 4 years ago

That is very strange. I'm guessing this is problem #384 is having as well.

SRGDamia1 commented 4 years ago

Does adding a static cast before the addition solve the problem? static_cast<uint16_t>(rx.size()) + sock_available