Skip to content
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

fix writing error on flash memory when address is unaligned #8588

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions cores/esp8266/Esp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -881,13 +881,39 @@ bool EspClass::flashWrite(uint32_t address, const uint8_t *data, size_t size) {
}
}
} else {
// Pointer is properly aligned and write does not cross page boundary,
// so use aligned write
if (!flashWrite(address, (uint32_t *)data, sizeLeft)) {
return false;
// If the flash address is not aligned, write a partial 4-bytes block and than re-check
// the alignment of data address of remaining data. This may lead to a reallocation and
// a significant stack usage.
if(address % 4){
size_t byteCount = 4 - (address % 4);

if (!flashReplaceBlock(address, data, byteCount)) {
return false;
}
// We will now have aligned address, so we can cross page boundaries
currentOffset += byteCount;
// Realign size to 4
sizeLeft = (size - byteCount) & ~3;

// Memory is unaligned, so we need to copy it to an aligned buffer
uint32_t alignedData[FLASH_PAGE_SIZE / sizeof(uint32_t)] __attribute__((aligned(4)));
memcpy(alignedData, data + currentOffset, sizeLeft);

// Pointer is properly aligned and write does not cross page boundary,
// so use aligned write
if (!flashWrite(address + currentOffset, alignedData, sizeLeft)) {
return false;
}
currentOffset += sizeLeft;
} else {
// Pointer is properly aligned and write does not cross page boundary,
// so use aligned write
if (!flashWrite(address, (uint32_t *)data, sizeLeft)) {
return false;
}
currentOffset = sizeLeft;
sizeLeft = 0;
}
currentOffset = sizeLeft;
sizeLeft = 0;
}
}
}
Expand Down