Wasi.cpp 36 KB

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