]> git.proxmox.com Git - mirror_qemu.git/blame - util/path.c
Merge tag 'pull-maintainer-may24-160524-2' of https://gitlab.com/stsquad/qemu into...
[mirror_qemu.git] / util / path.c
CommitLineData
84778508
BS
1/* Code to mangle pathnames into those matching a given prefix.
2 eg. open("/lib/foo.so") => open("/usr/gnemul/i386-linux/lib/foo.so");
3
4 The assumption is that this area does not change.
5*/
aafd7584 6#include "qemu/osdep.h"
84778508
BS
7#include <sys/param.h>
8#include <dirent.h>
f348b6d1
VB
9#include "qemu/cutils.h"
10#include "qemu/path.h"
f3a8bdc1 11#include "qemu/thread.h"
84778508 12
f3a8bdc1
RH
13static const char *base;
14static GHashTable *hash;
15static QemuMutex lock;
84778508 16
f3a8bdc1 17void init_paths(const char *prefix)
84778508 18{
f3a8bdc1
RH
19 if (prefix[0] == '\0' || !strcmp(prefix, "/")) {
20 return;
84778508 21 }
2296f194 22
f3a8bdc1
RH
23 if (prefix[0] == '/') {
24 base = g_strdup(prefix);
25 } else {
26 char *cwd = g_get_current_dir();
27 base = g_build_filename(cwd, prefix, NULL);
28 g_free(cwd);
2296f194 29 }
84778508 30
f3a8bdc1
RH
31 hash = g_hash_table_new(g_str_hash, g_str_equal);
32 qemu_mutex_init(&lock);
84778508
BS
33}
34
f3a8bdc1
RH
35/* Look for path in emulation dir, otherwise return name. */
36const char *path(const char *name)
84778508 37{
f3a8bdc1
RH
38 gpointer key, value;
39 const char *ret;
84778508 40
f3a8bdc1
RH
41 /* Only do absolute paths: quick and dirty, but should mostly be OK. */
42 if (!base || !name || name[0] != '/') {
43 return name;
44 }
84778508 45
f3a8bdc1 46 qemu_mutex_lock(&lock);
84778508 47
f3a8bdc1
RH
48 /* Have we looked up this file before? */
49 if (g_hash_table_lookup_extended(hash, name, &key, &value)) {
50 ret = value ? value : name;
84778508 51 } else {
f3a8bdc1
RH
52 char *save = g_strdup(name);
53 char *full = g_build_filename(base, name, NULL);
54
55 /* Look for the path; record the result, pass or fail. */
56 if (access(full, F_OK) == 0) {
57 /* Exists. */
58 g_hash_table_insert(hash, save, full);
59 ret = full;
60 } else {
61 /* Does not exist. */
62 g_free(full);
63 g_hash_table_insert(hash, save, NULL);
64 ret = name;
65 }
84778508 66 }
84778508 67
f3a8bdc1
RH
68 qemu_mutex_unlock(&lock);
69 return ret;
84778508 70}