@@ -70,31 +70,40 @@ int esp32_onOTARequest(char const * ota_url)
7070
7171String esp32_getOTAImageSHA256 ()
7272{
73- SHA256 sha256;
74-
75- uint32_t lengthLeft = ESP.getSketchSize ();
76-
7773 const esp_partition_t *running = esp_ota_get_running_partition ();
7874 if (!running) {
79- DEBUG_ERROR (" Partition could not be found" );
75+ DEBUG_ERROR (" ESP32::SHA256 Running partition could not be found" );
76+ return String ();
8077 }
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 ( );
8683 }
8784
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+
8890 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 ();
93100 }
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 ;
97104 }
105+ free (b);
106+
98107 /* Retrieve the final hash string. */
99108 uint8_t sha256_hash[SHA256::HASH_SIZE] = {0 };
100109 sha256.finalize (sha256_hash);
@@ -107,7 +116,7 @@ String esp32_getOTAImageSHA256()
107116 snprintf (buf, 4 , " %02X" , elem);
108117 sha256_str += buf;
109118 });
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 );
111120 return sha256_str;
112121}
113122
0 commit comments