File: cache.c

package info (click to toggle)
radare2 0.9.6-3.1%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 17,496 kB
  • ctags: 45,959
  • sloc: ansic: 240,999; sh: 3,645; makefile: 2,520; python: 1,212; asm: 312; ruby: 214; awk: 209; perl: 188; lisp: 169; java: 23; xml: 17; php: 6
file content (74 lines) | stat: -rw-r--r-- 1,632 bytes parent folder | download | duplicates (2)
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
66
67
68
69
70
71
72
73
74
/* radare - LGPL - Copyright 2013 - pancake */

#include <r_util.h>
// TODO: optimize reallocs.. store RBuffer info.. wait. extend r_buf_ for that?

R_API RCache *r_cache_new() {
	RCache *c = R_NEW (RCache);
	c->buf = NULL;
	c->base = 0;
	c->len = 0;
	return c;
}

R_API void r_cache_free(RCache *c) {
	free (c->buf);
	free (c);
}

R_API const ut8* r_cache_get(RCache *c, ut64 addr, int *len) {
	if (!c->buf)
		return NULL;
	if (len) *len = c->base - addr;
	if (addr<c->base)
		return NULL;
	if (addr>(c->base+c->len))
		return NULL;
	if (len) *len = c->len - (addr-c->base);
//eprintf ("4 - %d\n", (addr-c->base));
	return c->buf + (addr-c->base);
}

R_API int r_cache_set(RCache *c, ut64 addr, const ut8 *buf, int len) {
	if (c->buf == NULL) {
		c->buf = malloc (len);
		if (!c->buf) return 0;
		memcpy (c->buf, buf, len);
		c->base = addr;
		c->len = len;
	} else
	if (addr < c->base) {
		ut8 *b;
		int baselen = (c->base - addr);
		int newlen = baselen + ((len > c->len)? len: c->base);
		// XXX expensive heap usage. must simplify
		b = malloc (newlen);
		if (!b) return 0;
		memset (b, 0xff, newlen);
		memcpy (b+baselen, c->buf, c->len);
		memcpy (b, buf, len);
		free (c->buf);
		c->buf = b;
		c->base = addr;
		c->len = newlen;
	} else if ((addr+len)>(c->base+c->len)) {
		ut8 *b;
		int baselen = (addr - c->base);
		int newlen = baselen + len;
		b = realloc (c->buf, newlen);
		if (!b) return 0;
		memcpy (b+baselen, buf, len);
		c->buf = b;
		c->len = newlen;
	} else {
		memcpy (c->buf, buf, len);
	}
	return c->len;
}

R_API void r_cache_flush (RCache *c) {
	c->base = 0;
	c->len = 0;
	free (c->buf);
	c->buf = NULL;
}