arduino / ArduinoCore-avr

The Official Arduino AVR core
https://www.arduino.cc
1.25k stars 1.06k forks source link

Stream#find does incorrect comparison #541

Open NathanSweet opened 1 year ago

NathanSweet commented 1 year ago

This code hangs forever, even when Serial repeatedly receives 0xCA, tested on Arduino Mega 2560 R3:

while (!Serial1.find(0xCA)) ;

The reason is in Stream findMulti: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Stream.cpp#L270

Consider this comparison:

if (c == t->str[t->index]) {

c is int with an unsigned value 0xCA. t->str is const char * with (on Arduino Mega 2560 R3) a signed value -54 decimal which as an unsigned value is 0xCA. In the comparison, the char is sign extended to an int, resulting in 0xFFFFFFCA giving:

if (0xCA == 0xFFFFFFCA) {

This is never true and not the intention. There appear to be other comparisons in Stream.cpp with this problem.

NathanSweet commented 1 year ago

Here is a fix:

    int cc = timedRead();
    if (cc < 0)
      return -1;
    char c = cc;

I leave it to those more familiar with this codebase to decide on the best fix.