Code analysis violations Bug in scheduler - race during with worker thread shutdown.
Showing the changes to src/vm/sys/fd_manager.cpp (1 of 18 files). Show all
Unified · Split
| @@ -0,0 +1,84 @@ | ||
| 1 | +// | |
| 2 | +// Dis VM | |
| 3 | +// File: fd_manager.cpp | |
| 4 | +// Author: arr | |
| 5 | +// | |
| 6 | + | |
| 7 | +#include <array> | |
| 8 | +#include <mutex> | |
| 9 | +#include <unordered_map> | |
| 10 | +#include <exceptions.h> | |
| 11 | +#include <vm_memory.h> | |
| 12 | +#include "sys_utils.h" | |
| 13 | + | |
| 14 | +using namespace disvm::runtime; | |
| 15 | + | |
| 16 | +namespace | |
| 17 | +{ | |
| 18 | + using fd_map_t = std::unordered_map<word_t, vm_alloc_t *>; | |
| 19 | + | |
| 20 | + auto std_fd = std::array<vm_alloc_t * , 3> | |
| 21 | + { | |
| 22 | + nullptr, // stdin | |
| 23 | + nullptr, // stdout | |
| 24 | + nullptr, // stderr | |
| 25 | + }; | |
| 26 | + | |
| 27 | + auto next_fd = word_t{ 0 }; | |
| 28 | + | |
| 29 | + std::mutex fd_map_lock; | |
| 30 | + auto fd_map = fd_map_t{}; | |
| 31 | +} | |
| 32 | + | |
| 33 | +word_t disvm::runtime::sys::create_fd_record(vm_alloc_t * fd_alloc) | |
| 34 | +{ | |
| 35 | + assert(fd_alloc != nullptr); | |
| 36 | + | |
| 37 | + { | |
| 38 | + std::lock_guard<std::mutex> lock{ fd_map_lock }; | |
| 39 | + | |
| 40 | + auto new_fd = next_fd; | |
| 41 | + next_fd++; | |
| 42 | + if (new_fd < static_cast<word_t>(std_fd.size())) | |
| 43 | + { | |
| 44 | + std_fd[new_fd] = fd_alloc; | |
| 45 | + } | |
| 46 | + else | |
| 47 | + { | |
| 48 | + assert(fd_map.cend() == fd_map.find(new_fd)); | |
| 49 | + fd_map[new_fd] = fd_alloc; | |
| 50 | + } | |
| 51 | + | |
| 52 | + return new_fd; | |
| 53 | + } | |
| 54 | +} | |
| 55 | + | |
| 56 | +vm_alloc_t * disvm::runtime::sys::fetch_fd_record(word_t fd) | |
| 57 | +{ | |
| 58 | + assert(fd != sys::vm_invalid_fd && "Invalid FD value"); | |
| 59 | + | |
| 60 | + if (0 <= fd && fd < static_cast<word_t>(std_fd.size())) | |
| 61 | + return std_fd[fd]; | |
| 62 | + | |
| 63 | + { | |
| 64 | + std::lock_guard<std::mutex> lock{ fd_map_lock }; | |
| 65 | + auto iter = fd_map.find(fd); | |
| 66 | + if (iter == fd_map.cend()) | |
| 67 | + throw vm_user_exception{ "Unknown file descriptor" }; | |
| 68 | + | |
| 69 | + return iter->second; | |
| 70 | + } | |
| 71 | +} | |
| 72 | + | |
| 73 | +void disvm::runtime::sys::drop_fd_record(word_t fd) | |
| 74 | +{ | |
| 75 | + assert(fd != sys::vm_invalid_fd && "Invalid FD value"); | |
| 76 | + assert(fd >= static_cast<word_t>(std_fd.size()) && "Request to drop std file?"); | |
| 77 | + | |
| 78 | + { | |
| 79 | + std::lock_guard<std::mutex> lock{ fd_map_lock }; | |
| 80 | + auto iter = fd_map.find(fd); | |
| 81 | + if (iter != fd_map.cend()) | |
| 82 | + fd_map.erase(iter); | |
| 83 | + } | |
| 84 | +} | |