Skip to content

Commit 62987bb

Browse files
committed
Fix style issues and stack space leak
1 parent 93de65a commit 62987bb

File tree

6 files changed

+54
-45
lines changed

6 files changed

+54
-45
lines changed

src/library_fetchfs.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ addToLibrary({
88
$FETCHFS__deps: ['$stringToUTF8OnStack', 'wasmfs_create_fetch_backend', 'wasmfs_fetch_create_manifest', 'wasmfs_fetch_add_to_manifest'],
99
$FETCHFS: {
1010
createBackend(opts) {
11-
var manifest = 0;
12-
if (opts['manifest']) {
13-
manifest = wasmfs_fetch_create_manifest();
14-
Object.entries(opts['manifest']).forEach((pair) => {
15-
var path = stringToUTF8OnStack(pair[0]);
16-
var url = stringToUTF8OnStack(pair[1]);
17-
wasmfs_fetch_add_to_manifest(path, url);
18-
})
19-
}
20-
return _wasmfs_create_fetch_backend(stringToUTF8OnStack(opts.base_url), opts.chunkSize | 0, manifest);
21-
}
11+
return withStackSave(() => {
12+
var manifest = 0;
13+
if (opts['manifest']) {
14+
manifest = wasmfs_fetch_create_manifest();
15+
Object.entries(opts['manifest']).forEach(([path, url]) => {
16+
wasmfs_fetch_add_to_manifest(stringToUTF8OnStack(path),
17+
stringToUTF8OnStack(url));
18+
});
19+
}
20+
return _wasmfs_create_fetch_backend(stringToUTF8OnStack(opts.base_url), opts.chunkSize | 0, manifest);
21+
});
2222
},
2323
});
2424

