blob: 3b809c69fb1860690c5a901c517a6964ca8046df [file] [log] [blame]
Edward O'Callaghan4c76c732022-08-12 11:03:00 +10001/*
2 * This file is part of the flashrom project.
3 *
4 * Copyright (C) 2009-2010 Carl-Daniel Hailfinger
5 * Copyright (C) 2013 Stefan Tauner
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 */
17
18#include <ctype.h>
19#include <stdlib.h>
20#include <string.h>
21#include <errno.h>
22
23#ifndef __LIBPAYLOAD__
24#include <sys/stat.h>
25#endif
26
27#include "flash.h"
28
29int read_buf_from_file(unsigned char *buf, unsigned long size,
30 const char *filename)
31{
32#ifdef __LIBPAYLOAD__
33 msg_gerr("Error: No file I/O support in libpayload\n");
34 return 1;
35#else
36 int ret = 0;
37
38 FILE *image;
39 if (!strcmp(filename, "-"))
40 image = fdopen(fileno(stdin), "rb");
41 else
42 image = fopen(filename, "rb");
43 if (image == NULL) {
44 msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
45 return 1;
46 }
47
48 struct stat image_stat;
49 if (fstat(fileno(image), &image_stat) != 0) {
50 msg_gerr("Error: getting metadata of file \"%s\" failed: %s\n", filename, strerror(errno));
51 ret = 1;
52 goto out;
53 }
54 if ((image_stat.st_size != (intmax_t)size) && strcmp(filename, "-")) {
55 msg_gerr("Error: Image size (%jd B) doesn't match the flash chip's size (%lu B)!\n",
56 (intmax_t)image_stat.st_size, size);
57 ret = 1;
58 goto out;
59 }
60
61 unsigned long numbytes = fread(buf, 1, size, image);
62 if (numbytes != size) {
63 msg_gerr("Error: Failed to read complete file. Got %ld bytes, "
64 "wanted %ld!\n", numbytes, size);
65 ret = 1;
66 }
67out:
68 (void)fclose(image);
69 return ret;
70#endif
71}