<commit_before>#include <botan/dsa.h>
#include <botan/rsa.h>
#include <botan/dh.h>
#include <botan/nr.h>
#include <botan/rw.h>
#include <botan/elgamal.h>
#include <botan/parsing.h>

#include <botan/pkcs8.h>
#include <botan/mem_ops.h>
#include <botan/look_pk.h>
#include <botan/libstate.h>

using namespace Botan;

#include "common.h"
#include "timer.h"
#include "bench.h"

#include <iostream>
#include <fstream>
#include <string>
#include <memory>

namespace {

void benchmark_enc_dec(PK_Encryptor& enc, PK_Decryptor& dec,
                       Timer& enc_timer, Timer& dec_timer,
                       RandomNumberGenerator& rng,
                       u32bit runs, double seconds)
   {
   SecureVector<byte> plaintext, ciphertext;

   for(u32bit i = 0; i != runs; ++i)
      {
      if(enc_timer.seconds() < seconds || ciphertext.size() == 0)
         {
         plaintext.create(enc.maximum_input_size());

         // Ensure for Raw, etc, it stays large
         if((i % 100) == 0)
            {
            rng.randomize(plaintext.begin(), plaintext.size());
            plaintext[0] |= 0x80;
            }

         enc_timer.start();
         ciphertext = enc.encrypt(plaintext, rng);
         enc_timer.stop();
         }

      if(dec_timer.seconds() < seconds)
         {
         dec_timer.start();
         SecureVector<byte> plaintext_out = dec.decrypt(ciphertext);
         dec_timer.stop();

         if(plaintext_out != plaintext)
            { // has never happened...
            std::cerr << "Contents mismatched on decryption during benchmark!\n";
            }
         }
      }
   }

void benchmark_sig_ver(PK_Verifier& ver, PK_Signer& sig,
                       Timer& verify_timer, Timer& sig_timer,
                       RandomNumberGenerator& rng,
                       u32bit runs, double seconds)
   {
   SecureVector<byte> message, signature, sig_random;

   for(u32bit i = 0; i != runs; ++i)
      {
      if(sig_timer.seconds() < seconds || signature.size() == 0)
         {
         if((i % 100) == 0)
            {
            message.create(48);
            rng.randomize(message.begin(), message.size());
            }

         sig_timer.start();
         signature = sig.sign_message(message, rng);
         sig_timer.stop();
         }

      if(verify_timer.seconds() < seconds)
         {
         verify_timer.start();
         bool verified = ver.verify_message(message, signature);
         verify_timer.stop();

         if(!verified)
            std::cerr << "Signature verification failure\n";

         if((i % 100) == 0)
            {
            sig_random.create(signature.size());
            rng.randomize(sig_random, sig_random.size());

            verify_timer.start();
            bool verified2 = ver.verify_message(message, sig_random);
            verify_timer.stop();

            if(verified2)
               std::cerr << "Signature verification failure (bad sig OK)\n";
            }
         }
      }
   }

/*
  Between benchmark_rsa_rw + benchmark_dsa_nr:
     Type of the key
     Arguments to the constructor (A list of some arbitrary type?)
     Type of padding
*/

void benchmark_rsa(RandomNumberGenerator& rng,
                   double seconds,
                   Benchmark_Report& report)
   {
   for(size_t keylen = 512; keylen <= 8192; keylen += 256)
      {
      Timer verify_timer("verify");
      Timer sig_timer("signature");
      Timer enc_timer("encrypt");
      Timer dec_timer("decrypt");

      const std::string sig_padding = "EMSA4(SHA-1)";
      const std::string enc_padding = "EME1(SHA-1)";

      try
         {
         PKCS8_PrivateKey* pkcs8_key = PKCS8::load_key("rsa/" + to_string(keylen) + ".pem", rng);
         RSA_PrivateKey* key_ptr = dynamic_cast<RSA_PrivateKey*>(pkcs8_key);

         RSA_PrivateKey key = *key_ptr;

         while(verify_timer.seconds() < seconds ||
               sig_timer.seconds() < seconds)
            {
            std::auto_ptr<PK_Encryptor> enc(get_pk_encryptor(key, enc_padding));
            std::auto_ptr<PK_Decryptor> dec(get_pk_decryptor(key, enc_padding));
            benchmark_enc_dec(*enc, *dec, enc_timer, dec_timer, rng, 10000, seconds);

            std::auto_ptr<PK_Signer> sig(get_pk_signer(key, sig_padding));
            std::auto_ptr<PK_Verifier> ver(get_pk_verifier(key, sig_padding));
            benchmark_sig_ver(*ver, *sig, verify_timer, sig_timer, rng, 10000, seconds);
            }

         const std::string rsa_keylen = "RSA " + to_string(keylen);

         report.report(rsa_keylen + " " + sig_padding, verify_timer);
         report.report(rsa_keylen + " " + sig_padding, sig_timer);
         report.report(rsa_keylen + " " + enc_padding, enc_timer);
         report.report(rsa_keylen + " " + enc_padding, dec_timer);
         }
      catch(Stream_IO_Error)
         {
         }
      catch(Exception& e)
         {
         std::cout << e.what() << "\n";
         }
      }
   }

void benchmark_rw(RandomNumberGenerator& rng,
                  double seconds,
                  Benchmark_Report& report)
   {
   const u32bit keylens[] = { 512, 1024, 2048, 3072, 4096, 6144, 8192, 0 };

   for(size_t j = 0; keylens[j]; j++)
      {
      u32bit keylen = keylens[j];

      Timer keygen_timer("keygen");
      Timer verify_timer("verify");
      Timer sig_timer("signature");

      std::string padding = "EMSA2(SHA-1)";

      while(verify_timer.seconds() < seconds ||
            sig_timer.seconds() < seconds)
         {
         keygen_timer.start();
         RW_PrivateKey key(rng, keylen);
         keygen_timer.stop();

         std::auto_ptr<PK_Signer> sig(get_pk_signer(key, padding));
         std::auto_ptr<PK_Verifier> ver(get_pk_verifier(key, padding));

         benchmark_sig_ver(*ver, *sig, verify_timer, sig_timer, rng, 10000, seconds);
         }

      const std::string nm = "RW-" + to_string(keylen);
      report.report(nm, keygen_timer);
      report.report(nm, verify_timer);
      report.report(nm, sig_timer);
      }
   }

template<typename PRIV_KEY_TYPE>
void benchmark_dsa_nr(RandomNumberGenerator& rng,
                      double seconds,
                      Benchmark_Report& report)
   {
   const char* domains[] = { "dsa/jce/512",
                             "dsa/jce/768",
                             "dsa/jce/1024",
                             "dsa/botan/2048",
                             "dsa/botan/3072",
                             NULL };

   const std::string algo_name = PRIV_KEY_TYPE().algo_name();

   for(size_t j = 0; domains[j]; j++)
      {
      u32bit pbits = to_u32bit(split_on(domains[j], '/')[2]);
      u32bit qbits = (pbits <= 1024) ? 160 : 256;

      Timer keygen_timer("keygen");
      Timer verify_timer("verify");
      Timer sig_timer("signature");

      while(verify_timer.seconds() < seconds ||
            sig_timer.seconds() < seconds)
         {
         DL_Group group(domains[j]);

         keygen_timer.start();
         PRIV_KEY_TYPE key(rng, group);
         keygen_timer.stop();

         const std::string padding = "EMSA1(SHA-" + to_string(qbits) + ")";

         std::auto_ptr<PK_Signer> sig(get_pk_signer(key, padding));
         std::auto_ptr<PK_Verifier> ver(get_pk_verifier(key, padding));

         benchmark_sig_ver(*ver, *sig, verify_timer, sig_timer, rng, 1000, seconds);
         }

      const std::string nm = algo_name + "-" + to_string(pbits);
      report.report(nm, keygen_timer);
      report.report(nm, verify_timer);
      report.report(nm, sig_timer);
      }
   }

void benchmark_dh(RandomNumberGenerator& rng,
                  double seconds,
                  Benchmark_Report& report)
   {
   const char* domains[] = { "modp/ietf/768",
                             "modp/ietf/1024",
                             "modp/ietf/2048",
                             "modp/ietf/3072",
                             "modp/ietf/4096",
                             "modp/ietf/6144",
                             "modp/ietf/8192",
                             NULL };

   for(size_t j = 0; domains[j]; j++)
      {
      Timer keygen_timer("keygen");
      Timer kex_timer("kex");

      while(kex_timer.seconds() < seconds)
         {
         DL_Group group(domains[j]);

         keygen_timer.start();
         DH_PrivateKey dh1(rng, group);
         keygen_timer.stop();

         keygen_timer.start();
         DH_PrivateKey dh2(rng, group);
         keygen_timer.stop();

         DH_PublicKey pub1(dh1);
         DH_PublicKey pub2(dh2);

         SecureVector<byte> secret1, secret2;

         for(u32bit i = 0; i != 1000; ++i)
            {
            if(kex_timer.seconds() > seconds)
               break;

            kex_timer.start();
            secret1 = dh1.derive_key(pub2);
            kex_timer.stop();

            kex_timer.start();
            secret2 = dh2.derive_key(pub1);
            kex_timer.stop();

            if(secret1 != secret2)
               {
               std::cerr << "DH secrets did not match, bug in the library!?!\n";
               }

            }

         }

      const std::string nm = "DH-" + split_on(domains[j], '/')[2];
      report.report(nm, keygen_timer);
      report.report(nm, kex_timer);
      }
   }

void benchmark_elg(RandomNumberGenerator& rng,
                   double seconds,
                   Benchmark_Report& report)
   {
   const char* domains[] = { "modp/ietf/768",
                             "modp/ietf/1024",
                             "modp/ietf/2048",
                             "modp/ietf/3072",
                             "modp/ietf/4096",
                             "modp/ietf/6144",
                             "modp/ietf/8192",
                             NULL };

   const std::string algo_name = "ElGamal";

   for(size_t j = 0; domains[j]; j++)
      {
      u32bit pbits = to_u32bit(split_on(domains[j], '/')[2]);

      Timer keygen_timer("keygen");
      Timer enc_timer("encrypt");
      Timer dec_timer("decrypt");

      while(enc_timer.seconds() < seconds ||
            dec_timer.seconds() < seconds)
         {
         DL_Group group(domains[j]);

         keygen_timer.start();
         ElGamal_PrivateKey key(rng, group);
         keygen_timer.stop();

         const std::string padding = "EME1(SHA-1)";

         std::auto_ptr<PK_Decryptor> dec(get_pk_decryptor(key, padding));
         std::auto_ptr<PK_Encryptor> enc(get_pk_encryptor(key, padding));

         benchmark_enc_dec(*enc, *dec, enc_timer, dec_timer, rng, 1000, seconds);
         }

      const std::string nm = algo_name + "-" + to_string(pbits);
      report.report(nm, keygen_timer);
      report.report(nm, enc_timer);
      report.report(nm, dec_timer);
      }
   }

}

