Skip to content

Commit 1d35dfb

Browse files
authored
Fix fetchfs off by one error (#23852)
In #23669 , I tried to implement length clipping to prevent reads past the end of a file. Unfortunately I had an extra, unnecessary +1 term in some places which led to issues including problems when the whole file fit into a single chunk. This patch corrects the clipping.
1 parent b570030 commit 1d35dfb

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/lib/libwasmfs_fetch.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ addToLibrary({
5151
chunks: [],
5252
chunkSize: chunkSize
5353
};
54-
len = Math.min(len, size-offset+1) | 0;
54+
len = Math.min(len, size-offset);
5555
} else {
5656
// may as well/forced to download the whole file
5757
var wholeFileReq = await fetch(url);
@@ -134,7 +134,7 @@ addToLibrary({
134134
return failedResponse.status === 404 ? -{{{ cDefs.ENOENT }}} : -{{{ cDefs.EBADF }}};
135135
}
136136
var fileInfo = wasmFS$JSMemoryRanges[file];
137-
length = Math.min(length, fileInfo.size-offset+1) | 0;
137+
length = Math.min(length, fileInfo.size-offset);
138138
// As above, we check the length just in case offset was beyond size and length is now negative.
139139
if (length <= 0) {
140140
return 0;

test/wasmfs/wasmfs_fetch.c

+19-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ void test_small_chunks() {
171171
buf[size] = 0;
172172
printf("buf %s\n",buf);
173173
assert(strcmp(buf, "hello") == 0);
174-
assert(read(fd, buf+size-1, 1024) == 1);
174+
assert(read(fd, buf, 1024) == 0);
175175

176176
assert(close(fd) == 0);
177177

@@ -263,6 +263,23 @@ void test_nonexistent() {
263263
assert(close(fd) == 0);
264264
}
265265

266+
void test_big_chunks() {
267+
printf("Running %s...\n", __FUNCTION__);
268+
269+
char expected[] = "hello";
270+
size_t size = 5;
271+
272+
backend_t backend = wasmfs_create_fetch_backend("small.dat", 16);
273+
int fd;
274+
char buf[size + 1];
275+
fd = wasmfs_create_file("/testfile11", 0777, backend);
276+
read_chunks_check(fd, buf, size, 2);
277+
buf[size] = 0;
278+
printf("buf %s\n",buf);
279+
assert(strcmp(buf, "hello") == 0);
280+
assert(close(fd) == 0);
281+
}
282+
266283
int main() {
267284
getUrlOrigin(url_orig, sizeof(url_orig));
268285
test_default();
@@ -273,6 +290,7 @@ int main() {
273290
test_small_chunks();
274291
test_small_chunks_divisor_of_size();
275292
test_nonexistent();
293+
test_big_chunks();
276294

277295
return 0;
278296
}

0 commit comments

Comments
 (0)