#!/usr/bin/env python3

import random

# ----- precomputed test vectors

precomputed = {}

# -----

Z = r'''/* WARNING: auto-generated (by autogen/test); do not edit */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/resource.h>
#include "crypto_uint8.h"
#include "crypto_uint32.h"
#include "crypto_uint64.h"
#include "crypto_declassify.h"
#include <mceliece.h> /* -lmceliece */
#include <randombytes.h>

static const char *targeto = 0;
static const char *targetp = 0;
static const char *targeti = 0;
static const char *targetn = 0;
static const char *targetoffset = 0;

static int ok = 1;

#define fail ((ok = 0),printf)

/* ----- valgrind support */

static int valgrind = 0;
static unsigned char valgrind_undefined_byte = 0;
static char *volatile valgrind_pointer = 0;

static char *valgrind_malloc_1(void)
{
  char *x = (char *) malloc(1);
  if (!x) abort();
  *(char **volatile) &valgrind_pointer = x;
  return valgrind_pointer;
}

static void valgrind_init(void)
{
  char *e = getenv("valgrind_multiplier");
  char *x;
  if (!e) return;
  x = valgrind_malloc_1();
  valgrind_undefined_byte = x[0]+1;
  valgrind_undefined_byte *= atoi(e);
  valgrind_undefined_byte ^= x[0]+1;
  free(x);
  valgrind = 1;
}

static void secret(void *xvoid,long long xlen)
{
  unsigned char *x = (unsigned char *) xvoid;
  while (xlen > 0) {
    *x ^= valgrind_undefined_byte;
    ++x;
    --xlen;
  }
}

static void declassify(void *x,long long xlen)
{
  crypto_declassify(x,xlen);
}

/* ----- rng and hash, from supercop/try-anything.c */

typedef crypto_uint8 u8;
typedef crypto_uint32 u32;
typedef crypto_uint64 u64;

#define FOR(i,n) for (i = 0;i < n;++i)

static u32 L32(u32 x,int c) { return (x << c) | ((x&0xffffffff) >> (32 - c)); }

static u32 ld32(const u8 *x)
{
  u32 u = x[3];
  u = (u<<8)|x[2];
  u = (u<<8)|x[1];
  return (u<<8)|x[0];
}

static void st32(u8 *x,u32 u)
{
  int i;
  FOR(i,4) { x[i] = u; u >>= 8; }
}

static const u8 sigma[17] = "expand 32-byte k";

static void core_salsa(u8 *out,const u8 *in,const u8 *k)
{
  u32 w[16],x[16],y[16],t[4];
  int i,j,m;

  FOR(i,4) {
    x[5*i] = ld32(sigma+4*i);
    x[1+i] = ld32(k+4*i);
    x[6+i] = ld32(in+4*i);
    x[11+i] = ld32(k+16+4*i);
  }

  FOR(i,16) y[i] = x[i];

  FOR(i,20) {
    FOR(j,4) {
      FOR(m,4) t[m] = x[(5*j+4*m)%16];
      t[1] ^= L32(t[0]+t[3], 7);
      t[2] ^= L32(t[1]+t[0], 9);
      t[3] ^= L32(t[2]+t[1],13);
      t[0] ^= L32(t[3]+t[2],18);
      FOR(m,4) w[4*j+(j+m)%4] = t[m];
    }
    FOR(m,16) x[m] = w[m];
  }

  FOR(i,16) st32(out + 4 * i,x[i] + y[i]);
}

static void salsa20(u8 *c,u64 b,const u8 *n,const u8 *k)
{
  u8 z[16],x[64];
  u32 u,i;
  if (!b) return;
  FOR(i,16) z[i] = 0;
  FOR(i,8) z[i] = n[i];
  while (b >= 64) {
    core_salsa(x,z,k);
    FOR(i,64) c[i] = x[i];
    u = 1;
    for (i = 8;i < 16;++i) {
      u += (u32) z[i];
      z[i] = u;
      u >>= 8;
    }
    b -= 64;
    c += 64;
  }
  if (b) {
    core_salsa(x,z,k);
    FOR(i,b) c[i] = x[i];
  }
}

static void increment(u8 *n)
{
  if (!++n[0])
    if (!++n[1])
      if (!++n[2])
        if (!++n[3])
          if (!++n[4])
            if (!++n[5])
              if (!++n[6])
                if (!++n[7])
                  ;
}

static unsigned char testvector_n[8];

static void testvector_clear(void)
{
  memset(testvector_n,0,sizeof testvector_n);
}

static void testvector(unsigned char *x,unsigned long long xlen)
{
  const static unsigned char testvector_k[33] = "generate inputs for test vectors";
  salsa20(x,xlen,testvector_n,testvector_k);
  increment(testvector_n);
}

static unsigned long long myrandom(void)
{
  unsigned char x[8];
  unsigned long long result;
  testvector(x,8);
  result = x[7];
  result = (result<<8)|x[6];
  result = (result<<8)|x[5];
  result = (result<<8)|x[4];
  result = (result<<8)|x[3];
  result = (result<<8)|x[2];
  result = (result<<8)|x[1];
  result = (result<<8)|x[0];
  return result;
}

static unsigned char canary_n[8];

static void canary(unsigned char *x,unsigned long long xlen)
{
  const static unsigned char canary_k[33] = "generate pad to catch overwrites";
  salsa20(x,xlen,canary_n,canary_k);
  increment(canary_n);
}

static void double_canary(unsigned char *x2,unsigned char *x,unsigned long long xlen)
{
  if (valgrind) return;
  canary(x - 16,16);
  canary(x + xlen,16);
  memcpy(x2 - 16,x - 16,16);
  memcpy(x2 + xlen,x + xlen,16);
}

static void input_prepare(unsigned char *x2,unsigned char *x,unsigned long long xlen)
{
  testvector(x,xlen);
  if (valgrind) {
    memcpy(x2,x,xlen);
    return;
  }
  canary(x - 16,16);
  canary(x + xlen,16);
  memcpy(x2 - 16,x - 16,xlen + 32);
}

static void input_compare(const unsigned char *x2,const unsigned char *x,unsigned long long xlen,const char *fun)
{
  if (valgrind) return;
  if (memcmp(x2 - 16,x - 16,xlen + 32)) {
    fail("failure: %s overwrites input\n",fun);
  }
}

static void output_prepare(unsigned char *x2,unsigned char *x,unsigned long long xlen)
{
  if (valgrind) {
    memcpy(x2,x,xlen);
    return;
  }
  canary(x - 16,xlen + 32);
  memcpy(x2 - 16,x - 16,xlen + 32);
}

static void output_compare(const unsigned char *x2,const unsigned char *x,unsigned long long xlen,const char *fun)
{
  if (valgrind) return;
  if (memcmp(x2 - 16,x - 16,16)) {
    fail("failure: %s writes before output\n",fun);
  }
  if (memcmp(x2 + xlen,x + xlen,16)) {
    fail("failure: %s writes after output\n",fun);
  }
}

/* ----- knownrandombytes */

static const int knownrandombytes_is_only_for_testing_not_for_cryptographic_use = 1;
#define knownrandombytes randombytes

#define QUARTERROUND(a,b,c,d) \
  a += b; d = L32(d^a,16); \
  c += d; b = L32(b^c,12); \
  a += b; d = L32(d^a, 8); \
  c += d; b = L32(b^c, 7);

static void core_chacha(u8 *out,const u8 *in,const u8 *k)
{
  u32 x[16],y[16];
  int i,j;
  FOR(i,4) {
    x[i] = ld32(sigma+4*i);
    x[12+i] = ld32(in+4*i);
  }
  FOR(i,8) x[4+i] = ld32(k+4*i);
  FOR(i,16) y[i] = x[i];
  FOR(i,10) {
    FOR(j,4) { QUARTERROUND(x[j],x[j+4],x[j+8],x[j+12]) }
    FOR(j,4) { QUARTERROUND(x[j],x[((j+1)&3)+4],x[((j+2)&3)+8],x[((j+3)&3)+12]) }
  }
  FOR(i,16) st32(out+4*i,x[i]+y[i]);
}

static void chacha20(u8 *c,u64 b,const u8 *n,const u8 *k)
{
  u8 z[16],x[64];
  u32 u,i;
  if (!b) return;
  FOR(i,16) z[i] = 0;
  FOR(i,8) z[i+8] = n[i];
  while (b >= 64) {
    core_chacha(x,z,k);
    FOR(i,64) c[i] = x[i];
    u = 1;
    FOR(i,8) {
      u += (u32) z[i];
      z[i] = u;
      u >>= 8;
    }
    b -= 64;
    c += 64;
  }
  if (b) {
    core_chacha(x,z,k);
    FOR(i,b) c[i] = x[i];
  }
}

#define crypto_rng_OUTPUTBYTES 736

static int crypto_rng(
        unsigned char *r, /* random output */
        unsigned char *n, /* new key */
  const unsigned char *g  /* old key */
)
{
  static const unsigned char nonce[8] = {0};
  unsigned char x[32+crypto_rng_OUTPUTBYTES];
  chacha20(x,sizeof x,nonce,g);
  memcpy(n,x,32);
  memcpy(r,x+32,crypto_rng_OUTPUTBYTES);
  return 0;
}

static unsigned char knownrandombytes_g[32];
static unsigned char knownrandombytes_r[crypto_rng_OUTPUTBYTES];
static unsigned long long knownrandombytes_pos = crypto_rng_OUTPUTBYTES;

static void knownrandombytes_clear(void)
{
  memset(knownrandombytes_g,0,sizeof knownrandombytes_g);
  memset(knownrandombytes_r,0,sizeof knownrandombytes_r);
  knownrandombytes_pos = crypto_rng_OUTPUTBYTES;
}

void knownrandombytes_main(void *xvoid,long long xlen)
{
  unsigned char *x = (unsigned char *) xvoid;
  assert(knownrandombytes_is_only_for_testing_not_for_cryptographic_use);

  while (xlen > 0) {
    if (knownrandombytes_pos == crypto_rng_OUTPUTBYTES) {
      crypto_rng(knownrandombytes_r,knownrandombytes_g,knownrandombytes_g);
      knownrandombytes_pos = 0;
    }
    *x++ = knownrandombytes_r[knownrandombytes_pos];
    xlen -= 1;
    knownrandombytes_r[knownrandombytes_pos++] = 0;
  }
}

void knownrandombytes(void *xvoid,long long xlen)
{
  knownrandombytes_main(xvoid,xlen);
  secret(xvoid,xlen);
}

/* ----- checksums */

static unsigned char checksum_state[64];
static char checksum_hex[65];

static void checksum_expected(const char *expected)
{
  long long i;
  for (i = 0;i < 32;++i) {
    checksum_hex[2 * i] = "0123456789abcdef"[15 & (checksum_state[i] >> 4)];
    checksum_hex[2 * i + 1] = "0123456789abcdef"[15 & checksum_state[i]];
  }
  checksum_hex[2 * i] = 0;

  if (strcmp(checksum_hex,expected))
    fail("failure: checksum mismatch: %s expected %s\n",checksum_hex,expected);
}

static void checksum_clear(void)
{
  memset(checksum_state,0,sizeof checksum_state);
  knownrandombytes_clear();
  testvector_clear();
  /* not necessary to clear canary */
}

static void checksum(const unsigned char *x,unsigned long long xlen)
{
  u8 block[16];
  int i;
  while (xlen >= 16) {
    core_salsa(checksum_state,x,checksum_state);
    x += 16;
    xlen -= 16;
  }
  FOR(i,16) block[i] = 0;
  FOR(i,xlen) block[i] = x[i];
  block[xlen] = 1;
  checksum_state[0] ^= 1;
  core_salsa(checksum_state,block,checksum_state);
}

#include "limits.inc"

static void *callocplus(long long len)
{
  if (valgrind) {
    unsigned char *x = (unsigned char *) malloc(len);
    if (!x) abort();
    return x;
  } else {
    unsigned char *x = (unsigned char *) calloc(1,len + 256);
    long long i;
    if (!x) abort();
    for (i = 0;i < len + 256;++i) x[i] = random();
    return x;
  }
}

static void *aligned(void *x,long long len)
{
  if (valgrind)
    return x;
  else {
    long long i;
    unsigned char *y = (unsigned char *) x;
    y += 64;
    y += 63 & (-(unsigned long) y);
    for (i = 0;i < len;++i) y[i] = 0;
    return y;
  }
}

/* ----- catching SIGILL, SIGBUS, SIGSEGV, etc. */

static void forked(void (*test)(long long),long long impl)
{
  if (valgrind) {
    test(impl);
    return;
  }
  fflush(stdout);
  pid_t child = fork();
  int childstatus = -1;
  if (child == -1) {
    fprintf(stderr,"fatal: fork failed: %s",strerror(errno));
    exit(111);
  }
  if (child == 0) {
    ok = 1;
    limits();
    test(impl);
    if (!ok) exit(100);
    exit(0);
  }
  if (waitpid(child,&childstatus,0) != child) {
    fprintf(stderr,"fatal: wait failed: %s",strerror(errno));
    exit(111);
  }
  if (childstatus)
    fail("failure: process failed, status %d\n",childstatus);
  fflush(stdout);
}

/* ----- endianness */

/* on big-endian machines, flip into little-endian */
/* other types of endianness are not supported */
static void endianness(unsigned char *e,unsigned long long words,unsigned long long bytesperword)
{
  long long i = 1;

  if (1 == *(unsigned char *) &i) return;

  while (words > 0) {
    for (i = 0;2 * i < bytesperword;++i) {
      long long j = bytesperword - 1 - i;
      unsigned char ei = e[i];
      e[i] = e[j];
      e[j] = ei;
    }
    e += bytesperword;
    words -= 1;
  }
}
'''

