ioquake / ioq3

The ioquake3 community effort to continue supporting/developing id's Quake III Arena
https://ioquake3.org/
GNU General Public License v2.0
2.38k stars 528 forks source link

Fix OpenArena on glibc 2.37+ and replace all strncpy calls #659

Open zturtleman opened 4 months ago

zturtleman commented 4 months ago

macOS (targeting newer SDKs) and glibc 2.37 changes broke overlapping dest and src in strncpy() used by OpenArena 0.8.8 QVMs. (Technically it was undefined behavior.)

Add Q_strncpy() by Eugene C. from Quake3e that allows overlapping dest and src for QVM strncpy syscalls.

I made everything use Q_strncpyz and it use the new Q_strncpy function. I made QVMs remap the Q_strncpy call to the strncpy syscall in case there is a better idea of how to handle it in the future. I tried to make "strncpy" behave the same in QVMs and DLLs.

Also fix a CGame network buffer overflow due to mishandling of strncpy. NUL terminator is great but it's better when it's in the destination buffer.

Fixes https://github.com/ioquake/ioq3/pull/639.

zturtleman commented 4 months ago
ec- commented 3 months ago

I'm implemented both src >= dst and src < dst cases :

char *Q_strncpy( char *dest, char *src, int destsize )
{
    char *s = src, *start = dest;
    int src_len;

    while ( *s != '\0' )
        ++s;
    src_len = (int)(s - src);

    if ( src_len > destsize ) {
        src_len = destsize;
    }
    destsize -= src_len;

    if ( dest > src && dest < src + src_len ) {
        int i;
#ifdef _DEBUG
        Com_Printf( S_COLOR_YELLOW "Q_strncpy: overlapped (dest > src) buffers\n" );
#endif
        for ( i = src_len - 1; i >= 0; --i ) {
            dest[i] = src[i]; // back overlapping
        }
        dest += src_len;
    } else {
#ifdef _DEBUG
        if ( src >= dest && src < dest + src_len ) {
            Com_Printf( S_COLOR_YELLOW "Q_strncpy: overlapped (src >= dst) buffers\n" );
#ifdef _MSC_VER
            // __debugbreak();
#endif 
        }
#endif
        while ( src_len > 0 ) {
            *dest++ = *src++;
            --src_len;
        }
    }

    while ( destsize > 0 ) {
        *dest++ = '\0';
        --destsize;
    }

    return start;
}

it is longer than any suggested/existing version but fully inline and do not have any references to external functions like memmove()

If you want to use it in QVM code then you should replace all post-increment assignments like *dest++ = '\0'; with *dest = '\0'; ++dest; because LCC generates suboptimal code for such cases

zturtleman commented 3 months ago

Thank you. I don't compile it in QVMs, it's only called it through the strncpy syscall.