libmodbus icon indicating copy to clipboard operation
libmodbus copied to clipboard

incorrect type to store socket on Windows

Open Swiftkill opened this issue 2 years ago • 2 comments

modbus-private.h:100 int s;

SOCKET on Windows is not int, it's a larger type - int64_t*.

Swiftkill avatar Dec 14 '23 14:12 Swiftkill

Do you mean int are not set according to the underlying architecture on Windows (64 bits)?!

stephane avatar Oct 22 '24 12:10 stephane

Not on all compilers, no, not in all compile modes either, and ISO standard doesn't prescribe it. You got no guarantee that happen. Tha's more typical for embedded or microcontroller stuff. Nether x86-64 gcc nor MSVC does that (the latter is where I spotted the problem). The headers Winsock.h and Winsock2.h (POSIX-esque and async API) are ones where that type is defined , same headers are used both for x32 and x64:

typedef UINT_PTR        SOCKET;

basetsd.h:

#if defined(_WIN64)
    typedef __int64 INT_PTR, *PINT_PTR;
#else
    typedef _W64 int INT_PTR, *PINT_PTR;
#endif

https://learn.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-170

So on Windows you're safe to use uintptr_t to cast a SOCKET to, I suppose, but some guaranteed size type is better. Random tests may show that everything is ok because descripor pointer value often stays low. Infamous Windows's HANDLE is also a pointer to void now. it used to be int, just as SOCKET in times of of Win98\Win2000, so you can find a legacy code that relies on it.

Swiftkill avatar Dec 21 '24 01:12 Swiftkill