Compare commits

..
9 changed files with 300 additions and 221 deletions

No files matched your search

@@ -108,11 +108,7 @@ public class HudMetrics {
} }
private List<String> discoverGpuUsagePaths() { private List<String> discoverGpuUsagePaths() {
if (gpuUsagePathsCache == null) gpuUsagePathsCache = gpuUsagePaths(); if (gpuUsagePathsCache != null) return gpuUsagePathsCache;
return gpuUsagePathsCache;
}
public static List<String> gpuUsagePaths() {
LinkedHashSet<String> candidates = new LinkedHashSet<>(); LinkedHashSet<String> candidates = new LinkedHashSet<>();
for (String p : GPU_USAGE_STATIC_PATHS) { for (String p : GPU_USAGE_STATIC_PATHS) {
@@ -161,7 +157,8 @@ public class HudMetrics {
} }
} }
return new ArrayList<>(candidates); gpuUsagePathsCache = new ArrayList<>(candidates);
return gpuUsagePathsCache;
} }
private static final String[] GPU_USAGE_STATIC_PATHS = { private static final String[] GPU_USAGE_STATIC_PATHS = {
@@ -3,18 +3,11 @@ package com.droiddeck.launcher.session
import android.os.SystemClock import android.os.SystemClock
import android.util.Log import android.util.Log
import com.droiddeck.launcher.core.SessionPart import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.hud.HudMetrics
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File import java.io.File
import java.io.RandomAccessFile import java.io.RandomAccessFile
class GpuStatsComponent( class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
val dir: File,
private val root: File,
private val metrics: HudMetrics? = null,
private val kgsl: Boolean = File(KGSL).exists(),
private val loadNodes: () -> List<String> = HudMetrics::gpuUsagePaths,
) : SessionPart() {
@Volatile private var running = false @Volatile private var running = false
private var thread: Thread? = null private var thread: Thread? = null
private val feeds = ArrayList<Feed>() private val feeds = ArrayList<Feed>()
@@ -30,7 +23,6 @@ class GpuStatsComponent(
) )
fun binds(): List<String> { fun binds(): List<String> {
if (!kgsl) return emptyList()
val list = mutableListOf(dir.path + ":" + KGSL) val list = mutableListOf(dir.path + ":" + KGSL)
if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD) if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD)
if (File(dir, "cur_freq").exists()) list.add(File(dir, "cur_freq").path + ":" + MSM_CLOCK) if (File(dir, "cur_freq").exists()) list.add(File(dir, "cur_freq").path + ":" + MSM_CLOCK)
@@ -41,9 +33,10 @@ class GpuStatsComponent(
sources = "" sources = ""
KgslBusy.status = "not tried" KgslBusy.status = "not tried"
KgslClock.status = "not tried" KgslClock.status = "not tried"
if (!File(KGSL).exists()) return false
val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } } val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }
// Where SELinux hides the kgsl nodes completely (exists() is false too), the layer and cycle-counter feeds stand in. // Where SELinux hides the kgsl nodes completely (exists() is false too), the layer and cycle-counter feeds stand in.
if (kgsl && !unreadable && !File(GPUBUSY).canRead() && !loadBlocked()) return false if (!unreadable && !File(GPUBUSY).canRead() && !loadBlocked()) return false
return try { return try {
dir.mkdirs() dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) } dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
@@ -51,20 +44,19 @@ class GpuStatsComponent(
PASSTHROUGH_FILES.forEach { name -> PASSTHROUGH_FILES.forEach { name ->
runCatching { File(dir, name).writeText(File(KGSL, name).readText()) } runCatching { File(dir, name).writeText(File(KGSL, name).readText()) }
} }
((if (kgsl) loadFeed() else nodeLoadFeed()) ?: blockedLoadFeed())?.let { load -> (loadFeed() ?: blockedLoadFeed())?.let { load ->
feeds.add(load) feeds.add(load)
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true)) feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
} }
(pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) } ?: (if (kgsl) cycleClockFeed() else null))?.let { clock -> (pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) } ?: cycleClockFeed())?.let { clock ->
feeds.add(clock) feeds.add(clock)
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n")) feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
} }
if (kgsl) pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) } pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
if (!kgsl && feeds.isEmpty()) return false
refresh() refresh()
createMissing(feeds.map { it.file }) createMissing(feeds.map { it.file })
describeSources() describeSources()
Log.i(TAG, "hud: GPU stats from the session's own: $sources") Log.i(TAG, "hud: kgsl stats from the session's own: $sources")
true true
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "hud: could not stand in for kgsl stats: $e") Log.w(TAG, "hud: could not stand in for kgsl stats: $e")
@@ -154,10 +146,10 @@ class GpuStatsComponent(
// Vulkan layer and the compositor time their own GPU work until the memstore timestamps are seen moving, and // Vulkan layer and the compositor time their own GPU work until the memstore timestamps are seen moving, and
// for the whole session where they never move. // for the whole session where they never move.
private fun blockedLoadFeed(): Feed? { private fun blockedLoadFeed(): Feed? {
if (!noLoadNode(kgsl, loadNodes)) return null if (!loadBlocked()) return null
val load = LayerLoad(guestLoadDir(root), extra = ::compositorBusyNs, onWanted = ::compositorTiming) val load = LayerLoad(guestLoadDir(root), extra = ::compositorBusyNs, onWanted = ::compositorTiming)
.also { it.clear(); layerLoad = it } .also { it.clear(); layerLoad = it }
val sampled = if (!kgsl) null else KgslBusy.open()?.let { reader -> val sampled = KgslBusy.open()?.let { reader ->
memstore = reader memstore = reader
MemstoreLoad(reader::counts).also { memstoreLoad = it } MemstoreLoad(reader::counts).also { memstoreLoad = it }
} }
@@ -297,12 +289,6 @@ class GpuStatsComponent(
} }
} }
private fun nodeLoadFeed(): Feed? {
val metrics = metrics ?: return null
val node = loadNodes().firstOrNull() ?: return null
return Feed(File(dir, "gpu_busy_percentage"), node, { metrics.gpuUsagePercent?.toLong() }, "%3d %%\n")
}
private fun loadFeed(): Feed? { private fun loadFeed(): Feed? {
latchedBusyFeed()?.let { return it } latchedBusyFeed()?.let { return it }
return pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) } return pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }
@@ -376,14 +362,9 @@ class GpuStatsComponent(
/** True when this app can see kgsl but none of its GPU load nodes (SELinux-blocked, e.g. the Retroid Pocket Duo). */ /** True when this app can see kgsl but none of its GPU load nodes (SELinux-blocked, e.g. the Retroid Pocket Duo). */
fun loadBlocked(): Boolean = File(KGSL).exists() && !File(GPUBUSY).canRead() && LOAD_SOURCES.none { File(it).canRead() } fun loadBlocked(): Boolean = File(KGSL).exists() && !File(GPUBUSY).canRead() && LOAD_SOURCES.none { File(it).canRead() }
private fun noLoadNode(): Boolean = noLoadNode(File(KGSL).exists(), HudMetrics::gpuUsagePaths)
internal fun noLoadNode(kgsl: Boolean, loadNodes: () -> List<String>): Boolean =
if (kgsl) loadBlocked() else loadNodes().isEmpty()
/** Turns on the in-game layer (tools/gpuload) where the load is blocked; empty elsewhere. */ /** Turns on the in-game layer (tools/gpuload) where the load is blocked; empty elsewhere. */
fun guestEnv(root: File): List<String> { fun guestEnv(root: File): List<String> {
if (!noLoadNode()) return emptyList() if (!loadBlocked()) return emptyList()
guestLoadDir(root).mkdirs() guestLoadDir(root).mkdirs()
return listOf("DROIDDECK_GPU_LOAD=1", "DROIDDECK_GPU_LOAD_DIR=$GUEST_LOAD_DIR") return listOf("DROIDDECK_GPU_LOAD=1", "DROIDDECK_GPU_LOAD_DIR=$GUEST_LOAD_DIR")
} }
@@ -4,7 +4,6 @@ import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.SystemVulkanDriver import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.hud.HudMetrics
import android.app.Notification import android.app.Notification
import android.app.NotificationChannel import android.app.NotificationChannel
@@ -1294,7 +1293,7 @@ class SessionService : Service() {
gpuMem.attach(this) gpuMem.attach(this)
components.add(gpuMem) components.add(gpuMem)
} }
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"), LinuxRuntime.rootDir(this), HudMetrics(this)) val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"), LinuxRuntime.rootDir(this))
if (gpuStats.prepare()) { if (gpuStats.prepare()) {
gpuStats.attach(this) gpuStats.attach(this)
components.add(gpuStats) components.add(gpuStats)
@@ -13,7 +13,7 @@ class GpuStatsBindsTest {
@Test fun feedsWithNoValueYetAreStillBound() { @Test fun feedsWithNoValueYetAreStillBound() {
val dir = tmp.newFolder("kgsl-3d0") val dir = tmp.newFolder("kgsl-3d0")
GpuStatsComponent.createMissing(listOf(File(dir, "perf_now"), File(dir, "cur_freq"))) GpuStatsComponent.createMissing(listOf(File(dir, "perf_now"), File(dir, "cur_freq")))
val binds = GpuStatsComponent(dir, tmp.root, kgsl = true).binds() val binds = GpuStatsComponent(dir, tmp.root).binds()
assertTrue(binds.contains(File(dir, "perf_now").path + ":" + GpuStatsComponent.MSM_LOAD)) assertTrue(binds.contains(File(dir, "perf_now").path + ":" + GpuStatsComponent.MSM_LOAD))
assertTrue(binds.contains(File(dir, "cur_freq").path + ":" + GpuStatsComponent.MSM_CLOCK)) assertTrue(binds.contains(File(dir, "cur_freq").path + ":" + GpuStatsComponent.MSM_CLOCK))
} }
@@ -1,57 +0,0 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.hud.HudMetrics
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class GpuStatsComponentWithoutKgslTest {
@get:Rule val tmp = TemporaryFolder()
private val parts = ArrayList<GpuStatsComponent>()
private fun component(nodes: List<String>, metrics: HudMetrics? = null) =
GpuStatsComponent(tmp.newFolder("kgsl-3d0"), tmp.root, metrics, kgsl = false, loadNodes = { nodes }).also { parts += it }
@After fun reset() {
parts.forEach { it.stop() }
KgslBusy.status = "not tried"
KgslClock.status = "not tried"
}
@Test fun noReadableLoadNodeWithoutKgslTurnsTheTimingFeedOn() {
assertTrue(GpuStatsComponent.noLoadNode(false) { emptyList() })
assertFalse(GpuStatsComponent.noLoadNode(false) { listOf(MALI_NODE) })
}
@Test fun kgslDevicesIgnoreOtherGpusNodes() {
val decided = GpuStatsComponent.noLoadNode(true) { throw AssertionError("kgsl devices read other GPUs' nodes") }
assertEquals(GpuStatsComponent.loadBlocked(), decided)
}
@Test fun withoutAnyLoadNodeTheHudLoadComesFromVulkanTiming() {
val gpu = component(emptyList())
assertTrue(gpu.prepare())
assertTrue(GpuStatsComponent.sources, GpuStatsComponent.sources.startsWith("gpu_busy_percentage Vulkan timing"))
assertTrue(File(gpu.dir, "perf_now").isFile)
assertEquals(emptyList<String>(), gpu.binds())
assertEquals("", GpuStatsComponent.readerStatus())
}
@Test fun aReadableLoadNodeFeedsTheHudInsteadOfTheLayer() {
val gpu = component(listOf(MALI_NODE), HudMetrics(null))
assertTrue(gpu.prepare())
assertTrue(GpuStatsComponent.sources, GpuStatsComponent.sources.startsWith("gpu_busy_percentage $MALI_NODE"))
assertTrue(File(gpu.dir, "perf_now").isFile)
assertFalse(File(GpuStatsComponent.guestLoadDir(tmp.root), "on").exists())
assertEquals("", GpuStatsComponent.readerStatus())
}
private companion object {
const val MALI_NODE = "/sys/class/misc/mali0/device/utilisation"
}
}
+17
View File
@@ -0,0 +1,17 @@
#define _GNU_SOURCE
#if defined(__x86_64__) || defined(__i386__)
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "named_semaphores.h"
#endif
+127
View File
@@ -0,0 +1,127 @@
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) + 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%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
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);
}
+1 -126
View File
@@ -6,17 +6,7 @@
#ifndef DDNATV_HOST_TEST #ifndef DDNATV_HOST_TEST
static int posix_shm_path(const char *name, const char *prefix, char *path, size_t size) { #include "../../linuxfs/preload/named_semaphores.h"
if (!name) { errno = EINVAL; return -1; }
while (*name == '/') name++;
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%s", prefix, name) >= (int)size) { errno = ENAMETOOLONG; return -1; }
return 0;
}
int shm_open(const char *name, int oflag, mode_t mode) { int shm_open(const char *name, int oflag, mode_t mode) {
char path[PATH_MAX]; char path[PATH_MAX];
@@ -30,121 +20,6 @@ int shm_unlink(const char *name) {
return unlink(path); 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);
}
#endif /* !DDNATV_HOST_TEST */ #endif /* !DDNATV_HOST_TEST */
@@ -0,0 +1,140 @@
from pathlib import Path
import os
import platform
import shutil
import subprocess
import sys
import tempfile
import unittest
from tools.tests.test_native_hook_named_semaphores import CALLS, KEEP, PROBE
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
DENY_LINKS = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_link, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_linkat, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {sizeof(filter) / sizeof(filter[0]), filter};
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) || prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) return 125;
execvp(argv[1], argv + 1);
return 126;
}
"""
OPEN_EXISTING = r"""
#include <fcntl.h>
#include <semaphore.h>
#include <stdlib.h>
int main(int argc, char **argv) {
sem_t *sem = sem_open(argv[1], 0);
int value;
if (sem == SEM_FAILED || sem_getvalue(sem, &value) || value != atoi(argv[2])) return 1;
return sem_trywait(sem) || sem_close(sem);
}
"""
PYTHON_PROBE = '''
import multiprocessing as mp
import _multiprocessing
import os
import sys
def square(n):
return n * n
if __name__ == "__main__":
name = "/dd-py-sem-" + str(os.getpid())
sem = _multiprocessing.SemLock(1, 1, 1, name, True)
assert sem.acquire(False)
assert not sem.acquire(False)
sem.release()
for method in mp.get_all_start_methods():
ctx = mp.get_context(method)
lock = ctx.Lock()
with lock:
assert not lock.acquire(False)
queue = ctx.Queue()
queue.put(7)
assert queue.get(timeout=10) == 7
queue.close()
queue.join_thread()
with ctx.Pool(2) as pool:
assert pool.map(square, [1, 2, 3]) == [1, 4, 9]
print(method, flush=True)
'''
@unittest.skipUnless(platform.machine() == "x86_64" and shutil.which("cc"), "needs an x86-64 compiler and host")
class NamedSemaphoresPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = tempfile.TemporaryDirectory()
cls.addClassCleanup(cls.tmp.cleanup)
cls.root = Path(cls.tmp.name)
cls.lib = cls.root / "semaphores.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-Werror", "-pthread", "-o", str(cls.lib),
str(PRELOAD / "named_semaphores.c")], check=True)
for name, source in (("deny", DENY_LINKS), ("probe", PROBE), ("keep", KEEP), ("existing", OPEN_EXISTING)):
path = cls.root / (name + ".c")
path.write_text(source)
subprocess.run(["cc", "-pthread", "-o", str(cls.root / name), str(path)], check=True)
cls.script = cls.root / "pool.py"
cls.script.write_text(PYTHON_PROBE)
def run_program(self, args, hooked=True, denied=True):
env = dict(os.environ)
env.pop("LD_PRELOAD", None)
if hooked:
env["LD_PRELOAD"] = str(self.lib)
command = ([str(self.root / "deny")] if denied else []) + list(map(str, args))
return subprocess.run(command, env=env, text=True, capture_output=True, timeout=60)
def test_glibc_semlock_fails_when_hard_links_are_denied(self):
result = self.run_program([sys.executable, "-c",
"import multiprocessing; multiprocessing.Lock()"], hooked=False)
self.assertNotEqual(0, result.returncode)
self.assertIn("PermissionError: [Errno 1]", result.stderr)
def test_named_semaphore_contract_with_and_without_hard_links(self):
for denied in (True, False):
with self.subTest(denied=denied):
result = self.run_program([self.root / "probe", f"/dd-preload-{os.getpid()}-{int(denied)}"], denied=denied)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual({call: "1" for call in CALLS}, dict(line.split("\t") for line in result.stdout.splitlines()))
def test_semaphores_remain_compatible_with_glibc_and_keep_the_requested_mode(self):
for hooked in (True, False):
with self.subTest(creator_hooked=hooked):
name = f"/dd-preload-existing-{os.getpid()}-{int(hooked)}"
path = Path("/dev/shm/sem." + name[1:])
self.addCleanup(path.unlink, missing_ok=True)
result = self.run_program([self.root / "keep", name], hooked=hooked, denied=hooked)
self.assertEqual(0, result.returncode, result.stderr)
umask = os.umask(0)
os.umask(umask)
self.assertEqual(0o640 & ~umask, path.stat().st_mode & 0o777)
for reader, value in ((not hooked, 3), (hooked, 2)):
result = self.run_program([self.root / "existing", name, value], hooked=reader, denied=reader)
self.assertEqual(0, result.returncode, result.stderr)
def test_python_semlock_queues_and_explicit_pool_contexts(self):
for denied in (True, False):
with self.subTest(denied=denied):
result = self.run_program([sys.executable, self.script], denied=denied)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual({"fork", "forkserver", "spawn"}, set(result.stdout.splitlines()))