void bench_pk(RandomNumberGenerator& rng,
              const std::string& algo, bool, double seconds)
   {
   /*
     There is some strangeness going on here. It looks like algorithms
     at the end take some kind of penalty. For example, running the RW tests
     first got a result of:
         RW-1024: 148.14 ms / private operation
     but running them last output:
         RW-1024: 363.54 ms / private operation

     I think it's from memory fragmentation in the allocators, but I'm
     not really sure. Need to investigate.

     Until then, I've basically ordered the tests in order of most important
     algorithms (RSA, DSA) to least important (NR, RW).

     This strange behaviour does not seem to occur with DH (?)

     To get more accurate runs, use --bench-algo (RSA|DSA|DH|ELG|NR); in this
     case the distortion is less than 5%, which is good enough.

     We do random keys with the DL schemes, since it's so easy and fast to
     generate keys for them. For RSA and RW, we load the keys from a file.  The
     RSA keys are stored in a PKCS #8 structure, while RW is stored in a more
     ad-hoc format (the RW algorithm has no assigned OID that I know of, so
     there is no way to encode a RW key into a PKCS #8 structure).
   */

   global_state().set_option("pk/test/private_gen", "basic");

   Benchmark_Report report;

   if(algo == "All" || algo == "RSA")
      benchmark_rsa(rng, seconds, report);

   if(algo == "All" || algo == "DSA")
      benchmark_dsa_nr<DSA_PrivateKey>(rng, seconds, report);

   if(algo == "All" || algo == "DH")
      benchmark_dh(rng, seconds, report);

   if(algo == "All" || algo == "ELG" || algo == "ElGamal")
      benchmark_elg(rng, seconds, report);

   if(algo == "All" || algo == "NR")
      benchmark_dsa_nr<NR_PrivateKey>(rng, seconds, report);

   if(algo == "All" || algo == "RW")
      benchmark_rw(rng, seconds, report);
   }
<commit_msg>Oops disable part of previous, was for testing<commit_after>#include <botan/dsa.h>
#include <botan/rsa.h>
#include <botan/dh.h>
#include <botan/nr.h>
#include <botan/rw.h>
#include <botan/elgamal.h>
#include <botan/parsing.h>

#include <botan/pkcs8.h>
#include <botan/mem_ops.h>
#include <botan/look_pk.h>
#include <botan/libstate.h>

using namespace Botan;

#include "common.h"
#include "timer.h"
#include "bench.h"

#include <iostream>
#include <fstream>
#include <string>
#include <memory>

