CSystemWASI.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. This source file is part of the Swift System open source project
  3. Copyright (c) 2024 - 2025 Apple Inc. and the Swift System project authors
  4. Licensed under Apache License v2.0 with Runtime Library Exception
  5. See https://swift.org/LICENSE.txt for license information
  6. */
  7. #pragma once
  8. #if __wasi__
  9. #include <dirent.h>
  10. #include <errno.h>
  11. #include <fcntl.h>
  12. #include <limits.h> // For NAME_MAX
  13. // wasi-libc defines the following constants in a way that Clang Importer can't
  14. // understand, so we need to expose them manually.
  15. static inline int32_t _getConst_O_ACCMODE(void) { return O_ACCMODE; }
  16. static inline int32_t _getConst_O_APPEND(void) { return O_APPEND; }
  17. static inline int32_t _getConst_O_CREAT(void) { return O_CREAT; }
  18. static inline int32_t _getConst_O_DIRECTORY(void) { return O_DIRECTORY; }
  19. static inline int32_t _getConst_O_EXCL(void) { return O_EXCL; }
  20. static inline int32_t _getConst_O_NONBLOCK(void) { return O_NONBLOCK; }
  21. static inline int32_t _getConst_O_TRUNC(void) { return O_TRUNC; }
  22. static inline int32_t _getConst_O_WRONLY(void) { return O_WRONLY; }
  23. static inline int32_t _getConst_EWOULDBLOCK(void) { return EWOULDBLOCK; }
  24. static inline int32_t _getConst_EOPNOTSUPP(void) { return EOPNOTSUPP; }
  25. static inline uint8_t _getConst_DT_DIR(void) { return DT_DIR; }
  26. // Modified dirent struct that can be imported to Swift
  27. struct _system_dirent {
  28. ino_t d_ino;
  29. unsigned char d_type;
  30. // char d_name[] cannot be imported to Swift
  31. char d_name[NAME_MAX + 1];
  32. };
  33. // Convert WASI dirent with d_name[] to _system_dirent
  34. static inline
  35. struct _system_dirent *
  36. _system_dirent_from_wasi_dirent(const struct dirent *wasi_dirent) {
  37. // Match readdir behavior and use thread-local storage for the converted dirent
  38. static __thread struct _system_dirent _converted_dirent;
  39. if (wasi_dirent == NULL) {
  40. return NULL;
  41. }
  42. memset(&_converted_dirent, 0, sizeof(struct _system_dirent));
  43. _converted_dirent.d_ino = wasi_dirent->d_ino;
  44. _converted_dirent.d_type = wasi_dirent->d_type;
  45. strncpy(_converted_dirent.d_name, wasi_dirent->d_name, NAME_MAX);
  46. _converted_dirent.d_name[NAME_MAX] = '\0';
  47. return &_converted_dirent;
  48. }
  49. #endif