pepper-project / pequin

A system for verifying outsourced computations, and applying SNARKs. Simplified release of the main Pepper codebase.
Other
122 stars 46 forks source link

Multiple function calls in same line return value of the last call #45

Open fleupold opened 5 years ago

fleupold commented 5 years ago

Given the following example app:

#include <stdint.h>

struct In { uint32_t in; };
struct Out { uint32_t out; };

uint32_t id(uint32_t x) {
  return x;
}

void compute(struct In *input, struct Out *output) {
  printf("5 is %Zd", id(5));
  printf("5 is %Zd and 7 is %Zd", id(5), id(7));
  uint32_t sum = id(5) + id(7);
  printf("Sum: %Zd", sum);
}

Running it will print:

PRINTF in computation_p 1:
"5 is 5"
PRINTF in computation_p 2:
"5 is 7 and 7 is 7"
PRINTF in computation_p 1:
"Sum: 14"

It looks like id(5) and id(7) return the same value if called in the same line, although they should return different ones. If id(5) is called on its own line, it returns the expected value.

Interestingly, changing the implementation of id to

uint32_t id(uint32_t x) {
  return x + 0;
}

makes the issue go away.

@maxhowald do you have any idea why this could be happening? What would be a good point to start debugging this?

maxhowald commented 5 years ago

Hmm, thanks for reporting this.

I can reproduce the problem using your test case, or an even shorter one:

#include <stdint.h>

struct In { uint32_t in; };
struct Out { uint32_t out; };

uint32_t id(uint32_t x) {
  return x;
}

void compute(struct In *input, struct Out *output) {
  output->out = id(5) + id(7);
}

which produces the following circuit file at compiler/id.c.ZAATAR.circuit:

0 input     //__malloc0.in uint bits 32
7 output gate poly inputs [ C1 * ( ( ) * ( )  + (  ) ) ]    //#compute$__compute__ uint bits 1
8 output gate poly inputs [ C1 * ( ( ) * ( )  + ( C14 ) ) ] //__malloc1.out uint bits 4

Note the wrong constant (C14) is assigned to the output at compile time by the frontend of the compiler.

So it looks like this is a bug in the part of the compiler that reduces constant expressions for functions. My guess is the bug is somewhere in this directory, but I'm not sure exactly where.