Skip to content

Commit 946f3dd

Browse files
committed
preload: Trap relative paths into mocked directories
Fix trap_path() to try and get an absolute path argument, so that relative paths into the mocked /sys work as expected.
1 parent 0e60ddb commit 946f3dd

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/libumockdev-preload.c

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,11 @@ static size_t trap_path_prefix_len = 0;
141141
static const char *
142142
trap_path(const char *path)
143143
{
144+
libc_func(realpath, char *, const char *, char *);
145+
static char abspath_buf[PATH_MAX];
144146
static char buf[PATH_MAX * 2];
145147
const char *prefix;
148+
const char *abspath = NULL;
146149
size_t path_len;
147150
int check_exist = 0;
148151

@@ -154,12 +157,22 @@ trap_path(const char *path)
154157
if (prefix == NULL)
155158
return path;
156159

157-
if (strncmp(path, "/dev/", 5) == 0 || strcmp(path, "/dev") == 0 || strncmp(path, "/proc/", 6) == 0)
160+
if (path[0] != '/') {
161+
int orig_errno = errno;
162+
abspath = _realpath(path, abspath_buf);
163+
errno = orig_errno;
164+
if (abspath)
165+
DBG(DBG_PATH, "trap_path relative %s -> absolute %s\n", path, abspath);
166+
}
167+
if (!abspath)
168+
abspath = path;
169+
170+
if (strncmp(abspath, "/dev/", 5) == 0 || strcmp(abspath, "/dev") == 0 || strncmp(abspath, "/proc/", 6) == 0)
158171
check_exist = 1;
159-
else if (strncmp(path, "/sys/", 5) != 0 && strcmp(path, "/sys") != 0)
172+
else if (strncmp(abspath, "/sys/", 5) != 0 && strcmp(abspath, "/sys") != 0)
160173
return path;
161174

162-
path_len = strlen(path);
175+
path_len = strlen(abspath);
163176
trap_path_prefix_len = strlen(prefix);
164177
if (path_len + trap_path_prefix_len >= sizeof(buf)) {
165178
errno = ENAMETOOLONG;
@@ -172,7 +185,7 @@ trap_path(const char *path)
172185
if (path_exists(buf) == 0)
173186
return path;
174187

175-
strcpy(buf + trap_path_prefix_len, path);
188+
strcpy(buf + trap_path_prefix_len, abspath);
176189

177190
if (check_exist && path_exists(buf) < 0)
178191
return path;

tests/test-umockdev-vala.vala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,17 @@ t_testbed_fs_ops ()
150150
assert_cmpint (Posix.chdir ("/sys/class"), Op.EQ, -1);
151151
assert_cmpint (Posix.errno, Op.EQ, Posix.ENOENT);
152152

153+
// relative paths into trapped /sys
154+
assert_cmpint (Posix.chdir ("/"), Op.EQ, 0);
155+
assert_listdir ("sys", {"bus", "devices"});
156+
assert_listdir ("sys/devices", {"dev1"});
157+
assert_listdir ("sys/bus", {"pci"});
158+
159+
assert_cmpint (Posix.chdir ("/etc"), Op.EQ, 0);
160+
assert_listdir ("../sys", {"bus", "devices"});
161+
assert_listdir ("../sys/devices", {"dev1"});
162+
assert_listdir ("../sys/bus", {"pci"});
163+
153164
assert_cmpint (Posix.chdir (orig_cwd), Op.EQ, 0);
154165
}
155166

0 commit comments

Comments
 (0)