This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathpal_process.cpp
626 lines (554 loc) · 19.2 KB
/
pal_process.cpp
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "pal_config.h"
#include "pal_process.h"
#include "pal_io.h"
#include "pal_utilities.h"
#include <assert.h>
#include <errno.h>
#include <limits>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <syslog.h>
#include <unistd.h>
#if HAVE_CRT_EXTERNS_H
#include <crt_externs.h>
#endif
#if HAVE_PIPE2
#include <fcntl.h>
#endif
#if HAVE_SCHED_SETAFFINITY || HAVE_SCHED_GETAFFINITY
#include <sched.h>
#endif
// Validate that our Signals enum values are correct for the platform
static_assert(PAL_SIGKILL == SIGKILL, "");
// Validate that our SysLogPriority values are correct for the platform
static_assert(PAL_LOG_EMERG == LOG_EMERG, "");
static_assert(PAL_LOG_ALERT == LOG_ALERT, "");
static_assert(PAL_LOG_CRIT == LOG_CRIT, "");
static_assert(PAL_LOG_ERR == LOG_ERR, "");
static_assert(PAL_LOG_WARNING == LOG_WARNING, "");
static_assert(PAL_LOG_NOTICE == LOG_NOTICE, "");
static_assert(PAL_LOG_INFO == LOG_INFO, "");
static_assert(PAL_LOG_DEBUG == LOG_DEBUG, "");
static_assert(PAL_LOG_KERN == LOG_KERN, "");
static_assert(PAL_LOG_USER == LOG_USER, "");
static_assert(PAL_LOG_MAIL == LOG_MAIL, "");
static_assert(PAL_LOG_DAEMON == LOG_DAEMON, "");
static_assert(PAL_LOG_AUTH == LOG_AUTH, "");
static_assert(PAL_LOG_SYSLOG == LOG_SYSLOG, "");
static_assert(PAL_LOG_LPR == LOG_LPR, "");
static_assert(PAL_LOG_NEWS == LOG_NEWS, "");
static_assert(PAL_LOG_UUCP == LOG_UUCP, "");
static_assert(PAL_LOG_CRON == LOG_CRON, "");
static_assert(PAL_LOG_AUTHPRIV == LOG_AUTHPRIV, "");
static_assert(PAL_LOG_FTP == LOG_FTP, "");
static_assert(PAL_LOG_LOCAL0 == LOG_LOCAL0, "");
static_assert(PAL_LOG_LOCAL1 == LOG_LOCAL1, "");
static_assert(PAL_LOG_LOCAL2 == LOG_LOCAL2, "");
static_assert(PAL_LOG_LOCAL3 == LOG_LOCAL3, "");
static_assert(PAL_LOG_LOCAL4 == LOG_LOCAL4, "");
static_assert(PAL_LOG_LOCAL5 == LOG_LOCAL5, "");
static_assert(PAL_LOG_LOCAL6 == LOG_LOCAL6, "");
static_assert(PAL_LOG_LOCAL7 == LOG_LOCAL7, "");
// Validate that out PriorityWhich values are correct for the platform
static_assert(PAL_PRIO_PROCESS == static_cast<int>(PRIO_PROCESS), "");
static_assert(PAL_PRIO_PGRP == static_cast<int>(PRIO_PGRP), "");
static_assert(PAL_PRIO_USER == static_cast<int>(PRIO_USER), "");
enum
{
READ_END_OF_PIPE = 0,
WRITE_END_OF_PIPE = 1,
};
static void CloseIfOpen(int fd)
{
if (fd >= 0)
{
close(fd); // Ignoring errors from close is a deliberate choice
}
}
static int Dup2WithInterruptedRetry(int oldfd, int newfd)
{
int result;
while (CheckInterrupted(result = dup2(oldfd, newfd)));
return result;
}
static ssize_t WriteSize(int fd, const void* buffer, size_t count)
{
ssize_t rv = 0;
while (count > 0)
{
ssize_t result = 0;
while (CheckInterrupted(result = write(fd, buffer, count)));
if (result > 0)
{
rv += result;
buffer = reinterpret_cast<const uint8_t*>(buffer) + result;
count -= static_cast<size_t>(result);
}
else
{
return -1;
}
}
return rv;
}
static ssize_t ReadSize(int fd, void* buffer, size_t count)
{
ssize_t rv = 0;
while (count > 0)
{
ssize_t result = 0;
while (CheckInterrupted(result = read(fd, buffer, count)));
if (result > 0)
{
rv += result;
buffer = reinterpret_cast<uint8_t*>(buffer) + result;
count -= static_cast<size_t>(result);
}
else
{
return -1;
}
}
return rv;
}
__attribute__((noreturn))
static void ExitChild(int pipeToParent, int error)
{
if (pipeToParent != -1)
{
WriteSize(pipeToParent, &error, sizeof(error));
}
_exit(error != 0 ? error : EXIT_FAILURE);
}
extern "C" int32_t SystemNative_ForkAndExecProcess(const char* filename,
char* const argv[],
char* const envp[],
const char* cwd,
int32_t redirectStdin,
int32_t redirectStdout,
int32_t redirectStderr,
int32_t setCredentials,
uint32_t userId,
uint32_t groupId,
int32_t* childPid,
int32_t* stdinFd,
int32_t* stdoutFd,
int32_t* stderrFd)
{
int success = true;
int stdinFds[2] = {-1, -1}, stdoutFds[2] = {-1, -1}, stderrFds[2] = {-1, -1}, waitForChildToExecPipe[2] = {-1, -1};
int processId = -1;
// Validate arguments
if (nullptr == filename || nullptr == argv || nullptr == envp || nullptr == stdinFd || nullptr == stdoutFd ||
nullptr == stderrFd || nullptr == childPid)
{
assert(false && "null argument.");
errno = EINVAL;
success = false;
goto done;
}
if ((redirectStdin & ~1) != 0 || (redirectStdout & ~1) != 0 || (redirectStderr & ~1) != 0 || (setCredentials & ~1) != 0)
{
assert(false && "Boolean redirect* inputs must be 0 or 1.");
errno = EINVAL;
success = false;
goto done;
}
// Make sure we can find and access the executable. exec will do this, of course, but at that point it's already
// in the child process, at which point it'll translate to the child process' exit code rather than to failing
// the Start itself. There's a race condition here, in that this could change prior to exec's checks, but there's
// little we can do about that. There are also more rigorous checks exec does, such as validating the executable
// format of the target; such errors will emerge via the child process' exit code.
if (access(filename, X_OK) != 0)
{
success = false;
goto done;
}
// Open pipes for any requests to redirect stdin/stdout/stderr and set the
// close-on-exec flag to the pipe file descriptors.
if ((redirectStdin && SystemNative_Pipe(stdinFds, PAL_O_CLOEXEC) != 0) ||
(redirectStdout && SystemNative_Pipe(stdoutFds, PAL_O_CLOEXEC) != 0) ||
(redirectStderr && SystemNative_Pipe(stderrFds, PAL_O_CLOEXEC) != 0))
{
success = false;
goto done;
}
// If we have pipe2 and can use O_CLOEXEC, we create a pipe purely for the benefit
// of knowing when the child process has called exec. We can use that to block waiting
// on the pipe to be closed, which lets us block the parent from returning until the
// child process is actually transitioned to the target program. This avoids problems
// where the parent process uses members of Process, like ProcessName, when the Process
// is still the clone of this one. This is a best-effort attempt, so ignore any errors.
// If the child fails to exec we use the pipe to pass the errno to the parent process.
// NOTE: It's tempting to use SystemNative_Pipe here, as that would simulate pipe2 even
// on platforms that don't have it. But it's potentially problematic, in that if another
// process is launched between the pipe creation and the fcntl call to set CLOEXEC on it,
// that file descriptor will be inherited into the child process, which will in turn cause
// the loop below that waits for that pipe to be closed to loop indefinitely.
#if HAVE_PIPE2
pipe2(waitForChildToExecPipe, O_CLOEXEC);
#endif
// Fork the child process
if ((processId = fork()) == -1)
{
success = false;
goto done;
}
if (processId == 0) // processId == 0 if this is child process
{
// For any redirections that should happen, dup the pipe descriptors onto stdin/out/err.
// We don't need to explicitly close out the old pipe descriptors as they will be closed on the 'execve' call.
if ((redirectStdin && Dup2WithInterruptedRetry(stdinFds[READ_END_OF_PIPE], STDIN_FILENO) == -1) ||
(redirectStdout && Dup2WithInterruptedRetry(stdoutFds[WRITE_END_OF_PIPE], STDOUT_FILENO) == -1) ||
(redirectStderr && Dup2WithInterruptedRetry(stderrFds[WRITE_END_OF_PIPE], STDERR_FILENO) == -1))
{
ExitChild(waitForChildToExecPipe[WRITE_END_OF_PIPE], errno);
}
if (setCredentials)
{
if (setgid(groupId) == -1 || setuid(userId) == -1)
{
ExitChild(waitForChildToExecPipe[WRITE_END_OF_PIPE], errno);
}
}
// Change to the designated working directory, if one was specified
if (nullptr != cwd)
{
int result;
while (CheckInterrupted(result = chdir(cwd)));
if (result == -1)
{
ExitChild(waitForChildToExecPipe[WRITE_END_OF_PIPE], errno);
}
}
// Finally, execute the new process. execve will not return if it's successful.
execve(filename, argv, envp);
ExitChild(waitForChildToExecPipe[WRITE_END_OF_PIPE], errno); // execve failed
}
// This is the parent process. processId == pid of the child
*childPid = processId;
*stdinFd = stdinFds[WRITE_END_OF_PIPE];
*stdoutFd = stdoutFds[READ_END_OF_PIPE];
*stderrFd = stderrFds[READ_END_OF_PIPE];
done:
int priorErrno = errno;
// Regardless of success or failure, close the parent's copy of the child's end of
// any opened pipes. The parent doesn't need them anymore.
CloseIfOpen(stdinFds[READ_END_OF_PIPE]);
CloseIfOpen(stdoutFds[WRITE_END_OF_PIPE]);
CloseIfOpen(stderrFds[WRITE_END_OF_PIPE]);
// Also close the write end of the exec waiting pipe, and wait for the pipe to be closed
// by trying to read from it (the read will wake up when the pipe is closed and broken).
// Ignore any errors... this is a best-effort attempt.
CloseIfOpen(waitForChildToExecPipe[WRITE_END_OF_PIPE]);
if (waitForChildToExecPipe[READ_END_OF_PIPE] != -1)
{
int childError;
if (success)
{
ssize_t result = ReadSize(waitForChildToExecPipe[READ_END_OF_PIPE], &childError, sizeof(childError));
if (result == sizeof(childError))
{
success = false;
priorErrno = childError;
}
}
CloseIfOpen(waitForChildToExecPipe[READ_END_OF_PIPE]);
}
// If we failed, close everything else and give back error values in all out arguments.
if (!success)
{
CloseIfOpen(stdinFds[WRITE_END_OF_PIPE]);
CloseIfOpen(stdoutFds[READ_END_OF_PIPE]);
CloseIfOpen(stderrFds[READ_END_OF_PIPE]);
// Reap child
if (processId > 0)
{
int status;
waitpid(processId, &status, 0);
}
*stdinFd = -1;
*stdoutFd = -1;
*stderrFd = -1;
*childPid = -1;
errno = priorErrno;
return -1;
}
return 0;
}
extern "C" FILE* SystemNative_POpen(const char* command, const char* type)
{
assert(command != nullptr);
assert(type != nullptr);
return popen(command, type);
}
extern "C" int32_t SystemNative_PClose(FILE* stream)
{
assert(stream != nullptr);
return pclose(stream);
}
// Each platform type has it's own RLIMIT values but the same name, so we need
// to convert our standard types into the platform specific ones.
static int32_t ConvertRLimitResourcesPalToPlatform(RLimitResources value)
{
switch (value)
{
case PAL_RLIMIT_CPU:
return RLIMIT_CPU;
case PAL_RLIMIT_FSIZE:
return RLIMIT_FSIZE;
case PAL_RLIMIT_DATA:
return RLIMIT_DATA;
case PAL_RLIMIT_STACK:
return RLIMIT_STACK;
case PAL_RLIMIT_CORE:
return RLIMIT_CORE;
case PAL_RLIMIT_AS:
return RLIMIT_AS;
case PAL_RLIMIT_RSS:
return RLIMIT_RSS;
case PAL_RLIMIT_MEMLOCK:
return RLIMIT_MEMLOCK;
case PAL_RLIMIT_NPROC:
return RLIMIT_NPROC;
case PAL_RLIMIT_NOFILE:
return RLIMIT_NOFILE;
}
assert_msg(false, "Unknown RLIMIT value", static_cast<int>(value));
return -1;
}
// Because RLIM_INFINITY is different per-platform, use the max value of a uint64 (which is RLIM_INFINITY on Ubuntu)
// to signify RLIM_INIFINITY; on OS X, where RLIM_INFINITY is slightly lower, we'll translate it to the correct value
// here.
static rlim_t ConvertFromManagedRLimitInfinityToPalIfNecessary(uint64_t value)
{
// rlim_t type can vary per platform, so we also treat anything outside its range as infinite.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wtautological-type-limit-compare"
if (value == UINT64_MAX || value > std::numeric_limits<rlim_t>::max())
#pragma clang diagnostic pop
return RLIM_INFINITY;
return static_cast<rlim_t>(value);
}
// Because RLIM_INFINITY is different per-platform, use the max value of a uint64 (which is RLIM_INFINITY on Ubuntu)
// to signify RLIM_INIFINITY; on OS X, where RLIM_INFINITY is slightly lower, we'll translate it to the correct value
// here.
static uint64_t ConvertFromNativeRLimitInfinityToManagedIfNecessary(rlim_t value)
{
if (value == RLIM_INFINITY)
return UINT64_MAX;
return UnsignedCast(value);
}
static void ConvertFromRLimitManagedToPal(const RLimit& pal, rlimit& native)
{
native.rlim_cur = ConvertFromManagedRLimitInfinityToPalIfNecessary(pal.CurrentLimit);
native.rlim_max = ConvertFromManagedRLimitInfinityToPalIfNecessary(pal.MaximumLimit);
}
static void ConvertFromPalRLimitToManaged(const rlimit& native, RLimit& pal)
{
pal.CurrentLimit = ConvertFromNativeRLimitInfinityToManagedIfNecessary(native.rlim_cur);
pal.MaximumLimit = ConvertFromNativeRLimitInfinityToManagedIfNecessary(native.rlim_max);
}
extern "C" int32_t SystemNative_GetRLimit(RLimitResources resourceType, RLimit* limits)
{
assert(limits != nullptr);
int32_t platformLimit = ConvertRLimitResourcesPalToPlatform(resourceType);
rlimit internalLimit;
int result = getrlimit(platformLimit, &internalLimit);
if (result == 0)
{
ConvertFromPalRLimitToManaged(internalLimit, *limits);
}
else
{
*limits = {};
}
return result;
}
extern "C" int32_t SystemNative_SetRLimit(RLimitResources resourceType, const RLimit* limits)
{
assert(limits != nullptr);
int32_t platformLimit = ConvertRLimitResourcesPalToPlatform(resourceType);
rlimit internalLimit;
ConvertFromRLimitManagedToPal(*limits, internalLimit);
return setrlimit(platformLimit, &internalLimit);
}
extern "C" int32_t SystemNative_Kill(int32_t pid, int32_t signal)
{
return kill(pid, signal);
}
extern "C" int32_t SystemNative_GetPid()
{
return getpid();
}
extern "C" int32_t SystemNative_GetSid(int32_t pid)
{
return getsid(pid);
}
extern "C" void SystemNative_SysLog(SysLogPriority priority, const char* message, const char* arg1)
{
syslog(static_cast<int>(priority), message, arg1);
}
extern "C" int32_t SystemNative_WaitIdExitedNoHang(int32_t pid, int32_t* exitCode, int32_t keepWaitable)
{
assert(exitCode != nullptr);
siginfo_t siginfo;
int32_t result;
idtype_t idtype = pid == -1 ? P_ALL : P_PID;
int options = WEXITED | WNOHANG;
if (keepWaitable != 0)
{
options |= WNOWAIT;
}
while (CheckInterrupted(result = waitid(idtype, static_cast<id_t>(pid), &siginfo, options)));
if (idtype == P_ALL && result == -1 && errno == ECHILD)
{
result = 0;
}
else if (result == 0 && siginfo.si_signo == SIGCHLD)
{
if (siginfo.si_code == CLD_EXITED)
{
*exitCode = siginfo.si_status;
}
else
{
*exitCode = 128 + siginfo.si_status;
}
result = siginfo.si_pid;
}
return result;
}
extern "C" int64_t SystemNative_PathConf(const char* path, PathConfName name)
{
int32_t confValue = -1;
switch (name)
{
case PAL_PC_LINK_MAX:
confValue = _PC_LINK_MAX;
break;
case PAL_PC_MAX_CANON:
confValue = _PC_MAX_CANON;
break;
case PAL_PC_MAX_INPUT:
confValue = _PC_MAX_INPUT;
break;
case PAL_PC_NAME_MAX:
confValue = _PC_NAME_MAX;
break;
case PAL_PC_PATH_MAX:
confValue = _PC_PATH_MAX;
break;
case PAL_PC_PIPE_BUF:
confValue = _PC_PIPE_BUF;
break;
case PAL_PC_CHOWN_RESTRICTED:
confValue = _PC_CHOWN_RESTRICTED;
break;
case PAL_PC_NO_TRUNC:
confValue = _PC_NO_TRUNC;
break;
case PAL_PC_VDISABLE:
confValue = _PC_VDISABLE;
break;
}
if (confValue == -1)
{
assert_msg(false, "Unknown PathConfName", static_cast<int>(name));
errno = EINVAL;
return -1;
}
return pathconf(path, confValue);
}
extern "C" int32_t SystemNative_GetPriority(PriorityWhich which, int32_t who)
{
// GetPriority uses errno 0 to show success to make sure we don't have a stale value
errno = 0;
#if PRIORITY_REQUIRES_INT_WHO
return getpriority(which, who);
#else
return getpriority(which, static_cast<id_t>(who));
#endif
}
extern "C" int32_t SystemNative_SetPriority(PriorityWhich which, int32_t who, int32_t nice)
{
#if PRIORITY_REQUIRES_INT_WHO
return setpriority(which, who, nice);
#else
return setpriority(which, static_cast<id_t>(who), nice);
#endif
}
extern "C" char* SystemNative_GetCwd(char* buffer, int32_t bufferSize)
{
assert(bufferSize >= 0);
if (bufferSize < 0)
{
errno = EINVAL;
return nullptr;
}
return getcwd(buffer, UnsignedCast(bufferSize));
}
#if HAVE_SCHED_SETAFFINITY
extern "C" int32_t SystemNative_SchedSetAffinity(int32_t pid, intptr_t* mask)
{
assert(mask != nullptr);
int maxCpu = sizeof(intptr_t) * 8;
assert(maxCpu <= CPU_SETSIZE);
cpu_set_t set;
CPU_ZERO(&set);
intptr_t bits = *mask;
for (int cpu = 0; cpu < maxCpu; cpu++)
{
if ((bits & static_cast<intptr_t>(1u << cpu)) != 0)
{
CPU_SET(cpu, &set);
}
}
return sched_setaffinity(pid, sizeof(cpu_set_t), &set);
}
#endif
#if HAVE_SCHED_GETAFFINITY
extern "C" int32_t SystemNative_SchedGetAffinity(int32_t pid, intptr_t* mask)
{
assert(mask != nullptr);
cpu_set_t set;
int32_t result = sched_getaffinity(pid, sizeof(cpu_set_t), &set);
if (result == 0)
{
int maxCpu = sizeof(intptr_t) * 8;
assert(maxCpu <= CPU_SETSIZE);
intptr_t bits = 0;
for (int cpu = 0; cpu < maxCpu; cpu++)
{
if (CPU_ISSET(cpu, &set))
{
bits |= (1u << cpu);
}
}
*mask = bits;
}
else
{
*mask = 0;
}
return result;
}
#endif
extern "C" char** SystemNative_GetEnviron()
{
#if HAVE_NSGETENVIRON
return *(_NSGetEnviron());
#else
extern char **environ;
return environ;
#endif
}