[openssl-project] Style guide updates

Matt Caswell matt at openssl.org
Sat Jan 27 00:26:38 UTC 2018



On 26/01/18 20:27, Kurt Roeckx wrote:
> On Fri, Jan 26, 2018 at 02:06:27PM +0000, Matt Caswell wrote:
>> - Use size_t for sizes of things
> 
> How do you feel about ssize_t?

When I did the size_t work in libssl one of things I was trying hard to
eradicate was the constant casting of types from one thing to another.
It was common to see things like one function use an int for a size, and
then pass that to a function that uses a long for a size, but which then
needs to call something that uses a size_t. I saw numerous instances of
the same values being cast 4 or 5 times in a single chain of events
(often going back and forwards between the same type).

Such casts are dangerous and should be avoided as much as possible.
Negative numbers can suddenly become large positives. Large positives
can suddenly get truncated or go negative. Stuff that works safely on
one platform is dangerous on another. You have to be really careful
about bounds checking, and experience showed that we just weren't that
good at it.

By deciding on a single type for sizes we can avoid lots of casts. The
same argument might apply for other types of things too - but sizes are
an extremely common instance of this. size_t is here to stay (we are
already committed to in our API, and many C library calls expect it). I
think that, in general, introducing ssize_t into the mix is not helpful.
It will inevitably lead to casts between size_t and ssize_t and back
again - and all the problems that that entails.

Obviously the argument for using ssize_t is its ability to hold negative
numbers. Actually though it is quite rare for something to validly have
a negative size. Often the reason for wanting a negative value is to be
able to have some kind of error state (e.g. <0 means error, >=0 means
its a real size). This is then trying to force two different types of
meaning into a single thing and introduces even more problems. Suddenly
an error code when cast to a size_t becomes a valid size and vice versa.
I think we should generally be trying to avoid APIs (internal and
external) that work like that. Instead we should try and separate the
concepts, e.g. the return code of a function is a simple success/failure
indicator; a returned size is passed back via a pointer argument.

I wouldn't say that we should never use ssize_t. There are real uses for
this, e.g. an offset into something. An offset could quite legitimately
have a positive value or a negative value. An offset though is not a
size so casts between a size thing and an offset are less likely to
happen. More likely is an addition of a size_t and an ssize_t which will
require some casting to get the expected result - but that is probably
unavoidable.

Matt


More information about the openssl-project mailing list