checksums = {}
operations = []
primitives = {}
sizes = {}
exports = {}
prototypes = {}
nooverlap = set()

with open('api') as f:
  for line in f:
    line = line.strip()
    if line.startswith('crypto_'):
      line = line.split()
      x = line[0].split('/')
      assert len(x) == 2
      o = x[0].split('_')[1]
      if o not in operations: operations += [o]
      p = x[1]
      if o not in primitives: primitives[o] = []
      primitives[o] += [p]
      if len(line) >= 3:
        checksums[o,p] = line[1],line[2]
      for option in line[3:]:
        if option == 'nooverlap':
          nooverlap.add((o,p))
      continue
    if line.startswith('#define '):
      x = line.split(' ')
      x = x[1].split('_')
      assert len(x) == 4
      assert x[0] == 'crypto'
      o = x[1]
      p = x[2]
      if (o,p) not in sizes: sizes[o,p] = ''
      sizes[o,p] += line+'\n'
      continue
    if line.endswith(');'):
      fun,args = line[:-2].split('(')
      rettype,fun = fun.split()
      fun = fun.split('_')
      o = fun[1]
      assert fun[0] == 'crypto'
      if o not in exports: exports[o] = []
      exports[o] += ['_'.join(fun[1:])]
      if o not in prototypes: prototypes[o] = []
      prototypes[o] += [(rettype,fun,args)]

