blob: d2aff462bf0d1239e777d88256f82daa3486079d [file] [log] [blame]
Ronald G. Minnich5d01ec02009-03-31 11:57:36 +00001/*
2 * romtool
3 *
4 * Copyright (C) 2008 Jordan Crouse <jordan@cosmicpenguin.net>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA, 02110-1301 USA
18 */
19
20#include <stdio.h>
21#include "elf.h"
22#include <stdlib.h>
23#include <string.h>
24#include <unistd.h>
25#include <fcntl.h>
26#include <sys/stat.h>
27
28#include "common.h"
29
30#define BLOCKSIZE (1024 * 16)
31
32void file_write_from_buffer(int fd, unsigned char *buffer, int size)
33{
34 unsigned char *ptr = buffer;
35
36 while (size) {
37 int ret = write(fd, ptr, size);
38
39 if (ret == -1)
40 break;
41
42 size -= ret;
43 ptr += ret;
44 }
45}
46
47unsigned char *file_read_to_buffer(int fd, int *fsize)
48{
49 unsigned char *buffer = malloc(BLOCKSIZE);
50 unsigned char *ptr = buffer;
51
52 int bsize = BLOCKSIZE;
53 int remain = BLOCKSIZE;
54 int size = 0;
55 int ret;
56
57 if (buffer == NULL)
58 return NULL;
59
60 while (1) {
61 ret = read(fd, ptr, remain);
62
63 if (ret <= 0)
64 break;
65
66 remain -= ret;
67 ptr += ret;
68 size += ret;
69
70 /* Allocate more memory */
71
72 if (remain == 0) {
73 buffer = realloc(buffer, bsize + BLOCKSIZE);
74
75 if (buffer == NULL)
76 return NULL;
77
78 ptr = buffer + size;
79
80 bsize += BLOCKSIZE;
81 remain = BLOCKSIZE;
82 }
83 }
84
85 if (ret == 0) {
86 *fsize = size;
87 return buffer;
88 }
89
90 *fsize = 0;
91 free(buffer);
92 return NULL;
93}
94
95unsigned char *file_read(const char *filename, int *fsize)
96{
97 int fd = open(filename, O_RDONLY);
98 unsigned char *buffer;
99
100 if (fd == -1)
101 return NULL;
102
103 buffer = file_read_to_buffer(fd, fsize);
104 close(fd);
105 return buffer;
106}
107
108void file_write(const char *filename, unsigned char *buffer, int size)
109{
110 int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,
111 S_IRUSR | S_IWUSR);
112
113 if (fd == -1) {
114 fprintf(stderr, "E: Could not create %s: %m\n", filename);
115 return;
116 }
117
118 file_write_from_buffer(fd, buffer, size);
119 close(fd);
120}
121
122int iself(unsigned char *input)
123{
124 Elf32_Ehdr *ehdr = (Elf32_Ehdr *) input;
125 return !memcmp(ehdr->e_ident, ELFMAG, 4);
126}