test_nvs.cpp 129 KB

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