1570af302Sopenharmony_ci#define _GNU_SOURCE
2570af302Sopenharmony_ci#include <unistd.h>
3570af302Sopenharmony_ci#include <signal.h>
4570af302Sopenharmony_ci#include "syscall.h"
5570af302Sopenharmony_ci#include "libc.h"
6570af302Sopenharmony_ci
7570af302Sopenharmony_cistruct ctx {
8570af302Sopenharmony_ci	size_t count;
9570af302Sopenharmony_ci	const gid_t *list;
10570af302Sopenharmony_ci	int ret;
11570af302Sopenharmony_ci};
12570af302Sopenharmony_ci
13570af302Sopenharmony_cistatic void do_setgroups(void *p)
14570af302Sopenharmony_ci{
15570af302Sopenharmony_ci	struct ctx *c = p;
16570af302Sopenharmony_ci	if (c->ret<0) return;
17570af302Sopenharmony_ci	int ret = __syscall(SYS_setgroups, c->count, c->list);
18570af302Sopenharmony_ci	if (ret && !c->ret) {
19570af302Sopenharmony_ci		/* If one thread fails to set groups after another has already
20570af302Sopenharmony_ci		 * succeeded, forcibly killing the process is the only safe
21570af302Sopenharmony_ci		 * thing to do. State is inconsistent and dangerous. Use
22570af302Sopenharmony_ci		 * SIGKILL because it is uncatchable. */
23570af302Sopenharmony_ci		__block_all_sigs(0);
24570af302Sopenharmony_ci		__syscall(SYS_kill, __syscall(SYS_getpid), SIGKILL);
25570af302Sopenharmony_ci	}
26570af302Sopenharmony_ci	c->ret = ret;
27570af302Sopenharmony_ci}
28570af302Sopenharmony_ci
29570af302Sopenharmony_ciint setgroups(size_t count, const gid_t list[])
30570af302Sopenharmony_ci{
31570af302Sopenharmony_ci	/* ret is initially nonzero so that failure of the first thread does not
32570af302Sopenharmony_ci	 * trigger the safety kill above. */
33570af302Sopenharmony_ci	struct ctx c = { .count = count, .list = list, .ret = 1 };
34570af302Sopenharmony_ci	__synccall(do_setgroups, &c);
35570af302Sopenharmony_ci	return __syscall_ret(c.ret);
36570af302Sopenharmony_ci}
37