120-fs-add-dup2-function.patch 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. From: Felix Fietkau <[email protected]>
  2. Date: Wed, 8 Oct 2025 22:15:42 +0200
  3. Subject: [PATCH] fs: add dup2() function
  4. Add dup2() function to duplicate file descriptors, useful for redirecting
  5. standard streams in child processes.
  6. Signed-off-by: Felix Fietkau <[email protected]>
  7. ---
  8. --- a/lib/fs.c
  9. +++ b/lib/fs.c
  10. @@ -1278,6 +1278,54 @@ uc_fs_fdopen(uc_vm_t *vm, size_t nargs)
  11. return ucv_resource_create(vm, "fs.file", fp);
  12. }
  13. +/**
  14. + * Duplicates a file descriptor.
  15. + *
  16. + * This function duplicates the file descriptor `oldfd` to `newfd`. If `newfd`
  17. + * was previously open, it is silently closed before being reused.
  18. + *
  19. + * Returns `true` on success.
  20. + * Returns `null` on error.
  21. + *
  22. + * @function module:fs#dup2
  23. + *
  24. + * @param {number} oldfd
  25. + * The file descriptor to duplicate.
  26. + *
  27. + * @param {number} newfd
  28. + * The file descriptor number to duplicate to.
  29. + *
  30. + * @returns {?boolean}
  31. + *
  32. + * @example
  33. + * // Redirect stderr to a log file
  34. + * const logfile = open('/tmp/error.log', 'w');
  35. + * dup2(logfile.fileno(), 2);
  36. + * logfile.close();
  37. + */
  38. +static uc_value_t *
  39. +uc_fs_dup2(uc_vm_t *vm, size_t nargs)
  40. +{
  41. + uc_value_t *oldfd_arg = uc_fn_arg(0);
  42. + uc_value_t *newfd_arg = uc_fn_arg(1);
  43. + int oldfd, newfd;
  44. +
  45. + oldfd = get_fd(vm, oldfd_arg);
  46. +
  47. + if (oldfd == -1)
  48. + err_return(errno ? errno : EBADF);
  49. +
  50. + newfd = get_fd(vm, newfd_arg);
  51. +
  52. + if (newfd == -1)
  53. + err_return(errno ? errno : EBADF);
  54. +
  55. + if (dup2(oldfd, newfd) == -1)
  56. + err_return(errno);
  57. +
  58. + return ucv_boolean_new(true);
  59. +}
  60. +
  61. /**
  62. * Represents a handle for interacting with a directory opened by `opendir()`.
  63. @@ -2890,6 +2938,7 @@ static const uc_function_list_t global_f
  64. { "error", uc_fs_error },
  65. { "open", uc_fs_open },
  66. { "fdopen", uc_fs_fdopen },
  67. + { "dup2", uc_fs_dup2 },
  68. { "opendir", uc_fs_opendir },
  69. { "popen", uc_fs_popen },
  70. { "readlink", uc_fs_readlink },