Skip to content

Refuse an impossible RTC date or time; stm: also what the calendar can't hold - #11959

Open
vegardw wants to merge 2 commits into
adafruit:mainfrom
vegardw:stm-rtc-set-time-range
Open

vegardw wants to merge 2 commits into
adafruit:mainfrom
vegardw:stm-rtc-set-time-range

Conversation

@vegardw

@vegardw vegardw commented Nov 25, 2026 •

Copy link
Copy Markdown

Refuses an impossible date or time when a struct_time is read, on every port, and on STM also a date or time the RTC calendar can't hold. It also stores the weekday of the date on STM instead of tm_wday. Two commits: the STM fix, then the general check moved to struct_time_to_tm(), as asked in review.

Problem

On STM, rtc.RTC().datetime = ... writes the fields straight into the RTC's BCD calendar registers through HAL_RTC_SetTime() and HAL_RTC_SetDate(). Their range checks are assert_param()s, which are compiled out, so anything is stored. On an STM32F412, 1999 read back as 2095, and (2026, 2, 30, 25, 61, 0, ...) read back unchanged.

tm_wday is stored as given too. Reading hides that, since struct_time_from_tm() works the weekday out from the date, but HAL_RTC_SetDate() shifts the weekday into the date register unmasked: tm_wday = 7 sets the lowest bit of the year, so (2026, 11, 24, 12, 0, 0, 7, -1, -1) read back as 2027-11-24.

On every port, struct_time_to_tm() narrows each field into a uint8_t (the year into a uint16_t) before the port sees it, so a month of 257 arrives as 1 and an hour of 256 as 0. And the ports that count seconds pass the month to timeutils_seconds_since_2000(), which reads its month table out of bounds for a month of 0.

Fix

struct_time_validate(), called from struct_time_to_tm() on the values before they are narrowed, raises ValueError unless they are a real date and time: tm_mon 1-12, tm_mday up to the month's length (Feb 29 only in leap years), tm_hour 0-23, tm_min 0-59, tm_sec 0-61 (leap seconds, as time.struct_time documents) and tm_year 1970-2099, the range py/mpconfig.h says the time functions handle on 32-bit boards. It takes the six values rather than a timeutils_struct_time_t, so that it can see them before narrowing; a caller that has a struct can pass its fields. tm_wday and tm_yday aren't checked: nothing that sets a clock uses them.

On STM, common_hal_rtc_set_time() adds what the calendar can't hold: tm_year 2000-2099 and tm_sec 0-59. stm32_peripherals_rtc_set_time() stores the weekday of the date, worked out with timeutils, instead of tm_wday.

time.time(), time.localtime() and alarm.time.TimeAlarm read the clock through struct_time_to_tm() too. Every port's clock starts at 1970 or 2000, except Silicon Labs', whose sleeptimer starts at 1900-01-01; it now starts at 2000-01-01 at reset, so time.localtime() doesn't raise before the clock is set. rtc.RTC.datetime's docstring says that an impossible date or time raises ValueError, and what STM32 boards hold.

The messages are the existing %q must be %d-%d, so there are no new strings to translate.

Testing

Check Base First commit only This PR
Valid dates read back, with the weekday of the date (6, two with a wrong tm_wday) 5 of 6: tm_wday = 7 read back as 2027 6 of 6 6 of 6
13 impossible values (years 1999 and 2100, months 0 and 13, days 0, 32, Feb 29 2026 and Apr 31, hours 24 and -1, minute 60, seconds 60 and 61) raise ValueError, clock kept none: all accepted all 13 all 13
6 values that narrowing turns into valid ones (month 257, day 257, hour, minute and second 256, year 67562) raise ValueError none none all 6
A time source returning Feb 30 makes time.localtime() raise; one in 1999 still works Feb 30 accepted Feb 30 accepted yes
time.mktime() still rolls Feb 30 over to Mar 2; time.monotonic() steady across a set yes yes yes
Size, STM (en_US, against main) +132 bytes (Feather F405: +176) +224 bytes (Feather F405: +280, Nucleo H743ZI2: +228); Meowbit ru keeps 5180 free
Size, other ports (en_US: Trinket M0, Feather M0 Express, Metro M4 Express, Feather nRF52840 Express, Pico, Pico 2; Silicon Labs xG24 Explorer Kit, xG24 Dev Kit, SparkFun Thing Plus MGM240P) unchanged +136 to +232 bytes; Silicon Labs +212

