test_nvs.cpp 125 KB

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