fix(hook): named semaphores live where the session maps /dev/shm (#3110)

* fix(hook): named semaphores live where the session maps /dev/shm

* fix(hook): a semaphore opened twice is one mapping, mapped before its name is published

* fix(nativeguest): a fork while another thread opens a semaphore leaves the child a usable registry

* Native hook: register the semaphore fork handlers at load
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-23 22:53:19 -05:00
1 parent f9304f41c7
commit cd87718ac2
3 files changed
+285 -9

No files matched your search

+1
View File
@@ -41,6 +41,7 @@
#include <elf.h>
#include <sys/sendfile.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sched.h>
#include <time.h>
#include <sys/xattr.h>
+125 -9
View File
@@ -1,32 +1,148 @@
// Part of libddnatv-hook.so, included by ddnatv-hook.c.
//
// shm_open() and shm_unlink() of glibc open /dev/shm/NAME with a system call of their own, which
// the path hooks never see and Android has no /dev/shm for. They go through open() and unlink()
// here, which map /dev/shm.
// shm_open(), shm_unlink() and the named semaphores of glibc open /dev/shm/NAME with system calls
// of their own, which the path hooks never see and Android has no /dev/shm for. They go through
// open(), renameat2() and unlink() here, which map /dev/shm.
#ifndef DDNATV_HOST_TEST
static int posix_shm_path(const char *name, char *path, size_t size) {
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) {
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
size_t len = strlen(name);
if (len == 0 || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
size_t len = strlen(name) + strlen(prefix);
if (len == strlen(prefix) || len > NAME_MAX || strchr(name, '/') || strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
errno = len > NAME_MAX ? ENAMETOOLONG : EINVAL;
return -1;
}
if (snprintf(path, size, "/dev/shm/%s", name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
if (snprintf(path, size, "/dev/shm/%s%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
int shm_open(const char *name, int oflag, mode_t mode) {
char path[PATH_MAX];
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
return open(path, (oflag & (O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC)) | O_NOFOLLOW | O_CLOEXEC, mode);
}
int shm_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, path, sizeof(path)) < 0) return -1;
if (posix_shm_path(name, "", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
struct posix_sem {
dev_t dev;
ino_t ino;
sem_t *addr;
unsigned int refs;
struct posix_sem *next;
};
static struct posix_sem *g_posix_sems;
static pthread_mutex_t g_posix_sems_lock = PTHREAD_MUTEX_INITIALIZER;
static void posix_sems_unlock(void) { pthread_mutex_unlock(&g_posix_sems_lock); }
static void posix_sems_hold(void) { pthread_mutex_lock(&g_posix_sems_lock); }
__attribute__((constructor)) static void posix_sems_across_fork(void) {
pthread_atfork(posix_sems_hold, posix_sems_unlock, posix_sems_unlock);
}
static void close_keeping_errno(int fd) {
int saved = errno;
close(fd);
errno = saved;
}
static sem_t *posix_sem_map(int fd) {
struct stat st;
if (fstat(fd, &st) < 0) return SEM_FAILED;
sem_t *sem = SEM_FAILED;
posix_sems_hold();
struct posix_sem *e = g_posix_sems;
while (e && (e->dev != st.st_dev || e->ino != st.st_ino)) e = e->next;
if (e) {
e->refs++;
sem = e->addr;
} else {
void *addr = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
e = addr == MAP_FAILED ? NULL : malloc(sizeof(*e));
if (e) {
*e = (struct posix_sem){st.st_dev, st.st_ino, addr, 1, g_posix_sems};
g_posix_sems = e;
sem = addr;
} else if (addr != MAP_FAILED) {
munmap(addr, sizeof(sem_t));
errno = ENOMEM;
}
}
posix_sems_unlock();
return sem;
}
static sem_t *posix_sem_open_fd(int fd) {
if (fd < 0) return SEM_FAILED;
sem_t *sem = posix_sem_map(fd);
close_keeping_errno(fd);
return sem;
}
sem_t *sem_open(const char *name, int oflag, ...) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return SEM_FAILED;
if (!(oflag & O_CREAT)) return posix_sem_open_fd(open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC));
va_list args;
va_start(args, oflag);
mode_t mode = va_arg(args, mode_t);
unsigned int value = va_arg(args, unsigned int);
va_end(args);
static unsigned int serial;
for (;;) {
if (!(oflag & O_EXCL)) {
int fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC);
if (fd >= 0 || errno != ENOENT) return posix_sem_open_fd(fd);
}
if (value > SEM_VALUE_MAX) { errno = EINVAL; return SEM_FAILED; }
sem_t initial;
memset(&initial, 0, sizeof(initial));
sem_init(&initial, 1, value);
char temp[PATH_MAX];
int fd;
do {
snprintf(temp, sizeof(temp), "/dev/shm/.sem-%d-%u", (int)getpid(), __atomic_fetch_add(&serial, 1, __ATOMIC_RELAXED));
fd = open(temp, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
} while (fd < 0 && errno == EEXIST);
if (fd < 0) return SEM_FAILED;
errno = EIO;
sem_t *sem = write(fd, &initial, sizeof(initial)) == (ssize_t)sizeof(initial) ? posix_sem_map(fd) : SEM_FAILED;
close_keeping_errno(fd);
if (sem != SEM_FAILED && renameat2(AT_FDCWD, temp, AT_FDCWD, path, RENAME_NOREPLACE) == 0) return sem;
int saved = errno;
if (sem != SEM_FAILED) sem_close(sem);
unlink(temp);
errno = saved;
if (errno != EEXIST || (oflag & O_EXCL)) return SEM_FAILED;
}
}
int sem_close(sem_t *sem) {
posix_sems_hold();
struct posix_sem **link = &g_posix_sems;
while (*link && (*link)->addr != sem) link = &(*link)->next;
struct posix_sem *e = *link;
if (e && --e->refs == 0) {
*link = e->next;
munmap(e->addr, sizeof(sem_t));
free(e);
}
posix_sems_unlock();
if (!e) { errno = EINVAL; return -1; }
return 0;
}
int sem_unlink(const char *name) {
char path[PATH_MAX];
if (posix_shm_path(name, "sem.", path, sizeof(path)) < 0) return -1;
return unlink(path);
}
@@ -0,0 +1,159 @@
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <semaphore.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
static void show(const char *name, int ok) { printf("%s\t%d\n", name, ok); fflush(stdout); }
int main(int argc, char **argv) {
const char *name = argv[1];
sem_t *sem = sem_open(name, O_CREAT | O_EXCL, 0600, 1);
show("create", sem != SEM_FAILED);
show("exclusive", sem_open(name, O_CREAT | O_EXCL, 0600, 1) == SEM_FAILED && errno == EEXIST);
sem_t *again = sem_open(name, O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1);
int value = -1;
show("existing", again == sem && sem_getvalue(again, &value) == 0 && value == 1);
show("too-large", sem_open("/ddsem-absent", O_CREAT, 0600, (unsigned int)SEM_VALUE_MAX + 1) == SEM_FAILED && errno == EINVAL);
show("wait", sem_wait(sem) == 0 && sem_trywait(again) == -1 && errno == EAGAIN);
pid_t child = fork();
if (child == 0) {
sem_t *other = sem_open(name, 0);
_exit(other != SEM_FAILED && sem_post(other) == 0 && sem_close(other) == 0 ? 0 : 1);
}
int status = 0;
waitpid(child, &status, 0);
show("shared", WIFEXITED(status) && WEXITSTATUS(status) == 0 && sem_trywait(sem) == 0);
show("close", sem_close(again) == 0 && sem_post(sem) == 0 && sem_close(sem) == 0 && sem_close(sem) == -1 && errno == EINVAL);
show("unlink", sem_unlink(name) == 0);
show("gone", sem_open(name, 0) == SEM_FAILED && errno == ENOENT);
return 0;
}
"""
KEEP = r"""
#include <fcntl.h>
#include <semaphore.h>
int main(int argc, char **argv) { return sem_open(argv[1], O_CREAT | O_EXCL, 0640, 3) == SEM_FAILED; }
"""
FORKER = r"""
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
static const char *name;
static _Atomic int done;
static void *churn(void *arg) {
while (!done) {
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
if (sem != SEM_FAILED) sem_close(sem);
}
return arg;
}
int main(int argc, char **argv) {
name = argv[1];
pthread_t thread;
if (pthread_create(&thread, NULL, churn, NULL) != 0) return 1;
int finished = 0;
for (int i = 0; i < 200; i++) {
pid_t pid = fork();
if (pid < 0) break;
if (pid == 0) {
alarm(10);
sem_t *sem = sem_open(name, O_CREAT, 0600, 0);
_exit(sem == SEM_FAILED || sem_close(sem) != 0);
}
int status;
if (waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0) finished++;
}
done = 1;
pthread_join(thread, NULL);
sem_unlink(name);
printf("finished\t%d\n", finished);
return 0;
}
"""
CALLS = ("create", "exclusive", "existing", "too-large", "wait", "shared", "close", "unlink", "gone")
class NativeHookNamedSemaphoresTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory(dir="/tmp")
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-pthread", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.shm = tmp / "root/tmp/shm"
cls.shm.mkdir(parents=True)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_hooked(self, program, *args):
hook_env = {"DDNATV_ROOT": str(self.shm.parent.parent), "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
out = subprocess.run(cmd + [str(program), *args], env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return dict(line.split("\t") for line in out.stdout.splitlines())
def test_a_named_semaphore_lives_in_the_rootfs_and_is_shared_between_processes(self):
name = f"/ddsem-{os.getpid()}"
self.assertEqual({call: "1" for call in CALLS}, self.run_hooked(self.probe, name))
self.assertFalse(Path(f"/dev/shm/sem.{name[1:]}").exists())
self.assertEqual([], list(self.shm.iterdir()))
def test_a_child_forked_while_another_thread_opens_a_semaphore_can_open_one(self):
source = self.probe.with_name("forker.c")
source.write_text(FORKER)
forker = self.probe.with_name("forker")
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(forker), str(source)], check=True)
self.assertEqual({"finished": "200"}, self.run_hooked(forker, f"/ddsem-fork-{os.getpid()}"))
def test_a_created_semaphore_keeps_its_name_and_mode(self):
name = f"ddsem-kept-{os.getpid()}"
source = self.probe.with_name("keep.c")
source.write_text(KEEP)
keep = self.probe.with_name("keep")
subprocess.run([self.cc, "-O1", "-pthread", "-o", str(keep), str(source)], check=True)
self.run_hooked(keep, name)
made = self.shm / f"sem.{name}"
self.addCleanup(made.unlink)
umask = os.umask(0)
os.umask(umask)
self.assertEqual([made.name], [p.name for p in self.shm.iterdir()])
self.assertEqual(0o640 & ~umask, made.stat().st_mode & 0o777)
if __name__ == "__main__":
unittest.main()