Isolate CLI workers and module serialization
This commit is contained in:
+33
-2
@@ -1642,14 +1642,30 @@ public:
|
||||
|
||||
static String serialize_module_artifact(const String& wasm_path)
|
||||
{
|
||||
int lock_fd = open((wasm_path + ".lock").c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666);
|
||||
if(lock_fd < 0 || flock(lock_fd, LOCK_EX) != 0)
|
||||
{
|
||||
if(lock_fd >= 0)
|
||||
close(lock_fd);
|
||||
return("cannot lock " + wasm_path);
|
||||
}
|
||||
struct SerializationLock
|
||||
{
|
||||
int fd;
|
||||
~SerializationLock() { flock(fd, LOCK_UN); close(fd); }
|
||||
} lock{lock_fd};
|
||||
if(!serialized_module_needs_refresh(wasm_path))
|
||||
return("");
|
||||
struct stat initial_stat;
|
||||
if(stat(wasm_path.c_str(), &initial_stat) != 0 || !S_ISREG(initial_stat.st_mode))
|
||||
return("cannot stat " + wasm_path);
|
||||
std::vector<u8> bytes;
|
||||
if(!wasm_read_file(wasm_path, bytes))
|
||||
return("cannot read " + wasm_path);
|
||||
wasmtime::Engine engine = make_engine();
|
||||
String error;
|
||||
auto module = compile_and_cache_module(engine, cached_wasm_path(wasm_path), bytes, error);
|
||||
auto module = compile_and_cache_module(engine, cached_wasm_path(wasm_path), bytes, error,
|
||||
wasm_path, &initial_stat);
|
||||
if(!module)
|
||||
return(error);
|
||||
if(serialized_module_needs_refresh(wasm_path))
|
||||
@@ -1697,8 +1713,15 @@ private:
|
||||
return(std::nullopt);
|
||||
}
|
||||
|
||||
static bool same_artifact(const struct stat& left, const struct stat& right)
|
||||
{
|
||||
return(left.st_dev == right.st_dev && left.st_ino == right.st_ino && left.st_size == right.st_size &&
|
||||
left.st_mtim.tv_sec == right.st_mtim.tv_sec && left.st_mtim.tv_nsec == right.st_mtim.tv_nsec &&
|
||||
left.st_ctim.tv_sec == right.st_ctim.tv_sec && left.st_ctim.tv_nsec == right.st_ctim.tv_nsec);
|
||||
}
|
||||
|
||||
static std::optional<wasmtime::Module> compile_and_cache_module(wasmtime::Engine& engine, const String& cached_path,
|
||||
std::vector<u8>& bytes, String& compile_error)
|
||||
std::vector<u8>& bytes, String& compile_error, const String& source_path = "", const struct stat* expected_source = 0)
|
||||
{
|
||||
auto compiled = wasmtime::Module::compile(engine, bytes);
|
||||
if(!compiled)
|
||||
@@ -1721,6 +1744,14 @@ private:
|
||||
{
|
||||
out.flush();
|
||||
out.close();
|
||||
struct stat current_source;
|
||||
if(expected_source && (stat(source_path.c_str(), ¤t_source) != 0 ||
|
||||
!same_artifact(*expected_source, current_source)))
|
||||
{
|
||||
(void)std::remove(tmp.c_str());
|
||||
compile_error = "wasm artifact changed during serialization: " + source_path;
|
||||
return(std::nullopt);
|
||||
}
|
||||
if(std::rename(tmp.c_str(), cached_path.c_str()) != 0)
|
||||
(void)std::remove(tmp.c_str());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user