Skip to content

Instantly share code, notes, and snippets.

@delcypher
Created December 2, 2016 14:08
Show Gist options
  • Save delcypher/823d741ef5ea20b15e244dd401ffe603 to your computer and use it in GitHub Desktop.
Save delcypher/823d741ef5ea20b15e244dd401ffe603 to your computer and use it in GitHub Desktop.
Use LibFuzzer to look for violations of the result of floating point addition being subnormal implying
#include <assert.h>
#include <fenv.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int is_subnormal(float f) {
return fpclassify(f) == FP_SUBNORMAL;
}
void dump_float(float f, const char* name) {
printf("Dumping float \"%s\"\n", name);
printf("Bad value: %f\n", f);
printf("as hex float: %a\n", f);
// Show as bits
uint32_t as_bits = 0;
memcpy(&as_bits, &f, sizeof(float));
printf("as bits: 0x%.8" PRIx32 "\n", as_bits);
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
float a = 0.0;
float b = 0.0;
if (Size < (sizeof(a) + sizeof(b)))
return 0;
// Big enough
memcpy(&a, Data, sizeof(a));
memcpy(&b, Data + sizeof(a), sizeof(b));
int failure = feclearexcept(FE_ALL_EXCEPT);
assert(!failure);
__asm__ __volatile__ (""); // HACK: Don't move my code plz.
float result = a + b;
__asm__ __volatile__ (""); // HACK: Don't move my code plz.
bool inexact = fetestexcept(FE_INEXACT);
if (!is_subnormal(result))
return 0;
if (inexact) {
dump_float(a, "a");
dump_float(b, "b");
dump_float(result, "result");
abort();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment