Wasi.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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(tag, Array { data.slice(0, sizeof(tag)) });
  149. if (tag == 0)
  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. .tag = 0,
  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. .tag = 0,
  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. if (mapped_fd.has<PreopenedDirectoryDescriptor>()) {
  442. auto& entry = preopened_directories()[mapped_fd.get<PreopenedDirectoryDescriptor>().value()];
  443. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  444. DeprecatedString path = entry.host_path.string();
  445. return open(path.characters(), O_DIRECTORY, 0755);
  446. });
  447. entry.opened_fd = dir_fd;
  448. }
  449. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  450. return errno_value_from_errno(errno);
  451. int options = 0;
  452. if (!flags.bits.symlink_follow)
  453. options |= AT_SYMLINK_NOFOLLOW;
  454. auto slice = TRY(slice_typed_memory(configuration, path, path_len));
  455. auto null_terminated_string = DeprecatedString::copy(slice);
  456. struct stat stat_buf;
  457. if (fstatat(dir_fd, null_terminated_string.characters(), &stat_buf, options) < 0)
  458. return errno_value_from_errno(errno);
  459. constexpr auto file_type_of = [](struct stat const& buf) {
  460. if (S_ISDIR(buf.st_mode))
  461. return FileType::Directory;
  462. if (S_ISCHR(buf.st_mode))
  463. return FileType::CharacterDevice;
  464. if (S_ISBLK(buf.st_mode))
  465. return FileType::BlockDevice;
  466. if (S_ISREG(buf.st_mode))
  467. return FileType::RegularFile;
  468. if (S_ISFIFO(buf.st_mode))
  469. return FileType::Unknown; // no Pipe? :yakfused:
  470. if (S_ISLNK(buf.st_mode))
  471. return FileType::SymbolicLink;
  472. if (S_ISSOCK(buf.st_mode))
  473. return FileType::SocketDGram; // :shrug:
  474. return FileType::Unknown;
  475. };
  476. return Result(FileStat {
  477. .dev = stat_buf.st_dev,
  478. .ino = stat_buf.st_ino,
  479. .filetype = file_type_of(stat_buf),
  480. .nlink = stat_buf.st_nlink,
  481. .size = stat_buf.st_size,
  482. .atim = stat_buf.st_atime,
  483. .mtim = stat_buf.st_mtime,
  484. .ctim = stat_buf.st_ctime,
  485. });
  486. }
  487. ErrorOr<Result<void>> Implementation::impl$path_create_directory(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
  488. {
  489. auto dir_fd = AT_FDCWD;
  490. auto mapped_fd = map_fd(fd);
  491. if (mapped_fd.has<PreopenedDirectoryDescriptor>()) {
  492. auto& entry = preopened_directories()[mapped_fd.get<PreopenedDirectoryDescriptor>().value()];
  493. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  494. DeprecatedString path = entry.host_path.string();
  495. return open(path.characters(), O_DIRECTORY, 0755);
  496. });
  497. entry.opened_fd = dir_fd;
  498. }
  499. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  500. return errno_value_from_errno(errno);
  501. auto slice = TRY(slice_typed_memory(configuration, path, path_len));
  502. auto null_terminated_string = DeprecatedString::copy(slice);
  503. if (mkdirat(dir_fd, null_terminated_string.characters(), 0755) < 0)
  504. return errno_value_from_errno(errno);
  505. return Result<void> {};
  506. }
  507. 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)
  508. {
  509. auto dir_fd = AT_FDCWD;
  510. auto mapped_fd = map_fd(fd);
  511. if (mapped_fd.has<PreopenedDirectoryDescriptor>()) {
  512. auto& entry = preopened_directories()[mapped_fd.get<PreopenedDirectoryDescriptor>().value()];
  513. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  514. DeprecatedString path = entry.host_path.string();
  515. return open(path.characters(), O_DIRECTORY, 0755);
  516. });
  517. entry.opened_fd = dir_fd;
  518. }
  519. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  520. return errno_value_from_errno(errno);
  521. // FIXME: What should we do with dsync/rsync?
  522. int open_flags = 0;
  523. if (fd_flags.bits.append)
  524. open_flags |= O_APPEND;
  525. if (fd_flags.bits.nonblock)
  526. open_flags |= O_NONBLOCK;
  527. if (fd_flags.bits.sync)
  528. open_flags |= O_SYNC;
  529. if (o_flags.bits.trunc)
  530. open_flags |= O_TRUNC;
  531. if (o_flags.bits.creat)
  532. open_flags |= O_CREAT;
  533. if (o_flags.bits.directory)
  534. open_flags |= O_DIRECTORY;
  535. if (o_flags.bits.excl)
  536. open_flags |= O_EXCL;
  537. if (!lookup_flags.bits.symlink_follow)
  538. open_flags |= O_NOFOLLOW;
  539. auto path_data = TRY(slice_typed_memory(configuration, path, path_len));
  540. auto path_string = DeprecatedString::copy(path_data);
  541. dbgln_if(WASI_FINE_GRAINED_DEBUG, "path_open: dir_fd={}, path={}, open_flags={}", dir_fd, path_string, open_flags);
  542. int opened_fd = openat(dir_fd, path_string.characters(), open_flags, 0644);
  543. if (opened_fd < 0)
  544. return errno_value_from_errno(errno);
  545. // FIXME: Implement Rights and RightsInheriting.
  546. m_fd_map.insert(opened_fd, static_cast<u32>(opened_fd));
  547. return FD(opened_fd);
  548. }
  549. ErrorOr<Result<Timestamp>> Implementation::impl$clock_time_get(Configuration&, ClockID id, Timestamp precision)
  550. {
  551. constexpr u64 nanoseconds_in_millisecond = 1000'000ull;
  552. constexpr u64 nanoseconds_in_second = 1000'000'000ull;
  553. clockid_t clock_id;
  554. switch (id) {
  555. case ClockID::Realtime:
  556. if (precision >= nanoseconds_in_millisecond)
  557. clock_id = CLOCK_REALTIME_COARSE;
  558. else
  559. clock_id = CLOCK_REALTIME;
  560. break;
  561. case ClockID::Monotonic:
  562. if (precision >= nanoseconds_in_millisecond)
  563. clock_id = CLOCK_MONOTONIC_COARSE;
  564. else
  565. clock_id = CLOCK_MONOTONIC;
  566. break;
  567. case ClockID::ProcessCPUTimeID:
  568. case ClockID::ThreadCPUTimeID:
  569. return Errno::NoSys;
  570. break;
  571. }
  572. struct timespec ts;
  573. if (clock_gettime(clock_id, &ts) < 0)
  574. return errno_value_from_errno(errno);
  575. return Result<Timestamp> { static_cast<u64>(ts.tv_sec) * nanoseconds_in_second + static_cast<u64>(ts.tv_nsec) };
  576. }
  577. ErrorOr<Result<void>> Implementation::impl$random_get(Configuration& configuration, Pointer<u8> buf, Size buf_len)
  578. {
  579. auto buffer_slice = TRY(slice_typed_memory(configuration, buf, buf_len));
  580. fill_with_random(buffer_slice);
  581. return Result<void> {};
  582. }
  583. #pragma GCC diagnostic push
  584. #pragma GCC diagnostic ignored "-Wunused-parameter"
  585. ErrorOr<Result<Timestamp>> Implementation::impl$clock_res_get(Configuration&, ClockID id)
  586. {
  587. return Errno::NoSys;
  588. }
  589. ErrorOr<Result<void>> Implementation::impl$fd_advise(Configuration&, FD, FileSize offset, FileSize len, Advice) { return Errno::NoSys; }
  590. ErrorOr<Result<void>> Implementation::impl$fd_allocate(Configuration&, FD, FileSize offset, FileSize len) { return Errno::NoSys; }
  591. ErrorOr<Result<void>> Implementation::impl$fd_datasync(Configuration&, FD) { return Errno::NoSys; }
  592. ErrorOr<Result<FDStat>> Implementation::impl$fd_fdstat_get(Configuration&, FD) { return Errno::NoSys; }
  593. ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_flags(Configuration&, FD, FDFlags) { return Errno::NoSys; }
  594. ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_rights(Configuration&, FD, Rights fs_rights_base, Rights fs_rights_inheriting) { return Errno::NoSys; }
  595. ErrorOr<Result<FileStat>> Implementation::impl$fd_filestat_get(Configuration&, FD) { return Errno::NoSys; }
  596. ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_size(Configuration&, FD, FileSize) { return Errno::NoSys; }
  597. ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_times(Configuration&, FD, Timestamp atim, Timestamp mtim, FSTFlags) { return Errno::NoSys; }
  598. ErrorOr<Result<Size>> Implementation::impl$fd_pread(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
  599. ErrorOr<Result<Size>> Implementation::impl$fd_pwrite(Configuration&, FD, Pointer<CIOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
  600. ErrorOr<Result<Size>> Implementation::impl$fd_read(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len) { return Errno::NoSys; }
  601. ErrorOr<Result<Size>> Implementation::impl$fd_readdir(Configuration&, FD, Pointer<u8> buf, Size buf_len, DirCookie cookie) { return Errno::NoSys; }
  602. ErrorOr<Result<void>> Implementation::impl$fd_renumber(Configuration&, FD from, FD to) { return Errno::NoSys; }
  603. ErrorOr<Result<FileSize>> Implementation::impl$fd_seek(Configuration&, FD, FileDelta offset, Whence whence) { return Errno::NoSys; }
  604. ErrorOr<Result<void>> Implementation::impl$fd_sync(Configuration&, FD) { return Errno::NoSys; }
  605. ErrorOr<Result<FileSize>> Implementation::impl$fd_tell(Configuration&, FD) { return Errno::NoSys; }
  606. 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; }
  607. 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; }
  608. 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; }
  609. ErrorOr<Result<void>> Implementation::impl$path_remove_directory(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
  610. 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; }
  611. 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; }
  612. ErrorOr<Result<void>> Implementation::impl$path_unlink_file(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
  613. ErrorOr<Result<Size>> Implementation::impl$poll_oneoff(Configuration&, ConstPointer<Subscription> in, Pointer<Event> out, Size nsubscriptions) { return Errno::NoSys; }
  614. ErrorOr<Result<void>> Implementation::impl$proc_raise(Configuration&, Signal) { return Errno::NoSys; }
  615. ErrorOr<Result<void>> Implementation::impl$sched_yield(Configuration&) { return Errno::NoSys; }
  616. ErrorOr<Result<FD>> Implementation::impl$sock_accept(Configuration&, FD fd, FDFlags fd_flags) { return Errno::NoSys; }
  617. ErrorOr<Result<SockRecvResult>> Implementation::impl$sock_recv(Configuration&, FD fd, Pointer<IOVec> ri_data, Size ri_data_len, RIFlags ri_flags) { return Errno::NoSys; }
  618. ErrorOr<Result<Size>> Implementation::impl$sock_send(Configuration&, FD fd, Pointer<CIOVec> si_data, Size si_data_len, SIFlags si_flags) { return Errno::NoSys; }
  619. ErrorOr<Result<void>> Implementation::impl$sock_shutdown(Configuration&, FD fd, SDFlags how) { return Errno::NoSys; }
  620. #pragma GCC diagnostic pop
  621. template<size_t N>
  622. static Array<Bytes, N> address_spans(Span<Value> values, Configuration& configuration)
  623. {
  624. Array<Bytes, N> result;
  625. auto memory = configuration.store().get(MemoryAddress { 0 })->data().span();
  626. for (size_t i = 0; i < N; ++i)
  627. result[i] = memory.slice(*values[i].to<i32>());
  628. return result;
  629. }
  630. #define ENUMERATE_FUNCTION_NAMES(M) \
  631. M(args_get) \
  632. M(args_sizes_get) \
  633. M(environ_get) \
  634. M(environ_sizes_get) \
  635. M(clock_res_get) \
  636. M(clock_time_get) \
  637. M(fd_advise) \
  638. M(fd_allocate) \
  639. M(fd_close) \
  640. M(fd_datasync) \
  641. M(fd_fdstat_get) \
  642. M(fd_fdstat_set_flags) \
  643. M(fd_fdstat_set_rights) \
  644. M(fd_filestat_get) \
  645. M(fd_filestat_set_size) \
  646. M(fd_filestat_set_times) \
  647. M(fd_pread) \
  648. M(fd_prestat_get) \
  649. M(fd_prestat_dir_name) \
  650. M(fd_pwrite) \
  651. M(fd_read) \
  652. M(fd_readdir) \
  653. M(fd_renumber) \
  654. M(fd_seek) \
  655. M(fd_sync) \
  656. M(fd_tell) \
  657. M(fd_write) \
  658. M(path_create_directory) \
  659. M(path_filestat_get) \
  660. M(path_filestat_set_times) \
  661. M(path_link) \
  662. M(path_open) \
  663. M(path_readlink) \
  664. M(path_remove_directory) \
  665. M(path_rename) \
  666. M(path_symlink) \
  667. M(path_unlink_file) \
  668. M(poll_oneoff) \
  669. M(proc_exit) \
  670. M(proc_raise) \
  671. M(sched_yield) \
  672. M(random_get) \
  673. M(sock_accept) \
  674. M(sock_recv) \
  675. M(sock_send) \
  676. M(sock_shutdown)
  677. struct Names {
  678. #define NAME(x) FlyString x;
  679. ENUMERATE_FUNCTION_NAMES(NAME)
  680. #undef NAME
  681. static ErrorOr<Names> construct()
  682. {
  683. return Names {
  684. #define NAME(x) .x = TRY(FlyString::from_utf8(#x##sv)),
  685. ENUMERATE_FUNCTION_NAMES(NAME)
  686. #undef NAME
  687. };
  688. }
  689. };
  690. ErrorOr<HostFunction> Implementation::function_by_name(StringView name)
  691. {
  692. auto name_for_comparison = TRY(FlyString::from_utf8(name));
  693. static auto names = TRY(Names::construct());
  694. #define IMPL(x) \
  695. if (name_for_comparison == names.x) \
  696. return invocation_of<&Implementation::impl$##x>(#x##sv);
  697. ENUMERATE_FUNCTION_NAMES(IMPL)
  698. #undef IMPL
  699. return Error::from_string_literal("No such host function");
  700. }
  701. namespace ABI {
  702. template<typename T>
  703. auto CompatibleValueType = IsOneOf<T, i8, i16, i32>
  704. ? Wasm::ValueType(Wasm::ValueType::I32)
  705. : Wasm::ValueType(Wasm::ValueType::I64);
  706. template<typename R, typename... Args, ErrorOr<Result<R>> (Implementation::*impl)(Configuration&, Args...)>
  707. struct InvocationOf<impl> {
  708. HostFunction operator()(Implementation& self, StringView function_name)
  709. {
  710. Vector<ValueType> arguments_types { CompatibleValueType<typename ABI::ToCompatibleValue<Args>::Type>... };
  711. if constexpr (!IsVoid<R>) {
  712. if constexpr (requires { declval<typename R::SerializationComponents>(); }) {
  713. for_each_type<typename R::SerializationComponents>([&]<typename T>(TypeWrapper<T>) {
  714. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<T>>::Type>);
  715. });
  716. } else {
  717. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<R>>::Type>);
  718. }
  719. }
  720. return HostFunction(
  721. [&self, function_name](Configuration& configuration, Vector<Value>& arguments) -> Wasm::Result {
  722. Tuple args = [&]<typename... Ts, auto... Is>(IndexSequence<Is...>)
  723. {
  724. return Tuple { ABI::deserialize(ABI::to_compatible_value<Ts>(arguments[Is]))... };
  725. }
  726. .template operator()<Args...>(MakeIndexSequence<sizeof...(Args)>());
  727. auto result = args.apply_as_args([&](auto&&... impl_args) { return (self.*impl)(configuration, impl_args...); });
  728. dbgln_if(WASI_DEBUG, "WASI: {}({}) = {}", function_name, arguments, result);
  729. if (result.is_error())
  730. return Wasm::Trap { DeprecatedString::formatted("Invalid call to {}() = {}", function_name, result.error()) };
  731. auto value = result.release_value();
  732. if (value.is_error())
  733. return Wasm::Result { Vector { Value { ValueType(ValueType::I32), static_cast<u64>(to_underlying(value.error().value())) } } };
  734. if constexpr (!IsVoid<R>) {
  735. // Return values are passed as pointers, after the arguments
  736. if constexpr (requires { &R::serialize_into; }) {
  737. constexpr auto ResultCount = []<auto N>(void(R::*)(Array<Bytes, N>) const) { return N; }
  738. (&R::serialize_into);
  739. ABI::serialize(*value.result(), address_spans<ResultCount>(arguments.span().slice(sizeof...(Args)), configuration));
  740. } else {
  741. ABI::serialize(*value.result(), address_spans<1>(arguments.span().slice(sizeof...(Args)), configuration));
  742. }
  743. }
  744. // Return value is errno, we have nothing to return.
  745. return Wasm::Result { Vector<Value> { Value(ValueType(ValueType::I32), 0ull) } };
  746. },
  747. FunctionType {
  748. move(arguments_types),
  749. { ValueType(ValueType::I32) },
  750. });
  751. }
  752. };
  753. };
  754. Errno errno_value_from_errno(int value)
  755. {
  756. switch (value) {
  757. #ifdef ESUCCESS
  758. case ESUCCESS:
  759. return Errno::Success;
  760. #endif
  761. case E2BIG:
  762. return Errno::TooBig;
  763. case EACCES:
  764. return Errno::Access;
  765. case EADDRINUSE:
  766. return Errno::AddressInUse;
  767. case EADDRNOTAVAIL:
  768. return Errno::AddressNotAvailable;
  769. case EAFNOSUPPORT:
  770. return Errno::AFNotSupported;
  771. case EAGAIN:
  772. return Errno::Again;
  773. case EALREADY:
  774. return Errno::Already;
  775. case EBADF:
  776. return Errno::BadF;
  777. case EBUSY:
  778. return Errno::Busy;
  779. case ECANCELED:
  780. return Errno::Canceled;
  781. case ECHILD:
  782. return Errno::Child;
  783. case ECONNABORTED:
  784. return Errno::ConnectionAborted;
  785. case ECONNREFUSED:
  786. return Errno::ConnectionRefused;
  787. case ECONNRESET:
  788. return Errno::ConnectionReset;
  789. case EDEADLK:
  790. return Errno::Deadlock;
  791. case EDESTADDRREQ:
  792. return Errno::DestinationAddressRequired;
  793. case EDOM:
  794. return Errno::Domain;
  795. case EEXIST:
  796. return Errno::Exist;
  797. case EFAULT:
  798. return Errno::Fault;
  799. case EFBIG:
  800. return Errno::FBig;
  801. case EHOSTUNREACH:
  802. return Errno::HostUnreachable;
  803. case EILSEQ:
  804. return Errno::IllegalSequence;
  805. case EINPROGRESS:
  806. return Errno::InProgress;
  807. case EINTR:
  808. return Errno::Interrupted;
  809. case EINVAL:
  810. return Errno::Invalid;
  811. case EIO:
  812. return Errno::IO;
  813. case EISCONN:
  814. return Errno::IsConnected;
  815. case EISDIR:
  816. return Errno::IsDirectory;
  817. case ELOOP:
  818. return Errno::Loop;
  819. case EMFILE:
  820. return Errno::MFile;
  821. case EMLINK:
  822. return Errno::MLink;
  823. case EMSGSIZE:
  824. return Errno::MessageSize;
  825. case ENAMETOOLONG:
  826. return Errno::NameTooLong;
  827. case ENETDOWN:
  828. return Errno::NetworkDown;
  829. case ENETRESET:
  830. return Errno::NetworkReset;
  831. case ENETUNREACH:
  832. return Errno::NetworkUnreachable;
  833. case ENFILE:
  834. return Errno::NFile;
  835. case ENOBUFS:
  836. return Errno::NoBufferSpace;
  837. case ENODEV:
  838. return Errno::NoDevice;
  839. case ENOENT:
  840. return Errno::NoEntry;
  841. case ENOEXEC:
  842. return Errno::NoExec;
  843. case ENOLCK:
  844. return Errno::NoLock;
  845. case ENOMEM:
  846. return Errno::NoMemory;
  847. case ENOPROTOOPT:
  848. return Errno::NoProtocolOption;
  849. case ENOSPC:
  850. return Errno::NoSpace;
  851. case ENOSYS:
  852. return Errno::NoSys;
  853. case ENOTCONN:
  854. return Errno::NotConnected;
  855. case ENOTDIR:
  856. return Errno::NotDirectory;
  857. case ENOTEMPTY:
  858. return Errno::NotEmpty;
  859. case ENOTRECOVERABLE:
  860. return Errno::NotRecoverable;
  861. case ENOTSOCK:
  862. return Errno::NotSocket;
  863. case ENOTSUP:
  864. return Errno::NotSupported;
  865. case ENOTTY:
  866. return Errno::NoTTY;
  867. case ENXIO:
  868. return Errno::NXIO;
  869. case EOVERFLOW:
  870. return Errno::Overflow;
  871. case EPERM:
  872. return Errno::Permission;
  873. case EPIPE:
  874. return Errno::Pipe;
  875. case EPROTO:
  876. return Errno::Protocol;
  877. case EPROTONOSUPPORT:
  878. return Errno::ProtocolNotSupported;
  879. case EPROTOTYPE:
  880. return Errno::ProtocolType;
  881. case ERANGE:
  882. return Errno::Range;
  883. case ESPIPE:
  884. return Errno::SPipe;
  885. case ESRCH:
  886. return Errno::SRCH;
  887. case ESTALE:
  888. return Errno::Stale;
  889. case ETIMEDOUT:
  890. return Errno::TimedOut;
  891. case ETXTBSY:
  892. return Errno::TextBusy;
  893. case EXDEV:
  894. return Errno::XDev;
  895. default:
  896. return Errno::Invalid;
  897. }
  898. }
  899. }
  900. namespace AK {
  901. template<>
  902. struct Formatter<Wasm::Value> : AK::Formatter<FormatString> {
  903. ErrorOr<void> format(FormatBuilder& builder, Wasm::Value const& value)
  904. {
  905. return value.value().visit(
  906. [&](Wasm::Reference const&) {
  907. return Formatter<FormatString>::format(builder, "({}) &r"sv, Wasm::ValueType::kind_name(value.type().kind()));
  908. },
  909. [&](auto const& v) {
  910. return Formatter<FormatString>::format(builder, "({}) {}"sv, Wasm::ValueType::kind_name(value.type().kind()), v);
  911. });
  912. }
  913. };
  914. template<>
  915. struct Formatter<Wasm::Wasi::Errno> : AK::Formatter<FormatString> {
  916. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Errno const& value)
  917. {
  918. return Formatter<FormatString>::format(builder, "{}"sv, to_underlying(value));
  919. }
  920. };
  921. template<>
  922. struct Formatter<Empty> : AK::Formatter<FormatString> {
  923. ErrorOr<void> format(FormatBuilder&, Empty)
  924. {
  925. return {};
  926. }
  927. };
  928. template<typename T>
  929. struct Formatter<Wasm::Wasi::Result<T>> : AK::Formatter<FormatString> {
  930. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Result<T> const& value)
  931. {
  932. if (value.is_error())
  933. return Formatter<FormatString>::format(builder, "Error({})"sv, *value.error());
  934. return Formatter<FormatString>::format(builder, "Ok({})"sv, *value.result());
  935. }
  936. };
  937. template<OneOf<Wasm::Wasi::ArgsSizes, Wasm::Wasi::EnvironSizes> T>
  938. struct Formatter<T> : AK::Formatter<FormatString> {
  939. ErrorOr<void> format(FormatBuilder& builder, T const& value)
  940. {
  941. return Formatter<FormatString>::format(builder, "size={}, count={}"sv, value.size, value.count);
  942. }
  943. };
  944. template<>
  945. struct Formatter<Wasm::Wasi::FDStat> : AK::Formatter<FormatString> {
  946. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FDStat const&)
  947. {
  948. return Formatter<FormatString>::format(builder, "(rights)"sv);
  949. }
  950. };
  951. template<>
  952. struct Formatter<Wasm::Wasi::FileStat> : AK::Formatter<FormatString> {
  953. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FileStat const& value)
  954. {
  955. return Formatter<FormatString>::format(builder, "dev={}, ino={}, ft={}, nlink={}, size={}, atim={}, mtim={}, ctim={}"sv,
  956. value.dev, value.ino, to_underlying(value.filetype), value.nlink, value.size, value.atim, value.mtim, value.ctim);
  957. }
  958. };
  959. template<>
  960. struct Formatter<Wasm::Wasi::PreStat> : AK::Formatter<FormatString> {
  961. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::PreStat const& value)
  962. {
  963. return Formatter<FormatString>::format(builder, "length={}"sv, value.dir.pr_name_len);
  964. }
  965. };
  966. template<>
  967. struct Formatter<Wasm::Wasi::SockRecvResult> : AK::Formatter<FormatString> {
  968. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::SockRecvResult const& value)
  969. {
  970. return Formatter<FormatString>::format(builder, "size={}"sv, value.size);
  971. }
  972. };
  973. }