-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXCWProcessRunner.m
More file actions
310 lines (281 loc) · 11.4 KB
/
XCWProcessRunner.m
File metadata and controls
310 lines (281 loc) · 11.4 KB
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
#import "XCWProcessRunner.h"
#import <errno.h>
#import <fcntl.h>
#import <math.h>
#import <signal.h>
#import <spawn.h>
#import <string.h>
#import <sys/wait.h>
#import <unistd.h>
extern char **environ;
static NSString * const XCWProcessRunnerErrorDomain = @"SimDeck.ProcessRunner";
static void XCWCloseFD(int *fd) {
if (fd != NULL && *fd >= 0) {
close(*fd);
*fd = -1;
}
}
static void XCWWriteAllAndCloseFD(int fd, NSData *data) {
if (fd < 0) {
return;
}
const uint8_t *bytes = data.bytes;
NSUInteger remaining = data.length;
while (remaining > 0) {
ssize_t written = write(fd, bytes, remaining);
if (written > 0) {
bytes += written;
remaining -= (NSUInteger)written;
continue;
}
if (written < 0 && errno == EINTR) {
continue;
}
break;
}
close(fd);
}
static NSError *XCWProcessRunnerError(NSInteger code, NSString *description) {
return [NSError errorWithDomain:XCWProcessRunnerErrorDomain
code:code
userInfo:@{ NSLocalizedDescriptionKey: description ?: @"Process failed." }];
}
static NSString *XCWCommandDescription(NSString *launchPath, NSArray<NSString *> *arguments) {
NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithObject:launchPath.lastPathComponent ?: launchPath];
[parts addObjectsFromArray:arguments];
return [parts componentsJoinedByString:@" "];
}
static int XCWCreateTemporaryOutputFile(NSString **path, NSError * _Nullable __autoreleasing *error) {
NSString *templatePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"simdeck-process-XXXXXX"];
char *fileTemplate = strdup(templatePath.fileSystemRepresentation);
if (fileTemplate == NULL) {
if (error != NULL) {
*error = XCWProcessRunnerError(6, @"Failed to allocate temporary output path.");
}
return -1;
}
int fd = mkstemp(fileTemplate);
if (fd < 0) {
if (error != NULL) {
*error = XCWProcessRunnerError(7, [NSString stringWithFormat:@"Failed to create temporary output file: %s", strerror(errno)]);
}
free(fileTemplate);
return -1;
}
if (path != NULL) {
*path = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:fileTemplate
length:strlen(fileTemplate)];
}
free(fileTemplate);
return fd;
}
@implementation XCWProcessResult
- (instancetype)initWithTerminationStatus:(int)terminationStatus
stdoutData:(NSData *)stdoutData
stderrData:(NSData *)stderrData {
self = [super init];
if (self == nil) {
return nil;
}
_terminationStatus = terminationStatus;
_stdoutData = [stdoutData copy];
_stderrData = [stderrData copy];
_stdoutString = [[NSString alloc] initWithData:_stdoutData encoding:NSUTF8StringEncoding] ?: @"";
_stderrString = [[NSString alloc] initWithData:_stderrData encoding:NSUTF8StringEncoding] ?: @"";
return self;
}
@end
@implementation XCWProcessRunner
+ (XCWProcessResult *)runLaunchPath:(NSString *)launchPath
arguments:(NSArray<NSString *> *)arguments
inputData:(NSData *)inputData
error:(NSError * _Nullable __autoreleasing *)error {
return [self runLaunchPath:launchPath
arguments:arguments
inputData:inputData
timeoutSec:0
error:error];
}
+ (XCWProcessResult *)runLaunchPath:(NSString *)launchPath
arguments:(NSArray<NSString *> *)arguments
inputData:(NSData *)inputData
timeoutSec:(NSTimeInterval)timeoutSec
error:(NSError * _Nullable __autoreleasing *)error {
int stdoutFD = -1;
int stderrFD = -1;
int stdinPipe[2] = { -1, -1 };
NSString *stdoutPath = nil;
NSString *stderrPath = nil;
posix_spawn_file_actions_t fileActions;
BOOL fileActionsInitialized = NO;
char **argv = NULL;
NSError *creationError = nil;
stdoutFD = XCWCreateTemporaryOutputFile(&stdoutPath, &creationError);
stderrFD = XCWCreateTemporaryOutputFile(&stderrPath, &creationError);
if (stdoutFD < 0 || stderrFD < 0 || (inputData != nil && pipe(stdinPipe) != 0)) {
if (error != NULL) {
*error = creationError ?: XCWProcessRunnerError(1, [NSString stringWithFormat:@"Failed to create process pipes: %s", strerror(errno)]);
}
XCWCloseFD(&stdoutFD);
XCWCloseFD(&stderrFD);
XCWCloseFD(&stdinPipe[0]);
XCWCloseFD(&stdinPipe[1]);
if (stdoutPath != nil) {
[[NSFileManager defaultManager] removeItemAtPath:stdoutPath error:nil];
}
if (stderrPath != nil) {
[[NSFileManager defaultManager] removeItemAtPath:stderrPath error:nil];
}
return nil;
}
if (posix_spawn_file_actions_init(&fileActions) != 0) {
if (error != NULL) {
*error = XCWProcessRunnerError(2, [NSString stringWithFormat:@"Failed to initialize spawn actions: %s", strerror(errno)]);
}
XCWCloseFD(&stdoutFD);
XCWCloseFD(&stderrFD);
XCWCloseFD(&stdinPipe[0]);
XCWCloseFD(&stdinPipe[1]);
[[NSFileManager defaultManager] removeItemAtPath:stdoutPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:stderrPath error:nil];
return nil;
}
fileActionsInitialized = YES;
posix_spawn_file_actions_adddup2(&fileActions, stdoutFD, STDOUT_FILENO);
posix_spawn_file_actions_adddup2(&fileActions, stderrFD, STDERR_FILENO);
if (inputData != nil) {
posix_spawn_file_actions_adddup2(&fileActions, stdinPipe[0], STDIN_FILENO);
} else {
posix_spawn_file_actions_addopen(&fileActions, STDIN_FILENO, "/dev/null", O_RDONLY, 0);
}
posix_spawn_file_actions_addclose(&fileActions, stdoutFD);
posix_spawn_file_actions_addclose(&fileActions, stderrFD);
if (inputData != nil) {
posix_spawn_file_actions_addclose(&fileActions, stdinPipe[0]);
posix_spawn_file_actions_addclose(&fileActions, stdinPipe[1]);
}
NSUInteger argc = arguments.count + 2;
argv = calloc(argc, sizeof(char *));
if (argv == NULL) {
if (error != NULL) {
*error = XCWProcessRunnerError(3, @"Failed to allocate process arguments.");
}
posix_spawn_file_actions_destroy(&fileActions);
XCWCloseFD(&stdoutFD);
XCWCloseFD(&stderrFD);
XCWCloseFD(&stdinPipe[0]);
XCWCloseFD(&stdinPipe[1]);
[[NSFileManager defaultManager] removeItemAtPath:stdoutPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:stderrPath error:nil];
return nil;
}
argv[0] = (char *)launchPath.fileSystemRepresentation;
for (NSUInteger index = 0; index < arguments.count; index += 1) {
argv[index + 1] = (char *)arguments[index].UTF8String;
}
argv[argc - 1] = NULL;
pid_t pid = 0;
int spawnResult = posix_spawn(&pid, launchPath.fileSystemRepresentation, &fileActions, NULL, argv, environ);
if (spawnResult != 0) {
if (error != NULL) {
*error = XCWProcessRunnerError(4, [NSString stringWithFormat:@"Failed to launch %@: %s", launchPath, strerror(spawnResult)]);
}
posix_spawn_file_actions_destroy(&fileActions);
free(argv);
XCWCloseFD(&stdoutFD);
XCWCloseFD(&stderrFD);
XCWCloseFD(&stdinPipe[0]);
XCWCloseFD(&stdinPipe[1]);
[[NSFileManager defaultManager] removeItemAtPath:stdoutPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:stderrPath error:nil];
return nil;
}
XCWCloseFD(&stdoutFD);
XCWCloseFD(&stderrFD);
dispatch_group_t writeGroup = inputData != nil ? dispatch_group_create() : nil;
if (inputData != nil) {
XCWCloseFD(&stdinPipe[0]);
int stdinWriteFD = stdinPipe[1];
stdinPipe[1] = -1;
dispatch_group_async(writeGroup, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
XCWWriteAllAndCloseFD(stdinWriteFD, inputData);
});
}
int waitStatus = 0;
pid_t waitResult = -1;
BOOL timedOut = NO;
BOOL hasTimeout = timeoutSec > 0;
NSDate *deadline = hasTimeout ? [NSDate dateWithTimeIntervalSinceNow:timeoutSec] : nil;
do {
waitResult = waitpid(pid, &waitStatus, hasTimeout ? WNOHANG : 0);
if (waitResult == pid) {
break;
}
if (waitResult < 0 && errno == EINTR) {
continue;
}
if (waitResult < 0) {
break;
}
if (hasTimeout && [deadline timeIntervalSinceNow] <= 0) {
timedOut = YES;
kill(pid, SIGTERM);
NSDate *killDeadline = [NSDate dateWithTimeIntervalSinceNow:2.0];
do {
waitResult = waitpid(pid, &waitStatus, WNOHANG);
if (waitResult == pid || (waitResult < 0 && errno != EINTR)) {
break;
}
usleep(10 * 1000);
} while ([killDeadline timeIntervalSinceNow] > 0);
if (waitResult != pid) {
kill(pid, SIGKILL);
do {
waitResult = waitpid(pid, &waitStatus, 0);
} while (waitResult < 0 && errno == EINTR);
}
break;
}
usleep(10 * 1000);
} while (YES);
if (writeGroup != nil) {
dispatch_group_wait(writeGroup, DISPATCH_TIME_FOREVER);
}
int terminationStatus = 1;
NSString *timeoutMessage = nil;
if (timedOut) {
terminationStatus = 124;
timeoutMessage = [NSString stringWithFormat:@"%@ timed out after %.0fs.",
XCWCommandDescription(launchPath, arguments),
ceil(timeoutSec)];
} else if (waitResult < 0) {
if (error != NULL) {
*error = XCWProcessRunnerError(5, [NSString stringWithFormat:@"Failed to wait for %@: %s", launchPath, strerror(errno)]);
}
} else if (WIFEXITED(waitStatus)) {
terminationStatus = WEXITSTATUS(waitStatus);
} else if (WIFSIGNALED(waitStatus)) {
terminationStatus = 128 + WTERMSIG(waitStatus);
}
if (fileActionsInitialized) {
posix_spawn_file_actions_destroy(&fileActions);
}
free(argv);
NSData *stdoutData = [NSData dataWithContentsOfFile:stdoutPath] ?: [NSData data];
NSData *stderrData = [NSData dataWithContentsOfFile:stderrPath] ?: [NSData data];
if (timeoutMessage.length > 0) {
NSMutableData *combinedStderr = [stderrData mutableCopy];
if (combinedStderr.length > 0) {
const char newline = '\n';
[combinedStderr appendBytes:&newline length:1];
}
[combinedStderr appendData:[timeoutMessage dataUsingEncoding:NSUTF8StringEncoding] ?: [NSData data]];
stderrData = combinedStderr;
}
[[NSFileManager defaultManager] removeItemAtPath:stdoutPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:stderrPath error:nil];
return [[XCWProcessResult alloc] initWithTerminationStatus:terminationStatus
stdoutData:stdoutData
stderrData:stderrData];
}
@end