summaryrefslogtreecommitdiffstats
path: root/usr/kinit/readfile.c
blob: 7a16b4a655b1934451ed848249e395c721a1eb4d (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Read the entire contents of a file into malloc'd storage.  This
 * is mostly useful for things like /proc files where we can't just
 * fstat() to get the length and then mmap().
 *
 * Returns the number of bytes read, or -1 on error.
 */

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>

#include "kinit.h"

ssize_t freadfile(FILE *f, char **pp)
{
	size_t bs;		/* Decent starting point... */
	size_t bf;		/* Bytes free */
	size_t bu = 0;		/* Bytes used */
	char *buffer, *nb;
	size_t rv;
	int old_errno = errno;

	bs = BUFSIZ;		/* A guess as good as any */
	bf = bs;
	buffer = malloc(bs);

	if (!buffer)
		return -1;

	for (;;) {
		errno = 0;

		while (bf && (rv = _fread(buffer + bu, bf, f))) {
			bu += rv;
			bf -= rv;
		}

		if (errno && errno != EINTR && errno != EAGAIN) {
			/* error */
			free(buffer);
			return -1;
		}

		if (bf) {
			/* Hit EOF, no error */

			/* Try to free superfluous memory */
			if ((nb = realloc(buffer, bu + 1)))
				buffer = nb;

			/* Null-terminate result for good measure */
			buffer[bu] = '\0';

			*pp = buffer;
			errno = old_errno;
			return bu;
		}

		/* Double the size of the buffer */
		bf += bs;
		bs += bs;
		if (!(nb = realloc(buffer, bs))) {
			/* out of memory error */
			free(buffer);
			return -1;
		}
		buffer = nb;
	}
}

ssize_t readfile(const char *filename, char **pp)
{
	FILE *f = fopen(filename, "r");
	ssize_t rv;

	if (!f)
		return -1;

	rv = freadfile(f, pp);

	fclose(f);

	return rv;
}