On Thu, 7 Jul 2005, Andy Polyakov wrote:

>>>> 1) In openssl-0.9.8/crypto/des/cfb_enc.c line 170 there is "memcpy
>>>> (ovec,ovec+num,8);" and since ovec and ovec+num will overlap
>>>> sometimes,
>>>> this function relies on undocumented/undefined behavior of memcpy?
>>> The original reason for choosing of memcpy was a) it's comonly inlined
>>> by compilers [most notably gcc], but not memmove, b) I fail to imagine
>>> how it can fail with overlapping regions if num is guaranteed to be
>>> positive, even if the routine is super-optimized, inlined, whatever. Can
>>> you?

>> This doesn't make any sense - if memcpy can handle overlapping regions
>> without any slowdown, then wouldn't it make sense to implemenent
>> memmove as a #define (or inline call to) memcpy?

> Do note "[when] num [as in memcpy(ovec,ovec+num,8)] is guaranteed to be
> positive." Question was can you imagine memcpy implementation that would fail
> to handle overlapping regions when source address is *larger* than
> destination? Question was *not* if you can imagine memcpy implementation that
> would fail to handle arbitrary overlapping regions.


void * memcpy(void * dst, const void * src, size_t len) {
char * d = ((char *) dst) + len;
const char * s = ((const char *) src) + len;

while (len-- > 0) {
*--d = *--s;
return dst;

This is a fully conformant implementation of memcpy. Not sure why you'd
implement it this way, but it's legal.

>> Either memcpy does
>> not handle overlaps while memmove does, or memcpy and memmove work at
>> the same speed, because the ability to handle overlapping memory
>> regions is the only difference between the two.

> See a). Inlining is believed/expected to be faster than call to a function.

This is not always true. If the inlining causes the code size to bloat
and no longer fit into cache, for example. Also, shared copies of the
function can share branch prediction information.

It is true in this case, I mention. At least on the x86.

But this is an example of programming by coincidence.


__________________________________________________ ____________________
OpenSSL Project http://www.openssl.org
Development Mailing List openssl-dev@openssl.org
Automated List Manager majordomo@openssl.org