summaryrefslogtreecommitdiffstats
path: root/contrib/restricted/wavm/Lib/WASI/WASI.cpp
blob: 7f45a0aa06524d3c3c737a3e9119814fecbec407 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#include "WAVM/WASI/WASI.h"
#include "./WASIPrivate.h"
#include "WAVM/IR/Types.h"
#include "WAVM/Inline/BasicTypes.h"
#include "WAVM/Inline/IndexMap.h"
#include "WAVM/Logging/Logging.h"
#include "WAVM/Platform/Clock.h"
#include "WAVM/Platform/Defines.h"
#include "WAVM/Platform/Diagnostics.h"
#include "WAVM/Platform/File.h"
#include "WAVM/Platform/Intrinsic.h"
#include "WAVM/Platform/Random.h"
#include "WAVM/Platform/Thread.h"
#include "WAVM/Runtime/Intrinsics.h"
#include "WAVM/Runtime/Linker.h"
#include "WAVM/Runtime/Runtime.h"
#include "WAVM/VFS/VFS.h"
#include "WAVM/WASI/WASI.h"
#include "WAVM/WASI/WASIABI.h"

using namespace WAVM;
using namespace WAVM::IR;
using namespace WAVM::Runtime;
using namespace WAVM::WASI;

namespace WAVM { namespace WASI {
	WAVM_DEFINE_INTRINSIC_MODULE(wasi);
}}

bool ProcessResolver::resolve(const std::string& moduleName,
							  const std::string& exportName,
							  ExternType type,
							  Object*& outObject)
{
	const auto& namedInstance = moduleNameToInstanceMap.get(moduleName);
	if(namedInstance)
	{
		outObject = getInstanceExport(*namedInstance, exportName);
		if(outObject)
		{
			if(isA(outObject, type)) { return true; }
			else
			{
				Log::printf(Log::debug,
							"Resolved import %s.%s to a %s, but was expecting %s\n",
							moduleName.c_str(),
							exportName.c_str(),
							asString(getExternType(outObject)).c_str(),
							asString(type).c_str());
				return false;
			}
		}
	}

	return false;
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi,
							   "poll_oneoff",
							   __wasi_errno_return_t,
							   wasi_poll_oneoff,
							   WASIAddress inAddress,
							   WASIAddress outAddress,
							   WASIAddress numSubscriptions,
							   WASIAddress outNumEventsAddress)
{
	UNIMPLEMENTED_SYSCALL("poll_oneoff",
						  "(" WASIADDRESS_FORMAT ", " WASIADDRESS_FORMAT ", %u, " WASIADDRESS_FORMAT
						  ")",
						  inAddress,
						  outAddress,
						  numSubscriptions,
						  outNumEventsAddress);
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi, "proc_exit", void, wasi_proc_exit, __wasi_exitcode_t exitCode)
{
	TRACE_SYSCALL("proc_exit", "(%u)", exitCode);
	throw ExitException{exitCode};
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi,
							   "proc_raise",
							   __wasi_errno_return_t,
							   wasi_proc_raise,
							   __wasi_signal_t sig)
{
	// proc_raise will possibly be removed: https://github.com/WebAssembly/WASI/issues/7
	UNIMPLEMENTED_SYSCALL("proc_raise", "(%u)", sig);
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi,
							   "random_get",
							   __wasi_errno_return_t,
							   wasi_random_get,
							   WASIAddress bufferAddress,
							   WASIAddress numBufferBytes)
{
	TRACE_SYSCALL("random_get", "(" WASIADDRESS_FORMAT ", %u)", bufferAddress, numBufferBytes);

	Process* process = getProcessFromContextRuntimeData(contextRuntimeData);

	__wasi_errno_t result = __WASI_ESUCCESS;
	Runtime::catchRuntimeExceptions(
		[&] {
			U8* buffer = memoryArrayPtr<U8>(process->memory, bufferAddress, numBufferBytes);
			Platform::getCryptographicRNG(buffer, numBufferBytes);
		},
		[&](Runtime::Exception* exception) {
			WAVM_ASSERT(getExceptionType(exception) == ExceptionTypes::outOfBoundsMemoryAccess);
			result = __WASI_EFAULT;
		});

	return TRACE_SYSCALL_RETURN(result);
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi,
							   "sock_recv",
							   __wasi_errno_return_t,
							   wasi_sock_recv,
							   __wasi_fd_t sock,
							   WASIAddress ri_data,
							   WASIAddress ri_data_len,
							   __wasi_riflags_t ri_flags,
							   WASIAddress ro_datalen,
							   WASIAddress ro_flags)
{
	UNIMPLEMENTED_SYSCALL("sock_recv",
						  "(%u, " WASIADDRESS_FORMAT ", %u, 0x%04x, " WASIADDRESS_FORMAT
						  ", " WASIADDRESS_FORMAT ")",
						  sock,
						  ri_data,
						  ri_data_len,
						  ri_flags,
						  ro_datalen,
						  ro_flags);
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi,
							   "sock_send",
							   __wasi_errno_return_t,
							   wasi_sock_send,
							   __wasi_fd_t sock,
							   WASIAddress si_data,
							   WASIAddress si_data_len,
							   __wasi_siflags_t si_flags,
							   WASIAddress so_datalen)
{
	UNIMPLEMENTED_SYSCALL("sock_send",
						  "(%u, " WASIADDRESS_FORMAT ", %u, 0x%04x, " WASIADDRESS_FORMAT ")",
						  sock,
						  si_data,
						  si_data_len,
						  si_flags,
						  so_datalen);
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi,
							   "sock_shutdown",
							   __wasi_errno_return_t,
							   wasi_sock_shutdown,
							   __wasi_fd_t sock,
							   __wasi_sdflags_t how)
{
	UNIMPLEMENTED_SYSCALL("sock_shutdown", "(%u, 0x%02x)", sock, how);
}