src/library_wasmfs_fetch.js

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ addToLibrary({
3131
try {
3232
var u = new URL(fileUrl, self.location.origin);
3333
url = u.toString();
34-
} catch (e) {
34+
} catch(_e) {
35+
throw {status: 404};
3536
}
3637
}
3738
var chunkSize = __wasmfs_fetch_get_chunk_size(file);
@@ -41,15 +42,15 @@ addToLibrary({
4142
var lastChunk = ((offset+len) / chunkSize) | 0;
4243
if (!(file in wasmFS$JSMemoryRanges)) {
4344
var fileInfo = await fetch(url,{method:"HEAD", headers:{"Range": "bytes=0-"}});
44-
if(fileInfo.ok &&
45+
if (fileInfo.ok &&
4546
fileInfo.headers.has("Content-Length") &&
4647
fileInfo.headers.get("Accept-Ranges") == "bytes" &&
4748
(parseInt(fileInfo.headers.get("Content-Length")) > chunkSize*2)) {
4849
wasmFS$JSMemoryRanges[file] = {size:parseInt(fileInfo.headers.get("Content-Length")), chunks:[], chunkSize:chunkSize};
4950
} else {
5051
// may as well/forced to download the whole file
5152
var wholeFileReq = await fetch(url);
52-
if(!wholeFileReq.ok) {
53+
if (!wholeFileReq.ok) {
5354
throw wholeFileReq;
5455
}
5556
var wholeFileData = new Uint8Array(await wholeFileReq.arrayBuffer());
@@ -60,11 +61,11 @@ addToLibrary({
6061
}
6162
var allPresent = true;
6263
var i;
63-
if(lastChunk * chunkSize < offset+len) {
64+
if (lastChunk * chunkSize < offset+len) {
6465
lastChunk += 1;
6566
}
66-
for(i = firstChunk; i < lastChunk; i++) {
67-
if(!wasmFS$JSMemoryRanges[file].chunks[i]) {
67+
for (i = firstChunk; i < lastChunk; i++) {
68+
if (!wasmFS$JSMemoryRanges[file].chunks[i]) {
6869
allPresent = false;
6970
break;
7071
}
@@ -78,14 +79,13 @@ addToLibrary({
7879
var start = firstChunk*chunkSize;
7980
var end = lastChunk*chunkSize;
8081
var response = await fetch(url, {headers:{"Range": `bytes=${start}-${end-1}`}});
81-
if (response.ok) {
82-
var bytes = new Uint8Array(await response['arrayBuffer']());
83-
for (i = firstChunk; i < lastChunk; i++) {
84-
wasmFS$JSMemoryRanges[file].chunks[i] = bytes.slice(i*chunkSize-start,(i+1)*chunkSize-start);
85-
}
86-
} else {
82+
if (!response.ok) {
8783
throw response;
8884
}
85+
var bytes = new Uint8Array(await response['arrayBuffer']());
86+
for (i = firstChunk; i < lastChunk; i++) {
87+
wasmFS$JSMemoryRanges[file].chunks[i] = bytes.slice(i*chunkSize-start,(i+1)*chunkSize-start);
88+
}
8989
return Promise.resolve();
9090
}
9191

@@ -110,24 +110,21 @@ addToLibrary({
110110
read: async (file, buffer, length, offset) => {
111111
try {
112112
await getFileRange(file, offset || 0, length);
113-
} catch (response) {
114-
return response.status === 404 ? -{{{ cDefs.ENOENT }}} : -{{{ cDefs.EBADF }}};
113+
} catch (failedResponse) {
114+
return failedResponse.status === 404 ? -{{{ cDefs.ENOENT }}} : -{{{ cDefs.EBADF }}};
115115
}
116116
var fileInfo = wasmFS$JSMemoryRanges[file];
117117
var fileData = fileInfo.chunks;
118118
var chunkSize = fileInfo.chunkSize;
119119
var firstChunk = (offset / chunkSize) | 0;
120120
var lastChunk = ((offset+length) / chunkSize) | 0;
121-
if(offset + length > lastChunk * chunkSize) {
121+
if (offset + length > lastChunk * chunkSize) {
122122
lastChunk += 1;
123123
}
124124
var readLength = 0;
125125
for (var i = firstChunk; i < lastChunk; i++) {
126126
var chunk = fileData[i];
127127
var start = Math.max(i*chunkSize, offset);
128-
if(!chunk) {
129-
throw [fileData.length, firstChunk, lastChunk, i];
130-
}
131128
var chunkStart = i*chunkSize;
132129
var end = Math.min(chunkStart+chunkSize, offset+length);
133130
HEAPU8.set(chunk.subarray(start-chunkStart, end-chunkStart), buffer+(start-offset));
@@ -138,7 +135,7 @@ addToLibrary({
138135
getSize: async (file) => {
139136
try {
140137
await getFileRange(file, 0, 0);
141-
} catch (response) {
138+
} catch (failedResponse) {
142139
return 0;
143140
}
144141
return wasmFS$JSMemoryRanges[file].size;

system/include/emscripten/wasmfs.h

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,18 @@ backend_t wasmfs_create_memory_backend(void);
5757
//
5858
// TODO: Add an async version of this function that will work on the main
5959
// thread.
60-
backend_t wasmfs_create_fetch_backend(const char* base_url __attribute__((nonnull)), uint32_t, void *);
60+
backend_t wasmfs_create_fetch_backend(const char* base_url __attribute__((nonnull)),
61+
uint32_t chunkSize,
62+
void *manifest);
6163

64+
// Create a FetchFS manifest record that can be populated and passed into
65+
// wasmfs_fetch_create_backend.
6266
void *wasmfs_fetch_create_manifest();
63-
void wasmfs_fetch_add_to_manifest(void *, const char *, const char *);
67+
68+
// Add a path to URL mapping to the given manifest.
69+
void wasmfs_fetch_add_to_manifest(void *manifest __attribute__((nonnull)),
70+
const char *path __attribute__((nonnull)),
71+
const char *url __attribute__((nonnull)));
6472

6573
backend_t wasmfs_create_node_backend(const char* root __attribute__((nonnull)));
6674

system/lib/wasmfs/backends/fetch_backend.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ const std::string FetchBackend::getFileURL(const std::string& filePath) {
112112
}
113113
return baseUrl + "/" + filePath;
114114
}
115+
115116
uint32_t FetchBackend::getChunkSize() {
116117
return chunkSize;
117118
}
@@ -124,27 +125,30 @@ extern "C" {
124125
"Cannot safely create fetch backend on main browser thread");
125126
return wasmFS.addBackend(std::make_unique<FetchBackend>(
126127
base_url ? base_url : "",
127-
chunkSize != 0 ? chunkSize : DEFAULT_CHUNK_SIZE,
128+
chunkSize ? chunkSize : DEFAULT_CHUNK_SIZE,
128129
manifest,
129130
[](backend_t backend) { _wasmfs_create_fetch_backend_js(backend); }));
130131
}
131132

132-
const char* EMSCRIPTEN_KEEPALIVE _wasmfs_fetch_get_file_path(void* ptr) {
133+
const char* _wasmfs_fetch_get_file_path(void* ptr) {
133134
auto* file = reinterpret_cast<wasmfs::FetchFile*>(ptr);
134135
return file ? file->getPath().data() : nullptr;
135136
}
136-
const char* EMSCRIPTEN_KEEPALIVE _wasmfs_fetch_get_file_url(void* ptr) {
137+
138+
const char* _wasmfs_fetch_get_file_url(void* ptr) {
137139
auto* file = reinterpret_cast<wasmfs::FetchFile*>(ptr);
138140
return file ? file->getURL().data() : nullptr;
139141
}
140-
uint32_t EMSCRIPTEN_KEEPALIVE _wasmfs_fetch_get_chunk_size(void* ptr) {
142+
143+
uint32_t _wasmfs_fetch_get_chunk_size(void* ptr) {
141144
auto* file = reinterpret_cast<wasmfs::FetchFile*>(ptr);
142145
return file ? file->getChunkSize() : DEFAULT_CHUNK_SIZE;
143146
}
144147

145148
void *EMSCRIPTEN_KEEPALIVE wasmfs_fetch_create_manifest() {
146149
return new FetchManifest();
147150
}
151+
148152
void EMSCRIPTEN_KEEPALIVE wasmfs_fetch_add_to_manifest(void *manifest_ptr, const char *path, const char *url) {
149153
auto* manifest = reinterpret_cast<FetchManifest *>(manifest_ptr);
150154
auto path_str = std::string(path);

system/lib/wasmfs/backends/fetch_backend.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@
66
#include "wasmfs.h"
77

88
extern "C" {
9-
// See library_wasmfs_fetch.js
10-
void _wasmfs_create_fetch_backend_js(wasmfs::backend_t);
9+
// See library_wasmfs_fetch.js
10+
void _wasmfs_create_fetch_backend_js(wasmfs::backend_t);
1111
}

test/common.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1938,7 +1938,7 @@ def send_head(self):
19381938
f = open(path, 'rb')
19391939
fs = os.fstat(f.fileno())
19401940
except IOError:
1941-
self.send_error(404, "File not found: " + path)
1941+
self.send_error(404, f'File not found {path}')
19421942
return None
19431943
if self.path.endswith('.js'):
19441944
self.send_response(200)
@@ -1947,16 +1947,16 @@ def send_head(self):
19471947
self.send_header('Content-length', fs[6])
19481948
self.end_headers()
19491949
return f
1950-
elif self.headers.get("Range"):
1950+
elif self.headers.get('Range'):
19511951
self.send_response(206)
19521952
ctype = self.guess_type(path)
19531953
self.send_header('Content-Type', ctype)
1954-
pieces = self.headers.get("Range").split("=")[1].split("-")
1954+
pieces = self.headers.get('Range').split('=')[1].split('-')
19551955
start = int(pieces[0]) if pieces[0] != '' else 0
19561956
end = int(pieces[1]) if pieces[1] != '' else fs[6] - 1
19571957
end = min(fs[6] - 1, end)
19581958
length = end - start + 1
1959-
self.send_header('Content-Range', "bytes " + str(start) + "-" + str(end) + "/" + str(fs[6]))
1959+
self.send_header('Content-Range', f'bytes {start}-{end}/{fs[6]}')
19601960
self.send_header('Content-Length', str(length))
19611961
self.end_headers()
19621962
return f
@@ -2060,19 +2060,19 @@ def do_GET(self):
20602060
# Use SimpleHTTPServer default file serving operation for GET.
20612061
if DEBUG:
20622062
print('[simple HTTP serving:', unquote_plus(self.path), ']')
2063-
if self.headers.get("Range"):
2063+
if self.headers.get('Range'):
20642064
self.send_response(206)
20652065
path = self.translate_path(self.path)
20662066
data = read_binary(path)
20672067
ctype = self.guess_type(path)
20682068
self.send_header('Content-type', ctype)
2069-
pieces = self.headers.get("range").split("=")[1].split("-")
2069+
pieces = self.headers.get('Range').split('=')[1].split('-')
20702070
start = int(pieces[0]) if pieces[0] != '' else 0
20712071
end = int(pieces[1]) if pieces[1] != '' else len(data) - 1
20722072
end = min(len(data) - 1, end)
20732073
length = end - start + 1
20742074
self.send_header('Content-Length', str(length))
2075-
self.send_header('Content-Range', "bytes " + str(start) + "-" + str(end) + "/" + str(len(data)))
2075+
self.send_header('Content-Range', f'bytes {start}-{end}/{len(data)}')
20762076
self.end_headers()
20772077
self.wfile.write(data[start:end + 1])
20782078
else:

0 commit comments

Comments
 (0)