namespace {

void benchmark_enc_dec(PK_Encryptor& enc, PK_Decryptor& dec,
                       Timer& enc_timer, Timer& dec_timer,
                       RandomNumberGenerator& rng,
                       u32bit runs, double seconds)
   {
   SecureVector<byte> plaintext, ciphertext;

   for(u32bit i = 0; i != runs; ++i)
      {
      if(enc_timer.seconds() < seconds || ciphertext.size() == 0)
         {
         plaintext.create(enc.maximum_input_size());

         // Ensure for Raw, etc, it stays large
         if((i % 100) == 0)
            {
            rng.randomize(plaintext.begin(), plaintext.size());
            plaintext[0] |= 0x80;
            }

         enc_timer.start();
         ciphertext = enc.encrypt(plaintext, rng);
         enc_timer.stop();
         }

      if(dec_timer.seconds() < seconds)
         {
         dec_timer.start();
         SecureVector<byte> plaintext_out = dec.decrypt(ciphertext);
         dec_timer.stop();

         if(plaintext_out != plaintext)
            { // has never happened...
            std::cerr << "Contents mismatched on decryption during benchmark!\n";
            }
         }
      }
   }

void benchmark_sig_ver(PK_Verifier& ver, PK_Signer& sig,
                       Timer& verify_timer, Timer& sig_timer,
                       RandomNumberGenerator& rng,
                       u32bit runs, double seconds)
   {
   SecureVector<byte> message, signature, sig_random;

   for(u32bit i = 0; i != runs; ++i)
      {
      if(sig_timer.seconds() < seconds || signature.size() == 0)
         {
         if((i % 100) == 0)
            {
            message.create(48);
            rng.randomize(message.begin(), message.size());
            }

         sig_timer.start();
         signature = sig.sign_message(message, rng);
         sig_timer.stop();
         }

      if(verify_timer.seconds() < seconds)
         {
         verify_timer.start();
         bool verified = ver.verify_message(message, signature);
         verify_timer.stop();

         if(!verified)
            std::cerr << "Signature verification failure\n";

         if((i % 100) == 0)
            {
            sig_random.create(signature.size());
            rng.randomize(sig_random, sig_random.size());

            verify_timer.start();
            bool verified2 = ver.verify_message(message, sig_random);
            verify_timer.stop();

            if(verified2)
               std::cerr << "Signature verification failure (bad sig OK)\n";
            }
         }
      }
   }

/*
  Between benchmark_rsa_rw + benchmark_dsa_nr:
     Type of the key
     Arguments to the constructor (A list of some arbitrary type?)
     Type of padding
*/

void benchmark_rsa(RandomNumberGenerator& rng,
                   double seconds,
                   Benchmark_Report& report)
   {
   for(size_t keylen = 1024; keylen <= 4096; keylen += 1024)
      {
      Timer verify_timer("verify");
      Timer sig_timer("signature");
      Timer enc_timer("encrypt");
      Timer dec_timer("decrypt");

      const std::string sig_padding = "EMSA4(SHA-1)";
      const std::string enc_padding = "EME1(SHA-1)";

      try
         {

#if 0
         PKCS8_PrivateKey* pkcs8_key = PKCS8::load_key("rsa/" + to_string(keylen) + ".pem", rng);
         RSA_PrivateKey* key_ptr = dynamic_cast<RSA_PrivateKey*>(pkcs8_key);

         RSA_PrivateKey key = *key_ptr;
#else

         RSA_PrivateKey key(rng, keylen);
#endif

         while(verify_timer.seconds() < seconds ||
               sig_timer.seconds() < seconds)
            {
            std::auto_ptr<PK_Encryptor> enc(get_pk_encryptor(key, enc_padding));
            std::auto_ptr<PK_Decryptor> dec(get_pk_decryptor(key, enc_padding));
            benchmark_enc_dec(*enc, *dec, enc_timer, dec_timer, rng, 10000, seconds);

            std::auto_ptr<PK_Signer> sig(get_pk_signer(key, sig_padding));
            std::auto_ptr<PK_Verifier> ver(get_pk_verifier(key, sig_padding));
            benchmark_sig_ver(*ver, *sig, verify_timer, sig_timer, rng, 10000, seconds);
            }

         const std::string rsa_keylen = "RSA " + to_string(keylen);

         report.report(rsa_keylen + " " + sig_padding, verify_timer);
         report.report(rsa_keylen + " " + sig_padding, sig_timer);
         report.report(rsa_keylen + " " + enc_padding, enc_timer);
         report.report(rsa_keylen + " " + enc_padding, dec_timer);
         }
      catch(Stream_IO_Error)
         {
         }
      catch(Exception& e)
         {
         std::cout << e.what() << "\n";
         }
      }
   }

void benchmark_rw(RandomNumberGenerator& rng,
                  double seconds,
                  Benchmark_Report& report)
   {
   const u32bit keylens[] = { 512, 1024, 2048, 3072, 4096, 6144, 8192, 0 };

   for(size_t j = 0; keylens[j]; j++)
      {
      u32bit keylen = keylens[j];

      Timer keygen_timer("keygen");
      Timer verify_timer("verify");
      Timer sig_timer("signature");

      std::string padding = "EMSA2(SHA-1)";

      while(verify_timer.seconds() < seconds ||
            sig_timer.seconds() < seconds)
         {
         keygen_timer.start();
         RW_PrivateKey key(rng, keylen);
         keygen_timer.stop();

         std::auto_ptr<PK_Signer> sig(get_pk_signer(key, padding));
         std::auto_ptr<PK_Verifier> ver(get_pk_verifier(key, padding));

         benchmark_sig_ver(*ver, *sig, verify_timer, sig_timer, rng, 10000, seconds);
         }

      const std::string nm = "RW-" + to_string(keylen);
      report.report(nm, keygen_timer);
      report.report(nm, verify_timer);
      report.report(nm, sig_timer);
      }
   }

template<typename PRIV_KEY_TYPE>
void benchmark_dsa_nr(RandomNumberGenerator& rng,
                      double seconds,
                      Benchmark_Report& report)
   {
   const char* domains[] = { "dsa/jce/512",
                             "dsa/jce/768",
                             "dsa/jce/1024",
                             "dsa/botan/2048",
                             "dsa/botan/3072",
                             NULL };

   const std::string algo_name = PRIV_KEY_TYPE().algo_name();

   for(size_t j = 0; domains[j]; j++)
      {
      u32bit pbits = to_u32bit(split_on(domains[j], '/')[2]);
      u32bit qbits = (pbits <= 1024) ? 160 : 256;

      Timer keygen_timer("keygen");
      Timer verify_timer("verify");
      Timer sig_timer("signature");

      while(verify_timer.seconds() < seconds ||
            sig_timer.seconds() < seconds)
         {
         DL_Group group(domains[j]);

         keygen_timer.start();
         PRIV_KEY_TYPE key(rng, group);
         keygen_timer.stop();

         const std::string padding = "EMSA1(SHA-" + to_string(qbits) + ")";

         std::auto_ptr<PK_Signer> sig(get_pk_signer(key, padding));
         std::auto_ptr<PK_Verifier> ver(get_pk_verifier(key, padding));

         benchmark_sig_ver(*ver, *sig, verify_timer, sig_timer, rng, 1000, seconds);
         }

      const std::string nm = algo_name + "-" + to_string(pbits);
      report.report(nm, keygen_timer);
      report.report(nm, verify_timer);
      report.report(nm, sig_timer);
      }
   }

void benchmark_dh(RandomNumberGenerator& rng,
                  double seconds,
                  Benchmark_Report& report)
   {
   const char* domains[] = { "modp/ietf/768",
                             "modp/ietf/1024",
                             "modp/ietf/2048",
                             "modp/ietf/3072",
                             "modp/ietf/4096",
                             "modp/ietf/6144",
                             "modp/ietf/8192",
                             NULL };

   for(size_t j = 0; domains[j]; j++)
      {
      Timer keygen_timer("keygen");
      Timer kex_timer("kex");

      while(kex_timer.seconds() < seconds)
         {
         DL_Group group(domains[j]);

         keygen_timer.start();
         DH_PrivateKey dh1(rng, group);
         keygen_timer.stop();

         keygen_timer.start();
         DH_PrivateKey dh2(rng, group);
         keygen_timer.stop();

         DH_PublicKey pub1(dh1);
         DH_PublicKey pub2(dh2);

         SecureVector<byte> secret1, secret2;

         for(u32bit i = 0; i != 1000; ++i)
            {
            if(kex_timer.seconds() > seconds)
               break;

            kex_timer.start();
            secret1 = dh1.derive_key(pub2);
            kex_timer.stop();

            kex_timer.start();
            secret2 = dh2.derive_key(pub1);
            kex_timer.stop();

            if(secret1 != secret2)
               {
               std::cerr << "DH secrets did not match, bug in the library!?!\n";
               }

            }

         }

      const std::string nm = "DH-" + split_on(domains[j], '/')[2];
      report.report(nm, keygen_timer);
      report.report(nm, kex_timer);
      }
   }

void benchmark_elg(RandomNumberGenerator& rng,
                   double seconds,
                   Benchmark_Report& report)
   {
   const char* domains[] = { "modp/ietf/768",
                             "modp/ietf/1024",
                             "modp/ietf/2048",
                             "modp/ietf/3072",
                             "modp/ietf/4096",
                             "modp/ietf/6144",
                             "modp/ietf/8192",
                             NULL };

   const std::string algo_name = "ElGamal";

   for(size_t j = 0; domains[j]; j++)
      {
      u32bit pbits = to_u32bit(split_on(domains[j], '/')[2]);

      Timer keygen_timer("keygen");
      Timer enc_timer("encrypt");
      Timer dec_timer("decrypt");

      while(enc_timer.seconds() < seconds ||
            dec_timer.seconds() < seconds)
         {
         DL_Group group(domains[j]);

         keygen_timer.start();
         ElGamal_PrivateKey key(rng, group);
         keygen_timer.stop();

         const std::string padding = "EME1(SHA-1)";

         std::auto_ptr<PK_Decryptor> dec(get_pk_decryptor(key, padding));
         std::auto_ptr<PK_Encryptor> enc(get_pk_encryptor(key, padding));

         benchmark_enc_dec(*enc, *dec, enc_timer, dec_timer, rng, 1000, seconds);
         }

      const std::string nm = algo_name + "-" + to_string(pbits);
      report.report(nm, keygen_timer);
      report.report(nm, enc_timer);
      report.report(nm, dec_timer);
      }
   }

}