todo = (
  ('xof',(
    ('h',None,'16384'),
    ('m',None,'16384'),
  ),(
    ('loops','64','512'),
    ('maxtest','128','16384'),
  ),(
    ('',('h',),(),('hlen','m','mlen')),
  )),
  ('sort',(
    ('x',None,'4096'),
  ),(
    ('loops','1024','4096'),
    ('maxtest','128','4096'),
  ),(
    ('',(),('x',),('xwords',)),
  )),
  ('kem',(
    ('p','crypto_kem_PUBLICKEYBYTES','crypto_kem_PUBLICKEYBYTES'),
    ('s','crypto_kem_SECRETKEYBYTES','crypto_kem_SECRETKEYBYTES'),
    ('k','crypto_kem_BYTES','crypto_kem_BYTES'),
    ('c','crypto_kem_CIPHERTEXTBYTES','crypto_kem_CIPHERTEXTBYTES'),
    ('t','crypto_kem_BYTES','crypto_kem_BYTES'),
  ),(
    ('loops','8','64'),
  ),(
    ('_keypair',('p','s'),(),()),
    ('_enc',('c','k'),(),('p',)),
    ('_dec',('t',),(),('c','s')),
  )),
)

for t in todo:
  o,vars,howmuch,tests = t

  Z += '\n'
  Z += '/* ----- %s, derived from supercop/crypto_%s/try.c */\n' % (o,o)

  for rettype,fun,args in prototypes[o]:
    Z += 'static %s (*%s)(%s);\n' % (rettype,'_'.join(fun),args)

  for p in primitives[o]:
    Z += 'static const char *%s_%s_checksums[] = {\n' % (o,p)
    Z += '  "%s",\n' % checksums[o,p][0]
    Z += '  "%s",\n' % checksums[o,p][1]
    Z += '} ;\n'
    Z += '\n'

    if (o,p) in sizes:
      for line in sizes[o,p].splitlines():
        psize = line.split()[1]
        size1 = psize.replace('crypto_%s_%s_'%(o,p),'crypto_%s_'%o)
        size2 = psize.replace('crypto_','mceliece_')
        Z += '#define %s %s\n' % (size1,size2)
      Z += '\n'

    for v,initsize,allocsize in vars:
      Z += 'static void *storage_%s_%s_%s;\n' % (o,p,v)
      Z += 'static unsigned char *test_%s_%s_%s;\n' % (o,p,v)
    for v,initsize,allocsize in vars:
      Z += 'static void *storage_%s_%s_%s2;\n' % (o,p,v)
      Z += 'static unsigned char *test_%s_%s_%s2;\n' % (o,p,v)
    Z += '\n'

    if (o,p) in precomputed:
      Z += '#define precomputed_%s_%s_NUM %d\n' % (o,p,len(precomputed[o,p]))
      Z += '\n'
      for v,initsize,allocsize in vars:
        Z += 'static const unsigned char precomputed_%s_%s_%s[precomputed_%s_%s_NUM][%s] = {\n' % (o,p,v,o,p,allocsize)
        for precomp in precomputed[o,p]:
          Z += '  {%s},\n' % ','.join(str(c) for c in precomp[v])
        Z += '} ;\n'
        Z += '\n'

    Z += 'static void test_%s_%s_impl(long long impl)\n' % (o,p)
    Z += '{\n'
    for v,initsize,allocsize in vars:
      Z += '  unsigned char *%s = test_%s_%s_%s;\n' % (v,o,p,v)
    for v,initsize,allocsize in vars:
      Z += '  unsigned char *%s2 = test_%s_%s_%s2;\n' % (v,o,p,v)
    for v,initsize,allocsize in vars:
      if initsize is None:
        Z += '  long long %slen;\n' % v
        if o == 'sort':
          Z += '  long long %swords;\n' % v
      else:
        Z += '  long long %slen = %s;\n' % (v,initsize)
    Z += '\n'

    Z += '  if (targeti && strcmp(targeti,".") && strcmp(targeti,mceliece_dispatch_%s_%s_implementation(impl))) return;\n' % (o,p)
    Z += '  if (targetn && atol(targetn) != impl) return;\n' # XXX: atoll is slightly unportable

    Z += '  if (impl >= 0) {\n'
    for rettype,fun,args in prototypes[o]:
      f2 = ['mceliece','dispatch',o,p]+fun[2:]
      Z += '    %s = %s(impl);\n' % ('_'.join(fun),'_'.join(f2))
    Z += '    printf("%s_%s %%lld implementation %%s compiler %%s\\n",impl,mceliece_dispatch_%s_%s_implementation(impl),mceliece_dispatch_%s_%s_compiler(impl));\n' % (o,p,o,p,o,p)
    Z += '  } else {\n'
    for rettype,fun,args in prototypes[o]:
      f2 = ['mceliece',o,p]+fun[2:]
      Z += '    %s = %s;\n' % ('_'.join(fun),'_'.join(f2))
    Z += '    printf("%s_%s selected implementation %%s compiler %%s\\n",mceliece_%s_%s_implementation(),mceliece_%s_%s_compiler());\n' % (o,p,o,p,o,p)
    Z += '  }\n'

    Z += '  for (long long checksumbig = 0;checksumbig < 2;++checksumbig) {\n'

    maxtestdefined = False
    for v,small,big in howmuch:
      Z += '    long long %s = checksumbig ? %s : %s;\n' % (v,big,small)
      if v == 'maxtest': maxtestdefined = True
    Z += '\n'
    Z += '    checksum_clear();\n'
    Z += '\n'
    Z += '    for (long long loop = 0;loop < loops;++loop) {\n'

    wantresult = False
    for f,output,inout,input in tests:
      cof = 'crypto_'+o+f
      for rettype,fun,args in prototypes[o]:
        if cof == '_'.join(fun):
          if rettype != 'void':
            wantresult = True
    if wantresult:
      Z += '      int result;\n'

    if maxtestdefined and 'mlen' in input:
      Z += '      mlen = myrandom() % (maxtest + 1);\n'
    if maxtestdefined and 'hlen' in input:
      Z += '      hlen = myrandom() % (maxtest + 1);\n'
    if maxtestdefined and 'xwords' in input:
      Z += '      xwords = myrandom() % (maxtest + 1);\n'
      Z += '      xlen = mceliece_sort_%s_BYTES*xwords;\n' % p
    Z += '\n'

    initialized = set()
    for f,output,inout,input in tests:
      cof = 'crypto_'+o+f

      cofrettype = None
      for rettype,fun,args in prototypes[o]:
        if cof == '_'.join(fun):
          cofrettype = rettype

      expected = '0'
      unexpected = 'nonzero'

      for v in output:
        if len(v) == 1:
          Z += '      output_prepare(%s2,%s,%slen);\n' % (v,v,v)
          # v now has CDE where C is canary, D is canary, E is canary
          # v2 now has same CDE
          # D is at start of v with specified length
          # C is 16 bytes before beginning
          # E is 16 bytes past end
      for v in input+inout:
        if len(v) == 1:
          if v in initialized:
            Z += '      memcpy(%s2,%s,%slen);\n' % (v,v,v)
            Z += '      double_canary(%s2,%s,%slen);\n' % (v,v,v)
          else:
            Z += '      input_prepare(%s2,%s,%slen);\n' % (v,v,v)
            # v now has CTE where C is canary, T is test data, E is canary
            # v2 has same CTE
            initialized.add(v)

      if o == 'sort':
        Z += '      endianness(x,xwords,mceliece_sort_%s_BYTES);\n' % p

      for v in input+inout:
        if len(v) == 1:
          Z += '      secret(%s,%slen);\n' % (v,v)

      args = ','.join(output+inout+input)
      if cofrettype == 'void':
        Z += '      %s(%s);\n' % (cof,args)
      else:
        Z += '      result = %s(%s);\n' % (cof,args)
        Z += '      declassify(&result,sizeof result);\n'
        Z += '      if (result != %s) fail("failure: %s returns %s\\n");\n' % (expected,cof,unexpected)
    
      for v in input+inout+output:
        if len(v) == 1:
          Z += '      declassify(%s,%slen);\n' % (v,v)

      if o == 'sort':
        Z += '      endianness(x,xwords,mceliece_sort_%s_BYTES);\n' % p

      if cof == 'crypto_kem_dec':
        Z += '      if (memcmp(t,k,klen) != 0) fail("failure: %s does not match k\\n");\n' % cof

      for v in output+inout:
        if len(v) == 1:
          Z += '      checksum(%s,%slen);\n' % (v,v)
          # output v,v2 now has COE,CDE where O is output; checksum O
          initialized.add(v)
      for v in output+inout:
        if len(v) == 1:
          if cof == 'crypto_sign_open' and v == 't':
            Z += '      output_compare(%s2,%s,%slen,"%s");\n' % (v,v,'c',cof)
          else:
            Z += '      output_compare(%s2,%s,%slen,"%s");\n' % (v,v,v,cof)
            # output_compare checks COE,CDE for equal C, equal E
      for v in input:
        if len(v) == 1:
          Z += '      input_compare(%s2,%s,%slen,"%s");\n' % (v,v,v,cof)
          # input_compare checks CTE,CTE for equal C, equal T, equal E
    
      deterministic = True
      if inout+input == (): deterministic = False
      if cof == 'crypto_kem_enc': deterministic = False
    
      if deterministic:
        Z += '\n'
        for v in output+inout+input:
          if len(v) == 1:
            Z += '      double_canary(%s2,%s,%slen);\n' % (v,v,v)
            # old output v,v2: COE,CDE; new v,v2: FOG,FDG where F,G are new canaries
            # old inout v,v2: COE,CTE; new v,v2: FOG,FTG
            # old input v,v2: CTE,CTE; new v,v2: FTG,FTG
    
        if o == 'sort':
          Z += '      endianness(x2,xwords,mceliece_sort_%s_BYTES);\n' % p

        for v in input+inout:
          if len(v) == 1:
            Z += '      secret(%s2,%slen);\n' % (v,v)

        args = ','.join([v if v.endswith('words') or v.endswith('len') else v+'2' for v in output+inout+input])
        if cofrettype == 'void':
          Z += '      %s(%s);\n' % (cof,args)
        else:
          Z += '      result = %s(%s);\n' % (cof,args)
          Z += '      declassify(&result,sizeof result);\n'
          Z += '      if (result != %s) fail("failure: %s returns %s\\n");\n' % (expected,cof,unexpected)
    
        for v in input+inout+output:
          if len(v) == 1:
            Z += '      declassify(%s2,%slen);\n' % (v,v)

        if o == 'sort':
          Z += '      endianness(x2,xwords,mceliece_sort_%s_BYTES);\n' % p

        for w in output + inout:
          if len(w) == 1:
            # w,w2: COE,COE; goal now is to compare O
            Z += '      if (memcmp(%s2,%s,%slen) != 0) fail("failure: %s is nondeterministic\\n");\n' % (w,w,w,cof)
    
      overlap = deterministic
      if inout != (): overlap = False
      if (o,p) in nooverlap: overlap = False

      # XXX: overlap test assumes that inputs are at least as big as outputs
    
      if overlap:
        for y in output:
          if len(y) == 1:
            Z += '\n'
            for v in output:
              if len(v) == 1:
                Z += '      double_canary(%s2,%s,%slen);\n' % (v,v,v)
            for v in input:
              if len(v) == 1:
                Z += '      double_canary(%s2,%s,%slen);\n' % (v,v,v)
            for x in input:
              if len(x) == 1:
                # try writing to x2 instead of y, while reading x2
                args = ','.join([x+'2' if v==y else v for v in output] + [x+'2' if v==x else v for v in input])
    
                for v in input+inout:
                  v2 = x+'2' if v==x else v
                  if len(v) == 1:
                    Z += '      secret(%s,%slen);\n' % (v2,v)

                if cofrettype == 'void':
                  Z += '      %s(%s);\n' % (cof,args)
                else:
                  Z += '      result = %s(%s);\n' % (cof,args)
                  Z += '      declassify(&result,sizeof result);\n'
                  Z += '      if (result != %s) fail("failure: %s with %s=%s overlap returns %s\\n");\n' % (expected,cof,x,y,unexpected)
    
                for v in output:
                  v2 = x+'2' if v==y else v
                  if len(v) == 1:
                    Z += '      declassify(%s,%slen);\n' % (v2,v)
                for v in input:
                  if v == x: continue
                  if len(v) == 1:
                    Z += '      declassify(%s,%slen);\n' % (v,v)

                Z += '      if (memcmp(%s2,%s,%slen) != 0) fail("failure: %s does not handle %s=%s overlap\\n");\n' % (x,y,y,cof,x,y)
                Z += '      memcpy(%s2,%s,%slen);\n' % (x,x,x)
    
      if cof == 'crypto_kem_dec':
        Z += '\n'
        for tweaks in range(3):
          Z += '      c[myrandom() % clen] += 1 + (myrandom() % 255);\n'
          Z += '      if (%s(t,c,s) == 0)\n' % cof
          Z += '        checksum(t,tlen);\n'
          Z += '      else\n'
          Z += '        checksum(c,clen);\n'

    Z += '    }\n'
    Z += '    checksum_expected(%s_%s_checksums[checksumbig]);\n' % (o,p)
    Z += '  }\n'

    # ----- test vectors computed by python

    for f,output,inout,input in tests:
      cof = 'crypto_'+o+f
      if (o,p) in precomputed:
        Z += '  for (long long precomp = 0;precomp < precomputed_%s_%s_NUM;++precomp) {\n' % (o,p)
        for v,initsize,allocsize in vars:
          if v in output:
            Z += '    output_prepare(%s2,%s,%s);\n' % (v,v,allocsize)
          if v in input+inout:
            Z += '    input_prepare(%s2,%s,%s);\n' % (v,v,allocsize)
            Z += '    memcpy(%s,precomputed_%s_%s_%s[precomp],%s);\n' % (v,o,p,v,allocsize)
            Z += '    memcpy(%s2,precomputed_%s_%s_%s[precomp],%s);\n' % (v,o,p,v,allocsize)

        args = ','.join(output+inout+input)
        Z += '    %s(%s);\n' % (cof,args)

        for v,initsize,allocsize in vars:
          if v in output+inout:
            Z += '    if (memcmp(%s,precomputed_%s_%s_%s[precomp],%s)) {\n' % (v,o,p,v,allocsize)
            Z += '      fail("failure: %s fails precomputed test vectors\\n");\n' % cof
            Z += '      printf("expected %s: ");\n' % v
            Z += '      for (long long pos = 0;pos < %s;++pos) printf("%%02x",precomputed_%s_%s_%s[precomp][pos]);\n' % (allocsize,o,p,v)
            Z += '      printf("\\n");\n'
            Z += '      printf("received %s: ");\n' % v
            Z += '      for (long long pos = 0;pos < %s;++pos) printf("%%02x",%s[pos]);\n' % (allocsize,v)
            Z += '      printf("\\n");\n'
            Z += '    }\n'

        for v,initsize,allocsize in vars:
          if v in output+inout:
            Z += '    output_compare(%s2,%s,%s,"%s");\n' % (v,v,allocsize,cof)
          if v in input:
            Z += '    input_compare(%s2,%s,%s,"%s");\n' % (v,v,allocsize,cof)

        Z += '  }\n'

    Z += '}\n'
    Z += '\n'

    Z += 'static void test_%s_%s(void)\n' % (o,p)
    Z += '{\n'
    Z += '  if (targeto && strcmp(targeto,"%s")) return;\n' % o
    Z += '  if (targetp && strcmp(targetp,"%s")) return;\n' % p

    if cof == 'crypto_sort':
      for v,initsize,allocsize in vars:
        Z += '  storage_%s_%s_%s = callocplus(mceliece_sort_%s_BYTES*%s);\n' % (o,p,v,p,allocsize)
        Z += '  test_%s_%s_%s = (unsigned char *) aligned(storage_%s_%s_%s,mceliece_sort_%s_BYTES*%s);\n' % (o,p,v,o,p,v,p,allocsize)
      for v,initsize,allocsize in vars:
        Z += '  storage_%s_%s_%s2 = callocplus(mceliece_sort_%s_BYTES*%s);\n' % (o,p,v,p,allocsize)
        Z += '  test_%s_%s_%s2 = (unsigned char *) aligned(storage_%s_%s_%s2,mceliece_sort_%s_BYTES*%s);\n' % (o,p,v,o,p,v,p,allocsize)
    else:
      for v,initsize,allocsize in vars:
        Z += '  storage_%s_%s_%s = callocplus(%s);\n' % (o,p,v,allocsize)
        Z += '  test_%s_%s_%s = (unsigned char *) aligned(storage_%s_%s_%s,%s);\n' % (o,p,v,o,p,v,allocsize)
      for v,initsize,allocsize in vars:
        Z += '  storage_%s_%s_%s2 = callocplus(%s);\n' % (o,p,v,allocsize)
        Z += '  test_%s_%s_%s2 = (unsigned char *) aligned(storage_%s_%s_%s2,%s);\n' % (o,p,v,o,p,v,allocsize)
    Z += '\n'

    if o == 'sort': # requires alignment
      Z += '  for (long long offset = 0;offset < 1;++offset) {\n'
    else:
      Z += '  for (long long offset = 0;offset < 2;++offset) {\n'
    Z += '    if (targetoffset && atol(targetoffset) != offset) continue;\n'
    Z += '    if (offset && valgrind) break;\n'
    Z += '    printf("%s_%s offset %%lld\\n",offset);\n' % (o,p)
    Z += '    for (long long impl = -1;impl < mceliece_numimpl_%s_%s();++impl)\n' % (o,p)
    Z += '      forked(test_%s_%s_impl,impl);\n' % (o,p)
    for v,initsize,allocsize in vars:
      Z += '    ++test_%s_%s_%s;\n' % (o,p,v)
    for v,initsize,allocsize in vars:
      Z += '    ++test_%s_%s_%s2;\n' % (o,p,v)

    Z += '  }\n'

    for v,initsize,allocsize in reversed(vars):
      Z += '  free(storage_%s_%s_%s2);\n' % (o,p,v)
    for v,initsize,allocsize in reversed(vars):
      Z += '  free(storage_%s_%s_%s);\n' % (o,p,v)

    Z += '}\n'

    if (o,p) in sizes:
      for line in sizes[o,p].splitlines():
        psize = line.split()[1]
        size1 = psize.replace('crypto_%s_%s_'%(o,p),'crypto_%s_'%o)
        Z += '#undef %s\n' % size1
      Z += '\n'


