Skip to content

Commit

Permalink
Avoid use of ftime() and fix overflow of unsigned int
Browse files Browse the repository at this point in the history
ftime() is an obsolete interface, and <sys/timeb.h> may not be present on all platforms.
Also, multiplying a time_t by 1000 will overflow the range of an unsigned 32-bit int.
  • Loading branch information
th-otto committed Mar 19, 2024
1 parent ffd4077 commit 3043fc6
Showing 1 changed file with 8 additions and 11 deletions.
19 changes: 8 additions & 11 deletions common/connect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

#include <stdio.h>
//#include <mem.h>
#include <sys/timeb.h>
#include <chrono>
#include <string.h>
#include "connect.h"

Expand Down Expand Up @@ -227,6 +227,8 @@ int ConnectionClass::Send_Packet(void* buf, int buflen, int ack_req)

SwapCommHeaderType((CommHeaderType*)PacketBuf);

SwapCommHeaderType((CommHeaderType*)PacketBuf);

/*------------------------------------------------------------------------
Now build the packet
------------------------------------------------------------------------*/
Expand Down Expand Up @@ -747,7 +749,6 @@ int ConnectionClass::Service_Receive_Queue(void)
*=========================================================================*/
unsigned int ConnectionClass::Time(void)
{
static struct timeb mytime; // DOS time
unsigned int msec;

#ifdef WWLIB32_H
Expand All @@ -764,23 +765,19 @@ unsigned int ConnectionClass::Time(void)
/*------------------------------------------------------------------------
Otherwise, use the DOS timer
------------------------------------------------------------------------*/
else {
ftime(&mytime);
msec = (unsigned int)mytime.time * 1000 + (unsigned int)mytime.millitm;
return ((msec / 100) * 6);
}

#else

/*------------------------------------------------------------------------
If the Westwood library isn't being used, use the DOS timer.
------------------------------------------------------------------------*/
ftime(&mytime);
msec = (unsigned int)mytime.time * 1000 + (unsigned int)mytime.millitm;
return ((msec / 100) * 6);

#endif

static auto epoch = std::chrono::steady_clock::now().time_since_epoch();
auto now = std::chrono::steady_clock::now().time_since_epoch();
msec = unsigned(std::chrono::duration_cast<std::chrono::milliseconds>(now - epoch).count());

return ((msec / 100) * 6);
} /* end of Time */

/***************************************************************************
Expand Down

0 comments on commit 3043fc6

Please sign in to comment.