Skip to content

Commit 2339e72

Browse files
committed
util: Add read_file() function for reading sysfs files
Add a function that can read a complete, unknown size file for reading entry point files from sysfs. This function models its signature on the mem_chunk() funtion, so it also allocates memory that the caller needs to free. The files that we are interested in reading are very small, and have a known upper bound on the size. The EINTR handling is based on the myread() function. Contributed by Roy Franz.
1 parent 7d2339a commit 2339e72

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

CHANGELOG

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
2015-04-21 Roy Franz <[email protected]>
2+
3+
* util.c, util.h: Add utility function read_file, which reads an
4+
entire binary file into a buffer.
5+
16
2015-04-20 Jean Delvare <[email protected]>
27

38
* biosdecode.c: Add support for the _SM3_ entry point, as defined in

util.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,61 @@ int checksum(const u8 *buf, size_t len)
8888
return (sum == 0);
8989
}
9090

91+
/*
92+
* Reads all of file, up to max_len bytes.
93+
* A buffer of max_len bytes is allocated by this function, and
94+
* needs to be freed by the caller.
95+
* This provides a similar usage model to mem_chunk()
96+
*
97+
* Returns pointer to buffer of max_len bytes, or NULL on error
98+
*
99+
*/
100+
void *read_file(size_t max_len, const char *filename)
101+
{
102+
int fd;
103+
size_t r2 = 0;
104+
ssize_t r;
105+
u8 *p;
106+
107+
/*
108+
* Don't print error message on missing file, as we will try to read
109+
* files that may or may not be present.
110+
*/
111+
if ((fd = open(filename, O_RDONLY)) == -1)
112+
{
113+
if (errno != ENOENT)
114+
perror(filename);
115+
return(NULL);
116+
}
117+
118+
if ((p = malloc(max_len)) == NULL)
119+
{
120+
perror("malloc");
121+
return NULL;
122+
}
123+
124+
do
125+
{
126+
r = read(fd, p + r2, max_len - r2);
127+
if (r == -1)
128+
{
129+
if (errno != EINTR)
130+
{
131+
close(fd);
132+
perror(filename);
133+
free(p);
134+
return NULL;
135+
}
136+
}
137+
else
138+
r2 += r;
139+
}
140+
while (r != 0);
141+
142+
close(fd);
143+
return p;
144+
}
145+
91146
/*
92147
* Copy a physical memory chunk into a memory buffer.
93148
* This function allocates memory.

util.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
2626

2727
int checksum(const u8 *buf, size_t len);
28+
void *read_file(size_t len, const char *filename);
2829
void *mem_chunk(size_t base, size_t len, const char *devmem);
2930
int write_dump(size_t base, size_t len, const void *data, const char *dumpfile, int add);
3031
u64 u64_range(u64 start, u64 end);

0 commit comments

Comments
 (0)