Skip to content

moudzx/C-Integer-Overflow

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C-Integer-Overflow

integer-overflow Image Reference: https://wizardzines.com/comics/integer-overflow/

Integer overflow is especially problematic for signed integer overflow, which is undefined behavior.

uint x = UINT_MAX + 1; -> overflow + round to 0
int x = INT_MAX + 1; -> overflow + undefined behavior

There's no way to detect int overflows directly in C
But there is hardware support in the CPU, so maybe we can mix C and assembly?

Assembly

after arithmetic instructions [add, sub, mul]
CPU sets flag registers

  • OF = Overflow flag (signed overflow)
  • CF = Carry flag (unsigned overflow)

these flags are available in assembly, but are not directly exposed in C

Assembly instructions:

  • jo (jump if OF=1)
  • seto (set if OF=1)
  • jno (jump if OF=0)
  • jc (jump if CF=1)

GCC and Clang provide compiler intrinsics that perform arithmetic while reporting whether an overflow occurred
bool __builtin_add_overflow(type a, type b, type *result); [/sub/mul]

This is a recreational project.

Usage

#include <ioverflow.h>

int8 a=250;
if (!would_overflow(a,'+',5)) {
    // ..
}

Supports '+', '-' and '*'

typedef unsigned char int8;
typedef unsigned short int int16;
typedef unsigned int int32;

typedef signed char sint8;
typedef signed short int sint16;
typedef signed int sint32;

Build

Requires nasm and a 32-bit capable gcc (gcc-multilib on most distros):

sudo apt install nasm gcc-multilib
make

This produces libioverflow.a.
Install system-wide with:

sudo make install

which drops libioverflow.a into /usr/local/lib and ioverflow.h into /usr/local/include.

About

Hardware-support and (32-bit) Assembly integer overflow detection for C - <ioverflow.h>

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors