From 775c4993063d7673903a2dfaebeacd1a9c71cbf7 Mon Sep 17 00:00:00 2001
From: havoc <havoc@d7cf8633-e32d-0410-b094-e92efae38249>
Date: Mon, 21 Dec 2009 08:46:20 +0000
Subject: [PATCH] added mem_bigendian variable made LittleLong/Short/Float and
 BigLong/Short/Float functions pass a pointer to the variable to
 BuffBigLong/BuffLittleLong and friends to avoid unaligned memory access
 crashes on some platforms even if a file has unaligned data in it added
 StoreBigLong function to help the netconn.c code removed BYTE_ORDER
 compile-time detection

git-svn-id: svn://svn.icculus.org/twilight/trunk/darkplaces@9617 d7cf8633-e32d-0410-b094-e92efae38249
---
 common.c      | 70 ++++++++++++++++++----------------------
 common.h      | 88 +++++++++++++++------------------------------------
 host_cmd.c    |  2 +-
 model_alias.h |  2 +-
 model_brush.c |  7 ++--
 netconn.c     | 59 ++++++++++++++++------------------
 snd_bsd.c     |  5 ++-
 snd_ogg.c     |  9 ++----
 snd_wav.c     |  4 +--
 sv_demo.c     |  4 ++-
 zone.c        |  8 ++++-
 zone.h        |  2 ++
 12 files changed, 107 insertions(+), 153 deletions(-)

diff --git a/common.c b/common.c
index 9fa09688..c002be8d 100644
--- a/common.c
+++ b/common.c
@@ -51,68 +51,58 @@ char com_modname[MAX_OSPATH] = "";
 ============================================================================
 */
 
-short   ShortSwap (short l)
-{
-	unsigned char    b1,b2;
-
-	b1 = l&255;
-	b2 = (l>>8)&255;
-
-	return (b1<<8) + b2;
-}
 
-int    LongSwap (int l)
-{
-	unsigned char    b1,b2,b3,b4;
-
-	b1 = l&255;
-	b2 = (l>>8)&255;
-	b3 = (l>>16)&255;
-	b4 = (l>>24)&255;
-
-	return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4;
-}
-
-float FloatSwap (float f)
+float BuffBigFloat (const unsigned char *buffer)
 {
 	union
 	{
-		float   f;
-		unsigned char    b[4];
-	} dat1, dat2;
-
-
-	dat1.f = f;
-	dat2.b[0] = dat1.b[3];
-	dat2.b[1] = dat1.b[2];
-	dat2.b[2] = dat1.b[1];
-	dat2.b[3] = dat1.b[0];
-	return dat2.f;
+		float f;
+		unsigned int i;
+	}
+	u;
+	u.i = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
+	return u.f;
 }
 
-
-// Extract integers from buffers
-
-unsigned int BuffBigLong (const unsigned char *buffer)
+int BuffBigLong (const unsigned char *buffer)
 {
 	return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
 }
 
-unsigned short BuffBigShort (const unsigned char *buffer)
+short BuffBigShort (const unsigned char *buffer)
 {
 	return (buffer[0] << 8) | buffer[1];
 }
 
-unsigned int BuffLittleLong (const unsigned char *buffer)
+float BuffLittleFloat (const unsigned char *buffer)
+{
+	union
+	{
+		float f;
+		unsigned int i;
+	}
+	u;
+	u.i = (buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0];
+	return u.f;
+}
+
+int BuffLittleLong (const unsigned char *buffer)
 {
 	return (buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0];
 }
 
-unsigned short BuffLittleShort (const unsigned char *buffer)
+short BuffLittleShort (const unsigned char *buffer)
 {
 	return (buffer[1] << 8) | buffer[0];
 }
 
