From 2a162f32fb97e70338066903143643e14a0f6c5b Mon Sep 17 00:00:00 2001 From: Charlotte Koch Date: Tue, 7 Jul 2020 15:39:13 -0700 Subject: [PATCH] lputil: Proper support for big-endian platforms with the various Read*() functions Determine at configure-time whether we're building for a big-endian or a little-endian machine, which in turn will enable or disable such things as htons(3) from happening --- CMakeLists.txt | 6 ++++++ src/lputil/lputil.c | 12 ++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ece6982..cfba19c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,5 +54,11 @@ if(${LUNAPURPURA_DEBUG}) add_definitions(-DLUNAPURPURA_DEBUG) endif() +include(TestBigEndian) +test_big_endian(LUNAPURPURA_BIG_ENDIAN) +if(${LUNAPURPURA_BIG_ENDIAN}) + add_definitions(-DLUNAPURPURA_BIG_ENDIAN) +endif() + # Good to go. add_subdirectory(src) diff --git a/src/lputil/lputil.c b/src/lputil/lputil.c index 3a1ca5a..3c9b801 100644 --- a/src/lputil/lputil.c +++ b/src/lputil/lputil.c @@ -184,7 +184,9 @@ size_t ReadUint16(FILE *file, size_t count, uint16_t *dest) { size_t rv = fread(dest, sizeof(uint16_t), count, file); +#ifndef LUNAPURPURA_BIG_ENDIAN *dest = htons(*dest); +#endif return rv; } @@ -197,7 +199,9 @@ size_t ReadUint16LE(FILE *file, size_t count, uint16_t *dest) { size_t rv = fread(dest, sizeof(uint16_t), count, file); - /* XXX do something to guarantee it was little-endian */ +#ifdef LUNAPURPURA_BIG_ENDIAN + *dest = ntohs(*dest); +#endif return rv; } @@ -210,7 +214,9 @@ size_t ReadUint32(FILE *file, size_t count, uint32_t *dest) { size_t rv = fread(dest, sizeof(uint32_t), count, file); +#ifndef LUNAPURPURA_BIG_ENDIAN *dest = htonl(*dest); +#endif return rv; } @@ -223,6 +229,8 @@ size_t ReadUint32LE(FILE *file, size_t count, uint32_t *dest) { size_t rv = fread(dest, sizeof(uint32_t), count, file); - /* XXX do something to guarantee it was little-endian */ +#ifdef LUNAPURPURA_BIG_ENDIAN + *dest = ntohl(*dest); +#endif return rv; }