void bench_pk(RandomNumberGenerator& rng,
              const std::string& algo, bool, double seconds)
   {
   /*
     There is some strangeness going on here. It looks like algorithms
     at the end take some kind of penalty. For example, running the RW tests
     first got a result of:
         RW-1024: 148.14 ms / private operation
     but running them last output:
         RW-1024: 363.54 ms / private operation

     I think it's from memory fragmentation in the allocators, but I'm
     not really sure. Need to investigate.

     Until then, I've basically ordered the tests in order of most important
     algorithms (RSA, DSA) to least important (NR, RW).

     This strange behaviour does not seem to occur with DH (?)

     To get more accurate runs, use --bench-algo (RSA|DSA|DH|ELG|NR); in this
     case the distortion is less than 5%, which is good enough.

     We do random keys with the DL schemes, since it's so easy and fast to
     generate keys for them. For RSA and RW, we load the keys from a file.  The
     RSA keys are stored in a PKCS #8 structure, while RW is stored in a more
     ad-hoc format (the RW algorithm has no assigned OID that I know of, so
     there is no way to encode a RW key into a PKCS #8 structure).
   */

   global_state().set_option("pk/test/private_gen", "basic");

   Benchmark_Report report;

   if(algo == "All" || algo == "RSA")
      benchmark_rsa(rng, seconds, report);

   if(algo == "All" || algo == "DSA")
      benchmark_dsa_nr<DSA_PrivateKey>(rng, seconds, report);

   if(algo == "All" || algo == "DH")
      benchmark_dh(rng, seconds, report);

   if(algo == "All" || algo == "ELG" || algo == "ElGamal")
      benchmark_elg(rng, seconds, report);

   if(algo == "All" || algo == "NR")
      benchmark_dsa_nr<NR_PrivateKey>(rng, seconds, report);

   if(algo == "All" || algo == "RW")
      benchmark_rw(rng, seconds, report);
   }
<|endoftext|>


<commit_before>47247cde-ad5a-11e7-8c33-ac87a332f658<commit_msg>roselyn broke it<commit_after>47cc0840-ad5a-11e7-8f22-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <mpi.h>
#include <algorithm>
#include <numeric>
#include <vector>
//#include "MPISharedVector.h"
#include <QElapsedTimer>
#include <memory.h>
#include <QDebug>

#include "include/MPI/Environment.h"
#include "include/MPI/Communicator.h"
#include "include/MPI/WindowObject.h"

#include "test/Test.h"

//const int ExecCount = 100;

int main(int argc, char *argv[])
{
    //! MPIの初期化
    MPIEnvPtr->Init( argc, argv );
    auto comm = MPIEnvPtr->CreateCommunicator( MPI_COMM_WORLD );

//    P2PTest( comm );
//    BcastTest( comm );
//    CorrectiveTest( comm );
//    CorrectiveAllTest( comm );

    WindowObjectTest( comm );

//    //! RMAの確認 =======================================================================================================
//{
//    _MYNAMESPACE_::MPI::WindowObject<double> rmaobj( comm, 10000, 0, "test" );
//    _MYNAMESPACE_::MPI::WindowObject<int> rmaobj1( comm, 10000, 0, "test1" );
//    _MYNAMESPACE_::MPI::WindowObject<double> rmaobj2( comm, 10000, 0, "test1" );
//    comm->Barrier();

//    double val;
//    val = 0.09;
////    qDebug() << rmaobj.GetWindowObjName().c_str();

////    if( comm->GetMPIRank() == 0 )
////    {
////        rmaobj.Write( 333.333, 50 );
////        rmaobj2.Write( 454.090, 9000 );
////        rmaobj.Write( 555.555, 8000 );

//        rmaobj[50] = 0.7777 *( comm->GetMPIRank() + 1.0);
////    }
//    comm->Barrier();

//    qDebug() <<  rmaobj[50] << rmaobj[ 8000 ]/* << MPIEnvPtr->GetHostName().c_str()*/;

//    rmaobj2 = rmaobj;

//    comm->Barrier();

//    qDebug() <<  rmaobj2[50] << rmaobj2[ 8000 ]/* << MPIEnvPtr->GetHostName().c_str()*/;
//}
////MPI_Barrier( MPI_COMM_WORLD );

////     double dval = 100.0 * (comm->GetMPIRank() + 1);
////     double darray[6000] = {0.0};
//////     rmaobj.Fence();
////     rmaobj.Write( dval, 9999 );
////     rmaobj.Write( 4.5, 9999 );
////     rmaobj.Write( darray, 0, 6000 );
//////     rmaobj.Fence();

//////    MPI_Barrier( MPI_COMM_WORLD );
//////    rmaobj.Fence();

//////    if( myrank == 1 )
//////    {
//////        auto dval = rmaobj.ReadOneValue( 9999 );
//////    }

////    for( auto ii = 0; ii < comm->GetMPISize(); ii++ )
////    {
////        if( comm->GetMPIRank() == ii )
////        {
////            std::cout << MPIEnvPtr->GetHostName() << " RMA Get " << rmaobj.Read( 9999 ) << std::endl;
////        }
////        comm->Barrier();
////    }
////    qint64 totalelapsed1 = 0;
////    comm->Allreduce<_MYNAMESPACE_::MPI::SUM, qint64>( elapsed, totalelapsed1, 1);

////    MPIEnvPtr->RemoveCommunicator( comm );

////    //! ラップしたMPI_Finalize()の呼び出し。
////    MPIEnvPtr->Finalize();

////    if( myrank == 0 )
////    {
////        std::cout << MPIEnvPtr->GetHostName() << " Time " << totalelapsed1 / mpisize << std::endl;
////    }

    return 0;
}

<commit_msg>コメントアウトの削除<commit_after>#include <iostream>
#include <mpi.h>
#include <algorithm>
#include <numeric>
#include <vector>
//#include "MPISharedVector.h"
#include <QElapsedTimer>
#include <memory.h>
#include <QDebug>

#include "include/MPI/Environment.h"
#include "include/MPI/Communicator.h"
#include "include/MPI/WindowObject.h"

#include "test/Test.h"

//const int ExecCount = 100;

