summaryrefslogtreecommitdiff
path: root/chip/host/persistence.c
blob: c712d01414d6b5db04c90b30e008b9fd299782a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* Copyright 2013 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/* Persistence module for emulator */

#include <assert.h>
#include <linux/limits.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

static void get_storage_path(char *out)
{
	char buf[PATH_MAX];
	int sz;
	char *current;

	sz = readlink("/proc/self/exe", buf, PATH_MAX - 1);
	buf[sz] = '\0';

	/* replace / by underscores in the path to get the shared memory name */
	current = strchr(buf, '/');
	while (current) {
		*current = '_';
		current = strchr(current, '/');
	}

	assert(snprintf(out, PATH_MAX - 1, "/dev/shm/EC_persist_%s", buf) > 0);
	out[PATH_MAX - 1] = '\0';
}

FILE *get_persistent_storage(const char *tag, const char *mode)
{
	char buf[PATH_MAX];
	char path[PATH_MAX];

	/*
	 * The persistent storage with tag 'foo' for test 'bar' would
	 * be named 'bar_persist_foo'
	 */
	get_storage_path(buf);
	assert(snprintf(path, PATH_MAX - 1, "%s_%s", buf, tag) > 0);
	path[PATH_MAX - 1] = '\0';

	return fopen(path, mode);
}

void release_persistent_storage(FILE *ps)
{
	fclose(ps);
}

void remove_persistent_storage(const char *tag)
{
	char buf[PATH_MAX];
	char path[PATH_MAX];

	get_storage_path(buf);
	assert(snprintf(path, PATH_MAX - 1, "%s_%s", buf, tag) > 0);
	path[PATH_MAX - 1] = '\0';

	unlink(path);
}