From 50c17f33d9cbda6ab36098eaa14eaceb698b104f Mon Sep 17 00:00:00 2001 From: mykola2312 <49044616+mykola2312@users.noreply.github.com> Date: Thu, 28 Apr 2022 18:26:15 +0300 Subject: [PATCH] implement endiannes run-time detection --- CMakeLists.txt | 2 ++ cutil.c | 3 +++ cutypes.h | 2 +- endian.c | 27 +++++++++++++++++++++++++++ endian.h | 17 +++++++++++++++++ test.c | 2 ++ 6 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 endian.c create mode 100644 endian.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 4cdf5ff..198451e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,6 +7,7 @@ set(HEADERS list.h array.h bitmap.h + endian.h ) set(SOURCES @@ -14,6 +15,7 @@ set(SOURCES list.c array.c bitmap.c + endian.c ) add_library(cutil STATIC ${SOURCES} ${HEADERS}) diff --git a/cutil.c b/cutil.c index 534c606..88ee079 100644 --- a/cutil.c +++ b/cutil.c @@ -1,4 +1,5 @@ #include "cutil.h" +#include "endian.h" #include void* (*cu_malloc)(size_t); @@ -10,6 +11,8 @@ void* (*cu_memmove)(void*,const void*,size_t); void cutil_init() { + cu_endian_init(); + cu_malloc = CUTIL_MALLOC; cu_realloc = CUTIL_REALLOC; cu_free = CUTIL_FREE; diff --git a/cutypes.h b/cutypes.h index e283b52..a8e7277 100644 --- a/cutypes.h +++ b/cutypes.h @@ -89,7 +89,7 @@ typedef int64_t iword; typedef uint32_t uword; typedef int32_t iword; #else -# warning "define CU_32BIT or CU_64BIT" +# warning "unknown bus width for arch " CU_ARCH #endif typedef uint32_t uint; diff --git a/endian.c b/endian.c new file mode 100644 index 0000000..0e9bde6 --- /dev/null +++ b/endian.c @@ -0,0 +1,27 @@ +#include "endian.h" + +enum cu_endian_e cu_endian; + +static const union { + uint8_t bytes[4]; + uint32_t value; +} host_order = { + {0, 1, 2, 3} +}; + +#define ORDER_LITTLE_ENDIAN 0x03020100 +#define ORDER_BIG_ENDIAN 0x00010203 +#define ORDER_PDP_ENDIAN 0x01000302 +#define ORDER_HONEYWELL_ENDIAN 0x02030001 + +void cu_endian_init() +{ + if (host_order.value == ORDER_LITTLE_ENDIAN) + cu_endian = LittleEndian; + else if (host_order.value == ORDER_BIG_ENDIAN) + cu_endian = BigEndian; + else if (host_order.value == ORDER_PDP_ENDIAN) + cu_endian = PDPEndian; + else if (host_order.value == ORDER_HONEYWELL_ENDIAN) + cu_endian = HoneywellEndian; +} diff --git a/endian.h b/endian.h new file mode 100644 index 0000000..6fdff4f --- /dev/null +++ b/endian.h @@ -0,0 +1,17 @@ +#ifndef __ENDIAN_H +#define __ENDIAN_H + +#include "cutypes.h" + +enum cu_endian_e { + LittleEndian, + BigEndian, + PDPEndian, + HoneywellEndian +}; + +extern enum cu_endian_e cu_endian; + +void cu_endian_init(); + +#endif \ No newline at end of file diff --git a/test.c b/test.c index 4b37af9..9a28daf 100644 --- a/test.c +++ b/test.c @@ -5,6 +5,7 @@ #include "list.h" #include "array.h" #include "bitmap.h" +#include "endian.h" int main() { @@ -76,6 +77,7 @@ int main() printf("[cutil]\n"); printf("cutil_arch\t%u\n", CU_ARCH); + printf("cutil_endian\t%u\n", cu_endian); cutil_exit(); return 0;