int main(int argc, char *argv[])
{
    //! MPIの初期化
    MPIEnvPtr->Init( argc, argv );
    auto comm = MPIEnvPtr->CreateCommunicator( MPI_COMM_WORLD );

//    P2PTest( comm );
//    BcastTest( comm );
//    CorrectiveTest( comm );
//    CorrectiveAllTest( comm );

    WindowObjectTest( comm );

    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

struct Graveyard : public Room
{
    Graveyard() : Room(Map::Location::GRAVEYARD, "The graveyard")
    {
        exits["north"] = Map::Location::GRAVEYARD_GATES;
    }
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        currentLocation = Map::Location::GRAVEYARD;
        map.rooms[Map::Location::GRAVEYARD] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard description"));
        map.rooms[Map::Location::GRAVEYARD_GATES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard gates description"));
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Moms house"));
        map.rooms[Map::Location::GATES_OF_SHOGUN] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Gates of shogun"));
        map.rooms[Map::Location::HOUSE_OF_BLUES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Blues"));
        map.rooms[Map::Location::FOGGY_FOREST] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Forest"));
    }

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if (map.rooms.at(currentLocation)->exits.find(direction) == map.rooms.at(currentLocation)->exits.end())
			return false;
		currentLocation = map.rooms.at(currentLocation)->exits[direction];
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>indents<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    	enum Location
    	{
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    	};
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

struct Graveyard : public Room
{
    Graveyard() : Room(Map::Location::GRAVEYARD, "The graveyard")
    {
        exits["north"] = Map::Location::GRAVEYARD_GATES;
    }
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        currentLocation = Map::Location::GRAVEYARD;
        map.rooms[Map::Location::GRAVEYARD] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard description"));
        map.rooms[Map::Location::GRAVEYARD_GATES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard gates description"));
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Moms house"));
        map.rooms[Map::Location::GATES_OF_SHOGUN] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Gates of shogun"));
        map.rooms[Map::Location::HOUSE_OF_BLUES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Blues"));
        map.rooms[Map::Location::FOGGY_FOREST] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Forest"));
    }

    bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
	if (map.rooms.at(currentLocation)->exits.find(direction) == map.rooms.at(currentLocation)->exits.end())
		return false;
	currentLocation = map.rooms.at(currentLocation)->exits[direction];
	if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
		return false;
	if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
		return false;
	if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
	if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
	    case Map::GATES_OF_SHOGUN:
		cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
		break;
	    case Map::HOUSE_OF_BLUES:
		cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
		break;
	    case Map::FOGGY_FOREST:
		cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
		break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

    RoomID currentLocation;

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <time.h>

#include "bcm_host.h"

#include "GLES2/gl2.h"
#include "EGL/egl.h"
#include "EGL/eglext.h"

#include "shader.h"
#include "inotify-cxx.h"

typedef struct {
    uint32_t screen_width;
    uint32_t screen_height;
    // OpenGL|ES objects
    EGLDisplay display;
    EGLSurface surface;
    EGLContext context;

    GLuint buf;

    Shader shader;

} CUBE_STATE_T;

static CUBE_STATE_T _state, *state=&_state;

#define check() assert(glGetError() == 0)

static void init_ogl(CUBE_STATE_T *state){
    int32_t success = 0;
    EGLBoolean result;
    EGLint num_config;

    static EGL_DISPMANX_WINDOW_T nativewindow;

    DISPMANX_ELEMENT_HANDLE_T dispman_element;
    DISPMANX_DISPLAY_HANDLE_T dispman_display;
    DISPMANX_UPDATE_HANDLE_T dispman_update;
    VC_RECT_T dst_rect;
    VC_RECT_T src_rect;

    static const EGLint attribute_list[] = {
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_NONE
    };

    static const EGLint context_attributes[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };
    EGLConfig config;

    // get an EGL display connection
    state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    assert(state->display!=EGL_NO_DISPLAY);
    check();

    // initialize the EGL display connection
    result = eglInitialize(state->display, NULL, NULL);
    assert(EGL_FALSE != result);
    check();

    // get an appropriate EGL frame buffer configuration
    result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
    assert(EGL_FALSE != result);
    check();

    // get an appropriate EGL frame buffer configuration
    result = eglBindAPI(EGL_OPENGL_ES_API);
    assert(EGL_FALSE != result);
    check();

    // create an EGL rendering context
    state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
    assert(state->context!=EGL_NO_CONTEXT);
    check();

    // create an EGL window surface
    success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
    assert( success >= 0 );

    dst_rect.x = 0;
    dst_rect.y = 0;
    dst_rect.width = state->screen_width;
    dst_rect.height = state->screen_height;

    src_rect.x = 0;
    src_rect.y = 0;
    src_rect.width = state->screen_width << 16;
    src_rect.height = state->screen_height << 16;

    dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
    dispman_update = vc_dispmanx_update_start( 0 );
    dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
                                               0/*layer*/, &dst_rect, 0/*src*/,
                                               &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);

    nativewindow.element = dispman_element;
    nativewindow.width = state->screen_width;
    nativewindow.height = state->screen_height;
    vc_dispmanx_update_submit_sync( dispman_update );
    check();

    state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
    assert(state->surface != EGL_NO_SURFACE);
    check();

    // connect the context to the surface
    result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
    assert(EGL_FALSE != result);
    check();

    // Set background color and clear buffers
    glClearColor(0.15f, 0.25f, 0.35f, 1.0f);
    glClear( GL_COLOR_BUFFER_BIT );

    check();
}

static bool loadFromPath(const std::string& path, std::string* into) {
    std::ifstream file;
    std::string buffer;

    file.open(path.c_str());
    if(!file.is_open()) return false;
    while(!file.eof()) {
        getline(file, buffer);
        (*into) += buffer + "\n";
    }

    file.close();
    return true;
}

static void draw(CUBE_STATE_T *state, GLfloat cx, GLfloat cy){
    // Now render to the main frame buffer
    glBindFramebuffer(GL_FRAMEBUFFER,0);
    // Clear the background (not really necessary I suppose)
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    check();

    glBindBuffer(GL_ARRAY_BUFFER, state->buf);
    check();
    state->shader.use();
    check();

    state->shader.sendUniform("u_time",((float)clock())/CLOCKS_PER_SEC);
    state->shader.sendUniform("u_mouse",cx, cy);
    state->shader.sendUniform("u_resolution",state->screen_width, state->screen_height);
    check();

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    check();

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glFlush();
    glFinish();
    check();

    eglSwapBuffers(state->display, state->surface);
    check();
}

static int get_mouse(CUBE_STATE_T *state, int *outx, int *outy){
    static int fd = -1;
    const int width=state->screen_width, height=state->screen_height;
    static int x=800, y=400;
    const int XSIGN = 1<<4, YSIGN = 1<<5;
    if (fd<0) {
       fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK);
    }
    if (fd>=0) {
        struct {char buttons, dx, dy; } m;
        while (1) {
           int bytes = read(fd, &m, sizeof m);
           if (bytes < (int)sizeof m) goto _exit;
           if (m.buttons&8) {
              break; // This bit should always be set
           }
           read(fd, &m, 1); // Try to sync up again
        }
        if (m.buttons&3)
           return m.buttons&3;
        x+=m.dx;
        y+=m.dy;
        if (m.buttons&XSIGN)
           x-=256;
        if (m.buttons&YSIGN)
           y-=256;
        if (x<0) x=0;
        if (y<0) y=0;
        if (x>width) x=width;
        if (y>height) y=height;
   }
_exit:
   if (outx) *outx = x;
   if (outy) *outy = y;
   return 0;
}

//==============================================================================

int main(int argc, char **argv){
   int terminate = 0;
   GLfloat cx, cy;
   bcm_host_init();

   // Clear application state
    memset( state, 0, sizeof( *state ) );

    // Start OGLES
    init_ogl(state);
    // init_shaders(state, std::string(argv[1]) );

    //  Build shader;
    //
    std::string fragSource;
    std::string vertSource =
    "attribute vec4 a_position;"
    "varying vec2 v_texcoord;"
    "void main(void) {"
    "    gl_Position = a_position;"
    "    v_texcoord = a_position.xy*0.5+0.5;"
    "}";
    if(!loadFromPath(_frag_shader_path, &fragSource)) {
        return;
    }
    state->shader.build(fragSource,vertSource);

    //  Make Quad
    //
    static const GLfloat vertex_data[] = {
        -1.0,-1.0,1.0,1.0,
        1.0,-1.0,1.0,1.0,
        1.0,1.0,1.0,1.0,
        -1.0,1.0,1.0,1.0
    };
    GLint posAttribut = state->shader.getAttribLocation("a_position");

    glClearColor ( 0.0, 1.0, 1.0, 1.0 );

    glGenBuffers(1, &state->buf);
    check();

    // Prepare viewport
    glViewport ( 0, 0, state->screen_width, state->screen_height );
    check();

    // Upload vertex data to a buffer
    glBindBuffer(GL_ARRAY_BUFFER, state->buf);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data),
                 vertex_data, GL_STATIC_DRAW);
    glVertexAttribPointer(posAttribut, 4, GL_FLOAT, 0, 16, 0);
    glEnableVertexAttribArray(posAttribut);
    check();

    while (!terminate){
        int x, y, b;
        b = get_mouse(state, &x, &y);
        if (b) break;
        draw(state, x, y);
    }
    return 0;
}

<commit_msg>arg[1]<commit_after>#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <time.h>

#include "bcm_host.h"

#include "GLES2/gl2.h"
#include "EGL/egl.h"
#include "EGL/eglext.h"

#include "shader.h"
#include "inotify-cxx.h"

typedef struct {
    uint32_t screen_width;
    uint32_t screen_height;
    // OpenGL|ES objects
    EGLDisplay display;
    EGLSurface surface;
    EGLContext context;

    GLuint buf;

    Shader shader;

} CUBE_STATE_T;

static CUBE_STATE_T _state, *state=&_state;

#define check() assert(glGetError() == 0)

static void init_ogl(CUBE_STATE_T *state){
    int32_t success = 0;
    EGLBoolean result;
    EGLint num_config;

    static EGL_DISPMANX_WINDOW_T nativewindow;

    DISPMANX_ELEMENT_HANDLE_T dispman_element;
    DISPMANX_DISPLAY_HANDLE_T dispman_display;
    DISPMANX_UPDATE_HANDLE_T dispman_update;
    VC_RECT_T dst_rect;
    VC_RECT_T src_rect;

    static const EGLint attribute_list[] = {
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_NONE
    };

    static const EGLint context_attributes[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };
    EGLConfig config;

    // get an EGL display connection
    state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    assert(state->display!=EGL_NO_DISPLAY);
    check();

    // initialize the EGL display connection
    result = eglInitialize(state->display, NULL, NULL);
    assert(EGL_FALSE != result);
    check();

    // get an appropriate EGL frame buffer configuration
    result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
    assert(EGL_FALSE != result);
    check();

    // get an appropriate EGL frame buffer configuration
    result = eglBindAPI(EGL_OPENGL_ES_API);
    assert(EGL_FALSE != result);
    check();

    // create an EGL rendering context
    state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
    assert(state->context!=EGL_NO_CONTEXT);
    check();

    // create an EGL window surface
    success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
    assert( success >= 0 );

    dst_rect.x = 0;
    dst_rect.y = 0;
    dst_rect.width = state->screen_width;
    dst_rect.height = state->screen_height;

    src_rect.x = 0;
    src_rect.y = 0;
    src_rect.width = state->screen_width << 16;
    src_rect.height = state->screen_height << 16;

    dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
    dispman_update = vc_dispmanx_update_start( 0 );
    dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
                                               0/*layer*/, &dst_rect, 0/*src*/,
                                               &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);

    nativewindow.element = dispman_element;
    nativewindow.width = state->screen_width;
    nativewindow.height = state->screen_height;
    vc_dispmanx_update_submit_sync( dispman_update );
    check();

    state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
    assert(state->surface != EGL_NO_SURFACE);
    check();

    // connect the context to the surface
    result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
    assert(EGL_FALSE != result);
    check();

    // Set background color and clear buffers
    glClearColor(0.15f, 0.25f, 0.35f, 1.0f);
    glClear( GL_COLOR_BUFFER_BIT );

    check();
}

