1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 #ifndef _OBJTOOL_ENDIANNESS_H
3 #define _OBJTOOL_ENDIANNESS_H
4 
5 #include <linux/kernel.h>
6 #include <endian.h>
7 #include <objtool/elf.h>
8 
9 /*
10  * Does a byte swap if target file endianness doesn't match the host, i.e. cross
11  * compilation for little endian on big endian and vice versa.
12  * To be used for multi-byte values conversion, which are read from / about
13  * to be written to a target native endianness ELF file.
14  */
need_bswap(struct elf * elf)15 static inline bool need_bswap(struct elf *elf)
16 {
17 	return (__BYTE_ORDER == __LITTLE_ENDIAN) ^
18 	       (elf->ehdr.e_ident[EI_DATA] == ELFDATA2LSB);
19 }
20 
21 #define bswap_if_needed(elf, val)					\
22 ({									\
23 	__typeof__(val) __ret;						\
24 	bool __need_bswap = need_bswap(elf);				\
25 	switch (sizeof(val)) {						\
26 	case 8:								\
27 		__ret = __need_bswap ? bswap_64(val) : (val); break;	\
28 	case 4:								\
29 		__ret = __need_bswap ? bswap_32(val) : (val); break;	\
30 	case 2:								\
31 		__ret = __need_bswap ? bswap_16(val) : (val); break;	\
32 	default:							\
33 		BUILD_BUG(); break;					\
34 	}								\
35 	__ret;								\
36 })
37 
38 #endif /* _OBJTOOL_ENDIANNESS_H */
39