@@ -70,31 +70,40 @@ int esp32_onOTARequest(char const * ota_url)
70
70
71
71
String esp32_getOTAImageSHA256 ()
72
72
{
73
- SHA256 sha256;
74
-
75
- uint32_t lengthLeft = ESP.getSketchSize ();
76
-
77
73
const esp_partition_t *running = esp_ota_get_running_partition ();
78
74
if (!running) {
79
- DEBUG_ERROR (" Partition could not be found" );
75
+ DEBUG_ERROR (" ESP32::SHA256 Running partition could not be found" );
76
+ return String ();
80
77
}
81
- const size_t bufSize = SPI_FLASH_SEC_SIZE;
82
- std::unique_ptr< uint8_t []> buf ( new uint8_t [bufSize] );
83
- uint32_t offset = 0 ;
84
- if (!buf. get ()) {
85
- DEBUG_ERROR ( " Not enough memory to allocate buffer " );
78
+
79
+ uint8_t *b = ( uint8_t *) malloc (SPI_FLASH_SEC_SIZE );
80
+ if (b == nullptr ) {
81
+ DEBUG_ERROR ( " ESP32::SHA256 Not enough memory to allocate buffer " );
82
+ return String ( );
86
83
}
87
84
85
+ SHA256 sha256;
86
+ uint32_t const app_start = running->address ;
87
+ uint32_t const app_size = ESP.getSketchSize ();
88
+ uint32_t read_bytes = 0 ;
89
+
88
90
sha256.begin ();
89
- while ( lengthLeft > 0 ) {
90
- size_t readBytes = (lengthLeft < bufSize) ? lengthLeft : bufSize;
91
- if (!ESP.flashRead (running->address + offset, reinterpret_cast <uint32_t *>(buf.get ()), (readBytes + 3 ) & ~3 )) {
92
- DEBUG_ERROR (" Could not read buffer from flash" );
91
+ for (uint32_t a = app_start; read_bytes < app_size; )
92
+ {
93
+ /* Check if we are reading last sector and compute used size */
94
+ uint32_t const read_size = read_bytes + SPI_FLASH_SEC_SIZE < app_size ? SPI_FLASH_SEC_SIZE : app_size - read_bytes;
95
+
96
+ /* Use always 4 bytes aligned reads */
97
+ if (!ESP.flashRead (a, reinterpret_cast <uint32_t *>(b), (read_size + 3 ) & ~3 )) {
98
+ DEBUG_ERROR (" ESP32::SHA256 Could not read data from flash" );
99
+ return String ();
93
100
}
94
- sha256.update (buf. get (), readBytes );
95
- lengthLeft -= readBytes ;
96
- offset += readBytes ;
101
+ sha256.update (b, read_size );
102
+ a += read_size ;
103
+ read_bytes += read_size ;
97
104
}
105
+ free (b);
106
+
98
107
/* Retrieve the final hash string. */
99
108
uint8_t sha256_hash[SHA256::HASH_SIZE] = {0 };
100
109
sha256.finalize (sha256_hash);
@@ -107,7 +116,7 @@ String esp32_getOTAImageSHA256()
107
116
snprintf (buf, 4 , " %02X" , elem);
108
117
sha256_str += buf;
109
118
});
110
- DEBUG_VERBOSE (" SHA256: %d bytes (of %d) read" , ESP. getSketchSize () - lengthLeft, ESP. getSketchSize () );
119
+ DEBUG_VERBOSE (" SHA256: %d bytes (of %d) read" , read_bytes, app_size );
111
120
return sha256_str;
112
121
}
113
122
0 commit comments