test_nvs.cpp 125 KB

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