Skip to content

Instantly share code, notes, and snippets.

@srgoogleguy
Created August 18, 2015 03:27
Show Gist options
  • Save srgoogleguy/6fc65988aedcd8fed3d7 to your computer and use it in GitHub Desktop.
Save srgoogleguy/6fc65988aedcd8fed3d7 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int add_i64(int64_t a, int64_t b, int64_t* r)
{
volatile int overflow = 1;
volatile int64_t result = a + b;
asm volatile
(
"jno 1f ;"
"movl $0, %[xo] ;"
"1: ;"
: [xo] "=m" (overflow)
);
if(r)
*r = result;
return overflow;
}
void main() {
int64_t a,b,x,y,z;
int64_t r = 0;
int c;
a = 536870919;
b = 2147483647;
x = 2305843009213693952;
y = -498763014;
z = 6917529027641081856;
c = add_i64(a,b,&r);
if (!c) {
printf("Integer overflow detected adding %"PRIi64" and %"PRIi64"\n", a, b);
} else {
printf("result = %"PRIi64"\n", r);
}
r = 0;
c = add_i64(x,y,&r);
if (!c) {
printf("Integer overflow detected adding %"PRIi64" and %"PRIi64"\n", x, y);
} else {
printf("result = %"PRIi64"\n", r);
}
r = 0;
c = add_i64(z,x,&r);
if (!c) {
printf("Integer overflow detected adding %"PRIi64" and %"PRIi64"\n", z, x);
} else {
printf("result = %"PRIi64"\n", r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment