Wasi.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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. struct HostTypeImpl {
  783. using Type = T;
  784. };
  785. template<Enum T>
  786. struct HostTypeImpl<T> {
  787. using Type = UnderlyingType<T>;
  788. };
  789. template<typename T>
  790. using HostType = typename HostTypeImpl<T>::Type;
  791. template<typename T>
  792. auto CompatibleValueType = IsOneOf<HostType<T>, i8, i16, i32, u8, u16>
  793. ? Wasm::ValueType(Wasm::ValueType::I32)
  794. : Wasm::ValueType(Wasm::ValueType::I64);
  795. template<typename R, typename... Args, ErrorOr<Result<R>> (Implementation::*impl)(Configuration&, Args...)>
  796. struct InvocationOf<impl> {
  797. HostFunction operator()(Implementation& self, StringView function_name)
  798. {
  799. Vector<ValueType> arguments_types { CompatibleValueType<typename ABI::ToCompatibleValue<Args>::Type>... };
  800. if constexpr (!IsVoid<R>) {
  801. if constexpr (requires { declval<typename R::SerializationComponents>(); }) {
  802. for_each_type<typename R::SerializationComponents>([&]<typename T>(TypeWrapper<T>) {
  803. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<T>>::Type>);
  804. });
  805. } else {
  806. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<R>>::Type>);
  807. }
  808. }
  809. return HostFunction(
  810. [&self, function_name](Configuration& configuration, Vector<Value>& arguments) -> Wasm::Result {
  811. Tuple args = [&]<typename... Ts, auto... Is>(IndexSequence<Is...>) {
  812. return Tuple { ABI::deserialize(ABI::to_compatible_value<Ts>(arguments[Is]))... };
  813. }.template operator()<Args...>(MakeIndexSequence<sizeof...(Args)>());
  814. auto result = args.apply_as_args([&](auto&&... impl_args) { return (self.*impl)(configuration, impl_args...); });
  815. dbgln_if(WASI_DEBUG, "WASI: {}({}) = {}", function_name, arguments, result);
  816. if (result.is_error())
  817. return Wasm::Trap { ByteString::formatted("Invalid call to {}() = {}", function_name, result.error()) };
  818. auto value = result.release_value();
  819. if (value.is_error())
  820. return Wasm::Result { Vector { Value { ValueType(ValueType::I32), static_cast<u64>(to_underlying(value.error().value())) } } };
  821. if constexpr (!IsVoid<R>) {
  822. // Return values are passed as pointers, after the arguments
  823. if constexpr (requires { &R::serialize_into; }) {
  824. constexpr auto ResultCount = []<auto N>(void (R::*)(Array<Bytes, N>) const) { return N; }(&R::serialize_into);
  825. ABI::serialize(*value.result(), address_spans<ResultCount>(arguments.span().slice(sizeof...(Args)), configuration));
  826. } else {
  827. ABI::serialize(*value.result(), address_spans<1>(arguments.span().slice(sizeof...(Args)), configuration));
  828. }
  829. }
  830. // Return value is errno, we have nothing to return.
  831. return Wasm::Result { Vector<Value> { Value(ValueType(ValueType::I32), 0ull) } };
  832. },
  833. FunctionType {
  834. move(arguments_types),
  835. { ValueType(ValueType::I32) },
  836. },
  837. function_name);
  838. }
  839. };
  840. };
  841. Errno errno_value_from_errno(int value)
  842. {
  843. switch (value) {
  844. #ifdef ESUCCESS
  845. case ESUCCESS:
  846. return Errno::Success;
  847. #endif
  848. case E2BIG:
  849. return Errno::TooBig;
  850. case EACCES:
  851. return Errno::Access;
  852. case EADDRINUSE:
  853. return Errno::AddressInUse;
  854. case EADDRNOTAVAIL:
  855. return Errno::AddressNotAvailable;
  856. case EAFNOSUPPORT:
  857. return Errno::AFNotSupported;
  858. case EAGAIN:
  859. return Errno::Again;
  860. case EALREADY:
  861. return Errno::Already;
  862. case EBADF:
  863. return Errno::BadF;
  864. case EBUSY:
  865. return Errno::Busy;
  866. case ECANCELED:
  867. return Errno::Canceled;
  868. case ECHILD:
  869. return Errno::Child;
  870. case ECONNABORTED:
  871. return Errno::ConnectionAborted;
  872. case ECONNREFUSED:
  873. return Errno::ConnectionRefused;
  874. case ECONNRESET:
  875. return Errno::ConnectionReset;
  876. case EDEADLK:
  877. return Errno::Deadlock;
  878. case EDESTADDRREQ:
  879. return Errno::DestinationAddressRequired;
  880. case EDOM:
  881. return Errno::Domain;
  882. case EEXIST:
  883. return Errno::Exist;
  884. case EFAULT:
  885. return Errno::Fault;
  886. case EFBIG:
  887. return Errno::FBig;
  888. case EHOSTUNREACH:
  889. return Errno::HostUnreachable;
  890. case EILSEQ:
  891. return Errno::IllegalSequence;
  892. case EINPROGRESS:
  893. return Errno::InProgress;
  894. case EINTR:
  895. return Errno::Interrupted;
  896. case EINVAL:
  897. return Errno::Invalid;
  898. case EIO:
  899. return Errno::IO;
  900. case EISCONN:
  901. return Errno::IsConnected;
  902. case EISDIR:
  903. return Errno::IsDirectory;
  904. case ELOOP:
  905. return Errno::Loop;
  906. case EMFILE:
  907. return Errno::MFile;
  908. case EMLINK:
  909. return Errno::MLink;
  910. case EMSGSIZE:
  911. return Errno::MessageSize;
  912. case ENAMETOOLONG:
  913. return Errno::NameTooLong;
  914. case ENETDOWN:
  915. return Errno::NetworkDown;
  916. case ENETRESET:
  917. return Errno::NetworkReset;
  918. case ENETUNREACH:
  919. return Errno::NetworkUnreachable;
  920. case ENFILE:
  921. return Errno::NFile;
  922. case ENOBUFS:
  923. return Errno::NoBufferSpace;
  924. case ENODEV:
  925. return Errno::NoDevice;
  926. case ENOENT:
  927. return Errno::NoEntry;
  928. case ENOEXEC:
  929. return Errno::NoExec;
  930. case ENOLCK:
  931. return Errno::NoLock;
  932. case ENOMEM:
  933. return Errno::NoMemory;
  934. case ENOPROTOOPT:
  935. return Errno::NoProtocolOption;
  936. case ENOSPC:
  937. return Errno::NoSpace;
  938. case ENOSYS:
  939. return Errno::NoSys;
  940. case ENOTCONN:
  941. return Errno::NotConnected;
  942. case ENOTDIR:
  943. return Errno::NotDirectory;
  944. case ENOTEMPTY:
  945. return Errno::NotEmpty;
  946. case ENOTRECOVERABLE:
  947. return Errno::NotRecoverable;
  948. case ENOTSOCK:
  949. return Errno::NotSocket;
  950. case ENOTSUP:
  951. return Errno::NotSupported;
  952. case ENOTTY:
  953. return Errno::NoTTY;
  954. case ENXIO:
  955. return Errno::NXIO;
  956. case EOVERFLOW:
  957. return Errno::Overflow;
  958. case EPERM:
  959. return Errno::Permission;
  960. case EPIPE:
  961. return Errno::Pipe;
  962. case EPROTO:
  963. return Errno::Protocol;
  964. case EPROTONOSUPPORT:
  965. return Errno::ProtocolNotSupported;
  966. case EPROTOTYPE:
  967. return Errno::ProtocolType;
  968. case ERANGE:
  969. return Errno::Range;
  970. case ESPIPE:
  971. return Errno::SPipe;
  972. case ESRCH:
  973. return Errno::SRCH;
  974. case ESTALE:
  975. return Errno::Stale;
  976. case ETIMEDOUT:
  977. return Errno::TimedOut;
  978. case ETXTBSY:
  979. return Errno::TextBusy;
  980. case EXDEV:
  981. return Errno::XDev;
  982. default:
  983. return Errno::Invalid;
  984. }
  985. }
  986. }
  987. namespace AK {
  988. template<>
  989. struct Formatter<Wasm::Value> : AK::Formatter<FormatString> {
  990. ErrorOr<void> format(FormatBuilder& builder, Wasm::Value const& value)
  991. {
  992. return value.value().visit(
  993. [&](Wasm::Reference const&) {
  994. return Formatter<FormatString>::format(builder, "({}) &r"sv, Wasm::ValueType::kind_name(value.type().kind()));
  995. },
  996. [&](auto const& v) {
  997. return Formatter<FormatString>::format(builder, "({}) {}"sv, Wasm::ValueType::kind_name(value.type().kind()), v);
  998. });
  999. }
  1000. };
  1001. template<>
  1002. struct Formatter<Wasm::Wasi::Errno> : AK::Formatter<FormatString> {
  1003. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Errno const& value)
  1004. {
  1005. return Formatter<FormatString>::format(builder, "{}"sv, to_underlying(value));
  1006. }
  1007. };
  1008. template<>
  1009. struct Formatter<Empty> : AK::Formatter<FormatString> {
  1010. ErrorOr<void> format(FormatBuilder&, Empty)
  1011. {
  1012. return {};
  1013. }
  1014. };
  1015. template<typename T>
  1016. struct Formatter<Wasm::Wasi::Result<T>> : AK::Formatter<FormatString> {
  1017. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Result<T> const& value)
  1018. {
  1019. if (value.is_error())
  1020. return Formatter<FormatString>::format(builder, "Error({})"sv, *value.error());
  1021. return Formatter<FormatString>::format(builder, "Ok({})"sv, *value.result());
  1022. }
  1023. };
  1024. template<OneOf<Wasm::Wasi::ArgsSizes, Wasm::Wasi::EnvironSizes> T>
  1025. struct Formatter<T> : AK::Formatter<FormatString> {
  1026. ErrorOr<void> format(FormatBuilder& builder, T const& value)
  1027. {
  1028. return Formatter<FormatString>::format(builder, "size={}, count={}"sv, value.size, value.count);
  1029. }
  1030. };
  1031. template<>
  1032. struct Formatter<Wasm::Wasi::FDStat> : AK::Formatter<FormatString> {
  1033. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FDStat const&)
  1034. {
  1035. return Formatter<FormatString>::format(builder, "(rights)"sv);
  1036. }
  1037. };
  1038. template<>
  1039. struct Formatter<Wasm::Wasi::FileStat> : AK::Formatter<FormatString> {
  1040. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FileStat const& value)
  1041. {
  1042. return Formatter<FormatString>::format(builder, "dev={}, ino={}, ft={}, nlink={}, size={}, atim={}, mtim={}, ctim={}"sv,
  1043. value.dev, value.ino, to_underlying(value.filetype), value.nlink, value.size, value.atim, value.mtim, value.ctim);
  1044. }
  1045. };
  1046. template<>
  1047. struct Formatter<Wasm::Wasi::PreStat> : AK::Formatter<FormatString> {
  1048. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::PreStat const& value)
  1049. {
  1050. return Formatter<FormatString>::format(builder, "length={}"sv, value.dir.pr_name_len);
  1051. }
  1052. };
  1053. template<>
  1054. struct Formatter<Wasm::Wasi::SockRecvResult> : AK::Formatter<FormatString> {
  1055. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::SockRecvResult const& value)
  1056. {
  1057. return Formatter<FormatString>::format(builder, "size={}"sv, value.size);
  1058. }
  1059. };
  1060. }