Something very weird happens when I control my code execution to fish out integer overflows. The control program checks the value of the overflow flag using inline assembly.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int add_u32(uint32_t a, uint32_t b, uint32_t* r) {
volatile int no_overflow = 1;
volatile uint32_t result = a * b;
__asm__ __volatile__ (
"jno 1f ;"
"movl $0, %[xo] ;" "1: ;"
: [xo] "=m" (no_overflow) );
if (r)
*r = result;
printf("overflow flag:%d\n", no_overflow);
return no_overflow;
}
int main(void) {
uint32_t quantity;
uint32_t price = 5;
uint32_t total;
printf("Please enter desired quantity\n");
scanf("%d", &quantity);
if (add_u32(quantity, price, &total) == 0) {
printf("Wrong input, program shutting down...");
return (1);
}
else {
printf("Total price:%d\n", total);
}
return (0); }
This code detects payloads like
123456789123
but payloads like:
//123456789123222900000 results in 836000
//123456789123222800000 results in 336000
//123456789123222733000 results in 1000
//123456789123222732801 results in 5
Why does this happen and how can I fix this?