tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: New function: consttime_memcmp(3)

   Date: Mon, 16 Mar 2015 02:04:50 +0100
   From: Alistair Crooks <>

   Well, djb's NaCl implementation, which should probably be referred to
   as the reference implementation, has the return statement codified as:

           return (int)(1 & ((ret - 1) >> 8)) - 1;

NaCl doesn't have a memcmp analogue -- it has only a memequal
analogue.  Kamil's proposed addition is memcmp, which provides
lexicographic ordering, not simply equality testing.

We discussed consttime_memcmp a while ago and tossed around some
implementations for fun, but nobody had a use for it.

   Various people have tried to decide why it was done this way, but, in
   any case, trying to second guess optimisers, compilers or djb is not
   my idea of fun, so I'll just leave it at that.

The purpose of that expression is to map zero ret to 0 and nonzero ret
to -1 without conditionals, unlike, e.g., `-!!ret' or `!ret - 1', for
which the compiler may generate a branch.  (E.g., GCC generates a
branch for `!ret - 1' on amd64 with -O0.)

Home | Main Index | Thread Index | Old Index