Wasi.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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. static FileType file_type_of(struct stat const& buf);
  271. static FDFlags fd_flags_of(struct stat const& buf);
  272. Vector<AK::String> const& Implementation::arguments() const
  273. {
  274. if (!cache.cached_arguments.has_value()) {
  275. cache.cached_arguments.lazy_emplace([&] {
  276. if (provide_arguments)
  277. return provide_arguments();
  278. return Vector<AK::String> {};
  279. });
  280. }
  281. return *cache.cached_arguments;
  282. }
  283. Vector<AK::String> const& Implementation::environment() const
  284. {
  285. if (!cache.cached_environment.has_value()) {
  286. cache.cached_environment.lazy_emplace([&] {
  287. if (provide_environment)
  288. return provide_environment();
  289. return Vector<AK::String> {};
  290. });
  291. }
  292. return *cache.cached_environment;
  293. }
  294. Vector<Implementation::MappedPath> const& Implementation::preopened_directories() const
  295. {
  296. if (!cache.cached_preopened_directories.has_value()) {
  297. cache.cached_preopened_directories.lazy_emplace([&] {
  298. if (provide_preopened_directories)
  299. return provide_preopened_directories();
  300. return Vector<MappedPath> {};
  301. });
  302. }
  303. return *cache.cached_preopened_directories;
  304. }
  305. Implementation::Descriptor Implementation::map_fd(FD fd)
  306. {
  307. u32 fd_value = fd.value();
  308. if (auto* value = m_fd_map.find(fd_value))
  309. return value->downcast<Descriptor>();
  310. return UnmappedDescriptor(fd_value);
  311. }
  312. ErrorOr<Result<void>> Implementation::impl$args_get(Configuration& configuration, Pointer<Pointer<u8>> argv, Pointer<u8> argv_buf)
  313. {
  314. UnderlyingPointerType raw_argv_buffer = argv_buf.value();
  315. UnderlyingPointerType raw_argv = argv.value();
  316. for (auto& entry : arguments()) {
  317. auto ptr = Pointer<u8> { raw_argv_buffer };
  318. auto byte_count = TRY(copy_string_including_terminating_null(configuration, entry.bytes_as_string_view(), ptr));
  319. raw_argv_buffer += byte_count;
  320. TRY(copy_typed_value_to(configuration, ptr, Pointer<Pointer<u8>> { raw_argv }));
  321. raw_argv += sizeof(ptr);
  322. }
  323. return Result<void> {};
  324. }
  325. ErrorOr<Result<ArgsSizes>> Implementation::impl$args_sizes_get(Configuration&)
  326. {
  327. size_t count = 0;
  328. size_t total_size = 0;
  329. for (auto& entry : arguments()) {
  330. count += 1;
  331. total_size += entry.bytes().size() + 1; // 1 extra byte for terminating null.
  332. }
  333. return Result<ArgsSizes>(ArgsSizes {
  334. count,
  335. total_size,
  336. });
  337. }
  338. ErrorOr<Result<void>> Implementation::impl$environ_get(Configuration& configuration, Pointer<Pointer<u8>> environ, Pointer<u8> environ_buf)
  339. {
  340. UnderlyingPointerType raw_environ_buffer = environ_buf.value();
  341. UnderlyingPointerType raw_environ = environ.value();
  342. for (auto& entry : environment()) {
  343. auto ptr = Pointer<u8> { raw_environ_buffer };
  344. auto byte_count = TRY(copy_string_including_terminating_null(configuration, entry.bytes_as_string_view(), ptr));
  345. raw_environ_buffer += byte_count;
  346. TRY(copy_typed_value_to(configuration, ptr, Pointer<Pointer<u8>> { raw_environ }));
  347. raw_environ += sizeof(ptr);
  348. }
  349. return Result<void> {};
  350. }
  351. ErrorOr<Result<EnvironSizes>> Implementation::impl$environ_sizes_get(Configuration&)
  352. {
  353. size_t count = 0;
  354. size_t total_size = 0;
  355. for (auto& entry : environment()) {
  356. count += 1;
  357. total_size += entry.bytes().size() + 1; // 1 extra byte for terminating null.
  358. }
  359. return Result<EnvironSizes>(EnvironSizes {
  360. count,
  361. total_size,
  362. });
  363. }
  364. ErrorOr<Result<void>> Implementation::impl$proc_exit(Configuration&, ExitCode exit_code)
  365. {
  366. exit(exit_code);
  367. }
  368. ErrorOr<Result<void>> Implementation::impl$fd_close(Configuration&, FD fd)
  369. {
  370. return map_fd(fd).visit(
  371. [&](u32 fd) -> Result<void> {
  372. if (close(bit_cast<i32>(fd)) != 0)
  373. return errno_value_from_errno(errno);
  374. return {};
  375. },
  376. [&](PreopenedDirectoryDescriptor) -> Result<void> {
  377. return errno_value_from_errno(EISDIR);
  378. },
  379. [&](UnmappedDescriptor) -> Result<void> {
  380. return errno_value_from_errno(EBADF);
  381. });
  382. }
  383. ErrorOr<Result<Size>> Implementation::impl$fd_write(Configuration& configuration, FD fd, Pointer<CIOVec> iovs, Size iovs_len)
  384. {
  385. auto mapped_fd = map_fd(fd);
  386. if (!mapped_fd.has<u32>())
  387. return errno_value_from_errno(EBADF);
  388. u32 fd_value = mapped_fd.get<u32>();
  389. Size bytes_written = 0;
  390. for (auto& iovec : TRY(copy_typed_array(configuration, iovs, iovs_len))) {
  391. auto slice = TRY(slice_typed_memory(configuration, iovec.buf, iovec.buf_len));
  392. auto result = write(fd_value, slice.data(), slice.size());
  393. if (result < 0)
  394. return errno_value_from_errno(errno);
  395. bytes_written += static_cast<Size>(result);
  396. }
  397. return bytes_written;
  398. }
  399. ErrorOr<Result<PreStat>> Implementation::impl$fd_prestat_get(Configuration&, FD fd)
  400. {
  401. auto& paths = preopened_directories();
  402. return map_fd(fd).visit(
  403. [&](UnmappedDescriptor unmapped_fd) -> Result<PreStat> {
  404. // Map the new fd to the next available directory.
  405. if (m_first_unmapped_preopened_directory_index >= paths.size())
  406. return errno_value_from_errno(EBADF);
  407. auto index = m_first_unmapped_preopened_directory_index++;
  408. m_fd_map.insert(unmapped_fd.value(), PreopenedDirectoryDescriptor(index));
  409. return PreStat {
  410. .type = PreOpenType::Dir,
  411. .dir = PreStatDir {
  412. .pr_name_len = paths[index].mapped_path.string().bytes().size(),
  413. },
  414. };
  415. },
  416. [&](u32) -> Result<PreStat> {
  417. return errno_value_from_errno(EBADF);
  418. },
  419. [&](PreopenedDirectoryDescriptor fd) -> Result<PreStat> {
  420. return PreStat {
  421. .type = PreOpenType::Dir,
  422. .dir = PreStatDir {
  423. .pr_name_len = paths[fd.value()].mapped_path.string().bytes().size(),
  424. },
  425. };
  426. });
  427. }
  428. ErrorOr<Result<void>> Implementation::impl$fd_prestat_dir_name(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
  429. {
  430. auto mapped_fd = map_fd(fd);
  431. if (!mapped_fd.has<PreopenedDirectoryDescriptor>())
  432. return errno_value_from_errno(EBADF);
  433. auto& entry = preopened_directories()[mapped_fd.get<PreopenedDirectoryDescriptor>().value()];
  434. auto byte_count = TRY(copy_string_excluding_terminating_null(configuration, entry.mapped_path.string().view(), path, path_len));
  435. if (byte_count < path_len.value())
  436. return errno_value_from_errno(ENOBUFS);
  437. return Result<void> {};
  438. }
  439. ErrorOr<Result<FileStat>> Implementation::impl$path_filestat_get(Configuration& configuration, FD fd, LookupFlags flags, ConstPointer<u8> path, Size path_len)
  440. {
  441. auto dir_fd = AT_FDCWD;
  442. auto mapped_fd = map_fd(fd);
  443. mapped_fd.visit(
  444. [&](PreopenedDirectoryDescriptor descriptor) {
  445. auto& entry = preopened_directories()[descriptor.value()];
  446. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  447. ByteString path = entry.host_path.string();
  448. return open(path.characters(), O_DIRECTORY, 0);
  449. });
  450. entry.opened_fd = dir_fd;
  451. },
  452. [&](u32 fd) {
  453. dir_fd = fd;
  454. },
  455. [](UnmappedDescriptor) {});
  456. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  457. return errno_value_from_errno(errno);
  458. int options = 0;
  459. if (!flags.bits.symlink_follow)
  460. options |= AT_SYMLINK_NOFOLLOW;
  461. auto slice = TRY(slice_typed_memory(configuration, path, path_len));
  462. auto null_terminated_string = ByteString::copy(slice);
  463. struct stat stat_buf;
  464. if (fstatat(dir_fd, null_terminated_string.characters(), &stat_buf, options) < 0)
  465. return errno_value_from_errno(errno);
  466. constexpr auto file_type_of = [](struct stat const& buf) {
  467. if (S_ISDIR(buf.st_mode))
  468. return FileType::Directory;
  469. if (S_ISCHR(buf.st_mode))
  470. return FileType::CharacterDevice;
  471. if (S_ISBLK(buf.st_mode))
  472. return FileType::BlockDevice;
  473. if (S_ISREG(buf.st_mode))
  474. return FileType::RegularFile;
  475. if (S_ISFIFO(buf.st_mode))
  476. return FileType::Unknown; // FIXME: FileType::Pipe is currently not present in WASI (but it should be) so we use Unknown for now.
  477. if (S_ISLNK(buf.st_mode))
  478. return FileType::SymbolicLink;
  479. if (S_ISSOCK(buf.st_mode))
  480. return FileType::SocketStream;
  481. return FileType::Unknown;
  482. };
  483. return Result(FileStat {
  484. .dev = stat_buf.st_dev,
  485. .ino = stat_buf.st_ino,
  486. .filetype = file_type_of(stat_buf),
  487. .nlink = stat_buf.st_nlink,
  488. .size = stat_buf.st_size,
  489. .atim = stat_buf.st_atime,
  490. .mtim = stat_buf.st_mtime,
  491. .ctim = stat_buf.st_ctime,
  492. });
  493. }
  494. ErrorOr<Result<void>> Implementation::impl$path_create_directory(Configuration& configuration, FD fd, Pointer<u8> path, Size path_len)
  495. {
  496. auto dir_fd = AT_FDCWD;
  497. auto mapped_fd = map_fd(fd);
  498. mapped_fd.visit(
  499. [&](PreopenedDirectoryDescriptor descriptor) {
  500. auto& entry = preopened_directories()[descriptor.value()];
  501. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  502. ByteString path = entry.host_path.string();
  503. return open(path.characters(), O_DIRECTORY, 0);
  504. });
  505. entry.opened_fd = dir_fd;
  506. },
  507. [&](u32 fd) {
  508. dir_fd = fd;
  509. },
  510. [](UnmappedDescriptor) {});
  511. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  512. return errno_value_from_errno(errno);
  513. auto slice = TRY(slice_typed_memory(configuration, path, path_len));
  514. auto null_terminated_string = ByteString::copy(slice);
  515. if (mkdirat(dir_fd, null_terminated_string.characters(), 0755) < 0)
  516. return errno_value_from_errno(errno);
  517. return Result<void> {};
  518. }
  519. 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)
  520. {
  521. auto dir_fd = AT_FDCWD;
  522. auto mapped_fd = map_fd(fd);
  523. mapped_fd.visit(
  524. [&](PreopenedDirectoryDescriptor descriptor) {
  525. auto& entry = preopened_directories()[descriptor.value()];
  526. dir_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  527. ByteString path = entry.host_path.string();
  528. return open(path.characters(), O_DIRECTORY, 0);
  529. });
  530. entry.opened_fd = dir_fd;
  531. },
  532. [&](u32 fd) {
  533. dir_fd = fd;
  534. },
  535. [](UnmappedDescriptor) {});
  536. if (dir_fd < 0 && dir_fd != AT_FDCWD)
  537. return errno_value_from_errno(errno);
  538. // FIXME: What should we do with dsync/rsync?
  539. int open_flags = 0;
  540. if (fd_flags.bits.append)
  541. open_flags |= O_APPEND;
  542. if (fd_flags.bits.nonblock)
  543. open_flags |= O_NONBLOCK;
  544. if (fd_flags.bits.sync)
  545. open_flags |= O_SYNC;
  546. if (o_flags.bits.trunc)
  547. open_flags |= O_TRUNC;
  548. if (o_flags.bits.creat)
  549. open_flags |= O_CREAT;
  550. if (o_flags.bits.directory)
  551. open_flags |= O_DIRECTORY;
  552. if (o_flags.bits.excl)
  553. open_flags |= O_EXCL;
  554. if (!lookup_flags.bits.symlink_follow)
  555. open_flags |= O_NOFOLLOW;
  556. auto path_data = TRY(slice_typed_memory(configuration, path, path_len));
  557. auto path_string = ByteString::copy(path_data);
  558. dbgln_if(WASI_FINE_GRAINED_DEBUG, "path_open: dir_fd={}, path={}, open_flags={}", dir_fd, path_string, open_flags);
  559. int opened_fd = openat(dir_fd, path_string.characters(), open_flags, 0644);
  560. if (opened_fd < 0)
  561. return errno_value_from_errno(errno);
  562. // FIXME: Implement Rights and RightsInheriting.
  563. m_fd_map.insert(opened_fd, static_cast<u32>(opened_fd));
  564. return FD(opened_fd);
  565. }
  566. ErrorOr<Result<Timestamp>> Implementation::impl$clock_time_get(Configuration&, ClockID id, Timestamp precision)
  567. {
  568. constexpr u64 nanoseconds_in_millisecond = 1000'000ull;
  569. constexpr u64 nanoseconds_in_second = 1000'000'000ull;
  570. clockid_t clock_id;
  571. switch (id) {
  572. case ClockID::Realtime:
  573. if (precision >= nanoseconds_in_millisecond)
  574. clock_id = CLOCK_REALTIME_COARSE;
  575. else
  576. clock_id = CLOCK_REALTIME;
  577. break;
  578. case ClockID::Monotonic:
  579. if (precision >= nanoseconds_in_millisecond)
  580. clock_id = CLOCK_MONOTONIC_COARSE;
  581. else
  582. clock_id = CLOCK_MONOTONIC;
  583. break;
  584. case ClockID::ProcessCPUTimeID:
  585. case ClockID::ThreadCPUTimeID:
  586. return Errno::NoSys;
  587. break;
  588. }
  589. struct timespec ts;
  590. if (clock_gettime(clock_id, &ts) < 0)
  591. return errno_value_from_errno(errno);
  592. return Result<Timestamp> { static_cast<u64>(ts.tv_sec) * nanoseconds_in_second + static_cast<u64>(ts.tv_nsec) };
  593. }
  594. ErrorOr<Result<FileStat>> Implementation::impl$fd_filestat_get(Configuration&, FD fd)
  595. {
  596. int resolved_fd = -1;
  597. auto mapped_fd = map_fd(fd);
  598. mapped_fd.visit(
  599. [&](PreopenedDirectoryDescriptor descriptor) {
  600. auto& entry = preopened_directories()[descriptor.value()];
  601. resolved_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  602. ByteString path = entry.host_path.string();
  603. return open(path.characters(), O_DIRECTORY, 0);
  604. });
  605. entry.opened_fd = resolved_fd;
  606. },
  607. [&](u32 fd) {
  608. resolved_fd = fd;
  609. },
  610. [](UnmappedDescriptor) {});
  611. if (resolved_fd < 0)
  612. return errno_value_from_errno(errno);
  613. struct stat stat_buf;
  614. if (fstat(resolved_fd, &stat_buf) < 0)
  615. return errno_value_from_errno(errno);
  616. constexpr auto file_type_of = [](struct stat const& buf) {
  617. if (S_ISDIR(buf.st_mode))
  618. return FileType::Directory;
  619. if (S_ISCHR(buf.st_mode))
  620. return FileType::CharacterDevice;
  621. if (S_ISBLK(buf.st_mode))
  622. return FileType::BlockDevice;
  623. if (S_ISREG(buf.st_mode))
  624. return FileType::RegularFile;
  625. if (S_ISFIFO(buf.st_mode))
  626. return FileType::Unknown; // no Pipe? :yakfused:
  627. if (S_ISLNK(buf.st_mode))
  628. return FileType::SymbolicLink;
  629. if (S_ISSOCK(buf.st_mode))
  630. return FileType::SocketDGram; // :shrug:
  631. return FileType::Unknown;
  632. };
  633. return Result(FileStat {
  634. .dev = stat_buf.st_dev,
  635. .ino = stat_buf.st_ino,
  636. .filetype = file_type_of(stat_buf),
  637. .nlink = stat_buf.st_nlink,
  638. .size = stat_buf.st_size,
  639. .atim = stat_buf.st_atime,
  640. .mtim = stat_buf.st_mtime,
  641. .ctim = stat_buf.st_ctime,
  642. });
  643. }
  644. ErrorOr<Result<void>> Implementation::impl$random_get(Configuration& configuration, Pointer<u8> buf, Size buf_len)
  645. {
  646. auto buffer_slice = TRY(slice_typed_memory(configuration, buf, buf_len));
  647. fill_with_random(buffer_slice);
  648. return Result<void> {};
  649. }
  650. ErrorOr<Result<Size>> Implementation::impl$fd_read(Configuration& configuration, FD fd, Pointer<IOVec> iovs, Size iovs_len)
  651. {
  652. auto mapped_fd = map_fd(fd);
  653. if (!mapped_fd.has<u32>())
  654. return errno_value_from_errno(EBADF);
  655. u32 fd_value = mapped_fd.get<u32>();
  656. Size bytes_read = 0;
  657. for (auto& iovec : TRY(copy_typed_array(configuration, iovs, iovs_len))) {
  658. auto slice = TRY(slice_typed_memory(configuration, iovec.buf, iovec.buf_len));
  659. auto result = read(fd_value, slice.data(), slice.size());
  660. if (result < 0)
  661. return errno_value_from_errno(errno);
  662. bytes_read += static_cast<Size>(result);
  663. }
  664. return bytes_read;
  665. }
  666. ErrorOr<Result<FDStat>> Implementation::impl$fd_fdstat_get(Configuration&, FD fd)
  667. {
  668. auto mapped_fd = map_fd(fd);
  669. auto resolved_fd = -1;
  670. mapped_fd.visit(
  671. [&](PreopenedDirectoryDescriptor descriptor) {
  672. auto& entry = preopened_directories()[descriptor.value()];
  673. resolved_fd = entry.opened_fd.value_or_lazy_evaluated([&] {
  674. ByteString path = entry.host_path.string();
  675. return open(path.characters(), O_DIRECTORY, 0);
  676. });
  677. entry.opened_fd = resolved_fd;
  678. },
  679. [&](u32 fd) {
  680. resolved_fd = fd;
  681. },
  682. [](UnmappedDescriptor) {});
  683. if (resolved_fd < 0)
  684. return errno_value_from_errno(errno);
  685. struct stat stat_buf;
  686. if (fstat(resolved_fd, &stat_buf) < 0)
  687. return errno_value_from_errno(errno);
  688. return FDStat {
  689. .fs_filetype = file_type_of(stat_buf),
  690. .fs_flags = fd_flags_of(stat_buf),
  691. .fs_rights_base = Rights { .data = 0 },
  692. .fs_rights_inheriting = Rights { .data = 0 },
  693. };
  694. }
  695. ErrorOr<Result<FileSize>> Implementation::impl$fd_seek(Configuration&, FD fd, FileDelta offset, Whence whence)
  696. {
  697. auto mapped_fd = map_fd(fd);
  698. if (!mapped_fd.has<u32>())
  699. return errno_value_from_errno(EBADF);
  700. u32 fd_value = mapped_fd.get<u32>();
  701. auto result = lseek(fd_value, offset, static_cast<int>(whence));
  702. if (result < 0)
  703. return errno_value_from_errno(errno);
  704. return FileSize(result);
  705. }
  706. #pragma GCC diagnostic push
  707. #pragma GCC diagnostic ignored "-Wunused-parameter"
  708. ErrorOr<Result<Timestamp>> Implementation::impl$clock_res_get(Configuration&, ClockID id)
  709. {
  710. return Errno::NoSys;
  711. }
  712. ErrorOr<Result<void>> Implementation::impl$fd_advise(Configuration&, FD, FileSize offset, FileSize len, Advice) { return Errno::NoSys; }
  713. ErrorOr<Result<void>> Implementation::impl$fd_allocate(Configuration&, FD, FileSize offset, FileSize len) { return Errno::NoSys; }
  714. ErrorOr<Result<void>> Implementation::impl$fd_datasync(Configuration&, FD) { return Errno::NoSys; }
  715. ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_flags(Configuration&, FD, FDFlags) { return Errno::NoSys; }
  716. ErrorOr<Result<void>> Implementation::impl$fd_fdstat_set_rights(Configuration&, FD, Rights fs_rights_base, Rights fs_rights_inheriting) { return Errno::NoSys; }
  717. ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_size(Configuration&, FD, FileSize) { return Errno::NoSys; }
  718. ErrorOr<Result<void>> Implementation::impl$fd_filestat_set_times(Configuration&, FD, Timestamp atim, Timestamp mtim, FSTFlags) { return Errno::NoSys; }
  719. ErrorOr<Result<Size>> Implementation::impl$fd_pread(Configuration&, FD, Pointer<IOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
  720. ErrorOr<Result<Size>> Implementation::impl$fd_pwrite(Configuration&, FD, Pointer<CIOVec> iovs, Size iovs_len, FileSize offset) { return Errno::NoSys; }
  721. ErrorOr<Result<Size>> Implementation::impl$fd_readdir(Configuration&, FD, Pointer<u8> buf, Size buf_len, DirCookie cookie) { return Errno::NoSys; }
  722. ErrorOr<Result<void>> Implementation::impl$fd_renumber(Configuration&, FD from, FD to) { return Errno::NoSys; }
  723. ErrorOr<Result<void>> Implementation::impl$fd_sync(Configuration&, FD) { return Errno::NoSys; }
  724. ErrorOr<Result<FileSize>> Implementation::impl$fd_tell(Configuration&, FD) { return Errno::NoSys; }
  725. 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; }
  726. 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; }
  727. 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; }
  728. ErrorOr<Result<void>> Implementation::impl$path_remove_directory(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
  729. 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; }
  730. 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; }
  731. ErrorOr<Result<void>> Implementation::impl$path_unlink_file(Configuration&, FD, Pointer<u8> path, Size path_len) { return Errno::NoSys; }
  732. ErrorOr<Result<Size>> Implementation::impl$poll_oneoff(Configuration&, ConstPointer<Subscription> in, Pointer<Event> out, Size nsubscriptions) { return Errno::NoSys; }
  733. ErrorOr<Result<void>> Implementation::impl$proc_raise(Configuration&, Signal) { return Errno::NoSys; }
  734. ErrorOr<Result<void>> Implementation::impl$sched_yield(Configuration&) { return Errno::NoSys; }
  735. ErrorOr<Result<FD>> Implementation::impl$sock_accept(Configuration&, FD fd, FDFlags fd_flags) { return Errno::NoSys; }
  736. ErrorOr<Result<SockRecvResult>> Implementation::impl$sock_recv(Configuration&, FD fd, Pointer<IOVec> ri_data, Size ri_data_len, RIFlags ri_flags) { return Errno::NoSys; }
  737. ErrorOr<Result<Size>> Implementation::impl$sock_send(Configuration&, FD fd, Pointer<CIOVec> si_data, Size si_data_len, SIFlags si_flags) { return Errno::NoSys; }
  738. ErrorOr<Result<void>> Implementation::impl$sock_shutdown(Configuration&, FD fd, SDFlags how) { return Errno::NoSys; }
  739. #pragma GCC diagnostic pop
  740. template<size_t N>
  741. static Array<Bytes, N> address_spans(Span<Value> values, Configuration& configuration)
  742. {
  743. Array<Bytes, N> result;
  744. auto memory = configuration.store().get(MemoryAddress { 0 })->data().span();
  745. for (size_t i = 0; i < N; ++i)
  746. result[i] = memory.slice(*values[i].to<i32>());
  747. return result;
  748. }
  749. #define ENUMERATE_FUNCTION_NAMES(M) \
  750. M(args_get) \
  751. M(args_sizes_get) \
  752. M(environ_get) \
  753. M(environ_sizes_get) \
  754. M(clock_res_get) \
  755. M(clock_time_get) \
  756. M(fd_advise) \
  757. M(fd_allocate) \
  758. M(fd_close) \
  759. M(fd_datasync) \
  760. M(fd_fdstat_get) \
  761. M(fd_fdstat_set_flags) \
  762. M(fd_fdstat_set_rights) \
  763. M(fd_filestat_get) \
  764. M(fd_filestat_set_size) \
  765. M(fd_filestat_set_times) \
  766. M(fd_pread) \
  767. M(fd_prestat_get) \
  768. M(fd_prestat_dir_name) \
  769. M(fd_pwrite) \
  770. M(fd_read) \
  771. M(fd_readdir) \
  772. M(fd_renumber) \
  773. M(fd_seek) \
  774. M(fd_sync) \
  775. M(fd_tell) \
  776. M(fd_write) \
  777. M(path_create_directory) \
  778. M(path_filestat_get) \
  779. M(path_filestat_set_times) \
  780. M(path_link) \
  781. M(path_open) \
  782. M(path_readlink) \
  783. M(path_remove_directory) \
  784. M(path_rename) \
  785. M(path_symlink) \
  786. M(path_unlink_file) \
  787. M(poll_oneoff) \
  788. M(proc_exit) \
  789. M(proc_raise) \
  790. M(sched_yield) \
  791. M(random_get) \
  792. M(sock_accept) \
  793. M(sock_recv) \
  794. M(sock_send) \
  795. M(sock_shutdown)
  796. struct Names {
  797. #define NAME(x) FlyString x;
  798. ENUMERATE_FUNCTION_NAMES(NAME)
  799. #undef NAME
  800. static ErrorOr<Names> construct()
  801. {
  802. return Names {
  803. #define NAME(x) .x = TRY(FlyString::from_utf8(#x##sv)),
  804. ENUMERATE_FUNCTION_NAMES(NAME)
  805. #undef NAME
  806. };
  807. }
  808. };
  809. ErrorOr<HostFunction> Implementation::function_by_name(StringView name)
  810. {
  811. auto name_for_comparison = TRY(FlyString::from_utf8(name));
  812. static auto names = TRY(Names::construct());
  813. #define IMPL(x) \
  814. if (name_for_comparison == names.x) \
  815. return invocation_of<&Implementation::impl$##x>(#x##sv);
  816. ENUMERATE_FUNCTION_NAMES(IMPL)
  817. #undef IMPL
  818. return Error::from_string_literal("No such host function");
  819. }
  820. namespace ABI {
  821. template<typename T>
  822. struct HostTypeImpl {
  823. using Type = T;
  824. };
  825. template<Enum T>
  826. struct HostTypeImpl<T> {
  827. using Type = UnderlyingType<T>;
  828. };
  829. template<typename T>
  830. using HostType = typename HostTypeImpl<T>::Type;
  831. template<typename T>
  832. auto CompatibleValueType = IsOneOf<HostType<T>, i8, i16, i32, u8, u16>
  833. ? Wasm::ValueType(Wasm::ValueType::I32)
  834. : Wasm::ValueType(Wasm::ValueType::I64);
  835. template<typename R, typename... Args, ErrorOr<Result<R>> (Implementation::*impl)(Configuration&, Args...)>
  836. struct InvocationOf<impl> {
  837. HostFunction operator()(Implementation& self, StringView function_name)
  838. {
  839. Vector<ValueType> arguments_types { CompatibleValueType<typename ABI::ToCompatibleValue<Args>::Type>... };
  840. if constexpr (!IsVoid<R>) {
  841. if constexpr (requires { declval<typename R::SerializationComponents>(); }) {
  842. for_each_type<typename R::SerializationComponents>([&]<typename T>(TypeWrapper<T>) {
  843. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<T>>::Type>);
  844. });
  845. } else {
  846. arguments_types.append(CompatibleValueType<typename ABI::ToCompatibleValue<Pointer<R>>::Type>);
  847. }
  848. }
  849. return HostFunction(
  850. [&self, function_name](Configuration& configuration, Vector<Value>& arguments) -> Wasm::Result {
  851. Tuple args = [&]<typename... Ts, auto... Is>(IndexSequence<Is...>) {
  852. return Tuple { ABI::deserialize(ABI::to_compatible_value<Ts>(arguments[Is]))... };
  853. }.template operator()<Args...>(MakeIndexSequence<sizeof...(Args)>());
  854. auto result = args.apply_as_args([&](auto&&... impl_args) { return (self.*impl)(configuration, impl_args...); });
  855. dbgln_if(WASI_DEBUG, "WASI: {}({}) = {}", function_name, arguments, result);
  856. if (result.is_error())
  857. return Wasm::Trap { ByteString::formatted("Invalid call to {}() = {}", function_name, result.error()) };
  858. auto value = result.release_value();
  859. if (value.is_error())
  860. return Wasm::Result { Vector { Value { ValueType(ValueType::I32), static_cast<u64>(to_underlying(value.error().value())) } } };
  861. if constexpr (!IsVoid<R>) {
  862. // Return values are passed as pointers, after the arguments
  863. if constexpr (requires { &R::serialize_into; }) {
  864. constexpr auto ResultCount = []<auto N>(void (R::*)(Array<Bytes, N>) const) { return N; }(&R::serialize_into);
  865. ABI::serialize(*value.result(), address_spans<ResultCount>(arguments.span().slice(sizeof...(Args)), configuration));
  866. } else {
  867. ABI::serialize(*value.result(), address_spans<1>(arguments.span().slice(sizeof...(Args)), configuration));
  868. }
  869. }
  870. // Return value is errno, we have nothing to return.
  871. return Wasm::Result { Vector<Value> { Value(ValueType(ValueType::I32), 0ull) } };
  872. },
  873. FunctionType {
  874. move(arguments_types),
  875. { ValueType(ValueType::I32) },
  876. },
  877. function_name);
  878. }
  879. };
  880. };
  881. Errno errno_value_from_errno(int value)
  882. {
  883. switch (value) {
  884. #ifdef ESUCCESS
  885. case ESUCCESS:
  886. return Errno::Success;
  887. #endif
  888. case E2BIG:
  889. return Errno::TooBig;
  890. case EACCES:
  891. return Errno::Access;
  892. case EADDRINUSE:
  893. return Errno::AddressInUse;
  894. case EADDRNOTAVAIL:
  895. return Errno::AddressNotAvailable;
  896. case EAFNOSUPPORT:
  897. return Errno::AFNotSupported;
  898. case EAGAIN:
  899. return Errno::Again;
  900. case EALREADY:
  901. return Errno::Already;
  902. case EBADF:
  903. return Errno::BadF;
  904. case EBUSY:
  905. return Errno::Busy;
  906. case ECANCELED:
  907. return Errno::Canceled;
  908. case ECHILD:
  909. return Errno::Child;
  910. case ECONNABORTED:
  911. return Errno::ConnectionAborted;
  912. case ECONNREFUSED:
  913. return Errno::ConnectionRefused;
  914. case ECONNRESET:
  915. return Errno::ConnectionReset;
  916. case EDEADLK:
  917. return Errno::Deadlock;
  918. case EDESTADDRREQ:
  919. return Errno::DestinationAddressRequired;
  920. case EDOM:
  921. return Errno::Domain;
  922. case EEXIST:
  923. return Errno::Exist;
  924. case EFAULT:
  925. return Errno::Fault;
  926. case EFBIG:
  927. return Errno::FBig;
  928. case EHOSTUNREACH:
  929. return Errno::HostUnreachable;
  930. case EILSEQ:
  931. return Errno::IllegalSequence;
  932. case EINPROGRESS:
  933. return Errno::InProgress;
  934. case EINTR:
  935. return Errno::Interrupted;
  936. case EINVAL:
  937. return Errno::Invalid;
  938. case EIO:
  939. return Errno::IO;
  940. case EISCONN:
  941. return Errno::IsConnected;
  942. case EISDIR:
  943. return Errno::IsDirectory;
  944. case ELOOP:
  945. return Errno::Loop;
  946. case EMFILE:
  947. return Errno::MFile;
  948. case EMLINK:
  949. return Errno::MLink;
  950. case EMSGSIZE:
  951. return Errno::MessageSize;
  952. case ENAMETOOLONG:
  953. return Errno::NameTooLong;
  954. case ENETDOWN:
  955. return Errno::NetworkDown;
  956. case ENETRESET:
  957. return Errno::NetworkReset;
  958. case ENETUNREACH:
  959. return Errno::NetworkUnreachable;
  960. case ENFILE:
  961. return Errno::NFile;
  962. case ENOBUFS:
  963. return Errno::NoBufferSpace;
  964. case ENODEV:
  965. return Errno::NoDevice;
  966. case ENOENT:
  967. return Errno::NoEntry;
  968. case ENOEXEC:
  969. return Errno::NoExec;
  970. case ENOLCK:
  971. return Errno::NoLock;
  972. case ENOMEM:
  973. return Errno::NoMemory;
  974. case ENOPROTOOPT:
  975. return Errno::NoProtocolOption;
  976. case ENOSPC:
  977. return Errno::NoSpace;
  978. case ENOSYS:
  979. return Errno::NoSys;
  980. case ENOTCONN:
  981. return Errno::NotConnected;
  982. case ENOTDIR:
  983. return Errno::NotDirectory;
  984. case ENOTEMPTY:
  985. return Errno::NotEmpty;
  986. case ENOTRECOVERABLE:
  987. return Errno::NotRecoverable;
  988. case ENOTSOCK:
  989. return Errno::NotSocket;
  990. case ENOTSUP:
  991. return Errno::NotSupported;
  992. case ENOTTY:
  993. return Errno::NoTTY;
  994. case ENXIO:
  995. return Errno::NXIO;
  996. case EOVERFLOW:
  997. return Errno::Overflow;
  998. case EPERM:
  999. return Errno::Permission;
  1000. case EPIPE:
  1001. return Errno::Pipe;
  1002. case EPROTO:
  1003. return Errno::Protocol;
  1004. case EPROTONOSUPPORT:
  1005. return Errno::ProtocolNotSupported;
  1006. case EPROTOTYPE:
  1007. return Errno::ProtocolType;
  1008. case ERANGE:
  1009. return Errno::Range;
  1010. case ESPIPE:
  1011. return Errno::SPipe;
  1012. case ESRCH:
  1013. return Errno::SRCH;
  1014. case ESTALE:
  1015. return Errno::Stale;
  1016. case ETIMEDOUT:
  1017. return Errno::TimedOut;
  1018. case ETXTBSY:
  1019. return Errno::TextBusy;
  1020. case EXDEV:
  1021. return Errno::XDev;
  1022. default:
  1023. return Errno::Invalid;
  1024. }
  1025. }
  1026. FileType file_type_of(struct stat const& buf)
  1027. {
  1028. switch (buf.st_mode & S_IFMT) {
  1029. case S_IFDIR:
  1030. return FileType::Directory;
  1031. case S_IFCHR:
  1032. return FileType::CharacterDevice;
  1033. case S_IFBLK:
  1034. return FileType::BlockDevice;
  1035. case S_IFREG:
  1036. return FileType::RegularFile;
  1037. case S_IFIFO:
  1038. return FileType::Unknown; // FIXME: FileType::Pipe is currently not present in WASI (but it should be) so we use Unknown for now.
  1039. case S_IFLNK:
  1040. return FileType::SymbolicLink;
  1041. case S_IFSOCK:
  1042. return FileType::SocketStream;
  1043. default:
  1044. return FileType::Unknown;
  1045. }
  1046. }
  1047. FDFlags fd_flags_of(struct stat const&)
  1048. {
  1049. FDFlags::Bits result {};
  1050. return FDFlags { result };
  1051. }
  1052. }
  1053. namespace AK {
  1054. template<>
  1055. struct Formatter<Wasm::Value> : AK::Formatter<FormatString> {
  1056. ErrorOr<void> format(FormatBuilder& builder, Wasm::Value const& value)
  1057. {
  1058. return value.value().visit(
  1059. [&](Wasm::Reference const&) {
  1060. return Formatter<FormatString>::format(builder, "({}) &r"sv, Wasm::ValueType::kind_name(value.type().kind()));
  1061. },
  1062. [&](auto const& v) {
  1063. return Formatter<FormatString>::format(builder, "({}) {}"sv, Wasm::ValueType::kind_name(value.type().kind()), v);
  1064. });
  1065. }
  1066. };
  1067. template<>
  1068. struct Formatter<Wasm::Wasi::Errno> : AK::Formatter<FormatString> {
  1069. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Errno const& value)
  1070. {
  1071. return Formatter<FormatString>::format(builder, "{}"sv, to_underlying(value));
  1072. }
  1073. };
  1074. template<>
  1075. struct Formatter<Empty> : AK::Formatter<FormatString> {
  1076. ErrorOr<void> format(FormatBuilder&, Empty)
  1077. {
  1078. return {};
  1079. }
  1080. };
  1081. template<typename T>
  1082. struct Formatter<Wasm::Wasi::Result<T>> : AK::Formatter<FormatString> {
  1083. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::Result<T> const& value)
  1084. {
  1085. if (value.is_error())
  1086. return Formatter<FormatString>::format(builder, "Error({})"sv, *value.error());
  1087. return Formatter<FormatString>::format(builder, "Ok({})"sv, *value.result());
  1088. }
  1089. };
  1090. template<OneOf<Wasm::Wasi::ArgsSizes, Wasm::Wasi::EnvironSizes> T>
  1091. struct Formatter<T> : AK::Formatter<FormatString> {
  1092. ErrorOr<void> format(FormatBuilder& builder, T const& value)
  1093. {
  1094. return Formatter<FormatString>::format(builder, "size={}, count={}"sv, value.size, value.count);
  1095. }
  1096. };
  1097. template<>
  1098. struct Formatter<Wasm::Wasi::FDStat> : AK::Formatter<FormatString> {
  1099. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FDStat const&)
  1100. {
  1101. return Formatter<FormatString>::format(builder, "(rights)"sv);
  1102. }
  1103. };
  1104. template<>
  1105. struct Formatter<Wasm::Wasi::FileStat> : AK::Formatter<FormatString> {
  1106. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::FileStat const& value)
  1107. {
  1108. return Formatter<FormatString>::format(builder, "dev={}, ino={}, ft={}, nlink={}, size={}, atim={}, mtim={}, ctim={}"sv,
  1109. value.dev, value.ino, to_underlying(value.filetype), value.nlink, value.size, value.atim, value.mtim, value.ctim);
  1110. }
  1111. };
  1112. template<>
  1113. struct Formatter<Wasm::Wasi::PreStat> : AK::Formatter<FormatString> {
  1114. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::PreStat const& value)
  1115. {
  1116. return Formatter<FormatString>::format(builder, "length={}"sv, value.dir.pr_name_len);
  1117. }
  1118. };
  1119. template<>
  1120. struct Formatter<Wasm::Wasi::SockRecvResult> : AK::Formatter<FormatString> {
  1121. ErrorOr<void> format(FormatBuilder& builder, Wasm::Wasi::SockRecvResult const& value)
  1122. {
  1123. return Formatter<FormatString>::format(builder, "size={}"sv, value.size);
  1124. }
  1125. };
  1126. }