The state of a file on the underlying Node file system.
| 17 | |
| 18 | // The state of a file on the underlying Node file system. |
| 19 | class NodeState { |
| 20 | // Map all separate WasmFS opens of a file to a single underlying fd. |
| 21 | size_t openCount = 0; |
| 22 | oflags_t openFlags = 0; |
| 23 | int fd = -1; |
| 24 | |
| 25 | public: |
| 26 | std::string path; |
| 27 | |
| 28 | NodeState(std::string path) : path(path) {} |
| 29 | |
| 30 | int getFD() { |
| 31 | assert(openCount > 0); |
| 32 | return fd; |
| 33 | } |
| 34 | |
| 35 | bool isOpen() { return openCount > 0; } |
| 36 | |
| 37 | // Attempt to open the file with the given flags, returning 0 on success or an |
| 38 | // error code. |
| 39 | int open(oflags_t flags) { |
| 40 | int result = 0; |
| 41 | if (openCount == 0) { |
| 42 | // No existing fd, so open a fresh one. |
| 43 | switch (flags) { |
| 44 | case O_RDONLY: |
| 45 | result = _wasmfs_node_open(path.c_str(), "r"); |
| 46 | break; |
| 47 | case O_WRONLY: |
| 48 | // TODO(sbc): Specific handling of O_WRONLY. |
| 49 | // There is no simple way to map O_WRONLY to an fopen-style |
| 50 | // mode string since the only two modes that are write only |
| 51 | // are `w` and `a`. The problem with the former is that it |
| 52 | // truncates to file. The problem with the latter is that it |
| 53 | // opens for appending. For now simply opening in O_RDWR |
| 54 | // mode is enough to pass all our tests. |
| 55 | case O_RDWR: |
| 56 | result = _wasmfs_node_open(path.c_str(), "r+"); |
| 57 | break; |
| 58 | default: |
| 59 | WASMFS_UNREACHABLE("Unexpected open access mode"); |
| 60 | } |
| 61 | if (result < 0) { |
| 62 | return result; |
| 63 | } |
| 64 | // Fall through to update our state with the new result. |
| 65 | } else if ((openFlags == O_RDONLY && |
| 66 | (flags == O_WRONLY || flags == O_RDWR)) || |
| 67 | (openFlags == O_WRONLY && |
| 68 | (flags == O_RDONLY || flags == O_RDWR))) { |
| 69 | // We already have a file descriptor, but we need to replace it with a new |
| 70 | // fd with more access. |
| 71 | result = _wasmfs_node_open(path.c_str(), "r+"); |
| 72 | if (result < 0) { |
| 73 | return result; |
| 74 | } |
| 75 | // Success! Close the old fd before updating it. |
| 76 | (void)_wasmfs_node_close(fd); |