1 /* 2 * Copyright (c) 2019, Remi Pommarel <repk@triplefau.lt> 3 * 4 * SPDX-License-Identifier: BSD-3-Clause 5 */ 6 #include <stdlib.h> 7 #include <stdio.h> 8 #include <fcntl.h> 9 #include <unistd.h> 10 #include <stdint.h> 11 #include <endian.h> 12 13 #define DEFAULT_PROGNAME "doimage" 14 #define PROGNAME(argc, argv) (((argc) >= 1) ? ((argv)[0]) : DEFAULT_PROGNAME) 15 16 #define BL31_MAGIC 0x12348765 17 #define BL31_LOADADDR 0x05100000 18 #define BUFLEN 512 19 20 static inline void usage(char const *prog) 21 { 22 fprintf(stderr, "Usage: %s <bl31.bin> <bl31.img>\n", prog); 23 } 24 25 static inline int fdwrite(int fd, uint8_t *data, size_t len) 26 { 27 ssize_t nr; 28 size_t l; 29 int ret = -1; 30 31 for (l = 0; l < len; l += nr) { 32 nr = write(fd, data + l, len - l); 33 if (nr < 0) { 34 perror("Cannot write to bl31.img"); 35 goto out; 36 } 37 } 38 39 ret = 0; 40 out: 41 return ret; 42 } 43 44 int main(int argc, char **argv) 45 { 46 int fin, fout, ret = -1; 47 ssize_t len; 48 uint32_t data; 49 uint8_t buf[BUFLEN]; 50 51 if (argc != 3) { 52 usage(PROGNAME(argc, argv)); 53 goto out; 54 } 55 56 fin = open(argv[1], O_RDONLY); 57 if (fin < 0) { 58 perror("Cannot open bl31.bin"); 59 goto out; 60 } 61 62 fout = open(argv[2], O_WRONLY | O_CREAT, 0660); 63 if (fout < 0) { 64 perror("Cannot open bl31.img"); 65 goto closefin; 66 } 67 68 data = htole32(BL31_MAGIC); 69 if (fdwrite(fout, (uint8_t *)&data, sizeof(data)) < 0) 70 goto closefout; 71 72 lseek(fout, 8, SEEK_SET); 73 data = htole32(BL31_LOADADDR); 74 if (fdwrite(fout, (uint8_t *)&data, sizeof(data)) < 0) 75 goto closefout; 76 77 lseek(fout, 0x200, SEEK_SET); 78 while ((len = read(fin, buf, sizeof(buf))) > 0) 79 if (fdwrite(fout, buf, len) < 0) 80 goto closefout; 81 if (len < 0) { 82 perror("Cannot read bl31.bin"); 83 goto closefout; 84 } 85 86 ret = 0; 87 88 closefout: 89 close(fout); 90 closefin: 91 close(fin); 92 out: 93 return ret; 94 } 95