WAVM_DEFINE_INTRINSIC_FUNCTION(wasi, "sched_yield", __wasi_errno_return_t, wasi_sched_yield)
{
	TRACE_SYSCALL("sched_yield", "()");
	Platform::yieldToAnotherThread();
	return TRACE_SYSCALL_RETURN(__WASI_ESUCCESS);
}

WASI::Process::~Process()
{
	for(const std::shared_ptr<WASI::FDE>& fde : fdMap)
	{
		VFS::Result result = fde->close();
		if(result != VFS::Result::success)
		{
			Log::printf(Log::Category::debug,
						"Error while closing file because of process exit: %s\n",
						VFS::describeResult(result));
		}
	}
}

std::shared_ptr<Process> WASI::createProcess(Runtime::Compartment* compartment,
											 std::vector<std::string>&& inArgs,
											 std::vector<std::string>&& inEnvs,
											 VFS::FileSystem* fileSystem,
											 VFS::VFD* stdIn,
											 VFS::VFD* stdOut,
											 VFS::VFD* stdErr)
{
	std::shared_ptr<Process> process = std::make_shared<Process>();
	process->args = std::move(inArgs);
	process->envs = std::move(inEnvs);
	process->fileSystem = fileSystem;

	process->compartment = compartment;
	setUserData(process->compartment, process.get(), nullptr);

	Instance* wasi_snapshot_preview1
		= Intrinsics::instantiateModule(compartment,
										{WAVM_INTRINSIC_MODULE_REF(wasi),
										 WAVM_INTRINSIC_MODULE_REF(wasiArgsEnvs),
										 WAVM_INTRINSIC_MODULE_REF(wasiClocks),
										 WAVM_INTRINSIC_MODULE_REF(wasiFile)},
										"wasi_snapshot_preview1");

	process->resolver.moduleNameToInstanceMap.set("wasi_unstable", wasi_snapshot_preview1);
	process->resolver.moduleNameToInstanceMap.set("wasi_snapshot_preview1", wasi_snapshot_preview1);

	__wasi_rights_t stdioRights = __WASI_RIGHT_FD_READ | __WASI_RIGHT_FD_FDSTAT_SET_FLAGS
								  | __WASI_RIGHT_FD_WRITE | __WASI_RIGHT_FD_FILESTAT_GET
								  | __WASI_RIGHT_POLL_FD_READWRITE;

	process->fdMap.insertOrFail(0, std::make_shared<FDE>(stdIn, stdioRights, 0, "/dev/stdin"));
	process->fdMap.insertOrFail(1, std::make_shared<FDE>(stdOut, stdioRights, 0, "/dev/stdout"));
	process->fdMap.insertOrFail(2, std::make_shared<FDE>(stdErr, stdioRights, 0, "/dev/stderr"));

	if(fileSystem)
	{
		// Map the root directory as both / and ., which allows files to be opened from it using
		// either "/file" or just "file".
		const char* preopenedRootAliases[2] = {"/", "."};
		for(Uptr aliasIndex = 0; aliasIndex < 2; ++aliasIndex)
		{
			VFS::VFD* rootFD = nullptr;
			VFS::Result openResult = fileSystem->open(
				"/", VFS::FileAccessMode::none, VFS::FileCreateMode::openExisting, rootFD);
			if(openResult != VFS::Result::success)
			{
				Errors::fatalf("Error opening WASI root directory: %s",
							   VFS::describeResult(openResult));
			}

			process->fdMap.insertOrFail(
				3 + __wasi_fd_t(aliasIndex),
				std::make_shared<FDE>(rootFD,
									  DIRECTORY_RIGHTS,
									  INHERITING_DIRECTORY_RIGHTS,
									  preopenedRootAliases[aliasIndex],
									  true,
									  __wasi_preopentype_t(__WASI_PREOPENTYPE_DIR)));
		}
	}

	process->processClockOrigin = Platform::getClockTime(Platform::Clock::processCPUTime);

	return process;
}

Resolver& WASI::getProcessResolver(Process& process) { return process.resolver; }

Process* WASI::getProcessFromContextRuntimeData(Runtime::ContextRuntimeData* contextRuntimeData)
{
	return (Process*)Runtime::getUserData(
		Runtime::getCompartmentFromContextRuntimeData(contextRuntimeData));
}

Memory* WASI::getProcessMemory(const Process& process) { return process.memory; }
void WASI::setProcessMemory(Process& process, Memory* memory) { process.memory = memory; }

I32 WASI::catchExit(std::function<I32()>&& thunk)
{
	try
	{
		return std::move(thunk)();
	}
	catch(ExitException const& exitException)
	{
		return I32(exitException.exitCode);
	}
}