Skip to content

Commit 289faaa

Browse files
MLXXXpfacchinm
authored andcommitted
Fix save/restore of magic key location during reset
In the USB CDC code to invoke an auto-reset, the magic key location could be restored before it had actually been saved. The sketch would then have a corrupted value at this location. This fix prevents the value from being restored if it hasn't previously been saved.
1 parent b084848 commit 289faaa

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

cores/arduino/CDC.cpp

+6-4
Original file line numberDiff line numberDiff line change
@@ -119,22 +119,24 @@ bool CDC_Setup(USBSetup& setup)
119119
if (1200 == _usbLineInfo.dwDTERate && (_usbLineInfo.lineState & 0x01) == 0)
120120
{
121121
#if MAGIC_KEY_POS != (RAMEND-1)
122-
// Backup ram value if its not a newer bootloader.
122+
// Backup ram value if its not a newer bootloader and it hasn't already been saved.
123123
// This should avoid memory corruption at least a bit, not fully
124-
if (magic_key_pos != (RAMEND-1)) {
124+
if (magic_key_pos != (RAMEND-1) && *(uint16_t *)magic_key_pos != MAGIC_KEY) {
125125
*(uint16_t *)(RAMEND-1) = *(uint16_t *)magic_key_pos;
126126
}
127127
#endif
128128
// Store boot key
129129
*(uint16_t *)magic_key_pos = MAGIC_KEY;
130130
wdt_enable(WDTO_120MS);
131131
}
132-
else
132+
else if (*(uint16_t *)magic_key_pos == MAGIC_KEY)
133133
{
134134
// Most OSs do some intermediate steps when configuring ports and DTR can
135135
// twiggle more than once before stabilizing.
136-
// To avoid spurious resets we set the watchdog to 250ms and eventually
136+
// To avoid spurious resets we set the watchdog to 120ms and eventually
137137
// cancel if DTR goes back high.
138+
// Cancellation is only done if an auto-reset was started, which is
139+
// indicated by the magic key having been set.
138140

139141
wdt_disable();
140142
wdt_reset();

0 commit comments

Comments
 (0)