The board is the ELECFREAKS Retro Arcade (STM32F412RE; its board definition isn't upstream yet), on main 7d4ca58b48 plus the board's definition (the change's files are the same as on this branch's base), with the script below. With this PR, time.time() and time.localtime() still read the RTC as before. Not tested on other boards; the other ports were only built. On the Silicon Labs builds, the firmware calls the new common_hal_rtc_init() from port_init() right after sl_system_init().

How to run the test

On any STM board with the rtc module, copy the script as code.py and watch the serial console; it finishes within a second and sets the RTC and its time source back. Expect PASS for every check. Without this PR the impossible values are accepted, so the base run stores some of them.

set_time_test.py
# Copy to CIRCUITPY as code.py on an STM board with the rtc module. It prints its results on the
# serial console within a second.
#
# Sets rtc.RTC().datetime to dates and times the STM calendar can and can't hold. Without the
# change, every value is stored as given: 1999 reads back as 2095, Feb 30 and 25:61 are kept, and
# a tm_wday of 7 changes the year. struct_time_to_tm() also narrows each field to 8 bits (the year
# to 16), so a month of 257 arrives as 1. (The weekday read back is always worked out from the
# date.)
#
# PASS if every valid value reads back with the weekday of its date; every impossible one, also
# one that narrowing would turn into a valid value, raises ValueError and leaves the clock as it
# was; a time source with an impossible date raises ValueError and one in 1999 doesn't (the shared
# check allows 1970-2099; only the STM calendar needs 2000 or later); time.mktime() still rolls
# over; and time.monotonic() doesn't jump. The RTC and its time source are set back at the end.
import time

import rtc

r = rtc.RTC()
results = []


def report(ok, name):
    results.append(ok)
    print("PASS" if ok else "FAIL", name)


def weekday(year, month, day):
    # Monday is 0, as in time.struct_time. Sakamoto's method, independent of the firmware.
    offsets = (0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4)
    if month < 3:
        year -= 1
    sunday_based = (year + year // 4 - year // 100 + year // 400 + offsets[month - 1] + day) % 7
    return (sunday_based + 6) % 7


def stamp(year, month, day, hour=12, minute=0, second=0, wday=-1):
    return time.struct_time((year, month, day, hour, minute, second, wday, -1, -1))


class Source:
    # A time source for rtc.set_time_source() that always gives the same struct_time.
    def __init__(self, value):
        self.value = value

    @property
    def datetime(self):
        return self.value


start = r.datetime
start_monotonic = time.monotonic()

# 1. Valid values are stored; the weekday comes from the date, whatever tm_wday says.
for t in (
    stamp(2000, 1, 1, 0, 0, 0),
    stamp(2024, 2, 29, 23, 59, 30),
    stamp(2099, 12, 31, 23, 59, 0),
    stamp(2026, 11, 24, 12, 0, 58),
    stamp(2026, 11, 24, wday=7),
    stamp(2026, 11, 24, wday=4),
):
    r.datetime = t
    got = r.datetime
    same = tuple(got)[:5] == tuple(t)[:5] and got.tm_sec - t.tm_sec in (0, 1)
    want = weekday(t.tm_year, t.tm_mon, t.tm_mday)
    report(
        same and got.tm_wday == want,
        f"{tuple(t)[:7]} reads back {tuple(got)[:7]}, weekday {want} expected",
    )

# 2. Impossible values raise ValueError and leave the clock as it was. The last six would be
#    narrowed into valid ones (257 to 1, 256 to 0, 67562 to 2026) before a port could see them.
r.datetime = stamp(2026, 11, 24)
for fields in (
    (1999, 12, 31),
    (2100, 1, 1),
    (2026, 0, 1),
    (2026, 13, 1),
    (2026, 1, 0),
    (2026, 1, 32),
    (2026, 2, 29),
    (2026, 4, 31),
    (2026, 11, 24, 24),
    (2026, 11, 24, -1),
    (2026, 11, 24, 12, 60),
    (2026, 11, 24, 12, 0, 60),
    (2026, 11, 24, 12, 0, 61),
    (2026, 257, 1),
    (2026, 1, 257),
    (2026, 11, 24, 256),
    (2026, 11, 24, 12, 256),
    (2026, 11, 24, 12, 0, 256),
    (2026 + 65536, 11, 24),
):
    try:
        r.datetime = stamp(*fields)
        error = None
    except ValueError as e:
        error = e
    kept = tuple(r.datetime)[:5] == (2026, 11, 24, 12, 0)
    report(error is not None and kept, f"{fields}: {error or 'accepted'}; clock kept: {kept}")
    if not kept:
        r.datetime = stamp(2026, 11, 24)

# 3. The check covers every struct_time read, also from a time source. 1999 is fine there: the
#    shared check allows 1970-2099, and only the STM calendar needs 2000 or later.
rtc.set_time_source(Source(stamp(2026, 2, 30)))
try:
    got = time.localtime()
    error = None
except ValueError as e:
    error = e
report(error is not None, f"time source (2026, 2, 30): {error or 'accepted as ' + str(tuple(got)[:6])}")
rtc.set_time_source(Source(stamp(1999, 12, 31, 23, 59, 59)))
try:
    got = time.time()
    error = None
except ValueError as e:
    error = e
report(error is None and got == 946684799, f"time source (1999, 12, 31, 23, 59, 59): {error or got}")
rtc.set_time_source(r)

# 4. time.mktime() doesn't use the check: it still rolls over, Feb 30 to Mar 2 in 2026.
a = time.mktime(stamp(2026, 2, 30))
b = time.mktime(stamp(2026, 3, 2))
report(a == b, f"time.mktime((2026, 2, 30, ...)) == time.mktime((2026, 3, 2, ...)): {a} {b}")

# 5. Setting the clock doesn't move time.monotonic().
before = time.monotonic()
r.datetime = stamp(2050, 6, 15)
after = time.monotonic()
report(0 <= after - before < 0.1, f"time.monotonic() moved {after - before:.3f} s across a set")

rtc.set_time_source(r)
try:
    r.datetime = start
except ValueError:
    r.datetime = stamp(2000, 1, 1, 0, 0, 0)
print("Set back to", tuple(r.datetime)[:6], "after", f"{time.monotonic() - start_monotonic:.1f} s")
print(f"{results.count(True)} PASS, {results.count(False)} FAIL")

Trade-offs and Alternatives

  • Size on every port: the shared check adds 136-232 bytes on the non-STM boards built here. It could be turned off on very small ports if one doesn't fit; CI will show.
  • Behaviour change on the other ports: Feb 30, 24:00 and a minute of 60 now raise ValueError where they used to roll over. Leap seconds are still allowed and rolled over there; STM refuses them, since its calendar can't hold them.
  • Reads are checked too: struct_time_to_tm() also reads the time source for time.time(), time.localtime() and alarm.time.TimeAlarm, so a time source that returns an impossible date now raises there, instead of giving a wrong time. Reading rtc.RTC().datetime itself isn't checked, so a clock with a bad date can still be read and set. On the ports that count seconds since 2000, whose 32-bit count runs to 2106, reads would raise from 2100 on. time.mktime() doesn't use it and still rolls over.
  • Leap seconds on calendar clocks: the shared check allows seconds 60 and 61, as time.struct_time documents. Silicon Labs' sleeptimer refuses them, and its port ignores the error, so such a time is silently not set, as any bad value was before (mimxrt10xx probably likewise); Zephyr raises the driver's error. Not changed here.
  • Two messages for the year on STM: 1999 gives tm_year must be 2000-2099 (the port) and 2100 tm_year must be 1970-2099 (the shared check). One range would need a port-configurable range in the shared check, which would also refuse an STM time source's 1999.
  • Rolling over instead, in the STM port only, was also built and tested; it doesn't catch the narrowing, so the shared check was chosen in review.

Generative AI

I used generative AI (Claude Code) to write and test this change. I have reviewed it, and I am responsible for the code and this description.

🤖 Generated with Claude Code

rtc.RTC().datetime wrote the fields straight into the RTC's BCD
calendar, unchecked: 1999 read back as 2095, Feb 30 25:61 was kept, and
a tm_wday of 7 changed the year, since the HAL shifts the weekday into
the date register unmasked. Check the fields first and raise ValueError
for a year outside 2000-2099 or an impossible date or time. Store the
weekday of the date instead of tm_wday.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@dhalbert dhalbert left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, the validation should be done in a common place. Right now no other port validates the timeutils_struct_time_t fields.

I think it makes more sense to do the validation in struct_time_to_tm in shared-bindings/time/__init__.c. Then everyone benefits. But this will increase code size on every port.

Maybe there should even be a separate function to do the validation, so however the timeutils_struct_time_t is filled in, you can check it's OK. That function can be called in struct_time_to_tm.

If there are then specific things to validate for STM (like the 2099 limit), you can do that in the port.

@vegardw

vegardw commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

@dhalbert I had Claude test the two approaches: a shared implementation for every port, and rolling over like the other ports. Claude says:

One thing only the shared check catches: struct_time_to_tm() narrows the fields into a uint16_t year and uint8_ts before any port sees them, so this PR as it stands accepts a month of 257 as January, and 256 as 0 for an hour, minute or second. The check has to look at the integers before that, so struct_time_validate() takes the values rather than a timeutils_struct_time_t.

  • Shared check: struct_time_validate(), called from struct_time_to_tm(), refuses impossible dates and times on every port, with years 1970–2099 (what the time functions handle on 32-bit boards) and seconds up to 61, as struct_time documents. The STM port adds only what its calendar can't hold: years before 2000 and leap seconds. Flash: +224 bytes on STM (this PR: +132), and +136 to +232 on SAMD21, SAMD51, nRF52840, RP2040 and RP2350.
  • Rolling over: the STM port turns impossible values into real dates, as the ports that count seconds do (Feb 30 becomes Mar 1 or 2), and refuses only years outside 2000–2099. Flash: +76 bytes, STM only. Like the other ports, it doesn't catch the narrowing.

Both pass their tests on an ELECFREAKS Retro Arcade (STM32F412RE); this PR as submitted fails on the narrowed values.

Which would you prefer? I'll update the PR, its test and its description to match.

@dhalbert

Copy link
Copy Markdown
Collaborator

Which would you prefer? I'll update the PR, its test and its description to match.

Go ahead with a shared check, thanks. We could turn it off on very small ports if needed.

struct_time_to_tm() narrowed each field into timeutils_struct_time_t's
uint8_t and uint16_t members unchecked, so a month of 257 arrived as 1
and an hour of 256 as 0 on every port, and the ports that count seconds
read their month table out of bounds for a month of 0. Add
struct_time_validate(), which checks the values before they are
narrowed, and call it from struct_time_to_tm(): a real date and time,
years 1970-2099 (what timeutils handles on 32-bit boards) and seconds
up to 61, as struct_time documents. The STM port now checks only what
its calendar can't hold: years before 2000 and leap seconds.

time.localtime() reads the clock through struct_time_to_tm() too, and
the Silicon Labs sleeptimer's clock starts at 1900-01-01, so start it
at 2000-01-01 at reset, as the other ports start. Say in the
rtc.RTC.datetime docstring that impossible values raise ValueError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vegardw vegardw changed the title stm: refuse an RTC date or time the calendar can't hold Refuse an impossible RTC date or time; stm: also what the calendar can't hold Nov 26, 2026
@vegardw

vegardw commented Nov 26, 2026

Copy link
Copy Markdown
Author

I've pushed a second commit with the shared check, as you suggested:

  • struct_time_validate(), called from struct_time_to_tm(), checks the values before they are narrowed into timeutils_struct_time_t: a real date and time, years 1970-2099 (what the time functions handle on 32-bit boards) and seconds up to 61, as time.struct_time documents. The STM port now checks only what its calendar can't hold: years before 2000 and leap seconds.
  • time.localtime() reads the clock through struct_time_to_tm() too, and the Silicon Labs sleeptimer's clock starts at 1900-01-01, so the silabs port now starts it at 2000-01-01 at reset, as the other ports do.
  • The rtc.RTC.datetime docstring now says that an impossible date or time raises ValueError.

It adds 224 bytes on STM, 136-232 on the other ports built for this, and 212 on Silicon Labs. Tested on the Retro Arcade (STM32F412RE); the other boards were only built. The description has the details.

@vegardw
vegardw requested a review from dhalbert November 26, 2026 08:32
@bablokb

bablokb commented Nov 26, 2026

Copy link
Copy Markdown
  • The STM port now checks only what its calendar can't hold: years before 2000 and leap seconds.

Leap seconds are abandoned with decision from 15th. Oct., effective from May 20 next year. So one thing less to worry about (at least for a few thousand years, until the difference is larger than an hour).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants