Wasi.cpp 46 KB

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