diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1d4dd0a --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +Makefile +/config.status +/libmastik.a +/src/config.h +/demo/config.h +/tools/Doubloon/doubloon +/tools/Doubloon/src/__pycache__ +/tools/Doubloon/src/config.py +install_manifest.txt +tools/tools/ +/config.log +*.pdf +*.html +*.o +*.a +.en.utf-8.add +.en.utf-8.add.spl + diff --git a/CREDITS b/CREDITS new file mode 100644 index 0000000..a8ccc1b --- /dev/null +++ b/CREDITS @@ -0,0 +1,13 @@ +Ben Amos +Craig Disselkoen +Dallas McNeil +Daniel Genkin +Diego Aranha +Feichi Hu +Madura A. Shelton +Pierre Ayoub +Rui Qi Sim +Sioli O'Connell +William Kosasih +Yuval Yarom +Zhiyuan Zhang diff --git a/Makefile.in b/Makefile.in new file mode 100644 index 0000000..5ebf441 --- /dev/null +++ b/Makefile.in @@ -0,0 +1,28 @@ +SUBDIRS=mastik src bin tools demo tests + +all: + for f in ${SUBDIRS}; do ${MAKE} -C $$f || break ; done + +install: all + for f in ${SUBDIRS}; do ${MAKE} -C $$f install || break ; done + +clean: cleansubdirs localclean + +cleansubdirs: + for f in ${SUBDIRS}; do ${MAKE} -C $$f clean; done + +localclean: + +distclean: localclean + for f in ${SUBDIRS}; do ${MAKE} -C $$f distclean; done + rm Makefile + rm config.status config.log + +maintainerclean: versionclean + rm configure + +versionclean: distclean + rm -rf autom4te.cache + + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..32b1462 --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# Mastik: A Micro-Architectural Side-Channel Toolkit + +## About + +Micro-architectural side-channel attacks exploit contention on internal components +of the processor to leak information between processes. +While in theory such attacks are straightforward, +practical implementations tend to be finicky and +require significant understanding of poorly documented processor features +and other domain-specific arcane knowledge. +Consequently, there is a barrier to entry into work on +micro-architectural side-channel attacks, +which hinders the development of the area and the analysis of the +resilience of existing software against such attacks. + +This repository contains Mastik, a toolkit for experimenting with micro-architectural side-channel attacks. Mastik aims to provide implementations of published attack and analysis techniques. +Currently, Mastik supports six side-channel attack techniques on the Intel x86-64 architecture: + +- [Prime+Probe](https://www.cs.tau.ac.il/~tromer/papers/cache-joc-official.pdf) on several caches, including + - [L1 data cache](https://www.cs.tau.ac.il/~tromer/papers/cache-joc-official.pdf) + - [L1 instruction](https://www.iacr.org/archive/ches2010/62250105/62250105.pdf) + - L2 (only with huge pages) + - [Last Level Cache+Probe](http://palms.ee.princeton.edu/system/files/SP_vfinal.pdf) +- [Prime+Abort](https://www.usenix.org/system/files/conference/usenixsecurity17/sec17-disselkoen.pdf) +- [Flush+Reload](https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-yarom.pdf) +- [Flush+Flush](https://arxiv.org/pdf/1511.04594.pdf) +- Two variants of [CacheBleed](https://trustworthy.systems/publications/nicta_full_text/9535.pdf) +- [Performance-degradation attack](https://trustworthy.systems/publications/nicta_full_text/9427.pdf) + + + +## Installation + +Mastik follows the de-facto standard Linux installation process. +If the system has all of the required software and +you want the default configuration, use: +`$ ./configure && make && sudo make install` + +See below for more information. + +#### Required packages +For the core operation, Mastik does not require any packages. +However, the ability to resolve symbols in binaries is extremely useful, +and requires the build packages `binutils` and `libdwarf` on Linux. +On Mac OS X there is no support for debugging symbols yet. + +The Mastik GUI interface `doubloon` +requires Python 3 with the following packages: +`wx`, `numpy`, `paramiko`, `matplotlib`, and `tqdm`. + +Installation depends on the flavour of the Operating System. + +**Fedora**: +`$ sudo dnf install binutils-devel libdwarf-devel` + +**Ubuntu**: +`$ sudo apt-get install binutils-dev libdwarf-dev libelf-dev` + +**CentOS**: +Enable the PowerTools repository: +`$ sudo dnf config-manager --set-enabled PowerTools` +Then install the packages: +`$ sudo dnf install libdwarf binutils-devel elfutils-libelf-devel libdwarf-devel python3` + + +#### Configuring the build directory + +To set up the build environment, use the `configure` script. +To use the default options, use: + +`$ ./configure` + +The script accepts several flags to modify its behaviour. +Some of these are listed below. +Use `./configure --help` for a complete list. + +|Flag|Description| +|----|-----------| +| `--help` | Help message | +| `--prefix=PREFIX` | Install files in PREFIX [/usr/local] | +| `--disable-symbols` | Disables handling of symbol tables in binaries. Also, removes requirement for `binutils` and `libdwarf` | +| `--disable-debug-symbols` | Disable handling of debug symbols in binaries. Removes requirement for `libdwarf` | +| `--disable-doubloon` | Do not install `doubloon`. Removes requirement for Python3 | + + +#### Building Mastik + +After configuring the build environment, build Mastik using: + +`$ make` + +#### Installing Mastik +To install Mastik, use: + +`$ make install` + +To change the install directory use: + +`$ make prefix=DIR install` + +## Usage + +For example of usage look at the demo folder. + + + +## + + +## Thanks + +Mastik is supported by a generous gift from Intel. + diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..49d5957 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1 diff --git a/bin/.gitignore b/bin/.gitignore new file mode 100644 index 0000000..dae6668 --- /dev/null +++ b/bin/.gitignore @@ -0,0 +1,10 @@ +FR-* +L1-* +L3-* +FF-* +CB-* +ST-* +!*.c + +gpg-1.4.13 +out diff --git a/bin/FR-trace.c b/bin/FR-trace.c new file mode 100644 index 0000000..01acc1d --- /dev/null +++ b/bin/FR-trace.c @@ -0,0 +1,341 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SAMPLES 100000 +#define SLOT 10000 +#define IDLE 500 +#define THRESHOLD 100 + +#define MAX_MONITORED 100 +#define MAX_EVICTED 100 +#define MAX_PDA_TARGETS 10 + +#define MAX_PDAS 8 + +void usage(char *p) { + fprintf(stderr, "Usage: %s [-s ] [-c ] [-h ] [-i ]\n" + " [-p ] [-H] [-f ] [-S ] [-a cpu]\n" + " [-F ] [-r ]\n" + " [-m ] [-e ] [-t ] ...\n", p); + exit(1); +} + +struct map_entry { + char *file; + char *debugfile; + char *adrsspec; + uint64_t offset; + void *map_address; +}; + +struct config { + char *progname; + int samples; + int slot; + int threshold; + int idle; + int pdacount; + struct map_entry monitored[MAX_MONITORED]; + int nmonitored; + struct map_entry evicted[MAX_EVICTED]; + int nevicted; + struct map_entry pda_targets[MAX_PDA_TARGETS]; + int npdatargets; + int printheader; + char *outfilenameformat; + int runs; + int minlen; + int affinity; +}; + + +void fill_map_entry(struct map_entry *e) { + if (e->file == NULL) { + fprintf(stderr, "No filename\n"); + exit(1); + } + e->offset = sym_getsymboloffset(e->debugfile, e->adrsspec); + if (e->offset == ~0ULL) { + fprintf(stderr, "Cannot find %s in %s (%s)\n", e->adrsspec, e->file, e->debugfile); + exit(1); + } + + e->map_address = map_offset(e->file, e->offset); + if (e->map_address == NULL) { + perror(e->file); + exit(1); + } +} + + + +static void printmapentries(FILE * f, struct map_entry *entries, int count, char *name) { + for (int i = 0; i < count; i++) { + fprintf(f, "# %s%d=%s %s 0x%" PRIx64 "\n", name, i, entries[i].file, entries[i].adrsspec, entries[i].offset); + } +} + +static void printuname(FILE *f) { + struct utsname name; + uname(&name); + fprintf(f, "# sysname=%s\n", name.sysname); + fprintf(f, "# nodename=%s\n", name.nodename); + fprintf(f, "# release=%s\n", name.release); + fprintf(f, "# version=%s\n", name.version); + fprintf(f, "# machine=%s\n", name.machine); +} + + +void readargs(struct config *c, int ac, char **av) { + char *file = NULL; + char *debugfile = NULL; + int ch; + + c->samples = SAMPLES; + c->slot = SLOT; + c->threshold = THRESHOLD; + c->idle = IDLE; + c->pdacount = 0; + c->npdatargets = 0; + c->nmonitored = 0; + c->nevicted = 0; + c->progname = av[0]; + c->printheader = 0; + c->outfilenameformat = NULL; + c->runs = 0; + c->minlen = 0; + c->affinity = -1; + + while ((ch = getopt(ac, av, "Ha:f:S:s:c:h:i:p:t:m:e:r:F:l:")) != -1) { + switch (ch) { + case 'H': + c->printheader = 1; + break; + case 's': + c->slot = atoi(optarg); + break; + case 'c': + c->samples = atoi(optarg); + break; + case 'a': + c->affinity = atoi(optarg); + break; + case 'h': + c->threshold = atoi(optarg); + break; + case 'i': + c->idle = atoi(optarg); + break; + case 'p': + c->pdacount = atoi(optarg); + break; + case 'f': + file = optarg; + debugfile = optarg; + break; + case 'S': + debugfile = optarg; + break; + case 't': + if (c->npdatargets >= MAX_PDA_TARGETS) { + fprintf(stderr, "Too many pda targets (Max %d)\n", MAX_PDA_TARGETS); + exit(1); + } + c->pda_targets[c->npdatargets].file = file; + c->pda_targets[c->npdatargets].debugfile = debugfile; + c->pda_targets[c->npdatargets].adrsspec = optarg; + fill_map_entry(&c->pda_targets[c->npdatargets]); + c->npdatargets++; + break; + case 'm': + if (c->nmonitored >= MAX_MONITORED) { + fprintf(stderr, "Too many monitored locations(Max %d)\n", MAX_MONITORED); + exit(1); + } + c->monitored[c->nmonitored].file = file; + c->monitored[c->nmonitored].debugfile = debugfile; + c->monitored[c->nmonitored].adrsspec = optarg; + fill_map_entry(&c->monitored[c->nmonitored]); + c->nmonitored++; + break; + case 'e': + if (c->nevicted >= MAX_EVICTED) { + fprintf(stderr, "Too many evicted locations(Max %d)\n", MAX_EVICTED); + exit(1); + } + c->evicted[c->nevicted].file = file; + c->evicted[c->nevicted].debugfile = debugfile; + c->evicted[c->nevicted].adrsspec = optarg; + fill_map_entry(&c->evicted[c->nevicted]); + c->nevicted++; + break; + case 'F': + c->outfilenameformat = optarg; + break; + case 'r': + c->runs = atoi(optarg); + break; + case 'l': + c->minlen = atoi(optarg); + break; + default: usage(av[0]); + } + } + + if (c->nmonitored == 0) + usage(av[0]); + + int maxcpus = ncpus(); + if (maxcpus < 0) + maxcpus = MAX_PDAS; + + if (c->pdacount < 0) + c->pdacount += maxcpus; + + if (c->pdacount > maxcpus) { + fprintf(stderr, "Too many performance degradation attack threads. (Max %d)\n", maxcpus); + exit(1); + } + + if (c->runs == 0) { + c->runs = 1; + c->outfilenameformat = NULL; + } + + if (c->minlen <= 0) + c->minlen = c->idle * 3; + if (c->minlen > c->samples) + c->minlen = c->samples; +} + + +void printheader(FILE *f, struct config *c, int lines, int run, fr_t fr) { + if (!c->printheader) + return; + time_t now = time(NULL); + fprintf(f, "# %s starting at %.24s\n", c->progname, ctime(&now)); + fprintf(f, "################# CONFIG #################\n"); + fprintf(f, "# slot=%d\n", c->slot); + fprintf(f, "# samples=%d\n", c->samples); + fprintf(f, "# threshold=%d\n", c->threshold); + fprintf(f, "# idle=%d\n", c->idle); + fprintf(f, "# minlen=%d\n", c->minlen); + fprintf(f, "# runs=%d\n", c->runs); + fprintf(f, "# pdathreads=%d\n", c->pdacount); + fprintf(f, "# nmonitored=%d\n", c->nmonitored); + printmapentries(f, c->monitored, c->nmonitored, "monitor"); + fprintf(f, "# nevicted=%d\n", c->nevicted); + printmapentries(f, c->evicted, c->nevicted, "evict"); + fprintf(f, "# npdatargets=%d\n", c->npdatargets); + printmapentries(f, c->pda_targets, c->npdatargets, "target"); + fprintf(f, "# affinity="); + if (c->affinity == -1) + fprintf(f, "all\n"); + else + fprintf(f, "%d\n", c->affinity); + fprintf(f, "############## SYSTEM INFO ###############\n"); + fprintf(f, "# mastik_version=%s\n", mastik_version()); + printuname(f); + fprintf(f, "################## DATA ##################\n"); + fprintf(f, "# run=%d\n", run); + fprintf(f, "# datapoints=%d\n", lines); +} + +void printdata(char *fn, struct config *c, int lines, uint16_t *res, int run, fr_t fr) { + + FILE *f = stdout; + if (fn) + f = fopen(fn, "w"); + printheader(f, c, lines, run, fr); + for (int i = 0; i < lines; i++) { + for (int j = 0; j < c->nmonitored; j++) + fprintf(f, "%d ", res[i * c->nmonitored + j]); + putc('\n', f); + } + if (fn) + fclose(f); +} + +int main(int ac, char **av) { + struct config c; + pda_t *pdas = NULL; + fr_t fr = fr_prepare(); + + readargs(&c, ac, av); + + for (int i = 0; i < c.nmonitored; i++) + fr_monitor(fr, c.monitored[i].map_address); + + for (int i = 0; i < c.nevicted; i++) + fr_evict(fr, c.evicted[i].map_address); + + + + uint16_t *res = malloc(c.samples * c.nmonitored * sizeof(uint16_t)); + for (int i = 0; i < c.samples * c.nmonitored ; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + fr_probe(fr, res); + + if (c.pdacount > 0) { + pdas = calloc(c.pdacount, sizeof(pda_t)); + for (int i = 0; i < c.pdacount; i++) { + pdas[i] = pda_prepare(); + for (int j = 0; j < c.npdatargets; j++) + pda_target(pdas[i], c.pda_targets[j].map_address); + pda_activate(pdas[i]); + } + } + + + if (c.affinity != -1) + setaffinity(c.affinity); + for (int r = 0; r < c.runs; r++) { + int l = fr_trace(fr, c.samples, res, c.slot, c.threshold, c.idle); + + char *outfile=NULL; + if (c.outfilenameformat != NULL) + asprintf(&outfile, c.outfilenameformat, r); + printdata(outfile, &c, l, res, r, fr); + if (c.outfilenameformat != NULL) + free(outfile); + } + + if (c.pdacount > 0) { + for (int i = 0; i < c.pdacount; i++) + pda_release(pdas[i]); + } + + free(res); + fr_release(fr); +} + diff --git a/bin/Makefile.in b/bin/Makefile.in new file mode 100644 index 0000000..f4d3e00 --- /dev/null +++ b/bin/Makefile.in @@ -0,0 +1,27 @@ +FILES= \ + FR-trace.c + +TARGETS=$(FILES:.c=) +OBJS=${FILES:.c=.o} +CFLAGS=@CFLAGS@ -I.. +LDFLAGS=-L../src/ -g +LDLIBS=-lmastik @LIBS@ + +prefix=@prefix@ +exec_prefix=@exec_prefix@ + +all: ${TARGETS} + +install: ${TARGETS} + install -d @bindir@ + install ${TARGETS} @bindir@ + +${TARGETS}: %: %.o + ${CC} ${LDFLAGS} -o $@ $@.o ${LDLIBS} + + +clean: + rm -f ${TARGETS} ${OBJS} *.sig out + +distclean: clean + rm Makefile diff --git a/configure b/configure new file mode 100755 index 0000000..cbc4cc3 --- /dev/null +++ b/configure @@ -0,0 +1,6126 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.69 for mastik 0.1. +# +# Report bugs to . +# +# +# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +as_fn_exit 255 + fi + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org and +$0: yval@cs.adelaide.edu.au about your system, including +$0: any error possibly output before this message. Then +$0: install a modern shell, or manually run the script +$0: under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME='mastik' +PACKAGE_TARNAME='mastik' +PACKAGE_VERSION='0.1' +PACKAGE_STRING='mastik 0.1' +PACKAGE_BUGREPORT='yval@cs.adelaide.edu.au' +PACKAGE_URL='' + +ac_unique_file="src/symbol.c" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_header_list= +ac_subst_vars='LTLIBOBJS +TOOLS +DOUBLOON_EXPERIMENTAL +DOUBLOON_HAVE_DWARF +DOUBLOON_TEXTBOX_HEIGHT +SYMBOL_SRCS +LIBOBJS +PYTHON +UNAME +EGREP +GREP +CPP +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +enable_symbols +enable_debug_symbols +enable_doubloon +enable_experimental +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures mastik 0.1 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/mastik] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of mastik 0.1:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --disable-symbols do not use symbols in binaries + --disable-debug-symbols do not use debugging symbols in binaries + --disable-doubloon do not install doubloon + --enable-experimental enable experimental features + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to . +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +mastik configure 0.1 +generated by GNU Autoconf 2.69 + +Copyright (C) 2012 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if eval \${$3+:} false; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.i conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( $as_echo "## -------------------------------------- ## +## Report this to yval@cs.adelaide.edu.au ## +## -------------------------------------- ##" + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_mongrel + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_find_intX_t LINENO BITS VAR +# ----------------------------------- +# Finds a signed integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_intX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for int$2_t" >&5 +$as_echo_n "checking for int$2_t... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in int$2_t 'int' 'long int' \ + 'long long int' 'short int' 'signed char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))]; +test_array [0] = 0; +return test_array [0]; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default + enum { N = $2 / 2 - 1 }; +int +main () +{ +static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1) + < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))]; +test_array [0] = 0; +return test_array [0]; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + case $ac_type in #( + int$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if eval test \"x\$"$3"\" = x"no"; then : + +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_find_intX_t + +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_c_find_uintX_t LINENO BITS VAR +# ------------------------------------ +# Finds an unsigned integer type with width BITS, setting cache variable VAR +# accordingly. +ac_fn_c_find_uintX_t () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5 +$as_echo_n "checking for uint$2_t... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + # Order is important - never check a type that is potentially smaller + # than half of the expected target width. + for ac_type in uint$2_t 'unsigned int' 'unsigned long int' \ + 'unsigned long long int' 'unsigned short int' 'unsigned char'; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +static int test_array [1 - 2 * !((($ac_type) -1 >> ($2 / 2 - 1)) >> ($2 / 2 - 1) == 3)]; +test_array [0] = 0; +return test_array [0]; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + case $ac_type in #( + uint$2_t) : + eval "$3=yes" ;; #( + *) : + eval "$3=\$ac_type" ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if eval test \"x\$"$3"\" = x"no"; then : + +else + break +fi + done +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_find_uintX_t + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main () +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by mastik $as_me 0.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +as_fn_append ac_header_list " stdlib.h" +as_fn_append ac_header_list " unistd.h" +as_fn_append ac_header_list " sys/param.h" +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +ac_config_headers="$ac_config_headers src/config.h" + +ac_config_headers="$ac_config_headers demo/config.h" + + +# Checks for programs. +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if ${ac_cv_objext+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if ${ac_cv_c_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if ${ac_cv_prog_cc_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if ${ac_cv_prog_cc_c89+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +struct stat; +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C99" >&5 +$as_echo_n "checking for $CC option to accept ISO C99... " >&6; } +if ${ac_cv_prog_cc_c99+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c99=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +#include + +// Check varargs macros. These examples are taken from C99 6.10.3.5. +#define debug(...) fprintf (stderr, __VA_ARGS__) +#define showlist(...) puts (#__VA_ARGS__) +#define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__)) +static void +test_varargs_macros (void) +{ + int x = 1234; + int y = 5678; + debug ("Flag"); + debug ("X = %d\n", x); + showlist (The first, second, and third items.); + report (x>y, "x is %d but y is %d", x, y); +} + +// Check long long types. +#define BIG64 18446744073709551615ull +#define BIG32 4294967295ul +#define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0) +#if !BIG_OK + your preprocessor is broken; +#endif +#if BIG_OK +#else + your preprocessor is broken; +#endif +static long long int bignum = -9223372036854775807LL; +static unsigned long long int ubignum = BIG64; + +struct incomplete_array +{ + int datasize; + double data[]; +}; + +struct named_init { + int number; + const wchar_t *name; + double average; +}; + +typedef const char *ccp; + +static inline int +test_restrict (ccp restrict text) +{ + // See if C++-style comments work. + // Iterate through items via the restricted pointer. + // Also check for declarations in for loops. + for (unsigned int i = 0; *(text+i) != '\0'; ++i) + continue; + return 0; +} + +// Check varargs and va_copy. +static void +test_varargs (const char *format, ...) +{ + va_list args; + va_start (args, format); + va_list args_copy; + va_copy (args_copy, args); + + const char *str; + int number; + float fnumber; + + while (*format) + { + switch (*format++) + { + case 's': // string + str = va_arg (args_copy, const char *); + break; + case 'd': // int + number = va_arg (args_copy, int); + break; + case 'f': // float + fnumber = va_arg (args_copy, double); + break; + default: + break; + } + } + va_end (args_copy); + va_end (args); +} + +int +main () +{ + + // Check bool. + _Bool success = false; + + // Check restrict. + if (test_restrict ("String literal") == 0) + success = true; + char *restrict newvar = "Another string"; + + // Check varargs. + test_varargs ("s, d' f .", "string", 65, 34.234); + test_varargs_macros (); + + // Check flexible array members. + struct incomplete_array *ia = + malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10)); + ia->datasize = 10; + for (int i = 0; i < ia->datasize; ++i) + ia->data[i] = i * 1.234; + + // Check named initializers. + struct named_init ni = { + .number = 34, + .name = L"Test wide string", + .average = 543.34343, + }; + + ni.number = 58; + + int dynamic_array[ni.number]; + dynamic_array[ni.number - 1] = 543; + + // work around unused variable warnings + return (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == 'x' + || dynamic_array[ni.number - 1] != 543); + + ; + return 0; +} +_ACEOF +for ac_arg in '' -std=gnu99 -std=c99 -c99 -AC99 -D_STDC_C99= -qlanglvl=extc99 +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c99=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c99" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c99" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c99" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 +$as_echo "$ac_cv_prog_cc_c99" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c99" != xno; then : + +fi + + + +# Check whether --enable-symbols was given. +if test "${enable_symbols+set}" = set; then : + enableval=$enable_symbols; +fi + +# Check whether --enable-debug-symbols was given. +if test "${enable_debug_symbols+set}" = set; then : + enableval=$enable_debug_symbols; +fi + +# Check whether --enable-doubloon was given. +if test "${enable_doubloon+set}" = set; then : + enableval=$enable_doubloon; +fi + +# Check whether --enable-experimental was given. +if test "${enable_experimental+set}" = set; then : + enableval=$enable_experimental; +fi + + + + +# Checks for header files. + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if ${ac_cv_prog_CPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if ${ac_cv_path_GREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +for ac_header in fcntl.h stdint.h stdlib.h string.h strings.h unistd.h sched.h sys/prctl.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +# Extract the first word of "uname", so it can be a program name with args. +set dummy uname; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_UNAME+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $UNAME in + [\\/]* | ?:[\\/]*) + ac_cv_path_UNAME="$UNAME" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_UNAME="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +UNAME=$ac_cv_path_UNAME +if test -n "$UNAME"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $UNAME" >&5 +$as_echo "$UNAME" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +for ac_prog in python3 python +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$PYTHON"; then + ac_cv_prog_PYTHON="$PYTHON" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_PYTHON="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +PYTHON=$ac_cv_prog_PYTHON +if test -n "$PYTHON"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5 +$as_echo "$PYTHON" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$PYTHON" && break +done + +# Extract the first word of "${PYTHON}", so it can be a program name with args. +set dummy ${PYTHON}; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_PYTHON+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $PYTHON in + [\\/]* | ?:[\\/]*) + ac_cv_path_PYTHON="$PYTHON" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_PYTHON="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +PYTHON=$ac_cv_path_PYTHON +if test -n "$PYTHON"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5 +$as_echo "$PYTHON" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + +BUILD_OS="unknown" +if test x"$UNAME" != x; then + BUILD_OS=`$UNAME` +fi + +DOUBLOON_HAVE_DWARF="False" +if test "$enable_symbols" != "no"; then + # We first identify a Mac using the mach-o headers. Failing that, try Linux files. + for ac_header in mach-o/loader.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "mach-o/loader.h" "ac_cv_header_mach_o_loader_h" "$ac_includes_default" +if test "x$ac_cv_header_mach_o_loader_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_MACH_O_LOADER_H 1 +_ACEOF + +fi + +done + + if test x"$ac_cv_header_mach_o_loader_h" = x"yes"; then + SYMBOL_SRCS=symbol_mach.c + +$as_echo "#define HAVE_SYMBOLS 1" >>confdefs.h + + else + for ac_header in bfd.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "bfd.h" "ac_cv_header_bfd_h" "$ac_includes_default" +if test "x$ac_cv_header_bfd_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_BFD_H 1 +_ACEOF + +else + as_fn_error $? "bfd.h is required for symbols support." "$LINENO" 5 +fi + +done + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for bfd_init in -lbfd" >&5 +$as_echo_n "checking for bfd_init in -lbfd... " >&6; } +if ${ac_cv_lib_bfd_bfd_init+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lbfd $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char bfd_init (); +int +main () +{ +return bfd_init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_bfd_bfd_init=yes +else + ac_cv_lib_bfd_bfd_init=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bfd_bfd_init" >&5 +$as_echo "$ac_cv_lib_bfd_bfd_init" >&6; } +if test "x$ac_cv_lib_bfd_bfd_init" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBBFD 1 +_ACEOF + + LIBS="-lbfd $LIBS" + +else + as_fn_error $? "A working libbfd is required for symbols support" "$LINENO" 5 +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for elf_version in -lelf" >&5 +$as_echo_n "checking for elf_version in -lelf... " >&6; } +if ${ac_cv_lib_elf_elf_version+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lelf $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char elf_version (); +int +main () +{ +return elf_version (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_elf_elf_version=yes +else + ac_cv_lib_elf_elf_version=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_elf_elf_version" >&5 +$as_echo "$ac_cv_lib_elf_elf_version" >&6; } +if test "x$ac_cv_lib_elf_elf_version" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBELF 1 +_ACEOF + + LIBS="-lelf $LIBS" + +else + as_fn_error $? "A working libelf is required for symbols support" "$LINENO" 5 +fi + + + SYMBOL_SRCS=symbol_bfd.c + +$as_echo "#define HAVE_SYMBOLS 1" >>confdefs.h + + + MYINCLUDE="#include " + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$MYINCLUDE +int +main () +{ +bfd_section_vma((bfd*)0,(asection*)0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +$as_echo "#define HAVE_LEGACY_BFD 1" >>confdefs.h + +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + + + if test "$enable_debug_symbols" != "no"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dwarf_init in -ldwarf" >&5 +$as_echo_n "checking for dwarf_init in -ldwarf... " >&6; } +if ${ac_cv_lib_dwarf_dwarf_init+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldwarf $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dwarf_init (); +int +main () +{ +return dwarf_init (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dwarf_dwarf_init=yes +else + ac_cv_lib_dwarf_dwarf_init=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dwarf_dwarf_init" >&5 +$as_echo "$ac_cv_lib_dwarf_dwarf_init" >&6; } +if test "x$ac_cv_lib_dwarf_dwarf_init" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDWARF 1 +_ACEOF + + LIBS="-ldwarf $LIBS" + +else + as_fn_error $? "A working libdwarf is required for debug-symbols support" "$LINENO" 5 +fi + + for ac_header in libdwarf.h libdwarf/libdwarf.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + mastik_have_dwarf="yes" +fi + +done + + if test x"$mastik_have_dwarf" = x"yes" ; then + +$as_echo "#define HAVE_DEBUG_SYMBOLS 1" >>confdefs.h + + +$as_echo "#define HAVE_DWARF 1" >>confdefs.h + + DOUBLOON_HAVE_DWARF="True" + else + as_fn_error $? "libdwarf.h is required for debug-symbols support" "$LINENO" 5 + fi + fi + fi +fi + +case "$enable_experimental" in + yes) DOUBLOON_EXPERIMENTAL="True";; + *) DOUBLOON_EXPERIMENTAL="False";; +esac + +if test x"${BUILD_OS}" = x"Darwin"; then + DOUBLOON_TEXTBOX_HEIGHT=22 +else + DOUBLOON_TEXTBOX_HEIGHT=30 +fi + +PYVER=unknown +if test x"$PYTHON" != x; then + case "`${PYTHON} -V`" in + "Python 2."*) PYVER=2;; + "Python 3."*) PYVER=3;; + esac +fi + +TOOLS="" +if test x"$enable_doubloon" != x"no"; then + if test x"${PYVER}" = "x3"; then + TOOLS+=" Doubloon" + DOUBLOON=yes + missingmodules="" + for module in wx numpy paramiko matplotlib tqdm; do + ${PYTHON} -c "import ${module}" >/dev/null 2>&1 + if test x"$?" != x"0"; then + missingmodules+=" $module" + fi + done + if test x"$missingmodules" != x""; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Doubloon needs these missing modules: $missingmodules" >&5 +$as_echo "$as_me: WARNING: Doubloon needs these missing modules: $missingmodules" >&2;} + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Cannot find Python 3. Not installing Doubloon" >&5 +$as_echo "$as_me: WARNING: Cannot find Python 3. Not installing Doubloon" >&2;} + fi +fi + + + + + + +# Checks for typedefs, structures, and compiler characteristics. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5 +$as_echo_n "checking for inline... " >&6; } +if ${ac_cv_c_inline+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_c_inline=no +for ac_kw in inline __inline__ __inline; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __cplusplus +typedef int foo_t; +static $ac_kw foo_t static_foo () {return 0; } +$ac_kw foo_t foo () {return 0; } +#endif + +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_inline=$ac_kw +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + test "$ac_cv_c_inline" != no && break +done + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5 +$as_echo "$ac_cv_c_inline" >&6; } + +case $ac_cv_c_inline in + inline | yes) ;; + *) + case $ac_cv_c_inline in + no) ac_val=;; + *) ac_val=$ac_cv_c_inline;; + esac + cat >>confdefs.h <<_ACEOF +#ifndef __cplusplus +#define inline $ac_val +#endif +_ACEOF + ;; +esac + +ac_fn_c_find_intX_t "$LINENO" "16" "ac_cv_c_int16_t" +case $ac_cv_c_int16_t in #( + no|yes) ;; #( + *) + +cat >>confdefs.h <<_ACEOF +#define int16_t $ac_cv_c_int16_t +_ACEOF +;; +esac + +ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" +if test "x$ac_cv_type_pid_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define pid_t int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + +ac_fn_c_find_uintX_t "$LINENO" "16" "ac_cv_c_uint16_t" +case $ac_cv_c_uint16_t in #( + no|yes) ;; #( + *) + + +cat >>confdefs.h <<_ACEOF +#define uint16_t $ac_cv_c_uint16_t +_ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "32" "ac_cv_c_uint32_t" +case $ac_cv_c_uint32_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT32_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint32_t $ac_cv_c_uint32_t +_ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "64" "ac_cv_c_uint64_t" +case $ac_cv_c_uint64_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT64_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint64_t $ac_cv_c_uint64_t +_ACEOF +;; + esac + +ac_fn_c_find_uintX_t "$LINENO" "8" "ac_cv_c_uint8_t" +case $ac_cv_c_uint8_t in #( + no|yes) ;; #( + *) + +$as_echo "#define _UINT8_T 1" >>confdefs.h + + +cat >>confdefs.h <<_ACEOF +#define uint8_t $ac_cv_c_uint8_t +_ACEOF +;; + esac + + +# Checks for library functions. +for ac_header in vfork.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "vfork.h" "ac_cv_header_vfork_h" "$ac_includes_default" +if test "x$ac_cv_header_vfork_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_VFORK_H 1 +_ACEOF + +fi + +done + +for ac_func in fork vfork +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +if test "x$ac_cv_func_fork" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working fork" >&5 +$as_echo_n "checking for working fork... " >&6; } +if ${ac_cv_func_fork_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_fork_works=cross +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + /* By Ruediger Kuhlmann. */ + return fork () < 0; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_fork_works=yes +else + ac_cv_func_fork_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_fork_works" >&5 +$as_echo "$ac_cv_func_fork_works" >&6; } + +else + ac_cv_func_fork_works=$ac_cv_func_fork +fi +if test "x$ac_cv_func_fork_works" = xcross; then + case $host in + *-*-amigaos* | *-*-msdosdjgpp*) + # Override, as these systems have only a dummy fork() stub + ac_cv_func_fork_works=no + ;; + *) + ac_cv_func_fork_works=yes + ;; + esac + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 +$as_echo "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} +fi +ac_cv_func_vfork_works=$ac_cv_func_vfork +if test "x$ac_cv_func_vfork" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working vfork" >&5 +$as_echo_n "checking for working vfork... " >&6; } +if ${ac_cv_func_vfork_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_vfork_works=cross +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Thanks to Paul Eggert for this test. */ +$ac_includes_default +#include +#ifdef HAVE_VFORK_H +# include +#endif +/* On some sparc systems, changes by the child to local and incoming + argument registers are propagated back to the parent. The compiler + is told about this with #include , but some compilers + (e.g. gcc -O) don't grok . Test for this by using a + static variable whose address is put into a register that is + clobbered by the vfork. */ +static void +#ifdef __cplusplus +sparc_address_test (int arg) +# else +sparc_address_test (arg) int arg; +#endif +{ + static pid_t child; + if (!child) { + child = vfork (); + if (child < 0) { + perror ("vfork"); + _exit(2); + } + if (!child) { + arg = getpid(); + write(-1, "", 0); + _exit (arg); + } + } +} + +int +main () +{ + pid_t parent = getpid (); + pid_t child; + + sparc_address_test (0); + + child = vfork (); + + if (child == 0) { + /* Here is another test for sparc vfork register problems. This + test uses lots of local variables, at least as many local + variables as main has allocated so far including compiler + temporaries. 4 locals are enough for gcc 1.40.3 on a Solaris + 4.1.3 sparc, but we use 8 to be safe. A buggy compiler should + reuse the register of parent for one of the local variables, + since it will think that parent can't possibly be used any more + in this routine. Assigning to the local variable will thus + munge parent in the parent process. */ + pid_t + p = getpid(), p1 = getpid(), p2 = getpid(), p3 = getpid(), + p4 = getpid(), p5 = getpid(), p6 = getpid(), p7 = getpid(); + /* Convince the compiler that p..p7 are live; otherwise, it might + use the same hardware register for all 8 local variables. */ + if (p != p1 || p != p2 || p != p3 || p != p4 + || p != p5 || p != p6 || p != p7) + _exit(1); + + /* On some systems (e.g. IRIX 3.3), vfork doesn't separate parent + from child file descriptors. If the child closes a descriptor + before it execs or exits, this munges the parent's descriptor + as well. Test for this by closing stdout in the child. */ + _exit(close(fileno(stdout)) != 0); + } else { + int status; + struct stat st; + + while (wait(&status) != child) + ; + return ( + /* Was there some problem with vforking? */ + child < 0 + + /* Did the child fail? (This shouldn't happen.) */ + || status + + /* Did the vfork/compiler bug occur? */ + || parent != getpid() + + /* Did the file descriptor bug occur? */ + || fstat(fileno(stdout), &st) != 0 + ); + } +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_vfork_works=yes +else + ac_cv_func_vfork_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vfork_works" >&5 +$as_echo "$ac_cv_func_vfork_works" >&6; } + +fi; +if test "x$ac_cv_func_fork_works" = xcross; then + ac_cv_func_vfork_works=$ac_cv_func_vfork + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 +$as_echo "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} +fi + +if test "x$ac_cv_func_vfork_works" = xyes; then + +$as_echo "#define HAVE_WORKING_VFORK 1" >>confdefs.h + +else + +$as_echo "#define vfork fork" >>confdefs.h + +fi +if test "x$ac_cv_func_fork_works" = xyes; then + +$as_echo "#define HAVE_WORKING_FORK 1" >>confdefs.h + +fi + +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 +$as_echo_n "checking for GNU libc compatible malloc... " >&6; } +if ${ac_cv_func_malloc_0_nonnull+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_malloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include +#else +char *malloc (); +#endif + +int +main () +{ +return ! malloc (0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_malloc_0_nonnull=yes +else + ac_cv_func_malloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } +if test $ac_cv_func_malloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_MALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_MALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" malloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS malloc.$ac_objext" + ;; +esac + + +$as_echo "#define malloc rpl_malloc" >>confdefs.h + +fi + + + + + + for ac_header in $ac_header_list +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + + + + + +for ac_func in getpagesize +do : + ac_fn_c_check_func "$LINENO" "getpagesize" "ac_cv_func_getpagesize" +if test "x$ac_cv_func_getpagesize" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETPAGESIZE 1 +_ACEOF + +fi +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mmap" >&5 +$as_echo_n "checking for working mmap... " >&6; } +if ${ac_cv_func_mmap_fixed_mapped+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_mmap_fixed_mapped=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +/* malloc might have been renamed as rpl_malloc. */ +#undef malloc + +/* Thanks to Mike Haertel and Jim Avera for this test. + Here is a matrix of mmap possibilities: + mmap private not fixed + mmap private fixed at somewhere currently unmapped + mmap private fixed at somewhere already mapped + mmap shared not fixed + mmap shared fixed at somewhere currently unmapped + mmap shared fixed at somewhere already mapped + For private mappings, we should verify that changes cannot be read() + back from the file, nor mmap's back from the file at a different + address. (There have been systems where private was not correctly + implemented like the infamous i386 svr4.0, and systems where the + VM page cache was not coherent with the file system buffer cache + like early versions of FreeBSD and possibly contemporary NetBSD.) + For shared mappings, we should conversely verify that changes get + propagated back to all the places they're supposed to be. + + Grep wants private fixed already mapped. + The main things grep needs to know about mmap are: + * does it exist and is it safe to write into the mmap'd area + * how to use it (BSD variants) */ + +#include +#include + +#if !defined STDC_HEADERS && !defined HAVE_STDLIB_H +char *malloc (); +#endif + +/* This mess was copied from the GNU getpagesize.h. */ +#ifndef HAVE_GETPAGESIZE +# ifdef _SC_PAGESIZE +# define getpagesize() sysconf(_SC_PAGESIZE) +# else /* no _SC_PAGESIZE */ +# ifdef HAVE_SYS_PARAM_H +# include +# ifdef EXEC_PAGESIZE +# define getpagesize() EXEC_PAGESIZE +# else /* no EXEC_PAGESIZE */ +# ifdef NBPG +# define getpagesize() NBPG * CLSIZE +# ifndef CLSIZE +# define CLSIZE 1 +# endif /* no CLSIZE */ +# else /* no NBPG */ +# ifdef NBPC +# define getpagesize() NBPC +# else /* no NBPC */ +# ifdef PAGESIZE +# define getpagesize() PAGESIZE +# endif /* PAGESIZE */ +# endif /* no NBPC */ +# endif /* no NBPG */ +# endif /* no EXEC_PAGESIZE */ +# else /* no HAVE_SYS_PARAM_H */ +# define getpagesize() 8192 /* punt totally */ +# endif /* no HAVE_SYS_PARAM_H */ +# endif /* no _SC_PAGESIZE */ + +#endif /* no HAVE_GETPAGESIZE */ + +int +main () +{ + char *data, *data2, *data3; + const char *cdata2; + int i, pagesize; + int fd, fd2; + + pagesize = getpagesize (); + + /* First, make a file with some known garbage in it. */ + data = (char *) malloc (pagesize); + if (!data) + return 1; + for (i = 0; i < pagesize; ++i) + *(data + i) = rand (); + umask (0); + fd = creat ("conftest.mmap", 0600); + if (fd < 0) + return 2; + if (write (fd, data, pagesize) != pagesize) + return 3; + close (fd); + + /* Next, check that the tail of a page is zero-filled. File must have + non-zero length, otherwise we risk SIGBUS for entire page. */ + fd2 = open ("conftest.txt", O_RDWR | O_CREAT | O_TRUNC, 0600); + if (fd2 < 0) + return 4; + cdata2 = ""; + if (write (fd2, cdata2, 1) != 1) + return 5; + data2 = (char *) mmap (0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0L); + if (data2 == MAP_FAILED) + return 6; + for (i = 0; i < pagesize; ++i) + if (*(data2 + i)) + return 7; + close (fd2); + if (munmap (data2, pagesize)) + return 8; + + /* Next, try to mmap the file at a fixed address which already has + something else allocated at it. If we can, also make sure that + we see the same garbage. */ + fd = open ("conftest.mmap", O_RDWR); + if (fd < 0) + return 9; + if (data2 != mmap (data2, pagesize, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED, fd, 0L)) + return 10; + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data2 + i)) + return 11; + + /* Finally, make sure that changes to the mapped area do not + percolate back to the file as seen by read(). (This is a bug on + some variants of i386 svr4.0.) */ + for (i = 0; i < pagesize; ++i) + *(data2 + i) = *(data2 + i) + 1; + data3 = (char *) malloc (pagesize); + if (!data3) + return 12; + if (read (fd, data3, pagesize) != pagesize) + return 13; + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data3 + i)) + return 14; + close (fd); + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_mmap_fixed_mapped=yes +else + ac_cv_func_mmap_fixed_mapped=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_mmap_fixed_mapped" >&5 +$as_echo "$ac_cv_func_mmap_fixed_mapped" >&6; } +if test $ac_cv_func_mmap_fixed_mapped = yes; then + +$as_echo "#define HAVE_MMAP 1" >>confdefs.h + +fi +rm -f conftest.mmap conftest.txt + +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible realloc" >&5 +$as_echo_n "checking for GNU libc compatible realloc... " >&6; } +if ${ac_cv_func_realloc_0_nonnull+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_realloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include +#else +char *realloc (); +#endif + +int +main () +{ +return ! realloc (0, 0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_realloc_0_nonnull=yes +else + ac_cv_func_realloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_realloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_realloc_0_nonnull" >&6; } +if test $ac_cv_func_realloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_REALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_REALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" realloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS realloc.$ac_objext" + ;; +esac + + +$as_echo "#define realloc rpl_realloc" >>confdefs.h + +fi + + +for ac_func in bzero memset munmap strchr strdup strtoul strtoull uname +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +for ac_func in mmap64 sched_setaffinity +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + + +if test x"$ac_cv_prog_cc_c99" != x"no"; then + CFLAGS+=" $ac_cv_prog_cc_c99" +fi + + +SYMBOL_SRCS="$SYMBOL_SRCS" + + + + + + + +ac_config_files="$ac_config_files Makefile" + +ac_config_files="$ac_config_files mastik/Makefile" + +ac_config_files="$ac_config_files src/Makefile" + +ac_config_files="$ac_config_files bin/Makefile" + +ac_config_files="$ac_config_files demo/Makefile" + +ac_config_files="$ac_config_files tests/Makefile" + +ac_config_files="$ac_config_files tools/Makefile" + +if test x"$DOUBLOON" = x"yes"; then + ac_config_files="$ac_config_files tools/Doubloon/Makefile" + +fi +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by mastik $as_me 0.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to ." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +mastik config.status 0.1 +configured by $0, generated by GNU Autoconf 2.69, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2012 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;; + "demo/config.h") CONFIG_HEADERS="$CONFIG_HEADERS demo/config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "mastik/Makefile") CONFIG_FILES="$CONFIG_FILES mastik/Makefile" ;; + "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; + "bin/Makefile") CONFIG_FILES="$CONFIG_FILES bin/Makefile" ;; + "demo/Makefile") CONFIG_FILES="$CONFIG_FILES demo/Makefile" ;; + "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;; + "tools/Makefile") CONFIG_FILES="$CONFIG_FILES tools/Makefile" ;; + "tools/Doubloon/Makefile") CONFIG_FILES="$CONFIG_FILES tools/Doubloon/Makefile" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi + ;; + + + esac + +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + diff --git a/configure.ac b/configure.ac new file mode 100644 index 0000000..a6939f9 --- /dev/null +++ b/configure.ac @@ -0,0 +1,155 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. + +AC_PREREQ([2.69]) +AC_INIT([mastik], [0.1], [yval@cs.adelaide.edu.au]) +AC_CONFIG_SRCDIR([src/symbol.c]) +AC_CONFIG_HEADERS([src/config.h]) +AC_CONFIG_HEADERS([demo/config.h]) + +# Checks for programs. +AC_PROG_CC + +AC_PROG_CC_C99 + +AC_ARG_ENABLE(symbols, [AS_HELP_STRING([--disable-symbols], [do not use symbols in binaries])]) +AC_ARG_ENABLE(debug-symbols, [AS_HELP_STRING([--disable-debug-symbols], [do not use debugging symbols in binaries])]) +AC_ARG_ENABLE(doubloon, [AS_HELP_STRING([--disable-doubloon], [do not install doubloon])]) +AC_ARG_ENABLE(experimental, [AS_HELP_STRING([--enable-experimental], [enable experimental features])]) + + + +# Checks for header files. +AC_CHECK_HEADERS([fcntl.h stdint.h stdlib.h string.h strings.h unistd.h sched.h sys/prctl.h]) + +AC_PATH_PROG(UNAME, uname) +AC_CHECK_PROGS(PYTHON, [python3 python]) +AC_PATH_PROG(PYTHON, [${PYTHON}]) + +BUILD_OS="unknown" +if test x"$UNAME" != x; then + BUILD_OS=`$UNAME` +fi + +DOUBLOON_HAVE_DWARF="False" +if test "$enable_symbols" != "no"; then + # We first identify a Mac using the mach-o headers. Failing that, try Linux files. + AC_CHECK_HEADERS([mach-o/loader.h]) + if test x"$ac_cv_header_mach_o_loader_h" = x"yes"; then + SYMBOL_SRCS=symbol_mach.c + AC_DEFINE([HAVE_SYMBOLS], [1], [Have support for parsing loader symbol table]) + else + AC_CHECK_HEADERS([bfd.h], [], [AC_ERROR([bfd.h is required for symbols support.])]) + AC_CHECK_LIB([bfd], [bfd_init], [], [AC_ERROR([A working libbfd is required for symbols support])]) + AC_CHECK_LIB([elf], [elf_version], [], [AC_ERROR([A working libelf is required for symbols support])]) + + SYMBOL_SRCS=symbol_bfd.c + AC_DEFINE([HAVE_SYMBOLS], [1], [Have support for parsing loader symbol table]) + + MYINCLUDE="#include " + AC_COMPILE_IFELSE( + [AC_LANG_PROGRAM([[$MYINCLUDE]], + [[bfd_section_vma((bfd*)0,(asection*)0);]])], + AC_DEFINE([HAVE_LEGACY_BFD], [1], [Have legacy bfd.h])) + + + if test "$enable_debug_symbols" != "no"; then + AC_CHECK_LIB([dwarf], [dwarf_init], [], [AC_ERROR([A working libdwarf is required for debug-symbols support])]) + AC_CHECK_HEADERS([libdwarf.h libdwarf/libdwarf.h], [mastik_have_dwarf="yes"]) + if test x"$mastik_have_dwarf" = x"yes" ; then + AC_DEFINE([HAVE_DEBUG_SYMBOLS], [1], [Have support for debug symbols]) + AC_DEFINE([HAVE_DWARF], [1], [Have support for dwarf]) + DOUBLOON_HAVE_DWARF="True" + else + AC_ERROR([libdwarf.h is required for debug-symbols support]) + fi + fi + fi +fi + +case "$enable_experimental" in + yes) DOUBLOON_EXPERIMENTAL="True";; + *) DOUBLOON_EXPERIMENTAL="False";; +esac + +if test x"${BUILD_OS}" = x"Darwin"; then + DOUBLOON_TEXTBOX_HEIGHT=22 +else + DOUBLOON_TEXTBOX_HEIGHT=30 +fi + +PYVER=unknown +if test x"$PYTHON" != x; then + case "`${PYTHON} -V`" in + "Python 2."*) PYVER=2;; + "Python 3."*) PYVER=3;; + esac +fi + +TOOLS="" +if test x"$enable_doubloon" != x"no"; then + if test x"${PYVER}" = "x3"; then + TOOLS+=" Doubloon" + DOUBLOON=yes + missingmodules="" + for module in wx numpy paramiko matplotlib tqdm; do + ${PYTHON} -c "import ${module}" >/dev/null 2>&1 + if test x"$?" != x"0"; then + missingmodules+=" $module" + fi + done + if test x"$missingmodules" != x""; then + AC_WARN([Doubloon needs these missing modules: $missingmodules]) + fi + else + AC_WARN([Cannot find Python 3. Not installing Doubloon]) + fi +fi + + + + + + +# Checks for typedefs, structures, and compiler characteristics. +AC_C_INLINE +AC_TYPE_INT16_T +AC_TYPE_PID_T +AC_TYPE_SIZE_T +AC_TYPE_UINT16_T +AC_TYPE_UINT32_T +AC_TYPE_UINT64_T +AC_TYPE_UINT8_T + +# Checks for library functions. +AC_FUNC_FORK +AC_FUNC_MALLOC +AC_FUNC_MMAP +AC_FUNC_REALLOC +AC_CHECK_FUNCS([bzero memset munmap strchr strdup strtoul strtoull uname]) +AC_CHECK_FUNCS([mmap64 sched_setaffinity]) + + +if test x"$ac_cv_prog_cc_c99" != x"no"; then + CFLAGS+=" $ac_cv_prog_cc_c99" +fi + + +AC_SUBST(SYMBOL_SRCS, ["$SYMBOL_SRCS"]) +AC_SUBST(DOUBLOON_TEXTBOX_HEIGHT) +AC_SUBST(DOUBLOON_HAVE_DWARF) +AC_SUBST(DOUBLOON_EXPERIMENTAL) +AC_SUBST(TOOLS) +AC_SUBST(PYTHON) + +AC_CONFIG_FILES([Makefile]) +AC_CONFIG_FILES([mastik/Makefile]) +AC_CONFIG_FILES([src/Makefile]) +AC_CONFIG_FILES([bin/Makefile]) +AC_CONFIG_FILES([demo/Makefile]) +AC_CONFIG_FILES([tests/Makefile]) +AC_CONFIG_FILES([tools/Makefile]) +if test x"$DOUBLOON" = x"yes"; then + AC_CONFIG_FILES([tools/Doubloon/Makefile]) +fi +AC_OUTPUT diff --git a/demo/.gitignore b/demo/.gitignore new file mode 100644 index 0000000..583b790 --- /dev/null +++ b/demo/.gitignore @@ -0,0 +1,11 @@ +FR-* +L1-* +L3-* +L2-* +FF-* +CB-* +ST-* +!*.c + +gpg-1.4.13 +out diff --git a/demo/CB-hist.c b/demo/CB-hist.c new file mode 100644 index 0000000..cfafe9f --- /dev/null +++ b/demo/CB-hist.c @@ -0,0 +1,97 @@ +/* + * Copyright 2017 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ +#include +#include +#include +#include +#include +#include +#include + +#define COUNT 1000000 +#define RANGE 512 +#define OFFSETS 16 + +int *hist; +uint32_t *buf; + +void measure(cb_t cb, int offset, int hoffset, int count, int range) { + cb_monitor(cb, offset, 0); + cb_repeatedprobe(cb, 10, buf); + cb_repeatedprobe(cb, count, buf); + for (int i = 0; i < count; i++) { + int ind = buf[i]; + if (ind >= range) + ind = 0; + hist[hoffset * range + ind]++; + } +} + +void usage(char *p) { + fprintf(stderr, "Usage: %s [-B|F] [-c count] [-n rounds] [-r range] [-b base offset] [-o offsets] [-s skip]\n", p); + exit(1); +} + +int main(int ac, char **av) { + int mode = CBT_BANK_CONFLICT; + int opt; + int count = 1000000; + int rounds = 1; + int range = 1024; + int base = 0; + int offsets = 8; + int skip = 4; + + while ((opt = getopt(ac, av, "BFc:n:r:b:o:s:")) != -1) { + switch (opt) { + case 'B': mode = CBT_BANK_CONFLICT; break; + case 'F': mode = CBT_FALSE_DEPENDENCY; break; + case 'c': count = atoi(optarg); break; + case 'n': rounds = atoi(optarg); break; + case 'r': range = atoi(optarg); break; + case 'b': base = atoi(optarg); break; + case 'o': offsets = atoi(optarg); break; + case 's': skip = atoi(optarg); break; + case'?': + default: usage(av[0]); + } + } + + buf = malloc(sizeof(uint32_t) * count); + memset(buf, '\0', sizeof(uint32_t) * count); + hist = malloc(sizeof(int)*range*offsets); + memset(hist, '\0', sizeof(int)*range*offsets); + + + cb_t cb = cb_prepare(mode); + for (int r = 0; r < rounds; r++) + for (int i = 0; i < offsets; i++) + measure(cb, base + i * skip, i, count, range); + + for (int i = 0; i < range; i++) { + printf("%4d", i); + for (int j = 0; j < offsets; j++) + printf(" %8d" , hist[j * range + i]); + putchar('\n'); + } +} + + + + diff --git a/demo/FF-gnupg-1.4.13.c b/demo/FF-gnupg-1.4.13.c new file mode 100644 index 0000000..6745fb8 --- /dev/null +++ b/demo/FF-gnupg-1.4.13.c @@ -0,0 +1,76 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include + +#define SAMPLES 100000 +#define SLOT 2000 +#define THRESHOLD 100 + +#define BINARY "gpg-1.4.13" + +char *monitor[] = { + "mpih-mul.c:85", + "mpih-mul.c:271", + "mpih-div.c:356" +}; +int nmonitor = sizeof(monitor)/sizeof(monitor[0]); + +int main(int ac, char **av) { +#ifdef HAVE_DEBUG_SYMBOLS + delayloop(2000000000); + ff_t ff = ff_prepare(); + for (int i = 0; i < nmonitor; i++) { + uint64_t offset = sym_getsymboloffset(BINARY, monitor[i]); + if (offset == ~0ULL) { + fprintf(stderr, "Cannot find %s in %s\n", monitor[i], BINARY); + exit(1); + } + ff_monitor(ff, map_offset(BINARY, offset)); + } + + uint16_t *res = malloc(SAMPLES * nmonitor * sizeof(uint16_t)); + for (int i = 0; i < SAMPLES * nmonitor ; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + ff_probe(ff, res); + + int l; + do { + l = ff_trace(ff, SAMPLES, res, SLOT, THRESHOLD, 500); + } while (l < 10000); + for (int i = 0; i < l; i++) { + for (int j = 0; j < nmonitor; j++) + printf("%d ", res[i * nmonitor + j]); + putchar('\n'); + } + + free(res); + ff_release(ff); +#else // HAVE_DEBUG_SYMBOLS + fprintf(stderr, "%s: No dupport for debug symbols\n", av[0]); + exit(1); +#endif +} diff --git a/demo/FF-trace.c b/demo/FF-trace.c new file mode 100644 index 0000000..85b8dbd --- /dev/null +++ b/demo/FF-trace.c @@ -0,0 +1,312 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SAMPLES 100000 +#define SLOT 10000 +#define IDLE 500 +#define THRESHOLD 100 + +#define MAX_MONITORED 100 +#define MAX_EVICTED 100 +#define MAX_PDA_TARGETS 10 + +#define MAX_PDAS 8 + +void usage(char *p) { + fprintf(stderr, "Usage: %s [-s ] [-c ] [-h ] [-i ]\n" + " [-p ] [-H] [-f ] [-a cpu] \n" + " [-F ] [-r ]\n" + " [-m ] [-t ] ...\n", p); + exit(1); +} + +struct map_entry { + char *file; + char *adrsspec; + uint64_t offset; + void *map_address; +}; + +struct config { + char *progname; + int samples; + int slot; + int threshold; + int idle; + int pdacount; + struct map_entry monitored[MAX_MONITORED]; + int nmonitored; + struct map_entry pda_targets[MAX_PDA_TARGETS]; + int npdatargets; + int printheader; + char *outfilenameformat; + int runs; + int minlen; + int affinity; +}; + + +void fill_map_entry(struct map_entry *e) { + if (e->file == NULL) { + fprintf(stderr, "No filename\n"); + exit(1); + } + e->offset = sym_getsymboloffset(e->file, e->adrsspec); + if (e->offset == ~0ULL) { + fprintf(stderr, "Cannot find %s in %s\n", e->adrsspec, e->file); + exit(1); + } + + e->map_address = map_offset(e->file, e->offset); + if (e->map_address == NULL) { + perror(e->file); + exit(1); + } +} + + + +static void printmapentries(FILE *f, struct map_entry *entries, int count, char *name) { + for (int i = 0; i < count; i++) { + fprintf(f, "# %s%d=%s %s 0x%lx\n", name, i, entries[i].file, entries[i].adrsspec, entries[i].offset); + } +} + +static void printuname(FILE *f) { + struct utsname name; + uname(&name); + fprintf(f, "# sysname=%s\n", name.sysname); + fprintf(f, "# nodename=%s\n", name.nodename); + fprintf(f, "# release=%s\n", name.release); + fprintf(f, "# version=%s\n", name.version); + fprintf(f, "# machine=%s\n", name.machine); +} + + +void readargs(struct config *c, int ac, char **av) { + char *file = NULL; + int ch; + + c->samples = SAMPLES; + c->slot = SLOT; + c->threshold = THRESHOLD; + c->idle = IDLE; + c->pdacount = 0; + c->npdatargets = 0; + c->nmonitored = 0; + c->progname = av[0]; + c->printheader = 0; + c->outfilenameformat = "out.%04d.dat"; + c->runs = 0; + c->minlen = 0; + c->affinity = -1; + + while ((ch = getopt(ac, av, "Ha:f:s:c:h:i:p:t:m:e:r:F:l:")) != -1) { + switch (ch) { + case 'H': + c->printheader = 1; + break; + case 's': + c->slot = atoi(optarg); + break; + case 'c': + c->samples = atoi(optarg); + break; + case 'a': + c->affinity = atoi(optarg); + break; + case 'h': + c->threshold = atoi(optarg); + break; + case 'i': + c->idle = atoi(optarg); + break; + case 'p': + c->pdacount = atoi(optarg); + break; + case 'f': + file = optarg; + break; + case 't': + if (c->npdatargets >= MAX_PDA_TARGETS) { + fprintf(stderr, "Too many pda targets (Max %d)\n", MAX_PDA_TARGETS); + exit(1); + } + c->pda_targets[c->npdatargets].file = file; + c->pda_targets[c->npdatargets].adrsspec = optarg; + fill_map_entry(&c->pda_targets[c->npdatargets]); + c->npdatargets++; + break; + case 'm': + if (c->nmonitored >= MAX_MONITORED) { + fprintf(stderr, "Too many monitored locations(Max %d)\n", MAX_MONITORED); + exit(1); + } + c->monitored[c->nmonitored].file = file; + c->monitored[c->nmonitored].adrsspec = optarg; + fill_map_entry(&c->monitored[c->nmonitored]); + c->nmonitored++; + break; + case 'F': + c->outfilenameformat = optarg; + break; + case 'r': + c->runs = atoi(optarg); + break; + case 'l': + c->minlen = atoi(optarg); + break; + default: usage(av[0]); + } + } + + if (c->nmonitored == 0) + usage(av[0]); + + if (c->pdacount > MAX_PDAS) { + fprintf(stderr, "Too many performance degradation attack threads. (Max %d)\n", MAX_PDAS); + exit(1); + } + + if (c->runs == 0) { + c->runs = 1; + c->outfilenameformat = NULL; + } + + if (c->minlen <= 0) + c->minlen = c->idle * 3; + if (c->minlen > c->samples) + c->minlen = c->samples; +} + +void printheader(FILE *f, struct config *c, int lines, int run, ff_t ff) { + if (!c->printheader) + return; + time_t now = time(NULL); + fprintf(f, "# %s starting at %.24s\n", c->progname, ctime(&now)); + fprintf(f, "################# CONFIG #################\n"); + fprintf(f, "# slot=%d\n", c->slot); + fprintf(f, "# samples=%d\n", c->samples); + fprintf(f, "# threshold=%d\n", c->threshold); + fprintf(f, "# idle=%d\n", c->idle); + fprintf(f, "# minlen=%d\n", c->minlen); + fprintf(f, "# runs=%d\n", c->runs); + fprintf(f, "# pdathreads=%d\n", c->pdacount); + fprintf(f, "# nmonitored=%d\n", c->nmonitored); + printmapentries(f, c->monitored, c->nmonitored, "monitor"); + fprintf(f, "# npdatargets=%d\n", c->npdatargets); + printmapentries(f, c->pda_targets, c->npdatargets, "target"); + fprintf(f, "# affinity="); + if (c->affinity == -1) + fprintf(f, "all\n"); + else + fprintf(f, "%d\n", c->affinity); + fprintf(f, "############## SYSTEM INFO ###############\n"); + fprintf(f, "# mastik_version=%s\n", mastik_version()); + printuname(f); + fprintf(f, "################## DATA ##################\n"); + fprintf(f, "# run=%d\n", run); + fprintf(f, "# thresholds="); + for (int i = 0; i < c->nmonitored; i++) + fprintf(f, "%d ", ff_getthreshold(ff, i)); + fprintf(f, "\n"); + fprintf(f, "# datapoints=%d\n", lines); +} + +void printdata(char *fn, struct config *c, int lines, uint16_t *res, int run, ff_t ff) { + + FILE *f = stdout; + if (fn) + f = fopen(fn, "w"); + printheader(f, c, lines, run, ff); + for (int i = 0; i < lines; i++) { + for (int j = 0; j < c->nmonitored; j++) + fprintf(f, "%d ", res[i * c->nmonitored + j]); + putc('\n', f); + } + if (fn) + fclose(f); +} + +int main(int ac, char **av) { + struct config c; + pda_t *pdas = NULL; + ff_t ff = ff_prepare(); + + readargs(&c, ac, av); + + for (int i = 0; i < c.nmonitored; i++) + ff_monitor(ff, c.monitored[i].map_address); + + + + uint16_t *res = malloc(c.samples * c.nmonitored * sizeof(uint16_t)); + for (int i = 0; i < c.samples * c.nmonitored ; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + ff_probe(ff, res); + + if (c.pdacount > 0) { + pdas = calloc(c.pdacount, sizeof(pda_t)); + for (int i = 0; i < c.pdacount; i++) { + pdas[i] = pda_prepare(); + for (int j = 0; j < c.npdatargets; j++) + pda_target(pdas[i], c.pda_targets[j].map_address); + pda_activate(pdas[i]); + } + } + + if (c.affinity != -1) + setaffinity(c.affinity); + delayloop(1000000000); + for (int r = 0; r < c.runs; r++) { + int l; + do { + ff_setthresholds(ff); + l = ff_trace(ff, c.samples, res, c.slot, c.threshold, c.idle); + } while (l < c.minlen); + + char *outfile=NULL; + if (c.outfilenameformat != NULL) + asprintf(&outfile, c.outfilenameformat, r); + printdata(outfile, &c, l, res, r, ff); + if (c.outfilenameformat != NULL) + free(outfile); + } + + if (c.pdacount > 0) { + for (int i = 0; i < c.pdacount; i++) + pda_release(pdas[i]); + } + + free(res); + ff_release(ff); +} diff --git a/demo/FR-1-file-access.c b/demo/FR-1-file-access.c new file mode 100644 index 0000000..078911f --- /dev/null +++ b/demo/FR-1-file-access.c @@ -0,0 +1,42 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include + +int main(int ac, char **av) { + fr_t fr = fr_prepare(); + + void *ptr = map_offset("FR-1-file-access.c", 0); + fr_monitor(fr, ptr); + + uint16_t res[1]; + fr_probe(fr, res); + + for (;;) { + fr_probe(fr, res); + if (res[0] < 100) + printf("FR-1-file-access.c accessed\n"); + delayloop(10000); + } +} + diff --git a/demo/FR-2-file-access.c b/demo/FR-2-file-access.c new file mode 100644 index 0000000..8910fea --- /dev/null +++ b/demo/FR-2-file-access.c @@ -0,0 +1,46 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include + +int main(int ac, char **av) { + fr_t fr = fr_prepare(); + + void *ptr = map_offset("FR-1-file-access.c", 0); + fr_monitor(fr, ptr); + ptr = map_offset("FR-2-file-access.c", 0); + fr_monitor(fr, ptr); + + uint16_t res[2]; + fr_probe(fr, res); + + for (;;) { + fr_probe(fr, res); + if (res[0] < 100) + printf("FR-1-file-access.c accessed\n"); + if (res[1] < 100) + printf("FR-2-file-access.c accessed\n"); + delayloop(10000); + } +} + diff --git a/demo/FR-flush.c b/demo/FR-flush.c new file mode 100644 index 0000000..a1e5085 --- /dev/null +++ b/demo/FR-flush.c @@ -0,0 +1,47 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#define BINARY "gpg-1.4.13" + +int main(int ac, char **av) { + pda_t pda = pda_prepare(); + + void *ptr = map_offset(BINARY, sym_getsymboloffset(BINARY, "mpihelp_sub_n")); + void *ptr2 = map_offset(BINARY, sym_getsymboloffset(BINARY, "mpihelp_sub_n+64")); + if (ptr == NULL || ptr2==NULL) { + printf("Bad symbol translation\n"); + exit(1); + } + pda_target(pda, ptr); + pda_target(pda, ptr2); + + pda_activate(pda); + wait(NULL); +} + diff --git a/demo/FR-function-call-nodelay.c b/demo/FR-function-call-nodelay.c new file mode 100644 index 0000000..3aba755 --- /dev/null +++ b/demo/FR-function-call-nodelay.c @@ -0,0 +1,44 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include + +int main(int ac, char **av) { + void *ptr = map_offset("/usr/lib64/libc-2.17.so", 0x6d300); + if (ptr == NULL) + exit(0); + + fr_t fr = fr_prepare(); + fr_monitor(fr, ptr); + + uint16_t res[1]; + fr_probe(fr, res); + + int lines=0; + for (;;) { + fr_probe(fr, res); + if (res[0] < 100) + printf("%4d: %s", ++lines, "Call to puts\n"); + } +} + diff --git a/demo/FR-function-call.c b/demo/FR-function-call.c new file mode 100644 index 0000000..14f9256 --- /dev/null +++ b/demo/FR-function-call.c @@ -0,0 +1,45 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include + +int main(int ac, char **av) { + void *ptr = map_offset("/usr/lib64/libc-2.17.so", 0x6d300); + if (ptr == NULL) + exit(0); + + fr_t fr = fr_prepare(); + fr_monitor(fr, ptr); + + uint16_t res[1]; + fr_probe(fr, res); + + int lines=0; + for (;;) { + fr_probe(fr, res); + if (res[0] < 100) + printf("%4d: %s", ++lines, "Call to puts\n"); + delayloop(10000); + } +} + diff --git a/demo/FR-gnupg-1.4.13.c b/demo/FR-gnupg-1.4.13.c new file mode 100644 index 0000000..7dff292 --- /dev/null +++ b/demo/FR-gnupg-1.4.13.c @@ -0,0 +1,81 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include + +#define SAMPLES 100000 +#define SLOT 2000 +#define THRESHOLD 100 + +char *monitor[] = { + "mpih-mul.c:85", + "mpih-mul.c:271", + "mpih-div.c:356" +}; +int nmonitor = sizeof(monitor)/sizeof(monitor[0]); + +void usage(const char *prog) { + fprintf(stderr, "Usage: %s \n", prog); + exit(1); +} + + +int main(int ac, char **av) { +#ifdef HAVE_DEBUG_SYMBOLS + char *binary = av[1]; + if (binary == NULL) + usage(av[0]); + + fr_t fr = fr_prepare(); + for (int i = 0; i < nmonitor; i++) { + uint64_t offset = sym_getsymboloffset(binary, monitor[i]); + if (offset == ~0ULL) { + fprintf(stderr, "Cannot find %s in %s\n", monitor[i], binary); + exit(1); + } + fr_monitor(fr, map_offset(binary, offset)); + } + + uint16_t *res = malloc(SAMPLES * nmonitor * sizeof(uint16_t)); + for (int i = 0; i < SAMPLES * nmonitor ; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + fr_probe(fr, res); + + int l = fr_trace(fr, SAMPLES, res, SLOT, THRESHOLD, 500); + for (int i = 0; i < l; i++) { + for (int j = 0; j < nmonitor; j++) + printf("%d ", res[i * nmonitor + j]); + putchar('\n'); + } + + free(res); + fr_release(fr); +#else // HAVE_DEBUG_SYMBOLS + fprintf(stderr, "%s: No dupport for debug symbols\n", av[0]); + exit(1); +#endif + +} diff --git a/demo/FR-threshold.c b/demo/FR-threshold.c new file mode 100644 index 0000000..e6f327b --- /dev/null +++ b/demo/FR-threshold.c @@ -0,0 +1,96 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define SAMPLES 100000 + +int forkslave(void *ptr); +int compare(const void *p1, const void *p2); + + +int main(int ac, char **av) { + fr_t fr = fr_prepare(); + + void *ptr = map_offset("FR-threshold.c", 0); + fr_monitor(fr, ptr); + + uint16_t *memory = malloc(SAMPLES * sizeof(uint16_t)); + memset(memory, 1, SAMPLES * sizeof(uint16_t)); + delayloop(1000000000); + + for (int i = 0; i < SAMPLES; i++) { + fr_probe(fr, memory + i); + delayloop(10000); + } + + pid_t pid = forkslave(ptr); + if (pid == -1) { + perror("fork"); + exit(1); + } + + uint16_t *cache = malloc(SAMPLES * sizeof(uint16_t)); + memset(cache, 1, SAMPLES * sizeof(uint16_t)); + + for (int i = 0; i < SAMPLES; i++) { + fr_probe(fr, cache + i); + delayloop(10000); + } + + kill(pid, SIGKILL); + + qsort(memory, SAMPLES, sizeof(uint16_t), compare); + qsort(cache, SAMPLES, sizeof(uint16_t), compare); + printf(" : Mem Cache\n"); + printf("Minimum : %5d %5d\n", memory[0], cache[0]); + printf("Bottom decile: %5d %5d\n", memory[SAMPLES/10], cache[SAMPLES/10]); + printf("Median : %5d %5d\n", memory[SAMPLES/2], cache[SAMPLES/2]); + printf("Top decile : %5d %5d\n", memory[(SAMPLES * 9)/10], cache[(SAMPLES * 9)/10]); + printf("Maximum : %5d %5d\n", memory[SAMPLES-1], cache[SAMPLES-1]); + + free(memory); + free(cache); + fr_release(fr); +} + +volatile int a; + +int forkslave(void *ptr) { + pid_t pid = fork(); + if (pid != 0) + return pid; + for(;;) + a += *(char *)ptr; +} + +int compare(const void *p1, const void *p2) { + uint16_t u1 = *(uint16_t *)p1; + uint16_t u2 = *(uint16_t *)p2; + + return (int)u1 - (int)u2; +} + diff --git a/demo/L1-capture.c b/demo/L1-capture.c new file mode 100644 index 0000000..9676f87 --- /dev/null +++ b/demo/L1-capture.c @@ -0,0 +1,78 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include + +#include +#include + +#define MAX_SAMPLES 100000 + +void usage(const char *prog) { + fprintf(stderr, "Usage: %s \n", prog); + exit(1); +} + +int main(int ac, char **av) { + int samples = 0; + + if (av[1] == NULL) + usage(av[0]); + samples = atoi(av[1]); + if (samples < 0) + usage(av[0]); + if (samples > MAX_SAMPLES) + samples = MAX_SAMPLES; + l1pp_t l1 = l1_prepare(NULL); + + int nsets = l1_getmonitoredset(l1, NULL, 0); + + int *map = calloc(nsets, sizeof(int)); + l1_getmonitoredset(l1, map, nsets); + + int rmap[L1_SETS]; + for (int i = 0; i < L1_SETS; i++) + rmap[i] = -1; + for (int i = 0; i < nsets; i++) + rmap[map[i]] = i; + + + uint16_t *res = calloc(samples * nsets, sizeof(uint16_t)); + for (int i = 0; i < samples * nsets; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + + delayloop(3000000000U); + l1_repeatedprobe(l1, samples, res, 0); + + for (int i = 0; i < samples; i++) { + for (int j = 0; j < L1_SETS; j++) { + if (rmap[j] == -1) + printf(" 0 "); + else + printf("%3d ", res[i*nsets + rmap[j]]); + } + putchar('\n'); + } + + free(map); + free(res); + l1_release(l1); +} diff --git a/demo/L1-rattle.c b/demo/L1-rattle.c new file mode 100644 index 0000000..4224507 --- /dev/null +++ b/demo/L1-rattle.c @@ -0,0 +1,14 @@ +#include +#include +#include + +volatile char buffer[4096]; + +int main(int ac, char **av) { + for (;;) { + for (int i = 0; i < 64000; i++) + buffer[800] += i; + for (int i = 0; i < 64000; i++) + buffer[1800] += i; + } +} diff --git a/demo/L2-capture.c b/demo/L2-capture.c new file mode 100644 index 0000000..051ed50 --- /dev/null +++ b/demo/L2-capture.c @@ -0,0 +1,84 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include + +#include +#include + +#define MAX_SAMPLES 100000 + +void usage(const char *prog) { + fprintf(stderr, "Usage: %s \n", prog); + exit(1); +} + +int main(int ac, char **av) { + int samples = 0; + + if (av[1] == NULL) + usage(av[0]); + samples = atoi(av[1]); + if (samples < 0) + usage(av[0]); + if (samples > MAX_SAMPLES) + samples = MAX_SAMPLES; + + l2info_t l2i = (l2info_t)malloc(sizeof(struct l2info)); + l2i->associativity = 8; + l2i->sets = 1024; + + l2pp_t l2 = l2_prepare(l2i, NULL); + + int nsets = l2_getmonitoredset(l2, NULL, 0); + + int *map = calloc(nsets, sizeof(int)); + l2_getmonitoredset(l2, map, nsets); + + int rmap[l2i->sets]; + for (int i = 0; i < l2i->sets; i++) + rmap[i] = -1; + for (int i = 0; i < nsets; i++) + rmap[map[i]] = i; + + uint16_t *res = calloc(samples * nsets, sizeof(uint16_t)); + for (int i = 0; i < samples * nsets; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + + delayloop(3000000000U); + l2_repeatedprobe(l2, samples, res, 0); + + + + for (int i = 0; i < samples; i++) { + for (int j = 0; j < l2i->sets; j++) { + if (rmap[j] == -1) + printf(" 0 "); + else + printf("%3d ", res[i*nsets + rmap[j]]); + } + putchar('\n'); + } + + free(map); + free(res); + l2_release(l2); +} diff --git a/demo/L2-rattle.c b/demo/L2-rattle.c new file mode 100644 index 0000000..85dbc78 --- /dev/null +++ b/demo/L2-rattle.c @@ -0,0 +1,94 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef MAP_HUGETLB +#define HUGEPAGES MAP_HUGETLB +#endif +#ifdef VM_FLAGS_SUPERPAGE_SIZE_2MB +#define HUGEPAGES VM_FLAGS_SUPERPAGE_SIZE_2MB +#endif + +#ifdef HUGEPAGES +#define HUGEPAGEBITS 21 +#define HUGEPAGESIZE (1<. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#define L2_SETS 1024 + +#include +#include +#include +#include + +#ifdef MAP_HUGETLB +#define HUGEPAGES MAP_HUGETLB +#endif +#ifdef VM_FLAGS_SUPERPAGE_SIZE_2MB +#define HUGEPAGES VM_FLAGS_SUPERPAGE_SIZE_2MB +#endif + +#ifdef HUGEPAGES +#define HUGEPAGEBITS 21 +#define HUGEPAGESIZE (1 << HUGEPAGEBITS) +#define HUGEPAGEMASK (HUGEPAGESIZE - 1) +#endif + +#define TEST_RANGE 200 + +void grayspace(int64_t intensity, int64_t min, int64_t max, char c) +{ + printf("\e[48;5;%ld;31;1m%c\e[0m", 232 + ((intensity - min) * 24) / (max - min), c); +} + +void display(int64_t *data[L2_SETS]) +{ + int64_t min = INT64_MAX; + int64_t max = INT64_MIN; + + for (int i = 0; i < TEST_RANGE; i++) + { + for (int j = 0; j < L2_SETS; j++) + { + if (min > data[i][j]) + min = data[i][j]; + if (max < data[i][j]) + max = data[i][j]; + } + } + + if (max == min) + max++; + for (int itr = 0; itr < TEST_RANGE; itr++) + { + printf("%05X. ", itr); + for (int j = 0; j < L2_SETS; j++) + { + grayspace(data[itr][j], min, max, ' '); + } + printf("\n"); + } +} + +char *readBuffer; + +void exec(lxpp_t l1, int recnum, void *data) +{ + register uint16_t num = (uint16_t)(uintptr_t)data; + for (volatile int i = 0; i < 100; i++) + readBuffer[num * L2_CACHELINE] = i; + return; +} + +#define SCALE 1000 +#define SAMPLES 10000 + +static void normalise(int64_t *avg[TEST_RANGE]) +{ + uint64_t set_avg[1024]; + bzero(set_avg, sizeof(set_avg)); + + for (int key = 0; key < TEST_RANGE; key++) + { + for (int set = 0; set < L2_SETS; set++) + { + avg[key][set] = (SCALE * avg[key][set] / SAMPLES); + set_avg[set] += avg[key][set]; + } + } + for (int i = 0; i < 1024; i++) + { + set_avg[i] /= TEST_RANGE; + } + for (int key = 0; key < TEST_RANGE; key++) + { + for (int set = 0; set < 1024; set++) + { + avg[key][set] -= set_avg[set]; + } + } +} + +int main(int argc, char **argv) +{ + l2pp_t l2 = l2_prepare(NULL, NULL); + l2info_t l2info = (l2info_t)malloc(sizeof(struct l2info)); + + l2_getl2info(l2, l2info); + const int nsets = l2info->sets; + + int monitoredSets = l2_getmonitoredset(l2, NULL, nsets); + readBuffer = mmap(NULL, monitoredSets * L2_CACHELINE, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | HUGEPAGES, -1, 0); + + int64_t *avg[TEST_RANGE]; + for (int i = 0; i < TEST_RANGE; i++) + { + avg[i] = calloc(1024, sizeof(int64_t)); + } + + for (int i = 0; i < TEST_RANGE; i++) + { + uint16_t key = i; + + int *map = calloc(monitoredSets, sizeof(int)); + uint16_t *res = calloc(SAMPLES * monitoredSets, sizeof(uint16_t)); + l2_randomise(l2); + l2_getmonitoredset(l2, map, monitoredSets); + + l2_syncpp(l2, SAMPLES, res, lx_dummy_cb, exec, (void *)(uint64_t)key); + + for (int sample = 0; sample < SAMPLES; sample++) + { + for (int idx = 0; idx < monitoredSets; idx++) + { + // printf("%d\n", map[idx]); + avg[i][map[idx]] += res[idx + monitoredSets * sample]; + } + } + + free(map); + free(res); + } + normalise(avg); + display(avg); + munmap(readBuffer, monitoredSets * L2_CACHELINE); +} diff --git a/demo/L3-capture.c b/demo/L3-capture.c new file mode 100644 index 0000000..63e44dd --- /dev/null +++ b/demo/L3-capture.c @@ -0,0 +1,58 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include + +#include +#include + +#define SAMPLES 1000 + + +int main(int ac, char **av) { + delayloop(3000000000U); + + l3pp_t l3 = l3_prepare(NULL, NULL); + + int nsets = l3_getSets(l3); + int nmonitored = nsets/64; + + for (int i = 17; i < nsets; i += 64) + l3_monitor(l3, i); + + + uint16_t *res = calloc(SAMPLES * nmonitored, sizeof(uint16_t)); + for (int i = 0; i < SAMPLES * nmonitored; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + + l3_repeatedprobe(l3, SAMPLES, res, 0); + + + for (int i = 0; i < SAMPLES; i++) { + for (int j = 0; j < nmonitored; j++) { + printf("%4d ", res[i*nmonitored + j]); + } + putchar('\n'); + } + + free(res); + l3_release(l3); +} diff --git a/demo/L3-capturecount.c b/demo/L3-capturecount.c new file mode 100644 index 0000000..ab32c7c --- /dev/null +++ b/demo/L3-capturecount.c @@ -0,0 +1,57 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include + +#include +#include + +#define SAMPLES 1000 + + +int main(int ac, char **av) { + delayloop(3000000000U); + + l3pp_t l3 = l3_prepare(NULL, NULL); + + int nsets = l3_getSets(l3); + int nmonitored = nsets/64; + + for (int i = 17; i < nsets; i += 64) + l3_monitor(l3, i); + + + uint16_t *res = calloc(SAMPLES * nmonitored, sizeof(uint16_t)); + for (int i = 0; i < SAMPLES * nmonitored; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + + l3_repeatedprobecount(l3, SAMPLES, res, 0); + + for (int i = 0; i < SAMPLES; i++) { + for (int j = 0; j < nmonitored; j++) { + printf("%4d ", res[i*nmonitored + j]); + } + putchar('\n'); + } + + free(res); + l3_release(l3); +} diff --git a/demo/L3-scan.c b/demo/L3-scan.c new file mode 100644 index 0000000..3986fd5 --- /dev/null +++ b/demo/L3-scan.c @@ -0,0 +1,119 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include + +#include +#include +#include + +#define SAMPLES 200 + +struct descr { + uint32_t flags; + char *text; +}; + +struct descr descr[] = { + {0, "Default"}, + {L3FLAG_QUADRATICMAP, "Quadratic"}, + {L3FLAG_LINEARMAP, "Linear"}, + {L3FLAG_NOHUGEPAGES, "Small pages"}, + {L3FLAG_QUADRATICMAP|L3FLAG_NOHUGEPAGES, "Small pages, Quad."}, + {L3FLAG_LINEARMAP|L3FLAG_NOHUGEPAGES, "Small pages, Lin."}, + { 0, NULL} +}; + + +int main(int ac, char **av) { + delayloop(3000000000U); + + + l3info_t l3i = (l3info_t)malloc(sizeof(struct l3info)); + l3i->associativity = 0; + l3i->slices = 0; + l3i->setsperslice = 0; + l3i->bufsize = 0; + //l3i->flags = L3FLAG_NOHUGEPAGES|L3FLAG_QUADRATICMAP; + //l3i->flags = L3FLAG_NOHUGEPAGES; + l3i->flags = L3FLAG_QUADRATICMAP; + //l3i->flags = 0; + l3i->progressNotification = NULL; + l3i->progressNotificationData = NULL; + + for (int j = 0; j < 5; j++) { + for (int i = 0; descr[i].text; i++) { + uint64_t t = rdtscp64(); + l3i->associativity = 0; + l3i->slices = 0; + l3i->setsperslice = 0; + l3i->bufsize = 0; + l3i->flags = descr[i].flags; + l3i->progressNotification = NULL; + l3i->progressNotificationData = NULL; + l3pp_t l3 = l3_prepare(l3i, NULL); + + t = rdtscp64() - t; + char l=' '; + if (t > 2000) { + t = t / 1000; + l = 'K'; + } + if (t > 2000) { + t = t / 1000; + l = 'M'; + } + if (t > 2000) { + t = t / 1000; + l = 'G'; + } + if (t > 2000) { + t = t / 1000; + l = 'T'; + } + printf("%20s %5lu%c cycles, %5d sets\n", descr[i].text, t, l, l3_getSets(l3)); + l3_release(l3); + } + } + + + + /* + uint16_t *res = calloc(SAMPLES, sizeof(uint16_t)); + for (int i = 0; i < SAMPLES; i+= 4096/sizeof(uint16_t)) + res[i] = 1; + + for (int i = 0; i < nsets; i++) { + l3_unmonitorall(l3); + l3_monitor(l3, i); + + l3_repeatedprobecount(l3, SAMPLES, res, 2000); + + for (int j = 0; j < SAMPLES; j++) { + printf("%4d ", (int16_t)res[j]); + } + putchar('\n'); + } + + free(res); + */ +} diff --git a/demo/MM-allocate b/demo/MM-allocate new file mode 100755 index 0000000..f973f13 Binary files /dev/null and b/demo/MM-allocate differ diff --git a/demo/Makefile.in b/demo/Makefile.in new file mode 100644 index 0000000..590d97b --- /dev/null +++ b/demo/Makefile.in @@ -0,0 +1,48 @@ +FILES= \ + CB-hist.c \ + FF-gnupg-1.4.13.c \ + FF-trace.c \ + FR-1-file-access.c \ + FR-2-file-access.c \ + FR-flush.c \ + FR-function-call-nodelay.c \ + FR-function-call.c \ + FR-gnupg-1.4.13.c \ + FR-threshold.c \ + L1-capture.c \ + L1-rattle.c \ + L3-capture.c \ + L3-capturecount.c \ + L3-scan.c \ + L2-capture.c \ + L2-rattle.c \ + L2-sequence.c + +prefix=@prefix@ +exec_prefix=@exec_prefix@ + +FTARGETS=$(FILES:.c=) +FOBJS=${FILES:.c=.o} +#CFLAGS=-g -std=gnu99 -I.. +CFLAGS=@CFLAGS@ -I.. +LDFLAGS=-L../src/ -g +LDLIBS=-lmastik @LIBS@ + +TARGETS=${FTARGETS} ST-L1PP-AES +OBJS=${FOBJS} ST-L1PP-AES.o aes_core.o + +all: ${TARGETS} + +install: + +${FTARGETS}: %: %.o + ${CC} ${LDFLAGS} -o $@ $@.o ${LDLIBS} + +ST-L1PP-AES: ST-L1PP-AES.o aes_core.o + ${CC} ${LDFLAGS} -o $@ ST-L1PP-AES.o aes_core.o ${LDLIBS} + +clean: + rm -f ${TARGETS} ${OBJS} *.sig out + +distclean: clean + rm Makefile config.h diff --git a/demo/ST-L1PP-AES.c b/demo/ST-L1PP-AES.c new file mode 100644 index 0000000..1d4158b --- /dev/null +++ b/demo/ST-L1PP-AES.c @@ -0,0 +1,224 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include "aes.h" + +#include +#include + +#define AESSIZE 16 + +#define NSAMPLES 100000 + +typedef uint8_t aes_t[AESSIZE]; + +void usage(char *p) { + fprintf(stderr, "Usage: %s -aAhH [-s ]\n", p); + exit(1); +} + +void tobinary(char *data, aes_t aes) { + assert(strlen(data)==AESSIZE*2); + unsigned int x; + for (int i = 0; i < AESSIZE; i++) { + sscanf(data+i*2, "%2x", &x); + aes[i] = x; + } +} + +void grayspace(int64_t intensity, int64_t min, int64_t max, char c) { + printf("\e[48;5;%ld;31;1m%c\e[0m", 232+((intensity - min) *24)/(max - min), c); +} + +int64_t display(int counts[256], int64_t data[256][1024], int guess, int offset) { + int64_t min = INT64_MAX; + int64_t max = INT64_MIN; + for (int i = 0; i < 256; i++) + if (counts[i]) + for (int j = 0; j < L1_SETS; j++){ + if (min > data[i][j]) + min = data[i][j]; + if (max < data[i][j]) + max = data[i][j]; + } + + if (max == min) + max++; + for (int i = 0; i < 256; i++) { + if (counts[i]) { + printf("%02X. ", i); + int set = (((i >> 4) ^ guess) + offset) % L1_SETS; + if (offset < 0) + set = -1; + for (int j = 0; j < L1_SETS; j++) { + grayspace(data[i][j], min, max, set == j ? '#' : ' '); + } + printf("\n"); + } + } +} + +void analyse(int64_t data[256][1024], int *key, int *offset) { + int64_t max = INT64_MIN; + + for (int guess = 0; guess < 16; guess++) { + for (int off = 0; off < L1_SETS; off++) { + int64_t sum = 0LL; + for (int pt = 0; pt < 16; pt++) { + int set = (off + (pt ^ guess)) % L1_SETS; + sum += data[pt << 4][set]; + } + if (sum > max) { + max = sum; + *key = guess; + *offset = off; + } + } + } +} + + +void crypto(uint8_t *input, uint8_t *output, void *data) { + AES_KEY *aeskey = (AES_KEY *)data; + AES_encrypt(input, output, aeskey); +} + + + + +int main(int ac, char **av) { + int samples = NSAMPLES; + int round = 1; + int analysis = 1; + int heatmap = 1; + int byte = 0; + int ch; + while ((ch = getopt(ac, av, "b:s:12aAhH")) != -1) { + switch (ch){ + case 's': + samples = atoi(optarg); + break; + case '1': + round = 1; + break; + case '2': + round = 2; + break; + case 'a': + analysis = 1; + break; + case 'A': + analysis = 0; + break; + case 'h': + heatmap = 1; + break; + case 'H': + heatmap = 0; + break; + case 'b': + byte = atoi(optarg); + break; + default: + usage(av[0]); + } + } + + if (round == 2) + analysis = 0; + if (!analysis && !heatmap) { + fprintf(stderr, "No output format specified\n"); + usage(av[0]); + } + if (samples <= 0) { + fprintf(stderr, "Negative number of samples\n"); + usage(av[0]); + } + if (byte < 0 || byte >= AESSIZE) { + fprintf(stderr, "Target byte must be in the range 0--15\n"); + usage(av[0]); + } + + + aes_t key; + char * keystr = "2b7e151628aed2a6abf7158809cf4f3c"; + tobinary(keystr, key); + AES_KEY aeskey; + private_AES_set_encrypt_key(key, 128, &aeskey); + + delayloop(1000000000); + + if (round == 1) { + st_clusters_t clusters = syncPrimeProbe(samples, + AESSIZE, + 1, + NULL, + NULL, + crypto, + &aeskey, + 0xf0, + 1); + for (int i = 0; i < 16; i++) { + int key, offset; + printf("Key byte %2d", i); + if (analysis) { + analyse(clusters[i].avg, &key, &offset); + printf(" Guess:%1x-\n", key); + } else { + offset = -L1_SETS; + printf("\n"); + } + if (heatmap) { + display(clusters[i].count, clusters[i].avg, key, offset); + printf("\n"); + } + } + free(clusters); + } else if (round == 2) { + aes_t fixmask, fixdata; + tobinary("00000000000000000000000000000000", fixmask); + tobinary("00000000000000000000000000000000", fixdata); + + int col0 = (byte + 4 - (byte >> 2) & 3); + for (int row = 0; row < 4; row++) { + int b = row * 4 + ((col0 + row) & 3); + if (b != byte) + fixmask[b] = 0xff; + } + + st_clusters_t clusters = syncPrimeProbe(samples, + AESSIZE, + 1, + fixmask, + fixdata, + crypto, + &aeskey, + 0xff, + 1); + + display(clusters[byte].count, clusters[byte].avg, 0, -L1_SETS); + free(clusters); + } +} diff --git a/demo/aes.h b/demo/aes.h new file mode 100644 index 0000000..8d28343 --- /dev/null +++ b/demo/aes.h @@ -0,0 +1,149 @@ +/* crypto/aes/aes.h */ +/* ==================================================================== + * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + */ + +#ifndef HEADER_AES_H +# define HEADER_AES_H + +//# include + +# ifdef OPENSSL_NO_AES +# error AES is disabled. +# endif + +# include + +# define AES_ENCRYPT 1 +# define AES_DECRYPT 0 + +/* + * Because array size can't be a const in C, the following two are macros. + * Both sizes are in bytes. + */ +# define AES_MAXNR 14 +# define AES_BLOCK_SIZE 16 + +#ifdef __cplusplus +extern "C" { +#endif + +/* This should be a hidden type, but EVP requires that the size be known */ +struct aes_key_st { +# ifdef AES_LONG + unsigned long rd_key[4 * (AES_MAXNR + 1)]; +# else + unsigned int rd_key[4 * (AES_MAXNR + 1)]; +# endif + int rounds; +}; +typedef struct aes_key_st AES_KEY; + +const char *AES_options(void); + +int AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); +int AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); + +int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); +int private_AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); + +void AES_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key); +void AES_decrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key); + +void AES_ecb_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key, const int enc); +void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); +void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num); +void AES_ctr128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char ivec[AES_BLOCK_SIZE], + unsigned char ecount_buf[AES_BLOCK_SIZE], + unsigned int *num); +/* NB: the IV is _two_ blocks long */ +void AES_ige_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); +/* NB: the IV is _four_ blocks long */ +void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + const AES_KEY *key2, const unsigned char *ivec, + const int enc); + +int AES_wrap_key(AES_KEY *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, unsigned int inlen); +int AES_unwrap_key(AES_KEY *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, unsigned int inlen); + + +#ifdef __cplusplus +} +#endif + +#endif /* !HEADER_AES_H */ diff --git a/demo/aes_core.c b/demo/aes_core.c new file mode 100644 index 0000000..ce90a8d --- /dev/null +++ b/demo/aes_core.c @@ -0,0 +1,1369 @@ +/* crypto/aes/aes_core.c */ +/** + * rijndael-alg-fst.c + * + * @version 3.0 (December 2000) + * + * Optimised ANSI C code for the Rijndael cipher (now AES) + * + * @author Vincent Rijmen + * @author Antoon Bosselaers + * @author Paulo Barreto + * + * This code is hereby placed in the public domain. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* Note: rewritten a little bit to provide error control and an OpenSSL- + compatible API */ + +#ifndef AES_DEBUG +# ifndef NDEBUG +# define NDEBUG +# endif +#endif +#include + +#include +#include +typedef uint32_t u32; +typedef uint32_t u8; +# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3])) +# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); } + +#include "aes.h" + + +#ifndef AES_ASM +/*- +Te0[x] = S [x].[02, 01, 01, 03]; +Te1[x] = S [x].[03, 02, 01, 01]; +Te2[x] = S [x].[01, 03, 02, 01]; +Te3[x] = S [x].[01, 01, 03, 02]; + +Td0[x] = Si[x].[0e, 09, 0d, 0b]; +Td1[x] = Si[x].[0b, 0e, 09, 0d]; +Td2[x] = Si[x].[0d, 0b, 0e, 09]; +Td3[x] = Si[x].[09, 0d, 0b, 0e]; +Td4[x] = Si[x].[01]; +*/ + +static const u32 Te0[256] __attribute__ ((aligned (64)))= { + 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU, + 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U, + 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU, + 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU, + 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U, + 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU, + 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU, + 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, + 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, + 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, + 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U, + 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU, + 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU, + 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U, + 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU, + 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU, + 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU, + 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU, + 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU, + 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U, + 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU, + 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU, + 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU, + 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU, + 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U, + 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U, + 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U, + 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U, + 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU, + 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U, + 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U, + 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU, + 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU, + 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U, + 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U, + 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U, + 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU, + 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U, + 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU, + 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U, + 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU, + 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U, + 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U, + 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU, + 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U, + 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U, + 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U, + 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U, + 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U, + 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U, + 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U, + 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U, + 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU, + 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U, + 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U, + 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U, + 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U, + 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U, + 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U, + 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU, + 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U, + 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U, + 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U, + 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU, +}; +static const u32 Te1[256] = { + 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU, + 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U, + 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU, + 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U, + 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU, + 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U, + 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU, + 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U, + 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U, + 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU, + 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U, + 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U, + 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U, + 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU, + 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U, + 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U, + 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU, + 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U, + 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U, + 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U, + 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU, + 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU, + 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U, + 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU, + 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU, + 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U, + 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU, + 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U, + 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU, + 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U, + 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U, + 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U, + 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU, + 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U, + 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU, + 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U, + 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU, + 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U, + 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U, + 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU, + 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU, + 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU, + 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U, + 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U, + 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU, + 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U, + 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU, + 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U, + 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU, + 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U, + 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU, + 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU, + 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U, + 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU, + 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U, + 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU, + 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U, + 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U, + 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U, + 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU, + 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU, + 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U, + 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU, + 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U, +}; +static const u32 Te2[256] = { + 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU, + 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U, + 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU, + 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U, + 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU, + 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U, + 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU, + 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U, + 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U, + 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU, + 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U, + 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U, + 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U, + 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU, + 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U, + 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U, + 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU, + 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U, + 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U, + 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U, + 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU, + 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU, + 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U, + 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU, + 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU, + 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U, + 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU, + 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U, + 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU, + 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U, + 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U, + 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U, + 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU, + 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U, + 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU, + 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U, + 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU, + 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U, + 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U, + 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU, + 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU, + 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU, + 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U, + 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U, + 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU, + 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U, + 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU, + 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U, + 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU, + 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U, + 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU, + 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU, + 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U, + 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU, + 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U, + 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU, + 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U, + 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U, + 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U, + 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU, + 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU, + 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U, + 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU, + 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U, +}; +static const u32 Te3[256] = { + 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U, + 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U, + 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U, + 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU, + 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU, + 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU, + 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U, + 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU, + 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU, + 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U, + 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U, + 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU, + 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU, + 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU, + 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU, + 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU, + 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U, + 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU, + 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU, + 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U, + 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U, + 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U, + 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U, + 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U, + 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU, + 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U, + 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU, + 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU, + 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U, + 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U, + 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U, + 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU, + 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U, + 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU, + 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU, + 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U, + 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U, + 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU, + 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U, + 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU, + 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U, + 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U, + 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U, + 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U, + 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU, + 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U, + 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU, + 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U, + 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU, + 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U, + 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU, + 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU, + 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU, + 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU, + 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U, + 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U, + 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U, + 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U, + 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U, + 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U, + 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU, + 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U, + 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU, + 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU, +}; + +static const u32 Td0[256] = { + 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U, + 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U, + 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U, + 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU, + 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U, + 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U, + 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU, + 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U, + 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU, + 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U, + 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U, + 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U, + 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U, + 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU, + 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U, + 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU, + 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U, + 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU, + 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U, + 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U, + 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U, + 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU, + 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U, + 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU, + 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U, + 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU, + 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U, + 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU, + 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU, + 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U, + 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU, + 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U, + 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU, + 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U, + 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U, + 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U, + 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU, + 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U, + 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U, + 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU, + 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U, + 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U, + 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U, + 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U, + 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U, + 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU, + 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U, + 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U, + 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U, + 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U, + 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U, + 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU, + 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU, + 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU, + 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU, + 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U, + 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U, + 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU, + 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU, + 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U, + 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU, + 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U, + 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U, + 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U, +}; +static const u32 Td1[256] = { + 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU, + 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U, + 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU, + 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U, + 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U, + 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U, + 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U, + 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U, + 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U, + 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU, + 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU, + 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU, + 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U, + 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU, + 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U, + 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U, + 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U, + 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU, + 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU, + 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U, + 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU, + 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U, + 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU, + 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU, + 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U, + 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U, + 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U, + 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU, + 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U, + 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU, + 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U, + 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U, + 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U, + 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU, + 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U, + 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U, + 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U, + 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U, + 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U, + 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U, + 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU, + 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU, + 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U, + 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU, + 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U, + 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU, + 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU, + 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U, + 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU, + 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U, + 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U, + 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U, + 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U, + 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U, + 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U, + 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U, + 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU, + 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U, + 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U, + 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU, + 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U, + 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U, + 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U, + 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U, +}; +static const u32 Td2[256] = { + 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U, + 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U, + 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U, + 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U, + 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU, + 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U, + 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U, + 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U, + 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U, + 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU, + 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U, + 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U, + 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU, + 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U, + 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U, + 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U, + 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U, + 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U, + 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U, + 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU, + 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U, + 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U, + 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U, + 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U, + 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U, + 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU, + 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU, + 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U, + 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU, + 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U, + 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU, + 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU, + 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU, + 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU, + 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U, + 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U, + 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U, + 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U, + 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U, + 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U, + 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U, + 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU, + 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU, + 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U, + 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U, + 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU, + 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU, + 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U, + 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U, + 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U, + 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U, + 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U, + 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U, + 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U, + 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU, + 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U, + 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U, + 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U, + 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U, + 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U, + 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U, + 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU, + 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U, + 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U, +}; +static const u32 Td3[256] = { + 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU, + 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU, + 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U, + 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U, + 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU, + 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU, + 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U, + 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU, + 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U, + 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU, + 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U, + 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U, + 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U, + 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U, + 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U, + 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU, + 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU, + 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U, + 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U, + 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU, + 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU, + 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U, + 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U, + 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U, + 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U, + 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU, + 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U, + 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U, + 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU, + 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU, + 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U, + 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U, + 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U, + 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU, + 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U, + 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U, + 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U, + 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U, + 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U, + 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U, + 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U, + 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU, + 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U, + 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U, + 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU, + 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU, + 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U, + 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU, + 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U, + 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U, + 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U, + 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U, + 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U, + 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U, + 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU, + 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU, + 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU, + 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU, + 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U, + 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U, + 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U, + 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU, + 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U, + 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U, +}; +static const u8 Td4[256] = { + 0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U, + 0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU, + 0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U, + 0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU, + 0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU, + 0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU, + 0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U, + 0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U, + 0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U, + 0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U, + 0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU, + 0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U, + 0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU, + 0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U, + 0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U, + 0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU, + 0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU, + 0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U, + 0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U, + 0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU, + 0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U, + 0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU, + 0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U, + 0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U, + 0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U, + 0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU, + 0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU, + 0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU, + 0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U, + 0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U, + 0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U, + 0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU, +}; +static const u32 rcon[] = { + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ +}; + +/** + * Expand the cipher key into the encryption key schedule. + */ +int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i = 0; + u32 temp; + + if (!userKey || !key) + return -1; + if (bits != 128 && bits != 192 && bits != 256) + return -2; + + rk = key->rd_key; + + if (bits==128) + key->rounds = 10; + else if (bits==192) + key->rounds = 12; + else + key->rounds = 14; + + rk[0] = GETU32(userKey ); + rk[1] = GETU32(userKey + 4); + rk[2] = GETU32(userKey + 8); + rk[3] = GETU32(userKey + 12); + if (bits == 128) { + while (1) { + temp = rk[3]; + rk[4] = rk[0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[5] = rk[1] ^ rk[4]; + rk[6] = rk[2] ^ rk[5]; + rk[7] = rk[3] ^ rk[6]; + if (++i == 10) { + return 0; + } + rk += 4; + } + } + rk[4] = GETU32(userKey + 16); + rk[5] = GETU32(userKey + 20); + if (bits == 192) { + while (1) { + temp = rk[ 5]; + rk[ 6] = rk[ 0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 7] = rk[ 1] ^ rk[ 6]; + rk[ 8] = rk[ 2] ^ rk[ 7]; + rk[ 9] = rk[ 3] ^ rk[ 8]; + if (++i == 8) { + return 0; + } + rk[10] = rk[ 4] ^ rk[ 9]; + rk[11] = rk[ 5] ^ rk[10]; + rk += 6; + } + } + rk[6] = GETU32(userKey + 24); + rk[7] = GETU32(userKey + 28); + if (bits == 256) { + while (1) { + temp = rk[ 7]; + rk[ 8] = rk[ 0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 9] = rk[ 1] ^ rk[ 8]; + rk[10] = rk[ 2] ^ rk[ 9]; + rk[11] = rk[ 3] ^ rk[10]; + if (++i == 7) { + return 0; + } + temp = rk[11]; + rk[12] = rk[ 4] ^ + (Te2[(temp >> 24) ] & 0xff000000) ^ + (Te3[(temp >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(temp >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(temp ) & 0xff] & 0x000000ff); + rk[13] = rk[ 5] ^ rk[12]; + rk[14] = rk[ 6] ^ rk[13]; + rk[15] = rk[ 7] ^ rk[14]; + + rk += 8; + } + } + return 0; +} + +/** + * Expand the cipher key into the decryption key schedule. + */ +int private_AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i, j, status; + u32 temp; + + /* first, start with an encryption schedule */ + status = private_AES_set_encrypt_key(userKey, bits, key); + if (status < 0) + return status; + + rk = key->rd_key; + + /* invert the order of the round keys: */ + for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) { + temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp; + temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; + temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; + temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; + } + /* apply the inverse MixColumn transform to all round keys but the first and the last: */ + for (i = 1; i < (key->rounds); i++) { + rk += 4; + rk[0] = + Td0[Te1[(rk[0] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[0] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[0] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[0] ) & 0xff] & 0xff]; + rk[1] = + Td0[Te1[(rk[1] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[1] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[1] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[1] ) & 0xff] & 0xff]; + rk[2] = + Td0[Te1[(rk[2] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[2] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[2] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[2] ) & 0xff] & 0xff]; + rk[3] = + Td0[Te1[(rk[3] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[3] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[3] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[3] ) & 0xff] & 0xff]; + } + return 0; +} + +/* + * Encrypt a single block + * in and out can overlap + */ +void AES_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key) { + + const u32 *rk; + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + assert(in && out && key); + rk = key->rd_key; + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(in ) ^ rk[0]; + s1 = GETU32(in + 4) ^ rk[1]; + s2 = GETU32(in + 8) ^ rk[2]; + s3 = GETU32(in + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39]; + if (key->rounds > 10) { + /* round 10: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47]; + if (key->rounds > 12) { + /* round 12: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55]; + } + } + rk += key->rounds << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = key->rounds >> 1; + for (;;) { + t0 = + Te0[(s0 >> 24) ] ^ + Te1[(s1 >> 16) & 0xff] ^ + Te2[(s2 >> 8) & 0xff] ^ + Te3[(s3 ) & 0xff] ^ + rk[4]; + t1 = + Te0[(s1 >> 24) ] ^ + Te1[(s2 >> 16) & 0xff] ^ + Te2[(s3 >> 8) & 0xff] ^ + Te3[(s0 ) & 0xff] ^ + rk[5]; + t2 = + Te0[(s2 >> 24) ] ^ + Te1[(s3 >> 16) & 0xff] ^ + Te2[(s0 >> 8) & 0xff] ^ + Te3[(s1 ) & 0xff] ^ + rk[6]; + t3 = + Te0[(s3 >> 24) ] ^ + Te1[(s0 >> 16) & 0xff] ^ + Te2[(s1 >> 8) & 0xff] ^ + Te3[(s2 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Te0[(t0 >> 24) ] ^ + Te1[(t1 >> 16) & 0xff] ^ + Te2[(t2 >> 8) & 0xff] ^ + Te3[(t3 ) & 0xff] ^ + rk[0]; + s1 = + Te0[(t1 >> 24) ] ^ + Te1[(t2 >> 16) & 0xff] ^ + Te2[(t3 >> 8) & 0xff] ^ + Te3[(t0 ) & 0xff] ^ + rk[1]; + s2 = + Te0[(t2 >> 24) ] ^ + Te1[(t3 >> 16) & 0xff] ^ + Te2[(t0 >> 8) & 0xff] ^ + Te3[(t1 ) & 0xff] ^ + rk[2]; + s3 = + Te0[(t3 >> 24) ] ^ + Te1[(t0 >> 16) & 0xff] ^ + Te2[(t1 >> 8) & 0xff] ^ + Te3[(t2 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + (Te2[(t0 >> 24) ] & 0xff000000) ^ + (Te3[(t1 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t2 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t3 ) & 0xff] & 0x000000ff) ^ + rk[0]; + PUTU32(out , s0); + s1 = + (Te2[(t1 >> 24) ] & 0xff000000) ^ + (Te3[(t2 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t3 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t0 ) & 0xff] & 0x000000ff) ^ + rk[1]; + PUTU32(out + 4, s1); + s2 = + (Te2[(t2 >> 24) ] & 0xff000000) ^ + (Te3[(t3 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t0 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t1 ) & 0xff] & 0x000000ff) ^ + rk[2]; + PUTU32(out + 8, s2); + s3 = + (Te2[(t3 >> 24) ] & 0xff000000) ^ + (Te3[(t0 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t1 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t2 ) & 0xff] & 0x000000ff) ^ + rk[3]; + PUTU32(out + 12, s3); +} + +/* + * Decrypt a single block + * in and out can overlap + */ +void AES_decrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key) +{ + + const u32 *rk; + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + assert(in && out && key); + rk = key->rd_key; + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(in ) ^ rk[0]; + s1 = GETU32(in + 4) ^ rk[1]; + s2 = GETU32(in + 8) ^ rk[2]; + s3 = GETU32(in + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39]; + if (key->rounds > 10) { + /* round 10: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47]; + if (key->rounds > 12) { + /* round 12: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55]; + } + } + rk += key->rounds << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = key->rounds >> 1; + for (;;) { + t0 = + Td0[(s0 >> 24) ] ^ + Td1[(s3 >> 16) & 0xff] ^ + Td2[(s2 >> 8) & 0xff] ^ + Td3[(s1 ) & 0xff] ^ + rk[4]; + t1 = + Td0[(s1 >> 24) ] ^ + Td1[(s0 >> 16) & 0xff] ^ + Td2[(s3 >> 8) & 0xff] ^ + Td3[(s2 ) & 0xff] ^ + rk[5]; + t2 = + Td0[(s2 >> 24) ] ^ + Td1[(s1 >> 16) & 0xff] ^ + Td2[(s0 >> 8) & 0xff] ^ + Td3[(s3 ) & 0xff] ^ + rk[6]; + t3 = + Td0[(s3 >> 24) ] ^ + Td1[(s2 >> 16) & 0xff] ^ + Td2[(s1 >> 8) & 0xff] ^ + Td3[(s0 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Td0[(t0 >> 24) ] ^ + Td1[(t3 >> 16) & 0xff] ^ + Td2[(t2 >> 8) & 0xff] ^ + Td3[(t1 ) & 0xff] ^ + rk[0]; + s1 = + Td0[(t1 >> 24) ] ^ + Td1[(t0 >> 16) & 0xff] ^ + Td2[(t3 >> 8) & 0xff] ^ + Td3[(t2 ) & 0xff] ^ + rk[1]; + s2 = + Td0[(t2 >> 24) ] ^ + Td1[(t1 >> 16) & 0xff] ^ + Td2[(t0 >> 8) & 0xff] ^ + Td3[(t3 ) & 0xff] ^ + rk[2]; + s3 = + Td0[(t3 >> 24) ] ^ + Td1[(t2 >> 16) & 0xff] ^ + Td2[(t1 >> 8) & 0xff] ^ + Td3[(t0 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + ((u32)Td4[(t0 >> 24) ] << 24) ^ + ((u32)Td4[(t3 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t2 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t1 ) & 0xff]) ^ + rk[0]; + PUTU32(out , s0); + s1 = + ((u32)Td4[(t1 >> 24) ] << 24) ^ + ((u32)Td4[(t0 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t3 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t2 ) & 0xff]) ^ + rk[1]; + PUTU32(out + 4, s1); + s2 = + ((u32)Td4[(t2 >> 24) ] << 24) ^ + ((u32)Td4[(t1 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t0 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t3 ) & 0xff]) ^ + rk[2]; + PUTU32(out + 8, s2); + s3 = + ((u32)Td4[(t3 >> 24) ] << 24) ^ + ((u32)Td4[(t2 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t1 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t0 ) & 0xff]) ^ + rk[3]; + PUTU32(out + 12, s3); +} + +#else /* AES_ASM */ + +static const u8 Te4[256] = { + 0x63U, 0x7cU, 0x77U, 0x7bU, 0xf2U, 0x6bU, 0x6fU, 0xc5U, + 0x30U, 0x01U, 0x67U, 0x2bU, 0xfeU, 0xd7U, 0xabU, 0x76U, + 0xcaU, 0x82U, 0xc9U, 0x7dU, 0xfaU, 0x59U, 0x47U, 0xf0U, + 0xadU, 0xd4U, 0xa2U, 0xafU, 0x9cU, 0xa4U, 0x72U, 0xc0U, + 0xb7U, 0xfdU, 0x93U, 0x26U, 0x36U, 0x3fU, 0xf7U, 0xccU, + 0x34U, 0xa5U, 0xe5U, 0xf1U, 0x71U, 0xd8U, 0x31U, 0x15U, + 0x04U, 0xc7U, 0x23U, 0xc3U, 0x18U, 0x96U, 0x05U, 0x9aU, + 0x07U, 0x12U, 0x80U, 0xe2U, 0xebU, 0x27U, 0xb2U, 0x75U, + 0x09U, 0x83U, 0x2cU, 0x1aU, 0x1bU, 0x6eU, 0x5aU, 0xa0U, + 0x52U, 0x3bU, 0xd6U, 0xb3U, 0x29U, 0xe3U, 0x2fU, 0x84U, + 0x53U, 0xd1U, 0x00U, 0xedU, 0x20U, 0xfcU, 0xb1U, 0x5bU, + 0x6aU, 0xcbU, 0xbeU, 0x39U, 0x4aU, 0x4cU, 0x58U, 0xcfU, + 0xd0U, 0xefU, 0xaaU, 0xfbU, 0x43U, 0x4dU, 0x33U, 0x85U, + 0x45U, 0xf9U, 0x02U, 0x7fU, 0x50U, 0x3cU, 0x9fU, 0xa8U, + 0x51U, 0xa3U, 0x40U, 0x8fU, 0x92U, 0x9dU, 0x38U, 0xf5U, + 0xbcU, 0xb6U, 0xdaU, 0x21U, 0x10U, 0xffU, 0xf3U, 0xd2U, + 0xcdU, 0x0cU, 0x13U, 0xecU, 0x5fU, 0x97U, 0x44U, 0x17U, + 0xc4U, 0xa7U, 0x7eU, 0x3dU, 0x64U, 0x5dU, 0x19U, 0x73U, + 0x60U, 0x81U, 0x4fU, 0xdcU, 0x22U, 0x2aU, 0x90U, 0x88U, + 0x46U, 0xeeU, 0xb8U, 0x14U, 0xdeU, 0x5eU, 0x0bU, 0xdbU, + 0xe0U, 0x32U, 0x3aU, 0x0aU, 0x49U, 0x06U, 0x24U, 0x5cU, + 0xc2U, 0xd3U, 0xacU, 0x62U, 0x91U, 0x95U, 0xe4U, 0x79U, + 0xe7U, 0xc8U, 0x37U, 0x6dU, 0x8dU, 0xd5U, 0x4eU, 0xa9U, + 0x6cU, 0x56U, 0xf4U, 0xeaU, 0x65U, 0x7aU, 0xaeU, 0x08U, + 0xbaU, 0x78U, 0x25U, 0x2eU, 0x1cU, 0xa6U, 0xb4U, 0xc6U, + 0xe8U, 0xddU, 0x74U, 0x1fU, 0x4bU, 0xbdU, 0x8bU, 0x8aU, + 0x70U, 0x3eU, 0xb5U, 0x66U, 0x48U, 0x03U, 0xf6U, 0x0eU, + 0x61U, 0x35U, 0x57U, 0xb9U, 0x86U, 0xc1U, 0x1dU, 0x9eU, + 0xe1U, 0xf8U, 0x98U, 0x11U, 0x69U, 0xd9U, 0x8eU, 0x94U, + 0x9bU, 0x1eU, 0x87U, 0xe9U, 0xceU, 0x55U, 0x28U, 0xdfU, + 0x8cU, 0xa1U, 0x89U, 0x0dU, 0xbfU, 0xe6U, 0x42U, 0x68U, + 0x41U, 0x99U, 0x2dU, 0x0fU, 0xb0U, 0x54U, 0xbbU, 0x16U +}; +static const u32 rcon[] = { + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ +}; + +/** + * Expand the cipher key into the encryption key schedule. + */ +int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + u32 *rk; + int i = 0; + u32 temp; + + if (!userKey || !key) + return -1; + if (bits != 128 && bits != 192 && bits != 256) + return -2; + + rk = key->rd_key; + + if (bits==128) + key->rounds = 10; + else if (bits==192) + key->rounds = 12; + else + key->rounds = 14; + + rk[0] = GETU32(userKey ); + rk[1] = GETU32(userKey + 4); + rk[2] = GETU32(userKey + 8); + rk[3] = GETU32(userKey + 12); + if (bits == 128) { + while (1) { + temp = rk[3]; + rk[4] = rk[0] ^ + ((u32)Te4[(temp >> 16) & 0xff] << 24) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 16) ^ + ((u32)Te4[(temp ) & 0xff] << 8) ^ + ((u32)Te4[(temp >> 24) ]) ^ + rcon[i]; + rk[5] = rk[1] ^ rk[4]; + rk[6] = rk[2] ^ rk[5]; + rk[7] = rk[3] ^ rk[6]; + if (++i == 10) { + return 0; + } + rk += 4; + } + } + rk[4] = GETU32(userKey + 16); + rk[5] = GETU32(userKey + 20); + if (bits == 192) { + while (1) { + temp = rk[ 5]; + rk[ 6] = rk[ 0] ^ + ((u32)Te4[(temp >> 16) & 0xff] << 24) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 16) ^ + ((u32)Te4[(temp ) & 0xff] << 8) ^ + ((u32)Te4[(temp >> 24) ]) ^ + rcon[i]; + rk[ 7] = rk[ 1] ^ rk[ 6]; + rk[ 8] = rk[ 2] ^ rk[ 7]; + rk[ 9] = rk[ 3] ^ rk[ 8]; + if (++i == 8) { + return 0; + } + rk[10] = rk[ 4] ^ rk[ 9]; + rk[11] = rk[ 5] ^ rk[10]; + rk += 6; + } + } + rk[6] = GETU32(userKey + 24); + rk[7] = GETU32(userKey + 28); + if (bits == 256) { + while (1) { + temp = rk[ 7]; + rk[ 8] = rk[ 0] ^ + ((u32)Te4[(temp >> 16) & 0xff] << 24) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 16) ^ + ((u32)Te4[(temp ) & 0xff] << 8) ^ + ((u32)Te4[(temp >> 24) ]) ^ + rcon[i]; + rk[ 9] = rk[ 1] ^ rk[ 8]; + rk[10] = rk[ 2] ^ rk[ 9]; + rk[11] = rk[ 3] ^ rk[10]; + if (++i == 7) { + return 0; + } + temp = rk[11]; + rk[12] = rk[ 4] ^ + ((u32)Te4[(temp >> 24) ] << 24) ^ + ((u32)Te4[(temp >> 16) & 0xff] << 16) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 8) ^ + ((u32)Te4[(temp ) & 0xff]); + rk[13] = rk[ 5] ^ rk[12]; + rk[14] = rk[ 6] ^ rk[13]; + rk[15] = rk[ 7] ^ rk[14]; + + rk += 8; + } + } + return 0; +} + +/** + * Expand the cipher key into the decryption key schedule. + */ +int private_AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i, j, status; + u32 temp; + + /* first, start with an encryption schedule */ + status = private_AES_set_encrypt_key(userKey, bits, key); + if (status < 0) + return status; + + rk = key->rd_key; + + /* invert the order of the round keys: */ + for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) { + temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp; + temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; + temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; + temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; + } + /* apply the inverse MixColumn transform to all round keys but the first and the last: */ + for (i = 1; i < (key->rounds); i++) { + rk += 4; + for (j = 0; j < 4; j++) { + u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m; + + tp1 = rk[j]; + m = tp1 & 0x80808080; + tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^ + ((m - (m >> 7)) & 0x1b1b1b1b); + m = tp2 & 0x80808080; + tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^ + ((m - (m >> 7)) & 0x1b1b1b1b); + m = tp4 & 0x80808080; + tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^ + ((m - (m >> 7)) & 0x1b1b1b1b); + tp9 = tp8 ^ tp1; + tpb = tp9 ^ tp2; + tpd = tp9 ^ tp4; + tpe = tp8 ^ tp4 ^ tp2; +#if defined(ROTATE) + rk[j] = tpe ^ ROTATE(tpd,16) ^ + ROTATE(tp9,24) ^ ROTATE(tpb,8); +#else + rk[j] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^ + (tp9 >> 8) ^ (tp9 << 24) ^ + (tpb >> 24) ^ (tpb << 8); +#endif + } + } + return 0; +} + +#endif /* AES_ASM */ diff --git a/demo/config.h.in b/demo/config.h.in new file mode 100644 index 0000000..1a5caa4 --- /dev/null +++ b/demo/config.h.in @@ -0,0 +1,3 @@ + +#undef HAVE_DEBUG_SYMBOLS +#undef HAVE_SYMBOLS diff --git a/demo/debuginfo.sh b/demo/debuginfo.sh new file mode 100755 index 0000000..75ff10b --- /dev/null +++ b/demo/debuginfo.sh @@ -0,0 +1,14 @@ +#!/bin/bash + + +usage() { + echo "Usage $1 " >&2 + exit 1 +} + +case $# in + 2);; + *) usage $0;; +esac + +gdb -batch -ex "file $1" -ex "info line $2" diff --git a/demo/disas.sh b/demo/disas.sh new file mode 100755 index 0000000..7d8425e --- /dev/null +++ b/demo/disas.sh @@ -0,0 +1,14 @@ +#!/bin/bash + + +usage() { + echo "Usage $1 " >&2 + exit 1 +} + +case $# in + 2);; + *) usage $0;; +esac + +gdb -batch -ex "file $1" -ex "disassemble $2" diff --git a/demo/rungnupg.sh b/demo/rungnupg.sh new file mode 100755 index 0000000..56c8553 --- /dev/null +++ b/demo/rungnupg.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +while true; do ./gpg-1.4.13 --yes -b echo.c; done diff --git a/docs/doubloon/doubloon.md b/docs/doubloon/doubloon.md new file mode 100644 index 0000000..251b408 --- /dev/null +++ b/docs/doubloon/doubloon.md @@ -0,0 +1,97 @@ +--- +title: Doubloon user guide +author: +- Dallas McNeil +date: 25 April 2020 +--- + +# Introduction + +Doubloon is a a GUI tool for conducting CPU cache side-channel attack. It provides an interface for quickly configuring and conducting attacks and visualisations to assist in attack analysis. Currently Doubloon best supports `Flush+Reload` attacks by using Mastik's `FR-trace` utility. + +# User Interface + +Doubloon is focused around a main window. + +![Main Window](mainWindow.png) + +The toolbar along the top provides the main functionality of the program. + +- Run/Stop: Starts and attack or stops it once it is currently running +- Config: Opens the config window allowing the user to configure an attack +- Load: Load a previously saved configuration with results from file +- Save: Save their configuration and results to a file +- Import: Load results only from a separate file +- Export: Save results only to a file + +The central view provides a graph of the attack results. This presents a line graph with time slots along the X axis and cycles along the Y axis. A set of lines represent the results. + +Right of the graph is the graph properties. This presents some information about the results along with options for changing the graph + +- X limits: The range of values along the X axis of the graph +- Y limits: The range of values along the Y axis of the graph +- Threshold: Number of cycles that should separate memory and cache accesses +- Threshold binary: Shows results as only being either above or below threshold +- Interpolate missing values: Draws a line across missing results +- Set toggle: Choose to display each set of results or not. + +# Attack configuration + +The 'Run' button will start an attack and visualise the results once it is complete. However, an attack needs to be configured first. The 'Config' option next to the 'Run' button will open a new window that allows the attack to be configured. This window can remain open allows a user to quickly edit the attack parameters and immediately run the attack again. + +## General + +This option is for any program. The user simply needs to provide the absolute path to the program or command they wish to run and the arguments for it separated by spaces. Any custom program should stdout a space and newline separated list of times (see 'Import/Export data' section for details). + +## FR-trace + +This option is for with Mastik's FR-trace program. This option is simpler to configure. + +- FR-trace program: Absolute path or command to use Mastik's FR-trace program. Defaults to 'FR-trace' and should be found if installed. +- Monitor locations: Locations to monitor in victim program and will be evicted from cache and measured, seperated by spaces. Example locations are `symbol+64` for byte offset on symbol or `file.c:80` for line number in file (only on linux). +- Evict locations: Locations to evict from cache but not measure. Same format at monitor locations. +- PDA locations: Locations to perform a performance degredation attack on. +- Slot length: Time in cycles to take a sample. +- Max samples: Maximum number of samples to take in attack. +- Threshold: Threshold between memory and cache acceses in cycles. +- Idle count: Number of idle time slots before attack will be ended early. Set to 0 to not stop until maximum samples are taken. +- PDA count: How much to impact each PDA location. + +## Common + +Some parameters are common between all attacks. +- Run victim program: Execute a victim program automatically when the attack is ran. +- Victim program: Specify the victim program or command to be executed. +- Victim arguments: Arguments to be supplied to the victim program + +An attack can be run on a remote computer. This is currently an experimental feature. +- Run remotely (SSH): Execute the attack and victim programs remotely through SSH +- SSH hostname: Remote host to connect to +- SSH port: Port of remote host to connect to +- SSH username: User to connect as +- SSH password: Password of user to connect as (NOTE: password is not saved to disk but is in memory, use at own risk) + +# Graph shortcuts + +The graph can be navigated in a number of ways. +- Click and drag zoom: Click and drag over the graph to select a horizontal region. On release the newly selected area will be zoomed in to. +- Scroll bar: Use the scroll bar along the top to scroll and navigate through the results. +- Arrow keys: Keyboard arrow keys can be used to zoom in and out, and pan the graph selection. +- Properties: The X-limits can always be adjusted in the properties section next to the graph to change the section. + +# Import/Export data + +Doubloon can visualise data from an external source or export results in a general format. This format consists of several lines. Each line has a series of integers separated by spaces. If an integer is 0, the data is assumed to be missing. Each line represents a sample and each column represents a monitored location or set. Data can be imported in this format and will be exported in it. An example of this format looks like this. + +``` +# This is a comment and will be ignored +274 250 53 +271 247 30 +265 250 33 +271 33 30 +0 0 0 +271 56 250 +268 250 235 +271 33 250 +... +``` \ No newline at end of file diff --git a/docs/doubloon/mainWindow.png b/docs/doubloon/mainWindow.png new file mode 100644 index 0000000..ad7acac Binary files /dev/null and b/docs/doubloon/mainWindow.png differ diff --git a/mastik/Makefile.in b/mastik/Makefile.in new file mode 100644 index 0000000..e0d567b --- /dev/null +++ b/mastik/Makefile.in @@ -0,0 +1,32 @@ +HEADERS= \ + cb.h \ + ff.h \ + fr.h \ + l1.h \ + l1i.h \ + l3.h \ + low.h \ + pda.h \ + symbol.h \ + synctrace.h \ + transient.h \ + util.h \ + l2.h \ + mm.h \ + info.h + +prefix=@prefix@ +exec_prefix=@exec_prefix@ + +all: ${HEADERS} + + +install: ${HEADERS} + install -d @includedir@/mastik + install ${HEADERS} @includedir@/mastik + + +clean: + +distclean: clean + rm Makefile diff --git a/mastik/cb.h b/mastik/cb.h new file mode 100644 index 0000000..b2c33b6 --- /dev/null +++ b/mastik/cb.h @@ -0,0 +1,53 @@ +/* + * Copyright 2017 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __CB_H__ +#define __CB_H__ 1 + +#include +#include + + +#define CBT_BANK_CONFLICT 0 +#define CBT_FALSE_DEPENDENCY 1 + + + +typedef struct cb *cb_t; + +cb_t cb_prepare(int type); +void cb_release(cb_t cb); + +int cb_maxoffset(cb_t cb); +int cb_offsetmask(cb_t cb); + +int cb_monitor(cb_t cb, int offset, int accesses); +int cb_getmonitored_offset(cb_t cb); +int cb_getmonitored_accesses(cb_t cb); + +void cb_probe(cb_t cb, uint32_t *results); +void cb_bprobe(cb_t cb, uint32_t *results); + +int cb_repeatedprobe(cb_t cb, int nrecords, uint32_t *results); +uint32_t cb_repeatedproberaw(cb_t cb, int nrecords, uint32_t *results); + + + +#endif // __CB_H__ + diff --git a/mastik/ff.h b/mastik/ff.h new file mode 100644 index 0000000..8cedf1f --- /dev/null +++ b/mastik/ff.h @@ -0,0 +1,165 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __FF_H__ +#define __FF_H__ 1 + + +/* + * Performs the Flush+Flush [1] attack. + * The attack exploits the timing variations in the clflush, which takes + * a longer time to ensure the flushed memory line is evicted from + * all cache levels if the line is cached. + * + * The attack can only target memory addresses that are shared between + * the spy and the victim. Typically, such sharing results from mmaping + * a binary the victim use. For cross-VM attacks, the hypervisor + * must support page deduplication. The most common attack target is + * shared code. + * + * The spatial resolution of the attack is one cache line (64 bytes). The + * attack is likely to be unaffected by cache optimisations such as + * the Spatial Prefetcher that pair consecutive cache lines and any streamers + * that try to identify access patterns to the cache. + * + * False positives are relatively common. + * + * The attack is sensitive to migration between processor cores. clflush timing + * depends on both the core the instruction executes on and the cache slice + * the data is in. No single threshold is useful for distinguishin results on + * all combinations of cores and slices. It is recommended to control the spy + * placement using taskset(1) or the supplied setaffinity. (See util.h.) + * + * [1] D. Gruss, C. Maurice, K. Wagner, and S. Mangard, "Flush+Flush: + * A Fast and Stealthy Cahce Attack", DIMVA 2016 + */ + + +/* + * An opaque reference to an attack instance + */ +typedef struct ff *ff_t; + + + +/* + * Creates and initialises an attack instance + */ +ff_t ff_prepare(); + + +/* + * Disposes of all resources acquired for an attack instance + */ +void ff_release(ff_t ff); + + +/* + * Adds a memory address to the list of addresses monitored by + * an attack instance + */ +int ff_monitor(ff_t ff, void *adrs); + + +/* + * Removes a memory address from the list of addresses monitored + * by an attack instance. + */ +int ff_unmonitor(ff_t ff, void *adrs); + + +/* + * Retrieve the list of addresses monitored by an attack instance. Parameters: + * ff - Attack instance + * adrss - A buffer for storing the list. Set to NULL to retrieve the number + * of monitored addresses. + * nlines - Buffer size + * Returns the number of addresses monitored. + */ +int ff_getmonitoredset(ff_t ff, void **adrss, int nlines); + + +/* + * Calculate the thresholds between flushing a cached and a non-cached line. + * ff_trace (see below) usually keeps track of the thresholds, but + * explicit calculation is required when the spy migrates between cores or + * to avoid delays when calling ff_trace. + */ +void ff_setthresholds(ff_t ff); + + +/* + * Returns the threshold for a monitored address. + * 0 - threshold not calculates + * -1 - index out of bounds. + */ +int ff_getthreshold(ff_t ff, int index); + +/* + * Not currently implemented + */ +void ff_randomise(ff_t ff); + + + + + +/* + * Performs a single probe round on each of the monitored addresses. + * results points to a buffer for storing the timing to clflush each + * each of the monitored addresses. + * Addresses are stored in the order returned by ff_getmonitoredset. + * This is guaranteed to be the order addresses are added using ff_monitor + * as long as ff_unmonitor is not used. + */ +void ff_probe(ff_t ff, uint16_t *results); + + +/* + * Performs repeated calls to ff_probe. Prameters are: + * ff - The ff descriptor + * max_records - The number of records to collect + * results - An array for results of size ff_len(ff) * max_records + * slot - The length of a time-slot in cycles. Use 0 to have flexible slot size + * threshold - True if should calculate activity thresholds and use them. + * max_idle - Stop capture when read more than max_idle idle records. + * + * If threshold is set, capture record starts when a probe is active, i.e. + * above its threshold. Otherwise capture starts immediately. + * Capture stops when either max_idle records with no active address or when max_records + * are captured. max_idle is ignored if =0. + * + * Output is the reload times for each of the monitored addresses in each time slot. + * Missed slots are indicted using time 0. + * The return value is the number of records captured. + */ +int ff_trace(ff_t ff, int max_records, uint16_t *results, int slot, int threshold, int max_idle); + + +/* + * Repeat ff_probe max_record times. Equivalent to: + * ff_trace(ff, max_records, results, slot, 0, max_records); + */ +int ff_repeatedprobe(ff_t ff, int max_records, uint16_t *results, int slot); + + +int ff_fastrepeatedprobe(ff_t ff, int max_records, uint16_t *results); + +#endif // __FF_H__ + diff --git a/mastik/fr.h b/mastik/fr.h new file mode 100644 index 0000000..9b69d13 --- /dev/null +++ b/mastik/fr.h @@ -0,0 +1,70 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __FR_H__ +#define __FR_H__ 1 + +typedef struct fr *fr_t; + + + +fr_t fr_prepare(); +void fr_release(fr_t fr); + +int fr_monitor(fr_t fr, void *adrs); +int fr_unmonitor(fr_t fr, void *adrs); +int fr_getmonitoredset(fr_t fr, void **adrss, int nlines); +void fr_randomise(fr_t fr); + +int fr_evict(fr_t fr, void *adrs); +int fr_unevict(fr_t fr, void *adrs); +int fr_getevictedset(fr_t fr, void **adrss, int nlines); + +int fr_probethreshold(void); + + +void fr_probe(fr_t fr, uint16_t *results); + + +/* + * Performs repeated calls to fr_probe. Prameters are: + * fr - The fr descriptor + * max_records - The number of records to collect + * results - An array for results of size fr_len(fr) * max_records + * slot - The length of a time-slot in cycles. Use 0 to have flexible slot size + * threshold - Activity threshold. If >0, capture starts when one of the results is above the threshold + * max_idle - Stop capture when read more than max_idle idle records. + * + * Capture record starts when a probe is above the threshold. Hence threshold=0 means that capture + * starts immediately. + * Capture stops when either max_idle records have no value above the threshold or when max_records + * are captured. max_idle is ignored if =0. + * + * Output is the reload times for each of the monitored addresses in each time slot. + * Missed slots are indicted using time 0. + * The return value is the number of records captured. + */ +int fr_trace(fr_t fr, int max_records, uint16_t *results, int slot, int threshold, int max_idle); + +int fr_repeatedprobe(fr_t fr, int max_records, uint16_t *results, int slot); + + + +#endif // __FR_H__ + diff --git a/mastik/impl.h b/mastik/impl.h new file mode 100644 index 0000000..6b5680f --- /dev/null +++ b/mastik/impl.h @@ -0,0 +1,78 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef _IMPL_H +#define _IMPL_H + +#include +#include + +#include "lx.h" + +#define LNEXT(t) (*(void **)(t)) +#define OFFSET(p, o) ((void *)((uintptr_t)(p) + (o))) +#define NEXTPTR(p) (OFFSET((p), sizeof(void *))) + +#define IS_MONITORED(monitored, setno) ((monitored)[(setno)>>5] & (1 << ((setno)&0x1f))) +#define SET_MONITORED(monitored, setno) ((monitored)[(setno)>>5] |= (1 << ((setno)&0x1f))) +#define UNSET_MONITORED(monitored, setno) ((monitored)[(setno)>>5] &= ~(1 << ((setno)&0x1f))) + +#define LXFLAG_NOHUGEPAGES 0x01 +#define LXFLAG_USEPTE 0x02 +#define LXFLAG_NOPROBE 0x04 +#define LXFLAG_QUADRATICMAP 0x08 // Defaults to this if huge pages is specified +#define LXFLAG_LINEARMAP 0x10 // Defaults to this if small pages is specified + +#define LX_CACHELINE 0x40 + +int probetime(void *pp); +int bprobetime(void *pp); + +void lx_probe(lxpp_t lx, uint16_t *results); +void lx_bprobe(lxpp_t lx, uint16_t *results); +void lx_probecount(lxpp_t lx, uint16_t *results); +void lx_bprobecount(lxpp_t lx, uint16_t *results); + +int lx_repeatedprobe(lxpp_t lx, int nrecords, uint16_t *results, int slot); +int lx_repeatedprobecount(lxpp_t lx, int nrecords, uint16_t *results, int slot); + +void lx_randomise(lxpp_t lx); +int lx_getmonitoredset(lxpp_t lx, int *lines, int nlines); + +int lx_monitor(lxpp_t lx, int line); +void lx_monitorall(lxpp_t lx); + +int lx_unmonitor(lxpp_t lx, int line); +void lx_unmonitorall(lxpp_t lx); + +void * lx_sethead(lxpp_t lx, int set); + +int lx_getlxinfo(lxpp_t lx, lxinfo_t lxinfo); + +// Type of callback for setup and execute for synchronized PP or ET +typedef void (*lx_sync_cb)(lxpp_t l1, int recnum, void *data); + +// Synchronized Prime+Probe +int lx_syncpp(lxpp_t lx, int nrecords, uint16_t *results, lx_sync_cb setup, lx_sync_cb exec, void *data); + +void lx_dummy_cb(lxpp_t l1, int recnum, void *data); + +void lx_release(lxpp_t lx); + +#endif diff --git a/mastik/info.h b/mastik/info.h new file mode 100644 index 0000000..73d6817 --- /dev/null +++ b/mastik/info.h @@ -0,0 +1,40 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef INFO_H +#define INFO_H + +#include + +typedef void (*lxprogressNotification_t)(int count, int est, void *data); + +struct lxinfo { + int associativity; + int sets; + int bufsize; + int flags; + void *progressNotificationData; + + int slices; + lxprogressNotification_t progressNotification; + union cpuid cpuidInfo; +}; +typedef struct lxinfo *lxinfo_t; + +#endif diff --git a/mastik/l1.h b/mastik/l1.h new file mode 100644 index 0000000..334666d --- /dev/null +++ b/mastik/l1.h @@ -0,0 +1,80 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __L1_H__ +#define __L1_H__ 1 + +#define L1_SETS 64 + +#include +#include + +typedef void (*l1progressNotification_t)(int count, int est, void *data); + +struct l1info { + int associativity; + int sets; + int bufsize; + int flags; + void *progressNotificationData; + + // padding variables + int slices; + l1progressNotification_t progressNotification; + union cpuid cpuidInfo; +}; + +#define L1_ASSOCIATIVITY 8 +#define L1_CACHELINE 64 +#define L1_STRIDE (L1_CACHELINE * L1_SETS) + +typedef struct l1pp *l1pp_t; +typedef struct l1info *l1info_t; + +l1pp_t l1_prepare(mm_t mm); +void l1_release(l1pp_t l1); + +int l1_monitor(l1pp_t l1, int line); +int l1_unmonitor(l1pp_t l1, int line); +void l1_monitorall(l1pp_t l1); +void l1_unmonitorall(l1pp_t l1); +int l1_getmonitoredset(l1pp_t l1, int *lines, int nlines); +void l1_randomise(l1pp_t l1); + +void l1_probe(l1pp_t l1, uint16_t *results); +void l1_bprobe(l1pp_t l1, uint16_t *results); + +// Slot is currently not implemented +int l1_repeatedprobe(l1pp_t l1, int nrecords, uint16_t *results, int slot); + + + +// Type of callback for setup and execute for synchronized PP or ET +typedef void (*l1_sync_cb)(l1pp_t l1, int recnum, void *data); + +// Synchronized Prime+Probe +int l1_syncpp(l1pp_t l1, int nrecords, uint16_t *results, lx_sync_cb setup, lx_sync_cb exec, void *data); +// Synchronized Evict+Time +int l1_syncet(l1pp_t l1, int nrecords, uint16_t *results, l1_sync_cb setup, l1_sync_cb exec, void *data); + +void fillL1Info(l1info_t l1info); + + +#endif // __L1_H__ + diff --git a/mastik/l1i.h b/mastik/l1i.h new file mode 100644 index 0000000..ef7373e --- /dev/null +++ b/mastik/l1i.h @@ -0,0 +1,45 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __L1I_H__ +#define __L1I_H__ 1 + +#define L1I_SETS 64 + +typedef struct l1ipp *l1ipp_t; + +l1ipp_t l1i_prepare(); +void l1i_release(l1ipp_t l1i); + +int l1i_monitor(l1ipp_t l1i, int line); +int l1i_unmonitor(l1ipp_t l1i, int line); +void l1i_monitorall(l1ipp_t l1i); +void l1i_unmonitorall(l1ipp_t l1i); +int l1i_getmonitoredset(l1ipp_t l1i, int *lines, int nlines); +void l1i_randomise(l1ipp_t l1); + +void l1i_probe(l1ipp_t l1, uint16_t *results); + +// Slot is currently not implemented +int l1i_repeatedprobe(l1ipp_t l1, int nrecords, uint16_t *results, int slot); + + + +#endif // __L1I_H__ + diff --git a/mastik/l2.h b/mastik/l2.h new file mode 100644 index 0000000..15126d8 --- /dev/null +++ b/mastik/l2.h @@ -0,0 +1,71 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __L2 +#define __L2 + +#include +#include "impl.h" + +#include "mm.h" + +typedef struct l2pp *l2pp_t; +typedef struct l2info *l2info_t; + +#define L2_SETS 1024 + +#define L2_CACHELINE 64 + +// The number of cache sets in each page +#define L2_SETS_PER_PAGE 64 + +typedef void (*l2progressNotification_t)(int count, int est, void *data); + +struct l2info { + int associativity; + int sets; + int bufsize; + int flags; + void *progressNotificationData; + + // padding variables + int slices; + l2progressNotification_t progressNotification; + union cpuid cpuidInfo; +}; + +l2pp_t l2_prepare(l2info_t l2info, mm_t mm); +int l2_monitor(l2pp_t l2, int line); +int l2_getmonitoredset(l2pp_t l2, int *lines, int nlines); +int l2_unmonitor(l2pp_t l2, int line); +void l2_monitorall(l2pp_t l2); +void l2_unmonitorall(l2pp_t l2); +void l2_probe(l2pp_t l2, uint16_t *results); +void l2_bprobe(l2pp_t l2, uint16_t *results); +int l2_getmonitoredset(l2pp_t l2, int *lines, int nlines); +void l2_release(l2pp_t l2); +int l2_repeatedprobe(l2pp_t l2, int nrecords, uint16_t *results, int slot); +int l2_getl2info(l2pp_t l2, l2info_t l2info); +int l2_syncpp(l2pp_t l2, int nrecords, uint16_t *results, lx_sync_cb setup, lx_sync_cb exec, void *data); +void l2_randomise(l2pp_t l2); + +int loadL2cpuidInfo(l2info_t l2info); +void fillL2Info(l2info_t l2info); + +#endif diff --git a/mastik/l3.h b/mastik/l3.h new file mode 100644 index 0000000..b67fa8b --- /dev/null +++ b/mastik/l3.h @@ -0,0 +1,85 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __L3_H__ +#define __L3_H__ 1 + +#include +#include + +typedef void (*l3progressNotification_t)(int count, int est, void *data); +struct l3info { + int associativity; + int setsperslice; + int bufsize; + int flags; + void *progressNotificationData; + int slices; + l3progressNotification_t progressNotification; + union cpuid cpuidInfo; +}; + +typedef struct l3pp *l3pp_t; +typedef struct l3info *l3info_t; + + +#define L3FLAG_NOHUGEPAGES 0x01 +#define L3FLAG_USEPTE 0x02 +#define L3FLAG_NOPROBE 0x04 +#define L3FLAG_QUADRATICMAP 0x08 // Defaults to this if huge pages is specified +#define L3FLAG_LINEARMAP 0x10 // Defaults to this if small pages is specified + + +l3pp_t l3_prepare(l3info_t l3info, mm_t mm); +void l3_release(l3pp_t l3); + +// Returns the number of probed sets in the LLC +int l3_getSets(l3pp_t l3); + +// Returns the number slices +int l3_getSlices(l3pp_t l3); + +// Returns the LLC associativity +int l3_getAssociativity(l3pp_t l3); + +int l3_monitor(l3pp_t l3, int line); +void l3_unmonitorall(l3pp_t l3); +int l3_unmonitor(l3pp_t l3, int line); +int l3_getmonitoredset(l3pp_t l3, int *lines, int nlines); + +void l3_randomise(l3pp_t l3); + +void l3_probe(l3pp_t l3, uint16_t *results); +void l3_bprobe(l3pp_t l3, uint16_t *results); +void l3_probecount(l3pp_t l3, uint16_t *results); +void l3_bprobecount(l3pp_t l3, uint16_t *results); + +int l3_repeatedprobe(l3pp_t l3, int nrecords, uint16_t *results, int slot); +int l3_repeatedprobecount(l3pp_t l3, int nrecords, uint16_t *results, int slot); + +// Prime+Abort +void l3_pa_prime(l3pp_t l3); +int l3_pabort(l3pp_t l3, uint32_t time_limit); +void l3_repeatedpabort(l3pp_t l3, int sample, int16_t *results, uint32_t time_limit); + +int loadL3cpuidInfo(l3info_t l3info); +void fillL3Info(l3info_t l3info); + +#endif // __L3_H__ + diff --git a/mastik/low.h b/mastik/low.h new file mode 100644 index 0000000..d936cba --- /dev/null +++ b/mastik/low.h @@ -0,0 +1,147 @@ +/* + * Copyright 2016,2020 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __LOW_H__ +#define __LOW_H__ + + +#define L2_THRESHOLD 110 +#define L3_THRESHOLD 140 + +#ifdef PAGE_SIZE +#undef PAGE_SIZE +#endif +#define PAGE_SIZE 4096 + + +static inline int memaccess(void *v) { + int rv; + asm volatile("mov (%1), %0": "+r" (rv): "r" (v):); + return rv; +} + +static inline uint32_t memaccesstime(void *v) { + uint32_t rv; + asm volatile ( + "mfence\n" + "lfence\n" + "rdtscp\n" + "mov %%eax, %%esi\n" + "mov (%1), %%eax\n" + "rdtscp\n" + "sub %%esi, %%eax\n" + : "=&a" (rv): "r" (v): "ecx", "edx", "esi"); + return rv; +} + +static inline void clflush(void *v) { + asm volatile ("clflush 0(%0)": : "r" (v):); +} + +static inline uint32_t rdtscp() { + uint32_t rv; + asm volatile ("rdtscp": "=a" (rv) :: "edx", "ecx"); + return rv; +} + +static inline uint64_t rdtscp64() { + uint32_t low, high; + asm volatile ("rdtscp": "=a" (low), "=d" (high) :: "ecx"); + return (((uint64_t)high) << 32) | low; +} + +static inline void mfence() { + asm volatile("mfence"); +} + +static inline void lfence() { + asm volatile("lfence"); +} + +static inline void walk(void *p, int count) { + if (p == NULL) + return; + asm volatile( + "movq %0, %%rsi\n" + "1:\n" + "movq (%0), %0\n" + "cmpq %0, %%rsi\n" + "jnz 1b\n" + "decl %1\n" + "jnz 1b\n" + : "+r" (p), "+r" (count)::"rsi"); +} + + +struct cpuidRegs { + uint32_t eax; + uint32_t ebx; + uint32_t ecx; + uint32_t edx; +}; + +#define CPUID_CACHEINFO 4 + + +#define CACHETYPE_NULL 0 +#define CACHETYPE_DATA 1 +#define CACHETYPE_INSTRUCTION 2 +#define CACHETYPE_UNIFIED 3 + +struct cpuidCacheInfo { + uint32_t type:5; + uint32_t level:3; + uint32_t selfInitializing:1; + uint32_t fullyAssociative:1; + uint32_t reserved1:4; + uint32_t logIds:12; + uint32_t phyIds:6; + + uint32_t lineSize:12; + uint32_t partitions:10; + uint32_t associativity:10; + + uint32_t sets:32; + + uint32_t wbinvd:1; + uint32_t inclusive:1; + uint32_t complexIndex:1; + uint32_t reserved2:29; +}; + +union cpuid { + struct cpuidRegs regs; + struct cpuidCacheInfo cacheInfo; +}; + +inline void cpuid(union cpuid *c) { + asm volatile ("cpuid": "+a" (c->regs.eax), "+b" (c->regs.ebx), "+c" (c->regs.ecx), "+d" (c->regs.edx)); +} + +static inline int slotwait(uint64_t slotend) { + if (rdtscp64() > slotend) + return 1; + while (rdtscp64() < slotend) + ; + return 0; +} + + + +#endif //__LOW_H__ diff --git a/mastik/lx.h b/mastik/lx.h new file mode 100644 index 0000000..36a15d4 --- /dev/null +++ b/mastik/lx.h @@ -0,0 +1,54 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef _LX_H +#define _LX_H + +#include + +#include "mastik/low.h" +#include "../src/vlist.h" +#include +#include + +struct lxpp { + void **monitoredhead; + int nmonitored; + + int *monitoredset; + + uint32_t *monitoredbitmap; + + int level; + size_t totalsets; + + int ngroups; + int groupsize; + vlist_t *groups; + + struct lxinfo lxinfo; + + mm_t mm; + uint8_t internalmm; +}; + +typedef struct lxpp *lxpp_t; + + +#endif diff --git a/mastik/mm.h b/mastik/mm.h new file mode 100644 index 0000000..72af310 --- /dev/null +++ b/mastik/mm.h @@ -0,0 +1,52 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef MM_H +#define MM_H +#include +#include + +enum pagetype { + PAGETYPE_SMALL, + PAGETYPE_HUGE +}; +typedef enum pagetype pagetype_e; + +enum cachelevel { + L1, + L2, + L3 +}; +typedef enum cachelevel cachelevel_e; + + +typedef struct mm* mm_t; + +mm_t mm_prepare(lxinfo_t l1info, lxinfo_t l2info, lxinfo_t l3info); + +void* mm_requestline(mm_t mm, cachelevel_e cachelevel, int line); + +void mm_returnline(mm_t mm, void* line); + +void mm_release(mm_t mm); + +int mm_initialisel3(mm_t mm); + + +#endif diff --git a/mastik/pda.h b/mastik/pda.h new file mode 100644 index 0000000..4de90b5 --- /dev/null +++ b/mastik/pda.h @@ -0,0 +1,98 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __PDA_H__ +#define __PDA_H__ 1 + + +/* + * Perfoms a performance degradation attack. + * See: * T. Allan, B.B. Brumley, K. Falkner, J. van de Pol and + * Y. Yarom, "Amplifying Side Channels Through Performance Degradation," + * ACSAC 2016 (eprint 2015/1141) + * + * pda_t abstracts over a single attacking thread (currently implemented as + * a child process). Each attack targets a set of addresses which it continuosly + * evicts from the cache. + * To ensure attack effectiveness, the target set cannot be changed while the + * attack is active. Any changes to the target set becomes effective in the + * activation following the change. + */ + +typedef struct pda *pda_t; + + + +/* + * Prepares a new instance of a performance degradation attack + */ +pda_t pda_prepare(); + + +/* + * Releases all resources associated with a performace degradation attack + */ +void pda_release(pda_t pda); + +/* + * Adds an address to be targeted in a performance degradation attack + * The address will be targeted from the next activation of the attack. + * Does not affect an active attack. + */ +int pda_target(pda_t pda, void *adrs); + +/* + * Removes an address from a performance degradation attack + * The address will be removed from the next activation of the attack. + * Does not affect an active attack. + */ +int pda_untarget(pda_t pda, void *adrs); + +/* + * Returns the list of addresses to be targeted in the next activation of the attack. + */ +int pda_gettargetset(pda_t pda, void **adrss, int nlines); + +/* + * Randomises the order of accessing targeted addresses in the attack. Effective + * starting the next activation. + */ +void pda_randomise(pda_t pda); + +/* + * Activates a performance degradation attack + * + * If executed on an active attack, the attack may be stopped and restarted to accommodate + * any changes to the target set. + */ +void pda_activate(pda_t pda); + +/* + * Deactivates a performance degradation attack. + */ +void pda_deactivate(pda_t pda); + +/* + * Returns true if the attack is currently active. + */ +int pda_isactive(pda_t pda); + + +#endif // __PDA_H__ + diff --git a/mastik/symbol.h b/mastik/symbol.h new file mode 100644 index 0000000..d1d44bd --- /dev/null +++ b/mastik/symbol.h @@ -0,0 +1,29 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __SYMBOL_H__ +#define __SYMBOL_H__ 1 + +uint64_t sym_getsymboloffset(const char *file, const char *symbol); + +uint64_t sym_loadersymboloffset(const char *file, const char *symbol); +uint64_t sym_debuglineoffset(const char *file, const char *src, int lineno); +uint64_t sym_addresstooffset(const char *file, uint64_t address); + +#endif // __SYMBOL_H__ diff --git a/mastik/synctrace.h b/mastik/synctrace.h new file mode 100644 index 0000000..c6f8ddd --- /dev/null +++ b/mastik/synctrace.h @@ -0,0 +1,81 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __SYNCTRACE_H__ +#define __SYNCTRACE_H__ 1 + +#include "l1.h" +#include "l2.h" + +#include + +// Type of callback for setup +typedef void (*st_setup_cb)(int recnum, void *data); +// Type of callback for exec +typedef void (*st_exec_cb)(int recnum, void *data); +// Type of callback for results processing +typedef void (*st_process_cb)(int recnum, void *data, int nres, uint16_t results[]); + +// Synchronized Prime+Probe +int st_lpp(lxpp_t lx, int nrecords, st_setup_cb setup, st_exec_cb exec, st_process_cb process, void *data); + +// Synchronized Evict+Time +int st_l1et(l1pp_t l1, int nrecords, st_setup_cb setup, st_exec_cb exec, st_process_cb process, void *data); + + +// Crypto specific functions +// +#define ST_BLOCKBITS 512 +#define ST_BLOCKBYTES (ST_BLOCKBITS>>3) +#define ST_TRACEWIDTH L2_SETS + +typedef void (*st_crypto_f)(uint8_t input[], uint8_t output[], void *cryptoData); + +struct st_clusters { + int count[256]; + int64_t avg[256][ST_TRACEWIDTH]; + int64_t var[256][ST_TRACEWIDTH]; +}; + +typedef struct st_clusters *st_clusters_t; + +st_clusters_t syncPrimeProbe(int nsamples, + int blocksize, + int splitinput, + uint8_t *fixMask, + uint8_t *fixData, + st_crypto_f crypto, + void *cryptoData, + uint8_t clusterMask, + int cachelevel); + +/* +st_clusters_t syncEvictTime(int nsamples, + int blocksize, + uint8_t *fixMask, + uint8_t *fixData, + st_crypto_f crypto, + void *cryptoData, + uint8_t clusterMask); +*/ + + +#endif // __SYNCTRACE_H__ + + diff --git a/mastik/transient.h b/mastik/transient.h new file mode 100644 index 0000000..628a5f6 --- /dev/null +++ b/mastik/transient.h @@ -0,0 +1,87 @@ +/* + * Copyright 2020 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ +#ifndef __TRANSIENT_H__ +#define __TRANSIENT_H__ 1 + +#include +#include + +#ifndef MASTIK_FRCC_THRESHOLD +#define MASTIK_FRCC_THRESHOLD 100 +#endif + +#ifndef MASTIK_FRCC_STEP +#define MASTIK_FRCC_STEP 4096 +#endif + +#ifndef MASTIK_FRCC_LEN +#define MASTIK_FRCC_LEN 256 +#endif + +#ifndef MASTIK_FRCC_SKIP +#define MASTIK_FRCC_SKIP 171 +#endif + +// Flush+Reload Covert Channel +typedef void *frcc_t; + + +static inline frcc_t frcc_new() { + return calloc(MASTIK_FRCC_LEN * MASTIK_FRCC_STEP, 1); +} + +static inline void frcc_delete(frcc_t frcc) { + free(frcc); +} + +static inline void frcc_send(frcc_t frcc, int ind) { + memaccess((char *)frcc + ind * MASTIK_FRCC_STEP); +} + +static inline void frcc_prepare(frcc_t frcc) { + for (int i = 0; i < MASTIK_FRCC_LEN; i++) { + clflush((char *)frcc + i*MASTIK_FRCC_STEP); + } +} + +static inline void frcc_recv(frcc_t frcc, int *data) { + for (int i = 0; i < MASTIK_FRCC_LEN; i++) { + int ind = (i * MASTIK_FRCC_SKIP)%MASTIK_FRCC_LEN; + if (memaccesstime(frcc + ind * MASTIK_FRCC_STEP) < MASTIK_FRCC_THRESHOLD) + data[ind]++; + } +} + +static inline int frcc_recv1(frcc_t frcc) { + int min = memaccesstime(frcc); + int minind = 0; + for (int i = 1; i < MASTIK_FRCC_LEN; i++) { + int ind = (i * MASTIK_FRCC_SKIP)%MASTIK_FRCC_LEN; + int atime = memaccesstime(frcc + ind * MASTIK_FRCC_STEP); + if (atime < min) { + min = atime; + minind = ind; + } + } + if (min < MASTIK_FRCC_THRESHOLD) + return minind; + return -1; +} + +#endif // __TRANSIENT_H__ diff --git a/mastik/util.h b/mastik/util.h new file mode 100644 index 0000000..389c45d --- /dev/null +++ b/mastik/util.h @@ -0,0 +1,34 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __UTIL_H__ +#define __UTIL_H__ 1 + +const char *mastik_version(); + +void *map_offset(const char *file, uint64_t offset); +void unmap_offset(void *address); + +void delayloop(uint32_t cycles); + +void setaffinity(int cpu); + +int ncpus(void); + +#endif // __UTIL_H__ diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..846a2a6 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1 @@ +LocalMakefile diff --git a/src/Makefile.in b/src/Makefile.in new file mode 100644 index 0000000..12574d9 --- /dev/null +++ b/src/Makefile.in @@ -0,0 +1,73 @@ +LIB=libmastik.a +LIBSRCS= \ + cb.c \ + ff.c \ + fr.c \ + l1.c \ + l1i.c \ + l3.c \ + pda.c \ + util.c \ + symbol.c \ + synctrace.c \ + timestats.c \ + vlist.c \ + l2.c \ + impl.c \ + mm.c \ + @SYMBOL_SRCS@ + +prefix=@prefix@ +exec_prefix=@exec_prefix@ + +LIBOBJS=${LIBSRCS:.c=.o} +VERSION=$(shell cut -f 1 -d \ ../VERSION) + +all: ${LIB} ${TARGETS} + + +include LocalMakefile +CFLAGS=@CFLAGS@ -I.. -DNDEBUG ${EXTRA_CFLAGS} + +${LIB}:${LIBOBJS} + ar crv ${LIB} ${LIBOBJS} + ranlib ${LIB} + +install: ${LIB} + install -d @libdir@ + install ${LIB} @libdir@ + +l3.o: ../mastik/l3.h vlist.h timestats.h ../mastik/low.h config.h ../mastik/mm.h mm-impl.h + +l2.o: ../mastik/l2.h vlist.h timestats.h ../mastik/low.h config.h ../mastik/mm.h mm-impl.h + +mm.o: vlist.h ../mastik/low.h config.h ../mastik/mm.h mm-impl.h + +vlist.o: vlist.h config.h + +timestats.o: timestats.h config.h + + +#pp.o: vlist.h pp.h low.h + +l1.o: ../mastik/l1.h ../mastik/low.h config.h ../mastik/mm.h mm-impl.h + +l1i.o: ../mastik/l1i.h ../mastik/low.h config.h + +ff.o: ../mastik/ff.h ../mastik/low.h vlist.h timestats.h config.h + +fr.o: ../mastik/fr.h ../mastik/low.h vlist.h config.h + +pda.o: ../mastik/pda.h ../mastik/low.h vlist.h config.h + + +symbol.o: ../mastik/symbol.h ../mastik/util.h config.h + +LocalMakefile: + touch LocalMakefile + +clean: + rm -f ${LIB} ${LIBOBJS} + +distclean: clean + rm Makefile config.h diff --git a/src/cb.c b/src/cb.c new file mode 100644 index 0000000..4347471 --- /dev/null +++ b/src/cb.c @@ -0,0 +1,328 @@ +/* + * Copyright 2017 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include + +#include +#include + + +#define CBT_BANK_COLLISION 0 +#define CBT_FALSE_DEPENDENCY 1 + +#define CB_CODESIZE (4*4096) +#define CB_BUFSIZE (16*4096) + +static uint8_t cb_prefix[] = { + 0x49, 0x89, 0xd3, // mov %rdx,%r11 +}; + +static uint8_t cb_prefix_bc[] = { + 0x49, 0x89, 0xd3, // mov %rdx,%r11 +}; + + +static uint8_t cb_loopstart[] = { + 0x0f, 0x01, 0xf9, // rdtscp + 0x41, 0x89, 0x03, // mov %eax,(%r11) + 0x4d, 0x8d, 0x5b, 0x04 // lea 0x4(%r11),%r11 +}; + +static uint8_t cb_suffix[] = { + 0xff, 0xce, // dec %esi + 0x0f, 0x85, 0x74, 0xff, 0xff, 0xff, // jne + 0x0f, 0x01, 0xf9, // rdtscp + 0xc3 // retq +}; + +#define MAX_COMMAND_LEN 8 +struct cb_command { + int len; + uint8_t command[MAX_COMMAND_LEN]; +}; + +static struct cb_command cb_bank_conflict_commands[] = { + 6, { 0x03, 0x87, 0x00, 0x00, 0x00, 0x00}, // add 0x0000(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x00, 0x00, 0x00}, // add 0x0040(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x00, 0x00, 0x00}, // add 0x0080(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x00, 0x00, 0x00}, // add 0x00c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x01, 0x00, 0x00}, // add 0x0100(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x01, 0x00, 0x00}, // add 0x0140(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x01, 0x00, 0x00}, // add 0x0180(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x01, 0x00, 0x00}, // add 0x01c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x02, 0x00, 0x00}, // add 0x0200(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x02, 0x00, 0x00}, // add 0x0240(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x02, 0x00, 0x00}, // add 0x0280(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x02, 0x00, 0x00}, // add 0x02c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x03, 0x00, 0x00}, // add 0x0300(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x03, 0x00, 0x00}, // add 0x0340(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x03, 0x00, 0x00}, // add 0x0380(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x03, 0x00, 0x00}, // add 0x03c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x04, 0x00, 0x00}, // add 0x0400(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x04, 0x00, 0x00}, // add 0x0440(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x04, 0x00, 0x00}, // add 0x0480(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x04, 0x00, 0x00}, // add 0x04c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x05, 0x00, 0x00}, // add 0x0500(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x05, 0x00, 0x00}, // add 0x0540(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x05, 0x00, 0x00}, // add 0x0580(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x05, 0x00, 0x00}, // add 0x05c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x06, 0x00, 0x00}, // add 0x0600(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x06, 0x00, 0x00}, // add 0x0640(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x06, 0x00, 0x00}, // add 0x0680(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x06, 0x00, 0x00}, // add 0x06c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x07, 0x00, 0x00}, // add 0x0700(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x07, 0x00, 0x00}, // add 0x0740(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x07, 0x00, 0x00}, // add 0x0700(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x07, 0x00, 0x00}, // add 0x07c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x08, 0x00, 0x00}, // add 0x0800(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x08, 0x00, 0x00}, // add 0x0840(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x08, 0x00, 0x00}, // add 0x0880(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x08, 0x00, 0x00}, // add 0x08c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x09, 0x00, 0x00}, // add 0x0900(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x09, 0x00, 0x00}, // add 0x0940(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x09, 0x00, 0x00}, // add 0x0980(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x09, 0x00, 0x00}, // add 0x09c0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x0a, 0x00, 0x00}, // add 0x0a00(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x0a, 0x00, 0x00}, // add 0x0a40(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x0a, 0x00, 0x00}, // add 0x0a80(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x0a, 0x00, 0x00}, // add 0x0ac0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x0b, 0x00, 0x00}, // add 0x0b00(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x0b, 0x00, 0x00}, // add 0x0b40(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x0b, 0x00, 0x00}, // add 0x0b80(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x0b, 0x00, 0x00}, // add 0x0bc0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x0c, 0x00, 0x00}, // add 0x0c00(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x0c, 0x00, 0x00}, // add 0x0c40(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x0c, 0x00, 0x00}, // add 0x0c80(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x0c, 0x00, 0x00}, // add 0x0cc0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x0d, 0x00, 0x00}, // add 0x0d00(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x0d, 0x00, 0x00}, // add 0x0d40(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x0d, 0x00, 0x00}, // add 0x0d80(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x0d, 0x00, 0x00}, // add 0x0dc0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x0e, 0x00, 0x00}, // add 0x0e00(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x0e, 0x00, 0x00}, // add 0x0e40(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x0e, 0x00, 0x00}, // add 0x0e80(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x0e, 0x00, 0x00}, // add 0x0ec0(%rdi), %esi + + 6, { 0x03, 0x87, 0x00, 0x0f, 0x00, 0x00}, // add 0x0f00(%rdi), %eax + 6, { 0x03, 0x8f, 0x40, 0x0f, 0x00, 0x00}, // add 0x0f40(%rdi), %ecx + 6, { 0x03, 0x97, 0x80, 0x0f, 0x00, 0x00}, // add 0x0f00(%rdi), %edx + 6, { 0x03, 0xb7, 0xc0, 0x0f, 0x00, 0x00}, // add 0x0fc0(%rdi), %esi +}; + +static struct cb_command cb_false_dependency_commands[] = { + 6, { 0x01, 0x87, 0x00, 0x00, 0x00, 0x00}, // add %eax, 0x0000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x10, 0x00, 0x00}, // add %eax, 0x1000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x20, 0x00, 0x00}, // add %eax, 0x2000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x30, 0x00, 0x00}, // add %eax, 0x3000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x40, 0x00, 0x00}, // add %eax, 0x4000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x50, 0x00, 0x00}, // add %eax, 0x5000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x60, 0x00, 0x00}, // add %eax, 0x6000(%rdi) + 6, { 0x01, 0x87, 0x00, 0x70, 0x00, 0x00} // add %eax, 0x7000(%rdi) + +}; + + +typedef uint32_t (*cb_measure_t)(uintptr_t base /* %rdi */, uint32_t count /* rsi */, uint32_t *results /* rdx */); + +#define ARRAYSIZE(x) x, sizeof(x)/sizeof(x[0]) +struct cbinfo { + int maxoffset; + int offsetmask; + uint8_t *prefix; + int prefix_len; + uint8_t *loopstart; + int loopstart_len; + struct cb_command *commands; + int ncommands; + uint8_t *suffix; + int suffix_len; + int suffix_jmpoffset_start; + int default_accesses; +}; + +static struct cbinfo cbinfo[] = { + { // CBT_BANK_COLLISION + 63, 0x03, + ARRAYSIZE(cb_prefix_bc), + ARRAYSIZE(cb_loopstart), + ARRAYSIZE(cb_bank_conflict_commands), + ARRAYSIZE(cb_suffix), 4, + 256 + }, + { // CBT_FALSE_DEPENDENCY + 4095, 0x03, + ARRAYSIZE(cb_prefix), + ARRAYSIZE(cb_loopstart), + ARRAYSIZE(cb_false_dependency_commands), + ARRAYSIZE(cb_suffix), 4, + 32 + } +}; + +struct cb { + int type; + int offset; + int accesses; + struct cbinfo *cbinfo; + cb_measure_t code; + uintptr_t buffer; +}; + + + +cb_t cb_prepare(int type) { + cb_t cb = (cb_t)malloc(sizeof(struct cb)); + if (cb == NULL) + return NULL; + cb->type = type; + cb->offset = 0; + cb->accesses = 0; + cb->cbinfo = &cbinfo[type]; + void *code = mmap(NULL, CB_CODESIZE, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_ANON|MAP_PRIVATE, -1, 0); + if (code == MAP_FAILED) { + free(cb); + return NULL; + } + cb->code = (cb_measure_t)code; + void *buffer = mmap(NULL, CB_BUFSIZE, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); + if (buffer == MAP_FAILED) { + munmap((void *)cb->code, CB_CODESIZE); + free(cb); + return NULL; + } + cb->buffer = (uintptr_t)buffer; + cb_monitor(cb, 0, 0); + return cb; +} + + +void cb_release(cb_t cb) { + if (cb == NULL) + return; + if (cb->code) + munmap((void *)cb->code, CB_CODESIZE); + if (cb->buffer) + munmap((void *)cb->buffer, CB_BUFSIZE); + free(cb); +} + +int cb_maxoffset(cb_t cb) { + assert(cb != NULL); + return cb->cbinfo->maxoffset; +} + + +int cb_offsetmask(cb_t cb) { + assert(cb != NULL); + return cb->cbinfo->offsetmask; +} + +int cb_monitor(cb_t cb, int offset, int accesses) { + assert(cb != NULL); + struct cbinfo *cbinfo = cb->cbinfo; + + int rv = 0; + cb->offset = offset; + if (accesses == 0) + accesses = cbinfo->default_accesses; + cb->accesses = accesses; + uint8_t *p = (uint8_t *)cb->code; + uint8_t *start = p; + + memcpy(p, cbinfo->prefix, cbinfo->prefix_len); + p += cbinfo->prefix_len; + memcpy(p, cbinfo->loopstart, cbinfo->loopstart_len); + p += cbinfo->loopstart_len; + for (int i = 0; i < accesses; i++) { + struct cb_command *command = &cbinfo->commands[i % cbinfo->ncommands]; + if (p - start + command->len + cbinfo->suffix_len > CB_CODESIZE) { + cb->accesses = i; + rv = -1; + break; + } + memcpy(p, command->command, command->len); + p += command->len; + } + memcpy(p, cbinfo->suffix, cbinfo->suffix_len); + + // Patch jump + start += cbinfo->prefix_len; // Start is now the start of the loop + p += cbinfo->suffix_jmpoffset_start; // p points to the start of the jump offset + int32_t jmpoffset = start - p - sizeof(jmpoffset); // offset is the distance from the jump end to the loop start + memcpy(p, &jmpoffset, sizeof(jmpoffset)); + + + return rv; +} + + + + +int cb_getmonitored_offset(cb_t cb) { + assert(cb != NULL); + return cb->offset; +} + +int cb_getmonitored_accesses(cb_t cb) { + assert(cb != NULL); + return cb->accesses; +} + +void cb_probe(cb_t cb, uint32_t *results) { + cb_repeatedprobe(cb, 1, results); +} + +void cb_bprobe(cb_t cb, uint32_t *results) { + cb_repeatedprobe(cb, 1, results); +} + +int cb_repeatedprobe(cb_t cb, int nrecords, uint32_t *results) { + uint32_t last = cb_repeatedproberaw(cb, nrecords, results); + for (int i = 0; i < nrecords - 1; i++) + results[i] = results[i+1] - results[i]; + results[nrecords-1] = last - results[nrecords-1]; + return 0; +} + + +uint32_t cb_repeatedproberaw(cb_t cb, int nrecords, uint32_t *results) { + return (*cb->code)(cb->buffer + cb->offset, nrecords, results); +} + + diff --git a/src/config.h.in b/src/config.h.in new file mode 100644 index 0000000..b3f3ae8 --- /dev/null +++ b/src/config.h.in @@ -0,0 +1,14 @@ +#undef PACKAGE_VERSION + +#undef HAVE_DWARF +#undef HAVE_LIBDWARF_H +#undef HAVE_LIBDWARF_LIBDWARF_H +#undef HAVE_BFD_H +#undef HAVE_SYS_PRCTL_H +#undef HAVE_SCHED_H +#undef HAVE_MMAP64 +#undef HAVE_LEGACY_BFD + +#undef HAVE_SCHED_SETAFFINITY + +#undef HAVE_SYMBOLS diff --git a/src/ff.c b/src/ff.c new file mode 100644 index 0000000..2be7e08 --- /dev/null +++ b/src/ff.c @@ -0,0 +1,251 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "vlist.h" +#include "timestats.h" + + +#define DEFAULT_THRESHOLD_CAPACITY 16 + +#define THRESHOLD_SAMPLES 1000 + +struct ff { + vlist_t vl; + int modified; + uint16_t *thresholds; + int thresholdcap; +}; + + +static inline void ensurecapacity(ff_t ff) { + if (ff->thresholdcap >= vl_len(ff->vl)) + return; + int newcap = ff->thresholdcap + vl_len(ff->vl); + ff->thresholds = realloc(ff->thresholds, newcap * sizeof(uint16_t)); + bzero(ff->thresholds + ff->thresholdcap, vl_len(ff->vl) * sizeof(uint16_t)); +} + +ff_t ff_prepare() { + ff_t rv = malloc(sizeof(struct ff)); + rv->vl = vl_new(); + rv->modified = 0; + rv->thresholds = calloc(DEFAULT_THRESHOLD_CAPACITY, sizeof(uint16_t)); + rv->thresholdcap = DEFAULT_THRESHOLD_CAPACITY; + return rv; +} + +void ff_release(ff_t ff) { + vl_free(ff->vl); + ff->vl = NULL; + free(ff->thresholds); + ff->thresholds = NULL; + free(ff); +} + + +int ff_monitor(ff_t ff, void *adrs) { + assert(ff != NULL); + assert(adrs != NULL); + if (vl_find(ff->vl, adrs) >= 0) + return 0; + int ind = vl_push(ff->vl, adrs); + if (!ff->modified) { + ensurecapacity(ff); + ff->thresholds[ind] = 0; + } + return 1; +} + + +int ff_unmonitor(ff_t ff, void *adrs) { + assert(ff != NULL); + assert(adrs != NULL); + int i = vl_find(ff->vl, adrs); + if (i < 0) + return 0; + vl_del(ff->vl, i); + ff->modified = 1; + return 1; +} + + +int ff_getmonitoredset(ff_t ff, void **adrss, int nlines) { + assert(ff != NULL); + + if (adrss != NULL) { + int l = vl_len(ff->vl); + if (l > nlines) + l = nlines; + for (int i = 0; i < l; i++) + adrss[i] = vl_get(ff->vl, i); + } + return vl_len(ff->vl); +} + +void ff_randomise(ff_t ff) { + assert(ff != NULL); + assert(0); +} + +static uint16_t inline probeaddr(void *addr) { + uint32_t start = rdtscp(); + mfence(); + clflush(addr); + mfence(); + uint32_t res = rdtscp() - start; + return res > UINT16_MAX ? UINT16_MAX : res; +} + +void ff_probe(ff_t fr, uint16_t *results) { + assert(fr != NULL); + assert(results != NULL); + int l = vl_len(fr->vl); + for (int i = 0; i < l; i++) + results[i] = probeaddr(vl_get(fr->vl, i)); +} + +static void setthresholds(ff_t ff, int force) { + ensurecapacity(ff); + int l = vl_len(ff->vl); + if (ff->modified || force) + bzero(ff->thresholds, l * sizeof(uint16_t)); + ts_t samples = NULL; + for (int i = 0; i < l; i++) { + if (ff->thresholds[i] != 0) + continue; + if (samples == NULL) + samples = ts_alloc(); + ts_clear(samples); + void *addr = vl_get(ff->vl, i); + for (int j = 0; j < THRESHOLD_SAMPLES; j++) { + ts_add(samples, probeaddr(addr)); + delayloop(10000); + } + ff->thresholds[i] = ts_percentile(samples, 99) + 6; + } + if (samples != NULL) + ts_free(samples); + ff->modified = 0; +} + +void ff_setthresholds(ff_t ff) { + setthresholds(ff, 1); +} + +int ff_getthreshold(ff_t ff, int index) { + ensurecapacity(ff); + if (index < 0 || index > vl_len(ff->vl)) + return -1; + return ff->thresholds[index]; +} + + +inline int is_active(uint16_t *results, int len, uint16_t *thresholds) { + if (thresholds == NULL) + return 1; + for (int i = 0; i < len; i++) + if (results[i] < thresholds[i] * 2 && results[i] > thresholds[i]) + return 1; + return 0; +} + +int ff_fastrepeatedprobe(ff_t ff, int max_records, uint16_t *results) { + uint32_t start = rdtscp(); + int l = vl_len(ff->vl); + for (int i = 0; i < max_records; i++) { + for (int j = 0; j < l; j++) { + mfence(); + clflush(vl_get(ff->vl, j)); + mfence(); + uint32_t end = rdtscp(); + *results++ = (end - start) > UINT16_MAX ? UINT16_MAX : end-start; + start = end; + } + } + return max_records; +} + +int ff_repeatedprobe(ff_t ff, int max_records, uint16_t *results, int slot) { + return ff_trace(ff, max_records, results, slot, 0, max_records); +} + + +int ff_trace(ff_t ff, int max_records, uint16_t *results, int slot, int threshold, int max_idle) { + assert(ff != NULL); + assert(results != NULL); + + if (max_records == 0) + return 0; + if (max_idle == 0) + max_idle = max_records; + + uint16_t *thresholds = NULL; + if (threshold) { + setthresholds(ff, 0); + thresholds = ff->thresholds; + } + + int len = vl_len(ff->vl); + + // Wait to hit threshold + uint64_t prev_time = rdtscp64(); + ff_probe(ff, results); + do { + if (slot > 0) { + do { + prev_time += slot; + } while (slotwait(prev_time)); + } + ff_probe(ff, results); + } while (!is_active(results, len, thresholds)); + + int count = 1; + int idle_count = 0; + int missed = 0; + + while (idle_count < max_idle && count < max_records) { + idle_count++; + results += len; + count++; + if (missed) { + for (int i = 0; i < len; i++) + results[i] = 0; + } else { + ff_probe(ff, results); + if (is_active(results, len, thresholds)) + idle_count = 0; + } + prev_time += slot; + missed = slotwait(prev_time); + } + return count; +} + + diff --git a/src/fr.c b/src/fr.c new file mode 100644 index 0000000..a8c6220 --- /dev/null +++ b/src/fr.c @@ -0,0 +1,217 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include + +#include +#include + +#include "vlist.h" +#include "timestats.h" + +struct fr { + vlist_t vl; + vlist_t evict; +}; + + + +fr_t fr_prepare() { + fr_t rv = malloc(sizeof(struct fr)); + rv->vl = vl_new(); + rv->evict = vl_new(); + return rv; +} + +void fr_release(fr_t fr) { + vl_free(fr->vl); + fr->vl = NULL; + vl_free(fr->evict); + fr->evict = NULL; + free(fr); +} + + +int fr_monitor(fr_t fr, void *adrs) { + assert(fr != NULL); + assert(adrs != NULL); + if (vl_find(fr->vl, adrs) >= 0) + return 0; + vl_push(fr->vl, adrs); + return 1; +} + + +int fr_unmonitor(fr_t fr, void *adrs) { + assert(fr != NULL); + assert(adrs != NULL); + int i = vl_find(fr->vl, adrs); + if (i < 0) + return 0; + vl_del(fr->vl, i); + return 1; +} + + +int fr_getmonitoredset(fr_t fr, void **adrss, int nlines) { + assert(fr != NULL); + + if (adrss != NULL) { + int l = vl_len(fr->vl); + if (l > nlines) + l = nlines; + for (int i = 0; i < l; i++) + adrss[i] = vl_get(fr->vl, i); + } + return vl_len(fr->vl); +} + +int fr_evict(fr_t fr, void *adrs) { + assert(fr != NULL); + assert(adrs != NULL); + if (vl_find(fr->evict, adrs) >= 0) + return 0; + vl_push(fr->evict, adrs); + return 1; +} + + +int fr_unevict(fr_t fr, void *adrs) { + assert(fr != NULL); + assert(adrs != NULL); + int i = vl_find(fr->evict, adrs); + if (i < 0) + return 0; + vl_del(fr->evict, i); + return 1; +} + + +int fr_getevictedset(fr_t fr, void **adrss, int nlines) { + assert(fr != NULL); + + if (adrss != NULL) { + int l = vl_len(fr->evict); + if (l > nlines) + l = nlines; + for (int i = 0; i < l; i++) + adrss[i] = vl_get(fr->evict, i); + } + return vl_len(fr->evict); +} + +void fr_randomise(fr_t fr) { + assert(fr != NULL); + assert(0); +} + + +int fr_probethreshold() { + static char dummy; + + ts_t ts = ts_alloc(); + for (int i = 0; i < 100000; i++) { + clflush(&dummy); + ts_add(ts, memaccesstime(&dummy)); + } + int res = ts_percentile(ts, 1); + ts_free(ts); + return res < 100 ? res - 10 : res * 9 / 10; +} + + + + + + +void fr_probe(fr_t fr, uint16_t *results) { + assert(fr != NULL); + assert(results != NULL); + int l = vl_len(fr->vl); + for (int i = 0; i < l; i++) { + void *adrs = vl_get(fr->vl, i); + int res = memaccesstime(adrs); + results[i] = res > UINT16_MAX ? UINT16_MAX : res; + clflush(adrs); + } + l = vl_len(fr->evict); + for (int i = 0; i < l; i++) + clflush(vl_get(fr->evict, i)); +} + +inline int is_active(uint16_t *results, int len, int threshold) { + for (int i = 0; i < len; i++) + if (results[i] < threshold) + return 1; + return threshold == 0; +} + +int fr_trace(fr_t fr, int max_records, uint16_t *results, int slot, int threshold, int max_idle) { + assert(fr != NULL); + assert(results != NULL); + + if (max_records == 0) + return 0; + if (max_idle == 0) + max_idle = max_records; + + int len = vl_len(fr->vl); + + // Wait to hit threshold + uint64_t prev_time = rdtscp64(); + fr_probe(fr, results); + do { + if (slot > 0) { + do { + prev_time += slot; + } while (slotwait(prev_time)); + } + fr_probe(fr, results); + } while (!is_active(results, len, threshold)); + + int count = 1; + int idle_count = 0; + int missed = 0; + + while (idle_count < max_idle && count < max_records) { + idle_count++; + results += len; + count++; + if (missed) { + for (int i = 0; i < len; i++) + results[i] = 0; + } else { + fr_probe(fr, results); + if (is_active(results, len, threshold)) + idle_count = 0; + } + prev_time += slot; + missed = slotwait(prev_time); + } + return count; +} + +int fr_repeatedprobe(fr_t fr, int max_records, uint16_t *results, int slot) { + return fr_trace(fr, max_records, results, slot, 0, max_records); +} + diff --git a/src/impl.c b/src/impl.c new file mode 100644 index 0000000..28a973c --- /dev/null +++ b/src/impl.c @@ -0,0 +1,321 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include "vlist.h" +#include "mm-impl.h" +#include "timestats.h" +#include "tsx.h" + +int probetime(void *pp) { + if (pp == NULL) + return 0; + int rv = 0; + void *p = (void *)pp; + uint32_t s = rdtscp(); + do { + p = LNEXT(p); + } while (p != (void *) pp); + return rdtscp()-s; +} + +int bprobetime(void *pp) { + if (pp == NULL) + return 0; + return probetime(NEXTPTR(pp)); +} + +int probecount(void *pp) { + if (pp == NULL) + return 0; + int rv = 0; + void *p = (void *)pp; + do { + uint32_t s = rdtscp(); + p = LNEXT(p); + s = rdtscp() - s; + if (s > L3_THRESHOLD) + rv++; + } while (p != (void *) pp); + return rv; +} + +int bprobecount(void *pp) { + if (pp == NULL) + return 0; + return probecount(NEXTPTR(pp)); +} + +void lx_probe(lxpp_t lx, uint16_t *results) { + for (int i = 0; i < lx->nmonitored; i++) { + int t = probetime(lx->monitoredhead[i]); + results[i] = t > UINT16_MAX ? UINT16_MAX : t; + } +} + +void lx_bprobe(lxpp_t lx, uint16_t *results) { + for (int i = 0; i < lx->nmonitored; i++) { + int t = bprobetime(lx->monitoredhead[i]); + results[i] = t > UINT16_MAX ? UINT16_MAX : t; + } +} + +void lx_probecount(lxpp_t lx, uint16_t *results) { + for (int i = 0; i < lx->nmonitored; i++) + results[i] = probecount(lx->monitoredhead[i]); +} + +void lx_bprobecount(lxpp_t lx, uint16_t *results) { + for (int i = 0; i < lx->nmonitored; i++) + results[i] = bprobecount(lx->monitoredhead[i]); +} + +int lx_repeatedprobe(lxpp_t lx, int nrecords, uint16_t *results, int slot) { + assert(lx != NULL); + assert(results != NULL); + + if (nrecords == 0) + return 0; + + int len = lx->nmonitored; + + int even = 1; + int missed = 0; + uint64_t prev_time = rdtscp64(); + for (int i = 0; i < nrecords; i++, results+=len) { + if (missed) { + for (int j = 0; j < len; j++) + results[j] = 0; + } else { + if (even) + lx_probe(lx, results); + else + lx_bprobe(lx, results); + even = !even; + } + if (slot > 0) { + prev_time += slot; + missed = slotwait(prev_time); + } + } + return nrecords; +} + +int lx_repeatedprobecount(lxpp_t lx, int nrecords, uint16_t *results, int slot) { + assert(lx != NULL); + assert(results != NULL); + + if (nrecords == 0) + return 0; + + int len = lx->nmonitored; + + int even = 1; + int missed = 0; + uint64_t prev_time = rdtscp64(); + for (int i = 0; i < nrecords; i++, results+=len) { + if (missed) { + for (int j = 0; j < len; j++) + results[j] = -1; + } else { + if (even) + lx_probecount(lx, results); + else + lx_bprobecount(lx, results); + even = !even; + } + if (slot > 0) { + prev_time += slot; + missed = slotwait(prev_time); + } + } + return nrecords; +} + +void lx_randomise(lxpp_t lx) { + for (int i = 0; i < lx->nmonitored; i++) { + int p = random() % (lx->nmonitored - i) + i; + int t = lx->monitoredset[p]; + lx->monitoredset[p] = lx->monitoredset[i]; + lx->monitoredset[i] = t; + + void *vt = lx->monitoredhead[p]; + lx->monitoredhead[p] = lx->monitoredhead[i]; + lx->monitoredhead[i] = vt; + } +} + +int lx_getmonitoredset(lxpp_t lx, int *lines, int nlines) { + if (lines == NULL || nlines == 0) + return lx->nmonitored; + if (nlines > lx->nmonitored) + nlines = lx->nmonitored; + bcopy(lx->monitoredset, lines, nlines * sizeof(int)); + return lx->nmonitored; +} + +static int return_linked_memory(lxpp_t lx, void* head) { + void* p = head; + while(p != head) { + mm_returnline(lx->mm, head); + head = *((void **) head); + } +} + +int lx_unmonitor(lxpp_t lx, int line) { + if (line < 0 || line >= lx->nmonitored) + return 0; + if (!IS_MONITORED(lx->monitoredbitmap, line)) + return 0; + UNSET_MONITORED(lx->monitoredbitmap, line); + for (int i = 0; i < lx->nmonitored; i++) + if (lx->monitoredset[i] == line) { + --lx->nmonitored; + lx->monitoredset[i] = lx->monitoredset[lx->nmonitored]; + + return_linked_memory(lx, lx->monitoredhead[i]); + + lx->monitoredhead[i] = lx->monitoredhead[lx->nmonitored]; + + break; + } + return 1; +} + +void lx_monitorall(lxpp_t lx) { + for (int i = 0; i < lx->totalsets; i++) + lx_monitor(lx, i); +} + +void lx_unmonitorall(lxpp_t lx) { + for (int i = 0; i < lx->totalsets / 32; i++) + lx->monitoredbitmap[i] = 0; + for (int i = 0; i < lx->nmonitored; i++) + return_linked_memory(lx, lx->monitoredhead[i]); + lx->nmonitored = 0; +} + +void * lx_sethead(lxpp_t lx, int set) { //vlist_t list, int count, int offset) { + vlist_t list = lx->groups[set / lx->groupsize]; + + int count = lx->lxinfo.associativity; + if (count == 0 || vl_len(list) < count) + count = vl_len(list); + + int offset = (set % lx->groupsize) * LX_CACHELINE; + + for (int i = 0; i < count; i++) { + LNEXT(OFFSET(vl_get(list, i), offset)) = OFFSET(vl_get(list, (i + 1) % count), offset); + LNEXT(OFFSET(vl_get(list, i), offset+sizeof(void*))) = OFFSET(vl_get(list, (i + count - 1) % count), offset+sizeof(void *)); + } + + return OFFSET(vl_get(list, 0), offset); +} + +int lx_getlxinfo(lxpp_t lx, lxinfo_t lxinfo) { + if (!lxinfo || !lx) + return -1; + bcopy(&lx->lxinfo, lxinfo, sizeof(struct lxinfo)); +} + +void lx_dummy_cb(lxpp_t l1, int recnum, void *data) { + return; +} + +// Synchronized Prime+Probe +int lx_syncpp(lxpp_t lx, int nrecords, uint16_t *results, lx_sync_cb setup, lx_sync_cb exec, void *data) { + assert(lx != NULL); + assert(results != NULL); + assert(exec != NULL); + assert(nrecords >= 0); + + if (nrecords == 0) + return 0; + + if (setup == NULL) + setup = lx_dummy_cb; + int len = lx->nmonitored; + + for (int i = 0; i < nrecords; i++, results += len) { + setup(lx, i, data); + + lx_probe(lx, results); + + exec(lx, i, data); + + lx_bprobe(lx, results); + + } + return nrecords; +} + +int lx_monitor(lxpp_t lx, int line) { + if (IS_MONITORED(lx->monitoredbitmap, line)) + return 0; + + int associativity = lx->lxinfo.associativity; + + vlist_t vl = vl_new(); + mm_requestlines(lx->mm, lx->level, line, associativity, vl); + + int len = vl_len(vl); + for (int way = 0; way < len; way++) { + void* mem = vl_get(vl, way); + void* nmem = vl_get(vl, (way + 1) % len); + void* pmem = vl_get(vl, (way - 1 + len) % len); + + LNEXT(mem) = nmem; + LNEXT(mem + sizeof(void*)) = (pmem + sizeof(void *)); + } + lx->monitoredset[lx->nmonitored] = line; + lx->monitoredhead[lx->nmonitored++] = vl_get(vl, 0); + SET_MONITORED(lx->monitoredbitmap, line); + vl_free(vl); + return 1; +} + +void lx_release(lxpp_t lx) { + free(lx->monitoredbitmap); + free(lx->monitoredset); + free(lx->monitoredhead); + if (lx->internalmm) + mm_release(lx->mm); + bzero(lx, sizeof(struct lxpp)); + free(lx); +} diff --git a/src/l1.c b/src/l1.c new file mode 100644 index 0000000..a38fc41 --- /dev/null +++ b/src/l1.c @@ -0,0 +1,183 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "mm-impl.h" + +#include "vlist.h" +#include + +struct l1pp { + void **monitoredhead; + int nsets; + + int* monitored; + + uint32_t *monitoredbitmap; + + cachelevel_e level; + size_t totalsets; + + int ngroups; + int groupsize; + vlist_t *groups; + + struct l1info l1info; + + mm_t mm; + uint8_t internalmm; +}; + +int loadL1cpuidInfo(l1info_t l1info) { + for (int i = 0; ; i++) { + l1info->cpuidInfo.regs.eax = CPUID_CACHEINFO; + l1info->cpuidInfo.regs.ecx = i; + cpuid(&l1info->cpuidInfo); + if (l1info->cpuidInfo.cacheInfo.type == 0) + return 0; + if (l1info->cpuidInfo.cacheInfo.level == 1) + return 1; + } +} + +void fillL1Info(l1info_t l1info) { + loadL1cpuidInfo(l1info); + + if (l1info->associativity == 0) + l1info->associativity = l1info->cpuidInfo.cacheInfo.associativity + 1; + if (l1info->sets == 0) + l1info->sets = l1info->cpuidInfo.cacheInfo.sets + 1; + if (l1info->bufsize == 0) + l1info->bufsize = L1_STRIDE * l1info->associativity; +} + +l1pp_t l1_prepare(mm_t mm) { + l1pp_t l1 = (l1pp_t)malloc(sizeof(struct l1pp)); + bzero(l1, sizeof(struct l1pp)); + + fillL1Info(&l1->l1info); + + l1->mm = mm; + if (l1->mm == NULL) { + l1->mm = mm_prepare(NULL, NULL, NULL); + l1->internalmm = 1; + } + + l1->monitored = (int*)malloc(L1_SETS * sizeof(int)); + l1->monitoredhead = (void **)malloc(L1_SETS * sizeof(void *)); + l1->monitoredbitmap = (uint32_t *)calloc((L1_SETS / 32) + 1, sizeof(uint32_t)); + l1->level = L1; + l1->totalsets = L1_SETS; + l1_monitorall(l1); + return l1; +} + +void l1_release(l1pp_t l1) { + lx_release((lxpp_t)l1); +} + + +int l1_monitor(l1pp_t l1, int line) { + return lx_monitor((lxpp_t) l1, line); +} + +int l1_unmonitor(l1pp_t l1, int line) { + lx_unmonitor((lxpp_t) l1, line); +} + +void l1_monitorall(l1pp_t l1) { + lx_monitorall((lxpp_t)l1); +} + +void l1_unmonitorall(l1pp_t l1) { + lx_unmonitorall((lxpp_t) l1); +} + +int l1_getmonitoredset(l1pp_t l1, int *lines, int nlines) { + return lx_getmonitoredset((lxpp_t) l1, lines, nlines); +} + +int l1_nsets(l1pp_t l1) { + return l1->nsets; +} + +void l1_randomise(l1pp_t l1) { + lx_randomise((lxpp_t) l1); +} + +void l1_probe(l1pp_t l1, uint16_t *results) { + lx_probe((lxpp_t) l1, results); +} + +void l1_bprobe(l1pp_t l1, uint16_t *results) { + lx_bprobe((lxpp_t) l1, results); +} + +int l1_repeatedprobe(l1pp_t l1, int nrecords, uint16_t *results, int slot) { + return lx_repeatedprobe((lxpp_t) l1, nrecords, results, slot); +} + +static void l1_dummy_cb(l1pp_t l1, int recnum, void *data) { + return; +} + +// Synchronized Prime+Probe +int l1_syncpp(l1pp_t l1, int nrecords, uint16_t *results, lx_sync_cb setup, lx_sync_cb exec, void *data) { + lx_syncpp((lxpp_t)l1, nrecords, results, setup, exec, data); +} + +// Synchronized Evict+Time +int l1_syncet(l1pp_t l1, int nrecords, uint16_t *results, l1_sync_cb setup, l1_sync_cb exec, void *data) { + assert(l1 != NULL); + assert(results != NULL); + assert(exec != NULL); + assert(nrecords >= 0); + + uint16_t dummyres[64]; + + if (nrecords == 0) + return 0; + + if (setup == NULL) + setup = l1_dummy_cb; + int len = l1->nsets; + + for (int i = 0; i < nrecords; i++, results++) { + setup(l1, i, data); + exec(l1, i, data); + l1_probe(l1, dummyres); + l1_probe(l1, dummyres); + l1_probe(l1, dummyres); + uint32_t start = rdtscp(); + exec(l1, i, data); + uint32_t res = rdtscp() - start; + *results = res > UINT16_MAX ? UINT16_MAX : res; + } + return nrecords; +} diff --git a/src/l1i.c b/src/l1i.c new file mode 100644 index 0000000..96a601a --- /dev/null +++ b/src/l1i.c @@ -0,0 +1,164 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +#define L1I_ASSOCIATIVITY 8 +#define L1I_CACHELINE 64 + +#define JMP_OFFSET (PAGE_SIZE - 5) +#define JMP_OPCODE 0xE9 +#define RET_OPCODE 0xC3 + +#define SET(page, set) (((uint8_t *)l1->memory) + PAGE_SIZE * (page) + L1I_CACHELINE * (set)) + + +struct l1ipp{ + void *memory; + uint8_t monitored[L1I_SETS]; + void *sets[L1I_SETS]; + int nsets; +}; + + + +l1ipp_t l1i_prepare(void) { + static uint8_t jmp[] = { JMP_OPCODE, + JMP_OFFSET & 0xff, + (JMP_OFFSET >>8) & 0xff, + (JMP_OFFSET >> 16) & 0xff, + (JMP_OFFSET >> 24) & 0xff}; + + + l1ipp_t l1 = (l1ipp_t)malloc(sizeof(struct l1ipp)); + l1->memory = mmap(0, PAGE_SIZE * L1I_ASSOCIATIVITY, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0); + for (int i = 0; i < L1I_SETS; i++) { + for (int j = 0; j < L1I_ASSOCIATIVITY - 1; j++) { + uint8_t *p = SET(j, i); + *p++ = JMP_OPCODE; + *p++ = JMP_OFFSET & 0xff; + *p++ = (JMP_OFFSET >>8) & 0xff; + *p++ = (JMP_OFFSET >> 16) & 0xff; + *p++ = (JMP_OFFSET >> 24) & 0xff; + } + *SET(L1I_ASSOCIATIVITY - 1, i) = RET_OPCODE; + } + l1i_monitorall(l1); + return l1; +} + +void l1i_release(l1ipp_t l1i) { + munmap(l1i->memory, PAGE_SIZE * L1I_ASSOCIATIVITY); + bzero(l1i, sizeof(struct l1ipp)); + free(l1i); +} + +int l1i_monitor(l1ipp_t l1i, int line) { + for (int i = 0; i < l1i->nsets; i++) + if (l1i->monitored[i] == line) + return 0; + l1i->monitored[l1i->nsets++] = line; + return 1; +} + +int l1i_unmonitor(l1ipp_t l1i, int line) { + for (int i = 0; i < l1i->nsets; i++) + if (l1i->monitored[i] == line) { + l1i->monitored[i] = l1i->monitored[l1i->nsets--]; + return 1; + } + return 0; +} + +void l1i_monitorall(l1ipp_t l1i) { + for (int i = 0; i < L1I_SETS; i++) + l1i->monitored[i] = i; + l1i->nsets = L1I_SETS; + l1i_randomise(l1i); +} + +void l1i_unmonitorall(l1ipp_t l1i) { + l1i->nsets = 0; +} + + +int l1i_getmonitoredset(l1ipp_t l1i, int *lines, int nlines) { + if (lines != NULL) { + if (nlines > l1i->nsets) + nlines = l1i->nsets; + for (int i = 0; i < nlines; i++) + lines[i] = l1i->monitored[i]; + } + return l1i->nsets; +} + + +int l1i_nsets(l1ipp_t l1i) { + return l1i->nsets; +} + +void l1i_randomise(l1ipp_t l1) { + char *mem = (char *)l1->memory; + for (int i = 0; i < l1->nsets; i++) { + int p = random() % (l1->nsets - i) + i; + uint8_t t = l1->monitored[p]; + l1->monitored[p] = l1->monitored[i]; + l1->monitored[i] = t; + } +} + +typedef void (*fptr)(void); +void l1i_probe(l1ipp_t l1, uint16_t *results) { + for (int i = 0; i < l1->nsets; i++) { + uint32_t start = rdtscp(); + // Using assembly because I am not sure I can trust the compiler + //asm volatile ("callq %0": : "r" (SET(0, l1->monitored[i])):); + (*((fptr)SET(0, l1->monitored[i])))(); + uint32_t res = rdtscp() - start; + results[i] = res > UINT16_MAX ? UINT16_MAX : res; + } +} + + +int l1i_repeatedprobe(l1ipp_t l1, int nrecords, uint16_t *results, int slot) { + assert(l1 != NULL); + assert(results != NULL); + + if (nrecords == 0) + return 0; + + int len = l1->nsets; + + for (int i = 0; i < nrecords; /* Increment inside */) { + l1i_probe(l1, results); + results += len; + i++; + } + return nrecords; +} + diff --git a/src/l2.c b/src/l2.c new file mode 100644 index 0000000..b23c862 --- /dev/null +++ b/src/l2.c @@ -0,0 +1,194 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#endif + +#include +#include +#include + +#include "vlist.h" +#include "mm-impl.h" + +#include "timestats.h" +#include "tsx.h" +#include +#include + +#ifdef MAP_HUGETLB +#define HUGEPAGES MAP_HUGETLB +#endif +#ifdef VM_FLAGS_SUPERPAGE_SIZE_2MB +#define HUGEPAGES VM_FLAGS_SUPERPAGE_SIZE_2MB +#endif + +#ifdef HUGEPAGES +#define HUGEPAGEBITS 21 +#define HUGEPAGESIZE (1<cpuidInfo.regs.eax = CPUID_CACHEINFO; + l2info->cpuidInfo.regs.ecx = i; + cpuid(&l2info->cpuidInfo); + if (l2info->cpuidInfo.cacheInfo.type == 0) + return 0; + if (l2info->cpuidInfo.cacheInfo.level == 2) + return 1; + } +} + +void fillL2Info(l2info_t l2info) { + loadL2cpuidInfo(l2info); + if (l2info->associativity == 0) + l2info->associativity = l2info->cpuidInfo.cacheInfo.associativity + 1; + // if (l2->l2info.slices == 0) { + // if (l2->l2info.setsperslice == 0) + // l2->l2info.setsperslice = l2_SETS_PER_SLICE; + // l2->l2info.slices = (l2->cpuidInfo.cacheInfo.sets + 1)/ l2->l2info.setsperslice; + // } + if (l2info->sets == 0) + l2info->sets = l2info->cpuidInfo.cacheInfo.sets + 1; + if (l2info->bufsize == 0) { + l2info->bufsize = l2info->associativity * l2info->sets * L2_CACHELINE * 2; + } +} + +l2pp_t l2_prepare(l2info_t l2info, mm_t mm) { + // Setup + l2pp_t l2 = (l2pp_t)malloc(sizeof(struct l2pp)); + bzero(l2, sizeof(struct l2pp)); + if (l2info != NULL) + bcopy(l2info, &l2->l2info, sizeof(struct l2info)); + fillL2Info(&l2->l2info); + l2->level = L2; + + // Check if linearmap and quadratic map are called together + if ((l2->l2info.flags & (LXFLAG_LINEARMAP | LXFLAG_QUADRATICMAP)) == (LXFLAG_LINEARMAP | LXFLAG_QUADRATICMAP)) { + free(l2); + return NULL; + //fprintf(stderr, "Error: Cannot call linear and quadratic map together\n"); + //exit(1); + } + + l2->mm = mm; + if (l2->mm == NULL) { + l2->mm = mm_prepare(NULL, NULL, NULL); + l2->internalmm = 1; + } + + const int nsets = l2->l2info.sets; + const int nways = l2->l2info.associativity; + + l2->groupsize = L2_SETS_PER_PAGE; + + l2->ngroups = l2->l2info.sets / l2->groupsize; + + l2->monitoredbitmap = (uint32_t *)calloc((nsets/32) + 1, sizeof(uint32_t)); + l2->monitoredset = malloc(nsets * sizeof(int)); + l2->monitoredhead = (void **)malloc(nsets * sizeof(void *)); + l2->nmonitored = 0; + l2->totalsets = l2->l2info.sets; + + l2_monitorall(l2); + + return l2; +} + +int l2_monitor(l2pp_t l2, int line) { + lx_monitor((lxpp_t) l2, line); +} + +void l2_randomise(l2pp_t l2) { + lx_randomise((lxpp_t) l2); +} + +void l2_monitorall(l2pp_t l2) { + lx_monitorall((lxpp_t)l2); +} + +int l2_unmonitor(l2pp_t l2, int line) { + return lx_unmonitor((lxpp_t) l2, line); +} + +void l2_unmonitorall(l2pp_t l2) { + lx_unmonitorall((lxpp_t) l2); +} + +void l2_probe(l2pp_t l2, uint16_t *results) { + lx_probe((lxpp_t) l2, results); +} + +void l2_bprobe(l2pp_t l2, uint16_t *results) { + lx_bprobe((lxpp_t) l2, results); +} + +int l2_getmonitoredset(l2pp_t l2, int *lines, int nlines) { + return lx_getmonitoredset((lxpp_t) l2, lines, nlines); +} + +void l2_release(l2pp_t l2) { + lx_release((lxpp_t)l2); +} + +int l2_repeatedprobe(l2pp_t l2, int nrecords, uint16_t *results, int slot) { + return lx_repeatedprobe((lxpp_t) l2, nrecords, results, slot); +} + +int l2_getl2info(l2pp_t l2, l2info_t l2info) { + return lx_getlxinfo((lxpp_t)l2, (lxinfo_t)l2info); +} + +int l2_syncpp(l2pp_t l2, int nrecords, uint16_t *results, lx_sync_cb setup, lx_sync_cb exec, void *data) { + return lx_syncpp((lxpp_t)l2, nrecords, results, setup, exec, data); +} diff --git a/src/l3.c b/src/l3.c new file mode 100644 index 0000000..521fea5 --- /dev/null +++ b/src/l3.c @@ -0,0 +1,310 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#endif + +#include +#include +#include +#include "mastik/impl.h" +#include "mastik/lx.h" + +#include "vlist.h" +#include "mm-impl.h" +#include "timestats.h" +#include "tsx.h" + +#define CHECKTIMES 16 + +/* + * Intel documentation still mentiones one slice per core, but + * experience shows that at least some Skylake models have two + * smaller slices per core. + * When probing the cache, we can use the smaller size - this will + * increase the probe time but for huge pages, where we use + * the slice size, the probe is fast and the increase is not too + * significant. + * When using the PTE maps, we need to know the correct size and + * the correct number of slices. This means that, currently and + * without user input, PTE is not guaranteed to work. + * So, on a practical note, L3_GROUPSIZE_FOR_HUGEPAGES is the + * smallest slice size we have seen; L3_SETS_PER_SLICE is the + * default for the more common size. If we learn how to probe + * the slice size we can get rid of this mess. + */ +#define L3_SETS_PER_SLICE 2048 +#define L3_GROUPSIZE_FOR_HUGEPAGES 1024 + +// The number of cache sets in each page +#define L3_SETS_PER_PAGE 64 + +#define L3_CACHELINE 64 + +#ifdef MAP_HUGETLB +#define HUGEPAGES MAP_HUGETLB +#endif +#ifdef VM_FLAGS_SUPERPAGE_SIZE_2MB +#define HUGEPAGES VM_FLAGS_SUPERPAGE_SIZE_2MB +#endif + +#ifdef HUGEPAGES +#define HUGEPAGEBITS 21 +#define HUGEPAGESIZE (1<cpuidInfo.regs.eax = CPUID_CACHEINFO; + l3info->cpuidInfo.regs.ecx = i; + cpuid(&l3info->cpuidInfo); + if (l3info->cpuidInfo.cacheInfo.type == 0) + return 0; + if (l3info->cpuidInfo.cacheInfo.level == 3) + return 1; + } +} + +void fillL3Info(l3info_t l3info) { + loadL3cpuidInfo(l3info); + if (l3info->associativity == 0) + l3info->associativity = l3info->cpuidInfo.cacheInfo.associativity + 1; + if (l3info->slices == 0) { + if (l3info->setsperslice == 0) + l3info->setsperslice = L3_SETS_PER_SLICE; + l3info->slices = (l3info->cpuidInfo.cacheInfo.sets + 1)/ l3info->setsperslice; + } + if (l3info->setsperslice == 0) + l3info->setsperslice = (l3info->cpuidInfo.cacheInfo.sets + 1)/l3info->slices; + if (l3info->bufsize == 0) { + l3info->bufsize = l3info->associativity * l3info->slices * l3info->setsperslice * L3_CACHELINE * 2; + if (l3info->bufsize < 10 * 1024 * 1024) + l3info->bufsize = 10 * 1024 * 1024; + } +} + +#if 0 +void printL3Info() { + struct l3info l3Info; + loadL3cpuidInfo(&l3Info); + printf("type : %u\n", l3Info.cpuidInfo.cacheInfo.type); + printf("level : %u\n", l3Info.cpuidInfo.cacheInfo.level); + printf("selfInitializing: %u\n", l3Info.cpuidInfo.cacheInfo.selfInitializing); + printf("fullyAssociative: %u\n", l3Info.cpuidInfo.cacheInfo.fullyAssociative); + printf("logIds : %u\n", l3Info.cpuidInfo.cacheInfo.logIds + 1); + printf("phyIds : %u\n", l3Info.cpuidInfo.cacheInfo.phyIds + 1); + printf("lineSize : %u\n", l3Info.cpuidInfo.cacheInfo.lineSize + 1); + printf("partitions : %u\n", l3Info.cpuidInfo.cacheInfo.partitions + 1); + printf("associativity : %u\n", l3Info.cpuidInfo.cacheInfo.associativity + 1); + printf("sets : %u\n", l3Info.cpuidInfo.cacheInfo.sets + 1); + printf("wbinvd : %u\n", l3Info.cpuidInfo.cacheInfo.wbinvd); + printf("inclusive : %u\n", l3Info.cpuidInfo.cacheInfo.inclusive); + printf("complexIndex : %u\n", l3Info.cpuidInfo.cacheInfo.complexIndex); + exit(0); +} +#endif + +void prime(void *pp, int reps) { + walk((void *)pp, reps); +} + +#define str(x) #x +#define xstr(x) str(x) + +l3pp_t l3_prepare(l3info_t l3info, mm_t mm) { + // Setup + l3pp_t l3 = (l3pp_t)malloc(sizeof(struct l3pp)); + bzero(l3, sizeof(struct l3pp)); + if (l3info != NULL) + bcopy(l3info, &l3->l3info, sizeof(struct l3info)); + fillL3Info(&l3->l3info); + l3->level = L3; + + // Check if linearmap and quadratic map are called together + if ((l3->l3info.flags & (L3FLAG_LINEARMAP | L3FLAG_QUADRATICMAP)) == (L3FLAG_LINEARMAP | L3FLAG_QUADRATICMAP)) { + free(l3); + return NULL; + //fprintf(stderr, "Error: Cannot call linear and quadratic map together\n"); + //exit(1); + } + + l3->mm = mm; + if (l3->mm == NULL) { + l3->mm = mm_prepare(NULL, NULL, (lxinfo_t)l3info); + l3->internalmm = 1; + } + + if (!mm_initialisel3(l3->mm)) + return NULL; + + l3->ngroups = l3->mm->l3ngroups; + l3->groupsize = l3->mm->l3groupsize; + + // Allocate monitored set info + l3->monitoredbitmap = (uint32_t *)calloc((l3->ngroups*l3->groupsize/32) + 1, sizeof(uint32_t)); + l3->monitoredset = (int *)malloc(l3->ngroups * l3->groupsize * sizeof(int)); + l3->monitoredhead = (void **)malloc(l3->ngroups * l3->groupsize * sizeof(void *)); + l3->nmonitored = 0; + l3->totalsets = l3->ngroups * l3->groupsize; + + return l3; +} + +void l3_release(l3pp_t l3) { + lx_release((lxpp_t)l3); +} + +int l3_monitor(l3pp_t l3, int line) { + return lx_monitor((lxpp_t) l3, line); +} + +int l3_unmonitor(l3pp_t l3, int line) { + return lx_unmonitor((lxpp_t) l3, line); +} + +void l3_unmonitorall(l3pp_t l3) { + lx_unmonitorall((lxpp_t) l3); +} + +int l3_getmonitoredset(l3pp_t l3, int *lines, int nlines) { + return lx_getmonitoredset((lxpp_t) l3, lines, nlines); +} + +void l3_randomise(l3pp_t l3) { + lx_randomise((lxpp_t) l3); +} + +void l3_probe(l3pp_t l3, uint16_t *results) { + lx_probe((lxpp_t) l3, results); +} + +void l3_bprobe(l3pp_t l3, uint16_t *results) { + lx_bprobe((lxpp_t) l3, results); +} + +void l3_probecount(l3pp_t l3, uint16_t *results) { + lx_probecount((lxpp_t) l3, results); +} + +void l3_bprobecount(l3pp_t l3, uint16_t *results) { + lx_bprobecount((lxpp_t) l3, results); +} + +// Returns the number of probed sets in the LLC +int l3_getSets(l3pp_t l3) { + return l3->ngroups * l3->groupsize; +} + +// Returns the number slices +int l3_getSlices(l3pp_t l3) { + return l3->l3info.slices; +} + +// Returns the LLC associativity +int l3_getAssociativity(l3pp_t l3) { + return l3->l3info.associativity; +} + +int l3_repeatedprobe(l3pp_t l3, int nrecords, uint16_t *results, int slot) { + return lx_repeatedprobe((lxpp_t) l3, nrecords, results, slot); +} + +int l3_repeatedprobecount(l3pp_t l3, int nrecords, uint16_t *results, int slot) { + return lx_repeatedprobecount((lxpp_t) l3, nrecords, results, slot); +} + +void l3_pa_prime(l3pp_t l3) { + for (int i = 0; i < l3->nmonitored; i++) { + int t = probetime(l3->monitoredhead[i]); + } +} + +/* A single round of TSX abort detection, decide existing time period of + * RTM region by modifing 'time_limit'. It returns 0 if there is no TSX + * abort; It returns 1 if the abort is caused by internal buffer overflow or + * memory address conflict; It returns -1 if abort is caused by other reasons, + * e.g. context switch, some micro instructions + */ +int l3_pabort(l3pp_t l3, uint32_t time_limit) { + unsigned ret; + + if ((ret = xbegin()) == XBEGIN_INIT){ + l3_pa_prime(l3); + uint32_t s = rdtscp(); + while((rdtscp() - s) < time_limit) + ; + xend(); + } else { + if ((ret & XABORT_CAPACITY) || (ret & XABORT_CONFLICT) ) + return 1; + else + return -1; + } + return 0; +} + +/* Run TSX abort detection repeatedly. 'Sample': How many repeats will + * be performed; 'results': store results of l3_pabort() + */ +void l3_repeatedpabort(l3pp_t l3, int sample, int16_t *results, uint32_t time_limit) { + int cont = 0; + + do{ + results[cont] = l3_pabort(l3, time_limit); + } while(cont++ < sample); +} diff --git a/src/mm-impl.h b/src/mm-impl.h new file mode 100644 index 0000000..a22011b --- /dev/null +++ b/src/mm-impl.h @@ -0,0 +1,44 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef MM_IMPL_H +#define MM_IMPL_H + +struct mm { + vlist_t memory; + size_t pagesize; + + struct lxinfo l1info; + struct lxinfo l2info; + struct lxinfo l3info; + + int l3ngroups; + int l3groupsize; + vlist_t *l3groups; + void* l3buffer; + + pagetype_e pagetype; +}; + +void mm_requestlines(mm_t mm, cachelevel_e cachelevel, int line, int count, vlist_t list); +void mm_returnlines(mm_t mm, vlist_t line); +int timeevict(vlist_t es, void *candidate); + + +#endif diff --git a/src/mm.c b/src/mm.c new file mode 100644 index 0000000..d8942af --- /dev/null +++ b/src/mm.c @@ -0,0 +1,632 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "vlist.h" +#include "mm-impl.h" +#include "timestats.h" +#include "tsx.h" + +#define L3_SETS_PER_SLICE 2048 +#define L3_GROUPSIZE_FOR_HUGEPAGES 1024 + +// The number of cache sets in each page +#define L3_SETS_PER_PAGE 64 + +#define L3_CACHELINE 64 + +#ifdef MAP_HUGETLB +#define HUGEPAGES MAP_HUGETLB +#endif +#ifdef VM_FLAGS_SUPERPAGE_SIZE_2MB +#define HUGEPAGES VM_FLAGS_SUPERPAGE_SIZE_2MB +#endif + +#ifdef HUGEPAGES +#define HUGEPAGEBITS 21 +#define HUGEPAGESIZE (1<l3info.bufsize; +#ifdef HUGEPAGES + // add an if here to check if we want to use huge pages. + mm->pagesize = HUGEPAGESIZE; + mm->pagetype = PAGETYPE_HUGE; + mm->l3groupsize = L3_GROUPSIZE_FOR_HUGEPAGES; + buffer = mmap(NULL, bufsize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|HUGEPAGES, -1, 0); + +#endif + if (buffer == MAP_FAILED) { + mm->pagetype = PAGETYPE_SMALL; + mm->l3groupsize = L3_SETS_PER_PAGE; + mm->pagesize = 4096; + buffer = mmap(NULL, bufsize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); + } + if (buffer == MAP_FAILED) { + perror("Error allocating buffer!\n"); + exit(-1); + } + uint64_t physAddr = getphysaddr(buffer); + // printf("Physical set of allocated buffer %lu\n", physAddr); + // printf("L1 allignment: %lu\n", (physAddr % (mm->l1info.sets * LX_CACHELINE))); + // printf("L2 allignment: %lu\n", (physAddr % (mm->l2info.sets * LX_CACHELINE))); + // printf("L3 slice allignment: %lu\n", (physAddr % (mm->l3info.sets * LX_CACHELINE))); + bzero(buffer, bufsize); + return buffer; +} + +mm_t mm_prepare(lxinfo_t l1info, lxinfo_t l2info, lxinfo_t l3info) { + mm_t mm = calloc(1, sizeof(struct mm)); + + if (l1info) + bcopy(l1info, &mm->l1info, sizeof(struct lxinfo)); + if (l2info) + bcopy(l2info, &mm->l2info, sizeof(struct lxinfo)); + if (l3info) + bcopy(l3info, &mm->l3info, sizeof(struct lxinfo)); + + fillL1Info((l1info_t)&mm->l1info); + fillL2Info((l2info_t)&mm->l2info); + fillL3Info((l3info_t)&mm->l3info); + + mm->memory = vl_new(); + vl_push(mm->memory, allocate_buffer(mm)); + + return mm; +} + +void mm_release(mm_t mm) { + int len = vl_len(mm->memory); + size_t bufferSize = mm->l3info.bufsize; + for (int i = 0; i < len; i++) { + munmap(vl_get(mm->memory, i), bufferSize); + } + if (mm->l3buffer) { + munmap(mm->l3buffer, bufferSize); + } + if (mm->l3groups) { + for (int i = 0; i < mm->l3ngroups; i++) + vl_free(mm->l3groups[i]); + free(mm->l3groups); + } + vl_free(mm->memory); + free(mm); +} + +#define CHECK_ALLOCATED_FLAG(buf, offset) *((uint64_t *)(buf + offset + 3 * sizeof(uint64_t))) +#define SET_ALLOCATED_FLAG(buf, offset) (*((uint64_t *)(buf + offset + 3 * sizeof(uint64_t))) = 1) +#define UNSET_ALLOCATED_FLAG(buf) (*((uint64_t *)(buf + 3 * sizeof(uint64_t))) = 0) + +#define L2_STRIDE ((mm->l2info.sets * L2_CACHELINE)) + +int mm_initialisel3(mm_t mm) { + if (mm->l3groups == NULL) { + mm->l3buffer = allocate_buffer(mm); + // Create the cache map + if (!ptemap(mm)) { + if (!probemap(mm)) { + free(mm->l3buffer); + return 0; + } + } + } + return 1; +} + +static void mm_l3findlines(mm_t mm, int set, int count, vlist_t list) { + assert(list != NULL); + + if (!mm_initialisel3(mm)) + return; + + int i = 0; + while (count > 0) { + int list_len = vl_len(mm->memory); + for (; i < list_len; i++) { + void* buf = vl_get(mm->memory, i); + + vlist_t es = mm->l3groups[set / mm->l3groupsize]; + + int groupOffset = set % mm->l3groupsize; + + for (uintptr_t offset = 0; offset < mm->l3info.bufsize; offset += mm->l3groupsize * LX_CACHELINE) { + void* cand = buf + offset; + clflush(cand); + if (checkevict(es, cand)) { + if (!CHECK_ALLOCATED_FLAG(cand, groupOffset * L3_CACHELINE)) { + SET_ALLOCATED_FLAG(cand, groupOffset * L3_CACHELINE); + vl_push(list, cand + groupOffset); + if(--count == 0) + return; + } + } + } + } + vl_push(mm->memory, allocate_buffer(mm)); + } + return; +} + +static void mm_l1l2findlines(mm_t mm, cachelevel_e cachelevel, + int line, int count, vlist_t list) { + assert(list != NULL); + + uintptr_t stride; + if (cachelevel == L1) { + stride = L1_STRIDE; + } else if (cachelevel == L2) { + stride = L2_STRIDE; + } + + int i = 0; + while (count > 0) { + int list_len = vl_len(mm->memory); + for (; i < list_len; i++) { + void* buf = vl_get(mm->memory, i); + for (uintptr_t offset = line * LX_CACHELINE; offset < mm->l3info.bufsize; offset += stride) { + if (!CHECK_ALLOCATED_FLAG(buf, offset)) { + // printf("Added, count = %d\n", count); + SET_ALLOCATED_FLAG(buf, offset); + vl_push(list, buf + offset); + if(--count == 0) + return; + } + } + } + vl_push(mm->memory, allocate_buffer(mm)); + } + return; +} + +static int parity(uint64_t v) { + v ^= v >> 1; + v ^= v >> 2; + v = (v & 0x1111111111111111UL) * 0x1111111111111111UL; + return (v >> 60) & 1; +} + +#define SLICE_MASK_0 0x1b5f575440UL +#define SLICE_MASK_1 0x2eb5faa880UL +#define SLICE_MASK_2 0x3cccc93100UL + + +static int addr2slice_linear(uintptr_t addr, int slices) { + int bit0 = parity(addr & SLICE_MASK_0); + int bit1 = parity(addr & SLICE_MASK_1); + int bit2 = parity(addr & SLICE_MASK_2); + return ((bit2 << 2) | (bit1 << 1) | bit0) & (slices - 1); +} + +static uintptr_t getphysaddr(void *p) { +#ifdef __linux__ + static int fd = -1; + + if (fd < 0) { + fd = open("/proc/self/pagemap", O_RDONLY); + if (fd < 0) + return 0; + } + uint64_t buf; + memaccess(p); + uintptr_t intp = (uintptr_t)p; + int r = pread(fd, &buf, sizeof(buf), ((uintptr_t)p)/4096 * sizeof(buf)); + + return (buf & ((1ULL << 54) - 1)) << 12 | ((uintptr_t)p & 0x3ff); +#else + return 0; +#endif +} + +static int ptemap(mm_t mm) { + if ((mm->l3info.flags & L3FLAG_USEPTE) == 0) + return 0; + if (getphysaddr(mm->l3buffer) == 0) + return 0; + if (mm->l3info.slices & (mm->l3info.slices - 1)) // Cannot do non-linear for now + return 0; + // mm->l3info.sets = sets per slice + mm->l3ngroups = mm->l3info.sets * mm->l3info.slices / mm->l3groupsize; + mm->l3groups = (vlist_t *)calloc(mm->l3ngroups, sizeof(vlist_t)); + + for (int i = 0; i < mm->l3ngroups; i++) + mm->l3groups[i] = vl_new(); + + for (int i = 0; i < mm->l3info.bufsize; i+= mm->l3groupsize * L3_CACHELINE) { + uintptr_t phys = getphysaddr(mm->l3buffer + i); + int slice = addr2slice_linear(phys, mm->l3info.slices); + // mm->l3info.sets = sets per slice + int cacheindex = ((phys / L3_CACHELINE) & (mm->l3info.sets - 1)); + vlist_t list = mm->l3groups[slice * (mm->l3info.sets/mm->l3groupsize) + cacheindex/mm->l3groupsize]; + vl_push(list, mm->l3buffer + i); + } + return 1; +} + +#define CHECKTIMES 16 + +static int timedwalk(void *list, register void *candidate) { +#ifdef DEBUG + static int debug = 100; + static int debugl = 1000; +#else +#define debug 0 +#endif //DEBUG + if (list == NULL) + return 0; + if (LNEXT(list) == NULL) + return 0; + void *start = list; + ts_t ts = ts_alloc(); + void *c2 = (void *)((uintptr_t)candidate ^ 0x200); + LNEXT(c2) = candidate; + clflush(c2); + memaccess(candidate); + for (int i = 0; i < CHECKTIMES * (debug ? 20 : 1); i++) { + walk(list, 20); + void *p = LNEXT(c2); + uint32_t time = memaccesstime(p); + ts_add(ts, time); + } + int rv = ts_median(ts); +#ifdef DEBUG + if (!--debugl) { + debugl=1000; + debug++; + } + if (debug) { + printf("--------------------\n"); + for (int i = 0; i < TIME_MAX; i++) + if (ts_get(ts, i) != 0) + printf("++ %4d: %4d\n", i, ts_get(ts, i)); + debug--; + } +#endif //DEBUG + ts_free(ts); + return rv; +} + +int timeevict(vlist_t es, void *candidate) { + if (vl_len(es) == 0) + return 0; + for (int i = 0; i < vl_len(es); i++) + LNEXT(vl_get(es, i)) = vl_get(es, (i + 1) % vl_len(es)); + int timecur = timedwalk(vl_get(es, 0), candidate); + + return timecur; +} + +static int checkevict(vlist_t es, void *candidate) { + int timecur = timeevict(es, candidate); + + return timecur > L3_THRESHOLD; +} + +// Read lines from es\partition[removed_partition_index] to check if +// partition[removed_partition_index] is part of the eviction set. es is +// partitioned into nPartitions sublists with remainders added to last +// sublist. +static int checkevict_remove_partition(vlist_t es, int removed_partition_index, + int subl_len, int nPartitions, void *candidate) { + if (vl_len(es) == 0) + return 0; + + int start_removal_ind = subl_len * removed_partition_index; + int end_removal_ind = start_removal_ind + subl_len - 1; + // If the removed partition is last partition, extend to end of es: + if (removed_partition_index == nPartitions - 1) { + end_removal_ind = vl_len(es) - 1; + } + + if (end_removal_ind - start_removal_ind + 1 == vl_len(es)) { + // The removed partition is the entire es + return 0; + } + + int current_index = (end_removal_ind + 1) % vl_len(es); + int next_index = (current_index + 1) % vl_len(es); + while (next_index != start_removal_ind) { + LNEXT(vl_get(es, current_index)) = vl_get(es, next_index); + current_index = next_index; + next_index = (next_index + 1) % vl_len(es); + } + LNEXT(vl_get(es, current_index)) = vl_get(es, (end_removal_ind + 1) % vl_len(es)); + int timecur = timedwalk(vl_get(es, (end_removal_ind + 1) % vl_len(es)), candidate); + + return timecur > L3_THRESHOLD; +} + +static void contract(vlist_t es, vlist_t candidates, void *current); + +static void *expand(vlist_t es, vlist_t candidates) { + while (vl_len(candidates) > 0) { + void *current = vl_poprand(candidates); + int time = timeevict(es, current); + + if (time > L3_THRESHOLD) + return current; + + vl_push(es, current); + } + return NULL; +} + +static void contract(vlist_t es, vlist_t candidates, void *current) { + for (int i = 0; i < vl_len(es);) { + void *cand = vl_get(es, i); + vl_del(es, i); + clflush(current); + if (checkevict(es, current)) + vl_push(candidates, cand); + else { + vl_insert(es, i, cand); + i++; + } + } +} + +// Finds minimal eviction set by repeatedly partitioning es into (minEvictionSetSize + 1) sublists of +// equal length (remainder added to last sublist) and removing sublists not part of the eviction set +static void contract_partition(vlist_t es, vlist_t candidates, int minEvictionSetSize, void *current) { + int nPartitions = minEvictionSetSize + 1; + + // While negative elements remain in es + while (nPartitions <= vl_len(es)) { + int sublist_len = vl_len(es) / nPartitions; + int n_sublist_positives = nPartitions; + + // Find which sublists are not part of the eviction set + for (int i = nPartitions - 1; i >=0 ; i--) { + clflush(current); + if (checkevict_remove_partition(es, i, sublist_len, nPartitions, current)) { + n_sublist_positives--; + // Calculate partition length (last partition can have more elements) + int partition_len = i == nPartitions - 1 ? sublist_len + (vl_len(es) % nPartitions) : sublist_len; + // Remove sublist[i] and push it into candidates + for (int j = partition_len - 1; j >= 0; j--) { + vl_push(candidates, vl_del(es, sublist_len*i + j)); + } + } + } + // No sublists were removed. Error will be handled in map(l3pp_t, vlist_t) + // function since its not an eviction set + if (n_sublist_positives == nPartitions) { + return; + } + } + return; +} + +static void collect(vlist_t es, vlist_t candidates, vlist_t set) { + for (int i = vl_len(candidates); i--; ) { + void *p = vl_del(candidates, i); + if (checkevict(es, p)) + vl_push(set, p); + else + vl_push(candidates, p); + } +} + +static vlist_t map(mm_t mm, vlist_t lines) { +#ifdef DEBUG + printf("%d lines\n", vl_len(lines)); +#endif // DEBUG + vlist_t groups = vl_new(); + vlist_t es = vl_new(); + int nlines = vl_len(lines); + int fail = 0; + while (vl_len(lines)) { + assert(vl_len(es) == 0); +#ifdef DEBUG + int d_l1 = vl_len(lines); +#endif // DEBUG + if (fail > 5) + break; + void *c = vl_poprand(lines); +#ifdef DEBUG + int d_l2 = vl_len(lines); +#endif // DEBUG + vlist_t leftovers = vl_new(); + contract_partition(lines, leftovers, mm->l3info.associativity, c); + es = lines; + lines = leftovers; +#ifdef DEBUG + int d_l3 = vl_len(es); +#endif //DEBUG + if (vl_len(es) > mm->l3info.associativity || vl_len(es) < mm->l3info.associativity - 3) { + vl_push(lines, c); + while (vl_len(es)) + vl_push(lines, vl_del(es, 0)); +#ifdef DEBUG + printf("set %3d: lines: %4d contracted: %2d failed\n", vl_len(groups), d_l1, d_l3); +#endif // DEBUG + fail++; + continue; + } + fail = 0; + vlist_t set = vl_new(); + vl_push(set, c); + collect(es, lines, set); + while (vl_len(es)) + vl_push(set, vl_del(es, 0)); +#ifdef DEBUG + printf("set %3d: lines: %4d contracted: %2d collected: %d\n", vl_len(groups), d_l1, d_l3, vl_len(set)); +#endif // DEBUG + vl_push(groups, set); + if (mm->l3info.progressNotification) + (*mm->l3info.progressNotification)(nlines - vl_len(lines), nlines, mm->l3info.progressNotificationData); + } + + vl_free(es); + return groups; +} + +static vlist_t quadraticmap(mm_t mm, vlist_t lines) { +#ifdef DEBUG + printf("%d lines\n", vl_len(lines)); +#endif // DEBUG + vlist_t groups = vl_new(); + vlist_t es = vl_new(); + int nlines = vl_len(lines); + int fail = 0; + while (vl_len(lines)) { + assert(vl_len(es) == 0); +#ifdef DEBUG + int d_l1 = vl_len(lines); +#endif // DEBUG + if (fail > 5) + break; + void *c = expand(es, lines); +#ifdef DEBUG + int d_l2 = vl_len(es); +#endif //DEBUG + if (c == NULL) { + while (vl_len(es)) + vl_push(lines, vl_del(es, 0)); +#ifdef DEBUG + printf("set %3d: lines: %4d expanded: %4d c=NULL\n", vl_len(groups), d_l1, d_l2); +#endif // DEBUG + fail++; + continue; + } + contract(es, lines, c); + contract(es, lines, c); + contract(es, lines, c); +#ifdef DEBUG + int d_l3 = vl_len(es); +#endif //DEBUG + if (vl_len(es) > mm->l3info.associativity || vl_len(es) < mm->l3info.associativity - 3) { + while (vl_len(es)) + vl_push(lines, vl_del(es, 0)); +#ifdef DEBUG + printf("set %3d: lines: %4d expanded: %4d contracted: %2d failed\n", vl_len(groups), d_l1, d_l2, d_l3); +#endif // DEBUG + fail++; + continue; + } + fail = 0; + vlist_t set = vl_new(); + vl_push(set, c); + collect(es, lines, set); + while (vl_len(es)) + vl_push(set, vl_del(es, 0)); +#ifdef DEBUG + printf("set %3d: lines: %4d expanded: %4d contracted: %2d collected: %d\n", vl_len(groups), d_l1, d_l2, d_l3, vl_len(set)); +#endif // DEBUG + vl_push(groups, set); + if (mm->l3info.progressNotification) + (*mm->l3info.progressNotification)(nlines - vl_len(lines), nlines, mm->l3info.progressNotificationData); + } + + vl_free(es); + return groups; +} + +static int probemap(mm_t mm) { + if ((mm->l3info.flags & LXFLAG_NOPROBE) != 0) + return 0; + vlist_t pages = vl_new(); + for (int i = 0; i < mm->l3info.bufsize; i += mm->l3groupsize * LX_CACHELINE) + vl_push(pages, mm->l3buffer + i); + vlist_t groups = vl_new(); + + if ((mm->l3info.flags & LXFLAG_QUADRATICMAP) != 0) { + groups = quadraticmap(mm, pages); + } + else if ((mm->l3info.flags & LXFLAG_LINEARMAP) != 0) { + groups = map(mm, pages); + } + // If quadratic or linear map aren't specified, default to fastest behavior based on small/huge pages + else if ((mm->l3info.flags & LXFLAG_NOHUGEPAGES) != 0) { + groups = map(mm, pages); + } else { + groups = quadraticmap(mm, pages); + } + //Store map results + mm->l3ngroups = vl_len(groups); + + mm->l3groups = (vlist_t *)calloc(mm->l3ngroups, sizeof(vlist_t)); + for (int i = 0; i < vl_len(groups); i++) + mm->l3groups[i] = vl_get(groups, i); + vl_free(groups); + vl_free(pages); + return 1; +} + +void mm_requestlines(mm_t mm, cachelevel_e cachelevel, int line, int count, vlist_t list) { + switch (cachelevel) { + case L1: + return mm_l1l2findlines(mm, cachelevel, line, count, list); + case L2: + if (mm->pagetype == PAGETYPE_HUGE) + return mm_l1l2findlines(mm, cachelevel, line, count, list); + else + perror("Operation not supported yet!\n"); + exit(-2); + case L3: + return mm_l3findlines(mm, line, count, list); + } +} + +void* mm_requestline(mm_t mm, cachelevel_e cachelevel, int line) { + vlist_t vl = vl_new(); + mm_requestlines(mm, cachelevel, line, 1, vl); + void* mem = vl_get(vl, 0); + vl_free(vl); + return mem; +} + +void mm_returnline(mm_t mm, void* line) { + UNSET_ALLOCATED_FLAG(line); +} +void mm_returnlines(mm_t mm, vlist_t lines) { + int len = vl_len(lines); + for (int i = 0; i < len; i++) + mm_returnline(mm, vl_get(lines, i)); +} diff --git a/src/pda.c b/src/pda.c new file mode 100644 index 0000000..75335be --- /dev/null +++ b/src/pda.c @@ -0,0 +1,203 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_SYS_PRCTL_H +#include +#endif + +#include +#include + +#include "vlist.h" + +struct pda { + vlist_t vl; + pid_t child; + int modified; + int active; +}; + + + +pda_t pda_prepare() { + pda_t rv = malloc(sizeof(struct pda)); + rv->vl = vl_new(); + rv->child = -1; + rv->modified = 0; + rv->active = 0; + return rv; +} + +void pda_release(pda_t pda) { + pda_deactivate(pda); + vl_free(pda->vl); + pda->vl = NULL; + free(pda); +} + + +int pda_target(pda_t pda, void *adrs) { + assert(pda != NULL); + assert(adrs != NULL); + vl_push(pda->vl, adrs); + pda->modified = 1; + return 1; +} + + +int pda_untarget(pda_t pda, void *adrs) { + assert(pda != NULL); + assert(adrs != NULL); + int i; + int count = 0; + while ((i = vl_find(pda->vl, adrs)) >= 0) { + vl_del(pda->vl, i); + count++; + } + pda->modified = count != 0; + return count; +} + + +int pda_gettargetedset(pda_t pda, void **adrss, int nlines) { + assert(pda != NULL); + + if (adrss != NULL) { + int l = vl_len(pda->vl); + if (l > nlines) + l = nlines; + for (int i = 0; i < l; i++) + adrss[i] = vl_get(pda->vl, i); + } + return vl_len(pda->vl); +} + +void pda_randomise(pda_t pda) { + assert(pda != NULL); + assert(0); + + pda->modified = 1; +} + + + +static void pda_flush(pda_t pda) { + void *p1,*p2, *p3, *p4; + vlist_t vl = pda->vl; + int len = vl_len(vl); + + switch (len) { + case 0: return; + case 1: + p1 = vl_get(pda->vl, 0); + for (;;) { + clflush(p1); + } + case 2: + p1 = vl_get(pda->vl, 0); + p2 = vl_get(pda->vl, 1); + for (;;) { + clflush(p1); + clflush(p2); + } + case 3: + p1 = vl_get(pda->vl, 0); + p2 = vl_get(pda->vl, 1); + p3 = vl_get(pda->vl, 1); + for (;;) { + clflush(p1); + clflush(p2); + clflush(p3); + } + case 4: + p1 = vl_get(pda->vl, 0); + p2 = vl_get(pda->vl, 1); + p3 = vl_get(pda->vl, 1); + p4 = vl_get(pda->vl, 1); + for (;;) { + clflush(p1); + clflush(p2); + clflush(p3); + clflush(p4); + } + default: + vl = pda->vl; + for (;;) { + for (int i = 0; i < len; i++) + clflush(vl_get(vl, i)); + } + } +} + +static void setautodeath() { +#ifdef HAVE_SYS_PRCTL_H + prctl(PR_SET_PDEATHSIG, SIGHUP); +#endif +} + +void pda_activate(pda_t pda) { + if (pda->active) { + if (!pda->modified) + return; + pda_deactivate(pda); + } + + if (vl_len(pda->vl) == 0) + return; + + pda->child = fork(); + switch (pda->child) { + case -1: + return; + case 0: + setautodeath(); + pda_flush(pda); + // unreached + default: + pda->active = 1; + pda->modified = 0; + return; + } +} + +void pda_deactivate(pda_t pda) { + if (!pda->active) + return; + if (pda->child > 0) { + kill(pda->child, SIGKILL); + wait4(pda->child, NULL, 0, NULL); + } + pda->child = -1; + pda->active = 0; + return; +} + +int pda_isactive(pda_t pda) { + return pda->active; +} + + diff --git a/src/symbol.c b/src/symbol.c new file mode 100644 index 0000000..e78087f --- /dev/null +++ b/src/symbol.c @@ -0,0 +1,105 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +#include + + +/* + * Convert a symbolic reference to a file offset. Accepted formats are: + * - offset to file + * @
- virtual address of a location + * - symbolic name, usually a function + * : - Start of a source line + * All optionally followed by [+-] + */ +uint64_t sym_getsymboloffset(const char *file, const char *symbol) { + char *symcopy = strdup(symbol); + uint64_t rv = ~0ULL; + char *srcfile = NULL; + uint32_t lineno = 0; + int offset = 0; + + char *ptr = strchr(symcopy, ':'); + if (ptr != NULL) { + *ptr = '\0'; + srcfile = symcopy; + ptr++; + } else { + ptr = symcopy; + } + + char *tmp = strchr(ptr, '+'); + if (tmp != NULL) { + *tmp = '\0'; + tmp++; + offset = strtoul(tmp, NULL, 0); + } else { + tmp = strchr(ptr, '-'); + if (tmp != NULL) { + *tmp = '\0'; + tmp++; + offset = -strtoul(tmp, NULL, 0); + } + } + + if (srcfile) { + lineno = strtoul(ptr, NULL, 0); + rv = sym_debuglineoffset(file, srcfile, lineno); + } else if (*ptr == '@') { + rv = sym_addresstooffset(file, strtoull(ptr+1, NULL, 0)); + } else if (isdigit(*ptr)) { + rv = strtoull(ptr, NULL, 0); + } else { + rv = sym_loadersymboloffset(file, ptr); + } + + if (rv != ~0ULL) + rv += offset; + +out: + if (symcopy) + free(symcopy); + return rv; +} + + +#ifndef HAVE_SYMBOLS +uint64_t sym_loadersymboloffset(const char *file, const char *name) { + return ~0ULL; +} + +uint64_t sym_addresstooffset(const char *file, uint64_t address) { + return ~0ULL; +} + +uint64_t sym_debuglineoffset(const char *file, const char *src, int lineno) { + return ~0ULL; +} +#endif + diff --git a/src/symbol_bfd.c b/src/symbol_bfd.c new file mode 100644 index 0000000..a8d8cd8 --- /dev/null +++ b/src/symbol_bfd.c @@ -0,0 +1,251 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + + +#include "config.h" +#ifndef HAVE_BFD_H +#error Must have bfd to compile this +#endif + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(HAVE_LIBDWARF_H) +#include +#elif defined(HAVE_LIBDWARF_LIBDWARF_H) +#include +#endif + +#include + +static void initialise() { + static int init = 0; + if (init) + return; + + bfd_init(); + init = 1; +} + +uint64_t sym_loadersymboloffset(const char *file, const char *name) { + initialise(); + + bfd *abfd = NULL; + asymbol **symbol_table = NULL; + uint64_t rv = ~0ULL; + + abfd = bfd_openr(file, "default"); + if (abfd == NULL) + goto out; + + + + if (!bfd_check_format(abfd, bfd_object)) { + if (bfd_get_error () != bfd_error_file_ambiguously_recognized) + goto out; + } + + long storage_needed = bfd_get_symtab_upper_bound (abfd); + if (storage_needed <= 0) + goto out; + + symbol_table = (asymbol **) malloc (storage_needed); + + long number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table); + if (number_of_symbols < 0) + goto out; + + for (long i = 0; i < number_of_symbols; i++) { + if (!strcmp(name, symbol_table[i]->name)) { + struct bfd_section *section = symbol_table[i]->section; + rv = symbol_table[i]->value + section->filepos; + goto out; + } + } + + +out: + if (symbol_table != NULL) + free(symbol_table); + if (abfd != NULL) + bfd_close(abfd); + return rv; +} + +uint64_t sym_addresstooffset(const char *file, uint64_t address) { + initialise(); + + bfd *abfd = NULL; + uint64_t rv = ~0ULL; + + abfd = bfd_openr(file, "default"); + if (abfd == NULL) + goto out; + + if (!bfd_check_format(abfd, bfd_object)) { + if (bfd_get_error () != bfd_error_file_ambiguously_recognized) + goto out; + } + + +// Interface for bfd changed in verison 2.33, support older versions as well +#ifdef HAVE_LEGACY_BFD + + for (asection *s = abfd->sections; s; s = s->next) { + if (bfd_get_section_flags (abfd, s) & (SEC_LOAD)) { + uint64_t vma = bfd_section_vma(abfd, s); + uint64_t size = bfd_section_size(abfd, s); + if (address >= vma && address - vma < size) { + rv = address - vma + s->filepos; + break; + } + } + } + +#else + + for (asection *s = abfd->sections; s; s = s->next) { + if (bfd_section_flags (s) & (SEC_LOAD)) { + uint64_t vma = bfd_section_vma(s); + uint64_t size = bfd_section_size(s); + if (address >= vma && address - vma < size) { + rv = address - vma + s->filepos; + break; + } + } + } + +#endif + +out: + if (abfd != NULL) + bfd_close(abfd); + return rv; +} + + +#ifdef HAVE_DWARF +static void dwarf_handler(Dwarf_Error error, Dwarf_Ptr errarg) { + Dwarf_Debug dbg = *(Dwarf_Debug *)errarg; + dwarf_dealloc(dbg, error, DW_DLA_ERROR); +} +#endif + +uint64_t sym_debuglineoffset(const char *file, const char *src, int lineno) { +#ifdef HAVE_DWARF + Dwarf_Debug dbg = NULL; + int res = DW_DLV_ERROR; + Dwarf_Error error = NULL; + Dwarf_Unsigned next_cu_header; + Dwarf_Die die = NULL; + char *name = NULL; + Dwarf_Line *linebuf = NULL; + Dwarf_Signed linecount; + Dwarf_Unsigned line; + Dwarf_Addr lineaddr; + int fd = -1; + uint64_t rv = -1; + + fd = open(file, O_RDONLY); + if(fd < 0) + goto out; + + res = dwarf_init(fd, DW_DLC_READ, dwarf_handler, (Dwarf_Ptr)&dbg, &dbg, &error); + if (res != DW_DLV_OK) { + if (error) + free(error); + goto out; + } + + for (;;) { + res = dwarf_next_cu_header(dbg, NULL, NULL, NULL, NULL, &next_cu_header, NULL); + if (res != DW_DLV_OK) + goto out; + + // The first sibling is a DW_TAG_compile_unit + res = dwarf_siblingof(dbg, NULL, &die, NULL); + if (res != DW_DLV_OK) + goto out; + + res = dwarf_diename(die, &name, NULL); + if (res != DW_DLV_OK) + goto out; + + int found = !strcmp(name, src); + + dwarf_dealloc(dbg, name, DW_DLA_STRING); + name = NULL; + if (found) + break; + + dwarf_dealloc(dbg, die, DW_DLA_DIE); + die = NULL; + } + + res = dwarf_srclines(die, &linebuf, &linecount, &error); + if(res != DW_DLV_OK) + goto out; + int nextline = 0; + uint64_t nextaddr = ~0ULL; + for (int i = 0; i < linecount; i++) { + dwarf_lineno(linebuf[i], &line, &error); + dwarf_lineaddr(linebuf[i], &lineaddr, &error); + if (rv == ~0ULL) { + if (lineno == line) + rv = lineaddr; + else if (line > lineno) { + if (nextline == 0 || nextline > line) { + nextline = line; + nextaddr = lineaddr; + } + } + } + dwarf_dealloc(dbg, linebuf[i], DW_DLA_LINE); + } + + dwarf_dealloc(dbg, linebuf, DW_DLA_LIST); + + if (rv == ~0ULL) + rv = nextaddr; + if (rv != ~0ULL) + rv = sym_addresstooffset(file, rv); + + +out: + if (name != NULL) + dwarf_dealloc(dbg, name, DW_DLA_STRING); + if (die != NULL) + dwarf_dealloc(dbg, die, DW_DLA_DIE); + if (dbg != NULL) + dwarf_finish(dbg, NULL); + if (fd >=0) + close(fd); + return rv; +#else + return ~0ULL; +#endif +} + + diff --git a/src/symbol_mach.c b/src/symbol_mach.c new file mode 100644 index 0000000..68d7a8a --- /dev/null +++ b/src/symbol_mach.c @@ -0,0 +1,193 @@ +/* + * Copyright 2021 The University of Adelaide + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __APPLE__ +#error No use compiling a Mac OS X file here +#endif + + +static void *map_file(const char *name, off_t *size) { + struct stat sb; + int fd = open(name, O_RDONLY); + if (fd < 0) + return MAP_FAILED; + if (fstat(fd, &sb) < 0) { + close(fd); + return MAP_FAILED; + } + + *size = sb.st_size; + void *rv = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + close(fd); + return rv; +} + +static void *handle_fat(void *adrs) { + if (OSSwapBigToHostInt32(*(uint32_t *)adrs) != FAT_MAGIC) + return adrs; + + struct host_basic_info basic_info; + unsigned int count = sizeof(basic_info)/sizeof(int); + if (host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)(&basic_info), &count) != KERN_SUCCESS) + return 0; + + struct fat_header *fh = (struct fat_header *)adrs; + uint32_t narch = OSSwapBigToHostInt32(fh->nfat_arch); + + struct fat_arch *archs = (struct fat_arch *)(fh + 1); + int index = -1; + for (int i = 0; i < narch; i++) { + uint32_t fatcputype = OSSwapBigToHostInt32(archs[i].cputype); + + // We choose the 64-bit ABI if exists. + if (fatcputype == (basic_info.cpu_type | CPU_ARCH_ABI64)) + index = i; + if (fatcputype == basic_info.cpu_type && index != -1) + index = i; + } + + if (index == -1) + return NULL; + return (void *)((uintptr_t)adrs + OSSwapBigToHostInt32(archs[index].offset)); +} + + +static uint64_t addrstooffset64(void *base, uint64_t vaddr) { + struct mach_header_64 *mh = (struct mach_header_64 *)base; + struct load_command *lc = (struct load_command *)(mh + 1); + int count = mh->ncmds; + + while (--count) { + switch (lc->cmd) { + case LC_SEGMENT: // Can this even happen? + break; + case LC_SEGMENT_64: + { + struct segment_command_64 *sc = (struct segment_command_64 *)lc; + if (vaddr >= sc->vmaddr && (vaddr - sc->vmaddr) < sc->filesize) + return vaddr - sc->vmaddr + sc->fileoff; + break; + } + } + lc = (struct load_command *)((uintptr_t)lc + lc->cmdsize); + } + + return ~0ULL; +} + +static uint64_t getsymoffset64(void *base, const char *name) { + struct mach_header_64 *mh = (struct mach_header_64 *)base; + struct load_command *lc = (struct load_command *)(mh + 1); + int count = mh->ncmds; + + while (--count) { + switch (lc->cmd) { + case LC_SYMTAB: + { + struct symtab_command *sc = (struct symtab_command *)lc; + + struct nlist_64 *symbols = (struct nlist_64 *)((uintptr_t)base + sc->symoff); + for (int i = 0; i < sc->nsyms; i++) { + char *p = (char *)base + sc->stroff + symbols[i].n_un.n_strx; + if ((symbols[i].n_type & N_TYPE) != N_SECT) + continue; + if (*p == '_') + p++; + if (strcmp(p, name)) + continue; + return addrstooffset64(base, symbols[i].n_value); + } + } + break; + } + + lc = (struct load_command *)((uintptr_t)lc + lc->cmdsize); + } + + return ~0ULL; +} + +uint64_t sym_loadersymboloffset(const char *file, const char *name) { + uint64_t rv = ~0ULL; + off_t size = 0; + void *adrs = map_file(file, &size); + void *base = handle_fat(adrs); + if (base == NULL) + goto out; + switch (*(uint32_t *)base) { + /* + case MH_MAGIC: + rv = getsymoffset32(base, name); + break; + */ + case MH_MAGIC_64: + rv = getsymoffset64(base, name); + break; + } + if (rv != ~0ULL) + rv += (uintptr_t)base - (uintptr_t)adrs; +out: + if (adrs != MAP_FAILED) + munmap(adrs, size); + return rv; +} + + +uint64_t sym_addresstooffset(const char *file, uint64_t address) { + uint64_t rv = ~0ULL; + off_t size = 0; + void *adrs = map_file(file, &size); + + // Later we might want to support fat files here... + + switch (*(uint32_t *)adrs) { + /* + case MH_MAGIC: + rv = addrstooffset32(adrs, address); + break; + */ + case MH_MAGIC_64: + rv = addrstooffset64(adrs, address); + break; + } + munmap(adrs, size); + return rv; +} + + +uint64_t sym_debuglineoffset(const char *file, const char *src, int lineno) { + return ~0ULL; +} + + + + + diff --git a/src/synctrace.c b/src/synctrace.c new file mode 100644 index 0000000..63a9731 --- /dev/null +++ b/src/synctrace.c @@ -0,0 +1,267 @@ +/* + * Copyright 2019 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#define ST_TRACEWIDTH L2_SETS + +#define L2_LOW_THRESHOLD 90 +#define LIMIT 400 +#define SCALE 1000 + +typedef struct synctrace *synctrace_t; + +struct synctrace +{ + // setup data + int blockSize; + uint8_t fixMask[ST_BLOCKBYTES]; + uint8_t fixData[ST_BLOCKBYTES]; + + // exec data + uint8_t input[ST_BLOCKBYTES]; + uint8_t output[ST_BLOCKBYTES]; + st_crypto_f crypto; + void *cryptoData; + + // Prcoess data + int limit; + uint8_t *split; + int map[L2_SETS]; + uint8_t clusterMask; + st_clusters_t clusters; +}; + +void dummy_setup_cb(int nrecords, void *data) +{ + return; +} + +// Synchronized Prime+Probe +int st_lxpp(lxpp_t lx, int nrecords, st_setup_cb setup, st_exec_cb exec, st_process_cb process, void *data) +{ + assert(lx != NULL); + assert(exec != NULL); + assert(nrecords >= 0); + + if (nrecords == 0) + return 0; + + if (setup == NULL) + setup = dummy_setup_cb; + int len = lx_getmonitoredset(lx, NULL, 0); + + uint16_t *res = malloc(len * sizeof(uint16_t)); + + for (int i = 0; i < nrecords; i++) + { + setup(i, data); + lx_probe(lx, res); + exec(i, data); + lx_bprobe(lx, res); + process(i, data, len, res); + } + + free(res); + return nrecords; +} + +/* +// Synchronized Evict+Time +int st_l1et(l1pp_t l1, int nrecords, st_setup_cb setup, st_exec_cb exec, st_process_cb process, void *data); +// Synchronized Evict+Time +int l1_syncet(l1pp_t l1, int nrecords, uint16_t *results, l1_sync_cb setup, l1_sync_cb exec, void *data) { + assert(l1 != NULL); + assert(results != NULL); + assert(exec != NULL); + assert(nrecords >= 0); + + uint16_t dummyres[64]; + + if (nrecords == 0) + return 0; + + if (setup == NULL) + setup = l1_dummy_cb; + int len = l1->nsets; + + for (int i = 0; i < nrecords; i++, results++) { + setup(l1, i, data); + exec(l1, i, data); + l1_probe(l1, dummyres); + l1_probe(l1, dummyres); + l1_probe(l1, dummyres); + uint32_t start = rdtscp(); + exec(l1, i, data); + uint32_t res = rdtscp() - start; + *results = res > UINT16_MAX ? UINT16_MAX : res; + } + return nrecords; +} +*/ + +static void spp_setup(int recnum, void *vst) +{ + synctrace_t st = (synctrace_t)vst; + for (int i = 0; i < st->blockSize; i++) + st->input[i] = (rand() & 0xff & ~st->fixMask[i]) | (st->fixData[i] & st->fixMask[i]); +} + +static void spp_process(int recnum, void *vst, int nres, uint16_t results[]) +{ + synctrace_t st = (synctrace_t)vst; + for (int byte = 0; byte < st->blockSize; byte++) + { + int inputbyte = st->split[byte] & st->clusterMask; + st->clusters[byte].count[inputbyte]++; + for (int i = 0; i < nres; i++) + { + uint64_t res = results[i] > LIMIT ? LIMIT : results[i]; + + st->clusters[byte].avg[inputbyte][st->map[i]] += res; + st->clusters[byte].var[inputbyte][st->map[i]] += res * res; + } + } +} + +static void spp_exec(int recnum, void *vst) +{ + synctrace_t st = (synctrace_t)vst; + (*st->crypto)(st->input, st->output, st->cryptoData); +} + +static void normalise(int blockSize, st_clusters_t clusters, + int level) +{ + int nsets; + if (level == 1) + nsets = L1_SETS; + else if (level == 2) + nsets = L2_SETS; + for (int byte = 0; byte < blockSize; byte++) + { + int total_count = 0; + int64_t total_avg[nsets]; + memset(total_avg, 0, sizeof(total_avg)); + for (int cluster = 0; cluster < 256; cluster++) + { + if (clusters[byte].count[cluster]) + { + int count = clusters[byte].count[cluster]; + total_count += count; + for (int set = 0; set < nsets; set++) + { + int64_t avg = clusters[byte].avg[cluster][set]; + total_avg[set] += avg; + avg = (avg * SCALE + count / 2) / count; + clusters[byte].avg[cluster][set] = avg; + } + } + } + for (int set = 0; set < nsets; set++) + total_avg[set] = (total_avg[set] * SCALE + total_count / 2) / total_count; + + for (int cluster = 0; cluster < 256; cluster++) + if (clusters[byte].count[cluster]) + for (int set = 0; set < nsets; set++) + clusters[byte].avg[cluster][set] -= total_avg[set]; + } +} + +st_clusters_t syncPrimeProbe(int nsamples, + int blockSize, + int splitinput, + uint8_t *fixMask, + uint8_t *fixData, + st_crypto_f crypto, + void *cryptoData, + uint8_t clusterMask, + int cachelevel) +{ + synctrace_t st = (synctrace_t)malloc(sizeof(struct synctrace)); + memset(st, 0, sizeof(struct synctrace)); + st->blockSize = blockSize; + if (fixMask && fixData) + { + memcpy(st->fixMask, fixMask, blockSize); + memcpy(st->fixData, fixData, blockSize); + } + st->crypto = crypto; + st->cryptoData = cryptoData; + st_clusters_t clusters = calloc(blockSize, sizeof(struct st_clusters)); + st->clusters = clusters; + st->clusterMask = clusterMask; + st->split = splitinput ? st->input : st->output; + lxpp_t lx; + if (cachelevel == 1) + lx = (lxpp_t)l1_prepare(NULL); + else if (cachelevel == 2) + lx = (lxpp_t)l2_prepare(NULL, NULL); + + lx_monitorall(lx); + + lx_getmonitoredset(lx, st->map, lx->nmonitored); + st_lxpp(lx, nsamples, spp_setup, spp_exec, spp_process, st); + + free(st); + normalise(blockSize, clusters, cachelevel); + lx_release(lx); + return clusters; +} + +/* +st_clusters_t syncEvictTime(int nsamples, + int blockSize, + uint8_t *fixMask, + uint8_t *fixData, + st_crypto_f crypto, + void *cryptoData, + uint8_t clusterMask) { + synctrace_t st = (synctrace_t)malloc(sizeof(struct synctrace)); + memset(st, 0, sizeof(struct synctrace)); + st->blockSize = blockSize; + if (fixMask && fixData) { + memcpy(st->fixMask, fixMask, blockSize); + memcpy(st->fixData, fixData, blockSize); + } + st->crypto = crypto; + st->cryptoData = cryptoData; + st_clusters_t clusters = calloc(blockSize, sizeof(struct st_clusters)); + st->clusters = clusters; + st->clusterMask = clusterMask; + l1pp_t l1 = l1_prepare(NULL); + l1_getmonitoredset(l1, st->map, L1_SETS); + st_l1pp(l1, nsamples, spp_setup, spp_exec, spp_process, st); + free(st); + normalise(blockSize, clusters); + return clusters; +} +*/ diff --git a/src/timestats.c b/src/timestats.c new file mode 100644 index 0000000..76c0dc2 --- /dev/null +++ b/src/timestats.c @@ -0,0 +1,113 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include +#include + +#include "timestats.h" + + + +struct ts { + uint32_t data[TIME_MAX]; +}; + + +static ts_t lastfree = NULL; + +ts_t ts_alloc() { + ts_t rv = lastfree; + if (rv == NULL) + rv = (ts_t)malloc(sizeof(struct ts)); + else + lastfree = NULL; + ts_clear(rv); + return rv; +} + +void ts_free(ts_t ts) { + if (lastfree == NULL) + lastfree = ts; + else + free(ts); +} + +void ts_clear(ts_t ts) { + bzero(ts, sizeof(struct ts)); +} + +void ts_add(ts_t ts, int tm) { + if (tm < TIME_MAX && tm >= 0) + ts->data[tm]++; + else + ts->data[0]++; +} + +uint32_t ts_get(ts_t ts, int tm) { + return tm < TIME_MAX && tm > 0 ? ts->data[tm] : 0; +} + +uint32_t ts_outliers(ts_t ts) { + return ts->data[0]; +} + + +int ts_median(ts_t ts) { + int c = 0; + for (int i = 0; i < TIME_MAX; i++) + c += ts->data[i]; + c = (c + 1) / 2; + for (int i = 1; i < TIME_MAX; i++) + if ((c -= ts->data[i]) < 0) + return i; + return 0; +} + +int ts_max(ts_t ts) { + for (int i = TIME_MAX; --i; ) + if (ts->data[i] != 0) + return i; + return 0; +} + +int ts_percentile(ts_t ts, int percentile) { + int c = 0; + for (int i = 0; i < TIME_MAX; i++) + c += ts->data[i]; + c = (c * percentile + 50) / 100; + for (int i = 1; i < TIME_MAX; i++) + if ((c -= ts->data[i]) < 0) + return i; + return ts_max(ts); +} + + +int ts_mean(ts_t ts, int scale) { + uint64_t sum = 0; + int count = 0; + for (int i = 0; i < TIME_MAX; i++) { + count += ts->data[i]; + sum += i* (uint64_t)ts->data[i]; + } + return (int)((sum * scale)/count); +} diff --git a/src/timestats.h b/src/timestats.h new file mode 100644 index 0000000..19befb2 --- /dev/null +++ b/src/timestats.h @@ -0,0 +1,47 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __TIMESTATS_H__ +#define __TIMESTATS_H__ 1 + +#define TIME_MAX 1024 + +typedef struct ts *ts_t; + +ts_t ts_alloc(); +void ts_free(ts_t ts); + +void ts_clear(ts_t ts); + +// tm > 0 +void ts_add(ts_t ts, int tm); + +// tm > 0 +uint32_t ts_get(ts_t ts, int tm); + +uint32_t ts_outliers(ts_t ts); + +int ts_median(ts_t ts); + +int ts_max(ts_t ts); +int ts_percentile(ts_t ts, int percentile); + +int ts_mean(ts_t ts, int scale); + +#endif // __TIMESTATS_H__ diff --git a/src/tsx.h b/src/tsx.h new file mode 100644 index 0000000..acaffa8 --- /dev/null +++ b/src/tsx.h @@ -0,0 +1,41 @@ +/* +This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this file, +You can obtain one at https://mozilla.org/MPL/2.0/. + +Copyright (c) 2018, Stephan van Schaik + + +Imported from https://github.com/vusec/xlate/blob/master/include/xlate/x86-64/tsx.h +*/ + +#pragma once + +#define XBEGIN_INIT (~0u) +#define XABORT_EXPLICIT (1 << 0) +#define XABORT_RETRY (1 << 1) +#define XABORT_CONFLICT (1 << 2) +#define XABORT_CAPACITY (1 << 3) +#define XABORT_DEBUG (1 << 4) +#define XABORT_NESTED (1 << 5) +#define XABORT_CODE(x) (((x) >> 24) & 0xff) + +static inline unsigned xbegin(void) +{ + uint32_t ret = XBEGIN_INIT; + + asm volatile( + "xbegin 1f\n" + "1:\n" + : "+a" (ret) + :: "memory"); + + return ret; +} + +static inline void xend(void) +{ + asm volatile( + "xend\n" + ::: "memory"); +} diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..e93fe2c --- /dev/null +++ b/src/util.c @@ -0,0 +1,88 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#ifdef HAVE_SCHED_H +#include +#endif + +#include + +const char *mastik_version() { + return PACKAGE_VERSION; +} + +void *map_offset(const char *file, uint64_t offset) { + int fd = open(file, O_RDONLY); + if (fd < 0) + return NULL; + + char *mapaddress = MAP_FAILED; +#ifdef HAVE_MMAP64 + mapaddress = mmap(0, sysconf(_SC_PAGE_SIZE), PROT_READ, MAP_PRIVATE, fd, offset & ~(sysconf(_SC_PAGE_SIZE) -1)); +#else + mapaddress = mmap(0, sysconf(_SC_PAGE_SIZE), PROT_READ, MAP_PRIVATE, fd, ((off_t)offset) & ~(sysconf(_SC_PAGE_SIZE) -1)); +#endif + close(fd); + if (mapaddress == MAP_FAILED) + return NULL; + return (void *)(mapaddress+(offset & (sysconf(_SC_PAGE_SIZE) -1))); +} + + +void unmap_offset(void *address) { + munmap((char *)(((uintptr_t)address) & ~(sysconf(_SC_PAGE_SIZE) -1)), + sysconf(_SC_PAGE_SIZE)); +} + + +void delayloop(uint32_t cycles) { + uint64_t start = rdtscp64(); + while ((rdtscp64()-start) < cycles) + ; +} + +int setaffinity(int cpu) { +#ifdef HAVE_SCHED_SETAFFINITY + cpu_set_t cs; + CPU_ZERO(&cs); + CPU_SET(cpu, &cs); + if (sched_setaffinity(0, sizeof(cs), &cs) < 0) + return -1; + return 0; +#else + return -1; +#endif +} + +int ncpus(void) { +#ifdef _SC_NPROCESSORS_ONLN + return sysconf(_SC_NPROCESSORS_ONLN); +#else + return -1; +#endif +} + + diff --git a/src/vlist.c b/src/vlist.c new file mode 100644 index 0000000..80492af --- /dev/null +++ b/src/vlist.c @@ -0,0 +1,119 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include + +#include "vlist.h" + +extern void *vl_get(vlist_t vl, int ind); +extern int vl_len(vlist_t vl); + +#define VLIST_DEF_SIZE 16 + +vlist_t vl_new() { + vlist_t vl = (vlist_t)malloc(sizeof(struct vlist)); + vl->size = VLIST_DEF_SIZE; + vl->data = (void **)calloc(VLIST_DEF_SIZE, sizeof(void *)); + vl->len = 0; + return vl; +} + +void vl_free(vlist_t vl) { + assert(vl != NULL); + free(vl->data); + bzero(vl, sizeof(struct vlist)); + free(vl); +} + +void vl_set(vlist_t vl, int ind, void *dat) { + assert(vl != NULL); + assert(dat != NULL); + assert(ind < vl->len); + vl->data[ind] = dat; +} + +static void vl_setsize(vlist_t vl, int size) { + assert(vl != NULL); + assert(size >= vl->len); + void **old = vl->data; + vl->data = (void **)realloc(old, size * sizeof(void *)); + vl->size = size; +} + + +int vl_push(vlist_t vl, void *dat) { + assert(vl != NULL); + assert(dat != NULL); + if (vl->len == vl->size) + vl_setsize(vl, vl->size * 2); + assert(vl->len < vl->size); + vl->data[vl->len++] = dat; + return vl->len - 1; +} + +void *vl_pop(vlist_t vl) { + assert(vl != NULL); + if (vl->len == 0) + return NULL; + return vl->data[--vl->len]; +} + +void *vl_del(vlist_t vl, int ind) { + assert(vl != NULL); + assert(ind < vl->len); + void * rv = vl->data[ind]; + vl->data[ind] = vl->data[--vl->len]; + return rv; +} + +void *vl_poprand(vlist_t vl) { + assert(vl != NULL); + if (vl->len == 0) + return NULL; + int ind = random() % vl->len; + void *rv = vl->data[ind]; + vl_del(vl, ind); + return rv; +} + +void vl_insert(vlist_t vl, int ind, void *dat) { + assert(vl != NULL); + assert(dat != NULL); + assert(ind <= vl->len); + if (ind == vl->len) { + vl_push(vl, dat); + } else { + vl_push(vl, vl->data[ind]); + vl->data[ind] = dat; + } +} + +int vl_find(vlist_t vl, void *dat) { + assert(vl != NULL); + assert(dat != NULL); + for (int i = 0; i < vl->len; i++) + if (vl->data[i] == dat) + return i; + return -1; +} + diff --git a/src/vlist.h b/src/vlist.h new file mode 100644 index 0000000..3baaff4 --- /dev/null +++ b/src/vlist.h @@ -0,0 +1,64 @@ +/* + * Copyright 2016 CSIRO + * + * This file is part of Mastik. + * + * Mastik is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Mastik is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mastik. If not, see . + */ + +#ifndef __VLIST_H__ +#define __VLIST_H__ + +#include + +typedef struct vlist *vlist_t; + +vlist_t vl_new(); +void vl_free(vlist_t vl); + +inline void *vl_get(vlist_t vl, int ind); +void vl_set(vlist_t vl, int ind, void *dat); +int vl_push(vlist_t vl, void *dat); +void *vl_pop(vlist_t vl); +void *vl_poprand(vlist_t vl); +void *vl_del(vlist_t vl, int ind); +inline int vl_len(vlist_t vl); +void vl_insert(vlist_t vl, int ind, void *dat); +int vl_find(vlist_t vl, void *dat); + + +//--------------------------------------------- +// Implementation details +//--------------------------------------------- + +struct vlist { + int size; + int len; + void **data; +}; + +inline void *vl_get(vlist_t vl, int ind) { + assert(vl != NULL); + assert(ind < vl->len); + return vl->data[ind]; +} + +inline int vl_len(vlist_t vl) { + assert(vl != NULL); + return vl->len; +} + + + +#endif // __VLIST_H__ diff --git a/tests/.gitignore b/tests/.gitignore new file mode 100644 index 0000000..39ee7c8 --- /dev/null +++ b/tests/.gitignore @@ -0,0 +1,8 @@ +l1irattle +l1rattle +testfr +testl1 +testl1i +testl3 +testl1aes +testl2aes diff --git a/tests/Makefile.in b/tests/Makefile.in new file mode 100644 index 0000000..f77f397 --- /dev/null +++ b/tests/Makefile.in @@ -0,0 +1,41 @@ +FILES= \ + l1irattle.c \ + l1rattle.c \ + testfr.c \ + testl1.c \ + testl1i.c \ + testl3.c \ + testl1aes.c \ + testl2aes.c + +prefix=@prefix@ +exec_prefix=@exec_prefix@ + +FTARGETS=$(FILES:.c=) +FOBJS=${FILES:.c=.o} +CFLAGS=@CFLAGS@ -I.. +LDFLAGS=-L../src/ -g +LDLIBS=-lmastik @LIBS@ + +TARGETS=${FTARGETS} testl1aes +OBJS=${FOBJS} testl1aes.o aes_core.o + +all: ${TARGETS} + +${TARGETS}: %: %.o + ${CC} ${LDFLAGS} -o $@ $@.o ${LDLIBS} + +testl1aes: testl1aes.o aes_core.o + ${CC} ${LDFLAGS} -o $@ testl1aes.o aes_core.o ${LDLIBS} + +testl2aes: testl2aes.o aes_core.o + ${CC} ${LDFLAGS} -o $@ $^ ${LDLIBS} + +install: + + +clean: + rm -f ${TARGETS} ${OBJS} *.sig out + +distclean: clean + rm Makefile \ No newline at end of file diff --git a/tests/aes.h b/tests/aes.h new file mode 100644 index 0000000..8d28343 --- /dev/null +++ b/tests/aes.h @@ -0,0 +1,149 @@ +/* crypto/aes/aes.h */ +/* ==================================================================== + * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + */ + +#ifndef HEADER_AES_H +# define HEADER_AES_H + +//# include + +# ifdef OPENSSL_NO_AES +# error AES is disabled. +# endif + +# include + +# define AES_ENCRYPT 1 +# define AES_DECRYPT 0 + +/* + * Because array size can't be a const in C, the following two are macros. + * Both sizes are in bytes. + */ +# define AES_MAXNR 14 +# define AES_BLOCK_SIZE 16 + +#ifdef __cplusplus +extern "C" { +#endif + +/* This should be a hidden type, but EVP requires that the size be known */ +struct aes_key_st { +# ifdef AES_LONG + unsigned long rd_key[4 * (AES_MAXNR + 1)]; +# else + unsigned int rd_key[4 * (AES_MAXNR + 1)]; +# endif + int rounds; +}; +typedef struct aes_key_st AES_KEY; + +const char *AES_options(void); + +int AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); +int AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); + +int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); +int private_AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key); + +void AES_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key); +void AES_decrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key); + +void AES_ecb_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key, const int enc); +void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); +void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num, const int enc); +void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, int *num); +void AES_ctr128_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char ivec[AES_BLOCK_SIZE], + unsigned char ecount_buf[AES_BLOCK_SIZE], + unsigned int *num); +/* NB: the IV is _two_ blocks long */ +void AES_ige_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); +/* NB: the IV is _four_ blocks long */ +void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + const AES_KEY *key2, const unsigned char *ivec, + const int enc); + +int AES_wrap_key(AES_KEY *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, unsigned int inlen); +int AES_unwrap_key(AES_KEY *key, const unsigned char *iv, + unsigned char *out, + const unsigned char *in, unsigned int inlen); + + +#ifdef __cplusplus +} +#endif + +#endif /* !HEADER_AES_H */ diff --git a/tests/aes_core.c b/tests/aes_core.c new file mode 100644 index 0000000..ce90a8d --- /dev/null +++ b/tests/aes_core.c @@ -0,0 +1,1369 @@ +/* crypto/aes/aes_core.c */ +/** + * rijndael-alg-fst.c + * + * @version 3.0 (December 2000) + * + * Optimised ANSI C code for the Rijndael cipher (now AES) + * + * @author Vincent Rijmen + * @author Antoon Bosselaers + * @author Paulo Barreto + * + * This code is hereby placed in the public domain. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* Note: rewritten a little bit to provide error control and an OpenSSL- + compatible API */ + +#ifndef AES_DEBUG +# ifndef NDEBUG +# define NDEBUG +# endif +#endif +#include + +#include +#include +typedef uint32_t u32; +typedef uint32_t u8; +# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3])) +# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); } + +#include "aes.h" + + +#ifndef AES_ASM +/*- +Te0[x] = S [x].[02, 01, 01, 03]; +Te1[x] = S [x].[03, 02, 01, 01]; +Te2[x] = S [x].[01, 03, 02, 01]; +Te3[x] = S [x].[01, 01, 03, 02]; + +Td0[x] = Si[x].[0e, 09, 0d, 0b]; +Td1[x] = Si[x].[0b, 0e, 09, 0d]; +Td2[x] = Si[x].[0d, 0b, 0e, 09]; +Td3[x] = Si[x].[09, 0d, 0b, 0e]; +Td4[x] = Si[x].[01]; +*/ + +static const u32 Te0[256] __attribute__ ((aligned (64)))= { + 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU, + 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U, + 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU, + 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU, + 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U, + 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU, + 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU, + 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, + 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, + 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, + 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U, + 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU, + 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU, + 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U, + 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU, + 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU, + 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU, + 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU, + 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU, + 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U, + 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU, + 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU, + 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU, + 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU, + 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U, + 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U, + 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U, + 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U, + 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU, + 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U, + 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U, + 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU, + 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU, + 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U, + 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U, + 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U, + 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU, + 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U, + 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU, + 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U, + 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU, + 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U, + 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U, + 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU, + 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U, + 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U, + 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U, + 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U, + 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U, + 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U, + 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U, + 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U, + 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU, + 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U, + 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U, + 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U, + 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U, + 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U, + 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U, + 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU, + 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U, + 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U, + 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U, + 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU, +}; +static const u32 Te1[256] = { + 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU, + 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U, + 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU, + 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U, + 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU, + 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U, + 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU, + 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U, + 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U, + 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU, + 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U, + 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U, + 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U, + 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU, + 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U, + 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U, + 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU, + 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U, + 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U, + 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U, + 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU, + 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU, + 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U, + 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU, + 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU, + 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U, + 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU, + 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U, + 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU, + 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U, + 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U, + 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U, + 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU, + 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U, + 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU, + 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U, + 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU, + 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U, + 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U, + 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU, + 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU, + 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU, + 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U, + 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U, + 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU, + 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U, + 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU, + 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U, + 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU, + 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U, + 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU, + 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU, + 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U, + 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU, + 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U, + 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU, + 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U, + 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U, + 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U, + 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU, + 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU, + 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U, + 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU, + 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U, +}; +static const u32 Te2[256] = { + 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU, + 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U, + 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU, + 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U, + 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU, + 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U, + 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU, + 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U, + 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U, + 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU, + 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U, + 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U, + 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U, + 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU, + 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U, + 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U, + 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU, + 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U, + 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U, + 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U, + 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU, + 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU, + 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U, + 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU, + 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU, + 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U, + 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU, + 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U, + 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU, + 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U, + 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U, + 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U, + 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU, + 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U, + 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU, + 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U, + 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU, + 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U, + 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U, + 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU, + 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU, + 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU, + 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U, + 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U, + 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU, + 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U, + 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU, + 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U, + 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU, + 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U, + 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU, + 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU, + 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U, + 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU, + 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U, + 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU, + 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U, + 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U, + 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U, + 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU, + 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU, + 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U, + 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU, + 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U, +}; +static const u32 Te3[256] = { + 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U, + 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U, + 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U, + 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU, + 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU, + 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU, + 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U, + 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU, + 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU, + 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U, + 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U, + 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU, + 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU, + 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU, + 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU, + 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU, + 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U, + 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU, + 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU, + 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U, + 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U, + 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U, + 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U, + 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U, + 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU, + 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U, + 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU, + 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU, + 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U, + 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U, + 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U, + 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU, + 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U, + 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU, + 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU, + 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U, + 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U, + 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU, + 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U, + 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU, + 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U, + 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U, + 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U, + 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U, + 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU, + 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U, + 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU, + 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U, + 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU, + 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U, + 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU, + 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU, + 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU, + 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU, + 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U, + 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U, + 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U, + 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U, + 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U, + 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U, + 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU, + 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U, + 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU, + 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU, +}; + +static const u32 Td0[256] = { + 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U, + 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U, + 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U, + 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU, + 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U, + 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U, + 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU, + 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U, + 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU, + 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U, + 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U, + 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U, + 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U, + 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU, + 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U, + 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU, + 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U, + 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU, + 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U, + 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U, + 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U, + 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU, + 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U, + 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU, + 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U, + 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU, + 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U, + 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU, + 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU, + 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U, + 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU, + 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U, + 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU, + 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U, + 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U, + 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U, + 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU, + 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U, + 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U, + 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU, + 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U, + 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U, + 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U, + 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U, + 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U, + 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU, + 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U, + 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U, + 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U, + 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U, + 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U, + 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU, + 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU, + 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU, + 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU, + 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U, + 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U, + 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU, + 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU, + 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U, + 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU, + 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U, + 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U, + 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U, +}; +static const u32 Td1[256] = { + 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU, + 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U, + 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU, + 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U, + 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U, + 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U, + 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U, + 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U, + 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U, + 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU, + 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU, + 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU, + 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U, + 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU, + 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U, + 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U, + 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U, + 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU, + 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU, + 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U, + 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU, + 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U, + 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU, + 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU, + 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U, + 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U, + 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U, + 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU, + 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U, + 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU, + 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U, + 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U, + 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U, + 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU, + 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U, + 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U, + 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U, + 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U, + 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U, + 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U, + 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU, + 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU, + 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U, + 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU, + 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U, + 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU, + 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU, + 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U, + 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU, + 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U, + 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U, + 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U, + 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U, + 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U, + 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U, + 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U, + 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU, + 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U, + 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U, + 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU, + 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U, + 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U, + 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U, + 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U, +}; +static const u32 Td2[256] = { + 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U, + 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U, + 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U, + 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U, + 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU, + 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U, + 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U, + 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U, + 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U, + 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU, + 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U, + 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U, + 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU, + 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U, + 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U, + 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U, + 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U, + 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U, + 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U, + 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU, + 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U, + 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U, + 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U, + 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U, + 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U, + 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU, + 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU, + 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U, + 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU, + 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U, + 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU, + 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU, + 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU, + 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU, + 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U, + 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U, + 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U, + 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U, + 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U, + 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U, + 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U, + 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU, + 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU, + 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U, + 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U, + 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU, + 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU, + 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U, + 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U, + 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U, + 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U, + 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U, + 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U, + 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U, + 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU, + 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U, + 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U, + 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U, + 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U, + 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U, + 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U, + 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU, + 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U, + 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U, +}; +static const u32 Td3[256] = { + 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU, + 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU, + 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U, + 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U, + 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU, + 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU, + 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U, + 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU, + 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U, + 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU, + 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U, + 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U, + 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U, + 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U, + 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U, + 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU, + 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU, + 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U, + 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U, + 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU, + 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU, + 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U, + 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U, + 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U, + 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U, + 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU, + 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U, + 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U, + 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU, + 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU, + 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U, + 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U, + 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U, + 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU, + 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U, + 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U, + 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U, + 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U, + 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U, + 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U, + 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U, + 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU, + 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U, + 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U, + 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU, + 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU, + 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U, + 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU, + 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U, + 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U, + 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U, + 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U, + 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U, + 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U, + 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU, + 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU, + 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU, + 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU, + 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U, + 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U, + 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U, + 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU, + 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U, + 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U, +}; +static const u8 Td4[256] = { + 0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U, + 0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU, + 0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U, + 0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU, + 0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU, + 0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU, + 0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U, + 0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U, + 0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U, + 0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U, + 0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU, + 0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U, + 0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU, + 0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U, + 0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U, + 0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU, + 0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU, + 0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U, + 0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U, + 0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU, + 0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U, + 0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU, + 0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U, + 0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U, + 0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U, + 0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU, + 0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU, + 0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU, + 0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U, + 0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U, + 0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U, + 0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU, +}; +static const u32 rcon[] = { + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ +}; + +/** + * Expand the cipher key into the encryption key schedule. + */ +int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i = 0; + u32 temp; + + if (!userKey || !key) + return -1; + if (bits != 128 && bits != 192 && bits != 256) + return -2; + + rk = key->rd_key; + + if (bits==128) + key->rounds = 10; + else if (bits==192) + key->rounds = 12; + else + key->rounds = 14; + + rk[0] = GETU32(userKey ); + rk[1] = GETU32(userKey + 4); + rk[2] = GETU32(userKey + 8); + rk[3] = GETU32(userKey + 12); + if (bits == 128) { + while (1) { + temp = rk[3]; + rk[4] = rk[0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[5] = rk[1] ^ rk[4]; + rk[6] = rk[2] ^ rk[5]; + rk[7] = rk[3] ^ rk[6]; + if (++i == 10) { + return 0; + } + rk += 4; + } + } + rk[4] = GETU32(userKey + 16); + rk[5] = GETU32(userKey + 20); + if (bits == 192) { + while (1) { + temp = rk[ 5]; + rk[ 6] = rk[ 0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 7] = rk[ 1] ^ rk[ 6]; + rk[ 8] = rk[ 2] ^ rk[ 7]; + rk[ 9] = rk[ 3] ^ rk[ 8]; + if (++i == 8) { + return 0; + } + rk[10] = rk[ 4] ^ rk[ 9]; + rk[11] = rk[ 5] ^ rk[10]; + rk += 6; + } + } + rk[6] = GETU32(userKey + 24); + rk[7] = GETU32(userKey + 28); + if (bits == 256) { + while (1) { + temp = rk[ 7]; + rk[ 8] = rk[ 0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 9] = rk[ 1] ^ rk[ 8]; + rk[10] = rk[ 2] ^ rk[ 9]; + rk[11] = rk[ 3] ^ rk[10]; + if (++i == 7) { + return 0; + } + temp = rk[11]; + rk[12] = rk[ 4] ^ + (Te2[(temp >> 24) ] & 0xff000000) ^ + (Te3[(temp >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(temp >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(temp ) & 0xff] & 0x000000ff); + rk[13] = rk[ 5] ^ rk[12]; + rk[14] = rk[ 6] ^ rk[13]; + rk[15] = rk[ 7] ^ rk[14]; + + rk += 8; + } + } + return 0; +} + +/** + * Expand the cipher key into the decryption key schedule. + */ +int private_AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i, j, status; + u32 temp; + + /* first, start with an encryption schedule */ + status = private_AES_set_encrypt_key(userKey, bits, key); + if (status < 0) + return status; + + rk = key->rd_key; + + /* invert the order of the round keys: */ + for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) { + temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp; + temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; + temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; + temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; + } + /* apply the inverse MixColumn transform to all round keys but the first and the last: */ + for (i = 1; i < (key->rounds); i++) { + rk += 4; + rk[0] = + Td0[Te1[(rk[0] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[0] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[0] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[0] ) & 0xff] & 0xff]; + rk[1] = + Td0[Te1[(rk[1] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[1] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[1] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[1] ) & 0xff] & 0xff]; + rk[2] = + Td0[Te1[(rk[2] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[2] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[2] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[2] ) & 0xff] & 0xff]; + rk[3] = + Td0[Te1[(rk[3] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[3] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[3] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[3] ) & 0xff] & 0xff]; + } + return 0; +} + +/* + * Encrypt a single block + * in and out can overlap + */ +void AES_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key) { + + const u32 *rk; + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + assert(in && out && key); + rk = key->rd_key; + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(in ) ^ rk[0]; + s1 = GETU32(in + 4) ^ rk[1]; + s2 = GETU32(in + 8) ^ rk[2]; + s3 = GETU32(in + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39]; + if (key->rounds > 10) { + /* round 10: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47]; + if (key->rounds > 12) { + /* round 12: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55]; + } + } + rk += key->rounds << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = key->rounds >> 1; + for (;;) { + t0 = + Te0[(s0 >> 24) ] ^ + Te1[(s1 >> 16) & 0xff] ^ + Te2[(s2 >> 8) & 0xff] ^ + Te3[(s3 ) & 0xff] ^ + rk[4]; + t1 = + Te0[(s1 >> 24) ] ^ + Te1[(s2 >> 16) & 0xff] ^ + Te2[(s3 >> 8) & 0xff] ^ + Te3[(s0 ) & 0xff] ^ + rk[5]; + t2 = + Te0[(s2 >> 24) ] ^ + Te1[(s3 >> 16) & 0xff] ^ + Te2[(s0 >> 8) & 0xff] ^ + Te3[(s1 ) & 0xff] ^ + rk[6]; + t3 = + Te0[(s3 >> 24) ] ^ + Te1[(s0 >> 16) & 0xff] ^ + Te2[(s1 >> 8) & 0xff] ^ + Te3[(s2 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Te0[(t0 >> 24) ] ^ + Te1[(t1 >> 16) & 0xff] ^ + Te2[(t2 >> 8) & 0xff] ^ + Te3[(t3 ) & 0xff] ^ + rk[0]; + s1 = + Te0[(t1 >> 24) ] ^ + Te1[(t2 >> 16) & 0xff] ^ + Te2[(t3 >> 8) & 0xff] ^ + Te3[(t0 ) & 0xff] ^ + rk[1]; + s2 = + Te0[(t2 >> 24) ] ^ + Te1[(t3 >> 16) & 0xff] ^ + Te2[(t0 >> 8) & 0xff] ^ + Te3[(t1 ) & 0xff] ^ + rk[2]; + s3 = + Te0[(t3 >> 24) ] ^ + Te1[(t0 >> 16) & 0xff] ^ + Te2[(t1 >> 8) & 0xff] ^ + Te3[(t2 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + (Te2[(t0 >> 24) ] & 0xff000000) ^ + (Te3[(t1 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t2 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t3 ) & 0xff] & 0x000000ff) ^ + rk[0]; + PUTU32(out , s0); + s1 = + (Te2[(t1 >> 24) ] & 0xff000000) ^ + (Te3[(t2 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t3 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t0 ) & 0xff] & 0x000000ff) ^ + rk[1]; + PUTU32(out + 4, s1); + s2 = + (Te2[(t2 >> 24) ] & 0xff000000) ^ + (Te3[(t3 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t0 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t1 ) & 0xff] & 0x000000ff) ^ + rk[2]; + PUTU32(out + 8, s2); + s3 = + (Te2[(t3 >> 24) ] & 0xff000000) ^ + (Te3[(t0 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t1 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t2 ) & 0xff] & 0x000000ff) ^ + rk[3]; + PUTU32(out + 12, s3); +} + +/* + * Decrypt a single block + * in and out can overlap + */ +void AES_decrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key) +{ + + const u32 *rk; + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + assert(in && out && key); + rk = key->rd_key; + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(in ) ^ rk[0]; + s1 = GETU32(in + 4) ^ rk[1]; + s2 = GETU32(in + 8) ^ rk[2]; + s3 = GETU32(in + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39]; + if (key->rounds > 10) { + /* round 10: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47]; + if (key->rounds > 12) { + /* round 12: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55]; + } + } + rk += key->rounds << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = key->rounds >> 1; + for (;;) { + t0 = + Td0[(s0 >> 24) ] ^ + Td1[(s3 >> 16) & 0xff] ^ + Td2[(s2 >> 8) & 0xff] ^ + Td3[(s1 ) & 0xff] ^ + rk[4]; + t1 = + Td0[(s1 >> 24) ] ^ + Td1[(s0 >> 16) & 0xff] ^ + Td2[(s3 >> 8) & 0xff] ^ + Td3[(s2 ) & 0xff] ^ + rk[5]; + t2 = + Td0[(s2 >> 24) ] ^ + Td1[(s1 >> 16) & 0xff] ^ + Td2[(s0 >> 8) & 0xff] ^ + Td3[(s3 ) & 0xff] ^ + rk[6]; + t3 = + Td0[(s3 >> 24) ] ^ + Td1[(s2 >> 16) & 0xff] ^ + Td2[(s1 >> 8) & 0xff] ^ + Td3[(s0 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Td0[(t0 >> 24) ] ^ + Td1[(t3 >> 16) & 0xff] ^ + Td2[(t2 >> 8) & 0xff] ^ + Td3[(t1 ) & 0xff] ^ + rk[0]; + s1 = + Td0[(t1 >> 24) ] ^ + Td1[(t0 >> 16) & 0xff] ^ + Td2[(t3 >> 8) & 0xff] ^ + Td3[(t2 ) & 0xff] ^ + rk[1]; + s2 = + Td0[(t2 >> 24) ] ^ + Td1[(t1 >> 16) & 0xff] ^ + Td2[(t0 >> 8) & 0xff] ^ + Td3[(t3 ) & 0xff] ^ + rk[2]; + s3 = + Td0[(t3 >> 24) ] ^ + Td1[(t2 >> 16) & 0xff] ^ + Td2[(t1 >> 8) & 0xff] ^ + Td3[(t0 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + ((u32)Td4[(t0 >> 24) ] << 24) ^ + ((u32)Td4[(t3 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t2 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t1 ) & 0xff]) ^ + rk[0]; + PUTU32(out , s0); + s1 = + ((u32)Td4[(t1 >> 24) ] << 24) ^ + ((u32)Td4[(t0 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t3 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t2 ) & 0xff]) ^ + rk[1]; + PUTU32(out + 4, s1); + s2 = + ((u32)Td4[(t2 >> 24) ] << 24) ^ + ((u32)Td4[(t1 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t0 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t3 ) & 0xff]) ^ + rk[2]; + PUTU32(out + 8, s2); + s3 = + ((u32)Td4[(t3 >> 24) ] << 24) ^ + ((u32)Td4[(t2 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t1 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t0 ) & 0xff]) ^ + rk[3]; + PUTU32(out + 12, s3); +} + +#else /* AES_ASM */ + +static const u8 Te4[256] = { + 0x63U, 0x7cU, 0x77U, 0x7bU, 0xf2U, 0x6bU, 0x6fU, 0xc5U, + 0x30U, 0x01U, 0x67U, 0x2bU, 0xfeU, 0xd7U, 0xabU, 0x76U, + 0xcaU, 0x82U, 0xc9U, 0x7dU, 0xfaU, 0x59U, 0x47U, 0xf0U, + 0xadU, 0xd4U, 0xa2U, 0xafU, 0x9cU, 0xa4U, 0x72U, 0xc0U, + 0xb7U, 0xfdU, 0x93U, 0x26U, 0x36U, 0x3fU, 0xf7U, 0xccU, + 0x34U, 0xa5U, 0xe5U, 0xf1U, 0x71U, 0xd8U, 0x31U, 0x15U, + 0x04U, 0xc7U, 0x23U, 0xc3U, 0x18U, 0x96U, 0x05U, 0x9aU, + 0x07U, 0x12U, 0x80U, 0xe2U, 0xebU, 0x27U, 0xb2U, 0x75U, + 0x09U, 0x83U, 0x2cU, 0x1aU, 0x1bU, 0x6eU, 0x5aU, 0xa0U, + 0x52U, 0x3bU, 0xd6U, 0xb3U, 0x29U, 0xe3U, 0x2fU, 0x84U, + 0x53U, 0xd1U, 0x00U, 0xedU, 0x20U, 0xfcU, 0xb1U, 0x5bU, + 0x6aU, 0xcbU, 0xbeU, 0x39U, 0x4aU, 0x4cU, 0x58U, 0xcfU, + 0xd0U, 0xefU, 0xaaU, 0xfbU, 0x43U, 0x4dU, 0x33U, 0x85U, + 0x45U, 0xf9U, 0x02U, 0x7fU, 0x50U, 0x3cU, 0x9fU, 0xa8U, + 0x51U, 0xa3U, 0x40U, 0x8fU, 0x92U, 0x9dU, 0x38U, 0xf5U, + 0xbcU, 0xb6U, 0xdaU, 0x21U, 0x10U, 0xffU, 0xf3U, 0xd2U, + 0xcdU, 0x0cU, 0x13U, 0xecU, 0x5fU, 0x97U, 0x44U, 0x17U, + 0xc4U, 0xa7U, 0x7eU, 0x3dU, 0x64U, 0x5dU, 0x19U, 0x73U, + 0x60U, 0x81U, 0x4fU, 0xdcU, 0x22U, 0x2aU, 0x90U, 0x88U, + 0x46U, 0xeeU, 0xb8U, 0x14U, 0xdeU, 0x5eU, 0x0bU, 0xdbU, + 0xe0U, 0x32U, 0x3aU, 0x0aU, 0x49U, 0x06U, 0x24U, 0x5cU, + 0xc2U, 0xd3U, 0xacU, 0x62U, 0x91U, 0x95U, 0xe4U, 0x79U, + 0xe7U, 0xc8U, 0x37U, 0x6dU, 0x8dU, 0xd5U, 0x4eU, 0xa9U, + 0x6cU, 0x56U, 0xf4U, 0xeaU, 0x65U, 0x7aU, 0xaeU, 0x08U, + 0xbaU, 0x78U, 0x25U, 0x2eU, 0x1cU, 0xa6U, 0xb4U, 0xc6U, + 0xe8U, 0xddU, 0x74U, 0x1fU, 0x4bU, 0xbdU, 0x8bU, 0x8aU, + 0x70U, 0x3eU, 0xb5U, 0x66U, 0x48U, 0x03U, 0xf6U, 0x0eU, + 0x61U, 0x35U, 0x57U, 0xb9U, 0x86U, 0xc1U, 0x1dU, 0x9eU, + 0xe1U, 0xf8U, 0x98U, 0x11U, 0x69U, 0xd9U, 0x8eU, 0x94U, + 0x9bU, 0x1eU, 0x87U, 0xe9U, 0xceU, 0x55U, 0x28U, 0xdfU, + 0x8cU, 0xa1U, 0x89U, 0x0dU, 0xbfU, 0xe6U, 0x42U, 0x68U, + 0x41U, 0x99U, 0x2dU, 0x0fU, 0xb0U, 0x54U, 0xbbU, 0x16U +}; +static const u32 rcon[] = { + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ +}; + +/** + * Expand the cipher key into the encryption key schedule. + */ +int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + u32 *rk; + int i = 0; + u32 temp; + + if (!userKey || !key) + return -1; + if (bits != 128 && bits != 192 && bits != 256) + return -2; + + rk = key->rd_key; + + if (bits==128) + key->rounds = 10; + else if (bits==192) + key->rounds = 12; + else + key->rounds = 14; + + rk[0] = GETU32(userKey ); + rk[1] = GETU32(userKey + 4); + rk[2] = GETU32(userKey + 8); + rk[3] = GETU32(userKey + 12); + if (bits == 128) { + while (1) { + temp = rk[3]; + rk[4] = rk[0] ^ + ((u32)Te4[(temp >> 16) & 0xff] << 24) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 16) ^ + ((u32)Te4[(temp ) & 0xff] << 8) ^ + ((u32)Te4[(temp >> 24) ]) ^ + rcon[i]; + rk[5] = rk[1] ^ rk[4]; + rk[6] = rk[2] ^ rk[5]; + rk[7] = rk[3] ^ rk[6]; + if (++i == 10) { + return 0; + } + rk += 4; + } + } + rk[4] = GETU32(userKey + 16); + rk[5] = GETU32(userKey + 20); + if (bits == 192) { + while (1) { + temp = rk[ 5]; + rk[ 6] = rk[ 0] ^ + ((u32)Te4[(temp >> 16) & 0xff] << 24) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 16) ^ + ((u32)Te4[(temp ) & 0xff] << 8) ^ + ((u32)Te4[(temp >> 24) ]) ^ + rcon[i]; + rk[ 7] = rk[ 1] ^ rk[ 6]; + rk[ 8] = rk[ 2] ^ rk[ 7]; + rk[ 9] = rk[ 3] ^ rk[ 8]; + if (++i == 8) { + return 0; + } + rk[10] = rk[ 4] ^ rk[ 9]; + rk[11] = rk[ 5] ^ rk[10]; + rk += 6; + } + } + rk[6] = GETU32(userKey + 24); + rk[7] = GETU32(userKey + 28); + if (bits == 256) { + while (1) { + temp = rk[ 7]; + rk[ 8] = rk[ 0] ^ + ((u32)Te4[(temp >> 16) & 0xff] << 24) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 16) ^ + ((u32)Te4[(temp ) & 0xff] << 8) ^ + ((u32)Te4[(temp >> 24) ]) ^ + rcon[i]; + rk[ 9] = rk[ 1] ^ rk[ 8]; + rk[10] = rk[ 2] ^ rk[ 9]; + rk[11] = rk[ 3] ^ rk[10]; + if (++i == 7) { + return 0; + } + temp = rk[11]; + rk[12] = rk[ 4] ^ + ((u32)Te4[(temp >> 24) ] << 24) ^ + ((u32)Te4[(temp >> 16) & 0xff] << 16) ^ + ((u32)Te4[(temp >> 8) & 0xff] << 8) ^ + ((u32)Te4[(temp ) & 0xff]); + rk[13] = rk[ 5] ^ rk[12]; + rk[14] = rk[ 6] ^ rk[13]; + rk[15] = rk[ 7] ^ rk[14]; + + rk += 8; + } + } + return 0; +} + +/** + * Expand the cipher key into the decryption key schedule. + */ +int private_AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i, j, status; + u32 temp; + + /* first, start with an encryption schedule */ + status = private_AES_set_encrypt_key(userKey, bits, key); + if (status < 0) + return status; + + rk = key->rd_key; + + /* invert the order of the round keys: */ + for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) { + temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp; + temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; + temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; + temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; + } + /* apply the inverse MixColumn transform to all round keys but the first and the last: */ + for (i = 1; i < (key->rounds); i++) { + rk += 4; + for (j = 0; j < 4; j++) { + u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m; + + tp1 = rk[j]; + m = tp1 & 0x80808080; + tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^ + ((m - (m >> 7)) & 0x1b1b1b1b); + m = tp2 & 0x80808080; + tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^ + ((m - (m >> 7)) & 0x1b1b1b1b); + m = tp4 & 0x80808080; + tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^ + ((m - (m >> 7)) & 0x1b1b1b1b); + tp9 = tp8 ^ tp1; + tpb = tp9 ^ tp2; + tpd = tp9 ^ tp4; + tpe = tp8 ^ tp4 ^ tp2; +#if defined(ROTATE) + rk[j] = tpe ^ ROTATE(tpd,16) ^ + ROTATE(tp9,24) ^ ROTATE(tpb,8); +#else + rk[j] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^ + (tp9 >> 8) ^ (tp9 << 24) ^ + (tpb >> 24) ^ (tpb << 8); +#endif + } + } + return 0; +} + +#endif /* AES_ASM */ diff --git a/tests/l1irattle.c b/tests/l1irattle.c new file mode 100644 index 0000000..a822b49 --- /dev/null +++ b/tests/l1irattle.c @@ -0,0 +1,25 @@ +#include +#include +#include +#include +uint8_t *p; + +typedef void (*fptr)(void); + +#define RET_OPCODE 0xC3 +int main(int c, char **v) { + p = mmap(0, 4096, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); + for (int i = 0; i < 4096; i++) + p[i] = RET_OPCODE; + + while (1) { + for (int i = 0; i < 32000; i++) + (*((fptr)(p + 1880)))(); + for (int i = 0; i < 32000; i++) + (*((fptr)(p + 880)))(); + for (int i = 0; i < 32000; i++) + (*((fptr)(p + 2880)))(); + for (int i = 0; i < 64000; i++) + (*((fptr)(p + 880)))(); + } +} diff --git a/tests/l1rattle.c b/tests/l1rattle.c new file mode 100644 index 0000000..226c007 --- /dev/null +++ b/tests/l1rattle.c @@ -0,0 +1,14 @@ +#include +#include +#include +#include + char *p; +int main(int c, char **v) { + p = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); + while (1) { + for (int i = 0; i < 64000; i++) + p[1880]++; + for (int i = 0; i < 64000; i++) + p[880]++; + } +} diff --git a/tests/testfr.c b/tests/testfr.c new file mode 100644 index 0000000..13a7e61 --- /dev/null +++ b/tests/testfr.c @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include +#include + +char a[1024]; + + +int main(int ac, char **v) { + fr_t fr = fr_prepare(); + uint16_t results[1000*2]; + int fd = open(v[1], O_RDONLY); + void *p = mmap(0, 4096, PROT_READ, MAP_PRIVATE, fd, 0); + if (p == MAP_FAILED) { + perror("mmap"); + exit(1); + } + close(fd); + + fr_monitor(fr, p); + int count = fr_repeatedprobe(fr, 1000, results, 100000); + printf("%d\n", count); + for (int i = 0; i < count; i++) { + printf("%3u ", results[i]); + if (i % 20 == 19) + putchar('\n'); + } + putchar('\n'); + + return 0; +} + diff --git a/tests/testl1.c b/tests/testl1.c new file mode 100644 index 0000000..82cade0 --- /dev/null +++ b/tests/testl1.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include + +#include + +uint16_t res[400][64]; + +volatile int a; + +int main(int c, char **v) { + int rmap[64]; + int map[64]; + srandom(time(NULL)); + l1pp_t l1 = l1_prepare(NULL); + if (l1_getmonitoredset(l1, rmap, 64) != 64) { + fprintf(stderr, "Expected 64 monitored sets\n"); + exit(1); + } + for (int i = 0; i < 64; i++) + map[rmap[i]] = i; + for (int i = 0; i < 1024*1024*1024; i++) + a+=i; + for (int i = 0; i < 400; i++) + res[i][0] = 1; + for (int i = 0; i < 200; i++) { + l1_probe(l1, res[i*2]); + l1_bprobe(l1, res[i*2+1]); + } + for (int i = 0; i < 400; i++) { + for (int j = 0; j < 64; j++) + printf("%u ", res[i][map[j]]); + putchar('\n'); + } + + return 0; +} diff --git a/tests/testl1aes.c b/tests/testl1aes.c new file mode 100644 index 0000000..d110c45 --- /dev/null +++ b/tests/testl1aes.c @@ -0,0 +1,218 @@ +#include +#include +#include +#include +#include +#include +#include "aes.h" + +#include +#include + +#define AESSIZE 16 + +#define NSAMPLES 100000 + +typedef uint8_t aes_t[AESSIZE]; + +void usage(char *p) { + fprintf(stderr, "Usage: %s -aAhH [-s ]\n", p); + exit(1); +} + +void tobinary(char *data, aes_t aes) { + assert(strlen(data)==AESSIZE*2); + unsigned int x; + for (int i = 0; i < AESSIZE; i++) { + sscanf(data+i*2, "%2x", &x); + aes[i] = x; + } +} + +void grayspace(int64_t intensity, int64_t min, int64_t max, char c) { + printf("\e[48;5;%ld;31;1m%c\e[0m", 232+((intensity - min) *24)/(max - min), c); +} + +void display(int counts[256], int64_t data[256][ST_TRACEWIDTH], int guess, int offset) { + int64_t min = INT64_MAX; + int64_t max = INT64_MIN; + for (int i = 0; i < 256; i++) + if (counts[i]) + for (int j = 0; j < L1_SETS; j++){ + if (min > data[i][j]) + min = data[i][j]; + if (max < data[i][j]) + max = data[i][j]; + } + + if (max == min) + max++; + for (int i = 0; i < 256; i++) { + if (counts[i]) { + printf("%02X. ", i); + int set = (((i >> 4) ^ guess) + offset) % L1_SETS; + if (offset < 0) + set = -1; + for (int j = 0; j < L1_SETS; j++) { + grayspace(data[i][j], min, max, set == j ? '#' : ' '); + } + printf("\n"); + } + } +} + +void analyse(int64_t data[256][ST_TRACEWIDTH], uint8_t *key, int *offset) { + int64_t max = INT64_MIN; + + for (int guess = 0; guess < 16; guess++) { + for (int off = 0; off < L1_SETS; off++) { + int64_t sum = 0LL; + for (int pt = 0; pt < 16; pt++) { + int set = (off + (pt ^ guess)) % L1_SETS; + sum += data[pt << 4][set]; + } + if (sum > max) { + max = sum; + *key = (uint8_t)guess; + *offset = off; + } + } + } +} + + +void crypto(uint8_t *input, uint8_t *output, void *data) { + AES_KEY *aeskey = (AES_KEY *)data; + AES_encrypt(input, output, aeskey); +} + + + + +int main(int ac, char **av) { + int samples = NSAMPLES; + int round = 1; + int analysis = 1; + int heatmap = 1; + int byte = 0; + int ch; + while ((ch = getopt(ac, av, "b:s:12aAhH")) != -1) { + switch (ch){ + case 's': + samples = atoi(optarg); + break; + case '1': + round = 1; + break; + case '2': + round = 2; + break; + case 'a': + analysis = 1; + break; + case 'A': + analysis = 0; + break; + case 'h': + heatmap = 1; + break; + case 'H': + heatmap = 0; + break; + case 'b': + byte = atoi(optarg); + break; + default: + usage(av[0]); + } + } + + if (round == 2) + analysis = 0; + if (!analysis && !heatmap) { + fprintf(stderr, "No output format specified\n"); + usage(av[0]); + } + if (samples <= 0) { + fprintf(stderr, "Negative number of samples\n"); + usage(av[0]); + } + if (byte < 0 || byte >= AESSIZE) { + fprintf(stderr, "Target byte must be in the range 0--15\n"); + usage(av[0]); + } + + + aes_t key; + aes_t keyGuess; + aes_t keySolution; + char * keystr = "2b7e151628aed2a6abf7158809cf4f3c"; + tobinary(keystr, key); + tobinary(keystr, keySolution); + AES_KEY aeskey; + private_AES_set_encrypt_key(key, 128, &aeskey); + + delayloop(1000000000); + + if (round == 1) { + st_clusters_t clusters = syncPrimeProbe(samples, + AESSIZE, + 1, + NULL, + NULL, + crypto, + &aeskey, + 0xf0, + 1); + for (int i = 0; i < 16; i++) { + int key, offset; + printf("Key byte %2d", i); + if (analysis) { + analyse(clusters[i].avg, &keyGuess[i], &offset); + printf(" Guess:%1x-\n", keyGuess[i]); + } else { + offset = -L1_SETS; + printf("\n"); + } + if (heatmap) { + display(clusters[i].count, clusters[i].avg, key, offset); + printf("\n"); + } + } + free(clusters); + } else if (round == 2) { + aes_t fixmask, fixdata; + tobinary("00000000000000000000000000000000", fixmask); + tobinary("00000000000000000000000000000000", fixdata); + + int col0 = (byte + 4 - (byte >> 2) & 3); + for (int row = 0; row < 4; row++) { + int b = row * 4 + ((col0 + row) & 3); + if (b != byte) + fixmask[b] = 0xff; + } + + st_clusters_t clusters = syncPrimeProbe(samples, + AESSIZE, + 1, + fixmask, + fixdata, + crypto, + &aeskey, + 0xff, + 1); + + display(clusters[byte].count, clusters[byte].avg, 0, -L1_SETS); + free(clusters); + } + + for (int i=0; i<16; i++) + { + if (keyGuess[i] != keySolution[i] >> 4) + { + return 1; + } + } + return 0; + +} diff --git a/tests/testl1i.c b/tests/testl1i.c new file mode 100644 index 0000000..afc6f9f --- /dev/null +++ b/tests/testl1i.c @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include + +#include + +uint16_t res[400][64]; + +volatile int a; + +int main(int c, char **v) { + int map[64]; + int rmap[64]; + srandom(time(NULL)); + l1ipp_t l1 = l1i_prepare(); + + if (l1i_getmonitoredset(l1, rmap, 64) != 64) { + fprintf(stderr, "Expected 64 sets\n"); + exit(1); + } + + for (int i = 0; i < 1024*1024*1024; i++) + a+=i; + + putchar('#'); + for (int i = 0; i < 64; i++) { + printf("%2d ", rmap[i]); + map[rmap[i]] = i; + } + putchar('\n'); + + for (int i = 0; i < 400; i++) + res[i][0] = 1; + for (int i = 0; i < 400; i++) + l1i_probe(l1, res[i]); + for (int i = 0; i < 400; i++) { + for (int j = 0; j < 64; j++) + printf("%u ", res[i][map[j]]); + putchar('\n'); + } + + return 0; +} diff --git a/tests/testl2aes.c b/tests/testl2aes.c new file mode 100644 index 0000000..727ab61 --- /dev/null +++ b/tests/testl2aes.c @@ -0,0 +1,218 @@ +#include +#include +#include +#include +#include +#include +#include "aes.h" + +#include +#include + +#define AESSIZE 16 + +#define NSAMPLES 1000000 +#define L2_SETS 1024 + +typedef uint8_t aes_t[AESSIZE]; + +void usage(char *p) { + fprintf(stderr, "Usage: %s -aAhH [-s ]\n", p); + exit(1); +} + +void tobinary(char *data, aes_t aes) { + assert(strlen(data)==AESSIZE*2); + unsigned int x; + for (int i = 0; i < AESSIZE; i++) { + sscanf(data+i*2, "%2x", &x); + aes[i] = x; + } +} + +void grayspace(int64_t intensity, int64_t min, int64_t max, char c) { + printf("\e[48;5;%ld;31;1m%c\e[0m", 232+((intensity - min) *24)/(max - min), c); +} + +void display(int counts[256], int64_t data[256][L2_SETS], int guess, int offset) { + int64_t min = INT64_MAX; + int64_t max = INT64_MIN; + for (int i = 0; i < 256; i++) + if (counts[i]) + for (int j = 0; j < L2_SETS; j++){ + if (min > data[i][j]) + min = data[i][j]; + if (max < data[i][j]) + max = data[i][j]; + } + + if (max == min) + max++; + for (int i = 0; i < 256; i++) { + if (counts[i]) { + printf("%02X. ", i); + int set = (((i >> 4) ^ guess) + offset) % L2_SETS; + if (offset < 0) + set = -1; + for (int j = 0; j < L2_SETS; j++) { + grayspace(data[i][j], min, max, set == j ? '#' : ' '); + } + printf("\n"); + } + } +} + +void analyse(int64_t data[256][L2_SETS], uint8_t *key, int *offset) { + int64_t max = INT64_MIN; + for (int guess = 0; guess < 16; guess++) { + for (int off = 0; off < L2_SETS; off++) { + int64_t sum = 0LL; + for (int pt = 0; pt < 16; pt++) { + int set = (off + (pt ^ guess)) % L2_SETS; + sum += data[pt << 4][set]; + } + if (sum > max) { + max = sum; + *key = (uint8_t)guess; + *offset = off; + } + } + } +} + + +void crypto(uint8_t *input, uint8_t *output, void *data) { + AES_KEY *aeskey = (AES_KEY *)data; + AES_encrypt(input, output, aeskey); +} + + + + +int main(int ac, char **av) { + int samples = NSAMPLES; + int round = 1; + int analysis = 1; + int heatmap = 1; + int byte = 0; + int ch; + while ((ch = getopt(ac, av, "b:s:12aAhH")) != -1) { + switch (ch){ + case 's': + samples = atoi(optarg); + break; + case '1': + round = 1; + break; + case '2': + round = 2; + break; + case 'a': + analysis = 1; + break; + case 'A': + analysis = 0; + break; + case 'h': + heatmap = 1; + break; + case 'H': + heatmap = 0; + break; + case 'b': + byte = atoi(optarg); + break; + default: + usage(av[0]); + } + } + + if (round == 2) + analysis = 0; + if (!analysis && !heatmap) { + fprintf(stderr, "No output format specified\n"); + usage(av[0]); + } + if (samples <= 0) { + fprintf(stderr, "Negative number of samples\n"); + usage(av[0]); + } + if (byte < 0 || byte >= AESSIZE) { + fprintf(stderr, "Target byte must be in the range 0--15\n"); + usage(av[0]); + } + + + aes_t key; + aes_t keyGuess; + aes_t keySolution; + char * keystr = "2b7e151628aed2a6abf7158809cf4f3c"; + tobinary(keystr, key); + tobinary(keystr, keySolution); + AES_KEY aeskey; + private_AES_set_encrypt_key(key, 128, &aeskey); + + delayloop(1000000000); + + if (round == 1) { + st_clusters_t clusters = syncPrimeProbe(samples, + AESSIZE, + 1, + NULL, + NULL, + crypto, + &aeskey, + 0xf0, + 2); + for (int i = 0; i < 16; i++) { + int key, offset; + printf("Key byte %2d", i); + if (analysis) { + analyse(clusters[i].avg, &keyGuess[i], &offset); + printf(" Guess:%1x-\n", keyGuess[i]); + } else { + offset = -L2_SETS; + printf("\n"); + } + if (heatmap) { + display(clusters[i].count, clusters[i].avg, key, offset); + printf("\n"); + } + } + free(clusters); + } else if (round == 2) { + aes_t fixmask, fixdata; + tobinary("00000000000000000000000000000000", fixmask); + tobinary("00000000000000000000000000000000", fixdata); + + int col0 = (byte + 4 - (byte >> 2) & 3); + for (int row = 0; row < 4; row++) { + int b = row * 4 + ((col0 + row) & 3); + if (b != byte) + fixmask[b] = 0xff; + } + + st_clusters_t clusters = syncPrimeProbe(samples, + AESSIZE, + 1, + fixmask, + fixdata, + crypto, + &aeskey, + 0xff, + 2); + + display(clusters[byte].count, clusters[byte].avg, 0, -L2_SETS); + free(clusters); + } + + for (int i=0; i<16; i++) + { + if (keyGuess[i] != keySolution[i] >> 4) + { + return 1; + } + } + return 0; + +} diff --git a/tests/testl3.c b/tests/testl3.c new file mode 100644 index 0000000..45080af --- /dev/null +++ b/tests/testl3.c @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include +#include + +#include + +uint16_t res[400][64]; + +void progressNotification(int a1, int a2, void *data) { + int *count = (int *)data; + printf("# %d: %d/%d\n", *count, a1, a2); + (*count)++; +} + +volatile int a = 0; + +int main(int c, char **v) { + for (int i = 0; i < 1024*1024*1024; i++) + a+=i; + + + int map[64]; + srandom(time(NULL)); + struct l3info l3info; + bzero(&l3info, sizeof(l3info)); + int setcount = 0; + l3info.progressNotification = progressNotification; + l3info.progressNotificationData = &setcount; + //l3info.flags = L3FLAG_NOHUGEPAGES|L3FLAG_USEPTE; + l3pp_t l3 = l3_prepare(&l3info, NULL); + + int nsets = l3_getSets(l3); + printf("# Found %d sets of %d ways. Total size %d KB\n", nsets, l3_getAssociativity(l3), (l3_getAssociativity(l3) * nsets) /16); + + if (nsets <= 0 || l3_getAssociativity(l3) <= 0) + { + exit(1); + } + + for (int i = 0; i < nsets; i+= 64) + l3_monitor(l3, i); + + printf("# Setup done\n"); + int n = 8192/64; + uint16_t res[8192/64*400]; + + for (int i = 0; i < 400;) { + l3_probecount(l3, res + n * i++); + l3_bprobecount(l3, res + n * i++); + } + + printf("# Probing done\n"); + for (int i = 0; i < 400; i++) { + for (int j = 0; j < n; j++) + printf("%u ", res[n * i + j]); + putchar('\n'); + } + + return 0; +} diff --git a/tools/Doubloon/COPYING b/tools/Doubloon/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/tools/Doubloon/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/tools/Doubloon/Makefile.in b/tools/Doubloon/Makefile.in new file mode 100644 index 0000000..8bf78fc --- /dev/null +++ b/tools/Doubloon/Makefile.in @@ -0,0 +1,44 @@ +SRCS=${wildcard src/*.py} +ICONS=${wildcard data/icons/*.png} + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +datarootdir=@datarootdir@ +datadir=@datadir@ + +mastiktoolsdir=${datadir}/mastik/tools +doubloonsrcdir=${mastiktoolsdir}/doubloon + +edit = sed \ + -e 's|@DOUBLOON_TEXTBOX_HEIGHT[@]|@DOUBLOON_TEXTBOX_HEIGHT@|g' \ + -e 's|@DOUBLOON_HAVE_DWARF[@]|@DOUBLOON_HAVE_DWARF@|g' \ + -e 's|@DOUBLOON_EXPERIMENTAL[@]|@DOUBLOON_EXPERIMENTAL@|g' \ + -e 's|@DOUBLOON_INSTALL_DATADIR[@]|${doubloonsrcdir}/data|g' + + +all: doubloon src/config.py + + +install: all + install -d ${doubloonsrcdir} + install ${SRCS} ${doubloonsrcdir} + install src/config.py ${doubloonsrcdir} + cp -r data ${doubloonsrcdir} + install -d @bindir@ + install doubloon @bindir@ + +doubloon: + echo "#!/bin/bash" > doubloon + echo "@PYTHON@ ${doubloonsrcdir}" >> doubloon + chmod +x doubloon + +src/config.py: src/config.py.in + rm -f src/config.py + ${edit} src/config.py.in > src/config.py + +clean: + rm -f doubloon src/config.py + + +distclean: clean + rm Makefile diff --git a/tools/Doubloon/README.md b/tools/Doubloon/README.md new file mode 100755 index 0000000..18d3b29 --- /dev/null +++ b/tools/Doubloon/README.md @@ -0,0 +1,48 @@ +# Doubloon + + +## About +Doubloon is a tool for conducting and analysing CPU cache side-channel attacks. Doubloon provides a UI for configuring attacks and victim programs with support for remote attacks through SSH. Attacks are ran quickly and results are immediately graphed. Doubloon provides an easy interface to analyse and filter results with a live visualisation. Attack configurations and results can be saved and loaded or just the data can be imported and exported to view. + +Currently Doubloon only supports Flush+Reload attacks. + + +## Required dependencies +- Python 3 (tested with 3.7) +- wxPython 4 (available through pip3 or other sources, https://wxpython.org/pages/downloads/index.html) +- numpy (available through pip3) +- paramiko (available through pip3) + + +## Setup +Run the 'setup' script to check if all dependencies are installed. + + +## Run +Use the 'run' script to start the program + + +## Credit +- https://icons8.com for toolbar icons + + +## Quick start guide + +### Configure attack +Click the gears in the toolbar to open the attack configuration window. Select the type of attack you would like to use and fill in the attack parameters. 'General' is for any attack where 'FR-trace' uses the FR-trace binary from Mastik. Optionally a victim program can run as well and the attack can be ran remotely through SSH. The programs will need to be on the host computer. This menu can stay open and the configuration modified at any time. + +### Running an attack +Use the play button in the toolbar to run the attack program. Once it finishes the results will be displayed. The attack can be stopped at anytime by the cancel button. If a victim program is specified, it will run as well. + +### Graph +The graph presents the results of the attack. The arrow keys can be used to zoom and pan the graph. A subsection can be viewed though a click and drag selection. The scroll bar at the top shows the current selection and can be dragged to pan. + +### Graph options +The graph limits are shown and can be modified. The Y limits can only be changed here. The attack threshold can be modified as well. Missing values can be interpolated or not be drawn. Values can be displayed as a binary value depending if they are above or below the threshold. Certain sets of results can be disabled or enabled as well. + +### Saving +The application state, which includes attack configuration, attack results and graph options, can be saved and loaded later. Use the save icon to create a file with this information (SSH password not included) and use the folder icon to load state from a file. Only the attack results can be exported or imported using the export and import buttons in the toolbar. + +### Customisation +Some default values and options can be modified in 'src/config.py' and 'src/State.py' where indicated. Options like default attack parameters and many graph properties can be changed. + diff --git a/tools/Doubloon/VERSION b/tools/Doubloon/VERSION new file mode 100644 index 0000000..8acdd82 --- /dev/null +++ b/tools/Doubloon/VERSION @@ -0,0 +1 @@ +0.0.1 diff --git a/tools/Doubloon/data/icons/config-26.png b/tools/Doubloon/data/icons/config-26.png new file mode 100755 index 0000000..9a20408 Binary files /dev/null and b/tools/Doubloon/data/icons/config-26.png differ diff --git a/tools/Doubloon/data/icons/config-52.png b/tools/Doubloon/data/icons/config-52.png new file mode 100755 index 0000000..d783edd Binary files /dev/null and b/tools/Doubloon/data/icons/config-52.png differ diff --git a/tools/Doubloon/data/icons/export-26.png b/tools/Doubloon/data/icons/export-26.png new file mode 100755 index 0000000..97feb5f Binary files /dev/null and b/tools/Doubloon/data/icons/export-26.png differ diff --git a/tools/Doubloon/data/icons/export-52.png b/tools/Doubloon/data/icons/export-52.png new file mode 100755 index 0000000..102ec7e Binary files /dev/null and b/tools/Doubloon/data/icons/export-52.png differ diff --git a/tools/Doubloon/data/icons/import-26.png b/tools/Doubloon/data/icons/import-26.png new file mode 100755 index 0000000..5e5de31 Binary files /dev/null and b/tools/Doubloon/data/icons/import-26.png differ diff --git a/tools/Doubloon/data/icons/import-52.png b/tools/Doubloon/data/icons/import-52.png new file mode 100755 index 0000000..38b20c6 Binary files /dev/null and b/tools/Doubloon/data/icons/import-52.png differ diff --git a/tools/Doubloon/data/icons/open-26.png b/tools/Doubloon/data/icons/open-26.png new file mode 100644 index 0000000..f35c618 Binary files /dev/null and b/tools/Doubloon/data/icons/open-26.png differ diff --git a/tools/Doubloon/data/icons/open-52.png b/tools/Doubloon/data/icons/open-52.png new file mode 100755 index 0000000..a8aa128 Binary files /dev/null and b/tools/Doubloon/data/icons/open-52.png differ diff --git a/tools/Doubloon/data/icons/play-26.png b/tools/Doubloon/data/icons/play-26.png new file mode 100755 index 0000000..921e191 Binary files /dev/null and b/tools/Doubloon/data/icons/play-26.png differ diff --git a/tools/Doubloon/data/icons/play-52.png b/tools/Doubloon/data/icons/play-52.png new file mode 100755 index 0000000..6bfe27f Binary files /dev/null and b/tools/Doubloon/data/icons/play-52.png differ diff --git a/tools/Doubloon/data/icons/save-26.png b/tools/Doubloon/data/icons/save-26.png new file mode 100755 index 0000000..c96c81d Binary files /dev/null and b/tools/Doubloon/data/icons/save-26.png differ diff --git a/tools/Doubloon/data/icons/save-52.png b/tools/Doubloon/data/icons/save-52.png new file mode 100755 index 0000000..d25526f Binary files /dev/null and b/tools/Doubloon/data/icons/save-52.png differ diff --git a/tools/Doubloon/data/icons/stop-26.png b/tools/Doubloon/data/icons/stop-26.png new file mode 100755 index 0000000..6c2adb6 Binary files /dev/null and b/tools/Doubloon/data/icons/stop-26.png differ diff --git a/tools/Doubloon/data/icons/stop-52.png b/tools/Doubloon/data/icons/stop-52.png new file mode 100755 index 0000000..a4f8492 Binary files /dev/null and b/tools/Doubloon/data/icons/stop-52.png differ diff --git a/tools/Doubloon/data/icons/x86-26.png b/tools/Doubloon/data/icons/x86-26.png new file mode 100755 index 0000000..ee5df95 Binary files /dev/null and b/tools/Doubloon/data/icons/x86-26.png differ diff --git a/tools/Doubloon/run b/tools/Doubloon/run new file mode 100755 index 0000000..13d5348 --- /dev/null +++ b/tools/Doubloon/run @@ -0,0 +1,3 @@ +#!/bin/bash + +python3 src \ No newline at end of file diff --git a/tools/Doubloon/setup b/tools/Doubloon/setup new file mode 100755 index 0000000..0224442 --- /dev/null +++ b/tools/Doubloon/setup @@ -0,0 +1,79 @@ +#!/bin/bash + +# Text coloring +RED='\033[0;31m' +NC='\033[0m' + +# General python modules required +declare -a pyModules=("numpy" "paramiko" "matplotlib" "tqdm") + +# Check python 3 is available +echo "Checking for Python 3..." +pyVersion="$(python3 -V)" +if [[ $? == 0 ]] +then + echo "Python 3 found" +else + printf ${RED} + echo "ERROR: Python 3 unavailable" + echo "Please install Python 3 and ensure it is available through 'python3'" + printf ${NC} + + exit 1 +fi + +# wxPython is a special case, check seperately with addition information +echo "Checking for 'wx' python module (wxPython)..." +$(python3 -c "import wx") +if [[ $? == 0 ]] +then + echo "'wx' module available" +else + printf ${RED} + echo "ERROR: 'wx' module unavailable" + echo "Try 'pip3 install -U wxPython'" + echo "Otherwise see here: https://wiki.wxpython.org/How%20to%20install%20wxPython" + printf ${NC} + + exit 1 +fi + +# Check general python modules are installed +missing=0 +missingModules=() +for module in "${pyModules[@]}" +do + echo "Checking for '$module' python module..." + + python3 -c "import $module" > /dev/null 2>&1 + + if [[ $? == 0 ]] + then + echo "'$module' module available" + else + printf ${RED} + echo "ERROR: '$module' module unavailable" + printf $NC + missing=1 + missingModules+=($module) + fi +done + +if [[ $missing == 1 ]] +then + printf ${RED} + echo "Missing dependencies. Please install the following modules" + + installText="pip3 install -U" + for module in "${missingModules[@]}" + do + printf "\t$module\n" + installText="$installText $module" + done + echo "Try: '$installText'" + printf $NC + + exit 1 +else + echo "All dependencies installed" +fi \ No newline at end of file diff --git a/tools/Doubloon/src/Application.py b/tools/Doubloon/src/Application.py new file mode 100755 index 0000000..d47fc13 --- /dev/null +++ b/tools/Doubloon/src/Application.py @@ -0,0 +1,340 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx +import math +import numpy +import json +import time + +import config +from util import * +from State import * +from Events import * +from ExternalAttack import * +from GraphView import * +from ToolbarView import * +from PropertiesView import * +from ExternalAttackConfigFrame import * +from Dump import * +from AssemblyFrame import * + + + +# Main application, holds all views and data, coordinates everything +class Application(wx.App): + def __init__(self): + super(Application, self).__init__(False) + + # Application state + # These are passed by reference to other objects so there is only one shared state across the application + self.externalAttackState = ExternalAttackState() + self.graphState = GraphState() + + # Setup external attack object + self.externalAttack = ExternalAttack(self.externalAttackState) + + #setup assembly view object + self.dump = Dump(self.externalAttackState) + + # Setup main window + self.mainFrame = wx.Frame(None) + self.mainFrame.SetTitle(config.applicationName) + self.mainFrame.SetClientSize(config.defaultWindowSize) + self.mainFrame.Center() + + # Setup attack config window + self.externalAttackConfigFrame = ExternalAttackConfigFrame(self.externalAttackState) + + ## Setup machine code view + self.assemblyFrame = AssemblyFrame(self.externalAttackState) + + # Create views + self.graph = GraphView(self.mainFrame, self.graphState) + self.toolbar = ToolbarView(self.mainFrame) + self.properties = PropertiesView(self.mainFrame, self.graphState) + + # Setup views + self.positionViews() + self.updatePropsFromGraph() + + # Bind events + self.mainFrame.Bind(wx.EVT_CLOSE, self.onClose) + self.mainFrame.Bind(wx.EVT_SIZE, self.onSize) + self.Bind(EVT_RUN_EXTERNAL_ATTACK, self.onRunExternalAttack) + self.Bind(EVT_EXTERNAL_ATTACK_DONE, self.onExternalAttackDone) + self.Bind(EVT_UPDATE_LOCATION, self.onUpdateLocation) + self.Bind(EVT_OPEN_EXTERNAL_ATTACK_CONFIG, self.onOpenExternalAttackConfig) + self.Bind(EVT_OPEN_ASSEMBLY, self.onOpenAssemblyFrame) + self.Bind(EVT_RUN_DUMP, self.onRunDump) + self.Bind(EVT_DUMP_DONE, self.onInsertDump) + self.Bind(EVT_GRAPH_PROPS_UPDATE, self.onGraphPropsUpdate) + self.Bind(EVT_GRAPH_UPDATE, self.onGraphUpdate) + self.Bind(EVT_LOAD_DATA, self.onLoadData) + self.Bind(EVT_SAVE_DATA, self.onSaveData) + self.Bind(EVT_LOAD_STATE, self.onLoadState) + self.Bind(EVT_SAVE_STATE, self.onSaveState) + + # Shortcut events + self.Bind(wx.EVT_KEY_DOWN, self.onButton) + + # Start application + def run(self): + self.mainFrame.Show() + self.MainLoop() + + + # On window resize, should resize views + def onSize(self, event): + self.positionViews() + + + # On close, should quit the application + def onClose(self, event): + self.ExitMainLoop() + + + # Positions all views in main window + def positionViews(self): + size = self.mainFrame.GetClientSize() + heightOffset = 40 + widthOffset = config.propertiesWidth + + self.toolbar.SetSize(0, 0, size.Width, heightOffset) + if (config.propertiesAlignment == "right"): + self.graph.SetSize(0, heightOffset, size.Width - widthOffset, size.Height - heightOffset) + self.properties.SetSize(size.Width - widthOffset, heightOffset, widthOffset, size.Height - heightOffset) + else: + self.graph.SetSize(widthOffset, heightOffset, size.Width - widthOffset, size.Height - heightOffset) + self.properties.SetSize(0, heightOffset, widthOffset, size.Height - heightOffset) + + # On button press, handle shortcut + def onButton(self, event): + if (type(event.GetEventObject()) != wx._core.TextCtrl): + if (event.GetKeyCode() == wx.WXK_UP): + self.graph.zoom(1.0/config.graphZoomFactor) + elif (event.GetKeyCode() == wx.WXK_DOWN): + self.graph.zoom(config.graphZoomFactor) + elif (event.GetKeyCode() == wx.WXK_LEFT): + self.graph.shift(-config.graphShiftFactor) + elif (event.GetKeyCode() == wx.WXK_RIGHT): + self.graph.shift(config.graphShiftFactor) + + # Keep proppigating event + event.Skip(True) + + + # External attack functions + + # Should run the attack + def onRunExternalAttack(self, event): + #self.Pro = self.externalAttackState.frMonitor + self.runExternalAttack() + + # Should run objdump + def onRunDump(self, event): + self.runDump() + + + # Run the external attack, or cancel it if already running + def runExternalAttack(self): + if (self.externalAttack.running): + self.toolbar.onExternalAttackDone(None) + self.externalAttack.cancel() + else: + self.externalAttack.run() + + # Run objdump + def runDump(self): + self.assemblyFrame.clear() + self.dump.run() + self.assemblyFrame.open() + + # + def onInsertDump(self, event): + print("try insert result") + if(not self.dump.inserted): + if(self.dump.hasResults): + self.insertDump() + else: + print("already inserted, just show") + + # Insert dumped item into listctrl + def insertDump(self): + print("--try insert-----") + if(self.dump.hasResults): + print("--insert dump result into list-----") + self.assemblyFrame.insert(self.dump.results) + if(self.dump.hasMapResults): + print("---insert map result into list-----") + self.assemblyFrame.insertSource(self.dump.sourceCode) + self.assemblyFrame.s2m = self.dump.s2m + self.assemblyFrame.m2s = self.dump.m2s + self.assemblyFrame.initMonitorList() + print("--insert finished--") + + # On external attack done + def onExternalAttackDone(self, event): + self.toolbar.onExternalAttackDone(None) + if (self.externalAttack.hasResults): + if (self.externalAttackState.type == EXTERNAL_ATTACK_TYPE_FRTRACE): + self.graphState.threshold = self.externalAttackState.frThreshold + self.graphState.data = self.externalAttack.results + self.graphState.monitorLocations = self.externalAttackState.frMonitor.split() + #self.Properties.graphState = self.graphState #update metadata + self.graphData() + + def onUpdateLocation(self, event): + print("update location in application") + self.externalAttack.state.frMonitor = self.assemblyFrame.location + print(self.externalAttack.state.frMonitor) + + # Open attack config frame + def onOpenExternalAttackConfig(self, event): + self.externalAttackConfigFrame.open() + + # Open assembly frame + def onOpenAssemblyFrame(self, event): + self.assemblyFrame.open() + + + # Data functions + + # Ask user for state file and load it + def onLoadState(self,event): + with wx.FileDialog(self.mainFrame, "Save state file", wildcard="*."+config.applicationExtension, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + try: + with open(pathname, "rb") as file: + results = json.loads(file.read()) + self.graphState.fromDictionary(results["graphState"]) + self.externalAttackState.fromDictionary(results["externalAttackState"]) + + # Update UI and graph with new state + self.externalAttackConfigFrame.setConfig() + self.graph.setData(clean=False) + self.updatePropsFromGraph() + self.properties.setGraphProps() + self.properties.setStats() + self.properties.showPanels() + + except Exception as e: + errorMessage("Error loading state file", str(e)) + + + # Ask user for state file to save to + def onSaveState(self,event): + with wx.FileDialog(self.mainFrame, "Save state file", wildcard="*."+config.applicationExtension, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + try: + with open(pathname, 'w') as file: + aState = json.dumps(self.externalAttackState.toDictionary()) + gState = json.dumps(self.graphState.toDictionary()) + + file.write("{\"externalAttackState\": "+aState+", \"graphState\": "+gState+"}") + file.close() + + except Exception as e: + errorMessage("Error saving state file", str(e)) + + # Ask user for data file and load it + def onLoadData(self, event): + with wx.FileDialog(self.mainFrame, "Load data file", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + try: + with open(pathname, 'rb') as file: + lines = file.read().decode('utf-8') + + if (len(lines) < 2): + return + + startTime = time.time() + + self.graphState.data = resultsStringToArray(lines) + + if (config.printMetrics): + print("Finished loading data in " + str(time.time() - startTime)) + self.graphData() + + except Exception as e: + errorMessage("Error loading data file", str(e)) + self.graphState.data = None + + + # Ask user for data file to save to + def onSaveData(self, event): + with wx.FileDialog(self.mainFrame, "Save data file", wildcard="*.txt", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + try: + with open(pathname, 'w') as file: + data = self.graphState.data + + for i in range(0, data.shape[0]): + for j in range(0, data.shape[1]): + if (math.isnan(data[i][j])): + file.write("0 ") + else: + file.write(str(int(data[i][j]))+" ") + file.write("\n") + + file.close() + + except Exception as e: + errorMessage("Error saving data file", str(e)) + + + # Graph functions + + # On graph update event received (graph drawn) + def onGraphUpdate(self, event): + self.updatePropsFromGraph() + + + # Graph the data and reset limits and properties + def graphData(self): + self.graph.setData() + self.updatePropsFromGraph() + self.properties.setStats() + self.properties.showPanels() + + + # Update the graph with received properties + def onGraphPropsUpdate(self, event): + self.graph.Refresh() + + + # Update properties with graph settings + def updatePropsFromGraph(self): + self.properties.setGraphProps() + diff --git a/tools/Doubloon/src/AssemblyFrame.py b/tools/Doubloon/src/AssemblyFrame.py new file mode 100755 index 0000000..cd9cd42 --- /dev/null +++ b/tools/Doubloon/src/AssemblyFrame.py @@ -0,0 +1,362 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author0: Dallas McNeil a1724759@student.adelaide.edu.au +Author1: Feichi Hu feichi@umich.edu +""" + + +import wx + +import config +from util import * +from State import * +from Events import * +from tqdm import tqdm + + + +# Window displaying machine code of chosen executable +class AssemblyFrame(wx.Frame): + def __init__(self, state): + wx.Frame.__init__(self, None, wx.ID_ANY, "Assembly viewer") + # Copy of the common attack state from application + self.panel = wx.Panel(self, wx.ID_ANY) + #self.panel1 = wx.Panel(self, wx.ID_ANY) + #self.panel2 = wx.Panel(self, wx.ID_ANY) + self.state = state + self.s2m = None + self.m2s = None + self.selectedMIdx = -1 + self.selectedSIdx = -1 + self.selectedList = False + self.fileIdx = {} + self.sourceCode = [] + self.searchIdx = [] + self.searchIdxIdx = 0 + self.location = "" + # Setup list view + + self.fileList = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT|wx.SUNKEN_BORDER) + self.fileList.InsertColumn(0,'File', width = 100) + + + self.assemblyList = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT|wx.SUNKEN_BORDER) + self.assemblyList.InsertColumn(0,'File') + self.assemblyList.InsertColumn(1,'LineNum') + self.assemblyList.InsertColumn(2,'Address') + self.assemblyList.InsertColumn(3,'Function') + self.assemblyList.InsertColumn(4,'Instr') + self.assemblyList.InsertColumn(5,'Param', width = 100) + self.assemblyList.InsertColumn(6,'Comment', width = 100) + + self.sourceCodeList = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT|wx.SUNKEN_BORDER) + self.sourceCodeList.InsertColumn(0,'File') + self.sourceCodeList.InsertColumn(1,'LineNum') + self.sourceCodeList.InsertColumn(2,'Source Code',width = 500) + + self.monitorList = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT|wx.SUNKEN_BORDER) + self.monitorList.InsertColumn(0,'Source File',width = 100) + self.monitorList.InsertColumn(1,'LineNum',width = 100) + self.monitorDict = dict() + + self.label = wx.StaticText(self.panel, -1, "Search Code") + self.searchBox = wx.TextCtrl(self.panel,style = wx.TE_PROCESS_ENTER, size=(200,config.textboxHeight)) + self.searchIdx = [] + self.numResult = -1 + self.prompt = wx.StaticText(self.panel, -1, "Press enter to search / jump to next") + + + self.SetTitle("Source Code and Assembly List") + self.SetClientSize(config.defaultWindowSize) + + # Setup UI + largeSizer = wx.BoxSizer(wx.VERTICAL) + sizer = wx.BoxSizer(wx.HORIZONTAL) #bottom + sizer2 = wx.BoxSizer(wx.HORIZONTAL) # top + sizer.Add(self.fileList, 0, wx.ALL|wx.EXPAND, 5) + sizer.Add(self.sourceCodeList, 0, wx.ALL|wx.EXPAND, 5) + sizer.Add(self.assemblyList, 0, wx.ALL|wx.EXPAND, 5) + sizer.Add(self.monitorList, 0, wx.ALL|wx.EXPAND, 5) + sizer2.Add(self.label, 0, wx.ALL, 5) + sizer2.Add(self.searchBox, 0, wx.ALL, 5) + sizer2.Add(self.prompt, 0, wx.ALL, 5) + largeSizer.Add(sizer2, 0, wx.ALL, 5) + largeSizer.Add(sizer, 1, wx.ALL|wx.EXPAND, 5) + self.panel.SetSizer(largeSizer) + #sizer.Fit(self) + #self.Layout() + + # Sizing + self.SetClientSize(20+self.panel.GetClientSize().Width,20+self.panel.GetClientSize().Height) + + # Event bindings + self.Bind(wx.EVT_CLOSE, self.onClose) + self.fileList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectF) + self.assemblyList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectM) + self.sourceCodeList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectS) + self.sourceCodeList.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onMonitorS) + self.monitorList.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onDemonitor) + self.monitorList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectMonitor) + self.searchBox.Bind(wx.EVT_TEXT_ENTER, self.onSearch) + self.searchBox.Bind(wx.EVT_TEXT, self.resetIdx) + + self.setConfig() + + # put items in monitor list into a location string + def generateLocationString(self): + location = "" + for key in self.monitorDict: + location += key + " " + print("--- The monitor locations are ---") + print(location) + self.location = location + evt = updateMonitorLocationEvent() + wx.PostEvent(self, evt) + + def initMonitorList(self): + print("--- Init monitor list ---") + frMonitor = self.state.frMonitor + print(frMonitor) + locations = frMonitor.split() + print(locations) + for i, location in enumerate(locations): + loc = location.split(':') + print("loc",loc) + self.monitorList.Append(loc) + self.monitorDict[location] = self.locateMonitor(loc) + + #find sourceList idx from file and line + def locateMonitor(self, location): + print("Locating monitor location in file") + print(location) + file = location[0] + line = location[1] + for idx in range(self.sourceCodeList.GetItemCount()): + item = self.sourceCodeList.GetItem(idx, 0) + if item.GetText() == file: + lineNum = self.sourceCodeList.GetItem(idx, 1) + if(lineNum.GetText()==line): + print("Target found!!!", file,line,idx) + return idx + return -1 + + + # Open window + def open(self): + print("Try open assem") + self.Show() + self.Maximize(True) + + + # Close window on cross out + def onClose(self, event): + self.setConfig() + self.generateLocationString() + self.Hide() + + + # reset search Idx on new content + def resetIdx(self,event): + self.searchIdx = [] + self.searchIdxIdx = -1 + self.prompt.SetLabel("Press enter to search / jump to next") + + # press enter in the search box + def onSearch(self,event): + keyWord = self.searchBox.GetValue() + if self.searchIdxIdx == -1: + for i in range(len(self.sourceCode)): + if keyWord in self.sourceCode[i]: + self.searchIdx.append(i) + #self.searchIdx = self.sourceCodeList.FindItem(self.searchIdx, keyWord, partial = True) + #add on : Idx == -1 + if self.searchIdx != []: #[] means no search result + self.searchIdxIdx = self.searchIdxIdx + 1 + if self.searchIdxIdx == self.numResult: + self.searchIdxIdx = 0 + #print(self.searchIdx) + self.numResult = len(self.searchIdx) + self.sourceCodeList.Focus(self.searchIdx[self.searchIdxIdx]) + self.sourceCodeList.Select(self.searchIdx[self.searchIdxIdx]) + else: + self.numResult = 0 + print("Result not found") + self.prompt.SetLabel(str(self.numResult) + " results found") + + + # select monitor location + def onSelectMonitor(self, event): + idx = event.GetIndex() + file = self.monitorList.GetItem(idx, 0).GetText() + line = self.monitorList.GetItem(idx, 1).GetText() + Sidx = self.monitorDict[file+":"+line] + print(Sidx) + if(Sidx==-1): + print("Location not found") + return + self.sourceCodeList.Select(-1,on=0) + self.sourceCodeList.Focus(Sidx) + self.sourceCodeList.Select(Sidx) + + + # right click on item to add it into monitor list + def onMonitorS(self, event): + idx = event.GetIndex() + file = self.sourceCodeList.GetItem(idx, 0).GetText() + line = self.sourceCodeList.GetItem(idx, 1).GetText() + if file+":"+line not in self.monitorDict: + self.monitorList.Append([file,line]) + self.monitorDict[file+":"+line]= idx + + #remove monitor location: + def onDemonitor(self, event): + idx = event.GetIndex() + file = self.monitorList.GetItem(idx, 0).GetText() + line = self.monitorList.GetItem(idx, 1).GetText() + self.monitorList.DeleteItem(idx) + try: + del self.monitorDict[file+":"+line] + except KeyError: + pass + + + # Select one line //add to config + def onSelectF(self, event): + item = event.GetItem() + print(item.GetText()) + Fidx = self.fileIdx[item.GetText()] + self.sourceCodeList.Focus(Fidx) + self.sourceCodeList.Select(Fidx) + + + def onSelectM(self, event): + idx = event.GetIndex() + Sidx = self.m2s[idx] + print(idx,Sidx) + self.sourceCodeList.Unbind(wx.EVT_LIST_ITEM_SELECTED) + self.sourceCodeList.Select(-1,on=0) + self.sourceCodeList.Focus(Sidx) + self.sourceCodeList.Select(Sidx) + self.sourceCodeList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectS) + + def onSelectS(self, event): + idx = event.GetIndex() + Midx = self.s2m[idx] + print(idx,Midx) + self.assemblyList.Unbind(wx.EVT_LIST_ITEM_SELECTED) + self.assemblyList.Select(-1,on=0) + self.assemblyList.Focus(Midx) + self.assemblyList.Select(Midx) + self.assemblyList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelectM) + + + + # Limit input of numbers to digits + def onLimitChar(self, event): + key = event.GetKeyCode() + if (key < 255): + if chr(key).isdigit(): + event.Skip() + + + # When attack UI is edited, update attack state + def onConfig(self, event): + if (self.IsShown()): + self.state.frMonitor = self.frMonitor.GetValue() + + # Set UI from attack state + def setConfig(self): + self.setting = True + #self.frMonitor.ChangeValue(self.state.frMonitor) + + #insert dump result into listctrl + def insert(self, results): + print("=== Inserting Assembly Lines ===") + start = -1 + end = -1 + color = 0 + nextColor = 0 + colors = [config.assemblyColorA, config.assemblyColorAB, config.assemblyColorB] + cacheLine = start/64 + for i in tqdm(range(0,len(results)-1)): + start = results[i][2] + end = results[i+1][2] - 1 + startCacheLine = start//64 + endCacheLine = end//64 + #print(startCacheLine, endCacheLine) + if(cacheLinestartCacheLine): + color = 1 + row = results[i] + row[2] = hex(row[2]) + idx = self.assemblyList.Append(row) + self.assemblyList.SetItemBackgroundColour(idx, colors[color]) + print("=== Assembly Insertion Finished ===") + self.Show() + + # insert source code into list + def insertSource(self, results): + try: + print("=== Inserting Source File Lines ===") + file = "" + for i in tqdm(range(len(results))): + line = results[i] + self.sourceCode.append(line[2]) # append source code to self.sourceCode + if file != line[0]: + file = line[0] + self.fileIdx[file] = i + self.fileList.Append([file]) + self.sourceCodeList.Append(line) + print("=== Inserting Source File Lines ===") + except Exception as e: + errorMessage("Error inserting source code", str(e)) + + + + + #add one line in listctrl at a time + def addLine(self, row): + pos = self.assemblyList.InsertStringItem(0,row[0]) + for i in range(1,7): + self.assemblyList.SetStringItem(pos, i,row[i]) + + def clear(self): + print("Clear assembly frame") + self.assemblyList.DeleteAllItems() + self.sourceCodeList.DeleteAllItems() + self.fileList.DeleteAllItems() + self.monitorDict.clear() + self.monitorList.DeleteAllItems() + self.s2m = None + self.m2s = None + self.fileIdx.clear() + self.searchIdx.clear() + self.numResult = -1 + self.searchIdxIdx = 0 + self.selectedMIdx = -1 + self.selectedSIdx = -1 + self.selectedList = False + self.sourceCode = [] + self.location = "" + \ No newline at end of file diff --git a/tools/Doubloon/src/Dump.py b/tools/Doubloon/src/Dump.py new file mode 100755 index 0000000..8f3bbe3 --- /dev/null +++ b/tools/Doubloon/src/Dump.py @@ -0,0 +1,391 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import subprocess +import time +import threading +import numpy +import shlex +import paramiko +from tqdm import tqdm +import wx +import re +import platform + +import config +from util import * +from State import * +from Events import * + + +# Manages external attack and victim programs +# Attacks that rely on an external binary (such as FR-trace) +class Dump(wx.EvtHandler): + def __init__(self, state): + super(Dump, self).__init__() + + # Copy of the common attack state from application + self.state = state + + # Attack variables + self.hasResults = False + self.hasMapResults = False + self.cancelled = False + self.inserted = False + self.mapCancelled = False + self.Proccess = None + self.sshClient = None + + # results + self.map = dict() + self.rawResults = "" + self.rawMapResults = "" + self.results = None + self.mapResults = None + self.sourceCode = [] + self.s2m = dict() + self.m2s = dict() + + + # Create new thread and do runThreaded + def run(self): + self.s2m.clear() + self.m2s.clear() + self.sourceCode.clear() + self.rawMapResults = "" + self.rawResults = "" + self.results = None + self.mapResults = None + self.map.clear() + + try: + self.mapthread = threading.Thread(target=self.runMapThreaded) + self.mapthread.start() + self.mapthread.join() + self.dumpthread = threading.Thread(target=self.runThreaded) + self.dumpthread.start() + self.dumpthread.join() + except Exception as e: + errorMessage("Error starting dump binary", str(e)) + + + # Perform an Dump + def runThreaded(self): + print("=== Running objdump ===") + + try: + # If remote, setup the ssh connection if it doesn't already exist + self.hasResults = False + + # Setup attack program paramaters + dumpArgs = [] + # TODO: No handling for header information yet + # if (self.state.frHeader): + # attackAllArgs.append("-H") + + #disassemble + dumpArgs.append("objdump") + dumpArgs.append("-lS") + dumpArgs.append("-j") + dumpArgs.append(".text") + + dumpArgs.append(self.state.victimProgram) + + + print("Running objdump") + + self.ran = True + # Run dump proccesses + self.Proccess = subprocess.Popen(dumpArgs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + # Wait until done + dumpOut, dumpError = self.Proccess.communicate() + + if (self.cancelled): + print("Dump cancelled") + self.cancelled = False + return + + self.rawResults = dumpOut.decode("utf-8") + + # Show errors for debugging + print("Dump program finished") + print(dumpError.decode("utf-8")) + + # Process results if possible + if (len(self.rawResults) > 0): + print("Proccessing dump results...") + startTime = time.time() + + self.results = self.handleDump(self.rawResults) + + if (config.printMetrics): + print("Finished processing in " + str(time.time() - startTime)) + + self.hasResults = True + else: + print("No results") + + self.running = False + self.Proccess = None + print("=== Dump Finished ===") + + except Exception as e: + errorMessage("Error running dump", str(e)) + + self.hasResults = False + self.cancelled = False + self.running = False + if (not self.attackProccess is None): + self.attackProccess.terminate() + if (not self.victimProccess is None): + self.victimProccess.terminate() + if (self.sshClient): + self.sshClient.close() + self.sshClient = None + + evt = dumpDoneEvent() + wx.PostEvent(self, evt) + + # objdump for source code lines to machine code address projection + def runMapThreaded(self): + if platform.system() == "Darwin": + print("Cannot run objdump map") + self.hasMapResults = False + evt = mapDoneEvent() + wx.PostEvent(self, evt) + return + + + print("=== Running objdump decodedline===") + + try: + self.hasMapResults = False + # Setup map program paramaters + dumpArgs = [] + # TODO: No handling for header information yet + # if (self.state.frHeader): + # attackAllArgs.append("-H") + #disassemble + dumpArgs.append("objdump") + dumpArgs.append("--dwarf=decodedline") + + dumpArgs.append(self.state.victimProgram) + self.ran_map = True + # Run dump proccesses + self.mapProccess = subprocess.Popen(dumpArgs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + # Wait until done + dumpOut, dumpError = self.mapProccess.communicate() + + #self.mapProccess.terminate() + + if (self.cancelled): + print("Map cancelled") + self.cancelled = False + return + + self.mapRawResults = dumpOut.decode("utf-8") + + # Show errors for debugging + print("=== Map program finished ===") + #print("Map STDERR:") + print(dumpError.decode("utf-8")) + + # Process results if possible + if (len(self.mapRawResults) > 0): + print("--Proccessing map results...") + startTime = time.time() + #print(self.rawResults) + self.mapResults = self.handleMap(self.mapRawResults) + if (config.printMetrics): + print("Finished processing in " + str(time.time() - startTime)) + + self.hasMapResults = True + else: + print("No map results") + + self.mapRunning = False + self.mapProccess = None + print("=== Map Finished ===") + + except Exception as e: + errorMessage("Error running dump", str(e)) + + self.hasMapResults = False + self.Mapcancelled = False + self.mapRunning = False + if (not self.attackProccess is None): + self.attackProccess.terminate() + if (not self.victimProccess is None): + self.victimProccess.terminate() + if (self.sshClient): + self.sshClient.close() + self.sshClient = None + evt = mapDoneEvent() + wx.PostEvent(self, evt) + + # Cancel the dump + def cancel(self): + print("Cancelling objdump...") + try: + if (self.running): + self.hasResults = False + self.running = False + self.cancelled = True + if (self.state.sshRun): + if (self.sshClient): + self.sshClient.close() + print("Closed ssh connection") + self.sshClient = None + else: + self.Proccess.terminate() + self.mapProccess.terminate() + print("Cancelled") + except Exception as e: + errorMessage("Error cancelling dump", str(e)) + + + + + + #convert dumped file listctrl format + def handleDump(self, raw): + ''' + This is a code section looks like + + 0000000000014de2 : + init_compress(): + /home/abc/Desktop/gnupg-1.4.13/g10/compress.c:51 + int compress_filter_bz2( void *opaque, int control, + IOBUF a, byte *buf, size_t *ret_len); + + static void + init_compress( compress_filter_context_t *zfx, z_stream *zs ) + { + 14de2: 55 push %rbp + 14de3: 48 89 e5 mov %rsp,%rbp + 14de6: 48 83 ec 20 sub $0x20,%rsp + 14dea: 48 89 7d e8 mov %rdi,-0x18(%rbp) + 14dee: 48 89 75 e0 mov %rsi,-0x20(%rbp) + ''' + ''' + read dump result + 1. append to self.sourceCode + 2. match address to line + 3. + ''' + try: + print("=== Handle dump results ===") + aregex = re.compile('^[0-9a-fA-F]+ <(.*)>:$') # regex for function name + lregex = re.compile('^(?:/.*)?/([^/]+\.c):([0-9]+)(?: \(discriminator [0-9]+\))?$') # regex for /home/abc/Desktop/gnupg-1.4.13/g10/compress.c:73 (discriminator 1) + mregex = re.compile('^[ \t]+[0-9a-f]+:[ \t]+[0-9a-f]+') #regex for assembly line + functions = re.compile('\n\n(?=^[0-9a-fA-F]+ <.*>:$)',re.M).split(raw) + #functions = raw.split('\n\n') + result = [] + for idx, func in tqdm(enumerate(functions),desc="All functions in the binary"): + lines = func.splitlines() + if(idx>100): + break #debug + if(aregex.match(lines[0])): #this func is a fucntion disassembly + sym_name = aregex.match(lines[0]).group(1) + #print("func",sym_name) + i = 2 + while(i. + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx.lib.newevent + + + +# Application owns everything, it doesn't need to send events to children, it can just calls their methods +# Most events will be owned objects (Toolbar, Attack, ...) informing Application to do something +# e.g Button in Toolbar for loading data, send event to application which handles asking and loading data + +# Toolbar informs Application to run attack +runExternalAttackEvent, EVT_RUN_EXTERNAL_ATTACK = wx.lib.newevent.NewEvent() + +# Attack informs Application attack is done +externalAttackDoneEvent, EVT_EXTERNAL_ATTACK_DONE = wx.lib.newevent.NewEvent() + +# Assembly frame informs application FRmonitor location has changed +updateMonitorLocationEvent, EVT_UPDATE_LOCATION = wx.lib.newevent.NewEvent() + +# Dump informs assembly viewer its done +dumpDoneEvent, EVT_DUMP_DONE = wx.lib.newevent.NewEvent() +mapDoneEvent, EVT_MAP_DONE = wx.lib.newevent.NewEvent() + +# Toolbar opens assembly viewer +openAssemblyFrameEvent, EVT_OPEN_ASSEMBLY = wx.lib.newevent.NewEvent() + +# perform dump while opening assembly viewer +openAssemblyFrameEvent, EVT_RUN_DUMP = wx.lib.newevent.NewEvent() + +# Toolbar informs Application to open ExternalAttackConfigFrame +openExternalAttackConfigEvent, EVT_OPEN_EXTERNAL_ATTACK_CONFIG = wx.lib.newevent.NewEvent() + +# PropertiesView informs Application graph properties are updated +graphPropsUpdateEvent, EVT_GRAPH_PROPS_UPDATE = wx.lib.newevent.NewEvent() + +# GraphView informs Application it updated itself (drawn) +graphUpdateEvent, EVT_GRAPH_UPDATE = wx.lib.newevent.NewEvent() + +# Toolbar informs Application to ask user for data to load +loadDataEvent, EVT_LOAD_DATA = wx.lib.newevent.NewEvent() + +# Toolbar informs Application to save data +saveDataEvent, EVT_SAVE_DATA = wx.lib.newevent.NewEvent() + +# Toolbar informs Application to ask user for state to load +loadStateEvent, EVT_LOAD_STATE = wx.lib.newevent.NewEvent() + +# Toolbar informs Application to save state +saveStateEvent, EVT_SAVE_STATE = wx.lib.newevent.NewEvent() diff --git a/tools/Doubloon/src/ExternalAttack.py b/tools/Doubloon/src/ExternalAttack.py new file mode 100755 index 0000000..a7eebd3 --- /dev/null +++ b/tools/Doubloon/src/ExternalAttack.py @@ -0,0 +1,265 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import subprocess +import time +import threading +import numpy +import shlex +import paramiko +import wx + +import config +from util import * +from State import * +from Events import * + + + +# Manages external attack and victim programs +# Attacks that rely on an external binary (such as FR-trace) +class ExternalAttack(wx.EvtHandler): + def __init__(self, state): + super(ExternalAttack, self).__init__() + + # Copy of the common attack state from application + self.state = state + + # Attack variables + self.running = False + self.hasResults = False + self.cancelled = False + self.attackProccess = None + self.victimProccess = None + self.sshClient = None + + # Attack results + self.rawResults = "" + self.results = None + + + # Create new thread and do runThreaded + def run(self): + # Check paramaters + if (self.state.type == EXTERNAL_ATTACK_TYPE_GENERAL): + if (self.state.attackProgram == ""): + errorMessage("Error starting attack", "Attack program not specified") + return + if (self.state.type == EXTERNAL_ATTACK_TYPE_FRTRACE): + if (self.state.frProgram == ""): + errorMessage("Error starting attack", "FR-trace program not specified") + return + + if (self.state.victimRun and self.state.victimProgram == ""): + errorMessage("Error starting attack", "Victim program not specified") + return + + + try: + self.thread = threading.Thread(target=self.runThreaded) + self.thread.start() + except Exception as e: + errorMessage("Error starting attack", str(e)) + + + # Perform an attack + def runThreaded(self): + print("=== Running external attack ===") + + try: + # If remote, setup the ssh connection if it doesn't already exist + if (not self.sshClient and self.state.sshRun): + print("Connecting to ssh host...") + self.sshClient = paramiko.SSHClient() + self.sshClient.set_missing_host_key_policy(paramiko.client.AutoAddPolicy()) + self.sshClient.connect(self.state.sshHostname, port=self.state.sshPort, username=self.state.sshUsername, password=self.state.sshPassword) + print("Connected to ssh host") + + self.hasResults = False + + # Setup attack program paramaters + attackAllArgs = [] + if (self.state.type == EXTERNAL_ATTACK_TYPE_GENERAL): + attackAllArgs = [self.state.attackProgram] + attackAllArgs.extend(shlex.split(self.state.attackArgs)) + elif (self.state.type == EXTERNAL_ATTACK_TYPE_FRTRACE): + attackAllArgs.append(self.state.frProgram) + attackAllArgs.append("-s") + attackAllArgs.append(str(self.state.frSlotlen)) + attackAllArgs.append("-c") + attackAllArgs.append(str(self.state.frMaxSamples)) + attackAllArgs.append("-h") + attackAllArgs.append(str(self.state.frThreshold)) + attackAllArgs.append("-i") + attackAllArgs.append(str(self.state.frIdle)) + + # TODO: No handling for header information yet + # if (self.state.frHeader): + # attackAllArgs.append("-H") + + attackAllArgs.append("-f") + attackAllArgs.append(self.state.victimProgram) + attackAllArgs.append("-p") + attackAllArgs.append(str(self.state.frPDACount)) + + attackAddresses = self.state.frMonitor.split() + for i in range(0,len(attackAddresses),1): + attackAllArgs.append("-m") + attackAllArgs.append(attackAddresses[i]) + + attackAddresses = self.state.frEvict.split() + for i in range(0,len(attackAddresses),1): + attackAllArgs.append("-e") + attackAllArgs.append(attackAddresses[i]) + + attackAddresses = self.state.frPDA.split() + for i in range(0,len(attackAddresses),1): + attackAllArgs.append("-t") + attackAllArgs.append(attackAddresses[i]) + + victimAllArgs = [self.state.victimProgram] + victimAllArgs.extend(shlex.split(self.state.victimArgs)) + + print("Running attack program...") + + self.running = True + if (self.state.sshRun): + # Remote attack, run attack and victim if needed + attackCommand = "\"" + attackAllArgs[0] + "\"" + for i in range(1,len(attackAllArgs),1): + attackCommand = attackCommand + " " + attackAllArgs[i] + + attackStdin, attackStdout, attackStderr = self.sshClient.exec_command(attackCommand) + if (self.state.victimRun): + # Pause for a moment to allow attacker to start + time.sleep(0.1) + print("Running victim program...") + victimCommand = "\"" + self.state.victimProgram + "\" " + self.state.victimArgs + victimStdin, victimStdout, victimStderr = self.sshClient.exec_command(victimCommand) + + # Wait until done + while (attackStdout.channel.exit_status_ready()): + time.sleep(0.1) + if (self.cancelled): + print("Attack cancelled") + self.cancelled = False + return + + self.rawResults = attackStdout.read().decode('utf-8') + + # Show errors for debugging + print("Attack program finished") + print("Attack STDERR:") + print(attackStderr.read().decode("utf-8")) + if (self.state.victimRun): + print("Victim STDERR:") + print(victimStderr.read().decode("utf-8")) + + else: + # Run both proccesses + self.attackProccess = subprocess.Popen(attackAllArgs, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if (self.state.victimRun): + print("Running victim program...") + self.victimProccess = subprocess.Popen(victimAllArgs) + + # Wait until done + attackStdout, attackStderr = self.attackProccess.communicate() + + if (self.state.victimRun): + self.victimProccess.terminate() + + if (self.cancelled): + print("Attack cancelled") + self.cancelled = False + return + + self.rawResults = attackStdout.decode("utf-8") + + # Show errors for debugging + print("Attack program finished") + print("Attack STDERR:") + print(attackStderr.decode("utf-8")) + #if (self.state.victimRun): + # print("Victim STDERR:") + # print(victimStderr.read().decode("utf-8")) + + # Process results if possible + if (len(self.rawResults) > 0): + print("Proccessing attack results...") + startTime = time.time() + + self.results = resultsStringToArray(self.rawResults) + + if (config.printMetrics): + print("Finished processing in " + str(time.time() - startTime)) + + self.hasResults = True + else: + print("No results") + + self.running = False + + self.attackProccess = None + self.victimProccess = None + print("=== Attack Finished ===") + + except Exception as e: + errorMessage("Error running attack", str(e)) + + self.hasResults = False + self.cancelled = False + self.running = False + if (not self.attackProccess is None): + self.attackProccess.terminate() + if (not self.victimProccess is None): + self.victimProccess.terminate() + if (self.sshClient): + self.sshClient.close() + self.sshClient = None + + evt = externalAttackDoneEvent() + wx.PostEvent(self, evt) + + + # Cancel the attack running + def cancel(self): + print("Cancelling attack...") + try: + if (self.running): + self.hasResults = False + self.running = False + self.cancelled = True + if (self.state.sshRun): + if (self.sshClient): + self.sshClient.close() + print("Closed ssh connection") + self.sshClient = None + else: + self.attackProccess.terminate() + if (self.state.victimRun): + self.victimProccess.terminate() + + print("Cancelled") + except Exception as e: + errorMessage("Error cancelling attack", str(e)) + + \ No newline at end of file diff --git a/tools/Doubloon/src/ExternalAttackConfigFrame.py b/tools/Doubloon/src/ExternalAttackConfigFrame.py new file mode 100644 index 0000000..f8655b8 --- /dev/null +++ b/tools/Doubloon/src/ExternalAttackConfigFrame.py @@ -0,0 +1,342 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx + +import config +from util import * +from State import * +from Events import * + + + +# Window with options to configure external attack +class ExternalAttackConfigFrame(wx.Frame): + def __init__(self, state): + super(ExternalAttackConfigFrame, self).__init__(None, style=wx.DEFAULT_FRAME_STYLE - (wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER)) + + # Copy of the common attack state from application + self.state = state + + # Setup window + self.SetTitle("External attack config") + self.SetClientSize((480,320)) + + # Setup UI + sizer = wx.GridBagSizer(5,5) + self.panel = wx.Panel(self) + self.sizer = sizer + + self.notebook = wx.Notebook(self.panel) + sizer.Add(self.notebook, pos=(1,1), span=(1,3)) + + # General attack UI + generalPanel = wx.Panel(self.notebook) + generalSizer = wx.GridBagSizer(5,5) + + label = wx.StaticText(generalPanel, -1, "Attack program:") + generalSizer.Add(label, pos=(1,1)) + self.attackProgram = wx.TextCtrl(generalPanel, size=(350,config.textboxHeight)) + generalSizer.Add(self.attackProgram, pos=(1,2), flag=wx.TOP|wx.LEFT) + self.browseAttack = wx.Button(generalPanel, label="Browse") + generalSizer.Add(self.browseAttack, pos=(1,3), flag=wx.TOP|wx.RIGHT) + + label = wx.StaticText(generalPanel, -1, "Attack arguments:") + generalSizer.Add(label, pos=(2,1)) + self.attackArgs = wx.TextCtrl(generalPanel, size=(350,config.textboxHeight)) + generalSizer.Add(self.attackArgs, pos=(2,2), span=(1,2), flag=wx.TOP|wx.LEFT) + + generalPanel.SetSizer(generalSizer) + generalSizer.Fit(generalPanel) + self.notebook.InsertPage(0, generalPanel, "General", select=True) + + # FR-Trace attack UI + frPanel = wx.Panel(self.notebook) + frSizer = wx.GridBagSizer(5,5) + + label = wx.StaticText(frPanel, -1, "FR-trace program:") + frSizer.Add(label, pos=(1,1)) + self.frProgram = wx.TextCtrl(frPanel, size=(350,config.textboxHeight)) + frSizer.Add(self.frProgram, pos=(1,2), flag=wx.TOP|wx.LEFT) + self.browseFR = wx.Button(frPanel, label="Browse") + frSizer.Add(self.browseFR, pos=(1,3), flag=wx.TOP|wx.RIGHT) + + label = wx.StaticText(frPanel, -1, "Monitor locations:") + frSizer.Add(label, pos=(2,1)) + self.frMonitor = wx.TextCtrl(frPanel, size=(350,config.textboxHeight)) + frSizer.Add(self.frMonitor, pos=(2,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "Evict locations:") + frSizer.Add(label, pos=(3,1)) + self.frEvict = wx.TextCtrl(frPanel, size=(350,config.textboxHeight)) + frSizer.Add(self.frEvict, pos=(3,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "PDA locations:") + frSizer.Add(label, pos=(4,1)) + self.frPDA = wx.TextCtrl(frPanel, size=(350,config.textboxHeight)) + frSizer.Add(self.frPDA, pos=(4,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "Slot length:") + frSizer.Add(label, pos=(5,1)) + self.frSlotlen = wx.TextCtrl(frPanel, size=(150,config.textboxHeight)) + frSizer.Add(self.frSlotlen, pos=(5,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "Max samples:") + frSizer.Add(label, pos=(6,1)) + self.frMaxSamples = wx.TextCtrl(frPanel, size=(150,config.textboxHeight)) + frSizer.Add(self.frMaxSamples, pos=(6,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "Threshold:") + frSizer.Add(label, pos=(7,1)) + self.frThreshold = wx.TextCtrl(frPanel, size=(150,config.textboxHeight)) + frSizer.Add(self.frThreshold, pos=(7,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "Idle count:") + frSizer.Add(label, pos=(8,1)) + self.frIdle = wx.TextCtrl(frPanel, size=(150,config.textboxHeight)) + frSizer.Add(self.frIdle, pos=(8,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(frPanel, -1, "PDA count:") + frSizer.Add(label, pos=(9,1)) + self.frPDACount = wx.TextCtrl(frPanel, size=(150,config.textboxHeight)) + frSizer.Add(self.frPDACount, pos=(9,2), flag=wx.TOP|wx.LEFT) + + # self.frHeader = wx.CheckBox(frPanel, label="Include header") + # frSizer.Add(self.frHeader, pos=(10,2), span=(1,3)) + + frPanel.SetSizer(frSizer) + frSizer.Fit(frPanel) + self.notebook.InsertPage(1, frPanel, "FR-trace") + + # Standard UI + self.victimRun = wx.CheckBox(self.panel, label="Run victim program") + sizer.Add(self.victimRun, pos=(2,2), span=(1,3)) + + label = wx.StaticText(self.panel, -1, "Victim program:") + sizer.Add(label, pos=(3,1)) + self.victimProgram = wx.TextCtrl(self.panel, size=(400,config.textboxHeight)) + sizer.Add(self.victimProgram, pos=(3,2), flag=wx.TOP|wx.LEFT) + self.browseVictim = wx.Button(self.panel, label="Browse") + sizer.Add(self.browseVictim, pos=(3,3), flag=wx.TOP|wx.RIGHT) + + label = wx.StaticText(self.panel, -1, "Victim arguments:") + sizer.Add(label, pos=(4,1)) + self.victimArgs = wx.TextCtrl(self.panel, size=(400,config.textboxHeight)) + sizer.Add(self.victimArgs, pos=(4,2), span=(1,2), flag=wx.TOP|wx.LEFT) + + self.sshRun = wx.CheckBox(self.panel, label="Run remotely (SSH)") + sizer.Add(self.sshRun, pos=(5,2), span=(1,3)) + + label = wx.StaticText(self.panel, -1, "SSH hostname:") + sizer.Add(label, pos=(6,1)) + self.sshHostname = wx.TextCtrl(self.panel, size=(200,config.textboxHeight)) + sizer.Add(self.sshHostname, pos=(6,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(self.panel, -1, "SSH port:") + sizer.Add(label, pos=(7,1)) + self.sshPort = wx.TextCtrl(self.panel, size=(200,config.textboxHeight)) + sizer.Add(self.sshPort, pos=(7,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(self.panel, -1, "SSH username:") + sizer.Add(label, pos=(8,1)) + self.sshUsername = wx.TextCtrl(self.panel, size=(200,config.textboxHeight)) + sizer.Add(self.sshUsername, pos=(8,2), flag=wx.TOP|wx.LEFT) + + label = wx.StaticText(self.panel, -1, "SSH password:") + sizer.Add(label, pos=(9,1)) + self.sshPassword = wx.TextCtrl(self.panel, size=(200,config.textboxHeight), style=wx.TE_PASSWORD) + sizer.Add(self.sshPassword, pos=(9,2), flag=wx.TOP|wx.LEFT) + + self.panel.SetSizer(sizer) + sizer.Fit(self.panel) + + # Sizing + self.SetClientSize(20+self.panel.GetClientSize().Width,20+self.panel.GetClientSize().Height) + + # Event bindings + self.Bind(wx.EVT_CLOSE, self.onClose) + self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onNotebookChange, self.notebook) + + self.frProgram.Bind(wx.EVT_TEXT, self.onConfig) + self.browseFR.Bind(wx.EVT_BUTTON, self.onBrowseFR) + self.frMonitor.Bind(wx.EVT_TEXT, self.onConfig) + self.frEvict.Bind(wx.EVT_TEXT, self.onConfig) + self.frPDA.Bind(wx.EVT_TEXT, self.onConfig) + self.frSlotlen.Bind(wx.EVT_CHAR, self.onLimitChar) + self.frSlotlen.Bind(wx.EVT_TEXT, self.onConfig) + self.frMaxSamples.Bind(wx.EVT_CHAR, self.onLimitChar) + self.frMaxSamples.Bind(wx.EVT_TEXT, self.onConfig) + self.frThreshold.Bind(wx.EVT_CHAR, self.onLimitChar) + self.frThreshold.Bind(wx.EVT_TEXT, self.onConfig) + self.frIdle.Bind(wx.EVT_CHAR, self.onLimitChar) + self.frIdle.Bind(wx.EVT_TEXT, self.onConfig) + self.frPDACount.Bind(wx.EVT_CHAR, self.onLimitChar) + self.frPDACount.Bind(wx.EVT_TEXT, self.onConfig) + # self.frHeader.Bind(wx.EVT_CHECKBOX, self.onConfig) + + self.attackProgram.Bind(wx.EVT_TEXT, self.onConfig) + self.browseAttack.Bind(wx.EVT_BUTTON, self.onBrowseGeneral) + self.attackArgs.Bind(wx.EVT_TEXT, self.onConfig) + + self.victimProgram.Bind(wx.EVT_TEXT, self.onConfig) + self.victimArgs.Bind(wx.EVT_TEXT, self.onConfig) + self.browseVictim.Bind(wx.EVT_BUTTON, self.onBrowseVictim) + self.victimRun.Bind(wx.EVT_CHECKBOX, self.onConfig) + self.sshRun.Bind(wx.EVT_CHECKBOX, self.onConfig) + self.sshHostname.Bind(wx.EVT_TEXT, self.onConfig) + self.sshPort.Bind(wx.EVT_TEXT, self.onConfig) + self.sshPort.Bind(wx.EVT_CHAR, self.onLimitChar) + self.sshUsername.Bind(wx.EVT_TEXT, self.onConfig) + self.sshPassword.Bind(wx.EVT_TEXT, self.onConfig) + + self.setConfig() + + + # Ask the user for a file and fill in the text box + def onBrowseGeneral(self, event): + with wx.FileDialog(self, "Select program", wildcard="*", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + + # Fill in the corresponding objects textbox + self.attackProgram.ChangeValue(pathname) + self.onConfig(None) + + def onBrowseFR(self, event): + with wx.FileDialog(self, "Select program", wildcard="*", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + + # Fill in the corresponding objects textbox + self.frProgram.ChangeValue(pathname) + self.onConfig(None) + + def onBrowseVictim(self, event): + with wx.FileDialog(self, "Select program", wildcard="*", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: + if (fileDialog.ShowModal() == wx.ID_CANCEL): + return + + pathname = fileDialog.GetPath() + + # Fill in the corresponding objects textbox + self.victimProgram.ChangeValue(pathname) + self.onConfig(None) + + # Open window + def open(self): + self.setConfig() + self.Show() + + + # Close window on cross out + def onClose(self, event): + self.onConfig(None) + self.Hide() + + + # Limit input of numbers to digits + def onLimitChar(self, event): + key = event.GetKeyCode() + if (chr(key).isdigit() or key == wx.WXK_LEFT or key == wx.WXK_RIGHT or key == wx.WXK_BACK or key == wx.WXK_RETURN or key == wx.WXK_ESCAPE or key == wx.WXK_TAB): + event.Skip(True) + + + # When attack UI ExternalAttackState is edited, update attack state + def onConfig(self, event): + if (self.IsShown()): + self.state.attackProgram = self.attackProgram.GetValue() + self.state.attackArgs = self.attackArgs.GetValue() + + if (self.frSlotlen.GetValue() == ""): + self.frSlotlen.ChangeValue("0") + if (self.frMaxSamples.GetValue() == ""): + self.frMaxSamples.ChangeValue("0") + if (self.frThreshold.GetValue() == ""): + self.frThreshold.ChangeValue("0") + if (self.frIdle.GetValue() == ""): + self.frIdle.ChangeValue("0") + if (self.frPDACount.GetValue() == ""): + self.frPDACount.ChangeValue("0") + if (self.sshPort.GetValue() == ""): + self.sshPort.ChangeValue("22") + + self.state.frProgram = self.frProgram.GetValue() + self.state.frMonitor = self.frMonitor.GetValue() + self.state.frEvict = self.frEvict.GetValue() + self.state.frPDA = self.frPDA.GetValue() + self.state.frSlotlen = int(self.frSlotlen.GetValue()) + self.state.frMaxSamples = int(self.frMaxSamples.GetValue()) + self.state.frThreshold = int(self.frThreshold.GetValue()) + self.state.frIdle = int(self.frIdle.GetValue()) + self.state.frPDACount = int(self.frPDACount.GetValue()) + # self.state.frHeader = self.frHeader.IsChecked() + + self.state.victimProgram = self.victimProgram.GetValue() + self.state.victimArgs = self.victimArgs.GetValue() + self.state.victimRun = self.victimRun.IsChecked() + self.state.sshRun = self.sshRun.IsChecked() + self.state.sshHostname = self.sshHostname.GetValue() + self.state.sshPort = int(self.sshPort.GetValue()) + self.state.sshUsername = self.sshUsername.GetValue() + self.state.sshPassword = self.sshPassword.GetValue() + + + # If notebook page change, type of attack changed + def onNotebookChange(self, event): + self.state.type = self.notebook.GetSelection() + self.onConfig(None) + + + # Set UI from attack state + def setConfig(self): + self.setting = True + self.notebook.SetSelection(self.state.type) + self.attackProgram.ChangeValue(self.state.attackProgram) + self.attackArgs.ChangeValue(self.state.attackArgs) + + self.frProgram.ChangeValue(self.state.frProgram) + self.frMonitor.ChangeValue(self.state.frMonitor) + self.frEvict.ChangeValue(self.state.frEvict) + self.frPDA.ChangeValue(self.state.frPDA) + self.frSlotlen.ChangeValue(str(self.state.frSlotlen)) + self.frMaxSamples.ChangeValue(str(self.state.frMaxSamples)) + self.frThreshold.ChangeValue(str(self.state.frThreshold)) + self.frIdle.ChangeValue(str(self.state.frIdle)) + self.frPDACount.ChangeValue(str(self.state.frPDACount)) + # self.frHeader.SetValue(self.state.frHeader) + + self.victimRun.SetValue(self.state.victimRun) + self.victimProgram.ChangeValue(self.state.victimProgram) + self.victimArgs.ChangeValue(self.state.victimArgs) + self.sshRun.SetValue(self.state.sshRun) + self.sshHostname.ChangeValue(self.state.sshHostname) + self.sshPort.ChangeValue(str(self.state.sshPort)) + self.sshUsername.ChangeValue(self.state.sshUsername) + self.sshPassword.ChangeValue(self.state.sshPassword) + + + + \ No newline at end of file diff --git a/tools/Doubloon/src/GraphView.py b/tools/Doubloon/src/GraphView.py new file mode 100755 index 0000000..7e4f7f2 --- /dev/null +++ b/tools/Doubloon/src/GraphView.py @@ -0,0 +1,539 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx +import numpy +import math +import time + +import config +from util import * +from Events import * +from State import * + + + +# Graphs data and manages interactions +class GraphView(wx.Window): + def __init__(self, parent, state): + super(GraphView, self).__init__(parent) + + # Copy of the common graph state from application + self.state = state + + # Other drawing properties + self.xLength = 0 + + # Dragging variables + self.initialX = 0 + self.finalX = 1 + self.dragging = False + + # Setup UI + self.scrollBar = wx.ScrollBar(self) + self.SetBackgroundStyle(wx.BG_STYLE_PAINT) + self.scrollBar.SetScrollbar(0, 10000, 10000, 1) + self.scrollBar.SetThumbPosition(0) + + # Bind events + self.Bind(wx.EVT_PAINT, self.onPaint) + self.Bind(wx.EVT_SCROLL, self.onScroll) + + # Graph selection events + self.Bind(wx.EVT_LEFT_DOWN, self.onMouseDown) + self.Bind(wx.EVT_MOTION, self.onMouseMove) + self.Bind(wx.EVT_LEFT_UP, self.onMouseUp) + + + # Set the graph data, resets limits + # Use clean=False to disable resetting limits and masks + def setData(self, clean=True): + self.xLength = self.state.data.shape[0] + + if (clean): + self.state.mask = [True]*self.state.data.shape[1] + self.state.xLimit = [0, self.xLength-1] + self.state.yLimit = config.graphDefaultYLimits + + self.scrollBar.SetScrollbar(0, self.xLength, self.xLength, 1) + + self.Refresh() + + + # Set graph limits + def setLimits(self, xLimMin, xLimMax, yLimMin, yLimMax): + self.state.xLimit = [xLimMin, xLimMax] + self.state.yLimit = [yLimMin, yLimMax] + + self.cleanLimits() + + self.scrollBar.SetScrollbar(0, self.state.xLimit[1] - self.state.xLimit[0], self.xLength - 1, 1) + self.scrollBar.SetThumbPosition(self.state.xLimit[0]) + + + # Zoom in or out of graph by factor of current selection + def zoom(self, factor): + if (self.state.xLimit[1] - self.state.xLimit[0] > config.graphMinXSize or factor > 1): + centre = (self.state.xLimit[1] + self.state.xLimit[0]) / 2 + self.state.xLimit[0] = int(centre - ((centre - self.state.xLimit[0]) * factor)) + self.state.xLimit[1] = int(centre - ((centre - self.state.xLimit[1]) * factor)) + self.scrollBar.SetScrollbar(0, self.state.xLimit[1] - self.state.xLimit[0], self.xLength - 1, 1) + self.scrollBar.SetThumbPosition(self.state.xLimit[0]) + + self.Refresh() + + evt = graphUpdateEvent() + wx.PostEvent(self, evt) + + + # Move graph left or right by factor of current selection, negative for left, positive for right + def shift(self, factor): + diff = self.state.xLimit[1] - self.state.xLimit[0] + if (factor <= 0): + self.state.xLimit[0] = int(self.state.xLimit[0] + (diff * factor)) + if (self.state.xLimit[0] < 0): + self.state.xLimit[0] = 0 + self.state.xLimit[1] = self.state.xLimit[0] + diff + else: + self.state.xLimit[1] = int(self.state.xLimit[1] + (diff * factor)) + if (self.state.xLimit[1] > self.xLength): + self.state.xLimit[1] = self.xLength + self.state.xLimit[0] = self.state.xLimit[1] - diff + + self.scrollBar.SetScrollbar(0, self.state.xLimit[1] - self.state.xLimit[0], self.xLength - 1, 1) + self.scrollBar.SetThumbPosition(self.state.xLimit[0]) + + self.Refresh() + + evt = graphUpdateEvent() + wx.PostEvent(self, evt) + + + # Shift graph on scroll + def onScroll(self, event): + diff = self.state.xLimit[1] - self.state.xLimit[0] + self.state.xLimit[0] = event.GetPosition() + self.state.xLimit[1] = self.state.xLimit[0] + diff + self.Refresh() + + evt = graphUpdateEvent() + wx.PostEvent(self, evt) + + + # Shortcuts for graph + def onButton(self, event): + if (event.GetKeyCode() == wx.WXK_UP): + self.zoom(1.0/config.graphZoomFactor) + elif (event.GetKeyCode() == wx.WXK_DOWN): + self.zoom(config.graphZoomFactor) + elif (event.GetKeyCode() == wx.WXK_LEFT): + self.shift(-config.graphShiftFactor) + elif (event.GetKeyCode() == wx.WXK_RIGHT): + self.shift(config.graphShiftFactor) + + + # On mouse down, handle start of selection + def onMouseDown(self, event): + self.dragging = True + self.initialX = event.GetPosition()[0] + self.finalX = event.GetPosition()[0] + self.Refresh() + + + # On mouse move, handle selection + def onMouseMove(self, event): + if (self.dragging): + self.finalX = event.GetPosition()[0] + self.Refresh() + + + # On mouse up, handle end of selection + def onMouseUp(self, event): + self.dragging = False + self.finalX = event.GetPosition()[0] + if (self.initialX == self.finalX): + return + + if (self.initialX > self.finalX): + temp = self.finalX + self.finalX = self.initialX + self.initialX = temp + + xRange = self.state.xLimit[1] - self.state.xLimit[0] + factor = xRange / self.GetClientSize()[0] + + self.state.xLimit[1] = int(factor * self.finalX) + self.state.xLimit[0] + self.state.xLimit[0] = int(factor * self.initialX) + self.state.xLimit[0] + + self.scrollBar.SetScrollbar(0, self.state.xLimit[1] - self.state.xLimit[0], self.xLength - 1, 1) + self.scrollBar.SetThumbPosition(self.state.xLimit[0]) + + evt = graphUpdateEvent() + wx.PostEvent(self, evt) + + self.Refresh() + + + # Limit the limits to correct values + def cleanLimits(self): + updateProps = False + if (self.state.xLimit[1] - self.state.xLimit[0] < config.graphMinXSize): + self.state.xLimit[1] = self.state.xLimit[0] + config.graphMinXSize + updateProps = True + if (self.state.yLimit[1] - self.state.yLimit[0] < config.graphMinYSize): + self.state.yLimit[1] = self.state.yLimit[0] + config.graphMinYSize + updateProps = True + + if (self.state.xLimit[0] < 0): + self.state.xLimit[0] = 0 + updateProps = True + if (self.state.xLimit[1] > self.xLength): + self.state.xLimit[1] = self.xLength - 1 + updateProps = True + if (self.state.yLimit[0] < 0): + self.state.yLimit[0] = 0 + updateProps = True + + self.scrollBar.SetScrollbar(0, self.state.xLimit[1] - self.state.xLimit[0], self.xLength - 1, 1) + self.scrollBar.SetThumbPosition(self.state.xLimit[0]) + + if (updateProps): + evt = graphUpdateEvent() + wx.PostEvent(self, evt) + + + # Draw the graph based on settings + def onPaint(self, event): + # Measure the time + startTime = time.time() + + # Update UI elements + self.scrollBar.SetPosition(wx.Point(0,0)) + self.scrollBar.SetSize(wx.Size(self.GetClientSize()[0],self.scrollBar.GetClientSize()[1])) + + # Graph variables + marginX = (30, 0) + marginY = (16, 30) + width, height = self.GetClientSize() + width -= marginX[0] + marginX[1] + height -= marginY[0] + marginY[1] + + # Common drawing variables + dc = wx.AutoBufferedPaintDC(self) + brush = wx.Brush(config.graphBackground, style=wx.BRUSHSTYLE_SOLID) + pen = wx.Pen(config.graphForeground) + dc.SetBackgroundMode(wx.SOLID) + dc.SetBackground(brush) + dc.Clear() + + # Check if data to graph + if (self.state.data is None): + dc.TextBackground = wx.Colour(0,0,0,0) + dc.TextForeground = config.graphForeground + str1 = "No data" + dc.DrawText(str1, (width/2) - (dc.GetTextExtent(str1)[0]/2), (height/2)) + return + + # Cleanup limits + self.cleanLimits() + + # Other drawing variables + xScale = float(width) / float(self.state.xLimit[1] - self.state.xLimit[0]) + yScale = float(height) / float(self.state.yLimit[1] - self.state.yLimit[0]) + cluster = math.ceil((self.state.xLimit[1] - self.state.xLimit[0]) / config.graphMaxResolution) + xGrid = int(math.pow(10,math.floor(math.log10(self.state.xLimit[1] - self.state.xLimit[0])))) + yGrid = int(math.pow(10,math.floor(math.log10(self.state.yLimit[1] - self.state.yLimit[0])))) + + if (self.state.type == GRAPH_TYPE_LINE): + # Line graph + + # Draw grid (X lines) + pen.SetColour(config.graphGrid) + pen.SetWidth(2) + dc.SetPen(pen) + for x in range(math.floor(self.state.xLimit[0] / xGrid) * xGrid, self.state.xLimit[1], xGrid): + xVal = ((x - self.state.xLimit[0])*xScale) + marginX[0] + if (xVal >= marginX[0]): + dc.DrawLine(xVal, marginY[0], xVal, height + marginY[0]) + + pen.SetWidth(1) + dc.SetPen(pen) + if (xGrid == 1): + xGrid = 10 + for x in range(math.floor(self.state.xLimit[0] / xGrid) * xGrid, self.state.xLimit[1], int(xGrid / 10)): + xVal = ((x - self.state.xLimit[0])*xScale) + marginX[0] + if (xVal >= marginX[0]): + dc.DrawLine(xVal, marginY[0], xVal, height + marginY[0]) + + # Draw Grid (Y lines) and threshold line + pen.SetWidth(2) + dc.SetPen(pen) + if (self.state.thresholdBinary): + dc.DrawLine(marginX[0], (height / 2) + marginY[0], width + marginX[0], (height / 2)+marginY[0]) + else: + yVal = (height - ((self.state.threshold - self.state.yLimit[0])*yScale)) + marginY[0] + dc.DrawLine(marginX[0], yVal, width + marginX[0], yVal) + pen.SetWidth(1) + dc.SetPen(pen) + + for y in range(math.floor(self.state.yLimit[0] / yGrid) * yGrid, self.state.yLimit[1], yGrid): + yVal = (height - ((y - self.state.yLimit[0])*yScale)) + marginY[0] + if (yVal >= marginY[0]): + dc.DrawLine(marginX[0], yVal, width + marginX[0], yVal) + + # Draw each set + for j in range(0, self.state.data.shape[1], 1): + if (not self.state.mask[j]): + continue + + pen.SetColour(config.graphColours[j % len(config.graphColours)]) + lastPoint = [0,float("nan")] + + # Draw results for set + for i in range(self.state.xLimit[0], self.state.xLimit[1]+1, cluster): + selection = self.state.data[i:i + cluster,j] + if (selection.size == 0): + lastPoint = thisPoint + continue + + thisPoint = [i, float(numpy.nanmin(selection))] + + if (self.state.thresholdBinary): + if (math.isnan(thisPoint[1])): + pass + elif (thisPoint[1] > self.state.threshold): + thisPoint[1] = 1 + else: + thisPoint[1] = 0 + + if (math.isnan(lastPoint[1])): + lastPoint = thisPoint + continue + + if (math.isnan(thisPoint[1])): + if (not self.state.interpolateMissing): + lastPoint = thisPoint + continue + + if (lastPoint[1] < self.state.threshold and thisPoint[1] < self.state.threshold and self.state.highlightUnderThreshold and not self.state.thresholdBinary): + pen.SetWidth(2) + else: + pen.SetWidth(2) + + # Make connecting lines thinner for binary + if (lastPoint[1] != thisPoint[1] and self.state.thresholdBinary): + pen.SetWidth(1) + + dc.SetPen(pen) + if (self.state.thresholdBinary): + offset = (0.5 / (self.state.data.shape[1] + 1)) * (j + 1) + dc.DrawLine(((lastPoint[0] - self.state.xLimit[0])*xScale)+marginX[0], + (height * (1 - (offset + (lastPoint[1] * (1 - (2 * offset))))))+marginY[0], + ((thisPoint[0] - self.state.xLimit[0])*xScale)+marginX[0], + (height * (1 - (offset + (thisPoint[1] * (1 - (2 * offset))))))+marginY[0]) + else: + dc.DrawLine(((lastPoint[0] - self.state.xLimit[0])*xScale)+marginX[0], + (height - ((lastPoint[1] - self.state.yLimit[0])*yScale))+marginY[0], + ((thisPoint[0] - self.state.xLimit[0])*xScale)+marginX[0], + (height - ((thisPoint[1] - self.state.yLimit[0])*yScale))+marginY[0]) + lastPoint = thisPoint + + # Draw margin background + brush.SetColour(config.graphBackground) + dc.SetBrush(brush) + pen.SetWidth(0) + pen.SetColour(config.graphBackground) + dc.SetPen(pen) + + dc.DrawRectangle(0,0,marginX[0], height+marginY[0]) + dc.DrawRectangle(0,height+marginY[0],width+marginX[0], marginY[1]) + dc.DrawRectangle(marginX[0],0,width+marginX[1], marginY[0]) + dc.DrawRectangle(width+marginX[0],marginY[0],marginX[1], height+marginY[1]) + + brush.SetColour(wx.Colour(0,0,0,0)) + dc.SetBrush(brush) + pen.SetWidth(2) + pen.SetColour(config.graphBorder) + dc.SetPen(pen) + dc.DrawRectangle(marginX[0],marginY[0],width,height) + + # Draw numbers + dc.TextBackground = wx.Colour(0,0,0,0) + dc.TextForeground = config.graphForeground + for x in range(math.floor(self.state.xLimit[0] / xGrid) * xGrid, self.state.xLimit[1], xGrid): + xVal = ((x - self.state.xLimit[0])*xScale) + 2 + marginX[0] + if (xVal >= marginX[0]): + dc.DrawText(str(x), xVal, (height-16)+marginY[0]) + + # Draw threshold value text + if (self.state.thresholdBinary): + dc.DrawText("Above "+str(self.state.threshold), marginX[0], (height / 2) + marginY[0] - 16) + dc.DrawText("Below "+str(self.state.threshold), marginX[0], (height / 2) + marginY[0]) + else: + yVal = (height - ((self.state.threshold - self.state.yLimit[0])*yScale)) + marginY[0] + dc.DrawText("Threshold: " + str(self.state.threshold), marginX[0], yVal) + + for y in range(math.floor(self.state.yLimit[0] / yGrid) * yGrid, self.state.yLimit[1], yGrid): + yVal = (height - ((y - self.state.yLimit[0])*yScale)) + marginY[0] + if (yVal >= marginY[0] and y != self.state.threshold): + dc.DrawText(str(y), marginX[0], yVal) + + + # Draw selection, if applicable + if (self.dragging): + pen.SetColour(config.graphForeground) + fill = config.graphForeground + fill = wx.Colour(fill.red, fill.green, fill.blue, 25) + brush.SetColour(fill) + dc.SetBrush(brush) + dc.SetPen(pen) + dc.DrawRectangle(self.initialX, marginY[0], (self.finalX - self.initialX), height) + + # Draw axis labels + str1 = "Time slots" + dc.DrawText(str(str1), marginX[0] + (width/2) - (dc.GetTextExtent(str1)[0]/2), height + marginY[0] + 6) + str2 = "Access time (cycles)" + dc.DrawRotatedText(str("Access time (cycles)"), 6, marginY[0] + (height/2) + (dc.GetTextExtent(str2)[0]/2), 90) + + + elif (self.state.type == GRAPH_TYPE_MAP): + # Graph type + + # Change graph variables + marginX = (30, 30) + marginY = (16, 46) + width, height = self.GetClientSize() + width -= marginX[0] + marginX[1] + height -= marginY[0] + marginY[1] + + xCount = int((self.state.xLimit[1] - self.state.xLimit[0]+1) / cluster) + yCount = int(self.state.data.shape[1]) + + imageData = [0] * (xCount*yCount*3) + nextByte = 0 + + # Draw each set + for y in range(0, yCount, 1): + + lastPoint = [0,float("nan")] + + # Draw results for set + for x in range(self.state.xLimit[0], self.state.xLimit[1]+1, cluster): + + selection = self.state.data[x:x + cluster,y] + + if (selection.size == 0): + lastPoint = thisPoint + continue + + thisPoint = [x, float(numpy.nanmin(selection))] + + if (self.state.thresholdBinary): + if (math.isnan(thisPoint[1])): + pass + elif (thisPoint[1] > self.state.threshold): + thisPoint[1] = 1 + else: + thisPoint[1] = 0 + + if (math.isnan(lastPoint[1])): + lastPoint = thisPoint + imageData[nextByte] = 0 + imageData[nextByte+1] = 0 + imageData[nextByte+2] = 0 + nextByte = nextByte + 3 + continue + + if (math.isnan(thisPoint[1])): + if (not self.state.interpolateMissing): + lastPoint = thisPoint + imageData[nextByte] = 0 + imageData[nextByte+1] = 0 + imageData[nextByte+2] = 0 + nextByte = nextByte + 3 + continue + + if (lastPoint[1] < self.state.threshold and thisPoint[1] < self.state.threshold and self.state.highlightUnderThreshold and not self.state.thresholdBinary): + pen.SetWidth(3) + else: + pen.SetWidth(2) + + value = (thisPoint[1] - self.state.yLimit[0]) / (self.state.yLimit[1] - self.state.yLimit[0]) + if (self.state.thresholdBinary): + value = thisPoint[1] + + imageData[nextByte] = 0 + imageData[nextByte+1] = int(max(min(value*255,255),0)) + imageData[nextByte+2] = 0 + nextByte = nextByte + 3 + + lastPoint = thisPoint + + + image = wx.Image(xCount, yCount, bytes(imageData)) + image = image.Scale(width, height) + dc.DrawBitmap(image.ConvertToBitmap(), marginX[0], marginY[0]) + + # Draw grid (X lines) + dc.TextBackground = wx.Colour(0,0,0,0) + dc.TextForeground = config.graphForeground + pen.SetColour(config.graphGrid) + pen.SetWidth(2) + dc.SetPen(pen) + for x in range(math.floor(self.state.xLimit[0] / xGrid) * xGrid, self.state.xLimit[1], xGrid): + xVal = ((x-self.state.xLimit[0])*(width/xCount)) + marginX[0] + if (xVal >= marginX[0] and xVal <= marginX[0] + width): + dc.DrawLine(xVal, marginY[0], xVal, height + marginY[0]) + dc.DrawText(str(x), xVal, (height)+marginY[0]) + + if (xGrid == 1): + xGrid = 10 + pen.SetColour(config.graphGrid) + pen.SetWidth(1) + dc.SetPen(pen) + for x in range(math.floor(self.state.xLimit[0] / xGrid) * xGrid, self.state.xLimit[1], int(xGrid / 10)): + xVal = ((x-self.state.xLimit[0])*(width/xCount)) + marginX[0] + if (xVal >= marginX[0] and xVal <= marginX[0] + width): + dc.DrawLine(xVal, marginY[0], xVal, height + marginY[0]) + + brush.SetColour(wx.Colour(0,0,0,0)) + dc.SetBrush(brush) + pen.SetWidth(2) + pen.SetColour(config.graphBorder) + dc.SetPen(pen) + dc.DrawRectangle(marginX[0],marginY[0],width,height) + + # Draw selection, if applicable + if (self.dragging): + pen.SetColour(config.graphForeground) + fill = config.graphForeground + fill = wx.Colour(fill.red, fill.green, fill.blue, 25) + brush.SetColour(fill) + dc.SetBrush(brush) + dc.SetPen(pen) + dc.DrawRectangle(self.initialX, marginY[0], (self.finalX - self.initialX), height) + + + if (config.printMetrics): + print("Drew in " + str(time.time() - startTime)) + + \ No newline at end of file diff --git a/tools/Doubloon/src/PlotView.py b/tools/Doubloon/src/PlotView.py new file mode 100755 index 0000000..e69de29 diff --git a/tools/Doubloon/src/PropertiesView.py b/tools/Doubloon/src/PropertiesView.py new file mode 100755 index 0000000..5458e86 --- /dev/null +++ b/tools/Doubloon/src/PropertiesView.py @@ -0,0 +1,278 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx +import math + +import config +from util import * +from Events import * +from State import * +from matplotlib import pyplot as plt +import numpy as np + + + +# Provide graph settings +class PropertiesView(wx.ScrolledWindow): + def __init__(self, parent, graphState): + super(PropertiesView, self).__init__(parent, style=wx.VSCROLL) + + # TODO: View should scroll vertically but current isn't set up to do so + + # Copy of the common graph state from application + self.graphState = graphState + + # Panels and sizers + self.statsPanel = wx.Panel(self) + self.propsPanel = wx.Panel(self) + self.maskPanel = wx.Panel(self) + + psizer = wx.GridBagSizer(6,5) + ssizer = wx.GridBagSizer(5,5) + msizer = wx.GridBagSizer(5,5) + self.propsSizer = psizer + self.statsSizer = ssizer + self.maskSizer = msizer + + # Statistics UI + self.statsCount = wx.StaticText(self.statsPanel, -1, "Result count: 1000000") + ssizer.Add(self.statsCount, pos=(0,0)) + self.statsActive = wx.StaticText(self.statsPanel, -1, "Active: 100%") + ssizer.Add(self.statsActive, pos=(1,0)) + + # Properties UI + line = wx.StaticLine(self.propsPanel) + psizer.Add(line, pos=(0, 0), span=(1,3), flag=wx.EXPAND|wx.TOP) + + if (config.experimental): + self.graphTypeText = wx.StaticText(self.propsPanel, -1, "Type:") + psizer.Add(self.graphTypeText, pos=(1,0)) + self.graphChoice = wx.Choice(self.propsPanel, choices=["Line", "Map"]) + psizer.Add(self.graphChoice, pos=(1,1), span=(1,3)) + self.graphChoice.Bind(wx.EVT_CHOICE, self.onGraphProps) + + xLimit = wx.StaticText(self.propsPanel, -1, "X limits:") + psizer.Add(xLimit, pos=(2,0)) + self.xMinText = wx.TextCtrl(self.propsPanel, size=(60,config.textboxHeight)) + psizer.Add(self.xMinText, pos=(2,1), flag=wx.TOP|wx.LEFT) + self.xMinText.Bind(wx.EVT_CHAR, self.onLimitChar) + self.xMinText.Bind(wx.EVT_KILL_FOCUS, self.onGraphProps) + self.xMaxText = wx.TextCtrl(self.propsPanel, size=(60,config.textboxHeight)) + psizer.Add(self.xMaxText, pos=(2,2), flag=wx.TOP|wx.LEFT) + self.xMaxText.Bind(wx.EVT_CHAR, self.onLimitChar) + self.xMaxText.Bind(wx.EVT_KILL_FOCUS, self.onGraphProps) + + yLimit = wx.StaticText(self.propsPanel, -1, "Y limits:") + psizer.Add(yLimit, pos=(3,0)) + self.yMinText = wx.TextCtrl(self.propsPanel, size=(60,config.textboxHeight)) + psizer.Add(self.yMinText, pos=(3,1), flag=wx.TOP|wx.LEFT) + self.yMinText.Bind(wx.EVT_CHAR, self.onLimitChar) + self.yMinText.Bind(wx.EVT_KILL_FOCUS, self.onGraphProps) + self.yMaxText = wx.TextCtrl(self.propsPanel, size=(60,config.textboxHeight)) + psizer.Add(self.yMaxText, pos=(3,2), flag=wx.TOP|wx.LEFT) + self.yMaxText.Bind(wx.EVT_CHAR, self.onLimitChar) + self.yMaxText.Bind(wx.EVT_KILL_FOCUS, self.onGraphProps) + + threshold = wx.StaticText(self.propsPanel, -1, "Threshold:") + psizer.Add(threshold, pos=(4,0)) + self.thresholdText = wx.TextCtrl(self.propsPanel, size=(100,config.textboxHeight)) + psizer.Add(self.thresholdText, pos=(4,1), span=(1,2), flag=wx.TOP|wx.LEFT) + self.thresholdText.Bind(wx.EVT_CHAR, self.onLimitChar) + self.thresholdText.Bind(wx.EVT_KILL_FOCUS, self.onGraphProps) + + self.binaryCheckbox = wx.CheckBox(self.propsPanel, label="Threshold binary") + psizer.Add(self.binaryCheckbox, pos=(5, 0), span=(1,3), flag=wx.TOP|wx.LEFT) + self.Bind(wx.EVT_CHECKBOX, self.onGraphProps, self.binaryCheckbox) + + self.interpolateCheckbox = wx.CheckBox(self.propsPanel, label="Interpolate missing values") + psizer.Add(self.interpolateCheckbox, pos=(6, 0), span=(1,3), flag=wx.TOP|wx.LEFT) + self.Bind(wx.EVT_CHECKBOX, self.onGraphProps, self.interpolateCheckbox) + + if (config.experimental): + self.exportButton = wx.Button(self.propsPanel, label = "Export") + psizer.Add(self.exportButton, pos=(7, 0), span=(1,4), flag=wx.TOP|wx.LEFT) + self.Bind(wx.EVT_BUTTON, self.onExport, self.exportButton) + + self.maskCheckboxes = [] + + # Setup sizers and panels + self.statsPanel.SetSizer(ssizer) + ssizer.Fit(self.statsPanel) + self.propsPanel.SetSizer(psizer) + psizer.Fit(self.propsPanel) + self.maskPanel.SetSizer(self.maskSizer) + self.maskSizer.Fit(self.maskPanel) + + self.statsPanel.SetSize(10, 10, config.propertiesWidth - 20, self.statsPanel.GetClientSize().Height) + self.propsPanel.SetSize(10, 15 + self.statsPanel.GetClientSize().Height, config.propertiesWidth - 20, self.propsPanel.GetClientSize().Height) + self.maskPanel.SetSize(10, 20 + self.statsPanel.GetClientSize().Height + self.propsPanel.GetClientSize().Height, config.propertiesWidth - 20, self.maskPanel.GetClientSize().Height) + + self.setGraphProps() + self.hidePanels() + + + # Calculate and set statistics UI + def setStats(self): + count = 0 + activeCount = 0 + for i in range(0, self.graphState.data.shape[0]): + for j in range(0, self.graphState.data.shape[1]): + if (not math.isnan(self.graphState.data[i][j])): + count = count + 1 + if (self.graphState.data[i][j] <= self.graphState.threshold): + activeCount = activeCount + 1 + + self.statsCount.SetLabelText(str(count) + " results") + self.statsActive.SetLabelText(str(int(activeCount/count*10000)/100) + "% active") + + + # Limit x and y limit inputs to numbers + def onLimitChar(self, event): + key = event.GetKeyCode() + if (chr(key).isdigit() or key == wx.WXK_LEFT or key == wx.WXK_RIGHT or key == wx.WXK_BACK or key == wx.WXK_RETURN or key == wx.WXK_ESCAPE or key == wx.WXK_TAB): + event.Skip(True) + if (key == wx.WXK_RETURN): + self.onGraphProps(None) + + # On a properties change, update graph state + def onGraphProps(self, event): + if (self.propsPanel.IsShown()): + if (self.xMinText.GetValue() == ""): + self.xMinText.ChangeValue("0") + if (self.xMaxText.GetValue() == ""): + self.xMaxText.ChangeValue("0") + if (self.yMinText.GetValue() == ""): + self.yMinText.ChangeValue("0") + if (self.yMaxText.GetValue() == ""): + self.yMaxText.ChangeValue("0") + if (self.thresholdText.GetValue() == ""): + self.thresholdText.ChangeValue("0") + + self.graphState.threshold = int(self.thresholdText.GetValue()) + self.graphState.thresholdBinary = self.binaryCheckbox.IsChecked() + self.graphState.interpolateMissing = self.interpolateCheckbox.IsChecked() + self.graphState.xLimit = [int(self.xMinText.GetValue()), int(self.xMaxText.GetValue())] + self.graphState.yLimit = [int(self.yMinText.GetValue()), int(self.yMaxText.GetValue())] + + if (config.experimental): + self.graphState.type = self.graphChoice.GetSelection() + + # Set graph mask + for i in range(0,len(self.maskCheckboxes),1): + self.graphState.mask[i] = self.maskCheckboxes[i].IsChecked() + + evt = graphPropsUpdateEvent() + wx.PostEvent(self, evt) + self.setStats() + + + # Set graph properties UI elements + def setGraphProps(self): + self.binaryCheckbox.SetValue(self.graphState.thresholdBinary) + self.interpolateCheckbox.SetValue(self.graphState.interpolateMissing) + self.thresholdText.ChangeValue(str(self.graphState.threshold)) + self.xMinText.ChangeValue(str(self.graphState.xLimit[0])) + self.xMaxText.ChangeValue(str(self.graphState.xLimit[1])) + self.yMinText.ChangeValue(str(self.graphState.yLimit[0])) + self.yMaxText.ChangeValue(str(self.graphState.yLimit[1])) + + if (config.experimental): + self.graphChoice.SetSelection(self.graphState.type) + + if (len(self.graphState.mask) != len(self.maskCheckboxes)): + # Remove mask checkboxes + self.maskSizer.Clear() + for i in range(0,len(self.maskCheckboxes),1): + self.maskCheckboxes[-1].Destroy() + self.maskCheckboxes.pop() + + line = wx.StaticLine(self.maskPanel) + self.maskSizer.Add(line, pos=(0, 0), flag=wx.EXPAND|wx.TOP) + + # Add mask checkboxes + for i in range(0,len(self.graphState.mask),1): + if len(self.graphState.monitorLocations) > 0: + self.maskCheckboxes.append(wx.CheckBox(self.maskPanel, label=self.graphState.monitor[i])) + else: + self.maskCheckboxes.append(wx.CheckBox(self.maskPanel, label=("Set " + str(i+1)))) + self.maskSizer.Add(self.maskCheckboxes[-1], pos=(i+1, 0)) + self.Bind(wx.EVT_CHECKBOX, self.onGraphProps, self.maskCheckboxes[-1]) + self.maskCheckboxes[i].SetValue(self.graphState.mask[i]) + self.maskCheckboxes[i].SetBackgroundColour(config.graphColours[i%len(config.graphColours)]) + + else: + # Set mask checkboxes + for i in range(0,len(self.maskCheckboxes),1): + self.maskCheckboxes[i].SetValue(self.graphState.mask[i]) + + self.maskPanel.Layout() + self.maskSizer.Fit(self.maskPanel) + self.maskPanel.SetSize(10, 20 + self.statsPanel.GetClientSize().Height + self.propsPanel.GetClientSize().Height, config.propertiesWidth - 20, self.maskPanel.GetClientSize().Height) + + # Export graph to matplot + def onExport(self, event): + # TODO: Export is buggy and requires testing. + step = 20 + base = 3 + numLoc = len(self.graphState.monitorLocations) + data = np.array(self.graphState.data).transpose() + fig = plt.figure() + ax = fig.add_subplot(111) + if self.graphState.thresholdBinary: + plt.ylim(self.graphState.threshold - step * (numLoc+base),self.graphState.threshold + step * (numLoc+base)) + for i in range(data.shape[0]): + for j in range(data.shape[1]): + if data[i][j] >= self.graphState.threshold: + data[i][j] = step*(base+i) + self.graphState.threshold + else: + data[i][j] = -step*(base+i) + self.graphState.threshold + + #plt.ylim(0, 3* self.graphState.threshold) + plt.xlabel('time slot') + plt.ylabel('access time') + cm = plt.get_cmap('gist_rainbow') + ax.set_prop_cycle(color = [cm(1.*i/numLoc) for i in range(numLoc)]) + #plt.plot([1,2],[3,4], 'r--', label = 'mul') + for i in range(numLoc): + ax.plot(data[i],'-',label = self.graphState.monitorLocations[i]) + + #fig.savefig('moreColors.png') + plt.legend() + plt.show() + + # Hide all panels + def hidePanels(self): + self.propsPanel.Hide() + self.statsPanel.Hide() + self.maskPanel.Hide() + + + # Show all panels + def showPanels(self): + self.statsPanel.Show() + self.propsPanel.Show() + self.maskPanel.Show() + self.statsPanel.Raise() + self.propsPanel.Raise() + self.maskPanel.Raise() + self.Layout() diff --git a/tools/Doubloon/src/State.py b/tools/Doubloon/src/State.py new file mode 100644 index 0000000..bb86377 --- /dev/null +++ b/tools/Doubloon/src/State.py @@ -0,0 +1,199 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import numpy + + + +# Attack types +EXTERNAL_ATTACK_TYPE_GENERAL = 0 +EXTERNAL_ATTACK_TYPE_FRTRACE = 1 + +# Graph types +GRAPH_TYPE_LINE = 0 +GRAPH_TYPE_MAP = 1 + + +# Represents the state of external attacks +# Includes attack configuration, victim details and SSH settings +class ExternalAttackState: + def __init__(self): + + # Default configuration for attacks. These values can be modified + + # General attack + self.attackProgram = "" + self.attackArgs = "" + + # FR-trace attack + self.frProgram = "FR-trace" + self.frSlotlen = 5000 + self.frMaxSamples = 100000 + self.frThreshold = 100 + self.frIdle = 500 + self.frHeader = False # Unused + self.frMonitor = "" + self.frEvict = "" + self.frPDACount = 0 + self.frPDA = "" + + # Common details + self.type = EXTERNAL_ATTACK_TYPE_GENERAL + self.victimProgram = "" + self.victimArgs = "" + self.victimRun = False + + # SSH settings + self.sshRun = False + self.sshHostname = "" + self.sshPort = 22 + self.sshUsername = "" + self.sshPassword = "" + + + # Convert relevent configuration values to dictionary, to be saved + def toDictionary(self): + dict = {} + dict["attackProgram"] = self.attackProgram + dict["attackArgs"] = self.attackArgs + + dict["frProgram"] = self.frProgram + dict["frSlotlen"] = self.frSlotlen + dict["frMaxSamples"] = self.frMaxSamples + dict["frThreshold"] = self.frThreshold + dict["frIdle"] = self.frIdle + dict["frHeader"] = self.frHeader + dict["frMonitor"] = self.frMonitor + dict["frEvict"] = self.frEvict + dict["frPDACount"] = self.frPDACount + dict["frPDA"] = self.frPDA + + dict["type"] = self.type + dict["victimProgram"] = self.victimProgram + dict["victimArgs"] = self.victimArgs + dict["victimRun"] = self.victimRun + + dict["sshRun"] = self.sshRun + dict["sshHostname"] = self.sshHostname + dict["sshPort"] = self.sshPort + dict["sshUsername"] = self.sshUsername + + # Don't save password + #dict["sshPassword"] = self.sshPassword + + return dict + + + # Set configuration from dictionary + def fromDictionary(self, dict): + self.attackProgram = dict["attackProgram"] + self.attackArgs = dict["attackArgs"] + + self.frProgram = dict["frProgram"] + self.frSlotlen = dict["frSlotlen"] + self.frMaxSamples = dict["frMaxSamples"] + self.frThreshold = dict["frThreshold"] + self.frIdle = dict["frIdle"] + self.frHeader = dict["frHeader"] + self.frMonitor = dict["frMonitor"] + self.frEvict = dict["frEvict"] + self.frPDACount = dict["frPDACount"] + self.frPDA = dict["frPDA"] + + self.type = dict["type"] + self.victimProgram = dict["victimProgram"] + self.victimArgs = dict["victimArgs"] + self.victimRun = dict["victimRun"] + + self.sshRun = dict["sshRun"] + self.sshHostname = dict["sshHostname"] + self.sshPort = dict["sshPort"] + self.sshUsername = dict["sshUsername"] + + + +# Represents the state of the graph and data +class GraphState: + def __init__(self): + + # Data is None or a numpy array + self.data = None + + # Graph type + self.type = GRAPH_TYPE_LINE + + # Labels for monitored locations + self.monitorLocations = [] + + # Graph drawing properties + self.threshold = 100 + self.xLimit = [0,0] + self.yLimit = [0,0] + + # Graph filtering and options + self.mask = [] # True or false vector for each set of data + self.highlightUnderThreshold = False # Unused + self.interpolateMissing = True + self.thresholdBinary = False + + + # Convert relevent settings and data to dictionary, to be saved + def toDictionary(self): + dict = {} + + if (self.data is None): + dict["data"] = self.data + else: + dict["data"] = self.data.tolist() + + dict["threshold"] = self.threshold + dict["xLimit"] = self.xLimit + dict["yLimit"] = self.yLimit + dict["mask"] = self.mask + dict["highlightUnderThreshold"] = self.highlightUnderThreshold + dict["interpolateMissing"] = self.interpolateMissing + dict["thresholdBinary"] = self.thresholdBinary + dict["type"] = self.type + + return dict + + + # Set settings and data from dictionary + def fromDictionary(self, dict): + if (dict["data"] is None): + self.data = dict["data"] + else: + self.data = numpy.array(dict["data"], dtype=float) + + self.threshold = dict["threshold"] + self.xLimit = dict["xLimit"] + self.yLimit = dict["yLimit"] + self.mask = dict["mask"] + self.highlightUnderThreshold = dict["highlightUnderThreshold"] + self.interpolateMissing = dict["interpolateMissing"] + self.thresholdBinary = dict["thresholdBinary"] + + if ("type" in dict): + self.type = dict["type"] + + return dict + diff --git a/tools/Doubloon/src/ToolbarView.py b/tools/Doubloon/src/ToolbarView.py new file mode 100755 index 0000000..2e1d5fc --- /dev/null +++ b/tools/Doubloon/src/ToolbarView.py @@ -0,0 +1,118 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx +import config as cfg +from util import * +from Events import * + + + +# Toolbar view with common application functions +class ToolbarView(wx.ToolBar): + def __init__(self, parent): + super(ToolbarView, self).__init__(parent, -1) + self.SetToolBitmapSize(wx.Size(32,32)) + + # Setup toolbar items + self.runTool = self.AddTool(101, "Run", wx.Bitmap(cfg.getResource(cfg.RES_ICON_PLAY))) + self.Bind(wx.EVT_TOOL, self.onRunExternalAttack, self.runTool) + + self.configTool = self.AddTool(102, "Config", wx.Bitmap(cfg.getResource(cfg.RES_ICON_CONFIG))) + self.Bind(wx.EVT_TOOL, self.onOpenExternalAttackConfig, self.configTool) + + if (cfg.dwarfSupport and cfg.experimental): + self.AddSeparator() + self.assemblyTool = self.AddTool(482, "Open Assembly", wx.Bitmap(wx.Bitmap(cfg.getResource(cfg.RES_ICON_X86)))) + self.Bind(wx.EVT_TOOL, self.onOpenAssemblyFrame, self.assemblyTool) + + self.AddSeparator() + + self.loadStateTool = self.AddTool(201, "Load State", wx.Bitmap(cfg.getResource(cfg.RES_ICON_OPEN))) + self.Bind(wx.EVT_TOOL, self.onLoadState, self.loadStateTool) + + self.saveStateTool = self.AddTool(202, "Save State", wx.Bitmap(cfg.getResource(cfg.RES_ICON_SAVE))) + self.Bind(wx.EVT_TOOL, self.onSaveState, self.saveStateTool) + + self.AddSeparator() + + self.loadDataTool = self.AddTool(301, "Load Data", wx.Bitmap(cfg.getResource(cfg.RES_ICON_IMPORT))) + self.Bind(wx.EVT_TOOL, self.onLoadData, self.loadDataTool) + + self.saveDataTool = self.AddTool(302, "Save Data", wx.Bitmap(cfg.getResource(cfg.RES_ICON_EXPORT))) + self.Bind(wx.EVT_TOOL, self.onSaveData, self.saveDataTool) + + self.Realize() + + + # Raise run attack event and switch icon to cancel + def onRunExternalAttack(self, event): + evt = runExternalAttackEvent() + wx.PostEvent(self, evt) + self.DeleteTool(101) + self.runTool = self.InsertTool(0, 101, "Cancel", wx.Bitmap(cfg.getResource(cfg.RES_ICON_STOP))) + self.Realize() + self.Bind(wx.EVT_TOOL, self.onRunExternalAttack, self.runTool) + + + # When attack is done/cancelled, switch icon to run + def onExternalAttackDone(self, event): + self.DeleteTool(101) + self.runTool = self.InsertTool(0, 101, "Run", wx.Bitmap(cfg.getResource(cfg.RES_ICON_PLAY))) + self.Realize() + self.Bind(wx.EVT_TOOL, self.onRunExternalAttack, self.runTool) + + + # Raise config attack event to open config frame + def onOpenExternalAttackConfig(self, event): + evt = openExternalAttackConfigEvent() + wx.PostEvent(self, evt) + + + # Notify application to load data file + def onLoadData(self, event): + evt = loadDataEvent() + wx.PostEvent(self, evt) + + + # Notify application to save data file + def onSaveData(self, event): + evt = saveDataEvent() + wx.PostEvent(self, evt) + + + # Notify application to load state file + def onLoadState(self, event): + evt = loadStateEvent() + wx.PostEvent(self, evt) + + + # Notify application to save state file + def onSaveState(self, event): + evt = saveStateEvent() + wx.PostEvent(self, evt) + + # Open assembly view + def onOpenAssemblyFrame(self, event): + evt = openAssemblyFrameEvent() + wx.PostEvent(self, evt) + diff --git a/tools/Doubloon/src/__main__.py b/tools/Doubloon/src/__main__.py new file mode 100755 index 0000000..84029ba --- /dev/null +++ b/tools/Doubloon/src/__main__.py @@ -0,0 +1,34 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +from Application import * + + + +# Run the application +def main(): + app = Application() + app.run() + + +if __name__ == '__main__': + main() diff --git a/tools/Doubloon/src/config.py.in b/tools/Doubloon/src/config.py.in new file mode 100755 index 0000000..289d7c6 --- /dev/null +++ b/tools/Doubloon/src/config.py.in @@ -0,0 +1,72 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx +import os + + +# Application configuration +# These values can be changed + +# General application properties +applicationName = "Doubloon" +applicationExtension = "dbl" +defaultWindowSize = (1080, 720) +propertiesAlignment = "right" # left or right +propertiesWidth = 220 +textboxHeight = @DOUBLOON_TEXTBOX_HEIGHT@ +dwarfSupport = @DOUBLOON_HAVE_DWARF@ +printMetrics = False +experimental = @DOUBLOON_EXPERIMENTAL@ + +# Graph drawing colours +graphColours = [wx.Colour(255, 0, 0), wx.Colour(0, 0, 255), wx.Colour(0, 255, 0), wx.Colour(255, 255, 0), wx.Colour(0, 255, 255), wx.Colour(255, 0, 255), wx.Colour(255, 128, 0), wx.Colour(128, 0, 255), wx.Colour(0, 255, 128)] +graphBackground = wx.Colour(0, 0, 0) +graphForeground = wx.Colour(255, 255, 255) +graphGrid = wx.Colour(60, 60, 60) +graphBorder = wx.Colour(120, 120, 120) +assemblyColorA = wx.Colour(0,196,255) +assemblyColorAB = wx.Colour(64,220,128) +assemblyColorB = wx.Colour(128,255,0) + +# Depending on your computer, this value can be adjusted to increase or decrease the number of results drawn +graphMaxResolution = 500 + +# Graph properties +graphZoomFactor = 1.5 +graphShiftFactor = 0.25 +graphMinXSize = 50 +graphMinYSize = 10 +graphDefaultYLimits = [0, 300] + +RES_ICON_PLAY = "icons/play-26.png" +RES_ICON_STOP = "icons/stop-26.png" +RES_ICON_CONFIG = "icons/config-26.png" +RES_ICON_OPEN = "icons/open-26.png" +RES_ICON_SAVE = "icons/save-26.png" +RES_ICON_EXPORT = "icons/export-26.png" +RES_ICON_IMPORT = "icons/import-26.png" +RES_ICON_X86 = "icons/x86-26.png" + +__RES_BASE_PATH = "@DOUBLOON_INSTALL_DATADIR@" +def getResource(resource): + return os.path.join(__RES_BASE_PATH, resource) diff --git a/tools/Doubloon/src/util.py b/tools/Doubloon/src/util.py new file mode 100644 index 0000000..6201d07 --- /dev/null +++ b/tools/Doubloon/src/util.py @@ -0,0 +1,57 @@ +""" +Copyright 2018 Dallas McNeil + +This file is part of Mastik. +Mastik is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mastik is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mastik. If not, see . + + +Author: Dallas McNeil a1724759@student.adelaide.edu.au +""" + + +import wx +import numpy +import re + + +# Show an error dialog with a message +def errorMessage(title, message): + print(title + ": " + message) + dial = wx.MessageDialog(None, message, title, + wx.OK | wx.ICON_ERROR) + dial.ShowModal() + + +# Convert results string to numpy array, used to load in data from file or attack process +def resultsStringToArray(results): + # TODO: This could be optimised + allLines = results.splitlines() + lines = list(filter(isNotComment, allLines)) + array = numpy.empty((len(lines),len(lines[0].split()))) + + for i in range(0, len(lines)): + splitLine = lines[i].split() + for j in range(0, len(splitLine)): + value = int(splitLine[j]) + if (value != 0): + array[i][j] = int(splitLine[j]) + else: + array[i][j] = float("nan") + + return array + + +# Determines if a line is a comment or not +def isNotComment(str): + return str[0] != "#" \ No newline at end of file diff --git a/tools/Makefile.in b/tools/Makefile.in new file mode 100644 index 0000000..c738320 --- /dev/null +++ b/tools/Makefile.in @@ -0,0 +1,18 @@ +SUBDIRS=@TOOLS@ + +all: + for f in ${SUBDIRS}; do ${MAKE} -C $$f || break ; done + +install: all + for f in ${SUBDIRS}; do ${MAKE} -C $$f install || break ; done + +clean: cleansubdirs localclean + +cleansubdirs: + for f in ${SUBDIRS}; do ${MAKE} -C $$f clean; done + +localclean: + +distclean: localclean + for f in ${SUBDIRS}; do ${MAKE} -C $$f distclean; done + rm Makefile