[
  {
    "path": ".autom4te.cfg",
    "content": "## ------------------ ##\n## User Preferences.  ##\n## ------------------ ##\n\nbegin-language: \"Autoconf-without-aclocal-m4\"\nargs: --no-cache\nend-language: \"Autoconf-without-aclocal-m4\"\n"
  },
  {
    "path": ".github/workflows/compile.yml",
    "content": "name: Compile & test\n\n# Run whenever we push to any branch without a \"/\", other than [coverity-scan].\non:\n  push:\n    branches:\n    - '*'\n    - '!coverity-scan'\n\nenv:\n  # Shared variables amongst all projects / platforms / compilers.\n  CFLAGS_ALL: -std=c99 -O2\n  CFLAGS_CLANG_LIBCPERCIVA: -Wall -Wextra -Werror -Weverything\n                            -Wno-#warnings -Wno-pedantic -Wno-padded\n                            -Wno-format-nonliteral\n                            -Wno-disabled-macro-expansion\n                            -Wno-missing-noreturn\n                            -Wno-unused-macros\n                            -Wno-documentation-unknown-command\n                            -Wno-implicit-fallthrough\n  CFLAGS_GCC_LIBCPERCIVA: -Wall -Wextra -Werror -Wpedantic\n                          -pedantic-errors -Wno-clobbered\n  # Variables for specific projects / platforms / compilers.\n  CFLAGS_CLANG_PROJECT: -Wno-reserved-id-macro\n  CFLAGS_GCC_PROJECT: -Wno-cpp\n  CFLAGS_OSX: -Wno-poison-system-directories\n              -Wno-deprecated-declarations\n  LDFLAGS_OSX:\n\njobs:\n  Ubuntu:\n    name: Ubuntu\n    runs-on: ubuntu-22.04\n    steps:\n    - name: Update apt-get\n      run: sudo apt-get update\n    - name: Install software\n      run: sudo apt-get install --no-install-recommends\n           valgrind autoconf-archive\n    - name: Checkout code\n      uses: actions/checkout@v4\n    - name: Run autoreconf\n      run:\n        autoreconf -i\n    - name: Configure with clang\n      env:\n        CC: clang-13\n        CFLAGS: ${{ env.CFLAGS_ALL }}\n      run: ./configure\n    - name: Compile with clang\n      env:\n        CC: clang-13\n        CFLAGS: ${{ env.CFLAGS_ALL }}\n                ${{ env.CFLAGS_CLANG_LIBCPERCIVA }}\n                ${{ env.CFLAGS_CLANG_PROJECT }}\n      # make(1) doesn't automatically override the CFLAGS macro set inside\n      # Makefile with the environment variable.\n      run: make CFLAGS=\"${{ env.CFLAGS }}\"\n    - name: Test clang binaries\n      env:\n        USE_VALGRIND: 1\n      run: make test VERBOSE=1\n    - name: Clean\n      run: make clean\n    - name: Configure with gcc\n      env:\n        CC: gcc-10\n        CFLAGS: ${{ env.CFLAGS_ALL }}\n      run: ./configure\n    - name: Compile with gcc\n      env:\n        CC: gcc-10\n        CFLAGS: ${{ env.CFLAGS_ALL }}\n                ${{ env.CFLAGS_GCC_LIBCPERCIVA }}\n                ${{ env.CFLAGS_GCC_PROJECT }}\n      # make(1) doesn't automatically override the CFLAGS macro set inside\n      # Makefile with the environment variable.\n      run: make CFLAGS=\"${{ env.CFLAGS }}\"\n    - name: Test gcc binaries\n      env:\n        USE_VALGRIND: 1\n      run: make test VERBOSE=1\n    - name: Check for untracked files\n      run: test -z \"$(git status --porcelain=v1)\"\n  macOS:\n    name: macOS\n    runs-on: macOS-14\n    steps:\n    - name: Checkout code\n      uses: actions/checkout@v4\n    - name: Install software\n      run: brew install automake libtool\n    - name: Run autoreconf\n      run: autoreconf -i\n    - name: Configure with clang\n      env:\n        CC: clang\n        CFLAGS: ${{ env.CFLAGS_ALL }}\n                ${{ env.CFLAGS_OSX }}\n        LDFLAGS: ${{ env.LDFLAGS_OSX }}\n      run: ./configure\n    - name: Compile with clang\n      env:\n        CC: clang\n        CFLAGS: ${{ env.CFLAGS_ALL }}\n                ${{ env.CFLAGS_CLANG_LIBCPERCIVA }}\n                ${{ env.CFLAGS_CLANG_PROJECT }}\n                ${{ env.CFLAGS_OSX }}\n        LDFLAGS: ${{ env.LDFLAGS_OSX }}\n      # make(1) doesn't automatically override the CFLAGS macro set inside\n      # Makefile with the environment variable.\n      run: make CFLAGS=\"${{ env.CFLAGS }}\"\n    - name: Test clang binaries\n      run: make test VERBOSE=1\n"
  },
  {
    "path": ".github/workflows/coverity-scan.yml",
    "content": "name: coverity-scan\n\n# Only trigger on the [coverity-scan] branch.\non:\n  push:\n    branches:\n      - coverity-scan\n\n# Run coverity scan.  For now, we're re-using the Travis-CI script, which\n# requires us to fake a TRAVIS_BRANCH environment variable.\njobs:\n  coverity-scan:\n    runs-on: ubuntu-22.04\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n      - name: Run autoreconf\n        run: autoreconf -i\n      - name: Configure with the default compiler\n        run: ./configure\n      - name: Coverity scan\n        env:\n          COVERITY_SCAN_PROJECT_NAME: ${{ github.repository }}\n          COVERITY_SCAN_BRANCH_PATTERN: coverity-scan\n          COVERITY_SCAN_NOTIFICATION_EMAIL: cperciva@tarsnap.com\n          COVERITY_SCAN_BUILD_COMMAND: make all\n          COVERITY_SCAN_TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }}\n          TRAVIS_BRANCH: coverity-scan\n        run: curl -s \"https://scan.coverity.com/scripts/travisci_build_coverity_scan.sh\" | bash || true\n"
  },
  {
    "path": ".gitignore",
    "content": "# Development tools\n/devel-tools/\n# Result of autoreconf -i\n/Makefile.in\n/aclocal.m4\n/config.aux/\n/config.h.in\n/config.h.in~\n/configure\n/configure~\n# m4/ directory: only keep certain files\n/m4/*\n!/m4/check_darwin_paths.m4\n!/m4/check_disable_compiler_warnings.m4\n!/m4/check_libcperciva_posix.m4\n!/m4/check_memlimit_support.m4\n!/m4/check_posix_sh.m4\n!/m4/check_solaris_c99.m4\n# Standard out-of-tree build directory\n/build/\n# In-tree configure\n.deps/\n/Makefile\n/config.h\n/config.log\n/config.status\n/libtool\n/stamp-h1\n# In-tree build, only top-level\n/apisupport-config.h\n/cpusupport-config.h\n# In-tree build, all directories\n.dirstamp\n.libs/\n*.la\n*.lo\n*.o\n# In-tree binaries\n/scrypt\n/tests/libscrypt-kdf/sample-libscrypt-kdf\n/tests/valgrind/potential-memleaks\n/tests/verify-strings/test_scrypt\n# In-tree test output\n/tests-output/\n/tests-valgrind/\n"
  },
  {
    "path": "BUILDING",
    "content": "Installing\n----------\n\nWe strongly recommend that people use the latest official release tarball on\nhttps://www.tarsnap.com/scrypt.html, and build with:\n\n    ./configure\n    make\n    make install\n\nOfficial scrypt tarball releases should build and run on any IEEE Std 1003.1\n(POSIX) compliant system which\n  1. Includes the Software Development Utilities option,\n  2. Has OpenSSL available via -lcrypto and #include <openssl/foo>, and\n  3. Provides /dev/urandom.\n\n\nlibscrypt-kdf\n-------------\n\nTo install the development library, run:\n\n    ./configure --enable-libscrypt-kdf\n    make install\n\n\nPlatform-specific notes\n-----------------------\n\n- when cross-compiling, runtime POSIX compatibility checks are disabled.\n  For more information, see libcperciva/POSIX/README.\n\n- On OS X, the version of OpenSSL included with the operating\n  system is outdated (0.9.8) and deprecated, and it is recommended\n  that scrypt be built with an updated version of OpenSSL.  On OS X\n  10.11 \"El Capitan\" and higher, OpenSSL was removed entirely.  After\n  installing a newer version of OpenSSL, use\n      CPPFLAGS=\"-I /path/to/openssl/headers\"\n      LDFLAGS=\"-L /path/to/openssl/lib\"\n  to build scrypt.\n\n  In particular, if you installed OpenSSL using homebrew, you may\n  pass the relevant directories directly to ./configure:\n      ./configure CPPFLAGS=\"-I/usr/local/opt/openssl/include\" LDFLAGS=\"-L/usr/local/opt/openssl/lib\"\n\n  Alternatively, you may wish to add these lines to your $HOME/.profile file:\n      export CPPFLAGS=\"-I/usr/local/opt/openssl/include $CPPFLAGS\"\n      export LDFLAGS=\"-L/usr/local/opt/openssl/lib $LDFLAGS\"\n  and then close & re-open your terminal window.\n\n\nBuilding from git\n-----------------\n\nFor experimental development from git, build with:\n\n    autoreconf -i\n    ./configure\n    make\n\n- You must have automake 1.11.2 or higher, and libtool.\n- In order to support the `AX_CFLAGS_WARN_ALL` autoconf directive, you will\n  need to install the autoconf archive.  On Debian systems, use the\n  `autoconf-archive` package; on FreeBSD, use `devel/autoconf-archive`.\n- Ignore this message if it appears:\n  aclocal: warning: couldn't open directory 'm4': No such file or directory\n"
  },
  {
    "path": "COPYRIGHT",
    "content": "The included code and documentation (\"scrypt\") is distributed under the\nfollowing terms:\n\nCopyright 2005-2025 Colin Percival.  All rights reserved.\nCopyright 2011-2025 Tarsnap Backup Inc.  All rights reserved.\nCopyright 2014 Sean Kelly.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n1. Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\nOR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\nOUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n"
  },
  {
    "path": "FORMAT",
    "content": "scrypt encrypted data format\n----------------------------\n\noffset\tlength\n0\t6\t\"scrypt\"\n6\t1\tscrypt data file version number (== 0)\n7\t1\tlog2(N) (must be between 1 and 63 inclusive)\n8\t4\tr (big-endian integer; must satisfy r * p < 2^30)\n12\t4\tp (big-endian integer; must satisfy r * p < 2^30)\n16\t32\tsalt\n48\t16\tfirst 16 bytes of SHA256(bytes 0 .. 47)\n64\t32\tHMAC-SHA256(bytes 0 .. 63)\n96\tX\tdata xor AES256-CTR key stream generated with nonce == 0\n96+X\t32\tHMAC-SHA256(bytes 0 .. 96 + (X - 1))\n\nAES256-CTR is computed with a 256-bit AES key key_enc, and HMAC-SHA256 is\ncomputed with a 256-bit key key_hmac, where\n  scrypt(password, salt, N, r, p, 64) == [key_enc][key_hmac]\n"
  },
  {
    "path": "Makefile.am",
    "content": "bin_PROGRAMS=\tscrypt\nnoinst_PROGRAMS=\t\t\t\t\t\t\t\\\n\ttests/valgrind/potential-memleaks\t\t\t\t\\\n\ttests/verify-strings/test_scrypt\ndist_man_MANS=$(scrypt_man_MANS)\nACLOCAL_AMFLAGS=\t-I m4\n\n# These files fulfill the crypto_scrypt() function, with the exception of\n#     libcperciva/alg/sha256_shani.c\n#     lib/crypto/crypto_scrypt_smix_sse2.c\n# which require special compiler flags and are thus compiled as separate\n# libraries.  See test_scrypt for an example.\ncrypto_scrypt_files=\t\t\t\t\t\t\t\\\n\tlib-platform/crypto/crypto_scrypt.c\t\t\t\t\\\n\tlib-platform/crypto/crypto_scrypt.h\t\t\t\t\\\n\tlib-platform/platform.h\t\t\t\t\t\t\\\n\tlib/crypto/crypto_scrypt_smix.c\t\t\t\t\t\\\n\tlib/crypto/crypto_scrypt_smix.h\t\t\t\t\t\\\n\tlib/crypto/crypto_scrypt_smix_sse2.h\t\t\t\t\\\n\tlibcperciva/alg/sha256.c\t\t\t\t\t\\\n\tlibcperciva/alg/sha256.h\t\t\t\t\t\\\n\tlibcperciva/alg/sha256_arm.h\t\t\t\t\t\\\n\tlibcperciva/alg/sha256_shani.h\t\t\t\t\t\\\n\tlibcperciva/alg/sha256_sse2.h\t\t\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport.h\t\t\t\t\\\n\tlibcperciva/util/insecure_memzero.c\t\t\t\t\\\n\tlibcperciva/util/insecure_memzero.h\t\t\t\t\\\n\tlibcperciva/util/warnp.c\t\t\t\t\t\\\n\tlibcperciva/util/warnp.h\n\n# Don't include crypto_aesctr_shared.c in this list, as it should be included\n# directly into other translation unit(s), and not compiled on its own.\nscrypt_SOURCES=\t\t\t\t\t\t\t\t\\\n\t$(crypto_scrypt_files)\t\t\t\t\t\t\\\n\tlib-platform/util/memlimit.h\t\t\t\t\t\\\n\tlib/scryptenc/scryptenc.c\t\t\t\t\t\\\n\tlib/scryptenc/scryptenc.h\t\t\t\t\t\\\n\tlib/scryptenc/scryptenc_cpuperf.c\t\t\t\t\\\n\tlib/scryptenc/scryptenc_cpuperf.h\t\t\t\t\\\n\tlib/scryptenc/scryptenc_print_error.c\t\t\t\t\\\n\tlib/scryptenc/scryptenc_print_error.h\t\t\t\t\\\n\tlib/util/passphrase_entry.c\t\t\t\t\t\\\n\tlib/util/passphrase_entry.h\t\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aes.h\t\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aes_aesni.h\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aes_aesni_m128i.h\t\t\t\\\n\tlibcperciva/crypto/crypto_aes_arm.h\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aes_arm_u8.h\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr.c\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr.h\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr_aesni.h\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr_arm.h\t\t\t\t\\\n\tlibcperciva/crypto/crypto_entropy.c\t\t\t\t\\\n\tlibcperciva/crypto/crypto_entropy.h\t\t\t\t\\\n\tlibcperciva/crypto/crypto_entropy_rdrand.h\t\t\t\\\n\tlibcperciva/crypto/crypto_verify_bytes.c\t\t\t\\\n\tlibcperciva/crypto/crypto_verify_bytes.h\t\t\t\\\n\tlibcperciva/util/align_ptr.h\t\t\t\t\t\\\n\tlibcperciva/util/asprintf.c\t\t\t\t\t\\\n\tlibcperciva/util/asprintf.h\t\t\t\t\t\\\n\tlibcperciva/util/entropy.c\t\t\t\t\t\\\n\tlibcperciva/util/entropy.h\t\t\t\t\t\\\n\tlibcperciva/util/getopt.c\t\t\t\t\t\\\n\tlibcperciva/util/getopt.h\t\t\t\t\t\\\n\tlibcperciva/util/humansize.c\t\t\t\t\t\\\n\tlibcperciva/util/humansize.h\t\t\t\t\t\\\n\tlibcperciva/util/monoclock.c\t\t\t\t\t\\\n\tlibcperciva/util/monoclock.h\t\t\t\t\t\\\n\tlibcperciva/util/parsenum.h\t\t\t\t\t\\\n\tlibcperciva/util/readpass.c\t\t\t\t\t\\\n\tlibcperciva/util/readpass.h\t\t\t\t\t\\\n\tlibcperciva/util/readpass_file.c\t\t\t\t\\\n\tlibcperciva/util/sysendian.h\t\t\t\t\t\\\n\tmain.c\n\nAM_CPPFLAGS=\t\t\t\t\t\t\t\t\\\n\t-I$(srcdir)/lib\t\t\t\t\t\t\t\\\n\t-I$(srcdir)/lib-platform\t\t\t\t\t\\\n\t-I$(srcdir)/lib-platform/crypto\t\t\t\t\t\\\n\t-I$(srcdir)/lib-platform/util\t\t\t\t\t\\\n\t-I$(srcdir)/lib/crypto\t\t\t\t\t\t\\\n\t-I$(srcdir)/lib/scryptenc\t\t\t\t\t\\\n\t-I$(srcdir)/lib/util\t\t\t\t\t\t\\\n\t-I$(srcdir)/libcperciva/alg\t\t\t\t\t\\\n\t-I$(srcdir)/libcperciva/cpusupport\t\t\t\t\\\n\t-I$(srcdir)/libcperciva/crypto\t\t\t\t\t\\\n\t-I$(srcdir)/libcperciva/util\t\t\t\t\t\\\n\t-DAPISUPPORT_CONFIG_FILE=\\\"apisupport-config.h\\\"\t\t\\\n\t-DCPUSUPPORT_CONFIG_FILE=\\\"cpusupport-config.h\\\"\t\t\\\n\t-D_POSIX_C_SOURCE=200809L\t\t\t\t\t\\\n\t-D_XOPEN_SOURCE=700\t\t\t\t\t\t\\\n\t${CFLAGS_POSIX}\n\n# Each \"paragraph\" denotes a rank of dependencies.  Libraries without\n# dependencies go in the bottom paragraph; a library which depends on one of\n# those goes in the preceeding paragraph; and so on.\nscrypt_LDADD=\t\t\t\t\t\t\t\t\\\n\tlibcperciva_crypto_aes.la\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\tlibcperciva_aesni.la\t\t\t\t\t\t\\\n\tlibcperciva_arm_aes.la\t\t\t\t\t\t\\\n\tlibcperciva_arm_sha256.la\t\t\t\t\t\\\n\tlibcperciva_cpusupport_detect.la\t\t\t\t\\\n\tlibcperciva_rdrand.la\t\t\t\t\t\t\\\n\tlibcperciva_shani.la\t\t\t\t\t\t\\\n\tlibscrypt_memlimit.la\t\t\t\t\t\t\\\n\tlibscrypt_sse2.la\t\t\t\t\t\t\\\n\t${LDADD_POSIX}\nscrypt_man_MANS=\tscrypt.1\n\n# apisupport needs to access post-configure info: lib-platform/platform.h,\n# config.h, and -DHAVE_CONFIG_H.\napisupport-config.h:\n\t( export CC=\"${CC}\"; export CFLAGS=\"-I${top_srcdir}/lib-platform -I${builddir} ${DEFS} ${CFLAGS}\"; command -p sh $(srcdir)/libcperciva/apisupport/Build/apisupport.sh \"$$PATH\") > apisupport-config.h.tmp && command -p mv apisupport-config.h.tmp apisupport-config.h\ncpusupport-config.h:\n\t( export CC=\"${CC}\"; export CFLAGS=\"${CFLAGS}\"; command -p sh $(srcdir)/libcperciva/cpusupport/Build/cpusupport.sh \"$$PATH\") > cpusupport-config.h.tmp && command -p mv cpusupport-config.h.tmp cpusupport-config.h\nBUILT_SOURCES=\t\t\t\t\t\t\t\t\\\n\tapisupport-config.h\t\t\t\t\t\t\\\n\tcpusupport-config.h\nCLEANFILES=\t\t\t\t\t\t\t\t\\\n\tapisupport-config.h\t\t\t\t\t\t\\\n\tapisupport-config.h.tmp\t\t\t\t\t\t\\\n\tcpusupport-config.h\t\t\t\t\t\t\\\n\tcpusupport-config.h.tmp\n\n# Libraries from libcperciva code.\nnoinst_LTLIBRARIES=\tlibcperciva_aesni.la\nlibcperciva_aesni_la_SOURCES=\t\t\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aes_aesni.c\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr_aesni.c\nnodist_libcperciva_aesni_la_SOURCES=\tcpusupport-config.h\nlibcperciva_aesni_la_CFLAGS=`. ./cpusupport-config.h; echo $${CFLAGS_X86_AESNI}`\n\nnoinst_LTLIBRARIES+=\tlibcperciva_arm_aes.la\nlibcperciva_arm_aes_la_SOURCES=\t\t\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aes_arm.c\t\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr_arm.c\nnodist_libcperciva_arm_aes_la_SOURCES=\tcpusupport-config.h\nlibcperciva_arm_aes_la_CFLAGS=`. ./cpusupport-config.h; echo $${CFLAGS_ARM_AES}`\n\nnoinst_LTLIBRARIES+=\tlibcperciva_rdrand.la\nlibcperciva_rdrand_la_SOURCES=\tlibcperciva/crypto/crypto_entropy_rdrand.c\nnodist_libcperciva_rdrand_la_SOURCES=\tcpusupport-config.h\nlibcperciva_rdrand_la_CFLAGS=\t\t\t\t\t\t\\\n\t`. ./cpusupport-config.h; echo $${CFLAGS_X86_RDRAND}`\n\nnoinst_LTLIBRARIES+=\tlibcperciva_shani.la\nlibcperciva_shani_la_SOURCES=\tlibcperciva/alg/sha256_shani.c\nnodist_libcperciva_shani_la_SOURCES=\tcpusupport-config.h\nlibcperciva_shani_la_CFLAGS=`. ./cpusupport-config.h; echo $${CFLAGS_X86_SHANI} $${CFLAGS_X86_SSSE3}`\n\nnoinst_LTLIBRARIES+=\tlibcperciva_arm_sha256.la\nlibcperciva_arm_sha256_la_SOURCES=\tlibcperciva/alg/sha256_arm.c\nnodist_libcperciva_arm_sha256_la_SOURCES=\tcpusupport-config.h\nlibcperciva_arm_sha256_la_CFLAGS=`. ./cpusupport-config.h; echo $${CFLAGS_ARM_SHA256}`\n\nnoinst_LTLIBRARIES+=\tlibcperciva_crypto_aes.la\nlibcperciva_crypto_aes_la_SOURCES=\tlibcperciva/crypto/crypto_aes.c\nnodist_libcperciva_crypto_aes_la_SOURCES=\tcpusupport-config.h\nlibcperciva_crypto_aes_la_CFLAGS=`. ./apisupport-config.h; echo $${CFLAGS_LIBCRYPTO_LOW_LEVEL_AES}`\n\nnoinst_LTLIBRARIES+=\tlibcperciva_cpusupport_detect.la\nlibcperciva_cpusupport_detect_la_SOURCES=\t\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_arm_aes.c\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_arm_sha256.c\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_x86_aesni.c\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_x86_rdrand.c\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_x86_shani.c\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_x86_sse2.c\t\t\t\\\n\tlibcperciva/cpusupport/cpusupport_x86_ssse3.c\nnodist_libcperciva_cpusupport_detect_la_SOURCES=\tcpusupport-config.h\n\n\n# Library from libcperciva and scrypt code.\nnoinst_LTLIBRARIES+=\tlibscrypt_sse2.la\nlibscrypt_sse2_la_SOURCES=\t\t\t\t\t\t\\\n\tlib/crypto/crypto_scrypt_smix_sse2.c\t\t\t\t\\\n\tlibcperciva/alg/sha256_sse2.c\nnodist_libscrypt_sse2_la_SOURCES=\tcpusupport-config.h\nlibscrypt_sse2_la_CFLAGS=`. ./cpusupport-config.h; echo $${CFLAGS_X86_SSE2}`\n\n# This library uses non-POSIX functionality, so we need to cancel the\n# _POSIX_C_SOURCE and _XOPEN_SOURCE defined in AM_CPPFLAGS.\nnoinst_LTLIBRARIES+=\tlibscrypt_memlimit.la\nlibscrypt_memlimit_la_SOURCES=\t\t\t\t\t\t\\\n\tlib-platform/util/memlimit.c\nlibscrypt_memlimit_la_CFLAGS=`. ./apisupport-config.h; echo $${CFLAGS_NONPOSIX_MEMLIMIT}`\n\n# Install libscrypt-kdf?\nif LIBSCRYPT_KDF\nlib_LTLIBRARIES=\t\tlibscrypt-kdf.la\nlibscrypt_kdf_la_LDFLAGS=\t\t\t\t\t\t\\\n\t-export-symbols-regex 'crypto_scrypt$$'\t\t\t\t\\\n\t-version-info 1\ninclude_HEADERS=\t\tlibscrypt-kdf/scrypt-kdf.h\nnoinst_PROGRAMS+=\t\ttests/libscrypt-kdf/sample-libscrypt-kdf\nelse\n# Allow the user to get a usable library even if they didn't run configure\n# with --enable-libscrypt-kdf.  If we didn't include this, they would get\n# empty libraries if they ran `make libscrypt-kdf.la`.\nEXTRA_LTLIBRARIES=\t\tlibscrypt-kdf.la\nendif\n\n# Shared definitions for libscrypt-kdf.\nlibscrypt_kdf_la_SOURCES=\t$(crypto_scrypt_files)\nlibscrypt_kdf_la_LIBADD=\t\t\t\t\t\t\\\n\tlibcperciva_arm_sha256.la\t\t\t\t\t\\\n\tlibcperciva_cpusupport_detect.la\t\t\t\t\\\n\tlibcperciva_shani.la\t\t\t\t\t\t\\\n\tlibscrypt_sse2.la\n# Workaround for \"created with both libtool and without\".\nlibscrypt_kdf_la_CFLAGS=\t$(AM_CFLAGS)\n\n# Test libscrypt-kdf compile.\ntests_libscrypt_kdf_sample_libscrypt_kdf_SOURCES=\t\t\t\\\n\ttests/libscrypt-kdf/sample-libscrypt-kdf.c\ntests_libscrypt_kdf_sample_libscrypt_kdf_CPPFLAGS=\t\t\t\\\n\t-I$(srcdir)/libscrypt-kdf/\ntests_libscrypt_kdf_sample_libscrypt_kdf_LDADD=\t\tlibscrypt-kdf.la\n\n# crypto_aesctr_shared.c is in this list because it can't be included in the\n# _SOURCES because it should only be included as part of another translation\n# unit.\nEXTRA_DIST=\t\t\t\t\t\t\t\t\\\n\t.autom4te.cfg\t\t\t\t\t\t\t\\\n\tBUILDING\t\t\t\t\t\t\t\\\n\tCOPYRIGHT\t\t\t\t\t\t\t\\\n\tFORMAT\t\t\t\t\t\t\t\t\\\n\tREADME.md\t\t\t\t\t\t\t\\\n\tSTYLE\t\t\t\t\t\t\t\t\\\n\tget-version.sh\t\t\t\t\t\t\t\\\n\tlib/README\t\t\t\t\t\t\t\\\n\tlib/crypto/crypto_scrypt-ref.c\t\t\t\t\t\\\n\tlibcperciva/POSIX/README\t\t\t\t\t\\\n\tlibcperciva/POSIX/posix-abstract-declarator.c\t\t\t\\\n\tlibcperciva/POSIX/posix-cflags.sh\t\t\t\t\\\n\tlibcperciva/POSIX/posix-clock_gettime.c\t\t\t\t\\\n\tlibcperciva/POSIX/posix-clock_realtime.c\t\t\t\\\n\tlibcperciva/POSIX/posix-inet-addrstrlen.c\t\t\t\\\n\tlibcperciva/POSIX/posix-inet6-addrstrlen.c\t\t\t\\\n\tlibcperciva/POSIX/posix-l.sh\t\t\t\t\t\\\n\tlibcperciva/POSIX/posix-msg_nosignal.c\t\t\t\t\\\n\tlibcperciva/POSIX/posix-restrict.c\t\t\t\t\\\n\tlibcperciva/POSIX/posix-stat-st_mtim.c\t\t\t\t\\\n\tlibcperciva/POSIX/posix-trivial.c\t\t\t\t\\\n\tlibcperciva/apisupport/Build/apisupport-LIBCRYPTO-LOW_LEVEL_AES.c\\\n\tlibcperciva/apisupport/Build/apisupport-NONPOSIX-MEMLIMIT.c\t\\\n\tlibcperciva/apisupport/Build/apisupport.sh\t\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-ARM-AES.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-ARM-SHA256.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-HWCAP-ELF_AUX_INFO.c\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-HWCAP-GETAUXVAL.c\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-AESNI.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-CPUID.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-CPUID_COUNT.c\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-RDRAND.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-SHANI.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-SSE2.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport-X86-SSSE3.c\t\t\\\n\tlibcperciva/cpusupport/Build/cpusupport.sh\t\t\t\\\n\tlibcperciva/crypto/crypto_aesctr_shared.c\t\t\t\\\n\ttests/01-known-values.sh\t\t\t\t\t\\\n\ttests/02-decrypt-reference-file.sh\t\t\t\t\\\n\ttests/03-encrypt-decrypt-file.sh\t\t\t\t\\\n\ttests/04-force-resources.sh\t\t\t\t\t\\\n\ttests/05-system-scrypt-encrypt-decrypt.sh\t\t\t\\\n\ttests/06-decrypt-fail.sh\t\t\t\t\t\\\n\ttests/07-passphrase-env.sh\t\t\t\t\t\\\n\ttests/08-passphrase-file.sh\t\t\t\t\t\\\n\ttests/09-explicit-params.sh\t\t\t\t\t\\\n\ttests/shared_test_functions.sh\t\t\t\t\t\\\n\ttests/shared_valgrind_functions.sh\t\t\t\t\\\n\ttests/test_scrypt.sh\t\t\t\t\t\t\\\n\ttests/verify-strings/test_scrypt.good\t\t\t\t\\\n\ttests/verify-strings/test_scrypt_good.enc\t\t\t\\\n\ttests/verify-strings/test_scrypt_small.good\n\n# Binary to test the crypto_scrypt() function.\ntests_verify_strings_test_scrypt_SOURCES=\t\t\t\t\\\n\ttests/verify-strings/test_scrypt.c\t\t\t\t\\\n\t$(crypto_scrypt_files)\n\ntests_verify_strings_test_scrypt_LDADD=\t\t\t\t\t\\\n\tlibcperciva_arm_sha256.la\t\t\t\t\t\\\n\tlibcperciva_cpusupport_detect.la\t\t\t\t\\\n\tlibcperciva_shani.la\t\t\t\t\t\t\\\n\tlibscrypt_sse2.la\t\t\t\t\t\t\\\n\t${LDADD_POSIX}\n\n# Eliminate false positives while memory-checking for the test framework.\ntests_valgrind_potential_memleaks_SOURCES= tests/valgrind/potential-memleaks.c\n\n.PHONY: test\n# we can't only build \"scrypt tests/verify-strings/test_scrypt\" because that\n# won't build the BUILT_SOURCES.\ntest: all\n\t$(top_srcdir)/tests/test_scrypt.sh .\n"
  },
  {
    "path": "README.md",
    "content": "The scrypt key derivation function\n----------------------------------\n\n\nThe scrypt key derivation function was originally developed for use in the\n[Tarsnap online backup system](https://www.tarsnap.com/index.html) and is\ndesigned to be far more secure against hardware brute-force attacks than\nalternative functions such as [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) or\n[bcrypt](https://www.openbsd.org/papers/bcrypt-paper.ps).\n\nWe estimate that on modern (2009) hardware, if 5 seconds are spent computing a\nderived key, the cost of a hardware brute-force attack against `scrypt` is\nroughly 4000 times greater than the cost of a similar attack against bcrypt (to\nfind the same password), and 20000 times greater than a similar attack against\nPBKDF2.  If the `scrypt` encryption utility is used with default parameters,\nthe cost of cracking the password on a file encrypted by `scrypt enc` is\napproximately 100 billion times more than the cost of cracking the same\npassword on a file encrypted by `openssl enc`; this means that a five-character\npassword using `scrypt` is stronger than a ten-character password using\n`openssl`.\n\nDetails of the `scrypt` key derivation function are given in:\n\n* The Internet Engineering Task Force (IETF)\n  [RFC 7914: The scrypt Password-Based Key Derivation Function](\n  https://tools.ietf.org/html/rfc7914).\n* The original conference paper: Colin Percival,\n  [Stronger Key Derivation via Sequential Memory-Hard Functions](\n  https://www.tarsnap.com/scrypt/scrypt.pdf), presented at\n  [BSDCan'09](https://www.bsdcan.org/2009/), May 2009.\n  [Conference presentation slides](\n  https://www.tarsnap.com/scrypt/scrypt-slides.pdf).\n\nSome additional articles may be of interest:\n\n* Filippo Valsorda presented a very well-written explanation about how\n  [the scrypt parameters](https://blog.filippo.io/the-scrypt-parameters/)\n  impact the memory usage and CPU time of the algorithm.\n* J. Alwen, B. Chen, K. Pietrzak, L. Reyzin, S. Tessaro,\n  [Scrypt is Maximally Memory-Hard](https://eprint.iacr.org/2016/989),\n  Cryptology ePrint Archive: Report 2016/989.\n\n\nThe scrypt encryption utility\n-----------------------------\n\nA simple password-based encryption utility is available as a demonstration of\nthe `scrypt` key derivation function.  It can be invoked as:\n\n* `scrypt enc [options] infile [outfile]` to encrypt data,\n* `scrypt dec [options] infile [outfile]` to decrypt data, or\n* `scrypt info infile` to see the encryption parameters used, and the memory\n  required to decrypt the encrypted file.\n\nIf `[outfile]` is not specified, the output is written to standard output.\n`scrypt` also supports a number of command-line `[options]`:\n\n* `-t maxtime` will instruct `scrypt` to spend at most maxtime seconds\n  computing the derived encryption key from the password; for encryption, this\n  value will determine how secure the encrypted data is, while for decryption\n  this value is used as an upper limit (if `scrypt` detects that it would take\n  too long to decrypt the data, it will exit with an error message).\n* `-m maxmemfrac` instructs `scrypt` to use at most the specified fraction of\n  the available RAM for computing the derived encryption key.  For encryption,\n  increasing this value might increase the security of the encrypted data,\n  depending on the `maxtime` value; for decryption, this value is used as an\n  upper limit and may `cause` scrypt to exit with an error.\n* `-M maxmem` instructs `scrypt` to use at most the specified number of bytes\n  of RAM when computing the derived encryption key.\n* `--logN value1`, `-r value2`, `-p value3` will set the encryption parameters\n  explicitly.\n* `--passphrase method:arg` allows the user to specify whether to read the\n  passphrase from stdin, /dev/tty, an environment variable, or a file.\n\nIf the encrypted data is corrupt, `scrypt dec` will exit with a non-zero\nstatus.  However, **`scrypt dec` may produce output before it determines that\nthe encrypted data was corrupt**, so for applications which require data to be\nauthenticated, you must store the output of `scrypt dec` in a temporary\nlocation and check `scrypt`'s exit code before using the decrypted data.\n\n\nUsing scrypt as a KDF\n---------------------\n\nTo use scrypt as a [key derivation function](\nhttps://en.wikipedia.org/wiki/Key_derivation_function) (KDF) with\n`libscrypt-kdf`, include `scrypt-kdf.h` and use:\n\n```\n/**\n * scrypt_kdf(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):\n * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,\n * p, buflen) and write the result into buf.  The parameters r, p, and buflen\n * must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32.  The parameter N\n * must be a power of 2 greater than 1.\n *\n * Return 0 on success; or -1 on error.\n */\nint scrypt_kdf(const uint8_t *, size_t, const uint8_t *, size_t, uint64_t,\n    uint32_t, uint32_t, uint8_t *, size_t);\n```\n\nThere is a sample of using this function in `tests/libscrypt-kdf`.\nIf you installed the library, you can compile that file and run\nthe binary:\n\n```\n$ cd tests/libscrypt-kdf/\n$ c99 sample-libscrypt-kdf.c -lscrypt-kdf\n$ ./a.out\ncrypto_scrypt(): success\n```\n\nIf you would rather copy our source files directly into your\nproject, then take a look at the `lib/crypto/crypto_scrypt.h`\nheader, which provides `crypto_scrypt()`.\n\n\nOfficial releases\n-----------------\n\nThe `scrypt` utility has been tested on FreeBSD, NetBSD, OpenBSD, Linux\n(Slackware, CentOS, Gentoo, Ubuntu), Solaris, OS X, Cygwin, and GNU Hurd.\n\n* [scrypt version 1.3.3 source tarball](\n  https://www.tarsnap.com/scrypt/scrypt-1.3.3.tgz)\n* [GPG-signed SHA256 for scrypt version 1.3.3](\n  https://www.tarsnap.com/scrypt/scrypt-sigs-1.3.3.asc) (signature\n  generated using Tarsnap [code signing key](\n  https://www.tarsnap.com/tarsnap-signing-key.asc))\n\n  This cleartext signature of the SHA256 output can be verified with:\n\n      gpg --decrypt scrypt-sigs-1.3.3.asc\n\n  You may then compare the displayed hash to the SHA256 hash of\n  `scrypt-1.3.3.tgz`.\n\nIn addition, `scrypt` is available in the OpenBSD and FreeBSD ports trees and\nin NetBSD pkgsrc as `security/scrypt`.\n\n\nBuilding\n--------\n\n:exclamation: We strongly recommend that people use the latest\nofficial release tarball on https://www.tarsnap.com/scrypt.html\n\nTo build scrypt, extract the tarball and run `./configure` && `make`.  See the\n[BUILDING](BUILDING) file for more details (e.g., dealing with OpenSSL on OSX).\n\n\nTesting\n-------\n\nA small test suite can be run with:\n\n    make test\n\nOn platforms with less than 1 GB of RAM, use:\n\n    make test SMALLMEM=1\n\nMemory-testing normal operations with valgrind (takes approximately 4 times as\nlong as no valgrind tests) can be enabled with:\n\n    make test USE_VALGRIND=1\n\nMemory-testing all tests with valgrind (requires over 1 GB memory, and takes\napproximately 4 times as long as `USE_VALGRIND=1`) can be enabled with:\n\n    make test USE_VALGRIND=2\n\n\nMailing list\n------------\n\nThe scrypt key derivation function and the scrypt encryption utility are\ndiscussed on the <scrypt@tarsnap.com> mailing list.\n"
  },
  {
    "path": "STYLE",
    "content": "Code style\n==========\n\nIn general, FreeBSD style(9) should be followed unless it is irrelevant\n(e.g., $FreeBSD$ tags).\n\nFunctions with external linkage are declared like this:\n\t/**\n\t * module_func(arg1, arg2):\n\t * Description of what the function does, referring to arguments as\n\t * ${arg1} or suchlike.\n\t */\n\tint module_func(void *, int);\n\nThe identical comment appears in the C file where the function is defined.\n\nStatic functions may have the above form of comment, or simply a\n/* Brief description of what the function does. */\nline before the function.\n\n\"Unrewrappable\" comments starting in the first column should be\n/**\n * Written like this.\n *\n * Because (some of) the line-breaks are important.\n */\nwhereas when such comments are indented, they should be\n\t/*-\n\t * Written like this.\n\t *\n\t * Because (some of) the line-breaks are important.\n\t */\n\nLine lengths should generally be 78 characters, and not more than 80\ncharacters.\n\nIn general, functions should return (int)(-1) or NULL to indicate error.\n\nErrors should be printed via warnp (if errno is relevant) or warn0 (if errno\nis not relevant) when they are first detected and also at higher levels where\nuseful.  As an exception to this, malloc failures (i.e., errno = ENOMEM) can\nresult in failure being passed back up the call chain without being printed\nimmediately.  (Naturally, other errors can be passed back where a function\ndefinition so specifies; e.g., ENOENT in cases where a file not existing is\nnot erroneous.)\n\nThe first statement in main(), after variable declarations, should be\n\"WARNP_INIT;\" in order to set the program name used for printing warnings.\n\nWe use %d rather than %i in printf and warn0/warnp strings.\n\nIn general, functions should be structured with one return statement per\nstatus, e.g., one return() for success and one return() for failure.  Errors\nshould be handled by using goto to enter the error return path, e.g.,\n\tint\n\tfoo(int bar)\n\t{\n\n\t\tif (something fails)\n\t\t\tgoto err0;\n\t\t/* ... */\n\t\tif (something else fails)\n\t\t\tgoto err1;\n\t\t/* ... */\n\t\tif (yet another operation fails)\n\t\t\tgoto err2;\n\n\t\t/* Success! */\n\t\treturn (0);\n\n\terr2:\n\t\t/* Clean up something. */\n\terr1:\n\t\t/* Clean up something else. */\n\terr0:\n\t\t/* Failure! */\n\t\treturn (-1);\n\t}\n\nAs an exception to the above, if there is only one way for the function to\nfail, the idioms\n\treturn (baz(bar));\nand\n\tint rc;\n\n\trc = baz(bar);\n\t/* ... cleanup code here ... */\n\treturn (rc);\nare allowed; furthermore, in cases such as foo_free(), the idiom\n\tif (we shouldn't do anything)\n\t\treturn;\nis preferred over\n\tif (we shouldn't do anything)\n\t\tgoto done;\nat the start of a function.\n\nHeaders should be included in the following groups, with a blank line after\neach (non-empty) group:\n1. <sys/*.h>, with <sys/types.h> first followed by others alphabetically.\n2. <net/*.h>, in alphabetical order.\n3. <*.h>, in alphabetical order.\n4. header files from /lib/, in alphabetical order.\n5. header files from the program being built, in alphabetical order.\n6. header files (usually just one) defining the interface for this C file.\n\nIf ssize_t is needed, <unistd.h> should be included to provide it.\n\nIf size_t is needed, <stddef.h> should be included to provide it unless\n<stdio.h>, <stdlib.h>, <string.h>, or <unistd.h> is already required.\n\nIf the C99 integer types (uint8_t, int64_t, etc.) are required, <stdint.h>\nshould be included to provide them unless <inttypes.h> is already required.\n\nThe type 'char' should only be used to represent human-readable characters\n(input from users, output to users, pathnames, et cetera).  The type\n'char *' should normally be a NUL-terminated string.  The types 'signed\nchar' and 'unsigned char' should never be used; C99 integer types should\nbe used instead.\n\nWhen a variable is declared to have a pointer type, there should be a space\nbetween the '*' and the variable name, e.g.,\n\tint\n\tmain(int argc, char * argv[])\n\t{\n\t\tchar * opt_p = NULL;\nNote that this is inconsistent with FreeBSD style(9).  When used as a unary\noperator, '*' is not separated from its argument, e.g.,\n\twhile (*p != '\\0')\n\t\tp++;\n\nWhen a struct is referenced, the idiom\n\t/* Opaque types. */\n\tstruct foo;\n\n\tstruct bar * bar_from_foo(struct foo *);\nis preferable to\n\t#include \"foo.h\"\t/* needed for struct foo */\n\n\tstruct bar * bar_from_foo(struct foo *);\nunless there is some reason why the internal layout of struct foo is needed\n(e.g., if struct bar contains a struct foo rather than a struct foo *).  Such\nstruct declarations should be sorted alphabetically.\n\nThe file foo.c should only export symbols of the following forms:\n\tfoo_*\t-- most symbols should be of this form.\n\tFOO_* / BAR_FOO_*\n\t\t-- allowed in cases where FOO or BAR_FOO is idiomatic (e.g.,\n\t\t   MD5, HMAC_SHA256).\n\tfoo() / defoo() / unfoo()\n\t\t-- where \"foo\" is a verb and this improves code clarity.\n\nFunctions named foo_free should return void, and foo_free(NULL) should have\nno effect.  The right way to spell a comment about this is\n\t/* Behave consistently with free(NULL). */\n\nIf static variables need to be initialized to 0 (or NULL) then they should be\nexplicitly declared that way; implicit initialization should not be used.\n\nIn non-trivial code, comments should be included which describe in English\nwhat is being done by the surrounding code with sufficient detail that if the\ncode were removed, it could be replaced based on reading the comments without\nrequiring any significant creativity.\n\nComments and documentation should be written in en-GB-oed; i.e., with\nthe 'u' included in words such as \"honour\", \"colour\", and \"neighbour\",\nand the ending '-ize' in words such as \"organize\" and \"realize\".  The\nOxford (aka. serial) comma should be used in lists.  Quotation marks\nshould be placed logically, i.e., not including punctuation marks which\ndo not form a logical part of the quoted text.  Two spaces should be used\nafter a period which ends a sentence.\n\nThe first local variable declaration in cookie-using functions should be\n\tstruct foo * bar = cookie;\n\nWhen versions of functions are written to exploit special CPU features\n(using the cpusupport framework), that code should be placed into a\nseparate file (e.g., crypto_aes_aesni.c) so that it can be compiled with\ndifferent compiler flags.  Such a file should start with\n\t#include \"cpusupport.h\"\n\t#ifdef CPUSUPPORT_FOO_BAR\n\t/**\n\t * CPUSUPPORT CFLAGS: FOO_BAR FOO_BAZ\n\t */\nand end with\n\t#endif /* CPUSUPPORT_FOO_BAR */\n\nFor example, we could have\n\t#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3)\n\t/**\n\t * CPUSUPPORT CFLAGS: X86_SHANI X86_SSSE3\n\t */\n\nFunctions for which special CPU-feature-exploiting variants exist should\ntake the form\n\t{\n\t\t/* Variable declarations here. */\n\n\t\t/* Asserts here, if any. */\n\n\t#ifdef CPUSUPPORT_FOO_BAR\n\t\tif (/* We've decided we can use the variant code */) {\n\t\t\t/* Call variant code and return. */\n\t\t}\n\t#endif\n\n\t\t/* Normal implementation of the function. */\n\t}\n\nIf there are multiple CPU-feature-exploiting variants, the `if` could instead\nbe a `switch` which invokes the appropriate variant function.\n"
  },
  {
    "path": "configure.ac",
    "content": "AC_PREREQ([2.69])\nAC_INIT([scrypt],[m4_esyscmd([sh get-version.sh])],\n  [https://github.com/Tarsnap/scrypt],[scrypt],[http://www.tarsnap.com/scrypt/])\n\n# Safety check: make sure that the srcdir contains this file.\nAC_CONFIG_SRCDIR([lib/scryptenc/scryptenc.c])\n# Use auxiliary subscripts from this subdirectory (cleans up root).\nAC_CONFIG_AUX_DIR([config.aux])\n# Directory for our additional macros.\nAC_CONFIG_MACRO_DIR([m4])\n# Compute $target_os and related variables.\nAC_CANONICAL_TARGET\nAM_INIT_AUTOMAKE([foreign subdir-objects])\n\n# Checks for programs.\nm4_version_prereq([2.70], [AC_PROG_CC], [AC_PROG_CC_C99])\nAM_PROG_AR\nLT_INIT\n\n# Don't rebuild the configure script.  I'm distributing a perfectly good one.\nAM_MAINTAINER_MODE\n\n# Get the POSIX sh early, in case the configure script causes\n# `command -p getconf` to fail in a broken environment.\nCHECK_POSIX_SH\n\n# Check if we need -std=c99 in LDFLAGS (for gcc on Solaris).\nCHECK_SOLARIS_C99\n\n# Check if we need to add extra paths to CPPFLAGS and LDFLAGS for macOS.\nCHECK_DARWIN_PATHS\n\n# Checks for AES support in OpenSSL.\nAC_SEARCH_LIBS([AES_encrypt], [crypto],,\n    AC_MSG_ERROR([function AES_ENCRYPT not found]))\nAC_CHECK_HEADERS([openssl/aes.h],,\n  [AC_MSG_ERROR([Unable to find the openssl/aes.h header])])\n\n# Check how we can find out the available memory.\nCHECK_MEMLIMIT_SUPPORT\n\n# Check for posix_memalign.\nAC_CHECK_FUNCS_ONCE([posix_memalign])\n\n# Check for mmap so we can work around its absence on Minix.\nAC_CHECK_FUNCS_ONCE([mmap])\n\n# Use 64-bit file offsets.\nAC_SYS_LARGEFILE\n\n# Check whether the user has requested to disable compiler warnings.\nCHECK_DISABLE_COMPILER_WARNINGS\n\n# Check libcperciva POSIX compatibility.\nCHECK_LIBCPERCIVA_POSIX([${srcdir}/libcperciva])\n\n# Check whether the user wants to install libscrypt-kdf.\nAC_ARG_ENABLE(libscrypt-kdf, AS_HELP_STRING([--enable-libscrypt-kdf],\n    [Install libscrypt-kdf and development headers.]))\nAM_CONDITIONAL([LIBSCRYPT_KDF], [test \"x${enable_libscrypt_kdf}\" = \"xyes\"])\n\n# Write configure results and the Makefile.\nAC_CONFIG_HEADERS([config.h])\nAC_CONFIG_FILES([Makefile])\nAC_OUTPUT\n"
  },
  {
    "path": "get-version.sh",
    "content": "#!/bin/sh\n\nversion=1.3.3-head\n\n# This script outputs a version number for this project to stdout.\n# - if $SCRYPT_VERSION is given, it is used.\n# - otherwise, it uses ${version}.\n# - if there is a \".git/\" directory, it will attempt to get a version number\n#   from `git describe` in the form 1.2.0-238-g0a25a7c, where the middle value\n#   is the number of commits since the 1.2.0 tag.\n\n# Use $SCRYPT_VERSION if it exists.\nif [ -n \"${SCRYPT_VERSION}\" ]; then\n\t# Do not use \\n; that confuses autoconf.\n\tprintf \"%s\" \"${SCRYPT_VERSION}\"\n\texit 0\nfi\n\n# Get a version number from git, if it exists.\nif git rev-parse 2>/dev/null; then\n\t# Get a version string from the latest git tag.\n\tif version_git=$( git describe --tags --match '[[:digit:]].*' ) \\\n\t    2>/dev/null ; then\n\t\tversion_decapitated=$( echo \"${version}\" | sed \"s/-head//\" )\n\t\t# Check that the beginning of this tag matches the version.\n\t\tcase ${version_git} in\n\t\t\"${version_decapitated}\"*)\n\t\t\t# If so, use that version string.\n\t\t\tversion=${version_git};;\n\t\t*)\n\t\t\tprintf \"git tag does not match version\\n\" 1>&2\n\t\t\texit 1;;\n\t\tesac\n\tfi\nfi\n\n# Output the version to stdout.  Do not use \\n; that confuses autoconf.\nprintf \"%s\" \"${version}\"\n"
  },
  {
    "path": "lib/README",
    "content": "The source code under this directory is taken from the client for the\nTarsnap online backup system (and released under the 2-clause BSD license\nwith permission of the author); keeping this code in sync with the Tarsnap\ncode is highly desirable and explains why there is some functionality\nincluded here which is not actually used by the scrypt file encryption\nutility.\n"
  },
  {
    "path": "lib/crypto/crypto_scrypt-ref.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#include <errno.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"sha256.h\"\n#include \"sysendian.h\"\n\n#include \"crypto_scrypt.h\"\n\nstatic void blkcpy(uint8_t *, uint8_t *, size_t);\nstatic void blkxor(uint8_t *, uint8_t *, size_t);\nstatic void salsa20_8(uint8_t[64]);\nstatic void blockmix_salsa8(uint8_t *, uint8_t *, size_t);\nstatic uint64_t integerify(uint8_t *, size_t);\nstatic void smix(uint8_t *, size_t, uint64_t, uint8_t *, uint8_t *);\n\nstatic void\nblkcpy(uint8_t * dest, uint8_t * src, size_t len)\n{\n\tsize_t i;\n\n\tfor (i = 0; i < len; i++)\n\t\tdest[i] = src[i];\n}\n\nstatic void\nblkxor(uint8_t * dest, uint8_t * src, size_t len)\n{\n\tsize_t i;\n\n\tfor (i = 0; i < len; i++)\n\t\tdest[i] ^= src[i];\n}\n\n/**\n * salsa20_8(B):\n * Apply the salsa20/8 core to the provided block.\n */\nstatic void\nsalsa20_8(uint8_t B[64])\n{\n\tuint32_t B32[16];\n\tuint32_t x[16];\n\tsize_t i;\n\n\t/* Convert little-endian values in. */\n\tfor (i = 0; i < 16; i++)\n\t\tB32[i] = le32dec(&B[i * 4]);\n\n\t/* Compute x = doubleround^4(B32). */\n\tfor (i = 0; i < 16; i++)\n\t\tx[i] = B32[i];\n\tfor (i = 0; i < 8; i += 2) {\n#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))\n\t\t/* Operate on columns. */\n\t\tx[ 4] ^= R(x[ 0]+x[12], 7);  x[ 8] ^= R(x[ 4]+x[ 0], 9);\n\t\tx[12] ^= R(x[ 8]+x[ 4],13);  x[ 0] ^= R(x[12]+x[ 8],18);\n\n\t\tx[ 9] ^= R(x[ 5]+x[ 1], 7);  x[13] ^= R(x[ 9]+x[ 5], 9);\n\t\tx[ 1] ^= R(x[13]+x[ 9],13);  x[ 5] ^= R(x[ 1]+x[13],18);\n\n\t\tx[14] ^= R(x[10]+x[ 6], 7);  x[ 2] ^= R(x[14]+x[10], 9);\n\t\tx[ 6] ^= R(x[ 2]+x[14],13);  x[10] ^= R(x[ 6]+x[ 2],18);\n\n\t\tx[ 3] ^= R(x[15]+x[11], 7);  x[ 7] ^= R(x[ 3]+x[15], 9);\n\t\tx[11] ^= R(x[ 7]+x[ 3],13);  x[15] ^= R(x[11]+x[ 7],18);\n\n\t\t/* Operate on rows. */\n\t\tx[ 1] ^= R(x[ 0]+x[ 3], 7);  x[ 2] ^= R(x[ 1]+x[ 0], 9);\n\t\tx[ 3] ^= R(x[ 2]+x[ 1],13);  x[ 0] ^= R(x[ 3]+x[ 2],18);\n\n\t\tx[ 6] ^= R(x[ 5]+x[ 4], 7);  x[ 7] ^= R(x[ 6]+x[ 5], 9);\n\t\tx[ 4] ^= R(x[ 7]+x[ 6],13);  x[ 5] ^= R(x[ 4]+x[ 7],18);\n\n\t\tx[11] ^= R(x[10]+x[ 9], 7);  x[ 8] ^= R(x[11]+x[10], 9);\n\t\tx[ 9] ^= R(x[ 8]+x[11],13);  x[10] ^= R(x[ 9]+x[ 8],18);\n\n\t\tx[12] ^= R(x[15]+x[14], 7);  x[13] ^= R(x[12]+x[15], 9);\n\t\tx[14] ^= R(x[13]+x[12],13);  x[15] ^= R(x[14]+x[13],18);\n#undef R\n\t}\n\n\t/* Compute B32 = B32 + x. */\n\tfor (i = 0; i < 16; i++)\n\t\tB32[i] += x[i];\n\n\t/* Convert little-endian values out. */\n\tfor (i = 0; i < 16; i++)\n\t\tle32enc(&B[4 * i], B32[i]);\n}\n\n/**\n * blockmix_salsa8(B, Y, r):\n * Compute B = BlockMix_{salsa20/8, r}(B).  The input B must be 128r bytes in\n * length; the temporary space Y must also be the same size.\n */\nstatic void\nblockmix_salsa8(uint8_t * B, uint8_t * Y, size_t r)\n{\n\tuint8_t X[64];\n\tsize_t i;\n\n\t/* 1: X <-- B_{2r - 1} */\n\tblkcpy(X, &B[(2 * r - 1) * 64], 64);\n\n\t/* 2: for i = 0 to 2r - 1 do */\n\tfor (i = 0; i < 2 * r; i++) {\n\t\t/* 3: X <-- H(X \\xor B_i) */\n\t\tblkxor(X, &B[i * 64], 64);\n\t\tsalsa20_8(X);\n\n\t\t/* 4: Y_i <-- X */\n\t\tblkcpy(&Y[i * 64], X, 64);\n\t}\n\n\t/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */\n\tfor (i = 0; i < r; i++)\n\t\tblkcpy(&B[i * 64], &Y[(i * 2) * 64], 64);\n\tfor (i = 0; i < r; i++)\n\t\tblkcpy(&B[(i + r) * 64], &Y[(i * 2 + 1) * 64], 64);\n}\n\n/**\n * integerify(B, r):\n * Return the result of parsing B_{2r-1} as a little-endian integer.\n */\nstatic uint64_t\nintegerify(uint8_t * B, size_t r)\n{\n\tuint8_t * X = &B[(2 * r - 1) * 64];\n\n\treturn (le64dec(X));\n}\n\n/**\n * smix(B, r, N, V, XY):\n * Compute B = SMix_r(B, N).  The input B must be 128r bytes in length; the\n * temporary storage V must be 128rN bytes in length; the temporary storage\n * XY must be 256r bytes in length.  The value N must be a power of 2.\n */\nstatic void\nsmix(uint8_t * B, size_t r, uint64_t N, uint8_t * V, uint8_t * XY)\n{\n\tuint8_t * X = XY;\n\tuint8_t * Y = &XY[128 * r];\n\tuint64_t i;\n\tuint64_t j;\n\n\t/* 1: X <-- B */\n\tblkcpy(X, B, 128 * r);\n\n\t/* 2: for i = 0 to N - 1 do */\n\tfor (i = 0; i < N; i++) {\n\t\t/* 3: V_i <-- X */\n\t\tblkcpy(&V[i * (128 * r)], X, 128 * r);\n\n\t\t/* 4: X <-- H(X) */\n\t\tblockmix_salsa8(X, Y, r);\n\t}\n\n\t/* 6: for i = 0 to N - 1 do */\n\tfor (i = 0; i < N; i++) {\n\t\t/* 7: j <-- Integerify(X) mod N */\n\t\tj = integerify(X, r) & (N - 1);\n\n\t\t/* 8: X <-- H(X \\xor V_j) */\n\t\tblkxor(X, &V[j * (128 * r)], 128 * r);\n\t\tblockmix_salsa8(X, Y, r);\n\t}\n\n\t/* 10: B' <-- X */\n\tblkcpy(B, X, 128 * r);\n}\n\n/**\n * crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):\n * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,\n * p, buflen) and write the result into buf.  The parameters r, p, and buflen\n * must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32.  The parameter N\n * must be a power of 2.\n *\n * Return 0 on success; or -1 on error.\n */\nint\ncrypto_scrypt(const uint8_t * passwd, size_t passwdlen,\n    const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t _r, uint32_t _p,\n    uint8_t * buf, size_t buflen)\n{\n\tuint8_t * B;\n\tuint8_t * V;\n\tuint8_t * XY;\n\tsize_t r = _r, p = _p;\n\tuint32_t i;\n\n\t/* Sanity-check parameters. */\n#if SIZE_MAX > UINT32_MAX\n\tif (buflen > (((uint64_t)(1) << 32) - 1) * 32) {\n\t\terrno = EFBIG;\n\t\tgoto err0;\n\t}\n#endif\n\tif ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) {\n\t\terrno = EFBIG;\n\t\tgoto err0;\n\t}\n\tif (((N & (N - 1)) != 0) || (N == 0)) {\n\t\terrno = EINVAL;\n\t\tgoto err0;\n\t}\n\tif ((r > SIZE_MAX / 128 / p) ||\n#if SIZE_MAX / 256 <= UINT32_MAX\n\t    (r > SIZE_MAX / 256) ||\n#endif\n\t    (N > SIZE_MAX / 128 / r)) {\n\t\terrno = ENOMEM;\n\t\tgoto err0;\n\t}\n\n\t/* Allocate memory. */\n\tif ((B = malloc(128 * r * p)) == NULL)\n\t\tgoto err0;\n\tif ((XY = malloc(256 * r)) == NULL)\n\t\tgoto err1;\n\tif ((V = malloc(128 * r * N)) == NULL)\n\t\tgoto err2;\n\n\t/* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */\n\tPBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, B, p * 128 * r);\n\n\t/* 2: for i = 0 to p - 1 do */\n\tfor (i = 0; i < p; i++) {\n\t\t/* 3: B_i <-- MF(B_i, N) */\n\t\tsmix(&B[i * 128 * r], r, N, V, XY);\n\t}\n\n\t/* 5: DK <-- PBKDF2(P, B, 1, dkLen) */\n\tPBKDF2_SHA256(passwd, passwdlen, B, p * 128 * r, 1, buf, buflen);\n\n\t/* Free memory. */\n\tfree(V);\n\tfree(XY);\n\tfree(B);\n\n\t/* Success! */\n\treturn (0);\n\nerr2:\n\tfree(XY);\nerr1:\n\tfree(B);\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n"
  },
  {
    "path": "lib/crypto/crypto_scrypt_smix.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#include <stdint.h>\n#include <string.h>\n\n#include \"sysendian.h\"\n\n#include \"crypto_scrypt_smix.h\"\n\nstatic void blkcpy(uint32_t *, const uint32_t *, size_t);\nstatic void blkxor(uint32_t *, const uint32_t *, size_t);\nstatic void salsa20_8(uint32_t[16]);\nstatic void blockmix_salsa8(const uint32_t *, uint32_t *, uint32_t *, size_t);\nstatic uint64_t integerify(const uint32_t *, size_t);\n\nstatic void\nblkcpy(uint32_t * dest, const uint32_t * src, size_t len)\n{\n\n\tmemcpy(dest, src, len);\n}\n\nstatic void\nblkxor(uint32_t * dest, const uint32_t * src, size_t len)\n{\n\tsize_t i;\n\n\tfor (i = 0; i < len / 4; i++)\n\t\tdest[i] ^= src[i];\n}\n\n/**\n * salsa20_8(B):\n * Apply the salsa20/8 core to the provided block.\n */\nstatic void\nsalsa20_8(uint32_t B[16])\n{\n\tuint32_t x[16];\n\tsize_t i;\n\n\tblkcpy(x, B, 64);\n\tfor (i = 0; i < 8; i += 2) {\n#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))\n\t\t/* Operate on columns. */\n\t\tx[ 4] ^= R(x[ 0]+x[12], 7);  x[ 8] ^= R(x[ 4]+x[ 0], 9);\n\t\tx[12] ^= R(x[ 8]+x[ 4],13);  x[ 0] ^= R(x[12]+x[ 8],18);\n\n\t\tx[ 9] ^= R(x[ 5]+x[ 1], 7);  x[13] ^= R(x[ 9]+x[ 5], 9);\n\t\tx[ 1] ^= R(x[13]+x[ 9],13);  x[ 5] ^= R(x[ 1]+x[13],18);\n\n\t\tx[14] ^= R(x[10]+x[ 6], 7);  x[ 2] ^= R(x[14]+x[10], 9);\n\t\tx[ 6] ^= R(x[ 2]+x[14],13);  x[10] ^= R(x[ 6]+x[ 2],18);\n\n\t\tx[ 3] ^= R(x[15]+x[11], 7);  x[ 7] ^= R(x[ 3]+x[15], 9);\n\t\tx[11] ^= R(x[ 7]+x[ 3],13);  x[15] ^= R(x[11]+x[ 7],18);\n\n\t\t/* Operate on rows. */\n\t\tx[ 1] ^= R(x[ 0]+x[ 3], 7);  x[ 2] ^= R(x[ 1]+x[ 0], 9);\n\t\tx[ 3] ^= R(x[ 2]+x[ 1],13);  x[ 0] ^= R(x[ 3]+x[ 2],18);\n\n\t\tx[ 6] ^= R(x[ 5]+x[ 4], 7);  x[ 7] ^= R(x[ 6]+x[ 5], 9);\n\t\tx[ 4] ^= R(x[ 7]+x[ 6],13);  x[ 5] ^= R(x[ 4]+x[ 7],18);\n\n\t\tx[11] ^= R(x[10]+x[ 9], 7);  x[ 8] ^= R(x[11]+x[10], 9);\n\t\tx[ 9] ^= R(x[ 8]+x[11],13);  x[10] ^= R(x[ 9]+x[ 8],18);\n\n\t\tx[12] ^= R(x[15]+x[14], 7);  x[13] ^= R(x[12]+x[15], 9);\n\t\tx[14] ^= R(x[13]+x[12],13);  x[15] ^= R(x[14]+x[13],18);\n#undef R\n\t}\n\tfor (i = 0; i < 16; i++)\n\t\tB[i] += x[i];\n}\n\n/**\n * blockmix_salsa8(Bin, Bout, X, r):\n * Compute Bout = BlockMix_{salsa20/8, r}(Bin).  The input Bin must be 128r\n * bytes in length; the output Bout must also be the same size.  The\n * temporary space X must be 64 bytes.\n */\nstatic void\nblockmix_salsa8(const uint32_t * Bin, uint32_t * Bout, uint32_t * X, size_t r)\n{\n\tsize_t i;\n\n\t/* 1: X <-- B_{2r - 1} */\n\tblkcpy(X, &Bin[(2 * r - 1) * 16], 64);\n\n\t/* 2: for i = 0 to 2r - 1 do */\n\tfor (i = 0; i < 2 * r; i += 2) {\n\t\t/* 3: X <-- H(X \\xor B_i) */\n\t\tblkxor(X, &Bin[i * 16], 64);\n\t\tsalsa20_8(X);\n\n\t\t/* 4: Y_i <-- X */\n\t\t/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */\n\t\tblkcpy(&Bout[i * 8], X, 64);\n\n\t\t/* 3: X <-- H(X \\xor B_i) */\n\t\tblkxor(X, &Bin[i * 16 + 16], 64);\n\t\tsalsa20_8(X);\n\n\t\t/* 4: Y_i <-- X */\n\t\t/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */\n\t\tblkcpy(&Bout[i * 8 + r * 16], X, 64);\n\t}\n}\n\n/**\n * integerify(B, r):\n * Return the result of parsing B_{2r-1} as a little-endian integer.\n */\nstatic uint64_t\nintegerify(const uint32_t * B, size_t r)\n{\n\tconst uint32_t * X = B + (2 * r - 1) * 16;\n\n\treturn (((uint64_t)(X[1]) << 32) + X[0]);\n}\n\n/**\n * crypto_scrypt_smix(B, r, N, V, XY):\n * Compute B = SMix_r(B, N).  The input B must be 128r bytes in length;\n * the temporary storage V must be 128rN bytes in length; the temporary\n * storage XY must be 256r + 64 bytes in length.  The value N must be a\n * power of 2 greater than 1.  The arrays B, V, and XY must be aligned to a\n * multiple of 64 bytes.\n */\nvoid\ncrypto_scrypt_smix(uint8_t * B, size_t r, uint64_t N, void * _v, void * XY)\n{\n\tuint32_t * X = XY;\n\tuint32_t * Y = (void *)((uint8_t *)(XY) + 128 * r);\n\tuint32_t * Z = (void *)((uint8_t *)(XY) + 256 * r);\n\tuint32_t * V = _v;\n\tuint64_t i;\n\tuint64_t j;\n\tsize_t k;\n\n\t/* 1: X <-- B */\n\tfor (k = 0; k < 32 * r; k++)\n\t\tX[k] = le32dec(&B[4 * k]);\n\n\t/* 2: for i = 0 to N - 1 do */\n\tfor (i = 0; i < N; i += 2) {\n\t\t/* 3: V_i <-- X */\n\t\tblkcpy(&V[i * (32 * r)], X, 128 * r);\n\n\t\t/* 4: X <-- H(X) */\n\t\tblockmix_salsa8(X, Y, Z, r);\n\n\t\t/* 3: V_i <-- X */\n\t\tblkcpy(&V[(i + 1) * (32 * r)], Y, 128 * r);\n\n\t\t/* 4: X <-- H(X) */\n\t\tblockmix_salsa8(Y, X, Z, r);\n\t}\n\n\t/* 6: for i = 0 to N - 1 do */\n\tfor (i = 0; i < N; i += 2) {\n\t\t/* 7: j <-- Integerify(X) mod N */\n\t\tj = integerify(X, r) & (N - 1);\n\n\t\t/* 8: X <-- H(X \\xor V_j) */\n\t\tblkxor(X, &V[j * (32 * r)], 128 * r);\n\t\tblockmix_salsa8(X, Y, Z, r);\n\n\t\t/* 7: j <-- Integerify(X) mod N */\n\t\tj = integerify(Y, r) & (N - 1);\n\n\t\t/* 8: X <-- H(X \\xor V_j) */\n\t\tblkxor(Y, &V[j * (32 * r)], 128 * r);\n\t\tblockmix_salsa8(Y, X, Z, r);\n\t}\n\n\t/* 10: B' <-- X */\n\tfor (k = 0; k < 32 * r; k++)\n\t\tle32enc(&B[4 * k], X[k]);\n}\n"
  },
  {
    "path": "lib/crypto/crypto_scrypt_smix.h",
    "content": "#ifndef CRYPTO_SCRYPT_SMIX_H_\n#define CRYPTO_SCRYPT_SMIX_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_scrypt_smix(B, r, N, V, XY):\n * Compute B = SMix_r(B, N).  The input B must be 128r bytes in length;\n * the temporary storage V must be 128rN bytes in length; the temporary\n * storage XY must be 256r + 64 bytes in length.  The value N must be a\n * power of 2 greater than 1.  The arrays B, V, and XY must be aligned to a\n * multiple of 64 bytes.\n */\nvoid crypto_scrypt_smix(uint8_t *, size_t, uint64_t, void *, void *);\n\n#endif /* !CRYPTO_SCRYPT_SMIX_H_ */\n"
  },
  {
    "path": "lib/crypto/crypto_scrypt_smix_sse2.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_X86_SSE2\n\n#include <emmintrin.h>\n#include <stdint.h>\n\n#include \"sysendian.h\"\n\n#include \"crypto_scrypt_smix_sse2.h\"\n\nstatic void blkcpy(__m128i *, const __m128i *, size_t);\nstatic void blkxor(__m128i *, const __m128i *, size_t);\nstatic void salsa20_8(__m128i[4]);\nstatic void blockmix_salsa8(const __m128i *, __m128i *, __m128i *, size_t);\nstatic uint64_t integerify(const __m128i *, size_t);\n\nstatic void\nblkcpy(__m128i * dest, const __m128i * src, size_t len)\n{\n\tsize_t L = len / 16;\n\tsize_t i;\n\n\tfor (i = 0; i < L; i++)\n\t\tdest[i] = src[i];\n}\n\nstatic void\nblkxor(__m128i * dest, const __m128i * src, size_t len)\n{\n\tsize_t L = len / 16;\n\tsize_t i;\n\n\tfor (i = 0; i < L; i++)\n\t\tdest[i] = _mm_xor_si128(dest[i], src[i]);\n}\n\n/**\n * salsa20_8(B):\n * Apply the salsa20/8 core to the provided block.\n */\nstatic void\nsalsa20_8(__m128i B[4])\n{\n\t__m128i X0, X1, X2, X3;\n\t__m128i T;\n\tsize_t i;\n\n\tX0 = B[0];\n\tX1 = B[1];\n\tX2 = B[2];\n\tX3 = B[3];\n\n\tfor (i = 0; i < 8; i += 2) {\n\t\t/* Operate on \"columns\". */\n\t\tT = _mm_add_epi32(X0, X3);\n\t\tX1 = _mm_xor_si128(X1, _mm_slli_epi32(T, 7));\n\t\tX1 = _mm_xor_si128(X1, _mm_srli_epi32(T, 25));\n\t\tT = _mm_add_epi32(X1, X0);\n\t\tX2 = _mm_xor_si128(X2, _mm_slli_epi32(T, 9));\n\t\tX2 = _mm_xor_si128(X2, _mm_srli_epi32(T, 23));\n\t\tT = _mm_add_epi32(X2, X1);\n\t\tX3 = _mm_xor_si128(X3, _mm_slli_epi32(T, 13));\n\t\tX3 = _mm_xor_si128(X3, _mm_srli_epi32(T, 19));\n\t\tT = _mm_add_epi32(X3, X2);\n\t\tX0 = _mm_xor_si128(X0, _mm_slli_epi32(T, 18));\n\t\tX0 = _mm_xor_si128(X0, _mm_srli_epi32(T, 14));\n\n\t\t/* Rearrange data. */\n\t\tX1 = _mm_shuffle_epi32(X1, 0x93);\n\t\tX2 = _mm_shuffle_epi32(X2, 0x4E);\n\t\tX3 = _mm_shuffle_epi32(X3, 0x39);\n\n\t\t/* Operate on \"rows\". */\n\t\tT = _mm_add_epi32(X0, X1);\n\t\tX3 = _mm_xor_si128(X3, _mm_slli_epi32(T, 7));\n\t\tX3 = _mm_xor_si128(X3, _mm_srli_epi32(T, 25));\n\t\tT = _mm_add_epi32(X3, X0);\n\t\tX2 = _mm_xor_si128(X2, _mm_slli_epi32(T, 9));\n\t\tX2 = _mm_xor_si128(X2, _mm_srli_epi32(T, 23));\n\t\tT = _mm_add_epi32(X2, X3);\n\t\tX1 = _mm_xor_si128(X1, _mm_slli_epi32(T, 13));\n\t\tX1 = _mm_xor_si128(X1, _mm_srli_epi32(T, 19));\n\t\tT = _mm_add_epi32(X1, X2);\n\t\tX0 = _mm_xor_si128(X0, _mm_slli_epi32(T, 18));\n\t\tX0 = _mm_xor_si128(X0, _mm_srli_epi32(T, 14));\n\n\t\t/* Rearrange data. */\n\t\tX1 = _mm_shuffle_epi32(X1, 0x39);\n\t\tX2 = _mm_shuffle_epi32(X2, 0x4E);\n\t\tX3 = _mm_shuffle_epi32(X3, 0x93);\n\t}\n\n\tB[0] = _mm_add_epi32(B[0], X0);\n\tB[1] = _mm_add_epi32(B[1], X1);\n\tB[2] = _mm_add_epi32(B[2], X2);\n\tB[3] = _mm_add_epi32(B[3], X3);\n}\n\n/**\n * blockmix_salsa8(Bin, Bout, X, r):\n * Compute Bout = BlockMix_{salsa20/8, r}(Bin).  The input Bin must be 128r\n * bytes in length; the output Bout must also be the same size.  The\n * temporary space X must be 64 bytes.\n */\nstatic void\nblockmix_salsa8(const __m128i * Bin, __m128i * Bout, __m128i * X, size_t r)\n{\n\tsize_t i;\n\n\t/* 1: X <-- B_{2r - 1} */\n\tblkcpy(X, &Bin[8 * r - 4], 64);\n\n\t/* 2: for i = 0 to 2r - 1 do */\n\tfor (i = 0; i < r; i++) {\n\t\t/* 3: X <-- H(X \\xor B_i) */\n\t\tblkxor(X, &Bin[i * 8], 64);\n\t\tsalsa20_8(X);\n\n\t\t/* 4: Y_i <-- X */\n\t\t/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */\n\t\tblkcpy(&Bout[i * 4], X, 64);\n\n\t\t/* 3: X <-- H(X \\xor B_i) */\n\t\tblkxor(X, &Bin[i * 8 + 4], 64);\n\t\tsalsa20_8(X);\n\n\t\t/* 4: Y_i <-- X */\n\t\t/* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */\n\t\tblkcpy(&Bout[(r + i) * 4], X, 64);\n\t}\n}\n\n/**\n * integerify(B, r):\n * Return the result of parsing B_{2r-1} as a little-endian integer.\n * Note that B's layout is permuted compared to the generic implementation.\n */\nstatic uint64_t\nintegerify(const __m128i * B, size_t r)\n{\n\tconst __m128i * X = B + (2*r - 1) * 4;\n\tuint32_t X0, X13;\n\n\t/* Get the first 32-bit element in X[0]. */\n\tX0 = (uint32_t)_mm_cvtsi128_si32(X[0]);\n\n\t/* Get the second 32-bit element in X[3]. */\n\tX13 = (uint32_t)_mm_cvtsi128_si32(_mm_srli_si128(X[3], 4));\n\n\treturn (((uint64_t)(X13) << 32) + X0);\n}\n\n/**\n * crypto_scrypt_smix_sse2(B, r, N, V, XY):\n * Compute B = SMix_r(B, N).  The input B must be 128r bytes in length;\n * the temporary storage V must be 128rN bytes in length; the temporary\n * storage XY must be 256r + 64 bytes in length.  The value N must be a\n * power of 2 greater than 1.  The arrays B, V, and XY must be aligned to a\n * multiple of 64 bytes.\n *\n * Use SSE2 instructions.\n */\nvoid\ncrypto_scrypt_smix_sse2(uint8_t * B, size_t r, uint64_t N, void * V, void * XY)\n{\n\t__m128i * X = XY;\n\t__m128i * Y = (void *)((uintptr_t)(XY) + 128 * r);\n\t__m128i * Z = (void *)((uintptr_t)(XY) + 256 * r);\n\tuint32_t * X32 = (void *)X;\n\tuint64_t i, j;\n\tsize_t k;\n\n\t/* 1: X <-- B */\n\tfor (k = 0; k < 2 * r; k++) {\n\t\tfor (i = 0; i < 16; i++) {\n\t\t\tX32[k * 16 + i] =\n\t\t\t    le32dec(&B[(k * 16 + (i * 5 % 16)) * 4]);\n\t\t}\n\t}\n\n\t/* 2: for i = 0 to N - 1 do */\n\tfor (i = 0; i < N; i += 2) {\n\t\t/* 3: V_i <-- X */\n\t\tblkcpy((void *)((uintptr_t)(V) + i * 128 * r), X, 128 * r);\n\n\t\t/* 4: X <-- H(X) */\n\t\tblockmix_salsa8(X, Y, Z, r);\n\n\t\t/* 3: V_i <-- X */\n\t\tblkcpy((void *)((uintptr_t)(V) + (i + 1) * 128 * r),\n\t\t    Y, 128 * r);\n\n\t\t/* 4: X <-- H(X) */\n\t\tblockmix_salsa8(Y, X, Z, r);\n\t}\n\n\t/* 6: for i = 0 to N - 1 do */\n\tfor (i = 0; i < N; i += 2) {\n\t\t/* 7: j <-- Integerify(X) mod N */\n\t\tj = integerify(X, r) & (N - 1);\n\n\t\t/* 8: X <-- H(X \\xor V_j) */\n\t\tblkxor(X, (void *)((uintptr_t)(V) + j * 128 * r), 128 * r);\n\t\tblockmix_salsa8(X, Y, Z, r);\n\n\t\t/* 7: j <-- Integerify(X) mod N */\n\t\tj = integerify(Y, r) & (N - 1);\n\n\t\t/* 8: X <-- H(X \\xor V_j) */\n\t\tblkxor(Y, (void *)((uintptr_t)(V) + j * 128 * r), 128 * r);\n\t\tblockmix_salsa8(Y, X, Z, r);\n\t}\n\n\t/* 10: B' <-- X */\n\tfor (k = 0; k < 2 * r; k++) {\n\t\tfor (i = 0; i < 16; i++) {\n\t\t\tle32enc(&B[(k * 16 + (i * 5 % 16)) * 4],\n\t\t\t    X32[k * 16 + i]);\n\t\t}\n\t}\n}\n\n#endif /* CPUSUPPORT_X86_SSE2 */\n"
  },
  {
    "path": "lib/crypto/crypto_scrypt_smix_sse2.h",
    "content": "#ifndef CRYPTO_SCRYPT_SMIX_SSE2_H_\n#define CRYPTO_SCRYPT_SMIX_SSE2_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_scrypt_smix_sse2(B, r, N, V, XY):\n * Compute B = SMix_r(B, N).  The input B must be 128r bytes in length;\n * the temporary storage V must be 128rN bytes in length; the temporary\n * storage XY must be 256r + 64 bytes in length.  The value N must be a\n * power of 2 greater than 1.  The arrays B, V, and XY must be aligned to a\n * multiple of 64 bytes.\n *\n * Use SSE2 instructions.\n */\nvoid crypto_scrypt_smix_sse2(uint8_t *, size_t, uint64_t, void *, void *);\n\n#endif /* !CRYPTO_SCRYPT_SMIX_SSE2_H_ */\n"
  },
  {
    "path": "lib/scryptenc/scryptenc.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#include <assert.h>\n#include <inttypes.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"crypto_aes.h\"\n#include \"crypto_aesctr.h\"\n#include \"crypto_entropy.h\"\n#include \"crypto_verify_bytes.h\"\n#include \"humansize.h\"\n#include \"insecure_memzero.h\"\n#include \"sha256.h\"\n#include \"sysendian.h\"\n#include \"warnp.h\"\n\n#include \"crypto_scrypt.h\"\n#include \"memlimit.h\"\n#include \"scryptenc_cpuperf.h\"\n\n#include \"scryptenc.h\"\n\n#define ENCBLOCK 65536\n\nstatic int pickparams(size_t, double, double,\n    int *, uint32_t *, uint32_t *, int);\nstatic int checkparams(size_t, double, double, int, uint32_t, uint32_t, int,\n    int);\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nstatic int scryptdec_file_load_header(FILE * infile, uint8_t header[static 96]);\n#else\nstatic int scryptdec_file_load_header(FILE *, uint8_t[static 96]);\n#endif\n\nstruct scryptdec_file_cookie {\n\tFILE *\tinfile;\t\t/* This is not owned by this cookie. */\n\tuint8_t\theader[96];\n\tuint8_t\tdk[64];\n};\n\nstatic void\ndisplay_params(int logN, uint32_t r, uint32_t p, size_t memlimit,\n    double opps, double maxtime)\n{\n\tuint64_t N = (uint64_t)(1) << logN;\n\tuint64_t mem_minimum = 128 * r * N;\n\tdouble expected_seconds = opps > 0 ? (double)(4 * N * r * p) / opps : 0;\n\tchar * human_memlimit = humansize(memlimit);\n\tchar * human_mem_minimum = humansize(mem_minimum);\n\n\t/* Parameters */\n\tfprintf(stderr, \"Parameters used: N = %\" PRIu64 \"; r = %\" PRIu32\n\t    \"; p = %\" PRIu32 \";\\n\", N, r, p);\n\n\t/* Memory */\n\tfprintf(stderr, \"    Decrypting this file requires at least\"\n\t    \" %s of memory\", human_mem_minimum);\n\tif (memlimit > 0)\n\t\tfprintf(stderr, \" (%s available)\", human_memlimit);\n\n\t/* CPU time */\n\tif (opps > 0)\n\t\tfprintf(stderr, \",\\n    and will take approximately %.1f \"\n\t\t    \"seconds (limit: %.1f seconds)\", expected_seconds, maxtime);\n\tfprintf(stderr, \".\\n\");\n\n\t/* Clean up */\n\tfree(human_memlimit);\n\tfree(human_mem_minimum);\n}\n\nstatic int\npickparams(size_t maxmem, double maxmemfrac, double maxtime,\n    int * logN, uint32_t * r, uint32_t * p, int verbose)\n{\n\tsize_t memlimit;\n\tdouble opps;\n\tdouble opslimit;\n\tdouble maxN, maxrp;\n\tuint64_t checkN;\n\tint rc;\n\n\t/* Figure out how much memory to use. */\n\tif (memtouse(maxmem, maxmemfrac, &memlimit))\n\t\treturn (SCRYPT_ELIMIT);\n\n\t/* Figure out how fast the CPU is. */\n\tif ((rc = scryptenc_cpuperf(&opps)) != SCRYPT_OK)\n\t\treturn (rc);\n\topslimit = opps * maxtime;\n\n\t/* Allow a minimum of 2^15 salsa20/8 cores. */\n\tif (opslimit < 32768)\n\t\topslimit = 32768;\n\n\t/* Fix r = 8 for now. */\n\t*r = 8;\n\n\t/*\n\t * The memory limit requires that 128Nr <= memlimit, while the CPU\n\t * limit requires that 4Nrp <= opslimit.  If opslimit < memlimit/32,\n\t * opslimit imposes the stronger limit on N.\n\t */\n#ifdef DEBUG\n\tfprintf(stderr, \"Requiring 128Nr <= %zu, 4Nrp <= %f\\n\",\n\t    memlimit, opslimit);\n#endif\n\tif (opslimit < (double)memlimit / 32) {\n\t\t/* Set p = 1 and choose N based on the CPU limit. */\n\t\t*p = 1;\n\t\tmaxN = opslimit / (*r * 4);\n\t\tfor (*logN = 1; *logN < 63; *logN += 1) {\n\t\t\tcheckN = (uint64_t)(1) << *logN;\n\n\t\t\t/*\n\t\t\t * Find the largest power of two <= maxN, which is\n\t\t\t * also the least power of two > maxN/2.\n\t\t\t */\n\t\t\tif ((double)checkN > maxN / 2)\n\t\t\t\tbreak;\n\t\t}\n\t} else {\n\t\t/* Set N based on the memory limit. */\n\t\tmaxN = (double)(memlimit / (*r * 128));\n\t\tfor (*logN = 1; *logN < 63; *logN += 1) {\n\t\t\tcheckN = (uint64_t)(1) << *logN;\n\t\t\tif ((double)checkN > maxN / 2)\n\t\t\t\tbreak;\n\t\t}\n\n\t\t/* Choose p based on the CPU limit. */\n\t\tcheckN = (uint64_t)(1) << *logN;\n\t\tmaxrp = (opslimit / 4) / (double)checkN;\n\t\tif (maxrp > 0x3fffffff)\n\t\t\tmaxrp = 0x3fffffff;\n\t\t*p = (uint32_t)(maxrp) / *r;\n\t}\n\n\tif (verbose)\n\t\tdisplay_params(*logN, *r, *p, memlimit, opps, maxtime);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n}\n\nstatic int\ncheckparams(size_t maxmem, double maxmemfrac, double maxtime,\n    int logN, uint32_t r, uint32_t p, int verbose, int force)\n{\n\tsize_t memlimit;\n\tdouble opps;\n\tdouble opslimit;\n\tuint64_t N;\n\tint rc;\n\n\t/* Sanity-check values. */\n\tif ((logN < 1) || (logN > 63))\n\t\treturn (SCRYPT_EINVAL);\n\tif ((uint64_t)(r) * (uint64_t)(p) >= 0x40000000)\n\t\treturn (SCRYPT_EINVAL);\n\tif ((r == 0) || (p == 0))\n\t\treturn (SCRYPT_EINVAL);\n\n\t/* Are we forcing decryption, regardless of resource limits? */\n\tif (!force) {\n\t\t/* Figure out the maximum amount of memory we can use. */\n\t\tif (memtouse(maxmem, maxmemfrac, &memlimit))\n\t\t\treturn (SCRYPT_ELIMIT);\n\n\t\t/* Figure out how fast the CPU is. */\n\t\tif ((rc = scryptenc_cpuperf(&opps)) != SCRYPT_OK)\n\t\t\treturn (rc);\n\t\topslimit = opps * maxtime;\n\n\t\tif (verbose)\n\t\t\tdisplay_params(logN, r, p, memlimit, opps, maxtime);\n\n\t\t/* Check limits. */\n\t\tN = (uint64_t)(1) << logN;\n\t\tif (((memlimit / N) / r < 128) &&\n\t\t    (((opslimit / (double)N) / r) / p < 4))\n\t\t\treturn (SCRYPT_EBIGSLOW);\n\t\tif ((memlimit / N) / r < 128)\n\t\t\treturn (SCRYPT_ETOOBIG);\n\t\tif (((opslimit / (double)N) / r) / p < 4)\n\t\t\treturn (SCRYPT_ETOOSLOW);\n\t} else {\n\t\t/* We have no limit. */\n\t\tmemlimit = 0;\n\t\topps = 0;\n\n\t\tif (verbose)\n\t\t\tdisplay_params(logN, r, p, memlimit, opps, maxtime);\n\t}\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n}\n\n/*\n * NOTE: The caller is responsible for sanitizing ${dk}, including if this\n * function fails.\n */\nstatic int\nscryptenc_setup(uint8_t header[96], uint8_t dk[64],\n    const uint8_t * passwd, size_t passwdlen,\n    struct scryptenc_params * P, int verbose, int force)\n{\n\tuint8_t salt[32];\n\tuint8_t hbuf[32];\n\tuint64_t N;\n\tSHA256_CTX ctx;\n\tuint8_t * key_hmac = &dk[32];\n\tHMAC_SHA256_CTX hctx;\n\tint rc;\n\n\t/* Determine parameters. */\n\tif (P->logN != 0) {\n\t\t/* Check logN, r, p. */\n\t\tif ((rc = checkparams(P->maxmem, P->maxmemfrac, P->maxtime,\n\t\t    P->logN, P->r, P->p, verbose, force)) != 0) {\n\t\t\t/* Warn about resource limit, but suppress the error. */\n\t\t\tif ((rc == SCRYPT_ETOOBIG) || (rc == SCRYPT_EBIGSLOW))\n\t\t\t\twarn0(\"Warning: Explicit parameters\"\n\t\t\t\t    \" might exceed memory limit\");\n\t\t\tif ((rc == SCRYPT_ETOOSLOW) || (rc == SCRYPT_EBIGSLOW))\n\t\t\t\twarn0(\"Warning: Explicit parameters\"\n\t\t\t\t    \" might exceed time limit\");\n\t\t\tif ((rc == SCRYPT_ETOOBIG) || (rc == SCRYPT_ETOOSLOW) ||\n\t\t\t    (rc == SCRYPT_EBIGSLOW))\n\t\t\t\trc = 0;\n\n\t\t\t/* Provide a more meaningful error message. */\n\t\t\tif (rc == SCRYPT_EINVAL)\n\t\t\t\trc = SCRYPT_EPARAM;\n\n\t\t\t/* Bail if we haven't suppressed the error. */\n\t\t\tif (rc != 0)\n\t\t\t\treturn (rc);\n\t\t}\n\t} else {\n\t\t/* Pick values for N, r, p. */\n\t\tif ((rc = pickparams(P->maxmem, P->maxmemfrac, P->maxtime,\n\t\t    &P->logN, &P->r, &P->p, verbose)) != 0)\n\t\t\treturn (rc);\n\t}\n\n\t/* Sanity check. */\n\tassert((P->logN > 0) && (P->logN < 64));\n\n\t/* Set N. */\n\tN = (uint64_t)(1) << P->logN;\n\n\t/* Get some salt. */\n\tif (crypto_entropy_read(salt, 32))\n\t\treturn (SCRYPT_ESALT);\n\n\t/* Generate the derived keys. */\n\tif (crypto_scrypt(passwd, passwdlen, salt, 32, N, P->r, P->p, dk, 64))\n\t\treturn (SCRYPT_EKEY);\n\n\t/* Construct the file header. */\n\tmemcpy(header, \"scrypt\", 6);\n\theader[6] = 0;\n\theader[7] = P->logN & 0xff;\n\tbe32enc(&header[8], P->r);\n\tbe32enc(&header[12], P->p);\n\tmemcpy(&header[16], salt, 32);\n\n\t/* Add header checksum. */\n\tSHA256_Init(&ctx);\n\tSHA256_Update(&ctx, header, 48);\n\tSHA256_Final(hbuf, &ctx);\n\tmemcpy(&header[48], hbuf, 16);\n\n\t/* Add header signature (used for verifying password). */\n\tHMAC_SHA256_Init(&hctx, key_hmac, 32);\n\tHMAC_SHA256_Update(&hctx, header, 64);\n\tHMAC_SHA256_Final(hbuf, &hctx);\n\tmemcpy(&header[64], hbuf, 32);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n}\n\n/**\n * scryptdec_file_printparams(infile):\n * Print the encryption parameters (N, r, p) used for the encrypted ${infile}.\n */\nint\nscryptdec_file_printparams(FILE * infile)\n{\n\tuint8_t header[96];\n\tint logN;\n\tuint32_t r;\n\tuint32_t p;\n\tint rc;\n\n\t/* Load the header. */\n\tif ((rc = scryptdec_file_load_header(infile, header)) != 0)\n\t\tgoto err0;\n\n\t/* Parse N, r, p. */\n\tlogN = header[7];\n\tr = be32dec(&header[8]);\n\tp = be32dec(&header[12]);\n\n\t/* Print parameters. */\n\tdisplay_params(logN, r, p, 0, 0, 0);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr0:\n\t/* Failure! */\n\treturn (rc);\n}\n\n/*\n * NOTE: The caller is responsible for sanitizing ${dk}, including if this\n * function fails.\n */\nstatic int\nscryptdec_setup(const uint8_t header[96], uint8_t dk[64],\n    const uint8_t * passwd, size_t passwdlen,\n    struct scryptenc_params * P, int verbose,\n    int force)\n{\n\tuint8_t salt[32];\n\tuint8_t hbuf[32];\n\tuint64_t N;\n\tSHA256_CTX ctx;\n\tuint8_t * key_hmac = &dk[32];\n\tHMAC_SHA256_CTX hctx;\n\tint rc;\n\n\t/* Parse N, r, p, salt. */\n\tP->logN = header[7];\n\tP->r = be32dec(&header[8]);\n\tP->p = be32dec(&header[12]);\n\tmemcpy(salt, &header[16], 32);\n\n\t/* Verify header checksum. */\n\tSHA256_Init(&ctx);\n\tSHA256_Update(&ctx, header, 48);\n\tSHA256_Final(hbuf, &ctx);\n\tif (crypto_verify_bytes(&header[48], hbuf, 16))\n\t\treturn (SCRYPT_EINVAL);\n\n\t/*\n\t * Check whether the provided parameters are valid and whether the\n\t * key derivation function can be computed within the allowed memory\n\t * and CPU time, unless the user chose to disable this test.\n\t */\n\tif ((rc = checkparams(P->maxmem, P->maxmemfrac, P->maxtime, P->logN,\n\t    P->r, P->p, verbose, force)) != 0)\n\t\treturn (rc);\n\n\t/* Compute the derived keys. */\n\tN = (uint64_t)(1) << P->logN;\n\tif (crypto_scrypt(passwd, passwdlen, salt, 32, N, P->r, P->p, dk, 64))\n\t\treturn (SCRYPT_EKEY);\n\n\t/* Check header signature (i.e., verify password). */\n\tHMAC_SHA256_Init(&hctx, key_hmac, 32);\n\tHMAC_SHA256_Update(&hctx, header, 64);\n\tHMAC_SHA256_Final(hbuf, &hctx);\n\tif (crypto_verify_bytes(hbuf, &header[64], 32))\n\t\treturn (SCRYPT_EPASS);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n}\n\n/**\n * scryptenc_buf(inbuf, inbuflen, outbuf, passwd, passwdlen,\n *     params, verbose, force):\n * Encrypt ${inbuflen} bytes from ${inbuf}, writing the resulting\n * ${inbuflen} + 128 bytes to ${outbuf}.  If ${force} is 1, do not check\n * whether decryption will exceed the estimated available memory or time.\n * The explicit parameters within ${params} must be zero or must all be\n * non-zero.  If explicit parameters are used and the computation is estimated\n * to exceed resource limits, print a warning instead of returning an error.\n * Return the explicit parameters used via ${params}.\n */\nint\nscryptenc_buf(const uint8_t * inbuf, size_t inbuflen, uint8_t * outbuf,\n    const uint8_t * passwd, size_t passwdlen,\n    struct scryptenc_params * P, int verbose, int force)\n{\n\tuint8_t dk[64];\n\tuint8_t hbuf[32];\n\tuint8_t header[96];\n\tuint8_t * key_enc = dk;\n\tuint8_t * key_hmac = &dk[32];\n\tint rc;\n\tHMAC_SHA256_CTX hctx;\n\tstruct crypto_aes_key * key_enc_exp;\n\tstruct crypto_aesctr * AES;\n\n\t/* The explicit parameters must be zero, or all non-zero. */\n\tassert(((P->logN == 0) && (P->r == 0) && (P->p == 0)) ||\n\t    ((P->logN != 0) && (P->r != 0) && (P->p != 0)));\n\n\t/* Generate the header and derived key. */\n\tif ((rc = scryptenc_setup(header, dk, passwd, passwdlen,\n\t    P, verbose, force)) != 0)\n\t\tgoto err1;\n\n\t/* Copy header into output buffer. */\n\tmemcpy(outbuf, header, 96);\n\n\t/* Encrypt data. */\n\tif ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {\n\t\trc = SCRYPT_EOPENSSL;\n\t\tgoto err1;\n\t}\n\tif ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {\n\t\tcrypto_aes_key_free(key_enc_exp);\n\t\trc = SCRYPT_ENOMEM;\n\t\tgoto err1;\n\t}\n\tcrypto_aesctr_stream(AES, inbuf, &outbuf[96], inbuflen);\n\tcrypto_aesctr_free(AES);\n\tcrypto_aes_key_free(key_enc_exp);\n\n\t/* Add signature. */\n\tHMAC_SHA256_Init(&hctx, key_hmac, 32);\n\tHMAC_SHA256_Update(&hctx, outbuf, 96 + inbuflen);\n\tHMAC_SHA256_Final(hbuf, &hctx);\n\tmemcpy(&outbuf[96 + inbuflen], hbuf, 32);\n\n\t/* Zero sensitive data. */\n\tinsecure_memzero(dk, 64);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr1:\n\tinsecure_memzero(dk, 64);\n\n\t/* Failure! */\n\treturn (rc);\n}\n\n/**\n * scryptdec_buf(inbuf, inbuflen, outbuf, outlen, passwd, passwdlen,\n *     params, verbose, force):\n * Decrypt ${inbuflen} bytes from ${inbuf}, writing the result into ${outbuf}\n * and the decrypted data length to ${outlen}.  The allocated length of\n * ${outbuf} must be at least ${inbuflen}.  If ${force} is 1, do not check\n * whether decryption will exceed the estimated available memory or time.\n * The explicit parameters within ${params} must be zero.  Return the explicit\n * parameters used via ${params}.\n */\nint\nscryptdec_buf(const uint8_t * inbuf, size_t inbuflen, uint8_t * outbuf,\n    size_t * outlen, const uint8_t * passwd, size_t passwdlen,\n    struct scryptenc_params * P, int verbose,\n    int force)\n{\n\tuint8_t hbuf[32];\n\tuint8_t dk[64];\n\tuint8_t * key_enc = dk;\n\tuint8_t * key_hmac = &dk[32];\n\tint rc;\n\tHMAC_SHA256_CTX hctx;\n\tstruct crypto_aes_key * key_enc_exp;\n\tstruct crypto_aesctr * AES;\n\n\t/* The explicit parameters must be zero. */\n\tassert((P->logN == 0) && (P->r == 0) && (P->p == 0));\n\n\t/*\n\t * All versions of the scrypt format will start with \"scrypt\" and\n\t * have at least 7 bytes of header.\n\t */\n\tif ((inbuflen < 7) || (memcmp(inbuf, \"scrypt\", 6) != 0)) {\n\t\trc = SCRYPT_EINVAL;\n\t\tgoto err0;\n\t}\n\n\t/* Check the format. */\n\tif (inbuf[6] != 0) {\n\t\trc = SCRYPT_EVERSION;\n\t\tgoto err0;\n\t}\n\n\t/* We must have at least 128 bytes. */\n\tif (inbuflen < 128) {\n\t\trc = SCRYPT_EINVAL;\n\t\tgoto err0;\n\t}\n\n\t/* Parse the header and generate derived keys. */\n\tif ((rc = scryptdec_setup(inbuf, dk, passwd, passwdlen,\n\t    P, verbose, force)) != 0)\n\t\tgoto err1;\n\n\t/* Decrypt data. */\n\tif ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {\n\t\trc = SCRYPT_EOPENSSL;\n\t\tgoto err1;\n\t}\n\tif ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {\n\t\tcrypto_aes_key_free(key_enc_exp);\n\t\trc = SCRYPT_ENOMEM;\n\t\tgoto err1;\n\t}\n\tcrypto_aesctr_stream(AES, &inbuf[96], outbuf, inbuflen - 128);\n\tcrypto_aesctr_free(AES);\n\tcrypto_aes_key_free(key_enc_exp);\n\t*outlen = inbuflen - 128;\n\n\t/* Verify signature. */\n\tHMAC_SHA256_Init(&hctx, key_hmac, 32);\n\tHMAC_SHA256_Update(&hctx, inbuf, inbuflen - 32);\n\tHMAC_SHA256_Final(hbuf, &hctx);\n\tif (crypto_verify_bytes(hbuf, &inbuf[inbuflen - 32], 32)) {\n\t\trc = SCRYPT_EINVAL;\n\t\tgoto err1;\n\t}\n\n\t/* Zero sensitive data. */\n\tinsecure_memzero(dk, 64);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr1:\n\tinsecure_memzero(dk, 64);\nerr0:\n\t/* Failure! */\n\treturn (rc);\n}\n\n/**\n * scryptenc_file(infile, outfile, passwd, passwdlen, params, verbose, force):\n * Read a stream from ${infile} and encrypt it, writing the resulting stream\n * to ${outfile}.  If ${force} is 1, do not check whether decryption will\n * exceed the estimated available memory or time.  The explicit parameters\n * within ${params} must be zero or must all be non-zero.  If explicit\n * parameters are used and the computation is estimated to exceed resource\n * limits, print a warning instead of returning an error.  Return the explicit\n * parameters used via ${params}.\n */\nint\nscryptenc_file(FILE * infile, FILE * outfile,\n    const uint8_t * passwd, size_t passwdlen,\n    struct scryptenc_params * P, int verbose, int force)\n{\n\tuint8_t buf[ENCBLOCK];\n\tuint8_t dk[64];\n\tuint8_t hbuf[32];\n\tuint8_t header[96];\n\tuint8_t * key_enc = dk;\n\tuint8_t * key_hmac = &dk[32];\n\tsize_t readlen;\n\tHMAC_SHA256_CTX hctx;\n\tstruct crypto_aes_key * key_enc_exp;\n\tstruct crypto_aesctr * AES;\n\tint rc;\n\n\t/* The explicit parameters must be zero, or all non-zero. */\n\tassert(((P->logN == 0) && (P->r == 0) && (P->p == 0)) ||\n\t    ((P->logN != 0) && (P->r != 0) && (P->p != 0)));\n\n\t/* Generate the header and derived key. */\n\tif ((rc = scryptenc_setup(header, dk, passwd, passwdlen,\n\t    P, verbose, force)) != 0)\n\t\tgoto err1;\n\n\t/* Hash and write the header. */\n\tHMAC_SHA256_Init(&hctx, key_hmac, 32);\n\tHMAC_SHA256_Update(&hctx, header, 96);\n\tif (fwrite(header, 96, 1, outfile) != 1) {\n\t\trc = SCRYPT_EWRFILE;\n\t\tgoto err1;\n\t}\n\n\t/*\n\t * Read blocks of data, encrypt them, and write them out; hash the\n\t * data as it is produced.\n\t */\n\tif ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {\n\t\trc = SCRYPT_EOPENSSL;\n\t\tgoto err1;\n\t}\n\tif ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {\n\t\tcrypto_aes_key_free(key_enc_exp);\n\t\trc = SCRYPT_ENOMEM;\n\t\tgoto err1;\n\t}\n\tdo {\n\t\tif ((readlen = fread(buf, 1, ENCBLOCK, infile)) == 0)\n\t\t\tbreak;\n\t\tcrypto_aesctr_stream(AES, buf, buf, readlen);\n\t\tHMAC_SHA256_Update(&hctx, buf, readlen);\n\t\tif (fwrite(buf, 1, readlen, outfile) < readlen) {\n\t\t\tcrypto_aesctr_free(AES);\n\t\t\trc = SCRYPT_EWRFILE;\n\t\t\tgoto err1;\n\t\t}\n\t} while (1);\n\tcrypto_aesctr_free(AES);\n\tcrypto_aes_key_free(key_enc_exp);\n\n\t/* Did we exit the loop due to a read error? */\n\tif (ferror(infile)) {\n\t\trc = SCRYPT_ERDFILE;\n\t\tgoto err1;\n\t}\n\n\t/* Compute the final HMAC and output it. */\n\tHMAC_SHA256_Final(hbuf, &hctx);\n\tif (fwrite(hbuf, 32, 1, outfile) != 1) {\n\t\trc = SCRYPT_EWRFILE;\n\t\tgoto err1;\n\t}\n\n\t/* Zero sensitive data. */\n\tinsecure_memzero(dk, 64);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr1:\n\tinsecure_memzero(dk, 64);\n\n\t/* Failure! */\n\treturn (rc);\n}\n\n/**\n * scryptdec_file_cookie_free(cookie):\n * Free the ${cookie}.\n */\nvoid\nscryptdec_file_cookie_free(struct scryptdec_file_cookie * C)\n{\n\n\t/* Behave consistently with free(NULL). */\n\tif (C == NULL)\n\t\treturn;\n\n\t/* Zero sensitive data. */\n\tinsecure_memzero(C->dk, 64);\n\n\t/* We do not free C->infile because it is not owned by this cookie. */\n\n\t/* Free the cookie. */\n\tfree(C);\n}\n\n/* Load the header and check the magic. */\nstatic int\nscryptdec_file_load_header(FILE * infile, uint8_t header[static 96])\n{\n\tint rc;\n\n\t/*\n\t * Read the first 7 bytes of the file; all future versions of scrypt\n\t * are guaranteed to have at least 7 bytes of header.\n\t */\n\tif (fread(header, 7, 1, infile) < 1) {\n\t\tif (ferror(infile)) {\n\t\t\trc = SCRYPT_ERDFILE;\n\t\t\tgoto err0;\n\t\t} else {\n\t\t\trc = SCRYPT_EINVAL;\n\t\t\tgoto err0;\n\t\t}\n\t}\n\n\t/* Do we have the right magic? */\n\tif (memcmp(header, \"scrypt\", 6)) {\n\t\trc = SCRYPT_EINVAL;\n\t\tgoto err0;\n\t}\n\tif (header[6] != 0) {\n\t\trc = SCRYPT_EVERSION;\n\t\tgoto err0;\n\t}\n\n\t/*\n\t * Read another 89 bytes of the file; version 0 of the scrypt file\n\t * format has a 96-byte header.\n\t */\n\tif (fread(&header[7], 89, 1, infile) < 1) {\n\t\tif (ferror(infile)) {\n\t\t\trc = SCRYPT_ERDFILE;\n\t\t\tgoto err0;\n\t\t} else {\n\t\t\trc = SCRYPT_EINVAL;\n\t\t\tgoto err0;\n\t\t}\n\t}\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr0:\n\t/* Failure! */\n\treturn (rc);\n}\n\n/**\n * scryptdec_file_prep(infile, passwd, passwdlen, params, verbose, force,\n *     cookie):\n * Prepare to decrypt ${infile}, including checking the passphrase.  Allocate\n * a cookie at ${cookie}.  After calling this function, ${infile} should not\n * be modified until the decryption is completed by scryptdec_file_copy().\n * If ${force} is 1, do not check whether decryption will exceed the estimated\n * available memory or time.  The explicit parameters within ${params} must be\n * zero.  Return the explicit parameters to be used via ${params}.\n */\nint\nscryptdec_file_prep(FILE * infile, const uint8_t * passwd,\n    size_t passwdlen, struct scryptenc_params * P,\n    int verbose, int force, struct scryptdec_file_cookie ** cookie)\n{\n\tstruct scryptdec_file_cookie * C;\n\tint rc;\n\n\t/* The explicit parameters must be zero. */\n\tassert((P->logN == 0) && (P->r == 0) && (P->p == 0));\n\n\t/* Allocate the cookie. */\n\tif ((C = malloc(sizeof(struct scryptdec_file_cookie))) == NULL)\n\t\treturn (SCRYPT_ENOMEM);\n\tC->infile = infile;\n\n\t/* Load the header. */\n\tif ((rc = scryptdec_file_load_header(infile, C->header)) != 0)\n\t\tgoto err1;\n\n\t/* Parse the header and generate derived keys. */\n\tif ((rc = scryptdec_setup(C->header, C->dk, passwd, passwdlen,\n\t    P, verbose, force)) != 0)\n\t\tgoto err1;\n\n\t/* Set cookie for calling function. */\n\t*cookie = C;\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr1:\n\tscryptdec_file_cookie_free(C);\n\n\t/* Failure! */\n\treturn (rc);\n}\n\n/**\n * scryptdec_file_copy(cookie, outfile):\n * Read a stream from the file that was passed into the ${cookie} by\n * scryptdec_file_prep(), decrypt it, and write the resulting stream to\n * ${outfile}.  After this function completes, it is safe to modify/close\n * ${outfile} and the ${infile} which was given to scryptdec_file_prep().\n */\nint\nscryptdec_file_copy(struct scryptdec_file_cookie * C, FILE * outfile)\n{\n\tuint8_t buf[ENCBLOCK + 32];\n\tuint8_t hbuf[32];\n\tuint8_t * key_enc;\n\tuint8_t * key_hmac;\n\tsize_t buflen = 0;\n\tsize_t readlen;\n\tHMAC_SHA256_CTX hctx;\n\tstruct crypto_aes_key * key_enc_exp;\n\tstruct crypto_aesctr * AES;\n\tint rc;\n\n\t/* Sanity check. */\n\tassert(C != NULL);\n\n\t/* Use existing array for these pointers. */\n\tkey_enc = C->dk;\n\tkey_hmac = &C->dk[32];\n\n\t/* Start hashing with the header. */\n\tHMAC_SHA256_Init(&hctx, key_hmac, 32);\n\tHMAC_SHA256_Update(&hctx, C->header, 96);\n\n\t/*\n\t * We don't know how long the encrypted data block is (we can't know,\n\t * since data can be streamed into 'scrypt enc') so we need to read\n\t * data and decrypt all of it except the final 32 bytes, then check\n\t * if that final 32 bytes is the correct signature.\n\t */\n\tif ((key_enc_exp = crypto_aes_key_expand(key_enc, 32)) == NULL) {\n\t\trc = SCRYPT_EOPENSSL;\n\t\tgoto err0;\n\t}\n\tif ((AES = crypto_aesctr_init(key_enc_exp, 0)) == NULL) {\n\t\tcrypto_aes_key_free(key_enc_exp);\n\t\trc = SCRYPT_ENOMEM;\n\t\tgoto err0;\n\t}\n\tdo {\n\t\t/* Read data until we have more than 32 bytes of it. */\n\t\tif ((readlen = fread(&buf[buflen], 1,\n\t\t    ENCBLOCK + 32 - buflen, C->infile)) == 0)\n\t\t\tbreak;\n\t\tbuflen += readlen;\n\t\tif (buflen <= 32)\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * Decrypt, hash, and output everything except the last 32\n\t\t * bytes out of what we have in our buffer.\n\t\t */\n\t\tHMAC_SHA256_Update(&hctx, buf, buflen - 32);\n\t\tcrypto_aesctr_stream(AES, buf, buf, buflen - 32);\n\t\tif (fwrite(buf, 1, buflen - 32, outfile) < buflen - 32) {\n\t\t\tcrypto_aesctr_free(AES);\n\t\t\trc = SCRYPT_EWRFILE;\n\t\t\tgoto err0;\n\t\t}\n\n\t\t/* Move the last 32 bytes to the start of the buffer. */\n\t\tmemmove(buf, &buf[buflen - 32], 32);\n\t\tbuflen = 32;\n\t} while (1);\n\tcrypto_aesctr_free(AES);\n\tcrypto_aes_key_free(key_enc_exp);\n\n\t/* Did we exit the loop due to a read error? */\n\tif (ferror(C->infile)) {\n\t\trc = SCRYPT_ERDFILE;\n\t\tgoto err0;\n\t}\n\n\t/* Did we read enough data that we *might* have a valid signature? */\n\tif (buflen < 32) {\n\t\trc = SCRYPT_EINVAL;\n\t\tgoto err0;\n\t}\n\n\t/* Verify signature. */\n\tHMAC_SHA256_Final(hbuf, &hctx);\n\tif (crypto_verify_bytes(hbuf, buf, 32)) {\n\t\trc = SCRYPT_EINVAL;\n\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr0:\n\t/* Failure! */\n\treturn (rc);\n}\n\n/**\n * scryptdec_file(infile, outfile, passwd, passwdlen, params, verbose, force):\n * Read a stream from ${infile} and decrypt it, writing the resulting stream\n * to ${outfile}.  If ${force} is 1, do not check whether decryption\n * will exceed the estimated available memory or time.  The explicit\n * parameters within ${params} must be zero.  Return the explicit parameters\n * used via ${params}.\n */\nint\nscryptdec_file(FILE * infile, FILE * outfile, const uint8_t * passwd,\n    size_t passwdlen, struct scryptenc_params * P,\n    int verbose, int force)\n{\n\tstruct scryptdec_file_cookie * C;\n\tint rc;\n\n\t/* The explicit parameters must be zero. */\n\tassert((P->logN == 0) && (P->r == 0) && (P->p == 0));\n\n\t/* Check header, including passphrase. */\n\tif ((rc = scryptdec_file_prep(infile, passwd, passwdlen, P,\n\t    verbose, force, &C)) != 0)\n\t\tgoto err0;\n\n\t/* Copy unencrypted data to outfile. */\n\tif ((rc = scryptdec_file_copy(C, outfile)) != 0)\n\t\tgoto err1;\n\n\t/* Clean up cookie, attempting to zero sensitive data. */\n\tscryptdec_file_cookie_free(C);\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n\nerr1:\n\tscryptdec_file_cookie_free(C);\nerr0:\n\t/* Failure! */\n\treturn (rc);\n}\n"
  },
  {
    "path": "lib/scryptenc/scryptenc.h",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#ifndef SCRYPTENC_H_\n#define SCRYPTENC_H_\n\n#include <stdint.h>\n#include <stdio.h>\n\n/**\n * NOTE: This file provides prototypes for routines which encrypt/decrypt data\n * using a key derived from a password by using the scrypt key derivation\n * function.  If you are just trying to \"hash\" a password for user logins,\n * this is not the code you are looking for.  You want to use the\n * crypto_scrypt() function directly.\n */\n\n/**\n * The parameters maxmem, maxmemfrac, and maxtime used by all of these\n * functions are defined as follows:\n * maxmem - maximum number of bytes of storage to use for V array (which is\n *     by far the largest consumer of memory).  If this value is set to 0, no\n *     maximum will be enforced; any other value less than 1 MiB will be\n *     treated as 1 MiB.\n * maxmemfrac - maximum fraction of available storage to use for the V array,\n *     where \"available storage\" is defined as the minimum out of the\n *     RLIMIT_AS, RLIMIT_DATA. and RLIMIT_RSS resource limits (if any are\n *     set).  This value will never cause a limit of less than 1 MiB to\n *     be enforced.\n * maxtime - maximum amount of CPU time to spend computing the derived keys,\n *     in seconds.  This limit is only approximately enforced; the CPU\n *     performance is estimated and parameter limits are chosen accordingly.\n * For the encryption functions, the parameters to the scrypt key derivation\n * function are chosen to make the key as strong as possible subject to the\n * specified limits; for the decryption functions, the parameters used are\n * compared to the computed limits and an error is returned if decrypting\n * the data would take too much memory or CPU time.\n */\nstruct scryptenc_params {\n\tsize_t maxmem;\n\tdouble maxmemfrac;\n\tdouble maxtime;\n\n\t/* Explicit parameters. */\n\tint logN;\n\tuint32_t r;\n\tuint32_t p;\n};\n\n/* Return codes from scrypt(enc|dec)_(buf|file|prep). */\n#define SCRYPT_OK\t0\t/* success */\n#define SCRYPT_ELIMIT\t1\t/* getrlimit or sysctrl(hw.usermem) failed */\n#define SCRYPT_ECLOCK\t2\t/* clock_getres or clock_gettime failed */\n#define SCRYPT_EKEY\t3\t/* error computing derived key */\n#define SCRYPT_ESALT\t4\t/* could not read salt */\n#define SCRYPT_EOPENSSL\t5\t/* error in OpenSSL */\n#define SCRYPT_ENOMEM\t6\t/* malloc failed */\n#define SCRYPT_EINVAL\t7\t/* data is not a valid scrypt-encrypted block */\n#define SCRYPT_EVERSION\t8\t/* unrecognized scrypt version number */\n#define SCRYPT_ETOOBIG\t9\t/* decrypting would take too much memory */\n#define SCRYPT_ETOOSLOW\t10\t/* decrypting would take too long */\n#define SCRYPT_EPASS\t11\t/* password is incorrect */\n#define SCRYPT_EWRFILE\t12\t/* error writing output file */\n#define SCRYPT_ERDFILE\t13\t/* error reading input file */\n#define SCRYPT_EPARAM\t14\t/* error in explicit parameters */\n#define SCRYPT_EBIGSLOW 15\t/* both SCRYPT_ETOOBIG and SCRYPT_ETOOSLOW */\n\n/* Opaque structure. */\nstruct scryptdec_file_cookie;\n\n/**\n * scryptenc_buf(inbuf, inbuflen, outbuf, passwd, passwdlen,\n *     params, verbose, force):\n * Encrypt ${inbuflen} bytes from ${inbuf}, writing the resulting\n * ${inbuflen} + 128 bytes to ${outbuf}.  If ${force} is 1, do not check\n * whether decryption will exceed the estimated available memory or time.\n * The explicit parameters within ${params} must be zero or must all be\n * non-zero.  If explicit parameters are used and the computation is estimated\n * to exceed resource limits, print a warning instead of returning an error.\n * Return the explicit parameters used via ${params}.\n */\nint scryptenc_buf(const uint8_t *, size_t, uint8_t *,\n    const uint8_t *, size_t, struct scryptenc_params *, int, int);\n\n/**\n * scryptdec_buf(inbuf, inbuflen, outbuf, outlen, passwd, passwdlen,\n *     params, verbose, force):\n * Decrypt ${inbuflen} bytes from ${inbuf}, writing the result into ${outbuf}\n * and the decrypted data length to ${outlen}.  The allocated length of\n * ${outbuf} must be at least ${inbuflen}.  If ${force} is 1, do not check\n * whether decryption will exceed the estimated available memory or time.\n * The explicit parameters within ${params} must be zero.  Return the explicit\n * parameters used via ${params}.\n */\nint scryptdec_buf(const uint8_t *, size_t, uint8_t *, size_t *,\n    const uint8_t *, size_t, struct scryptenc_params *, int, int);\n\n/**\n * scryptenc_file(infile, outfile, passwd, passwdlen, params, verbose, force):\n * Read a stream from ${infile} and encrypt it, writing the resulting stream\n * to ${outfile}.  If ${force} is 1, do not check whether decryption will\n * exceed the estimated available memory or time.  The explicit parameters\n * within ${params} must be zero or must all be non-zero.  If explicit\n * parameters are used and the computation is estimated to exceed resource\n * limits, print a warning instead of returning an error.  Return the explicit\n * parameters used via ${params}.\n */\nint scryptenc_file(FILE *, FILE *, const uint8_t *, size_t,\n    struct scryptenc_params *, int, int);\n\n/**\n * scryptdec_file_printparams(infile):\n * Print the encryption parameters (N, r, p) used for the encrypted ${infile}.\n */\nint scryptdec_file_printparams(FILE *);\n\n/**\n * scryptdec_file(infile, outfile, passwd, passwdlen, params, verbose, force):\n * Read a stream from ${infile} and decrypt it, writing the resulting stream\n * to ${outfile}.  If ${force} is 1, do not check whether decryption\n * will exceed the estimated available memory or time.  The explicit\n * parameters within ${params} must be zero.  Return the explicit parameters\n * used via ${params}.\n */\nint scryptdec_file(FILE *, FILE *, const uint8_t *, size_t,\n    struct scryptenc_params *, int, int);\n\n/**\n * scryptdec_file_prep(infile, passwd, passwdlen, params, verbose, force,\n *     cookie):\n * Prepare to decrypt ${infile}, including checking the passphrase.  Allocate\n * a cookie at ${cookie}.  After calling this function, ${infile} should not\n * be modified until the decryption is completed by scryptdec_file_copy().\n * If ${force} is 1, do not check whether decryption will exceed the estimated\n * available memory or time.  The explicit parameters within ${params} must be\n * zero.  Return the explicit parameters to be used via ${params}.\n */\nint scryptdec_file_prep(FILE *, const uint8_t *, size_t,\n    struct scryptenc_params *, int, int, struct scryptdec_file_cookie **);\n\n/**\n * scryptdec_file_copy(cookie, outfile):\n * Read a stream from the file that was passed into the ${cookie} by\n * scryptdec_file_prep(), decrypt it, and write the resulting stream to\n * ${outfile}.  After this function completes, it is safe to modify/close\n * ${outfile} and the ${infile} which was given to scryptdec_file_prep().\n */\nint scryptdec_file_copy(struct scryptdec_file_cookie *, FILE *);\n\n/**\n * scryptdec_file_cookie_free(cookie):\n * Free the ${cookie}.\n */\nvoid scryptdec_file_cookie_free(struct scryptdec_file_cookie *);\n\n#endif /* !SCRYPTENC_H_ */\n"
  },
  {
    "path": "lib/scryptenc/scryptenc_cpuperf.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#include <sys/time.h>\n\n#include <stdint.h>\n#include <stdio.h>\n\n#include \"crypto_scrypt.h\"\n#include \"monoclock.h\"\n\n#include \"scryptenc.h\"\n#include \"scryptenc_cpuperf.h\"\n\nstatic int\ngetclockdiff(struct timeval * st, double * diffd)\n{\n\tstruct timeval en;\n\n\tif (monoclock_get(&en))\n\t\treturn (1);\n\t*diffd = timeval_diff((*st), en);\n\n\t/* Success! */\n\treturn (0);\n}\n\n/**\n * scryptenc_cpuperf(opps):\n * Estimate the number of salsa20/8 cores which can be executed per second,\n * and store the value in ${opps}.  Return a SCRYPT_* code.\n */\nint\nscryptenc_cpuperf(double * opps)\n{\n\tstruct timeval st;\n\tdouble resd, diffd;\n\tuint64_t i = 0;\n\n\t/* Get the clock resolution. */\n\tif (monoclock_getres(&resd))\n\t\treturn (SCRYPT_ECLOCK);\n\n#ifdef DEBUG\n\tfprintf(stderr, \"Clock resolution is %g\\n\", resd);\n#endif\n\n\t/* Loop until the clock ticks. */\n\tif (monoclock_get(&st))\n\t\treturn (SCRYPT_ECLOCK);\n\tdo {\n\t\t/* Do an scrypt. */\n\t\tif (crypto_scrypt(NULL, 0, NULL, 0, 16, 1, 1, NULL, 0))\n\t\t\treturn (SCRYPT_EKEY);\n\n\t\t/* Has the clock ticked? */\n\t\tif (getclockdiff(&st, &diffd))\n\t\t\treturn (SCRYPT_ECLOCK);\n\t\tif (diffd > 0)\n\t\t\tbreak;\n\t} while (1);\n\n\t/* Count how many scrypts we can do before the next tick. */\n\tif (monoclock_get(&st))\n\t\treturn (SCRYPT_ECLOCK);\n\tdo {\n\t\t/* Do an scrypt. */\n\t\tif (crypto_scrypt(NULL, 0, NULL, 0, 128, 1, 1, NULL, 0))\n\t\t\treturn (SCRYPT_EKEY);\n\n\t\t/* We invoked the salsa20/8 core 512 times. */\n\t\ti += 512;\n\n\t\t/* Check if we have looped for long enough. */\n\t\tif (getclockdiff(&st, &diffd))\n\t\t\treturn (SCRYPT_ECLOCK);\n\t\tif (diffd > resd)\n\t\t\tbreak;\n\t} while (1);\n\n#ifdef DEBUG\n\tfprintf(stderr, \"%ju salsa20/8 cores performed in %g seconds\\n\",\n\t    (uintmax_t)i, diffd);\n#endif\n\n\t/* We can do approximately i salsa20/8 cores per diffd seconds. */\n\t*opps = (double)i / diffd;\n\n\t/* Success! */\n\treturn (SCRYPT_OK);\n}\n"
  },
  {
    "path": "lib/scryptenc/scryptenc_cpuperf.h",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#ifndef SCRYPTENC_CPUPERF_H_\n#define SCRYPTENC_CPUPERF_H_\n\n/**\n * scryptenc_cpuperf(opps):\n * Estimate the number of salsa20/8 cores which can be executed per second,\n * and store the value in ${opps}.  Return a SCRYPT_* code.\n */\nint scryptenc_cpuperf(double *);\n\n#endif /* !SCRYPTENC_CPUPERF_H_ */\n"
  },
  {
    "path": "lib/scryptenc/scryptenc_print_error.c",
    "content": "#include <assert.h>\n#include <stddef.h>\n\n#include \"warnp.h\"\n\n#include \"scryptenc.h\"\n#include \"scryptenc_print_error.h\"\n\n/**\n * scryptenc_print_error(rc, infilename, outfilename):\n * Print the error corresponding to ${rc}.  If relevant, use ${infilename}\n * or ${outfilename} to display an error about reading or writing; these\n * arguments can be NULL to indicate standard input or output.\n */\nvoid\nscryptenc_print_error(int rc, const char * infilename,\n    const char * outfilename)\n{\n\n\t/* Sanity check: this should only be used for errors. */\n\tassert(rc != SCRYPT_OK);\n\n\t/* Display error. */\n\tswitch (rc) {\n\tcase SCRYPT_ELIMIT:\n\t\twarnp(\"Error determining amount of available memory\");\n\t\tbreak;\n\tcase SCRYPT_ECLOCK:\n\t\twarnp(\"Error reading clocks\");\n\t\tbreak;\n\tcase SCRYPT_EKEY:\n\t\twarnp(\"Error computing derived key\");\n\t\tbreak;\n\tcase SCRYPT_ESALT:\n\t\twarnp(\"Error reading salt\");\n\t\tbreak;\n\tcase SCRYPT_EOPENSSL:\n\t\twarnp(\"OpenSSL error\");\n\t\tbreak;\n\tcase SCRYPT_ENOMEM:\n\t\twarnp(\"Error allocating memory\");\n\t\tbreak;\n\tcase SCRYPT_EINVAL:\n\t\twarn0(\"Input is not valid scrypt-encrypted block\");\n\t\tbreak;\n\tcase SCRYPT_EVERSION:\n\t\twarn0(\"Unrecognized scrypt format version\");\n\t\tbreak;\n\tcase SCRYPT_ETOOBIG:\n\t\twarn0(\"Decrypting file would require too much memory\");\n\t\tbreak;\n\tcase SCRYPT_ETOOSLOW:\n\t\twarn0(\"Decrypting file would take too much CPU time\");\n\t\tbreak;\n\tcase SCRYPT_EBIGSLOW:\n\t\twarn0(\"Decrypting file would require too much memory\"\n\t\t    \" and CPU time\");\n\t\tbreak;\n\tcase SCRYPT_EPASS:\n\t\twarn0(\"Passphrase is incorrect\");\n\t\tbreak;\n\tcase SCRYPT_EWRFILE:\n\t\twarnp(\"Error writing file: %s\",\n\t\t    (outfilename != NULL) ? outfilename : \"standard output\");\n\t\tbreak;\n\tcase SCRYPT_ERDFILE:\n\t\twarnp(\"Error reading file: %s\",\n\t\t    (infilename != NULL) ? infilename : \"standard input\");\n\t\tbreak;\n\tcase SCRYPT_EPARAM:\n\t\twarn0(\"Error in explicit parameters\");\n\t\tbreak;\n\tdefault:\n\t\twarn0(\"Programmer error: unrecognized scrypt error\");\n\t\tbreak;\n\t}\n}\n"
  },
  {
    "path": "lib/scryptenc/scryptenc_print_error.h",
    "content": "#ifndef SCRYPTENC_PRINT_ERROR_H_\n#define SCRYPTENC_PRINT_ERROR_H_\n\n/**\n * scryptenc_print_error(rc, infilename, outfilename):\n * Print the error corresponding to ${rc}.  If relevant, use ${infilename}\n * or ${outfilename} to display an error about reading or writing; these\n * arguments can be NULL to indicate standard input or output.\n */\nvoid scryptenc_print_error(int, const char *, const char *);\n\n#endif /* !SCRYPTENC_PRINT_ERROR_H_ */\n"
  },
  {
    "path": "lib/util/passphrase_entry.c",
    "content": "#include <stdlib.h>\n#include <string.h>\n\n#include \"passphrase_entry.h\"\n#include \"readpass.h\"\n#include \"warnp.h\"\n\n/**\n * passphrase_entry_parse(arg, entry_method_p, entry_arg_p):\n * Parse \"METHOD:ARG\" from ${arg} into an ${*entry_method_p}:${*entry_arg_p}.\n */\nint\npassphrase_entry_parse(const char * arg,\n    enum passphrase_entry * passphrase_entry_p, const char ** passphrase_arg_p)\n{\n\tconst char * p;\n\n\t/* Find the separator in \"method:arg\", or fail if there isn't one. */\n\tif ((p = strchr(arg, ':')) == NULL)\n\t\tgoto err1;\n\n\t/* Extract the \"arg\" part. */\n\t*passphrase_arg_p = &p[1];\n\n\t/* Parse the \"method\". */\n\tif (strncmp(arg, \"dev:\", 4) == 0) {\n\t\tif (strcmp(*passphrase_arg_p, \"tty-stdin\") == 0) {\n\t\t\t*passphrase_entry_p = PASSPHRASE_TTY_STDIN;\n\t\t\tgoto success;\n\t\t}\n\t\telse if (strcmp(*passphrase_arg_p, \"stdin-once\") == 0) {\n\t\t\t*passphrase_entry_p = PASSPHRASE_STDIN_ONCE;\n\t\t\tgoto success;\n\t\t}\n\t\telse if (strcmp(*passphrase_arg_p, \"tty-once\") == 0) {\n\t\t\t*passphrase_entry_p = PASSPHRASE_TTY_ONCE;\n\t\t\tgoto success;\n\t\t}\n\t}\n\tif (strncmp(arg, \"env:\", 4) == 0) {\n\t\t*passphrase_entry_p = PASSPHRASE_ENV;\n\t\tgoto success;\n\t}\n\tif (strncmp(arg, \"file:\", 5) == 0) {\n\t\t*passphrase_entry_p = PASSPHRASE_FILE;\n\t\tgoto success;\n\t}\n\nerr1:\n\twarn0(\"Invalid option: --passphrase %s\", arg);\n\n\t/* Failure! */\n\treturn (-1);\n\nsuccess:\n\t/* Success! */\n\treturn (0);\n}\n\n/**\n * passphrase_entry_readpass(passwd, entry_method, entry_arg, prompt,\n *     confirmprompt, once):\n * Use ${entry_method} to read a passphrase and return it as a malloced\n * NUL-terminated string via ${passwd}.  If ${entry_method} is\n * PASSPHRASE_TTY_STDIN and ${once} is zero, ask for the passphrase twice;\n * otherwise ask for it once.  If reading from a terminal, use ${prompt} for\n * the first prompt, and ${confirmprompt} for the second prompt (if\n * applicable); otherwise do not print any prompts.\n */\nint\npassphrase_entry_readpass(char ** passwd,\n    enum passphrase_entry passphrase_entry, const char * passphrase_arg,\n    const char * prompt, const char * confirmprompt, int once)\n{\n\tconst char * passwd_env;\n\n\tswitch (passphrase_entry) {\n\tcase PASSPHRASE_TTY_STDIN:\n\t\t/* Read passphrase, prompting only once if decrypting. */\n\t\tif (readpass(passwd, prompt, (once) ? NULL : confirmprompt, 1))\n\t\t\tgoto err0;\n\t\tbreak;\n\tcase PASSPHRASE_STDIN_ONCE:\n\t\t/* Read passphrase, prompting only once, from stdin only. */\n\t\tif (readpass(passwd, prompt, NULL, 0))\n\t\t\tgoto err0;\n\t\tbreak;\n\tcase PASSPHRASE_TTY_ONCE:\n\t\t/* Read passphrase, prompting only once, from tty only. */\n\t\tif (readpass(passwd, prompt, NULL, 2))\n\t\t\tgoto err0;\n\t\tbreak;\n\tcase PASSPHRASE_ENV:\n\t\t/* We're not allowed to modify the output of getenv(). */\n\t\tif ((passwd_env = getenv(passphrase_arg)) == NULL) {\n\t\t\twarn0(\"Failed to read from ${%s}\", passphrase_arg);\n\t\t\tgoto err0;\n\t\t}\n\n\t\t/* This allows us to use the same insecure_zero() logic. */\n\t\tif ((*passwd = strdup(passwd_env)) == NULL) {\n\t\t\twarnp(\"Out of memory\");\n\t\t\tgoto err0;\n\t\t}\n\t\tbreak;\n\tcase PASSPHRASE_FILE:\n\t\tif (readpass_file(passwd, passphrase_arg))\n\t\t\tgoto err0;\n\t\tbreak;\n\tcase PASSPHRASE_UNSET:\n\t\twarn0(\"Programming error: passphrase_entry is not set\");\n\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n"
  },
  {
    "path": "lib/util/passphrase_entry.h",
    "content": "#ifndef PASSPHRASE_ENTRY_H_\n#define PASSPHRASE_ENTRY_H_\n\n/* How should we get the passphrase? */\nenum passphrase_entry {\n\tPASSPHRASE_UNSET,\n\tPASSPHRASE_TTY_STDIN,\n\tPASSPHRASE_STDIN_ONCE,\n\tPASSPHRASE_TTY_ONCE,\n\tPASSPHRASE_ENV,\n\tPASSPHRASE_FILE,\n};\n\n/**\n * passphrase_entry_parse(arg, entry_method_p, entry_arg_p):\n * Parse \"METHOD:ARG\" from ${arg} into an ${*entry_method_p}:${*entry_arg_p}.\n */\nint passphrase_entry_parse(const char *, enum passphrase_entry *,\n    const char **);\n\n/**\n * passphrase_entry_readpass(passwd, entry_method, entry_arg, prompt,\n *     confirmprompt, once):\n * Use ${entry_method} to read a passphrase and return it as a malloced\n * NUL-terminated string via ${passwd}.  If ${entry_method} is\n * PASSPHRASE_TTY_STDIN and ${once} is zero, ask for the passphrase twice;\n * otherwise ask for it once.  If reading from a terminal, use ${prompt} for\n * the first prompt, and ${confirmprompt} for the second prompt (if\n * applicable); otherwise do not print any prompts.\n */\nint passphrase_entry_readpass(char **, enum passphrase_entry, const char *,\n    const char *, const char *, int);\n\n#endif /* !PASSPHRASE_ENTRY_H_ */\n"
  },
  {
    "path": "lib-platform/crypto/crypto_scrypt.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#include \"platform.h\"\n\n#include <sys/types.h>\n#include <sys/mman.h>\n\n#include <errno.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"cpusupport.h\"\n#include \"sha256.h\"\n#include \"warnp.h\"\n\n#include \"crypto_scrypt_smix.h\"\n#include \"crypto_scrypt_smix_sse2.h\"\n\n#include \"crypto_scrypt.h\"\n\nstatic void (* smix_func)(uint8_t *, size_t, uint64_t, void *, void *) = NULL;\n\n/**\n * crypto_scrypt_internal(passwd, passwdlen, salt, saltlen, N, r, p, buf,\n *     buflen, smix):\n * Perform the requested scrypt computation, using ${smix} as the smix routine.\n */\nstatic int\ncrypto_scrypt_internal(const uint8_t * passwd, size_t passwdlen,\n    const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t _r, uint32_t _p,\n    uint8_t * buf, size_t buflen,\n    void (* smix)(uint8_t *, size_t, uint64_t, void *, void *))\n{\n\tvoid * B0, * V0, * XY0;\n\tuint8_t * B;\n\tuint32_t * V;\n\tuint32_t * XY;\n\tsize_t r = _r, p = _p;\n\tuint32_t i;\n\n\t/* Sanity-check parameters. */\n\tif ((r == 0) || (p == 0)) {\n\t\terrno = EINVAL;\n\t\tgoto err0;\n\t}\n#if SIZE_MAX > UINT32_MAX\n\tif (buflen > (((uint64_t)(1) << 32) - 1) * 32) {\n\t\terrno = EFBIG;\n\t\tgoto err0;\n\t}\n#endif\n\tif ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) {\n\t\terrno = EFBIG;\n\t\tgoto err0;\n\t}\n\tif (((N & (N - 1)) != 0) || (N < 2)) {\n\t\terrno = EINVAL;\n\t\tgoto err0;\n\t}\n\tif ((r > SIZE_MAX / 128 / p) ||\n#if SIZE_MAX / 256 <= UINT32_MAX\n\t    (r > (SIZE_MAX - 64) / 256) ||\n#endif\n\t    (N > SIZE_MAX / 128 / r)) {\n\t\terrno = ENOMEM;\n\t\tgoto err0;\n\t}\n\n\t/* Allocate memory. */\n#ifdef HAVE_POSIX_MEMALIGN\n\tif ((errno = posix_memalign(&B0, 64, 128 * r * p)) != 0)\n\t\tgoto err0;\n\tB = (uint8_t *)(B0);\n\tif ((errno = posix_memalign(&XY0, 64, 256 * r + 64)) != 0)\n\t\tgoto err1;\n\tXY = (uint32_t *)(XY0);\n#if !defined(MAP_ANON) || !defined(HAVE_MMAP)\n\tif ((errno = posix_memalign(&V0, 64, (size_t)(128 * r * N))) != 0)\n\t\tgoto err2;\n\tV = (uint32_t *)(V0);\n#endif\n#else\n\tif ((B0 = malloc(128 * r * p + 63)) == NULL)\n\t\tgoto err0;\n\tB = (uint8_t *)(((uintptr_t)(B0) + 63) & ~ (uintptr_t)(63));\n\tif ((XY0 = malloc(256 * r + 64 + 63)) == NULL)\n\t\tgoto err1;\n\tXY = (uint32_t *)(((uintptr_t)(XY0) + 63) & ~ (uintptr_t)(63));\n#if !defined(MAP_ANON) || !defined(HAVE_MMAP)\n\tif ((V0 = malloc(128 * r * N + 63)) == NULL)\n\t\tgoto err2;\n\tV = (uint32_t *)(((uintptr_t)(V0) + 63) & ~ (uintptr_t)(63));\n#endif\n#endif\n#if defined(MAP_ANON) && defined(HAVE_MMAP)\n\tif ((V0 = mmap(NULL, (size_t)(128 * r * N), PROT_READ | PROT_WRITE,\n#ifdef MAP_NOCORE\n\t    MAP_ANON | MAP_PRIVATE | MAP_NOCORE,\n#else\n\t    MAP_ANON | MAP_PRIVATE,\n#endif\n\t    -1, 0)) == MAP_FAILED)\n\t\tgoto err2;\n\tV = (uint32_t *)(V0);\n#endif\n\n\t/* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */\n\tPBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, B, p * 128 * r);\n\n\t/* 2: for i = 0 to p - 1 do */\n\tfor (i = 0; i < p; i++) {\n\t\t/* 3: B_i <-- MF(B_i, N) */\n\t\t(smix)(&B[i * 128 * r], r, N, V, XY);\n\t}\n\n\t/* 5: DK <-- PBKDF2(P, B, 1, dkLen) */\n\tPBKDF2_SHA256(passwd, passwdlen, B, p * 128 * r, 1, buf, buflen);\n\n\t/* Free memory. */\n#if defined(MAP_ANON) && defined(HAVE_MMAP)\n\tif (munmap(V0, (size_t)(128 * r * N)))\n\t\tgoto err2;\n#else\n\tfree(V0);\n#endif\n\tfree(XY0);\n\tfree(B0);\n\n\t/* Success! */\n\treturn (0);\n\nerr2:\n\tfree(XY0);\nerr1:\n\tfree(B0);\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n#define TESTLEN 64\nstatic struct scrypt_test {\n\tconst char * passwd;\n\tconst char * salt;\n\tuint64_t N;\n\tuint32_t r;\n\tuint32_t p;\n\tuint8_t result[TESTLEN];\n} testcase = {\n\t.passwd = \"pleaseletmein\",\n\t.salt = \"SodiumChloride\",\n\t.N = 16,\n\t.r = 8,\n\t.p = 1,\n\t.result = {\n\t\t0x25, 0xa9, 0xfa, 0x20, 0x7f, 0x87, 0xca, 0x09,\n\t\t0xa4, 0xef, 0x8b, 0x9f, 0x77, 0x7a, 0xca, 0x16,\n\t\t0xbe, 0xb7, 0x84, 0xae, 0x18, 0x30, 0xbf, 0xbf,\n\t\t0xd3, 0x83, 0x25, 0xaa, 0xbb, 0x93, 0x77, 0xdf,\n\t\t0x1b, 0xa7, 0x84, 0xd7, 0x46, 0xea, 0x27, 0x3b,\n\t\t0xf5, 0x16, 0xa4, 0x6f, 0xbf, 0xac, 0xf5, 0x11,\n\t\t0xc5, 0xbe, 0xba, 0x4c, 0x4a, 0xb3, 0xac, 0xc7,\n\t\t0xfa, 0x6f, 0x46, 0x0b, 0x6c, 0x0f, 0x47, 0x7b,\n\t}\n};\n\nstatic int\ntestsmix(void (* smix)(uint8_t *, size_t, uint64_t, void *, void *))\n{\n\tuint8_t hbuf[TESTLEN];\n\n\t/* Perform the computation. */\n\tif (crypto_scrypt_internal(\n\t    (const uint8_t *)testcase.passwd, strlen(testcase.passwd),\n\t    (const uint8_t *)testcase.salt, strlen(testcase.salt),\n\t    testcase.N, testcase.r, testcase.p, hbuf, TESTLEN, smix))\n\t\treturn (-1);\n\n\t/* Does it match? */\n\treturn (memcmp(testcase.result, hbuf, TESTLEN));\n}\n\nstatic void\nselectsmix(void)\n{\n\n#ifdef CPUSUPPORT_X86_SSE2\n\t/* If we're running on an SSE2-capable CPU, try that code. */\n\tif (cpusupport_x86_sse2()) {\n\t\t/* If SSE2ized smix works, use it. */\n\t\tif (!testsmix(crypto_scrypt_smix_sse2)) {\n\t\t\tsmix_func = crypto_scrypt_smix_sse2;\n\t\t\treturn;\n\t\t}\n\t\twarn0(\"Disabling broken SSE2 scrypt support - please report bug!\");\n\t}\n#endif\n\n\t/* If generic smix works, use it. */\n\tif (!testsmix(crypto_scrypt_smix)) {\n\t\tsmix_func = crypto_scrypt_smix;\n\t\treturn;\n\t}\n\twarn0(\"Generic scrypt code is broken - please report bug!\");\n\n\t/* If we get here, something really bad happened. */\n\tabort();\n}\n\n/**\n * crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):\n * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,\n * p, buflen) and write the result into buf.  The parameters r, p, and buflen\n * must satisfy 0 < r * p < 2^30 and buflen <= (2^32 - 1) * 32.  The parameter\n * N must be a power of 2 greater than 1.\n *\n * Return 0 on success; or -1 on error.\n */\nint\ncrypto_scrypt(const uint8_t * passwd, size_t passwdlen,\n    const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t _r, uint32_t _p,\n    uint8_t * buf, size_t buflen)\n{\n\n\tif (smix_func == NULL)\n\t\tselectsmix();\n\n\treturn (crypto_scrypt_internal(passwd, passwdlen, salt, saltlen, N,\n\t    _r, _p, buf, buflen, smix_func));\n}\n"
  },
  {
    "path": "lib-platform/crypto/crypto_scrypt.h",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#ifndef CRYPTO_SCRYPT_H_\n#define CRYPTO_SCRYPT_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_scrypt(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):\n * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,\n * p, buflen) and write the result into buf.  The parameters r, p, and buflen\n * must satisfy 0 < r * p < 2^30 and buflen <= (2^32 - 1) * 32.  The parameter\n * N must be a power of 2 greater than 1.\n *\n * Return 0 on success; or -1 on error.\n */\nint crypto_scrypt(const uint8_t *, size_t, const uint8_t *, size_t, uint64_t,\n    uint32_t, uint32_t, uint8_t *, size_t);\n\n#endif /* !CRYPTO_SCRYPT_H_ */\n"
  },
  {
    "path": "lib-platform/platform.h",
    "content": "#ifndef PLATFORM_H_\n#define PLATFORM_H_\n\n/* Ensure that we have a config file. */\n#if defined(CONFIG_H_FILE)\n#include CONFIG_H_FILE\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#else\n#error Need either CONFIG_H_FILE or HAVE_CONFIG_H defined.\n#endif\n\n#endif /* !PLATFORM_H_ */\n"
  },
  {
    "path": "lib-platform/util/memlimit.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n\n#include \"platform.h\"\n\n#include <sys/types.h>\n#include <sys/resource.h>\n\n#ifdef HAVE_SYS_PARAM_H\n#include <sys/param.h>\n#endif\n#ifdef HAVE_SYS_SYSCTL_H\n#include <sys/sysctl.h>\n#endif\n#ifdef HAVE_SYS_SYSINFO_H\n#include <sys/sysinfo.h>\n#endif\n\n#include <assert.h>\n#include <errno.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <string.h>\n#include <unistd.h>\n\n#ifdef DEBUG\n#include <stdio.h>\n#endif\n\n#include \"memlimit.h\"\n\n/* If we don't have CTL_HW, we can't use HW_USERMEM. */\n#ifndef CTL_HW\n#undef HW_USERMEM\n#endif\n\n/* Is RLIMIT_DATA relevant on this platform? */\n#if !defined(HAVE_MMAP) || defined(__OpenBSD__)\n#define USE_RLIMIT_DATA\n#endif\n\n#ifdef CTL_HW\nstatic int\nmemlimit_sysctl_hw(size_t * memlimit, int mibleaf)\n{\n\tint mib[2];\n\tuint8_t sysctlbuf[8];\n\tsize_t sysctlbuflen = 8;\n\tuint64_t sysctlval;\n\n\t/* Ask the kernel how much RAM we have. */\n\tmib[0] = CTL_HW;\n\tmib[1] = mibleaf;\n\tif (sysctl(mib, 2, sysctlbuf, &sysctlbuflen, NULL, 0))\n\t\treturn (1);\n\n\t/*\n\t * If we read 8 bytes out, assume this is a system-endian uint64_t.\n\t * If we only read 4 bytes out, the OS is trying to give us a\n\t * uint32_t answer -- but given how many systems now have 4GB+ of RAM,\n\t * it's probably truncating, and we really can't trust the value we\n\t * have returned to us.\n\t */\n\tif (sysctlbuflen == sizeof(uint64_t))\n\t\tmemcpy(&sysctlval, sysctlbuf, sizeof(uint64_t));\n\telse if (sysctlbuflen == sizeof(uint32_t))\n\t\tsysctlval = SIZE_MAX;\n\telse\n\t\treturn (1);\n\n\t/* Return the sysctl value, but clamp to SIZE_MAX if necessary. */\n#if UINT64_MAX > SIZE_MAX\n\tif (sysctlval > SIZE_MAX)\n\t\t*memlimit = SIZE_MAX;\n\telse\n\t\t*memlimit = (size_t)sysctlval;\n#else\n\t*memlimit = sysctlval;\n#endif\n\n\t/* Success! */\n\treturn (0);\n}\n#endif\n\n/* If we don't HAVE_STRUCT_SYSINFO, we can't use sysinfo. */\n#ifndef HAVE_STRUCT_SYSINFO\n#undef HAVE_SYSINFO\n#endif\n\n/* If we don't HAVE_STRUCT_SYSINFO_TOTALRAM, we can't use sysinfo. */\n#ifndef HAVE_STRUCT_SYSINFO_TOTALRAM\n#undef HAVE_SYSINFO\n#endif\n\n#ifdef HAVE_SYSINFO\nstatic int\nmemlimit_sysinfo(size_t * memlimit)\n{\n\tstruct sysinfo info;\n\tuint64_t totalmem;\n\n\t/* Get information from the kernel. */\n\tif (sysinfo(&info))\n\t\treturn (1);\n\ttotalmem = info.totalram;\n\n\t/* If we're on a modern kernel, adjust based on mem_unit. */\n#ifdef HAVE_STRUCT_SYSINFO_MEM_UNIT\n\ttotalmem = totalmem * info.mem_unit;\n#endif\n\n\t/* Return the value, but clamp to SIZE_MAX if necessary. */\n#if UINT64_MAX > SIZE_MAX\n\tif (totalmem > SIZE_MAX)\n\t\t*memlimit = SIZE_MAX;\n\telse\n\t\t*memlimit = (size_t)totalmem;\n#else\n\t*memlimit = totalmem;\n#endif\n\n\t/* Success! */\n\treturn (0);\n}\n#endif /* HAVE_SYSINFO */\n\nstatic int\nmemlimit_rlimit(size_t * memlimit)\n{\n\tstruct rlimit rl;\n\tuint64_t memrlimit;\n\n\t/* Find the least of... */\n\tmemrlimit = (uint64_t)(-1);\n\n\t/* ... RLIMIT_AS... */\n#ifdef RLIMIT_AS\n\tif (getrlimit(RLIMIT_AS, &rl))\n\t\treturn (1);\n\tif ((rl.rlim_cur != RLIM_INFINITY) &&\n\t    ((uint64_t)rl.rlim_cur < memrlimit))\n\t\tmemrlimit = (uint64_t)rl.rlim_cur;\n#endif\n\n#ifdef USE_RLIMIT_DATA\n\t/* ... RLIMIT_DATA (if we're not using mmap)... */\n\tif (getrlimit(RLIMIT_DATA, &rl))\n\t\treturn (1);\n\tif ((rl.rlim_cur != RLIM_INFINITY) &&\n\t    ((uint64_t)rl.rlim_cur < memrlimit))\n\t\tmemrlimit = (uint64_t)rl.rlim_cur;\n#endif\n\n\t/* ... and RLIMIT_RSS. */\n#ifdef RLIMIT_RSS\n\tif (getrlimit(RLIMIT_RSS, &rl))\n\t\treturn (1);\n\tif ((rl.rlim_cur != RLIM_INFINITY) &&\n\t    ((uint64_t)rl.rlim_cur < memrlimit))\n\t\tmemrlimit = (uint64_t)rl.rlim_cur;\n#endif\n\n\t/* Return the value, but clamp to SIZE_MAX if necessary. */\n#if UINT64_MAX > SIZE_MAX\n\tif (memrlimit > SIZE_MAX)\n\t\t*memlimit = SIZE_MAX;\n\telse\n\t\t*memlimit = (size_t)memrlimit;\n#else\n\t*memlimit = memrlimit;\n#endif\n\n\t/* Success! */\n\treturn (0);\n}\n\n#ifdef _SC_PHYS_PAGES\n\n/* Some systems define _SC_PAGESIZE instead of _SC_PAGE_SIZE. */\n#ifndef _SC_PAGE_SIZE\n#define _SC_PAGE_SIZE _SC_PAGESIZE\n#endif\n\nstatic int\nmemlimit_sysconf(size_t * memlimit)\n{\n\tlong pagesize;\n\tlong physpages;\n\tuint64_t totalmem;\n\n\t/* Set errno to 0 in order to distinguish \"no limit\" from \"error\". */\n\terrno = 0;\n\n\t/* Read the two limits. */\n\tif (((pagesize = sysconf(_SC_PAGE_SIZE)) == -1) ||\n\t    ((physpages = sysconf(_SC_PHYS_PAGES)) == -1)) {\n\t\t/*\n\t\t * Did an error occur?  OS X may return EINVAL due to not\n\t\t * supporting _SC_PHYS_PAGES in spite of defining it.\n\t\t */\n\t\tif (errno != 0 && errno != EINVAL)\n\t\t\treturn (1);\n\n\t\t/* If not, there is no limit. */\n\t\ttotalmem = (uint64_t)(-1);\n\t} else {\n\t\t/* Compute the limit. */\n\t\ttotalmem = (uint64_t)(pagesize) * (uint64_t)(physpages);\n\t}\n\n\t/* Return the value, but clamp to SIZE_MAX if necessary. */\n#if UINT64_MAX > SIZE_MAX\n\tif (totalmem > SIZE_MAX)\n\t\t*memlimit = SIZE_MAX;\n\telse\n\t\t*memlimit = (size_t)totalmem;\n#else\n\t*memlimit = totalmem;\n#endif\n\n\t/* Success! */\n\treturn (0);\n}\n#endif\n\n/**\n * memtouse(maxmem, maxmemfrac, memlimit):\n * Examine the system and return the amount of RAM which should be\n * used in ${memlimit}.  This value should be the specified\n * ${maxmemfrac} fraction of available RAM, but no more than\n * ${maxmem} and no less than 1 MiB.  ${maxmemfrac} must be larger than 0\n * and <= 1.0.\n */\nint\nmemtouse(size_t maxmem, double maxmemfrac, size_t * memlimit)\n{\n\tsize_t usermem_memlimit, memsize_memlimit;\n\tsize_t sysinfo_memlimit, rlimit_memlimit;\n\tsize_t sysconf_memlimit;\n\tsize_t memlimit_min;\n\tsize_t memavail;\n\n\t/* Check limit. */\n\tassert((maxmemfrac > 0) && (maxmemfrac <= 1.0));\n\n\t/* Get memory limits. */\n#ifdef HW_USERMEM\n\tif (memlimit_sysctl_hw(&usermem_memlimit, HW_USERMEM))\n\t\treturn (1);\n#else\n\tusermem_memlimit = SIZE_MAX;\n#endif\n#ifdef HW_MEMSIZE\n\tif (memlimit_sysctl_hw(&memsize_memlimit, HW_MEMSIZE))\n\t\treturn (1);\n#else\n\tmemsize_memlimit = SIZE_MAX;\n#endif\n#ifdef HAVE_SYSINFO\n\tif (memlimit_sysinfo(&sysinfo_memlimit))\n\t\treturn (1);\n#else\n\tsysinfo_memlimit = SIZE_MAX;\n#endif\n\tif (memlimit_rlimit(&rlimit_memlimit))\n\t\treturn (1);\n#ifdef _SC_PHYS_PAGES\n\tif (memlimit_sysconf(&sysconf_memlimit))\n\t\treturn (1);\n#else\n\tsysconf_memlimit = SIZE_MAX;\n#endif\n\n#ifdef DEBUG\n\t/* rlimit has two '\\t' so that they line up. */\n\tfprintf(stderr, \"Memory limits are:\\n\\tusermem:\\t%zu\\n\"\n\t    \"\\tmemsize:\\t%zu\\n\\tsysinfo:\\t%zu\\n\\trlimit:\\t\\t%zu\\n\"\n\t    \"\\tsysconf:\\t%zu\\n\", usermem_memlimit, memsize_memlimit,\n\t    sysinfo_memlimit, rlimit_memlimit, sysconf_memlimit);\n#endif\n\n\t/*\n\t * Some systems return bogus values for hw.usermem due to ZFS making\n\t * use of wired pages.  Assume that at least 50% of physical pages\n\t * are available to userland on demand.\n\t */\n\tif (sysconf_memlimit != SIZE_MAX) {\n\t\tif (usermem_memlimit < sysconf_memlimit / 2)\n\t\t\tusermem_memlimit = sysconf_memlimit / 2;\n\t}\n\n\t/* Find the smallest of them. */\n\tmemlimit_min = SIZE_MAX;\n\tif (memlimit_min > usermem_memlimit)\n\t\tmemlimit_min = usermem_memlimit;\n\tif (memlimit_min > memsize_memlimit)\n\t\tmemlimit_min = memsize_memlimit;\n\tif (memlimit_min > sysinfo_memlimit)\n\t\tmemlimit_min = sysinfo_memlimit;\n\tif (memlimit_min > rlimit_memlimit)\n\t\tmemlimit_min = rlimit_memlimit;\n\tif (memlimit_min > sysconf_memlimit)\n\t\tmemlimit_min = sysconf_memlimit;\n\n#ifdef DEBUG\n\t/* This line is continued after the maxmemfrac calculation. */\n\tfprintf(stderr, \"Minimum is %zu;\", memlimit_min);\n#endif\n\n\t/* Only use the specified fraction of the available memory. */\n\tmemavail = (size_t)(maxmemfrac * (double)memlimit_min);\n\n#ifdef DEBUG\n\tfprintf(stderr, \" will apply maxmemfrac of %g\\n\", maxmemfrac);\n#endif\n\n\t/* Don't use more than the specified maximum. */\n\tif ((maxmem > 0) && (memavail > maxmem))\n\t\tmemavail = maxmem;\n\n\t/* But always allow at least 1 MiB. */\n\tif (memavail < 1048576)\n\t\tmemavail = 1048576;\n\n#ifdef DEBUG\n\tfprintf(stderr, \"Memory allowed:\\t\\t%zu\\n\", memavail);\n#endif\n\n\t/* Return limit via the provided pointer. */\n\t*memlimit = memavail;\n\treturn (0);\n}\n"
  },
  {
    "path": "lib-platform/util/memlimit.h",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#ifndef MEMLIMIT_H_\n#define MEMLIMIT_H_\n\n#include <stddef.h>\n\n/**\n * memtouse(maxmem, maxmemfrac, memlimit):\n * Examine the system and return the amount of RAM which should be\n * used in ${memlimit}.  This value should be the specified\n * ${maxmemfrac} fraction of available RAM, but no more than\n * ${maxmem} and no less than 1 MiB.  ${maxmemfrac} must be larger than 0\n * and <= 1.0.\n */\nint memtouse(size_t, double, size_t *);\n\n#endif /* !MEMLIMIT_H_ */\n"
  },
  {
    "path": "libcperciva/POSIX/README",
    "content": "POSIX compatibility code\n------------------------\n\nThis code exists to work around some common POSIX compatibility issues.\nPOSIX specifies that if the first line of a Makefile is \".POSIX:\" then the\nMakefile should be processed according to POSIX rules, including with CC=c99;\nthus we should see behaviour consistent with a standard-compliant C99\ncompiler.\n\nOne POSIX compatibility check requires a runtime test.  This will be\nautomatically disabled if the build system detects that you are\ncross-compiling for another platform, or it can be manually disabled by\nsetting DISABLE_POSIX_RUNTIME_CHECKS to a non-zero value.\n\n- posix-cflags.sh: Detects if ${CC} supports certain POSIX features, and\n  outputs a POSIXFAIL_ define if it is not supported so that we can work around\n  the problem.\n\n  The potential command-line flags are:\n  - DPOSIXFAIL_MSG_NOSIGNAL: <sys/socket.h> not defining MSG_NOSIGNAL.\n  - DPOSIXFAIL_CLOCK_REALTIME: <time.h> not defining CLOCK_REALTIME.\n  - DPOSIXFAIL_CLOCK_GETTIME: <time.h> not declaring clock_gettime(), or\n    clock_gettime() is not linkable.  The latter test requires a runtime check.\n  - DPOSIXFAIL_INET_ADDRSTRLEN: <netinet/in.h> not defining\n    INET_ADDRSTRLEN.\n  - DPOSIXFAIL_INET6_ADDRSTRLEN: <netinet/in.h> not defining\n    INET6_ADDRSTRLEN.\n  - DPOSIXFAIL_ABSTRACT_DECLARATOR: ${CC} does not accept\n    qualifiers in an abstract declarator.\n  - DPOSIXFAIL_STAT_ST_MTIM: struct stat does not contain st_mtim.\n  - std=c99: ${CC} does not accept the `restrict` keyword by default, but\n    accepts it when given this flag.\n\n- posix-cflags-filter.sh: Detects if ${CC} supports expected ${CFLAG} value(s).\n\n  The potential ${CFLAGS} flags it checks are:\n  - O2: some compilers only accept -O.\n\n- posix-l.sh: Detects whether the linker supports certain POSIX features.\n\n  The potential command-line flags are:\n  - lrt lxnet: c99 is required to understand these options, and ignore them if\n    the routines for which they specify linkage are already in the standard C\n    library\n"
  },
  {
    "path": "libcperciva/POSIX/posix-abstract-declarator.c",
    "content": "#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nstatic int func(int ARGNAME[static restrict 1]);\n#else\nstatic int func(int [static restrict 1]);\n#endif\n\nint\nfunc(int arr[static restrict 1])\n{\n\n\t(void)arr; /* UNUSED */\n\n\t/* Success! */\n\treturn (0);\n}\n\nint\nmain(void)\n{\n\n\t(void)func; /* UNUSED */\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-cflags.sh",
    "content": "# Should be sourced by\n#     command -p sh posix-cflags.sh \"$PATH\"\n# from within a Makefile.\n\n# Sanity check environment variables\nif [ -z \"${CC}\" ]; then\n\techo \"\\$CC is not defined!  Cannot run any compiler tests.\" 1>&2\n\texit 1\nfi\nif ! [ \"${PATH}\" = \"$1\" ]; then\n\techo \"WARNING: POSIX violation: ${SHELL}'s command -p resets \\$PATH\" 1>&2\n\tPATH=$1\nfi\n\n# Find directory of this script and the source files\nD=$(dirname \"$0\")\n\n# Check if we can compile & run a binary.\nif ! ${CC} ${CFLAGS} \"${D}/posix-trivial.c\" 2>/dev/null; then\n\techo \"WARNING: failed to compile posix-trivial.c\" 1>&2\nelse\n\t# If the user hasn't disabled runtime checks...\n\tif [ \"${DISABLE_POSIX_RUNTIME_CHECKS:-0}\" -eq \"0\" ]; then\n\t\t# ... test if we can run the trivial binary.\n\t\tif ! ./a.out ; then\n\t\t\techo \"WARNING: failed to run a trivial binary; \" 1>&2\n\t\t\techo \"disabling runtime POSIX compatibility checks\" 1>&2\n\t\t\tDISABLE_POSIX_RUNTIME_CHECKS=1\n\t\tfi\n\tfi\nfi\n\nFIRST=YES\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L \"${D}/posix-msg_nosignal.c\" 2>/dev/null; then\n\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\tprintf %s \"-DPOSIXFAIL_MSG_NOSIGNAL\"\n\techo \"WARNING: POSIX violation: <sys/socket.h> not defining MSG_NOSIGNAL\" 1>&2\nfi\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L \"${D}/posix-clock_realtime.c\" 2>/dev/null; then\n\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\tprintf %s \"-DPOSIXFAIL_CLOCK_REALTIME\"\n\techo \"WARNING: POSIX violation: <time.h> not defining CLOCK_REALTIME\" 1>&2\nfi\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 \"${D}/posix-inet-addrstrlen.c\" 2>/dev/null; then\n\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\tprintf %s \"-DPOSIXFAIL_INET_ADDRSTRLEN\"\n\techo \"WARNING: POSIX violation: <netinet/in.h> not defining INET_ADDRSTRLEN\" 1>&2\nfi\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 \"${D}/posix-inet6-addrstrlen.c\" 2>/dev/null; then\n\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\tprintf %s \"-DPOSIXFAIL_INET6_ADDRSTRLEN\"\n\techo \"WARNING: POSIX violation: <netinet/in.h> not defining INET6_ADDRSTRLEN\" 1>&2\nfi\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L \"${D}/posix-clock_gettime.c\" 2>/dev/null; then\n\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\tprintf %s \"-DPOSIXFAIL_CLOCK_GETTIME\"\n\techo \"WARNING: POSIX violation: <time.h> not declaring clock_gettime()\" 1>&2\nelif [ \"${DISABLE_POSIX_RUNTIME_CHECKS:-0}\" -ne \"0\" ]; then\n\t# Do nothing\n\ttrue\nelse\n\t# Even if the compilation succeeds, we still need to run the binary\n\t# because OS X 10.11 with XCode 8 _will_ contain clock_gettime() in the\n\t# header (because it was added in 10.12 and they only use one SDK per\n\t# XCode version), but it will link to the 10.11 library (which doesn't\n\t# include it).  Annoyingly, there's two levels of error output on OS X:\n\t# one from the binary itself, and one from the signal it sends to the\n\t# calling process.  The \"( ./x 2>y ) 2>y\" captures both types of error\n\t# message.\n\tif ! ( ./a.out 2>/dev/null ) 2>/dev/null ; then\n\t\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\t\tprintf %s \"-DPOSIXFAIL_CLOCK_GETTIME\"\n\t\techo \"WARNING: POSIX violation: clock_gettime() is not linkable\" 1>&2\n\tfi\nfi\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 \"${D}/posix-stat-st_mtim.c\" 2>/dev/null; then\n\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\tprintf %s \"-DPOSIXFAIL_STAT_ST_MTIM\"\n\techo \"WARNING: POSIX violation: struct stat does not contain st_mtim\" 1>&2\nfi\nCFLAGS_C99=\"\"\nif ! ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L \"${D}/posix-restrict.c\" 2>/dev/null; then\n\techo \"WARNING: POSIX violation: ${CC} does not accept the 'restrict' keyword\" 1>&2\n\tif ${CC} ${CFLAGS} -D_POSIX_C_SOURCE=200809L -std=c99 \"${D}/posix-restrict.c\" 2>/dev/null; then\n\t\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\t\tprintf %s \"-std=c99\"\n\t\tCFLAGS_C99=\"-std=c99\"\n\tfi\nfi\nif ! ${CC} ${CFLAGS} ${CFLAGS_C99} -D_POSIX_C_SOURCE=200809L -DARGNAME=\"\" \"${D}/posix-abstract-declarator.c\" 2>/dev/null; then\n\techo \"WARNING: POSIX violation: ${CC} does not accept qualifiers in an abstract declarator\" 1>&2\n\t# Test compile with -DPOSIXFAIL_ABSTRACT_DECLARATOR\n\tif ${CC} ${CFLAGS} ${CFLAGS_C99} -D_POSIX_C_SOURCE=200809L -DPOSIXFAIL_ABSTRACT_DECLARATOR \"${D}/posix-abstract-declarator.c\" 2>/dev/null; then\n\t\t[ \"${FIRST}\" = \"NO\" ] && printf \" \"; FIRST=NO\n\t\tprintf %s \"-DPOSIXFAIL_ABSTRACT_DECLARATOR\"\n\tfi\nfi\nrm -f a.out\n"
  },
  {
    "path": "libcperciva/POSIX/posix-clock_gettime.c",
    "content": "#include <time.h>\n\nint\nmain(void)\n{\n\tstruct timespec ts;\n\n\treturn (clock_gettime(CLOCK_REALTIME, &ts));\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-clock_realtime.c",
    "content": "#include <time.h>\n\nint\nmain(void)\n{\n\n\treturn (CLOCK_REALTIME);\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-inet-addrstrlen.c",
    "content": "#include <netinet/in.h>\n\nint\nmain(void)\n{\n\n\treturn (INET_ADDRSTRLEN);\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-inet6-addrstrlen.c",
    "content": "#include <netinet/in.h>\n\nint\nmain(void)\n{\n\n\treturn (INET6_ADDRSTRLEN);\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-l.sh",
    "content": "# Should be sourced by\n#     command -p sh posix-l.sh \"$PATH\"\n# from within a Makefile.\n\n# Sanity check environment variables\nif [ -z \"${CC}\" ]; then\n\techo \"\\$CC is not defined!  Cannot run any compiler tests.\" 1>&2\n\texit 1\nfi\nif ! [ \"${PATH}\" = \"$1\" ]; then\n\techo \"WARNING: POSIX violation: ${SHELL}'s command -p resets \\$PATH\" 1>&2\n\tPATH=$1\nfi\n\n# Find directory of this script and the source files\nD=$(dirname \"$0\")\n\nFIRST=YES\nfor LIB in rt xnet; do\n\tif ${CC} ${CFLAGS} -l\"${LIB}\" \"${D}/posix-trivial.c\" 2>/dev/null; then\n\t\tif [ \"${FIRST}\" = \"NO\" ]; then\n\t\t\tprintf \" \";\n\t\tfi\n\t\tprintf \"%s\" \"-l${LIB}\";\n\t\tFIRST=NO;\n\telse\n\t\techo \"WARNING: POSIX violation: ${CC} does not understand -l${LIB}\" 1>&2\n\tfi\n\trm -f a.out\ndone\n"
  },
  {
    "path": "libcperciva/POSIX/posix-msg_nosignal.c",
    "content": "#include <sys/socket.h>\n\nint\nmain(void)\n{\n\n\treturn (MSG_NOSIGNAL);\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-restrict.c",
    "content": "static int\nfoo(const char * restrict x, const char * restrict y)\n{\n\n\treturn (x == y);\n}\n\nint\nmain(void)\n{\n\tchar x[10];\n\tchar y[10];\n\n\treturn (foo(x, y));\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-stat-st_mtim.c",
    "content": "#include <sys/stat.h>\n\nint\nmain(void)\n{\n\tstruct stat sb;\n\n\t/* Can we reference st_mtim? */\n\t(void)sb.st_mtim.tv_sec;\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/POSIX/posix-trivial.c",
    "content": "int\nmain(void)\n{\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/alg/sha256.c",
    "content": "#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n\n#include \"cpusupport.h\"\n#include \"insecure_memzero.h\"\n#include \"sha256_arm.h\"\n#include \"sha256_shani.h\"\n#include \"sha256_sse2.h\"\n#include \"sysendian.h\"\n#include \"warnp.h\"\n\n#include \"sha256.h\"\n\n#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3) ||\t\\\n    defined(CPUSUPPORT_X86_SSE2) ||\t\t\t\t\t\\\n    defined(CPUSUPPORT_ARM_SHA256)\n#define HWACCEL\n\nstatic enum {\n\tHW_SOFTWARE = 0,\n#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3)\n\tHW_X86_SHANI,\n#endif\n#if defined(CPUSUPPORT_X86_SSE2)\n\tHW_X86_SSE2,\n#endif\n#if defined(CPUSUPPORT_ARM_SHA256)\n\tHW_ARM_SHA256,\n#endif\n\tHW_UNSET\n} hwaccel = HW_UNSET;\n#endif\n\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nstatic void SHA256_Transform(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64], uint32_t W[static restrict 64],\n    uint32_t S[static restrict 8]);\n#else\nstatic void SHA256_Transform(uint32_t[static restrict 8],\n    const uint8_t[static restrict 64], uint32_t[static restrict 64],\n    uint32_t[static restrict 8]);\n#endif\n\n/*\n * Encode a length len/4 vector of (uint32_t) into a length len vector of\n * (uint8_t) in big-endian form.  Assumes len is a multiple of 4.\n */\nstatic void\nbe32enc_vect(uint8_t * dst, const uint32_t * src, size_t len)\n{\n\tsize_t i;\n\n\t/* Sanity-check. */\n\tassert(len % 4 == 0);\n\n\t/* Encode vector, one word at a time. */\n\tfor (i = 0; i < len / 4; i++)\n\t\tbe32enc(dst + i * 4, src[i]);\n}\n\n/*\n * Decode a big-endian length len vector of (uint8_t) into a length\n * len/4 vector of (uint32_t).  Assumes len is a multiple of 4.\n */\nstatic void\nbe32dec_vect(uint32_t * dst, const uint8_t * src, size_t len)\n{\n\tsize_t i;\n\n\t/* Sanity-check. */\n\tassert(len % 4 == 0);\n\n\t/* Decode vector, one word at a time. */\n\tfor (i = 0; i < len / 4; i++)\n\t\tdst[i] = be32dec(src + i * 4);\n}\n\n/* SHA256 round constants. */\nstatic const uint32_t Krnd[64] = {\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n\t0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n\t0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n\t0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n\t0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n\t0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n\t0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n\t0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n\t0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n};\n\n/* Magic initialization constants. */\nstatic const uint32_t initial_state[8] = {\n\t0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,\n\t0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19\n};\n\n#ifdef HWACCEL\n#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3)\n/* Shim so that we can test SHA256_Transform_shani() in the standard manner. */\nstatic void\nSHA256_Transform_shani_with_W_S(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64], uint32_t W[static restrict 64],\n    uint32_t S[static restrict 8])\n{\n\n\t(void)W; /* UNUSED */\n\t(void)S; /* UNUSED */\n\n\tSHA256_Transform_shani(state, block);\n}\n#endif\n#if defined(CPUSUPPORT_ARM_SHA256)\n/* Shim so that we can test SHA256_Transform_arm() in the standard manner. */\nstatic void\nSHA256_Transform_arm_with_W_S(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64], uint32_t W[static restrict 64],\n    uint32_t S[static restrict 8])\n{\n\n\t(void)W; /* UNUSED */\n\t(void)S; /* UNUSED */\n\n\tSHA256_Transform_arm(state, block);\n}\n#endif\n\n/*\n * Test whether software and hardware extensions transform code produce the\n * same results.  Must be called with (hwaccel == HW_SOFTWARE).\n */\nstatic int\nhwtest(const uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64],\n    uint32_t W[static restrict 64], uint32_t S[static restrict 8],\n    void (* func)(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64], uint32_t W[static restrict 64],\n    uint32_t S[static restrict 8]))\n{\n\tuint32_t state_sw[8];\n\tuint32_t state_hw[8];\n\n\t/* Software transform. */\n\tmemcpy(state_sw, state, sizeof(state_sw));\n\tSHA256_Transform(state_sw, block, W, S);\n\n\t/* Hardware transform. */\n\tmemcpy(state_hw, state, sizeof(state_hw));\n\tfunc(state_hw, block, W, S);\n\n\t/* Do the results match? */\n\treturn (memcmp(state_sw, state_hw, sizeof(state_sw)));\n}\n\n/* Which type of hardware acceleration should we use, if any? */\nstatic void\nhwaccel_init(void)\n{\n\tuint32_t W[64];\n\tuint32_t S[8];\n\tuint8_t block[64];\n\tuint8_t i;\n\n\t/* If we've already set hwaccel, we're finished. */\n\tif (hwaccel != HW_UNSET)\n\t\treturn;\n\n\t/* Default to software. */\n\thwaccel = HW_SOFTWARE;\n\n\t/* Test case: Hash 0x00 0x01 0x02 ... 0x3f. */\n\tfor (i = 0; i < 64; i++)\n\t\tblock[i] = i;\n\n#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3)\n\tCPUSUPPORT_VALIDATE(hwaccel, HW_X86_SHANI,\n\t    cpusupport_x86_shani() && cpusupport_x86_ssse3(),\n\t    hwtest(initial_state, block, W, S,\n\t\tSHA256_Transform_shani_with_W_S));\n#endif\n#if defined(CPUSUPPORT_X86_SSE2)\n\tCPUSUPPORT_VALIDATE(hwaccel, HW_X86_SSE2, cpusupport_x86_sse2(),\n\t    hwtest(initial_state, block, W, S, SHA256_Transform_sse2));\n#endif\n#if defined(CPUSUPPORT_ARM_SHA256)\n\tCPUSUPPORT_VALIDATE(hwaccel, HW_ARM_SHA256, cpusupport_arm_sha256(),\n\t    hwtest(initial_state, block, W, S, SHA256_Transform_arm_with_W_S));\n#endif\n}\n#endif /* HWACCEL */\n\n/* Elementary functions used by SHA256 */\n#define Ch(x, y, z)\t((x & (y ^ z)) ^ z)\n#define Maj(x, y, z)\t((x & (y | z)) | (y & z))\n#define SHR(x, n)\t(x >> n)\n#define ROTR(x, n)\t((x >> n) | (x << (32 - n)))\n#define S0(x)\t\t(ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))\n#define S1(x)\t\t(ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))\n#define s0(x)\t\t(ROTR(x, 7) ^ ROTR(x, 18) ^ SHR(x, 3))\n#define s1(x)\t\t(ROTR(x, 17) ^ ROTR(x, 19) ^ SHR(x, 10))\n\n/* SHA256 round function */\n#define RND(a, b, c, d, e, f, g, h, k)\t\t\t\\\n\th += S1(e) + Ch(e, f, g) + k;\t\t\t\\\n\td += h;\t\t\t\t\t\t\\\n\th += S0(a) + Maj(a, b, c)\n\n/* Adjusted round function for rotating state */\n#define RNDr(S, W, i, ii)\t\t\t\\\n\tRND(S[(64 - i) % 8], S[(65 - i) % 8],\t\\\n\t    S[(66 - i) % 8], S[(67 - i) % 8],\t\\\n\t    S[(68 - i) % 8], S[(69 - i) % 8],\t\\\n\t    S[(70 - i) % 8], S[(71 - i) % 8],\t\\\n\t    W[i + ii] + Krnd[i + ii])\n\n/* Message schedule computation */\n#define MSCH(W, ii, i)\t\t\t\t\\\n\tW[i + ii + 16] = s1(W[i + ii + 14]) + W[i + ii + 9] + s0(W[i + ii + 1]) + W[i + ii]\n\n/*\n * SHA256 block compression function.  The 256-bit state is transformed via\n * the 512-bit input block to produce a new state.  The arrays W and S may be\n * filled with sensitive data, and should be sanitized by the callee.\n */\nstatic void\nSHA256_Transform(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64],\n    uint32_t W[static restrict 64], uint32_t S[static restrict 8])\n{\n\tint i;\n\n#ifdef HWACCEL\n\n#if defined(__GNUC__) && defined(__aarch64__)\n\t/*\n\t * We require that SHA256_Init() is called before SHA256_Transform(),\n\t * but the compiler has no way of knowing that.  This assert adds a\n\t * significant speed boost for gcc on 64-bit ARM, and a minor penalty\n\t * on other systems & compilers.\n\t */\n\tassert(hwaccel != HW_UNSET);\n#endif\n\n\tswitch (hwaccel) {\n#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3)\n\tcase HW_X86_SHANI:\n\t\tSHA256_Transform_shani(state, block);\n\t\treturn;\n#endif\n#if defined(CPUSUPPORT_X86_SSE2)\n\tcase HW_X86_SSE2:\n\t\tSHA256_Transform_sse2(state, block, W, S);\n\t\treturn;\n#endif\n#if defined(CPUSUPPORT_ARM_SHA256)\n\tcase HW_ARM_SHA256:\n\t\tSHA256_Transform_arm(state, block);\n\t\treturn;\n#endif\n\tcase HW_SOFTWARE:\n\tcase HW_UNSET:\n\t\tbreak;\n\t}\n#endif /* HWACCEL */\n\n\t/* 1. Prepare the first part of the message schedule W. */\n\tbe32dec_vect(W, block, 64);\n\n\t/* 2. Initialize working variables. */\n\tmemcpy(S, state, 32);\n\n\t/* 3. Mix. */\n\tfor (i = 0; i < 64; i += 16) {\n\t\tRNDr(S, W, 0, i);\n\t\tRNDr(S, W, 1, i);\n\t\tRNDr(S, W, 2, i);\n\t\tRNDr(S, W, 3, i);\n\t\tRNDr(S, W, 4, i);\n\t\tRNDr(S, W, 5, i);\n\t\tRNDr(S, W, 6, i);\n\t\tRNDr(S, W, 7, i);\n\t\tRNDr(S, W, 8, i);\n\t\tRNDr(S, W, 9, i);\n\t\tRNDr(S, W, 10, i);\n\t\tRNDr(S, W, 11, i);\n\t\tRNDr(S, W, 12, i);\n\t\tRNDr(S, W, 13, i);\n\t\tRNDr(S, W, 14, i);\n\t\tRNDr(S, W, 15, i);\n\n\t\tif (i == 48)\n\t\t\tbreak;\n\t\tMSCH(W, 0, i);\n\t\tMSCH(W, 1, i);\n\t\tMSCH(W, 2, i);\n\t\tMSCH(W, 3, i);\n\t\tMSCH(W, 4, i);\n\t\tMSCH(W, 5, i);\n\t\tMSCH(W, 6, i);\n\t\tMSCH(W, 7, i);\n\t\tMSCH(W, 8, i);\n\t\tMSCH(W, 9, i);\n\t\tMSCH(W, 10, i);\n\t\tMSCH(W, 11, i);\n\t\tMSCH(W, 12, i);\n\t\tMSCH(W, 13, i);\n\t\tMSCH(W, 14, i);\n\t\tMSCH(W, 15, i);\n\t}\n\n\t/* 4. Mix local working variables into global state. */\n\tfor (i = 0; i < 8; i++)\n\t\tstate[i] += S[i];\n}\n\nstatic const uint8_t PAD[64] = {\n\t0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\t0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n};\n\n/* Add padding and terminating bit-count. */\nstatic void\nSHA256_Pad(SHA256_CTX * ctx, uint32_t tmp32[static restrict 72])\n{\n\tsize_t r;\n\n\t/* Figure out how many bytes we have buffered. */\n\tr = (ctx->count >> 3) & 0x3f;\n\n\t/* Pad to 56 mod 64, transforming if we finish a block en route. */\n\tif (r < 56) {\n\t\t/* Pad to 56 mod 64. */\n\t\tmemcpy(&ctx->buf[r], PAD, 56 - r);\n\t} else {\n\t\t/* Finish the current block and mix. */\n\t\tmemcpy(&ctx->buf[r], PAD, 64 - r);\n\t\tSHA256_Transform(ctx->state, ctx->buf, &tmp32[0], &tmp32[64]);\n\n\t\t/* The start of the final block is all zeroes. */\n\t\tmemset(&ctx->buf[0], 0, 56);\n\t}\n\n\t/* Add the terminating bit-count. */\n\tbe64enc(&ctx->buf[56], ctx->count);\n\n\t/* Mix in the final block. */\n\tSHA256_Transform(ctx->state, ctx->buf, &tmp32[0], &tmp32[64]);\n}\n\n/**\n * SHA256_Init(ctx):\n * Initialize the SHA256 context ${ctx}.\n */\nvoid\nSHA256_Init(SHA256_CTX * ctx)\n{\n\n\t/* Zero bits processed so far. */\n\tctx->count = 0;\n\n\t/* Initialize state. */\n\tmemcpy(ctx->state, initial_state, sizeof(initial_state));\n\n#ifdef HWACCEL\n\t/* Ensure that we've chosen the type of hardware acceleration. */\n\thwaccel_init();\n#endif\n}\n\n/**\n * SHA256_Update(ctx, in, len):\n * Input ${len} bytes from ${in} into the SHA256 context ${ctx}.\n */\nstatic void\nSHA256_Update_internal(SHA256_CTX * ctx, const void * in, size_t len,\n    uint32_t tmp32[static restrict 72])\n{\n\tuint32_t r;\n\tconst uint8_t * src = in;\n\n\t/* Return immediately if we have nothing to do. */\n\tif (len == 0)\n\t\treturn;\n\n\t/* Number of bytes left in the buffer from previous updates. */\n\tr = (ctx->count >> 3) & 0x3f;\n\n\t/* Update number of bits. */\n\tctx->count += (uint64_t)(len) << 3;\n\n\t/* Handle the case where we don't need to perform any transforms. */\n\tif (len < 64 - r) {\n\t\tmemcpy(&ctx->buf[r], src, len);\n\t\treturn;\n\t}\n\n\t/* Finish the current block. */\n\tmemcpy(&ctx->buf[r], src, 64 - r);\n\tSHA256_Transform(ctx->state, ctx->buf, &tmp32[0], &tmp32[64]);\n\tsrc += 64 - r;\n\tlen -= 64 - r;\n\n\t/* Perform complete blocks. */\n\twhile (len >= 64) {\n\t\tSHA256_Transform(ctx->state, src, &tmp32[0], &tmp32[64]);\n\t\tsrc += 64;\n\t\tlen -= 64;\n\t}\n\n\t/* Copy left over data into buffer. */\n\tmemcpy(ctx->buf, src, len);\n}\n\n/* Wrapper function for intermediate-values sanitization. */\nvoid\nSHA256_Update(SHA256_CTX * ctx, const void * in, size_t len)\n{\n\tuint32_t tmp32[72];\n\n\t/* Call the real function. */\n\tSHA256_Update_internal(ctx, in, len, tmp32);\n\n\t/* Clean the stack. */\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n}\n\n/**\n * SHA256_Final(digest, ctx):\n * Output the SHA256 hash of the data input to the context ${ctx} into the\n * buffer ${digest}, and clear the context state.\n */\nstatic void\nSHA256_Final_internal(uint8_t digest[32], SHA256_CTX * ctx,\n    uint32_t tmp32[static restrict 72])\n{\n\n\t/* Add padding. */\n\tSHA256_Pad(ctx, tmp32);\n\n\t/* Write the hash. */\n\tbe32enc_vect(digest, ctx->state, 32);\n}\n\n/* Wrapper function for intermediate-values sanitization. */\nvoid\nSHA256_Final(uint8_t digest[32], SHA256_CTX * ctx)\n{\n\tuint32_t tmp32[72];\n\n\t/* Call the real function. */\n\tSHA256_Final_internal(digest, ctx, tmp32);\n\n\t/* Clear the context state. */\n\tinsecure_memzero(ctx, sizeof(SHA256_CTX));\n\n\t/* Clean the stack. */\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n}\n\n/**\n * SHA256_Buf(in, len, digest):\n * Compute the SHA256 hash of ${len} bytes from ${in} and write it to ${digest}.\n */\nvoid\nSHA256_Buf(const void * in, size_t len, uint8_t digest[32])\n{\n\tSHA256_CTX ctx;\n\tuint32_t tmp32[72];\n\n\tSHA256_Init(&ctx);\n\tSHA256_Update_internal(&ctx, in, len, tmp32);\n\tSHA256_Final_internal(digest, &ctx, tmp32);\n\n\t/* Clean the stack. */\n\tinsecure_memzero(&ctx, sizeof(SHA256_CTX));\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n}\n\n/**\n * HMAC_SHA256_Init(ctx, K, Klen):\n * Initialize the HMAC-SHA256 context ${ctx} with ${Klen} bytes of key from\n * ${K}.\n */\nstatic void\nHMAC_SHA256_Init_internal(HMAC_SHA256_CTX * ctx, const void * _k, size_t Klen,\n    uint32_t tmp32[static restrict 72], uint8_t pad[static restrict 64],\n    uint8_t khash[static restrict 32])\n{\n\tconst uint8_t * K = _k;\n\tsize_t i;\n\n\t/* If Klen > 64, the key is really SHA256(K). */\n\tif (Klen > 64) {\n\t\tSHA256_Init(&ctx->ictx);\n\t\tSHA256_Update_internal(&ctx->ictx, K, Klen, tmp32);\n\t\tSHA256_Final_internal(khash, &ctx->ictx, tmp32);\n\t\tK = khash;\n\t\tKlen = 32;\n\t}\n\n\t/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */\n\tSHA256_Init(&ctx->ictx);\n\tmemset(pad, 0x36, 64);\n\tfor (i = 0; i < Klen; i++)\n\t\tpad[i] ^= K[i];\n\tSHA256_Update_internal(&ctx->ictx, pad, 64, tmp32);\n\n\t/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */\n\tSHA256_Init(&ctx->octx);\n\tmemset(pad, 0x5c, 64);\n\tfor (i = 0; i < Klen; i++)\n\t\tpad[i] ^= K[i];\n\tSHA256_Update_internal(&ctx->octx, pad, 64, tmp32);\n}\n\n/* Wrapper function for intermediate-values sanitization. */\nvoid\nHMAC_SHA256_Init(HMAC_SHA256_CTX * ctx, const void * K, size_t Klen)\n{\n\tuint32_t tmp32[72];\n\tuint8_t pad[64];\n\tuint8_t khash[32];\n\n\t/* Call the real function. */\n\tHMAC_SHA256_Init_internal(ctx, K, Klen, tmp32, pad, khash);\n\n\t/* Clean the stack. */\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n\tinsecure_memzero(khash, 32);\n\tinsecure_memzero(pad, 64);\n}\n\n/**\n * HMAC_SHA256_Update(ctx, in, len):\n * Input ${len} bytes from ${in} into the HMAC-SHA256 context ${ctx}.\n */\nstatic void\nHMAC_SHA256_Update_internal(HMAC_SHA256_CTX * ctx, const void * in, size_t len,\n    uint32_t tmp32[static restrict 72])\n{\n\n\t/* Feed data to the inner SHA256 operation. */\n\tSHA256_Update_internal(&ctx->ictx, in, len, tmp32);\n}\n\n/* Wrapper function for intermediate-values sanitization. */\nvoid\nHMAC_SHA256_Update(HMAC_SHA256_CTX * ctx, const void * in, size_t len)\n{\n\tuint32_t tmp32[72];\n\n\t/* Call the real function. */\n\tHMAC_SHA256_Update_internal(ctx, in, len, tmp32);\n\n\t/* Clean the stack. */\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n}\n\n/**\n * HMAC_SHA256_Final(digest, ctx):\n * Output the HMAC-SHA256 of the data input to the context ${ctx} into the\n * buffer ${digest}, and clear the context state.\n */\nstatic void\nHMAC_SHA256_Final_internal(uint8_t digest[32], HMAC_SHA256_CTX * ctx,\n    uint32_t tmp32[static restrict 72], uint8_t ihash[static restrict 32])\n{\n\n\t/* Finish the inner SHA256 operation. */\n\tSHA256_Final_internal(ihash, &ctx->ictx, tmp32);\n\n\t/* Feed the inner hash to the outer SHA256 operation. */\n\tSHA256_Update_internal(&ctx->octx, ihash, 32, tmp32);\n\n\t/* Finish the outer SHA256 operation. */\n\tSHA256_Final_internal(digest, &ctx->octx, tmp32);\n}\n\n/* Wrapper function for intermediate-values sanitization. */\nvoid\nHMAC_SHA256_Final(uint8_t digest[32], HMAC_SHA256_CTX * ctx)\n{\n\tuint32_t tmp32[72];\n\tuint8_t ihash[32];\n\n\t/* Call the real function. */\n\tHMAC_SHA256_Final_internal(digest, ctx, tmp32, ihash);\n\n\t/* Clear the context state. */\n\tinsecure_memzero(ctx, sizeof(HMAC_SHA256_CTX));\n\n\t/* Clean the stack. */\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n\tinsecure_memzero(ihash, 32);\n}\n\n/**\n * HMAC_SHA256_Buf(K, Klen, in, len, digest):\n * Compute the HMAC-SHA256 of ${len} bytes from ${in} using the key ${K} of\n * length ${Klen}, and write the result to ${digest}.\n */\nvoid\nHMAC_SHA256_Buf(const void * K, size_t Klen, const void * in, size_t len,\n    uint8_t digest[32])\n{\n\tHMAC_SHA256_CTX ctx;\n\tuint32_t tmp32[72];\n\tuint8_t tmp8[96];\n\n\tHMAC_SHA256_Init_internal(&ctx, K, Klen, tmp32, &tmp8[0], &tmp8[64]);\n\tHMAC_SHA256_Update_internal(&ctx, in, len, tmp32);\n\tHMAC_SHA256_Final_internal(digest, &ctx, tmp32, &tmp8[0]);\n\n\t/* Clean the stack. */\n\tinsecure_memzero(&ctx, sizeof(HMAC_SHA256_CTX));\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n\tinsecure_memzero(tmp8, 96);\n}\n\n/**\n * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):\n * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and\n * write the output to buf.  The value dkLen must be at most 32 * (2^32 - 1).\n */\nvoid\nPBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * salt,\n    size_t saltlen, uint64_t c, uint8_t * buf, size_t dkLen)\n{\n\tHMAC_SHA256_CTX Phctx, PShctx, hctx;\n\tuint32_t tmp32[72];\n\tuint8_t tmp8[96];\n\tsize_t i;\n\tuint8_t ivec[4];\n\tuint8_t U[32];\n\tuint8_t T[32];\n\tuint64_t j;\n\tint k;\n\tsize_t clen;\n\n#if SIZE_MAX >= (32 * UINT32_MAX)\n\t/* Sanity-check. */\n\tassert(dkLen <= 32 * (size_t)(UINT32_MAX));\n#endif\n\n\t/* Compute HMAC state after processing P. */\n\tHMAC_SHA256_Init_internal(&Phctx, passwd, passwdlen,\n\t    tmp32, &tmp8[0], &tmp8[64]);\n\n\t/* Compute HMAC state after processing P and S. */\n\tmemcpy(&PShctx, &Phctx, sizeof(HMAC_SHA256_CTX));\n\tHMAC_SHA256_Update_internal(&PShctx, salt, saltlen, tmp32);\n\n\t/* Iterate through the blocks. */\n\tfor (i = 0; i * 32 < dkLen; i++) {\n\t\t/* Generate INT(i + 1). */\n\t\tbe32enc(ivec, (uint32_t)(i + 1));\n\n\t\t/* Compute U_1 = PRF(P, S || INT(i)). */\n\t\tmemcpy(&hctx, &PShctx, sizeof(HMAC_SHA256_CTX));\n\t\tHMAC_SHA256_Update_internal(&hctx, ivec, 4, tmp32);\n\t\tHMAC_SHA256_Final_internal(U, &hctx, tmp32, tmp8);\n\n\t\t/* T_i = U_1 ... */\n\t\tmemcpy(T, U, 32);\n\n\t\tfor (j = 2; j <= c; j++) {\n\t\t\t/* Compute U_j. */\n\t\t\tmemcpy(&hctx, &Phctx, sizeof(HMAC_SHA256_CTX));\n\t\t\tHMAC_SHA256_Update_internal(&hctx, U, 32, tmp32);\n\t\t\tHMAC_SHA256_Final_internal(U, &hctx, tmp32, tmp8);\n\n\t\t\t/* ... xor U_j ... */\n\t\t\tfor (k = 0; k < 32; k++)\n\t\t\t\tT[k] ^= U[k];\n\t\t}\n\n\t\t/* Copy as many bytes as necessary into buf. */\n\t\tclen = dkLen - i * 32;\n\t\tif (clen > 32)\n\t\t\tclen = 32;\n\t\tmemcpy(&buf[i * 32], T, clen);\n\t}\n\n\t/* Clean the stack. */\n\tinsecure_memzero(&Phctx, sizeof(HMAC_SHA256_CTX));\n\tinsecure_memzero(&PShctx, sizeof(HMAC_SHA256_CTX));\n\tinsecure_memzero(&hctx, sizeof(HMAC_SHA256_CTX));\n\tinsecure_memzero(tmp32, sizeof(uint32_t) * 72);\n\tinsecure_memzero(tmp8, 96);\n\tinsecure_memzero(U, 32);\n\tinsecure_memzero(T, 32);\n}\n"
  },
  {
    "path": "libcperciva/alg/sha256.h",
    "content": "#ifndef SHA256_H_\n#define SHA256_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/*\n * Use #defines in order to avoid namespace collisions with anyone else's\n * SHA256 code (e.g., the code in OpenSSL).\n */\n#define SHA256_Init libcperciva_SHA256_Init\n#define SHA256_Update libcperciva_SHA256_Update\n#define SHA256_Final libcperciva_SHA256_Final\n#define SHA256_Buf libcperciva_SHA256_Buf\n#define SHA256_CTX libcperciva_SHA256_CTX\n#define HMAC_SHA256_Init libcperciva_HMAC_SHA256_Init\n#define HMAC_SHA256_Update libcperciva_HMAC_SHA256_Update\n#define HMAC_SHA256_Final libcperciva_HMAC_SHA256_Final\n#define HMAC_SHA256_Buf libcperciva_HMAC_SHA256_Buf\n#define HMAC_SHA256_CTX libcperciva_HMAC_SHA256_CTX\n\n/* Context structure for SHA256 operations. */\ntypedef struct {\n\tuint32_t state[8];\n\tuint64_t count;\n\tuint8_t buf[64];\n} SHA256_CTX;\n\n/**\n * SHA256_Init(ctx):\n * Initialize the SHA256 context ${ctx}.\n */\nvoid SHA256_Init(SHA256_CTX *);\n\n/**\n * SHA256_Update(ctx, in, len):\n * Input ${len} bytes from ${in} into the SHA256 context ${ctx}.\n */\nvoid SHA256_Update(SHA256_CTX *, const void *, size_t);\n\n/**\n * SHA256_Final(digest, ctx):\n * Output the SHA256 hash of the data input to the context ${ctx} into the\n * buffer ${digest}, and clear the context state.\n */\nvoid SHA256_Final(uint8_t[32], SHA256_CTX *);\n\n/**\n * SHA256_Buf(in, len, digest):\n * Compute the SHA256 hash of ${len} bytes from ${in} and write it to ${digest}.\n */\nvoid SHA256_Buf(const void *, size_t, uint8_t[32]);\n\n/* Context structure for HMAC-SHA256 operations. */\ntypedef struct {\n\tSHA256_CTX ictx;\n\tSHA256_CTX octx;\n} HMAC_SHA256_CTX;\n\n/**\n * HMAC_SHA256_Init(ctx, K, Klen):\n * Initialize the HMAC-SHA256 context ${ctx} with ${Klen} bytes of key from\n * ${K}.\n */\nvoid HMAC_SHA256_Init(HMAC_SHA256_CTX *, const void *, size_t);\n\n/**\n * HMAC_SHA256_Update(ctx, in, len):\n * Input ${len} bytes from ${in} into the HMAC-SHA256 context ${ctx}.\n */\nvoid HMAC_SHA256_Update(HMAC_SHA256_CTX *, const void *, size_t);\n\n/**\n * HMAC_SHA256_Final(digest, ctx):\n * Output the HMAC-SHA256 of the data input to the context ${ctx} into the\n * buffer ${digest}, and clear the context state.\n */\nvoid HMAC_SHA256_Final(uint8_t[32], HMAC_SHA256_CTX *);\n\n/**\n * HMAC_SHA256_Buf(K, Klen, in, len, digest):\n * Compute the HMAC-SHA256 of ${len} bytes from ${in} using the key ${K} of\n * length ${Klen}, and write the result to ${digest}.\n */\nvoid HMAC_SHA256_Buf(const void *, size_t, const void *, size_t, uint8_t[32]);\n\n/**\n * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):\n * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and\n * write the output to buf.  The value dkLen must be at most 32 * (2^32 - 1).\n */\nvoid PBKDF2_SHA256(const uint8_t *, size_t, const uint8_t *, size_t,\n    uint64_t, uint8_t *, size_t);\n\n#endif /* !SHA256_H_ */\n"
  },
  {
    "path": "libcperciva/alg/sha256_arm.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_ARM_SHA256\n/**\n * CPUSUPPORT CFLAGS: ARM_SHA256\n */\n\n#include <assert.h>\n#include <stddef.h>\n#include <stdint.h>\n\n#ifdef __ARM_NEON\n#include <arm_neon.h>\n#endif\n\n#include \"sha256_arm.h\"\n\n/* SHA256 round constants. */\nstatic const uint32_t Krnd[64] = {\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n\t0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n\t0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n\t0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n\t0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n\t0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n\t0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n\t0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n\t0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n};\n\n/* Round computation. */\n#define RND4(S, M, Kp) do {\t\t\t\t\t\\\n\tuint32x4_t S0_step;\t\t\t\t\t\\\n\tuint32x4_t Wk;\t\t\t\t\t\t\\\n\tS0_step = S[0];\t\t\t\t\t\t\\\n\tWk = vaddq_u32(M, vld1q_u32(Kp));\t\t\t\\\n\tS[0] = vsha256hq_u32(S[0], S[1], Wk);\t\t\t\\\n\tS[1] = vsha256h2q_u32(S[1], S0_step, Wk);\t\t\\\n} while (0)\n\n/* Message schedule computation */\n#define MSG4(X0, X1, X2, X3)\t\t\t\t\t\\\n\tX0 = vsha256su1q_u32(vsha256su0q_u32(X0, X1), X2, X3)\n\n/**\n * SHA256_Transform_arm(state, block):\n * Compute the SHA256 block compression function, transforming ${state} using\n * the data in ${block}.  This implementation uses ARM SHA256 instructions,\n * and should only be used if _SHA256 is defined and cpusupport_arm_sha256()\n * returns nonzero.\n */\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nvoid\nSHA256_Transform_arm(uint32_t state[8], const uint8_t block[64])\n#else\nvoid\nSHA256_Transform_arm(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64])\n#endif\n{\n\tuint32x4_t Y[4];\n\tuint32x4_t S[2];\n\tuint32x4_t _state[2];\n\tint i;\n\n\t/* 1. Prepare the first part of the message schedule W. */\n\tY[0] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(&block[0])));\n\tY[1] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(&block[16])));\n\tY[2] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(&block[32])));\n\tY[3] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(&block[48])));\n\n\t/* 2. Initialize working variables. */\n\tS[0] = _state[0] = vld1q_u32(&state[0]);\n\tS[1] = _state[1] = vld1q_u32(&state[4]);\n\n\t/* 3. Mix. */\n\tfor (i = 0; i < 64; i += 16) {\n\t\tRND4(S, Y[0], &Krnd[i + 0]);\n\t\tRND4(S, Y[1], &Krnd[i + 4]);\n\t\tRND4(S, Y[2], &Krnd[i + 8]);\n\t\tRND4(S, Y[3], &Krnd[i + 12]);\n\n\t\tif (i == 48)\n\t\t\tbreak;\n\t\tMSG4(Y[0], Y[1], Y[2], Y[3]);\n\t\tMSG4(Y[1], Y[2], Y[3], Y[0]);\n\t\tMSG4(Y[2], Y[3], Y[0], Y[1]);\n\t\tMSG4(Y[3], Y[0], Y[1], Y[2]);\n\t}\n\n\t/* 4. Mix local working variables into global state. */\n\tvst1q_u32(&state[0], vaddq_u32(_state[0], S[0]));\n\tvst1q_u32(&state[4], vaddq_u32(_state[1], S[1]));\n}\n#endif /* CPUSUPPORT_ARM_SHA256 */\n"
  },
  {
    "path": "libcperciva/alg/sha256_arm.h",
    "content": "#ifndef SHA256_ARM_H_\n#define SHA256_ARM_H_\n\n#include <stdint.h>\n\n/**\n * SHA256_Transform_arm(state, block):\n * Compute the SHA256 block compression function, transforming ${state} using\n * the data in ${block}.  This implementation uses ARM SHA256 instructions,\n * and should only be used if _SHA256 is defined and cpusupport_arm_sha256()\n * returns nonzero.\n */\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nvoid SHA256_Transform_arm(uint32_t state[8], const uint8_t block[64]);\n#else\nvoid SHA256_Transform_arm(uint32_t[static restrict 8],\n    const uint8_t[static restrict 64]);\n#endif\n\n#endif /* !SHA256_ARM_H_ */\n"
  },
  {
    "path": "libcperciva/alg/sha256_shani.c",
    "content": "#include \"cpusupport.h\"\n#if defined(CPUSUPPORT_X86_SHANI) && defined(CPUSUPPORT_X86_SSSE3)\n/**\n * CPUSUPPORT CFLAGS: X86_SHANI X86_SSSE3\n */\n\n#include <immintrin.h>\n#include <stdint.h>\n\n#include \"sha256_shani.h\"\n\n/**\n * This code uses intrinsics from the following feature sets:\n * SHANI: _mm_sha256msg1_epu32, _mm_sha256msg2_epu32, _mm_sha256rnds2_epu32\n * SSSE3: _mm_shuffle_epi8, _mm_alignr_epi8\n * SSE2: Everything else\n *\n * The SSSE3 intrinsics could be avoided at a slight cost by using a few SSE2\n * instructions in their place; we have not done this since to our knowledge\n * there are presently no CPUs which support the SHANI instruction set but do\n * not support SSSE3.\n */\n\n/* Load 32-bit big-endian words. */\nstatic __m128i\nbe32dec_128(const uint8_t * src)\n{\n\tconst __m128i SHUF = _mm_set_epi8(12, 13, 14, 15, 8, 9, 10, 11,\n\t    4, 5, 6, 7, 0, 1, 2, 3);\n\t__m128i x;\n\n\t/* Load four 32-bit words. */\n\tx = _mm_loadu_si128((const __m128i *)src);\n\n\t/* Reverse the order of the bytes in each word. */\n\treturn (_mm_shuffle_epi8(x, SHUF));\n}\n\n/* Convert an unsigned 32-bit immediate into a signed value. */\n#define I32(a) ((UINT32_C(a) >= UINT32_C(0x80000000)) ?\t\t\t\\\n    -(int32_t)(UINT32_C(0xffffffff) - UINT32_C(a)) - 1 : (int32_t)INT32_C(a))\n\n/* Load four unsigned 32-bit immediates into a vector register. */\n#define IMM4(a, b, c, d) _mm_set_epi32(I32(a), I32(b), I32(c), I32(d))\n\n/* Run four rounds of SHA256. */\n#define RND4(S, W, K0, K1, K2, K3) do {\t\t\t\t\t\t\\\n\t__m128i M;\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\\\n\t/* Add the next four words of message schedule and round constants. */\t\\\n\tM = _mm_add_epi32(W, IMM4(K3, K2, K1, K0));\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\\\n\t/* Perform two rounds of SHA256, using the low two words in M. */\t\\\n\tS[1] = _mm_sha256rnds2_epu32(S[1], S[0], M);\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\\\n\t/* Shift the two words of M down and perform the next two rounds. */\t\\\n\tM = _mm_srli_si128(M, 8);\t\t\t\t\t\t\\\n\tS[0] = _mm_sha256rnds2_epu32(S[0], S[1], M);\t\t\t\t\\\n} while (0)\n\n/* Compute the ith set of four words of message schedule. */\n#define MSG4(W, i) do {\t\t\t\t\t\t\t\t\\\n\tW[(i + 0) % 4] = _mm_sha256msg1_epu32(W[(i + 0) % 4], W[(i + 1) % 4]);\t\\\n\tW[(i + 0) % 4] = _mm_add_epi32(W[(i + 0) % 4],\t\t\t\t\\\n\t    _mm_alignr_epi8(W[(i + 3) % 4], W[(i + 2) % 4], 4));\t\t\\\n\tW[(i + 0) % 4] = _mm_sha256msg2_epu32(W[(i + 0) % 4], W[(i + 3) % 4]);\t\\\n} while (0)\n\n/* Perform 4 rounds of SHA256 and generate more message schedule if needed. */\n#define RNDMSG(S, W, i, K0, K1, K2, K3) do {\t\t\t\\\n\tRND4(S, W[i % 4], K0, K1, K2, K3);\t\t\t\\\n\tif (i < 12)\t\t\t\t\t\t\\\n\t\tMSG4(W, i + 4);\t\t\t\t\t\\\n} while (0)\n\n/**\n * SHA256_Transform_shani(state, block):\n * Compute the SHA256 block compression function, transforming ${state} using\n * the data in ${block}.  This implementation uses x86 SHANI and SSSE3\n * instructions, and should only be used if CPUSUPPORT_X86_SHANI and _SSSE3\n * are defined and cpusupport_x86_shani() and _ssse3() return nonzero.\n */\nvoid\nSHA256_Transform_shani(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64])\n{\n\t__m128i S3210, S7654;\n\t__m128i S0123, S4567;\n\t__m128i S0145, S2367;\n\t__m128i W[4];\n\t__m128i S[2];\n\n\t/* Load state. */\n\tS3210 = _mm_loadu_si128((const __m128i *)&state[0]);\n\tS7654 = _mm_loadu_si128((const __m128i *)&state[4]);\n\n\t/* Shuffle the 8 32-bit values into the order we need them. */\n\tS0123 = _mm_shuffle_epi32(S3210, 0x1B);\n\tS4567 = _mm_shuffle_epi32(S7654, 0x1B);\n\tS0145 = _mm_unpackhi_epi64(S4567, S0123);\n\tS2367 = _mm_unpacklo_epi64(S4567, S0123);\n\n\t/* Load input block; this is the start of the message schedule. */\n\tW[0] = be32dec_128(&block[0]);\n\tW[1] = be32dec_128(&block[16]);\n\tW[2] = be32dec_128(&block[32]);\n\tW[3] = be32dec_128(&block[48]);\n\n\t/* Initialize working variables. */\n\tS[0] = S0145;\n\tS[1] = S2367;\n\n\t/* Perform 64 rounds, 4 at a time. */\n\tRNDMSG(S, W, 0, 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5);\n\tRNDMSG(S, W, 1, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5);\n\tRNDMSG(S, W, 2, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3);\n\tRNDMSG(S, W, 3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174);\n\tRNDMSG(S, W, 4, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc);\n\tRNDMSG(S, W, 5, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da);\n\tRNDMSG(S, W, 6, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7);\n\tRNDMSG(S, W, 7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967);\n\tRNDMSG(S, W, 8, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13);\n\tRNDMSG(S, W, 9, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85);\n\tRNDMSG(S, W, 10, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3);\n\tRNDMSG(S, W, 11, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070);\n\tRNDMSG(S, W, 12, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5);\n\tRNDMSG(S, W, 13, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3);\n\tRNDMSG(S, W, 14, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208);\n\tRNDMSG(S, W, 15, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2);\n\n\t/* Mix local working variables into global state. */\n\tS0145 = _mm_add_epi32(S0145, S[0]);\n\tS2367 = _mm_add_epi32(S2367, S[1]);\n\n\t/* Shuffle state back to the original word order and store. */\n\tS0123 = _mm_unpackhi_epi64(S2367, S0145);\n\tS4567 = _mm_unpacklo_epi64(S2367, S0145);\n\tS3210 = _mm_shuffle_epi32(S0123, 0x1B);\n\tS7654 = _mm_shuffle_epi32(S4567, 0x1B);\n\t_mm_storeu_si128((__m128i *)&state[0], S3210);\n\t_mm_storeu_si128((__m128i *)&state[4], S7654);\n}\n#endif /* CPUSUPPORT_X86_SHANI && CPUSUPPORT_X86_SSSE3 */\n"
  },
  {
    "path": "libcperciva/alg/sha256_shani.h",
    "content": "#ifndef SHA256_SHANI_H_\n#define SHA256_SHANI_H_\n\n#include <stdint.h>\n\n/**\n * SHA256_Transform_shani(state, block):\n * Compute the SHA256 block compression function, transforming ${state} using\n * the data in ${block}.  This implementation uses x86 SHANI and SSSE3\n * instructions, and should only be used if CPUSUPPORT_X86_SHANI and _SSSE3\n * are defined and cpusupport_x86_shani() and _ssse3() return nonzero.\n */\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nvoid SHA256_Transform_shani(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64]);\n#else\nvoid SHA256_Transform_shani(uint32_t[static restrict 8],\n    const uint8_t[static restrict 64]);\n#endif\n\n#endif /* !SHA256_SHANI_H_ */\n"
  },
  {
    "path": "libcperciva/alg/sha256_sse2.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_X86_SSE2\n/**\n * CPUSUPPORT CFLAGS: X86_SSE2\n */\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n\n#include <emmintrin.h>\n\n#include \"sha256_sse2.h\"\n\n/**\n * mm_bswap_epi32(a):\n * Byte-swap each 32-bit word.\n */\nstatic inline __m128i\nmm_bswap_epi32(__m128i a)\n{\n\n\t/* Swap bytes in each 16-bit word. */\n\ta = _mm_or_si128(_mm_slli_epi16(a, 8), _mm_srli_epi16(a, 8));\n\n\t/* Swap all 16-bit words. */\n\ta = _mm_shufflelo_epi16(a, _MM_SHUFFLE(2, 3, 0, 1));\n\ta = _mm_shufflehi_epi16(a, _MM_SHUFFLE(2, 3, 0, 1));\n\n\treturn (a);\n}\n\n/* SHA256 round constants. */\nstatic const uint32_t Krnd[64] = {\n\t0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n\t0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n\t0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n\t0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n\t0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n\t0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n\t0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n\t0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n\t0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n\t0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n\t0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n\t0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n\t0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n\t0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n\t0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n\t0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n};\n\n/* Elementary functions used by SHA256 */\n#define Ch(x, y, z)\t((x & (y ^ z)) ^ z)\n#define Maj(x, y, z)\t((x & (y | z)) | (y & z))\n#define ROTR(x, n)\t((x >> n) | (x << (32 - n)))\n#define S0(x)\t\t(ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))\n#define S1(x)\t\t(ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))\n\n/* SHA256 round function */\n#define RND(a, b, c, d, e, f, g, h, k)\t\t\t\\\n\th += S1(e) + Ch(e, f, g) + k;\t\t\t\\\n\td += h;\t\t\t\t\t\t\\\n\th += S0(a) + Maj(a, b, c)\n\n/* Adjusted round function for rotating state */\n#define RNDr(S, W, i, ii)\t\t\t\\\n\tRND(S[(64 - i) % 8], S[(65 - i) % 8],\t\\\n\t    S[(66 - i) % 8], S[(67 - i) % 8],\t\\\n\t    S[(68 - i) % 8], S[(69 - i) % 8],\t\\\n\t    S[(70 - i) % 8], S[(71 - i) % 8],\t\\\n\t    W[i + ii] + Krnd[i + ii])\n\n/* Message schedule computation */\n#define SHR32(x, n) (_mm_srli_epi32(x, n))\n#define ROTR32(x, n) (_mm_or_si128(SHR32(x, n), _mm_slli_epi32(x, (32-n))))\n#define s0_128(x) _mm_xor_si128(_mm_xor_si128(\t\t\t\\\n\tROTR32(x, 7), ROTR32(x, 18)), SHR32(x, 3))\n\nstatic inline __m128i\ns1_128_high(__m128i a)\n{\n\t__m128i b;\n\t__m128i c;\n\n\t/* ROTR, loading data as {B, B, A, A}; lanes 1 & 3 will be junk. */\n\tb = _mm_shuffle_epi32(a, _MM_SHUFFLE(1, 1, 0, 0));\n\tc = _mm_xor_si128(_mm_srli_epi64(b, 17), _mm_srli_epi64(b, 19));\n\n\t/* Shift and XOR with rotated data; lanes 1 & 3 will be junk. */\n\tc = _mm_xor_si128(c, _mm_srli_epi32(b, 10));\n\n\t/* Shuffle good data back and zero unwanted lanes. */\n\tc = _mm_shuffle_epi32(c, _MM_SHUFFLE(2, 0, 2, 0));\n\tc = _mm_slli_si128(c, 8);\n\n\treturn (c);\n}\n\nstatic inline __m128i\ns1_128_low(__m128i a)\n{\n\t__m128i b;\n\t__m128i c;\n\n\t/* ROTR, loading data as {B, B, A, A}; lanes 1 & 3 will be junk. */\n\tb = _mm_shuffle_epi32(a, _MM_SHUFFLE(3, 3, 2, 2));\n\tc = _mm_xor_si128(_mm_srli_epi64(b, 17), _mm_srli_epi64(b, 19));\n\n\t/* Shift and XOR with rotated data; lanes 1 & 3 will be junk. */\n\tc = _mm_xor_si128(c, _mm_srli_epi32(b, 10));\n\n\t/* Shuffle good data back and zero unwanted lanes. */\n\tc = _mm_shuffle_epi32(c, _MM_SHUFFLE(2, 0, 2, 0));\n\tc = _mm_srli_si128(c, 8);\n\n\treturn (c);\n}\n\n/**\n * SPAN_ONE_THREE(a, b):\n * Combine the upper three words of ${a} with the lowest word of ${b}.  This\n * could also be thought of returning bits [159:32] of the 256-bit value\n * consisting of (b[127:0] a[127:0]).  In other words, set:\n *     dst[31:0] := a[63:32]\n *     dst[63:32] := a[95:64]\n *     dst[95:64] := a[127:96]\n *     dst[127:96] := b[31:0]\n */\n#define SPAN_ONE_THREE(a, b) (_mm_shuffle_epi32(_mm_castps_si128(\t\\\n\t_mm_move_ss(_mm_castsi128_ps(a), _mm_castsi128_ps(b))),\t\t\\\n\t_MM_SHUFFLE(0, 3, 2, 1)))\n\n/**\n * MSG4(X0, X1, X2, X3):\n * Calculate the next four values of the message schedule.  If we define\n * ${W[j]} as the first unknown value in the message schedule, then the input\n * arguments are:\n *     X0 = W[j - 16] : W[j - 13]\n *     X1 = W[j - 12] : W[j - 9]\n *     X2 = W[j - 8] : W[j - 5]\n *     X3 = W[j - 4] : W[j - 1]\n * This function therefore calculates:\n *     X4 = W[j + 0] : W[j + 3]\n */\nstatic inline __m128i\nMSG4(__m128i X0, __m128i X1, __m128i X2, __m128i X3)\n{\n\t__m128i X4;\n\t__m128i Xj_minus_seven, Xj_minus_fifteen;\n\n\t/* Set up variables which span X values. */\n\tXj_minus_seven = SPAN_ONE_THREE(X2, X3);\n\tXj_minus_fifteen = SPAN_ONE_THREE(X0, X1);\n\n\t/* Begin computing X4. */\n\tX4 = _mm_add_epi32(X0, Xj_minus_seven);\n\tX4 = _mm_add_epi32(X4, s0_128(Xj_minus_fifteen));\n\n\t/* First half of s1. */\n\tX4 = _mm_add_epi32(X4, s1_128_low(X3));\n\n\t/* Second half of s1; this depends on the above value of X4. */\n\tX4 = _mm_add_epi32(X4, s1_128_high(X4));\n\n\treturn (X4);\n}\n\n/**\n * SHA256_Transform_sse2(state, block, W, S):\n * Compute the SHA256 block compression function, transforming ${state} using\n * the data in ${block}.  This implementation uses x86 SSE2 instructions, and\n * should only be used if _SSE2 is defined and cpusupport_x86_sse2() returns\n * nonzero.  The arrays W and S may be filled with sensitive data, and should\n * be cleared by the callee.\n */\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nvoid\nSHA256_Transform_sse2(uint32_t state[8], const uint8_t block[64],\n    uint32_t W[64], uint32_t S[8])\n#else\nvoid\nSHA256_Transform_sse2(uint32_t state[static restrict 8],\n    const uint8_t block[static restrict 64], uint32_t W[static restrict 64],\n    uint32_t S[static restrict 8])\n#endif\n{\n\t__m128i Y[4];\n\tint i;\n\n\t/* 1. Prepare the first part of the message schedule W. */\n\tY[0] = mm_bswap_epi32(_mm_loadu_si128((const __m128i *)&block[0]));\n\t_mm_storeu_si128((__m128i *)&W[0], Y[0]);\n\tY[1] = mm_bswap_epi32(_mm_loadu_si128((const __m128i *)&block[16]));\n\t_mm_storeu_si128((__m128i *)&W[4], Y[1]);\n\tY[2] = mm_bswap_epi32(_mm_loadu_si128((const __m128i *)&block[32]));\n\t_mm_storeu_si128((__m128i *)&W[8], Y[2]);\n\tY[3] = mm_bswap_epi32(_mm_loadu_si128((const __m128i *)&block[48]));\n\t_mm_storeu_si128((__m128i *)&W[12], Y[3]);\n\n\t/* 2. Initialize working variables. */\n\tmemcpy(S, state, 32);\n\n\t/* 3. Mix. */\n\tfor (i = 0; i < 64; i += 16) {\n\t\tRNDr(S, W, 0, i);\n\t\tRNDr(S, W, 1, i);\n\t\tRNDr(S, W, 2, i);\n\t\tRNDr(S, W, 3, i);\n\t\tRNDr(S, W, 4, i);\n\t\tRNDr(S, W, 5, i);\n\t\tRNDr(S, W, 6, i);\n\t\tRNDr(S, W, 7, i);\n\t\tRNDr(S, W, 8, i);\n\t\tRNDr(S, W, 9, i);\n\t\tRNDr(S, W, 10, i);\n\t\tRNDr(S, W, 11, i);\n\t\tRNDr(S, W, 12, i);\n\t\tRNDr(S, W, 13, i);\n\t\tRNDr(S, W, 14, i);\n\t\tRNDr(S, W, 15, i);\n\n\t\tif (i == 48)\n\t\t\tbreak;\n\t\tY[0] = MSG4(Y[0], Y[1], Y[2], Y[3]);\n\t\t_mm_storeu_si128((__m128i *)&W[16 + i + 0], Y[0]);\n\t\tY[1] = MSG4(Y[1], Y[2], Y[3], Y[0]);\n\t\t_mm_storeu_si128((__m128i *)&W[16 + i + 4], Y[1]);\n\t\tY[2] = MSG4(Y[2], Y[3], Y[0], Y[1]);\n\t\t_mm_storeu_si128((__m128i *)&W[16 + i + 8], Y[2]);\n\t\tY[3] = MSG4(Y[3], Y[0], Y[1], Y[2]);\n\t\t_mm_storeu_si128((__m128i *)&W[16 + i + 12], Y[3]);\n\t}\n\n\t/* 4. Mix local working variables into global state. */\n\tfor (i = 0; i < 8; i++)\n\t\tstate[i] += S[i];\n}\n#endif /* CPUSUPPORT_X86_SSE2 */\n"
  },
  {
    "path": "libcperciva/alg/sha256_sse2.h",
    "content": "#ifndef SHA256_SSE2_H_\n#define SHA256_SSE2_H_\n\n#include <stdint.h>\n\n/**\n * SHA256_Transform_sse2(state, block, W, S):\n * Compute the SHA256 block compression function, transforming ${state} using\n * the data in ${block}.  This implementation uses x86 SSE2 instructions, and\n * should only be used if _SSE2 is defined and cpusupport_x86_sse2() returns\n * nonzero.  The arrays W and S may be filled with sensitive data, and should\n * be cleared by the callee.\n */\n#ifdef POSIXFAIL_ABSTRACT_DECLARATOR\nvoid SHA256_Transform_sse2(uint32_t state[8],\n    const uint8_t block[64], uint32_t W[64], uint32_t S[8]);\n#else\nvoid SHA256_Transform_sse2(uint32_t[static restrict 8],\n    const uint8_t[static restrict 64], uint32_t W[static restrict 64],\n    uint32_t S[static restrict 8]);\n#endif\n\n#endif /* !SHA256_SSE2_H_ */\n"
  },
  {
    "path": "libcperciva/apisupport/Build/apisupport-LIBCRYPTO-LOW_LEVEL_AES.c",
    "content": "#include <stdint.h>\n\n#include <openssl/aes.h>\n\nint\nmain(void)\n{\n\tAES_KEY kexp_actual;\n\tconst uint8_t key_unexpanded[16] = { 0 };\n\n\tAES_set_encrypt_key(key_unexpanded, 128, &kexp_actual);\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/apisupport/Build/apisupport-NONPOSIX-MEMLIMIT.c",
    "content": "#include \"platform.h\"\n\n#ifdef HAVE_SYS_PARAM_H\n#include <sys/param.h>\n#endif\n#ifdef HAVE_SYS_SYSCTL_H\n#include <sys/sysctl.h>\n#endif\n#ifdef HAVE_SYS_SYSINFO_H\n#include <sys/sysinfo.h>\n#endif\n\nint\nmain(void)\n{\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/apisupport/Build/apisupport.sh",
    "content": "# Should be sourced by `command -p sh path/to/apisupport.sh \"$PATH\"` from\n# within a Makefile.\nif ! [ \"${PATH}\" = \"$1\" ]; then\n\techo \"WARNING: POSIX violation: ${SHELL}'s command -p resets \\$PATH\" 1>&2\n\tPATH=$1\nfi\n\n# Standard output should be written to apisupport-config.h, which is both a\n# C header file defining APISUPPORT_PLATFORM_FEATURE macros and sourceable sh\n# code which sets CFLAGS_PLATFORM_FEATURE environment variables.\nSRCDIR=$(command -p dirname \"$0\")\n\nCFLAGS_HARDCODED=\"-D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700\"\n\n# Do we want to record stderr to a file?\nif [ \"${DEBUG:-0}\" -eq \"0\" ]; then\n\toutcc=\"/dev/null\"\nelse\n\toutcc=\"apisupport-stderr.log\"\n\trm -f \"${outcc}\"\nfi\n\nfeature() {\n\tPLATFORM=$1\n\tFEATURE=$2\n\tEXTRALIB=$3\n\tshift 3;\n\n\t# Bail if we didn't include this feature in this source tree.\n\tfeature_filename=\"${SRCDIR}/apisupport-${PLATFORM}-${FEATURE}.c\"\n\tif ! [ -f \"${feature_filename}\" ]; then\n\t\treturn\n\tfi\n\n\t# Check if we can compile this feature (and any required arguments).\n\tprintf \"Checking if compiler supports %s %s feature...\"\t\t\\\n\t    \"${PLATFORM}\" \"${FEATURE}\" 1>&2\n\tfor API_CFLAGS in \"$@\"; do\n\t\tif ${CC} ${CPPFLAGS} ${CFLAGS} ${CFLAGS_HARDCODED}\t\\\n\t\t    ${API_CFLAGS} \"${feature_filename}\" ${LDADD_EXTRA}\t\\\n\t\t    ${EXTRALIB}\t2>>\"${outcc}\"; then\n\t\t\trm -f a.out\n\t\t\tbreak;\n\t\tfi\n\t\tAPI_CFLAGS=NOTSUPPORTED;\n\tdone\n\tcase ${API_CFLAGS} in\n\tNOTSUPPORTED)\n\t\techo \" no\" 1>&2\n\t\t;;\n\t\"\")\n\t\techo \" yes\" 1>&2\n\t\techo \"#define APISUPPORT_${PLATFORM}_${FEATURE} 1\"\n\t\t;;\n\t*)\n\t\techo \" yes, via ${API_CFLAGS}\" 1>&2\n\t\techo \"#define APISUPPORT_${PLATFORM}_${FEATURE} 1\"\n\t\techo \"#ifdef apisupport_dummy\"\n\t\techo \"export CFLAGS_${PLATFORM}_${FEATURE}=\\\"${API_CFLAGS}\\\"\"\n\t\techo \"#endif\"\n\t\t;;\n\tesac\n}\n\nif [ \"$2\" = \"--all\" ]; then\n\tfeature() {\n\t\tPLATFORM=$1\n\t\tFEATURE=$2\n\t\techo \"#define APISUPPORT_${PLATFORM}_${FEATURE} 1\"\n\t}\nfi\n\n# Detect how to compile non-POSIX code.\nfeature NONPOSIX SETGROUPS \"\" \"\"\t\t\t\\\n\t\"-U_POSIX_C_SOURCE -U_XOPEN_SOURCE\"\t\t\\\n\t\"-U_POSIX_C_SOURCE -U_XOPEN_SOURCE -Wno-reserved-id-macro\"\nfeature NONPOSIX MEMLIMIT \"\" \"\"\t\t\t\t\\\n\t\"-U_POSIX_C_SOURCE -U_XOPEN_SOURCE\"\t\t\\\n\t\"-U_POSIX_C_SOURCE -U_XOPEN_SOURCE -Wno-reserved-id-macro\"\n\n# Detect how to compile libssl and libcrypto code.\nfeature LIBSSL HOST_NAME \"-lssl\" \"\"\t\t\t\\\n\t\"-Wno-cast-qual\"\nfeature LIBCRYPTO LOW_LEVEL_AES \"-lcrypto\" \"\"\t\t\\\n\t\"-Wno-deprecated-declarations\"\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-ARM-AES.c",
    "content": "#include <stdint.h>\n\n#ifdef __ARM_NEON\n#include <arm_neon.h>\n#endif\n\nint\nmain(void)\n{\n\tuint8x16_t data;\n\tuint8x16_t key = {0};\n\tuint8x16_t output;\n\tuint32x4_t lanes = {0};\n\tuint8_t arr[16] = {0};\n\n\t/* Check AES. */\n\tdata = vld1q_u8(arr);\n\toutput = vaeseq_u8(data, key);\n\t(void)output; /* UNUSED */\n\n\t/* Check _u32: some compilers only support the _u8 variant. */\n\tlanes = vdupq_laneq_u32(lanes, 0);\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-ARM-SHA256.c",
    "content": "#ifdef __ARM_NEON\n#include <arm_neon.h>\n#endif\n\nint\nmain(void)\n{\n\tuint32x4_t w0 = {0};\n\tuint32x4_t w4 = {0};\n\tuint32x4_t output;\n\n\toutput = vsha256su0q_u32(w0, w4);\n\t(void)output; /* UNUSED */\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-HWCAP-ELF_AUX_INFO.c",
    "content": "#include <sys/auxv.h>\n\nint\nmain(void)\n{\n\tint res;\n\tunsigned long val;\n\n\tres = elf_aux_info(AT_HWCAP, &val, sizeof(unsigned long));\n\t(void)res;\n\n\treturn (val != 0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-HWCAP-GETAUXVAL.c",
    "content": "#include <sys/auxv.h>\n\nint\nmain(void)\n{\n\tunsigned long val;\n\n\tval = getauxval(AT_HWCAP);\n\n\treturn (val != 0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-AESNI.c",
    "content": "#include <stdint.h>\n\n#include <wmmintrin.h>\n\n/*\n * Use a separate function for this, because that means that the alignment of\n * the _mm_loadu_si128() will move to function level, which may require\n * -Wno-cast-align.\n */\nstatic __m128i\nload_128(const uint8_t * src)\n{\n\t__m128i x;\n\n\tx = _mm_loadu_si128((const __m128i *)src);\n\treturn (x);\n}\n\nint\nmain(void)\n{\n\t__m128i x, y;\n\tuint8_t a[16] = {0};\n\n\tx = load_128(a);\n#ifdef BROKEN_MM_LOADU_SI64\n\ty = _mm_loadu_si128((const __m128i *)a);\n#else\n\ty = _mm_loadu_si64(a);\n#endif\n\ty = _mm_aesenc_si128(x, y);\n\t_mm_storeu_si128((__m128i *)&a[0], y);\n\treturn (a[0]);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-CPUID.c",
    "content": "#include <cpuid.h>\n\nint\nmain(void)\n{\n\tunsigned int a, b, c, d;\n\n\treturn (__get_cpuid(0, &a, &b, &c, &d));\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-CPUID_COUNT.c",
    "content": "#include <cpuid.h>\n\nint\nmain(void)\n{\n\tunsigned int a, b, c, d;\n\n\t__cpuid_count(7, 0, a, b, c, d);\n\treturn ((int)a);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-RDRAND.c",
    "content": "#include <immintrin.h>\n\nint\nmain(void)\n{\n\tunsigned int x;\n\n\treturn (!_rdrand32_step(&x));\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-SHANI.c",
    "content": "#include <immintrin.h>\n#include <stdint.h>\n\n/*\n * Use a separate function for this, because that means that the alignment of\n * the _mm_loadu_si128() will move to function level, which may require\n * -Wno-cast-align.\n */\nstatic __m128i\nload_128(const uint8_t * src)\n{\n\t__m128i x;\n\n\tx = _mm_loadu_si128((const __m128i *)src);\n\treturn (x);\n}\n\nint\nmain(void)\n{\n\t__m128i x;\n\tuint8_t a[16] = {0};\n\n\tx = load_128(a);\n\tx = _mm_sha256msg1_epu32(x, x);\n\t_mm_storeu_si128((__m128i *)a, x);\n\treturn (a[0]);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-SSE2.c",
    "content": "#include <emmintrin.h>\n\nstatic char a[16];\n\n/*\n * Use a separate function for this, because that means that the alignment of\n * the _mm_loadu_si128() will move to function level, which may require\n * -Wno-cast-align.\n */\nstatic __m128i\nload_128(const char * src)\n{\n\t__m128i x;\n\n\tx = _mm_loadu_si128((const __m128i *)src);\n\treturn (x);\n}\n\nint\nmain(void)\n{\n\t__m128i x;\n\n\tx = load_128(a);\n\t_mm_storeu_si128((__m128i *)a, x);\n\treturn (a[0]);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport-X86-SSSE3.c",
    "content": "#include <emmintrin.h>\n#include <tmmintrin.h>\n\nstatic char a[16];\n\n/*\n * Use a separate function for this, because that means that the alignment of\n * the _mm_loadu_si128() will move to function level, which may require\n * -Wno-cast-align.\n */\nstatic __m128i\nload_128(const char * src)\n{\n\t__m128i x;\n\n\tx = _mm_loadu_si128((const __m128i *)src);\n\treturn (x);\n}\n\nint\nmain(void)\n{\n\t__m128i x;\n\n\tx = load_128(a);\n\tx = _mm_alignr_epi8(x, x, 8);\n\t_mm_storeu_si128((__m128i *)a, x);\n\treturn (a[0]);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/Build/cpusupport.sh",
    "content": "# Should be sourced by `command -p sh path/to/cpusupport.sh \"$PATH\"` from\n# within a Makefile.\nif ! [ \"${PATH}\" = \"$1\" ]; then\n\techo \"WARNING: POSIX violation: ${SHELL}'s command -p resets \\$PATH\" 1>&2\n\tPATH=$1\nfi\n\n# Standard output should be written to cpusupport-config.h, which is both a\n# C header file defining CPUSUPPORT_ARCH_FEATURE macros and sourceable sh\n# code which sets CFLAGS_ARCH_FEATURE environment variables.\nSRCDIR=$(command -p dirname \"$0\")\n\nCFLAGS_HARDCODED=\"-D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700\"\n\n# Do we want to record stderr to a file?\nif [ \"${DEBUG:-0}\" -eq \"0\" ]; then\n\toutcc=\"/dev/null\"\nelse\n\toutcc=\"cpusupport-stderr.log\"\n\trm -f \"${outcc}\"\nfi\n\nfeature() {\n\tARCH=$1\n\tFEATURE=$2\n\tshift 2;\n\n\t# Bail if we didn't include this feature in this source tree.\n\tfeature_filename=\"${SRCDIR}/cpusupport-${ARCH}-${FEATURE}.c\"\n\tif ! [ -f \"${feature_filename}\" ]; then\n\t\treturn\n\tfi\n\n\t# Check if we can compile this feature (and any required arguments).\n\tprintf \"Checking if compiler supports %s %s feature...\"\t\t\\\n\t    \"${ARCH}\" \"${FEATURE}\" 1>&2\n\tfor CPU_CFLAGS in \"$@\"; do\n\t\tif ${CC} ${CPPFLAGS} ${CFLAGS} ${CFLAGS_HARDCODED}\t\\\n\t\t    ${CPU_CFLAGS} \"${feature_filename}\" 2>>\"${outcc}\"; then\n\t\t\trm -f a.out\n\t\t\tbreak;\n\t\tfi\n\t\tCPU_CFLAGS=NOTSUPPORTED;\n\tdone\n\tcase ${CPU_CFLAGS} in\n\tNOTSUPPORTED)\n\t\techo \" no\" 1>&2\n\t\t;;\n\t\"\")\n\t\techo \" yes\" 1>&2\n\t\techo \"#define CPUSUPPORT_${ARCH}_${FEATURE} 1\"\n\t\t;;\n\t*)\n\t\techo \" yes, via ${CPU_CFLAGS}\" 1>&2\n\t\techo \"#define CPUSUPPORT_${ARCH}_${FEATURE} 1\"\n\t\techo \"#ifdef cpusupport_dummy\"\n\t\techo \"export CFLAGS_${ARCH}_${FEATURE}=\\\"${CPU_CFLAGS}\\\"\"\n\t\techo \"#endif\"\n\t\t;;\n\tesac\n}\n\nif [ \"$2\" = \"--all\" ]; then\n\tfeature() {\n\t\tARCH=$1\n\t\tFEATURE=$2\n\t\techo \"#define CPUSUPPORT_${ARCH}_${FEATURE} 1\"\n\t}\nfi\n\n# Detect CPU-detection features\nfeature HWCAP ELF_AUX_INFO \"\"\nfeature HWCAP GETAUXVAL \"\"\nfeature X86 CPUID \"\"\nfeature X86 CPUID_COUNT \"\"\n\n# Detect specific features\nfeature X86 AESNI \"\" \"-maes\"\t\t\t\t\t\t\\\n    \"-maes -Wno-cast-align\"\t\t\t\t\t\t\\\n    \"-maes -Wno-missing-prototypes -Wno-cast-qual\"\t\t\t\\\n    \"-maes -Wno-missing-prototypes -Wno-cast-qual -Wno-cast-align\"\t\\\n    \"-maes -Wno-missing-prototypes -Wno-cast-qual -Wno-cast-align\t\\\n    -DBROKEN_MM_LOADU_SI64\"\nfeature X86 RDRAND \"\" \"-mrdrnd\"\nfeature X86 SHANI \"\" \"-msse2 -msha\"\t\t\t\t\t\\\n    \"-msse2 -msha -Wno-cast-align\"\nfeature X86 SSE2 \"\"\t\t\t\t\t\t\t\\\n    \"-Wno-cast-align\"\t\t\t\t\t\t\t\\\n    \"-msse2\"\t\t\t\t\t\t\t\t\\\n    \"-msse2 -Wno-cast-align\"\nfeature X86 SSE42 \"\" \"-msse4.2\"\t\t\t\t\t\t\\\n    \"-msse4.2 -Wno-cast-align\"\t\t\t\t\t\t\\\n    \"-msse4.2 -Wno-cast-align -fno-strict-aliasing\"\t\t\t\\\n    \"-msse4.2 -Wno-cast-align -fno-strict-aliasing -Wno-cast-qual\"\nfeature X86 SSE42_64 \"\" \"-msse4.2\"\t\t\t\t\t\\\n    \"-msse4.2 -Wno-cast-align\"\t\t\t\t\t\t\\\n    \"-msse4.2 -Wno-cast-align -fno-strict-aliasing\"\t\t\t\\\n    \"-msse4.2 -Wno-cast-align -fno-strict-aliasing -Wno-cast-qual\"\nfeature X86 SSSE3 \"\" \"-mssse3\"\t\t\t\t\t\t\\\n    \"-mssse3 -Wno-cast-align\"\n\n# Detect specific ARM features\nfeature ARM AES \"-march=armv8.1-a+crypto\"\t\t\t\t\\\n    \"-march=armv8.1-a+crypto -D__ARM_ACLE=200\"\nfeature ARM CRC32_64 \"-march=armv8.1-a\"\t\t\t\t\t\\\n    \"-march=armv8.1-a+crc\"\t\t\t\t\t\t\\\n    \"-march=armv8.1-a+crc -Wno-cast-align\"\t\t\t\t\\\n    \"-march=armv8.1-a -D__ARM_ACLE=200\"\nfeature ARM SHA256 \"-march=armv8.1-a+crypto\"\t\t\t\t\\\n    \"-march=armv8.1-a+crypto -Wno-cast-align\"\t\t\t\t\\\n    \"-march=armv8.1-a+crypto -D__ARM_ACLE=200\"\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport.h",
    "content": "#ifndef CPUSUPPORT_H_\n#define CPUSUPPORT_H_\n\n/*\n * To enable support for non-portable CPU features at compile time, one or\n * more CPUSUPPORT_ARCH_FEATURE macros should be defined.  This can be done\n * directly on the compiler command line via -D CPUSUPPORT_ARCH_FEATURE or\n * -D CPUSUPPORT_ARCH_FEATURE=1; or a file can be created with the\n * necessary #define lines and then -D CPUSUPPORT_CONFIG_FILE=cpuconfig.h\n * (or similar) can be provided to include that file here.\n */\n#ifdef CPUSUPPORT_CONFIG_FILE\n#include CPUSUPPORT_CONFIG_FILE\n#endif\n\n/**\n * The CPUSUPPORT_FEATURE macro declares the necessary variables and\n * functions for detecting CPU feature support at run time.  The function\n * defined in the macro acts to cache the result of the ..._detect function\n * using the ..._present and ..._init variables.  The _detect function and the\n * _present and _init variables are turn defined by CPUSUPPORT_FEATURE_DECL in\n * appropriate cpusupport_foo_bar.c file.\n *\n * In order to allow CPUSUPPORT_FEATURE to be used for features which do not\n * have corresponding CPUSUPPORT_FEATURE_DECL blocks in another source file,\n * we abuse the C preprocessor: If CPUSUPPORT_${enabler} is defined to 1, then\n * we access _present_1, _init_1, and _detect_1; but if it is not defined, we\n * access _present_CPUSUPPORT_${enabler} etc., which we define as static, thus\n * preventing the compiler from emitting a reference to an external symbol.\n *\n * In this way, it becomes possible to issue CPUSUPPORT_FEATURE invocations\n * for nonexistent features without running afoul of the requirement that\n * \"If an identifier declared with external linkage is used... in the entire\n * program there shall be exactly one external definition\" (C99 standard, 6.9\n * paragraph 5).  In practice, this means that users of the cpusupport code\n * can omit build and runtime detection files without changing the framework\n * code.\n */\n#define CPUSUPPORT_FEATURE__(arch_feature, enabler, enabled)\t\t\t\t\t\\\n\tstatic int cpusupport_ ## arch_feature ## _present ## _CPUSUPPORT_ ## enabler;\t\t\\\n\tstatic int cpusupport_ ## arch_feature ## _init ## _CPUSUPPORT_ ## enabler;\t\t\\\n\tstatic inline int cpusupport_ ## arch_feature ## _detect ## _CPUSUPPORT_ ## enabler(void) { return (0); }\t\\\n\textern int cpusupport_ ## arch_feature ## _present_ ## enabled;\t\t\t\t\\\n\textern int cpusupport_ ## arch_feature ## _init_ ## enabled;\t\t\t\t\\\n\tint cpusupport_ ## arch_feature ## _detect_ ## enabled(void);\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstatic inline int\t\t\t\t\t\t\t\t\t\\\n\tcpusupport_ ## arch_feature(void)\t\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tif (cpusupport_ ## arch_feature ## _present_ ## enabled)\t\t\t\\\n\t\t\treturn (1);\t\t\t\t\t\t\t\t\\\n\t\telse if (cpusupport_ ## arch_feature ## _init_ ## enabled)\t\t\t\\\n\t\t\treturn (0);\t\t\t\t\t\t\t\t\\\n\t\tcpusupport_ ## arch_feature ## _present_ ## enabled =\t\t\t\t\\\n\t\t    cpusupport_ ## arch_feature ## _detect_ ## enabled();\t\t\t\\\n\t\tcpusupport_ ## arch_feature ## _init_ ## enabled = 1;\t\t\t\t\\\n\t\treturn (cpusupport_ ## arch_feature ## _present_ ## enabled);\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\\\n\tstatic void (* cpusupport_ ## arch_feature ## _dummyptr)(void);\t\t\t\t\\\n\tstatic inline void\t\t\t\t\t\t\t\t\t\\\n\tcpusupport_ ## arch_feature ## _dummyfunc(void)\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _present ## _CPUSUPPORT_ ## enabler;\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _init ## _CPUSUPPORT_ ## enabler;\t\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _detect ## _CPUSUPPORT_ ## enabler;\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _present_ ## enabled;\t\t\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _init_ ## enabled;\t\t\t\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _detect_ ## enabled;\t\t\t\\\n\t\t(void)cpusupport_ ## arch_feature ## _dummyptr;\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\\\n\tstatic void (* cpusupport_ ## arch_feature ## _dummyptr)(void) = cpusupport_ ## arch_feature ## _dummyfunc;\t\\\n\tstruct cpusupport_ ## arch_feature ## _dummy\n#define CPUSUPPORT_FEATURE_(arch_feature, enabler, enabled)\t\\\n\tCPUSUPPORT_FEATURE__(arch_feature, enabler, enabled)\n#define CPUSUPPORT_FEATURE(arch, feature, enabler)\t\t\t\t\\\n\tCPUSUPPORT_FEATURE_(arch ## _ ## feature, enabler, CPUSUPPORT_ ## enabler)\n\n/**\n * CPUSUPPORT_FEATURE_DECL(arch, feature):\n * Macro which defines variables and provides a function declaration for\n * detecting the presence of \"feature\" on the \"arch\" architecture.  The\n * function body following this macro expansion must return nonzero if the\n * feature is present, or zero if the feature is not present or the detection\n * fails for any reason.\n */\n#define CPUSUPPORT_FEATURE_DECL(arch, feature)\t\t\t\t\\\n\textern int cpusupport_ ## arch ## _ ## feature ## _present_1;\t\\\n\textern int cpusupport_ ## arch ## _ ## feature ## _init_1;\t\\\n\tint cpusupport_ ## arch ## _ ## feature ## _present_1 = 0;\t\\\n\tint cpusupport_ ## arch ## _ ## feature ## _init_1 = 0;\t\t\\\n\tint cpusupport_ ## arch ## _ ## feature ## _detect_1(void); \\\n\tint\t\t\t\t\t\t\t\t\\\n\tcpusupport_ ## arch ## _ ## feature ## _detect_1(void)\n\n/**\n * CPUSUPPORT_VALIDATE(hwvar, success_value, cpusupport_checks, check):\n * Check if we can enable ${success_value}, given the ${cpusupport_checks} and\n * ${check}; if so, write to ${hwvar}.  If the ${cpusupport_checks} pass but\n * the ${check} is non-zero, produce a warning which includes a stringified\n * ${success_value}, then fallthrough.\n */\n#define CPUSUPPORT_VALIDATE(hwvar, success_value, cpusupport_checks,\t\\\n    check) do {\t\t\t\t\t\t\t\t\\\n\tif ((cpusupport_checks)) {\t\t\t\t\t\\\n\t\tif ((check) == 0) {\t\t\t\t\t\\\n\t\t\t(hwvar) = (success_value);\t\t\t\\\n\t\t\treturn;\t\t\t\t\t\t\\\n\t\t} else {\t\t\t\t\t\t\\\n\t\t\twarn0(\"Disabling \" #success_value\t\t\\\n\t\t\t    \" due to failed self-test\");\t\t\\\n\t\t}\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n} while (0)\n\n/**\n * List of features.  If a feature here is not enabled by the appropriate\n * CPUSUPPORT_ARCH_FEATURE macro being defined, it has no effect; but if the\n * relevant macro may be defined (e.g., by Build/cpusupport.sh successfully\n * compiling Build/cpusupport-ARCH-FEATURE.c) then the C file containing the\n * corresponding run-time detection code (cpusupport_arch_feature.c) must be\n * compiled and linked in.\n *\n * There are a few features for which we do not have run-time checks:\n * - X86_CPUID: compile-time is enough; if __get_cpuid() fails, then all the\n *              x86 detection features will fail, but there's nothing we can\n *              do about that.\n * - X86_CPUID_COUNT: ditto.\n * - X86_SSE42_64: the cpuid check tells us if the CPU supports SSE4.2, but\n *                 that says nothing about whether it's in 64-bit mode.\n */\nCPUSUPPORT_FEATURE(x86, aesni, X86_AESNI);\nCPUSUPPORT_FEATURE(x86, rdrand, X86_RDRAND);\nCPUSUPPORT_FEATURE(x86, shani, X86_SHANI);\nCPUSUPPORT_FEATURE(x86, sse2, X86_SSE2);\nCPUSUPPORT_FEATURE(x86, sse42, X86_SSE42);\nCPUSUPPORT_FEATURE(x86, ssse3, X86_SSSE3);\nCPUSUPPORT_FEATURE(arm, aes, ARM_AES);\nCPUSUPPORT_FEATURE(arm, crc32_64, ARM_CRC32_64);\nCPUSUPPORT_FEATURE(arm, sha256, ARM_SHA256);\n\n#endif /* !CPUSUPPORT_H_ */\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_arm_aes.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_HWCAP_GETAUXVAL\n#include <sys/auxv.h>\n\n#if defined(__arm__)\n/**\n * Workaround for a glibc bug: <bits/hwcap.h> contains a comment saying:\n *     The following must match the kernel's <asm/hwcap.h>.\n * However, it does not contain any of the HWCAP2_* entries from <asm/hwcap.h>.\n */\n#ifndef HWCAP2_AES\n#include <asm/hwcap.h>\n#endif\n#endif /* __arm__ */\n#endif /* CPUSUPPORT_HWCAP_GETAUXVAL */\n\n#if defined(CPUSUPPORT_HWCAP_ELF_AUX_INFO)\n#include <sys/auxv.h>\n#endif /* CPUSUPPORT_HWCAP_ELF_AUX_INFO */\n\nCPUSUPPORT_FEATURE_DECL(arm, aes)\n{\n\tint supported = 0;\n\n#if defined(CPUSUPPORT_ARM_AES)\n#if defined(CPUSUPPORT_HWCAP_GETAUXVAL)\n\tunsigned long capabilities;\n\n#if defined(__aarch64__)\n\tcapabilities = getauxval(AT_HWCAP);\n\tsupported = (capabilities & HWCAP_AES) ? 1 : 0;\n#elif defined(__arm__)\n\tcapabilities = getauxval(AT_HWCAP2);\n\tsupported = (capabilities & HWCAP2_AES) ? 1 : 0;\n#endif\n#endif /* CPUSUPPORT_HWCAP_GETAUXVAL */\n\n#if defined(CPUSUPPORT_HWCAP_ELF_AUX_INFO)\n\tunsigned long capabilities;\n\n#if defined(__aarch64__)\n\tif (elf_aux_info(AT_HWCAP, &capabilities, sizeof(unsigned long)))\n\t\treturn (0);\n\tsupported = (capabilities & HWCAP_AES) ? 1 : 0;\n#else\n\tif (elf_aux_info(AT_HWCAP2, &capabilities, sizeof(unsigned long)))\n\t\treturn (0);\n\tsupported = (capabilities & HWCAP2_AES) ? 1 : 0;\n#endif\n#endif /* CPUSUPPORT_HWCAP_ELF_AUX_INFO */\n#endif /* CPUSUPPORT_ARM_AES */\n\n\t/* Return the supported status. */\n\treturn (supported);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_arm_sha256.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_HWCAP_GETAUXVAL\n#include <sys/auxv.h>\n\n#if defined(__arm__)\n/**\n * Workaround for a glibc bug: <bits/hwcap.h> contains a comment saying:\n *     The following must match the kernel's <asm/hwcap.h>.\n * However, it does not contain any of the HWCAP2_* entries from <asm/hwcap.h>.\n */\n#ifndef HWCAP2_CRC32\n#include <asm/hwcap.h>\n#endif\n#endif /* __arm__ */\n#endif /* CPUSUPPORT_HWCAP_GETAUXVAL */\n\n#if defined(CPUSUPPORT_HWCAP_ELF_AUX_INFO)\n#include <sys/auxv.h>\n#endif /* CPUSUPPORT_HWCAP_ELF_AUX_INFO */\n\nCPUSUPPORT_FEATURE_DECL(arm, sha256)\n{\n\tint supported = 0;\n\n#if defined(CPUSUPPORT_ARM_SHA256)\n#if defined(CPUSUPPORT_HWCAP_GETAUXVAL)\n\tunsigned long capabilities;\n\n#if defined(__aarch64__)\n\tcapabilities = getauxval(AT_HWCAP);\n\tsupported = (capabilities & HWCAP_SHA2) ? 1 : 0;\n#elif defined(__arm__)\n\tcapabilities = getauxval(AT_HWCAP2);\n\tsupported = (capabilities & HWCAP2_SHA2) ? 1 : 0;\n#endif\n#endif /* CPUSUPPORT_HWCAP_GETAUXVAL */\n\n#if defined(CPUSUPPORT_HWCAP_ELF_AUX_INFO)\n\tunsigned long capabilities;\n\n#if defined(__aarch64__)\n\tif (elf_aux_info(AT_HWCAP, &capabilities, sizeof(unsigned long)))\n\t\treturn (0);\n\tsupported = (capabilities & HWCAP_SHA2) ? 1 : 0;\n#else\n\tif (elf_aux_info(AT_HWCAP2, &capabilities, sizeof(unsigned long)))\n\t\treturn (0);\n\tsupported = (capabilities & HWCAP2_SHA2) ? 1 : 0;\n#endif\n#endif /* CPUSUPPORT_HWCAP_ELF_AUX_INFO */\n#endif /* CPUSUPPORT_ARM_SHA256 */\n\n\t/* Return the supported status. */\n\treturn (supported);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_x86_aesni.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_X86_CPUID\n#include <cpuid.h>\n\n#define CPUID_AESNI_BIT (1 << 25)\n#endif\n\nCPUSUPPORT_FEATURE_DECL(x86, aesni)\n{\n#ifdef CPUSUPPORT_X86_CPUID\n\tunsigned int eax, ebx, ecx, edx;\n\n\t/* Check if CPUID supports the level we need. */\n\tif (!__get_cpuid(0, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\tif (eax < 1)\n\t\tgoto unsupported;\n\n\t/* Ask about CPU features. */\n\tif (!__get_cpuid(1, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\n\t/* Return the relevant feature bit. */\n\treturn ((ecx & CPUID_AESNI_BIT) ? 1 : 0);\n\nunsupported:\n#endif\n\n\t/* Not supported. */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_x86_rdrand.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_X86_CPUID\n#include <cpuid.h>\n\n#define CPUID_RDRAND_BIT (1 << 30)\n#endif\n\nCPUSUPPORT_FEATURE_DECL(x86, rdrand)\n{\n#ifdef CPUSUPPORT_X86_CPUID\n\tunsigned int eax, ebx, ecx, edx;\n\n\t/* Check if CPUID supports the level we need. */\n\tif (!__get_cpuid(0, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\tif (eax < 1)\n\t\tgoto unsupported;\n\n\t/* Ask about CPU features. */\n\tif (!__get_cpuid(1, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\n\t/* Return the relevant feature bit. */\n\treturn ((ecx & CPUID_RDRAND_BIT) ? 1 : 0);\n\nunsupported:\n#endif\n\n\t/* Not supported. */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_x86_shani.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_X86_CPUID_COUNT\n#include <cpuid.h>\n\n#define CPUID_SHANI_BIT (1 << 29)\n#endif\n\nCPUSUPPORT_FEATURE_DECL(x86, shani)\n{\n#ifdef CPUSUPPORT_X86_CPUID_COUNT\n\tunsigned int eax, ebx, ecx, edx;\n\n\t/* Check if CPUID supports the level we need. */\n\tif (!__get_cpuid(0, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\tif (eax < 7)\n\t\tgoto unsupported;\n\n\t/*\n\t * Ask about extended CPU features.  Note that this macro violates\n\t * the principle of being \"function-like\" by taking the variables\n\t * used for holding output registers as named parameters rather than\n\t * as pointers (which would be necessary if __cpuid_count were a\n\t * function).\n\t */\n\t__cpuid_count(7, 0, eax, ebx, ecx, edx);\n\n\t/* Return the relevant feature bit. */\n\treturn ((ebx & CPUID_SHANI_BIT) ? 1 : 0);\n\nunsupported:\n#endif\n\n\t/* Not supported. */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_x86_sse2.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_X86_CPUID\n#include <cpuid.h>\n\n#define CPUID_SSE2_BIT (1 << 26)\n#endif\n\nCPUSUPPORT_FEATURE_DECL(x86, sse2)\n{\n#ifdef CPUSUPPORT_X86_CPUID\n\tunsigned int eax, ebx, ecx, edx;\n\n\t/* Check if CPUID supports the level we need. */\n\tif (!__get_cpuid(0, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\tif (eax < 1)\n\t\tgoto unsupported;\n\n\t/* Ask about CPU features. */\n\tif (!__get_cpuid(1, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\n\t/* Return the relevant feature bit. */\n\treturn ((edx & CPUID_SSE2_BIT) ? 1 : 0);\n\nunsupported:\n#endif\n\n\t/* Not supported. */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/cpusupport/cpusupport_x86_ssse3.c",
    "content": "#include \"cpusupport.h\"\n\n#ifdef CPUSUPPORT_X86_CPUID\n#include <cpuid.h>\n\n#define CPUID_SSSE3_BIT (1 << 9)\n#endif\n\nCPUSUPPORT_FEATURE_DECL(x86, ssse3)\n{\n#ifdef CPUSUPPORT_X86_CPUID\n\tunsigned int eax, ebx, ecx, edx;\n\n\t/* Check if CPUID supports the level we need. */\n\tif (!__get_cpuid(0, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\tif (eax < 1)\n\t\tgoto unsupported;\n\n\t/* Ask about CPU features. */\n\tif (!__get_cpuid(1, &eax, &ebx, &ecx, &edx))\n\t\tgoto unsupported;\n\n\t/* Return the relevant feature bit. */\n\treturn ((ecx & CPUID_SSSE3_BIT) ? 1 : 0);\n\nunsupported:\n#endif\n\n\t/* Not supported. */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes.c",
    "content": "/**\n * APISUPPORT CFLAGS: LIBCRYPTO_LOW_LEVEL_AES\n */\n\n#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <openssl/aes.h>\n\n#include \"cpusupport.h\"\n#include \"crypto_aes_aesni.h\"\n#include \"crypto_aes_arm.h\"\n#include \"insecure_memzero.h\"\n#include \"warnp.h\"\n\n#include \"crypto_aes.h\"\n\n#if defined(CPUSUPPORT_X86_AESNI) || defined(CPUSUPPORT_ARM_AES)\n#define HWACCEL\n\nstatic enum {\n\tHW_SOFTWARE = 0,\n#if defined(CPUSUPPORT_X86_AESNI)\n\tHW_X86_AESNI,\n#endif\n#if defined(CPUSUPPORT_ARM_AES)\n\tHW_ARM_AES,\n#endif\n\tHW_UNSET\n} hwaccel = HW_UNSET;\n#endif\n\n/**\n * This represents either an AES_KEY or a struct crypto_aes_key_aesni; we\n * know which it is based on whether we're using AESNI code or not.  As such,\n * it's just an opaque pointer; but declaring it as a named structure type\n * prevents type-mismatch bugs in upstream code.\n */\nstruct crypto_aes_key;\n\n#ifdef HWACCEL\nstatic struct aes_test {\n\tconst uint8_t key[32];\n\tconst size_t len;\n\tconst uint8_t ptext[16];\n\tconst uint8_t ctext[16];\n} testcases[] = { {\n\t/* NIST FIPS 179, Appendix C - Example Vectors, AES-128, p. 35. */\n\t.key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n\t\t 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f},\n\t.len = 16,\n\t.ptext = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n\t\t   0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },\n\t.ctext = { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30,\n\t\t   0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }\n\t}, {\n\t/* NIST FIPS 179, Appendix C - Example Vectors, AES-256, p. 42. */\n\t.key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n\t\t 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n\t\t 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n\t\t 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, },\n\t.len = 32,\n\t.ptext = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,\n\t\t   0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },\n\t.ctext = { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf,\n\t\t   0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }\n\t}\n};\n\n/* Test a function against test vectors. */\nstatic int\nfunctest(int (* func)(const uint8_t *, size_t, const uint8_t[16], uint8_t[16]))\n{\n\tstruct aes_test * knowngood;\n\tuint8_t ctext[16];\n\tsize_t i;\n\n\tfor (i = 0; i < sizeof(testcases) / sizeof(testcases[0]); i++) {\n\t\tknowngood = &testcases[i];\n\n\t\t/* Sanity-check. */\n\t\tassert((knowngood->len == 16) || (knowngood->len == 32));\n\n\t\t/* Expand the key and encrypt with the provided function. */\n\t\tif (func(knowngood->key, knowngood->len, knowngood->ptext,\n\t\t    ctext))\n\t\t\tgoto err0;\n\n\t\t/* Does the output match the known good value? */\n\t\tif (memcmp(knowngood->ctext, ctext, 16))\n\t\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n#if defined(CPUSUPPORT_X86_AESNI)\nstatic int\nx86_aesni_oneshot(const uint8_t * key_unexpanded, size_t len,\n    const uint8_t ptext[16], uint8_t ctext[16])\n{\n\tvoid * kexp_hw;\n\n\t/* Expand the key and encrypt with hardware intrinsics. */\n\tif ((kexp_hw = crypto_aes_key_expand_aesni(key_unexpanded, len))\n\t    == NULL)\n\t\tgoto err0;\n\tcrypto_aes_encrypt_block_aesni(ptext, ctext, kexp_hw);\n\tcrypto_aes_key_free_aesni(kexp_hw);\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n#endif\n\n#if defined(CPUSUPPORT_ARM_AES)\nstatic int\narm_aes_oneshot(const uint8_t * key_unexpanded, size_t len,\n    const uint8_t ptext[16], uint8_t * ctext)\n{\n\tvoid * kexp_hw;\n\n\tif ((kexp_hw = crypto_aes_key_expand_arm(key_unexpanded, len)) == NULL)\n\t\tgoto err0;\n\tcrypto_aes_encrypt_block_arm(ptext, ctext, kexp_hw);\n\tcrypto_aes_key_free_arm(kexp_hw);\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n#endif\n\nstatic int\nopenssl_oneshot(const uint8_t * key_unexpanded, size_t len,\n    const uint8_t ptext[16], uint8_t * ctext)\n{\n\tAES_KEY kexp_actual;\n\tAES_KEY * kexp = &kexp_actual;\n\n\t/* Expand the key, encrypt, and clean up. */\n\tif (AES_set_encrypt_key(key_unexpanded, (int)(len * 8), kexp) != 0)\n\t\tgoto err0;\n\tAES_encrypt(ptext, ctext, kexp);\n\tinsecure_memzero(kexp, sizeof(AES_KEY));\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n/* Which type of hardware acceleration should we use, if any? */\nstatic void\nhwaccel_init(void)\n{\n\n\t/* If we've already set hwaccel, we're finished. */\n\tif (hwaccel != HW_UNSET)\n\t\treturn;\n\n\t/* Default to software. */\n\thwaccel = HW_SOFTWARE;\n\n#if defined(CPUSUPPORT_X86_AESNI)\n\tCPUSUPPORT_VALIDATE(hwaccel, HW_X86_AESNI, cpusupport_x86_aesni(),\n\t    functest(x86_aesni_oneshot));\n#endif\n#if defined(CPUSUPPORT_ARM_AES)\n\tCPUSUPPORT_VALIDATE(hwaccel, HW_ARM_AES, cpusupport_arm_aes(),\n\t    functest(arm_aes_oneshot));\n#endif\n\n\t/*\n\t * If we're here, we're not using any intrinsics.  Test OpenSSL; if\n\t * there's an error, print a warning and abort.\n\t */\n\tif (functest(openssl_oneshot)) {\n\t\twarn0(\"OpenSSL gives incorrect AES values.\");\n\t\tabort();\n\t}\n}\n#endif /* HWACCEL */\n\n/**\n * crypto_aes_can_use_intrinsics(void):\n * Test whether hardware intrinsics are safe to use.  Return 1 if x86 AESNI\n * operations are available, 2 if ARM-AES operations are available, or 0 if\n * none are available.\n */\nint\ncrypto_aes_can_use_intrinsics(void)\n{\n\n#ifdef HWACCEL\n\t/* Ensure that we've chosen the type of hardware acceleration. */\n\thwaccel_init();\n\n#if defined(CPUSUPPORT_X86_AESNI)\n\tif (hwaccel == HW_X86_AESNI)\n\t\treturn (1);\n#endif\n#if defined(CPUSUPPORT_ARM_AES)\n\tif (hwaccel == HW_ARM_AES)\n\t\treturn (2);\n#endif\n#endif /* HWACCEL */\n\n\t/* Software only. */\n\treturn (0);\n}\n\n/**\n * crypto_aes_key_expand(key_unexpanded, len):\n * Expand the ${len}-byte unexpanded AES key ${key_unexpanded} into a\n * structure which can be passed to crypto_aes_encrypt_block().  The length\n * must be 16 or 32.\n */\nstruct crypto_aes_key *\ncrypto_aes_key_expand(const uint8_t * key_unexpanded, size_t len)\n{\n\tAES_KEY * kexp;\n\n\t/* Sanity-check. */\n\tassert((len == 16) || (len == 32));\n\n#ifdef HWACCEL\n\t/* Ensure that we've chosen the type of hardware acceleration. */\n\thwaccel_init();\n\n#ifdef CPUSUPPORT_X86_AESNI\n\tif (hwaccel == HW_X86_AESNI)\n\t\treturn (crypto_aes_key_expand_aesni(key_unexpanded, len));\n#endif\n#ifdef CPUSUPPORT_ARM_AES\n\tif (hwaccel == HW_ARM_AES)\n\t\treturn (crypto_aes_key_expand_arm(key_unexpanded, len));\n#endif\n#endif /* HWACCEL */\n\n\t/* Allocate structure. */\n\tif ((kexp = malloc(sizeof(AES_KEY))) == NULL)\n\t\tgoto err0;\n\n\t/* Expand the key. */\n\tif (AES_set_encrypt_key(key_unexpanded, (int)(len * 8), kexp) != 0)\n\t\tgoto err1;\n\n\t/* Success! */\n\treturn ((void *)kexp);\n\nerr1:\n\tfree(kexp);\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * crypto_aes_encrypt_block(in, out, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and write the\n * resulting ciphertext to ${out}.  ${in} and ${out} can overlap.\n */\nvoid\ncrypto_aes_encrypt_block(const uint8_t in[16], uint8_t out[16],\n    const struct crypto_aes_key * key)\n{\n\n#ifdef HWACCEL\n#ifdef CPUSUPPORT_X86_AESNI\n\tif (hwaccel == HW_X86_AESNI) {\n\t\tcrypto_aes_encrypt_block_aesni(in, out, (const void *)key);\n\t\treturn;\n\t}\n#endif\n#ifdef CPUSUPPORT_ARM_AES\n\tif (hwaccel == HW_ARM_AES) {\n\t\tcrypto_aes_encrypt_block_arm(in, out, (const void *)key);\n\t\treturn;\n\t}\n#endif\n#endif /* HWACCEL */\n\n\t/* Get AES to do the work. */\n\tAES_encrypt(in, out, (const void *)key);\n}\n\n/**\n * crypto_aes_key_free(key):\n * Free the expanded AES key ${key}.\n */\nvoid\ncrypto_aes_key_free(struct crypto_aes_key * key)\n{\n\n#ifdef HWACCEL\n#ifdef CPUSUPPORT_X86_AESNI\n\tif (hwaccel == HW_X86_AESNI) {\n\t\tcrypto_aes_key_free_aesni((void *)key);\n\t\treturn;\n\t}\n#endif\n#ifdef CPUSUPPORT_ARM_AES\n\tif (hwaccel == HW_ARM_AES) {\n\t\tcrypto_aes_key_free_arm((void *)key);\n\t\treturn;\n\t}\n#endif\n#endif /* HWACCEL */\n\n\t/* Behave consistently with free(NULL). */\n\tif (key == NULL)\n\t\treturn;\n\n\t/* Attempt to zero the expanded key. */\n\tinsecure_memzero(key, sizeof(AES_KEY));\n\n\t/* Free the key. */\n\tfree(key);\n}\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes.h",
    "content": "#ifndef CRYPTO_AES_H_\n#define CRYPTO_AES_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* Opaque structure. */\nstruct crypto_aes_key;\n\n/**\n * crypto_aes_can_use_intrinsics(void):\n * Test whether hardware intrinsics are safe to use.  Return 1 if x86 AESNI\n * operations are available, 2 if ARM-AES operations are available, or 0 if\n * none are available.\n */\nint crypto_aes_can_use_intrinsics(void);\n\n/**\n * crypto_aes_key_expand(key_unexpanded, len):\n * Expand the ${len}-byte unexpanded AES key ${key_unexpanded} into a\n * structure which can be passed to crypto_aes_encrypt_block().  The length\n * must be 16 or 32.\n */\nstruct crypto_aes_key * crypto_aes_key_expand(const uint8_t *, size_t);\n\n/**\n * crypto_aes_encrypt_block(in, out, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and write the\n * resulting ciphertext to ${out}.  ${in} and ${out} can overlap.\n */\nvoid crypto_aes_encrypt_block(const uint8_t[16], uint8_t[16],\n    const struct crypto_aes_key *);\n\n/**\n * crypto_aes_key_free(key):\n * Free the expanded AES key ${key}.\n */\nvoid crypto_aes_key_free(struct crypto_aes_key *);\n\n#endif /* !CRYPTO_AES_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes_aesni.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_X86_AESNI\n/**\n * CPUSUPPORT CFLAGS: X86_AESNI\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <wmmintrin.h>\n\n#include \"align_ptr.h\"\n#include \"insecure_memzero.h\"\n#include \"warnp.h\"\n\n#include \"crypto_aes_aesni.h\"\n#include \"crypto_aes_aesni_m128i.h\"\n\n/* Expanded-key structure. */\nstruct crypto_aes_key_aesni {\n\tALIGN_PTR_DECL(__m128i, rkeys, 15, sizeof(__m128i));\n\tsize_t nr;\n};\n\n/* Compute an AES-128 round key. */\n#define MKRKEY128(rkeys, i, rcon) do {\t\t\t\t\\\n\t__m128i _s = rkeys[i - 1];\t\t\t\t\\\n\t__m128i _t = rkeys[i - 1];\t\t\t\t\\\n\t_s = _mm_xor_si128(_s, _mm_slli_si128(_s, 4));\t\t\\\n\t_s = _mm_xor_si128(_s, _mm_slli_si128(_s, 8));\t\t\\\n\t_t = _mm_aeskeygenassist_si128(_t, rcon);\t\t\\\n\t_t = _mm_shuffle_epi32(_t, 0xff);\t\t\t\\\n\trkeys[i] = _mm_xor_si128(_s, _t);\t\t\t\\\n} while (0)\n\n/**\n * crypto_aes_key_expand_128_aesni(key_unexpanded, rkeys):\n * Expand the 128-bit AES unexpanded key ${key_unexpanded} into the 11 round\n * keys ${rkeys}.  This implementation uses x86 AESNI instructions, and should\n * only be used if CPUSUPPORT_X86_AESNI is defined and cpusupport_x86_aesni()\n * returns nonzero.\n */\nstatic void\ncrypto_aes_key_expand_128_aesni(const uint8_t key_unexpanded[16],\n    __m128i rkeys[11])\n{\n\n\t/* The first round key is just the key. */\n\t/*-\n\t * XXX Compiler breakage:\n\t * The intrinsic defined by Intel for _mm_loadu_si128 defines it as\n\t * taking a (const __m128i *) parameter.  This forces us to write a\n\t * bug: The cast to (const __m128i *) is invalid since it increases\n\t * the alignment requirement of the pointer.  Alas, until compilers\n\t * get fixed intrinsics, all we can do is code the bug and require\n\t * that alignment-requirement-increasing compiler warnings get\n\t * disabled.\n\t */\n\trkeys[0] = _mm_loadu_si128((const __m128i *)&key_unexpanded[0]);\n\n\t/*\n\t * Each of the remaining round keys are computed from the preceding\n\t * round key: rotword+subword+rcon (provided as aeskeygenassist) to\n\t * compute the 'temp' value, then xor with 1, 2, 3, or all 4 of the\n\t * 32-bit words from the preceding round key.  Unfortunately, 'rcon'\n\t * is encoded as an immediate value, so we need to write the loop out\n\t * ourselves rather than allowing the compiler to expand it.\n\t */\n\tMKRKEY128(rkeys, 1, 0x01);\n\tMKRKEY128(rkeys, 2, 0x02);\n\tMKRKEY128(rkeys, 3, 0x04);\n\tMKRKEY128(rkeys, 4, 0x08);\n\tMKRKEY128(rkeys, 5, 0x10);\n\tMKRKEY128(rkeys, 6, 0x20);\n\tMKRKEY128(rkeys, 7, 0x40);\n\tMKRKEY128(rkeys, 8, 0x80);\n\tMKRKEY128(rkeys, 9, 0x1b);\n\tMKRKEY128(rkeys, 10, 0x36);\n}\n\n/* Compute an AES-256 round key. */\n#define MKRKEY256(rkeys, i, shuffle, rcon)\tdo {\t\t\\\n\t__m128i _s = rkeys[i - 2];\t\t\t\t\\\n\t__m128i _t = rkeys[i - 1];\t\t\t\t\\\n\t_s = _mm_xor_si128(_s, _mm_slli_si128(_s, 4));\t\t\\\n\t_s = _mm_xor_si128(_s, _mm_slli_si128(_s, 8));\t\t\\\n\t_t = _mm_aeskeygenassist_si128(_t, rcon);\t\t\\\n\t_t = _mm_shuffle_epi32(_t, shuffle);\t\t\t\\\n\trkeys[i] = _mm_xor_si128(_s, _t);\t\t\t\\\n} while (0)\n\n/**\n * crypto_aes_key_expand_256_aesni(key_unexpanded, rkeys):\n * Expand the 256-bit unexpanded AES key ${key_unexpanded} into the 15 round\n * keys ${rkeys}.  This implementation uses x86 AESNI instructions, and should\n * only be used if CPUSUPPORT_X86_AESNI is defined and cpusupport_x86_aesni()\n * returns nonzero.\n */\nstatic void\ncrypto_aes_key_expand_256_aesni(const uint8_t key_unexpanded[32],\n    __m128i rkeys[15])\n{\n\n\t/* The first two round keys are just the key. */\n\t/*-\n\t * XXX Compiler breakage:\n\t * The intrinsic defined by Intel for _mm_loadu_si128 defines it as\n\t * taking a (const __m128i *) parameter.  This forces us to write a\n\t * bug: The cast to (const __m128i *) is invalid since it increases\n\t * the alignment requirement of the pointer.  Alas, until compilers\n\t * get fixed intrinsics, all we can do is code the bug and require\n\t * that alignment-requirement-increasing compiler warnings get\n\t * disabled.\n\t */\n\trkeys[0] = _mm_loadu_si128((const __m128i *)&key_unexpanded[0]);\n\trkeys[1] = _mm_loadu_si128((const __m128i *)&key_unexpanded[16]);\n\n\t/*\n\t * Each of the remaining round keys are computed from the preceding\n\t * pair of keys.  Even rounds use rotword+subword+rcon, while odd\n\t * rounds just use subword; the aeskeygenassist instruction computes\n\t * both, and we use 0xff or 0xaa to select the one we need.  The rcon\n\t * value used is irrelevant for odd rounds since we ignore the value\n\t * which it feeds into.  Unfortunately, the 'shuffle' and 'rcon'\n\t * values are encoded into the instructions as immediates, so we need\n\t * to write the loop out ourselves rather than allowing the compiler\n\t * to expand it.\n\t */\n\tMKRKEY256(rkeys, 2, 0xff, 0x01);\n\tMKRKEY256(rkeys, 3, 0xaa, 0x00);\n\tMKRKEY256(rkeys, 4, 0xff, 0x02);\n\tMKRKEY256(rkeys, 5, 0xaa, 0x00);\n\tMKRKEY256(rkeys, 6, 0xff, 0x04);\n\tMKRKEY256(rkeys, 7, 0xaa, 0x00);\n\tMKRKEY256(rkeys, 8, 0xff, 0x08);\n\tMKRKEY256(rkeys, 9, 0xaa, 0x00);\n\tMKRKEY256(rkeys, 10, 0xff, 0x10);\n\tMKRKEY256(rkeys, 11, 0xaa, 0x00);\n\tMKRKEY256(rkeys, 12, 0xff, 0x20);\n\tMKRKEY256(rkeys, 13, 0xaa, 0x00);\n\tMKRKEY256(rkeys, 14, 0xff, 0x40);\n}\n\n/**\n * crypto_aes_key_expand_aesni(key_unexpanded, len):\n * Expand the ${len}-byte unexpanded AES key ${key_unexpanded} into a\n * structure which can be passed to crypto_aes_encrypt_block_aesni().  The\n * length must be 16 or 32.  This implementation uses x86 AESNI instructions,\n * and should only be used if CPUSUPPORT_X86_AESNI is defined and\n * cpusupport_x86_aesni() returns nonzero.\n */\nvoid *\ncrypto_aes_key_expand_aesni(const uint8_t * key_unexpanded, size_t len)\n{\n\tstruct crypto_aes_key_aesni * kexp;\n\n\t/* Allocate structure. */\n\tif ((kexp = malloc(sizeof(struct crypto_aes_key_aesni))) == NULL)\n\t\tgoto err0;\n\n\t/* Figure out where to put the round keys. */\n\tALIGN_PTR_INIT(kexp->rkeys, sizeof(__m128i));\n\n\t/* Compute round keys. */\n\tif (len == 16) {\n\t\tkexp->nr = 10;\n\t\tcrypto_aes_key_expand_128_aesni(key_unexpanded, kexp->rkeys);\n\t} else if (len == 32) {\n\t\tkexp->nr = 14;\n\t\tcrypto_aes_key_expand_256_aesni(key_unexpanded, kexp->rkeys);\n\t} else {\n\t\twarn0(\"Unsupported AES key length: %zu bytes\", len);\n\t\tgoto err1;\n\t}\n\n\t/* Success! */\n\treturn (kexp);\n\nerr1:\n\tfree(kexp);\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * crypto_aes_encrypt_block_aesni_m128i(in, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and return the\n * resulting ciphertext.  This implementation uses x86 AESNI instructions,\n * and should only be used if CPUSUPPORT_X86_AESNI is defined and\n * cpusupport_x86_aesni() returns nonzero.\n */\n__m128i\ncrypto_aes_encrypt_block_aesni_m128i(__m128i in, const void * key)\n{\n\tconst struct crypto_aes_key_aesni * _key = key;\n\tconst __m128i * aes_key = _key->rkeys;\n\t__m128i aes_state = in;\n\tsize_t nr = _key->nr;\n\n\taes_state = _mm_xor_si128(aes_state, aes_key[0]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[1]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[2]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[3]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[4]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[5]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[6]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[7]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[8]);\n\taes_state = _mm_aesenc_si128(aes_state, aes_key[9]);\n\tif (nr > 10) {\n\t\taes_state = _mm_aesenc_si128(aes_state, aes_key[10]);\n\t\taes_state = _mm_aesenc_si128(aes_state, aes_key[11]);\n\t\taes_state = _mm_aesenc_si128(aes_state, aes_key[12]);\n\t\taes_state = _mm_aesenc_si128(aes_state, aes_key[13]);\n\t}\n\n\taes_state = _mm_aesenclast_si128(aes_state, aes_key[nr]);\n\treturn (aes_state);\n}\n\n/**\n * crypto_aes_encrypt_block_aesni(in, out, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and write the\n * resulting ciphertext to ${out}.  ${in} and ${out} can overlap.  This\n * implementation uses x86 AESNI instructions, and should only be used if\n * CPUSUPPORT_X86_AESNI is defined and cpusupport_x86_aesni() returns nonzero.\n */\nvoid\ncrypto_aes_encrypt_block_aesni(const uint8_t in[16], uint8_t out[16],\n    const void * key)\n{\n\t__m128i aes_state;\n\n\taes_state = _mm_loadu_si128((const __m128i *)in);\n\taes_state = crypto_aes_encrypt_block_aesni_m128i(aes_state, key);\n\t_mm_storeu_si128((__m128i *)out, aes_state);\n}\n\n/**\n * crypto_aes_key_free_aesni(key):\n * Free the expanded AES key ${key}.\n */\nvoid\ncrypto_aes_key_free_aesni(void * key)\n{\n\n\t/* Behave consistently with free(NULL). */\n\tif (key == NULL)\n\t\treturn;\n\n\t/* Attempt to zero the expanded key. */\n\tinsecure_memzero(key, sizeof(struct crypto_aes_key_aesni));\n\n\t/* Free the key. */\n\tfree(key);\n}\n\n#endif /* CPUSUPPORT_X86_AESNI */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes_aesni.h",
    "content": "#ifndef CRYPTO_AES_AESNI_H_\n#define CRYPTO_AES_AESNI_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_aes_key_expand_aesni(key_unexpanded, len):\n * Expand the ${len}-byte unexpanded AES key ${key_unexpanded} into a\n * structure which can be passed to crypto_aes_encrypt_block_aesni().  The\n * length must be 16 or 32.  This implementation uses x86 AESNI instructions,\n * and should only be used if CPUSUPPORT_X86_AESNI is defined and\n * cpusupport_x86_aesni() returns nonzero.\n */\nvoid * crypto_aes_key_expand_aesni(const uint8_t *, size_t);\n\n/**\n * crypto_aes_encrypt_block_aesni(in, out, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and write the\n * resulting ciphertext to ${out}.  ${in} and ${out} can overlap.  This\n * implementation uses x86 AESNI instructions, and should only be used if\n * CPUSUPPORT_X86_AESNI is defined and cpusupport_x86_aesni() returns nonzero.\n */\nvoid crypto_aes_encrypt_block_aesni(const uint8_t[16], uint8_t[16],\n    const void *);\n\n/**\n * crypto_aes_key_free_aesni(key):\n * Free the expanded AES key ${key}.\n */\nvoid crypto_aes_key_free_aesni(void *);\n\n#endif /* !CRYPTO_AES_AESNI_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes_aesni_m128i.h",
    "content": "#ifndef CRYPTO_AES_AESNI_M128I_H_\n#define CRYPTO_AES_AESNI_M128I_H_\n\n#include <emmintrin.h>\n\n/**\n * crypto_aes_encrypt_block_aesni_m128i(in, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and return the\n * resulting ciphertext.  This implementation uses x86 AESNI instructions,\n * and should only be used if CPUSUPPORT_X86_AESNI is defined and\n * cpusupport_x86_aesni() returns nonzero.\n */\n__m128i crypto_aes_encrypt_block_aesni_m128i(__m128i, const void *);\n\n#endif /* !CRYPTO_AES_AESNI_M128I_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes_arm.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_ARM_AES\n/**\n * CPUSUPPORT CFLAGS: ARM_AES\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n\n#ifdef __ARM_NEON\n#include <arm_neon.h>\n#endif\n\n#include \"align_ptr.h\"\n#include \"insecure_memzero.h\"\n#include \"warnp.h\"\n\n#include \"crypto_aes_arm.h\"\n#include \"crypto_aes_arm_u8.h\"\n\n/* Expanded-key structure. */\nstruct crypto_aes_key_arm {\n\tALIGN_PTR_DECL(uint8x16_t, rkeys, 15, sizeof(uint8x16_t));\n\tsize_t nr;\n};\n\n/**\n * vdupq_laneq_u32_u8(a, lane):\n * Set all 32-bit vector lanes to the same value.  Exactly the same as\n * vdupq_laneq_u32(), except that accepts (and returns) uint8x16_t.\n */\n#define vdupq_laneq_u32_u8(a, lane)\t\t\t\\\n\tvreinterpretq_u8_u32(vdupq_laneq_u32(vreinterpretq_u32_u8(a), lane))\n\n/**\n * vshlq_n_u128(a, n):\n * Shift left (immediate), applied to the whole vector at once.\n *\n * Implementation note: this concatenates ${a} with a vector containing zeros,\n * then extracts a new vector from the pair (similar to a sliding window).\n * For example, vshlq_n_u128(a, 3) would do:\n *             0xaaaaaaaaaaaaaaaa0000000000000000\n *     return:      ~~~~~~~~~~~~~~~~\n * This is the recommended method of shifting an entire vector with Neon\n * intrinsics; all of the built-in shift instructions operate on multiple\n * values (such as a pair of 64-bit values).\n */\n#define vshlq_n_u128(a, n) vextq_u8(vdupq_n_u8(0), a, 16 - n)\n\n/**\n * SubWord_duplicate(a):\n * Perform the AES SubWord operation on the final 32-bit word (bits 96..127)\n * of ${a}, and return a vector consisting of that value copied to all lanes.\n */\nstatic inline uint8x16_t\nSubWord_duplicate(uint8x16_t a)\n{\n\n\t/*\n\t * Duplicate the final 32-bit word in all other lanes.  By having four\n\t * copies of the same uint32_t, we cause the ShiftRows in the upcoming\n\t * AESE to have no effect.\n\t */\n\ta = vdupq_laneq_u32_u8(a, 3);\n\n\t/* AESE does AddRoundKey (nop), ShiftRows (nop), and SubBytes. */\n\ta = vaeseq_u8(a, vdupq_n_u8(0));\n\n\treturn (a);\n}\n\n/**\n * SubWord_RotWord_XOR_duplicate(a, rcon):\n * Perform the AES key schedule operations of SubWord, RotWord, and XOR with\n * ${rcon}, acting on the final 32-bit word (bits 96..127) of ${a}, and return\n * a vector consisting of that value copied to all lanes.\n */\nstatic inline uint8x16_t\nSubWord_RotWord_XOR_duplicate(uint8x16_t a, const uint32_t rcon)\n{\n\tuint32_t x3;\n\n\t/* Perform SubWord on the final 32-bit word and copy it to all lanes. */\n\ta = SubWord_duplicate(a);\n\n\t/* We'll use non-neon for the rest. */\n\tx3 = vgetq_lane_u32(vreinterpretq_u32_u8(a), 0);\n\n\t/*-\n\t * x3 gets RotWord.  Note that\n\t *     RotWord(SubWord(a)) == SubWord(RotWord(a))\n\t */\n\tx3 = (x3 >> 8) | (x3 << (32 - 8));\n\n\t/* x3 gets XOR'd with rcon. */\n\tx3 = x3 ^ rcon;\n\n\t/* Copy x3 to all 128 bits, and convert it to a uint8x16_t. */\n\treturn (vreinterpretq_u8_u32(vdupq_n_u32(x3)));\n}\n\n/* Compute an AES-128 round key. */\n#define MKRKEY128(rkeys, i, rcon) do {\t\t\t\t\\\n\tuint8x16_t _s = rkeys[i - 1];\t\t\t\t\\\n\tuint8x16_t _t = rkeys[i - 1];\t\t\t\t\\\n\t_s = veorq_u8(_s, vshlq_n_u128(_s, 4));\t\t\t\\\n\t_s = veorq_u8(_s, vshlq_n_u128(_s, 8));\t\t\t\\\n\t_t = SubWord_RotWord_XOR_duplicate(_t, rcon);\t\t\\\n\trkeys[i] = veorq_u8(_s, _t);\t\t\t\t\\\n} while (0)\n\n/**\n * crypto_aes_key_expand_128_arm(key_unexpanded, rkeys):\n * Expand the 128-bit unexpanded AES key ${key_unexpanded} into the 11 round\n * keys ${rkeys}.  This implementation uses ARM AES instructions, and should\n * only be used if CPUSUPPORT_ARM_AES is defined and cpusupport_arm_aes()\n * returns nonzero.\n */\nstatic void\ncrypto_aes_key_expand_128_arm(const uint8_t key_unexpanded[16],\n    uint8x16_t rkeys[11])\n{\n\n\t/* The first round key is just the key. */\n\trkeys[0] = vld1q_u8(&key_unexpanded[0]);\n\n\t/*\n\t * Each of the remaining round keys are computed from the preceding\n\t * round key: rotword+subword+rcon (provided as aeskeygenassist) to\n\t * compute the 'temp' value, then xor with 1, 2, 3, or all 4 of the\n\t * 32-bit words from the preceding round key.\n\t */\n\tMKRKEY128(rkeys, 1, 0x01);\n\tMKRKEY128(rkeys, 2, 0x02);\n\tMKRKEY128(rkeys, 3, 0x04);\n\tMKRKEY128(rkeys, 4, 0x08);\n\tMKRKEY128(rkeys, 5, 0x10);\n\tMKRKEY128(rkeys, 6, 0x20);\n\tMKRKEY128(rkeys, 7, 0x40);\n\tMKRKEY128(rkeys, 8, 0x80);\n\tMKRKEY128(rkeys, 9, 0x1b);\n\tMKRKEY128(rkeys, 10, 0x36);\n}\n\n/* Compute an AES-256 round key. */\n#define MKRKEY256(rkeys, i, rcon)\tdo {\t\t\t\\\n\tuint8x16_t _s = rkeys[i - 2];\t\t\t\t\\\n\tuint8x16_t _t = rkeys[i - 1];\t\t\t\t\\\n\t_s = veorq_u8(_s, vshlq_n_u128(_s, 4));\t\t\t\\\n\t_s = veorq_u8(_s, vshlq_n_u128(_s, 8));\t\t\t\\\n\t_t = (i % 2 == 1) ?\t\t\t\t\t\\\n\t    SubWord_duplicate(_t) :\t\t\t\t\\\n\t    SubWord_RotWord_XOR_duplicate(_t, rcon);\t\t\\\n\trkeys[i] = veorq_u8(_s, _t);\t\t\t\t\\\n} while (0)\n\n/**\n * crypto_aes_key_expand_256_arm(key_unexpanded, rkeys):\n * Expand the 256-bit unexpanded AES key ${key_unexpanded} into the 15 round\n * keys ${rkeys}.  This implementation uses ARM AES instructions, and should\n * only be used if CPUSUPPORT_ARM_AES is defined and cpusupport_arm_aes()\n * returns nonzero.\n */\nstatic void\ncrypto_aes_key_expand_256_arm(const uint8_t key_unexpanded[32],\n    uint8x16_t rkeys[15])\n{\n\n\t/* The first two round keys are just the key. */\n\trkeys[0] = vld1q_u8(&key_unexpanded[0]);\n\trkeys[1] = vld1q_u8(&key_unexpanded[16]);\n\n\t/*\n\t * Each of the remaining round keys are computed from the preceding\n\t * pair of keys.  Even rounds use rotword+subword+rcon, while odd\n\t * rounds just use subword.  The rcon value used is irrelevant for odd\n\t * rounds since we ignore the value which it feeds into.\n\t */\n\tMKRKEY256(rkeys, 2, 0x01);\n\tMKRKEY256(rkeys, 3, 0x00);\n\tMKRKEY256(rkeys, 4, 0x02);\n\tMKRKEY256(rkeys, 5, 0x00);\n\tMKRKEY256(rkeys, 6, 0x04);\n\tMKRKEY256(rkeys, 7, 0x00);\n\tMKRKEY256(rkeys, 8, 0x08);\n\tMKRKEY256(rkeys, 9, 0x00);\n\tMKRKEY256(rkeys, 10, 0x10);\n\tMKRKEY256(rkeys, 11, 0x00);\n\tMKRKEY256(rkeys, 12, 0x20);\n\tMKRKEY256(rkeys, 13, 0x00);\n\tMKRKEY256(rkeys, 14, 0x40);\n}\n\n/**\n * crypto_aes_key_expand_arm(key_unexpanded, len):\n * Expand the ${len}-byte unexpanded AES key ${key_unexpanded} into a\n * structure which can be passed to crypto_aes_encrypt_block_arm().  The\n * length must be 16 or 32.  This implementation uses ARM AES instructions,\n * and should only be used if CPUSUPPORT_ARM_AES is defined and\n * cpusupport_arm_aes() returns nonzero.\n */\nvoid *\ncrypto_aes_key_expand_arm(const uint8_t * key_unexpanded, size_t len)\n{\n\tstruct crypto_aes_key_arm * kexp;\n\n\t/* Allocate structure. */\n\tif ((kexp = malloc(sizeof(struct crypto_aes_key_arm))) == NULL)\n\t\tgoto err0;\n\n\t/* Figure out where to put the round keys. */\n\tALIGN_PTR_INIT(kexp->rkeys, sizeof(uint8x16_t));\n\n\t/* Compute round keys. */\n\tif (len == 16) {\n\t\tkexp->nr = 10;\n\t\tcrypto_aes_key_expand_128_arm(key_unexpanded, kexp->rkeys);\n\t} else if (len == 32) {\n\t\tkexp->nr = 14;\n\t\tcrypto_aes_key_expand_256_arm(key_unexpanded, kexp->rkeys);\n\t} else {\n\t\twarn0(\"Unsupported AES key length: %zu bytes\", len);\n\t\tgoto err1;\n\t}\n\n\t/* Success! */\n\treturn (kexp);\n\nerr1:\n\tfree(kexp);\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * crypto_aes_encrypt_block_arm_u8(in, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and return the\n * resulting ciphertext.  This implementation uses ARM AES instructions,\n * and should only be used if CPUSUPPORT_ARM_AES is defined and\n * cpusupport_arm_aes() returns nonzero.\n */\nuint8x16_t\ncrypto_aes_encrypt_block_arm_u8(uint8x16_t in, const void * key)\n{\n\tconst struct crypto_aes_key_arm * _key = key;\n\tconst uint8x16_t * aes_key = _key->rkeys;\n\tuint8x16_t aes_state = in;\n\tsize_t nr = _key->nr;\n\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[0]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[1]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[2]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[3]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[4]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[5]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[6]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[7]));\n\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[8]));\n\tif (nr > 10) {\n\t\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[9]));\n\t\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[10]));\n\t\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[11]));\n\t\taes_state = vaesmcq_u8(vaeseq_u8(aes_state, aes_key[12]));\n\t}\n\n\t/* Last round. */\n\taes_state = vaeseq_u8(aes_state, aes_key[nr - 1]);\n\taes_state = veorq_u8(aes_state, aes_key[nr]);\n\n\treturn (aes_state);\n}\n\n/**\n * crypto_aes_encrypt_block_arm(in, out, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and write the\n * resulting ciphertext to ${out}.  ${in} and ${out} can overlap.  This\n * implementation uses ARM AES instructions, and should only be used if\n * CPUSUPPORT_ARM_AES is defined and cpusupport_arm_aes() returns nonzero.\n */\nvoid\ncrypto_aes_encrypt_block_arm(const uint8_t in[16], uint8_t out[16],\n    const void * key)\n{\n\tuint8x16_t aes_state;\n\n\taes_state = vld1q_u8(in);\n\taes_state = crypto_aes_encrypt_block_arm_u8(aes_state, key);\n\tvst1q_u8(out, aes_state);\n}\n\n/**\n * crypto_aes_key_free_arm(key):\n * Free the expanded AES key ${key}.\n */\nvoid\ncrypto_aes_key_free_arm(void * key)\n{\n\n\t/* Behave consistently with free(NULL). */\n\tif (key == NULL)\n\t\treturn;\n\n\t/* Attempt to zero the expanded key. */\n\tinsecure_memzero(key, sizeof(struct crypto_aes_key_arm));\n\n\t/* Free the key. */\n\tfree(key);\n}\n\n#endif /* CPUSUPPORT_ARM_AES */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes_arm.h",
    "content": "#ifndef CRYPTO_AES_ARM_H_\n#define CRYPTO_AES_ARM_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_aes_key_expand_arm(key_unexpanded, len):\n * Expand the ${len}-byte unexpanded AES key ${key_unexpanded} into a\n * structure which can be passed to crypto_aes_encrypt_block_arm().  The\n * length must be 16 or 32.  This implementation uses ARM AES instructions,\n * and should only be used if CPUSUPPORT_ARM_AES is defined and\n * cpusupport_arm_aes() returns nonzero.\n */\nvoid * crypto_aes_key_expand_arm(const uint8_t *, size_t);\n\n/**\n * crypto_aes_encrypt_block_arm(in, out, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and write the\n * resulting ciphertext to ${out}.  ${in} and ${out} can overlap.  This\n * implementation uses ARM AES instructions, and should only be used if\n * CPUSUPPORT_ARM_AES is defined and cpusupport_arm_aes() returns nonzero.\n */\nvoid crypto_aes_encrypt_block_arm(const uint8_t[16], uint8_t[16],\n    const void *);\n\n/**\n * crypto_aes_key_free_arm(key):\n * Free the expanded AES key ${key}.\n */\nvoid crypto_aes_key_free_arm(void *);\n\n#endif /* !CRYPTO_AES_ARM_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aes_arm_u8.h",
    "content": "#ifndef CRYPTO_AES_ARM_U8_H_\n#define CRYPTO_AES_ARM_U8_H_\n\n#ifdef __ARM_NEON\n#include <arm_neon.h>\n#endif\n\n/**\n * crypto_aes_encrypt_block_arm_u8(in, key):\n * Using the expanded AES key ${key}, encrypt the block ${in} and return the\n * resulting ciphertext.  This implementation uses ARM AES instructions,\n * and should only be used if CPUSUPPORT_ARM_AES is defined and\n * cpusupport_arm_aes() returns nonzero.\n */\nuint8x16_t crypto_aes_encrypt_block_arm_u8(uint8x16_t, const void *);\n\n#endif /* !CRYPTO_AES_ARM_U8_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr.c",
    "content": "#include <assert.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n#include \"cpusupport.h\"\n#include \"crypto_aes.h\"\n#include \"crypto_aesctr_aesni.h\"\n#include \"crypto_aesctr_arm.h\"\n#include \"insecure_memzero.h\"\n#include \"sysendian.h\"\n\n#include \"crypto_aesctr.h\"\n\n/**\n * In order to optimize AES-CTR, it is desirable to separate out the handling\n * of individual bytes of data vs. the handling of complete (16 byte) blocks.\n * The handling of blocks in turn can be optimized further using CPU\n * intrinsics, e.g. SSE2 on x86 CPUs; however while the byte-at-once code\n * remains the same across platforms it should be inlined into the same (CPU\n * feature specific) routines for performance reasons.\n *\n * In order to allow those generic functions to be inlined into multiple\n * functions in separate translation units, we place them into a \"shared\" C\n * file which is included in each of the platform-specific variants.\n */\n#include \"crypto_aesctr_shared.c\"\n\n#if defined(CPUSUPPORT_X86_AESNI) || defined(CPUSUPPORT_ARM_AES)\n#define HWACCEL\n\nstatic enum {\n\tHW_SOFTWARE = 0,\n#if defined(CPUSUPPORT_X86_AESNI)\n\tHW_X86_AESNI,\n#endif\n#if defined(CPUSUPPORT_ARM_AES)\n\tHW_ARM_AES,\n#endif\n\tHW_UNSET\n} hwaccel = HW_UNSET;\n#endif\n\n#ifdef HWACCEL\n/* Which type of hardware acceleration should we use, if any? */\nstatic void\nhwaccel_init(void)\n{\n\n\t/* If we've already set hwaccel, we're finished. */\n\tif (hwaccel != HW_UNSET)\n\t\treturn;\n\n\t/* Default to software. */\n\thwaccel = HW_SOFTWARE;\n\n\t/* Can we use AESNI? */\n\tswitch (crypto_aes_can_use_intrinsics()) {\n#ifdef CPUSUPPORT_X86_AESNI\n\tcase 1:\n\t\thwaccel = HW_X86_AESNI;\n\t\tbreak;\n#endif\n#ifdef CPUSUPPORT_ARM_AES\n\tcase 2:\n\t\thwaccel = HW_ARM_AES;\n\t\tbreak;\n#endif\n\tcase 0:\n\t\tbreak;\n\tdefault:\n\t\t/* Should never happen. */\n\t\tassert(0);\n\t}\n}\n#endif /* HWACCEL */\n\n/**\n * crypto_aesctr_alloc(void):\n * Allocate an object for performing AES in CTR code.  This must be followed\n * by calling _init2().\n */\nstruct crypto_aesctr *\ncrypto_aesctr_alloc(void)\n{\n\tstruct crypto_aesctr * stream;\n\n\t/* Allocate memory. */\n\tif ((stream = malloc(sizeof(struct crypto_aesctr))) == NULL)\n\t\tgoto err0;\n\n\t/* Success! */\n\treturn (stream);\n\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * crypto_aesctr_init2(stream, key, nonce):\n * Reset the AES-CTR stream ${stream}, using the ${key} and ${nonce}.  If ${key}\n * is NULL, retain the previous AES key.\n */\nvoid\ncrypto_aesctr_init2(struct crypto_aesctr * stream,\n    const struct crypto_aes_key * key, uint64_t nonce)\n{\n\n\t/* If the key is NULL, retain the previous AES key. */\n\tif (key != NULL)\n\t\tstream->key = key;\n\n\t/* Set nonce as provided and reset bytectr. */\n\tbe64enc(stream->pblk, nonce);\n\tstream->bytectr = 0;\n\n\t/*\n\t * Set the counter such that the least significant byte will wrap once\n\t * incremented.\n\t */\n\tstream->pblk[15] = 0xff;\n\n#ifdef HWACCEL\n\thwaccel_init();\n#endif\n\n\t/* Sanity check. */\n\tassert(stream->key != NULL);\n}\n\n/**\n * crypto_aesctr_init(key, nonce):\n * Prepare to encrypt/decrypt data with AES in CTR mode, using the provided\n * expanded ${key} and ${nonce}.  The key provided must remain valid for the\n * lifetime of the stream.  This is the same as calling _alloc() followed by\n * _init2().\n */\nstruct crypto_aesctr *\ncrypto_aesctr_init(const struct crypto_aes_key * key, uint64_t nonce)\n{\n\tstruct crypto_aesctr * stream;\n\n\t/* Sanity check. */\n\tassert(key != NULL);\n\n\t/* Allocate memory. */\n\tif ((stream = crypto_aesctr_alloc()) == NULL)\n\t\tgoto err0;\n\n\t/* Initialize values. */\n\tcrypto_aesctr_init2(stream, key, nonce);\n\n\t/* Success! */\n\treturn (stream);\n\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * crypto_aesctr_stream(stream, inbuf, outbuf, buflen):\n * Generate the next ${buflen} bytes of the AES-CTR stream ${stream} and xor\n * them with bytes from ${inbuf}, writing the result into ${outbuf}.  If the\n * buffers ${inbuf} and ${outbuf} overlap, they must be identical.\n */\nvoid\ncrypto_aesctr_stream(struct crypto_aesctr * stream, const uint8_t * inbuf,\n    uint8_t * outbuf, size_t buflen)\n{\n\n#if defined(HWACCEL)\n#if defined(CPUSUPPORT_X86_AESNI)\n\tif ((buflen >= 16) && (hwaccel == HW_X86_AESNI)) {\n\t\tcrypto_aesctr_aesni_stream(stream, inbuf, outbuf, buflen);\n\t\treturn;\n\t}\n#endif\n#if defined(CPUSUPPORT_ARM_AES)\n\tif ((buflen >= 16) && (hwaccel == HW_ARM_AES)) {\n\t\tcrypto_aesctr_arm_stream(stream, inbuf, outbuf, buflen);\n\t\treturn;\n\t}\n#endif\n#endif /* HWACCEL */\n\n\t/* Process any bytes before we can process a whole block. */\n\tif (crypto_aesctr_stream_pre_wholeblock(stream, &inbuf, &outbuf,\n\t    &buflen))\n\t\treturn;\n\n\t/* Process whole blocks of 16 bytes. */\n\twhile (buflen >= 16) {\n\t\t/* Generate a block of cipherstream. */\n\t\tcrypto_aesctr_stream_cipherblock_generate(stream);\n\n\t\t/* Encrypt the bytes and update the positions. */\n\t\tcrypto_aesctr_stream_cipherblock_use(stream, &inbuf, &outbuf,\n\t\t    &buflen, 16, 0);\n\t}\n\n\t/* Process any final bytes after finishing all whole blocks. */\n\tcrypto_aesctr_stream_post_wholeblock(stream, &inbuf, &outbuf, &buflen);\n}\n\n/**\n * crypto_aesctr_free(stream):\n * Free the AES-CTR stream ${stream}.\n */\nvoid\ncrypto_aesctr_free(struct crypto_aesctr * stream)\n{\n\n\t/* Behave consistently with free(NULL). */\n\tif (stream == NULL)\n\t\treturn;\n\n\t/* Zero potentially sensitive information. */\n\tinsecure_memzero(stream, sizeof(struct crypto_aesctr));\n\n\t/* Free the stream. */\n\tfree(stream);\n}\n\n/**\n * crypto_aesctr_buf(key, nonce, inbuf, outbuf, buflen):\n * Equivalent to _init(key, nonce); _stream(inbuf, outbuf, buflen); _free().\n */\nvoid\ncrypto_aesctr_buf(const struct crypto_aes_key * key, uint64_t nonce,\n    const uint8_t * inbuf, uint8_t * outbuf, size_t buflen)\n{\n\tstruct crypto_aesctr stream_rec;\n\tstruct crypto_aesctr * stream = &stream_rec;\n\n\t/* Sanity check. */\n\tassert(key != NULL);\n\n\t/* Initialize values. */\n\tcrypto_aesctr_init2(stream, key, nonce);\n\n\t/* Perform the encryption. */\n\tcrypto_aesctr_stream(stream, inbuf, outbuf, buflen);\n\n\t/* Zero potentially sensitive information. */\n\tinsecure_memzero(stream, sizeof(struct crypto_aesctr));\n}\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr.h",
    "content": "#ifndef CRYPTO_AESCTR_H_\n#define CRYPTO_AESCTR_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* Opaque types. */\nstruct crypto_aes_key;\nstruct crypto_aesctr;\n\n/**\n * crypto_aesctr_init(key, nonce):\n * Prepare to encrypt/decrypt data with AES in CTR mode, using the provided\n * expanded ${key} and ${nonce}.  The key provided must remain valid for the\n * lifetime of the stream.  This is the same as calling _alloc() followed by\n * _init2().\n */\nstruct crypto_aesctr * crypto_aesctr_init(const struct crypto_aes_key *,\n    uint64_t);\n\n/**\n * crypto_aesctr_alloc(void):\n * Allocate an object for performing AES in CTR code.  This must be followed\n * by calling _init2().\n */\nstruct crypto_aesctr * crypto_aesctr_alloc(void);\n\n/**\n * crypto_aesctr_init2(stream, key, nonce):\n * Reset the AES-CTR stream ${stream}, using the ${key} and ${nonce}.  If ${key}\n * is NULL, retain the previous AES key.\n */\nvoid crypto_aesctr_init2(struct crypto_aesctr *, const struct crypto_aes_key *,\n    uint64_t);\n\n/**\n * crypto_aesctr_stream(stream, inbuf, outbuf, buflen):\n * Generate the next ${buflen} bytes of the AES-CTR stream ${stream} and xor\n * them with bytes from ${inbuf}, writing the result into ${outbuf}.  If the\n * buffers ${inbuf} and ${outbuf} overlap, they must be identical.\n */\nvoid crypto_aesctr_stream(struct crypto_aesctr *, const uint8_t *,\n    uint8_t *, size_t);\n\n/**\n * crypto_aesctr_free(stream):\n * Free the AES-CTR stream ${stream}.\n */\nvoid crypto_aesctr_free(struct crypto_aesctr *);\n\n/**\n * crypto_aesctr_buf(key, nonce, inbuf, outbuf, buflen):\n * Equivalent to _init(key, nonce); _stream(inbuf, outbuf, buflen); _free().\n */\nvoid crypto_aesctr_buf(const struct crypto_aes_key *, uint64_t,\n    const uint8_t *, uint8_t *, size_t);\n\n#endif /* !CRYPTO_AESCTR_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr_aesni.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_X86_AESNI\n/**\n * CPUSUPPORT CFLAGS: X86_AESNI\n */\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n\n#include <emmintrin.h>\n\n#include \"crypto_aes.h\"\n#include \"crypto_aes_aesni_m128i.h\"\n#include \"sysendian.h\"\n\n#include \"crypto_aesctr_aesni.h\"\n\n/**\n * In order to optimize AES-CTR, it is desirable to separate out the handling\n * of individual bytes of data vs. the handling of complete (16 byte) blocks.\n * The handling of blocks in turn can be optimized further using CPU\n * intrinsics, e.g. SSE2 on x86 CPUs; however while the byte-at-once code\n * remains the same across platforms it should be inlined into the same (CPU\n * feature specific) routines for performance reasons.\n *\n * In order to allow those generic functions to be inlined into multiple\n * functions in separate translation units, we place them into a \"shared\" C\n * file which is included in each of the platform-specific variants.\n */\n#include \"crypto_aesctr_shared.c\"\n\n#ifdef BROKEN_MM_LOADU_SI64\n#warning Working around compiler bug: _mm_loadu_si64 is missing\n#warning Updating to a newer compiler may improve performance\n#endif\n\n/**\n * load_si64(mem):\n * Load an unaligned 64-bit integer from memory into the lowest 64 bits of the\n * returned value.  The contents of the upper 64 bits is not defined.\n */\nstatic inline __m128i\nload_si64(const void * mem)\n{\n\n#ifdef BROKEN_MM_LOADU_SI64\n\treturn (_mm_castpd_si128(_mm_load_sd(mem)));\n#else\n\treturn (_mm_loadu_si64(mem));\n#endif\n}\n\n/* Process multiple whole blocks by generating & using a cipherblock. */\nstatic void\ncrypto_aesctr_aesni_stream_wholeblocks(struct crypto_aesctr * stream,\n    const uint8_t ** inbuf, uint8_t ** outbuf, size_t * buflen)\n{\n\t__m128i bufsse;\n\t__m128i inbufsse;\n\t__m128i nonce_be;\n\tuint8_t block_counter_be_arr[8];\n\tuint64_t block_counter;\n\tsize_t num_blocks;\n\tsize_t i;\n\n\t/* Load local variables from stream. */\n\tnonce_be = load_si64(stream->pblk);\n\tblock_counter = stream->bytectr / 16;\n\n\t/* How many blocks should we process? */\n\tnum_blocks = (*buflen) / 16;\n\n\t/*\n\t * This is 'for (i = num_blocks; i > 0; i--)', but ensuring that the\n\t * compiler knows that we will execute the loop at least once.\n\t */\n\ti = num_blocks;\n\tdo {\n\t\t/* Prepare counter. */\n\t\tbe64enc(block_counter_be_arr, block_counter);\n\n\t\t/* Encrypt the cipherblock. */\n\t\tbufsse = load_si64(block_counter_be_arr);\n\t\tbufsse = _mm_unpacklo_epi64(nonce_be, bufsse);\n\t\tbufsse = crypto_aes_encrypt_block_aesni_m128i(bufsse,\n\t\t    stream->key);\n\n\t\t/* Encrypt the byte(s). */\n\t\tinbufsse = _mm_loadu_si128((const __m128i *)(*inbuf));\n\t\tbufsse = _mm_xor_si128(inbufsse, bufsse);\n\t\t_mm_storeu_si128((__m128i *)(*outbuf), bufsse);\n\n\t\t/* Update the positions. */\n\t\tblock_counter++;\n\t\t*inbuf += 16;\n\t\t*outbuf += 16;\n\n\t\t/* Update the counter. */\n\t\ti--;\n\t} while (i > 0);\n\n\t/* Update the overall buffer length. */\n\t*buflen -= 16 * num_blocks;\n\n\t/* Update variables in stream. */\n\tmemcpy(stream->pblk + 8, block_counter_be_arr, 8);\n\tstream->bytectr += 16 * num_blocks;\n}\n\n/**\n * crypto_aesctr_aesni_stream(stream, inbuf, outbuf, buflen):\n * Generate the next ${buflen} bytes of the AES-CTR stream ${stream} and xor\n * them with bytes from ${inbuf}, writing the result into ${outbuf}.  If the\n * buffers ${inbuf} and ${outbuf} overlap, they must be identical.\n */\nvoid\ncrypto_aesctr_aesni_stream(struct crypto_aesctr * stream, const uint8_t * inbuf,\n    uint8_t * outbuf, size_t buflen)\n{\n\n\t/* Process any bytes before we can process a whole block. */\n\tif (crypto_aesctr_stream_pre_wholeblock(stream, &inbuf, &outbuf,\n\t    &buflen))\n\t\treturn;\n\n\t/* Process whole blocks of 16 bytes. */\n\tif (buflen >= 16)\n\t\tcrypto_aesctr_aesni_stream_wholeblocks(stream, &inbuf,\n\t\t    &outbuf, &buflen);\n\n\t/* Process any final bytes after finishing all whole blocks. */\n\tcrypto_aesctr_stream_post_wholeblock(stream, &inbuf, &outbuf, &buflen);\n}\n\n#endif /* CPUSUPPORT_X86_AESNI */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr_aesni.h",
    "content": "#ifndef CRYPTO_AESCTR_AESNI_H_\n#define CRYPTO_AESCTR_AESNI_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* Opaque type. */\nstruct crypto_aesctr;\n\n/**\n * crypto_aesctr_aesni_stream(stream, inbuf, outbuf, buflen):\n * Generate the next ${buflen} bytes of the AES-CTR stream ${stream} and xor\n * them with bytes from ${inbuf}, writing the result into ${outbuf}.  If the\n * buffers ${inbuf} and ${outbuf} overlap, they must be identical.\n */\nvoid crypto_aesctr_aesni_stream(struct crypto_aesctr *, const uint8_t *,\n    uint8_t *, size_t);\n\n#endif /* !CRYPTO_AESCTR_AESNI_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr_arm.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_ARM_AES\n/**\n * CPUSUPPORT CFLAGS: ARM_AES\n */\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n\n#ifdef __ARM_NEON\n#include <arm_neon.h>\n#endif\n\n#include \"crypto_aes.h\"\n#include \"crypto_aes_arm_u8.h\"\n#include \"sysendian.h\"\n\n#include \"crypto_aesctr_arm.h\"\n\n/**\n * In order to optimize AES-CTR, it is desirable to separate out the handling\n * of individual bytes of data vs. the handling of complete (16 byte) blocks.\n * The handling of blocks in turn can be optimized further using CPU\n * intrinsics, e.g. SSE2 on x86 CPUs; however while the byte-at-once code\n * remains the same across platforms it should be inlined into the same (CPU\n * feature specific) routines for performance reasons.\n *\n * In order to allow those generic functions to be inlined into multiple\n * functions in separate translation units, we place them into a \"shared\" C\n * file which is included in each of the platform-specific variants.\n */\n#include \"crypto_aesctr_shared.c\"\n\n/* Process multiple whole blocks by generating & using a cipherblock. */\nstatic void\ncrypto_aesctr_arm_stream_wholeblocks(struct crypto_aesctr * stream,\n    const uint8_t ** inbuf, uint8_t ** outbuf, size_t * buflen)\n{\n\tuint8x16_t bufarm;\n\tuint8x16_t inbufarm;\n\tuint8x8_t nonce_be;\n\tuint8x8_t block_counter_be;\n\tuint8_t block_counter_be_arr[8];\n\tuint64_t block_counter;\n\tsize_t num_blocks;\n\tsize_t i;\n\n\t/* Load local variables from stream. */\n\tnonce_be = vld1_u8(stream->pblk);\n\tblock_counter = stream->bytectr / 16;\n\n\t/* How many blocks should we process? */\n\tnum_blocks = (*buflen) / 16;\n\n\t/*\n\t * This is 'for (i = num_blocks; i > 0; i--)', but ensuring that the\n\t * compiler knows that we will execute the loop at least once.\n\t */\n\ti = num_blocks;\n\tdo {\n\t\t/* Prepare counter. */\n\t\tbe64enc(block_counter_be_arr, block_counter);\n\n\t\t/* Encrypt the cipherblock. */\n\t\tblock_counter_be = vld1_u8(block_counter_be_arr);\n\t\tbufarm = vcombine_u8(nonce_be, block_counter_be);\n\t\tbufarm = crypto_aes_encrypt_block_arm_u8(bufarm, stream->key);\n\n\t\t/* Encrypt the byte(s). */\n\t\tinbufarm = vld1q_u8(*inbuf);\n\t\tbufarm = veorq_u8(inbufarm, bufarm);\n\t\tvst1q_u8(*outbuf, bufarm);\n\n\t\t/* Update the positions. */\n\t\tblock_counter++;\n\t\t*inbuf += 16;\n\t\t*outbuf += 16;\n\n\t\t/* Update the counter. */\n\t\ti--;\n\t} while (i > 0);\n\n\t/* Update the overall buffer length. */\n\t*buflen -= 16 * num_blocks;\n\n\t/* Update variables in stream. */\n\tmemcpy(stream->pblk + 8, block_counter_be_arr, 8);\n\tstream->bytectr += 16 * num_blocks;\n}\n\n/**\n * crypto_aesctr_arm_stream(stream, inbuf, outbuf, buflen):\n * Generate the next ${buflen} bytes of the AES-CTR stream ${stream} and xor\n * them with bytes from ${inbuf}, writing the result into ${outbuf}.  If the\n * buffers ${inbuf} and ${outbuf} overlap, they must be identical.\n */\nvoid\ncrypto_aesctr_arm_stream(struct crypto_aesctr * stream, const uint8_t * inbuf,\n    uint8_t * outbuf, size_t buflen)\n{\n\n\t/* Process any bytes before we can process a whole block. */\n\tif (crypto_aesctr_stream_pre_wholeblock(stream, &inbuf, &outbuf,\n\t    &buflen))\n\t\treturn;\n\n\t/* Process whole blocks of 16 bytes. */\n\tif (buflen >= 16)\n\t\tcrypto_aesctr_arm_stream_wholeblocks(stream, &inbuf, &outbuf,\n\t\t    &buflen);\n\n\t/* Process any final bytes after finishing all whole blocks. */\n\tcrypto_aesctr_stream_post_wholeblock(stream, &inbuf, &outbuf, &buflen);\n}\n\n#endif /* CPUSUPPORT_ARM_AES */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr_arm.h",
    "content": "#ifndef CRYPTO_AESCTR_ARM_H_\n#define CRYPTO_AESCTR_ARM_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* Opaque type. */\nstruct crypto_aesctr;\n\n/**\n * crypto_aesctr_arm_stream(stream, inbuf, outbuf, buflen):\n * Generate the next ${buflen} bytes of the AES-CTR stream ${stream} and xor\n * them with bytes from ${inbuf}, writing the result into ${outbuf}.  If the\n * buffers ${inbuf} and ${outbuf} overlap, they must be identical.\n */\nvoid crypto_aesctr_arm_stream(struct crypto_aesctr *, const uint8_t *,\n    uint8_t *, size_t);\n\n#endif /* !CRYPTO_AESCTR_ARM_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_aesctr_shared.c",
    "content": "/*\n * This code is shared between crypto_aesctr*.c files, and should not be\n * compiled as a separate translation unit.  For details, see the comments in\n * those files.\n */\n\n/* AES-CTR state. */\nstruct crypto_aesctr {\n\tconst struct crypto_aes_key * key;\n\tuint64_t bytectr;\n\tuint8_t buf[16];\n\tuint8_t pblk[16];\n};\n\n/* Generate a block of cipherstream. */\nstatic inline void\ncrypto_aesctr_stream_cipherblock_generate(struct crypto_aesctr * stream)\n{\n\n\t/* Sanity check. */\n\tassert(stream->bytectr % 16 == 0);\n\n\t/* Prepare counter. */\n\tstream->pblk[15]++;\n\tif (stream->pblk[15] == 0) {\n\t\t/*\n\t\t * If incrementing the least significant byte resulted in it\n\t\t * wrapping, re-encode the complete 64-bit value.\n\t\t */\n\t\tbe64enc(stream->pblk + 8, stream->bytectr / 16);\n\t}\n\n\t/* Encrypt the cipherblock. */\n\tcrypto_aes_encrypt_block(stream->pblk, stream->buf, stream->key);\n}\n\n/* Encrypt ${nbytes} bytes, then update ${inbuf}, ${outbuf}, and ${buflen}. */\nstatic inline void\ncrypto_aesctr_stream_cipherblock_use(struct crypto_aesctr * stream,\n    const uint8_t ** inbuf, uint8_t ** outbuf, size_t * buflen, size_t nbytes,\n    size_t bytemod)\n{\n\tsize_t i;\n\n\t/* Encrypt the byte(s). */\n\tfor (i = 0; i < nbytes; i++)\n\t\t(*outbuf)[i] = (*inbuf)[i] ^ stream->buf[bytemod + i];\n\n\t/* Move to the next byte(s) of cipherstream. */\n\tstream->bytectr += nbytes;\n\n\t/* Update the positions. */\n\t*inbuf += nbytes;\n\t*outbuf += nbytes;\n\t*buflen -= nbytes;\n}\n\n/*\n * Process any bytes before we can process a whole block.  Return 1 if there\n * are no bytes left to process after calling this function.\n */\nstatic inline int\ncrypto_aesctr_stream_pre_wholeblock(struct crypto_aesctr * stream,\n    const uint8_t ** inbuf, uint8_t ** outbuf, size_t * buflen_p)\n{\n\tsize_t bytemod;\n\n\t/* Do we have any bytes left in the current cipherblock? */\n\tbytemod = stream->bytectr % 16;\n\tif (bytemod != 0) {\n\t\t/* Do we have enough to complete the request? */\n\t\tif (bytemod + *buflen_p <= 16) {\n\t\t\t/* Process only buflen bytes, then return. */\n\t\t\tcrypto_aesctr_stream_cipherblock_use(stream, inbuf,\n\t\t\t    outbuf, buflen_p, *buflen_p, bytemod);\n\t\t\treturn (1);\n\t\t}\n\n\t\t/* Encrypt the byte(s) and update the positions. */\n\t\tcrypto_aesctr_stream_cipherblock_use(stream, inbuf, outbuf,\n\t\t    buflen_p, 16 - bytemod, bytemod);\n\t}\n\n\t/* Success! */\n\treturn (0);\n}\n\n/* Process any final bytes after finishing all whole blocks. */\nstatic inline void\ncrypto_aesctr_stream_post_wholeblock(struct crypto_aesctr * stream,\n    const uint8_t ** inbuf, uint8_t ** outbuf, size_t * buflen_p)\n{\n\n\t/* Process any final bytes; we need a new cipherblock. */\n\tif (*buflen_p > 0) {\n\t\t/* Generate a block of cipherstream. */\n\t\tcrypto_aesctr_stream_cipherblock_generate(stream);\n\n\t\t/* Encrypt the byte(s) and update the positions. */\n\t\tcrypto_aesctr_stream_cipherblock_use(stream, inbuf, outbuf,\n\t\t    buflen_p, *buflen_p, 0);\n\t}\n}\n"
  },
  {
    "path": "libcperciva/crypto/crypto_entropy.c",
    "content": "#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n\n#include \"cpusupport.h\"\n#include \"crypto_entropy_rdrand.h\"\n#include \"entropy.h\"\n#include \"insecure_memzero.h\"\n\n#include \"sha256.h\"\n\n#include \"crypto_entropy.h\"\n\n/**\n * This system implements the HMAC_DRBG pseudo-random number generator as\n * specified in section 10.1.2 of the NIST SP 800-90 standard.  In this\n * implementation, the optional personalization_string and additional_input\n * specified in the standard are not implemented.\n */\n\n/* Internal HMAC_DRBG state. */\nstatic struct {\n\tuint8_t Key[32];\n\tuint8_t V[32];\n\tuint32_t reseed_counter;\n} drbg;\n\n/* Set to non-zero once the PRNG has been instantiated. */\nstatic int instantiated = 0;\n\n/* Could be as high as 2^48 if we wanted... */\n#define RESEED_INTERVAL\t256\n\n/* Limited to 2^16 by specification. */\n#define GENERATE_MAXLEN\t65536\n\nstatic int instantiate(void);\nstatic void update(const uint8_t *, size_t);\nstatic int reseed(void);\nstatic void generate(uint8_t *, size_t);\n\n#ifdef CPUSUPPORT_X86_RDRAND\nstatic void\nupdate_from_rdrand(void)\n{\n\tunsigned int buf[8];\n\n\t/* This is only *extra* entropy, so it's ok if it fails. */\n\tif (generate_seed_rdrand(buf, 8))\n\t\treturn;\n\tupdate((uint8_t *)buf, sizeof(buf));\n\n\t/* Clean up. */\n\tinsecure_memzero(buf, sizeof(buf));\n}\n#endif\n\n/**\n * instantiate(void):\n * Initialize the DRBG state.  (Section 10.1.2.3)\n */\nstatic int\ninstantiate(void)\n{\n\tuint8_t seed_material[48];\n\n\t/* Obtain random seed_material = (entropy_input || nonce). */\n\tif (entropy_read(seed_material, 48))\n\t\treturn (-1);\n\n\t/* Initialize Key, V, and reseed_counter. */\n\tmemset(drbg.Key, 0x00, 32);\n\tmemset(drbg.V, 0x01, 32);\n\tdrbg.reseed_counter = 1;\n\n\t/* Mix the random seed into the state. */\n\tupdate(seed_material, 48);\n\n#ifdef CPUSUPPORT_X86_RDRAND\n\t/* Add output of RDRAND into the state. */\n\tif (cpusupport_x86_rdrand())\n\t\tupdate_from_rdrand();\n#endif\n\n\t/* Clean the stack. */\n\tinsecure_memzero(seed_material, 48);\n\n\t/* Success! */\n\treturn (0);\n}\n\n/**\n * update(data, datalen):\n * Update the DRBG state using the provided data.  (Section 10.1.2.2)\n */\nstatic void\nupdate(const uint8_t * data, size_t datalen)\n{\n\tHMAC_SHA256_CTX ctx;\n\tuint8_t K[32];\n\tuint8_t Vx[33];\n\n\t/* Load (Key, V) into (K, Vx). */\n\tmemcpy(K, drbg.Key, 32);\n\tmemcpy(Vx, drbg.V, 32);\n\n\t/* K <- HMAC(K, V || 0x00 || data). */\n\tVx[32] = 0x00;\n\tHMAC_SHA256_Init(&ctx, K, 32);\n\tHMAC_SHA256_Update(&ctx, Vx, 33);\n\tHMAC_SHA256_Update(&ctx, data, datalen);\n\tHMAC_SHA256_Final(K, &ctx);\n\n\t/* V <- HMAC(K, V). */\n\tHMAC_SHA256_Buf(K, 32, Vx, 32, Vx);\n\n\t/* If the provided data is non-Null, perform another mixing stage. */\n\tif (datalen != 0) {\n\t\t/* K <- HMAC(K, V || 0x01 || data). */\n\t\tVx[32] = 0x01;\n\t\tHMAC_SHA256_Init(&ctx, K, 32);\n\t\tHMAC_SHA256_Update(&ctx, Vx, 33);\n\t\tHMAC_SHA256_Update(&ctx, data, datalen);\n\t\tHMAC_SHA256_Final(K, &ctx);\n\n\t\t/* V <- HMAC(K, V). */\n\t\tHMAC_SHA256_Buf(K, 32, Vx, 32, Vx);\n\t}\n\n\t/* Copy (K, Vx) back to (Key, V). */\n\tmemcpy(drbg.Key, K, 32);\n\tmemcpy(drbg.V, Vx, 32);\n\n\t/* Clean the stack. */\n\tinsecure_memzero(K, 32);\n\tinsecure_memzero(Vx, 33);\n}\n\n/**\n * reseed(void):\n * Reseed the DRBG state (mix in new entropy).  (Section 10.1.2.4)\n */\nstatic int\nreseed(void)\n{\n\tuint8_t seed_material[32];\n\n\t/* Obtain random seed_material = entropy_input. */\n\tif (entropy_read(seed_material, 32))\n\t\treturn (-1);\n\n\t/* Mix the random seed into the state. */\n\tupdate(seed_material, 32);\n\n#ifdef CPUSUPPORT_X86_RDRAND\n\t/* Add output of RDRAND into the state. */\n\tif (cpusupport_x86_rdrand())\n\t\tupdate_from_rdrand();\n#endif\n\n\t/* Reset the reseed_counter. */\n\tdrbg.reseed_counter = 1;\n\n\t/* Clean the stack. */\n\tinsecure_memzero(seed_material, 32);\n\n\t/* Success! */\n\treturn (0);\n}\n\n/**\n * generate(buf, buflen):\n * Fill the provided buffer with random bits, assuming that reseed_counter\n * is less than RESEED_INTERVAL (the caller is responsible for calling\n * reseed() as needed) and ${buflen} is less than 2^16 (the caller is\n * responsible for splitting up larger requests).  (Section 10.1.2.5)\n */\nstatic void\ngenerate(uint8_t * buf, size_t buflen)\n{\n\tsize_t bufpos;\n\n\tassert(buflen <= GENERATE_MAXLEN);\n\tassert(drbg.reseed_counter <= RESEED_INTERVAL);\n\n\t/* Iterate until we've filled the buffer. */\n\tfor (bufpos = 0; bufpos < buflen; bufpos += 32) {\n\t\tHMAC_SHA256_Buf(drbg.Key, 32, drbg.V, 32, drbg.V);\n\t\tif (buflen - bufpos >= 32)\n\t\t\tmemcpy(&buf[bufpos], drbg.V, 32);\n\t\telse\n\t\t\tmemcpy(&buf[bufpos], drbg.V, buflen - bufpos);\n\t}\n\n\t/* Mix up state. */\n\tupdate(NULL, 0);\n\n\t/* We're one data-generation step closer to needing a reseed. */\n\tdrbg.reseed_counter += 1;\n}\n\n/**\n * crypto_entropy_read(buf, buflen):\n * Fill the buffer with unpredictable bits.\n */\nint\ncrypto_entropy_read(uint8_t * buf, size_t buflen)\n{\n\tsize_t bytes_to_provide;\n\n\t/* Instantiate if needed. */\n\tif (instantiated == 0) {\n\t\t/* Try to instantiate the PRNG. */\n\t\tif (instantiate())\n\t\t\treturn (-1);\n\n\t\t/* We have instantiated the PRNG. */\n\t\tinstantiated = 1;\n\t}\n\n\t/* Loop until we've filled the buffer. */\n\twhile (buflen > 0) {\n\t\t/* Do we need to reseed? */\n\t\tif (drbg.reseed_counter > RESEED_INTERVAL) {\n\t\t\tif (reseed())\n\t\t\t\treturn (-1);\n\t\t}\n\n\t\t/* How much data are we generating in this step? */\n\t\tif (buflen > GENERATE_MAXLEN)\n\t\t\tbytes_to_provide = GENERATE_MAXLEN;\n\t\telse\n\t\t\tbytes_to_provide = buflen;\n\n\t\t/* Generate bytes. */\n\t\tgenerate(buf, bytes_to_provide);\n\n\t\t/* We've done part of the buffer. */\n\t\tbuf += bytes_to_provide;\n\t\tbuflen -= bytes_to_provide;\n\t}\n\n\t/* Success! */\n\treturn (0);\n}\n"
  },
  {
    "path": "libcperciva/crypto/crypto_entropy.h",
    "content": "#ifndef CRYPTO_ENTROPY_H_\n#define CRYPTO_ENTROPY_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_entropy_read(buf, buflen):\n * Fill the buffer with unpredictable bits.\n */\nint crypto_entropy_read(uint8_t *, size_t);\n\n#endif /* !CRYPTO_ENTROPY_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_entropy_rdrand.c",
    "content": "#include \"cpusupport.h\"\n#ifdef CPUSUPPORT_X86_RDRAND\n/**\n * CPUSUPPORT CFLAGS: X86_RDRAND\n */\n\n#include <immintrin.h>\n#include <stddef.h>\n\n#include \"crypto_entropy_rdrand.h\"\n\n/**\n * generate_seed_rdrand(buf, len):\n * Fill the ${buf} buffer with values from RDRAND.  This implementation uses\n * the RDRAND instruction, and should only be used if CPUSUPPORT_X86_RDRAND is\n * defined and cpusupport_x86_rdrand() returns nonzero.\n */\nint\ngenerate_seed_rdrand(unsigned int * buf, size_t len)\n{\n\tsize_t i;\n\n\t/* Fill buffer. */\n\tfor (i = 0; i < len; i++) {\n\t\tif (!_rdrand32_step(&buf[i]))\n\t\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (1);\n}\n#endif /* CPUSUPPORT_X86_RDRAND */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_entropy_rdrand.h",
    "content": "#ifndef CRYPTO_ENTROPY_RDRAND_H_\n#define CRYPTO_ENTROPY_RDRAND_H_\n\n#include <stddef.h>\n\n/**\n * generate_seed_rdrand(buf, len):\n * Fill the ${buf} buffer with values from RDRAND.  This implementation uses\n * the RDRAND instruction, and should only be used if CPUSUPPORT_X86_RDRAND is\n * defined and cpusupport_x86_rdrand() returns nonzero.\n */\nint generate_seed_rdrand(unsigned int *, size_t);\n\n#endif /* !CRYPTO_ENTROPY_RDRAND_H_ */\n"
  },
  {
    "path": "libcperciva/crypto/crypto_verify_bytes.c",
    "content": "#include <stddef.h>\n#include <stdint.h>\n\n#include \"crypto_verify_bytes.h\"\n\n/**\n * crypto_verify_bytes(buf0, buf1, len):\n * Return zero if and only if ${buf0[0 .. len - 1]} and ${buf1[0 .. len - 1]}\n * are identical.  Do not leak any information via timing side channels.\n */\nuint8_t\ncrypto_verify_bytes(const uint8_t * buf0, const uint8_t * buf1, size_t len)\n{\n\tuint8_t rc = 0;\n\tsize_t i;\n\n\tfor (i = 0; i < len; i++)\n\t\trc = rc | (buf0[i] ^ buf1[i]);\n\n\treturn (rc);\n}\n"
  },
  {
    "path": "libcperciva/crypto/crypto_verify_bytes.h",
    "content": "#ifndef CRYPTO_VERIFY_BYTES_H_\n#define CRYPTO_VERIFY_BYTES_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * crypto_verify_bytes(buf0, buf1, len):\n * Return zero if and only if ${buf0[0 .. len - 1]} and ${buf1[0 .. len - 1]}\n * are identical.  Do not leak any information via timing side channels.\n */\nuint8_t crypto_verify_bytes(const uint8_t *, const uint8_t *, size_t);\n\n#endif /* !CRYPTO_VERIFY_BYTES_H_ */\n"
  },
  {
    "path": "libcperciva/util/align_ptr.h",
    "content": "#ifndef ALIGN_PTR_H_\n#define ALIGN_PTR_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/**\n * ALIGN_PTR_DECL(type, name, num, alignsize):\n * Declare a pointer called ${name}, which points to an array large enough to\n * contain ${num} values of ${type} and is aligned to ${alignsize} bytes.  The\n * pointer must not be used until ALIGN_PTR_INIT(${name}, ${alignsize}) has\n * been called.  This macro may also create an additional variable called\n * \"${name}_buf\".\n */\n#define ALIGN_PTR_DECL(type, name, num, alignsize)\t\t\t\\\n\tuint8_t name##_buf[num * sizeof(type) + (alignsize - 1)];\t\\\n\ttype * name\n\n/**\n * ALIGN_PTR_INIT(name, alignsize):\n * Initialize the variable called ${name} to point to an array which is\n * aligned to ${alignsize} bytes.  They must have previously been declared\n * with ALIGN_PTR_DECL(${name}, ${alignsize}).  This macro assumes that\n * casting a pointer to uintptr_t behaves naturally, i.e. yields a byte offset\n * relative to aligned memory.\n */\n#define ALIGN_PTR_INIT(name, alignsize)\t\t\t\t\t\\\n\tname = align_ptr(name##_buf, alignsize)\n\n/**\n * align_ptr(arr, alignment):\n * Return a pointer to the first memory location within ${arr} which is\n * aligned to ${alignsize} bytes.  (It is expected that this function will\n * only be called via the ALIGN_PTR_INIT macro).\n */\nstatic inline void *\nalign_ptr(uint8_t * arr, size_t alignment)\n{\n\tsize_t offset;\n\n\t/*\n\t * This assumes that casting a pointer to uintptr_t behaves naturally,\n\t * i.e. yields a byte offset relative to aligned memory.\n\t */\n\toffset = (uintptr_t)(&arr[0]) % alignment;\n\toffset = (alignment - offset) % alignment;\n\n\t/* Return the aligned pointer. */\n\treturn ((void *)&arr[offset]);\n}\n\n#endif /* !ALIGN_PTR_H_ */\n"
  },
  {
    "path": "libcperciva/util/asprintf.c",
    "content": "#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"asprintf.h\"\n\n/**\n * asprintf(ret, format, ...):\n * Do asprintf(3) like GNU and BSD do.\n */\nint\nasprintf(char ** ret, const char * format, ...)\n{\n\tva_list ap;\n\tint len;\n\tsize_t buflen;\n\n\t/* Figure out how long the string needs to be. */\n\tva_start(ap, format);\n\tlen = vsnprintf(NULL, 0, format, ap);\n\tva_end(ap);\n\n\t/* Did we fail? */\n\tif (len < 0)\n\t\tgoto err0;\n\tbuflen = (size_t)(len) + 1;\n\n\t/* Allocate memory. */\n\tif ((*ret = malloc(buflen)) == NULL)\n\t\tgoto err0;\n\n\t/* Actually generate the string. */\n\tva_start(ap, format);\n\tlen = vsnprintf(*ret, buflen, format, ap);\n\tva_end(ap);\n\n\t/* Did we fail? */\n\tif (len < 0)\n\t\tgoto err1;\n\n\t/* Success! */\n\treturn (len);\n\nerr1:\n\tfree(*ret);\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n"
  },
  {
    "path": "libcperciva/util/asprintf.h",
    "content": "#ifndef ASPRINTF_H_\n#define ASPRINTF_H_\n\n/* Avoid namespace collisions with BSD/GNU asprintf. */\n#ifdef asprintf\n#undef asprintf\n#endif\n#define asprintf libcperciva_asprintf\n\n/**\n * asprintf(ret, format, ...):\n * Do asprintf(3) like GNU and BSD do.\n */\nint asprintf(char **, const char *, ...);\n\n#endif /* !ASPRINTF_H_ */\n"
  },
  {
    "path": "libcperciva/util/entropy.c",
    "content": "#include <assert.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <limits.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include \"warnp.h\"\n\n#include \"entropy.h\"\n\n/**\n * XXX Portability\n * XXX We obtain random bytes from the operating system by opening\n * XXX /dev/urandom and reading them from that device; this works on\n * XXX modern UNIX-like operating systems but not on systems like\n * XXX win32 where there is no concept of /dev/urandom.\n */\n\n/**\n * Entropy reader state.  At present it holds a file descriptor for\n * /dev/urandom, but in the future this structure may gain other OS-dependent\n * state, e.g. a Windows Handle.\n */\nstruct entropy_read_cookie {\n\tint fd;\n};\n\n/**\n * entropy_read_init(void):\n * Initialize the ability to produce random bytes from the operating system,\n * and return a cookie.\n */\nstruct entropy_read_cookie *\nentropy_read_init(void)\n{\n\tstruct entropy_read_cookie * er;\n\n\t/* Allocate cookie. */\n\tif ((er = malloc(sizeof(struct entropy_read_cookie))) == NULL) {\n\t\twarnp(\"malloc\");\n\t\tgoto err0;\n\t}\n\n\t/* Open /dev/urandom. */\n\tif ((er->fd = open(\"/dev/urandom\", O_RDONLY)) == -1) {\n\t\twarnp(\"open(/dev/urandom)\");\n\t\tgoto err1;\n\t}\n\n\t/* Success! */\n\treturn (er);\n\nerr1:\n\tfree(er);\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * entropy_read_fill(er, buf, buflen):\n * Fill the given buffer with random bytes provided by the operating system\n * using the resources in ${er}.\n */\nint\nentropy_read_fill(struct entropy_read_cookie * er, uint8_t * buf,\n    size_t buflen)\n{\n\tssize_t lenread;\n\n\t/* Sanity checks. */\n\tassert(er != NULL);\n\tassert(buflen <= SSIZE_MAX);\n\n\t/* Read bytes until we have filled the buffer. */\n\twhile (buflen > 0) {\n\t\tif ((lenread = read(er->fd, buf, buflen)) == -1) {\n\t\t\twarnp(\"read(/dev/urandom)\");\n\t\t\tgoto err0;\n\t\t}\n\n\t\t/* The random device should never EOF. */\n\t\tif (lenread == 0) {\n\t\t\twarn0(\"EOF on /dev/urandom?\");\n\t\t\tgoto err0;\n\t\t}\n\n\t\t/* We've filled a portion of the buffer. */\n\t\tbuf += (size_t)lenread;\n\t\tbuflen -= (size_t)lenread;\n\t}\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n/**\n * entropy_read_done(er):\n * Release any resources used by ${er}.\n */\nint\nentropy_read_done(struct entropy_read_cookie * er)\n{\n\n\t/* Sanity check. */\n\tassert(er != NULL);\n\n\t/* Close the device. */\n\twhile (close(er->fd) == -1) {\n\t\tif (errno != EINTR) {\n\t\t\twarnp(\"close(/dev/urandom)\");\n\t\t\tgoto err1;\n\t\t}\n\t}\n\n\t/* Clean up. */\n\tfree(er);\n\n\t/* Success! */\n\treturn (0);\n\nerr1:\n\tfree(er);\n\n\t/* Failure! */\n\treturn (-1);\n}\n\n/**\n * entropy_read(buf, buflen):\n * Fill the given buffer with random bytes provided by the operating system.\n */\nint\nentropy_read(uint8_t * buf, size_t buflen)\n{\n\tstruct entropy_read_cookie * er;\n\n\t/* Sanity-check the buffer size. */\n\tassert(buflen <= SSIZE_MAX);\n\n\t/* Open /dev/urandom. */\n\tif ((er = entropy_read_init()) == NULL) {\n\t\twarn0(\"entropy_read_init\");\n\t\tgoto err0;\n\t}\n\n\t/* Read bytes until we have filled the buffer. */\n\tif (entropy_read_fill(er, buf, buflen)) {\n\t\twarn0(\"entropy_read_fill\");\n\t\tgoto err1;\n\t}\n\n\t/* Close the device. */\n\tif (entropy_read_done(er)) {\n\t\twarn0(\"entropy_read_done\");\n\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (0);\n\nerr1:\n\tentropy_read_done(er);\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n"
  },
  {
    "path": "libcperciva/util/entropy.h",
    "content": "#ifndef ENTROPY_H_\n#define ENTROPY_H_\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* Opaque type. */\nstruct entropy_read_cookie;\n\n/**\n * entropy_read_init(void):\n * Initialize the ability to produce random bytes from the operating system,\n * and return a cookie.\n */\nstruct entropy_read_cookie * entropy_read_init(void);\n\n/**\n * entropy_read_fill(er, buf, buflen):\n * Fill the given buffer with random bytes provided by the operating system\n * using the resources in ${er}.\n */\nint entropy_read_fill(struct entropy_read_cookie *, uint8_t *, size_t);\n\n/**\n * entropy_read_done(er):\n * Release any resources used by ${er}.\n */\nint entropy_read_done(struct entropy_read_cookie *);\n\n/**\n * entropy_read(buf, buflen):\n * Fill the given buffer with random bytes provided by the operating system.\n */\nint entropy_read(uint8_t *, size_t);\n\n#endif /* !ENTROPY_H_ */\n"
  },
  {
    "path": "libcperciva/util/getopt.c",
    "content": "#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"getopt.h\"\n\n/*\n * Standard getopt global variables.  optreset starts as non-zero in order to\n * trigger initialization behaviour.\n */\nconst char * optarg = NULL;\nint optind = 1;\nint opterr = 1;\nint optreset = 1;\n\n/*\n * Quasi-internal global variables -- these are used via GETOPT macros.\n */\nconst char * getopt_dummy = \"(dummy)\";\nint getopt_initialized = 0;\n\n/*\n * Internal variables.\n */\nstatic const char * cmdname = NULL;\nstatic struct opt {\n\tconst char * os;\n\tsize_t olen;\n\tint hasarg;\n} * opts = NULL;\t/* Probably a sparse array: some values, some NULLs. */\nstatic size_t nopts;\t/* Maximum number of options. */\nstatic size_t opt_missing;\nstatic size_t opt_default;\nstatic size_t opt_found;\nstatic const char * packedopts;\nstatic char popt[3];\nstatic int atexit_registered = 0;\n\n/* Print a message. */\n#define PRINTMSG(...)\tdo {\t\t\t\t\t\t\\\n\tif (cmdname != NULL)\t\t\t\t\t\t\\\n\t\tfprintf(stderr, \"%s: \", cmdname);\t\t\t\\\n\tfprintf(stderr, __VA_ARGS__);\t\t\t\t\t\\\n\tfprintf(stderr, \"\\n\");\t\t\t\t\t\t\\\n} while (0)\n\n/* Print an error message and die. */\n#define DIE(...)\tdo {\t\t\t\t\t\t\\\n\tPRINTMSG(__VA_ARGS__);\t\t\t\t\t\t\\\n\tabort();\t\t\t\t\t\t\t\\\n} while (0)\n\n/* Print a warning, if warnings are enabled. */\n#define WARN(...)\tdo {\t\t\t\t\t\t\\\n\tif (opterr == 0)\t\t\t\t\t\t\\\n\t\tbreak;\t\t\t\t\t\t\t\\\n\tif (opt_missing != opt_default)\t\t\t\t\t\\\n\t\tbreak;\t\t\t\t\t\t\t\\\n\tPRINTMSG(__VA_ARGS__);\t\t\t\t\t\t\\\n} while (0)\n\n/* Free allocated options array. */\nstatic void\ngetopt_atexit(void)\n{\n\n\tfree(opts);\n\topts = NULL;\n}\n\n/* Reset internal state. */\nstatic void\nreset(int argc, char * const argv[])\n{\n\tconst char * p;\n\n\t/* If we have arguments, stash argv[0] for error messages. */\n\tif (argc > 0) {\n\t\t/* Find the basename, without leading directories. */\n\t\tfor (p = cmdname = argv[0]; *p != '\\0'; p++) {\n\t\t\tif (*p == '/')\n\t\t\t\tcmdname = p + 1;\n\t\t}\n\t}\n\n\t/* Discard any registered command-line options. */\n\tfree(opts);\n\topts = NULL;\n\n\t/* Register atexit handler if we haven't done so already. */\n\tif (!atexit_registered) {\n\t\tatexit(getopt_atexit);\n\t\tatexit_registered = 1;\n\t}\n\n\t/* We will start scanning from the first option. */\n\toptind = 1;\n\n\t/* We're not in the middle of any packed options. */\n\tpackedopts = NULL;\n\n\t/* We haven't found any option yet. */\n\topt_found = (size_t)(-1);\n\n\t/* We're not initialized yet. */\n\tgetopt_initialized = 0;\n\n\t/* Finished resetting state. */\n\toptreset = 0;\n}\n\n/* Search for an option string. */\nstatic size_t\nsearchopt(const char * os)\n{\n\tsize_t i;\n\n\t/* Scan the array of options. */\n\tfor (i = 0; i < nopts; i++) {\n\t\t/* Is there an option in this slot? */\n\t\tif (opts[i].os == NULL)\n\t\t\tcontinue;\n\n\t\t/* Does this match up to the length of the option string? */\n\t\tif (strncmp(opts[i].os, os, opts[i].olen))\n\t\t\tcontinue;\n\n\t\t/* Do we have <option>\\0 or <option>= ? */\n\t\tif ((os[opts[i].olen] == '\\0') || (os[opts[i].olen] == '='))\n\t\t\treturn (i);\n\t}\n\n\t/* Not found. */\n\treturn (opt_default);\n}\n\nconst char *\ngetopt(int argc, char * const argv[])\n{\n\tconst char * os = NULL;\n\tconst char * canonical_os = NULL;\n\n\t/* No argument yet. */\n\toptarg = NULL;\n\n\t/* Reset the getopt state if needed. */\n\tif (optreset)\n\t\treset(argc, argv);\n\n\t/* If not initialized, return dummy option. */\n\tif (!getopt_initialized)\n\t\treturn (GETOPT_DUMMY);\n\n\t/* If we've run out of arguments, we're done. */\n\tif (optind >= argc)\n\t\treturn (NULL);\n\n\t/*\n\t * If we're not already in the middle of a packed single-character\n\t * options, see if we should start.\n\t */\n\tif ((packedopts == NULL) && (argv[optind][0] == '-') &&\n\t    (argv[optind][1] != '-') && (argv[optind][1] != '\\0')) {\n\t\t/* We have one or more single-character options. */\n\t\tpackedopts = &argv[optind][1];\n\t}\n\n\t/* If we're processing single-character options, fish one out. */\n\tif (packedopts != NULL) {\n\t\t/* Construct the option string. */\n\t\tpopt[0] = '-';\n\t\tpopt[1] = *packedopts;\n\t\tpopt[2] = '\\0';\n\t\tos = popt;\n\n\t\t/* We've done this character. */\n\t\tpackedopts++;\n\n\t\t/* Are we done with this string? */\n\t\tif (*packedopts == '\\0') {\n\t\t\tpackedopts = NULL;\n\t\t\toptind++;\n\t\t}\n\t}\n\n\t/* If we don't have an option yet, do we have dash-dash? */\n\tif ((os == NULL) && (argv[optind][0] == '-') &&\n\t    (argv[optind][1] == '-')) {\n\t\t/* If this is not \"--\\0\", it's an option. */\n\t\tif (argv[optind][2] != '\\0')\n\t\t\tos = argv[optind];\n\n\t\t/* Either way, we want to eat the string. */\n\t\toptind++;\n\t}\n\n\t/* If we have found nothing which looks like an option, we're done. */\n\tif (os == NULL)\n\t\treturn (NULL);\n\n\t/* Search for the potential option. */\n\topt_found = searchopt(os);\n\n\t/* If the option is not registered, give up now. */\n\tif (opt_found == opt_default) {\n\t\tWARN(\"unknown option: %s\", os);\n\t\treturn (os);\n\t}\n\n\t/* The canonical option string is the one registered. */\n\tcanonical_os = opts[opt_found].os;\n\n\t/* Does the option take an argument? */\n\tif (opts[opt_found].hasarg) {\n\t\t/*\n\t\t * If we're processing packed single-character options, the\n\t\t * rest of the string is the argument to this option.\n\t\t */\n\t\tif (packedopts != NULL) {\n\t\t\toptarg = packedopts;\n\t\t\tpackedopts = NULL;\n\t\t\toptind++;\n\t\t}\n\n\t\t/*\n\t\t * If the option string is <option>=<value>, extract that\n\t\t * value as the option argument.\n\t\t */\n\t\tif (os[opts[opt_found].olen] == '=')\n\t\t\toptarg = &os[opts[opt_found].olen + 1];\n\n\t\t/*\n\t\t * If we don't have an argument yet, take one from the\n\t\t * remaining command line.\n\t\t */\n\t\tif ((optarg == NULL) && (optind < argc))\n\t\t\toptarg = argv[optind++];\n\n\t\t/* If we still have no option, declare it MIA. */\n\t\tif (optarg == NULL) {\n\t\t\tWARN(\"option requires an argument: %s\",\n\t\t\t    opts[opt_found].os);\n\t\t\topt_found = opt_missing;\n\t\t}\n\t} else {\n\t\t/* If we have --foo=bar, something went wrong. */\n\t\tif (os[opts[opt_found].olen] == '=') {\n\t\t\tWARN(\"option doesn't take an argument: %s\",\n\t\t\t    opts[opt_found].os);\n\t\t\topt_found = opt_default;\n\t\t}\n\t}\n\n\t/* Return the canonical option string. */\n\treturn (canonical_os);\n}\n\nsize_t\ngetopt_lookup(const char * os)\n{\n\n\t/*\n\t * We only take this parameter so that we can assert that it's the\n\t * same option string as we returned from getopt(); as such, it is\n\t * unused in the absence of assertions.\n\t */\n\t(void)os; /* UNUSED */\n\n\t/* Can't reset here. */\n\tif (optreset)\n\t\tDIE(\"Can't reset in the middle of getopt loop\");\n\n\t/* We should only be called after initialization is complete. */\n\tassert(getopt_initialized);\n\n\t/* GETOPT_DUMMY should never get passed back to us. */\n\tassert(os != GETOPT_DUMMY);\n\n\t/*\n\t * Make sure the option passed back to us corresponds to the one we\n\t * found earlier.\n\t */\n\tassert((opt_found == opt_missing) || (opt_found == opt_default) ||\n\t    ((opt_found < nopts) && (strcmp(os, opts[opt_found].os) == 0)));\n\n\t/* Return the option number we identified earlier. */\n\treturn (opt_found);\n}\n\nvoid\ngetopt_register_opt(const char * os, size_t ln, int hasarg)\n{\n\n\t/* Can't reset here. */\n\tif (optreset)\n\t\tDIE(\"Can't reset in the middle of getopt loop\");\n\n\t/* We should only be called during initialization. */\n\tassert(!getopt_initialized);\n\n\t/* We should have space allocated for registering options. */\n\tassert(opts != NULL);\n\n\t/* We should not have registered an option here yet. */\n\tassert(opts[ln].os == NULL);\n\n\t/* Options should be \"-X\" or \"--foo\". */\n\tif ((os[0] != '-') || (os[1] == '\\0') ||\n\t    ((os[1] == '-') && (os[2] == '\\0')) ||\n\t    ((os[1] != '-') && (os[2] != '\\0')))\n\t\tDIE(\"Not a valid command-line option: %s\", os);\n\n\t/* Make sure we haven't already registered this option. */\n\tif (searchopt(os) != opt_default)\n\t\tDIE(\"Command-line option registered twice: %s\", os);\n\n\t/* Record option. */\n\topts[ln].os = os;\n\topts[ln].olen = strlen(os);\n\topts[ln].hasarg = hasarg;\n}\n\nvoid\ngetopt_register_missing(size_t ln)\n{\n\n\t/* Can't reset here. */\n\tif (optreset)\n\t\tDIE(\"Can't reset in the middle of getopt loop\");\n\n\t/* We should only be called during initialization. */\n\tassert(!getopt_initialized);\n\n\t/* Record missing-argument value. */\n\topt_missing = ln;\n}\n\n/* Prepare for the number of potential options. */\nvoid\ngetopt_setrange(size_t maxopts)\n{\n\tsize_t i;\n\n\t/* Can't reset here. */\n\tif (optreset)\n\t\tDIE(\"Can't reset in the middle of getopt loop\");\n\n\t/* We should only be called during initialization. */\n\tassert(!getopt_initialized);\n\n\t/* Allocate space for (potential) options. */\n\topts = malloc(maxopts * sizeof(struct opt));\n\tif ((maxopts > 0) && (opts == NULL))\n\t\tDIE(\"Failed to allocate memory in getopt\");\n\n\t/* Initialize options. */\n\tfor (i = 0; i < maxopts; i++)\n\t\topts[i].os = NULL;\n\n\t/* Record the number of (potential) options. */\n\tnopts = maxopts;\n\n\t/* Record default missing-argument and no-such-option values. */\n\topt_missing = opt_default = maxopts + 1;\n}\n"
  },
  {
    "path": "libcperciva/util/getopt.h",
    "content": "#ifndef GETOPT_H_\n#define GETOPT_H_\n\n#include <assert.h>\n#include <setjmp.h>\n#include <stddef.h>\n\n/**\n * This getopt implementation parses options of the following forms:\n * -a -b -c foo\t\t(single-character options)\n * -abc foo\t\t(packed single-character options)\n * -abcfoo\t\t(packed single-character options and an argument)\n * --foo bar\t\t(long option)\n * --foo=bar\t\t(long option and argument separated by '=')\n *\n * It does not support abbreviated options (e.g., interpreting --foo as\n * --foobar when there are no other --foo* options) since that misfeature\n * results in breakage when new options are added.  It also does not support\n * options appearing after non-options (e.g., \"cp foo bar -R\") since that is\n * a horrible GNU perversion.\n *\n * Upon encountering '--', it consumes that argument (by incrementing optind)\n * and returns NULL to signal the end of option processing.  Upon encountering\n * a bare '-' argument or any argument not starting with '-' it returns NULL\n * to signal the end of option processing (without consuming the argument).\n * Note that these behaviours do not apply when such strings are encountered\n * as arguments to options; e.g., if \"--foo\" takes an argument, then the\n * command line arguments \"--foo -- --bar\" is interpreted as having two\n * options (\"--foo --\" and \"--bar\") and no left-over arguments.\n */\n\n/* Work around LLVM bug. */\n#ifdef __clang__\n#warning Working around bug in LLVM optimizer\n#warning For more details see https://bugs.llvm.org/show_bug.cgi?id=27190\n#define GETOPT_USE_COMPUTED_GOTO\n#endif\n\n/* Work around broken <setjmp.h> header on Solaris. */\n#if defined(__GNUC__) && (defined(sun) || defined(__sun))\n#warning Working around broken <setjmp.h> header on Solaris\n#define GETOPT_USE_COMPUTED_GOTO\n#endif\n\n/* Select the method of performing local jumps. */\n#ifdef GETOPT_USE_COMPUTED_GOTO\n/* Workaround with computed goto. */\n#define DO_SETJMP DO_SETJMP_(__LINE__)\n#define DO_SETJMP_(x) DO_SETJMP__(x)\n#define DO_SETJMP__(x)\t\t\t\t\t\\\n\tvoid * getopt_initloop = && getopt_initloop_ ## x;\t\t\\\n\tgetopt_initloop_ ## x:\n#define DO_LONGJMP\t\t\t\t\t\t\t\\\n\tgoto *getopt_initloop\n#else\n/* Intended code, for fully C99-compliant systems. */\n#define DO_SETJMP\t\t\t\t\t\t\t\\\n\tsigjmp_buf getopt_initloop;\t\t\t\t\t\\\n\tif (!getopt_initialized)\t\t\t\t\t\\\n\t\tsigsetjmp(getopt_initloop, 0)\n#define DO_LONGJMP\t\t\t\t\t\t\t\\\n\tsiglongjmp(getopt_initloop, 1)\n#endif\n\n/* Avoid namespace collisions with libc getopt. */\n#define getopt\tlibcperciva_getopt\n#define optarg\tlibcperciva_optarg\n#define optind\tlibcperciva_optind\n#define opterr\tlibcperciva_opterr\n#define optreset\tlibcperciva_optreset\n\n/* Standard getopt global variables. */\nextern const char * optarg;\nextern int optind, opterr, optreset;\n\n/* Dummy option string, equal to \"(dummy)\". */\n#define GETOPT_DUMMY getopt_dummy\n\n/**\n * GETOPT(argc, argv):\n * When called for the first time (or the first time after optreset is set to\n * a nonzero value), return GETOPT_DUMMY, aka. \"(dummy)\".  Thereafter, return\n * the next option string and set optarg / optind appropriately; abort if not\n * properly initialized when not being called for the first time.\n */\n#define GETOPT(argc, argv) getopt(argc, argv)\n\n/**\n * GETOPT_SWITCH(ch):\n * Jump to the appropriate GETOPT_OPT, GETOPT_OPTARG, GETOPT_MISSING_ARG, or\n * GETOPT_DEFAULT based on the option string ${ch}.  When called for the first\n * time, perform magic to index the options.\n *\n * GETOPT_SWITCH(ch) is equivalent to \"switch (ch)\" in a standard getopt loop.\n */\n#define GETOPT_SWITCH(ch)\t\t\t\t\t\t\\\n\tvolatile size_t getopt_ln_min = __LINE__;\t\t\t\\\n\tvolatile size_t getopt_ln = getopt_ln_min - 1;\t\t\t\\\n\tvolatile int getopt_default_missing = 0;\t\t\t\\\n\tDO_SETJMP;\t\t\t\t\t\t\t\\\n\tswitch (getopt_initialized ? getopt_lookup(ch) + getopt_ln_min : getopt_ln++)\n\n/**\n * GETOPT_OPT(os):\n * Jump to this point when the option string ${os} is passed to GETOPT_SWITCH.\n *\n * GETOPT_OPT(\"-x\") is equivalent to \"case 'x'\" in a standard getopt loop\n * which has an optstring containing \"x\".\n */\n#define GETOPT_OPT(os)\tGETOPT_OPT_(os, __LINE__)\n#define GETOPT_OPT_(os, ln)\tGETOPT_OPT__(os, ln)\n#define GETOPT_OPT__(os, ln)\t\t\t\t\t\t\\\n\tcase ln:\t\t\t\t\t\t\t\\\n\t\tif (getopt_initialized)\t\t\t\t\t\\\n\t\t\tgoto getopt_skip_ ## ln;\t\t\t\\\n\t\tgetopt_register_opt(os, ln - getopt_ln_min, 0);\t\t\\\n\t\tDO_LONGJMP;\t\t\t\t\t\t\\\n\tgetopt_skip_ ## ln\n\n/**\n * GETOPT_OPTARG(os):\n * Jump to this point when the option string ${os} is passed to GETOPT_SWITCH,\n * unless no argument is available, in which case jump to GETOPT_MISSING_ARG\n * (if present) or GETOPT_DEFAULT (if not).\n *\n * GETOPT_OPTARG(\"-x\") is equivalent to \"case 'x'\" in a standard getopt loop\n * which has an optstring containing \"x:\".\n */\n#define GETOPT_OPTARG(os)\tGETOPT_OPTARG_(os, __LINE__)\n#define GETOPT_OPTARG_(os, ln)\tGETOPT_OPTARG__(os, ln)\n#define GETOPT_OPTARG__(os, ln)\t\t\t\t\t\t\\\n\tcase ln:\t\t\t\t\t\t\t\\\n\t\tif (getopt_initialized) {\t\t\t\t\\\n\t\t\tassert(optarg != NULL);\t\t\t\t\\\n\t\t\tgoto getopt_skip_ ## ln;\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\\\n\t\tgetopt_register_opt(os, ln - getopt_ln_min, 1);\t\t\\\n\t\tDO_LONGJMP;\t\t\t\t\t\t\\\n\tgetopt_skip_ ## ln\n\n/**\n * GETOPT_MISSING_ARG:\n * Jump to this point if an option string specified in GETOPT_OPTARG is seen\n * but no argument is available.\n *\n * GETOPT_MISSING_ARG is equivalent to \"case ':'\" in a standard getopt loop\n * which has an optstring starting with \":\".  As such, it also has the effect\n * of disabling warnings about invalid options, as if opterr had been zeroed.\n */\n#define GETOPT_MISSING_ARG\tGETOPT_MISSING_ARG_(__LINE__)\n#define GETOPT_MISSING_ARG_(ln)\tGETOPT_MISSING_ARG__(ln)\n#define GETOPT_MISSING_ARG__(ln)\t\t\t\t\t\\\n\tcase ln:\t\t\t\t\t\t\t\\\n\t\tif (getopt_initialized)\t\t\t\t\t\\\n\t\t\tgoto getopt_skip_ ## ln;\t\t\t\\\n\t\tgetopt_register_missing(ln - getopt_ln_min);\t\t\\\n\t\tDO_LONGJMP;\t\t\t\t\t\t\\\n\tgetopt_skip_ ## ln\n\n/**\n * GETOPT_DEFAULT:\n * Jump to this point if an unrecognized option is seen or if an option\n * specified in GETOPT_OPTARG is seen, no argument is available, and there is\n * no GETOPT_MISSING_ARG label.\n *\n * GETOPT_DEFAULT is equivalent to \"case '?'\" in a standard getopt loop.\n *\n * NOTE: This MUST be present in the GETOPT_SWITCH statement, and MUST occur\n * after all other GETOPT_* labels.\n */\n#define GETOPT_DEFAULT\t\tGETOPT_DEFAULT_(__LINE__)\n#define GETOPT_DEFAULT_(ln)\tGETOPT_DEFAULT__(ln)\n#define GETOPT_DEFAULT__(ln)\t\t\t\t\t\t\\\n\t\tgoto getopt_skip_ ## ln;\t\t\t\t\\\n\tcase ln:\t\t\t\t\t\t\t\\\n\t\tgetopt_initialized = 1;\t\t\t\t\t\\\n\t\tbreak;\t\t\t\t\t\t\t\\\n\tdefault:\t\t\t\t\t\t\t\\\n\t\tif (getopt_initialized)\t\t\t\t\t\\\n\t\t\tgoto getopt_skip_ ## ln;\t\t\t\\\n\t\tif (!getopt_default_missing) {\t\t\t\t\\\n\t\t\tgetopt_setrange(ln - getopt_ln_min);\t\t\\\n\t\t\tgetopt_default_missing = 1;\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\\\n\t\tDO_LONGJMP;\t\t\t\t\t\t\\\n\tgetopt_skip_ ## ln\n\n/*\n * The back-end implementation.  These should be considered internal\n * interfaces and not used directly.\n */\nconst char * getopt(int, char * const []);\nsize_t getopt_lookup(const char *);\nvoid getopt_register_opt(const char *, size_t, int);\nvoid getopt_register_missing(size_t);\nvoid getopt_setrange(size_t);\nextern const char * getopt_dummy;\nextern int getopt_initialized;\n\n#endif /* !GETOPT_H_ */\n"
  },
  {
    "path": "libcperciva/util/humansize.c",
    "content": "#include <stdio.h>\n\n#include \"asprintf.h\"\n#include \"warnp.h\"\n\n#include \"humansize.h\"\n\n/**\n * humansize(size):\n * Given a size ${size} in bytes, allocate and return a string of the form\n * \"<N> B\" for 0 <= N <= 999 or \"<X> <prefix>B\" where either 10 <= X <= 999 or\n * 1.0 <= X <= 9.9 and <prefix> is \"k\", \"M\", \"G\", \"T\", \"P\", or \"E\"; and where\n * the value returned is the largest valid value <= the provided size.\n */\nchar *\nhumansize(uint64_t size)\n{\n\tchar * s;\n\tchar prefix;\n\tint shiftcnt;\n\tint rc;\n\n\t/* Special-case for size < 1000. */\n\tif (size < 1000) {\n\t\trc = asprintf(&s, \"%d B\", (int)size);\n\t} else {\n\t\t/* Keep 10 * size / 1000^(3n) in size. */\n\t\tfor (size /= 100, shiftcnt = 1; size >= 10000; shiftcnt++)\n\t\t\tsize /= 1000;\n\n\t\t/*\n\t\t * Figure out what prefix to use.  Since 1 EB = 10^18 B and\n\t\t * the maximum value of a uint64_t is 2^64 which is roughly\n\t\t * 18.4 * 10^18, this cannot reference beyond the end of the\n\t\t * string.\n\t\t */\n\t\tprefix = \" kMGTPE\"[shiftcnt];\n\n\t\t/* Construct the string. */\n\t\tif (size < 100)\n\t\t\trc = asprintf(&s, \"%d.%d %cB\", (int)size / 10,\n\t\t\t    (int)size % 10, prefix);\n\t\telse\n\t\t\trc = asprintf(&s, \"%d %cB\", (int)size / 10, prefix);\n\t}\n\n\tif (rc == -1) {\n\t\twarnp(\"asprintf\");\n\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (s);\n\nerr0:\n\t/* Failure! */\n\treturn (NULL);\n}\n\n/**\n * humansize_parse(s, size):\n * Parse a string matching /[0-9]+ ?[kMGTPE]?B?/ as a size ${size} in bytes.\n */\nint\nhumansize_parse(const char * s, uint64_t * size)\n{\n\tint state = 0;\n\tuint64_t multiplier = 1;\n\n\tdo {\n\t\tswitch (state) {\n\t\tcase -1:\n\t\t\t/* Error state. */\n\t\t\tbreak;\n\t\tcase 0:\n\t\t\t/* Initial state. */\n\t\t\t*size = 0;\n\n\t\t\t/* We must start with at least one digit. */\n\t\t\tif ((*s < '0') || (*s > '9')) {\n\t\t\t\tstate = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* FALLTHROUGH */\n\t\tcase 1:\n\t\t\t/* We're now processing digits. */\n\t\t\tstate = 1;\n\n\t\t\t/* Digit-parsing state. */\n\t\t\tif (('0' <= *s) && (*s <= '9')) {\n\t\t\t\tif (*size > UINT64_MAX / 10)\n\t\t\t\t\tstate = -1;\n\t\t\t\telse\n\t\t\t\t\t*size *= 10;\n\t\t\t\tif (*size > UINT64_MAX - (uint64_t)(*s - '0'))\n\t\t\t\t\tstate = -1;\n\t\t\t\telse\n\t\t\t\t\t*size += (uint64_t)(*s - '0');\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* FALLTHROUGH */\n\t\tcase 2:\n\t\t\t/* We move into state 3 after an optional ' '. */\n\t\t\tstate = 3;\n\t\t\tif (*s == ' ')\n\t\t\t\tbreak;\n\n\t\t\t/* FALLTHROUGH */\n\t\tcase 3:\n\t\t\t/* We may have one SI prefix. */\n\t\t\tswitch (*s) {\n\t\t\tcase 'E':\n\t\t\t\tmultiplier *= 1000;\n\t\t\t\t/* FALLTHROUGH */\n\t\t\tcase 'P':\n\t\t\t\tmultiplier *= 1000;\n\t\t\t\t/* FALLTHROUGH */\n\t\t\tcase 'T':\n\t\t\t\tmultiplier *= 1000;\n\t\t\t\t/* FALLTHROUGH */\n\t\t\tcase 'G':\n\t\t\t\tmultiplier *= 1000;\n\t\t\t\t/* FALLTHROUGH */\n\t\t\tcase 'M':\n\t\t\t\tmultiplier *= 1000;\n\t\t\t\t/* FALLTHROUGH */\n\t\t\tcase 'k':\n\t\t\t\tmultiplier *= 1000;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* We move into state 4 after the optional prefix. */\n\t\t\tstate = 4;\n\t\t\tif (multiplier != 1)\n\t\t\t\tbreak;\n\n\t\t\t/* FALLTHROUGH */\n\t\tcase 4:\n\t\t\t/* We move into state 5 after an optional 'B'. */\n\t\t\tstate = 5;\n\t\t\tif (*s == 'B')\n\t\t\t\tbreak;\n\n\t\t\t/* FALLTHROUGH */\n\t\tcase 5:\n\t\t\t/* We have trailing garbage. */\n\t\t\tstate = -1;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Move on to the next character. */\n\t\ts++;\n\t} while ((state != -1) && (*s != '\\0'));\n\n\t/* Multiply by multiplier. */\n\tif (*size > UINT64_MAX / multiplier)\n\t\tstate = -1;\n\telse\n\t\t*size *= multiplier;\n\n\t/* Anything other than state -1 is success. */\n\treturn ((state == -1) ? -1 : 0);\n}\n"
  },
  {
    "path": "libcperciva/util/humansize.h",
    "content": "#ifndef HUMANSIZE_H_\n#define HUMANSIZE_H_\n\n#include <stdint.h>\n\n/**\n * humansize(size):\n * Given a size ${size} in bytes, allocate and return a string of the form\n * \"<N> B\" for 0 <= N <= 999 or \"<X> <prefix>B\" where either 10 <= X <= 999 or\n * 1.0 <= X <= 9.9 and <prefix> is \"k\", \"M\", \"G\", \"T\", \"P\", or \"E\"; and where\n * the value returned is the largest valid value <= the provided size.\n */\nchar * humansize(uint64_t);\n\n/**\n * humansize_parse(s, size):\n * Parse a string matching /[0-9]+ ?[kMGTPE]?B?/ as a size ${size} in bytes.\n */\nint humansize_parse(const char *, uint64_t *);\n\n#endif /* !HUMANSIZE_H_ */\n"
  },
  {
    "path": "libcperciva/util/insecure_memzero.c",
    "content": "#include <stddef.h>\n#include <stdint.h>\n\n#include \"insecure_memzero.h\"\n\n/* Function which does the zeroing. */\nstatic void\ninsecure_memzero_func(volatile void * buf, size_t len)\n{\n\tvolatile uint8_t * _buf = buf;\n\tsize_t i;\n\n\tfor (i = 0; i < len; i++)\n\t\t_buf[i] = 0;\n}\n\n/* Pointer to memory-zeroing function. */\nvoid (* volatile insecure_memzero_ptr)(volatile void *, size_t) =\n    insecure_memzero_func;\n"
  },
  {
    "path": "libcperciva/util/insecure_memzero.h",
    "content": "#ifndef INSECURE_MEMZERO_H_\n#define INSECURE_MEMZERO_H_\n\n#include <stddef.h>\n\n/* Pointer to memory-zeroing function. */\nextern void (* volatile insecure_memzero_ptr)(volatile void *, size_t);\n\n/**\n * insecure_memzero(buf, len):\n * Attempt to zero ${len} bytes at ${buf} in spite of optimizing compilers'\n * best (standards-compliant) attempts to remove the buffer-zeroing.  In\n * particular, to avoid performing the zeroing, a compiler would need to\n * use optimistic devirtualization; recognize that non-volatile objects do not\n * need to be treated as volatile, even if they are accessed via volatile\n * qualified pointers; and perform link-time optimization; in addition to the\n * dead-code elimination which often causes buffer-zeroing to be elided.\n *\n * Note however that zeroing a buffer does not guarantee that the data held\n * in the buffer is not stored elsewhere; in particular, there may be copies\n * held in CPU registers or in anonymous allocations on the stack, even if\n * every named variable is successfully sanitized.  Solving the \"wipe data\n * from the system\" problem will require a C language extension which does not\n * yet exist.\n *\n * For more information, see:\n * http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html\n * http://www.daemonology.net/blog/2014-09-06-zeroing-buffers-is-insufficient.html\n */\nstatic inline void\ninsecure_memzero(volatile void * buf, size_t len)\n{\n\n\t(insecure_memzero_ptr)(buf, len);\n}\n\n#endif /* !INSECURE_MEMZERO_H_ */\n"
  },
  {
    "path": "libcperciva/util/monoclock.c",
    "content": "#include <sys/time.h>\n\n#include <errno.h>\n#include <time.h>\n\n#include \"warnp.h\"\n\n#include \"monoclock.h\"\n\n/* Determine which clock(s) to use. */\n#ifndef POSIXFAIL_CLOCK_GETTIME\n#ifdef CLOCK_MONOTONIC\n#define USE_MONOTONIC\n#endif\n#ifndef POSIXFAIL_CLOCK_REALTIME\n#define USE_REALTIME\n#endif\n#endif\n\n/**\n * monoclock_get(tv):\n * Store the current time in ${tv}.  If CLOCK_MONOTONIC is available, use\n * that clock; if CLOCK_MONOTONIC is unavailable, use CLOCK_REALTIME (if\n * available) or gettimeofday(2).\n */\nint\nmonoclock_get(struct timeval * tv)\n{\n#if defined(USE_MONOTONIC) || defined(USE_REALTIME)\n\tstruct timespec tp;\n#endif\n\n#ifdef USE_MONOTONIC\n\tif (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) {\n\t\ttv->tv_sec = tp.tv_sec;\n\t\ttv->tv_usec = (suseconds_t)(tp.tv_nsec / 1000);\n\t} else if ((errno != ENOSYS) && (errno != EINVAL)) {\n\t\twarnp(\"clock_gettime(CLOCK_MONOTONIC)\");\n\t\tgoto err0;\n\t} else\n#endif\n#ifdef USE_REALTIME\n\tif (clock_gettime(CLOCK_REALTIME, &tp) == 0) {\n\t\ttv->tv_sec = tp.tv_sec;\n\t\ttv->tv_usec = (suseconds_t)(tp.tv_nsec / 1000);\n\t} else {\n\t\twarnp(\"clock_gettime(CLOCK_REALTIME)\");\n\t\tgoto err0;\n\t}\n#else\n\tif (gettimeofday(tv, NULL)) {\n\t\twarnp(\"gettimeofday\");\n\t\tgoto err0;\n\t}\n#endif\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n/**\n * monoclock_get_cputime(tv):\n * Store in ${tv} the duration the process has been running if\n * CLOCK_PROCESS_CPUTIME_ID is available; fall back to monoclock_get()\n * otherwise.\n */\nint\nmonoclock_get_cputime(struct timeval * tv)\n{\n\t/* Use CLOCK_PROCESS_CPUTIME_ID if available. */\n#ifdef CLOCK_PROCESS_CPUTIME_ID\n\tstruct timespec tp;\n\n\tif (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp) == 0) {\n\t\ttv->tv_sec = tp.tv_sec;\n\t\ttv->tv_usec = (suseconds_t)(tp.tv_nsec / 1000);\n\t} else if ((errno != ENOSYS) && (errno != EINVAL)) {\n\t\twarnp(\"clock_gettime(CLOCK_PROCESS_CPUTIME_ID)\");\n\t\tgoto err0;\n\t} else\n#endif\n\t/* Fall back to monoclock_get(). */\n\tif (monoclock_get(tv))\n\t\tgoto err0;\n\n\t/* Success! */\n\treturn (0);\n\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n/**\n * monoclock_getres(resd):\n * Store an upper limit on timer granularity in ${resd}.  If CLOCK_MONOTONIC\n * is available, use that clock; if CLOCK_MONOTONIC is unavailable, use\n * CLOCK_REALTIME (if available) or gettimeofday(2).  For this value to be\n * meaningful, we assume that clock_getres(x) succeeds iff clock_gettime(x)\n * succeeds.\n */\nint\nmonoclock_getres(double * resd)\n{\n#if defined(USE_MONOTONIC) || defined(USE_REALTIME)\n\tstruct timespec res;\n#endif\n\n#ifdef USE_MONOTONIC\n\tif (clock_getres(CLOCK_MONOTONIC, &res) == 0) {\n\t\t/* Convert clock resolution to a double. */\n\t\t*resd = (double)res.tv_sec + (double)res.tv_nsec * 0.000000001;\n\t} else if ((errno != ENOSYS) && (errno != EINVAL)) {\n\t\twarnp(\"clock_getres(CLOCK_MONOTONIC)\");\n\t\tgoto err0;\n\t} else\n#endif\n#ifdef USE_REALTIME\n\tif (clock_getres(CLOCK_REALTIME, &res) == 0) {\n\t\t/* Convert clock resolution to a double. */\n\t\t*resd = (double)res.tv_sec + (double)res.tv_nsec * 0.000000001;\n\t} else {\n\t\twarnp(\"clock_getres(CLOCK_REALTIME)\");\n\t\tgoto err0;\n\t}\n#else\n\t/*\n\t * We'll be using gettimeofday().  There is no standard way of getting\n\t * the resolution of this clock, but it seems safe to assume that it\n\t * ticks at a minimum rate of CLOCKS_PER_SEC Hz (even though that is\n\t * defined in relation to the measurement of processor time usage, not\n\t * wallclock time); on non-broken systems we'll be relying on\n\t * clock_gettime and clock_getres anyway.\n\t */\n\t*resd = 1.0 / CLOCKS_PER_SEC;\n#endif\n\n\t/* Success! */\n\treturn (0);\n\n#if defined(USE_MONOTONIC) || defined(USE_REALTIME)\nerr0:\n\t/* Failure! */\n\treturn (-1);\n#endif\n}\n"
  },
  {
    "path": "libcperciva/util/monoclock.h",
    "content": "#ifndef MONOCLOCK_H_\n#define MONOCLOCK_H_\n\n#include <sys/time.h>\n\n/* Macro to simplify benchmarks. */\n#define timeval_diff(x, y) ((double)((y).tv_sec - (x).tv_sec) +\t\t\\\n    (double)((y).tv_usec - (x).tv_usec) * 0.000001)\n\n/**\n * monoclock_get(tv):\n * Store the current time in ${tv}.  If CLOCK_MONOTONIC is available, use\n * that clock; if CLOCK_MONOTONIC is unavailable, use CLOCK_REALTIME (if\n * available) or gettimeofday(2).\n */\nint monoclock_get(struct timeval *);\n\n/**\n * monoclock_get_cputime(tv):\n * Store in ${tv} the duration the process has been running if\n * CLOCK_PROCESS_CPUTIME_ID is available; fall back to monoclock_get()\n * otherwise.\n */\nint monoclock_get_cputime(struct timeval *);\n\n/**\n * monoclock_getres(resd):\n * Store an upper limit on timer granularity in ${resd}.  If CLOCK_MONOTONIC\n * is available, use that clock; if CLOCK_MONOTONIC is unavailable, use\n * CLOCK_REALTIME (if available) or gettimeofday(2).  For this value to be\n * meaningful, we assume that clock_getres(x) succeeds iff clock_gettime(x)\n * succeeds.\n */\nint monoclock_getres(double *);\n\n#endif /* !MONOCLOCK_H_ */\n"
  },
  {
    "path": "libcperciva/util/parsenum.h",
    "content": "#ifndef PARSENUM_H_\n#define PARSENUM_H_\n\n#include <assert.h>\n#include <errno.h>\n#include <inttypes.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n/* Handle compiler warnings about implicit variable conversion in PARSENUM. */\n#ifdef __clang__\n\n/* Disable clang warnings. */\n#define PARSENUM_PROLOGUE\t\t\t\t\t\t\\\n_Pragma(\"clang diagnostic push\")\t\t\t\t\t\\\n_Pragma(\"clang diagnostic ignored \\\"-Wunknown-pragmas\\\"\")\t\t\\\n_Pragma(\"clang diagnostic ignored \\\"-Wfloat-conversion\\\"\")\t\t\\\n_Pragma(\"clang diagnostic ignored \\\"-Wsign-conversion\\\"\")\t\t\\\n_Pragma(\"clang diagnostic ignored \\\"-Wshorten-64-to-32\\\"\")\t\t\\\n_Pragma(\"clang diagnostic ignored \\\"-Wconversion\\\"\")\n\n/* Enable clang warnings for code outside of PARSENUM. */\n#define PARSENUM_EPILOGUE\t\t\t\t\t\t\\\n_Pragma(\"clang diagnostic pop\")\n\n/* Other compilers don't need any special handling */\n#else\n#define PARSENUM_PROLOGUE /* NOTHING */\n#define PARSENUM_EPILOGUE /* NOTHING */\n#endif /* !__clang__ */\n\n/* Print a message before assert(). */\n#define ASSERT_FAIL(s)\t\t\t\t\t\t\t\\\n\t(\t\t\t\t\t\t\t\t\\\n\t\tfprintf(stderr, \"Assertion failed: \" s\t\t\t\\\n\t\t    \", function %s, file %s, line %d\\n\",\t\t\\\n\t\t    __func__, __FILE__, __LINE__),\t\t\t\\\n\t\tabort()\t\t\t\t\t\t\t\\\n\t)\n\n/**\n * PARSENUM(x, s, min, max):\n * Parse the string ${s} according to the type of the unsigned integer, signed\n * integer, or floating-point number variable ${x}.  If the string consists of\n * optional whitespace followed by a number (and nothing else) and the numeric\n * interpretation of the number is between ${min} and ${max} inclusive, store\n * the value into ${x}, set errno to zero, and return zero.  Otherwise, return\n * nonzero with an unspecified value of ${x} and errno set to EINVAL or ERANGE\n * as appropriate.\n *\n * For floating-point and unsigned integer variables ${x}, this can also be\n * invoked as PARSENUM(x, s), in which case the minimum and maximum values are\n * set to +/- infinity or the limits of the unsigned integer type.\n */\n#define PARSENUM2(x, s)\t\t\t\t\t\t\t\\\n\tPARSENUM_EX4(x, s, 0, 0, \"PARSENUM\")\n#define PARSENUM4(x, s, min, max)\t\t\t\t\t\\\n\tPARSENUM_EX6(x, s, min, max, 0, 0, \"PARSENUM\")\n\n/* Magic to select which version of PARSENUM to use. */\n#define PARSENUM(...)\tPARSENUM_(PARSENUM_COUNT(__VA_ARGS__))(__VA_ARGS__)\n#define PARSENUM_(N)\tPARSENUM__(N)\n#define PARSENUM__(N)\tPARSENUM ## N\n#define PARSENUM_COUNT(...)\tPARSENUM_COUNT_(__VA_ARGS__, 4, 3, 2, 1)\n#define PARSENUM_COUNT_(_1, _2, _3, _4, N, ...)\tN\n\n/**\n * PARSENUM_EX(x, s, min, max, base, trailing):\n * Parse the string ${s} according to the type of the unsigned integer or\n * signed integer variable ${x}, in the specified ${base}.  If the string\n * consists of optional whitespace followed by a number (and nothing else) and\n * the numeric interpretation of the number is between ${min} and ${max}\n * inclusive, store the value into ${x}, set errno to zero, and return zero.\n * Otherwise, return nonzero with an unspecified value of ${x} and errno set\n * to EINVAL or ERANGE as appropriate.  The check for trailing characters (and\n * EINVAL if they are found) is disabled if ${trailing} is non-zero.\n *\n * For an unsigned integer variable ${x}, this can also be invoked as\n * PARSENUM_EX(x, s, base), in which case the minimum and maximum values are\n * set to the limits of the unsigned integer type.\n *\n * For a floating-point variable ${x}, the ${base} must be 0.\n */\n#define PARSENUM_EX4(x, s, base, trailing, _define_name)\t\t\\\n\t(\t\t\t\t\t\t\t\t\\\n\t\tPARSENUM_PROLOGUE\t\t\t\t\t\\\n\t\terrno = 0,\t\t\t\t\t\t\\\n\t\t(((*(x)) = 1, (*(x)) /= 2) > 0)\t?\t\t\t\\\n\t\t\t(((base) == 0) ?\t\t\t\t\\\n\t\t\t\t((*(x)) = parsenum_float((s),\t\t\\\n\t\t\t\t    (double)-INFINITY,\t\t\t\\\n\t\t\t\t    (double)INFINITY, (trailing))) :\t\\\n\t\t\t\t(ASSERT_FAIL(_define_name \" applied to\"\t\\\n\t\t\t\t    \" float with base != 0\"), 1)) :\t\\\n\t\t(((*(x)) = -1) > 0) ?\t\t\t\t\t\\\n\t\t\t((*(x)) = parsenum_unsigned((s), 0, (*(x)),\t\\\n\t\t\t    (*(x)), (base), (trailing))) :\t\t\\\n\t\t\t(ASSERT_FAIL(_define_name \" applied to signed\"\t\\\n\t\t\t    \" integer without specified bounds\"), 1),\t\\\n\t\terrno != 0\t\t\t\t\t\t\\\n\t\tPARSENUM_EPILOGUE\t\t\t\t\t\\\n\t)\n#define PARSENUM_EX6(x, s, min, max, base, trailing, _define_name)\t\\\n\t(\t\t\t\t\t\t\t\t\\\n\t\tPARSENUM_PROLOGUE\t\t\t\t\t\\\n\t\terrno = 0,\t\t\t\t\t\t\\\n\t\t(((*(x)) = 1, (*(x)) /= 2) > 0)\t?\t\t\t\\\n\t\t\t(((base) == 0) ?\t\t\t\t\\\n\t\t\t\t((*(x)) = parsenum_float((s),\t\t\\\n\t\t\t\t    (double)(min), (double)(max),\t\\\n\t\t\t\t    (trailing))) :\t\t\t\\\n\t\t\t\t(ASSERT_FAIL(_define_name \" applied to\"\t\\\n\t\t\t\t    \" float with base != 0\"), 1)) :\t\\\n\t\t(((*(x)) = -1) <= 0) ?\t\t\t\t\t\\\n\t\t\t((*(x)) = parsenum_signed((s),\t\t\t\\\n\t\t\t    ((*(x)) <= 0) ? (min) : 0,\t\t\t\\\n\t\t\t    ((*(x)) <= 0) ? (max) : 0, (base),\t\t\\\n\t\t\t    (trailing))) :\t\t\t\t\\\n\t\t\t(((*(x)) = parsenum_unsigned((s),\t\t\\\n\t\t\t    ((min) <= 0) ? 0 : (min),\t\t\t\\\n\t\t\t    (uintmax_t)(max), (*(x)), (base),\t\t\\\n\t\t\t    (trailing))),\t\t\t\t\\\n\t\t\t\t(((max) <= INTMAX_MAX) ?\t\t\\\n\t\t\t\t    (((intmax_t)(max) < 0) && (errno == 0)) ? \\\n\t\t\t\t\t(errno = ERANGE) :\t\t\\\n\t\t\t\t\t0 : 0)),\t\t\t\\\n\t\terrno != 0\t\t\t\t\t\t\\\n\t\tPARSENUM_EPILOGUE\t\t\t\t\t\\\n\t)\n\n/* Magic to select which version of PARSENUM_EX to use. */\n#define PARSENUM_EX(...)\t\t\t\t\t\t\\\n    PARSENUM_EX_(PARSENUM_EX_COUNT(__VA_ARGS__))(__VA_ARGS__, \"PARSENUM_EX\")\n#define PARSENUM_EX_(N)\tPARSENUM_EX__(N)\n#define PARSENUM_EX__(N)\tPARSENUM_EX ## N\n#define PARSENUM_EX_COUNT(...)\t\t\t\t\t\t\\\n    PARSENUM_EX_COUNT_(__VA_ARGS__, 6, 5, 4, 3, 2, 1)\n#define PARSENUM_EX_COUNT_(_1, _2, _3, _4, _5, _6, N, ...)\tN\n\n/* Functions for performing the parsing and parameter checking. */\nstatic inline double\nparsenum_float(const char * s, double min, double max, int trailing)\n{\n\tchar * eptr;\n\tdouble val;\n\n\t/* Sanity check. */\n\tassert(s != NULL);\n\n\tval = strtod(s, &eptr);\n\tif (eptr == s || (!trailing && (*eptr != '\\0')))\n\t\terrno = EINVAL;\n\telse if ((val < min) || (val > max))\n\t\terrno = ERANGE;\n\treturn (val);\n}\n\nstatic inline intmax_t\nparsenum_signed(const char * s, intmax_t min, intmax_t max, int base,\n    int trailing)\n{\n\tchar * eptr;\n\tintmax_t val;\n\n\t/* Sanity check. */\n\tassert(s != NULL);\n\n\tval = strtoimax(s, &eptr, base);\n\tif (eptr == s || (!trailing && (*eptr != '\\0')))\n\t\terrno = EINVAL;\n\telse if ((val < min) || (val > max)) {\n\t\terrno = ERANGE;\n\t\tval = 0;\n\t}\n\treturn (val);\n}\n\nstatic inline uintmax_t\nparsenum_unsigned(const char * s, uintmax_t min, uintmax_t max,\n    uintmax_t typemax, int base, int trailing)\n{\n\tchar * eptr;\n\tuintmax_t val;\n\n\t/* Sanity check. */\n\tassert(s != NULL);\n\n\tval = strtoumax(s, &eptr, base);\n\tif (eptr == s || (!trailing && (*eptr != '\\0')))\n\t\terrno = EINVAL;\n\telse if ((val < min) || (val > max) || (val > typemax))\n\t\terrno = ERANGE;\n\treturn (val);\n}\n\n#endif /* !PARSENUM_H_ */\n"
  },
  {
    "path": "libcperciva/util/readpass.c",
    "content": "#include <signal.h>\n#include <stdio.h>\n#include <string.h>\n#include <termios.h>\n#include <unistd.h>\n\n#include \"insecure_memzero.h\"\n#include \"warnp.h\"\n\n#include \"readpass.h\"\n\n#define MAXPASSLEN 2048\n\n/* Signals we need to block. */\nstatic const int badsigs[] = {\n\tSIGALRM, SIGHUP, SIGINT,\n\tSIGPIPE, SIGQUIT, SIGTERM,\n\tSIGTSTP, SIGTTIN, SIGTTOU\n};\n#define NSIGS sizeof(badsigs)/sizeof(badsigs[0])\n\n/* Highest signal number we care about. */\n#define MAX2(a, b) ((a) > (b) ? (a) : (b))\n#define MAX4(a, b, c, d) MAX2(MAX2(a, b), MAX2(c, d))\n#define MAX8(a, b, c, d, e, f, g, h) MAX2(MAX4(a, b, c, d), MAX4(e, f, g, h))\n#define MAXBADSIG\tMAX2(SIGALRM, MAX8(SIGHUP, SIGINT, SIGPIPE, SIGQUIT, \\\n\t\t\t    SIGTERM, SIGTSTP, SIGTTIN, SIGTTOU))\n\n/* Has a signal of this type been received? */\nstatic volatile sig_atomic_t gotsig[MAXBADSIG + 1];\n\n/* Signal handler. */\nstatic void\nhandle(int sig)\n{\n\n\tgotsig[sig] = 1;\n}\n\n/* Restore old signals and re-issue intercepted signals. */\nstatic void\nresetsigs(struct sigaction savedsa[NSIGS])\n{\n\tsize_t i;\n\n\t/* Restore old signals. */\n\tfor (i = 0; i < NSIGS; i++)\n\t\tsigaction(badsigs[i], &savedsa[i], NULL);\n\n\t/* If we intercepted a signal, re-issue it. */\n\tfor (i = 0; i < NSIGS; i++) {\n\t\tif (gotsig[badsigs[i]])\n\t\t\traise(badsigs[i]);\n\t}\n}\n\n/**\n * readpass(passwd, prompt, confirmprompt, devtty):\n * If ${devtty} is 0, read a password from stdin.  If ${devtty} is 1, read a\n * password from /dev/tty if possible; if not, read from stdin.  If ${devtty}\n * is 2, read a password from /dev/tty if possible; if not, exit with an error.\n * If reading from a tty (either /dev/tty or stdin), disable echo and prompt\n * the user by printing ${prompt} to stderr.  If ${confirmprompt} is non-NULL,\n * read a second password (prompting if a terminal is being used) and repeat\n * until the user enters the same password twice.  Return the password as a\n * malloced NUL-terminated string via ${passwd}.\n */\nint\nreadpass(char ** passwd, const char * prompt,\n    const char * confirmprompt, int devtty)\n{\n\tFILE * readfrom;\n\tchar passbuf[MAXPASSLEN];\n\tchar confpassbuf[MAXPASSLEN];\n\tstruct sigaction sa, savedsa[NSIGS];\n\tstruct termios term, term_old;\n\tsize_t i;\n\tint usingtty;\n\n\t/* Where should we read the password from? */\n\tswitch (devtty) {\n\tcase 0:\n\t\t/* Read directly from stdin. */\n\t\treadfrom = stdin;\n\t\tbreak;\n\tcase 1:\n\t\t/* Try to open /dev/tty; if that fails, read from stdin. */\n\t\tif ((readfrom = fopen(\"/dev/tty\", \"r\")) == NULL)\n\t\t\treadfrom = stdin;\n\t\tbreak;\n\tcase 2:\n\t\t/* Try to open /dev/tty; if that fails, bail. */\n\t\tif ((readfrom = fopen(\"/dev/tty\", \"r\")) == NULL) {\n\t\t\twarnp(\"fopen(/dev/tty)\");\n\t\t\tgoto err1;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\twarn0(\"readpass does not support devtty=%d\", devtty);\n\t\tgoto err1;\n\t}\n\n\t/* We have not received any signals yet. */\n\tfor (i = 0; i <= MAXBADSIG; i++)\n\t\tgotsig[i] = 0;\n\n\t/*\n\t * If we receive a signal while we're reading the password, we might\n\t * end up with echo disabled; to prevent this, we catch the signals\n\t * here, and we'll re-send them to ourselves later after we re-enable\n\t * terminal echo.\n\t */\n\tsa.sa_handler = handle;\n\tsa.sa_flags = 0;\n\tsigemptyset(&sa.sa_mask);\n\tfor (i = 0; i < NSIGS; i++)\n\t\tsigaction(badsigs[i], &sa, &savedsa[i]);\n\n\t/* If we're reading from a terminal, try to disable echo. */\n\tif ((usingtty = isatty(fileno(readfrom))) != 0) {\n\t\tif (tcgetattr(fileno(readfrom), &term_old)) {\n\t\t\twarnp(\"Cannot read terminal settings\");\n\t\t\tgoto err2;\n\t\t}\n\t\tmemcpy(&term, &term_old, sizeof(struct termios));\n\t\tterm.c_lflag = (term.c_lflag & ~((tcflag_t)ECHO)) | ECHONL;\n\t\tif (tcsetattr(fileno(readfrom), TCSANOW, &term)) {\n\t\t\twarnp(\"Cannot set terminal settings\");\n\t\t\tgoto err2;\n\t\t}\n\t}\n\nretry:\n\t/* If we have a terminal, prompt the user to enter the password. */\n\tif (usingtty)\n\t\tfprintf(stderr, \"%s: \", prompt);\n\n\t/* Read the password. */\n\tif (fgets(passbuf, MAXPASSLEN, readfrom) == NULL) {\n\t\tif (feof(readfrom))\n\t\t\twarn0(\"EOF reading password\");\n\t\telse\n\t\t\twarnp(\"Cannot read password\");\n\t\tgoto err3;\n\t}\n\n\t/* Confirm the password if necessary. */\n\tif (confirmprompt != NULL) {\n\t\tif (usingtty)\n\t\t\tfprintf(stderr, \"%s: \", confirmprompt);\n\t\tif (fgets(confpassbuf, MAXPASSLEN, readfrom) == NULL) {\n\t\t\tif (feof(readfrom))\n\t\t\t\twarn0(\"EOF reading password\");\n\t\t\telse\n\t\t\t\twarnp(\"Cannot read password\");\n\t\t\tgoto err3;\n\t\t}\n\t\tif (strcmp(passbuf, confpassbuf)) {\n\t\t\tfprintf(stderr,\n\t\t\t    \"Passwords mismatch, please try again\\n\");\n\t\t\tgoto retry;\n\t\t}\n\t}\n\n\t/* Terminate the string at the first \"\\r\" or \"\\n\" (if any). */\n\tpassbuf[strcspn(passbuf, \"\\r\\n\")] = '\\0';\n\n\t/* If we changed terminal settings, reset them. */\n\tif (usingtty)\n\t\ttcsetattr(fileno(readfrom), TCSANOW, &term_old);\n\n\t/* Restore old signals and re-issue intercepted signals. */\n\tresetsigs(savedsa);\n\n\t/* Close /dev/tty if we opened it. */\n\tif ((readfrom != stdin) && fclose(readfrom))\n\t\twarnp(\"fclose\");\n\n\t/* Copy the password out. */\n\tif ((*passwd = strdup(passbuf)) == NULL) {\n\t\twarnp(\"Cannot allocate memory\");\n\t\tgoto err1;\n\t}\n\n\t/*\n\t * Zero any stored passwords.  This is not guaranteed to work, since a\n\t * \"sufficiently intelligent\" compiler can optimize these out due to\n\t * the values not being accessed again; and even if we outwitted the\n\t * compiler, all we can do is ensure that *a* buffer is zeroed but\n\t * not that it is the only buffer containing the data in question.\n\t * Unfortunately the C standard does not provide any way to mark data\n\t * as \"sensitive\" in order to prevent extra copies being sprinkled\n\t * around the implementation address space.\n\t */\n\tinsecure_memzero(passbuf, MAXPASSLEN);\n\tinsecure_memzero(confpassbuf, MAXPASSLEN);\n\n\t/* Success! */\n\treturn (0);\n\nerr3:\n\t/* Reset terminal settings if necessary. */\n\tif (usingtty)\n\t\ttcsetattr(fileno(readfrom), TCSAFLUSH, &term_old);\nerr2:\n\t/* Close /dev/tty if we opened it. */\n\tif ((readfrom != stdin) && fclose(readfrom))\n\t\twarnp(\"fclose\");\n\n\t/* Restore old signals and re-issue intercepted signals. */\n\tresetsigs(savedsa);\nerr1:\n\t/* Zero any stored passwords. */\n\tinsecure_memzero(passbuf, MAXPASSLEN);\n\tinsecure_memzero(confpassbuf, MAXPASSLEN);\n\n\t/* Failure! */\n\treturn (-1);\n}\n"
  },
  {
    "path": "libcperciva/util/readpass.h",
    "content": "#ifndef READPASS_H_\n#define READPASS_H_\n\n/* Avoid namespace collisions with other \"readpass\" functions. */\n#ifdef readpass\n#undef readpass\n#endif\n#define readpass libcperciva_readpass\n\n/**\n * readpass(passwd, prompt, confirmprompt, devtty):\n * If ${devtty} is 0, read a password from stdin.  If ${devtty} is 1, read a\n * password from /dev/tty if possible; if not, read from stdin.  If ${devtty}\n * is 2, read a password from /dev/tty if possible; if not, exit with an error.\n * If reading from a tty (either /dev/tty or stdin), disable echo and prompt\n * the user by printing ${prompt} to stderr.  If ${confirmprompt} is non-NULL,\n * read a second password (prompting if a terminal is being used) and repeat\n * until the user enters the same password twice.  Return the password as a\n * malloced NUL-terminated string via ${passwd}.\n */\nint readpass(char **, const char *, const char *, int);\n\n/**\n * readpass_file(passwd, filename):\n * Read a passphrase from ${filename} and return it as a malloced\n * NUL-terminated string via ${passwd}.  Print an error and fail if the file\n * is 2048 characters or more, or if it contains any newline \\n or \\r\\n\n * characters other than at the end of the file.  Do not include the \\n or\n * \\r\\n characters in the passphrase.\n */\nint readpass_file(char **, const char *);\n\n#endif /* !READPASS_H_ */\n"
  },
  {
    "path": "libcperciva/util/readpass_file.c",
    "content": "#include <stdio.h>\n#include <string.h>\n\n#include \"insecure_memzero.h\"\n#include \"warnp.h\"\n\n#include \"readpass.h\"\n\n/* Maximum file length. */\n#define MAXPASSLEN 2048\n\n/**\n * readpass_file(passwd, filename):\n * Read a passphrase from ${filename} and return it as a malloced\n * NUL-terminated string via ${passwd}.  Print an error and fail if the file\n * is 2048 characters or more, or if it contains any newline \\n or \\r\\n\n * characters other than at the end of the file.  Do not include the \\n or\n * \\r\\n characters in the passphrase.\n */\nint\nreadpass_file(char ** passwd, const char * filename)\n{\n\tFILE * f;\n\tchar passbuf[MAXPASSLEN];\n\n\t/* Open the file. */\n\tif ((f = fopen(filename, \"r\")) == NULL) {\n\t\twarnp(\"fopen(%s)\", filename);\n\t\tgoto err1;\n\t}\n\n\t/* Get a line from the file. */\n\tif ((fgets(passbuf, MAXPASSLEN, f)) == NULL) {\n\t\tif (ferror(f)) {\n\t\t\twarnp(\"fread(%s)\", filename);\n\t\t\tgoto err2;\n\t\t} else {\n\t\t\t/* We have a 0-byte password. */\n\t\t\tpassbuf[0] = '\\0';\n\t\t}\n\t}\n\n\t/* Bail if there's the line is too long, or if there's a second line. */\n\tif (fgetc(f) != EOF) {\n\t\twarn0(\"line too long, or more than 1 line in %s\", filename);\n\t\tgoto err2;\n\t}\n\n\t/* Close the file. */\n\tif (fclose(f)) {\n\t\twarnp(\"fclose(%s)\", filename);\n\t\tgoto err1;\n\t}\n\n\t/* Truncate at any newline character. */\n\tpassbuf[strcspn(passbuf, \"\\r\\n\")] = '\\0';\n\n\t/* Copy the password out. */\n\tif ((*passwd = strdup(passbuf)) == NULL) {\n\t\twarnp(\"Cannot allocate memory\");\n\t\tgoto err1;\n\t}\n\n\t/* Clean up. */\n\tinsecure_memzero(passbuf, MAXPASSLEN);\n\n\t/* Success! */\n\treturn (0);\n\nerr2:\n\tif (fclose(f))\n\t\twarnp(\"fclose\");\nerr1:\n\t/* No harm in running this for all error paths. */\n\tinsecure_memzero(passbuf, MAXPASSLEN);\n\n\t/* Failure! */\n\treturn (-1);\n}\n"
  },
  {
    "path": "libcperciva/util/sysendian.h",
    "content": "#ifndef SYSENDIAN_H_\n#define SYSENDIAN_H_\n\n#include <stdint.h>\n\n/* Avoid namespace collisions with BSD <sys/endian.h>. */\n#define be16dec libcperciva_be16dec\n#define be16enc libcperciva_be16enc\n#define be32dec libcperciva_be32dec\n#define be32enc libcperciva_be32enc\n#define be64dec libcperciva_be64dec\n#define be64enc libcperciva_be64enc\n#define le16dec libcperciva_le16dec\n#define le16enc libcperciva_le16enc\n#define le32dec libcperciva_le32dec\n#define le32enc libcperciva_le32enc\n#define le64dec libcperciva_le64dec\n#define le64enc libcperciva_le64enc\n\nstatic inline uint16_t\nbe16dec(const void * pp)\n{\n\tconst uint8_t * p = (uint8_t const *)pp;\n\n\treturn (uint16_t)((uint16_t)(p[1]) | ((uint16_t)(p[0]) << 8));\n}\n\nstatic inline void\nbe16enc(void * pp, uint16_t x)\n{\n\tuint8_t * p = (uint8_t *)pp;\n\n\tp[1] = x & 0xff;\n\tp[0] = (x >> 8) & 0xff;\n}\n\nstatic inline uint32_t\nbe32dec(const void * pp)\n{\n\tconst uint8_t * p = (uint8_t const *)pp;\n\n\treturn ((uint32_t)(p[3]) | ((uint32_t)(p[2]) << 8) |\n\t    ((uint32_t)(p[1]) << 16) | ((uint32_t)(p[0]) << 24));\n}\n\nstatic inline void\nbe32enc(void * pp, uint32_t x)\n{\n\tuint8_t * p = (uint8_t *)pp;\n\n\tp[3] = x & 0xff;\n\tp[2] = (x >> 8) & 0xff;\n\tp[1] = (x >> 16) & 0xff;\n\tp[0] = (x >> 24) & 0xff;\n}\n\nstatic inline uint64_t\nbe64dec(const void * pp)\n{\n\tconst uint8_t * p = (uint8_t const *)pp;\n\n\treturn ((uint64_t)(p[7]) | ((uint64_t)(p[6]) << 8) |\n\t    ((uint64_t)(p[5]) << 16) | ((uint64_t)(p[4]) << 24) |\n\t    ((uint64_t)(p[3]) << 32) | ((uint64_t)(p[2]) << 40) |\n\t    ((uint64_t)(p[1]) << 48) | ((uint64_t)(p[0]) << 56));\n}\n\nstatic inline void\nbe64enc(void * pp, uint64_t x)\n{\n\tuint8_t * p = (uint8_t *)pp;\n\n\tp[7] = x & 0xff;\n\tp[6] = (x >> 8) & 0xff;\n\tp[5] = (x >> 16) & 0xff;\n\tp[4] = (x >> 24) & 0xff;\n\tp[3] = (x >> 32) & 0xff;\n\tp[2] = (x >> 40) & 0xff;\n\tp[1] = (x >> 48) & 0xff;\n\tp[0] = (x >> 56) & 0xff;\n}\n\nstatic inline uint16_t\nle16dec(const void * pp)\n{\n\tconst uint8_t * p = (uint8_t const *)pp;\n\n\treturn (uint16_t)((uint16_t)(p[0]) | ((uint16_t)(p[1]) << 8));\n}\n\nstatic inline void\nle16enc(void * pp, uint16_t x)\n{\n\tuint8_t * p = (uint8_t *)pp;\n\n\tp[0] = x & 0xff;\n\tp[1] = (x >> 8) & 0xff;\n}\n\nstatic inline uint32_t\nle32dec(const void * pp)\n{\n\tconst uint8_t * p = (uint8_t const *)pp;\n\n\treturn ((uint32_t)(p[0]) | ((uint32_t)(p[1]) << 8) |\n\t    ((uint32_t)(p[2]) << 16) | ((uint32_t)(p[3]) << 24));\n}\n\nstatic inline void\nle32enc(void * pp, uint32_t x)\n{\n\tuint8_t * p = (uint8_t *)pp;\n\n\tp[0] = x & 0xff;\n\tp[1] = (x >> 8) & 0xff;\n\tp[2] = (x >> 16) & 0xff;\n\tp[3] = (x >> 24) & 0xff;\n}\n\nstatic inline uint64_t\nle64dec(const void * pp)\n{\n\tconst uint8_t * p = (uint8_t const *)pp;\n\n\treturn ((uint64_t)(p[0]) | ((uint64_t)(p[1]) << 8) |\n\t    ((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |\n\t    ((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40) |\n\t    ((uint64_t)(p[6]) << 48) | ((uint64_t)(p[7]) << 56));\n}\n\nstatic inline void\nle64enc(void * pp, uint64_t x)\n{\n\tuint8_t * p = (uint8_t *)pp;\n\n\tp[0] = x & 0xff;\n\tp[1] = (x >> 8) & 0xff;\n\tp[2] = (x >> 16) & 0xff;\n\tp[3] = (x >> 24) & 0xff;\n\tp[4] = (x >> 32) & 0xff;\n\tp[5] = (x >> 40) & 0xff;\n\tp[6] = (x >> 48) & 0xff;\n\tp[7] = (x >> 56) & 0xff;\n}\n\n#endif /* !SYSENDIAN_H_ */\n"
  },
  {
    "path": "libcperciva/util/warnp.c",
    "content": "#include <errno.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <syslog.h>\n\n#include \"warnp.h\"\n\nstatic int initialized = 0;\nstatic char * name = NULL;\nstatic int use_syslog = 0;\nstatic int syslog_priority = LOG_WARNING;\n\n/* Free the name string and clean up writing to the syslog (if applicable). */\nstatic void\nwarnp_atexit(void)\n{\n\n\t/* Clean up writing to the syslog (if applicable). */\n\tif (use_syslog)\n\t\tcloselog();\n\n\tfree(name);\n\tname = NULL;\n}\n\n/**\n * warnp_setprogname(progname):\n * Set the program name to be used by warn() and warnx() to ${progname}.\n */\nvoid\nwarnp_setprogname(const char * progname)\n{\n\tconst char * p;\n\n\t/* Free the name if we already have one. */\n\tfree(name);\n\n\t/* Find the last segment of the program name. */\n\tfor (p = progname; progname[0] != '\\0'; progname++)\n\t\tif (progname[0] == '/')\n\t\t\tp = progname + 1;\n\n\t/* Copy the name string. */\n\tname = strdup(p);\n\n\t/* If we haven't already done so, register our exit handler. */\n\tif (initialized == 0) {\n\t\tatexit(warnp_atexit);\n\t\tinitialized = 1;\n\t}\n}\n\n/* This function will preserve errno. */\nvoid\nwarn(const char * fmt, ...)\n{\n\tva_list ap;\n\tchar msgbuf[WARNP_SYSLOG_MAX_LINE + 1];\n\tint saved_errno;\n\n\t/* Save errno in case it gets clobbered. */\n\tsaved_errno = errno;\n\n\tva_start(ap, fmt);\n\tif (use_syslog == 0) {\n\t\t/* Stop other threads writing to stderr. */\n\t\tflockfile(stderr);\n\n\t\t/* Print to stderr. */\n\t\tfprintf(stderr, \"%s\", (name != NULL) ? name : \"(unknown)\");\n\t\tif (fmt != NULL) {\n\t\t\tfprintf(stderr, \": \");\n\t\t\tvfprintf(stderr, fmt, ap);\n\t\t}\n\t\tfprintf(stderr, \": %s\\n\", strerror(saved_errno));\n\n\t\t/* Allow other threads to write to stderr. */\n\t\tfunlockfile(stderr);\n\t} else {\n\t\t/* Print to syslog. */\n\t\tif (fmt != NULL) {\n\t\t\t/* No need to print \"${name}: \"; syslog does it. */\n\t\t\tvsnprintf(msgbuf, WARNP_SYSLOG_MAX_LINE + 1, fmt, ap);\n\t\t\tsyslog(syslog_priority, \"%s: %s\\n\", msgbuf,\n\t\t\t    strerror(saved_errno));\n\t\t} else\n\t\t\tsyslog(syslog_priority, \"%s\\n\", strerror(saved_errno));\n\t}\n\tva_end(ap);\n\n\t/* Restore saved errno. */\n\terrno = saved_errno;\n}\n\n/* This function will preserve errno. */\nvoid\nwarnx(const char * fmt, ...)\n{\n\tva_list ap;\n\tchar msgbuf[WARNP_SYSLOG_MAX_LINE + 1];\n\tint saved_errno;\n\n\t/* Save errno in case it gets clobbered. */\n\tsaved_errno = errno;\n\n\tva_start(ap, fmt);\n\tif (use_syslog == 0) {\n\t\t/* Stop other threads writing to stderr. */\n\t\tflockfile(stderr);\n\n\t\t/* Print to stderr. */\n\t\tfprintf(stderr, \"%s\", (name != NULL) ? name : \"(unknown)\");\n\t\tif (fmt != NULL) {\n\t\t\tfprintf(stderr, \": \");\n\t\t\tvfprintf(stderr, fmt, ap);\n\t\t}\n\t\tfprintf(stderr, \"\\n\");\n\n\t\t/* Allow other threads to write to stderr. */\n\t\tfunlockfile(stderr);\n\t} else {\n\t\t/* Print to syslog. */\n\t\tif (fmt != NULL) {\n\t\t\t/* No need to print \"${name}: \"; syslog does it. */\n\t\t\tvsnprintf(msgbuf, WARNP_SYSLOG_MAX_LINE + 1, fmt, ap);\n\t\t\tsyslog(syslog_priority, \"%s\\n\", msgbuf);\n\t\t} else\n\t\t\tsyslog(syslog_priority, \"\\n\");\n\t}\n\tva_end(ap);\n\n\t/* Restore saved errno. */\n\terrno = saved_errno;\n}\n\n/**\n * warnp_syslog(enable):\n * Send future messages to syslog if ${enable} is non-zero.  Messages to\n * syslog will be truncated at WARNP_SYSLOG_MAX_LINE characters.\n */\nvoid\nwarnp_syslog(int enable)\n{\n\n\t/* Clean up writing to the syslog (if applicable). */\n\tif (use_syslog && !enable)\n\t\tcloselog();\n\n\tuse_syslog = enable;\n}\n\n/**\n * warnp_syslog_priority(priority):\n * Tag future syslog messages with priority ${priority}.  Do not enable\n * syslog messages; for that, use warnp_syslog().\n */\nvoid\nwarnp_syslog_priority(int priority)\n{\n\n\tsyslog_priority = priority;\n}\n"
  },
  {
    "path": "libcperciva/util/warnp.h",
    "content": "#ifndef WARNP_H_\n#define WARNP_H_\n\n#include <errno.h>\n#include <stddef.h>\n\n/* Avoid namespace collisions with BSD <err.h>. */\n#define warn libcperciva_warn\n#define warnx libcperciva_warnx\n\n/*\n * Maximum length of messages sent to syslog; longer warnings will\n * be truncated.\n */\n#define WARNP_SYSLOG_MAX_LINE 4095\n\n/**\n * warnp_setprogname(progname):\n * Set the program name to be used by warn() and warnx() to ${progname}.\n */\nvoid warnp_setprogname(const char *);\n#define WARNP_INIT\tdo {\t\t\\\n\tif (argv[0] != NULL)\t\t\\\n\t\twarnp_setprogname(argv[0]);\t\\\n} while (0)\n\n/**\n * warnp_syslog(enable):\n * Send future messages to syslog if ${enable} is non-zero.  Messages to\n * syslog will be truncated at WARNP_SYSLOG_MAX_LINE characters.\n */\nvoid warnp_syslog(int);\n\n/**\n * warnp_syslog_priority(priority):\n * Tag future syslog messages with priority ${priority}.  Do not enable\n * syslog messages; for that, use warnp_syslog().\n */\nvoid warnp_syslog_priority(int);\n\n/* As in BSD <err.h>. */\nvoid warn(const char *, ...);\nvoid warnx(const char *, ...);\n\n/*\n * If compiled with DEBUG defined, print __FILE__ and __LINE__.\n */\n#ifdef DEBUG\n#define warnline\tdo {\t\t\t\t\\\n\twarnx(\"%s, %d\", __FILE__, __LINE__);\t\\\n} while (0)\n#else\n#define warnline\n#endif\n\n/*\n * Call warn(3) or warnx(3) depending upon whether errno == 0; and clear\n * errno (so that the standard error message isn't repeated later).\n */\n#define\twarnp(...) do {\t\t\t\t\t\\\n\twarnline;\t\t\t\t\t\\\n\tif (errno != 0) {\t\t\t\t\\\n\t\twarn(__VA_ARGS__);\t\t\\\n\t\terrno = 0;\t\t\t\t\\\n\t} else\t\t\t\t\t\t\\\n\t\twarnx(__VA_ARGS__);\t\t\\\n} while (0)\n\n/*\n * Call warnx(3) and set errno == 0.  Unlike warnp(), this should be used\n * in cases where we're reporting a problem which we discover ourselves\n * rather than one which is reported to us from a library or the kernel.\n */\n#define warn0(...) do {\t\t\t\t\t\\\n\twarnline;\t\t\t\t\t\\\n\twarnx(__VA_ARGS__);\t\t\t\\\n\terrno = 0;\t\t\t\t\t\\\n} while (0)\n\n#endif /* !WARNP_H_ */\n"
  },
  {
    "path": "libscrypt-kdf/scrypt-kdf.h",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n * This file was originally written by Colin Percival as part of the Tarsnap\n * online backup system.\n */\n#ifndef SCRYPT_KDF_H\n#define SCRYPT_KDF_H\n\n#include <stddef.h>\n#include <stdint.h>\n\n/* Compatibility for C++. */\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Internal name of function. */\n#define scrypt_kdf crypto_scrypt\n\n/**\n * scrypt_kdf(passwd, passwdlen, salt, saltlen, N, r, p, buf, buflen):\n * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r,\n * p, buflen) and write the result into buf.  The parameters r, p, and buflen\n * must satisfy r * p < 2^30 and buflen <= (2^32 - 1) * 32.  The parameter N\n * must be a power of 2 greater than 1.\n *\n * Return 0 on success; or -1 on error.\n */\nint scrypt_kdf(const uint8_t *, size_t, const uint8_t *, size_t, uint64_t,\n    uint32_t, uint32_t, uint8_t *, size_t);\n\n/* End compatibility for C++. */\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* !SCRYPT_KDF_H */\n"
  },
  {
    "path": "m4/check_darwin_paths.m4",
    "content": "# CHECK_DARWIN_PATHS\n# -------------------\nAC_DEFUN([CHECK_DARWIN_PATHS],\n[AC_REQUIRE([AC_CANONICAL_TARGET])\n\ncase $target_os in\n*darwin*)\n\t# Get the homebrew directory, which varies based on arch.\n\tcase \"$(uname -m)\" in\n\tarm64)\n\t\thomebrew_dir=/opt/homebrew\n\t\t;;\n\t*)\n\t\thomebrew_dir=/usr/local\n\t\t;;\n\tesac\n\n\t# Use the homebrew directory to specify the paths to openssl.\n\tCPPFLAGS=\"${CPPFLAGS} -I${homebrew_dir}/opt/openssl/include\"\n\tLDFLAGS=\"${LDFLAGS} -L${homebrew_dir}/opt/openssl/lib\"\n\t;;\nesac\n])# CHECK_DARWIN_PATHS\n"
  },
  {
    "path": "m4/check_disable_compiler_warnings.m4",
    "content": "# CHECK_DISABLE_COMPILER_WARNINGS\n# -------------------------------\nAC_DEFUN([CHECK_DISABLE_COMPILER_WARNINGS], [\n\tAC_MSG_CHECKING([compiler_warnings])\n\tAC_ARG_ENABLE(compiler_warnings,\n\t   AS_HELP_STRING([--disable-compiler-warnings],\n\t       [Do not request compiler warnings. @<:@default=enabled@:>@]),\n\t   [ac_compiler_warnings=$enableval],\n\t   [ac_compiler_warnings=yes])\n\tAC_MSG_RESULT([${ac_compiler_warnings}])\n\tAS_IF([test x${ac_compiler_warnings} = xyes],\n\t   [AX_CFLAGS_WARN_ALL])\n])# CHECK_DISABLE_COMPILER_WARNINGS\n"
  },
  {
    "path": "m4/check_libcperciva_posix.m4",
    "content": "# CHECK_LIBCPERCIVA_POSIX([LIBCPERCIVA_DIR])\n# ------------------------------------------\nAC_DEFUN([CHECK_LIBCPERCIVA_POSIX], [\n\tAC_REQUIRE([CHECK_POSIX_SH])\n\tAC_MSG_NOTICE([checking POSIX compatibility...])\n\tLIBCPERCIVA_DIR=\"$1\"\n\tLDADD_POSIX=`export CC=\"${CC}\"; ${POSIX_SH} ${LIBCPERCIVA_DIR}/POSIX/posix-l.sh \"$PATH\"`\n\tCFLAGS_POSIX=`export CC=\"${CC}\"; ${POSIX_SH} ${LIBCPERCIVA_DIR}/POSIX/posix-cflags.sh \"$PATH\"`\n\tAC_SUBST([LDADD_POSIX])\n\tAC_SUBST([CFLAGS_POSIX])\n\tAC_MSG_RESULT([... done checking POSIX compatibility])\n])# CHECK_LIBCPERCIVA_POSIX\n"
  },
  {
    "path": "m4/check_memlimit_support.m4",
    "content": "# CHECK_MEMLIMIT_SUPPORT\n# ----------------------\nAC_DEFUN([CHECK_MEMLIMIT_SUPPORT], [\n\t# Check for a linuxy sysinfo syscall; and while we're doing that,\n\t# check if struct sysinfo is the old version (total RAM == totalmem)\n\t# or the new version (total RAM == totalmem * mem_unit).\n\tAC_CHECK_HEADERS_ONCE([sys/sysinfo.h])\n\tAC_CHECK_FUNCS_ONCE([sysinfo])\n\tAC_CHECK_TYPES([struct sysinfo], [], [], [[#include <sys/sysinfo.h>]])\n\tAC_CHECK_MEMBERS([struct sysinfo.totalram, struct sysinfo.mem_unit],\n\t    [], [], [[#include <sys/sysinfo.h>]])\n\n\t# Check if we have <sys/param.h>, since some systems require it for\n\t# sysctl to work.\n\tAC_CHECK_HEADERS_ONCE([sys/param.h])\n\n\t# Check for <sys/sysctl.h>.  If it exists and it defines HW_USERMEM\n\t# and/or HW_MEMSIZE, we'll try using those as memory limits.\n\tAC_CHECK_HEADERS_ONCE([sys/sysctl.h])\n])# CHECK_MEMLIMIT_SUPPORT\n"
  },
  {
    "path": "m4/check_posix_sh.m4",
    "content": "# CHECK_POSIX_SH\n# --------------\nAC_DEFUN([CHECK_POSIX_SH], [\n\t# Allow users to manually specify the path to a POSIX shell.\n\tAC_ARG_VAR([POSIX_SH], [path of a POSIX shell])\n\n\tAS_IF([test \"x${POSIX_SH}\" = \"x\"], [\n\t\t# If POSIX_SH is not set, get the default value of PATH which\n\t\t# is specified to find the standard POSIX utilities.\n\t\tPOSIX_PATH=`command -p getconf PATH`\n\t\tAS_IF([test \"x${POSIX_PATH}\" = \"x\"],\n\t\t    AC_MSG_ERROR([\"cannot get the default PATH\"]))\n\t\t# Get the path of sh within POSIX_PATH.\n\t\tAC_PATH_PROG([POSIX_SH], [sh], [\"\"], [${POSIX_PATH}])\n\t\tAS_IF([test \"x${POSIX_SH}\" = \"x\"],\n\t\t    AC_MSG_ERROR([\"cannot find a POSIX shell\"]))\n\t\t])\n])# CHECK_POSIX_SH\n"
  },
  {
    "path": "m4/check_solaris_c99.m4",
    "content": "# CHECK_SOLARIS_C99\n# -----------------\n# On Solaris, the default standard library is c89-compatible.  Some linkers\n# require -std=c99 to link to the c99-compatible library.\nAC_DEFUN([CHECK_SOLARIS_C99],\n[AC_REQUIRE([AC_CANONICAL_TARGET])\n\ncase $target_os in\n*solaris* | *sunos*)\n\tAC_MSG_CHECKING([Solaris c99 standard library])\n\tAC_RUN_IFELSE([AC_LANG_SOURCE([[#include <stdlib.h>\n\t\tint main(void) {\n\t\t\tchar * eptr;\n\t\t\tstrtod(\"0x1\", &eptr);\n\t\t\treturn (eptr[0] != '\\0');\n\t\t}]])],\n\t\t[AC_MSG_RESULT([yes])],\n\t\t[# If we failed, try adding -std=c99 to the LDFLAGS.\n\t\t LDFLAGS=\"${LDFLAGS} -std=c99\"\n\t\t AC_RUN_IFELSE([AC_LANG_SOURCE([[#include <stdlib.h>\n\t\t\tint main(void) {\n\t\t\t\tchar * eptr;\n\t\t\t\tstrtod(\"0x1\", &eptr);\n\t\t\t\treturn (eptr[0] != '\\0');\n\t\t\t}]])],\n\t\t\t[AC_MSG_RESULT([yes, if linked with -std=c99])],\n\t\t\t[AC_MSG_RESULT([no])\n\t\t\t AC_MSG_ERROR([c99 required])],\n\t\t\t# This should never arise, because the outer _ifelse\n\t\t\t# would jump to the action-if-cross-compiling rather\n\t\t\t# than executing its action-if-false.  However, adding\n\t\t\t# this explicitly makes autoconf happier.\n\t\t\t[AC_MSG_RESULT([skipping due to cross-compiling])]\n\t\t\t)],\n\t\t[AC_MSG_RESULT([skipping due to cross-compiling])])\n\t;;\n*)\n\t;;\nesac\n\n])# CHECK_SOLARIS_C99\n"
  },
  {
    "path": "main.c",
    "content": "/*-\n * Copyright 2009 Colin Percival\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n */\n#include \"platform.h\"\n\n#include <errno.h>\n#include <math.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"getopt.h\"\n#include \"humansize.h\"\n#include \"insecure_memzero.h\"\n#include \"parsenum.h\"\n#include \"passphrase_entry.h\"\n#include \"scryptenc.h\"\n#include \"scryptenc_print_error.h\"\n#include \"warnp.h\"\n\nstatic void\nusage(void)\n{\n\n\tfprintf(stderr,\n\t    \"usage: scrypt {enc | dec | info} [-f] [--logN value] [-M maxmem]\\n\"\n\t    \"              [-m maxmemfrac] [-P] [-p value] [-r value]\"\n\t    \" [-t maxtime] [-v]\\n\"\n\t    \"              [--passphrase method:arg] infile [outfile]\\n\"\n\t    \"       scrypt --version\\n\");\n\texit(1);\n}\n\n/**\n * scrypt_mode_info(infilename):\n * Print scrypt parameters used for the specified ${infilename}, or read from\n * stdin if that argument is NULL.\n */\nstatic int\nscrypt_mode_info(const char * infilename)\n{\n\tFILE * infile;\n\tint rc;\n\n\t/* If the input isn't stdin, open the file. */\n\tif (infilename != NULL) {\n\t\tif ((infile = fopen(infilename, \"rb\")) == NULL) {\n\t\t\twarnp(\"Cannot open input file: %s\", infilename);\n\t\t\tgoto err0;\n\t\t}\n\t} else {\n\t\tinfile = stdin;\n\t}\n\n\t/* Print the encryption parameters used for the file. */\n\tif ((rc = scryptdec_file_printparams(infile)) != SCRYPT_OK) {\n\t\tscryptenc_print_error(rc, infilename, NULL);\n\t\tgoto err1;\n\t}\n\n\t/* Clean up. */\n\tif ((infile != stdin) && fclose(infile))\n\t\twarnp(\"fclose\");\n\n\t/* Success! */\n\treturn (0);\n\nerr1:\n\tif ((infile != stdin) && fclose(infile))\n\t\twarnp(\"fclose\");\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n/**\n * scrypt_mode_enc_dec(params, passphrase_entry, passphrase_arg, dec, verbose,\n *     force_resources, infilename, outfilename):\n * Either encrypt (if ${dec} is 0) or decrypt (if ${dec} is non-zero)\n * ${infilename} (or standard input if this is NULL) to ${outfilename}.\n * Use scrypt parameters ${params}, with passphrase entry method\n * ${passphrase_entry} and argument ${passphrase_arg}.  If ${verbose} is\n * non-zero, print verbose messages.  If ${force_resources} is non-zero,\n * do not check whether encryption or decryption will exceed the estimated\n * time or memory requirements.\n */\nstatic int\nscrypt_mode_enc_dec(struct scryptenc_params params,\n    enum passphrase_entry passphrase_entry, const char * passphrase_arg,\n    int dec, int verbose, int force_resources,\n    const char * infilename, const char * outfilename)\n{\n\tstruct scryptdec_file_cookie * C = NULL;\n\tFILE * infile;\n\tFILE * outfile = stdout;\n\tchar * passwd;\n\tint rc;\n\n\t/* If the input isn't stdin, open the file. */\n\tif (infilename != NULL) {\n\t\tif ((infile = fopen(infilename, \"rb\")) == NULL) {\n\t\t\twarnp(\"Cannot open input file: %s\", infilename);\n\t\t\tgoto err0;\n\t\t}\n\t} else {\n\t\tinfile = stdin;\n\t}\n\n\t/* Get the password. */\n\tif (passphrase_entry_readpass(&passwd, passphrase_entry,\n\t    passphrase_arg, \"Please enter passphrase\",\n\t    \"Please confirm passphrase\", dec)) {\n\t\twarnp(\"passphrase_entry_readpass\");\n\t\tgoto err1;\n\t}\n\n\t/*-\n\t * If we're decrypting, open the input file and process its header;\n\t * doing this here allows us to abort without creating an output\n\t * file if the input file does not have a valid scrypt header or if\n\t * we have the wrong passphrase.\n\t *\n\t * If successful, we get back a cookie containing the decryption\n\t * parameters (which we'll use after we open the output file).\n\t */\n\tif (dec) {\n\t\tif ((rc = scryptdec_file_prep(infile, (uint8_t *)passwd,\n\t\t    strlen(passwd), &params, verbose, force_resources,\n\t\t    &C)) != 0) {\n\t\t\tgoto cleanup;\n\t\t}\n\t}\n\n\t/* If we have an output filename, open it. */\n\tif (outfilename != NULL) {\n\t\tif ((outfile = fopen(outfilename, \"wb\")) == NULL) {\n\t\t\twarnp(\"Cannot open output file: %s\", outfilename);\n\t\t\tgoto err2;\n\t\t}\n\t}\n\n\t/* Encrypt or decrypt. */\n\tif (dec)\n\t\trc = scryptdec_file_copy(C, outfile);\n\telse\n\t\trc = scryptenc_file(infile, outfile, (uint8_t *)passwd,\n\t\t    strlen(passwd), &params, verbose, force_resources);\n\ncleanup:\n\t/* Free the decryption cookie, if any. */\n\tscryptdec_file_cookie_free(C);\n\n\t/* Zero and free the password. */\n\tinsecure_memzero(passwd, strlen(passwd));\n\tfree(passwd);\n\n\t/* Close any files we opened. */\n\tif ((infile != stdin) && fclose(infile))\n\t\twarnp(\"fclose\");\n\tif ((outfile != stdout) && fclose(outfile))\n\t\twarnp(\"fclose\");\n\n\t/* If we failed, print the right error message and exit. */\n\tif (rc != SCRYPT_OK) {\n\t\tscryptenc_print_error(rc, infilename, outfilename);\n\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\treturn (0);\n\nerr2:\n\tscryptdec_file_cookie_free(C);\n\tinsecure_memzero(passwd, strlen(passwd));\n\tfree(passwd);\nerr1:\n\tif ((infile != stdin) && fclose(infile))\n\t\twarnp(\"fclose\");\nerr0:\n\t/* Failure! */\n\treturn (-1);\n}\n\n/* Parse a numeric optarg within a GETOPT context.  (Requires ch and optarg.) */\n#define GETOPT_PARSENUM_WITHIN_UNSIGNED(var, min, max) do {\t\t\\\n\tif (PARSENUM((var), optarg, (min), (max))) {\t\t\t\\\n\t\tif (errno == ERANGE) {\t\t\t\t\t\\\n\t\t\twarn0(\"%s must be between %ju and %ju\"\t\t\\\n\t\t\t    \" (inclusive)\", ch, (uintmax_t)(min),\t\\\n\t\t\t    (uintmax_t)(max));\t\t\t\t\\\n\t\t} else\t\t\t\t\t\t\t\\\n\t\t\twarnp(\"Invalid option: %s %s\", ch, optarg);\t\\\n\t\texit(1);\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n} while (0)\n\nint\nmain(int argc, char * argv[])\n{\n\tint dec = 0;\n\tint info = 0;\n\tint force_resources = 0;\n\tuint64_t maxmem64;\n\tstruct scryptenc_params params = {0, 0.5, 300.0, 0, 0, 0};\n\tconst char * ch;\n\tconst char * infilename;\n\tconst char * outfilename;\n\tint verbose = 0;\n\tenum passphrase_entry passphrase_entry = PASSPHRASE_UNSET;\n\tconst char * passphrase_arg;\n\n\tWARNP_INIT;\n\n\t/* We should have \"enc\", \"dec\", or \"info\" first. */\n\tif (argc < 2)\n\t\tusage();\n\tif (strcmp(argv[1], \"enc\") == 0) {\n\t\tparams.maxmem = 0;\n\t\tparams.maxmemfrac = 0.125;\n\t\tparams.maxtime = 5.0;\n\t} else if (strcmp(argv[1], \"dec\") == 0) {\n\t\tdec = 1;\n\t} else if (strcmp(argv[1], \"info\") == 0) {\n\t\tinfo = 1;\n\t} else if (strcmp(argv[1], \"--version\") == 0) {\n\t\tfprintf(stdout, \"scrypt %s\\n\", PACKAGE_VERSION);\n\t\texit(0);\n\t} else {\n\t\twarn0(\"First argument must be 'enc', 'dec', or 'info'.\");\n\t\tusage();\n\t}\n\targc--;\n\targv++;\n\n\t/* Parse arguments. */\n\twhile ((ch = GETOPT(argc, argv)) != NULL) {\n\t\tGETOPT_SWITCH(ch) {\n\t\tGETOPT_OPT(\"-f\"):\n\t\t\tforce_resources = 1;\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"--logN\"):\n\t\t\tGETOPT_PARSENUM_WITHIN_UNSIGNED(&params.logN, 10, 40);\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"-M\"):\n\t\t\tif (humansize_parse(optarg, &maxmem64)) {\n\t\t\t\twarn0(\"Could not parse the parameter to -M.\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tif (maxmem64 > SIZE_MAX) {\n\t\t\t\twarn0(\"The parameter to -M is too large.\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tparams.maxmem = (size_t)maxmem64;\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"-m\"):\n\t\t\tif (PARSENUM(&params.maxmemfrac, optarg, 0, 0.5)) {\n\t\t\t\twarnp(\"Invalid option: -m %s\", optarg);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"-p\"):\n\t\t\tGETOPT_PARSENUM_WITHIN_UNSIGNED(&params.p, 1, 2048);\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"--passphrase\"):\n\t\t\tif (passphrase_entry != PASSPHRASE_UNSET) {\n\t\t\t\twarn0(\"You can only enter one --passphrase or\"\n\t\t\t\t    \" -P argument\");\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t/* Parse \"method:arg\" optarg. */\n\t\t\tif (passphrase_entry_parse(optarg, &passphrase_entry,\n\t\t\t    &passphrase_arg))\n\t\t\t\texit(1);\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"-r\"):\n\t\t\tGETOPT_PARSENUM_WITHIN_UNSIGNED(&params.r, 1, 32);\n\t\t\tbreak;\n\t\tGETOPT_OPTARG(\"-t\"):\n\t\t\tif (PARSENUM(&params.maxtime, optarg, 0, INFINITY)) {\n\t\t\t\twarnp(\"Invalid option: -t %s\", optarg);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tbreak;\n\t\tGETOPT_OPT(\"-v\"):\n\t\t\tverbose = 1;\n\t\t\tbreak;\n\t\tGETOPT_OPT(\"-P\"):\n\t\t\tif (passphrase_entry != PASSPHRASE_UNSET) {\n\t\t\t\twarn0(\"You can only enter one --passphrase or\"\n\t\t\t\t    \" -P argument\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tpassphrase_entry = PASSPHRASE_STDIN_ONCE;\n\t\t\tpassphrase_arg = \"\";\n\t\t\tbreak;\n\t\tGETOPT_MISSING_ARG:\n\t\t\twarn0(\"Missing argument to %s\", ch);\n\t\t\tusage();\n\t\tGETOPT_DEFAULT:\n\t\t\twarn0(\"illegal option -- %s\", ch);\n\t\t\tusage();\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\t/* We must have one or two parameters left. */\n\tif ((argc < 1) || (argc > 2))\n\t\tusage();\n\n\t/* The explicit parameters must be zero, or all non-zero. */\n\tif ((params.logN != 0) && ((params.r == 0) || (params.p == 0))) {\n\t\twarn0(\"If --logN is set, -r and -p must also be set\");\n\t\tgoto err0;\n\t}\n\tif ((params.r != 0) && ((params.logN == 0) || (params.p == 0))) {\n\t\twarn0(\"If -r is set, --logN and -p must also be set\");\n\t\tgoto err0;\n\t}\n\tif ((params.p != 0) && ((params.logN == 0) || (params.r == 0))) {\n\t\twarn0(\"If -p is set, --logN and -r must also be set\");\n\t\tgoto err0;\n\t}\n\n\t/* We can't have a maxmemfrac of 0. */\n\tif (params.maxmemfrac == 0.0) {\n\t\twarn0(\"-m must be greater than 0\");\n\t\tgoto err0;\n\t}\n\n\t/* Set the input filename. */\n\tif (strcmp(argv[0], \"-\"))\n\t\tinfilename = argv[0];\n\telse\n\t\tinfilename = NULL;\n\n\t/* Set the output filename. */\n\tif (argc > 1)\n\t\toutfilename = argv[1];\n\telse\n\t\toutfilename = NULL;\n\n\t/* Set the default passphrase entry method. */\n\tif (passphrase_entry == PASSPHRASE_UNSET) {\n\t\tpassphrase_entry = PASSPHRASE_TTY_STDIN;\n\t\tpassphrase_arg = \"\";\n\t}\n\n\t/* Sanity check passphrase entry method and input filename. */\n\tif ((passphrase_entry == PASSPHRASE_STDIN_ONCE) &&\n\t    (infilename == NULL)) {\n\t\twarn0(\"Cannot read both passphrase and input file\"\n\t\t    \" from standard input\");\n\t\tgoto err0;\n\t}\n\n\t/* What type of operation are we doing? */\n\tif (info) {\n\t\t/* User selected 'info' mode. */\n\t\tif (scrypt_mode_info(infilename))\n\t\t\tgoto err0;\n\t} else {\n\t\t/* User selected encryption or decryption. */\n\t\tif (scrypt_mode_enc_dec(params, passphrase_entry,\n\t\t    passphrase_arg, dec, verbose, force_resources,\n\t\t    infilename, outfilename))\n\t\t\tgoto err0;\n\t}\n\n\t/* Success! */\n\texit(0);\n\nerr0:\n\t/* Failure! */\n\texit(1);\n}\n"
  },
  {
    "path": "release-tools/create-sign-tarball.sh",
    "content": "#!/bin/sh\n\n# Process command-line arguments\nSCRYPTVERSION=$1\nGNUPG_SIGNING_HOME=$2\n\n# Check for required arguments\nif [ -z \"${SCRYPTVERSION}\" ] || [ -z \"${GNUPG_SIGNING_HOME}\" ]; then\n\techo \"Usage: $0 SCRYPTVERSION GNUPG_SIGNING_HOME\"\n\texit 1\nfi\n\n# Check for correct OS\nif [ \"$(uname)\" != \"FreeBSD\" ]; then\n\techo \"Error: This script only works on FreeBSD due to the\"\n\techo \"    sha256 \\${PKGNAME}.tgz\"\n\techo \"command, which has a different meaning on other OSes.\"\n\texit 1\nfi\n\n# Constants\nPKGNAME=scrypt-${SCRYPTVERSION}\nPKGSIGS=scrypt-sigs-${SCRYPTVERSION}\n\n# Get directory of script\ndir=$(CDPATH='' cd -- \"$(dirname -- \"$0\")\" && pwd -P)\n\n# Create tarball\nsh \"${dir}/mktarball.sh\" \"${SCRYPTVERSION}\"\n\n# Sign tarball\nsha256 \"${PKGNAME}.tgz\" |\t\t\t\\\n    GNUPGHOME=${GNUPG_SIGNING_HOME} gpg --clearsign \\\n    > \"${PKGSIGS}.asc\"\n"
  },
  {
    "path": "release-tools/mktarball.sh",
    "content": "#!/bin/sh\n\nVERSION=$1\nif [ -z \"${VERSION}\" ]; then\n\techo \"Please specify the version number\"\n\texit 1\nfi\nDESTDIR=scrypt-${VERSION}\nRELEASEDATE=$(date \"+%B %d, %Y\")\n\n# Copy bits in\nmkdir \"${DESTDIR}\" \"${DESTDIR}/autotools\"\ncp main.c FORMAT COPYRIGHT BUILDING README.md STYLE \"${DESTDIR}\"\ncp Makefile.am .autom4te.cfg \"${DESTDIR}\"\ncp Makefile.am \"${DESTDIR}/autotools\"\ncp -R lib lib-platform libcperciva libscrypt-kdf m4 tests \"${DESTDIR}\"\n# Copy with substitution\nsed -e \"s/@DATE@/${RELEASEDATE}/\" < scrypt.1 > \"${DESTDIR}/scrypt.1\"\nsed -e \"s/\\[m4_esyscmd(\\[sh get-version\\.sh\\])]/${VERSION}/\" \\\n\t< configure.ac > \"${DESTDIR}/configure.ac\"\ncp \"${DESTDIR}/configure.ac\" \"${DESTDIR}/autotools\"\n\n# Generate autotools files\n( cd \"${DESTDIR}\" || exit\nautoreconf -i\nrm .autom4te.cfg Makefile.am aclocal.m4 configure.ac )\n\n# Create tarball\ntar -czf \"${DESTDIR}.tgz\" \"${DESTDIR}\"\nrm -r \"${DESTDIR}\"\n"
  },
  {
    "path": "scrypt.1",
    "content": ".\\\" Copyright 2009 Colin Percival\n.\\\" All rights reserved.\n.\\\"\n.\\\" Redistribution and use in source and binary forms, with or without\n.\\\" modification, are permitted provided that the following conditions\n.\\\" are met:\n.\\\" 1. Redistributions of source code must retain the above copyright\n.\\\"    notice, this list of conditions and the following disclaimer.\n.\\\" 2. Redistributions in binary form must reproduce the above copyright\n.\\\"    notice, this list of conditions and the following disclaimer in the\n.\\\"    documentation and/or other materials provided with the distribution.\n.\\\"\n.\\\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n.\\\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n.\\\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n.\\\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n.\\\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n.\\\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n.\\\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n.\\\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n.\\\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n.\\\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n.\\\" SUCH DAMAGE.\n.Dd @DATE@\n.Dt SCRYPT 1\n.Os\n.Sh NAME\n.Nm scrypt\n.Nd encrypt and decrypt files\n.Sh SYNOPSIS\n.Nm\n.Brq Cm enc | Cm dec | Cm info\n.Op Fl f\n.Op Fl -logN Ar value\n.Op Fl M Ar maxmem\n.Op Fl m Ar maxmemfrac\n.Op Fl P\n.Op Fl p Ar value\n.Op Fl -passphrase Ar method:arg\n.Op Fl r Ar value\n.Op Fl t Ar maxtime\n.Op Fl v\n.Ar infile\n.Op Ar outfile\n.Nm\n.Fl -version\n.Sh DESCRIPTION\n.Nm Cm enc\nencrypts\n.Ar infile\nand writes the result to\n.Ar outfile\nif specified, or the standard output otherwise.\nThe user will be prompted to enter a passphrase (twice) to\nbe used to generate a derived encryption key.\n.Pp\n.Nm Cm dec\ndecrypts\n.Ar infile\nand writes the result to\n.Ar outfile\nif specified, or the standard output otherwise.\nThe user will be prompted to enter the passphrase used at\nencryption time to generate the derived encryption key.\n.Pp\n.Nm Cm info\nprovides information about the encryption parameters used for\n.Ar infile .\n.Pp\nUnless otherwise specified via\n.Fl -passphrase ,\n.Nm\nreads passphrases from its controlling terminal, or failing that, from stdin.\nPrompts are only printed when\n.Nm\nis reading passphrases from some terminal.\n.Sh OPTIONS\n.Bl -tag -width \"-m maxmemfrac\"\n.It Fl f\nForce the operation to proceed even if it is anticipated to\nrequire an excessive amount of memory or CPU time.\nDo not print any warnings about exceeding any memory or CPU time limits.\n.It Fl -logN Ar value\nSet the work parameter N to\n.Pf 2^ Ar value .\nIf\n.Fl -logN\nis set,\n.Fl r\nand\n.Fl p\nmust also be set.\nIf such explicit parameters are given, the resource limits set by\n.Fl M ,\n.Fl m ,\nand\n.Fl t\nare not enforced.\n.It Fl M Ar maxmem\nUse at most\n.Ar maxmem\nbytes of RAM to compute the derived encryption key.\n.It Fl m Ar maxmemfrac\nUse at most the fraction\n.Ar maxmemfrac\nof the available RAM to compute the derived encryption key.\nThe maximum possible value for\n.Ar maxmemfrac\nis 0.5.\n.It Fl P\nDeprecated synonym for\n.Fl -passphrase Ar dev:stdin-once .\n.It Fl p Ar value\nSet the work parameter p to\n.Ar value .\nIf\n.Fl p\nis set,\n.Fl -logN\nand\n.Fl r\nmust also be set.\nIf such explicit parameters are given, the resource limits set by\n.Fl M ,\n.Fl m ,\nand\n.Fl t\nare not enforced.\n.It Fl -passphrase Ar method:arg\nRead the passphrase using the specified method.\n.Bl -tag -width aa\n.It Ar dev:tty-stdin\nAttempt to read the passphrase from /dev/tty; if that fails, read it from stdin.\nThis is the default behaviour.\n.It Ar dev:stdin-once\nAttempt to read the passphrase from stdin, and do so only once even when\nencrypting.\nThis cannot be used if\n.Ar infile\nis also stdin (aka '-').\n.It Ar dev:tty-once\nAttempt to read the passphrase from /dev/tty, and do so only once\neven when encrypting.\n.It Ar env:VAR\nRead the passphrase from the environment variable specified by\n.Ar VAR .\n.Pp\n.Bf Em\nStoring a passphrase in an environment variable may be a security risk.\n.Ef\nOnly use this option if you are certain that you know what you are doing.\n.It Ar file:FILENAME\nRead the passphrase from the file specified by\n.Ar FILENAME .\n.Pp\n.Bf Em\nStoring a passphrase in a file may be a security risk.\n.Ef\nOnly use this option if you are certain that you know what you are doing.\n.El\n.It Fl r Ar value\nSet the work parameter r to\n.Ar value .\nIf\n.Fl r\nis set,\n.Fl -logN\nand\n.Fl p\nmust also be set.\nIf such explicit parameters are given, the resource limits set by\n.Fl M ,\n.Fl m ,\nand\n.Fl t\nare not enforced.\n.It Fl t Ar maxtime\nUse at most\n.Ar maxtime\nseconds of CPU time to compute the derived encryption key.\n.It Fl v\nPrint encryption parameters (N, r, p) and memory/cpu limits.\n.It Fl -version\nPrint version of scrypt, and exit.\n.El\n.Pp\nIn\n.Nm Cm enc ,\nthe memory and CPU time limits are enforced by picking\nappropriate parameters to the\n.Nm\nkey derivation function.\nIn\n.Nm Cm dec ,\nthe memory and CPU time limits are enforced by exiting with\nan error if decrypting the file would require too much memory\nor CPU time.\n.Sh EXIT STATUS\nThe\n.Nm\nutility exits 0 on success, and >0 if an error occurs.\n.Pp\nNote that if the input encrypted file is corrupted,\n.Nm Cm dec\nmay produce output prior to determining that the input\nwas corrupt and exiting with a non-zero status; so\nusers should direct the output to a safe location and\ncheck the exit status of\n.Nm\nbefore using the decrypted data.\n.Sh ALGORITHM PARAMETERS\nThe scrypt algorithm has three tuneable work parameters: N, r, p.\nWhen decrypting, scrypt will always use the values specified by\nthe encryption header.\nWhen encrypting, scrypt will choose appropriate values based on your system's\nspeed and memory (influenced by\n.Fl M ,\n.Fl m ,\nand/or\n.Fl t ) ,\nunless you specify explicit parameters via\n.Fl -logN ,\n.Fl p ,\n.Fl r .\n.Sh SEE ALSO\n.Rs\n.%A \"Colin Percival\"\n.%T \"Stronger Key Derivation via Sequential Memory-Hard Functions\"\n.%R \"BSDCan'09\"\n.%D \"May 2009\"\n.Re\n.Rs\n.%A \"Colin Percival\"\n.%A \"Simon Josefsson\"\n.%T \"The scrypt Password-Based Key Derivation Function\"\n.%R \"IETF RFC 7914\"\n.%D \"August 2016\"\n.Re\n.Sh HISTORY\nThe\n.Nm\nutility was written in May 2009 by Colin Percival as a\ndemonstration of the\n.Nm\nkey derivation function.\nThe\n.Nm\nkey derivation function was invented in March 2009 by Colin\nPercival in order to allow key files from the\n.Nm Tarsnap\nbackup system to be passphrase protected.\n"
  },
  {
    "path": "tests/01-known-values.sh",
    "content": "#!/bin/sh\n\n### Constants\n# The scenario command requires a lot of memory, so valgrind is only enabled\n# if $USE_VALGRIND > 1.\nc_valgrind_min=2\ntest_output=\"${s_basename}-stdout.txt\"\nreference=\"${scriptdir}/verify-strings/test_scrypt.good\"\nreference_small=\"${scriptdir}/verify-strings/test_scrypt_small.good\"\n\n### Actual command\nscenario_cmd() {\n\t# Run the binary which tests known input/output strings.\n\tsetup_check \"test_scrypt\"\n\t(\n\t\t${c_valgrind_cmd} \"${bindir}/tests/verify-strings/test_scrypt\" \\\n\t\t\t\"${SMALLMEM:-0}\" 1> \"${test_output}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The generated values should match the known good values.\n\tsetup_check \"test_scrypt output against reference\"\n\tif [ \"${SMALLMEM:-0}\" -gt \"0\" ]; then\n\t\tcmp -s \"${test_output}\" \"${reference_small}\"\n\telse\n\t\tcmp -s \"${test_output}\" \"${reference}\"\n\tfi\n\techo $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/02-decrypt-reference-file.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\nencrypted_reference_file=\"${scriptdir}/verify-strings/test_scrypt_good.enc\"\ndecrypted_reference_file=\"${s_basename}-attempt_reference.txt\"\ndecrypted_reference_file_stderr=\"${s_basename}-attempt_reference.stderr\"\ndecrypted_badpass_file=\"${s_basename}-decrypt-badpass.txt\"\ndecrypted_badpass_log=\"${s_basename}-decrypt-badpass.log\"\n\nscenario_cmd() {\n\t# Decrypt a reference file.\n\tsetup_check \"scrypt dec\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t    dec -P \"${encrypted_reference_file}\"\t\t\\\n\t\t    \"${decrypted_reference_file}\"\t\t\t\\\n\t\t    2> \"${decrypted_reference_file_stderr}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The decrypted reference file should match the reference.\n\tsetup_check \"scrypt dec output against reference\"\n\tcmp -s \"${decrypted_reference_file}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# We should not have any output on stderr.\n\tsetup_check \"scrypt dec no stderr\"\n\ttest -s \"${decrypted_reference_file_stderr}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# Attempt to decrypt the reference file with an incorrect passphrase.\n\t# We want this command to fail with 1.\n\tsetup_check \"scrypt dec bad passphrase\"\n\t(\n\t\techo \"bad-pass\" | ${c_valgrind_cmd} \"${bindir}/scrypt\"\t\\\n\t\t    dec -P \"${encrypted_reference_file}\"\t\t\\\n\t\t    \"${decrypted_badpass_file}\"\t\t\t\t\\\n\t\t    2> \"${decrypted_badpass_log}\"\n\t\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\t)\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec bad passphrase error\"\n\tif grep -q \"scrypt: Passphrase is incorrect\" \\\n\t    \"${decrypted_badpass_log}\"; then\n\t\techo \"0\"\n\telse\n\t\techo \"1\"\n\tfi > \"${c_exitfile}\"\n\n\t# We should not have created a file.\n\tsetup_check \"scrypt dec bad passphrase no file\"\n\tif [ -e \"${decrypted_badpass_file}\" ]; then\n\t\techo \"1\"\n\telse\n\t\techo \"0\"\n\tfi > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/03-encrypt-decrypt-file.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\nencrypted_file=\"${s_basename}-attempt.enc\"\ndecrypted_file=\"${s_basename}-attempt.txt\"\n\nscenario_cmd() {\n\t# Encrypt a file.  Use --passphrase dev:stdin-once instead of -P.\n\tsetup_check \"scrypt enc\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t    enc --passphrase dev:stdin-once -t 1\t\t\\\n\t\t    \"${reference_file}\" \"${encrypted_file}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The encrypted file should be different from the original file.\n\t# We cannot check against the \"reference\" encrypted file, because\n\t# encrypted files include random salt.  If successful, don't delete\n\t# ${encrypted_file} yet; we need it for the next test.\n\tsetup_check \"scrypt enc random salt\"\n\tcmp -s \"${encrypted_file}\" \"${reference_file}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# Decrypt the file we just encrypted.\n\tsetup_check \"scrypt enc decrypt\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t    dec -P \"${encrypted_file}\" \"${decrypted_file}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The decrypted file should match the reference.\n\tsetup_check \"scrypt enc decrypt output against reference\"\n\tcmp -s \"${decrypted_file}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/04-force-resources.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\nlongwait_encrypted_file=\"${s_basename}.enc\"\nlongwait_decrypted_file=\"${s_basename}.txt\"\nlongwait_failed_log=\"${s_basename}-failed.log\"\n\nscenario_cmd() {\n\t# Encrypt file which should take a long time to decrypt.\n\tsetup_check \"scrypt enc 10 seconds\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t\tenc -P -t 10 \"${reference_file}\"\t\t\\\n\t\t\t\"${longwait_encrypted_file}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# Attempt to decrypt it with limited time.  We want this\n\t# command to fail, so we negate the normal return code.\n\tsetup_check \"scrypt dec 0.1 seconds\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t\tdec -P -t 0.1 \"${longwait_encrypted_file}\"\t\\\n\t\t\t\"${longwait_decrypted_file}\"\t\t\t\\\n\t\t\t2> \"${longwait_failed_log}\"\n\t\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\t)\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec 1 second error\"\n\tgrep -q \"scrypt: Decrypting file would take too much CPU time\" \\\n\t    \"${longwait_failed_log}\"\n\techo \"$?\" > \"${c_exitfile}\"\n\n\t# Attempt to decrypt it with limited time, but force success.\n\tsetup_check \"scrypt dec force\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t\tdec -P -t 1 -f \"${longwait_encrypted_file}\"\t\\\n\t\t\t\"${longwait_decrypted_file}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The decrypted reference file should match the reference.\n\tsetup_check \"scrypt dec force output against reference\"\n\tcmp -s \"${longwait_decrypted_file}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/05-system-scrypt-encrypt-decrypt.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\nencrypted_file_1=\"${s_basename}-sys.enc\"\ndecrypted_file_1=\"${s_basename}-sys.txt\"\nencrypted_file_2=\"${s_basename}-our.enc\"\ndecrypted_file_2=\"${s_basename}-our.txt\"\n\nscenario_cmd() {\n\tif [ -z \"${system_scrypt}\" ]; then\n\t\tprintf \"no suitable system scrypt: \" 1>&2\n\t\t# Inform test suite that we are skipping.\n\t\tsetup_check \"system scrypt skip\"\n\t\techo \"-1\" > \"${c_exitfile}\"\n\t\treturn\n\tfi\n\n\t# Encrypt a file with our scrypt.\n\tsetup_check \"scrypt enc for system\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t    enc -P -t 1 \"${reference_file}\" \"${encrypted_file_1}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# Use the system scrypt to decrypt the file we just\n\t# encrypted.  Don't use valgrind for this.\n\tsetup_check \"system scrypt dec\"\n\t(\n\t\techo \"${password}\" | ${system_scrypt}\t\t\t\\\n\t\t    dec -P \"${encrypted_file_1}\" \"${decrypted_file_1}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The decrypted file should match the reference.\n\tsetup_check \"system scrypt dec output against reference\"\n\tcmp -s \"${decrypted_file_1}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# Encrypt a file with the system scrypt.  Don't use\n\t# valgrind for this.\n\tsetup_check \"system scrypt enc\"\n\t(\n\t\techo \"${password}\" | ${system_scrypt}\t\t\t\\\n\t\t    enc -P -t 1 \"${reference_file}\" \"${encrypted_file_2}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# Use our scrypt to decrypt the file we just encrypted.\n\tsetup_check \"scrypt dec for system\"\n\t(\n\t\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\" \\\n\t\t    dec -P \"${encrypted_file_2}\" \"${decrypted_file_2}\"\n\t\techo $? > \"${c_exitfile}\"\n\t)\n\n\t# The decrypted file should match the reference.\n\tsetup_check \"scrypt dec for system output against reference\"\n\tcmp -s \"${decrypted_file_2}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/06-decrypt-fail.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nnon_encoded_file=\"${scriptdir}/06-decrypt-fail.sh\"\nnon_encoded_file_stderr=\"${s_basename}-stderr.txt\"\nnon_encoded_file_output=\"${s_basename}-nonfile.txt\"\n\nscenario_cmd() {\n\t# Attempt to decrypt a non-scrypt-encoded file.\n\t# We want this command to fail with 1.\n\tsetup_check \"scrypt dec non-scrypt\"\n\t(\n\t\techo \"\" | ${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\\\n\t\t    dec -P \"${non_encoded_file}\"\t\t\t\\\n\t\t    \"${non_encoded_file_output}\"\t\t\t\\\n\t\t\t2>> \"${non_encoded_file_stderr}\"\n\t\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\t)\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec non-scrypt error\"\n\tgrep -q \"scrypt: Input is not valid scrypt-encrypted block\" \\\n\t    \"${non_encoded_file_stderr}\"\n\techo \"$?\" > \"${c_exitfile}\"\n\n\t# We should not have created a file.\n\tsetup_check \"scrypt dec non-scrypt no file\"\n\tif [ -e \"${non_encoded_file_output}\" ]; then\n\t\techo \"1\"\n\telse\n\t\techo \"0\"\n\tfi > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/07-passphrase-env.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\nencrypted_reference_file=\"${scriptdir}/verify-strings/test_scrypt_good.enc\"\ndecrypted_reference_file=\"${s_basename}-attempt_reference.txt\"\ndecrypted_badpass_file=\"${s_basename}-decrypt-badpass.txt\"\ndecrypted_badpass_log=\"${s_basename}-decrypt-badpass.log\"\ndecrypted_no_envvar_log=\"${s_basename}-decrypt-no-envvar.log\"\n\nscenario_cmd() {\n\t# Decrypt a reference file using --passphrase env:VAR.\n\tsetup_check \"scrypt dec env\"\n\tPASSPHRASE=\"${password}\"\t\t\t\t\t\\\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    dec --passphrase env:PASSPHRASE\t\t\t\t\\\n\t    \"${encrypted_reference_file}\" \"${decrypted_reference_file}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# The decrypted reference file should match the reference.\n\tsetup_check \"scrypt dec env output against reference\"\n\tcmp -s \"${decrypted_reference_file}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# Attempt to decrypt the reference file with a non-existent envvar.\n\t# We want this command to fail with 1.\n\tsetup_check \"scrypt dec env none\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    dec --passphrase env:THIS_ENVVAR_DOES_NOT_EXIST\t\t\\\n\t    \"${encrypted_reference_file}\" \"${decrypted_reference_file}\"\t\\\n\t    2> \"${decrypted_no_envvar_log}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec env none error\"\n\tgrep -q\t\t\t\t\t\t\t\t\\\n\t    \"scrypt: Failed to read from \\${THIS_ENVVAR_DOES_NOT_EXIST}\" \\\n\t    \"${decrypted_no_envvar_log}\"\n\techo \"$?\" > \"${c_exitfile}\"\n\n\t# We should not have created a file.\n\tsetup_check \"scrypt dec env no file\"\n\ttest -e \"${decrypted_badpass_file}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# Attempt to decrypt the reference file with an incorrect passphrase.\n\t# We want this command to fail with 1.\n\tsetup_check \"scrypt dec env bad\"\n\tPASSPHRASE=\"bad-pass\"\t\t\t\t\t\t\\\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    dec --passphrase env:PASSPHRASE\t\t\t\t\\\n\t    \"${encrypted_reference_file}\" \"${decrypted_reference_file}\"\t\\\n\t    2> \"${decrypted_badpass_log}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec env bad error\"\n\tgrep -q \"scrypt: Passphrase is incorrect\" \"${decrypted_badpass_log}\"\n\techo \"$?\" > \"${c_exitfile}\"\n\n\tsetup_check \"scrypt dec env bad no file\"\n\t# We should not have created a file.\n\ttest -e \"${decrypted_badpass_file}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/08-passphrase-file.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\npassphrase_file=\"${s_basename}-passphrase.txt\"\nbad_passphrase_file=\"${s_basename}-passphrase-bad.txt\"\nencrypted_reference_file=\"${scriptdir}/verify-strings/test_scrypt_good.enc\"\ndecrypted_reference_file=\"${s_basename}-attempt_reference.txt\"\ndecrypted_badpass_file=\"${s_basename}-decrypt-badpass.txt\"\ndecrypted_badpass_log=\"${s_basename}-decrypt-badpass.log\"\ndecrypted_no_file_log=\"${s_basename}-decrypt-no-file.log\"\n\nscenario_cmd() {\n\t# Create the passphrase file.\n\techo \"${password}\" > \"${passphrase_file}\"\n\n\t# Decrypt a reference file using --passphrase file:FILENAME.\n\tsetup_check \"scrypt dec file\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    dec --passphrase file:\"${passphrase_file}\"\t\t\t\\\n\t    \"${encrypted_reference_file}\" \"${decrypted_reference_file}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# The decrypted reference file should match the reference.\n\tsetup_check \"scrypt dec file output against reference\"\n\tcmp -s \"${decrypted_reference_file}\" \"${reference_file}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# Attempt to decrypt the reference file with a non-existent file.\n\t# We want this command to fail with 1.\n\tsetup_check \"scrypt dec file none\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    dec --passphrase file:THIS_FILE_DOES_NOT_EXIST\t\t\\\n\t    \"${encrypted_reference_file}\" \"${decrypted_reference_file}\"\t\\\n\t    2> \"${decrypted_no_file_log}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec file none error\"\n\tgrep -q\t\"scrypt: fopen(THIS_FILE_DOES_NOT_EXIST)\"\t\t\\\n\t    \"${decrypted_no_file_log}\"\n\techo \"$?\" > \"${c_exitfile}\"\n\n\t# We should not have created a file.\n\tsetup_check \"scrypt dec file none no file\"\n\ttest -e \"${decrypted_badpass_file}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# Attempt to decrypt the reference file with an incorrect passphrase.\n\t# We want this command to fail with 1.\n\tsetup_check \"scrypt dec file bad\"\n\techo \"bad-pass\" > \"${bad_passphrase_file}\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    dec --passphrase file:\"${bad_passphrase_file}\"\t\t\\\n\t    \"${encrypted_reference_file}\" \"${decrypted_reference_file}\"\t\\\n\t    2> \"${decrypted_badpass_log}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# We should have received an error message.\n\tsetup_check \"scrypt dec file bad error\"\n\tgrep -q \"scrypt: Passphrase is incorrect\" \"${decrypted_badpass_log}\"\n\techo \"$?\" > \"${c_exitfile}\"\n\n\t# We should not have created a file.\n\tsetup_check \"scrypt dec file bad no file\"\n\ttest -e \"${decrypted_badpass_file}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/09-explicit-params.sh",
    "content": "#!/bin/sh\n\n### Constants\nc_valgrind_min=1\nreference_file=\"${scriptdir}/verify-strings/test_scrypt.good\"\nencrypted_file=\"${s_basename}-reference.enc\"\nstderr=\"${s_basename}-reference.stderr\"\nencrypted_file_bad=\"${s_basename}-reference-bad.enc\"\nstderr_bad=\"${s_basename}-reference-bad.stderr\"\n\nscenario_cmd() {\n\t# Encrypt with manually-specified N, r, p.\n\tsetup_check \"scrypt enc Nrp\"\n\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\"\t\\\n\t    enc -v --logN 12 -r 2 -p 3\t\t\t\t\t\\\n\t    --passphrase dev:stdin-once\t\t\t\t\t\\\n\t    \"${reference_file}\" \"${encrypted_file}\"\t\t\t\\\n\t    2> \"${stderr}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# Check that the options were used.\n\tsetup_check \"scrypt enc Nrp output N\"\n\tgrep -q \"N = 4096\" \"${stderr}\"\n\techo $? > \"${c_exitfile}\"\n\n\tsetup_check \"scrypt enc Nrp output r\"\n\tgrep -q \"r = 2\" \"${stderr}\"\n\techo $? > \"${c_exitfile}\"\n\n\tsetup_check \"scrypt enc Nrp output p\"\n\tgrep -q \"p = 3\" \"${stderr}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# Try to encrypt with badly-specified N, r, p; should fail.\n\tsetup_check \"scrypt enc Nrp bad\"\n\techo \"${password}\" | ${c_valgrind_cmd} \"${bindir}/scrypt\"\t\\\n\t    enc -v --logN 2 -r 0 -p 0\t\t\t\t\t\\\n\t    --passphrase dev:stdin-once\t\t\t\t\t\\\n\t    \"${reference_file}\" \"${encrypted_file_bad}\"\t\t\t\\\n\t    2> \"${stderr_bad}\"\n\texpected_exitcode 1 $? > \"${c_exitfile}\"\n\n\t# Check that we got an error.\n\tsetup_check \"scrypt enc Nrp bad output\"\n\tgrep -q \"\\--logN must be between 10 and 40 (inclusive)\" \"${stderr_bad}\"\n\techo $? > \"${c_exitfile}\"\n\n\t# Check that we can't partially set explicit parameters.\n\tsetup_check \"scrypt enc --logN only\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    enc --logN 12 \"${reference_file}\" 2>&1 |\t\t\t\\\n\t    grep -q \"If --logN is set, -r and -p must also be set\"\n\techo $? > \"${c_exitfile}\"\n\n\tsetup_check \"scrypt enc -r only\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    enc -r 12 \"${reference_file}\" 2>&1 |\t\t\t\\\n\t    grep -q \"If -r is set, --logN and -p must also be set\"\n\techo $? > \"${c_exitfile}\"\n\n\tsetup_check \"scrypt enc -p only\"\n\t${c_valgrind_cmd} \"${bindir}/scrypt\"\t\t\t\t\\\n\t    enc -p 12 \"${reference_file}\" 2>&1 |\t\t\t\\\n\t    grep -q \"If -p is set, --logN and -r must also be set\"\n\techo $? > \"${c_exitfile}\"\n}\n"
  },
  {
    "path": "tests/libscrypt-kdf/sample-libscrypt-kdf.c",
    "content": "#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"scrypt-kdf.h\"\n\n/* Parameters controlling memory usage and CPU time. */\n#define N 16384\n#define r 8\n#define p 1\n\n/* How much data should scrypt return? */\n#define OUTPUT_BUFLEN 8\n\nint\nmain(void)\n{\n\tconst char * passwd = \"hunter2\";\n\tconst char * salt = \"DANGER -- this should be a random salt -- DANGER\";\n\tuint8_t output[OUTPUT_BUFLEN];\n\tint exitcode;\n\n\t/* Perform hashing. */\n\texitcode = scrypt_kdf((const uint8_t *)passwd, strlen(passwd),\n\t    (const uint8_t*)salt, strlen(salt), N, r, p,\n\t    output, OUTPUT_BUFLEN);\n\n\t/* Notify user of success / failure. */\n\tif (exitcode == 0)\n\t\tprintf(\"scrypt(): success\\n\");\n\telse\n\t\tprintf(\"scrypt(): failure %d\\n\", exitcode);\n\n\treturn (exitcode);\n}\n"
  },
  {
    "path": "tests/shared_test_functions.sh",
    "content": "#!/bin/sh\n\n### Definitions\n#\n# This test suite uses the following terminology:\n# - scenario: a series of commands to test.  Each must be in a\n#       separate file, and must be completely self-contained\n#       (other than the variables listed below).\n# - check: a series of commands that produces an exit code which\n#       the test suite should check.  A scenario may contain any\n#       number of checks.\n#\n### Design\n#\n# The main function is _scenario_runner(scenario_filename), which\n# takes a scenario file as the argument, and runs a\n#     scenario_cmd()\n# function which was defined in that file.\n#\n# Functions which are available to other scripts as a \"public API\" are:\n# - find_system(cmd, args):\n#   Look for ${cmd} in the ${PATH}, and ensure that it supports ${args}.\n# - has_pid(cmd):\n#   Look for a ${cmd} in $(ps).\n# - wait_while(timeout, func):\n#   Wait up to ${timeout} milliseconds, or until ${func} returns non-zero.\n# - setup_check(description, check_prev):\n#   Set up the below variables.\n# - expected_exitcode(expected, actual):\n#   Check if ${expected} matches ${actual}.\n# - run_scenarios():\n#   Run scenarios in the test directory.\n#\n# We adopt the convention of \"private\" function names beginning with an _.\n#\n### Variables\n#\n# Wherever possible, this suite uses local variables and\n# explicitly-passed arguments, with the following exceptions:\n# - s_basename: this is the basename for the scenario's temporary\n#       and log files.\n# - s_val_basename: this is the basename for the scenario's\n#       valgrind log files.\n# - s_retval: this is the overall exit code of the scenario.\n# - c_count_next: this is the count of the scenario's checks (so that\n#       each check can have distinct files).\n# - c_count_str: the previous value of ${c_count_next}, expressed as a\n#       two-digit string.  In other words, when we're working on the Nth\n#       check, ${c_count_next} is N, while ${c_count_str} is N-1.\n# - c_exitfile: this contains the exit code of each check.\n# - c_valgrind_min: this is the minimum value of USE_VALGRIND\n#       which will enable valgrind checking for this check.\n# - c_valgrind_cmd: this is the valgrind command (including\n#       appropriate log file) if necessary, or is \"\" otherwise.\n\nset -o noclobber -o nounset\n\n# Keep the user-specified \"print info about test failures\", or initialize to 0\n# (don't print extra info).\nVERBOSE=${VERBOSE:-0}\n\n# Keep the user-specified ${USE_VALGRIND}, or initialize to 0 (don't do memory\n# tests).  If ${USE_VALGRIND_NO_REGEN} is non-zero, re-use the previous\n# suppressions files instead of generating new ones.\nUSE_VALGRIND=${USE_VALGRIND:-0}\nUSE_VALGRIND_NO_REGEN=${USE_VALGRIND_NO_REGEN:-0}\n\n# Load valgrind-related functions.  These functions will bail on a per-check\n# basis if the ${USE_VALGRIND} value does not indicate that we should run a\n# valgrind for that check.\n. \"${scriptdir}/shared_valgrind_functions.sh\"\n\n# Set ${bindir} to $1 if given, else use \".\" for in-tree builds.\nbindir=$(CDPATH='' cd -- \"$(dirname -- \"${1-.}\")\" && pwd -P)\n\n# Default value (should be set by tests).\nNO_EXITFILE=/dev/null\n\n# A non-zero value unlikely to be used as an exit code by the programs being\n# tested.\nvalgrind_exit_code=108\n\n\n## _prepdir():\n# Delete the previous test output directory, and create a new one.\n_prepdir() {\n\tif [ -d \"${out}\" ]; then\n\t\trm -rf \"${out}\"\n\tfi\n\tmkdir \"${out}\"\n\n\t# We don't want to back up this directory.\n\t[ \"$(uname)\" = \"FreeBSD\" ] && chflags nodump \"${out}\"\n}\n\n## find_system (cmd, args):\n# Look for ${cmd} in the ${PATH}, and ensure that it supports ${args}.\nfind_system() {\n\t_find_system_cmd=$1\n\t_find_system_cmd_with_args=\"$1 ${2:-}\"\n\n\t# Sanity check.\n\tif [ \"$#\" -gt \"2\" ]; then\n\t\tprintf \"Programmer error: find_system: too many args\\n\" 1>&2\n\t\texit 1\n\tfi\n\n\t# Look for ${cmd}; the \"|| true\" and -} make this work with set -e.\n\t_find_system_binary=$(command -v \"${_find_system_cmd}\") || true\n\tif [ -z \"${_find_system_binary-}\" ]; then\n\t\t_find_system_binary=\"\"\n\t\tprintf \"System %s not found.\\n\" \"${_find_system_cmd}\" 1>&2\n\t# If the command exists, check it ensures the ${args}.\n\telif ${_find_system_cmd_with_args} 2>&1 >/dev/null |\t\\\n\t    grep -qE \"(invalid|illegal) option\"; then\n\t\t_find_system_binary=\"\"\n\t\tprintf \"Cannot use system %s; does not\"\t\t\\\n\t\t    \"${_find_system_cmd}\" 1>&2\n\t\tprintf \" support necessary arguments.\\n\" 1>&2\n\tfi\n\techo \"${_find_system_binary}\"\n}\n\n## has_pid (cmd):\n# Look for ${cmd} in ps; return 0 if ${cmd} exists.\nhas_pid() {\n\t_has_pid_cmd=$1\n\t_has_pid_pid=$(ps -Aopid,args | grep -F \"${_has_pid_cmd}\" |\t\\\n\t    grep -v \"grep\") || true\n\tif [ -n \"${_has_pid_pid}\" ]; then\n\t\treturn 0\n\tfi\n\treturn 1\n}\n\n## wait_while(timeout, func):\n# Wait while ${func} returns 0.  If ${msleep} is defined, use that to wait\n# 100ms; otherwise, wait in 1 second increments.  If ${timeout} is non-zero,\n# return 1 if ${timeout} milliseconds have passed.\nwait_while() {\n\t_wait_while_ms=0\n\t_wait_while_timeout=$1\n\tshift 1\n\n\t# Check for the ending condition\n\twhile \"$@\"; do\n\t\t# Notify user (if desired)\n\t\tif [ \"${VERBOSE}\" -ne 0 ]; then\n\t\t\tprintf \"waited\\t%dms\\t%s\\n\"\t\t\\\n\t\t\t    \"${_wait_while_ms}\" \"$*\" 1>&2\n\t\tfi\n\n\t\t# Bail if we've exceeded the timeout\n\t\tif [ \"${_wait_while_timeout}\" -gt 0 ] &&\t\\\n\t\t    [ \"${_wait_while_ms}\" -gt \"${_wait_while_timeout}\" ]; then\n\t\t\tif [ \"${VERBOSE}\" -ne 0 ]; then\n\t\t\t\tprintf \"Bail; timeout exceeded\\n\" 1>&2\n\t\t\tfi\n\t\t\treturn 1\n\t\tfi\n\n\t\t# Wait using the appropriate binary\n\t\tif [ -n \"${msleep:-}\" ]; then\n\t\t\t\"${msleep}\" 100\n\t\t\t_wait_while_ms=$((_wait_while_ms + 100))\n\t\telse\n\t\t\tsleep 1\n\t\t\t_wait_while_ms=$((_wait_while_ms + 1000))\n\t\tfi\n\tdone\n\n\t# Success\n\treturn 0\n}\n\n## setup_check (description, check_prev=1):\n# Set up the \"check\" variables ${c_exitfile} and ${c_valgrind_cmd}, the\n# latter depending on the previously-defined ${c_valgrind_min}.\n# Advance the number of checks ${c_count_next} so that the next call to this\n# function will set up new filenames.  Write ${description} into a\n# file.  If ${check_prev} is non-zero, check that the previous\n# ${c_exitfile} exists.\nsetup_check() {\n\t_setup_check_description=$1\n\t_setup_check_prev=${2:-1}\n\n\t# Should we check for the previous exitfile?\n\tif [ \"${c_exitfile}\" != \"${NO_EXITFILE}\" ] &&\t\t\t\\\n\t    [ \"${_setup_check_prev}\" -gt 0 ] ; then\n\t\t# Check for the file.\n\t\tif [ ! -f \"${c_exitfile}\" ] ; then\n\t\t\t# We should have written the result of the\n\t\t\t# previous test to this file.\n\t\t\techo \"PROGRAMMING FAILURE\" 1>&2\n\t\t\techo \"We should already have ${c_exitfile}\" 1>&2\n\t\t\texit 1\n\t\tfi\n\tfi\n\n\t# Set up the \"exit\" file.\n\tc_count_str=$(printf \"%02d\" \"${c_count_next}\")\n\tc_exitfile=\"${s_basename}-${c_count_str}.exit\"\n\n\t# Write the \"description\" file.\n\tprintf \"%s\\n\" \"${_setup_check_description}\" >\t\t\t\\\n\t\t\"${s_basename}-${c_count_str}.desc\"\n\n\t# Set up the valgrind command (or an empty string).\n\tc_valgrind_cmd=\"$(valgrind_setup)\"\n\n\t# Advances the number of checks.\n\tc_count_next=$((c_count_next + 1))\n}\n\n## expected_exitcode (expected, exitcode):\n# If ${exitcode} matches the ${expected} value, return 0.  If the exitcode is\n# ${valgrind_exit_code}, return that.  Otherwise, return 1 to indicate\n# failure.\nexpected_exitcode() {\n\t_expected_exitcode_expected=$1\n\t_expected_exitcode_exitcode=$2\n\n\tif [ \"${_expected_exitcode_exitcode}\" -eq\t\t\\\n\t    \"${_expected_exitcode_expected}\" ]; then\n\t\techo \"0\"\n\telif [ \"${_expected_exitcode_exitcode}\" -eq\t\t\\\n\t    \"${valgrind_exit_code}\" ]; then\n\t\techo \"${valgrind_exit_code}\"\n\telse\n\t\techo \"1\"\n\tfi\n}\n\n## _check (log_basename, val_log_basename):\n# Examine all \"exit code\" files beginning with ${log_basename} and\n# print \"SUCCESS!\", \"FAILED!\", \"SKIP!\", or \"PARTIAL SUCCESS / SKIP!\"\n# as appropriate.  Check any valgrind log files associated with the\n# test and print \"FAILED!\" if appropriate, along with the valgrind\n# logfile.  If the test failed and ${VERBOSE} is non-zero, print\n# the description to stderr.\n_check() {\n\t_check_log_basename=$1\n\t_check_val_log_basename=$2\n\n\t# Bail if there's no exitfiles.\n\t_check_exitfiles=$(ls \"${_check_log_basename}\"-*.exit) || true\n\tif [ -z \"${_check_exitfiles}\" ]; then\n\t\techo \"FAILED\" 1>&2\n\t\ts_retval=1\n\t\treturn\n\tfi\n\n\t# Count results\n\t_check_total=0\n\t_check_skip=0\n\n\t# Check each exitfile.\n\tfor _check_exitfile in $(echo \"${_check_exitfiles}\" | sort); do\n\t\t_check_ret=$(cat \"${_check_exitfile}\")\n\t\t_check_total=$(( _check_total + 1 ))\n\t\tif [ \"${_check_ret}\" -lt 0 ]; then\n\t\t\t_check_skip=$(( _check_skip + 1 ))\n\t\tfi\n\n\t\t# Check for test failure.\n\t\t_check_descfile=$(echo \"${_check_exitfile}\"\t\t\\\n\t\t    | sed 's/\\.exit/\\.desc/g')\n\t\tif [ \"${_check_ret}\" -gt 0 ]; then\n\t\t\techo \"FAILED!\" 1>&2\n\t\t\tif [ \"${VERBOSE}\" -ne 0 ]; then\n\t\t\t\tprintf \"File %s contains exit code %s.\\n\" \\\n\t\t\t\t    \"${_check_exitfile}\" \"${_check_ret}\" \\\n\t\t\t\t    1>&2\n\t\t\t\tprintf \"Test description: \" 1>&2\n\t\t\t\tcat \"${_check_descfile}\" 1>&2\n\t\t\tfi\n\t\t\ts_retval=${_check_ret}\n\t\t\treturn\n\t\telse\n\t\t\t# If there's no failure, delete the files.\n\t\t\trm \"${_check_exitfile}\"\n\t\t\trm \"${_check_descfile}\"\n\t\tfi\n\n\t\t# Check valgrind logfile(s).\n\t\t_check_val_failed=\"$(valgrind_check \"${_check_exitfile}\")\"\n\t\tif [ -n \"${_check_val_failed}\" ]; then\n\t\t\techo \"FAILED!\" 1>&2\n\t\t\ts_retval=\"${valgrind_exit_code}\"\n\t\t\tcat \"${_check_val_failed}\" 1>&2\n\t\t\treturn\n\t\tfi\n\tdone\n\n\t# Notify about skip or success.\n\tif [ \"${_check_skip}\" -gt 0 ]; then\n\t\tif [ \"${_check_skip}\" -eq \"${_check_total}\" ]; then\n\t\t\techo \"SKIP!\" 1>&2\n\t\telse\n\t\t\techo \"PARTIAL SUCCESS / SKIP!\" 1>&2\n\t\tfi\n\telse\n\t\techo \"SUCCESS!\" 1>&2\n\tfi\n}\n\n## _scenario_runner (scenario_filename):\n# Run a test scenario from ${scenario_filename}.\n_scenario_runner() {\n\t_scenario_runner_filename=$1\n\t_scenario_runner_basename=$(basename \"${_scenario_runner_filename}\" .sh)\n\tprintf \"  %s... \" \"${_scenario_runner_basename}\" 1>&2\n\n\t# Initialize \"scenario\" and \"check\" variables.\n\ts_basename=${out}/${_scenario_runner_basename}\n\ts_val_basename=${out_valgrind}/${_scenario_runner_basename}\n\tc_count_next=0\n\tc_exitfile=\"${NO_EXITFILE}\"\n\tc_valgrind_min=9\n\tc_valgrind_cmd=\"\"\n\n\t# Load scenario_cmd() from the scenario file.\n\tunset scenario_cmd\n\t. \"${_scenario_runner_filename}\"\n\tif ! command -v scenario_cmd 1>/dev/null ; then\n\t\tprintf \"ERROR: scenario_cmd() is not defined in\\n\" 1>&2\n\t\tprintf \"  %s\\n\" \"${_scenario_runner_filename}\" 1>&2\n\t\texit 1\n\tfi\n\n\t# Run the scenario command.\n\tscenario_cmd\n\n\t# Print PASS or FAIL, and return result.\n\ts_retval=0\n\t_check \"${s_basename}\" \"${s_val_basename}\"\n\n\treturn \"${s_retval}\"\n}\n\n## run_scenarios ():\n# Run all scenarios in the test directory.  If the environment variable ${N}\n# is specified, only run the scenario corresponding to that number.\nrun_scenarios() {\n\t# Get the test number(s) to run.\n\tif [ \"${N:-0}\" -gt \"0\" ]; then\n\t\t_run_scenarios_filenames=\"$(printf\t\t\t\\\n\t\t    \"${scriptdir}/%02d-*.sh\" \"${N}\")\"\n\telse\n\t\t_run_scenarios_filenames=\"${scriptdir}/??-*.sh\"\n\tfi\n\n\t# Clean up any previous directory, and create a new one.\n\t_prepdir\n\n\t# Clean up any previous valgrind directory, and prepare for new\n\t# valgrind tests (if applicable).\n\tvalgrind_init\n\n\tprintf -- \"Running tests\\n\" 1>&2\n\tprintf -- \"-------------\\n\" 1>&2\n\tfor _run_scenarios_filename in ${_run_scenarios_filenames}; do\n\t\t# We can't call this function with $( ... ) because we\n\t\t# want to allow it to echo values to stdout.\n\t\t_scenario_runner \"${_run_scenarios_filename}\"\n\t\t_run_scenarios_retval=$?\n\t\tif [ \"${_run_scenarios_retval}\" -gt 0 ]; then\n\t\t\texit \"${_run_scenarios_retval}\"\n\t\tfi\n\tdone\n}\n"
  },
  {
    "path": "tests/shared_valgrind_functions.sh",
    "content": "#!/bin/sh\n\nset -o noclobber -o nounset\n\n### Design\n#\n# This file contains functions related to checking with valgrind.  The POSIX sh\n# language doesn't allow us to specify a \"public API\", but if we could, it\n# would be:\n# - valgrind_init():\n#   Clear previous valgrind output, and prepare for running valgrind tests\n#   (if applicable).\n# - valgrind_setup(str):\n#   Set up the valgrind command if ${USE_VALGRIND} is greater than or equal to\n#   ${valgrind_min}.  If ${str} is not blank, include it in the log filename.\n# - valgrind_check(exitfile):\n#   Check for any memory leaks recorded in valgrind logfiles associated with a\n#   test exitfile.  Return the filename if there's a leak; otherwise return an\n#   empty string.\n# - valgrind_incomplete():\n#   Check if any valgrind log files are incomplete.\n#\n# We adopt the convention of \"private\" function names beginning with an _.\n#\n### Variables\n#\n# Wherever possible, this suite uses local variables and\n# explicitly-passed arguments, with the following exceptions:\n# - valgrind_suppressions: filename of valgrind suppressions.\n# - valgrind_fds_log: filename of the log of open file descriptors.\n\n\n## _val_prepdir ():\n# Clean up a previous valgrind directory, and prepare for new valgrind tests\n# (if applicable).\n_val_prepdir() {\n\t# If we don't want to generate new suppressions files, move them.\n\tif [ \"${USE_VALGRIND_NO_REGEN}\" -gt 0 ]; then\n\t\t# Bail if the file doesn't exist.\n\t\tif [ ! -e \"${valgrind_suppressions}\" ]; then\n\t\t\techo \"No valgrind suppressions file\" 1>&2\n\t\t\texit 1\n\t\tfi\n\n\t\t# Move the files away.\n\t\t_val_prepdir_supp_tmp=\"$(mktemp /tmp/valgrind-suppressions.XXXXXX)\"\n\t\t_val_prepdir_fds_tmp=\"$(mktemp /tmp/valgrind-fds.XXXXXX)\"\n\t\tmv \"${valgrind_suppressions}\" \"${_val_prepdir_supp_tmp}\"\n\t\tmv \"${valgrind_fds_log}\" \"${_val_prepdir_fds_tmp}\"\n\tfi\n\n\t# Always delete any previous valgrind directory.\n\tif [ -d \"${out_valgrind}\" ]; then\n\t\trm -rf \"${out_valgrind}\"\n\tfi\n\n\t# Bail if we don't want valgrind at all.\n\tif [ \"${USE_VALGRIND}\" -eq 0 ]; then\n\t\treturn\n\tfi\n\n\tmkdir \"${out_valgrind}\"\n\n\t# If we don't want to generate a new suppressions file, restore it.\n\tif [ \"${USE_VALGRIND_NO_REGEN}\" -gt 0 ]; then\n\t\t# Move the files back.\n\t\tmv \"${_val_prepdir_supp_tmp}\" \"${valgrind_suppressions}\"\n\t\tmv \"${_val_prepdir_fds_tmp}\" \"${valgrind_fds_log}\"\n\tfi\n\n\t# We don't want to back up this directory.\n\t[ \"$(uname)\" = \"FreeBSD\" ] && chflags nodump \"${out_valgrind}\"\n}\n\n## _val_checkver ():\n# If ${USE_VALGRIND} is greater than 0, check that valgrind is available in\n# the ${PATH} and is at least version 3.13.\n_val_checkver() {\n\t# Quit if we're not using valgrind.\n\tif [ ! \"${USE_VALGRIND}\" -gt 0 ]; then\n\t\treturn\n\tfi;\n\n\t# Look for valgrind in $PATH.\n\tif ! command -v valgrind >/dev/null 2>&1; then\n\t\tprintf \"valgrind not found\\n\" 1>&2\n\t\texit 1\n\tfi\n\n\t# Check the version.\n\t_val_checkver_version=$(valgrind --version | cut -d \"-\" -f 2)\n\t_val_checkver_major=$(echo \"${_val_checkver_version}\" | cut -d \".\" -f 1)\n\t_val_checkver_minor=$(echo \"${_val_checkver_version}\" | cut -d \".\" -f 2)\n\tif [ \"${_val_checkver_major}\" -lt \"3\" ]; then\n\t\tprintf \"valgrind must be at least version 3.13\\n\" 1>&2\n\t\texit 1;\n\tfi\n\tif [ \"${_val_checkver_major}\" -eq \"3\" ] &&\t\t\t\\\n\t    [ \"${_val_checkver_minor}\" -lt \"13\" ]; then\n\t\tprintf \"valgrind must be at least version 3.13\\n\" 1>&2\n\t\texit 1;\n\tfi\n}\n\n## _val_seg(filename):\n# Generalize an already-segmented portion of a valgrind suppressions file;\n# write the result to ${valgrind_suppressions}.\n_val_seg() {\n\t_val_seg_filename=$1\n\n\t# Find last relevant line.\n\t_val_seg_lastline=\"$(grep -n \"}\" \"${_val_seg_filename}\" | cut -f1 -d:)\"\n\n\t# Cut off anything below the 1st \"fun:pl_\" (inclusive).\n\t_val_seg_funcline=\"$(grep -n \"fun:pl_\" \"${_val_seg_filename}\" |\t\\\n\t\tcut -f1 -d: |\t\t\t\t\t\t\\\n\t\thead -n1)\"\n\tif [ -n \"${_val_seg_funcline}\" ]; then\n\t\tif [ \"${_val_seg_lastline}\" -gt \"${_val_seg_funcline}\" ]; then\n\t\t\t_val_seg_lastline=\"${_val_seg_funcline}\"\n\t\tfi\n\tfi\n\n\t# Cut off anything below \"fun:main\" (including that line).  (Due to\n\t# linking and/or optimizations, some memory leaks occur without\n\t# \"fun:pl_\" appearing in the valgrind suppression.)\n\t_val_seg_funcline=\"$(grep -n \"fun:main\" \"${_val_seg_filename}\" | \\\n\t    cut -f1 -d:)\"\n\tif [ -n \"${_val_seg_funcline}\" ]; then\n\t\tif [ \"${_val_seg_lastline}\" -gt \"${_val_seg_funcline}\" ]; then\n\t\t\t_val_seg_lastline=\"${_val_seg_funcline}\"\n\t\tfi\n\tfi\n\n\t# Only keep the beginning of each suppression.\n\t_val_seg_lastline=\"$((_val_seg_lastline - 1))\"\n\thead -n \"${_val_seg_lastline}\" \"${_val_seg_filename}\" >>\t\\\n\t    \"${valgrind_suppressions}\"\n\tprintf \"}\\n\" >> \"${valgrind_suppressions}\"\n}\n\n## _val_generalize(filename):\n# Generalize suppressions from a valgrind suppression file by omitting the\n# \"fun:pl_*\" and \"fun:main\" lines and anything below them.\n_val_generalize() {\n\t_val_generalize_filename=$1\n\n\t# How many segments do we have?\n\t_val_generalize_num_segments=\"$(grep -c \"^{\" \"${_val_generalize_filename}\")\"\n\n\t# Bail if there's nothing to do.\n\tif [ \"${_val_generalize_num_segments}\" -eq \"0\" ]; then\n\t\treturn\n\tfi\n\n\t# Sanity check.\n\tif [ \"${_val_generalize_num_segments}\" -gt 100 ]; then\n\t\tprintf \"More than 100 valgrind suppressions?!\\n\" 1>&2\n\t\texit 1\n\tfi\n\n\t# Split into segments.\n\tcsplit -f \"${_val_generalize_filename}\" \"${_val_generalize_filename}\" \\\n\t    \"/{/\" \"{$((_val_generalize_num_segments - 1))}\" > /dev/null\n\n\t# Skip \"${filename}00\" because that doesn't contain a suppression.\n\t_val_generalize_i=1\n\twhile [ \"${_val_generalize_i}\" -le \"${_val_generalize_num_segments}\" ]; do\n\t\t# Process segment\n\t\t_val_seg \"$(printf \"%s%02d\"\t\t\t\t\\\n\t\t    \"${_val_generalize_filename}\" \"${_val_generalize_i}\")\"\n\n\t\t# Advance to the next suppression.\n\t\t_val_generalize_i=$((_val_generalize_i + 1))\n\tdone\n}\n\n## _val_ensure (potential_memleaks_binary):\n# Run the ${potential_memleaks_binary} through valgrind, keeping\n# track of any apparent memory leak in order to suppress reporting\n# those leaks when testing other binaries.  Record a log file which shows the\n# open file descriptors in ${valgrind_fds_log}.\n_val_ensure() {\n\t_val_ensure_potential_memleaks_binary=$1\n\n\t# Quit if we're not using valgrind.\n\tif [ ! \"${USE_VALGRIND}\" -gt 0 ]; then\n\t\treturn\n\tfi;\n\n\tif [ \"${USE_VALGRIND_NO_REGEN}\" -gt 0 ]; then\n\t\tprintf \"Using old valgrind suppressions\\n\" 1>&2\n\t\treturn\n\tfi\n\n\tprintf \"Generating valgrind suppressions... \" 1>&2\n\t_val_ensure_log=\"${out_valgrind}/suppressions.pre\"\n\n\t# Start off with an empty suppression file\n\ttouch \"${valgrind_suppressions}\"\n\n\t# Get list of tests and the number of open descriptors at a normal exit\n\t_val_ensure_names=\"${out_valgrind}/suppressions-names.txt\"\n\tvalgrind --track-fds=yes --log-file=\"${valgrind_fds_log}\"\t\\\n\t    \"${_val_ensure_potential_memleaks_binary}\"\t\t\t\\\n\t    > \"${_val_ensure_names}\"\n\n\t# Generate suppressions for each test\n\twhile read -r _val_ensure_testname; do\n\t\t_val_ensure_thisl=\"${_val_ensure_log}-${_val_ensure_testname}\"\n\n\t\t# Run valgrind on the binary, sending it a \"\\n\" so that\n\t\t# a test which uses STDIN will not wait for user input.\n\t\tprintf \"\\n\" | (valgrind\t\t\t\t\t\\\n\t\t    --leak-check=full --show-leak-kinds=all\t\t\\\n\t\t    --gen-suppressions=all\t\t\t\t\\\n\t\t    --trace-children=yes\t\t\t\t\\\n\t\t    --suppressions=\"${valgrind_suppressions}\"\t\t\\\n\t\t    --log-file=\"${_val_ensure_thisl}\"\t\t\t\\\n\t\t    \"${_val_ensure_potential_memleaks_binary}\"\t\t\\\n\t\t    \"${_val_ensure_testname}\")\t\t\t\t\\\n\t\t    > /dev/null\n\n\t\t# Append name to suppressions file\n\t\tprintf \"# %s\\n\" \"${_val_ensure_testname}\"\t\t\\\n\t\t    >> \"${valgrind_suppressions}\"\n\n\t\t# Strip out useless parts from the log file, and allow the\n\t\t# suppressions to apply to other binaries.\n\t\t_val_generalize \"${_val_ensure_thisl}\"\n\tdone < \"${_val_ensure_names}\"\n\n\t# Clean up\n\trm -f \"${_val_ensure_log}\"\n\tprintf \"done.\\n\" 1>&2\n}\n\n## valgrind_setup (str):\n# Set up the valgrind command if ${USE_VALGRIND} is greater than or equal to\n# ${valgrind_min}.  If ${str} is not blank, include it in the log filename.\nvalgrind_setup() {\n\t_valgrind_setup_str=${1:-}\n\n\t# Bail if we don't want to use valgrind for this check.\n\tif [ \"${USE_VALGRIND}\" -lt \"${c_valgrind_min}\" ]; then\n\t\treturn\n\tfi\n\n\t# Set up the log filename.\n\tif [ -n \"${_valgrind_setup_str}\" ]; then\n\t\t_valgrind_setup_logfilename=\"${s_val_basename}-${c_count_str}-${_valgrind_setup_str}-%p.log\"\n\telse\n\t\t_valgrind_setup_logfilename=\"${s_val_basename}-${c_count_str}-%p.log\"\n\tfi\n\n\t# Set up valgrind command.\n\t_valgrind_setup_cmd=\"valgrind\t\t\t\t\\\n\t\t--log-file=${_valgrind_setup_logfilename}\t\\\n\t\t--track-fds=yes\t\t\t\t\t\\\n\t\t--trace-children=yes\t\t\t\t\\\n\t\t--leak-check=full\t\t\t\t\\\n\t\t--show-leak-kinds=all\t\t\t\t\\\n\t\t--errors-for-leak-kinds=all\t\t\t\\\n\t\t--suppressions=${valgrind_suppressions}\"\n\techo \"${_valgrind_setup_cmd}\"\n}\n\n## valgrind_incomplete:\n# Return 0 if at least one valgrind log file is not complete.\nvalgrind_incomplete() {\n\t# The exit code of `grep -L` is undesirable: if at least one file\n\t# contains the pattern, it returns 0.  To detect if at least one file\n\t# does *not* contain the pattern, we need to check grep's output,\n\t# rather than the exit code.\n\t_valgrind_incomplete_logfiles=$(grep -L \"ERROR SUMMARY\"\t\t\\\n\t    \"${out_valgrind}\"/*.log)\n\ttest -n \"${_valgrind_incomplete_logfiles}\"\n}\n\n## _val_getbase (exitfile):\n# Return the filename without \".log\" of the valgrind logfile corresponding to\n# ${exitfile}.\n_val_getbase() {\n\t_val_getbase_exitfile=$1\n\t_val_getbase_basename=$(basename \"${_val_getbase_exitfile}\" \".exit\")\n\techo \"${out_valgrind}/${_val_getbase_basename}\"\n}\n\n## _val_checkl(logfile)\n# Check for any (unsuppressed) memory leaks recorded in a valgrind logfile.\n# Echo the filename if there's a leak; otherwise, echo nothing.\n_val_checkl() {\n\t_val_checkl_logfile=$1\n\n\t# Bytes in use at exit.\n\t_val_checkl_in_use=$(grep \"in use at exit:\" \"${_val_checkl_logfile}\" | awk '{print $6}')\n\n\t# Sanity check.\n\tif [ \"$(echo \"${_val_checkl_in_use}\" | wc -w)\" -ne \"1\" ]; then\n\t\techo \"Programmer error: invalid number valgrind outputs\" 1>&2\n\t\texit 1\n\tfi\n\n\t# Check for any leaks.  Use string comparison, because valgrind formats\n\t# the number with commas, and sh can't convert strings like \"1,000\"\n\t# into an integer.\n\tif [ \"${_val_checkl_in_use}\" != \"0\" ] ; then\n\t\t# Check if all of the leaked bytes are suppressed.  The extra\n\t\t# whitespace in \" suppressed\" is necessary to distinguish\n\t\t# between two instances of \"suppressed\" in the log file.  Use\n\t\t# string comparison due to the format of the number.\n\t\t_val_checkl_suppressed=$(grep \" suppressed:\" \"${_val_checkl_logfile}\" |\t\\\n\t\t    awk '{print $3}')\n\t\tif [ \"${_val_checkl_in_use}\" != \"${_val_checkl_suppressed}\" ]; then\n\t\t\t# There is an unsuppressed leak.\n\t\t\techo \"${_val_checkl_logfile}\"\n\t\t\treturn\n\t\tfi\n\tfi\n\n\t# Check for the wrong number of open fds.  On a normal desktop\n\t# computer, we expect 4: std{in,out,err}, plus the valgrind logfile.\n\t# If this is running inside a virtualized OS or container or shared\n\t# CI setup (such as Travis-CI), there might be other open\n\t# descriptors.  The important thing is that the number of fds should\n\t# match the simple test case (executing potential_memleaks without\n\t# running any actual tests).\n\t_val_checkl_fds_in_use=$(grep \"FILE DESCRIPTORS\" \"${_val_checkl_logfile}\" | awk '{print $4}')\n\t_val_checkl_valgrind_fds=$(grep \"FILE DESCRIPTORS\" \"${valgrind_fds_log}\" | \\\n\t    awk '{print $4}')\n\tif [ \"${_val_checkl_fds_in_use}\" != \"${_val_checkl_valgrind_fds}\" ] ; then\n\t\t# There is an unsuppressed leak.\n\t\techo \"${_val_checkl_logfile}\"\n\t\treturn\n\tfi\n\n\t# Check the error summary.  Get the number of expected errors from the\n\t# ${valgrind_fds_log} file.  (Ideally this would be 0, but due to\n\t# porting issues, some versions of valgrind on some platforms always\n\t# report a non-zero number of errors.)\n\t_val_checkl_num_errors=$(grep \"ERROR SUMMARY: \" \"${_val_checkl_logfile}\" | awk '{print $4}')\n\t_val_checkl_num_errors_basic=$(grep \"ERROR SUMMARY: \" \"${valgrind_fds_log}\" | awk '{ print $4}')\n\tif [ \"${_val_checkl_num_errors}\" != \"${_val_checkl_num_errors_basic}\" ]; then\n\t\t# There was some other error(s) -- invalid read or write,\n\t\t# conditional jump based on uninitialized value(s), invalid\n\t\t# free, etc.\n\t\techo \"${_val_checkl_logfile}\"\n\t\treturn\n\tfi\n}\n\n## _get_pids (logfiles):\n# Extract a list of pids in the format %08d from ${logfiles}.\n_get_pids() {\n\t_get_pids_logfiles=$1\n\n\t_get_pids_pids=\"\"\n\tfor _get_pids_logfile in ${_valgrind_check_logfiles} ; do\n\t\t# Get the pid.\n\t\t_get_pids_pid=$(printf \"%s\" \"${_get_pids_logfile%%.log}\" | \\\n\t\t    rev | cut -d \"-\" -f 1 | rev)\n\t\t# Zero-pad it and add it to the new list.\n\t\t_get_pids_pids=$(printf \"%s %08d\"\t\t\t\\\n\t\t    \"${_get_pids_pids}\" \"${_get_pids_pid}\")\n\tdone\n\n\techo \"${_get_pids_pids}\"\n}\n\n## _is_parent (logfile, pids):\n# If the parent pid of ${logfile} is in ${pids}, return 0; otherwise, return 1.\n_is_parent () {\n\t_is_parent_logfile=$1\n\t_is_parent_pids=$2\n\n\t# Get the parent pid from the valgrind logfile\n\tppid=$(grep \"Parent PID:\" \"${_is_parent_logfile}\" | \\\n\t    awk '{ print $4 }')\n\tppid=$(printf \"%08d\" \"${ppid}\")\n\n\t# If the parent is in the list of pids, this isn't the parent process.\n\tif [ \"${_is_parent_pids#*\"${ppid}\"}\" != \"${_is_parent_pids}\" ] ; then\n\t\treturn 1\n\tfi\n\n\t# Yes, this is the parent process.\n\treturn 0\n}\n\n## valgrind_check (exitfile):\n# Check for any memory leaks recorded in valgrind logfiles associated with a\n# test exitfile.  Return the filename if there's a leak; otherwise return an\n# empty string.\nvalgrind_check() {\n\t_valgrind_check_exitfile=\"$1\"\n\t_valgrind_check_basename=$(_val_getbase \"$1\")\n\n\t# Get list of files to check.  (Yes, the star goes outside the quotes.)\n\t_valgrind_check_logfiles=$(ls \"${_valgrind_check_basename}\"* 2>/dev/null)\n\t_valgrind_check_num=$(echo \"${_valgrind_check_logfiles}\" | wc -w)\n\n\t# Bail if we don't have any valgrind logfiles to check.\n\t# Use numeric comparison, because wc leaves a tab in the output.\n\tif [ \"${_valgrind_check_num}\" -eq \"0\" ] ; then\n\t\treturn\n\tfi\n\n\t# Check a single file.\n\tif [ \"${_valgrind_check_num}\" -eq \"1\" ]; then\n\t\t_val_checkl \"${_valgrind_check_logfiles}\"\n\t\treturn\n\tfi\n\n\t# Get a normalized list of pids.\n\t_valgrind_check_pids=$(_get_pids \"${_valgrind_check_logfiles}\")\n\n\t# If the valgrind logfiles contain \"-valgrind-parent-\", then we only\n\t# want to check the parent.  The parent is the logfile whose \"parent\n\t# pid\" is not in the list of pids.  (If one logfile contains\n\t# \"-valgrind-parent-\" then all of them should have it, so we can\n\t# simply check if that string occurs in the list of logfiles.)\n\tif [ \"${_valgrind_check_logfiles#*-valgrind-parent-}\" !=\t\\\n\t    \"${_valgrind_check_logfiles}\" ]; then\n\t\t_valgrind_check_parent=1\n\telse\n\t\t_valgrind_check_parent=0\n\tfi\n\n\t# Check the logfiles depending on whether it's the parent or not,\n\t# and whether we want to check the parent or children.\n\tfor _valgrind_check_logfile in ${_valgrind_check_logfiles} ; do\n\t\tif _is_parent \"${_valgrind_check_logfile}\"\t\\\n\t\t    \"${_valgrind_check_pids}\" ; then\n\t\t\t# This is the parent.\n\t\t\tif [ \"${_valgrind_check_parent}\" -eq 1 ] ; then\n\t\t\t\t_val_checkl \"${_valgrind_check_logfile}\"\n\t\t\t\t# Bail if there's a problem.\n\t\t\t\tif [ \"$?\" -ne 0 ]; then\n\t\t\t\t\treturn\n\t\t\t\tfi\n\t\t\tfi\n\t\telse\n\t\t\t# This is a child.\n\t\t\tif [ \"${_valgrind_check_parent}\" -eq 0 ] ; then\n\t\t\t\t_val_checkl \"${_valgrind_check_logfile}\"\n\t\t\t\t# Bail if there's a problem.\n\t\t\t\tif [ \"$?\" -ne 0 ]; then\n\t\t\t\t\treturn\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\tdone\n}\n\n## valgrind_init():\n# Clear previous valgrind output, and prepare for running valgrind tests\n# (if applicable).\nvalgrind_init() {\n\t# Set up global variables.\n\tvalgrind_suppressions=\"${out_valgrind}/suppressions\"\n\tvalgrind_fds_log=\"${out_valgrind}/fds.log\"\n\n\t# If we want valgrind, check that the version is high enough.\n\t_val_checkver\n\n\t# Remove any previous directory, and create a new one.\n\t_val_prepdir\n\n\t# Generate valgrind suppression file if it is required.  Must be\n\t# done after preparing the directory.\n\t_val_ensure \"${bindir}/tests/valgrind/potential-memleaks\"\n}\n"
  },
  {
    "path": "tests/test_scrypt.sh",
    "content": "#!/bin/sh\n\n### Find script directory and load helper functions.\nscriptdir=$(CDPATH='' cd -- \"$(dirname -- \"$0\")\" && pwd -P)\n. \"${scriptdir}/shared_test_functions.sh\"\n\n\n### Project-specific constants and setup\n\nout=\"${bindir}/tests-output\"\nout_valgrind=\"${bindir}/tests-valgrind\"\n\n# Constants used in multiple scenarios for this project.\npassword=\"hunter2\"\n\n# Find system scrypt, and ensure it supports -P.\nsystem_scrypt=$( find_system scrypt \"enc -P\" )\n\n\n### Run tests using project-specific constants\nrun_scenarios\n"
  },
  {
    "path": "tests/valgrind/potential-memleaks.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define FGETS_BUFSIZE 64\n\n/* Problem with FreeBSD 10.3 fgets() with stdin. */\nstatic void\npl_freebsd_fgets(void)\n{\n\tchar buf[FGETS_BUFSIZE];\n\n\tif (fgets(buf, FGETS_BUFSIZE, stdin) == NULL)\n\t\texit(1);\n}\n\n/* Problem with FreeBSD 12.0 and printf(). */\nstatic void\npl_freebsd_printf_space(void)\n{\n\n\tprintf(\" \");\n}\n\n/* Problem with FreeBSD 12.0 and printf(). */\nstatic void\npl_freebsd_printf_space_newline(void)\n{\n\n\tprintf(\" \\n\");\n}\n\n/* Problem with FreeBSD 12.0 and strerror(). */\nstatic void\npl_freebsd_strerror(void)\n{\n\tchar * str = strerror(0);\n\n\t(void)str; /* UNUSED */\n}\n\n#define MEMLEAKTEST(x) { #x, x }\nstatic const struct memleaktest {\n\tconst char * const name;\n\tvoid (* const volatile func)(void);\n} tests[] = {\n\tMEMLEAKTEST(pl_freebsd_fgets),\n\tMEMLEAKTEST(pl_freebsd_printf_space),\n\tMEMLEAKTEST(pl_freebsd_printf_space_newline),\n\tMEMLEAKTEST(pl_freebsd_strerror)\n};\nstatic const int num_tests = sizeof(tests) / sizeof(tests[0]);\n\nint\nmain(int argc, char * argv[])\n{\n\tint i;\n\n\tif (argc == 2) {\n\t\t/* Run the relevant function. */\n\t\tfor (i = 0; i < num_tests; i++) {\n\t\t\tif ((strcmp(argv[1], tests[i].name)) == 0) {\n\t\t\t\ttests[i].func();\n\t\t\t\tgoto success;\n\t\t\t}\n\t\t}\n\n\t\t/* We didn't find the desired function name. */\n\t\tgoto err0;\n\t} else {\n\t\t/* Print test names. */\n\t\tfor (i = 0; i < num_tests; i++)\n\t\t\tprintf(\"%s\\n\", tests[i].name);\n\t}\n\nsuccess:\n\t/* Success! */\n\texit(0);\n\nerr0:\n\t/* Failure! */\n\texit(1);\n}\n"
  },
  {
    "path": "tests/verify-strings/test_scrypt.c",
    "content": "#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"crypto_scrypt.h\"\n#include \"warnp.h\"\n\nstatic struct scrypt_test {\n\tconst char * passwd;\n\tconst char * salt;\n\tuint64_t N;\n\tuint32_t r;\n\tuint32_t p;\n\tint largemem;\n} tests[4] = {\n\t{ \"\", \"\", 16, 1, 1, 0 },\n\t{ \"password\", \"NaCl\", 1024, 8, 16, 0 },\n\t{ \"pleaseletmein\", \"SodiumChloride\", 16384, 8, 1, 0 },\n\t{ \"pleaseletmein\", \"SodiumChloride\", 1048576, 8, 1, 1 }\n};\n\nint\nmain(int argc, char * argv[])\n{\n\tstruct scrypt_test * test;\n\tchar kbuf[64];\n\tsize_t i;\n\tint failures = 0;\n\tint skip_largemem = 0;\n\n\tWARNP_INIT;\n\n\t/* Do we want to skip the large-memory test? */\n\tif ((argc == 2) && (strcmp(argv[1], \"1\") == 0))\n\t\tskip_largemem = 1;\n\n\tfor (test = tests;\n\t    test < tests + sizeof(tests) / sizeof(tests[0]);\n\t    test++) {\n\t\t/* Skip large memory tests (if desired). */\n\t\tif (skip_largemem && test->largemem)\n\t\t\tcontinue;\n\n\t\tif (crypto_scrypt((const uint8_t *)test->passwd,\n\t\t    strlen(test->passwd), (const uint8_t *)test->salt,\n\t\t    strlen(test->salt), test->N, test->r, test->p,\n\t\t    (uint8_t *)kbuf, 64)) {\n\t\t\twarnp(\"crypto_scrypt(%u, %u, %u) failed\",\n\t\t\t    (unsigned int)test->N, (unsigned int)test->r,\n\t\t\t    (unsigned int)test->p);\n\t\t\tfailures++;\n\t\t\tbreak;\n\t\t}\n\t\tprintf(\"scrypt(\\\"%s\\\", \\\"%s\\\", %u, %u, %u, 64) =\\n\",\n\t\t    test->passwd, test->salt, (unsigned int)test->N,\n\t\t    (unsigned int)(test->r), (unsigned int)test->p);\n\t\tfor (i = 0; i < 64; i++) {\n\t\t\tprintf(\"%02x\", (uint8_t)kbuf[i]);\n\t\t\tif ((i % 16) == 15)\n\t\t\t\tprintf(\"\\n\");\n\t\t\telse\n\t\t\t\tprintf(\" \");\n\t\t}\n\t}\n\n\treturn (failures ? 1 : 0);\n}\n"
  },
  {
    "path": "tests/verify-strings/test_scrypt.good",
    "content": "scrypt(\"\", \"\", 16, 1, 1, 64) =\n77 d6 57 62 38 65 7b 20 3b 19 ca 42 c1 8a 04 97\nf1 6b 48 44 e3 07 4a e8 df df fa 3f ed e2 14 42\nfc d0 06 9d ed 09 48 f8 32 6a 75 3a 0f c8 1f 17\ne8 d3 e0 fb 2e 0d 36 28 cf 35 e2 0c 38 d1 89 06\nscrypt(\"password\", \"NaCl\", 1024, 8, 16, 64) =\nfd ba be 1c 9d 34 72 00 78 56 e7 19 0d 01 e9 fe\n7c 6a d7 cb c8 23 78 30 e7 73 76 63 4b 37 31 62\n2e af 30 d9 2e 22 a3 88 6f f1 09 27 9d 98 30 da\nc7 27 af b9 4a 83 ee 6d 83 60 cb df a2 cc 06 40\nscrypt(\"pleaseletmein\", \"SodiumChloride\", 16384, 8, 1, 64) =\n70 23 bd cb 3a fd 73 48 46 1c 06 cd 81 fd 38 eb\nfd a8 fb ba 90 4f 8e 3e a9 b5 43 f6 54 5d a1 f2\nd5 43 29 55 61 3f 0f cf 62 d4 97 05 24 2a 9a f9\ne6 1e 85 dc 0d 65 1e 40 df cf 01 7b 45 57 58 87\nscrypt(\"pleaseletmein\", \"SodiumChloride\", 1048576, 8, 1, 64) =\n21 01 cb 9b 6a 51 1a ae ad db be 09 cf 70 f8 81\nec 56 8d 57 4a 2f fd 4d ab e5 ee 98 20 ad aa 47\n8e 56 fd 8f 4b a5 d0 9f fa 1c 6d 92 7c 40 f4 c3\n37 30 40 49 e8 a9 52 fb cb f4 5c 6f a7 7a 41 a4\n"
  },
  {
    "path": "tests/verify-strings/test_scrypt_small.good",
    "content": "scrypt(\"\", \"\", 16, 1, 1, 64) =\n77 d6 57 62 38 65 7b 20 3b 19 ca 42 c1 8a 04 97\nf1 6b 48 44 e3 07 4a e8 df df fa 3f ed e2 14 42\nfc d0 06 9d ed 09 48 f8 32 6a 75 3a 0f c8 1f 17\ne8 d3 e0 fb 2e 0d 36 28 cf 35 e2 0c 38 d1 89 06\nscrypt(\"password\", \"NaCl\", 1024, 8, 16, 64) =\nfd ba be 1c 9d 34 72 00 78 56 e7 19 0d 01 e9 fe\n7c 6a d7 cb c8 23 78 30 e7 73 76 63 4b 37 31 62\n2e af 30 d9 2e 22 a3 88 6f f1 09 27 9d 98 30 da\nc7 27 af b9 4a 83 ee 6d 83 60 cb df a2 cc 06 40\nscrypt(\"pleaseletmein\", \"SodiumChloride\", 16384, 8, 1, 64) =\n70 23 bd cb 3a fd 73 48 46 1c 06 cd 81 fd 38 eb\nfd a8 fb ba 90 4f 8e 3e a9 b5 43 f6 54 5d a1 f2\nd5 43 29 55 61 3f 0f cf 62 d4 97 05 24 2a 9a f9\ne6 1e 85 dc 0d 65 1e 40 df cf 01 7b 45 57 58 87\n"
  }
]