static bool loadFromPath(const std::string& path, std::string* into) {
    std::ifstream file;
    std::string buffer;

    file.open(path.c_str());
    if(!file.is_open()) return false;
    while(!file.eof()) {
        getline(file, buffer);
        (*into) += buffer + "\n";
    }

    file.close();
    return true;
}

static void draw(CUBE_STATE_T *state, GLfloat cx, GLfloat cy){
    // Now render to the main frame buffer
    glBindFramebuffer(GL_FRAMEBUFFER,0);
    // Clear the background (not really necessary I suppose)
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    check();

    glBindBuffer(GL_ARRAY_BUFFER, state->buf);
    check();
    state->shader.use();
    check();

    state->shader.sendUniform("u_time",((float)clock())/CLOCKS_PER_SEC);
    state->shader.sendUniform("u_mouse",cx, cy);
    state->shader.sendUniform("u_resolution",state->screen_width, state->screen_height);
    check();

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    check();

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glFlush();
    glFinish();
    check();

    eglSwapBuffers(state->display, state->surface);
    check();
}

static int get_mouse(CUBE_STATE_T *state, int *outx, int *outy){
    static int fd = -1;
    const int width=state->screen_width, height=state->screen_height;
    static int x=800, y=400;
    const int XSIGN = 1<<4, YSIGN = 1<<5;
    if (fd<0) {
       fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK);
    }
    if (fd>=0) {
        struct {char buttons, dx, dy; } m;
        while (1) {
           int bytes = read(fd, &m, sizeof m);
           if (bytes < (int)sizeof m) goto _exit;
           if (m.buttons&8) {
              break; // This bit should always be set
           }
           read(fd, &m, 1); // Try to sync up again
        }
        if (m.buttons&3)
           return m.buttons&3;
        x+=m.dx;
        y+=m.dy;
        if (m.buttons&XSIGN)
           x-=256;
        if (m.buttons&YSIGN)
           y-=256;
        if (x<0) x=0;
        if (y<0) y=0;
        if (x>width) x=width;
        if (y>height) y=height;
   }
_exit:
   if (outx) *outx = x;
   if (outy) *outy = y;
   return 0;
}

//==============================================================================

int main(int argc, char **argv){
   int terminate = 0;
   GLfloat cx, cy;
   bcm_host_init();

   // Clear application state
    memset( state, 0, sizeof( *state ) );

    // Start OGLES
    init_ogl(state);
    // init_shaders(state, std::string(argv[1]) );

    //  Build shader;
    //
    std::string fragSource;
    std::string vertSource =
    "attribute vec4 a_position;"
    "varying vec2 v_texcoord;"
    "void main(void) {"
    "    gl_Position = a_position;"
    "    v_texcoord = a_position.xy*0.5+0.5;"
    "}";
    if(!loadFromPath(std::string(arg[1]), &fragSource)) {
        return;
    }
    state->shader.build(fragSource,vertSource);

    //  Make Quad
    //
    static const GLfloat vertex_data[] = {
        -1.0,-1.0,1.0,1.0,
        1.0,-1.0,1.0,1.0,
        1.0,1.0,1.0,1.0,
        -1.0,1.0,1.0,1.0
    };
    GLint posAttribut = state->shader.getAttribLocation("a_position");

    glClearColor ( 0.0, 1.0, 1.0, 1.0 );

    glGenBuffers(1, &state->buf);
    check();

    // Prepare viewport
    glViewport ( 0, 0, state->screen_width, state->screen_height );
    check();

    // Upload vertex data to a buffer
    glBindBuffer(GL_ARRAY_BUFFER, state->buf);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data),
                 vertex_data, GL_STATIC_DRAW);
    glVertexAttribPointer(posAttribut, 4, GL_FLOAT, 0, 16, 0);
    glEnableVertexAttribArray(posAttribut);
    check();

    while (!terminate){
        int x, y, b;
        b = get_mouse(state, &x, &y);
        if (b) break;
        draw(state, x, y);
    }
    return 0;
}

<|endoftext|>


<commit_before>#include <arglib/arglib.hpp>
#include <interpreter.hpp>
#include <RFT.hpp>
#include <manager.hpp>
#include <syscall.hpp>
#include <timer.hpp>
#include <algorithm>

#include <iostream>
#include <memory>

clarg::argString RFTFlag("-rft", "Region Formation Technique (net)", "net");
clarg::argInt    HotnessFlag("-hot", "Hotness threshold for the RFTs", 50);
clarg::argString ReportFileFlag("-report", "Write down report to a file", "");
clarg::argBool   InterpreterFlag("-interpret",  "Only interpret.");
clarg::argString BinaryFlag("-bin",  "Path to the binary which will should be emulated.", "");
clarg::argBool   PreheatFlag("-p",  "Run one time to compile all regions and then reexecute measuring the time.");
clarg::argBool   VerboseFlag("-v",  "display the compiled regions");
clarg::argBool   HelpFlag("-h",  "display the help message");
clarg::argInt    RegionLimitSize("-l", "region size limit", 0);
clarg::argString ToCompileFlag("-tc", "Functions to compile", "");
clarg::argString ArgumentsFlag("-args", "Pass Parameters to binary file (as string)", "");