+void StoreBigLong (unsigned char *buffer, unsigned int i)
+{
+	buffer[0] = (i >> 24) & 0xFF;
+	buffer[1] = (i >> 16) & 0xFF;
+	buffer[2] = (i >>  8) & 0xFF;
+	buffer[3] = i         & 0xFF;
+}
 
 /*
 ============================================================================
diff --git a/common.h b/common.h
index 3b605849..2986045f 100644
--- a/common.h
+++ b/common.h
@@ -69,78 +69,40 @@ void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf);
 //							Endianess handling
 //============================================================================
 
-// We use BSD-style defines: BYTE_ORDER is defined to either BIG_ENDIAN or LITTLE_ENDIAN
-
-// Initializations
-#if !defined(BYTE_ORDER) || !defined(LITTLE_ENDIAN) || !defined(BIG_ENDIAN) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
-# undef BYTE_ORDER
-# undef LITTLE_ENDIAN
-# undef BIG_ENDIAN
-# define LITTLE_ENDIAN 1234
-# define BIG_ENDIAN 4321
-#endif
-
-// If we still don't know the CPU endianess at this point, we try to guess
-// normally including sys/types.h includes endian.h for the platform, which defines BYTE_ORDER, LITTLE_ENDIAN, and BIG_ENDIAN, however endian.h is a BSD-ism, and may not be present on all platforms (particularly windows)
-#ifndef BYTE_ORDER
-# if defined(WIN32) || defined (__i386) || defined(__amd64)
-#  define BYTE_ORDER LITTLE_ENDIAN
-# else
-#  if defined(SUNOS)
-#   if defined(__i386) || defined(__amd64)
-#    define BYTE_ORDER LITTLE_ENDIAN
-#   else
-#    define BYTE_ORDER BIG_ENDIAN
-#   endif
-#  else
-#   warning "Unable to determine the CPU endianess. Defaulting to little endian"
-#   define BYTE_ORDER LITTLE_ENDIAN
-#  endif
-# endif
-#endif
+// check mem_bigendian if you need to know the system byte order
 
 /*! \name Byte order functions.
  * @{
  */
 
-/// Swaps the byte order of the given short \p l.
-short ShortSwap (short l);
-
-/// Swaps the byte order of the given long \p l.
-int LongSwap (int l);
-
-/// Swaps the byte order of the given float \p f.
-float FloatSwap (float f);
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-// little endian
-#define BigShort(l) ShortSwap(l)
-#define LittleShort(l) (l)
-#define BigLong(l) LongSwap(l)
-#define LittleLong(l) (l)
-#define BigFloat(l) FloatSwap(l)
-#define LittleFloat(l) (l)
-#else
-// big endian
-#define BigShort(l) (l)
-#define LittleShort(l) ShortSwap(l)
-#define BigLong(l) (l)
-#define LittleLong(l) LongSwap(l)
-#define BigFloat(l) (l)
-#define LittleFloat(l) FloatSwap(l)
-#endif
+// unaligned memory access crashes on some platform, so always read bytes...
+#define BigShort(l) BuffBigShort((unsigned char *)&(l))
+#define LittleShort(l) BuffLittleShort((unsigned char *)&(l))
+#define BigLong(l) BuffBigLong((unsigned char *)&(l))
+#define LittleLong(l) BuffLittleLong((unsigned char *)&(l))
+#define BigFloat(l) BuffBigFloat((unsigned char *)&(l))
+#define LittleFloat(l) BuffLittleFloat((unsigned char *)&(l))
+
+/// Extract a big endian 32bit float from the given \p buffer.
+float BuffBigFloat (const unsigned char *buffer);
+
+/// Extract a big endian 32bit int from the given \p buffer.
+int BuffBigLong (const unsigned char *buffer);
+
+/// Extract a big endian 16bit short from the given \p buffer.
+short BuffBigShort (const unsigned char *buffer);
 
-/// Extract a big endian long from the given \p buffer.
-unsigned int BuffBigLong (const unsigned char *buffer);
+/// Extract a little endian 32bit float from the given \p buffer.
+float BuffLittleFloat (const unsigned char *buffer);
 
-/// Extract a big endian short from the given \p buffer.
-unsigned short BuffBigShort (const unsigned char *buffer);
+/// Extract a little endian 32bit int from the given \p buffer.
+int BuffLittleLong (const unsigned char *buffer);
 
-/// Extract a little endian long from the given \p buffer.
-unsigned int BuffLittleLong (const unsigned char *buffer);
+/// Extract a little endian 16bit short from the given \p buffer.
+short BuffLittleShort (const unsigned char *buffer);
 
-/// Extract a little endian short from the given \p buffer.
-unsigned short BuffLittleShort (const unsigned char *buffer);
+/// Encode a big endian 32bit int to the given \p buffer
+void StoreBigLong (unsigned char *buffer, unsigned int i);
 //@}
 
 //============================================================================
