diff --git a/libc/include/endian.h b/libc/include/endian.h new file mode 100644 index 00000000..7f9c359a --- /dev/null +++ b/libc/include/endian.h @@ -0,0 +1,47 @@ +/* endian.h: Functions to convert between different byte orderings. */ + +#ifndef _ENDIAN_H +#define _ENDIAN_H + +#include + +#define LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ +#define BIG_ENDIAN __ORDER_BIG_ENDIAN__ + +#define BYTE_ORDER __BYTE_ORDER__ + +#if BYTE_ORDER == LITTLE_ENDIAN +#define be16toh(x) __builtin_bswap16(x) +#define be32toh(x) __builtin_bswap32(x) +#define be64toh(x) __builtin_bswap64(x) + +#define htobe16(x) __builtin_bswap16(x) +#define htobe32(x) __builtin_bswap32(x) +#define htobe64(x) __builtin_bswap64(x) + +#define htole16(x) (x) +#define htole32(x) (x) +#define htole64(x) (x) + +#define le16toh(x) (x) +#define le32toh(x) (x) +#define le64toh(x) (x) +#else +#define be16toh(x) (x) +#define be32toh(x) (x) +#define be64toh(x) (x) + +#define htobe16(x) (x) +#define htobe32(x) (x) +#define htobe64(x) (x) + +#define htole16(x) __builtin_bswap16(x) +#define htole32(x) __builtin_bswap32(x) +#define htole64(x) __builtin_bswap64(x) + +#define le16toh(x) __builtin_bswap16(x) +#define le32toh(x) __builtin_bswap32(x) +#define le64toh(x) __builtin_bswap64(x) +#endif + +#endif diff --git a/libluna/src/SHA.cpp b/libluna/src/SHA.cpp index 538c2c09..b0e2f8fd 100644 --- a/libluna/src/SHA.cpp +++ b/libluna/src/SHA.cpp @@ -7,6 +7,7 @@ * */ +#include #include #include #include @@ -62,7 +63,7 @@ Result SHA256::digest() // Add the length of the original message (in bits), this has to be big-endian. usize message_length = m_message.size() * 8; - message_length = __builtin_bswap64(message_length); // FIXME: We're assuming we're on a little-endian platform. + message_length = htobe64(message_length); TRY(message_block.append_data((const u8*)&message_length, sizeof(usize))); // The length of the message block should now be a multiple of 512 bits (64 bytes). @@ -89,11 +90,13 @@ Result SHA256::digest() memcpy(message_schedule, &message_block.data()[i * 64], 64); +#if BYTE_ORDER == LITTLE_ENDIAN for (int j = 0; j < 16; j++) { - // SHA uses big-endian. FIXME: Don't assume little-endian. - message_schedule[j] = __builtin_bswap32(message_schedule[j]); + // SHA uses big-endian. + message_schedule[j] = htobe32(message_schedule[j]); } +#endif // Fill the rest of the message schedule. for (int j = 0; j < 48; j++) @@ -150,15 +153,14 @@ Result SHA256::digest() h7 += h; } - // FIXME: Again, this assumes little-endian. - h0 = __builtin_bswap32(h0); - h1 = __builtin_bswap32(h1); - h2 = __builtin_bswap32(h2); - h3 = __builtin_bswap32(h3); - h4 = __builtin_bswap32(h4); - h5 = __builtin_bswap32(h5); - h6 = __builtin_bswap32(h6); - h7 = __builtin_bswap32(h7); + h0 = be32toh(h0); + h1 = be32toh(h1); + h2 = be32toh(h2); + h3 = be32toh(h3); + h4 = be32toh(h4); + h5 = be32toh(h5); + h6 = be32toh(h6); + h7 = be32toh(h7); Digest result; memcpy(&result.m_bytes[0], &h0, sizeof(u32));