1 /* SPDX-License-Identifier: GPL-2.0-or-later */
3 /***************************************************************************
4 * Copyright (C) 2006 by Dominic Rath *
5 * Dominic.Rath@gmx.de *
6 ***************************************************************************/
12 #include "xilinx_bit.h"
14 #include <helper/log.h>
17 #include <helper/system.h>
19 static int read_section(FILE *input_file, int length_size, char section,
20 uint32_t *buffer_length, uint8_t **buffer)
22 uint8_t length_buffer[4];
27 if ((length_size != 2) && (length_size != 4)) {
28 LOG_ERROR("BUG: length_size neither 2 nor 4");
29 return ERROR_PLD_FILE_LOAD_FAILED;
32 read_count = fread(§ion_char, 1, 1, input_file);
34 return ERROR_PLD_FILE_LOAD_FAILED;
36 if (section_char != section)
37 return ERROR_PLD_FILE_LOAD_FAILED;
39 read_count = fread(length_buffer, 1, length_size, input_file);
40 if (read_count != length_size)
41 return ERROR_PLD_FILE_LOAD_FAILED;
44 length = be_to_h_u32(length_buffer);
45 else /* (length_size == 2) */
46 length = be_to_h_u16(length_buffer);
49 *buffer_length = length;
51 *buffer = malloc(length);
53 read_count = fread(*buffer, 1, length, input_file);
54 if (read_count != length)
55 return ERROR_PLD_FILE_LOAD_FAILED;
60 int xilinx_read_bit_file(struct xilinx_bit_file *bit_file, const char *filename)
63 struct stat input_stat;
66 if (!filename || !bit_file)
67 return ERROR_COMMAND_SYNTAX_ERROR;
69 if (stat(filename, &input_stat) == -1) {
70 LOG_ERROR("couldn't stat() %s: %s", filename, strerror(errno));
71 return ERROR_PLD_FILE_LOAD_FAILED;
74 if (S_ISDIR(input_stat.st_mode)) {
75 LOG_ERROR("%s is a directory", filename);
76 return ERROR_PLD_FILE_LOAD_FAILED;
79 if (input_stat.st_size == 0) {
80 LOG_ERROR("Empty file %s", filename);
81 return ERROR_PLD_FILE_LOAD_FAILED;
84 input_file = fopen(filename, "rb");
86 LOG_ERROR("couldn't open %s: %s", filename, strerror(errno));
87 return ERROR_PLD_FILE_LOAD_FAILED;
90 read_count = fread(bit_file->unknown_header, 1, 13, input_file);
91 if (read_count != 13) {
92 LOG_ERROR("couldn't read unknown_header from file '%s'", filename);
93 return ERROR_PLD_FILE_LOAD_FAILED;
96 if (read_section(input_file, 2, 'a', NULL, &bit_file->source_file) != ERROR_OK)
97 return ERROR_PLD_FILE_LOAD_FAILED;
99 if (read_section(input_file, 2, 'b', NULL, &bit_file->part_name) != ERROR_OK)
100 return ERROR_PLD_FILE_LOAD_FAILED;
102 if (read_section(input_file, 2, 'c', NULL, &bit_file->date) != ERROR_OK)
103 return ERROR_PLD_FILE_LOAD_FAILED;
105 if (read_section(input_file, 2, 'd', NULL, &bit_file->time) != ERROR_OK)
106 return ERROR_PLD_FILE_LOAD_FAILED;
108 if (read_section(input_file, 4, 'e', &bit_file->length, &bit_file->data) != ERROR_OK)
109 return ERROR_PLD_FILE_LOAD_FAILED;
111 LOG_DEBUG("bit_file: %s %s %s,%s %" PRIu32 "", bit_file->source_file, bit_file->part_name,
112 bit_file->date, bit_file->time, bit_file->length);