test_nvs.cpp 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269
  1. // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. #include "catch.hpp"
  14. #include "nvs.hpp"
  15. #include "nvs_test_api.h"
  16. #include "sdkconfig.h"
  17. #ifdef CONFIG_NVS_ENCRYPTION
  18. #include "nvs_encr.hpp"
  19. #endif
  20. #include "spi_flash_emulation.h"
  21. #include <sstream>
  22. #include <iostream>
  23. #include <fstream>
  24. #include <dirent.h>
  25. #include <unistd.h>
  26. #include <sys/wait.h>
  27. #include <string.h>
  28. #include <string>
  29. #define TEST_ESP_ERR(rc, res) CHECK((rc) == (res))
  30. #define TEST_ESP_OK(rc) CHECK((rc) == ESP_OK)
  31. using namespace std;
  32. using namespace nvs;
  33. stringstream s_perf;
  34. void dumpBytes(const uint8_t* data, size_t count)
  35. {
  36. for (uint32_t i = 0; i < count; ++i) {
  37. if (i % 32 == 0) {
  38. printf("%08x ", i);
  39. }
  40. printf("%02x ", data[i]);
  41. if ((i + 1) % 32 == 0) {
  42. printf("\n");
  43. }
  44. }
  45. }
  46. TEST_CASE("crc32 behaves as expected", "[nvs]")
  47. {
  48. Item item1;
  49. item1.datatype = ItemType::I32;
  50. item1.nsIndex = 1;
  51. item1.crc32 = 0;
  52. item1.chunkIndex = 0xff;
  53. fill_n(item1.key, sizeof(item1.key), 0xbb);
  54. fill_n(item1.data, sizeof(item1.data), 0xaa);
  55. auto crc32_1 = item1.calculateCrc32();
  56. Item item2 = item1;
  57. item2.crc32 = crc32_1;
  58. CHECK(crc32_1 == item2.calculateCrc32());
  59. item2 = item1;
  60. item2.nsIndex = 2;
  61. CHECK(crc32_1 != item2.calculateCrc32());
  62. item2 = item1;
  63. item2.datatype = ItemType::U32;
  64. CHECK(crc32_1 != item2.calculateCrc32());
  65. item2 = item1;
  66. strncpy(item2.key, "foo", Item::MAX_KEY_LENGTH);
  67. CHECK(crc32_1 != item2.calculateCrc32());
  68. }
  69. TEST_CASE("starting with empty flash, page is in uninitialized state", "[nvs]")
  70. {
  71. SpiFlashEmulator emu(1);
  72. Page page;
  73. CHECK(page.state() == Page::PageState::INVALID);
  74. CHECK(page.load(0) == ESP_OK);
  75. CHECK(page.state() == Page::PageState::UNINITIALIZED);
  76. }
  77. TEST_CASE("can distinguish namespaces", "[nvs]")
  78. {
  79. SpiFlashEmulator emu(1);
  80. Page page;
  81. CHECK(page.load(0) == ESP_OK);
  82. int32_t val1 = 0x12345678;
  83. CHECK(page.writeItem(1, ItemType::I32, "intval1", &val1, sizeof(val1)) == ESP_OK);
  84. int32_t val2 = 0x23456789;
  85. CHECK(page.writeItem(2, ItemType::I32, "intval1", &val2, sizeof(val2)) == ESP_OK);
  86. int32_t readVal;
  87. CHECK(page.readItem(2, ItemType::I32, "intval1", &readVal, sizeof(readVal)) == ESP_OK);
  88. CHECK(readVal == val2);
  89. }
  90. TEST_CASE("reading with different type causes type mismatch error", "[nvs]")
  91. {
  92. SpiFlashEmulator emu(1);
  93. Page page;
  94. CHECK(page.load(0) == ESP_OK);
  95. int32_t val = 0x12345678;
  96. CHECK(page.writeItem(1, ItemType::I32, "intval1", &val, sizeof(val)) == ESP_OK);
  97. CHECK(page.readItem(1, ItemType::U32, "intval1", &val, sizeof(val)) == ESP_ERR_NVS_TYPE_MISMATCH);
  98. }
  99. TEST_CASE("when page is erased, it's state becomes UNITIALIZED", "[nvs]")
  100. {
  101. SpiFlashEmulator emu(1);
  102. Page page;
  103. CHECK(page.load(0) == ESP_OK);
  104. int32_t val = 0x12345678;
  105. CHECK(page.writeItem(1, ItemType::I32, "intval1", &val, sizeof(val)) == ESP_OK);
  106. CHECK(page.erase() == ESP_OK);
  107. CHECK(page.state() == Page::PageState::UNINITIALIZED);
  108. }
  109. TEST_CASE("when writing and erasing, used/erased counts are updated correctly", "[nvs]")
  110. {
  111. SpiFlashEmulator emu(1);
  112. Page page;
  113. CHECK(page.load(0) == ESP_OK);
  114. CHECK(page.getUsedEntryCount() == 0);
  115. CHECK(page.getErasedEntryCount() == 0);
  116. uint32_t foo1 = 0;
  117. CHECK(page.writeItem(1, "foo1", foo1) == ESP_OK);
  118. CHECK(page.getUsedEntryCount() == 1);
  119. CHECK(page.writeItem(2, "foo1", foo1) == ESP_OK);
  120. CHECK(page.getUsedEntryCount() == 2);
  121. CHECK(page.eraseItem<uint32_t>(2, "foo1") == ESP_OK);
  122. CHECK(page.getUsedEntryCount() == 1);
  123. CHECK(page.getErasedEntryCount() == 1);
  124. for (size_t i = 0; i < Page::ENTRY_COUNT - 2; ++i) {
  125. char name[16];
  126. snprintf(name, sizeof(name), "i%ld", (long int)i);
  127. CHECK(page.writeItem(1, name, i) == ESP_OK);
  128. }
  129. CHECK(page.getUsedEntryCount() == Page::ENTRY_COUNT - 1);
  130. CHECK(page.getErasedEntryCount() == 1);
  131. for (size_t i = 0; i < Page::ENTRY_COUNT - 2; ++i) {
  132. char name[16];
  133. snprintf(name, sizeof(name), "i%ld", (long int)i);
  134. CHECK(page.eraseItem(1, itemTypeOf<size_t>(), name) == ESP_OK);
  135. }
  136. CHECK(page.getUsedEntryCount() == 1);
  137. CHECK(page.getErasedEntryCount() == Page::ENTRY_COUNT - 1);
  138. }
  139. TEST_CASE("when page is full, adding an element fails", "[nvs]")
  140. {
  141. SpiFlashEmulator emu(1);
  142. Page page;
  143. CHECK(page.load(0) == ESP_OK);
  144. for (size_t i = 0; i < Page::ENTRY_COUNT; ++i) {
  145. char name[16];
  146. snprintf(name, sizeof(name), "i%ld", (long int)i);
  147. CHECK(page.writeItem(1, name, i) == ESP_OK);
  148. }
  149. CHECK(page.writeItem(1, "foo", 64UL) == ESP_ERR_NVS_PAGE_FULL);
  150. }
  151. TEST_CASE("page maintains its seq number")
  152. {
  153. SpiFlashEmulator emu(1);
  154. {
  155. Page page;
  156. CHECK(page.load(0) == ESP_OK);
  157. CHECK(page.setSeqNumber(123) == ESP_OK);
  158. int32_t val = 42;
  159. CHECK(page.writeItem(1, ItemType::I32, "dummy", &val, sizeof(val)) == ESP_OK);
  160. }
  161. {
  162. Page page;
  163. CHECK(page.load(0) == ESP_OK);
  164. uint32_t seqno;
  165. CHECK(page.getSeqNumber(seqno) == ESP_OK);
  166. CHECK(seqno == 123);
  167. }
  168. }
  169. TEST_CASE("can write and read variable length data", "[nvs]")
  170. {
  171. SpiFlashEmulator emu(1);
  172. Page page;
  173. CHECK(page.load(0) == ESP_OK);
  174. const char str[] = "foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234";
  175. size_t len = strlen(str);
  176. CHECK(page.writeItem(1, "stuff1", 42) == ESP_OK);
  177. CHECK(page.writeItem(1, "stuff2", 1) == ESP_OK);
  178. CHECK(page.writeItem(1, ItemType::SZ, "foobaar", str, len + 1) == ESP_OK);
  179. CHECK(page.writeItem(1, "stuff3", 2) == ESP_OK);
  180. CHECK(page.writeItem(1, ItemType::BLOB, "baz", str, len) == ESP_OK);
  181. CHECK(page.writeItem(1, "stuff4", 0x7abbccdd) == ESP_OK);
  182. char buf[sizeof(str) + 16];
  183. int32_t value;
  184. CHECK(page.readItem(1, "stuff1", value) == ESP_OK);
  185. CHECK(value == 42);
  186. CHECK(page.readItem(1, "stuff2", value) == ESP_OK);
  187. CHECK(value == 1);
  188. CHECK(page.readItem(1, "stuff3", value) == ESP_OK);
  189. CHECK(value == 2);
  190. CHECK(page.readItem(1, "stuff4", value) == ESP_OK);
  191. CHECK(value == 0x7abbccdd);
  192. fill_n(buf, sizeof(buf), 0xff);
  193. CHECK(page.readItem(1, ItemType::SZ, "foobaar", buf, sizeof(buf)) == ESP_OK);
  194. CHECK(memcmp(buf, str, strlen(str) + 1) == 0);
  195. fill_n(buf, sizeof(buf), 0xff);
  196. CHECK(page.readItem(1, ItemType::BLOB, "baz", buf, sizeof(buf)) == ESP_OK);
  197. CHECK(memcmp(buf, str, strlen(str)) == 0);
  198. }
  199. TEST_CASE("different key names are distinguished even if the pointer is the same", "[nvs]")
  200. {
  201. SpiFlashEmulator emu(1);
  202. Page page;
  203. TEST_ESP_OK(page.load(0));
  204. TEST_ESP_OK(page.writeItem(1, "i1", 1));
  205. TEST_ESP_OK(page.writeItem(1, "i2", 2));
  206. int32_t value;
  207. char keyname[10] = {0};
  208. for (int i = 0; i < 2; ++i) {
  209. strncpy(keyname, "i1", sizeof(keyname) - 1);
  210. TEST_ESP_OK(page.readItem(1, keyname, value));
  211. CHECK(value == 1);
  212. strncpy(keyname, "i2", sizeof(keyname) - 1);
  213. TEST_ESP_OK(page.readItem(1, keyname, value));
  214. CHECK(value == 2);
  215. }
  216. }
  217. TEST_CASE("Page validates key size", "[nvs]")
  218. {
  219. SpiFlashEmulator emu(4);
  220. Page page;
  221. TEST_ESP_OK(page.load(0));
  222. // 16-character key fails
  223. TEST_ESP_ERR(page.writeItem(1, "0123456789123456", 1), ESP_ERR_NVS_KEY_TOO_LONG);
  224. // 15-character key is okay
  225. TEST_ESP_OK(page.writeItem(1, "012345678912345", 1));
  226. }
  227. TEST_CASE("Page validates blob size", "[nvs]")
  228. {
  229. SpiFlashEmulator emu(4);
  230. Page page;
  231. TEST_ESP_OK(page.load(0));
  232. char buf[2048] = { 0 };
  233. // There are two potential errors here:
  234. // - not enough space in the page (because one value has been written already)
  235. // - value is too long
  236. // Check that the second one is actually returned.
  237. TEST_ESP_ERR(page.writeItem(1, ItemType::BLOB, "2", buf, Page::ENTRY_COUNT * Page::ENTRY_SIZE), ESP_ERR_NVS_VALUE_TOO_LONG);
  238. // Should fail as well
  239. TEST_ESP_ERR(page.writeItem(1, ItemType::BLOB, "2", buf, Page::CHUNK_MAX_SIZE + 1), ESP_ERR_NVS_VALUE_TOO_LONG);
  240. TEST_ESP_OK(page.writeItem(1, ItemType::BLOB, "2", buf, Page::CHUNK_MAX_SIZE));
  241. }
  242. TEST_CASE("Page handles invalid CRC of variable length items", "[nvs][cur]")
  243. {
  244. SpiFlashEmulator emu(4);
  245. {
  246. Page page;
  247. TEST_ESP_OK(page.load(0));
  248. char buf[128] = {0};
  249. TEST_ESP_OK(page.writeItem(1, ItemType::BLOB, "1", buf, sizeof(buf)));
  250. }
  251. // corrupt header of the item (64 is the offset of the first item in page)
  252. uint32_t overwrite_buf = 0;
  253. emu.write(64, &overwrite_buf, 4);
  254. // load page again
  255. {
  256. Page page;
  257. TEST_ESP_OK(page.load(0));
  258. }
  259. }
  260. class HashListTestHelper : public HashList
  261. {
  262. public:
  263. size_t getBlockCount()
  264. {
  265. return mBlockList.size();
  266. }
  267. };
  268. TEST_CASE("HashList is cleaned up as soon as items are erased", "[nvs]")
  269. {
  270. HashListTestHelper hashlist;
  271. // Add items
  272. const size_t count = 128;
  273. for (size_t i = 0; i < count; ++i) {
  274. char key[16];
  275. snprintf(key, sizeof(key), "i%ld", (long int)i);
  276. Item item(1, ItemType::U32, 1, key);
  277. hashlist.insert(item, i);
  278. }
  279. INFO("Added " << count << " items, " << hashlist.getBlockCount() << " blocks");
  280. // Remove them in reverse order
  281. for (size_t i = count; i > 0; --i) {
  282. hashlist.erase(i - 1, true);
  283. }
  284. CHECK(hashlist.getBlockCount() == 0);
  285. // Add again
  286. for (size_t i = 0; i < count; ++i) {
  287. char key[16];
  288. snprintf(key, sizeof(key), "i%ld", (long int)i);
  289. Item item(1, ItemType::U32, 1, key);
  290. hashlist.insert(item, i);
  291. }
  292. INFO("Added " << count << " items, " << hashlist.getBlockCount() << " blocks");
  293. // Remove them in the same order
  294. for (size_t i = 0; i < count; ++i) {
  295. hashlist.erase(i, true);
  296. }
  297. CHECK(hashlist.getBlockCount() == 0);
  298. }
  299. TEST_CASE("can init PageManager in empty flash", "[nvs]")
  300. {
  301. SpiFlashEmulator emu(4);
  302. PageManager pm;
  303. CHECK(pm.load(0, 4) == ESP_OK);
  304. }
  305. TEST_CASE("PageManager adds page in the correct order", "[nvs]")
  306. {
  307. const size_t pageCount = 8;
  308. SpiFlashEmulator emu(pageCount);
  309. uint32_t pageNo[pageCount] = { -1U, 50, 11, -1U, 23, 22, 24, 49};
  310. for (uint32_t i = 0; i < pageCount; ++i) {
  311. Page p;
  312. p.load(i);
  313. if (pageNo[i] != -1U) {
  314. p.setSeqNumber(pageNo[i]);
  315. p.writeItem(1, "foo", 10U);
  316. }
  317. }
  318. PageManager pageManager;
  319. CHECK(pageManager.load(0, pageCount) == ESP_OK);
  320. uint32_t lastSeqNo = 0;
  321. for (auto it = std::begin(pageManager); it != std::end(pageManager); ++it) {
  322. uint32_t seqNo;
  323. CHECK(it->getSeqNumber(seqNo) == ESP_OK);
  324. CHECK(seqNo > lastSeqNo);
  325. }
  326. }
  327. TEST_CASE("can init storage in empty flash", "[nvs]")
  328. {
  329. SpiFlashEmulator emu(8);
  330. Storage storage;
  331. emu.setBounds(4, 8);
  332. CHECK(storage.init(4, 4) == ESP_OK);
  333. s_perf << "Time to init empty storage (4 sectors): " << emu.getTotalTime() << " us" << std::endl;
  334. }
  335. TEST_CASE("storage doesn't add duplicates within one page", "[nvs]")
  336. {
  337. SpiFlashEmulator emu(8);
  338. Storage storage;
  339. emu.setBounds(4, 8);
  340. CHECK(storage.init(4, 4) == ESP_OK);
  341. int bar = 0;
  342. CHECK(storage.writeItem(1, "bar", ++bar) == ESP_OK);
  343. CHECK(storage.writeItem(1, "bar", ++bar) == ESP_OK);
  344. Page page;
  345. page.load(4);
  346. CHECK(page.getUsedEntryCount() == 1);
  347. CHECK(page.getErasedEntryCount() == 1);
  348. }
  349. TEST_CASE("can write one item a thousand times", "[nvs]")
  350. {
  351. SpiFlashEmulator emu(8);
  352. Storage storage;
  353. emu.setBounds(4, 8);
  354. CHECK(storage.init(4, 4) == ESP_OK);
  355. for (size_t i = 0; i < Page::ENTRY_COUNT * 4 * 2; ++i) {
  356. REQUIRE(storage.writeItem(1, "i", static_cast<int>(i)) == ESP_OK);
  357. }
  358. s_perf << "Time to write one item a thousand times: " << emu.getTotalTime() << " us (" << emu.getEraseOps() << " " << emu.getWriteOps() << " " << emu.getReadOps() << " " << emu.getWriteBytes() << " " << emu.getReadBytes() << ")" << std::endl;
  359. }
  360. TEST_CASE("storage doesn't add duplicates within multiple pages", "[nvs]")
  361. {
  362. SpiFlashEmulator emu(8);
  363. Storage storage;
  364. emu.setBounds(4, 8);
  365. CHECK(storage.init(4, 4) == ESP_OK);
  366. int bar = 0;
  367. CHECK(storage.writeItem(1, "bar", ++bar) == ESP_OK);
  368. for (size_t i = 0; i < Page::ENTRY_COUNT; ++i) {
  369. CHECK(storage.writeItem(1, "foo", static_cast<int>(++bar)) == ESP_OK);
  370. }
  371. CHECK(storage.writeItem(1, "bar", ++bar) == ESP_OK);
  372. Page page;
  373. page.load(4);
  374. CHECK(page.findItem(1, itemTypeOf<int>(), "bar") == ESP_ERR_NVS_NOT_FOUND);
  375. page.load(5);
  376. CHECK(page.findItem(1, itemTypeOf<int>(), "bar") == ESP_OK);
  377. }
  378. TEST_CASE("storage can find items on second page if first is not fully written and has cached search data", "[nvs]")
  379. {
  380. SpiFlashEmulator emu(3);
  381. Storage storage;
  382. CHECK(storage.init(0, 3) == ESP_OK);
  383. int bar = 0;
  384. uint8_t bigdata[(Page::CHUNK_MAX_SIZE - Page::ENTRY_SIZE)/2] = {0};
  385. // write one big chunk of data
  386. ESP_ERROR_CHECK(storage.writeItem(0, ItemType::BLOB, "1", bigdata, sizeof(bigdata)));
  387. // write another big chunk of data
  388. ESP_ERROR_CHECK(storage.writeItem(0, ItemType::BLOB, "2", bigdata, sizeof(bigdata)));
  389. // write third one; it will not fit into the first page
  390. ESP_ERROR_CHECK(storage.writeItem(0, ItemType::BLOB, "3", bigdata, sizeof(bigdata)));
  391. size_t size;
  392. ESP_ERROR_CHECK(storage.getItemDataSize(0, ItemType::BLOB, "1", size));
  393. CHECK(size == sizeof(bigdata));
  394. ESP_ERROR_CHECK(storage.getItemDataSize(0, ItemType::BLOB, "3", size));
  395. CHECK(size == sizeof(bigdata));
  396. }
  397. TEST_CASE("can write and read variable length data lots of times", "[nvs]")
  398. {
  399. SpiFlashEmulator emu(8);
  400. Storage storage;
  401. emu.setBounds(4, 8);
  402. CHECK(storage.init(4, 4) == ESP_OK);
  403. const char str[] = "foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234";
  404. char buf[sizeof(str) + 16];
  405. size_t len = strlen(str);
  406. for (size_t i = 0; i < Page::ENTRY_COUNT * 4 * 2; ++i) {
  407. CAPTURE(i);
  408. CHECK(storage.writeItem(1, ItemType::SZ, "foobaar", str, len + 1) == ESP_OK);
  409. CHECK(storage.writeItem(1, "foo", static_cast<uint32_t>(i)) == ESP_OK);
  410. uint32_t value;
  411. CHECK(storage.readItem(1, "foo", value) == ESP_OK);
  412. CHECK(value == i);
  413. fill_n(buf, sizeof(buf), 0xff);
  414. CHECK(storage.readItem(1, ItemType::SZ, "foobaar", buf, sizeof(buf)) == ESP_OK);
  415. CHECK(memcmp(buf, str, strlen(str) + 1) == 0);
  416. }
  417. s_perf << "Time to write one string and one integer a thousand times: " << emu.getTotalTime() << " us (" << emu.getEraseOps() << " " << emu.getWriteOps() << " " << emu.getReadOps() << " " << emu.getWriteBytes() << " " << emu.getReadBytes() << ")" << std::endl;
  418. }
  419. TEST_CASE("can get length of variable length data", "[nvs]")
  420. {
  421. SpiFlashEmulator emu(8);
  422. emu.randomize(200);
  423. Storage storage;
  424. emu.setBounds(4, 8);
  425. CHECK(storage.init(4, 4) == ESP_OK);
  426. const char str[] = "foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234foobar1234";
  427. size_t len = strlen(str);
  428. CHECK(storage.writeItem(1, ItemType::SZ, "foobaar", str, len + 1) == ESP_OK);
  429. size_t dataSize;
  430. CHECK(storage.getItemDataSize(1, ItemType::SZ, "foobaar", dataSize) == ESP_OK);
  431. CHECK(dataSize == len + 1);
  432. CHECK(storage.writeItem(2, ItemType::BLOB, "foobaar", str, len) == ESP_OK);
  433. CHECK(storage.getItemDataSize(2, ItemType::BLOB, "foobaar", dataSize) == ESP_OK);
  434. CHECK(dataSize == len);
  435. }
  436. TEST_CASE("can create namespaces", "[nvs]")
  437. {
  438. SpiFlashEmulator emu(8);
  439. Storage storage;
  440. emu.setBounds(4, 8);
  441. CHECK(storage.init(4, 4) == ESP_OK);
  442. uint8_t nsi;
  443. CHECK(storage.createOrOpenNamespace("wifi", false, nsi) == ESP_ERR_NVS_NOT_FOUND);
  444. CHECK(storage.createOrOpenNamespace("wifi", true, nsi) == ESP_OK);
  445. Page page;
  446. page.load(4);
  447. CHECK(page.findItem(Page::NS_INDEX, ItemType::U8, "wifi") == ESP_OK);
  448. }
  449. TEST_CASE("storage may become full", "[nvs]")
  450. {
  451. SpiFlashEmulator emu(8);
  452. Storage storage;
  453. emu.setBounds(4, 8);
  454. CHECK(storage.init(4, 4) == ESP_OK);
  455. for (size_t i = 0; i < Page::ENTRY_COUNT * 3; ++i) {
  456. char name[Item::MAX_KEY_LENGTH + 1];
  457. snprintf(name, sizeof(name), "key%05d", static_cast<int>(i));
  458. REQUIRE(storage.writeItem(1, name, static_cast<int>(i)) == ESP_OK);
  459. }
  460. REQUIRE(storage.writeItem(1, "foo", 10) == ESP_ERR_NVS_NOT_ENOUGH_SPACE);
  461. }
  462. TEST_CASE("can modify an item on a page which will be erased", "[nvs]")
  463. {
  464. SpiFlashEmulator emu(2);
  465. Storage storage;
  466. CHECK(storage.init(0, 2) == ESP_OK);
  467. for (size_t i = 0; i < Page::ENTRY_COUNT * 3 + 1; ++i) {
  468. REQUIRE(storage.writeItem(1, "foo", 42U) == ESP_OK);
  469. }
  470. }
  471. TEST_CASE("can erase items", "[nvs]")
  472. {
  473. SpiFlashEmulator emu(3);
  474. Storage storage;
  475. CHECK(storage.init(0, 3) == ESP_OK);
  476. for (size_t i = 0; i < Page::ENTRY_COUNT * 2 - 3; ++i) {
  477. char name[Item::MAX_KEY_LENGTH + 1];
  478. snprintf(name, sizeof(name), "key%05d", static_cast<int>(i));
  479. REQUIRE(storage.writeItem(3, name, static_cast<int>(i)) == ESP_OK);
  480. }
  481. CHECK(storage.writeItem(1, "foo", 32) == ESP_OK);
  482. CHECK(storage.writeItem(2, "foo", 64) == ESP_OK);
  483. CHECK(storage.eraseItem(2, "foo") == ESP_OK);
  484. int val;
  485. CHECK(storage.readItem(1, "foo", val) == ESP_OK);
  486. CHECK(val == 32);
  487. CHECK(storage.eraseNamespace(3) == ESP_OK);
  488. CHECK(storage.readItem(2, "foo", val) == ESP_ERR_NVS_NOT_FOUND);
  489. CHECK(storage.readItem(3, "key00222", val) == ESP_ERR_NVS_NOT_FOUND);
  490. }
  491. TEST_CASE("nvs api tests", "[nvs]")
  492. {
  493. SpiFlashEmulator emu(10);
  494. emu.randomize(100);
  495. nvs_handle_t handle_1;
  496. const uint32_t NVS_FLASH_SECTOR = 6;
  497. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 3;
  498. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  499. TEST_ESP_ERR(nvs_open("namespace1", NVS_READWRITE, &handle_1), ESP_ERR_NVS_NOT_INITIALIZED);
  500. for (uint16_t i = NVS_FLASH_SECTOR; i <NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN; ++i) {
  501. spi_flash_erase_sector(i);
  502. }
  503. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  504. TEST_ESP_ERR(nvs_open("namespace1", NVS_READONLY, &handle_1), ESP_ERR_NVS_NOT_FOUND);
  505. // TEST_ESP_ERR(nvs_set_i32(handle_1, "foo", 0x12345678), ESP_ERR_NVS_READ_ONLY);
  506. // nvs_close(handle_1);
  507. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle_1));
  508. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x12345678));
  509. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x23456789));
  510. nvs_handle_t handle_2;
  511. TEST_ESP_OK(nvs_open("namespace2", NVS_READWRITE, &handle_2));
  512. TEST_ESP_OK(nvs_set_i32(handle_2, "foo", 0x3456789a));
  513. const char* str = "value 0123456789abcdef0123456789abcdef";
  514. TEST_ESP_OK(nvs_set_str(handle_2, "key", str));
  515. int32_t v1;
  516. TEST_ESP_OK(nvs_get_i32(handle_1, "foo", &v1));
  517. CHECK(0x23456789 == v1);
  518. int32_t v2;
  519. TEST_ESP_OK(nvs_get_i32(handle_2, "foo", &v2));
  520. CHECK(0x3456789a == v2);
  521. char buf[strlen(str) + 1];
  522. size_t buf_len = sizeof(buf);
  523. size_t buf_len_needed;
  524. TEST_ESP_OK(nvs_get_str(handle_2, "key", NULL, &buf_len_needed));
  525. CHECK(buf_len_needed == buf_len);
  526. size_t buf_len_short = buf_len - 1;
  527. TEST_ESP_ERR(ESP_ERR_NVS_INVALID_LENGTH, nvs_get_str(handle_2, "key", buf, &buf_len_short));
  528. CHECK(buf_len_short == buf_len);
  529. size_t buf_len_long = buf_len + 1;
  530. TEST_ESP_OK(nvs_get_str(handle_2, "key", buf, &buf_len_long));
  531. CHECK(buf_len_long == buf_len);
  532. TEST_ESP_OK(nvs_get_str(handle_2, "key", buf, &buf_len));
  533. CHECK(0 == strcmp(buf, str));
  534. nvs_close(handle_1);
  535. nvs_close(handle_2);
  536. }
  537. TEST_CASE("nvs iterators tests", "[nvs]")
  538. {
  539. SpiFlashEmulator emu(5);
  540. const uint32_t NVS_FLASH_SECTOR = 0;
  541. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 5;
  542. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  543. for (uint16_t i = NVS_FLASH_SECTOR; i < NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN; ++i) {
  544. spi_flash_erase_sector(i);
  545. }
  546. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  547. nvs_iterator_t it;
  548. nvs_entry_info_t info;
  549. nvs_handle handle_1;
  550. nvs_handle handle_2;
  551. const uint32_t blob = 0x11223344;
  552. const char *name_1 = "namespace1";
  553. const char *name_2 = "namespace2";
  554. TEST_ESP_OK(nvs_open(name_1, NVS_READWRITE, &handle_1));
  555. TEST_ESP_OK(nvs_open(name_2, NVS_READWRITE, &handle_2));
  556. TEST_ESP_OK(nvs_set_i8(handle_1, "value1", -11));
  557. TEST_ESP_OK(nvs_set_u8(handle_1, "value2", 11));
  558. TEST_ESP_OK(nvs_set_i16(handle_1, "value3", 1234));
  559. TEST_ESP_OK(nvs_set_u16(handle_1, "value4", -1234));
  560. TEST_ESP_OK(nvs_set_i32(handle_1, "value5", -222));
  561. TEST_ESP_OK(nvs_set_i32(handle_1, "value6", -222));
  562. TEST_ESP_OK(nvs_set_i32(handle_1, "value7", -222));
  563. TEST_ESP_OK(nvs_set_u32(handle_1, "value8", 222));
  564. TEST_ESP_OK(nvs_set_u32(handle_1, "value9", 222));
  565. TEST_ESP_OK(nvs_set_str(handle_1, "value10", "foo"));
  566. TEST_ESP_OK(nvs_set_blob(handle_1, "value11", &blob, sizeof(blob)));
  567. TEST_ESP_OK(nvs_set_i32(handle_2, "value1", -111));
  568. TEST_ESP_OK(nvs_set_i32(handle_2, "value2", -111));
  569. TEST_ESP_OK(nvs_set_i64(handle_2, "value3", -555));
  570. TEST_ESP_OK(nvs_set_u64(handle_2, "value4", 555));
  571. auto entry_count = [](const char *part, const char *name, nvs_type_t type)-> int {
  572. int count;
  573. nvs_iterator_t it = nvs_entry_find(part, name, type);
  574. for (count = 0; it != nullptr; count++) {
  575. it = nvs_entry_next(it);
  576. }
  577. return count;
  578. };
  579. SECTION("Number of entries found for specified namespace and type is correct")
  580. {
  581. CHECK(nvs_entry_find("", NULL, NVS_TYPE_ANY) == NULL);
  582. CHECK(entry_count(NVS_DEFAULT_PART_NAME, NULL, NVS_TYPE_ANY) == 15);
  583. CHECK(entry_count(NVS_DEFAULT_PART_NAME, name_1, NVS_TYPE_ANY) == 11);
  584. CHECK(entry_count(NVS_DEFAULT_PART_NAME, name_1, NVS_TYPE_I32) == 3);
  585. CHECK(entry_count(NVS_DEFAULT_PART_NAME, NULL, NVS_TYPE_I32) == 5);
  586. CHECK(entry_count(NVS_DEFAULT_PART_NAME, NULL, NVS_TYPE_U64) == 1);
  587. }
  588. SECTION("New entry is not created when existing key-value pair is set")
  589. {
  590. CHECK(entry_count(NVS_DEFAULT_PART_NAME, name_2, NVS_TYPE_ANY) == 4);
  591. TEST_ESP_OK(nvs_set_i32(handle_2, "value1", -222));
  592. CHECK(entry_count(NVS_DEFAULT_PART_NAME, name_2, NVS_TYPE_ANY) == 4);
  593. }
  594. SECTION("Number of entries found decrease when entry is erased")
  595. {
  596. CHECK(entry_count(NVS_DEFAULT_PART_NAME, NULL, NVS_TYPE_U64) == 1);
  597. TEST_ESP_OK(nvs_erase_key(handle_2, "value4"));
  598. CHECK(entry_count(NVS_DEFAULT_PART_NAME, "", NVS_TYPE_U64) == 0);
  599. }
  600. SECTION("All fields of nvs_entry_info_t structure are correct")
  601. {
  602. it = nvs_entry_find(NVS_DEFAULT_PART_NAME, name_1, NVS_TYPE_I32);
  603. CHECK(it != nullptr);
  604. string key = "value5";
  605. do {
  606. nvs_entry_info(it, &info);
  607. CHECK(string(name_1) == info.namespace_name);
  608. CHECK(key == info.key);
  609. CHECK(info.type == NVS_TYPE_I32);
  610. it = nvs_entry_next(it);
  611. key[5]++;
  612. } while (it != NULL);
  613. nvs_release_iterator(it);
  614. }
  615. SECTION("Entry info is not affected by subsequent erase")
  616. {
  617. nvs_entry_info_t info_after_erase;
  618. it = nvs_entry_find(NVS_DEFAULT_PART_NAME, name_1, NVS_TYPE_ANY);
  619. nvs_entry_info(it, &info);
  620. TEST_ESP_OK(nvs_erase_key(handle_1, "value1"));
  621. nvs_entry_info(it, &info_after_erase);
  622. CHECK(memcmp(&info, &info_after_erase, sizeof(info)) == 0);
  623. nvs_release_iterator(it);
  624. }
  625. SECTION("Entry info is not affected by subsequent set")
  626. {
  627. nvs_entry_info_t info_after_set;
  628. it = nvs_entry_find(NVS_DEFAULT_PART_NAME, name_1, NVS_TYPE_ANY);
  629. nvs_entry_info(it, &info);
  630. TEST_ESP_OK(nvs_set_u8(handle_1, info.key, 44));
  631. nvs_entry_info(it, &info_after_set);
  632. CHECK(memcmp(&info, &info_after_set, sizeof(info)) == 0);
  633. nvs_release_iterator(it);
  634. }
  635. SECTION("Iterating over multiple pages works correctly")
  636. {
  637. nvs_handle handle_3;
  638. const char *name_3 = "namespace3";
  639. const int entries_created = 250;
  640. TEST_ESP_OK(nvs_open(name_3, NVS_READWRITE, &handle_3));
  641. for (size_t i = 0; i < entries_created; i++) {
  642. TEST_ESP_OK(nvs_set_u8(handle_3, to_string(i).c_str(), 123));
  643. }
  644. int entries_found = 0;
  645. it = nvs_entry_find(NVS_DEFAULT_PART_NAME, name_3, NVS_TYPE_ANY);
  646. while(it != nullptr) {
  647. entries_found++;
  648. it = nvs_entry_next(it);
  649. }
  650. CHECK(entries_created == entries_found);
  651. nvs_release_iterator(it);
  652. nvs_close(handle_3);
  653. }
  654. SECTION("Iterating over multi-page blob works correctly")
  655. {
  656. nvs_handle handle_3;
  657. const char *name_3 = "namespace3";
  658. const uint8_t multipage_blob[4096 * 2] = { 0 };
  659. const int NUMBER_OF_ENTRIES_PER_PAGE = 125;
  660. size_t occupied_entries;
  661. TEST_ESP_OK(nvs_open(name_3, NVS_READWRITE, &handle_3));
  662. nvs_set_blob(handle_3, "blob", multipage_blob, sizeof(multipage_blob));
  663. TEST_ESP_OK(nvs_get_used_entry_count(handle_3, &occupied_entries));
  664. CHECK(occupied_entries > NUMBER_OF_ENTRIES_PER_PAGE * 2);
  665. CHECK(entry_count(NVS_DEFAULT_PART_NAME, name_3, NVS_TYPE_BLOB) == 1);
  666. nvs_close(handle_3);
  667. }
  668. nvs_close(handle_1);
  669. nvs_close(handle_2);
  670. }
  671. TEST_CASE("wifi test", "[nvs]")
  672. {
  673. SpiFlashEmulator emu(10);
  674. emu.randomize(10);
  675. const uint32_t NVS_FLASH_SECTOR = 5;
  676. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 3;
  677. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  678. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  679. nvs_handle_t misc_handle;
  680. TEST_ESP_OK(nvs_open("nvs.net80211", NVS_READWRITE, &misc_handle));
  681. char log[33];
  682. size_t log_size = sizeof(log);
  683. TEST_ESP_ERR(nvs_get_str(misc_handle, "log", log, &log_size), ESP_ERR_NVS_NOT_FOUND);
  684. strcpy(log, "foobarbazfizzz");
  685. TEST_ESP_OK(nvs_set_str(misc_handle, "log", log));
  686. nvs_handle_t net80211_handle;
  687. TEST_ESP_OK(nvs_open("nvs.net80211", NVS_READWRITE, &net80211_handle));
  688. uint8_t opmode = 2;
  689. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "wifi.opmode", &opmode), ESP_ERR_NVS_NOT_FOUND);
  690. TEST_ESP_OK(nvs_set_u8(net80211_handle, "wifi.opmode", opmode));
  691. uint8_t country = 0;
  692. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "wifi.country", &opmode), ESP_ERR_NVS_NOT_FOUND);
  693. TEST_ESP_OK(nvs_set_u8(net80211_handle, "wifi.country", opmode));
  694. char ssid[36];
  695. size_t size = sizeof(ssid);
  696. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.ssid", ssid, &size), ESP_ERR_NVS_NOT_FOUND);
  697. strcpy(ssid, "my android AP");
  698. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.ssid", ssid, size));
  699. char mac[6];
  700. size = sizeof(mac);
  701. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.mac", mac, &size), ESP_ERR_NVS_NOT_FOUND);
  702. memset(mac, 0xab, 6);
  703. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.mac", mac, size));
  704. uint8_t authmode = 1;
  705. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "sta.authmode", &authmode), ESP_ERR_NVS_NOT_FOUND);
  706. TEST_ESP_OK(nvs_set_u8(net80211_handle, "sta.authmode", authmode));
  707. char pswd[65];
  708. size = sizeof(pswd);
  709. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.pswd", pswd, &size), ESP_ERR_NVS_NOT_FOUND);
  710. strcpy(pswd, "`123456788990-=");
  711. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.pswd", pswd, size));
  712. char pmk[32];
  713. size = sizeof(pmk);
  714. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.pmk", pmk, &size), ESP_ERR_NVS_NOT_FOUND);
  715. memset(pmk, 1, size);
  716. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.pmk", pmk, size));
  717. uint8_t chan = 1;
  718. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "sta.chan", &chan), ESP_ERR_NVS_NOT_FOUND);
  719. TEST_ESP_OK(nvs_set_u8(net80211_handle, "sta.chan", chan));
  720. uint8_t autoconn = 1;
  721. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "auto.conn", &autoconn), ESP_ERR_NVS_NOT_FOUND);
  722. TEST_ESP_OK(nvs_set_u8(net80211_handle, "auto.conn", autoconn));
  723. uint8_t bssid_set = 1;
  724. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "bssid.set", &bssid_set), ESP_ERR_NVS_NOT_FOUND);
  725. TEST_ESP_OK(nvs_set_u8(net80211_handle, "bssid.set", bssid_set));
  726. char bssid[6];
  727. size = sizeof(bssid);
  728. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.bssid", bssid, &size), ESP_ERR_NVS_NOT_FOUND);
  729. memset(mac, 0xcd, 6);
  730. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.bssid", bssid, size));
  731. uint8_t phym = 3;
  732. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "sta.phym", &phym), ESP_ERR_NVS_NOT_FOUND);
  733. TEST_ESP_OK(nvs_set_u8(net80211_handle, "sta.phym", phym));
  734. uint8_t phybw = 2;
  735. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "sta.phybw", &phybw), ESP_ERR_NVS_NOT_FOUND);
  736. TEST_ESP_OK(nvs_set_u8(net80211_handle, "sta.phybw", phybw));
  737. char apsw[2];
  738. size = sizeof(apsw);
  739. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.apsw", apsw, &size), ESP_ERR_NVS_NOT_FOUND);
  740. memset(apsw, 0x2, size);
  741. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.apsw", apsw, size));
  742. char apinfo[700];
  743. size = sizeof(apinfo);
  744. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "sta.apinfo", apinfo, &size), ESP_ERR_NVS_NOT_FOUND);
  745. memset(apinfo, 0, size);
  746. TEST_ESP_OK(nvs_set_blob(net80211_handle, "sta.apinfo", apinfo, size));
  747. size = sizeof(ssid);
  748. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "ap.ssid", ssid, &size), ESP_ERR_NVS_NOT_FOUND);
  749. strcpy(ssid, "ESP_A2F340");
  750. TEST_ESP_OK(nvs_set_blob(net80211_handle, "ap.ssid", ssid, size));
  751. size = sizeof(mac);
  752. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "ap.mac", mac, &size), ESP_ERR_NVS_NOT_FOUND);
  753. memset(mac, 0xac, 6);
  754. TEST_ESP_OK(nvs_set_blob(net80211_handle, "ap.mac", mac, size));
  755. size = sizeof(pswd);
  756. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "ap.passwd", pswd, &size), ESP_ERR_NVS_NOT_FOUND);
  757. strcpy(pswd, "");
  758. TEST_ESP_OK(nvs_set_blob(net80211_handle, "ap.passwd", pswd, size));
  759. size = sizeof(pmk);
  760. TEST_ESP_ERR(nvs_get_blob(net80211_handle, "ap.pmk", pmk, &size), ESP_ERR_NVS_NOT_FOUND);
  761. memset(pmk, 1, size);
  762. TEST_ESP_OK(nvs_set_blob(net80211_handle, "ap.pmk", pmk, size));
  763. chan = 6;
  764. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "ap.chan", &chan), ESP_ERR_NVS_NOT_FOUND);
  765. TEST_ESP_OK(nvs_set_u8(net80211_handle, "ap.chan", chan));
  766. authmode = 0;
  767. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "ap.authmode", &authmode), ESP_ERR_NVS_NOT_FOUND);
  768. TEST_ESP_OK(nvs_set_u8(net80211_handle, "ap.authmode", authmode));
  769. uint8_t hidden = 0;
  770. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "ap.hidden", &hidden), ESP_ERR_NVS_NOT_FOUND);
  771. TEST_ESP_OK(nvs_set_u8(net80211_handle, "ap.hidden", hidden));
  772. uint8_t max_conn = 4;
  773. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "ap.max.conn", &max_conn), ESP_ERR_NVS_NOT_FOUND);
  774. TEST_ESP_OK(nvs_set_u8(net80211_handle, "ap.max.conn", max_conn));
  775. uint8_t bcn_interval = 2;
  776. TEST_ESP_ERR(nvs_get_u8(net80211_handle, "bcn_interval", &bcn_interval), ESP_ERR_NVS_NOT_FOUND);
  777. TEST_ESP_OK(nvs_set_u8(net80211_handle, "bcn_interval", bcn_interval));
  778. s_perf << "Time to simulate nvs init with wifi libs: " << emu.getTotalTime() << " us (" << emu.getEraseOps() << "E " << emu.getWriteOps() << "W " << emu.getReadOps() << "R " << emu.getWriteBytes() << "Wb " << emu.getReadBytes() << "Rb)" << std::endl;
  779. }
  780. TEST_CASE("writing the identical content does not write or erase", "[nvs]")
  781. {
  782. SpiFlashEmulator emu(20);
  783. const uint32_t NVS_FLASH_SECTOR = 5;
  784. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 10;
  785. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  786. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  787. nvs_handle misc_handle;
  788. TEST_ESP_OK(nvs_open("test", NVS_READWRITE, &misc_handle));
  789. // Test writing a u8 twice, then changing it
  790. nvs_set_u8(misc_handle, "test_u8", 8);
  791. emu.clearStats();
  792. nvs_set_u8(misc_handle, "test_u8", 8);
  793. CHECK(emu.getWriteOps() == 0);
  794. CHECK(emu.getEraseOps() == 0);
  795. CHECK(emu.getReadOps() != 0);
  796. emu.clearStats();
  797. nvs_set_u8(misc_handle, "test_u8", 9);
  798. CHECK(emu.getWriteOps() != 0);
  799. CHECK(emu.getReadOps() != 0);
  800. // Test writing a string twice, then changing it
  801. static const char *test[2] = {"Hello world.", "Hello world!"};
  802. nvs_set_str(misc_handle, "test_str", test[0]);
  803. emu.clearStats();
  804. nvs_set_str(misc_handle, "test_str", test[0]);
  805. CHECK(emu.getWriteOps() == 0);
  806. CHECK(emu.getEraseOps() == 0);
  807. CHECK(emu.getReadOps() != 0);
  808. emu.clearStats();
  809. nvs_set_str(misc_handle, "test_str", test[1]);
  810. CHECK(emu.getWriteOps() != 0);
  811. CHECK(emu.getReadOps() != 0);
  812. // Test writing a multi-page blob, then changing it
  813. uint8_t blob[Page::CHUNK_MAX_SIZE * 3] = {0};
  814. memset(blob, 1, sizeof(blob));
  815. nvs_set_blob(misc_handle, "test_blob", blob, sizeof(blob));
  816. emu.clearStats();
  817. nvs_set_blob(misc_handle, "test_blob", blob, sizeof(blob));
  818. CHECK(emu.getWriteOps() == 0);
  819. CHECK(emu.getEraseOps() == 0);
  820. CHECK(emu.getReadOps() != 0);
  821. blob[sizeof(blob) - 1]++;
  822. emu.clearStats();
  823. nvs_set_blob(misc_handle, "test_blob", blob, sizeof(blob));
  824. CHECK(emu.getWriteOps() != 0);
  825. CHECK(emu.getReadOps() != 0);
  826. }
  827. TEST_CASE("can init storage from flash with random contents", "[nvs]")
  828. {
  829. SpiFlashEmulator emu(10);
  830. emu.randomize(42);
  831. nvs_handle_t handle;
  832. const uint32_t NVS_FLASH_SECTOR = 5;
  833. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 3;
  834. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  835. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  836. TEST_ESP_OK(nvs_open("nvs.net80211", NVS_READWRITE, &handle));
  837. uint8_t opmode = 2;
  838. if (nvs_get_u8(handle, "wifi.opmode", &opmode) != ESP_OK) {
  839. TEST_ESP_OK(nvs_set_u8(handle, "wifi.opmode", opmode));
  840. }
  841. }
  842. TEST_CASE("nvs api tests, starting with random data in flash", "[nvs][long]")
  843. {
  844. const size_t testIters = 3000;
  845. int lastPercent = -1;
  846. for (size_t count = 0; count < testIters; ++count) {
  847. int percentDone = (int) (count * 100 / testIters);
  848. if (percentDone != lastPercent) {
  849. lastPercent = percentDone;
  850. printf("%d%%\n", percentDone);
  851. }
  852. SpiFlashEmulator emu(10);
  853. emu.randomize(static_cast<uint32_t>(count));
  854. const uint32_t NVS_FLASH_SECTOR = 6;
  855. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 3;
  856. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  857. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  858. nvs_handle_t handle_1;
  859. TEST_ESP_ERR(nvs_open("namespace1", NVS_READONLY, &handle_1), ESP_ERR_NVS_NOT_FOUND);
  860. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle_1));
  861. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x12345678));
  862. for (size_t i = 0; i < 500; ++i) {
  863. nvs_handle_t handle_2;
  864. TEST_ESP_OK(nvs_open("namespace2", NVS_READWRITE, &handle_2));
  865. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x23456789 % (i + 1)));
  866. TEST_ESP_OK(nvs_set_i32(handle_2, "foo", static_cast<int32_t>(i)));
  867. const char* str = "value 0123456789abcdef0123456789abcdef %09d";
  868. char str_buf[128];
  869. snprintf(str_buf, sizeof(str_buf), str, i + count * 1024);
  870. TEST_ESP_OK(nvs_set_str(handle_2, "key", str_buf));
  871. int32_t v1;
  872. TEST_ESP_OK(nvs_get_i32(handle_1, "foo", &v1));
  873. CHECK(0x23456789 % (i + 1) == v1);
  874. int32_t v2;
  875. TEST_ESP_OK(nvs_get_i32(handle_2, "foo", &v2));
  876. CHECK(static_cast<int32_t>(i) == v2);
  877. char buf[128];
  878. size_t buf_len = sizeof(buf);
  879. TEST_ESP_OK(nvs_get_str(handle_2, "key", buf, &buf_len));
  880. CHECK(0 == strcmp(buf, str_buf));
  881. nvs_close(handle_2);
  882. }
  883. nvs_close(handle_1);
  884. }
  885. }
  886. extern "C" void nvs_dump(const char *partName);
  887. class RandomTest {
  888. static const size_t nKeys = 11;
  889. int32_t v1 = 0, v2 = 0;
  890. uint64_t v3 = 0, v4 = 0;
  891. static const size_t strBufLen = 1024;
  892. static const size_t smallBlobLen = Page::CHUNK_MAX_SIZE / 3;
  893. static const size_t largeBlobLen = Page::CHUNK_MAX_SIZE * 3;
  894. char v5[strBufLen], v6[strBufLen], v7[strBufLen], v8[strBufLen], v9[strBufLen];
  895. uint8_t v10[smallBlobLen], v11[largeBlobLen];
  896. bool written[nKeys];
  897. public:
  898. RandomTest()
  899. {
  900. std::fill_n(written, nKeys, false);
  901. }
  902. template<typename TGen>
  903. esp_err_t doRandomThings(nvs_handle_t handle, TGen gen, size_t& count) {
  904. const char* keys[] = {"foo", "bar", "longkey_0123456", "another key", "param1", "param2", "param3", "param4", "param5", "singlepage", "multipage"};
  905. const ItemType types[] = {ItemType::I32, ItemType::I32, ItemType::U64, ItemType::U64, ItemType::SZ, ItemType::SZ, ItemType::SZ, ItemType::SZ, ItemType::SZ, ItemType::BLOB, ItemType::BLOB};
  906. void* values[] = {&v1, &v2, &v3, &v4, &v5, &v6, &v7, &v8, &v9, &v10, &v11};
  907. const size_t nKeys = sizeof(keys) / sizeof(keys[0]);
  908. static_assert(nKeys == sizeof(types) / sizeof(types[0]), "");
  909. static_assert(nKeys == sizeof(values) / sizeof(values[0]), "");
  910. auto randomRead = [&](size_t index) -> esp_err_t {
  911. switch (types[index]) {
  912. case ItemType::I32:
  913. {
  914. int32_t val;
  915. auto err = nvs_get_i32(handle, keys[index], &val);
  916. if (err == ESP_ERR_FLASH_OP_FAIL) {
  917. return err;
  918. }
  919. if (!written[index]) {
  920. REQUIRE(err == ESP_ERR_NVS_NOT_FOUND);
  921. }
  922. else {
  923. REQUIRE(err == ESP_OK);
  924. REQUIRE(val == *reinterpret_cast<int32_t*>(values[index]));
  925. }
  926. break;
  927. }
  928. case ItemType::U64:
  929. {
  930. uint64_t val;
  931. auto err = nvs_get_u64(handle, keys[index], &val);
  932. if (err == ESP_ERR_FLASH_OP_FAIL) {
  933. return err;
  934. }
  935. if (!written[index]) {
  936. REQUIRE(err == ESP_ERR_NVS_NOT_FOUND);
  937. }
  938. else {
  939. REQUIRE(err == ESP_OK);
  940. REQUIRE(val == *reinterpret_cast<uint64_t*>(values[index]));
  941. }
  942. break;
  943. }
  944. case ItemType::SZ:
  945. {
  946. char buf[strBufLen];
  947. size_t len = strBufLen;
  948. auto err = nvs_get_str(handle, keys[index], buf, &len);
  949. if (err == ESP_ERR_FLASH_OP_FAIL) {
  950. return err;
  951. }
  952. if (!written[index]) {
  953. REQUIRE(err == ESP_ERR_NVS_NOT_FOUND);
  954. }
  955. else {
  956. REQUIRE(err == ESP_OK);
  957. REQUIRE(strncmp(buf, reinterpret_cast<const char*>(values[index]), strBufLen) == 0);
  958. }
  959. break;
  960. }
  961. case ItemType::BLOB:
  962. {
  963. uint32_t blobBufLen = 0;
  964. if(strncmp(keys[index],"singlepage", sizeof("singlepage")) == 0) {
  965. blobBufLen = smallBlobLen ;
  966. } else {
  967. blobBufLen = largeBlobLen ;
  968. }
  969. uint8_t buf[blobBufLen];
  970. memset(buf, 0, blobBufLen);
  971. size_t len = blobBufLen;
  972. auto err = nvs_get_blob(handle, keys[index], buf, &len);
  973. if (err == ESP_ERR_FLASH_OP_FAIL) {
  974. return err;
  975. }
  976. if (!written[index]) {
  977. REQUIRE(err == ESP_ERR_NVS_NOT_FOUND);
  978. }
  979. else {
  980. REQUIRE(err == ESP_OK);
  981. REQUIRE(memcmp(buf, reinterpret_cast<const uint8_t*>(values[index]), blobBufLen) == 0);
  982. }
  983. break;
  984. }
  985. default:
  986. assert(0);
  987. }
  988. return ESP_OK;
  989. };
  990. auto randomWrite = [&](size_t index) -> esp_err_t {
  991. switch (types[index]) {
  992. case ItemType::I32:
  993. {
  994. int32_t val = static_cast<int32_t>(gen());
  995. auto err = nvs_set_i32(handle, keys[index], val);
  996. if (err == ESP_ERR_FLASH_OP_FAIL) {
  997. return err;
  998. }
  999. if (err == ESP_ERR_NVS_REMOVE_FAILED) {
  1000. written[index] = true;
  1001. *reinterpret_cast<int32_t*>(values[index]) = val;
  1002. return ESP_ERR_FLASH_OP_FAIL;
  1003. }
  1004. REQUIRE(err == ESP_OK);
  1005. written[index] = true;
  1006. *reinterpret_cast<int32_t*>(values[index]) = val;
  1007. break;
  1008. }
  1009. case ItemType::U64:
  1010. {
  1011. uint64_t val = static_cast<uint64_t>(gen());
  1012. auto err = nvs_set_u64(handle, keys[index], val);
  1013. if (err == ESP_ERR_FLASH_OP_FAIL) {
  1014. return err;
  1015. }
  1016. if (err == ESP_ERR_NVS_REMOVE_FAILED) {
  1017. written[index] = true;
  1018. *reinterpret_cast<uint64_t*>(values[index]) = val;
  1019. return ESP_ERR_FLASH_OP_FAIL;
  1020. }
  1021. REQUIRE(err == ESP_OK);
  1022. written[index] = true;
  1023. *reinterpret_cast<uint64_t*>(values[index]) = val;
  1024. break;
  1025. }
  1026. case ItemType::SZ:
  1027. {
  1028. char buf[strBufLen];
  1029. size_t len = strBufLen;
  1030. size_t strLen = gen() % (strBufLen - 1);
  1031. std::generate_n(buf, strLen, [&]() -> char {
  1032. const char c = static_cast<char>(gen() % 127);
  1033. return (c < 32) ? 32 : c;
  1034. });
  1035. buf[strLen] = 0;
  1036. auto err = nvs_set_str(handle, keys[index], buf);
  1037. if (err == ESP_ERR_FLASH_OP_FAIL) {
  1038. return err;
  1039. }
  1040. if (err == ESP_ERR_NVS_REMOVE_FAILED) {
  1041. written[index] = true;
  1042. strncpy(reinterpret_cast<char*>(values[index]), buf, strBufLen);
  1043. return ESP_ERR_FLASH_OP_FAIL;
  1044. }
  1045. REQUIRE(err == ESP_OK);
  1046. written[index] = true;
  1047. strncpy(reinterpret_cast<char*>(values[index]), buf, strBufLen);
  1048. break;
  1049. }
  1050. case ItemType::BLOB:
  1051. {
  1052. uint32_t blobBufLen = 0;
  1053. if(strncmp(keys[index],"singlepage", sizeof("singlepage")) == 0) {
  1054. blobBufLen = smallBlobLen ;
  1055. } else {
  1056. blobBufLen = largeBlobLen ;
  1057. }
  1058. uint8_t buf[blobBufLen];
  1059. memset(buf, 0, blobBufLen);
  1060. size_t blobLen = gen() % blobBufLen;
  1061. std::generate_n(buf, blobLen, [&]() -> uint8_t {
  1062. return static_cast<uint8_t>(gen() % 256);
  1063. });
  1064. auto err = nvs_set_blob(handle, keys[index], buf, blobLen);
  1065. if (err == ESP_ERR_FLASH_OP_FAIL) {
  1066. return err;
  1067. }
  1068. if (err == ESP_ERR_NVS_REMOVE_FAILED) {
  1069. written[index] = true;
  1070. memcpy(reinterpret_cast<uint8_t*>(values[index]), buf, blobBufLen);
  1071. return ESP_ERR_FLASH_OP_FAIL;
  1072. }
  1073. REQUIRE(err == ESP_OK);
  1074. written[index] = true;
  1075. memcpy(reinterpret_cast<char*>(values[index]), buf, blobBufLen);
  1076. break;
  1077. }
  1078. default:
  1079. assert(0);
  1080. }
  1081. return ESP_OK;
  1082. };
  1083. for (; count != 0; --count) {
  1084. size_t index = gen() % (nKeys);
  1085. switch (gen() % 3) {
  1086. case 0: // read, 1/3
  1087. if (randomRead(index) == ESP_ERR_FLASH_OP_FAIL) {
  1088. return ESP_ERR_FLASH_OP_FAIL;
  1089. }
  1090. break;
  1091. default: // write, 2/3
  1092. if (randomWrite(index) == ESP_ERR_FLASH_OP_FAIL) {
  1093. return ESP_ERR_FLASH_OP_FAIL;
  1094. }
  1095. break;
  1096. }
  1097. }
  1098. return ESP_OK;
  1099. }
  1100. esp_err_t handleExternalWriteAtIndex(uint8_t index, const void* value, const size_t len ) {
  1101. if(index == 9) { /* This is only done for small-page blobs for now*/
  1102. if(len > smallBlobLen) {
  1103. return ESP_FAIL;
  1104. }
  1105. memcpy(v10, value, len);
  1106. written[index] = true;
  1107. return ESP_OK;
  1108. } else {
  1109. return ESP_FAIL;
  1110. }
  1111. }
  1112. };
  1113. TEST_CASE("monkey test", "[nvs][monkey]")
  1114. {
  1115. std::random_device rd;
  1116. std::mt19937 gen(rd());
  1117. uint32_t seed = 3;
  1118. gen.seed(seed);
  1119. SpiFlashEmulator emu(10);
  1120. emu.randomize(seed);
  1121. emu.clearStats();
  1122. const uint32_t NVS_FLASH_SECTOR = 2;
  1123. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 8;
  1124. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  1125. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  1126. nvs_handle_t handle;
  1127. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1128. RandomTest test;
  1129. size_t count = 1000;
  1130. CHECK(test.doRandomThings(handle, gen, count) == ESP_OK);
  1131. s_perf << "Monkey test: nErase=" << emu.getEraseOps() << " nWrite=" << emu.getWriteOps() << std::endl;
  1132. }
  1133. TEST_CASE("test recovery from sudden poweroff", "[long][nvs][recovery][monkey]")
  1134. {
  1135. std::random_device rd;
  1136. std::mt19937 gen(rd());
  1137. uint32_t seed = 3;
  1138. gen.seed(seed);
  1139. const size_t iter_count = 2000;
  1140. SpiFlashEmulator emu(10);
  1141. const uint32_t NVS_FLASH_SECTOR = 2;
  1142. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 8;
  1143. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  1144. size_t totalOps = 0;
  1145. int lastPercent = -1;
  1146. for (uint32_t errDelay = 0; ; ++errDelay) {
  1147. INFO(errDelay);
  1148. emu.randomize(seed);
  1149. emu.clearStats();
  1150. emu.failAfter(errDelay);
  1151. RandomTest test;
  1152. if (totalOps != 0) {
  1153. int percent = errDelay * 100 / totalOps;
  1154. if (percent > lastPercent) {
  1155. printf("%d/%d (%d%%)\r\n", errDelay, static_cast<int>(totalOps), percent);
  1156. lastPercent = percent;
  1157. }
  1158. }
  1159. nvs_handle_t handle;
  1160. size_t count = iter_count;
  1161. if (nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN) == ESP_OK) {
  1162. if (nvs_open("namespace1", NVS_READWRITE, &handle) == ESP_OK) {
  1163. if(test.doRandomThings(handle, gen, count) != ESP_ERR_FLASH_OP_FAIL) {
  1164. nvs_close(handle);
  1165. break;
  1166. }
  1167. nvs_close(handle);
  1168. }
  1169. }
  1170. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  1171. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1172. auto res = test.doRandomThings(handle, gen, count);
  1173. if (res != ESP_OK) {
  1174. nvs_dump(NVS_DEFAULT_PART_NAME);
  1175. CHECK(0);
  1176. }
  1177. nvs_close(handle);
  1178. totalOps = emu.getEraseOps() + emu.getWriteBytes() / 4;
  1179. }
  1180. }
  1181. TEST_CASE("test for memory leaks in open/set", "[leaks]")
  1182. {
  1183. SpiFlashEmulator emu(10);
  1184. const uint32_t NVS_FLASH_SECTOR = 6;
  1185. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 3;
  1186. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  1187. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  1188. for (int i = 0; i < 100000; ++i) {
  1189. nvs_handle_t light_handle = 0;
  1190. char lightbulb[1024] = {12, 13, 14, 15, 16};
  1191. TEST_ESP_OK(nvs_open("light", NVS_READWRITE, &light_handle));
  1192. TEST_ESP_OK(nvs_set_blob(light_handle, "key", lightbulb, sizeof(lightbulb)));
  1193. TEST_ESP_OK(nvs_commit(light_handle));
  1194. nvs_close(light_handle);
  1195. }
  1196. }
  1197. TEST_CASE("duplicate items are removed", "[nvs][dupes]")
  1198. {
  1199. SpiFlashEmulator emu(3);
  1200. {
  1201. // create one item
  1202. nvs::Page p;
  1203. p.load(0);
  1204. p.writeItem<uint8_t>(1, "opmode", 3);
  1205. }
  1206. {
  1207. // add another two without deleting the first one
  1208. nvs::Item item(1, ItemType::U8, 1, "opmode");
  1209. item.data[0] = 2;
  1210. item.crc32 = item.calculateCrc32();
  1211. emu.write(3 * 32, reinterpret_cast<const uint32_t*>(&item), sizeof(item));
  1212. emu.write(4 * 32, reinterpret_cast<const uint32_t*>(&item), sizeof(item));
  1213. uint32_t mask = 0xFFFFFFEA;
  1214. emu.write(32, &mask, 4);
  1215. }
  1216. {
  1217. // load page and check that second item persists
  1218. nvs::Storage s;
  1219. s.init(0, 3);
  1220. uint8_t val;
  1221. ESP_ERROR_CHECK(s.readItem(1, "opmode", val));
  1222. CHECK(val == 2);
  1223. }
  1224. {
  1225. Page p;
  1226. p.load(0);
  1227. CHECK(p.getErasedEntryCount() == 2);
  1228. CHECK(p.getUsedEntryCount() == 1);
  1229. }
  1230. }
  1231. TEST_CASE("recovery after failure to write data", "[nvs]")
  1232. {
  1233. SpiFlashEmulator emu(3);
  1234. const char str[] = "value 0123456789abcdef012345678value 0123456789abcdef012345678";
  1235. // make flash write fail exactly in Page::writeEntryData
  1236. emu.failAfter(17);
  1237. {
  1238. Storage storage;
  1239. TEST_ESP_OK(storage.init(0, 3));
  1240. TEST_ESP_ERR(storage.writeItem(1, ItemType::SZ, "key", str, strlen(str)), ESP_ERR_FLASH_OP_FAIL);
  1241. // check that repeated operations cause an error
  1242. TEST_ESP_ERR(storage.writeItem(1, ItemType::SZ, "key", str, strlen(str)), ESP_ERR_NVS_INVALID_STATE);
  1243. uint8_t val;
  1244. TEST_ESP_ERR(storage.readItem(1, ItemType::U8, "key", &val, sizeof(val)), ESP_ERR_NVS_NOT_FOUND);
  1245. }
  1246. {
  1247. // load page and check that data was erased
  1248. Page p;
  1249. p.load(0);
  1250. CHECK(p.getErasedEntryCount() == 3);
  1251. CHECK(p.getUsedEntryCount() == 0);
  1252. // try to write again
  1253. TEST_ESP_OK(p.writeItem(1, ItemType::SZ, "key", str, strlen(str)));
  1254. }
  1255. }
  1256. TEST_CASE("crc errors in item header are handled", "[nvs]")
  1257. {
  1258. SpiFlashEmulator emu(3);
  1259. Storage storage;
  1260. // prepare some data
  1261. TEST_ESP_OK(storage.init(0, 3));
  1262. TEST_ESP_OK(storage.writeItem(0, "ns1", static_cast<uint8_t>(1)));
  1263. TEST_ESP_OK(storage.writeItem(1, "value1", static_cast<uint32_t>(1)));
  1264. TEST_ESP_OK(storage.writeItem(1, "value2", static_cast<uint32_t>(2)));
  1265. // corrupt item header
  1266. uint32_t val = 0;
  1267. emu.write(32 * 3, &val, 4);
  1268. // check that storage can recover
  1269. TEST_ESP_OK(storage.init(0, 3));
  1270. TEST_ESP_OK(storage.readItem(1, "value2", val));
  1271. CHECK(val == 2);
  1272. // check that the corrupted item is no longer present
  1273. TEST_ESP_ERR(ESP_ERR_NVS_NOT_FOUND, storage.readItem(1, "value1", val));
  1274. // add more items to make the page full
  1275. for (size_t i = 0; i < Page::ENTRY_COUNT; ++i) {
  1276. char item_name[Item::MAX_KEY_LENGTH + 1];
  1277. snprintf(item_name, sizeof(item_name), "item_%ld", (long int)i);
  1278. TEST_ESP_OK(storage.writeItem(1, item_name, static_cast<uint32_t>(i)));
  1279. }
  1280. // corrupt another item on the full page
  1281. val = 0;
  1282. emu.write(32 * 4, &val, 4);
  1283. // check that storage can recover
  1284. TEST_ESP_OK(storage.init(0, 3));
  1285. // check that the corrupted item is no longer present
  1286. TEST_ESP_ERR(ESP_ERR_NVS_NOT_FOUND, storage.readItem(1, "value2", val));
  1287. }
  1288. TEST_CASE("crc error in variable length item is handled", "[nvs]")
  1289. {
  1290. SpiFlashEmulator emu(3);
  1291. const uint64_t before_val = 0xbef04e;
  1292. const uint64_t after_val = 0xaf7e4;
  1293. // write some data
  1294. {
  1295. Page p;
  1296. p.load(0);
  1297. TEST_ESP_OK(p.writeItem<uint64_t>(0, "before", before_val));
  1298. const char* str = "foobar";
  1299. TEST_ESP_OK(p.writeItem(0, ItemType::SZ, "key", str, strlen(str)));
  1300. TEST_ESP_OK(p.writeItem<uint64_t>(0, "after", after_val));
  1301. }
  1302. // corrupt some data
  1303. uint32_t w;
  1304. CHECK(emu.read(&w, 32 * 3 + 8, sizeof(w)));
  1305. w &= 0xf000000f;
  1306. CHECK(emu.write(32 * 3 + 8, &w, sizeof(w)));
  1307. // load and check
  1308. {
  1309. Page p;
  1310. p.load(0);
  1311. CHECK(p.getUsedEntryCount() == 2);
  1312. CHECK(p.getErasedEntryCount() == 2);
  1313. uint64_t val;
  1314. TEST_ESP_OK(p.readItem<uint64_t>(0, "before", val));
  1315. CHECK(val == before_val);
  1316. TEST_ESP_ERR(p.findItem(0, ItemType::SZ, "key"), ESP_ERR_NVS_NOT_FOUND);
  1317. TEST_ESP_OK(p.readItem<uint64_t>(0, "after", val));
  1318. CHECK(val == after_val);
  1319. }
  1320. }
  1321. TEST_CASE("read/write failure (TW8406)", "[nvs]")
  1322. {
  1323. SpiFlashEmulator emu(3);
  1324. nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3);
  1325. for (int attempts = 0; attempts < 3; ++attempts) {
  1326. int i = 0;
  1327. nvs_handle_t light_handle = 0;
  1328. char key[15] = {0};
  1329. char data[76] = {12, 13, 14, 15, 16};
  1330. uint8_t number = 20;
  1331. size_t data_len = sizeof(data);
  1332. ESP_ERROR_CHECK(nvs_open("LIGHT", NVS_READWRITE, &light_handle));
  1333. ESP_ERROR_CHECK(nvs_set_u8(light_handle, "RecordNum", number));
  1334. for (i = 0; i < number; ++i) {
  1335. sprintf(key, "light%d", i);
  1336. ESP_ERROR_CHECK(nvs_set_blob(light_handle, key, data, sizeof(data)));
  1337. }
  1338. nvs_commit(light_handle);
  1339. uint8_t get_number = 0;
  1340. ESP_ERROR_CHECK(nvs_get_u8(light_handle, "RecordNum", &get_number));
  1341. REQUIRE(number == get_number);
  1342. for (i = 0; i < number; ++i) {
  1343. char data[76] = {0};
  1344. sprintf(key, "light%d", i);
  1345. ESP_ERROR_CHECK(nvs_get_blob(light_handle, key, data, &data_len));
  1346. }
  1347. nvs_close(light_handle);
  1348. }
  1349. }
  1350. TEST_CASE("nvs_flash_init checks for an empty page", "[nvs]")
  1351. {
  1352. const size_t blob_size = Page::CHUNK_MAX_SIZE;
  1353. uint8_t blob[blob_size] = {0};
  1354. SpiFlashEmulator emu(5);
  1355. TEST_ESP_OK( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5) );
  1356. nvs_handle_t handle;
  1357. TEST_ESP_OK( nvs_open("test", NVS_READWRITE, &handle) );
  1358. // Fill first page
  1359. TEST_ESP_OK( nvs_set_blob(handle, "1a", blob, blob_size) );
  1360. // Fill second page
  1361. TEST_ESP_OK( nvs_set_blob(handle, "2a", blob, blob_size) );
  1362. // Fill third page
  1363. TEST_ESP_OK( nvs_set_blob(handle, "3a", blob, blob_size) );
  1364. TEST_ESP_OK( nvs_commit(handle) );
  1365. nvs_close(handle);
  1366. // first two pages are now full, third one is writable, last two are empty
  1367. // init should fail
  1368. TEST_ESP_ERR( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3), ESP_ERR_NVS_NO_FREE_PAGES );
  1369. }
  1370. TEST_CASE("multiple partitions access check", "[nvs]")
  1371. {
  1372. SpiFlashEmulator emu(10);
  1373. TEST_ESP_OK( nvs_flash_init_custom("nvs1", 0, 5) );
  1374. TEST_ESP_OK( nvs_flash_init_custom("nvs2", 5, 5) );
  1375. nvs_handle_t handle1, handle2;
  1376. TEST_ESP_OK( nvs_open_from_partition("nvs1", "test", NVS_READWRITE, &handle1) );
  1377. TEST_ESP_OK( nvs_open_from_partition("nvs2", "test", NVS_READWRITE, &handle2) );
  1378. TEST_ESP_OK( nvs_set_i32(handle1, "foo", 0xdeadbeef));
  1379. TEST_ESP_OK( nvs_set_i32(handle2, "foo", 0xcafebabe));
  1380. int32_t v1, v2;
  1381. TEST_ESP_OK( nvs_get_i32(handle1, "foo", &v1));
  1382. TEST_ESP_OK( nvs_get_i32(handle2, "foo", &v2));
  1383. CHECK(v1 == 0xdeadbeef);
  1384. CHECK(v2 == 0xcafebabe);
  1385. }
  1386. TEST_CASE("nvs page selection takes into account free entries also not just erased entries", "[nvs]")
  1387. {
  1388. const size_t blob_size = Page::CHUNK_MAX_SIZE/2;
  1389. uint8_t blob[blob_size] = {0};
  1390. SpiFlashEmulator emu(3);
  1391. TEST_ESP_OK( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3) );
  1392. nvs_handle_t handle;
  1393. TEST_ESP_OK( nvs_open("test", NVS_READWRITE, &handle) );
  1394. // Fill first page
  1395. TEST_ESP_OK( nvs_set_blob(handle, "1a", blob, blob_size/3) );
  1396. TEST_ESP_OK( nvs_set_blob(handle, "1b", blob, blob_size) );
  1397. // Fill second page
  1398. TEST_ESP_OK( nvs_set_blob(handle, "2a", blob, blob_size) );
  1399. TEST_ESP_OK( nvs_set_blob(handle, "2b", blob, blob_size) );
  1400. // The item below should be able to fit the first page.
  1401. TEST_ESP_OK( nvs_set_blob(handle, "3a", blob, 4) );
  1402. TEST_ESP_OK( nvs_commit(handle) );
  1403. nvs_close(handle);
  1404. }
  1405. TEST_CASE("calculate used and free space", "[nvs]")
  1406. {
  1407. SpiFlashEmulator emu(6);
  1408. nvs_flash_deinit();
  1409. TEST_ESP_ERR(nvs_get_stats(NULL, NULL), ESP_ERR_INVALID_ARG);
  1410. nvs_stats_t stat1;
  1411. nvs_stats_t stat2;
  1412. TEST_ESP_ERR(nvs_get_stats(NULL, &stat1), ESP_ERR_NVS_NOT_INITIALIZED);
  1413. CHECK(stat1.free_entries == 0);
  1414. CHECK(stat1.namespace_count == 0);
  1415. CHECK(stat1.total_entries == 0);
  1416. CHECK(stat1.used_entries == 0);
  1417. nvs_handle_t handle = 0;
  1418. size_t h_count_entries;
  1419. TEST_ESP_ERR(nvs_get_used_entry_count(handle, &h_count_entries), ESP_ERR_NVS_INVALID_HANDLE);
  1420. CHECK(h_count_entries == 0);
  1421. // init nvs
  1422. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 6));
  1423. TEST_ESP_ERR(nvs_get_used_entry_count(handle, &h_count_entries), ESP_ERR_NVS_INVALID_HANDLE);
  1424. CHECK(h_count_entries == 0);
  1425. Page p;
  1426. // after erase. empty partition
  1427. TEST_ESP_OK(nvs_get_stats(NULL, &stat1));
  1428. CHECK(stat1.free_entries != 0);
  1429. CHECK(stat1.namespace_count == 0);
  1430. CHECK(stat1.total_entries == 6 * p.ENTRY_COUNT);
  1431. CHECK(stat1.used_entries == 0);
  1432. // create namespace test_k1
  1433. nvs_handle_t handle_1;
  1434. TEST_ESP_OK(nvs_open("test_k1", NVS_READWRITE, &handle_1));
  1435. TEST_ESP_OK(nvs_get_stats(NULL, &stat2));
  1436. CHECK(stat2.free_entries + 1 == stat1.free_entries);
  1437. CHECK(stat2.namespace_count == 1);
  1438. CHECK(stat2.total_entries == stat1.total_entries);
  1439. CHECK(stat2.used_entries == 1);
  1440. // create pair key-value com
  1441. TEST_ESP_OK(nvs_set_i32(handle_1, "com", 0x12345678));
  1442. TEST_ESP_OK(nvs_get_stats(NULL, &stat1));
  1443. CHECK(stat1.free_entries + 1 == stat2.free_entries);
  1444. CHECK(stat1.namespace_count == 1);
  1445. CHECK(stat1.total_entries == stat2.total_entries);
  1446. CHECK(stat1.used_entries == 2);
  1447. // change value in com
  1448. TEST_ESP_OK(nvs_set_i32(handle_1, "com", 0x01234567));
  1449. TEST_ESP_OK(nvs_get_stats(NULL, &stat2));
  1450. CHECK(stat2.free_entries == stat1.free_entries);
  1451. CHECK(stat2.namespace_count == 1);
  1452. CHECK(stat2.total_entries != 0);
  1453. CHECK(stat2.used_entries == 2);
  1454. // create pair key-value ru
  1455. TEST_ESP_OK(nvs_set_i32(handle_1, "ru", 0x00FF00FF));
  1456. TEST_ESP_OK(nvs_get_stats(NULL, &stat1));
  1457. CHECK(stat1.free_entries + 1 == stat2.free_entries);
  1458. CHECK(stat1.namespace_count == 1);
  1459. CHECK(stat1.total_entries != 0);
  1460. CHECK(stat1.used_entries == 3);
  1461. // amount valid pair in namespace 1
  1462. size_t h1_count_entries;
  1463. TEST_ESP_OK(nvs_get_used_entry_count(handle_1, &h1_count_entries));
  1464. CHECK(h1_count_entries == 2);
  1465. nvs_handle_t handle_2;
  1466. // create namespace test_k2
  1467. TEST_ESP_OK(nvs_open("test_k2", NVS_READWRITE, &handle_2));
  1468. TEST_ESP_OK(nvs_get_stats(NULL, &stat2));
  1469. CHECK(stat2.free_entries + 1 == stat1.free_entries);
  1470. CHECK(stat2.namespace_count == 2);
  1471. CHECK(stat2.total_entries == stat1.total_entries);
  1472. CHECK(stat2.used_entries == 4);
  1473. // create pair key-value
  1474. TEST_ESP_OK(nvs_set_i32(handle_2, "su1", 0x00000001));
  1475. TEST_ESP_OK(nvs_set_i32(handle_2, "su2", 0x00000002));
  1476. TEST_ESP_OK(nvs_set_i32(handle_2, "sus", 0x00000003));
  1477. TEST_ESP_OK(nvs_get_stats(NULL, &stat1));
  1478. CHECK(stat1.free_entries + 3 == stat2.free_entries);
  1479. CHECK(stat1.namespace_count == 2);
  1480. CHECK(stat1.total_entries == stat2.total_entries);
  1481. CHECK(stat1.used_entries == 7);
  1482. CHECK(stat1.total_entries == (stat1.used_entries + stat1.free_entries));
  1483. // amount valid pair in namespace 2
  1484. size_t h2_count_entries;
  1485. TEST_ESP_OK(nvs_get_used_entry_count(handle_2, &h2_count_entries));
  1486. CHECK(h2_count_entries == 3);
  1487. CHECK(stat1.used_entries == (h1_count_entries + h2_count_entries + stat1.namespace_count));
  1488. nvs_close(handle_1);
  1489. nvs_close(handle_2);
  1490. size_t temp = h2_count_entries;
  1491. TEST_ESP_ERR(nvs_get_used_entry_count(handle_1, &h2_count_entries), ESP_ERR_NVS_INVALID_HANDLE);
  1492. CHECK(h2_count_entries == 0);
  1493. h2_count_entries = temp;
  1494. TEST_ESP_ERR(nvs_get_used_entry_count(handle_1, NULL), ESP_ERR_INVALID_ARG);
  1495. nvs_handle_t handle_3;
  1496. // create namespace test_k3
  1497. TEST_ESP_OK(nvs_open("test_k3", NVS_READWRITE, &handle_3));
  1498. TEST_ESP_OK(nvs_get_stats(NULL, &stat2));
  1499. CHECK(stat2.free_entries + 1 == stat1.free_entries);
  1500. CHECK(stat2.namespace_count == 3);
  1501. CHECK(stat2.total_entries == stat1.total_entries);
  1502. CHECK(stat2.used_entries == 8);
  1503. // create pair blobs
  1504. uint32_t blob[12];
  1505. TEST_ESP_OK(nvs_set_blob(handle_3, "bl1", &blob, sizeof(blob)));
  1506. TEST_ESP_OK(nvs_get_stats(NULL, &stat1));
  1507. CHECK(stat1.free_entries + 4 == stat2.free_entries);
  1508. CHECK(stat1.namespace_count == 3);
  1509. CHECK(stat1.total_entries == stat2.total_entries);
  1510. CHECK(stat1.used_entries == 12);
  1511. // amount valid pair in namespace 2
  1512. size_t h3_count_entries;
  1513. TEST_ESP_OK(nvs_get_used_entry_count(handle_3, &h3_count_entries));
  1514. CHECK(h3_count_entries == 4);
  1515. CHECK(stat1.used_entries == (h1_count_entries + h2_count_entries + h3_count_entries + stat1.namespace_count));
  1516. nvs_close(handle_3);
  1517. }
  1518. TEST_CASE("Recovery from power-off when the entry being erased is not on active page", "[nvs]")
  1519. {
  1520. const size_t blob_size = Page::CHUNK_MAX_SIZE/2 ;
  1521. size_t read_size = blob_size;
  1522. uint8_t blob[blob_size] = {0x11};
  1523. SpiFlashEmulator emu(3);
  1524. TEST_ESP_OK( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3) );
  1525. nvs_handle_t handle;
  1526. TEST_ESP_OK( nvs_open("test", NVS_READWRITE, &handle) );
  1527. emu.clearStats();
  1528. emu.failAfter(Page::CHUNK_MAX_SIZE/4 + 75);
  1529. TEST_ESP_OK( nvs_set_blob(handle, "1a", blob, blob_size) );
  1530. TEST_ESP_OK( nvs_set_blob(handle, "1b", blob, blob_size) );
  1531. TEST_ESP_ERR( nvs_erase_key(handle, "1a"), ESP_ERR_FLASH_OP_FAIL );
  1532. TEST_ESP_OK( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3) );
  1533. /* Check 1a is erased fully*/
  1534. TEST_ESP_ERR( nvs_get_blob(handle, "1a", blob, &read_size), ESP_ERR_NVS_NOT_FOUND);
  1535. /* Check 2b is still accessible*/
  1536. TEST_ESP_OK( nvs_get_blob(handle, "1b", blob, &read_size));
  1537. nvs_close(handle);
  1538. }
  1539. TEST_CASE("Recovery from power-off when page is being freed.", "[nvs]")
  1540. {
  1541. const size_t blob_size = (Page::ENTRY_COUNT-3) * Page::ENTRY_SIZE;
  1542. size_t read_size = blob_size/2;
  1543. uint8_t blob[blob_size] = {0};
  1544. SpiFlashEmulator emu(3);
  1545. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3));
  1546. nvs_handle_t handle;
  1547. TEST_ESP_OK(nvs_open("test", NVS_READWRITE, &handle));
  1548. // Fill first page
  1549. TEST_ESP_OK(nvs_set_blob(handle, "1a", blob, blob_size/3));
  1550. TEST_ESP_OK(nvs_set_blob(handle, "1b", blob, blob_size/3));
  1551. TEST_ESP_OK(nvs_set_blob(handle, "1c", blob, blob_size/4));
  1552. // Fill second page
  1553. TEST_ESP_OK(nvs_set_blob(handle, "2a", blob, blob_size/2));
  1554. TEST_ESP_OK(nvs_set_blob(handle, "2b", blob, blob_size/2));
  1555. TEST_ESP_OK(nvs_erase_key(handle, "1c"));
  1556. emu.clearStats();
  1557. emu.failAfter(6 * Page::ENTRY_COUNT);
  1558. TEST_ESP_ERR(nvs_set_blob(handle, "1d", blob, blob_size/4), ESP_ERR_FLASH_OP_FAIL);
  1559. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3));
  1560. read_size = blob_size/3;
  1561. TEST_ESP_OK( nvs_get_blob(handle, "1a", blob, &read_size));
  1562. TEST_ESP_OK( nvs_get_blob(handle, "1b", blob, &read_size));
  1563. read_size = blob_size /4;
  1564. TEST_ESP_ERR( nvs_get_blob(handle, "1c", blob, &read_size), ESP_ERR_NVS_NOT_FOUND);
  1565. TEST_ESP_ERR( nvs_get_blob(handle, "1d", blob, &read_size), ESP_ERR_NVS_NOT_FOUND);
  1566. read_size = blob_size /2;
  1567. TEST_ESP_OK( nvs_get_blob(handle, "2a", blob, &read_size));
  1568. TEST_ESP_OK( nvs_get_blob(handle, "2b", blob, &read_size));
  1569. TEST_ESP_OK(nvs_commit(handle));
  1570. nvs_close(handle);
  1571. }
  1572. TEST_CASE("Multi-page blobs are supported", "[nvs]")
  1573. {
  1574. const size_t blob_size = Page::CHUNK_MAX_SIZE *2;
  1575. uint8_t blob[blob_size] = {0};
  1576. SpiFlashEmulator emu(5);
  1577. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5));
  1578. nvs_handle_t handle;
  1579. TEST_ESP_OK(nvs_open("test", NVS_READWRITE, &handle));
  1580. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, blob_size));
  1581. TEST_ESP_OK(nvs_commit(handle));
  1582. nvs_close(handle);
  1583. }
  1584. TEST_CASE("Failures are handled while storing multi-page blobs", "[nvs]")
  1585. {
  1586. const size_t blob_size = Page::CHUNK_MAX_SIZE *7;
  1587. uint8_t blob[blob_size] = {0};
  1588. SpiFlashEmulator emu(5);
  1589. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5));
  1590. nvs_handle_t handle;
  1591. TEST_ESP_OK(nvs_open("test", NVS_READWRITE, &handle));
  1592. TEST_ESP_ERR(nvs_set_blob(handle, "abc", blob, blob_size), ESP_ERR_NVS_VALUE_TOO_LONG);
  1593. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, Page::CHUNK_MAX_SIZE*2));
  1594. TEST_ESP_OK(nvs_commit(handle));
  1595. nvs_close(handle);
  1596. }
  1597. TEST_CASE("Reading multi-page blobs", "[nvs]")
  1598. {
  1599. const size_t blob_size = Page::CHUNK_MAX_SIZE *3;
  1600. uint8_t blob[blob_size];
  1601. uint8_t blob_read[blob_size];
  1602. size_t read_size = blob_size;
  1603. SpiFlashEmulator emu(5);
  1604. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5));
  1605. nvs_handle_t handle;
  1606. memset(blob, 0x11, blob_size);
  1607. memset(blob_read, 0xee, blob_size);
  1608. TEST_ESP_OK(nvs_open("readTest", NVS_READWRITE, &handle));
  1609. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, blob_size));
  1610. TEST_ESP_OK(nvs_get_blob(handle, "abc", blob_read, &read_size));
  1611. CHECK(memcmp(blob, blob_read, blob_size) == 0);
  1612. TEST_ESP_OK(nvs_commit(handle));
  1613. nvs_close(handle);
  1614. }
  1615. TEST_CASE("Modification of values for Multi-page blobs are supported", "[nvs]")
  1616. {
  1617. const size_t blob_size = Page::CHUNK_MAX_SIZE *2;
  1618. uint8_t blob[blob_size] = {0};
  1619. uint8_t blob_read[blob_size] = {0xfe};;
  1620. uint8_t blob2[blob_size] = {0x11};
  1621. uint8_t blob3[blob_size] = {0x22};
  1622. uint8_t blob4[blob_size] ={ 0x33};
  1623. size_t read_size = blob_size;
  1624. SpiFlashEmulator emu(6);
  1625. TEST_ESP_OK( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 6) );
  1626. nvs_handle_t handle;
  1627. memset(blob, 0x11, blob_size);
  1628. memset(blob2, 0x22, blob_size);
  1629. memset(blob3, 0x33, blob_size);
  1630. memset(blob4, 0x44, blob_size);
  1631. memset(blob_read, 0xff, blob_size);
  1632. TEST_ESP_OK( nvs_open("test", NVS_READWRITE, &handle) );
  1633. TEST_ESP_OK( nvs_set_blob(handle, "abc", blob, blob_size) );
  1634. TEST_ESP_OK( nvs_set_blob(handle, "abc", blob2, blob_size) );
  1635. TEST_ESP_OK( nvs_set_blob(handle, "abc", blob3, blob_size) );
  1636. TEST_ESP_OK( nvs_set_blob(handle, "abc", blob4, blob_size) );
  1637. TEST_ESP_OK( nvs_get_blob(handle, "abc", blob_read, &read_size));
  1638. CHECK(memcmp(blob4, blob_read, blob_size) == 0);
  1639. TEST_ESP_OK( nvs_commit(handle) );
  1640. nvs_close(handle);
  1641. }
  1642. TEST_CASE("Modification from single page blob to multi-page", "[nvs]")
  1643. {
  1644. const size_t blob_size = Page::CHUNK_MAX_SIZE *3;
  1645. uint8_t blob[blob_size] = {0};
  1646. uint8_t blob_read[blob_size] = {0xff};
  1647. size_t read_size = blob_size;
  1648. SpiFlashEmulator emu(5);
  1649. TEST_ESP_OK( nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5) );
  1650. nvs_handle_t handle;
  1651. TEST_ESP_OK(nvs_open("Test", NVS_READWRITE, &handle) );
  1652. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, Page::CHUNK_MAX_SIZE/2));
  1653. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, blob_size));
  1654. TEST_ESP_OK(nvs_get_blob(handle, "abc", blob_read, &read_size));
  1655. CHECK(memcmp(blob, blob_read, blob_size) == 0);
  1656. TEST_ESP_OK(nvs_commit(handle) );
  1657. nvs_close(handle);
  1658. }
  1659. TEST_CASE("Modification from multi-page to single page", "[nvs]")
  1660. {
  1661. const size_t blob_size = Page::CHUNK_MAX_SIZE *3;
  1662. uint8_t blob[blob_size] = {0};
  1663. uint8_t blob_read[blob_size] = {0xff};
  1664. size_t read_size = blob_size;
  1665. SpiFlashEmulator emu(5);
  1666. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5) );
  1667. nvs_handle_t handle;
  1668. TEST_ESP_OK(nvs_open("Test", NVS_READWRITE, &handle) );
  1669. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, blob_size));
  1670. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, Page::CHUNK_MAX_SIZE/2));
  1671. TEST_ESP_OK(nvs_set_blob(handle, "abc2", blob, blob_size));
  1672. TEST_ESP_OK(nvs_get_blob(handle, "abc", blob_read, &read_size));
  1673. CHECK(memcmp(blob, blob_read, Page::CHUNK_MAX_SIZE) == 0);
  1674. TEST_ESP_OK(nvs_commit(handle) );
  1675. nvs_close(handle);
  1676. }
  1677. TEST_CASE("Multi-page blob erased using nvs_erase_key should not be found when probed for just length", "[nvs]")
  1678. {
  1679. const size_t blob_size = Page::CHUNK_MAX_SIZE *3;
  1680. uint8_t blob[blob_size] = {0};
  1681. size_t read_size = blob_size;
  1682. SpiFlashEmulator emu(5);
  1683. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 5));
  1684. nvs_handle handle;
  1685. TEST_ESP_OK(nvs_open("Test", NVS_READWRITE, &handle));
  1686. TEST_ESP_OK(nvs_set_blob(handle, "abc", blob, blob_size));
  1687. TEST_ESP_OK(nvs_erase_key(handle, "abc"));
  1688. TEST_ESP_ERR(nvs_get_blob(handle, "abc", NULL, &read_size), ESP_ERR_NVS_NOT_FOUND);
  1689. TEST_ESP_OK(nvs_commit(handle));
  1690. nvs_close(handle);
  1691. }
  1692. TEST_CASE("Check that orphaned blobs are erased during init", "[nvs]")
  1693. {
  1694. const size_t blob_size = Page::CHUNK_MAX_SIZE *3 ;
  1695. uint8_t blob[blob_size] = {0x11};
  1696. uint8_t blob2[blob_size] = {0x22};
  1697. uint8_t blob3[blob_size] = {0x33};
  1698. SpiFlashEmulator emu(5);
  1699. Storage storage;
  1700. TEST_ESP_OK(storage.init(0, 5));
  1701. TEST_ESP_OK(storage.writeItem(1, ItemType::BLOB, "key", blob, sizeof(blob)));
  1702. TEST_ESP_OK(storage.init(0, 5));
  1703. /* Check that multi-page item is still available.**/
  1704. TEST_ESP_OK(storage.readItem(1, ItemType::BLOB, "key", blob, sizeof(blob)));
  1705. TEST_ESP_ERR(storage.writeItem(1, ItemType::BLOB, "key2", blob, sizeof(blob)), ESP_ERR_NVS_NOT_ENOUGH_SPACE);
  1706. Page p;
  1707. p.load(3); // This is where index will be placed.
  1708. p.erase();
  1709. TEST_ESP_OK(storage.init(0, 5));
  1710. TEST_ESP_ERR(storage.readItem(1, ItemType::BLOB, "key", blob, sizeof(blob)), ESP_ERR_NVS_NOT_FOUND);
  1711. TEST_ESP_OK(storage.writeItem(1, ItemType::BLOB, "key3", blob, sizeof(blob)));
  1712. }
  1713. TEST_CASE("nvs blob fragmentation test", "[nvs]")
  1714. {
  1715. SpiFlashEmulator emu(4);
  1716. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 4) );
  1717. const size_t BLOB_SIZE = 3500;
  1718. uint8_t *blob = (uint8_t*) malloc(BLOB_SIZE);
  1719. CHECK(blob != NULL);
  1720. memset(blob, 0xEE, BLOB_SIZE);
  1721. const uint32_t magic = 0xff33eaeb;
  1722. nvs_handle_t h;
  1723. TEST_ESP_OK( nvs_open("blob_tests", NVS_READWRITE, &h) );
  1724. for (int i = 0; i < 128; i++) {
  1725. INFO("Iteration " << i << "...\n");
  1726. TEST_ESP_OK( nvs_set_u32(h, "magic", magic) );
  1727. TEST_ESP_OK( nvs_set_blob(h, "blob", blob, BLOB_SIZE) );
  1728. char seq_buf[16];
  1729. sprintf(seq_buf, "seq%d", i);
  1730. TEST_ESP_OK( nvs_set_u32(h, seq_buf, i) );
  1731. }
  1732. free(blob);
  1733. }
  1734. TEST_CASE("nvs code handles errors properly when partition is near to full", "[nvs]")
  1735. {
  1736. const size_t blob_size = Page::CHUNK_MAX_SIZE * 0.3 ;
  1737. uint8_t blob[blob_size] = {0x11};
  1738. SpiFlashEmulator emu(5);
  1739. Storage storage;
  1740. char nvs_key[16] = "";
  1741. TEST_ESP_OK(storage.init(0, 5));
  1742. /* Four pages should fit roughly 12 blobs*/
  1743. for(uint8_t count = 1; count <= 12; count++) {
  1744. sprintf(nvs_key, "key:%u", count);
  1745. TEST_ESP_OK(storage.writeItem(1, ItemType::BLOB, nvs_key, blob, sizeof(blob)));
  1746. }
  1747. for(uint8_t count = 13; count <= 20; count++) {
  1748. sprintf(nvs_key, "key:%u", count);
  1749. TEST_ESP_ERR(storage.writeItem(1, ItemType::BLOB, nvs_key, blob, sizeof(blob)), ESP_ERR_NVS_NOT_ENOUGH_SPACE);
  1750. }
  1751. }
  1752. TEST_CASE("Check for nvs version incompatibility", "[nvs]")
  1753. {
  1754. SpiFlashEmulator emu(3);
  1755. int32_t val1 = 0x12345678;
  1756. Page p;
  1757. p.load(0);
  1758. TEST_ESP_OK(p.setVersion(Page::NVS_VERSION - 1));
  1759. TEST_ESP_OK(p.writeItem(1, ItemType::I32, "foo", &val1, sizeof(val1)));
  1760. TEST_ESP_ERR(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3), ESP_ERR_NVS_NEW_VERSION_FOUND);
  1761. }
  1762. TEST_CASE("Check that NVS supports old blob format without blob index", "[nvs]")
  1763. {
  1764. SpiFlashEmulator emu("../nvs_partition_generator/part_old_blob_format.bin");
  1765. nvs_handle_t handle;
  1766. TEST_ESP_OK( nvs_flash_init_custom("test", 0, 2) );
  1767. TEST_ESP_OK( nvs_open_from_partition("test", "dummyNamespace", NVS_READONLY, &handle));
  1768. char buf[64] = {0};
  1769. size_t buflen = 64;
  1770. uint8_t hexdata[] = {0x01, 0x02, 0x03, 0xab, 0xcd, 0xef};
  1771. TEST_ESP_OK( nvs_get_blob(handle, "dummyHex2BinKey", buf, &buflen));
  1772. CHECK(memcmp(buf, hexdata, buflen) == 0);
  1773. buflen = 64;
  1774. uint8_t base64data[] = {'1', '2', '3', 'a', 'b', 'c'};
  1775. TEST_ESP_OK( nvs_get_blob(handle, "dummyBase64Key", buf, &buflen));
  1776. CHECK(memcmp(buf, base64data, buflen) == 0);
  1777. Page p;
  1778. p.load(0);
  1779. /* Check that item is stored in old format without blob index*/
  1780. TEST_ESP_OK(p.findItem(1, ItemType::BLOB, "dummyHex2BinKey"));
  1781. /* Modify the blob so that it is stored in the new format*/
  1782. hexdata[0] = hexdata[1] = hexdata[2] = 0x99;
  1783. TEST_ESP_OK(nvs_set_blob(handle, "dummyHex2BinKey", hexdata, sizeof(hexdata)));
  1784. Page p2;
  1785. p2.load(0);
  1786. /* Check the type of the blob. Expect type mismatch since the blob is stored in new format*/
  1787. TEST_ESP_ERR(p2.findItem(1, ItemType::BLOB, "dummyHex2BinKey"), ESP_ERR_NVS_TYPE_MISMATCH);
  1788. /* Check that index is present for the modified blob according to new format*/
  1789. TEST_ESP_OK(p2.findItem(1, ItemType::BLOB_IDX, "dummyHex2BinKey"));
  1790. /* Read the blob in new format and check the contents*/
  1791. buflen = 64;
  1792. TEST_ESP_OK( nvs_get_blob(handle, "dummyBase64Key", buf, &buflen));
  1793. CHECK(memcmp(buf, base64data, buflen) == 0);
  1794. }
  1795. TEST_CASE("monkey test with old-format blob present", "[nvs][monkey]")
  1796. {
  1797. std::random_device rd;
  1798. std::mt19937 gen(rd());
  1799. uint32_t seed = 3;
  1800. gen.seed(seed);
  1801. SpiFlashEmulator emu(10);
  1802. emu.randomize(seed);
  1803. emu.clearStats();
  1804. const uint32_t NVS_FLASH_SECTOR = 2;
  1805. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 8;
  1806. static const size_t smallBlobLen = Page::CHUNK_MAX_SIZE / 3;
  1807. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  1808. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  1809. nvs_handle_t handle;
  1810. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1811. RandomTest test;
  1812. for ( uint8_t it = 0; it < 10; it++) {
  1813. size_t count = 200;
  1814. /* Erase index and chunks for the blob with "singlepage" key */
  1815. for (uint8_t num = NVS_FLASH_SECTOR; num < NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN; num++) {
  1816. Page p;
  1817. p.load(num);
  1818. p.eraseItem(1, ItemType::BLOB, "singlepage", Item::CHUNK_ANY, VerOffset::VER_ANY);
  1819. p.eraseItem(1, ItemType::BLOB_IDX, "singlepage", Item::CHUNK_ANY, VerOffset::VER_ANY);
  1820. p.eraseItem(1, ItemType::BLOB_DATA, "singlepage", Item::CHUNK_ANY, VerOffset::VER_ANY);
  1821. }
  1822. /* Now write "singlepage" blob in old format*/
  1823. for (uint8_t num = NVS_FLASH_SECTOR; num < NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN; num++) {
  1824. Page p;
  1825. p.load(num);
  1826. if (p.state() == Page::PageState::ACTIVE) {
  1827. uint8_t buf[smallBlobLen];
  1828. size_t blobLen = gen() % smallBlobLen;
  1829. if(blobLen > p.getVarDataTailroom()) {
  1830. blobLen = p.getVarDataTailroom();
  1831. }
  1832. std::generate_n(buf, blobLen, [&]() -> uint8_t {
  1833. return static_cast<uint8_t>(gen() % 256);
  1834. });
  1835. TEST_ESP_OK(p.writeItem(1, ItemType::BLOB, "singlepage", buf, blobLen, Item::CHUNK_ANY));
  1836. TEST_ESP_OK(p.findItem(1, ItemType::BLOB, "singlepage"));
  1837. test.handleExternalWriteAtIndex(9, buf, blobLen); // This assumes "singlepage" is always at index 9
  1838. break;
  1839. }
  1840. }
  1841. /* Initialize again */
  1842. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN));
  1843. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1844. /* Perform random things */
  1845. auto res = test.doRandomThings(handle, gen, count);
  1846. if (res != ESP_OK) {
  1847. nvs_dump(NVS_DEFAULT_PART_NAME);
  1848. CHECK(0);
  1849. }
  1850. /* Check that only one version is present for "singlepage". Its possible that last iteration did not write
  1851. * anything for "singlepage". So either old version or new version should be present.*/
  1852. bool oldVerPresent = false, newVerPresent = false;
  1853. for (uint8_t num = NVS_FLASH_SECTOR; num < NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN; num++) {
  1854. Page p;
  1855. p.load(num);
  1856. if(!oldVerPresent && p.findItem(1, ItemType::BLOB, "singlepage", Item::CHUNK_ANY, VerOffset::VER_ANY) == ESP_OK) {
  1857. oldVerPresent = true;
  1858. }
  1859. if(!newVerPresent && p.findItem(1, ItemType::BLOB_IDX, "singlepage", Item::CHUNK_ANY, VerOffset::VER_ANY) == ESP_OK) {
  1860. newVerPresent = true;
  1861. }
  1862. }
  1863. CHECK(oldVerPresent != newVerPresent);
  1864. }
  1865. s_perf << "Monkey test: nErase=" << emu.getEraseOps() << " nWrite=" << emu.getWriteOps() << std::endl;
  1866. }
  1867. TEST_CASE("Recovery from power-off during modification of blob present in old-format (same page)", "[nvs]")
  1868. {
  1869. std::random_device rd;
  1870. std::mt19937 gen(rd());
  1871. uint32_t seed = 3;
  1872. gen.seed(seed);
  1873. SpiFlashEmulator emu(3);
  1874. emu.clearStats();
  1875. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3));
  1876. nvs_handle_t handle;
  1877. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1878. uint8_t hexdata[] = {0x01, 0x02, 0x03, 0xab, 0xcd, 0xef};
  1879. uint8_t hexdata_old[] = {0x11, 0x12, 0x13, 0xbb, 0xcc, 0xee};
  1880. size_t buflen = sizeof(hexdata);
  1881. uint8_t buf[Page::CHUNK_MAX_SIZE];
  1882. /* Power-off when blob was being written on the same page where its old version in old format
  1883. * was present*/
  1884. Page p;
  1885. p.load(0);
  1886. /* Write blob in old-format*/
  1887. TEST_ESP_OK(p.writeItem(1, ItemType::BLOB, "singlepage", hexdata_old, sizeof(hexdata_old)));
  1888. /* Write blob in new format*/
  1889. TEST_ESP_OK(p.writeItem(1, ItemType::BLOB_DATA, "singlepage", hexdata, sizeof(hexdata), 0));
  1890. /* All pages are stored. Now store the index.*/
  1891. Item item;
  1892. item.blobIndex.dataSize = sizeof(hexdata);
  1893. item.blobIndex.chunkCount = 1;
  1894. item.blobIndex.chunkStart = VerOffset::VER_0_OFFSET;
  1895. TEST_ESP_OK(p.writeItem(1, ItemType::BLOB_IDX, "singlepage", item.data, sizeof(item.data)));
  1896. TEST_ESP_OK(p.findItem(1, ItemType::BLOB, "singlepage"));
  1897. /* Initialize again */
  1898. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3));
  1899. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1900. TEST_ESP_OK( nvs_get_blob(handle, "singlepage", buf, &buflen));
  1901. CHECK(memcmp(buf, hexdata, buflen) == 0);
  1902. Page p2;
  1903. p2.load(0);
  1904. TEST_ESP_ERR(p2.findItem(1, ItemType::BLOB, "singlepage"), ESP_ERR_NVS_TYPE_MISMATCH);
  1905. }
  1906. TEST_CASE("Recovery from power-off during modification of blob present in old-format (different page)", "[nvs]")
  1907. {
  1908. std::random_device rd;
  1909. std::mt19937 gen(rd());
  1910. uint32_t seed = 3;
  1911. gen.seed(seed);
  1912. SpiFlashEmulator emu(3);
  1913. emu.clearStats();
  1914. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3));
  1915. nvs_handle_t handle;
  1916. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1917. uint8_t hexdata[] = {0x01, 0x02, 0x03, 0xab, 0xcd, 0xef};
  1918. uint8_t hexdata_old[] = {0x11, 0x12, 0x13, 0xbb, 0xcc, 0xee};
  1919. size_t buflen = sizeof(hexdata);
  1920. uint8_t buf[Page::CHUNK_MAX_SIZE];
  1921. /* Power-off when blob was being written on the different page where its old version in old format
  1922. * was present*/
  1923. Page p;
  1924. p.load(0);
  1925. /* Write blob in old-format*/
  1926. TEST_ESP_OK(p.writeItem(1, ItemType::BLOB, "singlepage", hexdata_old, sizeof(hexdata_old)));
  1927. /* Write blob in new format*/
  1928. TEST_ESP_OK(p.writeItem(1, ItemType::BLOB_DATA, "singlepage", hexdata, sizeof(hexdata), 0));
  1929. /* All pages are stored. Now store the index.*/
  1930. Item item;
  1931. item.blobIndex.dataSize = sizeof(hexdata);
  1932. item.blobIndex.chunkCount = 1;
  1933. item.blobIndex.chunkStart = VerOffset::VER_0_OFFSET;
  1934. p.markFull();
  1935. Page p2;
  1936. p2.load(1);
  1937. p2.setSeqNumber(1);
  1938. TEST_ESP_OK(p2.writeItem(1, ItemType::BLOB_IDX, "singlepage", item.data, sizeof(item.data)));
  1939. TEST_ESP_OK(p.findItem(1, ItemType::BLOB, "singlepage"));
  1940. /* Initialize again */
  1941. TEST_ESP_OK(nvs_flash_init_custom(NVS_DEFAULT_PART_NAME, 0, 3));
  1942. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle));
  1943. TEST_ESP_OK( nvs_get_blob(handle, "singlepage", buf, &buflen));
  1944. CHECK(memcmp(buf, hexdata, buflen) == 0);
  1945. Page p3;
  1946. p3.load(0);
  1947. TEST_ESP_ERR(p3.findItem(1, ItemType::BLOB, "singlepage"), ESP_ERR_NVS_NOT_FOUND);
  1948. }
  1949. static void check_nvs_part_gen_args(char const *part_name, int size, char const *filename, bool is_encr, nvs_sec_cfg_t* xts_cfg)
  1950. {
  1951. nvs_handle_t handle;
  1952. if (is_encr)
  1953. TEST_ESP_OK(nvs_flash_secure_init_custom(part_name, 0, size, xts_cfg));
  1954. else
  1955. TEST_ESP_OK( nvs_flash_init_custom(part_name, 0, size) );
  1956. TEST_ESP_OK( nvs_open_from_partition(part_name, "dummyNamespace", NVS_READONLY, &handle));
  1957. uint8_t u8v;
  1958. TEST_ESP_OK( nvs_get_u8(handle, "dummyU8Key", &u8v));
  1959. CHECK(u8v == 127);
  1960. int8_t i8v;
  1961. TEST_ESP_OK( nvs_get_i8(handle, "dummyI8Key", &i8v));
  1962. CHECK(i8v == -128);
  1963. uint16_t u16v;
  1964. TEST_ESP_OK( nvs_get_u16(handle, "dummyU16Key", &u16v));
  1965. CHECK(u16v == 32768);
  1966. uint32_t u32v;
  1967. TEST_ESP_OK( nvs_get_u32(handle, "dummyU32Key", &u32v));
  1968. CHECK(u32v == 4294967295);
  1969. int32_t i32v;
  1970. TEST_ESP_OK( nvs_get_i32(handle, "dummyI32Key", &i32v));
  1971. CHECK(i32v == -2147483648);
  1972. char buf[64] = {0};
  1973. size_t buflen = 64;
  1974. TEST_ESP_OK( nvs_get_str(handle, "dummyStringKey", buf, &buflen));
  1975. CHECK(strncmp(buf, "0A:0B:0C:0D:0E:0F", buflen) == 0);
  1976. uint8_t hexdata[] = {0x01, 0x02, 0x03, 0xab, 0xcd, 0xef};
  1977. buflen = 64;
  1978. int j;
  1979. TEST_ESP_OK( nvs_get_blob(handle, "dummyHex2BinKey", buf, &buflen));
  1980. CHECK(memcmp(buf, hexdata, buflen) == 0);
  1981. uint8_t base64data[] = {'1', '2', '3', 'a', 'b', 'c'};
  1982. TEST_ESP_OK( nvs_get_blob(handle, "dummyBase64Key", buf, &buflen));
  1983. CHECK(memcmp(buf, base64data, buflen) == 0);
  1984. buflen = 64;
  1985. uint8_t hexfiledata[] = {0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef};
  1986. TEST_ESP_OK( nvs_get_blob(handle, "hexFileKey", buf, &buflen));
  1987. CHECK(memcmp(buf, hexfiledata, buflen) == 0);
  1988. buflen = 64;
  1989. uint8_t strfiledata[64] = "abcdefghijklmnopqrstuvwxyz\0";
  1990. TEST_ESP_OK( nvs_get_str(handle, "stringFileKey", buf, &buflen));
  1991. CHECK(memcmp(buf, strfiledata, buflen) == 0);
  1992. char bin_data[5200];
  1993. size_t bin_len = sizeof(bin_data);
  1994. char binfiledata[5200];
  1995. ifstream file;
  1996. file.open(filename);
  1997. file.read(binfiledata,5200);
  1998. TEST_ESP_OK( nvs_get_blob(handle, "binFileKey", bin_data, &bin_len));
  1999. CHECK(memcmp(bin_data, binfiledata, bin_len) == 0);
  2000. file.close();
  2001. nvs_close(handle);
  2002. }
  2003. TEST_CASE("check and read data from partition generated via partition generation utility with multipage blob support disabled", "[nvs_part_gen]")
  2004. {
  2005. int status;
  2006. int childpid = fork();
  2007. if (childpid == 0) {
  2008. exit(execlp("cp", " cp",
  2009. "-rf",
  2010. "../nvs_partition_generator/testdata",
  2011. ".",NULL));
  2012. } else {
  2013. CHECK(childpid > 0);
  2014. waitpid(childpid, &status, 0);
  2015. CHECK(WEXITSTATUS(status) != -1);
  2016. childpid = fork();
  2017. if (childpid == 0) {
  2018. exit(execlp("python", "python",
  2019. "../nvs_partition_generator/nvs_partition_gen.py",
  2020. "generate",
  2021. "../nvs_partition_generator/sample_singlepage_blob.csv",
  2022. "partition_single_page.bin",
  2023. "0x3000",
  2024. "--version",
  2025. "1",
  2026. "--outdir",
  2027. "../nvs_partition_generator",NULL));
  2028. } else {
  2029. CHECK(childpid > 0);
  2030. int status;
  2031. waitpid(childpid, &status, 0);
  2032. CHECK(WEXITSTATUS(status) != -1);
  2033. }
  2034. }
  2035. SpiFlashEmulator emu("../nvs_partition_generator/partition_single_page.bin");
  2036. TEST_ESP_OK(nvs_flash_deinit());
  2037. check_nvs_part_gen_args("test", 3, "../nvs_partition_generator/testdata/sample_singlepage_blob.bin", false, NULL);
  2038. childpid = fork();
  2039. if (childpid == 0) {
  2040. exit(execlp("rm", " rm",
  2041. "-rf",
  2042. "testdata",NULL));
  2043. } else {
  2044. CHECK(childpid > 0);
  2045. waitpid(childpid, &status, 0);
  2046. CHECK(WEXITSTATUS(status) != -1);
  2047. }
  2048. }
  2049. TEST_CASE("check and read data from partition generated via partition generation utility with multipage blob support enabled", "[nvs_part_gen]")
  2050. {
  2051. int status;
  2052. int childpid = fork();
  2053. if (childpid == 0) {
  2054. exit(execlp("cp", " cp",
  2055. "-rf",
  2056. "../nvs_partition_generator/testdata",
  2057. ".",NULL));
  2058. } else {
  2059. CHECK(childpid > 0);
  2060. waitpid(childpid, &status, 0);
  2061. CHECK(WEXITSTATUS(status) != -1);
  2062. childpid = fork();
  2063. if (childpid == 0) {
  2064. exit(execlp("python", "python",
  2065. "../nvs_partition_generator/nvs_partition_gen.py",
  2066. "generate",
  2067. "../nvs_partition_generator/sample_multipage_blob.csv",
  2068. "partition_multipage_blob.bin",
  2069. "0x4000",
  2070. "--version",
  2071. "2",
  2072. "--outdir",
  2073. "../nvs_partition_generator",NULL));
  2074. } else {
  2075. CHECK(childpid > 0);
  2076. waitpid(childpid, &status, 0);
  2077. CHECK(WEXITSTATUS(status) != -1);
  2078. }
  2079. }
  2080. SpiFlashEmulator emu("../nvs_partition_generator/partition_multipage_blob.bin");
  2081. check_nvs_part_gen_args("test", 4, "../nvs_partition_generator/testdata/sample_multipage_blob.bin",false,NULL);
  2082. childpid = fork();
  2083. if (childpid == 0) {
  2084. exit(execlp("rm", " rm",
  2085. "-rf",
  2086. "testdata",NULL));
  2087. } else {
  2088. CHECK(childpid > 0);
  2089. waitpid(childpid, &status, 0);
  2090. CHECK(WEXITSTATUS(status) != -1);
  2091. }
  2092. }
  2093. #if false
  2094. TEST_CASE("check and read data from partition generated via manufacturing utility with multipage blob support disabled", "[mfg_gen]")
  2095. {
  2096. int childpid = fork();
  2097. int status;
  2098. if (childpid == 0) {
  2099. exit(execlp("bash", "bash",
  2100. "-c",
  2101. "rm -rf ../../../tools/mass_mfg/host_test && \
  2102. cp -rf ../../../tools/mass_mfg/testdata mfg_testdata && \
  2103. cp -rf ../nvs_partition_generator/testdata . && \
  2104. mkdir -p ../../../tools/mass_mfg/host_test", NULL));
  2105. } else {
  2106. CHECK(childpid > 0);
  2107. waitpid(childpid, &status, 0);
  2108. CHECK(WEXITSTATUS(status) != -1);
  2109. childpid = fork();
  2110. if (childpid == 0) {
  2111. exit(execlp("python", "python",
  2112. "../../../tools/mass_mfg/mfg_gen.py",
  2113. "--conf",
  2114. "../../../tools/mass_mfg/samples/sample_config.csv",
  2115. "--values",
  2116. "../../../tools/mass_mfg/samples/sample_values_singlepage_blob.csv",
  2117. "--prefix",
  2118. "Test",
  2119. "--size",
  2120. "0x3000",
  2121. "--outdir",
  2122. "../../../tools/mass_mfg/host_test",
  2123. "--version",
  2124. "v1",NULL));
  2125. } else {
  2126. CHECK(childpid > 0);
  2127. waitpid(childpid, &status, 0);
  2128. CHECK(WEXITSTATUS(status) != -1);
  2129. childpid = fork();
  2130. if (childpid == 0) {
  2131. exit(execlp("python", "python",
  2132. "../nvs_partition_generator/nvs_partition_gen.py",
  2133. "--input",
  2134. "../../../tools/mass_mfg/host_test/csv/Test-1.csv",
  2135. "--output",
  2136. "../nvs_partition_generator/Test-1-partition.bin",
  2137. "--size",
  2138. "0x3000",
  2139. "--version",
  2140. "v1",NULL));
  2141. } else {
  2142. CHECK(childpid > 0);
  2143. waitpid(childpid, &status, 0);
  2144. CHECK(WEXITSTATUS(status) != -1);
  2145. }
  2146. }
  2147. }
  2148. SpiFlashEmulator emu1("../../../tools/mass_mfg/host_test/bin/Test-1.bin");
  2149. check_nvs_part_gen_args("test", 3, "mfg_testdata/sample_singlepage_blob.bin", false, NULL);
  2150. SpiFlashEmulator emu2("../nvs_partition_generator/Test-1-partition.bin");
  2151. check_nvs_part_gen_args("test", 3, "testdata/sample_singlepage_blob.bin", false, NULL);
  2152. childpid = fork();
  2153. if (childpid == 0) {
  2154. exit(execlp("bash", " bash",
  2155. "-c",
  2156. "rm -rf ../../../tools/mass_mfg/host_test | \
  2157. rm -rf mfg_testdata | \
  2158. rm -rf testdata",NULL));
  2159. } else {
  2160. CHECK(childpid > 0);
  2161. waitpid(childpid, &status, 0);
  2162. CHECK(WEXITSTATUS(status) != -1);
  2163. }
  2164. }
  2165. TEST_CASE("check and read data from partition generated via manufacturing utility with multipage blob support enabled", "[mfg_gen]")
  2166. {
  2167. int childpid = fork();
  2168. int status;
  2169. if (childpid == 0) {
  2170. exit(execlp("bash", " bash",
  2171. "-c",
  2172. "rm -rf ../../../tools/mass_mfg/host_test | \
  2173. cp -rf ../../../tools/mass_mfg/testdata mfg_testdata | \
  2174. cp -rf ../nvs_partition_generator/testdata . | \
  2175. mkdir -p ../../../tools/mass_mfg/host_test",NULL));
  2176. } else {
  2177. CHECK(childpid > 0);
  2178. waitpid(childpid, &status, 0);
  2179. CHECK(WEXITSTATUS(status) != -1);
  2180. childpid = fork();
  2181. if (childpid == 0) {
  2182. exit(execlp("python", "python",
  2183. "../../../tools/mass_mfg/mfg_gen.py",
  2184. "--conf",
  2185. "../../../tools/mass_mfg/samples/sample_config.csv",
  2186. "--values",
  2187. "../../../tools/mass_mfg/samples/sample_values_multipage_blob.csv",
  2188. "--prefix",
  2189. "Test",
  2190. "--size",
  2191. "0x4000",
  2192. "--outdir",
  2193. "../../../tools/mass_mfg/host_test",
  2194. "--version",
  2195. "v2",NULL));
  2196. } else {
  2197. CHECK(childpid > 0);
  2198. waitpid(childpid, &status, 0);
  2199. CHECK(WEXITSTATUS(status) != -1);
  2200. childpid = fork();
  2201. if (childpid == 0) {
  2202. exit(execlp("python", "python",
  2203. "../nvs_partition_generator/nvs_partition_gen.py",
  2204. "--input",
  2205. "../../../tools/mass_mfg/host_test/csv/Test-1.csv",
  2206. "--output",
  2207. "../nvs_partition_generator/Test-1-partition.bin",
  2208. "--size",
  2209. "0x4000",
  2210. "--version",
  2211. "v2",NULL));
  2212. } else {
  2213. CHECK(childpid > 0);
  2214. waitpid(childpid, &status, 0);
  2215. CHECK(WEXITSTATUS(status) != -1);
  2216. }
  2217. }
  2218. }
  2219. SpiFlashEmulator emu1("../../../tools/mass_mfg/host_test/bin/Test-1.bin");
  2220. check_nvs_part_gen_args("test", 4, "mfg_testdata/sample_multipage_blob.bin", false, NULL);
  2221. SpiFlashEmulator emu2("../nvs_partition_generator/Test-1-partition.bin");
  2222. check_nvs_part_gen_args("test", 4, "testdata/sample_multipage_blob.bin", false, NULL);
  2223. childpid = fork();
  2224. if (childpid == 0) {
  2225. exit(execlp("bash", " bash",
  2226. "-c",
  2227. "rm -rf ../../../tools/mass_mfg/host_test | \
  2228. rm -rf mfg_testdata | \
  2229. rm -rf testdata",NULL));
  2230. } else {
  2231. CHECK(childpid > 0);
  2232. waitpid(childpid, &status, 0);
  2233. CHECK(WEXITSTATUS(status) != -1);
  2234. }
  2235. }
  2236. #endif
  2237. #if CONFIG_NVS_ENCRYPTION
  2238. TEST_CASE("check underlying xts code for 32-byte size sector encryption", "[nvs]")
  2239. {
  2240. auto toHex = [](char ch) {
  2241. if(ch >= '0' && ch <= '9')
  2242. return ch - '0';
  2243. else if(ch >= 'a' && ch <= 'f')
  2244. return ch - 'a' + 10;
  2245. else if(ch >= 'A' && ch <= 'F')
  2246. return ch - 'A' + 10;
  2247. else
  2248. return 0;
  2249. };
  2250. auto toHexByte = [toHex](char* c) {
  2251. return 16 * toHex(c[0]) + toHex(c[1]);
  2252. };
  2253. auto toHexStream = [toHexByte](char* src, uint8_t* dest) {
  2254. uint32_t cnt =0;
  2255. char* p = src;
  2256. while(*p != '\0' && *(p + 1) != '\0')
  2257. {
  2258. dest[cnt++] = toHexByte(p); p += 2;
  2259. }
  2260. };
  2261. uint8_t eky_hex[2 * NVS_KEY_SIZE];
  2262. uint8_t ptxt_hex[Page::ENTRY_SIZE], ctxt_hex[Page::ENTRY_SIZE], ba_hex[16];
  2263. mbedtls_aes_xts_context ectx[1];
  2264. mbedtls_aes_xts_context dctx[1];
  2265. char eky[][2 * NVS_KEY_SIZE + 1] = {
  2266. "0000000000000000000000000000000000000000000000000000000000000000",
  2267. "1111111111111111111111111111111111111111111111111111111111111111"
  2268. };
  2269. char tky[][2 * NVS_KEY_SIZE + 1] = {
  2270. "0000000000000000000000000000000000000000000000000000000000000000",
  2271. "2222222222222222222222222222222222222222222222222222222222222222"
  2272. };
  2273. char blk_addr[][2*16 + 1] = {
  2274. "00000000000000000000000000000000",
  2275. "33333333330000000000000000000000"
  2276. };
  2277. char ptxt[][2 * Page::ENTRY_SIZE + 1] = {
  2278. "0000000000000000000000000000000000000000000000000000000000000000",
  2279. "4444444444444444444444444444444444444444444444444444444444444444"
  2280. };
  2281. char ctxt[][2 * Page::ENTRY_SIZE + 1] = {
  2282. "d456b4fc2e620bba6ffbed27b956c9543454dd49ebd8d8ee6f94b65cbe158f73",
  2283. "e622334f184bbce129a25b2ac76b3d92abf98e22df5bdd15af471f3db8946a85"
  2284. };
  2285. mbedtls_aes_xts_init(ectx);
  2286. mbedtls_aes_xts_init(dctx);
  2287. for(uint8_t cnt = 0; cnt < sizeof(eky)/sizeof(eky[0]); cnt++) {
  2288. toHexStream(eky[cnt], eky_hex);
  2289. toHexStream(tky[cnt], &eky_hex[NVS_KEY_SIZE]);
  2290. toHexStream(ptxt[cnt], ptxt_hex);
  2291. toHexStream(ctxt[cnt], ctxt_hex);
  2292. toHexStream(blk_addr[cnt], ba_hex);
  2293. CHECK(!mbedtls_aes_xts_setkey_enc(ectx, eky_hex, 2 * NVS_KEY_SIZE * 8));
  2294. CHECK(!mbedtls_aes_xts_setkey_enc(dctx, eky_hex, 2 * NVS_KEY_SIZE * 8));
  2295. CHECK(!mbedtls_aes_crypt_xts(ectx, MBEDTLS_AES_ENCRYPT, Page::ENTRY_SIZE, ba_hex, ptxt_hex, ptxt_hex));
  2296. CHECK(!memcmp(ptxt_hex, ctxt_hex, Page::ENTRY_SIZE));
  2297. }
  2298. }
  2299. TEST_CASE("test nvs apis with encryption enabled", "[nvs]")
  2300. {
  2301. SpiFlashEmulator emu(10);
  2302. emu.randomize(100);
  2303. nvs_handle_t handle_1;
  2304. const uint32_t NVS_FLASH_SECTOR = 6;
  2305. const uint32_t NVS_FLASH_SECTOR_COUNT_MIN = 3;
  2306. emu.setBounds(NVS_FLASH_SECTOR, NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN);
  2307. nvs_sec_cfg_t xts_cfg;
  2308. for(int count = 0; count < NVS_KEY_SIZE; count++) {
  2309. xts_cfg.eky[count] = 0x11;
  2310. xts_cfg.tky[count] = 0x22;
  2311. }
  2312. for (uint16_t i = NVS_FLASH_SECTOR; i <NVS_FLASH_SECTOR + NVS_FLASH_SECTOR_COUNT_MIN; ++i) {
  2313. spi_flash_erase_sector(i);
  2314. }
  2315. TEST_ESP_OK(nvs_flash_secure_init_custom(NVS_DEFAULT_PART_NAME, NVS_FLASH_SECTOR, NVS_FLASH_SECTOR_COUNT_MIN, &xts_cfg));
  2316. TEST_ESP_ERR(nvs_open("namespace1", NVS_READONLY, &handle_1), ESP_ERR_NVS_NOT_FOUND);
  2317. TEST_ESP_OK(nvs_open("namespace1", NVS_READWRITE, &handle_1));
  2318. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x12345678));
  2319. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x23456789));
  2320. nvs_handle_t handle_2;
  2321. TEST_ESP_OK(nvs_open("namespace2", NVS_READWRITE, &handle_2));
  2322. TEST_ESP_OK(nvs_set_i32(handle_2, "foo", 0x3456789a));
  2323. const char* str = "value 0123456789abcdef0123456789abcdef";
  2324. TEST_ESP_OK(nvs_set_str(handle_2, "key", str));
  2325. int32_t v1;
  2326. TEST_ESP_OK(nvs_get_i32(handle_1, "foo", &v1));
  2327. CHECK(0x23456789 == v1);
  2328. int32_t v2;
  2329. TEST_ESP_OK(nvs_get_i32(handle_2, "foo", &v2));
  2330. CHECK(0x3456789a == v2);
  2331. char buf[strlen(str) + 1];
  2332. size_t buf_len = sizeof(buf);
  2333. size_t buf_len_needed;
  2334. TEST_ESP_OK(nvs_get_str(handle_2, "key", NULL, &buf_len_needed));
  2335. CHECK(buf_len_needed == buf_len);
  2336. size_t buf_len_short = buf_len - 1;
  2337. TEST_ESP_ERR(ESP_ERR_NVS_INVALID_LENGTH, nvs_get_str(handle_2, "key", buf, &buf_len_short));
  2338. CHECK(buf_len_short == buf_len);
  2339. size_t buf_len_long = buf_len + 1;
  2340. TEST_ESP_OK(nvs_get_str(handle_2, "key", buf, &buf_len_long));
  2341. CHECK(buf_len_long == buf_len);
  2342. TEST_ESP_OK(nvs_get_str(handle_2, "key", buf, &buf_len));
  2343. CHECK(0 == strcmp(buf, str));
  2344. nvs_close(handle_1);
  2345. nvs_close(handle_2);
  2346. TEST_ESP_OK(nvs_flash_deinit());
  2347. }
  2348. TEST_CASE("test nvs apis for nvs partition generator utility with encryption enabled", "[nvs_part_gen]")
  2349. {
  2350. int status;
  2351. int childpid = fork();
  2352. if (childpid == 0) {
  2353. exit(execlp("cp", " cp",
  2354. "-rf",
  2355. "../nvs_partition_generator/testdata",
  2356. ".",NULL));
  2357. } else {
  2358. CHECK(childpid > 0);
  2359. waitpid(childpid, &status, 0);
  2360. CHECK(WEXITSTATUS(status) != -1);
  2361. childpid = fork();
  2362. if (childpid == 0) {
  2363. exit(execlp("python", "python",
  2364. "../nvs_partition_generator/nvs_partition_gen.py",
  2365. "encrypt",
  2366. "../nvs_partition_generator/sample_multipage_blob.csv",
  2367. "partition_encrypted.bin",
  2368. "0x4000",
  2369. "--inputkey",
  2370. "../nvs_partition_generator/testdata/sample_encryption_keys.bin",
  2371. "--outdir",
  2372. "../nvs_partition_generator",NULL));
  2373. } else {
  2374. CHECK(childpid > 0);
  2375. waitpid(childpid, &status, 0);
  2376. CHECK(WEXITSTATUS(status) != -1);
  2377. }
  2378. }
  2379. SpiFlashEmulator emu("../nvs_partition_generator/partition_encrypted.bin");
  2380. nvs_sec_cfg_t cfg;
  2381. for(int count = 0; count < NVS_KEY_SIZE; count++) {
  2382. cfg.eky[count] = 0x11;
  2383. cfg.tky[count] = 0x22;
  2384. }
  2385. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "../nvs_partition_generator/testdata/sample_multipage_blob.bin", true, &cfg);
  2386. childpid = fork();
  2387. if (childpid == 0) {
  2388. exit(execlp("rm", " rm",
  2389. "-rf",
  2390. "testdata",NULL));
  2391. } else {
  2392. CHECK(childpid > 0);
  2393. waitpid(childpid, &status, 0);
  2394. CHECK(WEXITSTATUS(status) != -1);
  2395. }
  2396. }
  2397. TEST_CASE("test nvs apis for nvs partition generator utility with encryption enabled using keygen", "[nvs_part_gen]")
  2398. {
  2399. int childpid = fork();
  2400. int status;
  2401. if (childpid == 0) {
  2402. exit(execlp("cp", " cp",
  2403. "-rf",
  2404. "../nvs_partition_generator/testdata",
  2405. ".",NULL));
  2406. } else {
  2407. CHECK(childpid > 0);
  2408. waitpid(childpid, &status, 0);
  2409. CHECK(WEXITSTATUS(status) != -1);
  2410. childpid = fork();
  2411. if (childpid == 0) {
  2412. exit(execlp("rm", " rm",
  2413. "-rf",
  2414. "../nvs_partition_generator/keys",NULL));
  2415. } else {
  2416. CHECK(childpid > 0);
  2417. waitpid(childpid, &status, 0);
  2418. CHECK(WEXITSTATUS(status) != -1);
  2419. childpid = fork();
  2420. if (childpid == 0) {
  2421. exit(execlp("python", "python",
  2422. "../nvs_partition_generator/nvs_partition_gen.py",
  2423. "encrypt",
  2424. "../nvs_partition_generator/sample_multipage_blob.csv",
  2425. "partition_encrypted_using_keygen.bin",
  2426. "0x4000",
  2427. "--keygen",
  2428. "--outdir",
  2429. "../nvs_partition_generator",NULL));
  2430. } else {
  2431. CHECK(childpid > 0);
  2432. waitpid(childpid, &status, 0);
  2433. CHECK(WEXITSTATUS(status) != -1);
  2434. }
  2435. }
  2436. }
  2437. DIR *dir;
  2438. struct dirent *file;
  2439. char *filename;
  2440. char *files;
  2441. char *file_ext;
  2442. dir = opendir("../nvs_partition_generator/keys");
  2443. while ((file = readdir(dir)) != NULL)
  2444. {
  2445. filename = file->d_name;
  2446. files = strrchr(filename, '.');
  2447. if (files != NULL)
  2448. {
  2449. file_ext = files+1;
  2450. if (strncmp(file_ext,"bin",3) == 0)
  2451. {
  2452. break;
  2453. }
  2454. }
  2455. }
  2456. std::string encr_file = std::string("../nvs_partition_generator/keys/") + std::string(filename);
  2457. SpiFlashEmulator emu("../nvs_partition_generator/partition_encrypted_using_keygen.bin");
  2458. char buffer[64];
  2459. FILE *fp;
  2460. fp = fopen(encr_file.c_str(),"rb");
  2461. fread(buffer,sizeof(buffer),1,fp);
  2462. fclose(fp);
  2463. TEST_ESP_OK(nvs_flash_deinit());
  2464. nvs_sec_cfg_t cfg;
  2465. for(int count = 0; count < NVS_KEY_SIZE; count++) {
  2466. cfg.eky[count] = buffer[count] & 255;
  2467. cfg.tky[count] = buffer[count+32] & 255;
  2468. }
  2469. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "../nvs_partition_generator/testdata/sample_multipage_blob.bin", true, &cfg);
  2470. }
  2471. TEST_CASE("test nvs apis for nvs partition generator utility with encryption enabled using inputkey", "[nvs_part_gen]")
  2472. {
  2473. int childpid = fork();
  2474. int status;
  2475. DIR *dir;
  2476. struct dirent *file;
  2477. char *filename;
  2478. char *files;
  2479. char *file_ext;
  2480. dir = opendir("../nvs_partition_generator/keys");
  2481. while ((file = readdir(dir)) != NULL)
  2482. {
  2483. filename = file->d_name;
  2484. files = strrchr(filename, '.');
  2485. if (files != NULL)
  2486. {
  2487. file_ext = files+1;
  2488. if (strncmp(file_ext,"bin",3) == 0)
  2489. {
  2490. break;
  2491. }
  2492. }
  2493. }
  2494. std::string encr_file = std::string("../nvs_partition_generator/keys/") + std::string(filename);
  2495. if (childpid == 0) {
  2496. exit(execlp("python", "python",
  2497. "../nvs_partition_generator/nvs_partition_gen.py",
  2498. "encrypt",
  2499. "../nvs_partition_generator/sample_multipage_blob.csv",
  2500. "partition_encrypted_using_keyfile.bin",
  2501. "0x4000",
  2502. "--inputkey",
  2503. encr_file.c_str(),
  2504. "--outdir",
  2505. "../nvs_partition_generator",NULL));
  2506. } else {
  2507. CHECK(childpid > 0);
  2508. waitpid(childpid, &status, 0);
  2509. CHECK(WEXITSTATUS(status) != -1);
  2510. }
  2511. SpiFlashEmulator emu("../nvs_partition_generator/partition_encrypted_using_keyfile.bin");
  2512. char buffer[64];
  2513. FILE *fp;
  2514. fp = fopen(encr_file.c_str(),"rb");
  2515. fread(buffer,sizeof(buffer),1,fp);
  2516. fclose(fp);
  2517. TEST_ESP_OK(nvs_flash_deinit());
  2518. nvs_sec_cfg_t cfg;
  2519. for(int count = 0; count < NVS_KEY_SIZE; count++) {
  2520. cfg.eky[count] = buffer[count] & 255;
  2521. cfg.tky[count] = buffer[count+32] & 255;
  2522. }
  2523. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "../nvs_partition_generator/testdata/sample_multipage_blob.bin", true, &cfg);
  2524. childpid = fork();
  2525. if (childpid == 0) {
  2526. exit(execlp("rm", " rm",
  2527. "-rf",
  2528. "../nvs_partition_generator/keys",NULL));
  2529. } else {
  2530. CHECK(childpid > 0);
  2531. waitpid(childpid, &status, 0);
  2532. CHECK(WEXITSTATUS(status) != -1);
  2533. childpid = fork();
  2534. if (childpid == 0) {
  2535. exit(execlp("rm", " rm",
  2536. "-rf",
  2537. "testdata",NULL));
  2538. } else {
  2539. CHECK(childpid > 0);
  2540. waitpid(childpid, &status, 0);
  2541. CHECK(WEXITSTATUS(status) != -1);
  2542. }
  2543. }
  2544. }
  2545. #if false
  2546. TEST_CASE("check and read data from partition generated via manufacturing utility with encryption enabled using sample keyfile", "[mfg_gen]")
  2547. {
  2548. int childpid = fork();
  2549. int status;
  2550. if (childpid == 0) {
  2551. exit(execlp("bash", " bash",
  2552. "-c",
  2553. "rm -rf ../../../tools/mass_mfg/host_test | \
  2554. cp -rf ../../../tools/mass_mfg/testdata mfg_testdata | \
  2555. cp -rf ../nvs_partition_generator/testdata . | \
  2556. mkdir -p ../../../tools/mass_mfg/host_test",NULL));
  2557. } else {
  2558. CHECK(childpid > 0);
  2559. waitpid(childpid, &status, 0);
  2560. CHECK(WEXITSTATUS(status) != -1);
  2561. childpid = fork();
  2562. if (childpid == 0) {
  2563. exit(execlp("python", "python",
  2564. "../../../tools/mass_mfg/mfg_gen.py",
  2565. "--conf",
  2566. "../../../tools/mass_mfg/samples/sample_config.csv",
  2567. "--values",
  2568. "../../../tools/mass_mfg/samples/sample_values_multipage_blob.csv",
  2569. "--prefix",
  2570. "Test",
  2571. "--size",
  2572. "0x4000",
  2573. "--outdir",
  2574. "../../../tools/mass_mfg/host_test",
  2575. "--version",
  2576. "v2",
  2577. "--encrypt",
  2578. "true",
  2579. "--keyfile",
  2580. "mfg_testdata/sample_encryption_keys.bin",NULL));
  2581. } else {
  2582. CHECK(childpid > 0);
  2583. waitpid(childpid, &status, 0);
  2584. CHECK(WEXITSTATUS(status) != -1);
  2585. childpid = fork();
  2586. if (childpid == 0) {
  2587. exit(execlp("python", "python",
  2588. "../nvs_partition_generator/nvs_partition_gen.py",
  2589. "--input",
  2590. "../../../tools/mass_mfg/host_test/csv/Test-1.csv",
  2591. "--output",
  2592. "../nvs_partition_generator/Test-1-partition-encrypted.bin",
  2593. "--size",
  2594. "0x4000",
  2595. "--version",
  2596. "v2",
  2597. "--encrypt",
  2598. "true",
  2599. "--keyfile",
  2600. "testdata/sample_encryption_keys.bin",NULL));
  2601. } else {
  2602. CHECK(childpid > 0);
  2603. waitpid(childpid, &status, 0);
  2604. CHECK(WEXITSTATUS(status) != -1);
  2605. }
  2606. }
  2607. }
  2608. SpiFlashEmulator emu1("../../../tools/mass_mfg/host_test/bin/Test-1.bin");
  2609. TEST_ESP_OK(nvs_flash_deinit());
  2610. nvs_sec_cfg_t cfg;
  2611. for(int count = 0; count < NVS_KEY_SIZE; count++) {
  2612. cfg.eky[count] = 0x11;
  2613. cfg.tky[count] = 0x22;
  2614. }
  2615. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "mfg_testdata/sample_multipage_blob.bin", true, &cfg);
  2616. SpiFlashEmulator emu2("../nvs_partition_generator/Test-1-partition-encrypted.bin");
  2617. TEST_ESP_OK(nvs_flash_deinit());
  2618. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "testdata/sample_multipage_blob.bin", true, &cfg);
  2619. childpid = fork();
  2620. if (childpid == 0) {
  2621. exit(execlp("bash", " bash",
  2622. "-c",
  2623. "rm -rf ../../../tools/mass_mfg/host_test | \
  2624. rm -rf mfg_testdata | \
  2625. rm -rf testdata",NULL));
  2626. } else {
  2627. CHECK(childpid > 0);
  2628. waitpid(childpid, &status, 0);
  2629. CHECK(WEXITSTATUS(status) != -1);
  2630. }
  2631. }
  2632. TEST_CASE("check and read data from partition generated via manufacturing utility with encryption enabled using new generated key", "[mfg_gen]")
  2633. {
  2634. int childpid = fork();
  2635. int status;
  2636. if (childpid == 0) {
  2637. exit(execlp("bash", " bash",
  2638. "-c",
  2639. "rm -rf ../../../tools/mass_mfg/host_test | \
  2640. cp -rf ../../../tools/mass_mfg/testdata mfg_testdata | \
  2641. cp -rf ../nvs_partition_generator/testdata . | \
  2642. mkdir -p ../../../tools/mass_mfg/host_test",NULL));
  2643. } else {
  2644. CHECK(childpid > 0);
  2645. waitpid(childpid, &status, 0);
  2646. CHECK(WEXITSTATUS(status) != -1);
  2647. childpid = fork();
  2648. if (childpid == 0) {
  2649. exit(execlp("python", "python",
  2650. "../../../tools/mass_mfg/mfg_gen.py",
  2651. "--keygen",
  2652. "true",
  2653. "--outdir",
  2654. "../../../tools/mass_mfg/host_test",
  2655. "--keyfile",
  2656. "encr_keys_host_test.bin",NULL));
  2657. } else {
  2658. CHECK(childpid > 0);
  2659. waitpid(childpid, &status, 0);
  2660. CHECK(WEXITSTATUS(status) != -1);
  2661. childpid = fork();
  2662. if (childpid == 0) {
  2663. exit(execlp("python", "python",
  2664. "../../../tools/mass_mfg/mfg_gen.py",
  2665. "--conf",
  2666. "../../../tools/mass_mfg/samples/sample_config.csv",
  2667. "--values",
  2668. "../../../tools/mass_mfg/samples/sample_values_multipage_blob.csv",
  2669. "--prefix",
  2670. "Test",
  2671. "--size",
  2672. "0x4000",
  2673. "--outdir",
  2674. "../../../tools/mass_mfg/host_test",
  2675. "--version",
  2676. "v2",
  2677. "--encrypt",
  2678. "true",
  2679. "--keyfile",
  2680. "../../../tools/mass_mfg/host_test/keys/encr_keys_host_test.bin",NULL));
  2681. } else {
  2682. CHECK(childpid > 0);
  2683. waitpid(childpid, &status, 0);
  2684. CHECK(WEXITSTATUS(status) != -1);
  2685. childpid = fork();
  2686. if (childpid == 0) {
  2687. exit(execlp("python", "python",
  2688. "../nvs_partition_generator/nvs_partition_gen.py",
  2689. "--input",
  2690. "../../../tools/mass_mfg/host_test/csv/Test-1.csv",
  2691. "--output",
  2692. "../nvs_partition_generator/Test-1-partition-encrypted.bin",
  2693. "--size",
  2694. "0x4000",
  2695. "--version",
  2696. "v2",
  2697. "--encrypt",
  2698. "true",
  2699. "--keyfile",
  2700. "../../../tools/mass_mfg/host_test/keys/encr_keys_host_test.bin",NULL));
  2701. } else {
  2702. CHECK(childpid > 0);
  2703. waitpid(childpid, &status, 0);
  2704. CHECK(WEXITSTATUS(status) != -1);
  2705. }
  2706. }
  2707. }
  2708. }
  2709. SpiFlashEmulator emu1("../../../tools/mass_mfg/host_test/bin/Test-1.bin");
  2710. char buffer[64];
  2711. FILE *fp;
  2712. fp = fopen("../../../tools/mass_mfg/host_test/keys/encr_keys_host_test.bin","rb");
  2713. fread(buffer,sizeof(buffer),1,fp);
  2714. fclose(fp);
  2715. TEST_ESP_OK(nvs_flash_deinit());
  2716. nvs_sec_cfg_t cfg;
  2717. for(int count = 0; count < NVS_KEY_SIZE; count++) {
  2718. cfg.eky[count] = buffer[count] & 255;
  2719. cfg.tky[count] = buffer[count+32] & 255;
  2720. }
  2721. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "mfg_testdata/sample_multipage_blob.bin", true, &cfg);
  2722. SpiFlashEmulator emu2("../nvs_partition_generator/Test-1-partition-encrypted.bin");
  2723. TEST_ESP_OK(nvs_flash_deinit());
  2724. check_nvs_part_gen_args(NVS_DEFAULT_PART_NAME, 4, "testdata/sample_multipage_blob.bin", true, &cfg);
  2725. childpid = fork();
  2726. if (childpid == 0) {
  2727. exit(execlp("bash", " bash",
  2728. "-c",
  2729. "rm -rf keys | \
  2730. rm -rf mfg_testdata | \
  2731. rm -rf testdata | \
  2732. rm -rf ../../../tools/mass_mfg/host_test",NULL));
  2733. } else {
  2734. CHECK(childpid > 0);
  2735. waitpid(childpid, &status, 0);
  2736. CHECK(WEXITSTATUS(status) != -1);
  2737. }
  2738. }
  2739. #endif
  2740. #endif
  2741. /* Add new tests above */
  2742. /* This test has to be the final one */
  2743. TEST_CASE("dump all performance data", "[nvs]")
  2744. {
  2745. std::cout << "====================" << std::endl << "Dumping benchmarks" << std::endl;
  2746. std::cout << s_perf.str() << std::endl;
  2747. std::cout << "====================" << std::endl;
  2748. }