void usage(char* PrgName) {
  cout << "Version: 0.0.1 (21-03-2018)\n\n";

  cout << "Usage: " << PrgName <<
    " [-rft {net, mret2, lef, lei, netplus, mb}] [-interpret] -bin PathToBinary\n\n";

  cout << "DESCRIPTION:\n";
  cout << "This program implements the OpenISA DBT (Dynamic Binary Translator)\n" <<
    "Institute of Computing, 2018.\n\n";

  cout << "ARGUMENTS:\n";
  clarg::arguments_descriptions(cout, "  ", "\n");
}

int validateArguments() {
  if (InterpreterFlag.was_set() && RFTFlag.was_set()) {
    cerr << "You can't use a RFT when you are only interpreting!\n";
    return 1;
  }

  if (!BinaryFlag.was_set()) {
    cerr << "You must set the path of the binary which will be emulated!\n";
    return 1;
  }

  return 0;
}

std::unique_ptr<dbt::RFT> RftChosen;
dbt::Machine M;

void  sigHandler(int sig) {
  if (VerboseFlag.was_set())
    RftChosen->printRegions();

  if (M.isOnNativeExecution()) {
    std::cerr << "Error while executing region " << std::hex << M.getRegionBeingExecuted() << "\n";
  } else {
    std::cerr << "Error while executing the interpreter.\n";
    if (M.getRegionBeingExecuted() != 0)
      std::cerr << "The last executed region was " << std::hex << M.getRegionBeingExecuted() << "\n";
  }

  if(sig == SIGABRT)
    std::cerr << "SIGABRT (" << sig << ") while emulating at PC: " << std::hex << M.getPC() << std::dec << "\n";
  else
    std::cerr << "SIGSEGV (" << sig << ") while emulating at PC: " << std::hex << M.getPC() << std::dec << "\n";
  exit(1);
}

int main(int argc, char** argv) {
  signal(SIGSEGV, sigHandler);
  signal(SIGABRT, sigHandler);

  dbt::Timer GlobalTimer;

  // Parse the arguments
  if (clarg::parse_arguments(argc, argv)) {
    cerr << "Error when parsing the arguments!" << endl;
    return 1;
  }

  if (HelpFlag.get_value() == true) {
    usage(argv[0]);
    return 1;
  }

  if (validateArguments())
    return 1;

  int loadStatus = M.loadELF(BinaryFlag.get_value());

  if (!loadStatus) {
    std::cerr << "Can't find or process ELF file " << argv[1] << std::endl;
    return 2;
  }

  dbt::Manager TheManager(1, dbt::Manager::OptPolitic::Normal, M.getDataMemOffset(), VerboseFlag.was_set());

  if (InterpreterFlag.was_set()) {
    RftChosen = std::make_unique<dbt::NullRFT>(TheManager);
  } else {
    std::string RFTName = RFTFlag.get_value();
    transform(RFTName.begin(), RFTName.end(), RFTName.begin(), ::tolower);

    if (RFTName == "net") {
      std::cerr << "NET RFT Selected\n";
      RftChosen = std::make_unique<dbt::NET>(TheManager);
    } else if (RFTName == "mret2") {
      std::cerr << "MRET2 RFT Selected\n";
      RftChosen = std::make_unique<dbt::MRET2>(TheManager);
    } else if (RFTName == "netplus") {
      std::cerr << "NETPlus RFT Selected\n";
      RftChosen = std::make_unique<dbt::NETPlus>(TheManager);
    } else if (RFTName == "lei") {
      std::cerr << "LEI rft selected\n";
      RftChosen = std::make_unique<dbt::LEI>(TheManager);
    } else if (RFTName == "mb") {
      std::cerr << "MethodBased rft selected\n";
      if (ToCompileFlag.was_set())
        RftChosen = std::make_unique<dbt::MethodBased>(TheManager, ToCompileFlag.get_value());
      else
        RftChosen = std::make_unique<dbt::MethodBased>(TheManager);
    } else {
      std::cerr << "You should select a valid RFT!\n";
      return 1;
    }
  }

  if(HotnessFlag.was_set()) {
    std::cerr << "The Hotness Threshold is set to " << HotnessFlag.get_value() << std::endl;
    RftChosen->setHotnessThreshold(HotnessFlag.get_value());
  }

  if (RegionLimitSize.was_set())
    RftChosen->setRegionLimitSize(RegionLimitSize.get_value());

  std::unique_ptr<dbt::SyscallManager> SyscallM;
  SyscallM = std::make_unique<dbt::LinuxSyscallManager>();

  if (PreheatFlag.was_set()) {
    std::cerr << "Preheating...\n";
    dbt::ITDInterpreter I(*SyscallM.get(), *RftChosen.get());
    I.executeAll(M);
    std::cerr << "done\n";

    std::cerr << "Cleaning VM... ";
    M.reset();
    std::cerr << "done\n";

    RftChosen = std::make_unique<dbt::PreheatRFT>(TheManager);
  }

  if(ArgumentsFlag.was_set())
  {
    if(M.setCommandLineArguments(ArgumentsFlag.get_value()) < 0)
      exit(1);
  }

  //Adjust to --args

  GlobalTimer.startClock();
  dbt::ITDInterpreter I(*SyscallM.get(), *RftChosen.get());
  std::cerr << "Starting execution:\n";
  I.executeAll(M);
  GlobalTimer.stopClock();

  GlobalTimer.printReport("Global");

  if(ReportFileFlag.was_set()) {
    ofstream report;
    report.open(ReportFileFlag.get_value());

    if(report.is_open()) {
      report << "No. Compiled Regions | "
        << "Avg Code Size Reduction | "
        << "No. OI Instructions Compiled | "
        << "No. LLVM compiled | "
        << "No. of Native Instructions Executed | "
        << "Total Cycles | "
        << "Conditional Branch Instructions Executed | "
        << "Conditional Branch Instructions Misses | "
        << "Total L1 I-Cache misses | "
        << "Time (s)"
        << "\n";
      report << std::dec << TheManager.getCompiledRegions() << std::endl;
      report << TheManager.getAvgOptCodeSize()/TheManager.getCompiledRegions() << std::endl;
      report << TheManager.getOICompiled() << std::endl;
      report << TheManager.getLLVMCompiled() << std::endl;
      GlobalTimer.printReport("", report);
    }

    else
      std::cerr << "Report Error: Unable to open file: \'" << ReportFileFlag.get_value() << "\' for writting.\n";
  }

  return SyscallM->getExitStatus();
}

/*
 * TODO:
 *  - Add all instructions need by printf (commit)
 *  - Correct bugs in at least 6 tests (commit)
 *  - Add new benchmarks (commit)
 *  - Make improvements on the code (commit)
 *  - Make improvements on the performance (commit)
 *  ---------------------------------------------------- Until: 24 May
 */
<commit_msg>Parameters to MB<commit_after>#include <arglib/arglib.hpp>
#include <interpreter.hpp>
#include <RFT.hpp>
#include <manager.hpp>
#include <syscall.hpp>
#include <timer.hpp>
#include <algorithm>

#include <iostream>
#include <memory>

clarg::argString RFTFlag("-rft", "Region Formation Technique (net)", "net");
clarg::argInt    HotnessFlag("-hot", "Hotness threshold for the RFTs", 50);
clarg::argString ReportFileFlag("-report", "Write down report to a file", "");
clarg::argBool   InterpreterFlag("-interpret",  "Only interpret.");
clarg::argString BinaryFlag("-bin",  "Path to the binary which will should be emulated.", "");
clarg::argBool   PreheatFlag("-p",  "Run one time to compile all regions and then reexecute measuring the time.");
clarg::argBool   VerboseFlag("-v",  "display the compiled regions");
clarg::argBool   HelpFlag("-h",  "display the help message");
clarg::argInt    RegionLimitSize("-l", "region size limit", 0);
clarg::argString ToCompileFlag("-tc", "Functions to compile", "");
clarg::argString ArgumentsFlag("-args", "Pass Parameters to binary file (as string)", "");

