This source file includes following definitions.
- dup_noinherit
- fd_safer_noinherit
- dup_safer_noinherit
- undup_safer_noinherit
- prepare_spawn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 #include <config.h>
19
20
21 #include "os2-spawn.h"
22
23
24 #include <io.h>
25
26 #include <stdbool.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <errno.h>
31
32 #include "cloexec.h"
33 #include "error.h"
34 #include "gettext.h"
35
36 #define _(str) gettext (str)
37
38
39
40
41 static int
42 dup_noinherit (int fd)
43 {
44 fd = dup_cloexec (fd);
45 if (fd < 0 && errno == EMFILE)
46 error (EXIT_FAILURE, errno, _("_open_osfhandle failed"));
47
48 return fd;
49 }
50
51
52
53
54
55
56 static int
57 fd_safer_noinherit (int fd)
58 {
59 if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
60 {
61
62 int nfd = fd_safer_noinherit (dup_noinherit (fd));
63 int saved_errno = errno;
64 close (fd);
65 errno = saved_errno;
66 return nfd;
67 }
68 return fd;
69 }
70
71 int
72 dup_safer_noinherit (int fd)
73 {
74 return fd_safer_noinherit (dup_noinherit (fd));
75 }
76
77 void
78 undup_safer_noinherit (int tempfd, int origfd)
79 {
80 if (tempfd >= 0)
81 {
82 if (dup2 (tempfd, origfd) < 0)
83 error (EXIT_FAILURE, errno, _("cannot restore fd %d: dup2 failed"),
84 origfd);
85 close (tempfd);
86 }
87 else
88 {
89
90
91 close (origfd);
92 }
93 }
94
95 const char **
96 prepare_spawn (const char * const *argv, char **mem_to_free)
97 {
98 size_t argc;
99 const char **new_argv;
100 size_t i;
101
102
103 for (argc = 0; argv[argc] != NULL; argc++)
104 ;
105
106
107 new_argv = (const char **) malloc ((1 + argc + 1) * sizeof (const char *));
108 if (new_argv == NULL)
109 return NULL;
110
111
112
113
114 new_argv[0] = "sh.exe";
115
116
117 size_t needed_size = 0;
118 for (i = 0; i < argc; i++)
119 {
120 const char *string = argv[i];
121 const char *quoted_string = (string[0] == '\0' ? "\"\"" : string);
122 size_t length = strlen (quoted_string);
123 needed_size += length + 1;
124 }
125
126 char *mem;
127 if (needed_size == 0)
128 mem = NULL;
129 else
130 {
131 mem = (char *) malloc (needed_size);
132 if (mem == NULL)
133 {
134
135 free (new_argv);
136 errno = ENOMEM;
137 return NULL;
138 }
139 }
140 *mem_to_free = mem;
141
142 for (i = 0; i < argc; i++)
143 {
144 const char *string = argv[i];
145
146 new_argv[1 + i] = mem;
147 const char *quoted_string = (string[0] == '\0' ? "\"\"" : string);
148 size_t length = strlen (quoted_string);
149 memcpy (mem, quoted_string, length + 1);
150 mem += length + 1;
151 }
152 new_argv[1 + argc] = NULL;
153
154 return new_argv;
155 }