diff --git a/host_cmd.c b/host_cmd.c
index 66c08cbc..7cbfe00f 100644
--- a/host_cmd.c
+++ b/host_cmd.c
@@ -2381,7 +2381,7 @@ void Host_PQRcon_f (void)
 		MSG_WriteByte (&net_message, CCREQ_RCON);
 		SZ_Write(&net_message, (void*)rcon_password.string, n);
 		MSG_WriteString (&net_message, Cmd_Args());
-		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+		StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 		NetConn_Write(mysocket, net_message.data, net_message.cursize, &to);
 		SZ_Clear (&net_message);
 	}
diff --git a/model_alias.h b/model_alias.h
index 6df1e011..846755ed 100644
--- a/model_alias.h
+++ b/model_alias.h
@@ -120,7 +120,7 @@ typedef struct md2_s
 
 // all md3 ints, floats, and shorts, are little endian, and thus need to be
 // passed through LittleLong/LittleFloat/LittleShort to avoid breaking on
-// bigendian machines (Macs for example)
+// bigendian machines
 #define MD3VERSION 15
 #define MD3NAME 64
 #define MD3FRAMENAME 16
diff --git a/model_brush.c b/model_brush.c
index 699512d8..069091df 100644
--- a/model_brush.c
+++ b/model_brush.c
@@ -3489,12 +3489,15 @@ void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
 	mod->brush.qw_md4sum2 = 0;
 	for (i = 0;i < HEADER_LUMPS;i++)
 	{
+		int temp;
 		if (i == LUMP_ENTITIES)
 			continue;
-		mod->brush.qw_md4sum ^= LittleLong(Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen));
+		temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
+		mod->brush.qw_md4sum ^= LittleLong(temp);
 		if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
 			continue;
-		mod->brush.qw_md4sum2 ^= LittleLong(Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen));
+		temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
+		mod->brush.qw_md4sum2 ^= LittleLong(temp);
 	}
 
 	Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
diff --git a/netconn.c b/netconn.c
index 32269b40..0b1c4120 100755
--- a/netconn.c
+++ b/netconn.c
@@ -624,6 +624,7 @@ qboolean NetConn_CanSend(netconn_t *conn)
 int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolversion_t protocol, int rate, qboolean quakesignon_suppressreliables)
 {
 	int totallen = 0;
+	int temp;
 
 	// if this packet was supposedly choked, but we find ourselves sending one
 	// anyway, make sure the size counting starts at zero
@@ -653,9 +654,11 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers
 			sendreliable = true;
 		}
 		// outgoing unreliable packet number, and outgoing reliable packet number (0 or 1)
-		*((int *)(sendbuffer + 0)) = LittleLong((unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31));
+		temp = (unsigned int)conn->outgoing_unreliable_sequence | ((unsigned int)sendreliable<<31);
+		*((int *)(sendbuffer + 0)) = LittleLong(temp);
 		// last received unreliable packet number, and last received reliable packet number (0 or 1)
-		*((int *)(sendbuffer + 4)) = LittleLong((unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31));
+		temp = (unsigned int)conn->qw.incoming_sequence | ((unsigned int)conn->qw.incoming_reliable_sequence<<31);
+		*((int *)(sendbuffer + 4)) = LittleLong(temp);
 		packetLen = 8;
 		conn->outgoing_unreliable_sequence++;
 		// client sends qport in every packet
@@ -703,7 +706,6 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers
 		unsigned int packetLen;
 		unsigned int dataLen;
 		unsigned int eom;
-		unsigned int *header;
 
 		// if a reliable message fragment has been lost, send it again
 		if (conn->sendMessageLength && (realtime - conn->lastSendTime) > 1.0)
@@ -721,9 +723,8 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers
 
 			packetLen = NET_HEADERSIZE + dataLen;
 
-			header = (unsigned int *)sendbuffer;
-			header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
-			header[1] = BigLong(conn->nq.sendSequence - 1);
+			StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
+			StoreBigLong(sendbuffer + 4, conn->nq.sendSequence - 1);
 			memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
 
 			conn->outgoing_netgraph[conn->outgoing_packetcounter].reliablebytes += packetLen + 28;
@@ -770,9 +771,8 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers
 
 			packetLen = NET_HEADERSIZE + dataLen;
 
-			header = (unsigned int *)sendbuffer;
-			header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
-			header[1] = BigLong(conn->nq.sendSequence);
+			StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
+			StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
 			memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
 
 			conn->nq.sendSequence++;
@@ -799,9 +799,8 @@ int NetConn_SendUnreliableMessage(netconn_t *conn, sizebuf_t *data, protocolvers
 				return -1;
 			}
 
