I see a strange behavior of reading a bin file and mapping in to the structure in the windows compared to linux gcc compiler.
Below is my c code:
#include <inttypes.h>
#include <stdio.h>
#include <fcntl.h>
#define IV_MAX_LEN 32
#define HASH_MAX_LEN 64
#define MAX_NUM_IMGS 8
#define MAX_NUM_SRK_RECORDS 4
#define SKIP_OFFSET_1K 0x400
typedef struct {
uint8_t version;
uint16_t length;
uint8_t tag;
uint16_t srk_table_offset;
uint16_t cert_offset;
uint16_t blob_offset;
uint16_t signature_offset;
uint32_t reserved;
} __attribute__((packed)) blk_hdr_t;
typedef struct {
uint32_t offset;
uint32_t size;
uint64_t dst;
uint64_t entry;
uint32_t hab_flags;
uint32_t meta;
uint8_t hash[HASH_MAX_LEN];
uint8_t iv[IV_MAX_LEN];
} __attribute__((packed)) boot_t;
typedef struct {
uint8_t version;
uint16_t length;
uint8_t tag;
uint32_t flags;
uint16_t sw_version;
uint8_t fuse_version;
uint8_t num_images;
uint16_t sig_blk_offset;
uint16_t reserved;
boot_t img[MAX_NUM_IMGS];
blk_hdr_t blk_hdr;
uint32_t sigblk_size;
uint32_t padding;
} __attribute__((packed)) headerMain_t;
int main()
{
int ofd =1;
char filename[] = "sample.bin";
int readSizes= 0;
int headerSizes= 0;
headerMain_t header;
uint8_t *byte;
ofd = open(filename, O_RDONLY);
printf("\nOPENING File: %s!\n", filename);
printf("\n STRUCT sizes: %d, %d, %d,\n", sizeof(headerMain_t), sizeof(boot_t), sizeof(blk_hdr_t));
#if 0
if(lseek(ofd, SKIP_OFFSET_1K, SEEK_SET) < 0) {
printf("Error Read \n");
}
#endif
readSizes = read(ofd, &header, sizeof(header)) ;
headerSizes = sizeof(header);
printf("\n Read SIZE: %d / %d !",readSizes,headerSizes);
printf("\n Read Bytes: \n");
byte = (uint8_t*)&header;
for(int i=0; i<readSizes; i++)
{
printf("0x%02x, ",*byte);
byte++;
if(0 ==i%20 )
printf("\n");
}
return 0;
}
and here is the input binary file it reads. (This sample bin file is 0x01 (20 times)... 0xFF(20 times) = so 255 x 20 = 5100 bytes) The same code is compiled and run in windows mingW-gcc and linux gcc.
Following are the strange observations seen in the windows run:
blk_hdr_t
struct although 4 byte aligned and 16 bytes it total: 22 bytes (Update: I found that this solution worked with -mno-ms-bitfields option)- Although 5100 bytes are available, read() function could read only 1000 bytes. what choked it further to read ?
- read() also puts the "holes" with "0x00" bytes value in it. I don't understand this strange behaviour.
- Enabling the lseek to skip first 1024 bytes shall reach the end of the file.
Everything looks perfect on the linux result (although point 3) does exist on the linux side too: although this is trivial for me, i'm curious on the behaviour)
so finally, How can make this code on windows gcc with the Exact result as in the linux gcc ? could anyone please enlighten me ? (The parameters in the structures cannot be reshuffled)