Z += r'''/* ----- top level */

#include "print_cpuid.inc"

int main(int argc,char **argv)
{
  valgrind_init();
  if (valgrind) limits();

  setvbuf(stdout,0,_IOLBF,0);
  printf("mceliece version %s\n",mceliece_version);
  printf("mceliece arch %s\n",mceliece_arch);
  print_cpuid();

  if (valgrind) {
    printf("valgrind %d",(int) valgrind);
    printf(" declassify %d",(int) crypto_declassify_uses_valgrind);
    if (!crypto_declassify_uses_valgrind)
      printf(" (expect false positives)");
    printf("\n");
  }

  if (*argv) ++argv;
  if (*argv) {
    targeto = *argv++;
    if (*argv) {
      targetp = *argv++;
      if (*argv) {
        targeti = *argv++;
        if (*argv) {
          targetn = *argv++;
          if (*argv) {
            targetoffset = *argv++;
          }
        }
      }
    }
  }

'''

for t in todo:
  o,vars,howmuch,tests = t
  for p in primitives[o]:
    Z += '  test_%s_%s();\n' % (o,p)

Z += r'''
  if (!ok) {
    printf("some tests failed\n");
    return 100;
  }
  printf("all tests succeeded\n");
  return 0;
}
'''

with open('command/mceliece-test.c','w') as f:
  f.write(Z)
