disk_cache_fuzzer.cc 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. // Copyright (c) 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <cinttypes>
  5. #include <cstdlib>
  6. #include <iostream>
  7. #include <map>
  8. #include <memory>
  9. #include <string>
  10. #include "base/at_exit.h"
  11. #include "base/callback.h"
  12. #include "base/command_line.h"
  13. #include "base/files/file_path.h"
  14. #include "base/files/file_util.h"
  15. #include "base/files/scoped_temp_dir.h"
  16. #include "base/logging.h"
  17. #include "base/memory/ref_counted.h"
  18. #include "base/memory/scoped_refptr.h"
  19. #include "base/numerics/checked_math.h"
  20. #include "base/strings/string_number_conversions.h"
  21. #include "base/test/task_environment.h"
  22. #include "base/test/test_timeouts.h"
  23. #include "base/time/time.h"
  24. #include "net/base/cache_type.h"
  25. #include "net/base/interval.h"
  26. #include "net/base/io_buffer.h"
  27. #include "net/base/net_errors.h"
  28. #include "net/base/test_completion_callback.h"
  29. #include "net/disk_cache/backend_cleanup_tracker.h"
  30. #include "net/disk_cache/blockfile/backend_impl.h"
  31. #include "net/disk_cache/disk_cache.h"
  32. #include "net/disk_cache/disk_cache_fuzzer.pb.h"
  33. #include "net/disk_cache/disk_cache_test_util.h"
  34. #include "net/disk_cache/memory/mem_backend_impl.h"
  35. #include "net/disk_cache/simple/simple_backend_impl.h"
  36. #include "net/disk_cache/simple/simple_file_tracker.h"
  37. #include "net/disk_cache/simple/simple_index.h"
  38. #include "testing/libfuzzer/proto/lpm_interface.h"
  39. // To get a good idea of what a test case is doing, just run the libfuzzer
  40. // target with LPM_DUMP_NATIVE_INPUT=1 prefixed. This will trigger all the
  41. // prints below and will convey exactly what the test case is doing: use this
  42. // instead of trying to print the protobuf as text.
  43. // For code coverage:
  44. // python ./tools/code_coverage/coverage.py disk_cache_lpm_fuzzer -b
  45. // out/coverage -o out/report -c 'out/coverage/disk_cache_lpm_fuzzer
  46. // -runs=0 -workers=24 corpus_disk_cache_simple' -f net/disk_cache
  47. void IOCallback(std::string io_type, int rv);
  48. namespace {
  49. const uint32_t kMaxSizeKB = 128; // 128KB maximum.
  50. const uint32_t kMaxSize = kMaxSizeKB * 1024;
  51. const uint32_t kMaxEntrySize = kMaxSize * 2;
  52. const uint32_t kNumStreams = 3; // All caches seem to have 3 streams. TODO do
  53. // other specialized caches have this?
  54. const uint64_t kFirstSavedTime =
  55. 5; // Totally random number chosen by dice roll. ;)
  56. const uint32_t kMaxNumMillisToWait = 2019;
  57. const int kMaxFdsSimpleCache = 10;
  58. // Known colliding key values taken from SimpleCacheCreateCollision unittest.
  59. const std::string kCollidingKey1 =
  60. "\xfb\x4e\x9c\x1d\x66\x71\xf7\x54\xa3\x11\xa0\x7e\x16\xa5\x68\xf6";
  61. const std::string kCollidingKey2 =
  62. "\xbc\x60\x64\x92\xbc\xa0\x5c\x15\x17\x93\x29\x2d\xe4\x21\xbd\x03";
  63. #define IOTYPES_APPLY(F) \
  64. F(WriteData) \
  65. F(ReadData) \
  66. F(WriteSparseData) \
  67. F(ReadSparseData) \
  68. F(DoomAllEntries) \
  69. F(DoomEntriesSince) \
  70. F(DoomEntriesBetween) \
  71. F(GetAvailableRange) \
  72. F(DoomKey)
  73. enum class IOType {
  74. #define ENUM_ENTRY(IO_TYPE) IO_TYPE,
  75. IOTYPES_APPLY(ENUM_ENTRY)
  76. #undef ENUM_ENTRY
  77. };
  78. struct InitGlobals {
  79. InitGlobals() {
  80. base::CommandLine::Init(0, nullptr);
  81. print_comms_ = ::getenv("LPM_DUMP_NATIVE_INPUT");
  82. // TaskEnvironment requires TestTimeouts initialization to watch for
  83. // problematic long-running tasks.
  84. TestTimeouts::Initialize();
  85. // Mark this thread as an IO_THREAD with MOCK_TIME, and ensure that Now()
  86. // is driven from the same mock clock.
  87. task_environment_ = std::make_unique<base::test::TaskEnvironment>(
  88. base::test::TaskEnvironment::MainThreadType::IO,
  89. base::test::TaskEnvironment::TimeSource::MOCK_TIME);
  90. // Disable noisy logging as per "libFuzzer in Chrome" documentation:
  91. // testing/libfuzzer/getting_started.md#Disable-noisy-error-message-logging.
  92. logging::SetMinLogLevel(logging::LOG_FATAL);
  93. // Re-using this buffer for write operations may technically be against
  94. // IOBuffer rules but it shouldn't cause any actual problems.
  95. buffer_ =
  96. base::MakeRefCounted<net::IOBuffer>(static_cast<size_t>(kMaxEntrySize));
  97. CacheTestFillBuffer(buffer_->data(), kMaxEntrySize, false);
  98. #define CREATE_IO_CALLBACK(IO_TYPE) \
  99. io_callbacks_.push_back(base::BindRepeating(&IOCallback, #IO_TYPE));
  100. IOTYPES_APPLY(CREATE_IO_CALLBACK)
  101. #undef CREATE_IO_CALLBACK
  102. }
  103. // This allows us to mock time for all threads.
  104. std::unique_ptr<base::test::TaskEnvironment> task_environment_;
  105. // Used as a pre-filled buffer for all writes.
  106. scoped_refptr<net::IOBuffer> buffer_;
  107. // Should we print debugging info?
  108. bool print_comms_;
  109. // List of IO callbacks. They do nothing (except maybe print) but are used by
  110. // all async entry operations.
  111. std::vector<base::RepeatingCallback<void(int)>> io_callbacks_;
  112. };
  113. InitGlobals* init_globals = new InitGlobals();
  114. } // namespace
  115. class DiskCacheLPMFuzzer {
  116. public:
  117. DiskCacheLPMFuzzer() {
  118. CHECK(temp_dir_.CreateUniqueTempDir());
  119. cache_path_ = temp_dir_.GetPath();
  120. }
  121. ~DiskCacheLPMFuzzer();
  122. void RunCommands(const disk_cache_fuzzer::FuzzCommands& commands);
  123. private:
  124. struct EntryInfo {
  125. EntryInfo() = default;
  126. EntryInfo(const EntryInfo&) = delete;
  127. EntryInfo& operator=(const EntryInfo&) = delete;
  128. disk_cache::Entry* entry_ptr = nullptr;
  129. std::unique_ptr<TestEntryResultCompletionCallback> tcb;
  130. };
  131. void RunTaskForTest(base::OnceClosure closure);
  132. // Waits for an entry to be ready. Only should be called if there is a pending
  133. // callback for this entry; i.e. ei->tcb != nullptr.
  134. // Also takes the rv that the cache entry creation functions return, and does
  135. // not wait if rv.net_error != net::ERR_IO_PENDING (and would never have
  136. // called the callback).
  137. disk_cache::EntryResult WaitOnEntry(
  138. EntryInfo* ei,
  139. disk_cache::EntryResult result =
  140. disk_cache::EntryResult::MakeError(net::ERR_IO_PENDING));
  141. // Used as a callback for entry-opening backend calls. Will record the entry
  142. // in the map as usable and will release any entry-specific calls waiting for
  143. // the entry to be ready.
  144. void OpenCacheEntryCallback(uint64_t entry_id,
  145. bool async,
  146. bool set_is_sparse,
  147. disk_cache::EntryResult result);
  148. // Waits for the entry to finish opening, in the async case. Then, if the
  149. // entry is successfully open (callback returns net::OK, or was already
  150. // successfully opened), check if the entry_ptr == nullptr. If so, the
  151. // entry has been closed.
  152. bool IsValidEntry(EntryInfo* ei);
  153. // Closes any non-nullptr entries in open_cache_entries_.
  154. void CloseAllRemainingEntries();
  155. void HandleSetMaxSize(const disk_cache_fuzzer::SetMaxSize&);
  156. void CreateBackend(
  157. disk_cache_fuzzer::FuzzCommands::CacheBackend cache_backend,
  158. uint32_t mask,
  159. net::CacheType type,
  160. bool simple_cache_wait_for_index);
  161. // Places to keep our cache files.
  162. base::FilePath cache_path_;
  163. base::ScopedTempDir temp_dir_;
  164. // Pointers to our backend. Only one of block_impl_, simple_cache_impl_, and
  165. // mem_cache_ are active at one time.
  166. std::unique_ptr<disk_cache::Backend> cache_;
  167. disk_cache::BackendImpl* block_impl_ = nullptr;
  168. std::unique_ptr<disk_cache::SimpleFileTracker> simple_file_tracker_;
  169. disk_cache::SimpleBackendImpl* simple_cache_impl_ = nullptr;
  170. disk_cache::MemBackendImpl* mem_cache_ = nullptr;
  171. // Maximum size of the cache, that we have currently set.
  172. uint32_t max_size_ = kMaxSize;
  173. // This "consistent hash table" keeys track of the keys we've added to the
  174. // backend so far. This should always be indexed by a "key_id" from a
  175. // protobuf.
  176. std::map<uint64_t, std::string> created_cache_entries_;
  177. // This "consistent hash table" keeps track of all opened entries we have from
  178. // the backend, and also contains some nullptr's where entries were already
  179. // closed. This should always be indexed by an "entry_id" from a protobuf.
  180. // When destructed, we close all entries that are still open in order to avoid
  181. // memory leaks.
  182. std::map<uint64_t, EntryInfo> open_cache_entries_;
  183. // This "consistent hash table" keeps track of all times we have saved, so
  184. // that we can call backend methods like DoomEntriesSince or
  185. // DoomEntriesBetween with sane timestamps. This should always be indexed by a
  186. // "time_id" from a protobuf.
  187. std::map<uint64_t, base::Time> saved_times_;
  188. // This "consistent hash table" keeps tack of all the iterators we have open
  189. // from the backend. This should always be indexed by a "it_id" from a
  190. // protobuf.
  191. std::map<uint64_t, std::unique_ptr<disk_cache::Backend::Iterator>>
  192. open_iterators_;
  193. // This maps keeps track of the sparsity of each entry, using their pointers.
  194. // TODO(mpdenton) remove if CreateEntry("Key0"); WriteData("Key0", index = 2,
  195. // ...); WriteSparseData("Key0", ...); is supposed to be valid.
  196. // Then we can just use CouldBeSparse before the WriteData.
  197. std::map<disk_cache::Entry*, bool> sparse_entry_tracker_;
  198. };
  199. #define MAYBE_PRINT \
  200. if (init_globals->print_comms_) \
  201. std::cout
  202. inline base::RepeatingCallback<void(int)> GetIOCallback(IOType iot) {
  203. return init_globals->io_callbacks_[static_cast<int>(iot)];
  204. }
  205. std::string ToKey(uint64_t key_num) {
  206. // Use one of the two colliding key values in 1% of executions.
  207. if (key_num % 100 == 99)
  208. return kCollidingKey1;
  209. if (key_num % 100 == 98)
  210. return kCollidingKey2;
  211. // Otherwise, use a value based on the key id and fuzzy padding.
  212. std::string padding(key_num & 0xFFFF, 'A');
  213. return "Key" + padding + base::NumberToString(key_num);
  214. }
  215. net::RequestPriority GetRequestPriority(
  216. disk_cache_fuzzer::RequestPriority lpm_pri) {
  217. CHECK(net::MINIMUM_PRIORITY <= static_cast<int>(lpm_pri) &&
  218. static_cast<int>(lpm_pri) <= net::MAXIMUM_PRIORITY);
  219. return static_cast<net::RequestPriority>(lpm_pri);
  220. }
  221. net::CacheType GetCacheTypeAndPrint(
  222. disk_cache_fuzzer::FuzzCommands::CacheType type,
  223. disk_cache_fuzzer::FuzzCommands::CacheBackend backend) {
  224. switch (type) {
  225. case disk_cache_fuzzer::FuzzCommands::APP_CACHE:
  226. MAYBE_PRINT << "Cache type = APP_CACHE." << std::endl;
  227. return net::CacheType::APP_CACHE;
  228. break;
  229. case disk_cache_fuzzer::FuzzCommands::REMOVED_MEDIA_CACHE:
  230. // Media cache no longer in use; handle as HTTP_CACHE
  231. MAYBE_PRINT << "Cache type = REMOVED_MEDIA_CACHE." << std::endl;
  232. return net::CacheType::DISK_CACHE;
  233. break;
  234. case disk_cache_fuzzer::FuzzCommands::SHADER_CACHE:
  235. MAYBE_PRINT << "Cache type = SHADER_CACHE." << std::endl;
  236. return net::CacheType::SHADER_CACHE;
  237. break;
  238. case disk_cache_fuzzer::FuzzCommands::PNACL_CACHE:
  239. // Simple cache won't handle PNACL_CACHE.
  240. if (backend == disk_cache_fuzzer::FuzzCommands::SIMPLE) {
  241. MAYBE_PRINT << "Cache type = DISK_CACHE." << std::endl;
  242. return net::CacheType::DISK_CACHE;
  243. }
  244. MAYBE_PRINT << "Cache type = PNACL_CACHE." << std::endl;
  245. return net::CacheType::PNACL_CACHE;
  246. break;
  247. case disk_cache_fuzzer::FuzzCommands::GENERATED_BYTE_CODE_CACHE:
  248. MAYBE_PRINT << "Cache type = GENERATED_BYTE_CODE_CACHE." << std::endl;
  249. return net::CacheType::GENERATED_BYTE_CODE_CACHE;
  250. break;
  251. case disk_cache_fuzzer::FuzzCommands::GENERATED_NATIVE_CODE_CACHE:
  252. MAYBE_PRINT << "Cache type = GENERATED_NATIVE_CODE_CACHE." << std::endl;
  253. return net::CacheType::GENERATED_NATIVE_CODE_CACHE;
  254. break;
  255. case disk_cache_fuzzer::FuzzCommands::DISK_CACHE:
  256. MAYBE_PRINT << "Cache type = DISK_CACHE." << std::endl;
  257. return net::CacheType::DISK_CACHE;
  258. break;
  259. }
  260. }
  261. void IOCallback(std::string io_type, int rv) {
  262. MAYBE_PRINT << " [Async IO (" << io_type << ") = " << rv << "]" << std::endl;
  263. }
  264. /*
  265. * Consistent hashing inspired map for fuzzer state.
  266. * If we stored open cache entries in a hash table mapping cache_entry_id ->
  267. * disk_cache::Entry*, then it would be highly unlikely that any subsequent
  268. * "CloseEntry" or "WriteData" etc. command would come up with an ID that would
  269. * correspond to a valid entry in the hash table. The optimal solution is for
  270. * libfuzzer to generate CloseEntry commands with an ID that matches the ID of a
  271. * previous OpenEntry command. But libfuzzer is stateless and should stay that
  272. * way.
  273. *
  274. * On the other hand, if we stored entries in a vector, and on a CloseEntry
  275. * command we took the entry at CloseEntry.id % (size of entries vector), we
  276. * would always generate correct CloseEntries. This is good, but all
  277. * dumb/general minimization techniques stop working, because deleting a single
  278. * OpenEntry command changes the indexes of every entry in the vector from then
  279. * on.
  280. *
  281. * So, we use something that's more stable for minimization: consistent hashing.
  282. * Basically, when we see a CloseEntry.id, we take the entry in the table that
  283. * has the next highest id (wrapping when there is no higher entry).
  284. *
  285. * This makes us resilient to deleting irrelevant OpenEntry commands. But, if we
  286. * delete from the table on CloseEntry commands, we still screw up all the
  287. * indexes during minimization. We'll get around this by not deleting entries
  288. * after CloseEntry commands, but that will result in a slightly less efficient
  289. * fuzzer, as if there are many closed entries in the table, many of the *Entry
  290. * commands will be useless. It seems like a decent balance between generating
  291. * useful fuzz commands and effective minimization.
  292. */
  293. template <typename T>
  294. typename std::map<uint64_t, T>::iterator GetNextValue(
  295. typename std::map<uint64_t, T>* entries,
  296. uint64_t val) {
  297. auto iter = entries->lower_bound(val);
  298. if (iter != entries->end())
  299. return iter;
  300. // Wrap to 0
  301. iter = entries->lower_bound(0);
  302. if (iter != entries->end())
  303. return iter;
  304. return entries->end();
  305. }
  306. void DiskCacheLPMFuzzer::RunTaskForTest(base::OnceClosure closure) {
  307. if (!block_impl_) {
  308. std::move(closure).Run();
  309. return;
  310. }
  311. net::TestCompletionCallback cb;
  312. int rv = block_impl_->RunTaskForTest(std::move(closure), cb.callback());
  313. CHECK_EQ(cb.GetResult(rv), net::OK);
  314. }
  315. // Resets the cb in the map so that WriteData and other calls that work on an
  316. // entry don't wait for its result.
  317. void DiskCacheLPMFuzzer::OpenCacheEntryCallback(
  318. uint64_t entry_id,
  319. bool async,
  320. bool set_is_sparse,
  321. disk_cache::EntryResult result) {
  322. // TODO(mpdenton) if this fails should we delete the entry entirely?
  323. // Would need to mark it for deletion and delete it later, as
  324. // IsValidEntry might be waiting for it.
  325. EntryInfo* ei = &open_cache_entries_[entry_id];
  326. if (async) {
  327. int rv = result.net_error();
  328. ei->entry_ptr = result.ReleaseEntry();
  329. // We are responsible for setting things up.
  330. if (set_is_sparse && ei->entry_ptr) {
  331. sparse_entry_tracker_[ei->entry_ptr] = true;
  332. }
  333. if (ei->entry_ptr) {
  334. MAYBE_PRINT << " [Async opening of cache entry for \""
  335. << ei->entry_ptr->GetKey() << "\" callback (rv = " << rv
  336. << ")]" << std::endl;
  337. }
  338. // Unblock any subsequent ops waiting for this --- they don't care about
  339. // the actual return value, but use something distinctive for debugging.
  340. ei->tcb->callback().Run(
  341. disk_cache::EntryResult::MakeError(net::ERR_FILE_VIRUS_INFECTED));
  342. } else {
  343. // The operation code will pull the result out of the completion callback,
  344. // so hand it to it.
  345. ei->tcb->callback().Run(std::move(result));
  346. }
  347. }
  348. disk_cache::EntryResult DiskCacheLPMFuzzer::WaitOnEntry(
  349. EntryInfo* ei,
  350. disk_cache::EntryResult result) {
  351. CHECK(ei->tcb);
  352. result = ei->tcb->GetResult(std::move(result));
  353. // Reset the callback so nobody accidentally waits on a callback that never
  354. // comes.
  355. ei->tcb.reset();
  356. return result;
  357. }
  358. bool DiskCacheLPMFuzzer::IsValidEntry(EntryInfo* ei) {
  359. if (ei->tcb) {
  360. // If we have a callback, we are the first to access this async-created
  361. // entry. Wait for it, and then delete it so nobody waits on it again.
  362. WaitOnEntry(ei);
  363. }
  364. // entry_ptr will be nullptr if the entry has been closed.
  365. return ei->entry_ptr != nullptr;
  366. }
  367. /*
  368. * Async implementation:
  369. 1. RunUntilIdle at the top of the loop to handle any callbacks we've been
  370. posted from the backend thread.
  371. 2. Only the entry creation functions have important callbacks. The good thing
  372. is backend destruction will cancel these operations. The entry creation
  373. functions simply need to keep the entry_ptr* alive until the callback is
  374. posted, and then need to make sure the entry_ptr is added to the map in order
  375. to Close it in the destructor.
  376. As for iterators, it's unclear whether closing an iterator will cancel
  377. callbacks.
  378. Problem: WriteData (and similar) calls will fail on the entry_id until the
  379. callback happens. So, I should probably delay these calls or otherwise will
  380. have very unreliable test cases. These are the options:
  381. 1. Queue up WriteData (etc.) calls in some map, such that when the OpenEntry
  382. callback runs, the WriteData calls will all run.
  383. 2. Just sit there and wait for the entry to be ready.
  384. #2 is probably best as it doesn't prevent any interesting cases and is much
  385. simpler.
  386. */
  387. void DiskCacheLPMFuzzer::RunCommands(
  388. const disk_cache_fuzzer::FuzzCommands& commands) {
  389. // Skip too long command sequences, they are counterproductive for fuzzing.
  390. // The number was chosen empirically using the existing fuzzing corpus.
  391. if (commands.fuzz_commands_size() > 129)
  392. return;
  393. uint32_t mask =
  394. commands.has_set_mask() ? (commands.set_mask() ? 0x1 : 0xf) : 0;
  395. net::CacheType type =
  396. GetCacheTypeAndPrint(commands.cache_type(), commands.cache_backend());
  397. CreateBackend(commands.cache_backend(), mask, type,
  398. commands.simple_cache_wait_for_index());
  399. MAYBE_PRINT << "CreateBackend()" << std::endl;
  400. if (commands.has_set_max_size()) {
  401. HandleSetMaxSize(commands.set_max_size());
  402. }
  403. {
  404. base::Time curr_time = base::Time::Now();
  405. saved_times_[kFirstSavedTime] = curr_time;
  406. // MAYBE_PRINT << "Saved initial time " << curr_time << std::endl;
  407. }
  408. for (const disk_cache_fuzzer::FuzzCommand& command :
  409. commands.fuzz_commands()) {
  410. // Handle any callbacks that other threads may have posted to us in the
  411. // meantime, so any successful async OpenEntry's (etc.) add their
  412. // entry_ptr's to the map.
  413. init_globals->task_environment_->RunUntilIdle();
  414. switch (command.fuzz_command_oneof_case()) {
  415. case disk_cache_fuzzer::FuzzCommand::kSetMaxSize: {
  416. HandleSetMaxSize(command.set_max_size());
  417. break;
  418. }
  419. case disk_cache_fuzzer::FuzzCommand::kCreateEntry: {
  420. if (!cache_)
  421. continue;
  422. const disk_cache_fuzzer::CreateEntry& ce = command.create_entry();
  423. uint64_t key_id = ce.key_id();
  424. uint64_t entry_id = ce.entry_id();
  425. net::RequestPriority pri = GetRequestPriority(ce.pri());
  426. bool async = ce.async();
  427. bool is_sparse = ce.is_sparse();
  428. if (open_cache_entries_.find(entry_id) != open_cache_entries_.end())
  429. continue; // Don't overwrite a currently open cache entry.
  430. std::string key_str = ToKey(key_id);
  431. created_cache_entries_[key_id] = key_str;
  432. EntryInfo* entry_info = &open_cache_entries_[entry_id];
  433. entry_info->tcb = std::make_unique<TestEntryResultCompletionCallback>();
  434. disk_cache::EntryResultCallback cb =
  435. base::BindOnce(&DiskCacheLPMFuzzer::OpenCacheEntryCallback,
  436. base::Unretained(this), entry_id, async, is_sparse);
  437. MAYBE_PRINT << "CreateEntry(\"" << key_str
  438. << "\", set_is_sparse = " << is_sparse
  439. << ") = " << std::flush;
  440. disk_cache::EntryResult result =
  441. cache_->CreateEntry(key_str, pri, std::move(cb));
  442. if (!async || result.net_error() != net::ERR_IO_PENDING) {
  443. result = WaitOnEntry(entry_info, std::move(result));
  444. int rv = result.net_error();
  445. // Ensure we mark sparsity, save entry if the callback never ran.
  446. if (rv == net::OK) {
  447. entry_info->entry_ptr = result.ReleaseEntry();
  448. sparse_entry_tracker_[entry_info->entry_ptr] = is_sparse;
  449. }
  450. MAYBE_PRINT << rv << std::endl;
  451. } else {
  452. MAYBE_PRINT << "net::ERR_IO_PENDING (async)" << std::endl;
  453. }
  454. break;
  455. }
  456. case disk_cache_fuzzer::FuzzCommand::kOpenEntry: {
  457. if (!cache_)
  458. continue;
  459. const disk_cache_fuzzer::OpenEntry& oe = command.open_entry();
  460. uint64_t key_id = oe.key_id();
  461. uint64_t entry_id = oe.entry_id();
  462. net::RequestPriority pri = GetRequestPriority(oe.pri());
  463. bool async = oe.async();
  464. if (created_cache_entries_.empty())
  465. continue;
  466. if (open_cache_entries_.find(entry_id) != open_cache_entries_.end())
  467. continue; // Don't overwrite a currently open cache entry.
  468. EntryInfo* entry_info = &open_cache_entries_[entry_id];
  469. entry_info->tcb = std::make_unique<TestEntryResultCompletionCallback>();
  470. disk_cache::EntryResultCallback cb =
  471. base::BindOnce(&DiskCacheLPMFuzzer::OpenCacheEntryCallback,
  472. base::Unretained(this), entry_id, async, false);
  473. auto key_it = GetNextValue(&created_cache_entries_, key_id);
  474. MAYBE_PRINT << "OpenEntry(\"" << key_it->second
  475. << "\") = " << std::flush;
  476. disk_cache::EntryResult result =
  477. cache_->OpenEntry(key_it->second, pri, std::move(cb));
  478. if (!async || result.net_error() != net::ERR_IO_PENDING) {
  479. result = WaitOnEntry(entry_info, std::move(result));
  480. int rv = result.net_error();
  481. if (rv == net::OK)
  482. entry_info->entry_ptr = result.ReleaseEntry();
  483. MAYBE_PRINT << rv << std::endl;
  484. } else {
  485. MAYBE_PRINT << "net::ERR_IO_PENDING (async)" << std::endl;
  486. }
  487. break;
  488. }
  489. case disk_cache_fuzzer::FuzzCommand::kOpenOrCreateEntry: {
  490. if (!cache_)
  491. continue;
  492. const disk_cache_fuzzer::OpenOrCreateEntry& ooce =
  493. command.open_or_create_entry();
  494. uint64_t key_id = ooce.key_id();
  495. uint64_t entry_id = ooce.entry_id();
  496. net::RequestPriority pri = GetRequestPriority(ooce.pri());
  497. bool async = ooce.async();
  498. bool is_sparse = ooce.is_sparse();
  499. if (open_cache_entries_.find(entry_id) != open_cache_entries_.end())
  500. continue; // Don't overwrite a currently open cache entry.
  501. std::string key_str;
  502. // If our proto tells us to create a new entry, create a new entry, just
  503. // with OpenOrCreateEntry.
  504. if (ooce.create_new()) {
  505. // Use a possibly new key.
  506. key_str = ToKey(key_id);
  507. created_cache_entries_[key_id] = key_str;
  508. } else {
  509. if (created_cache_entries_.empty())
  510. continue;
  511. auto key_it = GetNextValue(&created_cache_entries_, key_id);
  512. key_str = key_it->second;
  513. }
  514. // Setup for callbacks.
  515. EntryInfo* entry_info = &open_cache_entries_[entry_id];
  516. entry_info->tcb = std::make_unique<TestEntryResultCompletionCallback>();
  517. disk_cache::EntryResultCallback cb =
  518. base::BindOnce(&DiskCacheLPMFuzzer::OpenCacheEntryCallback,
  519. base::Unretained(this), entry_id, async, is_sparse);
  520. // Will only be set as sparse if it is created and not opened.
  521. MAYBE_PRINT << "OpenOrCreateEntry(\"" << key_str
  522. << "\", set_is_sparse = " << is_sparse
  523. << ") = " << std::flush;
  524. disk_cache::EntryResult result =
  525. cache_->OpenOrCreateEntry(key_str, pri, std::move(cb));
  526. if (!async || result.net_error() != net::ERR_IO_PENDING) {
  527. result = WaitOnEntry(entry_info, std::move(result));
  528. int rv = result.net_error();
  529. bool opened = result.opened();
  530. entry_info->entry_ptr = result.ReleaseEntry();
  531. // Ensure we mark sparsity, even if the callback never ran.
  532. if (rv == net::OK && !opened)
  533. sparse_entry_tracker_[entry_info->entry_ptr] = is_sparse;
  534. MAYBE_PRINT << rv << ", opened = " << opened << std::endl;
  535. } else {
  536. MAYBE_PRINT << "net::ERR_IO_PENDING (async)" << std::endl;
  537. }
  538. break;
  539. }
  540. case disk_cache_fuzzer::FuzzCommand::kCloseEntry: {
  541. if (open_cache_entries_.empty())
  542. continue;
  543. auto entry_it = GetNextValue(&open_cache_entries_,
  544. command.close_entry().entry_id());
  545. if (!IsValidEntry(&entry_it->second))
  546. continue;
  547. MAYBE_PRINT << "CloseEntry(\"" << entry_it->second.entry_ptr->GetKey()
  548. << "\")" << std::endl;
  549. entry_it->second.entry_ptr->Close();
  550. // Set the entry_ptr to nullptr to ensure no one uses it anymore.
  551. entry_it->second.entry_ptr = nullptr;
  552. break;
  553. }
  554. case disk_cache_fuzzer::FuzzCommand::kDoomEntry: {
  555. if (open_cache_entries_.empty())
  556. continue;
  557. auto entry_it =
  558. GetNextValue(&open_cache_entries_, command.doom_entry().entry_id());
  559. if (!IsValidEntry(&entry_it->second))
  560. continue;
  561. MAYBE_PRINT << "DoomEntry(\"" << entry_it->second.entry_ptr->GetKey()
  562. << "\")" << std::endl;
  563. entry_it->second.entry_ptr->Doom();
  564. break;
  565. }
  566. case disk_cache_fuzzer::FuzzCommand::kWriteData: {
  567. if (open_cache_entries_.empty())
  568. continue;
  569. const disk_cache_fuzzer::WriteData& wd = command.write_data();
  570. auto entry_it = GetNextValue(&open_cache_entries_, wd.entry_id());
  571. if (!IsValidEntry(&entry_it->second))
  572. continue;
  573. int index = 0; // if it's sparse, these non-sparse aware streams must
  574. // read from stream 0 according to the spec.
  575. // Implementations might have weaker constraints.
  576. if (!sparse_entry_tracker_[entry_it->second.entry_ptr])
  577. index = wd.index() % kNumStreams;
  578. uint32_t offset = wd.offset() % kMaxEntrySize;
  579. size_t size = wd.size() % kMaxEntrySize;
  580. bool async = wd.async();
  581. net::TestCompletionCallback tcb;
  582. net::CompletionOnceCallback cb =
  583. !async ? tcb.callback() : GetIOCallback(IOType::WriteData);
  584. MAYBE_PRINT << "WriteData(\"" << entry_it->second.entry_ptr->GetKey()
  585. << "\", index = " << index << ", offset = " << offset
  586. << ", size = " << size << ", truncate = " << wd.truncate()
  587. << ")" << std::flush;
  588. int rv = entry_it->second.entry_ptr->WriteData(
  589. index, offset, init_globals->buffer_.get(), size, std::move(cb),
  590. wd.truncate());
  591. if (!async)
  592. rv = tcb.GetResult(rv);
  593. MAYBE_PRINT << " = " << rv << std::endl;
  594. break;
  595. }
  596. case disk_cache_fuzzer::FuzzCommand::kReadData: {
  597. if (open_cache_entries_.empty())
  598. continue;
  599. const disk_cache_fuzzer::ReadData& wd = command.read_data();
  600. auto entry_it = GetNextValue(&open_cache_entries_, wd.entry_id());
  601. if (!IsValidEntry(&entry_it->second))
  602. continue;
  603. int index = 0; // if it's sparse, these non-sparse aware streams must
  604. // read from stream 0 according to the spec.
  605. // Implementations might weaker constraints?
  606. if (!sparse_entry_tracker_[entry_it->second.entry_ptr])
  607. index = wd.index() % kNumStreams;
  608. uint32_t offset = wd.offset() % kMaxEntrySize;
  609. size_t size = wd.size() % kMaxEntrySize;
  610. bool async = wd.async();
  611. scoped_refptr<net::IOBuffer> buffer =
  612. base::MakeRefCounted<net::IOBuffer>(size);
  613. net::TestCompletionCallback tcb;
  614. net::CompletionOnceCallback cb =
  615. !async ? tcb.callback() : GetIOCallback(IOType::ReadData);
  616. MAYBE_PRINT << "ReadData(\"" << entry_it->second.entry_ptr->GetKey()
  617. << "\", index = " << index << ", offset = " << offset
  618. << ", size = " << size << ")" << std::flush;
  619. int rv = entry_it->second.entry_ptr->ReadData(
  620. index, offset, buffer.get(), size, std::move(cb));
  621. if (!async)
  622. rv = tcb.GetResult(rv);
  623. MAYBE_PRINT << " = " << rv << std::endl;
  624. break;
  625. }
  626. case disk_cache_fuzzer::FuzzCommand::kWriteSparseData: {
  627. if (open_cache_entries_.empty())
  628. continue;
  629. const disk_cache_fuzzer::WriteSparseData& wsd =
  630. command.write_sparse_data();
  631. auto entry_it = GetNextValue(&open_cache_entries_, wsd.entry_id());
  632. if (!IsValidEntry(&entry_it->second) ||
  633. !sparse_entry_tracker_[entry_it->second.entry_ptr])
  634. continue;
  635. uint64_t offset = wsd.offset();
  636. if (wsd.cap_offset())
  637. offset %= kMaxEntrySize;
  638. size_t size = wsd.size() % kMaxEntrySize;
  639. bool async = wsd.async();
  640. net::TestCompletionCallback tcb;
  641. net::CompletionOnceCallback cb =
  642. !async ? tcb.callback() : GetIOCallback(IOType::WriteSparseData);
  643. MAYBE_PRINT << "WriteSparseData(\""
  644. << entry_it->second.entry_ptr->GetKey()
  645. << "\", offset = " << offset << ", size = " << size << ")"
  646. << std::flush;
  647. int rv = entry_it->second.entry_ptr->WriteSparseData(
  648. offset, init_globals->buffer_.get(), size, std::move(cb));
  649. if (!async)
  650. rv = tcb.GetResult(rv);
  651. MAYBE_PRINT << " = " << rv << std::endl;
  652. break;
  653. }
  654. case disk_cache_fuzzer::FuzzCommand::kReadSparseData: {
  655. if (open_cache_entries_.empty())
  656. continue;
  657. const disk_cache_fuzzer::ReadSparseData& rsd =
  658. command.read_sparse_data();
  659. auto entry_it = GetNextValue(&open_cache_entries_, rsd.entry_id());
  660. if (!IsValidEntry(&entry_it->second) ||
  661. !sparse_entry_tracker_[entry_it->second.entry_ptr])
  662. continue;
  663. uint64_t offset = rsd.offset();
  664. if (rsd.cap_offset())
  665. offset %= kMaxEntrySize;
  666. size_t size = rsd.size() % kMaxEntrySize;
  667. bool async = rsd.async();
  668. scoped_refptr<net::IOBuffer> buffer =
  669. base::MakeRefCounted<net::IOBuffer>(size);
  670. net::TestCompletionCallback tcb;
  671. net::CompletionOnceCallback cb =
  672. !async ? tcb.callback() : GetIOCallback(IOType::ReadSparseData);
  673. MAYBE_PRINT << "ReadSparseData(\""
  674. << entry_it->second.entry_ptr->GetKey()
  675. << "\", offset = " << offset << ", size = " << size << ")"
  676. << std::flush;
  677. int rv = entry_it->second.entry_ptr->ReadSparseData(
  678. offset, buffer.get(), size, std::move(cb));
  679. if (!async)
  680. rv = tcb.GetResult(rv);
  681. MAYBE_PRINT << " = " << rv << std::endl;
  682. break;
  683. }
  684. case disk_cache_fuzzer::FuzzCommand::kDoomAllEntries: {
  685. if (!cache_)
  686. continue;
  687. bool async = command.doom_all_entries().async();
  688. net::TestCompletionCallback tcb;
  689. net::CompletionOnceCallback cb =
  690. !async ? tcb.callback() : GetIOCallback(IOType::DoomAllEntries);
  691. MAYBE_PRINT << "DoomAllEntries()" << std::flush;
  692. int rv = cache_->DoomAllEntries(std::move(cb));
  693. if (!async)
  694. rv = tcb.GetResult(rv);
  695. MAYBE_PRINT << " = " << rv << std::endl;
  696. break;
  697. }
  698. case disk_cache_fuzzer::FuzzCommand::kFlushQueueForTest: {
  699. // Blockfile-cache specific method.
  700. if (!block_impl_)
  701. return;
  702. net::TestCompletionCallback cb;
  703. MAYBE_PRINT << "FlushQueueForTest()" << std::endl;
  704. int rv = block_impl_->FlushQueueForTest(cb.callback());
  705. CHECK_EQ(cb.GetResult(rv), net::OK);
  706. break;
  707. }
  708. case disk_cache_fuzzer::FuzzCommand::kCreateIterator: {
  709. if (!cache_)
  710. continue;
  711. uint64_t it_id = command.create_iterator().it_id();
  712. MAYBE_PRINT << "CreateIterator(), id = " << it_id << std::endl;
  713. open_iterators_[it_id] = cache_->CreateIterator();
  714. break;
  715. }
  716. case disk_cache_fuzzer::FuzzCommand::kIteratorOpenNextEntry: {
  717. const disk_cache_fuzzer::IteratorOpenNextEntry& ione =
  718. command.iterator_open_next_entry();
  719. uint64_t it_id = ione.it_id();
  720. uint64_t entry_id = ione.entry_id();
  721. bool async = ione.async();
  722. if (open_iterators_.empty())
  723. continue;
  724. if (open_cache_entries_.find(entry_id) != open_cache_entries_.end())
  725. continue; // Don't overwrite a currently
  726. // open cache entry.
  727. auto iterator_it = GetNextValue(&open_iterators_, it_id);
  728. EntryInfo* entry_info = &open_cache_entries_[entry_id];
  729. entry_info->tcb = std::make_unique<TestEntryResultCompletionCallback>();
  730. disk_cache::EntryResultCallback cb =
  731. base::BindOnce(&DiskCacheLPMFuzzer::OpenCacheEntryCallback,
  732. base::Unretained(this), entry_id, async, false);
  733. MAYBE_PRINT << "Iterator(" << ione.it_id()
  734. << ").OpenNextEntry() = " << std::flush;
  735. disk_cache::EntryResult result =
  736. iterator_it->second->OpenNextEntry(std::move(cb));
  737. if (!async || result.net_error() != net::ERR_IO_PENDING) {
  738. result = WaitOnEntry(entry_info, std::move(result));
  739. int rv = result.net_error();
  740. entry_info->entry_ptr = result.ReleaseEntry();
  741. // Print return value, and key if applicable.
  742. if (!entry_info->entry_ptr) {
  743. MAYBE_PRINT << rv << std::endl;
  744. } else {
  745. MAYBE_PRINT << rv << ", key = " << entry_info->entry_ptr->GetKey()
  746. << std::endl;
  747. }
  748. } else {
  749. MAYBE_PRINT << "net::ERR_IO_PENDING (async)" << std::endl;
  750. }
  751. break;
  752. }
  753. case disk_cache_fuzzer::FuzzCommand::kFastForwardBy: {
  754. base::TimeDelta to_wait =
  755. base::Milliseconds(command.fast_forward_by().capped_num_millis() %
  756. kMaxNumMillisToWait);
  757. MAYBE_PRINT << "FastForwardBy(" << to_wait << ")" << std::endl;
  758. init_globals->task_environment_->FastForwardBy(to_wait);
  759. base::Time curr_time = base::Time::Now();
  760. saved_times_[command.fast_forward_by().time_id()] = curr_time;
  761. // MAYBE_PRINT << "Saved time " << curr_time << std::endl;
  762. break;
  763. }
  764. case disk_cache_fuzzer::FuzzCommand::kDoomEntriesSince: {
  765. if (!cache_)
  766. continue;
  767. // App cache does not keep track of LRU timestamps so this method cannot
  768. // be used.
  769. if (type == net::APP_CACHE)
  770. continue;
  771. if (saved_times_.empty())
  772. continue;
  773. const disk_cache_fuzzer::DoomEntriesSince& des =
  774. command.doom_entries_since();
  775. auto time_it = GetNextValue(&saved_times_, des.time_id());
  776. bool async = des.async();
  777. net::TestCompletionCallback tcb;
  778. net::CompletionOnceCallback cb =
  779. !async ? tcb.callback() : GetIOCallback(IOType::DoomEntriesSince);
  780. MAYBE_PRINT << "DoomEntriesSince(" << time_it->second << ")"
  781. << std::flush;
  782. int rv = cache_->DoomEntriesSince(time_it->second, std::move(cb));
  783. if (!async)
  784. rv = tcb.GetResult(rv);
  785. MAYBE_PRINT << " = " << rv << std::endl;
  786. break;
  787. }
  788. case disk_cache_fuzzer::FuzzCommand::kDoomEntriesBetween: {
  789. if (!cache_)
  790. continue;
  791. // App cache does not keep track of LRU timestamps so this method cannot
  792. // be used.
  793. if (type == net::APP_CACHE)
  794. continue;
  795. if (saved_times_.empty())
  796. continue;
  797. const disk_cache_fuzzer::DoomEntriesBetween& deb =
  798. command.doom_entries_between();
  799. auto time_it1 = GetNextValue(&saved_times_, deb.time_id1());
  800. auto time_it2 = GetNextValue(&saved_times_, deb.time_id2());
  801. base::Time time1 = time_it1->second;
  802. base::Time time2 = time_it2->second;
  803. if (time1 > time2)
  804. std::swap(time1, time2);
  805. bool async = deb.async();
  806. net::TestCompletionCallback tcb;
  807. net::CompletionOnceCallback cb =
  808. !async ? tcb.callback() : GetIOCallback(IOType::DoomEntriesBetween);
  809. MAYBE_PRINT << "DoomEntriesBetween(" << time1 << ", " << time2 << ")"
  810. << std::flush;
  811. int rv = cache_->DoomEntriesBetween(time1, time2, std::move(cb));
  812. if (!async)
  813. rv = tcb.GetResult(rv);
  814. MAYBE_PRINT << " = " << rv << std::endl;
  815. break;
  816. }
  817. case disk_cache_fuzzer::FuzzCommand::kOnExternalCacheHit: {
  818. if (!cache_)
  819. continue;
  820. if (created_cache_entries_.empty())
  821. continue;
  822. uint64_t key_id = command.on_external_cache_hit().key_id();
  823. auto key_it = GetNextValue(&created_cache_entries_, key_id);
  824. MAYBE_PRINT << "OnExternalCacheHit(\"" << key_it->second << "\")"
  825. << std::endl;
  826. cache_->OnExternalCacheHit(key_it->second);
  827. break;
  828. }
  829. case disk_cache_fuzzer::FuzzCommand::kTrimForTest: {
  830. // Blockfile-cache specific method.
  831. if (!block_impl_ || type != net::DISK_CACHE)
  832. return;
  833. MAYBE_PRINT << "TrimForTest()" << std::endl;
  834. RunTaskForTest(base::BindOnce(&disk_cache::BackendImpl::TrimForTest,
  835. base::Unretained(block_impl_),
  836. command.trim_for_test().empty()));
  837. break;
  838. }
  839. case disk_cache_fuzzer::FuzzCommand::kTrimDeletedListForTest: {
  840. // Blockfile-cache specific method.
  841. if (!block_impl_ || type != net::DISK_CACHE)
  842. return;
  843. MAYBE_PRINT << "TrimDeletedListForTest()" << std::endl;
  844. RunTaskForTest(
  845. base::BindOnce(&disk_cache::BackendImpl::TrimDeletedListForTest,
  846. base::Unretained(block_impl_),
  847. command.trim_deleted_list_for_test().empty()));
  848. break;
  849. }
  850. case disk_cache_fuzzer::FuzzCommand::kGetAvailableRange: {
  851. if (open_cache_entries_.empty())
  852. continue;
  853. const disk_cache_fuzzer::GetAvailableRange& gar =
  854. command.get_available_range();
  855. auto entry_it = GetNextValue(&open_cache_entries_, gar.entry_id());
  856. if (!IsValidEntry(&entry_it->second) ||
  857. !sparse_entry_tracker_[entry_it->second.entry_ptr])
  858. continue;
  859. disk_cache::Entry* entry = entry_it->second.entry_ptr;
  860. uint32_t offset = gar.offset() % kMaxEntrySize;
  861. uint32_t len = gar.len() % kMaxEntrySize;
  862. bool async = gar.async();
  863. auto result_checker = base::BindRepeating(
  864. [](net::CompletionOnceCallback callback, uint32_t offset,
  865. uint32_t len, const disk_cache::RangeResult& result) {
  866. std::move(callback).Run(result.net_error);
  867. if (result.net_error <= 0)
  868. return;
  869. // Make sure that the result is contained in what was
  870. // requested. It doesn't have to be the same even if there was
  871. // an exact corresponding write, since representation of ranges
  872. // may be imprecise, and here we don't know that there was.
  873. // No overflow thanks to % kMaxEntrySize.
  874. net::Interval<uint32_t> requested(offset, offset + len);
  875. uint32_t range_start, range_end;
  876. base::CheckedNumeric<uint64_t> range_start64(result.start);
  877. CHECK(range_start64.AssignIfValid(&range_start));
  878. base::CheckedNumeric<uint64_t> range_end64 =
  879. range_start + result.available_len;
  880. CHECK(range_end64.AssignIfValid(&range_end));
  881. net::Interval<uint32_t> gotten(range_start, range_end);
  882. CHECK(requested.Contains(gotten));
  883. },
  884. GetIOCallback(IOType::GetAvailableRange), offset, len);
  885. TestRangeResultCompletionCallback tcb;
  886. disk_cache::RangeResultCallback cb =
  887. !async ? tcb.callback() : result_checker;
  888. MAYBE_PRINT << "GetAvailableRange(\"" << entry->GetKey() << "\", "
  889. << offset << ", " << len << ")" << std::flush;
  890. disk_cache::RangeResult result =
  891. entry->GetAvailableRange(offset, len, std::move(cb));
  892. if (result.net_error != net::ERR_IO_PENDING) {
  893. // Run the checker callback ourselves.
  894. result_checker.Run(result);
  895. } else if (!async) {
  896. // In this case the callback will be run by the backend, so we don't
  897. // need to do it manually.
  898. result = tcb.GetResult(result);
  899. }
  900. // Finally, take care of printing.
  901. if (async && result.net_error == net::ERR_IO_PENDING) {
  902. MAYBE_PRINT << " = net::ERR_IO_PENDING (async)" << std::endl;
  903. } else {
  904. MAYBE_PRINT << " = " << result.net_error
  905. << ", start = " << result.start
  906. << ", available_len = " << result.available_len;
  907. if (result.net_error < 0) {
  908. MAYBE_PRINT << ", error to string: "
  909. << net::ErrorToShortString(result.net_error)
  910. << std::endl;
  911. } else {
  912. MAYBE_PRINT << std::endl;
  913. }
  914. }
  915. break;
  916. }
  917. case disk_cache_fuzzer::FuzzCommand::kCancelSparseIo: {
  918. if (open_cache_entries_.empty())
  919. continue;
  920. const disk_cache_fuzzer::CancelSparseIO& csio =
  921. command.cancel_sparse_io();
  922. auto entry_it = GetNextValue(&open_cache_entries_, csio.entry_id());
  923. if (!IsValidEntry(&entry_it->second))
  924. continue;
  925. MAYBE_PRINT << "CancelSparseIO(\""
  926. << entry_it->second.entry_ptr->GetKey() << "\")"
  927. << std::endl;
  928. entry_it->second.entry_ptr->CancelSparseIO();
  929. break;
  930. }
  931. case disk_cache_fuzzer::FuzzCommand::kDoomKey: {
  932. if (!cache_)
  933. continue;
  934. if (created_cache_entries_.empty())
  935. continue;
  936. const disk_cache_fuzzer::DoomKey& dk = command.doom_key();
  937. uint64_t key_id = dk.key_id();
  938. net::RequestPriority pri = GetRequestPriority(dk.pri());
  939. bool async = dk.async();
  940. auto key_it = GetNextValue(&created_cache_entries_, key_id);
  941. net::TestCompletionCallback tcb;
  942. net::CompletionOnceCallback cb =
  943. !async ? tcb.callback() : GetIOCallback(IOType::DoomKey);
  944. MAYBE_PRINT << "DoomKey(\"" << key_it->second << "\")" << std::flush;
  945. int rv = cache_->DoomEntry(key_it->second, pri, std::move(cb));
  946. if (!async)
  947. rv = tcb.GetResult(rv);
  948. MAYBE_PRINT << " = " << rv << std::endl;
  949. break;
  950. }
  951. case disk_cache_fuzzer::FuzzCommand::kDestructBackend: {
  952. // Block_impl_ will leak if we destruct the backend without closing
  953. // previous entries.
  954. // TODO(mpdenton) consider creating a separate fuzz target that allows
  955. // closing the |block_impl_| and ignore leaks.
  956. if (block_impl_ || !cache_)
  957. continue;
  958. const disk_cache_fuzzer::DestructBackend& db =
  959. command.destruct_backend();
  960. // Only sometimes actually destruct the backend.
  961. if (!db.actually_destruct1() || !db.actually_destruct2())
  962. continue;
  963. MAYBE_PRINT << "~Backend(). Backend destruction." << std::endl;
  964. cache_.reset();
  965. break;
  966. }
  967. case disk_cache_fuzzer::FuzzCommand::kAddRealDelay: {
  968. if (!command.add_real_delay().actually_delay())
  969. continue;
  970. MAYBE_PRINT << "AddRealDelay(1ms)" << std::endl;
  971. base::PlatformThread::Sleep(base::Milliseconds(1));
  972. break;
  973. }
  974. case disk_cache_fuzzer::FuzzCommand::FUZZ_COMMAND_ONEOF_NOT_SET: {
  975. continue;
  976. break;
  977. }
  978. }
  979. }
  980. }
  981. void DiskCacheLPMFuzzer::HandleSetMaxSize(
  982. const disk_cache_fuzzer::SetMaxSize& sms) {
  983. if (!cache_)
  984. return;
  985. max_size_ = sms.size();
  986. max_size_ %= kMaxSizeKB;
  987. max_size_ *= 1024;
  988. MAYBE_PRINT << "SetMaxSize(" << max_size_ << ")" << std::endl;
  989. if (simple_cache_impl_)
  990. CHECK_EQ(true, simple_cache_impl_->SetMaxSize(max_size_));
  991. if (block_impl_)
  992. CHECK_EQ(true, block_impl_->SetMaxSize(max_size_));
  993. if (mem_cache_)
  994. CHECK_EQ(true, mem_cache_->SetMaxSize(max_size_));
  995. }
  996. void DiskCacheLPMFuzzer::CreateBackend(
  997. disk_cache_fuzzer::FuzzCommands::CacheBackend cache_backend,
  998. uint32_t mask,
  999. net::CacheType type,
  1000. bool simple_cache_wait_for_index) {
  1001. if (cache_backend == disk_cache_fuzzer::FuzzCommands::IN_MEMORY) {
  1002. MAYBE_PRINT << "Using in-memory cache." << std::endl;
  1003. auto cache = std::make_unique<disk_cache::MemBackendImpl>(nullptr);
  1004. mem_cache_ = cache.get();
  1005. cache_ = std::move(cache);
  1006. CHECK(cache_);
  1007. } else if (cache_backend == disk_cache_fuzzer::FuzzCommands::SIMPLE) {
  1008. MAYBE_PRINT << "Using simple cache." << std::endl;
  1009. net::TestCompletionCallback cb;
  1010. // We limit ourselves to 64 fds since OS X by default gives us 256.
  1011. // (Chrome raises the number on startup, but the fuzzer doesn't).
  1012. if (!simple_file_tracker_)
  1013. simple_file_tracker_ =
  1014. std::make_unique<disk_cache::SimpleFileTracker>(kMaxFdsSimpleCache);
  1015. auto simple_backend = std::make_unique<disk_cache::SimpleBackendImpl>(
  1016. /*file_operations=*/nullptr, cache_path_,
  1017. /*cleanup_tracker=*/nullptr, simple_file_tracker_.get(), max_size_,
  1018. type, /*net_log=*/nullptr);
  1019. simple_backend->Init(cb.callback());
  1020. CHECK_EQ(cb.WaitForResult(), net::OK);
  1021. simple_cache_impl_ = simple_backend.get();
  1022. cache_ = std::move(simple_backend);
  1023. if (simple_cache_wait_for_index) {
  1024. MAYBE_PRINT << "Waiting for simple cache index to be ready..."
  1025. << std::endl;
  1026. net::TestCompletionCallback wait_for_index_cb;
  1027. simple_cache_impl_->index()->ExecuteWhenReady(
  1028. wait_for_index_cb.callback());
  1029. int rv = wait_for_index_cb.WaitForResult();
  1030. CHECK_EQ(rv, net::OK);
  1031. }
  1032. } else {
  1033. MAYBE_PRINT << "Using blockfile cache";
  1034. std::unique_ptr<disk_cache::BackendImpl> cache;
  1035. if (mask) {
  1036. MAYBE_PRINT << ", mask = " << mask << std::endl;
  1037. cache = std::make_unique<disk_cache::BackendImpl>(
  1038. cache_path_, mask,
  1039. /* runner = */ nullptr, type,
  1040. /* net_log = */ nullptr);
  1041. } else {
  1042. MAYBE_PRINT << "." << std::endl;
  1043. cache = std::make_unique<disk_cache::BackendImpl>(
  1044. cache_path_,
  1045. /* cleanup_tracker = */ nullptr,
  1046. /* runner = */ nullptr, type,
  1047. /* net_log = */ nullptr);
  1048. }
  1049. block_impl_ = cache.get();
  1050. cache_ = std::move(cache);
  1051. CHECK(cache_);
  1052. // TODO(mpdenton) kNoRandom or not? It does a lot of waiting for IO. May be
  1053. // good for avoiding leaks but tests a less realistic cache.
  1054. // block_impl_->SetFlags(disk_cache::kNoRandom);
  1055. // TODO(mpdenton) should I always wait here?
  1056. net::TestCompletionCallback cb;
  1057. block_impl_->Init(cb.callback());
  1058. CHECK_EQ(cb.WaitForResult(), net::OK);
  1059. }
  1060. }
  1061. void DiskCacheLPMFuzzer::CloseAllRemainingEntries() {
  1062. for (auto& entry_info : open_cache_entries_) {
  1063. disk_cache::Entry** entry_ptr = &entry_info.second.entry_ptr;
  1064. if (!*entry_ptr)
  1065. continue;
  1066. MAYBE_PRINT << "Destructor CloseEntry(\"" << (*entry_ptr)->GetKey() << "\")"
  1067. << std::endl;
  1068. (*entry_ptr)->Close();
  1069. *entry_ptr = nullptr;
  1070. }
  1071. }
  1072. DiskCacheLPMFuzzer::~DiskCacheLPMFuzzer() {
  1073. // |block_impl_| leaks a lot more if we don't close entries before destructing
  1074. // the backend.
  1075. if (block_impl_) {
  1076. // TODO(mpdenton) Consider creating a fuzz target that does not wait for
  1077. // blockfile, and also does not detect leaks.
  1078. // Because the blockfile backend will leak any entries closed after its
  1079. // destruction, we need to wait for any remaining backend callbacks to
  1080. // finish. Otherwise, there will always be a race between handling callbacks
  1081. // with RunUntilIdle() and actually closing all of the remaining entries.
  1082. // And, closing entries after destructing the backend will not work and
  1083. // cause leaks.
  1084. for (auto& entry_it : open_cache_entries_) {
  1085. if (entry_it.second.tcb) {
  1086. WaitOnEntry(&entry_it.second);
  1087. }
  1088. }
  1089. // Destroy any open iterators before destructing the backend so we don't
  1090. // cause leaks. TODO(mpdenton) should maybe be documented?
  1091. // Also *must* happen after waiting for all OpenNextEntry callbacks to
  1092. // finish, because destructing the iterators may cause those callbacks to be
  1093. // cancelled, which will cause WaitOnEntry() to spin forever waiting.
  1094. // TODO(mpdenton) should also be documented?
  1095. open_iterators_.clear();
  1096. // Just in case, finish any callbacks.
  1097. init_globals->task_environment_->RunUntilIdle();
  1098. // Close all entries that haven't been closed yet.
  1099. CloseAllRemainingEntries();
  1100. // Destroy the backend.
  1101. cache_.reset();
  1102. } else {
  1103. // Here we won't bother with waiting for our OpenEntry* callbacks.
  1104. cache_.reset();
  1105. // Finish any callbacks that came in before backend destruction.
  1106. init_globals->task_environment_->RunUntilIdle();
  1107. // Close all entries that haven't been closed yet.
  1108. CloseAllRemainingEntries();
  1109. }
  1110. // Make sure any tasks triggered by the CloseEntry's have run.
  1111. init_globals->task_environment_->RunUntilIdle();
  1112. if (simple_cache_impl_)
  1113. CHECK(simple_file_tracker_->IsEmptyForTesting());
  1114. base::RunLoop().RunUntilIdle();
  1115. DeleteCache(cache_path_);
  1116. }
  1117. DEFINE_BINARY_PROTO_FUZZER(const disk_cache_fuzzer::FuzzCommands& commands) {
  1118. {
  1119. DiskCacheLPMFuzzer disk_cache_fuzzer_instance;
  1120. disk_cache_fuzzer_instance.RunCommands(commands);
  1121. }
  1122. MAYBE_PRINT << "-----------------------" << std::endl;
  1123. }
  1124. //