Opened 7 years ago

Closed 20 months ago

#11726 closed Bugs (fixed)

boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1

Reported by: davidlt Owned by: Joel de Guzman
Milestone: To Be Determined Component: spirit
Version: Boost 1.57.0 Severity: Problem
Keywords: spirit Cc:

Description

Boost Spirit is triggered undefined behaviour in C++.

#include <iostream>

#include <boost/spirit/home/support/detail/endian.hpp>

int main(void) {
  const unsigned char raw_bytes[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
  long long result = boost::spirit::detail::load_little_endian<long long, 8ul>(raw_bytes);
  std::cout << result << std::endl;
  return 0;
}

or

#include <iostream>
#include <memory>
#include <tuple>

#include <boost/spirit/home/support/detail/endian.hpp>

int main(void) {
  long long* p;
  std::size_t sz;
  std::tie(p, sz)  = std::get_temporary_buffer<long long>(1);
  assert(sz != 0);
  boost::spirit::detail::store_little_endian<long long, 8ul>(p, -1);

  long long result2 = boost::spirit::detail::load_little_endian<long long, 8ul>(p);
  std::cout << result2 << std::endl;
  return 0;
}

Compile:

g++ -fsanitize=undefined -fno-omit-frame-pointer -g -std=c++14 -O2 test.cpp

Used GCC 4.9.3 in my case.

Result:

/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
/usr/include/boost/spirit/home/support/detail/endian/endian.hpp:76:57: runtime error: left shift of negative value -1
-1

Tested with Boost 1.57, but code has not been changed in master.

I guess, this will trigger undefined behaviour every time a singed type is used. Reference: C++ standard 5.8 "Shift operators" section.

From Boost:

     75       static T load_little(const unsigned char* bytes)
     76         { return *bytes | (next::load_little(bytes + 1) << 8); }

Attachments (1)

0001-Fix-undefined-behavior-in-.-support-detail-endian-en.patch (3.7 KB ) - added by davidlt 7 years ago.
proposed patch (same as on GitHub)

Download all attachments as: .zip

Change History (3)

by davidlt, 7 years ago

proposed patch (same as on GitHub)

comment:2 by Joel de Guzman, 20 months ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.