Wasi.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. /*
  2. * Copyright (c) 2023, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ByteReader.h>
  7. #include <AK/Debug.h>
  8. #include <AK/FlyString.h>
  9. #include <AK/Random.h>
  10. #include <AK/SourceLocation.h>
  11. #include <AK/Tuple.h>
  12. #include <LibCore/File.h>
  13. #include <LibWasm/AbstractMachine/Interpreter.h>
  14. #include <LibWasm/Printer/Printer.h>
  15. #include <LibWasm/Wasi.h>
  16. #include <dirent.h>
  17. #include <fcntl.h>
  18. #include <sys/stat.h>
  19. #include <time.h>
  20. #include <unistd.h>
  21. namespace Wasm::Wasi::ABI {
  22. template<typename T>
  23. Wasm::Value CompatibleValue<T>::to_wasm_value() const
  24. {
  25. return Wasm::Value(value);
  26. }
  27. template<typename T>
  28. T deserialize(CompatibleValue<T> const& data)
  29. {
  30. return deserialize<T>(Array { ReadonlyBytes { &data.value, sizeof(data.value) } });
  31. }
  32. template<typename T, size_t N>
  33. void serialize(T const& value, Array<Bytes, N> bytes)
  34. {
  35. if constexpr (IsEnum<T>)
  36. return serialize(to_underlying(value), move(bytes));
  37. else if constexpr (IsIntegral<T>)
  38. ReadonlyBytes { &value, sizeof(value) }.copy_to(bytes[0]);
  39. else if constexpr (IsSpecializationOf<T, DistinctNumeric>)
  40. return serialize(value.value(), move(bytes));
  41. else
  42. return value.serialize_into(move(bytes));
  43. }
  44. template<typename T, size_t N>
  45. T deserialize(Array<ReadonlyBytes, N> const& bytes)
  46. {
  47. if constexpr (IsEnum<T>) {
  48. return static_cast<T>(deserialize<UnderlyingType<T>>(bytes));
  49. } else if constexpr (IsIntegral<T>) {
  50. T value;
  51. ByteReader::load(bytes[0].data(), value);
  52. return value;
  53. } else if constexpr (IsSpecializationOf<T, DistinctNumeric>) {
  54. return deserialize<RemoveCVReference<decltype(T(0).value())>>(bytes);
  55. } else {
  56. return T::read_from(bytes);
  57. }
  58. }
  59. template<typename T>
  60. CompatibleValue<T> to_compatible_value(Wasm::Value const& value)
  61. {
  62. using Type = typename ToCompatibleValue<T>::Type;
  63. // Note: the type can't be something else, we've already checked before through the function type's runtime checker.
  64. auto converted_value = *value.template to<Type>();
  65. return { .value = converted_value };
  66. }
  67. }
  68. namespace Wasm::Wasi {
  69. void ArgsSizes::serialize_into(Array<Bytes, 2> bytes) const
  70. {
  71. ABI::serialize(count, Array { bytes[0] });
  72. ABI::serialize(size, Array { bytes[1] });
  73. }
  74. void EnvironSizes::serialize_into(Array<Bytes, 2> bytes) const
  75. {
  76. ABI::serialize(count, Array { bytes[0] });
  77. ABI::serialize(size, Array { bytes[1] });
  78. }
  79. void SockRecvResult::serialize_into(Array<Bytes, 2> bytes) const
  80. {
  81. ABI::serialize(size, Array { bytes[0] });
  82. ABI::serialize(roflags, Array { bytes[1] });
  83. }
  84. void ROFlags::serialize_into(Array<Bytes, 1> bytes) const
  85. {
  86. ABI::serialize(data, Array { bytes[0] });
  87. }
  88. template<typename T>
  89. void LittleEndian<T>::serialize_into(Array<Bytes, 1> bytes) const
  90. {
  91. ABI::serialize(m_value, move(bytes));
  92. }
  93. template<typename T>
  94. LittleEndian<T> LittleEndian<T>::read_from(Array<ReadonlyBytes, 1> const& bytes)
  95. {
  96. auto swapped = ABI::deserialize<T>(bytes);
  97. return bit_cast<LittleEndian<T>>(swapped);
  98. }
  99. Rights Rights::read_from(Array<ReadonlyBytes, 1> const& bytes)
  100. {
  101. Rights rights { .data = 0 };
  102. bytes[0].copy_to(rights.data.bytes());
  103. return rights;
  104. }
  105. void Rights::serialize_into(Array<Bytes, 1> bytes) const
  106. {
  107. data.bytes().copy_to(bytes[0]);
  108. }
  109. void FDFlags::serialize_into(Array<Bytes, 1> bytes) const
  110. {
  111. ReadonlyBytes { &data, sizeof(data) }.copy_to(bytes[0]);
  112. }
  113. FDFlags FDFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
  114. {
  115. FDFlags flags { .data = 0 };
  116. bytes[0].copy_to(flags.data.bytes());
  117. return flags;
  118. }
  119. FSTFlags FSTFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
  120. {
  121. FSTFlags flags { .data = 0 };
  122. bytes[0].copy_to(flags.data.bytes());
  123. return flags;
  124. }
  125. OFlags OFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
  126. {
  127. OFlags flags { .data = 0 };
  128. bytes[0].copy_to(flags.data.bytes());
  129. return flags;
  130. }
  131. SDFlags SDFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
  132. {
  133. SDFlags flags { .data = 0 };
  134. bytes[0].copy_to(flags.data.bytes());
  135. return flags;
  136. }
  137. void FDStat::serialize_into(Array<Bytes, 1> bytes) const
  138. {
  139. auto data = bytes[0];
  140. ABI::serialize(fs_filetype, Array { data.slice(offsetof(FDStat, fs_filetype), sizeof(fs_filetype)) });
  141. ABI::serialize(fs_flags, Array { data.slice(offsetof(FDStat, fs_flags), sizeof(fs_flags)) });
  142. ABI::serialize(fs_rights_base, Array { data.slice(offsetof(FDStat, fs_rights_base), sizeof(fs_rights_base)) });
  143. ABI::serialize(fs_rights_inheriting, Array { data.slice(offsetof(FDStat, fs_rights_inheriting), sizeof(fs_rights_inheriting)) });
  144. }
  145. void PreStat::serialize_into(Array<Bytes, 1> bytes) const
  146. {
  147. auto data = bytes[0];
  148. ABI::serialize(type, Array { data.slice(0, sizeof(type)) });
  149. if (type == PreOpenType::Dir)
  150. ABI::serialize(dir, Array { data.slice(offsetof(PreStat, dir), sizeof(dir)) });
  151. else
  152. VERIFY_NOT_REACHED();
  153. }
  154. void PreStatDir::serialize_into(Array<Bytes, 1> bytes) const
  155. {
  156. ABI::serialize(pr_name_len, move(bytes));
  157. }
  158. void FileStat::serialize_into(Array<Bytes, 1> bytes) const
  159. {
  160. auto data = bytes[0];
  161. ABI::serialize(dev, Array { data.slice(0, sizeof(dev)) });
  162. ABI::serialize(ino, Array { data.slice(offsetof(FileStat, ino), sizeof(ino)) });
  163. ABI::serialize(filetype, Array { data.slice(offsetof(FileStat, filetype), sizeof(filetype)) });
  164. ABI::serialize(nlink, Array { data.slice(offsetof(FileStat, nlink), sizeof(nlink)) });
  165. ABI::serialize(size, Array { data.slice(offsetof(FileStat, size), sizeof(size)) });
  166. ABI::serialize(atim, Array { data.slice(offsetof(FileStat, atim), sizeof(atim)) });
  167. ABI::serialize(mtim, Array { data.slice(offsetof(FileStat, mtim), sizeof(mtim)) });
  168. ABI::serialize(ctim, Array { data.slice(offsetof(FileStat, ctim), sizeof(ctim)) });
  169. }
  170. RIFlags RIFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
  171. {
  172. RIFlags flags { .data = 0 };
  173. bytes[0].copy_to(flags.data.bytes());
  174. return flags;
  175. }
  176. LookupFlags LookupFlags::read_from(Array<ReadonlyBytes, 1> const& bytes)
  177. {
  178. LookupFlags flags { .data = 0 };
  179. bytes[0].copy_to(flags.data.bytes());
  180. return flags;
  181. }
  182. CIOVec CIOVec::read_from(Array<ReadonlyBytes, 1> const& bytes)
  183. {
  184. return CIOVec {
  185. .buf = ABI::deserialize<decltype(buf)>(Array { bytes[0].slice(offsetof(CIOVec, buf), sizeof(buf)) }),
  186. .buf_len = ABI::deserialize<decltype(buf_len)>(Array { bytes[0].slice(offsetof(CIOVec, buf_len), sizeof(buf_len)) }),
  187. };
  188. }
  189. IOVec IOVec::read_from(Array<ReadonlyBytes, 1> const& bytes)
  190. {
  191. return IOVec {
  192. .buf = ABI::deserialize<decltype(buf)>(Array { bytes[0].slice(offsetof(IOVec, buf), sizeof(buf)) }),
  193. .buf_len = ABI::deserialize<decltype(buf_len)>(Array { bytes[0].slice(offsetof(IOVec, buf_len), sizeof(buf_len)) }),
  194. };
  195. }
  196. template<typename T>
  197. ErrorOr<Vector<T>> copy_typed_array(Configuration& configuration, Pointer<T> source, Size count)
  198. {
  199. Vector<T> values;
  200. TRY(values.try_ensure_capacity(count));
  201. auto* memory = configuration.store().get(MemoryAddress { 0 });
  202. if (!memory)
  203. return Error::from_errno(ENOMEM);
  204. UnderlyingPointerType address = source.value();
  205. auto size = sizeof(T);
  206. if (memory->size() < address || memory->size() <= address + (size * count)) {
  207. return Error::from_errno(ENOBUFS);
  208. }
  209. for (Size i = 0; i < count; i += 1) {
  210. values.unchecked_append(T::read_from(Array { ReadonlyBytes { memory->data().bytes().slice(address, size) } }));
  211. address += size;
  212. }
  213. return values;
  214. }
  215. template<typename T>
  216. ErrorOr<void> copy_typed_value_to(Configuration& configuration, T const& value, Pointer<T> destination)
  217. {
  218. auto* memory = configuration.store().get(MemoryAddress { 0 });
  219. if (!memory)
  220. return Error::from_errno(ENOMEM);
  221. UnderlyingPointerType address = destination.value();
  222. auto size = sizeof(T);
  223. if (memory->size() < address || memory->size() <= address + size) {
  224. return Error::from_errno(ENOBUFS);
  225. }
  226. ABI::serialize(value, Array { Bytes { memory->data().bytes().slice(address, size) } });
  227. return {};
  228. }
  229. template<typename T>
  230. ErrorOr<Span<T>> slice_typed_memory(Configuration& configuration, Pointer<T> source, Size count)
  231. {
  232. auto* memory = configuration.store().get(MemoryAddress { 0 });
  233. if (!memory)
  234. return Error::from_errno(ENOMEM);
  235. auto address = source.value();
  236. auto size = sizeof(T);
  237. if (memory->size() < address || memory->size() <= address + (size * count))
  238. return Error::from_errno(ENOBUFS);
  239. auto untyped_slice = memory->data().bytes().slice(address, size * count);
  240. return Span<T>(untyped_slice.data(), count);
  241. }
  242. template<typename T>
  243. ErrorOr<Span<T const>> slice_typed_memory(Configuration& configuration, ConstPointer<T> source, Size count)
  244. {
  245. auto* memory = configuration.store().get(MemoryAddress { 0 });
  246. if (!memory)
  247. return Error::from_errno(ENOMEM);
  248. auto address = source.value();
  249. auto size = sizeof(T);
  250. if (memory->size() < address || memory->size() <= address + (size * count))
  251. return Error::from_errno(ENOBUFS);
  252. auto untyped_slice = memory->data().bytes().slice(address, size * count);
  253. return Span<T const>(untyped_slice.data(), count);
  254. }
  255. static ErrorOr<size_t> copy_string_including_terminating_null(Configuration& configuration, StringView string, Pointer<u8> target)
  256. {
  257. auto slice = TRY(slice_typed_memory(configuration, target, string.bytes().size() + 1));
  258. string.bytes().copy_to(slice);
  259. slice[string.bytes().size()] = 0;
  260. return slice.size();
  261. }
  262. static ErrorOr<size_t> copy_string_excluding_terminating_null(Configuration& configuration, StringView string, Pointer<u8> target, Size target_length)
  263. {
  264. auto byte_count = min(string.bytes().size(), target_length);
  265. auto slice = TRY(slice_typed_memory(configuration, target, byte_count));
  266. string.bytes().copy_trimmed_to(slice);
  267. return byte_count;
  268. }
  269. static Errno errno_value_from_errno(int value);
  270. Vector<AK::String> const& Implementation::arguments() const
  271. {
  272. if (!cache.cached_arguments.has_value()) {
  273. cache.cached_arguments.lazy_emplace([&] {
  274. if (provide_arguments)
  275. return provide_arguments();
  276. return Vector<AK::String> {};
  277. });
  278. }
  279. return *cache.cached_arguments;
  280. }
  281. Vector<AK::String> const& Implementation::environment() const
  282. {
  283. if (!cache.cached_environment.has_value()) {
  284. cache.cached_environment.lazy_emplace([&] {
  285. if (provide_environment)
  286. return provide_environment();
  287. return Vector<AK::String> {};
  288. });
  289. }
  290. return *cache.cached_environment;
  291. }
  292. Vector<Implementation::MappedPath> const& Implementation::preopened_directories() const
  293. {
  294. if (!cache.cached_preopened_directories.has_value()) {
  295. cache.cached_preopened_directories.lazy_emplace([&] {
  296. if (provide_preopened_directories)
  297. return provide_preopened_directories();
  298. return Vector<MappedPath> {};
  299. });
  300. }
  301. return *cache.cached_preopened_directories;
  302. }
  303. Implementation::Descriptor Implementation::map_fd(FD fd)
  304. {
  305. u32 fd_value = fd.value();
  306. if (auto* value = m_fd_map.find(fd_value))
  307. return value->downcast<Descriptor>();
  308. return UnmappedDescriptor(fd_value);
  309. }
  310. ErrorOr<Result<void>> Implementation::impl$args_get(Configuration& configuration, Pointer<Pointer<u8>> argv, Pointer<u8> argv_buf)
  311. {
  312. UnderlyingPointerType raw_argv_buffer = argv_buf.value();
  313. UnderlyingPointerType raw_argv = argv.value();
  314. for (auto& entry : arguments()) {
  315. auto ptr = Pointer<u8> { raw_argv_buffer };
  316. auto byte_count = TRY(copy_string_including_terminating_null(configuration, entry.bytes_as_string_view(), ptr));
  317. raw_argv_buffer += byte_count;
  318. TRY(copy_typed_value_to(configuration, ptr, Pointer<Pointer<u8>> { raw_argv }));
  319. raw_argv += sizeof(ptr);
  320. }
  321. return Result<void> {};
  322. }
  323. ErrorOr<Result<ArgsSizes>> Implementation::impl$args_sizes_get(Configuration&)
  324. {
  325. size_t count = 0;
  326. size_t total_size = 0;
  327. for (auto& entry : arguments()) {
  328. count += 1;
  329. total_size += entry.bytes().size() + 1; // 1 extra byte for terminating null.
  330. }
  331. return Result<ArgsSizes>(ArgsSizes {
  332. count,
  333. total_size,
  334. });
  335. }
  336. ErrorOr<Result<void>> Implementation::impl$environ_get(Configuration& configuration, Pointer<Pointer<u8>> environ, Pointer<u8> environ_buf)
  337. {
  338. UnderlyingPointerType raw_environ_buffer = environ_buf.value();
  339. UnderlyingPointerType raw_environ = environ.value();
  340. for (auto& entry : environment()) {
  341. auto ptr = Pointer<u8> { raw_environ_buffer };
  342. auto byte_count = TRY(copy_string_including_terminating_null(configuration, entry.bytes_as_string_view(), ptr));
  343. raw_environ_buffer += byte_count;
  344. TRY(copy_typed_value_to(configuration, ptr, Pointer<Pointer<u8>> { raw_environ }));
  345. raw_environ += sizeof(ptr);
  346. }
  347. return Result<void> {};
  348. }
  349. ErrorOr<Result<EnvironSizes>> Implementation::impl$environ_sizes_get(Configuration&)
  350. {
  351. size_t count = 0;
  352. size_t total_size = 0;
  353. for (auto& entry : environment()) {
  354. count += 1;
  355. total_size += entry.bytes().size() + 1; // 1 extra byte for terminating null.
  356. }
  357. return Result<EnvironSizes>(EnvironSizes {
  358. count,
  359. total_size,
  360. });
  361. }
  362. ErrorOr<Result<void>> Implementation::impl$proc_exit(Configuration&, ExitCode exit_code)
  363. {
  364. exit(exit_code);
  365. }
  366. ErrorOr<Result<void>> Implementation::impl$fd_close(Configuration&, FD fd)
  367. {
  368. return map_fd(fd).visit(
  369. [&](u32 fd) -> Result<void> {
  370. if (close(bit_cast<i32>(fd)) != 0)
  371. return errno_value_from_errno(errno);
  372. return {};
  373. },
  374. [&](PreopenedDirectoryDescriptor) -> Result<void> {
  375. return errno_value_from_errno(EISDIR);
  376. },
  377. [&](UnmappedDescriptor) -> Result<void> {
  378. return errno_value_from_errno(EBADF);
  379. });
  380. }
  381. ErrorOr<Result<Size>> Implementation::impl$fd_write(Configuration& configuration, FD fd, Pointer<CIOVec> iovs, Size iovs_len)
  382. {
  383. auto mapped_fd = map_fd(fd);
  384. if (!mapped_fd.has<u32>())
  385. return errno_value_from_errno(EBADF);
  386. u32 fd_value = mapped_fd.get<u32>();
  387. Size bytes_written = 0;
  388. for (auto& iovec : TRY(copy_typed_array(configuration, iovs, iovs_len))) {
  389. auto slice = TRY(slice_typed_memory(configuration, iovec.buf, iovec.buf_len));
  390. auto result = write(fd_value, slice.data(), slice.size());
  391. if (result < 0)
  392. return errno_value_from_errno(errno);
  393. bytes_written += static_cast<Size>(result);
  394. }
  395. return bytes_written;
  396. }
  397. ErrorOr<Result<PreStat>> Implementation::impl$fd_prestat_get(Configuration&, FD fd)
  398. {
  399. auto& paths = preopened_directories();
  400. return map_fd(fd).visit(
  401. [&](UnmappedDescriptor unmapped_fd) -> Result<PreStat> {
  402. // Map the new fd to the next available directory.
  403. if (m_first_unmapped_preopened_directory_index >= paths.size())
  404. return errno_value_from_errno(EBADF);
  405. auto index = m_first_unmapped_preopened_directory_index++;
  406. m_fd_map.insert(unmapped_fd.value(), PreopenedDirectoryDescriptor(index));
  407. return PreStat {
  408. .type = PreOpenType::Dir,
  409. .dir = PreStatDir {
  410. .pr_name_len = paths[index].mapped_path.string().bytes().size(),
  411. },
  412. };
  413. },
  414. [&](u32) -> Result<PreStat> {
  415. return errno_value_from_errno(EBADF);
  416. },
  417. [&](PreopenedDirectoryDescriptor fd) -> Result<PreStat> {
  418. return PreStat {
  419. .type = PreOpenType::Dir,
  420. .dir = PreStatDir {
  421. .pr_name_len = paths[fd.value()].mapped_path.string().bytes().size(),
  422. },
  423. };
  424. });
  425. }
  426. ErrorOr<Result<void>> Implementation::impl$fd_prestat_dir_name(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
  427. {
  428. auto mapped_fd = map_fd(fd);
  429. if (!mapped_fd.has<PreopenedDirectoryDescriptor>())
  430. return errno_value_from_errno(EBADF);
  431. auto& entry = preopened_directories()[mapped_fd.get<PreopenedDirectoryDescriptor>().value()];
  432. auto byte_count = TRY(copy_string_excluding_terminating_null(configuration, entry.mapped_path.string().view(), path, path_len));
  433. if (byte_count < path_len.value())
  434. return errno_value_from_errno(ENOBUFS);
  435. return Result<void> {};
  436. }
  437. ErrorOr<Result<FileStat>> Implementation::impl$path_filestat_get(Configuration& configuration, FD fd, LookupFlags flags, ConstPointer<u8> path, Size path_len)
  438. {
  439. auto dir_fd = AT_FDCWD;
  440. auto mapped_fd = map_fd(fd);
  441. mapped_fd.visit(
  442. [&](PreopenedDirectoryDescriptor descriptor) {
  443. auto& entry = preopened_directories()[descriptor.value()];
  444. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  445. ByteString path = entry.host_path.string();
  446. return open(path.characters(), O_DIRECTORY, 0);
  447. });
  448. entry.opened_fd = dir_fd;
  449. },
  450. [&](u32 fd) {
  451. dir_fd = fd;
  452. },
  453. [](UnmappedDescriptor) {});
  454. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  455. return errno_value_from_errno(errno);
  456. int options = 0;
  457. if (!flags.bits.symlink_follow)
  458. options |= AT_SYMLINK_NOFOLLOW;
  459. auto slice = TRY(slice_typed_memory(configuration, path, path_len));
  460. auto null_terminated_string = ByteString::copy(slice);
  461. struct stat stat_buf;
  462. if (fstatat(dir_fd, null_terminated_string.characters(), &stat_buf, options) < 0)
  463. return errno_value_from_errno(errno);
  464. constexpr auto file_type_of = [](struct stat const& buf) {
  465. if (S_ISDIR(buf.st_mode))
  466. return FileType::Directory;
  467. if (S_ISCHR(buf.st_mode))
  468. return FileType::CharacterDevice;
  469. if (S_ISBLK(buf.st_mode))
  470. return FileType::BlockDevice;
  471. if (S_ISREG(buf.st_mode))
  472. return FileType::RegularFile;
  473. if (S_ISFIFO(buf.st_mode))
  474. return FileType::Unknown; // FIXME: FileType::Pipe is currently not present in WASI (but it should be) so we use Unknown for now.
  475. if (S_ISLNK(buf.st_mode))
  476. return FileType::SymbolicLink;
  477. if (S_ISSOCK(buf.st_mode))
  478. return FileType::SocketStream;
  479. return FileType::Unknown;
  480. };
  481. return Result(FileStat {
  482. .dev = stat_buf.st_dev,
  483. .ino = stat_buf.st_ino,
  484. .filetype = file_type_of(stat_buf),
  485. .nlink = stat_buf.st_nlink,
  486. .size = stat_buf.st_size,
  487. .atim = stat_buf.st_atime,
  488. .mtim = stat_buf.st_mtime,
  489. .ctim = stat_buf.st_ctime,
  490. });
  491. }
  492. ErrorOr<Result<void>> Implementation::impl$path_create_directory(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
  493. {
  494. auto dir_fd = AT_FDCWD;
  495. auto mapped_fd = map_fd(fd);
  496. mapped_fd.visit(
  497. [&](PreopenedDirectoryDescriptor descriptor) {
  498. auto& entry = preopened_directories()[descriptor.value()];
  499. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  500. ByteString path = entry.host_path.string();
  501. return open(path.characters(), O_DIRECTORY, 0);
  502. });
  503. entry.opened_fd = dir_fd;
  504. },
  505. [&](u32 fd) {
  506. dir_fd = fd;
  507. },
  508. [](UnmappedDescriptor) {});
  509. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  510. return errno_value_from_errno(errno);
  511. auto slice = TRY(slice_typed_memory(configuration, path, path_len));
  512. auto null_terminated_string = ByteString::copy(slice);
  513. if (mkdirat(dir_fd, null_terminated_string.characters(), 0755) < 0)
  514. return errno_value_from_errno(errno);
  515. return Result<void> {};
  516. }
  517. ErrorOr<Result<FD>> Implementation::impl$path_open(Configuration& configuration, FD fd, LookupFlags lookup_flags, Pointer<u8> path, Size path_len, OFlags o_flags, Rights, Rights, FDFlags fd_flags)
  518. {
  519. auto dir_fd = AT_FDCWD;
  520. auto mapped_fd = map_fd(fd);
  521. mapped_fd.visit(
  522. [&](PreopenedDirectoryDescriptor descriptor) {
  523. auto& entry = preopened_directories()[descriptor.value()];
  524. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  525. ByteString path = entry.host_path.string();
  526. return open(path.characters(), O_DIRECTORY, 0);
  527. });
  528. entry.opened_fd = dir_fd;
  529. },
  530. [&](u32 fd) {
  531. dir_fd = fd;
  532. },
  533. [](UnmappedDescriptor) {});
  534. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  535. return errno_value_from_errno(errno);
  536. // FIXME: What should we do with dsync/rsync?
  537. int open_flags = 0;
  538. if (fd_flags.bits.append)
  539. open_flags |= O_APPEND;
  540. if (fd_flags.bits.nonblock)
  541. open_flags |= O_NONBLOCK;
  542. if (fd_flags.bits.sync)
  543. open_flags |= O_SYNC;
  544. if (o_flags.bits.trunc)
  545. open_flags |= O_TRUNC;
  546. if (o_flags.bits.creat)
  547. open_flags |= O_CREAT;
  548. if (o_flags.bits.directory)
  549. open_flags |= O_DIRECTORY;
  550. if (o_flags.bits.excl)
  551. open_flags |= O_EXCL;
  552. if (!lookup_flags.bits.symlink_follow)
  553. open_flags |= O_NOFOLLOW;
  554. auto path_data = TRY(slice_typed_memory(configuration, path, path_len));
  555. auto path_string = ByteString::copy(path_data);
  556. dbgln_if(WASI_FINE_GRAINED_DEBUG, "path_open: dir_fd={}, path={}, open_flags={}", dir_fd, path_string, open_flags);
  557. int opened_fd = openat(dir_fd, path_string.characters(), open_flags, 0644);
  558. if (opened_fd < 0)
  559. return errno_value_from_errno(errno);
  560. // FIXME: Implement Rights and RightsInheriting.
  561. m_fd_map.insert(opened_fd, static_cast<u32>(opened_fd));
  562. return FD(opened_fd);
  563. }
  564. ErrorOr<Result<Timestamp>> Implementation::impl$clock_time_get(Configuration&, ClockID id, Timestamp precision)
  565. {
  566. constexpr u64 nanoseconds_in_millisecond = 1000'000ull;
  567. constexpr u64 nanoseconds_in_second = 1000'000'000ull;
  568. clockid_t clock_id;
  569. switch (id) {
  570. case ClockID::Realtime:
  571. if (precision >= nanoseconds_in_millisecond)
  572. clock_id = CLOCK_REALTIME_COARSE;
  573. else
  574. clock_id = CLOCK_REALTIME;
  575. break;
  576. case ClockID::Monotonic:
  577. if (precision >= nanoseconds_in_millisecond)
  578. clock_id = CLOCK_MONOTONIC_COARSE;
  579. else
  580. clock_id = CLOCK_MONOTONIC;
  581. break;
  582. case ClockID::ProcessCPUTimeID:
  583. case ClockID::ThreadCPUTimeID:
  584. return Errno::NoSys;
  585. break;
  586. }
  587. struct timespec ts;
  588. if (clock_gettime(clock_id, &ts) < 0)
  589. return errno_value_from_errno(errno);
  590. return Result<Timestamp> { static_cast<u64>(ts.tv_sec) * nanoseconds_in_second + static_cast<u64>(ts.tv_nsec) };
  591. }
  592. ErrorOr<Result<FileStat>> Implementation::impl$fd_filestat_get(Configuration&, FD fd)
  593. {
  594. int resolved_fd = -1;
  595. auto mapped_fd = map_fd(fd);
  596. mapped_fd.visit(
  597. [&](PreopenedDirectoryDescriptor descriptor) {
  598. auto& entry = preopened_directories()[descriptor.value()];
  599. resolved_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  600. ByteString path = entry.host_path.string();
  601. return open(path.characters(), O_DIRECTORY, 0);
  602. });
  603. entry.opened_fd = resolved_fd;
  604. },
  605. [&](u32 fd) {
  606. resolved_fd = fd;
  607. },
  608. [](UnmappedDescriptor) {});
  609. if (resolved_fd < 0)
  610. return errno_value_from_errno(errno);
  611. struct stat stat_buf;
  612. if (fstat(resolved_fd, &stat_buf) < 0)
  613. return errno_value_from_errno(errno);
  614. constexpr auto file_type_of = [](struct stat const& buf) {
  615. if (S_ISDIR(buf.st_mode))
  616. return FileType::Directory;
  617. if (S_ISCHR(buf.st_mode))
  618. return FileType::CharacterDevice;
  619. if (S_ISBLK(buf.st_mode))
  620. return FileType::BlockDevice;
  621. if (S_ISREG(buf.st_mode))
  622. return FileType::RegularFile;
  623. if (S_ISFIFO(buf.st_mode))
  624. return FileType::Unknown; // no Pipe? :yakfused:
  625. if (S_ISLNK(buf.st_mode))
  626. return FileType::SymbolicLink;
  627. if (S_ISSOCK(buf.st_mode))
  628. return FileType::SocketDGram; // :shrug:
  629. return FileType::Unknown;
  630. };
  631. return Result(FileStat {
  632. .dev = stat_buf.st_dev,
  633. .ino = stat_buf.st_ino,
  634. .filetype = file_type_of(stat_buf),
  635. .nlink = stat_buf.st_nlink,
  636. .size = stat_buf.st_size,
  637. .atim = stat_buf.st_atime,
  638. .mtim = stat_buf.st_mtime,
  639. .ctim = stat_buf.st_ctime,
  640. });
  641. }
  642. ErrorOr<Result<void>> Implementation::impl$random_get(Configuration& configuration, Pointer<u8> buf, Size buf_len)
  643. {
  644. auto buffer_slice = TRY(slice_typed_memory(configuration, buf, buf_len));
  645. fill_with_random(buffer_slice);
  646. return Result<void> {};
  647. }
  648. ErrorOr<Result<Size>> Implementation::impl$fd_read(Configuration& configuration, FD fd, Pointer<IOVec> iovs, Size iovs_len)
  649. {
  650. auto mapped_fd = map_fd(fd);
  651. if (!mapped_fd.has<u32>())
  652. return errno_value_from_errno(EBADF);
  653. u32 fd_value = mapped_fd.get<u32>();
  654. Size bytes_read = 0;
  655. for (auto& iovec : TRY(copy_typed_array(configuration, iovs, iovs_len))) {
  656. auto slice = TRY(slice_typed_memory(configuration, iovec.buf, iovec.buf_len));
  657. auto result = read(fd_value, slice.data(), slice.size());
  658. if (result < 0)
  659. return errno_value_from_errno(errno);
  660. bytes_read += static_cast<Size>(result);
  661. }
  662. return bytes_read;
  663. }
  664. #pragma GCC diagnostic push
  665. #pragma GCC diagnostic ignored "-Wunused-parameter"
  666. ErrorOr<Result<Timestamp>> Implementation::impl$clock_res_get(Configuration&, ClockID id)
  667. {
  668. return Errno::NoSys;
  669. }
  670. ErrorOr<Result<void>> Implementation::impl$fd_advise(Configuration&, FD, FileSize offset, FileSize len, Advice) { return Errno::NoSys; }
  671. ErrorOr<Result<void>> Implementation::impl$fd_allocate(Configuration&, FD, FileSize offset, FileSize len) { return Errno::NoSys; }
  672. ErrorOr<Result<void>> Implementation::impl$fd_datasync(Configuration&, FD) { return Errno::NoSys; }
  673. ErrorOr<Result<FDStat>> Implementation::impl$fd_fdstat_get(Configuration&, FD) { return Errno::NoSys; }
  674. ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_flags(Configuration&, FD, FDFlags) { return Errno::NoSys; }
  675. ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_rights(Configuration&, FD, Rights fs_rights_base, Rights fs_rights_inheriting) { return Errno::NoSys; }
  676. ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_size(Configuration&, FD, FileSize) { return Errno::NoSys; }
  677. ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_times(Configuration&, FD, Timestamp atim, Timestamp mtim, FSTFlags) { return Errno::NoSys; }
  678. ErrorOr<Result<Size>> Implementation::impl$fd_pread(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
  679. ErrorOr<Result<Size>> Implementation::impl$fd_pwrite(Configuration&, FD, Pointer<CIOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
  680. ErrorOr<Result<Size>> Implementation::impl$fd_readdir(Configuration&, FD, Pointer<u8> buf, Size buf_len, DirCookie cookie) { return Errno::NoSys; }
  681. ErrorOr<Result<void>> Implementation::impl$fd_renumber(Configuration&, FD from, FD to) { return Errno::NoSys; }
  682. ErrorOr<Result<FileSize>> Implementation::impl$fd_seek(Configuration&, FD, FileDelta offset, Whence whence) { return Errno::NoSys; }
  683. ErrorOr<Result<void>> Implementation::impl$fd_sync(Configuration&, FD) { return Errno::NoSys; }
  684. ErrorOr<Result<FileSize>> Implementation::impl$fd_tell(Configuration&, FD) { return Errno::NoSys; }
  685. ErrorOr<Result<void>> Implementation::impl$path_filestat_set_times(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, Timestamp atim, Timestamp mtim, FSTFlags) { return Errno::NoSys; }
  686. ErrorOr<Result<void>> Implementation::impl$path_link(Configuration&, FD, LookupFlags, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len) { return Errno::NoSys; }
  687. ErrorOr<Result<Size>> Implementation::impl$path_readlink(Configuration&, FD, LookupFlags, Pointer<u8> path, Size path_len, Pointer<u8> buf, Size buf_len) { return Errno::NoSys; }
  688. ErrorOr<Result<void>> Implementation::impl$path_remove_directory(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
  689. ErrorOr<Result<void>> Implementation::impl$path_rename(Configuration&, FD, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len) { return Errno::NoSys; }
  690. ErrorOr<Result<void>> Implementation::impl$path_symlink(Configuration&, Pointer<u8> old_path, Size old_path_len, FD, Pointer<u8> new_path, Size new_path_len) { return Errno::NoSys; }
  691. ErrorOr<Result<void>> Implementation::impl$path_unlink_file(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
  692. ErrorOr<Result<Size>> Implementation::impl$poll_oneoff(Configuration&, ConstPointer<Subscription> in, Pointer<Event> out, Size nsubscriptions) { return Errno::NoSys; }
  693. ErrorOr<Result<void>> Implementation::impl$proc_raise(Configuration&, Signal) { return Errno::NoSys; }
  694. ErrorOr<Result<void>> Implementation::impl$sched_yield(Configuration&) { return Errno::NoSys; }
  695. ErrorOr<Result<FD>> Implementation::impl$sock_accept(Configuration&, FD fd, FDFlags fd_flags) { return Errno::NoSys; }
  696. ErrorOr<Result<SockRecvResult>> Implementation::impl$sock_recv(Configuration&, FD fd, Pointer<IOVec> ri_data, Size ri_data_len, RIFlags ri_flags) { return Errno::NoSys; }
  697. ErrorOr<Result<Size>> Implementation::impl$sock_send(Configuration&, FD fd, Pointer<CIOVec> si_data, Size si_data_len, SIFlags si_flags) { return Errno::NoSys; }
  698. ErrorOr<Result<void>> Implementation::impl$sock_shutdown(Configuration&, FD fd, SDFlags how) { return Errno::NoSys; }
  699. #pragma GCC diagnostic pop
  700. template<size_t N>
  701. static Array<Bytes, N> address_spans(Span<Value> values, Configuration& configuration)
  702. {
  703. Array<Bytes, N> result;
  704. auto memory = configuration.store().get(MemoryAddress { 0 })->data().span();
  705. for (size_t i = 0; i < N; ++i)
  706. result[i] = memory.slice(*values[i].to<i32>());
  707. return result;
  708. }
  709. #define ENUMERATE_FUNCTION_NAMES(M) \
  710. M(args_get) \
  711. M(args_sizes_get) \
  712. M(environ_get) \
  713. M(environ_sizes_get) \
  714. M(clock_res_get) \
  715. M(clock_time_get) \
  716. M(fd_advise) \
  717. M(fd_allocate) \
  718. M(fd_close) \
  719. M(fd_datasync) \
  720. M(fd_fdstat_get) \
  721. M(fd_fdstat_set_flags) \
  722. M(fd_fdstat_set_rights) \
  723. M(fd_filestat_get) \
  724. M(fd_filestat_set_size) \
  725. M(fd_filestat_set_times) \
  726. M(fd_pread) \
  727. M(fd_prestat_get) \
  728. M(fd_prestat_dir_name) \
  729. M(fd_pwrite) \
  730. M(fd_read) \
  731. M(fd_readdir) \
  732. M(fd_renumber) \
  733. M(fd_seek) \
  734. M(fd_sync) \
  735. M(fd_tell) \
  736. M(fd_write) \
  737. M(path_create_directory) \
  738. M(path_filestat_get) \
  739. M(path_filestat_set_times) \
  740. M(path_link) \
  741. M(path_open) \
  742. M(path_readlink) \
  743. M(path_remove_directory) \
  744. M(path_rename) \
  745. M(path_symlink) \
  746. M(path_unlink_file) \
  747. M(poll_oneoff) \
  748. M(proc_exit) \
  749. M(proc_raise) \
  750. M(sched_yield) \
  751. M(random_get) \
  752. M(sock_accept) \
  753. M(sock_recv) \
  754. M(sock_send) \
  755. M(sock_shutdown)
  756. struct Names {
  757. #define NAME(x) FlyString x;
  758. ENUMERATE_FUNCTION_NAMES(NAME)
  759. #undef NAME
  760. static ErrorOr<Names> construct()
  761. {
  762. return Names {
  763. #define NAME(x) .x = TRY(FlyString::from_utf8(#x##sv)),
  764. ENUMERATE_FUNCTION_NAMES(NAME)
  765. #undef NAME
  766. };
  767. }
  768. };
  769. ErrorOr<HostFunction> Implementation::function_by_name(StringView name)
  770. {
  771. auto name_for_comparison = TRY(FlyString::from_utf8(name));
  772. static auto names = TRY(Names::construct());
  773. #define IMPL(x) \
  774. if (name_for_comparison == names.x) \
  775. return invocation_of<&Implementation::impl$##x>(#x##sv);
  776. ENUMERATE_FUNCTION_NAMES(IMPL)
  777. #undef IMPL
  778. return Error::from_string_literal("No such host function");
  779. }
  780. namespace ABI {
  781. template<typename T>
  782. auto CompatibleValueType = IsOneOf<T, i8, i16, i32>
  783. ? Wasm::ValueType(Wasm::ValueType::I32)
  784. : Wasm::ValueType(Wasm::ValueType::I64);
  785. template<typename R, typename... Args, ErrorOr<Result<R>> (Implementation::*impl)(Configuration&, Args...)>
  786. struct InvocationOf<impl> {
  787. HostFunction operator()(Implementation& self, StringView function_name)
  788. {
  789. Vector<ValueType> arguments_types { CompatibleValueType<typename ABI::ToCompatibleValue<Args>::Type>... };
  790. if constexpr (!IsVoid<R>) {
  791. if constexpr (requires { declval<typename R::SerializationComponents>(); }) {
  792. for_each_type<typename R::SerializationComponents>([&]<typename T>(TypeWrapper<T>) {
  793. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<T>>::Type>);
  794. });
  795. } else {
  796. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<R>>::Type>);
  797. }
  798. }
  799. return HostFunction(
  800. [&self, function_name](Configuration& configuration, Vector<Value>& arguments) -> Wasm::Result {
  801. Tuple args = [&]<typename... Ts, auto... Is>(IndexSequence<Is...>) {
  802. return Tuple { ABI::deserialize(ABI::to_compatible_value<Ts>(arguments[Is]))... };
  803. }.template operator()<Args...>(MakeIndexSequence<sizeof...(Args)>());
  804. auto result = args.apply_as_args([&](auto&&... impl_args) { return (self.*impl)(configuration, impl_args...); });
  805. dbgln_if(WASI_DEBUG, "WASI: {}({}) = {}", function_name, arguments, result);
  806. if (result.is_error())
  807. return Wasm::Trap { ByteString::formatted("Invalid call to {}() = {}", function_name, result.error()) };
  808. auto value = result.release_value();
  809. if (value.is_error())
  810. return Wasm::Result { Vector { Value { ValueType(ValueType::I32), static_cast<u64>(to_underlying(value.error().value())) } } };
  811. if constexpr (!IsVoid<R>) {
  812. // Return values are passed as pointers, after the arguments
  813. if constexpr (requires { &R::serialize_into; }) {
  814. constexpr auto ResultCount = []<auto N>(void (R::*)(Array<Bytes, N>) const) { return N; }(&R::serialize_into);
  815. ABI::serialize(*value.result(), address_spans<ResultCount>(arguments.span().slice(sizeof...(Args)), configuration));
  816. } else {
  817. ABI::serialize(*value.result(), address_spans<1>(arguments.span().slice(sizeof...(Args)), configuration));
  818. }
  819. }
  820. // Return value is errno, we have nothing to return.
  821. return Wasm::Result { Vector<Value> { Value(ValueType(ValueType::I32), 0ull) } };
  822. },
  823. FunctionType {
  824. move(arguments_types),
  825. { ValueType(ValueType::I32) },
  826. });
  827. }
  828. };
  829. };
  830. Errno errno_value_from_errno(int value)
  831. {
  832. switch (value) {
  833. #ifdef ESUCCESS
  834. case ESUCCESS:
  835. return Errno::Success;
  836. #endif
  837. case E2BIG:
  838. return Errno::TooBig;
  839. case EACCES:
  840. return Errno::Access;
  841. case EADDRINUSE:
  842. return Errno::AddressInUse;
  843. case EADDRNOTAVAIL:
  844. return Errno::AddressNotAvailable;
  845. case EAFNOSUPPORT:
  846. return Errno::AFNotSupported;
  847. case EAGAIN:
  848. return Errno::Again;
  849. case EALREADY:
  850. return Errno::Already;
  851. case EBADF:
  852. return Errno::BadF;
  853. case EBUSY:
  854. return Errno::Busy;
  855. case ECANCELED:
  856. return Errno::Canceled;
  857. case ECHILD:
  858. return Errno::Child;
  859. case ECONNABORTED:
  860. return Errno::ConnectionAborted;
  861. case ECONNREFUSED:
  862. return Errno::ConnectionRefused;
  863. case ECONNRESET:
  864. return Errno::ConnectionReset;
  865. case EDEADLK:
  866. return Errno::Deadlock;
  867. case EDESTADDRREQ:
  868. return Errno::DestinationAddressRequired;
  869. case EDOM:
  870. return Errno::Domain;
  871. case EEXIST:
  872. return Errno::Exist;
  873. case EFAULT:
  874. return Errno::Fault;
  875. case EFBIG:
  876. return Errno::FBig;
  877. case EHOSTUNREACH:
  878. return Errno::HostUnreachable;
  879. case EILSEQ:
  880. return Errno::IllegalSequence;
  881. case EINPROGRESS:
  882. return Errno::InProgress;
  883. case EINTR:
  884. return Errno::Interrupted;
  885. case EINVAL:
  886. return Errno::Invalid;
  887. case EIO:
  888. return Errno::IO;
  889. case EISCONN:
  890. return Errno::IsConnected;
  891. case EISDIR:
  892. return Errno::IsDirectory;
  893. case ELOOP:
  894. return Errno::Loop;
  895. case EMFILE:
  896. return Errno::MFile;
  897. case EMLINK:
  898. return Errno::MLink;
  899. case EMSGSIZE:
  900. return Errno::MessageSize;
  901. case ENAMETOOLONG:
  902. return Errno::NameTooLong;
  903. case ENETDOWN:
  904. return Errno::NetworkDown;
  905. case ENETRESET:
  906. return Errno::NetworkReset;
  907. case ENETUNREACH:
  908. return Errno::NetworkUnreachable;
  909. case ENFILE:
  910. return Errno::NFile;
  911. case ENOBUFS:
  912. return Errno::NoBufferSpace;
  913. case ENODEV:
  914. return Errno::NoDevice;
  915. case ENOENT:
  916. return Errno::NoEntry;
  917. case ENOEXEC:
  918. return Errno::NoExec;
  919. case ENOLCK:
  920. return Errno::NoLock;
  921. case ENOMEM:
  922. return Errno::NoMemory;
  923. case ENOPROTOOPT:
  924. return Errno::NoProtocolOption;
  925. case ENOSPC:
  926. return Errno::NoSpace;
  927. case ENOSYS:
  928. return Errno::NoSys;
  929. case ENOTCONN:
  930. return Errno::NotConnected;
  931. case ENOTDIR:
  932. return Errno::NotDirectory;
  933. case ENOTEMPTY:
  934. return Errno::NotEmpty;
  935. case ENOTRECOVERABLE:
  936. return Errno::NotRecoverable;
  937. case ENOTSOCK:
  938. return Errno::NotSocket;
  939. case ENOTSUP:
  940. return Errno::NotSupported;
  941. case ENOTTY:
  942. return Errno::NoTTY;
  943. case ENXIO:
  944. return Errno::NXIO;
  945. case EOVERFLOW:
  946. return Errno::Overflow;
  947. case EPERM:
  948. return Errno::Permission;
  949. case EPIPE:
  950. return Errno::Pipe;
  951. case EPROTO:
  952. return Errno::Protocol;
  953. case EPROTONOSUPPORT:
  954. return Errno::ProtocolNotSupported;
  955. case EPROTOTYPE:
  956. return Errno::ProtocolType;
  957. case ERANGE:
  958. return Errno::Range;
  959. case ESPIPE:
  960. return Errno::SPipe;
  961. case ESRCH:
  962. return Errno::SRCH;
  963. case ESTALE:
  964. return Errno::Stale;
  965. case ETIMEDOUT:
  966. return Errno::TimedOut;
  967. case ETXTBSY:
  968. return Errno::TextBusy;
  969. case EXDEV:
  970. return Errno::XDev;
  971. default:
  972. return Errno::Invalid;
  973. }
  974. }
  975. }
  976. namespace AK {
  977. template<>
  978. struct Formatter<Wasm::Value> : AK::Formatter<FormatString> {
  979. ErrorOr<void> format(FormatBuilder& builder, Wasm::Value const& value)
  980. {
  981. return value.value().visit(
  982. [&](Wasm::Reference const&) {
  983. return Formatter<FormatString>::format(builder, "({}) &r"sv, Wasm::ValueType::kind_name(value.type().kind()));
  984. },
  985. [&](auto const& v) {
  986. return Formatter<FormatString>::format(builder, "({}) {}"sv, Wasm::ValueType::kind_name(value.type().kind()), v);
  987. });
  988. }
  989. };
  990. template<>
  991. struct Formatter<Wasm::Wasi::Errno> : AK::Formatter<FormatString> {
  992. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Errno const& value)
  993. {
  994. return Formatter<FormatString>::format(builder, "{}"sv, to_underlying(value));
  995. }
  996. };
  997. template<>
  998. struct Formatter<Empty> : AK::Formatter<FormatString> {
  999. ErrorOr<void> format(FormatBuilder&, Empty)
  1000. {
  1001. return {};
  1002. }
  1003. };
  1004. template<typename T>
  1005. struct Formatter<Wasm::Wasi::Result<T>> : AK::Formatter<FormatString> {
  1006. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Result<T> const& value)
  1007. {
  1008. if (value.is_error())
  1009. return Formatter<FormatString>::format(builder, "Error({})"sv, *value.error());
  1010. return Formatter<FormatString>::format(builder, "Ok({})"sv, *value.result());
  1011. }
  1012. };
  1013. template<OneOf<Wasm::Wasi::ArgsSizes, Wasm::Wasi::EnvironSizes> T>
  1014. struct Formatter<T> : AK::Formatter<FormatString> {
  1015. ErrorOr<void> format(FormatBuilder& builder, T const& value)
  1016. {
  1017. return Formatter<FormatString>::format(builder, "size={}, count={}"sv, value.size, value.count);
  1018. }
  1019. };
  1020. template<>
  1021. struct Formatter<Wasm::Wasi::FDStat> : AK::Formatter<FormatString> {
  1022. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FDStat const&)
  1023. {
  1024. return Formatter<FormatString>::format(builder, "(rights)"sv);
  1025. }
  1026. };
  1027. template<>
  1028. struct Formatter<Wasm::Wasi::FileStat> : AK::Formatter<FormatString> {
  1029. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FileStat const& value)
  1030. {
  1031. return Formatter<FormatString>::format(builder, "dev={}, ino={}, ft={}, nlink={}, size={}, atim={}, mtim={}, ctim={}"sv,
  1032. value.dev, value.ino, to_underlying(value.filetype), value.nlink, value.size, value.atim, value.mtim, value.ctim);
  1033. }
  1034. };
  1035. template<>
  1036. struct Formatter<Wasm::Wasi::PreStat> : AK::Formatter<FormatString> {
  1037. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::PreStat const& value)
  1038. {
  1039. return Formatter<FormatString>::format(builder, "length={}"sv, value.dir.pr_name_len);
  1040. }
  1041. };
  1042. template<>
  1043. struct Formatter<Wasm::Wasi::SockRecvResult> : AK::Formatter<FormatString> {
  1044. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::SockRecvResult const& value)
  1045. {
  1046. return Formatter<FormatString>::format(builder, "size={}"sv, value.size);
  1047. }
  1048. };
  1049. }