1 /* 2 * Copyright 2021 NXP 3 * 4 * SPDX-License-Identifier: BSD-3-Clause 5 * 6 */ 7 8 #include <stdint.h> 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <string.h> 12 13 #include <getopt.h> 14 #include <unistd.h> 15 16 #define NUM_MEM_BLOCK 1 17 #define FOUR_BYTE_ALIGN 4 18 #define EIGHT_BYTE_ALIGN 8 19 #define SIZE_TWO_PBL_CMD 24 20 21 #define SUCCESS 0 22 #define FAILURE -1 23 #define BYTE_SWAP_32(word) ((((word) & 0xff000000) >> 24)| \ 24 (((word) & 0x00ff0000) >> 8) | \ 25 (((word) & 0x0000ff00) << 8) | \ 26 (((word) & 0x000000ff) << 24)) 27 28 29 /* 30 * Returns: 31 * SUCCESS, on successful byte swapping. 32 * FAILURE, on failure. 33 */ 34 int do_byteswap(FILE *fp) 35 { 36 int bytes = 0; 37 uint32_t upper_byte; 38 uint32_t lower_byte; 39 uint32_t pad = 0U; 40 /* Carries number of Padding bytes to be appended to 41 * make file size 8 byte aligned. 42 */ 43 int append_bytes; 44 int ret = FAILURE; 45 46 fseek(fp, 0L, SEEK_END); 47 bytes = ftell(fp); 48 49 append_bytes = EIGHT_BYTE_ALIGN - (bytes % EIGHT_BYTE_ALIGN); 50 if (append_bytes != 0) { 51 if (fwrite(&pad, append_bytes, NUM_MEM_BLOCK, fp) 52 != NUM_MEM_BLOCK) { 53 printf("%s: Error in appending padding bytes.\n", 54 __func__); 55 goto byteswap_err; 56 } 57 bytes += append_bytes; 58 } 59 60 rewind(fp); 61 while (bytes > 0) { 62 if ((fread(&upper_byte, sizeof(upper_byte), NUM_MEM_BLOCK, fp) 63 != NUM_MEM_BLOCK) && (feof(fp) == 0)) { 64 printf("%s: Error reading upper bytes.\n", __func__); 65 goto byteswap_err; 66 } 67 if ((fread(&lower_byte, sizeof(lower_byte), NUM_MEM_BLOCK, fp) 68 != NUM_MEM_BLOCK) && (feof(fp) == 0)) { 69 printf("%s: Error reading lower bytes.\n", __func__); 70 goto byteswap_err; 71 } 72 fseek(fp, -8L, SEEK_CUR); 73 upper_byte = BYTE_SWAP_32(upper_byte); 74 lower_byte = BYTE_SWAP_32(lower_byte); 75 if (fwrite(&lower_byte, sizeof(lower_byte), NUM_MEM_BLOCK, fp) 76 != NUM_MEM_BLOCK) { 77 printf("%s: Error writing lower bytes.\n", __func__); 78 goto byteswap_err; 79 } 80 if (fwrite(&upper_byte, sizeof(upper_byte), NUM_MEM_BLOCK, fp) 81 != NUM_MEM_BLOCK) { 82 printf("%s: Error writing upper bytes.\n", __func__); 83 goto byteswap_err; 84 } 85 bytes -= EIGHT_BYTE_ALIGN; 86 } 87 ret = SUCCESS; 88 89 byteswap_err: 90 return ret; 91 } 92 93 int main(int argc, char **argv) 94 { 95 FILE *fp = NULL; 96 int ret = 0; 97 98 if (argc > 2) { 99 printf("Usage format is byteswap <filename>"); 100 return -1; 101 } 102 103 fp = fopen(argv[1], "rb+"); 104 if (fp == NULL) { 105 printf("%s: Error opening the input file: %s\n", 106 __func__, argv[1]); 107 return -1; 108 } 109 110 ret = do_byteswap(fp); 111 fclose(fp); 112 return ret; 113 } 114