test_nvs.cpp 114 KB

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