/
exec.c
371 lines (301 loc) · 14.5 KB
/
exec.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/***********************************************************************************************************************************
Execute Process
***********************************************************************************************************************************/
#include "build.auto.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "common/debug.h"
#include "common/exec.h"
#include "common/fork.h"
#include "common/io/fdRead.h"
#include "common/io/fdWrite.h"
#include "common/io/io.h"
#include "common/io/read.h"
#include "common/io/write.h"
#include "common/log.h"
#include "common/wait.h"
/***********************************************************************************************************************************
Object type
***********************************************************************************************************************************/
struct Exec
{
ExecPub pub; // Publicly accessible variables
String *command; // Command to execute
StringList *param; // List of parameters to pass to command
const String *name; // Name to display in log/error messages
TimeMSec timeout; // Timeout for any i/o operation (read, write, etc.)
pid_t processId; // Process id of the child process
int fdRead; // Read file descriptor
int fdWrite; // Write file descriptor
int fdError; // Error file descriptor
IoRead *ioReadFd; // File descriptor read interface
IoWrite *ioWriteFd; // File descriptor write interface
};
/***********************************************************************************************************************************
Macro to close file descriptors after dup2() in the child process
If the parent process is daemomized and has closed stdout, stdin, and stderr or some combination of them, then the newly created
descriptors might overlap stdout, stdin, or stderr. In that case we don't want to accidentally close the descriptor that we have
just copied.
Note that this is pretty specific to the way that file descriptors are handled in this module and may not be generally applicable in
other code.
***********************************************************************************************************************************/
#define PIPE_DUP2(pipe, pipeIdx, fd) \
do \
{ \
dup2(pipe[pipeIdx], fd); \
\
if (pipe[0] != fd) \
close(pipe[0]); \
\
if (pipe[1] != fd) \
close(pipe[1]); \
} \
while (0);
/***********************************************************************************************************************************
Free exec file descriptors and ensure process is shut down
***********************************************************************************************************************************/
static void
execFreeResource(THIS_VOID)
{
THIS(Exec);
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(EXEC, this);
FUNCTION_LOG_END();
ASSERT(this != NULL);
// Close file descriptors
close(this->fdRead);
close(this->fdWrite);
close(this->fdError);
// Wait for the child to exit. We don't really care how it exits as long as it does.
if (this->processId != 0)
{
MEM_CONTEXT_TEMP_BEGIN()
{
int processResult = 0;
Wait *wait = waitNew(this->timeout);
do
{
THROW_ON_SYS_ERROR(
(processResult = waitpid(this->processId, NULL, WNOHANG)) == -1, ExecuteError,
"unable to wait on child process");
}
while (processResult == 0 && waitMore(wait));
// If the process did not exit then error -- else we may end up with a collection of zombie processes
if (processResult == 0)
THROW_FMT(ExecuteError, "%s did not exit when expected", strZ(this->name));
}
MEM_CONTEXT_TEMP_END();
}
FUNCTION_LOG_RETURN_VOID();
}
/**********************************************************************************************************************************/
FN_EXTERN Exec *
execNew(const String *command, const StringList *param, const String *name, TimeMSec timeout)
{
FUNCTION_LOG_BEGIN(logLevelDebug);
FUNCTION_LOG_PARAM(STRING, command);
FUNCTION_LOG_PARAM(STRING_LIST, param);
FUNCTION_LOG_PARAM(STRING, name);
FUNCTION_LOG_PARAM(TIME_MSEC, timeout);
FUNCTION_LOG_END();
ASSERT(command != NULL);
ASSERT(name != NULL);
ASSERT(timeout > 0);
OBJ_NEW_BEGIN(Exec, .childQty = MEM_CONTEXT_QTY_MAX, .callbackQty = 1)
{
*this = (Exec)
{
.command = strDup(command),
.name = strDup(name),
.timeout = timeout,
// Parameter list is optional but if not specified we need to build one with the command
.param = param == NULL ? strLstNew() : strLstDup(param),
};
// The first parameter must be the command
strLstInsert(this->param, 0, this->command);
}
OBJ_NEW_END();
FUNCTION_LOG_RETURN(EXEC, this);
}
/***********************************************************************************************************************************
Check if the process is still running
This should be called when anything unexpected happens while reading or writing, including errors and eof. If this function returns
then the original error should be rethrown.
***********************************************************************************************************************************/
static void
execCheck(Exec *this)
{
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(EXEC, this);
FUNCTION_LOG_END();
ASSERT(this != NULL);
int processStatus;
int processResult;
THROW_ON_SYS_ERROR(
(processResult = waitpid(this->processId, &processStatus, WNOHANG)) == -1, ExecuteError, "unable to wait on child process");
if (processResult != 0)
{
// Clear the process id so we don't try to wait for this process on free
this->processId = 0;
// If the process exited normally
if (WIFEXITED(processStatus))
{
// Get data from stderr to help diagnose the problem
String *errorStr = strTrim(
strNewBuf(ioReadBuf(ioFdReadNewOpen(strNewFmt("%s error", strZ(this->name)), this->fdError, 0))));
// Throw the error with as much information as is available
THROWP_FMT(
errorTypeFromCode(WEXITSTATUS(processStatus)), "%s terminated unexpectedly [%d]%s%s", strZ(this->name),
WEXITSTATUS(processStatus), strSize(errorStr) > 0 ? ": " : "", strSize(errorStr) > 0 ? strZ(errorStr) : "");
}
// If the process did not exit normally then it must have been a signal
THROW_FMT(ExecuteError, "%s terminated unexpectedly on signal %d", strZ(this->name), WTERMSIG(processStatus));
}
FUNCTION_LOG_RETURN_VOID();
}
/***********************************************************************************************************************************
Read from the process
***********************************************************************************************************************************/
static size_t
execRead(THIS_VOID, Buffer *buffer, bool block)
{
THIS(Exec);
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(EXEC, this);
FUNCTION_LOG_PARAM(BUFFER, buffer);
FUNCTION_LOG_PARAM(BOOL, block);
FUNCTION_LOG_END();
ASSERT(this != NULL);
ASSERT(buffer != NULL);
size_t result = 0;
TRY_BEGIN()
{
result = ioReadInterface(this->ioReadFd)->read(ioReadDriver(this->ioReadFd), buffer, block);
}
CATCH_ANY()
{
execCheck(this);
RETHROW();
}
TRY_END();
FUNCTION_LOG_RETURN(SIZE, result);
}
/***********************************************************************************************************************************
Write to the process
***********************************************************************************************************************************/
static void
execWrite(THIS_VOID, const Buffer *buffer)
{
THIS(Exec);
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(EXEC, this);
FUNCTION_LOG_PARAM(BUFFER, buffer);
FUNCTION_LOG_END();
ASSERT(this != NULL);
ASSERT(buffer != NULL);
TRY_BEGIN()
{
ioWrite(this->ioWriteFd, buffer);
ioWriteFlush(this->ioWriteFd);
}
CATCH_ANY()
{
execCheck(this);
RETHROW();
}
TRY_END();
FUNCTION_LOG_RETURN_VOID();
}
/***********************************************************************************************************************************
Is the process eof?
***********************************************************************************************************************************/
static bool
execEof(THIS_VOID)
{
THIS(Exec);
FUNCTION_LOG_BEGIN(logLevelTrace);
FUNCTION_LOG_PARAM(EXEC, this);
FUNCTION_LOG_END();
ASSERT(this != NULL);
// Check if the process is still running on eof
if (ioReadInterface(this->ioReadFd)->eof(ioReadDriver(this->ioReadFd)))
execCheck(this);
FUNCTION_LOG_RETURN(BOOL, false);
}
/***********************************************************************************************************************************
Get the read file descriptor
***********************************************************************************************************************************/
static int
execFdRead(const THIS_VOID)
{
THIS(const Exec);
FUNCTION_TEST_BEGIN();
FUNCTION_TEST_PARAM(EXEC, this);
FUNCTION_TEST_END();
ASSERT(this != NULL);
FUNCTION_TEST_RETURN(INT, this->fdRead);
}
/**********************************************************************************************************************************/
FN_EXTERN void
execOpen(Exec *this)
{
FUNCTION_LOG_BEGIN(logLevelDebug);
FUNCTION_LOG_PARAM(EXEC, this);
FUNCTION_LOG_END();
ASSERT(this != NULL);
// Create pipes to communicate with the subprocess. The names of the pipes are from the perspective of the parent process since
// the child process will use them only briefly before exec'ing.
int pipeRead[2];
int pipeWrite[2];
int pipeError[2];
THROW_ON_SYS_ERROR(pipe(pipeRead) == -1, KernelError, "unable to create read pipe");
THROW_ON_SYS_ERROR(pipe(pipeWrite) == -1, KernelError, "unable to create write pipe");
THROW_ON_SYS_ERROR(pipe(pipeError) == -1, KernelError, "unable to create error pipe");
// Fork the subprocess
this->processId = forkSafe();
// Exec command in the child process
if (this->processId == 0)
{
// Disable logging and close log file
logClose();
// Assign stdout to the input side of the read pipe
PIPE_DUP2(pipeRead, 1, STDOUT_FILENO);
// Assign stdin to the output side of the write pipe
PIPE_DUP2(pipeWrite, 0, STDIN_FILENO);
// Assign stderr to the input side of the error pipe
PIPE_DUP2(pipeError, 1, STDERR_FILENO);
// Execute the binary. This statement will not return if it is successful
execvp(strZ(this->command), (char **const)strLstPtr(this->param));
// If we got here then there was an error. We can't use a throw as we normally would because we have already shutdown
// logging and we don't want to execute exit paths that might free parent resources which we still have references to.
fprintf(stderr, "unable to execute '%s': [%d] %s\n", strZ(this->command), errno, strerror(errno));
exit(errorTypeCode(&ExecuteError));
}
// Close the unused file descriptors
close(pipeRead[1]);
close(pipeWrite[0]);
close(pipeError[1]);
// Store the file descriptors we'll use and need to close when the process terminates
this->fdRead = pipeRead[0];
this->fdWrite = pipeWrite[1];
this->fdError = pipeError[0];
MEM_CONTEXT_OBJ_BEGIN(this)
{
// Assign file descriptors to io interfaces
this->ioReadFd = ioFdReadNew(strNewFmt("%s read", strZ(this->name)), this->fdRead, this->timeout);
this->ioWriteFd = ioFdWriteNewOpen(strNewFmt("%s write", strZ(this->name)), this->fdWrite, this->timeout);
// Create wrapper interfaces that check process state
this->pub.ioReadExec = ioReadNewP(this, .block = true, .read = execRead, .eof = execEof, .fd = execFdRead);
ioReadOpen(execIoRead(this));
this->pub.ioWriteExec = ioWriteNewP(this, .write = execWrite);
ioWriteOpen(execIoWrite(this));
}
MEM_CONTEXT_OBJ_END();
// Set a callback so the file descriptors will get freed
memContextCallbackSet(objMemContext(this), execFreeResource, this);
FUNCTION_LOG_RETURN_VOID();
}