mirror of
https://git.tartarus.org/simon/putty.git
synced 2025-07-01 03:22:48 -05:00
Tighten up a lot of casts from unsigned to int which are read by one
of the GET_32BIT macros and then used as length fields. Missing bounds checks against zero have been added, and also I've introduced a helper function toint() which casts from unsigned to int in such a way as to avoid C undefined behaviour, since I'm not sure I trust compilers any more to do the obviously sensible thing. [originally from svn r9918]
This commit is contained in:
23
misc.c
23
misc.c
@ -208,6 +208,29 @@ void burnstr(char *string) /* sfree(str), only clear it first */
|
||||
}
|
||||
}
|
||||
|
||||
int toint(unsigned u)
|
||||
{
|
||||
/*
|
||||
* Convert an unsigned to an int, without running into the
|
||||
* undefined behaviour which happens by the strict C standard if
|
||||
* the value overflows. You'd hope that sensible compilers would
|
||||
* do the sensible thing in response to a cast, but actually I
|
||||
* don't trust modern compilers not to do silly things like
|
||||
* assuming that _obviously_ you wouldn't have caused an overflow
|
||||
* and so they can elide an 'if (i < 0)' test immediately after
|
||||
* the cast.
|
||||
*
|
||||
* Sensible compilers ought of course to optimise this entire
|
||||
* function into 'just return the input value'!
|
||||
*/
|
||||
if (u <= (unsigned)INT_MAX)
|
||||
return (int)u;
|
||||
else if (u >= (unsigned)INT_MIN) /* wrap in cast _to_ unsigned is OK */
|
||||
return INT_MIN + (int)(u - (unsigned)INT_MIN);
|
||||
else
|
||||
return INT_MIN; /* fallback; should never occur on binary machines */
|
||||
}
|
||||
|
||||
/*
|
||||
* Do an sprintf(), but into a custom-allocated buffer.
|
||||
*
|
||||
|
Reference in New Issue
Block a user