-			header = (unsigned int *)sendbuffer;
-			header[0] = BigLong(packetLen | NETFLAG_UNRELIABLE);
-			header[1] = BigLong(conn->outgoing_unreliable_sequence);
+			StoreBigLong(sendbuffer, packetLen | NETFLAG_UNRELIABLE);
+			StoreBigLong(sendbuffer + 4, conn->outgoing_unreliable_sequence);
 			memcpy(sendbuffer + NET_HEADERSIZE, data->data, data->cursize);
 
 			conn->outgoing_unreliable_sequence++;
@@ -1157,13 +1156,13 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len
 		unsigned int sequence;
 		int qlength;
 
-		qlength = (unsigned int)BigLong(((int *)data)[0]);
+		qlength = (unsigned int)BuffBigLong(data);
 		flags = qlength & ~NETFLAG_LENGTH_MASK;
 		qlength &= NETFLAG_LENGTH_MASK;
 		// control packets were already handled
 		if (!(flags & NETFLAG_CTL) && qlength == length)
 		{
-			sequence = BigLong(((int *)data)[1]);
+			sequence = BuffBigLong(data + 4);
 			packetsReceived++;
 			data += 8;
 			length -= 8;
@@ -1223,7 +1222,6 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len
 							unsigned int packetLen;
 							unsigned int dataLen;
 							unsigned int eom;
-							unsigned int *header;
 
 							conn->sendMessageLength -= MAX_PACKETFRAGMENT;
 							memmove(conn->sendMessage, conn->sendMessage+MAX_PACKETFRAGMENT, conn->sendMessageLength);
@@ -1241,9 +1239,8 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len
 
 							packetLen = NET_HEADERSIZE + dataLen;
 
-							header = (unsigned int *)sendbuffer;
-							header[0] = BigLong(packetLen | (NETFLAG_DATA | eom));
-							header[1] = BigLong(conn->nq.sendSequence);
+							StoreBigLong(sendbuffer, packetLen | (NETFLAG_DATA | eom));
+							StoreBigLong(sendbuffer + 4, conn->nq.sendSequence);
 							memcpy(sendbuffer + NET_HEADERSIZE, conn->sendMessage, dataLen);
 
 							conn->nq.sendSequence++;
@@ -1269,8 +1266,8 @@ static int NetConn_ReceivedMessage(netconn_t *conn, unsigned char *data, int len
 				unsigned int temppacket[2];
 				conn->incoming_netgraph[conn->incoming_packetcounter].reliablebytes   += originallength + 28;
 				conn->outgoing_netgraph[conn->outgoing_packetcounter].ackbytes        += 8 + 28;
-				temppacket[0] = BigLong(8 | NETFLAG_ACK);
-				temppacket[1] = BigLong(sequence);
+				StoreBigLong(sendbuffer, 8 | NETFLAG_ACK);
+				StoreBigLong(sendbuffer + 4, sequence);
 				NetConn_Write(conn->mysocket, (unsigned char *)temppacket, 8, &conn->peeraddress);
 				if (sequence == conn->nq.receiveSequence)
 				{
@@ -1895,7 +1892,7 @@ static int NetConn_ClientParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 		return ret;
 	}
 	// netquake control packets, supported for compatibility only
-	if (length >= 5 && (control = BigLong(*((int *)data))) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
+	if (length >= 5 && (control = BuffBigLong(data)) && (control & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (control & NETFLAG_LENGTH_MASK) == length)
 	{
 		int n;
 		serverlist_info_t *info;
@@ -2096,7 +2093,7 @@ void NetConn_ClientFrame(void)
 		MSG_WriteByte(&net_message, CCREQ_CONNECT);
 		MSG_WriteString(&net_message, "QUAKE");
 		MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
-		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+		StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 		NetConn_Write(cls.connect_mysocket, net_message.data, net_message.cursize, &cls.connect_address);
 		SZ_Clear(&net_message);
 	}
@@ -2818,7 +2815,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 	// protocol
 	// (this protects more modern protocols against being used for
 	//  Quake packet flood Denial Of Service attacks)
-	if (length >= 5 && (i = BigLong(*((int *)data))) && (i & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (i & NETFLAG_LENGTH_MASK) == length && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
+	if (length >= 5 && (i = BuffBigLong(data)) && (i & (~NETFLAG_LENGTH_MASK)) == (int)NETFLAG_CTL && (i & NETFLAG_LENGTH_MASK) == length && (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3 || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3))
 	{
 		int c;
 		int protocolnumber;
@@ -2848,7 +2845,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 				MSG_WriteLong(&net_message, 0);
 				MSG_WriteByte(&net_message, CCREP_REJECT);
 				MSG_WriteString(&net_message, "Incompatible version.\n");
-				*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+				StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 				NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 				SZ_Clear(&net_message);
 				break;
@@ -2871,7 +2868,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 					MSG_WriteLong(&net_message, 0);
 					MSG_WriteByte(&net_message, CCREP_ACCEPT);
 					MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(client->netconnection->mysocket)));
-					*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+					StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 					NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 					SZ_Clear(&net_message);
 
@@ -2908,7 +2905,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 					MSG_WriteLong(&net_message, 0);
 					MSG_WriteByte(&net_message, CCREP_ACCEPT);
 					MSG_WriteLong(&net_message, LHNETADDRESS_GetPort(LHNET_AddressFromSocket(conn->mysocket)));
-					*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+					StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 					NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 					SZ_Clear(&net_message);
 					// now set up the client struct
@@ -2928,7 +2925,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 			MSG_WriteLong(&net_message, 0);
 			MSG_WriteByte(&net_message, CCREP_REJECT);
 			MSG_WriteString(&net_message, "Server is full.\n");
-			*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+			StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 			NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 			SZ_Clear(&net_message);
 			break;
@@ -2958,7 +2955,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 				MSG_WriteByte(&net_message, numclients);
 				MSG_WriteByte(&net_message, svs.maxclients);
 				MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
-				*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+				StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 				NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 				SZ_Clear(&net_message);
 			}
@@ -2990,7 +2987,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 					MSG_WriteLong(&net_message, client->frags);
 					MSG_WriteLong(&net_message, (int)(realtime - client->connecttime));
 					MSG_WriteString(&net_message, client->netconnection ? client->netconnection->address : "botclient");
-					*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+					StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 					NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 					SZ_Clear(&net_message);
 				}
@@ -3020,7 +3017,7 @@ static int NetConn_ServerParsePacket(lhnetsocket_t *mysocket, unsigned char *dat
 					MSG_WriteString(&net_message, var->name);
 					MSG_WriteString(&net_message, var->string);
 				}
-				*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+				StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 				NetConn_Write(mysocket, net_message.data, net_message.cursize, peeraddress);
 				SZ_Clear(&net_message);
 			}
@@ -3105,7 +3102,7 @@ void NetConn_QueryMasters(qboolean querydp, qboolean queryqw)
 					MSG_WriteByte(&net_message, CCREQ_SERVER_INFO);
 					MSG_WriteString(&net_message, "QUAKE");
 					MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
-					*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
+					StoreBigLong(net_message.data, NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
 					NetConn_Write(cl_sockets[i], net_message.data, net_message.cursize, &broadcastaddress);
 					SZ_Clear(&net_message);
 
diff --git a/snd_bsd.c b/snd_bsd.c
index 85f10df4..0e927f1e 100644
--- a/snd_bsd.c
+++ b/snd_bsd.c
@@ -84,11 +84,10 @@ qboolean SndSys_Init (const snd_format_t* requested, snd_format_t* suggested)
 #ifdef SUNOS
 		info.play.encoding = AUDIO_ENCODING_LINEAR;
 #else
-#	if BYTE_ORDER == BIG_ENDIAN
+	if (mem_bigendian)
 		info.play.encoding = AUDIO_ENCODING_SLINEAR_BE;
-#	else
+	else
 		info.play.encoding = AUDIO_ENCODING_SLINEAR_LE;
-#	endif
 #endif
 
 	if (ioctl (audio_fd, AUDIO_SETINFO, &info) != 0)
diff --git a/snd_ogg.c b/snd_ogg.c
index fb21b93a..693ed0a2 100644
--- a/snd_ogg.c
+++ b/snd_ogg.c
@@ -411,7 +411,7 @@ static const snd_buffer_t* OGG_FetchSound (void *sfxfetcher, void **chfetcherpoi
 	ogg_stream_perchannel_t* per_ch = (ogg_stream_perchannel_t *)*chfetcherpointer;
 	ogg_stream_persfx_t* per_sfx = (ogg_stream_persfx_t *)sfxfetcher;
 	snd_buffer_t* sb;
-	int newlength, done, ret, bigendian;
+	int newlength, done, ret;
 	unsigned int real_start;
 	unsigned int factor;
 
@@ -529,13 +529,8 @@ static const snd_buffer_t* OGG_FetchSound (void *sfxfetcher, void **chfetcherpoi
 		newlength = sizeof(resampling_buffer);
 
 	// Decompress in the resampling_buffer
-#if BYTE_ORDER == BIG_ENDIAN
-	bigendian = 1;
-#else
-	bigendian = 0;
-#endif
 	done = 0;
-	while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), bigendian, 2, 1, &per_ch->bs)) > 0)
+	while ((ret = qov_read (&per_ch->vf, (char *)&resampling_buffer[done], (int)(newlength - done), mem_bigendian, 2, 1, &per_ch->bs)) > 0)
 		done += ret;
 
 	Snd_AppendToSndBuffer (sb, resampling_buffer, (size_t)done / (size_t)factor, &per_sfx->format);
diff --git a/snd_wav.c b/snd_wav.c
index 9ca7fa95..438db2ba 100644
--- a/snd_wav.c
+++ b/snd_wav.c
@@ -297,10 +297,9 @@ qboolean S_LoadWavFile (const char *filename, sfx_t *sfx)
 	//if (info.channels == 2)
 	//	Log_Printf("stereosounds.log", "%s\n", sfx->name);
 
-#if BYTE_ORDER != LITTLE_ENDIAN
 	// We must convert the WAV data from little endian
 	// to the machine endianess before resampling it
-	if (info.width == 2)
+	if (info.width == 2 && mem_bigendian)
 	{
 		unsigned int len, i;
 		short* ptr;
@@ -310,7 +309,6 @@ qboolean S_LoadWavFile (const char *filename, sfx_t *sfx)
 		for (i = 0; i < len; i++)
 			ptr[i] = LittleShort (ptr[i]);
 	}
-#endif
 
 	wav_format.speed = info.rate;
 	wav_format.width = info.width;
diff --git a/sv_demo.c b/sv_demo.c
index c5627470..81f169bb 100644
--- a/sv_demo.c
+++ b/sv_demo.c
@@ -27,13 +27,15 @@ void SV_WriteDemoMessage(client_t *client, sizebuf_t *sendbuffer, qboolean clien
 {
 	int len, i;
 	float f;
+	int temp;
 
 	if(client->sv_demo_file == NULL)
 		return;
 	if(sendbuffer->cursize == 0)
 		return;
 	
-	len = LittleLong(sendbuffer->cursize | (clienttoserver ? DEMOMSG_CLIENT_TO_SERVER : 0));
+	temp = sendbuffer->cursize | (clienttoserver ? DEMOMSG_CLIENT_TO_SERVER : 0);
+	len = LittleLong(temp);
 	FS_Write(client->sv_demo_file, &len, 4);
 	for(i = 0; i < 3; ++i)
 	{
diff --git a/zone.c b/zone.c
index 5627097a..0326b06d 100644
--- a/zone.c
+++ b/zone.c
@@ -35,6 +35,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
 unsigned int sentinel_seed;
 
+qboolean mem_bigendian = false;
+
 // LordHavoc: enables our own low-level allocator (instead of malloc)
 #define MEMCLUMPING 0
 #define MEMCLUMPING_FREECLUMPS 0
@@ -43,7 +45,7 @@ unsigned int sentinel_seed;
 // smallest unit we care about is this many bytes
 #define MEMUNIT 128
 // try to do 32MB clumps, but overhead eats into this
-#define MEMWANTCLUMPSIZE (1<<29)
+#define MEMWANTCLUMPSIZE (1<<27)
 // give malloc padding so we can't waste most of a page at the end
 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
@@ -800,6 +802,10 @@ Memory_Init
 */
 void Memory_Init (void)
 {
+	static union {unsigned short s;unsigned char b[2];} u;
+	u.s = 0x100;
+	mem_bigendian = u.b[0];
+
 	sentinel_seed = rand();
 	poolchain = NULL;
 	tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
diff --git a/zone.h b/zone.h
index 40f32298..6caa0390 100644
--- a/zone.h
+++ b/zone.h
@@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #ifndef ZONE_H
 #define ZONE_H
 
+extern qboolean mem_bigendian;
+
 // div0: heap overflow detection paranoia
 #define MEMPARANOIA 0
 
-- 
2.39.5