Path: blob/main/system/lib/wasmfs/fuzzer/workload.cpp
6175 views
// Copyright 2021 The Emscripten Authors. All rights reserved.1// Emscripten is available under two separate licenses, the MIT license and the2// University of Illinois/NCSA Open Source License. Both these licenses can be3// found in the LICENSE file.45// This file defines fuzzer workloads which primarily fuzz multi-threaded6// operations.78#include "workload.h"910namespace wasmfs {1112bool ReadWrite::isSame(std::vector<char>& target) {13std::set<char> seen;1415for (auto it = target.begin(); it != target.end() - 1; it++) {16seen.insert(*it);17if (seen.size() > 1) {18printf("Read the following incorrect data: %s\n", target.data());19return false;20}21}22return true;23}2425void ReadWrite::writer() {26while (!go) {27std::this_thread::yield();28}2930while (!stop) {31if (VERBOSE) {32std::cout << std::this_thread::get_id() << " is running.\n";33}34auto current = rand.upTo(work.size());3536int bytesWritten =37pwrite(fd, work[current].c_str(), work[current].size(), 0);3839assert(bytesWritten == work[current].size());40}41}4243void ReadWrite::reader() {44while (!go) {45std::this_thread::yield();46}47if (VERBOSE) {48std::cout << std::this_thread::get_id() << " is running.\n";49}5051int size = work.begin()->size();52// Add room for null terminator.53std::vector<char> buf(size + 1, 0);5455while (!stop) {56std::fill(buf.begin(), buf.end(), 0);5758int bytesRead = pread(fd, buf.data(), size, 0);59if (VERBOSE) {60printf("Read the following data: %s\n", buf.data());61printf("Bytes read: %i", bytesRead);62printf("Expected: %lu", work.begin()->size());63}64assert(bytesRead == work.begin()->size());6566assert(isSame(buf));67}68}6970void ReadWrite::execute() {71// This function should produce a string that consists of 1 character type.72work.resize(1 + rand.upTo(MAX_WORK));7374for (int i = 0; i < work.size(); i++) {75work[i] = rand.getSingleSymbolString(FILE_SIZE);76}77// Generate a test file to read and write to.78fd = open("test", O_CREAT | O_RDWR, 0777);79assert(fd != -1);8081// Populate the file with initial data.82assert(pwrite(fd, work.begin()->c_str(), work.begin()->size(), 0) != -1);8384// Create writer threads.85std::vector<std::thread> writers;86std::vector<std::thread> readers;8788for (int i = 0; i < NUM_WRITERS; i++) {89std::thread th(&ReadWrite::writer, this);90writers.emplace_back(std::move(th));91}9293for (int i = 0; i < NUM_READERS; i++) {94std::thread th(&ReadWrite::reader, this);95readers.emplace_back(std::move(th));96}9798// This atomic bool ensures that all threads have an equal chance of99// starting first.100go.store(true);101102std::this_thread::sleep_for(std::chrono::seconds(DURATION));103104// Stop file operations after pre-defined duration.105stop.store(true);106107for (auto& th : writers) {108th.join();109}110111for (auto& th : readers) {112th.join();113}114115// Clean up files.116unlink("test");117close(fd);118}119} // namespace wasmfs120121122