void usage(char* PrgName) {
  cout << "Version: 0.0.1 (21-03-2018)\n\n";

  cout << "Usage: " << PrgName <<
    " [-rft {net, mret2, lef, lei, netplus, mb}] [-interpret] -bin PathToBinary\n\n";

  cout << "DESCRIPTION:\n";
  cout << "This program implements the OpenISA DBT (Dynamic Binary Translator)\n" <<
    "Institute of Computing, 2018.\n\n";

  cout << "ARGUMENTS:\n";
  clarg::arguments_descriptions(cout, "  ", "\n");
}

int validateArguments() {
  if (InterpreterFlag.was_set() && RFTFlag.was_set()) {
    cerr << "You can't use a RFT when you are only interpreting!\n";
    return 1;
  }

  if (!BinaryFlag.was_set()) {
    cerr << "You must set the path of the binary which will be emulated!\n";
    return 1;
  }

  return 0;
}

std::unique_ptr<dbt::RFT> RftChosen;
dbt::Machine M;

void  sigHandler(int sig) {
  if (VerboseFlag.was_set())
    RftChosen->printRegions();

  if (M.isOnNativeExecution()) {
    std::cerr << "Error while executing region " << std::hex << M.getRegionBeingExecuted() << "\n";
  } else {
    std::cerr << "Error while executing the interpreter.\n";
    if (M.getRegionBeingExecuted() != 0)
      std::cerr << "The last executed region was " << std::hex << M.getRegionBeingExecuted() << "\n";
  }

  if(sig == SIGABRT)
    std::cerr << "SIGABRT (" << sig << ") while emulating at PC: " << std::hex << M.getPC() << std::dec << "\n";
  else
    std::cerr << "SIGSEGV (" << sig << ") while emulating at PC: " << std::hex << M.getPC() << std::dec << "\n";
  exit(1);
}

int main(int argc, char** argv) {
  signal(SIGSEGV, sigHandler);
  signal(SIGABRT, sigHandler);

  dbt::Timer GlobalTimer;

  // Parse the arguments
  if (clarg::parse_arguments(argc, argv)) {
    cerr << "Error when parsing the arguments!" << endl;
    return 1;
  }

  if (HelpFlag.get_value() == true) {
    usage(argv[0]);
    return 1;
  }

  if (validateArguments())
    return 1;

  int loadStatus = M.loadELF(BinaryFlag.get_value());

  if (!loadStatus) {
    std::cerr << "Can't find or process ELF file " << argv[1] << std::endl;
    return 2;
  }

  dbt::Manager TheManager(1, dbt::Manager::OptPolitic::Normal, M.getDataMemOffset(), VerboseFlag.was_set());

  if (InterpreterFlag.was_set()) {
    RftChosen = std::make_unique<dbt::NullRFT>(TheManager);
  } else {
    std::string RFTName = RFTFlag.get_value();
    transform(RFTName.begin(), RFTName.end(), RFTName.begin(), ::tolower);

    if (RFTName == "net") {
      std::cerr << "NET RFT Selected\n";
      RftChosen = std::make_unique<dbt::NET>(TheManager);
    } else if (RFTName == "mret2") {
      std::cerr << "MRET2 RFT Selected\n";
      RftChosen = std::make_unique<dbt::MRET2>(TheManager);
    } else if (RFTName == "netplus") {
      std::cerr << "NETPlus RFT Selected\n";
      RftChosen = std::make_unique<dbt::NETPlus>(TheManager);
    } else if (RFTName == "lei") {
      std::cerr << "LEI rft selected\n";
      RftChosen = std::make_unique<dbt::LEI>(TheManager);
    } else if (RFTName == "mb") {
      std::cerr << "MethodBased rft selected\n";
      if (ToCompileFlag.was_set())
        RftChosen = std::make_unique<dbt::MethodBased>(TheManager, ToCompileFlag.get_value());
      else
        RftChosen = std::make_unique<dbt::MethodBased>(TheManager);
    } else {
      std::cerr << "You should select a valid RFT!\n";
      return 1;
    }
  }

  if(HotnessFlag.was_set()) {
    std::cerr << "The Hotness Threshold is set to " << HotnessFlag.get_value() << std::endl;
    RftChosen->setHotnessThreshold(HotnessFlag.get_value());
  }

  if (RegionLimitSize.was_set())
    RftChosen->setRegionLimitSize(RegionLimitSize.get_value());

  std::unique_ptr<dbt::SyscallManager> SyscallM;
  SyscallM = std::make_unique<dbt::LinuxSyscallManager>();

  if (PreheatFlag.was_set()) {
	 if(ArgumentsFlag.was_set())
  	{
    		if(M.setCommandLineArguments(ArgumentsFlag.get_value()) < 0)
      		exit(1);
  	}

    std::cerr << "Preheating...\n";
    dbt::ITDInterpreter I(*SyscallM.get(), *RftChosen.get());
    I.executeAll(M);
    std::cerr << "done\n";

    std::cerr << "Cleaning VM... ";
    M.reset();
    std::cerr << "done\n";

    RftChosen = std::make_unique<dbt::PreheatRFT>(TheManager);
  }

  if(ArgumentsFlag.was_set())
  {
    if(M.setCommandLineArguments(ArgumentsFlag.get_value()) < 0)
      exit(1);
  }

  //Adjust to --args

  GlobalTimer.startClock();
  dbt::ITDInterpreter I(*SyscallM.get(), *RftChosen.get());
  std::cerr << "Starting execution:\n";
  I.executeAll(M);
  GlobalTimer.stopClock();

  GlobalTimer.printReport("Global");

  if(ReportFileFlag.was_set()) {
    ofstream report;
    report.open(ReportFileFlag.get_value());

    if(report.is_open()) {
      report << "No. Compiled Regions | "
        << "Avg Code Size Reduction | "
        << "No. OI Instructions Compiled | "
        << "No. LLVM compiled | "
        << "No. of Native Instructions Executed | "
        << "Total Cycles | "
        << "Conditional Branch Instructions Executed | "
        << "Conditional Branch Instructions Misses | "
        << "Total L1 I-Cache misses | "
        << "Time (s)"
        << "\n";
      report << std::dec << TheManager.getCompiledRegions() << std::endl;
      report << TheManager.getAvgOptCodeSize()/TheManager.getCompiledRegions() << std::endl;
      report << TheManager.getOICompiled() << std::endl;
      report << TheManager.getLLVMCompiled() << std::endl;
      GlobalTimer.printReport("", report);
    }

    else
      std::cerr << "Report Error: Unable to open file: \'" << ReportFileFlag.get_value() << "\' for writting.\n";
  }

  return SyscallM->getExitStatus();
}

/*
 * TODO:
 *  - Add all instructions need by printf (commit)
 *  - Correct bugs in at least 6 tests (commit)
 *  - Add new benchmarks (commit)
 *  - Make improvements on the code (commit)
 *  - Make improvements on the performance (commit)
 *  ---------------------------------------------------- Until: 24 May
 */
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(int index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>map system working<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[49][49] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(int index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>

int main()
{
    int input;
    if (scanf("%d", &input) == 1)
    {
        if (input == 2)
        {
            int *a;
            int *n = a;
            a = n;
            *n = 5;
        }
        else
        {
            printf("OK\n");
        }
    }
    return 0;
}<commit_msg>Remove extra whitespace<commit_after>#include <stdio.h>
int main()
{
    int input;
    if (scanf("%d", &input) == 1)
    {
        if (input == 2)
        {
            int *a;
            int *n = a;
            a = n;
            *n = 5;
        }
        else
        {
            printf("OK\n");
        }
    }
    return 0;
}<|endoftext|>