Ruby 4.1.0dev (2026-11-18 revision 9de06831e37534f8a163e598cc0c6903c7687430)
process.c (9de06831e37534f8a163e598cc0c6903c7687430)
1/**********************************************************************
2
3 process.c -
4
5 $Author$
6 created at: Tue Aug 10 14:30:50 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15
17
18#include <ctype.h>
19#include <errno.h>
20#include <signal.h>
21#include <stdarg.h>
22#include <stdio.h>
23#include <time.h>
24
25#ifdef HAVE_STDLIB_H
26# include <stdlib.h>
27#endif
28
29#ifdef HAVE_UNISTD_H
30# include <unistd.h>
31#endif
32
33#ifdef HAVE_FCNTL_H
34# include <fcntl.h>
35#endif
36
37#ifdef HAVE_PROCESS_H
38# include <process.h>
39#endif
40
41#ifndef EXIT_SUCCESS
42# define EXIT_SUCCESS 0
43#endif
44
45#ifndef EXIT_FAILURE
46# define EXIT_FAILURE 1
47#endif
48
49#ifdef HAVE_SYS_WAIT_H
50# include <sys/wait.h>
51#endif
52
53#ifdef HAVE_SYS_RESOURCE_H
54# include <sys/resource.h>
55#endif
56
57#ifdef HAVE_VFORK_H
58# include <vfork.h>
59#endif
60
61#ifdef HAVE_SYS_PARAM_H
62# include <sys/param.h>
63#endif
64
65#ifndef MAXPATHLEN
66# define MAXPATHLEN 1024
67#endif
68
69#include <sys/stat.h>
70
71#ifdef HAVE_SYS_TIME_H
72# include <sys/time.h>
73#endif
74
75#ifdef HAVE_SYS_TIMES_H
76# include <sys/times.h>
77#endif
78
79#ifdef HAVE_PWD_H
80# include <pwd.h>
81#endif
82
83#ifdef HAVE_GRP_H
84# include <grp.h>
85# ifdef __CYGWIN__
86int initgroups(const char *, rb_gid_t);
87# endif
88#endif
89
90#ifdef HAVE_SYS_ID_H
91# include <sys/id.h>
92#endif
93
94#ifdef __APPLE__
95# include <mach/mach_time.h>
96#endif
97
98#include "dln.h"
99#include "hrtime.h"
100#include "internal.h"
101#include "internal/bits.h"
102#include "internal/dir.h"
103#include "internal/error.h"
104#include "internal/eval.h"
105#include "internal/hash.h"
106#include "internal/io.h"
107#include "internal/numeric.h"
108#include "internal/object.h"
109#include "internal/process.h"
110#include "internal/thread.h"
111#include "internal/variable.h"
112#include "internal/warnings.h"
113#include "ruby/io.h"
114#include "ruby/st.h"
115#include "ruby/thread.h"
116#include "ruby/util.h"
117#include "ractor_core.h"
118#include "vm_core.h"
119#include "vm_sync.h"
120#include "ruby/ractor.h"
121
122/* define system APIs */
123#ifdef _WIN32
124#undef open
125#define open rb_w32_uopen
126#endif
127
128#if defined(HAVE_TIMES)
129/*********************************************************************
130 *
131 * Document-class: Process::Tms
132 *
133 * Placeholder for rusage
134 */
135static VALUE rb_cProcessTms;
136#endif
137
138#ifndef WIFEXITED
139#define WIFEXITED(w) (((w) & 0xff) == 0)
140#endif
141#ifndef WIFSIGNALED
142#define WIFSIGNALED(w) (((w) & 0x7f) > 0 && (((w) & 0x7f) < 0x7f))
143#endif
144#ifndef WIFSTOPPED
145#define WIFSTOPPED(w) (((w) & 0xff) == 0x7f)
146#endif
147#ifndef WEXITSTATUS
148#define WEXITSTATUS(w) (((w) >> 8) & 0xff)
149#endif
150#ifndef WTERMSIG
151#define WTERMSIG(w) ((w) & 0x7f)
152#endif
153#ifndef WSTOPSIG
154#define WSTOPSIG WEXITSTATUS
155#endif
156
157#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
158#define HAVE_44BSD_SETUID 1
159#define HAVE_44BSD_SETGID 1
160#endif
161
162#ifdef __NetBSD__
163#undef HAVE_SETRUID
164#undef HAVE_SETRGID
165#endif
166
167#if defined(HAVE_44BSD_SETUID) || defined(__APPLE__)
168#if !defined(USE_SETREUID)
169#define OBSOLETE_SETREUID 1
170#endif
171#if !defined(USE_SETREGID)
172#define OBSOLETE_SETREGID 1
173#endif
174#endif
175
176static void check_uid_switch(void);
177static void check_gid_switch(void);
178static int exec_async_signal_safe(const struct rb_execarg *, char *, size_t);
179
180VALUE rb_envtbl(void);
181VALUE rb_env_to_hash(void);
182
183#if 1
184#define p_uid_from_name p_uid_from_name
185#define p_gid_from_name p_gid_from_name
186#endif
187
188#if defined(HAVE_UNISTD_H)
189# if defined(HAVE_GETLOGIN_R)
190# define USE_GETLOGIN_R 1
191# define GETLOGIN_R_SIZE_DEFAULT 0x100
192# define GETLOGIN_R_SIZE_LIMIT 0x1000
193# if defined(_SC_LOGIN_NAME_MAX)
194# define GETLOGIN_R_SIZE_INIT sysconf(_SC_LOGIN_NAME_MAX)
195# else
196# define GETLOGIN_R_SIZE_INIT GETLOGIN_R_SIZE_DEFAULT
197# endif
198# elif defined(HAVE_GETLOGIN)
199# define USE_GETLOGIN 1
200# endif
201#endif
202
203#if defined(HAVE_PWD_H)
204# if defined(HAVE_GETPWUID_R)
205# define USE_GETPWUID_R 1
206# elif defined(HAVE_GETPWUID)
207# define USE_GETPWUID 1
208# endif
209# if defined(HAVE_GETPWNAM_R)
210# define USE_GETPWNAM_R 1
211# elif defined(HAVE_GETPWNAM)
212# define USE_GETPWNAM 1
213# endif
214# if defined(HAVE_GETPWNAM_R) || defined(HAVE_GETPWUID_R)
215# define GETPW_R_SIZE_DEFAULT 0x1000
216# define GETPW_R_SIZE_LIMIT 0x10000
217# if defined(_SC_GETPW_R_SIZE_MAX)
218# define GETPW_R_SIZE_INIT sysconf(_SC_GETPW_R_SIZE_MAX)
219# else
220# define GETPW_R_SIZE_INIT GETPW_R_SIZE_DEFAULT
221# endif
222# endif
223# ifdef USE_GETPWNAM_R
224# define PREPARE_GETPWNAM \
225 VALUE getpw_buf = 0
226# define FINISH_GETPWNAM \
227 (getpw_buf ? (void)rb_str_resize(getpw_buf, 0) : (void)0)
228# define OBJ2UID1(id) obj2uid((id), &getpw_buf)
229# define OBJ2UID(id) obj2uid0(id)
230static rb_uid_t obj2uid(VALUE id, VALUE *getpw_buf);
231static inline rb_uid_t
232obj2uid0(VALUE id)
233{
234 rb_uid_t uid;
235 PREPARE_GETPWNAM;
236 uid = OBJ2UID1(id);
237 FINISH_GETPWNAM;
238 return uid;
239}
240# else
241# define PREPARE_GETPWNAM /* do nothing */
242# define FINISH_GETPWNAM /* do nothing */
243# define OBJ2UID1(id) obj2uid((id))
244# define OBJ2UID(id) obj2uid((id))
245static rb_uid_t obj2uid(VALUE id);
246# endif
247#else
248# define PREPARE_GETPWNAM /* do nothing */
249# define FINISH_GETPWNAM /* do nothing */
250# define OBJ2UID1(id) NUM2UIDT(id)
251# define OBJ2UID(id) NUM2UIDT(id)
252# ifdef p_uid_from_name
253# undef p_uid_from_name
254# define p_uid_from_name rb_f_notimplement
255# endif
256#endif
257
258#if defined(HAVE_GRP_H)
259# if defined(HAVE_GETGRNAM_R) && defined(_SC_GETGR_R_SIZE_MAX)
260# define USE_GETGRNAM_R
261# define GETGR_R_SIZE_INIT sysconf(_SC_GETGR_R_SIZE_MAX)
262# define GETGR_R_SIZE_DEFAULT 0x1000
263# define GETGR_R_SIZE_LIMIT 0x10000
264# endif
265# ifdef USE_GETGRNAM_R
266# define PREPARE_GETGRNAM \
267 VALUE getgr_buf = 0
268# define FINISH_GETGRNAM \
269 (getgr_buf ? (void)rb_str_resize(getgr_buf, 0) : (void)0)
270# define OBJ2GID1(id) obj2gid((id), &getgr_buf)
271# define OBJ2GID(id) obj2gid0(id)
272static rb_gid_t obj2gid(VALUE id, VALUE *getgr_buf);
273static inline rb_gid_t
274obj2gid0(VALUE id)
275{
276 rb_gid_t gid;
277 PREPARE_GETGRNAM;
278 gid = OBJ2GID1(id);
279 FINISH_GETGRNAM;
280 return gid;
281}
282static rb_gid_t obj2gid(VALUE id, VALUE *getgr_buf);
283# else
284# define PREPARE_GETGRNAM /* do nothing */
285# define FINISH_GETGRNAM /* do nothing */
286# define OBJ2GID1(id) obj2gid((id))
287# define OBJ2GID(id) obj2gid((id))
288static rb_gid_t obj2gid(VALUE id);
289# endif
290#else
291# define PREPARE_GETGRNAM /* do nothing */
292# define FINISH_GETGRNAM /* do nothing */
293# define OBJ2GID1(id) NUM2GIDT(id)
294# define OBJ2GID(id) NUM2GIDT(id)
295# ifdef p_gid_from_name
296# undef p_gid_from_name
297# define p_gid_from_name rb_f_notimplement
298# endif
299#endif
300
301#if SIZEOF_CLOCK_T == SIZEOF_INT
302typedef unsigned int unsigned_clock_t;
303#elif SIZEOF_CLOCK_T == SIZEOF_LONG
304typedef unsigned long unsigned_clock_t;
305#elif defined(HAVE_LONG_LONG) && SIZEOF_CLOCK_T == SIZEOF_LONG_LONG
306typedef unsigned LONG_LONG unsigned_clock_t;
307#endif
308#ifndef HAVE_SIG_T
309typedef void (*sig_t) (int);
310#endif
311
312#define id_exception idException
313static ID id_in, id_out, id_err, id_pid, id_uid, id_gid;
314static ID id_close, id_child;
315#ifdef HAVE_SETPGID
316static ID id_pgroup;
317#endif
318#ifdef _WIN32
319static ID id_new_pgroup;
320#endif
321static ID id_unsetenv_others, id_chdir, id_umask, id_close_others;
322static ID id_nanosecond, id_microsecond, id_millisecond, id_second;
323static ID id_float_microsecond, id_float_millisecond, id_float_second;
324static ID id_GETTIMEOFDAY_BASED_CLOCK_REALTIME, id_TIME_BASED_CLOCK_REALTIME;
325#ifdef CLOCK_REALTIME
326static ID id_CLOCK_REALTIME;
327# define RUBY_CLOCK_REALTIME ID2SYM(id_CLOCK_REALTIME)
328#endif
329#ifdef CLOCK_MONOTONIC
330static ID id_CLOCK_MONOTONIC;
331# define RUBY_CLOCK_MONOTONIC ID2SYM(id_CLOCK_MONOTONIC)
332#endif
333#ifdef CLOCK_PROCESS_CPUTIME_ID
334static ID id_CLOCK_PROCESS_CPUTIME_ID;
335# define RUBY_CLOCK_PROCESS_CPUTIME_ID ID2SYM(id_CLOCK_PROCESS_CPUTIME_ID)
336#endif
337#ifdef CLOCK_THREAD_CPUTIME_ID
338static ID id_CLOCK_THREAD_CPUTIME_ID;
339# define RUBY_CLOCK_THREAD_CPUTIME_ID ID2SYM(id_CLOCK_THREAD_CPUTIME_ID)
340#endif
341#ifdef HAVE_TIMES
342static ID id_TIMES_BASED_CLOCK_MONOTONIC;
343static ID id_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID;
344#endif
345#ifdef RUSAGE_SELF
346static ID id_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID;
347#endif
348static ID id_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID;
349#ifdef __APPLE__
350static ID id_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC;
351# define RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC ID2SYM(id_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC)
352#endif
353static ID id_hertz;
354#ifdef HAVE_WORKING_FORK
355static ID id__fork;
356#endif
357
358static rb_pid_t cached_pid;
359
360/* execv and execl are async-signal-safe since SUSv4 (POSIX.1-2008, XPG7) */
361#if defined(__sun) && !defined(_XPG7) /* Solaris 10, 9, ... */
362#define execv(path, argv) (rb_async_bug_errno("unreachable: async-signal-unsafe execv() is called", 0))
363#define execl(path, arg0, arg1, arg2, term) do { extern char **environ; execle((path), (arg0), (arg1), (arg2), (term), (environ)); } while (0)
364#define ALWAYS_NEED_ENVP 1
365#else
366#define ALWAYS_NEED_ENVP 0
367#endif
368
369static void
370assert_close_on_exec(int fd)
371{
372#if VM_CHECK_MODE > 0
373#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(FD_CLOEXEC)
374 int flags = fcntl(fd, F_GETFD);
375 if (flags == -1) {
376 static const char m[] = "reserved FD closed unexpectedly?\n";
377 (void)!write(2, m, sizeof(m) - 1);
378 return;
379 }
380 if (flags & FD_CLOEXEC) return;
381 rb_bug("reserved FD did not have close-on-exec set");
382#else
383 rb_bug("reserved FD without close-on-exec support");
384#endif /* FD_CLOEXEC */
385#endif /* VM_CHECK_MODE */
386}
387
388static inline int
389close_unless_reserved(int fd)
390{
391 if (rb_reserved_fd_p(fd)) { /* async-signal-safe */
392 assert_close_on_exec(fd);
393 return 0;
394 }
395 return close(fd); /* async-signal-safe */
396}
397
398/*#define DEBUG_REDIRECT*/
399#if defined(DEBUG_REDIRECT)
400
401static void
402ttyprintf(const char *fmt, ...)
403{
404 va_list ap;
405 FILE *tty;
406 int save = errno;
407#ifdef _WIN32
408 tty = fopen("con", "w");
409#else
410 tty = fopen("/dev/tty", "w");
411#endif
412 if (!tty)
413 return;
414
415 va_start(ap, fmt);
416 vfprintf(tty, fmt, ap);
417 va_end(ap);
418 fclose(tty);
419 errno = save;
420}
421
422static int
423redirect_dup(int oldfd)
424{
425 int ret;
426 ret = dup(oldfd);
427 ttyprintf("dup(%d) => %d\n", oldfd, ret);
428 return ret;
429}
430
431static int
432redirect_dup2(int oldfd, int newfd)
433{
434 int ret;
435 ret = dup2(oldfd, newfd);
436 ttyprintf("dup2(%d, %d) => %d\n", oldfd, newfd, ret);
437 return ret;
438}
439
440static int
441redirect_cloexec_dup(int oldfd)
442{
443 int ret;
444 ret = rb_cloexec_dup(oldfd);
445 ttyprintf("cloexec_dup(%d) => %d\n", oldfd, ret);
446 return ret;
447}
448
449static int
450redirect_cloexec_dup2(int oldfd, int newfd)
451{
452 int ret;
453 ret = rb_cloexec_dup2(oldfd, newfd);
454 ttyprintf("cloexec_dup2(%d, %d) => %d\n", oldfd, newfd, ret);
455 return ret;
456}
457
458static int
459redirect_close(int fd)
460{
461 int ret;
462 ret = close_unless_reserved(fd);
463 ttyprintf("close(%d) => %d\n", fd, ret);
464 return ret;
465}
466
467static int
468parent_redirect_open(const char *pathname, int flags, mode_t perm)
469{
470 int ret;
471 ret = rb_cloexec_open(pathname, flags, perm);
472 ttyprintf("parent_open(\"%s\", 0x%x, 0%o) => %d\n", pathname, flags, perm, ret);
473 return ret;
474}
475
476static int
477parent_redirect_close(int fd)
478{
479 int ret;
480 ret = close_unless_reserved(fd);
481 ttyprintf("parent_close(%d) => %d\n", fd, ret);
482 return ret;
483}
484
485#else
486#define redirect_dup(oldfd) dup(oldfd)
487#define redirect_dup2(oldfd, newfd) dup2((oldfd), (newfd))
488#define redirect_cloexec_dup(oldfd) rb_cloexec_dup(oldfd)
489#define redirect_cloexec_dup2(oldfd, newfd) rb_cloexec_dup2((oldfd), (newfd))
490#define redirect_close(fd) close_unless_reserved(fd)
491#define parent_redirect_open(pathname, flags, perm) rb_cloexec_open((pathname), (flags), (perm))
492#define parent_redirect_close(fd) close_unless_reserved(fd)
493#endif
494
495static VALUE
496get_pid(void)
497{
498 if (UNLIKELY(!cached_pid)) { /* 0 is not a valid pid */
499 cached_pid = getpid();
500 }
501 /* pid should be likely POSFIXABLE() */
502 return PIDT2NUM(cached_pid);
503}
504
505#if defined HAVE_WORKING_FORK || defined HAVE_DAEMON
506static void
507clear_pid_cache(void)
508{
509 cached_pid = 0;
510}
511#endif
512
513/*
514 * call-seq:
515 * Process.pid -> integer
516 *
517 * Returns the process ID of the current process:
518 *
519 * Process.pid # => 15668
520 *
521 */
522
523static VALUE
524proc_get_pid(VALUE _)
525{
526 return get_pid();
527}
528
529static VALUE
530get_ppid(void)
531{
532 return PIDT2NUM(getppid());
533}
534
535/*
536 * call-seq:
537 * Process.ppid -> integer
538 *
539 * Returns the process ID of the parent of the current process:
540 *
541 * puts "Pid is #{Process.pid}."
542 * fork { puts "Parent pid is #{Process.ppid}." }
543 *
544 * Output:
545 *
546 * Pid is 271290.
547 * Parent pid is 271290.
548 *
549 * May not return a trustworthy value on certain platforms.
550 */
551
552static VALUE
553proc_get_ppid(VALUE _)
554{
555 return get_ppid();
556}
557
558
559/*********************************************************************
560 *
561 * Document-class: Process::Status
562 *
563 * A Process::Status contains information about a system process.
564 *
565 * Thread-local variable <tt>$?</tt> is initially +nil+.
566 * Some methods assign to it a Process::Status object
567 * that represents a system process (either running or terminated):
568 *
569 * `ruby -e "exit 99"`
570 * stat = $? # => #<Process::Status: pid 1262862 exit 99>
571 * stat.class # => Process::Status
572 * stat.to_i # => 25344
573 * stat.stopped? # => false
574 * stat.exited? # => true
575 * stat.exitstatus # => 99
576 *
577 */
578
579static VALUE rb_cProcessStatus;
580
582 rb_pid_t pid;
583 int status;
584 int error;
585};
586
587static const rb_data_type_t rb_process_status_type = {
588 .wrap_struct_name = "Process::Status",
589 .function = {
590 .dmark = NULL,
591 .dfree = RUBY_DEFAULT_FREE,
592 .dsize = NULL,
593 },
594 .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE | RUBY_TYPED_FROZEN_SHAREABLE,
595};
596
597static VALUE
598rb_process_status_allocate(VALUE klass)
599{
600 struct rb_process_status *data;
601 return TypedData_Make_Struct(klass, struct rb_process_status, &rb_process_status_type, data);
602}
603
604VALUE
606{
607 return GET_THREAD()->last_status;
608}
609
610/*
611 * call-seq:
612 * Process.last_status -> Process::Status or nil
613 *
614 * Returns a Process::Status object representing the most recently exited
615 * child process in the current thread, or +nil+ if none:
616 *
617 * Process.spawn('ruby', '-e', 'exit 13')
618 * Process.wait
619 * Process.last_status # => #<Process::Status: pid 14396 exit 13>
620 *
621 * Process.spawn('ruby', '-e', 'exit 14')
622 * Process.wait
623 * Process.last_status # => #<Process::Status: pid 4692 exit 14>
624 *
625 * Process.spawn('ruby', '-e', 'exit 15')
626 * # 'exit 15' has not been reaped by #wait.
627 * Process.last_status # => #<Process::Status: pid 4692 exit 14>
628 * Process.wait
629 * Process.last_status # => #<Process::Status: pid 1380 exit 15>
630 *
631 */
632static VALUE
633proc_s_last_status(VALUE mod)
634{
635 return rb_last_status_get();
636}
637
638VALUE
639rb_process_status_for(rb_pid_t pid, int status, int error)
640{
641 VALUE last_status = rb_process_status_allocate(rb_cProcessStatus);
642 struct rb_process_status *data = RTYPEDDATA_GET_DATA(last_status);
643 data->pid = pid;
644 data->status = status;
645 data->error = error;
646
647 rb_obj_freeze(last_status);
648 return last_status;
649}
650
651static VALUE
652process_status_dump(VALUE status)
653{
654 VALUE dump = rb_class_allocate_instance_capa(rb_cObject, 2);
655 struct rb_process_status *data;
656 TypedData_Get_Struct(status, struct rb_process_status, &rb_process_status_type, data);
657 if (data->pid) {
658 rb_ivar_set(dump, id_status, INT2NUM(data->status));
659 rb_ivar_set(dump, id_pid, PIDT2NUM(data->pid));
660 }
661 return dump;
662}
663
664static VALUE
665process_status_load(VALUE real_obj, VALUE load_obj)
666{
667 struct rb_process_status *data = rb_check_typeddata(real_obj, &rb_process_status_type);
668 VALUE status = rb_attr_get(load_obj, id_status);
669 VALUE pid = rb_attr_get(load_obj, id_pid);
670 data->pid = NIL_P(pid) ? 0 : NUM2PIDT(pid);
671 data->status = NIL_P(status) ? 0 : NUM2INT(status);
672 return real_obj;
673}
674
675void
676rb_last_status_set(int status, rb_pid_t pid)
677{
678 GET_THREAD()->last_status = rb_process_status_for(pid, status, 0);
679}
680
681static void
682last_status_clear(rb_thread_t *th)
683{
684 th->last_status = Qnil;
685}
686
687void
688rb_last_status_clear(void)
689{
690 last_status_clear(GET_THREAD());
691}
692
693static rb_pid_t
694pst_pid(VALUE status)
695{
696 struct rb_process_status *data;
697 TypedData_Get_Struct(status, struct rb_process_status, &rb_process_status_type, data);
698 return data->pid;
699}
700
701static int
702pst_status(VALUE status)
703{
704 struct rb_process_status *data;
705 TypedData_Get_Struct(status, struct rb_process_status, &rb_process_status_type, data);
706 return data->status;
707}
708
709/*
710 * call-seq:
711 * to_i -> integer
712 *
713 * Returns the system-dependent integer status of +self+:
714 *
715 * `cat /nop`
716 * $?.to_i # => 256
717 */
718
719static VALUE
720pst_to_i(VALUE self)
721{
722 int status = pst_status(self);
723 return RB_INT2NUM(status);
724}
725
726#define PST2INT(st) pst_status(st)
727
728/*
729 * call-seq:
730 * pid -> integer
731 *
732 * Returns the process ID of the process:
733 *
734 * system("false")
735 * $?.pid # => 1247002
736 *
737 */
738
739static VALUE
740pst_pid_m(VALUE self)
741{
742 rb_pid_t pid = pst_pid(self);
743 return PIDT2NUM(pid);
744}
745
746static VALUE pst_message_status(VALUE str, int status);
747
748static void
749pst_message(VALUE str, rb_pid_t pid, int status)
750{
751 rb_str_catf(str, "pid %ld", (long)pid);
752 pst_message_status(str, status);
753}
754
755static VALUE
756pst_message_status(VALUE str, int status)
757{
758 if (WIFSTOPPED(status)) {
759 int stopsig = WSTOPSIG(status);
760 const char *signame = ruby_signal_name(stopsig);
761 if (signame) {
762 rb_str_catf(str, " stopped SIG%s (signal %d)", signame, stopsig);
763 }
764 else {
765 rb_str_catf(str, " stopped signal %d", stopsig);
766 }
767 }
768 if (WIFSIGNALED(status)) {
769 int termsig = WTERMSIG(status);
770 const char *signame = ruby_signal_name(termsig);
771 if (signame) {
772 rb_str_catf(str, " SIG%s (signal %d)", signame, termsig);
773 }
774 else {
775 rb_str_catf(str, " signal %d", termsig);
776 }
777 }
778 if (WIFEXITED(status)) {
779 rb_str_catf(str, " exit %d", WEXITSTATUS(status));
780 }
781#ifdef WCOREDUMP
782 if (WCOREDUMP(status)) {
783 rb_str_cat2(str, " (core dumped)");
784 }
785#endif
786 return str;
787}
788
789
790/*
791 * call-seq:
792 * to_s -> string
793 *
794 * Returns a string representation of +self+:
795 *
796 * `cat /nop`
797 * $?.to_s # => "pid 1262141 exit 1"
798 *
799 *
800 */
801
802static VALUE
803pst_to_s(VALUE st)
804{
805 rb_pid_t pid;
806 int status;
807 VALUE str;
808
809 pid = pst_pid(st);
810 status = PST2INT(st);
811
812 str = rb_str_buf_new(0);
813 pst_message(str, pid, status);
814 return str;
815}
816
817
818/*
819 * call-seq:
820 * inspect -> string
821 *
822 * Returns a string representation of +self+:
823 *
824 * system("false")
825 * $?.inspect # => "#<Process::Status: pid 1303494 exit 1>"
826 *
827 */
828
829static VALUE
830pst_inspect(VALUE st)
831{
832 rb_pid_t pid;
833 int status;
834 VALUE str;
835
836 pid = pst_pid(st);
837 if (!pid) {
838 return rb_sprintf("#<%s: uninitialized>", rb_class2name(CLASS_OF(st)));
839 }
840 status = PST2INT(st);
841
842 str = rb_sprintf("#<%s: ", rb_class2name(CLASS_OF(st)));
843 pst_message(str, pid, status);
844 rb_str_cat2(str, ">");
845 return str;
846}
847
848
849/*
850 * call-seq:
851 * stat == other -> true or false
852 *
853 * Returns whether the value of #to_i == +other+:
854 *
855 * `cat /nop`
856 * stat = $? # => #<Process::Status: pid 1170366 exit 1>
857 * sprintf('%x', stat.to_i) # => "100"
858 * stat == 0x100 # => true
859 *
860 */
861
862static VALUE
863pst_equal(VALUE st1, VALUE st2)
864{
865 if (st1 == st2) return Qtrue;
866 return rb_equal(pst_to_i(st1), st2);
867}
868
869
870/*
871 * call-seq:
872 * stopped? -> true or false
873 *
874 * Returns +true+ if this process is stopped,
875 * and if the corresponding #wait call had the Process::WUNTRACED flag set,
876 * +false+ otherwise.
877 */
878
879static VALUE
880pst_wifstopped(VALUE st)
881{
882 int status = PST2INT(st);
883
884 return RBOOL(WIFSTOPPED(status));
885}
886
887
888/*
889 * call-seq:
890 * stopsig -> integer or nil
891 *
892 * Returns the number of the signal that caused the process to stop,
893 * or +nil+ if the process is not stopped.
894 */
895
896static VALUE
897pst_wstopsig(VALUE st)
898{
899 int status = PST2INT(st);
900
901 if (WIFSTOPPED(status))
902 return INT2NUM(WSTOPSIG(status));
903 return Qnil;
904}
905
906
907/*
908 * call-seq:
909 * signaled? -> true or false
910 *
911 * Returns +true+ if the process terminated because of an uncaught signal,
912 * +false+ otherwise.
913 */
914
915static VALUE
916pst_wifsignaled(VALUE st)
917{
918 int status = PST2INT(st);
919
920 return RBOOL(WIFSIGNALED(status));
921}
922
923
924/*
925 * call-seq:
926 * termsig -> integer or nil
927 *
928 * Returns the number of the signal that caused the process to terminate
929 * or +nil+ if the process was not terminated by an uncaught signal.
930 */
931
932static VALUE
933pst_wtermsig(VALUE st)
934{
935 int status = PST2INT(st);
936
937 if (WIFSIGNALED(status))
938 return INT2NUM(WTERMSIG(status));
939 return Qnil;
940}
941
942
943/*
944 * call-seq:
945 * exited? -> true or false
946 *
947 * Returns +true+ if the process exited normally
948 * (for example using an <code>exit()</code> call or finishing the
949 * program), +false+ if not.
950 */
951
952static VALUE
953pst_wifexited(VALUE st)
954{
955 int status = PST2INT(st);
956
957 return RBOOL(WIFEXITED(status));
958}
959
960
961/*
962 * call-seq:
963 * exitstatus -> integer or nil
964 *
965 * Returns the least significant eight bits of the return code
966 * of the process if it has exited;
967 * +nil+ otherwise:
968 *
969 * `exit 99`
970 * $?.exitstatus # => 99
971 *
972 */
973
974static VALUE
975pst_wexitstatus(VALUE st)
976{
977 int status = PST2INT(st);
978
979 if (WIFEXITED(status))
980 return INT2NUM(WEXITSTATUS(status));
981 return Qnil;
982}
983
984
985/*
986 * call-seq:
987 * success? -> true, false, or nil
988 *
989 * Returns:
990 *
991 * - +true+ if the process has completed successfully and exited.
992 * - +false+ if the process has completed unsuccessfully and exited.
993 * - +nil+ if the process has not exited.
994 *
995 */
996
997static VALUE
998pst_success_p(VALUE st)
999{
1000 int status = PST2INT(st);
1001
1002 if (!WIFEXITED(status))
1003 return Qnil;
1004 return RBOOL(WEXITSTATUS(status) == EXIT_SUCCESS);
1005}
1006
1007
1008/*
1009 * call-seq:
1010 * coredump? -> true or false
1011 *
1012 * Returns +true+ if the process generated a coredump
1013 * when it terminated, +false+ if not.
1014 *
1015 * Not available on all platforms.
1016 */
1017
1018static VALUE
1019pst_wcoredump(VALUE st)
1020{
1021#ifdef WCOREDUMP
1022 int status = PST2INT(st);
1023
1024 return RBOOL(WCOREDUMP(status));
1025#else
1026 return Qfalse;
1027#endif
1028}
1029
1030static rb_pid_t
1031do_waitpid(rb_pid_t pid, int *st, int flags)
1032{
1033#if defined HAVE_WAITPID
1034 return waitpid(pid, st, flags);
1035#elif defined HAVE_WAIT4
1036 return wait4(pid, st, flags, NULL);
1037#else
1038# error waitpid or wait4 is required.
1039#endif
1040}
1041
1043 struct ccan_list_node wnode;
1044 rb_execution_context_t *ec;
1045 rb_nativethread_cond_t *cond;
1046 rb_pid_t ret;
1047 rb_pid_t pid;
1048 int status;
1049 int options;
1050 int errnum;
1051};
1052
1053static void
1054waitpid_state_init(struct waitpid_state *w, rb_pid_t pid, int options)
1055{
1056 w->ret = 0;
1057 w->pid = pid;
1058 w->options = options;
1059 w->errnum = 0;
1060 w->status = 0;
1061}
1062
1063static void *
1064waitpid_blocking_no_SIGCHLD(void *x)
1065{
1066 struct waitpid_state *w = x;
1067
1068 w->ret = do_waitpid(w->pid, &w->status, w->options);
1069
1070 return 0;
1071}
1072
1073static void
1074waitpid_no_SIGCHLD(struct waitpid_state *w)
1075{
1076 if (w->options & WNOHANG) {
1077 w->ret = do_waitpid(w->pid, &w->status, w->options);
1078 }
1079 else {
1080 do {
1081 rb_thread_call_without_gvl(waitpid_blocking_no_SIGCHLD, w, RUBY_UBF_PROCESS, 0);
1082 } while (w->ret < 0 && errno == EINTR && (RUBY_VM_CHECK_INTS(w->ec),1));
1083 }
1084 if (w->ret == -1)
1085 w->errnum = errno;
1086}
1087
1088VALUE
1089rb_process_status_wait(rb_pid_t pid, int flags)
1090{
1091 // We only enter the scheduler if we are "blocking":
1092 if (!(flags & WNOHANG)) {
1093 VALUE scheduler = rb_fiber_scheduler_current();
1094 if (scheduler != Qnil) {
1095 VALUE result = rb_fiber_scheduler_process_wait(scheduler, pid, flags);
1096 if (!UNDEF_P(result)) return result;
1097 }
1098 }
1099
1101
1102 waitpid_state_init(&waitpid_state, pid, flags);
1103 waitpid_state.ec = GET_EC();
1104
1105 waitpid_no_SIGCHLD(&waitpid_state);
1106
1107 if (waitpid_state.ret == 0) return Qnil;
1108
1110}
1111
1112/*
1113 * call-seq:
1114 * Process::Status.wait(pid = -1, flags = 0) -> Process::Status
1115 *
1116 * Like Process.wait, but returns a Process::Status object
1117 * (instead of an integer pid or nil);
1118 * see Process.wait for the values of +pid+ and +flags+.
1119 *
1120 * If there are child processes,
1121 * waits for a child process to exit and returns a Process::Status object
1122 * containing information on that process.
1123 * Unlike Process.wait, this method does not set thread-local variable
1124 * <tt>$?</tt>:
1125 *
1126 * Process.spawn('cat /nop') # => 1155880
1127 * Process::Status.wait # => #<Process::Status: pid 1155880 exit 1>
1128 * $? # => nil # Not set.
1129 *
1130 * If there is no child process,
1131 * returns an "empty" Process::Status object
1132 * that does not represent an actual process:
1133 *
1134 * Process::Status.wait # => #<Process::Status: pid -1 exit 0>
1135 *
1136 * May invoke the scheduler hook Fiber::Scheduler#process_wait.
1137 *
1138 * Not available on all platforms.
1139 */
1140
1141static VALUE
1142rb_process_status_waitv(int argc, VALUE *argv, VALUE _)
1143{
1144 rb_check_arity(argc, 0, 2);
1145
1146 rb_pid_t pid = -1;
1147 int flags = 0;
1148
1149 if (argc >= 1) {
1150 pid = NUM2PIDT(argv[0]);
1151 }
1152
1153 if (argc >= 2) {
1154 flags = RB_NUM2INT(argv[1]);
1155 }
1156
1157 return rb_process_status_wait(pid, flags);
1158}
1159
1160rb_pid_t
1161rb_waitpid(rb_pid_t pid, int *st, int flags)
1162{
1163 VALUE status = rb_process_status_wait(pid, flags);
1164 if (NIL_P(status)) return 0;
1165
1166 struct rb_process_status *data = rb_check_typeddata(status, &rb_process_status_type);
1167 pid = data->pid;
1168
1169 if (st) *st = data->status;
1170
1171 if (pid == -1) {
1172 errno = data->error;
1173 }
1174 else {
1175 GET_THREAD()->last_status = status;
1176 }
1177
1178 return pid;
1179}
1180
1181static VALUE
1182proc_wait(int argc, VALUE *argv)
1183{
1184 rb_pid_t pid;
1185 int flags, status;
1186
1187 flags = 0;
1188 if (rb_check_arity(argc, 0, 2) == 0) {
1189 pid = -1;
1190 }
1191 else {
1192 VALUE vflags;
1193 pid = NUM2PIDT(argv[0]);
1194 if (argc == 2 && !NIL_P(vflags = argv[1])) {
1195 flags = NUM2UINT(vflags);
1196 }
1197 }
1198
1199 if ((pid = rb_waitpid(pid, &status, flags)) < 0)
1200 rb_sys_fail(0);
1201
1202 if (pid == 0) {
1203 rb_last_status_clear();
1204 return Qnil;
1205 }
1206
1207 return PIDT2NUM(pid);
1208}
1209
1210/* [MG]:FIXME: I wasn't sure how this should be done, since ::wait()
1211 has historically been documented as if it didn't take any arguments
1212 despite the fact that it's just an alias for ::waitpid(). The way I
1213 have it below is more truthful, but a little confusing.
1214
1215 I also took the liberty of putting in the pid values, as they're
1216 pretty useful, and it looked as if the original 'ri' output was
1217 supposed to contain them after "[...]depending on the value of
1218 aPid:".
1219
1220 The 'ansi' and 'bs' formats of the ri output don't display the
1221 definition list for some reason, but the plain text one does.
1222 */
1223
1224/*
1225 * call-seq:
1226 * Process.wait(pid = -1, flags = 0) -> integer
1227 *
1228 * Waits for a suitable child process to exit, returns its process ID,
1229 * and sets <tt>$?</tt> to a Process::Status object
1230 * containing information on that process.
1231 * Which child it waits for depends on the value of the given +pid+:
1232 *
1233 * - Positive integer: Waits for the child process whose process ID is +pid+:
1234 *
1235 * pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 230866
1236 * pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 230891
1237 * Process.wait(pid0) # => 230866
1238 * $? # => #<Process::Status: pid 230866 exit 13>
1239 * Process.wait(pid1) # => 230891
1240 * $? # => #<Process::Status: pid 230891 exit 14>
1241 * Process.wait(pid0) # Raises Errno::ECHILD
1242 *
1243 * - <tt>0</tt>: Waits for any child process whose group ID
1244 * is the same as that of the current process:
1245 *
1246 * parent_pgpid = Process.getpgid(Process.pid)
1247 * puts "Parent process group ID is #{parent_pgpid}."
1248 * child0_pid = fork do
1249 * puts "Child 0 pid is #{Process.pid}"
1250 * child0_pgid = Process.getpgid(Process.pid)
1251 * puts "Child 0 process group ID is #{child0_pgid} (same as parent's)."
1252 * end
1253 * child1_pid = fork do
1254 * puts "Child 1 pid is #{Process.pid}"
1255 * Process.setpgid(0, Process.pid)
1256 * child1_pgid = Process.getpgid(Process.pid)
1257 * puts "Child 1 process group ID is #{child1_pgid} (different from parent's)."
1258 * end
1259 * retrieved_pid = Process.wait(0)
1260 * puts "Process.wait(0) returned pid #{retrieved_pid}, which is child 0 pid."
1261 * begin
1262 * Process.wait(0)
1263 * rescue Errno::ECHILD => x
1264 * puts "Raised #{x.class}, because child 1 process group ID differs from parent process group ID."
1265 * end
1266 *
1267 * Output:
1268 *
1269 * Parent process group ID is 225764.
1270 * Child 0 pid is 225788
1271 * Child 0 process group ID is 225764 (same as parent's).
1272 * Child 1 pid is 225789
1273 * Child 1 process group ID is 225789 (different from parent's).
1274 * Process.wait(0) returned pid 225788, which is child 0 pid.
1275 * Raised Errno::ECHILD, because child 1 process group ID differs from parent process group ID.
1276 *
1277 * - <tt>-1</tt> (default): Waits for any child process:
1278 *
1279 * parent_pgpid = Process.getpgid(Process.pid)
1280 * puts "Parent process group ID is #{parent_pgpid}."
1281 * child0_pid = fork do
1282 * puts "Child 0 pid is #{Process.pid}"
1283 * child0_pgid = Process.getpgid(Process.pid)
1284 * puts "Child 0 process group ID is #{child0_pgid} (same as parent's)."
1285 * end
1286 * child1_pid = fork do
1287 * puts "Child 1 pid is #{Process.pid}"
1288 * Process.setpgid(0, Process.pid)
1289 * child1_pgid = Process.getpgid(Process.pid)
1290 * puts "Child 1 process group ID is #{child1_pgid} (different from parent's)."
1291 * sleep 3 # To force child 1 to exit later than child 0 exit.
1292 * end
1293 * child_pids = [child0_pid, child1_pid]
1294 * retrieved_pid = Process.wait(-1)
1295 * puts child_pids.include?(retrieved_pid)
1296 * retrieved_pid = Process.wait(-1)
1297 * puts child_pids.include?(retrieved_pid)
1298 *
1299 * Output:
1300 *
1301 * Parent process group ID is 228736.
1302 * Child 0 pid is 228758
1303 * Child 0 process group ID is 228736 (same as parent's).
1304 * Child 1 pid is 228759
1305 * Child 1 process group ID is 228759 (different from parent's).
1306 * true
1307 * true
1308 *
1309 * - Less than <tt>-1</tt>: Waits for any child whose process group ID is <tt>-pid</tt>:
1310 *
1311 * parent_pgpid = Process.getpgid(Process.pid)
1312 * puts "Parent process group ID is #{parent_pgpid}."
1313 * child0_pid = fork do
1314 * puts "Child 0 pid is #{Process.pid}"
1315 * child0_pgid = Process.getpgid(Process.pid)
1316 * puts "Child 0 process group ID is #{child0_pgid} (same as parent's)."
1317 * end
1318 * child1_pid = fork do
1319 * puts "Child 1 pid is #{Process.pid}"
1320 * Process.setpgid(0, Process.pid)
1321 * child1_pgid = Process.getpgid(Process.pid)
1322 * puts "Child 1 process group ID is #{child1_pgid} (different from parent's)."
1323 * end
1324 * sleep 1
1325 * retrieved_pid = Process.wait(-child1_pid)
1326 * puts "Process.wait(-child1_pid) returned pid #{retrieved_pid}, which is child 1 pid."
1327 * begin
1328 * Process.wait(-child1_pid)
1329 * rescue Errno::ECHILD => x
1330 * puts "Raised #{x.class}, because there's no longer a child with process group id #{child1_pid}."
1331 * end
1332 *
1333 * Output:
1334 *
1335 * Parent process group ID is 230083.
1336 * Child 0 pid is 230108
1337 * Child 0 process group ID is 230083 (same as parent's).
1338 * Child 1 pid is 230109
1339 * Child 1 process group ID is 230109 (different from parent's).
1340 * Process.wait(-child1_pid) returned pid 230109, which is child 1 pid.
1341 * Raised Errno::ECHILD, because there's no longer a child with process group id 230109.
1342 *
1343 * Argument +flags+ should be given as one of the following constants,
1344 * or as the logical OR of both:
1345 *
1346 * - Process::WNOHANG: Does not block if no child process is available.
1347 * - Process::WUNTRACED: May return a stopped child process, even if not yet reported.
1348 *
1349 * Not all flags are available on all platforms.
1350 *
1351 * Raises Errno::ECHILD if there is no suitable child process.
1352 *
1353 * Not available on all platforms.
1354 *
1355 * Process.waitpid is an alias for Process.wait.
1356 */
1357static VALUE
1358proc_m_wait(int c, VALUE *v, VALUE _)
1359{
1360 return proc_wait(c, v);
1361}
1362
1363/*
1364 * call-seq:
1365 * Process.wait2(pid = -1, flags = 0) -> [pid, status]
1366 *
1367 * Like Process.waitpid, but returns an array
1368 * containing the child process +pid+ and Process::Status +status+:
1369 *
1370 * pid = Process.spawn('ruby', '-e', 'exit 13') # => 309581
1371 * Process.wait2(pid)
1372 * # => [309581, #<Process::Status: pid 309581 exit 13>]
1373 *
1374 * Process.waitpid2 is an alias for Process.wait2.
1375 */
1376
1377static VALUE
1378proc_wait2(int argc, VALUE *argv, VALUE _)
1379{
1380 VALUE pid = proc_wait(argc, argv);
1381 if (NIL_P(pid)) return Qnil;
1382 return rb_assoc_new(pid, rb_last_status_get());
1383}
1384
1385
1386/*
1387 * call-seq:
1388 * Process.waitall -> array
1389 *
1390 * Waits for all children, returns an array of 2-element arrays;
1391 * each subarray contains the integer pid and Process::Status status
1392 * for one of the reaped child processes:
1393 *
1394 * pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 325470
1395 * pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 325495
1396 * Process.waitall
1397 * # => [[325470, #<Process::Status: pid 325470 exit 13>], [325495, #<Process::Status: pid 325495 exit 14>]]
1398 *
1399 */
1400
1401static VALUE
1402proc_waitall(VALUE _)
1403{
1404 VALUE result;
1405 rb_pid_t pid;
1406 int status;
1407
1408 result = rb_ary_new();
1409 rb_last_status_clear();
1410
1411 for (pid = -1;;) {
1412 pid = rb_waitpid(-1, &status, 0);
1413 if (pid == -1) {
1414 int e = errno;
1415 if (e == ECHILD)
1416 break;
1417 rb_syserr_fail(e, 0);
1418 }
1420 }
1421 return result;
1422}
1423
1424static VALUE rb_cWaiter;
1425
1426static VALUE
1427detach_process_pid(VALUE thread)
1428{
1429 return rb_thread_local_aref(thread, id_pid);
1430}
1431
1432static VALUE
1433detach_process_watcher(void *arg)
1434{
1435 rb_pid_t cpid, pid = (rb_pid_t)(VALUE)arg;
1436 int status;
1437
1438 while ((cpid = rb_waitpid(pid, &status, 0)) == 0) {
1439 /* wait while alive */
1440 }
1441 return rb_last_status_get();
1442}
1443
1444VALUE
1446{
1447 VALUE watcher = rb_thread_create(detach_process_watcher, (void*)(VALUE)pid);
1448 rb_thread_local_aset(watcher, id_pid, PIDT2NUM(pid));
1449 RBASIC_SET_CLASS(watcher, rb_cWaiter);
1450 return watcher;
1451}
1452
1453
1454/*
1455 * call-seq:
1456 * Process.detach(pid) -> thread
1457 *
1458 * Avoids the potential for a child process to become a
1459 * {zombie process}[https://en.wikipedia.org/wiki/Zombie_process].
1460 * Process.detach prevents this by setting up a separate Ruby thread
1461 * whose sole job is to reap the status of the process _pid_ when it terminates.
1462 *
1463 * This method is needed only when the parent process will never wait
1464 * for the child process.
1465 *
1466 * This example does not reap the second child process;
1467 * that process appears as a zombie in the process status (+ps+) output:
1468 *
1469 * pid = Process.spawn('ruby', '-e', 'exit 13') # => 312691
1470 * sleep(1)
1471 * # Find zombies.
1472 * system("ps -ho pid,state -p #{pid}")
1473 *
1474 * Output:
1475 *
1476 * 312716 Z
1477 *
1478 * This example also does not reap the second child process,
1479 * but it does detach the process so that it does not become a zombie:
1480 *
1481 * pid = Process.spawn('ruby', '-e', 'exit 13') # => 313213
1482 * thread = Process.detach(pid)
1483 * sleep(1)
1484 * # => #<Process::Waiter:0x00007f038f48b838 run>
1485 * system("ps -ho pid,state -p #{pid}") # Finds no zombies.
1486 *
1487 * The waiting thread can return the pid of the detached child process:
1488 *
1489 * thread.join.pid # => 313262
1490 *
1491 */
1492
1493static VALUE
1494proc_detach(VALUE obj, VALUE pid)
1495{
1496 return rb_detach_process(NUM2PIDT(pid));
1497}
1498
1499/* This function should be async-signal-safe. Actually it is. */
1500static void
1501before_exec_async_signal_safe(void)
1502{
1503}
1504
1505static void
1506before_exec_non_async_signal_safe(void)
1507{
1508 /*
1509 * On Mac OS X 10.5.x (Leopard) or earlier, exec() may return ENOTSUP
1510 * if the process have multiple threads. Therefore we have to kill
1511 * internal threads temporary. [ruby-core:10583]
1512 * This is also true on Haiku. It returns Errno::EPERM against exec()
1513 * in multiple threads.
1514 *
1515 * Nowadays, we always stop the timer thread completely to allow redirects.
1516 */
1517 rb_thread_stop_timer_thread();
1518}
1519
1520#define WRITE_CONST(fd, str) (void)(write((fd),(str),sizeof(str)-1)<0)
1521#ifdef _WIN32
1522int rb_w32_set_nonblock2(int fd, int nonblock);
1523#endif
1524
1525static int
1526set_blocking(int fd)
1527{
1528#ifdef _WIN32
1529 return rb_w32_set_nonblock2(fd, 0);
1530#elif defined(F_GETFL) && defined(F_SETFL)
1531 int fl = fcntl(fd, F_GETFL); /* async-signal-safe */
1532
1533 /* EBADF ought to be possible */
1534 if (fl == -1) return fl;
1535 if (fl & O_NONBLOCK) {
1536 fl &= ~O_NONBLOCK;
1537 return fcntl(fd, F_SETFL, fl);
1538 }
1539 return 0;
1540#endif
1541}
1542
1543static void
1544stdfd_clear_nonblock(void)
1545{
1546 /* many programs cannot deal with non-blocking stdin/stdout/stderr */
1547 int fd;
1548 for (fd = 0; fd < 3; fd++) {
1549 (void)set_blocking(fd); /* can't do much about errors anyhow */
1550 }
1551}
1552
1553static void
1554before_exec(void)
1555{
1556 before_exec_non_async_signal_safe();
1557 before_exec_async_signal_safe();
1558}
1559
1560static void
1561after_exec(void)
1562{
1563 rb_thread_reset_timer_thread();
1564 rb_thread_start_timer_thread();
1565}
1566
1567#if defined HAVE_WORKING_FORK || defined HAVE_DAEMON
1568static void
1569before_fork_ruby(void)
1570{
1571 before_exec();
1572 rb_gc_before_fork();
1573}
1574
1575static void
1576after_fork_ruby(rb_pid_t pid)
1577{
1578 rb_gc_after_fork(pid);
1579
1580 if (pid == 0) {
1581 // child
1582 clear_pid_cache();
1584 }
1585 else {
1586 // parent
1587 after_exec();
1588 }
1589}
1590
1591static void
1592release_fork_lock_after_fork(rb_pid_t pid)
1593{
1594 if (pid == 0) {
1595 rb_thread_reset_fork_lock();
1596 }
1597 else {
1598 rb_thread_release_fork_lock();
1599 }
1600}
1601#endif
1602
1603#if defined(HAVE_WORKING_FORK)
1604
1605COMPILER_WARNING_PUSH
1606#if __has_warning("-Wdeprecated-declarations") || RBIMPL_COMPILER_IS(GCC)
1607COMPILER_WARNING_IGNORED(-Wdeprecated-declarations)
1608#endif
1609static inline rb_pid_t
1610rb_fork(void)
1611{
1612 return fork();
1613}
1614COMPILER_WARNING_POP
1615
1616/* try_with_sh and exec_with_sh should be async-signal-safe. Actually it is.*/
1617#define try_with_sh(err, prog, argv, envp) ((err == ENOEXEC) ? exec_with_sh((prog), (argv), (envp)) : (void)0)
1618static void
1619exec_with_sh(const char *prog, char **argv, char **envp)
1620{
1621 *argv = (char *)prog;
1622 *--argv = (char *)"sh";
1623 if (envp)
1624 execve("/bin/sh", argv, envp); /* async-signal-safe */
1625 else
1626 execv("/bin/sh", argv); /* async-signal-safe (since SUSv4) */
1627}
1628
1629#else
1630#define try_with_sh(err, prog, argv, envp) (void)0
1631#endif
1632
1633/* This function should be async-signal-safe. Actually it is. */
1634static int
1635proc_exec_cmd(const char *prog, VALUE argv_str, VALUE envp_str)
1636{
1637 char **argv;
1638#ifndef _WIN32
1639 char **envp;
1640 int err;
1641#endif
1642
1643 argv = ARGVSTR2ARGV(argv_str);
1644
1645 if (!prog) {
1646 return ENOENT;
1647 }
1648
1649#ifdef _WIN32
1650 rb_w32_uaspawn(P_OVERLAY, prog, argv);
1651 return errno;
1652#else
1653 envp = envp_str ? RB_IMEMO_TMPBUF_PTR(envp_str) : NULL;
1654 if (envp_str)
1655 execve(prog, argv, envp); /* async-signal-safe */
1656 else
1657 execv(prog, argv); /* async-signal-safe (since SUSv4) */
1658 err = errno;
1659 try_with_sh(err, prog, argv, envp); /* try_with_sh() is async-signal-safe. */
1660 return err;
1661#endif
1662}
1663
1664/* This function should be async-signal-safe. Actually it is. */
1665static int
1666proc_exec_sh(const char *str, VALUE envp_str)
1667{
1668 const char *s;
1669
1670 s = str;
1671 while (*s == ' ' || *s == '\t' || *s == '\n')
1672 s++;
1673
1674 if (!*s) {
1675 return ENOENT;
1676 }
1677
1678#ifdef _WIN32
1679 rb_w32_uspawn(P_OVERLAY, (char *)str, 0);
1680#else
1681 if (envp_str)
1682 execle("/bin/sh", "sh", "-c", str, (char *)NULL, RB_IMEMO_TMPBUF_PTR(envp_str)); /* async-signal-safe */
1683 else
1684 execl("/bin/sh", "sh", "-c", str, (char *)NULL); /* async-signal-safe (since SUSv4) */
1685#endif /* _WIN32 */
1686 return errno;
1687}
1688
1689int
1690rb_proc_exec(const char *str)
1691{
1692 int ret;
1693 before_exec();
1694 ret = proc_exec_sh(str, Qfalse);
1695 after_exec();
1696 errno = ret;
1697 return -1;
1698}
1699
1700static void
1701mark_exec_arg(void *ptr)
1702{
1703 struct rb_execarg *eargp = ptr;
1704 if (eargp->use_shell)
1705 rb_gc_mark(eargp->invoke.sh.shell_script);
1706 else {
1707 rb_gc_mark(eargp->invoke.cmd.command_name);
1708 rb_gc_mark(eargp->invoke.cmd.command_abspath);
1709 rb_gc_mark(eargp->invoke.cmd.argv_str);
1710 rb_gc_mark(eargp->invoke.cmd.argv_buf);
1711 }
1712 rb_gc_mark(eargp->redirect_fds);
1713 rb_gc_mark(eargp->envp_str);
1714 rb_gc_mark(eargp->envp_buf);
1715 rb_gc_mark(eargp->dup2_tmpbuf);
1716 rb_gc_mark(eargp->rlimit_limits);
1717 rb_gc_mark(eargp->fd_dup2);
1718 rb_gc_mark(eargp->fd_close);
1719 rb_gc_mark(eargp->fd_open);
1720 rb_gc_mark(eargp->fd_dup2_child);
1721 rb_gc_mark(eargp->env_modification);
1722 rb_gc_mark(eargp->path_env);
1723 rb_gc_mark(eargp->chdir_dir);
1724}
1725
1726static size_t
1727memsize_exec_arg(const void *ptr)
1728{
1729 return sizeof(struct rb_execarg);
1730}
1731
1732static const rb_data_type_t exec_arg_data_type = {
1733 "exec_arg",
1734 {mark_exec_arg, RUBY_TYPED_DEFAULT_FREE, memsize_exec_arg},
1735 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
1736};
1737
1738#ifdef _WIN32
1739# define DEFAULT_PROCESS_ENCODING rb_utf8_encoding()
1740#endif
1741#define EXPORT_STR(str) export_str(str)
1742#define EXPORT_DUP(str) export_dup(str)
1743
1744WARN_UNUSED_RESULT(static VALUE)
1745export_str(VALUE str)
1746{
1747 StringValue(str);
1748 mustnot_wchar(str);
1749#ifdef DEFAULT_PROCESS_ENCODING
1750 str = rb_str_export_to_enc(str, DEFAULT_PROCESS_ENCODING);
1751 mustnot_broken(str);
1752#endif
1753 rb_str_null_check(str);
1754 return str;
1755}
1756
1757WARN_UNUSED_RESULT(static VALUE)
1758export_dup(VALUE str)
1759{
1760 VALUE newstr = EXPORT_STR(str);
1761 if (newstr == str) newstr = rb_str_dup(str);
1762 return newstr;
1763}
1764
1765#if !defined(HAVE_WORKING_FORK) && defined(HAVE_SPAWNV)
1766# define USE_SPAWNV 1
1767#else
1768# define USE_SPAWNV 0
1769#endif
1770#ifndef P_NOWAIT
1771# define P_NOWAIT _P_NOWAIT
1772#endif
1773
1774#if USE_SPAWNV
1775static rb_pid_t
1776proc_spawn_cmd(char **argv, VALUE prog, struct rb_execarg *eargp)
1777{
1778 rb_pid_t pid = -1;
1779
1780 if (argv[0]) {
1781 DWORD flags = 0;
1782 if (eargp->new_pgroup_given && eargp->new_pgroup_flag) {
1783 flags = CREATE_NEW_PROCESS_GROUP;
1784 }
1785 pid = rb_w32_uaspawn_flags(P_NOWAIT, prog ? RSTRING_PTR(prog) : 0, argv, flags);
1786 }
1787 return pid;
1788}
1789
1790#define proc_spawn_sh(str) rb_w32_uspawn(P_NOWAIT, (str), 0)
1791#endif
1792
1793static VALUE
1794hide_obj(VALUE obj)
1795{
1796 RBASIC_CLEAR_CLASS(obj);
1797 return obj;
1798}
1799
1800static VALUE
1801check_exec_redirect_fd(VALUE v, int iskey)
1802{
1803 VALUE tmp;
1804 int fd;
1805 if (FIXNUM_P(v)) {
1806 fd = FIX2INT(v);
1807 }
1808 else if (SYMBOL_P(v)) {
1809 ID id = rb_check_id(&v);
1810 if (id == id_in)
1811 fd = 0;
1812 else if (id == id_out)
1813 fd = 1;
1814 else if (id == id_err)
1815 fd = 2;
1816 else
1817 goto wrong;
1818 }
1819 else if (!NIL_P(tmp = rb_io_check_io(v))) {
1820 rb_io_t *fptr;
1821 GetOpenFile(tmp, fptr);
1822 if (fptr->tied_io_for_writing)
1823 rb_raise(rb_eArgError, "duplex IO redirection");
1824 fd = fptr->fd;
1825 }
1826 else {
1827 goto wrong;
1828 }
1829 if (fd < 0) {
1830 rb_raise(rb_eArgError, "negative file descriptor");
1831 }
1832#ifdef _WIN32
1833 else if (fd >= 3 && iskey) {
1834 rb_raise(rb_eArgError, "wrong file descriptor (%d)", fd);
1835 }
1836#endif
1837 return INT2FIX(fd);
1838
1839 wrong:
1840 rb_raise(rb_eArgError, "wrong exec redirect");
1842}
1843
1844static VALUE
1845check_exec_redirect1(VALUE ary, VALUE key, VALUE param)
1846{
1847 if (ary == Qfalse) {
1848 ary = hide_obj(rb_ary_new());
1849 }
1850 if (!RB_TYPE_P(key, T_ARRAY)) {
1851 VALUE fd = check_exec_redirect_fd(key, !NIL_P(param));
1852 rb_ary_push(ary, hide_obj(rb_assoc_new(fd, param)));
1853 }
1854 else {
1855 int i;
1856 for (i = 0 ; i < RARRAY_LEN(key); i++) {
1857 VALUE v = RARRAY_AREF(key, i);
1858 VALUE fd = check_exec_redirect_fd(v, !NIL_P(param));
1859 rb_ary_push(ary, hide_obj(rb_assoc_new(fd, param)));
1860 }
1861 }
1862 return ary;
1863}
1864
1865static void
1866check_exec_redirect(VALUE key, VALUE val, struct rb_execarg *eargp)
1867{
1868 VALUE param;
1869 VALUE path, flags, perm;
1870 VALUE tmp;
1871 ID id;
1872
1873 switch (TYPE(val)) {
1874 case T_SYMBOL:
1875 id = rb_check_id(&val);
1876 if (id == id_close) {
1877 param = Qnil;
1878 eargp->fd_close = check_exec_redirect1(eargp->fd_close, key, param);
1879 }
1880 else if (id == id_in) {
1881 param = INT2FIX(0);
1882 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1883 }
1884 else if (id == id_out) {
1885 param = INT2FIX(1);
1886 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1887 }
1888 else if (id == id_err) {
1889 param = INT2FIX(2);
1890 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1891 }
1892 else {
1893 rb_raise(rb_eArgError, "wrong exec redirect symbol: %"PRIsVALUE,
1894 val);
1895 }
1896 break;
1897
1898 case T_FILE:
1899 io:
1900 val = check_exec_redirect_fd(val, 0);
1901 /* fall through */
1902 case T_FIXNUM:
1903 param = val;
1904 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1905 break;
1906
1907 case T_ARRAY:
1908 path = rb_ary_entry(val, 0);
1909 if (RARRAY_LEN(val) == 2 && SYMBOL_P(path) &&
1910 path == ID2SYM(id_child)) {
1911 param = check_exec_redirect_fd(rb_ary_entry(val, 1), 0);
1912 eargp->fd_dup2_child = check_exec_redirect1(eargp->fd_dup2_child, key, param);
1913 }
1914 else {
1915 FilePathValue(path);
1916 flags = rb_ary_entry(val, 1);
1917 if (NIL_P(flags))
1918 flags = INT2NUM(O_RDONLY);
1919 else if (RB_TYPE_P(flags, T_STRING))
1921 else
1922 flags = rb_to_int(flags);
1923 perm = rb_ary_entry(val, 2);
1924 perm = NIL_P(perm) ? INT2FIX(0644) : rb_to_int(perm);
1925 param = hide_obj(rb_ary_new3(4, hide_obj(EXPORT_DUP(path)),
1926 flags, perm, Qnil));
1927 eargp->fd_open = check_exec_redirect1(eargp->fd_open, key, param);
1928 }
1929 break;
1930
1931 case T_STRING:
1932 path = val;
1933 FilePathValue(path);
1934 if (RB_TYPE_P(key, T_FILE))
1935 key = check_exec_redirect_fd(key, 1);
1936 if (FIXNUM_P(key) && (FIX2INT(key) == 1 || FIX2INT(key) == 2))
1937 flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC);
1938 else if (RB_TYPE_P(key, T_ARRAY)) {
1939 int i;
1940 for (i = 0; i < RARRAY_LEN(key); i++) {
1941 VALUE v = RARRAY_AREF(key, i);
1942 VALUE fd = check_exec_redirect_fd(v, 1);
1943 if (FIX2INT(fd) != 1 && FIX2INT(fd) != 2) break;
1944 }
1945 if (i == RARRAY_LEN(key))
1946 flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC);
1947 else
1948 flags = INT2NUM(O_RDONLY);
1949 }
1950 else
1951 flags = INT2NUM(O_RDONLY);
1952 perm = INT2FIX(0644);
1953 param = hide_obj(rb_ary_new3(4, hide_obj(EXPORT_DUP(path)),
1954 flags, perm, Qnil));
1955 eargp->fd_open = check_exec_redirect1(eargp->fd_open, key, param);
1956 break;
1957
1958 default:
1959 tmp = val;
1960 val = rb_io_check_io(tmp);
1961 if (!NIL_P(val)) goto io;
1962 rb_raise(rb_eArgError, "wrong exec redirect action");
1963 }
1964
1965}
1966
1967#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
1968static int rlimit_type_by_sym(VALUE key);
1969
1970static void
1971rb_execarg_addopt_rlimit(struct rb_execarg *eargp, int rtype, VALUE val)
1972{
1973 VALUE ary = eargp->rlimit_limits;
1974 VALUE tmp, softlim, hardlim;
1975 if (eargp->rlimit_limits == Qfalse)
1976 ary = eargp->rlimit_limits = hide_obj(rb_ary_new());
1977 else
1978 ary = eargp->rlimit_limits;
1979 tmp = rb_check_array_type(val);
1980 if (!NIL_P(tmp)) {
1981 if (RARRAY_LEN(tmp) == 1)
1982 softlim = hardlim = rb_to_int(rb_ary_entry(tmp, 0));
1983 else if (RARRAY_LEN(tmp) == 2) {
1984 softlim = rb_to_int(rb_ary_entry(tmp, 0));
1985 hardlim = rb_to_int(rb_ary_entry(tmp, 1));
1986 }
1987 else {
1988 rb_raise(rb_eArgError, "wrong exec rlimit option");
1989 }
1990 }
1991 else {
1992 softlim = hardlim = rb_to_int(val);
1993 }
1994 (void)NUM2RLIM(softlim);
1995 (void)NUM2RLIM(hardlim);
1996 tmp = hide_obj(rb_ary_new3(3, INT2NUM(rtype), softlim, hardlim));
1997 rb_ary_push(ary, tmp);
1998}
1999#endif
2000
2001#define TO_BOOL(val, name) (NIL_P(val) ? 0 : rb_bool_expected((val), name, TRUE))
2002int
2003rb_execarg_addopt(VALUE execarg_obj, VALUE key, VALUE val)
2004{
2005 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2006
2007 ID id;
2008
2009 switch (TYPE(key)) {
2010 case T_SYMBOL:
2011#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
2012 {
2013 int rtype = rlimit_type_by_sym(key);
2014 if (rtype != -1) {
2015 rb_execarg_addopt_rlimit(eargp, rtype, val);
2016 RB_GC_GUARD(execarg_obj);
2017 return ST_CONTINUE;
2018 }
2019 }
2020#endif
2021 if (!(id = rb_check_id(&key))) return ST_STOP;
2022#ifdef HAVE_SETPGID
2023 if (id == id_pgroup) {
2024 rb_pid_t pgroup;
2025 if (eargp->pgroup_given) {
2026 rb_raise(rb_eArgError, "pgroup option specified twice");
2027 }
2028 if (!RTEST(val))
2029 pgroup = -1; /* asis(-1) means "don't call setpgid()". */
2030 else if (val == Qtrue)
2031 pgroup = 0; /* new process group. */
2032 else {
2033 pgroup = NUM2PIDT(val);
2034 if (pgroup < 0) {
2035 rb_raise(rb_eArgError, "negative process group ID : %ld", (long)pgroup);
2036 }
2037 }
2038 eargp->pgroup_given = 1;
2039 eargp->pgroup_pgid = pgroup;
2040 }
2041 else
2042#endif
2043#ifdef _WIN32
2044 if (id == id_new_pgroup) {
2045 if (eargp->new_pgroup_given) {
2046 rb_raise(rb_eArgError, "new_pgroup option specified twice");
2047 }
2048 eargp->new_pgroup_given = 1;
2049 eargp->new_pgroup_flag = TO_BOOL(val, "new_pgroup");
2050 }
2051 else
2052#endif
2053 if (id == id_unsetenv_others) {
2054 if (eargp->unsetenv_others_given) {
2055 rb_raise(rb_eArgError, "unsetenv_others option specified twice");
2056 }
2057 eargp->unsetenv_others_given = 1;
2058 eargp->unsetenv_others_do = TO_BOOL(val, "unsetenv_others");
2059 }
2060 else if (id == id_chdir) {
2061 if (eargp->chdir_given) {
2062 rb_raise(rb_eArgError, "chdir option specified twice");
2063 }
2064 FilePathValue(val);
2065 val = rb_str_encode_ospath(val);
2066 eargp->chdir_given = 1;
2067 eargp->chdir_dir = hide_obj(EXPORT_DUP(val));
2068 }
2069 else if (id == id_umask) {
2070 mode_t cmask = NUM2MODET(val);
2071 if (eargp->umask_given) {
2072 rb_raise(rb_eArgError, "umask option specified twice");
2073 }
2074 eargp->umask_given = 1;
2075 eargp->umask_mask = cmask;
2076 }
2077 else if (id == id_close_others) {
2078 if (eargp->close_others_given) {
2079 rb_raise(rb_eArgError, "close_others option specified twice");
2080 }
2081 eargp->close_others_given = 1;
2082 eargp->close_others_do = TO_BOOL(val, "close_others");
2083 }
2084 else if (id == id_in) {
2085 key = INT2FIX(0);
2086 goto redirect;
2087 }
2088 else if (id == id_out) {
2089 key = INT2FIX(1);
2090 goto redirect;
2091 }
2092 else if (id == id_err) {
2093 key = INT2FIX(2);
2094 goto redirect;
2095 }
2096 else if (id == id_uid) {
2097#ifdef HAVE_SETUID
2098 if (eargp->uid_given) {
2099 rb_raise(rb_eArgError, "uid option specified twice");
2100 }
2101 check_uid_switch();
2102 {
2103 eargp->uid = OBJ2UID(val);
2104 eargp->uid_given = 1;
2105 }
2106#else
2107 rb_raise(rb_eNotImpError,
2108 "uid option is unimplemented on this machine");
2109#endif
2110 }
2111 else if (id == id_gid) {
2112#ifdef HAVE_SETGID
2113 if (eargp->gid_given) {
2114 rb_raise(rb_eArgError, "gid option specified twice");
2115 }
2116 check_gid_switch();
2117 {
2118 eargp->gid = OBJ2GID(val);
2119 eargp->gid_given = 1;
2120 }
2121#else
2122 rb_raise(rb_eNotImpError,
2123 "gid option is unimplemented on this machine");
2124#endif
2125 }
2126 else if (id == id_exception) {
2127 if (eargp->exception_given) {
2128 rb_raise(rb_eArgError, "exception option specified twice");
2129 }
2130 eargp->exception_given = 1;
2131 eargp->exception = TO_BOOL(val, "exception");
2132 }
2133 else {
2134 return ST_STOP;
2135 }
2136 break;
2137
2138 case T_FIXNUM:
2139 case T_FILE:
2140 case T_ARRAY:
2141redirect:
2142 check_exec_redirect(key, val, eargp);
2143 break;
2144
2145 default:
2146 return ST_STOP;
2147 }
2148
2149 RB_GC_GUARD(execarg_obj);
2150 return ST_CONTINUE;
2151}
2152
2153static int
2154check_exec_options_i(st_data_t st_key, st_data_t st_val, st_data_t arg)
2155{
2156 VALUE key = (VALUE)st_key;
2157 VALUE val = (VALUE)st_val;
2158 VALUE execarg_obj = (VALUE)arg;
2159 if (rb_execarg_addopt(execarg_obj, key, val) != ST_CONTINUE) {
2160 if (SYMBOL_P(key))
2161 rb_raise(rb_eArgError, "wrong exec option symbol: % "PRIsVALUE,
2162 key);
2163 rb_raise(rb_eArgError, "wrong exec option: %"PRIsVALUE, rb_obj_class(key));
2164 }
2165 return ST_CONTINUE;
2166}
2167
2168static int
2169check_exec_options_i_extract(st_data_t st_key, st_data_t st_val, st_data_t arg)
2170{
2171 VALUE key = (VALUE)st_key;
2172 VALUE val = (VALUE)st_val;
2173 VALUE *args = (VALUE *)arg;
2174 VALUE execarg_obj = args[0];
2175 if (rb_execarg_addopt(execarg_obj, key, val) != ST_CONTINUE) {
2176 VALUE nonopts = args[1];
2177 if (NIL_P(nonopts)) args[1] = nonopts = rb_hash_new();
2178 rb_hash_aset(nonopts, key, val);
2179 }
2180 return ST_CONTINUE;
2181}
2182
2183static int
2184check_exec_fds_1(struct rb_execarg *eargp, VALUE h, int maxhint, VALUE ary)
2185{
2186 rb_len_t i;
2187
2188 if (ary != Qfalse) {
2189 for (i = 0; i < RARRAY_LEN(ary); i++) {
2190 VALUE elt = RARRAY_AREF(ary, i);
2191 int fd = FIX2INT(RARRAY_AREF(elt, 0));
2192 if (RTEST(rb_hash_lookup(h, INT2FIX(fd)))) {
2193 rb_raise(rb_eArgError, "fd %d specified twice", fd);
2194 }
2195 if (ary == eargp->fd_dup2)
2196 rb_hash_aset(h, INT2FIX(fd), Qtrue);
2197 else if (ary == eargp->fd_dup2_child)
2198 rb_hash_aset(h, INT2FIX(fd), RARRAY_AREF(elt, 1));
2199 else /* ary == eargp->fd_close */
2200 rb_hash_aset(h, INT2FIX(fd), INT2FIX(-1));
2201 if (maxhint < fd)
2202 maxhint = fd;
2203 if (ary == eargp->fd_dup2 || ary == eargp->fd_dup2_child) {
2204 fd = FIX2INT(RARRAY_AREF(elt, 1));
2205 if (maxhint < fd)
2206 maxhint = fd;
2207 }
2208 }
2209 }
2210 return maxhint;
2211}
2212
2213static VALUE
2214check_exec_fds(struct rb_execarg *eargp)
2215{
2216 VALUE h = rb_hash_new();
2217 VALUE ary;
2218 int maxhint = -1;
2219 rb_len_t i;
2220
2221 maxhint = check_exec_fds_1(eargp, h, maxhint, eargp->fd_dup2);
2222 maxhint = check_exec_fds_1(eargp, h, maxhint, eargp->fd_close);
2223 maxhint = check_exec_fds_1(eargp, h, maxhint, eargp->fd_dup2_child);
2224
2225 if (eargp->fd_dup2_child) {
2226 ary = eargp->fd_dup2_child;
2227 for (i = 0; i < RARRAY_LEN(ary); i++) {
2228 VALUE elt = RARRAY_AREF(ary, i);
2229 int newfd = FIX2INT(RARRAY_AREF(elt, 0));
2230 int oldfd = FIX2INT(RARRAY_AREF(elt, 1));
2231 int lastfd = oldfd;
2232 VALUE val = rb_hash_lookup(h, INT2FIX(lastfd));
2233 rb_len_t depth = 0;
2234 while (FIXNUM_P(val) && 0 <= FIX2INT(val)) {
2235 lastfd = FIX2INT(val);
2236 val = rb_hash_lookup(h, val);
2237 if (RARRAY_LEN(ary) < depth)
2238 rb_raise(rb_eArgError, "cyclic child fd redirection from %d", oldfd);
2239 depth++;
2240 }
2241 if (val != Qtrue)
2242 rb_raise(rb_eArgError, "child fd %d is not redirected", oldfd);
2243 if (oldfd != lastfd) {
2244 VALUE val2;
2245 rb_ary_store(elt, 1, INT2FIX(lastfd));
2246 rb_hash_aset(h, INT2FIX(newfd), INT2FIX(lastfd));
2247 val = INT2FIX(oldfd);
2248 while (FIXNUM_P(val2 = rb_hash_lookup(h, val))) {
2249 rb_hash_aset(h, val, INT2FIX(lastfd));
2250 val = val2;
2251 }
2252 }
2253 }
2254 }
2255
2256 eargp->close_others_maxhint = maxhint;
2257 return h;
2258}
2259
2260static void
2261rb_check_exec_options(VALUE opthash, VALUE execarg_obj)
2262{
2263 if (RHASH_EMPTY_P(opthash))
2264 return;
2265 rb_hash_stlike_foreach(opthash, check_exec_options_i, (st_data_t)execarg_obj);
2266}
2267
2268VALUE
2269rb_execarg_extract_options(VALUE execarg_obj, VALUE opthash)
2270{
2271 VALUE args[2];
2272 if (RHASH_EMPTY_P(opthash))
2273 return Qnil;
2274 args[0] = execarg_obj;
2275 args[1] = Qnil;
2276 rb_hash_stlike_foreach(opthash, check_exec_options_i_extract, (st_data_t)args);
2277 return args[1];
2278}
2279
2280#ifdef ENV_IGNORECASE
2281#define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
2282#else
2283#define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
2284#endif
2285
2286static int
2287check_exec_env_i(st_data_t st_key, st_data_t st_val, st_data_t arg)
2288{
2289 VALUE key = (VALUE)st_key;
2290 VALUE val = (VALUE)st_val;
2291 VALUE env = ((VALUE *)arg)[0];
2292 VALUE *path = &((VALUE *)arg)[1];
2293
2294 const char *k = RSTRING_PTR(key = EXPORT_STR(key));
2295 if (strchr(k, '='))
2296 rb_raise(rb_eArgError, "environment name contains a equal : %"PRIsVALUE, key);
2297
2298 if (!NIL_P(val)) val = EXPORT_STR(val);
2299
2300 if (ENVMATCH(k, PATH_ENV)) {
2301 *path = val;
2302 }
2303 rb_ary_push(env, hide_obj(rb_assoc_new(key, val)));
2304
2305 return ST_CONTINUE;
2306}
2307
2308static VALUE
2309rb_check_exec_env(VALUE hash, VALUE *path)
2310{
2311 VALUE env[2];
2312
2313 env[0] = hide_obj(rb_ary_new());
2314 env[1] = Qfalse;
2315 rb_hash_stlike_foreach(hash, check_exec_env_i, (st_data_t)env);
2316 *path = env[1];
2317
2318 return env[0];
2319}
2320
2321static VALUE
2322rb_check_argv(int argc, VALUE *argv)
2323{
2324 VALUE tmp, prog;
2325 int i;
2326
2328
2329 prog = 0;
2330 tmp = rb_check_array_type(argv[0]);
2331 if (!NIL_P(tmp)) {
2332 if (RARRAY_LEN(tmp) != 2) {
2333 rb_raise(rb_eArgError, "wrong first argument");
2334 }
2335 prog = RARRAY_AREF(tmp, 0);
2336 argv[0] = RARRAY_AREF(tmp, 1);
2337 prog = rb_str_new_frozen(EXPORT_STR(prog));
2338 }
2339 for (i = 0; i < argc; i++) {
2340 argv[i] = rb_str_new_frozen(EXPORT_STR(argv[i]));
2341 }
2342 return prog;
2343}
2344
2345static VALUE
2346check_hash(VALUE obj)
2347{
2348 if (RB_SPECIAL_CONST_P(obj)) return Qnil;
2349 switch (RB_BUILTIN_TYPE(obj)) {
2350 case T_STRING:
2351 case T_ARRAY:
2352 return Qnil;
2353 default:
2354 break;
2355 }
2356 return rb_check_hash_type(obj);
2357}
2358
2359static VALUE
2360rb_exec_getargs(int *argc_p, VALUE **argv_p, int accept_shell, VALUE *env_ret, VALUE *opthash_ret)
2361{
2362 VALUE hash, prog;
2363
2364 if (0 < *argc_p) {
2365 hash = check_hash((*argv_p)[*argc_p-1]);
2366 if (!NIL_P(hash)) {
2367 *opthash_ret = hash;
2368 (*argc_p)--;
2369 }
2370 }
2371
2372 if (0 < *argc_p) {
2373 hash = check_hash((*argv_p)[0]);
2374 if (!NIL_P(hash)) {
2375 *env_ret = hash;
2376 (*argc_p)--;
2377 (*argv_p)++;
2378 }
2379 }
2380 prog = rb_check_argv(*argc_p, *argv_p);
2381 if (!prog) {
2382 prog = (*argv_p)[0];
2383 if (accept_shell && *argc_p == 1) {
2384 *argc_p = 0;
2385 *argv_p = 0;
2386 }
2387 }
2388 return prog;
2389}
2390
2391#ifndef _WIN32
2393 const char *ptr;
2394 size_t len;
2395};
2396
2397static int
2398compare_posix_sh(const void *key, const void *el)
2399{
2400 const struct string_part *word = key;
2401 int ret = strncmp(word->ptr, el, word->len);
2402 if (!ret && ((const char *)el)[word->len]) ret = -1;
2403 return ret;
2404}
2405#endif
2406
2407#define append_terminator(buf) rb_str_buf_cat(buf, "", 1) /* append '\0' */
2408
2409static void
2410rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VALUE execarg_obj)
2411{
2412 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2413 char fbuf[MAXPATHLEN];
2414
2415 MEMZERO(eargp, struct rb_execarg, 1);
2416
2417 if (!NIL_P(opthash)) {
2418 rb_check_exec_options(opthash, execarg_obj);
2419 }
2420 if (!NIL_P(env)) {
2421 env = rb_check_exec_env(env, &eargp->path_env);
2422 eargp->env_modification = env;
2423 }
2424
2425 prog = EXPORT_STR(prog);
2426 eargp->use_shell = argc == 0;
2427 if (eargp->use_shell)
2428 eargp->invoke.sh.shell_script = prog;
2429 else
2430 eargp->invoke.cmd.command_name = prog;
2431
2432#ifndef _WIN32
2433 if (eargp->use_shell) {
2434 static const char posix_sh_cmds[][9] = {
2435 "!", /* reserved */
2436 ".", /* special built-in */
2437 ":", /* special built-in */
2438 "break", /* special built-in */
2439 "case", /* reserved */
2440 "continue", /* special built-in */
2441 "do", /* reserved */
2442 "done", /* reserved */
2443 "elif", /* reserved */
2444 "else", /* reserved */
2445 "esac", /* reserved */
2446 "eval", /* special built-in */
2447 "exec", /* special built-in */
2448 "exit", /* special built-in */
2449 "export", /* special built-in */
2450 "fi", /* reserved */
2451 "for", /* reserved */
2452 "if", /* reserved */
2453 "in", /* reserved */
2454 "readonly", /* special built-in */
2455 "return", /* special built-in */
2456 "set", /* special built-in */
2457 "shift", /* special built-in */
2458 "then", /* reserved */
2459 "times", /* special built-in */
2460 "trap", /* special built-in */
2461 "unset", /* special built-in */
2462 "until", /* reserved */
2463 "while", /* reserved */
2464 };
2465 const char *p;
2466 const char *const s = rb_str_null_check(prog);
2467 const char *const e = RSTRING_END(prog);
2468 struct string_part first = {0, 0};
2469 int has_slash = 0;
2470 int has_meta = 0;
2471 /*
2472 * meta characters:
2473 *
2474 * * Pathname Expansion
2475 * ? Pathname Expansion
2476 * {} Grouping Commands
2477 * [] Pathname Expansion
2478 * <> Redirection
2479 * () Grouping Commands
2480 * ~ Tilde Expansion
2481 * & AND Lists, Asynchronous Lists
2482 * | OR Lists, Pipelines
2483 * \ Escape Character
2484 * $ Parameter Expansion
2485 * ; Sequential Lists
2486 * ' Single-Quotes
2487 * ` Command Substitution
2488 * " Double-Quotes
2489 * \n Lists
2490 *
2491 * # Comment
2492 * = Assignment preceding command name
2493 * % (used in Parameter Expansion)
2494 */
2495 for (p = s; p < e; p++) {
2496 if (*p == ' ' || *p == '\t') {
2497 if (first.ptr && !first.len) first.len = p - first.ptr;
2498 }
2499 else {
2500 if (!first.ptr) first.ptr = p;
2501 }
2502 if (!has_meta && strchr("*?{}[]<>()~&|\\$;'`\"\n#", *p))
2503 has_meta = 1;
2504 if (!first.len) {
2505 if (*p == '=') {
2506 has_meta = 1;
2507 }
2508 else if (*p == '/') {
2509 has_slash = 1;
2510 }
2511 }
2512 if (has_meta)
2513 break;
2514 }
2515 if (!has_meta) {
2516 if (!first.ptr) first.ptr = e;
2517 if (!first.len) first.len = p - first.ptr;
2518 if (first.len > 0 && first.len <= sizeof(posix_sh_cmds[0]) &&
2519 !has_slash &&
2520 bsearch(&first, posix_sh_cmds, numberof(posix_sh_cmds), sizeof(posix_sh_cmds[0]), compare_posix_sh))
2521 has_meta = 1;
2522 }
2523 if (!has_meta) {
2524 /* avoid shell since no shell meta character found. */
2525 eargp->use_shell = 0;
2526 }
2527 if (!eargp->use_shell) {
2528 VALUE argv_buf;
2529 argv_buf = hide_obj(rb_str_buf_new(0));
2530 rb_str_buf_cat(argv_buf, first.ptr, first.len);
2531 append_terminator(argv_buf);
2532 for (p = first.ptr + first.len; p < e;) {
2533 while (p < e && (*p == ' ' || *p == '\t'))
2534 p++;
2535 if (p < e) {
2536 const char *w = p;
2537 while (p < e && *p != ' ' && *p != '\t')
2538 p++;
2539 rb_str_buf_cat(argv_buf, w, p-w);
2540 append_terminator(argv_buf);
2541 }
2542 }
2543 eargp->invoke.cmd.argv_buf = argv_buf;
2544 eargp->invoke.cmd.command_name =
2545 hide_obj(rb_str_subseq(argv_buf, 0, first.len));
2546 rb_enc_copy(eargp->invoke.cmd.command_name, prog);
2547 }
2548 }
2549#endif
2550
2551 if (!eargp->use_shell) {
2552 const char *abspath;
2553 const char *path_env = 0;
2554 if (RTEST(eargp->path_env)) path_env = RSTRING_PTR(eargp->path_env);
2555 abspath = dln_find_exe_r(RSTRING_PTR(eargp->invoke.cmd.command_name),
2556 path_env, fbuf, sizeof(fbuf));
2557 if (abspath)
2558 eargp->invoke.cmd.command_abspath = rb_str_new_cstr(abspath);
2559 else
2560 eargp->invoke.cmd.command_abspath = Qnil;
2561 }
2562
2563 if (!eargp->use_shell && !eargp->invoke.cmd.argv_buf) {
2564 int i;
2565 VALUE argv_buf;
2566 argv_buf = rb_str_buf_new(0);
2567 hide_obj(argv_buf);
2568 for (i = 0; i < argc; i++) {
2569 VALUE arg = argv[i];
2570 const char *s = RSTRING_PTR(arg); /* exported */
2571 rb_str_buf_cat(argv_buf, s, RSTRING_LEN(arg));
2572 append_terminator(argv_buf);
2573 }
2574 eargp->invoke.cmd.argv_buf = argv_buf;
2575 }
2576
2577 if (!eargp->use_shell) {
2578 const char *p, *ep, *null=NULL;
2579 VALUE argv_str;
2580 argv_str = hide_obj(rb_str_buf_new(sizeof(char*) * (argc + 2)));
2581 rb_str_buf_cat(argv_str, (char *)&null, sizeof(null)); /* place holder for /bin/sh of try_with_sh. */
2582 p = RSTRING_PTR(eargp->invoke.cmd.argv_buf);
2583 ep = p + RSTRING_LEN(eargp->invoke.cmd.argv_buf);
2584 while (p < ep) {
2585 rb_str_buf_cat(argv_str, (char *)&p, sizeof(p));
2586 p += strlen(p) + 1;
2587 }
2588 rb_str_buf_cat(argv_str, (char *)&null, sizeof(null)); /* terminator for execve. */
2589 eargp->invoke.cmd.argv_str =
2590 rb_imemo_tmpbuf_new_from_an_RString(argv_str);
2591 }
2592 RB_GC_GUARD(execarg_obj);
2593}
2594
2595struct rb_execarg *
2596rb_execarg_get(VALUE execarg_obj)
2597{
2598 struct rb_execarg *eargp;
2599 TypedData_Get_Struct(execarg_obj, struct rb_execarg, &exec_arg_data_type, eargp);
2600 return eargp;
2601}
2602
2603static VALUE
2604rb_execarg_init(int argc, const VALUE *orig_argv, int accept_shell, VALUE execarg_obj)
2605{
2606 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2607 VALUE prog, ret;
2608 VALUE env = Qnil, opthash = Qnil;
2609 VALUE argv_buf;
2610 VALUE *argv = ALLOCV_N(VALUE, argv_buf, argc);
2611 MEMCPY(argv, orig_argv, VALUE, argc);
2612 prog = rb_exec_getargs(&argc, &argv, accept_shell, &env, &opthash);
2613 rb_exec_fillarg(prog, argc, argv, env, opthash, execarg_obj);
2614 ALLOCV_END(argv_buf);
2615 ret = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
2616 RB_GC_GUARD(execarg_obj);
2617 return ret;
2618}
2619
2620VALUE
2621rb_execarg_new(int argc, const VALUE *argv, int accept_shell, int allow_exc_opt)
2622{
2623 VALUE execarg_obj;
2624 struct rb_execarg *eargp;
2625 execarg_obj = TypedData_Make_Struct(0, struct rb_execarg, &exec_arg_data_type, eargp);
2626 rb_execarg_init(argc, argv, accept_shell, execarg_obj);
2627 if (!allow_exc_opt && eargp->exception_given) {
2628 rb_raise(rb_eArgError, "exception option is not allowed");
2629 }
2630 return execarg_obj;
2631}
2632
2633void
2634rb_execarg_setenv(VALUE execarg_obj, VALUE env)
2635{
2636 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2637 env = !NIL_P(env) ? rb_check_exec_env(env, &eargp->path_env) : Qfalse;
2638 eargp->env_modification = env;
2639 RB_GC_GUARD(execarg_obj);
2640}
2641
2642static int
2643fill_envp_buf_i(st_data_t st_key, st_data_t st_val, st_data_t arg)
2644{
2645 VALUE key = (VALUE)st_key;
2646 VALUE val = (VALUE)st_val;
2647 VALUE envp_buf = (VALUE)arg;
2648
2649 rb_str_buf_cat2(envp_buf, RSTRING_PTR(key)); /* exported */
2650 rb_str_buf_cat2(envp_buf, "=");
2651 rb_str_buf_cat2(envp_buf, RSTRING_PTR(val)); /* exported */
2652 append_terminator(envp_buf);
2653
2654 return ST_CONTINUE;
2655}
2656
2657
2658static rb_len_t run_exec_dup2_tmpbuf_size(rb_len_t n);
2659
2661 VALUE fname;
2662 int oflags;
2663 mode_t perm;
2664 int ret;
2665 int err;
2666};
2667
2668static void *
2669open_func(void *ptr)
2670{
2671 struct open_struct *data = ptr;
2672 const char *fname = RSTRING_PTR(data->fname);
2673 data->ret = parent_redirect_open(fname, data->oflags, data->perm);
2674 data->err = errno;
2675 return NULL;
2676}
2677
2678static void
2679rb_execarg_allocate_dup2_tmpbuf(struct rb_execarg *eargp, rb_len_t len)
2680{
2681 rb_alloc_tmp_buffer(&eargp->dup2_tmpbuf, run_exec_dup2_tmpbuf_size(len), false);
2682}
2683
2684static VALUE
2685rb_execarg_parent_start1(VALUE execarg_obj)
2686{
2687 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2688 int unsetenv_others;
2689 VALUE envopts;
2690 VALUE ary;
2691
2692 ary = eargp->fd_open;
2693 if (ary != Qfalse) {
2694 rb_len_t i;
2695 for (i = 0; i < RARRAY_LEN(ary); i++) {
2696 VALUE elt = RARRAY_AREF(ary, i);
2697 int fd = FIX2INT(RARRAY_AREF(elt, 0));
2698 VALUE param = RARRAY_AREF(elt, 1);
2699 VALUE vpath = RARRAY_AREF(param, 0);
2700 int flags = NUM2INT(RARRAY_AREF(param, 1));
2701 mode_t perm = NUM2MODET(RARRAY_AREF(param, 2));
2702 VALUE fd2v = RARRAY_AREF(param, 3);
2703 int fd2;
2704 if (NIL_P(fd2v)) {
2705 struct open_struct open_data;
2706 again:
2707 open_data.fname = vpath;
2708 open_data.oflags = flags;
2709 open_data.perm = perm;
2710 open_data.ret = -1;
2711 open_data.err = EINTR;
2712 rb_thread_call_without_gvl2(open_func, (void *)&open_data, RUBY_UBF_IO, 0);
2713 if (open_data.ret == -1) {
2714 if (open_data.err == EINTR) {
2716 goto again;
2717 }
2718 rb_syserr_fail_str(open_data.err, vpath);
2719 }
2720 fd2 = open_data.ret;
2721 rb_update_max_fd(fd2);
2722 RARRAY_ASET(param, 3, INT2FIX(fd2));
2724 }
2725 else {
2726 fd2 = NUM2INT(fd2v);
2727 }
2728 rb_execarg_addopt(execarg_obj, INT2FIX(fd), INT2FIX(fd2));
2729 }
2730 }
2731
2732 eargp->redirect_fds = check_exec_fds(eargp);
2733
2734 ary = eargp->fd_dup2;
2735 if (ary != Qfalse) {
2736 rb_execarg_allocate_dup2_tmpbuf(eargp, RARRAY_LEN(ary));
2737 }
2738
2739 unsetenv_others = eargp->unsetenv_others_given && eargp->unsetenv_others_do;
2740 envopts = eargp->env_modification;
2741 if (ALWAYS_NEED_ENVP || unsetenv_others || envopts != Qfalse) {
2742 VALUE envtbl, envp_str, envp_buf;
2743 char *p, *ep;
2744 if (unsetenv_others) {
2745 envtbl = rb_hash_new();
2746 }
2747 else {
2748 envtbl = rb_env_to_hash();
2749 }
2750 hide_obj(envtbl);
2751 if (envopts != Qfalse) {
2752 rb_len_t i;
2753 for (i = 0; i < RARRAY_LEN(envopts); i++) {
2754 VALUE pair = RARRAY_AREF(envopts, i);
2755 VALUE key = EXPORT_STR(RARRAY_AREF(pair, 0));
2756 VALUE val = RARRAY_AREF(pair, 1);
2757 if (NIL_P(val)) {
2758 rb_hash_delete(envtbl, key);
2759 }
2760 else {
2761 rb_hash_aset(envtbl, key, EXPORT_STR(val));
2762 }
2763 }
2764 }
2765 envp_buf = rb_str_buf_new(0);
2766 hide_obj(envp_buf);
2767 rb_hash_stlike_foreach(envtbl, fill_envp_buf_i, (st_data_t)envp_buf);
2768 envp_str = rb_str_buf_new(sizeof(char*) * (RHASH_SIZE(envtbl) + 1));
2769 hide_obj(envp_str);
2770 p = RSTRING_PTR(envp_buf);
2771 ep = p + RSTRING_LEN(envp_buf);
2772 while (p < ep) {
2773 rb_str_buf_cat(envp_str, (char *)&p, sizeof(p));
2774 p += strlen(p) + 1;
2775 }
2776 p = NULL;
2777 rb_str_buf_cat(envp_str, (char *)&p, sizeof(p));
2778 eargp->envp_str =
2779 rb_imemo_tmpbuf_new_from_an_RString(envp_str);
2780 eargp->envp_buf = envp_buf;
2781
2782 /*
2783 char **tmp_envp = (char **)RSTRING_PTR(envp_str);
2784 while (*tmp_envp) {
2785 printf("%s\n", *tmp_envp);
2786 tmp_envp++;
2787 }
2788 */
2789 }
2790
2791 RB_GC_GUARD(execarg_obj);
2792 return Qnil;
2793}
2794
2795void
2796rb_execarg_parent_start(VALUE execarg_obj)
2797{
2798 int state;
2799 rb_protect(rb_execarg_parent_start1, execarg_obj, &state);
2800 if (state) {
2801 rb_execarg_parent_end(execarg_obj);
2802 rb_jump_tag(state);
2803 }
2804}
2805
2806static VALUE
2807execarg_parent_end(VALUE execarg_obj)
2808{
2809 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2810 int err = errno;
2811 VALUE ary;
2812
2813 ary = eargp->fd_open;
2814 if (ary != Qfalse) {
2815 rb_len_t i;
2816 for (i = 0; i < RARRAY_LEN(ary); i++) {
2817 VALUE elt = RARRAY_AREF(ary, i);
2818 VALUE param = RARRAY_AREF(elt, 1);
2819 VALUE fd2v;
2820 int fd2;
2821 fd2v = RARRAY_AREF(param, 3);
2822 if (!NIL_P(fd2v)) {
2823 fd2 = FIX2INT(fd2v);
2824 parent_redirect_close(fd2);
2825 RARRAY_ASET(param, 3, Qnil);
2826 }
2827 }
2828 }
2829
2830 errno = err;
2831 RB_GC_GUARD(execarg_obj);
2832 return execarg_obj;
2833}
2834
2835void
2836rb_execarg_parent_end(VALUE execarg_obj)
2837{
2838 execarg_parent_end(execarg_obj);
2839}
2840
2841static void
2842rb_exec_fail(struct rb_execarg *eargp, int err, const char *errmsg)
2843{
2844 if (!errmsg || !*errmsg) return;
2845 if (strcmp(errmsg, "chdir") == 0) {
2846 rb_sys_fail_str(eargp->chdir_dir);
2847 }
2848 rb_sys_fail(errmsg);
2849}
2850
2851#if 0
2852void
2853rb_execarg_fail(VALUE execarg_obj, int err, const char *errmsg)
2854{
2855 if (!errmsg || !*errmsg) return;
2856 rb_exec_fail(rb_execarg_get(execarg_obj), err, errmsg);
2857 RB_GC_GUARD(execarg_obj);
2858}
2859#endif
2860
2861VALUE
2862rb_f_exec(int argc, const VALUE *argv)
2863{
2864 VALUE execarg_obj, fail_str;
2865 struct rb_execarg *eargp;
2866#define CHILD_ERRMSG_BUFLEN 80
2867 char errmsg[CHILD_ERRMSG_BUFLEN] = { '\0' };
2868 int err, state;
2869
2870 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
2871 eargp = rb_execarg_get(execarg_obj);
2872 before_exec(); /* stop timer thread before redirects */
2873
2874 rb_protect(rb_execarg_parent_start1, execarg_obj, &state);
2875 if (state) {
2876 execarg_parent_end(execarg_obj);
2877 after_exec(); /* restart timer thread */
2878 rb_jump_tag(state);
2879 }
2880
2881 fail_str = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
2882
2883 err = exec_async_signal_safe(eargp, errmsg, sizeof(errmsg));
2884 after_exec(); /* restart timer thread */
2885
2886 rb_exec_fail(eargp, err, errmsg);
2887 RB_GC_GUARD(execarg_obj);
2888 rb_syserr_fail_str(err, fail_str);
2890}
2891
2892NORETURN(static VALUE f_exec(int c, const VALUE *a, VALUE _));
2893
2894/*
2895 * call-seq:
2896 * exec([env, ] command_line, options = {})
2897 * exec([env, ] exe_path, *args, options = {})
2898 *
2899 * Replaces the current process by doing one of the following:
2900 *
2901 * - Passing string +command_line+ to the shell.
2902 * - Invoking the executable at +exe_path+.
2903 *
2904 * This method has potential security vulnerabilities if called with untrusted input;
2905 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
2906 *
2907 * The new process is created using the
2908 * {exec system call}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/functions/execve.html];
2909 * it may inherit some of its environment from the calling program
2910 * (possibly including open file descriptors).
2911 *
2912 * Argument +env+, if given, is a hash that affects +ENV+ for the new process;
2913 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
2914 *
2915 * Argument +options+ is a hash of options for the new process;
2916 * see {Execution Options}[rdoc-ref:Process@Execution+Options].
2917 *
2918 * The first required argument is one of the following:
2919 *
2920 * - +command_line+ if it is a string,
2921 * and if it begins with a shell reserved word or special built-in,
2922 * or if it contains one or more meta characters.
2923 * - +exe_path+ otherwise.
2924 *
2925 * <b>Argument +command_line+</b>
2926 *
2927 * \String argument +command_line+ is a command line to be passed to a shell;
2928 * it must begin with a shell reserved word, begin with a special built-in,
2929 * or contain meta characters:
2930 *
2931 * exec('if true; then echo "Foo"; fi') # Shell reserved word.
2932 * exec('exit') # Built-in.
2933 * exec('date > date.tmp') # Contains meta character.
2934 *
2935 * The command line may also contain arguments and options for the command:
2936 *
2937 * exec('echo "Foo"')
2938 *
2939 * Output:
2940 *
2941 * Foo
2942 *
2943 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
2944 *
2945 * Raises an exception if the new process could not execute.
2946 *
2947 * <b>Argument +exe_path+</b>
2948 *
2949 * Argument +exe_path+ is one of the following:
2950 *
2951 * - The string path to an executable to be called.
2952 * - A 2-element array containing the path to an executable
2953 * and the string to be used as the name of the executing process.
2954 *
2955 * Example:
2956 *
2957 * exec('/usr/bin/date')
2958 *
2959 * Output:
2960 *
2961 * Sat Aug 26 09:38:00 AM CDT 2023
2962 *
2963 * Ruby invokes the executable directly.
2964 * This form does not use the shell;
2965 * see {Arguments args}[rdoc-ref:Process@Arguments+args] for caveats.
2966 *
2967 * exec('doesnt_exist') # Raises Errno::ENOENT
2968 *
2969 * If one or more +args+ is given, each is an argument or option
2970 * to be passed to the executable:
2971 *
2972 * exec('echo', 'C*')
2973 * exec('echo', 'hello', 'world')
2974 *
2975 * Output:
2976 *
2977 * C*
2978 * hello world
2979 *
2980 * Raises an exception if the new process could not execute.
2981 */
2982
2983static VALUE
2984f_exec(int c, const VALUE *a, VALUE _)
2985{
2986 rb_f_exec(c, a);
2988}
2989
2990#define ERRMSG(str) \
2991 ((errmsg && 0 < errmsg_buflen) ? \
2992 (void)strlcpy(errmsg, (str), errmsg_buflen) : (void)0)
2993
2994#define ERRMSG_FMT(...) \
2995 ((errmsg && 0 < errmsg_buflen) ? \
2996 (void)snprintf(errmsg, errmsg_buflen, __VA_ARGS__) : (void)0)
2997
2998static int fd_get_cloexec(int fd, char *errmsg, size_t errmsg_buflen);
2999static int fd_set_cloexec(int fd, char *errmsg, size_t errmsg_buflen);
3000static int fd_clear_cloexec(int fd, char *errmsg, size_t errmsg_buflen);
3001
3002static int
3003save_redirect_fd(int fd, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3004{
3005 if (sargp) {
3006 VALUE newary, redirection;
3007 int save_fd = redirect_cloexec_dup(fd), cloexec;
3008 if (save_fd == -1) {
3009 if (errno == EBADF)
3010 return 0;
3011 ERRMSG("dup");
3012 return -1;
3013 }
3014 rb_update_max_fd(save_fd);
3015 newary = sargp->fd_dup2;
3016 if (newary == Qfalse) {
3017 newary = hide_obj(rb_ary_new());
3018 sargp->fd_dup2 = newary;
3019 }
3020 cloexec = fd_get_cloexec(fd, errmsg, errmsg_buflen);
3021 redirection = hide_obj(rb_assoc_new(INT2FIX(fd), INT2FIX(save_fd)));
3022 if (cloexec) rb_ary_push(redirection, Qtrue);
3023 rb_ary_push(newary, redirection);
3024
3025 newary = sargp->fd_close;
3026 if (newary == Qfalse) {
3027 newary = hide_obj(rb_ary_new());
3028 sargp->fd_close = newary;
3029 }
3030 rb_ary_push(newary, hide_obj(rb_assoc_new(INT2FIX(save_fd), Qnil)));
3031 }
3032
3033 return 0;
3034}
3035
3036static int
3037intcmp(const void *a, const void *b)
3038{
3039 return *(int*)a - *(int*)b;
3040}
3041
3042static int
3043intrcmp(const void *a, const void *b)
3044{
3045 return *(int*)b - *(int*)a;
3046}
3047
3049 int oldfd;
3050 int newfd;
3051 rb_len_t older_index;
3052 rb_len_t num_newer;
3053 int cloexec;
3054};
3055
3056static rb_len_t
3057run_exec_dup2_tmpbuf_size(rb_len_t n)
3058{
3059 return sizeof(struct run_exec_dup2_fd_pair) * n;
3060}
3061
3062/* This function should be async-signal-safe. Actually it is. */
3063static int
3064fd_get_cloexec(int fd, char *errmsg, size_t errmsg_buflen)
3065{
3066#ifdef F_GETFD
3067 int ret = 0;
3068 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
3069 if (ret == -1) {
3070 ERRMSG("fcntl(F_GETFD)");
3071 return -1;
3072 }
3073 if (ret & FD_CLOEXEC) return 1;
3074#endif
3075 return 0;
3076}
3077
3078/* This function should be async-signal-safe. Actually it is. */
3079static int
3080fd_set_cloexec(int fd, char *errmsg, size_t errmsg_buflen)
3081{
3082#ifdef F_GETFD
3083 int ret = 0;
3084 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
3085 if (ret == -1) {
3086 ERRMSG("fcntl(F_GETFD)");
3087 return -1;
3088 }
3089 if (!(ret & FD_CLOEXEC)) {
3090 ret |= FD_CLOEXEC;
3091 ret = fcntl(fd, F_SETFD, ret); /* async-signal-safe */
3092 if (ret == -1) {
3093 ERRMSG("fcntl(F_SETFD)");
3094 return -1;
3095 }
3096 }
3097#endif
3098 return 0;
3099}
3100
3101/* This function should be async-signal-safe. Actually it is. */
3102static int
3103fd_clear_cloexec(int fd, char *errmsg, size_t errmsg_buflen)
3104{
3105#ifdef F_GETFD
3106 int ret;
3107 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
3108 if (ret == -1) {
3109 ERRMSG("fcntl(F_GETFD)");
3110 return -1;
3111 }
3112 if (ret & FD_CLOEXEC) {
3113 ret &= ~FD_CLOEXEC;
3114 ret = fcntl(fd, F_SETFD, ret); /* async-signal-safe */
3115 if (ret == -1) {
3116 ERRMSG("fcntl(F_SETFD)");
3117 return -1;
3118 }
3119 }
3120#endif
3121 return 0;
3122}
3123
3124/* This function should be async-signal-safe when sargp is NULL. Hopefully it is. */
3125static int
3126run_exec_dup2(VALUE ary, VALUE tmpbuf, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3127{
3128 rb_len_t n, i;
3129 int ret;
3130 int extra_fd = -1;
3131 struct run_exec_dup2_fd_pair *pairs = RB_IMEMO_TMPBUF_PTR(tmpbuf);
3132
3133 n = RARRAY_LEN(ary);
3134
3135 /* initialize oldfd and newfd: O(n) */
3136 for (i = 0; i < n; i++) {
3137 VALUE elt = RARRAY_AREF(ary, i);
3138 pairs[i].oldfd = FIX2INT(RARRAY_AREF(elt, 1));
3139 pairs[i].newfd = FIX2INT(RARRAY_AREF(elt, 0)); /* unique */
3140 pairs[i].cloexec = RARRAY_LEN(elt) > 2 && RTEST(RARRAY_AREF(elt, 2));
3141 pairs[i].older_index = -1;
3142 }
3143
3144 /* sort the table by oldfd: O(n log n) */
3145 if (!sargp)
3146 qsort(pairs, n, sizeof(struct run_exec_dup2_fd_pair), intcmp); /* hopefully async-signal-safe */
3147 else
3148 qsort(pairs, n, sizeof(struct run_exec_dup2_fd_pair), intrcmp);
3149
3150 /* initialize older_index and num_newer: O(n log n) */
3151 for (i = 0; i < n; i++) {
3152 int newfd = pairs[i].newfd;
3153 struct run_exec_dup2_fd_pair key, *found;
3154 key.oldfd = newfd;
3155 found = bsearch(&key, pairs, n, sizeof(struct run_exec_dup2_fd_pair), intcmp); /* hopefully async-signal-safe */
3156 pairs[i].num_newer = 0;
3157 if (found) {
3158 while (pairs < found && (found-1)->oldfd == newfd)
3159 found--;
3160 while (found < pairs+n && found->oldfd == newfd) {
3161 pairs[i].num_newer++;
3162 found->older_index = i;
3163 found++;
3164 }
3165 }
3166 }
3167
3168 /* non-cyclic redirection: O(n) */
3169 for (i = 0; i < n; i++) {
3170 rb_len_t j = i;
3171 while (j != -1 && pairs[j].oldfd != -1 && pairs[j].num_newer == 0) {
3172 if (save_redirect_fd(pairs[j].newfd, sargp, errmsg, errmsg_buflen) < 0) /* async-signal-safe */
3173 goto fail;
3174 ret = redirect_dup2(pairs[j].oldfd, pairs[j].newfd); /* async-signal-safe */
3175 if (ret == -1) {
3176 ERRMSG("dup2");
3177 goto fail;
3178 }
3179 if (pairs[j].cloexec &&
3180 fd_set_cloexec(pairs[j].newfd, errmsg, errmsg_buflen)) {
3181 goto fail;
3182 }
3183 rb_update_max_fd(pairs[j].newfd); /* async-signal-safe but don't need to call it in a child process. */
3184 pairs[j].oldfd = -1;
3185 j = pairs[j].older_index;
3186 if (j != -1)
3187 pairs[j].num_newer--;
3188 }
3189 }
3190
3191 /* cyclic redirection: O(n) */
3192 for (i = 0; i < n; i++) {
3193 rb_len_t j;
3194 if (pairs[i].oldfd == -1)
3195 continue;
3196 if (pairs[i].oldfd == pairs[i].newfd) { /* self cycle */
3197 if (fd_clear_cloexec(pairs[i].oldfd, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3198 goto fail;
3199 pairs[i].oldfd = -1;
3200 continue;
3201 }
3202 if (extra_fd == -1) {
3203 extra_fd = redirect_dup(pairs[i].oldfd); /* async-signal-safe */
3204 if (extra_fd == -1) {
3205 ERRMSG("dup");
3206 goto fail;
3207 }
3208 // without this, kqueue timer_th.event_fd fails with a reserved FD did not have close-on-exec
3209 // in #assert_close_on_exec because the FD_CLOEXEC is not dup'd by default
3210 if (fd_get_cloexec(pairs[i].oldfd, errmsg, errmsg_buflen)) {
3211 if (fd_set_cloexec(extra_fd, errmsg, errmsg_buflen)) {
3212 close(extra_fd);
3213 goto fail;
3214 }
3215 }
3216 rb_update_max_fd(extra_fd);
3217 }
3218 else {
3219 ret = redirect_dup2(pairs[i].oldfd, extra_fd); /* async-signal-safe */
3220 if (ret == -1) {
3221 ERRMSG("dup2");
3222 goto fail;
3223 }
3224 rb_update_max_fd(extra_fd);
3225 }
3226 pairs[i].oldfd = extra_fd;
3227 j = pairs[i].older_index;
3228 pairs[i].older_index = -1;
3229 while (j != -1) {
3230 ret = redirect_dup2(pairs[j].oldfd, pairs[j].newfd); /* async-signal-safe */
3231 if (ret == -1) {
3232 ERRMSG("dup2");
3233 goto fail;
3234 }
3235 rb_update_max_fd(ret);
3236 pairs[j].oldfd = -1;
3237 j = pairs[j].older_index;
3238 }
3239 }
3240 if (extra_fd != -1) {
3241 ret = redirect_close(extra_fd); /* async-signal-safe */
3242 if (ret == -1) {
3243 ERRMSG("close");
3244 goto fail;
3245 }
3246 }
3247
3248 return 0;
3249
3250 fail:
3251 return -1;
3252}
3253
3254/* This function should be async-signal-safe. Actually it is. */
3255static int
3256run_exec_close(VALUE ary, char *errmsg, size_t errmsg_buflen)
3257{
3258 rb_len_t i;
3259 int ret;
3260
3261 for (i = 0; i < RARRAY_LEN(ary); i++) {
3262 VALUE elt = RARRAY_AREF(ary, i);
3263 int fd = FIX2INT(RARRAY_AREF(elt, 0));
3264 ret = redirect_close(fd); /* async-signal-safe */
3265 if (ret == -1) {
3266 ERRMSG("close");
3267 return -1;
3268 }
3269 }
3270 return 0;
3271}
3272
3273/* This function should be async-signal-safe when sargp is NULL. Actually it is. */
3274static int
3275run_exec_dup2_child(VALUE ary, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3276{
3277 rb_len_t i;
3278 int ret;
3279
3280 for (i = 0; i < RARRAY_LEN(ary); i++) {
3281 VALUE elt = RARRAY_AREF(ary, i);
3282 int newfd = FIX2INT(RARRAY_AREF(elt, 0));
3283 int oldfd = FIX2INT(RARRAY_AREF(elt, 1));
3284
3285 if (save_redirect_fd(newfd, sargp, errmsg, errmsg_buflen) < 0) /* async-signal-safe */
3286 return -1;
3287 ret = redirect_dup2(oldfd, newfd); /* async-signal-safe */
3288 if (ret == -1) {
3289 ERRMSG("dup2");
3290 return -1;
3291 }
3292 rb_update_max_fd(newfd);
3293 }
3294 return 0;
3295}
3296
3297#ifdef HAVE_SETPGID
3298/* This function should be async-signal-safe when sargp is NULL. Actually it is. */
3299static int
3300run_exec_pgroup(const struct rb_execarg *eargp, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3301{
3302 /*
3303 * If FD_CLOEXEC is available, rb_fork_async_signal_safe waits the child's execve.
3304 * So setpgid is done in the child when rb_fork_async_signal_safe is returned in
3305 * the parent.
3306 * No race condition, even without setpgid from the parent.
3307 * (Is there an environment which has setpgid but no FD_CLOEXEC?)
3308 */
3309 int ret;
3310 rb_pid_t pgroup;
3311
3312 pgroup = eargp->pgroup_pgid;
3313 if (pgroup == -1)
3314 return 0;
3315
3316 if (sargp) {
3317 /* maybe meaningless with no fork environment... */
3318 sargp->pgroup_given = 1;
3319 sargp->pgroup_pgid = getpgrp();
3320 }
3321
3322 if (pgroup == 0) {
3323 pgroup = getpid(); /* async-signal-safe */
3324 }
3325 ret = setpgid(getpid(), pgroup); /* async-signal-safe */
3326 if (ret == -1) ERRMSG("setpgid");
3327 return ret;
3328}
3329#endif
3330
3331#if defined(HAVE_SETRLIMIT) && defined(RLIM2NUM)
3332/* This function should be async-signal-safe when sargp is NULL. Hopefully it is. */
3333static int
3334run_exec_rlimit(VALUE ary, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3335{
3336 rb_len_t i;
3337 for (i = 0; i < RARRAY_LEN(ary); i++) {
3338 VALUE elt = RARRAY_AREF(ary, i);
3339 int rtype = NUM2INT(RARRAY_AREF(elt, 0));
3340 struct rlimit rlim;
3341 if (sargp) {
3342 VALUE tmp, newary;
3343 if (getrlimit(rtype, &rlim) == -1) {
3344 ERRMSG("getrlimit");
3345 return -1;
3346 }
3347 tmp = hide_obj(rb_ary_new3(3, RARRAY_AREF(elt, 0),
3348 RLIM2NUM(rlim.rlim_cur),
3349 RLIM2NUM(rlim.rlim_max)));
3350 if (sargp->rlimit_limits == Qfalse)
3351 newary = sargp->rlimit_limits = hide_obj(rb_ary_new());
3352 else
3353 newary = sargp->rlimit_limits;
3354 rb_ary_push(newary, tmp);
3355 }
3356 rlim.rlim_cur = NUM2RLIM(RARRAY_AREF(elt, 1));
3357 rlim.rlim_max = NUM2RLIM(RARRAY_AREF(elt, 2));
3358 if (setrlimit(rtype, &rlim) == -1) { /* hopefully async-signal-safe */
3359 ERRMSG("setrlimit");
3360 return -1;
3361 }
3362 }
3363 return 0;
3364}
3365#endif
3366
3367#if !defined(HAVE_WORKING_FORK)
3368static VALUE
3369save_env_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3370{
3371 rb_ary_push(ary, hide_obj(rb_ary_dup(argv[0])));
3372 return Qnil;
3373}
3374
3375static void
3376save_env(struct rb_execarg *sargp)
3377{
3378 if (!sargp)
3379 return;
3380 if (sargp->env_modification == Qfalse) {
3381 VALUE env = rb_envtbl();
3382 if (RTEST(env)) {
3383 VALUE ary = hide_obj(rb_ary_new());
3384 rb_block_call(env, idEach, 0, 0, save_env_i,
3385 (VALUE)ary);
3386 sargp->env_modification = ary;
3387 }
3388 sargp->unsetenv_others_given = 1;
3389 sargp->unsetenv_others_do = 1;
3390 }
3391}
3392#endif
3393
3394#ifdef _WIN32
3395#undef chdir
3396#define chdir(p) rb_w32_uchdir(p)
3397#endif
3398
3399/* This function should be async-signal-safe when sargp is NULL. Hopefully it is. */
3400int
3401rb_execarg_run_options(const struct rb_execarg *eargp, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3402{
3403 VALUE obj;
3404
3405 if (sargp) {
3406 /* assume that sargp is always NULL on fork-able environments */
3407 MEMZERO(sargp, struct rb_execarg, 1);
3408 sargp->redirect_fds = Qnil;
3409 }
3410
3411#ifdef HAVE_SETPGID
3412 if (eargp->pgroup_given) {
3413 if (run_exec_pgroup(eargp, sargp, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3414 return -1;
3415 }
3416#endif
3417
3418#if defined(HAVE_SETRLIMIT) && defined(RLIM2NUM)
3419 obj = eargp->rlimit_limits;
3420 if (obj != Qfalse) {
3421 if (run_exec_rlimit(obj, sargp, errmsg, errmsg_buflen) == -1) /* hopefully async-signal-safe */
3422 return -1;
3423 }
3424#endif
3425
3426#if !defined(HAVE_WORKING_FORK)
3427 if (eargp->unsetenv_others_given && eargp->unsetenv_others_do) {
3428 save_env(sargp);
3429 rb_env_clear();
3430 }
3431
3432 obj = eargp->env_modification;
3433 if (obj != Qfalse) {
3434 rb_len_t i;
3435 save_env(sargp);
3436 for (i = 0; i < RARRAY_LEN(obj); i++) {
3437 VALUE pair = RARRAY_AREF(obj, i);
3438 VALUE key = RARRAY_AREF(pair, 0);
3439 VALUE val = RARRAY_AREF(pair, 1);
3440 const char *name = RSTRING_PTR(key);
3441 ruby_setenv(name, NIL_P(val) ? 0 : RSTRING_PTR(val));
3442 }
3443 }
3444#endif
3445
3446 if (eargp->umask_given) {
3447 mode_t mask = eargp->umask_mask;
3448 mode_t oldmask = umask(mask); /* never fail */ /* async-signal-safe */
3449 if (sargp) {
3450 sargp->umask_given = 1;
3451 sargp->umask_mask = oldmask;
3452 }
3453 }
3454
3455 if (sargp && (eargp->fd_dup2 != Qfalse || eargp->fd_dup2_child != Qfalse)) {
3456 rb_len_t n = 0;
3457 if (eargp->fd_dup2 != Qfalse) n += RARRAY_LEN(eargp->fd_dup2);
3458 if (eargp->fd_dup2_child != Qfalse) n += RARRAY_LEN(eargp->fd_dup2_child);
3459 rb_execarg_allocate_dup2_tmpbuf(sargp, n);
3460 }
3461
3462 obj = eargp->fd_dup2;
3463 if (obj != Qfalse) {
3464 if (run_exec_dup2(obj, eargp->dup2_tmpbuf, sargp, errmsg, errmsg_buflen) == -1) /* hopefully async-signal-safe */
3465 return -1;
3466 }
3467
3468 obj = eargp->fd_close;
3469 if (obj != Qfalse) {
3470 if (sargp)
3471 rb_warn("cannot close fd before spawn");
3472 else {
3473 if (run_exec_close(obj, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3474 return -1;
3475 }
3476 }
3477
3478#ifdef HAVE_WORKING_FORK
3479 if (eargp->close_others_do) {
3480 rb_close_before_exec(3, eargp->close_others_maxhint, eargp->redirect_fds); /* async-signal-safe */
3481 }
3482#endif
3483
3484 obj = eargp->fd_dup2_child;
3485 if (obj != Qfalse) {
3486 if (run_exec_dup2_child(obj, sargp, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3487 return -1;
3488 }
3489
3490 if (eargp->chdir_given) {
3491 if (sargp) {
3492 sargp->chdir_given = 1;
3493 sargp->chdir_dir = hide_obj(rb_dir_getwd_ospath());
3494 }
3495 if (chdir(RSTRING_PTR(eargp->chdir_dir)) == -1) { /* async-signal-safe */
3496 ERRMSG("chdir");
3497 return -1;
3498 }
3499 }
3500
3501#ifdef HAVE_SETGID
3502 if (eargp->gid_given) {
3503 if (setgid(eargp->gid) < 0) {
3504 ERRMSG("setgid");
3505 return -1;
3506 }
3507 }
3508#endif
3509#ifdef HAVE_SETUID
3510 if (eargp->uid_given) {
3511 if (setuid(eargp->uid) < 0) {
3512 ERRMSG("setuid");
3513 return -1;
3514 }
3515 }
3516#endif
3517
3518 {
3519 int preserve = errno;
3520 stdfd_clear_nonblock();
3521 errno = preserve;
3522 }
3523
3524 return 0;
3525}
3526#if !defined(HAVE_WORKING_FORK)
3527# define execarg_restore(sargp) rb_execarg_run_options((sargp), NULL, errmsg, errmsg_buflen)
3528#else
3529# define execarg_restore(sargp) (void)0
3530#endif
3531
3532/* This function should be async-signal-safe. Hopefully it is. */
3533int
3534rb_exec_async_signal_safe(const struct rb_execarg *eargp, char *errmsg, size_t errmsg_buflen)
3535{
3536 errno = exec_async_signal_safe(eargp, errmsg, errmsg_buflen);
3537 return -1;
3538}
3539
3540static int
3541exec_async_signal_safe(const struct rb_execarg *eargp, char *errmsg, size_t errmsg_buflen)
3542{
3543#if !defined(HAVE_WORKING_FORK)
3544 struct rb_execarg sarg, *const sargp = &sarg;
3545#else
3546 struct rb_execarg *const sargp = NULL;
3547#endif
3548 int err;
3549
3550 if (rb_execarg_run_options(eargp, sargp, errmsg, errmsg_buflen) < 0) { /* hopefully async-signal-safe */
3551 err = errno;
3552 execarg_restore(sargp);
3553 return err;
3554 }
3555
3556 if (eargp->use_shell) {
3557 err = proc_exec_sh(RSTRING_PTR(eargp->invoke.sh.shell_script), eargp->envp_str); /* async-signal-safe */
3558 }
3559 else {
3560 char *abspath = NULL;
3561 if (!NIL_P(eargp->invoke.cmd.command_abspath))
3562 abspath = RSTRING_PTR(eargp->invoke.cmd.command_abspath);
3563 err = proc_exec_cmd(abspath, eargp->invoke.cmd.argv_str, eargp->envp_str); /* async-signal-safe */
3564 }
3565 execarg_restore(sargp);
3566
3567 return err;
3568}
3569
3570#ifdef HAVE_WORKING_FORK
3571/* This function should be async-signal-safe. Hopefully it is. */
3572static int
3573rb_exec_atfork(void* arg, char *errmsg, size_t errmsg_buflen)
3574{
3575 return rb_exec_async_signal_safe(arg, errmsg, errmsg_buflen); /* hopefully async-signal-safe */
3576}
3577
3578static VALUE
3579proc_syswait(VALUE pid)
3580{
3581 rb_syswait((rb_pid_t)pid);
3582 return Qnil;
3583}
3584
3585static int
3586move_fds_to_avoid_crash(int *fdp, int n, VALUE fds)
3587{
3588 int min = 0;
3589 int i;
3590 for (i = 0; i < n; i++) {
3591 int ret;
3592 while (RTEST(rb_hash_lookup(fds, INT2FIX(fdp[i])))) {
3593 if (min <= fdp[i])
3594 min = fdp[i]+1;
3595 while (RTEST(rb_hash_lookup(fds, INT2FIX(min))))
3596 min++;
3597 ret = rb_cloexec_fcntl_dupfd(fdp[i], min);
3598 if (ret == -1)
3599 return -1;
3600 rb_update_max_fd(ret);
3601 close(fdp[i]);
3602 fdp[i] = ret;
3603 }
3604 }
3605 return 0;
3606}
3607
3608static int
3609pipe_nocrash(int filedes[2], VALUE fds)
3610{
3611 int ret;
3612 ret = rb_pipe(filedes);
3613 if (ret == -1)
3614 return -1;
3615 if (RTEST(fds)) {
3616 int save = errno;
3617 if (move_fds_to_avoid_crash(filedes, 2, fds) == -1) {
3618 close(filedes[0]);
3619 close(filedes[1]);
3620 return -1;
3621 }
3622 errno = save;
3623 }
3624 return ret;
3625}
3626
3627#ifndef O_BINARY
3628#define O_BINARY 0
3629#endif
3630
3631static VALUE
3632rb_thread_sleep_that_takes_VALUE_as_sole_argument(VALUE n)
3633{
3635 return Qundef;
3636}
3637
3638static int
3639handle_fork_error(int err, struct rb_process_status *status, int *ep, volatile int *try_gc_p)
3640{
3641 int state = 0;
3642
3643 switch (err) {
3644 case ENOMEM:
3645 if ((*try_gc_p)-- > 0 && !rb_during_gc()) {
3646 rb_gc();
3647 return 0;
3648 }
3649 break;
3650 case EAGAIN:
3651#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
3652 case EWOULDBLOCK:
3653#endif
3654 if (!status && !ep) {
3655 rb_thread_sleep(1);
3656 return 0;
3657 }
3658 else {
3659 rb_protect(rb_thread_sleep_that_takes_VALUE_as_sole_argument, INT2FIX(1), &state);
3660 if (status) status->status = state;
3661 if (!state) return 0;
3662 }
3663 break;
3664 }
3665 if (ep) {
3666 close(ep[0]);
3667 close(ep[1]);
3668 errno = err;
3669 }
3670 if (state && !status) rb_jump_tag(state);
3671 return -1;
3672}
3673
3674/* Flush the current Ractor's own stdio: taking the write_lock of an IO owned
3675 * by another Ractor can block on a thread that rb_check_deadlock can't see. */
3676#define prefork() ( \
3677 rb_io_flush(rb_ractor_stdout()), \
3678 rb_io_flush(rb_ractor_stderr()) \
3679 )
3680
3681/*
3682 * Forks child process, and returns the process ID in the parent
3683 * process.
3684 *
3685 * If +status+ is given, protects from any exceptions and sets the
3686 * jump status to it, and returns -1. If failed to fork new process
3687 * but no exceptions occurred, sets 0 to it. Otherwise, if forked
3688 * successfully, the value of +status+ is undetermined.
3689 *
3690 * In the child process, just returns 0 if +chfunc+ is +NULL+.
3691 * Otherwise +chfunc+ will be called with +charg+, and then the child
3692 * process exits with +EXIT_SUCCESS+ when it returned zero.
3693 *
3694 * In the case of the function is called and returns non-zero value,
3695 * the child process exits with non-+EXIT_SUCCESS+ value (normally
3696 * 127). And, on the platforms where +FD_CLOEXEC+ is available,
3697 * +errno+ is propagated to the parent process, and this function
3698 * returns -1 in the parent process. On the other platforms, just
3699 * returns pid.
3700 *
3701 * If fds is not Qnil, internal pipe for the errno propagation is
3702 * arranged to avoid conflicts of the hash keys in +fds+.
3703 *
3704 * +chfunc+ must not raise any exceptions.
3705 */
3706
3707static ssize_t
3708write_retry(int fd, const void *buf, size_t len)
3709{
3710 ssize_t w;
3711
3712 do {
3713 w = write(fd, buf, len);
3714 } while (w < 0 && errno == EINTR);
3715
3716 return w;
3717}
3718
3719static ssize_t
3720read_retry(int fd, void *buf, size_t len)
3721{
3722 ssize_t r;
3723
3724 if (set_blocking(fd) != 0) {
3725#ifndef _WIN32
3726 rb_async_bug_errno("set_blocking failed reading child error", errno);
3727#endif
3728 }
3729
3730 do {
3731 r = read(fd, buf, len);
3732 } while (r < 0 && errno == EINTR);
3733
3734 return r;
3735}
3736
3737static void
3738send_child_error(int fd, char *errmsg, size_t errmsg_buflen)
3739{
3740 int err;
3741
3742 err = errno;
3743 if (write_retry(fd, &err, sizeof(err)) < 0) err = errno;
3744 if (errmsg && 0 < errmsg_buflen) {
3745 errmsg[errmsg_buflen-1] = '\0';
3746 errmsg_buflen = strlen(errmsg);
3747 if (errmsg_buflen > 0 && write_retry(fd, errmsg, errmsg_buflen) < 0)
3748 err = errno;
3749 }
3750}
3751
3752static int
3753recv_child_error(int fd, int *errp, char *errmsg, size_t errmsg_buflen)
3754{
3755 int err;
3756 ssize_t size;
3757 if ((size = read_retry(fd, &err, sizeof(err))) < 0) {
3758 err = errno;
3759 }
3760 *errp = err;
3761 if (size == sizeof(err) &&
3762 errmsg && 0 < errmsg_buflen) {
3763 ssize_t ret = read_retry(fd, errmsg, errmsg_buflen-1);
3764 if (0 <= ret) {
3765 errmsg[ret] = '\0';
3766 }
3767 }
3768 close(fd);
3769 return size != 0;
3770}
3771
3772#ifdef HAVE_WORKING_VFORK
3773#if !defined(HAVE_GETRESUID) && defined(HAVE_GETUIDX)
3774/* AIX 7.1 */
3775static int
3776getresuid(rb_uid_t *ruid, rb_uid_t *euid, rb_uid_t *suid)
3777{
3778 rb_uid_t ret;
3779
3780 *ruid = getuid();
3781 *euid = geteuid();
3782 ret = getuidx(ID_SAVED);
3783 if (ret == (rb_uid_t)-1)
3784 return -1;
3785 *suid = ret;
3786 return 0;
3787}
3788#define HAVE_GETRESUID
3789#endif
3790
3791#if !defined(HAVE_GETRESGID) && defined(HAVE_GETGIDX)
3792/* AIX 7.1 */
3793static int
3794getresgid(rb_gid_t *rgid, rb_gid_t *egid, rb_gid_t *sgid)
3795{
3796 rb_gid_t ret;
3797
3798 *rgid = getgid();
3799 *egid = getegid();
3800 ret = getgidx(ID_SAVED);
3801 if (ret == (rb_gid_t)-1)
3802 return -1;
3803 *sgid = ret;
3804 return 0;
3805}
3806#define HAVE_GETRESGID
3807#endif
3808
3809#if !defined(RUBY_ASAN_ENABLED)
3810static int
3811has_privilege(void)
3812{
3813 /*
3814 * has_privilege() is used to choose vfork() or fork().
3815 *
3816 * If the process has privilege, the parent process or
3817 * the child process can change UID/GID.
3818 * If vfork() is used to create the child process and
3819 * the parent or child process change effective UID/GID,
3820 * different privileged processes shares memory.
3821 * It is a bad situation.
3822 * So, fork() should be used.
3823 */
3824
3825 rb_uid_t ruid, euid;
3826 rb_gid_t rgid, egid;
3827
3828#if defined HAVE_ISSETUGID
3829 if (issetugid())
3830 return 1;
3831#endif
3832
3833#ifdef HAVE_GETRESUID
3834 {
3835 int ret;
3836 rb_uid_t suid;
3837 ret = getresuid(&ruid, &euid, &suid);
3838 if (ret == -1)
3839 rb_sys_fail("getresuid(2)");
3840 if (euid != suid)
3841 return 1;
3842 }
3843#else
3844 ruid = getuid();
3845 euid = geteuid();
3846#endif
3847
3848 if (euid == 0 || euid != ruid)
3849 return 1;
3850
3851#ifdef HAVE_GETRESGID
3852 {
3853 int ret;
3854 rb_gid_t sgid;
3855 ret = getresgid(&rgid, &egid, &sgid);
3856 if (ret == -1)
3857 rb_sys_fail("getresgid(2)");
3858 if (egid != sgid)
3859 return 1;
3860 }
3861#else
3862 rgid = getgid();
3863 egid = getegid();
3864#endif
3865
3866 if (egid != rgid)
3867 return 1;
3868
3869 return 0;
3870}
3871#endif
3872#endif
3873
3874struct child_handler_disabler_state
3875{
3876 sigset_t sigmask;
3877};
3878
3879static void
3880disable_child_handler_before_fork(struct child_handler_disabler_state *old)
3881{
3882#ifdef HAVE_PTHREAD_SIGMASK
3883 int ret;
3884 sigset_t all;
3885
3886 ret = sigfillset(&all);
3887 if (ret == -1)
3888 rb_sys_fail("sigfillset");
3889
3890 ret = pthread_sigmask(SIG_SETMASK, &all, &old->sigmask); /* not async-signal-safe */
3891 if (ret != 0) {
3892 rb_syserr_fail(ret, "pthread_sigmask");
3893 }
3894#else
3895# pragma GCC warning "pthread_sigmask on fork is not available. potentially dangerous"
3896#endif
3897}
3898
3899static void
3900disable_child_handler_fork_parent(struct child_handler_disabler_state *old)
3901{
3902#ifdef HAVE_PTHREAD_SIGMASK
3903 int ret;
3904
3905 ret = pthread_sigmask(SIG_SETMASK, &old->sigmask, NULL); /* not async-signal-safe */
3906 if (ret != 0) {
3907 rb_syserr_fail(ret, "pthread_sigmask");
3908 }
3909#else
3910# pragma GCC warning "pthread_sigmask on fork is not available. potentially dangerous"
3911#endif
3912}
3913
3914/* This function should be async-signal-safe. Actually it is. */
3915static int
3916disable_child_handler_fork_child(struct child_handler_disabler_state *old, char *errmsg, size_t errmsg_buflen)
3917{
3918 int sig;
3919 int ret;
3920
3921 for (sig = 1; sig < NSIG; sig++) {
3922 sig_t handler = signal(sig, SIG_DFL);
3923
3924 if (handler == SIG_ERR && errno == EINVAL) {
3925 continue; /* Ignore invalid signal number */
3926 }
3927 if (handler == SIG_ERR) {
3928 ERRMSG("signal to obtain old action");
3929 return -1;
3930 }
3931#ifdef SIGPIPE
3932 if (sig == SIGPIPE) {
3933 continue;
3934 }
3935#endif
3936 /* it will be reset to SIG_DFL at execve time, instead */
3937 if (handler == SIG_IGN) {
3938 signal(sig, SIG_IGN);
3939 }
3940 }
3941
3942 /* non-Ruby child process, ensure cmake can see SIGCHLD */
3943 sigemptyset(&old->sigmask);
3944 ret = sigprocmask(SIG_SETMASK, &old->sigmask, NULL); /* async-signal-safe */
3945 if (ret != 0) {
3946 ERRMSG("sigprocmask");
3947 return -1;
3948 }
3949 return 0;
3950}
3951
3952static rb_pid_t
3953retry_fork_async_signal_safe(struct rb_process_status *status, int *ep,
3954 int (*chfunc)(void*, char *, size_t), void *charg,
3955 char *errmsg, size_t errmsg_buflen,
3956 struct waitpid_state *w)
3957{
3958 rb_pid_t pid;
3959 volatile int try_gc = 1;
3960 struct child_handler_disabler_state old;
3961 int err;
3962
3963 while (1) {
3964 prefork();
3965 disable_child_handler_before_fork(&old);
3966
3967 // Older versions of ASAN does not work with vfork
3968 // See https://github.com/google/sanitizers/issues/925
3969#if defined(HAVE_WORKING_VFORK) && !defined(RUBY_ASAN_ENABLED)
3970 if (!has_privilege())
3971 pid = vfork();
3972 else
3973 pid = rb_fork();
3974#else
3975 pid = rb_fork();
3976#endif
3977 if (pid == 0) {/* fork succeed, child process */
3978 int ret;
3979 close(ep[0]);
3980 ret = disable_child_handler_fork_child(&old, errmsg, errmsg_buflen); /* async-signal-safe */
3981 if (ret == 0) {
3982 ret = chfunc(charg, errmsg, errmsg_buflen);
3983 if (!ret) _exit(EXIT_SUCCESS);
3984 }
3985 send_child_error(ep[1], errmsg, errmsg_buflen);
3986#if EXIT_SUCCESS == 127
3987 _exit(EXIT_FAILURE);
3988#else
3989 _exit(127);
3990#endif
3991 }
3992 err = errno;
3993 disable_child_handler_fork_parent(&old);
3994 if (0 < pid) /* fork succeed, parent process */
3995 return pid;
3996 /* fork failed */
3997 if (handle_fork_error(err, status, ep, &try_gc))
3998 return -1;
3999 }
4000}
4001
4002static rb_pid_t
4003fork_check_err(struct rb_process_status *status, int (*chfunc)(void*, char *, size_t), void *charg,
4004 VALUE fds, char *errmsg, size_t errmsg_buflen,
4005 struct rb_execarg *eargp)
4006{
4007 rb_pid_t pid;
4008 int err;
4009 int ep[2];
4010 int error_occurred;
4011
4012 struct waitpid_state *w = eargp && eargp->waitpid_state ? eargp->waitpid_state : 0;
4013
4014 if (status) status->status = 0;
4015
4016 if (pipe_nocrash(ep, fds)) return -1;
4017
4018 pid = retry_fork_async_signal_safe(status, ep, chfunc, charg, errmsg, errmsg_buflen, w);
4019
4020 if (status) status->pid = pid;
4021
4022 if (pid < 0) {
4023 if (status) status->error = errno;
4024
4025 return pid;
4026 }
4027
4028 close(ep[1]);
4029
4030 error_occurred = recv_child_error(ep[0], &err, errmsg, errmsg_buflen);
4031
4032 if (error_occurred) {
4033 if (status) {
4034 int state = 0;
4035 status->error = err;
4036
4037 VM_ASSERT((w == 0) && "only used by extensions");
4038 rb_protect(proc_syswait, (VALUE)pid, &state);
4039
4040 status->status = state;
4041 }
4042 else if (!w) {
4043 rb_syswait(pid);
4044 }
4045
4046 errno = err;
4047 return -1;
4048 }
4049
4050 return pid;
4051}
4052
4053/*
4054 * The "async_signal_safe" name is a lie, but it is used by pty.c and
4055 * maybe other exts. fork() is not async-signal-safe due to pthread_atfork
4056 * and future POSIX revisions will remove it from a list of signal-safe
4057 * functions. rb_waitpid is not async-signal-safe.
4058 * For our purposes, we do not need async-signal-safety, here
4059 */
4060rb_pid_t
4061rb_fork_async_signal_safe(int *status,
4062 int (*chfunc)(void*, char *, size_t), void *charg,
4063 VALUE fds, char *errmsg, size_t errmsg_buflen)
4064{
4065 struct rb_process_status process_status;
4066
4067 rb_pid_t result = fork_check_err(&process_status, chfunc, charg, fds, errmsg, errmsg_buflen, 0);
4068
4069 if (status) {
4070 *status = process_status.status;
4071 }
4072
4073 return result;
4074}
4075
4076rb_pid_t
4077rb_fork_ruby(int *status)
4078{
4079 if (UNLIKELY(!rb_ractor_main_p())) {
4080 rb_raise(rb_eRactorIsolationError, "can not fork from non-main Ractors");
4081 }
4082
4083 struct rb_process_status child = {.status = 0};
4084 rb_pid_t pid;
4085 int try_gc = 1, err = 0;
4086 struct child_handler_disabler_state old;
4087
4088 do {
4089 prefork();
4090
4091 before_fork_ruby();
4092 rb_thread_acquire_fork_lock();
4093 disable_child_handler_before_fork(&old);
4094
4095 RB_VM_LOCKING() {
4096 child.pid = pid = rb_fork();
4097 child.error = err = errno;
4098 }
4099
4100 disable_child_handler_fork_parent(&old); /* yes, bad name */
4101 release_fork_lock_after_fork(pid);
4102 after_fork_ruby(pid);
4103
4104 /* repeat while fork failed but retryable */
4105 } while (pid < 0 && handle_fork_error(err, status ? &child : NULL, NULL, &try_gc) == 0);
4106
4107 if (status) *status = child.status;
4108
4109 return pid;
4110}
4111
4112static rb_pid_t
4113proc_fork_pid(void)
4114{
4115 rb_pid_t pid = rb_fork_ruby(NULL);
4116
4117 if (pid == -1) {
4118 rb_sys_fail("fork(2)");
4119 }
4120
4121 return pid;
4122}
4123
4124static VALUE
4125call_proc__fork_protected(VALUE arg)
4126{
4127 VALUE ret = rb_funcall(rb_mProcess, id__fork, 0);
4128 *(rb_pid_t *)arg = NUM2PIDT(ret);
4129 /* discard the returned object itself */
4130 return Qtrue;
4131}
4132
4133rb_pid_t
4134rb_call_proc__fork(void)
4135{
4137 return proc_fork_pid();
4138 }
4139 else {
4140 rb_pid_t parent = getpid(), pid;
4141 int state;
4142
4143 if (NIL_P(rb_protect(call_proc__fork_protected, (VALUE)&pid, &state))) {
4144 if (getpid() != parent) {
4145 ruby_stop(state);
4146 }
4147 rb_jump_tag(state);
4148 }
4149 return pid;
4150 }
4151}
4152#endif
4153
4154#if defined(HAVE_WORKING_FORK) && !defined(CANNOT_FORK_WITH_PTHREAD)
4155/*
4156 * call-seq:
4157 * Process._fork -> integer
4158 *
4159 * An internal API for fork. Do not call this method directly.
4160 * Currently, this is called via Kernel#fork, Process.fork, and
4161 * IO.popen with <tt>"-"</tt>.
4162 *
4163 * This method is not for casual code but for application monitoring
4164 * libraries. You can add custom code before and after fork events
4165 * by overriding this method.
4166 *
4167 * Note: Process.daemon may be implemented using fork(2) BUT does not go
4168 * through this method.
4169 * Thus, depending on your reason to hook into this method, you
4170 * may also want to hook into that one.
4171 * See {this issue}[https://bugs.ruby-lang.org/issues/18911] for a
4172 * more detailed discussion of this.
4173 */
4174VALUE
4175rb_proc__fork(VALUE _obj)
4176{
4177 rb_pid_t pid = proc_fork_pid();
4178 return PIDT2NUM(pid);
4179}
4180
4181/*
4182 * call-seq:
4183 * Process.fork { ... } -> integer or nil
4184 * Process.fork -> integer or nil
4185 *
4186 * Creates a child process.
4187 *
4188 * With a block given, runs the block in the child process;
4189 * on block exit, the child terminates with a status of zero:
4190 *
4191 * puts "Before the fork: #{Process.pid}"
4192 * fork do
4193 * puts "In the child process: #{Process.pid}"
4194 * end # => 420520
4195 * puts "After the fork: #{Process.pid}"
4196 *
4197 * Output:
4198 *
4199 * Before the fork: 420496
4200 * After the fork: 420496
4201 * In the child process: 420520
4202 *
4203 * With no block given, the +fork+ call returns twice:
4204 *
4205 * - Once in the parent process, returning the pid of the child process.
4206 * - Once in the child process, returning +nil+.
4207 *
4208 * Example:
4209 *
4210 * puts "This is the first line before the fork (pid #{Process.pid})"
4211 * puts fork
4212 * puts "This is the second line after the fork (pid #{Process.pid})"
4213 *
4214 * Output:
4215 *
4216 * This is the first line before the fork (pid 420199)
4217 * 420223
4218 * This is the second line after the fork (pid 420199)
4219 *
4220 * This is the second line after the fork (pid 420223)
4221 *
4222 * In either case, the child process may exit using
4223 * Kernel.exit! to avoid the call to Kernel#at_exit.
4224 *
4225 * To avoid zombie processes, the parent process should call either:
4226 *
4227 * - Process.wait, to collect the termination statuses of its children.
4228 * - Process.detach, to register disinterest in their status.
4229 *
4230 * The thread calling +fork+ is the only thread in the created child process;
4231 * +fork+ doesn't copy other threads.
4232 *
4233 * Note that method +fork+ is available on some platforms,
4234 * but not on others:
4235 *
4236 * Process.respond_to?(:fork) # => true # Would be false on some.
4237 *
4238 * If not, you may use ::spawn instead of +fork+.
4239 */
4240
4241static VALUE
4242rb_f_fork(VALUE obj)
4243{
4244 rb_pid_t pid;
4245
4246 pid = rb_call_proc__fork();
4247
4248 if (pid == 0) {
4249 if (rb_block_given_p()) {
4250 int status;
4251 rb_protect(rb_yield, Qundef, &status);
4252 ruby_stop(status);
4253 }
4254 return Qnil;
4255 }
4256
4257 return PIDT2NUM(pid);
4258}
4259#else
4260#define rb_proc__fork rb_f_notimplement
4261#define rb_f_fork rb_f_notimplement
4262#endif
4263
4264static int
4265exit_status_code(VALUE status)
4266{
4267 int istatus;
4268
4269 switch (status) {
4270 case Qtrue:
4271 istatus = EXIT_SUCCESS;
4272 break;
4273 case Qfalse:
4274 istatus = EXIT_FAILURE;
4275 break;
4276 default:
4277 istatus = NUM2INT(status);
4278#if EXIT_SUCCESS != 0
4279 if (istatus == 0)
4280 istatus = EXIT_SUCCESS;
4281#endif
4282 break;
4283 }
4284 return istatus;
4285}
4286
4287NORETURN(static VALUE rb_f_exit_bang(int argc, VALUE *argv, VALUE obj));
4288/*
4289 * call-seq:
4290 * exit!(status = false)
4291 * Process.exit!(status = false)
4292 *
4293 * Exits the process immediately; no exit handlers are called.
4294 * Returns exit status +status+ to the underlying operating system.
4295 *
4296 * Process.exit!(true)
4297 *
4298 * Values +true+ and +false+ for argument +status+
4299 * indicate, respectively, success and failure;
4300 * The meanings of integer values are system-dependent.
4301 *
4302 */
4303
4304static VALUE
4305rb_f_exit_bang(int argc, VALUE *argv, VALUE obj)
4306{
4307 int istatus;
4308
4309 if (rb_check_arity(argc, 0, 1) == 1) {
4310 istatus = exit_status_code(argv[0]);
4311 }
4312 else {
4313 istatus = EXIT_FAILURE;
4314 }
4315 _exit(istatus);
4316
4318}
4319
4320void
4321rb_exit(int status)
4322{
4323 if (GET_EC()->tag) {
4324 VALUE args[2];
4325
4326 args[0] = INT2NUM(status);
4327 args[1] = rb_str_new2("exit");
4329 }
4330 ruby_stop(status);
4331}
4332
4333VALUE
4334rb_f_exit(int argc, const VALUE *argv)
4335{
4336 int istatus;
4337
4338 if (rb_check_arity(argc, 0, 1) == 1) {
4339 istatus = exit_status_code(argv[0]);
4340 }
4341 else {
4342 istatus = EXIT_SUCCESS;
4343 }
4344 rb_exit(istatus);
4345
4347}
4348
4349NORETURN(static VALUE f_exit(int c, const VALUE *a, VALUE _));
4350/*
4351 * call-seq:
4352 * exit(status = true)
4353 * Process.exit(status = true)
4354 *
4355 * Initiates termination of the Ruby script by raising SystemExit;
4356 * the exception may be caught.
4357 * Returns exit status +status+ to the underlying operating system.
4358 *
4359 * Values +true+ and +false+ for argument +status+
4360 * indicate, respectively, success and failure;
4361 * The meanings of integer values are system-dependent.
4362 *
4363 * Example:
4364 *
4365 * begin
4366 * exit
4367 * puts 'Never get here.'
4368 * rescue SystemExit
4369 * puts 'Rescued a SystemExit exception.'
4370 * end
4371 * puts 'After begin block.'
4372 *
4373 * Output:
4374 *
4375 * Rescued a SystemExit exception.
4376 * After begin block.
4377 *
4378 * Just prior to final termination,
4379 * Ruby executes any at-exit procedures (see Kernel::at_exit)
4380 * and any object finalizers (see ObjectSpace::define_finalizer).
4381 *
4382 * Example:
4383 *
4384 * at_exit { puts 'In at_exit function.' }
4385 * ObjectSpace.define_finalizer('string', proc { puts 'In finalizer.' })
4386 * exit
4387 *
4388 * Output:
4389 *
4390 * In at_exit function.
4391 * In finalizer.
4392 *
4393 */
4394
4395static VALUE
4396f_exit(int c, const VALUE *a, VALUE _)
4397{
4398 rb_f_exit(c, a);
4400}
4401
4402VALUE
4403rb_f_abort(int argc, const VALUE *argv)
4404{
4405 rb_check_arity(argc, 0, 1);
4406 if (argc == 0) {
4407 rb_execution_context_t *ec = GET_EC();
4408 VALUE errinfo = rb_ec_get_errinfo(ec);
4409 if (!NIL_P(errinfo)) {
4410 rb_ec_error_print(ec, errinfo);
4411 }
4412 rb_exit(EXIT_FAILURE);
4413 }
4414 else {
4415 VALUE args[2];
4416
4417 args[1] = args[0] = argv[0];
4418 StringValue(args[0]);
4419 rb_io_puts(1, args, rb_ractor_stderr());
4420 args[0] = INT2NUM(EXIT_FAILURE);
4422 }
4423
4425}
4426
4427NORETURN(static VALUE f_abort(int c, const VALUE *a, VALUE _));
4428
4429/*
4430 * call-seq:
4431 * abort
4432 * Process.abort(msg = nil)
4433 *
4434 * Terminates execution immediately, effectively by calling
4435 * <tt>Kernel.exit(false)</tt>.
4436 *
4437 * If string argument +msg+ is given,
4438 * it is written to STDERR prior to termination;
4439 * otherwise, if an exception was raised,
4440 * prints its message and backtrace.
4441 */
4442
4443static VALUE
4444f_abort(int c, const VALUE *a, VALUE _)
4445{
4446 rb_f_abort(c, a);
4448}
4449
4450void
4451rb_syswait(rb_pid_t pid)
4452{
4453 int status;
4454
4455 rb_waitpid(pid, &status, 0);
4456}
4457
4458#if !defined HAVE_WORKING_FORK && !defined HAVE_SPAWNV && !defined __EMSCRIPTEN__
4459const char *
4460rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog)
4461{
4462 VALUE cmd = *prog;
4463 if (eargp && !eargp->use_shell) {
4464 VALUE str = eargp->invoke.cmd.argv_str;
4465 VALUE buf = eargp->invoke.cmd.argv_buf;
4466 char *p, **argv = ARGVSTR2ARGV(str);
4467 long i, argc = ARGVSTR2ARGC(str);
4468 const char *start = RSTRING_PTR(buf);
4469 cmd = rb_str_new(start, RSTRING_LEN(buf));
4470 p = RSTRING_PTR(cmd);
4471 for (i = 1; i < argc; ++i) {
4472 p[argv[i] - start - 1] = ' ';
4473 }
4474 *prog = cmd;
4475 return p;
4476 }
4477 return RSTRING_PTR(*prog);
4478}
4479#endif
4480
4481static rb_pid_t
4482rb_spawn_process(struct rb_execarg *eargp, char *errmsg, size_t errmsg_buflen)
4483{
4484 rb_pid_t pid;
4485#if !defined HAVE_WORKING_FORK || USE_SPAWNV
4486 VALUE prog;
4487 struct rb_execarg sarg;
4488# if !defined HAVE_SPAWNV
4489 int status;
4490# endif
4491#endif
4492
4493#if defined HAVE_WORKING_FORK && !USE_SPAWNV
4494 pid = fork_check_err(eargp->status, rb_exec_atfork, eargp, eargp->redirect_fds, errmsg, errmsg_buflen, eargp);
4495#else
4496 prog = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
4497
4498 if (rb_execarg_run_options(eargp, &sarg, errmsg, errmsg_buflen) < 0) {
4499 execarg_restore(&sarg);
4500 return -1;
4501 }
4502
4503 if (prog && !eargp->use_shell) {
4504 char **argv = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
4505 argv[0] = RSTRING_PTR(prog);
4506 }
4507# if defined HAVE_SPAWNV
4508 if (eargp->use_shell) {
4509 pid = proc_spawn_sh(RSTRING_PTR(prog));
4510 }
4511 else {
4512 char **argv = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
4513 pid = proc_spawn_cmd(argv, prog, eargp);
4514 }
4515
4516 if (pid == -1) {
4517 rb_last_status_set(0x7f << 8, pid);
4518 }
4519# else
4520 status = system(rb_execarg_commandline(eargp, &prog));
4521 pid = 1; /* dummy */
4522 rb_last_status_set((status & 0xff) << 8, pid);
4523# endif
4524
4525 if (eargp->waitpid_state) {
4526 eargp->waitpid_state->pid = pid;
4527 }
4528
4529 execarg_restore(&sarg);
4530#endif
4531
4532 return pid;
4533}
4534
4536 VALUE execarg;
4537 struct {
4538 char *ptr;
4539 size_t buflen;
4540 } errmsg;
4541};
4542
4543static VALUE
4544do_spawn_process(VALUE arg)
4545{
4546 struct spawn_args *argp = (struct spawn_args *)arg;
4547
4548 rb_execarg_parent_start1(argp->execarg);
4549
4550 return (VALUE)rb_spawn_process(rb_execarg_get(argp->execarg),
4551 argp->errmsg.ptr, argp->errmsg.buflen);
4552}
4553
4554NOINLINE(static rb_pid_t
4555 rb_execarg_spawn(VALUE execarg_obj, char *errmsg, size_t errmsg_buflen));
4556
4557static rb_pid_t
4558rb_execarg_spawn(VALUE execarg_obj, char *errmsg, size_t errmsg_buflen)
4559{
4560 struct spawn_args args;
4561
4562 args.execarg = execarg_obj;
4563 args.errmsg.ptr = errmsg;
4564 args.errmsg.buflen = errmsg_buflen;
4565
4566 rb_pid_t r = (rb_pid_t)rb_ensure(do_spawn_process, (VALUE)&args,
4567 execarg_parent_end, execarg_obj);
4568 return r;
4569}
4570
4571static rb_pid_t
4572rb_spawn_internal(int argc, const VALUE *argv, char *errmsg, size_t errmsg_buflen)
4573{
4574 VALUE execarg_obj;
4575
4576 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
4577 return rb_execarg_spawn(execarg_obj, errmsg, errmsg_buflen);
4578}
4579
4580rb_pid_t
4581rb_spawn_err(int argc, const VALUE *argv, char *errmsg, size_t errmsg_buflen)
4582{
4583 return rb_spawn_internal(argc, argv, errmsg, errmsg_buflen);
4584}
4585
4586rb_pid_t
4587rb_spawn(int argc, const VALUE *argv)
4588{
4589 return rb_spawn_internal(argc, argv, NULL, 0);
4590}
4591
4592/*
4593 * call-seq:
4594 * system([env, ] command_line, options = {}, exception: false) -> true, false, or nil
4595 * system([env, ] exe_path, *args, options = {}, exception: false) -> true, false, or nil
4596 *
4597 * Creates a new child process by doing one of the following
4598 * in that process:
4599 *
4600 * - Passing string +command_line+ to the shell.
4601 * - Invoking the executable at +exe_path+.
4602 *
4603 * This method has potential security vulnerabilities if called with untrusted input;
4604 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
4605 *
4606 * Returns:
4607 *
4608 * - +true+ if the command exits with status zero.
4609 * - +false+ if the exit status is a non-zero integer.
4610 * - +nil+ if the command could not execute.
4611 *
4612 * Raises an exception (instead of returning +false+ or +nil+)
4613 * if keyword argument +exception+ is set to +true+.
4614 *
4615 * Assigns the command's error status to <tt>$?</tt>.
4616 *
4617 * The new process is created using the
4618 * {system system call}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/functions/system.html];
4619 * it may inherit some of its environment from the calling program
4620 * (possibly including open file descriptors).
4621 *
4622 * Argument +env+, if given, is a hash that affects +ENV+ for the new process;
4623 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
4624 *
4625 * Argument +options+ is a hash of options for the new process;
4626 * see {Execution Options}[rdoc-ref:Process@Execution+Options].
4627 *
4628 * The first required argument is one of the following:
4629 *
4630 * - +command_line+ if it is a string,
4631 * and if it begins with a shell reserved word or special built-in,
4632 * or if it contains one or more meta characters.
4633 * - +exe_path+ otherwise.
4634 *
4635 * <b>Argument +command_line+</b>
4636 *
4637 * \String argument +command_line+ is a command line to be passed to a shell;
4638 * it must begin with a shell reserved word, begin with a special built-in,
4639 * or contain meta characters:
4640 *
4641 * system('if true; then echo "Foo"; fi') # => true # Shell reserved word.
4642 * system('exit') # => true # Built-in.
4643 * system('date > /tmp/date.tmp') # => true # Contains meta character.
4644 * system('date > /nop/date.tmp') # => false
4645 * system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
4646 *
4647 * Assigns the command's error status to <tt>$?</tt>:
4648 *
4649 * system('exit') # => true # Built-in.
4650 * $? # => #<Process::Status: pid 640610 exit 0>
4651 * system('date > /nop/date.tmp') # => false
4652 * $? # => #<Process::Status: pid 640742 exit 2>
4653 *
4654 * The command line may also contain arguments and options for the command:
4655 *
4656 * system('echo "Foo"') # => true
4657 *
4658 * Output:
4659 *
4660 * Foo
4661 *
4662 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
4663 *
4664 * <b>Argument +exe_path+</b>
4665 *
4666 * Argument +exe_path+ is one of the following:
4667 *
4668 * - The string path to an executable to be called.
4669 * - A 2-element array containing the path to an executable
4670 * and the string to be used as the name of the executing process.
4671 *
4672 * Example:
4673 *
4674 * system('/usr/bin/date') # => true # Path to date on Unix-style system.
4675 * system('foo') # => nil # Command failed.
4676 *
4677 * Output:
4678 *
4679 * Mon Aug 28 11:43:10 AM CDT 2023
4680 *
4681 * Assigns the command's error status to <tt>$?</tt>:
4682 *
4683 * system('/usr/bin/date') # => true
4684 * $? # => #<Process::Status: pid 645605 exit 0>
4685 * system('foo') # => nil
4686 * $? # => #<Process::Status: pid 645608 exit 127>
4687 *
4688 * Ruby invokes the executable directly.
4689 * This form does not use the shell;
4690 * see {Arguments args}[rdoc-ref:Process@Arguments+args] for caveats.
4691 *
4692 * system('doesnt_exist') # => nil
4693 *
4694 * If one or more +args+ is given, each is an argument or option
4695 * to be passed to the executable:
4696 *
4697 * system('echo', 'C*') # => true
4698 * system('echo', 'hello', 'world') # => true
4699 *
4700 * Output:
4701 *
4702 * C*
4703 * hello world
4704 *
4705 */
4706
4707static VALUE
4708rb_f_system(int argc, VALUE *argv, VALUE _)
4709{
4710 rb_thread_t *th = GET_THREAD();
4711 VALUE execarg_obj = rb_execarg_new(argc, argv, TRUE, TRUE);
4712 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
4713
4714 struct rb_process_status status = {0};
4715 eargp->status = &status;
4716
4717 last_status_clear(th);
4718
4719 // This function can set the thread's last status.
4720 // May be different from waitpid_state.pid on exec failure.
4721 rb_pid_t pid = rb_execarg_spawn(execarg_obj, 0, 0);
4722
4723 if (pid > 0) {
4724 VALUE status = rb_process_status_wait(pid, 0);
4725 struct rb_process_status *data = rb_check_typeddata(status, &rb_process_status_type);
4726 // Set the last status:
4727 rb_obj_freeze(status);
4728 th->last_status = status;
4729
4730 if (data->status == EXIT_SUCCESS) {
4731 return Qtrue;
4732 }
4733
4734 if (data->error != 0) {
4735 if (eargp->exception) {
4736 VALUE command = eargp->invoke.sh.shell_script;
4737 RB_GC_GUARD(execarg_obj);
4738 rb_syserr_fail_str(data->error, command);
4739 }
4740 else {
4741 return Qnil;
4742 }
4743 }
4744 else if (eargp->exception) {
4745 VALUE command = eargp->invoke.sh.shell_script;
4746 VALUE str = rb_str_new_cstr("Command failed with");
4747 rb_str_cat_cstr(pst_message_status(str, data->status), ": ");
4748 rb_str_append(str, command);
4749 RB_GC_GUARD(execarg_obj);
4751 }
4752 else {
4753 return Qfalse;
4754 }
4755
4756 RB_GC_GUARD(status);
4757 }
4758
4759 if (eargp->exception) {
4760 VALUE command = eargp->invoke.sh.shell_script;
4761 RB_GC_GUARD(execarg_obj);
4762 rb_syserr_fail_str(errno, command);
4763 }
4764 else {
4765 return Qnil;
4766 }
4767}
4768
4769/*
4770 * call-seq:
4771 * spawn([env, ] command_line, options = {}) -> pid
4772 * spawn([env, ] exe_path, *args, options = {}) -> pid
4773 *
4774 * Creates a new child process by doing one of the following
4775 * in that process:
4776 *
4777 * - Passing string +command_line+ to the shell.
4778 * - Invoking the executable at +exe_path+.
4779 *
4780 * This method has potential security vulnerabilities if called with untrusted input;
4781 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
4782 *
4783 * Returns the process ID (pid) of the new process,
4784 * without waiting for it to complete.
4785 *
4786 * To avoid zombie processes, the parent process should call either:
4787 *
4788 * - Process.wait, to collect the termination statuses of its children.
4789 * - Process.detach, to register disinterest in their status.
4790 *
4791 * The new process is created using the
4792 * {exec system call}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/functions/execve.html];
4793 * it may inherit some of its environment from the calling program
4794 * (possibly including open file descriptors).
4795 *
4796 * Argument +env+, if given, is a hash that affects +ENV+ for the new process;
4797 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
4798 *
4799 * Argument +options+ is a hash of options for the new process;
4800 * see {Execution Options}[rdoc-ref:Process@Execution+Options].
4801 *
4802 * The first required argument is one of the following:
4803 *
4804 * - +command_line+ if it is a string,
4805 * and if it begins with a shell reserved word or special built-in,
4806 * or if it contains one or more meta characters.
4807 * - +exe_path+ otherwise.
4808 *
4809 * <b>Argument +command_line+</b>
4810 *
4811 * \String argument +command_line+ is a command line to be passed to a shell;
4812 * it must begin with a shell reserved word, begin with a special built-in,
4813 * or contain meta characters:
4814 *
4815 * spawn('if true; then echo "Foo"; fi') # => 798847 # Shell reserved word.
4816 * Process.wait # => 798847
4817 * spawn('exit') # => 798848 # Built-in.
4818 * Process.wait # => 798848
4819 * spawn('date > /tmp/date.tmp') # => 798879 # Contains meta character.
4820 * Process.wait # => 798849
4821 * spawn('date > /nop/date.tmp') # => 798882 # Issues error message.
4822 * Process.wait # => 798882
4823 *
4824 * The command line may also contain arguments and options for the command:
4825 *
4826 * spawn('echo "Foo"') # => 799031
4827 * Process.wait # => 799031
4828 *
4829 * Output:
4830 *
4831 * Foo
4832 *
4833 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
4834 *
4835 * Raises an exception if the new process could not execute.
4836 *
4837 * <b>Argument +exe_path+</b>
4838 *
4839 * Argument +exe_path+ is one of the following:
4840 *
4841 * - The string path to an executable to be called.
4842 * - A 2-element array containing the path to an executable to be called,
4843 * and the string to be used as the name of the executing process.
4844 *
4845 * spawn('/usr/bin/date') # Path to date on Unix-style system.
4846 * Process.wait
4847 *
4848 * Output:
4849 *
4850 * Mon Aug 28 11:43:10 AM CDT 2023
4851 *
4852 * Ruby invokes the executable directly.
4853 * This form does not use the shell;
4854 * see {Arguments args}[rdoc-ref:Process@Arguments+args] for caveats.
4855 *
4856 * If one or more +args+ is given, each is an argument or option
4857 * to be passed to the executable:
4858 *
4859 * spawn('echo', 'C*') # => 799392
4860 * Process.wait # => 799392
4861 * spawn('echo', 'hello', 'world') # => 799393
4862 * Process.wait # => 799393
4863 *
4864 * Output:
4865 *
4866 * C*
4867 * hello world
4868 *
4869 * Raises an exception if the new process could not execute.
4870 */
4871
4872static VALUE
4873rb_f_spawn(int argc, VALUE *argv, VALUE _)
4874{
4875 rb_pid_t pid;
4876 char errmsg[CHILD_ERRMSG_BUFLEN] = { '\0' };
4877 VALUE execarg_obj, fail_str;
4878 struct rb_execarg *eargp;
4879
4880 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
4881 eargp = rb_execarg_get(execarg_obj);
4882 fail_str = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
4883
4884 pid = rb_execarg_spawn(execarg_obj, errmsg, sizeof(errmsg));
4885
4886 if (pid == -1) {
4887 int err = errno;
4888 rb_exec_fail(eargp, err, errmsg);
4889 RB_GC_GUARD(execarg_obj);
4890 rb_syserr_fail_str(err, fail_str);
4891 }
4892#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
4893 return PIDT2NUM(pid);
4894#else
4895 return Qnil;
4896#endif
4897}
4898
4899/*
4900 * call-seq:
4901 * sleep(secs = nil) -> slept_secs
4902 *
4903 * Suspends execution of the current thread for the number of seconds
4904 * specified by numeric argument +secs+, or forever if +secs+ is +nil+;
4905 * returns the integer number of seconds suspended (rounded).
4906 *
4907 * Time.new # => 2008-03-08 19:56:19 +0900
4908 * sleep 1.2 # => 1
4909 * Time.new # => 2008-03-08 19:56:20 +0900
4910 * sleep 1.9 # => 2
4911 * Time.new # => 2008-03-08 19:56:22 +0900
4912 *
4913 */
4914
4915static VALUE
4916rb_f_sleep(int argc, VALUE *argv, VALUE _)
4917{
4918 time_t beg = time(0);
4919 VALUE scheduler = rb_fiber_scheduler_current();
4920
4921 if (scheduler != Qnil) {
4922 rb_fiber_scheduler_kernel_sleepv(scheduler, argc, argv);
4923 }
4924 else {
4925 if (argc == 0 || (argc == 1 && NIL_P(argv[0]))) {
4927 }
4928 else {
4929 rb_check_arity(argc, 0, 1);
4931 }
4932 }
4933
4934 time_t end = time(0) - beg;
4935
4936 return TIMET2NUM(end);
4937}
4938
4939
4940#if (defined(HAVE_GETPGRP) && defined(GETPGRP_VOID)) || defined(HAVE_GETPGID)
4941/*
4942 * call-seq:
4943 * Process.getpgrp -> integer
4944 *
4945 * Returns the process group ID for the current process:
4946 *
4947 * Process.getpgid(0) # => 25527
4948 * Process.getpgrp # => 25527
4949 *
4950 */
4951
4952static VALUE
4953proc_getpgrp(VALUE _)
4954{
4955 rb_pid_t pgrp;
4956
4957#if defined(HAVE_GETPGRP) && defined(GETPGRP_VOID)
4958 pgrp = getpgrp();
4959 if (pgrp < 0) rb_sys_fail(0);
4960 return PIDT2NUM(pgrp);
4961#else /* defined(HAVE_GETPGID) */
4962 pgrp = getpgid(0);
4963 if (pgrp < 0) rb_sys_fail(0);
4964 return PIDT2NUM(pgrp);
4965#endif
4966}
4967#else
4968#define proc_getpgrp rb_f_notimplement
4969#endif
4970
4971
4972#if defined(HAVE_SETPGID) || (defined(HAVE_SETPGRP) && defined(SETPGRP_VOID))
4973/*
4974 * call-seq:
4975 * Process.setpgrp -> 0
4976 *
4977 * Equivalent to <tt>setpgid(0, 0)</tt>.
4978 *
4979 * Not available on all platforms.
4980 */
4981
4982static VALUE
4983proc_setpgrp(VALUE _)
4984{
4985 /* check for posix setpgid() first; this matches the posix */
4986 /* getpgrp() above. It appears that configure will set SETPGRP_VOID */
4987 /* even though setpgrp(0,0) would be preferred. The posix call avoids */
4988 /* this confusion. */
4989#ifdef HAVE_SETPGID
4990 if (setpgid(0,0) < 0) rb_sys_fail(0);
4991#elif defined(HAVE_SETPGRP) && defined(SETPGRP_VOID)
4992 if (setpgrp() < 0) rb_sys_fail(0);
4993#endif
4994 return INT2FIX(0);
4995}
4996#else
4997#define proc_setpgrp rb_f_notimplement
4998#endif
4999
5000
5001#if defined(HAVE_GETPGID)
5002/*
5003 * call-seq:
5004 * Process.getpgid(pid) -> integer
5005 *
5006 * Returns the process group ID for the given process ID +pid+:
5007 *
5008 * Process.getpgid(Process.ppid) # => 25527
5009 *
5010 * Not available on all platforms.
5011 */
5012
5013static VALUE
5014proc_getpgid(VALUE obj, VALUE pid)
5015{
5016 rb_pid_t i;
5017
5018 i = getpgid(NUM2PIDT(pid));
5019 if (i < 0) rb_sys_fail(0);
5020 return PIDT2NUM(i);
5021}
5022#else
5023#define proc_getpgid rb_f_notimplement
5024#endif
5025
5026
5027#ifdef HAVE_SETPGID
5028/*
5029 * call-seq:
5030 * Process.setpgid(pid, pgid) -> 0
5031 *
5032 * Sets the process group ID for the process given by process ID +pid+
5033 * to +pgid+.
5034 *
5035 * Not available on all platforms.
5036 */
5037
5038static VALUE
5039proc_setpgid(VALUE obj, VALUE pid, VALUE pgrp)
5040{
5041 rb_pid_t ipid, ipgrp;
5042
5043 ipid = NUM2PIDT(pid);
5044 ipgrp = NUM2PIDT(pgrp);
5045
5046 if (setpgid(ipid, ipgrp) < 0) rb_sys_fail(0);
5047 return INT2FIX(0);
5048}
5049#else
5050#define proc_setpgid rb_f_notimplement
5051#endif
5052
5053
5054#ifdef HAVE_GETSID
5055/*
5056 * call-seq:
5057 * Process.getsid(pid = nil) -> integer
5058 *
5059 * Returns the session ID of the given process ID +pid+,
5060 * or of the current process if not given:
5061 *
5062 * Process.getsid # => 27422
5063 * Process.getsid(0) # => 27422
5064 * Process.getsid(Process.pid()) # => 27422
5065 *
5066 * Not available on all platforms.
5067 */
5068static VALUE
5069proc_getsid(int argc, VALUE *argv, VALUE _)
5070{
5071 rb_pid_t sid;
5072 rb_pid_t pid = 0;
5073
5074 if (rb_check_arity(argc, 0, 1) == 1 && !NIL_P(argv[0]))
5075 pid = NUM2PIDT(argv[0]);
5076
5077 sid = getsid(pid);
5078 if (sid < 0) rb_sys_fail(0);
5079 return PIDT2NUM(sid);
5080}
5081#else
5082#define proc_getsid rb_f_notimplement
5083#endif
5084
5085
5086#if defined(HAVE_SETSID) || (defined(HAVE_SETPGRP) && defined(TIOCNOTTY))
5087#if !defined(HAVE_SETSID)
5088static rb_pid_t ruby_setsid(void);
5089#define setsid() ruby_setsid()
5090#endif
5091/*
5092 * call-seq:
5093 * Process.setsid -> integer
5094 *
5095 * Establishes the current process as a new session and process group leader,
5096 * with no controlling tty;
5097 * returns the session ID:
5098 *
5099 * Process.setsid # => 27422
5100 *
5101 * Not available on all platforms.
5102 */
5103
5104static VALUE
5105proc_setsid(VALUE _)
5106{
5107 rb_pid_t pid;
5108
5109 pid = setsid();
5110 if (pid < 0) rb_sys_fail(0);
5111 return PIDT2NUM(pid);
5112}
5113
5114#if !defined(HAVE_SETSID)
5115#define HAVE_SETSID 1
5116static rb_pid_t
5117ruby_setsid(void)
5118{
5119 rb_pid_t pid;
5120 int ret, fd;
5121
5122 pid = getpid();
5123#if defined(SETPGRP_VOID)
5124 ret = setpgrp();
5125 /* If `pid_t setpgrp(void)' is equivalent to setsid(),
5126 `ret' will be the same value as `pid', and following open() will fail.
5127 In Linux, `int setpgrp(void)' is equivalent to setpgid(0, 0). */
5128#else
5129 ret = setpgrp(0, pid);
5130#endif
5131 if (ret == -1) return -1;
5132
5133 if ((fd = rb_cloexec_open("/dev/tty", O_RDWR, 0)) >= 0) {
5134 rb_update_max_fd(fd);
5135 ioctl(fd, TIOCNOTTY, NULL);
5136 close(fd);
5137 }
5138 return pid;
5139}
5140#endif
5141#else
5142#define proc_setsid rb_f_notimplement
5143#endif
5144
5145
5146#ifdef HAVE_GETPRIORITY
5147/*
5148 * call-seq:
5149 * Process.getpriority(kind, id) -> integer
5150 *
5151 * Returns the scheduling priority for specified process, process group,
5152 * or user.
5153 *
5154 * Argument +kind+ is one of:
5155 *
5156 * - Process::PRIO_PROCESS: return priority for process.
5157 * - Process::PRIO_PGRP: return priority for process group.
5158 * - Process::PRIO_USER: return priority for user.
5159 *
5160 * Argument +id+ is the ID for the process, process group, or user;
5161 * zero specified the current ID for +kind+.
5162 *
5163 * Examples:
5164 *
5165 * Process.getpriority(Process::PRIO_USER, 0) # => 19
5166 * Process.getpriority(Process::PRIO_PROCESS, 0) # => 19
5167 *
5168 * Not available on all platforms.
5169 */
5170
5171static VALUE
5172proc_getpriority(VALUE obj, VALUE which, VALUE who)
5173{
5174 int prio, iwhich, iwho;
5175
5176 iwhich = NUM2INT(which);
5177 iwho = NUM2INT(who);
5178
5179 errno = 0;
5180 prio = getpriority(iwhich, iwho);
5181 if (errno) rb_sys_fail(0);
5182 return INT2FIX(prio);
5183}
5184#else
5185#define proc_getpriority rb_f_notimplement
5186#endif
5187
5188
5189#ifdef HAVE_GETPRIORITY
5190/*
5191 * call-seq:
5192 * Process.setpriority(kind, integer, priority) -> 0
5193 *
5194 * See Process.getpriority.
5195 *
5196 * Examples:
5197 *
5198 * Process.setpriority(Process::PRIO_USER, 0, 19) # => 0
5199 * Process.setpriority(Process::PRIO_PROCESS, 0, 19) # => 0
5200 * Process.getpriority(Process::PRIO_USER, 0) # => 19
5201 * Process.getpriority(Process::PRIO_PROCESS, 0) # => 19
5202 *
5203 * Not available on all platforms.
5204 */
5205
5206static VALUE
5207proc_setpriority(VALUE obj, VALUE which, VALUE who, VALUE prio)
5208{
5209 int iwhich, iwho, iprio;
5210
5211 iwhich = NUM2INT(which);
5212 iwho = NUM2INT(who);
5213 iprio = NUM2INT(prio);
5214
5215 if (setpriority(iwhich, iwho, iprio) < 0)
5216 rb_sys_fail(0);
5217 return INT2FIX(0);
5218}
5219#else
5220#define proc_setpriority rb_f_notimplement
5221#endif
5222
5223#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
5224static int
5225rlimit_resource_name2int(const char *name, rb_len_t len, int casetype)
5226{
5227 int resource;
5228 const char *p;
5229#define RESCHECK(r) \
5230 do { \
5231 if (len == rb_strlen_lit(#r) && STRCASECMP(name, #r) == 0) { \
5232 resource = RLIMIT_##r; \
5233 goto found; \
5234 } \
5235 } while (0)
5236
5237 switch (TOUPPER(*name)) {
5238 case 'A':
5239#ifdef RLIMIT_AS
5240 RESCHECK(AS);
5241#endif
5242 break;
5243
5244 case 'C':
5245#ifdef RLIMIT_CORE
5246 RESCHECK(CORE);
5247#endif
5248#ifdef RLIMIT_CPU
5249 RESCHECK(CPU);
5250#endif
5251 break;
5252
5253 case 'D':
5254#ifdef RLIMIT_DATA
5255 RESCHECK(DATA);
5256#endif
5257 break;
5258
5259 case 'F':
5260#ifdef RLIMIT_FSIZE
5261 RESCHECK(FSIZE);
5262#endif
5263 break;
5264
5265 case 'M':
5266#ifdef RLIMIT_MEMLOCK
5267 RESCHECK(MEMLOCK);
5268#endif
5269#ifdef RLIMIT_MSGQUEUE
5270 RESCHECK(MSGQUEUE);
5271#endif
5272 break;
5273
5274 case 'N':
5275#ifdef RLIMIT_NOFILE
5276 RESCHECK(NOFILE);
5277#endif
5278#ifdef RLIMIT_NPROC
5279 RESCHECK(NPROC);
5280#endif
5281#ifdef RLIMIT_NPTS
5282 RESCHECK(NPTS);
5283#endif
5284#ifdef RLIMIT_NICE
5285 RESCHECK(NICE);
5286#endif
5287 break;
5288
5289 case 'R':
5290#ifdef RLIMIT_RSS
5291 RESCHECK(RSS);
5292#endif
5293#ifdef RLIMIT_RTPRIO
5294 RESCHECK(RTPRIO);
5295#endif
5296#ifdef RLIMIT_RTTIME
5297 RESCHECK(RTTIME);
5298#endif
5299 break;
5300
5301 case 'S':
5302#ifdef RLIMIT_STACK
5303 RESCHECK(STACK);
5304#endif
5305#ifdef RLIMIT_SBSIZE
5306 RESCHECK(SBSIZE);
5307#endif
5308#ifdef RLIMIT_SIGPENDING
5309 RESCHECK(SIGPENDING);
5310#endif
5311 break;
5312 }
5313 return -1;
5314
5315 found:
5316 switch (casetype) {
5317 case 0:
5318 for (p = name; *p; p++)
5319 if (!ISUPPER(*p))
5320 return -1;
5321 break;
5322
5323 case 1:
5324 for (p = name; *p; p++)
5325 if (!ISLOWER(*p))
5326 return -1;
5327 break;
5328
5329 default:
5330 rb_bug("unexpected casetype");
5331 }
5332 return resource;
5333#undef RESCHECK
5334}
5335
5336static int
5337rlimit_type_by_hname(const char *name, rb_len_t len)
5338{
5339 return rlimit_resource_name2int(name, len, 0);
5340}
5341
5342static int
5343rlimit_type_by_lname(const char *name, rb_len_t len)
5344{
5345 return rlimit_resource_name2int(name, len, 1);
5346}
5347
5348static int
5349rlimit_type_by_sym(VALUE key)
5350{
5351 VALUE name = rb_sym2str(key);
5352 const char *rname = RSTRING_PTR(name);
5353 rb_len_t len = RSTRING_LEN(name);
5354 int rtype = -1;
5355 static const char prefix[] = "rlimit_";
5356 enum {prefix_len = sizeof(prefix)-1};
5357
5358 if (len > prefix_len && strncmp(prefix, rname, prefix_len) == 0) {
5359 rtype = rlimit_type_by_lname(rname + prefix_len, len - prefix_len);
5360 }
5361
5362 RB_GC_GUARD(key);
5363 return rtype;
5364}
5365
5366static int
5367rlimit_resource_type(VALUE rtype)
5368{
5369 const char *name;
5370 rb_len_t len;
5371 VALUE v;
5372 int r;
5373
5374 switch (TYPE(rtype)) {
5375 case T_SYMBOL:
5376 v = rb_sym2str(rtype);
5377 name = RSTRING_PTR(v);
5378 len = RSTRING_LEN(v);
5379 break;
5380
5381 default:
5382 v = rb_check_string_type(rtype);
5383 if (!NIL_P(v)) {
5384 rtype = v;
5385 case T_STRING:
5386 name = StringValueCStr(rtype);
5387 len = RSTRING_LEN(rtype);
5388 break;
5389 }
5390 /* fall through */
5391
5392 case T_FIXNUM:
5393 case T_BIGNUM:
5394 return NUM2INT(rtype);
5395 }
5396
5397 r = rlimit_type_by_hname(name, len);
5398 if (r != -1)
5399 return r;
5400
5401 rb_raise(rb_eArgError, "invalid resource name: % "PRIsVALUE, rtype);
5402
5404}
5405
5406static rlim_t
5407rlimit_resource_value(VALUE rval)
5408{
5409 const char *name;
5410 VALUE v;
5411
5412 switch (TYPE(rval)) {
5413 case T_SYMBOL:
5414 v = rb_sym2str(rval);
5415 name = RSTRING_PTR(v);
5416 break;
5417
5418 default:
5419 v = rb_check_string_type(rval);
5420 if (!NIL_P(v)) {
5421 rval = v;
5422 case T_STRING:
5423 name = StringValueCStr(rval);
5424 break;
5425 }
5426 /* fall through */
5427
5428 case T_FIXNUM:
5429 case T_BIGNUM:
5430 return NUM2RLIM(rval);
5431 }
5432
5433#ifdef RLIM_INFINITY
5434 if (strcmp(name, "INFINITY") == 0) return RLIM_INFINITY;
5435#endif
5436#ifdef RLIM_SAVED_MAX
5437 if (strcmp(name, "SAVED_MAX") == 0) return RLIM_SAVED_MAX;
5438#endif
5439#ifdef RLIM_SAVED_CUR
5440 if (strcmp(name, "SAVED_CUR") == 0) return RLIM_SAVED_CUR;
5441#endif
5442 rb_raise(rb_eArgError, "invalid resource value: %"PRIsVALUE, rval);
5443
5444 UNREACHABLE_RETURN((rlim_t)-1);
5445}
5446#endif
5447
5448#if defined(HAVE_GETRLIMIT) && defined(RLIM2NUM)
5449/*
5450 * call-seq:
5451 * Process.getrlimit(resource) -> [cur_limit, max_limit]
5452 *
5453 * Returns a 2-element array of the current (soft) limit
5454 * and maximum (hard) limit for the given +resource+.
5455 *
5456 * Argument +resource+ specifies the resource whose limits are to be returned;
5457 * see Process.setrlimit.
5458 *
5459 * Each of the returned values +cur_limit+ and +max_limit+ is an integer;
5460 * see Process.setrlimit.
5461 *
5462 * Example:
5463 *
5464 * Process.getrlimit(:CORE) # => [0, 18446744073709551615]
5465 *
5466 * See Process.setrlimit.
5467 *
5468 * Not available on all platforms.
5469 */
5470
5471static VALUE
5472proc_getrlimit(VALUE obj, VALUE resource)
5473{
5474 struct rlimit rlim;
5475
5476 if (getrlimit(rlimit_resource_type(resource), &rlim) < 0) {
5477 rb_sys_fail("getrlimit");
5478 }
5479 return rb_assoc_new(RLIM2NUM(rlim.rlim_cur), RLIM2NUM(rlim.rlim_max));
5480}
5481#else
5482#define proc_getrlimit rb_f_notimplement
5483#endif
5484
5485#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
5486/*
5487 * call-seq:
5488 * Process.setrlimit(resource, cur_limit, max_limit = cur_limit) -> nil
5489 *
5490 * Sets limits for the current process for the given +resource+
5491 * to +cur_limit+ (soft limit) and +max_limit+ (hard limit);
5492 * returns +nil+.
5493 *
5494 * Argument +resource+ specifies the resource whose limits are to be set;
5495 * the argument may be given as a symbol, as a string, or as a constant
5496 * beginning with <tt>Process::RLIMIT_</tt>
5497 * (e.g., +:CORE+, <tt>'CORE'</tt>, or <tt>Process::RLIMIT_CORE</tt>.
5498 *
5499 * The resources available and supported are system-dependent,
5500 * and may include (here expressed as symbols):
5501 *
5502 * - +:AS+: Total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD except 4.4BSD-Lite).
5503 * - +:CORE+: Core size (bytes) (SUSv3).
5504 * - +:CPU+: CPU time (seconds) (SUSv3).
5505 * - +:DATA+: Data segment (bytes) (SUSv3).
5506 * - +:FSIZE+: File size (bytes) (SUSv3).
5507 * - +:MEMLOCK+: Total size for mlock(2) (bytes) (4.4BSD, GNU/Linux).
5508 * - +:MSGQUEUE+: Allocation for POSIX message queues (bytes) (GNU/Linux).
5509 * - +:NICE+: Ceiling on process's nice(2) value (number) (GNU/Linux).
5510 * - +:NOFILE+: File descriptors (number) (SUSv3).
5511 * - +:NPROC+: Number of processes for the user (number) (4.4BSD, GNU/Linux).
5512 * - +:NPTS+: Number of pseudo terminals (number) (FreeBSD).
5513 * - +:RSS+: Resident memory size (bytes) (4.2BSD, GNU/Linux).
5514 * - +:RTPRIO+: Ceiling on the process's real-time priority (number) (GNU/Linux).
5515 * - +:RTTIME+: CPU time for real-time process (us) (GNU/Linux).
5516 * - +:SBSIZE+: All socket buffers (bytes) (NetBSD, FreeBSD).
5517 * - +:SIGPENDING+: Number of queued signals allowed (signals) (GNU/Linux).
5518 * - +:STACK+: Stack size (bytes) (SUSv3).
5519 *
5520 * Arguments +cur_limit+ and +max_limit+ may be:
5521 *
5522 * - Integers (+max_limit+ should not be smaller than +cur_limit+).
5523 * - Symbol +:SAVED_MAX+, string <tt>'SAVED_MAX'</tt>,
5524 * or constant <tt>Process::RLIM_SAVED_MAX</tt>: saved maximum limit.
5525 * - Symbol +:SAVED_CUR+, string <tt>'SAVED_CUR'</tt>,
5526 * or constant <tt>Process::RLIM_SAVED_CUR</tt>: saved current limit.
5527 * - Symbol +:INFINITY+, string <tt>'INFINITY'</tt>,
5528 * or constant <tt>Process::RLIM_INFINITY</tt>: no limit on resource.
5529 *
5530 * This example raises the soft limit of core size to
5531 * the hard limit to try to make core dump possible:
5532 *
5533 * Process.setrlimit(:CORE, Process.getrlimit(:CORE)[1])
5534 *
5535 * Not available on all platforms.
5536 */
5537
5538static VALUE
5539proc_setrlimit(int argc, VALUE *argv, VALUE obj)
5540{
5541 VALUE resource, rlim_cur, rlim_max;
5542 struct rlimit rlim;
5543
5544 rb_check_arity(argc, 2, 3);
5545 resource = argv[0];
5546 rlim_cur = argv[1];
5547 if (argc < 3 || NIL_P(rlim_max = argv[2]))
5548 rlim_max = rlim_cur;
5549
5550 rlim.rlim_cur = rlimit_resource_value(rlim_cur);
5551 rlim.rlim_max = rlimit_resource_value(rlim_max);
5552
5553 if (setrlimit(rlimit_resource_type(resource), &rlim) < 0) {
5554 rb_sys_fail("setrlimit");
5555 }
5556 return Qnil;
5557}
5558#else
5559#define proc_setrlimit rb_f_notimplement
5560#endif
5561
5562static int under_uid_switch = 0;
5563static void
5564check_uid_switch(void)
5565{
5566 if (under_uid_switch) {
5567 rb_raise(rb_eRuntimeError, "can't handle UID while evaluating block given to Process::UID.switch method");
5568 }
5569}
5570
5571static int under_gid_switch = 0;
5572static void
5573check_gid_switch(void)
5574{
5575 if (under_gid_switch) {
5576 rb_raise(rb_eRuntimeError, "can't handle GID while evaluating block given to Process::UID.switch method");
5577 }
5578}
5579
5580
5581#if defined(HAVE_PWD_H)
5582static inline bool
5583login_not_found(int err)
5584{
5585 return (err == ENOTTY || err == ENXIO || err == ENOENT);
5586}
5587
5593VALUE
5594rb_getlogin(void)
5595{
5596# if !defined(USE_GETLOGIN_R) && !defined(USE_GETLOGIN)
5597 return Qnil;
5598# else
5599 char MAYBE_UNUSED(*login) = NULL;
5600
5601# ifdef USE_GETLOGIN_R
5602
5603# if defined(__FreeBSD__)
5604 typedef int getlogin_r_size_t;
5605# else
5606 typedef size_t getlogin_r_size_t;
5607# endif
5608
5609 rb_len_t loginsize = GETLOGIN_R_SIZE_INIT; /* maybe -1 */
5610
5611 if (loginsize < 0)
5612 loginsize = GETLOGIN_R_SIZE_DEFAULT;
5613
5614 VALUE maybe_result = rb_str_buf_new(loginsize);
5615
5616 login = RSTRING_PTR(maybe_result);
5617 loginsize = rb_str_capacity(maybe_result);
5618 rb_str_set_len(maybe_result, loginsize);
5619
5620 int gle;
5621 while ((gle = getlogin_r(login, (getlogin_r_size_t)loginsize)) != 0) {
5622 if (login_not_found(gle)) {
5623 rb_str_resize(maybe_result, 0);
5624 return Qnil;
5625 }
5626
5627 if (gle != ERANGE || loginsize >= GETLOGIN_R_SIZE_LIMIT) {
5628 rb_str_resize(maybe_result, 0);
5629 rb_syserr_fail(gle, "getlogin_r");
5630 }
5631
5632 rb_str_modify_expand(maybe_result, loginsize);
5633 login = RSTRING_PTR(maybe_result);
5634 loginsize = rb_str_capacity(maybe_result);
5635 }
5636
5637 if (login == NULL) {
5638 rb_str_resize(maybe_result, 0);
5639 return Qnil;
5640 }
5641
5642 rb_str_set_len(maybe_result, strlen(login));
5643 return maybe_result;
5644
5645# elif defined(USE_GETLOGIN)
5646
5647 errno = 0;
5648 login = getlogin();
5649 int err = errno;
5650 if (err) {
5651 if (login_not_found(err)) {
5652 return Qnil;
5653 }
5654 rb_syserr_fail(err, "getlogin");
5655 }
5656
5657 return login ? rb_str_new_cstr(login) : Qnil;
5658# endif
5659
5660#endif
5661}
5662
5663/* avoid treating as errors errno values that indicate "not found" */
5664static inline bool
5665pwd_not_found(int err)
5666{
5667 switch (err) {
5668 case 0:
5669 case ENOENT:
5670 case ESRCH:
5671 case EBADF:
5672 case EPERM:
5673 return true;
5674 default:
5675 return false;
5676 }
5677}
5678
5679# if defined(USE_GETPWNAM_R)
5680struct getpwnam_r_args {
5681 const char *login;
5682 char *buf;
5683 size_t bufsize;
5684 struct passwd *result;
5685 struct passwd pwstore;
5686};
5687
5688# define GETPWNAM_R_ARGS(login_, buf_, bufsize_) (struct getpwnam_r_args) \
5689 {.login = login_, .buf = buf_, .bufsize = bufsize_, .result = NULL}
5690
5691static void *
5692nogvl_getpwnam_r(void *args)
5693{
5694 struct getpwnam_r_args *arg = args;
5695 return (void *)(VALUE)getpwnam_r(arg->login, &arg->pwstore, arg->buf, arg->bufsize, &arg->result);
5696}
5697# endif
5698
5699VALUE
5700rb_getpwdirnam_for_login(VALUE login_name)
5701{
5702#if !defined(USE_GETPWNAM_R) && !defined(USE_GETPWNAM)
5703 return Qnil;
5704#else
5705
5706 if (NIL_P(login_name)) {
5707 /* nothing to do; no name with which to query the password database */
5708 return Qnil;
5709 }
5710
5711 const char *login = RSTRING_PTR(login_name);
5712
5713
5714# ifdef USE_GETPWNAM_R
5715
5716 char *bufnm;
5717 rb_len_t bufsizenm = GETPW_R_SIZE_INIT; /* maybe -1 */
5718
5719 if (bufsizenm < 0)
5720 bufsizenm = GETPW_R_SIZE_DEFAULT;
5721
5722 VALUE getpwnm_tmp = rb_str_tmp_new(bufsizenm);
5723
5724 bufnm = RSTRING_PTR(getpwnm_tmp);
5725 bufsizenm = rb_str_capacity(getpwnm_tmp);
5726 rb_str_set_len(getpwnm_tmp, bufsizenm);
5727 struct getpwnam_r_args args = GETPWNAM_R_ARGS(login, bufnm, (size_t)bufsizenm);
5728
5729 int enm;
5730 while ((enm = IO_WITHOUT_GVL_INT(nogvl_getpwnam_r, &args)) != 0) {
5731 if (pwd_not_found(enm)) {
5732 rb_str_resize(getpwnm_tmp, 0);
5733 return Qnil;
5734 }
5735
5736 if (enm != ERANGE || args.bufsize >= GETPW_R_SIZE_LIMIT) {
5737 rb_str_resize(getpwnm_tmp, 0);
5738 rb_syserr_fail(enm, "getpwnam_r");
5739 }
5740
5741 rb_str_modify_expand(getpwnm_tmp, (rb_len_t)args.bufsize);
5742 args.buf = RSTRING_PTR(getpwnm_tmp);
5743 args.bufsize = (size_t)rb_str_capacity(getpwnm_tmp);
5744 }
5745
5746 if (args.result == NULL) {
5747 /* no record in the password database for the login name */
5748 rb_str_resize(getpwnm_tmp, 0);
5749 return Qnil;
5750 }
5751
5752 /* found it */
5753 VALUE result = rb_str_new_cstr(args.result->pw_dir);
5754 rb_str_resize(getpwnm_tmp, 0);
5755 return result;
5756
5757# elif defined(USE_GETPWNAM)
5758
5759 struct passwd *pwptr;
5760 errno = 0;
5761 if (!(pwptr = getpwnam(login))) {
5762 int err = errno;
5763
5764 if (pwd_not_found(err)) {
5765 return Qnil;
5766 }
5767
5768 rb_syserr_fail(err, "getpwnam");
5769 }
5770
5771 /* found it */
5772 return rb_str_new_cstr(pwptr->pw_dir);
5773# endif
5774
5775#endif
5776}
5777
5778# if defined(USE_GETPWUID_R)
5779struct getpwuid_r_args {
5780 uid_t uid;
5781 char *buf;
5782 size_t bufsize;
5783 struct passwd *result;
5784 struct passwd pwstore;
5785};
5786
5787# define GETPWUID_R_ARGS(uid_, buf_, bufsize_) (struct getpwuid_r_args) \
5788 {.uid = uid_, .buf = buf_, .bufsize = bufsize_, .result = NULL}
5789
5790static void *
5791nogvl_getpwuid_r(void *args)
5792{
5793 struct getpwuid_r_args *arg = args;
5794 return (void *)(VALUE)getpwuid_r(arg->uid, &arg->pwstore, arg->buf, arg->bufsize, &arg->result);
5795}
5796# endif
5797
5801VALUE
5802rb_getpwdiruid(void)
5803{
5804# if !defined(USE_GETPWUID_R) && !defined(USE_GETPWUID)
5805 /* Should never happen... </famous-last-words> */
5806 return Qnil;
5807# else
5808 uid_t ruid = getuid();
5809
5810# ifdef USE_GETPWUID_R
5811
5812 char *bufid;
5813 rb_len_t bufsizeid = GETPW_R_SIZE_INIT; /* maybe -1 */
5814
5815 if (bufsizeid < 0)
5816 bufsizeid = GETPW_R_SIZE_DEFAULT;
5817
5818 VALUE getpwid_tmp = rb_str_tmp_new(bufsizeid);
5819
5820 bufid = RSTRING_PTR(getpwid_tmp);
5821 bufsizeid = rb_str_capacity(getpwid_tmp);
5822 rb_str_set_len(getpwid_tmp, bufsizeid);
5823 struct getpwuid_r_args args = GETPWUID_R_ARGS(ruid, bufid, (size_t)bufsizeid);
5824
5825 int eid;
5826 while ((eid = IO_WITHOUT_GVL_INT(nogvl_getpwuid_r, &args)) != 0) {
5827 if (pwd_not_found(eid)) {
5828 rb_str_resize(getpwid_tmp, 0);
5829 return Qnil;
5830 }
5831
5832 if (eid != ERANGE || args.bufsize >= GETPW_R_SIZE_LIMIT) {
5833 rb_str_resize(getpwid_tmp, 0);
5834 rb_syserr_fail(eid, "getpwuid_r");
5835 }
5836
5837 rb_str_modify_expand(getpwid_tmp, (rb_len_t)args.bufsize);
5838 args.buf = RSTRING_PTR(getpwid_tmp);
5839 args.bufsize = (size_t)rb_str_capacity(getpwid_tmp);
5840 }
5841
5842 if (args.result == NULL) {
5843 /* no record in the password database for the uid */
5844 rb_str_resize(getpwid_tmp, 0);
5845 return Qnil;
5846 }
5847
5848 /* found it */
5849 VALUE result = rb_str_new_cstr(args.result->pw_dir);
5850 rb_str_resize(getpwid_tmp, 0);
5851 return result;
5852
5853# elif defined(USE_GETPWUID)
5854
5855 struct passwd *pwptr;
5856 errno = 0;
5857 if (!(pwptr = getpwuid(ruid))) {
5858 int err = errno;
5859
5860 if (pwd_not_found(err)) {
5861 return Qnil;
5862 }
5863
5864 rb_syserr_fail(err, "getpwuid");
5865 }
5866
5867 /* found it */
5868 return rb_str_new_cstr(pwptr->pw_dir);
5869# endif
5870
5871#endif /* !defined(USE_GETPWUID_R) && !defined(USE_GETPWUID) */
5872}
5873#endif /* HAVE_PWD_H */
5874
5875
5876/*********************************************************************
5877 * Document-class: Process::Sys
5878 *
5879 * The Process::Sys module contains UID and GID
5880 * functions which provide direct bindings to the system calls of the
5881 * same names instead of the more-portable versions of the same
5882 * functionality found in the +Process+,
5883 * Process::UID, and Process::GID modules.
5884 */
5885
5886#if defined(HAVE_PWD_H)
5887static rb_uid_t
5888obj2uid(VALUE id
5889# ifdef USE_GETPWNAM_R
5890 , VALUE *getpw_tmp
5891# endif
5892 )
5893{
5894 rb_uid_t uid;
5895 VALUE tmp;
5896
5897 if (FIXNUM_P(id) || NIL_P(tmp = rb_check_string_type(id))) {
5898 uid = NUM2UIDT(id);
5899 }
5900 else {
5901 const char *usrname = StringValueCStr(id);
5902 struct passwd *pwptr;
5903#ifdef USE_GETPWNAM_R
5904 char *getpw_buf;
5905 rb_len_t getpw_buf_len;
5906 int e;
5907 if (!*getpw_tmp) {
5908 getpw_buf_len = GETPW_R_SIZE_INIT;
5909 if (getpw_buf_len < 0) getpw_buf_len = GETPW_R_SIZE_DEFAULT;
5910 *getpw_tmp = rb_str_tmp_new(getpw_buf_len);
5911 }
5912 getpw_buf = RSTRING_PTR(*getpw_tmp);
5913 getpw_buf_len = rb_str_capacity(*getpw_tmp);
5914 rb_str_set_len(*getpw_tmp, getpw_buf_len);
5915 errno = 0;
5916 struct getpwnam_r_args args = GETPWNAM_R_ARGS((char *)usrname, getpw_buf, (size_t)getpw_buf_len);
5917
5918 while ((e = IO_WITHOUT_GVL_INT(nogvl_getpwnam_r, &args)) != 0) {
5919 if (e != ERANGE || args.bufsize >= GETPW_R_SIZE_LIMIT) {
5920 rb_str_resize(*getpw_tmp, 0);
5921 rb_syserr_fail(e, "getpwnam_r");
5922 }
5923 rb_str_modify_expand(*getpw_tmp, (rb_len_t)args.bufsize);
5924 args.buf = RSTRING_PTR(*getpw_tmp);
5925 args.bufsize = (size_t)rb_str_capacity(*getpw_tmp);
5926 }
5927 pwptr = args.result;
5928#else
5929 pwptr = getpwnam(usrname);
5930#endif
5931 if (!pwptr) {
5932#ifndef USE_GETPWNAM_R
5933 endpwent();
5934#endif
5935 rb_raise(rb_eArgError, "can't find user for %"PRIsVALUE, id);
5936 }
5937 uid = pwptr->pw_uid;
5938#ifndef USE_GETPWNAM_R
5939 endpwent();
5940#endif
5941 }
5942 return uid;
5943}
5944
5945# ifdef p_uid_from_name
5946/*
5947 * call-seq:
5948 * Process::UID.from_name(name) -> uid
5949 *
5950 * Get the user ID by the _name_.
5951 * If the user is not found, +ArgumentError+ will be raised.
5952 *
5953 * Process::UID.from_name("root") #=> 0
5954 * Process::UID.from_name("nosuchuser") #=> can't find user for nosuchuser (ArgumentError)
5955 */
5956
5957static VALUE
5958p_uid_from_name(VALUE self, VALUE id)
5959{
5960 return UIDT2NUM(OBJ2UID(id));
5961}
5962# endif
5963#endif
5964
5965#if defined(HAVE_GRP_H)
5966# if defined(USE_GETGRNAM_R)
5967struct getgrnam_r_args {
5968 const char *name;
5969 char *buf;
5970 size_t bufsize;
5971 struct group *result;
5972 struct group grp;
5973};
5974
5975# define GETGRNAM_R_ARGS(name_, buf_, bufsize_) (struct getgrnam_r_args) \
5976 {.name = name_, .buf = buf_, .bufsize = bufsize_, .result = NULL}
5977
5978static void *
5979nogvl_getgrnam_r(void *args)
5980{
5981 struct getgrnam_r_args *arg = args;
5982 return (void *)(VALUE)getgrnam_r(arg->name, &arg->grp, arg->buf, arg->bufsize, &arg->result);
5983}
5984# endif
5985
5986static rb_gid_t
5987obj2gid(VALUE id
5988# ifdef USE_GETGRNAM_R
5989 , VALUE *getgr_tmp
5990# endif
5991 )
5992{
5993 rb_gid_t gid;
5994 VALUE tmp;
5995
5996 if (FIXNUM_P(id) || NIL_P(tmp = rb_check_string_type(id))) {
5997 gid = NUM2GIDT(id);
5998 }
5999 else {
6000 const char *grpname = StringValueCStr(id);
6001 struct group *grptr;
6002#ifdef USE_GETGRNAM_R
6003 char *getgr_buf;
6004 rb_len_t getgr_buf_len;
6005 int e;
6006 if (!*getgr_tmp) {
6007 getgr_buf_len = GETGR_R_SIZE_INIT;
6008 if (getgr_buf_len < 0) getgr_buf_len = GETGR_R_SIZE_DEFAULT;
6009 *getgr_tmp = rb_str_tmp_new(getgr_buf_len);
6010 }
6011 getgr_buf = RSTRING_PTR(*getgr_tmp);
6012 getgr_buf_len = rb_str_capacity(*getgr_tmp);
6013 rb_str_set_len(*getgr_tmp, getgr_buf_len);
6014 errno = 0;
6015 struct getgrnam_r_args args = GETGRNAM_R_ARGS(grpname, getgr_buf, (size_t)getgr_buf_len);
6016
6017 while ((e = IO_WITHOUT_GVL_INT(nogvl_getgrnam_r, &args)) != 0) {
6018 if (e != ERANGE || args.bufsize >= GETGR_R_SIZE_LIMIT) {
6019 rb_str_resize(*getgr_tmp, 0);
6020 rb_syserr_fail(e, "getgrnam_r");
6021 }
6022 rb_str_modify_expand(*getgr_tmp, (rb_len_t)args.bufsize);
6023 args.buf = RSTRING_PTR(*getgr_tmp);
6024 args.bufsize = (size_t)rb_str_capacity(*getgr_tmp);
6025 }
6026 grptr = args.result;
6027#elif defined(HAVE_GETGRNAM)
6028 grptr = getgrnam(grpname);
6029#else
6030 grptr = NULL;
6031#endif
6032 if (!grptr) {
6033#if !defined(USE_GETGRNAM_R) && defined(HAVE_ENDGRENT)
6034 endgrent();
6035#endif
6036 rb_raise(rb_eArgError, "can't find group for %"PRIsVALUE, id);
6037 }
6038 gid = grptr->gr_gid;
6039#if !defined(USE_GETGRNAM_R) && defined(HAVE_ENDGRENT)
6040 endgrent();
6041#endif
6042 }
6043 return gid;
6044}
6045
6046# ifdef p_gid_from_name
6047/*
6048 * call-seq:
6049 * Process::GID.from_name(name) -> gid
6050 *
6051 * Get the group ID by the _name_.
6052 * If the group is not found, +ArgumentError+ will be raised.
6053 *
6054 * Process::GID.from_name("wheel") #=> 0
6055 * Process::GID.from_name("nosuchgroup") #=> can't find group for nosuchgroup (ArgumentError)
6056 */
6057
6058static VALUE
6059p_gid_from_name(VALUE self, VALUE id)
6060{
6061 return GIDT2NUM(OBJ2GID(id));
6062}
6063# endif
6064#endif
6065
6066#if defined HAVE_SETUID
6067/*
6068 * call-seq:
6069 * Process::Sys.setuid(user) -> nil
6070 *
6071 * Set the user ID of the current process to _user_. Not
6072 * available on all platforms.
6073 *
6074 */
6075
6076static VALUE
6077p_sys_setuid(VALUE obj, VALUE id)
6078{
6079 check_uid_switch();
6080 if (setuid(OBJ2UID(id)) != 0) rb_sys_fail(0);
6081 return Qnil;
6082}
6083#else
6084#define p_sys_setuid rb_f_notimplement
6085#endif
6086
6087
6088#if defined HAVE_SETRUID
6089/*
6090 * call-seq:
6091 * Process::Sys.setruid(user) -> nil
6092 *
6093 * Set the real user ID of the calling process to _user_.
6094 * Not available on all platforms.
6095 *
6096 */
6097
6098static VALUE
6099p_sys_setruid(VALUE obj, VALUE id)
6100{
6101 check_uid_switch();
6102 if (setruid(OBJ2UID(id)) != 0) rb_sys_fail(0);
6103 return Qnil;
6104}
6105#else
6106#define p_sys_setruid rb_f_notimplement
6107#endif
6108
6109
6110#if defined HAVE_SETEUID
6111/*
6112 * call-seq:
6113 * Process::Sys.seteuid(user) -> nil
6114 *
6115 * Set the effective user ID of the calling process to
6116 * _user_. Not available on all platforms.
6117 *
6118 */
6119
6120static VALUE
6121p_sys_seteuid(VALUE obj, VALUE id)
6122{
6123 check_uid_switch();
6124 if (seteuid(OBJ2UID(id)) != 0) rb_sys_fail(0);
6125 return Qnil;
6126}
6127#else
6128#define p_sys_seteuid rb_f_notimplement
6129#endif
6130
6131
6132#if defined HAVE_SETREUID
6133/*
6134 * call-seq:
6135 * Process::Sys.setreuid(rid, eid) -> nil
6136 *
6137 * Sets the (user) real and/or effective user IDs of the current
6138 * process to _rid_ and _eid_, respectively. A value of
6139 * <code>-1</code> for either means to leave that ID unchanged. Not
6140 * available on all platforms.
6141 *
6142 */
6143
6144static VALUE
6145p_sys_setreuid(VALUE obj, VALUE rid, VALUE eid)
6146{
6147 rb_uid_t ruid, euid;
6148 PREPARE_GETPWNAM;
6149 check_uid_switch();
6150 ruid = OBJ2UID1(rid);
6151 euid = OBJ2UID1(eid);
6152 FINISH_GETPWNAM;
6153 if (setreuid(ruid, euid) != 0) rb_sys_fail(0);
6154 return Qnil;
6155}
6156#else
6157#define p_sys_setreuid rb_f_notimplement
6158#endif
6159
6160
6161#if defined HAVE_SETRESUID
6162/*
6163 * call-seq:
6164 * Process::Sys.setresuid(rid, eid, sid) -> nil
6165 *
6166 * Sets the (user) real, effective, and saved user IDs of the
6167 * current process to _rid_, _eid_, and _sid_ respectively. A
6168 * value of <code>-1</code> for any value means to
6169 * leave that ID unchanged. Not available on all platforms.
6170 *
6171 */
6172
6173static VALUE
6174p_sys_setresuid(VALUE obj, VALUE rid, VALUE eid, VALUE sid)
6175{
6176 rb_uid_t ruid, euid, suid;
6177 PREPARE_GETPWNAM;
6178 check_uid_switch();
6179 ruid = OBJ2UID1(rid);
6180 euid = OBJ2UID1(eid);
6181 suid = OBJ2UID1(sid);
6182 FINISH_GETPWNAM;
6183 if (setresuid(ruid, euid, suid) != 0) rb_sys_fail(0);
6184 return Qnil;
6185}
6186#else
6187#define p_sys_setresuid rb_f_notimplement
6188#endif
6189
6190
6191/*
6192 * call-seq:
6193 * Process.uid -> integer
6194 * Process::UID.rid -> integer
6195 * Process::Sys.getuid -> integer
6196 *
6197 * Returns the (real) user ID of the current process.
6198 *
6199 * Process.uid # => 1000
6200 *
6201 */
6202
6203static VALUE
6204proc_getuid(VALUE obj)
6205{
6206 rb_uid_t uid = getuid();
6207 return UIDT2NUM(uid);
6208}
6209
6210
6211#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETRUID) || defined(HAVE_SETUID)
6212/*
6213 * call-seq:
6214 * Process.uid = new_uid -> new_uid
6215 *
6216 * Sets the (user) user ID for the current process to +new_uid+:
6217 *
6218 * Process.uid = 1000 # => 1000
6219 *
6220 * Not available on all platforms.
6221 */
6222
6223static VALUE
6224proc_setuid(VALUE obj, VALUE id)
6225{
6226 rb_uid_t uid;
6227
6228 check_uid_switch();
6229
6230 uid = OBJ2UID(id);
6231#if defined(HAVE_SETRESUID)
6232 if (setresuid(uid, -1, -1) < 0) rb_sys_fail(0);
6233#elif defined HAVE_SETREUID
6234 if (setreuid(uid, -1) < 0) rb_sys_fail(0);
6235#elif defined HAVE_SETRUID
6236 if (setruid(uid) < 0) rb_sys_fail(0);
6237#elif defined HAVE_SETUID
6238 {
6239 if (geteuid() == uid) {
6240 if (setuid(uid) < 0) rb_sys_fail(0);
6241 }
6242 else {
6244 }
6245 }
6246#endif
6247 return id;
6248}
6249#else
6250#define proc_setuid rb_f_notimplement
6251#endif
6252
6253
6254/********************************************************************
6255 *
6256 * Document-class: Process::UID
6257 *
6258 * The Process::UID module contains a collection of
6259 * module functions which can be used to portably get, set, and
6260 * switch the current process's real, effective, and saved user IDs.
6261 *
6262 */
6263
6264static rb_uid_t SAVED_USER_ID = -1;
6265
6266/*
6267 * call-seq:
6268 * Process::UID.change_privilege(user) -> integer
6269 *
6270 * Change the current process's real and effective user ID to that
6271 * specified by _user_. Returns the new user ID. Not
6272 * available on all platforms.
6273 *
6274 * [Process.uid, Process.euid] #=> [0, 0]
6275 * Process::UID.change_privilege(31) #=> 31
6276 * [Process.uid, Process.euid] #=> [31, 31]
6277 */
6278
6279static VALUE
6280p_uid_change_privilege(VALUE obj, VALUE id)
6281{
6282 rb_uid_t uid;
6283
6284 check_uid_switch();
6285
6286 uid = OBJ2UID(id);
6287
6288 if (geteuid() == 0) { /* root-user */
6289#if defined(HAVE_SETRESUID)
6290 if (setresuid(uid, uid, uid) < 0) rb_sys_fail(0);
6291 SAVED_USER_ID = uid;
6292#elif defined(HAVE_SETUID)
6293 if (setuid(uid) < 0) rb_sys_fail(0);
6294 SAVED_USER_ID = uid;
6295#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
6296 if (getuid() == uid) {
6297 if (SAVED_USER_ID == uid) {
6298 if (setreuid(-1, uid) < 0) rb_sys_fail(0);
6299 }
6300 else {
6301 if (uid == 0) { /* (r,e,s) == (root, root, x) */
6302 if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0);
6303 if (setreuid(SAVED_USER_ID, 0) < 0) rb_sys_fail(0);
6304 SAVED_USER_ID = 0; /* (r,e,s) == (x, root, root) */
6305 if (setreuid(uid, uid) < 0) rb_sys_fail(0);
6306 SAVED_USER_ID = uid;
6307 }
6308 else {
6309 if (setreuid(0, -1) < 0) rb_sys_fail(0);
6310 SAVED_USER_ID = 0;
6311 if (setreuid(uid, uid) < 0) rb_sys_fail(0);
6312 SAVED_USER_ID = uid;
6313 }
6314 }
6315 }
6316 else {
6317 if (setreuid(uid, uid) < 0) rb_sys_fail(0);
6318 SAVED_USER_ID = uid;
6319 }
6320#elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID)
6321 if (getuid() == uid) {
6322 if (SAVED_USER_ID == uid) {
6323 if (seteuid(uid) < 0) rb_sys_fail(0);
6324 }
6325 else {
6326 if (uid == 0) {
6327 if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
6328 SAVED_USER_ID = 0;
6329 if (setruid(0) < 0) rb_sys_fail(0);
6330 }
6331 else {
6332 if (setruid(0) < 0) rb_sys_fail(0);
6333 SAVED_USER_ID = 0;
6334 if (seteuid(uid) < 0) rb_sys_fail(0);
6335 if (setruid(uid) < 0) rb_sys_fail(0);
6336 SAVED_USER_ID = uid;
6337 }
6338 }
6339 }
6340 else {
6341 if (seteuid(uid) < 0) rb_sys_fail(0);
6342 if (setruid(uid) < 0) rb_sys_fail(0);
6343 SAVED_USER_ID = uid;
6344 }
6345#else
6346 (void)uid;
6348#endif
6349 }
6350 else { /* unprivileged user */
6351#if defined(HAVE_SETRESUID)
6352 if (setresuid((getuid() == uid)? (rb_uid_t)-1: uid,
6353 (geteuid() == uid)? (rb_uid_t)-1: uid,
6354 (SAVED_USER_ID == uid)? (rb_uid_t)-1: uid) < 0) rb_sys_fail(0);
6355 SAVED_USER_ID = uid;
6356#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
6357 if (SAVED_USER_ID == uid) {
6358 if (setreuid((getuid() == uid)? (rb_uid_t)-1: uid,
6359 (geteuid() == uid)? (rb_uid_t)-1: uid) < 0)
6360 rb_sys_fail(0);
6361 }
6362 else if (getuid() != uid) {
6363 if (setreuid(uid, (geteuid() == uid)? (rb_uid_t)-1: uid) < 0)
6364 rb_sys_fail(0);
6365 SAVED_USER_ID = uid;
6366 }
6367 else if (/* getuid() == uid && */ geteuid() != uid) {
6368 if (setreuid(geteuid(), uid) < 0) rb_sys_fail(0);
6369 SAVED_USER_ID = uid;
6370 if (setreuid(uid, -1) < 0) rb_sys_fail(0);
6371 }
6372 else { /* getuid() == uid && geteuid() == uid */
6373 if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0);
6374 if (setreuid(SAVED_USER_ID, uid) < 0) rb_sys_fail(0);
6375 SAVED_USER_ID = uid;
6376 if (setreuid(uid, -1) < 0) rb_sys_fail(0);
6377 }
6378#elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID)
6379 if (SAVED_USER_ID == uid) {
6380 if (geteuid() != uid && seteuid(uid) < 0) rb_sys_fail(0);
6381 if (getuid() != uid && setruid(uid) < 0) rb_sys_fail(0);
6382 }
6383 else if (/* SAVED_USER_ID != uid && */ geteuid() == uid) {
6384 if (getuid() != uid) {
6385 if (setruid(uid) < 0) rb_sys_fail(0);
6386 SAVED_USER_ID = uid;
6387 }
6388 else {
6389 if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
6390 SAVED_USER_ID = uid;
6391 if (setruid(uid) < 0) rb_sys_fail(0);
6392 }
6393 }
6394 else if (/* geteuid() != uid && */ getuid() == uid) {
6395 if (seteuid(uid) < 0) rb_sys_fail(0);
6396 if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
6397 SAVED_USER_ID = uid;
6398 if (setruid(uid) < 0) rb_sys_fail(0);
6399 }
6400 else {
6401 rb_syserr_fail(EPERM, 0);
6402 }
6403#elif defined HAVE_44BSD_SETUID
6404 if (getuid() == uid) {
6405 /* (r,e,s)==(uid,?,?) ==> (uid,uid,uid) */
6406 if (setuid(uid) < 0) rb_sys_fail(0);
6407 SAVED_USER_ID = uid;
6408 }
6409 else {
6410 rb_syserr_fail(EPERM, 0);
6411 }
6412#elif defined HAVE_SETEUID
6413 if (getuid() == uid && SAVED_USER_ID == uid) {
6414 if (seteuid(uid) < 0) rb_sys_fail(0);
6415 }
6416 else {
6417 rb_syserr_fail(EPERM, 0);
6418 }
6419#elif defined HAVE_SETUID
6420 if (getuid() == uid && SAVED_USER_ID == uid) {
6421 if (setuid(uid) < 0) rb_sys_fail(0);
6422 }
6423 else {
6424 rb_syserr_fail(EPERM, 0);
6425 }
6426#else
6428#endif
6429 }
6430 return id;
6431}
6432
6433
6434
6435#if defined HAVE_SETGID
6436/*
6437 * call-seq:
6438 * Process::Sys.setgid(group) -> nil
6439 *
6440 * Set the group ID of the current process to _group_. Not
6441 * available on all platforms.
6442 *
6443 */
6444
6445static VALUE
6446p_sys_setgid(VALUE obj, VALUE id)
6447{
6448 check_gid_switch();
6449 if (setgid(OBJ2GID(id)) != 0) rb_sys_fail(0);
6450 return Qnil;
6451}
6452#else
6453#define p_sys_setgid rb_f_notimplement
6454#endif
6455
6456
6457#if defined HAVE_SETRGID
6458/*
6459 * call-seq:
6460 * Process::Sys.setrgid(group) -> nil
6461 *
6462 * Set the real group ID of the calling process to _group_.
6463 * Not available on all platforms.
6464 *
6465 */
6466
6467static VALUE
6468p_sys_setrgid(VALUE obj, VALUE id)
6469{
6470 check_gid_switch();
6471 if (setrgid(OBJ2GID(id)) != 0) rb_sys_fail(0);
6472 return Qnil;
6473}
6474#else
6475#define p_sys_setrgid rb_f_notimplement
6476#endif
6477
6478
6479#if defined HAVE_SETEGID
6480/*
6481 * call-seq:
6482 * Process::Sys.setegid(group) -> nil
6483 *
6484 * Set the effective group ID of the calling process to
6485 * _group_. Not available on all platforms.
6486 *
6487 */
6488
6489static VALUE
6490p_sys_setegid(VALUE obj, VALUE id)
6491{
6492 check_gid_switch();
6493 if (setegid(OBJ2GID(id)) != 0) rb_sys_fail(0);
6494 return Qnil;
6495}
6496#else
6497#define p_sys_setegid rb_f_notimplement
6498#endif
6499
6500
6501#if defined HAVE_SETREGID
6502/*
6503 * call-seq:
6504 * Process::Sys.setregid(rid, eid) -> nil
6505 *
6506 * Sets the (group) real and/or effective group IDs of the current
6507 * process to <em>rid</em> and <em>eid</em>, respectively. A value of
6508 * <code>-1</code> for either means to leave that ID unchanged. Not
6509 * available on all platforms.
6510 *
6511 */
6512
6513static VALUE
6514p_sys_setregid(VALUE obj, VALUE rid, VALUE eid)
6515{
6516 rb_gid_t rgid, egid;
6517 check_gid_switch();
6518 rgid = OBJ2GID(rid);
6519 egid = OBJ2GID(eid);
6520 if (setregid(rgid, egid) != 0) rb_sys_fail(0);
6521 return Qnil;
6522}
6523#else
6524#define p_sys_setregid rb_f_notimplement
6525#endif
6526
6527#if defined HAVE_SETRESGID
6528/*
6529 * call-seq:
6530 * Process::Sys.setresgid(rid, eid, sid) -> nil
6531 *
6532 * Sets the (group) real, effective, and saved user IDs of the
6533 * current process to <em>rid</em>, <em>eid</em>, and <em>sid</em>
6534 * respectively. A value of <code>-1</code> for any value means to
6535 * leave that ID unchanged. Not available on all platforms.
6536 *
6537 */
6538
6539static VALUE
6540p_sys_setresgid(VALUE obj, VALUE rid, VALUE eid, VALUE sid)
6541{
6542 rb_gid_t rgid, egid, sgid;
6543 check_gid_switch();
6544 rgid = OBJ2GID(rid);
6545 egid = OBJ2GID(eid);
6546 sgid = OBJ2GID(sid);
6547 if (setresgid(rgid, egid, sgid) != 0) rb_sys_fail(0);
6548 return Qnil;
6549}
6550#else
6551#define p_sys_setresgid rb_f_notimplement
6552#endif
6553
6554
6555#if defined HAVE_ISSETUGID
6556/*
6557 * call-seq:
6558 * Process::Sys.issetugid -> true or false
6559 *
6560 * Returns +true+ if the process was created as a result
6561 * of an execve(2) system call which had either of the setuid or
6562 * setgid bits set (and extra privileges were given as a result) or
6563 * if it has changed any of its real, effective or saved user or
6564 * group IDs since it began execution.
6565 *
6566 */
6567
6568static VALUE
6569p_sys_issetugid(VALUE obj)
6570{
6571 return RBOOL(issetugid());
6572}
6573#else
6574#define p_sys_issetugid rb_f_notimplement
6575#endif
6576
6577
6578/*
6579 * call-seq:
6580 * Process.gid -> integer
6581 * Process::GID.rid -> integer
6582 * Process::Sys.getgid -> integer
6583 *
6584 * Returns the (real) group ID for the current process:
6585 *
6586 * Process.gid # => 1000
6587 *
6588 */
6589
6590static VALUE
6591proc_getgid(VALUE obj)
6592{
6593 rb_gid_t gid = getgid();
6594 return GIDT2NUM(gid);
6595}
6596
6597
6598#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETRGID) || defined(HAVE_SETGID)
6599/*
6600 * call-seq:
6601 * Process.gid = new_gid -> new_gid
6602 *
6603 * Sets the group ID for the current process to +new_gid+:
6604 *
6605 * Process.gid = 1000 # => 1000
6606 *
6607 */
6608
6609static VALUE
6610proc_setgid(VALUE obj, VALUE id)
6611{
6612 rb_gid_t gid;
6613
6614 check_gid_switch();
6615
6616 gid = OBJ2GID(id);
6617#if defined(HAVE_SETRESGID)
6618 if (setresgid(gid, -1, -1) < 0) rb_sys_fail(0);
6619#elif defined HAVE_SETREGID
6620 if (setregid(gid, -1) < 0) rb_sys_fail(0);
6621#elif defined HAVE_SETRGID
6622 if (setrgid(gid) < 0) rb_sys_fail(0);
6623#elif defined HAVE_SETGID
6624 {
6625 if (getegid() == gid) {
6626 if (setgid(gid) < 0) rb_sys_fail(0);
6627 }
6628 else {
6630 }
6631 }
6632#endif
6633 return GIDT2NUM(gid);
6634}
6635#else
6636#define proc_setgid rb_f_notimplement
6637#endif
6638
6639
6640#if defined(_SC_NGROUPS_MAX) || defined(NGROUPS_MAX)
6641/*
6642 * Maximum supplementary groups are platform dependent.
6643 * FWIW, 65536 is enough big for our supported OSs.
6644 *
6645 * OS Name max groups
6646 * -----------------------------------------------
6647 * Linux Kernel >= 2.6.3 65536
6648 * Linux Kernel < 2.6.3 32
6649 * IBM AIX 5.2 64
6650 * IBM AIX 5.3 ... 6.1 128
6651 * IBM AIX 7.1 128 (can be configured to be up to 2048)
6652 * OpenBSD, NetBSD 16
6653 * FreeBSD < 8.0 16
6654 * FreeBSD >=8.0 1023
6655 * Darwin (Mac OS X) 16
6656 * Sun Solaris 7,8,9,10 16
6657 * Sun Solaris 11 / OpenSolaris 1024
6658 * Windows 1015
6659 */
6660static int _maxgroups = -1;
6661static int
6662get_sc_ngroups_max(void)
6663{
6664#ifdef _SC_NGROUPS_MAX
6665 return (int)sysconf(_SC_NGROUPS_MAX);
6666#elif defined(NGROUPS_MAX)
6667 return (int)NGROUPS_MAX;
6668#else
6669 return -1;
6670#endif
6671}
6672static int
6673maxgroups(void)
6674{
6675 if (_maxgroups < 0) {
6676 _maxgroups = get_sc_ngroups_max();
6677 if (_maxgroups < 0)
6678 _maxgroups = RB_MAX_GROUPS;
6679 }
6680
6681 return _maxgroups;
6682}
6683#endif
6684
6685
6686
6687#ifdef HAVE_GETGROUPS
6688/*
6689 * call-seq:
6690 * Process.groups -> array
6691 *
6692 * Returns an array of the group IDs
6693 * in the supplemental group access list for the current process:
6694 *
6695 * Process.groups # => [4, 24, 27, 30, 46, 122, 135, 136, 1000]
6696 *
6697 * These properties of the returned array are system-dependent:
6698 *
6699 * - Whether (and how) the array is sorted.
6700 * - Whether the array includes effective group IDs.
6701 * - Whether the array includes duplicate group IDs.
6702 * - Whether the array size exceeds the value of Process.maxgroups.
6703 *
6704 * Use this call to get a sorted and unique array:
6705 *
6706 * Process.groups.uniq.sort
6707 *
6708 */
6709
6710static VALUE
6711proc_getgroups(VALUE obj)
6712{
6713 VALUE ary, tmp;
6714 int i, ngroups;
6715 rb_gid_t *groups;
6716
6717 ngroups = getgroups(0, NULL);
6718 if (ngroups == -1)
6719 rb_sys_fail(0);
6720
6721 groups = ALLOCV_N(rb_gid_t, tmp, ngroups);
6722
6723 ngroups = getgroups(ngroups, groups);
6724 if (ngroups == -1)
6725 rb_sys_fail(0);
6726
6727 ary = rb_ary_new();
6728 for (i = 0; i < ngroups; i++)
6729 rb_ary_push(ary, GIDT2NUM(groups[i]));
6730
6731 ALLOCV_END(tmp);
6732
6733 return ary;
6734}
6735#else
6736#define proc_getgroups rb_f_notimplement
6737#endif
6738
6739
6740#ifdef HAVE_SETGROUPS
6741/*
6742 * call-seq:
6743 * Process.groups = new_groups -> new_groups
6744 *
6745 * Sets the supplemental group access list to the given
6746 * array of group IDs.
6747 *
6748 * Process.groups # => [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
6749 * Process.groups = [27, 6, 10, 11] # => [27, 6, 10, 11]
6750 * Process.groups # => [27, 6, 10, 11]
6751 *
6752 */
6753
6754static VALUE
6755proc_setgroups(VALUE obj, VALUE ary)
6756{
6757 int ngroups, i;
6758 rb_gid_t *groups;
6759 VALUE tmp;
6760 PREPARE_GETGRNAM;
6761
6762 Check_Type(ary, T_ARRAY);
6763
6764 ngroups = RARRAY_LENINT(ary);
6765 if (ngroups > maxgroups())
6766 rb_raise(rb_eArgError, "too many groups, %d max", maxgroups());
6767
6768 groups = ALLOCV_N(rb_gid_t, tmp, ngroups);
6769
6770 for (i = 0; i < ngroups; i++) {
6771 VALUE g = RARRAY_AREF(ary, i);
6772
6773 groups[i] = OBJ2GID1(g);
6774 }
6775 FINISH_GETGRNAM;
6776
6777 if (setgroups(ngroups, groups) == -1) /* ngroups <= maxgroups */
6778 rb_sys_fail(0);
6779
6780 ALLOCV_END(tmp);
6781
6782 return proc_getgroups(obj);
6783}
6784#else
6785#define proc_setgroups rb_f_notimplement
6786#endif
6787
6788
6789#ifdef HAVE_INITGROUPS
6790/*
6791 * call-seq:
6792 * Process.initgroups(username, gid) -> array
6793 *
6794 * Sets the supplemental group access list;
6795 * the new list includes:
6796 *
6797 * - The group IDs of those groups to which the user given by +username+ belongs.
6798 * - The group ID +gid+.
6799 *
6800 * Example:
6801 *
6802 * Process.groups # => [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
6803 * Process.initgroups('me', 30) # => [30, 6, 10, 11]
6804 * Process.groups # => [30, 6, 10, 11]
6805 *
6806 * Not available on all platforms.
6807 */
6808
6809static VALUE
6810proc_initgroups(VALUE obj, VALUE uname, VALUE base_grp)
6811{
6812 if (initgroups(StringValueCStr(uname), OBJ2GID(base_grp)) != 0) {
6813 rb_sys_fail(0);
6814 }
6815 return proc_getgroups(obj);
6816}
6817#else
6818#define proc_initgroups rb_f_notimplement
6819#endif
6820
6821#if defined(_SC_NGROUPS_MAX) || defined(NGROUPS_MAX)
6822/*
6823 * call-seq:
6824 * Process.maxgroups -> integer
6825 *
6826 * Returns the maximum number of group IDs allowed
6827 * in the supplemental group access list:
6828 *
6829 * Process.maxgroups # => 32
6830 *
6831 */
6832
6833static VALUE
6834proc_getmaxgroups(VALUE obj)
6835{
6836 return INT2FIX(maxgroups());
6837}
6838#else
6839#define proc_getmaxgroups rb_f_notimplement
6840#endif
6841
6842#ifdef HAVE_SETGROUPS
6843/*
6844 * call-seq:
6845 * Process.maxgroups = new_max -> new_max
6846 *
6847 * Sets the maximum number of group IDs allowed
6848 * in the supplemental group access list.
6849 */
6850
6851static VALUE
6852proc_setmaxgroups(VALUE obj, VALUE val)
6853{
6854 int ngroups = FIX2INT(val);
6855 int ngroups_max = get_sc_ngroups_max();
6856
6857 if (ngroups <= 0)
6858 rb_raise(rb_eArgError, "maxgroups %d should be positive", ngroups);
6859
6860 if (ngroups > RB_MAX_GROUPS)
6861 ngroups = RB_MAX_GROUPS;
6862
6863 if (ngroups_max > 0 && ngroups > ngroups_max)
6864 ngroups = ngroups_max;
6865
6866 _maxgroups = ngroups;
6867
6868 return INT2FIX(_maxgroups);
6869}
6870#else
6871#define proc_setmaxgroups rb_f_notimplement
6872#endif
6873
6874#if defined(HAVE_DAEMON) || (defined(HAVE_WORKING_FORK) && defined(HAVE_SETSID))
6875static int rb_daemon(int nochdir, int noclose);
6876
6877/*
6878 * call-seq:
6879 * Process.daemon(nochdir = nil, noclose = nil) -> 0
6880 *
6881 * Detaches the current process from its controlling terminal
6882 * and runs it in the background as system daemon;
6883 * returns zero.
6884 *
6885 * By default:
6886 *
6887 * - Changes the current working directory to the root directory.
6888 * - Redirects $stdin, $stdout, and $stderr to the null device.
6889 *
6890 * If optional argument +nochdir+ is +true+,
6891 * does not change the current working directory.
6892 *
6893 * If optional argument +noclose+ is +true+,
6894 * does not redirect $stdin, $stdout, or $stderr.
6895 */
6896
6897static VALUE
6898proc_daemon(int argc, VALUE *argv, VALUE _)
6899{
6900 int n, nochdir = FALSE, noclose = FALSE;
6901
6902 switch (rb_check_arity(argc, 0, 2)) {
6903 case 2: noclose = TO_BOOL(argv[1], "noclose");
6904 case 1: nochdir = TO_BOOL(argv[0], "nochdir");
6905 }
6906
6907 prefork();
6908 n = rb_daemon(nochdir, noclose);
6909 if (n < 0) rb_sys_fail("daemon");
6910 return INT2FIX(n);
6911}
6912
6913extern const char ruby_null_device[];
6914
6915static int
6916rb_daemon(int nochdir, int noclose)
6917{
6918 int err = 0;
6919#ifdef HAVE_DAEMON
6920 rb_pid_t pid = getpid();
6921 before_fork_ruby();
6922 rb_thread_acquire_fork_lock();
6923 err = daemon(nochdir, noclose);
6924 /* daemon(3) can fail in the child as well, so compare pids */
6925 release_fork_lock_after_fork(getpid() == pid ? pid : 0);
6926 after_fork_ruby(0);
6927#else
6928 int n;
6929
6930 switch (rb_fork_ruby(NULL)) {
6931 case -1: return -1;
6932 case 0: break;
6933 default: _exit(EXIT_SUCCESS);
6934 }
6935
6936 /* ignore EPERM which means already being process-leader */
6937 if (setsid() < 0) (void)0;
6938
6939 if (!nochdir)
6940 err = chdir("/");
6941
6942 if (!noclose && (n = rb_cloexec_open(ruby_null_device, O_RDWR, 0)) != -1) {
6944 (void)dup2(n, 0);
6945 (void)dup2(n, 1);
6946 (void)dup2(n, 2);
6947 if (n > 2)
6948 (void)close (n);
6949 }
6950#endif
6951 return err;
6952}
6953#else
6954#define proc_daemon rb_f_notimplement
6955#endif
6956
6957/********************************************************************
6958 *
6959 * Document-class: Process::GID
6960 *
6961 * The Process::GID module contains a collection of
6962 * module functions which can be used to portably get, set, and
6963 * switch the current process's real, effective, and saved group IDs.
6964 *
6965 */
6966
6967static rb_gid_t SAVED_GROUP_ID = -1;
6968
6969/*
6970 * call-seq:
6971 * Process::GID.change_privilege(group) -> integer
6972 *
6973 * Change the current process's real and effective group ID to that
6974 * specified by _group_. Returns the new group ID. Not
6975 * available on all platforms.
6976 *
6977 * [Process.gid, Process.egid] #=> [0, 0]
6978 * Process::GID.change_privilege(33) #=> 33
6979 * [Process.gid, Process.egid] #=> [33, 33]
6980 */
6981
6982static VALUE
6983p_gid_change_privilege(VALUE obj, VALUE id)
6984{
6985 rb_gid_t gid;
6986
6987 check_gid_switch();
6988
6989 gid = OBJ2GID(id);
6990
6991 if (geteuid() == 0) { /* root-user */
6992#if defined(HAVE_SETRESGID)
6993 if (setresgid(gid, gid, gid) < 0) rb_sys_fail(0);
6994 SAVED_GROUP_ID = gid;
6995#elif defined HAVE_SETGID
6996 if (setgid(gid) < 0) rb_sys_fail(0);
6997 SAVED_GROUP_ID = gid;
6998#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
6999 if (getgid() == gid) {
7000 if (SAVED_GROUP_ID == gid) {
7001 if (setregid(-1, gid) < 0) rb_sys_fail(0);
7002 }
7003 else {
7004 if (gid == 0) { /* (r,e,s) == (root, y, x) */
7005 if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7006 if (setregid(SAVED_GROUP_ID, 0) < 0) rb_sys_fail(0);
7007 SAVED_GROUP_ID = 0; /* (r,e,s) == (x, root, root) */
7008 if (setregid(gid, gid) < 0) rb_sys_fail(0);
7009 SAVED_GROUP_ID = gid;
7010 }
7011 else { /* (r,e,s) == (z, y, x) */
7012 if (setregid(0, 0) < 0) rb_sys_fail(0);
7013 SAVED_GROUP_ID = 0;
7014 if (setregid(gid, gid) < 0) rb_sys_fail(0);
7015 SAVED_GROUP_ID = gid;
7016 }
7017 }
7018 }
7019 else {
7020 if (setregid(gid, gid) < 0) rb_sys_fail(0);
7021 SAVED_GROUP_ID = gid;
7022 }
7023#elif defined(HAVE_SETRGID) && defined (HAVE_SETEGID)
7024 if (getgid() == gid) {
7025 if (SAVED_GROUP_ID == gid) {
7026 if (setegid(gid) < 0) rb_sys_fail(0);
7027 }
7028 else {
7029 if (gid == 0) {
7030 if (setegid(gid) < 0) rb_sys_fail(0);
7031 if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7032 SAVED_GROUP_ID = 0;
7033 if (setrgid(0) < 0) rb_sys_fail(0);
7034 }
7035 else {
7036 if (setrgid(0) < 0) rb_sys_fail(0);
7037 SAVED_GROUP_ID = 0;
7038 if (setegid(gid) < 0) rb_sys_fail(0);
7039 if (setrgid(gid) < 0) rb_sys_fail(0);
7040 SAVED_GROUP_ID = gid;
7041 }
7042 }
7043 }
7044 else {
7045 if (setegid(gid) < 0) rb_sys_fail(0);
7046 if (setrgid(gid) < 0) rb_sys_fail(0);
7047 SAVED_GROUP_ID = gid;
7048 }
7049#else
7051#endif
7052 }
7053 else { /* unprivileged user */
7054#if defined(HAVE_SETRESGID)
7055 if (setresgid((getgid() == gid)? (rb_gid_t)-1: gid,
7056 (getegid() == gid)? (rb_gid_t)-1: gid,
7057 (SAVED_GROUP_ID == gid)? (rb_gid_t)-1: gid) < 0) rb_sys_fail(0);
7058 SAVED_GROUP_ID = gid;
7059#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7060 if (SAVED_GROUP_ID == gid) {
7061 if (setregid((getgid() == gid)? (rb_uid_t)-1: gid,
7062 (getegid() == gid)? (rb_uid_t)-1: gid) < 0)
7063 rb_sys_fail(0);
7064 }
7065 else if (getgid() != gid) {
7066 if (setregid(gid, (getegid() == gid)? (rb_uid_t)-1: gid) < 0)
7067 rb_sys_fail(0);
7068 SAVED_GROUP_ID = gid;
7069 }
7070 else if (/* getgid() == gid && */ getegid() != gid) {
7071 if (setregid(getegid(), gid) < 0) rb_sys_fail(0);
7072 SAVED_GROUP_ID = gid;
7073 if (setregid(gid, -1) < 0) rb_sys_fail(0);
7074 }
7075 else { /* getgid() == gid && getegid() == gid */
7076 if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7077 if (setregid(SAVED_GROUP_ID, gid) < 0) rb_sys_fail(0);
7078 SAVED_GROUP_ID = gid;
7079 if (setregid(gid, -1) < 0) rb_sys_fail(0);
7080 }
7081#elif defined(HAVE_SETRGID) && defined(HAVE_SETEGID)
7082 if (SAVED_GROUP_ID == gid) {
7083 if (getegid() != gid && setegid(gid) < 0) rb_sys_fail(0);
7084 if (getgid() != gid && setrgid(gid) < 0) rb_sys_fail(0);
7085 }
7086 else if (/* SAVED_GROUP_ID != gid && */ getegid() == gid) {
7087 if (getgid() != gid) {
7088 if (setrgid(gid) < 0) rb_sys_fail(0);
7089 SAVED_GROUP_ID = gid;
7090 }
7091 else {
7092 if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7093 SAVED_GROUP_ID = gid;
7094 if (setrgid(gid) < 0) rb_sys_fail(0);
7095 }
7096 }
7097 else if (/* getegid() != gid && */ getgid() == gid) {
7098 if (setegid(gid) < 0) rb_sys_fail(0);
7099 if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7100 SAVED_GROUP_ID = gid;
7101 if (setrgid(gid) < 0) rb_sys_fail(0);
7102 }
7103 else {
7104 rb_syserr_fail(EPERM, 0);
7105 }
7106#elif defined HAVE_44BSD_SETGID
7107 if (getgid() == gid) {
7108 /* (r,e,s)==(gid,?,?) ==> (gid,gid,gid) */
7109 if (setgid(gid) < 0) rb_sys_fail(0);
7110 SAVED_GROUP_ID = gid;
7111 }
7112 else {
7113 rb_syserr_fail(EPERM, 0);
7114 }
7115#elif defined HAVE_SETEGID
7116 if (getgid() == gid && SAVED_GROUP_ID == gid) {
7117 if (setegid(gid) < 0) rb_sys_fail(0);
7118 }
7119 else {
7120 rb_syserr_fail(EPERM, 0);
7121 }
7122#elif defined HAVE_SETGID
7123 if (getgid() == gid && SAVED_GROUP_ID == gid) {
7124 if (setgid(gid) < 0) rb_sys_fail(0);
7125 }
7126 else {
7127 rb_syserr_fail(EPERM, 0);
7128 }
7129#else
7130 (void)gid;
7132#endif
7133 }
7134 return id;
7135}
7136
7137
7138/*
7139 * call-seq:
7140 * Process.euid -> integer
7141 * Process::UID.eid -> integer
7142 * Process::Sys.geteuid -> integer
7143 *
7144 * Returns the effective user ID for the current process.
7145 *
7146 * Process.euid # => 501
7147 *
7148 */
7149
7150static VALUE
7151proc_geteuid(VALUE obj)
7152{
7153 rb_uid_t euid = geteuid();
7154 return UIDT2NUM(euid);
7155}
7156
7157#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID) || defined(HAVE_SETUID) || defined(_POSIX_SAVED_IDS)
7158static void
7159proc_seteuid(rb_uid_t uid)
7160{
7161#if defined(HAVE_SETRESUID)
7162 if (setresuid(-1, uid, -1) < 0) rb_sys_fail(0);
7163#elif defined HAVE_SETREUID
7164 if (setreuid(-1, uid) < 0) rb_sys_fail(0);
7165#elif defined HAVE_SETEUID
7166 if (seteuid(uid) < 0) rb_sys_fail(0);
7167#elif defined HAVE_SETUID
7168 if (uid == getuid()) {
7169 if (setuid(uid) < 0) rb_sys_fail(0);
7170 }
7171 else {
7173 }
7174#else
7176#endif
7177}
7178#endif
7179
7180#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID) || defined(HAVE_SETUID)
7181/*
7182 * call-seq:
7183 * Process.euid = new_euid -> new_euid
7184 *
7185 * Sets the effective user ID for the current process.
7186 *
7187 * Not available on all platforms.
7188 */
7189
7190static VALUE
7191proc_seteuid_m(VALUE mod, VALUE euid)
7192{
7193 check_uid_switch();
7194 proc_seteuid(OBJ2UID(euid));
7195 return euid;
7196}
7197#else
7198#define proc_seteuid_m rb_f_notimplement
7199#endif
7200
7201static rb_uid_t
7202rb_seteuid_core(rb_uid_t euid)
7203{
7204#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7205 rb_uid_t uid;
7206#endif
7207
7208 check_uid_switch();
7209
7210#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7211 uid = getuid();
7212#endif
7213
7214#if defined(HAVE_SETRESUID)
7215 if (uid != euid) {
7216 if (setresuid(-1,euid,euid) < 0) rb_sys_fail(0);
7217 SAVED_USER_ID = euid;
7218 }
7219 else {
7220 if (setresuid(-1,euid,-1) < 0) rb_sys_fail(0);
7221 }
7222#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
7223 if (setreuid(-1, euid) < 0) rb_sys_fail(0);
7224 if (uid != euid) {
7225 if (setreuid(euid,uid) < 0) rb_sys_fail(0);
7226 if (setreuid(uid,euid) < 0) rb_sys_fail(0);
7227 SAVED_USER_ID = euid;
7228 }
7229#elif defined HAVE_SETEUID
7230 if (seteuid(euid) < 0) rb_sys_fail(0);
7231#elif defined HAVE_SETUID
7232 if (geteuid() == 0) rb_sys_fail(0);
7233 if (setuid(euid) < 0) rb_sys_fail(0);
7234#else
7236#endif
7237 return euid;
7238}
7239
7240
7241/*
7242 * call-seq:
7243 * Process::UID.grant_privilege(user) -> integer
7244 * Process::UID.eid= user -> integer
7245 *
7246 * Set the effective user ID, and if possible, the saved user ID of
7247 * the process to the given _user_. Returns the new
7248 * effective user ID. Not available on all platforms.
7249 *
7250 * [Process.uid, Process.euid] #=> [0, 0]
7251 * Process::UID.grant_privilege(31) #=> 31
7252 * [Process.uid, Process.euid] #=> [0, 31]
7253 */
7254
7255static VALUE
7256p_uid_grant_privilege(VALUE obj, VALUE id)
7257{
7258 rb_seteuid_core(OBJ2UID(id));
7259 return id;
7260}
7261
7262
7263/*
7264 * call-seq:
7265 * Process.egid -> integer
7266 * Process::GID.eid -> integer
7267 * Process::Sys.geteid -> integer
7268 *
7269 * Returns the effective group ID for the current process:
7270 *
7271 * Process.egid # => 500
7272 *
7273 * Not available on all platforms.
7274 */
7275
7276static VALUE
7277proc_getegid(VALUE obj)
7278{
7279 rb_gid_t egid = getegid();
7280
7281 return GIDT2NUM(egid);
7282}
7283
7284#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID) || defined(_POSIX_SAVED_IDS)
7285/*
7286 * call-seq:
7287 * Process.egid = new_egid -> new_egid
7288 *
7289 * Sets the effective group ID for the current process.
7290 *
7291 * Not available on all platforms.
7292 */
7293
7294static VALUE
7295proc_setegid(VALUE obj, VALUE egid)
7296{
7297#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID)
7298 rb_gid_t gid;
7299#endif
7300
7301 check_gid_switch();
7302
7303#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID)
7304 gid = OBJ2GID(egid);
7305#endif
7306
7307#if defined(HAVE_SETRESGID)
7308 if (setresgid(-1, gid, -1) < 0) rb_sys_fail(0);
7309#elif defined HAVE_SETREGID
7310 if (setregid(-1, gid) < 0) rb_sys_fail(0);
7311#elif defined HAVE_SETEGID
7312 if (setegid(gid) < 0) rb_sys_fail(0);
7313#elif defined HAVE_SETGID
7314 if (gid == getgid()) {
7315 if (setgid(gid) < 0) rb_sys_fail(0);
7316 }
7317 else {
7319 }
7320#else
7322#endif
7323 return egid;
7324}
7325#endif
7326
7327#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID)
7328#define proc_setegid_m proc_setegid
7329#else
7330#define proc_setegid_m rb_f_notimplement
7331#endif
7332
7333static rb_gid_t
7334rb_setegid_core(rb_gid_t egid)
7335{
7336#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7337 rb_gid_t gid;
7338#endif
7339
7340 check_gid_switch();
7341
7342#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7343 gid = getgid();
7344#endif
7345
7346#if defined(HAVE_SETRESGID)
7347 if (gid != egid) {
7348 if (setresgid(-1,egid,egid) < 0) rb_sys_fail(0);
7349 SAVED_GROUP_ID = egid;
7350 }
7351 else {
7352 if (setresgid(-1,egid,-1) < 0) rb_sys_fail(0);
7353 }
7354#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7355 if (setregid(-1, egid) < 0) rb_sys_fail(0);
7356 if (gid != egid) {
7357 if (setregid(egid,gid) < 0) rb_sys_fail(0);
7358 if (setregid(gid,egid) < 0) rb_sys_fail(0);
7359 SAVED_GROUP_ID = egid;
7360 }
7361#elif defined HAVE_SETEGID
7362 if (setegid(egid) < 0) rb_sys_fail(0);
7363#elif defined HAVE_SETGID
7364 if (geteuid() == 0 /* root user */) rb_sys_fail(0);
7365 if (setgid(egid) < 0) rb_sys_fail(0);
7366#else
7368#endif
7369 return egid;
7370}
7371
7372
7373/*
7374 * call-seq:
7375 * Process::GID.grant_privilege(group) -> integer
7376 * Process::GID.eid = group -> integer
7377 *
7378 * Set the effective group ID, and if possible, the saved group ID of
7379 * the process to the given _group_. Returns the new
7380 * effective group ID. Not available on all platforms.
7381 *
7382 * [Process.gid, Process.egid] #=> [0, 0]
7383 * Process::GID.grant_privilege(31) #=> 33
7384 * [Process.gid, Process.egid] #=> [0, 33]
7385 */
7386
7387static VALUE
7388p_gid_grant_privilege(VALUE obj, VALUE id)
7389{
7390 rb_setegid_core(OBJ2GID(id));
7391 return id;
7392}
7393
7394
7395/*
7396 * call-seq:
7397 * Process::UID.re_exchangeable? -> true or false
7398 *
7399 * Returns +true+ if the real and effective user IDs of a
7400 * process may be exchanged on the current platform.
7401 *
7402 */
7403
7404static VALUE
7405p_uid_exchangeable(VALUE _)
7406{
7407#if defined(HAVE_SETRESUID)
7408 return Qtrue;
7409#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
7410 return Qtrue;
7411#else
7412 return Qfalse;
7413#endif
7414}
7415
7416
7417/*
7418 * call-seq:
7419 * Process::UID.re_exchange -> integer
7420 *
7421 * Exchange real and effective user IDs and return the new effective
7422 * user ID. Not available on all platforms.
7423 *
7424 * [Process.uid, Process.euid] #=> [0, 31]
7425 * Process::UID.re_exchange #=> 0
7426 * [Process.uid, Process.euid] #=> [31, 0]
7427 */
7428
7429static VALUE
7430p_uid_exchange(VALUE obj)
7431{
7432 rb_uid_t uid;
7433#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7434 rb_uid_t euid;
7435#endif
7436
7437 check_uid_switch();
7438
7439 uid = getuid();
7440#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7441 euid = geteuid();
7442#endif
7443
7444#if defined(HAVE_SETRESUID)
7445 if (setresuid(euid, uid, uid) < 0) rb_sys_fail(0);
7446 SAVED_USER_ID = uid;
7447#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
7448 if (setreuid(euid,uid) < 0) rb_sys_fail(0);
7449 SAVED_USER_ID = uid;
7450#else
7451 (void)SAVED_USER_ID;
7453#endif
7454 return UIDT2NUM(uid);
7455}
7456
7457
7458/*
7459 * call-seq:
7460 * Process::GID.re_exchangeable? -> true or false
7461 *
7462 * Returns +true+ if the real and effective group IDs of a
7463 * process may be exchanged on the current platform.
7464 *
7465 */
7466
7467static VALUE
7468p_gid_exchangeable(VALUE _)
7469{
7470#if defined(HAVE_SETRESGID)
7471 return Qtrue;
7472#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7473 return Qtrue;
7474#else
7475 return Qfalse;
7476#endif
7477}
7478
7479
7480/*
7481 * call-seq:
7482 * Process::GID.re_exchange -> integer
7483 *
7484 * Exchange real and effective group IDs and return the new effective
7485 * group ID. Not available on all platforms.
7486 *
7487 * [Process.gid, Process.egid] #=> [0, 33]
7488 * Process::GID.re_exchange #=> 0
7489 * [Process.gid, Process.egid] #=> [33, 0]
7490 */
7491
7492static VALUE
7493p_gid_exchange(VALUE obj)
7494{
7495 rb_gid_t gid;
7496#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7497 rb_gid_t egid;
7498#endif
7499
7500 check_gid_switch();
7501
7502 gid = getgid();
7503#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7504 egid = getegid();
7505#endif
7506
7507#if defined(HAVE_SETRESGID)
7508 if (setresgid(egid, gid, gid) < 0) rb_sys_fail(0);
7509 SAVED_GROUP_ID = gid;
7510#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7511 if (setregid(egid,gid) < 0) rb_sys_fail(0);
7512 SAVED_GROUP_ID = gid;
7513#else
7514 (void)SAVED_GROUP_ID;
7516#endif
7517 return GIDT2NUM(gid);
7518}
7519
7520/* [MG] :FIXME: Is this correct? I'm not sure how to phrase this. */
7521
7522/*
7523 * call-seq:
7524 * Process::UID.sid_available? -> true or false
7525 *
7526 * Returns +true+ if the current platform has saved user
7527 * ID functionality.
7528 *
7529 */
7530
7531static VALUE
7532p_uid_have_saved_id(VALUE _)
7533{
7534#if defined(HAVE_SETRESUID) || defined(HAVE_SETEUID) || defined(_POSIX_SAVED_IDS)
7535 return Qtrue;
7536#else
7537 return Qfalse;
7538#endif
7539}
7540
7541
7542#if defined(HAVE_SETRESUID) || defined(HAVE_SETEUID) || defined(_POSIX_SAVED_IDS)
7543static VALUE
7544p_uid_sw_ensure(VALUE i)
7545{
7546 rb_uid_t id = (rb_uid_t/* narrowing */)i;
7547 under_uid_switch = 0;
7548 id = rb_seteuid_core(id);
7549 return UIDT2NUM(id);
7550}
7551
7552
7553/*
7554 * call-seq:
7555 * Process::UID.switch -> integer
7556 * Process::UID.switch {|| block} -> object
7557 *
7558 * Switch the effective and real user IDs of the current process. If
7559 * a <em>block</em> is given, the user IDs will be switched back
7560 * after the block is executed. Returns the new effective user ID if
7561 * called without a block, and the return value of the block if one
7562 * is given.
7563 *
7564 */
7565
7566static VALUE
7567p_uid_switch(VALUE obj)
7568{
7569 rb_uid_t uid, euid;
7570
7571 check_uid_switch();
7572
7573 uid = getuid();
7574 euid = geteuid();
7575
7576 if (uid != euid) {
7577 proc_seteuid(uid);
7578 if (rb_block_given_p()) {
7579 under_uid_switch = 1;
7580 return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, SAVED_USER_ID);
7581 }
7582 else {
7583 return UIDT2NUM(euid);
7584 }
7585 }
7586 else if (euid != SAVED_USER_ID) {
7587 proc_seteuid(SAVED_USER_ID);
7588 if (rb_block_given_p()) {
7589 under_uid_switch = 1;
7590 return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, euid);
7591 }
7592 else {
7593 return UIDT2NUM(uid);
7594 }
7595 }
7596 else {
7597 rb_syserr_fail(EPERM, 0);
7598 }
7599
7601}
7602#else
7603static VALUE
7604p_uid_sw_ensure(VALUE obj)
7605{
7606 under_uid_switch = 0;
7607 return p_uid_exchange(obj);
7608}
7609
7610static VALUE
7611p_uid_switch(VALUE obj)
7612{
7613 rb_uid_t uid, euid;
7614
7615 check_uid_switch();
7616
7617 uid = getuid();
7618 euid = geteuid();
7619
7620 if (uid == euid) {
7621 rb_syserr_fail(EPERM, 0);
7622 }
7623 p_uid_exchange(obj);
7624 if (rb_block_given_p()) {
7625 under_uid_switch = 1;
7626 return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, obj);
7627 }
7628 else {
7629 return UIDT2NUM(euid);
7630 }
7631}
7632#endif
7633
7634
7635/* [MG] :FIXME: Is this correct? I'm not sure how to phrase this. */
7636
7637/*
7638 * call-seq:
7639 * Process::GID.sid_available? -> true or false
7640 *
7641 * Returns +true+ if the current platform has saved group
7642 * ID functionality.
7643 *
7644 */
7645
7646static VALUE
7647p_gid_have_saved_id(VALUE _)
7648{
7649#if defined(HAVE_SETRESGID) || defined(HAVE_SETEGID) || defined(_POSIX_SAVED_IDS)
7650 return Qtrue;
7651#else
7652 return Qfalse;
7653#endif
7654}
7655
7656#if defined(HAVE_SETRESGID) || defined(HAVE_SETEGID) || defined(_POSIX_SAVED_IDS)
7657static VALUE
7658p_gid_sw_ensure(VALUE i)
7659{
7660 rb_gid_t id = (rb_gid_t/* narrowing */)i;
7661 under_gid_switch = 0;
7662 id = rb_setegid_core(id);
7663 return GIDT2NUM(id);
7664}
7665
7666
7667/*
7668 * call-seq:
7669 * Process::GID.switch -> integer
7670 * Process::GID.switch {|| block} -> object
7671 *
7672 * Switch the effective and real group IDs of the current process. If
7673 * a <em>block</em> is given, the group IDs will be switched back
7674 * after the block is executed. Returns the new effective group ID if
7675 * called without a block, and the return value of the block if one
7676 * is given.
7677 *
7678 */
7679
7680static VALUE
7681p_gid_switch(VALUE obj)
7682{
7683 rb_gid_t gid, egid;
7684
7685 check_gid_switch();
7686
7687 gid = getgid();
7688 egid = getegid();
7689
7690 if (gid != egid) {
7691 proc_setegid(obj, GIDT2NUM(gid));
7692 if (rb_block_given_p()) {
7693 under_gid_switch = 1;
7694 return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, SAVED_GROUP_ID);
7695 }
7696 else {
7697 return GIDT2NUM(egid);
7698 }
7699 }
7700 else if (egid != SAVED_GROUP_ID) {
7701 proc_setegid(obj, GIDT2NUM(SAVED_GROUP_ID));
7702 if (rb_block_given_p()) {
7703 under_gid_switch = 1;
7704 return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, egid);
7705 }
7706 else {
7707 return GIDT2NUM(gid);
7708 }
7709 }
7710 else {
7711 rb_syserr_fail(EPERM, 0);
7712 }
7713
7715}
7716#else
7717static VALUE
7718p_gid_sw_ensure(VALUE obj)
7719{
7720 under_gid_switch = 0;
7721 return p_gid_exchange(obj);
7722}
7723
7724static VALUE
7725p_gid_switch(VALUE obj)
7726{
7727 rb_gid_t gid, egid;
7728
7729 check_gid_switch();
7730
7731 gid = getgid();
7732 egid = getegid();
7733
7734 if (gid == egid) {
7735 rb_syserr_fail(EPERM, 0);
7736 }
7737 p_gid_exchange(obj);
7738 if (rb_block_given_p()) {
7739 under_gid_switch = 1;
7740 return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, obj);
7741 }
7742 else {
7743 return GIDT2NUM(egid);
7744 }
7745}
7746#endif
7747
7748
7749#if defined(HAVE_TIMES)
7750static long
7751get_clk_tck(void)
7752{
7753#ifdef HAVE__SC_CLK_TCK
7754 return sysconf(_SC_CLK_TCK);
7755#elif defined CLK_TCK
7756 return CLK_TCK;
7757#elif defined HZ
7758 return HZ;
7759#else
7760 return 60;
7761#endif
7762}
7763
7764/*
7765 * call-seq:
7766 * Process.times -> process_tms
7767 *
7768 * Returns a Process::Tms structure that contains user and system CPU times
7769 * for the current process, and for its children processes:
7770 *
7771 * Process.times
7772 * # => #<struct Process::Tms utime=55.122118, stime=35.533068, cutime=0.0, cstime=0.002846>
7773 *
7774 * The precision is platform-defined.
7775 */
7776
7777VALUE
7778rb_proc_times(VALUE obj)
7779{
7780 VALUE utime, stime, cutime, cstime, ret;
7781#if defined(RUSAGE_SELF) && defined(RUSAGE_CHILDREN)
7782 struct rusage usage_s, usage_c;
7783
7784 if (getrusage(RUSAGE_SELF, &usage_s) != 0 || getrusage(RUSAGE_CHILDREN, &usage_c) != 0)
7785 rb_sys_fail("getrusage");
7786 utime = DBL2NUM((double)usage_s.ru_utime.tv_sec + (double)usage_s.ru_utime.tv_usec/1e6);
7787 stime = DBL2NUM((double)usage_s.ru_stime.tv_sec + (double)usage_s.ru_stime.tv_usec/1e6);
7788 cutime = DBL2NUM((double)usage_c.ru_utime.tv_sec + (double)usage_c.ru_utime.tv_usec/1e6);
7789 cstime = DBL2NUM((double)usage_c.ru_stime.tv_sec + (double)usage_c.ru_stime.tv_usec/1e6);
7790#else
7791 const double hertz = (double)get_clk_tck();
7792 struct tms buf;
7793
7794 times(&buf);
7795 utime = DBL2NUM(buf.tms_utime / hertz);
7796 stime = DBL2NUM(buf.tms_stime / hertz);
7797 cutime = DBL2NUM(buf.tms_cutime / hertz);
7798 cstime = DBL2NUM(buf.tms_cstime / hertz);
7799#endif
7800 ret = rb_struct_new(rb_cProcessTms, utime, stime, cutime, cstime);
7801 RB_GC_GUARD(utime);
7802 RB_GC_GUARD(stime);
7803 RB_GC_GUARD(cutime);
7804 RB_GC_GUARD(cstime);
7805 return ret;
7806}
7807#else
7808#define rb_proc_times rb_f_notimplement
7809#endif
7810
7811#ifdef HAVE_LONG_LONG
7812typedef LONG_LONG timetick_int_t;
7813#define TIMETICK_INT_MIN LLONG_MIN
7814#define TIMETICK_INT_MAX LLONG_MAX
7815#define TIMETICK_INT2NUM(v) LL2NUM(v)
7816#define MUL_OVERFLOW_TIMETICK_P(a, b) MUL_OVERFLOW_LONG_LONG_P(a, b)
7817#else
7818typedef long timetick_int_t;
7819#define TIMETICK_INT_MIN LONG_MIN
7820#define TIMETICK_INT_MAX LONG_MAX
7821#define TIMETICK_INT2NUM(v) LONG2NUM(v)
7822#define MUL_OVERFLOW_TIMETICK_P(a, b) MUL_OVERFLOW_LONG_P(a, b)
7823#endif
7824
7825CONSTFUNC(static timetick_int_t gcd_timetick_int(timetick_int_t, timetick_int_t));
7826static timetick_int_t
7827gcd_timetick_int(timetick_int_t a, timetick_int_t b)
7828{
7829 timetick_int_t t;
7830
7831 if (a < b) {
7832 t = a;
7833 a = b;
7834 b = t;
7835 }
7836
7837 while (1) {
7838 t = a % b;
7839 if (t == 0)
7840 return b;
7841 a = b;
7842 b = t;
7843 }
7844}
7845
7846static void
7847reduce_fraction(timetick_int_t *np, timetick_int_t *dp)
7848{
7849 timetick_int_t gcd = gcd_timetick_int(*np, *dp);
7850 if (gcd != 1) {
7851 *np /= gcd;
7852 *dp /= gcd;
7853 }
7854}
7855
7856static void
7857reduce_factors(timetick_int_t *numerators, int num_numerators,
7858 timetick_int_t *denominators, int num_denominators)
7859{
7860 int i, j;
7861 for (i = 0; i < num_numerators; i++) {
7862 if (numerators[i] == 1)
7863 continue;
7864 for (j = 0; j < num_denominators; j++) {
7865 if (denominators[j] == 1)
7866 continue;
7867 reduce_fraction(&numerators[i], &denominators[j]);
7868 }
7869 }
7870}
7871
7872struct timetick {
7873 timetick_int_t giga_count;
7874 int32_t count; /* 0 .. 999999999 */
7875};
7876
7877static VALUE
7878timetick2dblnum(struct timetick *ttp,
7879 timetick_int_t *numerators, int num_numerators,
7880 timetick_int_t *denominators, int num_denominators)
7881{
7882 double d;
7883 int i;
7884
7885 reduce_factors(numerators, num_numerators,
7886 denominators, num_denominators);
7887
7888 d = ttp->giga_count * 1e9 + ttp->count;
7889
7890 for (i = 0; i < num_numerators; i++)
7891 d *= numerators[i];
7892 for (i = 0; i < num_denominators; i++)
7893 d /= denominators[i];
7894
7895 return DBL2NUM(d);
7896}
7897
7898static VALUE
7899timetick2dblnum_reciprocal(struct timetick *ttp,
7900 timetick_int_t *numerators, int num_numerators,
7901 timetick_int_t *denominators, int num_denominators)
7902{
7903 double d;
7904 int i;
7905
7906 reduce_factors(numerators, num_numerators,
7907 denominators, num_denominators);
7908
7909 d = 1.0;
7910 for (i = 0; i < num_denominators; i++)
7911 d *= denominators[i];
7912 for (i = 0; i < num_numerators; i++)
7913 d /= numerators[i];
7914 d /= ttp->giga_count * 1e9 + ttp->count;
7915
7916 return DBL2NUM(d);
7917}
7918
7919#define NDIV(x,y) (-(-((x)+1)/(y))-1)
7920#define DIV(n,d) ((n)<0 ? NDIV((n),(d)) : (n)/(d))
7921
7922static VALUE
7923timetick2integer(struct timetick *ttp,
7924 timetick_int_t *numerators, int num_numerators,
7925 timetick_int_t *denominators, int num_denominators)
7926{
7927 VALUE v;
7928 int i;
7929
7930 reduce_factors(numerators, num_numerators,
7931 denominators, num_denominators);
7932
7933 if (!MUL_OVERFLOW_SIGNED_INTEGER_P(1000000000, ttp->giga_count,
7934 TIMETICK_INT_MIN, TIMETICK_INT_MAX-ttp->count)) {
7935 timetick_int_t t = ttp->giga_count * 1000000000 + ttp->count;
7936 for (i = 0; i < num_numerators; i++) {
7937 timetick_int_t factor = numerators[i];
7938 if (MUL_OVERFLOW_TIMETICK_P(factor, t))
7939 goto generic;
7940 t *= factor;
7941 }
7942 for (i = 0; i < num_denominators; i++) {
7943 t = DIV(t, denominators[i]);
7944 }
7945 return TIMETICK_INT2NUM(t);
7946 }
7947
7948 generic:
7949 v = TIMETICK_INT2NUM(ttp->giga_count);
7950 v = rb_funcall(v, '*', 1, LONG2FIX(1000000000));
7951 v = rb_funcall(v, '+', 1, LONG2FIX(ttp->count));
7952 for (i = 0; i < num_numerators; i++) {
7953 timetick_int_t factor = numerators[i];
7954 if (factor == 1)
7955 continue;
7956 v = rb_funcall(v, '*', 1, TIMETICK_INT2NUM(factor));
7957 }
7958 for (i = 0; i < num_denominators; i++) {
7959 v = rb_funcall(v, '/', 1, TIMETICK_INT2NUM(denominators[i])); /* Ruby's '/' is div. */
7960 }
7961 return v;
7962}
7963
7964static VALUE
7965make_clock_result(struct timetick *ttp,
7966 timetick_int_t *numerators, int num_numerators,
7967 timetick_int_t *denominators, int num_denominators,
7968 VALUE unit)
7969{
7970 if (unit == ID2SYM(id_nanosecond)) {
7971 numerators[num_numerators++] = 1000000000;
7972 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
7973 }
7974 else if (unit == ID2SYM(id_microsecond)) {
7975 numerators[num_numerators++] = 1000000;
7976 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
7977 }
7978 else if (unit == ID2SYM(id_millisecond)) {
7979 numerators[num_numerators++] = 1000;
7980 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
7981 }
7982 else if (unit == ID2SYM(id_second)) {
7983 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
7984 }
7985 else if (unit == ID2SYM(id_float_microsecond)) {
7986 numerators[num_numerators++] = 1000000;
7987 return timetick2dblnum(ttp, numerators, num_numerators, denominators, num_denominators);
7988 }
7989 else if (unit == ID2SYM(id_float_millisecond)) {
7990 numerators[num_numerators++] = 1000;
7991 return timetick2dblnum(ttp, numerators, num_numerators, denominators, num_denominators);
7992 }
7993 else if (NIL_P(unit) || unit == ID2SYM(id_float_second)) {
7994 return timetick2dblnum(ttp, numerators, num_numerators, denominators, num_denominators);
7995 }
7996 else
7997 rb_raise(rb_eArgError, "unexpected unit: %"PRIsVALUE, unit);
7998}
7999
8000#ifdef __APPLE__
8001static const mach_timebase_info_data_t *
8002get_mach_timebase_info(void)
8003{
8004 static mach_timebase_info_data_t sTimebaseInfo;
8005
8006 if ( sTimebaseInfo.denom == 0 ) {
8007 (void) mach_timebase_info(&sTimebaseInfo);
8008 }
8009
8010 return &sTimebaseInfo;
8011}
8012
8013double
8014ruby_real_ms_time(void)
8015{
8016 const mach_timebase_info_data_t *info = get_mach_timebase_info();
8017 uint64_t t = mach_absolute_time();
8018 return (double)t * info->numer / info->denom / 1e6;
8019}
8020#endif
8021
8022#if defined(NUM2CLOCKID)
8023# define NUMERIC_CLOCKID 1
8024#else
8025# define NUMERIC_CLOCKID 0
8026# define NUM2CLOCKID(x) 0
8027#endif
8028
8029#define clock_failed(name, err, arg) do { \
8030 int clock_error = (err); \
8031 rb_syserr_fail_str(clock_error, rb_sprintf("clock_" name "(%+"PRIsVALUE")", (arg))); \
8032 } while (0)
8033
8034/*
8035 * call-seq:
8036 * Process.clock_gettime(clock_id, unit = :float_second) -> number
8037 *
8038 * Returns a clock time as determined by POSIX function
8039 * {clock_gettime()}[https://man7.org/linux/man-pages/man3/clock_gettime.3.html]:
8040 *
8041 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID) # => 198.650379677
8042 *
8043 * Argument +clock_id+ should be a symbol or a constant that specifies
8044 * the clock whose time is to be returned;
8045 * see below.
8046 *
8047 * Optional argument +unit+ should be a symbol that specifies
8048 * the unit to be used in the returned clock time;
8049 * see below.
8050 *
8051 * <b>Argument +clock_id+</b>
8052 *
8053 * Argument +clock_id+ specifies the clock whose time is to be returned;
8054 * it may be a constant such as <tt>Process::CLOCK_REALTIME</tt>,
8055 * or a symbol shorthand such as +:CLOCK_REALTIME+.
8056 *
8057 * The supported clocks depend on the underlying operating system;
8058 * this method supports the following clocks on the indicated platforms
8059 * (raises Errno::EINVAL if called with an unsupported clock):
8060 *
8061 * - +:CLOCK_BOOTTIME+: Linux 2.6.39.
8062 * - +:CLOCK_BOOTTIME_ALARM+: Linux 3.0.
8063 * - +:CLOCK_MONOTONIC+: SUSv3 to 4, Linux 2.5.63, FreeBSD 3.0, NetBSD 2.0, OpenBSD 3.4, macOS 10.12, Windows-2000.
8064 * - +:CLOCK_MONOTONIC_COARSE+: Linux 2.6.32.
8065 * - +:CLOCK_MONOTONIC_FAST+: FreeBSD 8.1.
8066 * - +:CLOCK_MONOTONIC_PRECISE+: FreeBSD 8.1.
8067 * - +:CLOCK_MONOTONIC_RAW+: Linux 2.6.28, macOS 10.12.
8068 * - +:CLOCK_MONOTONIC_RAW_APPROX+: macOS 10.12.
8069 * - +:CLOCK_PROCESS_CPUTIME_ID+: SUSv3 to 4, Linux 2.5.63, FreeBSD 9.3, OpenBSD 5.4, macOS 10.12.
8070 * - +:CLOCK_PROF+: FreeBSD 3.0, OpenBSD 2.1.
8071 * - +:CLOCK_REALTIME+: SUSv2 to 4, Linux 2.5.63, FreeBSD 3.0, NetBSD 2.0, OpenBSD 2.1, macOS 10.12, Windows-8/Server-2012.
8072 * Time.now is recommended over +:CLOCK_REALTIME:.
8073 * - +:CLOCK_REALTIME_ALARM+: Linux 3.0.
8074 * - +:CLOCK_REALTIME_COARSE+: Linux 2.6.32.
8075 * - +:CLOCK_REALTIME_FAST+: FreeBSD 8.1.
8076 * - +:CLOCK_REALTIME_PRECISE+: FreeBSD 8.1.
8077 * - +:CLOCK_SECOND+: FreeBSD 8.1.
8078 * - +:CLOCK_TAI+: Linux 3.10.
8079 * - +:CLOCK_THREAD_CPUTIME_ID+: SUSv3 to 4, Linux 2.5.63, FreeBSD 7.1, OpenBSD 5.4, macOS 10.12.
8080 * - +:CLOCK_UPTIME+: FreeBSD 7.0, OpenBSD 5.5.
8081 * - +:CLOCK_UPTIME_FAST+: FreeBSD 8.1.
8082 * - +:CLOCK_UPTIME_PRECISE+: FreeBSD 8.1.
8083 * - +:CLOCK_UPTIME_RAW+: macOS 10.12.
8084 * - +:CLOCK_UPTIME_RAW_APPROX+: macOS 10.12.
8085 * - +:CLOCK_VIRTUAL+: FreeBSD 3.0, OpenBSD 2.1.
8086 *
8087 * Note that SUS stands for Single Unix Specification.
8088 * SUS contains POSIX and clock_gettime is defined in the POSIX part.
8089 * SUS defines +:CLOCK_REALTIME+ as mandatory but
8090 * +:CLOCK_MONOTONIC+, +:CLOCK_PROCESS_CPUTIME_ID+,
8091 * and +:CLOCK_THREAD_CPUTIME_ID+ are optional.
8092 *
8093 * +:CLOCK_THREAD_CPUTIME_ID+ measures the native thread that reads it, not
8094 * the Ruby thread. Under the M:N thread scheduler (see +RUBY_MN_THREADS+) a
8095 * Ruby thread can move between native threads, so two reads taken from one
8096 * Ruby thread may come from different native threads, and the later read can
8097 * be smaller than the earlier one. To measure elapsed time there, use
8098 * +:CLOCK_PROCESS_CPUTIME_ID+ or +:CLOCK_MONOTONIC+.
8099 *
8100 * Certain emulations are used when the given +clock_id+
8101 * is not supported directly:
8102 *
8103 * - Emulations for +:CLOCK_REALTIME+:
8104 *
8105 * - +:GETTIMEOFDAY_BASED_CLOCK_REALTIME+:
8106 * Use gettimeofday() defined by SUS (deprecated in SUSv4).
8107 * The resolution is 1 microsecond.
8108 * - +:TIME_BASED_CLOCK_REALTIME+:
8109 * Use time() defined by ISO C.
8110 * The resolution is 1 second.
8111 *
8112 * - Emulations for +:CLOCK_MONOTONIC+:
8113 *
8114 * - +:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC+:
8115 * Use mach_absolute_time(), available on Darwin.
8116 * The resolution is CPU dependent.
8117 * - +:TIMES_BASED_CLOCK_MONOTONIC+:
8118 * Use the result value of times() defined by POSIX, thus:
8119 * >>>
8120 * Upon successful completion, times() shall return the elapsed real time,
8121 * in clock ticks, since an arbitrary point in the past
8122 * (for example, system start-up time).
8123 *
8124 * For example, GNU/Linux returns a value based on jiffies and it is monotonic.
8125 * However, 4.4BSD uses gettimeofday() and it is not monotonic.
8126 * (FreeBSD uses +:CLOCK_MONOTONIC+ instead, though.)
8127 *
8128 * The resolution is the clock tick.
8129 * "getconf CLK_TCK" command shows the clock ticks per second.
8130 * (The clock ticks-per-second is defined by HZ macro in older systems.)
8131 * If it is 100 and clock_t is 32 bits integer type,
8132 * the resolution is 10 millisecond and cannot represent over 497 days.
8133 *
8134 * - Emulations for +:CLOCK_PROCESS_CPUTIME_ID+:
8135 *
8136 * - +:GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID+:
8137 * Use getrusage() defined by SUS.
8138 * getrusage() is used with RUSAGE_SELF to obtain the time only for
8139 * the calling process (excluding the time for child processes).
8140 * The result is addition of user time (ru_utime) and system time (ru_stime).
8141 * The resolution is 1 microsecond.
8142 * - +:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID+:
8143 * Use times() defined by POSIX.
8144 * The result is addition of user time (tms_utime) and system time (tms_stime).
8145 * tms_cutime and tms_cstime are ignored to exclude the time for child processes.
8146 * The resolution is the clock tick.
8147 * "getconf CLK_TCK" command shows the clock ticks per second.
8148 * (The clock ticks per second is defined by HZ macro in older systems.)
8149 * If it is 100, the resolution is 10 millisecond.
8150 * - +:CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID+:
8151 * Use clock() defined by ISO C.
8152 * The resolution is <tt>1/CLOCKS_PER_SEC</tt>.
8153 * +CLOCKS_PER_SEC+ is the C-level macro defined by time.h.
8154 * SUS defines +CLOCKS_PER_SEC+ as 1000000;
8155 * other systems may define it differently.
8156 * If +CLOCKS_PER_SEC+ is 1000000 (as in SUS),
8157 * the resolution is 1 microsecond.
8158 * If +CLOCKS_PER_SEC+ is 1000000 and clock_t is a 32-bit integer type,
8159 * it cannot represent over 72 minutes.
8160 *
8161 * <b>Argument +unit+</b>
8162 *
8163 * Optional argument +unit+ (default +:float_second+)
8164 * specifies the unit for the returned value.
8165 *
8166 * - +:float_microsecond+: Number of microseconds as a float.
8167 * - +:float_millisecond+: Number of milliseconds as a float.
8168 * - +:float_second+: Number of seconds as a float.
8169 * - +:microsecond+: Number of microseconds as an integer.
8170 * - +:millisecond+: Number of milliseconds as an integer.
8171 * - +:nanosecond+: Number of nanoseconds as an integer.
8172 * - +:second+: Number of seconds as an integer.
8173 *
8174 * Examples:
8175 *
8176 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :float_microsecond)
8177 * # => 203605054.825
8178 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :float_millisecond)
8179 * # => 203643.696848
8180 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :float_second)
8181 * # => 203.762181929
8182 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :microsecond)
8183 * # => 204123212
8184 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :millisecond)
8185 * # => 204298
8186 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :nanosecond)
8187 * # => 204602286036
8188 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :second)
8189 * # => 204
8190 *
8191 * The underlying function, clock_gettime(), returns a number of nanoseconds.
8192 * Float object (IEEE 754 double) is not enough to represent
8193 * the return value for +:CLOCK_REALTIME+.
8194 * If the exact nanoseconds value is required, use +:nanosecond+ as the +unit+.
8195 *
8196 * The origin (time zero) of the returned value is system-dependent,
8197 * and may be, for example, system start up time,
8198 * process start up time, the Epoch, etc.
8199 *
8200 * The origin in +:CLOCK_REALTIME+ is defined as the Epoch:
8201 * <tt>1970-01-01 00:00:00 UTC</tt>;
8202 * some systems count leap seconds and others don't,
8203 * so the result may vary across systems.
8204 */
8205static VALUE
8206rb_clock_gettime(int argc, VALUE *argv, VALUE _)
8207{
8208 int ret;
8209
8210 struct timetick tt;
8211 timetick_int_t numerators[2];
8212 timetick_int_t denominators[2];
8213 int num_numerators = 0;
8214 int num_denominators = 0;
8215
8216 VALUE unit = (rb_check_arity(argc, 1, 2) == 2) ? argv[1] : Qnil;
8217 VALUE clk_id = argv[0];
8218#ifdef HAVE_CLOCK_GETTIME
8219 clockid_t c;
8220#endif
8221
8222 if (SYMBOL_P(clk_id)) {
8223#ifdef CLOCK_REALTIME
8224 if (clk_id == RUBY_CLOCK_REALTIME) {
8225 c = CLOCK_REALTIME;
8226 goto gettime;
8227 }
8228#endif
8229
8230#ifdef CLOCK_MONOTONIC
8231 if (clk_id == RUBY_CLOCK_MONOTONIC) {
8232 c = CLOCK_MONOTONIC;
8233 goto gettime;
8234 }
8235#endif
8236
8237#ifdef CLOCK_PROCESS_CPUTIME_ID
8238 if (clk_id == RUBY_CLOCK_PROCESS_CPUTIME_ID) {
8239 c = CLOCK_PROCESS_CPUTIME_ID;
8240 goto gettime;
8241 }
8242#endif
8243
8244#ifdef CLOCK_THREAD_CPUTIME_ID
8245 if (clk_id == RUBY_CLOCK_THREAD_CPUTIME_ID) {
8246 c = CLOCK_THREAD_CPUTIME_ID;
8247 goto gettime;
8248 }
8249#endif
8250
8251 /*
8252 * Non-clock_gettime clocks are provided by symbol clk_id.
8253 */
8254#ifdef HAVE_GETTIMEOFDAY
8255 /*
8256 * GETTIMEOFDAY_BASED_CLOCK_REALTIME is used for
8257 * CLOCK_REALTIME if clock_gettime is not available.
8258 */
8259#define RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME ID2SYM(id_GETTIMEOFDAY_BASED_CLOCK_REALTIME)
8260 if (clk_id == RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME) {
8261 struct timeval tv;
8262 ret = gettimeofday(&tv, 0);
8263 if (ret != 0)
8264 rb_sys_fail("gettimeofday");
8265 tt.giga_count = tv.tv_sec;
8266 tt.count = (int32_t)tv.tv_usec * 1000;
8267 denominators[num_denominators++] = 1000000000;
8268 goto success;
8269 }
8270#endif
8271
8272#define RUBY_TIME_BASED_CLOCK_REALTIME ID2SYM(id_TIME_BASED_CLOCK_REALTIME)
8273 if (clk_id == RUBY_TIME_BASED_CLOCK_REALTIME) {
8274 time_t t;
8275 t = time(NULL);
8276 if (t == (time_t)-1)
8277 rb_sys_fail("time");
8278 tt.giga_count = t;
8279 tt.count = 0;
8280 denominators[num_denominators++] = 1000000000;
8281 goto success;
8282 }
8283
8284#ifdef HAVE_TIMES
8285#define RUBY_TIMES_BASED_CLOCK_MONOTONIC \
8286 ID2SYM(id_TIMES_BASED_CLOCK_MONOTONIC)
8287 if (clk_id == RUBY_TIMES_BASED_CLOCK_MONOTONIC) {
8288 struct tms buf;
8289 clock_t c;
8290 unsigned_clock_t uc;
8291 c = times(&buf);
8292 if (c == (clock_t)-1)
8293 rb_sys_fail("times");
8294 uc = (unsigned_clock_t)c;
8295 tt.count = (int32_t)(uc % 1000000000);
8296 tt.giga_count = (uc / 1000000000);
8297 denominators[num_denominators++] = get_clk_tck();
8298 goto success;
8299 }
8300#endif
8301
8302#ifdef RUSAGE_SELF
8303#define RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID \
8304 ID2SYM(id_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID)
8305 if (clk_id == RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8306 struct rusage usage;
8307 int32_t usec;
8308 ret = getrusage(RUSAGE_SELF, &usage);
8309 if (ret != 0)
8310 rb_sys_fail("getrusage");
8311 tt.giga_count = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
8312 usec = (int32_t)(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec);
8313 if (1000000 <= usec) {
8314 tt.giga_count++;
8315 usec -= 1000000;
8316 }
8317 tt.count = usec * 1000;
8318 denominators[num_denominators++] = 1000000000;
8319 goto success;
8320 }
8321#endif
8322
8323#ifdef HAVE_TIMES
8324#define RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID \
8325 ID2SYM(id_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID)
8326 if (clk_id == RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8327 struct tms buf;
8328 unsigned_clock_t utime, stime;
8329 if (times(&buf) == (clock_t)-1)
8330 rb_sys_fail("times");
8331 utime = (unsigned_clock_t)buf.tms_utime;
8332 stime = (unsigned_clock_t)buf.tms_stime;
8333 tt.count = (int32_t)((utime % 1000000000) + (stime % 1000000000));
8334 tt.giga_count = (utime / 1000000000) + (stime / 1000000000);
8335 if (1000000000 <= tt.count) {
8336 tt.count -= 1000000000;
8337 tt.giga_count++;
8338 }
8339 denominators[num_denominators++] = get_clk_tck();
8340 goto success;
8341 }
8342#endif
8343
8344#define RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID \
8345 ID2SYM(id_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID)
8346 if (clk_id == RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8347 clock_t c;
8348 unsigned_clock_t uc;
8349 errno = 0;
8350 c = clock();
8351 if (c == (clock_t)-1)
8352 rb_sys_fail("clock");
8353 uc = (unsigned_clock_t)c;
8354 tt.count = (int32_t)(uc % 1000000000);
8355 tt.giga_count = uc / 1000000000;
8356 denominators[num_denominators++] = CLOCKS_PER_SEC;
8357 goto success;
8358 }
8359
8360#ifdef __APPLE__
8361 if (clk_id == RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) {
8362 const mach_timebase_info_data_t *info = get_mach_timebase_info();
8363 uint64_t t = mach_absolute_time();
8364 tt.count = (int32_t)(t % 1000000000);
8365 tt.giga_count = t / 1000000000;
8366 numerators[num_numerators++] = info->numer;
8367 denominators[num_denominators++] = info->denom;
8368 denominators[num_denominators++] = 1000000000;
8369 goto success;
8370 }
8371#endif
8372 }
8373 else if (NUMERIC_CLOCKID) {
8374#if defined(HAVE_CLOCK_GETTIME)
8375 struct timespec ts;
8376 c = NUM2CLOCKID(clk_id);
8377 gettime:
8378 ret = clock_gettime(c, &ts);
8379 if (ret == -1)
8380 clock_failed("gettime", errno, clk_id);
8381 tt.count = (int32_t)ts.tv_nsec;
8382 tt.giga_count = ts.tv_sec;
8383 denominators[num_denominators++] = 1000000000;
8384 goto success;
8385#endif
8386 }
8387 else {
8389 }
8390 clock_failed("gettime", EINVAL, clk_id);
8391
8392 success:
8393 return make_clock_result(&tt, numerators, num_numerators, denominators, num_denominators, unit);
8394}
8395
8396/*
8397 * call-seq:
8398 * Process.clock_getres(clock_id, unit = :float_second) -> number
8399 *
8400 * Returns a clock resolution as determined by POSIX function
8401 * {clock_getres()}[https://man7.org/linux/man-pages/man3/clock_getres.3.html]:
8402 *
8403 * Process.clock_getres(:CLOCK_REALTIME) # => 1.0e-09
8404 *
8405 * See Process.clock_gettime for the values of +clock_id+ and +unit+.
8406 *
8407 * Examples:
8408 *
8409 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :float_microsecond) # => 0.001
8410 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :float_millisecond) # => 1.0e-06
8411 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :float_second) # => 1.0e-09
8412 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :microsecond) # => 0
8413 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :millisecond) # => 0
8414 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :nanosecond) # => 1
8415 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :second) # => 0
8416 *
8417 * In addition to the values for +unit+ supported in Process.clock_gettime,
8418 * this method supports +:hertz+, the integer number of clock ticks per second
8419 * (which is the reciprocal of +:float_second+):
8420 *
8421 * Process.clock_getres(:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID, :hertz) # => 100.0
8422 * Process.clock_getres(:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID, :float_second) # => 0.01
8423 *
8424 * <b>Accuracy</b>:
8425 * Note that the returned resolution may be inaccurate on some platforms
8426 * due to underlying bugs.
8427 * Inaccurate resolutions have been reported for various clocks including
8428 * +:CLOCK_MONOTONIC+ and +:CLOCK_MONOTONIC_RAW+
8429 * on Linux, macOS, BSD or AIX platforms, when using ARM processors,
8430 * or when using virtualization.
8431 */
8432static VALUE
8433rb_clock_getres(int argc, VALUE *argv, VALUE _)
8434{
8435 int ret;
8436
8437 struct timetick tt;
8438 timetick_int_t numerators[2];
8439 timetick_int_t denominators[2];
8440 int num_numerators = 0;
8441 int num_denominators = 0;
8442#ifdef HAVE_CLOCK_GETRES
8443 clockid_t c;
8444#endif
8445
8446 VALUE unit = (rb_check_arity(argc, 1, 2) == 2) ? argv[1] : Qnil;
8447 VALUE clk_id = argv[0];
8448
8449 if (SYMBOL_P(clk_id)) {
8450#ifdef CLOCK_REALTIME
8451 if (clk_id == RUBY_CLOCK_REALTIME) {
8452 c = CLOCK_REALTIME;
8453 goto getres;
8454 }
8455#endif
8456
8457#ifdef CLOCK_MONOTONIC
8458 if (clk_id == RUBY_CLOCK_MONOTONIC) {
8459 c = CLOCK_MONOTONIC;
8460 goto getres;
8461 }
8462#endif
8463
8464#ifdef CLOCK_PROCESS_CPUTIME_ID
8465 if (clk_id == RUBY_CLOCK_PROCESS_CPUTIME_ID) {
8466 c = CLOCK_PROCESS_CPUTIME_ID;
8467 goto getres;
8468 }
8469#endif
8470
8471#ifdef CLOCK_THREAD_CPUTIME_ID
8472 if (clk_id == RUBY_CLOCK_THREAD_CPUTIME_ID) {
8473 c = CLOCK_THREAD_CPUTIME_ID;
8474 goto getres;
8475 }
8476#endif
8477
8478#ifdef RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME
8479 if (clk_id == RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME) {
8480 tt.giga_count = 0;
8481 tt.count = 1000;
8482 denominators[num_denominators++] = 1000000000;
8483 goto success;
8484 }
8485#endif
8486
8487#ifdef RUBY_TIME_BASED_CLOCK_REALTIME
8488 if (clk_id == RUBY_TIME_BASED_CLOCK_REALTIME) {
8489 tt.giga_count = 1;
8490 tt.count = 0;
8491 denominators[num_denominators++] = 1000000000;
8492 goto success;
8493 }
8494#endif
8495
8496#ifdef RUBY_TIMES_BASED_CLOCK_MONOTONIC
8497 if (clk_id == RUBY_TIMES_BASED_CLOCK_MONOTONIC) {
8498 tt.count = 1;
8499 tt.giga_count = 0;
8500 denominators[num_denominators++] = get_clk_tck();
8501 goto success;
8502 }
8503#endif
8504
8505#ifdef RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
8506 if (clk_id == RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8507 tt.giga_count = 0;
8508 tt.count = 1000;
8509 denominators[num_denominators++] = 1000000000;
8510 goto success;
8511 }
8512#endif
8513
8514#ifdef RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID
8515 if (clk_id == RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8516 tt.count = 1;
8517 tt.giga_count = 0;
8518 denominators[num_denominators++] = get_clk_tck();
8519 goto success;
8520 }
8521#endif
8522
8523#ifdef RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID
8524 if (clk_id == RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8525 tt.count = 1;
8526 tt.giga_count = 0;
8527 denominators[num_denominators++] = CLOCKS_PER_SEC;
8528 goto success;
8529 }
8530#endif
8531
8532#ifdef RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
8533 if (clk_id == RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) {
8534 const mach_timebase_info_data_t *info = get_mach_timebase_info();
8535 tt.count = 1;
8536 tt.giga_count = 0;
8537 numerators[num_numerators++] = info->numer;
8538 denominators[num_denominators++] = info->denom;
8539 denominators[num_denominators++] = 1000000000;
8540 goto success;
8541 }
8542#endif
8543 }
8544 else if (NUMERIC_CLOCKID) {
8545#if defined(HAVE_CLOCK_GETRES)
8546 struct timespec ts;
8547 c = NUM2CLOCKID(clk_id);
8548 getres:
8549 ret = clock_getres(c, &ts);
8550 if (ret == -1)
8551 clock_failed("getres", errno, clk_id);
8552 tt.count = (int32_t)ts.tv_nsec;
8553 tt.giga_count = ts.tv_sec;
8554 denominators[num_denominators++] = 1000000000;
8555 goto success;
8556#endif
8557 }
8558 else {
8560 }
8561 clock_failed("getres", EINVAL, clk_id);
8562
8563 success:
8564 if (unit == ID2SYM(id_hertz)) {
8565 return timetick2dblnum_reciprocal(&tt, numerators, num_numerators, denominators, num_denominators);
8566 }
8567 else {
8568 return make_clock_result(&tt, numerators, num_numerators, denominators, num_denominators, unit);
8569 }
8570}
8571
8572static VALUE
8573get_CHILD_STATUS(ID _x, VALUE *_y)
8574{
8575 return rb_last_status_get();
8576}
8577
8578static VALUE
8579get_PROCESS_ID(ID _x, VALUE *_y)
8580{
8581 return get_pid();
8582}
8583
8584/*
8585 * call-seq:
8586 * Process.kill(signal, *ids) -> count
8587 *
8588 * Sends a signal to each process specified by +ids+
8589 * (which must specify at least one ID);
8590 * returns the count of signals sent.
8591 *
8592 * For each given +id+, if +id+ is:
8593 *
8594 * - Positive, sends the signal to the process whose process ID is +id+.
8595 * - Zero, send the signal to all processes in the current process group.
8596 * - Negative, sends the signal to a system-dependent collection of processes.
8597 *
8598 * Argument +signal+ specifies the signal to be sent;
8599 * the argument may be:
8600 *
8601 * - An integer signal number: e.g., +-29+, +0+, +29+.
8602 * - A signal name (string), with or without leading <tt>'SIG'</tt>,
8603 * and with or without a further prefixed minus sign (<tt>'-'</tt>):
8604 * e.g.:
8605 *
8606 * - <tt>'SIGPOLL'</tt>.
8607 * - <tt>'POLL'</tt>,
8608 * - <tt>'-SIGPOLL'</tt>.
8609 * - <tt>'-POLL'</tt>.
8610 *
8611 * - A signal symbol, with or without leading <tt>'SIG'</tt>,
8612 * and with or without a further prefixed minus sign (<tt>'-'</tt>):
8613 * e.g.:
8614 *
8615 * - +:SIGPOLL+.
8616 * - +:POLL+.
8617 * - <tt>:'-SIGPOLL'</tt>.
8618 * - <tt>:'-POLL'</tt>.
8619 *
8620 * If +signal+ is:
8621 *
8622 * - A non-negative integer, or a signal name or symbol
8623 * without prefixed <tt>'-'</tt>,
8624 * each process with process ID +id+ is signalled.
8625 * - A negative integer, or a signal name or symbol
8626 * with prefixed <tt>'-'</tt>,
8627 * each process group with group ID +id+ is signalled.
8628 *
8629 * Use method Signal.list to see which signals are supported
8630 * by Ruby on the underlying platform;
8631 * the method returns a hash of the string names
8632 * and non-negative integer values of the supported signals.
8633 * The size and content of the returned hash varies widely
8634 * among platforms.
8635 *
8636 * Additionally, signal +0+ is useful to determine if the process exists.
8637 *
8638 * Example:
8639 *
8640 * pid = fork do
8641 * Signal.trap('HUP') { puts 'Ouch!'; exit }
8642 * # ... do some work ...
8643 * end
8644 * # ...
8645 * Process.kill('HUP', pid)
8646 * Process.wait
8647 *
8648 * Output:
8649 *
8650 * Ouch!
8651 *
8652 * Exceptions:
8653 *
8654 * - Raises Errno::EINVAL or RangeError if +signal+ is an integer
8655 * but invalid.
8656 * - Raises ArgumentError if +signal+ is a string or symbol
8657 * but invalid.
8658 * - Raises Errno::ESRCH or RangeError if one of +ids+ is invalid.
8659 * - Raises Errno::EPERM if needed permissions are not in force.
8660 *
8661 * In the last two cases, signals may have been sent to some processes.
8662 */
8663
8664static VALUE
8665proc_rb_f_kill(int c, const VALUE *v, VALUE _)
8666{
8667 return rb_f_kill(c, v);
8668}
8669
8671static VALUE rb_mProcUID;
8672static VALUE rb_mProcGID;
8673static VALUE rb_mProcID_Syscall;
8674
8675/*
8676 * call-seq:
8677 * Process.warmup -> true
8678 *
8679 * Notify the Ruby virtual machine that the boot sequence is finished,
8680 * and that now is a good time to optimize the application. This is useful
8681 * for long running applications.
8682 *
8683 * This method is expected to be called at the end of the application boot.
8684 * If the application is deployed using a pre-forking model, +Process.warmup+
8685 * should be called in the original process before the first fork.
8686 *
8687 * The actual optimizations performed are entirely implementation specific
8688 * and may change in the future without notice.
8689 *
8690 * On CRuby, +Process.warmup+:
8691 *
8692 * * Performs a major GC.
8693 * * Compacts the heap.
8694 * * Promotes all surviving objects to the old generation.
8695 * * Precomputes the coderange of all strings.
8696 * * Frees all empty heap pages and increments the allocatable pages counter
8697 * by the number of pages freed.
8698 * * Invoke +malloc_trim+ if available to free empty malloc pages.
8699 * * Eagerly loads the +error_highlight+, +did_you_mean+, and +syntax_suggest+
8700 * gems, which are otherwise loaded lazily on the first error display.
8701 */
8702
8703static VALUE
8704proc_warmup(VALUE _)
8705{
8706 // Load the error decoration gems now so that their detailed_message
8707 // decorators land in shared memory before a pre-forking server forks,
8708 // instead of being loaded lazily on the first error at runtime.
8709 rb_eager_load_detailed_message_extension();
8710
8711 RB_VM_LOCKING() {
8712 rb_gc_prepare_heap();
8713 }
8714 return Qtrue;
8715}
8716
8717/*
8718 * Document-module: Process
8719 *
8720 * Module +Process+ represents a process in the underlying operating system.
8721 * Its methods support management of the current process and its child processes.
8722 *
8723 * == Process Creation
8724 *
8725 * Each of the following methods executes a given command in a new process or subshell,
8726 * or multiple commands in new processes and/or subshells.
8727 * The choice of process or subshell depends on the form of the command;
8728 * see {Argument command_line or exe_path}[rdoc-ref:Process@Argument+command_line+or+exe_path].
8729 *
8730 * - Process.spawn, Kernel#spawn: Executes the command;
8731 * returns the new pid without waiting for completion.
8732 * - Process.exec: Replaces the current process by executing the command.
8733 *
8734 * In addition:
8735 *
8736 * - Method Kernel#system executes a given command-line (string) in a subshell;
8737 * returns +true+, +false+, or +nil+.
8738 * - Method Kernel#` executes a given command-line (string) in a subshell;
8739 * returns its $stdout string.
8740 * - Module Open3 supports creating child processes
8741 * with access to their $stdin, $stdout, and $stderr streams.
8742 *
8743 * === Execution Environment
8744 *
8745 * Optional leading argument +env+ is a hash of name/value pairs,
8746 * where each name is a string and each value is a string or +nil+;
8747 * each name/value pair is added to ENV in the new process.
8748 *
8749 * Process.spawn( 'ruby -e "p ENV[\"Foo\"]"')
8750 * Process.spawn({'Foo' => '0'}, 'ruby -e "p ENV[\"Foo\"]"')
8751 *
8752 * Output:
8753 *
8754 * "0"
8755 *
8756 * The effect is usually similar to that of calling ENV#update with argument +env+,
8757 * where each named environment variable is created or updated
8758 * (if the value is non-+nil+),
8759 * or deleted (if the value is +nil+).
8760 *
8761 * However, some modifications to the calling process may remain
8762 * if the new process fails.
8763 * For example, hard resource limits are not restored.
8764 *
8765 * === Argument +command_line+ or +exe_path+
8766 *
8767 * The required string argument is one of the following:
8768 *
8769 * - +command_line+ if it begins with a shell reserved word or special built-in,
8770 * or if it contains one or more meta characters.
8771 * - +exe_path+ otherwise.
8772 *
8773 * ==== Argument +command_line+
8774 *
8775 * \String argument +command_line+ is a command line to be passed to a shell;
8776 * it must begin with a shell reserved word, begin with a special built-in,
8777 * or contain meta characters:
8778 *
8779 * system('if true; then echo "Foo"; fi') # => true # Shell reserved word.
8780 * system('exit') # => true # Built-in.
8781 * system('date > /tmp/date.tmp') # => true # Contains meta character.
8782 * system('date > /nop/date.tmp') # => false
8783 * system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
8784 *
8785 * The command line may also contain arguments and options for the command:
8786 *
8787 * system('echo "Foo"') # => true
8788 *
8789 * Output:
8790 *
8791 * Foo
8792 *
8793 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
8794 *
8795 * ==== Argument +exe_path+
8796 *
8797 * Argument +exe_path+ is one of the following:
8798 *
8799 * - The string path to an executable file to be called:
8800 *
8801 * Example:
8802 *
8803 * system('/usr/bin/date') # => true # Path to date on Unix-style system.
8804 * system('foo') # => nil # Command execlution failed.
8805 *
8806 * Output:
8807 *
8808 * Thu Aug 31 10:06:48 AM CDT 2023
8809 *
8810 * A path or command name containing spaces without arguments cannot
8811 * be distinguished from +command_line+ above, so you must quote or
8812 * escape the entire command name using a shell in platform
8813 * dependent manner, or use the array form below.
8814 *
8815 * If +exe_path+ does not contain any path separator, an executable
8816 * file is searched from directories specified with the +PATH+
8817 * environment variable. What the word "executable" means here is
8818 * depending on platforms.
8819 *
8820 * Even if the file considered "executable", its content may not be
8821 * in proper executable format. In that case, Ruby tries to run it
8822 * by using <tt>/bin/sh</tt> on a Unix-like system, like system(3)
8823 * does.
8824 *
8825 * File.write('shell_command', 'echo $SHELL', perm: 0o755)
8826 * system('./shell_command') # prints "/bin/sh" or something.
8827 *
8828 * - A 2-element array containing the path to an executable
8829 * and the string to be used as the name of the executing process:
8830 *
8831 * Example:
8832 *
8833 * pid = spawn(['sleep', 'Hello!'], '1') # 2-element array.
8834 * p `ps -p #{pid} -o command=`
8835 *
8836 * Output:
8837 *
8838 * "Hello! 1\n"
8839 *
8840 * === Arguments +args+
8841 *
8842 * If +command_line+ does not contain shell meta characters except for
8843 * spaces and tabs, or +exe_path+ is given, Ruby invokes the
8844 * executable directly. This form does not use the shell:
8845 *
8846 * spawn("doesnt_exist") # Raises Errno::ENOENT
8847 * spawn("doesnt_exist", "\n") # Raises Errno::ENOENT
8848 *
8849 * spawn("doesnt_exist\n") # => false
8850 * # sh: 1: doesnot_exist: not found
8851 *
8852 * The error message is from a shell and would vary depending on your
8853 * system.
8854 *
8855 * If one or more +args+ is given after +exe_path+, each is an
8856 * argument or option to be passed to the executable:
8857 *
8858 * Example:
8859 *
8860 * system('echo', '<', 'C*', '|', '$SHELL', '>') # => true
8861 *
8862 * Output:
8863 *
8864 * < C* | $SHELL >
8865 *
8866 * However, there are exceptions on Windows. See {Execution Shell on
8867 * Windows}[rdoc-ref:Process@Execution+Shell+on+Windows].
8868 *
8869 * If you want to invoke a path containing spaces with no arguments
8870 * without shell, you will need to use a 2-element array +exe_path+.
8871 *
8872 * Example:
8873 *
8874 * path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
8875 * spawn(path) # Raises Errno::ENOENT; No such file or directory - /Applications/Google
8876 * spawn([path] * 2)
8877 *
8878 * === Execution Options
8879 *
8880 * Optional trailing argument +options+ is a hash of execution options.
8881 *
8882 * ==== Working Directory (+:chdir+)
8883 *
8884 * By default, the working directory for the new process is the same as
8885 * that of the current process:
8886 *
8887 * Dir.chdir('/var')
8888 * Process.spawn('ruby -e "puts Dir.pwd"')
8889 *
8890 * Output:
8891 *
8892 * /var
8893 *
8894 * Use option +:chdir+ to set the working directory for the new process:
8895 *
8896 * Process.spawn('ruby -e "puts Dir.pwd"', {chdir: '/tmp'})
8897 *
8898 * Output:
8899 *
8900 * /tmp
8901 *
8902 * The working directory of the current process is not changed:
8903 *
8904 * Dir.pwd # => "/var"
8905 *
8906 * ==== \File Redirection (\File Descriptor)
8907 *
8908 * Use execution options for file redirection in the new process.
8909 *
8910 * The key for such an option may be an integer file descriptor (fd),
8911 * specifying a source,
8912 * or an array of fds, specifying multiple sources.
8913 *
8914 * An integer source fd may be specified as:
8915 *
8916 * - _n_: Specifies file descriptor _n_.
8917 *
8918 * There are these shorthand symbols for fds:
8919 *
8920 * - +:in+: Specifies file descriptor 0 (STDIN).
8921 * - +:out+: Specifies file descriptor 1 (STDOUT).
8922 * - +:err+: Specifies file descriptor 2 (STDERR).
8923 *
8924 * The value given with a source is one of:
8925 *
8926 * - _n_:
8927 * Redirects to fd _n_ in the parent process.
8928 * - +filepath+:
8929 * Redirects from or to the file at +filepath+ via <tt>open(filepath, mode, 0644)</tt>,
8930 * where +mode+ is <tt>'r'</tt> for source +:in+,
8931 * or <tt>'w'</tt> for source +:out+ or +:err+.
8932 * - <tt>[filepath]</tt>:
8933 * Redirects from the file at +filepath+ via <tt>open(filepath, 'r', 0644)</tt>.
8934 * - <tt>[filepath, mode]</tt>:
8935 * Redirects from or to the file at +filepath+ via <tt>open(filepath, mode, 0644)</tt>.
8936 * - <tt>[filepath, mode, perm]</tt>:
8937 * Redirects from or to the file at +filepath+ via <tt>open(filepath, mode, perm)</tt>.
8938 * - <tt>[:child, fd]</tt>:
8939 * Redirects to the redirected +fd+.
8940 * - +:close+: Closes the file descriptor in child process.
8941 *
8942 * See {Access Modes}[rdoc-ref:File@Access+Modes]
8943 * and {File Permissions}[rdoc-ref:File@File+Permissions].
8944 *
8945 * ==== Environment Variables (+:unsetenv_others+)
8946 *
8947 * By default, the new process inherits environment variables
8948 * from the parent process;
8949 * use execution option key +:unsetenv_others+ with value +true+
8950 * to clear environment variables in the new process.
8951 *
8952 * Any changes specified by execution option +env+ are made after the new process
8953 * inherits or clears its environment variables;
8954 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
8955 *
8956 * ==== \File-Creation Access (+:umask+)
8957 *
8958 * Use execution option +:umask+ to set the file-creation access
8959 * for the new process;
8960 * see {Access Modes}[rdoc-ref:File@Access+Modes]:
8961 *
8962 * command = 'ruby -e "puts sprintf(\"0%o\", File.umask)"'
8963 * options = {:umask => 0644}
8964 * Process.spawn(command, options)
8965 *
8966 * Output:
8967 *
8968 * 0644
8969 *
8970 * ==== Process Groups (+:pgroup+ and +:new_pgroup+)
8971 *
8972 * By default, the new process belongs to the same
8973 * {process group}[https://en.wikipedia.org/wiki/Process_group]
8974 * as the parent process.
8975 *
8976 * To specify a different process group.
8977 * use execution option +:pgroup+ with one of the following values:
8978 *
8979 * - +true+: Create a new process group for the new process.
8980 * - _pgid_: Create the new process in the process group
8981 * whose id is _pgid_.
8982 *
8983 * On Windows only, use execution option +:new_pgroup+ with value +true+
8984 * to create a new process group for the new process.
8985 *
8986 * ==== Resource Limits
8987 *
8988 * Use execution options to set resource limits.
8989 *
8990 * The keys for these options are symbols of the form
8991 * <tt>:rlimit_<i>resource_name</i></tt>,
8992 * where _resource_name_ is the downcased form of one of the string
8993 * resource names described at method Process.setrlimit.
8994 * For example, key +:rlimit_cpu+ corresponds to resource limit <tt>'CPU'</tt>.
8995 *
8996 * The value for such as key is one of:
8997 *
8998 * - An integer, specifying both the current and maximum limits.
8999 * - A 2-element array of integers, specifying the current and maximum limits.
9000 *
9001 * ==== \File Descriptor Inheritance
9002 *
9003 * By default, the new process inherits file descriptors from the parent process.
9004 *
9005 * Use execution option <tt>:close_others => true</tt> to modify that inheritance
9006 * by closing non-standard fds (3 and greater) that are not otherwise redirected.
9007 *
9008 * === Execution Shell
9009 *
9010 * On a Unix-like system, the shell invoked is <tt>/bin/sh</tt>;
9011 * the entire string +command_line+ is passed as an argument
9012 * to {shell option -c}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/sh.html].
9013 *
9014 * The shell performs normal shell expansion on the command line:
9015 *
9016 * Example:
9017 *
9018 * system('echo $SHELL: C*') # => true
9019 *
9020 * Output:
9021 *
9022 * /bin/bash: CONTRIBUTING.md COPYING COPYING.ja
9023 *
9024 * ==== Execution Shell on Windows
9025 *
9026 * On Windows, the shell invoked is determined by environment variable
9027 * +RUBYSHELL+, if defined, or +COMSPEC+ otherwise; the entire string
9028 * +command_line+ is passed as an argument to <tt>-c</tt> option for
9029 * +RUBYSHELL+, as well as <tt>/bin/sh</tt>, and {/c
9030 * option}[https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd]
9031 * for +COMSPEC+. The shell is invoked automatically in the following
9032 * cases:
9033 *
9034 * - The command is a built-in of +cmd.exe+, such as +echo+.
9035 * - The executable file is a batch file; its name ends with +.bat+ or
9036 * +.cmd+.
9037 *
9038 * Note that the command will still be invoked as +command_line+ form
9039 * even when called in +exe_path+ form, because +cmd.exe+ does not
9040 * accept a script name like <tt>/bin/sh</tt> does but only works with
9041 * <tt>/c</tt> option.
9042 *
9043 * The standard shell +cmd.exe+ performs environment variable
9044 * expansion but does not have globbing functionality:
9045 *
9046 * Example:
9047 *
9048 * system("echo %COMSPEC%: C*")' # => true
9049 *
9050 * Output:
9051 *
9052 * C:\WINDOWS\system32\cmd.exe: C*
9053 *
9054 * == What's Here
9055 *
9056 * === Current-Process Getters
9057 *
9058 * - ::argv0: Returns the process name as a frozen string.
9059 * - ::egid: Returns the effective group ID.
9060 * - ::euid: Returns the effective user ID.
9061 * - ::getpgrp: Return the process group ID.
9062 * - ::getrlimit: Returns the resource limit.
9063 * - ::gid: Returns the (real) group ID.
9064 * - ::pid: Returns the process ID.
9065 * - ::ppid: Returns the process ID of the parent process.
9066 * - ::uid: Returns the (real) user ID.
9067 *
9068 * === Current-Process Setters
9069 *
9070 * - ::egid=: Sets the effective group ID.
9071 * - ::euid=: Sets the effective user ID.
9072 * - ::gid=: Sets the (real) group ID.
9073 * - ::setproctitle: Sets the process title.
9074 * - ::setpgrp: Sets the process group ID of the process to zero.
9075 * - ::setrlimit: Sets a resource limit.
9076 * - ::setsid: Establishes the process as a new session and process group leader,
9077 * with no controlling tty.
9078 * - ::uid=: Sets the user ID.
9079 *
9080 * === Current-Process Execution
9081 *
9082 * - ::abort: Immediately terminates the process.
9083 * - ::daemon: Detaches the process from its controlling terminal
9084 * and continues running it in the background as system daemon.
9085 * - ::exec: Replaces the process by running a given external command.
9086 * - ::exit: Initiates process termination by raising exception SystemExit
9087 * (which may be caught).
9088 * - ::exit!: Immediately exits the process.
9089 * - ::warmup: Notifies the Ruby virtual machine that the boot sequence
9090 * for the application is completed,
9091 * and that the VM may begin optimizing the application.
9092 *
9093 * === Child Processes
9094 *
9095 * - ::detach: Guards against a child process becoming a zombie.
9096 * - ::fork: Creates a child process.
9097 * - ::kill: Sends a given signal to processes.
9098 * - ::spawn: Creates a child process.
9099 * - ::wait, ::waitpid: Waits for a child process to exit; returns its process ID.
9100 * - ::wait2, ::waitpid2: Waits for a child process to exit; returns its process ID and status.
9101 * - ::waitall: Waits for all child processes to exit;
9102 * returns their process IDs and statuses.
9103 *
9104 * === Process Groups
9105 *
9106 * - ::getpgid: Returns the process group ID for a process.
9107 * - ::getpriority: Returns the scheduling priority
9108 * for a process, process group, or user.
9109 * - ::getsid: Returns the session ID for a process.
9110 * - ::groups: Returns an array of the group IDs
9111 * in the supplemental group access list for this process.
9112 * - ::groups=: Sets the supplemental group access list
9113 * to the given array of group IDs.
9114 * - ::initgroups: Initializes the supplemental group access list.
9115 * - ::last_status: Returns the status of the last executed child process
9116 * in the current thread.
9117 * - ::maxgroups: Returns the maximum number of group IDs allowed
9118 * in the supplemental group access list.
9119 * - ::maxgroups=: Sets the maximum number of group IDs allowed
9120 * in the supplemental group access list.
9121 * - ::setpgid: Sets the process group ID of a process.
9122 * - ::setpriority: Sets the scheduling priority
9123 * for a process, process group, or user.
9124 *
9125 * === Timing
9126 *
9127 * - ::clock_getres: Returns the resolution of a system clock.
9128 * - ::clock_gettime: Returns the time from a system clock.
9129 * - ::times: Returns a Process::Tms object containing times
9130 * for the current process and its child processes.
9131 *
9132 */
9133
9134void
9135InitVM_process(void)
9136{
9137 rb_define_virtual_variable("$?", get_CHILD_STATUS, 0);
9138 rb_define_virtual_variable("$$", get_PROCESS_ID, 0);
9139
9140 rb_gvar_ractor_local("$$");
9141 rb_gvar_ractor_local("$?");
9142 rb_gvar_box_ready("$$");
9143 rb_gvar_box_ready("$?");
9144
9145 rb_define_global_function("exec", f_exec, -1);
9146 rb_define_global_function("fork", rb_f_fork, 0);
9147 rb_define_global_function("exit!", rb_f_exit_bang, -1);
9148 rb_define_global_function("system", rb_f_system, -1);
9149 rb_define_global_function("spawn", rb_f_spawn, -1);
9150 rb_define_global_function("sleep", rb_f_sleep, -1);
9151 rb_define_global_function("exit", f_exit, -1);
9152 rb_define_global_function("abort", f_abort, -1);
9153
9154 rb_mProcess = rb_define_module("Process");
9155
9156#ifdef WNOHANG
9157 /* see Process.wait */
9158 rb_define_const(rb_mProcess, "WNOHANG", INT2FIX(WNOHANG));
9159#else
9160 /* see Process.wait */
9161 rb_define_const(rb_mProcess, "WNOHANG", INT2FIX(0));
9162#endif
9163#ifdef WUNTRACED
9164 /* see Process.wait */
9165 rb_define_const(rb_mProcess, "WUNTRACED", INT2FIX(WUNTRACED));
9166#else
9167 /* see Process.wait */
9168 rb_define_const(rb_mProcess, "WUNTRACED", INT2FIX(0));
9169#endif
9170
9171 rb_define_singleton_method(rb_mProcess, "exec", f_exec, -1);
9172 rb_define_singleton_method(rb_mProcess, "fork", rb_f_fork, 0);
9173 rb_define_singleton_method(rb_mProcess, "spawn", rb_f_spawn, -1);
9174 rb_define_singleton_method(rb_mProcess, "exit!", rb_f_exit_bang, -1);
9175 rb_define_singleton_method(rb_mProcess, "exit", f_exit, -1);
9176 rb_define_singleton_method(rb_mProcess, "abort", f_abort, -1);
9177 rb_define_singleton_method(rb_mProcess, "last_status", proc_s_last_status, 0);
9178 rb_define_singleton_method(rb_mProcess, "_fork", rb_proc__fork, 0);
9179
9180 rb_define_module_function(rb_mProcess, "kill", proc_rb_f_kill, -1);
9181 rb_define_module_function(rb_mProcess, "wait", proc_m_wait, -1);
9182 rb_define_module_function(rb_mProcess, "wait2", proc_wait2, -1);
9183 rb_define_module_function(rb_mProcess, "waitpid", proc_m_wait, -1);
9184 rb_define_module_function(rb_mProcess, "waitpid2", proc_wait2, -1);
9185 rb_define_module_function(rb_mProcess, "waitall", proc_waitall, 0);
9186 rb_define_module_function(rb_mProcess, "detach", proc_detach, 1);
9187
9188 /* :nodoc: */
9189 rb_cWaiter = rb_define_class_under(rb_mProcess, "Waiter", rb_cThread);
9190 rb_undef_alloc_func(rb_cWaiter);
9191 rb_undef_method(CLASS_OF(rb_cWaiter), "new");
9192 rb_define_method(rb_cWaiter, "pid", detach_process_pid, 0);
9193
9194 rb_cProcessStatus = rb_define_class_under(rb_mProcess, "Status", rb_cObject);
9195 rb_define_alloc_func(rb_cProcessStatus, rb_process_status_allocate);
9196 rb_undef_method(CLASS_OF(rb_cProcessStatus), "new");
9197 rb_marshal_define_compat(rb_cProcessStatus, rb_cObject,
9198 process_status_dump, process_status_load);
9199
9200 rb_define_singleton_method(rb_cProcessStatus, "wait", rb_process_status_waitv, -1);
9201
9202 rb_define_method(rb_cProcessStatus, "==", pst_equal, 1);
9203 rb_define_method(rb_cProcessStatus, "to_i", pst_to_i, 0);
9204 rb_define_method(rb_cProcessStatus, "to_s", pst_to_s, 0);
9205 rb_define_method(rb_cProcessStatus, "inspect", pst_inspect, 0);
9206
9207 rb_define_method(rb_cProcessStatus, "pid", pst_pid_m, 0);
9208
9209 rb_define_method(rb_cProcessStatus, "stopped?", pst_wifstopped, 0);
9210 rb_define_method(rb_cProcessStatus, "stopsig", pst_wstopsig, 0);
9211 rb_define_method(rb_cProcessStatus, "signaled?", pst_wifsignaled, 0);
9212 rb_define_method(rb_cProcessStatus, "termsig", pst_wtermsig, 0);
9213 rb_define_method(rb_cProcessStatus, "exited?", pst_wifexited, 0);
9214 rb_define_method(rb_cProcessStatus, "exitstatus", pst_wexitstatus, 0);
9215 rb_define_method(rb_cProcessStatus, "success?", pst_success_p, 0);
9216 rb_define_method(rb_cProcessStatus, "coredump?", pst_wcoredump, 0);
9217
9218 rb_define_module_function(rb_mProcess, "pid", proc_get_pid, 0);
9219 rb_define_module_function(rb_mProcess, "ppid", proc_get_ppid, 0);
9220
9221 rb_define_module_function(rb_mProcess, "getpgrp", proc_getpgrp, 0);
9222 rb_define_module_function(rb_mProcess, "setpgrp", proc_setpgrp, 0);
9223 rb_define_module_function(rb_mProcess, "getpgid", proc_getpgid, 1);
9224 rb_define_module_function(rb_mProcess, "setpgid", proc_setpgid, 2);
9225
9226 rb_define_module_function(rb_mProcess, "getsid", proc_getsid, -1);
9227 rb_define_module_function(rb_mProcess, "setsid", proc_setsid, 0);
9228
9229 rb_define_module_function(rb_mProcess, "getpriority", proc_getpriority, 2);
9230 rb_define_module_function(rb_mProcess, "setpriority", proc_setpriority, 3);
9231
9232 rb_define_module_function(rb_mProcess, "warmup", proc_warmup, 0);
9233
9234#ifdef HAVE_GETPRIORITY
9235 /* see Process.setpriority */
9236 rb_define_const(rb_mProcess, "PRIO_PROCESS", INT2FIX(PRIO_PROCESS));
9237 /* see Process.setpriority */
9238 rb_define_const(rb_mProcess, "PRIO_PGRP", INT2FIX(PRIO_PGRP));
9239 /* see Process.setpriority */
9240 rb_define_const(rb_mProcess, "PRIO_USER", INT2FIX(PRIO_USER));
9241#endif
9242
9243 rb_define_module_function(rb_mProcess, "getrlimit", proc_getrlimit, 1);
9244 rb_define_module_function(rb_mProcess, "setrlimit", proc_setrlimit, -1);
9245#if defined(RLIM2NUM) && defined(RLIM_INFINITY)
9246 {
9247 VALUE inf = RLIM2NUM(RLIM_INFINITY);
9248#ifdef RLIM_SAVED_MAX
9249 {
9250 VALUE v = RLIM_INFINITY == RLIM_SAVED_MAX ? inf : RLIM2NUM(RLIM_SAVED_MAX);
9251 /* see Process.setrlimit */
9252 rb_define_const(rb_mProcess, "RLIM_SAVED_MAX", v);
9253 }
9254#endif
9255 /* see Process.setrlimit */
9256 rb_define_const(rb_mProcess, "RLIM_INFINITY", inf);
9257#ifdef RLIM_SAVED_CUR
9258 {
9259 VALUE v = RLIM_INFINITY == RLIM_SAVED_CUR ? inf : RLIM2NUM(RLIM_SAVED_CUR);
9260 /* see Process.setrlimit */
9261 rb_define_const(rb_mProcess, "RLIM_SAVED_CUR", v);
9262 }
9263#endif
9264 }
9265#ifdef RLIMIT_AS
9266 /* Maximum size of the process's virtual memory (address space) in bytes.
9267 *
9268 * see the system getrlimit(2) manual for details.
9269 */
9270 rb_define_const(rb_mProcess, "RLIMIT_AS", INT2FIX(RLIMIT_AS));
9271#endif
9272#ifdef RLIMIT_CORE
9273 /* Maximum size of the core file.
9274 *
9275 * see the system getrlimit(2) manual for details.
9276 */
9277 rb_define_const(rb_mProcess, "RLIMIT_CORE", INT2FIX(RLIMIT_CORE));
9278#endif
9279#ifdef RLIMIT_CPU
9280 /* CPU time limit in seconds.
9281 *
9282 * see the system getrlimit(2) manual for details.
9283 */
9284 rb_define_const(rb_mProcess, "RLIMIT_CPU", INT2FIX(RLIMIT_CPU));
9285#endif
9286#ifdef RLIMIT_DATA
9287 /* Maximum size of the process's data segment.
9288 *
9289 * see the system getrlimit(2) manual for details.
9290 */
9291 rb_define_const(rb_mProcess, "RLIMIT_DATA", INT2FIX(RLIMIT_DATA));
9292#endif
9293#ifdef RLIMIT_FSIZE
9294 /* Maximum size of files that the process may create.
9295 *
9296 * see the system getrlimit(2) manual for details.
9297 */
9298 rb_define_const(rb_mProcess, "RLIMIT_FSIZE", INT2FIX(RLIMIT_FSIZE));
9299#endif
9300#ifdef RLIMIT_MEMLOCK
9301 /* Maximum number of bytes of memory that may be locked into RAM.
9302 *
9303 * see the system getrlimit(2) manual for details.
9304 */
9305 rb_define_const(rb_mProcess, "RLIMIT_MEMLOCK", INT2FIX(RLIMIT_MEMLOCK));
9306#endif
9307#ifdef RLIMIT_MSGQUEUE
9308 /* Specifies the limit on the number of bytes that can be allocated
9309 * for POSIX message queues for the real user ID of the calling process.
9310 *
9311 * see the system getrlimit(2) manual for details.
9312 */
9313 rb_define_const(rb_mProcess, "RLIMIT_MSGQUEUE", INT2FIX(RLIMIT_MSGQUEUE));
9314#endif
9315#ifdef RLIMIT_NICE
9316 /* Specifies a ceiling to which the process's nice value can be raised.
9317 *
9318 * see the system getrlimit(2) manual for details.
9319 */
9320 rb_define_const(rb_mProcess, "RLIMIT_NICE", INT2FIX(RLIMIT_NICE));
9321#endif
9322#ifdef RLIMIT_NOFILE
9323 /* Specifies a value one greater than the maximum file descriptor
9324 * number that can be opened by this process.
9325 *
9326 * see the system getrlimit(2) manual for details.
9327 */
9328 rb_define_const(rb_mProcess, "RLIMIT_NOFILE", INT2FIX(RLIMIT_NOFILE));
9329#endif
9330#ifdef RLIMIT_NPROC
9331 /* The maximum number of processes that can be created for the
9332 * real user ID of the calling process.
9333 *
9334 * see the system getrlimit(2) manual for details.
9335 */
9336 rb_define_const(rb_mProcess, "RLIMIT_NPROC", INT2FIX(RLIMIT_NPROC));
9337#endif
9338#ifdef RLIMIT_NPTS
9339 /* The maximum number of pseudo-terminals that can be created for the
9340 * real user ID of the calling process.
9341 *
9342 * see the system getrlimit(2) manual for details.
9343 */
9344 rb_define_const(rb_mProcess, "RLIMIT_NPTS", INT2FIX(RLIMIT_NPTS));
9345#endif
9346#ifdef RLIMIT_RSS
9347 /* Specifies the limit (in pages) of the process's resident set.
9348 *
9349 * see the system getrlimit(2) manual for details.
9350 */
9351 rb_define_const(rb_mProcess, "RLIMIT_RSS", INT2FIX(RLIMIT_RSS));
9352#endif
9353#ifdef RLIMIT_RTPRIO
9354 /* Specifies a ceiling on the real-time priority that may be set for this process.
9355 *
9356 * see the system getrlimit(2) manual for details.
9357 */
9358 rb_define_const(rb_mProcess, "RLIMIT_RTPRIO", INT2FIX(RLIMIT_RTPRIO));
9359#endif
9360#ifdef RLIMIT_RTTIME
9361 /* Specifies limit on CPU time this process scheduled under a real-time
9362 * scheduling policy can consume.
9363 *
9364 * see the system getrlimit(2) manual for details.
9365 */
9366 rb_define_const(rb_mProcess, "RLIMIT_RTTIME", INT2FIX(RLIMIT_RTTIME));
9367#endif
9368#ifdef RLIMIT_SBSIZE
9369 /* Maximum size of the socket buffer.
9370 */
9371 rb_define_const(rb_mProcess, "RLIMIT_SBSIZE", INT2FIX(RLIMIT_SBSIZE));
9372#endif
9373#ifdef RLIMIT_SIGPENDING
9374 /* Specifies a limit on the number of signals that may be queued for
9375 * the real user ID of the calling process.
9376 *
9377 * see the system getrlimit(2) manual for details.
9378 */
9379 rb_define_const(rb_mProcess, "RLIMIT_SIGPENDING", INT2FIX(RLIMIT_SIGPENDING));
9380#endif
9381#ifdef RLIMIT_STACK
9382 /* Maximum size of the stack, in bytes.
9383 *
9384 * see the system getrlimit(2) manual for details.
9385 */
9386 rb_define_const(rb_mProcess, "RLIMIT_STACK", INT2FIX(RLIMIT_STACK));
9387#endif
9388#endif
9389
9390 rb_define_module_function(rb_mProcess, "uid", proc_getuid, 0);
9391 rb_define_module_function(rb_mProcess, "uid=", proc_setuid, 1);
9392 rb_define_module_function(rb_mProcess, "gid", proc_getgid, 0);
9393 rb_define_module_function(rb_mProcess, "gid=", proc_setgid, 1);
9394 rb_define_module_function(rb_mProcess, "euid", proc_geteuid, 0);
9395 rb_define_module_function(rb_mProcess, "euid=", proc_seteuid_m, 1);
9396 rb_define_module_function(rb_mProcess, "egid", proc_getegid, 0);
9397 rb_define_module_function(rb_mProcess, "egid=", proc_setegid_m, 1);
9398 rb_define_module_function(rb_mProcess, "initgroups", proc_initgroups, 2);
9399 rb_define_module_function(rb_mProcess, "groups", proc_getgroups, 0);
9400 rb_define_module_function(rb_mProcess, "groups=", proc_setgroups, 1);
9401 rb_define_module_function(rb_mProcess, "maxgroups", proc_getmaxgroups, 0);
9402 rb_define_module_function(rb_mProcess, "maxgroups=", proc_setmaxgroups, 1);
9403
9404 rb_define_module_function(rb_mProcess, "daemon", proc_daemon, -1);
9405
9406 rb_define_module_function(rb_mProcess, "times", rb_proc_times, 0);
9407
9408#if defined(RUBY_CLOCK_REALTIME)
9409#elif defined(RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME)
9410# define RUBY_CLOCK_REALTIME RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME
9411#elif defined(RUBY_TIME_BASED_CLOCK_REALTIME)
9412# define RUBY_CLOCK_REALTIME RUBY_TIME_BASED_CLOCK_REALTIME
9413#endif
9414#if defined(CLOCK_REALTIME) && defined(CLOCKID2NUM)
9415 /* see Process.clock_gettime */
9416 rb_define_const(rb_mProcess, "CLOCK_REALTIME", CLOCKID2NUM(CLOCK_REALTIME));
9417#elif defined(RUBY_CLOCK_REALTIME)
9418 rb_define_const(rb_mProcess, "CLOCK_REALTIME", RUBY_CLOCK_REALTIME);
9419#endif
9420
9421#if defined(RUBY_CLOCK_MONOTONIC)
9422#elif defined(RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC)
9423# define RUBY_CLOCK_MONOTONIC RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
9424#endif
9425#if defined(CLOCK_MONOTONIC) && defined(CLOCKID2NUM)
9426 /* see Process.clock_gettime */
9427 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC", CLOCKID2NUM(CLOCK_MONOTONIC));
9428#elif defined(RUBY_CLOCK_MONOTONIC)
9429 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC", RUBY_CLOCK_MONOTONIC);
9430#endif
9431
9432#if defined(RUBY_CLOCK_PROCESS_CPUTIME_ID)
9433#elif defined(RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID)
9434# define RUBY_CLOCK_PROCESS_CPUTIME_ID RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
9435#endif
9436#if defined(CLOCK_PROCESS_CPUTIME_ID) && defined(CLOCKID2NUM)
9437 /* see Process.clock_gettime */
9438 rb_define_const(rb_mProcess, "CLOCK_PROCESS_CPUTIME_ID", CLOCKID2NUM(CLOCK_PROCESS_CPUTIME_ID));
9439#elif defined(RUBY_CLOCK_PROCESS_CPUTIME_ID)
9440 rb_define_const(rb_mProcess, "CLOCK_PROCESS_CPUTIME_ID", RUBY_CLOCK_PROCESS_CPUTIME_ID);
9441#endif
9442
9443#if defined(CLOCK_THREAD_CPUTIME_ID) && defined(CLOCKID2NUM)
9444 /* see Process.clock_gettime */
9445 rb_define_const(rb_mProcess, "CLOCK_THREAD_CPUTIME_ID", CLOCKID2NUM(CLOCK_THREAD_CPUTIME_ID));
9446#elif defined(RUBY_CLOCK_THREAD_CPUTIME_ID)
9447 rb_define_const(rb_mProcess, "CLOCK_THREAD_CPUTIME_ID", RUBY_CLOCK_THREAD_CPUTIME_ID);
9448#endif
9449
9450#ifdef CLOCKID2NUM
9451#ifdef CLOCK_VIRTUAL
9452 /* see Process.clock_gettime */
9453 rb_define_const(rb_mProcess, "CLOCK_VIRTUAL", CLOCKID2NUM(CLOCK_VIRTUAL));
9454#endif
9455#ifdef CLOCK_PROF
9456 /* see Process.clock_gettime */
9457 rb_define_const(rb_mProcess, "CLOCK_PROF", CLOCKID2NUM(CLOCK_PROF));
9458#endif
9459#ifdef CLOCK_REALTIME_FAST
9460 /* see Process.clock_gettime */
9461 rb_define_const(rb_mProcess, "CLOCK_REALTIME_FAST", CLOCKID2NUM(CLOCK_REALTIME_FAST));
9462#endif
9463#ifdef CLOCK_REALTIME_PRECISE
9464 /* see Process.clock_gettime */
9465 rb_define_const(rb_mProcess, "CLOCK_REALTIME_PRECISE", CLOCKID2NUM(CLOCK_REALTIME_PRECISE));
9466#endif
9467#ifdef CLOCK_REALTIME_COARSE
9468 /* see Process.clock_gettime */
9469 rb_define_const(rb_mProcess, "CLOCK_REALTIME_COARSE", CLOCKID2NUM(CLOCK_REALTIME_COARSE));
9470#endif
9471#ifdef CLOCK_REALTIME_ALARM
9472 /* see Process.clock_gettime */
9473 rb_define_const(rb_mProcess, "CLOCK_REALTIME_ALARM", CLOCKID2NUM(CLOCK_REALTIME_ALARM));
9474#endif
9475#ifdef CLOCK_MONOTONIC_FAST
9476 /* see Process.clock_gettime */
9477 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_FAST", CLOCKID2NUM(CLOCK_MONOTONIC_FAST));
9478#endif
9479#ifdef CLOCK_MONOTONIC_PRECISE
9480 /* see Process.clock_gettime */
9481 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_PRECISE", CLOCKID2NUM(CLOCK_MONOTONIC_PRECISE));
9482#endif
9483#ifdef CLOCK_MONOTONIC_RAW
9484 /* see Process.clock_gettime */
9485 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_RAW", CLOCKID2NUM(CLOCK_MONOTONIC_RAW));
9486#endif
9487#ifdef CLOCK_MONOTONIC_RAW_APPROX
9488 /* see Process.clock_gettime */
9489 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_RAW_APPROX", CLOCKID2NUM(CLOCK_MONOTONIC_RAW_APPROX));
9490#endif
9491#ifdef CLOCK_MONOTONIC_COARSE
9492 /* see Process.clock_gettime */
9493 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_COARSE", CLOCKID2NUM(CLOCK_MONOTONIC_COARSE));
9494#endif
9495#ifdef CLOCK_BOOTTIME
9496 /* see Process.clock_gettime */
9497 rb_define_const(rb_mProcess, "CLOCK_BOOTTIME", CLOCKID2NUM(CLOCK_BOOTTIME));
9498#endif
9499#ifdef CLOCK_BOOTTIME_ALARM
9500 /* see Process.clock_gettime */
9501 rb_define_const(rb_mProcess, "CLOCK_BOOTTIME_ALARM", CLOCKID2NUM(CLOCK_BOOTTIME_ALARM));
9502#endif
9503#ifdef CLOCK_UPTIME
9504 /* see Process.clock_gettime */
9505 rb_define_const(rb_mProcess, "CLOCK_UPTIME", CLOCKID2NUM(CLOCK_UPTIME));
9506#endif
9507#ifdef CLOCK_UPTIME_FAST
9508 /* see Process.clock_gettime */
9509 rb_define_const(rb_mProcess, "CLOCK_UPTIME_FAST", CLOCKID2NUM(CLOCK_UPTIME_FAST));
9510#endif
9511#ifdef CLOCK_UPTIME_PRECISE
9512 /* see Process.clock_gettime */
9513 rb_define_const(rb_mProcess, "CLOCK_UPTIME_PRECISE", CLOCKID2NUM(CLOCK_UPTIME_PRECISE));
9514#endif
9515#ifdef CLOCK_UPTIME_RAW
9516 /* see Process.clock_gettime */
9517 rb_define_const(rb_mProcess, "CLOCK_UPTIME_RAW", CLOCKID2NUM(CLOCK_UPTIME_RAW));
9518#endif
9519#ifdef CLOCK_UPTIME_RAW_APPROX
9520 /* see Process.clock_gettime */
9521 rb_define_const(rb_mProcess, "CLOCK_UPTIME_RAW_APPROX", CLOCKID2NUM(CLOCK_UPTIME_RAW_APPROX));
9522#endif
9523#ifdef CLOCK_SECOND
9524 /* see Process.clock_gettime */
9525 rb_define_const(rb_mProcess, "CLOCK_SECOND", CLOCKID2NUM(CLOCK_SECOND));
9526#endif
9527#ifdef CLOCK_TAI
9528 /* see Process.clock_gettime */
9529 rb_define_const(rb_mProcess, "CLOCK_TAI", CLOCKID2NUM(CLOCK_TAI));
9530#endif
9531#endif
9532 rb_define_module_function(rb_mProcess, "clock_gettime", rb_clock_gettime, -1);
9533 rb_define_module_function(rb_mProcess, "clock_getres", rb_clock_getres, -1);
9534
9535#if defined(HAVE_TIMES)
9536 rb_cProcessTms = rb_struct_define_under(rb_mProcess, "Tms", "utime", "stime", "cutime", "cstime", NULL);
9537#if 0 /* for RDoc */
9538 /* user time used in this process */
9539 rb_define_attr(rb_cProcessTms, "utime", TRUE, TRUE);
9540 /* system time used in this process */
9541 rb_define_attr(rb_cProcessTms, "stime", TRUE, TRUE);
9542 /* user time used in the child processes */
9543 rb_define_attr(rb_cProcessTms, "cutime", TRUE, TRUE);
9544 /* system time used in the child processes */
9545 rb_define_attr(rb_cProcessTms, "cstime", TRUE, TRUE);
9546#endif
9547#endif
9548
9549 SAVED_USER_ID = geteuid();
9550 SAVED_GROUP_ID = getegid();
9551
9552 rb_mProcUID = rb_define_module_under(rb_mProcess, "UID");
9553 rb_mProcGID = rb_define_module_under(rb_mProcess, "GID");
9554
9555 rb_define_module_function(rb_mProcUID, "rid", proc_getuid, 0);
9556 rb_define_module_function(rb_mProcGID, "rid", proc_getgid, 0);
9557 rb_define_module_function(rb_mProcUID, "eid", proc_geteuid, 0);
9558 rb_define_module_function(rb_mProcGID, "eid", proc_getegid, 0);
9559 rb_define_module_function(rb_mProcUID, "change_privilege", p_uid_change_privilege, 1);
9560 rb_define_module_function(rb_mProcGID, "change_privilege", p_gid_change_privilege, 1);
9561 rb_define_module_function(rb_mProcUID, "grant_privilege", p_uid_grant_privilege, 1);
9562 rb_define_module_function(rb_mProcGID, "grant_privilege", p_gid_grant_privilege, 1);
9563 rb_define_alias(rb_singleton_class(rb_mProcUID), "eid=", "grant_privilege");
9564 rb_define_alias(rb_singleton_class(rb_mProcGID), "eid=", "grant_privilege");
9565 rb_define_module_function(rb_mProcUID, "re_exchange", p_uid_exchange, 0);
9566 rb_define_module_function(rb_mProcGID, "re_exchange", p_gid_exchange, 0);
9567 rb_define_module_function(rb_mProcUID, "re_exchangeable?", p_uid_exchangeable, 0);
9568 rb_define_module_function(rb_mProcGID, "re_exchangeable?", p_gid_exchangeable, 0);
9569 rb_define_module_function(rb_mProcUID, "sid_available?", p_uid_have_saved_id, 0);
9570 rb_define_module_function(rb_mProcGID, "sid_available?", p_gid_have_saved_id, 0);
9571 rb_define_module_function(rb_mProcUID, "switch", p_uid_switch, 0);
9572 rb_define_module_function(rb_mProcGID, "switch", p_gid_switch, 0);
9573#ifdef p_uid_from_name
9574 rb_define_module_function(rb_mProcUID, "from_name", p_uid_from_name, 1);
9575#endif
9576#ifdef p_gid_from_name
9577 rb_define_module_function(rb_mProcGID, "from_name", p_gid_from_name, 1);
9578#endif
9579
9580 rb_mProcID_Syscall = rb_define_module_under(rb_mProcess, "Sys");
9581
9582 rb_define_module_function(rb_mProcID_Syscall, "getuid", proc_getuid, 0);
9583 rb_define_module_function(rb_mProcID_Syscall, "geteuid", proc_geteuid, 0);
9584 rb_define_module_function(rb_mProcID_Syscall, "getgid", proc_getgid, 0);
9585 rb_define_module_function(rb_mProcID_Syscall, "getegid", proc_getegid, 0);
9586
9587 rb_define_module_function(rb_mProcID_Syscall, "setuid", p_sys_setuid, 1);
9588 rb_define_module_function(rb_mProcID_Syscall, "setgid", p_sys_setgid, 1);
9589
9590 rb_define_module_function(rb_mProcID_Syscall, "setruid", p_sys_setruid, 1);
9591 rb_define_module_function(rb_mProcID_Syscall, "setrgid", p_sys_setrgid, 1);
9592
9593 rb_define_module_function(rb_mProcID_Syscall, "seteuid", p_sys_seteuid, 1);
9594 rb_define_module_function(rb_mProcID_Syscall, "setegid", p_sys_setegid, 1);
9595
9596 rb_define_module_function(rb_mProcID_Syscall, "setreuid", p_sys_setreuid, 2);
9597 rb_define_module_function(rb_mProcID_Syscall, "setregid", p_sys_setregid, 2);
9598
9599 rb_define_module_function(rb_mProcID_Syscall, "setresuid", p_sys_setresuid, 3);
9600 rb_define_module_function(rb_mProcID_Syscall, "setresgid", p_sys_setresgid, 3);
9601 rb_define_module_function(rb_mProcID_Syscall, "issetugid", p_sys_issetugid, 0);
9602}
9603
9604void
9605Init_process(void)
9606{
9607#define define_id(name) id_##name = rb_intern_const(#name)
9608 define_id(in);
9609 define_id(out);
9610 define_id(err);
9611 define_id(pid);
9612 define_id(uid);
9613 define_id(gid);
9614 define_id(close);
9615 define_id(child);
9616#ifdef HAVE_SETPGID
9617 define_id(pgroup);
9618#endif
9619#ifdef _WIN32
9620 define_id(new_pgroup);
9621#endif
9622 define_id(unsetenv_others);
9623 define_id(chdir);
9624 define_id(umask);
9625 define_id(close_others);
9626 define_id(nanosecond);
9627 define_id(microsecond);
9628 define_id(millisecond);
9629 define_id(second);
9630 define_id(float_microsecond);
9631 define_id(float_millisecond);
9632 define_id(float_second);
9633 define_id(GETTIMEOFDAY_BASED_CLOCK_REALTIME);
9634 define_id(TIME_BASED_CLOCK_REALTIME);
9635#ifdef CLOCK_REALTIME
9636 define_id(CLOCK_REALTIME);
9637#endif
9638#ifdef CLOCK_MONOTONIC
9639 define_id(CLOCK_MONOTONIC);
9640#endif
9641#ifdef CLOCK_PROCESS_CPUTIME_ID
9642 define_id(CLOCK_PROCESS_CPUTIME_ID);
9643#endif
9644#ifdef CLOCK_THREAD_CPUTIME_ID
9645 define_id(CLOCK_THREAD_CPUTIME_ID);
9646#endif
9647#ifdef HAVE_TIMES
9648 define_id(TIMES_BASED_CLOCK_MONOTONIC);
9649 define_id(TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID);
9650#endif
9651#ifdef RUSAGE_SELF
9652 define_id(GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID);
9653#endif
9654 define_id(CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID);
9655#ifdef __APPLE__
9656 define_id(MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC);
9657#endif
9658 define_id(hertz);
9659#ifdef HAVE_WORKING_FORK
9660 define_id(_fork);
9661#endif
9662
9663 InitVM(process);
9664}
#define LONG_LONG
Definition long_long.h:38
#define ISUPPER
@old{rb_isupper}
Definition ctype.h:89
#define TOUPPER
@old{rb_toupper}
Definition ctype.h:100
#define ISLOWER
@old{rb_islower}
Definition ctype.h:90
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_module_function(klass, mid, func, arity)
Defines klass#mid and makes it a module function.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define PATH_ENV
Definition dosish.h:63
#define GIDT2NUM
Converts a C's gid_t into an instance of rb_cInteger.
Definition gid_t.h:28
#define NUM2GIDT
Converts an instance of rb_cNumeric into C's gid_t.
Definition gid_t.h:33
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3025
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3068
void rb_define_attr(VALUE klass, const char *name, int read, int write)
Defines public accessor method(s) for an attribute.
Definition class.c:3074
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2871
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1041
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1707
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:307
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1467
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:4053
VALUE rb_eSystemExit
SystemExit exception.
Definition error.c:1450
#define rb_notimplement()
Definition flock.c:3
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:4059
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition error.c:1443
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1508
void rb_unexpected_type(VALUE x, int t)
Fails with the given object's type incompatibility to the type.
Definition error.c:1412
void rb_exit(int status)
Terminates the current execution context.
Definition process.c:4321
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_mProcess
Process module.
Definition process.c:8670
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2305
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_cThread
Thread class.
Definition vm.c:719
VALUE rb_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1305
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3337
Scheduler APIs.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:581
VALUE rb_fiber_scheduler_kernel_sleepv(VALUE scheduler, int argc, VALUE *argv)
Identical to rb_fiber_scheduler_kernel_sleep(), except it can pass multiple arguments.
Definition scheduler.c:659
VALUE rb_fiber_scheduler_process_wait(VALUE scheduler, rb_pid_t pid, int flags)
Non-blocking waitpid.
Definition scheduler.c:746
VALUE rb_str_export_to_enc(VALUE obj, rb_encoding *enc)
Identical to rb_str_export(), except it additionally takes an encoding.
Definition string.c:1498
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1149
int rb_during_gc(void)
Queries if the GC is busy.
Definition gc.c:5703
void rb_gc(void)
Triggers a GC process.
Definition gc.c:5695
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_f_abort(int argc, const VALUE *argv)
This is similar to rb_f_exit().
Definition process.c:4403
VALUE rb_f_exit(int argc, const VALUE *argv)
Identical to rb_exit(), except how arguments are passed.
Definition process.c:4334
VALUE rb_env_clear(void)
Destructively removes every environment variables of the running process.
Definition hash.c:6518
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1646
int rb_cloexec_dup2(int oldfd, int newfd)
Identical to rb_cloexec_dup(), except you can specify the destination file descriptor.
Definition io.c:376
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:274
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:337
void rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
Closes everything.
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
int rb_pipe(int *pipes)
This is an rb_cloexec_pipe() + rb_update_max_fd() combo.
Definition io.c:7650
int rb_cloexec_fcntl_dupfd(int fd, int minfd)
Duplicates a file descriptor with closing on exec.
Definition io.c:484
int rb_cloexec_dup(int oldfd)
Identical to rb_cloexec_fcntl_dupfd(), except it implies minfd is 3.
Definition io.c:369
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:139
int rb_proc_exec(const char *cmd)
Executes a shell command.
Definition process.c:1690
VALUE rb_last_status_get(void)
Queries the "last status", or the $?.
Definition process.c:605
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
Definition process.c:1161
VALUE rb_process_status_for(rb_pid_t pid, int status, int error)
Returns the Ruby value representing a waitpid(2) outcome.
Definition process.c:639
rb_pid_t rb_spawn_err(int argc, const VALUE *argv, char *errbuf, size_t buflen)
Identical to rb_spawn(), except you can additionally know the detailed situation in case of abnormal ...
Definition process.c:4581
void rb_syswait(rb_pid_t pid)
This is a shorthand of rb_waitpid without status and flags.
Definition process.c:4451
VALUE rb_f_exec(int argc, const VALUE *argv)
Replaces the current process by running the given external command.
Definition process.c:2862
rb_pid_t rb_spawn(int argc, const VALUE *argv)
Identical to rb_f_exec(), except it spawns a child process instead of replacing the current one.
Definition process.c:4587
VALUE rb_process_status_wait(rb_pid_t pid, int flags)
Wait for the specified process to terminate, reap it, and return its status.
Definition process.c:1089
void rb_last_status_set(int status, rb_pid_t pid)
Sets the "last status", or the $?.
Definition process.c:676
VALUE rb_detach_process(rb_pid_t pid)
"Detaches" a subprocess.
Definition process.c:1445
const char * ruby_signal_name(int signo)
Queries the name of the signal.
Definition signal.c:318
VALUE rb_f_kill(int argc, const VALUE *argv)
Sends a signal ("kills") to processes.
Definition signal.c:429
void rb_str_modify_expand(VALUE str, rb_len_t capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2838
VALUE rb_str_subseq(VALUE str, rb_len_t beg, rb_len_t len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3288
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3940
VALUE rb_str_tmp_new(rb_len_t len)
Allocates a "temporary" string.
Definition string.c:1811
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1706
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1037
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1569
void rb_str_set_len(VALUE str, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3522
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2052
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1783
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3069
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_struct_define_under(VALUE space, const char *name,...)
Identical to rb_struct_define(), except it defines the class under the specified namespace instead of...
Definition struct.c:532
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition struct.c:935
VALUE rb_thread_local_aref(VALUE thread, ID key)
This badly named function reads from a Fiber local storage.
Definition thread.c:4082
#define RUBY_UBF_IO
A special UBF for blocking IO operations.
Definition thread.h:382
void rb_thread_sleep_forever(void)
Blocks indefinitely.
Definition thread.c:1592
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
Definition thread.c:1625
void rb_thread_check_ints(void)
Checks for interrupts.
Definition thread.c:1646
void rb_thread_atfork(void)
A pthread_atfork(3posix)-like API.
Definition thread.c:5429
VALUE rb_thread_local_aset(VALUE thread, ID key, VALUE val)
This badly named function writes to a Fiber local storage.
Definition thread.c:4230
#define RUBY_UBF_PROCESS
A special UBF for blocking process operations.
Definition thread.h:389
void rb_thread_sleep(int sec)
Blocks for the given period of time.
Definition thread.c:1669
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2984
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2168
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1893
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well... Let us hesitate from describing what a "basic definition" is.
Definition vm_method.c:3621
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1296
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1155
int rb_io_modestr_oflags(const char *modestr)
Identical to rb_io_modestr_fmode(), except it returns a mixture of O_ flags.
Definition io.c:6868
#define GetOpenFile
This is an old name of RB_IO_POINTER.
Definition io.h:442
VALUE rb_io_check_io(VALUE io)
Try converting an object to its IO representation using its to_io method, if any.
Definition io.c:827
int len
Length of the buffer.
Definition io.h:8
VALUE rb_ractor_stderr(void)
Queries the standard error of the current Ractor that is calling this function.
Definition ractor.c:1520
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Identical to rb_thread_call_without_gvl(), except it does not interface with signals etc.
Definition thread.c:1925
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Allows the passed function to run in parallel with other Ruby threads.
Definition thread.c:1932
#define RB_NUM2INT
Just another name of rb_num2int_inline.
Definition int.h:38
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1404
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
Definition mode_t.h:28
VALUE rb_thread_create(type *q, void *w)
Creates a rb_cThread instance.
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define PIDT2NUM
Converts a C's pid_t into an instance of rb_cInteger.
Definition pid_t.h:28
#define NUM2PIDT
Converts an instance of rb_cNumeric into C's pid_t.
Definition pid_t.h:33
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:422
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:386
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:56
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:57
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:67
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition variable.c:523
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
Defines old _.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
VALUE tied_io_for_writing
Duplex IO object, if set.
Definition io.h:345
int fd
file descriptor.
Definition io.h:306
Definition win32.h:676
#define UIDT2NUM
Converts a C's uid_t into an instance of rb_cInteger.
Definition uid_t.h:28
#define NUM2UIDT
Converts an instance of rb_cNumeric into C's uid_t.
Definition uid_t.h:33
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:425
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376