Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How difficult is source-level detection of arrays of runtime bounds?

The (accepted) proposal for "Runtime-sized arrays with automatic storage duration (N3639)" asserts that

Stack overflow becomes more likely, in particular if the size depends on external input and is not properly checked. Some environments might therefore prohibit the use of the feature. Such a prohibition can be easily enforced with a static analysis tool.

I do not consider enforcement to be easy if it requires the analyzer to implement a full C++ compiler.

Consider the following code:

template<typename T>
inline void array_user( const T& x )
{
    int a[f(traits<T>::omega)];
}

It looks to me like the analysis needs to be repeated for each use of array_user<T> and consider:

  • Applicable specializations of traits<T> discoverable at the point of use of array_user<T>
  • Whether traits<T>::omega is a compile-time constant expression (either via constexpr or C++03 approaches such as enum)
  • The type of traits<T>::omega
  • Whether the applicable overload of f() (at the point of use of array_user<T> and possibly found via ADL) is constexpr

Am I missing something? Is it possible to enforce such a restriction without going through full compilation?

Can code be written in such a way to simplify verification of non-use of runtime bounds?

like image 632
Ben Voigt Avatar asked Aug 01 '13 20:08

Ben Voigt


1 Answers

If I were tasked with writing an analyzer to statically verify non-use of runtime-bounds, I would reject the above code. I would require all array declarations to either use an integral literal for the bound or be annotated to have the compiler reject runtime-bounds.

template<typename T>
inline void array_user( const T& x )
{
    int a[f(traits<T>::omega)];
    sizeof a;
}

However, given the number of compilers that currently provide C99-style VLAs in C++ mode as an extension, I'm not confident that they would actually conform to the C++14 behavior of forbidding sizeof.

like image 200
Ben Voigt Avatar answered Nov 07 '22 00:11

Ben Voigt