satoren / kaguya

C++ binding to Lua
Boost Software License 1.0
345 stars 70 forks source link

Check range of integral when converting from number #91

Open Flamefire opened 5 years ago

Flamefire commented 5 years ago

In Lua numbers are essentially doubles. So the following is valid in lua: foo(-1)

If this is bound to a C++ function void foo(unsigned i) it silently does the wrong thing.

This is caused by the unchecked cast at: https://github.com/satoren/kaguya/blob/38ca7e1d894c138e454bbe5c89048bdd5091545a/include/kaguya/type.hpp#L520

Similar problem for C++ function void bar(int8_t i) called with foo(1000)

Proposed fix:


lua_Number num = lua_type_traits<lua_Number>::get(l, index);
if(num < std::numeric_limits<get_type>::min() || num > std::numeric_limits<get_type>::max())
  throw LuaTypeMismatch();
return static_cast<get_type>(num);

Probably extract the check to a standalone function as it is also required at other places (e.g. opt and for Lua 5.3)

Not sure if this breaks the contract of strictCheckType as it may be possible, that a value passes the check (just from checking types) but fails to be gotten as it is outside the range.