-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
pinMode() does not check valid pin number #149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This also affects Honestly I have no idea how this check was supposed to work. It would have made sense if pins_arduino.h defined
so that if you queried it with a (uint8_t) pin from 20 to 255 you'd get 0, thus failing the |
Fix for `pinMode()`, `digitalWrite()`, `digitalRead()` (issue #4605). Current behavior: look up pin number in `digital_pin_to_port_PGM[]` and then check if it returned `NOT_A_PIN`. Causes undefined behavior if provided `pin` number is out of the range of `digital_pin_to_port_PGM[]`. Proposed behavior (from issue #4605): check if `pin` is within the valid range of `digital_pin_to_port_PGM[]`, and THEN look it up. Additionally, remove second check for `port` not being `NOT_A_PIN` (which was useful for boards where the pin numbering skips some numbers). This can still be achieved by making `bit = digitalPinToBitMask(pin)` be 0 for invalid pins, which causes further bitwise operations such as `*reg &= ~bit;` and `*out |= bit;` to not actually modify the value of the register. (This removal makes the operation complete a bit faster for valid pins and slower for invalid pins, which I think is a good trade; plus it saves binary size.)
What's the worst case result of passing an invalid pin number to one of these functions using Arduino AVR Boards if no checks at all were done? Is it possible this could cause hardware damage on a board with no external connections or corrupt the firmware? If the answer is no then I think it would be best to just assume that the user is passing a valid pin number and remove the overhead of checking the validity of the value, including the current |
Well, looking up outside of the lookup table is undefined behavior, so in principle anything can happen. |
@mikaelpatel Good catch 👍 Could create a small PR for this? |
Back in the day I opened arduino/Arduino#4649, but it was closed after Chainsaw and never reopened. |
The current pinMode() implementation performs a digitalPinToPort(pin) and then checks the port for NOT_A_PORT but digitalPinToPort() is a program memory table read. It is possible to give an illegal pin number.
Possible correction is:
Replacing the port check with a pin number check (first).
Cheers!
The text was updated successfully, but these errors were encountered: