Thread (1 message) 1 message, 1 author, 2016-06-15

Re: [PATCH] block-sha1: Windows declares ntohl() in winsock2.h

From: Junio C Hamano <hidden>
Date: 2016-06-15 22:47:16
Subsystem: the rest · Maintainer: Linus Torvalds

Possibly related (same subject, not in this thread)

Sebastian Schuberth [off-list ref] writes:
On Tue, Aug 18, 2009 at 18:08, Linus
Torvalds[off-list ref] wrote:
quoted
quoted
I'd suggest not using a gcc builtin, since if you're using gcc you might
as well just use inline asm that has been around forever (unlike the
builtin).
That seems to be what glibc does too.

Here's a patch.
Looks good to me, compiles & runs fine on Windows (with Hannes' patch
also applied).
But the Windows part that avoids arpa/inet.h and includes winsock2.h, only
to undef the two macros immediately after doing so, now looks quite silly.
Are there non i386/amd64 Windows we care about?

Squashing Linus's and Hannes's patch here is what I came up with.

-- >8 --
block-sha1: avoid potentially inefficient ntohl/htonl on i386/x86-64

Johannes Sixt reports that on Windows ntohl()/htonl() are not found in
<arpa/inet.h>, and minimally we need to include <winsock2.h> instead.
Sebastian Schuberth points out that they are implemented as out-of-line
functions on Windows, which defeats the use of these byteorder "macros"
for performance.

Use bswap instruction through gcc inline asm instead on i386/x86-64
as a generic solution to this.

Signed-off-by: Johannes Sixt <redacted>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>,
---
diff --git a/block-sha1/sha1.c b/block-sha1/sha1.c
index a1228cf..fa909a3 100644
--- a/block-sha1/sha1.c
+++ b/block-sha1/sha1.c
@@ -7,8 +7,6 @@
  */
 
 #include <string.h>
-#include <arpa/inet.h>
-
 #include "sha1.h"
 
 #if defined(__i386__) || defined(__x86_64__)
@@ -24,8 +22,15 @@
 #define SHA_ROL(x,n)	SHA_ASM("rol", x, n)
 #define SHA_ROR(x,n)	SHA_ASM("ror", x, n)
 
+#undef htonl
+#undef ntohl
+#define htonl(x) ({ unsigned int __res; __asm__("bswap %0":"=r" (__res):"0" (x)); __res; })
+#define ntohl(x) htonl(x)
+
 #else
 
+#include <arpa/inet.h>
+
 #define SHA_ROT(X,l,r)	(((X) << (l)) | ((X) >> (r)))
 #define SHA_ROL(X,n)	SHA_ROT(X,n,32-(n))
 #define SHA_ROR(X,n)	SHA_ROT(X,32-(n),n)
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help