MCPcopy Create free account
hub / github.com/emscripten-core/emscripten / readAtOffset

Function readAtOffset

system/lib/wasmfs/syscalls.cpp:179–248  ·  view source on GitHub ↗

Internal read function called by __wasi_fd_read and __wasi_fd_pread Receives an open file state offset. Optionally sets open file state offset. TODO: combine this with writeAtOffset because the code is nearly identical.

Source from the content-addressed store, hash-verified

177// Optionally sets open file state offset.
178// TODO: combine this with writeAtOffset because the code is nearly identical.
179static __wasi_errno_t readAtOffset(OffsetHandling setOffset,
180 __wasi_fd_t fd,
181 const __wasi_iovec_t* iovs,
182 size_t iovs_len,
183 __wasi_size_t* nread,
184 __wasi_filesize_t offset = 0) {
185 auto openFile = wasmFS.getFileTable().locked().getEntry(fd);
186 if (!openFile) {
187 return __WASI_ERRNO_BADF;
188 }
189
190 auto lockedOpenFile = openFile->locked();
191
192 if (setOffset == OffsetHandling::OpenFileState) {
193 offset = lockedOpenFile.getPosition();
194 }
195
196 if (iovs_len < 0 || offset < 0) {
197 return __WASI_ERRNO_INVAL;
198 }
199
200 // TODO: Check open file access mode for read permissions.
201
202 auto file = lockedOpenFile.getFile()->dynCast<DataFile>();
203
204 // If file is nullptr, then the file was not a DataFile.
205 if (!file) {
206 return __WASI_ERRNO_ISDIR;
207 }
208
209 auto lockedFile = file->locked();
210
211 size_t bytesRead = 0;
212 for (size_t i = 0; i < iovs_len; i++) {
213 uint8_t* buf = iovs[i].buf;
214 size_t len = iovs[i].buf_len;
215
216 if (!buf && len > 0) {
217 return __WASI_ERRNO_INVAL;
218 }
219
220 // TODO: Check for overflow when adding offset + bytesRead.
221 auto result = lockedFile.read(buf, len, offset + bytesRead);
222 if (result < 0) {
223 // This individual read failed. Report the error unless we've already read
224 // some bytes, in which case report a successful short read.
225 if (bytesRead > 0) {
226 break;
227 }
228 return -result;
229 }
230
231 // The read was successful.
232
233 // Backends must only return len or less.
234 assert(result <= len);
235
236 bytesRead += result;

Callers 2

__wasi_fd_readFunction · 0.85
__wasi_fd_preadFunction · 0.85

Calls 8

getEntryMethod · 0.80
getPositionMethod · 0.80
isSeekableMethod · 0.80
setPositionMethod · 0.80
assertFunction · 0.50
lockedMethod · 0.45
getFileMethod · 0.45
readMethod · 0.45

Tested by

no test coverage detected