leethomason / tinyxml2

TinyXML2 is a simple, small, efficient, C++ XML parser that can be easily integrated into other programs.
zlib License
5.11k stars 1.84k forks source link

XMLPrinter::Write() error and possible overflow. #1000

Open willywa opened 1 month ago

willywa commented 1 month ago

A very recent download (this week) has

void XMLPrinter::Write( const char* data, size_t size )
{
    if ( _fp ) {
        fwrite ( data , sizeof(char), size, _fp);
    }
    else {
        char* p = _buffer.PushArr( static_cast<int>(size) ) - 1;   // back up over the null terminator.
        memcpy( p, data, size );
        p[size] = 0;
    }
}

On many platforms, int is 32 bit but size_t is 64 bit. That static_cast(size) could result in an integer much smaller than the original size, meaning the later memcpy() has a good chance of trashing memory.

It may be that the tinyxml2 code would never call Write() with a size that large, but since Write is protected (not private), some class derived from XMLPrinter could do so.

It is not clear to me what the static_cast accomplishes, since PushArr expects a size_t argument.