Writing to a file in a callback corrupts the SD card when the file_id_object has closed
When running the following program which writes to SD card in a timer's callback. The SD card may become corrupt if the file has been closed before the callback has been set to None.
I discoverd this in a real example, but have written this version which you press the USR switch to close the file.
I'm running a pyboard version 1.1 and have edited my boot.py so the pyboard is a serial device and mouse.
Using a newly formatted SD Card, I insert the card into the pyboard and plug the pyboard into my laptop. I let the program run to completion.
I then start a REPL session and do a soft reboot. I press the USR switch to close the file during execution. The first time i do this everything looks ok. So I repeat the soft reboot and press the switch again, this time all my data has been lost there's only main.py left on the SD card.
PYB: sync filesystems
PYB: soft reboot
uncaught exception in Timer(4) interrupt handler
Traceback (most recent call last):
File "main.py", line 28, in timer_cb
OSError: [Errno 22] EINVAL
MicroPython v1.9.4-543-gdc77fdb7d on 2018-09-19; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> os.listdir()
['main.py', 'data-set.bin', 'data.001', 'new-file.bin']
>>> os.rename('new-file.bin', 'new.001')
>>>
PYB: sync filesystems
PYB: soft reboot
uncaught exception in Timer(4) interrupt handler
Traceback (most recent call last):
File "main.py", line 28, in timer_cb
OSError: [Errno 22] EINVAL
MicroPython v1.9.4-543-gdc77fdb7d on 2018-09-19; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> os.listdir()
['main.py']
when i plug the SD card into my laptop i can see files
data.001
main.py
new.001
new-file.bin
but no data-set.bin
Device Crashes Catastrophically when accessing SD in certain situations
Steps to reproduce
- Make sure device has SD Card inserted.
- Make sure device has SKIPSD on internal flash
- Run the following in main.py on internal flash. This puts my device in a boot loop.
It seems os.listdir('/') in another module crashes the device after throwing an exception with a file on the SD card.
Some devices fail the listdir in test with memory allocation fail 7958574 bytes and some devices get stuck in a boot loop, immediately crashing and restarting without displaying an error.
Using STM32F439 on these devices
import os
import pyb
print(os.listdir('/'))
with open('/flash/test.py', 'wb') as file:
file.write(b"import os\nos.listdir('/')\n")
if 'sd' not in os.listdir('/'):
os.mount(pyb.SD, '/sd')
print("os.mount() successful")
print(os.listdir('/'))
with open('/sd/test.txt', 'wb') as file:
for i in range(10000):
file.write(b"This is twenty bytes.")
file = open('/sd/test.txt', 'rb')
try:
a = file.read()
except MemoryError:
print('Exception thrown as expected')
print(os.listdir('/'))
import test